code
stringlengths
4
1.01M
#include <sys/stat.h> #include <stdlib.h> #include <stdio.h> #include <time.h> #include "expat.h" static void usage(const char *prog, int rc) { fprintf(stderr, "usage: %s [-n] filename bufferSize nr_of_loops\n", prog); exit(rc); } int main (int argc, char *argv[]) { XML_Parser parser; char *XMLBuf, *XMLBufEnd, *XMLBufPtr; FILE *fd; struct stat fileAttr; int nrOfLoops, bufferSize, fileSize, i, isFinal; int j = 0, ns = 0; clock_t tstart, tend; double cpuTime = 0.0; if (argc > 1) { if (argv[1][0] == '-') { if (argv[1][1] == 'n' && argv[1][2] == '\0') { ns = 1; j = 1; } else usage(argv[0], 1); } } if (argc != j + 4) usage(argv[0], 1); if (stat (argv[j + 1], &fileAttr) != 0) { fprintf (stderr, "could not access file '%s'\n", argv[j + 1]); return 2; } fd = fopen (argv[j + 1], "r"); if (!fd) { fprintf (stderr, "could not open file '%s'\n", argv[j + 1]); exit(2); } bufferSize = atoi (argv[j + 2]); nrOfLoops = atoi (argv[j + 3]); if (bufferSize <= 0 || nrOfLoops <= 0) { fprintf (stderr, "buffer size and nr of loops must be greater than zero.\n"); exit(3); } XMLBuf = malloc (fileAttr.st_size); fileSize = fread (XMLBuf, sizeof (char), fileAttr.st_size, fd); fclose (fd); i = 0; XMLBufEnd = XMLBuf + fileSize; while (i < nrOfLoops) { XMLBufPtr = XMLBuf; isFinal = 0; if (ns) parser = XML_ParserCreateNS(NULL, '!'); else parser = XML_ParserCreate(NULL); tstart = clock(); do { int parseBufferSize = XMLBufEnd - XMLBufPtr; if (parseBufferSize <= bufferSize) isFinal = 1; else parseBufferSize = bufferSize; if (!XML_Parse (parser, XMLBufPtr, parseBufferSize, isFinal)) { fprintf (stderr, "error '%s' at line %d character %d\n", XML_ErrorString (XML_GetErrorCode (parser)), XML_GetCurrentLineNumber (parser), XML_GetCurrentColumnNumber (parser)); free (XMLBuf); XML_ParserFree (parser); exit (4); } XMLBufPtr += bufferSize; } while (!isFinal); tend = clock(); cpuTime += ((double) (tend - tstart)) / CLOCKS_PER_SEC; XML_ParserFree (parser); i++; } free (XMLBuf); printf ("%d loops, with buffer size %d. Average time per loop: %f\n", nrOfLoops, bufferSize, cpuTime / (double) nrOfLoops); return 0; }
! Program to test the initialisation range of enumerators ! and kind values check program main implicit none enum, bind (c) enumerator :: red , yellow =255 , blue end enum enum, bind (c) enumerator :: r , y = 32767, b end enum enum, bind (c) enumerator :: aa , bb = 65535, cc end enum enum, bind (c) enumerator :: m , n = 2147483645, o end enum if (red /= 0 ) STOP 1 if (yellow /= 255) STOP 2 if (blue /= 256) STOP 3 if (r /= 0 ) STOP 4 if (y /= 32767) STOP 5 if (b /= 32768) STOP 6 if (kind (red) /= 4) STOP 7 if (kind (yellow) /= 4) STOP 8 if (kind (blue) /= 4) STOP 9 if (kind(r) /= 4 ) STOP 10 if (kind(y) /= 4) STOP 11 if (kind(b) /= 4) STOP 12 if (aa /= 0 ) STOP 13 if (bb /= 65535) STOP 14 if (cc /= 65536) STOP 15 if (kind (aa) /= 4 ) STOP 16 if (kind (bb) /= 4) STOP 17 if (kind (cc) /= 4) STOP 18 if (m /= 0 ) STOP 19 if (n /= 2147483645) STOP 20 if (o /= 2147483646) STOP 21 if (kind (m) /= 4 ) STOP 22 if (kind (n) /= 4) STOP 23 if (kind (o) /= 4) STOP 24 end program main
<?php namespace Composer\Installers; use Composer\Composer; use Composer\Installer\BinaryInstaller; use Composer\Installer\LibraryInstaller; use Composer\IO\IOInterface; use Composer\Package\PackageInterface; use Composer\Repository\InstalledRepositoryInterface; use Composer\Util\Filesystem; class Installer extends LibraryInstaller { /** * Package types to installer class map * * @var array */ private $supportedTypes = array( 'aimeos' => 'AimeosInstaller', 'asgard' => 'AsgardInstaller', 'attogram' => 'AttogramInstaller', 'agl' => 'AglInstaller', 'annotatecms' => 'AnnotateCmsInstaller', 'bitrix' => 'BitrixInstaller', 'bonefish' => 'BonefishInstaller', 'cakephp' => 'CakePHPInstaller', 'chef' => 'ChefInstaller', 'civicrm' => 'CiviCrmInstaller', 'ccframework' => 'ClanCatsFrameworkInstaller', 'cockpit' => 'CockpitInstaller', 'codeigniter' => 'CodeIgniterInstaller', 'concrete5' => 'Concrete5Installer', 'craft' => 'CraftInstaller', 'croogo' => 'CroogoInstaller', 'dokuwiki' => 'DokuWikiInstaller', 'dolibarr' => 'DolibarrInstaller', 'decibel' => 'DecibelInstaller', 'drupal' => 'DrupalInstaller', 'elgg' => 'ElggInstaller', 'eliasis' => 'EliasisInstaller', 'ee3' => 'ExpressionEngineInstaller', 'ee2' => 'ExpressionEngineInstaller', 'ezplatform' => 'EzPlatformInstaller', 'fuel' => 'FuelInstaller', 'fuelphp' => 'FuelphpInstaller', 'grav' => 'GravInstaller', 'hurad' => 'HuradInstaller', 'imagecms' => 'ImageCMSInstaller', 'itop' => 'ItopInstaller', 'joomla' => 'JoomlaInstaller', 'kanboard' => 'KanboardInstaller', 'kirby' => 'KirbyInstaller', 'kodicms' => 'KodiCMSInstaller', 'kohana' => 'KohanaInstaller', 'lms' => 'LanManagementSystemInstaller', 'laravel' => 'LaravelInstaller', 'lavalite' => 'LavaLiteInstaller', 'lithium' => 'LithiumInstaller', 'magento' => 'MagentoInstaller', 'majima' => 'MajimaInstaller', 'mako' => 'MakoInstaller', 'maya' => 'MayaInstaller', 'mautic' => 'MauticInstaller', 'mediawiki' => 'MediaWikiInstaller', 'microweber' => 'MicroweberInstaller', 'modulework' => 'MODULEWorkInstaller', 'modx' => 'ModxInstaller', 'modxevo' => 'MODXEvoInstaller', 'moodle' => 'MoodleInstaller', 'october' => 'OctoberInstaller', 'ontowiki' => 'OntoWikiInstaller', 'oxid' => 'OxidInstaller', 'osclass' => 'OsclassInstaller', 'pxcms' => 'PxcmsInstaller', 'phpbb' => 'PhpBBInstaller', 'pimcore' => 'PimcoreInstaller', 'piwik' => 'PiwikInstaller', 'plentymarkets'=> 'PlentymarketsInstaller', 'ppi' => 'PPIInstaller', 'puppet' => 'PuppetInstaller', 'radphp' => 'RadPHPInstaller', 'phifty' => 'PhiftyInstaller', 'porto' => 'PortoInstaller', 'redaxo' => 'RedaxoInstaller', 'reindex' => 'ReIndexInstaller', 'roundcube' => 'RoundcubeInstaller', 'shopware' => 'ShopwareInstaller', 'sitedirect' => 'SiteDirectInstaller', 'silverstripe' => 'SilverStripeInstaller', 'smf' => 'SMFInstaller', 'sydes' => 'SyDESInstaller', 'symfony1' => 'Symfony1Installer', 'thelia' => 'TheliaInstaller', 'tusk' => 'TuskInstaller', 'typo3-cms' => 'TYPO3CmsInstaller', 'typo3-flow' => 'TYPO3FlowInstaller', 'userfrosting' => 'UserFrostingInstaller', 'vanilla' => 'VanillaInstaller', 'whmcs' => 'WHMCSInstaller', 'wolfcms' => 'WolfCMSInstaller', 'wordpress' => 'WordPressInstaller', 'yawik' => 'YawikInstaller', 'zend' => 'ZendInstaller', 'zikula' => 'ZikulaInstaller', 'prestashop' => 'PrestashopInstaller' ); /** * Installer constructor. * * Disables installers specified in main composer extra installer-disable * list * * @param IOInterface $io * @param Composer $composer * @param string $type * @param Filesystem|null $filesystem * @param BinaryInstaller|null $binaryInstaller */ public function __construct( IOInterface $io, Composer $composer, $type = 'library', Filesystem $filesystem = null, BinaryInstaller $binaryInstaller = null ) { parent::__construct($io, $composer, $type, $filesystem, $binaryInstaller); $this->removeDisabledInstallers(); } /** * {@inheritDoc} */ public function getInstallPath(PackageInterface $package) { $type = $package->getType(); $frameworkType = $this->findFrameworkType($type); if ($frameworkType === false) { throw new \InvalidArgumentException( 'Sorry the package type of this package is not yet supported.' ); } $class = 'Composer\\Installers\\' . $this->supportedTypes[$frameworkType]; $installer = new $class($package, $this->composer, $this->getIO()); return $installer->getInstallPath($package, $frameworkType); } public function uninstall(InstalledRepositoryInterface $repo, PackageInterface $package) { parent::uninstall($repo, $package); $installPath = $this->getPackageBasePath($package); $this->io->write(sprintf('Deleting %s - %s', $installPath, !file_exists($installPath) ? '<comment>deleted</comment>' : '<error>not deleted</error>')); } /** * {@inheritDoc} */ public function supports($packageType) { $frameworkType = $this->findFrameworkType($packageType); if ($frameworkType === false) { return false; } $locationPattern = $this->getLocationPattern($frameworkType); return preg_match('#' . $frameworkType . '-' . $locationPattern . '#', $packageType, $matches) === 1; } /** * Finds a supported framework type if it exists and returns it * * @param string $type * @return string */ protected function findFrameworkType($type) { $frameworkType = false; krsort($this->supportedTypes); foreach ($this->supportedTypes as $key => $val) { if ($key === substr($type, 0, strlen($key))) { $frameworkType = substr($type, 0, strlen($key)); break; } } return $frameworkType; } /** * Get the second part of the regular expression to check for support of a * package type * * @param string $frameworkType * @return string */ protected function getLocationPattern($frameworkType) { $pattern = false; if (!empty($this->supportedTypes[$frameworkType])) { $frameworkClass = 'Composer\\Installers\\' . $this->supportedTypes[$frameworkType]; /** @var BaseInstaller $framework */ $framework = new $frameworkClass(null, $this->composer, $this->getIO()); $locations = array_keys($framework->getLocations()); $pattern = $locations ? '(' . implode('|', $locations) . ')' : false; } return $pattern ? : '(\w+)'; } /** * Get I/O object * * @return IOInterface */ private function getIO() { return $this->io; } /** * Look for installers set to be disabled in composer's extra config and * remove them from the list of supported installers. * * Globals: * - true, "all", and "*" - disable all installers. * - false - enable all installers (useful with * wikimedia/composer-merge-plugin or similar) * * @return void */ protected function removeDisabledInstallers() { $extra = $this->composer->getPackage()->getExtra(); if (!isset($extra['installer-disable']) || $extra['installer-disable'] === false) { // No installers are disabled return; } // Get installers to disable $disable = $extra['installer-disable']; // Ensure $disabled is an array if (!is_array($disable)) { $disable = array($disable); } // Check which installers should be disabled $all = array(true, "all", "*"); $intersect = array_intersect($all, $disable); if (!empty($intersect)) { // Disable all installers $this->supportedTypes = array(); } else { // Disable specified installers foreach ($disable as $key => $installer) { if (is_string($installer) && key_exists($installer, $this->supportedTypes)) { unset($this->supportedTypes[$installer]); } } } } }
/* * Copyright (c) 1993 Martin Birgmeier * All rights reserved. * * You may redistribute unmodified or modified versions of this source * code provided that the above copyright notice and this and the * following conditions are retained. * * This software is provided ``as is'', and comes with no warranties * of any kind. I shall in no event be liable for anything that happens * to anyone/anything when using this software. */ #include "rand48.h" double _drand48_r (struct _reent *r) { _REENT_CHECK_RAND48(r); return _erand48_r(r, __rand48_seed); } #ifndef _REENT_ONLY double drand48 (void) { return _drand48_r (_REENT); } #endif /* !_REENT_ONLY */
/* * Copyright (c) 2008 Patrick McHardy <kaber@trash.net> * Copyright (c) 2013 Pablo Neira Ayuso <pablo@netfilter.org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * Development of this code funded by Astaro AG (http://www.astaro.com/) */ #include <linux/init.h> #include <linux/module.h> #include <linux/netfilter_bridge.h> #include <net/netfilter/nf_tables.h> #include <linux/ip.h> #include <linux/ipv6.h> #include <net/netfilter/nf_tables_ipv4.h> #include <net/netfilter/nf_tables_ipv6.h> static unsigned int nft_do_chain_bridge(void *priv, struct sk_buff *skb, const struct nf_hook_state *state) { struct nft_pktinfo pkt; nft_set_pktinfo(&pkt, skb, state); switch (eth_hdr(skb)->h_proto) { case htons(ETH_P_IP): nft_set_pktinfo_ipv4_validate(&pkt, skb); break; case htons(ETH_P_IPV6): nft_set_pktinfo_ipv6_validate(&pkt, skb); break; default: nft_set_pktinfo_unspec(&pkt, skb); break; } return nft_do_chain(&pkt, priv); } static const struct nf_chain_type filter_bridge = { .name = "filter", .type = NFT_CHAIN_T_DEFAULT, .family = NFPROTO_BRIDGE, .owner = THIS_MODULE, .hook_mask = (1 << NF_BR_PRE_ROUTING) | (1 << NF_BR_LOCAL_IN) | (1 << NF_BR_FORWARD) | (1 << NF_BR_LOCAL_OUT) | (1 << NF_BR_POST_ROUTING), .hooks = { [NF_BR_PRE_ROUTING] = nft_do_chain_bridge, [NF_BR_LOCAL_IN] = nft_do_chain_bridge, [NF_BR_FORWARD] = nft_do_chain_bridge, [NF_BR_LOCAL_OUT] = nft_do_chain_bridge, [NF_BR_POST_ROUTING] = nft_do_chain_bridge, }, }; static int __init nf_tables_bridge_init(void) { return nft_register_chain_type(&filter_bridge); } static void __exit nf_tables_bridge_exit(void) { nft_unregister_chain_type(&filter_bridge); } module_init(nf_tables_bridge_init); module_exit(nf_tables_bridge_exit); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Patrick McHardy <kaber@trash.net>"); MODULE_ALIAS_NFT_CHAIN(AF_BRIDGE, "filter");
/* This testcase is part of GDB, the GNU debugger. Copyright 2004, 2007-2012 Free Software Foundation, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* Useful abreviations. */ typedef void t; typedef char tc; typedef short ts; typedef int ti; typedef long tl; typedef long long tll; typedef float tf; typedef double td; typedef long double tld; typedef enum { e = '1' } te; /* Force the type of each field. */ #ifndef T typedef t T; #endif T foo = '1', L; T fun() { return foo; } #ifdef PROTOTYPES void Fun(T foo) #else void Fun(foo) T foo; #endif { L = foo; } zed () { L = 'Z'; } int main() { int i; Fun(foo); /* An infinite loop that first clears all the variables and then calls the function. This "hack" is to make re-testing easier - "advance fun" is guaranteed to have always been preceded by a global variable clearing zed call. */ zed (); while (1) { L = fun (); zed (); } return 0; }
/* SPDX-License-Identifier: LGPL-2.1+ */ #include <getopt.h> #include "macro.h" #include "strv.h" #include "verbs.h" static int noop_dispatcher(int argc, char *argv[], void *userdata) { return 0; } #define test_dispatch_one(argv, verbs, expected) \ optind = 0; \ assert_se(dispatch_verb(strv_length(argv), argv, verbs, NULL) == expected); static void test_verbs(void) { static const Verb verbs[] = { { "help", VERB_ANY, VERB_ANY, 0, noop_dispatcher }, { "list-images", VERB_ANY, 1, 0, noop_dispatcher }, { "list", VERB_ANY, 2, VERB_DEFAULT, noop_dispatcher }, { "status", 2, VERB_ANY, 0, noop_dispatcher }, { "show", VERB_ANY, VERB_ANY, 0, noop_dispatcher }, { "terminate", 2, VERB_ANY, 0, noop_dispatcher }, { "login", 2, 2, 0, noop_dispatcher }, { "copy-to", 3, 4, 0, noop_dispatcher }, {} }; /* not found */ test_dispatch_one(STRV_MAKE("command-not-found"), verbs, -EINVAL); /* found */ test_dispatch_one(STRV_MAKE("show"), verbs, 0); /* found, too few args */ test_dispatch_one(STRV_MAKE("copy-to", "foo"), verbs, -EINVAL); /* found, meets min args */ test_dispatch_one(STRV_MAKE("status", "foo", "bar"), verbs, 0); /* found, too many args */ test_dispatch_one(STRV_MAKE("copy-to", "foo", "bar", "baz", "quux", "qaax"), verbs, -EINVAL); /* no verb, but a default is set */ test_dispatch_one(STRV_MAKE_EMPTY, verbs, 0); } static void test_verbs_no_default(void) { static const Verb verbs[] = { { "help", VERB_ANY, VERB_ANY, 0, noop_dispatcher }, {}, }; test_dispatch_one(STRV_MAKE(NULL), verbs, -EINVAL); } int main(int argc, char *argv[]) { test_verbs(); test_verbs_no_default(); return 0; }
#!/bin/sh test_description='signals work as we expect' . ./test-lib.sh cat >expect <<EOF three two one EOF test_expect_success 'sigchain works' ' test-sigchain >actual case "$?" in 143) true ;; # POSIX w/ SIGTERM=15 271) true ;; # ksh w/ SIGTERM=15 3) true ;; # Windows *) false ;; esac && test_cmp expect actual ' test_expect_success !MINGW 'signals are propagated using shell convention' ' # we use exec here to avoid any sub-shell interpretation # of the exit code git config alias.sigterm "!exec test-sigchain" && test_expect_code 143 git sigterm ' large_git () { for i in $(test_seq 1 100) do git diff --cached --binary || return done } test_expect_success 'create blob' ' test-genrandom foo 16384 >file && git add file ' test_expect_success !MINGW 'a constipated git dies with SIGPIPE' ' OUT=$( ((large_git; echo $? 1>&3) | :) 3>&1 ) test "$OUT" -eq 141 ' test_expect_success !MINGW 'a constipated git dies with SIGPIPE even if parent ignores it' ' OUT=$( ((trap "" PIPE; large_git; echo $? 1>&3) | :) 3>&1 ) test "$OUT" -eq 141 ' test_done
/** * @copyright (C) 2016 Open Source Matters, Inc. <https://www.joomla.org> * @license GNU General Public License version 2 or later; see LICENSE.txt */ !(function(document, $) { "use strict"; function initMinicolorsField (event) { $(event.target).find('.minicolors').each(function() { $(this).minicolors({ control: $(this).attr('data-control') || 'hue', format: $(this).attr('data-validate') === 'color' ? 'hex' : ($(this).attr('data-format') === 'rgba' ? 'rgb' : $(this).attr('data-format')) || 'hex', keywords: $(this).attr('data-keywords') || '', opacity: $(this).attr('data-format') === 'rgba', position: $(this).attr('data-position') || 'default', swatches: $(this).attr('data-colors') ? $(this).attr('data-colors').split(",") : [], theme: 'bootstrap' }); }); } /** * Initialize at an initial page load */ document.addEventListener("DOMContentLoaded", initMinicolorsField); /** * Initialize when a part of the page was updated */ document.addEventListener("joomla:updated", initMinicolorsField); })(document, jQuery);
/* * TCP over IPv6 * Linux INET6 implementation * * Authors: * Pedro Roque <roque@di.fc.ul.pt> * * Based on: * linux/net/ipv4/tcp.c * linux/net/ipv4/tcp_input.c * linux/net/ipv4/tcp_output.c * * Fixes: * Hideaki YOSHIFUJI : sin6_scope_id support * YOSHIFUJI Hideaki @USAGI and: Support IPV6_V6ONLY socket option, which * Alexey Kuznetsov allow both IPv4 and IPv6 sockets to bind * a single port at the same time. * YOSHIFUJI Hideaki @USAGI: convert /proc/net/tcp6 to seq_file. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #include <linux/bottom_half.h> #include <linux/module.h> #include <linux/errno.h> #include <linux/types.h> #include <linux/socket.h> #include <linux/sockios.h> #include <linux/net.h> #include <linux/jiffies.h> #include <linux/in.h> #include <linux/in6.h> #include <linux/netdevice.h> #include <linux/init.h> #include <linux/jhash.h> #include <linux/ipsec.h> #include <linux/times.h> #include <linux/slab.h> #include <linux/uaccess.h> #include <linux/ipv6.h> #include <linux/icmpv6.h> #include <linux/random.h> #include <net/tcp.h> #include <net/ndisc.h> #include <net/inet6_hashtables.h> #include <net/inet6_connection_sock.h> #include <net/ipv6.h> #include <net/transp_v6.h> #include <net/addrconf.h> #include <net/ip6_route.h> #include <net/ip6_checksum.h> #include <net/inet_ecn.h> #include <net/protocol.h> #include <net/xfrm.h> #include <net/snmp.h> #include <net/dsfield.h> #include <net/timewait_sock.h> #include <net/inet_common.h> #include <net/secure_seq.h> #include <net/busy_poll.h> #include <linux/proc_fs.h> #include <linux/seq_file.h> #include <linux/crypto.h> #include <linux/scatterlist.h> static void tcp_v6_send_reset(const struct sock *sk, struct sk_buff *skb); static void tcp_v6_reqsk_send_ack(const struct sock *sk, struct sk_buff *skb, struct request_sock *req); static int tcp_v6_do_rcv(struct sock *sk, struct sk_buff *skb); static const struct inet_connection_sock_af_ops ipv6_mapped; static const struct inet_connection_sock_af_ops ipv6_specific; #ifdef CONFIG_TCP_MD5SIG static const struct tcp_sock_af_ops tcp_sock_ipv6_specific; static const struct tcp_sock_af_ops tcp_sock_ipv6_mapped_specific; #else static struct tcp_md5sig_key *tcp_v6_md5_do_lookup(const struct sock *sk, const struct in6_addr *addr) { return NULL; } #endif static void inet6_sk_rx_dst_set(struct sock *sk, const struct sk_buff *skb) { struct dst_entry *dst = skb_dst(skb); if (dst && dst_hold_safe(dst)) { const struct rt6_info *rt = (const struct rt6_info *)dst; sk->sk_rx_dst = dst; inet_sk(sk)->rx_dst_ifindex = skb->skb_iif; inet6_sk(sk)->rx_dst_cookie = rt6_get_cookie(rt); } } static __u32 tcp_v6_init_sequence(const struct sk_buff *skb) { return secure_tcpv6_sequence_number(ipv6_hdr(skb)->daddr.s6_addr32, ipv6_hdr(skb)->saddr.s6_addr32, tcp_hdr(skb)->dest, tcp_hdr(skb)->source); } static int tcp_v6_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len) { struct sockaddr_in6 *usin = (struct sockaddr_in6 *) uaddr; struct inet_sock *inet = inet_sk(sk); struct inet_connection_sock *icsk = inet_csk(sk); struct ipv6_pinfo *np = inet6_sk(sk); struct tcp_sock *tp = tcp_sk(sk); struct in6_addr *saddr = NULL, *final_p, final; struct ipv6_txoptions *opt; struct flowi6 fl6; struct dst_entry *dst; int addr_type; int err; if (addr_len < SIN6_LEN_RFC2133) return -EINVAL; if (usin->sin6_family != AF_INET6) return -EAFNOSUPPORT; memset(&fl6, 0, sizeof(fl6)); if (np->sndflow) { fl6.flowlabel = usin->sin6_flowinfo&IPV6_FLOWINFO_MASK; IP6_ECN_flow_init(fl6.flowlabel); if (fl6.flowlabel&IPV6_FLOWLABEL_MASK) { struct ip6_flowlabel *flowlabel; flowlabel = fl6_sock_lookup(sk, fl6.flowlabel); if (!flowlabel) return -EINVAL; fl6_sock_release(flowlabel); } } /* * connect() to INADDR_ANY means loopback (BSD'ism). */ if (ipv6_addr_any(&usin->sin6_addr)) usin->sin6_addr.s6_addr[15] = 0x1; addr_type = ipv6_addr_type(&usin->sin6_addr); if (addr_type & IPV6_ADDR_MULTICAST) return -ENETUNREACH; if (addr_type&IPV6_ADDR_LINKLOCAL) { if (addr_len >= sizeof(struct sockaddr_in6) && usin->sin6_scope_id) { /* If interface is set while binding, indices * must coincide. */ if (sk->sk_bound_dev_if && sk->sk_bound_dev_if != usin->sin6_scope_id) return -EINVAL; sk->sk_bound_dev_if = usin->sin6_scope_id; } /* Connect to link-local address requires an interface */ if (!sk->sk_bound_dev_if) return -EINVAL; } if (tp->rx_opt.ts_recent_stamp && !ipv6_addr_equal(&sk->sk_v6_daddr, &usin->sin6_addr)) { tp->rx_opt.ts_recent = 0; tp->rx_opt.ts_recent_stamp = 0; tp->write_seq = 0; } sk->sk_v6_daddr = usin->sin6_addr; np->flow_label = fl6.flowlabel; /* * TCP over IPv4 */ if (addr_type == IPV6_ADDR_MAPPED) { u32 exthdrlen = icsk->icsk_ext_hdr_len; struct sockaddr_in sin; SOCK_DEBUG(sk, "connect: ipv4 mapped\n"); if (__ipv6_only_sock(sk)) return -ENETUNREACH; sin.sin_family = AF_INET; sin.sin_port = usin->sin6_port; sin.sin_addr.s_addr = usin->sin6_addr.s6_addr32[3]; icsk->icsk_af_ops = &ipv6_mapped; sk->sk_backlog_rcv = tcp_v4_do_rcv; #ifdef CONFIG_TCP_MD5SIG tp->af_specific = &tcp_sock_ipv6_mapped_specific; #endif err = tcp_v4_connect(sk, (struct sockaddr *)&sin, sizeof(sin)); if (err) { icsk->icsk_ext_hdr_len = exthdrlen; icsk->icsk_af_ops = &ipv6_specific; sk->sk_backlog_rcv = tcp_v6_do_rcv; #ifdef CONFIG_TCP_MD5SIG tp->af_specific = &tcp_sock_ipv6_specific; #endif goto failure; } np->saddr = sk->sk_v6_rcv_saddr; return err; } if (!ipv6_addr_any(&sk->sk_v6_rcv_saddr)) saddr = &sk->sk_v6_rcv_saddr; fl6.flowi6_proto = IPPROTO_TCP; fl6.daddr = sk->sk_v6_daddr; fl6.saddr = saddr ? *saddr : np->saddr; fl6.flowi6_oif = sk->sk_bound_dev_if; fl6.flowi6_mark = sk->sk_mark; fl6.fl6_dport = usin->sin6_port; fl6.fl6_sport = inet->inet_sport; opt = rcu_dereference_protected(np->opt, sock_owned_by_user(sk)); final_p = fl6_update_dst(&fl6, opt, &final); security_sk_classify_flow(sk, flowi6_to_flowi(&fl6)); dst = ip6_dst_lookup_flow(sk, &fl6, final_p); if (IS_ERR(dst)) { err = PTR_ERR(dst); goto failure; } if (!saddr) { saddr = &fl6.saddr; sk->sk_v6_rcv_saddr = *saddr; } /* set the source address */ np->saddr = *saddr; inet->inet_rcv_saddr = LOOPBACK4_IPV6; sk->sk_gso_type = SKB_GSO_TCPV6; ip6_dst_store(sk, dst, NULL, NULL); if (tcp_death_row.sysctl_tw_recycle && !tp->rx_opt.ts_recent_stamp && ipv6_addr_equal(&fl6.daddr, &sk->sk_v6_daddr)) tcp_fetch_timewait_stamp(sk, dst); icsk->icsk_ext_hdr_len = 0; if (opt) icsk->icsk_ext_hdr_len = opt->opt_flen + opt->opt_nflen; tp->rx_opt.mss_clamp = IPV6_MIN_MTU - sizeof(struct tcphdr) - sizeof(struct ipv6hdr); inet->inet_dport = usin->sin6_port; tcp_set_state(sk, TCP_SYN_SENT); err = inet6_hash_connect(&tcp_death_row, sk); if (err) goto late_failure; sk_set_txhash(sk); if (!tp->write_seq && likely(!tp->repair)) tp->write_seq = secure_tcpv6_sequence_number(np->saddr.s6_addr32, sk->sk_v6_daddr.s6_addr32, inet->inet_sport, inet->inet_dport); err = tcp_connect(sk); if (err) goto late_failure; return 0; late_failure: tcp_set_state(sk, TCP_CLOSE); __sk_dst_reset(sk); failure: inet->inet_dport = 0; sk->sk_route_caps = 0; return err; } static void tcp_v6_mtu_reduced(struct sock *sk) { struct dst_entry *dst; if ((1 << sk->sk_state) & (TCPF_LISTEN | TCPF_CLOSE)) return; dst = inet6_csk_update_pmtu(sk, tcp_sk(sk)->mtu_info); if (!dst) return; if (inet_csk(sk)->icsk_pmtu_cookie > dst_mtu(dst)) { tcp_sync_mss(sk, dst_mtu(dst)); tcp_simple_retransmit(sk); } } static void tcp_v6_err(struct sk_buff *skb, struct inet6_skb_parm *opt, u8 type, u8 code, int offset, __be32 info) { const struct ipv6hdr *hdr = (const struct ipv6hdr *)skb->data; const struct tcphdr *th = (struct tcphdr *)(skb->data+offset); struct net *net = dev_net(skb->dev); struct request_sock *fastopen; struct ipv6_pinfo *np; struct tcp_sock *tp; __u32 seq, snd_una; struct sock *sk; int err; sk = __inet6_lookup_established(net, &tcp_hashinfo, &hdr->daddr, th->dest, &hdr->saddr, ntohs(th->source), skb->dev->ifindex); if (!sk) { ICMP6_INC_STATS_BH(net, __in6_dev_get(skb->dev), ICMP6_MIB_INERRORS); return; } if (sk->sk_state == TCP_TIME_WAIT) { inet_twsk_put(inet_twsk(sk)); return; } seq = ntohl(th->seq); if (sk->sk_state == TCP_NEW_SYN_RECV) return tcp_req_err(sk, seq); bh_lock_sock(sk); if (sock_owned_by_user(sk) && type != ICMPV6_PKT_TOOBIG) NET_INC_STATS_BH(net, LINUX_MIB_LOCKDROPPEDICMPS); if (sk->sk_state == TCP_CLOSE) goto out; if (ipv6_hdr(skb)->hop_limit < inet6_sk(sk)->min_hopcount) { NET_INC_STATS_BH(net, LINUX_MIB_TCPMINTTLDROP); goto out; } tp = tcp_sk(sk); /* XXX (TFO) - tp->snd_una should be ISN (tcp_create_openreq_child() */ fastopen = tp->fastopen_rsk; snd_una = fastopen ? tcp_rsk(fastopen)->snt_isn : tp->snd_una; if (sk->sk_state != TCP_LISTEN && !between(seq, snd_una, tp->snd_nxt)) { NET_INC_STATS_BH(net, LINUX_MIB_OUTOFWINDOWICMPS); goto out; } np = inet6_sk(sk); if (type == NDISC_REDIRECT) { struct dst_entry *dst = __sk_dst_check(sk, np->dst_cookie); if (dst) dst->ops->redirect(dst, sk, skb); goto out; } if (type == ICMPV6_PKT_TOOBIG) { /* We are not interested in TCP_LISTEN and open_requests * (SYN-ACKs send out by Linux are always <576bytes so * they should go through unfragmented). */ if (sk->sk_state == TCP_LISTEN) goto out; if (!ip6_sk_accept_pmtu(sk)) goto out; tp->mtu_info = ntohl(info); if (!sock_owned_by_user(sk)) tcp_v6_mtu_reduced(sk); else if (!test_and_set_bit(TCP_MTU_REDUCED_DEFERRED, &tp->tsq_flags)) sock_hold(sk); goto out; } icmpv6_err_convert(type, code, &err); /* Might be for an request_sock */ switch (sk->sk_state) { case TCP_SYN_SENT: case TCP_SYN_RECV: /* Only in fast or simultaneous open. If a fast open socket is * is already accepted it is treated as a connected one below. */ if (fastopen && !fastopen->sk) break; if (!sock_owned_by_user(sk)) { sk->sk_err = err; sk->sk_error_report(sk); /* Wake people up to see the error (see connect in sock.c) */ tcp_done(sk); } else sk->sk_err_soft = err; goto out; } if (!sock_owned_by_user(sk) && np->recverr) { sk->sk_err = err; sk->sk_error_report(sk); } else sk->sk_err_soft = err; out: bh_unlock_sock(sk); sock_put(sk); } static int tcp_v6_send_synack(const struct sock *sk, struct dst_entry *dst, struct flowi *fl, struct request_sock *req, struct tcp_fastopen_cookie *foc, bool attach_req) { struct inet_request_sock *ireq = inet_rsk(req); struct ipv6_pinfo *np = inet6_sk(sk); struct flowi6 *fl6 = &fl->u.ip6; struct sk_buff *skb; int err = -ENOMEM; /* First, grab a route. */ if (!dst && (dst = inet6_csk_route_req(sk, fl6, req, IPPROTO_TCP)) == NULL) goto done; skb = tcp_make_synack(sk, dst, req, foc, attach_req); if (skb) { __tcp_v6_send_check(skb, &ireq->ir_v6_loc_addr, &ireq->ir_v6_rmt_addr); fl6->daddr = ireq->ir_v6_rmt_addr; if (np->repflow && ireq->pktopts) fl6->flowlabel = ip6_flowlabel(ipv6_hdr(ireq->pktopts)); rcu_read_lock(); err = ip6_xmit(sk, skb, fl6, rcu_dereference(np->opt), np->tclass); rcu_read_unlock(); err = net_xmit_eval(err); } done: return err; } static void tcp_v6_reqsk_destructor(struct request_sock *req) { kfree_skb(inet_rsk(req)->pktopts); } #ifdef CONFIG_TCP_MD5SIG static struct tcp_md5sig_key *tcp_v6_md5_do_lookup(const struct sock *sk, const struct in6_addr *addr) { return tcp_md5_do_lookup(sk, (union tcp_md5_addr *)addr, AF_INET6); } static struct tcp_md5sig_key *tcp_v6_md5_lookup(const struct sock *sk, const struct sock *addr_sk) { return tcp_v6_md5_do_lookup(sk, &addr_sk->sk_v6_daddr); } static int tcp_v6_parse_md5_keys(struct sock *sk, char __user *optval, int optlen) { struct tcp_md5sig cmd; struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)&cmd.tcpm_addr; if (optlen < sizeof(cmd)) return -EINVAL; if (copy_from_user(&cmd, optval, sizeof(cmd))) return -EFAULT; if (sin6->sin6_family != AF_INET6) return -EINVAL; if (!cmd.tcpm_keylen) { if (ipv6_addr_v4mapped(&sin6->sin6_addr)) return tcp_md5_do_del(sk, (union tcp_md5_addr *)&sin6->sin6_addr.s6_addr32[3], AF_INET); return tcp_md5_do_del(sk, (union tcp_md5_addr *)&sin6->sin6_addr, AF_INET6); } if (cmd.tcpm_keylen > TCP_MD5SIG_MAXKEYLEN) return -EINVAL; if (ipv6_addr_v4mapped(&sin6->sin6_addr)) return tcp_md5_do_add(sk, (union tcp_md5_addr *)&sin6->sin6_addr.s6_addr32[3], AF_INET, cmd.tcpm_key, cmd.tcpm_keylen, GFP_KERNEL); return tcp_md5_do_add(sk, (union tcp_md5_addr *)&sin6->sin6_addr, AF_INET6, cmd.tcpm_key, cmd.tcpm_keylen, GFP_KERNEL); } static int tcp_v6_md5_hash_pseudoheader(struct tcp_md5sig_pool *hp, const struct in6_addr *daddr, const struct in6_addr *saddr, int nbytes) { struct tcp6_pseudohdr *bp; struct scatterlist sg; bp = &hp->md5_blk.ip6; /* 1. TCP pseudo-header (RFC2460) */ bp->saddr = *saddr; bp->daddr = *daddr; bp->protocol = cpu_to_be32(IPPROTO_TCP); bp->len = cpu_to_be32(nbytes); sg_init_one(&sg, bp, sizeof(*bp)); return crypto_hash_update(&hp->md5_desc, &sg, sizeof(*bp)); } static int tcp_v6_md5_hash_hdr(char *md5_hash, struct tcp_md5sig_key *key, const struct in6_addr *daddr, struct in6_addr *saddr, const struct tcphdr *th) { struct tcp_md5sig_pool *hp; struct hash_desc *desc; hp = tcp_get_md5sig_pool(); if (!hp) goto clear_hash_noput; desc = &hp->md5_desc; if (crypto_hash_init(desc)) goto clear_hash; if (tcp_v6_md5_hash_pseudoheader(hp, daddr, saddr, th->doff << 2)) goto clear_hash; if (tcp_md5_hash_header(hp, th)) goto clear_hash; if (tcp_md5_hash_key(hp, key)) goto clear_hash; if (crypto_hash_final(desc, md5_hash)) goto clear_hash; tcp_put_md5sig_pool(); return 0; clear_hash: tcp_put_md5sig_pool(); clear_hash_noput: memset(md5_hash, 0, 16); return 1; } static int tcp_v6_md5_hash_skb(char *md5_hash, const struct tcp_md5sig_key *key, const struct sock *sk, const struct sk_buff *skb) { const struct in6_addr *saddr, *daddr; struct tcp_md5sig_pool *hp; struct hash_desc *desc; const struct tcphdr *th = tcp_hdr(skb); if (sk) { /* valid for establish/request sockets */ saddr = &sk->sk_v6_rcv_saddr; daddr = &sk->sk_v6_daddr; } else { const struct ipv6hdr *ip6h = ipv6_hdr(skb); saddr = &ip6h->saddr; daddr = &ip6h->daddr; } hp = tcp_get_md5sig_pool(); if (!hp) goto clear_hash_noput; desc = &hp->md5_desc; if (crypto_hash_init(desc)) goto clear_hash; if (tcp_v6_md5_hash_pseudoheader(hp, daddr, saddr, skb->len)) goto clear_hash; if (tcp_md5_hash_header(hp, th)) goto clear_hash; if (tcp_md5_hash_skb_data(hp, skb, th->doff << 2)) goto clear_hash; if (tcp_md5_hash_key(hp, key)) goto clear_hash; if (crypto_hash_final(desc, md5_hash)) goto clear_hash; tcp_put_md5sig_pool(); return 0; clear_hash: tcp_put_md5sig_pool(); clear_hash_noput: memset(md5_hash, 0, 16); return 1; } #endif static bool tcp_v6_inbound_md5_hash(const struct sock *sk, const struct sk_buff *skb) { #ifdef CONFIG_TCP_MD5SIG const __u8 *hash_location = NULL; struct tcp_md5sig_key *hash_expected; const struct ipv6hdr *ip6h = ipv6_hdr(skb); const struct tcphdr *th = tcp_hdr(skb); int genhash; u8 newhash[16]; hash_expected = tcp_v6_md5_do_lookup(sk, &ip6h->saddr); hash_location = tcp_parse_md5sig_option(th); /* We've parsed the options - do we have a hash? */ if (!hash_expected && !hash_location) return false; if (hash_expected && !hash_location) { NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPMD5NOTFOUND); return true; } if (!hash_expected && hash_location) { NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPMD5UNEXPECTED); return true; } /* check the signature */ genhash = tcp_v6_md5_hash_skb(newhash, hash_expected, NULL, skb); if (genhash || memcmp(hash_location, newhash, 16) != 0) { net_info_ratelimited("MD5 Hash %s for [%pI6c]:%u->[%pI6c]:%u\n", genhash ? "failed" : "mismatch", &ip6h->saddr, ntohs(th->source), &ip6h->daddr, ntohs(th->dest)); return true; } #endif return false; } static void tcp_v6_init_req(struct request_sock *req, const struct sock *sk_listener, struct sk_buff *skb) { struct inet_request_sock *ireq = inet_rsk(req); const struct ipv6_pinfo *np = inet6_sk(sk_listener); ireq->ir_v6_rmt_addr = ipv6_hdr(skb)->saddr; ireq->ir_v6_loc_addr = ipv6_hdr(skb)->daddr; /* So that link locals have meaning */ if (!sk_listener->sk_bound_dev_if && ipv6_addr_type(&ireq->ir_v6_rmt_addr) & IPV6_ADDR_LINKLOCAL) ireq->ir_iif = tcp_v6_iif(skb); if (!TCP_SKB_CB(skb)->tcp_tw_isn && (ipv6_opt_accepted(sk_listener, skb, &TCP_SKB_CB(skb)->header.h6) || np->rxopt.bits.rxinfo || np->rxopt.bits.rxoinfo || np->rxopt.bits.rxhlim || np->rxopt.bits.rxohlim || np->repflow)) { atomic_inc(&skb->users); ireq->pktopts = skb; } } static struct dst_entry *tcp_v6_route_req(const struct sock *sk, struct flowi *fl, const struct request_sock *req, bool *strict) { if (strict) *strict = true; return inet6_csk_route_req(sk, &fl->u.ip6, req, IPPROTO_TCP); } struct request_sock_ops tcp6_request_sock_ops __read_mostly = { .family = AF_INET6, .obj_size = sizeof(struct tcp6_request_sock), .rtx_syn_ack = tcp_rtx_synack, .send_ack = tcp_v6_reqsk_send_ack, .destructor = tcp_v6_reqsk_destructor, .send_reset = tcp_v6_send_reset, .syn_ack_timeout = tcp_syn_ack_timeout, }; static const struct tcp_request_sock_ops tcp_request_sock_ipv6_ops = { .mss_clamp = IPV6_MIN_MTU - sizeof(struct tcphdr) - sizeof(struct ipv6hdr), #ifdef CONFIG_TCP_MD5SIG .req_md5_lookup = tcp_v6_md5_lookup, .calc_md5_hash = tcp_v6_md5_hash_skb, #endif .init_req = tcp_v6_init_req, #ifdef CONFIG_SYN_COOKIES .cookie_init_seq = cookie_v6_init_sequence, #endif .route_req = tcp_v6_route_req, .init_seq = tcp_v6_init_sequence, .send_synack = tcp_v6_send_synack, }; static void tcp_v6_send_response(const struct sock *sk, struct sk_buff *skb, u32 seq, u32 ack, u32 win, u32 tsval, u32 tsecr, int oif, struct tcp_md5sig_key *key, int rst, u8 tclass, u32 label) { const struct tcphdr *th = tcp_hdr(skb); struct tcphdr *t1; struct sk_buff *buff; struct flowi6 fl6; struct net *net = sk ? sock_net(sk) : dev_net(skb_dst(skb)->dev); struct sock *ctl_sk = net->ipv6.tcp_sk; unsigned int tot_len = sizeof(struct tcphdr); struct dst_entry *dst; __be32 *topt; if (tsecr) tot_len += TCPOLEN_TSTAMP_ALIGNED; #ifdef CONFIG_TCP_MD5SIG if (key) tot_len += TCPOLEN_MD5SIG_ALIGNED; #endif buff = alloc_skb(MAX_HEADER + sizeof(struct ipv6hdr) + tot_len, GFP_ATOMIC); if (!buff) return; skb_reserve(buff, MAX_HEADER + sizeof(struct ipv6hdr) + tot_len); t1 = (struct tcphdr *) skb_push(buff, tot_len); skb_reset_transport_header(buff); /* Swap the send and the receive. */ memset(t1, 0, sizeof(*t1)); t1->dest = th->source; t1->source = th->dest; t1->doff = tot_len / 4; t1->seq = htonl(seq); t1->ack_seq = htonl(ack); t1->ack = !rst || !th->ack; t1->rst = rst; t1->window = htons(win); topt = (__be32 *)(t1 + 1); if (tsecr) { *topt++ = htonl((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16) | (TCPOPT_TIMESTAMP << 8) | TCPOLEN_TIMESTAMP); *topt++ = htonl(tsval); *topt++ = htonl(tsecr); } #ifdef CONFIG_TCP_MD5SIG if (key) { *topt++ = htonl((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16) | (TCPOPT_MD5SIG << 8) | TCPOLEN_MD5SIG); tcp_v6_md5_hash_hdr((__u8 *)topt, key, &ipv6_hdr(skb)->saddr, &ipv6_hdr(skb)->daddr, t1); } #endif memset(&fl6, 0, sizeof(fl6)); fl6.daddr = ipv6_hdr(skb)->saddr; fl6.saddr = ipv6_hdr(skb)->daddr; fl6.flowlabel = label; buff->ip_summed = CHECKSUM_PARTIAL; buff->csum = 0; __tcp_v6_send_check(buff, &fl6.saddr, &fl6.daddr); fl6.flowi6_proto = IPPROTO_TCP; if (rt6_need_strict(&fl6.daddr) && !oif) fl6.flowi6_oif = tcp_v6_iif(skb); else fl6.flowi6_oif = oif; fl6.flowi6_mark = IP6_REPLY_MARK(net, skb->mark); fl6.fl6_dport = t1->dest; fl6.fl6_sport = t1->source; security_skb_classify_flow(skb, flowi6_to_flowi(&fl6)); /* Pass a socket to ip6_dst_lookup either it is for RST * Underlying function will use this to retrieve the network * namespace */ dst = ip6_dst_lookup_flow(ctl_sk, &fl6, NULL); if (!IS_ERR(dst)) { skb_dst_set(buff, dst); ip6_xmit(ctl_sk, buff, &fl6, NULL, tclass); TCP_INC_STATS_BH(net, TCP_MIB_OUTSEGS); if (rst) TCP_INC_STATS_BH(net, TCP_MIB_OUTRSTS); return; } kfree_skb(buff); } static void tcp_v6_send_reset(const struct sock *sk, struct sk_buff *skb) { const struct tcphdr *th = tcp_hdr(skb); u32 seq = 0, ack_seq = 0; struct tcp_md5sig_key *key = NULL; #ifdef CONFIG_TCP_MD5SIG const __u8 *hash_location = NULL; struct ipv6hdr *ipv6h = ipv6_hdr(skb); unsigned char newhash[16]; int genhash; struct sock *sk1 = NULL; #endif int oif; if (th->rst) return; /* If sk not NULL, it means we did a successful lookup and incoming * route had to be correct. prequeue might have dropped our dst. */ if (!sk && !ipv6_unicast_destination(skb)) return; #ifdef CONFIG_TCP_MD5SIG hash_location = tcp_parse_md5sig_option(th); if (sk && sk_fullsock(sk)) { key = tcp_v6_md5_do_lookup(sk, &ipv6h->saddr); } else if (hash_location) { /* * active side is lost. Try to find listening socket through * source port, and then find md5 key through listening socket. * we are not loose security here: * Incoming packet is checked with md5 hash with finding key, * no RST generated if md5 hash doesn't match. */ sk1 = inet6_lookup_listener(dev_net(skb_dst(skb)->dev), &tcp_hashinfo, &ipv6h->saddr, th->source, &ipv6h->daddr, ntohs(th->source), tcp_v6_iif(skb)); if (!sk1) return; rcu_read_lock(); key = tcp_v6_md5_do_lookup(sk1, &ipv6h->saddr); if (!key) goto release_sk1; genhash = tcp_v6_md5_hash_skb(newhash, key, NULL, skb); if (genhash || memcmp(hash_location, newhash, 16) != 0) goto release_sk1; } #endif if (th->ack) seq = ntohl(th->ack_seq); else ack_seq = ntohl(th->seq) + th->syn + th->fin + skb->len - (th->doff << 2); oif = sk ? sk->sk_bound_dev_if : 0; tcp_v6_send_response(sk, skb, seq, ack_seq, 0, 0, 0, oif, key, 1, 0, 0); #ifdef CONFIG_TCP_MD5SIG release_sk1: if (sk1) { rcu_read_unlock(); sock_put(sk1); } #endif } static void tcp_v6_send_ack(const struct sock *sk, struct sk_buff *skb, u32 seq, u32 ack, u32 win, u32 tsval, u32 tsecr, int oif, struct tcp_md5sig_key *key, u8 tclass, u32 label) { tcp_v6_send_response(sk, skb, seq, ack, win, tsval, tsecr, oif, key, 0, tclass, label); } static void tcp_v6_timewait_ack(struct sock *sk, struct sk_buff *skb) { struct inet_timewait_sock *tw = inet_twsk(sk); struct tcp_timewait_sock *tcptw = tcp_twsk(sk); tcp_v6_send_ack(sk, skb, tcptw->tw_snd_nxt, tcptw->tw_rcv_nxt, tcptw->tw_rcv_wnd >> tw->tw_rcv_wscale, tcp_time_stamp + tcptw->tw_ts_offset, tcptw->tw_ts_recent, tw->tw_bound_dev_if, tcp_twsk_md5_key(tcptw), tw->tw_tclass, cpu_to_be32(tw->tw_flowlabel)); inet_twsk_put(tw); } static void tcp_v6_reqsk_send_ack(const struct sock *sk, struct sk_buff *skb, struct request_sock *req) { /* sk->sk_state == TCP_LISTEN -> for regular TCP_SYN_RECV * sk->sk_state == TCP_SYN_RECV -> for Fast Open. */ tcp_v6_send_ack(sk, skb, (sk->sk_state == TCP_LISTEN) ? tcp_rsk(req)->snt_isn + 1 : tcp_sk(sk)->snd_nxt, tcp_rsk(req)->rcv_nxt, req->rsk_rcv_wnd, tcp_time_stamp, req->ts_recent, sk->sk_bound_dev_if, tcp_v6_md5_do_lookup(sk, &ipv6_hdr(skb)->daddr), 0, 0); } static struct sock *tcp_v6_cookie_check(struct sock *sk, struct sk_buff *skb) { #ifdef CONFIG_SYN_COOKIES const struct tcphdr *th = tcp_hdr(skb); if (!th->syn) sk = cookie_v6_check(sk, skb); #endif return sk; } static int tcp_v6_conn_request(struct sock *sk, struct sk_buff *skb) { if (skb->protocol == htons(ETH_P_IP)) return tcp_v4_conn_request(sk, skb); if (!ipv6_unicast_destination(skb)) goto drop; return tcp_conn_request(&tcp6_request_sock_ops, &tcp_request_sock_ipv6_ops, sk, skb); drop: NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_LISTENDROPS); return 0; /* don't send reset */ } static struct sock *tcp_v6_syn_recv_sock(const struct sock *sk, struct sk_buff *skb, struct request_sock *req, struct dst_entry *dst, struct request_sock *req_unhash, bool *own_req) { struct inet_request_sock *ireq; struct ipv6_pinfo *newnp; const struct ipv6_pinfo *np = inet6_sk(sk); struct ipv6_txoptions *opt; struct tcp6_sock *newtcp6sk; struct inet_sock *newinet; struct tcp_sock *newtp; struct sock *newsk; #ifdef CONFIG_TCP_MD5SIG struct tcp_md5sig_key *key; #endif struct flowi6 fl6; if (skb->protocol == htons(ETH_P_IP)) { /* * v6 mapped */ newsk = tcp_v4_syn_recv_sock(sk, skb, req, dst, req_unhash, own_req); if (!newsk) return NULL; newtcp6sk = (struct tcp6_sock *)newsk; inet_sk(newsk)->pinet6 = &newtcp6sk->inet6; newinet = inet_sk(newsk); newnp = inet6_sk(newsk); newtp = tcp_sk(newsk); memcpy(newnp, np, sizeof(struct ipv6_pinfo)); newnp->saddr = newsk->sk_v6_rcv_saddr; inet_csk(newsk)->icsk_af_ops = &ipv6_mapped; newsk->sk_backlog_rcv = tcp_v4_do_rcv; #ifdef CONFIG_TCP_MD5SIG newtp->af_specific = &tcp_sock_ipv6_mapped_specific; #endif newnp->ipv6_ac_list = NULL; newnp->ipv6_fl_list = NULL; newnp->pktoptions = NULL; newnp->opt = NULL; newnp->mcast_oif = tcp_v6_iif(skb); newnp->mcast_hops = ipv6_hdr(skb)->hop_limit; newnp->rcv_flowinfo = ip6_flowinfo(ipv6_hdr(skb)); if (np->repflow) newnp->flow_label = ip6_flowlabel(ipv6_hdr(skb)); /* * No need to charge this sock to the relevant IPv6 refcnt debug socks count * here, tcp_create_openreq_child now does this for us, see the comment in * that function for the gory details. -acme */ /* It is tricky place. Until this moment IPv4 tcp worked with IPv6 icsk.icsk_af_ops. Sync it now. */ tcp_sync_mss(newsk, inet_csk(newsk)->icsk_pmtu_cookie); return newsk; } ireq = inet_rsk(req); if (sk_acceptq_is_full(sk)) goto out_overflow; if (!dst) { dst = inet6_csk_route_req(sk, &fl6, req, IPPROTO_TCP); if (!dst) goto out; } newsk = tcp_create_openreq_child(sk, req, skb); if (!newsk) goto out_nonewsk; /* * No need to charge this sock to the relevant IPv6 refcnt debug socks * count here, tcp_create_openreq_child now does this for us, see the * comment in that function for the gory details. -acme */ newsk->sk_gso_type = SKB_GSO_TCPV6; ip6_dst_store(newsk, dst, NULL, NULL); inet6_sk_rx_dst_set(newsk, skb); newtcp6sk = (struct tcp6_sock *)newsk; inet_sk(newsk)->pinet6 = &newtcp6sk->inet6; newtp = tcp_sk(newsk); newinet = inet_sk(newsk); newnp = inet6_sk(newsk); memcpy(newnp, np, sizeof(struct ipv6_pinfo)); newsk->sk_v6_daddr = ireq->ir_v6_rmt_addr; newnp->saddr = ireq->ir_v6_loc_addr; newsk->sk_v6_rcv_saddr = ireq->ir_v6_loc_addr; newsk->sk_bound_dev_if = ireq->ir_iif; /* Now IPv6 options... First: no IPv4 options. */ newinet->inet_opt = NULL; newnp->ipv6_ac_list = NULL; newnp->ipv6_fl_list = NULL; /* Clone RX bits */ newnp->rxopt.all = np->rxopt.all; newnp->pktoptions = NULL; newnp->opt = NULL; newnp->mcast_oif = tcp_v6_iif(skb); newnp->mcast_hops = ipv6_hdr(skb)->hop_limit; newnp->rcv_flowinfo = ip6_flowinfo(ipv6_hdr(skb)); if (np->repflow) newnp->flow_label = ip6_flowlabel(ipv6_hdr(skb)); /* Clone native IPv6 options from listening socket (if any) Yes, keeping reference count would be much more clever, but we make one more one thing there: reattach optmem to newsk. */ opt = rcu_dereference(np->opt); if (opt) { opt = ipv6_dup_options(newsk, opt); RCU_INIT_POINTER(newnp->opt, opt); } inet_csk(newsk)->icsk_ext_hdr_len = 0; if (opt) inet_csk(newsk)->icsk_ext_hdr_len = opt->opt_nflen + opt->opt_flen; tcp_ca_openreq_child(newsk, dst); tcp_sync_mss(newsk, dst_mtu(dst)); newtp->advmss = dst_metric_advmss(dst); if (tcp_sk(sk)->rx_opt.user_mss && tcp_sk(sk)->rx_opt.user_mss < newtp->advmss) newtp->advmss = tcp_sk(sk)->rx_opt.user_mss; tcp_initialize_rcv_mss(newsk); newinet->inet_daddr = newinet->inet_saddr = LOOPBACK4_IPV6; newinet->inet_rcv_saddr = LOOPBACK4_IPV6; #ifdef CONFIG_TCP_MD5SIG /* Copy over the MD5 key from the original socket */ key = tcp_v6_md5_do_lookup(sk, &newsk->sk_v6_daddr); if (key) { /* We're using one, so create a matching key * on the newsk structure. If we fail to get * memory, then we end up not copying the key * across. Shucks. */ tcp_md5_do_add(newsk, (union tcp_md5_addr *)&newsk->sk_v6_daddr, AF_INET6, key->key, key->keylen, sk_gfp_mask(sk, GFP_ATOMIC)); } #endif if (__inet_inherit_port(sk, newsk) < 0) { inet_csk_prepare_forced_close(newsk); tcp_done(newsk); goto out; } *own_req = inet_ehash_nolisten(newsk, req_to_sk(req_unhash)); if (*own_req) { tcp_move_syn(newtp, req); /* Clone pktoptions received with SYN, if we own the req */ if (ireq->pktopts) { newnp->pktoptions = skb_clone(ireq->pktopts, sk_gfp_mask(sk, GFP_ATOMIC)); consume_skb(ireq->pktopts); ireq->pktopts = NULL; if (newnp->pktoptions) skb_set_owner_r(newnp->pktoptions, newsk); } } return newsk; out_overflow: NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_LISTENOVERFLOWS); out_nonewsk: dst_release(dst); out: NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_LISTENDROPS); return NULL; } /* The socket must have it's spinlock held when we get * here, unless it is a TCP_LISTEN socket. * * We have a potential double-lock case here, so even when * doing backlog processing we use the BH locking scheme. * This is because we cannot sleep with the original spinlock * held. */ static int tcp_v6_do_rcv(struct sock *sk, struct sk_buff *skb) { struct ipv6_pinfo *np = inet6_sk(sk); struct tcp_sock *tp; struct sk_buff *opt_skb = NULL; /* Imagine: socket is IPv6. IPv4 packet arrives, goes to IPv4 receive handler and backlogged. From backlog it always goes here. Kerboom... Fortunately, tcp_rcv_established and rcv_established handle them correctly, but it is not case with tcp_v6_hnd_req and tcp_v6_send_reset(). --ANK */ if (skb->protocol == htons(ETH_P_IP)) return tcp_v4_do_rcv(sk, skb); if (sk_filter(sk, skb)) goto discard; /* * socket locking is here for SMP purposes as backlog rcv * is currently called with bh processing disabled. */ /* Do Stevens' IPV6_PKTOPTIONS. Yes, guys, it is the only place in our code, where we may make it not affecting IPv4. The rest of code is protocol independent, and I do not like idea to uglify IPv4. Actually, all the idea behind IPV6_PKTOPTIONS looks not very well thought. For now we latch options, received in the last packet, enqueued by tcp. Feel free to propose better solution. --ANK (980728) */ if (np->rxopt.all) opt_skb = skb_clone(skb, sk_gfp_mask(sk, GFP_ATOMIC)); if (sk->sk_state == TCP_ESTABLISHED) { /* Fast path */ struct dst_entry *dst = sk->sk_rx_dst; sock_rps_save_rxhash(sk, skb); sk_mark_napi_id(sk, skb); if (dst) { if (inet_sk(sk)->rx_dst_ifindex != skb->skb_iif || dst->ops->check(dst, np->rx_dst_cookie) == NULL) { dst_release(dst); sk->sk_rx_dst = NULL; } } tcp_rcv_established(sk, skb, tcp_hdr(skb), skb->len); if (opt_skb) goto ipv6_pktoptions; return 0; } if (tcp_checksum_complete(skb)) goto csum_err; if (sk->sk_state == TCP_LISTEN) { struct sock *nsk = tcp_v6_cookie_check(sk, skb); if (!nsk) goto discard; if (nsk != sk) { sock_rps_save_rxhash(nsk, skb); sk_mark_napi_id(nsk, skb); if (tcp_child_process(sk, nsk, skb)) goto reset; if (opt_skb) __kfree_skb(opt_skb); return 0; } } else sock_rps_save_rxhash(sk, skb); if (tcp_rcv_state_process(sk, skb)) goto reset; if (opt_skb) goto ipv6_pktoptions; return 0; reset: tcp_v6_send_reset(sk, skb); discard: if (opt_skb) __kfree_skb(opt_skb); kfree_skb(skb); return 0; csum_err: TCP_INC_STATS_BH(sock_net(sk), TCP_MIB_CSUMERRORS); TCP_INC_STATS_BH(sock_net(sk), TCP_MIB_INERRS); goto discard; ipv6_pktoptions: /* Do you ask, what is it? 1. skb was enqueued by tcp. 2. skb is added to tail of read queue, rather than out of order. 3. socket is not in passive state. 4. Finally, it really contains options, which user wants to receive. */ tp = tcp_sk(sk); if (TCP_SKB_CB(opt_skb)->end_seq == tp->rcv_nxt && !((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_LISTEN))) { if (np->rxopt.bits.rxinfo || np->rxopt.bits.rxoinfo) np->mcast_oif = tcp_v6_iif(opt_skb); if (np->rxopt.bits.rxhlim || np->rxopt.bits.rxohlim) np->mcast_hops = ipv6_hdr(opt_skb)->hop_limit; if (np->rxopt.bits.rxflow || np->rxopt.bits.rxtclass) np->rcv_flowinfo = ip6_flowinfo(ipv6_hdr(opt_skb)); if (np->repflow) np->flow_label = ip6_flowlabel(ipv6_hdr(opt_skb)); if (ipv6_opt_accepted(sk, opt_skb, &TCP_SKB_CB(opt_skb)->header.h6)) { skb_set_owner_r(opt_skb, sk); opt_skb = xchg(&np->pktoptions, opt_skb); } else { __kfree_skb(opt_skb); opt_skb = xchg(&np->pktoptions, NULL); } } kfree_skb(opt_skb); return 0; } static void tcp_v6_fill_cb(struct sk_buff *skb, const struct ipv6hdr *hdr, const struct tcphdr *th) { /* This is tricky: we move IP6CB at its correct location into * TCP_SKB_CB(). It must be done after xfrm6_policy_check(), because * _decode_session6() uses IP6CB(). * barrier() makes sure compiler won't play aliasing games. */ memmove(&TCP_SKB_CB(skb)->header.h6, IP6CB(skb), sizeof(struct inet6_skb_parm)); barrier(); TCP_SKB_CB(skb)->seq = ntohl(th->seq); TCP_SKB_CB(skb)->end_seq = (TCP_SKB_CB(skb)->seq + th->syn + th->fin + skb->len - th->doff*4); TCP_SKB_CB(skb)->ack_seq = ntohl(th->ack_seq); TCP_SKB_CB(skb)->tcp_flags = tcp_flag_byte(th); TCP_SKB_CB(skb)->tcp_tw_isn = 0; TCP_SKB_CB(skb)->ip_dsfield = ipv6_get_dsfield(hdr); TCP_SKB_CB(skb)->sacked = 0; } static void tcp_v6_restore_cb(struct sk_buff *skb) { /* We need to move header back to the beginning if xfrm6_policy_check() * and tcp_v6_fill_cb() are going to be called again. */ memmove(IP6CB(skb), &TCP_SKB_CB(skb)->header.h6, sizeof(struct inet6_skb_parm)); } static int tcp_v6_rcv(struct sk_buff *skb) { const struct tcphdr *th; const struct ipv6hdr *hdr; struct sock *sk; int ret; struct net *net = dev_net(skb->dev); if (skb->pkt_type != PACKET_HOST) goto discard_it; /* * Count it even if it's bad. */ TCP_INC_STATS_BH(net, TCP_MIB_INSEGS); if (!pskb_may_pull(skb, sizeof(struct tcphdr))) goto discard_it; th = tcp_hdr(skb); if (th->doff < sizeof(struct tcphdr)/4) goto bad_packet; if (!pskb_may_pull(skb, th->doff*4)) goto discard_it; if (skb_checksum_init(skb, IPPROTO_TCP, ip6_compute_pseudo)) goto csum_error; th = tcp_hdr(skb); hdr = ipv6_hdr(skb); lookup: sk = __inet6_lookup_skb(&tcp_hashinfo, skb, th->source, th->dest, inet6_iif(skb)); if (!sk) goto no_tcp_socket; process: if (sk->sk_state == TCP_TIME_WAIT) goto do_time_wait; if (sk->sk_state == TCP_NEW_SYN_RECV) { struct request_sock *req = inet_reqsk(sk); struct sock *nsk = NULL; sk = req->rsk_listener; tcp_v6_fill_cb(skb, hdr, th); if (tcp_v6_inbound_md5_hash(sk, skb)) { reqsk_put(req); goto discard_it; } if (likely(sk->sk_state == TCP_LISTEN)) { nsk = tcp_check_req(sk, skb, req, false); } else { inet_csk_reqsk_queue_drop_and_put(sk, req); goto lookup; } if (!nsk) { reqsk_put(req); goto discard_it; } if (nsk == sk) { sock_hold(sk); reqsk_put(req); tcp_v6_restore_cb(skb); } else if (tcp_child_process(sk, nsk, skb)) { tcp_v6_send_reset(nsk, skb); goto discard_it; } else { return 0; } } if (hdr->hop_limit < inet6_sk(sk)->min_hopcount) { NET_INC_STATS_BH(net, LINUX_MIB_TCPMINTTLDROP); goto discard_and_relse; } if (!xfrm6_policy_check(sk, XFRM_POLICY_IN, skb)) goto discard_and_relse; tcp_v6_fill_cb(skb, hdr, th); if (tcp_v6_inbound_md5_hash(sk, skb)) goto discard_and_relse; if (sk_filter(sk, skb)) goto discard_and_relse; skb->dev = NULL; if (sk->sk_state == TCP_LISTEN) { ret = tcp_v6_do_rcv(sk, skb); goto put_and_return; } sk_incoming_cpu_update(sk); bh_lock_sock_nested(sk); tcp_sk(sk)->segs_in += max_t(u16, 1, skb_shinfo(skb)->gso_segs); ret = 0; if (!sock_owned_by_user(sk)) { if (!tcp_prequeue(sk, skb)) ret = tcp_v6_do_rcv(sk, skb); } else if (unlikely(sk_add_backlog(sk, skb, sk->sk_rcvbuf + sk->sk_sndbuf))) { bh_unlock_sock(sk); NET_INC_STATS_BH(net, LINUX_MIB_TCPBACKLOGDROP); goto discard_and_relse; } bh_unlock_sock(sk); put_and_return: sock_put(sk); return ret ? -1 : 0; no_tcp_socket: if (!xfrm6_policy_check(NULL, XFRM_POLICY_IN, skb)) goto discard_it; tcp_v6_fill_cb(skb, hdr, th); if (tcp_checksum_complete(skb)) { csum_error: TCP_INC_STATS_BH(net, TCP_MIB_CSUMERRORS); bad_packet: TCP_INC_STATS_BH(net, TCP_MIB_INERRS); } else { tcp_v6_send_reset(NULL, skb); } discard_it: kfree_skb(skb); return 0; discard_and_relse: sock_put(sk); goto discard_it; do_time_wait: if (!xfrm6_policy_check(NULL, XFRM_POLICY_IN, skb)) { inet_twsk_put(inet_twsk(sk)); goto discard_it; } tcp_v6_fill_cb(skb, hdr, th); if (tcp_checksum_complete(skb)) { inet_twsk_put(inet_twsk(sk)); goto csum_error; } switch (tcp_timewait_state_process(inet_twsk(sk), skb, th)) { case TCP_TW_SYN: { struct sock *sk2; sk2 = inet6_lookup_listener(dev_net(skb->dev), &tcp_hashinfo, &ipv6_hdr(skb)->saddr, th->source, &ipv6_hdr(skb)->daddr, ntohs(th->dest), tcp_v6_iif(skb)); if (sk2) { struct inet_timewait_sock *tw = inet_twsk(sk); inet_twsk_deschedule_put(tw); sk = sk2; tcp_v6_restore_cb(skb); goto process; } /* Fall through to ACK */ } case TCP_TW_ACK: tcp_v6_timewait_ack(sk, skb); break; case TCP_TW_RST: tcp_v6_restore_cb(skb); tcp_v6_send_reset(sk, skb); inet_twsk_deschedule_put(inet_twsk(sk)); goto discard_it; case TCP_TW_SUCCESS: ; } goto discard_it; } static void tcp_v6_early_demux(struct sk_buff *skb) { const struct ipv6hdr *hdr; const struct tcphdr *th; struct sock *sk; if (skb->pkt_type != PACKET_HOST) return; if (!pskb_may_pull(skb, skb_transport_offset(skb) + sizeof(struct tcphdr))) return; hdr = ipv6_hdr(skb); th = tcp_hdr(skb); if (th->doff < sizeof(struct tcphdr) / 4) return; /* Note : We use inet6_iif() here, not tcp_v6_iif() */ sk = __inet6_lookup_established(dev_net(skb->dev), &tcp_hashinfo, &hdr->saddr, th->source, &hdr->daddr, ntohs(th->dest), inet6_iif(skb)); if (sk) { skb->sk = sk; skb->destructor = sock_edemux; if (sk_fullsock(sk)) { struct dst_entry *dst = READ_ONCE(sk->sk_rx_dst); if (dst) dst = dst_check(dst, inet6_sk(sk)->rx_dst_cookie); if (dst && inet_sk(sk)->rx_dst_ifindex == skb->skb_iif) skb_dst_set_noref(skb, dst); } } } static struct timewait_sock_ops tcp6_timewait_sock_ops = { .twsk_obj_size = sizeof(struct tcp6_timewait_sock), .twsk_unique = tcp_twsk_unique, .twsk_destructor = tcp_twsk_destructor, }; static const struct inet_connection_sock_af_ops ipv6_specific = { .queue_xmit = inet6_csk_xmit, .send_check = tcp_v6_send_check, .rebuild_header = inet6_sk_rebuild_header, .sk_rx_dst_set = inet6_sk_rx_dst_set, .conn_request = tcp_v6_conn_request, .syn_recv_sock = tcp_v6_syn_recv_sock, .net_header_len = sizeof(struct ipv6hdr), .net_frag_header_len = sizeof(struct frag_hdr), .setsockopt = ipv6_setsockopt, .getsockopt = ipv6_getsockopt, .addr2sockaddr = inet6_csk_addr2sockaddr, .sockaddr_len = sizeof(struct sockaddr_in6), .bind_conflict = inet6_csk_bind_conflict, #ifdef CONFIG_COMPAT .compat_setsockopt = compat_ipv6_setsockopt, .compat_getsockopt = compat_ipv6_getsockopt, #endif .mtu_reduced = tcp_v6_mtu_reduced, }; #ifdef CONFIG_TCP_MD5SIG static const struct tcp_sock_af_ops tcp_sock_ipv6_specific = { .md5_lookup = tcp_v6_md5_lookup, .calc_md5_hash = tcp_v6_md5_hash_skb, .md5_parse = tcp_v6_parse_md5_keys, }; #endif /* * TCP over IPv4 via INET6 API */ static const struct inet_connection_sock_af_ops ipv6_mapped = { .queue_xmit = ip_queue_xmit, .send_check = tcp_v4_send_check, .rebuild_header = inet_sk_rebuild_header, .sk_rx_dst_set = inet_sk_rx_dst_set, .conn_request = tcp_v6_conn_request, .syn_recv_sock = tcp_v6_syn_recv_sock, .net_header_len = sizeof(struct iphdr), .setsockopt = ipv6_setsockopt, .getsockopt = ipv6_getsockopt, .addr2sockaddr = inet6_csk_addr2sockaddr, .sockaddr_len = sizeof(struct sockaddr_in6), .bind_conflict = inet6_csk_bind_conflict, #ifdef CONFIG_COMPAT .compat_setsockopt = compat_ipv6_setsockopt, .compat_getsockopt = compat_ipv6_getsockopt, #endif .mtu_reduced = tcp_v4_mtu_reduced, }; #ifdef CONFIG_TCP_MD5SIG static const struct tcp_sock_af_ops tcp_sock_ipv6_mapped_specific = { .md5_lookup = tcp_v4_md5_lookup, .calc_md5_hash = tcp_v4_md5_hash_skb, .md5_parse = tcp_v6_parse_md5_keys, }; #endif /* NOTE: A lot of things set to zero explicitly by call to * sk_alloc() so need not be done here. */ static int tcp_v6_init_sock(struct sock *sk) { struct inet_connection_sock *icsk = inet_csk(sk); tcp_init_sock(sk); icsk->icsk_af_ops = &ipv6_specific; #ifdef CONFIG_TCP_MD5SIG tcp_sk(sk)->af_specific = &tcp_sock_ipv6_specific; #endif return 0; } static void tcp_v6_destroy_sock(struct sock *sk) { tcp_v4_destroy_sock(sk); inet6_destroy_sock(sk); } #ifdef CONFIG_PROC_FS /* Proc filesystem TCPv6 sock list dumping. */ static void get_openreq6(struct seq_file *seq, const struct request_sock *req, int i) { long ttd = req->rsk_timer.expires - jiffies; const struct in6_addr *src = &inet_rsk(req)->ir_v6_loc_addr; const struct in6_addr *dest = &inet_rsk(req)->ir_v6_rmt_addr; if (ttd < 0) ttd = 0; seq_printf(seq, "%4d: %08X%08X%08X%08X:%04X %08X%08X%08X%08X:%04X " "%02X %08X:%08X %02X:%08lX %08X %5u %8d %d %d %pK\n", i, src->s6_addr32[0], src->s6_addr32[1], src->s6_addr32[2], src->s6_addr32[3], inet_rsk(req)->ir_num, dest->s6_addr32[0], dest->s6_addr32[1], dest->s6_addr32[2], dest->s6_addr32[3], ntohs(inet_rsk(req)->ir_rmt_port), TCP_SYN_RECV, 0, 0, /* could print option size, but that is af dependent. */ 1, /* timers active (only the expire timer) */ jiffies_to_clock_t(ttd), req->num_timeout, from_kuid_munged(seq_user_ns(seq), sock_i_uid(req->rsk_listener)), 0, /* non standard timer */ 0, /* open_requests have no inode */ 0, req); } static void get_tcp6_sock(struct seq_file *seq, struct sock *sp, int i) { const struct in6_addr *dest, *src; __u16 destp, srcp; int timer_active; unsigned long timer_expires; const struct inet_sock *inet = inet_sk(sp); const struct tcp_sock *tp = tcp_sk(sp); const struct inet_connection_sock *icsk = inet_csk(sp); const struct fastopen_queue *fastopenq = &icsk->icsk_accept_queue.fastopenq; int rx_queue; int state; dest = &sp->sk_v6_daddr; src = &sp->sk_v6_rcv_saddr; destp = ntohs(inet->inet_dport); srcp = ntohs(inet->inet_sport); if (icsk->icsk_pending == ICSK_TIME_RETRANS) { timer_active = 1; timer_expires = icsk->icsk_timeout; } else if (icsk->icsk_pending == ICSK_TIME_PROBE0) { timer_active = 4; timer_expires = icsk->icsk_timeout; } else if (timer_pending(&sp->sk_timer)) { timer_active = 2; timer_expires = sp->sk_timer.expires; } else { timer_active = 0; timer_expires = jiffies; } state = sk_state_load(sp); if (state == TCP_LISTEN) rx_queue = sp->sk_ack_backlog; else /* Because we don't lock the socket, * we might find a transient negative value. */ rx_queue = max_t(int, tp->rcv_nxt - tp->copied_seq, 0); seq_printf(seq, "%4d: %08X%08X%08X%08X:%04X %08X%08X%08X%08X:%04X " "%02X %08X:%08X %02X:%08lX %08X %5u %8d %lu %d %pK %lu %lu %u %u %d\n", i, src->s6_addr32[0], src->s6_addr32[1], src->s6_addr32[2], src->s6_addr32[3], srcp, dest->s6_addr32[0], dest->s6_addr32[1], dest->s6_addr32[2], dest->s6_addr32[3], destp, state, tp->write_seq - tp->snd_una, rx_queue, timer_active, jiffies_delta_to_clock_t(timer_expires - jiffies), icsk->icsk_retransmits, from_kuid_munged(seq_user_ns(seq), sock_i_uid(sp)), icsk->icsk_probes_out, sock_i_ino(sp), atomic_read(&sp->sk_refcnt), sp, jiffies_to_clock_t(icsk->icsk_rto), jiffies_to_clock_t(icsk->icsk_ack.ato), (icsk->icsk_ack.quick << 1) | icsk->icsk_ack.pingpong, tp->snd_cwnd, state == TCP_LISTEN ? fastopenq->max_qlen : (tcp_in_initial_slowstart(tp) ? -1 : tp->snd_ssthresh) ); } static void get_timewait6_sock(struct seq_file *seq, struct inet_timewait_sock *tw, int i) { long delta = tw->tw_timer.expires - jiffies; const struct in6_addr *dest, *src; __u16 destp, srcp; dest = &tw->tw_v6_daddr; src = &tw->tw_v6_rcv_saddr; destp = ntohs(tw->tw_dport); srcp = ntohs(tw->tw_sport); seq_printf(seq, "%4d: %08X%08X%08X%08X:%04X %08X%08X%08X%08X:%04X " "%02X %08X:%08X %02X:%08lX %08X %5d %8d %d %d %pK\n", i, src->s6_addr32[0], src->s6_addr32[1], src->s6_addr32[2], src->s6_addr32[3], srcp, dest->s6_addr32[0], dest->s6_addr32[1], dest->s6_addr32[2], dest->s6_addr32[3], destp, tw->tw_substate, 0, 0, 3, jiffies_delta_to_clock_t(delta), 0, 0, 0, 0, atomic_read(&tw->tw_refcnt), tw); } static int tcp6_seq_show(struct seq_file *seq, void *v) { struct tcp_iter_state *st; struct sock *sk = v; if (v == SEQ_START_TOKEN) { seq_puts(seq, " sl " "local_address " "remote_address " "st tx_queue rx_queue tr tm->when retrnsmt" " uid timeout inode\n"); goto out; } st = seq->private; if (sk->sk_state == TCP_TIME_WAIT) get_timewait6_sock(seq, v, st->num); else if (sk->sk_state == TCP_NEW_SYN_RECV) get_openreq6(seq, v, st->num); else get_tcp6_sock(seq, v, st->num); out: return 0; } static const struct file_operations tcp6_afinfo_seq_fops = { .owner = THIS_MODULE, .open = tcp_seq_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release_net }; static struct tcp_seq_afinfo tcp6_seq_afinfo = { .name = "tcp6", .family = AF_INET6, .seq_fops = &tcp6_afinfo_seq_fops, .seq_ops = { .show = tcp6_seq_show, }, }; int __net_init tcp6_proc_init(struct net *net) { return tcp_proc_register(net, &tcp6_seq_afinfo); } void tcp6_proc_exit(struct net *net) { tcp_proc_unregister(net, &tcp6_seq_afinfo); } #endif static void tcp_v6_clear_sk(struct sock *sk, int size) { struct inet_sock *inet = inet_sk(sk); /* we do not want to clear pinet6 field, because of RCU lookups */ sk_prot_clear_nulls(sk, offsetof(struct inet_sock, pinet6)); size -= offsetof(struct inet_sock, pinet6) + sizeof(inet->pinet6); memset(&inet->pinet6 + 1, 0, size); } struct proto tcpv6_prot = { .name = "TCPv6", .owner = THIS_MODULE, .close = tcp_close, .connect = tcp_v6_connect, .disconnect = tcp_disconnect, .accept = inet_csk_accept, .ioctl = tcp_ioctl, .init = tcp_v6_init_sock, .destroy = tcp_v6_destroy_sock, .shutdown = tcp_shutdown, .setsockopt = tcp_setsockopt, .getsockopt = tcp_getsockopt, .recvmsg = tcp_recvmsg, .sendmsg = tcp_sendmsg, .sendpage = tcp_sendpage, .backlog_rcv = tcp_v6_do_rcv, .release_cb = tcp_release_cb, .hash = inet_hash, .unhash = inet_unhash, .get_port = inet_csk_get_port, .enter_memory_pressure = tcp_enter_memory_pressure, .stream_memory_free = tcp_stream_memory_free, .sockets_allocated = &tcp_sockets_allocated, .memory_allocated = &tcp_memory_allocated, .memory_pressure = &tcp_memory_pressure, .orphan_count = &tcp_orphan_count, .sysctl_mem = sysctl_tcp_mem, .sysctl_wmem = sysctl_tcp_wmem, .sysctl_rmem = sysctl_tcp_rmem, .max_header = MAX_TCP_HEADER, .obj_size = sizeof(struct tcp6_sock), .slab_flags = SLAB_DESTROY_BY_RCU, .twsk_prot = &tcp6_timewait_sock_ops, .rsk_prot = &tcp6_request_sock_ops, .h.hashinfo = &tcp_hashinfo, .no_autobind = true, #ifdef CONFIG_COMPAT .compat_setsockopt = compat_tcp_setsockopt, .compat_getsockopt = compat_tcp_getsockopt, #endif .clear_sk = tcp_v6_clear_sk, .diag_destroy = tcp_abort, }; static const struct inet6_protocol tcpv6_protocol = { .early_demux = tcp_v6_early_demux, .handler = tcp_v6_rcv, .err_handler = tcp_v6_err, .flags = INET6_PROTO_NOPOLICY|INET6_PROTO_FINAL, }; static struct inet_protosw tcpv6_protosw = { .type = SOCK_STREAM, .protocol = IPPROTO_TCP, .prot = &tcpv6_prot, .ops = &inet6_stream_ops, .flags = INET_PROTOSW_PERMANENT | INET_PROTOSW_ICSK, }; static int __net_init tcpv6_net_init(struct net *net) { return inet_ctl_sock_create(&net->ipv6.tcp_sk, PF_INET6, SOCK_RAW, IPPROTO_TCP, net); } static void __net_exit tcpv6_net_exit(struct net *net) { inet_ctl_sock_destroy(net->ipv6.tcp_sk); } static void __net_exit tcpv6_net_exit_batch(struct list_head *net_exit_list) { inet_twsk_purge(&tcp_hashinfo, &tcp_death_row, AF_INET6); } static struct pernet_operations tcpv6_net_ops = { .init = tcpv6_net_init, .exit = tcpv6_net_exit, .exit_batch = tcpv6_net_exit_batch, }; int __init tcpv6_init(void) { int ret; ret = inet6_add_protocol(&tcpv6_protocol, IPPROTO_TCP); if (ret) goto out; /* register inet6 protocol */ ret = inet6_register_protosw(&tcpv6_protosw); if (ret) goto out_tcpv6_protocol; ret = register_pernet_subsys(&tcpv6_net_ops); if (ret) goto out_tcpv6_protosw; out: return ret; out_tcpv6_protosw: inet6_unregister_protosw(&tcpv6_protosw); out_tcpv6_protocol: inet6_del_protocol(&tcpv6_protocol, IPPROTO_TCP); goto out; } void tcpv6_exit(void) { unregister_pernet_subsys(&tcpv6_net_ops); inet6_unregister_protosw(&tcpv6_protosw); inet6_del_protocol(&tcpv6_protocol, IPPROTO_TCP); }
<?php /** * Shows a shipping line * * @var object $item The item being displayed * @var int $item_id The id of the item being displayed */ if ( ! defined( 'ABSPATH' ) ) { exit; } ?> <tr class="shipping <?php echo ( ! empty( $class ) ) ? esc_attr( $class ) : ''; ?>" data-order_item_id="<?php echo esc_attr( $item_id ); ?>"> <td class="thumb"><div></div></td> <td class="name"> <div class="view"> <?php echo esc_html( $item->get_name() ? $item->get_name() : __( 'Shipping', 'woocommerce' ) ); ?> </div> <div class="edit" style="display: none;"> <input type="hidden" name="shipping_method_id[]" value="<?php echo esc_attr( $item_id ); ?>" /> <input type="text" class="shipping_method_name" placeholder="<?php esc_attr_e( 'Shipping name', 'woocommerce' ); ?>" name="shipping_method_title[<?php echo esc_attr( $item_id ); ?>]" value="<?php echo esc_attr( $item->get_name() ); ?>" /> <select class="shipping_method" name="shipping_method[<?php echo esc_attr( $item_id ); ?>]"> <optgroup label="<?php esc_attr_e( 'Shipping method', 'woocommerce' ); ?>"> <option value=""><?php esc_html_e( 'N/A', 'woocommerce' ); ?></option> <?php $found_method = false; foreach ( $shipping_methods as $method ) { $current_method = ( 0 === strpos( $item->get_method_id(), $method->id ) ) ? $item->get_method_id() : $method->id; echo '<option value="' . esc_attr( $current_method ) . '" ' . selected( $item->get_method_id() === $current_method, true, false ) . '>' . esc_html( $method->get_method_title() ) . '</option>'; if ( $item->get_method_id() === $current_method ) { $found_method = true; } } if ( ! $found_method && $item->get_method_id() ) { echo '<option value="' . esc_attr( $item->get_method_id() ) . '" selected="selected">' . esc_html__( 'Other', 'woocommerce' ) . '</option>'; } else { echo '<option value="other">' . esc_html__( 'Other', 'woocommerce' ) . '</option>'; } ?> </optgroup> </select> </div> <?php do_action( 'woocommerce_before_order_itemmeta', $item_id, $item, null ); ?> <?php require 'html-order-item-meta.php'; ?> <?php do_action( 'woocommerce_after_order_itemmeta', $item_id, $item, null ); ?> </td> <?php do_action( 'woocommerce_admin_order_item_values', null, $item, absint( $item_id ) ); ?> <td class="item_cost" width="1%">&nbsp;</td> <td class="quantity" width="1%">&nbsp;</td> <td class="line_cost" width="1%"> <div class="view"> <?php echo wc_price( $item->get_total(), array( 'currency' => $order->get_currency() ) ); $refunded = $order->get_total_refunded_for_item( $item_id, 'shipping' ); if ( $refunded ) { echo '<small class="refunded">-' . wc_price( $refunded, array( 'currency' => $order->get_currency() ) ) . '</small>'; } ?> </div> <div class="edit" style="display: none;"> <input type="text" name="shipping_cost[<?php echo esc_attr( $item_id ); ?>]" placeholder="<?php echo esc_attr( wc_format_localized_price( 0 ) ); ?>" value="<?php echo esc_attr( wc_format_localized_price( $item->get_total() ) ); ?>" class="line_total wc_input_price" /> </div> <div class="refund" style="display: none;"> <input type="text" name="refund_line_total[<?php echo absint( $item_id ); ?>]" placeholder="<?php echo esc_attr( wc_format_localized_price( 0 ) ); ?>" class="refund_line_total wc_input_price" /> </div> </td> <?php if ( ( $tax_data = $item->get_taxes() ) && wc_tax_enabled() ) { foreach ( $order_taxes as $tax_item ) { $tax_item_id = $tax_item->get_rate_id(); $tax_item_total = isset( $tax_data['total'][ $tax_item_id ] ) ? $tax_data['total'][ $tax_item_id ] : ''; ?> <td class="line_tax" width="1%"> <div class="view"> <?php echo ( '' !== $tax_item_total ) ? wc_price( wc_round_tax_total( $tax_item_total ), array( 'currency' => $order->get_currency() ) ) : '&ndash;'; $refunded = $order->get_tax_refunded_for_item( $item_id, $tax_item_id, 'shipping' ); if ( $refunded ) { echo '<small class="refunded">-' . wc_price( $refunded, array( 'currency' => $order->get_currency() ) ) . '</small>'; } ?> </div> <div class="edit" style="display: none;"> <input type="text" name="shipping_taxes[<?php echo absint( $item_id ); ?>][<?php echo esc_attr( $tax_item_id ); ?>]" placeholder="<?php echo esc_attr( wc_format_localized_price( 0 ) ); ?>" value="<?php echo ( isset( $tax_item_total ) ) ? esc_attr( wc_format_localized_price( $tax_item_total ) ) : ''; ?>" class="line_tax wc_input_price" /> </div> <div class="refund" style="display: none;"> <input type="text" name="refund_line_tax[<?php echo absint( $item_id ); ?>][<?php echo esc_attr( $tax_item_id ); ?>]" placeholder="<?php echo esc_attr( wc_format_localized_price( 0 ) ); ?>" class="refund_line_tax wc_input_price" data-tax_id="<?php echo esc_attr( $tax_item_id ); ?>" /> </div> </td> <?php } } ?> <td class="wc-order-edit-line-item"> <?php if ( $order->is_editable() ) : ?> <div class="wc-order-edit-line-item-actions"> <a class="edit-order-item" href="#"></a><a class="delete-order-item" href="#"></a> </div> <?php endif; ?> </td> </tr>
#ifndef _ASM_CRIS_UNISTD_H_ #define _ASM_CRIS_UNISTD_H_ /* * This file contains the system call numbers, and stub macros for libc. */ #define __NR_setup 0 /* used only by init, to get system going */ #define __NR_exit 1 #define __NR_fork 2 #define __NR_read 3 #define __NR_write 4 #define __NR_open 5 #define __NR_close 6 #define __NR_waitpid 7 #define __NR_creat 8 #define __NR_link 9 #define __NR_unlink 10 #define __NR_execve 11 #define __NR_chdir 12 #define __NR_time 13 #define __NR_mknod 14 #define __NR_chmod 15 #define __NR_lchown 16 #define __NR_break 17 #define __NR_oldstat 18 #define __NR_lseek 19 #define __NR_getpid 20 #define __NR_mount 21 #define __NR_umount 22 #define __NR_setuid 23 #define __NR_getuid 24 #define __NR_stime 25 #define __NR_ptrace 26 #define __NR_alarm 27 #define __NR_oldfstat 28 #define __NR_pause 29 #define __NR_utime 30 #define __NR_stty 31 #define __NR_gtty 32 #define __NR_access 33 #define __NR_nice 34 #define __NR_ftime 35 #define __NR_sync 36 #define __NR_kill 37 #define __NR_rename 38 #define __NR_mkdir 39 #define __NR_rmdir 40 #define __NR_dup 41 #define __NR_pipe 42 #define __NR_times 43 #define __NR_prof 44 #define __NR_brk 45 #define __NR_setgid 46 #define __NR_getgid 47 #define __NR_signal 48 #define __NR_geteuid 49 #define __NR_getegid 50 #define __NR_acct 51 #define __NR_umount2 52 #define __NR_lock 53 #define __NR_ioctl 54 #define __NR_fcntl 55 #define __NR_mpx 56 #define __NR_setpgid 57 #define __NR_ulimit 58 #define __NR_oldolduname 59 #define __NR_umask 60 #define __NR_chroot 61 #define __NR_ustat 62 #define __NR_dup2 63 #define __NR_getppid 64 #define __NR_getpgrp 65 #define __NR_setsid 66 #define __NR_sigaction 67 #define __NR_sgetmask 68 #define __NR_ssetmask 69 #define __NR_setreuid 70 #define __NR_setregid 71 #define __NR_sigsuspend 72 #define __NR_sigpending 73 #define __NR_sethostname 74 #define __NR_setrlimit 75 #define __NR_getrlimit 76 #define __NR_getrusage 77 #define __NR_gettimeofday 78 #define __NR_settimeofday 79 #define __NR_getgroups 80 #define __NR_setgroups 81 #define __NR_select 82 #define __NR_symlink 83 #define __NR_oldlstat 84 #define __NR_readlink 85 #define __NR_uselib 86 #define __NR_swapon 87 #define __NR_reboot 88 #define __NR_readdir 89 #define __NR_mmap 90 #define __NR_munmap 91 #define __NR_truncate 92 #define __NR_ftruncate 93 #define __NR_fchmod 94 #define __NR_fchown 95 #define __NR_getpriority 96 #define __NR_setpriority 97 #define __NR_profil 98 #define __NR_statfs 99 #define __NR_fstatfs 100 #define __NR_ioperm 101 #define __NR_socketcall 102 #define __NR_syslog 103 #define __NR_setitimer 104 #define __NR_getitimer 105 #define __NR_stat 106 #define __NR_lstat 107 #define __NR_fstat 108 #define __NR_olduname 109 #define __NR_iopl 110 #define __NR_vhangup 111 #define __NR_idle 112 #define __NR_vm86 113 #define __NR_wait4 114 #define __NR_swapoff 115 #define __NR_sysinfo 116 #define __NR_ipc 117 #define __NR_fsync 118 #define __NR_sigreturn 119 #define __NR_clone 120 #define __NR_setdomainname 121 #define __NR_uname 122 #define __NR_modify_ldt 123 #define __NR_adjtimex 124 #define __NR_mprotect 125 #define __NR_sigprocmask 126 #define __NR_create_module 127 #define __NR_init_module 128 #define __NR_delete_module 129 #define __NR_get_kernel_syms 130 #define __NR_quotactl 131 #define __NR_getpgid 132 #define __NR_fchdir 133 #define __NR_bdflush 134 #define __NR_sysfs 135 #define __NR_personality 136 #define __NR_afs_syscall 137 /* Syscall for Andrew File System */ #define __NR_setfsuid 138 #define __NR_setfsgid 139 #define __NR__llseek 140 #define __NR_getdents 141 #define __NR__newselect 142 #define __NR_flock 143 #define __NR_msync 144 #define __NR_readv 145 #define __NR_writev 146 #define __NR_getsid 147 #define __NR_fdatasync 148 #define __NR__sysctl 149 #define __NR_mlock 150 #define __NR_munlock 151 #define __NR_mlockall 152 #define __NR_munlockall 153 #define __NR_sched_setparam 154 #define __NR_sched_getparam 155 #define __NR_sched_setscheduler 156 #define __NR_sched_getscheduler 157 #define __NR_sched_yield 158 #define __NR_sched_get_priority_max 159 #define __NR_sched_get_priority_min 160 #define __NR_sched_rr_get_interval 161 #define __NR_nanosleep 162 #define __NR_mremap 163 #define __NR_setresuid 164 #define __NR_getresuid 165 #define __NR_query_module 167 #define __NR_poll 168 #define __NR_nfsservctl 169 #define __NR_setresgid 170 #define __NR_getresgid 171 #define __NR_prctl 172 #define __NR_rt_sigreturn 173 #define __NR_rt_sigaction 174 #define __NR_rt_sigprocmask 175 #define __NR_rt_sigpending 176 #define __NR_rt_sigtimedwait 177 #define __NR_rt_sigqueueinfo 178 #define __NR_rt_sigsuspend 179 #define __NR_pread 180 #define __NR_pwrite 181 #define __NR_chown 182 #define __NR_getcwd 183 #define __NR_capget 184 #define __NR_capset 185 #define __NR_sigaltstack 186 #define __NR_sendfile 187 #define __NR_getpmsg 188 /* some people actually want streams */ #define __NR_putpmsg 189 /* some people actually want streams */ #define __NR_vfork 190 #define __NR_ugetrlimit 191 /* SuS compliant getrlimit */ #define __NR_mmap2 192 #define __NR_truncate64 193 #define __NR_ftruncate64 194 #define __NR_stat64 195 #define __NR_lstat64 196 #define __NR_fstat64 197 #define __NR_lchown32 198 #define __NR_getuid32 199 #define __NR_getgid32 200 #define __NR_geteuid32 201 #define __NR_getegid32 202 #define __NR_setreuid32 203 #define __NR_setregid32 204 #define __NR_getgroups32 205 #define __NR_setgroups32 206 #define __NR_fchown32 207 #define __NR_setresuid32 208 #define __NR_getresuid32 209 #define __NR_setresgid32 210 #define __NR_getresgid32 211 #define __NR_chown32 212 #define __NR_setuid32 213 #define __NR_setgid32 214 #define __NR_setfsuid32 215 #define __NR_setfsgid32 216 #define __NR_pivot_root 217 #define __NR_mincore 218 #define __NR_madvise 219 #define __NR_getdents64 220 #define __NR_fcntl64 221 #define __NR_security 223 /* syscall for security modules */ #define __NR_gettid 224 #define __NR_readahead 225 #define __NR_setxattr 226 #define __NR_lsetxattr 227 #define __NR_fsetxattr 228 #define __NR_getxattr 229 #define __NR_lgetxattr 230 #define __NR_fgetxattr 231 #define __NR_listxattr 232 #define __NR_llistxattr 233 #define __NR_flistxattr 234 #define __NR_removexattr 235 #define __NR_lremovexattr 236 #define __NR_fremovexattr 237 #define __NR_tkill 238 #define __NR_sendfile64 239 #define __NR_futex 240 #define __NR_sched_setaffinity 241 #define __NR_sched_getaffinity 242 #define __NR_set_thread_area 243 #define __NR_get_thread_area 244 #define __NR_io_setup 245 #define __NR_io_destroy 246 #define __NR_io_getevents 247 #define __NR_io_submit 248 #define __NR_io_cancel 249 #define __NR_alloc_hugepages 250 #define __NR_free_hugepages 251 #define __NR_exit_group 252 /* XXX - _foo needs to be __foo, while __NR_bar could be _NR_bar. */ /* * Don't remove the .ifnc tests; they are an insurance against * any hard-to-spot gcc register allocation bugs. */ #define _syscall0(type,name) \ type name(void) \ { \ register long __a __asm__ ("r10"); \ register long __n_ __asm__ ("r9") = (__NR_##name); \ __asm__ __volatile__ (".ifnc %0%1,$r10$r9\n\t" \ ".err\n\t" \ ".endif\n\t" \ "break 13" \ : "=r" (__a) \ : "r" (__n_)); \ if (__a >= 0) \ return (type) __a; \ errno = -__a; \ return (type) -1; \ } #define _syscall1(type,name,type1,arg1) \ type name(type1 arg1) \ { \ register long __a __asm__ ("r10") = (long) arg1; \ register long __n_ __asm__ ("r9") = (__NR_##name); \ __asm__ __volatile__ (".ifnc %0%1,$r10$r9\n\t" \ ".err\n\t" \ ".endif\n\t" \ "break 13" \ : "=r" (__a) \ : "r" (__n_), "0" (__a)); \ if (__a >= 0) \ return (type) __a; \ errno = -__a; \ return (type) -1; \ } #define _syscall2(type,name,type1,arg1,type2,arg2) \ type name(type1 arg1,type2 arg2) \ { \ register long __a __asm__ ("r10") = (long) arg1; \ register long __b __asm__ ("r11") = (long) arg2; \ register long __n_ __asm__ ("r9") = (__NR_##name); \ __asm__ __volatile__ (".ifnc %0%1%3,$r10$r9$r11\n\t" \ ".err\n\t" \ ".endif\n\t" \ "break 13" \ : "=r" (__a) \ : "r" (__n_), "0" (__a), "r" (__b)); \ if (__a >= 0) \ return (type) __a; \ errno = -__a; \ return (type) -1; \ } #define _syscall3(type,name,type1,arg1,type2,arg2,type3,arg3) \ type name(type1 arg1,type2 arg2,type3 arg3) \ { \ register long __a __asm__ ("r10") = (long) arg1; \ register long __b __asm__ ("r11") = (long) arg2; \ register long __c __asm__ ("r12") = (long) arg3; \ register long __n_ __asm__ ("r9") = (__NR_##name); \ __asm__ __volatile__ (".ifnc %0%1%3%4,$r10$r9$r11$r12\n\t" \ ".err\n\t" \ ".endif\n\t" \ "break 13" \ : "=r" (__a) \ : "r" (__n_), "0" (__a), "r" (__b), "r" (__c)); \ if (__a >= 0) \ return (type) __a; \ errno = -__a; \ return (type) -1; \ } #define _syscall4(type,name,type1,arg1,type2,arg2,type3,arg3,type4,arg4) \ type name (type1 arg1, type2 arg2, type3 arg3, type4 arg4) \ { \ register long __a __asm__ ("r10") = (long) arg1; \ register long __b __asm__ ("r11") = (long) arg2; \ register long __c __asm__ ("r12") = (long) arg3; \ register long __d __asm__ ("r13") = (long) arg4; \ register long __n_ __asm__ ("r9") = (__NR_##name); \ __asm__ __volatile__ (".ifnc %0%1%3%4%5,$r10$r9$r11$r12$r13\n\t" \ ".err\n\t" \ ".endif\n\t" \ "break 13" \ : "=r" (__a) \ : "r" (__n_), "0" (__a), "r" (__b), \ "r" (__c), "r" (__d)); \ if (__a >= 0) \ return (type) __a; \ errno = -__a; \ return (type) -1; \ } #define _syscall5(type,name,type1,arg1,type2,arg2,type3,arg3,type4,arg4, \ type5,arg5) \ type name (type1 arg1,type2 arg2,type3 arg3,type4 arg4,type5 arg5) \ { \ register long __a __asm__ ("r10") = (long) arg1; \ register long __b __asm__ ("r11") = (long) arg2; \ register long __c __asm__ ("r12") = (long) arg3; \ register long __d __asm__ ("r13") = (long) arg4; \ register long __n_ __asm__ ("r9") = (__NR_##name); \ __asm__ __volatile__ (".ifnc %0%1%3%4%5,$r10$r9$r11$r12$r13\n\t" \ ".err\n\t" \ ".endif\n\t" \ "move %6,$mof\n\t" \ "break 13" \ : "=r" (__a) \ : "r" (__n_), "0" (__a), "r" (__b), \ "r" (__c), "r" (__d), "g" (arg5)); \ if (__a >= 0) \ return (type) __a; \ errno = -__a; \ return (type) -1; \ } #define _syscall6(type,name,type1,arg1,type2,arg2,type3,arg3,type4,arg4, \ type5,arg5,type6,arg6) \ type name (type1 arg1,type2 arg2,type3 arg3,type4 arg4,type5 arg5,type6 arg6) \ { \ register long __a __asm__ ("r10") = (long) arg1; \ register long __b __asm__ ("r11") = (long) arg2; \ register long __c __asm__ ("r12") = (long) arg3; \ register long __d __asm__ ("r13") = (long) arg4; \ register long __n_ __asm__ ("r9") = (__NR_##name); \ __asm__ __volatile__ (".ifnc %0%1%3%4%5,$r10$r9$r11$r12$r13\n\t" \ ".err\n\t" \ ".endif\n\t" \ "move %6,$mof\n\tmove %7,$srp\n\t" \ "break 13" \ : "=r" (__a) \ : "r" (__n_), "0" (__a), "r" (__b), \ "r" (__c), "r" (__d), "g" (arg5), "g" (arg6)\ : "srp"); \ if (__a >= 0) \ return (type) __a; \ errno = -__a; \ return (type) -1; \ } #ifdef __KERNEL_SYSCALLS__ /* * we need this inline - forking from kernel space will result * in NO COPY ON WRITE (!!!), until an execve is executed. This * is no problem, but for the stack. This is handled by not letting * main() use the stack at all after fork(). Thus, no function * calls - which means inline code for fork too, as otherwise we * would use the stack upon exit from 'fork()'. * * Actually only pause and fork are needed inline, so that there * won't be any messing with the stack from main(), but we define * some others too. */ #define __NR__exit __NR_exit extern inline _syscall0(int,idle) extern inline _syscall0(int,fork) extern inline _syscall2(int,clone,unsigned long,flags,char *,esp) extern inline _syscall0(int,pause) extern inline _syscall0(int,setup) extern inline _syscall0(int,sync) extern inline _syscall0(pid_t,setsid) extern inline _syscall3(int,write,int,fd,const char *,buf,off_t,count) extern inline _syscall1(int,dup,int,fd) extern inline _syscall3(int,execve,const char *,file,char **,argv,char **,envp) extern inline _syscall3(int,open,const char *,file,int,flag,int,mode) extern inline _syscall1(int,close,int,fd) /* * Since we define it "external", it collides with the built-in * definition, which has the "noreturn" attribute and will cause * complaints. We don't want to use -fno-builtin, so just use a * different name when in the kernel. */ #ifdef __KERNEL__ #define _exit kernel_syscall_exit #endif extern inline _syscall1(int,_exit,int,exitcode) extern inline _syscall3(pid_t,waitpid,pid_t,pid,int *,wait_stat,int,options) extern inline _syscall3(off_t,lseek,int,fd,off_t,offset,int,count) /* the following are just while developing the elinux port! */ extern inline _syscall3(int,read,int,fd,char *,buf,off_t,count) extern inline _syscall2(int,socketcall,int,call,unsigned long *,args) extern inline _syscall3(int,ioctl,unsigned int,fd,unsigned int,cmd,unsigned long,arg) extern inline _syscall5(int,mount,const char *,a,const char *,b,const char *,c,unsigned long,rwflag,const void *,data) extern inline pid_t wait(int * wait_stat) { return waitpid(-1,wait_stat,0); } #endif #endif /* _ASM_CRIS_UNISTD_H_ */
MPLAYER_COV_OPTS="--enable-xvmc --enable-menu --enable-gui --enable-mga --enable-bl --enable-joystick --enable-radio --enable-s3fb --enable-tdfxfb --enable-tdfxvid --enable-wii --yasm=nasm" rm -rf cov-int MPlayer.tgz make distclean svn up ./configure $MPLAYER_COV_OPTS && make -j5 ffmpeglibs || exit 1 "$MPLAYER_COV_PATH"/bin/cov-build --dir cov-int make -j5 || exit 1 tar -czf MPlayer.tgz cov-int curl --form file=@MPlayer.tgz --form project=MPlayer --form password="$MPLAYER_COV_PWD" --form email="$MPLAYER_COV_EMAIL" --form version=2.5 --form description="automated run" http://scan5.coverity.com/cgi-bin/upload.py
/* Copyright 1999-2012 ImageMagick Studio LLC, a non-profit organization dedicated to making software imaging solutions freely available. You may not use this file except in compliance with the License. obtain a copy of the License at http://www.imagemagick.org/script/license.php Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. MagickCore image segment methods. */ #ifndef _MAGICKCORE_SEGMENT_H #define _MAGICKCORE_SEGMENT_H #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif extern MagickExport MagickBooleanType GetImageDynamicThreshold(const Image *,const double,const double, MagickPixelPacket *,ExceptionInfo *), SegmentImage(Image *,const ColorspaceType,const MagickBooleanType, const double,const double); #if defined(__cplusplus) || defined(c_plusplus) } #endif #endif
/* ***************************************************************************** * A.L.E (Arcade Learning Environment) * Copyright (c) 2009-2013 by Yavar Naddaf, Joel Veness, Marc G. Bellemare and * the Reinforcement Learning and Artificial Intelligence Laboratory * Released under the GNU General Public License; see License.txt for details. * * Based on: Stella -- "An Atari 2600 VCS Emulator" * Copyright (c) 1995-2007 by Bradford W. Mott and the Stella team * * ***************************************************************************** */ #ifndef __ASTEROIDS_HPP__ #define __ASTEROIDS_HPP__ #include "../RomSettings.hpp" /* RL wrapper for Asteroids */ class AsteroidsSettings : public RomSettings { public: AsteroidsSettings(); // reset void reset(); // is end of game bool isTerminal() const; // get the most recently observed reward reward_t getReward() const; // the rom-name const char* rom() const { return "asteroids"; } // create a new instance of the rom RomSettings* clone() const; // is an action part of the minimal set? bool isMinimal(const Action& a) const; // process the latest information from ALE void step(const System& system); // saves the state of the rom settings void saveState(Serializer & ser); // loads the state of the rom settings void loadState(Deserializer & ser); private: bool m_terminal; reward_t m_reward; reward_t m_score; }; #endif // __ASTEROIDS_HPP__
<?php /** * @package Joomla.Administrator * @subpackage com_languages * * @copyright (C) 2018 Open Source Matters, Inc. <https://www.joomla.org> * @license GNU General Public License version 2 or later; see LICENSE.txt */ defined('_JEXEC') or die; use Joomla\CMS\Dispatcher\ComponentDispatcherFactoryInterface; use Joomla\CMS\Extension\ComponentInterface; use Joomla\CMS\Extension\Service\Provider\ComponentDispatcherFactory; use Joomla\CMS\Extension\Service\Provider\MVCFactory; use Joomla\CMS\HTML\Registry; use Joomla\CMS\MVC\Factory\MVCFactoryInterface; use Joomla\Component\Languages\Administrator\Extension\LanguagesComponent; use Joomla\DI\Container; use Joomla\DI\ServiceProviderInterface; /** * The language service provider. * * @since 4.0.0 */ return new class implements ServiceProviderInterface { /** * Registers the service provider with a DI container. * * @param Container $container The DI container. * * @return void * * @since 4.0.0 */ public function register(Container $container) { $container->registerServiceProvider(new MVCFactory('\\Joomla\\Component\\Languages')); $container->registerServiceProvider(new ComponentDispatcherFactory('\\Joomla\\Component\\Languages')); $container->set( ComponentInterface::class, function (Container $container) { $component = new LanguagesComponent($container->get(ComponentDispatcherFactoryInterface::class)); $component->setMVCFactory($container->get(MVCFactoryInterface::class)); $component->setRegistry($container->get(Registry::class)); return $component; } ); } };
/** * Plugin that highlights matched word partials in a given element. * TODO: Add a function for restoring the previous text. * TODO: Accept mappings for converting shortcuts like WP: to Wikipedia:. */ ( function ( $ ) { $.highlightText = { // Split our pattern string at spaces and run our highlight function on the results splitAndHighlight: function ( node, pat ) { var i, patArray = pat.split( ' ' ); for ( i = 0; i < patArray.length; i++ ) { if ( patArray[i].length === 0 ) { continue; } $.highlightText.innerHighlight( node, patArray[i] ); } return node; }, // scans a node looking for the pattern and wraps a span around each match innerHighlight: function ( node, pat ) { var i, match, pos, spannode, middlebit, middleclone; // if this is a text node if ( node.nodeType === 3 ) { // TODO - need to be smarter about the character matching here. // non latin characters can make regex think a new word has begun: do not use \b // http://stackoverflow.com/questions/3787072/regex-wordwrap-with-utf8-characters-in-js // look for an occurrence of our pattern and store the starting position match = node.data.match( new RegExp( "(^|\\s)" + $.escapeRE( pat ), "i" ) ); if ( match ) { pos = match.index + match[1].length; // include length of any matched spaces // create the span wrapper for the matched text spannode = document.createElement( 'span' ); spannode.className = 'highlight'; // shave off the characters preceding the matched text middlebit = node.splitText( pos ); // shave off any unmatched text off the end middlebit.splitText( pat.length ); // clone for appending to our span middleclone = middlebit.cloneNode( true ); // append the matched text node to the span spannode.appendChild( middleclone ); // replace the matched node, with our span-wrapped clone of the matched node middlebit.parentNode.replaceChild( spannode, middlebit ); } // if this is an element with childnodes, and not a script, style or an element we created } else if ( node.nodeType === 1 && node.childNodes && !/(script|style)/i.test( node.tagName ) && !( node.tagName.toLowerCase() === 'span' && node.className.match( /\bhighlight/ ) ) ) { for ( i = 0; i < node.childNodes.length; ++i ) { // call the highlight function for each child node $.highlightText.innerHighlight( node.childNodes[i], pat ); } } } }; $.fn.highlightText = function ( matchString ) { return this.each( function () { var $el = $( this ); $el.data( 'highlightText', { originalText: $el.text() } ); $.highlightText.splitAndHighlight( this, matchString ); } ); }; }( jQuery ) );
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Automatically generated strings for Moodle installer * * Do not edit this file manually! It contains just a subset of strings * needed during the very first steps of installation. This file was * generated automatically by export-installer.php (which is part of AMOS * {@link http://docs.moodle.org/dev/Languages/AMOS}) using the * list of strings defined in /install/stringnames.txt. * * @package installer * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); $string['parentlanguage'] = 'el'; $string['thisdirection'] = 'ltr'; $string['thislanguage'] = 'Ελληνικά για Χώρους Εργασίας';
// // AccessExpireLRUCache.h // // $Id: //poco/1.3/Foundation/include/Poco/AccessExpireLRUCache.h#1 $ // // Library: Foundation // Package: Cache // Module: AccessExpireLRUCache // // Definition of the AccessExpireLRUCache class. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef Foundation_AccessExpireLRUCache_INCLUDED #define Foundation_AccessExpireLRUCache_INCLUDED #include "Poco/AbstractCache.h" #include "Poco/StrategyCollection.h" #include "Poco/AccessExpireStrategy.h" #include "Poco/LRUStrategy.h" namespace Poco { template < class TKey, class TValue > class AccessExpireLRUCache: public AbstractCache<TKey, TValue, StrategyCollection<TKey, TValue> > /// An AccessExpireLRUCache combines LRU caching and time based expire caching. /// It cache entries for a fixed time period (per default 10 minutes) /// but also limits the size of the cache (per default: 1024). { public: AccessExpireLRUCache(long cacheSize = 1024, Timestamp::TimeDiff expire = 600000): AbstractCache<TKey, TValue, StrategyCollection<TKey, TValue> >(StrategyCollection<TKey, TValue>()) { this->_strategy.pushBack(new LRUStrategy<TKey, TValue>(cacheSize)); this->_strategy.pushBack(new AccessExpireStrategy<TKey, TValue>(expire)); } ~AccessExpireLRUCache() { } private: AccessExpireLRUCache(const AccessExpireLRUCache& aCache); AccessExpireLRUCache& operator = (const AccessExpireLRUCache& aCache); }; } // namespace Poco #endif // Foundation_AccessExpireLRUCache_INCLUDED
<!doctype html> <html> <head> <title>menu</title> <meta content="text/html; charset=utf-8" http-equiv="Content-Type"/> <link rel="stylesheet" href="/resources/testharness.css"> <link rel="stylesheet" href="/wai-aria/scripts/manual.css"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/wai-aria/scripts/ATTAcomm.js"></script> <script> setup({explicit_timeout: true, explicit_done: true }); var theTest = new ATTAcomm( { "steps" : [ { "element" : "test", "test" : { "ATK" : [ [ "property", "role", "is", "ROLE_MENU" ], [ "property", "interfaces", "contains", "Selection" ] ], "AXAPI" : [ [ "property", "AXRole", "is", "AXMenu" ], [ "property", "AXSubrole", "is", "<nil>" ], [ "property", "AXRoleDescription", "is", "menu" ] ], "IAccessible2" : [ [ "result", "IAccessible::accSelect()", "is", "TBD" ], [ "result", "IAccessible::get_accSelection()", "is", "TBD" ] ], "MSAA" : [ [ "property", "role", "is", "ROLE_SYSTEM_MENUPOPUP" ] ], "UIA" : [ [ "property", "ControlType", "is", "Menu" ] ] }, "title" : "step 1", "type" : "test" } ], "title" : "menu" } ) ; </script> </head> <body> <p>This test examines the ARIA properties for menu.</p> <div role='menu' id='test'> <div role='menuitemradio'>content</div> </div> <div id="manualMode"></div> <div id="log"></div> <div id="ATTAmessages"></div> </body> </html>
<!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title>mathvariant bold-script</title> <link rel="help" href="http://www.mathml-association.org/MathMLinHTML5/S2.html#SS3.SSS1.tab2"/> <link rel="match" href="mathvariant-bold-script-ref.html"/> <meta name="assert" content="Verify that a single-char <mtext> with a bold-script mathvariant is equivalent to an <mtext> with the transformed unicode character."> <style> @font-face { font-family: TestFont; src: url("/fonts/math/mathvariant-bold-script.woff"); } body > span { padding: 10px; } span > span { font-family: monospace; font-size: 10px; } math { font-family: TestFont; font-size: 10px; } </style> <body> <!-- Generated by mathml/tools/mathvariant.py; DO NOT EDIT. --> <p>Test passes if all the equalities below are true.</p> <span><math><mtext mathvariant="bold-script">&#x41;</mtext></math>=<span>1D4D0</span></span> <span><math><mtext mathvariant="bold-script">&#x42;</mtext></math>=<span>1D4D1</span></span> <span><math><mtext mathvariant="bold-script">&#x43;</mtext></math>=<span>1D4D2</span></span> <span><math><mtext mathvariant="bold-script">&#x44;</mtext></math>=<span>1D4D3</span></span> <span><math><mtext mathvariant="bold-script">&#x45;</mtext></math>=<span>1D4D4</span></span> <span><math><mtext mathvariant="bold-script">&#x46;</mtext></math>=<span>1D4D5</span></span> <span><math><mtext mathvariant="bold-script">&#x47;</mtext></math>=<span>1D4D6</span></span> <span><math><mtext mathvariant="bold-script">&#x48;</mtext></math>=<span>1D4D7</span></span> <span><math><mtext mathvariant="bold-script">&#x49;</mtext></math>=<span>1D4D8</span></span> <span><math><mtext mathvariant="bold-script">&#x4A;</mtext></math>=<span>1D4D9</span></span><br/> <span><math><mtext mathvariant="bold-script">&#x4B;</mtext></math>=<span>1D4DA</span></span> <span><math><mtext mathvariant="bold-script">&#x4C;</mtext></math>=<span>1D4DB</span></span> <span><math><mtext mathvariant="bold-script">&#x4D;</mtext></math>=<span>1D4DC</span></span> <span><math><mtext mathvariant="bold-script">&#x4E;</mtext></math>=<span>1D4DD</span></span> <span><math><mtext mathvariant="bold-script">&#x4F;</mtext></math>=<span>1D4DE</span></span> <span><math><mtext mathvariant="bold-script">&#x50;</mtext></math>=<span>1D4DF</span></span> <span><math><mtext mathvariant="bold-script">&#x51;</mtext></math>=<span>1D4E0</span></span> <span><math><mtext mathvariant="bold-script">&#x52;</mtext></math>=<span>1D4E1</span></span> <span><math><mtext mathvariant="bold-script">&#x53;</mtext></math>=<span>1D4E2</span></span> <span><math><mtext mathvariant="bold-script">&#x54;</mtext></math>=<span>1D4E3</span></span><br/> <span><math><mtext mathvariant="bold-script">&#x55;</mtext></math>=<span>1D4E4</span></span> <span><math><mtext mathvariant="bold-script">&#x56;</mtext></math>=<span>1D4E5</span></span> <span><math><mtext mathvariant="bold-script">&#x57;</mtext></math>=<span>1D4E6</span></span> <span><math><mtext mathvariant="bold-script">&#x58;</mtext></math>=<span>1D4E7</span></span> <span><math><mtext mathvariant="bold-script">&#x59;</mtext></math>=<span>1D4E8</span></span> <span><math><mtext mathvariant="bold-script">&#x5A;</mtext></math>=<span>1D4E9</span></span> <span><math><mtext mathvariant="bold-script">&#x61;</mtext></math>=<span>1D4EA</span></span> <span><math><mtext mathvariant="bold-script">&#x62;</mtext></math>=<span>1D4EB</span></span> <span><math><mtext mathvariant="bold-script">&#x63;</mtext></math>=<span>1D4EC</span></span> <span><math><mtext mathvariant="bold-script">&#x64;</mtext></math>=<span>1D4ED</span></span><br/> <span><math><mtext mathvariant="bold-script">&#x65;</mtext></math>=<span>1D4EE</span></span> <span><math><mtext mathvariant="bold-script">&#x66;</mtext></math>=<span>1D4EF</span></span> <span><math><mtext mathvariant="bold-script">&#x67;</mtext></math>=<span>1D4F0</span></span> <span><math><mtext mathvariant="bold-script">&#x68;</mtext></math>=<span>1D4F1</span></span> <span><math><mtext mathvariant="bold-script">&#x69;</mtext></math>=<span>1D4F2</span></span> <span><math><mtext mathvariant="bold-script">&#x6A;</mtext></math>=<span>1D4F3</span></span> <span><math><mtext mathvariant="bold-script">&#x6B;</mtext></math>=<span>1D4F4</span></span> <span><math><mtext mathvariant="bold-script">&#x6C;</mtext></math>=<span>1D4F5</span></span> <span><math><mtext mathvariant="bold-script">&#x6D;</mtext></math>=<span>1D4F6</span></span> <span><math><mtext mathvariant="bold-script">&#x6E;</mtext></math>=<span>1D4F7</span></span><br/> <span><math><mtext mathvariant="bold-script">&#x6F;</mtext></math>=<span>1D4F8</span></span> <span><math><mtext mathvariant="bold-script">&#x70;</mtext></math>=<span>1D4F9</span></span> <span><math><mtext mathvariant="bold-script">&#x71;</mtext></math>=<span>1D4FA</span></span> <span><math><mtext mathvariant="bold-script">&#x72;</mtext></math>=<span>1D4FB</span></span> <span><math><mtext mathvariant="bold-script">&#x73;</mtext></math>=<span>1D4FC</span></span> <span><math><mtext mathvariant="bold-script">&#x74;</mtext></math>=<span>1D4FD</span></span> <span><math><mtext mathvariant="bold-script">&#x75;</mtext></math>=<span>1D4FE</span></span> <span><math><mtext mathvariant="bold-script">&#x76;</mtext></math>=<span>1D4FF</span></span> <span><math><mtext mathvariant="bold-script">&#x77;</mtext></math>=<span>1D500</span></span> <span><math><mtext mathvariant="bold-script">&#x78;</mtext></math>=<span>1D501</span></span><br/> <span><math><mtext mathvariant="bold-script">&#x79;</mtext></math>=<span>1D502</span></span> <span><math><mtext mathvariant="bold-script">&#x7A;</mtext></math>=<span>1D503</span></span> </body> </html>
<?php if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point'); /********************************************************************************* * SugarCRM is a customer relationship management program developed by * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc. * * 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. If the display of the logo is not reasonably feasible for * technical reasons, the Appropriate Legal Notices must display the words * "Powered by SugarCRM". ********************************************************************************/ $subpanel_layout = array( 'top_buttons' => array( array('widget_class' => 'SubPanelTopCreateButton'), array('widget_class' => 'SubPanelTopSelectButton', 'popup_module' => 'People'), ), 'where' => '', 'list_fields' => array( 'first_name'=>array( 'name'=>'first_name', 'usage' => 'query_only', ), 'last_name'=>array( 'name'=>'last_name', 'usage' => 'query_only', ), 'salutation'=>array( 'name'=>'salutation', 'usage' => 'query_only', ), 'name'=>array( 'name'=>'name', 'vname' => 'LBL_LIST_NAME', 'sort_by' => 'last_name', 'sort_order' => 'asc', 'widget_class' => 'SubPanelDetailViewLink', 'module' => 'Contacts', 'width' => '40%', ), 'email1'=>array( 'name'=>'email1', 'vname' => 'LBL_LIST_EMAIL', 'widget_class' => 'SubPanelEmailLink', 'width' => '35%', ), 'phone_work'=>array ( 'name'=>'phone_work', 'vname' => 'LBL_LIST_PHONE', 'width' => '15%', ), 'edit_button'=>array( 'widget_class' => 'SubPanelEditButton', 'module' => 'Contacts', 'width' => '5%', ), 'remove_button'=>array( 'widget_class' => 'SubPanelRemoveButton', 'module' => 'Contacts', 'width' => '5%', ), ), ); ?>
odoo.define('web.domain_tests', function (require) { "use strict"; var Domain = require('web.Domain'); QUnit.module('core', {}, function () { QUnit.module('domain'); QUnit.test("basic", function (assert) { assert.expect(3); var fields = { a: 3, group_method: 'line', select1: 'day', rrule_type: 'monthly', }; assert.ok(new Domain([['a', '=', 3]]).compute(fields)); assert.ok(new Domain([['group_method','!=','count']]).compute(fields)); assert.ok(new Domain([['select1','=','day'], ['rrule_type','=','monthly']]).compute(fields)); }); QUnit.test("or", function (assert) { assert.expect(3); var web = { section_id: null, user_id: null, member_ids: null, }; var currentDomain = [ '|', ['section_id', '=', 42], '|', ['user_id', '=', 3], ['member_ids', 'in', [3]] ]; assert.ok(new Domain(currentDomain).compute(_.extend({}, web, {section_id: 42}))); assert.ok(new Domain(currentDomain).compute(_.extend({}, web, {user_id: 3}))); assert.ok(new Domain(currentDomain).compute(_.extend({}, web, {member_ids: 3}))); }); QUnit.test("not", function (assert) { assert.expect(2); var fields = { a: 5, group_method: 'line', }; assert.ok(new Domain(['!', ['a', '=', 3]]).compute(fields)); assert.ok(new Domain(['!', ['group_method','=','count']]).compute(fields)); }); QUnit.test("domains initialized with a number", function (assert) { assert.expect(2); assert.ok(new Domain(1).compute({})); assert.notOk(new Domain(0).compute({})); }); }); });
<?php /* * $Id$ * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * This software consists of voluntary contributions made by many individuals * and is licensed under the LGPL. For more information, see * <http://www.doctrine-project.org>. */ /** * Doctrine_Migration_Diff_TestCase * * @package Doctrine * @author Konsta Vesterinen <kvesteri@cc.hut.fi> * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @category Object Relational Mapping * @link www.doctrine-project.org * @since 1.0 * @version $Revision$ */ class Doctrine_Migration_Diff_TestCase extends Doctrine_UnitTestCase { public function testTest() { $from = dirname(__FILE__) . '/Diff/schema/from.yml'; $to = dirname(__FILE__) . '/Diff/schema/to.yml'; $migrationsPath = dirname(__FILE__) . '/Diff/migrations'; Doctrine_Lib::makeDirectories($migrationsPath); $diff = new Doctrine_Migration_Diff($from, $to, $migrationsPath); $changes = $diff->generateChanges(); $this->assertEqual($changes['dropped_tables']['homepage']['tableName'], 'homepage'); $this->assertEqual($changes['created_tables']['blog_post']['tableName'], 'blog_post'); $this->assertEqual($changes['created_columns']['profile']['user_id'], array('type' => 'integer', 'length' => 8)); $this->assertEqual($changes['dropped_columns']['user']['homepage_id'], array('type' => 'integer', 'length' => 8)); $this->assertEqual($changes['dropped_columns']['user']['profile_id'], array('type' => 'integer', 'length' => 8)); $this->assertEqual($changes['changed_columns']['user']['username'], array('type' => 'string', 'length' => 255, 'unique' => true, 'notnull' => true)); $this->assertEqual($changes['created_foreign_keys']['profile']['profile_user_id_user_id']['local'], 'user_id'); $this->assertEqual($changes['created_foreign_keys']['blog_post']['blog_post_user_id_user_id']['local'], 'user_id'); $this->assertEqual($changes['dropped_foreign_keys']['user']['user_profile_id_profile_id']['local'], 'profile_id'); $this->assertEqual($changes['dropped_foreign_keys']['user']['user_homepage_id_homepage_id']['local'], 'homepage_id'); $this->assertEqual($changes['created_indexes']['blog_post']['blog_post_user_id'], array('fields' => array('user_id'))); $this->assertEqual($changes['created_indexes']['profile']['profile_user_id'], array('fields' => array('user_id'))); $this->assertEqual($changes['dropped_indexes']['user']['is_active'], array('fields' => array('is_active'))); $diff->generateMigrationClasses(); $files = glob($migrationsPath . '/*.php'); $this->assertEqual(count($files), 2); $this->assertTrue(strpos($files[0], '_version1.php')); $this->assertTrue(strpos($files[1], '_version2.php')); $code1 = file_get_contents($files[0]); $this->assertTrue(strpos($code1, 'this->dropTable')); $this->assertTrue(strpos($code1, 'this->createTable')); $this->assertTrue(strpos($code1, 'this->removeColumn')); $this->assertTrue(strpos($code1, 'this->addColumn')); $this->assertTrue(strpos($code1, 'this->changeColumn')); $code2 = file_get_contents($files[1]); $this->assertTrue(strpos($code2, 'this->dropForeignKey')); $this->assertTrue(strpos($code2, 'this->removeIndex')); $this->assertTrue(strpos($code2, 'this->addIndex')); $this->assertTrue(strpos($code2, 'this->createForeignKey')); Doctrine_Lib::removeDirectories($migrationsPath); } }
/* * JBoss, Home of Professional Open Source. * Copyright 2014 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * 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 io.undertow.server; /** * Connector level statistics * * * @author Stuart Douglas */ public interface ConnectorStatistics { /** * * @return The number of requests processed by this connector */ long getRequestCount(); /** * * @return The number of bytes sent on this connector */ long getBytesSent(); /** * * @return The number of bytes that have been received by this connector */ long getBytesReceived(); /** * * @return The number of requests that triggered an error (i.e. 500) response. */ long getErrorCount(); /** * * @return The total amount of time spent processing all requests on this connector * (nanoseconds) */ long getProcessingTime(); /** * * @return The time taken by the slowest request * (nanoseconds) */ long getMaxProcessingTime(); /** * Resets all values to zero */ void reset(); /** * * @return The current number of active connections */ long getActiveConnections(); /** * * @return The maximum number of active connections that have every been active on this connector */ long getMaxActiveConnections(); /** * * @return The current number of active requests */ long getActiveRequests(); /** * * @return The maximum number of active requests */ long getMaxActiveRequests(); }
// "Simplify boolean expression" "true" class A { public static void m(boolean fullSearch, boolean partialSearch) { if (!partialSearch) { return; } // comment String str = fullSearch ? "str1" : "str2 " + "str3"; } }
/* Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'elementspath', 'ca', { eleLabel: 'Ruta dels elements', eleTitle: '%1 element' } );
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.UnitTests.Emit; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen { public class CompoundAssignmentForDelegate : EmitMetadataTestBase { // The method to removal or concatenation with ‘optional’ parameter [Fact] public void OptionalParaInCompAssignOperator() { var text = @" delegate void MyDelegate1(int x, float y); class C { public void DelegatedMethod(int x, float y = 3.0f) { System.Console.WriteLine(y); } static void Main(string[] args) { C mc = new C(); MyDelegate1 md1 = null; md1 += mc.DelegatedMethod; md1(1, 5); md1 -= mc.DelegatedMethod; } } "; string expectedIL = @"{ // Code size 65 (0x41) .maxstack 4 .locals init (C V_0) //mc IL_0000: newobj ""C..ctor()"" IL_0005: stloc.0 IL_0006: ldnull IL_0007: ldloc.0 IL_0008: ldftn ""void C.DelegatedMethod(int, float)"" IL_000e: newobj ""MyDelegate1..ctor(object, System.IntPtr)"" IL_0013: call ""System.Delegate System.Delegate.Combine(System.Delegate, System.Delegate)"" IL_0018: castclass ""MyDelegate1"" IL_001d: dup IL_001e: ldc.i4.1 IL_001f: ldc.r4 5 IL_0024: callvirt ""void MyDelegate1.Invoke(int, float)"" IL_0029: ldloc.0 IL_002a: ldftn ""void C.DelegatedMethod(int, float)"" IL_0030: newobj ""MyDelegate1..ctor(object, System.IntPtr)"" IL_0035: call ""System.Delegate System.Delegate.Remove(System.Delegate, System.Delegate)"" IL_003a: castclass ""MyDelegate1"" IL_003f: pop IL_0040: ret } "; //var tree = SyntaxTree.ParseCompilationUnit(text); //var type = from item in ((CompilationUnitSyntax)tree.Root).Members where item as TypeDeclarationSyntax != null select item as TypeDeclarationSyntax; //var cla = type.First() as TypeDeclarationSyntax; //var method = from item in cla.Members where (MethodDeclarationSyntax)item != null select item as MethodDeclarationSyntax ; //var block = method.Last().Body; //var statement = block.Statements; CompileAndVerify(text, expectedOutput: "5").VerifyIL("C.Main", expectedIL); } // The object to removal or concatenation could be create a new instance of a method or an method name [Fact] public void ObjectOfCompAssignOperator() { var text = @" delegate void boo(); public class abc { public void bar() { System.Console.WriteLine(""bar""); } } class C { static void Main(string[] args) { abc p = new abc(); boo foo = null; foo += p.bar; foo += new boo(p.bar); foo(); foo -= p.bar; foo -= new boo(p.bar); } } "; var expectedOutput = @"bar bar"; CompileAndVerify(text, expectedOutput: expectedOutput); } // The object to removal or concatenation could be null [Fact] public void ObjectOfCompAssignOperatorIsNull() { var text = @" delegate void boo(); class C { static void Main(string[] args) { boo foo = null; foo += (boo)null; foo -= (boo)null; foo += null; foo -= null; } } "; var expectedIL = @"{ // Code size 47 (0x2f) .maxstack 2 IL_0000: ldnull IL_0001: ldnull IL_0002: call ""System.Delegate System.Delegate.Combine(System.Delegate, System.Delegate)"" IL_0007: castclass ""boo"" IL_000c: ldnull IL_000d: call ""System.Delegate System.Delegate.Remove(System.Delegate, System.Delegate)"" IL_0012: castclass ""boo"" IL_0017: ldnull IL_0018: call ""System.Delegate System.Delegate.Combine(System.Delegate, System.Delegate)"" IL_001d: castclass ""boo"" IL_0022: ldnull IL_0023: call ""System.Delegate System.Delegate.Remove(System.Delegate, System.Delegate)"" IL_0028: castclass ""boo"" IL_002d: pop IL_002e: ret }"; CompileAndVerify(text).VerifyIL("C.Main", expectedIL); } // The object to removal or concatenation could be an object of delegate [Fact] public void ObjectOfCompAssignOperatorIsObjectOfDelegate() { var text = @" using System; delegate void boo(); public class abc { public void bar() { System.Console.WriteLine(""bar""); } static public void far() { System.Console.WriteLine(""far""); } } class C { static void Main(string[] args) { abc p = new abc(); boo foo = null; boo foo1 = new boo(abc.far); foo += foo1; // Same type foo(); foo -= foo1; // Same type boo[] arrfoo = { p.bar, abc.far }; foo += (boo)Delegate.Combine(arrfoo); // OK foo += (boo)Delegate.Combine(foo, foo1); // OK foo(); } } "; var expectedOutput = @" far bar far bar far far"; CompileAndVerify(text, expectedOutput: expectedOutput); } [Fact] public void AnonymousMethodToRemovalOrConcatenation() { var text = @" using System; delegate void boo(int x); class C { static void Main() { boo foo = null; foo += delegate (int x) { System.Console.WriteLine(x); }; foo(10); Delegate[] del = foo.GetInvocationList(); foo -= (boo)del[0]; } } "; CompileAndVerify(text, expectedOutput: "10").VerifyIL("C.Main", @" { // Code size 77 (0x4d) .maxstack 3 .locals init (System.Delegate[] V_0) //del IL_0000: ldnull IL_0001: ldsfld ""boo C.<>c.<>9__0_0"" IL_0006: dup IL_0007: brtrue.s IL_0020 IL_0009: pop IL_000a: ldsfld ""C.<>c C.<>c.<>9"" IL_000f: ldftn ""void C.<>c.<Main>b__0_0(int)"" IL_0015: newobj ""boo..ctor(object, System.IntPtr)"" IL_001a: dup IL_001b: stsfld ""boo C.<>c.<>9__0_0"" IL_0020: call ""System.Delegate System.Delegate.Combine(System.Delegate, System.Delegate)"" IL_0025: castclass ""boo"" IL_002a: dup IL_002b: ldc.i4.s 10 IL_002d: callvirt ""void boo.Invoke(int)"" IL_0032: dup IL_0033: callvirt ""System.Delegate[] System.Delegate.GetInvocationList()"" IL_0038: stloc.0 IL_0039: ldloc.0 IL_003a: ldc.i4.0 IL_003b: ldelem.ref IL_003c: castclass ""boo"" IL_0041: call ""System.Delegate System.Delegate.Remove(System.Delegate, System.Delegate)"" IL_0046: castclass ""boo"" IL_004b: pop IL_004c: ret } "); } [Fact] public void LambdaMethodToRemovalOrConcatenation() { var text = @" using System; delegate void boo(string x); class C { static void Main() { boo foo = null; foo += (x) => { System.Console.WriteLine(x); }; foo(""Hello""); Delegate[] del = foo.GetInvocationList(); foo -= (boo)del[0]; } } "; CompileAndVerify(text, expectedOutput: "Hello").VerifyIL("C.Main()", @" { // Code size 80 (0x50) .maxstack 3 .locals init (System.Delegate[] V_0) //del IL_0000: ldnull IL_0001: ldsfld ""boo C.<>c.<>9__0_0"" IL_0006: dup IL_0007: brtrue.s IL_0020 IL_0009: pop IL_000a: ldsfld ""C.<>c C.<>c.<>9"" IL_000f: ldftn ""void C.<>c.<Main>b__0_0(string)"" IL_0015: newobj ""boo..ctor(object, System.IntPtr)"" IL_001a: dup IL_001b: stsfld ""boo C.<>c.<>9__0_0"" IL_0020: call ""System.Delegate System.Delegate.Combine(System.Delegate, System.Delegate)"" IL_0025: castclass ""boo"" IL_002a: dup IL_002b: ldstr ""Hello"" IL_0030: callvirt ""void boo.Invoke(string)"" IL_0035: dup IL_0036: callvirt ""System.Delegate[] System.Delegate.GetInvocationList()"" IL_003b: stloc.0 IL_003c: ldloc.0 IL_003d: ldc.i4.0 IL_003e: ldelem.ref IL_003f: castclass ""boo"" IL_0044: call ""System.Delegate System.Delegate.Remove(System.Delegate, System.Delegate)"" IL_0049: castclass ""boo"" IL_004e: pop IL_004f: ret } "); } // Mixed named method and Lambda expression to removal or concatenation [Fact] public void MixedNamedMethodAndLambdaToRemovalOrConcatenation() { var text = @" using System; delegate void boo(int x); class C { static public void far(int x) { Console.WriteLine(""far:{0}"", x); } static void Main(string[] args) { boo foo = far; foo += (x) => System.Console.WriteLine(""lambda:{0}"", x); foo(10); Delegate[] del = foo.GetInvocationList(); foo -= (boo)del[0]; foo(20); } } "; var expectedOutPut = @"far:10 lambda:10 lambda:20"; CompileAndVerify(text, expectedOutput: expectedOutPut); } // Mixed named method and Anonymous method to removal or concatenation [Fact] public void MixedNamedMethodAndAnonymousToRemovalOrConcatenation() { var text = @" using System; delegate void boo(int x); class C { static public void far(int x) { Console.WriteLine(""far:{0}"", x); } static void Main(string[] args) { boo foo = far; foo += delegate(int x) { System.Console.WriteLine(""Anonymous:{0}"", x); }; foo(10); Delegate[] del = foo.GetInvocationList(); foo -= (boo)del[0]; foo(20); } } "; var expectedOutPut = @"far:10 Anonymous:10 Anonymous:20"; CompileAndVerify(text, expectedOutput: expectedOutPut); } // Mixed Lambda expression and Anonymous method to removal or concatenation [Fact] public void MixedAnonymousAndLambdaToRemovalOrConcatenation() { var text = @" using System; delegate void boo(int x); class C { static public void far(int x) { Console.WriteLine(""far:{0}"", x); } static void Main(string[] args) { boo foo = far; foo += x => { System.Console.WriteLine(""Lambda:{0}"", x); }; foo += delegate(int x) { System.Console.WriteLine(""Anonymous:{0}"", x); }; foo(10); Delegate[] del = foo.GetInvocationList(); foo -= (boo)del[0]; foo(20); } } "; var expectedOutPut = @"far:10 Lambda:10 Anonymous:10 Lambda:20 Anonymous:20"; CompileAndVerify(text, expectedOutput: expectedOutPut); } // To removal or concatenation same method multi- times [Fact] public void RemoveSameMethodMultiTime() { var text = @" using System; delegate void D(ref int x); class C { public static void M1(ref int i) { Console.WriteLine(""M1: "" + i); i = 1; } public static void M2(ref int i) { Console.WriteLine(""M2: "" + i); i = 2; } static void Main(string[] args) { int i = 0; D cd1 = new D(M1); // M1 D cd2 = cd1; cd1 += M2; // M1,M2 cd1 += M1; // M1,M2,M1 cd1(ref i); cd1 -= cd2;// remove last M1 cd1(ref i); cd1 -= M1; // remove first M1 cd1(ref i); } } "; var expectedOutPut = @"M1: 0 M2: 1 M1: 2 M1: 1 M2: 1 M2: 2 "; CompileAndVerify(text, expectedOutput: expectedOutPut); } // Remove Non existed method [Fact] public void RemoveNotExistMethod() { var text = @" using System; delegate void D(ref int x); class C { public static void M1(ref int i) { Console.WriteLine(""M1: "" + i); i = 1; } public static void M2(ref int i) { Console.WriteLine(""M2: "" + i); i = 2; } static void Main(string[] args) { int i = 0; D cd1 = new D(M1); // M1 cd1 -= M2; // M1 cd1 -= M2; // M1 cd1(ref i); } } "; var expectedOutPut = @"M1: 0"; CompileAndVerify(text, expectedOutput: expectedOutPut); } // Removal and concatenation woks on both static and instance methods [Fact] public void RemovebothStaticAndInstanceMethod() { var text = @" delegate void boo(); public class abc { public void bar() { System.Console.WriteLine(""bar""); } static public void far() { System.Console.WriteLine(""far""); } } class C { static void Main(string[] args) { abc p = new abc(); boo foo = new boo(p.bar); foo(); foo -= p.bar; foo = new boo(abc.far); foo(); foo -= abc.far; foo += p.bar; foo += abc.far; foo(); } } "; var expectedOutPut = @"bar far bar far"; CompileAndVerify(text, expectedOutput: expectedOutPut); } // Removal or concatenation for the delegate that is member of classes [Fact] public void RemoveDelegateIsMemberOfClass() { var text = @" public delegate void boo(); public class abc { public void bar() { System.Console.WriteLine(""bar""); } static public void far() { System.Console.WriteLine(""far""); } public boo foo = null; } class C { static void Main(string[] args) { abc p = new abc(); p.foo = null; p.foo += abc.far; p.foo += p.bar; p.foo(); p.foo -= abc.far; p.foo -= p.bar; } } "; var expectedOutPut = @"far bar "; CompileAndVerify(text, expectedOutput: expectedOutPut); } // Removal or concatenation for the delegate works on ternary operator [Fact] public void CompAssignWorksOnTernaryOperator() { var text = @" delegate void boo(); public class abc { public void bar() { System.Console.WriteLine(""bar""); } static public void far() { System.Console.WriteLine(""far""); } } class C { static void Main(string[] args) { abc p = new abc(); boo foo = null; foo += loo() ? new boo(p.bar) : new boo(abc.far); foo(); foo -= loo() ? new boo(p.bar) : new boo(abc.far); boo left = null; boo right = null; foo = !loo() ? left += new boo(abc.far) : right += new boo(p.bar); foo(); foo = !loo() ? left -= new boo(abc.far) : right -= new boo(p.bar); } private static bool loo() { return true; } } "; var expectedOutPut = @"bar bar "; CompileAndVerify(text, expectedOutput: expectedOutPut); } // Removal or concatenation for the delegate that with 9 args [Fact] public void DelegateWithNineArgs() { var text = @" delegate void boo(out int i, double d, ref float f, string s, char c, decimal dc, C client, byte b, short sh); class C { public static void Hello(out int i, double d, ref float f, string s, char c, decimal dc, C client, byte b, short sh) { i = 1; System.Console.WriteLine(""Hello""); } static void Main(string[] args) { boo foo = null; foo += new boo(C.Hello); int i = 1; float ff = 0; foo(out i, 5.5, ref ff, ""a string"", 'C', 0.555m, new C(), 3, 16); } } "; var expectedOutPut = @"Hello "; CompileAndVerify(text, expectedOutput: expectedOutPut); } // Removal or concatenation for the delegate that is virtual struct methods [WorkItem(539908, "DevDiv")] [Fact] public void DelegateWithStructMethods() { var text = @" delegate int boo(); interface I { int bar(); } public struct abc : I { public int bar() { System.Console.WriteLine(""bar""); return 0x01; } } class C { static void Main(string[] args) { abc p = new abc(); boo foo = null; foo += new boo(p.bar); foo(); } } "; var expectedOutPut = @"bar "; var expectedIL = @" { // Code size 44 (0x2c) .maxstack 3 .locals init (abc V_0) //p IL_0000: ldloca.s V_0 IL_0002: initobj ""abc"" IL_0008: ldnull IL_0009: ldloc.0 IL_000a: box ""abc"" IL_000f: dup IL_0010: ldvirtftn ""int abc.bar()"" IL_0016: newobj ""boo..ctor(object, System.IntPtr)"" IL_001b: call ""System.Delegate System.Delegate.Combine(System.Delegate, System.Delegate)"" IL_0020: castclass ""boo"" IL_0025: callvirt ""int boo.Invoke()"" IL_002a: pop IL_002b: ret } "; CompileAndVerify(text, expectedOutput: expectedOutPut).VerifyIL("C.Main", expectedIL); } // Removal or concatenation for the delegate that the method is in base class [Fact] public void AddMethodThatInBaseClass() { var text = @" delegate double MyDelegate(int integerPortion, float fraction); public class BaseClass { public delegate void MyDelegate(); public void DelegatedMethod() { System.Console.WriteLine(""Base""); } } public class DerivedClass : BaseClass { new public delegate void MyDelegate(); public new void DelegatedMethod() { System.Console.WriteLine(""Derived""); } static void Main(string[] args) { DerivedClass derived = new DerivedClass(); BaseClass baseCls = new BaseClass(); MyDelegate derivedDel = new MyDelegate(derived.DelegatedMethod); derivedDel += baseCls.DelegatedMethod; derivedDel(); BaseClass.MyDelegate BaseDel = new BaseClass.MyDelegate(((BaseClass)derived).DelegatedMethod); BaseDel += derived.DelegatedMethod; BaseDel(); } } "; var expectedOutPut = @"Derived Base Base Derived "; CompileAndVerify(text, expectedOutput: expectedOutPut); } // delegate-in-a-generic-class (C<t>.foo(…)) += methodgroup-in-a-generic-class (C<T>.bar(…)) [Fact] public void CompAssignOperatorForGenericClass() { var text = @" delegate void boo(short x); class C<T> { public void bar(short x) { System.Console.WriteLine(""bar""); } public static void far(T x) { System.Console.WriteLine(""far""); } public static void par<U>(U x) { System.Console.WriteLine(""par""); } public static boo foo = null; } class D { static void Main(string[] args) { C<long> p = new C<long>(); C<long>.foo += p.bar; C<short>.foo += C<short>.far; C<long>.foo += C<long>.par<short>; C<long>.foo(short.MaxValue); C<short>.foo(short.MaxValue); } } "; var expectedOutPut = @"bar par far "; CompileAndVerify(text, expectedOutput: expectedOutPut); } // Compound assignment for the method with derived return type [Fact] public void CompAssignOperatorForInherit01() { var text = @" delegate BaseClass MyBaseDelegate(BaseClass x); delegate DerivedClass MyDerivedDelegate(DerivedClass x); public class BaseClass { public static BaseClass DelegatedMethod(BaseClass x) { System.Console.WriteLine(""Base""); return x; } } public class DerivedClass : BaseClass { public static DerivedClass DelegatedMethod(DerivedClass x) { System.Console.WriteLine(""Derived""); return x; } static void Main(string[] args) { MyBaseDelegate foo = null; foo += BaseClass.DelegatedMethod; foo += DerivedClass.DelegatedMethod; foo(new BaseClass()); foo(new DerivedClass()); MyDerivedDelegate foo1 = null; //foo1 += BaseClass.DelegatedMethod; foo1 += DerivedClass.DelegatedMethod; foo1(new DerivedClass()); } } "; var expectedOutPut = @"Base Base Base Base Derived "; CompileAndVerify(text, expectedOutput: expectedOutPut); } // Compound assignment for the method with derived return type [Fact] public void CompAssignOperatorForInherit02() { var text = @" delegate T MyDelegate<T>(T x); public class BaseClass { public static BaseClass DelegatedMethod(BaseClass x) { System.Console.WriteLine(""Base1""); return x; } public static DerivedClass DelegatedMethod(DerivedClass x) { System.Console.WriteLine(""Base2""); return x; } } public class DerivedClass : BaseClass { public static new DerivedClass DelegatedMethod(DerivedClass x) { System.Console.WriteLine(""Derived1""); return x; } public static new BaseClass DelegatedMethod(BaseClass x) { System.Console.WriteLine(""Derived2""); return x; } static void Main(string[] args) { MyDelegate<BaseClass> foo = null; foo += BaseClass.DelegatedMethod; foo += DerivedClass.DelegatedMethod; foo(new BaseClass()); foo(new DerivedClass()); MyDelegate<DerivedClass> foo1 = null; foo1 += BaseClass.DelegatedMethod; foo1 += DerivedClass.DelegatedMethod; //foo1(new BaseClass()); foo1(new DerivedClass()); } } "; var expectedOutPut = @"Base1 Derived2 Base1 Derived2 Base2 Derived1 "; CompileAndVerify(text, expectedOutput: expectedOutPut); } // Compound assignment for the method with derived return type [WorkItem(539927, "DevDiv")] [Fact] public void CompAssignOperatorForInherit03() { var text = @" delegate T MyDelegate<T>(T x); public class BaseClass { public static T DelegatedMethod<T>(T x) { System.Console.WriteLine(""Base""); return x; } public static double DelegatedMethod(double x) { System.Console.WriteLine(""double""); return x; } } public class DerivedClass : BaseClass { public static new T DelegatedMethod<T>(T x) { System.Console.WriteLine(""Derived""); return x; } static void Main(string[] args) { MyDelegate<BaseClass> foo = null; foo += BaseClass.DelegatedMethod; foo += DerivedClass.DelegatedMethod; foo(new BaseClass()); foo(new DerivedClass()); MyDelegate<DerivedClass> foo1 = null; foo1 += BaseClass.DelegatedMethod; foo1 += DerivedClass.DelegatedMethod; //foo1(new BaseClass()); foo1(new DerivedClass()); MyDelegate<double> foo2 = null; foo2 += BaseClass.DelegatedMethod<double>; foo2 += BaseClass.DelegatedMethod; foo2 += DerivedClass.DelegatedMethod; foo2(2); } } "; var expectedOutPut = @"Base Derived Base Derived Base Derived Base double Derived "; CompileAndVerify(text, expectedOutput: expectedOutPut); } // Compound assignment for the method with derived return type [WorkItem(539927, "DevDiv")] [Fact] public void CompAssignOperatorForInherit04() { var text = @" delegate double MyDelegate(double x); public class BaseClass { public static T DelegatedMethod<T>(T x) { System.Console.WriteLine(""Base""); return x; } public static double DelegatedMethod(double x) { System.Console.WriteLine(""double""); return x; } } public class DerivedClass : BaseClass { public static new T DelegatedMethod<T>(T x) { System.Console.WriteLine(""Derived""); return x; } static void Main(string[] args) { MyDelegate foo = null; foo += BaseClass.DelegatedMethod<double>; foo += BaseClass.DelegatedMethod; foo += DerivedClass.DelegatedMethod; MyDelegate foo1 = null; foo1 += foo; foo += foo1; foo(1); foo1(1); } } "; var expectedOutPut = @"Base double Derived Base double Derived Base double Derived "; CompileAndVerify(text, expectedOutput: expectedOutPut); } } }
var colors = require('../safe'); console.log(colors.yellow('First some yellow text')); console.log(colors.yellow.underline('Underline that text')); console.log(colors.red.bold('Make it bold and red')); console.log(colors.rainbow('Double Raindows All Day Long')); console.log(colors.trap('Drop the bass')); console.log(colors.rainbow(colors.trap('DROP THE RAINBOW BASS'))); // styles not widely supported console.log(colors.bold.italic.underline.red('Chains are also cool.')); // styles not widely supported console.log(colors.green('So ') + colors.underline('are') + ' ' + colors.inverse('inverse') + colors.yellow.bold(' styles! ')); console.log(colors.zebra('Zebras are so fun!')); console.log('This is ' + colors.strikethrough('not') + ' fun.'); console.log(colors.black.bgWhite('Background color attack!')); console.log(colors.random('Use random styles on everything!')); console.log(colors.america('America, Heck Yeah!')); console.log(colors.brightCyan('Blindingly ') + colors.brightRed('bright? ') + colors.brightYellow('Why ') + colors.brightGreen('not?!')); console.log('Setting themes is useful'); // // Custom themes // // console.log('Generic logging theme as JSON'.green.bold.underline); // Load theme with JSON literal colors.setTheme({ silly: 'rainbow', input: 'blue', verbose: 'cyan', prompt: 'grey', info: 'green', data: 'grey', help: 'cyan', warn: 'yellow', debug: 'blue', error: 'red', }); // outputs red text console.log(colors.error('this is an error')); // outputs yellow text console.log(colors.warn('this is a warning')); // outputs blue text console.log(colors.input('this is an input')); // console.log('Generic logging theme as file'.green.bold.underline); // Load a theme from file colors.setTheme(require(__dirname + '/../themes/generic-logging.js')); // outputs red text console.log(colors.error('this is an error')); // outputs yellow text console.log(colors.warn('this is a warning')); // outputs grey text console.log(colors.input('this is an input')); // console.log(colors.zalgo("Don't summon him"))
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use zed::bar; use zed::baz; //~ ERROR unresolved import `zed::baz` [E0432] //~^ no `baz` in `zed`. Did you mean to use `bar`? mod zed { pub fn bar() { println!("bar"); } use foo; //~ ERROR unresolved import `foo` [E0432] //~^ no `foo` in the root } fn main() { zed::foo(); //~ ERROR `foo` is private bar(); }
/* * Jitsi, the OpenSource Java VoIP and Instant Messaging client. * * Copyright @ 2015 Atlassian Pty Ltd * * 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 net.java.sip.communicator.impl.protocol.icq; import java.util.*; import net.java.sip.communicator.service.protocol.*; import org.osgi.framework.*; /** * The ICQ implementation of the ProtocolProviderFactory. * @author Emil Ivov */ public class ProtocolProviderFactoryIcqImpl extends ProtocolProviderFactory { /** * Is this factory is created for aim or icq accounts */ private boolean isAimFactory = false; /** * Creates an instance of the ProtocolProviderFactoryIcqImpl. * @param isAimFactory whether its an aim factory */ protected ProtocolProviderFactoryIcqImpl(boolean isAimFactory) { super(IcqActivator.getBundleContext(), isAimFactory ? ProtocolNames.AIM : ProtocolNames.ICQ); this.isAimFactory = isAimFactory; } /** * Initializes and creates an account corresponding to the specified * accountProperties and registers the resulting ProtocolProvider in the * <tt>context</tt> BundleContext parameter. This method has a persistent * effect. Once created the resulting account will remain installed until * removed through the uninstall account method. * * @param userIDStr the user identifier for the new account * @param accountProperties a set of protocol (or implementation) * specific properties defining the new account. * @return the AccountID of the newly created account */ @Override public AccountID installAccount( String userIDStr, Map<String, String> accountProperties) { BundleContext context = IcqActivator.getBundleContext(); if (context == null) throw new NullPointerException("The specified BundleContext was null"); if (userIDStr == null) throw new NullPointerException("The specified AccountID was null"); if (accountProperties == null) throw new NullPointerException("The specified property map was null"); accountProperties.put(USER_ID, userIDStr); // we are installing new aim account from the wizzard, so mark it as aim if(isAimFactory) accountProperties.put(IcqAccountID.IS_AIM, "true"); AccountID accountID = new IcqAccountID(userIDStr, accountProperties); //make sure we haven't seen this account id before. if( registeredAccounts.containsKey(accountID) ) throw new IllegalStateException( "An account for id " + userIDStr + " was already installed!"); //first store the account and only then load it as the load generates //an osgi event, the osgi event triggers (through the UI) a call to //the register() method and it needs to access the configuration service //and check for a password. this.storeAccount(accountID, false); accountID = loadAccount(accountProperties); return accountID; } /** * Initializes and creates an account corresponding to the specified * accountProperties and registers the resulting ProtocolProvider in the * <tt>context</tt> BundleContext parameter. * * @param accountProperties a set of protocol (or implementation) specific * properties defining the new account. * @return the AccountID of the newly created account */ @Override public AccountID loadAccount(Map<String, String> accountProperties) { // there are two factories - one for icq accounts and one for aim ones. // if we are trying to load an icq account in aim factory - skip it // and the same for aim accounts in icq factory boolean accountPropertiesIsAIM = IcqAccountID.isAIM(accountProperties); if ((accountPropertiesIsAIM && !isAimFactory) || (!accountPropertiesIsAIM && isAimFactory)) { return null; } return super.loadAccount(accountProperties); } /** * Creates a protocol provider for the given <tt>accountID</tt> and * registers it in the bundle context. This method has a persistent * effect. Once created the resulting account will remain installed until * removed through the uninstallAccount method. * * @param accountID the account identifier * @return <tt>true</tt> if the account with the given <tt>accountID</tt> is * successfully loaded, otherwise returns <tt>false</tt> */ @Override public boolean loadAccount(AccountID accountID) { // there are two factories - one for icq accounts and one for aim ones. // if we are trying to load an icq account in aim factory - skip it // and the same for aim accounts in icq factory boolean accountPropertiesIsAIM = IcqAccountID.isAIM(accountID.getAccountProperties()); if ((accountPropertiesIsAIM && !isAimFactory) || (!accountPropertiesIsAIM && isAimFactory)) { return false; } return super.loadAccount(accountID); } /** * Initializes and creates an account corresponding to the specified * accountProperties. * * @param accountProperties a set of protocol (or implementation) specific * properties defining the new account. * @return the AccountID of the newly created account */ @Override public AccountID createAccount(Map<String, String> accountProperties) { // there are two factories - one for icq accounts and one for aim ones. // if we are trying to load an icq account in aim factory - skip it // and the same for aim accounts in icq factory boolean accountPropertiesIsAIM = IcqAccountID.isAIM(accountProperties); if ((accountPropertiesIsAIM && !isAimFactory) || (!accountPropertiesIsAIM && isAimFactory)) { return null; } return super.createAccount(accountProperties); } @Override protected AccountID createAccountID(String userID, Map<String, String> accountProperties) { return new IcqAccountID(userID, accountProperties); } @Override protected ProtocolProviderService createService(String userID, AccountID accountID) { ProtocolProviderServiceIcqImpl service = new ProtocolProviderServiceIcqImpl(); service.initialize(userID, accountID); return service; } @Override public void modifyAccount( ProtocolProviderService protocolProvider, Map<String, String> accountProperties) throws NullPointerException { // Make sure the specified arguments are valid. if (protocolProvider == null) throw new NullPointerException( "The specified Protocol Provider was null"); if (accountProperties == null) throw new NullPointerException( "The specified property map was null"); BundleContext context = IcqActivator.getBundleContext(); if (context == null) throw new NullPointerException( "The specified BundleContext was null"); IcqAccountID accountID = (IcqAccountID) protocolProvider.getAccountID(); // If the given accountID doesn't correspond to an existing account // we return. if(!registeredAccounts.containsKey(accountID)) return; ServiceRegistration registration = registeredAccounts.get(accountID); // kill the service if (registration != null) registration.unregister(); accountProperties.put(USER_ID, accountID.getUserID()); if (!accountProperties.containsKey(PROTOCOL)) accountProperties.put(PROTOCOL, ProtocolNames.ICQ); accountID.setAccountProperties(accountProperties); // First store the account and only then load it as the load generates // an osgi event, the osgi event triggers (trhgough the UI) a call to // the register() method and it needs to acces the configuration service // and check for a password. this.storeAccount(accountID); Hashtable<String, String> properties = new Hashtable<String, String>(); properties.put(PROTOCOL, ProtocolNames.ICQ); properties.put(USER_ID, accountID.getUserID()); ((ProtocolProviderServiceIcqImpl) protocolProvider) .initialize(accountID.getUserID(), accountID); // We store again the account in order to store all properties added // during the protocol provider initialization. this.storeAccount(accountID); registration = context.registerService( ProtocolProviderService.class.getName(), protocolProvider, properties); registeredAccounts.put(accountID, registration); } }
/* * Copyright 2008-2013 NVIDIA Corporation * * 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. */ #pragma once #include <thrust/detail/config.h> #include <thrust/iterator/iterator_traits.h> namespace thrust { namespace system { namespace detail { namespace generic { template<typename InputIterator> inline __host__ __device__ typename thrust::iterator_traits<InputIterator>::difference_type distance(InputIterator first, InputIterator last); } // end namespace generic } // end namespace detail } // end namespace system } // end namespace thrust #include <thrust/system/detail/generic/distance.inl>
INSERT INTO SAM_TYPE_T (TYPEID ,AUTHORITY ,DOMAIN, KEYWORD, DESCRIPTION, STATUS, CREATEDBY, CREATEDDATE, LASTMODIFIEDBY, LASTMODIFIEDDATE ) VALUES (1 , 'stanford.edu' ,'assessment.item' ,'Multiple Choice' ,NULL ,1 ,'1' , '2005-01-01 12:00:00','1' ,'2005-01-01 12:00:00') ; INSERT INTO SAM_TYPE_T (TYPEID ,AUTHORITY ,DOMAIN, KEYWORD, DESCRIPTION, STATUS, CREATEDBY, CREATEDDATE, LASTMODIFIEDBY, LASTMODIFIEDDATE ) VALUES (2 , 'stanford.edu' ,'assessment.item' ,'Multiple Correct' ,NULL ,1 ,'1' , '2005-01-01 12:00:00','1' ,'2005-01-01 12:00:00') ; INSERT INTO SAM_TYPE_T (TYPEID ,AUTHORITY ,DOMAIN, KEYWORD, DESCRIPTION, STATUS, CREATEDBY, CREATEDDATE, LASTMODIFIEDBY, LASTMODIFIEDDATE ) VALUES (3 , 'stanford.edu' ,'assessment.item' ,'Multiple Choice Survey' ,NULL ,1 ,'1' , '2005-01-01 12:00:00','1' ,'2005-01-01 12:00:00') ; INSERT INTO SAM_TYPE_T (TYPEID ,AUTHORITY ,DOMAIN, KEYWORD, DESCRIPTION, STATUS, CREATEDBY, CREATEDDATE, LASTMODIFIEDBY, LASTMODIFIEDDATE ) VALUES (4 , 'stanford.edu' ,'assessment.item' ,'True - False' ,NULL ,1 ,'1' , '2005-01-01 12:00:00','1' ,'2005-01-01 12:00:00') ; INSERT INTO SAM_TYPE_T (TYPEID ,AUTHORITY ,DOMAIN, KEYWORD, DESCRIPTION, STATUS, CREATEDBY, CREATEDDATE, LASTMODIFIEDBY, LASTMODIFIEDDATE ) VALUES (5 , 'stanford.edu' ,'assessment.item' ,'Short Answer/Essay' ,NULL ,1 ,'1' , '2005-01-01 12:00:00','1' ,'2005-01-01 12:00:00') ; INSERT INTO SAM_TYPE_T (TYPEID ,AUTHORITY ,DOMAIN, KEYWORD, DESCRIPTION, STATUS, CREATEDBY, CREATEDDATE, LASTMODIFIEDBY, LASTMODIFIEDDATE ) VALUES (6 , 'stanford.edu' ,'assessment.item' ,'File Upload' ,NULL ,1 ,'1' , '2005-01-01 12:00:00','1' ,'2005-01-01 12:00:00') ; INSERT INTO SAM_TYPE_T (TYPEID ,AUTHORITY ,DOMAIN, KEYWORD, DESCRIPTION, STATUS, CREATEDBY, CREATEDDATE, LASTMODIFIEDBY, LASTMODIFIEDDATE ) VALUES (7 , 'stanford.edu' ,'assessment.item' ,'Audio Recording' ,NULL ,1 ,'1', '2005-01-01 12:00:00','1' ,'2005-01-01 12:00:00') ; INSERT INTO SAM_TYPE_T (TYPEID ,AUTHORITY ,DOMAIN, KEYWORD, DESCRIPTION, STATUS, CREATEDBY, CREATEDDATE, LASTMODIFIEDBY, LASTMODIFIEDDATE ) VALUES (8 , 'stanford.edu' ,'assessment.item' ,'Fill in Blank' ,NULL ,1 ,'1', '2005-01-01 12:00:00','1' ,'2005-01-01 12:00:00') ; INSERT INTO SAM_TYPE_T (TYPEID ,AUTHORITY ,DOMAIN, KEYWORD, DESCRIPTION, STATUS, CREATEDBY, CREATEDDATE, LASTMODIFIEDBY, LASTMODIFIEDDATE ) VALUES (9 , 'stanford.edu' ,'assessment.item' ,'Matching' ,NULL ,1 ,'1', '2005-01-01 12:00:00','1' ,'2005-01-01 12:00:00') ; INSERT INTO SAM_TYPE_T (TYPEID ,AUTHORITY ,DOMAIN, KEYWORD, DESCRIPTION, STATUS, CREATEDBY, CREATEDDATE, LASTMODIFIEDBY, LASTMODIFIEDDATE ) VALUES (11 , 'stanford.edu' ,'assessment.item' ,'Numeric Response' ,NULL ,1 ,'1' , '2005-01-01 12:00:00','1' ,'2005-01-01 12:00:00') ; INSERT INTO SAM_TYPE_T (TYPEID ,AUTHORITY ,DOMAIN, KEYWORD, DESCRIPTION, STATUS, CREATEDBY, CREATEDDATE, LASTMODIFIEDBY, LASTMODIFIEDDATE ) VALUES (13 , 'stanford.edu' ,'assessment.item' ,'Matrix Choices Survey' ,NULL ,1 ,'1' , '2005-01-01 12:00:00','1' ,'2005-01-01 12:00:00') ; INSERT INTO SAM_TYPE_T (TYPEID ,AUTHORITY ,DOMAIN, KEYWORD, DESCRIPTION, STATUS, CREATEDBY, CREATEDDATE, LASTMODIFIEDBY, LASTMODIFIEDDATE ) VALUES (14 , 'stanford.edu' ,'assessment.item' ,'Extended Matching_Items' ,NULL ,1 ,'1' , '2005-01-01 12:00:00','1' ,'2005-01-01 12:00:00') ; INSERT INTO SAM_TYPE_T (TYPEID ,AUTHORITY ,DOMAIN, KEYWORD, DESCRIPTION, STATUS, CREATEDBY, CREATEDDATE, LASTMODIFIEDBY, LASTMODIFIEDDATE ) VALUES (21 , 'stanford.edu' ,'assessment.section' ,'Default' ,NULL ,1 ,'1', '2005-01-01 12:00:00','1' ,'2005-01-01 12:00:00') ; INSERT INTO SAM_TYPE_T (TYPEID ,AUTHORITY ,DOMAIN, KEYWORD, DESCRIPTION, STATUS, CREATEDBY, CREATEDDATE, LASTMODIFIEDBY, LASTMODIFIEDDATE ) VALUES (22 , 'stanford.edu' ,'assessment.section' ,'Normal' ,NULL ,1 ,'1', '2005-01-01 12:00:00','1' ,'2005-01-01 12:00:00') ; INSERT INTO SAM_TYPE_T (TYPEID ,AUTHORITY ,DOMAIN, KEYWORD, DESCRIPTION, STATUS, CREATEDBY, CREATEDDATE, LASTMODIFIEDBY, LASTMODIFIEDDATE ) VALUES (41 , 'stanford.edu' ,'assessment.template' ,'Quiz' ,NULL ,1 ,'1', '2005-01-01 12:00:00','1' ,'2005-01-01 12:00:00') ; INSERT INTO SAM_TYPE_T (TYPEID ,AUTHORITY ,DOMAIN, KEYWORD, DESCRIPTION, STATUS, CREATEDBY, CREATEDDATE, LASTMODIFIEDBY, LASTMODIFIEDDATE ) VALUES (42 , 'stanford.edu' ,'assessment.template' ,'Homework' ,NULL ,1 ,'1', '2005-01-01 12:00:00','1' ,'2005-01-01 12:00:00') ; INSERT INTO SAM_TYPE_T (TYPEID ,AUTHORITY ,DOMAIN, KEYWORD, DESCRIPTION, STATUS, CREATEDBY, CREATEDDATE, LASTMODIFIEDBY, LASTMODIFIEDDATE ) VALUES (43 , 'stanford.edu' ,'assessment.template' ,'Mid Term' ,NULL ,1 ,'1', '2005-01-01 12:00:00','1' ,'2005-01-01 12:00:00') ; INSERT INTO SAM_TYPE_T (TYPEID ,AUTHORITY ,DOMAIN, KEYWORD, DESCRIPTION, STATUS, CREATEDBY, CREATEDDATE, LASTMODIFIEDBY, LASTMODIFIEDDATE ) VALUES (44 , 'stanford.edu' ,'assessment.template' ,'Final' ,NULL ,1 ,'1', '2005-01-01 12:00:00','1' ,'2005-01-01 12:00:00') ; INSERT INTO SAM_TYPE_T (TYPEID ,AUTHORITY ,DOMAIN, KEYWORD, DESCRIPTION, STATUS, CREATEDBY, CREATEDDATE, LASTMODIFIEDBY, LASTMODIFIEDDATE ) VALUES (61 , 'stanford.edu' ,'assessment' ,'Quiz' ,NULL ,1 ,'1', '2005-01-01 12:00:00','1' ,'2005-01-01 12:00:00') ; INSERT INTO SAM_TYPE_T (TYPEID ,AUTHORITY ,DOMAIN, KEYWORD, DESCRIPTION, STATUS, CREATEDBY, CREATEDDATE, LASTMODIFIEDBY, LASTMODIFIEDDATE ) VALUES (62 , 'stanford.edu' ,'assessment' ,'Homework' ,NULL ,1 ,'1', '2005-01-01 12:00:00','1' ,'2005-01-01 12:00:00') ; INSERT INTO SAM_TYPE_T (TYPEID ,AUTHORITY ,DOMAIN, KEYWORD, DESCRIPTION, STATUS, CREATEDBY, CREATEDDATE, LASTMODIFIEDBY, LASTMODIFIEDDATE ) VALUES (63 , 'stanford.edu' ,'assessment' ,'Mid Term' ,NULL ,1 ,'1', '2005-01-01 12:00:00','1' ,'2005-01-01 12:00:00') ; INSERT INTO SAM_TYPE_T (TYPEID ,AUTHORITY ,DOMAIN, KEYWORD, DESCRIPTION, STATUS, CREATEDBY, CREATEDDATE, LASTMODIFIEDBY, LASTMODIFIEDDATE ) VALUES (64 , 'stanford.edu' ,'assessment' ,'Final' ,NULL ,1 ,'1', '2005-01-01 12:00:00','1' ,'2005-01-01 12:00:00') ; INSERT INTO SAM_TYPE_T (TYPEID ,AUTHORITY ,DOMAIN, KEYWORD, DESCRIPTION, STATUS, CREATEDBY, CREATEDDATE, LASTMODIFIEDBY, LASTMODIFIEDDATE ) VALUES (0 , 'stanford.edu' ,'assessment.questionpool' ,'Default' , 'Stanford Question Pool',1 ,'1' , '2005-01-01 12:00:00','1' ,'2005-01-01 12:00:00') ; INSERT INTO SAM_TYPE_T (TYPEID ,AUTHORITY ,DOMAIN, KEYWORD, DESCRIPTION, STATUS, CREATEDBY, CREATEDDATE, LASTMODIFIEDBY, LASTMODIFIEDDATE ) VALUES (30 , 'stanford.edu' ,'assessment.questionpool.access' ,'Access Denied' , 'Access Denied',1 ,'1' , '2005-01-01 12:00:00','1' ,'2005-01-01 12:00:00') ; INSERT INTO SAM_TYPE_T (TYPEID ,AUTHORITY ,DOMAIN, KEYWORD, DESCRIPTION, STATUS, CREATEDBY, CREATEDDATE, LASTMODIFIEDBY, LASTMODIFIEDDATE ) VALUES (31 , 'stanford.edu' ,'assessment.questionpool.access' ,'Read Only' , 'Read Only',1 ,'1' , '2005-01-01 12:00:00','1' ,'2005-01-01 12:00:00') ; INSERT INTO SAM_TYPE_T (TYPEID ,AUTHORITY ,DOMAIN, KEYWORD, DESCRIPTION, STATUS, CREATEDBY, CREATEDDATE, LASTMODIFIEDBY, LASTMODIFIEDDATE ) VALUES (32 , 'stanford.edu' ,'assessment.questionpool.access' ,'Read and Copy' , 'Read and Copy',1 ,'1' , '2005-01-01 12:00:00','1' ,'2005-01-01 12:00:00') ; INSERT INTO SAM_TYPE_T (TYPEID ,AUTHORITY ,DOMAIN, KEYWORD, DESCRIPTION, STATUS, CREATEDBY, CREATEDDATE, LASTMODIFIEDBY, LASTMODIFIEDDATE ) VALUES (33 , 'stanford.edu' ,'assessment.questionpool.access' ,'Read/Write' , 'Read/Write',1 ,'1' , '2005-01-01 12:00:00','1' ,'2005-01-01 12:00:00') ; INSERT INTO SAM_TYPE_T (TYPEID ,AUTHORITY ,DOMAIN, KEYWORD, DESCRIPTION, STATUS, CREATEDBY, CREATEDDATE, LASTMODIFIEDBY, LASTMODIFIEDDATE ) VALUES (34 , 'stanford.edu' ,'assessment.questionpool.access' ,'Administration' , 'Adminstration',1 ,'1' , '2005-01-01 12:00:00','1' ,'2005-01-01 12:00:00') ; INSERT INTO SAM_TYPE_T (TYPEID ,AUTHORITY ,DOMAIN, KEYWORD, DESCRIPTION, STATUS, CREATEDBY, CREATEDDATE, LASTMODIFIEDBY, LASTMODIFIEDDATE ) VALUES (81 , 'stanford.edu' ,'assessment.taking' ,'Taking Assessment' , 'Taking Assessment',1 ,'1' , '2005-01-01 12:00:00','1' ,'2005-01-01 12:00:00') ; INSERT INTO SAM_TYPE_T (TYPEID ,AUTHORITY ,DOMAIN, KEYWORD, DESCRIPTION, STATUS, CREATEDBY, CREATEDDATE, LASTMODIFIEDBY, LASTMODIFIEDDATE ) VALUES (101 , 'stanford.edu' ,'assessment.published' ,'A Published Assessment' , 'A Published Assessment',1 ,'1' , '2005-01-01 12:00:00','1' ,'2005-01-01 12:00:00') ; INSERT INTO SAM_TYPE_T (TYPEID ,AUTHORITY ,DOMAIN, KEYWORD, DESCRIPTION, STATUS, CREATEDBY, CREATEDDATE, LASTMODIFIEDBY, LASTMODIFIEDDATE ) VALUES (142 , 'stanford.edu' ,'assessment.template.system' ,'System Defined' ,NULL ,1 ,'1', '2006-01-01 12:00:00','1' ,'2005-06-01 12:00:00') ; ALTER TABLE SAM_TYPE_T ALTER COLUMN TYPEID RESTART WITH 143 ; INSERT INTO SAM_ASSESSMENTBASE_T (ID ,ISTEMPLATE , PARENTID ,TITLE ,DESCRIPTION ,COMMENTS, ASSESSMENTTEMPLATEID, TYPEID, INSTRUCTORNOTIFICATION, TESTEENOTIFICATION , MULTIPARTALLOWED, STATUS, CREATEDBY, CREATEDDATE, LASTMODIFIEDBY, LASTMODIFIEDDATE ) VALUES (1,'1' ,0 ,'Default Assessment Type' ,'System Defined Assessment Type' ,'comments' , NULL ,142 ,1 ,1 ,1 ,1 ,'admin' ,'2005-01-01 12:00:00' ,'admin' ,'2005-01-01 12:00:00' ) ; ALTER TABLE SAM_ASSESSMENTBASE_T ALTER COLUMN ID RESTART WITH 2 ; INSERT INTO SAM_ASSESSEVALUATION_T (ASSESSMENTID, EVALUATIONCOMPONENTS, SCORINGTYPE, NUMERICMODELID, FIXEDTOTALSCORE, GRADEAVAILABLE, ISSTUDENTIDPUBLIC, ANONYMOUSGRADING, AUTOSCORING,TOGRADEBOOK) VALUES (1 ,'' ,1 ,'' , NULL , NULL , NULL ,2 , NULL ,'2' ) ; INSERT INTO SAM_ASSESSFEEDBACK_T (ASSESSMENTID, FEEDBACKDELIVERY, FEEDBACKAUTHORING, SHOWQUESTIONTEXT, SHOWSTUDENTRESPONSE, SHOWCORRECTRESPONSE, SHOWSTUDENTSCORE, SHOWSTUDENTQUESTIONSCORE, SHOWQUESTIONLEVELFEEDBACK, SHOWSELECTIONLEVELFEEDBACK, SHOWGRADERCOMMENTS, SHOWSTATISTICS, EDITCOMPONENTS, FEEDBACKCOMPONENTOPTION) VALUES (1 ,1 ,1, 1 ,1 ,1 ,1 ,1 ,1 ,1 ,1 ,1 ,1 ,2 ) ; INSERT INTO SAM_ASSESSACCESSCONTROL_T (ASSESSMENTID, SUBMISSIONSALLOWED, SUBMISSIONSSAVED, ASSESSMENTFORMAT, BOOKMARKINGITEM, TIMELIMIT, TIMEDASSESSMENT, RETRYALLOWED, LATEHANDLING, STARTDATE, DUEDATE, SCOREDATE, FEEDBACKDATE, RETRACTDATE, AUTOSUBMIT, ITEMNAVIGATION, ITEMNUMBERING, SUBMISSIONMESSAGE, RELEASETO, USERNAME, PASSWORD, FINALPAGEURL, UNLIMITEDSUBMISSIONS) VALUES (1 ,NULL,1 ,1 , NULL , NULL , NULL , NULL ,1 , NULL, NULL, NULL, NULL, NULL, 0 ,2 ,1 ,'' ,'' ,'' ,'' ,'' , 1 ) ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(1, 1, 'finalPageURL_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(2, 1, 'anonymousRelease_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(3, 1, 'dueDate_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(4, 1, 'description_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(5, 1, 'metadataQuestions_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(6, 1, 'bgImage_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(7, 1, 'feedbackComponents_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(8, 1, 'retractDate_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(9, 1, 'feedbackType_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(10, 1, 'timedAssessmentAutoSubmit_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(11, 1, 'toGradebook_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(12, 1, 'displayChunking_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(13, 1, 'recordedScore_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(14, 1, 'authenticatedRelease_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(15, 1, 'displayNumbering_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(16, 1, 'submissionMessage_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(17, 1, 'releaseDate_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(18, 1, 'assessmentAuthor_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(19, 1, 'passwordRequired_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(19, 1, 'lockedBrowser_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(20, 1, 'author', '') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(21, 1, 'submissionModel_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(22, 1, 'ipAccessType_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(23, 1, 'timedAssessment_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(24, 1, 'metadataAssess_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(25, 1, 'bgColor_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(26, 1, 'testeeIdentity_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(27, 1, 'templateInfo_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(28, 1, 'itemAccessType_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(29, 1, 'lateHandling_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(30, 1, 'feedbackAuthoring_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, 1, 'releaseTo', 'SITE_MEMBERS') ; ALTER TABLE SAM_ASSESSMETADATA_T ALTER COLUMN ASSESSMENTMETADATAID RESTART WITH 31 ; INSERT INTO SAM_FUNCTIONDATA_T values (1, 'take.published.assessment', 'Take Assessment','Take Assessment', '81') ; INSERT INTO SAM_FUNCTIONDATA_T values (2, 'view.published.assessment', 'View Assessment','View Assessment', '81') ; INSERT INTO SAM_FUNCTIONDATA_T values (3, 'submit.assessment', 'Submit Assessment','Submit Assessment', '81') ; INSERT INTO SAM_FUNCTIONDATA_T values (4, 'submit.assessment.forgrade', 'Submit Assessment For Grade','Submit Assessment For Grade', '81') ; ALTER TABLE SAM_FUNCTIONDATA_T ALTER COLUMN FUNCTIONID RESTART WITH 5 ; -- 6 new assessmentTypes for samigo 2.2 -- INSERT INTO SAM_ASSESSMENTBASE_T (ID ,ISTEMPLATE , PARENTID ,TITLE ,DESCRIPTION ,COMMENTS, ASSESSMENTTEMPLATEID, TYPEID, INSTRUCTORNOTIFICATION, TESTEENOTIFICATION , MULTIPARTALLOWED, STATUS, CREATEDBY, CREATEDDATE, LASTMODIFIEDBY, LASTMODIFIEDDATE ) VALUES (DEFAULT,'1' ,0 ,'Formative Assessment' , 'System Defined Assessment Type', '', NULL ,142 ,1 ,1 ,1 ,1 ,'admin' ,'2006-06-01 12:00:00' ,'admin' ,'2006-06-01 12:00:00' ) ; INSERT INTO SAM_ASSESSEVALUATION_T (ASSESSMENTID, EVALUATIONCOMPONENTS, SCORINGTYPE, NUMERICMODELID, FIXEDTOTALSCORE, GRADEAVAILABLE, ISSTUDENTIDPUBLIC, ANONYMOUSGRADING, AUTOSCORING,TOGRADEBOOK) VALUES ((SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Formative Assessment' AND TYPEID=142 AND ISTEMPLATE='1'), '' ,1 ,'' , NULL , NULL , NULL ,1 , NULL ,'2' ) ; INSERT INTO SAM_ASSESSFEEDBACK_T (ASSESSMENTID, FEEDBACKDELIVERY, FEEDBACKAUTHORING, SHOWQUESTIONTEXT, SHOWSTUDENTRESPONSE, SHOWCORRECTRESPONSE, SHOWSTUDENTSCORE, SHOWSTUDENTQUESTIONSCORE, SHOWQUESTIONLEVELFEEDBACK, SHOWSELECTIONLEVELFEEDBACK, SHOWGRADERCOMMENTS, SHOWSTATISTICS, EDITCOMPONENTS, FEEDBACKCOMPONENTOPTION) VALUES ((SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Formative Assessment' AND TYPEID=142 AND ISTEMPLATE='1'), 1 ,3, 1 ,1 ,1 ,1 ,1 ,1 ,1 ,1 ,1 ,1 ,2 ) ; INSERT INTO SAM_ASSESSACCESSCONTROL_T (ASSESSMENTID, SUBMISSIONSALLOWED, SUBMISSIONSSAVED, ASSESSMENTFORMAT, BOOKMARKINGITEM, TIMELIMIT, TIMEDASSESSMENT, RETRYALLOWED, LATEHANDLING, STARTDATE, DUEDATE, SCOREDATE, FEEDBACKDATE, RETRACTDATE, AUTOSUBMIT, ITEMNAVIGATION, ITEMNUMBERING, SUBMISSIONMESSAGE, RELEASETO, USERNAME, PASSWORD, FINALPAGEURL, UNLIMITEDSUBMISSIONS) VALUES ((SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Formative Assessment' AND TYPEID=142 AND ISTEMPLATE='1'), NULL,1 ,1 , NULL , NULL , NULL , NULL ,1 , NULL, NULL, NULL, NULL, NULL, 0 ,2 ,1 ,'' ,'' ,'' ,'' ,'' , 1 ) ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Formative Assessment' AND TYPEID=142 AND ISTEMPLATE='1'), 'finalPageURL_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Formative Assessment' AND TYPEID=142 AND ISTEMPLATE='1'), 'anonymousRelease_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Formative Assessment' AND TYPEID=142 AND ISTEMPLATE='1'), 'dueDate_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Formative Assessment' AND TYPEID=142 AND ISTEMPLATE='1'), 'description_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Formative Assessment' AND TYPEID=142 AND ISTEMPLATE='1'), 'metadataQuestions_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Formative Assessment' AND TYPEID=142 AND ISTEMPLATE='1'), 'bgImage_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Formative Assessment' AND TYPEID=142 AND ISTEMPLATE='1'), 'feedbackComponents_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Formative Assessment' AND TYPEID=142 AND ISTEMPLATE='1'), 'retractDate_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Formative Assessment' AND TYPEID=142 AND ISTEMPLATE='1'), 'feedbackType_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Formative Assessment' AND TYPEID=142 AND ISTEMPLATE='1'), 'timedAssessmentAutoSubmit_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Formative Assessment' AND TYPEID=142 AND ISTEMPLATE='1'), 'toGradebook_isInstructorEditable', 'false') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Formative Assessment' AND TYPEID=142 AND ISTEMPLATE='1'), 'displayChunking_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT,(SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Formative Assessment' AND TYPEID=142 AND ISTEMPLATE='1'), 'recordedScore_isInstructorEditable', 'false') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Formative Assessment' AND TYPEID=142 AND ISTEMPLATE='1'), 'authenticatedRelease_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Formative Assessment' AND TYPEID=142 AND ISTEMPLATE='1'), 'displayNumbering_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Formative Assessment' AND TYPEID=142 AND ISTEMPLATE='1'), 'submissionMessage_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Formative Assessment' AND TYPEID=142 AND ISTEMPLATE='1'), 'releaseDate_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Formative Assessment' AND TYPEID=142 AND ISTEMPLATE='1'), 'assessmentAuthor_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Formative Assessment' AND TYPEID=142 AND ISTEMPLATE='1'), 'passwordRequired_isInstructorEditable', 'false') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Formative Assessment' AND TYPEID=142 AND ISTEMPLATE='1'), 'author', '') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Formative Assessment' AND TYPEID=142 AND ISTEMPLATE='1'), 'submissionModel_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Formative Assessment' AND TYPEID=142 AND ISTEMPLATE='1'), 'ipAccessType_isInstructorEditable', 'false') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Formative Assessment' AND TYPEID=142 AND ISTEMPLATE='1'), 'timedAssessment_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Formative Assessment' AND TYPEID=142 AND ISTEMPLATE='1'), 'metadataAssess_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Formative Assessment' AND TYPEID=142 AND ISTEMPLATE='1'), 'bgColor_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Formative Assessment' AND TYPEID=142 AND ISTEMPLATE='1'), 'testeeIdentity_isInstructorEditable', 'false') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Formative Assessment' AND TYPEID=142 AND ISTEMPLATE='1'), 'templateInfo_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Formative Assessment' AND TYPEID=142 AND ISTEMPLATE='1'), 'itemAccessType_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Formative Assessment' AND TYPEID=142 AND ISTEMPLATE='1'), 'lateHandling_isInstructorEditable', 'false') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Formative Assessment' AND TYPEID=142 AND ISTEMPLATE='1'), 'feedbackAuthoring_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Formative Assessment' AND TYPEID=142 AND ISTEMPLATE='1'), 'releaseTo', 'SITE_MEMBERS') ; INSERT INTO SAM_ASSESSMENTBASE_T (ID ,ISTEMPLATE , PARENTID ,TITLE ,DESCRIPTION ,COMMENTS, ASSESSMENTTEMPLATEID, TYPEID, INSTRUCTORNOTIFICATION, TESTEENOTIFICATION , MULTIPARTALLOWED, STATUS, CREATEDBY, CREATEDDATE, LASTMODIFIEDBY, LASTMODIFIEDDATE ) VALUES (DEFAULT,'1' ,0 ,'Quiz' , 'System Defined Assessment Type', '', NULL ,142 ,1 ,1 ,1 ,1 ,'admin' ,'2006-06-01 12:00:00' ,'admin' ,'2006-06-01 12:00:00' ) ; INSERT INTO SAM_ASSESSEVALUATION_T (ASSESSMENTID, EVALUATIONCOMPONENTS, SCORINGTYPE, NUMERICMODELID, FIXEDTOTALSCORE, GRADEAVAILABLE, ISSTUDENTIDPUBLIC, ANONYMOUSGRADING, AUTOSCORING,TOGRADEBOOK) VALUES ((SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Quiz' AND TYPEID=142 AND ISTEMPLATE='1'), '' ,1 ,'' , NULL , NULL , NULL ,2 , NULL ,'2' ) ; INSERT INTO SAM_ASSESSFEEDBACK_T (ASSESSMENTID, FEEDBACKDELIVERY, FEEDBACKAUTHORING, SHOWQUESTIONTEXT, SHOWSTUDENTRESPONSE, SHOWCORRECTRESPONSE, SHOWSTUDENTSCORE, SHOWSTUDENTQUESTIONSCORE, SHOWQUESTIONLEVELFEEDBACK, SHOWSELECTIONLEVELFEEDBACK, SHOWGRADERCOMMENTS, SHOWSTATISTICS, EDITCOMPONENTS, FEEDBACKCOMPONENTOPTION) VALUES ((SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Quiz' AND TYPEID=142 AND ISTEMPLATE='1'), 2 ,1, 1 ,1 ,1 ,1 ,1 ,1 ,1 ,1 ,1 ,1 ,2 ) ; INSERT INTO SAM_ASSESSACCESSCONTROL_T (ASSESSMENTID, SUBMISSIONSALLOWED, SUBMISSIONSSAVED, ASSESSMENTFORMAT, BOOKMARKINGITEM, TIMELIMIT, TIMEDASSESSMENT, RETRYALLOWED, LATEHANDLING, STARTDATE, DUEDATE, SCOREDATE, FEEDBACKDATE, RETRACTDATE, AUTOSUBMIT, ITEMNAVIGATION, ITEMNUMBERING, SUBMISSIONMESSAGE, RELEASETO, USERNAME, PASSWORD, FINALPAGEURL, UNLIMITEDSUBMISSIONS) VALUES ((SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Quiz' AND TYPEID=142 AND ISTEMPLATE='1'), 1,1 ,3 , NULL , NULL , NULL , NULL ,2 , NULL, NULL, NULL, NULL, NULL, 0 ,1 ,1 ,'' ,'' ,'' ,'' ,'' , 0 ) ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Quiz' AND TYPEID=142 AND ISTEMPLATE='1'), 'finalPageURL_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Quiz' AND TYPEID=142 AND ISTEMPLATE='1'), 'anonymousRelease_isInstructorEditable', 'false') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Quiz' AND TYPEID=142 AND ISTEMPLATE='1'), 'dueDate_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Quiz' AND TYPEID=142 AND ISTEMPLATE='1'), 'description_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Quiz' AND TYPEID=142 AND ISTEMPLATE='1'), 'metadataQuestions_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Quiz' AND TYPEID=142 AND ISTEMPLATE='1'), 'bgImage_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Quiz' AND TYPEID=142 AND ISTEMPLATE='1'), 'feedbackComponents_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Quiz' AND TYPEID=142 AND ISTEMPLATE='1'), 'retractDate_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Quiz' AND TYPEID=142 AND ISTEMPLATE='1'), 'feedbackType_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Quiz' AND TYPEID=142 AND ISTEMPLATE='1'), 'timedAssessmentAutoSubmit_isInstructorEditable', 'false') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Quiz' AND TYPEID=142 AND ISTEMPLATE='1'), 'toGradebook_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Quiz' AND TYPEID=142 AND ISTEMPLATE='1'), 'displayChunking_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Quiz' AND TYPEID=142 AND ISTEMPLATE='1'), 'recordedScore_isInstructorEditable', 'false') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Quiz' AND TYPEID=142 AND ISTEMPLATE='1'), 'authenticatedRelease_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Quiz' AND TYPEID=142 AND ISTEMPLATE='1'), 'displayNumbering_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Quiz' AND TYPEID=142 AND ISTEMPLATE='1'), 'submissionMessage_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Quiz' AND TYPEID=142 AND ISTEMPLATE='1'), 'releaseDate_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Quiz' AND TYPEID=142 AND ISTEMPLATE='1'), 'assessmentAuthor_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Quiz' AND TYPEID=142 AND ISTEMPLATE='1'), 'passwordRequired_isInstructorEditable', 'false') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Quiz' AND TYPEID=142 AND ISTEMPLATE='1'), 'author', '') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Quiz' AND TYPEID=142 AND ISTEMPLATE='1'), 'submissionModel_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Quiz' AND TYPEID=142 AND ISTEMPLATE='1'), 'ipAccessType_isInstructorEditable', 'false') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Quiz' AND TYPEID=142 AND ISTEMPLATE='1'), 'timedAssessment_isInstructorEditable', 'false') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Quiz' AND TYPEID=142 AND ISTEMPLATE='1'), 'metadataAssess_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Quiz' AND TYPEID=142 AND ISTEMPLATE='1'), 'bgColor_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Quiz' AND TYPEID=142 AND ISTEMPLATE='1'), 'testeeIdentity_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Quiz' AND TYPEID=142 AND ISTEMPLATE='1'), 'templateInfo_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Quiz' AND TYPEID=142 AND ISTEMPLATE='1'), 'itemAccessType_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Quiz' AND TYPEID=142 AND ISTEMPLATE='1'), 'lateHandling_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Quiz' AND TYPEID=142 AND ISTEMPLATE='1'), 'feedbackAuthoring_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Quiz' AND TYPEID=142 AND ISTEMPLATE='1'), 'releaseTo', 'SITE_MEMBERS') ; INSERT INTO SAM_ASSESSMENTBASE_T (ID ,ISTEMPLATE , PARENTID ,TITLE ,DESCRIPTION ,COMMENTS, ASSESSMENTTEMPLATEID, TYPEID, INSTRUCTORNOTIFICATION, TESTEENOTIFICATION , MULTIPARTALLOWED, STATUS, CREATEDBY, CREATEDDATE, LASTMODIFIEDBY, LASTMODIFIEDDATE ) VALUES (DEFAULT,'1' ,0 ,'Problem Set' , 'System Defined Assessment Type', '', NULL ,142 ,1 ,1 ,1 ,1 ,'admin' ,'2006-06-01 12:00:00' ,'admin' ,'2006-06-01 12:00:00' ) ; INSERT INTO SAM_ASSESSEVALUATION_T (ASSESSMENTID, EVALUATIONCOMPONENTS, SCORINGTYPE, NUMERICMODELID, FIXEDTOTALSCORE, GRADEAVAILABLE, ISSTUDENTIDPUBLIC, ANONYMOUSGRADING, AUTOSCORING,TOGRADEBOOK) VALUES ((SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Problem Set' AND TYPEID=142 AND ISTEMPLATE='1'), '' ,1 ,'' , NULL , NULL , NULL ,2 , NULL ,'2' ) ; INSERT INTO SAM_ASSESSFEEDBACK_T (ASSESSMENTID, FEEDBACKDELIVERY, FEEDBACKAUTHORING, SHOWQUESTIONTEXT, SHOWSTUDENTRESPONSE, SHOWCORRECTRESPONSE, SHOWSTUDENTSCORE, SHOWSTUDENTQUESTIONSCORE, SHOWQUESTIONLEVELFEEDBACK, SHOWSELECTIONLEVELFEEDBACK, SHOWGRADERCOMMENTS, SHOWSTATISTICS, EDITCOMPONENTS, FEEDBACKCOMPONENTOPTION) VALUES ((SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Problem Set' AND TYPEID=142 AND ISTEMPLATE='1'), 2 ,1, 1 ,1 ,1 ,1 ,1 ,1 ,1 ,1 ,1 ,1 ,2 ) ; INSERT INTO SAM_ASSESSACCESSCONTROL_T (ASSESSMENTID, SUBMISSIONSALLOWED, SUBMISSIONSSAVED, ASSESSMENTFORMAT, BOOKMARKINGITEM, TIMELIMIT, TIMEDASSESSMENT, RETRYALLOWED, LATEHANDLING, STARTDATE, DUEDATE, SCOREDATE, FEEDBACKDATE, RETRACTDATE, AUTOSUBMIT, ITEMNAVIGATION, ITEMNUMBERING, SUBMISSIONMESSAGE, RELEASETO, USERNAME, PASSWORD, FINALPAGEURL, UNLIMITEDSUBMISSIONS) VALUES ((SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Problem Set' AND TYPEID=142 AND ISTEMPLATE='1'), NULL,1 ,2 , NULL , NULL , NULL , NULL ,1 , NULL, NULL, NULL, NULL, NULL, 0 ,2 ,1 ,'' ,'' ,'' ,'' ,'' , 1 ) ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Problem Set' AND TYPEID=142 AND ISTEMPLATE='1'), 'finalPageURL_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Problem Set' AND TYPEID=142 AND ISTEMPLATE='1'), 'anonymousRelease_isInstructorEditable', 'false') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Problem Set' AND TYPEID=142 AND ISTEMPLATE='1'), 'dueDate_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Problem Set' AND TYPEID=142 AND ISTEMPLATE='1'), 'description_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Problem Set' AND TYPEID=142 AND ISTEMPLATE='1'), 'metadataQuestions_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Problem Set' AND TYPEID=142 AND ISTEMPLATE='1'), 'bgImage_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Problem Set' AND TYPEID=142 AND ISTEMPLATE='1'), 'feedbackComponents_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Problem Set' AND TYPEID=142 AND ISTEMPLATE='1'), 'retractDate_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Problem Set' AND TYPEID=142 AND ISTEMPLATE='1'), 'feedbackType_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Problem Set' AND TYPEID=142 AND ISTEMPLATE='1'), 'timedAssessmentAutoSubmit_isInstructorEditable', 'false') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Problem Set' AND TYPEID=142 AND ISTEMPLATE='1'), 'toGradebook_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Problem Set' AND TYPEID=142 AND ISTEMPLATE='1'), 'displayChunking_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Problem Set' AND TYPEID=142 AND ISTEMPLATE='1'), 'recordedScore_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Problem Set' AND TYPEID=142 AND ISTEMPLATE='1'), 'authenticatedRelease_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Problem Set' AND TYPEID=142 AND ISTEMPLATE='1'), 'displayNumbering_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Problem Set' AND TYPEID=142 AND ISTEMPLATE='1'), 'submissionMessage_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Problem Set' AND TYPEID=142 AND ISTEMPLATE='1'), 'releaseDate_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Problem Set' AND TYPEID=142 AND ISTEMPLATE='1'), 'assessmentAuthor_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Problem Set' AND TYPEID=142 AND ISTEMPLATE='1'), 'passwordRequired_isInstructorEditable', 'false') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Problem Set' AND TYPEID=142 AND ISTEMPLATE='1'), 'author', '') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Problem Set' AND TYPEID=142 AND ISTEMPLATE='1'), 'submissionModel_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Problem Set' AND TYPEID=142 AND ISTEMPLATE='1'), 'ipAccessType_isInstructorEditable', 'false') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Problem Set' AND TYPEID=142 AND ISTEMPLATE='1'), 'timedAssessment_isInstructorEditable', 'false') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Problem Set' AND TYPEID=142 AND ISTEMPLATE='1'), 'metadataAssess_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Problem Set' AND TYPEID=142 AND ISTEMPLATE='1'), 'bgColor_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Problem Set' AND TYPEID=142 AND ISTEMPLATE='1'), 'testeeIdentity_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Problem Set' AND TYPEID=142 AND ISTEMPLATE='1'), 'templateInfo_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Problem Set' AND TYPEID=142 AND ISTEMPLATE='1'), 'itemAccessType_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Problem Set' AND TYPEID=142 AND ISTEMPLATE='1'), 'lateHandling_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Problem Set' AND TYPEID=142 AND ISTEMPLATE='1'), 'feedbackAuthoring_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Problem Set' AND TYPEID=142 AND ISTEMPLATE='1'), 'releaseTo', 'SITE_MEMBERS') ; INSERT INTO SAM_ASSESSMENTBASE_T (ID ,ISTEMPLATE , PARENTID ,TITLE ,DESCRIPTION ,COMMENTS, ASSESSMENTTEMPLATEID, TYPEID, INSTRUCTORNOTIFICATION, TESTEENOTIFICATION , MULTIPARTALLOWED, STATUS, CREATEDBY, CREATEDDATE, LASTMODIFIEDBY, LASTMODIFIEDDATE ) VALUES (DEFAULT,'1' ,0 ,'Survey' , 'System Defined Assessment Type', '', NULL ,142 ,1 ,1 ,1 ,1 ,'admin' ,'2006-06-01 12:00:00' ,'admin' ,'2006-06-01 12:00:00' ) ; INSERT INTO SAM_ASSESSEVALUATION_T (ASSESSMENTID, EVALUATIONCOMPONENTS, SCORINGTYPE, NUMERICMODELID, FIXEDTOTALSCORE, GRADEAVAILABLE, ISSTUDENTIDPUBLIC, ANONYMOUSGRADING, AUTOSCORING,TOGRADEBOOK) VALUES ((SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Survey' AND TYPEID=142 AND ISTEMPLATE='1'), '' ,1 ,'' , NULL , NULL , NULL ,1 , NULL ,'2' ) ; INSERT INTO SAM_ASSESSFEEDBACK_T (ASSESSMENTID, FEEDBACKDELIVERY, FEEDBACKAUTHORING, SHOWQUESTIONTEXT, SHOWSTUDENTRESPONSE, SHOWCORRECTRESPONSE, SHOWSTUDENTSCORE, SHOWSTUDENTQUESTIONSCORE, SHOWQUESTIONLEVELFEEDBACK, SHOWSELECTIONLEVELFEEDBACK, SHOWGRADERCOMMENTS, SHOWSTATISTICS, EDITCOMPONENTS, FEEDBACKCOMPONENTOPTION) VALUES ((SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Survey' AND TYPEID=142 AND ISTEMPLATE='1'), 1 ,3, 0 ,1 ,0 ,0 ,0 ,0 ,0 ,0 ,1 ,1 ,2 ) ; INSERT INTO SAM_ASSESSACCESSCONTROL_T (ASSESSMENTID, SUBMISSIONSALLOWED, SUBMISSIONSSAVED, ASSESSMENTFORMAT, BOOKMARKINGITEM, TIMELIMIT, TIMEDASSESSMENT, RETRYALLOWED, LATEHANDLING, STARTDATE, DUEDATE, SCOREDATE, FEEDBACKDATE, RETRACTDATE, AUTOSUBMIT, ITEMNAVIGATION, ITEMNUMBERING, SUBMISSIONMESSAGE, RELEASETO, USERNAME, PASSWORD, FINALPAGEURL, UNLIMITEDSUBMISSIONS) VALUES ((SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Survey' AND TYPEID=142 AND ISTEMPLATE='1'), 1,1 ,1 , NULL , NULL , NULL , NULL ,1 , NULL, NULL, NULL, NULL, NULL, 0 ,2 ,1 ,'' ,'' ,'' ,'' ,'' , 0 ) ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Survey' AND TYPEID=142 AND ISTEMPLATE='1'), 'finalPageURL_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Survey' AND TYPEID=142 AND ISTEMPLATE='1'), 'anonymousRelease_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Survey' AND TYPEID=142 AND ISTEMPLATE='1'), 'dueDate_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Survey' AND TYPEID=142 AND ISTEMPLATE='1'), 'description_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Survey' AND TYPEID=142 AND ISTEMPLATE='1'), 'metadataQuestions_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Survey' AND TYPEID=142 AND ISTEMPLATE='1'), 'bgImage_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Survey' AND TYPEID=142 AND ISTEMPLATE='1'), 'feedbackComponents_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Survey' AND TYPEID=142 AND ISTEMPLATE='1'), 'retractDate_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Survey' AND TYPEID=142 AND ISTEMPLATE='1'), 'feedbackType_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Survey' AND TYPEID=142 AND ISTEMPLATE='1'), 'timedAssessmentAutoSubmit_isInstructorEditable', 'false') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Survey' AND TYPEID=142 AND ISTEMPLATE='1'), 'toGradebook_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Survey' AND TYPEID=142 AND ISTEMPLATE='1'), 'displayChunking_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Survey' AND TYPEID=142 AND ISTEMPLATE='1'), 'recordedScore_isInstructorEditable', 'false') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Survey' AND TYPEID=142 AND ISTEMPLATE='1'), 'authenticatedRelease_isInstructorEditable', 'false') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Survey' AND TYPEID=142 AND ISTEMPLATE='1'), 'displayNumbering_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Survey' AND TYPEID=142 AND ISTEMPLATE='1'), 'submissionMessage_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Survey' AND TYPEID=142 AND ISTEMPLATE='1'), 'releaseDate_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Survey' AND TYPEID=142 AND ISTEMPLATE='1'), 'assessmentAuthor_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Survey' AND TYPEID=142 AND ISTEMPLATE='1'), 'passwordRequired_isInstructorEditable', 'false') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Survey' AND TYPEID=142 AND ISTEMPLATE='1'), 'author', '') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Survey' AND TYPEID=142 AND ISTEMPLATE='1'), 'submissionModel_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Survey' AND TYPEID=142 AND ISTEMPLATE='1'), 'ipAccessType_isInstructorEditable', 'false') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Survey' AND TYPEID=142 AND ISTEMPLATE='1'), 'timedAssessment_isInstructorEditable', 'false') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Survey' AND TYPEID=142 AND ISTEMPLATE='1'), 'metadataAssess_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Survey' AND TYPEID=142 AND ISTEMPLATE='1'), 'bgColor_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Survey' AND TYPEID=142 AND ISTEMPLATE='1'), 'testeeIdentity_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Survey' AND TYPEID=142 AND ISTEMPLATE='1'), 'templateInfo_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Survey' AND TYPEID=142 AND ISTEMPLATE='1'), 'itemAccessType_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Survey' AND TYPEID=142 AND ISTEMPLATE='1'), 'lateHandling_isInstructorEditable', 'false') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Survey' AND TYPEID=142 AND ISTEMPLATE='1'), 'feedbackAuthoring_isInstructorEditable', 'false') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Survey' AND TYPEID=142 AND ISTEMPLATE='1'), 'releaseTo', 'SITE_MEMBERS') ; INSERT INTO SAM_ASSESSMENTBASE_T (ID ,ISTEMPLATE , PARENTID ,TITLE ,DESCRIPTION ,COMMENTS, ASSESSMENTTEMPLATEID, TYPEID, INSTRUCTORNOTIFICATION, TESTEENOTIFICATION , MULTIPARTALLOWED, STATUS, CREATEDBY, CREATEDDATE, LASTMODIFIEDBY, LASTMODIFIEDDATE ) VALUES (DEFAULT,'1' ,0 ,'Test' , 'System Defined Assessment Type', '', NULL ,142 ,1 ,1 ,1 ,1 ,'admin' ,'2006-06-01 12:00:00' ,'admin' ,'2006-06-01 12:00:00' ) ; INSERT INTO SAM_ASSESSEVALUATION_T (ASSESSMENTID, EVALUATIONCOMPONENTS, SCORINGTYPE, NUMERICMODELID, FIXEDTOTALSCORE, GRADEAVAILABLE, ISSTUDENTIDPUBLIC, ANONYMOUSGRADING, AUTOSCORING,TOGRADEBOOK) VALUES ((SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Test' AND TYPEID=142 AND ISTEMPLATE='1'), '' ,1 ,'' , NULL , NULL , NULL ,1 , NULL ,'2' ) ; INSERT INTO SAM_ASSESSFEEDBACK_T (ASSESSMENTID, FEEDBACKDELIVERY, FEEDBACKAUTHORING, SHOWQUESTIONTEXT, SHOWSTUDENTRESPONSE, SHOWCORRECTRESPONSE, SHOWSTUDENTSCORE, SHOWSTUDENTQUESTIONSCORE, SHOWQUESTIONLEVELFEEDBACK, SHOWSELECTIONLEVELFEEDBACK, SHOWGRADERCOMMENTS, SHOWSTATISTICS, EDITCOMPONENTS, FEEDBACKCOMPONENTOPTION) VALUES ((SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Test' AND TYPEID=142 AND ISTEMPLATE='1'), 2 ,1, 1 ,1 ,1 ,1 ,1 ,1 ,1 ,1 ,1 ,1 ,2 ) ; INSERT INTO SAM_ASSESSACCESSCONTROL_T (ASSESSMENTID, SUBMISSIONSALLOWED, SUBMISSIONSSAVED, ASSESSMENTFORMAT, BOOKMARKINGITEM, TIMELIMIT, TIMEDASSESSMENT, RETRYALLOWED, LATEHANDLING, STARTDATE, DUEDATE, SCOREDATE, FEEDBACKDATE, RETRACTDATE, AUTOSUBMIT, ITEMNAVIGATION, ITEMNUMBERING, SUBMISSIONMESSAGE, RELEASETO, USERNAME, PASSWORD, FINALPAGEURL, UNLIMITEDSUBMISSIONS) VALUES ((SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Test' AND TYPEID=142 AND ISTEMPLATE='1'), 1,1 ,1 , NULL , NULL , NULL , NULL ,2 , NULL, NULL, NULL, NULL, NULL, 0 ,1 ,1 ,'' ,'' ,'' ,'' ,'' , 0 ) ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Test' AND TYPEID=142 AND ISTEMPLATE='1'), 'finalPageURL_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Test' AND TYPEID=142 AND ISTEMPLATE='1'), 'anonymousRelease_isInstructorEditable', 'false') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Test' AND TYPEID=142 AND ISTEMPLATE='1'), 'dueDate_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Test' AND TYPEID=142 AND ISTEMPLATE='1'), 'description_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Test' AND TYPEID=142 AND ISTEMPLATE='1'), 'metadataQuestions_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Test' AND TYPEID=142 AND ISTEMPLATE='1'), 'bgImage_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Test' AND TYPEID=142 AND ISTEMPLATE='1'), 'feedbackComponents_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Test' AND TYPEID=142 AND ISTEMPLATE='1'), 'retractDate_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Test' AND TYPEID=142 AND ISTEMPLATE='1'), 'feedbackType_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Test' AND TYPEID=142 AND ISTEMPLATE='1'), 'timedAssessmentAutoSubmit_isInstructorEditable', 'false') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Test' AND TYPEID=142 AND ISTEMPLATE='1'), 'toGradebook_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Test' AND TYPEID=142 AND ISTEMPLATE='1'), 'displayChunking_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Test' AND TYPEID=142 AND ISTEMPLATE='1'), 'recordedScore_isInstructorEditable', 'false') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Test' AND TYPEID=142 AND ISTEMPLATE='1'), 'authenticatedRelease_isInstructorEditable', 'false') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Test' AND TYPEID=142 AND ISTEMPLATE='1'), 'displayNumbering_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Test' AND TYPEID=142 AND ISTEMPLATE='1'), 'submissionMessage_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Test' AND TYPEID=142 AND ISTEMPLATE='1'), 'releaseDate_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Test' AND TYPEID=142 AND ISTEMPLATE='1'), 'assessmentAuthor_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Test' AND TYPEID=142 AND ISTEMPLATE='1'), 'passwordRequired_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Test' AND TYPEID=142 AND ISTEMPLATE='1'), 'lockedBrowser_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Test' AND TYPEID=142 AND ISTEMPLATE='1'), 'author', '') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Test' AND TYPEID=142 AND ISTEMPLATE='1'), 'submissionModel_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Test' AND TYPEID=142 AND ISTEMPLATE='1'), 'ipAccessType_isInstructorEditable', 'false') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Test' AND TYPEID=142 AND ISTEMPLATE='1'), 'timedAssessment_isInstructorEditable', 'false') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Test' AND TYPEID=142 AND ISTEMPLATE='1'), 'metadataAssess_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Test' AND TYPEID=142 AND ISTEMPLATE='1'), 'bgColor_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Test' AND TYPEID=142 AND ISTEMPLATE='1'), 'testeeIdentity_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Test' AND TYPEID=142 AND ISTEMPLATE='1'), 'templateInfo_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Test' AND TYPEID=142 AND ISTEMPLATE='1'), 'itemAccessType_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Test' AND TYPEID=142 AND ISTEMPLATE='1'), 'lateHandling_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Test' AND TYPEID=142 AND ISTEMPLATE='1'), 'feedbackAuthoring_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Test' AND TYPEID=142 AND ISTEMPLATE='1'), 'releaseTo', 'SITE_MEMBERS') ; INSERT INTO SAM_ASSESSMENTBASE_T (ID ,ISTEMPLATE , PARENTID ,TITLE ,DESCRIPTION ,COMMENTS, ASSESSMENTTEMPLATEID, TYPEID, INSTRUCTORNOTIFICATION, TESTEENOTIFICATION , MULTIPARTALLOWED, STATUS, CREATEDBY, CREATEDDATE, LASTMODIFIEDBY, LASTMODIFIEDDATE ) VALUES (DEFAULT,'1' ,0 ,'Timed Test' , 'System Defined Assessment Type', '', NULL ,142 ,1 ,1 ,1 ,1 ,'admin' ,'2006-06-01 12:00:00' ,'admin' ,'2006-06-01 12:00:00' ) ; INSERT INTO SAM_ASSESSEVALUATION_T (ASSESSMENTID, EVALUATIONCOMPONENTS, SCORINGTYPE, NUMERICMODELID, FIXEDTOTALSCORE, GRADEAVAILABLE, ISSTUDENTIDPUBLIC, ANONYMOUSGRADING, AUTOSCORING,TOGRADEBOOK) VALUES ((SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Timed Test' AND TYPEID=142 AND ISTEMPLATE='1'), '' ,1 ,'' , NULL , NULL , NULL ,1 , NULL ,'2' ) ; INSERT INTO SAM_ASSESSFEEDBACK_T (ASSESSMENTID, FEEDBACKDELIVERY, FEEDBACKAUTHORING, SHOWQUESTIONTEXT, SHOWSTUDENTRESPONSE, SHOWCORRECTRESPONSE, SHOWSTUDENTSCORE, SHOWSTUDENTQUESTIONSCORE, SHOWQUESTIONLEVELFEEDBACK, SHOWSELECTIONLEVELFEEDBACK, SHOWGRADERCOMMENTS, SHOWSTATISTICS, EDITCOMPONENTS, FEEDBACKCOMPONENTOPTION) VALUES ((SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Timed Test' AND TYPEID=142 AND ISTEMPLATE='1'), 2 ,1, 1 ,1 ,1 ,1 ,1 ,1 ,1 ,1 ,1 ,1 ,2 ) ; INSERT INTO SAM_ASSESSACCESSCONTROL_T (ASSESSMENTID, SUBMISSIONSALLOWED, SUBMISSIONSSAVED, ASSESSMENTFORMAT, BOOKMARKINGITEM, TIMELIMIT, TIMEDASSESSMENT, RETRYALLOWED, LATEHANDLING, STARTDATE, DUEDATE, SCOREDATE, FEEDBACKDATE, RETRACTDATE, AUTOSUBMIT, ITEMNAVIGATION, ITEMNUMBERING, SUBMISSIONMESSAGE, RELEASETO, USERNAME, PASSWORD, FINALPAGEURL, UNLIMITEDSUBMISSIONS) VALUES ((SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Timed Test' AND TYPEID=142 AND ISTEMPLATE='1'), 1,1 ,1 , NULL , NULL , NULL , NULL ,2 , NULL, NULL, NULL, NULL, NULL, 0 ,1 ,1 ,'' ,'' ,'' ,'' ,'' , 0 ) ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Timed Test' AND TYPEID=142 AND ISTEMPLATE='1'), 'finalPageURL_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Timed Test' AND TYPEID=142 AND ISTEMPLATE='1'), 'anonymousRelease_isInstructorEditable', 'false') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Timed Test' AND TYPEID=142 AND ISTEMPLATE='1'), 'dueDate_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Timed Test' AND TYPEID=142 AND ISTEMPLATE='1'), 'description_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Timed Test' AND TYPEID=142 AND ISTEMPLATE='1'), 'metadataQuestions_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Timed Test' AND TYPEID=142 AND ISTEMPLATE='1'), 'bgImage_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Timed Test' AND TYPEID=142 AND ISTEMPLATE='1'), 'feedbackComponents_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Timed Test' AND TYPEID=142 AND ISTEMPLATE='1'), 'retractDate_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Timed Test' AND TYPEID=142 AND ISTEMPLATE='1'), 'feedbackType_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Timed Test' AND TYPEID=142 AND ISTEMPLATE='1'), 'timedAssessmentAutoSubmit_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Timed Test' AND TYPEID=142 AND ISTEMPLATE='1'), 'toGradebook_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Timed Test' AND TYPEID=142 AND ISTEMPLATE='1'), 'displayChunking_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Timed Test' AND TYPEID=142 AND ISTEMPLATE='1'), 'recordedScore_isInstructorEditable', 'false') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Timed Test' AND TYPEID=142 AND ISTEMPLATE='1'), 'authenticatedRelease_isInstructorEditable', 'false') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Timed Test' AND TYPEID=142 AND ISTEMPLATE='1'), 'displayNumbering_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Timed Test' AND TYPEID=142 AND ISTEMPLATE='1'), 'submissionMessage_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Timed Test' AND TYPEID=142 AND ISTEMPLATE='1'), 'releaseDate_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Timed Test' AND TYPEID=142 AND ISTEMPLATE='1'), 'assessmentAuthor_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Timed Test' AND TYPEID=142 AND ISTEMPLATE='1'), 'passwordRequired_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Timed Test' AND TYPEID=142 AND ISTEMPLATE='1'), 'lockedBrowser_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Timed Test' AND TYPEID=142 AND ISTEMPLATE='1'), 'author', '') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Timed Test' AND TYPEID=142 AND ISTEMPLATE='1'), 'submissionModel_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Timed Test' AND TYPEID=142 AND ISTEMPLATE='1'), 'ipAccessType_isInstructorEditable', 'false') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Timed Test' AND TYPEID=142 AND ISTEMPLATE='1'), 'timedAssessment_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Timed Test' AND TYPEID=142 AND ISTEMPLATE='1'), 'metadataAssess_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Timed Test' AND TYPEID=142 AND ISTEMPLATE='1'), 'bgColor_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Timed Test' AND TYPEID=142 AND ISTEMPLATE='1'), 'testeeIdentity_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Timed Test' AND TYPEID=142 AND ISTEMPLATE='1'), 'templateInfo_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Timed Test' AND TYPEID=142 AND ISTEMPLATE='1'), 'itemAccessType_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Timed Test' AND TYPEID=142 AND ISTEMPLATE='1'), 'lateHandling_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Timed Test' AND TYPEID=142 AND ISTEMPLATE='1'), 'feedbackAuthoring_isInstructorEditable', 'true') ; INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES(DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Timed Test' AND TYPEID=142 AND ISTEMPLATE='1'), 'releaseTo', 'SITE_MEMBERS') ; INSERT INTO SAM_TYPE_T (TYPEID ,AUTHORITY, DOMAIN, KEYWORD, DESCRIPTION, STATUS, CREATEDBY, CREATEDDATE, LASTMODIFIEDBY, LASTMODIFIEDDATE) VALUES (12 , 'stanford.edu', 'assessment.item', 'Multiple Correct Single Selection', NULL, 1, '1', CURRENT TIMESTAMP, '1', CURRENT TIMESTAMP); INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES (DEFAULT, 1, 'markForReview_isInstructorEditable', 'true'); INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES (DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Formative Assessment' AND TYPEID=142 AND ISTEMPLATE='1'), 'markForReview_isInstructorEditable', 'true'); INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES (DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Quiz' AND TYPEID=142 AND ISTEMPLATE='1'), 'markForReview_isInstructorEditable', 'true'); INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES (DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Problem Set' AND TYPEID=142 AND ISTEMPLATE='1'), 'markForReview_isInstructorEditable', 'true'); INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES (DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Test' AND TYPEID=142 AND ISTEMPLATE='1'), 'markForReview_isInstructorEditable', 'true'); INSERT INTO SAM_ASSESSMETADATA_T (ASSESSMENTMETADATAID, ASSESSMENTID, LABEL, ENTRY) VALUES (DEFAULT, (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Timed Test' AND TYPEID=142 AND ISTEMPLATE='1'), 'markForReview_isInstructorEditable', 'true'); update SAM_ASSESSACCESSCONTROL_T set MARKFORREVIEW = 1 where ASSESSMENTID = (SELECT ID FROM SAM_ASSESSMENTBASE_T WHERE TITLE='Formative Assessment' AND TYPEID=142 AND ISTEMPLATE='1');
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.search.aggregations.bucket.histogram; import org.apache.lucene.index.LeafReaderContext; import org.apache.lucene.index.SortedNumericDocValues; import org.apache.lucene.util.CollectionUtil; import org.elasticsearch.common.inject.internal.Nullable; import org.elasticsearch.common.lease.Releasables; import org.elasticsearch.common.rounding.Rounding; import org.elasticsearch.common.util.LongHash; import org.elasticsearch.search.aggregations.Aggregator; import org.elasticsearch.search.aggregations.AggregatorFactories; import org.elasticsearch.search.aggregations.InternalAggregation; import org.elasticsearch.search.aggregations.LeafBucketCollector; import org.elasticsearch.search.aggregations.LeafBucketCollectorBase; import org.elasticsearch.search.aggregations.bucket.BucketsAggregator; import org.elasticsearch.search.aggregations.pipeline.PipelineAggregator; import org.elasticsearch.search.aggregations.support.AggregationContext; import org.elasticsearch.search.aggregations.support.ValuesSource; import org.elasticsearch.search.aggregations.support.ValuesSourceAggregatorFactory; import org.elasticsearch.search.aggregations.support.ValuesSourceConfig; import org.elasticsearch.search.aggregations.support.format.ValueFormatter; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; public class HistogramAggregator extends BucketsAggregator { private final ValuesSource.Numeric valuesSource; private final ValueFormatter formatter; private final Rounding rounding; private final InternalOrder order; private final boolean keyed; private final long minDocCount; private final ExtendedBounds extendedBounds; private final InternalHistogram.Factory histogramFactory; private final LongHash bucketOrds; public HistogramAggregator(String name, AggregatorFactories factories, Rounding rounding, InternalOrder order, boolean keyed, long minDocCount, @Nullable ExtendedBounds extendedBounds, @Nullable ValuesSource.Numeric valuesSource, ValueFormatter formatter, InternalHistogram.Factory<?> histogramFactory, AggregationContext aggregationContext, Aggregator parent, List<PipelineAggregator> pipelineAggregators, Map<String, Object> metaData) throws IOException { super(name, factories, aggregationContext, parent, pipelineAggregators, metaData); this.rounding = rounding; this.order = order; this.keyed = keyed; this.minDocCount = minDocCount; this.extendedBounds = extendedBounds; this.valuesSource = valuesSource; this.formatter = formatter; this.histogramFactory = histogramFactory; bucketOrds = new LongHash(1, aggregationContext.bigArrays()); } @Override public boolean needsScores() { return (valuesSource != null && valuesSource.needsScores()) || super.needsScores(); } @Override public LeafBucketCollector getLeafCollector(LeafReaderContext ctx, final LeafBucketCollector sub) throws IOException { if (valuesSource == null) { return LeafBucketCollector.NO_OP_COLLECTOR; } final SortedNumericDocValues values = valuesSource.longValues(ctx); return new LeafBucketCollectorBase(sub, values) { @Override public void collect(int doc, long bucket) throws IOException { assert bucket == 0; values.setDocument(doc); final int valuesCount = values.count(); long previousKey = Long.MIN_VALUE; for (int i = 0; i < valuesCount; ++i) { long value = values.valueAt(i); long key = rounding.roundKey(value); assert key >= previousKey; if (key == previousKey) { continue; } long bucketOrd = bucketOrds.add(key); if (bucketOrd < 0) { // already seen bucketOrd = -1 - bucketOrd; collectExistingBucket(sub, doc, bucketOrd); } else { collectBucket(sub, doc, bucketOrd); } previousKey = key; } } }; } @Override public InternalAggregation buildAggregation(long owningBucketOrdinal) throws IOException { assert owningBucketOrdinal == 0; List<InternalHistogram.Bucket> buckets = new ArrayList<>((int) bucketOrds.size()); for (long i = 0; i < bucketOrds.size(); i++) { buckets.add(histogramFactory.createBucket(rounding.valueForKey(bucketOrds.get(i)), bucketDocCount(i), bucketAggregations(i), keyed, formatter)); } // the contract of the histogram aggregation is that shards must return buckets ordered by key in ascending order CollectionUtil.introSort(buckets, InternalOrder.KEY_ASC.comparator()); // value source will be null for unmapped fields InternalHistogram.EmptyBucketInfo emptyBucketInfo = minDocCount == 0 ? new InternalHistogram.EmptyBucketInfo(rounding, buildEmptySubAggregations(), extendedBounds) : null; return histogramFactory.create(name, buckets, order, minDocCount, emptyBucketInfo, formatter, keyed, pipelineAggregators(), metaData()); } @Override public InternalAggregation buildEmptyAggregation() { InternalHistogram.EmptyBucketInfo emptyBucketInfo = minDocCount == 0 ? new InternalHistogram.EmptyBucketInfo(rounding, buildEmptySubAggregations(), extendedBounds) : null; return histogramFactory.create(name, Collections.emptyList(), order, minDocCount, emptyBucketInfo, formatter, keyed, pipelineAggregators(), metaData()); } @Override public void doClose() { Releasables.close(bucketOrds); } public static class Factory extends ValuesSourceAggregatorFactory<ValuesSource.Numeric> { private final Rounding rounding; private final InternalOrder order; private final boolean keyed; private final long minDocCount; private final ExtendedBounds extendedBounds; private final InternalHistogram.Factory<?> histogramFactory; public Factory(String name, ValuesSourceConfig<ValuesSource.Numeric> config, Rounding rounding, InternalOrder order, boolean keyed, long minDocCount, ExtendedBounds extendedBounds, InternalHistogram.Factory<?> histogramFactory) { super(name, histogramFactory.type(), config); this.rounding = rounding; this.order = order; this.keyed = keyed; this.minDocCount = minDocCount; this.extendedBounds = extendedBounds; this.histogramFactory = histogramFactory; } public long minDocCount() { return minDocCount; } @Override protected Aggregator createUnmapped(AggregationContext aggregationContext, Aggregator parent, List<PipelineAggregator> pipelineAggregators, Map<String, Object> metaData) throws IOException { return new HistogramAggregator(name, factories, rounding, order, keyed, minDocCount, extendedBounds, null, config.formatter(), histogramFactory, aggregationContext, parent, pipelineAggregators, metaData); } @Override protected Aggregator doCreateInternal(ValuesSource.Numeric valuesSource, AggregationContext aggregationContext, Aggregator parent, boolean collectsFromSingleBucket, List<PipelineAggregator> pipelineAggregators, Map<String, Object> metaData) throws IOException { if (collectsFromSingleBucket == false) { return asMultiBucketAggregator(this, aggregationContext, parent); } // we need to round the bounds given by the user and we have to do it for every aggregator we crate // as the rounding is not necessarily an idempotent operation. // todo we need to think of a better structure to the factory/agtor code so we won't need to do that ExtendedBounds roundedBounds = null; if (extendedBounds != null) { // we need to process & validate here using the parser extendedBounds.processAndValidate(name, aggregationContext.searchContext(), config.parser()); roundedBounds = extendedBounds.round(rounding); } return new HistogramAggregator(name, factories, rounding, order, keyed, minDocCount, roundedBounds, valuesSource, config.formatter(), histogramFactory, aggregationContext, parent, pipelineAggregators, metaData); } } }
/** * 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 com.alibaba.jstorm.container.cgroup; import java.util.HashMap; import java.util.Map; import java.util.Set; import com.alibaba.jstorm.container.SubSystemType; import com.alibaba.jstorm.container.cgroup.core.BlkioCore; import com.alibaba.jstorm.container.cgroup.core.CgroupCore; import com.alibaba.jstorm.container.cgroup.core.CpuCore; import com.alibaba.jstorm.container.cgroup.core.CpuacctCore; import com.alibaba.jstorm.container.cgroup.core.CpusetCore; import com.alibaba.jstorm.container.cgroup.core.DevicesCore; import com.alibaba.jstorm.container.cgroup.core.FreezerCore; import com.alibaba.jstorm.container.cgroup.core.MemoryCore; import com.alibaba.jstorm.container.cgroup.core.NetClsCore; import com.alibaba.jstorm.container.cgroup.core.NetPrioCore; public class CgroupCoreFactory { public static Map<SubSystemType, CgroupCore> getInstance( Set<SubSystemType> types, String dir) { Map<SubSystemType, CgroupCore> result = new HashMap<SubSystemType, CgroupCore>(); for (SubSystemType type : types) { switch (type) { case blkio: result.put(SubSystemType.blkio, new BlkioCore(dir)); break; case cpuacct: result.put(SubSystemType.cpuacct, new CpuacctCore(dir)); break; case cpuset: result.put(SubSystemType.cpuset, new CpusetCore(dir)); break; case cpu: result.put(SubSystemType.cpu, new CpuCore(dir)); break; case devices: result.put(SubSystemType.devices, new DevicesCore(dir)); break; case freezer: result.put(SubSystemType.freezer, new FreezerCore(dir)); break; case memory: result.put(SubSystemType.memory, new MemoryCore(dir)); break; case net_cls: result.put(SubSystemType.net_cls, new NetClsCore(dir)); break; case net_prio: result.put(SubSystemType.net_prio, new NetPrioCore(dir)); break; default: break; } } return result; } }
/* 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.camunda.bpm.engine.rest; import org.camunda.bpm.engine.rest.dto.CountResultDto; import org.camunda.bpm.engine.rest.dto.ResourceOptionsDto; import org.camunda.bpm.engine.rest.dto.authorization.AuthorizationCheckResultDto; import org.camunda.bpm.engine.rest.dto.authorization.AuthorizationCreateDto; import org.camunda.bpm.engine.rest.dto.authorization.AuthorizationDto; import org.camunda.bpm.engine.rest.sub.authorization.AuthorizationResource; import javax.ws.rs.*; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.UriInfo; import java.util.List; /** * @author Daniel Meyer * */ @Produces(MediaType.APPLICATION_JSON) public interface AuthorizationRestService { public static final String PATH = "/authorization"; @GET @Path("/check") @Produces(MediaType.APPLICATION_JSON) AuthorizationCheckResultDto isUserAuthorized( @QueryParam("permissionName") String permissionName, @QueryParam("resourceName") String resourceName, @QueryParam("resourceType") Integer resourceType, @QueryParam("resourceId") String resourceId); @Path("/{id}") AuthorizationResource getAuthorization(@PathParam("id") String id); @GET @Produces(MediaType.APPLICATION_JSON) List<AuthorizationDto> queryAuthorizations(@Context UriInfo uriInfo, @QueryParam("firstResult") Integer firstResult, @QueryParam("maxResults") Integer maxResults); @GET @Path("/count") @Produces(MediaType.APPLICATION_JSON) CountResultDto getAuthorizationCount(@Context UriInfo uriInfo); @POST @Path("/create") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) AuthorizationDto createAuthorization(@Context UriInfo context, AuthorizationCreateDto dto); @OPTIONS @Produces(MediaType.APPLICATION_JSON) ResourceOptionsDto availableOperations(@Context UriInfo context); }
/* * * 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.qpid.proton.codec.messaging; import java.util.AbstractList; import java.util.Date; import java.util.List; import org.apache.qpid.proton.amqp.Binary; import org.apache.qpid.proton.amqp.Symbol; import org.apache.qpid.proton.amqp.UnsignedInteger; import org.apache.qpid.proton.amqp.UnsignedLong; import org.apache.qpid.proton.amqp.messaging.Properties; import org.apache.qpid.proton.codec.AbstractDescribedType; import org.apache.qpid.proton.codec.Decoder; import org.apache.qpid.proton.codec.DescribedTypeConstructor; import org.apache.qpid.proton.codec.EncoderImpl; public class PropertiesType extends AbstractDescribedType<Properties,List> implements DescribedTypeConstructor<Properties> { private static final Object[] DESCRIPTORS = { UnsignedLong.valueOf(0x0000000000000073L), Symbol.valueOf("amqp:properties:list"), }; private static final UnsignedLong DESCRIPTOR = UnsignedLong.valueOf(0x0000000000000073L); private PropertiesType(EncoderImpl encoder) { super(encoder); } public UnsignedLong getDescriptor() { return DESCRIPTOR; } @Override protected List wrap(Properties val) { return new PropertiesWrapper(val); } private static final class PropertiesWrapper extends AbstractList { private Properties _impl; public PropertiesWrapper(Properties propertiesType) { _impl = propertiesType; } public Object get(final int index) { switch(index) { case 0: return _impl.getMessageId(); case 1: return _impl.getUserId(); case 2: return _impl.getTo(); case 3: return _impl.getSubject(); case 4: return _impl.getReplyTo(); case 5: return _impl.getCorrelationId(); case 6: return _impl.getContentType(); case 7: return _impl.getContentEncoding(); case 8: return _impl.getAbsoluteExpiryTime(); case 9: return _impl.getCreationTime(); case 10: return _impl.getGroupId(); case 11: return _impl.getGroupSequence(); case 12: return _impl.getReplyToGroupId(); } throw new IllegalStateException("Unknown index " + index); } public int size() { return _impl.getReplyToGroupId() != null ? 13 : _impl.getGroupSequence() != null ? 12 : _impl.getGroupId() != null ? 11 : _impl.getCreationTime() != null ? 10 : _impl.getAbsoluteExpiryTime() != null ? 9 : _impl.getContentEncoding() != null ? 8 : _impl.getContentType() != null ? 7 : _impl.getCorrelationId() != null ? 6 : _impl.getReplyTo() != null ? 5 : _impl.getSubject() != null ? 4 : _impl.getTo() != null ? 3 : _impl.getUserId() != null ? 2 : _impl.getMessageId() != null ? 1 : 0; } } public Properties newInstance(Object described) { List l = (List) described; Properties o = new Properties(); switch(13 - l.size()) { case 0: o.setReplyToGroupId( (String) l.get( 12 ) ); case 1: o.setGroupSequence( (UnsignedInteger) l.get( 11 ) ); case 2: o.setGroupId( (String) l.get( 10 ) ); case 3: o.setCreationTime( (Date) l.get( 9 ) ); case 4: o.setAbsoluteExpiryTime( (Date) l.get( 8 ) ); case 5: o.setContentEncoding( (Symbol) l.get( 7 ) ); case 6: o.setContentType( (Symbol) l.get( 6 ) ); case 7: o.setCorrelationId( (Object) l.get( 5 ) ); case 8: o.setReplyTo( (String) l.get( 4 ) ); case 9: o.setSubject( (String) l.get( 3 ) ); case 10: o.setTo( (String) l.get( 2 ) ); case 11: o.setUserId( (Binary) l.get( 1 ) ); case 12: o.setMessageId( (Object) l.get( 0 ) ); } return o; } public Class<Properties> getTypeClass() { return Properties.class; } public static void register(Decoder decoder, EncoderImpl encoder) { PropertiesType type = new PropertiesType(encoder); for(Object descriptor : DESCRIPTORS) { decoder.register(descriptor, type); } encoder.register(type); } }
/** * Copyright 2007-2016, Kaazing Corporation. 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 org.kaazing.gateway.transport.wsn.autobahn.framing; import static org.kaazing.test.util.ITUtil.createRuleChain; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestRule; import org.kaazing.gateway.server.test.GatewayRule; import org.kaazing.gateway.server.test.config.GatewayConfiguration; import org.kaazing.gateway.server.test.config.builder.GatewayConfigurationBuilder; import org.kaazing.k3po.junit.annotation.Specification; import org.kaazing.k3po.junit.rules.K3poRule; public class FramingTextMessagesIT { private K3poRule robot = new K3poRule(); private GatewayRule gateway = new GatewayRule() { { GatewayConfiguration configuration = new GatewayConfigurationBuilder() .service() .accept("ws://localhost:8555/echo") .type("echo") .done() .done(); init(configuration); } }; @Rule public TestRule chain = createRuleChain(gateway, robot); @Specification("sendTextMessageWithPayloadLength125") @Test(timeout = 5000) public void sendTextMessageWithPayloadLength125() throws Exception { robot.finish(); } @Specification("sendTextMessageWithPayloadLength126") @Test(timeout = 5000) public void sendTextMessageWithPayloadLength126() throws Exception { robot.finish(); } @Specification("sendTextMessageWithPayloadLength127") @Test(timeout = 5000) public void sendTextMessageWithPayloadLength127() throws Exception { robot.finish(); } @Specification("sendTextMessageWithPayloadLength128") @Test(timeout = 5000) public void sendTextMessageWithPayloadLength128() throws Exception { robot.finish(); } @Specification("sendTextMessageWithPayloadLength65535") @Test(timeout = 5000) public void sendTextMessageWithPayloadLength65535() throws Exception { robot.finish(); } @Specification("sendTextMessageWithPayloadLength65536") @Test(timeout = 5000) public void sendTextMessageWithPayloadLength65536() throws Exception { robot.finish(); } @Specification("sendTextMessageWithPayloadLength65536InChopsOf997Octets") @Test(timeout = 5000) public void sendTextMessageWithPayloadLength65536InChopsOf997Octets() throws Exception { robot.finish(); } @Ignore("KG-12366") @Specification("sendTextMessageWithEmptyPayload") @Test(timeout = 5000) public void sendTextMessageWithEmptyPayload() throws Exception { robot.finish(); } }
package automation // Copyright (c) Microsoft and contributors. 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. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( "context" "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/azure" "github.com/Azure/go-autorest/autorest/validation" "net/http" ) // ConnectionClient is the automation Client type ConnectionClient struct { BaseClient } // NewConnectionClient creates an instance of the ConnectionClient client. func NewConnectionClient(subscriptionID string, resourceGroupName string, clientRequestID string, automationAccountName string) ConnectionClient { return NewConnectionClientWithBaseURI(DefaultBaseURI, subscriptionID, resourceGroupName, clientRequestID, automationAccountName) } // NewConnectionClientWithBaseURI creates an instance of the ConnectionClient client. func NewConnectionClientWithBaseURI(baseURI string, subscriptionID string, resourceGroupName string, clientRequestID string, automationAccountName string) ConnectionClient { return ConnectionClient{NewWithBaseURI(baseURI, subscriptionID, resourceGroupName, clientRequestID, automationAccountName)} } // CreateOrUpdate create or update a connection. // // automationAccountName is the automation account name. connectionName is the parameters supplied to the create or // update connection operation. parameters is the parameters supplied to the create or update connection operation. func (client ConnectionClient) CreateOrUpdate(ctx context.Context, automationAccountName string, connectionName string, parameters ConnectionCreateOrUpdateParameters) (result Connection, err error) { if err := validation.Validate([]validation.Validation{ {TargetValue: client.ResourceGroupName, Constraints: []validation.Constraint{{Target: "client.ResourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._]+$`, Chain: nil}}}, {TargetValue: parameters, Constraints: []validation.Constraint{{Target: "parameters.Name", Name: validation.Null, Rule: true, Chain: nil}, {Target: "parameters.ConnectionCreateOrUpdateProperties", Name: validation.Null, Rule: true, Chain: []validation.Constraint{{Target: "parameters.ConnectionCreateOrUpdateProperties.ConnectionType", Name: validation.Null, Rule: true, Chain: nil}}}}}}); err != nil { return result, validation.NewError("automation.ConnectionClient", "CreateOrUpdate", err.Error()) } req, err := client.CreateOrUpdatePreparer(ctx, automationAccountName, connectionName, parameters) if err != nil { err = autorest.NewErrorWithError(err, "automation.ConnectionClient", "CreateOrUpdate", nil, "Failure preparing request") return } resp, err := client.CreateOrUpdateSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "automation.ConnectionClient", "CreateOrUpdate", resp, "Failure sending request") return } result, err = client.CreateOrUpdateResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "automation.ConnectionClient", "CreateOrUpdate", resp, "Failure responding to request") } return } // CreateOrUpdatePreparer prepares the CreateOrUpdate request. func (client ConnectionClient) CreateOrUpdatePreparer(ctx context.Context, automationAccountName string, connectionName string, parameters ConnectionCreateOrUpdateParameters) (*http.Request, error) { pathParameters := map[string]interface{}{ "automationAccountName": autorest.Encode("path", automationAccountName), "connectionName": autorest.Encode("path", connectionName), "resourceGroupName": autorest.Encode("path", client.ResourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2015-10-31" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsJSON(), autorest.AsPut(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/connections/{connectionName}", pathParameters), autorest.WithJSON(parameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the // http.Response Body if it receives an error. func (client ConnectionClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { return autorest.SendWithSender(client, req, azure.DoRetryWithRegistration(client.Client)) } // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always // closes the http.Response Body. func (client ConnectionClient) CreateOrUpdateResponder(resp *http.Response) (result Connection, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // Delete delete the connection. // // automationAccountName is the automation account name. connectionName is the name of connection. func (client ConnectionClient) Delete(ctx context.Context, automationAccountName string, connectionName string) (result Connection, err error) { if err := validation.Validate([]validation.Validation{ {TargetValue: client.ResourceGroupName, Constraints: []validation.Constraint{{Target: "client.ResourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._]+$`, Chain: nil}}}}); err != nil { return result, validation.NewError("automation.ConnectionClient", "Delete", err.Error()) } req, err := client.DeletePreparer(ctx, automationAccountName, connectionName) if err != nil { err = autorest.NewErrorWithError(err, "automation.ConnectionClient", "Delete", nil, "Failure preparing request") return } resp, err := client.DeleteSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "automation.ConnectionClient", "Delete", resp, "Failure sending request") return } result, err = client.DeleteResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "automation.ConnectionClient", "Delete", resp, "Failure responding to request") } return } // DeletePreparer prepares the Delete request. func (client ConnectionClient) DeletePreparer(ctx context.Context, automationAccountName string, connectionName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "automationAccountName": autorest.Encode("path", automationAccountName), "connectionName": autorest.Encode("path", connectionName), "resourceGroupName": autorest.Encode("path", client.ResourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2015-10-31" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsDelete(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/connections/{connectionName}", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // DeleteSender sends the Delete request. The method will close the // http.Response Body if it receives an error. func (client ConnectionClient) DeleteSender(req *http.Request) (*http.Response, error) { return autorest.SendWithSender(client, req, azure.DoRetryWithRegistration(client.Client)) } // DeleteResponder handles the response to the Delete request. The method always // closes the http.Response Body. func (client ConnectionClient) DeleteResponder(resp *http.Response) (result Connection, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // Get retrieve the connection identified by connection name. // // automationAccountName is the automation account name. connectionName is the name of connection. func (client ConnectionClient) Get(ctx context.Context, automationAccountName string, connectionName string) (result Connection, err error) { if err := validation.Validate([]validation.Validation{ {TargetValue: client.ResourceGroupName, Constraints: []validation.Constraint{{Target: "client.ResourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._]+$`, Chain: nil}}}}); err != nil { return result, validation.NewError("automation.ConnectionClient", "Get", err.Error()) } req, err := client.GetPreparer(ctx, automationAccountName, connectionName) if err != nil { err = autorest.NewErrorWithError(err, "automation.ConnectionClient", "Get", nil, "Failure preparing request") return } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "automation.ConnectionClient", "Get", resp, "Failure sending request") return } result, err = client.GetResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "automation.ConnectionClient", "Get", resp, "Failure responding to request") } return } // GetPreparer prepares the Get request. func (client ConnectionClient) GetPreparer(ctx context.Context, automationAccountName string, connectionName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "automationAccountName": autorest.Encode("path", automationAccountName), "connectionName": autorest.Encode("path", connectionName), "resourceGroupName": autorest.Encode("path", client.ResourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2015-10-31" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/connections/{connectionName}", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client ConnectionClient) GetSender(req *http.Request) (*http.Response, error) { return autorest.SendWithSender(client, req, azure.DoRetryWithRegistration(client.Client)) } // GetResponder handles the response to the Get request. The method always // closes the http.Response Body. func (client ConnectionClient) GetResponder(resp *http.Response) (result Connection, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // ListByAutomationAccount retrieve a list of connections. // // automationAccountName is the automation account name. func (client ConnectionClient) ListByAutomationAccount(ctx context.Context, automationAccountName string) (result ConnectionListResultPage, err error) { if err := validation.Validate([]validation.Validation{ {TargetValue: client.ResourceGroupName, Constraints: []validation.Constraint{{Target: "client.ResourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._]+$`, Chain: nil}}}}); err != nil { return result, validation.NewError("automation.ConnectionClient", "ListByAutomationAccount", err.Error()) } result.fn = client.listByAutomationAccountNextResults req, err := client.ListByAutomationAccountPreparer(ctx, automationAccountName) if err != nil { err = autorest.NewErrorWithError(err, "automation.ConnectionClient", "ListByAutomationAccount", nil, "Failure preparing request") return } resp, err := client.ListByAutomationAccountSender(req) if err != nil { result.clr.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "automation.ConnectionClient", "ListByAutomationAccount", resp, "Failure sending request") return } result.clr, err = client.ListByAutomationAccountResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "automation.ConnectionClient", "ListByAutomationAccount", resp, "Failure responding to request") } return } // ListByAutomationAccountPreparer prepares the ListByAutomationAccount request. func (client ConnectionClient) ListByAutomationAccountPreparer(ctx context.Context, automationAccountName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "automationAccountName": autorest.Encode("path", automationAccountName), "resourceGroupName": autorest.Encode("path", client.ResourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2015-10-31" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/connections", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // ListByAutomationAccountSender sends the ListByAutomationAccount request. The method will close the // http.Response Body if it receives an error. func (client ConnectionClient) ListByAutomationAccountSender(req *http.Request) (*http.Response, error) { return autorest.SendWithSender(client, req, azure.DoRetryWithRegistration(client.Client)) } // ListByAutomationAccountResponder handles the response to the ListByAutomationAccount request. The method always // closes the http.Response Body. func (client ConnectionClient) ListByAutomationAccountResponder(resp *http.Response) (result ConnectionListResult, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // listByAutomationAccountNextResults retrieves the next set of results, if any. func (client ConnectionClient) listByAutomationAccountNextResults(lastResults ConnectionListResult) (result ConnectionListResult, err error) { req, err := lastResults.connectionListResultPreparer() if err != nil { return result, autorest.NewErrorWithError(err, "automation.ConnectionClient", "listByAutomationAccountNextResults", nil, "Failure preparing next results request") } if req == nil { return } resp, err := client.ListByAutomationAccountSender(req) if err != nil { result.Response = autorest.Response{Response: resp} return result, autorest.NewErrorWithError(err, "automation.ConnectionClient", "listByAutomationAccountNextResults", resp, "Failure sending next results request") } result, err = client.ListByAutomationAccountResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "automation.ConnectionClient", "listByAutomationAccountNextResults", resp, "Failure responding to next results request") } return } // ListByAutomationAccountComplete enumerates all values, automatically crossing page boundaries as required. func (client ConnectionClient) ListByAutomationAccountComplete(ctx context.Context, automationAccountName string) (result ConnectionListResultIterator, err error) { result.page, err = client.ListByAutomationAccount(ctx, automationAccountName) return } // Update update a connection. // // automationAccountName is the automation account name. connectionName is the parameters supplied to the update a // connection operation. parameters is the parameters supplied to the update a connection operation. func (client ConnectionClient) Update(ctx context.Context, automationAccountName string, connectionName string, parameters ConnectionUpdateParameters) (result Connection, err error) { if err := validation.Validate([]validation.Validation{ {TargetValue: client.ResourceGroupName, Constraints: []validation.Constraint{{Target: "client.ResourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._]+$`, Chain: nil}}}}); err != nil { return result, validation.NewError("automation.ConnectionClient", "Update", err.Error()) } req, err := client.UpdatePreparer(ctx, automationAccountName, connectionName, parameters) if err != nil { err = autorest.NewErrorWithError(err, "automation.ConnectionClient", "Update", nil, "Failure preparing request") return } resp, err := client.UpdateSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "automation.ConnectionClient", "Update", resp, "Failure sending request") return } result, err = client.UpdateResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "automation.ConnectionClient", "Update", resp, "Failure responding to request") } return } // UpdatePreparer prepares the Update request. func (client ConnectionClient) UpdatePreparer(ctx context.Context, automationAccountName string, connectionName string, parameters ConnectionUpdateParameters) (*http.Request, error) { pathParameters := map[string]interface{}{ "automationAccountName": autorest.Encode("path", automationAccountName), "connectionName": autorest.Encode("path", connectionName), "resourceGroupName": autorest.Encode("path", client.ResourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2015-10-31" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsJSON(), autorest.AsPatch(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/connections/{connectionName}", pathParameters), autorest.WithJSON(parameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // UpdateSender sends the Update request. The method will close the // http.Response Body if it receives an error. func (client ConnectionClient) UpdateSender(req *http.Request) (*http.Response, error) { return autorest.SendWithSender(client, req, azure.DoRetryWithRegistration(client.Client)) } // UpdateResponder handles the response to the Update request. The method always // closes the http.Response Body. func (client ConnectionClient) UpdateResponder(resp *http.Response) (result Connection, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return }
package org.newdawn.slick.geom; import org.newdawn.slick.Image; import org.newdawn.slick.ShapeFill; import org.newdawn.slick.opengl.Texture; import org.newdawn.slick.opengl.TextureImpl; import org.newdawn.slick.opengl.renderer.LineStripRenderer; import org.newdawn.slick.opengl.renderer.Renderer; import org.newdawn.slick.opengl.renderer.SGL; /** * @author Mark Bernard * * Use this class to render shpaes directly to OpenGL. Allows you to bypass the Graphics class. */ public final class ShapeRenderer { /** The renderer to use for all GL operations */ private static SGL GL = Renderer.get(); /** The renderer to use line strips */ private static LineStripRenderer LSR = Renderer.getLineStripRenderer(); /** * Draw the outline of the given shape. Only the vertices are set. * The colour has to be set independently of this method. * * @param shape The shape to draw. */ public static final void draw(Shape shape) { Texture t = TextureImpl.getLastBind(); TextureImpl.bindNone(); float points[] = shape.getPoints(); LSR.start(); for(int i=0;i<points.length;i+=2) { LSR.vertex(points[i], points[i + 1]); } if (shape.closed()) { LSR.vertex(points[0], points[1]); } LSR.end(); if (t == null) { TextureImpl.bindNone(); } else { t.bind(); } } /** * Draw the outline of the given shape. Only the vertices are set. * The colour has to be set independently of this method. * * @param shape The shape to draw. * @param fill The fill to apply */ public static final void draw(Shape shape, ShapeFill fill) { float points[] = shape.getPoints(); Texture t = TextureImpl.getLastBind(); TextureImpl.bindNone(); float center[] = shape.getCenter(); GL.glBegin(SGL.GL_LINE_STRIP); for(int i=0;i<points.length;i+=2) { fill.colorAt(shape, points[i], points[i + 1]).bind(); Vector2f offset = fill.getOffsetAt(shape, points[i], points[i + 1]); GL.glVertex2f(points[i] + offset.x, points[i + 1] + offset.y); } if (shape.closed()) { fill.colorAt(shape, points[0], points[1]).bind(); Vector2f offset = fill.getOffsetAt(shape, points[0], points[1]); GL.glVertex2f(points[0] + offset.x, points[1] + offset.y); } GL.glEnd(); if (t == null) { TextureImpl.bindNone(); } else { t.bind(); } } /** * Check there are enough points to fill * * @param shape THe shape we're drawing * @return True if the fill is valid */ public static boolean validFill(Shape shape) { if (shape.getTriangles() == null) { return false; } return shape.getTriangles().getTriangleCount() != 0; } /** * Draw the the given shape filled in. Only the vertices are set. * The colour has to be set independently of this method. * * @param shape The shape to fill. */ public static final void fill(Shape shape) { if (!validFill(shape)) { return; } Texture t = TextureImpl.getLastBind(); TextureImpl.bindNone(); fill(shape, new PointCallback() { public float[] preRenderPoint(Shape shape, float x, float y) { // do nothing, we're just filling the shape this time return null; } }); if (t == null) { TextureImpl.bindNone(); } else { t.bind(); } } /** * Draw the the given shape filled in. Only the vertices are set. * The colour has to be set independently of this method. * * @param shape The shape to fill. * @param callback The callback that will be invoked for each shape point */ private static final void fill(Shape shape, PointCallback callback) { Triangulator tris = shape.getTriangles(); GL.glBegin(SGL.GL_TRIANGLES); for (int i=0;i<tris.getTriangleCount();i++) { for (int p=0;p<3;p++) { float[] pt = tris.getTrianglePoint(i, p); float[] np = callback.preRenderPoint(shape, pt[0],pt[1]); if (np == null) { GL.glVertex2f(pt[0],pt[1]); } else { GL.glVertex2f(np[0],np[1]); } } } GL.glEnd(); } /** * Draw the the given shape filled in with a texture. Only the vertices are set. * The colour has to be set independently of this method. * * @param shape The shape to texture. * @param image The image to tile across the shape */ public static final void texture(Shape shape, Image image) { texture(shape, image, 0.01f, 0.01f); } /** * Draw the the given shape filled in with a texture. Only the vertices are set. * The colour has to be set independently of this method. This method is required to * fit the texture once across the shape. * * @param shape The shape to texture. * @param image The image to tile across the shape */ public static final void textureFit(Shape shape, Image image) { textureFit(shape, image,1f,1f); } /** * Draw the the given shape filled in with a texture. Only the vertices are set. * The colour has to be set independently of this method. * * @param shape The shape to texture. * @param image The image to tile across the shape * @param scaleX The scale to apply on the x axis for texturing * @param scaleY The scale to apply on the y axis for texturing */ public static final void texture(Shape shape, final Image image, final float scaleX, final float scaleY) { if (!validFill(shape)) { return; } final Texture t = TextureImpl.getLastBind(); image.getTexture().bind(); fill(shape, new PointCallback() { public float[] preRenderPoint(Shape shape, float x, float y) { float tx = x * scaleX; float ty = y * scaleY; tx = image.getTextureOffsetX() + (image.getTextureWidth() * tx); ty = image.getTextureOffsetY() + (image.getTextureHeight() * ty); GL.glTexCoord2f(tx, ty); return null; } }); float points[] = shape.getPoints(); if (t == null) { TextureImpl.bindNone(); } else { t.bind(); } } /** * Draw the the given shape filled in with a texture. Only the vertices are set. * The colour has to be set independently of this method. This method is required to * fit the texture scaleX times across the shape and scaleY times down the shape. * * @param shape The shape to texture. * @param image The image to tile across the shape * @param scaleX The scale to apply on the x axis for texturing * @param scaleY The scale to apply on the y axis for texturing */ public static final void textureFit(Shape shape, final Image image, final float scaleX, final float scaleY) { if (!validFill(shape)) { return; } float points[] = shape.getPoints(); Texture t = TextureImpl.getLastBind(); image.getTexture().bind(); final float minX = shape.getX(); final float minY = shape.getY(); final float maxX = shape.getMaxX() - minX; final float maxY = shape.getMaxY() - minY; fill(shape, new PointCallback() { public float[] preRenderPoint(Shape shape, float x, float y) { x -= shape.getMinX(); y -= shape.getMinY(); x /= (shape.getMaxX() - shape.getMinX()); y /= (shape.getMaxY() - shape.getMinY()); float tx = x * scaleX; float ty = y * scaleY; tx = image.getTextureOffsetX() + (image.getTextureWidth() * tx); ty = image.getTextureOffsetY() + (image.getTextureHeight() * ty); GL.glTexCoord2f(tx, ty); return null; } }); if (t == null) { TextureImpl.bindNone(); } else { t.bind(); } } /** * Draw the the given shape filled in. Only the vertices are set. * The colour has to be set independently of this method. * * @param shape The shape to fill. * @param fill The fill to apply */ public static final void fill(final Shape shape, final ShapeFill fill) { if (!validFill(shape)) { return; } Texture t = TextureImpl.getLastBind(); TextureImpl.bindNone(); final float center[] = shape.getCenter(); fill(shape, new PointCallback() { public float[] preRenderPoint(Shape shape, float x, float y) { fill.colorAt(shape, x, y).bind(); Vector2f offset = fill.getOffsetAt(shape, x, y); return new float[] {offset.x + x,offset.y + y}; } }); if (t == null) { TextureImpl.bindNone(); } else { t.bind(); } } /** * Draw the the given shape filled in with a texture. Only the vertices are set. * The colour has to be set independently of this method. * * @param shape The shape to texture. * @param image The image to tile across the shape * @param scaleX The scale to apply on the x axis for texturing * @param scaleY The scale to apply on the y axis for texturing * @param fill The fill to apply */ public static final void texture(final Shape shape, final Image image, final float scaleX, final float scaleY, final ShapeFill fill) { if (!validFill(shape)) { return; } Texture t = TextureImpl.getLastBind(); image.getTexture().bind(); final float center[] = shape.getCenter(); fill(shape, new PointCallback() { public float[] preRenderPoint(Shape shape, float x, float y) { fill.colorAt(shape, x - center[0], y - center[1]).bind(); Vector2f offset = fill.getOffsetAt(shape, x, y); x += offset.x; y += offset.y; float tx = x * scaleX; float ty = y * scaleY; tx = image.getTextureOffsetX() + (image.getTextureWidth() * tx); ty = image.getTextureOffsetY() + (image.getTextureHeight() * ty); GL.glTexCoord2f(tx, ty); return new float[] {offset.x + x,offset.y + y}; } }); if (t == null) { TextureImpl.bindNone(); } else { t.bind(); } } /** * Draw the the given shape filled in with a texture. Only the vertices are set. * The colour has to be set independently of this method. * * @param shape The shape to texture. * @param image The image to tile across the shape * @param gen The texture coordinate generator to create coordiantes for the shape */ public static final void texture(final Shape shape, Image image, final TexCoordGenerator gen) { Texture t = TextureImpl.getLastBind(); image.getTexture().bind(); final float center[] = shape.getCenter(); fill(shape, new PointCallback() { public float[] preRenderPoint(Shape shape, float x, float y) { Vector2f tex = gen.getCoordFor(x, y); GL.glTexCoord2f(tex.x, tex.y); return new float[] {x,y}; } }); if (t == null) { TextureImpl.bindNone(); } else { t.bind(); } } /** * Description of some feature that will be applied to each point render * * @author kevin */ private static interface PointCallback { /** * Apply feature before the call to glVertex * * @param shape The shape the point belongs to * @param x The x poisiton the vertex will be at * @param y The y position the vertex will be at * @return The new coordinates of null */ float[] preRenderPoint(Shape shape, float x, float y); } }
import Data.Bits ((.&.)) flags :: Int -> Int flags x | x .&. 128 > 0 = 12 | otherwise = 13 {-# NOINLINE flags #-} main :: IO () main = print (flags 255)
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <mutex> // template <class Mutex> class unique_lock; // explicit unique_lock(mutex_type& m); #include <mutex> #include <thread> #include <cstdlib> #include <cassert> std::mutex m; typedef std::chrono::system_clock Clock; typedef Clock::time_point time_point; typedef Clock::duration duration; typedef std::chrono::milliseconds ms; typedef std::chrono::nanoseconds ns; void f() { time_point t0 = Clock::now(); time_point t1; { std::unique_lock<std::mutex> ul(m); t1 = Clock::now(); } ns d = t1 - t0 - ms(250); assert(d < ms(50)); // within 50ms } int main() { m.lock(); std::thread t(f); std::this_thread::sleep_for(ms(250)); m.unlock(); t.join(); }
// Copyright 2009 the Sputnik authors. All rights reserved. /** * Operator x ? y : z uses GetValue * * @path ch11/11.12/S11.12_A2.1_T3.js * @description If ToBoolean(x) is true and GetBase(y) is null, throw ReferenceError */ //CHECK#1 try { true ? y : false; $ERROR('#1.1: true ? y : false throw ReferenceError. Actual: ' + (true ? y : false)); } catch (e) { if ((e instanceof ReferenceError) !== true) { $ERROR('#1.2: true ? y : false throw ReferenceError. Actual: ' + (e)); } }
/* Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ /* Restore the dialog visibility */ body .cke_dialog { visibility: visible; } /* Force Gecko to consider table as positioned */ .cke_skin_office2003 table.cke_dialog.cke_browser_gecko { display:block; } .cke_skin_office2003 .cke_dialog_body { margin-left: 16px; margin-right: 16px; margin-top: 2px; margin-bottom: 20px; z-index: 1; /* 'cke_dialog' element has been fixed positioned in all but IE6, while we need it to be positioned to hold e.g. close button. */ position: relative; _position: static; } .cke_skin_office2003 .cke_dialog_tl, .cke_skin_office2003 .cke_dialog_tr, .cke_skin_office2003 .cke_dialog_tc, .cke_skin_office2003 .cke_dialog_bl, .cke_skin_office2003 .cke_dialog_br, .cke_skin_office2003 .cke_dialog_bc { background-image: url(images/sprites.png); background-repeat: no-repeat; position: absolute; /* IE6 does not support full color transparent PNG. */ _background-image: url(images/sprites_ie6.png); /* Dialog corner parts require a negative z-index to avoid covering dialog body. (#4954) */ _z-index: -1; } .cke_skin_office2003 .cke_dialog_tl { background-position: -16px -16px; height: 16px; width: 16px; top: 0; left: 0; } .cke_skin_office2003 .cke_rtl .cke_dialog_tl { background-position: -16px -397px; } .cke_skin_office2003 .cke_dialog_tr { background-position: -16px -76px; height: 16px; width: 16px; top: 0; right: 0; } .cke_skin_office2003 .cke_rtl .cke_dialog_tr { background-position: -16px -457px; } .cke_skin_office2003 .cke_dialog_tc { background-position: 0 -136px; background-repeat: repeat-x; height: 16px; top: 0; left: 16px; right: 16px; } .cke_skin_office2003 .cke_dialog_bl { background-position: -16px -196px; height: 51px; width: 30px; bottom: 0; left: 0; } .cke_skin_office2003 .cke_rtl .cke_dialog_bl { background-position: -16px -517px; } .cke_skin_office2003 .cke_dialog_br { background-position: -16px -263px; height: 51px; width: 30px; bottom: 0; right: 0; } .cke_skin_office2003 .cke_rtl .cke_dialog_br { background-position: -16px -584px; } .cke_skin_office2003 .cke_dialog_bc { background-position: 0 -330px; background-repeat: repeat-x; height: 51px; bottom: 0; left: 30px; right: 30px; } .cke_skin_office2003 .cke_dialog_ml, .cke_skin_office2003 .cke_dialog_mr { background-image: url(images/dialog_sides.png); background-repeat: repeat-y; position: absolute; width: 16px; top: 16px; bottom: 51px; /* IE6 does not support full color transparent PNG. */ _background-image: url(images/dialog_sides.gif); /* IE quirks gets confused when we have both top and bottom. */ _top: auto; } .cke_skin_office2003 .cke_rtl .cke_dialog_ml, .cke_skin_office2003 .cke_rtl .cke_dialog_mr { background-image: url(images/dialog_sides_rtl.png); /* IE6 does not support full color transparent PNG. */ _background-image: url(images/dialog_sides.gif); } .cke_skin_office2003 .cke_dialog_ml { background-position: 0 0; left: 0; } .cke_skin_office2003 .cke_dialog_mr { background-position: -16px 0; right: 0; } .cke_skin_office2003 .cke_browser_iequirks .cke_dialog_ml, .cke_skin_office2003 .cke_browser_iequirks .cke_dialog_mr { margin-top: 3px; } .cke_skin_office2003 .cke_dialog_title { background-image: url(images/sprites.png); _background-image: url(images/sprites_ie6.png); background-position: 0 -678px; background-repeat: repeat-x; font-weight: bold; font-size: 14pt; color: #0E3460; background-color: #8db1ff; padding: 3px 10px 26px 10px; cursor: move; position: relative; } .cke_skin_office2003 .cke_browser_ie.cke_rtl .cke_dialog_title { position: static !important; unicode-bidi: bidi-override; } .cke_skin_office2003 .cke_dialog_contents { background-color: #f7f8fd; border: #2b66c9 1px solid; overflow: auto; padding: 5px 10px; } .cke_skin_office2003 .cke_dialog_footer { background-color: #8db1ff; text-align: right; } .cke_skin_office2003 .cke_rtl .cke_dialog_footer { text-align: left; } /* tabs */ .cke_skin_office2003 .cke_dialog_tabs { height: 23px; background-color: #8db1ff; display: inline-block; margin-left:10px; margin-right:10px; margin-top:-23px; position: absolute; z-index: 2; } .cke_skin_office2003 .cke_rtl .cke_dialog_tabs { right: 10px; } .cke_skin_office2003 a.cke_dialog_tab, .cke_skin_office2003 a:link.cke_dialog_tab, .cke_skin_office2003 a:active.cke_dialog_tab, .cke_skin_office2003 a:hover.cke_dialog_tab, .cke_skin_office2003 a:visited.cke_dialog_tab { color: #0E3460; border-left: 1px solid #2b66c9; border-right: 1px solid #2b66c9; border-top: 1px solid #2b66c9; height: 14px; padding: 4px 5px; display: inline-block; cursor: pointer; } /* Gecko 1.8 layout workaround. */ .cke_skin_office2003 .cke_browser_gecko18 a.cke_dialog_tab, .cke_skin_office2003 .cke_browser_gecko18 a:link.cke_dialog_tab, .cke_skin_office2003 .cke_browser_gecko18 a:active.cke_dialog_tab, .cke_skin_office2003 .cke_browser_gecko18 a:hover.cke_dialog_tab, .cke_skin_office2003 .cke_browser_gecko18 a:visited.cke_dialog_tab { display: inline; position: relative; top: 6px; } .cke_skin_office2003 a:hover.cke_dialog_tab { background-color: #f7f8fd; } .cke_skin_office2003 .cke_hc a:hover.cke_dialog_tab { padding: 2px 3px !important; border-width: 3px; } .cke_skin_office2003 a.cke_dialog_tab_selected, .cke_skin_office2003 a:link.cke_dialog_tab_selected, .cke_skin_office2003 a:active.cke_dialog_tab_selected, .cke_skin_office2003 a:hover.cke_dialog_tab_selected, .cke_skin_office2003 a:visited.cke_dialog_tab_selected { border-bottom: 1px solid #f7f8fd; background-color: #f7f8fd; font-weight: bold; cursor: default; } .cke_skin_office2003 .cke_hc a.cke_dialog_tab_selected, .cke_skin_office2003 .cke_hc a:link.cke_dialog_tab_selected, .cke_skin_office2003 .cke_hc a:active.cke_dialog_tab_selected, .cke_skin_office2003 .cke_hc a:hover.cke_dialog_tab_selected, .cke_skin_office2003 .cke_hc a:visited.cke_dialog_tab_selected { padding: 2px 3px !important; border-width: 3px; } /* single_page */ .cke_skin_office2003 .cke_single_page .cke_dialog_tabs { display: none; } .cke_skin_office2003 .cke_hc .cke_dialog_tabs a, .cke_skin_office2003 .cke_hc .cke_dialog_footer a { opacity: 1.0; filter: alpha(opacity=100); border: 1px solid white; } .cke_skin_office2003 .cke_single_page .cke_dialog_title { padding-bottom: 3px; } .cke_skin_office2003 .cke_dialog_ui_vbox table, .cke_skin_office2003 .cke_dialog_ui_hbox table { margin: auto; } .cke_skin_office2003 .cke_dialog_ui_vbox_child { padding: 5px 0px; } .cke_skin_office2003 input.cke_dialog_ui_input_text, .cke_skin_office2003 input.cke_dialog_ui_input_password { background-color: white; border: none; padding: 0px; width: 100%; height: 14px; } .cke_skin_office2003 div.cke_dialog_ui_input_text, .cke_skin_office2003 div.cke_dialog_ui_input_password { background-color: white; border: 1px solid #a0a0a0; padding: 1px 0px; } .cke_skin_office2003 .cke_browser_gecko.cke_hc div.cke_dialog_ui_input_text, .cke_skin_office2003 .cke_browser_gecko.cke_hc div.cke_dialog_ui_input_password { border-width: 0px; } .cke_skin_office2003 .cke_browser_gecko18.cke_hc div.cke_dialog_ui_input_text, .cke_skin_office2003 .cke_browser_gecko18.cke_hc div.cke_dialog_ui_input_password { border-width: 1px; } .cke_skin_office2003 textarea.cke_dialog_ui_input_textarea { background-color: white; border: none; padding: 0px; width: 100%; /* * IE6 BUG: Scrollbars in textareas can overflow even if the outer DIV is set to overflow:hidden. * So leave 1% width for the scrollbar. In most situations the 1% isn't noticeable by users. */ _width: 99%; overflow: auto; resize: none; } .cke_skin_office2003 div.cke_dialog_ui_input_textarea { background-color: white; border: 1px solid #a0a0a0; padding: 1px 0px; } .cke_skin_office2003 div.cke_disabled .cke_dialog_ui_labeled_content * { background-color : #a0a0a0; cursor : default; } .cke_skin_office2003 .cke_dialog_ui_hbox { width: 100%; } .cke_skin_office2003 .cke_dialog_ui_hbox_first, .cke_skin_office2003 .cke_dialog_ui_hbox_child, .cke_skin_office2003 .cke_dialog_ui_hbox_last { vertical-align: top; } .cke_skin_office2003 .cke_ltr .cke_dialog_ui_hbox_first, .cke_skin_office2003 .cke_ltr .cke_dialog_ui_hbox_child { padding-right: 10px; } .cke_skin_office2003 .cke_rtl .cke_dialog_ui_hbox_first, .cke_skin_office2003 .cke_rtl .cke_dialog_ui_hbox_child { padding-left: 10px; } /* button */ .cke_skin_office2003 a.cke_dialog_ui_button { border-collapse: separate; cursor: default; } .cke_skin_office2003 span.cke_dialog_ui_button { background-image: url(images/sprites.png); _background-image: url(images/sprites_ie6.png); background-position: 0 -678px; background-repeat: repeat-x; border: #0E3460 1px solid; padding: 2px 10px; text-align: center; color: #0E3460; background-color: #8db1ff; display: inline-block; cursor: default; } /* Gecko 1.8 does not support display: inline-block */ .cke_skin_office2003 .cke_browser_gecko18 .cke_dialog_footer_buttons span.cke_dialog_ui_button { display: block; } .cke_skin_office2003 a.cke_dialog_ui_button span.cke_disabled { border: #898980 1px solid; color: #5e5e55; background-color: #c5c5b3; } .cke_skin_office2003 a:focus span.cke_dialog_ui_button, .cke_skin_office2003 a:active span.cke_dialog_ui_button { background-color: #8db1ff; } .cke_skin_office2003 .cke_hc a:focus span.cke_dialog_ui_button, .cke_skin_office2003 .cke_hc a:active span.cke_dialog_ui_button { border-width: 2px; } .cke_skin_office2003 .cke_dialog_footer_buttons { display: inline-table; margin-right: 12px; margin-left: 12px; width: auto; position: relative; } /* Gecko 1.8 does not support for display: inline-table */ .cke_skin_office2003 .cke_browser_gecko18 .cke_dialog_footer_buttons { display: inline; } .cke_skin_office2003 .cke_dialog_footer_buttons span.cke_dialog_ui_button { width: 60px; margin: 7px 0; } .cke_skin_office2003 strong { font-weight: bold; } /* close_button */ .cke_skin_office2003 a.cke_dialog_close_button, .cke_skin_office2003 a:hover.cke_dialog_close_button, .cke_skin_office2003 .cke_browser_ie6 a.cke_dialog_close_button, .cke_skin_office2003 .cke_browser_ie6 a:hover.cke_dialog_close_button { background-image: url(images/sprites.png); background-repeat: no-repeat; background-position: -20px -655px; position: absolute; cursor: pointer; text-align: center; height: 21px; width: 21px; top: 4px; /* IE6 does not support full color transparent PNG. */ _background-image: url(images/sprites_ie6.png); } .cke_skin_office2003 a.cke_dialog_close_button span { display: none; } .cke_skin_office2003 .cke_ltr a.cke_dialog_close_button { right: 10px; _right: 22px; } .cke_skin_office2003 .cke_rtl a.cke_dialog_close_button, .cke_skin_office2003 .cke_rtl a:hover.cke_dialog_close_button { left: 10px; _left: 16px; _top: 6px; } .cke_skin_office2003 .cke_browser_ie6.cke_rtl a.cke_dialog_close_button, .cke_skin_office2003 .cke_browser_ie6.cke_rtl a:hover.cke_dialog_close_button { position: relative; float: left; margin-top: -55px; margin-left: -7px; } .cke_skin_office2003 .cke_browser_iequirks.cke_rtl.cke_single_page a.cke_dialog_close_button, .cke_skin_office2003 .cke_browser_iequirks.cke_rtl.cke_single_page a:hover.cke_dialog_close_button { margin-top: -32px; } .cke_skin_office2003 .cke_browser_iequirks.cke_ltr a.cke_dialog_close_button, .cke_skin_office2003 .cke_browser_iequirks.cke_ltr a:hover.cke_dialog_close_button { margin-top: 0; } .cke_skin_office2003 .cke_dialog_ui_input_select { border: 1px solid #a0a0a0; background-color: white; } .cke_skin_office2003 iframe.cke_dialog_ui_input_file { width: 100%; height: 25px; } /* * Some utility CSS classes for dialog authors. */ .cke_skin_office2003 .cke_dialog .cke_dark_background { background-color: #eaead1; } .cke_skin_office2003 .cke_dialog .cke_hand { cursor: pointer; } .cke_skin_office2003 .cke_dialog .cke_centered { text-align: center; } .cke_skin_office2003 .cke_dialog a.cke_btn_reset { float: right; background-position: 0 -32px; background-image: url(images/mini.gif); width: 16px; height: 16px; background-repeat: no-repeat; border: 1px none; font-size: 1px; } .cke_skin_office2003 .cke_rtl .cke_dialog a.cke_btn_reset { float: left; } .cke_skin_office2003 .cke_dialog a.cke_btn_locked, .cke_skin_office2003 .cke_dialog a.cke_btn_unlocked { float: left; background-position: 0 0; background-image: url(images/mini.gif); width: 16px; height: 16px; background-repeat: no-repeat; border: none 1px; font-size: 1px; } .cke_skin_office2003 .cke_rtl .cke_dialog a.cke_btn_locked, .cke_skin_office2003 .cke_rtl .cke_dialog a.cke_btn_unlocked { float: right; } .cke_skin_office2003 .cke_dialog a.cke_btn_unlocked { background-position: 0 -16px; background-image: url(images/mini.gif); } .cke_skin_office2003 .cke_dialog .cke_btn_over { border: outset 1px; cursor: pointer; cursor: hand; } .cke_skin_office2003 .cke_dialog #ImagePreviewBox { border : 2px ridge black; overflow : scroll; height : 160px; width : 230px; padding : 2px; background-color : white; } .cke_skin_office2003 .cke_dialog #ImagePreviewBox table td { white-space: normal; } /* Fix iframedialog's height doesn't stretch to 100% #4863.*/ .cke_skin_office2003 .cke_browser_iequirks .cke_dialog_page_contents { _position: absolute; } .cke_skin_office2003 .cke_dialog #ImagePreviewLoader { position: absolute; white-space : normal; overflow : hidden; height : 160px; width : 230px; margin : 2px; padding : 2px; opacity : 0.9; filter : alpha(opacity=90); background-color : #e4e4e4; } .cke_skin_office2003 .cke_dialog #FlashPreviewBox { white-space : normal; border : 2px ridge black; overflow : auto; height : 160px; width : 390px; padding : 2px; background-color : white; } .cke_skin_office2003 .cke_dialog .cke_dark_background { text-align : center; background-color: #eaead1; font-size : 14px; } .cke_skin_office2003 .cke_dialog .cke_light_background { text-align : center; background-color: #ffffbe; } .cke_skin_office2003 .cke_dialog .cke_hand { cursor: pointer; cursor: hand; } .cke_skin_office2003 .cke_disabled { color: #a0a0a0; } /* High Contrast Mode */ .cke_skin_office2003 .cke_hc .cke_dialog_title, .cke_skin_office2003 .cke_hc .cke_dialog_tabs, .cke_skin_office2003 .cke_hc .cke_dialog_contents, .cke_skin_office2003 .cke_hc .cke_dialog_footer { border-left: 1px solid; border-right: 1px solid; } .cke_skin_office2003 .cke_hc .cke_dialog_title { border-top: 1px solid; } .cke_skin_office2003 .cke_hc .cke_dialog_footer { border-bottom: 1px solid; } .cke_skin_office2003 .cke_hc .cke_dialog_close_button span { display: inline; cursor: pointer; cursor: hand; font-weight: bold; position: relative; top: 3px; } .cke_skin_office2003 .cke_dialog_body .cke_label { display: none; } .cke_skin_office2003 .cke_hc .cke_dialog_body .cke_label { display: inline; } .cke_skin_office2003 .cke_hc a.cke_btn_locked, .cke_skin_office2003 .cke_hc a.cke_btn_unlocked, .cke_skin_office2003 .cke_hc a.cke_btn_reset { border-style: solid; float: left; width: auto; height: auto; } .cke_skin_office2003 .cke_rtl.cke_hc a.cke_btn_locked, .cke_skin_office2003 .cke_rtl.cke_hc a.cke_btn_unlocked, .cke_skin_office2003 .cke_rtl.cke_hc a.cke_btn_reset { float: right; }
/* SF16-FMR2 and SF16-FMD2 radio driver for Linux * Copyright (c) 2011 Ondrej Zary * * Original driver was (c) 2000-2002 Ziglio Frediano, freddy77@angelfire.com * but almost nothing remained here after conversion to generic TEA575x * implementation */ #include <linux/delay.h> #include <linux/module.h> /* Modules */ #include <linux/init.h> /* Initdata */ #include <linux/slab.h> #include <linux/ioport.h> /* request_region */ #include <linux/io.h> /* outb, outb_p */ #include <linux/isa.h> #include <linux/pnp.h> #include <sound/tea575x-tuner.h> MODULE_AUTHOR("Ondrej Zary"); MODULE_DESCRIPTION("MediaForte SF16-FMR2 and SF16-FMD2 FM radio card driver"); MODULE_LICENSE("GPL"); /* these cards can only use two different ports (0x384 and 0x284) */ #define FMR2_MAX 2 static int radio_nr[FMR2_MAX] = { [0 ... (FMR2_MAX - 1)] = -1 }; module_param_array(radio_nr, int, NULL, 0444); MODULE_PARM_DESC(radio_nr, "Radio device numbers"); struct fmr2 { int io; struct v4l2_device v4l2_dev; struct snd_tea575x tea; struct v4l2_ctrl *volume; struct v4l2_ctrl *balance; bool is_fmd2; }; static int num_fmr2_cards; static struct fmr2 *fmr2_cards[FMR2_MAX]; static bool isa_registered; static bool pnp_registered; /* the port is hardwired on SF16-FMR2 */ #define FMR2_PORT 0x384 /* TEA575x tuner pins */ #define STR_DATA (1 << 0) #define STR_CLK (1 << 1) #define STR_WREN (1 << 2) #define STR_MOST (1 << 3) /* PT2254A/TC9154A volume control pins */ #define PT_ST (1 << 4) #define PT_CK (1 << 5) #define PT_DATA (1 << 6) /* volume control presence pin */ #define FMR2_HASVOL (1 << 7) static void fmr2_tea575x_set_pins(struct snd_tea575x *tea, u8 pins) { struct fmr2 *fmr2 = tea->private_data; u8 bits = 0; bits |= (pins & TEA575X_DATA) ? STR_DATA : 0; bits |= (pins & TEA575X_CLK) ? STR_CLK : 0; /* WRITE_ENABLE is inverted, DATA must be high during read */ bits |= (pins & TEA575X_WREN) ? 0 : STR_WREN | STR_DATA; outb(bits, fmr2->io); } static u8 fmr2_tea575x_get_pins(struct snd_tea575x *tea) { struct fmr2 *fmr2 = tea->private_data; u8 bits = inb(fmr2->io); return (bits & STR_DATA) ? TEA575X_DATA : 0 | (bits & STR_MOST) ? TEA575X_MOST : 0; } static void fmr2_tea575x_set_direction(struct snd_tea575x *tea, bool output) { } static struct snd_tea575x_ops fmr2_tea_ops = { .set_pins = fmr2_tea575x_set_pins, .get_pins = fmr2_tea575x_get_pins, .set_direction = fmr2_tea575x_set_direction, }; /* TC9154A/PT2254A volume control */ /* 18-bit shift register bit definitions */ #define TC9154A_ATT_MAJ_0DB (1 << 0) #define TC9154A_ATT_MAJ_10DB (1 << 1) #define TC9154A_ATT_MAJ_20DB (1 << 2) #define TC9154A_ATT_MAJ_30DB (1 << 3) #define TC9154A_ATT_MAJ_40DB (1 << 4) #define TC9154A_ATT_MAJ_50DB (1 << 5) #define TC9154A_ATT_MAJ_60DB (1 << 6) #define TC9154A_ATT_MIN_0DB (1 << 7) #define TC9154A_ATT_MIN_2DB (1 << 8) #define TC9154A_ATT_MIN_4DB (1 << 9) #define TC9154A_ATT_MIN_6DB (1 << 10) #define TC9154A_ATT_MIN_8DB (1 << 11) /* bit 12 is ignored */ #define TC9154A_CHANNEL_LEFT (1 << 13) #define TC9154A_CHANNEL_RIGHT (1 << 14) /* bits 15, 16, 17 must be 0 */ #define TC9154A_ATT_MAJ(x) (1 << x) #define TC9154A_ATT_MIN(x) (1 << (7 + x)) static void tc9154a_set_pins(struct fmr2 *fmr2, u8 pins) { if (!fmr2->tea.mute) pins |= STR_WREN; outb(pins, fmr2->io); } static void tc9154a_set_attenuation(struct fmr2 *fmr2, int att, u32 channel) { int i; u32 reg; u8 bit; reg = TC9154A_ATT_MAJ(att / 10) | TC9154A_ATT_MIN((att % 10) / 2); reg |= channel; /* write 18-bit shift register, LSB first */ for (i = 0; i < 18; i++) { bit = reg & (1 << i) ? PT_DATA : 0; tc9154a_set_pins(fmr2, bit); udelay(5); tc9154a_set_pins(fmr2, bit | PT_CK); udelay(5); tc9154a_set_pins(fmr2, bit); } /* latch register data */ udelay(5); tc9154a_set_pins(fmr2, PT_ST); udelay(5); tc9154a_set_pins(fmr2, 0); } static int fmr2_s_ctrl(struct v4l2_ctrl *ctrl) { struct snd_tea575x *tea = container_of(ctrl->handler, struct snd_tea575x, ctrl_handler); struct fmr2 *fmr2 = tea->private_data; int volume, balance, left, right; switch (ctrl->id) { case V4L2_CID_AUDIO_VOLUME: volume = ctrl->val; balance = fmr2->balance->cur.val; break; case V4L2_CID_AUDIO_BALANCE: balance = ctrl->val; volume = fmr2->volume->cur.val; break; default: return -EINVAL; } left = right = volume; if (balance < 0) right = max(0, right + balance); if (balance > 0) left = max(0, left - balance); tc9154a_set_attenuation(fmr2, abs(left - 68), TC9154A_CHANNEL_LEFT); tc9154a_set_attenuation(fmr2, abs(right - 68), TC9154A_CHANNEL_RIGHT); return 0; } static const struct v4l2_ctrl_ops fmr2_ctrl_ops = { .s_ctrl = fmr2_s_ctrl, }; static int fmr2_tea_ext_init(struct snd_tea575x *tea) { struct fmr2 *fmr2 = tea->private_data; /* FMR2 can have volume control, FMD2 can't (uses SB16 mixer) */ if (!fmr2->is_fmd2 && inb(fmr2->io) & FMR2_HASVOL) { fmr2->volume = v4l2_ctrl_new_std(&tea->ctrl_handler, &fmr2_ctrl_ops, V4L2_CID_AUDIO_VOLUME, 0, 68, 2, 56); fmr2->balance = v4l2_ctrl_new_std(&tea->ctrl_handler, &fmr2_ctrl_ops, V4L2_CID_AUDIO_BALANCE, -68, 68, 2, 0); if (tea->ctrl_handler.error) { printk(KERN_ERR "radio-sf16fmr2: can't initialize controls\n"); return tea->ctrl_handler.error; } } return 0; } static struct pnp_device_id fmr2_pnp_ids[] = { { .id = "MFRad13" }, /* tuner subdevice of SF16-FMD2 */ { .id = "" } }; MODULE_DEVICE_TABLE(pnp, fmr2_pnp_ids); static int fmr2_probe(struct fmr2 *fmr2, struct device *pdev, int io) { int err, i; char *card_name = fmr2->is_fmd2 ? "SF16-FMD2" : "SF16-FMR2"; /* avoid errors if a card was already registered at given port */ for (i = 0; i < num_fmr2_cards; i++) if (io == fmr2_cards[i]->io) return -EBUSY; strlcpy(fmr2->v4l2_dev.name, "radio-sf16fmr2", sizeof(fmr2->v4l2_dev.name)), fmr2->io = io; if (!request_region(fmr2->io, 2, fmr2->v4l2_dev.name)) { printk(KERN_ERR "radio-sf16fmr2: I/O port 0x%x already in use\n", fmr2->io); return -EBUSY; } dev_set_drvdata(pdev, fmr2); err = v4l2_device_register(pdev, &fmr2->v4l2_dev); if (err < 0) { v4l2_err(&fmr2->v4l2_dev, "Could not register v4l2_device\n"); release_region(fmr2->io, 2); return err; } fmr2->tea.v4l2_dev = &fmr2->v4l2_dev; fmr2->tea.private_data = fmr2; fmr2->tea.radio_nr = radio_nr[num_fmr2_cards]; fmr2->tea.ops = &fmr2_tea_ops; fmr2->tea.ext_init = fmr2_tea_ext_init; strlcpy(fmr2->tea.card, card_name, sizeof(fmr2->tea.card)); snprintf(fmr2->tea.bus_info, sizeof(fmr2->tea.bus_info), "%s:%s", fmr2->is_fmd2 ? "PnP" : "ISA", dev_name(pdev)); if (snd_tea575x_init(&fmr2->tea, THIS_MODULE)) { printk(KERN_ERR "radio-sf16fmr2: Unable to detect TEA575x tuner\n"); release_region(fmr2->io, 2); return -ENODEV; } printk(KERN_INFO "radio-sf16fmr2: %s radio card at 0x%x.\n", card_name, fmr2->io); return 0; } static int fmr2_isa_match(struct device *pdev, unsigned int ndev) { struct fmr2 *fmr2 = kzalloc(sizeof(*fmr2), GFP_KERNEL); if (!fmr2) return 0; if (fmr2_probe(fmr2, pdev, FMR2_PORT)) { kfree(fmr2); return 0; } dev_set_drvdata(pdev, fmr2); fmr2_cards[num_fmr2_cards++] = fmr2; return 1; } static int fmr2_pnp_probe(struct pnp_dev *pdev, const struct pnp_device_id *id) { int ret; struct fmr2 *fmr2 = kzalloc(sizeof(*fmr2), GFP_KERNEL); if (!fmr2) return -ENOMEM; fmr2->is_fmd2 = true; ret = fmr2_probe(fmr2, &pdev->dev, pnp_port_start(pdev, 0)); if (ret) { kfree(fmr2); return ret; } pnp_set_drvdata(pdev, fmr2); fmr2_cards[num_fmr2_cards++] = fmr2; return 0; } static void fmr2_remove(struct fmr2 *fmr2) { snd_tea575x_exit(&fmr2->tea); release_region(fmr2->io, 2); v4l2_device_unregister(&fmr2->v4l2_dev); kfree(fmr2); } static int fmr2_isa_remove(struct device *pdev, unsigned int ndev) { fmr2_remove(dev_get_drvdata(pdev)); dev_set_drvdata(pdev, NULL); return 0; } static void fmr2_pnp_remove(struct pnp_dev *pdev) { fmr2_remove(pnp_get_drvdata(pdev)); pnp_set_drvdata(pdev, NULL); } struct isa_driver fmr2_isa_driver = { .match = fmr2_isa_match, .remove = fmr2_isa_remove, .driver = { .name = "radio-sf16fmr2", }, }; struct pnp_driver fmr2_pnp_driver = { .name = "radio-sf16fmr2", .id_table = fmr2_pnp_ids, .probe = fmr2_pnp_probe, .remove = fmr2_pnp_remove, }; static int __init fmr2_init(void) { int ret; ret = pnp_register_driver(&fmr2_pnp_driver); if (!ret) pnp_registered = true; ret = isa_register_driver(&fmr2_isa_driver, 1); if (!ret) isa_registered = true; return (pnp_registered || isa_registered) ? 0 : ret; } static void __exit fmr2_exit(void) { if (pnp_registered) pnp_unregister_driver(&fmr2_pnp_driver); if (isa_registered) isa_unregister_driver(&fmr2_isa_driver); } module_init(fmr2_init); module_exit(fmr2_exit);
#!/usr/bin/python # # (c) 2018 Extreme Networks Inc. # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>. # from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = """ --- module: exos_facts version_added: "2.7" author: - "Lance Richardson (@hlrichardson)" - "Ujwal Koamrla (@ujwalkomarla)" short_description: Collect facts from devices running Extreme EXOS description: - Collects a base set of device facts from a remote device that is running EXOS. This module prepends all of the base network fact keys with C(ansible_net_<fact>). The facts module will always collect a base set of facts from the device and can enable or disable collection of additional facts. notes: - Tested against EXOS 22.5.1.7 options: gather_subset: description: - When supplied, this argument will restrict the facts collected to a given subset. Possible values for this argument include all, hardware, config, and interfaces. Can specify a list of values to include a larger subset. Values can also be used with an initial C(M(!)) to specify that a specific subset should not be collected. required: false type: list default: ['!config'] gather_network_resources: description: - When supplied, this argument will restrict the facts collected to a given subset. Possible values for this argument include all and the resources like interfaces, vlans etc. Can specify a list of values to include a larger subset. Values can also be used with an initial C(M(!)) to specify that a specific subset should not be collected. Valid subsets are 'all', 'lldp_global'. type: list version_added: "2.9" """ EXAMPLES = """ - name: Gather all legacy facts exos_facts: gather_subset: all - name: Gather only the config and default facts exos_facts: gather_subset: config - name: do not gather hardware facts exos_facts: gather_subset: "!hardware" - name: Gather legacy and resource facts exos_facts: gather_subset: all gather_network_resources: all - name: Gather only the lldp global resource facts and no legacy facts exos_facts: gather_subset: - '!all' - '!min' gather_network_resource: - lldp_global - name: Gather lldp global resource and minimal legacy facts exos_facts: gather_subset: min gather_network_resource: lldp_global """ RETURN = """ ansible_net_gather_subset: description: The list of fact subsets collected from the device returned: always type: list ansible_net_gather_network_resources: description: The list of fact for network resource subsets collected from the device returned: when the resource is configured type: list # default ansible_net_model: description: The model name returned from the device returned: always type: str ansible_net_serialnum: description: The serial number of the remote device returned: always type: str ansible_net_version: description: The operating system version running on the remote device returned: always type: str ansible_net_hostname: description: The configured hostname of the device returned: always type: str # hardware ansible_net_memfree_mb: description: The available free memory on the remote device in Mb returned: when hardware is configured type: int ansible_net_memtotal_mb: description: The total memory on the remote device in Mb returned: when hardware is configured type: int # config ansible_net_config: description: The current active config from the device returned: when config is configured type: str # interfaces ansible_net_all_ipv4_addresses: description: All IPv4 addresses configured on the device returned: when interfaces is configured type: list ansible_net_all_ipv6_addresses: description: All Primary IPv6 addresses configured on the device returned: when interfaces is configured type: list ansible_net_interfaces: description: A hash of all interfaces running on the system returned: when interfaces is configured type: dict ansible_net_neighbors: description: The list of LLDP neighbors from the remote device returned: when interfaces is configured type: dict """ from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.network.exos.argspec.facts.facts import FactsArgs from ansible.module_utils.network.exos.facts.facts import Facts def main(): """Main entry point for AnsibleModule """ argument_spec = FactsArgs.argument_spec module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) warnings = ['default value for `gather_subset` ' 'will be changed to `min` from `!config` v2.11 onwards'] result = Facts(module).get_facts() ansible_facts, additional_warnings = result warnings.extend(additional_warnings) module.exit_json(ansible_facts=ansible_facts, warnings=warnings) if __name__ == '__main__': main()
.modal_form{ position: absolute; left: 50%; top: 50%; border-width: 11px 13px 15px 13px; width: 450px; /*height: 186px;*/ margin-left: -225px; margin-top: -100px; -webkit-border-image: url(i/modal_bg.png) 11 13 15 13 stretch stretch; } .modal_form .title{ font-size: 30px; color: #002864; margin-bottom: 6px; } .modal_form .text{ font-size: 22px; margin-bottom: 3px; border: 5px; -webkit-border-image: url(i/item_bg.png) 5; } .modal_form .status{ position: absolute; top: 3px; right: 5px; font-size: 22px; color: #990000; } .modal_form .item{ border-width: 20px 6px 20px 6px; -webkit-border-image: url(i/item_bg.png) 20 6 20 6 stretch stretch; margin-bottom: 6px; } .modal_form .item input{ float: right; height: 5px; width: 59%; margin-top: -15px; border-width: 13px 13px 13px 13px; -webkit-border-image: url(i/input.png) 13 13 14 13 stretch stretch; -webkit-border-radius: 15px; } .modal_form .item input:focus{ -webkit-border-image: url(i/input_act.png) 13 13 14 13 stretch stretch; } .modal_form .label{ float: left; font-size: 22px; color: #002864; text-shadow: white 1px 1px 1px; line-height: 38px; margin-top: -20px; } .modal_form .buttons{ width: 100%; text-align: right; } .modal_form .buttons input{ /*float: right;*/ background: url(i/btn2.png) right no-repeat; font-size: 19px; font-weight: bold; text-align: center; color: #fff; line-height: 28px; text-shadow: #808080 -1px -1px 3px; height: 31px; width: 200px; margin: 0 4px 0 10px; border: none; } .modal_form .buttons input:focus{ background: url(i/btn2.png) left no-repeat; color: #fff; text-shadow: #000 -1px -1px 3px; } .modal_form .form_select{ height: 5px; width: 233px !important; top: -13px; border-width: 13px 13px 14px 13px; -webkit-border-image: url(i/combobox.png) 13 13 14 13 stretch stretch !important; float: right; margin-top: -15px; line-height: 2px; overflow: hidden; font-size: 18px; } .modal_form .form_select.active{ -webkit-border-image: url(i/combobox_act.png) 13 13 14 13 stretch stretch !important; } .modal_form .form_time, .modal_form .form_date{ height: 5px; top: -13px; border-width: 13px 13px 14px 13px; -webkit-border-image: url(i/input.png) 13 12 14 12 stretch stretch !important; float: left; margin-top: -15px; line-height: 10px; /*overflow: hidden;*/ margin-right: 10px; font-size: 18px; /*font-family: "Courier New", serif;*/ } .modal_form .form_time.active, .modal_form .form_date.active{ -webkit-border-image: url(i/input_act.png) 13 12 14 12 stretch stretch !important; } .modal_form .form_time.edit, .modal_form .form_date.edit{ color: #00f; } .modal_form .form_time .highlight, .modal_form .form_date .highlight{ color: #f00; } .modal_form .form_time{ width: 45px; } .modal_form .form_date{ width: 88px; } .modal_form .fixed_container{ width: 283px; float: right; } .modal_form .select_arrow{ float: right; font-size: 20px; font-family: "Myriad Pro Cond", serif; position: relative; bottom: 11px; color: #888; height: 40px; width: 10px; padding-right: 2px; } .modal_form .select_arrow.active{ color: #035f9e; } #local_pvr_confirm{ margin-top: -164px; }
/** * sp-pnp-js v2.0.6-beta.1 - A JavaScript library for SharePoint development. * MIT (https://github.com/SharePoint/PnP-JS-Core/blob/master/LICENSE) * Copyright (c) 2017 Microsoft * docs: http://officedev.github.io/PnP-JS-Core * source: https://github.com/SharePoint/PnP-JS-Core * bugs: https://github.com/SharePoint/PnP-JS-Core/issues */ (function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else if(typeof exports === 'object') exports["$pnp"] = factory(); else root["$pnp"] = factory(); })(this, function() { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // identity function for calling harmony imports with the correct context /******/ __webpack_require__.i = function(value) { return value; }; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "/assets/"; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 41); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* WEBPACK VAR INJECTION */(function(global) { Object.defineProperty(exports, "__esModule", { value: true }); var pnplibconfig_1 = __webpack_require__(4); var Util = (function () { function Util() { } /** * Gets a callback function which will maintain context across async calls. * Allows for the calling pattern getCtxCallback(thisobj, method, methodarg1, methodarg2, ...) * * @param context The object that will be the 'this' value in the callback * @param method The method to which we will apply the context and parameters * @param params Optional, additional arguments to supply to the wrapped method when it is invoked */ Util.getCtxCallback = function (context, method) { var params = []; for (var _i = 2; _i < arguments.length; _i++) { params[_i - 2] = arguments[_i]; } return function () { method.apply(context, params); }; }; /** * Tests if a url param exists * * @param name The name of the url paramter to check */ Util.urlParamExists = function (name) { name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]"); var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"); return regex.test(location.search); }; /** * Gets a url param value by name * * @param name The name of the paramter for which we want the value */ Util.getUrlParamByName = function (name) { name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]"); var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"); var results = regex.exec(location.search); return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " ")); }; /** * Gets a url param by name and attempts to parse a bool value * * @param name The name of the paramter for which we want the boolean value */ Util.getUrlParamBoolByName = function (name) { var p = this.getUrlParamByName(name); var isFalse = (p === "" || /false|0/i.test(p)); return !isFalse; }; /** * Inserts the string s into the string target as the index specified by index * * @param target The string into which we will insert s * @param index The location in target to insert s (zero based) * @param s The string to insert into target at position index */ Util.stringInsert = function (target, index, s) { if (index > 0) { return target.substring(0, index) + s + target.substring(index, target.length); } return s + target; }; /** * Adds a value to a date * * @param date The date to which we will add units, done in local time * @param interval The name of the interval to add, one of: ['year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second'] * @param units The amount to add to date of the given interval * * http://stackoverflow.com/questions/1197928/how-to-add-30-minutes-to-a-javascript-date-object */ Util.dateAdd = function (date, interval, units) { var ret = new Date(date.toLocaleString()); // don't change original date switch (interval.toLowerCase()) { case "year": ret.setFullYear(ret.getFullYear() + units); break; case "quarter": ret.setMonth(ret.getMonth() + 3 * units); break; case "month": ret.setMonth(ret.getMonth() + units); break; case "week": ret.setDate(ret.getDate() + 7 * units); break; case "day": ret.setDate(ret.getDate() + units); break; case "hour": ret.setTime(ret.getTime() + units * 3600000); break; case "minute": ret.setTime(ret.getTime() + units * 60000); break; case "second": ret.setTime(ret.getTime() + units * 1000); break; default: ret = undefined; break; } return ret; }; /** * Loads a stylesheet into the current page * * @param path The url to the stylesheet * @param avoidCache If true a value will be appended as a query string to avoid browser caching issues */ Util.loadStylesheet = function (path, avoidCache) { if (avoidCache) { path += "?" + encodeURIComponent((new Date()).getTime().toString()); } var head = document.getElementsByTagName("head"); if (head.length > 0) { var e = document.createElement("link"); head[0].appendChild(e); e.setAttribute("type", "text/css"); e.setAttribute("rel", "stylesheet"); e.setAttribute("href", path); } }; /** * Combines an arbitrary set of paths ensuring that the slashes are normalized * * @param paths 0 to n path parts to combine */ Util.combinePaths = function () { var paths = []; for (var _i = 0; _i < arguments.length; _i++) { paths[_i] = arguments[_i]; } return paths .filter(function (path) { return !Util.stringIsNullOrEmpty(path); }) .map(function (path) { return path.replace(/^[\\|\/]/, "").replace(/[\\|\/]$/, ""); }) .join("/") .replace(/\\/g, "/"); }; /** * Gets a random string of chars length * * @param chars The length of the random string to generate */ Util.getRandomString = function (chars) { var text = new Array(chars); var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; for (var i = 0; i < chars; i++) { text[i] = possible.charAt(Math.floor(Math.random() * possible.length)); } return text.join(""); }; /** * Gets a random GUID value * * http://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript */ /* tslint:disable no-bitwise */ Util.getGUID = function () { var d = new Date().getTime(); var guid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) { var r = (d + Math.random() * 16) % 16 | 0; d = Math.floor(d / 16); return (c === "x" ? r : (r & 0x3 | 0x8)).toString(16); }); return guid; }; /* tslint:enable */ /** * Determines if a given value is a function * * @param candidateFunction The thing to test for being a function */ Util.isFunction = function (candidateFunction) { return typeof candidateFunction === "function"; }; /** * @returns whether the provided parameter is a JavaScript Array or not. */ Util.isArray = function (array) { if (Array.isArray) { return Array.isArray(array); } return array && typeof array.length === "number" && array.constructor === Array; }; /** * Determines if a string is null or empty or undefined * * @param s The string to test */ Util.stringIsNullOrEmpty = function (s) { return typeof s === "undefined" || s === null || s.length < 1; }; /** * Provides functionality to extend the given object by doing a shallow copy * * @param target The object to which properties will be copied * @param source The source object from which properties will be copied * @param noOverwrite If true existing properties on the target are not overwritten from the source * */ Util.extend = function (target, source, noOverwrite) { if (noOverwrite === void 0) { noOverwrite = false; } if (source === null || typeof source === "undefined") { return target; } // ensure we don't overwrite things we don't want overwritten var check = noOverwrite ? function (o, i) { return !(i in o); } : function () { return true; }; return Object.getOwnPropertyNames(source) .filter(function (v) { return check(target, v); }) .reduce(function (t, v) { t[v] = source[v]; return t; }, target); }; /** * Determines if a given url is absolute * * @param url The url to check to see if it is absolute */ Util.isUrlAbsolute = function (url) { return /^https?:\/\/|^\/\//i.test(url); }; /** * Ensures that a given url is absolute for the current web based on context * * @param candidateUrl The url to make absolute * */ Util.toAbsoluteUrl = function (candidateUrl) { return new Promise(function (resolve) { if (Util.isUrlAbsolute(candidateUrl)) { // if we are already absolute, then just return the url return resolve(candidateUrl); } if (pnplibconfig_1.RuntimeConfig.baseUrl !== null) { // base url specified either with baseUrl of spfxContext config property return resolve(Util.combinePaths(pnplibconfig_1.RuntimeConfig.baseUrl, candidateUrl)); } if (typeof global._spPageContextInfo !== "undefined") { // operating in classic pages if (global._spPageContextInfo.hasOwnProperty("webAbsoluteUrl")) { return resolve(Util.combinePaths(global._spPageContextInfo.webAbsoluteUrl, candidateUrl)); } else if (global._spPageContextInfo.hasOwnProperty("webServerRelativeUrl")) { return resolve(Util.combinePaths(global._spPageContextInfo.webServerRelativeUrl, candidateUrl)); } } // does window.location exist and have _layouts in it? if (typeof global.location !== "undefined") { var index = global.location.toString().toLowerCase().indexOf("/_layouts/"); if (index > 0) { // we are likely in the workbench in /_layouts/ return resolve(Util.combinePaths(global.location.toString().substr(0, index), candidateUrl)); } } return resolve(candidateUrl); }); }; return Util; }()); exports.Util = Util; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(32))) /***/ }), /* 1 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var util_1 = __webpack_require__(0); var collections_1 = __webpack_require__(6); var odata_1 = __webpack_require__(2); var pnplibconfig_1 = __webpack_require__(4); var exceptions_1 = __webpack_require__(3); var logging_1 = __webpack_require__(5); var pipeline_1 = __webpack_require__(45); /** * Queryable Base Class * */ var Queryable = (function () { /** * Creates a new instance of the Queryable class * * @constructor * @param baseUrl A string or Queryable that should form the base part of the url * */ function Queryable(baseUrl, path) { this._query = new collections_1.Dictionary(); this._batch = null; if (typeof baseUrl === "string") { // we need to do some extra parsing to get the parent url correct if we are // being created from just a string. var urlStr = baseUrl; if (util_1.Util.isUrlAbsolute(urlStr) || urlStr.lastIndexOf("/") < 0) { this._parentUrl = urlStr; this._url = util_1.Util.combinePaths(urlStr, path); } else if (urlStr.lastIndexOf("/") > urlStr.lastIndexOf("(")) { // .../items(19)/fields var index = urlStr.lastIndexOf("/"); this._parentUrl = urlStr.slice(0, index); path = util_1.Util.combinePaths(urlStr.slice(index), path); this._url = util_1.Util.combinePaths(this._parentUrl, path); } else { // .../items(19) var index = urlStr.lastIndexOf("("); this._parentUrl = urlStr.slice(0, index); this._url = util_1.Util.combinePaths(urlStr, path); } } else { var q = baseUrl; this._parentUrl = q._url; var target = q._query.get("@target"); if (target !== null) { this._query.add("@target", target); } this._url = util_1.Util.combinePaths(this._parentUrl, path); } } /** * Directly concatonates the supplied string to the current url, not normalizing "/" chars * * @param pathPart The string to concatonate to the url */ Queryable.prototype.concat = function (pathPart) { this._url += pathPart; return this; }; /** * Appends the given string and normalizes "/" chars * * @param pathPart The string to append */ Queryable.prototype.append = function (pathPart) { this._url = util_1.Util.combinePaths(this._url, pathPart); }; /** * Blocks a batch call from occuring, MUST be cleared by calling the returned function */ Queryable.prototype.addBatchDependency = function () { if (this.hasBatch) { return this._batch.addDependency(); } return function () { return null; }; }; Object.defineProperty(Queryable.prototype, "hasBatch", { /** * Indicates if the current query has a batch associated * */ get: function () { return this._batch !== null; }, enumerable: true, configurable: true }); Object.defineProperty(Queryable.prototype, "batch", { /** * The batch currently associated with this query or null * */ get: function () { return this.hasBatch ? this._batch : null; }, enumerable: true, configurable: true }); Object.defineProperty(Queryable.prototype, "parentUrl", { /** * Gets the parent url used when creating this instance * */ get: function () { return this._parentUrl; }, enumerable: true, configurable: true }); Object.defineProperty(Queryable.prototype, "query", { /** * Provides access to the query builder for this url * */ get: function () { return this._query; }, enumerable: true, configurable: true }); /** * Creates a new instance of the supplied factory and extends this into that new instance * * @param factory constructor for the new queryable */ Queryable.prototype.as = function (factory) { var o = new factory(this._url, null); return util_1.Util.extend(o, this, true); }; /** * Adds this query to the supplied batch * * @example * ``` * * let b = pnp.sp.createBatch(); * pnp.sp.web.inBatch(b).get().then(...); * b.execute().then(...) * ``` */ Queryable.prototype.inBatch = function (batch) { if (this._batch !== null) { throw new exceptions_1.AlreadyInBatchException(); } this._batch = batch; return this; }; /** * Enables caching for this request * * @param options Defines the options used when caching this request */ Queryable.prototype.usingCaching = function (options) { if (!pnplibconfig_1.RuntimeConfig.globalCacheDisable) { this._useCaching = true; this._cachingOptions = options; } return this; }; /** * Gets the currentl url, made absolute based on the availability of the _spPageContextInfo object * */ Queryable.prototype.toUrl = function () { return this._url; }; /** * Gets the full url with query information * */ Queryable.prototype.toUrlAndQuery = function () { var aliasedParams = new collections_1.Dictionary(); var url = this.toUrl().replace(/'!(@.*?)::(.*?)'/ig, function (match, labelName, value) { logging_1.Logger.write("Rewriting aliased parameter from match " + match + " to label: " + labelName + " value: " + value, logging_1.LogLevel.Verbose); aliasedParams.add(labelName, "'" + value + "'"); return labelName; }); // inlude our explicitly set query string params aliasedParams.merge(this._query); if (aliasedParams.count() > 0) { url += "?" + aliasedParams.getKeys().map(function (key) { return key + "=" + aliasedParams.get(key); }).join("&"); } return url; }; /** * Gets a parent for this instance as specified * * @param factory The contructor for the class to create */ Queryable.prototype.getParent = function (factory, baseUrl, path, batch) { if (baseUrl === void 0) { baseUrl = this.parentUrl; } var parent = new factory(baseUrl, path); var target = this.query.get("@target"); if (target !== null) { parent.query.add("@target", target); } if (typeof batch !== "undefined") { parent = parent.inBatch(batch); } return parent; }; /** * Clones this queryable into a new queryable instance of T * @param factory Constructor used to create the new instance * @param additionalPath Any additional path to include in the clone * @param includeBatch If true this instance's batch will be added to the cloned instance */ Queryable.prototype.clone = function (factory, additionalPath, includeBatch) { if (includeBatch === void 0) { includeBatch = false; } var clone = new factory(this, additionalPath); var target = this.query.get("@target"); if (target !== null) { clone.query.add("@target", target); } if (includeBatch && this.hasBatch) { clone = clone.inBatch(this.batch); } return clone; }; /** * Executes the currently built request * * @param parser Allows you to specify a parser to handle the result * @param getOptions The options used for this request */ Queryable.prototype.get = function (parser, getOptions) { if (parser === void 0) { parser = new odata_1.ODataDefaultParser(); } if (getOptions === void 0) { getOptions = {}; } return this.toRequestContext("GET", getOptions, parser).then(function (context) { return pipeline_1.pipe(context); }); }; Queryable.prototype.getAs = function (parser, getOptions) { if (parser === void 0) { parser = new odata_1.ODataDefaultParser(); } if (getOptions === void 0) { getOptions = {}; } return this.toRequestContext("GET", getOptions, parser).then(function (context) { return pipeline_1.pipe(context); }); }; Queryable.prototype.post = function (postOptions, parser) { if (postOptions === void 0) { postOptions = {}; } if (parser === void 0) { parser = new odata_1.ODataDefaultParser(); } return this.toRequestContext("POST", postOptions, parser).then(function (context) { return pipeline_1.pipe(context); }); }; Queryable.prototype.postAs = function (postOptions, parser) { if (postOptions === void 0) { postOptions = {}; } if (parser === void 0) { parser = new odata_1.ODataDefaultParser(); } return this.toRequestContext("POST", postOptions, parser).then(function (context) { return pipeline_1.pipe(context); }); }; Queryable.prototype.patch = function (patchOptions, parser) { if (patchOptions === void 0) { patchOptions = {}; } if (parser === void 0) { parser = new odata_1.ODataDefaultParser(); } return this.toRequestContext("PATCH", patchOptions, parser).then(function (context) { return pipeline_1.pipe(context); }); }; Queryable.prototype.delete = function (deleteOptions, parser) { if (deleteOptions === void 0) { deleteOptions = {}; } if (parser === void 0) { parser = new odata_1.ODataDefaultParser(); } return this.toRequestContext("DELETE", deleteOptions, parser).then(function (context) { return pipeline_1.pipe(context); }); }; /** * Converts the current instance to a request context * * @param verb The request verb * @param options The set of supplied request options * @param parser The supplied ODataParser instance * @param pipeline Optional request processing pipeline */ Queryable.prototype.toRequestContext = function (verb, options, parser, pipeline) { var _this = this; if (options === void 0) { options = {}; } if (pipeline === void 0) { pipeline = pipeline_1.PipelineMethods.default; } var dependencyDispose = this.hasBatch ? this.addBatchDependency() : function () { return; }; return util_1.Util.toAbsoluteUrl(this.toUrlAndQuery()).then(function (url) { // build our request context var context = { batch: _this._batch, batchDependency: dependencyDispose, cachingOptions: _this._cachingOptions, isBatched: _this.hasBatch, isCached: _this._useCaching, options: options, parser: parser, pipeline: pipeline, requestAbsoluteUrl: url, requestId: util_1.Util.getGUID(), verb: verb, }; return context; }); }; return Queryable; }()); exports.Queryable = Queryable; /** * Represents a REST collection which can be filtered, paged, and selected * */ var QueryableCollection = (function (_super) { __extends(QueryableCollection, _super); function QueryableCollection() { return _super !== null && _super.apply(this, arguments) || this; } /** * Filters the returned collection (https://msdn.microsoft.com/en-us/library/office/fp142385.aspx#bk_supported) * * @param filter The string representing the filter query */ QueryableCollection.prototype.filter = function (filter) { this._query.add("$filter", filter); return this; }; /** * Choose which fields to return * * @param selects One or more fields to return */ QueryableCollection.prototype.select = function () { var selects = []; for (var _i = 0; _i < arguments.length; _i++) { selects[_i] = arguments[_i]; } if (selects.length > 0) { this._query.add("$select", selects.join(",")); } return this; }; /** * Expands fields such as lookups to get additional data * * @param expands The Fields for which to expand the values */ QueryableCollection.prototype.expand = function () { var expands = []; for (var _i = 0; _i < arguments.length; _i++) { expands[_i] = arguments[_i]; } if (expands.length > 0) { this._query.add("$expand", expands.join(",")); } return this; }; /** * Orders based on the supplied fields ascending * * @param orderby The name of the field to sort on * @param ascending If false DESC is appended, otherwise ASC (default) */ QueryableCollection.prototype.orderBy = function (orderBy, ascending) { if (ascending === void 0) { ascending = true; } var keys = this._query.getKeys(); var query = []; var asc = ascending ? " asc" : " desc"; for (var i = 0; i < keys.length; i++) { if (keys[i] === "$orderby") { query.push(this._query.get("$orderby")); break; } } query.push("" + orderBy + asc); this._query.add("$orderby", query.join(",")); return this; }; /** * Skips the specified number of items * * @param skip The number of items to skip */ QueryableCollection.prototype.skip = function (skip) { this._query.add("$skip", skip.toString()); return this; }; /** * Limits the query to only return the specified number of items * * @param top The query row limit */ QueryableCollection.prototype.top = function (top) { this._query.add("$top", top.toString()); return this; }; return QueryableCollection; }(Queryable)); exports.QueryableCollection = QueryableCollection; /** * Represents an instance that can be selected * */ var QueryableInstance = (function (_super) { __extends(QueryableInstance, _super); function QueryableInstance() { return _super !== null && _super.apply(this, arguments) || this; } /** * Choose which fields to return * * @param selects One or more fields to return */ QueryableInstance.prototype.select = function () { var selects = []; for (var _i = 0; _i < arguments.length; _i++) { selects[_i] = arguments[_i]; } if (selects.length > 0) { this._query.add("$select", selects.join(",")); } return this; }; /** * Expands fields such as lookups to get additional data * * @param expands The Fields for which to expand the values */ QueryableInstance.prototype.expand = function () { var expands = []; for (var _i = 0; _i < arguments.length; _i++) { expands[_i] = arguments[_i]; } if (expands.length > 0) { this._query.add("$expand", expands.join(",")); } return this; }; return QueryableInstance; }(Queryable)); exports.QueryableInstance = QueryableInstance; /***/ }), /* 2 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var util_1 = __webpack_require__(0); var logging_1 = __webpack_require__(5); var httpclient_1 = __webpack_require__(15); var pnplibconfig_1 = __webpack_require__(4); var exceptions_1 = __webpack_require__(3); var exceptions_2 = __webpack_require__(3); function extractOdataId(candidate) { if (candidate.hasOwnProperty("odata.id")) { return candidate["odata.id"]; } else if (candidate.hasOwnProperty("__metadata") && candidate.__metadata.hasOwnProperty("id")) { return candidate.__metadata.id; } else { throw new exceptions_1.ODataIdException(candidate); } } exports.extractOdataId = extractOdataId; var ODataParserBase = (function () { function ODataParserBase() { } ODataParserBase.prototype.parse = function (r) { var _this = this; return new Promise(function (resolve, reject) { if (_this.handleError(r, reject)) { if ((r.headers.has("Content-Length") && parseFloat(r.headers.get("Content-Length")) === 0) || r.status === 204) { resolve({}); } else { r.json().then(function (json) { return resolve(_this.parseODataJSON(json)); }).catch(function (e) { return reject(e); }); } } }); }; ODataParserBase.prototype.handleError = function (r, reject) { if (!r.ok) { r.json().then(function (json) { // include the headers as they contain diagnostic information var data = { responseBody: json, responseHeaders: r.headers, }; reject(new exceptions_2.ProcessHttpClientResponseException(r.status, r.statusText, data)); }).catch(function (e) { // we failed to read the body - possibly it is empty. Let's report the original status that caused // the request to fail and log the error with parsing the body if anyone needs it for debugging logging_1.Logger.log({ data: e, level: logging_1.LogLevel.Warning, message: "There was an error parsing the error response body. See data for details.", }); // include the headers as they contain diagnostic information var data = { responseBody: "[[body not available]]", responseHeaders: r.headers, }; reject(new exceptions_2.ProcessHttpClientResponseException(r.status, r.statusText, data)); }); } return r.ok; }; ODataParserBase.prototype.parseODataJSON = function (json) { var result = json; if (json.hasOwnProperty("d")) { if (json.d.hasOwnProperty("results")) { result = json.d.results; } else { result = json.d; } } else if (json.hasOwnProperty("value")) { result = json.value; } return result; }; return ODataParserBase; }()); exports.ODataParserBase = ODataParserBase; var ODataDefaultParser = (function (_super) { __extends(ODataDefaultParser, _super); function ODataDefaultParser() { return _super !== null && _super.apply(this, arguments) || this; } return ODataDefaultParser; }(ODataParserBase)); exports.ODataDefaultParser = ODataDefaultParser; var ODataRawParserImpl = (function () { function ODataRawParserImpl() { } ODataRawParserImpl.prototype.parse = function (r) { return r.json(); }; return ODataRawParserImpl; }()); exports.ODataRawParserImpl = ODataRawParserImpl; var ODataValueParserImpl = (function (_super) { __extends(ODataValueParserImpl, _super); function ODataValueParserImpl() { return _super !== null && _super.apply(this, arguments) || this; } ODataValueParserImpl.prototype.parse = function (r) { return _super.prototype.parse.call(this, r).then(function (d) { return d; }); }; return ODataValueParserImpl; }(ODataParserBase)); var ODataEntityParserImpl = (function (_super) { __extends(ODataEntityParserImpl, _super); function ODataEntityParserImpl(factory) { var _this = _super.call(this) || this; _this.factory = factory; return _this; } ODataEntityParserImpl.prototype.parse = function (r) { var _this = this; return _super.prototype.parse.call(this, r).then(function (d) { var o = new _this.factory(getEntityUrl(d), null); return util_1.Util.extend(o, d); }); }; return ODataEntityParserImpl; }(ODataParserBase)); var ODataEntityArrayParserImpl = (function (_super) { __extends(ODataEntityArrayParserImpl, _super); function ODataEntityArrayParserImpl(factory) { var _this = _super.call(this) || this; _this.factory = factory; return _this; } ODataEntityArrayParserImpl.prototype.parse = function (r) { var _this = this; return _super.prototype.parse.call(this, r).then(function (d) { return d.map(function (v) { var o = new _this.factory(getEntityUrl(v), null); return util_1.Util.extend(o, v); }); }); }; return ODataEntityArrayParserImpl; }(ODataParserBase)); function getEntityUrl(entity) { if (entity.hasOwnProperty("odata.editLink")) { // we are dealign with minimal metadata (default) return util_1.Util.combinePaths("_api", entity["odata.editLink"]); } else if (entity.hasOwnProperty("__metadata")) { // we are dealing with verbose, which has an absolute uri return entity.__metadata.uri; } else { // we are likely dealing with nometadata, so don't error but we won't be able to // chain off these objects logging_1.Logger.write("No uri information found in ODataEntity parsing, chaining will fail for this object.", logging_1.LogLevel.Warning); return ""; } } exports.getEntityUrl = getEntityUrl; exports.ODataRaw = new ODataRawParserImpl(); function ODataValue() { return new ODataValueParserImpl(); } exports.ODataValue = ODataValue; function ODataEntity(factory) { return new ODataEntityParserImpl(factory); } exports.ODataEntity = ODataEntity; function ODataEntityArray(factory) { return new ODataEntityArrayParserImpl(factory); } exports.ODataEntityArray = ODataEntityArray; /** * Manages a batch of OData operations */ var ODataBatch = (function () { function ODataBatch(baseUrl, _batchId) { if (_batchId === void 0) { _batchId = util_1.Util.getGUID(); } this.baseUrl = baseUrl; this._batchId = _batchId; this._requests = []; this._dependencies = []; } Object.defineProperty(ODataBatch.prototype, "batchId", { get: function () { return this._batchId; }, enumerable: true, configurable: true }); /** * Adds a request to a batch (not designed for public use) * * @param url The full url of the request * @param method The http method GET, POST, etc * @param options Any options to include in the request * @param parser The parser that will hadle the results of the request */ ODataBatch.prototype.add = function (url, method, options, parser) { var info = { method: method.toUpperCase(), options: options, parser: parser, reject: null, resolve: null, url: url, }; var p = new Promise(function (resolve, reject) { info.resolve = resolve; info.reject = reject; }); this._requests.push(info); return p; }; /** * Adds a dependency insuring that some set of actions will occur before a batch is processed. * MUST be cleared using the returned resolve delegate to allow batches to run */ ODataBatch.prototype.addDependency = function () { var resolver; var promise = new Promise(function (resolve) { resolver = resolve; }); this._dependencies.push(promise); return resolver; }; /** * Execute the current batch and resolve the associated promises * * @returns A promise which will be resolved once all of the batch's child promises have resolved */ ODataBatch.prototype.execute = function () { var _this = this; // we need to check the dependencies twice due to how different engines handle things. // We can get a second set of promises added after the first set resolve return Promise.all(this._dependencies).then(function () { return Promise.all(_this._dependencies); }).then(function () { return _this.executeImpl(); }); }; ODataBatch.prototype.executeImpl = function () { var _this = this; logging_1.Logger.write("[" + this.batchId + "] (" + (new Date()).getTime() + ") Executing batch with " + this._requests.length + " requests.", logging_1.LogLevel.Info); // if we don't have any requests, don't bother sending anything // this could be due to caching further upstream, or just an empty batch if (this._requests.length < 1) { logging_1.Logger.write("Resolving empty batch.", logging_1.LogLevel.Info); return Promise.resolve(); } // creating the client here allows the url to be populated for nodejs client as well as potentially // any other hacks needed for other types of clients. Essentially allows the absoluteRequestUrl // below to be correct var client = new httpclient_1.HttpClient(); // due to timing we need to get the absolute url here so we can use it for all the individual requests // and for sending the entire batch return util_1.Util.toAbsoluteUrl(this.baseUrl).then(function (absoluteRequestUrl) { // build all the requests, send them, pipe results in order to parsers var batchBody = []; var currentChangeSetId = ""; for (var i = 0; i < _this._requests.length; i++) { var reqInfo = _this._requests[i]; if (reqInfo.method === "GET") { if (currentChangeSetId.length > 0) { // end an existing change set batchBody.push("--changeset_" + currentChangeSetId + "--\n\n"); currentChangeSetId = ""; } batchBody.push("--batch_" + _this._batchId + "\n"); } else { if (currentChangeSetId.length < 1) { // start new change set currentChangeSetId = util_1.Util.getGUID(); batchBody.push("--batch_" + _this._batchId + "\n"); batchBody.push("Content-Type: multipart/mixed; boundary=\"changeset_" + currentChangeSetId + "\"\n\n"); } batchBody.push("--changeset_" + currentChangeSetId + "\n"); } // common batch part prefix batchBody.push("Content-Type: application/http\n"); batchBody.push("Content-Transfer-Encoding: binary\n\n"); var headers = { "Accept": "application/json;", }; // this is the url of the individual request within the batch var url = util_1.Util.isUrlAbsolute(reqInfo.url) ? reqInfo.url : util_1.Util.combinePaths(absoluteRequestUrl, reqInfo.url); logging_1.Logger.write("[" + _this.batchId + "] (" + (new Date()).getTime() + ") Adding request " + reqInfo.method + " " + url + " to batch.", logging_1.LogLevel.Verbose); if (reqInfo.method !== "GET") { var method = reqInfo.method; if (reqInfo.hasOwnProperty("options") && reqInfo.options.hasOwnProperty("headers") && typeof reqInfo.options.headers["X-HTTP-Method"] !== "undefined") { method = reqInfo.options.headers["X-HTTP-Method"]; delete reqInfo.options.headers["X-HTTP-Method"]; } batchBody.push(method + " " + url + " HTTP/1.1\n"); headers = util_1.Util.extend(headers, { "Content-Type": "application/json;odata=verbose;charset=utf-8" }); } else { batchBody.push(reqInfo.method + " " + url + " HTTP/1.1\n"); } if (typeof pnplibconfig_1.RuntimeConfig.headers !== "undefined") { headers = util_1.Util.extend(headers, pnplibconfig_1.RuntimeConfig.headers); } if (reqInfo.options && reqInfo.options.headers) { headers = util_1.Util.extend(headers, reqInfo.options.headers); } for (var name_1 in headers) { if (headers.hasOwnProperty(name_1)) { batchBody.push(name_1 + ": " + headers[name_1] + "\n"); } } batchBody.push("\n"); if (reqInfo.options.body) { batchBody.push(reqInfo.options.body + "\n\n"); } } if (currentChangeSetId.length > 0) { // Close the changeset batchBody.push("--changeset_" + currentChangeSetId + "--\n\n"); currentChangeSetId = ""; } batchBody.push("--batch_" + _this._batchId + "--\n"); var batchHeaders = { "Content-Type": "multipart/mixed; boundary=batch_" + _this._batchId, }; var batchOptions = { "body": batchBody.join(""), "headers": batchHeaders, }; logging_1.Logger.write("[" + _this.batchId + "] (" + (new Date()).getTime() + ") Sending batch request.", logging_1.LogLevel.Info); return client.post(util_1.Util.combinePaths(absoluteRequestUrl, "/_api/$batch"), batchOptions) .then(function (r) { return r.text(); }) .then(_this._parseResponse) .then(function (responses) { if (responses.length !== _this._requests.length) { throw new exceptions_1.BatchParseException("Could not properly parse responses to match requests in batch."); } logging_1.Logger.write("[" + _this.batchId + "] (" + (new Date()).getTime() + ") Resolving batched requests.", logging_1.LogLevel.Info); return responses.reduce(function (chain, response, index) { var request = _this._requests[index]; logging_1.Logger.write("[" + _this.batchId + "] (" + (new Date()).getTime() + ") Resolving batched request " + request.method + " " + request.url + ".", logging_1.LogLevel.Verbose); return chain.then(function (_) { return request.parser.parse(response).then(request.resolve).catch(request.reject); }); }, Promise.resolve()); }); }); }; /** * Parses the response from a batch request into an array of Response instances * * @param body Text body of the response from the batch request */ ODataBatch.prototype._parseResponse = function (body) { return new Promise(function (resolve, reject) { var responses = []; var header = "--batchresponse_"; // Ex. "HTTP/1.1 500 Internal Server Error" var statusRegExp = new RegExp("^HTTP/[0-9.]+ +([0-9]+) +(.*)", "i"); var lines = body.split("\n"); var state = "batch"; var status; var statusText; for (var i = 0; i < lines.length; ++i) { var line = lines[i]; switch (state) { case "batch": if (line.substr(0, header.length) === header) { state = "batchHeaders"; } else { if (line.trim() !== "") { throw new exceptions_1.BatchParseException("Invalid response, line " + i); } } break; case "batchHeaders": if (line.trim() === "") { state = "status"; } break; case "status": var parts = statusRegExp.exec(line); if (parts.length !== 3) { throw new exceptions_1.BatchParseException("Invalid status, line " + i); } status = parseInt(parts[1], 10); statusText = parts[2]; state = "statusHeaders"; break; case "statusHeaders": if (line.trim() === "") { state = "body"; } break; case "body": responses.push((status === 204) ? new Response() : new Response(line, { status: status, statusText: statusText })); state = "batch"; break; } } if (state !== "status") { reject(new exceptions_1.BatchParseException("Unexpected end of input")); } resolve(responses); }); }; return ODataBatch; }()); exports.ODataBatch = ODataBatch; var TextFileParser = (function () { function TextFileParser() { } TextFileParser.prototype.parse = function (r) { return r.text(); }; return TextFileParser; }()); exports.TextFileParser = TextFileParser; var BlobFileParser = (function () { function BlobFileParser() { } BlobFileParser.prototype.parse = function (r) { return r.blob(); }; return BlobFileParser; }()); exports.BlobFileParser = BlobFileParser; var JSONFileParser = (function () { function JSONFileParser() { } JSONFileParser.prototype.parse = function (r) { return r.json(); }; return JSONFileParser; }()); exports.JSONFileParser = JSONFileParser; var BufferFileParser = (function () { function BufferFileParser() { } BufferFileParser.prototype.parse = function (r) { if (util_1.Util.isFunction(r.arrayBuffer)) { return r.arrayBuffer(); } return r.buffer(); }; return BufferFileParser; }()); exports.BufferFileParser = BufferFileParser; /***/ }), /* 3 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var logging_1 = __webpack_require__(5); function defaultLog(error) { logging_1.Logger.log({ data: {}, level: logging_1.LogLevel.Error, message: "[" + error.name + "]::" + error.message }); } /** * Represents an exception with an HttpClient request * */ var ProcessHttpClientResponseException = (function (_super) { __extends(ProcessHttpClientResponseException, _super); function ProcessHttpClientResponseException(status, statusText, data) { var _this = _super.call(this, "Error making HttpClient request in queryable: [" + status + "] " + statusText) || this; _this.status = status; _this.statusText = statusText; _this.data = data; _this.name = "ProcessHttpClientResponseException"; logging_1.Logger.log({ data: _this.data, level: logging_1.LogLevel.Error, message: _this.message }); return _this; } return ProcessHttpClientResponseException; }(Error)); exports.ProcessHttpClientResponseException = ProcessHttpClientResponseException; var NoCacheAvailableException = (function (_super) { __extends(NoCacheAvailableException, _super); function NoCacheAvailableException(msg) { if (msg === void 0) { msg = "Cannot create a caching configuration provider since cache is not available."; } var _this = _super.call(this, msg) || this; _this.name = "NoCacheAvailableException"; defaultLog(_this); return _this; } return NoCacheAvailableException; }(Error)); exports.NoCacheAvailableException = NoCacheAvailableException; var APIUrlException = (function (_super) { __extends(APIUrlException, _super); function APIUrlException(msg) { if (msg === void 0) { msg = "Unable to determine API url."; } var _this = _super.call(this, msg) || this; _this.name = "APIUrlException"; defaultLog(_this); return _this; } return APIUrlException; }(Error)); exports.APIUrlException = APIUrlException; var AuthUrlException = (function (_super) { __extends(AuthUrlException, _super); function AuthUrlException(data, msg) { if (msg === void 0) { msg = "Auth URL Endpoint could not be determined from data. Data logged."; } var _this = _super.call(this, msg) || this; _this.name = "APIUrlException"; logging_1.Logger.log({ data: data, level: logging_1.LogLevel.Error, message: _this.message }); return _this; } return AuthUrlException; }(Error)); exports.AuthUrlException = AuthUrlException; var NodeFetchClientUnsupportedException = (function (_super) { __extends(NodeFetchClientUnsupportedException, _super); function NodeFetchClientUnsupportedException(msg) { if (msg === void 0) { msg = "Using NodeFetchClient in the browser is not supported."; } var _this = _super.call(this, msg) || this; _this.name = "NodeFetchClientUnsupportedException"; defaultLog(_this); return _this; } return NodeFetchClientUnsupportedException; }(Error)); exports.NodeFetchClientUnsupportedException = NodeFetchClientUnsupportedException; var SPRequestExecutorUndefinedException = (function (_super) { __extends(SPRequestExecutorUndefinedException, _super); function SPRequestExecutorUndefinedException() { var _this = this; var msg = [ "SP.RequestExecutor is undefined. ", "Load the SP.RequestExecutor.js library (/_layouts/15/SP.RequestExecutor.js) before loading the PnP JS Core library.", ].join(" "); _this = _super.call(this, msg) || this; _this.name = "SPRequestExecutorUndefinedException"; defaultLog(_this); return _this; } return SPRequestExecutorUndefinedException; }(Error)); exports.SPRequestExecutorUndefinedException = SPRequestExecutorUndefinedException; var MaxCommentLengthException = (function (_super) { __extends(MaxCommentLengthException, _super); function MaxCommentLengthException(msg) { if (msg === void 0) { msg = "The maximum comment length is 1023 characters."; } var _this = _super.call(this, msg) || this; _this.name = "MaxCommentLengthException"; defaultLog(_this); return _this; } return MaxCommentLengthException; }(Error)); exports.MaxCommentLengthException = MaxCommentLengthException; var NotSupportedInBatchException = (function (_super) { __extends(NotSupportedInBatchException, _super); function NotSupportedInBatchException(operation) { if (operation === void 0) { operation = "This operation"; } var _this = _super.call(this, operation + " is not supported as part of a batch.") || this; _this.name = "NotSupportedInBatchException"; defaultLog(_this); return _this; } return NotSupportedInBatchException; }(Error)); exports.NotSupportedInBatchException = NotSupportedInBatchException; var ODataIdException = (function (_super) { __extends(ODataIdException, _super); function ODataIdException(data, msg) { if (msg === void 0) { msg = "Could not extract odata id in object, you may be using nometadata. Object data logged to logger."; } var _this = _super.call(this, msg) || this; _this.name = "ODataIdException"; logging_1.Logger.log({ data: data, level: logging_1.LogLevel.Error, message: _this.message }); return _this; } return ODataIdException; }(Error)); exports.ODataIdException = ODataIdException; var BatchParseException = (function (_super) { __extends(BatchParseException, _super); function BatchParseException(msg) { var _this = _super.call(this, msg) || this; _this.name = "BatchParseException"; defaultLog(_this); return _this; } return BatchParseException; }(Error)); exports.BatchParseException = BatchParseException; var AlreadyInBatchException = (function (_super) { __extends(AlreadyInBatchException, _super); function AlreadyInBatchException(msg) { if (msg === void 0) { msg = "This query is already part of a batch."; } var _this = _super.call(this, msg) || this; _this.name = "AlreadyInBatchException"; defaultLog(_this); return _this; } return AlreadyInBatchException; }(Error)); exports.AlreadyInBatchException = AlreadyInBatchException; var FunctionExpectedException = (function (_super) { __extends(FunctionExpectedException, _super); function FunctionExpectedException(msg) { if (msg === void 0) { msg = "This query is already part of a batch."; } var _this = _super.call(this, msg) || this; _this.name = "FunctionExpectedException"; defaultLog(_this); return _this; } return FunctionExpectedException; }(Error)); exports.FunctionExpectedException = FunctionExpectedException; var UrlException = (function (_super) { __extends(UrlException, _super); function UrlException(msg) { var _this = _super.call(this, msg) || this; _this.name = "UrlException"; defaultLog(_this); return _this; } return UrlException; }(Error)); exports.UrlException = UrlException; /***/ }), /* 4 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var fetchclient_1 = __webpack_require__(21); var RuntimeConfigImpl = (function () { function RuntimeConfigImpl() { // these are our default values for the library this._headers = null; this._defaultCachingStore = "session"; this._defaultCachingTimeoutSeconds = 60; this._globalCacheDisable = false; this._fetchClientFactory = function () { return new fetchclient_1.FetchClient(); }; this._baseUrl = null; this._spfxContext = null; } RuntimeConfigImpl.prototype.set = function (config) { if (config.hasOwnProperty("headers")) { this._headers = config.headers; } if (config.hasOwnProperty("globalCacheDisable")) { this._globalCacheDisable = config.globalCacheDisable; } if (config.hasOwnProperty("defaultCachingStore")) { this._defaultCachingStore = config.defaultCachingStore; } if (config.hasOwnProperty("defaultCachingTimeoutSeconds")) { this._defaultCachingTimeoutSeconds = config.defaultCachingTimeoutSeconds; } if (config.hasOwnProperty("fetchClientFactory")) { this._fetchClientFactory = config.fetchClientFactory; } if (config.hasOwnProperty("baseUrl")) { this._baseUrl = config.baseUrl; } if (config.hasOwnProperty("spfxContext")) { this._spfxContext = config.spfxContext; } }; Object.defineProperty(RuntimeConfigImpl.prototype, "headers", { get: function () { return this._headers; }, enumerable: true, configurable: true }); Object.defineProperty(RuntimeConfigImpl.prototype, "defaultCachingStore", { get: function () { return this._defaultCachingStore; }, enumerable: true, configurable: true }); Object.defineProperty(RuntimeConfigImpl.prototype, "defaultCachingTimeoutSeconds", { get: function () { return this._defaultCachingTimeoutSeconds; }, enumerable: true, configurable: true }); Object.defineProperty(RuntimeConfigImpl.prototype, "globalCacheDisable", { get: function () { return this._globalCacheDisable; }, enumerable: true, configurable: true }); Object.defineProperty(RuntimeConfigImpl.prototype, "fetchClientFactory", { get: function () { return this._fetchClientFactory; }, enumerable: true, configurable: true }); Object.defineProperty(RuntimeConfigImpl.prototype, "baseUrl", { get: function () { if (this._baseUrl !== null) { return this._baseUrl; } else if (this._spfxContext !== null) { return this._spfxContext.pageContext.web.absoluteUrl; } return null; }, enumerable: true, configurable: true }); return RuntimeConfigImpl; }()); exports.RuntimeConfigImpl = RuntimeConfigImpl; var _runtimeConfig = new RuntimeConfigImpl(); exports.RuntimeConfig = _runtimeConfig; function setRuntimeConfig(config) { _runtimeConfig.set(config); } exports.setRuntimeConfig = setRuntimeConfig; /***/ }), /* 5 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * A set of logging levels * */ var LogLevel; (function (LogLevel) { LogLevel[LogLevel["Verbose"] = 0] = "Verbose"; LogLevel[LogLevel["Info"] = 1] = "Info"; LogLevel[LogLevel["Warning"] = 2] = "Warning"; LogLevel[LogLevel["Error"] = 3] = "Error"; LogLevel[LogLevel["Off"] = 99] = "Off"; })(LogLevel = exports.LogLevel || (exports.LogLevel = {})); /** * Class used to subscribe ILogListener and log messages throughout an application * */ var Logger = (function () { function Logger() { } Object.defineProperty(Logger, "activeLogLevel", { get: function () { return Logger.instance.activeLogLevel; }, set: function (value) { Logger.instance.activeLogLevel = value; }, enumerable: true, configurable: true }); Object.defineProperty(Logger, "instance", { get: function () { if (typeof Logger._instance === "undefined" || Logger._instance === null) { Logger._instance = new LoggerImpl(); } return Logger._instance; }, enumerable: true, configurable: true }); /** * Adds ILogListener instances to the set of subscribed listeners * * @param listeners One or more listeners to subscribe to this log */ Logger.subscribe = function () { var listeners = []; for (var _i = 0; _i < arguments.length; _i++) { listeners[_i] = arguments[_i]; } listeners.map(function (listener) { return Logger.instance.subscribe(listener); }); }; /** * Clears the subscribers collection, returning the collection before modifiction */ Logger.clearSubscribers = function () { return Logger.instance.clearSubscribers(); }; Object.defineProperty(Logger, "count", { /** * Gets the current subscriber count */ get: function () { return Logger.instance.count; }, enumerable: true, configurable: true }); /** * Writes the supplied string to the subscribed listeners * * @param message The message to write * @param level [Optional] if supplied will be used as the level of the entry (Default: LogLevel.Verbose) */ Logger.write = function (message, level) { if (level === void 0) { level = LogLevel.Verbose; } Logger.instance.log({ level: level, message: message }); }; /** * Writes the supplied string to the subscribed listeners * * @param json The json object to stringify and write * @param level [Optional] if supplied will be used as the level of the entry (Default: LogLevel.Verbose) */ Logger.writeJSON = function (json, level) { if (level === void 0) { level = LogLevel.Verbose; } Logger.instance.log({ level: level, message: JSON.stringify(json) }); }; /** * Logs the supplied entry to the subscribed listeners * * @param entry The message to log */ Logger.log = function (entry) { Logger.instance.log(entry); }; /** * Logs performance tracking data for the the execution duration of the supplied function using console.profile * * @param name The name of this profile boundary * @param f The function to execute and track within this performance boundary */ Logger.measure = function (name, f) { return Logger.instance.measure(name, f); }; return Logger; }()); exports.Logger = Logger; var LoggerImpl = (function () { function LoggerImpl(activeLogLevel, subscribers) { if (activeLogLevel === void 0) { activeLogLevel = LogLevel.Warning; } if (subscribers === void 0) { subscribers = []; } this.activeLogLevel = activeLogLevel; this.subscribers = subscribers; } LoggerImpl.prototype.subscribe = function (listener) { this.subscribers.push(listener); }; LoggerImpl.prototype.clearSubscribers = function () { var s = this.subscribers.slice(0); this.subscribers.length = 0; return s; }; Object.defineProperty(LoggerImpl.prototype, "count", { get: function () { return this.subscribers.length; }, enumerable: true, configurable: true }); LoggerImpl.prototype.write = function (message, level) { if (level === void 0) { level = LogLevel.Verbose; } this.log({ level: level, message: message }); }; LoggerImpl.prototype.log = function (entry) { if (typeof entry === "undefined" || entry.level < this.activeLogLevel) { return; } this.subscribers.map(function (subscriber) { return subscriber.log(entry); }); }; LoggerImpl.prototype.measure = function (name, f) { console.profile(name); try { return f(); } finally { console.profileEnd(); } }; return LoggerImpl; }()); /** * Implementation of ILogListener which logs to the browser console * */ var ConsoleListener = (function () { function ConsoleListener() { } /** * Any associated data that a given logging listener may choose to log or ignore * * @param entry The information to be logged */ ConsoleListener.prototype.log = function (entry) { var msg = this.format(entry); switch (entry.level) { case LogLevel.Verbose: case LogLevel.Info: console.log(msg); break; case LogLevel.Warning: console.warn(msg); break; case LogLevel.Error: console.error(msg); break; } }; /** * Formats the message * * @param entry The information to format into a string */ ConsoleListener.prototype.format = function (entry) { return "Message: " + entry.message + " Data: " + JSON.stringify(entry.data); }; return ConsoleListener; }()); exports.ConsoleListener = ConsoleListener; /** * Implementation of ILogListener which logs to the supplied function * */ var FunctionListener = (function () { /** * Creates a new instance of the FunctionListener class * * @constructor * @param method The method to which any logging data will be passed */ function FunctionListener(method) { this.method = method; } /** * Any associated data that a given logging listener may choose to log or ignore * * @param entry The information to be logged */ FunctionListener.prototype.log = function (entry) { this.method(entry); }; return FunctionListener; }()); exports.FunctionListener = FunctionListener; /***/ }), /* 6 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * Generic dictionary */ var Dictionary = (function () { /** * Creates a new instance of the Dictionary<T> class * * @constructor */ function Dictionary(keys, values) { if (keys === void 0) { keys = []; } if (values === void 0) { values = []; } this.keys = keys; this.values = values; } /** * Gets a value from the collection using the specified key * * @param key The key whose value we want to return, returns null if the key does not exist */ Dictionary.prototype.get = function (key) { var index = this.keys.indexOf(key); if (index < 0) { return null; } return this.values[index]; }; /** * Adds the supplied key and value to the dictionary * * @param key The key to add * @param o The value to add */ Dictionary.prototype.add = function (key, o) { var index = this.keys.indexOf(key); if (index > -1) { this.values[index] = o; } else { this.keys.push(key); this.values.push(o); } }; /** * Merges the supplied typed hash into this dictionary instance. Existing values are updated and new ones are created as appropriate. */ Dictionary.prototype.merge = function (source) { var _this = this; if ("getKeys" in source) { var sourceAsDictionary_1 = source; sourceAsDictionary_1.getKeys().map(function (key) { _this.add(key, sourceAsDictionary_1.get(key)); }); } else { var sourceAsHash = source; for (var key in sourceAsHash) { if (sourceAsHash.hasOwnProperty(key)) { this.add(key, sourceAsHash[key]); } } } }; /** * Removes a value from the dictionary * * @param key The key of the key/value pair to remove. Returns null if the key was not found. */ Dictionary.prototype.remove = function (key) { var index = this.keys.indexOf(key); if (index < 0) { return null; } var val = this.values[index]; this.keys.splice(index, 1); this.values.splice(index, 1); return val; }; /** * Returns all the keys currently in the dictionary as an array */ Dictionary.prototype.getKeys = function () { return this.keys; }; /** * Returns all the values currently in the dictionary as an array */ Dictionary.prototype.getValues = function () { return this.values; }; /** * Clears the current dictionary */ Dictionary.prototype.clear = function () { this.keys = []; this.values = []; }; /** * Gets a count of the items currently in the dictionary */ Dictionary.prototype.count = function () { return this.keys.length; }; return Dictionary; }()); exports.Dictionary = Dictionary; /***/ }), /* 7 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var queryable_1 = __webpack_require__(1); var odata_1 = __webpack_require__(2); var util_1 = __webpack_require__(0); var exceptions_1 = __webpack_require__(3); var webparts_1 = __webpack_require__(50); var items_1 = __webpack_require__(10); var queryableshareable_1 = __webpack_require__(12); var odata_2 = __webpack_require__(2); /** * Describes a collection of File objects * */ var Files = (function (_super) { __extends(Files, _super); /** * Creates a new instance of the Files class * * @param baseUrl The url or Queryable which forms the parent of this fields collection */ function Files(baseUrl, path) { if (path === void 0) { path = "files"; } return _super.call(this, baseUrl, path) || this; } /** * Gets a File by filename * * @param name The name of the file, including extension. */ Files.prototype.getByName = function (name) { var f = new File(this); f.concat("('" + name + "')"); return f; }; /** * Uploads a file. Not supported for batching * * @param url The folder-relative url of the file. * @param content The file contents blob. * @param shouldOverWrite Should a file with the same name in the same location be overwritten? (default: true) * @returns The new File and the raw response. */ Files.prototype.add = function (url, content, shouldOverWrite) { var _this = this; if (shouldOverWrite === void 0) { shouldOverWrite = true; } return new Files(this, "add(overwrite=" + shouldOverWrite + ",url='" + url + "')") .post({ body: content, }).then(function (response) { return { data: response, file: _this.getByName(url), }; }); }; /** * Uploads a file. Not supported for batching * * @param url The folder-relative url of the file. * @param content The Blob file content to add * @param progress A callback function which can be used to track the progress of the upload * @param shouldOverWrite Should a file with the same name in the same location be overwritten? (default: true) * @param chunkSize The size of each file slice, in bytes (default: 10485760) * @returns The new File and the raw response. */ Files.prototype.addChunked = function (url, content, progress, shouldOverWrite, chunkSize) { var _this = this; if (shouldOverWrite === void 0) { shouldOverWrite = true; } if (chunkSize === void 0) { chunkSize = 10485760; } var adder = this.clone(Files, "add(overwrite=" + shouldOverWrite + ",url='" + url + "')"); return adder.post().then(function () { return _this.getByName(url); }).then(function (file) { return file.setContentChunked(content, progress, chunkSize); }).then(function (response) { return { data: response, file: _this.getByName(url), }; }); }; /** * Adds a ghosted file to an existing list or document library. Not supported for batching. * * @param fileUrl The server-relative url where you want to save the file. * @param templateFileType The type of use to create the file. * @returns The template file that was added and the raw response. */ Files.prototype.addTemplateFile = function (fileUrl, templateFileType) { var _this = this; return this.clone(Files, "addTemplateFile(urloffile='" + fileUrl + "',templatefiletype=" + templateFileType + ")") .post().then(function (response) { return { data: response, file: _this.getByName(fileUrl), }; }); }; return Files; }(queryable_1.QueryableCollection)); exports.Files = Files; /** * Describes a single File instance * */ var File = (function (_super) { __extends(File, _super); function File() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(File.prototype, "listItemAllFields", { /** * Gets a value that specifies the list item field values for the list item corresponding to the file. * */ get: function () { return new queryable_1.QueryableCollection(this, "listItemAllFields"); }, enumerable: true, configurable: true }); Object.defineProperty(File.prototype, "versions", { /** * Gets a collection of versions * */ get: function () { return new Versions(this); }, enumerable: true, configurable: true }); /** * Approves the file submitted for content approval with the specified comment. * Only documents in lists that are enabled for content approval can be approved. * * @param comment The comment for the approval. */ File.prototype.approve = function (comment) { if (comment === void 0) { comment = ""; } return this.clone(File, "approve(comment='" + comment + "')", true).post(); }; /** * Stops the chunk upload session without saving the uploaded data. Does not support batching. * If the file doesn’t already exist in the library, the partially uploaded file will be deleted. * Use this in response to user action (as in a request to cancel an upload) or an error or exception. * Use the uploadId value that was passed to the StartUpload method that started the upload session. * This method is currently available only on Office 365. * * @param uploadId The unique identifier of the upload session. */ File.prototype.cancelUpload = function (uploadId) { return this.clone(File, "cancelUpload(uploadId=guid'" + uploadId + "')", false).post(); }; /** * Checks the file in to a document library based on the check-in type. * * @param comment A comment for the check-in. Its length must be <= 1023. * @param checkinType The check-in type for the file. */ File.prototype.checkin = function (comment, checkinType) { if (comment === void 0) { comment = ""; } if (checkinType === void 0) { checkinType = CheckinType.Major; } if (comment.length > 1023) { throw new exceptions_1.MaxCommentLengthException(); } return this.clone(File, "checkin(comment='" + comment + "',checkintype=" + checkinType + ")", true).post(); }; /** * Checks out the file from a document library. */ File.prototype.checkout = function () { return this.clone(File, "checkout", true).post(); }; /** * Copies the file to the destination url. * * @param url The absolute url or server relative url of the destination file path to copy to. * @param shouldOverWrite Should a file with the same name in the same location be overwritten? */ File.prototype.copyTo = function (url, shouldOverWrite) { if (shouldOverWrite === void 0) { shouldOverWrite = true; } return this.clone(File, "copyTo(strnewurl='" + url + "',boverwrite=" + shouldOverWrite + ")", true).post(); }; /** * Delete this file. * * @param eTag Value used in the IF-Match header, by default "*" */ File.prototype.delete = function (eTag) { if (eTag === void 0) { eTag = "*"; } return this.clone(File, null, true).post({ headers: { "IF-Match": eTag, "X-HTTP-Method": "DELETE", }, }); }; /** * Denies approval for a file that was submitted for content approval. * Only documents in lists that are enabled for content approval can be denied. * * @param comment The comment for the denial. */ File.prototype.deny = function (comment) { if (comment === void 0) { comment = ""; } if (comment.length > 1023) { throw new exceptions_1.MaxCommentLengthException(); } return this.clone(File, "deny(comment='" + comment + "')", true).post(); }; /** * Specifies the control set used to access, modify, or add Web Parts associated with this Web Part Page and view. * An exception is thrown if the file is not an ASPX page. * * @param scope The WebPartsPersonalizationScope view on the Web Parts page. */ File.prototype.getLimitedWebPartManager = function (scope) { if (scope === void 0) { scope = WebPartsPersonalizationScope.Shared; } return new webparts_1.LimitedWebPartManager(this, "getLimitedWebPartManager(scope=" + scope + ")"); }; /** * Moves the file to the specified destination url. * * @param url The absolute url or server relative url of the destination file path to move to. * @param moveOperations The bitwise MoveOperations value for how to move the file. */ File.prototype.moveTo = function (url, moveOperations) { if (moveOperations === void 0) { moveOperations = MoveOperations.Overwrite; } return this.clone(File, "moveTo(newurl='" + url + "',flags=" + moveOperations + ")", true).post(); }; /** * Submits the file for content approval with the specified comment. * * @param comment The comment for the published file. Its length must be <= 1023. */ File.prototype.publish = function (comment) { if (comment === void 0) { comment = ""; } if (comment.length > 1023) { throw new exceptions_1.MaxCommentLengthException(); } return this.clone(File, "publish(comment='" + comment + "')", true).post(); }; /** * Moves the file to the Recycle Bin and returns the identifier of the new Recycle Bin item. * * @returns The GUID of the recycled file. */ File.prototype.recycle = function () { return this.clone(File, "recycle", true).post(); }; /** * Reverts an existing checkout for the file. * */ File.prototype.undoCheckout = function () { return this.clone(File, "undoCheckout", true).post(); }; /** * Removes the file from content approval or unpublish a major version. * * @param comment The comment for the unpublish operation. Its length must be <= 1023. */ File.prototype.unpublish = function (comment) { if (comment === void 0) { comment = ""; } if (comment.length > 1023) { throw new exceptions_1.MaxCommentLengthException(); } return this.clone(File, "unpublish(comment='" + comment + "')", true).post(); }; /** * Gets the contents of the file as text. Not supported in batching. * */ File.prototype.getText = function () { return this.clone(File, "$value").get(new odata_1.TextFileParser(), { headers: { "binaryStringResponseBody": "true" } }); }; /** * Gets the contents of the file as a blob, does not work in Node.js. Not supported in batching. * */ File.prototype.getBlob = function () { return this.clone(File, "$value").get(new odata_1.BlobFileParser(), { headers: { "binaryStringResponseBody": "true" } }); }; /** * Gets the contents of a file as an ArrayBuffer, works in Node.js. Not supported in batching. */ File.prototype.getBuffer = function () { return this.clone(File, "$value").get(new odata_1.BufferFileParser(), { headers: { "binaryStringResponseBody": "true" } }); }; /** * Gets the contents of a file as an ArrayBuffer, works in Node.js. Not supported in batching. */ File.prototype.getJSON = function () { return this.clone(File, "$value").get(new odata_1.JSONFileParser(), { headers: { "binaryStringResponseBody": "true" } }); }; /** * Sets the content of a file, for large files use setContentChunked. Not supported in batching. * * @param content The file content * */ File.prototype.setContent = function (content) { var _this = this; return this.clone(File, "$value").post({ body: content, headers: { "X-HTTP-Method": "PUT", }, }).then(function (_) { return new File(_this); }); }; /** * Gets the associated list item for this folder, loading the default properties */ File.prototype.getItem = function () { var selects = []; for (var _i = 0; _i < arguments.length; _i++) { selects[_i] = arguments[_i]; } var q = this.listItemAllFields; return q.select.apply(q, selects).get().then(function (d) { return util_1.Util.extend(new items_1.Item(odata_2.getEntityUrl(d)), d); }); }; /** * Sets the contents of a file using a chunked upload approach. Not supported in batching. * * @param file The file to upload * @param progress A callback function which can be used to track the progress of the upload * @param chunkSize The size of each file slice, in bytes (default: 10485760) */ File.prototype.setContentChunked = function (file, progress, chunkSize) { if (chunkSize === void 0) { chunkSize = 10485760; } if (typeof progress === "undefined") { progress = function () { return null; }; } var self = this; var fileSize = file.size; var blockCount = parseInt((file.size / chunkSize).toString(), 10) + ((file.size % chunkSize === 0) ? 1 : 0); var uploadId = util_1.Util.getGUID(); // start the chain with the first fragment progress({ blockNumber: 1, chunkSize: chunkSize, currentPointer: 0, fileSize: fileSize, stage: "starting", totalBlocks: blockCount }); var chain = self.startUpload(uploadId, file.slice(0, chunkSize)); var _loop_1 = function (i) { chain = chain.then(function (pointer) { progress({ blockNumber: i, chunkSize: chunkSize, currentPointer: pointer, fileSize: fileSize, stage: "continue", totalBlocks: blockCount }); return self.continueUpload(uploadId, pointer, file.slice(pointer, pointer + chunkSize)); }); }; // skip the first and last blocks for (var i = 2; i < blockCount; i++) { _loop_1(i); } return chain.then(function (pointer) { progress({ blockNumber: blockCount, chunkSize: chunkSize, currentPointer: pointer, fileSize: fileSize, stage: "finishing", totalBlocks: blockCount }); return self.finishUpload(uploadId, pointer, file.slice(pointer)); }).then(function (_) { return self; }); }; /** * Starts a new chunk upload session and uploads the first fragment. * The current file content is not changed when this method completes. * The method is idempotent (and therefore does not change the result) as long as you use the same values for uploadId and stream. * The upload session ends either when you use the CancelUpload method or when you successfully * complete the upload session by passing the rest of the file contents through the ContinueUpload and FinishUpload methods. * The StartUpload and ContinueUpload methods return the size of the running total of uploaded data in bytes, * so you can pass those return values to subsequent uses of ContinueUpload and FinishUpload. * This method is currently available only on Office 365. * * @param uploadId The unique identifier of the upload session. * @param fragment The file contents. * @returns The size of the total uploaded data in bytes. */ File.prototype.startUpload = function (uploadId, fragment) { return this.clone(File, "startUpload(uploadId=guid'" + uploadId + "')").postAs({ body: fragment }).then(function (n) { return parseFloat(n); }); }; /** * Continues the chunk upload session with an additional fragment. * The current file content is not changed. * Use the uploadId value that was passed to the StartUpload method that started the upload session. * This method is currently available only on Office 365. * * @param uploadId The unique identifier of the upload session. * @param fileOffset The size of the offset into the file where the fragment starts. * @param fragment The file contents. * @returns The size of the total uploaded data in bytes. */ File.prototype.continueUpload = function (uploadId, fileOffset, fragment) { return this.clone(File, "continueUpload(uploadId=guid'" + uploadId + "',fileOffset=" + fileOffset + ")").postAs({ body: fragment }).then(function (n) { return parseFloat(n); }); }; /** * Uploads the last file fragment and commits the file. The current file content is changed when this method completes. * Use the uploadId value that was passed to the StartUpload method that started the upload session. * This method is currently available only on Office 365. * * @param uploadId The unique identifier of the upload session. * @param fileOffset The size of the offset into the file where the fragment starts. * @param fragment The file contents. * @returns The newly uploaded file. */ File.prototype.finishUpload = function (uploadId, fileOffset, fragment) { return this.clone(File, "finishUpload(uploadId=guid'" + uploadId + "',fileOffset=" + fileOffset + ")") .postAs({ body: fragment }).then(function (response) { return { data: response, file: new File(response.ServerRelativeUrl), }; }); }; return File; }(queryableshareable_1.QueryableShareableFile)); exports.File = File; /** * Describes a collection of Version objects * */ var Versions = (function (_super) { __extends(Versions, _super); /** * Creates a new instance of the File class * * @param baseUrl The url or Queryable which forms the parent of this fields collection */ function Versions(baseUrl, path) { if (path === void 0) { path = "versions"; } return _super.call(this, baseUrl, path) || this; } /** * Gets a version by id * * @param versionId The id of the version to retrieve */ Versions.prototype.getById = function (versionId) { var v = new Version(this); v.concat("(" + versionId + ")"); return v; }; /** * Deletes all the file version objects in the collection. * */ Versions.prototype.deleteAll = function () { return new Versions(this, "deleteAll").post(); }; /** * Deletes the specified version of the file. * * @param versionId The ID of the file version to delete. */ Versions.prototype.deleteById = function (versionId) { return this.clone(Versions, "deleteById(vid=" + versionId + ")", true).post(); }; /** * Deletes the file version object with the specified version label. * * @param label The version label of the file version to delete, for example: 1.2 */ Versions.prototype.deleteByLabel = function (label) { return this.clone(Versions, "deleteByLabel(versionlabel='" + label + "')", true).post(); }; /** * Creates a new file version from the file specified by the version label. * * @param label The version label of the file version to restore, for example: 1.2 */ Versions.prototype.restoreByLabel = function (label) { return this.clone(Versions, "restoreByLabel(versionlabel='" + label + "')", true).post(); }; return Versions; }(queryable_1.QueryableCollection)); exports.Versions = Versions; /** * Describes a single Version instance * */ var Version = (function (_super) { __extends(Version, _super); function Version() { return _super !== null && _super.apply(this, arguments) || this; } /** * Delete a specific version of a file. * * @param eTag Value used in the IF-Match header, by default "*" */ Version.prototype.delete = function (eTag) { if (eTag === void 0) { eTag = "*"; } return this.post({ headers: { "IF-Match": eTag, "X-HTTP-Method": "DELETE", }, }); }; return Version; }(queryable_1.QueryableInstance)); exports.Version = Version; var CheckinType; (function (CheckinType) { CheckinType[CheckinType["Minor"] = 0] = "Minor"; CheckinType[CheckinType["Major"] = 1] = "Major"; CheckinType[CheckinType["Overwrite"] = 2] = "Overwrite"; })(CheckinType = exports.CheckinType || (exports.CheckinType = {})); var WebPartsPersonalizationScope; (function (WebPartsPersonalizationScope) { WebPartsPersonalizationScope[WebPartsPersonalizationScope["User"] = 0] = "User"; WebPartsPersonalizationScope[WebPartsPersonalizationScope["Shared"] = 1] = "Shared"; })(WebPartsPersonalizationScope = exports.WebPartsPersonalizationScope || (exports.WebPartsPersonalizationScope = {})); var MoveOperations; (function (MoveOperations) { MoveOperations[MoveOperations["Overwrite"] = 1] = "Overwrite"; MoveOperations[MoveOperations["AllowBrokenThickets"] = 8] = "AllowBrokenThickets"; })(MoveOperations = exports.MoveOperations || (exports.MoveOperations = {})); var TemplateFileType; (function (TemplateFileType) { TemplateFileType[TemplateFileType["StandardPage"] = 0] = "StandardPage"; TemplateFileType[TemplateFileType["WikiPage"] = 1] = "WikiPage"; TemplateFileType[TemplateFileType["FormPage"] = 2] = "FormPage"; })(TemplateFileType = exports.TemplateFileType || (exports.TemplateFileType = {})); /***/ }), /* 8 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); 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; }; Object.defineProperty(exports, "__esModule", { value: true }); var queryable_1 = __webpack_require__(1); var lists_1 = __webpack_require__(11); var fields_1 = __webpack_require__(24); var navigation_1 = __webpack_require__(25); var sitegroups_1 = __webpack_require__(18); var contenttypes_1 = __webpack_require__(16); var folders_1 = __webpack_require__(9); var roles_1 = __webpack_require__(17); var files_1 = __webpack_require__(7); var util_1 = __webpack_require__(0); var lists_2 = __webpack_require__(11); var siteusers_1 = __webpack_require__(30); var usercustomactions_1 = __webpack_require__(19); var odata_1 = __webpack_require__(2); var features_1 = __webpack_require__(23); var decorators_1 = __webpack_require__(51); var queryableshareable_1 = __webpack_require__(12); var relateditems_1 = __webpack_require__(46); var Webs = (function (_super) { __extends(Webs, _super); function Webs(baseUrl, webPath) { if (webPath === void 0) { webPath = "webs"; } return _super.call(this, baseUrl, webPath) || this; } /** * Adds a new web to the collection * * @param title The new web's title * @param url The new web's relative url * @param description The web web's description * @param template The web's template * @param language The language code to use for this web * @param inheritPermissions If true permissions will be inherited from the partent web * @param additionalSettings Will be passed as part of the web creation body */ Webs.prototype.add = function (title, url, description, template, language, inheritPermissions, additionalSettings) { if (description === void 0) { description = ""; } if (template === void 0) { template = "STS"; } if (language === void 0) { language = 1033; } if (inheritPermissions === void 0) { inheritPermissions = true; } if (additionalSettings === void 0) { additionalSettings = {}; } var props = util_1.Util.extend({ Description: description, Language: language, Title: title, Url: url, UseSamePermissionsAsParentSite: inheritPermissions, WebTemplate: template, }, additionalSettings); var postBody = JSON.stringify({ "parameters": util_1.Util.extend({ "__metadata": { "type": "SP.WebCreationInformation" }, }, props), }); return this.clone(Webs, "add", true).post({ body: postBody }).then(function (data) { return { data: data, web: new Web(odata_1.extractOdataId(data).replace(/_api\/web\/?/i, "")), }; }); }; return Webs; }(queryable_1.QueryableCollection)); exports.Webs = Webs; var WebInfos = (function (_super) { __extends(WebInfos, _super); function WebInfos(baseUrl, webPath) { if (webPath === void 0) { webPath = "webinfos"; } return _super.call(this, baseUrl, webPath) || this; } return WebInfos; }(queryable_1.QueryableCollection)); exports.WebInfos = WebInfos; /** * Describes a web * */ var Web = (function (_super) { __extends(Web, _super); function Web(baseUrl, path) { if (path === void 0) { path = "_api/web"; } return _super.call(this, baseUrl, path) || this; } /** * Creates a new web instance from the given url by indexing the location of the /_api/ * segment. If this is not found the method creates a new web with the entire string as * supplied. * * @param url */ Web.fromUrl = function (url, path) { if (url === null) { return new Web(""); } var index = url.indexOf("_api/"); if (index > -1) { return new Web(url.substr(0, index), path); } return new Web(url, path); }; Object.defineProperty(Web.prototype, "webs", { get: function () { return new Webs(this); }, enumerable: true, configurable: true }); Object.defineProperty(Web.prototype, "webinfos", { get: function () { return new WebInfos(this); }, enumerable: true, configurable: true }); Object.defineProperty(Web.prototype, "contentTypes", { /** * Get the content types available in this web * */ get: function () { return new contenttypes_1.ContentTypes(this); }, enumerable: true, configurable: true }); Object.defineProperty(Web.prototype, "lists", { /** * Get the lists in this web * */ get: function () { return new lists_1.Lists(this); }, enumerable: true, configurable: true }); Object.defineProperty(Web.prototype, "fields", { /** * Gets the fields in this web * */ get: function () { return new fields_1.Fields(this); }, enumerable: true, configurable: true }); Object.defineProperty(Web.prototype, "features", { /** * Gets the active features for this web * */ get: function () { return new features_1.Features(this); }, enumerable: true, configurable: true }); Object.defineProperty(Web.prototype, "availablefields", { /** * Gets the available fields in this web * */ get: function () { return new fields_1.Fields(this, "availablefields"); }, enumerable: true, configurable: true }); Object.defineProperty(Web.prototype, "navigation", { /** * Get the navigation options in this web * */ get: function () { return new navigation_1.Navigation(this); }, enumerable: true, configurable: true }); Object.defineProperty(Web.prototype, "siteUsers", { /** * Gets the site users * */ get: function () { return new siteusers_1.SiteUsers(this); }, enumerable: true, configurable: true }); Object.defineProperty(Web.prototype, "siteGroups", { /** * Gets the site groups * */ get: function () { return new sitegroups_1.SiteGroups(this); }, enumerable: true, configurable: true }); Object.defineProperty(Web.prototype, "currentUser", { /** * Gets the current user */ get: function () { return new siteusers_1.CurrentUser(this); }, enumerable: true, configurable: true }); Object.defineProperty(Web.prototype, "folders", { /** * Get the folders in this web * */ get: function () { return new folders_1.Folders(this); }, enumerable: true, configurable: true }); Object.defineProperty(Web.prototype, "userCustomActions", { /** * Get all custom actions on a site * */ get: function () { return new usercustomactions_1.UserCustomActions(this); }, enumerable: true, configurable: true }); Object.defineProperty(Web.prototype, "roleDefinitions", { /** * Gets the collection of RoleDefinition resources. * */ get: function () { return new roles_1.RoleDefinitions(this); }, enumerable: true, configurable: true }); Object.defineProperty(Web.prototype, "relatedItems", { /** * Provides an interface to manage related items * */ get: function () { return relateditems_1.RelatedItemManagerImpl.FromUrl(this.toUrl()); }, enumerable: true, configurable: true }); /** * Creates a new batch for requests within the context of context this web * */ Web.prototype.createBatch = function () { return new odata_1.ODataBatch(this.parentUrl); }; Object.defineProperty(Web.prototype, "rootFolder", { /** * The root folder of the web */ get: function () { return new folders_1.Folder(this, "rootFolder"); }, enumerable: true, configurable: true }); Object.defineProperty(Web.prototype, "associatedOwnerGroup", { get: function () { return new sitegroups_1.SiteGroup(this, "associatedownergroup"); }, enumerable: true, configurable: true }); Object.defineProperty(Web.prototype, "associatedMemberGroup", { get: function () { return new sitegroups_1.SiteGroup(this, "associatedmembergroup"); }, enumerable: true, configurable: true }); Object.defineProperty(Web.prototype, "associatedVisitorGroup", { get: function () { return new sitegroups_1.SiteGroup(this, "associatedvisitorgroup"); }, enumerable: true, configurable: true }); /** * Get a folder by server relative url * * @param folderRelativeUrl the server relative path to the folder (including /sites/ if applicable) */ Web.prototype.getFolderByServerRelativeUrl = function (folderRelativeUrl) { return new folders_1.Folder(this, "getFolderByServerRelativeUrl('" + folderRelativeUrl + "')"); }; /** * Get a file by server relative url * * @param fileRelativeUrl the server relative path to the file (including /sites/ if applicable) */ Web.prototype.getFileByServerRelativeUrl = function (fileRelativeUrl) { return new files_1.File(this, "getFileByServerRelativeUrl('" + fileRelativeUrl + "')"); }; /** * Get a list by server relative url (list's root folder) * * @param listRelativeUrl the server relative path to the list's root folder (including /sites/ if applicable) */ Web.prototype.getList = function (listRelativeUrl) { return new lists_2.List(this, "getList('" + listRelativeUrl + "')"); }; /** * Updates this web intance with the supplied properties * * @param properties A plain object hash of values to update for the web */ Web.prototype.update = function (properties) { var _this = this; var postBody = JSON.stringify(util_1.Util.extend({ "__metadata": { "type": "SP.Web" }, }, properties)); return this.post({ body: postBody, headers: { "X-HTTP-Method": "MERGE", }, }).then(function (data) { return { data: data, web: _this, }; }); }; /** * Delete this web * */ Web.prototype.delete = function () { return _super.prototype.delete.call(this); }; /** * Applies the theme specified by the contents of each of the files specified in the arguments to the site. * * @param colorPaletteUrl Server-relative URL of the color palette file. * @param fontSchemeUrl Server-relative URL of the font scheme. * @param backgroundImageUrl Server-relative URL of the background image. * @param shareGenerated true to store the generated theme files in the root site, or false to store them in this site. */ Web.prototype.applyTheme = function (colorPaletteUrl, fontSchemeUrl, backgroundImageUrl, shareGenerated) { var postBody = JSON.stringify({ backgroundImageUrl: backgroundImageUrl, colorPaletteUrl: colorPaletteUrl, fontSchemeUrl: fontSchemeUrl, shareGenerated: shareGenerated, }); return this.clone(Web, "applytheme", true).post({ body: postBody }); }; /** * Applies the specified site definition or site template to the Web site that has no template applied to it. * * @param template Name of the site definition or the name of the site template */ Web.prototype.applyWebTemplate = function (template) { var q = this.clone(Web, "applywebtemplate", true); q.concat("(@t)"); q.query.add("@t", template); return q.post(); }; /** * Returns whether the current user has the given set of permissions. * * @param perms The high and low permission range. */ Web.prototype.doesUserHavePermissions = function (perms) { var q = this.clone(Web, "doesuserhavepermissions", true); q.concat("(@p)"); q.query.add("@p", JSON.stringify(perms)); return q.get(); }; /** * Checks whether the specified login name belongs to a valid user in the site. If the user doesn't exist, adds the user to the site. * * @param loginName The login name of the user (ex: i:0#.f|membership|user@domain.onmicrosoft.com) */ Web.prototype.ensureUser = function (loginName) { var postBody = JSON.stringify({ logonName: loginName, }); return this.clone(Web, "ensureuser", true).post({ body: postBody }).then(function (data) { return { data: data, user: new siteusers_1.SiteUser(odata_1.extractOdataId(data)), }; }); }; /** * Returns a collection of site templates available for the site. * * @param language The LCID of the site templates to get. * @param true to include language-neutral site templates; otherwise false */ Web.prototype.availableWebTemplates = function (language, includeCrossLanugage) { if (language === void 0) { language = 1033; } if (includeCrossLanugage === void 0) { includeCrossLanugage = true; } return new queryable_1.QueryableCollection(this, "getavailablewebtemplates(lcid=" + language + ", doincludecrosslanguage=" + includeCrossLanugage + ")"); }; /** * Returns the list gallery on the site. * * @param type The gallery type - WebTemplateCatalog = 111, WebPartCatalog = 113 ListTemplateCatalog = 114, * MasterPageCatalog = 116, SolutionCatalog = 121, ThemeCatalog = 123, DesignCatalog = 124, AppDataCatalog = 125 */ Web.prototype.getCatalog = function (type) { return this.clone(Web, "getcatalog(" + type + ")", true).select("Id").get().then(function (data) { return new lists_2.List(odata_1.extractOdataId(data)); }); }; /** * Returns the collection of changes from the change log that have occurred within the list, based on the specified query. */ Web.prototype.getChanges = function (query) { var postBody = JSON.stringify({ "query": util_1.Util.extend({ "__metadata": { "type": "SP.ChangeQuery" } }, query) }); return this.clone(Web, "getchanges", true).post({ body: postBody }); }; Object.defineProperty(Web.prototype, "customListTemplate", { /** * Gets the custom list templates for the site. * */ get: function () { return new queryable_1.QueryableCollection(this, "getcustomlisttemplates"); }, enumerable: true, configurable: true }); /** * Returns the user corresponding to the specified member identifier for the current site. * * @param id The ID of the user. */ Web.prototype.getUserById = function (id) { return new siteusers_1.SiteUser(this, "getUserById(" + id + ")"); }; /** * Returns the name of the image file for the icon that is used to represent the specified file. * * @param filename The file name. If this parameter is empty, the server returns an empty string. * @param size The size of the icon: 16x16 pixels = 0, 32x32 pixels = 1. * @param progId The ProgID of the application that was used to create the file, in the form OLEServerName.ObjectName */ Web.prototype.mapToIcon = function (filename, size, progId) { if (size === void 0) { size = 0; } if (progId === void 0) { progId = ""; } return this.clone(Web, "maptoicon(filename='" + filename + "', progid='" + progId + "', size=" + size + ")", true).get(); }; return Web; }(queryableshareable_1.QueryableShareableWeb)); __decorate([ decorators_1.deprecated("This method will be removed in future releases. Please use the methods found in queryable securable.") ], Web.prototype, "doesUserHavePermissions", null); exports.Web = Web; /***/ }), /* 9 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var queryable_1 = __webpack_require__(1); var queryableshareable_1 = __webpack_require__(12); var files_1 = __webpack_require__(7); var util_1 = __webpack_require__(0); var odata_1 = __webpack_require__(2); var items_1 = __webpack_require__(10); /** * Describes a collection of Folder objects * */ var Folders = (function (_super) { __extends(Folders, _super); /** * Creates a new instance of the Folders class * * @param baseUrl The url or Queryable which forms the parent of this fields collection */ function Folders(baseUrl, path) { if (path === void 0) { path = "folders"; } return _super.call(this, baseUrl, path) || this; } /** * Gets a folder by folder name * */ Folders.prototype.getByName = function (name) { var f = new Folder(this); f.concat("('" + name + "')"); return f; }; /** * Adds a new folder to the current folder (relative) or any folder (absolute) * * @param url The relative or absolute url where the new folder will be created. Urls starting with a forward slash are absolute. * @returns The new Folder and the raw response. */ Folders.prototype.add = function (url) { var _this = this; return this.clone(Folders, "add('" + url + "')", true).post().then(function (response) { return { data: response, folder: _this.getByName(url), }; }); }; return Folders; }(queryable_1.QueryableCollection)); exports.Folders = Folders; /** * Describes a single Folder instance * */ var Folder = (function (_super) { __extends(Folder, _super); function Folder() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(Folder.prototype, "contentTypeOrder", { /** * Specifies the sequence in which content types are displayed. * */ get: function () { return new queryable_1.QueryableCollection(this, "contentTypeOrder"); }, enumerable: true, configurable: true }); Object.defineProperty(Folder.prototype, "files", { /** * Gets this folder's files * */ get: function () { return new files_1.Files(this); }, enumerable: true, configurable: true }); Object.defineProperty(Folder.prototype, "folders", { /** * Gets this folder's sub folders * */ get: function () { return new Folders(this); }, enumerable: true, configurable: true }); Object.defineProperty(Folder.prototype, "listItemAllFields", { /** * Gets this folder's list item field values * */ get: function () { return new queryable_1.QueryableCollection(this, "listItemAllFields"); }, enumerable: true, configurable: true }); Object.defineProperty(Folder.prototype, "parentFolder", { /** * Gets the parent folder, if available * */ get: function () { return new Folder(this, "parentFolder"); }, enumerable: true, configurable: true }); Object.defineProperty(Folder.prototype, "properties", { /** * Gets this folder's properties * */ get: function () { return new queryable_1.QueryableInstance(this, "properties"); }, enumerable: true, configurable: true }); Object.defineProperty(Folder.prototype, "serverRelativeUrl", { /** * Gets this folder's server relative url * */ get: function () { return new queryable_1.Queryable(this, "serverRelativeUrl"); }, enumerable: true, configurable: true }); Object.defineProperty(Folder.prototype, "uniqueContentTypeOrder", { /** * Gets a value that specifies the content type order. * */ get: function () { return new queryable_1.QueryableCollection(this, "uniqueContentTypeOrder"); }, enumerable: true, configurable: true }); Folder.prototype.update = function (properties) { var _this = this; var postBody = JSON.stringify(util_1.Util.extend({ "__metadata": { "type": "SP.Folder" }, }, properties)); return this.post({ body: postBody, headers: { "X-HTTP-Method": "MERGE", }, }).then(function (data) { return { data: data, folder: _this, }; }); }; /** * Delete this folder * * @param eTag Value used in the IF-Match header, by default "*" */ Folder.prototype.delete = function (eTag) { if (eTag === void 0) { eTag = "*"; } return this.clone(Folder, null, true).post({ headers: { "IF-Match": eTag, "X-HTTP-Method": "DELETE", }, }); }; /** * Moves the folder to the Recycle Bin and returns the identifier of the new Recycle Bin item. */ Folder.prototype.recycle = function () { return this.clone(Folder, "recycle", true).post(); }; /** * Gets the associated list item for this folder, loading the default properties */ Folder.prototype.getItem = function () { var selects = []; for (var _i = 0; _i < arguments.length; _i++) { selects[_i] = arguments[_i]; } var q = this.listItemAllFields; return q.select.apply(q, selects).get().then(function (d) { return util_1.Util.extend(new items_1.Item(odata_1.getEntityUrl(d)), d); }); }; return Folder; }(queryableshareable_1.QueryableShareableFolder)); exports.Folder = Folder; /***/ }), /* 10 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var queryable_1 = __webpack_require__(1); var queryableshareable_1 = __webpack_require__(12); var folders_1 = __webpack_require__(9); var files_1 = __webpack_require__(7); var contenttypes_1 = __webpack_require__(16); var util_1 = __webpack_require__(0); var odata_1 = __webpack_require__(2); var attachmentfiles_1 = __webpack_require__(42); var lists_1 = __webpack_require__(11); /** * Describes a collection of Item objects * */ var Items = (function (_super) { __extends(Items, _super); /** * Creates a new instance of the Items class * * @param baseUrl The url or Queryable which forms the parent of this fields collection */ function Items(baseUrl, path) { if (path === void 0) { path = "items"; } return _super.call(this, baseUrl, path) || this; } /** * Gets an Item by id * * @param id The integer id of the item to retrieve */ Items.prototype.getById = function (id) { var i = new Item(this); i.concat("(" + id + ")"); return i; }; /** * Skips the specified number of items (https://msdn.microsoft.com/en-us/library/office/fp142385.aspx#sectionSection6) * * @param skip The starting id where the page should start, use with top to specify pages */ Items.prototype.skip = function (skip) { this._query.add("$skiptoken", encodeURIComponent("Paged=TRUE&p_ID=" + skip)); return this; }; /** * Gets a collection designed to aid in paging through data * */ Items.prototype.getPaged = function () { return this.getAs(new PagedItemCollectionParser()); }; // /** * Adds a new item to the collection * * @param properties The new items's properties */ Items.prototype.add = function (properties, listItemEntityTypeFullName) { var _this = this; if (properties === void 0) { properties = {}; } if (listItemEntityTypeFullName === void 0) { listItemEntityTypeFullName = null; } var removeDependency = this.addBatchDependency(); return this.ensureListItemEntityTypeName(listItemEntityTypeFullName).then(function (listItemEntityType) { var postBody = JSON.stringify(util_1.Util.extend({ "__metadata": { "type": listItemEntityType }, }, properties)); var promise = _this.clone(Items, null, true).postAs({ body: postBody }).then(function (data) { return { data: data, item: _this.getById(data.Id), }; }); removeDependency(); return promise; }); }; /** * Ensures we have the proper list item entity type name, either from the value provided or from the list * * @param candidatelistItemEntityTypeFullName The potential type name */ Items.prototype.ensureListItemEntityTypeName = function (candidatelistItemEntityTypeFullName) { return candidatelistItemEntityTypeFullName ? Promise.resolve(candidatelistItemEntityTypeFullName) : this.getParent(lists_1.List).getListItemEntityTypeFullName(); }; return Items; }(queryable_1.QueryableCollection)); exports.Items = Items; /** * Descrines a single Item instance * */ var Item = (function (_super) { __extends(Item, _super); function Item() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(Item.prototype, "attachmentFiles", { /** * Gets the set of attachments for this item * */ get: function () { return new attachmentfiles_1.AttachmentFiles(this); }, enumerable: true, configurable: true }); Object.defineProperty(Item.prototype, "contentType", { /** * Gets the content type for this item * */ get: function () { return new contenttypes_1.ContentType(this, "ContentType"); }, enumerable: true, configurable: true }); Object.defineProperty(Item.prototype, "effectiveBasePermissions", { /** * Gets the effective base permissions for the item * */ get: function () { return new queryable_1.Queryable(this, "EffectiveBasePermissions"); }, enumerable: true, configurable: true }); Object.defineProperty(Item.prototype, "effectiveBasePermissionsForUI", { /** * Gets the effective base permissions for the item in a UI context * */ get: function () { return new queryable_1.Queryable(this, "EffectiveBasePermissionsForUI"); }, enumerable: true, configurable: true }); Object.defineProperty(Item.prototype, "fieldValuesAsHTML", { /** * Gets the field values for this list item in their HTML representation * */ get: function () { return new queryable_1.QueryableInstance(this, "FieldValuesAsHTML"); }, enumerable: true, configurable: true }); Object.defineProperty(Item.prototype, "fieldValuesAsText", { /** * Gets the field values for this list item in their text representation * */ get: function () { return new queryable_1.QueryableInstance(this, "FieldValuesAsText"); }, enumerable: true, configurable: true }); Object.defineProperty(Item.prototype, "fieldValuesForEdit", { /** * Gets the field values for this list item for use in editing controls * */ get: function () { return new queryable_1.QueryableInstance(this, "FieldValuesForEdit"); }, enumerable: true, configurable: true }); Object.defineProperty(Item.prototype, "folder", { /** * Gets the folder associated with this list item (if this item represents a folder) * */ get: function () { return new folders_1.Folder(this, "folder"); }, enumerable: true, configurable: true }); Object.defineProperty(Item.prototype, "file", { /** * Gets the folder associated with this list item (if this item represents a folder) * */ get: function () { return new files_1.File(this, "file"); }, enumerable: true, configurable: true }); /** * Updates this list intance with the supplied properties * * @param properties A plain object hash of values to update for the list * @param eTag Value used in the IF-Match header, by default "*" */ Item.prototype.update = function (properties, eTag) { var _this = this; if (eTag === void 0) { eTag = "*"; } return new Promise(function (resolve, reject) { var removeDependency = _this.addBatchDependency(); var parentList = _this.getParent(queryable_1.QueryableInstance, _this.parentUrl.substr(0, _this.parentUrl.lastIndexOf("/"))); parentList.select("ListItemEntityTypeFullName").getAs().then(function (d) { var postBody = JSON.stringify(util_1.Util.extend({ "__metadata": { "type": d.ListItemEntityTypeFullName }, }, properties)); removeDependency(); return _this.post({ body: postBody, headers: { "IF-Match": eTag, "X-HTTP-Method": "MERGE", }, }, new ItemUpdatedParser()).then(function (data) { resolve({ data: data, item: _this, }); }); }).catch(function (e) { return reject(e); }); }); }; /** * Delete this item * * @param eTag Value used in the IF-Match header, by default "*" */ Item.prototype.delete = function (eTag) { if (eTag === void 0) { eTag = "*"; } return this.post({ headers: { "IF-Match": eTag, "X-HTTP-Method": "DELETE", }, }); }; /** * Moves the list item to the Recycle Bin and returns the identifier of the new Recycle Bin item. */ Item.prototype.recycle = function () { return this.clone(Item, "recycle", true).post(); }; /** * Gets a string representation of the full URL to the WOPI frame. * If there is no associated WOPI application, or no associated action, an empty string is returned. * * @param action Display mode: 0: view, 1: edit, 2: mobileView, 3: interactivePreview */ Item.prototype.getWopiFrameUrl = function (action) { if (action === void 0) { action = 0; } var i = this.clone(Item, "getWOPIFrameUrl(@action)", true); i._query.add("@action", action); return i.post().then(function (data) { return data.GetWOPIFrameUrl; }); }; /** * Validates and sets the values of the specified collection of fields for the list item. * * @param formValues The fields to change and their new values. * @param newDocumentUpdate true if the list item is a document being updated after upload; otherwise false. */ Item.prototype.validateUpdateListItem = function (formValues, newDocumentUpdate) { if (newDocumentUpdate === void 0) { newDocumentUpdate = false; } return this.clone(Item, "validateupdatelistitem", true).post({ body: JSON.stringify({ "formValues": formValues, bNewDocumentUpdate: newDocumentUpdate }), }); }; return Item; }(queryableshareable_1.QueryableShareableItem)); exports.Item = Item; /** * Provides paging functionality for list items */ var PagedItemCollection = (function () { function PagedItemCollection(nextUrl, results) { this.nextUrl = nextUrl; this.results = results; } Object.defineProperty(PagedItemCollection.prototype, "hasNext", { /** * If true there are more results available in the set, otherwise there are not */ get: function () { return typeof this.nextUrl === "string" && this.nextUrl.length > 0; }, enumerable: true, configurable: true }); /** * Gets the next set of results, or resolves to null if no results are available */ PagedItemCollection.prototype.getNext = function () { if (this.hasNext) { var items = new Items(this.nextUrl, null); return items.getPaged(); } return new Promise(function (r) { return r(null); }); }; return PagedItemCollection; }()); exports.PagedItemCollection = PagedItemCollection; var PagedItemCollectionParser = (function (_super) { __extends(PagedItemCollectionParser, _super); function PagedItemCollectionParser() { return _super !== null && _super.apply(this, arguments) || this; } PagedItemCollectionParser.prototype.parse = function (r) { var _this = this; return new Promise(function (resolve, reject) { if (_this.handleError(r, reject)) { r.json().then(function (json) { var nextUrl = json.hasOwnProperty("d") && json.d.hasOwnProperty("__next") ? json.d.__next : json["odata.nextLink"]; resolve(new PagedItemCollection(nextUrl, _this.parseODataJSON(json))); }); } }); }; return PagedItemCollectionParser; }(odata_1.ODataParserBase)); var ItemUpdatedParser = (function (_super) { __extends(ItemUpdatedParser, _super); function ItemUpdatedParser() { return _super !== null && _super.apply(this, arguments) || this; } ItemUpdatedParser.prototype.parse = function (r) { var _this = this; return new Promise(function (resolve, reject) { if (_this.handleError(r, reject)) { resolve({ "odata.etag": r.headers.get("etag"), }); } }); }; return ItemUpdatedParser; }(odata_1.ODataParserBase)); /***/ }), /* 11 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var items_1 = __webpack_require__(10); var views_1 = __webpack_require__(49); var contenttypes_1 = __webpack_require__(16); var fields_1 = __webpack_require__(24); var forms_1 = __webpack_require__(43); var subscriptions_1 = __webpack_require__(47); var queryable_1 = __webpack_require__(1); var queryablesecurable_1 = __webpack_require__(26); var util_1 = __webpack_require__(0); var usercustomactions_1 = __webpack_require__(19); var odata_1 = __webpack_require__(2); var exceptions_1 = __webpack_require__(3); var folders_1 = __webpack_require__(9); /** * Describes a collection of List objects * */ var Lists = (function (_super) { __extends(Lists, _super); /** * Creates a new instance of the Lists class * * @param baseUrl The url or Queryable which forms the parent of this fields collection */ function Lists(baseUrl, path) { if (path === void 0) { path = "lists"; } return _super.call(this, baseUrl, path) || this; } /** * Gets a list from the collection by title * * @param title The title of the list */ Lists.prototype.getByTitle = function (title) { return new List(this, "getByTitle('" + title + "')"); }; /** * Gets a list from the collection by guid id * * @param id The Id of the list (GUID) */ Lists.prototype.getById = function (id) { var list = new List(this); list.concat("('" + id + "')"); return list; }; /** * Adds a new list to the collection * * @param title The new list's title * @param description The new list's description * @param template The list template value * @param enableContentTypes If true content types will be allowed and enabled, otherwise they will be disallowed and not enabled * @param additionalSettings Will be passed as part of the list creation body */ Lists.prototype.add = function (title, description, template, enableContentTypes, additionalSettings) { var _this = this; if (description === void 0) { description = ""; } if (template === void 0) { template = 100; } if (enableContentTypes === void 0) { enableContentTypes = false; } if (additionalSettings === void 0) { additionalSettings = {}; } var addSettings = util_1.Util.extend({ "AllowContentTypes": enableContentTypes, "BaseTemplate": template, "ContentTypesEnabled": enableContentTypes, "Description": description, "Title": title, "__metadata": { "type": "SP.List" }, }, additionalSettings); return this.post({ body: JSON.stringify(addSettings) }).then(function (data) { return { data: data, list: _this.getByTitle(addSettings.Title) }; }); }; /** * Ensures that the specified list exists in the collection (note: this method not supported for batching) * * @param title The new list's title * @param description The new list's description * @param template The list template value * @param enableContentTypes If true content types will be allowed and enabled, otherwise they will be disallowed and not enabled * @param additionalSettings Will be passed as part of the list creation body or used to update an existing list */ Lists.prototype.ensure = function (title, description, template, enableContentTypes, additionalSettings) { var _this = this; if (description === void 0) { description = ""; } if (template === void 0) { template = 100; } if (enableContentTypes === void 0) { enableContentTypes = false; } if (additionalSettings === void 0) { additionalSettings = {}; } if (this.hasBatch) { throw new exceptions_1.NotSupportedInBatchException("The ensure list method"); } return new Promise(function (resolve, reject) { var addOrUpdateSettings = util_1.Util.extend(additionalSettings, { Title: title, Description: description, ContentTypesEnabled: enableContentTypes }, true); var list = _this.getByTitle(addOrUpdateSettings.Title); list.get().then(function (_) { list.update(addOrUpdateSettings).then(function (d) { resolve({ created: false, data: d, list: _this.getByTitle(addOrUpdateSettings.Title) }); }).catch(function (e) { return reject(e); }); }).catch(function (_) { _this.add(title, description, template, enableContentTypes, addOrUpdateSettings).then(function (r) { resolve({ created: true, data: r.data, list: _this.getByTitle(addOrUpdateSettings.Title) }); }).catch(function (e) { return reject(e); }); }); }); }; /** * Gets a list that is the default asset location for images or other files, which the users upload to their wiki pages. */ Lists.prototype.ensureSiteAssetsLibrary = function () { return this.clone(Lists, "ensuresiteassetslibrary", true).post().then(function (json) { return new List(odata_1.extractOdataId(json)); }); }; /** * Gets a list that is the default location for wiki pages. */ Lists.prototype.ensureSitePagesLibrary = function () { return this.clone(Lists, "ensuresitepageslibrary", true).post().then(function (json) { return new List(odata_1.extractOdataId(json)); }); }; return Lists; }(queryable_1.QueryableCollection)); exports.Lists = Lists; /** * Describes a single List instance * */ var List = (function (_super) { __extends(List, _super); function List() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(List.prototype, "contentTypes", { /** * Gets the content types in this list * */ get: function () { return new contenttypes_1.ContentTypes(this); }, enumerable: true, configurable: true }); Object.defineProperty(List.prototype, "items", { /** * Gets the items in this list * */ get: function () { return new items_1.Items(this); }, enumerable: true, configurable: true }); Object.defineProperty(List.prototype, "views", { /** * Gets the views in this list * */ get: function () { return new views_1.Views(this); }, enumerable: true, configurable: true }); Object.defineProperty(List.prototype, "fields", { /** * Gets the fields in this list * */ get: function () { return new fields_1.Fields(this); }, enumerable: true, configurable: true }); Object.defineProperty(List.prototype, "forms", { /** * Gets the forms in this list * */ get: function () { return new forms_1.Forms(this); }, enumerable: true, configurable: true }); Object.defineProperty(List.prototype, "defaultView", { /** * Gets the default view of this list * */ get: function () { return new queryable_1.QueryableInstance(this, "DefaultView"); }, enumerable: true, configurable: true }); Object.defineProperty(List.prototype, "userCustomActions", { /** * Get all custom actions on a site collection * */ get: function () { return new usercustomactions_1.UserCustomActions(this); }, enumerable: true, configurable: true }); Object.defineProperty(List.prototype, "effectiveBasePermissions", { /** * Gets the effective base permissions of this list * */ get: function () { return new queryable_1.Queryable(this, "EffectiveBasePermissions"); }, enumerable: true, configurable: true }); Object.defineProperty(List.prototype, "eventReceivers", { /** * Gets the event receivers attached to this list * */ get: function () { return new queryable_1.QueryableCollection(this, "EventReceivers"); }, enumerable: true, configurable: true }); Object.defineProperty(List.prototype, "relatedFields", { /** * Gets the related fields of this list * */ get: function () { return new queryable_1.Queryable(this, "getRelatedFields"); }, enumerable: true, configurable: true }); Object.defineProperty(List.prototype, "informationRightsManagementSettings", { /** * Gets the IRM settings for this list * */ get: function () { return new queryable_1.Queryable(this, "InformationRightsManagementSettings"); }, enumerable: true, configurable: true }); Object.defineProperty(List.prototype, "subscriptions", { /** * Gets the webhook subscriptions of this list * */ get: function () { return new subscriptions_1.Subscriptions(this); }, enumerable: true, configurable: true }); Object.defineProperty(List.prototype, "rootFolder", { /** * The root folder of the list */ get: function () { return new folders_1.Folder(this, "rootFolder"); }, enumerable: true, configurable: true }); /** * Gets a view by view guid id * */ List.prototype.getView = function (viewId) { return new views_1.View(this, "getView('" + viewId + "')"); }; /** * Updates this list intance with the supplied properties * * @param properties A plain object hash of values to update for the list * @param eTag Value used in the IF-Match header, by default "*" */ /* tslint:disable no-string-literal */ List.prototype.update = function (properties, eTag) { var _this = this; if (eTag === void 0) { eTag = "*"; } var postBody = JSON.stringify(util_1.Util.extend({ "__metadata": { "type": "SP.List" }, }, properties)); return this.post({ body: postBody, headers: { "IF-Match": eTag, "X-HTTP-Method": "MERGE", }, }).then(function (data) { var retList = _this; if (properties.hasOwnProperty("Title")) { retList = _this.getParent(List, _this.parentUrl, "getByTitle('" + properties["Title"] + "')"); } return { data: data, list: retList, }; }); }; /* tslint:enable */ /** * Delete this list * * @param eTag Value used in the IF-Match header, by default "*" */ List.prototype.delete = function (eTag) { if (eTag === void 0) { eTag = "*"; } return this.post({ headers: { "IF-Match": eTag, "X-HTTP-Method": "DELETE", }, }); }; /** * Returns the collection of changes from the change log that have occurred within the list, based on the specified query. */ List.prototype.getChanges = function (query) { return this.clone(List, "getchanges", true).post({ body: JSON.stringify({ "query": util_1.Util.extend({ "__metadata": { "type": "SP.ChangeQuery" } }, query) }), }); }; /** * Returns a collection of items from the list based on the specified query. * * @param CamlQuery The Query schema of Collaborative Application Markup * Language (CAML) is used in various ways within the context of Microsoft SharePoint Foundation * to define queries against list data. * see: * * https://msdn.microsoft.com/en-us/library/office/ms467521.aspx * * @param expands A URI with a $expand System Query Option indicates that Entries associated with * the Entry or Collection of Entries identified by the Resource Path * section of the URI must be represented inline (i.e. eagerly loaded). * see: * * https://msdn.microsoft.com/en-us/library/office/fp142385.aspx * * http://www.odata.org/documentation/odata-version-2-0/uri-conventions/#ExpandSystemQueryOption */ List.prototype.getItemsByCAMLQuery = function (query) { var expands = []; for (var _i = 1; _i < arguments.length; _i++) { expands[_i - 1] = arguments[_i]; } var q = this.clone(List, "getitems", true); return q.expand.apply(q, expands).post({ body: JSON.stringify({ "query": util_1.Util.extend({ "__metadata": { "type": "SP.CamlQuery" } }, query) }), }); }; /** * See: https://msdn.microsoft.com/en-us/library/office/dn292554.aspx */ List.prototype.getListItemChangesSinceToken = function (query) { return this.clone(List, "getlistitemchangessincetoken", true).post({ body: JSON.stringify({ "query": util_1.Util.extend({ "__metadata": { "type": "SP.ChangeLogItemQuery" } }, query) }), }, { parse: function (r) { return r.text(); } }); }; /** * Moves the list to the Recycle Bin and returns the identifier of the new Recycle Bin item. */ List.prototype.recycle = function () { return this.clone(List, "recycle", true).post().then(function (data) { if (data.hasOwnProperty("Recycle")) { return data.Recycle; } else { return data; } }); }; /** * Renders list data based on the view xml provided */ List.prototype.renderListData = function (viewXml) { var q = this.clone(List, "renderlistdata(@viewXml)"); q.query.add("@viewXml", "'" + viewXml + "'"); return q.post().then(function (data) { // data will be a string, so we parse it again data = JSON.parse(data); if (data.hasOwnProperty("RenderListData")) { return data.RenderListData; } else { return data; } }); }; /** * Gets the field values and field schema attributes for a list item. */ List.prototype.renderListFormData = function (itemId, formId, mode) { return this.clone(List, "renderlistformdata(itemid=" + itemId + ", formid='" + formId + "', mode='" + mode + "')", true).post().then(function (data) { // data will be a string, so we parse it again data = JSON.parse(data); if (data.hasOwnProperty("ListData")) { return data.ListData; } else { return data; } }); }; /** * Reserves a list item ID for idempotent list item creation. */ List.prototype.reserveListItemId = function () { return this.clone(List, "reservelistitemid", true).post().then(function (data) { if (data.hasOwnProperty("ReserveListItemId")) { return data.ReserveListItemId; } else { return data; } }); }; /** * Returns the ListItemEntityTypeFullName for this list, used when adding/updating list items. Does not support batching. * */ List.prototype.getListItemEntityTypeFullName = function () { return this.clone(List, null).select("ListItemEntityTypeFullName").getAs().then(function (o) { return o.ListItemEntityTypeFullName; }); }; return List; }(queryablesecurable_1.QueryableSecurable)); exports.List = List; /***/ }), /* 12 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var util_1 = __webpack_require__(0); var webs_1 = __webpack_require__(8); var odata_1 = __webpack_require__(2); var queryable_1 = __webpack_require__(1); var queryablesecurable_1 = __webpack_require__(26); var types_1 = __webpack_require__(13); /** * Internal helper class used to augment classes to include sharing functionality */ var QueryableShareable = (function (_super) { __extends(QueryableShareable, _super); function QueryableShareable() { return _super !== null && _super.apply(this, arguments) || this; } /** * Gets a sharing link for the supplied * * @param kind The kind of link to share * @param expiration The optional expiration for this link */ QueryableShareable.prototype.getShareLink = function (kind, expiration) { if (expiration === void 0) { expiration = null; } // date needs to be an ISO string or null var expString = expiration !== null ? expiration.toISOString() : null; // clone using the factory and send the request return this.clone(QueryableShareable, "shareLink", true).postAs({ body: JSON.stringify({ request: { createLink: true, emailData: null, settings: { expiration: expString, linkKind: kind, }, }, }), }); }; /** * Shares this instance with the supplied users * * @param loginNames Resolved login names to share * @param role The role * @param requireSignin True to require the user is authenticated, otherwise false * @param propagateAcl True to apply this share to all children * @param emailData If supplied an email will be sent with the indicated properties */ QueryableShareable.prototype.shareWith = function (loginNames, role, requireSignin, propagateAcl, emailData) { var _this = this; if (requireSignin === void 0) { requireSignin = true; } if (propagateAcl === void 0) { propagateAcl = false; } // handle the multiple input types if (!Array.isArray(loginNames)) { loginNames = [loginNames]; } var userStr = JSON.stringify(loginNames.map(function (login) { return { Key: login }; })); var roleFilter = role === types_1.SharingRole.Edit ? types_1.RoleType.Contributor : types_1.RoleType.Reader; // start by looking up the role definition id we need to set the roleValue return webs_1.Web.fromUrl(this.toUrl()).roleDefinitions.select("Id").filter("RoleTypeKind eq " + roleFilter).get().then(function (def) { if (!Array.isArray(def) || def.length < 1) { throw new Error("Could not locate a role defintion with RoleTypeKind " + roleFilter); } var postBody = { includeAnonymousLinkInEmail: requireSignin, peoplePickerInput: userStr, propagateAcl: propagateAcl, roleValue: "role:" + def[0].Id, useSimplifiedRoles: true, }; if (typeof emailData !== "undefined") { postBody = util_1.Util.extend(postBody, { emailBody: emailData.body, emailSubject: typeof emailData.subject !== "undefined" ? emailData.subject : "", sendEmail: true, }); } return _this.clone(QueryableShareable, "shareObject", true).postAs({ body: JSON.stringify(postBody), }); }); }; /** * Shares an object based on the supplied options * * @param options The set of options to send to the ShareObject method * @param bypass If true any processing is skipped and the options are sent directly to the ShareObject method */ QueryableShareable.prototype.shareObject = function (options, bypass) { var _this = this; if (bypass === void 0) { bypass = false; } if (bypass) { // if the bypass flag is set send the supplied parameters directly to the service return this.sendShareObjectRequest(options); } // extend our options with some defaults options = util_1.Util.extend(options, { group: null, includeAnonymousLinkInEmail: false, propagateAcl: false, useSimplifiedRoles: true, }, true); return this.getRoleValue(options.role, options.group).then(function (roleValue) { // handle the multiple input types if (!Array.isArray(options.loginNames)) { options.loginNames = [options.loginNames]; } var userStr = JSON.stringify(options.loginNames.map(function (login) { return { Key: login }; })); var postBody = { peoplePickerInput: userStr, roleValue: roleValue, url: options.url, }; if (typeof options.emailData !== "undefined" && options.emailData !== null) { postBody = util_1.Util.extend(postBody, { emailBody: options.emailData.body, emailSubject: typeof options.emailData.subject !== "undefined" ? options.emailData.subject : "Shared with you.", sendEmail: true, }); } return _this.sendShareObjectRequest(postBody); }); }; /** * Calls the web's UnshareObject method * * @param url The url of the object to unshare */ QueryableShareable.prototype.unshareObjectWeb = function (url) { return this.clone(QueryableShareable, "unshareObject", true).postAs({ body: JSON.stringify({ url: url, }), }); }; /** * Checks Permissions on the list of Users and returns back role the users have on the Item. * * @param recipients The array of Entities for which Permissions need to be checked. */ QueryableShareable.prototype.checkPermissions = function (recipients) { return this.clone(QueryableShareable, "checkPermissions", true).postAs({ body: JSON.stringify({ recipients: recipients, }), }); }; /** * Get Sharing Information. * * @param request The SharingInformationRequest Object. */ QueryableShareable.prototype.getSharingInformation = function (request) { if (request === void 0) { request = null; } return this.clone(QueryableShareable, "getSharingInformation", true).postAs({ body: JSON.stringify({ request: request, }), }); }; /** * Gets the sharing settings of an item. * * @param useSimplifiedRoles Determines whether to use simplified roles. */ QueryableShareable.prototype.getObjectSharingSettings = function (useSimplifiedRoles) { if (useSimplifiedRoles === void 0) { useSimplifiedRoles = true; } return this.clone(QueryableShareable, "getObjectSharingSettings", true).postAs({ body: JSON.stringify({ useSimplifiedRoles: useSimplifiedRoles, }), }); }; /** * Unshares this object */ QueryableShareable.prototype.unshareObject = function () { return this.clone(QueryableShareable, "unshareObject", true).postAs(); }; /** * Deletes a link by type * * @param kind Deletes a sharing link by the kind of link */ QueryableShareable.prototype.deleteLinkByKind = function (kind) { return this.clone(QueryableShareable, "deleteLinkByKind", true).post({ body: JSON.stringify({ linkKind: kind }), }); }; /** * Removes the specified link to the item. * * @param kind The kind of link to be deleted. * @param shareId */ QueryableShareable.prototype.unshareLink = function (kind, shareId) { if (shareId === void 0) { shareId = "00000000-0000-0000-0000-000000000000"; } return this.clone(QueryableShareable, "unshareLink", true).post({ body: JSON.stringify({ linkKind: kind, shareId: shareId }), }); }; /** * Calculates the roleValue string used in the sharing query * * @param role The Sharing Role * @param group The Group type */ QueryableShareable.prototype.getRoleValue = function (role, group) { // we will give group precedence, because we had to make a choice if (typeof group !== "undefined" && group !== null) { switch (group) { case types_1.RoleType.Contributor: return webs_1.Web.fromUrl(this.toUrl()).associatedMemberGroup.select("Id").getAs().then(function (g) { return "group: " + g.Id; }); case types_1.RoleType.Reader: case types_1.RoleType.Guest: return webs_1.Web.fromUrl(this.toUrl()).associatedVisitorGroup.select("Id").getAs().then(function (g) { return "group: " + g.Id; }); default: throw new Error("Could not determine role value for supplied value. Contributor, Reader, and Guest are supported"); } } else { var roleFilter = role === types_1.SharingRole.Edit ? types_1.RoleType.Contributor : types_1.RoleType.Reader; return webs_1.Web.fromUrl(this.toUrl()).roleDefinitions.select("Id").top(1).filter("RoleTypeKind eq " + roleFilter).getAs().then(function (def) { if (def.length < 1) { throw new Error("Could not locate associated role definition for supplied role. Edit and View are supported"); } return "role: " + def[0].Id; }); } }; QueryableShareable.prototype.getShareObjectWeb = function (candidate) { return Promise.resolve(webs_1.Web.fromUrl(candidate, "/_api/SP.Web.ShareObject")); }; QueryableShareable.prototype.sendShareObjectRequest = function (options) { return this.getShareObjectWeb(this.toUrl()).then(function (web) { return web.expand("UsersWithAccessRequests", "GroupsSharedWith").as(QueryableShareable).post({ body: JSON.stringify(options), }); }); }; return QueryableShareable; }(queryable_1.Queryable)); exports.QueryableShareable = QueryableShareable; var QueryableShareableWeb = (function (_super) { __extends(QueryableShareableWeb, _super); function QueryableShareableWeb() { return _super !== null && _super.apply(this, arguments) || this; } /** * Shares this web with the supplied users * @param loginNames The resolved login names to share * @param role The role to share this web * @param emailData Optional email data */ QueryableShareableWeb.prototype.shareWith = function (loginNames, role, emailData) { var _this = this; if (role === void 0) { role = types_1.SharingRole.View; } var dependency = this.addBatchDependency(); return webs_1.Web.fromUrl(this.toUrl(), "/_api/web/url").get().then(function (url) { dependency(); return _this.shareObject(util_1.Util.combinePaths(url, "/_layouts/15/aclinv.aspx?forSharing=1&mbypass=1"), loginNames, role, emailData); }); }; /** * Provides direct access to the static web.ShareObject method * * @param url The url to share * @param loginNames Resolved loginnames string[] of a single login name string * @param roleValue Role value * @param emailData Optional email data * @param groupId Optional group id * @param propagateAcl * @param includeAnonymousLinkInEmail * @param useSimplifiedRoles */ QueryableShareableWeb.prototype.shareObject = function (url, loginNames, role, emailData, group, propagateAcl, includeAnonymousLinkInEmail, useSimplifiedRoles) { if (propagateAcl === void 0) { propagateAcl = false; } if (includeAnonymousLinkInEmail === void 0) { includeAnonymousLinkInEmail = false; } if (useSimplifiedRoles === void 0) { useSimplifiedRoles = true; } return this.clone(QueryableShareable, null, true).shareObject({ emailData: emailData, group: group, includeAnonymousLinkInEmail: includeAnonymousLinkInEmail, loginNames: loginNames, propagateAcl: propagateAcl, role: role, url: url, useSimplifiedRoles: useSimplifiedRoles, }); }; /** * Supplies a method to pass any set of arguments to ShareObject * * @param options The set of options to send to ShareObject */ QueryableShareableWeb.prototype.shareObjectRaw = function (options) { return this.clone(QueryableShareable, null, true).shareObject(options, true); }; /** * Unshares the object * * @param url The url of the object to stop sharing */ QueryableShareableWeb.prototype.unshareObject = function (url) { return this.clone(QueryableShareable, null, true).unshareObjectWeb(url); }; return QueryableShareableWeb; }(queryablesecurable_1.QueryableSecurable)); exports.QueryableShareableWeb = QueryableShareableWeb; var QueryableShareableItem = (function (_super) { __extends(QueryableShareableItem, _super); function QueryableShareableItem() { return _super !== null && _super.apply(this, arguments) || this; } /** * Gets a link suitable for sharing for this item * * @param kind The type of link to share * @param expiration The optional expiration date */ QueryableShareableItem.prototype.getShareLink = function (kind, expiration) { if (kind === void 0) { kind = types_1.SharingLinkKind.OrganizationView; } if (expiration === void 0) { expiration = null; } return this.clone(QueryableShareable, null, true).getShareLink(kind, expiration); }; /** * Shares this item with one or more users * * @param loginNames string or string[] of resolved login names to which this item will be shared * @param role The role (View | Edit) applied to the share * @param emailData Optional, if inlucded an email will be sent. Note subject currently has no effect. */ QueryableShareableItem.prototype.shareWith = function (loginNames, role, requireSignin, emailData) { if (role === void 0) { role = types_1.SharingRole.View; } if (requireSignin === void 0) { requireSignin = true; } return this.clone(QueryableShareable, null, true).shareWith(loginNames, role, requireSignin, false, emailData); }; /** * Checks Permissions on the list of Users and returns back role the users have on the Item. * * @param recipients The array of Entities for which Permissions need to be checked. */ QueryableShareableItem.prototype.checkSharingPermissions = function (recipients) { return this.clone(QueryableShareable, null, true).checkPermissions(recipients); }; /** * Get Sharing Information. * * @param request The SharingInformationRequest Object. */ QueryableShareableItem.prototype.getSharingInformation = function (request) { if (request === void 0) { request = null; } return this.clone(QueryableShareable, null, true).getSharingInformation(request); }; /** * Gets the sharing settings of an item. * * @param useSimplifiedRoles Determines whether to use simplified roles. */ QueryableShareableItem.prototype.getObjectSharingSettings = function (useSimplifiedRoles) { if (useSimplifiedRoles === void 0) { useSimplifiedRoles = true; } return this.clone(QueryableShareable, null, true).getObjectSharingSettings(useSimplifiedRoles); }; /** * Unshare this item */ QueryableShareableItem.prototype.unshare = function () { return this.clone(QueryableShareable, null, true).unshareObject(); }; /** * Deletes a sharing link by kind * * @param kind Deletes a sharing link by the kind of link */ QueryableShareableItem.prototype.deleteSharingLinkByKind = function (kind) { return this.clone(QueryableShareable, null, true).deleteLinkByKind(kind); }; /** * Removes the specified link to the item. * * @param kind The kind of link to be deleted. * @param shareId */ QueryableShareableItem.prototype.unshareLink = function (kind, shareId) { return this.clone(QueryableShareable, null, true).unshareLink(kind, shareId); }; return QueryableShareableItem; }(queryablesecurable_1.QueryableSecurable)); exports.QueryableShareableItem = QueryableShareableItem; var FileFolderShared = (function (_super) { __extends(FileFolderShared, _super); function FileFolderShared() { return _super !== null && _super.apply(this, arguments) || this; } /** * Gets a link suitable for sharing * * @param kind The kind of link to get * @param expiration Optional, an expiration for this link */ FileFolderShared.prototype.getShareLink = function (kind, expiration) { if (kind === void 0) { kind = types_1.SharingLinkKind.OrganizationView; } if (expiration === void 0) { expiration = null; } var dependency = this.addBatchDependency(); return this.getShareable().then(function (shareable) { dependency(); return shareable.getShareLink(kind, expiration); }); }; /** * Checks Permissions on the list of Users and returns back role the users have on the Item. * * @param recipients The array of Entities for which Permissions need to be checked. */ FileFolderShared.prototype.checkSharingPermissions = function (recipients) { var dependency = this.addBatchDependency(); return this.getShareable().then(function (shareable) { dependency(); return shareable.checkPermissions(recipients); }); }; /** * Get Sharing Information. * * @param request The SharingInformationRequest Object. */ FileFolderShared.prototype.getSharingInformation = function (request) { if (request === void 0) { request = null; } var dependency = this.addBatchDependency(); return this.getShareable().then(function (shareable) { dependency(); return shareable.getSharingInformation(request); }); }; /** * Gets the sharing settings of an item. * * @param useSimplifiedRoles Determines whether to use simplified roles. */ FileFolderShared.prototype.getObjectSharingSettings = function (useSimplifiedRoles) { if (useSimplifiedRoles === void 0) { useSimplifiedRoles = true; } var dependency = this.addBatchDependency(); return this.getShareable().then(function (shareable) { dependency(); return shareable.getObjectSharingSettings(useSimplifiedRoles); }); }; /** * Unshare this item */ FileFolderShared.prototype.unshare = function () { var dependency = this.addBatchDependency(); return this.getShareable().then(function (shareable) { dependency(); return shareable.unshareObject(); }); }; /** * Deletes a sharing link by the kind of link * * @param kind The kind of link to be deleted. */ FileFolderShared.prototype.deleteSharingLinkByKind = function (kind) { var dependency = this.addBatchDependency(); return this.getShareable().then(function (shareable) { dependency(); return shareable.deleteLinkByKind(kind); }); }; /** * Removes the specified link to the item. * * @param kind The kind of link to be deleted. * @param shareId The share id to delete */ FileFolderShared.prototype.unshareLink = function (kind, shareId) { var dependency = this.addBatchDependency(); return this.getShareable().then(function (shareable) { dependency(); return shareable.unshareLink(kind, shareId); }); }; /** * For files and folders we need to use the associated item end point */ FileFolderShared.prototype.getShareable = function () { var _this = this; // sharing only works on the item end point, not the file one - so we create a folder instance with the item url internally return this.clone(QueryableShareableFile, "listItemAllFields", false).select("odata.editlink").get().then(function (d) { var shareable = new QueryableShareable(odata_1.getEntityUrl(d)); // we need to handle batching if (_this.hasBatch) { shareable = shareable.inBatch(_this.batch); } return shareable; }); }; return FileFolderShared; }(queryable_1.QueryableInstance)); exports.FileFolderShared = FileFolderShared; var QueryableShareableFile = (function (_super) { __extends(QueryableShareableFile, _super); function QueryableShareableFile() { return _super !== null && _super.apply(this, arguments) || this; } /** * Shares this item with one or more users * * @param loginNames string or string[] of resolved login names to which this item will be shared * @param role The role (View | Edit) applied to the share * @param shareEverything Share everything in this folder, even items with unique permissions. * @param requireSignin If true the user must signin to view link, otherwise anyone with the link can access the resource * @param emailData Optional, if inlucded an email will be sent. Note subject currently has no effect. */ QueryableShareableFile.prototype.shareWith = function (loginNames, role, requireSignin, emailData) { if (role === void 0) { role = types_1.SharingRole.View; } if (requireSignin === void 0) { requireSignin = true; } var dependency = this.addBatchDependency(); return this.getShareable().then(function (shareable) { dependency(); return shareable.shareWith(loginNames, role, requireSignin, false, emailData); }); }; return QueryableShareableFile; }(FileFolderShared)); exports.QueryableShareableFile = QueryableShareableFile; var QueryableShareableFolder = (function (_super) { __extends(QueryableShareableFolder, _super); function QueryableShareableFolder() { return _super !== null && _super.apply(this, arguments) || this; } /** * Shares this item with one or more users * * @param loginNames string or string[] of resolved login names to which this item will be shared * @param role The role (View | Edit) applied to the share * @param shareEverything Share everything in this folder, even items with unique permissions. * @param requireSignin If true the user must signin to view link, otherwise anyone with the link can access the resource * @param emailData Optional, if inlucded an email will be sent. Note subject currently has no effect. */ QueryableShareableFolder.prototype.shareWith = function (loginNames, role, requireSignin, shareEverything, emailData) { if (role === void 0) { role = types_1.SharingRole.View; } if (requireSignin === void 0) { requireSignin = true; } if (shareEverything === void 0) { shareEverything = false; } var dependency = this.addBatchDependency(); return this.getShareable().then(function (shareable) { dependency(); return shareable.shareWith(loginNames, role, requireSignin, shareEverything, emailData); }); }; return QueryableShareableFolder; }(FileFolderShared)); exports.QueryableShareableFolder = QueryableShareableFolder; /***/ }), /* 13 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // reference: https://msdn.microsoft.com/en-us/library/office/dn600183.aspx Object.defineProperty(exports, "__esModule", { value: true }); /** * Determines the display mode of the given control or view */ var ControlMode; (function (ControlMode) { ControlMode[ControlMode["Display"] = 1] = "Display"; ControlMode[ControlMode["Edit"] = 2] = "Edit"; ControlMode[ControlMode["New"] = 3] = "New"; })(ControlMode = exports.ControlMode || (exports.ControlMode = {})); /** * Specifies the type of the field. */ var FieldTypes; (function (FieldTypes) { FieldTypes[FieldTypes["Invalid"] = 0] = "Invalid"; FieldTypes[FieldTypes["Integer"] = 1] = "Integer"; FieldTypes[FieldTypes["Text"] = 2] = "Text"; FieldTypes[FieldTypes["Note"] = 3] = "Note"; FieldTypes[FieldTypes["DateTime"] = 4] = "DateTime"; FieldTypes[FieldTypes["Counter"] = 5] = "Counter"; FieldTypes[FieldTypes["Choice"] = 6] = "Choice"; FieldTypes[FieldTypes["Lookup"] = 7] = "Lookup"; FieldTypes[FieldTypes["Boolean"] = 8] = "Boolean"; FieldTypes[FieldTypes["Number"] = 9] = "Number"; FieldTypes[FieldTypes["Currency"] = 10] = "Currency"; FieldTypes[FieldTypes["URL"] = 11] = "URL"; FieldTypes[FieldTypes["Computed"] = 12] = "Computed"; FieldTypes[FieldTypes["Threading"] = 13] = "Threading"; FieldTypes[FieldTypes["Guid"] = 14] = "Guid"; FieldTypes[FieldTypes["MultiChoice"] = 15] = "MultiChoice"; FieldTypes[FieldTypes["GridChoice"] = 16] = "GridChoice"; FieldTypes[FieldTypes["Calculated"] = 17] = "Calculated"; FieldTypes[FieldTypes["File"] = 18] = "File"; FieldTypes[FieldTypes["Attachments"] = 19] = "Attachments"; FieldTypes[FieldTypes["User"] = 20] = "User"; FieldTypes[FieldTypes["Recurrence"] = 21] = "Recurrence"; FieldTypes[FieldTypes["CrossProjectLink"] = 22] = "CrossProjectLink"; FieldTypes[FieldTypes["ModStat"] = 23] = "ModStat"; FieldTypes[FieldTypes["Error"] = 24] = "Error"; FieldTypes[FieldTypes["ContentTypeId"] = 25] = "ContentTypeId"; FieldTypes[FieldTypes["PageSeparator"] = 26] = "PageSeparator"; FieldTypes[FieldTypes["ThreadIndex"] = 27] = "ThreadIndex"; FieldTypes[FieldTypes["WorkflowStatus"] = 28] = "WorkflowStatus"; FieldTypes[FieldTypes["AllDayEvent"] = 29] = "AllDayEvent"; FieldTypes[FieldTypes["WorkflowEventType"] = 30] = "WorkflowEventType"; })(FieldTypes = exports.FieldTypes || (exports.FieldTypes = {})); var DateTimeFieldFormatType; (function (DateTimeFieldFormatType) { DateTimeFieldFormatType[DateTimeFieldFormatType["DateOnly"] = 0] = "DateOnly"; DateTimeFieldFormatType[DateTimeFieldFormatType["DateTime"] = 1] = "DateTime"; })(DateTimeFieldFormatType = exports.DateTimeFieldFormatType || (exports.DateTimeFieldFormatType = {})); /** * Specifies the control settings while adding a field. */ var AddFieldOptions; (function (AddFieldOptions) { /** * Specify that a new field added to the list must also be added to the default content type in the site collection */ AddFieldOptions[AddFieldOptions["DefaultValue"] = 0] = "DefaultValue"; /** * Specify that a new field added to the list must also be added to the default content type in the site collection. */ AddFieldOptions[AddFieldOptions["AddToDefaultContentType"] = 1] = "AddToDefaultContentType"; /** * Specify that a new field must not be added to any other content type */ AddFieldOptions[AddFieldOptions["AddToNoContentType"] = 2] = "AddToNoContentType"; /** * Specify that a new field that is added to the specified list must also be added to all content types in the site collection */ AddFieldOptions[AddFieldOptions["AddToAllContentTypes"] = 4] = "AddToAllContentTypes"; /** * Specify adding an internal field name hint for the purpose of avoiding possible database locking or field renaming operations */ AddFieldOptions[AddFieldOptions["AddFieldInternalNameHint"] = 8] = "AddFieldInternalNameHint"; /** * Specify that a new field that is added to the specified list must also be added to the default list view */ AddFieldOptions[AddFieldOptions["AddFieldToDefaultView"] = 16] = "AddFieldToDefaultView"; /** * Specify to confirm that no other field has the same display name */ AddFieldOptions[AddFieldOptions["AddFieldCheckDisplayName"] = 32] = "AddFieldCheckDisplayName"; })(AddFieldOptions = exports.AddFieldOptions || (exports.AddFieldOptions = {})); var CalendarType; (function (CalendarType) { CalendarType[CalendarType["Gregorian"] = 1] = "Gregorian"; CalendarType[CalendarType["Japan"] = 3] = "Japan"; CalendarType[CalendarType["Taiwan"] = 4] = "Taiwan"; CalendarType[CalendarType["Korea"] = 5] = "Korea"; CalendarType[CalendarType["Hijri"] = 6] = "Hijri"; CalendarType[CalendarType["Thai"] = 7] = "Thai"; CalendarType[CalendarType["Hebrew"] = 8] = "Hebrew"; CalendarType[CalendarType["GregorianMEFrench"] = 9] = "GregorianMEFrench"; CalendarType[CalendarType["GregorianArabic"] = 10] = "GregorianArabic"; CalendarType[CalendarType["GregorianXLITEnglish"] = 11] = "GregorianXLITEnglish"; CalendarType[CalendarType["GregorianXLITFrench"] = 12] = "GregorianXLITFrench"; CalendarType[CalendarType["KoreaJapanLunar"] = 14] = "KoreaJapanLunar"; CalendarType[CalendarType["ChineseLunar"] = 15] = "ChineseLunar"; CalendarType[CalendarType["SakaEra"] = 16] = "SakaEra"; CalendarType[CalendarType["UmAlQura"] = 23] = "UmAlQura"; })(CalendarType = exports.CalendarType || (exports.CalendarType = {})); var UrlFieldFormatType; (function (UrlFieldFormatType) { UrlFieldFormatType[UrlFieldFormatType["Hyperlink"] = 0] = "Hyperlink"; UrlFieldFormatType[UrlFieldFormatType["Image"] = 1] = "Image"; })(UrlFieldFormatType = exports.UrlFieldFormatType || (exports.UrlFieldFormatType = {})); var PermissionKind; (function (PermissionKind) { /** * Has no permissions on the Site. Not available through the user interface. */ PermissionKind[PermissionKind["EmptyMask"] = 0] = "EmptyMask"; /** * View items in lists, documents in document libraries, and Web discussion comments. */ PermissionKind[PermissionKind["ViewListItems"] = 1] = "ViewListItems"; /** * Add items to lists, documents to document libraries, and Web discussion comments. */ PermissionKind[PermissionKind["AddListItems"] = 2] = "AddListItems"; /** * Edit items in lists, edit documents in document libraries, edit Web discussion comments * in documents, and customize Web Part Pages in document libraries. */ PermissionKind[PermissionKind["EditListItems"] = 3] = "EditListItems"; /** * Delete items from a list, documents from a document library, and Web discussion * comments in documents. */ PermissionKind[PermissionKind["DeleteListItems"] = 4] = "DeleteListItems"; /** * Approve a minor version of a list item or document. */ PermissionKind[PermissionKind["ApproveItems"] = 5] = "ApproveItems"; /** * View the source of documents with server-side file handlers. */ PermissionKind[PermissionKind["OpenItems"] = 6] = "OpenItems"; /** * View past versions of a list item or document. */ PermissionKind[PermissionKind["ViewVersions"] = 7] = "ViewVersions"; /** * Delete past versions of a list item or document. */ PermissionKind[PermissionKind["DeleteVersions"] = 8] = "DeleteVersions"; /** * Discard or check in a document which is checked out to another user. */ PermissionKind[PermissionKind["CancelCheckout"] = 9] = "CancelCheckout"; /** * Create, change, and delete personal views of lists. */ PermissionKind[PermissionKind["ManagePersonalViews"] = 10] = "ManagePersonalViews"; /** * Create and delete lists, add or remove columns in a list, and add or remove public views of a list. */ PermissionKind[PermissionKind["ManageLists"] = 12] = "ManageLists"; /** * View forms, views, and application pages, and enumerate lists. */ PermissionKind[PermissionKind["ViewFormPages"] = 13] = "ViewFormPages"; /** * Make content of a list or document library retrieveable for anonymous users through SharePoint search. * The list permissions in the site do not change. */ PermissionKind[PermissionKind["AnonymousSearchAccessList"] = 14] = "AnonymousSearchAccessList"; /** * Allow users to open a Site, list, or folder to access items inside that container. */ PermissionKind[PermissionKind["Open"] = 17] = "Open"; /** * View pages in a Site. */ PermissionKind[PermissionKind["ViewPages"] = 18] = "ViewPages"; /** * Add, change, or delete HTML pages or Web Part Pages, and edit the Site using * a Windows SharePoint Services compatible editor. */ PermissionKind[PermissionKind["AddAndCustomizePages"] = 19] = "AddAndCustomizePages"; /** * Apply a theme or borders to the entire Site. */ PermissionKind[PermissionKind["ApplyThemeAndBorder"] = 20] = "ApplyThemeAndBorder"; /** * Apply a style sheet (.css file) to the Site. */ PermissionKind[PermissionKind["ApplyStyleSheets"] = 21] = "ApplyStyleSheets"; /** * View reports on Site usage. */ PermissionKind[PermissionKind["ViewUsageData"] = 22] = "ViewUsageData"; /** * Create a Site using Self-Service Site Creation. */ PermissionKind[PermissionKind["CreateSSCSite"] = 23] = "CreateSSCSite"; /** * Create subsites such as team sites, Meeting Workspace sites, and Document Workspace sites. */ PermissionKind[PermissionKind["ManageSubwebs"] = 24] = "ManageSubwebs"; /** * Create a group of users that can be used anywhere within the site collection. */ PermissionKind[PermissionKind["CreateGroups"] = 25] = "CreateGroups"; /** * Create and change permission levels on the Site and assign permissions to users * and groups. */ PermissionKind[PermissionKind["ManagePermissions"] = 26] = "ManagePermissions"; /** * Enumerate files and folders in a Site using Microsoft Office SharePoint Designer * and WebDAV interfaces. */ PermissionKind[PermissionKind["BrowseDirectories"] = 27] = "BrowseDirectories"; /** * View information about users of the Site. */ PermissionKind[PermissionKind["BrowseUserInfo"] = 28] = "BrowseUserInfo"; /** * Add or remove personal Web Parts on a Web Part Page. */ PermissionKind[PermissionKind["AddDelPrivateWebParts"] = 29] = "AddDelPrivateWebParts"; /** * Update Web Parts to display personalized information. */ PermissionKind[PermissionKind["UpdatePersonalWebParts"] = 30] = "UpdatePersonalWebParts"; /** * Grant the ability to perform all administration tasks for the Site as well as * manage content, activate, deactivate, or edit properties of Site scoped Features * through the object model or through the user interface (UI). When granted on the * root Site of a Site Collection, activate, deactivate, or edit properties of * site collection scoped Features through the object model. To browse to the Site * Collection Features page and activate or deactivate Site Collection scoped Features * through the UI, you must be a Site Collection administrator. */ PermissionKind[PermissionKind["ManageWeb"] = 31] = "ManageWeb"; /** * Content of lists and document libraries in the Web site will be retrieveable for anonymous users through * SharePoint search if the list or document library has AnonymousSearchAccessList set. */ PermissionKind[PermissionKind["AnonymousSearchAccessWebLists"] = 32] = "AnonymousSearchAccessWebLists"; /** * Use features that launch client applications. Otherwise, users must work on documents * locally and upload changes. */ PermissionKind[PermissionKind["UseClientIntegration"] = 37] = "UseClientIntegration"; /** * Use SOAP, WebDAV, or Microsoft Office SharePoint Designer interfaces to access the Site. */ PermissionKind[PermissionKind["UseRemoteAPIs"] = 38] = "UseRemoteAPIs"; /** * Manage alerts for all users of the Site. */ PermissionKind[PermissionKind["ManageAlerts"] = 39] = "ManageAlerts"; /** * Create e-mail alerts. */ PermissionKind[PermissionKind["CreateAlerts"] = 40] = "CreateAlerts"; /** * Allows a user to change his or her user information, such as adding a picture. */ PermissionKind[PermissionKind["EditMyUserInfo"] = 41] = "EditMyUserInfo"; /** * Enumerate permissions on Site, list, folder, document, or list item. */ PermissionKind[PermissionKind["EnumeratePermissions"] = 63] = "EnumeratePermissions"; /** * Has all permissions on the Site. Not available through the user interface. */ PermissionKind[PermissionKind["FullMask"] = 65] = "FullMask"; })(PermissionKind = exports.PermissionKind || (exports.PermissionKind = {})); var PrincipalType; (function (PrincipalType) { PrincipalType[PrincipalType["None"] = 0] = "None"; PrincipalType[PrincipalType["User"] = 1] = "User"; PrincipalType[PrincipalType["DistributionList"] = 2] = "DistributionList"; PrincipalType[PrincipalType["SecurityGroup"] = 4] = "SecurityGroup"; PrincipalType[PrincipalType["SharePointGroup"] = 8] = "SharePointGroup"; PrincipalType[PrincipalType["All"] = 15] = "All"; })(PrincipalType = exports.PrincipalType || (exports.PrincipalType = {})); var PrincipalSource; (function (PrincipalSource) { PrincipalSource[PrincipalSource["None"] = 0] = "None"; PrincipalSource[PrincipalSource["UserInfoList"] = 1] = "UserInfoList"; PrincipalSource[PrincipalSource["Windows"] = 2] = "Windows"; PrincipalSource[PrincipalSource["MembershipProvider"] = 4] = "MembershipProvider"; PrincipalSource[PrincipalSource["RoleProvider"] = 8] = "RoleProvider"; PrincipalSource[PrincipalSource["All"] = 15] = "All"; })(PrincipalSource = exports.PrincipalSource || (exports.PrincipalSource = {})); var RoleType; (function (RoleType) { RoleType[RoleType["None"] = 0] = "None"; RoleType[RoleType["Guest"] = 1] = "Guest"; RoleType[RoleType["Reader"] = 2] = "Reader"; RoleType[RoleType["Contributor"] = 3] = "Contributor"; RoleType[RoleType["WebDesigner"] = 4] = "WebDesigner"; RoleType[RoleType["Administrator"] = 5] = "Administrator"; })(RoleType = exports.RoleType || (exports.RoleType = {})); var PageType; (function (PageType) { PageType[PageType["Invalid"] = -1] = "Invalid"; PageType[PageType["DefaultView"] = 0] = "DefaultView"; PageType[PageType["NormalView"] = 1] = "NormalView"; PageType[PageType["DialogView"] = 2] = "DialogView"; PageType[PageType["View"] = 3] = "View"; PageType[PageType["DisplayForm"] = 4] = "DisplayForm"; PageType[PageType["DisplayFormDialog"] = 5] = "DisplayFormDialog"; PageType[PageType["EditForm"] = 6] = "EditForm"; PageType[PageType["EditFormDialog"] = 7] = "EditFormDialog"; PageType[PageType["NewForm"] = 8] = "NewForm"; PageType[PageType["NewFormDialog"] = 9] = "NewFormDialog"; PageType[PageType["SolutionForm"] = 10] = "SolutionForm"; PageType[PageType["PAGE_MAXITEMS"] = 11] = "PAGE_MAXITEMS"; })(PageType = exports.PageType || (exports.PageType = {})); var SharingLinkKind; (function (SharingLinkKind) { /** * Uninitialized link */ SharingLinkKind[SharingLinkKind["Uninitialized"] = 0] = "Uninitialized"; /** * Direct link to the object being shared */ SharingLinkKind[SharingLinkKind["Direct"] = 1] = "Direct"; /** * Organization-shareable link to the object being shared with view permissions */ SharingLinkKind[SharingLinkKind["OrganizationView"] = 2] = "OrganizationView"; /** * Organization-shareable link to the object being shared with edit permissions */ SharingLinkKind[SharingLinkKind["OrganizationEdit"] = 3] = "OrganizationEdit"; /** * View only anonymous link */ SharingLinkKind[SharingLinkKind["AnonymousView"] = 4] = "AnonymousView"; /** * Read/Write anonymous link */ SharingLinkKind[SharingLinkKind["AnonymousEdit"] = 5] = "AnonymousEdit"; /** * Flexible sharing Link where properties can change without affecting link URL */ SharingLinkKind[SharingLinkKind["Flexible"] = 6] = "Flexible"; })(SharingLinkKind = exports.SharingLinkKind || (exports.SharingLinkKind = {})); ; /** * Indicates the role of the sharing link */ var SharingRole; (function (SharingRole) { SharingRole[SharingRole["None"] = 0] = "None"; SharingRole[SharingRole["View"] = 1] = "View"; SharingRole[SharingRole["Edit"] = 2] = "Edit"; SharingRole[SharingRole["Owner"] = 3] = "Owner"; })(SharingRole = exports.SharingRole || (exports.SharingRole = {})); var SharingOperationStatusCode; (function (SharingOperationStatusCode) { /** * The share operation completed without errors. */ SharingOperationStatusCode[SharingOperationStatusCode["CompletedSuccessfully"] = 0] = "CompletedSuccessfully"; /** * The share operation completed and generated requests for access. */ SharingOperationStatusCode[SharingOperationStatusCode["AccessRequestsQueued"] = 1] = "AccessRequestsQueued"; /** * The share operation failed as there were no resolved users. */ SharingOperationStatusCode[SharingOperationStatusCode["NoResolvedUsers"] = -1] = "NoResolvedUsers"; /** * The share operation failed due to insufficient permissions. */ SharingOperationStatusCode[SharingOperationStatusCode["AccessDenied"] = -2] = "AccessDenied"; /** * The share operation failed when attempting a cross site share, which is not supported. */ SharingOperationStatusCode[SharingOperationStatusCode["CrossSiteRequestNotSupported"] = -3] = "CrossSiteRequestNotSupported"; /** * The sharing operation failed due to an unknown error. */ SharingOperationStatusCode[SharingOperationStatusCode["UnknowError"] = -4] = "UnknowError"; /** * The text you typed is too long. Please shorten it. */ SharingOperationStatusCode[SharingOperationStatusCode["EmailBodyTooLong"] = -5] = "EmailBodyTooLong"; /** * The maximum number of unique scopes in the list has been exceeded. */ SharingOperationStatusCode[SharingOperationStatusCode["ListUniqueScopesExceeded"] = -6] = "ListUniqueScopesExceeded"; /** * The share operation failed because a sharing capability is disabled in the site. */ SharingOperationStatusCode[SharingOperationStatusCode["CapabilityDisabled"] = -7] = "CapabilityDisabled"; /** * The specified object for the share operation is not supported. */ SharingOperationStatusCode[SharingOperationStatusCode["ObjectNotSupported"] = -8] = "ObjectNotSupported"; /** * A SharePoint group cannot contain another SharePoint group. */ SharingOperationStatusCode[SharingOperationStatusCode["NestedGroupsNotSupported"] = -9] = "NestedGroupsNotSupported"; })(SharingOperationStatusCode = exports.SharingOperationStatusCode || (exports.SharingOperationStatusCode = {})); var SPSharedObjectType; (function (SPSharedObjectType) { SPSharedObjectType[SPSharedObjectType["Unknown"] = 0] = "Unknown"; SPSharedObjectType[SPSharedObjectType["File"] = 1] = "File"; SPSharedObjectType[SPSharedObjectType["Folder"] = 2] = "Folder"; SPSharedObjectType[SPSharedObjectType["Item"] = 3] = "Item"; SPSharedObjectType[SPSharedObjectType["List"] = 4] = "List"; SPSharedObjectType[SPSharedObjectType["Web"] = 5] = "Web"; SPSharedObjectType[SPSharedObjectType["Max"] = 6] = "Max"; })(SPSharedObjectType = exports.SPSharedObjectType || (exports.SPSharedObjectType = {})); var SharingDomainRestrictionMode; (function (SharingDomainRestrictionMode) { SharingDomainRestrictionMode[SharingDomainRestrictionMode["None"] = 0] = "None"; SharingDomainRestrictionMode[SharingDomainRestrictionMode["AllowList"] = 1] = "AllowList"; SharingDomainRestrictionMode[SharingDomainRestrictionMode["BlockList"] = 2] = "BlockList"; })(SharingDomainRestrictionMode = exports.SharingDomainRestrictionMode || (exports.SharingDomainRestrictionMode = {})); ; /***/ }), /* 14 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var util_1 = __webpack_require__(0); var collections_1 = __webpack_require__(6); var pnplibconfig_1 = __webpack_require__(4); /** * A wrapper class to provide a consistent interface to browser based storage * */ var PnPClientStorageWrapper = (function () { /** * Creates a new instance of the PnPClientStorageWrapper class * * @constructor */ function PnPClientStorageWrapper(store, defaultTimeoutMinutes) { this.store = store; this.defaultTimeoutMinutes = defaultTimeoutMinutes; this.defaultTimeoutMinutes = (defaultTimeoutMinutes === void 0) ? -1 : defaultTimeoutMinutes; this.enabled = this.test(); } /** * Get a value from storage, or null if that value does not exist * * @param key The key whose value we want to retrieve */ PnPClientStorageWrapper.prototype.get = function (key) { if (!this.enabled) { return null; } var o = this.store.getItem(key); if (o == null) { return null; } var persistable = JSON.parse(o); if (new Date(persistable.expiration) <= new Date()) { this.delete(key); return null; } else { return persistable.value; } }; /** * Adds a value to the underlying storage * * @param key The key to use when storing the provided value * @param o The value to store * @param expire Optional, if provided the expiration of the item, otherwise the default is used */ PnPClientStorageWrapper.prototype.put = function (key, o, expire) { if (this.enabled) { this.store.setItem(key, this.createPersistable(o, expire)); } }; /** * Deletes a value from the underlying storage * * @param key The key of the pair we want to remove from storage */ PnPClientStorageWrapper.prototype.delete = function (key) { if (this.enabled) { this.store.removeItem(key); } }; /** * Gets an item from the underlying storage, or adds it if it does not exist using the supplied getter function * * @param key The key to use when storing the provided value * @param getter A function which will upon execution provide the desired value * @param expire Optional, if provided the expiration of the item, otherwise the default is used */ PnPClientStorageWrapper.prototype.getOrPut = function (key, getter, expire) { var _this = this; if (!this.enabled) { return getter(); } return new Promise(function (resolve) { var o = _this.get(key); if (o == null) { getter().then(function (d) { _this.put(key, d, expire); resolve(d); }); } else { resolve(o); } }); }; /** * Used to determine if the wrapped storage is available currently */ PnPClientStorageWrapper.prototype.test = function () { var str = "test"; try { this.store.setItem(str, str); this.store.removeItem(str); return true; } catch (e) { return false; } }; /** * Creates the persistable to store */ PnPClientStorageWrapper.prototype.createPersistable = function (o, expire) { if (typeof expire === "undefined") { // ensure we are by default inline with the global library setting var defaultTimeout = pnplibconfig_1.RuntimeConfig.defaultCachingTimeoutSeconds; if (this.defaultTimeoutMinutes > 0) { defaultTimeout = this.defaultTimeoutMinutes * 60; } expire = util_1.Util.dateAdd(new Date(), "second", defaultTimeout); } return JSON.stringify({ expiration: expire, value: o }); }; return PnPClientStorageWrapper; }()); exports.PnPClientStorageWrapper = PnPClientStorageWrapper; /** * A thin implementation of in-memory storage for use in nodejs */ var MemoryStorage = (function () { function MemoryStorage(_store) { if (_store === void 0) { _store = new collections_1.Dictionary(); } this._store = _store; } Object.defineProperty(MemoryStorage.prototype, "length", { get: function () { return this._store.count(); }, enumerable: true, configurable: true }); MemoryStorage.prototype.clear = function () { this._store.clear(); }; MemoryStorage.prototype.getItem = function (key) { return this._store.get(key); }; MemoryStorage.prototype.key = function (index) { return this._store.getKeys()[index]; }; MemoryStorage.prototype.removeItem = function (key) { this._store.remove(key); }; MemoryStorage.prototype.setItem = function (key, data) { this._store.add(key, data); }; return MemoryStorage; }()); /** * A class that will establish wrappers for both local and session storage */ var PnPClientStorage = (function () { /** * Creates a new instance of the PnPClientStorage class * * @constructor */ function PnPClientStorage() { this.local = typeof localStorage !== "undefined" ? new PnPClientStorageWrapper(localStorage) : new PnPClientStorageWrapper(new MemoryStorage()); this.session = typeof sessionStorage !== "undefined" ? new PnPClientStorageWrapper(sessionStorage) : new PnPClientStorageWrapper(new MemoryStorage()); } return PnPClientStorage; }()); exports.PnPClientStorage = PnPClientStorage; /***/ }), /* 15 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var digestcache_1 = __webpack_require__(38); var util_1 = __webpack_require__(0); var pnplibconfig_1 = __webpack_require__(4); var exceptions_1 = __webpack_require__(3); var HttpClient = (function () { function HttpClient() { this._impl = pnplibconfig_1.RuntimeConfig.fetchClientFactory(); this._digestCache = new digestcache_1.DigestCache(this); } HttpClient.prototype.fetch = function (url, options) { var _this = this; if (options === void 0) { options = {}; } var opts = util_1.Util.extend(options, { cache: "no-cache", credentials: "same-origin" }, true); var headers = new Headers(); // first we add the global headers so they can be overwritten by any passed in locally to this call this.mergeHeaders(headers, pnplibconfig_1.RuntimeConfig.headers); // second we add the local options so we can overwrite the globals this.mergeHeaders(headers, options.headers); // lastly we apply any default headers we need that may not exist if (!headers.has("Accept")) { headers.append("Accept", "application/json"); } if (!headers.has("Content-Type")) { headers.append("Content-Type", "application/json;odata=verbose;charset=utf-8"); } if (!headers.has("X-ClientService-ClientTag")) { headers.append("X-ClientService-ClientTag", "PnPCoreJS:2.0.6-beta.1"); } opts = util_1.Util.extend(opts, { headers: headers }); if (opts.method && opts.method.toUpperCase() !== "GET") { if (!headers.has("X-RequestDigest")) { var index = url.indexOf("_api/"); if (index < 0) { throw new exceptions_1.APIUrlException(); } var webUrl = url.substr(0, index); return this._digestCache.getDigest(webUrl) .then(function (digest) { headers.append("X-RequestDigest", digest); return _this.fetchRaw(url, opts); }); } } return this.fetchRaw(url, opts); }; HttpClient.prototype.fetchRaw = function (url, options) { var _this = this; if (options === void 0) { options = {}; } // here we need to normalize the headers var rawHeaders = new Headers(); this.mergeHeaders(rawHeaders, options.headers); options = util_1.Util.extend(options, { headers: rawHeaders }); var retry = function (ctx) { _this._impl.fetch(url, options).then(function (response) { return ctx.resolve(response); }).catch(function (response) { // grab our current delay var delay = ctx.delay; // Check if request was throttled - http status code 429 // Check is request failed due to server unavailable - http status code 503 if (response.status !== 429 && response.status !== 503) { ctx.reject(response); } // Increment our counters. ctx.delay *= 2; ctx.attempts++; // If we have exceeded the retry count, reject. if (ctx.retryCount <= ctx.attempts) { ctx.reject(response); } // Set our retry timeout for {delay} milliseconds. setTimeout(util_1.Util.getCtxCallback(_this, retry, ctx), delay); }); }; return new Promise(function (resolve, reject) { var retryContext = { attempts: 0, delay: 100, reject: reject, resolve: resolve, retryCount: 7, }; retry.call(_this, retryContext); }); }; HttpClient.prototype.get = function (url, options) { if (options === void 0) { options = {}; } var opts = util_1.Util.extend(options, { method: "GET" }); return this.fetch(url, opts); }; HttpClient.prototype.post = function (url, options) { if (options === void 0) { options = {}; } var opts = util_1.Util.extend(options, { method: "POST" }); return this.fetch(url, opts); }; HttpClient.prototype.patch = function (url, options) { if (options === void 0) { options = {}; } var opts = util_1.Util.extend(options, { method: "PATCH" }); return this.fetch(url, opts); }; HttpClient.prototype.delete = function (url, options) { if (options === void 0) { options = {}; } var opts = util_1.Util.extend(options, { method: "DELETE" }); return this.fetch(url, opts); }; HttpClient.prototype.mergeHeaders = function (target, source) { if (typeof source !== "undefined" && source !== null) { var temp = new Request("", { headers: source }); temp.headers.forEach(function (value, name) { target.append(name, value); }); } }; return HttpClient; }()); exports.HttpClient = HttpClient; ; /***/ }), /* 16 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var util_1 = __webpack_require__(0); var queryable_1 = __webpack_require__(1); /** * Describes a collection of content types * */ var ContentTypes = (function (_super) { __extends(ContentTypes, _super); /** * Creates a new instance of the ContentTypes class * * @param baseUrl The url or Queryable which forms the parent of this content types collection */ function ContentTypes(baseUrl, path) { if (path === void 0) { path = "contenttypes"; } return _super.call(this, baseUrl, path) || this; } /** * Gets a ContentType by content type id */ ContentTypes.prototype.getById = function (id) { var ct = new ContentType(this); ct.concat("('" + id + "')"); return ct; }; /** * Adds an existing contenttype to a content type collection * * @param contentTypeId in the following format, for example: 0x010102 */ ContentTypes.prototype.addAvailableContentType = function (contentTypeId) { var _this = this; var postBody = JSON.stringify({ "contentTypeId": contentTypeId, }); return this.clone(ContentTypes, "addAvailableContentType", true).postAs({ body: postBody }).then(function (data) { return { contentType: _this.getById(data.id), data: data, }; }); }; /** * Adds a new content type to the collection * * @param id The desired content type id for the new content type (also determines the parent content type) * @param name The name of the content type * @param description The description of the content type * @param group The group in which to add the content type * @param additionalSettings Any additional settings to provide when creating the content type * */ ContentTypes.prototype.add = function (id, name, description, group, additionalSettings) { var _this = this; if (description === void 0) { description = ""; } if (group === void 0) { group = "Custom Content Types"; } if (additionalSettings === void 0) { additionalSettings = {}; } var postBody = JSON.stringify(util_1.Util.extend({ "Description": description, "Group": group, "Id": { "StringValue": id }, "Name": name, "__metadata": { "type": "SP.ContentType" }, }, additionalSettings)); return this.post({ body: postBody }).then(function (data) { return { contentType: _this.getById(data.id), data: data }; }); }; return ContentTypes; }(queryable_1.QueryableCollection)); exports.ContentTypes = ContentTypes; /** * Describes a single ContentType instance * */ var ContentType = (function (_super) { __extends(ContentType, _super); function ContentType() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(ContentType.prototype, "fieldLinks", { /** * Gets the column (also known as field) references in the content type. */ get: function () { return new FieldLinks(this); }, enumerable: true, configurable: true }); Object.defineProperty(ContentType.prototype, "fields", { /** * Gets a value that specifies the collection of fields for the content type. */ get: function () { return new queryable_1.QueryableCollection(this, "fields"); }, enumerable: true, configurable: true }); Object.defineProperty(ContentType.prototype, "parent", { /** * Gets the parent content type of the content type. */ get: function () { return new ContentType(this, "parent"); }, enumerable: true, configurable: true }); Object.defineProperty(ContentType.prototype, "workflowAssociations", { /** * Gets a value that specifies the collection of workflow associations for the content type. */ get: function () { return new queryable_1.QueryableCollection(this, "workflowAssociations"); }, enumerable: true, configurable: true }); /** * Delete this content type */ ContentType.prototype.delete = function () { return this.post({ headers: { "X-HTTP-Method": "DELETE", }, }); }; return ContentType; }(queryable_1.QueryableInstance)); exports.ContentType = ContentType; /** * Represents a collection of field link instances */ var FieldLinks = (function (_super) { __extends(FieldLinks, _super); /** * Creates a new instance of the ContentType class * * @param baseUrl The url or Queryable which forms the parent of this content type instance */ function FieldLinks(baseUrl, path) { if (path === void 0) { path = "fieldlinks"; } return _super.call(this, baseUrl, path) || this; } /** * Gets a FieldLink by GUID id * * @param id The GUID id of the field link */ FieldLinks.prototype.getById = function (id) { var fl = new FieldLink(this); fl.concat("(guid'" + id + "')"); return fl; }; return FieldLinks; }(queryable_1.QueryableCollection)); exports.FieldLinks = FieldLinks; /** * Represents a field link instance */ var FieldLink = (function (_super) { __extends(FieldLink, _super); function FieldLink() { return _super !== null && _super.apply(this, arguments) || this; } return FieldLink; }(queryable_1.QueryableInstance)); exports.FieldLink = FieldLink; /***/ }), /* 17 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var queryable_1 = __webpack_require__(1); var sitegroups_1 = __webpack_require__(18); var util_1 = __webpack_require__(0); /** * Describes a set of role assignments for the current scope * */ var RoleAssignments = (function (_super) { __extends(RoleAssignments, _super); /** * Creates a new instance of the RoleAssignments class * * @param baseUrl The url or Queryable which forms the parent of this fields collection */ function RoleAssignments(baseUrl, path) { if (path === void 0) { path = "roleassignments"; } return _super.call(this, baseUrl, path) || this; } /** * Adds a new role assignment with the specified principal and role definitions to the collection. * * @param principalId The ID of the user or group to assign permissions to * @param roleDefId The ID of the role definition that defines the permissions to assign * */ RoleAssignments.prototype.add = function (principalId, roleDefId) { return this.clone(RoleAssignments, "addroleassignment(principalid=" + principalId + ", roledefid=" + roleDefId + ")", true).post(); }; /** * Removes the role assignment with the specified principal and role definition from the collection * * @param principalId The ID of the user or group in the role assignment. * @param roleDefId The ID of the role definition in the role assignment * */ RoleAssignments.prototype.remove = function (principalId, roleDefId) { return this.clone(RoleAssignments, "removeroleassignment(principalid=" + principalId + ", roledefid=" + roleDefId + ")", true).post(); }; /** * Gets the role assignment associated with the specified principal ID from the collection. * * @param id The id of the role assignment */ RoleAssignments.prototype.getById = function (id) { var ra = new RoleAssignment(this); ra.concat("(" + id + ")"); return ra; }; return RoleAssignments; }(queryable_1.QueryableCollection)); exports.RoleAssignments = RoleAssignments; var RoleAssignment = (function (_super) { __extends(RoleAssignment, _super); function RoleAssignment() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(RoleAssignment.prototype, "groups", { get: function () { return new sitegroups_1.SiteGroups(this, "groups"); }, enumerable: true, configurable: true }); Object.defineProperty(RoleAssignment.prototype, "bindings", { /** * Get the role definition bindings for this role assignment * */ get: function () { return new RoleDefinitionBindings(this); }, enumerable: true, configurable: true }); /** * Delete this role assignment * */ RoleAssignment.prototype.delete = function () { return this.post({ headers: { "X-HTTP-Method": "DELETE", }, }); }; return RoleAssignment; }(queryable_1.QueryableInstance)); exports.RoleAssignment = RoleAssignment; var RoleDefinitions = (function (_super) { __extends(RoleDefinitions, _super); /** * Creates a new instance of the RoleDefinitions class * * @param baseUrl The url or Queryable which forms the parent of this fields collection * @param path * */ function RoleDefinitions(baseUrl, path) { if (path === void 0) { path = "roledefinitions"; } return _super.call(this, baseUrl, path) || this; } /** * Gets the role definition with the specified ID from the collection. * * @param id The ID of the role definition. * */ RoleDefinitions.prototype.getById = function (id) { return new RoleDefinition(this, "getById(" + id + ")"); }; /** * Gets the role definition with the specified name. * * @param name The name of the role definition. * */ RoleDefinitions.prototype.getByName = function (name) { return new RoleDefinition(this, "getbyname('" + name + "')"); }; /** * Gets the role definition with the specified type. * * @param name The name of the role definition. * */ RoleDefinitions.prototype.getByType = function (roleTypeKind) { return new RoleDefinition(this, "getbytype(" + roleTypeKind + ")"); }; /** * Create a role definition * * @param name The new role definition's name * @param description The new role definition's description * @param order The order in which the role definition appears * @param basePermissions The permissions mask for this role definition * */ RoleDefinitions.prototype.add = function (name, description, order, basePermissions) { var _this = this; var postBody = JSON.stringify({ BasePermissions: util_1.Util.extend({ __metadata: { type: "SP.BasePermissions" } }, basePermissions), Description: description, Name: name, Order: order, __metadata: { "type": "SP.RoleDefinition" }, }); return this.post({ body: postBody }).then(function (data) { return { data: data, definition: _this.getById(data.Id), }; }); }; return RoleDefinitions; }(queryable_1.QueryableCollection)); exports.RoleDefinitions = RoleDefinitions; var RoleDefinition = (function (_super) { __extends(RoleDefinition, _super); function RoleDefinition() { return _super !== null && _super.apply(this, arguments) || this; } /** * Updates this web intance with the supplied properties * * @param properties A plain object hash of values to update for the web */ /* tslint:disable no-string-literal */ RoleDefinition.prototype.update = function (properties) { var _this = this; if (typeof properties.hasOwnProperty("BasePermissions") !== "undefined") { properties["BasePermissions"] = util_1.Util.extend({ __metadata: { type: "SP.BasePermissions" } }, properties["BasePermissions"]); } var postBody = JSON.stringify(util_1.Util.extend({ "__metadata": { "type": "SP.RoleDefinition" }, }, properties)); return this.post({ body: postBody, headers: { "X-HTTP-Method": "MERGE", }, }).then(function (data) { var retDef = _this; if (properties.hasOwnProperty("Name")) { var parent_1 = _this.getParent(RoleDefinitions, _this.parentUrl, ""); retDef = parent_1.getByName(properties["Name"]); } return { data: data, definition: retDef, }; }); }; /* tslint:enable */ /** * Delete this role definition * */ RoleDefinition.prototype.delete = function () { return this.post({ headers: { "X-HTTP-Method": "DELETE", }, }); }; return RoleDefinition; }(queryable_1.QueryableInstance)); exports.RoleDefinition = RoleDefinition; var RoleDefinitionBindings = (function (_super) { __extends(RoleDefinitionBindings, _super); function RoleDefinitionBindings(baseUrl, path) { if (path === void 0) { path = "roledefinitionbindings"; } return _super.call(this, baseUrl, path) || this; } return RoleDefinitionBindings; }(queryable_1.QueryableCollection)); exports.RoleDefinitionBindings = RoleDefinitionBindings; /***/ }), /* 18 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var queryable_1 = __webpack_require__(1); var siteusers_1 = __webpack_require__(30); var util_1 = __webpack_require__(0); /** * Principal Type enum * */ var PrincipalType; (function (PrincipalType) { PrincipalType[PrincipalType["None"] = 0] = "None"; PrincipalType[PrincipalType["User"] = 1] = "User"; PrincipalType[PrincipalType["DistributionList"] = 2] = "DistributionList"; PrincipalType[PrincipalType["SecurityGroup"] = 4] = "SecurityGroup"; PrincipalType[PrincipalType["SharePointGroup"] = 8] = "SharePointGroup"; PrincipalType[PrincipalType["All"] = 15] = "All"; })(PrincipalType = exports.PrincipalType || (exports.PrincipalType = {})); /** * Describes a collection of site groups * */ var SiteGroups = (function (_super) { __extends(SiteGroups, _super); /** * Creates a new instance of the SiteGroups class * * @param baseUrl The url or Queryable which forms the parent of this group collection */ function SiteGroups(baseUrl, path) { if (path === void 0) { path = "sitegroups"; } return _super.call(this, baseUrl, path) || this; } /** * Adds a new group to the site collection * * @param props The group properties object of property names and values to be set for the group */ SiteGroups.prototype.add = function (properties) { var _this = this; var postBody = JSON.stringify(util_1.Util.extend({ "__metadata": { "type": "SP.Group" } }, properties)); return this.post({ body: postBody }).then(function (data) { return { data: data, group: _this.getById(data.Id), }; }); }; /** * Gets a group from the collection by name * * @param groupName The name of the group to retrieve */ SiteGroups.prototype.getByName = function (groupName) { return new SiteGroup(this, "getByName('" + groupName + "')"); }; /** * Gets a group from the collection by id * * @param id The id of the group to retrieve */ SiteGroups.prototype.getById = function (id) { var sg = new SiteGroup(this); sg.concat("(" + id + ")"); return sg; }; /** * Removes the group with the specified member id from the collection * * @param id The id of the group to remove */ SiteGroups.prototype.removeById = function (id) { return this.clone(SiteGroups, "removeById('" + id + "')", true).post(); }; /** * Removes the cross-site group with the specified name from the collection * * @param loginName The name of the group to remove */ SiteGroups.prototype.removeByLoginName = function (loginName) { return this.clone(SiteGroups, "removeByLoginName('" + loginName + "')", true).post(); }; return SiteGroups; }(queryable_1.QueryableCollection)); exports.SiteGroups = SiteGroups; /** * Describes a single group * */ var SiteGroup = (function (_super) { __extends(SiteGroup, _super); function SiteGroup() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(SiteGroup.prototype, "users", { /** * Gets the users for this group * */ get: function () { return new siteusers_1.SiteUsers(this, "users"); }, enumerable: true, configurable: true }); /** * Updates this group instance with the supplied properties * * @param properties A GroupWriteableProperties object of property names and values to update for the group */ /* tslint:disable no-string-literal */ SiteGroup.prototype.update = function (properties) { var _this = this; var postBody = util_1.Util.extend({ "__metadata": { "type": "SP.Group" } }, properties); return this.post({ body: JSON.stringify(postBody), headers: { "X-HTTP-Method": "MERGE", }, }).then(function (data) { var retGroup = _this; if (properties.hasOwnProperty("Title")) { retGroup = _this.getParent(SiteGroup, _this.parentUrl, "getByName('" + properties["Title"] + "')"); } return { data: data, group: retGroup, }; }); }; return SiteGroup; }(queryable_1.QueryableInstance)); exports.SiteGroup = SiteGroup; /***/ }), /* 19 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var queryable_1 = __webpack_require__(1); var util_1 = __webpack_require__(0); /** * Describes a collection of user custom actions * */ var UserCustomActions = (function (_super) { __extends(UserCustomActions, _super); /** * Creates a new instance of the UserCustomActions class * * @param baseUrl The url or Queryable which forms the parent of this user custom actions collection */ function UserCustomActions(baseUrl, path) { if (path === void 0) { path = "usercustomactions"; } return _super.call(this, baseUrl, path) || this; } /** * Returns the user custom action with the specified id * * @param id The GUID id of the user custom action to retrieve */ UserCustomActions.prototype.getById = function (id) { var uca = new UserCustomAction(this); uca.concat("('" + id + "')"); return uca; }; /** * Creates a user custom action * * @param properties The information object of property names and values which define the new user custom action * */ UserCustomActions.prototype.add = function (properties) { var _this = this; var postBody = JSON.stringify(util_1.Util.extend({ __metadata: { "type": "SP.UserCustomAction" } }, properties)); return this.post({ body: postBody }).then(function (data) { return { action: _this.getById(data.Id), data: data, }; }); }; /** * Deletes all user custom actions in the collection * */ UserCustomActions.prototype.clear = function () { return this.clone(UserCustomActions, "clear", true).post(); }; return UserCustomActions; }(queryable_1.QueryableCollection)); exports.UserCustomActions = UserCustomActions; /** * Describes a single user custom action * */ var UserCustomAction = (function (_super) { __extends(UserCustomAction, _super); function UserCustomAction() { return _super !== null && _super.apply(this, arguments) || this; } /** * Updates this user custom action with the supplied properties * * @param properties An information object of property names and values to update for this user custom action */ UserCustomAction.prototype.update = function (properties) { var _this = this; var postBody = JSON.stringify(util_1.Util.extend({ "__metadata": { "type": "SP.UserCustomAction" }, }, properties)); return this.post({ body: postBody, headers: { "X-HTTP-Method": "MERGE", }, }).then(function (data) { return { action: _this, data: data, }; }); }; /** * Removes this user custom action * */ UserCustomAction.prototype.delete = function () { return _super.prototype.delete.call(this); }; return UserCustomAction; }(queryable_1.QueryableInstance)); exports.UserCustomAction = UserCustomAction; /***/ }), /* 20 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var storage = __webpack_require__(14); var exceptions_1 = __webpack_require__(3); /** * A caching provider which can wrap other non-caching providers * */ var CachingConfigurationProvider = (function () { /** * Creates a new caching configuration provider * @constructor * @param {IConfigurationProvider} wrappedProvider Provider which will be used to fetch the configuration * @param {string} cacheKey Key that will be used to store cached items to the cache * @param {IPnPClientStore} cacheStore OPTIONAL storage, which will be used to store cached settings. */ function CachingConfigurationProvider(wrappedProvider, cacheKey, cacheStore) { this.wrappedProvider = wrappedProvider; this.store = (cacheStore) ? cacheStore : this.selectPnPCache(); this.cacheKey = "_configcache_" + cacheKey; } /** * Gets the wrapped configuration providers * * @return {IConfigurationProvider} Wrapped configuration provider */ CachingConfigurationProvider.prototype.getWrappedProvider = function () { return this.wrappedProvider; }; /** * Loads the configuration values either from the cache or from the wrapped provider * * @return {Promise<TypedHash<string>>} Promise of loaded configuration values */ CachingConfigurationProvider.prototype.getConfiguration = function () { var _this = this; // Cache not available, pass control to the wrapped provider if ((!this.store) || (!this.store.enabled)) { return this.wrappedProvider.getConfiguration(); } // Value is found in cache, return it directly var cachedConfig = this.store.get(this.cacheKey); if (cachedConfig) { return new Promise(function (resolve) { resolve(cachedConfig); }); } // Get and cache value from the wrapped provider var providerPromise = this.wrappedProvider.getConfiguration(); providerPromise.then(function (providedConfig) { _this.store.put(_this.cacheKey, providedConfig); }); return providerPromise; }; CachingConfigurationProvider.prototype.selectPnPCache = function () { var pnpCache = new storage.PnPClientStorage(); if ((pnpCache.local) && (pnpCache.local.enabled)) { return pnpCache.local; } if ((pnpCache.session) && (pnpCache.session.enabled)) { return pnpCache.session; } throw new exceptions_1.NoCacheAvailableException(); }; return CachingConfigurationProvider; }()); exports.default = CachingConfigurationProvider; /***/ }), /* 21 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* WEBPACK VAR INJECTION */(function(global) { Object.defineProperty(exports, "__esModule", { value: true }); /** * Makes requests using the fetch API */ var FetchClient = (function () { function FetchClient() { } FetchClient.prototype.fetch = function (url, options) { return global.fetch(url, options); }; return FetchClient; }()); exports.FetchClient = FetchClient; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(32))) /***/ }), /* 22 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var storage_1 = __webpack_require__(14); var util_1 = __webpack_require__(0); var pnplibconfig_1 = __webpack_require__(4); var CachingOptions = (function () { function CachingOptions(key) { this.key = key; this.expiration = util_1.Util.dateAdd(new Date(), "second", pnplibconfig_1.RuntimeConfig.defaultCachingTimeoutSeconds); this.storeName = pnplibconfig_1.RuntimeConfig.defaultCachingStore; } Object.defineProperty(CachingOptions.prototype, "store", { get: function () { if (this.storeName === "local") { return CachingOptions.storage.local; } else { return CachingOptions.storage.session; } }, enumerable: true, configurable: true }); return CachingOptions; }()); CachingOptions.storage = new storage_1.PnPClientStorage(); exports.CachingOptions = CachingOptions; var CachingParserWrapper = (function () { function CachingParserWrapper(_parser, _cacheOptions) { this._parser = _parser; this._cacheOptions = _cacheOptions; } CachingParserWrapper.prototype.parse = function (response) { var _this = this; // add this to the cache based on the options return this._parser.parse(response).then(function (data) { if (_this._cacheOptions.store !== null) { _this._cacheOptions.store.put(_this._cacheOptions.key, data, _this._cacheOptions.expiration); } return data; }); }; return CachingParserWrapper; }()); exports.CachingParserWrapper = CachingParserWrapper; /***/ }), /* 23 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var queryable_1 = __webpack_require__(1); /** * Describes a collection of List objects * */ var Features = (function (_super) { __extends(Features, _super); /** * Creates a new instance of the Lists class * * @param baseUrl The url or Queryable which forms the parent of this fields collection */ function Features(baseUrl, path) { if (path === void 0) { path = "features"; } return _super.call(this, baseUrl, path) || this; } /** * Gets a list from the collection by guid id * * @param id The Id of the feature (GUID) */ Features.prototype.getById = function (id) { var feature = new Feature(this); feature.concat("('" + id + "')"); return feature; }; /** * Adds a new list to the collection * * @param id The Id of the feature (GUID) * @param force If true the feature activation will be forced */ Features.prototype.add = function (id, force) { var _this = this; if (force === void 0) { force = false; } return this.clone(Features, "add", true).post({ body: JSON.stringify({ featdefScope: 0, featureId: id, force: force, }), }).then(function (data) { return { data: data, feature: _this.getById(id), }; }); }; /** * Removes (deactivates) a feature from the collection * * @param id The Id of the feature (GUID) * @param force If true the feature deactivation will be forced */ Features.prototype.remove = function (id, force) { if (force === void 0) { force = false; } return this.clone(Features, "remove", true).post({ body: JSON.stringify({ featureId: id, force: force, }), }); }; return Features; }(queryable_1.QueryableCollection)); exports.Features = Features; var Feature = (function (_super) { __extends(Feature, _super); function Feature() { return _super !== null && _super.apply(this, arguments) || this; } /** * Removes (deactivates) a feature from the collection * * @param force If true the feature deactivation will be forced */ Feature.prototype.deactivate = function (force) { var _this = this; if (force === void 0) { force = false; } var removeDependency = this.addBatchDependency(); var idGet = new Feature(this).select("DefinitionId"); return idGet.getAs().then(function (feature) { var promise = _this.getParent(Features, _this.parentUrl, "", _this.batch).remove(feature.DefinitionId, force); removeDependency(); return promise; }); }; return Feature; }(queryable_1.QueryableInstance)); exports.Feature = Feature; /***/ }), /* 24 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var queryable_1 = __webpack_require__(1); var util_1 = __webpack_require__(0); var types_1 = __webpack_require__(13); /** * Describes a collection of Field objects * */ var Fields = (function (_super) { __extends(Fields, _super); /** * Creates a new instance of the Fields class * * @param baseUrl The url or Queryable which forms the parent of this fields collection */ function Fields(baseUrl, path) { if (path === void 0) { path = "fields"; } return _super.call(this, baseUrl, path) || this; } /** * Gets a field from the collection by title * * @param title The case-sensitive title of the field */ Fields.prototype.getByTitle = function (title) { return new Field(this, "getByTitle('" + title + "')"); }; /** * Gets a field from the collection by using internal name or title * * @param name The case-sensitive internal name or title of the field */ Fields.prototype.getByInternalNameOrTitle = function (name) { return new Field(this, "getByInternalNameOrTitle('" + name + "')"); }; /** * Gets a list from the collection by guid id * * @param title The Id of the list */ Fields.prototype.getById = function (id) { var f = new Field(this); f.concat("('" + id + "')"); return f; }; /** * Creates a field based on the specified schema */ Fields.prototype.createFieldAsXml = function (xml) { var _this = this; var info; if (typeof xml === "string") { info = { SchemaXml: xml }; } else { info = xml; } var postBody = JSON.stringify({ "parameters": util_1.Util.extend({ "__metadata": { "type": "SP.XmlSchemaFieldCreationInformation", }, }, info), }); return this.clone(Fields, "createfieldasxml", true).postAs({ body: postBody }).then(function (data) { return { data: data, field: _this.getById(data.Id), }; }); }; /** * Adds a new list to the collection * * @param title The new field's title * @param fieldType The new field's type (ex: SP.FieldText) * @param properties Differ by type of field being created (see: https://msdn.microsoft.com/en-us/library/office/dn600182.aspx) */ Fields.prototype.add = function (title, fieldType, properties) { var _this = this; if (properties === void 0) { properties = {}; } var postBody = JSON.stringify(util_1.Util.extend({ "Title": title, "__metadata": { "type": fieldType }, }, properties)); return this.clone(Fields, null, true).postAs({ body: postBody }).then(function (data) { return { data: data, field: _this.getById(data.Id), }; }); }; /** * Adds a new SP.FieldText to the collection * * @param title The field title * @param maxLength The maximum number of characters allowed in the value of the field. * @param properties Differ by type of field being created (see: https://msdn.microsoft.com/en-us/library/office/dn600182.aspx) */ Fields.prototype.addText = function (title, maxLength, properties) { if (maxLength === void 0) { maxLength = 255; } var props = { FieldTypeKind: 2, MaxLength: maxLength, }; return this.add(title, "SP.FieldText", util_1.Util.extend(props, properties)); }; /** * Adds a new SP.FieldCalculated to the collection * * @param title The field title. * @param formula The formula for the field. * @param dateFormat The date and time format that is displayed in the field. * @param outputType Specifies the output format for the field. Represents a FieldType value. * @param properties Differ by type of field being created (see: https://msdn.microsoft.com/en-us/library/office/dn600182.aspx) */ Fields.prototype.addCalculated = function (title, formula, dateFormat, outputType, properties) { if (outputType === void 0) { outputType = types_1.FieldTypes.Text; } var props = { DateFormat: dateFormat, FieldTypeKind: 17, Formula: formula, OutputType: outputType, }; return this.add(title, "SP.FieldCalculated", util_1.Util.extend(props, properties)); }; /** * Adds a new SP.FieldDateTime to the collection * * @param title The field title * @param displayFormat The format of the date and time that is displayed in the field. * @param calendarType Specifies the calendar type of the field. * @param properties Differ by type of field being created (see: https://msdn.microsoft.com/en-us/library/office/dn600182.aspx) */ Fields.prototype.addDateTime = function (title, displayFormat, calendarType, friendlyDisplayFormat, properties) { if (displayFormat === void 0) { displayFormat = types_1.DateTimeFieldFormatType.DateOnly; } if (calendarType === void 0) { calendarType = types_1.CalendarType.Gregorian; } if (friendlyDisplayFormat === void 0) { friendlyDisplayFormat = 0; } var props = { DateTimeCalendarType: calendarType, DisplayFormat: displayFormat, FieldTypeKind: 4, FriendlyDisplayFormat: friendlyDisplayFormat, }; return this.add(title, "SP.FieldDateTime", util_1.Util.extend(props, properties)); }; /** * Adds a new SP.FieldNumber to the collection * * @param title The field title * @param minValue The field's minimum value * @param maxValue The field's maximum value * @param properties Differ by type of field being created (see: https://msdn.microsoft.com/en-us/library/office/dn600182.aspx) */ Fields.prototype.addNumber = function (title, minValue, maxValue, properties) { var props = { FieldTypeKind: 9 }; if (typeof minValue !== "undefined") { props = util_1.Util.extend({ MinimumValue: minValue }, props); } if (typeof maxValue !== "undefined") { props = util_1.Util.extend({ MaximumValue: maxValue }, props); } return this.add(title, "SP.FieldNumber", util_1.Util.extend(props, properties)); }; /** * Adds a new SP.FieldCurrency to the collection * * @param title The field title * @param minValue The field's minimum value * @param maxValue The field's maximum value * @param currencyLocalId Specifies the language code identifier (LCID) used to format the value of the field * @param properties Differ by type of field being created (see: https://msdn.microsoft.com/en-us/library/office/dn600182.aspx) */ Fields.prototype.addCurrency = function (title, minValue, maxValue, currencyLocalId, properties) { if (currencyLocalId === void 0) { currencyLocalId = 1033; } var props = { CurrencyLocaleId: currencyLocalId, FieldTypeKind: 10, }; if (typeof minValue !== "undefined") { props = util_1.Util.extend({ MinimumValue: minValue }, props); } if (typeof maxValue !== "undefined") { props = util_1.Util.extend({ MaximumValue: maxValue }, props); } return this.add(title, "SP.FieldCurrency", util_1.Util.extend(props, properties)); }; /** * Adds a new SP.FieldMultiLineText to the collection * * @param title The field title * @param numberOfLines Specifies the number of lines of text to display for the field. * @param richText Specifies whether the field supports rich formatting. * @param restrictedMode Specifies whether the field supports a subset of rich formatting. * @param appendOnly Specifies whether all changes to the value of the field are displayed in list forms. * @param allowHyperlink Specifies whether a hyperlink is allowed as a value of the field. * @param properties Differ by type of field being created (see: https://msdn.microsoft.com/en-us/library/office/dn600182.aspx) * */ Fields.prototype.addMultilineText = function (title, numberOfLines, richText, restrictedMode, appendOnly, allowHyperlink, properties) { if (numberOfLines === void 0) { numberOfLines = 6; } if (richText === void 0) { richText = true; } if (restrictedMode === void 0) { restrictedMode = false; } if (appendOnly === void 0) { appendOnly = false; } if (allowHyperlink === void 0) { allowHyperlink = true; } var props = { AllowHyperlink: allowHyperlink, AppendOnly: appendOnly, FieldTypeKind: 3, NumberOfLines: numberOfLines, RestrictedMode: restrictedMode, RichText: richText, }; return this.add(title, "SP.FieldMultiLineText", util_1.Util.extend(props, properties)); }; /** * Adds a new SP.FieldUrl to the collection * * @param title The field title */ Fields.prototype.addUrl = function (title, displayFormat, properties) { if (displayFormat === void 0) { displayFormat = types_1.UrlFieldFormatType.Hyperlink; } var props = { DisplayFormat: displayFormat, FieldTypeKind: 11, }; return this.add(title, "SP.FieldUrl", util_1.Util.extend(props, properties)); }; return Fields; }(queryable_1.QueryableCollection)); exports.Fields = Fields; /** * Describes a single of Field instance * */ var Field = (function (_super) { __extends(Field, _super); function Field() { return _super !== null && _super.apply(this, arguments) || this; } /** * Updates this field intance with the supplied properties * * @param properties A plain object hash of values to update for the list * @param fieldType The type value, required to update child field type properties */ Field.prototype.update = function (properties, fieldType) { var _this = this; if (fieldType === void 0) { fieldType = "SP.Field"; } var postBody = JSON.stringify(util_1.Util.extend({ "__metadata": { "type": fieldType }, }, properties)); return this.post({ body: postBody, headers: { "X-HTTP-Method": "MERGE", }, }).then(function (data) { return { data: data, field: _this, }; }); }; /** * Delete this fields * */ Field.prototype.delete = function () { return this.post({ headers: { "X-HTTP-Method": "DELETE", }, }); }; /** * Sets the value of the ShowInDisplayForm property for this field. */ Field.prototype.setShowInDisplayForm = function (show) { return this.clone(Field, "setshowindisplayform(" + show + ")", true).post(); }; /** * Sets the value of the ShowInEditForm property for this field. */ Field.prototype.setShowInEditForm = function (show) { return this.clone(Field, "setshowineditform(" + show + ")", true).post(); }; /** * Sets the value of the ShowInNewForm property for this field. */ Field.prototype.setShowInNewForm = function (show) { return this.clone(Field, "setshowinnewform(" + show + ")", true).post(); }; return Field; }(queryable_1.QueryableInstance)); exports.Field = Field; /***/ }), /* 25 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var util_1 = __webpack_require__(0); var queryable_1 = __webpack_require__(1); /** * Represents a collection of navigation nodes * */ var NavigationNodes = (function (_super) { __extends(NavigationNodes, _super); function NavigationNodes() { return _super !== null && _super.apply(this, arguments) || this; } /** * Gets a navigation node by id * * @param id The id of the node */ NavigationNodes.prototype.getById = function (id) { var node = new NavigationNode(this); node.concat("(" + id + ")"); return node; }; /** * Adds a new node to the collection * * @param title Display name of the node * @param url The url of the node * @param visible If true the node is visible, otherwise it is hidden (default: true) */ NavigationNodes.prototype.add = function (title, url, visible) { var _this = this; if (visible === void 0) { visible = true; } var postBody = JSON.stringify({ IsVisible: visible, Title: title, Url: url, "__metadata": { "type": "SP.NavigationNode" }, }); return this.clone(NavigationNodes, null, true).post({ body: postBody }).then(function (data) { return { data: data, node: _this.getById(data.Id), }; }); }; /** * Moves a node to be after another node in the navigation * * @param nodeId Id of the node to move * @param previousNodeId Id of the node after which we move the node specified by nodeId */ NavigationNodes.prototype.moveAfter = function (nodeId, previousNodeId) { var postBody = JSON.stringify({ nodeId: nodeId, previousNodeId: previousNodeId, }); return this.clone(NavigationNodes, "MoveAfter", true).post({ body: postBody }); }; return NavigationNodes; }(queryable_1.QueryableCollection)); exports.NavigationNodes = NavigationNodes; var NavigationNode = (function (_super) { __extends(NavigationNode, _super); function NavigationNode() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(NavigationNode.prototype, "children", { /** * Represents the child nodes of this node */ get: function () { return new NavigationNodes(this, "Children"); }, enumerable: true, configurable: true }); /** * Updates this node based on the supplied properties * * @param properties The hash of key/value pairs to update */ NavigationNode.prototype.update = function (properties) { var _this = this; var postBody = JSON.stringify(util_1.Util.extend({ "__metadata": { "type": "SP.NavigationNode" }, }, properties)); return this.post({ body: postBody, headers: { "X-HTTP-Method": "MERGE", }, }).then(function (data) { return { data: data, node: _this, }; }); }; /** * Deletes this node and any child nodes */ NavigationNode.prototype.delete = function () { return _super.prototype.delete.call(this); }; return NavigationNode; }(queryable_1.QueryableInstance)); exports.NavigationNode = NavigationNode; /** * Exposes the navigation components * */ var Navigation = (function (_super) { __extends(Navigation, _super); /** * Creates a new instance of the Lists class * * @param baseUrl The url or Queryable which forms the parent of this fields collection */ function Navigation(baseUrl, path) { if (path === void 0) { path = "navigation"; } return _super.call(this, baseUrl, path) || this; } Object.defineProperty(Navigation.prototype, "quicklaunch", { /** * Gets the quicklaunch navigation for the current context * */ get: function () { return new NavigationNodes(this, "quicklaunch"); }, enumerable: true, configurable: true }); Object.defineProperty(Navigation.prototype, "topNavigationBar", { /** * Gets the top bar navigation navigation for the current context * */ get: function () { return new NavigationNodes(this, "topnavigationbar"); }, enumerable: true, configurable: true }); return Navigation; }(queryable_1.Queryable)); exports.Navigation = Navigation; /***/ }), /* 26 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var webs_1 = __webpack_require__(8); var roles_1 = __webpack_require__(17); var types_1 = __webpack_require__(13); var queryable_1 = __webpack_require__(1); var QueryableSecurable = (function (_super) { __extends(QueryableSecurable, _super); function QueryableSecurable() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(QueryableSecurable.prototype, "roleAssignments", { /** * Gets the set of role assignments for this item * */ get: function () { return new roles_1.RoleAssignments(this); }, enumerable: true, configurable: true }); Object.defineProperty(QueryableSecurable.prototype, "firstUniqueAncestorSecurableObject", { /** * Gets the closest securable up the security hierarchy whose permissions are applied to this list item * */ get: function () { return new queryable_1.QueryableInstance(this, "FirstUniqueAncestorSecurableObject"); }, enumerable: true, configurable: true }); /** * Gets the effective permissions for the user supplied * * @param loginName The claims username for the user (ex: i:0#.f|membership|user@domain.com) */ QueryableSecurable.prototype.getUserEffectivePermissions = function (loginName) { var q = this.clone(queryable_1.Queryable, "getUserEffectivePermissions(@user)", true); q.query.add("@user", "'" + encodeURIComponent(loginName) + "'"); return q.getAs(); }; /** * Gets the effective permissions for the current user */ QueryableSecurable.prototype.getCurrentUserEffectivePermissions = function () { var _this = this; var w = webs_1.Web.fromUrl(this.toUrl()); return w.currentUser.select("LoginName").getAs().then(function (user) { return _this.getUserEffectivePermissions(user.LoginName); }); }; /** * Breaks the security inheritance at this level optinally copying permissions and clearing subscopes * * @param copyRoleAssignments If true the permissions are copied from the current parent scope * @param clearSubscopes Optional. true to make all child securable objects inherit role assignments from the current object */ QueryableSecurable.prototype.breakRoleInheritance = function (copyRoleAssignments, clearSubscopes) { if (copyRoleAssignments === void 0) { copyRoleAssignments = false; } if (clearSubscopes === void 0) { clearSubscopes = false; } return this.clone(QueryableSecurable, "breakroleinheritance(copyroleassignments=" + copyRoleAssignments + ", clearsubscopes=" + clearSubscopes + ")", true).post(); }; /** * Removes the local role assignments so that it re-inherit role assignments from the parent object. * */ QueryableSecurable.prototype.resetRoleInheritance = function () { return this.clone(QueryableSecurable, "resetroleinheritance", true).post(); }; /** * Determines if a given user has the appropriate permissions * * @param loginName The user to check * @param permission The permission being checked */ QueryableSecurable.prototype.userHasPermissions = function (loginName, permission) { var _this = this; return this.getUserEffectivePermissions(loginName).then(function (perms) { return _this.hasPermissions(perms, permission); }); }; /** * Determines if the current user has the requested permissions * * @param permission The permission we wish to check */ QueryableSecurable.prototype.currentUserHasPermissions = function (permission) { var _this = this; return this.getCurrentUserEffectivePermissions().then(function (perms) { return _this.hasPermissions(perms, permission); }); }; /** * Taken from sp.js, checks the supplied permissions against the mask * * @param value The security principal's permissions on the given object * @param perm The permission checked against the value */ /* tslint:disable:no-bitwise */ QueryableSecurable.prototype.hasPermissions = function (value, perm) { if (!perm) { return true; } if (perm === types_1.PermissionKind.FullMask) { return (value.High & 32767) === 32767 && value.Low === 65535; } perm = perm - 1; var num = 1; if (perm >= 0 && perm < 32) { num = num << perm; return 0 !== (value.Low & num); } else if (perm >= 32 && perm < 64) { num = num << perm - 32; return 0 !== (value.High & num); } return false; }; return QueryableSecurable; }(queryable_1.QueryableInstance)); exports.QueryableSecurable = QueryableSecurable; /***/ }), /* 27 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var queryable_1 = __webpack_require__(1); var util_1 = __webpack_require__(0); /** * Allows for the fluent construction of search queries */ var SearchQueryBuilder = (function () { function SearchQueryBuilder(queryText, _query) { if (queryText === void 0) { queryText = ""; } if (_query === void 0) { _query = {}; } this._query = _query; if (typeof queryText === "string" && queryText.length > 0) { this.extendQuery({ Querytext: queryText }); } } SearchQueryBuilder.create = function (queryText, queryTemplate) { if (queryText === void 0) { queryText = ""; } if (queryTemplate === void 0) { queryTemplate = {}; } return new SearchQueryBuilder(queryText, queryTemplate); }; SearchQueryBuilder.prototype.text = function (queryText) { return this.extendQuery({ Querytext: queryText }); }; SearchQueryBuilder.prototype.template = function (template) { return this.extendQuery({ QueryTemplate: template }); }; SearchQueryBuilder.prototype.sourceId = function (id) { return this.extendQuery({ SourceId: id }); }; Object.defineProperty(SearchQueryBuilder.prototype, "enableInterleaving", { get: function () { return this.extendQuery({ EnableInterleaving: true }); }, enumerable: true, configurable: true }); Object.defineProperty(SearchQueryBuilder.prototype, "enableStemming", { get: function () { return this.extendQuery({ EnableStemming: true }); }, enumerable: true, configurable: true }); Object.defineProperty(SearchQueryBuilder.prototype, "trimDuplicates", { get: function () { return this.extendQuery({ TrimDuplicates: true }); }, enumerable: true, configurable: true }); Object.defineProperty(SearchQueryBuilder.prototype, "enableNicknames", { get: function () { return this.extendQuery({ EnableNicknames: true }); }, enumerable: true, configurable: true }); Object.defineProperty(SearchQueryBuilder.prototype, "enableFql", { get: function () { return this.extendQuery({ EnableFql: true }); }, enumerable: true, configurable: true }); Object.defineProperty(SearchQueryBuilder.prototype, "enablePhonetic", { get: function () { return this.extendQuery({ EnablePhonetic: true }); }, enumerable: true, configurable: true }); Object.defineProperty(SearchQueryBuilder.prototype, "bypassResultTypes", { get: function () { return this.extendQuery({ BypassResultTypes: true }); }, enumerable: true, configurable: true }); Object.defineProperty(SearchQueryBuilder.prototype, "processBestBets", { get: function () { return this.extendQuery({ ProcessBestBets: true }); }, enumerable: true, configurable: true }); Object.defineProperty(SearchQueryBuilder.prototype, "enableQueryRules", { get: function () { return this.extendQuery({ EnableQueryRules: true }); }, enumerable: true, configurable: true }); Object.defineProperty(SearchQueryBuilder.prototype, "enableSorting", { get: function () { return this.extendQuery({ EnableSorting: true }); }, enumerable: true, configurable: true }); Object.defineProperty(SearchQueryBuilder.prototype, "generateBlockRankLog", { get: function () { return this.extendQuery({ GenerateBlockRankLog: true }); }, enumerable: true, configurable: true }); SearchQueryBuilder.prototype.rankingModelId = function (id) { return this.extendQuery({ RankingModelId: id }); }; SearchQueryBuilder.prototype.startRow = function (id) { return this.extendQuery({ StartRow: id }); }; SearchQueryBuilder.prototype.rowLimit = function (id) { return this.extendQuery({ RowLimit: id }); }; SearchQueryBuilder.prototype.rowsPerPage = function (id) { return this.extendQuery({ RowsPerPage: id }); }; SearchQueryBuilder.prototype.selectProperties = function () { var properties = []; for (var _i = 0; _i < arguments.length; _i++) { properties[_i] = arguments[_i]; } return this.extendQuery({ SelectProperties: properties }); }; SearchQueryBuilder.prototype.culture = function (culture) { return this.extendQuery({ Culture: culture }); }; SearchQueryBuilder.prototype.refinementFilters = function () { var filters = []; for (var _i = 0; _i < arguments.length; _i++) { filters[_i] = arguments[_i]; } return this.extendQuery({ RefinementFilters: filters }); }; SearchQueryBuilder.prototype.refiners = function (refiners) { return this.extendQuery({ Refiners: refiners }); }; SearchQueryBuilder.prototype.hiddenConstraints = function (constraints) { return this.extendQuery({ HiddenConstraints: constraints }); }; SearchQueryBuilder.prototype.sortList = function () { var sorts = []; for (var _i = 0; _i < arguments.length; _i++) { sorts[_i] = arguments[_i]; } return this.extendQuery({ SortList: sorts }); }; SearchQueryBuilder.prototype.timeout = function (milliseconds) { return this.extendQuery({ Timeout: milliseconds }); }; SearchQueryBuilder.prototype.hithighlightedProperties = function () { var properties = []; for (var _i = 0; _i < arguments.length; _i++) { properties[_i] = arguments[_i]; } return this.extendQuery({ HithighlightedProperties: properties }); }; SearchQueryBuilder.prototype.clientType = function (clientType) { return this.extendQuery({ ClientType: clientType }); }; SearchQueryBuilder.prototype.personalizationData = function (data) { return this.extendQuery({ PersonalizationData: data }); }; SearchQueryBuilder.prototype.resultsURL = function (url) { return this.extendQuery({ ResultsURL: url }); }; SearchQueryBuilder.prototype.queryTag = function () { var tags = []; for (var _i = 0; _i < arguments.length; _i++) { tags[_i] = arguments[_i]; } return this.extendQuery({ QueryTag: tags }); }; SearchQueryBuilder.prototype.properties = function () { var properties = []; for (var _i = 0; _i < arguments.length; _i++) { properties[_i] = arguments[_i]; } return this.extendQuery({ Properties: properties }); }; Object.defineProperty(SearchQueryBuilder.prototype, "processPersonalFavorites", { get: function () { return this.extendQuery({ ProcessPersonalFavorites: true }); }, enumerable: true, configurable: true }); SearchQueryBuilder.prototype.queryTemplatePropertiesUrl = function (url) { return this.extendQuery({ QueryTemplatePropertiesUrl: url }); }; SearchQueryBuilder.prototype.reorderingRules = function () { var rules = []; for (var _i = 0; _i < arguments.length; _i++) { rules[_i] = arguments[_i]; } return this.extendQuery({ ReorderingRules: rules }); }; SearchQueryBuilder.prototype.hitHighlightedMultivaluePropertyLimit = function (limit) { return this.extendQuery({ HitHighlightedMultivaluePropertyLimit: limit }); }; Object.defineProperty(SearchQueryBuilder.prototype, "enableOrderingHitHighlightedProperty", { get: function () { return this.extendQuery({ EnableOrderingHitHighlightedProperty: true }); }, enumerable: true, configurable: true }); SearchQueryBuilder.prototype.collapseSpecification = function (spec) { return this.extendQuery({ CollapseSpecification: spec }); }; SearchQueryBuilder.prototype.uiLanguage = function (lang) { return this.extendQuery({ UIlanguage: lang }); }; SearchQueryBuilder.prototype.desiredSnippetLength = function (len) { return this.extendQuery({ DesiredSnippetLength: len }); }; SearchQueryBuilder.prototype.maxSnippetLength = function (len) { return this.extendQuery({ MaxSnippetLength: len }); }; SearchQueryBuilder.prototype.summaryLength = function (len) { return this.extendQuery({ SummaryLength: len }); }; SearchQueryBuilder.prototype.toSearchQuery = function () { return this._query; }; SearchQueryBuilder.prototype.extendQuery = function (part) { this._query = util_1.Util.extend(this._query, part); return this; }; return SearchQueryBuilder; }()); exports.SearchQueryBuilder = SearchQueryBuilder; /** * Describes the search API * */ var Search = (function (_super) { __extends(Search, _super); /** * Creates a new instance of the Search class * * @param baseUrl The url for the search context * @param query The SearchQuery object to execute */ function Search(baseUrl, path) { if (path === void 0) { path = "_api/search/postquery"; } return _super.call(this, baseUrl, path) || this; } /** * ....... * @returns Promise */ Search.prototype.execute = function (query) { var _this = this; var formattedBody; formattedBody = query; if (formattedBody.SelectProperties) { formattedBody.SelectProperties = { results: query.SelectProperties }; } if (formattedBody.RefinementFilters) { formattedBody.RefinementFilters = { results: query.RefinementFilters }; } if (formattedBody.SortList) { formattedBody.SortList = { results: query.SortList }; } if (formattedBody.HithighlightedProperties) { formattedBody.HithighlightedProperties = { results: query.HithighlightedProperties }; } if (formattedBody.ReorderingRules) { formattedBody.ReorderingRules = { results: query.ReorderingRules }; } if (formattedBody.Properties) { formattedBody.Properties = { results: query.Properties }; } var postBody = JSON.stringify({ request: util_1.Util.extend({ "__metadata": { "type": "Microsoft.Office.Server.Search.REST.SearchRequest" }, }, formattedBody), }); return this.post({ body: postBody }).then(function (data) { return new SearchResults(data, _this.toUrl(), query); }); }; return Search; }(queryable_1.QueryableInstance)); exports.Search = Search; /** * Describes the SearchResults class, which returns the formatted and raw version of the query response */ var SearchResults = (function () { /** * Creates a new instance of the SearchResult class * */ function SearchResults(rawResponse, _url, _query, _raw, _primary) { if (_raw === void 0) { _raw = null; } if (_primary === void 0) { _primary = null; } this._url = _url; this._query = _query; this._raw = _raw; this._primary = _primary; this._raw = rawResponse.postquery ? rawResponse.postquery : rawResponse; } Object.defineProperty(SearchResults.prototype, "ElapsedTime", { get: function () { return this.RawSearchResults.ElapsedTime; }, enumerable: true, configurable: true }); Object.defineProperty(SearchResults.prototype, "RowCount", { get: function () { return this.RawSearchResults.PrimaryQueryResult.RelevantResults.RowCount; }, enumerable: true, configurable: true }); Object.defineProperty(SearchResults.prototype, "TotalRows", { get: function () { return this.RawSearchResults.PrimaryQueryResult.RelevantResults.TotalRows; }, enumerable: true, configurable: true }); Object.defineProperty(SearchResults.prototype, "TotalRowsIncludingDuplicates", { get: function () { return this.RawSearchResults.PrimaryQueryResult.RelevantResults.TotalRowsIncludingDuplicates; }, enumerable: true, configurable: true }); Object.defineProperty(SearchResults.prototype, "RawSearchResults", { get: function () { return this._raw; }, enumerable: true, configurable: true }); Object.defineProperty(SearchResults.prototype, "PrimarySearchResults", { get: function () { if (this._primary === null) { this._primary = this.formatSearchResults(this._raw.PrimaryQueryResult.RelevantResults.Table.Rows); } return this._primary; }, enumerable: true, configurable: true }); /** * Gets a page of results * * @param pageNumber Index of the page to return. Used to determine StartRow * @param pageSize Optional, items per page (default = 10) */ SearchResults.prototype.getPage = function (pageNumber, pageSize) { // if we got all the available rows we don't have another page if (this.TotalRows < this.RowCount) { return Promise.resolve(null); } // if pageSize is supplied, then we use that regardless of any previous values // otherwise get the previous RowLimit or default to 10 var rows = typeof pageSize !== "undefined" ? pageSize : this._query.hasOwnProperty("RowLimit") ? this._query.RowLimit : 10; var query = util_1.Util.extend(this._query, { RowLimit: rows, StartRow: rows * (pageNumber - 1) + 1, }); // we have reached the end if (query.StartRow > this.TotalRows) { return Promise.resolve(null); } var search = new Search(this._url, null); return search.execute(query); }; /** * Formats a search results array * * @param rawResults The array to process */ SearchResults.prototype.formatSearchResults = function (rawResults) { var results = new Array(); var tempResults = rawResults.results ? rawResults.results : rawResults; for (var _i = 0, tempResults_1 = tempResults; _i < tempResults_1.length; _i++) { var tempResult = tempResults_1[_i]; var cells = tempResult.Cells.results ? tempResult.Cells.results : tempResult.Cells; results.push(cells.reduce(function (res, cell) { Object.defineProperty(res, cell.Key, { configurable: false, enumerable: false, value: cell.Value, writable: false, }); return res; }, {})); } return results; }; return SearchResults; }()); exports.SearchResults = SearchResults; /** * defines the SortDirection enum */ var SortDirection; (function (SortDirection) { SortDirection[SortDirection["Ascending"] = 0] = "Ascending"; SortDirection[SortDirection["Descending"] = 1] = "Descending"; SortDirection[SortDirection["FQLFormula"] = 2] = "FQLFormula"; })(SortDirection = exports.SortDirection || (exports.SortDirection = {})); /** * defines the ReorderingRuleMatchType enum */ var ReorderingRuleMatchType; (function (ReorderingRuleMatchType) { ReorderingRuleMatchType[ReorderingRuleMatchType["ResultContainsKeyword"] = 0] = "ResultContainsKeyword"; ReorderingRuleMatchType[ReorderingRuleMatchType["TitleContainsKeyword"] = 1] = "TitleContainsKeyword"; ReorderingRuleMatchType[ReorderingRuleMatchType["TitleMatchesKeyword"] = 2] = "TitleMatchesKeyword"; ReorderingRuleMatchType[ReorderingRuleMatchType["UrlStartsWith"] = 3] = "UrlStartsWith"; ReorderingRuleMatchType[ReorderingRuleMatchType["UrlExactlyMatches"] = 4] = "UrlExactlyMatches"; ReorderingRuleMatchType[ReorderingRuleMatchType["ContentTypeIs"] = 5] = "ContentTypeIs"; ReorderingRuleMatchType[ReorderingRuleMatchType["FileExtensionMatches"] = 6] = "FileExtensionMatches"; ReorderingRuleMatchType[ReorderingRuleMatchType["ResultHasTag"] = 7] = "ResultHasTag"; ReorderingRuleMatchType[ReorderingRuleMatchType["ManualCondition"] = 8] = "ManualCondition"; })(ReorderingRuleMatchType = exports.ReorderingRuleMatchType || (exports.ReorderingRuleMatchType = {})); /** * Specifies the type value for the property */ var QueryPropertyValueType; (function (QueryPropertyValueType) { QueryPropertyValueType[QueryPropertyValueType["None"] = 0] = "None"; QueryPropertyValueType[QueryPropertyValueType["StringType"] = 1] = "StringType"; QueryPropertyValueType[QueryPropertyValueType["Int32TYpe"] = 2] = "Int32TYpe"; QueryPropertyValueType[QueryPropertyValueType["BooleanType"] = 3] = "BooleanType"; QueryPropertyValueType[QueryPropertyValueType["StringArrayType"] = 4] = "StringArrayType"; QueryPropertyValueType[QueryPropertyValueType["UnSupportedType"] = 5] = "UnSupportedType"; })(QueryPropertyValueType = exports.QueryPropertyValueType || (exports.QueryPropertyValueType = {})); var SearchBuiltInSourceId = (function () { function SearchBuiltInSourceId() { } return SearchBuiltInSourceId; }()); SearchBuiltInSourceId.Documents = "e7ec8cee-ded8-43c9-beb5-436b54b31e84"; SearchBuiltInSourceId.ItemsMatchingContentType = "5dc9f503-801e-4ced-8a2c-5d1237132419"; SearchBuiltInSourceId.ItemsMatchingTag = "e1327b9c-2b8c-4b23-99c9-3730cb29c3f7"; SearchBuiltInSourceId.ItemsRelatedToCurrentUser = "48fec42e-4a92-48ce-8363-c2703a40e67d"; SearchBuiltInSourceId.ItemsWithSameKeywordAsThisItem = "5c069288-1d17-454a-8ac6-9c642a065f48"; SearchBuiltInSourceId.LocalPeopleResults = "b09a7990-05ea-4af9-81ef-edfab16c4e31"; SearchBuiltInSourceId.LocalReportsAndDataResults = "203fba36-2763-4060-9931-911ac8c0583b"; SearchBuiltInSourceId.LocalSharePointResults = "8413cd39-2156-4e00-b54d-11efd9abdb89"; SearchBuiltInSourceId.LocalVideoResults = "78b793ce-7956-4669-aa3b-451fc5defebf"; SearchBuiltInSourceId.Pages = "5e34578e-4d08-4edc-8bf3-002acf3cdbcc"; SearchBuiltInSourceId.Pictures = "38403c8c-3975-41a8-826e-717f2d41568a"; SearchBuiltInSourceId.Popular = "97c71db1-58ce-4891-8b64-585bc2326c12"; SearchBuiltInSourceId.RecentlyChangedItems = "ba63bbae-fa9c-42c0-b027-9a878f16557c"; SearchBuiltInSourceId.RecommendedItems = "ec675252-14fa-4fbe-84dd-8d098ed74181"; SearchBuiltInSourceId.Wiki = "9479bf85-e257-4318-b5a8-81a180f5faa1"; exports.SearchBuiltInSourceId = SearchBuiltInSourceId; /***/ }), /* 28 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var queryable_1 = __webpack_require__(1); var SearchSuggest = (function (_super) { __extends(SearchSuggest, _super); function SearchSuggest(baseUrl, path) { if (path === void 0) { path = "_api/search/suggest"; } return _super.call(this, baseUrl, path) || this; } SearchSuggest.prototype.execute = function (query) { this.mapQueryToQueryString(query); return this.get().then(function (response) { return new SearchSuggestResult(response); }); }; SearchSuggest.prototype.mapQueryToQueryString = function (query) { this.query.add("querytext", "'" + query.querytext + "'"); if (query.hasOwnProperty("count")) { this.query.add("inumberofquerysuggestions", query.count.toString()); } if (query.hasOwnProperty("personalCount")) { this.query.add("inumberofresultsuggestions", query.personalCount.toString()); } if (query.hasOwnProperty("preQuery")) { this.query.add("fprequerysuggestions", query.preQuery.toString()); } if (query.hasOwnProperty("hitHighlighting")) { this.query.add("fhithighlighting", query.hitHighlighting.toString()); } if (query.hasOwnProperty("capitalize")) { this.query.add("fcapitalizefirstletters", query.capitalize.toString()); } if (query.hasOwnProperty("culture")) { this.query.add("culture", query.culture.toString()); } if (query.hasOwnProperty("stemming")) { this.query.add("enablestemming", query.stemming.toString()); } if (query.hasOwnProperty("includePeople")) { this.query.add("showpeoplenamesuggestions", query.includePeople.toString()); } if (query.hasOwnProperty("queryRules")) { this.query.add("enablequeryrules", query.queryRules.toString()); } if (query.hasOwnProperty("prefixMatch")) { this.query.add("fprefixmatchallterms", query.prefixMatch.toString()); } }; return SearchSuggest; }(queryable_1.QueryableInstance)); exports.SearchSuggest = SearchSuggest; var SearchSuggestResult = (function () { function SearchSuggestResult(json) { if (json.hasOwnProperty("suggest")) { // verbose this.PeopleNames = json.suggest.PeopleNames.results; this.PersonalResults = json.suggest.PersonalResults.results; this.Queries = json.suggest.Queries.results; } else { this.PeopleNames = json.PeopleNames; this.PersonalResults = json.PersonalResults; this.Queries = json.Queries; } } return SearchSuggestResult; }()); exports.SearchSuggestResult = SearchSuggestResult; /***/ }), /* 29 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var queryable_1 = __webpack_require__(1); var webs_1 = __webpack_require__(8); var usercustomactions_1 = __webpack_require__(19); var odata_1 = __webpack_require__(2); var features_1 = __webpack_require__(23); /** * Describes a site collection * */ var Site = (function (_super) { __extends(Site, _super); /** * Creates a new instance of the Site class * * @param baseUrl The url or Queryable which forms the parent of this site collection */ function Site(baseUrl, path) { if (path === void 0) { path = "_api/site"; } return _super.call(this, baseUrl, path) || this; } Object.defineProperty(Site.prototype, "rootWeb", { /** * Gets the root web of the site collection * */ get: function () { return new webs_1.Web(this, "rootweb"); }, enumerable: true, configurable: true }); Object.defineProperty(Site.prototype, "features", { /** * Gets the active features for this site collection * */ get: function () { return new features_1.Features(this); }, enumerable: true, configurable: true }); Object.defineProperty(Site.prototype, "userCustomActions", { /** * Gets all custom actions for this site collection * */ get: function () { return new usercustomactions_1.UserCustomActions(this); }, enumerable: true, configurable: true }); /** * Gets the context information for this site collection */ Site.prototype.getContextInfo = function () { var q = new Site(this.parentUrl, "_api/contextinfo"); return q.post().then(function (data) { if (data.hasOwnProperty("GetContextWebInformation")) { var info = data.GetContextWebInformation; info.SupportedSchemaVersions = info.SupportedSchemaVersions.results; return info; } else { return data; } }); }; /** * Gets the document libraries on a site. Static method. (SharePoint Online only) * * @param absoluteWebUrl The absolute url of the web whose document libraries should be returned */ Site.prototype.getDocumentLibraries = function (absoluteWebUrl) { var q = new queryable_1.Queryable("", "_api/sp.web.getdocumentlibraries(@v)"); q.query.add("@v", "'" + absoluteWebUrl + "'"); return q.get().then(function (data) { if (data.hasOwnProperty("GetDocumentLibraries")) { return data.GetDocumentLibraries; } else { return data; } }); }; /** * Gets the site url from a page url * * @param absolutePageUrl The absolute url of the page */ Site.prototype.getWebUrlFromPageUrl = function (absolutePageUrl) { var q = new queryable_1.Queryable("", "_api/sp.web.getweburlfrompageurl(@v)"); q.query.add("@v", "'" + absolutePageUrl + "'"); return q.get().then(function (data) { if (data.hasOwnProperty("GetWebUrlFromPageUrl")) { return data.GetWebUrlFromPageUrl; } else { return data; } }); }; /** * Creates a new batch for requests within the context of this site collection * */ Site.prototype.createBatch = function () { return new odata_1.ODataBatch(this.parentUrl); }; /** * Opens a web by id (using POST) * * @param webId The GUID id of the web to open */ Site.prototype.openWebById = function (webId) { return this.clone(Site, "openWebById('" + webId + "')", true).post().then(function (d) { return { data: d, web: webs_1.Web.fromUrl(odata_1.extractOdataId(d)), }; }); }; return Site; }(queryable_1.QueryableInstance)); exports.Site = Site; /***/ }), /* 30 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var queryable_1 = __webpack_require__(1); var sitegroups_1 = __webpack_require__(18); var util_1 = __webpack_require__(0); /** * Describes a collection of all site collection users * */ var SiteUsers = (function (_super) { __extends(SiteUsers, _super); /** * Creates a new instance of the SiteUsers class * * @param baseUrl The url or Queryable which forms the parent of this user collection */ function SiteUsers(baseUrl, path) { if (path === void 0) { path = "siteusers"; } return _super.call(this, baseUrl, path) || this; } /** * Gets a user from the collection by email * * @param email The email address of the user to retrieve */ SiteUsers.prototype.getByEmail = function (email) { return new SiteUser(this, "getByEmail('" + email + "')"); }; /** * Gets a user from the collection by id * * @param id The id of the user to retrieve */ SiteUsers.prototype.getById = function (id) { return new SiteUser(this, "getById(" + id + ")"); }; /** * Gets a user from the collection by login name * * @param loginName The login name of the user to retrieve */ SiteUsers.prototype.getByLoginName = function (loginName) { var su = new SiteUser(this); su.concat("(@v)"); su.query.add("@v", "'" + encodeURIComponent(loginName) + "'"); return su; }; /** * Removes a user from the collection by id * * @param id The id of the user to remove */ SiteUsers.prototype.removeById = function (id) { return this.clone(SiteUsers, "removeById(" + id + ")", true).post(); }; /** * Removes a user from the collection by login name * * @param loginName The login name of the user to remove */ SiteUsers.prototype.removeByLoginName = function (loginName) { var o = this.clone(SiteUsers, "removeByLoginName(@v)", true); o.query.add("@v", "'" + encodeURIComponent(loginName) + "'"); return o.post(); }; /** * Adds a user to a group * * @param loginName The login name of the user to add to the group * */ SiteUsers.prototype.add = function (loginName) { var _this = this; return this.clone(SiteUsers, null, true).post({ body: JSON.stringify({ "__metadata": { "type": "SP.User" }, LoginName: loginName }), }).then(function () { return _this.getByLoginName(loginName); }); }; return SiteUsers; }(queryable_1.QueryableCollection)); exports.SiteUsers = SiteUsers; /** * Describes a single user * */ var SiteUser = (function (_super) { __extends(SiteUser, _super); function SiteUser() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(SiteUser.prototype, "groups", { /** * Gets the groups for this user * */ get: function () { return new sitegroups_1.SiteGroups(this, "groups"); }, enumerable: true, configurable: true }); /** * Updates this user instance with the supplied properties * * @param properties A plain object of property names and values to update for the user */ SiteUser.prototype.update = function (properties) { var _this = this; var postBody = util_1.Util.extend({ "__metadata": { "type": "SP.User" } }, properties); return this.post({ body: JSON.stringify(postBody), headers: { "X-HTTP-Method": "MERGE", }, }).then(function (data) { return { data: data, user: _this, }; }); }; /** * Delete this user * */ SiteUser.prototype.delete = function () { return this.post({ headers: { "X-HTTP-Method": "DELETE", }, }); }; return SiteUser; }(queryable_1.QueryableInstance)); exports.SiteUser = SiteUser; /** * Represents the current user */ var CurrentUser = (function (_super) { __extends(CurrentUser, _super); function CurrentUser(baseUrl, path) { if (path === void 0) { path = "currentuser"; } return _super.call(this, baseUrl, path) || this; } return CurrentUser; }(queryable_1.QueryableInstance)); exports.CurrentUser = CurrentUser; /***/ }), /* 31 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var queryable_1 = __webpack_require__(1); var util_1 = __webpack_require__(0); var files_1 = __webpack_require__(7); var odata_1 = __webpack_require__(2); /** * Allows for calling of the static SP.Utilities.Utility methods by supplying the method name */ var UtilityMethod = (function (_super) { __extends(UtilityMethod, _super); /** * Creates a new instance of the Utility method class * * @param baseUrl The parent url provider * @param methodName The static method name to call on the utility class */ function UtilityMethod(baseUrl, methodName) { return _super.call(this, UtilityMethod.getBaseUrl(baseUrl), "_api/SP.Utilities.Utility." + methodName) || this; } UtilityMethod.getBaseUrl = function (candidate) { if (typeof candidate === "string") { return candidate; } var c = candidate; var url = c.toUrl(); var index = url.indexOf("_api/"); if (index < 0) { return url; } return url.substr(0, index); }; UtilityMethod.prototype.excute = function (props) { return this.postAs({ body: JSON.stringify(props), }); }; /** * Clones this queryable into a new queryable instance of T * @param factory Constructor used to create the new instance * @param additionalPath Any additional path to include in the clone * @param includeBatch If true this instance's batch will be added to the cloned instance */ UtilityMethod.prototype.create = function (methodName, includeBatch) { var clone = new UtilityMethod(this.parentUrl, methodName); var target = this.query.get("@target"); if (target !== null) { clone.query.add("@target", target); } if (includeBatch && this.hasBatch) { clone = clone.inBatch(this.batch); } return clone; }; /** * Sends an email based on the supplied properties * * @param props The properties of the email to send */ UtilityMethod.prototype.sendEmail = function (props) { var params = { properties: { Body: props.Body, From: props.From, Subject: props.Subject, "__metadata": { "type": "SP.Utilities.EmailProperties" }, }, }; if (props.To && props.To.length > 0) { params.properties = util_1.Util.extend(params.properties, { To: { results: props.To }, }); } if (props.CC && props.CC.length > 0) { params.properties = util_1.Util.extend(params.properties, { CC: { results: props.CC }, }); } if (props.BCC && props.BCC.length > 0) { params.properties = util_1.Util.extend(params.properties, { BCC: { results: props.BCC }, }); } if (props.AdditionalHeaders) { params.properties = util_1.Util.extend(params.properties, { AdditionalHeaders: props.AdditionalHeaders, }); } return this.create("SendEmail", true).excute(params); }; UtilityMethod.prototype.getCurrentUserEmailAddresses = function () { return this.create("GetCurrentUserEmailAddresses", true).excute({}); }; UtilityMethod.prototype.resolvePrincipal = function (input, scopes, sources, inputIsEmailOnly, addToUserInfoList, matchUserInfoList) { if (matchUserInfoList === void 0) { matchUserInfoList = false; } var params = { addToUserInfoList: addToUserInfoList, input: input, inputIsEmailOnly: inputIsEmailOnly, matchUserInfoList: matchUserInfoList, scopes: scopes, sources: sources, }; return this.create("ResolvePrincipalInCurrentContext", true).excute(params); }; UtilityMethod.prototype.searchPrincipals = function (input, scopes, sources, groupName, maxCount) { var params = { groupName: groupName, input: input, maxCount: maxCount, scopes: scopes, sources: sources, }; return this.create("SearchPrincipalsUsingContextWeb", true).excute(params); }; UtilityMethod.prototype.createEmailBodyForInvitation = function (pageAddress) { var params = { pageAddress: pageAddress, }; return this.create("CreateEmailBodyForInvitation", true).excute(params); }; UtilityMethod.prototype.expandGroupsToPrincipals = function (inputs, maxCount) { if (maxCount === void 0) { maxCount = 30; } var params = { inputs: inputs, maxCount: maxCount, }; return this.create("ExpandGroupsToPrincipals", true).excute(params); }; UtilityMethod.prototype.createWikiPage = function (info) { return this.create("CreateWikiPageInContextWeb", true).excute({ parameters: info, }).then(function (r) { return { data: r, file: new files_1.File(odata_1.extractOdataId(r)), }; }); }; return UtilityMethod; }(queryable_1.Queryable)); exports.UtilityMethod = UtilityMethod; /***/ }), /* 32 */ /***/ (function(module, exports) { var g; // This works in non-strict mode g = (function() { return this; })(); try { // This works if eval is allowed (see CSP) g = g || Function("return this")() || (1,eval)("this"); } catch(e) { // This works if the window reference is available if(typeof window === "object") g = window; } // g can still be undefined, but nothing to do about it... // We return undefined, instead of nothing here, so it's // easier to handle this case. if(!global) { ...} module.exports = g; /***/ }), /* 33 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var collections_1 = __webpack_require__(6); /** * Class used to manage the current application settings * */ var Settings = (function () { /** * Creates a new instance of the settings class * * @constructor */ function Settings() { this._settings = new collections_1.Dictionary(); } /** * Adds a new single setting, or overwrites a previous setting with the same key * * @param {string} key The key used to store this setting * @param {string} value The setting value to store */ Settings.prototype.add = function (key, value) { this._settings.add(key, value); }; /** * Adds a JSON value to the collection as a string, you must use getJSON to rehydrate the object when read * * @param {string} key The key used to store this setting * @param {any} value The setting value to store */ Settings.prototype.addJSON = function (key, value) { this._settings.add(key, JSON.stringify(value)); }; /** * Applies the supplied hash to the setting collection overwriting any existing value, or created new values * * @param {TypedHash<any>} hash The set of values to add */ Settings.prototype.apply = function (hash) { var _this = this; return new Promise(function (resolve, reject) { try { _this._settings.merge(hash); resolve(); } catch (e) { reject(e); } }); }; /** * Loads configuration settings into the collection from the supplied provider and returns a Promise * * @param {IConfigurationProvider} provider The provider from which we will load the settings */ Settings.prototype.load = function (provider) { var _this = this; return new Promise(function (resolve, reject) { provider.getConfiguration().then(function (value) { _this._settings.merge(value); resolve(); }).catch(function (reason) { reject(reason); }); }); }; /** * Gets a value from the configuration * * @param {string} key The key whose value we want to return. Returns null if the key does not exist * @return {string} string value from the configuration */ Settings.prototype.get = function (key) { return this._settings.get(key); }; /** * Gets a JSON value, rehydrating the stored string to the original object * * @param {string} key The key whose value we want to return. Returns null if the key does not exist * @return {any} object from the configuration */ Settings.prototype.getJSON = function (key) { var o = this.get(key); if (typeof o === "undefined" || o === null) { return o; } return JSON.parse(o); }; return Settings; }()); exports.Settings = Settings; /***/ }), /* 34 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var search_1 = __webpack_require__(27); var searchsuggest_1 = __webpack_require__(28); var site_1 = __webpack_require__(29); var webs_1 = __webpack_require__(8); var util_1 = __webpack_require__(0); var userprofiles_1 = __webpack_require__(48); var exceptions_1 = __webpack_require__(3); var utilities_1 = __webpack_require__(31); /** * Root of the SharePoint REST module */ var SPRest = (function () { function SPRest() { } /** * Executes a search against this web context * * @param query The SearchQuery definition */ SPRest.prototype.searchSuggest = function (query) { var finalQuery; if (typeof query === "string") { finalQuery = { querytext: query }; } else { finalQuery = query; } return new searchsuggest_1.SearchSuggest("").execute(finalQuery); }; /** * Executes a search against this web context * * @param query The SearchQuery definition */ SPRest.prototype.search = function (query) { var finalQuery; if (typeof query === "string") { finalQuery = { Querytext: query }; } else if (query instanceof search_1.SearchQueryBuilder) { finalQuery = query.toSearchQuery(); } else { finalQuery = query; } return new search_1.Search("").execute(finalQuery); }; Object.defineProperty(SPRest.prototype, "site", { /** * Begins a site collection scoped REST request * */ get: function () { return new site_1.Site(""); }, enumerable: true, configurable: true }); Object.defineProperty(SPRest.prototype, "web", { /** * Begins a web scoped REST request * */ get: function () { return new webs_1.Web(""); }, enumerable: true, configurable: true }); Object.defineProperty(SPRest.prototype, "profiles", { /** * Access to user profile methods * */ get: function () { return new userprofiles_1.UserProfileQuery(""); }, enumerable: true, configurable: true }); /** * Creates a new batch object for use with the Queryable.addToBatch method * */ SPRest.prototype.createBatch = function () { return this.web.createBatch(); }; Object.defineProperty(SPRest.prototype, "utility", { /** * Static utilities methods from SP.Utilities.Utility */ get: function () { return new utilities_1.UtilityMethod("", ""); }, enumerable: true, configurable: true }); /** * Begins a cross-domain, host site scoped REST request, for use in add-in webs * * @param addInWebUrl The absolute url of the add-in web * @param hostWebUrl The absolute url of the host web */ SPRest.prototype.crossDomainSite = function (addInWebUrl, hostWebUrl) { return this._cdImpl(site_1.Site, addInWebUrl, hostWebUrl, "site"); }; /** * Begins a cross-domain, host web scoped REST request, for use in add-in webs * * @param addInWebUrl The absolute url of the add-in web * @param hostWebUrl The absolute url of the host web */ SPRest.prototype.crossDomainWeb = function (addInWebUrl, hostWebUrl) { return this._cdImpl(webs_1.Web, addInWebUrl, hostWebUrl, "web"); }; /** * Implements the creation of cross domain REST urls * * @param factory The constructor of the object to create Site | Web * @param addInWebUrl The absolute url of the add-in web * @param hostWebUrl The absolute url of the host web * @param urlPart String part to append to the url "site" | "web" */ SPRest.prototype._cdImpl = function (factory, addInWebUrl, hostWebUrl, urlPart) { if (!util_1.Util.isUrlAbsolute(addInWebUrl)) { throw new exceptions_1.UrlException("The addInWebUrl parameter must be an absolute url."); } if (!util_1.Util.isUrlAbsolute(hostWebUrl)) { throw new exceptions_1.UrlException("The hostWebUrl parameter must be an absolute url."); } var url = util_1.Util.combinePaths(addInWebUrl, "_api/SP.AppContextSite(@target)"); var instance = new factory(url, urlPart); instance.query.add("@target", "'" + encodeURIComponent(hostWebUrl) + "'"); return instance; }; return SPRest; }()); exports.SPRest = SPRest; /***/ }), /* 35 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; function __export(m) { for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; } Object.defineProperty(exports, "__esModule", { value: true }); __export(__webpack_require__(44)); var httpclient_1 = __webpack_require__(15); exports.HttpClient = httpclient_1.HttpClient; var sprequestexecutorclient_1 = __webpack_require__(40); exports.SPRequestExecutorClient = sprequestexecutorclient_1.SPRequestExecutorClient; var nodefetchclient_1 = __webpack_require__(39); exports.NodeFetchClient = nodefetchclient_1.NodeFetchClient; var fetchclient_1 = __webpack_require__(21); exports.FetchClient = fetchclient_1.FetchClient; __export(__webpack_require__(36)); var collections_1 = __webpack_require__(6); exports.Dictionary = collections_1.Dictionary; var util_1 = __webpack_require__(0); exports.Util = util_1.Util; __export(__webpack_require__(5)); __export(__webpack_require__(3)); /***/ }), /* 36 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var cachingConfigurationProvider_1 = __webpack_require__(20); exports.CachingConfigurationProvider = cachingConfigurationProvider_1.default; var spListConfigurationProvider_1 = __webpack_require__(37); exports.SPListConfigurationProvider = spListConfigurationProvider_1.default; /***/ }), /* 37 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var cachingConfigurationProvider_1 = __webpack_require__(20); /** * A configuration provider which loads configuration values from a SharePoint list * */ var SPListConfigurationProvider = (function () { /** * Creates a new SharePoint list based configuration provider * @constructor * @param {string} webUrl Url of the SharePoint site, where the configuration list is located * @param {string} listTitle Title of the SharePoint list, which contains the configuration settings (optional, default = "config") */ function SPListConfigurationProvider(sourceWeb, sourceListTitle) { if (sourceListTitle === void 0) { sourceListTitle = "config"; } this.sourceWeb = sourceWeb; this.sourceListTitle = sourceListTitle; } Object.defineProperty(SPListConfigurationProvider.prototype, "web", { /** * Gets the url of the SharePoint site, where the configuration list is located * * @return {string} Url address of the site */ get: function () { return this.sourceWeb; }, enumerable: true, configurable: true }); Object.defineProperty(SPListConfigurationProvider.prototype, "listTitle", { /** * Gets the title of the SharePoint list, which contains the configuration settings * * @return {string} List title */ get: function () { return this.sourceListTitle; }, enumerable: true, configurable: true }); /** * Loads the configuration values from the SharePoint list * * @return {Promise<TypedHash<string>>} Promise of loaded configuration values */ SPListConfigurationProvider.prototype.getConfiguration = function () { return this.web.lists.getByTitle(this.listTitle).items.select("Title", "Value") .getAs().then(function (data) { return data.reduce(function (configuration, item) { return Object.defineProperty(configuration, item.Title, { configurable: false, enumerable: false, value: item.Value, writable: false, }); }, {}); }); }; /** * Wraps the current provider in a cache enabled provider * * @return {CachingConfigurationProvider} Caching providers which wraps the current provider */ SPListConfigurationProvider.prototype.asCaching = function () { var cacheKey = "splist_" + this.web.toUrl() + "+" + this.listTitle; return new cachingConfigurationProvider_1.default(this, cacheKey); }; return SPListConfigurationProvider; }()); exports.default = SPListConfigurationProvider; /***/ }), /* 38 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var collections_1 = __webpack_require__(6); var util_1 = __webpack_require__(0); var odata_1 = __webpack_require__(2); var CachedDigest = (function () { function CachedDigest() { } return CachedDigest; }()); exports.CachedDigest = CachedDigest; // allows for the caching of digests across all HttpClient's which each have their own DigestCache wrapper. var digests = new collections_1.Dictionary(); var DigestCache = (function () { function DigestCache(_httpClient, _digests) { if (_digests === void 0) { _digests = digests; } this._httpClient = _httpClient; this._digests = _digests; } DigestCache.prototype.getDigest = function (webUrl) { var _this = this; var cachedDigest = this._digests.get(webUrl); if (cachedDigest !== null) { var now = new Date(); if (now < cachedDigest.expiration) { return Promise.resolve(cachedDigest.value); } } var url = util_1.Util.combinePaths(webUrl, "/_api/contextinfo"); return this._httpClient.fetchRaw(url, { cache: "no-cache", credentials: "same-origin", headers: { "Accept": "application/json;odata=verbose", "Content-type": "application/json;odata=verbose;charset=utf-8", }, method: "POST", }).then(function (response) { var parser = new odata_1.ODataDefaultParser(); return parser.parse(response).then(function (d) { return d.GetContextWebInformation; }); }).then(function (data) { var newCachedDigest = new CachedDigest(); newCachedDigest.value = data.FormDigestValue; var seconds = data.FormDigestTimeoutSeconds; var expiration = new Date(); expiration.setTime(expiration.getTime() + 1000 * seconds); newCachedDigest.expiration = expiration; _this._digests.add(webUrl, newCachedDigest); return newCachedDigest.value; }); }; DigestCache.prototype.clear = function () { this._digests.clear(); }; return DigestCache; }()); exports.DigestCache = DigestCache; /***/ }), /* 39 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var exceptions_1 = __webpack_require__(3); /** * This module is substituted for the NodeFetchClient.ts during the packaging process. This helps to reduce the pnp.js file size by * not including all of the node dependencies */ var NodeFetchClient = (function () { function NodeFetchClient() { } /** * Always throws an error that NodeFetchClient is not supported for use in the browser */ NodeFetchClient.prototype.fetch = function () { throw new exceptions_1.NodeFetchClientUnsupportedException(); }; return NodeFetchClient; }()); exports.NodeFetchClient = NodeFetchClient; /***/ }), /* 40 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var util_1 = __webpack_require__(0); var exceptions_1 = __webpack_require__(3); /** * Makes requests using the SP.RequestExecutor library. */ var SPRequestExecutorClient = (function () { function SPRequestExecutorClient() { /** * Converts a SharePoint REST API response to a fetch API response. */ this.convertToResponse = function (spResponse) { var responseHeaders = new Headers(); for (var h in spResponse.headers) { if (spResponse.headers[h]) { responseHeaders.append(h, spResponse.headers[h]); } } // issue #256, Cannot have an empty string body when creating a Response with status 204 var body = spResponse.statusCode === 204 ? null : spResponse.body; return new Response(body, { headers: responseHeaders, status: spResponse.statusCode, statusText: spResponse.statusText, }); }; } /** * Fetches a URL using the SP.RequestExecutor library. */ SPRequestExecutorClient.prototype.fetch = function (url, options) { var _this = this; if (typeof SP === "undefined" || typeof SP.RequestExecutor === "undefined") { throw new exceptions_1.SPRequestExecutorUndefinedException(); } var addinWebUrl = url.substring(0, url.indexOf("/_api")), executor = new SP.RequestExecutor(addinWebUrl); var headers = {}, iterator, temp; if (options.headers && options.headers instanceof Headers) { iterator = options.headers.entries(); temp = iterator.next(); while (!temp.done) { headers[temp.value[0]] = temp.value[1]; temp = iterator.next(); } } else { headers = options.headers; } return new Promise(function (resolve, reject) { var requestOptions = { error: function (error) { reject(_this.convertToResponse(error)); }, headers: headers, method: options.method, success: function (response) { resolve(_this.convertToResponse(response)); }, url: url, }; if (options.body) { requestOptions = util_1.Util.extend(requestOptions, { body: options.body }); } else { requestOptions = util_1.Util.extend(requestOptions, { binaryStringRequestBody: true }); } executor.executeAsync(requestOptions); }); }; return SPRequestExecutorClient; }()); exports.SPRequestExecutorClient = SPRequestExecutorClient; /***/ }), /* 41 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; function __export(m) { for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; } Object.defineProperty(exports, "__esModule", { value: true }); var util_1 = __webpack_require__(0); var storage_1 = __webpack_require__(14); var configuration_1 = __webpack_require__(33); var logging_1 = __webpack_require__(5); var rest_1 = __webpack_require__(34); var pnplibconfig_1 = __webpack_require__(4); /** * Root class of the Patterns and Practices namespace, provides an entry point to the library */ /** * Utility methods */ exports.util = util_1.Util; /** * Provides access to the REST interface */ exports.sp = new rest_1.SPRest(); /** * Provides access to local and session storage */ exports.storage = new storage_1.PnPClientStorage(); /** * Global configuration instance to which providers can be added */ exports.config = new configuration_1.Settings(); /** * Global logging instance to which subscribers can be registered and messages written */ exports.log = logging_1.Logger; /** * Allows for the configuration of the library */ exports.setup = pnplibconfig_1.setRuntimeConfig; /** * Expose a subset of classes from the library for public consumption */ __export(__webpack_require__(35)); // creating this class instead of directly assigning to default fixes issue #116 var Def = { /** * Global configuration instance to which providers can be added */ config: exports.config, /** * Global logging instance to which subscribers can be registered and messages written */ log: exports.log, /** * Provides access to local and session storage */ setup: exports.setup, /** * Provides access to the REST interface */ sp: exports.sp, /** * Provides access to local and session storage */ storage: exports.storage, /** * Utility methods */ util: exports.util, }; /** * Enables use of the import pnp from syntax */ exports.default = Def; /***/ }), /* 42 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var queryable_1 = __webpack_require__(1); var odata_1 = __webpack_require__(2); /** * Describes a collection of Item objects * */ var AttachmentFiles = (function (_super) { __extends(AttachmentFiles, _super); /** * Creates a new instance of the AttachmentFiles class * * @param baseUrl The url or Queryable which forms the parent of this attachments collection */ function AttachmentFiles(baseUrl, path) { if (path === void 0) { path = "AttachmentFiles"; } return _super.call(this, baseUrl, path) || this; } /** * Gets a Attachment File by filename * * @param name The name of the file, including extension. */ AttachmentFiles.prototype.getByName = function (name) { var f = new AttachmentFile(this); f.concat("('" + name + "')"); return f; }; /** * Adds a new attachment to the collection. Not supported for batching. * * @param name The name of the file, including extension. * @param content The Base64 file content. */ AttachmentFiles.prototype.add = function (name, content) { var _this = this; return this.clone(AttachmentFiles, "add(FileName='" + name + "')").post({ body: content, }).then(function (response) { return { data: response, file: _this.getByName(name), }; }); }; /** * Adds mjultiple new attachment to the collection. Not supported for batching. * * @files name The collection of files to add */ AttachmentFiles.prototype.addMultiple = function (files) { var _this = this; // add the files in series so we don't get update conflicts return files.reduce(function (chain, file) { return chain.then(function () { return _this.clone(AttachmentFiles, "add(FileName='" + file.name + "')").post({ body: file.content, }); }); }, Promise.resolve()); }; return AttachmentFiles; }(queryable_1.QueryableCollection)); exports.AttachmentFiles = AttachmentFiles; /** * Describes a single attachment file instance * */ var AttachmentFile = (function (_super) { __extends(AttachmentFile, _super); function AttachmentFile() { return _super !== null && _super.apply(this, arguments) || this; } /** * Gets the contents of the file as text * */ AttachmentFile.prototype.getText = function () { return this.clone(AttachmentFile, "$value").get(new odata_1.TextFileParser()); }; /** * Gets the contents of the file as a blob, does not work in Node.js * */ AttachmentFile.prototype.getBlob = function () { return this.clone(AttachmentFile, "$value").get(new odata_1.BlobFileParser()); }; /** * Gets the contents of a file as an ArrayBuffer, works in Node.js */ AttachmentFile.prototype.getBuffer = function () { return this.clone(AttachmentFile, "$value").get(new odata_1.BufferFileParser()); }; /** * Gets the contents of a file as an ArrayBuffer, works in Node.js */ AttachmentFile.prototype.getJSON = function () { return this.clone(AttachmentFile, "$value").get(new odata_1.JSONFileParser()); }; /** * Sets the content of a file. Not supported for batching * * @param content The value to set for the file contents */ AttachmentFile.prototype.setContent = function (content) { var _this = this; return this.clone(AttachmentFile, "$value").post({ body: content, headers: { "X-HTTP-Method": "PUT", }, }).then(function (_) { return new AttachmentFile(_this); }); }; /** * Delete this attachment file * * @param eTag Value used in the IF-Match header, by default "*" */ AttachmentFile.prototype.delete = function (eTag) { if (eTag === void 0) { eTag = "*"; } return this.post({ headers: { "IF-Match": eTag, "X-HTTP-Method": "DELETE", }, }); }; return AttachmentFile; }(queryable_1.QueryableInstance)); exports.AttachmentFile = AttachmentFile; /***/ }), /* 43 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var queryable_1 = __webpack_require__(1); /** * Describes a collection of Field objects * */ var Forms = (function (_super) { __extends(Forms, _super); /** * Creates a new instance of the Fields class * * @param baseUrl The url or Queryable which forms the parent of this fields collection */ function Forms(baseUrl, path) { if (path === void 0) { path = "forms"; } return _super.call(this, baseUrl, path) || this; } /** * Gets a form by id * * @param id The guid id of the item to retrieve */ Forms.prototype.getById = function (id) { var i = new Form(this); i.concat("('" + id + "')"); return i; }; return Forms; }(queryable_1.QueryableCollection)); exports.Forms = Forms; /** * Describes a single of Form instance * */ var Form = (function (_super) { __extends(Form, _super); function Form() { return _super !== null && _super.apply(this, arguments) || this; } return Form; }(queryable_1.QueryableInstance)); exports.Form = Form; /***/ }), /* 44 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; function __export(m) { for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; } Object.defineProperty(exports, "__esModule", { value: true }); __export(__webpack_require__(22)); var files_1 = __webpack_require__(7); exports.CheckinType = files_1.CheckinType; exports.WebPartsPersonalizationScope = files_1.WebPartsPersonalizationScope; exports.MoveOperations = files_1.MoveOperations; exports.TemplateFileType = files_1.TemplateFileType; var folders_1 = __webpack_require__(9); exports.Folder = folders_1.Folder; exports.Folders = folders_1.Folders; var items_1 = __webpack_require__(10); exports.Item = items_1.Item; exports.Items = items_1.Items; exports.PagedItemCollection = items_1.PagedItemCollection; var navigation_1 = __webpack_require__(25); exports.NavigationNodes = navigation_1.NavigationNodes; exports.NavigationNode = navigation_1.NavigationNode; var lists_1 = __webpack_require__(11); exports.List = lists_1.List; exports.Lists = lists_1.Lists; var odata_1 = __webpack_require__(2); exports.extractOdataId = odata_1.extractOdataId; exports.ODataParserBase = odata_1.ODataParserBase; exports.ODataDefaultParser = odata_1.ODataDefaultParser; exports.ODataRaw = odata_1.ODataRaw; exports.ODataValue = odata_1.ODataValue; exports.ODataEntity = odata_1.ODataEntity; exports.ODataEntityArray = odata_1.ODataEntityArray; exports.TextFileParser = odata_1.TextFileParser; exports.BlobFileParser = odata_1.BlobFileParser; exports.BufferFileParser = odata_1.BufferFileParser; exports.JSONFileParser = odata_1.JSONFileParser; var queryable_1 = __webpack_require__(1); exports.Queryable = queryable_1.Queryable; exports.QueryableInstance = queryable_1.QueryableInstance; exports.QueryableCollection = queryable_1.QueryableCollection; var roles_1 = __webpack_require__(17); exports.RoleDefinitionBindings = roles_1.RoleDefinitionBindings; var search_1 = __webpack_require__(27); exports.Search = search_1.Search; exports.SearchQueryBuilder = search_1.SearchQueryBuilder; exports.SearchResults = search_1.SearchResults; exports.SortDirection = search_1.SortDirection; exports.ReorderingRuleMatchType = search_1.ReorderingRuleMatchType; exports.QueryPropertyValueType = search_1.QueryPropertyValueType; exports.SearchBuiltInSourceId = search_1.SearchBuiltInSourceId; var searchsuggest_1 = __webpack_require__(28); exports.SearchSuggest = searchsuggest_1.SearchSuggest; exports.SearchSuggestResult = searchsuggest_1.SearchSuggestResult; var site_1 = __webpack_require__(29); exports.Site = site_1.Site; __export(__webpack_require__(13)); var utilities_1 = __webpack_require__(31); exports.UtilityMethod = utilities_1.UtilityMethod; var webs_1 = __webpack_require__(8); exports.Web = webs_1.Web; /***/ }), /* 45 */ /***/ (function(module, exports, __webpack_require__) { "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; }; Object.defineProperty(exports, "__esModule", { value: true }); var caching_1 = __webpack_require__(22); var httpclient_1 = __webpack_require__(15); var logging_1 = __webpack_require__(5); var util_1 = __webpack_require__(0); /** * Resolves the context's result value * * @param context The current context */ function returnResult(context) { logging_1.Logger.log({ data: context.result, level: logging_1.LogLevel.Verbose, message: "[" + context.requestId + "] (" + (new Date()).getTime() + ") Returning result, see data property for value.", }); return Promise.resolve(context.result); } /** * Sets the result on the context */ function setResult(context, value) { return new Promise(function (resolve) { context.result = value; context.hasResult = true; resolve(context); }); } exports.setResult = setResult; /** * Invokes the next method in the provided context's pipeline * * @param c The current request context */ function next(c) { if (c.pipeline.length < 1) { return Promise.resolve(c); } return c.pipeline.shift()(c); } /** * Executes the current request context's pipeline * * @param context Current context */ function pipe(context) { return next(context) .then(function (ctx) { return returnResult(ctx); }) .catch(function (e) { logging_1.Logger.log({ data: e, level: logging_1.LogLevel.Error, message: "Error in request pipeline: " + e.message, }); throw e; }); } exports.pipe = pipe; /** * decorator factory applied to methods in the pipeline to control behavior */ function requestPipelineMethod(alwaysRun) { if (alwaysRun === void 0) { alwaysRun = false; } return function (target, propertyKey, descriptor) { var method = descriptor.value; descriptor.value = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } // if we have a result already in the pipeline, pass it along and don't call the tagged method if (!alwaysRun && args.length > 0 && args[0].hasOwnProperty("hasResult") && args[0].hasResult) { logging_1.Logger.write("[" + args[0].requestId + "] (" + (new Date()).getTime() + ") Skipping request pipeline method " + propertyKey + ", existing result in pipeline.", logging_1.LogLevel.Verbose); return Promise.resolve(args[0]); } // apply the tagged method logging_1.Logger.write("[" + args[0].requestId + "] (" + (new Date()).getTime() + ") Calling request pipeline method " + propertyKey + ".", logging_1.LogLevel.Verbose); // then chain the next method in the context's pipeline - allows for dynamic pipeline return method.apply(target, args).then(function (ctx) { return next(ctx); }); }; }; } exports.requestPipelineMethod = requestPipelineMethod; /** * Contains the methods used within the request pipeline */ var PipelineMethods = (function () { function PipelineMethods() { } /** * Logs the start of the request */ PipelineMethods.logStart = function (context) { return new Promise(function (resolve) { logging_1.Logger.log({ data: logging_1.Logger.activeLogLevel === logging_1.LogLevel.Info ? {} : context, level: logging_1.LogLevel.Info, message: "[" + context.requestId + "] (" + (new Date()).getTime() + ") Beginning " + context.verb + " request (" + context.requestAbsoluteUrl + ")", }); resolve(context); }); }; /** * Handles caching of the request */ PipelineMethods.caching = function (context) { return new Promise(function (resolve) { // handle caching, if applicable if (context.verb === "GET" && context.isCached) { logging_1.Logger.write("[" + context.requestId + "] (" + (new Date()).getTime() + ") Caching is enabled for request, checking cache...", logging_1.LogLevel.Info); var cacheOptions = new caching_1.CachingOptions(context.requestAbsoluteUrl.toLowerCase()); if (typeof context.cachingOptions !== "undefined") { cacheOptions = util_1.Util.extend(cacheOptions, context.cachingOptions); } // we may not have a valid store if (cacheOptions.store !== null) { // check if we have the data in cache and if so resolve the promise and return var data = cacheOptions.store.get(cacheOptions.key); if (data !== null) { // ensure we clear any help batch dependency we are resolving from the cache logging_1.Logger.log({ data: logging_1.Logger.activeLogLevel === logging_1.LogLevel.Info ? {} : data, level: logging_1.LogLevel.Info, message: "[" + context.requestId + "] (" + (new Date()).getTime() + ") Value returned from cache.", }); context.batchDependency(); return setResult(context, data).then(function (ctx) { return resolve(ctx); }); } } logging_1.Logger.write("[" + context.requestId + "] (" + (new Date()).getTime() + ") Value not found in cache.", logging_1.LogLevel.Info); // if we don't then wrap the supplied parser in the caching parser wrapper // and send things on their way context.parser = new caching_1.CachingParserWrapper(context.parser, cacheOptions); } return resolve(context); }); }; /** * Sends the request */ PipelineMethods.send = function (context) { return new Promise(function (resolve, reject) { // send or batch the request if (context.isBatched) { // we are in a batch, so add to batch, remove dependency, and resolve with the batch's promise var p = context.batch.add(context.requestAbsoluteUrl, context.verb, context.options, context.parser); // we release the dependency here to ensure the batch does not execute until the request is added to the batch context.batchDependency(); logging_1.Logger.write("[" + context.requestId + "] (" + (new Date()).getTime() + ") Batching request in batch " + context.batch.batchId + ".", logging_1.LogLevel.Info); // we set the result as the promise which will be resolved by the batch's execution resolve(setResult(context, p)); } else { logging_1.Logger.write("[" + context.requestId + "] (" + (new Date()).getTime() + ") Sending request.", logging_1.LogLevel.Info); // we are not part of a batch, so proceed as normal var client = new httpclient_1.HttpClient(); var opts = util_1.Util.extend(context.options || {}, { method: context.verb }); client.fetch(context.requestAbsoluteUrl, opts) .then(function (response) { return context.parser.parse(response); }) .then(function (result) { return setResult(context, result); }) .then(function (ctx) { return resolve(ctx); }) .catch(function (e) { return reject(e); }); } }); }; /** * Logs the end of the request */ PipelineMethods.logEnd = function (context) { return new Promise(function (resolve) { if (context.isBatched) { logging_1.Logger.log({ data: logging_1.Logger.activeLogLevel === logging_1.LogLevel.Info ? {} : context, level: logging_1.LogLevel.Info, message: "[" + context.requestId + "] (" + (new Date()).getTime() + ") " + context.verb + " request will complete in batch " + context.batch.batchId + ".", }); } else { logging_1.Logger.log({ data: logging_1.Logger.activeLogLevel === logging_1.LogLevel.Info ? {} : context, level: logging_1.LogLevel.Info, message: "[" + context.requestId + "] (" + (new Date()).getTime() + ") Completing " + context.verb + " request.", }); } resolve(context); }); }; Object.defineProperty(PipelineMethods, "default", { get: function () { return [ PipelineMethods.logStart, PipelineMethods.caching, PipelineMethods.send, PipelineMethods.logEnd, ]; }, enumerable: true, configurable: true }); return PipelineMethods; }()); __decorate([ requestPipelineMethod(true) ], PipelineMethods, "logStart", null); __decorate([ requestPipelineMethod() ], PipelineMethods, "caching", null); __decorate([ requestPipelineMethod() ], PipelineMethods, "send", null); __decorate([ requestPipelineMethod(true) ], PipelineMethods, "logEnd", null); exports.PipelineMethods = PipelineMethods; /***/ }), /* 46 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var queryable_1 = __webpack_require__(1); var RelatedItemManagerImpl = (function (_super) { __extends(RelatedItemManagerImpl, _super); function RelatedItemManagerImpl(baseUrl, path) { if (path === void 0) { path = "_api/SP.RelatedItemManager"; } return _super.call(this, baseUrl, path) || this; } RelatedItemManagerImpl.FromUrl = function (url) { if (url === null) { return new RelatedItemManagerImpl(""); } var index = url.indexOf("_api/"); if (index > -1) { return new RelatedItemManagerImpl(url.substr(0, index)); } return new RelatedItemManagerImpl(url); }; RelatedItemManagerImpl.prototype.getRelatedItems = function (sourceListName, sourceItemId) { var query = this.clone(RelatedItemManagerImpl, null, true); query.concat(".GetRelatedItems"); return query.post({ body: JSON.stringify({ SourceItemID: sourceItemId, SourceListName: sourceListName, }), }); }; RelatedItemManagerImpl.prototype.getPageOneRelatedItems = function (sourceListName, sourceItemId) { var query = this.clone(RelatedItemManagerImpl, null, true); query.concat(".GetPageOneRelatedItems"); return query.post({ body: JSON.stringify({ SourceItemID: sourceItemId, SourceListName: sourceListName, }), }); }; RelatedItemManagerImpl.prototype.addSingleLink = function (sourceListName, sourceItemId, sourceWebUrl, targetListName, targetItemID, targetWebUrl, tryAddReverseLink) { if (tryAddReverseLink === void 0) { tryAddReverseLink = false; } var query = this.clone(RelatedItemManagerImpl, null, true); query.concat(".AddSingleLink"); return query.post({ body: JSON.stringify({ SourceItemID: sourceItemId, SourceListName: sourceListName, SourceWebUrl: sourceWebUrl, TargetItemID: targetItemID, TargetListName: targetListName, TargetWebUrl: targetWebUrl, TryAddReverseLink: tryAddReverseLink, }), }); }; /** * Adds a related item link from an item specified by list name and item id, to an item specified by url * * @param sourceListName The source list name or list id * @param sourceItemId The source item id * @param targetItemUrl The target item url * @param tryAddReverseLink If set to true try to add the reverse link (will not return error if it fails) */ RelatedItemManagerImpl.prototype.addSingleLinkToUrl = function (sourceListName, sourceItemId, targetItemUrl, tryAddReverseLink) { if (tryAddReverseLink === void 0) { tryAddReverseLink = false; } var query = this.clone(RelatedItemManagerImpl, null, true); query.concat(".AddSingleLinkToUrl"); return query.post({ body: JSON.stringify({ SourceItemID: sourceItemId, SourceListName: sourceListName, TargetItemUrl: targetItemUrl, TryAddReverseLink: tryAddReverseLink, }), }); }; /** * Adds a related item link from an item specified by url, to an item specified by list name and item id * * @param sourceItemUrl The source item url * @param targetListName The target list name or list id * @param targetItemId The target item id * @param tryAddReverseLink If set to true try to add the reverse link (will not return error if it fails) */ RelatedItemManagerImpl.prototype.addSingleLinkFromUrl = function (sourceItemUrl, targetListName, targetItemId, tryAddReverseLink) { if (tryAddReverseLink === void 0) { tryAddReverseLink = false; } var query = this.clone(RelatedItemManagerImpl, null, true); query.concat(".AddSingleLinkFromUrl"); return query.post({ body: JSON.stringify({ SourceItemUrl: sourceItemUrl, TargetItemID: targetItemId, TargetListName: targetListName, TryAddReverseLink: tryAddReverseLink, }), }); }; RelatedItemManagerImpl.prototype.deleteSingleLink = function (sourceListName, sourceItemId, sourceWebUrl, targetListName, targetItemId, targetWebUrl, tryDeleteReverseLink) { if (tryDeleteReverseLink === void 0) { tryDeleteReverseLink = false; } var query = this.clone(RelatedItemManagerImpl, null, true); query.concat(".DeleteSingleLink"); return query.post({ body: JSON.stringify({ SourceItemID: sourceItemId, SourceListName: sourceListName, SourceWebUrl: sourceWebUrl, TargetItemID: targetItemId, TargetListName: targetListName, TargetWebUrl: targetWebUrl, TryDeleteReverseLink: tryDeleteReverseLink, }), }); }; return RelatedItemManagerImpl; }(queryable_1.Queryable)); exports.RelatedItemManagerImpl = RelatedItemManagerImpl; /***/ }), /* 47 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var queryable_1 = __webpack_require__(1); /** * Describes a collection of webhook subscriptions * */ var Subscriptions = (function (_super) { __extends(Subscriptions, _super); /** * Creates a new instance of the Subscriptions class * * @param baseUrl - The url or Queryable which forms the parent of this webhook subscriptions collection */ function Subscriptions(baseUrl, path) { if (path === void 0) { path = "subscriptions"; } return _super.call(this, baseUrl, path) || this; } /** * Returns all the webhook subscriptions or the specified webhook subscription * * @param subscriptionId The id of a specific webhook subscription to retrieve, omit to retrieve all the webhook subscriptions */ Subscriptions.prototype.getById = function (subscriptionId) { var subscription = new Subscription(this); subscription.concat("('" + subscriptionId + "')"); return subscription; }; /** * Creates a new webhook subscription * * @param notificationUrl The url to receive the notifications * @param expirationDate The date and time to expire the subscription in the form YYYY-MM-ddTHH:mm:ss+00:00 (maximum of 6 months) * @param clientState A client specific string (defaults to pnp-js-core-subscription when omitted) */ Subscriptions.prototype.add = function (notificationUrl, expirationDate, clientState) { var _this = this; var postBody = JSON.stringify({ "clientState": clientState || "pnp-js-core-subscription", "expirationDateTime": expirationDate, "notificationUrl": notificationUrl, "resource": this.toUrl(), }); return this.post({ body: postBody, headers: { "Content-Type": "application/json" } }).then(function (result) { return { data: result, subscription: _this.getById(result.id) }; }); }; return Subscriptions; }(queryable_1.QueryableCollection)); exports.Subscriptions = Subscriptions; /** * Describes a single webhook subscription instance * */ var Subscription = (function (_super) { __extends(Subscription, _super); function Subscription() { return _super !== null && _super.apply(this, arguments) || this; } /** * Renews this webhook subscription * * @param expirationDate The date and time to expire the subscription in the form YYYY-MM-ddTHH:mm:ss+00:00 (maximum of 6 months) */ Subscription.prototype.update = function (expirationDate) { var _this = this; var postBody = JSON.stringify({ "expirationDateTime": expirationDate, }); return this.patch({ body: postBody, headers: { "Content-Type": "application/json" } }).then(function (data) { return { data: data, subscription: _this }; }); }; /** * Removes this webhook subscription * */ Subscription.prototype.delete = function () { return _super.prototype.delete.call(this); }; return Subscription; }(queryable_1.QueryableInstance)); exports.Subscription = Subscription; /***/ }), /* 48 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var queryable_1 = __webpack_require__(1); var files_1 = __webpack_require__(52); var odata_1 = __webpack_require__(2); var UserProfileQuery = (function (_super) { __extends(UserProfileQuery, _super); /** * Creates a new instance of the UserProfileQuery class * * @param baseUrl The url or Queryable which forms the parent of this user profile query */ function UserProfileQuery(baseUrl, path) { if (path === void 0) { path = "_api/sp.userprofiles.peoplemanager"; } var _this = _super.call(this, baseUrl, path) || this; _this.profileLoader = new ProfileLoader(baseUrl); return _this; } Object.defineProperty(UserProfileQuery.prototype, "editProfileLink", { /** * The url of the edit profile page for the current user */ get: function () { return this.clone(UserProfileQuery, "EditProfileLink").getAs(odata_1.ODataValue()); }, enumerable: true, configurable: true }); Object.defineProperty(UserProfileQuery.prototype, "isMyPeopleListPublic", { /** * A boolean value that indicates whether the current user's "People I'm Following" list is public */ get: function () { return this.clone(UserProfileQuery, "IsMyPeopleListPublic").getAs(odata_1.ODataValue()); }, enumerable: true, configurable: true }); /** * A boolean value that indicates whether the current user is being followed by the specified user * * @param loginName The account name of the user */ UserProfileQuery.prototype.amIFollowedBy = function (loginName) { var q = this.clone(UserProfileQuery, "amifollowedby(@v)", true); q.query.add("@v", "'" + encodeURIComponent(loginName) + "'"); return q.get(); }; /** * A boolean value that indicates whether the current user is following the specified user * * @param loginName The account name of the user */ UserProfileQuery.prototype.amIFollowing = function (loginName) { var q = this.clone(UserProfileQuery, "amifollowing(@v)", true); q.query.add("@v", "'" + encodeURIComponent(loginName) + "'"); return q.get(); }; /** * Gets tags that the current user is following * * @param maxCount The maximum number of tags to retrieve (default is 20) */ UserProfileQuery.prototype.getFollowedTags = function (maxCount) { if (maxCount === void 0) { maxCount = 20; } return this.clone(UserProfileQuery, "getfollowedtags(" + maxCount + ")", true).get(); }; /** * Gets the people who are following the specified user * * @param loginName The account name of the user */ UserProfileQuery.prototype.getFollowersFor = function (loginName) { var q = this.clone(UserProfileQuery, "getfollowersfor(@v)", true); q.query.add("@v", "'" + encodeURIComponent(loginName) + "'"); return q.get(); }; Object.defineProperty(UserProfileQuery.prototype, "myFollowers", { /** * Gets the people who are following the current user * */ get: function () { return new queryable_1.QueryableCollection(this, "getmyfollowers"); }, enumerable: true, configurable: true }); Object.defineProperty(UserProfileQuery.prototype, "myProperties", { /** * Gets user properties for the current user * */ get: function () { return new UserProfileQuery(this, "getmyproperties"); }, enumerable: true, configurable: true }); /** * Gets the people who the specified user is following * * @param loginName The account name of the user. */ UserProfileQuery.prototype.getPeopleFollowedBy = function (loginName) { var q = this.clone(UserProfileQuery, "getpeoplefollowedby(@v)", true); q.query.add("@v", "'" + encodeURIComponent(loginName) + "'"); return q.get(); }; /** * Gets user properties for the specified user. * * @param loginName The account name of the user. */ UserProfileQuery.prototype.getPropertiesFor = function (loginName) { var q = this.clone(UserProfileQuery, "getpropertiesfor(@v)", true); q.query.add("@v", "'" + encodeURIComponent(loginName) + "'"); return q.get(); }; Object.defineProperty(UserProfileQuery.prototype, "trendingTags", { /** * Gets the 20 most popular hash tags over the past week, sorted so that the most popular tag appears first * */ get: function () { var q = this.clone(UserProfileQuery, null, true); q.concat(".gettrendingtags"); return q.get(); }, enumerable: true, configurable: true }); /** * Gets the specified user profile property for the specified user * * @param loginName The account name of the user * @param propertyName The case-sensitive name of the property to get */ UserProfileQuery.prototype.getUserProfilePropertyFor = function (loginName, propertyName) { var q = this.clone(UserProfileQuery, "getuserprofilepropertyfor(accountname=@v, propertyname='" + propertyName + "')", true); q.query.add("@v", "'" + encodeURIComponent(loginName) + "'"); return q.get(); }; /** * Removes the specified user from the user's list of suggested people to follow * * @param loginName The account name of the user */ UserProfileQuery.prototype.hideSuggestion = function (loginName) { var q = this.clone(UserProfileQuery, "hidesuggestion(@v)", true); q.query.add("@v", "'" + encodeURIComponent(loginName) + "'"); return q.post(); }; /** * A boolean values that indicates whether the first user is following the second user * * @param follower The account name of the user who might be following the followee * @param followee The account name of the user who might be followed by the follower */ UserProfileQuery.prototype.isFollowing = function (follower, followee) { var q = this.clone(UserProfileQuery, null, true); q.concat(".isfollowing(possiblefolloweraccountname=@v, possiblefolloweeaccountname=@y)"); q.query.add("@v", "'" + encodeURIComponent(follower) + "'"); q.query.add("@y", "'" + encodeURIComponent(followee) + "'"); return q.get(); }; /** * Uploads and sets the user profile picture (Users can upload a picture to their own profile only). Not supported for batching. * * @param profilePicSource Blob data representing the user's picture in BMP, JPEG, or PNG format of up to 4.76MB */ UserProfileQuery.prototype.setMyProfilePic = function (profilePicSource) { var _this = this; return new Promise(function (resolve, reject) { files_1.readBlobAsArrayBuffer(profilePicSource).then(function (buffer) { var request = new UserProfileQuery(_this, "setmyprofilepicture"); request.post({ body: String.fromCharCode.apply(null, new Uint16Array(buffer)), }).then(function (_) { return resolve(); }); }).catch(function (e) { return reject(e); }); }); }; /** * Provisions one or more users' personal sites. (My Site administrator on SharePoint Online only) * * @param emails The email addresses of the users to provision sites for */ UserProfileQuery.prototype.createPersonalSiteEnqueueBulk = function () { var emails = []; for (var _i = 0; _i < arguments.length; _i++) { emails[_i] = arguments[_i]; } return this.profileLoader.createPersonalSiteEnqueueBulk(emails); }; Object.defineProperty(UserProfileQuery.prototype, "ownerUserProfile", { /** * Gets the user profile of the site owner * */ get: function () { return this.profileLoader.ownerUserProfile; }, enumerable: true, configurable: true }); Object.defineProperty(UserProfileQuery.prototype, "userProfile", { /** * Gets the user profile for the current user */ get: function () { return this.profileLoader.userProfile; }, enumerable: true, configurable: true }); /** * Enqueues creating a personal site for this user, which can be used to share documents, web pages, and other files * * @param interactiveRequest true if interactively (web) initiated request, or false (default) if non-interactively (client) initiated request */ UserProfileQuery.prototype.createPersonalSite = function (interactiveRequest) { if (interactiveRequest === void 0) { interactiveRequest = false; } return this.profileLoader.createPersonalSite(interactiveRequest); }; /** * Sets the privacy settings for this profile * * @param share true to make all social data public; false to make all social data private */ UserProfileQuery.prototype.shareAllSocialData = function (share) { return this.profileLoader.shareAllSocialData(share); }; return UserProfileQuery; }(queryable_1.QueryableInstance)); exports.UserProfileQuery = UserProfileQuery; var ProfileLoader = (function (_super) { __extends(ProfileLoader, _super); /** * Creates a new instance of the ProfileLoader class * * @param baseUrl The url or Queryable which forms the parent of this profile loader */ function ProfileLoader(baseUrl, path) { if (path === void 0) { path = "_api/sp.userprofiles.profileloader.getprofileloader"; } return _super.call(this, baseUrl, path) || this; } /** * Provisions one or more users' personal sites. (My Site administrator on SharePoint Online only) * * @param emails The email addresses of the users to provision sites for */ ProfileLoader.prototype.createPersonalSiteEnqueueBulk = function (emails) { return this.clone(ProfileLoader, "createpersonalsiteenqueuebulk").post({ body: JSON.stringify({ "emailIDs": emails }), }); }; Object.defineProperty(ProfileLoader.prototype, "ownerUserProfile", { /** * Gets the user profile of the site owner. * */ get: function () { var q = this.getParent(ProfileLoader, this.parentUrl, "_api/sp.userprofiles.profileloader.getowneruserprofile"); if (this.hasBatch) { q = q.inBatch(this.batch); } return q.postAs(); }, enumerable: true, configurable: true }); Object.defineProperty(ProfileLoader.prototype, "userProfile", { /** * Gets the user profile of the current user. * */ get: function () { return this.clone(ProfileLoader, "getuserprofile", true).postAs(); }, enumerable: true, configurable: true }); /** * Enqueues creating a personal site for this user, which can be used to share documents, web pages, and other files. * * @param interactiveRequest true if interactively (web) initiated request, or false (default) if non-interactively (client) initiated request */ ProfileLoader.prototype.createPersonalSite = function (interactiveRequest) { if (interactiveRequest === void 0) { interactiveRequest = false; } return this.clone(ProfileLoader, "getuserprofile/createpersonalsiteenque(" + interactiveRequest + ")", true).post(); }; /** * Sets the privacy settings for this profile * * @param share true to make all social data public; false to make all social data private. */ ProfileLoader.prototype.shareAllSocialData = function (share) { return this.clone(ProfileLoader, "getuserprofile/shareallsocialdata(" + share + ")", true).post(); }; return ProfileLoader; }(queryable_1.Queryable)); /***/ }), /* 49 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var queryable_1 = __webpack_require__(1); var util_1 = __webpack_require__(0); /** * Describes the views available in the current context * */ var Views = (function (_super) { __extends(Views, _super); /** * Creates a new instance of the Views class * * @param baseUrl The url or Queryable which forms the parent of this fields collection */ function Views(baseUrl, path) { if (path === void 0) { path = "views"; } return _super.call(this, baseUrl, path) || this; } /** * Gets a view by guid id * * @param id The GUID id of the view */ Views.prototype.getById = function (id) { var v = new View(this); v.concat("('" + id + "')"); return v; }; /** * Gets a view by title (case-sensitive) * * @param title The case-sensitive title of the view */ Views.prototype.getByTitle = function (title) { return new View(this, "getByTitle('" + title + "')"); }; /** * Adds a new view to the collection * * @param title The new views's title * @param personalView True if this is a personal view, otherwise false, default = false * @param additionalSettings Will be passed as part of the view creation body */ /*tslint:disable max-line-length */ Views.prototype.add = function (title, personalView, additionalSettings) { var _this = this; if (personalView === void 0) { personalView = false; } if (additionalSettings === void 0) { additionalSettings = {}; } var postBody = JSON.stringify(util_1.Util.extend({ "PersonalView": personalView, "Title": title, "__metadata": { "type": "SP.View" }, }, additionalSettings)); return this.clone(Views, null, true).postAs({ body: postBody }).then(function (data) { return { data: data, view: _this.getById(data.Id), }; }); }; return Views; }(queryable_1.QueryableCollection)); exports.Views = Views; /** * Describes a single View instance * */ var View = (function (_super) { __extends(View, _super); function View() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(View.prototype, "fields", { get: function () { return new ViewFields(this); }, enumerable: true, configurable: true }); /** * Updates this view intance with the supplied properties * * @param properties A plain object hash of values to update for the view */ View.prototype.update = function (properties) { var _this = this; var postBody = JSON.stringify(util_1.Util.extend({ "__metadata": { "type": "SP.View" }, }, properties)); return this.post({ body: postBody, headers: { "X-HTTP-Method": "MERGE", }, }).then(function (data) { return { data: data, view: _this, }; }); }; /** * Delete this view * */ View.prototype.delete = function () { return this.post({ headers: { "X-HTTP-Method": "DELETE", }, }); }; /** * Returns the list view as HTML. * */ View.prototype.renderAsHtml = function () { return this.clone(queryable_1.Queryable, "renderashtml", true).get(); }; return View; }(queryable_1.QueryableInstance)); exports.View = View; var ViewFields = (function (_super) { __extends(ViewFields, _super); function ViewFields(baseUrl, path) { if (path === void 0) { path = "viewfields"; } return _super.call(this, baseUrl, path) || this; } /** * Gets a value that specifies the XML schema that represents the collection. */ ViewFields.prototype.getSchemaXml = function () { return this.clone(queryable_1.Queryable, "schemaxml", true).get(); }; /** * Adds the field with the specified field internal name or display name to the collection. * * @param fieldTitleOrInternalName The case-sensitive internal name or display name of the field to add. */ ViewFields.prototype.add = function (fieldTitleOrInternalName) { return this.clone(ViewFields, "addviewfield('" + fieldTitleOrInternalName + "')", true).post(); }; /** * Moves the field with the specified field internal name to the specified position in the collection. * * @param fieldInternalName The case-sensitive internal name of the field to move. * @param index The zero-based index of the new position for the field. */ ViewFields.prototype.move = function (fieldInternalName, index) { return this.clone(ViewFields, "moveviewfieldto", true).post({ body: JSON.stringify({ "field": fieldInternalName, "index": index }), }); }; /** * Removes all the fields from the collection. */ ViewFields.prototype.removeAll = function () { return this.clone(ViewFields, "removeallviewfields", true).post(); }; /** * Removes the field with the specified field internal name from the collection. * * @param fieldInternalName The case-sensitive internal name of the field to remove from the view. */ ViewFields.prototype.remove = function (fieldInternalName) { return this.clone(ViewFields, "removeviewfield('" + fieldInternalName + "')", true).post(); }; return ViewFields; }(queryable_1.QueryableCollection)); exports.ViewFields = ViewFields; /***/ }), /* 50 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var queryable_1 = __webpack_require__(1); var LimitedWebPartManager = (function (_super) { __extends(LimitedWebPartManager, _super); function LimitedWebPartManager() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(LimitedWebPartManager.prototype, "webparts", { /** * Gets the set of web part definitions contained by this web part manager * */ get: function () { return new WebPartDefinitions(this, "webparts"); }, enumerable: true, configurable: true }); /** * Exports a webpart definition * * @param id the GUID id of the definition to export */ LimitedWebPartManager.prototype.export = function (id) { return this.clone(LimitedWebPartManager, "ExportWebPart", true).post({ body: JSON.stringify({ webPartId: id }), }); }; /** * Imports a webpart * * @param xml webpart definition which must be valid XML in the .dwp or .webpart format */ LimitedWebPartManager.prototype.import = function (xml) { return this.clone(LimitedWebPartManager, "ImportWebPart", true).post({ body: JSON.stringify({ webPartXml: xml }), }); }; return LimitedWebPartManager; }(queryable_1.Queryable)); exports.LimitedWebPartManager = LimitedWebPartManager; var WebPartDefinitions = (function (_super) { __extends(WebPartDefinitions, _super); function WebPartDefinitions() { return _super !== null && _super.apply(this, arguments) || this; } /** * Gets a web part definition from the collection by id * * @param id GUID id of the web part definition to get */ WebPartDefinitions.prototype.getById = function (id) { return new WebPartDefinition(this, "getbyid('" + id + "')"); }; return WebPartDefinitions; }(queryable_1.QueryableCollection)); exports.WebPartDefinitions = WebPartDefinitions; var WebPartDefinition = (function (_super) { __extends(WebPartDefinition, _super); function WebPartDefinition() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(WebPartDefinition.prototype, "webpart", { /** * Gets the webpart information associated with this definition */ get: function () { return new WebPart(this); }, enumerable: true, configurable: true }); /** * Removes a webpart from a page, all settings will be lost */ WebPartDefinition.prototype.delete = function () { return this.clone(WebPartDefinition, "DeleteWebPart", true).post(); }; return WebPartDefinition; }(queryable_1.QueryableInstance)); exports.WebPartDefinition = WebPartDefinition; var WebPart = (function (_super) { __extends(WebPart, _super); /** * Creates a new instance of the WebPart class * * @param baseUrl The url or Queryable which forms the parent of this fields collection * @param path Optional, if supplied will be appended to the supplied baseUrl */ function WebPart(baseUrl, path) { if (path === void 0) { path = "webpart"; } return _super.call(this, baseUrl, path) || this; } return WebPart; }(queryable_1.QueryableInstance)); exports.WebPart = WebPart; /***/ }), /* 51 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var logging_1 = __webpack_require__(5); function deprecated(message) { return function (target, propertyKey, descriptor) { var method = descriptor.value; descriptor.value = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } logging_1.Logger.log({ data: { descriptor: descriptor, propertyKey: propertyKey, target: target, }, level: logging_1.LogLevel.Warning, message: message, }); return method.apply(this, args); }; }; } exports.deprecated = deprecated; /***/ }), /* 52 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * Reads a blob as text * * @param blob The data to read */ function readBlobAsText(blob) { return readBlobAs(blob, "string"); } exports.readBlobAsText = readBlobAsText; /** * Reads a blob into an array buffer * * @param blob The data to read */ function readBlobAsArrayBuffer(blob) { return readBlobAs(blob, "buffer"); } exports.readBlobAsArrayBuffer = readBlobAsArrayBuffer; /** * Generic method to read blob's content * * @param blob The data to read * @param mode The read mode */ function readBlobAs(blob, mode) { return new Promise(function (resolve, reject) { try { var reader = new FileReader(); reader.onload = function (e) { resolve(e.target.result); }; switch (mode) { case "string": reader.readAsText(blob); break; case "buffer": reader.readAsArrayBuffer(blob); break; } } catch (e) { reject(e); } }); } /***/ }) /******/ ]); }); //# sourceMappingURL=pnp.js.map
<?php /** * Register the ElggDiscussionReply class for the object/discussion_reply subtype */ if (get_subtype_id('object', 'discussion_reply')) { update_subtype('object', 'discussion_reply', 'ElggDiscussionReply'); } else { add_subtype('object', 'discussion_reply', 'ElggDiscussionReply'); }
/* ScummVM - Graphic Adventure Engine * * ScummVM is the legal property of its developers, whose names * are too numerous to list here. Please refer to the COPYRIGHT * file distributed with this source distribution. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "mutationofjb/tasks/conversationtask.h" #include "mutationofjb/assets.h" #include "mutationofjb/game.h" #include "mutationofjb/gamedata.h" #include "mutationofjb/gamescreen.h" #include "mutationofjb/script.h" #include "mutationofjb/tasks/saytask.h" #include "mutationofjb/tasks/sequentialtask.h" #include "mutationofjb/tasks/taskmanager.h" #include "mutationofjb/util.h" #include "mutationofjb/widgets/conversationwidget.h" namespace MutationOfJB { void ConversationTask::start() { setState(RUNNING); Game &game = getTaskManager()->getGame(); game.getGameScreen().showConversationWidget(true); ConversationWidget &widget = game.getGameScreen().getConversationWidget(); widget.setCallback(this); _currentGroupIndex = 0; showChoicesOrPick(); } void ConversationTask::update() { if (_sayTask) { if (_sayTask->getState() == Task::FINISHED) { _sayTask.reset(); switch (_substate) { case SAYING_NO_QUESTIONS: finish(); break; case SAYING_QUESTION: { const ConversationLineList &responseList = getTaskManager()->getGame().getAssets().getResponseList(); const ConversationLineList::Line *const line = responseList.getLine(_currentItem->_response); _substate = SAYING_RESPONSE; createSayTasks(line); getTaskManager()->startTask(_sayTask); break; } case SAYING_RESPONSE: { startExtra(); if (_substate != RUNNING_EXTRA) { gotoNextGroup(); } break; } default: break; } } } if (_innerExecCtx) { Command::ExecuteResult res = _innerExecCtx->runActiveCommand(); if (res == Command::Finished) { delete _innerExecCtx; _innerExecCtx = nullptr; gotoNextGroup(); } } } void ConversationTask::onChoiceClicked(ConversationWidget *convWidget, int, uint32 data) { const ConversationInfo::Item &item = getCurrentGroup()[data]; convWidget->clearChoices(); const ConversationLineList &toSayList = getTaskManager()->getGame().getAssets().getToSayList(); const ConversationLineList::Line *line = toSayList.getLine(item._question); _substate = SAYING_QUESTION; createSayTasks(line); getTaskManager()->startTask(_sayTask); _currentItem = &item; if (!line->_speeches[0].isRepeating()) { getTaskManager()->getGame().getGameData().getCurrentScene()->addExhaustedConvItem(_convInfo._context, data + 1, _currentGroupIndex + 1); } } void ConversationTask::showChoicesOrPick() { Game &game = getTaskManager()->getGame(); GameData &gameData = game.getGameData(); Scene *const scene = gameData.getScene(_sceneId); if (!scene) { return; } Common::Array<uint32> itemsWithValidQuestions; Common::Array<uint32> itemsWithValidResponses; Common::Array<uint32> itemsWithValidNext; /* Collect valid questions (not exhausted and not empty). Collect valid responses (not exhausted and not empty). If there are at least two visible questions, we show them. If there is just one visible question, pick it automatically ONLY if this is not the first question in this conversation. Otherwise we don't start the conversation. If there are no visible questions, automatically pick the first valid response. If nothing above applies, don't start the conversation. */ const ConversationInfo::ItemGroup &currentGroup = getCurrentGroup(); for (ConversationInfo::ItemGroup::size_type i = 0; i < currentGroup.size(); ++i) { const ConversationInfo::Item &item = currentGroup[i]; if (scene->isConvItemExhausted(_convInfo._context, static_cast<uint8>(i + 1), static_cast<uint8>(_currentGroupIndex + 1))) { continue; } const uint8 toSay = item._question; const uint8 response = item._response; const uint8 next = item._nextGroupIndex; if (toSay != 0) { itemsWithValidQuestions.push_back(i); } if (response != 0) { itemsWithValidResponses.push_back(i); } if (next != 0) { itemsWithValidNext.push_back(i); } } if (itemsWithValidQuestions.size() > 1) { ConversationWidget &widget = game.getGameScreen().getConversationWidget(); const ConversationLineList &toSayList = game.getAssets().getToSayList(); for (Common::Array<uint32>::size_type i = 0; i < itemsWithValidQuestions.size() && i < ConversationWidget::CONVERSATION_MAX_CHOICES; ++i) { const ConversationInfo::Item &item = currentGroup[itemsWithValidQuestions[i]]; const ConversationLineList::Line *const line = toSayList.getLine(item._question); const Common::String widgetText = toUpperCP895(line->_speeches[0]._text); widget.setChoice(static_cast<int>(i), widgetText, itemsWithValidQuestions[i]); } _substate = IDLE; _currentItem = nullptr; _haveChoices = true; } else if (itemsWithValidQuestions.size() == 1 && _haveChoices) { const ConversationLineList &toSayList = game.getAssets().getToSayList(); const ConversationInfo::Item &item = currentGroup[itemsWithValidQuestions.front()]; const ConversationLineList::Line *const line = toSayList.getLine(item._question); _substate = SAYING_QUESTION; createSayTasks(line); getTaskManager()->startTask(_sayTask); _currentItem = &item; if (!line->_speeches[0].isRepeating()) { game.getGameData().getCurrentScene()->addExhaustedConvItem(_convInfo._context, itemsWithValidQuestions.front() + 1, _currentGroupIndex + 1); } _haveChoices = true; } else if (!itemsWithValidResponses.empty() && _haveChoices) { const ConversationLineList &responseList = game.getAssets().getResponseList(); const ConversationInfo::Item &item = currentGroup[itemsWithValidResponses.front()]; const ConversationLineList::Line *const line = responseList.getLine(item._response); _substate = SAYING_RESPONSE; createSayTasks(line); getTaskManager()->startTask(_sayTask); _currentItem = &item; _haveChoices = true; } else if (!itemsWithValidNext.empty() && _haveChoices) { _currentGroupIndex = currentGroup[itemsWithValidNext.front()]._nextGroupIndex - 1; showChoicesOrPick(); } else { if (_haveChoices) { finish(); } else { _sayTask = TaskPtr(new SayTask("Nothing to talk about.", _convInfo._color)); // TODO: This is hardcoded in executable. Load it. getTaskManager()->startTask(_sayTask); _substate = SAYING_NO_QUESTIONS; _currentItem = nullptr; } } } const ConversationInfo::ItemGroup &ConversationTask::getCurrentGroup() const { assert(_currentGroupIndex < _convInfo._itemGroups.size()); return _convInfo._itemGroups[_currentGroupIndex]; } void ConversationTask::finish() { setState(FINISHED); Game &game = getTaskManager()->getGame(); game.getGameScreen().showConversationWidget(false); ConversationWidget &widget = game.getGameScreen().getConversationWidget(); widget.setCallback(nullptr); } void ConversationTask::startExtra() { const ConversationLineList &responseList = getTaskManager()->getGame().getAssets().getResponseList(); const ConversationLineList::Line *const line = responseList.getLine(_currentItem->_response); if (!line->_extra.empty()) { _innerExecCtx = new ScriptExecutionContext(getTaskManager()->getGame()); Command *const extraCmd = _innerExecCtx->getExtra(line->_extra); if (extraCmd) { Command::ExecuteResult res = _innerExecCtx->startCommand(extraCmd); if (res == Command::InProgress) { _substate = RUNNING_EXTRA; } else { delete _innerExecCtx; _innerExecCtx = nullptr; } } else { warning("Extra '%s' not found", line->_extra.c_str()); delete _innerExecCtx; _innerExecCtx = nullptr; } } } void ConversationTask::gotoNextGroup() { if (_currentItem->_nextGroupIndex == 0) { finish(); } else { _currentGroupIndex = _currentItem->_nextGroupIndex - 1; showChoicesOrPick(); } } void ConversationTask::createSayTasks(const ConversationLineList::Line *line) { if (line->_speeches.size() == 1) { const ConversationLineList::Speech &speech = line->_speeches[0]; _sayTask = TaskPtr(new SayTask(speech._text, getSpeechColor(speech))); } else { TaskPtrs tasks; for (ConversationLineList::Speeches::const_iterator it = line->_speeches.begin(); it != line->_speeches.end(); ++it) { tasks.push_back(TaskPtr(new SayTask(it->_text, getSpeechColor(*it)))); } _sayTask = TaskPtr(new SequentialTask(tasks)); } } uint8 ConversationTask::getSpeechColor(const ConversationLineList::Speech &speech) { uint8 color = WHITE; if (_substate == SAYING_RESPONSE) { color = _convInfo._color; if (_mode == TalkCommand::RAY_AND_BUTTLEG_MODE) { if (speech.isFirstSpeaker()) { color = GREEN; } else if (speech.isSecondSpeaker()) { color = LIGHTBLUE; } } } return color; } }
/* JWindow.java -- Copyright (C) 2002, 2003, 2004, 2005 Free Software Foundation, Inc. This file is part of GNU Classpath. GNU Classpath is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ package javax.swing; import java.awt.AWTEvent; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.Frame; import java.awt.Graphics; import java.awt.GraphicsConfiguration; import java.awt.LayoutManager; import java.awt.Window; import java.awt.event.KeyEvent; import javax.accessibility.Accessible; import javax.accessibility.AccessibleContext; /** * Unlike JComponent derivatives, JWindow inherits from * java.awt.Window. But also lets a look-and-feel component to its work. * * @author Ronald Veldema (rveldema@cs.vu.nl) */ public class JWindow extends Window implements Accessible, RootPaneContainer { /** * Provides accessibility support for <code>JWindow</code>. */ protected class AccessibleJWindow extends Window.AccessibleAWTWindow { /** * Creates a new instance of <code>AccessibleJWindow</code>. */ protected AccessibleJWindow() { super(); // Nothing to do here. } } private static final long serialVersionUID = 5420698392125238833L; protected JRootPane rootPane; /** * @specnote rootPaneCheckingEnabled is false to comply with J2SE 5.0 */ protected boolean rootPaneCheckingEnabled = false; protected AccessibleContext accessibleContext; /** * Creates a new <code>JWindow</code> that has a shared invisible owner frame * as its parent. */ public JWindow() { super(SwingUtilities.getOwnerFrame(null)); windowInit(); } /** * Creates a new <code>JWindow</code> that uses the specified graphics * environment. This can be used to open a window on a different screen for * example. * * @param gc the graphics environment to use */ public JWindow(GraphicsConfiguration gc) { super(SwingUtilities.getOwnerFrame(null), gc); windowInit(); } /** * Creates a new <code>JWindow</code> that has the specified * <code>owner</code> frame. If <code>owner</code> is <code>null</code>, then * an invisible shared owner frame is installed as owner frame. * * @param owner the owner frame of this window; if <code>null</code> a shared * invisible owner frame is used */ public JWindow(Frame owner) { super(SwingUtilities.getOwnerFrame(owner)); windowInit(); } /** * Creates a new <code>JWindow</code> that has the specified * <code>owner</code> window. If <code>owner</code> is <code>null</code>, * then an invisible shared owner frame is installed as owner frame. * * @param owner the owner window of this window; if <code>null</code> a * shared invisible owner frame is used */ public JWindow(Window owner) { super(SwingUtilities.getOwnerFrame(owner)); windowInit(); } /** * Creates a new <code>JWindow</code> for the given graphics configuration * and that has the specified <code>owner</code> window. If * <code>owner</code> is <code>null</code>, then an invisible shared owner * frame is installed as owner frame. * * The <code>gc</code> parameter can be used to open the window on a * different screen for example. * * @param owner the owner window of this window; if <code>null</code> a * shared invisible owner frame is used * @param gc the graphics configuration to use */ public JWindow(Window owner, GraphicsConfiguration gc) { super(SwingUtilities.getOwnerFrame(owner), gc); windowInit(); } protected void windowInit() { // We need to explicitly enable events here so that our processKeyEvent() // and processWindowEvent() gets called. enableEvents(AWTEvent.KEY_EVENT_MASK); super.setLayout(new BorderLayout(1, 1)); getRootPane(); // will do set/create // Now we're done init stage, adds and layouts go to content pane. setRootPaneCheckingEnabled(true); } public Dimension getPreferredSize() { return super.getPreferredSize(); } public void setLayout(LayoutManager manager) { // Check if we're in initialization stage. If so, call super.setLayout // otherwise, valid calls go to the content pane. if (isRootPaneCheckingEnabled()) getContentPane().setLayout(manager); else super.setLayout(manager); } public void setLayeredPane(JLayeredPane layeredPane) { getRootPane().setLayeredPane(layeredPane); } public JLayeredPane getLayeredPane() { return getRootPane().getLayeredPane(); } public JRootPane getRootPane() { if (rootPane == null) setRootPane(createRootPane()); return rootPane; } protected void setRootPane(JRootPane root) { if (rootPane != null) remove(rootPane); rootPane = root; add(rootPane, BorderLayout.CENTER); } protected JRootPane createRootPane() { return new JRootPane(); } public Container getContentPane() { return getRootPane().getContentPane(); } public void setContentPane(Container contentPane) { getRootPane().setContentPane(contentPane); } public Component getGlassPane() { return getRootPane().getGlassPane(); } public void setGlassPane(Component glassPane) { getRootPane().setGlassPane(glassPane); } protected void addImpl(Component comp, Object constraints, int index) { // If we're adding in the initialization stage use super.add. // otherwise pass the add onto the content pane. if (isRootPaneCheckingEnabled()) getContentPane().add(comp, constraints, index); else super.addImpl(comp, constraints, index); } public void remove(Component comp) { // If we're removing the root pane, use super.remove. Otherwise // pass it on to the content pane instead. if (comp == rootPane) super.remove(rootPane); else getContentPane().remove(comp); } protected boolean isRootPaneCheckingEnabled() { return rootPaneCheckingEnabled; } protected void setRootPaneCheckingEnabled(boolean enabled) { rootPaneCheckingEnabled = enabled; } public void update(Graphics g) { paint(g); } protected void processKeyEvent(KeyEvent e) { super.processKeyEvent(e); } public AccessibleContext getAccessibleContext() { if (accessibleContext == null) accessibleContext = new AccessibleJWindow(); return accessibleContext; } protected String paramString() { return "JWindow"; } }
/* Bluetooth Low Energy Protocol for QMK. * Author: Wez Furlong, 2016 * Supports the Adafruit BLE board built around the nRF51822 chip. */ #pragma once #ifdef MODULE_ADAFRUIT_BLE # include <stdbool.h> # include <stdint.h> # include <string.h> # include "config_common.h" # include "progmem.h" # ifdef __cplusplus extern "C" { # endif /* Instruct the module to enable HID keyboard support and reset */ extern bool adafruit_ble_enable_keyboard(void); /* Query to see if the BLE module is connected */ extern bool adafruit_ble_query_is_connected(void); /* Returns true if we believe that the BLE module is connected. * This uses our cached understanding that is maintained by * calling ble_task() periodically. */ extern bool adafruit_ble_is_connected(void); /* Call this periodically to process BLE-originated things */ extern void adafruit_ble_task(void); /* Generates keypress events for a set of keys. * The hid modifier mask specifies the state of the modifier keys for * this set of keys. * Also sends a key release indicator, so that the keys do not remain * held down. */ extern bool adafruit_ble_send_keys(uint8_t hid_modifier_mask, uint8_t *keys, uint8_t nkeys); /* Send a consumer keycode, holding it down for the specified duration * (milliseconds) */ extern bool adafruit_ble_send_consumer_key(uint16_t keycode, int hold_duration); # ifdef MOUSE_ENABLE /* Send a mouse/wheel movement report. * The parameters are signed and indicate positive of negative direction * change. */ extern bool adafruit_ble_send_mouse_move(int8_t x, int8_t y, int8_t scroll, int8_t pan, uint8_t buttons); # endif /* Compute battery voltage by reading an analog pin. * Returns the integer number of millivolts */ extern uint32_t adafruit_ble_read_battery_voltage(void); extern bool adafruit_ble_set_mode_leds(bool on); extern bool adafruit_ble_set_power_level(int8_t level); # ifdef __cplusplus } # endif #endif // MODULE_ADAFRUIT_BLE
include RbCommonHelper include RbFormHelper include ProjectsHelper class RbReleasesMultiviewController < RbApplicationController unloadable def index end def show respond_to do |format| format.html { render } end end def new @release_multiview = RbReleaseMultiview.new(:project => @project) if request.post? # Convert id's into numbers and remove blank params[:release_multiview][:release_ids]=selected_ids(params[:release_multiview][:release_ids]) @release_multiview.attributes = params[:release_multiview] if @release_multiview.save flash[:notice] = l(:notice_successful_create) redirect_to :controller => 'rb_releases', :action => 'index', :project_id => @project end end end def edit if request.post? # Convert id's into numbers and remove blank params[:release_multiview][:release_ids]=selected_ids(params[:release_multiview][:release_ids]) if @release_multiview.update_attributes(params[:release_multiview]) flash[:notice] = l(:notice_successful_update) redirect_to :controller => 'rb_releases_multiview', :action => 'show', :release_multiview_id => @release_multiview end end end def update end def destroy @release_multiview.destroy redirect_to :controller => 'rb_releases', :action => 'index', :project_id => @project end end
<?php /** * File containing the eZDBTestSuite class * * @copyright Copyright (C) eZ Systems AS. All rights reserved. * @license For full copyright and license information view LICENSE file distributed with this source code. * @version //autogentag// * @package tests */ class eZDBTestSuite extends ezpDatabaseTestSuite { public function __construct() { parent::__construct(); $this->setName( "eZDB Test Suite" ); $this->addTestSuite( 'eZPostgreSQLDBTest' ); $this->addTestSuite( 'eZDBInterfaceTest' ); $this->addTestSuite( 'eZMySQLiDBFKTest' ); $this->addTestSuite( 'eZMySQLCharsetTest' ); } public static function suite() { return new self(); } } ?>
<?php /** * Link/Bookmark API * * @package WordPress * @subpackage Bookmark */ /** * Retrieve Bookmark data * * @since 2.1.0 * * @global wpdb $wpdb WordPress database abstraction object. * * @param int|stdClass $bookmark * @param string $output Optional. The required return type. One of OBJECT, ARRAY_A, or ARRAY_N, which * correspond to an stdClass object, an associative array, or a numeric array, * respectively. Default OBJECT. * @param string $filter Optional. How to sanitize bookmark fields. Default 'raw'. * @return array|object|null Type returned depends on $output value. */ function get_bookmark( $bookmark, $output = OBJECT, $filter = 'raw' ) { global $wpdb; if ( empty( $bookmark ) ) { if ( isset( $GLOBALS['link'] ) ) { $_bookmark = & $GLOBALS['link']; } else { $_bookmark = null; } } elseif ( is_object( $bookmark ) ) { wp_cache_add( $bookmark->link_id, $bookmark, 'bookmark' ); $_bookmark = $bookmark; } else { if ( isset( $GLOBALS['link'] ) && ( $GLOBALS['link']->link_id == $bookmark ) ) { $_bookmark = & $GLOBALS['link']; } else { $_bookmark = wp_cache_get( $bookmark, 'bookmark' ); if ( ! $_bookmark ) { $_bookmark = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->links WHERE link_id = %d LIMIT 1", $bookmark ) ); if ( $_bookmark ) { $_bookmark->link_category = array_unique( wp_get_object_terms( $_bookmark->link_id, 'link_category', array( 'fields' => 'ids' ) ) ); wp_cache_add( $_bookmark->link_id, $_bookmark, 'bookmark' ); } } } } if ( ! $_bookmark ) { return $_bookmark; } $_bookmark = sanitize_bookmark( $_bookmark, $filter ); if ( OBJECT === $output ) { return $_bookmark; } elseif ( ARRAY_A === $output ) { return get_object_vars( $_bookmark ); } elseif ( ARRAY_N === $output ) { return array_values( get_object_vars( $_bookmark ) ); } else { return $_bookmark; } } /** * Retrieve single bookmark data item or field. * * @since 2.3.0 * * @param string $field The name of the data field to return. * @param int $bookmark The bookmark ID to get field. * @param string $context Optional. The context of how the field will be used. * @return string|WP_Error */ function get_bookmark_field( $field, $bookmark, $context = 'display' ) { $bookmark = (int) $bookmark; $bookmark = get_bookmark( $bookmark ); if ( is_wp_error( $bookmark ) ) { return $bookmark; } if ( ! is_object( $bookmark ) ) { return ''; } if ( ! isset( $bookmark->$field ) ) { return ''; } return sanitize_bookmark_field( $field, $bookmark->$field, $bookmark->link_id, $context ); } /** * Retrieves the list of bookmarks * * Attempts to retrieve from the cache first based on MD5 hash of arguments. If * that fails, then the query will be built from the arguments and executed. The * results will be stored to the cache. * * @since 2.1.0 * * @global wpdb $wpdb WordPress database abstraction object. * * @param string|array $args { * Optional. String or array of arguments to retrieve bookmarks. * * @type string $orderby How to order the links by. Accepts 'id', 'link_id', 'name', 'link_name', * 'url', 'link_url', 'visible', 'link_visible', 'rating', 'link_rating', * 'owner', 'link_owner', 'updated', 'link_updated', 'notes', 'link_notes', * 'description', 'link_description', 'length' and 'rand'. * When `$orderby` is 'length', orders by the character length of * 'link_name'. Default 'name'. * @type string $order Whether to order bookmarks in ascending or descending order. * Accepts 'ASC' (ascending) or 'DESC' (descending). Default 'ASC'. * @type int $limit Amount of bookmarks to display. Accepts any positive number or * -1 for all. Default -1. * @type string $category Comma-separated list of category IDs to include links from. * Default empty. * @type string $category_name Category to retrieve links for by name. Default empty. * @type int|bool $hide_invisible Whether to show or hide links marked as 'invisible'. Accepts * 1|true or 0|false. Default 1|true. * @type int|bool $show_updated Whether to display the time the bookmark was last updated. * Accepts 1|true or 0|false. Default 0|false. * @type string $include Comma-separated list of bookmark IDs to include. Default empty. * @type string $exclude Comma-separated list of bookmark IDs to exclude. Default empty. * @type string $search Search terms. Will be SQL-formatted with wildcards before and after * and searched in 'link_url', 'link_name' and 'link_description'. * Default empty. * } * @return object[] List of bookmark row objects. */ function get_bookmarks( $args = '' ) { global $wpdb; $defaults = array( 'orderby' => 'name', 'order' => 'ASC', 'limit' => -1, 'category' => '', 'category_name' => '', 'hide_invisible' => 1, 'show_updated' => 0, 'include' => '', 'exclude' => '', 'search' => '', ); $parsed_args = wp_parse_args( $args, $defaults ); $key = md5( serialize( $parsed_args ) ); $cache = wp_cache_get( 'get_bookmarks', 'bookmark' ); if ( 'rand' !== $parsed_args['orderby'] && $cache ) { if ( is_array( $cache ) && isset( $cache[ $key ] ) ) { $bookmarks = $cache[ $key ]; /** * Filters the returned list of bookmarks. * * The first time the hook is evaluated in this file, it returns the cached * bookmarks list. The second evaluation returns a cached bookmarks list if the * link category is passed but does not exist. The third evaluation returns * the full cached results. * * @since 2.1.0 * * @see get_bookmarks() * * @param array $bookmarks List of the cached bookmarks. * @param array $parsed_args An array of bookmark query arguments. */ return apply_filters( 'get_bookmarks', $bookmarks, $parsed_args ); } } if ( ! is_array( $cache ) ) { $cache = array(); } $inclusions = ''; if ( ! empty( $parsed_args['include'] ) ) { $parsed_args['exclude'] = ''; // Ignore exclude, category, and category_name params if using include. $parsed_args['category'] = ''; $parsed_args['category_name'] = ''; $inclinks = wp_parse_id_list( $parsed_args['include'] ); if ( count( $inclinks ) ) { foreach ( $inclinks as $inclink ) { if ( empty( $inclusions ) ) { $inclusions = ' AND ( link_id = ' . $inclink . ' '; } else { $inclusions .= ' OR link_id = ' . $inclink . ' '; } } } } if ( ! empty( $inclusions ) ) { $inclusions .= ')'; } $exclusions = ''; if ( ! empty( $parsed_args['exclude'] ) ) { $exlinks = wp_parse_id_list( $parsed_args['exclude'] ); if ( count( $exlinks ) ) { foreach ( $exlinks as $exlink ) { if ( empty( $exclusions ) ) { $exclusions = ' AND ( link_id <> ' . $exlink . ' '; } else { $exclusions .= ' AND link_id <> ' . $exlink . ' '; } } } } if ( ! empty( $exclusions ) ) { $exclusions .= ')'; } if ( ! empty( $parsed_args['category_name'] ) ) { $parsed_args['category'] = get_term_by( 'name', $parsed_args['category_name'], 'link_category' ); if ( $parsed_args['category'] ) { $parsed_args['category'] = $parsed_args['category']->term_id; } else { $cache[ $key ] = array(); wp_cache_set( 'get_bookmarks', $cache, 'bookmark' ); /** This filter is documented in wp-includes/bookmark.php */ return apply_filters( 'get_bookmarks', array(), $parsed_args ); } } $search = ''; if ( ! empty( $parsed_args['search'] ) ) { $like = '%' . $wpdb->esc_like( $parsed_args['search'] ) . '%'; $search = $wpdb->prepare( ' AND ( (link_url LIKE %s) OR (link_name LIKE %s) OR (link_description LIKE %s) ) ', $like, $like, $like ); } $category_query = ''; $join = ''; if ( ! empty( $parsed_args['category'] ) ) { $incategories = wp_parse_id_list( $parsed_args['category'] ); if ( count( $incategories ) ) { foreach ( $incategories as $incat ) { if ( empty( $category_query ) ) { $category_query = ' AND ( tt.term_id = ' . $incat . ' '; } else { $category_query .= ' OR tt.term_id = ' . $incat . ' '; } } } } if ( ! empty( $category_query ) ) { $category_query .= ") AND taxonomy = 'link_category'"; $join = " INNER JOIN $wpdb->term_relationships AS tr ON ($wpdb->links.link_id = tr.object_id) INNER JOIN $wpdb->term_taxonomy as tt ON tt.term_taxonomy_id = tr.term_taxonomy_id"; } if ( $parsed_args['show_updated'] ) { $recently_updated_test = ', IF (DATE_ADD(link_updated, INTERVAL 120 MINUTE) >= NOW(), 1,0) as recently_updated '; } else { $recently_updated_test = ''; } $get_updated = ( $parsed_args['show_updated'] ) ? ', UNIX_TIMESTAMP(link_updated) AS link_updated_f ' : ''; $orderby = strtolower( $parsed_args['orderby'] ); $length = ''; switch ( $orderby ) { case 'length': $length = ', CHAR_LENGTH(link_name) AS length'; break; case 'rand': $orderby = 'rand()'; break; case 'link_id': $orderby = "$wpdb->links.link_id"; break; default: $orderparams = array(); $keys = array( 'link_id', 'link_name', 'link_url', 'link_visible', 'link_rating', 'link_owner', 'link_updated', 'link_notes', 'link_description' ); foreach ( explode( ',', $orderby ) as $ordparam ) { $ordparam = trim( $ordparam ); if ( in_array( 'link_' . $ordparam, $keys, true ) ) { $orderparams[] = 'link_' . $ordparam; } elseif ( in_array( $ordparam, $keys, true ) ) { $orderparams[] = $ordparam; } } $orderby = implode( ',', $orderparams ); } if ( empty( $orderby ) ) { $orderby = 'link_name'; } $order = strtoupper( $parsed_args['order'] ); if ( '' !== $order && ! in_array( $order, array( 'ASC', 'DESC' ), true ) ) { $order = 'ASC'; } $visible = ''; if ( $parsed_args['hide_invisible'] ) { $visible = "AND link_visible = 'Y'"; } $query = "SELECT * $length $recently_updated_test $get_updated FROM $wpdb->links $join WHERE 1=1 $visible $category_query"; $query .= " $exclusions $inclusions $search"; $query .= " ORDER BY $orderby $order"; if ( -1 != $parsed_args['limit'] ) { $query .= ' LIMIT ' . $parsed_args['limit']; } $results = $wpdb->get_results( $query ); if ( 'rand()' !== $orderby ) { $cache[ $key ] = $results; wp_cache_set( 'get_bookmarks', $cache, 'bookmark' ); } /** This filter is documented in wp-includes/bookmark.php */ return apply_filters( 'get_bookmarks', $results, $parsed_args ); } /** * Sanitizes all bookmark fields. * * @since 2.3.0 * * @param stdClass|array $bookmark Bookmark row. * @param string $context Optional. How to filter the fields. Default 'display'. * @return stdClass|array Same type as $bookmark but with fields sanitized. */ function sanitize_bookmark( $bookmark, $context = 'display' ) { $fields = array( 'link_id', 'link_url', 'link_name', 'link_image', 'link_target', 'link_category', 'link_description', 'link_visible', 'link_owner', 'link_rating', 'link_updated', 'link_rel', 'link_notes', 'link_rss', ); if ( is_object( $bookmark ) ) { $do_object = true; $link_id = $bookmark->link_id; } else { $do_object = false; $link_id = $bookmark['link_id']; } foreach ( $fields as $field ) { if ( $do_object ) { if ( isset( $bookmark->$field ) ) { $bookmark->$field = sanitize_bookmark_field( $field, $bookmark->$field, $link_id, $context ); } } else { if ( isset( $bookmark[ $field ] ) ) { $bookmark[ $field ] = sanitize_bookmark_field( $field, $bookmark[ $field ], $link_id, $context ); } } } return $bookmark; } /** * Sanitizes a bookmark field. * * Sanitizes the bookmark fields based on what the field name is. If the field * has a strict value set, then it will be tested for that, else a more generic * filtering is applied. After the more strict filter is applied, if the `$context` * is 'raw' then the value is immediately return. * * Hooks exist for the more generic cases. With the 'edit' context, the {@see 'edit_$field'} * filter will be called and passed the `$value` and `$bookmark_id` respectively. * * With the 'db' context, the {@see 'pre_$field'} filter is called and passed the value. * The 'display' context is the final context and has the `$field` has the filter name * and is passed the `$value`, `$bookmark_id`, and `$context`, respectively. * * @since 2.3.0 * * @param string $field The bookmark field. * @param mixed $value The bookmark field value. * @param int $bookmark_id Bookmark ID. * @param string $context How to filter the field value. Accepts 'raw', 'edit', 'db', * 'display', 'attribute', or 'js'. Default 'display'. * @return mixed The filtered value. */ function sanitize_bookmark_field( $field, $value, $bookmark_id, $context ) { $int_fields = array( 'link_id', 'link_rating' ); if ( in_array( $field, $int_fields, true ) ) { $value = (int) $value; } switch ( $field ) { case 'link_category': // array( ints ) $value = array_map( 'absint', (array) $value ); // We return here so that the categories aren't filtered. // The 'link_category' filter is for the name of a link category, not an array of a link's link categories. return $value; case 'link_visible': // bool stored as Y|N $value = preg_replace( '/[^YNyn]/', '', $value ); break; case 'link_target': // "enum" $targets = array( '_top', '_blank' ); if ( ! in_array( $value, $targets, true ) ) { $value = ''; } break; } if ( 'raw' === $context ) { return $value; } if ( 'edit' === $context ) { /** This filter is documented in wp-includes/post.php */ $value = apply_filters( "edit_{$field}", $value, $bookmark_id ); if ( 'link_notes' === $field ) { $value = esc_html( $value ); // textarea_escaped } else { $value = esc_attr( $value ); } } elseif ( 'db' === $context ) { /** This filter is documented in wp-includes/post.php */ $value = apply_filters( "pre_{$field}", $value ); } else { /** This filter is documented in wp-includes/post.php */ $value = apply_filters( "{$field}", $value, $bookmark_id, $context ); if ( 'attribute' === $context ) { $value = esc_attr( $value ); } elseif ( 'js' === $context ) { $value = esc_js( $value ); } } // Restore the type for integer fields after esc_attr(). if ( in_array( $field, $int_fields, true ) ) { $value = (int) $value; } return $value; } /** * Deletes the bookmark cache. * * @since 2.7.0 * * @param int $bookmark_id Bookmark ID. */ function clean_bookmark_cache( $bookmark_id ) { wp_cache_delete( $bookmark_id, 'bookmark' ); wp_cache_delete( 'get_bookmarks', 'bookmark' ); clean_object_term_cache( $bookmark_id, 'link' ); }
#pragma once /* * Copyright (C) 2005-2013 Team XBMC * http://xbmc.org * * This Program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This Program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with XBMC; see the file COPYING. If not, see * <http://www.gnu.org/licenses/>. * */ #include "BackgroundInfoLoader.h" #include "MusicDatabase.h" class CFileItemList; class CMusicThumbLoader; namespace MUSIC_INFO { class CMusicInfoLoader : public CBackgroundInfoLoader { public: CMusicInfoLoader(); virtual ~CMusicInfoLoader(); void UseCacheOnHD(const CStdString& strFileName); virtual bool LoadItem(CFileItem* pItem); virtual bool LoadItemCached(CFileItem* pItem); virtual bool LoadItemLookup(CFileItem* pItem); static bool LoadAdditionalTagInfo(CFileItem* pItem); protected: virtual void OnLoaderStart(); virtual void OnLoaderFinish(); void LoadCache(const CStdString& strFileName, CFileItemList& items); void SaveCache(const CStdString& strFileName, CFileItemList& items); protected: CStdString m_strCacheFileName; CFileItemList* m_mapFileItems; MAPSONGS m_songsMap; CStdString m_strPrevPath; CMusicDatabase m_musicDatabase; unsigned int m_databaseHits; unsigned int m_tagReads; CMusicThumbLoader *m_thumbLoader; }; }
DROP TABLE IF EXISTS `server_processes`; CREATE TABLE `server_processes` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `pid` int(11) unsigned NOT NULL, `type` enum('mri_upload') NOT NULL, `stdout_file` varchar(255) DEFAULT NULL, `stderr_file` varchar(255) DEFAULT NULL, `exit_code_file` varchar(255) DEFAULT NULL, `exit_code` varchar(255) DEFAULT NULL, `userid` varchar(255) NOT NULL, `start_time` timestamp NULL, `end_time` timestamp NULL, `exit_text` text DEFAULT NULL, PRIMARY KEY (`id`), KEY `FK_task_1` (`userid`), CONSTRAINT `FK_task_1` FOREIGN KEY (`userid`) REFERENCES `users` (`UserID`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; INSERT INTO permissions (code,description,categoryID) VALUES ('server_processes_manager','View and manage server processes','2'); INSERT INTO user_perm_rel (userID, permID) VALUES (1, (SELECT permID FROM permissions WHERE code = 'server_processes_manager')); INSERT INTO LorisMenu (Parent, Label, Link, Visible, OrderNumber) VALUES (6, 'Server Processes Manager', 'main.php?test_name=server_processes_manager', NULL, 6); INSERT INTO LorisMenuPermissions (MenuID, PermID) SELECT m.ID, p.PermID FROM permissions p CROSS JOIN LorisMenu m WHERE p.code='server_processes_manager' AND m.Label='Server Processes Manager';
package fastly import ( "fmt" "reflect" "sort" "testing" "github.com/hashicorp/terraform/helper/acctest" "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/terraform" gofastly "github.com/sethvargo/go-fastly" ) func TestFastlyServiceV1_BuildHeaders(t *testing.T) { cases := []struct { remote *gofastly.CreateHeaderInput local map[string]interface{} }{ { remote: &gofastly.CreateHeaderInput{ Name: "someheadder", Action: gofastly.HeaderActionDelete, IgnoreIfSet: gofastly.CBool(true), Type: gofastly.HeaderTypeCache, Destination: "http.aws-id", Priority: uint(100), }, local: map[string]interface{}{ "name": "someheadder", "action": "delete", "ignore_if_set": true, "destination": "http.aws-id", "priority": 100, "source": "", "regex": "", "substitution": "", "request_condition": "", "cache_condition": "", "response_condition": "", "type": "cache", }, }, { remote: &gofastly.CreateHeaderInput{ Name: "someheadder", Action: gofastly.HeaderActionSet, IgnoreIfSet: gofastly.CBool(false), Type: gofastly.HeaderTypeCache, Destination: "http.aws-id", Priority: uint(100), Source: "http.server-name", }, local: map[string]interface{}{ "name": "someheadder", "action": "set", "ignore_if_set": false, "destination": "http.aws-id", "priority": 100, "source": "http.server-name", "regex": "", "substitution": "", "request_condition": "", "cache_condition": "", "response_condition": "", "type": "cache", }, }, } for _, c := range cases { out, _ := buildHeader(c.local) if !reflect.DeepEqual(out, c.remote) { t.Fatalf("Error matching:\nexpected: %#v\ngot: %#v", c.remote, out) } } } func TestAccFastlyServiceV1_headers_basic(t *testing.T) { var service gofastly.ServiceDetail name := fmt.Sprintf("tf-test-%s", acctest.RandString(10)) domainName1 := fmt.Sprintf("%s.notadomain.com", acctest.RandString(10)) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckServiceV1Destroy, Steps: []resource.TestStep{ resource.TestStep{ Config: testAccServiceV1HeadersConfig(name, domainName1), Check: resource.ComposeTestCheckFunc( testAccCheckServiceV1Exists("fastly_service_v1.foo", &service), testAccCheckFastlyServiceV1HeaderAttributes(&service, name, []string{"http.x-amz-request-id", "http.Server"}, nil), resource.TestCheckResourceAttr( "fastly_service_v1.foo", "name", name), resource.TestCheckResourceAttr( "fastly_service_v1.foo", "header.#", "2"), ), }, resource.TestStep{ Config: testAccServiceV1HeadersConfig_update(name, domainName1), Check: resource.ComposeTestCheckFunc( testAccCheckServiceV1Exists("fastly_service_v1.foo", &service), testAccCheckFastlyServiceV1HeaderAttributes(&service, name, []string{"http.x-amz-request-id", "http.Server"}, []string{"http.server-name"}), resource.TestCheckResourceAttr( "fastly_service_v1.foo", "name", name), resource.TestCheckResourceAttr( "fastly_service_v1.foo", "header.#", "3"), resource.TestCheckResourceAttr( "fastly_service_v1.foo", "header.1147514417.source", "server.identity"), ), }, }, }) } func testAccCheckFastlyServiceV1HeaderAttributes(service *gofastly.ServiceDetail, name string, headersDeleted, headersAdded []string) resource.TestCheckFunc { return func(s *terraform.State) error { if service.Name != name { return fmt.Errorf("Bad name, expected (%s), got (%s)", name, service.Name) } conn := testAccProvider.Meta().(*FastlyClient).conn headersList, err := conn.ListHeaders(&gofastly.ListHeadersInput{ Service: service.ID, Version: service.ActiveVersion.Number, }) if err != nil { return fmt.Errorf("[ERR] Error looking up Headers for (%s), version (%s): %s", service.Name, service.ActiveVersion.Number, err) } var deleted []string var added []string for _, h := range headersList { if h.Action == gofastly.HeaderActionDelete { deleted = append(deleted, h.Destination) } if h.Action == gofastly.HeaderActionSet { added = append(added, h.Destination) } } sort.Strings(headersAdded) sort.Strings(headersDeleted) sort.Strings(deleted) sort.Strings(added) if !reflect.DeepEqual(headersDeleted, deleted) { return fmt.Errorf("Deleted Headers did not match.\n\tExpected: (%#v)\n\tGot: (%#v)", headersDeleted, deleted) } if !reflect.DeepEqual(headersAdded, added) { return fmt.Errorf("Added Headers did not match.\n\tExpected: (%#v)\n\tGot: (%#v)", headersAdded, added) } return nil } } func testAccServiceV1HeadersConfig(name, domain string) string { return fmt.Sprintf(` resource "fastly_service_v1" "foo" { name = "%s" domain { name = "%s" comment = "tf-testing-domain" } backend { address = "aws.amazon.com" name = "amazon docs" } header { destination = "http.x-amz-request-id" type = "cache" action = "delete" name = "remove x-amz-request-id" } header { destination = "http.Server" type = "cache" action = "delete" name = "remove s3 server" ignore_if_set = "true" } force_destroy = true }`, name, domain) } func testAccServiceV1HeadersConfig_update(name, domain string) string { return fmt.Sprintf(` resource "fastly_service_v1" "foo" { name = "%s" domain { name = "%s" comment = "tf-testing-domain" } backend { address = "aws.amazon.com" name = "amazon docs" } header { destination = "http.x-amz-request-id" type = "cache" action = "delete" name = "remove x-amz-request-id" } header { destination = "http.Server" type = "cache" action = "delete" name = "DESTROY S3" } header { destination = "http.server-name" type = "request" action = "set" source = "server.identity" name = "Add server name" } force_destroy = true }`, name, domain) }
<?php /** * This file is part of the OpenPNE package. * (c) OpenPNE Project (http://www.openpne.jp/) * * For the full copyright and license information, please view the LICENSE * file and the NOTICE file that were distributed with this source code. */ /** * csrfError action. * * @package OpenPNE * @subpackage default * @author Kousuke Ebihara <ebihara@tejimaya.com> */ class csrfErrorAction extends sfAction { public function execute($request) { } }
/* * Copyright 2000-2009 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. */ /* * User: anna * Date: 09-Feb-2009 */ package com.intellij.projectImport; import com.intellij.ide.util.PropertiesComponent; import com.intellij.ide.util.projectWizard.WizardContext; import com.intellij.openapi.components.StorageScheme; import com.intellij.openapi.project.Project; import javax.swing.*; public class ProjectFormatPanel { private static final String STORAGE_FORMAT_PROPERTY = "default.storage.format"; public static final String DIR_BASED = Project.DIRECTORY_STORE_FOLDER + " (directory based)"; private static final String FILE_BASED = ".ipr (file based)"; private JComboBox myStorageFormatCombo; private JPanel myWholePanel; public ProjectFormatPanel() { myStorageFormatCombo.insertItemAt(DIR_BASED, 0); myStorageFormatCombo.insertItemAt(FILE_BASED, 1); myStorageFormatCombo.setSelectedItem(PropertiesComponent.getInstance().getOrInit(STORAGE_FORMAT_PROPERTY, DIR_BASED)); } public JPanel getPanel() { return myWholePanel; } public JComboBox getStorageFormatComboBox() { return myStorageFormatCombo; } public void updateData(WizardContext context) { StorageScheme format = FILE_BASED.equals(myStorageFormatCombo.getSelectedItem()) ? StorageScheme.DEFAULT : StorageScheme.DIRECTORY_BASED; context.setProjectStorageFormat(format); setDefaultFormat(isDefault()); } public static void setDefaultFormat(boolean aDefault) { PropertiesComponent.getInstance().setValue(STORAGE_FORMAT_PROPERTY, aDefault ? FILE_BASED : DIR_BASED); } public void setVisible(boolean visible) { myWholePanel.setVisible(visible); } public boolean isDefault() { return FILE_BASED.equals(myStorageFormatCombo.getSelectedItem()); } }
/******************************************************************************* * Copyright (c) 2006 Oracle Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Oracle Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.bpel.common.ui.assist; import org.eclipse.jface.fieldassist.IContentProposalProvider; import org.eclipse.jface.fieldassist.IControlContentAdapter; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.widgets.Control; import org.eclipse.ui.fieldassist.ContentAssistCommandAdapter; /** * This is a field assist adapter which extends the core SWT content * assist adapter and allows programmatic opening of the assist dialog * as well as automatic width sizing. * * @author Michal Chmielewski (michal.chmielewski@oracle.com) * @date Aug 9, 2006 * */ public class FieldAssistAdapter extends ContentAssistCommandAdapter { /** * @param control * @param controlContentAdapter * @param proposalProvider * @param commandId * @param autoActivationCharacters */ public FieldAssistAdapter(Control control, IControlContentAdapter controlContentAdapter, IContentProposalProvider proposalProvider, String commandId, char[] autoActivationCharacters) { super(control, controlContentAdapter, proposalProvider, commandId, autoActivationCharacters); } /** * @param control * @param controlContentAdapter * @param proposalProvider * @param commandId * @param autoActivationCharacters * @param installDecoration */ public FieldAssistAdapter(Control control, IControlContentAdapter controlContentAdapter, IContentProposalProvider proposalProvider, String commandId, char[] autoActivationCharacters, boolean installDecoration) { super(control, controlContentAdapter, proposalProvider, commandId, autoActivationCharacters, installDecoration); } public void openProposals () { openProposalPopup(); getControl().setFocus(); } @Override protected void openProposalPopup () { Point popupSize = getPopupSize(); popupSize.x = getProposalWidth(); super.openProposalPopup(); } public int getProposalWidth () { Point size = getControl().getSize(); return size.x + 20; } }
package org.nutz.dao.test.meta; import org.nutz.dao.entity.annotation.Column; import org.nutz.dao.entity.annotation.Id; import org.nutz.dao.entity.annotation.Readonly; import org.nutz.dao.entity.annotation.Table; @Table("t_simple_pojo") public class SimplePOJO { @Id private long id; @Column @Readonly private String name; @Column private String sex; public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
/*<license> Copyright 2004 - $Date$ by PeopleWare n.v.. 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. </license>*/ package org.ppwcode.vernacular.semantics_VI.bean.stubs; public class StubRousseauBeanB extends StubRousseauBean { private StubRousseauBeanA $property8; public final StubRousseauBeanA getProperty8() { return $property8; } public final void setProperty8(StubRousseauBeanA property8) { $property8 = property8; } @Override public int nrOfProperties() { return 6; } }
// run-pass pub fn main() { let f = |(x, y): (isize, isize)| { assert_eq!(x, 1); assert_eq!(y, 2); }; f((1, 2)); }
/* * * Paros and its related class files. * * Paros is an HTTP/HTTPS proxy for assessing web application security. * Copyright (C) 2003-2004 Chinotec Technologies Company * * This program is free software; you can redistribute it and/or * modify it under the terms of the Clarified Artistic License * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * Clarified Artistic License for more details. * * You should have received a copy of the Clarified Artistic License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ // ZAP: 2011/08/04 Changed for cleanup // ZAP: 2011/11/20 Set order // ZAP: 2012/03/15 Changed to reset the message of the ManualRequestEditorDialog // when a new session is created. Added the key configuration to the // ManualRequestEditorDialog. // ZAP: 2012/03/17 Issue 282 Added getAuthor() // ZAP: 2012/04/25 Added @Override annotation to all appropriate methods. // ZAP: 2012/07/02 ManualRequestEditorDialog changed to receive Message instead // of HttpMessage. Changed logger to static. // ZAP: 2012/07/29 Issue 43: added sessionScopeChanged event // ZAP: 2012/08/01 Issue 332: added support for Modes // ZAP: 2012/11/21 Heavily refactored extension to support non-HTTP messages. // ZAP: 2013/01/25 Added method removeManualSendEditor(). // ZAP: 2013/02/06 Issue 499: NullPointerException while uninstalling an add-on // with a manual request editor // ZAP: 2014/03/23 Issue 1094: Change ExtensionManualRequestEditor to only add view components if in GUI mode // ZAP: 2014/08/14 Issue 1292: NullPointerException while attempting to remove an unregistered ManualRequestEditorDialog // ZAP: 2014/12/12 Issue 1449: Added help button // ZAP: 2015/03/16 Issue 1525: Further database independence changes package org.parosproxy.paros.extension.manualrequest; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import org.parosproxy.paros.Constant; import org.parosproxy.paros.control.Control; import org.parosproxy.paros.control.Control.Mode; import org.parosproxy.paros.extension.ExtensionAdaptor; import org.parosproxy.paros.extension.ExtensionHook; import org.parosproxy.paros.extension.ExtensionLoader; import org.parosproxy.paros.extension.SessionChangedListener; import org.parosproxy.paros.extension.ViewDelegate; import org.parosproxy.paros.extension.manualrequest.http.impl.ManualHttpRequestEditorDialog; import org.parosproxy.paros.model.Session; import org.zaproxy.zap.extension.httppanel.Message; public class ExtensionManualRequestEditor extends ExtensionAdaptor implements SessionChangedListener { private Map<Class<? extends Message>, ManualRequestEditorDialog> dialogues = new HashMap<>(); /** * Name of this extension. */ public static final String NAME = "ExtensionManualRequest"; public ExtensionManualRequestEditor() { super(); initialize(); } public ExtensionManualRequestEditor(String name) { super(name); } private void initialize() { this.setName(NAME); this.setOrder(36); } @Override public void initView(ViewDelegate view) { super.initView(view); // add default manual request editor ManualRequestEditorDialog httpSendEditorDialog = new ManualHttpRequestEditorDialog(true, "manual", "ui.dialogs.manreq"); httpSendEditorDialog.setTitle(Constant.messages.getString("manReq.dialog.title")); addManualSendEditor(httpSendEditorDialog); } /** * Should be called before extension is initialized via its * {@link #hook(ExtensionHook)} method. * * @param dialogue */ public void addManualSendEditor(ManualRequestEditorDialog dialogue) { dialogues.put(dialogue.getMessageType(), dialogue); } public void removeManualSendEditor(Class<? extends Message> messageType) { // remove from list ManualRequestEditorDialog dialogue = dialogues.remove(messageType); if (dialogue != null) { // remove from GUI dialogue.clear(); dialogue.dispose(); if (getView() != null) { // unload menu items ExtensionLoader extLoader = Control.getSingleton().getExtensionLoader(); extLoader.removeToolsMenuItem(dialogue.getMenuItem()); } } } /** * Get special manual send editor to add listeners, etc. * * @param type * @return */ public ManualRequestEditorDialog getManualSendEditor(Class<? extends Message> type) { return dialogues.get(type); } @Override public void hook(ExtensionHook extensionHook) { super.hook(extensionHook); if (getView() != null) { for (Entry<Class<? extends Message>, ManualRequestEditorDialog> dialogue : dialogues.entrySet()) { extensionHook.getHookMenu().addToolsMenuItem(dialogue.getValue().getMenuItem()); } extensionHook.addSessionListener(this); } } @Override public String getAuthor() { return Constant.PAROS_TEAM; } @Override public void sessionChanged(Session session) { for (Entry<Class<? extends Message>, ManualRequestEditorDialog> dialogue : dialogues.entrySet()) { dialogue.getValue().clear(); dialogue.getValue().setDefaultMessage(); } } @Override public void sessionAboutToChange(Session session) { } @Override public void sessionScopeChanged(Session session) { } @Override public void sessionModeChanged(Mode mode) { Boolean isEnabled = null; switch (mode) { case safe: isEnabled = false; break; case protect: case standard: case attack: isEnabled = true; break; } if (isEnabled != null) { for (Entry<Class<? extends Message>, ManualRequestEditorDialog> dialog : dialogues.entrySet()) { dialog.getValue().setEnabled(isEnabled); } } } /** * No database tables used, so all supported */ @Override public boolean supportsDb(String type) { return true; } }
//// [invalidThisEmitInContextualObjectLiteral.ts] interface IDef { p1: (e:string) => void; p2: () => (n: number) => any; } class TestController { public m(def: IDef) { } public p = this.m({ p1: e => { }, p2: () => { return vvvvvvvvv => this; }, }); } //// [invalidThisEmitInContextualObjectLiteral.js] var TestController = (function () { function TestController() { var _this = this; this.p = this.m({ p1: function (e) { }, p2: function () { return function (vvvvvvvvv) { return _this; }; } }); } TestController.prototype.m = function (def) { }; return TestController; }());
#! /bin/sh # # runlex.sh # Script to run Lex/Flex. # First argument is the (quoted) name of the command; if it's null, that # means that neither Flex nor Lex was found, so we report an error and # quit. # # # Get the name of the command to run, and then shift to get the arguments. # if [ $# -eq 0 ] then echo "Usage: runlex <lex/flex command to run> [ arguments ]" 1>&2 exit 1 fi LEX="$1" shift # # Check whether we have Lex or Flex. # if [ -z "${LEX}" ] then echo "Neither lex nor flex was found" 1>&2 exit 1 fi # # Process the flags. We don't use getopt because we don't want to # embed complete knowledge of what options are supported by Lex/Flex. # flags="" outfile=lex.yy.c while [ $# -ne 0 ] do case "$1" in -o*) # # Set the output file name. # outfile=`echo "$1" | sed 's/-o\(.*\)/\1/'` ;; -*) # # Add this to the list of flags. # flags="$flags $1" ;; --|*) # # End of flags. # break ;; esac shift done # # Is it Lex, or is it Flex? # if [ "${LEX}" = flex ] then # # It's Flex. # have_flex=yes # # Does it support the --noFUNCTION options? If so, we pass # --nounput, as at least some versions that support those # options don't support disabling yyunput by defining # YY_NO_UNPUT. # if flex --help | egrep noFUNCTION >/dev/null then flags="$flags --nounput" # # Does it support -R, for generating reentrant scanners? # If so, we're not currently using that feature, but # it'll generate some unused functions anyway - and there # won't be any header file declaring them, so there'll be # defined-but-not-declared warnings. Therefore, we use # --noFUNCTION options to suppress generating those # functions. # if flex --help | egrep reentrant >/dev/null then flags="$flags --noyyget_lineno --noyyget_in --noyyget_out --noyyget_leng --noyyget_text --noyyset_lineno --noyyset_in --noyyset_out" fi fi else # # It's Lex. # have_flex=no fi # # OK, run it. # If it's lex, it doesn't support -o, so we just write to # lex.yy.c and, if it succeeds, rename it to the right name, # otherwise we remove lex.yy.c. # If it's flex, it supports -o, so we use that - flex with -P doesn't # write to lex.yy.c, it writes to a lex.{prefix from -P}.c. # if [ $have_flex = yes ] then ${LEX} $flags -o"$outfile" "$@" # # Did it succeed? # status=$? if [ $status -ne 0 ] then # # No. Exit with the failing exit status. # exit $status fi # # Flex has the annoying habit of stripping all but the last # component of the "-o" flag argument and using that as the # place to put the output. This gets in the way of building # in a directory different from the source directory. Try # to work around this. # # Is the outfile where we think it is? # outfile_base=`basename "$outfile"` if [ "$outfile_base" != "$outfile" -a \( ! -r "$outfile" \) -a -r "$outfile_base" ] then # # No, it's not, but it is in the current directory. Put it # where it's supposed to be. # mv "$outfile_base" "$outfile" # # Did that succeed? # status=$? if [ $status -ne 0 ] then # # No. Exit with the failing exit status. # exit $status fi fi else ${LEX} $flags "$@" # # Did it succeed? # status=$? if [ $status -ne 0 ] then # # No. Get rid of any lex.yy.c file we generated, and # exit with the failing exit status. # rm -f lex.yy.c exit $status fi # # OK, rename lex.yy.c to the right output file. # mv lex.yy.c "$outfile" # # Did that succeed? # status=$? if [ $status -ne 0 ] then # # No. Get rid of any lex.yy.c file we generated, and # exit with the failing exit status. # rm -f lex.yy.c exit $status fi fi # # OK, now let's generate a header file declaring the relevant functions # defined by the .c file; if the .c file is .../foo.c, the header file # will be .../foo.h. # # This works around some other Flex suckage, wherein it doesn't declare # the lex routine before defining it, causing compiler warnings. # XXX - newer versions of Flex support --header-file=, to generate the # appropriate header file. With those versions, we should use that option. # # # Get the name of the prefix; scan the source files for a %option prefix # line. We use the last one. # prefix=`sed -n 's/%option[ ][ ]*prefix="\(.*\)".*/\1/p' "$@" | tail -1` if [ ! -z "$prefix" ] then prefixline="#define yylex ${prefix}lex" fi # # Construct the name of the header file. # header_file=`dirname "$outfile"`/`basename "$outfile" .c`.h # # Spew out the declaration. # cat <<EOF >$header_file /* This is generated by runlex.sh. Do not edit it. */ $prefixline #ifndef YY_DECL #define YY_DECL int yylex(void) #endif YY_DECL; EOF
/* * Copyright (c) 2013 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.cloud.backend.spi; import com.google.appengine.api.prospectivesearch.ProspectiveSearchService; import com.google.appengine.api.prospectivesearch.ProspectiveSearchServiceFactory; import com.google.appengine.api.taskqueue.Queue; import com.google.appengine.api.taskqueue.QueueFactory; import com.google.appengine.api.taskqueue.TaskOptions; import com.google.cloud.backend.config.StringUtility; import com.google.gson.Gson; import java.util.Arrays; import java.util.List; import java.util.Set; import java.util.logging.Logger; /** * Utility class with helper functions to decode subscription information and handle * Prospective Search API. */ public class SubscriptionUtility { protected static final String IOS_DEVICE_PREFIX = "ios_"; protected static final String GCM_KEY_SUBID = "subId"; protected static final String REQUEST_TYPE_DEVICE_SUB = "deviceSubscriptionRequest"; protected static final String REQUEST_TYPE_PSI_SUB = "PSISubscriptionRequest"; /** * A key word to indicate "query" type in Prospective Search API subscription id. */ public static final String GCM_TYPEID_QUERY = "query"; private static final ProspectiveSearchService prosSearch = ProspectiveSearchServiceFactory .getProspectiveSearchService(); private static final Logger log = Logger.getLogger(SubscriptionUtility.class.getName()); /** * An enumeration of supported mobile device type. */ public enum MobileType { ANDROID, IOS } /** * Gets the mobile type based on the subscription id provided by client. * * Subscription id is in format of <device token>:GCM_TYPEID_QUERY:<topic>. Clients prefix * device token with "ios_" if the mobile type is "iOS", while Android device * token does not have any prefix. * * @param subId Subscription ID sent by client during query subscription * @return Mobile type */ public static MobileType getMobileType(String subId) { return (subId.startsWith(IOS_DEVICE_PREFIX)) ? MobileType.IOS : MobileType.ANDROID; } /** * Extracts device registration id from subscription id. * * @param subId Subscription id sent by client during query subscription * @return Device registration id */ public static String extractRegId(String subId) { if (StringUtility.isNullOrEmpty(subId)) { throw new IllegalArgumentException("subId cannot be null or empty"); } String[] tokens = subId.split(":"); return tokens[0].replaceFirst(IOS_DEVICE_PREFIX, ""); } /** * Extracts device registration id from subscription id. * * @param subId Subscription id sent by client during query subscription * @return Device registration id as List */ public static List<String> extractRegIdAsList(String subId) { return Arrays.asList(extractRegId(subId)); } /** * Constructs subscription id based on registration id and query id. * * @param regId Registration id provided by the client * @param queryId Query id provided by the client * @return */ public static String constructSubId(String regId, String queryId) { if (StringUtility.isNullOrEmpty(regId) || StringUtility.isNullOrEmpty(queryId)) { throw new IllegalArgumentException("regId and queryId cannot be null or empty"); } // ProsSearch subId = <regId>:query:<clientSubId> return regId + ":" + GCM_TYPEID_QUERY + ":" + queryId; } /** * Clears Prospective Search API subscription and device subscription entity for listed devices. * * @param deviceIds A list of device ids for which subscriptions are to be removed */ public static void clearSubscriptionAndDeviceEntity(List<String> deviceIds) { DeviceSubscription deviceSubscription = new DeviceSubscription(); for (String deviceId : deviceIds) { Set<String> subIds = deviceSubscription.getSubscriptionIds(deviceId); // Delete all subscriptions for the device from Prospective Search API for (String subId : subIds) { try { prosSearch.unsubscribe(QueryOperations.PROS_SEARCH_DEFAULT_TOPIC, subId); } catch (IllegalArgumentException e) { log.warning("Unsubscribe " + subId + " from PSI encounters error, " + e.getMessage()); } } // Remove device from datastore deviceSubscription.delete(deviceId); } } /** * Clears Prospective Search API subscription and removes device entity for all devices. */ public static void clearAllSubscriptionAndDeviceEntity() { // Remove all device subscription and psi subscription DeviceSubscription deviceSubscription = new DeviceSubscription(); deviceSubscription.enqueueDeleteDeviceSubscription(); } /** * Enqueues subscription ids in task queue for deletion. * * @param subIds Psi subscription ids to be deleted */ protected static void enqueueDeletePsiSubscription(String[] subIds) { Queue deviceTokenCleanupQueue = QueueFactory.getQueue("subscription-removal"); deviceTokenCleanupQueue.add(TaskOptions.Builder.withMethod(TaskOptions.Method.POST) .url("/admin/push/devicesubscription/delete") .param("subIds", new Gson().toJson(subIds, String[].class)) .param("type", SubscriptionUtility.REQUEST_TYPE_PSI_SUB)); } }
cask "osirix-quicklook" do version "6.0" sha256 :no_check url "https://www.osirix-viewer.com/Museum/OsiriXQuickLookInstaller.zip" name "OsiriX DICOM QuickLook" homepage "https://www.osirix-viewer.com/" pkg "OsiriXQuickLookInstaller.pkg" uninstall pkgutil: "com.pixmeo.osirix.osirixQuicklookPlugin.OsiriXQuickLookPlugin.pkg" end
cask 'sqlworkbenchj' do version '119' sha256 '8565105504e517ca972b4f3c99f4436b13e7a3caaf8f53a97f44a71a7c71efc6' url "http://www.sql-workbench.net/archive/Workbench-Build#{version}-MacJava8.tgz" name 'SQL Workbench/J' homepage 'http://www.sql-workbench.net' license :apache app 'SQLWorkbenchJ.app' caveats do depends_on_java end end
<!DOCTYPE html> <title>Image source selection using media queries is performed for img elements outside the document</title> <link rel="help" href="https://html.spec.whatwg.org/#reacting-to-environment-changes"> <link rel="help" href="https://html.spec.whatwg.org/#reacting-to-dom-mutations"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <iframe width="350" height="100" onload="async_test(this.contentWindow.run)" srcdoc=" <!DOCTYPE html> <script> const { assert_equals } = parent; const iframe = parent.document.querySelector('iframe'); function run(t) { const picture = document.createElement('picture'); const source1 = document.createElement('source'); source1.setAttribute('media', '(min-width: 300px)'); source1.setAttribute('srcset', 'data:,a'); picture.append(source1); const source2 = document.createElement('source'); source2.setAttribute('media', '(min-width: 200px)'); source2.setAttribute('srcset', 'data:,b'); picture.append(source2); const img = document.createElement('img'); img.src = 'data:,c'; picture.append(img); queueMicrotask(t.step_func(function() { assert_equals(img.currentSrc, 'data:,a', 'Initial currentSrc value'); matchMedia(source1.media).addEventListener( 'change', function() { queueMicrotask(t.step_func(function() { assert_equals(img.currentSrc, 'data:,b', 'After MQ change'); img.remove(); queueMicrotask(t.step_func(function() { assert_equals(img.currentSrc, 'data:,c', 'After removing img'); t.done(); })); })); }, { once: true } ); iframe.width = 250; })); } </script> "></iframe>
#!/bin/bash cp test-infra/npm-shrinkwrap.canonical.json npm-shrinkwrap.json npm install rm npm-shrinkwrap.json
<!DOCTYPE html> <!-- Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ --> <html> <head> <meta charset="utf-8"> <title>CSS Test: 'object-fit: scale-down' on embed element, with a PNG image and with various 'object-position' values</title> <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com"> <link rel="help" href="http://www.w3.org/TR/css3-images/#sizing"> <link rel="help" href="http://www.w3.org/TR/css3-images/#the-object-fit"> <link rel="help" href="http://www.w3.org/TR/css3-images/#the-object-position"> <link rel="match" href="object-fit-scale-down-png-002-ref.html"> <style type="text/css"> embed { border: 1px dashed gray; padding: 1px; object-fit: scale-down; image-rendering: crisp-edges; float: left; } .bigWide { width: 48px; height: 32px; } .bigTall { width: 32px; height: 48px; } .small { width: 8px; height: 8px; } br { clear: both; } .tr { object-position: top right } .bl { object-position: bottom left } .tl { object-position: top 25% left 25% } .br { object-position: bottom 1px right 2px } .tc { object-position: top 3px left 50% } .cr { object-position: top 50% right 25% } </style> </head> <body> <!-- big/wide: --> <embed src="support/colors-8x16.png" class="bigWide tr"> <embed src="support/colors-8x16.png" class="bigWide bl"> <embed src="support/colors-8x16.png" class="bigWide tl"> <embed src="support/colors-8x16.png" class="bigWide br"> <embed src="support/colors-8x16.png" class="bigWide tc"> <embed src="support/colors-8x16.png" class="bigWide cr"> <embed src="support/colors-8x16.png" class="bigWide"> <br> <!-- big/tall: --> <embed src="support/colors-8x16.png" class="bigTall tr"> <embed src="support/colors-8x16.png" class="bigTall bl"> <embed src="support/colors-8x16.png" class="bigTall tl"> <embed src="support/colors-8x16.png" class="bigTall br"> <embed src="support/colors-8x16.png" class="bigTall tc"> <embed src="support/colors-8x16.png" class="bigTall cr"> <embed src="support/colors-8x16.png" class="bigTall"> <br> <!-- small: --> <embed src="support/colors-8x16.png" class="small tr"> <embed src="support/colors-8x16.png" class="small bl"> <embed src="support/colors-8x16.png" class="small tl"> <embed src="support/colors-8x16.png" class="small br"> <embed src="support/colors-8x16.png" class="small tc"> <embed src="support/colors-8x16.png" class="small cr"> <embed src="support/colors-8x16.png" class="small"> <br> </body> </html>
/* Copyright 2013 Google Inc. All Rights Reserved. Distributed under MIT license. See file LICENSE for detail or copy at https://opensource.org/licenses/MIT */ /* Data model for a font file in sfnt format, reading and writing functions and accessors for the glyph data. */ #ifndef WOFF2_FONT_H_ #define WOFF2_FONT_H_ #include <stddef.h> #include <inttypes.h> #include <map> #include <vector> namespace woff2 { // Represents an sfnt font file. Only the table directory is parsed, for the // table data we only store a raw pointer, therefore a font object is valid only // as long the data from which it was parsed is around. struct Font { uint32_t flavor; uint16_t num_tables; struct Table { uint32_t tag; uint32_t checksum; uint32_t offset; uint32_t length; const uint8_t* data; // Buffer used to mutate the data before writing out. std::vector<uint8_t> buffer; // If we've seen this tag/offset before, pointer to the first time we saw it // If this is the first time we've seen this table, NULL // Intended use is to bypass re-processing tables Font::Table* reuse_of; uint8_t flag_byte; // Is this table reused by a TTC bool IsReused() const; }; std::map<uint32_t, Table> tables; std::vector<uint32_t> OutputOrderedTags() const; Table* FindTable(uint32_t tag); const Table* FindTable(uint32_t tag) const; }; // Accomodates both singular (OTF, TTF) and collection (TTC) fonts struct FontCollection { uint32_t flavor; uint32_t header_version; // (offset, first use of table*) pairs std::map<uint32_t, Font::Table*> tables; std::vector<Font> fonts; }; // Parses the font from the given data. Returns false on parsing failure or // buffer overflow. The font is valid only so long the input data pointer is // valid. Does NOT support collections. bool ReadFont(const uint8_t* data, size_t len, Font* font); // Parses the font from the given data. Returns false on parsing failure or // buffer overflow. The font is valid only so long the input data pointer is // valid. Supports collections. bool ReadFontCollection(const uint8_t* data, size_t len, FontCollection* fonts); // Returns the file size of the font. size_t FontFileSize(const Font& font); size_t FontCollectionFileSize(const FontCollection& font); // Writes the font into the specified dst buffer. The dst_size should be the // same as returned by FontFileSize(). Returns false upon buffer overflow (which // should not happen if dst_size was computed by FontFileSize()). bool WriteFont(const Font& font, uint8_t* dst, size_t dst_size); // Write the font at a specific offset bool WriteFont(const Font& font, size_t* offset, uint8_t* dst, size_t dst_size); bool WriteFontCollection(const FontCollection& font_collection, uint8_t* dst, size_t dst_size); // Returns the number of glyphs in the font. // NOTE: Currently this works only for TrueType-flavored fonts, will return // zero for CFF-flavored fonts. int NumGlyphs(const Font& font); // Returns the index format of the font int IndexFormat(const Font& font); // Sets *glyph_data and *glyph_size to point to the location of the glyph data // with the given index. Returns false if the glyph is not found. bool GetGlyphData(const Font& font, int glyph_index, const uint8_t** glyph_data, size_t* glyph_size); // Removes the digital signature (DSIG) table bool RemoveDigitalSignature(Font* font); } // namespace woff2 #endif // WOFF2_FONT_H_
# load-json-file [![Build Status](https://travis-ci.org/sindresorhus/load-json-file.svg?branch=master)](https://travis-ci.org/sindresorhus/load-json-file) > Read and parse a JSON file [Strips UTF-8 BOM](https://github.com/sindresorhus/strip-bom), uses [`graceful-fs`](https://github.com/isaacs/node-graceful-fs), and throws more [helpful JSON errors](https://github.com/sindresorhus/parse-json). ## Install ``` $ npm install --save load-json-file ``` ## Usage ```js const loadJsonFile = require('load-json-file'); loadJsonFile('foo.json').then(json => { console.log(json); //=> {foo: true} }); ``` ## API ### loadJsonFile(filepath) Returns a promise that resolves to the parsed JSON. ### loadJsonFile.sync(filepath) Returns the parsed JSON. ## Related - [write-json-file](https://github.com/sindresorhus/write-json-file) - Stringify and write JSON to a file atomically ## License MIT © [Sindre Sorhus](http://sindresorhus.com)
@IF EXIST "%~dp0\node.exe" ( "%~dp0\node.exe" "%~dp0\..\..\..\.0.5.0@jsesc\bin\jsesc" %* ) ELSE ( @SETLOCAL @SET PATHEXT=%PATHEXT:;.JS;=;% node "%~dp0\..\..\..\.0.5.0@jsesc\bin\jsesc" %* )
<span class="tooltip tip-{{placement}}" ng-class="{ in: isOpen(), fade: animation() }" style="width: auto"> <span ng-bind="content"></span> <span class="nub"></span> </span>
var leafletDirective = angular.module("leaflet-directive", []); leafletDirective.directive('leaflet', [ '$http', '$log', '$parse', '$rootScope', function ($http, $log, $parse, $rootScope) { var defaults = { maxZoom: 14, minZoom: 1, doubleClickZoom: true, tileLayer: 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', tileLayerOptions: { attribution: 'Tiles &copy; Open Street Maps' }, icon: { url: 'http://cdn.leafletjs.com/leaflet-0.5.1/images/marker-icon.png', retinaUrl: 'http://cdn.leafletjs.com/leaflet-0.5.1/images/marker-icon@2x.png', size: [25, 41], anchor: [12, 40], popup: [0, -40], shadow: { url: 'http://cdn.leafletjs.com/leaflet-0.5.1/images/marker-shadow.png', retinaUrl: 'http://cdn.leafletjs.com/leaflet-0.5.1/images/marker-shadow.png', size: [41, 41], anchor: [12, 40] } }, path: { weight: 10, opacity: 1, color: '#0000ff' } }; var str_inspect_hint = 'Add testing="testing" to <leaflet> tag to inspect this object'; return { restrict: "E", replace: true, transclude: true, scope: { center: '=center', maxBounds: '=maxbounds', bounds: '=bounds', marker: '=marker', markers: '=markers', defaults: '=defaults', paths: '=paths', tiles: '=tiles', events: '=events' }, template: '<div class="angular-leaflet-map"></div>', link: function ($scope, element, attrs /*, ctrl */) { var centerModel = { lat:$parse("center.lat"), lng:$parse("center.lng"), zoom:$parse("center.zoom") }; if (attrs.width) { element.css('width', attrs.width); } if (attrs.height) { element.css('height', attrs.height); } $scope.leaflet = {}; $scope.leaflet.maxZoom = !!(attrs.defaults && $scope.defaults && $scope.defaults.maxZoom) ? parseInt($scope.defaults.maxZoom, 10) : defaults.maxZoom; $scope.leaflet.minZoom = !!(attrs.defaults && $scope.defaults && $scope.defaults.minZoom) ? parseInt($scope.defaults.minZoom, 10) : defaults.minZoom; $scope.leaflet.doubleClickZoom = !!(attrs.defaults && $scope.defaults && (typeof($scope.defaults.doubleClickZoom) == "boolean") ) ? $scope.defaults.doubleClickZoom : defaults.doubleClickZoom; var map = new L.Map(element[0], { maxZoom: $scope.leaflet.maxZoom, minZoom: $scope.leaflet.minZoom, doubleClickZoom: $scope.leaflet.doubleClickZoom }); map.setView([0, 0], 1); $scope.leaflet.tileLayer = !!(attrs.defaults && $scope.defaults && $scope.defaults.tileLayer) ? $scope.defaults.tileLayer : defaults.tileLayer; $scope.leaflet.map = !!attrs.testing ? map : str_inspect_hint; setupTiles(); setupCenter(); setupMaxBounds(); setupBounds(); setupMainMaerker(); setupMarkers(); setupPaths(); setupEvents(); // use of leafletDirectiveSetMap event is not encouraged. only use // it when there is no easy way to bind data to the directive $scope.$on('leafletDirectiveSetMap', function(event, message) { var meth = message.shift(); map[meth].apply(map, message); }); $scope.safeApply = function(fn) { var phase = this.$root.$$phase; if (phase == '$apply' || phase == '$digest') { $scope.$eval(fn); } else { $scope.$apply(fn); } }; /* * Event setup watches for callbacks set in the parent scope * * $scope.events = { * dblclick: function(){ * // doThis() * }, * click: function(){ * // doThat() * } * } * */ function setupEvents(){ if ( typeof($scope.events) != 'object'){ return false; }else{ for (var bind_to in $scope.events){ map.on(bind_to,$scope.events[bind_to]); } } } function setupTiles(){ // TODO build custom object for tiles, actually only the tile string if ($scope.defaults && $scope.defaults.tileLayerOptions) { for (var key in $scope.defaults.tileLayerOptions) { defaults.tileLayerOptions[key] = $scope.defaults.tileLayerOptions[key]; } } if ($scope.tiles) { if ($scope.tiles.tileLayer) { $scope.leaflet.tileLayer = $scope.tiles.tileLayer; } if ($scope.tiles.tileLayerOptions.attribution) { defaults.tileLayerOptions.attribution = $scope.tiles.tileLayerOptions.attribution; } } var tileLayerObj = L.tileLayer( $scope.leaflet.tileLayer, defaults.tileLayerOptions); tileLayerObj.addTo(map); $scope.leaflet.tileLayerObj = !!attrs.testing ? tileLayerObj : str_inspect_hint; } function setupMaxBounds() { if (!$scope.maxBounds) { return; } if ($scope.maxBounds.southWest && $scope.maxBounds.southWest.lat && $scope.maxBounds.southWest.lng && $scope.maxBounds.northEast && $scope.maxBounds.northEast.lat && $scope.maxBounds.northEast.lng) { map.setMaxBounds( new L.LatLngBounds( new L.LatLng($scope.maxBounds.southWest.lat, $scope.maxBounds.southWest.lng), new L.LatLng($scope.maxBounds.northEast.lat, $scope.maxBounds.northEast.lng) ) ); $scope.$watch("maxBounds", function (maxBounds) { if (maxBounds.southWest && maxBounds.northEast && maxBounds.southWest.lat && maxBounds.southWest.lng && maxBounds.northEast.lat && maxBounds.northEast.lng) { map.setMaxBounds( new L.LatLngBounds( new L.LatLng(maxBounds.southWest.lat, maxBounds.southWest.lng), new L.LatLng(maxBounds.northEast.lat, maxBounds.northEast.lng) ) ); } }); } } function tryFitBounds(bounds) { if (bounds) { var southWest = bounds.southWest; var northEast = bounds.northEast; if (southWest && northEast && southWest.lat && southWest.lng && northEast.lat && northEast.lng) { var sw_latlng = new L.LatLng(southWest.lat, southWest.lng); var ne_latlng = new L.LatLng(northEast.lat, northEast.lng); map.fitBounds(new L.LatLngBounds(sw_latlng, ne_latlng)); } } } function setupBounds() { if (!$scope.bounds) { return; } $scope.$watch('bounds', function (new_bounds) { tryFitBounds(new_bounds); }); } function setupCenter() { $scope.$watch("center", function (center) { if (!center) { $log.warn("[AngularJS - Leaflet] 'center' is undefined in the current scope, did you forget to initialize it?"); return; } if (center.lat && center.lng && center.zoom) { map.setView([center.lat, center.lng], center.zoom); } else if (center.autoDiscover === true) { map.locate({ setView: true, maxZoom: $scope.leaflet.maxZoom }); } }, true); map.on("dragend", function (/* event */) { $scope.safeApply(function (scope) { centerModel.lat.assign(scope, map.getCenter().lat); centerModel.lng.assign(scope, map.getCenter().lng); }); }); map.on("zoomend", function (/* event */) { if(angular.isUndefined($scope.center)){ $log.warn("[AngularJS - Leaflet] 'center' is undefined in the current scope, did you forget to initialize it?"); } if (angular.isUndefined($scope.center) || $scope.center.zoom !== map.getZoom()) { $scope.safeApply(function (s) { centerModel.zoom.assign(s, map.getZoom()); centerModel.lat.assign(s, map.getCenter().lat); centerModel.lng.assign(s, map.getCenter().lng); }); } }); } function setupMainMaerker() { var main_marker; if (!$scope.marker) { return; } main_marker = createMarker('marker', $scope.marker, map); $scope.leaflet.marker = !!attrs.testing ? main_marker : str_inspect_hint; main_marker.on('click', function(e) { $rootScope.$broadcast('leafletDirectiveMainMarkerClick'); }); } function setupMarkers() { var markers = {}; $scope.leaflet.markers = !!attrs.testing ? markers : str_inspect_hint; if (!$scope.markers) { return; } function genMultiMarkersClickCallback(m_name) { return function(e) { $rootScope.$broadcast('leafletDirectiveMarkersClick', m_name); }; } for (var name in $scope.markers) { markers[name] = createMarker( 'markers.'+name, $scope.markers[name], map); markers[name].on('click', genMultiMarkersClickCallback(name)); } $scope.$watch('markers', function(newMarkers) { // Delete markers from the array for (var name in markers) { if (newMarkers[name] === undefined) { delete markers[name]; } } // add new markers for (var new_name in newMarkers) { if (markers[new_name] === undefined) { markers[new_name] = createMarker( 'markers.'+new_name, newMarkers[new_name], map); markers[new_name].on('click', genMultiMarkersClickCallback(new_name)); } } }, true); } function createMarker(scope_watch_name, marker_data, map) { var marker = buildMarker(marker_data); map.addLayer(marker); if (marker_data.focus === true) { marker.openPopup(); } marker.on("dragend", function () { $scope.safeApply(function (scope) { marker_data.lat = marker.getLatLng().lat; marker_data.lng = marker.getLatLng().lng; }); if (marker_data.message) { marker.openPopup(); } }); var clearWatch = $scope.$watch(scope_watch_name, function (data, old_data) { if (!data) { map.removeLayer(marker); clearWatch(); return; } if (old_data) { if (data.draggable !== undefined && data.draggable !== old_data.draggable) { if (data.draggable === true) { marker.dragging.enable(); } else { marker.dragging.disable(); } } if (data.focus !== undefined && data.focus !== old_data.focus) { if (data.focus === true) { marker.openPopup(); } else { marker.closePopup(); } } if (data.message !== undefined && data.message !== old_data.message) { marker.bindPopup(data); } if (data.lat !== old_data.lat || data.lng !== old_data.lng) { marker.setLatLng(new L.LatLng(data.lat, data.lng)); } if (data.icon && data.icon !== old_data.icon) { marker.setIcon(data.icon); } } }, true); return marker; } function buildMarker(data) { var micon = null; if (data.icon) { micon = data.icon; } else { micon = buildIcon(); } var marker = new L.marker(data, { icon: micon, draggable: data.draggable ? true : false } ); if (data.message) { marker.bindPopup(data.message); } return marker; } function buildIcon() { return L.icon({ iconUrl: defaults.icon.url, iconRetinaUrl: defaults.icon.retinaUrl, iconSize: defaults.icon.size, iconAnchor: defaults.icon.anchor, popupAnchor: defaults.icon.popup, shadowUrl: defaults.icon.shadow.url, shadowRetinaUrl: defaults.icon.shadow.retinaUrl, shadowSize: defaults.icon.shadow.size, shadowAnchor: defaults.icon.shadow.anchor }); } function setupPaths() { var paths = {}; $scope.leaflet.paths = !!attrs.testing ? paths : str_inspect_hint; if (!$scope.paths) { return; } $log.warn("[AngularJS - Leaflet] Creating polylines and adding them to the map will break the directive's scope's inspection in AngularJS Batarang"); for (var name in $scope.paths) { paths[name] = createPath(name, $scope.paths[name], map); } $scope.$watch("paths", function (newPaths) { for (var new_name in newPaths) { if (paths[new_name] === undefined) { paths[new_name] = createPath(new_name, newPaths[new_name], map); } } // Delete paths from the array for (var name in paths) { if (newPaths[name] === undefined) { delete paths[name]; } } }, true); } function createPath(name, scopePath, map) { var polyline = new L.Polyline([], { weight: defaults.path.weight, color: defaults.path.color, opacity: defaults.path.opacity }); if (scopePath.latlngs !== undefined) { var latlngs = convertToLeafletLatLngs(scopePath.latlngs); polyline.setLatLngs(latlngs); } if (scopePath.weight !== undefined) { polyline.setStyle({ weight: scopePath.weight }); } if (scopePath.color !== undefined) { polyline.setStyle({ color: scopePath.color }); } if (scopePath.opacity !== undefined) { polyline.setStyle({ opacity: scopePath.opacity }); } map.addLayer(polyline); var clearWatch = $scope.$watch('paths.' + name, function (data, oldData) { if (!data) { map.removeLayer(polyline); clearWatch(); return; } if (oldData) { if (data.latlngs !== undefined && data.latlngs !== oldData.latlngs) { var latlngs = convertToLeafletLatLngs(data.latlngs); polyline.setLatLngs(latlngs); } if (data.weight !== undefined && data.weight !== oldData.weight) { polyline.setStyle({ weight: data.weight }); } if (data.color !== undefined && data.color !== oldData.color) { polyline.setStyle({ color: data.color }); } if (data.opacity !== undefined && data.opacity !== oldData.opacity) { polyline.setStyle({ opacity: data.opacity }); } } }, true); return polyline; } function convertToLeafletLatLngs(latlngs) { var leafletLatLngs = latlngs.filter(function (latlng) { return !!latlng.lat && !!latlng.lng; }).map(function (latlng) { return new L.LatLng(latlng.lat, latlng.lng); }); return leafletLatLngs; } } }; }]);
#! /bin/sh if [ -z "$1" ]; then echo "specify the file that contains a list of files" exit fi files=$(cat $1) mkdir -p out for item in $files ; do dn=$(dirname $item) mkdir -p out/$dn src/uncrustify -f $item -c etc/ben.cfg > out/$item done
/** * AngularJS filter for Numeral.js: number formatting as a filter * @version v2.0.1 - 2017-05-06 * @link https://github.com/baumandm/angular-numeraljs * @author Dave Bauman <baumandm@gmail.com> * @license MIT License, http://www.opensource.org/licenses/MIT */ "use strict";!function(a,b){"object"==typeof exports?module.exports=b(require("numeral")):"function"==typeof define&&define.amd?define(["numeral"],function(c){return a.ngNumeraljs=b(c)}):a.ngNumeraljs=b(a.numeral)}(this,function(a){return angular.module("ngNumeraljs",[]).provider("$numeraljsConfig",function(){var b={};this.defaultFormat=function(b){a.defaultFormat(b)},this.locale=function(b){a.locale(b)},this.namedFormat=function(a,c){b[a]=c},this.register=function(b,c,d){a.register(b,c,d)},this.$get=function(){return{customFormat:function(a){return b[a]||a},defaultFormat:this.defaultFormat,locale:this.locale,register:this.register,namedFormat:this.namedFormat}}}).filter("numeraljs",["$numeraljsConfig",function(b){return function(c,d){return null==c?c:(d=b.customFormat(d),a(c).format(d))}}])});
/* packet-dpvreq.c * Routines for DOCSIS 3.0 DOCSIS Path Verify Response Message dissection. * Copyright 2010, Guido Reismueller <g.reismueller[AT]avm.de> * * Wireshark - Network traffic analyzer * By Gerald Combs <gerald@wireshark.org> * Copyright 1998 Gerald Combs * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "config.h" #include <epan/packet.h> void proto_register_docsis_dpvreq(void); void proto_reg_handoff_docsis_dpvreq(void); /* Initialize the protocol and registered fields */ static int proto_docsis_dpvreq = -1; static int hf_docsis_dpvreq_tranid = -1; static int hf_docsis_dpvreq_dschan = -1; static int hf_docsis_dpvreq_flags = -1; static int hf_docsis_dpvreq_us_sf = -1; static int hf_docsis_dpvreq_n = -1; static int hf_docsis_dpvreq_start = -1; static int hf_docsis_dpvreq_end = -1; static int hf_docsis_dpvreq_ts_start = -1; static int hf_docsis_dpvreq_ts_end = -1; /* Initialize the subtree pointers */ static gint ett_docsis_dpvreq = -1; /* Dissection */ static void dissect_dpvreq (tvbuff_t * tvb, packet_info * pinfo, proto_tree * tree) { proto_item *it; proto_tree *dpvreq_tree = NULL; guint16 transid; guint8 dschan; transid = tvb_get_ntohs (tvb, 0); dschan = tvb_get_guint8 (tvb, 2); col_add_fstr (pinfo->cinfo, COL_INFO, "DOCSIS Path Verify Request: Transaction-Id = %u DS-Ch %d", transid, dschan); if (tree) { it = proto_tree_add_protocol_format (tree, proto_docsis_dpvreq, tvb, 0, -1, "DPV Request"); dpvreq_tree = proto_item_add_subtree (it, ett_docsis_dpvreq); proto_tree_add_item (dpvreq_tree, hf_docsis_dpvreq_tranid, tvb, 0, 2, ENC_BIG_ENDIAN); proto_tree_add_item (dpvreq_tree, hf_docsis_dpvreq_dschan, tvb, 2, 1, ENC_BIG_ENDIAN); proto_tree_add_item (dpvreq_tree, hf_docsis_dpvreq_flags, tvb, 3, 1, ENC_BIG_ENDIAN); proto_tree_add_item (dpvreq_tree, hf_docsis_dpvreq_us_sf, tvb, 4, 4, ENC_BIG_ENDIAN); proto_tree_add_item (dpvreq_tree, hf_docsis_dpvreq_n, tvb, 8, 2, ENC_BIG_ENDIAN); proto_tree_add_item (dpvreq_tree, hf_docsis_dpvreq_start, tvb, 10, 1, ENC_BIG_ENDIAN); proto_tree_add_item (dpvreq_tree, hf_docsis_dpvreq_end, tvb, 11, 1, ENC_BIG_ENDIAN); proto_tree_add_item (dpvreq_tree, hf_docsis_dpvreq_ts_start, tvb, 12, 4, ENC_BIG_ENDIAN); proto_tree_add_item (dpvreq_tree, hf_docsis_dpvreq_ts_end, tvb, 16, 4, ENC_BIG_ENDIAN); } } /* Register the protocol with Wireshark */ void proto_register_docsis_dpvreq (void) { static hf_register_info hf[] = { {&hf_docsis_dpvreq_tranid, {"Transaction Id", "docsis_dpvreq.tranid", FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL} }, {&hf_docsis_dpvreq_dschan, {"Downstream Channel ID", "docsis_dpvreq.dschan", FT_UINT8, BASE_DEC, NULL, 0x0, NULL, HFILL} }, {&hf_docsis_dpvreq_flags, {"Flags", "docsis_dpvreq.flags", FT_UINT8, BASE_DEC, NULL, 0x0, NULL, HFILL} }, {&hf_docsis_dpvreq_us_sf, {"Upstream Service Flow ID", "docsis_dpvreq.us_sf", FT_UINT32, BASE_DEC, NULL, 0x0, NULL, HFILL} }, {&hf_docsis_dpvreq_n, {"N (Measurement avaraging factor)", "docsis_dpvreq.n", FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL} }, {&hf_docsis_dpvreq_start, {"Start Reference Point", "docsis_dpvreq.start", FT_UINT8, BASE_DEC, NULL, 0x0, NULL, HFILL} }, {&hf_docsis_dpvreq_end, {"End Reference Point", "docsis_dpvreq.end", FT_UINT8, BASE_DEC, NULL, 0x0, NULL, HFILL} }, {&hf_docsis_dpvreq_ts_start, {"Timestamp Start", "docsis_dpvreq.ts_start", FT_UINT32, BASE_DEC, NULL, 0x0, NULL, HFILL} }, {&hf_docsis_dpvreq_ts_end, {"Timestamp End", "docsis_dpvreq.ts_end", FT_UINT32, BASE_DEC, NULL, 0x0, NULL, HFILL} }, }; static gint *ett[] = { &ett_docsis_dpvreq, }; proto_docsis_dpvreq = proto_register_protocol ("DOCSIS Path Verify Request", "DOCSIS DPV-REQ", "docsis_dpvreq"); proto_register_field_array (proto_docsis_dpvreq, hf, array_length (hf)); proto_register_subtree_array (ett, array_length (ett)); register_dissector ("docsis_dpvreq", dissect_dpvreq, proto_docsis_dpvreq); } void proto_reg_handoff_docsis_dpvreq (void) { dissector_handle_t docsis_dpvreq_handle; docsis_dpvreq_handle = find_dissector ("docsis_dpvreq"); dissector_add_uint ("docsis_mgmt", 0x27, docsis_dpvreq_handle); } /* * Editor modelines - http://www.wireshark.org/tools/modelines.html * * Local Variables: * c-basic-offset: 2 * tab-width: 8 * indent-tabs-mode: nil * End: * * ex: set shiftwidth=2 tabstop=8 expandtab: * :indentSize=2:tabSize=8:noTabs=true: */
/* esp.c */ #define ESP_MAX_DEVS 7 typedef void (*espdma_memory_read_write)(void *opaque, uint8_t *buf, int len); void esp_init(target_phys_addr_t espaddr, int it_shift, espdma_memory_read_write dma_memory_read, espdma_memory_read_write dma_memory_write, void *dma_opaque, qemu_irq irq, qemu_irq *reset);
/* * Copyright (c) 2007, 2016, 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 com.sun.swingset3.demos; import java.net.URL; import java.util.MissingResourceException; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.*; /** * @author Pavel Porvatov */ public class ResourceManager { private static final Logger logger = Logger.getLogger(ResourceManager.class.getName()); private final Class<?> demoClass; // Resource bundle for internationalized and accessible text private ResourceBundle bundle = null; public ResourceManager(Class<?> demoClass) { this.demoClass = demoClass; String bundleName = demoClass.getPackage().getName() + ".resources." + demoClass.getSimpleName(); try { bundle = ResourceBundle.getBundle(bundleName); } catch (MissingResourceException e) { logger.log(Level.SEVERE, "Couldn't load bundle: " + bundleName); } } public String getString(String key) { return bundle != null ? bundle.getString(key) : key; } public char getMnemonic(String key) { return (getString(key)).charAt(0); } public ImageIcon createImageIcon(String filename, String description) { String path = "resources/images/" + filename; URL imageURL = demoClass.getResource(path); if (imageURL == null) { logger.log(Level.SEVERE, "unable to access image file: " + path); return null; } else { return new ImageIcon(imageURL, description); } } }
/* * Routines to compress and uncompress tcp packets (for transmission * over low speed serial lines). * * Copyright (c) 1989 Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms are permitted * provided that the above copyright notice and this paragraph are * duplicated in all such forms and that any documentation, * advertising materials, and other materials related to such * distribution and use acknowledge that the software was developed * by the University of California, Berkeley. The name of the * University may not be used to endorse or promote products derived * from this software without specific prior written permission. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. * * Van Jacobson (van@helios.ee.lbl.gov), Dec 31, 1989: * - Initial distribution. * * * modified for KA9Q Internet Software Package by * Katie Stevens (dkstevens@ucdavis.edu) * University of California, Davis * Computing Services * - 01-31-90 initial adaptation (from 1.19) * PPP.05 02-15-90 [ks] * PPP.08 05-02-90 [ks] use PPP protocol field to signal compression * PPP.15 09-90 [ks] improve mbuf handling * PPP.16 11-02 [karn] substantially rewritten to use NOS facilities * * - Feb 1991 Bill_Simpson@um.cc.umich.edu * variable number of conversation slots * allow zero or one slots * separate routines * status display * - Jul 1994 Dmitry Gorodchanin * Fixes for memory leaks. * - Oct 1994 Dmitry Gorodchanin * Modularization. * - Jan 1995 Bjorn Ekwall * Use ip_fast_csum from ip.h * - July 1995 Christos A. Polyzols * Spotted bug in tcp option checking * * * This module is a difficult issue. It's clearly inet code but it's also clearly * driver code belonging close to PPP and SLIP */ #include <linux/config.h> #include <linux/module.h> #include <linux/types.h> #include <linux/string.h> #include <linux/errno.h> #include <linux/kernel.h> #include <net/slhc_vj.h> #ifdef CONFIG_INET /* Entire module is for IP only */ #include <linux/mm.h> #include <linux/socket.h> #include <linux/sockios.h> #include <linux/termios.h> #include <linux/in.h> #include <linux/fcntl.h> #include <linux/inet.h> #include <linux/netdevice.h> #include <net/ip.h> #include <net/protocol.h> #include <net/icmp.h> #include <net/tcp.h> #include <linux/skbuff.h> #include <net/sock.h> #include <linux/timer.h> #include <asm/system.h> #include <asm/uaccess.h> #include <net/checksum.h> #include <asm/unaligned.h> static unsigned char *encode(unsigned char *cp, unsigned short n); static long decode(unsigned char **cpp); static unsigned char * put16(unsigned char *cp, unsigned short x); static unsigned short pull16(unsigned char **cpp); /* Initialize compression data structure * slots must be in range 0 to 255 (zero meaning no compression) */ struct slcompress * slhc_init(int rslots, int tslots) { register short i; register struct cstate *ts; struct slcompress *comp; comp = (struct slcompress *)kmalloc(sizeof(struct slcompress), GFP_KERNEL); if (! comp) goto out_fail; memset(comp, 0, sizeof(struct slcompress)); if ( rslots > 0 && rslots < 256 ) { size_t rsize = rslots * sizeof(struct cstate); comp->rstate = (struct cstate *) kmalloc(rsize, GFP_KERNEL); if (! comp->rstate) goto out_free; memset(comp->rstate, 0, rsize); comp->rslot_limit = rslots - 1; } if ( tslots > 0 && tslots < 256 ) { size_t tsize = tslots * sizeof(struct cstate); comp->tstate = (struct cstate *) kmalloc(tsize, GFP_KERNEL); if (! comp->tstate) goto out_free2; memset(comp->tstate, 0, tsize); comp->tslot_limit = tslots - 1; } comp->xmit_oldest = 0; comp->xmit_current = 255; comp->recv_current = 255; /* * don't accept any packets with implicit index until we get * one with an explicit index. Otherwise the uncompress code * will try to use connection 255, which is almost certainly * out of range */ comp->flags |= SLF_TOSS; if ( tslots > 0 ) { ts = comp->tstate; for(i = comp->tslot_limit; i > 0; --i){ ts[i].cs_this = i; ts[i].next = &(ts[i - 1]); } ts[0].next = &(ts[comp->tslot_limit]); ts[0].cs_this = 0; } return comp; out_free2: kfree((unsigned char *)comp->rstate); out_free: kfree((unsigned char *)comp); out_fail: return NULL; } /* Free a compression data structure */ void slhc_free(struct slcompress *comp) { if ( comp == NULLSLCOMPR ) return; if ( comp->tstate != NULLSLSTATE ) kfree( comp->tstate ); if ( comp->rstate != NULLSLSTATE ) kfree( comp->rstate ); kfree( comp ); } /* Put a short in host order into a char array in network order */ static inline unsigned char * put16(unsigned char *cp, unsigned short x) { *cp++ = x >> 8; *cp++ = x; return cp; } /* Encode a number */ unsigned char * encode(unsigned char *cp, unsigned short n) { if(n >= 256 || n == 0){ *cp++ = 0; cp = put16(cp,n); } else { *cp++ = n; } return cp; } /* Pull a 16-bit integer in host order from buffer in network byte order */ static unsigned short pull16(unsigned char **cpp) { short rval; rval = *(*cpp)++; rval <<= 8; rval |= *(*cpp)++; return rval; } /* Decode a number */ long decode(unsigned char **cpp) { register int x; x = *(*cpp)++; if(x == 0){ return pull16(cpp) & 0xffff; /* pull16 returns -1 on error */ } else { return x & 0xff; /* -1 if PULLCHAR returned error */ } } /* * icp and isize are the original packet. * ocp is a place to put a copy if necessary. * cpp is initially a pointer to icp. If the copy is used, * change it to ocp. */ int slhc_compress(struct slcompress *comp, unsigned char *icp, int isize, unsigned char *ocp, unsigned char **cpp, int compress_cid) { register struct cstate *ocs = &(comp->tstate[comp->xmit_oldest]); register struct cstate *lcs = ocs; register struct cstate *cs = lcs->next; register unsigned long deltaS, deltaA; register short changes = 0; int hlen; unsigned char new_seq[16]; register unsigned char *cp = new_seq; struct iphdr *ip; struct tcphdr *th, *oth; /* * Don't play with runt packets. */ if(isize<sizeof(struct iphdr)) return isize; ip = (struct iphdr *) icp; /* Bail if this packet isn't TCP, or is an IP fragment */ if (ip->protocol != IPPROTO_TCP || (ntohs(ip->frag_off) & 0x3fff)) { /* Send as regular IP */ if(ip->protocol != IPPROTO_TCP) comp->sls_o_nontcp++; else comp->sls_o_tcp++; return isize; } /* Extract TCP header */ th = (struct tcphdr *)(((unsigned char *)ip) + ip->ihl*4); hlen = ip->ihl*4 + th->doff*4; /* Bail if the TCP packet isn't `compressible' (i.e., ACK isn't set or * some other control bit is set). Also uncompressible if * it's a runt. */ if(hlen > isize || th->syn || th->fin || th->rst || ! (th->ack)){ /* TCP connection stuff; send as regular IP */ comp->sls_o_tcp++; return isize; } /* * Packet is compressible -- we're going to send either a * COMPRESSED_TCP or UNCOMPRESSED_TCP packet. Either way, * we need to locate (or create) the connection state. * * States are kept in a circularly linked list with * xmit_oldest pointing to the end of the list. The * list is kept in lru order by moving a state to the * head of the list whenever it is referenced. Since * the list is short and, empirically, the connection * we want is almost always near the front, we locate * states via linear search. If we don't find a state * for the datagram, the oldest state is (re-)used. */ for ( ; ; ) { if( ip->saddr == cs->cs_ip.saddr && ip->daddr == cs->cs_ip.daddr && th->source == cs->cs_tcp.source && th->dest == cs->cs_tcp.dest) goto found; /* if current equal oldest, at end of list */ if ( cs == ocs ) break; lcs = cs; cs = cs->next; comp->sls_o_searches++; }; /* * Didn't find it -- re-use oldest cstate. Send an * uncompressed packet that tells the other side what * connection number we're using for this conversation. * * Note that since the state list is circular, the oldest * state points to the newest and we only need to set * xmit_oldest to update the lru linkage. */ comp->sls_o_misses++; comp->xmit_oldest = lcs->cs_this; goto uncompressed; found: /* * Found it -- move to the front on the connection list. */ if(lcs == ocs) { /* found at most recently used */ } else if (cs == ocs) { /* found at least recently used */ comp->xmit_oldest = lcs->cs_this; } else { /* more than 2 elements */ lcs->next = cs->next; cs->next = ocs->next; ocs->next = cs; } /* * Make sure that only what we expect to change changed. * Check the following: * IP protocol version, header length & type of service. * The "Don't fragment" bit. * The time-to-live field. * The TCP header length. * IP options, if any. * TCP options, if any. * If any of these things are different between the previous & * current datagram, we send the current datagram `uncompressed'. */ oth = &cs->cs_tcp; if(ip->version != cs->cs_ip.version || ip->ihl != cs->cs_ip.ihl || ip->tos != cs->cs_ip.tos || (ip->frag_off & htons(0x4000)) != (cs->cs_ip.frag_off & htons(0x4000)) || ip->ttl != cs->cs_ip.ttl || th->doff != cs->cs_tcp.doff || (ip->ihl > 5 && memcmp(ip+1,cs->cs_ipopt,((ip->ihl)-5)*4) != 0) || (th->doff > 5 && memcmp(th+1,cs->cs_tcpopt,((th->doff)-5)*4) != 0)){ goto uncompressed; } /* * Figure out which of the changing fields changed. The * receiver expects changes in the order: urgent, window, * ack, seq (the order minimizes the number of temporaries * needed in this section of code). */ if(th->urg){ deltaS = ntohs(th->urg_ptr); cp = encode(cp,deltaS); changes |= NEW_U; } else if(th->urg_ptr != oth->urg_ptr){ /* argh! URG not set but urp changed -- a sensible * implementation should never do this but RFC793 * doesn't prohibit the change so we have to deal * with it. */ goto uncompressed; } if((deltaS = ntohs(th->window) - ntohs(oth->window)) != 0){ cp = encode(cp,deltaS); changes |= NEW_W; } if((deltaA = ntohl(th->ack_seq) - ntohl(oth->ack_seq)) != 0L){ if(deltaA > 0x0000ffff) goto uncompressed; cp = encode(cp,deltaA); changes |= NEW_A; } if((deltaS = ntohl(th->seq) - ntohl(oth->seq)) != 0L){ if(deltaS > 0x0000ffff) goto uncompressed; cp = encode(cp,deltaS); changes |= NEW_S; } switch(changes){ case 0: /* Nothing changed. If this packet contains data and the * last one didn't, this is probably a data packet following * an ack (normal on an interactive connection) and we send * it compressed. Otherwise it's probably a retransmit, * retransmitted ack or window probe. Send it uncompressed * in case the other side missed the compressed version. */ if(ip->tot_len != cs->cs_ip.tot_len && ntohs(cs->cs_ip.tot_len) == hlen) break; goto uncompressed; break; case SPECIAL_I: case SPECIAL_D: /* actual changes match one of our special case encodings -- * send packet uncompressed. */ goto uncompressed; case NEW_S|NEW_A: if(deltaS == deltaA && deltaS == ntohs(cs->cs_ip.tot_len) - hlen){ /* special case for echoed terminal traffic */ changes = SPECIAL_I; cp = new_seq; } break; case NEW_S: if(deltaS == ntohs(cs->cs_ip.tot_len) - hlen){ /* special case for data xfer */ changes = SPECIAL_D; cp = new_seq; } break; } deltaS = ntohs(ip->id) - ntohs(cs->cs_ip.id); if(deltaS != 1){ cp = encode(cp,deltaS); changes |= NEW_I; } if(th->psh) changes |= TCP_PUSH_BIT; /* Grab the cksum before we overwrite it below. Then update our * state with this packet's header. */ deltaA = ntohs(th->check); memcpy(&cs->cs_ip,ip,20); memcpy(&cs->cs_tcp,th,20); /* We want to use the original packet as our compressed packet. * (cp - new_seq) is the number of bytes we need for compressed * sequence numbers. In addition we need one byte for the change * mask, one for the connection id and two for the tcp checksum. * So, (cp - new_seq) + 4 bytes of header are needed. */ deltaS = cp - new_seq; if(compress_cid == 0 || comp->xmit_current != cs->cs_this){ cp = ocp; *cpp = ocp; *cp++ = changes | NEW_C; *cp++ = cs->cs_this; comp->xmit_current = cs->cs_this; } else { cp = ocp; *cpp = ocp; *cp++ = changes; } cp = put16(cp,(short)deltaA); /* Write TCP checksum */ /* deltaS is now the size of the change section of the compressed header */ memcpy(cp,new_seq,deltaS); /* Write list of deltas */ memcpy(cp+deltaS,icp+hlen,isize-hlen); comp->sls_o_compressed++; ocp[0] |= SL_TYPE_COMPRESSED_TCP; return isize - hlen + deltaS + (cp - ocp); /* Update connection state cs & send uncompressed packet (i.e., * a regular ip/tcp packet but with the 'conversation id' we hope * to use on future compressed packets in the protocol field). */ uncompressed: memcpy(&cs->cs_ip,ip,20); memcpy(&cs->cs_tcp,th,20); if (ip->ihl > 5) memcpy(cs->cs_ipopt, ip+1, ((ip->ihl) - 5) * 4); if (th->doff > 5) memcpy(cs->cs_tcpopt, th+1, ((th->doff) - 5) * 4); comp->xmit_current = cs->cs_this; comp->sls_o_uncompressed++; memcpy(ocp, icp, isize); *cpp = ocp; ocp[9] = cs->cs_this; ocp[0] |= SL_TYPE_UNCOMPRESSED_TCP; return isize; } int slhc_uncompress(struct slcompress *comp, unsigned char *icp, int isize) { register int changes; long x; register struct tcphdr *thp; register struct iphdr *ip; register struct cstate *cs; int len, hdrlen; unsigned char *cp = icp; /* We've got a compressed packet; read the change byte */ comp->sls_i_compressed++; if(isize < 3){ comp->sls_i_error++; return 0; } changes = *cp++; if(changes & NEW_C){ /* Make sure the state index is in range, then grab the state. * If we have a good state index, clear the 'discard' flag. */ x = *cp++; /* Read conn index */ if(x < 0 || x > comp->rslot_limit) goto bad; comp->flags &=~ SLF_TOSS; comp->recv_current = x; } else { /* this packet has an implicit state index. If we've * had a line error since the last time we got an * explicit state index, we have to toss the packet. */ if(comp->flags & SLF_TOSS){ comp->sls_i_tossed++; return 0; } } cs = &comp->rstate[comp->recv_current]; thp = &cs->cs_tcp; ip = &cs->cs_ip; if((x = pull16(&cp)) == -1) { /* Read the TCP checksum */ goto bad; } thp->check = htons(x); thp->psh = (changes & TCP_PUSH_BIT) ? 1 : 0; /* * we can use the same number for the length of the saved header and * the current one, because the packet wouldn't have been sent * as compressed unless the options were the same as the previous one */ hdrlen = ip->ihl * 4 + thp->doff * 4; switch(changes & SPECIALS_MASK){ case SPECIAL_I: /* Echoed terminal traffic */ { register short i; i = ntohs(ip->tot_len) - hdrlen; thp->ack_seq = htonl( ntohl(thp->ack_seq) + i); thp->seq = htonl( ntohl(thp->seq) + i); } break; case SPECIAL_D: /* Unidirectional data */ thp->seq = htonl( ntohl(thp->seq) + ntohs(ip->tot_len) - hdrlen); break; default: if(changes & NEW_U){ thp->urg = 1; if((x = decode(&cp)) == -1) { goto bad; } thp->urg_ptr = htons(x); } else thp->urg = 0; if(changes & NEW_W){ if((x = decode(&cp)) == -1) { goto bad; } thp->window = htons( ntohs(thp->window) + x); } if(changes & NEW_A){ if((x = decode(&cp)) == -1) { goto bad; } thp->ack_seq = htonl( ntohl(thp->ack_seq) + x); } if(changes & NEW_S){ if((x = decode(&cp)) == -1) { goto bad; } thp->seq = htonl( ntohl(thp->seq) + x); } break; } if(changes & NEW_I){ if((x = decode(&cp)) == -1) { goto bad; } ip->id = htons (ntohs (ip->id) + x); } else ip->id = htons (ntohs (ip->id) + 1); /* * At this point, cp points to the first byte of data in the * packet. Put the reconstructed TCP and IP headers back on the * packet. Recalculate IP checksum (but not TCP checksum). */ len = isize - (cp - icp); if (len < 0) goto bad; len += hdrlen; ip->tot_len = htons(len); ip->check = 0; memmove(icp + hdrlen, cp, len - hdrlen); cp = icp; memcpy(cp, ip, 20); cp += 20; if (ip->ihl > 5) { memcpy(cp, cs->cs_ipopt, (ip->ihl - 5) * 4); cp += (ip->ihl - 5) * 4; } put_unaligned(ip_fast_csum(icp, ip->ihl), &((struct iphdr *)icp)->check); memcpy(cp, thp, 20); cp += 20; if (thp->doff > 5) { memcpy(cp, cs->cs_tcpopt, ((thp->doff) - 5) * 4); cp += ((thp->doff) - 5) * 4; } return len; bad: comp->sls_i_error++; return slhc_toss( comp ); } int slhc_remember(struct slcompress *comp, unsigned char *icp, int isize) { register struct cstate *cs; unsigned ihl; unsigned char index; if(isize < 20) { /* The packet is shorter than a legal IP header */ comp->sls_i_runt++; return slhc_toss( comp ); } /* Peek at the IP header's IHL field to find its length */ ihl = icp[0] & 0xf; if(ihl < 20 / 4){ /* The IP header length field is too small */ comp->sls_i_runt++; return slhc_toss( comp ); } index = icp[9]; icp[9] = IPPROTO_TCP; if (ip_fast_csum(icp, ihl)) { /* Bad IP header checksum; discard */ comp->sls_i_badcheck++; return slhc_toss( comp ); } if(index > comp->rslot_limit) { comp->sls_i_error++; return slhc_toss(comp); } /* Update local state */ cs = &comp->rstate[comp->recv_current = index]; comp->flags &=~ SLF_TOSS; memcpy(&cs->cs_ip,icp,20); memcpy(&cs->cs_tcp,icp + ihl*4,20); if (ihl > 5) memcpy(cs->cs_ipopt, icp + sizeof(struct iphdr), (ihl - 5) * 4); if (cs->cs_tcp.doff > 5) memcpy(cs->cs_tcpopt, icp + ihl*4 + sizeof(struct tcphdr), (cs->cs_tcp.doff - 5) * 4); cs->cs_hsize = ihl*2 + cs->cs_tcp.doff*2; /* Put headers back on packet * Neither header checksum is recalculated */ comp->sls_i_uncompressed++; return isize; } int slhc_toss(struct slcompress *comp) { if ( comp == NULLSLCOMPR ) return 0; comp->flags |= SLF_TOSS; return 0; } void slhc_i_status(struct slcompress *comp) { if (comp != NULLSLCOMPR) { printk("\t%d Cmp, %d Uncmp, %d Bad, %d Tossed\n", comp->sls_i_compressed, comp->sls_i_uncompressed, comp->sls_i_error, comp->sls_i_tossed); } } void slhc_o_status(struct slcompress *comp) { if (comp != NULLSLCOMPR) { printk("\t%d Cmp, %d Uncmp, %d AsIs, %d NotTCP\n", comp->sls_o_compressed, comp->sls_o_uncompressed, comp->sls_o_tcp, comp->sls_o_nontcp); printk("\t%10d Searches, %10d Misses\n", comp->sls_o_searches, comp->sls_o_misses); } } /* Should this be surrounded with "#ifdef CONFIG_MODULES" ? */ /* VJ header compression */ EXPORT_SYMBOL(slhc_init); EXPORT_SYMBOL(slhc_free); EXPORT_SYMBOL(slhc_remember); EXPORT_SYMBOL(slhc_compress); EXPORT_SYMBOL(slhc_uncompress); EXPORT_SYMBOL(slhc_toss); #ifdef MODULE int init_module(void) { printk(KERN_INFO "CSLIP: code copyright 1989 Regents of the University of California\n"); return 0; } void cleanup_module(void) { return; } #endif /* MODULE */ #else /* CONFIG_INET */ int slhc_toss(struct slcompress *comp) { printk(KERN_DEBUG "Called IP function on non IP-system: slhc_toss"); return -EINVAL; } int slhc_uncompress(struct slcompress *comp, unsigned char *icp, int isize) { printk(KERN_DEBUG "Called IP function on non IP-system: slhc_uncompress"); return -EINVAL; } int slhc_compress(struct slcompress *comp, unsigned char *icp, int isize, unsigned char *ocp, unsigned char **cpp, int compress_cid) { printk(KERN_DEBUG "Called IP function on non IP-system: slhc_compress"); return -EINVAL; } int slhc_remember(struct slcompress *comp, unsigned char *icp, int isize) { printk(KERN_DEBUG "Called IP function on non IP-system: slhc_remember"); return -EINVAL; } void slhc_free(struct slcompress *comp) { printk(KERN_DEBUG "Called IP function on non IP-system: slhc_free"); return; } struct slcompress * slhc_init(int rslots, int tslots) { printk(KERN_DEBUG "Called IP function on non IP-system: slhc_init"); return NULL; } EXPORT_SYMBOL(slhc_init); EXPORT_SYMBOL(slhc_free); EXPORT_SYMBOL(slhc_remember); EXPORT_SYMBOL(slhc_compress); EXPORT_SYMBOL(slhc_uncompress); EXPORT_SYMBOL(slhc_toss); #endif /* CONFIG_INET */ MODULE_LICENSE("Dual BSD/GPL");
/** @file Vector4.h Homogeneous vector class. @maintainer Morgan McGuire, http://graphics.cs.williams.edu @created 2002-07-09 @edited 2008-11-01 Copyright 2000-2009, Morgan McGuire. All rights reserved. */ #ifndef G3D_Vector4_h #define G3D_Vector4_h #include "G3D/platform.h" #include "G3D/g3dmath.h" #include "G3D/Vector3.h" #include "G3D/Vector2.h" #include "G3D/Table.h" #include "G3D/HashTrait.h" #include "G3D/PositionTrait.h" #include <string> namespace G3D { class Vector2; class Vector3; class Vector4; class Vector4int8; class Any; /** Do not subclass-- this implementation makes assumptions about the memory layout. */ class Vector4 { private: // Hidden operators bool operator<(const Vector4&) const; bool operator>(const Vector4&) const; bool operator<=(const Vector4&) const; bool operator>=(const Vector4&) const; public: /** \param any Must either Vector4(#, #, #, #) or Vector3 {x = #, y = #, z = #, w =#}*/ Vector4(const Any& any); /** Converts the Vector4 to an Any. */ operator Any() const; // construction Vector4(); Vector4(float fX, float fY, float fZ, float fW); Vector4(float afCoordinate[4]); Vector4(const Vector4& rkVector); Vector4(const class Color4& c); Vector4(const Vector3& rkVector, float fW); Vector4(const Vector2& v1, const Vector2& v2); Vector4(const Vector2& v1, float fz, float fw); /** Divides by 127 when converting */ Vector4(const Vector4int8&); Vector4(class BinaryInput& b); void serialize(class BinaryOutput& b) const; void deserialize(class BinaryInput& b); // coordinates float x, y, z, w; // access vector V as V[0] = V.x, V[1] = V.y, V[2] = V.z, etc. // // WARNING. These member functions rely on // (1) Vector4 not having virtual functions // (2) the data packed in a 4*sizeof(float) memory block float& operator[] (int i); const float& operator[] (int i) const; // assignment and comparison Vector4& operator= (const Vector4& rkVector); bool operator== (const Vector4& rkVector) const; bool operator!= (const Vector4& rkVector) const; static const Vector4& zero(); inline void set(float _x, float _y, float _z, float _w) { x = _x; y = _y; z = _z; w = _w; } inline void set(const Vector3& v, float _w) { x = v.x; y = v.y; z = v.z; w = _w; } inline void set(const Vector2& v, float _z, float _w) { x = v.x; y = v.y; z = _z; w = _w; } size_t hashCode() const; bool fuzzyEq(const Vector4& other) const; bool fuzzyNe(const Vector4& other) const; static const Vector4& inf(); static const Vector4& nan(); /** sqrt(this->dot(*this)) */ float length() const; float squaredLength() const; inline float sum() const { return x + y + z + w; } /** Returns true if this vector has finite length */ bool isFinite() const; /** Returns true if this vector has length == 0 */ bool isZero() const; /** Returns true if this vector has length == 1 */ bool isUnit() const; // arithmetic operations Vector4 operator+ (const Vector4& rkVector) const; Vector4 operator- (const Vector4& rkVector) const; inline Vector4 operator*(const Vector4& rkVector) const { return Vector4(x * rkVector.x, y * rkVector.y, z * rkVector.z, w * rkVector.w); } inline Vector4 operator/(const Vector4& rkVector) const { return Vector4(x / rkVector.x, y / rkVector.y, z / rkVector.z, w / rkVector.w); } Vector4 operator*(const class Matrix4& M) const; Vector4 operator* (float fScalar) const; Vector4 operator/ (float fScalar) const; Vector4 operator- () const; friend Vector4 operator* (float, const Vector4& rkVector); // arithmetic updates Vector4& operator+= (const Vector4& rkVector); Vector4& operator-= (const Vector4& rkVector); Vector4& operator*= (float fScalar); Vector4& operator/= (float fScalar); inline Vector4 clamp(const Vector4& low, const Vector4& high) const { return Vector4( G3D::clamp(x, low.x, high.x), G3D::clamp(y, low.y, high.y), G3D::clamp(z, low.z, high.z), G3D::clamp(w, low.w, high.w)); } inline Vector4 clamp(float low, float high) const { return Vector4( G3D::clamp(x, low, high), G3D::clamp(y, low, high), G3D::clamp(z, low, high), G3D::clamp(w, low, high)); } float dot (const Vector4& rkVector) const; Vector4 min(const Vector4& v) const; Vector4 max(const Vector4& v) const; std::string toString() const; /** Linear interpolation */ Vector4 lerp(const Vector4& v, float alpha) const; // 2-char swizzles Vector2 xx() const; Vector2 yx() const; Vector2 zx() const; Vector2 wx() const; Vector2 xy() const; Vector2 yy() const; Vector2 zy() const; Vector2 wy() const; Vector2 xz() const; Vector2 yz() const; Vector2 zz() const; Vector2 wz() const; Vector2 xw() const; Vector2 yw() const; Vector2 zw() const; Vector2 ww() const; // 3-char swizzles Vector3 xxx() const; Vector3 yxx() const; Vector3 zxx() const; Vector3 wxx() const; Vector3 xyx() const; Vector3 yyx() const; Vector3 zyx() const; Vector3 wyx() const; Vector3 xzx() const; Vector3 yzx() const; Vector3 zzx() const; Vector3 wzx() const; Vector3 xwx() const; Vector3 ywx() const; Vector3 zwx() const; Vector3 wwx() const; Vector3 xxy() const; Vector3 yxy() const; Vector3 zxy() const; Vector3 wxy() const; Vector3 xyy() const; Vector3 yyy() const; Vector3 zyy() const; Vector3 wyy() const; Vector3 xzy() const; Vector3 yzy() const; Vector3 zzy() const; Vector3 wzy() const; Vector3 xwy() const; Vector3 ywy() const; Vector3 zwy() const; Vector3 wwy() const; Vector3 xxz() const; Vector3 yxz() const; Vector3 zxz() const; Vector3 wxz() const; Vector3 xyz() const; Vector3 yyz() const; Vector3 zyz() const; Vector3 wyz() const; Vector3 xzz() const; Vector3 yzz() const; Vector3 zzz() const; Vector3 wzz() const; Vector3 xwz() const; Vector3 ywz() const; Vector3 zwz() const; Vector3 wwz() const; Vector3 xxw() const; Vector3 yxw() const; Vector3 zxw() const; Vector3 wxw() const; Vector3 xyw() const; Vector3 yyw() const; Vector3 zyw() const; Vector3 wyw() const; Vector3 xzw() const; Vector3 yzw() const; Vector3 zzw() const; Vector3 wzw() const; Vector3 xww() const; Vector3 yww() const; Vector3 zww() const; Vector3 www() const; // 4-char swizzles Vector4 xxxx() const; Vector4 yxxx() const; Vector4 zxxx() const; Vector4 wxxx() const; Vector4 xyxx() const; Vector4 yyxx() const; Vector4 zyxx() const; Vector4 wyxx() const; Vector4 xzxx() const; Vector4 yzxx() const; Vector4 zzxx() const; Vector4 wzxx() const; Vector4 xwxx() const; Vector4 ywxx() const; Vector4 zwxx() const; Vector4 wwxx() const; Vector4 xxyx() const; Vector4 yxyx() const; Vector4 zxyx() const; Vector4 wxyx() const; Vector4 xyyx() const; Vector4 yyyx() const; Vector4 zyyx() const; Vector4 wyyx() const; Vector4 xzyx() const; Vector4 yzyx() const; Vector4 zzyx() const; Vector4 wzyx() const; Vector4 xwyx() const; Vector4 ywyx() const; Vector4 zwyx() const; Vector4 wwyx() const; Vector4 xxzx() const; Vector4 yxzx() const; Vector4 zxzx() const; Vector4 wxzx() const; Vector4 xyzx() const; Vector4 yyzx() const; Vector4 zyzx() const; Vector4 wyzx() const; Vector4 xzzx() const; Vector4 yzzx() const; Vector4 zzzx() const; Vector4 wzzx() const; Vector4 xwzx() const; Vector4 ywzx() const; Vector4 zwzx() const; Vector4 wwzx() const; Vector4 xxwx() const; Vector4 yxwx() const; Vector4 zxwx() const; Vector4 wxwx() const; Vector4 xywx() const; Vector4 yywx() const; Vector4 zywx() const; Vector4 wywx() const; Vector4 xzwx() const; Vector4 yzwx() const; Vector4 zzwx() const; Vector4 wzwx() const; Vector4 xwwx() const; Vector4 ywwx() const; Vector4 zwwx() const; Vector4 wwwx() const; Vector4 xxxy() const; Vector4 yxxy() const; Vector4 zxxy() const; Vector4 wxxy() const; Vector4 xyxy() const; Vector4 yyxy() const; Vector4 zyxy() const; Vector4 wyxy() const; Vector4 xzxy() const; Vector4 yzxy() const; Vector4 zzxy() const; Vector4 wzxy() const; Vector4 xwxy() const; Vector4 ywxy() const; Vector4 zwxy() const; Vector4 wwxy() const; Vector4 xxyy() const; Vector4 yxyy() const; Vector4 zxyy() const; Vector4 wxyy() const; Vector4 xyyy() const; Vector4 yyyy() const; Vector4 zyyy() const; Vector4 wyyy() const; Vector4 xzyy() const; Vector4 yzyy() const; Vector4 zzyy() const; Vector4 wzyy() const; Vector4 xwyy() const; Vector4 ywyy() const; Vector4 zwyy() const; Vector4 wwyy() const; Vector4 xxzy() const; Vector4 yxzy() const; Vector4 zxzy() const; Vector4 wxzy() const; Vector4 xyzy() const; Vector4 yyzy() const; Vector4 zyzy() const; Vector4 wyzy() const; Vector4 xzzy() const; Vector4 yzzy() const; Vector4 zzzy() const; Vector4 wzzy() const; Vector4 xwzy() const; Vector4 ywzy() const; Vector4 zwzy() const; Vector4 wwzy() const; Vector4 xxwy() const; Vector4 yxwy() const; Vector4 zxwy() const; Vector4 wxwy() const; Vector4 xywy() const; Vector4 yywy() const; Vector4 zywy() const; Vector4 wywy() const; Vector4 xzwy() const; Vector4 yzwy() const; Vector4 zzwy() const; Vector4 wzwy() const; Vector4 xwwy() const; Vector4 ywwy() const; Vector4 zwwy() const; Vector4 wwwy() const; Vector4 xxxz() const; Vector4 yxxz() const; Vector4 zxxz() const; Vector4 wxxz() const; Vector4 xyxz() const; Vector4 yyxz() const; Vector4 zyxz() const; Vector4 wyxz() const; Vector4 xzxz() const; Vector4 yzxz() const; Vector4 zzxz() const; Vector4 wzxz() const; Vector4 xwxz() const; Vector4 ywxz() const; Vector4 zwxz() const; Vector4 wwxz() const; Vector4 xxyz() const; Vector4 yxyz() const; Vector4 zxyz() const; Vector4 wxyz() const; Vector4 xyyz() const; Vector4 yyyz() const; Vector4 zyyz() const; Vector4 wyyz() const; Vector4 xzyz() const; Vector4 yzyz() const; Vector4 zzyz() const; Vector4 wzyz() const; Vector4 xwyz() const; Vector4 ywyz() const; Vector4 zwyz() const; Vector4 wwyz() const; Vector4 xxzz() const; Vector4 yxzz() const; Vector4 zxzz() const; Vector4 wxzz() const; Vector4 xyzz() const; Vector4 yyzz() const; Vector4 zyzz() const; Vector4 wyzz() const; Vector4 xzzz() const; Vector4 yzzz() const; Vector4 zzzz() const; Vector4 wzzz() const; Vector4 xwzz() const; Vector4 ywzz() const; Vector4 zwzz() const; Vector4 wwzz() const; Vector4 xxwz() const; Vector4 yxwz() const; Vector4 zxwz() const; Vector4 wxwz() const; Vector4 xywz() const; Vector4 yywz() const; Vector4 zywz() const; Vector4 wywz() const; Vector4 xzwz() const; Vector4 yzwz() const; Vector4 zzwz() const; Vector4 wzwz() const; Vector4 xwwz() const; Vector4 ywwz() const; Vector4 zwwz() const; Vector4 wwwz() const; Vector4 xxxw() const; Vector4 yxxw() const; Vector4 zxxw() const; Vector4 wxxw() const; Vector4 xyxw() const; Vector4 yyxw() const; Vector4 zyxw() const; Vector4 wyxw() const; Vector4 xzxw() const; Vector4 yzxw() const; Vector4 zzxw() const; Vector4 wzxw() const; Vector4 xwxw() const; Vector4 ywxw() const; Vector4 zwxw() const; Vector4 wwxw() const; Vector4 xxyw() const; Vector4 yxyw() const; Vector4 zxyw() const; Vector4 wxyw() const; Vector4 xyyw() const; Vector4 yyyw() const; Vector4 zyyw() const; Vector4 wyyw() const; Vector4 xzyw() const; Vector4 yzyw() const; Vector4 zzyw() const; Vector4 wzyw() const; Vector4 xwyw() const; Vector4 ywyw() const; Vector4 zwyw() const; Vector4 wwyw() const; Vector4 xxzw() const; Vector4 yxzw() const; Vector4 zxzw() const; Vector4 wxzw() const; Vector4 xyzw() const; Vector4 yyzw() const; Vector4 zyzw() const; Vector4 wyzw() const; Vector4 xzzw() const; Vector4 yzzw() const; Vector4 zzzw() const; Vector4 wzzw() const; Vector4 xwzw() const; Vector4 ywzw() const; Vector4 zwzw() const; Vector4 wwzw() const; Vector4 xxww() const; Vector4 yxww() const; Vector4 zxww() const; Vector4 wxww() const; Vector4 xyww() const; Vector4 yyww() const; Vector4 zyww() const; Vector4 wyww() const; Vector4 xzww() const; Vector4 yzww() const; Vector4 zzww() const; Vector4 wzww() const; Vector4 xwww() const; Vector4 ywww() const; Vector4 zwww() const; Vector4 wwww() const; }; //---------------------------------------------------------------------------- inline Vector4::Vector4() { x = y = z = w = 0; } //---------------------------------------------------------------------------- inline Vector4::Vector4 (float fX, float fY, float fZ, float fW) { x = fX; y = fY; z = fZ; w = fW; } //---------------------------------------------------------------------------- inline Vector4::Vector4 (float afCoordinate[4]) { x = afCoordinate[0]; y = afCoordinate[1]; z = afCoordinate[2]; w = afCoordinate[3]; } //---------------------------------------------------------------------------- inline Vector4::Vector4(const Vector4& rkVector) { x = rkVector.x; y = rkVector.y; z = rkVector.z; w = rkVector.w; } //---------------------------------------------------------------------------- inline Vector4::Vector4(const Vector3& rkVector, float fW) { x = rkVector.x; y = rkVector.y; z = rkVector.z; w = fW; } //---------------------------------------------------------------------------- inline float& Vector4::operator[] (int i) { return ((float*)this)[i]; } //---------------------------------------------------------------------------- inline const float& Vector4::operator[] (int i) const { return ((float*)this)[i]; } //---------------------------------------------------------------------------- inline Vector4& Vector4::operator= (const Vector4& rkVector) { x = rkVector.x; y = rkVector.y; z = rkVector.z; w = rkVector.w; return *this; } //---------------------------------------------------------------------------- inline bool Vector4::operator== (const Vector4& rkVector) const { return ( (x == rkVector.x) && (y == rkVector.y) && (z == rkVector.z) && (w == rkVector.w)); } //---------------------------------------------------------------------------- inline bool Vector4::operator!= (const Vector4& rkVector) const { return ( x != rkVector.x || y != rkVector.y || z != rkVector.z || w != rkVector.w); } //---------------------------------------------------------------------------- inline Vector4 Vector4::operator+ (const Vector4& rkVector) const { return Vector4(x + rkVector.x, y + rkVector.y, z + rkVector.z, w + rkVector.w); } //---------------------------------------------------------------------------- inline Vector4 Vector4::operator- (const Vector4& rkVector) const { return Vector4(x - rkVector.x, y - rkVector.y, z - rkVector.z, w - rkVector.w); } //---------------------------------------------------------------------------- inline Vector4 Vector4::operator* (float fScalar) const { return Vector4(fScalar*x, fScalar*y, fScalar*z, fScalar*w); } //---------------------------------------------------------------------------- inline Vector4 Vector4::operator- () const { return Vector4( -x, -y, -z, -w); } //---------------------------------------------------------------------------- inline Vector4& Vector4::operator+= (const Vector4& rkVector) { x += rkVector.x; y += rkVector.y; z += rkVector.z; w += rkVector.w; return *this; } //---------------------------------------------------------------------------- inline Vector4& Vector4::operator-= (const Vector4& rkVector) { x -= rkVector.x; y -= rkVector.y; z -= rkVector.z; w -= rkVector.w; return *this; } //---------------------------------------------------------------------------- inline Vector4 Vector4::lerp(const Vector4& v, float alpha) const { return (*this) + (v - *this) * alpha; } //---------------------------------------------------------------------------- inline Vector4& Vector4::operator*= (float fScalar) { x *= fScalar; y *= fScalar; z *= fScalar; w *= fScalar; return *this; } //---------------------------------------------------------------------------- inline float Vector4::dot(const Vector4& rkVector) const { return x*rkVector.x + y*rkVector.y + z*rkVector.z + w*rkVector.w; } //---------------------------------------------------------------------------- inline Vector4 Vector4::min(const Vector4 &v) const { return Vector4(G3D::min(v.x, x), G3D::min(v.y, y), G3D::min(v.z, z), G3D::min(v.w, w)); } //---------------------------------------------------------------------------- inline Vector4 Vector4::max(const Vector4 &v) const { return Vector4(G3D::max(v.x, x), G3D::max(v.y, y), G3D::max(v.z, z), G3D::max(v.w, w)); } //---------------------------------------------------------------------------- inline bool Vector4::isZero() const { return (x == 0.0f) && (y == 0.0f) && (z == 0.0f) && (w == 0.0f); } //---------------------------------------------------------------------------- inline bool Vector4::isFinite() const { return G3D::isFinite(x) && G3D::isFinite(y) && G3D::isFinite(z) && G3D::isFinite(w); } //---------------------------------------------------------------------------- inline bool Vector4::isUnit() const { return squaredLength() == 1.0; } //---------------------------------------------------------------------------- inline float Vector4::length() const { return sqrtf(squaredLength()); } //---------------------------------------------------------------------------- inline float Vector4::squaredLength() const { return x * x + y * y + z * z + w * w; } } template <> struct HashTrait<G3D::Vector4> { static size_t hashCode(const G3D::Vector4& key) { return key.hashCode(); } }; template<> struct PositionTrait<class G3D::Vector4> { static void getPosition(const G3D::Vector4& v, G3D::Vector3& p) { p = v.xyz(); } }; inline G3D::Vector4 operator* (float s, const G3D::Vector4& v) { return v * s; } #endif
<?php // $Id$ /** * @file * Default theme implementation to present all user profile data. * * This template is used when viewing a registered member's profile page, * e.g., example.com/user/123. 123 being the users ID. * * Use render($user_profile) to print all profile items, or print a subset * such as render($content['field_example']). Always call render($user_profile) * at the end in order to print all remaining items. If the item is a category, * it will contain all its profile items. By default, $user_profile['summary'] * is provided which contains data on the user's history. Other data can be * included by modules. $user_profile['user_picture'] is available * for showing the account picture. * * Available variables: * - $user_profile: An array of profile items. Use render() to print them. * - Field variables: for each field instance attached to the user a * corresponding variable is defined; e.g., $user->field_example has a * variable $field_example defined. When needing to access a field's raw * values, developers/themers are strongly encouraged to use these * variables. Otherwise they will have to explicitly specify the desired * field language, e.g. $user->field_example['en'], thus overriding any * language negotiation rule that was previously applied. * * @see user-profile-category.tpl.php * Where the html is handled for the group. * @see user-profile-item.tpl.php * Where the html is handled for each item in the group. * @see template_preprocess_user_profile() */ ?> <div class="profile"<?php print $attributes; ?>> <?php print render($user_profile); ?> </div>
/* BlueZ - Bluetooth protocol stack for Linux Copyright (C) 2000-2001 Qualcomm Incorporated Copyright 2010, Sony Ericsson Mobile Communications AB Written 2000,2001 by Maxim Krasnyansky <maxk@qualcomm.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation; 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 OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) AND AUTHOR(S) BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ALL LIABILITY, INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS, RELATING TO USE OF THIS SOFTWARE IS DISCLAIMED. */ /* Bluetooth L2CAP core and sockets. */ #include <linux/module.h> #include <linux/types.h> #include <linux/capability.h> #include <linux/errno.h> #include <linux/kernel.h> #include <linux/sched.h> #include <linux/slab.h> #include <linux/poll.h> #include <linux/fcntl.h> #include <linux/init.h> #include <linux/interrupt.h> #include <linux/socket.h> #include <linux/skbuff.h> #include <linux/list.h> #include <linux/device.h> #include <net/sock.h> #include <asm/system.h> #include <asm/uaccess.h> #include <asm/unaligned.h> #include <net/bluetooth/bluetooth.h> #include <net/bluetooth/hci_core.h> #include <net/bluetooth/l2cap.h> #define VERSION "2.13" static u32 l2cap_feat_mask = 0x0080; static u8 l2cap_fixed_chan[8] = { 0x02, }; static const struct proto_ops l2cap_sock_ops; static struct bt_sock_list l2cap_sk_list = { .lock = __RW_LOCK_UNLOCKED(l2cap_sk_list.lock) }; static void __l2cap_sock_close(struct sock *sk, int reason); static void l2cap_sock_close(struct sock *sk); static void l2cap_sock_kill(struct sock *sk); static struct sk_buff *l2cap_build_cmd(struct l2cap_conn *conn, u8 code, u8 ident, u16 dlen, void *data); /* ---- L2CAP timers ---- */ static void l2cap_sock_timeout(unsigned long arg) { struct sock *sk = (struct sock *) arg; int reason; BT_DBG("sock %p state %d", sk, sk->sk_state); bh_lock_sock(sk); if (sk->sk_state == BT_CONNECTED || sk->sk_state == BT_CONFIG) reason = ECONNREFUSED; else if (sk->sk_state == BT_CONNECT && l2cap_pi(sk)->sec_level != BT_SECURITY_SDP) reason = ECONNREFUSED; else reason = ETIMEDOUT; __l2cap_sock_close(sk, reason); bh_unlock_sock(sk); l2cap_sock_kill(sk); sock_put(sk); } static void l2cap_sock_set_timer(struct sock *sk, long timeout) { BT_DBG("sk %p state %d timeout %ld", sk, sk->sk_state, timeout); sk_reset_timer(sk, &sk->sk_timer, jiffies + timeout); } static void l2cap_sock_clear_timer(struct sock *sk) { BT_DBG("sock %p state %d", sk, sk->sk_state); sk_stop_timer(sk, &sk->sk_timer); } /* ---- L2CAP channels ---- */ static struct sock *__l2cap_get_chan_by_dcid(struct l2cap_chan_list *l, u16 cid) { struct sock *s; for (s = l->head; s; s = l2cap_pi(s)->next_c) { if (l2cap_pi(s)->dcid == cid) break; } return s; } static struct sock *__l2cap_get_chan_by_scid(struct l2cap_chan_list *l, u16 cid) { struct sock *s; for (s = l->head; s; s = l2cap_pi(s)->next_c) { if (l2cap_pi(s)->scid == cid) break; } return s; } /* Find channel with given SCID. * Returns locked socket */ static inline struct sock *l2cap_get_chan_by_scid(struct l2cap_chan_list *l, u16 cid) { struct sock *s; read_lock(&l->lock); s = __l2cap_get_chan_by_scid(l, cid); if (s) bh_lock_sock(s); read_unlock(&l->lock); return s; } static struct sock *__l2cap_get_chan_by_ident(struct l2cap_chan_list *l, u8 ident) { struct sock *s; for (s = l->head; s; s = l2cap_pi(s)->next_c) { if (l2cap_pi(s)->ident == ident) break; } return s; } static inline struct sock *l2cap_get_chan_by_ident(struct l2cap_chan_list *l, u8 ident) { struct sock *s; read_lock(&l->lock); s = __l2cap_get_chan_by_ident(l, ident); if (s) bh_lock_sock(s); read_unlock(&l->lock); return s; } static u16 l2cap_alloc_cid(struct l2cap_chan_list *l) { u16 cid = 0x0040; for (; cid < 0xffff; cid++) { if(!__l2cap_get_chan_by_scid(l, cid)) return cid; } return 0; } static inline void __l2cap_chan_link(struct l2cap_chan_list *l, struct sock *sk) { sock_hold(sk); if (l->head) l2cap_pi(l->head)->prev_c = sk; l2cap_pi(sk)->next_c = l->head; l2cap_pi(sk)->prev_c = NULL; l->head = sk; } static inline void l2cap_chan_unlink(struct l2cap_chan_list *l, struct sock *sk) { struct sock *next = l2cap_pi(sk)->next_c, *prev = l2cap_pi(sk)->prev_c; write_lock_bh(&l->lock); if (sk == l->head) l->head = next; if (next) l2cap_pi(next)->prev_c = prev; if (prev) l2cap_pi(prev)->next_c = next; write_unlock_bh(&l->lock); __sock_put(sk); } static void __l2cap_chan_add(struct l2cap_conn *conn, struct sock *sk, struct sock *parent) { struct l2cap_chan_list *l = &conn->chan_list; BT_DBG("conn %p, psm 0x%2.2x, dcid 0x%4.4x", conn, l2cap_pi(sk)->psm, l2cap_pi(sk)->dcid); conn->disc_reason = 0x13; l2cap_pi(sk)->conn = conn; if (sk->sk_type == SOCK_SEQPACKET) { /* Alloc CID for connection-oriented socket */ l2cap_pi(sk)->scid = l2cap_alloc_cid(l); } else if (sk->sk_type == SOCK_DGRAM) { /* Connectionless socket */ l2cap_pi(sk)->scid = 0x0002; l2cap_pi(sk)->dcid = 0x0002; l2cap_pi(sk)->omtu = L2CAP_DEFAULT_MTU; } else { /* Raw socket can send/recv signalling messages only */ l2cap_pi(sk)->scid = 0x0001; l2cap_pi(sk)->dcid = 0x0001; l2cap_pi(sk)->omtu = L2CAP_DEFAULT_MTU; } __l2cap_chan_link(l, sk); if (parent) bt_accept_enqueue(parent, sk); } /* Delete channel. * Must be called on the locked socket. */ static void l2cap_chan_del(struct sock *sk, int err) { struct l2cap_conn *conn = l2cap_pi(sk)->conn; struct sock *parent = bt_sk(sk)->parent; l2cap_sock_clear_timer(sk); BT_DBG("sk %p, conn %p, err %d", sk, conn, err); if (conn) { /* Unlink from channel list */ l2cap_chan_unlink(&conn->chan_list, sk); l2cap_pi(sk)->conn = NULL; hci_conn_put(conn->hcon); } sk->sk_state = BT_CLOSED; sock_set_flag(sk, SOCK_ZAPPED); if (err) sk->sk_err = err; if (parent) { bt_accept_unlink(sk); parent->sk_data_ready(parent, 0); } else sk->sk_state_change(sk); } /* Service level security */ static inline int l2cap_check_security(struct sock *sk) { struct l2cap_conn *conn = l2cap_pi(sk)->conn; __u8 auth_type; if (l2cap_pi(sk)->psm == cpu_to_le16(0x0001)) { if (l2cap_pi(sk)->sec_level == BT_SECURITY_HIGH) auth_type = HCI_AT_NO_BONDING_MITM; else auth_type = HCI_AT_NO_BONDING; if (l2cap_pi(sk)->sec_level == BT_SECURITY_LOW) l2cap_pi(sk)->sec_level = BT_SECURITY_SDP; } else { switch (l2cap_pi(sk)->sec_level) { case BT_SECURITY_HIGH: auth_type = HCI_AT_GENERAL_BONDING_MITM; break; case BT_SECURITY_MEDIUM: auth_type = HCI_AT_GENERAL_BONDING; break; default: auth_type = HCI_AT_NO_BONDING; break; } } return hci_conn_security(conn->hcon, l2cap_pi(sk)->sec_level, auth_type); } static inline u8 l2cap_get_ident(struct l2cap_conn *conn) { u8 id; /* Get next available identificator. * 1 - 128 are used by kernel. * 129 - 199 are reserved. * 200 - 254 are used by utilities like l2ping, etc. */ spin_lock_bh(&conn->lock); if (++conn->tx_ident > 128) conn->tx_ident = 1; id = conn->tx_ident; spin_unlock_bh(&conn->lock); return id; } static inline int l2cap_send_cmd(struct l2cap_conn *conn, u8 ident, u8 code, u16 len, void *data) { struct sk_buff *skb = l2cap_build_cmd(conn, code, ident, len, data); BT_DBG("code 0x%2.2x", code); if (!skb) return -ENOMEM; return hci_send_acl(conn->hcon, skb, 0); } static void l2cap_do_start(struct sock *sk) { struct l2cap_conn *conn = l2cap_pi(sk)->conn; if (conn->info_state & L2CAP_INFO_FEAT_MASK_REQ_SENT) { if (!(conn->info_state & L2CAP_INFO_FEAT_MASK_REQ_DONE)) return; if (l2cap_check_security(sk)) { struct l2cap_conn_req req; req.scid = cpu_to_le16(l2cap_pi(sk)->scid); req.psm = l2cap_pi(sk)->psm; l2cap_pi(sk)->ident = l2cap_get_ident(conn); l2cap_send_cmd(conn, l2cap_pi(sk)->ident, L2CAP_CONN_REQ, sizeof(req), &req); l2cap_pi(sk)->conf_state |= L2CAP_CONF_CONNECT_REQ_SENT; } } else { struct l2cap_info_req req; req.type = cpu_to_le16(L2CAP_IT_FEAT_MASK); conn->info_state |= L2CAP_INFO_FEAT_MASK_REQ_SENT; conn->info_ident = l2cap_get_ident(conn); mod_timer(&conn->info_timer, jiffies + msecs_to_jiffies(L2CAP_INFO_TIMEOUT)); l2cap_send_cmd(conn, conn->info_ident, L2CAP_INFO_REQ, sizeof(req), &req); } } /* ---- L2CAP connections ---- */ static void l2cap_conn_start(struct l2cap_conn *conn) { struct l2cap_chan_list *l = &conn->chan_list; struct sock *sk; BT_DBG("conn %p", conn); read_lock(&l->lock); for (sk = l->head; sk; sk = l2cap_pi(sk)->next_c) { bh_lock_sock(sk); if (sk->sk_type != SOCK_SEQPACKET) { bh_unlock_sock(sk); continue; } if (sk->sk_state == BT_CONNECT) { if (l2cap_check_security(sk)) { struct l2cap_conn_req req; req.scid = cpu_to_le16(l2cap_pi(sk)->scid); req.psm = l2cap_pi(sk)->psm; l2cap_pi(sk)->ident = l2cap_get_ident(conn); l2cap_send_cmd(conn, l2cap_pi(sk)->ident, L2CAP_CONN_REQ, sizeof(req), &req); l2cap_pi(sk)->conf_state |= L2CAP_CONF_CONNECT_REQ_SENT; } } else if (sk->sk_state == BT_CONNECT2) { struct l2cap_conn_rsp rsp; rsp.scid = cpu_to_le16(l2cap_pi(sk)->dcid); rsp.dcid = cpu_to_le16(l2cap_pi(sk)->scid); if (l2cap_check_security(sk)) { if (bt_sk(sk)->defer_setup) { struct sock *parent = bt_sk(sk)->parent; rsp.result = cpu_to_le16(L2CAP_CR_PEND); rsp.status = cpu_to_le16(L2CAP_CS_AUTHOR_PEND); parent->sk_data_ready(parent, 0); } else { sk->sk_state = BT_CONFIG; rsp.result = cpu_to_le16(L2CAP_CR_SUCCESS); rsp.status = cpu_to_le16(L2CAP_CS_NO_INFO); } } else { rsp.result = cpu_to_le16(L2CAP_CR_PEND); rsp.status = cpu_to_le16(L2CAP_CS_AUTHEN_PEND); } l2cap_send_cmd(conn, l2cap_pi(sk)->ident, L2CAP_CONN_RSP, sizeof(rsp), &rsp); } bh_unlock_sock(sk); } read_unlock(&l->lock); } static void l2cap_conn_ready(struct l2cap_conn *conn) { struct l2cap_chan_list *l = &conn->chan_list; struct sock *sk; BT_DBG("conn %p", conn); read_lock(&l->lock); for (sk = l->head; sk; sk = l2cap_pi(sk)->next_c) { bh_lock_sock(sk); if (sk->sk_type != SOCK_SEQPACKET) { l2cap_sock_clear_timer(sk); sk->sk_state = BT_CONNECTED; sk->sk_state_change(sk); } else if (sk->sk_state == BT_CONNECT) l2cap_do_start(sk); bh_unlock_sock(sk); } read_unlock(&l->lock); } /* Notify sockets that we cannot guaranty reliability anymore */ static void l2cap_conn_unreliable(struct l2cap_conn *conn, int err) { struct l2cap_chan_list *l = &conn->chan_list; struct sock *sk; BT_DBG("conn %p", conn); read_lock(&l->lock); for (sk = l->head; sk; sk = l2cap_pi(sk)->next_c) { if (l2cap_pi(sk)->force_reliable) sk->sk_err = err; } read_unlock(&l->lock); } static void l2cap_info_timeout(unsigned long arg) { struct l2cap_conn *conn = (void *) arg; conn->info_state |= L2CAP_INFO_FEAT_MASK_REQ_DONE; conn->info_ident = 0; l2cap_conn_start(conn); } static struct l2cap_conn *l2cap_conn_add(struct hci_conn *hcon, u8 status) { struct l2cap_conn *conn = hcon->l2cap_data; if (conn || status) return conn; conn = kzalloc(sizeof(struct l2cap_conn), GFP_ATOMIC); if (!conn) return NULL; hcon->l2cap_data = conn; conn->hcon = hcon; BT_DBG("hcon %p conn %p", hcon, conn); conn->mtu = hcon->hdev->acl_mtu; conn->src = &hcon->hdev->bdaddr; conn->dst = &hcon->dst; conn->feat_mask = 0; setup_timer(&conn->info_timer, l2cap_info_timeout, (unsigned long) conn); spin_lock_init(&conn->lock); rwlock_init(&conn->chan_list.lock); conn->disc_reason = 0x13; return conn; } static void l2cap_conn_del(struct hci_conn *hcon, int err) { struct l2cap_conn *conn = hcon->l2cap_data; struct sock *sk; if (!conn) return; BT_DBG("hcon %p conn %p, err %d", hcon, conn, err); kfree_skb(conn->rx_skb); /* Kill channels */ while ((sk = conn->chan_list.head)) { bh_lock_sock(sk); l2cap_chan_del(sk, err); bh_unlock_sock(sk); l2cap_sock_kill(sk); } if (conn->info_state & L2CAP_INFO_FEAT_MASK_REQ_SENT) del_timer_sync(&conn->info_timer); hcon->l2cap_data = NULL; kfree(conn); } static inline void l2cap_chan_add(struct l2cap_conn *conn, struct sock *sk, struct sock *parent) { struct l2cap_chan_list *l = &conn->chan_list; write_lock_bh(&l->lock); __l2cap_chan_add(conn, sk, parent); write_unlock_bh(&l->lock); } /* ---- Socket interface ---- */ static struct sock *__l2cap_get_sock_by_addr(__le16 psm, bdaddr_t *src) { struct sock *sk; struct hlist_node *node; sk_for_each(sk, node, &l2cap_sk_list.head) if (l2cap_pi(sk)->sport == psm && !bacmp(&bt_sk(sk)->src, src)) goto found; sk = NULL; found: return sk; } /* Find socket with psm and source bdaddr. * Returns closest match. */ static struct sock *__l2cap_get_sock_by_psm(int state, __le16 psm, bdaddr_t *src) { struct sock *sk = NULL, *sk1 = NULL; struct hlist_node *node; sk_for_each(sk, node, &l2cap_sk_list.head) { if (state && sk->sk_state != state) continue; if (l2cap_pi(sk)->psm == psm) { /* Exact match. */ if (!bacmp(&bt_sk(sk)->src, src)) break; /* Closest match */ if (!bacmp(&bt_sk(sk)->src, BDADDR_ANY)) sk1 = sk; } } return node ? sk : sk1; } /* Find socket with given address (psm, src). * Returns locked socket */ static inline struct sock *l2cap_get_sock_by_psm(int state, __le16 psm, bdaddr_t *src) { struct sock *s; read_lock(&l2cap_sk_list.lock); s = __l2cap_get_sock_by_psm(state, psm, src); if (s) bh_lock_sock(s); read_unlock(&l2cap_sk_list.lock); return s; } static void l2cap_sock_destruct(struct sock *sk) { BT_DBG("sk %p", sk); skb_queue_purge(&sk->sk_receive_queue); skb_queue_purge(&sk->sk_write_queue); } static void l2cap_sock_cleanup_listen(struct sock *parent) { struct sock *sk; BT_DBG("parent %p", parent); /* Close not yet accepted channels */ while ((sk = bt_accept_dequeue(parent, NULL))) l2cap_sock_close(sk); parent->sk_state = BT_CLOSED; sock_set_flag(parent, SOCK_ZAPPED); } /* Kill socket (only if zapped and orphan) * Must be called on unlocked socket. */ static void l2cap_sock_kill(struct sock *sk) { if (!sock_flag(sk, SOCK_ZAPPED) || sk->sk_socket) return; BT_DBG("sk %p state %d", sk, sk->sk_state); /* Kill poor orphan */ bt_sock_unlink(&l2cap_sk_list, sk); sock_set_flag(sk, SOCK_DEAD); sock_put(sk); } static void __l2cap_sock_close(struct sock *sk, int reason) { BT_DBG("sk %p state %d socket %p", sk, sk->sk_state, sk->sk_socket); switch (sk->sk_state) { case BT_LISTEN: l2cap_sock_cleanup_listen(sk); break; case BT_CONNECTED: case BT_CONFIG: if (sk->sk_type == SOCK_SEQPACKET) { struct l2cap_conn *conn = l2cap_pi(sk)->conn; struct l2cap_disconn_req req; sk->sk_state = BT_DISCONN; l2cap_sock_set_timer(sk, sk->sk_sndtimeo); req.dcid = cpu_to_le16(l2cap_pi(sk)->dcid); req.scid = cpu_to_le16(l2cap_pi(sk)->scid); l2cap_send_cmd(conn, l2cap_get_ident(conn), L2CAP_DISCONN_REQ, sizeof(req), &req); } else l2cap_chan_del(sk, reason); break; case BT_CONNECT2: if (sk->sk_type == SOCK_SEQPACKET) { struct l2cap_conn *conn = l2cap_pi(sk)->conn; struct l2cap_conn_rsp rsp; __u16 result; if (bt_sk(sk)->defer_setup) result = L2CAP_CR_SEC_BLOCK; else result = L2CAP_CR_BAD_PSM; rsp.scid = cpu_to_le16(l2cap_pi(sk)->dcid); rsp.dcid = cpu_to_le16(l2cap_pi(sk)->scid); rsp.result = cpu_to_le16(result); rsp.status = cpu_to_le16(L2CAP_CS_NO_INFO); l2cap_send_cmd(conn, l2cap_pi(sk)->ident, L2CAP_CONN_RSP, sizeof(rsp), &rsp); } else l2cap_chan_del(sk, reason); break; case BT_CONNECT: case BT_DISCONN: l2cap_chan_del(sk, reason); break; default: sock_set_flag(sk, SOCK_ZAPPED); break; } } /* Must be called on unlocked socket. */ static void l2cap_sock_close(struct sock *sk) { l2cap_sock_clear_timer(sk); lock_sock(sk); __l2cap_sock_close(sk, ECONNRESET); release_sock(sk); l2cap_sock_kill(sk); } static void l2cap_sock_init(struct sock *sk, struct sock *parent) { struct l2cap_pinfo *pi = l2cap_pi(sk); BT_DBG("sk %p", sk); if (parent) { sk->sk_type = parent->sk_type; bt_sk(sk)->defer_setup = bt_sk(parent)->defer_setup; pi->imtu = l2cap_pi(parent)->imtu; pi->omtu = l2cap_pi(parent)->omtu; pi->sec_level = l2cap_pi(parent)->sec_level; pi->role_switch = l2cap_pi(parent)->role_switch; pi->force_reliable = l2cap_pi(parent)->force_reliable; } else { pi->imtu = L2CAP_DEFAULT_MTU; pi->omtu = 0; pi->sec_level = BT_SECURITY_LOW; pi->role_switch = 0; pi->force_reliable = 0; } /* Default config options */ pi->conf_len = 0; pi->flush_to = L2CAP_DEFAULT_FLUSH_TO; } static struct proto l2cap_proto = { .name = "L2CAP", .owner = THIS_MODULE, .obj_size = sizeof(struct l2cap_pinfo) }; static struct sock *l2cap_sock_alloc(struct net *net, struct socket *sock, int proto, gfp_t prio) { struct sock *sk; sk = sk_alloc(net, PF_BLUETOOTH, prio, &l2cap_proto); if (!sk) return NULL; sock_init_data(sock, sk); INIT_LIST_HEAD(&bt_sk(sk)->accept_q); sk->sk_destruct = l2cap_sock_destruct; sk->sk_sndtimeo = msecs_to_jiffies(L2CAP_CONN_TIMEOUT); sock_reset_flag(sk, SOCK_ZAPPED); sk->sk_protocol = proto; sk->sk_state = BT_OPEN; setup_timer(&sk->sk_timer, l2cap_sock_timeout, (unsigned long) sk); bt_sock_link(&l2cap_sk_list, sk); return sk; } static int l2cap_sock_create(struct net *net, struct socket *sock, int protocol) { struct sock *sk; BT_DBG("sock %p", sock); sock->state = SS_UNCONNECTED; if (sock->type != SOCK_SEQPACKET && sock->type != SOCK_DGRAM && sock->type != SOCK_RAW) return -ESOCKTNOSUPPORT; if (sock->type == SOCK_RAW && !capable(CAP_NET_RAW)) return -EPERM; sock->ops = &l2cap_sock_ops; sk = l2cap_sock_alloc(net, sock, protocol, GFP_ATOMIC); if (!sk) return -ENOMEM; l2cap_sock_init(sk, NULL); return 0; } static int l2cap_sock_bind(struct socket *sock, struct sockaddr *addr, int alen) { struct sock *sk = sock->sk; struct sockaddr_l2 la; int len, err = 0; BT_DBG("sk %p", sk); if (!addr || addr->sa_family != AF_BLUETOOTH) return -EINVAL; memset(&la, 0, sizeof(la)); len = min_t(unsigned int, sizeof(la), alen); memcpy(&la, addr, len); if (la.l2_cid) return -EINVAL; lock_sock(sk); if (sk->sk_state != BT_OPEN) { err = -EBADFD; goto done; } if (la.l2_psm && btohs(la.l2_psm) < 0x1001 && !capable(CAP_NET_BIND_SERVICE)) { err = -EACCES; goto done; } write_lock_bh(&l2cap_sk_list.lock); if (la.l2_psm && __l2cap_get_sock_by_addr(la.l2_psm, &la.l2_bdaddr)) { err = -EADDRINUSE; } else { /* Save source address */ bacpy(&bt_sk(sk)->src, &la.l2_bdaddr); l2cap_pi(sk)->psm = la.l2_psm; l2cap_pi(sk)->sport = la.l2_psm; sk->sk_state = BT_BOUND; if (btohs(la.l2_psm) == 0x0001 || btohs(la.l2_psm) == 0x0003) l2cap_pi(sk)->sec_level = BT_SECURITY_SDP; } write_unlock_bh(&l2cap_sk_list.lock); done: release_sock(sk); return err; } static int l2cap_do_connect(struct sock *sk) { bdaddr_t *src = &bt_sk(sk)->src; bdaddr_t *dst = &bt_sk(sk)->dst; struct l2cap_conn *conn; struct hci_conn *hcon; struct hci_dev *hdev; __u8 auth_type; int err = 0; BT_DBG("%s -> %s psm 0x%2.2x", batostr(src), batostr(dst), l2cap_pi(sk)->psm); if (!(hdev = hci_get_route(dst, src))) return -EHOSTUNREACH; hci_dev_lock_bh(hdev); err = -ENOMEM; if (sk->sk_type == SOCK_RAW) { switch (l2cap_pi(sk)->sec_level) { case BT_SECURITY_HIGH: auth_type = HCI_AT_DEDICATED_BONDING_MITM; break; case BT_SECURITY_MEDIUM: auth_type = HCI_AT_DEDICATED_BONDING; break; default: auth_type = HCI_AT_NO_BONDING; break; } } else if (l2cap_pi(sk)->psm == cpu_to_le16(0x0001)) { if (l2cap_pi(sk)->sec_level == BT_SECURITY_HIGH) auth_type = HCI_AT_NO_BONDING_MITM; else auth_type = HCI_AT_NO_BONDING; if (l2cap_pi(sk)->sec_level == BT_SECURITY_LOW) l2cap_pi(sk)->sec_level = BT_SECURITY_SDP; } else { switch (l2cap_pi(sk)->sec_level) { case BT_SECURITY_HIGH: auth_type = HCI_AT_GENERAL_BONDING_MITM; break; case BT_SECURITY_MEDIUM: auth_type = HCI_AT_GENERAL_BONDING; break; default: auth_type = HCI_AT_NO_BONDING; break; } } hcon = hci_connect(hdev, ACL_LINK, dst, l2cap_pi(sk)->sec_level, auth_type); if (!hcon) goto done; conn = l2cap_conn_add(hcon, 0); if (!conn) { hci_conn_put(hcon); goto done; } err = 0; /* Update source addr of the socket */ bacpy(src, conn->src); l2cap_chan_add(conn, sk, NULL); sk->sk_state = BT_CONNECT; l2cap_sock_set_timer(sk, sk->sk_sndtimeo); if (hcon->state == BT_CONNECTED) { if (sk->sk_type != SOCK_SEQPACKET) { l2cap_sock_clear_timer(sk); sk->sk_state = BT_CONNECTED; } else l2cap_do_start(sk); } done: hci_dev_unlock_bh(hdev); hci_dev_put(hdev); return err; } static int l2cap_sock_connect(struct socket *sock, struct sockaddr *addr, int alen, int flags) { struct sock *sk = sock->sk; struct sockaddr_l2 la; int len, err = 0; BT_DBG("sk %p", sk); if (!addr || addr->sa_family != AF_BLUETOOTH) return -EINVAL; memset(&la, 0, sizeof(la)); len = min_t(unsigned int, sizeof(la), alen); memcpy(&la, addr, len); if (la.l2_cid) return -EINVAL; lock_sock(sk); if (sk->sk_type == SOCK_SEQPACKET && !la.l2_psm) { err = -EINVAL; goto done; } switch(sk->sk_state) { case BT_CONNECT: case BT_CONNECT2: case BT_CONFIG: /* Already connecting */ goto wait; case BT_CONNECTED: /* Already connected */ goto done; case BT_OPEN: case BT_BOUND: /* Can connect */ break; default: err = -EBADFD; goto done; } /* Set destination address and psm */ bacpy(&bt_sk(sk)->dst, &la.l2_bdaddr); l2cap_pi(sk)->psm = la.l2_psm; if ((err = l2cap_do_connect(sk))) goto done; wait: err = bt_sock_wait_state(sk, BT_CONNECTED, sock_sndtimeo(sk, flags & O_NONBLOCK)); done: release_sock(sk); return err; } static int l2cap_sock_listen(struct socket *sock, int backlog) { struct sock *sk = sock->sk; int err = 0; BT_DBG("sk %p backlog %d", sk, backlog); lock_sock(sk); if (sk->sk_state != BT_BOUND || sock->type != SOCK_SEQPACKET) { err = -EBADFD; goto done; } if (!l2cap_pi(sk)->psm) { bdaddr_t *src = &bt_sk(sk)->src; u16 psm; err = -EINVAL; write_lock_bh(&l2cap_sk_list.lock); for (psm = 0x1001; psm < 0x1100; psm += 2) if (!__l2cap_get_sock_by_addr(htobs(psm), src)) { l2cap_pi(sk)->psm = htobs(psm); l2cap_pi(sk)->sport = htobs(psm); err = 0; break; } write_unlock_bh(&l2cap_sk_list.lock); if (err < 0) goto done; } sk->sk_max_ack_backlog = backlog; sk->sk_ack_backlog = 0; sk->sk_state = BT_LISTEN; done: release_sock(sk); return err; } static int l2cap_sock_accept(struct socket *sock, struct socket *newsock, int flags) { DECLARE_WAITQUEUE(wait, current); struct sock *sk = sock->sk, *nsk; long timeo; int err = 0; lock_sock_nested(sk, SINGLE_DEPTH_NESTING); if (sk->sk_state != BT_LISTEN) { err = -EBADFD; goto done; } timeo = sock_rcvtimeo(sk, flags & O_NONBLOCK); BT_DBG("sk %p timeo %ld", sk, timeo); /* Wait for an incoming connection. (wake-one). */ add_wait_queue_exclusive(sk->sk_sleep, &wait); while (!(nsk = bt_accept_dequeue(sk, newsock))) { set_current_state(TASK_INTERRUPTIBLE); if (!timeo) { err = -EAGAIN; break; } release_sock(sk); timeo = schedule_timeout(timeo); lock_sock_nested(sk, SINGLE_DEPTH_NESTING); if (sk->sk_state != BT_LISTEN) { err = -EBADFD; break; } if (signal_pending(current)) { err = sock_intr_errno(timeo); break; } } set_current_state(TASK_RUNNING); remove_wait_queue(sk->sk_sleep, &wait); if (err) goto done; newsock->state = SS_CONNECTED; BT_DBG("new socket %p", nsk); done: release_sock(sk); return err; } static int l2cap_sock_getname(struct socket *sock, struct sockaddr *addr, int *len, int peer) { struct sockaddr_l2 *la = (struct sockaddr_l2 *) addr; struct sock *sk = sock->sk; BT_DBG("sock %p, sk %p", sock, sk); addr->sa_family = AF_BLUETOOTH; *len = sizeof(struct sockaddr_l2); if (peer) { la->l2_psm = l2cap_pi(sk)->psm; bacpy(&la->l2_bdaddr, &bt_sk(sk)->dst); la->l2_cid = htobs(l2cap_pi(sk)->dcid); } else { la->l2_psm = l2cap_pi(sk)->sport; bacpy(&la->l2_bdaddr, &bt_sk(sk)->src); la->l2_cid = htobs(l2cap_pi(sk)->scid); } return 0; } static inline int l2cap_do_send(struct sock *sk, struct msghdr *msg, int len) { struct l2cap_conn *conn = l2cap_pi(sk)->conn; struct sk_buff *skb, **frag; int err, hlen, count, sent=0; struct l2cap_hdr *lh; BT_DBG("sk %p len %d", sk, len); /* First fragment (with L2CAP header) */ if (sk->sk_type == SOCK_DGRAM) hlen = L2CAP_HDR_SIZE + 2; else hlen = L2CAP_HDR_SIZE; count = min_t(unsigned int, (conn->mtu - hlen), len); skb = bt_skb_send_alloc(sk, hlen + count, msg->msg_flags & MSG_DONTWAIT, &err); if (!skb) return err; /* Create L2CAP header */ lh = (struct l2cap_hdr *) skb_put(skb, L2CAP_HDR_SIZE); lh->cid = cpu_to_le16(l2cap_pi(sk)->dcid); lh->len = cpu_to_le16(len + (hlen - L2CAP_HDR_SIZE)); if (sk->sk_type == SOCK_DGRAM) put_unaligned(l2cap_pi(sk)->psm, (__le16 *) skb_put(skb, 2)); if (memcpy_fromiovec(skb_put(skb, count), msg->msg_iov, count)) { err = -EFAULT; goto fail; } sent += count; len -= count; /* Continuation fragments (no L2CAP header) */ frag = &skb_shinfo(skb)->frag_list; while (len) { count = min_t(unsigned int, conn->mtu, len); *frag = bt_skb_send_alloc(sk, count, msg->msg_flags & MSG_DONTWAIT, &err); if (!*frag) goto fail; if (memcpy_fromiovec(skb_put(*frag, count), msg->msg_iov, count)) { err = -EFAULT; goto fail; } sent += count; len -= count; frag = &(*frag)->next; } if ((err = hci_send_acl(conn->hcon, skb, 0)) < 0) goto fail; return sent; fail: kfree_skb(skb); return err; } static int l2cap_sock_sendmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t len) { struct sock *sk = sock->sk; int err = 0; BT_DBG("sock %p, sk %p", sock, sk); err = sock_error(sk); if (err) return err; if (msg->msg_flags & MSG_OOB) return -EOPNOTSUPP; /* Check outgoing MTU */ if (sk->sk_type != SOCK_RAW && len > l2cap_pi(sk)->omtu) return -EINVAL; lock_sock(sk); if (sk->sk_state == BT_CONNECTED) err = l2cap_do_send(sk, msg, len); else err = -ENOTCONN; release_sock(sk); return err; } static int l2cap_sock_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t len, int flags) { struct sock *sk = sock->sk; lock_sock(sk); if (sk->sk_state == BT_CONNECT2 && bt_sk(sk)->defer_setup) { struct l2cap_conn_rsp rsp; sk->sk_state = BT_CONFIG; rsp.scid = cpu_to_le16(l2cap_pi(sk)->dcid); rsp.dcid = cpu_to_le16(l2cap_pi(sk)->scid); rsp.result = cpu_to_le16(L2CAP_CR_SUCCESS); rsp.status = cpu_to_le16(L2CAP_CS_NO_INFO); l2cap_send_cmd(l2cap_pi(sk)->conn, l2cap_pi(sk)->ident, L2CAP_CONN_RSP, sizeof(rsp), &rsp); release_sock(sk); return 0; } release_sock(sk); return bt_sock_recvmsg(iocb, sock, msg, len, flags); } static int l2cap_sock_setsockopt_old(struct socket *sock, int optname, char __user *optval, int optlen) { struct sock *sk = sock->sk; struct l2cap_options opts; int len, err = 0; u32 opt; BT_DBG("sk %p", sk); lock_sock(sk); switch (optname) { case L2CAP_OPTIONS: opts.imtu = l2cap_pi(sk)->imtu; opts.omtu = l2cap_pi(sk)->omtu; opts.flush_to = l2cap_pi(sk)->flush_to; opts.mode = L2CAP_MODE_BASIC; len = min_t(unsigned int, sizeof(opts), optlen); if (copy_from_user((char *) &opts, optval, len)) { err = -EFAULT; break; } l2cap_pi(sk)->imtu = opts.imtu; l2cap_pi(sk)->omtu = opts.omtu; break; case L2CAP_LM: if (get_user(opt, (u32 __user *) optval)) { err = -EFAULT; break; } if (opt & L2CAP_LM_AUTH) l2cap_pi(sk)->sec_level = BT_SECURITY_LOW; if (opt & L2CAP_LM_ENCRYPT) l2cap_pi(sk)->sec_level = BT_SECURITY_MEDIUM; if (opt & L2CAP_LM_SECURE) l2cap_pi(sk)->sec_level = BT_SECURITY_HIGH; l2cap_pi(sk)->role_switch = (opt & L2CAP_LM_MASTER); l2cap_pi(sk)->force_reliable = (opt & L2CAP_LM_RELIABLE); break; default: err = -ENOPROTOOPT; break; } release_sock(sk); return err; } static int l2cap_sock_setsockopt(struct socket *sock, int level, int optname, char __user *optval, int optlen) { struct sock *sk = sock->sk; struct bt_security sec; int len, err = 0; u32 opt; BT_DBG("sk %p", sk); if (level == SOL_L2CAP) return l2cap_sock_setsockopt_old(sock, optname, optval, optlen); if (level != SOL_BLUETOOTH) return -ENOPROTOOPT; lock_sock(sk); switch (optname) { case BT_SECURITY: if (sk->sk_type != SOCK_SEQPACKET && sk->sk_type != SOCK_RAW) { err = -EINVAL; break; } sec.level = BT_SECURITY_LOW; len = min_t(unsigned int, sizeof(sec), optlen); if (copy_from_user((char *) &sec, optval, len)) { err = -EFAULT; break; } if (sec.level < BT_SECURITY_LOW || sec.level > BT_SECURITY_HIGH) { err = -EINVAL; break; } l2cap_pi(sk)->sec_level = sec.level; break; case BT_DEFER_SETUP: if (sk->sk_state != BT_BOUND && sk->sk_state != BT_LISTEN) { err = -EINVAL; break; } if (get_user(opt, (u32 __user *) optval)) { err = -EFAULT; break; } bt_sk(sk)->defer_setup = opt; break; default: err = -ENOPROTOOPT; break; } release_sock(sk); return err; } static int l2cap_sock_getsockopt_old(struct socket *sock, int optname, char __user *optval, int __user *optlen) { struct sock *sk = sock->sk; struct l2cap_options opts; struct l2cap_conninfo cinfo; int len, err = 0; u32 opt; BT_DBG("sk %p", sk); if (get_user(len, optlen)) return -EFAULT; lock_sock(sk); switch (optname) { case L2CAP_OPTIONS: opts.imtu = l2cap_pi(sk)->imtu; opts.omtu = l2cap_pi(sk)->omtu; opts.flush_to = l2cap_pi(sk)->flush_to; opts.mode = L2CAP_MODE_BASIC; len = min_t(unsigned int, len, sizeof(opts)); if (copy_to_user(optval, (char *) &opts, len)) err = -EFAULT; break; case L2CAP_LM: switch (l2cap_pi(sk)->sec_level) { case BT_SECURITY_LOW: opt = L2CAP_LM_AUTH; break; case BT_SECURITY_MEDIUM: opt = L2CAP_LM_AUTH | L2CAP_LM_ENCRYPT; break; case BT_SECURITY_HIGH: opt = L2CAP_LM_AUTH | L2CAP_LM_ENCRYPT | L2CAP_LM_SECURE; break; default: opt = 0; break; } if (l2cap_pi(sk)->role_switch) opt |= L2CAP_LM_MASTER; if (l2cap_pi(sk)->force_reliable) opt |= L2CAP_LM_RELIABLE; if (put_user(opt, (u32 __user *) optval)) err = -EFAULT; break; case L2CAP_CONNINFO: if (sk->sk_state != BT_CONNECTED && !(sk->sk_state == BT_CONNECT2 && bt_sk(sk)->defer_setup)) { err = -ENOTCONN; break; } cinfo.hci_handle = l2cap_pi(sk)->conn->hcon->handle; memcpy(cinfo.dev_class, l2cap_pi(sk)->conn->hcon->dev_class, 3); len = min_t(unsigned int, len, sizeof(cinfo)); if (copy_to_user(optval, (char *) &cinfo, len)) err = -EFAULT; break; default: err = -ENOPROTOOPT; break; } release_sock(sk); return err; } static int l2cap_sock_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { struct sock *sk = sock->sk; struct bt_security sec; int len, err = 0; BT_DBG("sk %p", sk); if (level == SOL_L2CAP) return l2cap_sock_getsockopt_old(sock, optname, optval, optlen); if (level != SOL_BLUETOOTH) return -ENOPROTOOPT; if (get_user(len, optlen)) return -EFAULT; lock_sock(sk); switch (optname) { case BT_SECURITY: if (sk->sk_type != SOCK_SEQPACKET && sk->sk_type != SOCK_RAW) { err = -EINVAL; break; } sec.level = l2cap_pi(sk)->sec_level; len = min_t(unsigned int, len, sizeof(sec)); if (copy_to_user(optval, (char *) &sec, len)) err = -EFAULT; break; case BT_DEFER_SETUP: if (sk->sk_state != BT_BOUND && sk->sk_state != BT_LISTEN) { err = -EINVAL; break; } if (put_user(bt_sk(sk)->defer_setup, (u32 __user *) optval)) err = -EFAULT; break; default: err = -ENOPROTOOPT; break; } release_sock(sk); return err; } static int l2cap_sock_shutdown(struct socket *sock, int how) { struct sock *sk = sock->sk; int err = 0; BT_DBG("sock %p, sk %p", sock, sk); if (!sk) return 0; lock_sock(sk); if (!sk->sk_shutdown) { sk->sk_shutdown = SHUTDOWN_MASK; l2cap_sock_clear_timer(sk); __l2cap_sock_close(sk, 0); if (sock_flag(sk, SOCK_LINGER) && sk->sk_lingertime) err = bt_sock_wait_state(sk, BT_CLOSED, sk->sk_lingertime); } release_sock(sk); return err; } static int l2cap_sock_release(struct socket *sock) { struct sock *sk = sock->sk; int err; BT_DBG("sock %p, sk %p", sock, sk); if (!sk) return 0; err = l2cap_sock_shutdown(sock, 2); sock_orphan(sk); l2cap_sock_kill(sk); return err; } static void l2cap_chan_ready(struct sock *sk) { struct sock *parent = bt_sk(sk)->parent; BT_DBG("sk %p, parent %p", sk, parent); l2cap_pi(sk)->conf_state = 0; l2cap_sock_clear_timer(sk); if (!parent) { /* Outgoing channel. * Wake up socket sleeping on connect. */ sk->sk_state = BT_CONNECTED; sk->sk_state_change(sk); } else { /* Incoming channel. * Wake up socket sleeping on accept. */ parent->sk_data_ready(parent, 0); } } /* Copy frame to all raw sockets on that connection */ static void l2cap_raw_recv(struct l2cap_conn *conn, struct sk_buff *skb) { struct l2cap_chan_list *l = &conn->chan_list; struct sk_buff *nskb; struct sock * sk; BT_DBG("conn %p", conn); read_lock(&l->lock); for (sk = l->head; sk; sk = l2cap_pi(sk)->next_c) { if (sk->sk_type != SOCK_RAW) continue; /* Don't send frame to the socket it came from */ if (skb->sk == sk) continue; if (!(nskb = skb_clone(skb, GFP_ATOMIC))) continue; if (sock_queue_rcv_skb(sk, nskb)) kfree_skb(nskb); } read_unlock(&l->lock); } /* ---- L2CAP signalling commands ---- */ static struct sk_buff *l2cap_build_cmd(struct l2cap_conn *conn, u8 code, u8 ident, u16 dlen, void *data) { struct sk_buff *skb, **frag; struct l2cap_cmd_hdr *cmd; struct l2cap_hdr *lh; int len, count; BT_DBG("conn %p, code 0x%2.2x, ident 0x%2.2x, len %d", conn, code, ident, dlen); len = L2CAP_HDR_SIZE + L2CAP_CMD_HDR_SIZE + dlen; count = min_t(unsigned int, conn->mtu, len); skb = bt_skb_alloc(count, GFP_ATOMIC); if (!skb) return NULL; lh = (struct l2cap_hdr *) skb_put(skb, L2CAP_HDR_SIZE); lh->len = cpu_to_le16(L2CAP_CMD_HDR_SIZE + dlen); lh->cid = cpu_to_le16(0x0001); cmd = (struct l2cap_cmd_hdr *) skb_put(skb, L2CAP_CMD_HDR_SIZE); cmd->code = code; cmd->ident = ident; cmd->len = cpu_to_le16(dlen); if (dlen) { count -= L2CAP_HDR_SIZE + L2CAP_CMD_HDR_SIZE; memcpy(skb_put(skb, count), data, count); data += count; } len -= skb->len; /* Continuation fragments (no L2CAP header) */ frag = &skb_shinfo(skb)->frag_list; while (len) { count = min_t(unsigned int, conn->mtu, len); *frag = bt_skb_alloc(count, GFP_ATOMIC); if (!*frag) goto fail; memcpy(skb_put(*frag, count), data, count); len -= count; data += count; frag = &(*frag)->next; } return skb; fail: kfree_skb(skb); return NULL; } static inline int l2cap_get_conf_opt(void **ptr, int *type, int *olen, unsigned long *val) { struct l2cap_conf_opt *opt = *ptr; int len; len = L2CAP_CONF_OPT_SIZE + opt->len; *ptr += len; *type = opt->type; *olen = opt->len; switch (opt->len) { case 1: *val = *((u8 *) opt->val); break; case 2: *val = __le16_to_cpu(*((__le16 *) opt->val)); break; case 4: *val = __le32_to_cpu(*((__le32 *) opt->val)); break; default: *val = (unsigned long) opt->val; break; } BT_DBG("type 0x%2.2x len %d val 0x%lx", *type, opt->len, *val); return len; } static void l2cap_add_conf_opt(void **ptr, u8 type, u8 len, unsigned long val) { struct l2cap_conf_opt *opt = *ptr; BT_DBG("type 0x%2.2x len %d val 0x%lx", type, len, val); opt->type = type; opt->len = len; switch (len) { case 1: *((u8 *) opt->val) = val; break; case 2: *((__le16 *) opt->val) = cpu_to_le16(val); break; case 4: *((__le32 *) opt->val) = cpu_to_le32(val); break; default: memcpy(opt->val, (void *) val, len); break; } *ptr += L2CAP_CONF_OPT_SIZE + len; } static int l2cap_build_conf_req(struct sock *sk, void *data) { struct l2cap_pinfo *pi = l2cap_pi(sk); struct l2cap_conf_req *req = data; void *ptr = req->data; BT_DBG("sk %p", sk); if (pi->imtu != L2CAP_DEFAULT_MTU) l2cap_add_conf_opt(&ptr, L2CAP_CONF_MTU, 2, pi->imtu); /* FIXME: Need actual value of the flush timeout */ //if (flush_to != L2CAP_DEFAULT_FLUSH_TO) // l2cap_add_conf_opt(&ptr, L2CAP_CONF_FLUSH_TO, 2, pi->flush_to); req->dcid = cpu_to_le16(pi->dcid); req->flags = cpu_to_le16(0); return ptr - data; } static int l2cap_parse_conf_req(struct sock *sk, void *data) { struct l2cap_pinfo *pi = l2cap_pi(sk); struct l2cap_conf_rsp *rsp = data; void *ptr = rsp->data; void *req = pi->conf_req; int len = pi->conf_len; int type, hint, olen; unsigned long val; struct l2cap_conf_rfc rfc = { .mode = L2CAP_MODE_BASIC }; u16 mtu = L2CAP_DEFAULT_MTU; u16 result = L2CAP_CONF_SUCCESS; BT_DBG("sk %p", sk); while (len >= L2CAP_CONF_OPT_SIZE) { len -= l2cap_get_conf_opt(&req, &type, &olen, &val); hint = type & 0x80; type &= 0x7f; switch (type) { case L2CAP_CONF_MTU: mtu = val; break; case L2CAP_CONF_FLUSH_TO: pi->flush_to = val; break; case L2CAP_CONF_QOS: break; case L2CAP_CONF_RFC: if (olen == sizeof(rfc)) memcpy(&rfc, (void *) val, olen); break; default: if (hint) break; result = L2CAP_CONF_UNKNOWN; *((u8 *) ptr++) = type; break; } } if (result == L2CAP_CONF_SUCCESS) { /* Configure output options and let the other side know * which ones we don't like. */ if (rfc.mode == L2CAP_MODE_BASIC) { if (mtu < pi->omtu) result = L2CAP_CONF_UNACCEPT; else { pi->omtu = mtu; pi->conf_state |= L2CAP_CONF_OUTPUT_DONE; } l2cap_add_conf_opt(&ptr, L2CAP_CONF_MTU, 2, pi->omtu); } else { result = L2CAP_CONF_UNACCEPT; memset(&rfc, 0, sizeof(rfc)); rfc.mode = L2CAP_MODE_BASIC; l2cap_add_conf_opt(&ptr, L2CAP_CONF_RFC, sizeof(rfc), (unsigned long) &rfc); } } rsp->scid = cpu_to_le16(pi->dcid); rsp->result = cpu_to_le16(result); rsp->flags = cpu_to_le16(0x0000); return ptr - data; } static int l2cap_build_conf_rsp(struct sock *sk, void *data, u16 result, u16 flags) { struct l2cap_conf_rsp *rsp = data; void *ptr = rsp->data; BT_DBG("sk %p", sk); rsp->scid = cpu_to_le16(l2cap_pi(sk)->dcid); rsp->result = cpu_to_le16(result); rsp->flags = cpu_to_le16(flags); return ptr - data; } static inline int l2cap_command_rej(struct l2cap_conn *conn, struct l2cap_cmd_hdr *cmd, u8 *data) { struct l2cap_cmd_rej *rej = (struct l2cap_cmd_rej *) data; if (rej->reason != 0x0000) return 0; if ((conn->info_state & L2CAP_INFO_FEAT_MASK_REQ_SENT) && cmd->ident == conn->info_ident) { del_timer(&conn->info_timer); conn->info_state |= L2CAP_INFO_FEAT_MASK_REQ_DONE; conn->info_ident = 0; l2cap_conn_start(conn); } return 0; } static inline int l2cap_connect_req(struct l2cap_conn *conn, struct l2cap_cmd_hdr *cmd, u8 *data) { struct l2cap_chan_list *list = &conn->chan_list; struct l2cap_conn_req *req = (struct l2cap_conn_req *) data; struct l2cap_conn_rsp rsp; struct sock *sk, *parent; int result, status = L2CAP_CS_NO_INFO; u16 dcid = 0, scid = __le16_to_cpu(req->scid); __le16 psm = req->psm; BT_DBG("psm 0x%2.2x scid 0x%4.4x", psm, scid); /* Check if we have socket listening on psm */ parent = l2cap_get_sock_by_psm(BT_LISTEN, psm, conn->src); if (!parent) { result = L2CAP_CR_BAD_PSM; goto sendresp; } /* Check if the ACL is secure enough (if not SDP) */ if (psm != cpu_to_le16(0x0001) && !hci_conn_check_link_mode(conn->hcon)) { conn->disc_reason = 0x05; result = L2CAP_CR_SEC_BLOCK; goto response; } result = L2CAP_CR_NO_MEM; /* Check for backlog size */ if (sk_acceptq_is_full(parent)) { BT_DBG("backlog full %d", parent->sk_ack_backlog); goto response; } sk = l2cap_sock_alloc(sock_net(parent), NULL, BTPROTO_L2CAP, GFP_ATOMIC); if (!sk) goto response; write_lock_bh(&list->lock); /* Check if we already have channel with that dcid */ if (__l2cap_get_chan_by_dcid(list, scid)) { write_unlock_bh(&list->lock); sock_set_flag(sk, SOCK_ZAPPED); l2cap_sock_kill(sk); goto response; } hci_conn_hold(conn->hcon); l2cap_sock_init(sk, parent); bacpy(&bt_sk(sk)->src, conn->src); bacpy(&bt_sk(sk)->dst, conn->dst); l2cap_pi(sk)->psm = psm; l2cap_pi(sk)->dcid = scid; __l2cap_chan_add(conn, sk, parent); dcid = l2cap_pi(sk)->scid; l2cap_sock_set_timer(sk, sk->sk_sndtimeo); l2cap_pi(sk)->ident = cmd->ident; if (conn->info_state & L2CAP_INFO_FEAT_MASK_REQ_DONE) { if (l2cap_check_security(sk)) { if (bt_sk(sk)->defer_setup) { sk->sk_state = BT_CONNECT2; result = L2CAP_CR_PEND; status = L2CAP_CS_AUTHOR_PEND; parent->sk_data_ready(parent, 0); } else { sk->sk_state = BT_CONFIG; result = L2CAP_CR_SUCCESS; status = L2CAP_CS_NO_INFO; } } else { sk->sk_state = BT_CONNECT2; result = L2CAP_CR_PEND; status = L2CAP_CS_AUTHEN_PEND; } } else { sk->sk_state = BT_CONNECT2; result = L2CAP_CR_PEND; status = L2CAP_CS_NO_INFO; } write_unlock_bh(&list->lock); response: bh_unlock_sock(parent); sendresp: rsp.scid = cpu_to_le16(scid); rsp.dcid = cpu_to_le16(dcid); rsp.result = cpu_to_le16(result); rsp.status = cpu_to_le16(status); l2cap_send_cmd(conn, cmd->ident, L2CAP_CONN_RSP, sizeof(rsp), &rsp); if (result == L2CAP_CR_PEND && status == L2CAP_CS_NO_INFO) { struct l2cap_info_req info; info.type = cpu_to_le16(L2CAP_IT_FEAT_MASK); conn->info_state |= L2CAP_INFO_FEAT_MASK_REQ_SENT; conn->info_ident = l2cap_get_ident(conn); mod_timer(&conn->info_timer, jiffies + msecs_to_jiffies(L2CAP_INFO_TIMEOUT)); l2cap_send_cmd(conn, conn->info_ident, L2CAP_INFO_REQ, sizeof(info), &info); } return 0; } static inline int l2cap_connect_rsp(struct l2cap_conn *conn, struct l2cap_cmd_hdr *cmd, u8 *data) { struct l2cap_conn_rsp *rsp = (struct l2cap_conn_rsp *) data; u16 scid, dcid, result, status; struct sock *sk; u8 req[128]; scid = __le16_to_cpu(rsp->scid); dcid = __le16_to_cpu(rsp->dcid); result = __le16_to_cpu(rsp->result); status = __le16_to_cpu(rsp->status); BT_DBG("dcid 0x%4.4x scid 0x%4.4x result 0x%2.2x status 0x%2.2x", dcid, scid, result, status); if (scid) { if (!(sk = l2cap_get_chan_by_scid(&conn->chan_list, scid))) return 0; } else { if (!(sk = l2cap_get_chan_by_ident(&conn->chan_list, cmd->ident))) return 0; } l2cap_pi(sk)->conf_state &= ~L2CAP_CONF_CONNECT_REQ_SENT; switch (result) { case L2CAP_CR_SUCCESS: sk->sk_state = BT_CONFIG; l2cap_pi(sk)->ident = 0; l2cap_pi(sk)->dcid = dcid; l2cap_pi(sk)->conf_state |= L2CAP_CONF_REQ_SENT; l2cap_pi(sk)->conf_state &= ~L2CAP_CONF_CONNECT_PEND; l2cap_send_cmd(conn, l2cap_get_ident(conn), L2CAP_CONF_REQ, l2cap_build_conf_req(sk, req), req); break; case L2CAP_CR_PEND: l2cap_pi(sk)->conf_state |= L2CAP_CONF_CONNECT_PEND; break; default: l2cap_chan_del(sk, ECONNREFUSED); break; } bh_unlock_sock(sk); return 0; } static inline int l2cap_config_req(struct l2cap_conn *conn, struct l2cap_cmd_hdr *cmd, u16 cmd_len, u8 *data) { struct l2cap_conf_req *req = (struct l2cap_conf_req *) data; u16 dcid, flags; u8 rsp[64]; struct sock *sk; int len; dcid = __le16_to_cpu(req->dcid); flags = __le16_to_cpu(req->flags); BT_DBG("dcid 0x%4.4x flags 0x%2.2x", dcid, flags); if (!(sk = l2cap_get_chan_by_scid(&conn->chan_list, dcid))) return -ENOENT; if (sk->sk_state == BT_DISCONN) goto unlock; /* Reject if config buffer is too small. */ len = cmd_len - sizeof(*req); if (l2cap_pi(sk)->conf_len + len > sizeof(l2cap_pi(sk)->conf_req)) { l2cap_send_cmd(conn, cmd->ident, L2CAP_CONF_RSP, l2cap_build_conf_rsp(sk, rsp, L2CAP_CONF_REJECT, flags), rsp); goto unlock; } /* Store config. */ memcpy(l2cap_pi(sk)->conf_req + l2cap_pi(sk)->conf_len, req->data, len); l2cap_pi(sk)->conf_len += len; if (flags & 0x0001) { /* Incomplete config. Send empty response. */ l2cap_send_cmd(conn, cmd->ident, L2CAP_CONF_RSP, l2cap_build_conf_rsp(sk, rsp, L2CAP_CONF_SUCCESS, 0x0001), rsp); goto unlock; } /* Complete config. */ len = l2cap_parse_conf_req(sk, rsp); if (len < 0) goto unlock; l2cap_send_cmd(conn, cmd->ident, L2CAP_CONF_RSP, len, rsp); /* Reset config buffer. */ l2cap_pi(sk)->conf_len = 0; if (!(l2cap_pi(sk)->conf_state & L2CAP_CONF_OUTPUT_DONE)) goto unlock; if (l2cap_pi(sk)->conf_state & L2CAP_CONF_INPUT_DONE) { sk->sk_state = BT_CONNECTED; l2cap_chan_ready(sk); goto unlock; } if (!(l2cap_pi(sk)->conf_state & L2CAP_CONF_REQ_SENT)) { u8 buf[64]; l2cap_send_cmd(conn, l2cap_get_ident(conn), L2CAP_CONF_REQ, l2cap_build_conf_req(sk, buf), buf); } unlock: bh_unlock_sock(sk); return 0; } static inline int l2cap_config_rsp(struct l2cap_conn *conn, struct l2cap_cmd_hdr *cmd, u8 *data) { struct l2cap_conf_rsp *rsp = (struct l2cap_conf_rsp *)data; u16 scid, flags, result; struct sock *sk; scid = __le16_to_cpu(rsp->scid); flags = __le16_to_cpu(rsp->flags); result = __le16_to_cpu(rsp->result); BT_DBG("scid 0x%4.4x flags 0x%2.2x result 0x%2.2x", scid, flags, result); if (!(sk = l2cap_get_chan_by_scid(&conn->chan_list, scid))) return 0; switch (result) { case L2CAP_CONF_SUCCESS: break; case L2CAP_CONF_UNACCEPT: if (++l2cap_pi(sk)->conf_retry < L2CAP_CONF_MAX_RETRIES) { char req[128]; /* It does not make sense to adjust L2CAP parameters * that are currently defined in the spec. We simply * resend config request that we sent earlier. It is * stupid, but it helps qualification testing which * expects at least some response from us. */ l2cap_send_cmd(conn, l2cap_get_ident(conn), L2CAP_CONF_REQ, l2cap_build_conf_req(sk, req), req); goto done; } default: sk->sk_state = BT_DISCONN; sk->sk_err = ECONNRESET; l2cap_sock_set_timer(sk, HZ * 5); { struct l2cap_disconn_req req; req.dcid = cpu_to_le16(l2cap_pi(sk)->dcid); req.scid = cpu_to_le16(l2cap_pi(sk)->scid); l2cap_send_cmd(conn, l2cap_get_ident(conn), L2CAP_DISCONN_REQ, sizeof(req), &req); } goto done; } if (flags & 0x01) goto done; l2cap_pi(sk)->conf_state |= L2CAP_CONF_INPUT_DONE; if (l2cap_pi(sk)->conf_state & L2CAP_CONF_OUTPUT_DONE) { sk->sk_state = BT_CONNECTED; l2cap_chan_ready(sk); } done: bh_unlock_sock(sk); return 0; } static inline int l2cap_disconnect_req(struct l2cap_conn *conn, struct l2cap_cmd_hdr *cmd, u8 *data) { struct l2cap_disconn_req *req = (struct l2cap_disconn_req *) data; struct l2cap_disconn_rsp rsp; u16 dcid, scid; struct sock *sk; scid = __le16_to_cpu(req->scid); dcid = __le16_to_cpu(req->dcid); BT_DBG("scid 0x%4.4x dcid 0x%4.4x", scid, dcid); if (!(sk = l2cap_get_chan_by_scid(&conn->chan_list, dcid))) return 0; rsp.dcid = cpu_to_le16(l2cap_pi(sk)->scid); rsp.scid = cpu_to_le16(l2cap_pi(sk)->dcid); l2cap_send_cmd(conn, cmd->ident, L2CAP_DISCONN_RSP, sizeof(rsp), &rsp); sk->sk_shutdown = SHUTDOWN_MASK; l2cap_chan_del(sk, ECONNRESET); bh_unlock_sock(sk); l2cap_sock_kill(sk); return 0; } static inline int l2cap_disconnect_rsp(struct l2cap_conn *conn, struct l2cap_cmd_hdr *cmd, u8 *data) { struct l2cap_disconn_rsp *rsp = (struct l2cap_disconn_rsp *) data; u16 dcid, scid; struct sock *sk; scid = __le16_to_cpu(rsp->scid); dcid = __le16_to_cpu(rsp->dcid); BT_DBG("dcid 0x%4.4x scid 0x%4.4x", dcid, scid); if (!(sk = l2cap_get_chan_by_scid(&conn->chan_list, scid))) return 0; l2cap_chan_del(sk, 0); bh_unlock_sock(sk); l2cap_sock_kill(sk); return 0; } static inline int l2cap_information_req(struct l2cap_conn *conn, struct l2cap_cmd_hdr *cmd, u8 *data) { struct l2cap_info_req *req = (struct l2cap_info_req *) data; u16 type; type = __le16_to_cpu(req->type); BT_DBG("type 0x%4.4x", type); if (type == L2CAP_IT_FEAT_MASK) { u8 buf[8]; struct l2cap_info_rsp *rsp = (struct l2cap_info_rsp *) buf; rsp->type = cpu_to_le16(L2CAP_IT_FEAT_MASK); rsp->result = cpu_to_le16(L2CAP_IR_SUCCESS); put_unaligned(cpu_to_le32(l2cap_feat_mask), (__le32 *) rsp->data); l2cap_send_cmd(conn, cmd->ident, L2CAP_INFO_RSP, sizeof(buf), buf); } else if (type == L2CAP_IT_FIXED_CHAN) { u8 buf[12]; struct l2cap_info_rsp *rsp = (struct l2cap_info_rsp *) buf; rsp->type = cpu_to_le16(L2CAP_IT_FIXED_CHAN); rsp->result = cpu_to_le16(L2CAP_IR_SUCCESS); memcpy(buf + 4, l2cap_fixed_chan, 8); l2cap_send_cmd(conn, cmd->ident, L2CAP_INFO_RSP, sizeof(buf), buf); } else { struct l2cap_info_rsp rsp; rsp.type = cpu_to_le16(type); rsp.result = cpu_to_le16(L2CAP_IR_NOTSUPP); l2cap_send_cmd(conn, cmd->ident, L2CAP_INFO_RSP, sizeof(rsp), &rsp); } return 0; } static inline int l2cap_information_rsp(struct l2cap_conn *conn, struct l2cap_cmd_hdr *cmd, u8 *data) { struct l2cap_info_rsp *rsp = (struct l2cap_info_rsp *) data; u16 type, result; type = __le16_to_cpu(rsp->type); result = __le16_to_cpu(rsp->result); BT_DBG("type 0x%4.4x result 0x%2.2x", type, result); del_timer(&conn->info_timer); if (type == L2CAP_IT_FEAT_MASK) { conn->feat_mask = get_unaligned_le32(rsp->data); if (conn->feat_mask & 0x0080) { struct l2cap_info_req req; req.type = cpu_to_le16(L2CAP_IT_FIXED_CHAN); conn->info_ident = l2cap_get_ident(conn); l2cap_send_cmd(conn, conn->info_ident, L2CAP_INFO_REQ, sizeof(req), &req); } else { conn->info_state |= L2CAP_INFO_FEAT_MASK_REQ_DONE; conn->info_ident = 0; l2cap_conn_start(conn); } } else if (type == L2CAP_IT_FIXED_CHAN) { conn->info_state |= L2CAP_INFO_FEAT_MASK_REQ_DONE; conn->info_ident = 0; l2cap_conn_start(conn); } return 0; } static inline void l2cap_sig_channel(struct l2cap_conn *conn, struct sk_buff *skb) { u8 *data = skb->data; int len = skb->len; struct l2cap_cmd_hdr cmd; int err = 0; l2cap_raw_recv(conn, skb); while (len >= L2CAP_CMD_HDR_SIZE) { u16 cmd_len; memcpy(&cmd, data, L2CAP_CMD_HDR_SIZE); data += L2CAP_CMD_HDR_SIZE; len -= L2CAP_CMD_HDR_SIZE; cmd_len = le16_to_cpu(cmd.len); BT_DBG("code 0x%2.2x len %d id 0x%2.2x", cmd.code, cmd_len, cmd.ident); if (cmd_len > len || !cmd.ident) { BT_DBG("corrupted command"); break; } switch (cmd.code) { case L2CAP_COMMAND_REJ: l2cap_command_rej(conn, &cmd, data); break; case L2CAP_CONN_REQ: err = l2cap_connect_req(conn, &cmd, data); break; case L2CAP_CONN_RSP: err = l2cap_connect_rsp(conn, &cmd, data); break; case L2CAP_CONF_REQ: err = l2cap_config_req(conn, &cmd, cmd_len, data); break; case L2CAP_CONF_RSP: err = l2cap_config_rsp(conn, &cmd, data); break; case L2CAP_DISCONN_REQ: err = l2cap_disconnect_req(conn, &cmd, data); break; case L2CAP_DISCONN_RSP: err = l2cap_disconnect_rsp(conn, &cmd, data); break; case L2CAP_ECHO_REQ: l2cap_send_cmd(conn, cmd.ident, L2CAP_ECHO_RSP, cmd_len, data); break; case L2CAP_ECHO_RSP: break; case L2CAP_INFO_REQ: err = l2cap_information_req(conn, &cmd, data); break; case L2CAP_INFO_RSP: err = l2cap_information_rsp(conn, &cmd, data); break; default: BT_ERR("Unknown signaling command 0x%2.2x", cmd.code); err = -EINVAL; break; } if (err) { struct l2cap_cmd_rej rej; BT_DBG("error %d", err); /* FIXME: Map err to a valid reason */ rej.reason = cpu_to_le16(0); l2cap_send_cmd(conn, cmd.ident, L2CAP_COMMAND_REJ, sizeof(rej), &rej); } data += cmd_len; len -= cmd_len; } kfree_skb(skb); } static inline int l2cap_data_channel(struct l2cap_conn *conn, u16 cid, struct sk_buff *skb) { struct sock *sk; sk = l2cap_get_chan_by_scid(&conn->chan_list, cid); if (!sk) { BT_DBG("unknown cid 0x%4.4x", cid); goto drop; } BT_DBG("sk %p, len %d", sk, skb->len); if (sk->sk_state != BT_CONNECTED) goto drop; if (l2cap_pi(sk)->imtu < skb->len) goto drop; /* If socket recv buffers overflows we drop data here * which is *bad* because L2CAP has to be reliable. * But we don't have any other choice. L2CAP doesn't * provide flow control mechanism. */ if (!sock_queue_rcv_skb(sk, skb)) goto done; drop: kfree_skb(skb); done: if (sk) bh_unlock_sock(sk); return 0; } static inline int l2cap_conless_channel(struct l2cap_conn *conn, __le16 psm, struct sk_buff *skb) { struct sock *sk; sk = l2cap_get_sock_by_psm(0, psm, conn->src); if (!sk) goto drop; BT_DBG("sk %p, len %d", sk, skb->len); if (sk->sk_state != BT_BOUND && sk->sk_state != BT_CONNECTED) goto drop; if (l2cap_pi(sk)->imtu < skb->len) goto drop; if (!sock_queue_rcv_skb(sk, skb)) goto done; drop: kfree_skb(skb); done: if (sk) bh_unlock_sock(sk); return 0; } static void l2cap_recv_frame(struct l2cap_conn *conn, struct sk_buff *skb) { struct l2cap_hdr *lh = (void *) skb->data; u16 cid, len; __le16 psm; skb_pull(skb, L2CAP_HDR_SIZE); cid = __le16_to_cpu(lh->cid); len = __le16_to_cpu(lh->len); BT_DBG("len %d, cid 0x%4.4x", len, cid); switch (cid) { case 0x0001: l2cap_sig_channel(conn, skb); break; case 0x0002: psm = get_unaligned((__le16 *) skb->data); skb_pull(skb, 2); l2cap_conless_channel(conn, psm, skb); break; default: l2cap_data_channel(conn, cid, skb); break; } } /* ---- L2CAP interface with lower layer (HCI) ---- */ static int l2cap_connect_ind(struct hci_dev *hdev, bdaddr_t *bdaddr, u8 type) { int exact = 0, lm1 = 0, lm2 = 0; register struct sock *sk; struct hlist_node *node; if (type != ACL_LINK) return 0; BT_DBG("hdev %s, bdaddr %s", hdev->name, batostr(bdaddr)); /* Find listening sockets and check their link_mode */ read_lock(&l2cap_sk_list.lock); sk_for_each(sk, node, &l2cap_sk_list.head) { if (sk->sk_state != BT_LISTEN) continue; if (!bacmp(&bt_sk(sk)->src, &hdev->bdaddr)) { lm1 |= HCI_LM_ACCEPT; if (l2cap_pi(sk)->role_switch) lm1 |= HCI_LM_MASTER; exact++; } else if (!bacmp(&bt_sk(sk)->src, BDADDR_ANY)) { lm2 |= HCI_LM_ACCEPT; if (l2cap_pi(sk)->role_switch) lm2 |= HCI_LM_MASTER; } } read_unlock(&l2cap_sk_list.lock); return exact ? lm1 : lm2; } static int l2cap_connect_cfm(struct hci_conn *hcon, u8 status) { struct l2cap_conn *conn; BT_DBG("hcon %p bdaddr %s status %d", hcon, batostr(&hcon->dst), status); if (hcon->type != ACL_LINK) return 0; if (!status) { conn = l2cap_conn_add(hcon, status); if (conn) l2cap_conn_ready(conn); } else l2cap_conn_del(hcon, bt_err(status)); return 0; } static int l2cap_disconn_ind(struct hci_conn *hcon) { struct l2cap_conn *conn = hcon->l2cap_data; BT_DBG("hcon %p", hcon); if (hcon->type != ACL_LINK || !conn) return 0x13; return conn->disc_reason; } static int l2cap_disconn_cfm(struct hci_conn *hcon, u8 reason) { BT_DBG("hcon %p reason %d", hcon, reason); if (hcon->type != ACL_LINK) return 0; l2cap_conn_del(hcon, bt_err(reason)); return 0; } static inline void l2cap_check_encryption(struct sock *sk, u8 encrypt) { if (sk->sk_type != SOCK_SEQPACKET) return; if (encrypt == 0x00) { if (l2cap_pi(sk)->sec_level == BT_SECURITY_MEDIUM) { l2cap_sock_clear_timer(sk); l2cap_sock_set_timer(sk, HZ * 5); } else if (l2cap_pi(sk)->sec_level == BT_SECURITY_HIGH) __l2cap_sock_close(sk, ECONNREFUSED); } else { if (l2cap_pi(sk)->sec_level == BT_SECURITY_MEDIUM) l2cap_sock_clear_timer(sk); } } static int l2cap_security_cfm(struct hci_conn *hcon, u8 status, u8 encrypt) { struct l2cap_chan_list *l; struct l2cap_conn *conn = hcon->l2cap_data; struct sock *sk; if (!conn) return 0; l = &conn->chan_list; BT_DBG("conn %p", conn); read_lock(&l->lock); for (sk = l->head; sk; sk = l2cap_pi(sk)->next_c) { bh_lock_sock(sk); if (l2cap_pi(sk)->conf_state & (L2CAP_CONF_CONNECT_PEND | L2CAP_CONF_CONNECT_REQ_SENT)) { bh_unlock_sock(sk); continue; } if (!status && (sk->sk_state == BT_CONNECTED || sk->sk_state == BT_CONFIG)) { l2cap_check_encryption(sk, encrypt); bh_unlock_sock(sk); continue; } if (sk->sk_state == BT_CONNECT) { if (!status) { struct l2cap_conn_req req; req.scid = cpu_to_le16(l2cap_pi(sk)->scid); req.psm = l2cap_pi(sk)->psm; l2cap_pi(sk)->ident = l2cap_get_ident(conn); l2cap_send_cmd(conn, l2cap_pi(sk)->ident, L2CAP_CONN_REQ, sizeof(req), &req); l2cap_pi(sk)->conf_state |= L2CAP_CONF_CONNECT_REQ_SENT; } else { l2cap_sock_clear_timer(sk); l2cap_sock_set_timer(sk, HZ / 10); } } else if (sk->sk_state == BT_CONNECT2) { struct l2cap_conn_rsp rsp; __u16 result; if (!status) { sk->sk_state = BT_CONFIG; result = L2CAP_CR_SUCCESS; } else { sk->sk_state = BT_DISCONN; l2cap_sock_set_timer(sk, HZ / 10); result = L2CAP_CR_SEC_BLOCK; } rsp.scid = cpu_to_le16(l2cap_pi(sk)->dcid); rsp.dcid = cpu_to_le16(l2cap_pi(sk)->scid); rsp.result = cpu_to_le16(result); rsp.status = cpu_to_le16(L2CAP_CS_NO_INFO); l2cap_send_cmd(conn, l2cap_pi(sk)->ident, L2CAP_CONN_RSP, sizeof(rsp), &rsp); } bh_unlock_sock(sk); } read_unlock(&l->lock); return 0; } static int l2cap_recv_acldata(struct hci_conn *hcon, struct sk_buff *skb, u16 flags) { struct l2cap_conn *conn = hcon->l2cap_data; if (!conn && !(conn = l2cap_conn_add(hcon, 0))) goto drop; BT_DBG("conn %p len %d flags 0x%x", conn, skb->len, flags); if (flags & ACL_START) { struct l2cap_hdr *hdr; int len; if (conn->rx_len) { BT_ERR("Unexpected start frame (len %d)", skb->len); kfree_skb(conn->rx_skb); conn->rx_skb = NULL; conn->rx_len = 0; l2cap_conn_unreliable(conn, ECOMM); } if (skb->len < 2) { BT_ERR("Frame is too short (len %d)", skb->len); l2cap_conn_unreliable(conn, ECOMM); goto drop; } hdr = (struct l2cap_hdr *) skb->data; len = __le16_to_cpu(hdr->len) + L2CAP_HDR_SIZE; if (len == skb->len) { /* Complete frame received */ l2cap_recv_frame(conn, skb); return 0; } BT_DBG("Start: total len %d, frag len %d", len, skb->len); if (skb->len > len) { BT_ERR("Frame is too long (len %d, expected len %d)", skb->len, len); l2cap_conn_unreliable(conn, ECOMM); goto drop; } /* Allocate skb for the complete frame (with header) */ if (!(conn->rx_skb = bt_skb_alloc(len, GFP_ATOMIC))) goto drop; skb_copy_from_linear_data(skb, skb_put(conn->rx_skb, skb->len), skb->len); conn->rx_len = len - skb->len; } else { BT_DBG("Cont: frag len %d (expecting %d)", skb->len, conn->rx_len); if (!conn->rx_len) { BT_ERR("Unexpected continuation frame (len %d)", skb->len); l2cap_conn_unreliable(conn, ECOMM); goto drop; } if (skb->len > conn->rx_len) { BT_ERR("Fragment is too long (len %d, expected %d)", skb->len, conn->rx_len); kfree_skb(conn->rx_skb); conn->rx_skb = NULL; conn->rx_len = 0; l2cap_conn_unreliable(conn, ECOMM); goto drop; } skb_copy_from_linear_data(skb, skb_put(conn->rx_skb, skb->len), skb->len); conn->rx_len -= skb->len; if (!conn->rx_len) { /* Complete frame received */ l2cap_recv_frame(conn, conn->rx_skb); conn->rx_skb = NULL; } } drop: kfree_skb(skb); return 0; } static ssize_t l2cap_sysfs_show(struct class *dev, char *buf) { struct sock *sk; struct hlist_node *node; char *str = buf; read_lock_bh(&l2cap_sk_list.lock); sk_for_each(sk, node, &l2cap_sk_list.head) { struct l2cap_pinfo *pi = l2cap_pi(sk); str += sprintf(str, "%s %s %d %d 0x%4.4x 0x%4.4x %d %d %d\n", batostr(&bt_sk(sk)->src), batostr(&bt_sk(sk)->dst), sk->sk_state, btohs(pi->psm), pi->scid, pi->dcid, pi->imtu, pi->omtu, pi->sec_level); } read_unlock_bh(&l2cap_sk_list.lock); return (str - buf); } static CLASS_ATTR(l2cap, S_IRUGO, l2cap_sysfs_show, NULL); static const struct proto_ops l2cap_sock_ops = { .family = PF_BLUETOOTH, .owner = THIS_MODULE, .release = l2cap_sock_release, .bind = l2cap_sock_bind, .connect = l2cap_sock_connect, .listen = l2cap_sock_listen, .accept = l2cap_sock_accept, .getname = l2cap_sock_getname, .sendmsg = l2cap_sock_sendmsg, .recvmsg = l2cap_sock_recvmsg, .poll = bt_sock_poll, .ioctl = bt_sock_ioctl, .mmap = sock_no_mmap, .socketpair = sock_no_socketpair, .shutdown = l2cap_sock_shutdown, .setsockopt = l2cap_sock_setsockopt, .getsockopt = l2cap_sock_getsockopt }; static struct net_proto_family l2cap_sock_family_ops = { .family = PF_BLUETOOTH, .owner = THIS_MODULE, .create = l2cap_sock_create, }; static struct hci_proto l2cap_hci_proto = { .name = "L2CAP", .id = HCI_PROTO_L2CAP, .connect_ind = l2cap_connect_ind, .connect_cfm = l2cap_connect_cfm, .disconn_ind = l2cap_disconn_ind, .disconn_cfm = l2cap_disconn_cfm, .security_cfm = l2cap_security_cfm, .recv_acldata = l2cap_recv_acldata }; static int __init l2cap_init(void) { int err; err = proto_register(&l2cap_proto, 0); if (err < 0) return err; err = bt_sock_register(BTPROTO_L2CAP, &l2cap_sock_family_ops); if (err < 0) { BT_ERR("L2CAP socket registration failed"); goto error; } err = hci_register_proto(&l2cap_hci_proto); if (err < 0) { BT_ERR("L2CAP protocol registration failed"); bt_sock_unregister(BTPROTO_L2CAP); goto error; } if (class_create_file(bt_class, &class_attr_l2cap) < 0) BT_ERR("Failed to create L2CAP info file"); BT_INFO("L2CAP ver %s", VERSION); BT_INFO("L2CAP socket layer initialized"); return 0; error: proto_unregister(&l2cap_proto); return err; } static void __exit l2cap_exit(void) { class_remove_file(bt_class, &class_attr_l2cap); if (bt_sock_unregister(BTPROTO_L2CAP) < 0) BT_ERR("L2CAP socket unregistration failed"); if (hci_unregister_proto(&l2cap_hci_proto) < 0) BT_ERR("L2CAP protocol unregistration failed"); proto_unregister(&l2cap_proto); } void l2cap_load(void) { /* Dummy function to trigger automatic L2CAP module loading by * other modules that use L2CAP sockets but don't use any other * symbols from it. */ return; } EXPORT_SYMBOL(l2cap_load); module_init(l2cap_init); module_exit(l2cap_exit); MODULE_AUTHOR("Marcel Holtmann <marcel@holtmann.org>"); MODULE_DESCRIPTION("Bluetooth L2CAP ver " VERSION); MODULE_VERSION(VERSION); MODULE_LICENSE("GPL"); MODULE_ALIAS("bt-proto-0");
/* PR optimization/13985 */ /* Copied from gcc.c-torture/compile/930621-1.c */ /* { dg-do compile } */ /* { dg-options "-O3" } */ /* { dg-options "-O3 -mtune=i386" { target { { i?86-*-* x86_64-*-* } && ia32 } } } */ /* { dg-add-options stack_size } */ #if defined(STACK_SIZE) && (STACK_SIZE < 65536) # define BYTEMEM_SIZE 10000L #endif #ifndef BYTEMEM_SIZE # define BYTEMEM_SIZE 45000L #endif int bytestart[5000 + 1]; unsigned char modtext[400 + 1]; unsigned char bytemem[2][BYTEMEM_SIZE + 1]; long modlookup (int l) { signed char c; long j; long k; signed char w; long p; while (p != 0) { while ((k < bytestart[p + 2]) && (j <= l) && (modtext[j] == bytemem[w][k])) { k = k + 1; j = j + 1; } if (k == bytestart[p + 2]) if (j > l) c = 1; else c = 4; else if (j > l) c = 3; else if (modtext[j] < bytemem[w][k]) c = 0; else c = 2; } }
/** @file AreaMemoryManager.cpp @maintainer Morgan McGuire, http://graphics.cs.williams.edu @created 2009-01-20 @edited 2009-01-20 Copyright 2000-2009, Morgan McGuire. All rights reserved. */ #include "G3D/AreaMemoryManager.h" #include "G3D/System.h" namespace G3D { AreaMemoryManager::Buffer::Buffer(size_t size) : m_size(size), m_used(0) { // Allocate space for a lot of buffers. m_first = (uint8*)::malloc(m_size); } AreaMemoryManager::Buffer::~Buffer() { ::free(m_first); } void* AreaMemoryManager::Buffer::alloc(size_t s) { if (s + m_used > m_size) { return NULL; } else { void* old = m_first + m_used; m_used += s; return old; } } bool AreaMemoryManager::isThreadsafe() const { return false; } AreaMemoryManager::Ref AreaMemoryManager::create(size_t sizeHint) { return new AreaMemoryManager(sizeHint); } AreaMemoryManager::AreaMemoryManager(size_t sizeHint) : m_sizeHint(sizeHint) { debugAssert(sizeHint > 0); } AreaMemoryManager::~AreaMemoryManager() { deallocateAll(); } size_t AreaMemoryManager::bytesAllocated() const { return m_sizeHint * m_bufferArray.size(); } void* AreaMemoryManager::alloc(size_t s) { void* n = (m_bufferArray.size() > 0) ? m_bufferArray.last()->alloc(s) : NULL; if (n == NULL) { // This buffer is full m_bufferArray.append(new Buffer(max(s, m_sizeHint))); return m_bufferArray.last()->alloc(s); } else { return n; } } void AreaMemoryManager::free(void* x) { // Intentionally empty; we block deallocate } void AreaMemoryManager::deallocateAll() { m_bufferArray.deleteAll(); m_bufferArray.clear(); } }
.foo,.bar,.baz{display:block}@media screen and (min-width:99px){.bar{display:block!important;background-image:url(bar.png)}}
/* Software floating-point emulation. Definitions for IEEE Quad Precision. Copyright (C) 1997-2016 Free Software Foundation, Inc. This file is part of the GNU C Library. Contributed by Richard Henderson (rth@cygnus.com), Jakub Jelinek (jj@ultra.linux.cz), David S. Miller (davem@redhat.com) and Peter Maydell (pmaydell@chiark.greenend.org.uk). The GNU C 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. In addition to the permissions in the GNU Lesser General Public License, the Free Software Foundation gives you unlimited permission to link the compiled version of this file into combinations with other programs, and to distribute those combinations without any restriction coming from the use of this file. (The Lesser General Public License restrictions do apply in other respects; for example, they cover modification of the file, and distribution when not linked into a combine executable.) The GNU C 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 the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ #ifndef SOFT_FP_QUAD_H #define SOFT_FP_QUAD_H 1 #if _FP_W_TYPE_SIZE < 32 # error "Here's a nickel, kid. Go buy yourself a real computer." #endif #if _FP_W_TYPE_SIZE < 64 # define _FP_FRACTBITS_Q (4*_FP_W_TYPE_SIZE) # define _FP_FRACTBITS_DW_Q (8*_FP_W_TYPE_SIZE) #else # define _FP_FRACTBITS_Q (2*_FP_W_TYPE_SIZE) # define _FP_FRACTBITS_DW_Q (4*_FP_W_TYPE_SIZE) #endif #define _FP_FRACBITS_Q 113 #define _FP_FRACXBITS_Q (_FP_FRACTBITS_Q - _FP_FRACBITS_Q) #define _FP_WFRACBITS_Q (_FP_WORKBITS + _FP_FRACBITS_Q) #define _FP_WFRACXBITS_Q (_FP_FRACTBITS_Q - _FP_WFRACBITS_Q) #define _FP_EXPBITS_Q 15 #define _FP_EXPBIAS_Q 16383 #define _FP_EXPMAX_Q 32767 #define _FP_QNANBIT_Q \ ((_FP_W_TYPE) 1 << (_FP_FRACBITS_Q-2) % _FP_W_TYPE_SIZE) #define _FP_QNANBIT_SH_Q \ ((_FP_W_TYPE) 1 << (_FP_FRACBITS_Q-2+_FP_WORKBITS) % _FP_W_TYPE_SIZE) #define _FP_IMPLBIT_Q \ ((_FP_W_TYPE) 1 << (_FP_FRACBITS_Q-1) % _FP_W_TYPE_SIZE) #define _FP_IMPLBIT_SH_Q \ ((_FP_W_TYPE) 1 << (_FP_FRACBITS_Q-1+_FP_WORKBITS) % _FP_W_TYPE_SIZE) #define _FP_OVERFLOW_Q \ ((_FP_W_TYPE) 1 << (_FP_WFRACBITS_Q % _FP_W_TYPE_SIZE)) #define _FP_WFRACBITS_DW_Q (2 * _FP_WFRACBITS_Q) #define _FP_WFRACXBITS_DW_Q (_FP_FRACTBITS_DW_Q - _FP_WFRACBITS_DW_Q) #define _FP_HIGHBIT_DW_Q \ ((_FP_W_TYPE) 1 << (_FP_WFRACBITS_DW_Q - 1) % _FP_W_TYPE_SIZE) typedef float TFtype __attribute__ ((mode (TF))); #if _FP_W_TYPE_SIZE < 64 union _FP_UNION_Q { TFtype flt; struct _FP_STRUCT_LAYOUT { # if __BYTE_ORDER == __BIG_ENDIAN unsigned sign : 1; unsigned exp : _FP_EXPBITS_Q; unsigned long frac3 : _FP_FRACBITS_Q - (_FP_IMPLBIT_Q != 0)-(_FP_W_TYPE_SIZE * 3); unsigned long frac2 : _FP_W_TYPE_SIZE; unsigned long frac1 : _FP_W_TYPE_SIZE; unsigned long frac0 : _FP_W_TYPE_SIZE; # else unsigned long frac0 : _FP_W_TYPE_SIZE; unsigned long frac1 : _FP_W_TYPE_SIZE; unsigned long frac2 : _FP_W_TYPE_SIZE; unsigned long frac3 : _FP_FRACBITS_Q - (_FP_IMPLBIT_Q != 0)-(_FP_W_TYPE_SIZE * 3); unsigned exp : _FP_EXPBITS_Q; unsigned sign : 1; # endif /* not bigendian */ } bits __attribute__ ((packed)); }; # define FP_DECL_Q(X) _FP_DECL (4, X) # define FP_UNPACK_RAW_Q(X, val) _FP_UNPACK_RAW_4 (Q, X, (val)) # define FP_UNPACK_RAW_QP(X, val) _FP_UNPACK_RAW_4_P (Q, X, (val)) # define FP_PACK_RAW_Q(val, X) _FP_PACK_RAW_4 (Q, (val), X) # define FP_PACK_RAW_QP(val, X) \ do \ { \ if (!FP_INHIBIT_RESULTS) \ _FP_PACK_RAW_4_P (Q, (val), X); \ } \ while (0) # define FP_UNPACK_Q(X, val) \ do \ { \ _FP_UNPACK_RAW_4 (Q, X, (val)); \ _FP_UNPACK_CANONICAL (Q, 4, X); \ } \ while (0) # define FP_UNPACK_QP(X, val) \ do \ { \ _FP_UNPACK_RAW_4_P (Q, X, (val)); \ _FP_UNPACK_CANONICAL (Q, 4, X); \ } \ while (0) # define FP_UNPACK_SEMIRAW_Q(X, val) \ do \ { \ _FP_UNPACK_RAW_4 (Q, X, (val)); \ _FP_UNPACK_SEMIRAW (Q, 4, X); \ } \ while (0) # define FP_UNPACK_SEMIRAW_QP(X, val) \ do \ { \ _FP_UNPACK_RAW_4_P (Q, X, (val)); \ _FP_UNPACK_SEMIRAW (Q, 4, X); \ } \ while (0) # define FP_PACK_Q(val, X) \ do \ { \ _FP_PACK_CANONICAL (Q, 4, X); \ _FP_PACK_RAW_4 (Q, (val), X); \ } \ while (0) # define FP_PACK_QP(val, X) \ do \ { \ _FP_PACK_CANONICAL (Q, 4, X); \ if (!FP_INHIBIT_RESULTS) \ _FP_PACK_RAW_4_P (Q, (val), X); \ } \ while (0) # define FP_PACK_SEMIRAW_Q(val, X) \ do \ { \ _FP_PACK_SEMIRAW (Q, 4, X); \ _FP_PACK_RAW_4 (Q, (val), X); \ } \ while (0) # define FP_PACK_SEMIRAW_QP(val, X) \ do \ { \ _FP_PACK_SEMIRAW (Q, 4, X); \ if (!FP_INHIBIT_RESULTS) \ _FP_PACK_RAW_4_P (Q, (val), X); \ } \ while (0) # define FP_ISSIGNAN_Q(X) _FP_ISSIGNAN (Q, 4, X) # define FP_NEG_Q(R, X) _FP_NEG (Q, 4, R, X) # define FP_ADD_Q(R, X, Y) _FP_ADD (Q, 4, R, X, Y) # define FP_SUB_Q(R, X, Y) _FP_SUB (Q, 4, R, X, Y) # define FP_MUL_Q(R, X, Y) _FP_MUL (Q, 4, R, X, Y) # define FP_DIV_Q(R, X, Y) _FP_DIV (Q, 4, R, X, Y) # define FP_SQRT_Q(R, X) _FP_SQRT (Q, 4, R, X) # define _FP_SQRT_MEAT_Q(R, S, T, X, Q) _FP_SQRT_MEAT_4 (R, S, T, X, (Q)) # define FP_FMA_Q(R, X, Y, Z) _FP_FMA (Q, 4, 8, R, X, Y, Z) # define FP_CMP_Q(r, X, Y, un, ex) _FP_CMP (Q, 4, (r), X, Y, (un), (ex)) # define FP_CMP_EQ_Q(r, X, Y, ex) _FP_CMP_EQ (Q, 4, (r), X, Y, (ex)) # define FP_CMP_UNORD_Q(r, X, Y, ex) _FP_CMP_UNORD (Q, 4, (r), X, Y, (ex)) # define FP_TO_INT_Q(r, X, rsz, rsg) _FP_TO_INT (Q, 4, (r), X, (rsz), (rsg)) # define FP_TO_INT_ROUND_Q(r, X, rsz, rsg) \ _FP_TO_INT_ROUND (Q, 4, (r), X, (rsz), (rsg)) # define FP_FROM_INT_Q(X, r, rs, rt) _FP_FROM_INT (Q, 4, X, (r), (rs), rt) # define _FP_FRAC_HIGH_Q(X) _FP_FRAC_HIGH_4 (X) # define _FP_FRAC_HIGH_RAW_Q(X) _FP_FRAC_HIGH_4 (X) # define _FP_FRAC_HIGH_DW_Q(X) _FP_FRAC_HIGH_8 (X) #else /* not _FP_W_TYPE_SIZE < 64 */ union _FP_UNION_Q { TFtype flt /* __attribute__ ((mode (TF))) */ ; struct _FP_STRUCT_LAYOUT { _FP_W_TYPE a, b; } longs; struct _FP_STRUCT_LAYOUT { # if __BYTE_ORDER == __BIG_ENDIAN unsigned sign : 1; unsigned exp : _FP_EXPBITS_Q; _FP_W_TYPE frac1 : _FP_FRACBITS_Q - (_FP_IMPLBIT_Q != 0) - _FP_W_TYPE_SIZE; _FP_W_TYPE frac0 : _FP_W_TYPE_SIZE; # else _FP_W_TYPE frac0 : _FP_W_TYPE_SIZE; _FP_W_TYPE frac1 : _FP_FRACBITS_Q - (_FP_IMPLBIT_Q != 0) - _FP_W_TYPE_SIZE; unsigned exp : _FP_EXPBITS_Q; unsigned sign : 1; # endif } bits; }; # define FP_DECL_Q(X) _FP_DECL (2, X) # define FP_UNPACK_RAW_Q(X, val) _FP_UNPACK_RAW_2 (Q, X, (val)) # define FP_UNPACK_RAW_QP(X, val) _FP_UNPACK_RAW_2_P (Q, X, (val)) # define FP_PACK_RAW_Q(val, X) _FP_PACK_RAW_2 (Q, (val), X) # define FP_PACK_RAW_QP(val, X) \ do \ { \ if (!FP_INHIBIT_RESULTS) \ _FP_PACK_RAW_2_P (Q, (val), X); \ } \ while (0) # define FP_UNPACK_Q(X, val) \ do \ { \ _FP_UNPACK_RAW_2 (Q, X, (val)); \ _FP_UNPACK_CANONICAL (Q, 2, X); \ } \ while (0) # define FP_UNPACK_QP(X, val) \ do \ { \ _FP_UNPACK_RAW_2_P (Q, X, (val)); \ _FP_UNPACK_CANONICAL (Q, 2, X); \ } \ while (0) # define FP_UNPACK_SEMIRAW_Q(X, val) \ do \ { \ _FP_UNPACK_RAW_2 (Q, X, (val)); \ _FP_UNPACK_SEMIRAW (Q, 2, X); \ } \ while (0) # define FP_UNPACK_SEMIRAW_QP(X, val) \ do \ { \ _FP_UNPACK_RAW_2_P (Q, X, (val)); \ _FP_UNPACK_SEMIRAW (Q, 2, X); \ } \ while (0) # define FP_PACK_Q(val, X) \ do \ { \ _FP_PACK_CANONICAL (Q, 2, X); \ _FP_PACK_RAW_2 (Q, (val), X); \ } \ while (0) # define FP_PACK_QP(val, X) \ do \ { \ _FP_PACK_CANONICAL (Q, 2, X); \ if (!FP_INHIBIT_RESULTS) \ _FP_PACK_RAW_2_P (Q, (val), X); \ } \ while (0) # define FP_PACK_SEMIRAW_Q(val, X) \ do \ { \ _FP_PACK_SEMIRAW (Q, 2, X); \ _FP_PACK_RAW_2 (Q, (val), X); \ } \ while (0) # define FP_PACK_SEMIRAW_QP(val, X) \ do \ { \ _FP_PACK_SEMIRAW (Q, 2, X); \ if (!FP_INHIBIT_RESULTS) \ _FP_PACK_RAW_2_P (Q, (val), X); \ } \ while (0) # define FP_ISSIGNAN_Q(X) _FP_ISSIGNAN (Q, 2, X) # define FP_NEG_Q(R, X) _FP_NEG (Q, 2, R, X) # define FP_ADD_Q(R, X, Y) _FP_ADD (Q, 2, R, X, Y) # define FP_SUB_Q(R, X, Y) _FP_SUB (Q, 2, R, X, Y) # define FP_MUL_Q(R, X, Y) _FP_MUL (Q, 2, R, X, Y) # define FP_DIV_Q(R, X, Y) _FP_DIV (Q, 2, R, X, Y) # define FP_SQRT_Q(R, X) _FP_SQRT (Q, 2, R, X) # define _FP_SQRT_MEAT_Q(R, S, T, X, Q) _FP_SQRT_MEAT_2 (R, S, T, X, (Q)) # define FP_FMA_Q(R, X, Y, Z) _FP_FMA (Q, 2, 4, R, X, Y, Z) # define FP_CMP_Q(r, X, Y, un, ex) _FP_CMP (Q, 2, (r), X, Y, (un), (ex)) # define FP_CMP_EQ_Q(r, X, Y, ex) _FP_CMP_EQ (Q, 2, (r), X, Y, (ex)) # define FP_CMP_UNORD_Q(r, X, Y, ex) _FP_CMP_UNORD (Q, 2, (r), X, Y, (ex)) # define FP_TO_INT_Q(r, X, rsz, rsg) _FP_TO_INT (Q, 2, (r), X, (rsz), (rsg)) # define FP_TO_INT_ROUND_Q(r, X, rsz, rsg) \ _FP_TO_INT_ROUND (Q, 2, (r), X, (rsz), (rsg)) # define FP_FROM_INT_Q(X, r, rs, rt) _FP_FROM_INT (Q, 2, X, (r), (rs), rt) # define _FP_FRAC_HIGH_Q(X) _FP_FRAC_HIGH_2 (X) # define _FP_FRAC_HIGH_RAW_Q(X) _FP_FRAC_HIGH_2 (X) # define _FP_FRAC_HIGH_DW_Q(X) _FP_FRAC_HIGH_4 (X) #endif /* not _FP_W_TYPE_SIZE < 64 */ #endif /* !SOFT_FP_QUAD_H */
/* Analog Devices 1889 audio driver * * This is a driver for the AD1889 PCI audio chipset found * on the HP PA-RISC [BCJ]-xxx0 workstations. * * Copyright (C) 2004-2005, Kyle McMartin <kyle@parisc-linux.org> * Copyright (C) 2005, Thibaut Varene <varenet@parisc-linux.org> * Based on the OSS AD1889 driver by Randolph Chung <tausq@debian.org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License, version 2, as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * TODO: * Do we need to take care of CCS register? * Maybe we could use finer grained locking (separate locks for pb/cap)? * Wishlist: * Control Interface (mixer) support * Better AC97 support (VSR...)? * PM support * MIDI support * Game Port support * SG DMA support (this will need *alot* of work) */ #include <linux/init.h> #include <linux/pci.h> #include <linux/dma-mapping.h> #include <linux/slab.h> #include <linux/interrupt.h> #include <linux/compiler.h> #include <linux/delay.h> #include <sound/core.h> #include <sound/pcm.h> #include <sound/initval.h> #include <sound/ac97_codec.h> #include <asm/io.h> #include "ad1889.h" #include "ac97/ac97_id.h" #define AD1889_DRVVER "Version: 1.7" MODULE_AUTHOR("Kyle McMartin <kyle@parisc-linux.org>, Thibaut Varene <t-bone@parisc-linux.org>"); MODULE_DESCRIPTION("Analog Devices AD1889 ALSA sound driver"); MODULE_LICENSE("GPL"); MODULE_SUPPORTED_DEVICE("{{Analog Devices,AD1889}}"); static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX; module_param_array(index, int, NULL, 0444); MODULE_PARM_DESC(index, "Index value for the AD1889 soundcard."); static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR; module_param_array(id, charp, NULL, 0444); MODULE_PARM_DESC(id, "ID string for the AD1889 soundcard."); static int enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_PNP; module_param_array(enable, bool, NULL, 0444); MODULE_PARM_DESC(enable, "Enable AD1889 soundcard."); static char *ac97_quirk[SNDRV_CARDS]; module_param_array(ac97_quirk, charp, NULL, 0444); MODULE_PARM_DESC(ac97_quirk, "AC'97 workaround for strange hardware."); #define DEVNAME "ad1889" #define PFX DEVNAME ": " /* let's use the global sound debug interfaces */ #define ad1889_debug(fmt, arg...) snd_printd(KERN_DEBUG fmt, ## arg) /* keep track of some hw registers */ struct ad1889_register_state { u16 reg; /* reg setup */ u32 addr; /* dma base address */ unsigned long size; /* DMA buffer size */ }; struct snd_ad1889 { struct snd_card *card; struct pci_dev *pci; int irq; unsigned long bar; void __iomem *iobase; struct snd_ac97 *ac97; struct snd_ac97_bus *ac97_bus; struct snd_pcm *pcm; struct snd_info_entry *proc; struct snd_pcm_substream *psubs; struct snd_pcm_substream *csubs; /* playback register state */ struct ad1889_register_state wave; struct ad1889_register_state ramc; spinlock_t lock; }; static inline u16 ad1889_readw(struct snd_ad1889 *chip, unsigned reg) { return readw(chip->iobase + reg); } static inline void ad1889_writew(struct snd_ad1889 *chip, unsigned reg, u16 val) { writew(val, chip->iobase + reg); } static inline u32 ad1889_readl(struct snd_ad1889 *chip, unsigned reg) { return readl(chip->iobase + reg); } static inline void ad1889_writel(struct snd_ad1889 *chip, unsigned reg, u32 val) { writel(val, chip->iobase + reg); } static inline void ad1889_unmute(struct snd_ad1889 *chip) { u16 st; st = ad1889_readw(chip, AD_DS_WADA) & ~(AD_DS_WADA_RWAM | AD_DS_WADA_LWAM); ad1889_writew(chip, AD_DS_WADA, st); ad1889_readw(chip, AD_DS_WADA); } static inline void ad1889_mute(struct snd_ad1889 *chip) { u16 st; st = ad1889_readw(chip, AD_DS_WADA) | AD_DS_WADA_RWAM | AD_DS_WADA_LWAM; ad1889_writew(chip, AD_DS_WADA, st); ad1889_readw(chip, AD_DS_WADA); } static inline void ad1889_load_adc_buffer_address(struct snd_ad1889 *chip, u32 address) { ad1889_writel(chip, AD_DMA_ADCBA, address); ad1889_writel(chip, AD_DMA_ADCCA, address); } static inline void ad1889_load_adc_buffer_count(struct snd_ad1889 *chip, u32 count) { ad1889_writel(chip, AD_DMA_ADCBC, count); ad1889_writel(chip, AD_DMA_ADCCC, count); } static inline void ad1889_load_adc_interrupt_count(struct snd_ad1889 *chip, u32 count) { ad1889_writel(chip, AD_DMA_ADCIB, count); ad1889_writel(chip, AD_DMA_ADCIC, count); } static inline void ad1889_load_wave_buffer_address(struct snd_ad1889 *chip, u32 address) { ad1889_writel(chip, AD_DMA_WAVBA, address); ad1889_writel(chip, AD_DMA_WAVCA, address); } static inline void ad1889_load_wave_buffer_count(struct snd_ad1889 *chip, u32 count) { ad1889_writel(chip, AD_DMA_WAVBC, count); ad1889_writel(chip, AD_DMA_WAVCC, count); } static inline void ad1889_load_wave_interrupt_count(struct snd_ad1889 *chip, u32 count) { ad1889_writel(chip, AD_DMA_WAVIB, count); ad1889_writel(chip, AD_DMA_WAVIC, count); } static void ad1889_channel_reset(struct snd_ad1889 *chip, unsigned int channel) { u16 reg; if (channel & AD_CHAN_WAV) { /* Disable wave channel */ reg = ad1889_readw(chip, AD_DS_WSMC) & ~AD_DS_WSMC_WAEN; ad1889_writew(chip, AD_DS_WSMC, reg); chip->wave.reg = reg; /* disable IRQs */ reg = ad1889_readw(chip, AD_DMA_WAV); reg &= AD_DMA_IM_DIS; reg &= ~AD_DMA_LOOP; ad1889_writew(chip, AD_DMA_WAV, reg); /* clear IRQ and address counters and pointers */ ad1889_load_wave_buffer_address(chip, 0x0); ad1889_load_wave_buffer_count(chip, 0x0); ad1889_load_wave_interrupt_count(chip, 0x0); /* flush */ ad1889_readw(chip, AD_DMA_WAV); } if (channel & AD_CHAN_ADC) { /* Disable ADC channel */ reg = ad1889_readw(chip, AD_DS_RAMC) & ~AD_DS_RAMC_ADEN; ad1889_writew(chip, AD_DS_RAMC, reg); chip->ramc.reg = reg; reg = ad1889_readw(chip, AD_DMA_ADC); reg &= AD_DMA_IM_DIS; reg &= ~AD_DMA_LOOP; ad1889_writew(chip, AD_DMA_ADC, reg); ad1889_load_adc_buffer_address(chip, 0x0); ad1889_load_adc_buffer_count(chip, 0x0); ad1889_load_adc_interrupt_count(chip, 0x0); /* flush */ ad1889_readw(chip, AD_DMA_ADC); } } static u16 snd_ad1889_ac97_read(struct snd_ac97 *ac97, unsigned short reg) { struct snd_ad1889 *chip = ac97->private_data; return ad1889_readw(chip, AD_AC97_BASE + reg); } static void snd_ad1889_ac97_write(struct snd_ac97 *ac97, unsigned short reg, unsigned short val) { struct snd_ad1889 *chip = ac97->private_data; ad1889_writew(chip, AD_AC97_BASE + reg, val); } static int snd_ad1889_ac97_ready(struct snd_ad1889 *chip) { int retry = 400; /* average needs 352 msec */ while (!(ad1889_readw(chip, AD_AC97_ACIC) & AD_AC97_ACIC_ACRDY) && --retry) mdelay(1); if (!retry) { snd_printk(KERN_ERR PFX "[%s] Link is not ready.\n", __func__); return -EIO; } ad1889_debug("[%s] ready after %d ms\n", __func__, 400 - retry); return 0; } static int snd_ad1889_hw_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *hw_params) { return snd_pcm_lib_malloc_pages(substream, params_buffer_bytes(hw_params)); } static int snd_ad1889_hw_free(struct snd_pcm_substream *substream) { return snd_pcm_lib_free_pages(substream); } static struct snd_pcm_hardware snd_ad1889_playback_hw = { .info = SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_INTERLEAVED | SNDRV_PCM_INFO_MMAP_VALID | SNDRV_PCM_INFO_BLOCK_TRANSFER, .formats = SNDRV_PCM_FMTBIT_S16_LE, .rates = SNDRV_PCM_RATE_CONTINUOUS | SNDRV_PCM_RATE_8000_48000, .rate_min = 8000, /* docs say 7000, but we're lazy */ .rate_max = 48000, .channels_min = 1, .channels_max = 2, .buffer_bytes_max = BUFFER_BYTES_MAX, .period_bytes_min = PERIOD_BYTES_MIN, .period_bytes_max = PERIOD_BYTES_MAX, .periods_min = PERIODS_MIN, .periods_max = PERIODS_MAX, /*.fifo_size = 0,*/ }; static struct snd_pcm_hardware snd_ad1889_capture_hw = { .info = SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_INTERLEAVED | SNDRV_PCM_INFO_MMAP_VALID | SNDRV_PCM_INFO_BLOCK_TRANSFER, .formats = SNDRV_PCM_FMTBIT_S16_LE, .rates = SNDRV_PCM_RATE_48000, .rate_min = 48000, /* docs say we could to VSR, but we're lazy */ .rate_max = 48000, .channels_min = 1, .channels_max = 2, .buffer_bytes_max = BUFFER_BYTES_MAX, .period_bytes_min = PERIOD_BYTES_MIN, .period_bytes_max = PERIOD_BYTES_MAX, .periods_min = PERIODS_MIN, .periods_max = PERIODS_MAX, /*.fifo_size = 0,*/ }; static int snd_ad1889_playback_open(struct snd_pcm_substream *ss) { struct snd_ad1889 *chip = snd_pcm_substream_chip(ss); struct snd_pcm_runtime *rt = ss->runtime; chip->psubs = ss; rt->hw = snd_ad1889_playback_hw; return 0; } static int snd_ad1889_capture_open(struct snd_pcm_substream *ss) { struct snd_ad1889 *chip = snd_pcm_substream_chip(ss); struct snd_pcm_runtime *rt = ss->runtime; chip->csubs = ss; rt->hw = snd_ad1889_capture_hw; return 0; } static int snd_ad1889_playback_close(struct snd_pcm_substream *ss) { struct snd_ad1889 *chip = snd_pcm_substream_chip(ss); chip->psubs = NULL; return 0; } static int snd_ad1889_capture_close(struct snd_pcm_substream *ss) { struct snd_ad1889 *chip = snd_pcm_substream_chip(ss); chip->csubs = NULL; return 0; } static int snd_ad1889_playback_prepare(struct snd_pcm_substream *ss) { struct snd_ad1889 *chip = snd_pcm_substream_chip(ss); struct snd_pcm_runtime *rt = ss->runtime; unsigned int size = snd_pcm_lib_buffer_bytes(ss); unsigned int count = snd_pcm_lib_period_bytes(ss); u16 reg; ad1889_channel_reset(chip, AD_CHAN_WAV); reg = ad1889_readw(chip, AD_DS_WSMC); /* Mask out 16-bit / Stereo */ reg &= ~(AD_DS_WSMC_WA16 | AD_DS_WSMC_WAST); if (snd_pcm_format_width(rt->format) == 16) reg |= AD_DS_WSMC_WA16; if (rt->channels > 1) reg |= AD_DS_WSMC_WAST; /* let's make sure we don't clobber ourselves */ spin_lock_irq(&chip->lock); chip->wave.size = size; chip->wave.reg = reg; chip->wave.addr = rt->dma_addr; ad1889_writew(chip, AD_DS_WSMC, chip->wave.reg); /* Set sample rates on the codec */ ad1889_writew(chip, AD_DS_WAS, rt->rate); /* Set up DMA */ ad1889_load_wave_buffer_address(chip, chip->wave.addr); ad1889_load_wave_buffer_count(chip, size); ad1889_load_wave_interrupt_count(chip, count); /* writes flush */ ad1889_readw(chip, AD_DS_WSMC); spin_unlock_irq(&chip->lock); ad1889_debug("prepare playback: addr = 0x%x, count = %u, " "size = %u, reg = 0x%x, rate = %u\n", chip->wave.addr, count, size, reg, rt->rate); return 0; } static int snd_ad1889_capture_prepare(struct snd_pcm_substream *ss) { struct snd_ad1889 *chip = snd_pcm_substream_chip(ss); struct snd_pcm_runtime *rt = ss->runtime; unsigned int size = snd_pcm_lib_buffer_bytes(ss); unsigned int count = snd_pcm_lib_period_bytes(ss); u16 reg; ad1889_channel_reset(chip, AD_CHAN_ADC); reg = ad1889_readw(chip, AD_DS_RAMC); /* Mask out 16-bit / Stereo */ reg &= ~(AD_DS_RAMC_AD16 | AD_DS_RAMC_ADST); if (snd_pcm_format_width(rt->format) == 16) reg |= AD_DS_RAMC_AD16; if (rt->channels > 1) reg |= AD_DS_RAMC_ADST; /* let's make sure we don't clobber ourselves */ spin_lock_irq(&chip->lock); chip->ramc.size = size; chip->ramc.reg = reg; chip->ramc.addr = rt->dma_addr; ad1889_writew(chip, AD_DS_RAMC, chip->ramc.reg); /* Set up DMA */ ad1889_load_adc_buffer_address(chip, chip->ramc.addr); ad1889_load_adc_buffer_count(chip, size); ad1889_load_adc_interrupt_count(chip, count); /* writes flush */ ad1889_readw(chip, AD_DS_RAMC); spin_unlock_irq(&chip->lock); ad1889_debug("prepare capture: addr = 0x%x, count = %u, " "size = %u, reg = 0x%x, rate = %u\n", chip->ramc.addr, count, size, reg, rt->rate); return 0; } /* this is called in atomic context with IRQ disabled. Must be as fast as possible and not sleep. DMA should be *triggered* by this call. The WSMC "WAEN" bit triggers DMA Wave On/Off */ static int snd_ad1889_playback_trigger(struct snd_pcm_substream *ss, int cmd) { u16 wsmc; struct snd_ad1889 *chip = snd_pcm_substream_chip(ss); wsmc = ad1889_readw(chip, AD_DS_WSMC); switch (cmd) { case SNDRV_PCM_TRIGGER_START: /* enable DMA loop & interrupts */ ad1889_writew(chip, AD_DMA_WAV, AD_DMA_LOOP | AD_DMA_IM_CNT); wsmc |= AD_DS_WSMC_WAEN; /* 1 to clear CHSS bit */ ad1889_writel(chip, AD_DMA_CHSS, AD_DMA_CHSS_WAVS); ad1889_unmute(chip); break; case SNDRV_PCM_TRIGGER_STOP: ad1889_mute(chip); wsmc &= ~AD_DS_WSMC_WAEN; break; default: snd_BUG(); return -EINVAL; } chip->wave.reg = wsmc; ad1889_writew(chip, AD_DS_WSMC, wsmc); ad1889_readw(chip, AD_DS_WSMC); /* flush */ /* reset the chip when STOP - will disable IRQs */ if (cmd == SNDRV_PCM_TRIGGER_STOP) ad1889_channel_reset(chip, AD_CHAN_WAV); return 0; } /* this is called in atomic context with IRQ disabled. Must be as fast as possible and not sleep. DMA should be *triggered* by this call. The RAMC "ADEN" bit triggers DMA ADC On/Off */ static int snd_ad1889_capture_trigger(struct snd_pcm_substream *ss, int cmd) { u16 ramc; struct snd_ad1889 *chip = snd_pcm_substream_chip(ss); ramc = ad1889_readw(chip, AD_DS_RAMC); switch (cmd) { case SNDRV_PCM_TRIGGER_START: /* enable DMA loop & interrupts */ ad1889_writew(chip, AD_DMA_ADC, AD_DMA_LOOP | AD_DMA_IM_CNT); ramc |= AD_DS_RAMC_ADEN; /* 1 to clear CHSS bit */ ad1889_writel(chip, AD_DMA_CHSS, AD_DMA_CHSS_ADCS); break; case SNDRV_PCM_TRIGGER_STOP: ramc &= ~AD_DS_RAMC_ADEN; break; default: return -EINVAL; } chip->ramc.reg = ramc; ad1889_writew(chip, AD_DS_RAMC, ramc); ad1889_readw(chip, AD_DS_RAMC); /* flush */ /* reset the chip when STOP - will disable IRQs */ if (cmd == SNDRV_PCM_TRIGGER_STOP) ad1889_channel_reset(chip, AD_CHAN_ADC); return 0; } /* Called in atomic context with IRQ disabled */ static snd_pcm_uframes_t snd_ad1889_playback_pointer(struct snd_pcm_substream *ss) { size_t ptr = 0; struct snd_ad1889 *chip = snd_pcm_substream_chip(ss); if (unlikely(!(chip->wave.reg & AD_DS_WSMC_WAEN))) return 0; ptr = ad1889_readl(chip, AD_DMA_WAVCA); ptr -= chip->wave.addr; snd_assert((ptr >= 0) && (ptr < chip->wave.size), return 0); return bytes_to_frames(ss->runtime, ptr); } /* Called in atomic context with IRQ disabled */ static snd_pcm_uframes_t snd_ad1889_capture_pointer(struct snd_pcm_substream *ss) { size_t ptr = 0; struct snd_ad1889 *chip = snd_pcm_substream_chip(ss); if (unlikely(!(chip->ramc.reg & AD_DS_RAMC_ADEN))) return 0; ptr = ad1889_readl(chip, AD_DMA_ADCCA); ptr -= chip->ramc.addr; snd_assert((ptr >= 0) && (ptr < chip->ramc.size), return 0); return bytes_to_frames(ss->runtime, ptr); } static struct snd_pcm_ops snd_ad1889_playback_ops = { .open = snd_ad1889_playback_open, .close = snd_ad1889_playback_close, .ioctl = snd_pcm_lib_ioctl, .hw_params = snd_ad1889_hw_params, .hw_free = snd_ad1889_hw_free, .prepare = snd_ad1889_playback_prepare, .trigger = snd_ad1889_playback_trigger, .pointer = snd_ad1889_playback_pointer, }; static struct snd_pcm_ops snd_ad1889_capture_ops = { .open = snd_ad1889_capture_open, .close = snd_ad1889_capture_close, .ioctl = snd_pcm_lib_ioctl, .hw_params = snd_ad1889_hw_params, .hw_free = snd_ad1889_hw_free, .prepare = snd_ad1889_capture_prepare, .trigger = snd_ad1889_capture_trigger, .pointer = snd_ad1889_capture_pointer, }; static irqreturn_t snd_ad1889_interrupt(int irq, void *dev_id) { unsigned long st; struct snd_ad1889 *chip = dev_id; st = ad1889_readl(chip, AD_DMA_DISR); /* clear ISR */ ad1889_writel(chip, AD_DMA_DISR, st); st &= AD_INTR_MASK; if (unlikely(!st)) return IRQ_NONE; if (st & (AD_DMA_DISR_PMAI|AD_DMA_DISR_PTAI)) ad1889_debug("Unexpected master or target abort interrupt!\n"); if ((st & AD_DMA_DISR_WAVI) && chip->psubs) snd_pcm_period_elapsed(chip->psubs); if ((st & AD_DMA_DISR_ADCI) && chip->csubs) snd_pcm_period_elapsed(chip->csubs); return IRQ_HANDLED; } static int __devinit snd_ad1889_pcm_init(struct snd_ad1889 *chip, int device, struct snd_pcm **rpcm) { int err; struct snd_pcm *pcm; if (rpcm) *rpcm = NULL; err = snd_pcm_new(chip->card, chip->card->driver, device, 1, 1, &pcm); if (err < 0) return err; snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &snd_ad1889_playback_ops); snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE, &snd_ad1889_capture_ops); pcm->private_data = chip; pcm->info_flags = 0; strcpy(pcm->name, chip->card->shortname); chip->pcm = pcm; chip->psubs = NULL; chip->csubs = NULL; err = snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV, snd_dma_pci_data(chip->pci), BUFFER_BYTES_MAX / 2, BUFFER_BYTES_MAX); if (err < 0) { snd_printk(KERN_ERR PFX "buffer allocation error: %d\n", err); return err; } if (rpcm) *rpcm = pcm; return 0; } static void snd_ad1889_proc_read(struct snd_info_entry *entry, struct snd_info_buffer *buffer) { struct snd_ad1889 *chip = entry->private_data; u16 reg; int tmp; reg = ad1889_readw(chip, AD_DS_WSMC); snd_iprintf(buffer, "Wave output: %s\n", (reg & AD_DS_WSMC_WAEN) ? "enabled" : "disabled"); snd_iprintf(buffer, "Wave Channels: %s\n", (reg & AD_DS_WSMC_WAST) ? "stereo" : "mono"); snd_iprintf(buffer, "Wave Quality: %d-bit linear\n", (reg & AD_DS_WSMC_WA16) ? 16 : 8); /* WARQ is at offset 12 */ tmp = (reg & AD_DS_WSMC_WARQ) ? (((reg & AD_DS_WSMC_WARQ >> 12) & 0x01) ? 12 : 18) : 4; tmp /= (reg & AD_DS_WSMC_WAST) ? 2 : 1; snd_iprintf(buffer, "Wave FIFO: %d %s words\n\n", tmp, (reg & AD_DS_WSMC_WAST) ? "stereo" : "mono"); snd_iprintf(buffer, "Synthesis output: %s\n", reg & AD_DS_WSMC_SYEN ? "enabled" : "disabled"); /* SYRQ is at offset 4 */ tmp = (reg & AD_DS_WSMC_SYRQ) ? (((reg & AD_DS_WSMC_SYRQ >> 4) & 0x01) ? 12 : 18) : 4; tmp /= (reg & AD_DS_WSMC_WAST) ? 2 : 1; snd_iprintf(buffer, "Synthesis FIFO: %d %s words\n\n", tmp, (reg & AD_DS_WSMC_WAST) ? "stereo" : "mono"); reg = ad1889_readw(chip, AD_DS_RAMC); snd_iprintf(buffer, "ADC input: %s\n", (reg & AD_DS_RAMC_ADEN) ? "enabled" : "disabled"); snd_iprintf(buffer, "ADC Channels: %s\n", (reg & AD_DS_RAMC_ADST) ? "stereo" : "mono"); snd_iprintf(buffer, "ADC Quality: %d-bit linear\n", (reg & AD_DS_RAMC_AD16) ? 16 : 8); /* ACRQ is at offset 4 */ tmp = (reg & AD_DS_RAMC_ACRQ) ? (((reg & AD_DS_RAMC_ACRQ >> 4) & 0x01) ? 12 : 18) : 4; tmp /= (reg & AD_DS_RAMC_ADST) ? 2 : 1; snd_iprintf(buffer, "ADC FIFO: %d %s words\n\n", tmp, (reg & AD_DS_RAMC_ADST) ? "stereo" : "mono"); snd_iprintf(buffer, "Resampler input: %s\n", reg & AD_DS_RAMC_REEN ? "enabled" : "disabled"); /* RERQ is at offset 12 */ tmp = (reg & AD_DS_RAMC_RERQ) ? (((reg & AD_DS_RAMC_RERQ >> 12) & 0x01) ? 12 : 18) : 4; tmp /= (reg & AD_DS_RAMC_ADST) ? 2 : 1; snd_iprintf(buffer, "Resampler FIFO: %d %s words\n\n", tmp, (reg & AD_DS_WSMC_WAST) ? "stereo" : "mono"); /* doc says LSB represents -1.5dB, but the max value (-94.5dB) suggests that LSB is -3dB, which is more coherent with the logarithmic nature of the dB scale */ reg = ad1889_readw(chip, AD_DS_WADA); snd_iprintf(buffer, "Left: %s, -%d dB\n", (reg & AD_DS_WADA_LWAM) ? "mute" : "unmute", ((reg & AD_DS_WADA_LWAA) >> 8) * 3); reg = ad1889_readw(chip, AD_DS_WADA); snd_iprintf(buffer, "Right: %s, -%d dB\n", (reg & AD_DS_WADA_RWAM) ? "mute" : "unmute", ((reg & AD_DS_WADA_RWAA) >> 8) * 3); reg = ad1889_readw(chip, AD_DS_WAS); snd_iprintf(buffer, "Wave samplerate: %u Hz\n", reg); reg = ad1889_readw(chip, AD_DS_RES); snd_iprintf(buffer, "Resampler samplerate: %u Hz\n", reg); } static void __devinit snd_ad1889_proc_init(struct snd_ad1889 *chip) { struct snd_info_entry *entry; if (!snd_card_proc_new(chip->card, chip->card->driver, &entry)) snd_info_set_text_ops(entry, chip, snd_ad1889_proc_read); } static struct ac97_quirk ac97_quirks[] = { { .subvendor = 0x11d4, /* AD */ .subdevice = 0x1889, /* AD1889 */ .codec_id = AC97_ID_AD1819, .name = "AD1889", .type = AC97_TUNE_HP_ONLY }, { } /* terminator */ }; static void __devinit snd_ad1889_ac97_xinit(struct snd_ad1889 *chip) { u16 reg; reg = ad1889_readw(chip, AD_AC97_ACIC); reg |= AD_AC97_ACIC_ACRD; /* Reset Disable */ ad1889_writew(chip, AD_AC97_ACIC, reg); ad1889_readw(chip, AD_AC97_ACIC); /* flush posted write */ udelay(10); /* Interface Enable */ reg |= AD_AC97_ACIC_ACIE; ad1889_writew(chip, AD_AC97_ACIC, reg); snd_ad1889_ac97_ready(chip); /* Audio Stream Output | Variable Sample Rate Mode */ reg = ad1889_readw(chip, AD_AC97_ACIC); reg |= AD_AC97_ACIC_ASOE | AD_AC97_ACIC_VSRM; ad1889_writew(chip, AD_AC97_ACIC, reg); ad1889_readw(chip, AD_AC97_ACIC); /* flush posted write */ } static void snd_ad1889_ac97_bus_free(struct snd_ac97_bus *bus) { struct snd_ad1889 *chip = bus->private_data; chip->ac97_bus = NULL; } static void snd_ad1889_ac97_free(struct snd_ac97 *ac97) { struct snd_ad1889 *chip = ac97->private_data; chip->ac97 = NULL; } static int __devinit snd_ad1889_ac97_init(struct snd_ad1889 *chip, const char *quirk_override) { int err; struct snd_ac97_template ac97; static struct snd_ac97_bus_ops ops = { .write = snd_ad1889_ac97_write, .read = snd_ad1889_ac97_read, }; /* doing that here, it works. */ snd_ad1889_ac97_xinit(chip); err = snd_ac97_bus(chip->card, 0, &ops, chip, &chip->ac97_bus); if (err < 0) return err; chip->ac97_bus->private_free = snd_ad1889_ac97_bus_free; memset(&ac97, 0, sizeof(ac97)); ac97.private_data = chip; ac97.private_free = snd_ad1889_ac97_free; ac97.pci = chip->pci; err = snd_ac97_mixer(chip->ac97_bus, &ac97, &chip->ac97); if (err < 0) return err; snd_ac97_tune_hardware(chip->ac97, ac97_quirks, quirk_override); return 0; } static int snd_ad1889_free(struct snd_ad1889 *chip) { if (chip->irq < 0) goto skip_hw; spin_lock_irq(&chip->lock); ad1889_mute(chip); /* Turn off interrupt on count and zero DMA registers */ ad1889_channel_reset(chip, AD_CHAN_WAV | AD_CHAN_ADC); /* clear DISR. If we don't, we'd better jump off the Eiffel Tower */ ad1889_writel(chip, AD_DMA_DISR, AD_DMA_DISR_PTAI | AD_DMA_DISR_PMAI); ad1889_readl(chip, AD_DMA_DISR); /* flush, dammit! */ spin_unlock_irq(&chip->lock); if (chip->irq >= 0) free_irq(chip->irq, chip); skip_hw: if (chip->iobase) iounmap(chip->iobase); pci_release_regions(chip->pci); pci_disable_device(chip->pci); kfree(chip); return 0; } static int snd_ad1889_dev_free(struct snd_device *device) { struct snd_ad1889 *chip = device->device_data; return snd_ad1889_free(chip); } static int __devinit snd_ad1889_init(struct snd_ad1889 *chip) { ad1889_writew(chip, AD_DS_CCS, AD_DS_CCS_CLKEN); /* turn on clock */ ad1889_readw(chip, AD_DS_CCS); /* flush posted write */ mdelay(10); /* enable Master and Target abort interrupts */ ad1889_writel(chip, AD_DMA_DISR, AD_DMA_DISR_PMAE | AD_DMA_DISR_PTAE); return 0; } static int __devinit snd_ad1889_create(struct snd_card *card, struct pci_dev *pci, struct snd_ad1889 **rchip) { int err; struct snd_ad1889 *chip; static struct snd_device_ops ops = { .dev_free = snd_ad1889_dev_free, }; *rchip = NULL; if ((err = pci_enable_device(pci)) < 0) return err; /* check PCI availability (32bit DMA) */ if (pci_set_dma_mask(pci, DMA_32BIT_MASK) < 0 || pci_set_consistent_dma_mask(pci, DMA_32BIT_MASK) < 0) { printk(KERN_ERR PFX "error setting 32-bit DMA mask.\n"); pci_disable_device(pci); return -ENXIO; } /* allocate chip specific data with zero-filled memory */ if ((chip = kzalloc(sizeof(*chip), GFP_KERNEL)) == NULL) { pci_disable_device(pci); return -ENOMEM; } chip->card = card; card->private_data = chip; chip->pci = pci; chip->irq = -1; /* (1) PCI resource allocation */ if ((err = pci_request_regions(pci, card->driver)) < 0) goto free_and_ret; chip->bar = pci_resource_start(pci, 0); chip->iobase = ioremap_nocache(chip->bar, pci_resource_len(pci, 0)); if (chip->iobase == NULL) { printk(KERN_ERR PFX "unable to reserve region.\n"); err = -EBUSY; goto free_and_ret; } pci_set_master(pci); spin_lock_init(&chip->lock); /* only now can we call ad1889_free */ if (request_irq(pci->irq, snd_ad1889_interrupt, IRQF_SHARED, card->driver, chip)) { printk(KERN_ERR PFX "cannot obtain IRQ %d\n", pci->irq); snd_ad1889_free(chip); return -EBUSY; } chip->irq = pci->irq; synchronize_irq(chip->irq); /* (2) initialization of the chip hardware */ if ((err = snd_ad1889_init(chip)) < 0) { snd_ad1889_free(chip); return err; } if ((err = snd_device_new(card, SNDRV_DEV_LOWLEVEL, chip, &ops)) < 0) { snd_ad1889_free(chip); return err; } snd_card_set_dev(card, &pci->dev); *rchip = chip; return 0; free_and_ret: kfree(chip); pci_disable_device(pci); return err; } static int __devinit snd_ad1889_probe(struct pci_dev *pci, const struct pci_device_id *pci_id) { int err; static int devno; struct snd_card *card; struct snd_ad1889 *chip; /* (1) */ if (devno >= SNDRV_CARDS) return -ENODEV; if (!enable[devno]) { devno++; return -ENOENT; } /* (2) */ card = snd_card_new(index[devno], id[devno], THIS_MODULE, 0); /* XXX REVISIT: we can probably allocate chip in this call */ if (card == NULL) return -ENOMEM; strcpy(card->driver, "AD1889"); strcpy(card->shortname, "Analog Devices AD1889"); /* (3) */ err = snd_ad1889_create(card, pci, &chip); if (err < 0) goto free_and_ret; /* (4) */ sprintf(card->longname, "%s at 0x%lx irq %i", card->shortname, chip->bar, chip->irq); /* (5) */ /* register AC97 mixer */ err = snd_ad1889_ac97_init(chip, ac97_quirk[devno]); if (err < 0) goto free_and_ret; err = snd_ad1889_pcm_init(chip, 0, NULL); if (err < 0) goto free_and_ret; /* register proc interface */ snd_ad1889_proc_init(chip); /* (6) */ err = snd_card_register(card); if (err < 0) goto free_and_ret; /* (7) */ pci_set_drvdata(pci, card); devno++; return 0; free_and_ret: snd_card_free(card); return err; } static void __devexit snd_ad1889_remove(struct pci_dev *pci) { snd_card_free(pci_get_drvdata(pci)); pci_set_drvdata(pci, NULL); } static struct pci_device_id snd_ad1889_ids[] = { { PCI_DEVICE(PCI_VENDOR_ID_ANALOG_DEVICES, PCI_DEVICE_ID_AD1889JS) }, { 0, }, }; MODULE_DEVICE_TABLE(pci, snd_ad1889_ids); static struct pci_driver ad1889_pci_driver = { .name = "AD1889 Audio", .id_table = snd_ad1889_ids, .probe = snd_ad1889_probe, .remove = __devexit_p(snd_ad1889_remove), }; static int __init alsa_ad1889_init(void) { return pci_register_driver(&ad1889_pci_driver); } static void __exit alsa_ad1889_fini(void) { pci_unregister_driver(&ad1889_pci_driver); } module_init(alsa_ad1889_init); module_exit(alsa_ad1889_fini);
/* * Copyright (c) 1982, 1986, 1988, 1990, 1993 * The Regents of the University of California. 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. * 4. Neither the name of the University 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 REGENTS 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. * * @(#)ip_output.c 8.3 (Berkeley) 1/21/94 * $FreeBSD: src/sys/netinet/ip_output.c,v 1.271 2007/03/23 09:43:36 bms Exp $ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #define _IP_VHL #include <sys/param.h> #include <sys/queue.h> #include <sys/systm.h> #include <sys/malloc.h> #include <sys/mbuf.h> #include <errno.h> #include <sys/protosw.h> #include <sys/socket.h> #include <sys/socketvar.h> #include <net/if.h> #include <net/route.h> #include <netinet/in.h> #include <netinet/in_systm.h> #include <netinet/ip.h> #include <netinet/in_pcb.h> #include <netinet/in_var.h> #include <netinet/ip_var.h> #include <machine/in_cksum.h> #if !defined(COMPAT_IPFW) || COMPAT_IPFW == 1 #undef COMPAT_IPFW #define COMPAT_IPFW 1 #else #undef COMPAT_IPFW #endif u_short ip_id; static struct mbuf *ip_insertoptions(struct mbuf *, struct mbuf *, int *); static void ip_mloopback (struct ifnet *, struct mbuf *, struct sockaddr_in *, int); static int ip_getmoptions (int, struct ip_moptions *, struct mbuf **); static int ip_optcopy(struct ip *, struct ip *); static int ip_pcbopts(struct mbuf **, struct mbuf *); static int ip_setmoptions (int, struct ip_moptions **, struct mbuf *); extern struct protosw inetsw[]; /* * IP output. The packet in mbuf chain m contains a skeletal IP * header (with len, off, ttl, proto, tos, src, dst). * The mbuf chain containing the packet will be freed. * The mbuf opt, if present, will not be freed. */ int ip_output(struct mbuf *m0, struct mbuf *opt, struct route *ro, int flags, struct ip_moptions *imo) { struct ip *ip, *mhip; struct ifnet *ifp; struct mbuf *m = m0; int hlen = sizeof (struct ip); int len = 0, off, error = 0; struct sockaddr_in *dst; struct in_ifaddr *ia; int isbroadcast; #ifdef DIAGNOSTIC if ((m->m_flags & M_PKTHDR) == 0) panic("ip_output no HDR"); if (!ro) panic("ip_output no route, proto = %d", mtod(m, struct ip *)->ip_p); #endif if (opt) { m = ip_insertoptions(m, opt, &len); hlen = len; } ip = mtod(m, struct ip *); /* * Fill in IP header. */ if ((flags & (IP_FORWARDING|IP_RAWOUTPUT)) == 0) { #ifdef _IP_VHL ip->ip_vhl = IP_MAKE_VHL(IPVERSION, hlen >> 2); #else ip->ip_v = IPVERSION; ip->ip_hl = hlen >> 2; #endif ip->ip_off &= IP_DF; ip->ip_id = htons(ip_id++); ipstat.ips_localout++; } else { #ifdef _IP_VHL hlen = IP_VHL_HL(ip->ip_vhl) << 2; #else hlen = ip->ip_hl << 2; #endif } dst = (struct sockaddr_in *)&ro->ro_dst; /* * If there is a cached route, * check that it is to the same destination * and is still up. If not, free it and try again. */ if (ro->ro_rt && ((ro->ro_rt->rt_flags & RTF_UP) == 0 || dst->sin_addr.s_addr != ip->ip_dst.s_addr)) { RTFREE(ro->ro_rt); ro->ro_rt = (struct rtentry *)0; } if (ro->ro_rt == NULL) { dst->sin_family = AF_INET; dst->sin_len = sizeof(*dst); dst->sin_addr = ip->ip_dst; } /* * If routing to interface only, * short circuit routing lookup. */ #define ifatoia(ifa) ((struct in_ifaddr *)(ifa)) #define sintosa(sin) ((struct sockaddr *)(sin)) if (flags & IP_ROUTETOIF) { if ((ia = ifatoia(ifa_ifwithdstaddr(sintosa(dst)))) == 0 && (ia = ifatoia(ifa_ifwithnet(sintosa(dst)))) == 0) { ipstat.ips_noroute++; error = ENETUNREACH; goto bad; } ifp = ia->ia_ifp; ip->ip_ttl = 1; isbroadcast = in_broadcast(dst->sin_addr, ifp); } else if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) && imo != NULL && imo->imo_multicast_ifp != NULL) { /* * Bypass the normal routing lookup for multicast * packets if the interface is specified. */ ifp = imo->imo_multicast_ifp; IFP_TO_IA(ifp, ia); isbroadcast = 0; /* fool gcc */ } else { /* * If this is the case, we probably don't want to allocate * a protocol-cloned route since we didn't get one from the * ULP. This lets TCP do its thing, while not burdening * forwarding or ICMP with the overhead of cloning a route. * Of course, we still want to do any cloning requested by * the link layer, as this is probably required in all cases * for correct operation (as it is for ARP). */ if (ro->ro_rt == 0) rtalloc_ign(ro, RTF_PRCLONING); if (ro->ro_rt == 0) { ipstat.ips_noroute++; error = EHOSTUNREACH; goto bad; } ia = ifatoia(ro->ro_rt->rt_ifa); ifp = ro->ro_rt->rt_ifp; ro->ro_rt->rt_use++; if (ro->ro_rt->rt_flags & RTF_GATEWAY) dst = (struct sockaddr_in *)ro->ro_rt->rt_gateway; if (ro->ro_rt->rt_flags & RTF_HOST) isbroadcast = (ro->ro_rt->rt_flags & RTF_BROADCAST); else isbroadcast = in_broadcast(dst->sin_addr, ifp); } if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr))) { struct in_multi *inm; m->m_flags |= M_MCAST; /* * IP destination address is multicast. Make sure "dst" * still points to the address in "ro". (It may have been * changed to point to a gateway address, above.) */ dst = (struct sockaddr_in *)&ro->ro_dst; /* * See if the caller provided any multicast options */ if (imo != NULL) { ip->ip_ttl = imo->imo_multicast_ttl; if (imo->imo_multicast_ifp != NULL) ifp = imo->imo_multicast_ifp; if (imo->imo_multicast_vif != -1) ip->ip_src.s_addr = ip_mcast_src(imo->imo_multicast_vif); } else ip->ip_ttl = IP_DEFAULT_MULTICAST_TTL; /* * Confirm that the outgoing interface supports multicast. */ if ((imo == NULL) || (imo->imo_multicast_vif == -1)) { if ((ifp->if_flags & IFF_MULTICAST) == 0) { ipstat.ips_noroute++; error = ENETUNREACH; goto bad; } } /* * If source address not specified yet, use address * of outgoing interface. */ if (ip->ip_src.s_addr == INADDR_ANY) { register struct in_ifaddr *ia; for (ia = in_ifaddr; ia; ia = ia->ia_next) if (ia->ia_ifp == ifp) { ip->ip_src = IA_SIN(ia)->sin_addr; break; } } IN_LOOKUP_MULTI(ip->ip_dst, ifp, inm); if (inm != NULL && (imo == NULL || imo->imo_multicast_loop)) { /* * If we belong to the destination multicast group * on the outgoing interface, and the caller did not * forbid loopback, loop back a copy. */ ip_mloopback(ifp, m, dst, hlen); } else { /* * If we are acting as a multicast router, perform * multicast forwarding as if the packet had just * arrived on the interface to which we are about * to send. The multicast forwarding function * recursively calls this function, using the * IP_FORWARDING flag to prevent infinite recursion. * * Multicasts that are looped back by ip_mloopback(), * above, will be forwarded by the ip_input() routine, * if necessary. */ if (ip_mrouter && (flags & IP_FORWARDING) == 0) { /* * Check if rsvp daemon is running. If not, don't * set ip_moptions. This ensures that the packet * is multicast and not just sent down one link * as prescribed by rsvpd. */ if (!rsvp_on) imo = NULL; if (ip_mforward(ip, ifp, m, imo) != 0) { m_freem(m); goto done; } } } /* * Multicasts with a time-to-live of zero may be looped- * back, above, but must not be transmitted on a network. * Also, multicasts addressed to the loopback interface * are not sent -- the above call to ip_mloopback() will * loop back a copy if this host actually belongs to the * destination group on the loopback interface. */ if (ip->ip_ttl == 0 || ifp->if_flags & IFF_LOOPBACK) { m_freem(m); goto done; } goto sendit; } #ifndef notdef /* * If source address not specified yet, use address * of outgoing interface. */ if (ip->ip_src.s_addr == INADDR_ANY) ip->ip_src = IA_SIN(ia)->sin_addr; #endif /* * Verify that we have any chance at all of being able to queue * the packet or packet fragments */ if ((ifp->if_snd.ifq_len + ip->ip_len / ifp->if_mtu + 1) >= ifp->if_snd.ifq_maxlen) { error = ENOBUFS; goto bad; } /* * Look for broadcast address and * verify user is allowed to send * such a packet. */ if (isbroadcast) { if ((ifp->if_flags & IFF_BROADCAST) == 0) { error = EADDRNOTAVAIL; goto bad; } if ((flags & IP_ALLOWBROADCAST) == 0) { error = EACCES; goto bad; } /* don't allow broadcast messages to be fragmented */ if (ip->ip_len > ifp->if_mtu) { error = EMSGSIZE; goto bad; } m->m_flags |= M_BCAST; } else { m->m_flags &= ~M_BCAST; } sendit: /* * IpHack's section. * - Xlate: translate packet's addr/port (NAT). * - Firewall: deny/allow/etc. * - Wrap: fake packet's addr/port <unimpl.> * - Encapsulate: put it in another IP and send out. <unimp.> */ #ifdef COMPAT_IPFW if (ip_nat_ptr && !(*ip_nat_ptr)(&ip, &m, ifp, IP_NAT_OUT)) { error = EACCES; goto done; } /* * Check with the firewall... */ if (ip_fw_chk_ptr) { #ifdef IPDIVERT ip_divert_port = (*ip_fw_chk_ptr)(&ip, hlen, ifp, ip_divert_ignore, &m); ip_divert_ignore = 0; if (ip_divert_port) { /* Divert packet */ (*inetsw[ip_protox[IPPROTO_DIVERT]].pr_input)(m, 0); goto done; } #else /* If ipfw says divert, we have to just drop packet */ if ((*ip_fw_chk_ptr)(&ip, hlen, ifp, 0, &m)) { m_freem(m); goto done; } #endif if (!m) { error = EACCES; goto done; } } #endif /* COMPAT_IPFW */ /* * If small enough for interface, or the interface will take * care of the fragmentation for us, we can just send directly. */ if ((u_short)ip->ip_len <= ifp->if_mtu) { ip->ip_len = htons(ip->ip_len); ip->ip_off = htons(ip->ip_off); ip->ip_sum = 0; #ifdef _IP_VHL if (ip->ip_vhl == IP_VHL_BORING) { #else if ((ip->ip_hl == 5) && (ip->ip_v = IPVERSION)) { #endif ip->ip_sum = in_cksum_hdr(ip); } else { ip->ip_sum = in_cksum(m, hlen); } error = (*ifp->if_output)(ifp, m, (struct sockaddr *)dst, ro->ro_rt); goto done; } /* * Too large for interface; fragment if possible. * Must be able to put at least 8 bytes per fragment. */ if (ip->ip_off & IP_DF) { error = EMSGSIZE; /* * This case can happen if the user changed the MTU * of an interface after enabling IP on it. Because * most netifs don't keep track of routes pointing to * them, there is no way for one to update all its * routes when the MTU is changed. */ if ((ro->ro_rt->rt_flags & (RTF_UP | RTF_HOST)) && !(ro->ro_rt->rt_rmx.rmx_locks & RTV_MTU) && (ro->ro_rt->rt_rmx.rmx_mtu > ifp->if_mtu)) { ro->ro_rt->rt_rmx.rmx_mtu = ifp->if_mtu; } ipstat.ips_cantfrag++; goto bad; } len = (ifp->if_mtu - hlen) &~ 7; if (len < 8) { error = EMSGSIZE; goto bad; } { int mhlen, firstlen = len; struct mbuf **mnext = &m->m_nextpkt; /* * Loop through length of segment after first fragment, * make new header and copy data of each part and link onto chain. */ m0 = m; mhlen = sizeof (struct ip); for (off = hlen + len; off < (u_short)ip->ip_len; off += len) { MGETHDR(m, M_DONTWAIT, MT_HEADER); if (m == 0) { error = ENOBUFS; ipstat.ips_odropped++; goto sendorfree; } m->m_flags |= (m0->m_flags & M_MCAST); m->m_data += max_linkhdr; mhip = mtod(m, struct ip *); *mhip = *ip; if (hlen > sizeof (struct ip)) { mhlen = ip_optcopy(ip, mhip) + sizeof (struct ip); #ifdef _IP_VHL mhip->ip_vhl = IP_MAKE_VHL(IPVERSION, mhlen >> 2); #else mhip->ip_v = IPVERSION; mhip->ip_hl = mhlen >> 2; #endif } m->m_len = mhlen; mhip->ip_off = ((off - hlen) >> 3) + (ip->ip_off & ~IP_MF); if (ip->ip_off & IP_MF) mhip->ip_off |= IP_MF; if (off + len >= (u_short)ip->ip_len) len = (u_short)ip->ip_len - off; else mhip->ip_off |= IP_MF; mhip->ip_len = htons((u_short)(len + mhlen)); m->m_next = m_copy(m0, off, len); if (m->m_next == 0) { (void) m_free(m); error = ENOBUFS; /* ??? */ ipstat.ips_odropped++; goto sendorfree; } m->m_pkthdr.len = mhlen + len; m->m_pkthdr.rcvif = NULL; mhip->ip_off = htons(mhip->ip_off); mhip->ip_sum = 0; #ifdef _IP_VHL if (mhip->ip_vhl == IP_VHL_BORING) { #else if ((mhip->ip_hl == 5) && (mhip->ip_v == IPVERSION) ) { #endif mhip->ip_sum = in_cksum_hdr(mhip); } else { mhip->ip_sum = in_cksum(m, mhlen); } *mnext = m; mnext = &m->m_nextpkt; ipstat.ips_ofragments++; } /* * Update first fragment by trimming what's been copied out * and updating header, then send each fragment (in order). */ m = m0; m_adj(m, hlen + firstlen - (u_short)ip->ip_len); m->m_pkthdr.len = hlen + firstlen; ip->ip_len = htons((u_short)m->m_pkthdr.len); ip->ip_off |= IP_MF; ip->ip_off = htons(ip->ip_off); ip->ip_sum = 0; #ifdef _IP_VHL if (ip->ip_vhl == IP_VHL_BORING) { #else if ((ip->ip_hl == 5) && (ip->ip_v == IPVERSION) ) { #endif ip->ip_sum = in_cksum_hdr(ip); } else { ip->ip_sum = in_cksum(m, hlen); } sendorfree: for (m = m0; m; m = m0) { m0 = m->m_nextpkt; m->m_nextpkt = 0; if (error == 0) error = (*ifp->if_output)(ifp, m, (struct sockaddr *)dst, ro->ro_rt); else m_freem(m); } if (error == 0) ipstat.ips_fragmented++; } done: return (error); bad: m_freem(m0); goto done; } /* * Insert IP options into preformed packet. * Adjust IP destination as required for IP source routing, * as indicated by a non-zero in_addr at the start of the options. * * XXX This routine assumes that the packet has no options in place. */ static struct mbuf * ip_insertoptions(struct mbuf *m, struct mbuf *opt, int *phlen) { register struct ipoption *p = mtod(opt, struct ipoption *); struct mbuf *n; register struct ip *ip = mtod(m, struct ip *); uint32_t optlen; optlen = opt->m_len - sizeof(p->ipopt_dst); if (optlen + ip->ip_len > IP_MAXPACKET) return (m); /* XXX should fail */ if (p->ipopt_dst.s_addr) ip->ip_dst = p->ipopt_dst; if (m->m_flags & M_EXT || m->m_data - optlen < m->m_pktdat) { MGETHDR(n, M_DONTWAIT, MT_HEADER); if (n == 0) return (m); n->m_pkthdr.len = m->m_pkthdr.len + optlen; m->m_len -= sizeof(struct ip); m->m_data += sizeof(struct ip); n->m_next = m; m = n; m->m_len = optlen + sizeof(struct ip); m->m_data += max_linkhdr; (void)memcpy(mtod(m, void *), ip, sizeof(struct ip)); } else { m->m_data -= optlen; m->m_len += optlen; m->m_pkthdr.len += optlen; ovbcopy((caddr_t)ip, mtod(m, caddr_t), sizeof(struct ip)); } ip = mtod(m, struct ip *); bcopy(p->ipopt_list, ip + 1, optlen); *phlen = sizeof(struct ip) + optlen; #ifdef _IP_VHL ip->ip_vhl = IP_MAKE_VHL(IPVERSION, *phlen >> 2); #else ip->ip_v = IPVERSION; ip->ip_hl = *phlen >> 2; #endif ip->ip_len += optlen; return (m); } /* * Copy options from ip to jp, * omitting those not copied during fragmentation. */ static int ip_optcopy(struct ip *ip, struct ip *jp) { register u_char *cp, *dp; int opt, optlen, cnt; cp = (u_char *)(ip + 1); dp = (u_char *)(jp + 1); #ifdef _IP_VHL cnt = (IP_VHL_HL(ip->ip_vhl) << 2) - sizeof (struct ip); #else cnt = (ip->ip_hl << 2) - sizeof (struct ip); #endif for (; cnt > 0; cnt -= optlen, cp += optlen) { opt = cp[0]; if (opt == IPOPT_EOL) break; if (opt == IPOPT_NOP) { /* Preserve for IP mcast tunnel's LSRR alignment. */ *dp++ = IPOPT_NOP; optlen = 1; continue; } else optlen = cp[IPOPT_OLEN]; /* bogus lengths should have been caught by ip_dooptions */ if (optlen > cnt) optlen = cnt; if (IPOPT_COPIED(opt)) { bcopy(cp, dp, optlen); dp += optlen; } } for (optlen = dp - (u_char *)(jp+1); optlen & 0x3; optlen++) *dp++ = IPOPT_EOL; return (optlen); } /* * IP socket option processing. */ int ip_ctloutput(int op, struct socket *so, int level, int optname, struct mbuf **mp) { struct inpcb *inp = sotoinpcb(so); register struct mbuf *m = *mp; register int optval = 0; int error = 0; if (level != IPPROTO_IP) { error = EINVAL; if (op == PRCO_SETOPT && *mp) (void) m_free(*mp); } else switch (op) { case PRCO_SETOPT: switch (optname) { case IP_OPTIONS: #ifdef notyet case IP_RETOPTS: return (ip_pcbopts(optname, &inp->inp_options, m)); #else return (ip_pcbopts(&inp->inp_options, m)); #endif case IP_TOS: case IP_TTL: case IP_RECVOPTS: case IP_RECVRETOPTS: case IP_RECVDSTADDR: case IP_RECVIF: if (m == 0 || m->m_len != sizeof(int)) error = EINVAL; else { optval = *mtod(m, int *); switch (optname) { case IP_TOS: inp->inp_ip_tos = optval; break; case IP_TTL: inp->inp_ip_ttl = optval; break; #define OPTSET(bit) \ if (optval) \ inp->inp_flags |= bit; \ else \ inp->inp_flags &= ~bit; case IP_RECVOPTS: OPTSET(INP_RECVOPTS); break; case IP_RECVRETOPTS: OPTSET(INP_RECVRETOPTS); break; case IP_RECVDSTADDR: OPTSET(INP_RECVDSTADDR); break; case IP_RECVIF: OPTSET(INP_RECVIF); break; } } break; #undef OPTSET case IP_MULTICAST_IF: case IP_MULTICAST_VIF: case IP_MULTICAST_TTL: case IP_MULTICAST_LOOP: case IP_ADD_MEMBERSHIP: case IP_DROP_MEMBERSHIP: error = ip_setmoptions(optname, &inp->inp_moptions, m); break; case IP_PORTRANGE: if (m == 0 || m->m_len != sizeof(int)) error = EINVAL; else { optval = *mtod(m, int *); switch (optval) { case IP_PORTRANGE_DEFAULT: inp->inp_flags &= ~(INP_LOWPORT); inp->inp_flags &= ~(INP_HIGHPORT); break; case IP_PORTRANGE_HIGH: inp->inp_flags &= ~(INP_LOWPORT); inp->inp_flags |= INP_HIGHPORT; break; case IP_PORTRANGE_LOW: inp->inp_flags &= ~(INP_HIGHPORT); inp->inp_flags |= INP_LOWPORT; break; default: error = EINVAL; break; } } break; default: error = ENOPROTOOPT; break; } if (m) (void)m_free(m); break; case PRCO_GETOPT: switch (optname) { case IP_OPTIONS: case IP_RETOPTS: *mp = m = m_get(M_WAIT, MT_SOOPTS); if (inp->inp_options) { m->m_len = inp->inp_options->m_len; bcopy(mtod(inp->inp_options, void *), mtod(m, void *), m->m_len); } else m->m_len = 0; break; case IP_TOS: case IP_TTL: case IP_RECVOPTS: case IP_RECVRETOPTS: case IP_RECVDSTADDR: case IP_RECVIF: *mp = m = m_get(M_WAIT, MT_SOOPTS); m->m_len = sizeof(int); switch (optname) { case IP_TOS: optval = inp->inp_ip_tos; break; case IP_TTL: optval = inp->inp_ip_ttl; break; #define OPTBIT(bit) (inp->inp_flags & bit ? 1 : 0) case IP_RECVOPTS: optval = OPTBIT(INP_RECVOPTS); break; case IP_RECVRETOPTS: optval = OPTBIT(INP_RECVRETOPTS); break; case IP_RECVDSTADDR: optval = OPTBIT(INP_RECVDSTADDR); break; case IP_RECVIF: optval = OPTBIT(INP_RECVIF); break; } *mtod(m, int *) = optval; break; case IP_MULTICAST_IF: case IP_MULTICAST_VIF: case IP_MULTICAST_TTL: case IP_MULTICAST_LOOP: case IP_ADD_MEMBERSHIP: case IP_DROP_MEMBERSHIP: error = ip_getmoptions(optname, inp->inp_moptions, mp); break; case IP_PORTRANGE: *mp = m = m_get(M_WAIT, MT_SOOPTS); m->m_len = sizeof(int); if (inp->inp_flags & INP_HIGHPORT) optval = IP_PORTRANGE_HIGH; else if (inp->inp_flags & INP_LOWPORT) optval = IP_PORTRANGE_LOW; else optval = 0; *mtod(m, int *) = optval; break; default: error = ENOPROTOOPT; break; } break; } return (error); } /* * Set up IP options in pcb for insertion in output packets. * Store in mbuf with pointer in pcbopt, adding pseudo-option * with destination address if source routed. */ static int #ifdef notyet ip_pcbopts(int optname, struct mbuf **pcbopt, struct mbuf *m) #else ip_pcbopts(struct mbuf **pcbopt, struct mbuf *m) #endif { register int cnt, optlen; register u_char *cp; u_char opt; /* turn off any old options */ if (*pcbopt) (void)m_free(*pcbopt); *pcbopt = 0; if (m == (struct mbuf *)0 || m->m_len == 0) { /* * Only turning off any previous options. */ if (m) (void)m_free(m); return (0); } #ifndef vax if (m->m_len % sizeof(long)) goto bad; #endif /* * IP first-hop destination address will be stored before * actual options; move other options back * and clear it when none present. */ if (m->m_data + m->m_len + sizeof(struct in_addr) >= &m->m_dat[MLEN]) goto bad; cnt = m->m_len; m->m_len += sizeof(struct in_addr); cp = mtod(m, u_char *) + sizeof(struct in_addr); ovbcopy(mtod(m, caddr_t), (caddr_t)cp, (unsigned)cnt); bzero(mtod(m, caddr_t), sizeof(struct in_addr)); for (; cnt > 0; cnt -= optlen, cp += optlen) { opt = cp[IPOPT_OPTVAL]; if (opt == IPOPT_EOL) break; if (opt == IPOPT_NOP) optlen = 1; else { optlen = cp[IPOPT_OLEN]; if (optlen <= IPOPT_OLEN || optlen > cnt) goto bad; } switch (opt) { default: break; case IPOPT_LSRR: case IPOPT_SSRR: /* * user process specifies route as: * ->A->B->C->D * D must be our final destination (but we can't * check that since we may not have connected yet). * A is first hop destination, which doesn't appear in * actual IP option, but is stored before the options. */ if (optlen < IPOPT_MINOFF - 1 + sizeof(struct in_addr)) goto bad; m->m_len -= sizeof(struct in_addr); cnt -= sizeof(struct in_addr); optlen -= sizeof(struct in_addr); cp[IPOPT_OLEN] = optlen; /* * Move first hop before start of options. */ bcopy((caddr_t)&cp[IPOPT_OFFSET+1], mtod(m, caddr_t), sizeof(struct in_addr)); /* * Then copy rest of options back * to close up the deleted entry. */ ovbcopy((caddr_t)(&cp[IPOPT_OFFSET+1] + sizeof(struct in_addr)), (caddr_t)&cp[IPOPT_OFFSET+1], (unsigned)cnt + sizeof(struct in_addr)); break; } } if (m->m_len > MAX_IPOPTLEN + sizeof(struct in_addr)) goto bad; *pcbopt = m; return (0); bad: (void)m_free(m); return (EINVAL); } /* * Set the IP multicast options in response to user setsockopt(). */ static int ip_setmoptions(int optname, struct ip_moptions **imop, struct mbuf *m) { int error = 0; u_char loop; int i; struct in_addr addr; struct ip_mreq *mreq; struct ifnet *ifp; struct ip_moptions *imo = *imop; struct route ro; register struct sockaddr_in *dst; int s; if (imo == NULL) { /* * No multicast option buffer attached to the pcb; * allocate one and initialize to default values. */ imo = (struct ip_moptions*)malloc(sizeof(*imo), M_IPMOPTS, M_WAITOK); if (imo == NULL) return (ENOBUFS); *imop = imo; imo->imo_multicast_ifp = NULL; imo->imo_multicast_vif = -1; imo->imo_multicast_ttl = IP_DEFAULT_MULTICAST_TTL; imo->imo_multicast_loop = IP_DEFAULT_MULTICAST_LOOP; imo->imo_num_memberships = 0; } switch (optname) { /* store an index number for the vif you wanna use in the send */ case IP_MULTICAST_VIF: if (!legal_vif_num) { error = EOPNOTSUPP; break; } if (m == NULL || m->m_len != sizeof(int)) { error = EINVAL; break; } i = *(mtod(m, int *)); if (!legal_vif_num(i) && (i != -1)) { error = EINVAL; break; } imo->imo_multicast_vif = i; break; case IP_MULTICAST_IF: /* * Select the interface for outgoing multicast packets. */ if (m == NULL || m->m_len != sizeof(struct in_addr)) { error = EINVAL; break; } addr = *(mtod(m, struct in_addr *)); /* * INADDR_ANY is used to remove a previous selection. * When no interface is selected, a default one is * chosen every time a multicast packet is sent. */ if (addr.s_addr == INADDR_ANY) { imo->imo_multicast_ifp = NULL; break; } /* * The selected interface is identified by its local * IP address. Find the interface and confirm that * it supports multicasting. */ s = splimp(); INADDR_TO_IFP(addr, ifp); if (ifp == NULL || (ifp->if_flags & IFF_MULTICAST) == 0) { splx(s); error = EADDRNOTAVAIL; break; } imo->imo_multicast_ifp = ifp; splx(s); break; case IP_MULTICAST_TTL: /* * Set the IP time-to-live for outgoing multicast packets. */ if (m == NULL || m->m_len != 1) { error = EINVAL; break; } imo->imo_multicast_ttl = *(mtod(m, u_char *)); break; case IP_MULTICAST_LOOP: /* * Set the loopback flag for outgoing multicast packets. * Must be zero or one. */ if (m == NULL || m->m_len != 1 || (loop = *(mtod(m, u_char *))) > 1) { error = EINVAL; break; } imo->imo_multicast_loop = loop; break; case IP_ADD_MEMBERSHIP: /* * Add a multicast group membership. * Group must be a valid IP multicast address. */ if (m == NULL || m->m_len != sizeof(struct ip_mreq)) { error = EINVAL; break; } mreq = mtod(m, struct ip_mreq *); if (!IN_MULTICAST(ntohl(mreq->imr_multiaddr.s_addr))) { error = EINVAL; break; } s = splimp(); /* * If no interface address was provided, use the interface of * the route to the given multicast address. */ if (mreq->imr_interface.s_addr == INADDR_ANY) { bzero((caddr_t)&ro, sizeof(ro)); dst = (struct sockaddr_in *)&ro.ro_dst; dst->sin_len = sizeof(*dst); dst->sin_family = AF_INET; dst->sin_addr = mreq->imr_multiaddr; rtalloc(&ro); if (ro.ro_rt == NULL) { error = EADDRNOTAVAIL; splx(s); break; } ifp = ro.ro_rt->rt_ifp; rtfree(ro.ro_rt); } else { INADDR_TO_IFP(mreq->imr_interface, ifp); } /* * See if we found an interface, and confirm that it * supports multicast. */ if (ifp == NULL || (ifp->if_flags & IFF_MULTICAST) == 0) { error = EADDRNOTAVAIL; splx(s); break; } /* * See if the membership already exists or if all the * membership slots are full. */ for (i = 0; i < imo->imo_num_memberships; ++i) { if (imo->imo_membership[i]->inm_ifp == ifp && imo->imo_membership[i]->inm_addr.s_addr == mreq->imr_multiaddr.s_addr) break; } if (i < imo->imo_num_memberships) { error = EADDRINUSE; splx(s); break; } if (i == IP_MAX_MEMBERSHIPS) { error = ETOOMANYREFS; splx(s); break; } /* * Everything looks good; add a new record to the multicast * address list for the given interface. */ if ((imo->imo_membership[i] = in_addmulti(&mreq->imr_multiaddr, ifp)) == NULL) { error = ENOBUFS; splx(s); break; } ++imo->imo_num_memberships; splx(s); break; case IP_DROP_MEMBERSHIP: /* * Drop a multicast group membership. * Group must be a valid IP multicast address. */ if (m == NULL || m->m_len != sizeof(struct ip_mreq)) { error = EINVAL; break; } mreq = mtod(m, struct ip_mreq *); if (!IN_MULTICAST(ntohl(mreq->imr_multiaddr.s_addr))) { error = EINVAL; break; } s = splimp(); /* * If an interface address was specified, get a pointer * to its ifnet structure. */ if (mreq->imr_interface.s_addr == INADDR_ANY) ifp = NULL; else { INADDR_TO_IFP(mreq->imr_interface, ifp); if (ifp == NULL) { error = EADDRNOTAVAIL; splx(s); break; } } /* * Find the membership in the membership array. */ for (i = 0; i < imo->imo_num_memberships; ++i) { if ((ifp == NULL || imo->imo_membership[i]->inm_ifp == ifp) && imo->imo_membership[i]->inm_addr.s_addr == mreq->imr_multiaddr.s_addr) break; } if (i == imo->imo_num_memberships) { error = EADDRNOTAVAIL; splx(s); break; } /* * Give up the multicast address record to which the * membership points. */ in_delmulti(imo->imo_membership[i]); /* * Remove the gap in the membership array. */ for (++i; i < imo->imo_num_memberships; ++i) imo->imo_membership[i-1] = imo->imo_membership[i]; --imo->imo_num_memberships; splx(s); break; default: error = EOPNOTSUPP; break; } /* * If all options have default values, no need to keep the mbuf. */ if (imo->imo_multicast_ifp == NULL && imo->imo_multicast_vif == -1 && imo->imo_multicast_ttl == IP_DEFAULT_MULTICAST_TTL && imo->imo_multicast_loop == IP_DEFAULT_MULTICAST_LOOP && imo->imo_num_memberships == 0) { free(*imop, M_IPMOPTS); *imop = NULL; } return (error); } /* * Return the IP multicast options in response to user getsockopt(). */ static int ip_getmoptions(int optname, struct ip_moptions *imo, struct mbuf **mp) { u_char *ttl; u_char *loop; struct in_addr *addr; struct in_ifaddr *ia; *mp = m_get(M_WAIT, MT_SOOPTS); switch (optname) { case IP_MULTICAST_VIF: if (imo != NULL) *(mtod(*mp, int *)) = imo->imo_multicast_vif; else *(mtod(*mp, int *)) = -1; (*mp)->m_len = sizeof(int); return(0); case IP_MULTICAST_IF: addr = mtod(*mp, struct in_addr *); (*mp)->m_len = sizeof(struct in_addr); if (imo == NULL || imo->imo_multicast_ifp == NULL) addr->s_addr = INADDR_ANY; else { IFP_TO_IA(imo->imo_multicast_ifp, ia); addr->s_addr = (ia == NULL) ? INADDR_ANY : IA_SIN(ia)->sin_addr.s_addr; } return (0); case IP_MULTICAST_TTL: ttl = mtod(*mp, u_char *); (*mp)->m_len = 1; *ttl = (imo == NULL) ? IP_DEFAULT_MULTICAST_TTL : imo->imo_multicast_ttl; return (0); case IP_MULTICAST_LOOP: loop = mtod(*mp, u_char *); (*mp)->m_len = 1; *loop = (imo == NULL) ? IP_DEFAULT_MULTICAST_LOOP : imo->imo_multicast_loop; return (0); default: return (EOPNOTSUPP); } } /* * Discard the IP multicast options. */ void ip_freemoptions(struct ip_moptions *imo) { register int i; if (imo != NULL) { for (i = 0; i < imo->imo_num_memberships; ++i) in_delmulti(imo->imo_membership[i]); free(imo, M_IPMOPTS); } } /* * Routine called from ip_output() to loop back a copy of an IP multicast * packet to the input queue of a specified interface. Note that this * calls the output routine of the loopback "driver", but with an interface * pointer that might NOT be a loopback interface -- evil, but easier than * replicating that code here. */ static void ip_mloopback(struct ifnet *ifp, struct mbuf *m, struct sockaddr_in *dst, int hlen) { register struct ip *ip; struct mbuf *copym; copym = m_copy(m, 0, M_COPYALL); if (copym != NULL && (copym->m_flags & M_EXT || copym->m_len < hlen)) copym = m_pullup(copym, hlen); if (copym != NULL) { /* * We don't bother to fragment if the IP length is greater * than the interface's MTU. Can this possibly matter? */ ip = mtod(copym, struct ip *); ip->ip_len = htons(ip->ip_len); ip->ip_off = htons(ip->ip_off); ip->ip_sum = 0; #ifdef _IP_VHL if (ip->ip_vhl == IP_VHL_BORING) { ip->ip_sum = in_cksum_hdr(ip); } else { ip->ip_sum = in_cksum(copym, hlen); } #else ip->ip_sum = in_cksum(copym, hlen); #endif /* * NB: * It's not clear whether there are any lingering * reentrancy problems in other areas which might * be exposed by using ip_input directly (in * particular, everything which modifies the packet * in-place). Yet another option is using the * protosw directly to deliver the looped back * packet. For the moment, we'll err on the side * of safety by continuing to abuse looutput(). */ #ifdef notdef copym->m_pkthdr.rcvif = ifp; ip_input(copym); #else (void) looutput(ifp, copym, (struct sockaddr *)dst, NULL); #endif } }
# /* ************************************************************************** # * * # * (C) Copyright Paul Mensonides 2002. # * 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) # * * # ************************************************************************** */ # # /* Revised by Edward Diener (2020) */ # # /* See http://www.boost.org for most recent version. */ # # ifndef BOOST_PREPROCESSOR_SEQ_DETAIL_SPLIT_HPP # define BOOST_PREPROCESSOR_SEQ_DETAIL_SPLIT_HPP # # include <boost/preprocessor/config/config.hpp> # # /* BOOST_PP_SEQ_SPLIT */ # # define BOOST_PP_SEQ_SPLIT(n, seq) BOOST_PP_SEQ_SPLIT_D(n, seq) # # if ~BOOST_PP_CONFIG_FLAGS() & BOOST_PP_CONFIG_MWCC() # define BOOST_PP_SEQ_SPLIT_D(n, seq) (BOOST_PP_SEQ_SPLIT_ ## n seq) # else # define BOOST_PP_SEQ_SPLIT_D(n, seq) (BOOST_PP_SEQ_SPLIT_ ## n ## seq) # endif # # if ~BOOST_PP_CONFIG_FLAGS() & BOOST_PP_CONFIG_STRICT() # # define BOOST_PP_SEQ_SPLIT_1(x) (x), # define BOOST_PP_SEQ_SPLIT_2(x) (x) BOOST_PP_SEQ_SPLIT_1 # define BOOST_PP_SEQ_SPLIT_3(x) (x) BOOST_PP_SEQ_SPLIT_2 # define BOOST_PP_SEQ_SPLIT_4(x) (x) BOOST_PP_SEQ_SPLIT_3 # define BOOST_PP_SEQ_SPLIT_5(x) (x) BOOST_PP_SEQ_SPLIT_4 # define BOOST_PP_SEQ_SPLIT_6(x) (x) BOOST_PP_SEQ_SPLIT_5 # define BOOST_PP_SEQ_SPLIT_7(x) (x) BOOST_PP_SEQ_SPLIT_6 # define BOOST_PP_SEQ_SPLIT_8(x) (x) BOOST_PP_SEQ_SPLIT_7 # define BOOST_PP_SEQ_SPLIT_9(x) (x) BOOST_PP_SEQ_SPLIT_8 # define BOOST_PP_SEQ_SPLIT_10(x) (x) BOOST_PP_SEQ_SPLIT_9 # define BOOST_PP_SEQ_SPLIT_11(x) (x) BOOST_PP_SEQ_SPLIT_10 # define BOOST_PP_SEQ_SPLIT_12(x) (x) BOOST_PP_SEQ_SPLIT_11 # define BOOST_PP_SEQ_SPLIT_13(x) (x) BOOST_PP_SEQ_SPLIT_12 # define BOOST_PP_SEQ_SPLIT_14(x) (x) BOOST_PP_SEQ_SPLIT_13 # define BOOST_PP_SEQ_SPLIT_15(x) (x) BOOST_PP_SEQ_SPLIT_14 # define BOOST_PP_SEQ_SPLIT_16(x) (x) BOOST_PP_SEQ_SPLIT_15 # define BOOST_PP_SEQ_SPLIT_17(x) (x) BOOST_PP_SEQ_SPLIT_16 # define BOOST_PP_SEQ_SPLIT_18(x) (x) BOOST_PP_SEQ_SPLIT_17 # define BOOST_PP_SEQ_SPLIT_19(x) (x) BOOST_PP_SEQ_SPLIT_18 # define BOOST_PP_SEQ_SPLIT_20(x) (x) BOOST_PP_SEQ_SPLIT_19 # define BOOST_PP_SEQ_SPLIT_21(x) (x) BOOST_PP_SEQ_SPLIT_20 # define BOOST_PP_SEQ_SPLIT_22(x) (x) BOOST_PP_SEQ_SPLIT_21 # define BOOST_PP_SEQ_SPLIT_23(x) (x) BOOST_PP_SEQ_SPLIT_22 # define BOOST_PP_SEQ_SPLIT_24(x) (x) BOOST_PP_SEQ_SPLIT_23 # define BOOST_PP_SEQ_SPLIT_25(x) (x) BOOST_PP_SEQ_SPLIT_24 # define BOOST_PP_SEQ_SPLIT_26(x) (x) BOOST_PP_SEQ_SPLIT_25 # define BOOST_PP_SEQ_SPLIT_27(x) (x) BOOST_PP_SEQ_SPLIT_26 # define BOOST_PP_SEQ_SPLIT_28(x) (x) BOOST_PP_SEQ_SPLIT_27 # define BOOST_PP_SEQ_SPLIT_29(x) (x) BOOST_PP_SEQ_SPLIT_28 # define BOOST_PP_SEQ_SPLIT_30(x) (x) BOOST_PP_SEQ_SPLIT_29 # define BOOST_PP_SEQ_SPLIT_31(x) (x) BOOST_PP_SEQ_SPLIT_30 # define BOOST_PP_SEQ_SPLIT_32(x) (x) BOOST_PP_SEQ_SPLIT_31 # define BOOST_PP_SEQ_SPLIT_33(x) (x) BOOST_PP_SEQ_SPLIT_32 # define BOOST_PP_SEQ_SPLIT_34(x) (x) BOOST_PP_SEQ_SPLIT_33 # define BOOST_PP_SEQ_SPLIT_35(x) (x) BOOST_PP_SEQ_SPLIT_34 # define BOOST_PP_SEQ_SPLIT_36(x) (x) BOOST_PP_SEQ_SPLIT_35 # define BOOST_PP_SEQ_SPLIT_37(x) (x) BOOST_PP_SEQ_SPLIT_36 # define BOOST_PP_SEQ_SPLIT_38(x) (x) BOOST_PP_SEQ_SPLIT_37 # define BOOST_PP_SEQ_SPLIT_39(x) (x) BOOST_PP_SEQ_SPLIT_38 # define BOOST_PP_SEQ_SPLIT_40(x) (x) BOOST_PP_SEQ_SPLIT_39 # define BOOST_PP_SEQ_SPLIT_41(x) (x) BOOST_PP_SEQ_SPLIT_40 # define BOOST_PP_SEQ_SPLIT_42(x) (x) BOOST_PP_SEQ_SPLIT_41 # define BOOST_PP_SEQ_SPLIT_43(x) (x) BOOST_PP_SEQ_SPLIT_42 # define BOOST_PP_SEQ_SPLIT_44(x) (x) BOOST_PP_SEQ_SPLIT_43 # define BOOST_PP_SEQ_SPLIT_45(x) (x) BOOST_PP_SEQ_SPLIT_44 # define BOOST_PP_SEQ_SPLIT_46(x) (x) BOOST_PP_SEQ_SPLIT_45 # define BOOST_PP_SEQ_SPLIT_47(x) (x) BOOST_PP_SEQ_SPLIT_46 # define BOOST_PP_SEQ_SPLIT_48(x) (x) BOOST_PP_SEQ_SPLIT_47 # define BOOST_PP_SEQ_SPLIT_49(x) (x) BOOST_PP_SEQ_SPLIT_48 # define BOOST_PP_SEQ_SPLIT_50(x) (x) BOOST_PP_SEQ_SPLIT_49 # define BOOST_PP_SEQ_SPLIT_51(x) (x) BOOST_PP_SEQ_SPLIT_50 # define BOOST_PP_SEQ_SPLIT_52(x) (x) BOOST_PP_SEQ_SPLIT_51 # define BOOST_PP_SEQ_SPLIT_53(x) (x) BOOST_PP_SEQ_SPLIT_52 # define BOOST_PP_SEQ_SPLIT_54(x) (x) BOOST_PP_SEQ_SPLIT_53 # define BOOST_PP_SEQ_SPLIT_55(x) (x) BOOST_PP_SEQ_SPLIT_54 # define BOOST_PP_SEQ_SPLIT_56(x) (x) BOOST_PP_SEQ_SPLIT_55 # define BOOST_PP_SEQ_SPLIT_57(x) (x) BOOST_PP_SEQ_SPLIT_56 # define BOOST_PP_SEQ_SPLIT_58(x) (x) BOOST_PP_SEQ_SPLIT_57 # define BOOST_PP_SEQ_SPLIT_59(x) (x) BOOST_PP_SEQ_SPLIT_58 # define BOOST_PP_SEQ_SPLIT_60(x) (x) BOOST_PP_SEQ_SPLIT_59 # define BOOST_PP_SEQ_SPLIT_61(x) (x) BOOST_PP_SEQ_SPLIT_60 # define BOOST_PP_SEQ_SPLIT_62(x) (x) BOOST_PP_SEQ_SPLIT_61 # define BOOST_PP_SEQ_SPLIT_63(x) (x) BOOST_PP_SEQ_SPLIT_62 # define BOOST_PP_SEQ_SPLIT_64(x) (x) BOOST_PP_SEQ_SPLIT_63 # define BOOST_PP_SEQ_SPLIT_65(x) (x) BOOST_PP_SEQ_SPLIT_64 # define BOOST_PP_SEQ_SPLIT_66(x) (x) BOOST_PP_SEQ_SPLIT_65 # define BOOST_PP_SEQ_SPLIT_67(x) (x) BOOST_PP_SEQ_SPLIT_66 # define BOOST_PP_SEQ_SPLIT_68(x) (x) BOOST_PP_SEQ_SPLIT_67 # define BOOST_PP_SEQ_SPLIT_69(x) (x) BOOST_PP_SEQ_SPLIT_68 # define BOOST_PP_SEQ_SPLIT_70(x) (x) BOOST_PP_SEQ_SPLIT_69 # define BOOST_PP_SEQ_SPLIT_71(x) (x) BOOST_PP_SEQ_SPLIT_70 # define BOOST_PP_SEQ_SPLIT_72(x) (x) BOOST_PP_SEQ_SPLIT_71 # define BOOST_PP_SEQ_SPLIT_73(x) (x) BOOST_PP_SEQ_SPLIT_72 # define BOOST_PP_SEQ_SPLIT_74(x) (x) BOOST_PP_SEQ_SPLIT_73 # define BOOST_PP_SEQ_SPLIT_75(x) (x) BOOST_PP_SEQ_SPLIT_74 # define BOOST_PP_SEQ_SPLIT_76(x) (x) BOOST_PP_SEQ_SPLIT_75 # define BOOST_PP_SEQ_SPLIT_77(x) (x) BOOST_PP_SEQ_SPLIT_76 # define BOOST_PP_SEQ_SPLIT_78(x) (x) BOOST_PP_SEQ_SPLIT_77 # define BOOST_PP_SEQ_SPLIT_79(x) (x) BOOST_PP_SEQ_SPLIT_78 # define BOOST_PP_SEQ_SPLIT_80(x) (x) BOOST_PP_SEQ_SPLIT_79 # define BOOST_PP_SEQ_SPLIT_81(x) (x) BOOST_PP_SEQ_SPLIT_80 # define BOOST_PP_SEQ_SPLIT_82(x) (x) BOOST_PP_SEQ_SPLIT_81 # define BOOST_PP_SEQ_SPLIT_83(x) (x) BOOST_PP_SEQ_SPLIT_82 # define BOOST_PP_SEQ_SPLIT_84(x) (x) BOOST_PP_SEQ_SPLIT_83 # define BOOST_PP_SEQ_SPLIT_85(x) (x) BOOST_PP_SEQ_SPLIT_84 # define BOOST_PP_SEQ_SPLIT_86(x) (x) BOOST_PP_SEQ_SPLIT_85 # define BOOST_PP_SEQ_SPLIT_87(x) (x) BOOST_PP_SEQ_SPLIT_86 # define BOOST_PP_SEQ_SPLIT_88(x) (x) BOOST_PP_SEQ_SPLIT_87 # define BOOST_PP_SEQ_SPLIT_89(x) (x) BOOST_PP_SEQ_SPLIT_88 # define BOOST_PP_SEQ_SPLIT_90(x) (x) BOOST_PP_SEQ_SPLIT_89 # define BOOST_PP_SEQ_SPLIT_91(x) (x) BOOST_PP_SEQ_SPLIT_90 # define BOOST_PP_SEQ_SPLIT_92(x) (x) BOOST_PP_SEQ_SPLIT_91 # define BOOST_PP_SEQ_SPLIT_93(x) (x) BOOST_PP_SEQ_SPLIT_92 # define BOOST_PP_SEQ_SPLIT_94(x) (x) BOOST_PP_SEQ_SPLIT_93 # define BOOST_PP_SEQ_SPLIT_95(x) (x) BOOST_PP_SEQ_SPLIT_94 # define BOOST_PP_SEQ_SPLIT_96(x) (x) BOOST_PP_SEQ_SPLIT_95 # define BOOST_PP_SEQ_SPLIT_97(x) (x) BOOST_PP_SEQ_SPLIT_96 # define BOOST_PP_SEQ_SPLIT_98(x) (x) BOOST_PP_SEQ_SPLIT_97 # define BOOST_PP_SEQ_SPLIT_99(x) (x) BOOST_PP_SEQ_SPLIT_98 # define BOOST_PP_SEQ_SPLIT_100(x) (x) BOOST_PP_SEQ_SPLIT_99 # define BOOST_PP_SEQ_SPLIT_101(x) (x) BOOST_PP_SEQ_SPLIT_100 # define BOOST_PP_SEQ_SPLIT_102(x) (x) BOOST_PP_SEQ_SPLIT_101 # define BOOST_PP_SEQ_SPLIT_103(x) (x) BOOST_PP_SEQ_SPLIT_102 # define BOOST_PP_SEQ_SPLIT_104(x) (x) BOOST_PP_SEQ_SPLIT_103 # define BOOST_PP_SEQ_SPLIT_105(x) (x) BOOST_PP_SEQ_SPLIT_104 # define BOOST_PP_SEQ_SPLIT_106(x) (x) BOOST_PP_SEQ_SPLIT_105 # define BOOST_PP_SEQ_SPLIT_107(x) (x) BOOST_PP_SEQ_SPLIT_106 # define BOOST_PP_SEQ_SPLIT_108(x) (x) BOOST_PP_SEQ_SPLIT_107 # define BOOST_PP_SEQ_SPLIT_109(x) (x) BOOST_PP_SEQ_SPLIT_108 # define BOOST_PP_SEQ_SPLIT_110(x) (x) BOOST_PP_SEQ_SPLIT_109 # define BOOST_PP_SEQ_SPLIT_111(x) (x) BOOST_PP_SEQ_SPLIT_110 # define BOOST_PP_SEQ_SPLIT_112(x) (x) BOOST_PP_SEQ_SPLIT_111 # define BOOST_PP_SEQ_SPLIT_113(x) (x) BOOST_PP_SEQ_SPLIT_112 # define BOOST_PP_SEQ_SPLIT_114(x) (x) BOOST_PP_SEQ_SPLIT_113 # define BOOST_PP_SEQ_SPLIT_115(x) (x) BOOST_PP_SEQ_SPLIT_114 # define BOOST_PP_SEQ_SPLIT_116(x) (x) BOOST_PP_SEQ_SPLIT_115 # define BOOST_PP_SEQ_SPLIT_117(x) (x) BOOST_PP_SEQ_SPLIT_116 # define BOOST_PP_SEQ_SPLIT_118(x) (x) BOOST_PP_SEQ_SPLIT_117 # define BOOST_PP_SEQ_SPLIT_119(x) (x) BOOST_PP_SEQ_SPLIT_118 # define BOOST_PP_SEQ_SPLIT_120(x) (x) BOOST_PP_SEQ_SPLIT_119 # define BOOST_PP_SEQ_SPLIT_121(x) (x) BOOST_PP_SEQ_SPLIT_120 # define BOOST_PP_SEQ_SPLIT_122(x) (x) BOOST_PP_SEQ_SPLIT_121 # define BOOST_PP_SEQ_SPLIT_123(x) (x) BOOST_PP_SEQ_SPLIT_122 # define BOOST_PP_SEQ_SPLIT_124(x) (x) BOOST_PP_SEQ_SPLIT_123 # define BOOST_PP_SEQ_SPLIT_125(x) (x) BOOST_PP_SEQ_SPLIT_124 # define BOOST_PP_SEQ_SPLIT_126(x) (x) BOOST_PP_SEQ_SPLIT_125 # define BOOST_PP_SEQ_SPLIT_127(x) (x) BOOST_PP_SEQ_SPLIT_126 # define BOOST_PP_SEQ_SPLIT_128(x) (x) BOOST_PP_SEQ_SPLIT_127 # define BOOST_PP_SEQ_SPLIT_129(x) (x) BOOST_PP_SEQ_SPLIT_128 # define BOOST_PP_SEQ_SPLIT_130(x) (x) BOOST_PP_SEQ_SPLIT_129 # define BOOST_PP_SEQ_SPLIT_131(x) (x) BOOST_PP_SEQ_SPLIT_130 # define BOOST_PP_SEQ_SPLIT_132(x) (x) BOOST_PP_SEQ_SPLIT_131 # define BOOST_PP_SEQ_SPLIT_133(x) (x) BOOST_PP_SEQ_SPLIT_132 # define BOOST_PP_SEQ_SPLIT_134(x) (x) BOOST_PP_SEQ_SPLIT_133 # define BOOST_PP_SEQ_SPLIT_135(x) (x) BOOST_PP_SEQ_SPLIT_134 # define BOOST_PP_SEQ_SPLIT_136(x) (x) BOOST_PP_SEQ_SPLIT_135 # define BOOST_PP_SEQ_SPLIT_137(x) (x) BOOST_PP_SEQ_SPLIT_136 # define BOOST_PP_SEQ_SPLIT_138(x) (x) BOOST_PP_SEQ_SPLIT_137 # define BOOST_PP_SEQ_SPLIT_139(x) (x) BOOST_PP_SEQ_SPLIT_138 # define BOOST_PP_SEQ_SPLIT_140(x) (x) BOOST_PP_SEQ_SPLIT_139 # define BOOST_PP_SEQ_SPLIT_141(x) (x) BOOST_PP_SEQ_SPLIT_140 # define BOOST_PP_SEQ_SPLIT_142(x) (x) BOOST_PP_SEQ_SPLIT_141 # define BOOST_PP_SEQ_SPLIT_143(x) (x) BOOST_PP_SEQ_SPLIT_142 # define BOOST_PP_SEQ_SPLIT_144(x) (x) BOOST_PP_SEQ_SPLIT_143 # define BOOST_PP_SEQ_SPLIT_145(x) (x) BOOST_PP_SEQ_SPLIT_144 # define BOOST_PP_SEQ_SPLIT_146(x) (x) BOOST_PP_SEQ_SPLIT_145 # define BOOST_PP_SEQ_SPLIT_147(x) (x) BOOST_PP_SEQ_SPLIT_146 # define BOOST_PP_SEQ_SPLIT_148(x) (x) BOOST_PP_SEQ_SPLIT_147 # define BOOST_PP_SEQ_SPLIT_149(x) (x) BOOST_PP_SEQ_SPLIT_148 # define BOOST_PP_SEQ_SPLIT_150(x) (x) BOOST_PP_SEQ_SPLIT_149 # define BOOST_PP_SEQ_SPLIT_151(x) (x) BOOST_PP_SEQ_SPLIT_150 # define BOOST_PP_SEQ_SPLIT_152(x) (x) BOOST_PP_SEQ_SPLIT_151 # define BOOST_PP_SEQ_SPLIT_153(x) (x) BOOST_PP_SEQ_SPLIT_152 # define BOOST_PP_SEQ_SPLIT_154(x) (x) BOOST_PP_SEQ_SPLIT_153 # define BOOST_PP_SEQ_SPLIT_155(x) (x) BOOST_PP_SEQ_SPLIT_154 # define BOOST_PP_SEQ_SPLIT_156(x) (x) BOOST_PP_SEQ_SPLIT_155 # define BOOST_PP_SEQ_SPLIT_157(x) (x) BOOST_PP_SEQ_SPLIT_156 # define BOOST_PP_SEQ_SPLIT_158(x) (x) BOOST_PP_SEQ_SPLIT_157 # define BOOST_PP_SEQ_SPLIT_159(x) (x) BOOST_PP_SEQ_SPLIT_158 # define BOOST_PP_SEQ_SPLIT_160(x) (x) BOOST_PP_SEQ_SPLIT_159 # define BOOST_PP_SEQ_SPLIT_161(x) (x) BOOST_PP_SEQ_SPLIT_160 # define BOOST_PP_SEQ_SPLIT_162(x) (x) BOOST_PP_SEQ_SPLIT_161 # define BOOST_PP_SEQ_SPLIT_163(x) (x) BOOST_PP_SEQ_SPLIT_162 # define BOOST_PP_SEQ_SPLIT_164(x) (x) BOOST_PP_SEQ_SPLIT_163 # define BOOST_PP_SEQ_SPLIT_165(x) (x) BOOST_PP_SEQ_SPLIT_164 # define BOOST_PP_SEQ_SPLIT_166(x) (x) BOOST_PP_SEQ_SPLIT_165 # define BOOST_PP_SEQ_SPLIT_167(x) (x) BOOST_PP_SEQ_SPLIT_166 # define BOOST_PP_SEQ_SPLIT_168(x) (x) BOOST_PP_SEQ_SPLIT_167 # define BOOST_PP_SEQ_SPLIT_169(x) (x) BOOST_PP_SEQ_SPLIT_168 # define BOOST_PP_SEQ_SPLIT_170(x) (x) BOOST_PP_SEQ_SPLIT_169 # define BOOST_PP_SEQ_SPLIT_171(x) (x) BOOST_PP_SEQ_SPLIT_170 # define BOOST_PP_SEQ_SPLIT_172(x) (x) BOOST_PP_SEQ_SPLIT_171 # define BOOST_PP_SEQ_SPLIT_173(x) (x) BOOST_PP_SEQ_SPLIT_172 # define BOOST_PP_SEQ_SPLIT_174(x) (x) BOOST_PP_SEQ_SPLIT_173 # define BOOST_PP_SEQ_SPLIT_175(x) (x) BOOST_PP_SEQ_SPLIT_174 # define BOOST_PP_SEQ_SPLIT_176(x) (x) BOOST_PP_SEQ_SPLIT_175 # define BOOST_PP_SEQ_SPLIT_177(x) (x) BOOST_PP_SEQ_SPLIT_176 # define BOOST_PP_SEQ_SPLIT_178(x) (x) BOOST_PP_SEQ_SPLIT_177 # define BOOST_PP_SEQ_SPLIT_179(x) (x) BOOST_PP_SEQ_SPLIT_178 # define BOOST_PP_SEQ_SPLIT_180(x) (x) BOOST_PP_SEQ_SPLIT_179 # define BOOST_PP_SEQ_SPLIT_181(x) (x) BOOST_PP_SEQ_SPLIT_180 # define BOOST_PP_SEQ_SPLIT_182(x) (x) BOOST_PP_SEQ_SPLIT_181 # define BOOST_PP_SEQ_SPLIT_183(x) (x) BOOST_PP_SEQ_SPLIT_182 # define BOOST_PP_SEQ_SPLIT_184(x) (x) BOOST_PP_SEQ_SPLIT_183 # define BOOST_PP_SEQ_SPLIT_185(x) (x) BOOST_PP_SEQ_SPLIT_184 # define BOOST_PP_SEQ_SPLIT_186(x) (x) BOOST_PP_SEQ_SPLIT_185 # define BOOST_PP_SEQ_SPLIT_187(x) (x) BOOST_PP_SEQ_SPLIT_186 # define BOOST_PP_SEQ_SPLIT_188(x) (x) BOOST_PP_SEQ_SPLIT_187 # define BOOST_PP_SEQ_SPLIT_189(x) (x) BOOST_PP_SEQ_SPLIT_188 # define BOOST_PP_SEQ_SPLIT_190(x) (x) BOOST_PP_SEQ_SPLIT_189 # define BOOST_PP_SEQ_SPLIT_191(x) (x) BOOST_PP_SEQ_SPLIT_190 # define BOOST_PP_SEQ_SPLIT_192(x) (x) BOOST_PP_SEQ_SPLIT_191 # define BOOST_PP_SEQ_SPLIT_193(x) (x) BOOST_PP_SEQ_SPLIT_192 # define BOOST_PP_SEQ_SPLIT_194(x) (x) BOOST_PP_SEQ_SPLIT_193 # define BOOST_PP_SEQ_SPLIT_195(x) (x) BOOST_PP_SEQ_SPLIT_194 # define BOOST_PP_SEQ_SPLIT_196(x) (x) BOOST_PP_SEQ_SPLIT_195 # define BOOST_PP_SEQ_SPLIT_197(x) (x) BOOST_PP_SEQ_SPLIT_196 # define BOOST_PP_SEQ_SPLIT_198(x) (x) BOOST_PP_SEQ_SPLIT_197 # define BOOST_PP_SEQ_SPLIT_199(x) (x) BOOST_PP_SEQ_SPLIT_198 # define BOOST_PP_SEQ_SPLIT_200(x) (x) BOOST_PP_SEQ_SPLIT_199 # define BOOST_PP_SEQ_SPLIT_201(x) (x) BOOST_PP_SEQ_SPLIT_200 # define BOOST_PP_SEQ_SPLIT_202(x) (x) BOOST_PP_SEQ_SPLIT_201 # define BOOST_PP_SEQ_SPLIT_203(x) (x) BOOST_PP_SEQ_SPLIT_202 # define BOOST_PP_SEQ_SPLIT_204(x) (x) BOOST_PP_SEQ_SPLIT_203 # define BOOST_PP_SEQ_SPLIT_205(x) (x) BOOST_PP_SEQ_SPLIT_204 # define BOOST_PP_SEQ_SPLIT_206(x) (x) BOOST_PP_SEQ_SPLIT_205 # define BOOST_PP_SEQ_SPLIT_207(x) (x) BOOST_PP_SEQ_SPLIT_206 # define BOOST_PP_SEQ_SPLIT_208(x) (x) BOOST_PP_SEQ_SPLIT_207 # define BOOST_PP_SEQ_SPLIT_209(x) (x) BOOST_PP_SEQ_SPLIT_208 # define BOOST_PP_SEQ_SPLIT_210(x) (x) BOOST_PP_SEQ_SPLIT_209 # define BOOST_PP_SEQ_SPLIT_211(x) (x) BOOST_PP_SEQ_SPLIT_210 # define BOOST_PP_SEQ_SPLIT_212(x) (x) BOOST_PP_SEQ_SPLIT_211 # define BOOST_PP_SEQ_SPLIT_213(x) (x) BOOST_PP_SEQ_SPLIT_212 # define BOOST_PP_SEQ_SPLIT_214(x) (x) BOOST_PP_SEQ_SPLIT_213 # define BOOST_PP_SEQ_SPLIT_215(x) (x) BOOST_PP_SEQ_SPLIT_214 # define BOOST_PP_SEQ_SPLIT_216(x) (x) BOOST_PP_SEQ_SPLIT_215 # define BOOST_PP_SEQ_SPLIT_217(x) (x) BOOST_PP_SEQ_SPLIT_216 # define BOOST_PP_SEQ_SPLIT_218(x) (x) BOOST_PP_SEQ_SPLIT_217 # define BOOST_PP_SEQ_SPLIT_219(x) (x) BOOST_PP_SEQ_SPLIT_218 # define BOOST_PP_SEQ_SPLIT_220(x) (x) BOOST_PP_SEQ_SPLIT_219 # define BOOST_PP_SEQ_SPLIT_221(x) (x) BOOST_PP_SEQ_SPLIT_220 # define BOOST_PP_SEQ_SPLIT_222(x) (x) BOOST_PP_SEQ_SPLIT_221 # define BOOST_PP_SEQ_SPLIT_223(x) (x) BOOST_PP_SEQ_SPLIT_222 # define BOOST_PP_SEQ_SPLIT_224(x) (x) BOOST_PP_SEQ_SPLIT_223 # define BOOST_PP_SEQ_SPLIT_225(x) (x) BOOST_PP_SEQ_SPLIT_224 # define BOOST_PP_SEQ_SPLIT_226(x) (x) BOOST_PP_SEQ_SPLIT_225 # define BOOST_PP_SEQ_SPLIT_227(x) (x) BOOST_PP_SEQ_SPLIT_226 # define BOOST_PP_SEQ_SPLIT_228(x) (x) BOOST_PP_SEQ_SPLIT_227 # define BOOST_PP_SEQ_SPLIT_229(x) (x) BOOST_PP_SEQ_SPLIT_228 # define BOOST_PP_SEQ_SPLIT_230(x) (x) BOOST_PP_SEQ_SPLIT_229 # define BOOST_PP_SEQ_SPLIT_231(x) (x) BOOST_PP_SEQ_SPLIT_230 # define BOOST_PP_SEQ_SPLIT_232(x) (x) BOOST_PP_SEQ_SPLIT_231 # define BOOST_PP_SEQ_SPLIT_233(x) (x) BOOST_PP_SEQ_SPLIT_232 # define BOOST_PP_SEQ_SPLIT_234(x) (x) BOOST_PP_SEQ_SPLIT_233 # define BOOST_PP_SEQ_SPLIT_235(x) (x) BOOST_PP_SEQ_SPLIT_234 # define BOOST_PP_SEQ_SPLIT_236(x) (x) BOOST_PP_SEQ_SPLIT_235 # define BOOST_PP_SEQ_SPLIT_237(x) (x) BOOST_PP_SEQ_SPLIT_236 # define BOOST_PP_SEQ_SPLIT_238(x) (x) BOOST_PP_SEQ_SPLIT_237 # define BOOST_PP_SEQ_SPLIT_239(x) (x) BOOST_PP_SEQ_SPLIT_238 # define BOOST_PP_SEQ_SPLIT_240(x) (x) BOOST_PP_SEQ_SPLIT_239 # define BOOST_PP_SEQ_SPLIT_241(x) (x) BOOST_PP_SEQ_SPLIT_240 # define BOOST_PP_SEQ_SPLIT_242(x) (x) BOOST_PP_SEQ_SPLIT_241 # define BOOST_PP_SEQ_SPLIT_243(x) (x) BOOST_PP_SEQ_SPLIT_242 # define BOOST_PP_SEQ_SPLIT_244(x) (x) BOOST_PP_SEQ_SPLIT_243 # define BOOST_PP_SEQ_SPLIT_245(x) (x) BOOST_PP_SEQ_SPLIT_244 # define BOOST_PP_SEQ_SPLIT_246(x) (x) BOOST_PP_SEQ_SPLIT_245 # define BOOST_PP_SEQ_SPLIT_247(x) (x) BOOST_PP_SEQ_SPLIT_246 # define BOOST_PP_SEQ_SPLIT_248(x) (x) BOOST_PP_SEQ_SPLIT_247 # define BOOST_PP_SEQ_SPLIT_249(x) (x) BOOST_PP_SEQ_SPLIT_248 # define BOOST_PP_SEQ_SPLIT_250(x) (x) BOOST_PP_SEQ_SPLIT_249 # define BOOST_PP_SEQ_SPLIT_251(x) (x) BOOST_PP_SEQ_SPLIT_250 # define BOOST_PP_SEQ_SPLIT_252(x) (x) BOOST_PP_SEQ_SPLIT_251 # define BOOST_PP_SEQ_SPLIT_253(x) (x) BOOST_PP_SEQ_SPLIT_252 # define BOOST_PP_SEQ_SPLIT_254(x) (x) BOOST_PP_SEQ_SPLIT_253 # define BOOST_PP_SEQ_SPLIT_255(x) (x) BOOST_PP_SEQ_SPLIT_254 # define BOOST_PP_SEQ_SPLIT_256(x) (x) BOOST_PP_SEQ_SPLIT_255 # # else # # include <boost/preprocessor/config/limits.hpp> # # if BOOST_PP_LIMIT_SEQ == 256 # include <boost/preprocessor/seq/detail/limits/split_256.hpp> # elif BOOST_PP_LIMIT_SEQ == 512 # include <boost/preprocessor/seq/detail/limits/split_256.hpp> # include <boost/preprocessor/seq/detail/limits/split_512.hpp> # elif BOOST_PP_LIMIT_SEQ == 1024 # include <boost/preprocessor/seq/detail/limits/split_256.hpp> # include <boost/preprocessor/seq/detail/limits/split_512.hpp> # include <boost/preprocessor/seq/detail/limits/split_1024.hpp> # else # error Incorrect value for the BOOST_PP_LIMIT_SEQ limit # endif # # endif # # endif
// // detail/dev_poll_reactor.hpp // ~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2013 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // 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) // #ifndef BOOST_ASIO_DETAIL_DEV_POLL_REACTOR_HPP #define BOOST_ASIO_DETAIL_DEV_POLL_REACTOR_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #if defined(BOOST_ASIO_HAS_DEV_POLL) #include <cstddef> #include <vector> #include <sys/devpoll.h> #include <boost/asio/detail/dev_poll_reactor_fwd.hpp> #include <boost/asio/detail/hash_map.hpp> #include <boost/asio/detail/limits.hpp> #include <boost/asio/detail/mutex.hpp> #include <boost/asio/detail/op_queue.hpp> #include <boost/asio/detail/reactor_op.hpp> #include <boost/asio/detail/reactor_op_queue.hpp> #include <boost/asio/detail/select_interrupter.hpp> #include <boost/asio/detail/socket_types.hpp> #include <boost/asio/detail/timer_queue_base.hpp> #include <boost/asio/detail/timer_queue_fwd.hpp> #include <boost/asio/detail/timer_queue_set.hpp> #include <boost/asio/detail/wait_op.hpp> #include <boost/asio/io_service.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { namespace asio { namespace detail { class dev_poll_reactor : public boost::asio::detail::service_base<dev_poll_reactor> { public: enum op_types { read_op = 0, write_op = 1, connect_op = 1, except_op = 2, max_ops = 3 }; // Per-descriptor data. struct per_descriptor_data { }; // Constructor. BOOST_ASIO_DECL dev_poll_reactor(boost::asio::io_service& io_service); // Destructor. BOOST_ASIO_DECL ~dev_poll_reactor(); // Destroy all user-defined handler objects owned by the service. BOOST_ASIO_DECL void shutdown_service(); // Recreate internal descriptors following a fork. BOOST_ASIO_DECL void fork_service( boost::asio::io_service::fork_event fork_ev); // Initialise the task. BOOST_ASIO_DECL void init_task(); // Register a socket with the reactor. Returns 0 on success, system error // code on failure. BOOST_ASIO_DECL int register_descriptor(socket_type, per_descriptor_data&); // Register a descriptor with an associated single operation. Returns 0 on // success, system error code on failure. BOOST_ASIO_DECL int register_internal_descriptor( int op_type, socket_type descriptor, per_descriptor_data& descriptor_data, reactor_op* op); // Move descriptor registration from one descriptor_data object to another. BOOST_ASIO_DECL void move_descriptor(socket_type descriptor, per_descriptor_data& target_descriptor_data, per_descriptor_data& source_descriptor_data); // Post a reactor operation for immediate completion. void post_immediate_completion(reactor_op* op, bool is_continuation) { io_service_.post_immediate_completion(op, is_continuation); } // Start a new operation. The reactor operation will be performed when the // given descriptor is flagged as ready, or an error has occurred. BOOST_ASIO_DECL void start_op(int op_type, socket_type descriptor, per_descriptor_data&, reactor_op* op, bool is_continuation, bool allow_speculative); // Cancel all operations associated with the given descriptor. The // handlers associated with the descriptor will be invoked with the // operation_aborted error. BOOST_ASIO_DECL void cancel_ops(socket_type descriptor, per_descriptor_data&); // Cancel any operations that are running against the descriptor and remove // its registration from the reactor. BOOST_ASIO_DECL void deregister_descriptor(socket_type descriptor, per_descriptor_data&, bool closing); // Cancel any operations that are running against the descriptor and remove // its registration from the reactor. BOOST_ASIO_DECL void deregister_internal_descriptor( socket_type descriptor, per_descriptor_data&); // Add a new timer queue to the reactor. template <typename Time_Traits> void add_timer_queue(timer_queue<Time_Traits>& queue); // Remove a timer queue from the reactor. template <typename Time_Traits> void remove_timer_queue(timer_queue<Time_Traits>& queue); // Schedule a new operation in the given timer queue to expire at the // specified absolute time. template <typename Time_Traits> void schedule_timer(timer_queue<Time_Traits>& queue, const typename Time_Traits::time_type& time, typename timer_queue<Time_Traits>::per_timer_data& timer, wait_op* op); // Cancel the timer operations associated with the given token. Returns the // number of operations that have been posted or dispatched. template <typename Time_Traits> std::size_t cancel_timer(timer_queue<Time_Traits>& queue, typename timer_queue<Time_Traits>::per_timer_data& timer, std::size_t max_cancelled = (std::numeric_limits<std::size_t>::max)()); // Run /dev/poll once until interrupted or events are ready to be dispatched. BOOST_ASIO_DECL void run(bool block, op_queue<operation>& ops); // Interrupt the select loop. BOOST_ASIO_DECL void interrupt(); private: // Create the /dev/poll file descriptor. Throws an exception if the descriptor // cannot be created. BOOST_ASIO_DECL static int do_dev_poll_create(); // Helper function to add a new timer queue. BOOST_ASIO_DECL void do_add_timer_queue(timer_queue_base& queue); // Helper function to remove a timer queue. BOOST_ASIO_DECL void do_remove_timer_queue(timer_queue_base& queue); // Get the timeout value for the /dev/poll DP_POLL operation. The timeout // value is returned as a number of milliseconds. A return value of -1 // indicates that the poll should block indefinitely. BOOST_ASIO_DECL int get_timeout(); // Cancel all operations associated with the given descriptor. The do_cancel // function of the handler objects will be invoked. This function does not // acquire the dev_poll_reactor's mutex. BOOST_ASIO_DECL void cancel_ops_unlocked(socket_type descriptor, const boost::system::error_code& ec); // Helper class used to reregister descriptors after a fork. class fork_helper; friend class fork_helper; // Add a pending event entry for the given descriptor. BOOST_ASIO_DECL ::pollfd& add_pending_event_change(int descriptor); // The io_service implementation used to post completions. io_service_impl& io_service_; // Mutex to protect access to internal data. boost::asio::detail::mutex mutex_; // The /dev/poll file descriptor. int dev_poll_fd_; // Vector of /dev/poll events waiting to be written to the descriptor. std::vector< ::pollfd> pending_event_changes_; // Hash map to associate a descriptor with a pending event change index. hash_map<int, std::size_t> pending_event_change_index_; // The interrupter is used to break a blocking DP_POLL operation. select_interrupter interrupter_; // The queues of read, write and except operations. reactor_op_queue<socket_type> op_queue_[max_ops]; // The timer queues. timer_queue_set timer_queues_; // Whether the service has been shut down. bool shutdown_; }; } // namespace detail } // namespace asio } // namespace boost #include <boost/asio/detail/pop_options.hpp> #include <boost/asio/detail/impl/dev_poll_reactor.hpp> #if defined(BOOST_ASIO_HEADER_ONLY) # include <boost/asio/detail/impl/dev_poll_reactor.ipp> #endif // defined(BOOST_ASIO_HEADER_ONLY) #endif // defined(BOOST_ASIO_HAS_DEV_POLL) #endif // BOOST_ASIO_DETAIL_DEV_POLL_REACTOR_HPP
/* * Copyright (c) 2008-2015 Emmanuel Dupuy * This program is made available under the terms of the GPLv3 License. */ package org.jd.gui.service.type; import groovyjarjarasm.asm.ClassReader; import groovyjarjarasm.asm.Opcodes; import groovyjarjarasm.asm.tree.ClassNode; import groovyjarjarasm.asm.tree.FieldNode; import groovyjarjarasm.asm.tree.InnerClassNode; import groovyjarjarasm.asm.tree.MethodNode; import org.jd.gui.api.API; import org.jd.gui.api.model.Container; import org.jd.gui.api.model.Type; import javax.swing.*; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.*; public class ClassFileTypeFactoryProvider extends AbstractTypeFactoryProvider { static { // Early class loading JavaType.class.getName(); } // Create cache protected Cache<URI, JavaType> cache = new Cache(); /** * @return local + optional external selectors */ public String[] getSelectors() { List<String> externalSelectors = getExternalSelectors(); if (externalSelectors == null) { return new String[] { "*:file:*.class" }; } else { int size = externalSelectors.size(); String[] selectors = new String[size+1]; externalSelectors.toArray(selectors); selectors[size] = "*:file:*.class"; return selectors; } } public Collection<Type> make(API api, Container.Entry entry) { return Collections.singletonList(make(api, entry, null)); } public Type make(API api, Container.Entry entry, String fragment) { URI key = entry.getUri(); if (cache.containsKey(key)) { return cache.get(key); } else { JavaType type; try (InputStream is = entry.getInputStream()) { ClassReader classReader = new ClassReader(is); if ((fragment != null) && (fragment.length() > 0)) { // Search type name in fragment. URI format : see jd.gui.api.feature.UriOpener int index = fragment.indexOf('-'); if (index != -1) { // Keep type name only fragment = fragment.substring(0, index); } if (!classReader.getClassName().equals(fragment)) { // Search entry for type name String entryTypePath = classReader.getClassName() + ".class"; String fragmentTypePath = fragment + ".class"; while (true) { if (entry.getPath().endsWith(entryTypePath)) { // Entry path ends with the internal class name String pathToFound = entry.getPath().substring(0, entry.getPath().length() - entryTypePath.length()) + fragmentTypePath; Container.Entry entryFound = null; for (Container.Entry e : entry.getParent().getChildren()) { if (e.getPath().equals(pathToFound)) { entryFound = e; break; } } if (entryFound == null) return null; entry = entryFound; try (InputStream is2 = entry.getInputStream()) { classReader = new ClassReader(is2); } catch (IOException ignore) { return null; } break; } // Truncated path ? Cut first package name and retry int firstPackageSeparatorIndex = entryTypePath.indexOf('/'); if (firstPackageSeparatorIndex == -1) { // Nothing to cut -> Stop return null; } entryTypePath = entryTypePath.substring(firstPackageSeparatorIndex + 1); fragmentTypePath = fragmentTypePath.substring(fragmentTypePath.indexOf('/') + 1); } } } type = new JavaType(entry, classReader, -1); } catch (IOException ignore) { type = null; } cache.put(key, type); return type; } } static class JavaType implements Type { protected ClassNode classNode; protected Container.Entry entry; protected int access; protected String name; protected String superName; protected String outerName; protected String displayTypeName; protected String displayInnerTypeName; protected String displayPackageName; protected List<Type> innerTypes = null; protected List<Type.Field> fields = null; protected List<Type.Method> methods = null; @SuppressWarnings("unchecked") protected JavaType(Container.Entry entry, ClassReader classReader, int outerAccess) { this.classNode = new ClassNode(); this.entry = entry; classReader.accept(classNode, ClassReader.SKIP_CODE|ClassReader.SKIP_DEBUG|ClassReader.SKIP_FRAMES); this.access = (outerAccess == -1) ? classNode.access : outerAccess; this.name = classNode.name; this.superName = ((access & Opcodes.ACC_INTERFACE) != 0) && "java/lang/Object".equals(classNode.superName) ? null : classNode.superName; this.outerName = null; this.displayInnerTypeName = null; int indexDollar = name.lastIndexOf('$'); if (indexDollar != -1) { int indexSeparator = name.lastIndexOf('/'); if (indexDollar > indexSeparator) { for (final InnerClassNode innerClassNode : (List<InnerClassNode>)classNode.innerClasses) { if (name.equals(innerClassNode.name)) { // Inner class path found if (innerClassNode.outerName != null) { this.outerName = innerClassNode.outerName; this.displayInnerTypeName = this.name.substring(this.outerName.length() + 1); } } } } } int lastPackageSeparatorIndex = name.lastIndexOf('/'); if (lastPackageSeparatorIndex == -1) { this.displayPackageName = ""; this.displayTypeName = (this.outerName == null) ? this.name : null; } else { this.displayPackageName = this.name.substring(0, lastPackageSeparatorIndex).replace('/', '.'); this.displayTypeName = (this.outerName == null) ? this.name.substring(lastPackageSeparatorIndex+1) : null; } } public int getFlags() { return access; } public String getName() { return name; } public String getSuperName() { return superName; } public String getOuterName() { return outerName; } public String getDisplayPackageName() { return displayPackageName; } public String getDisplayTypeName() { if (displayTypeName == null) { displayTypeName = getDisplayTypeName(outerName, displayPackageName.length()) + '.' + displayInnerTypeName; } return displayTypeName; } @SuppressWarnings("unchecked") protected String getDisplayTypeName(String name, int packageLength) { int indexDollar = name.lastIndexOf('$'); if (indexDollar > packageLength) { Container.Entry outerEntry = getEntry(name); if (outerEntry != null) { try (InputStream is = outerEntry.getInputStream()) { ClassReader classReader = new ClassReader(is); ClassNode classNode = new ClassNode(); classReader.accept(classNode, ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES); for (final InnerClassNode innerClassNode : (List<InnerClassNode>)classNode.innerClasses) { if (name.equals(innerClassNode.name)) { // Inner class path found => Recursive call return getDisplayTypeName(innerClassNode.outerName, packageLength) + '.' + innerClassNode.innerName; } } } catch (IOException ignore) { } } } return packageLength > 0 ? name.substring(packageLength+1) : name; } public String getDisplayInnerTypeName() { return displayInnerTypeName; } public Icon getIcon() { return getTypeIcon(access); } @SuppressWarnings("unchecked") public List<Type> getInnerTypes() { if (innerTypes == null) { innerTypes = new ArrayList<>(classNode.innerClasses.size()); for (final InnerClassNode innerClassNode : (List<InnerClassNode>)classNode.innerClasses) { if (((innerClassNode.access & (Opcodes.ACC_SYNTHETIC|Opcodes.ACC_BRIDGE)) == 0) && this.name.equals(innerClassNode.outerName)) { Container.Entry innerEntry = getEntry(innerClassNode.name); if (innerEntry != null) { try (InputStream is = innerEntry.getInputStream()) { ClassReader classReader = new ClassReader(is); innerTypes.add(new JavaType(innerEntry, classReader, innerClassNode.access)); } catch (IOException ignore) { } } } } } return innerTypes; } protected Container.Entry getEntry(String typeName) { String pathToFound = typeName + ".class"; for (Container.Entry e : entry.getParent().getChildren()) { if (e.getPath().equals(pathToFound)) { return e; } } return null; } @SuppressWarnings("unchecked") public List<Type.Field> getFields() { if (fields == null) { fields = new ArrayList<>(classNode.fields.size()); for (final FieldNode fieldNode : (List<FieldNode>)classNode.fields) { if ((fieldNode.access & (Opcodes.ACC_SYNTHETIC|Opcodes.ACC_ENUM)) == 0) { fields.add(new Type.Field() { public int getFlags() { return fieldNode.access; } public String getName() { return fieldNode.name; } public String getDescriptor() { return fieldNode.desc; } public Icon getIcon() { return getFieldIcon(fieldNode.access); } public String getDisplayName() { StringBuffer sb = new StringBuffer(); sb.append(fieldNode.name).append(" : "); writeSignature(sb, fieldNode.desc, fieldNode.desc.length(), 0, false); return sb.toString(); } }); } } } return fields; } @SuppressWarnings("unchecked") public List<Type.Method> getMethods() { if (methods == null) { methods = new ArrayList<>(classNode.methods.size()); for (final MethodNode methodNode : (List<MethodNode>)classNode.methods) { if ((methodNode.access & (Opcodes.ACC_SYNTHETIC|Opcodes.ACC_ENUM|Opcodes.ACC_BRIDGE)) == 0) { methods.add(new Type.Method() { public int getFlags() { return methodNode.access; } public String getName() { return methodNode.name; } public String getDescriptor() { return methodNode.desc; } public Icon getIcon() { return getMethodIcon(methodNode.access); } public String getDisplayName() { String constructorName = displayInnerTypeName; boolean isInnerClass = (constructorName != null); if (constructorName == null) constructorName = getDisplayTypeName(); StringBuffer sb = new StringBuffer(); writeMethodSignature(sb, access, methodNode.access, isInnerClass, constructorName, methodNode.name, methodNode.desc); return sb.toString(); } }); } } } return methods; } } }
# Copyright 2016 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. # ============================================================================== """Sparsemax op.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import nn __all__ = ["sparsemax"] def sparsemax(logits, name=None): """Computes sparsemax activations [1]. For each batch `i` and class `j` we have $$sparsemax[i, j] = max(logits[i, j] - tau(logits[i, :]), 0)$$ [1]: https://arxiv.org/abs/1602.02068 Args: logits: A `Tensor`. Must be one of the following types: `half`, `float32`, `float64`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `logits`. """ with ops.name_scope(name, "sparsemax", [logits]) as name: logits = ops.convert_to_tensor(logits, name="logits") obs = array_ops.shape(logits)[0] dims = array_ops.shape(logits)[1] # In the paper, they call the logits z. # The mean(logits) can be substracted from logits to make the algorithm # more numerically stable. the instability in this algorithm comes mostly # from the z_cumsum. Substacting the mean will cause z_cumsum to be close # to zero. However, in practise the numerical instability issues are very # minor and substacting the mean causes extra issues with inf and nan # input. z = logits # sort z z_sorted, _ = nn.top_k(z, k=dims) # calculate k(z) z_cumsum = math_ops.cumsum(z_sorted, axis=1) k = math_ops.range( 1, math_ops.cast(dims, logits.dtype) + 1, dtype=logits.dtype) z_check = 1 + k * z_sorted > z_cumsum # because the z_check vector is always [1,1,...1,0,0,...0] finding the # (index + 1) of the last `1` is the same as just summing the number of 1. k_z = math_ops.reduce_sum(math_ops.cast(z_check, dtypes.int32), axis=1) # calculate tau(z) # If there are inf values or all values are -inf, the k_z will be zero, # this is mathematically invalid and will also cause the gather_nd to fail. # Prevent this issue for now by setting k_z = 1 if k_z = 0, this is then # fixed later (see p_safe) by returning p = nan. This results in the same # behavior as softmax. k_z_safe = math_ops.maximum(k_z, 1) indices = array_ops.stack([math_ops.range(0, obs), k_z_safe - 1], axis=1) tau_sum = array_ops.gather_nd(z_cumsum, indices) tau_z = (tau_sum - 1) / math_ops.cast(k_z, logits.dtype) # calculate p p = math_ops.maximum( math_ops.cast(0, logits.dtype), z - tau_z[:, array_ops.newaxis]) # If k_z = 0 or if z = nan, then the input is invalid p_safe = array_ops.where( math_ops.logical_or( math_ops.equal(k_z, 0), math_ops.is_nan(z_cumsum[:, -1])), array_ops.fill([obs, dims], math_ops.cast(float("nan"), logits.dtype)), p) return p_safe
/** * 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.camel.component.netty4; import java.math.BigInteger; import java.security.Principal; import javax.net.ssl.SSLPeerUnverifiedException; import javax.net.ssl.SSLSession; import javax.security.cert.X509Certificate; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.ssl.SslHandler; import org.apache.camel.AsyncEndpoint; import org.apache.camel.Consumer; import org.apache.camel.Exchange; import org.apache.camel.Message; import org.apache.camel.Processor; import org.apache.camel.Producer; import org.apache.camel.impl.DefaultEndpoint; import org.apache.camel.impl.SynchronousDelegateProducer; import org.apache.camel.spi.UriEndpoint; import org.apache.camel.spi.UriParam; import org.apache.camel.util.ObjectHelper; /** * Socket level networking using TCP or UDP with the Netty 4.x library. */ @UriEndpoint(scheme = "netty4", title = "Netty4", syntax = "netty4:protocol:host:port", consumerClass = NettyConsumer.class, label = "networking,tcp,udp") public class NettyEndpoint extends DefaultEndpoint implements AsyncEndpoint { @UriParam private NettyConfiguration configuration; @UriParam(label = "advanced", javaType = "org.apache.camel.component.netty4.NettyServerBootstrapConfiguration", description = "To use a custom configured NettyServerBootstrapConfiguration for configuring this endpoint.") private Object bootstrapConfiguration; // to include in component docs as NettyServerBootstrapConfiguration is a @UriParams class public NettyEndpoint(String endpointUri, NettyComponent component, NettyConfiguration configuration) { super(endpointUri, component); this.configuration = configuration; } public Consumer createConsumer(Processor processor) throws Exception { Consumer answer = new NettyConsumer(this, processor, configuration); configureConsumer(answer); return answer; } public Producer createProducer() throws Exception { Producer answer = new NettyProducer(this, configuration); if (isSynchronous()) { return new SynchronousDelegateProducer(answer); } else { return answer; } } public Exchange createExchange(ChannelHandlerContext ctx, Object message) throws Exception { Exchange exchange = createExchange(); updateMessageHeader(exchange.getIn(), ctx); NettyPayloadHelper.setIn(exchange, message); return exchange; } public boolean isSingleton() { return true; } @Override public NettyComponent getComponent() { return (NettyComponent) super.getComponent(); } public NettyConfiguration getConfiguration() { return configuration; } public void setConfiguration(NettyConfiguration configuration) { this.configuration = configuration; } @Override protected String createEndpointUri() { ObjectHelper.notNull(configuration, "configuration"); return "netty4:" + getConfiguration().getProtocol() + "://" + getConfiguration().getHost() + ":" + getConfiguration().getPort(); } protected SSLSession getSSLSession(ChannelHandlerContext ctx) { final SslHandler sslHandler = ctx.pipeline().get(SslHandler.class); SSLSession sslSession = null; if (sslHandler != null) { sslSession = sslHandler.engine().getSession(); } return sslSession; } protected void updateMessageHeader(Message in, ChannelHandlerContext ctx) { in.setHeader(NettyConstants.NETTY_CHANNEL_HANDLER_CONTEXT, ctx); in.setHeader(NettyConstants.NETTY_REMOTE_ADDRESS, ctx.channel().remoteAddress()); in.setHeader(NettyConstants.NETTY_LOCAL_ADDRESS, ctx.channel().localAddress()); if (configuration.isSsl()) { // setup the SslSession header SSLSession sslSession = getSSLSession(ctx); in.setHeader(NettyConstants.NETTY_SSL_SESSION, sslSession); // enrich headers with details from the client certificate if option is enabled if (configuration.isSslClientCertHeaders()) { enrichWithClientCertInformation(sslSession, in); } } } /** * Enriches the message with client certificate details such as subject name, serial number etc. * <p/> * If the certificate is unverified then the headers is not enriched. * * @param sslSession the SSL session * @param message the message to enrich */ protected void enrichWithClientCertInformation(SSLSession sslSession, Message message) { try { X509Certificate[] certificates = sslSession.getPeerCertificateChain(); if (certificates != null && certificates.length > 0) { X509Certificate cert = certificates[0]; Principal subject = cert.getSubjectDN(); if (subject != null) { message.setHeader(NettyConstants.NETTY_SSL_CLIENT_CERT_SUBJECT_NAME, subject.getName()); } Principal issuer = cert.getIssuerDN(); if (issuer != null) { message.setHeader(NettyConstants.NETTY_SSL_CLIENT_CERT_ISSUER_NAME, issuer.getName()); } BigInteger serial = cert.getSerialNumber(); if (serial != null) { message.setHeader(NettyConstants.NETTY_SSL_CLIENT_CERT_SERIAL_NO, serial.toString()); } message.setHeader(NettyConstants.NETTY_SSL_CLIENT_CERT_NOT_BEFORE, cert.getNotBefore()); message.setHeader(NettyConstants.NETTY_SSL_CLIENT_CERT_NOT_AFTER, cert.getNotAfter()); } } catch (SSLPeerUnverifiedException e) { // ignore } } }
/* * Zed Attack Proxy (ZAP) and its related class files. * * ZAP is an HTTP/HTTPS proxy for assessing web application security. * * 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.zaproxy.zap.extension.script; import java.io.File; import java.util.ArrayList; import java.util.List; import org.parosproxy.paros.Constant; import org.zaproxy.zap.view.AbstractMultipleOptionsBaseTableModel; public class OptionsScriptTableModel extends AbstractMultipleOptionsBaseTableModel<File> { private static final long serialVersionUID = 1L; private static final String[] COLUMN_NAMES = { Constant.messages.getString("options.script.table.header.dir")}; private static final int COLUMN_COUNT = COLUMN_NAMES.length; private List<File> tokens = new ArrayList<>(0); /** * */ public OptionsScriptTableModel() { super(); } @Override public List<File> getElements() { return tokens; } /** * @param tokens The tokens to set. */ public void setTokens(List<File> files) { this.tokens = new ArrayList<>(tokens.size()); for (File file : files) { this.tokens.add(file); } fireTableDataChanged(); } @Override public String getColumnName(int col) { return COLUMN_NAMES[col]; } @Override public int getColumnCount() { return COLUMN_COUNT; } @Override public Class<?> getColumnClass(int c) { return String.class; } @Override public int getRowCount() { return tokens.size(); } @Override public boolean isCellEditable(int rowIndex, int columnIndex) { return false; } @Override public Object getValueAt(int rowIndex, int columnIndex) { switch(columnIndex) { case 0: return getElement(rowIndex).getAbsolutePath(); } return null; } @Override public void setValueAt(Object aValue, int rowIndex, int columnIndex) { } }
/* * 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.core.construction; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableList; import org.apache.beam.sdk.transforms.windowing.AfterAll; import org.apache.beam.sdk.transforms.windowing.AfterEach; import org.apache.beam.sdk.transforms.windowing.AfterFirst; import org.apache.beam.sdk.transforms.windowing.AfterPane; import org.apache.beam.sdk.transforms.windowing.AfterProcessingTime; import org.apache.beam.sdk.transforms.windowing.AfterSynchronizedProcessingTime; import org.apache.beam.sdk.transforms.windowing.AfterWatermark; import org.apache.beam.sdk.transforms.windowing.DefaultTrigger; import org.apache.beam.sdk.transforms.windowing.Never; import org.apache.beam.sdk.transforms.windowing.Repeatedly; import org.apache.beam.sdk.transforms.windowing.Trigger; import org.joda.time.Duration; import org.joda.time.Instant; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameter; import org.junit.runners.Parameterized.Parameters; /** Tests for utilities in {@link TriggerTranslation}. */ @RunWith(Parameterized.class) public class TriggerTranslationTest { @AutoValue abstract static class ToProtoAndBackSpec { abstract Trigger getTrigger(); } private static ToProtoAndBackSpec toProtoAndBackSpec(Trigger trigger) { return new AutoValue_TriggerTranslationTest_ToProtoAndBackSpec(trigger); } @Parameters(name = "{index}: {0}") public static Iterable<ToProtoAndBackSpec> data() { return ImmutableList.of( // Atomic triggers toProtoAndBackSpec(AfterWatermark.pastEndOfWindow()), toProtoAndBackSpec(AfterPane.elementCountAtLeast(73)), toProtoAndBackSpec(AfterSynchronizedProcessingTime.ofFirstElement()), toProtoAndBackSpec(Never.ever()), toProtoAndBackSpec(DefaultTrigger.of()), toProtoAndBackSpec(AfterProcessingTime.pastFirstElementInPane()), toProtoAndBackSpec( AfterProcessingTime.pastFirstElementInPane().plusDelayOf(Duration.millis(23))), toProtoAndBackSpec( AfterProcessingTime.pastFirstElementInPane() .alignedTo(Duration.millis(5), new Instant(27))), toProtoAndBackSpec( AfterProcessingTime.pastFirstElementInPane() .plusDelayOf(Duration.standardSeconds(3)) .alignedTo(Duration.millis(5), new Instant(27)) .plusDelayOf(Duration.millis(13))), // Composite triggers toProtoAndBackSpec( AfterAll.of(AfterPane.elementCountAtLeast(79), AfterWatermark.pastEndOfWindow())), toProtoAndBackSpec( AfterEach.inOrder(AfterPane.elementCountAtLeast(79), AfterPane.elementCountAtLeast(3))), toProtoAndBackSpec( AfterFirst.of(AfterWatermark.pastEndOfWindow(), AfterPane.elementCountAtLeast(3))), toProtoAndBackSpec( AfterWatermark.pastEndOfWindow().withEarlyFirings(AfterPane.elementCountAtLeast(3))), toProtoAndBackSpec( AfterWatermark.pastEndOfWindow().withLateFirings(AfterPane.elementCountAtLeast(3))), toProtoAndBackSpec( AfterWatermark.pastEndOfWindow() .withEarlyFirings( AfterProcessingTime.pastFirstElementInPane().plusDelayOf(Duration.millis(42))) .withLateFirings(AfterPane.elementCountAtLeast(3))), toProtoAndBackSpec(Repeatedly.forever(AfterWatermark.pastEndOfWindow())), toProtoAndBackSpec( Repeatedly.forever(AfterPane.elementCountAtLeast(1)) .orFinally(AfterWatermark.pastEndOfWindow()))); } @Parameter(0) public ToProtoAndBackSpec toProtoAndBackSpec; @Test public void testToProtoAndBack() throws Exception { Trigger trigger = toProtoAndBackSpec.getTrigger(); Trigger toProtoAndBackTrigger = TriggerTranslation.fromProto(TriggerTranslation.toProto(trigger)); assertThat(toProtoAndBackTrigger, equalTo(trigger)); } }