code
stringlengths
5
1.01M
repo_name
stringlengths
5
84
path
stringlengths
4
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
5
1.01M
input_ids
listlengths
502
502
token_type_ids
listlengths
502
502
attention_mask
listlengths
502
502
labels
listlengths
502
502
// Copyright 2015 CoreOS, Inc. All rights reserved. // Use of this source code is governed by the BSD 3-Clause license, // which can be found in the LICENSE file. package sqlbuilder type Dialect interface { EscapeCharacter() rune InsertReturningClause() string Kind() string Name() *string } type genericDialect struct { escapeChar rune returningClause string kind string name *string } func (db *genericDialect) EscapeCharacter() rune { return db.escapeChar } func (db *genericDialect) InsertReturningClause() string { return db.returningClause } func (db *genericDialect) Kind() string { return db.kind } func (db *genericDialect) Name() *string { return db.name } func NewMySQLDialect(dbName *string) Dialect { return &genericDialect{ escapeChar: '`', kind: "mysql", name: dbName, } } func NewPostgresDialect(dbName *string) Dialect { return &genericDialect{ escapeChar: '"', returningClause: " RETURNING *", kind: "postgres", name: dbName, } } func NewSQLiteDialect() Dialect { defaultName := "main" return &genericDialect{ escapeChar: '"', kind: "sqlite", name: &defaultName, } }
coreos/sqlbuilder
dialect.go
GO
bsd-3-clause
1,212
[ 30522, 1013, 1013, 9385, 2325, 4563, 2891, 1010, 4297, 1012, 2035, 2916, 9235, 1012, 1013, 1013, 2224, 1997, 2023, 3120, 3642, 2003, 9950, 2011, 1996, 18667, 2094, 1017, 1011, 11075, 6105, 1010, 1013, 1013, 2029, 2064, 2022, 2179, 1999, 1...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
package com.atlach.trafficdataloader; import java.util.ArrayList; /* Short Desc: Storage object for Trip info */ /* Trip Info > Trips > Routes */ public class TripInfo { private int tripCount = 0; public ArrayList<Trip> trips = null; public String date; public String origin; public String destination; public TripInfo() { trips = new ArrayList<Trip>(); } public int addTrip() { Trip temp = new Trip(); if (trips.add(temp) == false) { /* Failed */ return -1; } tripCount++; return trips.indexOf(temp); } public int addRouteToTrip(int tripId, String routeName, String mode, String dist, String agency, String start, String end, String points) { int result = -1; Trip temp = trips.get(tripId); if (temp != null) { result = temp.addRoute(routeName, mode, dist, agency, start, end, points); } return result; } public int getTripCount() { return tripCount; } public static class Trip { public double totalDist = 0.0; public double totalCost = 0.0; public int totalTraffic = 0; private int transfers = 0; public ArrayList<Route> routes = null; public Trip() { routes = new ArrayList<Route>(); }; public int addRoute(String routeName, String mode, String dist, String agency, String start, String end, String points) { Route temp = new Route(); temp.name = routeName; temp.mode = mode; temp.dist = dist; temp.agency = agency; temp.start = start; temp.end = end; temp.points = points; if (routes.add(temp) == false) { /* Failed */ return -1; } transfers++; return routes.indexOf(temp); } public int getTransfers() { return transfers; } } public static class Route { /* Object fields */ public String name = ""; public String mode = ""; public String dist = "0.0"; public String agency = ""; public String start = ""; public String end = ""; public String points = ""; public String cond = ""; //public String cost = "0.0"; public double costMatrix[] = {0.0, 0.0, 0.0, 0.0}; public double getRegularCost(boolean isDiscounted) { if (isDiscounted) { return costMatrix[1]; } return costMatrix[0]; } public double getSpecialCost(boolean isDiscounted) { if (isDiscounted) { return costMatrix[2]; } return costMatrix[3]; } } }
linusmotu/Viaje
ViajeUi/src/com/atlach/trafficdataloader/TripInfo.java
Java
gpl-2.0
2,363
[ 30522, 7427, 4012, 1012, 2012, 2721, 2818, 1012, 4026, 2850, 9080, 10441, 4063, 1025, 12324, 9262, 1012, 21183, 4014, 1012, 9140, 9863, 1025, 1013, 1008, 2460, 4078, 2278, 1024, 5527, 4874, 2005, 4440, 30524, 1025, 2270, 4440, 2378, 14876, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>metacoq-pcuic: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.8.1 / metacoq-pcuic - 1.0~beta1+8.12</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> metacoq-pcuic <small> 1.0~beta1+8.12 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2021-12-20 02:39:21 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2021-12-20 02:39:21 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-num base Num library distributed with the OCaml compiler base-threads base base-unix base camlp5 7.14 Preprocessor-pretty-printer of OCaml conf-findutils 1 Virtual package relying on findutils conf-perl 1 Virtual package relying on perl coq 8.8.1 Formal proof management system num 0 The Num library for arbitrary-precision integer and rational arithmetic ocaml 4.03.0 The OCaml compiler (virtual package) ocaml-base-compiler 4.03.0 Official 4.03.0 release ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.1 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;matthieu.sozeau@inria.fr&quot; homepage: &quot;https://metacoq.github.io/metacoq&quot; dev-repo: &quot;git+https://github.com/MetaCoq/metacoq.git#coq-8.12&quot; bug-reports: &quot;https://github.com/MetaCoq/metacoq/issues&quot; authors: [&quot;Abhishek Anand &lt;aa755@cs.cornell.edu&gt;&quot; &quot;Simon Boulier &lt;simon.boulier@inria.fr&gt;&quot; &quot;Cyril Cohen &lt;cyril.cohen@inria.fr&gt;&quot; &quot;Yannick Forster &lt;forster@ps.uni-saarland.de&gt;&quot; &quot;Fabian Kunze &lt;fkunze@fakusb.de&gt;&quot; &quot;Gregory Malecha &lt;gmalecha@gmail.com&gt;&quot; &quot;Matthieu Sozeau &lt;matthieu.sozeau@inria.fr&gt;&quot; &quot;Nicolas Tabareau &lt;nicolas.tabareau@inria.fr&gt;&quot; &quot;Théo Winterhalter &lt;theo.winterhalter@inria.fr&gt;&quot; ] license: &quot;MIT&quot; build: [ [&quot;sh&quot; &quot;./configure.sh&quot;] [make &quot;-j%{jobs}%&quot; &quot;-C&quot; &quot;pcuic&quot;] ] install: [ [make &quot;-C&quot; &quot;pcuic&quot; &quot;install&quot;] ] depends: [ &quot;ocaml&quot; {&gt;= &quot;4.07.1&quot;} &quot;coq&quot; {&gt;= &quot;8.12&quot; &amp; &lt; &quot;8.13~&quot;} &quot;coq-equations&quot; { = &quot;1.2.3+8.12&quot; } &quot;coq-metacoq-template&quot; {= version} &quot;coq-metacoq-checker&quot; {= version} ] synopsis: &quot;A type system equivalent to Coq&#39;s and its metatheory&quot; description: &quot;&quot;&quot; MetaCoq is a meta-programming framework for Coq. The PCUIC module provides a cleaned-up specification of Coq&#39;s typing algorithm along with a certified typechecker for it. This module includes the standard metatheory of PCUIC: Weakening, Substitution, Confluence and Subject Reduction are proven here. &quot;&quot;&quot; url { src: &quot;https://github.com/MetaCoq/metacoq/archive/v1.0-beta1-8.12.tar.gz&quot; checksum: &quot;sha256=19fc4475ae81677018e21a1e20503716a47713ec8b2081e7506f5c9390284c7a&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-metacoq-pcuic.1.0~beta1+8.12 coq.8.8.1</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.8.1). The following dependencies couldn&#39;t be met: - coq-metacoq-pcuic -&gt; ocaml &gt;= 4.07.1 base of this switch (use `--unlock-base&#39; to force) No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-metacoq-pcuic.1.0~beta1+8.12</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
coq-bench/coq-bench.github.io
clean/Linux-x86_64-4.03.0-2.0.5/released/8.8.1/metacoq-pcuic/1.0~beta1+8.12.html
HTML
mit
7,825
[ 30522, 1026, 999, 9986, 13874, 16129, 1028, 1026, 16129, 11374, 1027, 1000, 4372, 1000, 1028, 1026, 2132, 1028, 1026, 18804, 25869, 13462, 1027, 1000, 21183, 2546, 1011, 1022, 1000, 1028, 1026, 18804, 2171, 1027, 1000, 3193, 6442, 1000, 418...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* * Copyright 2011 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.jstestdriver.output; /** * Escapes and formats a filename. * * @author Cory Smith (corbinrsmith@gmail.com) */ public class FileNameFormatter { public String format(String path, String format) { String escaped = path .replace('/', 'a') .replace('\\', 'a') .replace(">", "a") .replace(":", "a") .replace(":", "a") .replace(";", "a") .replace("+", "a") .replace(",", "a") .replace("<", "a") .replace("?", "a") .replace("*", "a") .replace(" ", "a"); return String.format(format, escaped.length() > 200 ? escaped.substring(0, 200) : escaped); } }
BladeRunnerJS/brjs-JsTestDriver
JsTestDriver/src/com/google/jstestdriver/output/FileNameFormatter.java
Java
apache-2.0
1,271
[ 30522, 1013, 1008, 1008, 9385, 2249, 8224, 4297, 1012, 1008, 1008, 7000, 2104, 1996, 15895, 6105, 1010, 2544, 1016, 1012, 1014, 1006, 1996, 1000, 6105, 1000, 1007, 1025, 2017, 2089, 2025, 1008, 2224, 2023, 5371, 3272, 1999, 12646, 2007, 1...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* * linux/fs/namespace.c * * (C) Copyright Al Viro 2000, 2001 * Released under GPL v2. * * Based on code from fs/super.c, copyright Linus Torvalds and others. * Heavily rewritten. */ #include <linux/syscalls.h> #include <linux/export.h> #include <linux/capability.h> #include <linux/mnt_namespace.h> #include <linux/user_namespace.h> #include <linux/namei.h> #include <linux/security.h> #include <linux/idr.h> #include <linux/acct.h> /* acct_auto_close_mnt */ #include <linux/ramfs.h> /* init_rootfs */ #include <linux/fs_struct.h> /* get_fs_root et.al. */ #include <linux/fsnotify.h> /* fsnotify_vfsmount_delete */ #include <linux/uaccess.h> #include <linux/proc_ns.h> #include <linux/magic.h> #include "pnode.h" #include "internal.h" #define HASH_SHIFT ilog2(PAGE_SIZE / sizeof(struct list_head)) #define HASH_SIZE (1UL << HASH_SHIFT) static int event; static DEFINE_IDA(mnt_id_ida); static DEFINE_IDA(mnt_group_ida); static DEFINE_SPINLOCK(mnt_id_lock); static int mnt_id_start = 0; static int mnt_group_start = 1; static struct list_head *mount_hashtable __read_mostly; static struct list_head *mountpoint_hashtable __read_mostly; static struct kmem_cache *mnt_cache __read_mostly; static struct rw_semaphore namespace_sem; /* /sys/fs */ struct kobject *fs_kobj; EXPORT_SYMBOL_GPL(fs_kobj); /* * vfsmount lock may be taken for read to prevent changes to the * vfsmount hash, ie. during mountpoint lookups or walking back * up the tree. * * It should be taken for write in all cases where the vfsmount * tree or hash is modified or when a vfsmount structure is modified. */ DEFINE_BRLOCK(vfsmount_lock); static inline unsigned long hash(struct vfsmount *mnt, struct dentry *dentry) { unsigned long tmp = ((unsigned long)mnt / L1_CACHE_BYTES); tmp += ((unsigned long)dentry / L1_CACHE_BYTES); tmp = tmp + (tmp >> HASH_SHIFT); return tmp & (HASH_SIZE - 1); } #define MNT_WRITER_UNDERFLOW_LIMIT -(1<<16) /* * allocation is serialized by namespace_sem, but we need the spinlock to * serialize with freeing. */ static int mnt_alloc_id(struct mount *mnt) { int res; retry: ida_pre_get(&mnt_id_ida, GFP_KERNEL); spin_lock(&mnt_id_lock); res = ida_get_new_above(&mnt_id_ida, mnt_id_start, &mnt->mnt_id); if (!res) mnt_id_start = mnt->mnt_id + 1; spin_unlock(&mnt_id_lock); if (res == -EAGAIN) goto retry; return res; } static void mnt_free_id(struct mount *mnt) { int id = mnt->mnt_id; spin_lock(&mnt_id_lock); ida_remove(&mnt_id_ida, id); if (mnt_id_start > id) mnt_id_start = id; spin_unlock(&mnt_id_lock); } /* * Allocate a new peer group ID * * mnt_group_ida is protected by namespace_sem */ static int mnt_alloc_group_id(struct mount *mnt) { int res; if (!ida_pre_get(&mnt_group_ida, GFP_KERNEL)) return -ENOMEM; res = ida_get_new_above(&mnt_group_ida, mnt_group_start, &mnt->mnt_group_id); if (!res) mnt_group_start = mnt->mnt_group_id + 1; return res; } /* * Release a peer group ID */ void mnt_release_group_id(struct mount *mnt) { int id = mnt->mnt_group_id; ida_remove(&mnt_group_ida, id); if (mnt_group_start > id) mnt_group_start = id; mnt->mnt_group_id = 0; } /* * vfsmount lock must be held for read */ static inline void mnt_add_count(struct mount *mnt, int n) { #ifdef CONFIG_SMP this_cpu_add(mnt->mnt_pcp->mnt_count, n); #else preempt_disable(); mnt->mnt_count += n; preempt_enable(); #endif } /* * vfsmount lock must be held for write */ unsigned int mnt_get_count(struct mount *mnt) { #ifdef CONFIG_SMP unsigned int count = 0; int cpu; for_each_possible_cpu(cpu) { count += per_cpu_ptr(mnt->mnt_pcp, cpu)->mnt_count; } return count; #else return mnt->mnt_count; #endif } static struct mount *alloc_vfsmnt(const char *name) { struct mount *mnt = kmem_cache_zalloc(mnt_cache, GFP_KERNEL); if (mnt) { int err; err = mnt_alloc_id(mnt); if (err) goto out_free_cache; if (name) { mnt->mnt_devname = kstrdup(name, GFP_KERNEL); if (!mnt->mnt_devname) goto out_free_id; } #ifdef CONFIG_SMP mnt->mnt_pcp = alloc_percpu(struct mnt_pcp); if (!mnt->mnt_pcp) goto out_free_devname; this_cpu_add(mnt->mnt_pcp->mnt_count, 1); #else mnt->mnt_count = 1; mnt->mnt_writers = 0; #endif INIT_LIST_HEAD(&mnt->mnt_hash); INIT_LIST_HEAD(&mnt->mnt_child); INIT_LIST_HEAD(&mnt->mnt_mounts); INIT_LIST_HEAD(&mnt->mnt_list); INIT_LIST_HEAD(&mnt->mnt_expire); INIT_LIST_HEAD(&mnt->mnt_share); INIT_LIST_HEAD(&mnt->mnt_slave_list); INIT_LIST_HEAD(&mnt->mnt_slave); #ifdef CONFIG_FSNOTIFY INIT_HLIST_HEAD(&mnt->mnt_fsnotify_marks); #endif } return mnt; #ifdef CONFIG_SMP out_free_devname: kfree(mnt->mnt_devname); #endif out_free_id: mnt_free_id(mnt); out_free_cache: kmem_cache_free(mnt_cache, mnt); return NULL; } /* * Most r/o checks on a fs are for operations that take * discrete amounts of time, like a write() or unlink(). * We must keep track of when those operations start * (for permission checks) and when they end, so that * we can determine when writes are able to occur to * a filesystem. */ /* * __mnt_is_readonly: check whether a mount is read-only * @mnt: the mount to check for its write status * * This shouldn't be used directly ouside of the VFS. * It does not guarantee that the filesystem will stay * r/w, just that it is right *now*. This can not and * should not be used in place of IS_RDONLY(inode). * mnt_want/drop_write() will _keep_ the filesystem * r/w. */ int __mnt_is_readonly(struct vfsmount *mnt) { if (mnt->mnt_flags & MNT_READONLY) return 1; if (mnt->mnt_sb->s_flags & MS_RDONLY) return 1; return 0; } EXPORT_SYMBOL_GPL(__mnt_is_readonly); static inline void mnt_inc_writers(struct mount *mnt) { #ifdef CONFIG_SMP this_cpu_inc(mnt->mnt_pcp->mnt_writers); #else mnt->mnt_writers++; #endif } static inline void mnt_dec_writers(struct mount *mnt) { #ifdef CONFIG_SMP this_cpu_dec(mnt->mnt_pcp->mnt_writers); #else mnt->mnt_writers--; #endif } static unsigned int mnt_get_writers(struct mount *mnt) { #ifdef CONFIG_SMP unsigned int count = 0; int cpu; for_each_possible_cpu(cpu) { count += per_cpu_ptr(mnt->mnt_pcp, cpu)->mnt_writers; } return count; #else return mnt->mnt_writers; #endif } static int mnt_is_readonly(struct vfsmount *mnt) { if (mnt->mnt_sb->s_readonly_remount) return 1; /* Order wrt setting s_flags/s_readonly_remount in do_remount() */ smp_rmb(); return __mnt_is_readonly(mnt); } /* * Most r/o & frozen checks on a fs are for operations that take discrete * amounts of time, like a write() or unlink(). We must keep track of when * those operations start (for permission checks) and when they end, so that we * can determine when writes are able to occur to a filesystem. */ /** * __mnt_want_write - get write access to a mount without freeze protection * @m: the mount on which to take a write * * This tells the low-level filesystem that a write is about to be performed to * it, and makes sure that writes are allowed (mnt it read-write) before * returning success. This operation does not protect against filesystem being * frozen. When the write operation is finished, __mnt_drop_write() must be * called. This is effectively a refcount. */ int __mnt_want_write(struct vfsmount *m) { struct mount *mnt = real_mount(m); int ret = 0; preempt_disable(); mnt_inc_writers(mnt); /* * The store to mnt_inc_writers must be visible before we pass * MNT_WRITE_HOLD loop below, so that the slowpath can see our * incremented count after it has set MNT_WRITE_HOLD. */ smp_mb(); while (ACCESS_ONCE(mnt->mnt.mnt_flags) & MNT_WRITE_HOLD) cpu_relax(); /* * After the slowpath clears MNT_WRITE_HOLD, mnt_is_readonly will * be set to match its requirements. So we must not load that until * MNT_WRITE_HOLD is cleared. */ smp_rmb(); if (mnt_is_readonly(m)) { mnt_dec_writers(mnt); ret = -EROFS; } preempt_enable(); return ret; } /** * mnt_want_write - get write access to a mount * @m: the mount on which to take a write * * This tells the low-level filesystem that a write is about to be performed to * it, and makes sure that writes are allowed (mount is read-write, filesystem * is not frozen) before returning success. When the write operation is * finished, mnt_drop_write() must be called. This is effectively a refcount. */ int mnt_want_write(struct vfsmount *m) { int ret; sb_start_write(m->mnt_sb); ret = __mnt_want_write(m); if (ret) sb_end_write(m->mnt_sb); return ret; } EXPORT_SYMBOL_GPL(mnt_want_write); /** * mnt_clone_write - get write access to a mount * @mnt: the mount on which to take a write * * This is effectively like mnt_want_write, except * it must only be used to take an extra write reference * on a mountpoint that we already know has a write reference * on it. This allows some optimisation. * * After finished, mnt_drop_write must be called as usual to * drop the reference. */ int mnt_clone_write(struct vfsmount *mnt) { /* superblock may be r/o */ if (__mnt_is_readonly(mnt)) return -EROFS; preempt_disable(); mnt_inc_writers(real_mount(mnt)); preempt_enable(); return 0; } EXPORT_SYMBOL_GPL(mnt_clone_write); /** * __mnt_want_write_file - get write access to a file's mount * @file: the file who's mount on which to take a write * * This is like __mnt_want_write, but it takes a file and can * do some optimisations if the file is open for write already */ int __mnt_want_write_file(struct file *file) { struct inode *inode = file_inode(file); if (!(file->f_mode & FMODE_WRITE) || special_file(inode->i_mode)) return __mnt_want_write(file->f_path.mnt); else return mnt_clone_write(file->f_path.mnt); } /** * mnt_want_write_file - get write access to a file's mount * @file: the file who's mount on which to take a write * * This is like mnt_want_write, but it takes a file and can * do some optimisations if the file is open for write already */ int mnt_want_write_file(struct file *file) { int ret; sb_start_write(file->f_path.mnt->mnt_sb); ret = __mnt_want_write_file(file); if (ret) sb_end_write(file->f_path.mnt->mnt_sb); return ret; } EXPORT_SYMBOL_GPL(mnt_want_write_file); /** * __mnt_drop_write - give up write access to a mount * @mnt: the mount on which to give up write access * * Tells the low-level filesystem that we are done * performing writes to it. Must be matched with * __mnt_want_write() call above. */ void __mnt_drop_write(struct vfsmount *mnt) { preempt_disable(); mnt_dec_writers(real_mount(mnt)); preempt_enable(); } /** * mnt_drop_write - give up write access to a mount * @mnt: the mount on which to give up write access * * Tells the low-level filesystem that we are done performing writes to it and * also allows filesystem to be frozen again. Must be matched with * mnt_want_write() call above. */ void mnt_drop_write(struct vfsmount *mnt) { __mnt_drop_write(mnt); sb_end_write(mnt->mnt_sb); } EXPORT_SYMBOL_GPL(mnt_drop_write); void __mnt_drop_write_file(struct file *file) { __mnt_drop_write(file->f_path.mnt); } void mnt_drop_write_file(struct file *file) { mnt_drop_write(file->f_path.mnt); } EXPORT_SYMBOL(mnt_drop_write_file); static int mnt_make_readonly(struct mount *mnt) { int ret = 0; br_write_lock(&vfsmount_lock); mnt->mnt.mnt_flags |= MNT_WRITE_HOLD; /* * After storing MNT_WRITE_HOLD, we'll read the counters. This store * should be visible before we do. */ smp_mb(); /* * With writers on hold, if this value is zero, then there are * definitely no active writers (although held writers may subsequently * increment the count, they'll have to wait, and decrement it after * seeing MNT_READONLY). * * It is OK to have counter incremented on one CPU and decremented on * another: the sum will add up correctly. The danger would be when we * sum up each counter, if we read a counter before it is incremented, * but then read another CPU's count which it has been subsequently * decremented from -- we would see more decrements than we should. * MNT_WRITE_HOLD protects against this scenario, because * mnt_want_write first increments count, then smp_mb, then spins on * MNT_WRITE_HOLD, so it can't be decremented by another CPU while * we're counting up here. */ if (mnt_get_writers(mnt) > 0) ret = -EBUSY; else mnt->mnt.mnt_flags |= MNT_READONLY; /* * MNT_READONLY must become visible before ~MNT_WRITE_HOLD, so writers * that become unheld will see MNT_READONLY. */ smp_wmb(); mnt->mnt.mnt_flags &= ~MNT_WRITE_HOLD; br_write_unlock(&vfsmount_lock); return ret; } static void __mnt_unmake_readonly(struct mount *mnt) { br_write_lock(&vfsmount_lock); mnt->mnt.mnt_flags &= ~MNT_READONLY; br_write_unlock(&vfsmount_lock); } int sb_prepare_remount_readonly(struct super_block *sb) { struct mount *mnt; int err = 0; /* Racy optimization. Recheck the counter under MNT_WRITE_HOLD */ if (atomic_long_read(&sb->s_remove_count)) return -EBUSY; br_write_lock(&vfsmount_lock); list_for_each_entry(mnt, &sb->s_mounts, mnt_instance) { if (!(mnt->mnt.mnt_flags & MNT_READONLY)) { mnt->mnt.mnt_flags |= MNT_WRITE_HOLD; smp_mb(); if (mnt_get_writers(mnt) > 0) { err = -EBUSY; break; } } } if (!err && atomic_long_read(&sb->s_remove_count)) err = -EBUSY; if (!err) { sb->s_readonly_remount = 1; smp_wmb(); } list_for_each_entry(mnt, &sb->s_mounts, mnt_instance) { if (mnt->mnt.mnt_flags & MNT_WRITE_HOLD) mnt->mnt.mnt_flags &= ~MNT_WRITE_HOLD; } br_write_unlock(&vfsmount_lock); return err; } static void free_vfsmnt(struct mount *mnt) { kfree(mnt->mnt_devname); mnt_free_id(mnt); #ifdef CONFIG_SMP free_percpu(mnt->mnt_pcp); #endif kmem_cache_free(mnt_cache, mnt); } /* * find the first or last mount at @dentry on vfsmount @mnt depending on * @dir. If @dir is set return the first mount else return the last mount. * vfsmount_lock must be held for read or write. */ struct mount *__lookup_mnt(struct vfsmount *mnt, struct dentry *dentry, int dir) { struct list_head *head = mount_hashtable + hash(mnt, dentry); struct list_head *tmp = head; struct mount *p, *found = NULL; for (;;) { tmp = dir ? tmp->next : tmp->prev; p = NULL; if (tmp == head) break; p = list_entry(tmp, struct mount, mnt_hash); if (&p->mnt_parent->mnt == mnt && p->mnt_mountpoint == dentry) { found = p; break; } } return found; } /* * lookup_mnt - Return the first child mount mounted at path * * "First" means first mounted chronologically. If you create the * following mounts: * * mount /dev/sda1 /mnt * mount /dev/sda2 /mnt * mount /dev/sda3 /mnt * * Then lookup_mnt() on the base /mnt dentry in the root mount will * return successively the root dentry and vfsmount of /dev/sda1, then * /dev/sda2, then /dev/sda3, then NULL. * * lookup_mnt takes a reference to the found vfsmount. */ struct vfsmount *lookup_mnt(struct path *path) { struct mount *child_mnt; br_read_lock(&vfsmount_lock); child_mnt = __lookup_mnt(path->mnt, path->dentry, 1); if (child_mnt) { mnt_add_count(child_mnt, 1); br_read_unlock(&vfsmount_lock); return &child_mnt->mnt; } else { br_read_unlock(&vfsmount_lock); return NULL; } } static struct mountpoint *new_mountpoint(struct dentry *dentry) { struct list_head *chain = mountpoint_hashtable + hash(NULL, dentry); struct mountpoint *mp; list_for_each_entry(mp, chain, m_hash) { if (mp->m_dentry == dentry) { /* might be worth a WARN_ON() */ if (d_unlinked(dentry)) return ERR_PTR(-ENOENT); mp->m_count++; return mp; } } mp = kmalloc(sizeof(struct mountpoint), GFP_KERNEL); if (!mp) return ERR_PTR(-ENOMEM); spin_lock(&dentry->d_lock); if (d_unlinked(dentry)) { spin_unlock(&dentry->d_lock); kfree(mp); return ERR_PTR(-ENOENT); } dentry->d_flags |= DCACHE_MOUNTED; spin_unlock(&dentry->d_lock); mp->m_dentry = dentry; mp->m_count = 1; list_add(&mp->m_hash, chain); return mp; } static void put_mountpoint(struct mountpoint *mp) { if (!--mp->m_count) { struct dentry *dentry = mp->m_dentry; spin_lock(&dentry->d_lock); dentry->d_flags &= ~DCACHE_MOUNTED; spin_unlock(&dentry->d_lock); list_del(&mp->m_hash); kfree(mp); } } static inline int check_mnt(struct mount *mnt) { return mnt->mnt_ns == current->nsproxy->mnt_ns; } /* * vfsmount lock must be held for write */ static void touch_mnt_namespace(struct mnt_namespace *ns) { if (ns) { ns->event = ++event; wake_up_interruptible(&ns->poll); } } /* * vfsmount lock must be held for write */ static void __touch_mnt_namespace(struct mnt_namespace *ns) { if (ns && ns->event != event) { ns->event = event; wake_up_interruptible(&ns->poll); } } /* * vfsmount lock must be held for write */ static void detach_mnt(struct mount *mnt, struct path *old_path) { old_path->dentry = mnt->mnt_mountpoint; old_path->mnt = &mnt->mnt_parent->mnt; mnt->mnt_parent = mnt; mnt->mnt_mountpoint = mnt->mnt.mnt_root; list_del_init(&mnt->mnt_child); list_del_init(&mnt->mnt_hash); put_mountpoint(mnt->mnt_mp); mnt->mnt_mp = NULL; } /* * vfsmount lock must be held for write */ void mnt_set_mountpoint(struct mount *mnt, struct mountpoint *mp, struct mount *child_mnt) { mp->m_count++; mnt_add_count(mnt, 1); /* essentially, that's mntget */ child_mnt->mnt_mountpoint = dget(mp->m_dentry); child_mnt->mnt_parent = mnt; child_mnt->mnt_mp = mp; } /* * vfsmount lock must be held for write */ static void attach_mnt(struct mount *mnt, struct mount *parent, struct mountpoint *mp) { mnt_set_mountpoint(parent, mp, mnt); list_add_tail(&mnt->mnt_hash, mount_hashtable + hash(&parent->mnt, mp->m_dentry)); list_add_tail(&mnt->mnt_child, &parent->mnt_mounts); } /* * vfsmount lock must be held for write */ static void commit_tree(struct mount *mnt) { struct mount *parent = mnt->mnt_parent; struct mount *m; LIST_HEAD(head); struct mnt_namespace *n = parent->mnt_ns; BUG_ON(parent == mnt); list_add_tail(&head, &mnt->mnt_list); list_for_each_entry(m, &head, mnt_list) m->mnt_ns = n; list_splice(&head, n->list.prev); list_add_tail(&mnt->mnt_hash, mount_hashtable + hash(&parent->mnt, mnt->mnt_mountpoint)); list_add_tail(&mnt->mnt_child, &parent->mnt_mounts); touch_mnt_namespace(n); } static struct mount *next_mnt(struct mount *p, struct mount *root) { struct list_head *next = p->mnt_mounts.next; if (next == &p->mnt_mounts) { while (1) { if (p == root) return NULL; next = p->mnt_child.next; if (next != &p->mnt_parent->mnt_mounts) break; p = p->mnt_parent; } } return list_entry(next, struct mount, mnt_child); } static struct mount *skip_mnt_tree(struct mount *p) { struct list_head *prev = p->mnt_mounts.prev; while (prev != &p->mnt_mounts) { p = list_entry(prev, struct mount, mnt_child); prev = p->mnt_mounts.prev; } return p; } struct vfsmount * vfs_kern_mount(struct file_system_type *type, int flags, const char *name, void *data) { struct mount *mnt; struct dentry *root; if (!type) return ERR_PTR(-ENODEV); mnt = alloc_vfsmnt(name); if (!mnt) return ERR_PTR(-ENOMEM); if (flags & MS_KERNMOUNT) mnt->mnt.mnt_flags = MNT_INTERNAL; root = mount_fs(type, flags, name, data); if (IS_ERR(root)) { free_vfsmnt(mnt); return ERR_CAST(root); } mnt->mnt.mnt_root = root; mnt->mnt.mnt_sb = root->d_sb; mnt->mnt_mountpoint = mnt->mnt.mnt_root; mnt->mnt_parent = mnt; br_write_lock(&vfsmount_lock); list_add_tail(&mnt->mnt_instance, &root->d_sb->s_mounts); br_write_unlock(&vfsmount_lock); return &mnt->mnt; } EXPORT_SYMBOL_GPL(vfs_kern_mount); static struct mount *clone_mnt(struct mount *old, struct dentry *root, int flag) { struct super_block *sb = old->mnt.mnt_sb; struct mount *mnt; int err; mnt = alloc_vfsmnt(old->mnt_devname); if (!mnt) return ERR_PTR(-ENOMEM); if (flag & (CL_SLAVE | CL_PRIVATE | CL_SHARED_TO_SLAVE)) mnt->mnt_group_id = 0; /* not a peer of original */ else mnt->mnt_group_id = old->mnt_group_id; if ((flag & CL_MAKE_SHARED) && !mnt->mnt_group_id) { err = mnt_alloc_group_id(mnt); if (err) goto out_free; } mnt->mnt.mnt_flags = old->mnt.mnt_flags & ~MNT_WRITE_HOLD; /* Don't allow unprivileged users to change mount flags */ if ((flag & CL_UNPRIVILEGED) && (mnt->mnt.mnt_flags & MNT_READONLY)) mnt->mnt.mnt_flags |= MNT_LOCK_READONLY; atomic_inc(&sb->s_active); mnt->mnt.mnt_sb = sb; mnt->mnt.mnt_root = dget(root); mnt->mnt_mountpoint = mnt->mnt.mnt_root; mnt->mnt_parent = mnt; br_write_lock(&vfsmount_lock); list_add_tail(&mnt->mnt_instance, &sb->s_mounts); br_write_unlock(&vfsmount_lock); if ((flag & CL_SLAVE) || ((flag & CL_SHARED_TO_SLAVE) && IS_MNT_SHARED(old))) { list_add(&mnt->mnt_slave, &old->mnt_slave_list); mnt->mnt_master = old; CLEAR_MNT_SHARED(mnt); } else if (!(flag & CL_PRIVATE)) { if ((flag & CL_MAKE_SHARED) || IS_MNT_SHARED(old)) list_add(&mnt->mnt_share, &old->mnt_share); if (IS_MNT_SLAVE(old)) list_add(&mnt->mnt_slave, &old->mnt_slave); mnt->mnt_master = old->mnt_master; } if (flag & CL_MAKE_SHARED) set_mnt_shared(mnt); /* stick the duplicate mount on the same expiry list * as the original if that was on one */ if (flag & CL_EXPIRE) { if (!list_empty(&old->mnt_expire)) list_add(&mnt->mnt_expire, &old->mnt_expire); } return mnt; out_free: free_vfsmnt(mnt); return ERR_PTR(err); } static inline void mntfree(struct mount *mnt) { struct vfsmount *m = &mnt->mnt; struct super_block *sb = m->mnt_sb; /* * This probably indicates that somebody messed * up a mnt_want/drop_write() pair. If this * happens, the filesystem was probably unable * to make r/w->r/o transitions. */ /* * The locking used to deal with mnt_count decrement provides barriers, * so mnt_get_writers() below is safe. */ WARN_ON(mnt_get_writers(mnt)); fsnotify_vfsmount_delete(m); dput(m->mnt_root); free_vfsmnt(mnt); deactivate_super(sb); } static void mntput_no_expire(struct mount *mnt) { put_again: #ifdef CONFIG_SMP br_read_lock(&vfsmount_lock); if (likely(mnt->mnt_ns)) { /* shouldn't be the last one */ mnt_add_count(mnt, -1); br_read_unlock(&vfsmount_lock); return; } br_read_unlock(&vfsmount_lock); br_write_lock(&vfsmount_lock); mnt_add_count(mnt, -1); if (mnt_get_count(mnt)) { br_write_unlock(&vfsmount_lock); return; } #else mnt_add_count(mnt, -1); if (likely(mnt_get_count(mnt))) return; br_write_lock(&vfsmount_lock); #endif if (unlikely(mnt->mnt_pinned)) { mnt_add_count(mnt, mnt->mnt_pinned + 1); mnt->mnt_pinned = 0; br_write_unlock(&vfsmount_lock); acct_auto_close_mnt(&mnt->mnt); goto put_again; } list_del(&mnt->mnt_instance); br_write_unlock(&vfsmount_lock); mntfree(mnt); } void mntput(struct vfsmount *mnt) { if (mnt) { struct mount *m = real_mount(mnt); /* avoid cacheline pingpong, hope gcc doesn't get "smart" */ if (unlikely(m->mnt_expiry_mark)) m->mnt_expiry_mark = 0; mntput_no_expire(m); } } EXPORT_SYMBOL(mntput); struct vfsmount *mntget(struct vfsmount *mnt) { if (mnt) mnt_add_count(real_mount(mnt), 1); return mnt; } EXPORT_SYMBOL(mntget); void mnt_pin(struct vfsmount *mnt) { br_write_lock(&vfsmount_lock); real_mount(mnt)->mnt_pinned++; br_write_unlock(&vfsmount_lock); } EXPORT_SYMBOL(mnt_pin); void mnt_unpin(struct vfsmount *m) { struct mount *mnt = real_mount(m); br_write_lock(&vfsmount_lock); if (mnt->mnt_pinned) { mnt_add_count(mnt, 1); mnt->mnt_pinned--; } br_write_unlock(&vfsmount_lock); } EXPORT_SYMBOL(mnt_unpin); static inline void mangle(struct seq_file *m, const char *s) { seq_escape(m, s, " \t\n\\"); } /* * Simple .show_options callback for filesystems which don't want to * implement more complex mount option showing. * * See also save_mount_options(). */ int generic_show_options(struct seq_file *m, struct dentry *root) { const char *options; rcu_read_lock(); options = rcu_dereference(root->d_sb->s_options); if (options != NULL && options[0]) { seq_putc(m, ','); mangle(m, options); } rcu_read_unlock(); return 0; } EXPORT_SYMBOL(generic_show_options); /* * If filesystem uses generic_show_options(), this function should be * called from the fill_super() callback. * * The .remount_fs callback usually needs to be handled in a special * way, to make sure, that previous options are not overwritten if the * remount fails. * * Also note, that if the filesystem's .remount_fs function doesn't * reset all options to their default value, but changes only newly * given options, then the displayed options will not reflect reality * any more. */ void save_mount_options(struct super_block *sb, char *options) { BUG_ON(sb->s_options); rcu_assign_pointer(sb->s_options, kstrdup(options, GFP_KERNEL)); } EXPORT_SYMBOL(save_mount_options); void replace_mount_options(struct super_block *sb, char *options) { char *old = sb->s_options; rcu_assign_pointer(sb->s_options, options); if (old) { synchronize_rcu(); kfree(old); } } EXPORT_SYMBOL(replace_mount_options); #ifdef CONFIG_PROC_FS /* iterator; we want it to have access to namespace_sem, thus here... */ static void *m_start(struct seq_file *m, loff_t *pos) { struct proc_mounts *p = proc_mounts(m); down_read(&namespace_sem); return seq_list_start(&p->ns->list, *pos); } static void *m_next(struct seq_file *m, void *v, loff_t *pos) { struct proc_mounts *p = proc_mounts(m); return seq_list_next(v, &p->ns->list, pos); } static void m_stop(struct seq_file *m, void *v) { up_read(&namespace_sem); } static int m_show(struct seq_file *m, void *v) { struct proc_mounts *p = proc_mounts(m); struct mount *r = list_entry(v, struct mount, mnt_list); return p->show(m, &r->mnt); } const struct seq_operations mounts_op = { .start = m_start, .next = m_next, .stop = m_stop, .show = m_show, }; #endif /* CONFIG_PROC_FS */ /** * may_umount_tree - check if a mount tree is busy * @mnt: root of mount tree * * This is called to check if a tree of mounts has any * open files, pwds, chroots or sub mounts that are * busy. */ int may_umount_tree(struct vfsmount *m) { struct mount *mnt = real_mount(m); int actual_refs = 0; int minimum_refs = 0; struct mount *p; BUG_ON(!m); /* write lock needed for mnt_get_count */ br_write_lock(&vfsmount_lock); for (p = mnt; p; p = next_mnt(p, mnt)) { actual_refs += mnt_get_count(p); minimum_refs += 2; } br_write_unlock(&vfsmount_lock); if (actual_refs > minimum_refs) return 0; return 1; } EXPORT_SYMBOL(may_umount_tree); /** * may_umount - check if a mount point is busy * @mnt: root of mount * * This is called to check if a mount point has any * open files, pwds, chroots or sub mounts. If the * mount has sub mounts this will return busy * regardless of whether the sub mounts are busy. * * Doesn't take quota and stuff into account. IOW, in some cases it will * give false negatives. The main reason why it's here is that we need * a non-destructive way to look for easily umountable filesystems. */ int may_umount(struct vfsmount *mnt) { int ret = 1; down_read(&namespace_sem); br_write_lock(&vfsmount_lock); if (propagate_mount_busy(real_mount(mnt), 2)) ret = 0; br_write_unlock(&vfsmount_lock); up_read(&namespace_sem); return ret; } EXPORT_SYMBOL(may_umount); static LIST_HEAD(unmounted); /* protected by namespace_sem */ static void namespace_unlock(void) { struct mount *mnt; LIST_HEAD(head); if (likely(list_empty(&unmounted))) { up_write(&namespace_sem); return; } list_splice_init(&unmounted, &head); up_write(&namespace_sem); while (!list_empty(&head)) { mnt = list_first_entry(&head, struct mount, mnt_hash); list_del_init(&mnt->mnt_hash); if (mnt_has_parent(mnt)) { struct dentry *dentry; struct mount *m; br_write_lock(&vfsmount_lock); dentry = mnt->mnt_mountpoint; m = mnt->mnt_parent; mnt->mnt_mountpoint = mnt->mnt.mnt_root; mnt->mnt_parent = mnt; m->mnt_ghosts--; br_write_unlock(&vfsmount_lock); dput(dentry); mntput(&m->mnt); } mntput(&mnt->mnt); } } static inline void namespace_lock(void) { down_write(&namespace_sem); } /* * vfsmount lock must be held for write * namespace_sem must be held for write */ void umount_tree(struct mount *mnt, int propagate) { LIST_HEAD(tmp_list); struct mount *p; for (p = mnt; p; p = next_mnt(p, mnt)) list_move(&p->mnt_hash, &tmp_list); if (propagate) propagate_umount(&tmp_list); list_for_each_entry(p, &tmp_list, mnt_hash) { list_del_init(&p->mnt_expire); list_del_init(&p->mnt_list); __touch_mnt_namespace(p->mnt_ns); p->mnt_ns = NULL; list_del_init(&p->mnt_child); if (mnt_has_parent(p)) { p->mnt_parent->mnt_ghosts++; put_mountpoint(p->mnt_mp); p->mnt_mp = NULL; } change_mnt_propagation(p, MS_PRIVATE); } list_splice(&tmp_list, &unmounted); } static void shrink_submounts(struct mount *mnt); static int do_umount(struct mount *mnt, int flags) { struct super_block *sb = mnt->mnt.mnt_sb; int retval; retval = security_sb_umount(&mnt->mnt, flags); if (retval) return retval; /* * Allow userspace to request a mountpoint be expired rather than * unmounting unconditionally. Unmount only happens if: * (1) the mark is already set (the mark is cleared by mntput()) * (2) the usage count == 1 [parent vfsmount] + 1 [sys_umount] */ if (flags & MNT_EXPIRE) { if (&mnt->mnt == current->fs->root.mnt || flags & (MNT_FORCE | MNT_DETACH)) return -EINVAL; /* * probably don't strictly need the lock here if we examined * all race cases, but it's a slowpath. */ br_write_lock(&vfsmount_lock); if (mnt_get_count(mnt) != 2) { br_write_unlock(&vfsmount_lock); return -EBUSY; } br_write_unlock(&vfsmount_lock); if (!xchg(&mnt->mnt_expiry_mark, 1)) return -EAGAIN; } /* * If we may have to abort operations to get out of this * mount, and they will themselves hold resources we must * allow the fs to do things. In the Unix tradition of * 'Gee thats tricky lets do it in userspace' the umount_begin * might fail to complete on the first run through as other tasks * must return, and the like. Thats for the mount program to worry * about for the moment. */ if (flags & MNT_FORCE && sb->s_op->umount_begin) { sb->s_op->umount_begin(sb); } /* * No sense to grab the lock for this test, but test itself looks * somewhat bogus. Suggestions for better replacement? * Ho-hum... In principle, we might treat that as umount + switch * to rootfs. GC would eventually take care of the old vfsmount. * Actually it makes sense, especially if rootfs would contain a * /reboot - static binary that would close all descriptors and * call reboot(9). Then init(8) could umount root and exec /reboot. */ if (&mnt->mnt == current->fs->root.mnt && !(flags & MNT_DETACH)) { /* * Special case for "unmounting" root ... * we just try to remount it readonly. */ down_write(&sb->s_umount); if (!(sb->s_flags & MS_RDONLY)) retval = do_remount_sb(sb, MS_RDONLY, NULL, 0); up_write(&sb->s_umount); return retval; } namespace_lock(); br_write_lock(&vfsmount_lock); event++; if (!(flags & MNT_DETACH)) shrink_submounts(mnt); retval = -EBUSY; if (flags & MNT_DETACH || !propagate_mount_busy(mnt, 2)) { if (!list_empty(&mnt->mnt_list)) umount_tree(mnt, 1); retval = 0; } br_write_unlock(&vfsmount_lock); namespace_unlock(); return retval; } /* * Is the caller allowed to modify his namespace? */ static inline bool may_mount(void) { return ns_capable(current->nsproxy->mnt_ns->user_ns, CAP_SYS_ADMIN); } /* * Now umount can handle mount points as well as block devices. * This is important for filesystems which use unnamed block devices. * * We now support a flag for forced unmount like the other 'big iron' * unixes. Our API is identical to OSF/1 to avoid making a mess of AMD */ SYSCALL_DEFINE2(umount, char __user *, name, int, flags) { struct path path; struct mount *mnt; int retval; int lookup_flags = 0; if (flags & ~(MNT_FORCE | MNT_DETACH | MNT_EXPIRE | UMOUNT_NOFOLLOW)) return -EINVAL; if (!may_mount()) return -EPERM; if (!(flags & UMOUNT_NOFOLLOW)) lookup_flags |= LOOKUP_FOLLOW; retval = user_path_at(AT_FDCWD, name, lookup_flags, &path); if (retval) goto out; mnt = real_mount(path.mnt); retval = -EINVAL; if (path.dentry != path.mnt->mnt_root) goto dput_and_out; if (!check_mnt(mnt)) goto dput_and_out; retval = do_umount(mnt, flags); dput_and_out: /* we mustn't call path_put() as that would clear mnt_expiry_mark */ dput(path.dentry); mntput_no_expire(mnt); out: return retval; } #ifdef __ARCH_WANT_SYS_OLDUMOUNT /* * The 2.0 compatible umount. No flags. */ SYSCALL_DEFINE1(oldumount, char __user *, name) { return sys_umount(name, 0); } #endif static bool mnt_ns_loop(struct path *path) { /* Could bind mounting the mount namespace inode cause a * mount namespace loop? */ struct inode *inode = path->dentry->d_inode; struct proc_ns *ei; struct mnt_namespace *mnt_ns; if (!proc_ns_inode(inode)) return false; ei = get_proc_ns(inode); if (ei->ns_ops != &mntns_operations) return false; mnt_ns = ei->ns; return current->nsproxy->mnt_ns->seq >= mnt_ns->seq; } struct mount *copy_tree(struct mount *mnt, struct dentry *dentry, int flag) { struct mount *res, *p, *q, *r, *parent; if (!(flag & CL_COPY_ALL) && IS_MNT_UNBINDABLE(mnt)) return ERR_PTR(-EINVAL); res = q = clone_mnt(mnt, dentry, flag); if (IS_ERR(q)) return q; q->mnt_mountpoint = mnt->mnt_mountpoint; p = mnt; list_for_each_entry(r, &mnt->mnt_mounts, mnt_child) { struct mount *s; if (!is_subdir(r->mnt_mountpoint, dentry)) continue; for (s = r; s; s = next_mnt(s, r)) { if (!(flag & CL_COPY_ALL) && IS_MNT_UNBINDABLE(s)) { s = skip_mnt_tree(s); continue; } while (p != s->mnt_parent) { p = p->mnt_parent; q = q->mnt_parent; } p = s; parent = q; q = clone_mnt(p, p->mnt.mnt_root, flag); if (IS_ERR(q)) goto out; br_write_lock(&vfsmount_lock); list_add_tail(&q->mnt_list, &res->mnt_list); attach_mnt(q, parent, p->mnt_mp); br_write_unlock(&vfsmount_lock); } } return res; out: if (res) { br_write_lock(&vfsmount_lock); umount_tree(res, 0); br_write_unlock(&vfsmount_lock); } return q; } /* Caller should check returned pointer for errors */ struct vfsmount *collect_mounts(struct path *path) { struct mount *tree; namespace_lock(); if (!check_mnt(real_mount(path->mnt))) tree = ERR_PTR(-EINVAL); else tree = copy_tree(real_mount(path->mnt), path->dentry, CL_COPY_ALL | CL_PRIVATE); namespace_unlock(); if (IS_ERR(tree)) return ERR_CAST(tree); return &tree->mnt; } void drop_collected_mounts(struct vfsmount *mnt) { namespace_lock(); br_write_lock(&vfsmount_lock); umount_tree(real_mount(mnt), 0); br_write_unlock(&vfsmount_lock); namespace_unlock(); } int iterate_mounts(int (*f)(struct vfsmount *, void *), void *arg, struct vfsmount *root) { struct mount *mnt; int res = f(root, arg); if (res) return res; list_for_each_entry(mnt, &real_mount(root)->mnt_list, mnt_list) { res = f(&mnt->mnt, arg); if (res) return res; } return 0; } static void cleanup_group_ids(struct mount *mnt, struct mount *end) { struct mount *p; for (p = mnt; p != end; p = next_mnt(p, mnt)) { if (p->mnt_group_id && !IS_MNT_SHARED(p)) mnt_release_group_id(p); } } static int invent_group_ids(struct mount *mnt, bool recurse) { struct mount *p; for (p = mnt; p; p = recurse ? next_mnt(p, mnt) : NULL) { if (!p->mnt_group_id && !IS_MNT_SHARED(p)) { int err = mnt_alloc_group_id(p); if (err) { cleanup_group_ids(mnt, p); return err; } } } return 0; } /* * @source_mnt : mount tree to be attached * @nd : place the mount tree @source_mnt is attached * @parent_nd : if non-null, detach the source_mnt from its parent and * store the parent mount and mountpoint dentry. * (done when source_mnt is moved) * * NOTE: in the table below explains the semantics when a source mount * of a given type is attached to a destination mount of a given type. * --------------------------------------------------------------------------- * | BIND MOUNT OPERATION | * |************************************************************************** * | source-->| shared | private | slave | unbindable | * | dest | | | | | * | | | | | | | * | v | | | | | * |************************************************************************** * | shared | shared (++) | shared (+) | shared(+++)| invalid | * | | | | | | * |non-shared| shared (+) | private | slave (*) | invalid | * *************************************************************************** * A bind operation clones the source mount and mounts the clone on the * destination mount. * * (++) the cloned mount is propagated to all the mounts in the propagation * tree of the destination mount and the cloned mount is added to * the peer group of the source mount. * (+) the cloned mount is created under the destination mount and is marked * as shared. The cloned mount is added to the peer group of the source * mount. * (+++) the mount is propagated to all the mounts in the propagation tree * of the destination mount and the cloned mount is made slave * of the same master as that of the source mount. The cloned mount * is marked as 'shared and slave'. * (*) the cloned mount is made a slave of the same master as that of the * source mount. * * --------------------------------------------------------------------------- * | MOVE MOUNT OPERATION | * |************************************************************************** * | source-->| shared | private | slave | unbindable | * | dest | | | | | * | | | | | | | * | v | | | | | * |************************************************************************** * | shared | shared (+) | shared (+) | shared(+++) | invalid | * | | | | | | * |non-shared| shared (+*) | private | slave (*) | unbindable | * *************************************************************************** * * (+) the mount is moved to the destination. And is then propagated to * all the mounts in the propagation tree of the destination mount. * (+*) the mount is moved to the destination. * (+++) the mount is moved to the destination and is then propagated to * all the mounts belonging to the destination mount's propagation tree. * the mount is marked as 'shared and slave'. * (*) the mount continues to be a slave at the new location. * * if the source mount is a tree, the operations explained above is * applied to each mount in the tree. * Must be called without spinlocks held, since this function can sleep * in allocations. */ static int attach_recursive_mnt(struct mount *source_mnt, struct mount *dest_mnt, struct mountpoint *dest_mp, struct path *parent_path) { LIST_HEAD(tree_list); struct mount *child, *p; int err; if (IS_MNT_SHARED(dest_mnt)) { err = invent_group_ids(source_mnt, true); if (err) goto out; } err = propagate_mnt(dest_mnt, dest_mp, source_mnt, &tree_list); if (err) goto out_cleanup_ids; br_write_lock(&vfsmount_lock); if (IS_MNT_SHARED(dest_mnt)) { for (p = source_mnt; p; p = next_mnt(p, source_mnt)) set_mnt_shared(p); } if (parent_path) { detach_mnt(source_mnt, parent_path); attach_mnt(source_mnt, dest_mnt, dest_mp); touch_mnt_namespace(source_mnt->mnt_ns); } else { mnt_set_mountpoint(dest_mnt, dest_mp, source_mnt); commit_tree(source_mnt); } list_for_each_entry_safe(child, p, &tree_list, mnt_hash) { list_del_init(&child->mnt_hash); commit_tree(child); } br_write_unlock(&vfsmount_lock); return 0; out_cleanup_ids: if (IS_MNT_SHARED(dest_mnt)) cleanup_group_ids(source_mnt, NULL); out: return err; } static struct mountpoint *lock_mount(struct path *path) { struct vfsmount *mnt; struct dentry *dentry = path->dentry; retry: mutex_lock(&dentry->d_inode->i_mutex); if (unlikely(cant_mount(dentry))) { mutex_unlock(&dentry->d_inode->i_mutex); return ERR_PTR(-ENOENT); } namespace_lock(); mnt = lookup_mnt(path); if (likely(!mnt)) { struct mountpoint *mp = new_mountpoint(dentry); if (IS_ERR(mp)) { namespace_unlock(); mutex_unlock(&dentry->d_inode->i_mutex); return mp; } return mp; } namespace_unlock(); mutex_unlock(&path->dentry->d_inode->i_mutex); path_put(path); path->mnt = mnt; dentry = path->dentry = dget(mnt->mnt_root); goto retry; } static void unlock_mount(struct mountpoint *where) { struct dentry *dentry = where->m_dentry; put_mountpoint(where); namespace_unlock(); mutex_unlock(&dentry->d_inode->i_mutex); } static int graft_tree(struct mount *mnt, struct mount *p, struct mountpoint *mp) { if (mnt->mnt.mnt_sb->s_flags & MS_NOUSER) return -EINVAL; if (S_ISDIR(mp->m_dentry->d_inode->i_mode) != S_ISDIR(mnt->mnt.mnt_root->d_inode->i_mode)) return -ENOTDIR; return attach_recursive_mnt(mnt, p, mp, NULL); } /* * Sanity check the flags to change_mnt_propagation. */ static int flags_to_propagation_type(int flags) { int type = flags & ~(MS_REC | MS_SILENT); /* Fail if any non-propagation flags are set */ if (type & ~(MS_SHARED | MS_PRIVATE | MS_SLAVE | MS_UNBINDABLE)) return 0; /* Only one propagation flag should be set */ if (!is_power_of_2(type)) return 0; return type; } /* * recursively change the type of the mountpoint. */ static int do_change_type(struct path *path, int flag) { struct mount *m; struct mount *mnt = real_mount(path->mnt); int recurse = flag & MS_REC; int type; int err = 0; if (path->dentry != path->mnt->mnt_root) return -EINVAL; type = flags_to_propagation_type(flag); if (!type) return -EINVAL; namespace_lock(); if (type == MS_SHARED) { err = invent_group_ids(mnt, recurse); if (err) goto out_unlock; } br_write_lock(&vfsmount_lock); for (m = mnt; m; m = (recurse ? next_mnt(m, mnt) : NULL)) change_mnt_propagation(m, type); br_write_unlock(&vfsmount_lock); out_unlock: namespace_unlock(); return err; } /* * do loopback mount. */ static int do_loopback(struct path *path, const char *old_name, int recurse) { struct path old_path; struct mount *mnt = NULL, *old, *parent; struct mountpoint *mp; int err; if (!old_name || !*old_name) return -EINVAL; err = kern_path(old_name, LOOKUP_FOLLOW|LOOKUP_AUTOMOUNT, &old_path); if (err) return err; err = -EINVAL; if (mnt_ns_loop(&old_path)) goto out; mp = lock_mount(path); err = PTR_ERR(mp); if (IS_ERR(mp)) goto out; old = real_mount(old_path.mnt); parent = real_mount(path->mnt); err = -EINVAL; if (IS_MNT_UNBINDABLE(old)) goto out2; if (!check_mnt(parent) || !check_mnt(old)) goto out2; if (recurse) mnt = copy_tree(old, old_path.dentry, 0); else mnt = clone_mnt(old, old_path.dentry, 0); if (IS_ERR(mnt)) { err = PTR_ERR(mnt); goto out2; } err = graft_tree(mnt, parent, mp); if (err) { br_write_lock(&vfsmount_lock); umount_tree(mnt, 0); br_write_unlock(&vfsmount_lock); } out2: unlock_mount(mp); out: path_put(&old_path); return err; } static int change_mount_flags(struct vfsmount *mnt, int ms_flags) { int error = 0; int readonly_request = 0; if (ms_flags & MS_RDONLY) readonly_request = 1; if (readonly_request == __mnt_is_readonly(mnt)) return 0; if (mnt->mnt_flags & MNT_LOCK_READONLY) return -EPERM; if (readonly_request) error = mnt_make_readonly(real_mount(mnt)); else __mnt_unmake_readonly(real_mount(mnt)); return error; } /* * change filesystem flags. dir should be a physical root of filesystem. * If you've mounted a non-root directory somewhere and want to do remount * on it - tough luck. */ static int do_remount(struct path *path, int flags, int mnt_flags, void *data) { int err; struct super_block *sb = path->mnt->mnt_sb; struct mount *mnt = real_mount(path->mnt); if (!check_mnt(mnt)) return -EINVAL; if (path->dentry != path->mnt->mnt_root) return -EINVAL; err = security_sb_remount(sb, data); if (err) return err; down_write(&sb->s_umount); if (flags & MS_BIND) err = change_mount_flags(path->mnt, flags); else if (!capable(CAP_SYS_ADMIN)) err = -EPERM; else err = do_remount_sb(sb, flags, data, 0); if (!err) { br_write_lock(&vfsmount_lock); mnt_flags |= mnt->mnt.mnt_flags & MNT_PROPAGATION_MASK; mnt->mnt.mnt_flags = mnt_flags; br_write_unlock(&vfsmount_lock); } up_write(&sb->s_umount); if (!err) { br_write_lock(&vfsmount_lock); touch_mnt_namespace(mnt->mnt_ns); br_write_unlock(&vfsmount_lock); } return err; } static inline int tree_contains_unbindable(struct mount *mnt) { struct mount *p; for (p = mnt; p; p = next_mnt(p, mnt)) { if (IS_MNT_UNBINDABLE(p)) return 1; } return 0; } static int do_move_mount(struct path *path, const char *old_name) { struct path old_path, parent_path; struct mount *p; struct mount *old; struct mountpoint *mp; int err; if (!old_name || !*old_name) return -EINVAL; err = kern_path(old_name, LOOKUP_FOLLOW, &old_path); if (err) return err; mp = lock_mount(path); err = PTR_ERR(mp); if (IS_ERR(mp)) goto out; old = real_mount(old_path.mnt); p = real_mount(path->mnt); err = -EINVAL; if (!check_mnt(p) || !check_mnt(old)) goto out1; err = -EINVAL; if (old_path.dentry != old_path.mnt->mnt_root) goto out1; if (!mnt_has_parent(old)) goto out1; if (S_ISDIR(path->dentry->d_inode->i_mode) != S_ISDIR(old_path.dentry->d_inode->i_mode)) goto out1; /* * Don't move a mount residing in a shared parent. */ if (IS_MNT_SHARED(old->mnt_parent)) goto out1; /* * Don't move a mount tree containing unbindable mounts to a destination * mount which is shared. */ if (IS_MNT_SHARED(p) && tree_contains_unbindable(old)) goto out1; err = -ELOOP; for (; mnt_has_parent(p); p = p->mnt_parent) if (p == old) goto out1; err = attach_recursive_mnt(old, real_mount(path->mnt), mp, &parent_path); if (err) goto out1; /* if the mount is moved, it should no longer be expire * automatically */ list_del_init(&old->mnt_expire); out1: unlock_mount(mp); out: if (!err) path_put(&parent_path); path_put(&old_path); return err; } static struct vfsmount *fs_set_subtype(struct vfsmount *mnt, const char *fstype) { int err; const char *subtype = strchr(fstype, '.'); if (subtype) { subtype++; err = -EINVAL; if (!subtype[0]) goto err; } else subtype = ""; mnt->mnt_sb->s_subtype = kstrdup(subtype, GFP_KERNEL); err = -ENOMEM; if (!mnt->mnt_sb->s_subtype) goto err; return mnt; err: mntput(mnt); return ERR_PTR(err); } /* * add a mount into a namespace's mount tree */ static int do_add_mount(struct mount *newmnt, struct path *path, int mnt_flags) { struct mountpoint *mp; struct mount *parent; int err; mnt_flags &= ~(MNT_SHARED | MNT_WRITE_HOLD | MNT_INTERNAL); mp = lock_mount(path); if (IS_ERR(mp)) return PTR_ERR(mp); parent = real_mount(path->mnt); err = -EINVAL; if (unlikely(!check_mnt(parent))) { /* that's acceptable only for automounts done in private ns */ if (!(mnt_flags & MNT_SHRINKABLE)) goto unlock; /* ... and for those we'd better have mountpoint still alive */ if (!parent->mnt_ns) goto unlock; } /* Refuse the same filesystem on the same mount point */ err = -EBUSY; if (path->mnt->mnt_sb == newmnt->mnt.mnt_sb && path->mnt->mnt_root == path->dentry) goto unlock; err = -EINVAL; if (S_ISLNK(newmnt->mnt.mnt_root->d_inode->i_mode)) goto unlock; newmnt->mnt.mnt_flags = mnt_flags; err = graft_tree(newmnt, parent, mp); unlock: unlock_mount(mp); return err; } /* * create a new mount for userspace and request it to be added into the * namespace's tree */ static int do_new_mount(struct path *path, const char *fstype, int flags, int mnt_flags, const char *name, void *data) { struct file_system_type *type; struct user_namespace *user_ns = current->nsproxy->mnt_ns->user_ns; struct vfsmount *mnt; int err; if (!fstype) return -EINVAL; type = get_fs_type(fstype); if (!type) return -ENODEV; if (user_ns != &init_user_ns) { if (!(type->fs_flags & FS_USERNS_MOUNT)) { put_filesystem(type); return -EPERM; } /* Only in special cases allow devices from mounts * created outside the initial user namespace. */ if (!(type->fs_flags & FS_USERNS_DEV_MOUNT)) { flags |= MS_NODEV; mnt_flags |= MNT_NODEV; } } mnt = vfs_kern_mount(type, flags, name, data); if (!IS_ERR(mnt) && (type->fs_flags & FS_HAS_SUBTYPE) && !mnt->mnt_sb->s_subtype) mnt = fs_set_subtype(mnt, fstype); put_filesystem(type); if (IS_ERR(mnt)) return PTR_ERR(mnt); err = do_add_mount(real_mount(mnt), path, mnt_flags); if (err) mntput(mnt); return err; } int finish_automount(struct vfsmount *m, struct path *path) { struct mount *mnt = real_mount(m); int err; /* The new mount record should have at least 2 refs to prevent it being * expired before we get a chance to add it */ BUG_ON(mnt_get_count(mnt) < 2); if (m->mnt_sb == path->mnt->mnt_sb && m->mnt_root == path->dentry) { err = -ELOOP; goto fail; } err = do_add_mount(mnt, path, path->mnt->mnt_flags | MNT_SHRINKABLE); if (!err) return 0; fail: /* remove m from any expiration list it may be on */ if (!list_empty(&mnt->mnt_expire)) { namespace_lock(); br_write_lock(&vfsmount_lock); list_del_init(&mnt->mnt_expire); br_write_unlock(&vfsmount_lock); namespace_unlock(); } mntput(m); mntput(m); return err; } /** * mnt_set_expiry - Put a mount on an expiration list * @mnt: The mount to list. * @expiry_list: The list to add the mount to. */ void mnt_set_expiry(struct vfsmount *mnt, struct list_head *expiry_list) { namespace_lock(); br_write_lock(&vfsmount_lock); list_add_tail(&real_mount(mnt)->mnt_expire, expiry_list); br_write_unlock(&vfsmount_lock); namespace_unlock(); } EXPORT_SYMBOL(mnt_set_expiry); /* * process a list of expirable mountpoints with the intent of discarding any * mountpoints that aren't in use and haven't been touched since last we came * here */ void mark_mounts_for_expiry(struct list_head *mounts) { struct mount *mnt, *next; LIST_HEAD(graveyard); if (list_empty(mounts)) return; namespace_lock(); br_write_lock(&vfsmount_lock); /* extract from the expiration list every vfsmount that matches the * following criteria: * - only referenced by its parent vfsmount * - still marked for expiry (marked on the last call here; marks are * cleared by mntput()) */ list_for_each_entry_safe(mnt, next, mounts, mnt_expire) { if (!xchg(&mnt->mnt_expiry_mark, 1) || propagate_mount_busy(mnt, 1)) continue; list_move(&mnt->mnt_expire, &graveyard); } while (!list_empty(&graveyard)) { mnt = list_first_entry(&graveyard, struct mount, mnt_expire); touch_mnt_namespace(mnt->mnt_ns); umount_tree(mnt, 1); } br_write_unlock(&vfsmount_lock); namespace_unlock(); } EXPORT_SYMBOL_GPL(mark_mounts_for_expiry); /* * Ripoff of 'select_parent()' * * search the list of submounts for a given mountpoint, and move any * shrinkable submounts to the 'graveyard' list. */ static int select_submounts(struct mount *parent, struct list_head *graveyard) { struct mount *this_parent = parent; struct list_head *next; int found = 0; repeat: next = this_parent->mnt_mounts.next; resume: while (next != &this_parent->mnt_mounts) { struct list_head *tmp = next; struct mount *mnt = list_entry(tmp, struct mount, mnt_child); next = tmp->next; if (!(mnt->mnt.mnt_flags & MNT_SHRINKABLE)) continue; /* * Descend a level if the d_mounts list is non-empty. */ if (!list_empty(&mnt->mnt_mounts)) { this_parent = mnt; goto repeat; } if (!propagate_mount_busy(mnt, 1)) { list_move_tail(&mnt->mnt_expire, graveyard); found++; } } /* * All done at this level ... ascend and resume the search */ if (this_parent != parent) { next = this_parent->mnt_child.next; this_parent = this_parent->mnt_parent; goto resume; } return found; } /* * process a list of expirable mountpoints with the intent of discarding any * submounts of a specific parent mountpoint * * vfsmount_lock must be held for write */ static void shrink_submounts(struct mount *mnt) { LIST_HEAD(graveyard); struct mount *m; /* extract submounts of 'mountpoint' from the expiration list */ while (select_submounts(mnt, &graveyard)) { while (!list_empty(&graveyard)) { m = list_first_entry(&graveyard, struct mount, mnt_expire); touch_mnt_namespace(m->mnt_ns); umount_tree(m, 1); } } } /* * Some copy_from_user() implementations do not return the exact number of * bytes remaining to copy on a fault. But copy_mount_options() requires that. * Note that this function differs from copy_from_user() in that it will oops * on bad values of `to', rather than returning a short copy. */ static long exact_copy_from_user(void *to, const void __user * from, unsigned long n) { char *t = to; const char __user *f = from; char c; if (!access_ok(VERIFY_READ, from, n)) return n; while (n) { if (__get_user(c, f)) { memset(t, 0, n); break; } *t++ = c; f++; n--; } return n; } int copy_mount_options(const void __user * data, unsigned long *where) { int i; unsigned long page; unsigned long size; *where = 0; if (!data) return 0; if (!(page = __get_free_page(GFP_KERNEL))) return -ENOMEM; /* We only care that *some* data at the address the user * gave us is valid. Just in case, we'll zero * the remainder of the page. */ /* copy_from_user cannot cross TASK_SIZE ! */ size = TASK_SIZE - (unsigned long)data; if (size > PAGE_SIZE) size = PAGE_SIZE; i = size - exact_copy_from_user((void *)page, data, size); if (!i) { free_page(page); return -EFAULT; } if (i != PAGE_SIZE) memset((char *)page + i, 0, PAGE_SIZE - i); *where = page; return 0; } int copy_mount_string(const void __user *data, char **where) { char *tmp; if (!data) { *where = NULL; return 0; } tmp = strndup_user(data, PAGE_SIZE); if (IS_ERR(tmp)) return PTR_ERR(tmp); *where = tmp; return 0; } /* * Flags is a 32-bit value that allows up to 31 non-fs dependent flags to * be given to the mount() call (ie: read-only, no-dev, no-suid etc). * * data is a (void *) that can point to any structure up to * PAGE_SIZE-1 bytes, which can contain arbitrary fs-dependent * information (or be NULL). * * Pre-0.97 versions of mount() didn't have a flags word. * When the flags word was introduced its top half was required * to have the magic value 0xC0ED, and this remained so until 2.4.0-test9. * Therefore, if this magic number is present, it carries no information * and must be discarded. */ long do_mount(const char *dev_name, const char *dir_name, const char *type_page, unsigned long flags, void *data_page) { struct path path; int retval = 0; int mnt_flags = 0; /* Discard magic */ if ((flags & MS_MGC_MSK) == MS_MGC_VAL) flags &= ~MS_MGC_MSK; /* Basic sanity checks */ if (!dir_name || !*dir_name || !memchr(dir_name, 0, PAGE_SIZE)) return -EINVAL; if (data_page) ((char *)data_page)[PAGE_SIZE - 1] = 0; /* ... and get the mountpoint */ retval = kern_path(dir_name, LOOKUP_FOLLOW, &path); if (retval) return retval; retval = security_sb_mount(dev_name, &path, type_page, flags, data_page); if (!retval && !may_mount()) retval = -EPERM; if (retval) goto dput_out; /* Default to relatime unless overriden */ if (!(flags & MS_NOATIME)) mnt_flags |= MNT_RELATIME; /* Separate the per-mountpoint flags */ if (flags & MS_NOSUID) mnt_flags |= MNT_NOSUID; if (flags & MS_NODEV) mnt_flags |= MNT_NODEV; if (flags & MS_NOEXEC) mnt_flags |= MNT_NOEXEC; if (flags & MS_NOATIME) mnt_flags |= MNT_NOATIME; if (flags & MS_NODIRATIME) mnt_flags |= MNT_NODIRATIME; if (flags & MS_STRICTATIME) mnt_flags &= ~(MNT_RELATIME | MNT_NOATIME); if (flags & MS_RDONLY) mnt_flags |= MNT_READONLY; flags &= ~(MS_NOSUID | MS_NOEXEC | MS_NODEV | MS_ACTIVE | MS_BORN | MS_NOATIME | MS_NODIRATIME | MS_RELATIME| MS_KERNMOUNT | MS_STRICTATIME); if (flags & MS_REMOUNT) retval = do_remount(&path, flags & ~MS_REMOUNT, mnt_flags, data_page); else if (flags & MS_BIND) retval = do_loopback(&path, dev_name, flags & MS_REC); else if (flags & (MS_SHARED | MS_PRIVATE | MS_SLAVE | MS_UNBINDABLE)) retval = do_change_type(&path, flags); else if (flags & MS_MOVE) retval = do_move_mount(&path, dev_name); else retval = do_new_mount(&path, type_page, flags, mnt_flags, dev_name, data_page); dput_out: path_put(&path); return retval; } static void free_mnt_ns(struct mnt_namespace *ns) { proc_free_inum(ns->proc_inum); put_user_ns(ns->user_ns); kfree(ns); } /* * Assign a sequence number so we can detect when we attempt to bind * mount a reference to an older mount namespace into the current * mount namespace, preventing reference counting loops. A 64bit * number incrementing at 10Ghz will take 12,427 years to wrap which * is effectively never, so we can ignore the possibility. */ static atomic64_t mnt_ns_seq = ATOMIC64_INIT(1); static struct mnt_namespace *alloc_mnt_ns(struct user_namespace *user_ns) { struct mnt_namespace *new_ns; int ret; new_ns = kmalloc(sizeof(struct mnt_namespace), GFP_KERNEL); if (!new_ns) return ERR_PTR(-ENOMEM); ret = proc_alloc_inum(&new_ns->proc_inum); if (ret) { kfree(new_ns); return ERR_PTR(ret); } new_ns->seq = atomic64_add_return(1, &mnt_ns_seq); atomic_set(&new_ns->count, 1); new_ns->root = NULL; INIT_LIST_HEAD(&new_ns->list); init_waitqueue_head(&new_ns->poll); new_ns->event = 0; new_ns->user_ns = get_user_ns(user_ns); return new_ns; } /* * Allocate a new namespace structure and populate it with contents * copied from the namespace of the passed in task structure. */ static struct mnt_namespace *dup_mnt_ns(struct mnt_namespace *mnt_ns, struct user_namespace *user_ns, struct fs_struct *fs) { struct mnt_namespace *new_ns; struct vfsmount *rootmnt = NULL, *pwdmnt = NULL; struct mount *p, *q; struct mount *old = mnt_ns->root; struct mount *new; int copy_flags; new_ns = alloc_mnt_ns(user_ns); if (IS_ERR(new_ns)) return new_ns; namespace_lock(); /* First pass: copy the tree topology */ copy_flags = CL_COPY_ALL | CL_EXPIRE; if (user_ns != mnt_ns->user_ns) copy_flags |= CL_SHARED_TO_SLAVE | CL_UNPRIVILEGED; new = copy_tree(old, old->mnt.mnt_root, copy_flags); if (IS_ERR(new)) { namespace_unlock(); free_mnt_ns(new_ns); return ERR_CAST(new); } new_ns->root = new; br_write_lock(&vfsmount_lock); list_add_tail(&new_ns->list, &new->mnt_list); br_write_unlock(&vfsmount_lock); /* * Second pass: switch the tsk->fs->* elements and mark new vfsmounts * as belonging to new namespace. We have already acquired a private * fs_struct, so tsk->fs->lock is not needed. */ p = old; q = new; while (p) { q->mnt_ns = new_ns; if (fs) { if (&p->mnt == fs->root.mnt) { fs->root.mnt = mntget(&q->mnt); rootmnt = &p->mnt; } if (&p->mnt == fs->pwd.mnt) { fs->pwd.mnt = mntget(&q->mnt); pwdmnt = &p->mnt; } } p = next_mnt(p, old); q = next_mnt(q, new); } namespace_unlock(); if (rootmnt) mntput(rootmnt); if (pwdmnt) mntput(pwdmnt); return new_ns; } struct mnt_namespace *copy_mnt_ns(unsigned long flags, struct mnt_namespace *ns, struct user_namespace *user_ns, struct fs_struct *new_fs) { struct mnt_namespace *new_ns; BUG_ON(!ns); get_mnt_ns(ns); if (!(flags & CLONE_NEWNS)) return ns; new_ns = dup_mnt_ns(ns, user_ns, new_fs); put_mnt_ns(ns); return new_ns; } /** * create_mnt_ns - creates a private namespace and adds a root filesystem * @mnt: pointer to the new root filesystem mountpoint */ static struct mnt_namespace *create_mnt_ns(struct vfsmount *m) { struct mnt_namespace *new_ns = alloc_mnt_ns(&init_user_ns); if (!IS_ERR(new_ns)) { struct mount *mnt = real_mount(m); mnt->mnt_ns = new_ns; new_ns->root = mnt; list_add(&mnt->mnt_list, &new_ns->list); } else { mntput(m); } return new_ns; } struct dentry *mount_subtree(struct vfsmount *mnt, const char *name) { struct mnt_namespace *ns; struct super_block *s; struct path path; int err; ns = create_mnt_ns(mnt); if (IS_ERR(ns)) return ERR_CAST(ns); err = vfs_path_lookup(mnt->mnt_root, mnt, name, LOOKUP_FOLLOW|LOOKUP_AUTOMOUNT, &path); put_mnt_ns(ns); if (err) return ERR_PTR(err); /* trade a vfsmount reference for active sb one */ s = path.mnt->mnt_sb; atomic_inc(&s->s_active); mntput(path.mnt); /* lock the sucker */ down_write(&s->s_umount); /* ... and return the root of (sub)tree on it */ return path.dentry; } EXPORT_SYMBOL(mount_subtree); SYSCALL_DEFINE5(mount, char __user *, dev_name, char __user *, dir_name, char __user *, type, unsigned long, flags, void __user *, data) { int ret; char *kernel_type; struct filename *kernel_dir; char *kernel_dev; unsigned long data_page; ret = copy_mount_string(type, &kernel_type); if (ret < 0) goto out_type; kernel_dir = getname(dir_name); if (IS_ERR(kernel_dir)) { ret = PTR_ERR(kernel_dir); goto out_dir; } ret = copy_mount_string(dev_name, &kernel_dev); if (ret < 0) goto out_dev; ret = copy_mount_options(data, &data_page); if (ret < 0) goto out_data; ret = do_mount(kernel_dev, kernel_dir->name, kernel_type, flags, (void *) data_page); free_page(data_page); out_data: kfree(kernel_dev); out_dev: putname(kernel_dir); out_dir: kfree(kernel_type); out_type: return ret; } /* * Return true if path is reachable from root * * namespace_sem or vfsmount_lock is held */ bool is_path_reachable(struct mount *mnt, struct dentry *dentry, const struct path *root) { while (&mnt->mnt != root->mnt && mnt_has_parent(mnt)) { dentry = mnt->mnt_mountpoint; mnt = mnt->mnt_parent; } return &mnt->mnt == root->mnt && is_subdir(dentry, root->dentry); } int path_is_under(struct path *path1, struct path *path2) { int res; br_read_lock(&vfsmount_lock); res = is_path_reachable(real_mount(path1->mnt), path1->dentry, path2); br_read_unlock(&vfsmount_lock); return res; } EXPORT_SYMBOL(path_is_under); /* * pivot_root Semantics: * Moves the root file system of the current process to the directory put_old, * makes new_root as the new root file system of the current process, and sets * root/cwd of all processes which had them on the current root to new_root. * * Restrictions: * The new_root and put_old must be directories, and must not be on the * same file system as the current process root. The put_old must be * underneath new_root, i.e. adding a non-zero number of /.. to the string * pointed to by put_old must yield the same directory as new_root. No other * file system may be mounted on put_old. After all, new_root is a mountpoint. * * Also, the current root cannot be on the 'rootfs' (initial ramfs) filesystem. * See Documentation/filesystems/ramfs-rootfs-initramfs.txt for alternatives * in this situation. * * Notes: * - we don't move root/cwd if they are not at the root (reason: if something * cared enough to change them, it's probably wrong to force them elsewhere) * - it's okay to pick a root that isn't the root of a file system, e.g. * /nfs/my_root where /nfs is the mount point. It must be a mountpoint, * though, so you may need to say mount --bind /nfs/my_root /nfs/my_root * first. */ SYSCALL_DEFINE2(pivot_root, const char __user *, new_root, const char __user *, put_old) { struct path new, old, parent_path, root_parent, root; struct mount *new_mnt, *root_mnt, *old_mnt; struct mountpoint *old_mp, *root_mp; int error; if (!may_mount()) return -EPERM; error = user_path_dir(new_root, &new); if (error) goto out0; error = user_path_dir(put_old, &old); if (error) goto out1; error = security_sb_pivotroot(&old, &new); if (error) goto out2; get_fs_root(current->fs, &root); old_mp = lock_mount(&old); error = PTR_ERR(old_mp); if (IS_ERR(old_mp)) goto out3; error = -EINVAL; new_mnt = real_mount(new.mnt); root_mnt = real_mount(root.mnt); old_mnt = real_mount(old.mnt); if (IS_MNT_SHARED(old_mnt) || IS_MNT_SHARED(new_mnt->mnt_parent) || IS_MNT_SHARED(root_mnt->mnt_parent)) goto out4; if (!check_mnt(root_mnt) || !check_mnt(new_mnt)) goto out4; error = -ENOENT; if (d_unlinked(new.dentry)) goto out4; error = -EBUSY; if (new_mnt == root_mnt || old_mnt == root_mnt) goto out4; /* loop, on the same file system */ error = -EINVAL; if (root.mnt->mnt_root != root.dentry) goto out4; /* not a mountpoint */ if (!mnt_has_parent(root_mnt)) goto out4; /* not attached */ root_mp = root_mnt->mnt_mp; if (new.mnt->mnt_root != new.dentry) goto out4; /* not a mountpoint */ if (!mnt_has_parent(new_mnt)) goto out4; /* not attached */ /* make sure we can reach put_old from new_root */ if (!is_path_reachable(old_mnt, old.dentry, &new)) goto out4; /* make certain new is below the root */ if (!is_path_reachable(new_mnt, new.dentry, &root)) goto out4; root_mp->m_count++; /* pin it so it won't go away */ br_write_lock(&vfsmount_lock); detach_mnt(new_mnt, &parent_path); detach_mnt(root_mnt, &root_parent); /* mount old root on put_old */ attach_mnt(root_mnt, old_mnt, old_mp); /* mount new_root on / */ attach_mnt(new_mnt, real_mount(root_parent.mnt), root_mp); touch_mnt_namespace(current->nsproxy->mnt_ns); br_write_unlock(&vfsmount_lock); chroot_fs_refs(&root, &new); put_mountpoint(root_mp); error = 0; out4: unlock_mount(old_mp); if (!error) { path_put(&root_parent); path_put(&parent_path); } out3: path_put(&root); out2: path_put(&old); out1: path_put(&new); out0: return error; } static void __init init_mount_tree(void) { struct vfsmount *mnt; struct mnt_namespace *ns; struct path root; struct file_system_type *type; type = get_fs_type("rootfs"); if (!type) panic("Can't find rootfs type"); mnt = vfs_kern_mount(type, 0, "rootfs", NULL); put_filesystem(type); if (IS_ERR(mnt)) panic("Can't create rootfs"); ns = create_mnt_ns(mnt); if (IS_ERR(ns)) panic("Can't allocate initial namespace"); init_task.nsproxy->mnt_ns = ns; get_mnt_ns(ns); root.mnt = mnt; root.dentry = mnt->mnt_root; set_fs_pwd(current->fs, &root); set_fs_root(current->fs, &root); } void __init mnt_init(void) { unsigned u; int err; init_rwsem(&namespace_sem); mnt_cache = kmem_cache_create("mnt_cache", sizeof(struct mount), 0, SLAB_HWCACHE_ALIGN | SLAB_PANIC, NULL); mount_hashtable = (struct list_head *)__get_free_page(GFP_ATOMIC); mountpoint_hashtable = (struct list_head *)__get_free_page(GFP_ATOMIC); if (!mount_hashtable || !mountpoint_hashtable) panic("Failed to allocate mount hash table\n"); printk(KERN_INFO "Mount-cache hash table entries: %lu\n", HASH_SIZE); for (u = 0; u < HASH_SIZE; u++) INIT_LIST_HEAD(&mount_hashtable[u]); for (u = 0; u < HASH_SIZE; u++) INIT_LIST_HEAD(&mountpoint_hashtable[u]); br_lock_init(&vfsmount_lock); err = sysfs_init(); if (err) printk(KERN_WARNING "%s: sysfs_init error: %d\n", __func__, err); fs_kobj = kobject_create_and_add("fs", NULL); if (!fs_kobj) printk(KERN_WARNING "%s: kobj create error\n", __func__); init_rootfs(); init_mount_tree(); } void put_mnt_ns(struct mnt_namespace *ns) { if (!atomic_dec_and_test(&ns->count)) return; namespace_lock(); br_write_lock(&vfsmount_lock); umount_tree(ns->root, 0); br_write_unlock(&vfsmount_lock); namespace_unlock(); free_mnt_ns(ns); } struct vfsmount *kern_mount_data(struct file_system_type *type, void *data) { struct vfsmount *mnt; mnt = vfs_kern_mount(type, MS_KERNMOUNT, type->name, data); if (!IS_ERR(mnt)) { /* * it is a longterm mount, don't release mnt until * we unmount before file sys is unregistered */ real_mount(mnt)->mnt_ns = MNT_NS_INTERNAL; } return mnt; } EXPORT_SYMBOL_GPL(kern_mount_data); void kern_unmount(struct vfsmount *mnt) { /* release long term mount so mount point can be released */ if (!IS_ERR_OR_NULL(mnt)) { br_write_lock(&vfsmount_lock); real_mount(mnt)->mnt_ns = NULL; br_write_unlock(&vfsmount_lock); mntput(mnt); } } EXPORT_SYMBOL(kern_unmount); bool our_mnt(struct vfsmount *mnt) { return check_mnt(real_mount(mnt)); } bool current_chrooted(void) { /* Does the current process have a non-standard root */ struct path ns_root; struct path fs_root; bool chrooted; /* Find the namespace root */ ns_root.mnt = &current->nsproxy->mnt_ns->root->mnt; ns_root.dentry = ns_root.mnt->mnt_root; path_get(&ns_root); while (d_mountpoint(ns_root.dentry) && follow_down_one(&ns_root)) ; get_fs_root(current->fs, &fs_root); chrooted = !path_equal(&fs_root, &ns_root); path_put(&fs_root); path_put(&ns_root); return chrooted; } void update_mnt_policy(struct user_namespace *userns) { struct mnt_namespace *ns = current->nsproxy->mnt_ns; struct mount *mnt; down_read(&namespace_sem); list_for_each_entry(mnt, &ns->list, mnt_list) { switch (mnt->mnt.mnt_sb->s_magic) { case SYSFS_MAGIC: userns->may_mount_sysfs = true; break; case PROC_SUPER_MAGIC: userns->may_mount_proc = true; break; } if (userns->may_mount_sysfs && userns->may_mount_proc) break; } up_read(&namespace_sem); } static void *mntns_get(struct task_struct *task) { struct mnt_namespace *ns = NULL; struct nsproxy *nsproxy; rcu_read_lock(); nsproxy = task_nsproxy(task); if (nsproxy) { ns = nsproxy->mnt_ns; get_mnt_ns(ns); } rcu_read_unlock(); return ns; } static void mntns_put(void *ns) { put_mnt_ns(ns); } static int mntns_install(struct nsproxy *nsproxy, void *ns) { struct fs_struct *fs = current->fs; struct mnt_namespace *mnt_ns = ns; struct path root; if (!ns_capable(mnt_ns->user_ns, CAP_SYS_ADMIN) || !nsown_capable(CAP_SYS_CHROOT) || !nsown_capable(CAP_SYS_ADMIN)) return -EPERM; if (fs->users != 1) return -EINVAL; get_mnt_ns(mnt_ns); put_mnt_ns(nsproxy->mnt_ns); nsproxy->mnt_ns = mnt_ns; /* Find the root */ root.mnt = &mnt_ns->root->mnt; root.dentry = mnt_ns->root->mnt.mnt_root; path_get(&root); while(d_mountpoint(root.dentry) && follow_down_one(&root)) ; /* Update the pwd and root */ set_fs_pwd(fs, &root); set_fs_root(fs, &root); path_put(&root); return 0; } static unsigned int mntns_inum(void *ns) { struct mnt_namespace *mnt_ns = ns; return mnt_ns->proc_inum; } const struct proc_ns_operations mntns_operations = { .name = "mnt", .type = CLONE_NEWNS, .get = mntns_get, .put = mntns_put, .install = mntns_install, .inum = mntns_inum, };
Koloses/kernel_j5
fs/namespace.c
C
gpl-2.0
71,550
[ 30522, 1013, 1008, 1008, 11603, 1013, 1042, 2015, 1013, 3415, 15327, 1012, 1039, 1008, 1008, 1006, 1039, 1007, 9385, 2632, 6819, 3217, 2456, 1010, 2541, 1008, 2207, 2104, 14246, 2140, 1058, 2475, 1012, 1008, 1008, 2241, 2006, 3642, 2013, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<!DOCTYPE html> <html> <script id="vertex-shader" type="x-shader/x-vertex"> attribute vec4 vPosition; attribute vec4 vColor; varying vec4 fColor; void main() { gl_Position = vPosition; fColor = vColor; } </script> <script id="fragment-shader" type="x-shader/x-fragment"> precision mediump float; // For the colour of the vertices varying vec4 fColor; void main() { gl_FragColor = fColor; } </script> <script type="text/javascript" src="../Common/webgl-utils.js"></script> <script type="text/javascript" src="../Common/initShaders.js"></script> <script type="text/javascript" src="../Common/MV.js"></script> <script type="text/javascript" src="draw_lines.js"></script> <body> <canvas id="gl-canvas" width="512" height="512"> Oops ... your browser doesn't support the HTML5 canvas element </canvas> </body> <body> <div> Red: <input id="sliderred" type="range" min="0" max="255" step="1" value="128" /> <input type="text" id="textred" value="128" class="field left" size="3" readonly><br> Green: <input id="slidergreen" type="range" min="0" max="255" step="1" value="128" /> <input type="text" id="textgreen" value="128" class="field left" size="3" readonly> <br> Blue: <input id="sliderblue" type="range" min="0" max="255" step="1" value="128" /> <input type="text" id="textblue" value="128" class="field left" size="3" readonly> <br> Colour Preview: <input type="text" id="colourpreview" class="field left" size="3" style="background-color:#808080;" readonly><br> <button id="reset" type="button">Reset Canvas</button> </div> </html>
rayryeng/rayryeng.github.io
webgl-coursera/week2/draw_lines.html
HTML
mit
1,567
[ 30522, 1026, 999, 9986, 13874, 16129, 1028, 1026, 16129, 1028, 1026, 5896, 8909, 1027, 1000, 19449, 1011, 8703, 2099, 1000, 2828, 1027, 1000, 1060, 1011, 8703, 2099, 1013, 1060, 1011, 19449, 1000, 1028, 17961, 2310, 2278, 2549, 21210, 19234...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
#ifndef WAVEFRONT2GRAPHICS_H #define WAVEFRONT2GRAPHICS_H #include "../../ThirdPartyLibs/Wavefront/tiny_obj_loader.h" #include <vector> struct GLInstanceGraphicsShape* btgCreateGraphicsShapeFromWavefrontObj(const tinyobj::attrib_t& attribute, std::vector<tinyobj::shape_t>& shapes, bool flatShading = false); #endif //WAVEFRONT2GRAPHICS_H
MadManRises/Madgine
shared/bullet3-2.89/examples/Importers/ImportObjDemo/Wavefront2GLInstanceGraphicsShape.h
C
mit
343
[ 30522, 1001, 2065, 13629, 2546, 4400, 12792, 2475, 14773, 2015, 1035, 1044, 1001, 9375, 4400, 12792, 2475, 14773, 2015, 1035, 1044, 1001, 2421, 1000, 1012, 1012, 1013, 1012, 1012, 1013, 2353, 19362, 3723, 29521, 2015, 1013, 4400, 12792, 101...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
version https://git-lfs.github.com/spec/v1 oid sha256:277086ec0fb49c6da22640a41bd9d52e5e3503cc15ae358cd76662b81439df83 size 10713
yogeshsaroya/new-cdnjs
ajax/libs/yui/3.17.0/resize-base/resize-base-min.js
JavaScript
mit
130
[ 30522, 2544, 16770, 1024, 1013, 1013, 21025, 2102, 1011, 1048, 10343, 1012, 21025, 2705, 12083, 1012, 4012, 1013, 28699, 1013, 1058, 2487, 1051, 3593, 21146, 17788, 2575, 1024, 25578, 2692, 20842, 8586, 2692, 26337, 26224, 2278, 2575, 2850, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* * The implementation of the TRM.generateTRM methods * * author Christian Pesch */ #include "trm_wrapper.h" /* * Utility procedures. */ void setLongJavaMember(JNIEnv *env, jobject obj, char *field, unsigned long value) { jclass cls = (*env)->GetObjectClass(env, obj); jfieldID fid = (*env)->GetFieldID(env, cls, field, "J"); if(fid == 0) { return; } (*env)->SetLongField(env, obj, fid, value); } void setStringJavaMember(JNIEnv * env, jobject obj, char * field, char * value) { jstring string = (*env)->NewStringUTF(env, value); jclass cls = (*env)->GetObjectClass(env, obj); jfieldID fid = (*env)->GetFieldID(env, cls, field, "Ljava/lang/String;"); if(fid == 0) { return; } (*env)->SetObjectField(env, obj, fid, string); } /* ----------------------------------------------------------------------- */ /* Convert utf8-string to ucs1-string */ /* ----------------------------------------------------------------------- */ char* utf2ucs(const char *utf8, char *ucs, size_t n) { const char *pin; char *pout; unsigned char current, next; int i; for (i=0,pin=utf8,pout=ucs; i < n && *pin; i++,pin++,pout++) { current = *pin; if (current >= 0xE0) { /* we support only two-byte utf8 */ return NULL; } else if ((current & 0x80) == 0) /* one-byte utf8 */ *pout = current; else { /* two-byte utf8 */ next = *(++pin); if (next >= 0xC0) { /* illegal coding */ return NULL; } *pout = ((current & 3) << 6) + /* first two bits of first byte */ (next & 63); /* last six bits of second byte */ } } if (i < n) *pout = '\0'; return ucs; } JNIEXPORT jint JNICALL Java_org_metamusic_trm_TRM_generateTRMforMP3 (JNIEnv *javaEnv, jclass javaClass, jstring fileName, jlong durationL, jstring proxyServer, jint proxyPort, jobject result) { const char *file_name; const char *proxy_server; char signature[37]; unsigned long duration = durationL; int ret; file_name = (*javaEnv)->GetStringUTFChars(javaEnv, fileName, 0); proxy_server = (*javaEnv)->GetStringUTFChars(javaEnv, proxyServer, 0); // printf("file_name %s\n", file_name); ret = MP3_generateTRM(file_name, signature, &duration, proxy_server, proxyPort); // printf("duration %lu\n", duration); setLongJavaMember(javaEnv, result, "duration", duration); setStringJavaMember(javaEnv, result, "signature", signature); (*javaEnv)->ReleaseStringUTFChars(javaEnv, fileName, file_name); if(proxyServer != NULL) (*javaEnv)->ReleaseStringUTFChars(javaEnv, proxyServer, proxy_server); return ret; } JNIEXPORT jint JNICALL Java_org_metamusic_trm_TRM_generateTRMforWAV (JNIEnv *javaEnv, jclass javaClass, jstring fileName, jlong durationL, jstring proxyServer, jint proxyPort, jobject result) { const char *file_name; const char *proxy_server; char signature[37]; unsigned long duration = durationL; int ret; file_name = (*javaEnv)->GetStringUTFChars(javaEnv, fileName, 0); proxy_server = (*javaEnv)->GetStringUTFChars(javaEnv, proxyServer, 0); ret = Wav_generateTRM(file_name, signature, &duration, proxy_server, proxyPort); setLongJavaMember(javaEnv, result, "duration", duration); setStringJavaMember(javaEnv, result, "signature", signature); (*javaEnv)->ReleaseStringUTFChars(javaEnv, fileName, file_name); if(proxyServer != NULL) (*javaEnv)->ReleaseStringUTFChars(javaEnv, proxyServer, proxy_server); return ret; } JNIEXPORT jint JNICALL Java_org_metamusic_trm_TRM_generateTRMforOggVorbis (JNIEnv *javaEnv, jclass javaClass, jstring fileName, jlong durationL, jstring proxyServer, jint proxyPort, jobject result) { const char *file_name; const char *proxy_server; char signature[37]; unsigned long duration = durationL; int ret; file_name = (*javaEnv)->GetStringUTFChars(javaEnv, fileName, 0); proxy_server = (*javaEnv)->GetStringUTFChars(javaEnv, proxyServer, 0); ret = OggVorbis_generateTRM(file_name, signature, &duration, proxy_server, proxyPort); setLongJavaMember(javaEnv, result, "duration", duration); setStringJavaMember(javaEnv, result, "signature", signature); (*javaEnv)->ReleaseStringUTFChars(javaEnv, fileName, file_name); if(proxyServer != NULL) (*javaEnv)->ReleaseStringUTFChars(javaEnv, proxyServer, proxy_server); return ret; }
cpesch/MetaMusic
retrieval-tools/src/main/native/trm_wrapper.c
C
gpl-2.0
4,528
[ 30522, 1013, 1008, 1008, 1996, 7375, 1997, 1996, 19817, 2213, 1012, 9699, 16344, 2213, 4725, 1008, 1008, 3166, 3017, 21877, 11624, 1008, 1013, 1001, 2421, 1000, 19817, 2213, 1035, 10236, 4842, 1012, 1044, 1000, 1013, 1008, 1008, 9710, 8853,...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>mathcomp-field: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.13.2 / mathcomp-field - 1.6.2</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> mathcomp-field <small> 1.6.2 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-02-02 00:56:38 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-02-02 00:56:38 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils conf-gmp 4 Virtual package relying on a GMP lib system installation coq 8.13.2 Formal proof management system num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.10.2 The OCaml compiler (virtual package) ocaml-base-compiler 4.10.2 Official release 4.10.2 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.3 A library manager for OCaml zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers # opam file: opam-version: &quot;2.0&quot; name: &quot;coq-mathcomp-field&quot; version: &quot;1.6.2&quot; maintainer: &quot;Mathematical Components &lt;mathcomp-dev@sympa.inria.fr&gt;&quot; homepage: &quot;http://math-comp.github.io/math-comp/&quot; bug-reports: &quot;Mathematical Components &lt;mathcomp-dev@sympa.inria.fr&gt;&quot; license: &quot;CeCILL-B&quot; build: [ make &quot;-C&quot; &quot;mathcomp/field&quot; &quot;-j&quot; &quot;%{jobs}%&quot; ] install: [ make &quot;-C&quot; &quot;mathcomp/field&quot; &quot;install&quot; ] remove: [ &quot;sh&quot; &quot;-c&quot; &quot;rm -rf &#39;%{lib}%/coq/user-contrib/mathcomp/field&#39;&quot; ] depends: [ &quot;ocaml&quot; &quot;coq-mathcomp-solvable&quot; {= &quot;1.6.2&quot;} ] tags: [ &quot;keyword:algebra&quot; &quot;keyword:field&quot; &quot;keyword:small scale reflection&quot; &quot;keyword:mathematical components&quot; &quot;keyword:odd order theorem&quot; ] authors: [ &quot;Jeremy Avigad &lt;&gt;&quot; &quot;Andrea Asperti &lt;&gt;&quot; &quot;Stephane Le Roux &lt;&gt;&quot; &quot;Yves Bertot &lt;&gt;&quot; &quot;Laurence Rideau &lt;&gt;&quot; &quot;Enrico Tassi &lt;&gt;&quot; &quot;Ioana Pasca &lt;&gt;&quot; &quot;Georges Gonthier &lt;&gt;&quot; &quot;Sidi Ould Biha &lt;&gt;&quot; &quot;Cyril Cohen &lt;&gt;&quot; &quot;Francois Garillot &lt;&gt;&quot; &quot;Alexey Solovyev &lt;&gt;&quot; &quot;Russell O&#39;Connor &lt;&gt;&quot; &quot;Laurent Théry &lt;&gt;&quot; &quot;Assia Mahboubi &lt;&gt;&quot; ] synopsis: &quot;Mathematical Components Library on Fields&quot; description: &quot;&quot;&quot; This library contains definitions and theorems about field extensions, galois theory, algebraic numbers, cyclotomic polynomials...&quot;&quot;&quot; url { src: &quot;http://github.com/math-comp/math-comp/archive/mathcomp-1.6.2.tar.gz&quot; checksum: &quot;md5=cf10cb16f1ac239a9d52c029a4e00f66&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-mathcomp-field.1.6.2 coq.8.13.2</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.13.2). The following dependencies couldn&#39;t be met: - coq-mathcomp-field -&gt; coq-mathcomp-solvable = 1.6.2 -&gt; coq-mathcomp-algebra = 1.6.2 -&gt; coq-mathcomp-fingroup = 1.6.2 -&gt; coq-mathcomp-ssreflect = 1.6.2 -&gt; coq &lt; 8.6~ -&gt; ocaml &lt; 4.10 base of this switch (use `--unlock-base&#39; to force) No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-mathcomp-field.1.6.2</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
coq-bench/coq-bench.github.io
clean/Linux-x86_64-4.10.2-2.0.6/released/8.13.2/mathcomp-field/1.6.2.html
HTML
mit
7,808
[ 30522, 1026, 999, 9986, 13874, 16129, 1028, 1026, 16129, 11374, 1027, 1000, 4372, 1000, 1028, 1026, 2132, 1028, 1026, 18804, 25869, 13462, 1027, 1000, 21183, 2546, 1011, 1022, 1000, 1028, 1026, 18804, 2171, 1027, 1000, 3193, 6442, 1000, 418...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* * Copyright (C) 2013 Man YUAN <epsilon@epsilony.net> * * 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/>. */ package net.epsilony.tb.implicit; import java.awt.geom.Rectangle2D; import java.util.List; import net.epsilony.tb.solid.Line; import net.epsilony.tb.analysis.Math2D; import net.epsilony.tb.analysis.DifferentiableFunction; import net.epsilony.tb.analysis.LogicalMaximum; import net.epsilony.tb.solid.SegmentStartCoordIterable; import net.epsilony.tb.solid.winged.WingedCell; import org.junit.Test; import static org.junit.Assert.*; /** * * @author <a href="mailto:epsilonyuan@gmail.com">Man YUAN</a> */ public class TrackContourBuilderTest { public TrackContourBuilderTest() { } double diskCenterX = 10; double diskCenterY = -20; double diskRadius = 50; double holeCenterX = 15; double holeCenterY = -15; double holeRadius = 20; public class SampleOneDiskWithAHole implements DifferentiableFunction { LogicalMaximum max = new LogicalMaximum(); private CircleLevelSet disk; private CircleLevelSet hole; public SampleOneDiskWithAHole() { max.setK(diskRadius - holeRadius, 1e-10, true); disk = new CircleLevelSet(diskCenterX, diskCenterY, diskRadius); disk.setConcrete(true); hole = new CircleLevelSet(holeCenterX, holeCenterY, holeRadius); hole.setConcrete(false); max.setFunctions(disk, hole); } @Override public double[] value(double[] input, double[] output) { return max.value(input, output); } @Override public int getDiffOrder() { return max.getDiffOrder(); } @Override public int getInputDimension() { return max.getInputDimension(); } @Override public int getOutputDimension() { return max.getOutputDimension(); } @Override public void setDiffOrder(int diffOrder) { max.setDiffOrder(diffOrder); } } @Test public void testDiskWithAHole() { TriangleContourCellFactory factory = new TriangleContourCellFactory(); double edgeLength = 5; int expChainsSize = 2; double errRatio = 0.05; Rectangle2D range = new Rectangle2D.Double(diskCenterX - diskRadius - edgeLength * 2, diskCenterY - diskRadius - edgeLength * 2, diskRadius * 2 + edgeLength * 4, diskRadius * 2 + edgeLength * 4); SampleOneDiskWithAHole levelsetFunction = new SampleOneDiskWithAHole(); factory.setRectangle(range); factory.setEdgeLength(edgeLength); List<WingedCell> cells = factory.produce(); TrackContourBuilder builder = new TrackContourBuilder(); builder.setCells((List) cells); builder.setLevelSetFunction(levelsetFunction); SimpleGradientSolver solver = new SimpleGradientSolver(); solver.setMaxEval(200); builder.setImplicitFunctionSolver(solver); builder.genContour(); List<Line> contourHeads = builder.getContourHeads(); assertEquals(expChainsSize, contourHeads.size()); for (int i = 0; i < contourHeads.size(); i++) { double x0, y0, rad; Line head = contourHeads.get(i); boolean b = Math2D.isAnticlockwise(new SegmentStartCoordIterable(head)); if (b) { x0 = diskCenterX; y0 = diskCenterY; rad = diskRadius; } else { x0 = holeCenterX; y0 = holeCenterY; rad = holeRadius; } double expArea = Math.PI * rad * rad; expArea *= b ? 1 : -1; Line seg = head; double actArea = 0; double[] center = new double[] { x0, y0 }; do { double[] startCoord = seg.getStart().getCoord(); double[] endCoord = seg.getEnd().getCoord(); actArea += 0.5 * Math2D.cross(endCoord[0] - startCoord[0], endCoord[1] - startCoord[1], x0 - startCoord[0], y0 - startCoord[1]); seg = (Line) seg.getSucc(); double actRadius = Math2D.distance(startCoord, center); assertEquals(rad, actRadius, 1e-5); actRadius = Math2D.distance(endCoord, center); assertEquals(rad, actRadius, 1e-5); } while (seg != head); assertEquals(expArea, actArea, Math.abs(expArea) * errRatio); } } }
epsilony/tb
src/test/java/net/epsilony/tb/implicit/TrackContourBuilderTest.java
Java
gpl-3.0
5,181
[ 30522, 1013, 1008, 1008, 9385, 1006, 1039, 1007, 2286, 2158, 11237, 1026, 28038, 1030, 28038, 2100, 1012, 5658, 1028, 1008, 1008, 2023, 2565, 2003, 2489, 4007, 1024, 2017, 2064, 2417, 2923, 3089, 8569, 2618, 2009, 1998, 1013, 2030, 19933, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
(function(){ 'use strict'; Ns.views.map.Layout = Marionette.LayoutView.extend({ id: 'map-container', template: '#map-layout-template', regions: { content: '#map-js', legend: '#legend-js', panels: '#map-panels', toolbar: '#map-toolbar', add: '#map-add-node-js', details: '#map-details-js' }, /** * show regions */ onShow: function () { this.content.show(new Ns.views.map.Content({ parent: this })); }, /** * loads map data */ loadMap: function () { var options = { parent: this }; this.toolbar.show(new Ns.views.map.Toolbar(options)); this.panels.show(new Ns.views.map.Panels(options)); this.legend.show(new Ns.views.map.Legend(options)); this.content.currentView.initMapData(); }, /* * show add node view */ addNode: function () { this.reset(); // if not authenticated if (Ns.db.user.isAuthenticated() === false) { // show sign-in modal $('#signin-modal').modal('show'); // listen to loggedin event and come back here this.listenToOnce(Ns.db.user, 'loggedin', this.addNode); return; } this.add.show(new Ns.views.map.Add({ parent: this })); }, showNode: function(node) { this.details.show(new Ns.views.node.Detail({ model: node, parent: this })); }, showEditNode: function(node) { // ensure is allowed to edit if (node.get('can_edit')) { this.showNode(node); this.details.currentView.edit(); } // otherwise go back to details else { Ns.router.navigate('nodes/' + node.id, { trigger: true }); } }, /* * resets to view initial state */ reset: function () { this.content.currentView.closeLeafletPopup(); this.add.empty(); this.details.empty(); } }, { // static methods show: function (method, args) { var view; if (typeof Ns.body.currentView === 'undefined' || !(Ns.body.currentView instanceof Ns.views.map.Layout)) { view = new Ns.views.map.Layout(); Ns.body.show(view); } else { view = Ns.body.currentView; view.reset(); } // call method on Layout view is specified if (method) { view[method].apply(view, args); } }, /* * Resize page elements so that the leaflet map * takes most of the available space in the window */ resizeMap: function () { var overlayContainer = $('#map-overlay-container'), height, selector, width, setWidth = false, body = $('body'); body.css('overflow-x', 'hidden'); // map if (!overlayContainer.length) { height = $(window).height() - $('body > header').height(); selector = '#map-container, #map-toolbar'; } // node details else { height = overlayContainer.height() + parseInt(overlayContainer.css('top'), 10); selector = '#map-container'; } // set new height $(selector).height(height); width = $(window).width(); // take in consideration #map-add-node-js if visible if ($('#map-add-node-js').is(':visible')) { width = width - $('#map-add-node-js').outerWidth(); setWidth = true; } // take in consideration map toolbar if visible else if ($('#map-toolbar').is(':visible')) { width = width - $('#map-toolbar').outerWidth(); setWidth = true; } // set width only if map toolbar is showing if (setWidth){ $('#map').width(width); } else{ $('#map').attr('style', ''); } body.attr('style', ''); // TODO: this is ugly! // call leaflet invalidateSize() to download any gray spot if (Ns.body.currentView instanceof Ns.views.map.Layout && Ns.body.currentView.content && typeof Ns.body.currentView.content.currentView.map !== 'undefined'){ Ns.body.currentView.content.currentView.map.invalidateSize(); } } }); Ns.views.map.Content = Marionette.ItemView.extend({ template: false, collectionEvents: { // populate map as items are added to collection 'add': 'addGeoModelToMap', // remove items from map when models are removed 'remove': 'removeGeoModelFromMap' }, initialize: function (options) { this.parent = options.parent; this.collection = new Ns.collections.Geo(); this.popUpNodeTemplate = _.template($('#map-popup-node-template').html()); // link tweak this.popUpLinkTemplate = _.template($('#map-popup-link-template').html()); // reload data when user logs in or out this.listenTo(Ns.db.user, 'loggedin loggedout', this.reloadMapData); // bind to namespaced events $(window).on('resize.map', _.bind(this.resize, this)); $(window).on('beforeunload.map', _.bind(this.storeMapProperties, this)); // cleanup eventual alerts $.cleanupAlerts(); }, onShow: function () { this.initMap(); }, onDestroy: function () { // store current coordinates when changing view this.storeMapProperties(); // unbind the namespaced events $(window).off('beforeunload.map'); $(window).off('resize.map'); }, /* * get current map coordinates (lat, lng, zoom) */ getMapProperties: function () { var latLng = this.map.getCenter(); return { lat: latLng.lat, lng: latLng.lng, zoom: this.map.getZoom(), baseLayer: this.getCurrentBaseLayer() }; }, /* * store current map coordinates in localStorage */ storeMapProperties: function () { localStorage.setObject('map', this.getMapProperties()); }, /* * get latest stored coordinates or default ones */ rememberMapProperties: function () { return localStorage.getObject('map') || Ns.settings.map; }, /* * resize window event */ resize: function () { Ns.views.map.Layout.resizeMap(); // when narrowing the window to medium-small size and toolbar is hidden and any panel is still visible if ($(window).width() <= 767 && $('#map-toolbar').is(':hidden') && $('.side-panel:visible').length) { // close panel $('.mask').trigger('click'); } }, /* * initialize leaflet map */ initMap: function () { var self = this, memory = this.rememberMapProperties(); this.resize(); // init map this.map = $.loadDjangoLeafletMap(); // remember last coordinates this.map.setView([memory.lat, memory.lng], memory.zoom, { trackResize: true }); // store baseLayers this.baseLayers = {}; _.each(this.map.layerscontrol._layers, function (baseLayer) { self.baseLayers[baseLayer.name] = baseLayer.layer; // keep name reference self.baseLayers[baseLayer.name].name = baseLayer.name; }); // remember preferred baseLayer if (memory.baseLayer) { this.switchBaseLayer(memory.baseLayer); } // create (empty) clusters on map (will be filled by addGeoModelToMap) this.createClusters(); }, /** * changes base layer of the map, only if necessary * (calling the same action twice has no effect) */ switchBaseLayer: function(name){ // ignore if name is undefined if(typeof name === 'undefined'){ return; } // remove all base layers that are not relevant for (var key in this.baseLayers){ if (this.baseLayers[key].name !== name) { this.map.removeLayer(this.baseLayers[key]); } } // if the relevant layer is still not there add it if (!this.map.hasLayer(this.baseLayers[name])) { this.map.addLayer(this.baseLayers[name]); } }, /** * returns name of the current map base layer */ getCurrentBaseLayer: function () { for (var name in this.baseLayers){ if (Boolean(this.baseLayers[name]._map)) { return name; } } return null; }, /* * loads data from API */ initMapData: function () { Ns.changeTitle(gettext('Map')); Ns.menu.currentView.activate('map'); Ns.track(); Ns.state.onNodeClose = 'map'; // when a node-details is closed go back on map this.parent.toolbar.$el.addClass('enabled'); this.resize(); // load cached data if present if (Ns.db.geo.isEmpty() === false) { this.collection.add(Ns.db.geo.models); this.collection.trigger('ready'); } // otherwise fetch from server else { this.fetchMapData(); } // toggle legend group from map when visible attribute changes this.listenTo(Ns.db.legend, 'change:visible', this.toggleLegendGroup); // toggle layer data when visible attribute changes this.listenTo(Ns.db.layers, 'change:visible', this.toggleLayerData); }, /* * fetch map data, merging changes if necessary */ fetchMapData: function () { var self = this, // will contain fresh data geo = new Ns.collections.Geo(), // will be used to fetch data to merge in geo tmp = geo.clone(), additionalGeoJson = Ns.settings.additionalGeoJsonUrls, ready, fetch; // will be called when all sources have been fetched // we need to add 1 to account for the main geojson ready = _.after(additionalGeoJson.length + 1, function () { // reload models self.collection.remove(self.collection.models); self.collection.add(geo.models); // cache geo collection Ns.db.geo = self.collection; // trigger ready event self.collection.trigger('ready'); // unbind event self.collection.off('sync', ready); }); // fetch data and add it to collection fetch = function () { tmp.fetch().done(function () { geo.add(tmp.models); geo.trigger('sync'); }); }; geo.on('sync', ready); // fetch data from API fetch(); additionalGeoJson.forEach(function (url) { tmp._url = url; fetch(); }); // begin temporary tweak for links if (Ns.settings.links) { var links = new Ns.collections.Geo(); links._url = Ns.url('links.geojson'); links.fetch().done(function () { geo.add(links.models); geo.trigger('sync'); }); } // end tweak }, /** * reload map data in the background */ reloadMapData: function () { $.toggleLoading('hide'); // disable loading indicator while data gets refreshed Ns.state.autoToggleLoading = false; // fetch data this.fetchMapData(); // re-enable loading indicator once data is refreshed this.collection.once('ready', function(){ Ns.state.autoToggleLoading = true }); }, /** * prepare empty Leaflet.MarkerCluster objects */ createClusters: function () { var self = this, legend; // loop over each legend item Ns.db.legend.forEach(function (legendModel) { legend = legendModel.toJSON(); // group markers in clusters var cluster = new L.MarkerClusterGroup({ iconCreateFunction: function (cluster) { var count = cluster.getChildCount(), // determine size with the last number of the exponential notation // 0 for < 10, 1 for < 100, 2 for < 1000 and so on size = count.toExponential().split('+')[1]; return L.divIcon({ html: count, className: 'cluster cluster-size-' + size + ' marker-' + this.cssClass }); }, polygonOptions: { fillColor: legend.fill_color, stroke: legend.stroke_width > 0, weight: legend.stroke_width, color: legend.stroke_color, opacity: 0.4 }, cssClass: legend.slug, chunkedLoading: true, showCoverageOnHover: true, zoomToBoundsOnClick: true, removeOutsideVisibleBounds: true, disableClusteringAtZoom: Ns.settings.disableClusteringAtZoom, maxClusterRadius: Ns.settings.maxClusterRadius }); // store reference legendModel.cluster = cluster; // show cluster only if corresponding legend item is visible if(legend.visible){ self.map.addLayer(cluster); } }); }, /** * returns options for the initialization of tooltip for leaflet layers */ tooltipOptions: function(data) { return { container: '#map-js', placement: 'auto top', title: data.name, delay: { show: 600, hide: 0 } } }, /** * adds a geo model to its cluster * binds popup * called whenever a model is added to the collection */ addGeoModelToMap: function (model) { var self = this, leafletLayer = model.get('leaflet'), legend = model.get('legend'), data = model.toJSON(), layer = Ns.db.layers.get(data.layer), // link tweak template = model._type === 'node' ? this.popUpNodeTemplate : this.popUpLinkTemplate; // bind leaflet popup leafletLayer.bindPopup(template(data)); // mouse over / out events leafletLayer.on({ mouseover: function (e) { var l = e.target, type = l.feature.geometry.type; // opacity to 1 l.setStyle({ fillOpacity: 1 }); // bring to front if (!L.Browser.ie && !L.Browser.opera && type === 'Point') { l.bringToFront({ fillOpacity: 1 }); } }, mouseout: function (e) { e.target.setStyle({ fillOpacity: Ns.settings.leafletOptions.fillOpacity }); }, // when popup opens, change the URL fragment popupopen: function (e) { var fragment = Backbone.history.fragment; // do this only if in general map view if (fragment.indexOf('map') >= 0 && fragment.indexOf('nodes') < 0) { Ns.router.navigate('map/' + data.slug); } // destroy container to avoid the chance that the tooltip // might appear while showing the leaflet popup $(e.target._container).tooltip('destroy'); }, // when popup closes popupclose: function (e) { // (and no new popup opens) // URL fragment goes back to initial state var fragment = Backbone.history.fragment; setTimeout(function () { // do this only if in general map view if (self.map._popup === null && fragment.indexOf('map') >= 0 && fragment.indexOf('nodes') < 0) { Ns.router.navigate('map'); } }, 100); // rebind tooltip (it has been destroyed in popupopen event) $(e.target._container).tooltip(self.tooltipOptions(data)); }, add: function(e){ // create tootlip when leaflet layer is added to the view $(e.target._container).tooltip(self.tooltipOptions(data)); }, remove: function(e){ // ensure tooltip is removed when layer is removed from map $(e.target._container).tooltip('destroy'); } }); // show on map only if corresponding nodeshot layer is visible if (layer && layer.get('visible')) { legend.cluster.addLayer(leafletLayer); // avoid covering points if (leafletLayer._map && leafletLayer.feature.geometry.type !== 'Point') { leafletLayer.bringToBack(); } } }, /** * remove geo model from its cluster * called whenever a model is removed from the collection */ removeGeoModelFromMap: function (model) { var cluster = model.get('legend').cluster; cluster.removeLayer(model.get('leaflet')); }, /* * show / hide from map items of a legend group */ toggleLegendGroup: function (legend, visible) { var method = (visible) ? 'addLayer' : 'removeLayer'; this.map[method](legend.cluster); }, /* * show / hide from map items of a legend group */ toggleLayerData: function (layer, visible) { var geo = this.collection, method = (visible) ? 'addLayers' : 'removeLayers', l; Ns.db.legend.forEach(function(legend){ l = geo.whereCollection({ legend: legend, layer: layer.id }).pluck('leaflet'); legend.cluster[method](l); }); // needed to recalculate stats on legend this.trigger('layer-toggled'); }, /* * Open leaflet popup of the specified element */ openLeafletPopup: function (id) { var collection = this.collection, self = this, leafletLayer; // open leaflet pop up if ready if (collection.length && typeof collection !== 'undefined') { try { leafletLayer = this.collection.get(id).get('leaflet'); } catch (e) { $.createModal({ message: id + ' ' + gettext('not found'), onClose: function () { Ns.router.navigate('map'); } }); return; } try { leafletLayer.openPopup(); } // clustering plugin hides leafletLayers when clustered or outside viewport // so we have to zoom in and center the map catch (e){ this.map.fitBounds(leafletLayer.getBounds()); leafletLayer.openPopup(); } } // if not ready wait for map.collectionReady and call again else { this.collection.once('ready', function () { self.openLeafletPopup(id); }); } return; }, /* * Close leaflet popup if open */ closeLeafletPopup: function () { var popup = $('#map-js .leaflet-popup-close-button'); if (popup.length) { popup.get(0).click(); } }, /* * Go to specified latitude and longitude */ goToLatLng: function (latlng, zoom) { latlng = latlng.split(',') latlng = L.latLng(latlng[0], latlng[1]); var self = this, marker = L.marker(latlng); // used in search address feature if (!zoom) { marker.addTo(this.map); zoom = 18; } // go to marker and zoom in this.map.setView(latlng, zoom); // fade out marker if (typeof(marker) !== 'undefined' && this.map.hasLayer(marker)) { $([marker._icon, marker._shadow]).fadeOut(4000, function () { self.map.removeLayer(marker); }); } } }); Ns.views.map.Legend = Marionette.ItemView.extend({ id: 'map-legend', className: 'overlay inverse', template: '#map-legend-template', ui: { 'close': 'a.icon-close' }, events: { 'click @ui.close': 'toggleLegend', 'click li a': 'toggleGroup' }, collectionEvents: { // automatically render when toggling group or recounting 'change:visible counted': 'render' }, initialize: function (options) { this.parent = options.parent; this.collection = Ns.db.legend; this.legendButton = this.parent.toolbar.currentView.ui.legendButton; // display count in legend this.listenTo(this.parent.content.currentView.collection, 'ready', this.count); this.listenTo(this.parent.content.currentView, 'layer-toggled', this.count); }, onRender: function () { // default is true if (localStorage.getObject('legendOpen') === false) { this.$el.hide(); } else { this.legendButton.addClass('disabled'); } }, /* * calculate counts */ count: function () { this.collection.forEach(function (legend) { legend.set('count', legend.cluster.getLayers().length); }); // trigger once all legend items have been counted this.collection.trigger('counted'); }, /* * open or close legend */ toggleLegend: function (e) { e.preventDefault(); var legend = this.$el, button = this.legendButton, open; if (legend.is(':visible')) { legend.fadeOut(255); button.removeClass('disabled'); button.tooltip('enable'); open = false; } else { legend.fadeIn(255); button.addClass('disabled'); button.tooltip('disable').tooltip('hide'); open = true; } localStorage.setItem('legendOpen', open); }, /* * enable or disable something on the map * by clicking on its related legend control */ toggleGroup: function (e) { e.preventDefault(); var status = $(e.currentTarget).attr('data-status'), item = this.collection.get(status); item.set('visible', !item.get('visible')); } }); Ns.views.map.Toolbar = Marionette.ItemView.extend({ template: '#map-toolbar-template', ui: { 'buttons': 'a', 'switchMapMode': '#btn-map-mode', 'legendButton': '#btn-legend', 'toolsButton': 'a.icon-tools', 'prefButton': 'a.icon-config', 'layersControl': 'a.icon-layer-2' }, events: { 'click .icon-pin-add': 'addNode', 'click @ui.buttons': 'togglePanel', 'click @ui.switchMapMode': 'switchMapMode', // siblings events 'click @ui.legendButton': 'toggleLegend' }, initialize: function (options) { this.parent = options.parent; }, onRender: function () { var self = this; // init tooltip this.ui.buttons.tooltip(); // correction for map tools this.ui.toolsButton.click(function (e) { var button = $(this), prefButton = self.ui.prefButton; if (button.hasClass('active')) { prefButton.tooltip('disable'); } else { prefButton.tooltip('enable'); } }); // correction for map-filter this.ui.layersControl.click(function (e) { var button = $(this), otherButtons = self.$el.find('a.icon-config, a.icon-3d, a.icon-tools'); if (button.hasClass('active')) { otherButtons.tooltip('disable'); } else { otherButtons.tooltip('enable'); } }); }, /* * show / hide map toolbar on narrow screens */ toggleToolbar: function (e) { e.preventDefault(); // shortcut var toolbar = this.parent.toolbar.$el, target = $(e.currentTarget); // show toolbar if (toolbar.is(':hidden')) { // just add display:block // which overrides css media-query toolbar.show(); // overimpose on toolbar target.css('right', '-60px'); } // hide toolbar else { // instead of using jQuery.hide() which would hide the toolbar also // if the user enlarged the screen, we clear the style attribute // which will cause the toolbar to be hidden only on narrow screens toolbar.attr('style', ''); // close any open panel if ($('.side-panel:visible').length) { $('.mask').trigger('click'); } // eliminate negative margin correction target.css('right', '0'); } Ns.views.map.Layout.resizeMap(); }, /* * proxy to call add node */ addNode: function (e) { e.preventDefault(); this.parent.addNode(); }, /* * redirects to Ns.views.map.Panels */ toggleLegend: function (e) { this.parent.legend.currentView.toggleLegend(e); }, /* * redirects to Ns.views.map.Panels */ togglePanel: function (e) { this.parent.panels.currentView.togglePanel(e); }, /* * toggle 3D or 2D map */ switchMapMode: function (e) { e.preventDefault(); $.createModal({message: gettext('not implemented yet')}); } }); Ns.views.map.Panels = Marionette.ItemView.extend({ template: '#map-panels-template', ui: { 'switches': 'input.switch', 'scrollers': '.scroller', 'selects': '.selectpicker', 'tools': '.tool', 'distance': '#fn-map-tools .icon-ruler', 'area': '#fn-map-tools .icon-select-area', 'elevation': '#fn-map-tools .icon-elevation-profile' }, events: { 'click #fn-map-tools .notImplemented': 'toggleToolNotImplemented', 'click @ui.distance': 'toggleDistance', 'click @ui.area': 'toggleArea', 'click @ui.elevation': 'toggleElevation', 'click #toggle-toolbar': 'toggleToolbar', 'change .js-base-layers input': 'switchBaseLayer', 'switch-change #fn-map-layers .toggle-layer-data': 'toggleLayer', 'switch-change #fn-map-layers .toggle-legend-data': 'toggleLegend' }, initialize: function (options) { this.parent = options.parent; this.mapView = this.parent.content.currentView; this.toolbarView = this.parent.toolbar.currentView; this.toolbarButtons = this.toolbarView.ui.buttons; // listen to legend change event this.listenTo(Ns.db.legend, 'change:visible', this.syncLegendSwitch); this.populateBaseLayers(); // init tools if (Ns.settings.mapTools) { this.tools = { 'distance': new L.Polyline.Measure(this.mapView.map), 'area': new L.Polygon.Measure(this.mapView.map), 'elevation': new L.Polyline.Elevation(this.mapView.map) }; } }, // populate this.baseLayers populateBaseLayers: function () { var self = this, layer; this.baseLayers = []; // get ordering of baselayers django-leaflet options this.mapView.map.options.djoptions.layers.forEach(function (layerConfig) { layer = self.mapView.baseLayers[layerConfig[0]]; self.baseLayers.push({ checked: Boolean(layer._map), // if _map is not null it means this is the active layer name: layer.name }); }); }, serializeData: function(){ return { 'layers': Ns.db.layers.toJSON(), 'legend': Ns.db.legend.toJSON(), 'baseLayers': this.baseLayers } }, onRender: function () { this.ui.tools.tooltip(); // activate switch this.ui.switches.bootstrapSwitch().bootstrapSwitch('setSizeClass', 'switch-small'); // activate scroller this.ui.scrollers.scroller({ trackMargin: 6 }); // fancy selects this.ui.selects.selectpicker({ style: 'btn-special' }); }, /* * show / hide toolbar panels */ togglePanel: function (e) { e.preventDefault(); var button = $(e.currentTarget), panelId = button.attr('data-panel'), panel = $('#' + panelId), self = this, // determine distance from top distanceFromTop = button.offset().top - $('body > header').eq(0).outerHeight(), preferencesHeight; // if no panel return here if (!panel.length) { return; } // hide any open tooltip $('#map-toolbar .tooltip').hide(); panel.css('top', distanceFromTop); // adjust height of panel if marked as 'adjust-height' if (panel.hasClass('adjust-height')) { preferencesHeight = $('#map-toolbar').height() - distanceFromTop - 18; panel.height(preferencesHeight); } panel.fadeIn(25, function () { panel.find('.scroller').scroller('reset'); button.addClass('active'); button.tooltip('hide').tooltip('disable'); // create a mask for easy closing $.mask(panel, function (e) { // close function if (panel.is(':visible')) { panel.hide(); self.toolbarButtons.removeClass('active'); button.tooltip('enable'); // if clicking again on the same button avoid reopening the panel if ($(e.target).attr('data-panel') === panelId) { e.stopPropagation(); e.preventDefault(); } } }); }); }, toggleToolNotImplemented: function (e) { e.preventDefault(); $.createModal({ message: gettext('not implemented yet') }); return false; }, /* * toggle map tool */ toggleToolButton: function (e) { var button = $(e.currentTarget), active_buttons = $('#fn-map-tools .tool.active'); // if activating a tool if (!button.hasClass('active')) { // deactivate any other active_buttons.trigger('click'); button.addClass('active') .tooltip('hide') .tooltip('disable'); return true; // deactivate } else { button.removeClass('active') .tooltip('enable') .trigger('blur'); return false; } }, toggleDrawTool: function (toolName, e) { var result = this.toggleToolButton(e), tool = this.tools[toolName]; if (result) { tool.enable(); // if tool is disabled with ESC or other ways // sync the nodeshot UI tool.once('disabled', function () { this.toggleToolButton(e); }, this); } else { tool.off('disabled'); tool.disable(); } }, toggleDistance: function (e) { this.toggleDrawTool('distance', e); }, toggleArea: function (e) { this.toggleDrawTool('area', e); }, toggleElevation: function (e) { this.toggleDrawTool('elevation', e); }, drawElevation: function (geojson) { // local vars var points = [], self = this; // the elevation API expects latitude, longitude, so we have to reverse our coords geojson.geometry.coordinates.forEach(function(point){ points.push(point.reverse()); }); // query the elevation API $.getJSON(Ns.url('elevation/'), { // output is '<lat>,<lng>|<lat>,<lng>|<lat>,<lng' path: points.join('|') }).done(function(geojson){ // close tools panel $('.mask').trigger('click'); // create control var el = L.control.elevation({ position: 'bottomright', width: 1020, height: 299, margins: { top: 25, right: 40, bottom: 40, left: 70 }, }); el.addTo(self.mapView.map); var geojsonLayer = L.geoJson(geojson, { onEachFeature: el.addData.bind(el), style: function () { return { color: '#e6a1b3', opacity: 0.7 } } }).addTo(self.mapView.map); var close = $('<a href="#" class="icon-close"></a>'); $('#map-js .elevation.leaflet-control').append('<a href="#" class="icon-close"></a>'); $('#map-js .elevation.leaflet-control .icon-close').one('click', function (e) { e.preventDefault(); self.mapView.map.removeControl(el); self.mapView.map.removeLayer(geojsonLayer); }) }); }, /* * proxy to Ns.views.map.Toolbar.toggleToolbar */ toggleToolbar: function (e) { this.toolbarView.toggleToolbar(e); }, /** * changes base layer of the map * proxy to Ns.views.map.Content.switchBaseLayer */ switchBaseLayer: function (event) { this.mapView.switchBaseLayer($(event.target).attr('data-name')); }, /** * hide / show layer data on map */ toggleLayer: function (event, data) { var layer = Ns.db.layers.get(data.el.attr('data-slug')); layer.set('visible', data.value); }, /** * hide / show legend data on map */ toggleLegend: function(event, data){ this.parent.legend.currentView.$('a[data-status=' + data.el.attr('data-slug') + ']').trigger('click'); }, /** * sync legend state with switches in panel */ syncLegendSwitch: function(legend, state){ var input = this.$('#map-control-legend-' + legend.get('slug')); if(input.bootstrapSwitch('state') !== state){ // second parameter indicates wheter to skip triggering switch event input.bootstrapSwitch('toggleState', true); } } }); Ns.views.map.Add = Marionette.ItemView.extend({ template: '#map-add-node-template', tagName: 'article', ui: { 'formContainer': '#add-node-form-container' }, events: { 'click #add-node-form-container .btn-default': 'destroy', 'submit #add-node-form-container form': 'submitAddNode' }, initialize: function (options) { this.parent = options.parent; // references to objects of other views this.ext = { legend: this.parent.legend.$el, toolbar: this.parent.toolbar.$el, map: this.parent.content.$el, leafletMap: this.parent.content.currentView.map, geo: this.parent.content.currentView.collection, step1: $('#add-node-step1'), step2: $('#add-node-step2') }; // elements that must be hidden this.hidden = $().add(this.ext.legend) .add(this.ext.toolbar) .add(this.ext.map.find('.leaflet-control-attribution')); // needed for toggleLeafletLayers this.dimmed = false; }, serializeData: function(){ return { 'layers': Ns.db.layers.toJSON() }; }, onShow: function () { Ns.router.navigate('map/add'); Ns.changeTitle(gettext('Add node')); Ns.track(); // go to step1 when collection is ready if (this.ext.geo.length){ this.step1(); } else { this.listenToOnce(this.ext.geo, 'ready', this.step1); } // dynamic form this.form = new Backbone.Form({ model: new Ns.models.Node(), submitButton: gettext('Add node') }).render(); this.ui.formContainer.html(this.form.$el); this.$('input[type=checkbox]').bootstrapSwitch().bootstrapSwitch('setSizeClass', 'switch-small'); this.$('select').selectpicker({style: 'btn-special' }); }, /* * when the view is destroyed the map is taken backto its original state */ onBeforeDestroy: function () { this.closeAddNode(); // change url fragment but only if we are still on the map if (Backbone.history.fragment.substr(0, 3) == 'map'){ Ns.router.navigate('map'); } }, /* * proxy to Ns.views.map.Layout.resizeMap */ resizeMap: function() { Ns.views.map.Layout.resizeMap(); }, /* * hide elements that are not needed when adding a new node * show them back when finished */ toggleHidden: function(){ this.hidden.toggle(); this.resizeMap(); this.toggleLeafletLayers(); }, /* * dim out leaflet layers from map when adding a new node * reset default options when finished * clusters are toggled (hidden and shown back) through an additional style tag in <head> * because clusters are re-rendered whenever the map is moved or resized so inline changes * do not persist when resizing or moving */ toggleLeafletLayers: function () { var leafletOptions = Ns.settings.leafletOptions, tmpOpacity = leafletOptions.temporaryOpacity, clusterCss = $('#add-node-cluster-css'), dimOut = !this.dimmed, leaflet; // dim out or reset all leaflet layers this.ext.geo.forEach(function(model){ leaflet = model.get('leaflet'); if (dimOut) { leaflet.options.opacity = tmpOpacity; leaflet.options.fillOpacity = tmpOpacity; leaflet.setStyle(leaflet.options); } else { leaflet.options.opacity = leafletOptions.opacity; leaflet.options.fillOpacity = leafletOptions.fillOpacity; leaflet.setStyle(leaflet.options); } }); if (clusterCss.length === 0) { $('head').append('<style id="add-node-cluster-css">.cluster{ display: none }</style>'); } else{ clusterCss.remove(); } // change dimmed state this.dimmed = dimOut; }, /* * step1 of adding a new node */ step1: function (e) { var self = this, dialog = this.ext.step1, dialog_dimensions = dialog.getHiddenDimensions(); // hide toolbar and enlarge map this.toggleHidden(); // show step1 dialog.css({ width: dialog_dimensions.width+2, right: 0 }); dialog.fadeIn(255); // cancel this.ext.step1.find('button').one('click', function () { self.destroy() }); // on map click (only once) this.ext.leafletMap.once('click', function (e) { dialog.fadeOut(255); self.step2(e); }); }, step2: function (e) { var self = this, dialog = this.ext.step2, dialog_dimensions = dialog.getHiddenDimensions(), map = this.ext.leafletMap, callback, latlng, // draggable marker marker = L.marker([e.latlng.lat, e.latlng.lng], {draggable: true}).addTo(map); // keep a global reference this.newNodeMarker = marker; // set address on form this.setAddressFromLatLng(e.latlng); this.form.setValue('geometry', JSON.stringify(marker.toGeoJSON())); this.setGeometryFromMarker(marker); // update address when moving the marker marker.on('dragend', function (event) { latlng = event.target.getLatLng(); self.setAddressFromLatLng(latlng); self.setGeometryFromMarker(event.target); map.panTo(latlng); }); // zoom in to marker map.setView(marker.getLatLng(), 18, { animate: true }); // show step2 dialog = self.ext.step2, dialog_dimensions = dialog.getHiddenDimensions(); dialog.css({ width: dialog_dimensions.width+2, right: 0 }); dialog.fadeIn(255); // bind cancel button once this.ext.step2.find('.btn-default').one('click', function () { self.destroy() }); // bind confirm button once this.ext.step2.find('.btn-success').one('click', function () { callback = function () { self.resizeMap(); map.panTo(marker._latlng); }; dialog.fadeOut(255); // show form with a nice animation self.parent.add.$el.show().animate({ width: '+70%'}, { duration: 400, progress: callback, complete: callback }); }); }, /* * submit new node */ submitAddNode: function (e) { e.preventDefault(); var self = this, form = this.form, geojson = JSON.stringify(this.newNodeMarker.toGeoJSON().geometry), errorList = this.$('.error-list'), node = form.model, errors = form.commit(), geo; if (errors) { return false; } this.$('.help-block').text('').hide(); this.$('.error').removeClass('error'); this.$('.has-error').removeClass('has-error'); errorList.html('').hide(); node.save().done(function () { // convert to Geo model node = new Ns.models.Geo(node.toJSON()); // add to geo collection self.ext.geo.add(node); // destroy this view self.destroy(); // open new node popup node.get('leaflet').openPopup(); }).error(function (http) { // TODO: make this reusable var json = http.responseJSON, key, input, errorContainer; for (key in json) { input = self.$('input[name=' + key + ']'); if (input.length) { input.addClass('error'); errorContainer = input.parents('.form-group').find('.help-block'); errorContainer.text(json[key]) .removeClass('hidden') .addClass('has-error') .fadeIn(255); } else { errorList.show(); errorList.append('<li>' + json[key] + '</li>'); } } }); }, /* * cancel addNode operation * resets normal map functions */ closeAddNode: function () { var marker = this.newNodeMarker, container = this.parent.add.$el, map = this.ext.leafletMap, self = this, resetToOriginalState = function () { container.hide(); // show hidden elements again self.toggleHidden(); }; // unbind click events map.off('click'); this.ext.step1.find('button').off('click'); this.ext.step2.find('.btn-default').off('click'); this.ext.step2.find('.btn-success').off('click'); // remove marker if necessary if (marker) { map.removeLayer(marker); } // hide step1 if necessary if (this.ext.step1.is(':visible')) { this.ext.step1.fadeOut(255); } // hide step2 if necessary if (this.ext.step2.is(':visible')) { this.ext.step2.fadeOut(255); } // if container is visible if (container.is(':visible')) { // hide it with a nice animation container.animate({ width: '0' }, { duration: 400, progress: function () { self.resizeMap(); if (marker) { map.panTo(marker._latlng); } }, complete: resetToOriginalState }); } // reset original state else{ resetToOriginalState(); } }, /* * retrieve address from latlng through OSM Nominatim service * and set it on the add node form */ setAddressFromLatLng: function (latlng) { var self = this; $.geocode({ lat: latlng.lat, lon: latlng.lng, callback: function(result){ self.form.setValue('address', result.display_name); } }); }, /** * set geometry on model from marker geojson */ setGeometryFromMarker: function (marker) { this.form.setValue('geometry', JSON.stringify(marker.toGeoJSON().geometry)); } }); })();
ninuxorg/nodeshot
nodeshot/ui/default/static/ui/nodeshot/js/views/map.js
JavaScript
gpl-3.0
50,921
[ 30522, 1006, 3853, 1006, 1007, 1063, 30524, 1001, 4949, 1011, 9621, 1011, 23561, 1005, 1010, 4655, 1024, 1063, 4180, 1024, 1005, 1001, 4949, 1011, 1046, 2015, 1005, 1010, 5722, 1024, 1005, 1001, 5722, 1011, 1046, 2015, 1005, 1010, 9320, 1...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* * yosys -- Yosys Open SYnthesis Suite * * Copyright (C) 2020 whitequark <whitequark@whitequark.org> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ // This file is a part of the CXXRTL C API. It should be used together with `cxxrtl_vcd_capi.h`. #include <backends/cxxrtl/cxxrtl_vcd.h> #include <backends/cxxrtl/cxxrtl_vcd_capi.h> extern const cxxrtl::debug_items &cxxrtl_debug_items_from_handle(cxxrtl_handle handle); struct _cxxrtl_vcd { cxxrtl::vcd_writer writer; bool flush = false; }; cxxrtl_vcd cxxrtl_vcd_create() { return new _cxxrtl_vcd; } void cxxrtl_vcd_destroy(cxxrtl_vcd vcd) { delete vcd; } void cxxrtl_vcd_timescale(cxxrtl_vcd vcd, int number, const char *unit) { vcd->writer.timescale(number, unit); } void cxxrtl_vcd_add(cxxrtl_vcd vcd, const char *name, cxxrtl_object *object) { // Note the copy. We don't know whether `object` came from a design (in which case it is // an instance of `debug_item`), or from user code (in which case it is an instance of // `cxxrtl_object`), so casting the pointer wouldn't be safe. vcd->writer.add(name, cxxrtl::debug_item(*object)); } void cxxrtl_vcd_add_from(cxxrtl_vcd vcd, cxxrtl_handle handle) { vcd->writer.add(cxxrtl_debug_items_from_handle(handle)); } void cxxrtl_vcd_add_from_if(cxxrtl_vcd vcd, cxxrtl_handle handle, void *data, int (*filter)(void *data, const char *name, const cxxrtl_object *object)) { vcd->writer.add(cxxrtl_debug_items_from_handle(handle), [=](const std::string &name, const cxxrtl::debug_item &item) { return filter(data, name.c_str(), static_cast<const cxxrtl_object*>(&item)); }); } void cxxrtl_vcd_add_from_without_memories(cxxrtl_vcd vcd, cxxrtl_handle handle) { vcd->writer.add_without_memories(cxxrtl_debug_items_from_handle(handle)); } void cxxrtl_vcd_sample(cxxrtl_vcd vcd, uint64_t time) { if (vcd->flush) { vcd->writer.buffer.clear(); vcd->flush = false; } vcd->writer.sample(time); } void cxxrtl_vcd_read(cxxrtl_vcd vcd, const char **data, size_t *size) { if (vcd->flush) { vcd->writer.buffer.clear(); vcd->flush = false; } *data = vcd->writer.buffer.c_str(); *size = vcd->writer.buffer.size(); vcd->flush = true; }
SymbiFlow/yosys
backends/cxxrtl/cxxrtl_vcd_capi.cc
C++
isc
2,816
[ 30522, 1013, 1008, 1008, 10930, 6508, 2015, 1011, 1011, 10930, 6508, 2015, 2330, 10752, 7621, 1008, 1008, 9385, 1006, 1039, 1007, 12609, 2317, 16211, 8024, 1026, 2317, 16211, 8024, 1030, 2317, 16211, 8024, 1012, 8917, 1028, 1008, 1008, 6656...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<!-- Forms commonly use checkboxes for questions that may have more than one answer. Checkboxes are a type of input Each of your checkboxes should be nested within its own label element. All related checkbox inputs should have the same name attribute. Here's an example of a checkbox: <label for="loving"><input id="loving" type="checkbox" name="personality"> Loving</label> Add to your form a set of three checkboxes. Each checkbox should be nested within its own label element. All three should share the name attribute of personality. --> <h2>CatPhotoApp</h2> <main> <p>Click here to view more <a href="#">cat photos</a>.</p> <a href="#"> <img src="https://bit.ly/fcc-relaxing-cat" alt="A cute orange cat lying on its back."> </a> <p>Things cats love:</p> <ul> <li>cat nip</li> <li>laser pointers</li> <li>lasagna</li> </ul> <p>Top 3 things cats hate:</p> <ol> <li>flea treatment</li> <li>thunder</li> <li>other cats</li> </ol> <form action="/submit-cat-photo"> <label for="indoor"> <input id="indoor" type="radio" name="indoor-outdoor"> Indoor</label> <label for="outdoor"> <input id="outdoor" type="radio" name="indoor-outdoor">Outdoor</label> <br> <label for="playful"> <input id="playful" type="checkbox" name="personality">Playful</label> <label for="shy"> <input id="shy" type="checkbox" name="personality"> Shy</label> <label for="loving"> <input id="loving" type="checkbox" name="personality">Loving</label> <input type="text" placeholder="cat photo URL" required> <button type="submit">Submit</button> </form> </main>
Kaskade01/freecodecamp
01-RESPONSIVE-WEB-DESIGN/01_BASIC_HTML_AND_HTML5/23 - Create a Set of Checkboxes.html
HTML
gpl-3.0
1,770
[ 30522, 1026, 999, 1011, 1011, 3596, 4141, 2224, 4638, 8758, 2229, 2005, 3980, 2008, 2089, 2031, 2062, 2084, 2028, 3437, 1012, 4638, 8758, 2229, 2024, 1037, 2828, 1997, 7953, 2169, 1997, 2115, 4638, 8758, 2229, 2323, 2022, 9089, 2098, 2306...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/*************************************************************************** ---------------------------------------------------- date : 27.12.2014 copyright : (C) 2014 by Matthias Kuhn email : matthias (at) opengis.ch *************************************************************************** * * * 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 "featurelistextentcontroller.h" #include <qgsgeometry.h> FeatureListExtentController::FeatureListExtentController( QObject* parent ) : QObject( parent ) , mModel( 0 ) , mSelection( 0 ) , mMapSettings( 0 ) , mAutoZoom( false ) { connect( this, SIGNAL( autoZoomChanged() ), SLOT( zoomToSelected() ) ); connect( this, SIGNAL( modelChanged() ), SLOT( onModelChanged() ) ); connect( this, SIGNAL( selectionChanged() ), SLOT( onModelChanged() ) ); } FeatureListExtentController::~FeatureListExtentController() { } void FeatureListExtentController::zoomToSelected() const { if ( mModel && mSelection && mMapSettings ) { Feature feat = mSelection->selectedFeature().value<Feature>(); QgsRectangle featureExtent = feat.qgsFeature().geometry()->boundingBox(); QgsRectangle bufferedExtent = featureExtent.buffer( qMax( featureExtent.width(), featureExtent.height() ) ); mMapSettings->setExtent( bufferedExtent ); } } void FeatureListExtentController::onModelChanged() { if ( mModel && mSelection ) { connect( mSelection, SIGNAL( selectionChanged() ), SLOT( onCurrentSelectionChanged() ) ); } } void FeatureListExtentController::onCurrentSelectionChanged() { if ( mAutoZoom ) { zoomToSelected(); } }
ryfx/QField
src/featurelistextentcontroller.cpp
C++
gpl-2.0
2,199
[ 30522, 1013, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 100...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/json/json_parser.h" #include <cmath> #include "base/logging.h" #include "base/macros.h" #include "base/memory/scoped_ptr.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_piece.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversion_utils.h" #include "base/strings/utf_string_conversions.h" #include "base/third_party/icu/icu_utf.h" #include "base/values.h" namespace base { namespace internal { namespace { const int kStackMaxDepth = 100; const int32_t kExtendedASCIIStart = 0x80; // This and the class below are used to own the JSON input string for when // string tokens are stored as StringPiece instead of std::string. This // optimization avoids about 2/3rds of string memory copies. The constructor // takes ownership of the input string. The real root value is Swap()ed into // the new instance. class DictionaryHiddenRootValue : public DictionaryValue { public: DictionaryHiddenRootValue(std::string* json, Value* root) : json_(json) { DCHECK(root->IsType(Value::TYPE_DICTIONARY)); DictionaryValue::Swap(static_cast<DictionaryValue*>(root)); } void Swap(DictionaryValue* other) override { DVLOG(1) << "Swap()ing a DictionaryValue inefficiently."; // First deep copy to convert JSONStringValue to std::string and swap that // copy with |other|, which contains the new contents of |this|. scoped_ptr<DictionaryValue> copy(DeepCopy()); copy->Swap(other); // Then erase the contents of the current dictionary and swap in the // new contents, originally from |other|. Clear(); json_.reset(); DictionaryValue::Swap(copy.get()); } // Not overriding DictionaryValue::Remove because it just calls through to // the method below. bool RemoveWithoutPathExpansion(const std::string& key, scoped_ptr<Value>* out) override { // If the caller won't take ownership of the removed value, just call up. if (!out) return DictionaryValue::RemoveWithoutPathExpansion(key, out); DVLOG(1) << "Remove()ing from a DictionaryValue inefficiently."; // Otherwise, remove the value while its still "owned" by this and copy it // to convert any JSONStringValues to std::string. scoped_ptr<Value> out_owned; if (!DictionaryValue::RemoveWithoutPathExpansion(key, &out_owned)) return false; out->reset(out_owned->DeepCopy()); return true; } private: scoped_ptr<std::string> json_; DISALLOW_COPY_AND_ASSIGN(DictionaryHiddenRootValue); }; class ListHiddenRootValue : public ListValue { public: ListHiddenRootValue(std::string* json, Value* root) : json_(json) { DCHECK(root->IsType(Value::TYPE_LIST)); ListValue::Swap(static_cast<ListValue*>(root)); } void Swap(ListValue* other) override { DVLOG(1) << "Swap()ing a ListValue inefficiently."; // First deep copy to convert JSONStringValue to std::string and swap that // copy with |other|, which contains the new contents of |this|. scoped_ptr<ListValue> copy(DeepCopy()); copy->Swap(other); // Then erase the contents of the current list and swap in the new contents, // originally from |other|. Clear(); json_.reset(); ListValue::Swap(copy.get()); } bool Remove(size_t index, scoped_ptr<Value>* out) override { // If the caller won't take ownership of the removed value, just call up. if (!out) return ListValue::Remove(index, out); DVLOG(1) << "Remove()ing from a ListValue inefficiently."; // Otherwise, remove the value while its still "owned" by this and copy it // to convert any JSONStringValues to std::string. scoped_ptr<Value> out_owned; if (!ListValue::Remove(index, &out_owned)) return false; out->reset(out_owned->DeepCopy()); return true; } private: scoped_ptr<std::string> json_; DISALLOW_COPY_AND_ASSIGN(ListHiddenRootValue); }; // A variant on StringValue that uses StringPiece instead of copying the string // into the Value. This can only be stored in a child of hidden root (above), // otherwise the referenced string will not be guaranteed to outlive it. class JSONStringValue : public Value { public: explicit JSONStringValue(const StringPiece& piece) : Value(TYPE_STRING), string_piece_(piece) { } // Overridden from Value: bool GetAsString(std::string* out_value) const override { string_piece_.CopyToString(out_value); return true; } bool GetAsString(string16* out_value) const override { *out_value = UTF8ToUTF16(string_piece_); return true; } Value* DeepCopy() const override { return new StringValue(string_piece_.as_string()); } bool Equals(const Value* other) const override { std::string other_string; return other->IsType(TYPE_STRING) && other->GetAsString(&other_string) && StringPiece(other_string) == string_piece_; } private: // The location in the original input stream. StringPiece string_piece_; DISALLOW_COPY_AND_ASSIGN(JSONStringValue); }; // Simple class that checks for maximum recursion/"stack overflow." class StackMarker { public: explicit StackMarker(int* depth) : depth_(depth) { ++(*depth_); DCHECK_LE(*depth_, kStackMaxDepth); } ~StackMarker() { --(*depth_); } bool IsTooDeep() const { return *depth_ >= kStackMaxDepth; } private: int* const depth_; DISALLOW_COPY_AND_ASSIGN(StackMarker); }; } // namespace JSONParser::JSONParser(int options) : options_(options), start_pos_(NULL), pos_(NULL), end_pos_(NULL), index_(0), stack_depth_(0), line_number_(0), index_last_line_(0), error_code_(JSONReader::JSON_NO_ERROR), error_line_(0), error_column_(0) { } JSONParser::~JSONParser() { } Value* JSONParser::Parse(const StringPiece& input) { scoped_ptr<std::string> input_copy; // If the children of a JSON root can be detached, then hidden roots cannot // be used, so do not bother copying the input because StringPiece will not // be used anywhere. if (!(options_ & JSON_DETACHABLE_CHILDREN)) { input_copy.reset(new std::string(input.as_string())); start_pos_ = input_copy->data(); } else { start_pos_ = input.data(); } pos_ = start_pos_; end_pos_ = start_pos_ + input.length(); index_ = 0; line_number_ = 1; index_last_line_ = 0; error_code_ = JSONReader::JSON_NO_ERROR; error_line_ = 0; error_column_ = 0; // When the input JSON string starts with a UTF-8 Byte-Order-Mark // <0xEF 0xBB 0xBF>, advance the start position to avoid the // ParseNextToken function mis-treating a Unicode BOM as an invalid // character and returning NULL. if (CanConsume(3) && static_cast<uint8_t>(*pos_) == 0xEF && static_cast<uint8_t>(*(pos_ + 1)) == 0xBB && static_cast<uint8_t>(*(pos_ + 2)) == 0xBF) { NextNChars(3); } // Parse the first and any nested tokens. scoped_ptr<Value> root(ParseNextToken()); if (!root.get()) return NULL; // Make sure the input stream is at an end. if (GetNextToken() != T_END_OF_INPUT) { if (!CanConsume(1) || (NextChar() && GetNextToken() != T_END_OF_INPUT)) { ReportError(JSONReader::JSON_UNEXPECTED_DATA_AFTER_ROOT, 1); return NULL; } } // Dictionaries and lists can contain JSONStringValues, so wrap them in a // hidden root. if (!(options_ & JSON_DETACHABLE_CHILDREN)) { if (root->IsType(Value::TYPE_DICTIONARY)) { return new DictionaryHiddenRootValue(input_copy.release(), root.get()); } else if (root->IsType(Value::TYPE_LIST)) { return new ListHiddenRootValue(input_copy.release(), root.get()); } else if (root->IsType(Value::TYPE_STRING)) { // A string type could be a JSONStringValue, but because there's no // corresponding HiddenRootValue, the memory will be lost. Deep copy to // preserve it. return root->DeepCopy(); } } // All other values can be returned directly. return root.release(); } JSONReader::JsonParseError JSONParser::error_code() const { return error_code_; } std::string JSONParser::GetErrorMessage() const { return FormatErrorMessage(error_line_, error_column_, JSONReader::ErrorCodeToString(error_code_)); } int JSONParser::error_line() const { return error_line_; } int JSONParser::error_column() const { return error_column_; } // StringBuilder /////////////////////////////////////////////////////////////// JSONParser::StringBuilder::StringBuilder() : pos_(NULL), length_(0), string_(NULL) { } JSONParser::StringBuilder::StringBuilder(const char* pos) : pos_(pos), length_(0), string_(NULL) { } void JSONParser::StringBuilder::Swap(StringBuilder* other) { std::swap(other->string_, string_); std::swap(other->pos_, pos_); std::swap(other->length_, length_); } JSONParser::StringBuilder::~StringBuilder() { delete string_; } void JSONParser::StringBuilder::Append(const char& c) { DCHECK_GE(c, 0); DCHECK_LT(static_cast<unsigned char>(c), 128); if (string_) string_->push_back(c); else ++length_; } void JSONParser::StringBuilder::AppendString(const std::string& str) { DCHECK(string_); string_->append(str); } void JSONParser::StringBuilder::Convert() { if (string_) return; string_ = new std::string(pos_, length_); } bool JSONParser::StringBuilder::CanBeStringPiece() const { return !string_; } StringPiece JSONParser::StringBuilder::AsStringPiece() { if (string_) return StringPiece(); return StringPiece(pos_, length_); } const std::string& JSONParser::StringBuilder::AsString() { if (!string_) Convert(); return *string_; } // JSONParser private ////////////////////////////////////////////////////////// inline bool JSONParser::CanConsume(int length) { return pos_ + length <= end_pos_; } const char* JSONParser::NextChar() { DCHECK(CanConsume(1)); ++index_; ++pos_; return pos_; } void JSONParser::NextNChars(int n) { DCHECK(CanConsume(n)); index_ += n; pos_ += n; } JSONParser::Token JSONParser::GetNextToken() { EatWhitespaceAndComments(); if (!CanConsume(1)) return T_END_OF_INPUT; switch (*pos_) { case '{': return T_OBJECT_BEGIN; case '}': return T_OBJECT_END; case '[': return T_ARRAY_BEGIN; case ']': return T_ARRAY_END; case '"': return T_STRING; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '-': return T_NUMBER; case 't': return T_BOOL_TRUE; case 'f': return T_BOOL_FALSE; case 'n': return T_NULL; case ',': return T_LIST_SEPARATOR; case ':': return T_OBJECT_PAIR_SEPARATOR; default: return T_INVALID_TOKEN; } } void JSONParser::EatWhitespaceAndComments() { while (pos_ < end_pos_) { switch (*pos_) { case '\r': case '\n': index_last_line_ = index_; // Don't increment line_number_ twice for "\r\n". if (!(*pos_ == '\n' && pos_ > start_pos_ && *(pos_ - 1) == '\r')) ++line_number_; // Fall through. case ' ': case '\t': NextChar(); break; case '/': if (!EatComment()) return; break; default: return; } } } bool JSONParser::EatComment() { if (*pos_ != '/' || !CanConsume(1)) return false; char next_char = *NextChar(); if (next_char == '/') { // Single line comment, read to newline. while (CanConsume(1)) { next_char = *NextChar(); if (next_char == '\n' || next_char == '\r') return true; } } else if (next_char == '*') { char previous_char = '\0'; // Block comment, read until end marker. while (CanConsume(1)) { next_char = *NextChar(); if (previous_char == '*' && next_char == '/') { // EatWhitespaceAndComments will inspect pos_, which will still be on // the last / of the comment, so advance once more (which may also be // end of input). NextChar(); return true; } previous_char = next_char; } // If the comment is unterminated, GetNextToken will report T_END_OF_INPUT. } return false; } Value* JSONParser::ParseNextToken() { return ParseToken(GetNextToken()); } Value* JSONParser::ParseToken(Token token) { switch (token) { case T_OBJECT_BEGIN: return ConsumeDictionary(); case T_ARRAY_BEGIN: return ConsumeList(); case T_STRING: return ConsumeString(); case T_NUMBER: return ConsumeNumber(); case T_BOOL_TRUE: case T_BOOL_FALSE: case T_NULL: return ConsumeLiteral(); default: ReportError(JSONReader::JSON_UNEXPECTED_TOKEN, 1); return NULL; } } Value* JSONParser::ConsumeDictionary() { if (*pos_ != '{') { ReportError(JSONReader::JSON_UNEXPECTED_TOKEN, 1); return NULL; } StackMarker depth_check(&stack_depth_); if (depth_check.IsTooDeep()) { ReportError(JSONReader::JSON_TOO_MUCH_NESTING, 1); return NULL; } scoped_ptr<DictionaryValue> dict(new DictionaryValue); NextChar(); Token token = GetNextToken(); while (token != T_OBJECT_END) { if (token != T_STRING) { ReportError(JSONReader::JSON_UNQUOTED_DICTIONARY_KEY, 1); return NULL; } // First consume the key. StringBuilder key; if (!ConsumeStringRaw(&key)) { return NULL; } // Read the separator. NextChar(); token = GetNextToken(); if (token != T_OBJECT_PAIR_SEPARATOR) { ReportError(JSONReader::JSON_SYNTAX_ERROR, 1); return NULL; } // The next token is the value. Ownership transfers to |dict|. NextChar(); Value* value = ParseNextToken(); if (!value) { // ReportError from deeper level. return NULL; } dict->SetWithoutPathExpansion(key.AsString(), value); NextChar(); token = GetNextToken(); if (token == T_LIST_SEPARATOR) { NextChar(); token = GetNextToken(); if (token == T_OBJECT_END && !(options_ & JSON_ALLOW_TRAILING_COMMAS)) { ReportError(JSONReader::JSON_TRAILING_COMMA, 1); return NULL; } } else if (token != T_OBJECT_END) { ReportError(JSONReader::JSON_SYNTAX_ERROR, 0); return NULL; } } return dict.release(); } Value* JSONParser::ConsumeList() { if (*pos_ != '[') { ReportError(JSONReader::JSON_UNEXPECTED_TOKEN, 1); return NULL; } StackMarker depth_check(&stack_depth_); if (depth_check.IsTooDeep()) { ReportError(JSONReader::JSON_TOO_MUCH_NESTING, 1); return NULL; } scoped_ptr<ListValue> list(new ListValue); NextChar(); Token token = GetNextToken(); while (token != T_ARRAY_END) { Value* item = ParseToken(token); if (!item) { // ReportError from deeper level. return NULL; } list->Append(item); NextChar(); token = GetNextToken(); if (token == T_LIST_SEPARATOR) { NextChar(); token = GetNextToken(); if (token == T_ARRAY_END && !(options_ & JSON_ALLOW_TRAILING_COMMAS)) { ReportError(JSONReader::JSON_TRAILING_COMMA, 1); return NULL; } } else if (token != T_ARRAY_END) { ReportError(JSONReader::JSON_SYNTAX_ERROR, 1); return NULL; } } return list.release(); } Value* JSONParser::ConsumeString() { StringBuilder string; if (!ConsumeStringRaw(&string)) return NULL; // Create the Value representation, using a hidden root, if configured // to do so, and if the string can be represented by StringPiece. if (string.CanBeStringPiece() && !(options_ & JSON_DETACHABLE_CHILDREN)) { return new JSONStringValue(string.AsStringPiece()); } else { if (string.CanBeStringPiece()) string.Convert(); return new StringValue(string.AsString()); } } bool JSONParser::ConsumeStringRaw(StringBuilder* out) { if (*pos_ != '"') { ReportError(JSONReader::JSON_UNEXPECTED_TOKEN, 1); return false; } // StringBuilder will internally build a StringPiece unless a UTF-16 // conversion occurs, at which point it will perform a copy into a // std::string. StringBuilder string(NextChar()); int length = end_pos_ - start_pos_; int32_t next_char = 0; while (CanConsume(1)) { pos_ = start_pos_ + index_; // CBU8_NEXT is postcrement. CBU8_NEXT(start_pos_, index_, length, next_char); if (next_char < 0 || !IsValidCharacter(next_char)) { ReportError(JSONReader::JSON_UNSUPPORTED_ENCODING, 1); return false; } // If this character is an escape sequence... if (next_char == '\\') { // The input string will be adjusted (either by combining the two // characters of an encoded escape sequence, or with a UTF conversion), // so using StringPiece isn't possible -- force a conversion. string.Convert(); if (!CanConsume(1)) { ReportError(JSONReader::JSON_INVALID_ESCAPE, 0); return false; } switch (*NextChar()) { // Allowed esape sequences: case 'x': { // UTF-8 sequence. // UTF-8 \x escape sequences are not allowed in the spec, but they // are supported here for backwards-compatiblity with the old parser. if (!CanConsume(2)) { ReportError(JSONReader::JSON_INVALID_ESCAPE, 1); return false; } int hex_digit = 0; if (!HexStringToInt(StringPiece(NextChar(), 2), &hex_digit)) { ReportError(JSONReader::JSON_INVALID_ESCAPE, -1); return false; } NextChar(); if (hex_digit < kExtendedASCIIStart) string.Append(static_cast<char>(hex_digit)); else DecodeUTF8(hex_digit, &string); break; } case 'u': { // UTF-16 sequence. // UTF units are of the form \uXXXX. if (!CanConsume(5)) { // 5 being 'u' and four HEX digits. ReportError(JSONReader::JSON_INVALID_ESCAPE, 0); return false; } // Skip the 'u'. NextChar(); std::string utf8_units; if (!DecodeUTF16(&utf8_units)) { ReportError(JSONReader::JSON_INVALID_ESCAPE, -1); return false; } string.AppendString(utf8_units); break; } case '"': string.Append('"'); break; case '\\': string.Append('\\'); break; case '/': string.Append('/'); break; case 'b': string.Append('\b'); break; case 'f': string.Append('\f'); break; case 'n': string.Append('\n'); break; case 'r': string.Append('\r'); break; case 't': string.Append('\t'); break; case 'v': // Not listed as valid escape sequence in the RFC. string.Append('\v'); break; // All other escape squences are illegal. default: ReportError(JSONReader::JSON_INVALID_ESCAPE, 0); return false; } } else if (next_char == '"') { --index_; // Rewind by one because of CBU8_NEXT. out->Swap(&string); return true; } else { if (next_char < kExtendedASCIIStart) string.Append(static_cast<char>(next_char)); else DecodeUTF8(next_char, &string); } } ReportError(JSONReader::JSON_SYNTAX_ERROR, 0); return false; } // Entry is at the first X in \uXXXX. bool JSONParser::DecodeUTF16(std::string* dest_string) { if (!CanConsume(4)) return false; // This is a 32-bit field because the shift operations in the // conversion process below cause MSVC to error about "data loss." // This only stores UTF-16 code units, though. // Consume the UTF-16 code unit, which may be a high surrogate. int code_unit16_high = 0; if (!HexStringToInt(StringPiece(pos_, 4), &code_unit16_high)) return false; // Only add 3, not 4, because at the end of this iteration, the parser has // finished working with the last digit of the UTF sequence, meaning that // the next iteration will advance to the next byte. NextNChars(3); // Used to convert the UTF-16 code units to a code point and then to a UTF-8 // code unit sequence. char code_unit8[8] = { 0 }; size_t offset = 0; // If this is a high surrogate, consume the next code unit to get the // low surrogate. if (CBU16_IS_SURROGATE(code_unit16_high)) { // Make sure this is the high surrogate. If not, it's an encoding // error. if (!CBU16_IS_SURROGATE_LEAD(code_unit16_high)) return false; // Make sure that the token has more characters to consume the // lower surrogate. if (!CanConsume(6)) // 6 being '\' 'u' and four HEX digits. return false; if (*NextChar() != '\\' || *NextChar() != 'u') return false; NextChar(); // Read past 'u'. int code_unit16_low = 0; if (!HexStringToInt(StringPiece(pos_, 4), &code_unit16_low)) return false; NextNChars(3); if (!CBU16_IS_TRAIL(code_unit16_low)) { return false; } uint32_t code_point = CBU16_GET_SUPPLEMENTARY(code_unit16_high, code_unit16_low); if (!IsValidCharacter(code_point)) return false; offset = 0; CBU8_APPEND_UNSAFE(code_unit8, offset, code_point); } else { // Not a surrogate. DCHECK(CBU16_IS_SINGLE(code_unit16_high)); if (!IsValidCharacter(code_unit16_high)) return false; CBU8_APPEND_UNSAFE(code_unit8, offset, code_unit16_high); } dest_string->append(code_unit8); return true; } void JSONParser::DecodeUTF8(const int32_t& point, StringBuilder* dest) { DCHECK(IsValidCharacter(point)); // Anything outside of the basic ASCII plane will need to be decoded from // int32_t to a multi-byte sequence. if (point < kExtendedASCIIStart) { dest->Append(static_cast<char>(point)); } else { char utf8_units[4] = { 0 }; int offset = 0; CBU8_APPEND_UNSAFE(utf8_units, offset, point); dest->Convert(); // CBU8_APPEND_UNSAFE can overwrite up to 4 bytes, so utf8_units may not be // zero terminated at this point. |offset| contains the correct length. dest->AppendString(std::string(utf8_units, offset)); } } Value* JSONParser::ConsumeNumber() { const char* num_start = pos_; const int start_index = index_; int end_index = start_index; if (*pos_ == '-') NextChar(); if (!ReadInt(false)) { ReportError(JSONReader::JSON_SYNTAX_ERROR, 1); return NULL; } end_index = index_; // The optional fraction part. if (*pos_ == '.') { if (!CanConsume(1)) { ReportError(JSONReader::JSON_SYNTAX_ERROR, 1); return NULL; } NextChar(); if (!ReadInt(true)) { ReportError(JSONReader::JSON_SYNTAX_ERROR, 1); return NULL; } end_index = index_; } // Optional exponent part. if (*pos_ == 'e' || *pos_ == 'E') { NextChar(); if (*pos_ == '-' || *pos_ == '+') NextChar(); if (!ReadInt(true)) { ReportError(JSONReader::JSON_SYNTAX_ERROR, 1); return NULL; } end_index = index_; } // ReadInt is greedy because numbers have no easily detectable sentinel, // so save off where the parser should be on exit (see Consume invariant at // the top of the header), then make sure the next token is one which is // valid. const char* exit_pos = pos_ - 1; int exit_index = index_ - 1; switch (GetNextToken()) { case T_OBJECT_END: case T_ARRAY_END: case T_LIST_SEPARATOR: case T_END_OF_INPUT: break; default: ReportError(JSONReader::JSON_SYNTAX_ERROR, 1); return NULL; } pos_ = exit_pos; index_ = exit_index; StringPiece num_string(num_start, end_index - start_index); int num_int; if (StringToInt(num_string, &num_int)) return new FundamentalValue(num_int); double num_double; if (StringToDouble(num_string.as_string(), &num_double) && std::isfinite(num_double)) { return new FundamentalValue(num_double); } return NULL; } bool JSONParser::ReadInt(bool allow_leading_zeros) { char first = *pos_; int len = 0; char c = first; while (CanConsume(1) && IsAsciiDigit(c)) { c = *NextChar(); ++len; } if (len == 0) return false; if (!allow_leading_zeros && len > 1 && first == '0') return false; return true; } Value* JSONParser::ConsumeLiteral() { switch (*pos_) { case 't': { const char kTrueLiteral[] = "true"; const int kTrueLen = static_cast<int>(strlen(kTrueLiteral)); if (!CanConsume(kTrueLen - 1) || !StringsAreEqual(pos_, kTrueLiteral, kTrueLen)) { ReportError(JSONReader::JSON_SYNTAX_ERROR, 1); return NULL; } NextNChars(kTrueLen - 1); return new FundamentalValue(true); } case 'f': { const char kFalseLiteral[] = "false"; const int kFalseLen = static_cast<int>(strlen(kFalseLiteral)); if (!CanConsume(kFalseLen - 1) || !StringsAreEqual(pos_, kFalseLiteral, kFalseLen)) { ReportError(JSONReader::JSON_SYNTAX_ERROR, 1); return NULL; } NextNChars(kFalseLen - 1); return new FundamentalValue(false); } case 'n': { const char kNullLiteral[] = "null"; const int kNullLen = static_cast<int>(strlen(kNullLiteral)); if (!CanConsume(kNullLen - 1) || !StringsAreEqual(pos_, kNullLiteral, kNullLen)) { ReportError(JSONReader::JSON_SYNTAX_ERROR, 1); return NULL; } NextNChars(kNullLen - 1); return Value::CreateNullValue().release(); } default: ReportError(JSONReader::JSON_UNEXPECTED_TOKEN, 1); return NULL; } } // static bool JSONParser::StringsAreEqual(const char* one, const char* two, size_t len) { return strncmp(one, two, len) == 0; } void JSONParser::ReportError(JSONReader::JsonParseError code, int column_adjust) { error_code_ = code; error_line_ = line_number_; error_column_ = index_ - index_last_line_ + column_adjust; } // static std::string JSONParser::FormatErrorMessage(int line, int column, const std::string& description) { if (line || column) { return StringPrintf("Line: %i, column: %i, %s", line, column, description.c_str()); } return description; } } // namespace internal } // namespace base
junhuac/MQUIC
src/base/json/json_parser.cc
C++
mit
26,797
[ 30522, 1013, 1013, 9385, 1006, 1039, 1007, 2262, 1996, 10381, 21716, 5007, 6048, 1012, 2035, 2916, 9235, 1012, 1013, 1013, 2224, 1997, 2023, 3120, 3642, 2003, 9950, 2011, 1037, 18667, 2094, 1011, 2806, 6105, 2008, 2064, 2022, 1013, 1013, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<?php /* * This file is part of the PHPBench package * * (c) Daniel Leech <daniel@dantleech.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * */ namespace PhpBench\Tests\Unit\Registry; use InvalidArgumentException; use PhpBench\Registry\Config; use PhpBench\Tests\TestCase; class ConfigTest extends TestCase { private $config; protected function setUp(): void { } /** * It should throw an exception if an offset does not exist. * */ public function testExceptionOffsetNotExist(): void { $this->expectExceptionMessage('Configuration offset "offset_not_exist" does not exist.'); $this->expectException(InvalidArgumentException::class); $config = new Config( 'test', [ 'foo' => 'bar', 'bar' => [ 'one' => 1, 'two' => 2, ], ] ); $config['offset_not_exist']; } /** * It should throw an exception if an invalid name is given. * * @dataProvider provideInvalidName */ public function testInvalidName($name): void { $this->expectException(InvalidArgumentException::class); new Config($name, []); } public function provideInvalidName() { return [ ['he lo'], ['foo&'], [':'], [''], ]; } /** * It should allow good names. * * @dataProvider provideGoodName */ public function testGoodName($name): void { $config = new Config($name, []); $this->assertEquals($name, $config->getName()); } public function provideGoodName() { return [ ['helo'], ['foo-bar'], ['foo_bar'], ]; } }
phpbench/phpbench
tests/Unit/Registry/ConfigTest.php
PHP
mit
1,895
[ 30522, 1026, 1029, 25718, 1013, 1008, 1008, 2023, 5371, 2003, 2112, 1997, 1996, 25718, 10609, 2818, 7427, 1008, 1008, 1006, 1039, 1007, 3817, 3389, 2818, 1026, 3817, 1030, 4907, 9286, 15937, 1012, 4012, 1028, 1008, 1008, 2005, 1996, 2440, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
'use strict'; const chai = require('chai'), expect = chai.expect, Support = require(__dirname + '/../../support'), DataTypes = require(__dirname + '/../../../../lib/data-types'), dialect = Support.getTestDialect(), _ = require('lodash'), moment = require('moment'), QueryGenerator = require('../../../../lib/dialects/sqlite/query-generator'); if (dialect === 'sqlite') { describe('[SQLITE Specific] QueryGenerator', () => { beforeEach(function() { this.User = this.sequelize.define('User', { username: DataTypes.STRING }); return this.User.sync({ force: true }); }); const suites = { arithmeticQuery: [ { title:'Should use the plus operator', arguments: ['+', 'myTable', { foo: 'bar' }, {}], expectation: 'UPDATE `myTable` SET `foo`=`foo`+ \'bar\' ' }, { title:'Should use the plus operator with where clause', arguments: ['+', 'myTable', { foo: 'bar' }, { bar: 'biz'}], expectation: 'UPDATE `myTable` SET `foo`=`foo`+ \'bar\' WHERE `bar` = \'biz\'' }, { title:'Should use the minus operator', arguments: ['-', 'myTable', { foo: 'bar' }], expectation: 'UPDATE `myTable` SET `foo`=`foo`- \'bar\' ' }, { title:'Should use the minus operator with negative value', arguments: ['-', 'myTable', { foo: -1 }], expectation: 'UPDATE `myTable` SET `foo`=`foo`- -1 ' }, { title:'Should use the minus operator with where clause', arguments: ['-', 'myTable', { foo: 'bar' }, { bar: 'biz'}], expectation: 'UPDATE `myTable` SET `foo`=`foo`- \'bar\' WHERE `bar` = \'biz\'' } ], attributesToSQL: [ { arguments: [{id: 'INTEGER'}], expectation: {id: 'INTEGER'} }, { arguments: [{id: 'INTEGER', foo: 'VARCHAR(255)'}], expectation: {id: 'INTEGER', foo: 'VARCHAR(255)'} }, { arguments: [{id: {type: 'INTEGER'}}], expectation: {id: 'INTEGER'} }, { arguments: [{id: {type: 'INTEGER', allowNull: false}}], expectation: {id: 'INTEGER NOT NULL'} }, { arguments: [{id: {type: 'INTEGER', allowNull: true}}], expectation: {id: 'INTEGER'} }, { arguments: [{id: {type: 'INTEGER', primaryKey: true, autoIncrement: true}}], expectation: {id: 'INTEGER PRIMARY KEY AUTOINCREMENT'} }, { arguments: [{id: {type: 'INTEGER', defaultValue: 0}}], expectation: {id: 'INTEGER DEFAULT 0'} }, { arguments: [{id: {type: 'INTEGER', defaultValue: undefined}}], expectation: {id: 'INTEGER'} }, { arguments: [{id: {type: 'INTEGER', unique: true}}], expectation: {id: 'INTEGER UNIQUE'} }, // New references style { arguments: [{id: {type: 'INTEGER', references: { model: 'Bar' }}}], expectation: {id: 'INTEGER REFERENCES `Bar` (`id`)'} }, { arguments: [{id: {type: 'INTEGER', references: { model: 'Bar', key: 'pk' }}}], expectation: {id: 'INTEGER REFERENCES `Bar` (`pk`)'} }, { arguments: [{id: {type: 'INTEGER', references: { model: 'Bar' }, onDelete: 'CASCADE'}}], expectation: {id: 'INTEGER REFERENCES `Bar` (`id`) ON DELETE CASCADE'} }, { arguments: [{id: {type: 'INTEGER', references: { model: 'Bar' }, onUpdate: 'RESTRICT'}}], expectation: {id: 'INTEGER REFERENCES `Bar` (`id`) ON UPDATE RESTRICT'} }, { arguments: [{id: {type: 'INTEGER', allowNull: false, defaultValue: 1, references: { model: 'Bar' }, onDelete: 'CASCADE', onUpdate: 'RESTRICT'}}], expectation: {id: 'INTEGER NOT NULL DEFAULT 1 REFERENCES `Bar` (`id`) ON DELETE CASCADE ON UPDATE RESTRICT'} } ], createTableQuery: [ { arguments: ['myTable', {data: 'BLOB'}], expectation: 'CREATE TABLE IF NOT EXISTS `myTable` (`data` BLOB);' }, { arguments: ['myTable', {data: 'LONGBLOB'}], expectation: 'CREATE TABLE IF NOT EXISTS `myTable` (`data` LONGBLOB);' }, { arguments: ['myTable', {title: 'VARCHAR(255)', name: 'VARCHAR(255)'}], expectation: 'CREATE TABLE IF NOT EXISTS `myTable` (`title` VARCHAR(255), `name` VARCHAR(255));' }, { arguments: ['myTable', {title: 'VARCHAR BINARY(255)', number: 'INTEGER(5) UNSIGNED PRIMARY KEY '}], // length and unsigned are not allowed on primary key expectation: 'CREATE TABLE IF NOT EXISTS `myTable` (`title` VARCHAR BINARY(255), `number` INTEGER PRIMARY KEY);' }, { arguments: ['myTable', {title: 'ENUM("A", "B", "C")', name: 'VARCHAR(255)'}], expectation: 'CREATE TABLE IF NOT EXISTS `myTable` (`title` ENUM(\"A\", \"B\", \"C\"), `name` VARCHAR(255));' }, { arguments: ['myTable', {title: 'VARCHAR(255)', name: 'VARCHAR(255)', id: 'INTEGER PRIMARY KEY'}], expectation: 'CREATE TABLE IF NOT EXISTS `myTable` (`title` VARCHAR(255), `name` VARCHAR(255), `id` INTEGER PRIMARY KEY);' }, { arguments: ['myTable', {title: 'VARCHAR(255)', name: 'VARCHAR(255)', otherId: 'INTEGER REFERENCES `otherTable` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION'}], expectation: 'CREATE TABLE IF NOT EXISTS `myTable` (`title` VARCHAR(255), `name` VARCHAR(255), `otherId` INTEGER REFERENCES `otherTable` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION);' }, { arguments: ['myTable', {id: 'INTEGER PRIMARY KEY AUTOINCREMENT', name: 'VARCHAR(255)'}], expectation: 'CREATE TABLE IF NOT EXISTS `myTable` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `name` VARCHAR(255));' }, { arguments: ['myTable', {id: 'INTEGER PRIMARY KEY AUTOINCREMENT', name: 'VARCHAR(255)', surname: 'VARCHAR(255)'}, {uniqueKeys: {uniqueConstraint: {fields: ['name', 'surname']}}}], expectation: 'CREATE TABLE IF NOT EXISTS `myTable` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `name` VARCHAR(255), `surname` VARCHAR(255), UNIQUE (`name`, `surname`));' } ], selectQuery: [ { arguments: ['myTable'], expectation: 'SELECT * FROM `myTable`;', context: QueryGenerator }, { arguments: ['myTable', {attributes: ['id', 'name']}], expectation: 'SELECT `id`, `name` FROM `myTable`;', context: QueryGenerator }, { arguments: ['myTable', {where: {id: 2}}], expectation: 'SELECT * FROM `myTable` WHERE `myTable`.`id` = 2;', context: QueryGenerator }, { arguments: ['myTable', {where: {name: 'foo'}}], expectation: "SELECT * FROM `myTable` WHERE `myTable`.`name` = 'foo';", context: QueryGenerator }, { arguments: ['myTable', {where: {name: "foo';DROP TABLE myTable;"}}], expectation: "SELECT * FROM `myTable` WHERE `myTable`.`name` = 'foo\'\';DROP TABLE myTable;';", context: QueryGenerator }, { arguments: ['myTable', {where: 2}], expectation: 'SELECT * FROM `myTable` WHERE `myTable`.`id` = 2;', context: QueryGenerator }, { arguments: ['foo', { attributes: [['count(*)', 'count']] }], expectation: 'SELECT count(*) AS `count` FROM `foo`;', context: QueryGenerator }, { arguments: ['myTable', {order: ['id']}], expectation: 'SELECT * FROM `myTable` ORDER BY `id`;', context: QueryGenerator }, { arguments: ['myTable', {order: ['id', 'DESC']}], expectation: 'SELECT * FROM `myTable` ORDER BY `id`, `DESC`;', context: QueryGenerator }, { arguments: ['myTable', {order: ['myTable.id']}], expectation: 'SELECT * FROM `myTable` ORDER BY `myTable`.`id`;', context: QueryGenerator }, { arguments: ['myTable', {order: [['myTable.id', 'DESC']]}], expectation: 'SELECT * FROM `myTable` ORDER BY `myTable`.`id` DESC;', context: QueryGenerator }, { arguments: ['myTable', {order: [['id', 'DESC']]}, function(sequelize) {return sequelize.define('myTable', {});}], expectation: 'SELECT * FROM `myTable` AS `myTable` ORDER BY `myTable`.`id` DESC;', context: QueryGenerator, needsSequelize: true }, { arguments: ['myTable', {order: [['id', 'DESC'], ['name']]}, function(sequelize) {return sequelize.define('myTable', {});}], expectation: 'SELECT * FROM `myTable` AS `myTable` ORDER BY `myTable`.`id` DESC, `myTable`.`name`;', context: QueryGenerator, needsSequelize: true }, { title: 'sequelize.where with .fn as attribute and default comparator', arguments: ['myTable', function(sequelize) { return { where: sequelize.and( sequelize.where(sequelize.fn('LOWER', sequelize.col('user.name')), 'jan'), { type: 1 } ) }; }], expectation: "SELECT * FROM `myTable` WHERE (LOWER(`user`.`name`) = 'jan' AND `myTable`.`type` = 1);", context: QueryGenerator, needsSequelize: true }, { title: 'sequelize.where with .fn as attribute and LIKE comparator', arguments: ['myTable', function(sequelize) { return { where: sequelize.and( sequelize.where(sequelize.fn('LOWER', sequelize.col('user.name')), 'LIKE', '%t%'), { type: 1 } ) }; }], expectation: "SELECT * FROM `myTable` WHERE (LOWER(`user`.`name`) LIKE '%t%' AND `myTable`.`type` = 1);", context: QueryGenerator, needsSequelize: true }, { title: 'functions can take functions as arguments', arguments: ['myTable', function(sequelize) { return { order: [[sequelize.fn('f1', sequelize.fn('f2', sequelize.col('id'))), 'DESC']] }; }], expectation: 'SELECT * FROM `myTable` ORDER BY f1(f2(`id`)) DESC;', context: QueryGenerator, needsSequelize: true }, { title: 'functions can take all types as arguments', arguments: ['myTable', function(sequelize) { return { order: [ [sequelize.fn('f1', sequelize.col('myTable.id')), 'DESC'], [sequelize.fn('f2', 12, 'lalala', new Date(Date.UTC(2011, 2, 27, 10, 1, 55))), 'ASC'] ] }; }], expectation: "SELECT * FROM `myTable` ORDER BY f1(`myTable`.`id`) DESC, f2(12, 'lalala', '2011-03-27 10:01:55.000 +00:00') ASC;", context: QueryGenerator, needsSequelize: true }, { title: 'single string argument is not quoted', arguments: ['myTable', {group: 'name'}], expectation: 'SELECT * FROM `myTable` GROUP BY name;', context: QueryGenerator }, { arguments: ['myTable', {group: ['name']}], expectation: 'SELECT * FROM `myTable` GROUP BY `name`;', context: QueryGenerator }, { title: 'functions work for group by', arguments: ['myTable', function(sequelize) { return { group: [sequelize.fn('YEAR', sequelize.col('createdAt'))] }; }], expectation: 'SELECT * FROM `myTable` GROUP BY YEAR(`createdAt`);', context: QueryGenerator, needsSequelize: true }, { title: 'It is possible to mix sequelize.fn and string arguments to group by', arguments: ['myTable', function(sequelize) { return { group: [sequelize.fn('YEAR', sequelize.col('createdAt')), 'title'] }; }], expectation: 'SELECT * FROM `myTable` GROUP BY YEAR(`createdAt`), `title`;', context: QueryGenerator, needsSequelize: true }, { arguments: ['myTable', {group: ['name', 'title']}], expectation: 'SELECT * FROM `myTable` GROUP BY `name`, `title`;', context: QueryGenerator }, { arguments: ['myTable', {group: 'name', order: [['id', 'DESC']]}], expectation: 'SELECT * FROM `myTable` GROUP BY name ORDER BY `id` DESC;', context: QueryGenerator }, { title: 'HAVING clause works with where-like hash', arguments: ['myTable', function(sequelize) { return { attributes: ['*', [sequelize.fn('YEAR', sequelize.col('createdAt')), 'creationYear']], group: ['creationYear', 'title'], having: { creationYear: { gt: 2002 } } }; }], expectation: 'SELECT *, YEAR(`createdAt`) AS `creationYear` FROM `myTable` GROUP BY `creationYear`, `title` HAVING `creationYear` > 2002;', context: QueryGenerator, needsSequelize: true }, { arguments: ['myTable', {limit: 10}], expectation: 'SELECT * FROM `myTable` LIMIT 10;', context: QueryGenerator }, { arguments: ['myTable', {limit: 10, offset: 2}], expectation: 'SELECT * FROM `myTable` LIMIT 2, 10;', context: QueryGenerator }, { title: 'uses default limit if only offset is specified', arguments: ['myTable', {offset: 2}], expectation: 'SELECT * FROM `myTable` LIMIT 2, 10000000000000;', context: QueryGenerator }, { title: 'multiple where arguments', arguments: ['myTable', {where: {boat: 'canoe', weather: 'cold'}}], expectation: "SELECT * FROM `myTable` WHERE `myTable`.`boat` = 'canoe' AND `myTable`.`weather` = 'cold';", context: QueryGenerator }, { title: 'no where arguments (object)', arguments: ['myTable', {where: {}}], expectation: 'SELECT * FROM `myTable`;', context: QueryGenerator }, { title: 'no where arguments (string)', arguments: ['myTable', {where: ['']}], expectation: 'SELECT * FROM `myTable` WHERE 1=1;', context: QueryGenerator }, { title: 'no where arguments (null)', arguments: ['myTable', {where: null}], expectation: 'SELECT * FROM `myTable`;', context: QueryGenerator }, { title: 'buffer as where argument', arguments: ['myTable', {where: { field: new Buffer('Sequelize')}}], expectation: "SELECT * FROM `myTable` WHERE `myTable`.`field` = X'53657175656c697a65';", context: QueryGenerator }, { title: 'use != if ne !== null', arguments: ['myTable', {where: {field: {ne: 0}}}], expectation: 'SELECT * FROM `myTable` WHERE `myTable`.`field` != 0;', context: QueryGenerator }, { title: 'use IS NOT if ne === null', arguments: ['myTable', {where: {field: {ne: null}}}], expectation: 'SELECT * FROM `myTable` WHERE `myTable`.`field` IS NOT NULL;', context: QueryGenerator }, { title: 'use IS NOT if not === BOOLEAN', arguments: ['myTable', {where: {field: {not: true}}}], expectation: 'SELECT * FROM `myTable` WHERE `myTable`.`field` IS NOT 1;', context: QueryGenerator }, { title: 'use != if not !== BOOLEAN', arguments: ['myTable', {where: {field: {not: 3}}}], expectation: 'SELECT * FROM `myTable` WHERE `myTable`.`field` != 3;', context: QueryGenerator } ], insertQuery: [ { arguments: ['myTable', { name: 'foo' }], expectation: "INSERT INTO `myTable` (`name`) VALUES ('foo');" }, { arguments: ['myTable', { name: "'bar'" }], expectation: "INSERT INTO `myTable` (`name`) VALUES ('''bar''');" }, { arguments: ['myTable', {data: new Buffer('Sequelize') }], expectation: "INSERT INTO `myTable` (`data`) VALUES (X'53657175656c697a65');" }, { arguments: ['myTable', { name: 'bar', value: null }], expectation: "INSERT INTO `myTable` (`name`,`value`) VALUES ('bar',NULL);" }, { arguments: ['myTable', { name: 'bar', value: undefined }], expectation: "INSERT INTO `myTable` (`name`,`value`) VALUES ('bar',NULL);" }, { arguments: ['myTable', {name: 'foo', birthday: moment('2011-03-27 10:01:55 +0000', 'YYYY-MM-DD HH:mm:ss Z').toDate()}], expectation: "INSERT INTO `myTable` (`name`,`birthday`) VALUES ('foo','2011-03-27 10:01:55.000 +00:00');" }, { arguments: ['myTable', { name: 'foo', value: true }], expectation: "INSERT INTO `myTable` (`name`,`value`) VALUES ('foo',1);" }, { arguments: ['myTable', { name: 'foo', value: false }], expectation: "INSERT INTO `myTable` (`name`,`value`) VALUES ('foo',0);" }, { arguments: ['myTable', {name: 'foo', foo: 1, nullValue: null}], expectation: "INSERT INTO `myTable` (`name`,`foo`,`nullValue`) VALUES ('foo',1,NULL);" }, { arguments: ['myTable', {name: 'foo', foo: 1, nullValue: null}], expectation: "INSERT INTO `myTable` (`name`,`foo`,`nullValue`) VALUES ('foo',1,NULL);", context: {options: {omitNull: false}} }, { arguments: ['myTable', {name: 'foo', foo: 1, nullValue: null}], expectation: "INSERT INTO `myTable` (`name`,`foo`) VALUES ('foo',1);", context: {options: {omitNull: true}} }, { arguments: ['myTable', {name: 'foo', foo: 1, nullValue: undefined}], expectation: "INSERT INTO `myTable` (`name`,`foo`) VALUES ('foo',1);", context: {options: {omitNull: true}} }, { arguments: ['myTable', function(sequelize) { return { foo: sequelize.fn('NOW') }; }], expectation: 'INSERT INTO `myTable` (`foo`) VALUES (NOW());', needsSequelize: true } ], bulkInsertQuery: [ { arguments: ['myTable', [{name: 'foo'}, {name: 'bar'}]], expectation: "INSERT INTO `myTable` (`name`) VALUES ('foo'),('bar');" }, { arguments: ['myTable', [{name: "'bar'"}, {name: 'foo'}]], expectation: "INSERT INTO `myTable` (`name`) VALUES ('''bar'''),('foo');" }, { arguments: ['myTable', [{name: 'foo', birthday: moment('2011-03-27 10:01:55 +0000', 'YYYY-MM-DD HH:mm:ss Z').toDate()}, {name: 'bar', birthday: moment('2012-03-27 10:01:55 +0000', 'YYYY-MM-DD HH:mm:ss Z').toDate()}]], expectation: "INSERT INTO `myTable` (`name`,`birthday`) VALUES ('foo','2011-03-27 10:01:55.000 +00:00'),('bar','2012-03-27 10:01:55.000 +00:00');" }, { arguments: ['myTable', [{name: 'bar', value: null}, {name: 'foo', value: 1}]], expectation: "INSERT INTO `myTable` (`name`,`value`) VALUES ('bar',NULL),('foo',1);" }, { arguments: ['myTable', [{name: 'bar', value: undefined}, {name: 'bar', value: 2}]], expectation: "INSERT INTO `myTable` (`name`,`value`) VALUES ('bar',NULL),('bar',2);" }, { arguments: ['myTable', [{name: 'foo', value: true}, {name: 'bar', value: false}]], expectation: "INSERT INTO `myTable` (`name`,`value`) VALUES ('foo',1),('bar',0);" }, { arguments: ['myTable', [{name: 'foo', value: false}, {name: 'bar', value: false}]], expectation: "INSERT INTO `myTable` (`name`,`value`) VALUES ('foo',0),('bar',0);" }, { arguments: ['myTable', [{name: 'foo', foo: 1, nullValue: null}, {name: 'bar', foo: 2, nullValue: null}]], expectation: "INSERT INTO `myTable` (`name`,`foo`,`nullValue`) VALUES ('foo',1,NULL),('bar',2,NULL);" }, { arguments: ['myTable', [{name: 'foo', foo: 1, nullValue: null}, {name: 'bar', foo: 2, nullValue: null}]], expectation: "INSERT INTO `myTable` (`name`,`foo`,`nullValue`) VALUES ('foo',1,NULL),('bar',2,NULL);", context: {options: {omitNull: false}} }, { arguments: ['myTable', [{name: 'foo', foo: 1, nullValue: null}, {name: 'bar', foo: 2, nullValue: null}]], expectation: "INSERT INTO `myTable` (`name`,`foo`,`nullValue`) VALUES ('foo',1,NULL),('bar',2,NULL);", context: {options: {omitNull: true}} // Note: We don't honour this because it makes little sense when some rows may have nulls and others not }, { arguments: ['myTable', [{name: 'foo', foo: 1, nullValue: null}, {name: 'bar', foo: 2, nullValue: null}]], expectation: "INSERT INTO `myTable` (`name`,`foo`,`nullValue`) VALUES ('foo',1,NULL),('bar',2,NULL);", context: {options: {omitNull: true}} // Note: As above }, { arguments: ['myTable', [{name: 'foo'}, {name: 'bar'}], {ignoreDuplicates: true}], expectation: "INSERT OR IGNORE INTO `myTable` (`name`) VALUES ('foo'),('bar');" } ], updateQuery: [ { arguments: ['myTable', {name: 'foo', birthday: moment('2011-03-27 10:01:55 +0000', 'YYYY-MM-DD HH:mm:ss Z').toDate()}, {id: 2}], expectation: "UPDATE `myTable` SET `name`='foo',`birthday`='2011-03-27 10:01:55.000 +00:00' WHERE `id` = 2" }, { arguments: ['myTable', {name: 'foo', birthday: moment('2011-03-27 10:01:55 +0000', 'YYYY-MM-DD HH:mm:ss Z').toDate()}, {id: 2}], expectation: "UPDATE `myTable` SET `name`='foo',`birthday`='2011-03-27 10:01:55.000 +00:00' WHERE `id` = 2" }, { arguments: ['myTable', { name: 'foo' }, { id: 2 }], expectation: "UPDATE `myTable` SET `name`='foo' WHERE `id` = 2" }, { arguments: ['myTable', { name: "'bar'" }, { id: 2 }], expectation: "UPDATE `myTable` SET `name`='''bar''' WHERE `id` = 2" }, { arguments: ['myTable', { name: 'bar', value: null }, { id: 2 }], expectation: "UPDATE `myTable` SET `name`='bar',`value`=NULL WHERE `id` = 2" }, { arguments: ['myTable', { name: 'bar', value: undefined }, { id: 2 }], expectation: "UPDATE `myTable` SET `name`='bar',`value`=NULL WHERE `id` = 2" }, { arguments: ['myTable', { flag: true }, { id: 2 }], expectation: 'UPDATE `myTable` SET `flag`=1 WHERE `id` = 2' }, { arguments: ['myTable', { flag: false }, { id: 2 }], expectation: 'UPDATE `myTable` SET `flag`=0 WHERE `id` = 2' }, { arguments: ['myTable', {bar: 2, nullValue: null}, {name: 'foo'}], expectation: "UPDATE `myTable` SET `bar`=2,`nullValue`=NULL WHERE `name` = 'foo'" }, { arguments: ['myTable', {bar: 2, nullValue: null}, {name: 'foo'}], expectation: "UPDATE `myTable` SET `bar`=2,`nullValue`=NULL WHERE `name` = 'foo'", context: {options: {omitNull: false}} }, { arguments: ['myTable', {bar: 2, nullValue: null}, {name: 'foo'}], expectation: "UPDATE `myTable` SET `bar`=2 WHERE `name` = 'foo'", context: {options: {omitNull: true}} }, { arguments: ['myTable', function(sequelize) { return { bar: sequelize.fn('NOW') }; }, {name: 'foo'}], expectation: "UPDATE `myTable` SET `bar`=NOW() WHERE `name` = 'foo'", needsSequelize: true }, { arguments: ['myTable', function(sequelize) { return { bar: sequelize.col('foo') }; }, {name: 'foo'}], expectation: "UPDATE `myTable` SET `bar`=`foo` WHERE `name` = 'foo'", needsSequelize: true } ], renameColumnQuery: [ { title: 'Properly quotes column names', arguments: ['myTable', 'foo', 'commit', {commit: 'VARCHAR(255)', bar: 'VARCHAR(255)'}], expectation: 'CREATE TEMPORARY TABLE IF NOT EXISTS `myTable_backup` (`commit` VARCHAR(255), `bar` VARCHAR(255));' + 'INSERT INTO `myTable_backup` SELECT `foo` AS `commit`, `bar` FROM `myTable`;' + 'DROP TABLE `myTable`;' + 'CREATE TABLE IF NOT EXISTS `myTable` (`commit` VARCHAR(255), `bar` VARCHAR(255));' + 'INSERT INTO `myTable` SELECT `commit`, `bar` FROM `myTable_backup`;' + 'DROP TABLE `myTable_backup`;' } ], removeColumnQuery: [ { title: 'Properly quotes column names', arguments: ['myTable', {commit: 'VARCHAR(255)', bar: 'VARCHAR(255)'}], expectation: 'CREATE TEMPORARY TABLE IF NOT EXISTS `myTable_backup` (`commit` VARCHAR(255), `bar` VARCHAR(255));' + 'INSERT INTO `myTable_backup` SELECT `commit`, `bar` FROM `myTable`;' + 'DROP TABLE `myTable`;' + 'CREATE TABLE IF NOT EXISTS `myTable` (`commit` VARCHAR(255), `bar` VARCHAR(255));' + 'INSERT INTO `myTable` SELECT `commit`, `bar` FROM `myTable_backup`;' + 'DROP TABLE `myTable_backup`;' } ] }; _.each(suites, (tests, suiteTitle) => { describe(suiteTitle, () => { tests.forEach(test => { const title = test.title || 'SQLite correctly returns ' + test.expectation + ' for ' + JSON.stringify(test.arguments); it(title, function() { // Options would normally be set by the query interface that instantiates the query-generator, but here we specify it explicitly const context = test.context || {options: {}}; if (test.needsSequelize) { if (_.isFunction(test.arguments[1])) test.arguments[1] = test.arguments[1](this.sequelize); if (_.isFunction(test.arguments[2])) test.arguments[2] = test.arguments[2](this.sequelize); } QueryGenerator.options = _.assign(context.options, { timezone: '+00:00' }); QueryGenerator._dialect = this.sequelize.dialect; QueryGenerator.sequelize = this.sequelize; const conditions = QueryGenerator[suiteTitle].apply(QueryGenerator, test.arguments); expect(conditions).to.deep.equal(test.expectation); }); }); }); }); }); }
p0vidl0/sequelize
test/unit/dialects/sqlite/query-generator.test.js
JavaScript
mit
26,755
[ 30522, 1005, 2224, 9384, 1005, 1025, 9530, 3367, 15775, 2072, 1027, 5478, 1006, 1005, 15775, 2072, 1005, 1007, 1010, 30524, 1013, 1012, 1012, 1013, 1012, 1012, 1013, 1012, 1012, 1013, 5622, 2497, 1013, 2951, 1011, 4127, 1005, 1007, 1010, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* * Fast Userspace Mutexes (which I call "Futexes!"). * (C) Rusty Russell, IBM 2002 * * Generalized futexes, futex requeueing, misc fixes by Ingo Molnar * (C) Copyright 2003 Red Hat Inc, All Rights Reserved * * Removed page pinning, fix privately mapped COW pages and other cleanups * (C) Copyright 2003, 2004 Jamie Lokier * * Robust futex support started by Ingo Molnar * (C) Copyright 2006 Red Hat Inc, All Rights Reserved * Thanks to Thomas Gleixner for suggestions, analysis and fixes. * * PI-futex support started by Ingo Molnar and Thomas Gleixner * Copyright (C) 2006 Red Hat, Inc., Ingo Molnar <mingo@redhat.com> * Copyright (C) 2006 Timesys Corp., Thomas Gleixner <tglx@timesys.com> * * PRIVATE futexes by Eric Dumazet * Copyright (C) 2007 Eric Dumazet <dada1@cosmosbay.com> * * Requeue-PI support by Darren Hart <dvhltc@us.ibm.com> * Copyright (C) IBM Corporation, 2009 * Thanks to Thomas Gleixner for conceptual design and careful reviews. * * Thanks to Ben LaHaise for yelling "hashed waitqueues" loudly * enough at me, Linus for the original (flawed) idea, Matthew * Kirkwood for proof-of-concept implementation. * * "The futexes are also cursed." * "But they come in a choice of three flavours!" * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <linux/slab.h> #include <linux/poll.h> #include <linux/fs.h> #include <linux/file.h> #include <linux/jhash.h> #include <linux/init.h> #include <linux/futex.h> #include <linux/mount.h> #include <linux/pagemap.h> #include <linux/syscalls.h> #include <linux/signal.h> #include <linux/export.h> #include <linux/magic.h> #include <linux/pid.h> #include <linux/nsproxy.h> #include <linux/ptrace.h> #include <linux/sched/rt.h> #include <linux/freezer.h> #include <linux/hugetlb.h> #include <asm/futex.h> #include "rtmutex_common.h" #ifndef CONFIG_HAVE_FUTEX_CMPXCHG int __read_mostly futex_cmpxchg_enabled; #endif #define FUTEX_HASHBITS (CONFIG_BASE_SMALL ? 4 : 8) /* * Futex flags used to encode options to functions and preserve them across * restarts. */ #define FLAGS_SHARED 0x01 #define FLAGS_CLOCKRT 0x02 #define FLAGS_HAS_TIMEOUT 0x04 /* * Priority Inheritance state: */ struct futex_pi_state { /* * list of 'owned' pi_state instances - these have to be * cleaned up in do_exit() if the task exits prematurely: */ struct list_head list; /* * The PI object: */ struct rt_mutex pi_mutex; struct task_struct *owner; atomic_t refcount; union futex_key key; }; /** * struct futex_q - The hashed futex queue entry, one per waiting task * @list: priority-sorted list of tasks waiting on this futex * @task: the task waiting on the futex * @lock_ptr: the hash bucket lock * @key: the key the futex is hashed on * @pi_state: optional priority inheritance state * @rt_waiter: rt_waiter storage for use with requeue_pi * @requeue_pi_key: the requeue_pi target futex key * @bitset: bitset for the optional bitmasked wakeup * * We use this hashed waitqueue, instead of a normal wait_queue_t, so * we can wake only the relevant ones (hashed queues may be shared). * * A futex_q has a woken state, just like tasks have TASK_RUNNING. * It is considered woken when plist_node_empty(&q->list) || q->lock_ptr == 0. * The order of wakeup is always to make the first condition true, then * the second. * * PI futexes are typically woken before they are removed from the hash list via * the rt_mutex code. See unqueue_me_pi(). */ struct futex_q { struct plist_node list; struct task_struct *task; spinlock_t *lock_ptr; union futex_key key; struct futex_pi_state *pi_state; struct rt_mutex_waiter *rt_waiter; union futex_key *requeue_pi_key; u32 bitset; }; static const struct futex_q futex_q_init = { /* list gets initialized in queue_me()*/ .key = FUTEX_KEY_INIT, .bitset = FUTEX_BITSET_MATCH_ANY }; /* * Hash buckets are shared by all the futex_keys that hash to the same * location. Each key may have multiple futex_q structures, one for each task * waiting on a futex. */ struct futex_hash_bucket { spinlock_t lock; struct plist_head chain; }; static struct futex_hash_bucket futex_queues[1<<FUTEX_HASHBITS]; /* * We hash on the keys returned from get_futex_key (see below). */ static struct futex_hash_bucket *hash_futex(union futex_key *key) { u32 hash = jhash2((u32*)&key->both.word, (sizeof(key->both.word)+sizeof(key->both.ptr))/4, key->both.offset); return &futex_queues[hash & ((1 << FUTEX_HASHBITS)-1)]; } /* * Return 1 if two futex_keys are equal, 0 otherwise. */ static inline int match_futex(union futex_key *key1, union futex_key *key2) { return (key1 && key2 && key1->both.word == key2->both.word && key1->both.ptr == key2->both.ptr && key1->both.offset == key2->both.offset); } /* * Take a reference to the resource addressed by a key. * Can be called while holding spinlocks. * */ static void get_futex_key_refs(union futex_key *key) { if (!key->both.ptr) return; switch (key->both.offset & (FUT_OFF_INODE|FUT_OFF_MMSHARED)) { case FUT_OFF_INODE: ihold(key->shared.inode); break; case FUT_OFF_MMSHARED: atomic_inc(&key->private.mm->mm_count); break; } } /* * Drop a reference to the resource addressed by a key. * The hash bucket spinlock must not be held. */ static void drop_futex_key_refs(union futex_key *key) { if (!key->both.ptr) { /* If we're here then we tried to put a key we failed to get */ WARN_ON_ONCE(1); return; } switch (key->both.offset & (FUT_OFF_INODE|FUT_OFF_MMSHARED)) { case FUT_OFF_INODE: iput(key->shared.inode); break; case FUT_OFF_MMSHARED: mmdrop(key->private.mm); break; } } /** * get_futex_key() - Get parameters which are the keys for a futex * @uaddr: virtual address of the futex * @fshared: 0 for a PROCESS_PRIVATE futex, 1 for PROCESS_SHARED * @key: address where result is stored. * @rw: mapping needs to be read/write (values: VERIFY_READ, * VERIFY_WRITE) * * Return: a negative error code or 0 * * The key words are stored in *key on success. * * For shared mappings, it's (page->index, file_inode(vma->vm_file), * offset_within_page). For private mappings, it's (uaddr, current->mm). * We can usually work out the index without swapping in the page. * * lock_page() might sleep, the caller should not hold a spinlock. */ static int get_futex_key(u32 __user *uaddr, int fshared, union futex_key *key, int rw) { unsigned long address = (unsigned long)uaddr; struct mm_struct *mm = current->mm; struct page *page, *page_head; int err, ro = 0; /* * The futex address must be "naturally" aligned. */ key->both.offset = address % PAGE_SIZE; if (unlikely((address % sizeof(u32)) != 0)) return -EINVAL; address -= key->both.offset; /* * PROCESS_PRIVATE futexes are fast. * As the mm cannot disappear under us and the 'key' only needs * virtual address, we dont even have to find the underlying vma. * Note : We do have to check 'uaddr' is a valid user address, * but access_ok() should be faster than find_vma() */ if (!fshared) { if (unlikely(!access_ok(VERIFY_WRITE, uaddr, sizeof(u32)))) return -EFAULT; key->private.mm = mm; key->private.address = address; get_futex_key_refs(key); return 0; } again: err = get_user_pages_fast(address, 1, 1, &page); /* * If write access is not required (eg. FUTEX_WAIT), try * and get read-only access. */ if (err == -EFAULT && rw == VERIFY_READ) { err = get_user_pages_fast(address, 1, 0, &page); ro = 1; } if (err < 0) return err; else err = 0; #ifdef CONFIG_TRANSPARENT_HUGEPAGE page_head = page; if (unlikely(PageTail(page))) { put_page(page); /* serialize against __split_huge_page_splitting() */ local_irq_disable(); if (likely(__get_user_pages_fast(address, 1, !ro, &page) == 1)) { page_head = compound_head(page); /* * page_head is valid pointer but we must pin * it before taking the PG_lock and/or * PG_compound_lock. The moment we re-enable * irqs __split_huge_page_splitting() can * return and the head page can be freed from * under us. We can't take the PG_lock and/or * PG_compound_lock on a page that could be * freed from under us. */ if (page != page_head) { get_page(page_head); put_page(page); } local_irq_enable(); } else { local_irq_enable(); goto again; } } #else page_head = compound_head(page); if (page != page_head) { get_page(page_head); put_page(page); } #endif lock_page(page_head); /* * If page_head->mapping is NULL, then it cannot be a PageAnon * page; but it might be the ZERO_PAGE or in the gate area or * in a special mapping (all cases which we are happy to fail); * or it may have been a good file page when get_user_pages_fast * found it, but truncated or holepunched or subjected to * invalidate_complete_page2 before we got the page lock (also * cases which we are happy to fail). And we hold a reference, * so refcount care in invalidate_complete_page's remove_mapping * prevents drop_caches from setting mapping to NULL beneath us. * * The case we do have to guard against is when memory pressure made * shmem_writepage move it from filecache to swapcache beneath us: * an unlikely race, but we do need to retry for page_head->mapping. */ if (!page_head->mapping) { int shmem_swizzled = PageSwapCache(page_head); unlock_page(page_head); put_page(page_head); if (shmem_swizzled) goto again; return -EFAULT; } /* * Private mappings are handled in a simple way. * * NOTE: When userspace waits on a MAP_SHARED mapping, even if * it's a read-only handle, it's expected that futexes attach to * the object not the particular process. */ if (PageAnon(page_head)) { /* * A RO anonymous page will never change and thus doesn't make * sense for futex operations. */ if (ro) { err = -EFAULT; goto out; } key->both.offset |= FUT_OFF_MMSHARED; /* ref taken on mm */ key->private.mm = mm; key->private.address = address; } else { key->both.offset |= FUT_OFF_INODE; /* inode-based key */ key->shared.inode = page_head->mapping->host; key->shared.pgoff = basepage_index(page); } get_futex_key_refs(key); out: unlock_page(page_head); put_page(page_head); return err; } static inline void put_futex_key(union futex_key *key) { drop_futex_key_refs(key); } /** * fault_in_user_writeable() - Fault in user address and verify RW access * @uaddr: pointer to faulting user space address * * Slow path to fixup the fault we just took in the atomic write * access to @uaddr. * * We have no generic implementation of a non-destructive write to the * user address. We know that we faulted in the atomic pagefault * disabled section so we can as well avoid the #PF overhead by * calling get_user_pages() right away. */ static int fault_in_user_writeable(u32 __user *uaddr) { struct mm_struct *mm = current->mm; int ret; down_read(&mm->mmap_sem); ret = fixup_user_fault(current, mm, (unsigned long)uaddr, FAULT_FLAG_WRITE); up_read(&mm->mmap_sem); return ret < 0 ? ret : 0; } /** * futex_top_waiter() - Return the highest priority waiter on a futex * @hb: the hash bucket the futex_q's reside in * @key: the futex key (to distinguish it from other futex futex_q's) * * Must be called with the hb lock held. */ static struct futex_q *futex_top_waiter(struct futex_hash_bucket *hb, union futex_key *key) { struct futex_q *this; plist_for_each_entry(this, &hb->chain, list) { if (match_futex(&this->key, key)) return this; } return NULL; } static int cmpxchg_futex_value_locked(u32 *curval, u32 __user *uaddr, u32 uval, u32 newval) { int ret; pagefault_disable(); ret = futex_atomic_cmpxchg_inatomic(curval, uaddr, uval, newval); pagefault_enable(); return ret; } static int get_futex_value_locked(u32 *dest, u32 __user *from) { int ret; pagefault_disable(); ret = __copy_from_user_inatomic(dest, from, sizeof(u32)); pagefault_enable(); return ret ? -EFAULT : 0; } /* * PI code: */ static int refill_pi_state_cache(void) { struct futex_pi_state *pi_state; if (likely(current->pi_state_cache)) return 0; pi_state = kzalloc(sizeof(*pi_state), GFP_KERNEL); if (!pi_state) return -ENOMEM; INIT_LIST_HEAD(&pi_state->list); /* pi_mutex gets initialized later */ pi_state->owner = NULL; atomic_set(&pi_state->refcount, 1); pi_state->key = FUTEX_KEY_INIT; current->pi_state_cache = pi_state; return 0; } static struct futex_pi_state * alloc_pi_state(void) { struct futex_pi_state *pi_state = current->pi_state_cache; WARN_ON(!pi_state); current->pi_state_cache = NULL; return pi_state; } static void free_pi_state(struct futex_pi_state *pi_state) { if (!atomic_dec_and_test(&pi_state->refcount)) return; /* * If pi_state->owner is NULL, the owner is most probably dying * and has cleaned up the pi_state already */ if (pi_state->owner) { raw_spin_lock_irq(&pi_state->owner->pi_lock); list_del_init(&pi_state->list); raw_spin_unlock_irq(&pi_state->owner->pi_lock); rt_mutex_proxy_unlock(&pi_state->pi_mutex, pi_state->owner); } if (current->pi_state_cache) kfree(pi_state); else { /* * pi_state->list is already empty. * clear pi_state->owner. * refcount is at 0 - put it back to 1. */ pi_state->owner = NULL; atomic_set(&pi_state->refcount, 1); current->pi_state_cache = pi_state; } } /* * Look up the task based on what TID userspace gave us. * We dont trust it. */ static struct task_struct * futex_find_get_task(pid_t pid) { struct task_struct *p; rcu_read_lock(); p = find_task_by_vpid(pid); if (p) get_task_struct(p); rcu_read_unlock(); return p; } /* * This task is holding PI mutexes at exit time => bad. * Kernel cleans up PI-state, but userspace is likely hosed. * (Robust-futex cleanup is separate and might save the day for userspace.) */ void exit_pi_state_list(struct task_struct *curr) { struct list_head *next, *head = &curr->pi_state_list; struct futex_pi_state *pi_state; struct futex_hash_bucket *hb; union futex_key key = FUTEX_KEY_INIT; if (!futex_cmpxchg_enabled) return; /* * We are a ZOMBIE and nobody can enqueue itself on * pi_state_list anymore, but we have to be careful * versus waiters unqueueing themselves: */ raw_spin_lock_irq(&curr->pi_lock); while (!list_empty(head)) { next = head->next; pi_state = list_entry(next, struct futex_pi_state, list); key = pi_state->key; hb = hash_futex(&key); raw_spin_unlock_irq(&curr->pi_lock); spin_lock(&hb->lock); raw_spin_lock_irq(&curr->pi_lock); /* * We dropped the pi-lock, so re-check whether this * task still owns the PI-state: */ if (head->next != next) { spin_unlock(&hb->lock); continue; } WARN_ON(pi_state->owner != curr); WARN_ON(list_empty(&pi_state->list)); list_del_init(&pi_state->list); pi_state->owner = NULL; raw_spin_unlock_irq(&curr->pi_lock); rt_mutex_unlock(&pi_state->pi_mutex); spin_unlock(&hb->lock); raw_spin_lock_irq(&curr->pi_lock); } raw_spin_unlock_irq(&curr->pi_lock); } /* * We need to check the following states: * * Waiter | pi_state | pi->owner | uTID | uODIED | ? * * [1] NULL | --- | --- | 0 | 0/1 | Valid * [2] NULL | --- | --- | >0 | 0/1 | Valid * * [3] Found | NULL | -- | Any | 0/1 | Invalid * * [4] Found | Found | NULL | 0 | 1 | Valid * [5] Found | Found | NULL | >0 | 1 | Invalid * * [6] Found | Found | task | 0 | 1 | Valid * * [7] Found | Found | NULL | Any | 0 | Invalid * * [8] Found | Found | task | ==taskTID | 0/1 | Valid * [9] Found | Found | task | 0 | 0 | Invalid * [10] Found | Found | task | !=taskTID | 0/1 | Invalid * * [1] Indicates that the kernel can acquire the futex atomically. We * came came here due to a stale FUTEX_WAITERS/FUTEX_OWNER_DIED bit. * * [2] Valid, if TID does not belong to a kernel thread. If no matching * thread is found then it indicates that the owner TID has died. * * [3] Invalid. The waiter is queued on a non PI futex * * [4] Valid state after exit_robust_list(), which sets the user space * value to FUTEX_WAITERS | FUTEX_OWNER_DIED. * * [5] The user space value got manipulated between exit_robust_list() * and exit_pi_state_list() * * [6] Valid state after exit_pi_state_list() which sets the new owner in * the pi_state but cannot access the user space value. * * [7] pi_state->owner can only be NULL when the OWNER_DIED bit is set. * * [8] Owner and user space value match * * [9] There is no transient state which sets the user space TID to 0 * except exit_robust_list(), but this is indicated by the * FUTEX_OWNER_DIED bit. See [4] * * [10] There is no transient state which leaves owner and user space * TID out of sync. */ static int lookup_pi_state(u32 uval, struct futex_hash_bucket *hb, union futex_key *key, struct futex_pi_state **ps) { struct futex_pi_state *pi_state = NULL; struct futex_q *this, *next; struct plist_head *head; struct task_struct *p; pid_t pid = uval & FUTEX_TID_MASK; head = &hb->chain; plist_for_each_entry_safe(this, next, head, list) { if (match_futex(&this->key, key)) { /* * Sanity check the waiter before increasing * the refcount and attaching to it. */ pi_state = this->pi_state; /* * Userspace might have messed up non-PI and * PI futexes [3] */ if (unlikely(!pi_state)) return -EINVAL; WARN_ON(!atomic_read(&pi_state->refcount)); /* * Handle the owner died case: */ if (uval & FUTEX_OWNER_DIED) { /* * exit_pi_state_list sets owner to NULL and * wakes the topmost waiter. The task which * acquires the pi_state->rt_mutex will fixup * owner. */ if (!pi_state->owner) { /* * No pi state owner, but the user * space TID is not 0. Inconsistent * state. [5] */ if (pid) return -EINVAL; /* * Take a ref on the state and * return. [4] */ goto out_state; } /* * If TID is 0, then either the dying owner * has not yet executed exit_pi_state_list() * or some waiter acquired the rtmutex in the * pi state, but did not yet fixup the TID in * user space. * * Take a ref on the state and return. [6] */ if (!pid) goto out_state; } else { /* * If the owner died bit is not set, * then the pi_state must have an * owner. [7] */ if (!pi_state->owner) return -EINVAL; } /* * Bail out if user space manipulated the * futex value. If pi state exists then the * owner TID must be the same as the user * space TID. [9/10] */ if (pid != task_pid_vnr(pi_state->owner)) return -EINVAL; out_state: atomic_inc(&pi_state->refcount); *ps = pi_state; return 0; } } /* * We are the first waiter - try to look up the real owner and attach * the new pi_state to it, but bail out when TID = 0 [1] */ if (!pid) return -ESRCH; p = futex_find_get_task(pid); if (!p) return -ESRCH; if (!p->mm) { put_task_struct(p); return -EPERM; } /* * We need to look at the task state flags to figure out, * whether the task is exiting. To protect against the do_exit * change of the task flags, we do this protected by * p->pi_lock: */ raw_spin_lock_irq(&p->pi_lock); if (unlikely(p->flags & PF_EXITING)) { /* * The task is on the way out. When PF_EXITPIDONE is * set, we know that the task has finished the * cleanup: */ int ret = (p->flags & PF_EXITPIDONE) ? -ESRCH : -EAGAIN; raw_spin_unlock_irq(&p->pi_lock); put_task_struct(p); return ret; } /* * No existing pi state. First waiter. [2] */ pi_state = alloc_pi_state(); /* * Initialize the pi_mutex in locked state and make 'p' * the owner of it: */ rt_mutex_init_proxy_locked(&pi_state->pi_mutex, p); /* Store the key for possible exit cleanups: */ pi_state->key = *key; WARN_ON(!list_empty(&pi_state->list)); list_add(&pi_state->list, &p->pi_state_list); pi_state->owner = p; raw_spin_unlock_irq(&p->pi_lock); put_task_struct(p); *ps = pi_state; return 0; } /** * futex_lock_pi_atomic() - Atomic work required to acquire a pi aware futex * @uaddr: the pi futex user address * @hb: the pi futex hash bucket * @key: the futex key associated with uaddr and hb * @ps: the pi_state pointer where we store the result of the * lookup * @task: the task to perform the atomic lock work for. This will * be "current" except in the case of requeue pi. * @set_waiters: force setting the FUTEX_WAITERS bit (1) or not (0) * * Return: * 0 - ready to wait; * 1 - acquired the lock; * <0 - error * * The hb->lock and futex_key refs shall be held by the caller. */ static int futex_lock_pi_atomic(u32 __user *uaddr, struct futex_hash_bucket *hb, union futex_key *key, struct futex_pi_state **ps, struct task_struct *task, int set_waiters) { int lock_taken, ret, force_take = 0; u32 uval, newval, curval, vpid = task_pid_vnr(task); retry: ret = lock_taken = 0; /* * To avoid races, we attempt to take the lock here again * (by doing a 0 -> TID atomic cmpxchg), while holding all * the locks. It will most likely not succeed. */ newval = vpid; if (set_waiters) newval |= FUTEX_WAITERS; if (unlikely(cmpxchg_futex_value_locked(&curval, uaddr, 0, newval))) return -EFAULT; /* * Detect deadlocks. */ if ((unlikely((curval & FUTEX_TID_MASK) == vpid))) return -EDEADLK; /* * Surprise - we got the lock, but we do not trust user space at all. */ if (unlikely(!curval)) { /* * We verify whether there is kernel state for this * futex. If not, we can safely assume, that the 0 -> * TID transition is correct. If state exists, we do * not bother to fixup the user space state as it was * corrupted already. */ return futex_top_waiter(hb, key) ? -EINVAL : 1; } uval = curval; /* * Set the FUTEX_WAITERS flag, so the owner will know it has someone * to wake at the next unlock. */ newval = curval | FUTEX_WAITERS; /* * Should we force take the futex? See below. */ if (unlikely(force_take)) { /* * Keep the OWNER_DIED and the WAITERS bit and set the * new TID value. */ newval = (curval & ~FUTEX_TID_MASK) | vpid; force_take = 0; lock_taken = 1; } if (unlikely(cmpxchg_futex_value_locked(&curval, uaddr, uval, newval))) return -EFAULT; if (unlikely(curval != uval)) goto retry; /* * We took the lock due to forced take over. */ if (unlikely(lock_taken)) return 1; /* * We dont have the lock. Look up the PI state (or create it if * we are the first waiter): */ ret = lookup_pi_state(uval, hb, key, ps); if (unlikely(ret)) { switch (ret) { case -ESRCH: /* * We failed to find an owner for this * futex. So we have no pi_state to block * on. This can happen in two cases: * * 1) The owner died * 2) A stale FUTEX_WAITERS bit * * Re-read the futex value. */ if (get_futex_value_locked(&curval, uaddr)) return -EFAULT; /* * If the owner died or we have a stale * WAITERS bit the owner TID in the user space * futex is 0. */ if (!(curval & FUTEX_TID_MASK)) { force_take = 1; goto retry; } default: break; } } return ret; } /** * __unqueue_futex() - Remove the futex_q from its futex_hash_bucket * @q: The futex_q to unqueue * * The q->lock_ptr must not be NULL and must be held by the caller. */ static void __unqueue_futex(struct futex_q *q) { struct futex_hash_bucket *hb; if (WARN_ON_SMP(!q->lock_ptr || !spin_is_locked(q->lock_ptr)) || WARN_ON(plist_node_empty(&q->list))) return; hb = container_of(q->lock_ptr, struct futex_hash_bucket, lock); plist_del(&q->list, &hb->chain); } /* * The hash bucket lock must be held when this is called. * Afterwards, the futex_q must not be accessed. */ static void wake_futex(struct futex_q *q) { struct task_struct *p = q->task; if (WARN(q->pi_state || q->rt_waiter, "refusing to wake PI futex\n")) return; /* * We set q->lock_ptr = NULL _before_ we wake up the task. If * a non-futex wake up happens on another CPU then the task * might exit and p would dereference a non-existing task * struct. Prevent this by holding a reference on p across the * wake up. */ get_task_struct(p); __unqueue_futex(q); /* * The waiting task can free the futex_q as soon as * q->lock_ptr = NULL is written, without taking any locks. A * memory barrier is required here to prevent the following * store to lock_ptr from getting ahead of the plist_del. */ smp_wmb(); q->lock_ptr = NULL; wake_up_state(p, TASK_NORMAL); put_task_struct(p); } static int wake_futex_pi(u32 __user *uaddr, u32 uval, struct futex_q *this) { struct task_struct *new_owner; struct futex_pi_state *pi_state = this->pi_state; u32 uninitialized_var(curval), newval; int ret = 0; if (!pi_state) return -EINVAL; /* * If current does not own the pi_state then the futex is * inconsistent and user space fiddled with the futex value. */ if (pi_state->owner != current) return -EINVAL; raw_spin_lock(&pi_state->pi_mutex.wait_lock); new_owner = rt_mutex_next_owner(&pi_state->pi_mutex); /* * It is possible that the next waiter (the one that brought * this owner to the kernel) timed out and is no longer * waiting on the lock. */ if (!new_owner) new_owner = this->task; /* * We pass it to the next owner. The WAITERS bit is always * kept enabled while there is PI state around. We cleanup the * owner died bit, because we are the owner. */ newval = FUTEX_WAITERS | task_pid_vnr(new_owner); if (cmpxchg_futex_value_locked(&curval, uaddr, uval, newval)) ret = -EFAULT; else if (curval != uval) ret = -EINVAL; if (ret) { raw_spin_unlock(&pi_state->pi_mutex.wait_lock); return ret; } raw_spin_lock_irq(&pi_state->owner->pi_lock); WARN_ON(list_empty(&pi_state->list)); list_del_init(&pi_state->list); raw_spin_unlock_irq(&pi_state->owner->pi_lock); raw_spin_lock_irq(&new_owner->pi_lock); WARN_ON(!list_empty(&pi_state->list)); list_add(&pi_state->list, &new_owner->pi_state_list); pi_state->owner = new_owner; raw_spin_unlock_irq(&new_owner->pi_lock); raw_spin_unlock(&pi_state->pi_mutex.wait_lock); rt_mutex_unlock(&pi_state->pi_mutex); return 0; } static int unlock_futex_pi(u32 __user *uaddr, u32 uval) { u32 uninitialized_var(oldval); /* * There is no waiter, so we unlock the futex. The owner died * bit has not to be preserved here. We are the owner: */ if (cmpxchg_futex_value_locked(&oldval, uaddr, uval, 0)) return -EFAULT; if (oldval != uval) return -EAGAIN; return 0; } /* * Express the locking dependencies for lockdep: */ static inline void double_lock_hb(struct futex_hash_bucket *hb1, struct futex_hash_bucket *hb2) { if (hb1 <= hb2) { spin_lock(&hb1->lock); if (hb1 < hb2) spin_lock_nested(&hb2->lock, SINGLE_DEPTH_NESTING); } else { /* hb1 > hb2 */ spin_lock(&hb2->lock); spin_lock_nested(&hb1->lock, SINGLE_DEPTH_NESTING); } } static inline void double_unlock_hb(struct futex_hash_bucket *hb1, struct futex_hash_bucket *hb2) { spin_unlock(&hb1->lock); if (hb1 != hb2) spin_unlock(&hb2->lock); } /* * Wake up waiters matching bitset queued on this futex (uaddr). */ static int futex_wake(u32 __user *uaddr, unsigned int flags, int nr_wake, u32 bitset) { struct futex_hash_bucket *hb; struct futex_q *this, *next; struct plist_head *head; union futex_key key = FUTEX_KEY_INIT; int ret; if (!bitset) return -EINVAL; ret = get_futex_key(uaddr, flags & FLAGS_SHARED, &key, VERIFY_READ); if (unlikely(ret != 0)) goto out; hb = hash_futex(&key); spin_lock(&hb->lock); head = &hb->chain; plist_for_each_entry_safe(this, next, head, list) { if (match_futex (&this->key, &key)) { if (this->pi_state || this->rt_waiter) { ret = -EINVAL; break; } /* Check if one of the bits is set in both bitsets */ if (!(this->bitset & bitset)) continue; wake_futex(this); if (++ret >= nr_wake) break; } } spin_unlock(&hb->lock); put_futex_key(&key); out: return ret; } /* * Wake up all waiters hashed on the physical page that is mapped * to this virtual address: */ static int futex_wake_op(u32 __user *uaddr1, unsigned int flags, u32 __user *uaddr2, int nr_wake, int nr_wake2, int op) { union futex_key key1 = FUTEX_KEY_INIT, key2 = FUTEX_KEY_INIT; struct futex_hash_bucket *hb1, *hb2; struct plist_head *head; struct futex_q *this, *next; int ret, op_ret; retry: ret = get_futex_key(uaddr1, flags & FLAGS_SHARED, &key1, VERIFY_READ); if (unlikely(ret != 0)) goto out; ret = get_futex_key(uaddr2, flags & FLAGS_SHARED, &key2, VERIFY_WRITE); if (unlikely(ret != 0)) goto out_put_key1; hb1 = hash_futex(&key1); hb2 = hash_futex(&key2); retry_private: double_lock_hb(hb1, hb2); op_ret = futex_atomic_op_inuser(op, uaddr2); if (unlikely(op_ret < 0)) { double_unlock_hb(hb1, hb2); #ifndef CONFIG_MMU /* * we don't get EFAULT from MMU faults if we don't have an MMU, * but we might get them from range checking */ ret = op_ret; goto out_put_keys; #endif if (unlikely(op_ret != -EFAULT)) { ret = op_ret; goto out_put_keys; } ret = fault_in_user_writeable(uaddr2); if (ret) goto out_put_keys; if (!(flags & FLAGS_SHARED)) goto retry_private; put_futex_key(&key2); put_futex_key(&key1); goto retry; } head = &hb1->chain; plist_for_each_entry_safe(this, next, head, list) { if (match_futex (&this->key, &key1)) { if (this->pi_state || this->rt_waiter) { ret = -EINVAL; goto out_unlock; } wake_futex(this); if (++ret >= nr_wake) break; } } if (op_ret > 0) { head = &hb2->chain; op_ret = 0; plist_for_each_entry_safe(this, next, head, list) { if (match_futex (&this->key, &key2)) { if (this->pi_state || this->rt_waiter) { ret = -EINVAL; goto out_unlock; } wake_futex(this); if (++op_ret >= nr_wake2) break; } } ret += op_ret; } out_unlock: double_unlock_hb(hb1, hb2); out_put_keys: put_futex_key(&key2); out_put_key1: put_futex_key(&key1); out: return ret; } /** * requeue_futex() - Requeue a futex_q from one hb to another * @q: the futex_q to requeue * @hb1: the source hash_bucket * @hb2: the target hash_bucket * @key2: the new key for the requeued futex_q */ static inline void requeue_futex(struct futex_q *q, struct futex_hash_bucket *hb1, struct futex_hash_bucket *hb2, union futex_key *key2) { /* * If key1 and key2 hash to the same bucket, no need to * requeue. */ if (likely(&hb1->chain != &hb2->chain)) { plist_del(&q->list, &hb1->chain); plist_add(&q->list, &hb2->chain); q->lock_ptr = &hb2->lock; } get_futex_key_refs(key2); q->key = *key2; } /** * requeue_pi_wake_futex() - Wake a task that acquired the lock during requeue * @q: the futex_q * @key: the key of the requeue target futex * @hb: the hash_bucket of the requeue target futex * * During futex_requeue, with requeue_pi=1, it is possible to acquire the * target futex if it is uncontended or via a lock steal. Set the futex_q key * to the requeue target futex so the waiter can detect the wakeup on the right * futex, but remove it from the hb and NULL the rt_waiter so it can detect * atomic lock acquisition. Set the q->lock_ptr to the requeue target hb->lock * to protect access to the pi_state to fixup the owner later. Must be called * with both q->lock_ptr and hb->lock held. */ static inline void requeue_pi_wake_futex(struct futex_q *q, union futex_key *key, struct futex_hash_bucket *hb) { get_futex_key_refs(key); q->key = *key; __unqueue_futex(q); WARN_ON(!q->rt_waiter); q->rt_waiter = NULL; q->lock_ptr = &hb->lock; wake_up_state(q->task, TASK_NORMAL); } /** * futex_proxy_trylock_atomic() - Attempt an atomic lock for the top waiter * @pifutex: the user address of the to futex * @hb1: the from futex hash bucket, must be locked by the caller * @hb2: the to futex hash bucket, must be locked by the caller * @key1: the from futex key * @key2: the to futex key * @ps: address to store the pi_state pointer * @set_waiters: force setting the FUTEX_WAITERS bit (1) or not (0) * * Try and get the lock on behalf of the top waiter if we can do it atomically. * Wake the top waiter if we succeed. If the caller specified set_waiters, * then direct futex_lock_pi_atomic() to force setting the FUTEX_WAITERS bit. * hb1 and hb2 must be held by the caller. * * Return: * 0 - failed to acquire the lock atomically; * >0 - acquired the lock, return value is vpid of the top_waiter * <0 - error */ static int futex_proxy_trylock_atomic(u32 __user *pifutex, struct futex_hash_bucket *hb1, struct futex_hash_bucket *hb2, union futex_key *key1, union futex_key *key2, struct futex_pi_state **ps, int set_waiters) { struct futex_q *top_waiter = NULL; u32 curval; int ret, vpid; if (get_futex_value_locked(&curval, pifutex)) return -EFAULT; /* * Find the top_waiter and determine if there are additional waiters. * If the caller intends to requeue more than 1 waiter to pifutex, * force futex_lock_pi_atomic() to set the FUTEX_WAITERS bit now, * as we have means to handle the possible fault. If not, don't set * the bit unecessarily as it will force the subsequent unlock to enter * the kernel. */ top_waiter = futex_top_waiter(hb1, key1); /* There are no waiters, nothing for us to do. */ if (!top_waiter) return 0; /* Ensure we requeue to the expected futex. */ if (!match_futex(top_waiter->requeue_pi_key, key2)) return -EINVAL; /* * Try to take the lock for top_waiter. Set the FUTEX_WAITERS bit in * the contended case or if set_waiters is 1. The pi_state is returned * in ps in contended cases. */ vpid = task_pid_vnr(top_waiter->task); ret = futex_lock_pi_atomic(pifutex, hb2, key2, ps, top_waiter->task, set_waiters); if (ret == 1) { requeue_pi_wake_futex(top_waiter, key2, hb2); return vpid; } return ret; } /** * futex_requeue() - Requeue waiters from uaddr1 to uaddr2 * @uaddr1: source futex user address * @flags: futex flags (FLAGS_SHARED, etc.) * @uaddr2: target futex user address * @nr_wake: number of waiters to wake (must be 1 for requeue_pi) * @nr_requeue: number of waiters to requeue (0-INT_MAX) * @cmpval: @uaddr1 expected value (or %NULL) * @requeue_pi: if we are attempting to requeue from a non-pi futex to a * pi futex (pi to pi requeue is not supported) * * Requeue waiters on uaddr1 to uaddr2. In the requeue_pi case, try to acquire * uaddr2 atomically on behalf of the top waiter. * * Return: * >=0 - on success, the number of tasks requeued or woken; * <0 - on error */ static int futex_requeue(u32 __user *uaddr1, unsigned int flags, u32 __user *uaddr2, int nr_wake, int nr_requeue, u32 *cmpval, int requeue_pi) { union futex_key key1 = FUTEX_KEY_INIT, key2 = FUTEX_KEY_INIT; int drop_count = 0, task_count = 0, ret; struct futex_pi_state *pi_state = NULL; struct futex_hash_bucket *hb1, *hb2; struct plist_head *head1; struct futex_q *this, *next; u32 curval2; if (requeue_pi) { /* * Requeue PI only works on two distinct uaddrs. This * check is only valid for private futexes. See below. */ if (uaddr1 == uaddr2) return -EINVAL; /* * requeue_pi requires a pi_state, try to allocate it now * without any locks in case it fails. */ if (refill_pi_state_cache()) return -ENOMEM; /* * requeue_pi must wake as many tasks as it can, up to nr_wake * + nr_requeue, since it acquires the rt_mutex prior to * returning to userspace, so as to not leave the rt_mutex with * waiters and no owner. However, second and third wake-ups * cannot be predicted as they involve race conditions with the * first wake and a fault while looking up the pi_state. Both * pthread_cond_signal() and pthread_cond_broadcast() should * use nr_wake=1. */ if (nr_wake != 1) return -EINVAL; } retry: if (pi_state != NULL) { /* * We will have to lookup the pi_state again, so free this one * to keep the accounting correct. */ free_pi_state(pi_state); pi_state = NULL; } ret = get_futex_key(uaddr1, flags & FLAGS_SHARED, &key1, VERIFY_READ); if (unlikely(ret != 0)) goto out; ret = get_futex_key(uaddr2, flags & FLAGS_SHARED, &key2, requeue_pi ? VERIFY_WRITE : VERIFY_READ); if (unlikely(ret != 0)) goto out_put_key1; /* * The check above which compares uaddrs is not sufficient for * shared futexes. We need to compare the keys: */ if (requeue_pi && match_futex(&key1, &key2)) { ret = -EINVAL; goto out_put_keys; } /* * The check above which compares uaddrs is not sufficient for * shared futexes. We need to compare the keys: */ if (requeue_pi && match_futex(&key1, &key2)) { ret = -EINVAL; goto out_put_keys; } hb1 = hash_futex(&key1); hb2 = hash_futex(&key2); retry_private: double_lock_hb(hb1, hb2); if (likely(cmpval != NULL)) { u32 curval; ret = get_futex_value_locked(&curval, uaddr1); if (unlikely(ret)) { double_unlock_hb(hb1, hb2); ret = get_user(curval, uaddr1); if (ret) goto out_put_keys; if (!(flags & FLAGS_SHARED)) goto retry_private; put_futex_key(&key2); put_futex_key(&key1); goto retry; } if (curval != *cmpval) { ret = -EAGAIN; goto out_unlock; } } if (requeue_pi && (task_count - nr_wake < nr_requeue)) { /* * Attempt to acquire uaddr2 and wake the top waiter. If we * intend to requeue waiters, force setting the FUTEX_WAITERS * bit. We force this here where we are able to easily handle * faults rather in the requeue loop below. */ ret = futex_proxy_trylock_atomic(uaddr2, hb1, hb2, &key1, &key2, &pi_state, nr_requeue); /* * At this point the top_waiter has either taken uaddr2 or is * waiting on it. If the former, then the pi_state will not * exist yet, look it up one more time to ensure we have a * reference to it. If the lock was taken, ret contains the * vpid of the top waiter task. */ if (ret > 0) { WARN_ON(pi_state); drop_count++; task_count++; /* * If we acquired the lock, then the user * space value of uaddr2 should be vpid. It * cannot be changed by the top waiter as it * is blocked on hb2 lock if it tries to do * so. If something fiddled with it behind our * back the pi state lookup might unearth * it. So we rather use the known value than * rereading and handing potential crap to * lookup_pi_state. */ ret = lookup_pi_state(ret, hb2, &key2, &pi_state); } switch (ret) { case 0: break; case -EFAULT: double_unlock_hb(hb1, hb2); put_futex_key(&key2); put_futex_key(&key1); ret = fault_in_user_writeable(uaddr2); if (!ret) goto retry; goto out; case -EAGAIN: /* The owner was exiting, try again. */ double_unlock_hb(hb1, hb2); put_futex_key(&key2); put_futex_key(&key1); cond_resched(); goto retry; default: goto out_unlock; } } head1 = &hb1->chain; plist_for_each_entry_safe(this, next, head1, list) { if (task_count - nr_wake >= nr_requeue) break; if (!match_futex(&this->key, &key1)) continue; /* * FUTEX_WAIT_REQEUE_PI and FUTEX_CMP_REQUEUE_PI should always * be paired with each other and no other futex ops. * * We should never be requeueing a futex_q with a pi_state, * which is awaiting a futex_unlock_pi(). */ if ((requeue_pi && !this->rt_waiter) || (!requeue_pi && this->rt_waiter) || this->pi_state) { ret = -EINVAL; break; } /* * Wake nr_wake waiters. For requeue_pi, if we acquired the * lock, we already woke the top_waiter. If not, it will be * woken by futex_unlock_pi(). */ if (++task_count <= nr_wake && !requeue_pi) { wake_futex(this); continue; } /* Ensure we requeue to the expected futex for requeue_pi. */ if (requeue_pi && !match_futex(this->requeue_pi_key, &key2)) { ret = -EINVAL; break; } /* * Requeue nr_requeue waiters and possibly one more in the case * of requeue_pi if we couldn't acquire the lock atomically. */ if (requeue_pi) { /* Prepare the waiter to take the rt_mutex. */ atomic_inc(&pi_state->refcount); this->pi_state = pi_state; ret = rt_mutex_start_proxy_lock(&pi_state->pi_mutex, this->rt_waiter, this->task, 1); if (ret == 1) { /* We got the lock. */ requeue_pi_wake_futex(this, &key2, hb2); drop_count++; continue; } else if (ret) { /* -EDEADLK */ this->pi_state = NULL; free_pi_state(pi_state); goto out_unlock; } } requeue_futex(this, hb1, hb2, &key2); drop_count++; } out_unlock: double_unlock_hb(hb1, hb2); /* * drop_futex_key_refs() must be called outside the spinlocks. During * the requeue we moved futex_q's from the hash bucket at key1 to the * one at key2 and updated their key pointer. We no longer need to * hold the references to key1. */ while (--drop_count >= 0) drop_futex_key_refs(&key1); out_put_keys: put_futex_key(&key2); out_put_key1: put_futex_key(&key1); out: if (pi_state != NULL) free_pi_state(pi_state); return ret ? ret : task_count; } /* The key must be already stored in q->key. */ static inline struct futex_hash_bucket *queue_lock(struct futex_q *q) __acquires(&hb->lock) { struct futex_hash_bucket *hb; hb = hash_futex(&q->key); q->lock_ptr = &hb->lock; spin_lock(&hb->lock); return hb; } static inline void queue_unlock(struct futex_q *q, struct futex_hash_bucket *hb) __releases(&hb->lock) { spin_unlock(&hb->lock); } /** * queue_me() - Enqueue the futex_q on the futex_hash_bucket * @q: The futex_q to enqueue * @hb: The destination hash bucket * * The hb->lock must be held by the caller, and is released here. A call to * queue_me() is typically paired with exactly one call to unqueue_me(). The * exceptions involve the PI related operations, which may use unqueue_me_pi() * or nothing if the unqueue is done as part of the wake process and the unqueue * state is implicit in the state of woken task (see futex_wait_requeue_pi() for * an example). */ static inline void queue_me(struct futex_q *q, struct futex_hash_bucket *hb) __releases(&hb->lock) { int prio; /* * The priority used to register this element is * - either the real thread-priority for the real-time threads * (i.e. threads with a priority lower than MAX_RT_PRIO) * - or MAX_RT_PRIO for non-RT threads. * Thus, all RT-threads are woken first in priority order, and * the others are woken last, in FIFO order. */ prio = min(current->normal_prio, MAX_RT_PRIO); plist_node_init(&q->list, prio); plist_add(&q->list, &hb->chain); q->task = current; spin_unlock(&hb->lock); } /** * unqueue_me() - Remove the futex_q from its futex_hash_bucket * @q: The futex_q to unqueue * * The q->lock_ptr must not be held by the caller. A call to unqueue_me() must * be paired with exactly one earlier call to queue_me(). * * Return: * 1 - if the futex_q was still queued (and we removed unqueued it); * 0 - if the futex_q was already removed by the waking thread */ static int unqueue_me(struct futex_q *q) { spinlock_t *lock_ptr; int ret = 0; /* In the common case we don't take the spinlock, which is nice. */ retry: lock_ptr = q->lock_ptr; barrier(); if (lock_ptr != NULL) { spin_lock(lock_ptr); /* * q->lock_ptr can change between reading it and * spin_lock(), causing us to take the wrong lock. This * corrects the race condition. * * Reasoning goes like this: if we have the wrong lock, * q->lock_ptr must have changed (maybe several times) * between reading it and the spin_lock(). It can * change again after the spin_lock() but only if it was * already changed before the spin_lock(). It cannot, * however, change back to the original value. Therefore * we can detect whether we acquired the correct lock. */ if (unlikely(lock_ptr != q->lock_ptr)) { spin_unlock(lock_ptr); goto retry; } __unqueue_futex(q); BUG_ON(q->pi_state); spin_unlock(lock_ptr); ret = 1; } drop_futex_key_refs(&q->key); return ret; } /* * PI futexes can not be requeued and must remove themself from the * hash bucket. The hash bucket lock (i.e. lock_ptr) is held on entry * and dropped here. */ static void unqueue_me_pi(struct futex_q *q) __releases(q->lock_ptr) { __unqueue_futex(q); BUG_ON(!q->pi_state); free_pi_state(q->pi_state); q->pi_state = NULL; spin_unlock(q->lock_ptr); } /* * Fixup the pi_state owner with the new owner. * * Must be called with hash bucket lock held and mm->sem held for non * private futexes. */ static int fixup_pi_state_owner(u32 __user *uaddr, struct futex_q *q, struct task_struct *newowner) { u32 newtid = task_pid_vnr(newowner) | FUTEX_WAITERS; struct futex_pi_state *pi_state = q->pi_state; struct task_struct *oldowner = pi_state->owner; u32 uval, uninitialized_var(curval), newval; int ret; /* Owner died? */ if (!pi_state->owner) newtid |= FUTEX_OWNER_DIED; /* * We are here either because we stole the rtmutex from the * previous highest priority waiter or we are the highest priority * waiter but failed to get the rtmutex the first time. * We have to replace the newowner TID in the user space variable. * This must be atomic as we have to preserve the owner died bit here. * * Note: We write the user space value _before_ changing the pi_state * because we can fault here. Imagine swapped out pages or a fork * that marked all the anonymous memory readonly for cow. * * Modifying pi_state _before_ the user space value would * leave the pi_state in an inconsistent state when we fault * here, because we need to drop the hash bucket lock to * handle the fault. This might be observed in the PID check * in lookup_pi_state. */ retry: if (get_futex_value_locked(&uval, uaddr)) goto handle_fault; while (1) { newval = (uval & FUTEX_OWNER_DIED) | newtid; if (cmpxchg_futex_value_locked(&curval, uaddr, uval, newval)) goto handle_fault; if (curval == uval) break; uval = curval; } /* * We fixed up user space. Now we need to fix the pi_state * itself. */ if (pi_state->owner != NULL) { raw_spin_lock_irq(&pi_state->owner->pi_lock); WARN_ON(list_empty(&pi_state->list)); list_del_init(&pi_state->list); raw_spin_unlock_irq(&pi_state->owner->pi_lock); } pi_state->owner = newowner; raw_spin_lock_irq(&newowner->pi_lock); WARN_ON(!list_empty(&pi_state->list)); list_add(&pi_state->list, &newowner->pi_state_list); raw_spin_unlock_irq(&newowner->pi_lock); return 0; /* * To handle the page fault we need to drop the hash bucket * lock here. That gives the other task (either the highest priority * waiter itself or the task which stole the rtmutex) the * chance to try the fixup of the pi_state. So once we are * back from handling the fault we need to check the pi_state * after reacquiring the hash bucket lock and before trying to * do another fixup. When the fixup has been done already we * simply return. */ handle_fault: spin_unlock(q->lock_ptr); ret = fault_in_user_writeable(uaddr); spin_lock(q->lock_ptr); /* * Check if someone else fixed it for us: */ if (pi_state->owner != oldowner) return 0; if (ret) return ret; goto retry; } static long futex_wait_restart(struct restart_block *restart); /** * fixup_owner() - Post lock pi_state and corner case management * @uaddr: user address of the futex * @q: futex_q (contains pi_state and access to the rt_mutex) * @locked: if the attempt to take the rt_mutex succeeded (1) or not (0) * * After attempting to lock an rt_mutex, this function is called to cleanup * the pi_state owner as well as handle race conditions that may allow us to * acquire the lock. Must be called with the hb lock held. * * Return: * 1 - success, lock taken; * 0 - success, lock not taken; * <0 - on error (-EFAULT) */ static int fixup_owner(u32 __user *uaddr, struct futex_q *q, int locked) { struct task_struct *owner; int ret = 0; if (locked) { /* * Got the lock. We might not be the anticipated owner if we * did a lock-steal - fix up the PI-state in that case: */ if (q->pi_state->owner != current) ret = fixup_pi_state_owner(uaddr, q, current); goto out; } /* * Catch the rare case, where the lock was released when we were on the * way back before we locked the hash bucket. */ if (q->pi_state->owner == current) { /* * Try to get the rt_mutex now. This might fail as some other * task acquired the rt_mutex after we removed ourself from the * rt_mutex waiters list. */ if (rt_mutex_trylock(&q->pi_state->pi_mutex)) { locked = 1; goto out; } /* * pi_state is incorrect, some other task did a lock steal and * we returned due to timeout or signal without taking the * rt_mutex. Too late. */ raw_spin_lock(&q->pi_state->pi_mutex.wait_lock); owner = rt_mutex_owner(&q->pi_state->pi_mutex); if (!owner) owner = rt_mutex_next_owner(&q->pi_state->pi_mutex); raw_spin_unlock(&q->pi_state->pi_mutex.wait_lock); ret = fixup_pi_state_owner(uaddr, q, owner); goto out; } /* * Paranoia check. If we did not take the lock, then we should not be * the owner of the rt_mutex. */ if (rt_mutex_owner(&q->pi_state->pi_mutex) == current) printk(KERN_ERR "fixup_owner: ret = %d pi-mutex: %p " "pi-state %p\n", ret, q->pi_state->pi_mutex.owner, q->pi_state->owner); out: return ret ? ret : locked; } /** * futex_wait_queue_me() - queue_me() and wait for wakeup, timeout, or signal * @hb: the futex hash bucket, must be locked by the caller * @q: the futex_q to queue up on * @timeout: the prepared hrtimer_sleeper, or null for no timeout */ static void futex_wait_queue_me(struct futex_hash_bucket *hb, struct futex_q *q, struct hrtimer_sleeper *timeout) { /* * The task state is guaranteed to be set before another task can * wake it. set_current_state() is implemented using set_mb() and * queue_me() calls spin_unlock() upon completion, both serializing * access to the hash list and forcing another memory barrier. */ set_current_state(TASK_INTERRUPTIBLE); queue_me(q, hb); /* Arm the timer */ if (timeout) { hrtimer_start_expires(&timeout->timer, HRTIMER_MODE_ABS); if (!hrtimer_active(&timeout->timer)) timeout->task = NULL; } /* * If we have been removed from the hash list, then another task * has tried to wake us, and we can skip the call to schedule(). */ if (likely(!plist_node_empty(&q->list))) { /* * If the timer has already expired, current will already be * flagged for rescheduling. Only call schedule if there * is no timeout, or if it has yet to expire. */ if (!timeout || timeout->task) freezable_schedule(); } __set_current_state(TASK_RUNNING); } /** * futex_wait_setup() - Prepare to wait on a futex * @uaddr: the futex userspace address * @val: the expected value * @flags: futex flags (FLAGS_SHARED, etc.) * @q: the associated futex_q * @hb: storage for hash_bucket pointer to be returned to caller * * Setup the futex_q and locate the hash_bucket. Get the futex value and * compare it with the expected value. Handle atomic faults internally. * Return with the hb lock held and a q.key reference on success, and unlocked * with no q.key reference on failure. * * Return: * 0 - uaddr contains val and hb has been locked; * <1 - -EFAULT or -EWOULDBLOCK (uaddr does not contain val) and hb is unlocked */ static int futex_wait_setup(u32 __user *uaddr, u32 val, unsigned int flags, struct futex_q *q, struct futex_hash_bucket **hb) { u32 uval; int ret; /* * Access the page AFTER the hash-bucket is locked. * Order is important: * * Userspace waiter: val = var; if (cond(val)) futex_wait(&var, val); * Userspace waker: if (cond(var)) { var = new; futex_wake(&var); } * * The basic logical guarantee of a futex is that it blocks ONLY * if cond(var) is known to be true at the time of blocking, for * any cond. If we locked the hash-bucket after testing *uaddr, that * would open a race condition where we could block indefinitely with * cond(var) false, which would violate the guarantee. * * On the other hand, we insert q and release the hash-bucket only * after testing *uaddr. This guarantees that futex_wait() will NOT * absorb a wakeup if *uaddr does not match the desired values * while the syscall executes. */ retry: ret = get_futex_key(uaddr, flags & FLAGS_SHARED, &q->key, VERIFY_READ); if (unlikely(ret != 0)) return ret; retry_private: *hb = queue_lock(q); ret = get_futex_value_locked(&uval, uaddr); if (ret) { queue_unlock(q, *hb); ret = get_user(uval, uaddr); if (ret) goto out; if (!(flags & FLAGS_SHARED)) goto retry_private; put_futex_key(&q->key); goto retry; } if (uval != val) { queue_unlock(q, *hb); ret = -EWOULDBLOCK; } out: if (ret) put_futex_key(&q->key); return ret; } static int futex_wait(u32 __user *uaddr, unsigned int flags, u32 val, ktime_t *abs_time, u32 bitset) { struct hrtimer_sleeper timeout, *to = NULL; struct restart_block *restart; struct futex_hash_bucket *hb; struct futex_q q = futex_q_init; int ret; if (!bitset) return -EINVAL; q.bitset = bitset; if (abs_time) { to = &timeout; hrtimer_init_on_stack(&to->timer, (flags & FLAGS_CLOCKRT) ? CLOCK_REALTIME : CLOCK_MONOTONIC, HRTIMER_MODE_ABS); hrtimer_init_sleeper(to, current); hrtimer_set_expires_range_ns(&to->timer, *abs_time, current->timer_slack_ns); } retry: /* * Prepare to wait on uaddr. On success, holds hb lock and increments * q.key refs. */ ret = futex_wait_setup(uaddr, val, flags, &q, &hb); if (ret) goto out; /* queue_me and wait for wakeup, timeout, or a signal. */ futex_wait_queue_me(hb, &q, to); /* If we were woken (and unqueued), we succeeded, whatever. */ ret = 0; /* unqueue_me() drops q.key ref */ if (!unqueue_me(&q)) goto out; ret = -ETIMEDOUT; if (to && !to->task) goto out; /* * We expect signal_pending(current), but we might be the * victim of a spurious wakeup as well. */ if (!signal_pending(current)) goto retry; ret = -ERESTARTSYS; if (!abs_time) goto out; restart = &current_thread_info()->restart_block; restart->fn = futex_wait_restart; restart->futex.uaddr = uaddr; restart->futex.val = val; restart->futex.time = abs_time->tv64; restart->futex.bitset = bitset; restart->futex.flags = flags | FLAGS_HAS_TIMEOUT; ret = -ERESTART_RESTARTBLOCK; out: if (to) { hrtimer_cancel(&to->timer); destroy_hrtimer_on_stack(&to->timer); } return ret; } static long futex_wait_restart(struct restart_block *restart) { u32 __user *uaddr = restart->futex.uaddr; ktime_t t, *tp = NULL; if (restart->futex.flags & FLAGS_HAS_TIMEOUT) { t.tv64 = restart->futex.time; tp = &t; } restart->fn = do_no_restart_syscall; return (long)futex_wait(uaddr, restart->futex.flags, restart->futex.val, tp, restart->futex.bitset); } /* * Userspace tried a 0 -> TID atomic transition of the futex value * and failed. The kernel side here does the whole locking operation: * if there are waiters then it will block, it does PI, etc. (Due to * races the kernel might see a 0 value of the futex too.) */ static int futex_lock_pi(u32 __user *uaddr, unsigned int flags, int detect, ktime_t *time, int trylock) { struct hrtimer_sleeper timeout, *to = NULL; struct futex_hash_bucket *hb; struct futex_q q = futex_q_init; int res, ret; if (refill_pi_state_cache()) return -ENOMEM; if (time) { to = &timeout; hrtimer_init_on_stack(&to->timer, CLOCK_REALTIME, HRTIMER_MODE_ABS); hrtimer_init_sleeper(to, current); hrtimer_set_expires(&to->timer, *time); } retry: ret = get_futex_key(uaddr, flags & FLAGS_SHARED, &q.key, VERIFY_WRITE); if (unlikely(ret != 0)) goto out; retry_private: hb = queue_lock(&q); ret = futex_lock_pi_atomic(uaddr, hb, &q.key, &q.pi_state, current, 0); if (unlikely(ret)) { switch (ret) { case 1: /* We got the lock. */ ret = 0; goto out_unlock_put_key; case -EFAULT: goto uaddr_faulted; case -EAGAIN: /* * Task is exiting and we just wait for the * exit to complete. */ queue_unlock(&q, hb); put_futex_key(&q.key); cond_resched(); goto retry; default: goto out_unlock_put_key; } } /* * Only actually queue now that the atomic ops are done: */ queue_me(&q, hb); WARN_ON(!q.pi_state); /* * Block on the PI mutex: */ if (!trylock) ret = rt_mutex_timed_lock(&q.pi_state->pi_mutex, to, 1); else { ret = rt_mutex_trylock(&q.pi_state->pi_mutex); /* Fixup the trylock return value: */ ret = ret ? 0 : -EWOULDBLOCK; } spin_lock(q.lock_ptr); /* * Fixup the pi_state owner and possibly acquire the lock if we * haven't already. */ res = fixup_owner(uaddr, &q, !ret); /* * If fixup_owner() returned an error, proprogate that. If it acquired * the lock, clear our -ETIMEDOUT or -EINTR. */ if (res) ret = (res < 0) ? res : 0; /* * If fixup_owner() faulted and was unable to handle the fault, unlock * it and return the fault to userspace. */ if (ret && (rt_mutex_owner(&q.pi_state->pi_mutex) == current)) rt_mutex_unlock(&q.pi_state->pi_mutex); /* Unqueue and drop the lock */ unqueue_me_pi(&q); goto out_put_key; out_unlock_put_key: queue_unlock(&q, hb); out_put_key: put_futex_key(&q.key); out: if (to) destroy_hrtimer_on_stack(&to->timer); return ret != -EINTR ? ret : -ERESTARTNOINTR; uaddr_faulted: queue_unlock(&q, hb); ret = fault_in_user_writeable(uaddr); if (ret) goto out_put_key; if (!(flags & FLAGS_SHARED)) goto retry_private; put_futex_key(&q.key); goto retry; } /* * Userspace attempted a TID -> 0 atomic transition, and failed. * This is the in-kernel slowpath: we look up the PI state (if any), * and do the rt-mutex unlock. */ static int futex_unlock_pi(u32 __user *uaddr, unsigned int flags) { struct futex_hash_bucket *hb; struct futex_q *this, *next; struct plist_head *head; union futex_key key = FUTEX_KEY_INIT; u32 uval, vpid = task_pid_vnr(current); int ret; retry: if (get_user(uval, uaddr)) return -EFAULT; /* * We release only a lock we actually own: */ if ((uval & FUTEX_TID_MASK) != vpid) return -EPERM; ret = get_futex_key(uaddr, flags & FLAGS_SHARED, &key, VERIFY_WRITE); if (unlikely(ret != 0)) goto out; hb = hash_futex(&key); spin_lock(&hb->lock); /* * To avoid races, try to do the TID -> 0 atomic transition * again. If it succeeds then we can return without waking * anyone else up. We only try this if neither the waiters nor * the owner died bit are set. */ if (!(uval & ~FUTEX_TID_MASK) && cmpxchg_futex_value_locked(&uval, uaddr, vpid, 0)) goto pi_faulted; /* * Rare case: we managed to release the lock atomically, * no need to wake anyone else up: */ if (unlikely(uval == vpid)) goto out_unlock; /* * Ok, other tasks may need to be woken up - check waiters * and do the wakeup if necessary: */ head = &hb->chain; plist_for_each_entry_safe(this, next, head, list) { if (!match_futex (&this->key, &key)) continue; ret = wake_futex_pi(uaddr, uval, this); /* * The atomic access to the futex value * generated a pagefault, so retry the * user-access and the wakeup: */ if (ret == -EFAULT) goto pi_faulted; goto out_unlock; } /* * No waiters - kernel unlocks the futex: */ ret = unlock_futex_pi(uaddr, uval); if (ret == -EFAULT) goto pi_faulted; out_unlock: spin_unlock(&hb->lock); put_futex_key(&key); out: return ret; pi_faulted: spin_unlock(&hb->lock); put_futex_key(&key); ret = fault_in_user_writeable(uaddr); if (!ret) goto retry; return ret; } /** * handle_early_requeue_pi_wakeup() - Detect early wakeup on the initial futex * @hb: the hash_bucket futex_q was original enqueued on * @q: the futex_q woken while waiting to be requeued * @key2: the futex_key of the requeue target futex * @timeout: the timeout associated with the wait (NULL if none) * * Detect if the task was woken on the initial futex as opposed to the requeue * target futex. If so, determine if it was a timeout or a signal that caused * the wakeup and return the appropriate error code to the caller. Must be * called with the hb lock held. * * Return: * 0 = no early wakeup detected; * <0 = -ETIMEDOUT or -ERESTARTNOINTR */ static inline int handle_early_requeue_pi_wakeup(struct futex_hash_bucket *hb, struct futex_q *q, union futex_key *key2, struct hrtimer_sleeper *timeout) { int ret = 0; /* * With the hb lock held, we avoid races while we process the wakeup. * We only need to hold hb (and not hb2) to ensure atomicity as the * wakeup code can't change q.key from uaddr to uaddr2 if we hold hb. * It can't be requeued from uaddr2 to something else since we don't * support a PI aware source futex for requeue. */ if (!match_futex(&q->key, key2)) { WARN_ON(q->lock_ptr && (&hb->lock != q->lock_ptr)); /* * We were woken prior to requeue by a timeout or a signal. * Unqueue the futex_q and determine which it was. */ plist_del(&q->list, &hb->chain); /* Handle spurious wakeups gracefully */ ret = -EWOULDBLOCK; if (timeout && !timeout->task) ret = -ETIMEDOUT; else if (signal_pending(current)) ret = -ERESTARTNOINTR; } return ret; } /** * futex_wait_requeue_pi() - Wait on uaddr and take uaddr2 * @uaddr: the futex we initially wait on (non-pi) * @flags: futex flags (FLAGS_SHARED, FLAGS_CLOCKRT, etc.), they must be * the same type, no requeueing from private to shared, etc. * @val: the expected value of uaddr * @abs_time: absolute timeout * @bitset: 32 bit wakeup bitset set by userspace, defaults to all * @uaddr2: the pi futex we will take prior to returning to user-space * * The caller will wait on uaddr and will be requeued by futex_requeue() to * uaddr2 which must be PI aware and unique from uaddr. Normal wakeup will wake * on uaddr2 and complete the acquisition of the rt_mutex prior to returning to * userspace. This ensures the rt_mutex maintains an owner when it has waiters; * without one, the pi logic would not know which task to boost/deboost, if * there was a need to. * * We call schedule in futex_wait_queue_me() when we enqueue and return there * via the following-- * 1) wakeup on uaddr2 after an atomic lock acquisition by futex_requeue() * 2) wakeup on uaddr2 after a requeue * 3) signal * 4) timeout * * If 3, cleanup and return -ERESTARTNOINTR. * * If 2, we may then block on trying to take the rt_mutex and return via: * 5) successful lock * 6) signal * 7) timeout * 8) other lock acquisition failure * * If 6, return -EWOULDBLOCK (restarting the syscall would do the same). * * If 4 or 7, we cleanup and return with -ETIMEDOUT. * * Return: * 0 - On success; * <0 - On error */ static int futex_wait_requeue_pi(u32 __user *uaddr, unsigned int flags, u32 val, ktime_t *abs_time, u32 bitset, u32 __user *uaddr2) { struct hrtimer_sleeper timeout, *to = NULL; struct rt_mutex_waiter rt_waiter; struct rt_mutex *pi_mutex = NULL; struct futex_hash_bucket *hb; union futex_key key2 = FUTEX_KEY_INIT; struct futex_q q = futex_q_init; int res, ret; if (uaddr == uaddr2) return -EINVAL; if (!bitset) return -EINVAL; if (abs_time) { to = &timeout; hrtimer_init_on_stack(&to->timer, (flags & FLAGS_CLOCKRT) ? CLOCK_REALTIME : CLOCK_MONOTONIC, HRTIMER_MODE_ABS); hrtimer_init_sleeper(to, current); hrtimer_set_expires_range_ns(&to->timer, *abs_time, current->timer_slack_ns); } /* * The waiter is allocated on our stack, manipulated by the requeue * code while we sleep on uaddr. */ debug_rt_mutex_init_waiter(&rt_waiter); rt_waiter.task = NULL; ret = get_futex_key(uaddr2, flags & FLAGS_SHARED, &key2, VERIFY_WRITE); if (unlikely(ret != 0)) goto out; q.bitset = bitset; q.rt_waiter = &rt_waiter; q.requeue_pi_key = &key2; /* * Prepare to wait on uaddr. On success, increments q.key (key1) ref * count. */ ret = futex_wait_setup(uaddr, val, flags, &q, &hb); if (ret) goto out_key2; /* * The check above which compares uaddrs is not sufficient for * shared futexes. We need to compare the keys: */ if (match_futex(&q.key, &key2)) { ret = -EINVAL; goto out_put_keys; } /* * The check above which compares uaddrs is not sufficient for * shared futexes. We need to compare the keys: */ if (match_futex(&q.key, &key2)) { ret = -EINVAL; goto out_put_keys; } /* Queue the futex_q, drop the hb lock, wait for wakeup. */ futex_wait_queue_me(hb, &q, to); spin_lock(&hb->lock); ret = handle_early_requeue_pi_wakeup(hb, &q, &key2, to); spin_unlock(&hb->lock); if (ret) goto out_put_keys; /* * In order for us to be here, we know our q.key == key2, and since * we took the hb->lock above, we also know that futex_requeue() has * completed and we no longer have to concern ourselves with a wakeup * race with the atomic proxy lock acquisition by the requeue code. The * futex_requeue dropped our key1 reference and incremented our key2 * reference count. */ /* Check if the requeue code acquired the second futex for us. */ if (!q.rt_waiter) { /* * Got the lock. We might not be the anticipated owner if we * did a lock-steal - fix up the PI-state in that case. */ if (q.pi_state && (q.pi_state->owner != current)) { spin_lock(q.lock_ptr); ret = fixup_pi_state_owner(uaddr2, &q, current); spin_unlock(q.lock_ptr); } } else { /* * We have been woken up by futex_unlock_pi(), a timeout, or a * signal. futex_unlock_pi() will not destroy the lock_ptr nor * the pi_state. */ WARN_ON(!q.pi_state); pi_mutex = &q.pi_state->pi_mutex; ret = rt_mutex_finish_proxy_lock(pi_mutex, to, &rt_waiter, 1); debug_rt_mutex_free_waiter(&rt_waiter); spin_lock(q.lock_ptr); /* * Fixup the pi_state owner and possibly acquire the lock if we * haven't already. */ res = fixup_owner(uaddr2, &q, !ret); /* * If fixup_owner() returned an error, proprogate that. If it * acquired the lock, clear -ETIMEDOUT or -EINTR. */ if (res) ret = (res < 0) ? res : 0; /* Unqueue and drop the lock. */ unqueue_me_pi(&q); } /* * If fixup_pi_state_owner() faulted and was unable to handle the * fault, unlock the rt_mutex and return the fault to userspace. */ if (ret == -EFAULT) { if (pi_mutex && rt_mutex_owner(pi_mutex) == current) rt_mutex_unlock(pi_mutex); } else if (ret == -EINTR) { /* * We've already been requeued, but cannot restart by calling * futex_lock_pi() directly. We could restart this syscall, but * it would detect that the user space "val" changed and return * -EWOULDBLOCK. Save the overhead of the restart and return * -EWOULDBLOCK directly. */ ret = -EWOULDBLOCK; } out_put_keys: put_futex_key(&q.key); out_key2: put_futex_key(&key2); out: if (to) { hrtimer_cancel(&to->timer); destroy_hrtimer_on_stack(&to->timer); } return ret; } /* * Support for robust futexes: the kernel cleans up held futexes at * thread exit time. * * Implementation: user-space maintains a per-thread list of locks it * is holding. Upon do_exit(), the kernel carefully walks this list, * and marks all locks that are owned by this thread with the * FUTEX_OWNER_DIED bit, and wakes up a waiter (if any). The list is * always manipulated with the lock held, so the list is private and * per-thread. Userspace also maintains a per-thread 'list_op_pending' * field, to allow the kernel to clean up if the thread dies after * acquiring the lock, but just before it could have added itself to * the list. There can only be one such pending lock. */ /** * sys_set_robust_list() - Set the robust-futex list head of a task * @head: pointer to the list-head * @len: length of the list-head, as userspace expects */ SYSCALL_DEFINE2(set_robust_list, struct robust_list_head __user *, head, size_t, len) { if (!futex_cmpxchg_enabled) return -ENOSYS; /* * The kernel knows only one size for now: */ if (unlikely(len != sizeof(*head))) return -EINVAL; current->robust_list = head; return 0; } /** * sys_get_robust_list() - Get the robust-futex list head of a task * @pid: pid of the process [zero for current task] * @head_ptr: pointer to a list-head pointer, the kernel fills it in * @len_ptr: pointer to a length field, the kernel fills in the header size */ SYSCALL_DEFINE3(get_robust_list, int, pid, struct robust_list_head __user * __user *, head_ptr, size_t __user *, len_ptr) { struct robust_list_head __user *head; unsigned long ret; struct task_struct *p; if (!futex_cmpxchg_enabled) return -ENOSYS; rcu_read_lock(); ret = -ESRCH; if (!pid) p = current; else { p = find_task_by_vpid(pid); if (!p) goto err_unlock; } ret = -EPERM; if (!ptrace_may_access(p, PTRACE_MODE_READ)) goto err_unlock; head = p->robust_list; rcu_read_unlock(); if (put_user(sizeof(*head), len_ptr)) return -EFAULT; return put_user(head, head_ptr); err_unlock: rcu_read_unlock(); return ret; } /* * Process a futex-list entry, check whether it's owned by the * dying task, and do notification if so: */ int handle_futex_death(u32 __user *uaddr, struct task_struct *curr, int pi) { u32 uval, uninitialized_var(nval), mval; retry: if (get_user(uval, uaddr)) return -1; if ((uval & FUTEX_TID_MASK) == task_pid_vnr(curr)) { /* * Ok, this dying thread is truly holding a futex * of interest. Set the OWNER_DIED bit atomically * via cmpxchg, and if the value had FUTEX_WAITERS * set, wake up a waiter (if any). (We have to do a * futex_wake() even if OWNER_DIED is already set - * to handle the rare but possible case of recursive * thread-death.) The rest of the cleanup is done in * userspace. */ mval = (uval & FUTEX_WAITERS) | FUTEX_OWNER_DIED; /* * We are not holding a lock here, but we want to have * the pagefault_disable/enable() protection because * we want to handle the fault gracefully. If the * access fails we try to fault in the futex with R/W * verification via get_user_pages. get_user() above * does not guarantee R/W access. If that fails we * give up and leave the futex locked. */ if (cmpxchg_futex_value_locked(&nval, uaddr, uval, mval)) { if (fault_in_user_writeable(uaddr)) return -1; goto retry; } if (nval != uval) goto retry; /* * Wake robust non-PI futexes here. The wakeup of * PI futexes happens in exit_pi_state(): */ if (!pi && (uval & FUTEX_WAITERS)) futex_wake(uaddr, 1, 1, FUTEX_BITSET_MATCH_ANY); } return 0; } /* * Fetch a robust-list pointer. Bit 0 signals PI futexes: */ static inline int fetch_robust_entry(struct robust_list __user **entry, struct robust_list __user * __user *head, unsigned int *pi) { unsigned long uentry; if (get_user(uentry, (unsigned long __user *)head)) return -EFAULT; *entry = (void __user *)(uentry & ~1UL); *pi = uentry & 1; return 0; } /* * Walk curr->robust_list (very carefully, it's a userspace list!) * and mark any locks found there dead, and notify any waiters. * * We silently return on any sign of list-walking problem. */ void exit_robust_list(struct task_struct *curr) { struct robust_list_head __user *head = curr->robust_list; struct robust_list __user *entry, *next_entry, *pending; unsigned int limit = ROBUST_LIST_LIMIT, pi, pip; unsigned int uninitialized_var(next_pi); unsigned long futex_offset; int rc; if (!futex_cmpxchg_enabled) return; /* * Fetch the list head (which was registered earlier, via * sys_set_robust_list()): */ if (fetch_robust_entry(&entry, &head->list.next, &pi)) return; /* * Fetch the relative futex offset: */ if (get_user(futex_offset, &head->futex_offset)) return; /* * Fetch any possibly pending lock-add first, and handle it * if it exists: */ if (fetch_robust_entry(&pending, &head->list_op_pending, &pip)) return; next_entry = NULL; /* avoid warning with gcc */ while (entry != &head->list) { /* * Fetch the next entry in the list before calling * handle_futex_death: */ rc = fetch_robust_entry(&next_entry, &entry->next, &next_pi); /* * A pending lock might already be on the list, so * don't process it twice: */ if (entry != pending) if (handle_futex_death((void __user *)entry + futex_offset, curr, pi)) return; if (rc) return; entry = next_entry; pi = next_pi; /* * Avoid excessively long or circular lists: */ if (!--limit) break; cond_resched(); } if (pending) handle_futex_death((void __user *)pending + futex_offset, curr, pip); } long do_futex(u32 __user *uaddr, int op, u32 val, ktime_t *timeout, u32 __user *uaddr2, u32 val2, u32 val3) { int cmd = op & FUTEX_CMD_MASK; unsigned int flags = 0; if (!(op & FUTEX_PRIVATE_FLAG)) flags |= FLAGS_SHARED; if (op & FUTEX_CLOCK_REALTIME) { flags |= FLAGS_CLOCKRT; if (cmd != FUTEX_WAIT_BITSET && cmd != FUTEX_WAIT_REQUEUE_PI) return -ENOSYS; } switch (cmd) { case FUTEX_LOCK_PI: case FUTEX_UNLOCK_PI: case FUTEX_TRYLOCK_PI: case FUTEX_WAIT_REQUEUE_PI: case FUTEX_CMP_REQUEUE_PI: if (!futex_cmpxchg_enabled) return -ENOSYS; } switch (cmd) { case FUTEX_WAIT: val3 = FUTEX_BITSET_MATCH_ANY; case FUTEX_WAIT_BITSET: return futex_wait(uaddr, flags, val, timeout, val3); case FUTEX_WAKE: val3 = FUTEX_BITSET_MATCH_ANY; case FUTEX_WAKE_BITSET: return futex_wake(uaddr, flags, val, val3); case FUTEX_REQUEUE: return futex_requeue(uaddr, flags, uaddr2, val, val2, NULL, 0); case FUTEX_CMP_REQUEUE: return futex_requeue(uaddr, flags, uaddr2, val, val2, &val3, 0); case FUTEX_WAKE_OP: return futex_wake_op(uaddr, flags, uaddr2, val, val2, val3); case FUTEX_LOCK_PI: return futex_lock_pi(uaddr, flags, val, timeout, 0); case FUTEX_UNLOCK_PI: return futex_unlock_pi(uaddr, flags); case FUTEX_TRYLOCK_PI: return futex_lock_pi(uaddr, flags, 0, timeout, 1); case FUTEX_WAIT_REQUEUE_PI: val3 = FUTEX_BITSET_MATCH_ANY; return futex_wait_requeue_pi(uaddr, flags, val, timeout, val3, uaddr2); case FUTEX_CMP_REQUEUE_PI: return futex_requeue(uaddr, flags, uaddr2, val, val2, &val3, 1); } return -ENOSYS; } SYSCALL_DEFINE6(futex, u32 __user *, uaddr, int, op, u32, val, struct timespec __user *, utime, u32 __user *, uaddr2, u32, val3) { struct timespec ts; ktime_t t, *tp = NULL; u32 val2 = 0; int cmd = op & FUTEX_CMD_MASK; if (utime && (cmd == FUTEX_WAIT || cmd == FUTEX_LOCK_PI || cmd == FUTEX_WAIT_BITSET || cmd == FUTEX_WAIT_REQUEUE_PI)) { if (copy_from_user(&ts, utime, sizeof(ts)) != 0) return -EFAULT; if (!timespec_valid(&ts)) return -EINVAL; t = timespec_to_ktime(ts); if (cmd == FUTEX_WAIT) t = ktime_add_safe(ktime_get(), t); tp = &t; } /* * requeue parameter in 'utime' if cmd == FUTEX_*_REQUEUE_*. * number of waiters to wake in 'utime' if cmd == FUTEX_WAKE_OP. */ if (cmd == FUTEX_REQUEUE || cmd == FUTEX_CMP_REQUEUE || cmd == FUTEX_CMP_REQUEUE_PI || cmd == FUTEX_WAKE_OP) val2 = (u32) (unsigned long) utime; return do_futex(uaddr, op, val, tp, uaddr2, val2, val3); } static void __init futex_detect_cmpxchg(void) { #ifndef CONFIG_HAVE_FUTEX_CMPXCHG u32 curval; /* * This will fail and we want it. Some arch implementations do * runtime detection of the futex_atomic_cmpxchg_inatomic() * functionality. We want to know that before we call in any * of the complex code paths. Also we want to prevent * registration of robust lists in that case. NULL is * guaranteed to fault and we get -EFAULT on functional * implementation, the non-functional ones will return * -ENOSYS. */ if (cmpxchg_futex_value_locked(&curval, NULL, 0, 0) == -EFAULT) futex_cmpxchg_enabled = 1; #endif } static int __init futex_init(void) { int i; futex_detect_cmpxchg(); for (i = 0; i < ARRAY_SIZE(futex_queues); i++) { plist_head_init(&futex_queues[i].chain); spin_lock_init(&futex_queues[i].lock); } return 0; } __initcall(futex_init);
Psycho666/Simplicity_trlte_kernel
kernel/futex.c
C
gpl-2.0
77,612
[ 30522, 1013, 1008, 1008, 3435, 5198, 15327, 20101, 20156, 1006, 2029, 1045, 2655, 1000, 11865, 2618, 20156, 999, 1000, 1007, 1012, 1008, 1006, 1039, 1007, 13174, 5735, 1010, 9980, 2526, 1008, 1008, 18960, 11865, 2618, 20156, 1010, 11865, 26...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* * Copyright 2009-2013 Aarhus University * * 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 dk.brics.tajs.analysis; import dk.brics.tajs.flowgraph.BasicBlock; import dk.brics.tajs.lattice.CallEdge; import dk.brics.tajs.solver.CallGraph; import dk.brics.tajs.solver.IWorkListStrategy; /** * Work list strategy. */ public class WorkListStrategy implements IWorkListStrategy<Context> { private CallGraph<State,Context,CallEdge<State>> call_graph; /** * Constructs a new WorkListStrategy object. */ public WorkListStrategy() {} /** * Sets the call graph. */ public void setCallGraph(CallGraph<State,Context,CallEdge<State>> call_graph) { this.call_graph = call_graph; } @Override public int compare(IEntry<Context> e1, IEntry<Context> e2) { BasicBlock n1 = e1.getBlock(); BasicBlock n2 = e2.getBlock(); int serial1 = e1.getSerial(); int serial2 = e2.getSerial(); if (serial1 == serial2) return 0; final int E1_FIRST = -1; final int E2_FIRST = 1; if (n1.getFunction().equals(n2.getFunction()) && e1.getContext().equals(e2.getContext())) { // same function and same context: use block order if (n1.getOrder() < n2.getOrder()) return E1_FIRST; else if (n2.getOrder() < n1.getOrder()) return E2_FIRST; } int function_context_order1 = call_graph.getBlockContextOrder(e1.getContext().getEntryBlockAndContext()); int function_context_order2 = call_graph.getBlockContextOrder(e2.getContext().getEntryBlockAndContext()); // different function/context: order by occurrence number if (function_context_order1 < function_context_order2) return E2_FIRST; else if (function_context_order2 < function_context_order1) return E1_FIRST; // strategy: breadth first return serial1 - serial2; } }
cursem/ScriptCompressor
ScriptCompressor1.0/src/dk/brics/tajs/analysis/WorkListStrategy.java
Java
apache-2.0
2,303
[ 30522, 1013, 1008, 1008, 9385, 2268, 1011, 2286, 29173, 2118, 1008, 1008, 7000, 2104, 1996, 15895, 6105, 1010, 2544, 1016, 1012, 1014, 1006, 1996, 1000, 6105, 1000, 1007, 1025, 1008, 2017, 2089, 2025, 2224, 2023, 5371, 3272, 1999, 12646, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<?php /** * @package Advanced Module Manager * @version 4.17.0 * * @author Peter van Westen <peter@nonumber.nl> * @link http://www.nonumber.nl * @copyright Copyright © 2014 NoNumber All Rights Reserved * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL */ /** * @copyright Copyright (C) 2005 - 2014 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ defined('_JEXEC') or die; jimport('joomla.application.component.modeladmin'); /** * Module model. * * @package Joomla.Administrator * @subpackage com_advancedmodules * @since 1.6 */ class AdvancedModulesModelModule extends JModelAdmin { /** * @var string The prefix to use with controller messages. * @since 1.6 */ protected $text_prefix = 'COM_MODULES'; /** * @var string The help screen key for the module. * @since 1.6 */ protected $helpKey = 'JHELP_EXTENSIONS_MODULE_MANAGER_EDIT'; /** * @var string The help screen base URL for the module. * @since 1.6 */ protected $helpURL; /** * Method to auto-populate the model state. * * Note. Calling getState in this method will result in recursion. * * @return void * * @since 1.6 */ protected function populateState() { $app = JFactory::getApplication('administrator'); // Load the User state. $pk = $app->input->getInt('id'); if (!$pk) { if ($extensionId = (int) $app->getUserState('com_advancedmodules.add.module.extension_id')) { $this->setState('extension.id', $extensionId); } } $this->setState('module.id', $pk); // Load the parameters. $params = JComponentHelper::getParams('com_advancedmodules'); $this->setState('params', $params); $this->getConfig(); } /** * Method to perform batch operations on a set of modules. * * @param array $commands An array of commands to perform. * @param array $pks An array of item ids. * @param array $contexts An array of item contexts. * * @return boolean Returns true on success, false on failure. * * @since 1.7 */ public function batch($commands, $pks, $contexts) { // Sanitize user ids. $pks = array_unique($pks); JArrayHelper::toInteger($pks); // Remove any values of zero. if (array_search(0, $pks, true)) { unset($pks[array_search(0, $pks, true)]); } if (empty($pks)) { $this->setError(JText::_('JGLOBAL_NO_ITEM_SELECTED')); return false; } $done = false; if (!empty($commands['position_id'])) { $cmd = JArrayHelper::getValue($commands, 'move_copy', 'c'); if (!empty($commands['position_id'])) { if ($cmd == 'c') { $result = $this->batchCopy($commands['position_id'], $pks, $contexts); if (is_array($result)) { $pks = $result; } else { return false; } } elseif ($cmd == 'm' && !$this->batchMove($commands['position_id'], $pks, $contexts)) { return false; } $done = true; } } if (!empty($commands['assetgroup_id'])) { if (!$this->batchAccess($commands['assetgroup_id'], $pks, $contexts)) { return false; } $done = true; } if (!empty($commands['language_id'])) { if (!$this->batchLanguage($commands['language_id'], $pks, $contexts)) { return false; } $done = true; } if (!$done) { $this->setError(JText::_('JLIB_APPLICATION_ERROR_INSUFFICIENT_BATCH_INFORMATION')); return false; } // Clear the cache $this->cleanCache(); return true; } /** * Batch language changes for a group of rows. * * @param string $value The new value matching a language. * @param array $pks An array of row IDs. * @param array $contexts An array of item contexts. * * @return boolean True if successful, false otherwise and internal error is set. * * @since 11.3 */ protected function batchLanguage($value, $pks, $contexts) { // Set the variables $user = JFactory::getUser(); $db = $this->getDbo(); $table = $this->getTable(); $table_adv = JTable::getInstance('AdvancedModules', 'AdvancedModulesTable'); foreach ($pks as $pk) { if ($user->authorise('core.edit', $contexts[$pk])) { $table->reset(); $table->load($pk); $table->language = $value; if (!$table->store()) { $this->setError($table->getError()); return false; } if ($table->id && !$table_adv->load($table->id)) { $table_adv->moduleid = $table->id; $db->insertObject($table_adv->getTableName(), $table_adv, $table_adv->getKeyName()); } if ($table_adv->load($pk, true)) { $table_adv->moduleid = $table->id; $registry = new JRegistry; $registry->loadString($table_adv->params); $params = $registry->toArray(); if ($value == '*') { $params['assignto_languages'] = 0; $params['assignto_languages_selection'] = array(); } else { $params['assignto_languages'] = 1; $params['assignto_languages_selection'] = array($value); } $registry = new JRegistry; $registry->loadArray($params); $table_adv->params = (string) $registry; if (!$table_adv->check() || !$table_adv->store()) { $this->setError($table_adv->getError()); return false; } } } else { $this->setError(JText::_('JLIB_APPLICATION_ERROR_BATCH_CANNOT_EDIT')); return false; } } // Clean the cache $this->cleanCache(); return true; } /** * Batch copy modules to a new position or current. * * @param integer $value The new value matching a module position. * @param array $pks An array of row IDs. * @param array $contexts An array of item contexts. * * @return boolean True if successful, false otherwise and internal error is set. * * @since 11.1 */ protected function batchCopy($value, $pks, $contexts) { // Set the variables $user = JFactory::getUser(); $db = $this->getDbo(); $query = $db->getQuery(true); $table = $this->getTable(); $table_adv = JTable::getInstance('AdvancedModules', 'AdvancedModulesTable'); $newIds = array(); $i = 0; foreach ($pks as $pk) { if ($user->authorise('core.create', 'com_advancedmodules')) { $table->reset(); $table->load($pk); // Set the new position if ($value == 'noposition') { $position = ''; } elseif ($value == 'nochange') { $position = $table->position; } else { $position = $value; } $table->position = $position; // Alter the title if necessary $data = $this->generateNewTitle(0, $table->title, $table->position); $table->title = $data['0']; // Reset the ID because we are making a copy $table->id = 0; // Unpublish the new module $table->published = 0; if (!$table->store()) { $this->setError($table->getError()); return false; } // Get the new item ID $newId = (int) $table->get('id'); // Add the new ID to the array $newIds[$i] = $newId; $i++; // Now we need to handle the module assignments $query->clear() ->select('m.menuid') ->from('#__modules_menu as m') ->where('m.moduleid = ' . (int) $pk); $db->setQuery($query); $menus = $db->loadColumn(); // Insert the new records into the table foreach ($menus as $menu) { $query->clear() ->insert('#__modules_menu') ->columns(array($db->quoteName('moduleid'), $db->quoteName('menuid'))) ->values($newId . ', ' . $menu); $db->setQuery($query); try { $db->execute(); } catch (RuntimeException $e) { return JError::raiseWarning(500, $e->getMessage()); } } if ($table->id && !$table_adv->load($table->id)) { $table_adv->moduleid = $table->id; $db->insertObject($table_adv->getTableName(), $table_adv, $table_adv->getKeyName()); } if ($table_adv->load($pk, true)) { $table_adv->moduleid = $table->id; $rules = JAccess::getAssetRules('com_advancedmodules.module.' . $pk); $table_adv->setRules($rules); if (!$table_adv->check() || !$table_adv->store()) { $this->setError($table_adv->getError()); return false; } } } else { $this->setError(JText::_('JLIB_APPLICATION_ERROR_BATCH_CANNOT_CREATE')); return false; } } // Clean the cache $this->cleanCache(); return $newIds; } /** * Batch move modules to a new position or current. * * @param integer $value The new value matching a module position. * @param array $pks An array of row IDs. * @param array $contexts An array of item contexts. * * @return boolean True if successful, false otherwise and internal error is set. * * @since 11.1 */ protected function batchMove($value, $pks, $contexts) { // Set the variables $user = JFactory::getUser(); $table = $this->getTable(); foreach ($pks as $pk) { if ($user->authorise('core.edit', 'com_advancedmodules')) { $table->reset(); $table->load($pk); // Set the new position if ($value == 'noposition') { $position = ''; } elseif ($value == 'nochange') { $position = $table->position; } else { $position = $value; } $table->position = $position; // Alter the title if necessary $data = $this->generateNewTitle(0, $table->title, $table->position); $table->title = $data['0']; // Unpublish the moved module $table->published = 0; if (!$table->store()) { $this->setError($table->getError()); return false; } } else { $this->setError(JText::_('JLIB_APPLICATION_ERROR_BATCH_CANNOT_EDIT')); return false; } } // Clean the cache $this->cleanCache(); return true; } /** * Method to delete rows. * * @param array &$pks An array of item ids. * * @return boolean Returns true on success, false on failure. * * @since 1.6 */ public function delete(&$pks) { $pks = (array) $pks; $user = JFactory::getUser(); $table = $this->getTable(); $db = $this->getDbo(); $query = $db->getQuery(true); // Iterate the items to delete each one. foreach ($pks as $i => $pk) { if ($table->load($pk)) { // Access checks. if (!$user->authorise('core.delete', 'com_advancedmodules.module.' . (int) $pk) || $table->published != -2) { JError::raiseWarning(403, JText::_('JERROR_CORE_DELETE_NOT_PERMITTED')); return; } if (!$table->delete($pk)) { throw new Exception($table->getError()); } else { // Delete the menu assignments $query->clear() ->delete('#__modules_menu') ->where('moduleid=' . (int) $pk); $db->setQuery($query); $db->execute(); $query->clear() ->delete('#__advancedmodules') ->where('moduleid=' . (int) $pk); $db->setQuery($query); $db->execute(); // delete asset $query->clear() ->delete('#__assets') ->where('name = ' . $db->quote('com_advancedmodules.module.' . (int) $pk)); $db->setQuery($query); $db->execute(); } // Clear module cache parent::cleanCache($table->module, $table->client_id); } else { throw new Exception($table->getError()); } } // Clear modules cache $this->cleanCache(); return true; } /** * Method to duplicate modules. * * @param array &$pks An array of primary key IDs. * * @return boolean True if successful. * * @since 1.6 * @throws Exception */ public function duplicate(&$pks) { $user = JFactory::getUser(); // Access checks. if (!$user->authorise('core.create', 'com_advancedmodules')) { throw new Exception(JText::_('JERROR_CORE_CREATE_NOT_PERMITTED')); } $db = $this->getDbo(); $query = $db->getQuery(true); $inserts = array(); $table = $this->getTable(); $table_adv = JTable::getInstance('AdvancedModules', 'AdvancedModulesTable'); foreach ($pks as $pk) { if ($table->load($pk, true)) { // Reset the id to create a new record. $table->id = 0; // Alter the title. $m = null; if (preg_match('#\((\d+)\)$#', $table->title, $m)) { $table->title = preg_replace('#\(\d+\)$#', '(' . ($m[1] + 1) . ')', $table->title); } else { $table->title .= ' (2)'; } // Unpublish duplicate module $table->published = 0; if (!$table->check() || !$table->store()) { throw new Exception($table->getError()); } $query->clear() ->select($db->quoteName('menuid')) ->from($db->quoteName('#__modules_menu')) ->where($db->quoteName('moduleid') . ' = ' . (int) $pk); $db->setQuery($query); $rows = $db->loadColumn(); foreach ($rows as $menuid) { $inserts[(int) $table->id . '-' . (int) $menuid] = (int) $table->id . ',' . (int) $menuid; } if ($table->id && !$table_adv->load($table->id)) { $table_adv->moduleid = $table->id; $db->insertObject($table_adv->getTableName(), $table_adv, $table_adv->getKeyName()); } if ($table_adv->load($pk, true)) { $table_adv->moduleid = $table->id; $rules = JAccess::getAssetRules('com_advancedmodules.module.' . $pk); $table_adv->setRules($rules); if (!$table_adv->check() || !$table_adv->store()) { throw new Exception($table_adv->getError()); } } } else { throw new Exception($table->getError()); } } if (!empty($inserts)) { // Module-Menu Mapping: Do it in one query $query->clear() ->insert('#__modules_menu') ->columns(array($db->quoteName('moduleid'), $db->quoteName('menuid'))); foreach($inserts as $insert) { $query->values($insert); } $db->setQuery($query); try { $db->execute(); } catch (RuntimeException $e) { return JError::raiseWarning(500, $e->getMessage()); } } // Clear modules cache $this->cleanCache(); return true; } /** * Method to set color of modules. * * @param array &$pks An array of primary key IDs. * @param string $color RGB color * * @return boolean True if successful. * * @since 1.6 * @throws Exception */ public function setcolor(&$pks, $color) { // Set the variables $db = $this->getDbo(); $user = JFactory::getUser(); $table_adv = JTable::getInstance('AdvancedModules', 'AdvancedModulesTable'); foreach ($pks as $pk) { if ($user->authorise('core.edit', 'com_advancedmodules')) { if (!$table_adv->load($pk)) { $table_adv->moduleid = $pk; $db->insertObject($table_adv->getTableName(), $table_adv, $table_adv->getKeyName()); } if ($table_adv->load($pk, true)) { $registry = new JRegistry; $registry->loadString($table_adv->params); $params = $registry->toArray(); $params['color'] = $color; $registry = new JRegistry; $registry->loadArray($params); $table_adv->params = (string) $registry; if (!$table_adv->check() || !$table_adv->store()) { $this->setError($table_adv->getError()); return false; } } } else { $this->setError(JText::_('JLIB_APPLICATION_ERROR_BATCH_CANNOT_EDIT')); return false; } } // Clean the cache $this->cleanCache(); return true; } /** * Method to change the title. * * @param integer $category_id The id of the category. Not used here. * @param string $title The title. * @param string $position The position. * * @return array Contains the modified title. * * @since 2.5 */ protected function generateNewTitle($category_id, $title, $position) { // Alter the title & alias $table = $this->getTable(); while ($table->load(array('position' => $position, 'title' => $title))) { $title = JString::increment($title); } return array($title); } /** * Method to get the client object * * @return void * * @since 1.6 */ function &getClient() { return $this->_client; } /** * Method to get the record form. * * @param array $data Data for the form. * @param boolean $loadData True if the form is to load its own data (default case), false if not. * * @return JForm A JForm object on success, false on failure * * @since 1.6 */ public function getForm($data = array(), $loadData = true) { // The folder and element vars are passed when saving the form. if (empty($data)) { $item = $this->getItem(); $clientId = $item->client_id; $module = $item->module; } else { $clientId = JArrayHelper::getValue($data, 'client_id'); $module = JArrayHelper::getValue($data, 'module'); } // These variables are used to add data from the plugin XML files. $this->setState('item.client_id', $clientId); $this->setState('item.module', $module); // Get the form. $form = $this->loadForm('com_advancedmodules.module', 'module', array('control' => 'jform', 'load_data' => $loadData)); if (empty($form)) { return false; } $form->setFieldAttribute('position', 'client', $this->getState('item.client_id') == 0 ? 'site' : 'administrator'); // Modify the form based on access controls. if (!$this->canEditState((object) $data)) { // Disable fields for display. $form->setFieldAttribute('ordering', 'disabled', 'true'); $form->setFieldAttribute('published', 'disabled', 'true'); $form->setFieldAttribute('publish_up', 'disabled', 'true'); $form->setFieldAttribute('publish_down', 'disabled', 'true'); // Disable fields while saving. // The controller has already verified this is a record you can edit. $form->setFieldAttribute('ordering', 'filter', 'unset'); $form->setFieldAttribute('published', 'filter', 'unset'); $form->setFieldAttribute('publish_up', 'filter', 'unset'); $form->setFieldAttribute('publish_down', 'filter', 'unset'); } return $form; } /** * Method to get the data that should be injected in the form. * * @return mixed The data for the form. * * @since 1.6 */ protected function loadFormData() { $app = JFactory::getApplication(); // Check the session for previously entered form data. $data = JFactory::getApplication()->getUserState('com_advancedmodules.edit.module.data', array()); if (empty($data)) { $data = $this->getItem(); // This allows us to inject parameter settings into a new module. $params = $app->getUserState('com_advancedmodules.add.module.params'); if (is_array($params)) { $data->set('params', $params); } } return $data; } /** * Method to get a single record. * * @param integer $pk The id of the primary key. * * @return mixed Object on success, false on failure. * * @since 1.6 */ public function getItem($pk = null) { $pk = (!empty($pk)) ? (int) $pk : (int) $this->getState('module.id'); $db = $this->getDbo(); $query = $db->getQuery(true); if (!isset($this->_cache[$pk])) { $false = false; // Get a row instance. $table = $this->getTable(); // Attempt to load the row. $return = $table->load($pk); // Check for a table object error. if ($return === false && $error = $table->getError()) { $this->setError($error); return $false; } // Check if we are creating a new extension. if (empty($pk)) { if ($extensionId = (int) $this->getState('extension.id')) { $query->clear() ->select('e.element, e.client_id') ->from('#__extensions as e') ->where('e.extension_id = ' . $extensionId) ->where('e.type = ' . $db->quote('module')); $db->setQuery($query); try { $extension = $db->loadObject(); } catch (RuntimeException $e) { $this->setError($e->getMessage); return false; } if (empty($extension)) { $this->setError('COM_MODULES_ERROR_CANNOT_FIND_MODULE'); return false; } // Extension found, prime some module values. $table->module = $extension->element; $table->client_id = $extension->client_id; } else { $app = JFactory::getApplication(); $app->redirect(JRoute::_('index.php?option=com_advancedmodules&view=modules', false)); return false; } } // Convert to the JObject before adding other data. $properties = $table->getProperties(1); $this->_cache[$pk] = JArrayHelper::toObject($properties, 'JObject'); // Convert the params field to an array. $registry = new JRegistry; $registry->loadString($table->params); $this->_cache[$pk]->params = $registry->toArray(); // Advanced parameters // Get a row instance. $table_adv = $this->getTable('AdvancedModules', 'AdvancedModulesTable'); // Attempt to load the row. $table_adv->load($pk); $this->_cache[$pk]->asset_id = $table_adv->asset_id; // Convert the params field to an array. $registry = new JRegistry; $registry->loadString($table_adv->params); $this->_cache[$pk]->advancedparams = $registry->toArray(); $this->_cache[$pk]->advancedparams = $this->initAssignments($pk, $this->_cache[$pk]); $assigned = array(); $assignment = 0; if (isset($this->_cache[$pk]->advancedparams['assignto_menuitems']) && isset($this->_cache[$pk]->advancedparams['assignto_menuitems_selection'])) { $assigned = $this->_cache[$pk]->advancedparams['assignto_menuitems_selection']; if ($this->_cache[$pk]->advancedparams['assignto_menuitems'] == 1 && empty($this->_cache[$pk]->advancedparams['assignto_menuitems_selection'])) { $assignment = '-'; } else if ($this->_cache[$pk]->advancedparams['assignto_menuitems'] == 1) { $assignment = '1'; } else if ($this->_cache[$pk]->advancedparams['assignto_menuitems'] == 2) { $assignment = '-1'; } } $this->_cache[$pk]->assigned = $assigned; $this->_cache[$pk]->assignment = $assignment; // Get the module XML. $client = JApplicationHelper::getClientInfo($table->client_id); $path = JPath::clean($client->path . '/modules/' . $table->module . '/' . $table->module . '.xml'); if (file_exists($path)) { $this->_cache[$pk]->xml = simplexml_load_file($path); } else { $this->_cache[$pk]->xml = null; } } return $this->_cache[$pk]; } /** * Get the necessary data to load an item help screen. * * @return object An object with key, url, and local properties for loading the item help screen. * * @since 1.6 */ public function getHelp() { return (object) array('key' => $this->helpKey, 'url' => $this->helpURL); } /** * Returns a reference to the a Table object, always creating it. * * @param string $type The table type to instantiate * @param string $prefix A prefix for the table class name. Optional. * @param array $config Configuration array for model. Optional. * * @return JTable A database object * * @since 1.6 */ public function getTable($type = 'Module', $prefix = 'JTable', $config = array()) { return JTable::getInstance($type, $prefix, $config); } /** * Prepare and sanitise the table prior to saving. * * @param JTable &$table The database object * * @return void * * @since 1.6 */ protected function prepareTable(&$table) { $table->title = htmlspecialchars_decode($table->title, ENT_QUOTES); } /** * Method to preprocess the form * * @param JForm $form A form object. * @param mixed $data The data expected for the form. * @param string $group The name of the plugin group to import (defaults to "content"). * * @return void * * @since 1.6 * @throws Exception if there is an error loading the form. */ protected function preprocessForm(JForm $form, $data, $group = 'content') { jimport('joomla.filesystem.path'); $lang = JFactory::getLanguage(); $clientId = $this->getState('item.client_id'); $module = $this->getState('item.module'); $client = JApplicationHelper::getClientInfo($clientId); $formFile = JPath::clean($client->path . '/modules/' . $module . '/' . $module . '.xml'); // Load the core and/or local language file(s). $lang->load($module, $client->path, null, false, false) || $lang->load($module, $client->path . '/modules/' . $module, null, false, false) || $lang->load($module, $client->path, $lang->getDefault(), false, false) || $lang->load($module, $client->path . '/modules/' . $module, $lang->getDefault(), false, false); if (file_exists($formFile)) { // Get the module form. if (!$form->loadFile($formFile, false, '//config')) { throw new Exception(JText::_('JERROR_LOADFILE_FAILED')); } // Attempt to load the xml file. if (!$xml = simplexml_load_file($formFile)) { throw new Exception(JText::_('JERROR_LOADFILE_FAILED')); } // Get the help data from the XML file if present. $help = $xml->xpath('/extension/help'); if (!empty($help)) { $helpKey = trim((string) $help[0]['key']); $helpURL = trim((string) $help[0]['url']); $this->helpKey = $helpKey ? $helpKey : $this->helpKey; $this->helpURL = $helpURL ? $helpURL : $this->helpURL; } } // Trigger the default form events. parent::preprocessForm($form, $data, $group); } /** * Loads ContentHelper for filters before validating data. * * @param object $form The form to validate against. * @param array $data The data to validate. * @param string $group The name of the group(defaults to null). * * @return mixed Array of filtered data if valid, false otherwise. * * @since 1.1 */ public function validate($form, $data, $group = null) { require_once JPATH_ADMINISTRATOR . '/components/com_content/helpers/content.php'; return parent::validate($form, $data, $group); } /** * Applies the text filters to arbitrary text as per settings for current user groups * * @param text $text The string to filter * * @return string The filtered string */ public static function filterText($text) { return JComponentHelper::filterText($text); } /** * Method to save the form data. * * @param array $data The form data. * * @return boolean True on success. * * @since 1.6 */ public function save($data) { $advancedparams = JFactory::getApplication()->input->get('advancedparams', array(), 'array'); $dispatcher = JDispatcher::getInstance(); $input = JFactory::getApplication()->input; $table = $this->getTable(); $pk = (!empty($data['id'])) ? $data['id'] : (int) $this->getState('module.id'); $isNew = true; // Include the content modules for the onSave events. JPluginHelper::importPlugin('extension'); // Load the row if saving an existing record. if ($pk > 0) { $table->load($pk); $isNew = false; } // Alter the title and published state for Save as Copy if ($input->get('task') == 'save2copy') { $orig_data = $input->post->get('jform', array(), 'array'); $orig_table = clone($this->getTable()); $orig_table->load((int) $orig_data['id']); if ($data['title'] == $orig_table->title) { $data['title'] .= ' ' . JText::_('JGLOBAL_COPY'); $data['published'] = 0; } } // correct the publish date details if (isset($advancedparams['assignto_date'])) { $publish_up = 0; $publish_down = 0; if ($advancedparams['assignto_date'] == 2) { $publish_up = $advancedparams['assignto_date_publish_down']; } else if ($advancedparams['assignto_date'] == 1) { $publish_up = $advancedparams['assignto_date_publish_up']; $publish_down = $advancedparams['assignto_date_publish_down']; } $data['publish_up'] = $publish_up; $data['publish_down'] = $publish_down; } $lang = '*'; if (isset($advancedparams['assignto_languages']) && $advancedparams['assignto_languages'] == 1 && count($advancedparams['assignto_languages_selection']) === 1 ) { $lang = (string) $advancedparams['assignto_languages_selection']['0']; } $data['language'] = $lang; // Bind the data. if (!$table->bind($data)) { $this->setError($table->getError()); return false; } // Prepare the row for saving $this->prepareTable($table); // Check the data. if (!$table->check()) { $this->setError($table->getError()); return false; } // Trigger the onExtensionBeforeSave event. $result = $dispatcher->trigger('onExtensionBeforeSave', array('com_advancedmodules.module', &$table, $isNew)); if (in_array(false, $result, true)) { $this->setError($table->getError()); return false; } // Store the data. if (!$table->store()) { $this->setError($table->getError()); return false; } $table_adv = JTable::getInstance('AdvancedModules', 'AdvancedModulesTable'); $table_adv->moduleid = $table->id; if ($table_adv->moduleid && !$table_adv->load($table_adv->moduleid)) { $db = $table_adv->getDbo(); $db->insertObject($table_adv->getTableName(), $table_adv, $table_adv->getKeyName()); } if (isset($data['rules'])) { $table_adv->_title = $data['title']; $table_adv->setRules($data['rules']); } $registry = new JRegistry; $registry->loadArray($advancedparams); $table_adv->params = (string) $registry; // Check the row $table_adv->check(); // Store the row if (!$table_adv->store()) { $this->setError($table_adv->getError()); } // // Process the menu link mappings. // $data['assignment'] = '0'; $data['assigned'] = array(); if (isset($advancedparams['assignto_menuitems'])) { $empty = 0; if (isset($advancedparams['assignto_menuitems_selection'])) { $data['assigned'] = $advancedparams['assignto_menuitems_selection']; $empty = empty($advancedparams['assignto_menuitems_selection']); } else { $empty = 1; } if ($advancedparams['assignto_menuitems'] == 1 && $empty) { $data['assignment'] = '-'; } else if ($advancedparams['assignto_menuitems'] == 1) { $data['assignment'] = '1'; } else if ($advancedparams['assignto_menuitems'] == 2 && $empty) { $data['assignment'] = '0'; } else if ($advancedparams['assignto_menuitems'] == 2) { $data['assignment'] = '-1'; } } $assignment = $data['assignment']; $db = $this->getDbo(); $query = $db->getQuery(true) ->delete('#__modules_menu') ->where('moduleid = ' . (int) $table->id); $db->setQuery($query); $db->execute(); // If the assignment is numeric, then something is selected (otherwise it's none). if (is_numeric($assignment)) { // Variable is numeric, but could be a string. $assignment = (int) $assignment; // Logic check: if no module excluded then convert to display on all. if ($assignment == -1 && empty($data['assigned'])) { $assignment = 0; } // Check needed to stop a module being assigned to `All` // and other menu items resulting in a module being displayed twice. if ($assignment === 0) { // Assign new module to `all` menu item associations. $query->clear() ->insert('#__modules_menu') ->columns(array($db->quoteName('moduleid'), $db->quoteName('menuid'))) ->values((int) $table->id . ', 0'); $db->setQuery($query); try { $db->execute(); } catch (RuntimeException $e) { $this->setError($e->getMessage()); return false; } } elseif (!empty($data['assigned'])) { // Get the sign of the number. $sign = $assignment < 0 ? -1 : 1; // Preprocess the assigned array. $inserts = array(); if (!is_array($data['assigned'])) { $data['assigned'] = explode(',', $data['assigned']); } foreach ($data['assigned'] as &$pk) { if(is_numeric($pk)) { $menuid = (int) $pk * $sign; $inserts[(int) $table->id . '-' . $menuid] = (int) $table->id . ',' . $menuid; } } $query->clear() ->insert('#__modules_menu') ->columns(array($db->quoteName('moduleid'), $db->quoteName('menuid'))); foreach($inserts as $insert) { $query->values($insert); } $db->setQuery($query); try { $db->execute(); } catch (RuntimeException $e) { $this->setError($e->getMessage()); return false; } } } // Trigger the onExtensionAfterSave event. $dispatcher->trigger('onExtensionAfterSave', array('com_advancedmodules.module', &$table, $isNew)); // Compute the extension id of this module in case the controller wants it. $query->clear() ->select('extension_id') ->from('#__extensions AS e') ->join('LEFT', '#__modules AS m ON e.element = m.module') ->where('m.id = ' . (int) $table->id); $db->setQuery($query); try { $extensionId = $db->loadResult(); } catch (RuntimeException $e) { JError::raiseWarning(500, $e->getMessage()); return false; } $this->setState('module.extension_id', $extensionId); $this->setState('module.id', $table->id); // Clear modules cache $this->cleanCache(); // Clean module cache parent::cleanCache($table->module, $table->client_id); return true; } /** * Method to save the advanced parameters. * * @param array $data The form data. * * @return boolean True on success. * @since 1.6 */ public function saveAdvancedParams($data, $id = 0) { if (!$id) { $id = JFactory::getApplication()->input->getInt('id'); } if (!$id) { return true; } require_once JPATH_ADMINISTRATOR . '/components/com_advancedmodules/tables/advancedmodules.php'; $table_adv = JTable::getInstance('AdvancedModules', 'AdvancedModulesTable'); $table_adv->moduleid = $id; if ($id && !$table_adv->load($id)) { $db = $table_adv->getDbo(); $db->insertObject($table_adv->getTableName(), $table_adv, $table_adv->getKeyName()); } if (isset($data['rules'])) { $table_adv->_title = $data['title']; $table_adv->setRules($data['rules']); } $registry = new JRegistry; $registry->loadArray($data); $table_adv->params = (string) $registry; // Check the row $table_adv->check(); try { // Store the data. $table_adv->store(); } catch (RuntimeException $e) { JError::raiseWarning(500, $e->getMessage()); return false; } return true; } /** * Method to get and save the module core menu assignments * * @param int $id The module id. * * @return boolean True on success. * @since 1.6 */ public function initAssignments($id, &$module) { if (!$id) { $id = JFactory::getApplication()->input->getInt('id'); } if (empty($id)) { $module->advancedparams = array( 'assignto_menuitems' => $this->config->default_menu_assignment, 'assignto_menuitems_selection' => array() ); } else { if (!isset($module->advancedparams['assignto_menuitems'])) { $db = $this->getDbo(); $query = $db->getQuery(true) ->select('m.menuid') ->from('#__modules_menu as m') ->where('m.moduleid = ' . (int) $id); $db->setQuery($query); $module->advancedparams['assignto_menuitems_selection'] = $db->loadColumn(); $module->advancedparams['assignto_menuitems'] = 0; if (!empty($module->advancedparams['assignto_menuitems_selection'])) { if ($module->advancedparams['assignto_menuitems_selection']['0'] == 0) { $module->advancedparams['assignto_menuitems'] = 0; $module->advancedparams['assignto_menuitems_selection'] = array(); } else if ($module->advancedparams['assignto_menuitems_selection']['0'] < 0) { $module->advancedparams['assignto_menuitems'] = 2; } else { $module->advancedparams['assignto_menuitems'] = 1; } foreach ($module->advancedparams['assignto_menuitems_selection'] as $i => $menuitem) { if ($menuitem < 0) { $module->advancedparams['assignto_menuitems_selection'][$i] = $menuitem * -1; } } } } else if( isset($module->advancedparams['assignto_menuitems_selection']['0']) && strpos($module->advancedparams['assignto_menuitems_selection']['0'], ',') !== false) { $module->advancedparams['assignto_menuitems_selection'] = explode(',', $module->advancedparams['assignto_menuitems_selection']['0']); } if (!isset($module->advancedparams['assignto_date']) || !$module->advancedparams['assignto_date']) { if ((isset($module->publish_up) && (int) $module->publish_up) || (isset($module->publish_down) && (int) $module->publish_down) ) { $module->advancedparams['assignto_date'] = 1; $module->advancedparams['assignto_date_publish_up'] = isset($module->publish_up) ? $module->publish_up : ''; $module->advancedparams['assignto_date_publish_down'] = isset($module->publish_down) ? $module->publish_down : ''; } } if (!isset($module->advancedparams['assignto_languages']) || !$module->advancedparams['assignto_languages']) { if (isset($module->language) && $module->language && $module->language != '*') { $module->advancedparams['assignto_languages'] = 1; $module->advancedparams['assignto_languages_selection'] = array($module->language); } } } AdvancedModulesModelModule::saveAdvancedParams($module->advancedparams, $id); return $module->advancedparams; } /** * A protected method to get a set of ordering conditions. * * @param object $table A record object. * * @return array An array of conditions to add to add to ordering queries. * * @since 1.6 */ protected function getReorderConditions($table) { $condition = array(); $condition[] = 'client_id = ' . (int) $table->client_id; $condition[] = 'position = ' . $this->_db->quote($table->position); return $condition; } /** * Custom clean cache method for different clients * * @param string $group The name of the plugin group to import (defaults to null). * @param integer $client_id The client ID. [optional] * * @return void * * @since 1.6 */ protected function cleanCache($group = null, $client_id = 0) { parent::cleanCache('com_advancedmodules', $this->getClient()); } /** * Method to test whether a record can be deleted. * * @param object $record A record object. * * @return boolean True if allowed to delete the record. Defaults to the permission set in the component. */ protected function canDelete($record) { if (!empty($record->id)) { if ($record->state != -2) { return; } $user = JFactory::getUser(); return $user->authorise('core.delete', 'com_advancedmodules.module.' . (int) $record->id); } } /** * Method to test whether a record can have its state edited. * * @param object $record A record object. * * @return boolean True if allowed to change the state of the record. Defaults to the permission set in the component. */ protected function canEditState($record) { $user = JFactory::getUser(); // Check for existing module. if (!empty($record->id)) { return $user->authorise('core.edit.state', 'com_advancedmodules.module.' . (int) $record->id); } // Default to component settings if neither article nor category known. else { return parent::canEditState('com_advancedmodules'); } } /** * Method override to check if you can edit an existing record. * * @param array $data An array of input data. * @param string $key The name of the key for the primary key. * * @return boolean */ protected function allowEdit($data = array(), $key = 'id') { // Initialise variables. $recordId = (int) isset($data[$key]) ? $data[$key] : 0; $user = JFactory::getUser(); $userId = $user->get('id'); // Check general edit permission first. if ($user->authorise('core.edit', 'com_advancedmodules.module.' . $recordId)) { return true; } // Since there is no asset tracking, revert to the component permissions. return parent::allowEdit($data, $key); } /** * Function that gets the config settings * * @return Object */ protected function getConfig() { if (!isset($this->config)) { require_once JPATH_PLUGINS . '/system/nnframework/helpers/parameters.php'; $parameters = NNParameters::getInstance(); $this->config = $parameters->getComponentParams('advancedmodules'); } return $this->config; } }
adrian2020my/vichi
administrator/components/com_advancedmodules/models/module.php
PHP
gpl-2.0
40,561
[ 30522, 30524, 17953, 1028, 1008, 1030, 4957, 8299, 1024, 1013, 1013, 7479, 1012, 2512, 29440, 1012, 17953, 1008, 1030, 9385, 9385, 1075, 2297, 2512, 29440, 2035, 2916, 9235, 1008, 1030, 6105, 8299, 1024, 1013, 1013, 7479, 1012, 27004, 1012,...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
package main.java.de.c4.model.messages.file; public class FileTransferAnswer { public long id; public boolean accepted = false; public int serverPort; public FileTransferAnswer() { } }
desperateCoder/FileTo
src/main/java/de/c4/model/messages/file/FileTransferAnswer.java
Java
mit
195
[ 30522, 7427, 2364, 1012, 9262, 1012, 2139, 1012, 1039, 2549, 1012, 2944, 30524, 13777, 1063, 2270, 2146, 8909, 1025, 2270, 22017, 20898, 3970, 1027, 6270, 1025, 2270, 20014, 8241, 6442, 1025, 2270, 5371, 6494, 3619, 27709, 3619, 13777, 1006...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* Copyright (c) 2019, 2022 Dennis Wölfing * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ /* libc/src/stdio/__file_write.c * Write data to a file. (called from C89) */ #define write __write #include <unistd.h> #include "FILE.h" size_t __file_write(FILE* file, const unsigned char* p, size_t size) { size_t written = 0; while (written < size) { ssize_t result = write(file->fd, p, size - written); if (result < 0) { file->flags |= FILE_FLAG_ERROR; return written; } written += result; p += result; } return written; }
dennis95/dennix
libc/src/stdio/__file_write.c
C
isc
1,293
[ 30522, 1013, 1008, 9385, 1006, 1039, 1007, 10476, 1010, 16798, 2475, 6877, 4702, 2075, 1008, 1008, 6656, 2000, 2224, 1010, 6100, 1010, 19933, 1010, 1998, 1013, 2030, 16062, 2023, 4007, 2005, 2151, 1008, 3800, 2007, 2030, 2302, 7408, 2003, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
#include <QtGui> #include "btglobal.h" #include "btqlistdelegate.h" //#include <QMetaType> btQListDeletgate::btQListDeletgate(QObject *parent) : QItemDelegate(parent) { } QWidget *btQListDeletgate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const { //qRegisterMetaType<btChildWeights>("btChildWeights"); //qRegisterMetaType<btParallelConditions>("btParallelConditions"); QComboBox *comboBox = new QComboBox(parent); comboBox->addItem("int", QVariant("int")); comboBox->addItem("QString", QVariant("QString")); comboBox->addItem("double", QVariant("double")); comboBox->addItem("QVariantList", QVariant("QVariantList")); //comboBox->addItem("btChildWeights", QVariant("btChildWeights")); comboBox->setCurrentIndex(comboBox->findData(index.data())); return comboBox; } void btQListDeletgate::setEditorData(QWidget *editor, const QModelIndex &index) const { QString value = index.model()->data(index, Qt::EditRole).toString(); QComboBox *comboBox = static_cast<QComboBox*>(editor); comboBox->setCurrentIndex(comboBox->findText(value));//comboBox->findData(value)); } void btQListDeletgate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const { QComboBox *comboBox = static_cast<QComboBox*>(editor); QString value = comboBox->currentText(); model->setData(index, value, Qt::EditRole); } void btQListDeletgate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &/* index */) const { editor->setGeometry(option.rect); } #include "btqlistdelegate.moc"
pranavrc/gluon
smarts/editor/btqlistdelegate.cpp
C++
lgpl-2.1
1,655
[ 30522, 1001, 2421, 1026, 1053, 2102, 25698, 1028, 1001, 2421, 1000, 18411, 23296, 16429, 2389, 1012, 1044, 1000, 1001, 2421, 1000, 18411, 4160, 9863, 9247, 29107, 2618, 1012, 1044, 1000, 1013, 1013, 1001, 2421, 1026, 1053, 11368, 4017, 1886...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
// 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 System.Collections.Immutable; using System.Composition; using System.Threading; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.CSharp.Completion.Providers; using Microsoft.CodeAnalysis.CSharp.Completion.SuggestionMode; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Completion { [ExportLanguageServiceFactory(typeof(CompletionService), LanguageNames.CSharp), Shared] internal class CSharpCompletionServiceFactory : ILanguageServiceFactory { public ILanguageService CreateLanguageService(HostLanguageServices languageServices) { return new CSharpCompletionService(languageServices.WorkspaceServices.Workspace); } } internal class CSharpCompletionService : CommonCompletionService { private readonly ImmutableArray<CompletionProvider> _defaultCompletionProviders = ImmutableArray.Create<CompletionProvider>( new AttributeNamedParameterCompletionProvider(), new NamedParameterCompletionProvider(), new KeywordCompletionProvider(), new SymbolCompletionProvider(), new ExplicitInterfaceCompletionProvider(), new ObjectCreationCompletionProvider(), new ObjectInitializerCompletionProvider(), new SpeculativeTCompletionProvider(), new CSharpSuggestionModeCompletionProvider(), new EnumAndCompletionListTagCompletionProvider(), new CrefCompletionProvider(), new SnippetCompletionProvider(), new ExternAliasCompletionProvider(), new OverrideCompletionProvider(), new PartialMethodCompletionProvider(), new PartialTypeCompletionProvider(), new XmlDocCommentCompletionProvider(), new TupleNameCompletionProvider() ); private readonly Workspace _workspace; public CSharpCompletionService( Workspace workspace, ImmutableArray<CompletionProvider>? exclusiveProviders = null) : base(workspace, exclusiveProviders) { _workspace = workspace; } public override string Language => LanguageNames.CSharp; protected override ImmutableArray<CompletionProvider> GetBuiltInProviders() { return _defaultCompletionProviders; } public override TextSpan GetDefaultCompletionListSpan(SourceText text, int caretPosition) { return CompletionUtilities.GetCompletionItemSpan(text, caretPosition); } private CompletionRules _latestRules = CompletionRules.Default; public override CompletionRules GetRules() { var options = _workspace.Options; var enterRule = options.GetOption(CompletionOptions.EnterKeyBehavior, LanguageNames.CSharp); var snippetRule = options.GetOption(CompletionOptions.SnippetsBehavior, LanguageNames.CSharp); // Although EnterKeyBehavior is a per-language setting, the meaning of an unset setting (Default) differs between C# and VB // In C# the default means Never to maintain previous behavior if (enterRule == EnterKeyRule.Default) { enterRule = EnterKeyRule.Never; } if (snippetRule == SnippetsRule.Default) { snippetRule = SnippetsRule.AlwaysInclude; } // use interlocked + stored rules to reduce # of times this gets created when option is different than default var newRules = _latestRules.WithDefaultEnterKeyRule(enterRule) .WithSnippetsRule(snippetRule); Interlocked.Exchange(ref _latestRules, newRules); return newRules; } } }
weltkante/roslyn
src/Features/CSharp/Portable/Completion/CSharpCompletionService.cs
C#
apache-2.0
4,146
[ 30522, 1013, 1013, 9385, 1006, 1039, 1007, 7513, 1012, 2035, 2916, 9235, 1012, 7000, 2104, 1996, 15895, 6105, 1010, 2544, 1016, 1012, 1014, 1012, 2156, 6105, 1012, 19067, 2102, 1999, 1996, 2622, 7117, 2005, 6105, 2592, 1012, 2478, 2291, 1...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
h1{ text-align: center; } main{ width: 50%; margin: 0 auto; } .question-wrapper{ width: 100%; overflow: auto; } .question{ width: 100%; } .square{ width:80px; height:80px; margin:20px; border-radius:50%; border: 2px solid rgb(40,40,40); float:left; } .red{ /*background-color:rgb(250,0,0);*/ } .blue{ /*background-color:rgb(0,0,250);*/ } #gform input{ display: none; } #gform button{ width: 300px; height: 60px; background-color: #fff; border: 2px solid rgb(40,40,40); }
fairesy/fairesy.github.io
projects/prismof/handmaiden.css
CSS
mit
509
[ 30522, 1044, 2487, 1063, 3793, 1011, 25705, 1024, 2415, 1025, 1065, 2364, 1063, 9381, 1024, 2753, 1003, 1025, 7785, 1024, 1014, 8285, 1025, 1065, 1012, 3160, 1011, 10236, 4842, 1063, 9381, 1024, 2531, 1003, 1025, 2058, 12314, 1024, 8285, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* * Copyright (C) 2016 The Android Open Source Project * * 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 android.content.pm.cts.shortcut.backup.launcher3; import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.list; import android.content.pm.cts.shortcut.device.common.ShortcutManagerDeviceTestBase; import android.test.suitebuilder.annotation.SmallTest; @SmallTest public class ShortcutManagerPreBackupTest extends ShortcutManagerDeviceTestBase { static final String PUBLISHER1_PKG = "android.content.pm.cts.shortcut.backup.publisher1"; static final String PUBLISHER2_PKG = "android.content.pm.cts.shortcut.backup.publisher2"; static final String PUBLISHER3_PKG = "android.content.pm.cts.shortcut.backup.publisher3"; @Override protected void setUp() throws Exception { super.setUp(); setAsDefaultLauncher(MainActivity.class); } public void testPreBackup() { getLauncherApps().pinShortcuts(PUBLISHER1_PKG, list("s3", "ms1", "ms2"), getUserHandle()); getLauncherApps().pinShortcuts(PUBLISHER2_PKG, list("s1", "s3", "ms2"), getUserHandle()); getLauncherApps().pinShortcuts(PUBLISHER3_PKG, list("s1", "s3", "ms1"), getUserHandle()); } }
wiki2014/Learning-Summary
alps/cts/hostsidetests/shortcuts/deviceside/backup/launcher3/src/android/content/pm/cts/shortcut/backup/launcher3/ShortcutManagerPreBackupTest.java
Java
gpl-3.0
1,813
[ 30522, 1013, 1008, 1008, 9385, 1006, 1039, 1007, 2355, 1996, 11924, 2330, 3120, 2622, 1008, 1008, 7000, 2104, 1996, 15895, 6105, 1010, 2544, 1016, 1012, 1014, 1006, 1996, 1000, 6105, 1000, 1007, 1025, 1008, 2017, 2089, 2025, 2224, 2023, 5...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<?php /** * File containing the eZContentOperationCollection 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 kernel */ /*! \class eZContentOperationCollection ezcontentoperationcollection.php \brief The class eZContentOperationCollection does */ class eZContentOperationCollection { /** * Use by {@see beginTransaction()} and {@see commitTransaction()} to handle nested publish operations */ private static $operationsStack = 0; static public function readNode( $nodeID ) { } static public function readObject( $nodeID, $userID, $languageCode ) { if ( $languageCode != '' ) { $node = eZContentObjectTreeNode::fetch( $nodeID, $languageCode ); } else { $node = eZContentObjectTreeNode::fetch( $nodeID ); } if ( $node === null ) // return $Module->handleError( eZError::KERNEL_NOT_AVAILABLE, 'kernel' ); return false; $object = $node->attribute( 'object' ); if ( $object === null ) // return $Module->handleError( eZError::KERNEL_ACCESS_DENIED, 'kernel' ); { return false; } /* if ( !$object->attribute( 'can_read' ) ) { // return $Module->handleError( eZError::KERNEL_ACCESS_DENIED, 'kernel' ); return false; } */ return array( 'status' => true, 'object' => $object, 'node' => $node ); } static public function loopNodes( $nodeID ) { return array( 'parameters' => array( array( 'parent_node_id' => 3 ), array( 'parent_node_id' => 5 ), array( 'parent_node_id' => 12 ) ) ); } static public function loopNodeAssignment( $objectID, $versionNum ) { $object = eZContentObject::fetch( $objectID ); $version = $object->version( $versionNum ); $nodeAssignmentList = $version->attribute( 'node_assignments' ); $parameters = array(); foreach ( $nodeAssignmentList as $nodeAssignment ) { if ( $nodeAssignment->attribute( 'parent_node' ) > 0 ) { if ( $nodeAssignment->attribute( 'is_main' ) == 1 ) { $mainNodeID = self::publishNode( $nodeAssignment->attribute( 'parent_node' ), $objectID, $versionNum, false ); } else { $parameters[] = array( 'parent_node_id' => $nodeAssignment->attribute( 'parent_node' ) ); } } } for ( $i = 0; $i < count( $parameters ); $i++ ) { $parameters[$i]['main_node_id'] = $mainNodeID; } return array( 'parameters' => $parameters ); } function publishObjectExtensionHandler( $contentObjectID, $contentObjectVersion ) { eZContentObjectEditHandler::executePublish( $contentObjectID, $contentObjectVersion ); } /** * Starts a database transaction. */ static public function beginTransaction() { // We only start a transaction if another content publish operation hasn't been started if ( ++self::$operationsStack === 1 ) { eZDB::instance()->begin(); } } /** * Commit a previously started database transaction. */ static public function commitTransaction() { if ( --self::$operationsStack === 0 ) { eZDB::instance()->commit(); } } static public function setVersionStatus( $objectID, $versionNum, $status ) { $object = eZContentObject::fetch( $objectID ); if ( !$versionNum ) { $versionNum = $object->attribute( 'current_version' ); } $version = $object->version( $versionNum ); if ( !$version ) return; $version->setAttribute( 'status', $status ); $version->store(); } static public function setObjectStatusPublished( $objectID, $versionNum ) { $object = eZContentObject::fetch( $objectID ); $version = $object->version( $versionNum ); $db = eZDB::instance(); $db->begin(); $object->setAttribute( 'status', eZContentObject::STATUS_PUBLISHED ); $version->setAttribute( 'status', eZContentObjectVersion::STATUS_PUBLISHED ); $object->setAttribute( 'current_version', $versionNum ); $objectIsAlwaysAvailable = $object->isAlwaysAvailable(); $object->setAttribute( 'language_mask', eZContentLanguage::maskByLocale( $version->translationList( false, false ), $objectIsAlwaysAvailable ) ); if ( $object->attribute( 'published' ) == 0 ) { $object->setAttribute( 'published', time() ); } $object->setAttribute( 'modified', time() ); $classID = $object->attribute( 'contentclass_id' ); $class = eZContentClass::fetch( $classID ); $objectName = $class->contentObjectName( $object ); $object->setName( $objectName, $versionNum ); $existingTranslations = $version->translations( false ); foreach( $existingTranslations as $translation ) { $translatedName = $class->contentObjectName( $object, $versionNum, $translation ); $object->setName( $translatedName, $versionNum, $translation ); } if ( $objectIsAlwaysAvailable ) { $initialLanguageID = $object->attribute( 'initial_language_id' ); $object->setAlwaysAvailableLanguageID( $initialLanguageID ); } $version->store(); $object->store(); eZContentObjectTreeNode::setVersionByObjectID( $objectID, $versionNum ); $nodes = $object->assignedNodes(); foreach ( $nodes as $node ) { $node->setName( $object->attribute( 'name' ) ); $node->updateSubTreePath(); } $db->commit(); /* Check if current class is the user class, and if so, clean up the user-policy cache */ if ( in_array( $classID, eZUser::contentClassIDs() ) ) { eZUser::purgeUserCacheByUserId( $object->attribute( 'id' ) ); } } static public function attributePublishAction( $objectID, $versionNum ) { $object = eZContentObject::fetch( $objectID ); $nodes = $object->assignedNodes(); $version = $object->version( $versionNum ); $contentObjectAttributes = $object->contentObjectAttributes( true, $versionNum, $version->initialLanguageCode(), false ); foreach ( $contentObjectAttributes as $contentObjectAttribute ) { $contentObjectAttribute->onPublish( $object, $nodes ); } } /*! \static Generates the related viewcaches (PreGeneration) for the content object. It will only do this if [ContentSettings]/PreViewCache in site.ini is enabled. \param $objectID The ID of the content object to generate caches for. */ static public function generateObjectViewCache( $objectID ) { eZContentCacheManager::generateObjectViewCache( $objectID ); } /*! \static Clears the related viewcaches for the content object using the smart viewcache system. \param $objectID The ID of the content object to clear caches for \param $versionNum The version of the object to use or \c true for current version \param $additionalNodeList An array with node IDs to add to clear list, or \c false for no additional nodes. */ static public function clearObjectViewCache( $objectID, $versionNum = true, $additionalNodeList = false ) { eZContentCacheManager::clearContentCacheIfNeeded( $objectID, $versionNum, $additionalNodeList ); } static public function publishNode( $parentNodeID, $objectID, $versionNum, $mainNodeID ) { $object = eZContentObject::fetch( $objectID ); $nodeAssignment = eZNodeAssignment::fetch( $objectID, $versionNum, $parentNodeID ); $version = $object->version( $versionNum ); $fromNodeID = $nodeAssignment->attribute( 'from_node_id' ); $originalObjectID = $nodeAssignment->attribute( 'contentobject_id' ); $nodeID = $nodeAssignment->attribute( 'parent_node' ); $opCode = $nodeAssignment->attribute( 'op_code' ); $parentNode = eZContentObjectTreeNode::fetch( $nodeID ); // if parent doesn't exist, return. See issue #18320 if ( !$parentNode instanceof eZContentObjectTreeNode ) { eZDebug::writeError( "Parent node doesn't exist. object id: $objectID, node_assignment id: " . $nodeAssignment->attribute( 'id' ), __METHOD__ ); return; } $parentNodeID = $parentNode->attribute( 'node_id' ); $existingNode = null; $db = eZDB::instance(); $db->begin(); if ( strlen( $nodeAssignment->attribute( 'parent_remote_id' ) ) > 0 ) { $existingNode = eZContentObjectTreeNode::fetchByRemoteID( $nodeAssignment->attribute( 'parent_remote_id' ) ); } if ( !$existingNode ); { $existingNode = eZContentObjectTreeNode::findNode( $nodeID , $object->attribute( 'id' ), true ); } $updateSectionID = false; // now we check the op_code to see what to do if ( ( $opCode & 1 ) == eZNodeAssignment::OP_CODE_NOP ) { // There is nothing to do so just return $db->commit(); if ( $mainNodeID == false ) { return $object->attribute( 'main_node_id' ); } return; } $updateFields = false; if ( $opCode == eZNodeAssignment::OP_CODE_MOVE || $opCode == eZNodeAssignment::OP_CODE_CREATE ) { // if ( $fromNodeID == 0 || $fromNodeID == -1) if ( $opCode == eZNodeAssignment::OP_CODE_CREATE || $opCode == eZNodeAssignment::OP_CODE_SET ) { // If the node already exists it means we have a conflict (for 'CREATE'). // We resolve this by leaving node-assignment data be. if ( $existingNode == null ) { $parentNode = eZContentObjectTreeNode::fetch( $nodeID ); $user = eZUser::currentUser(); if ( !eZSys::isShellExecution() and !$user->isAnonymous() ) { eZContentBrowseRecent::createNew( $user->id(), $parentNode->attribute( 'node_id' ), $parentNode->attribute( 'name' ) ); } $updateFields = true; $existingNode = $parentNode->addChild( $object->attribute( 'id' ), true ); if ( $fromNodeID == -1 ) { $updateSectionID = true; } } elseif ( $opCode == eZNodeAssignment::OP_CODE_SET ) { $updateFields = true; } } elseif ( $opCode == eZNodeAssignment::OP_CODE_MOVE ) { if ( $fromNodeID == 0 || $fromNodeID == -1 ) { eZDebug::writeError( "NodeAssignment '" . $nodeAssignment->attribute( 'id' ) . "' is marked with op_code='$opCode' but has no data in from_node_id. Cannot use it for moving node.", __METHOD__ ); } else { // clear cache for old placement. $additionalNodeIDList = array( $fromNodeID ); eZContentCacheManager::clearContentCacheIfNeeded( $objectID, $versionNum, $additionalNodeIDList ); $originalNode = eZContentObjectTreeNode::fetchNode( $originalObjectID, $fromNodeID ); if ( $originalNode->attribute( 'main_node_id' ) == $originalNode->attribute( 'node_id' ) ) { $updateSectionID = true; } $originalNode->move( $parentNodeID ); $existingNode = eZContentObjectTreeNode::fetchNode( $originalObjectID, $parentNodeID ); $updateFields = true; } } } elseif ( $opCode == eZNodeAssignment::OP_CODE_REMOVE ) { $db->commit(); return; } if ( $updateFields ) { if ( strlen( $nodeAssignment->attribute( 'parent_remote_id' ) ) > 0 ) { $existingNode->setAttribute( 'remote_id', $nodeAssignment->attribute( 'parent_remote_id' ) ); } if ( $nodeAssignment->attribute( 'is_hidden' ) ) { $existingNode->setAttribute( 'is_hidden', 1 ); $existingNode->setAttribute( 'is_invisible', 1 ); } $existingNode->setAttribute( 'priority', $nodeAssignment->attribute( 'priority' ) ); $existingNode->setAttribute( 'sort_field', $nodeAssignment->attribute( 'sort_field' ) ); $existingNode->setAttribute( 'sort_order', $nodeAssignment->attribute( 'sort_order' ) ); } $existingNode->setAttribute( 'contentobject_is_published', 1 ); eZDebug::createAccumulatorGroup( 'nice_urls_total', 'Nice urls' ); if ( $mainNodeID > 0 ) { $existingNodeID = $existingNode->attribute( 'node_id' ); if ( $existingNodeID != $mainNodeID ) { eZContentBrowseRecent::updateNodeID( $existingNodeID, $mainNodeID ); } $existingNode->setAttribute( 'main_node_id', $mainNodeID ); } else { $existingNode->setAttribute( 'main_node_id', $existingNode->attribute( 'node_id' ) ); } $existingNode->store(); if ( $updateSectionID ) { eZContentOperationCollection::updateSectionID( $objectID, $versionNum ); } $db->commit(); if ( $mainNodeID == false ) { return $existingNode->attribute( 'node_id' ); } } static public function updateSectionID( $objectID, $versionNum ) { $object = eZContentObject::fetch( $objectID ); $version = $object->version( $versionNum ); if ( $versionNum == 1 or $object->attribute( 'current_version' ) == $versionNum ) { $newMainAssignment = null; $newMainAssignments = eZNodeAssignment::fetchForObject( $objectID, $versionNum, 1 ); if ( isset( $newMainAssignments[0] ) ) { $newMainAssignment = $newMainAssignments[0]; } // we should not update section id for toplevel nodes if ( $newMainAssignment && $newMainAssignment->attribute( 'parent_node' ) != 1 ) { // We should check if current object already has been updated for section_id // If yes we should not update object section_id by $parentNodeSectionID $sectionID = $object->attribute( 'section_id' ); if ( $sectionID > 0 ) return; $newParentObject = $newMainAssignment->getParentObject(); if ( !$newParentObject ) { return array( 'status' => eZModuleOperationInfo::STATUS_CANCELLED ); } $parentNodeSectionID = $newParentObject->attribute( 'section_id' ); $object->setAttribute( 'section_id', $parentNodeSectionID ); $object->store(); } return; } $newMainAssignmentList = eZNodeAssignment::fetchForObject( $objectID, $versionNum, 1 ); $newMainAssignment = ( count( $newMainAssignmentList ) ) ? array_pop( $newMainAssignmentList ) : null; $currentVersion = $object->attribute( 'current' ); // Here we need to fetch published nodes and not old node assignments. $oldMainNode = $object->mainNode(); if ( $newMainAssignment && $oldMainNode && $newMainAssignment->attribute( 'parent_node' ) != $oldMainNode->attribute( 'parent_node_id' ) ) { $oldMainParentNode = $oldMainNode->attribute( 'parent' ); if ( $oldMainParentNode ) { $oldParentObject = $oldMainParentNode->attribute( 'object' ); $oldParentObjectSectionID = $oldParentObject->attribute( 'section_id' ); if ( $oldParentObjectSectionID == $object->attribute( 'section_id' ) ) { $newParentNode = $newMainAssignment->attribute( 'parent_node_obj' ); if ( !$newParentNode ) return; $newParentObject = $newParentNode->attribute( 'object' ); if ( !$newParentObject ) return; $newSectionID = $newParentObject->attribute( 'section_id' ); if ( $newSectionID != $object->attribute( 'section_id' ) ) { $oldSectionID = $object->attribute( 'section_id' ); $object->setAttribute( 'section_id', $newSectionID ); $db = eZDB::instance(); $db->begin(); $object->store(); $mainNodeID = $object->attribute( 'main_node_id' ); if ( $mainNodeID > 0 ) { eZContentObjectTreeNode::assignSectionToSubTree( $mainNodeID, $newSectionID, $oldSectionID ); } $db->commit(); } } } } } static public function removeOldNodes( $objectID, $versionNum ) { $object = eZContentObject::fetch( $objectID ); if ( !$object instanceof eZContentObject ) { eZDebug::writeError( 'Unable to find object #' . $objectID, __METHOD__ ); return; } $version = $object->version( $versionNum ); if ( !$version instanceof eZContentObjectVersion ) { eZDebug::writeError( 'Unable to find version #' . $versionNum . ' for object #' . $objectID, __METHOD__ ); return; } $moveToTrash = true; $assignedExistingNodes = $object->attribute( 'assigned_nodes' ); $curentVersionNodeAssignments = $version->attribute( 'node_assignments' ); $removeParentNodeList = array(); $removeAssignmentsList = array(); foreach ( $curentVersionNodeAssignments as $nodeAssignment ) { $nodeAssignmentOpcode = $nodeAssignment->attribute( 'op_code' ); if ( $nodeAssignmentOpcode == eZNodeAssignment::OP_CODE_REMOVE || $nodeAssignmentOpcode == eZNodeAssignment::OP_CODE_REMOVE_NOP ) { $removeAssignmentsList[] = $nodeAssignment->attribute( 'id' ); if ( $nodeAssignmentOpcode == eZNodeAssignment::OP_CODE_REMOVE ) { $removeParentNodeList[] = $nodeAssignment->attribute( 'parent_node' ); } } } $db = eZDB::instance(); $db->begin(); foreach ( $assignedExistingNodes as $node ) { if ( in_array( $node->attribute( 'parent_node_id' ), $removeParentNodeList ) ) { eZContentObjectTreeNode::removeSubtrees( array( $node->attribute( 'node_id' ) ), $moveToTrash ); } } if ( count( $removeAssignmentsList ) > 0 ) { eZNodeAssignment::purgeByID( $removeAssignmentsList ); } $db->commit(); } // New function which resets the op_code field when the object is published. static public function resetNodeassignmentOpcodes( $objectID, $versionNum ) { $object = eZContentObject::fetch( $objectID ); $version = $object->version( $versionNum ); $nodeAssignments = $version->attribute( 'node_assignments' ); foreach ( $nodeAssignments as $nodeAssignment ) { if ( ( $nodeAssignment->attribute( 'op_code' ) & 1 ) == eZNodeAssignment::OP_CODE_EXECUTE ) { $nodeAssignment->setAttribute( 'op_code', ( $nodeAssignment->attribute( 'op_code' ) & ~1 ) ); $nodeAssignment->store(); } } } /** * Registers the object in search engine. * * @note Transaction unsafe. If you call several transaction unsafe methods you must enclose * the calls within a db transaction; thus within db->begin and db->commit. * * @param int $objectID Id of the object. * @param int $version Operation collection passes this default param. Not used in the method * @param bool $isMoved true if node is being moved */ static public function registerSearchObject( $objectID, $version = null, $isMoved = false ) { $objectID = (int)$objectID; eZDebug::createAccumulatorGroup( 'search_total', 'Search Total' ); $ini = eZINI::instance( 'site.ini' ); $insertPendingAction = false; $object = null; switch ( $ini->variable( 'SearchSettings', 'DelayedIndexing' ) ) { case 'enabled': $insertPendingAction = true; break; case 'classbased': $classList = $ini->variable( 'SearchSettings', 'DelayedIndexingClassList' ); $object = eZContentObject::fetch( $objectID ); if ( is_array( $classList ) && in_array( $object->attribute( 'class_identifier' ), $classList ) ) { $insertPendingAction = true; } } if ( $insertPendingAction ) { $action = $isMoved ? 'index_moved_node' : 'index_object'; eZDB::instance()->query( "INSERT INTO ezpending_actions( action, param ) VALUES ( '$action', '$objectID' )" ); return; } if ( $object === null ) $object = eZContentObject::fetch( $objectID ); // Register the object in the search engine. $needCommit = eZSearch::needCommit(); if ( eZSearch::needRemoveWithUpdate() ) { eZDebug::accumulatorStart( 'remove_object', 'search_total', 'remove object' ); eZSearch::removeObjectById( $objectID ); eZDebug::accumulatorStop( 'remove_object' ); } eZDebug::accumulatorStart( 'add_object', 'search_total', 'add object' ); if ( !eZSearch::addObject( $object, $needCommit ) ) { eZDebug::writeError( "Failed adding object ID {$object->attribute( 'id' )} in the search engine", __METHOD__ ); } eZDebug::accumulatorStop( 'add_object' ); } /*! \note Transaction unsafe. If you call several transaction unsafe methods you must enclose the calls within a db transaction; thus within db->begin and db->commit. */ static public function createNotificationEvent( $objectID, $versionNum ) { $event = eZNotificationEvent::create( 'ezpublish', array( 'object' => $objectID, 'version' => $versionNum ) ); $event->store(); } /*! Copies missing translations from published version to the draft. */ static public function copyTranslations( $objectID, $versionNum ) { $object = eZContentObject::fetch( $objectID ); if ( !$object instanceof eZContentObject ) { return array( 'status' => eZModuleOperationInfo::STATUS_CANCELLED ); } $publishedVersionNum = $object->attribute( 'current_version' ); if ( !$publishedVersionNum ) { return; } $publishedVersion = $object->version( $publishedVersionNum ); $publishedVersionTranslations = $publishedVersion->translations(); $publishedLanguages = eZContentLanguage::languagesByMask( $object->attribute( 'language_mask' ) ); $publishedLanguageCodes = array_keys( $publishedLanguages ); $version = $object->version( $versionNum ); $versionTranslationList = array_keys( eZContentLanguage::languagesByMask( $version->attribute( 'language_mask' ) ) ); foreach ( $publishedVersionTranslations as $translation ) { $translationLanguageCode = $translation->attribute( 'language_code' ); if ( in_array( $translationLanguageCode, $versionTranslationList ) || !in_array( $translationLanguageCode, $publishedLanguageCodes ) ) { continue; } foreach ( $translation->objectAttributes() as $attribute ) { $clonedAttribute = $attribute->cloneContentObjectAttribute( $versionNum, $publishedVersionNum, $objectID ); $clonedAttribute->sync(); } } $version->updateLanguageMask(); } /*! Updates non-translatable attributes. */ static public function updateNontranslatableAttributes( $objectID, $versionNum ) { $object = eZContentObject::fetch( $objectID ); $version = $object->version( $versionNum ); $nonTranslatableAttributes = $version->nonTranslatableAttributesToUpdate(); if ( $nonTranslatableAttributes ) { $attributes = $version->contentObjectAttributes( $version->initialLanguageCode() ); $attributeByClassAttrID = array(); foreach ( $attributes as $attribute ) { $attributeByClassAttrID[$attribute->attribute( 'contentclassattribute_id' )] = $attribute; } foreach ( $nonTranslatableAttributes as $attributeToUpdate ) { $originalAttribute =& $attributeByClassAttrID[$attributeToUpdate->attribute( 'contentclassattribute_id' )]; if ( $originalAttribute ) { unset( $tmp ); $tmp = $attributeToUpdate; $tmp->initialize( $attributeToUpdate->attribute( 'version' ), $originalAttribute ); $tmp->setAttribute( 'id', $attributeToUpdate->attribute( 'id' ) ); $tmp->setAttribute( 'language_code', $attributeToUpdate->attribute( 'language_code' ) ); $tmp->setAttribute( 'language_id', $attributeToUpdate->attribute( 'language_id' ) ); $tmp->setAttribute( 'attribute_original_id', $originalAttribute->attribute( 'id' ) ); $tmp->store(); $tmp->postInitialize( $attributeToUpdate->attribute( 'version' ), $originalAttribute ); } } } } static public function removeTemporaryDrafts( $objectID, $versionNum ) { $object = eZContentObject::fetch( $objectID ); $object->cleanupInternalDrafts( eZUser::currentUserID() ); } /** * Moves a node * * @param int $nodeID * @param int $objectID * @param int $newParentNodeID * * @return array An array with operation status, always true */ static public function moveNode( $nodeID, $objectID, $newParentNodeID ) { if( !eZContentObjectTreeNodeOperations::move( $nodeID, $newParentNodeID ) ) { eZDebug::writeError( "Failed to move node $nodeID as child of parent node $newParentNodeID", __METHOD__ ); return array( 'status' => false ); } eZContentObject::fixReverseRelations( $objectID, 'move' ); if ( !eZSearch::getEngine() instanceof eZSearchEngine ) { eZContentOperationCollection::registerSearchObject( $objectID ); } return array( 'status' => true ); } /** * Adds a new nodeAssignment * * @param int $nodeID * @param int $objectId * @param array $selectedNodeIDArray * * @return array An array with operation status, always true */ static public function addAssignment( $nodeID, $objectID, $selectedNodeIDArray ) { $userClassIDArray = eZUser::contentClassIDs(); $object = eZContentObject::fetch( $objectID ); $class = $object->contentClass(); $nodeAssignmentList = eZNodeAssignment::fetchForObject( $objectID, $object->attribute( 'current_version' ), 0, false ); $assignedNodes = $object->assignedNodes(); $parentNodeIDArray = array(); foreach ( $assignedNodes as $assignedNode ) { $append = false; foreach ( $nodeAssignmentList as $nodeAssignment ) { if ( $nodeAssignment['parent_node'] == $assignedNode->attribute( 'parent_node_id' ) ) { $append = true; break; } } if ( $append ) { $parentNodeIDArray[] = $assignedNode->attribute( 'parent_node_id' ); } } $db = eZDB::instance(); $db->begin(); $locationAdded = false; $node = eZContentObjectTreeNode::fetch( $nodeID ); foreach ( $selectedNodeIDArray as $selectedNodeID ) { if ( !in_array( $selectedNodeID, $parentNodeIDArray ) ) { $parentNode = eZContentObjectTreeNode::fetch( $selectedNodeID ); $parentNodeObject = $parentNode->attribute( 'object' ); $canCreate = ( ( $parentNode->checkAccess( 'create', $class->attribute( 'id' ), $parentNodeObject->attribute( 'contentclass_id' ) ) == 1 ) || ( $parentNode->canAddLocation() && $node->canRead() ) ); if ( $canCreate ) { $insertedNode = $object->addLocation( $selectedNodeID, true ); // Now set is as published and fix main_node_id $insertedNode->setAttribute( 'contentobject_is_published', 1 ); $insertedNode->setAttribute( 'main_node_id', $node->attribute( 'main_node_id' ) ); $insertedNode->setAttribute( 'contentobject_version', $node->attribute( 'contentobject_version' ) ); // Make sure the url alias is set updated. $insertedNode->updateSubTreePath(); $insertedNode->sync(); $locationAdded = true; } } } if ( $locationAdded ) { //call appropriate method from search engine eZSearch::addNodeAssignment( $nodeID, $objectID, $selectedNodeIDArray ); // clear user policy cache if this was a user object if ( in_array( $object->attribute( 'contentclass_id' ), $userClassIDArray ) ) { eZUser::purgeUserCacheByUserId( $object->attribute( 'id' ) ); } } $db->commit(); eZContentCacheManager::clearContentCacheIfNeeded( $objectID ); if ( !eZSearch::getEngine() instanceof eZSearchEngine ) { eZContentOperationCollection::registerSearchObject( $objectID ); } return array( 'status' => true ); } /** * Removes nodes * * This function does not check about permissions, this is the responsibility of the caller! * * @param array $removeNodeIdList Array of Node ID to remove * * @return array An array with operation status, always true */ static public function removeNodes( array $removeNodeIdList ) { $mainNodeChanged = array(); $nodeAssignmentIdList = array(); $objectIdList = array(); $db = eZDB::instance(); $db->begin(); foreach ( $removeNodeIdList as $nodeId ) { $node = eZContentObjectTreeNode::fetch($nodeId); $objectId = $node->attribute( 'contentobject_id' ); foreach ( eZNodeAssignment::fetchForObject( $objectId, eZContentObject::fetch( $objectId )->attribute( 'current_version' ), 0, false ) as $nodeAssignmentKey => $nodeAssignment ) { if ( $nodeAssignment['parent_node'] == $node->attribute( 'parent_node_id' ) ) { $nodeAssignmentIdList[$nodeAssignment['id']] = 1; } } if ( $nodeId == $node->attribute( 'main_node_id' ) ) $mainNodeChanged[$objectId] = 1; $node->removeThis(); if ( !isset( $objectIdList[$objectId] ) ) $objectIdList[$objectId] = eZContentObject::fetch( $objectId ); } eZNodeAssignment::purgeByID( array_keys( $nodeAssignmentIdList ) ); foreach ( array_keys( $mainNodeChanged ) as $objectId ) { $allNodes = $objectIdList[$objectId]->assignedNodes(); // Registering node that will be promoted as 'main' if ( isset( $allNodes[0] ) ) { $mainNodeChanged[$objectId] = $allNodes[0]; eZContentObjectTreeNode::updateMainNodeID( $allNodes[0]->attribute( 'node_id' ), $objectId, false, $allNodes[0]->attribute( 'parent_node_id' ) ); } } // Give other search engines that the default one a chance to reindex // when removing locations. if ( !eZSearch::getEngine() instanceof eZSearchEngine ) { foreach ( array_keys( $objectIdList ) as $objectId ) eZContentOperationCollection::registerSearchObject( $objectId ); } $db->commit(); //call appropriate method from search engine eZSearch::removeNodes( $removeNodeIdList ); $userClassIdList = eZUser::contentClassIDs(); foreach ( $objectIdList as $objectId => $object ) { eZContentCacheManager::clearObjectViewCacheIfNeeded( $objectId ); // clear user policy cache if this was a user object if ( in_array( $object->attribute( 'contentclass_id' ), $userClassIdList ) ) { eZUser::purgeUserCacheByUserId( $object->attribute( 'id' ) ); } // Give other search engines that the default one a chance to reindex // when removing locations. if ( !eZSearch::getEngine() instanceof eZSearchEngine ) { eZContentOperationCollection::registerSearchObject( $objectId ); } } // Triggering content/cache filter for Http cache purge ezpEvent::getInstance()->filter( 'content/cache', $removeNodeIdList, array_keys( $objectIdList ) ); // we don't clear template block cache here since it's cleared in eZContentObjectTreeNode::removeNode() return array( 'status' => true ); } /** * Deletes a content object, or a list of content objects * * @param array $deleteIDArray * @param bool $moveToTrash * * @return array An array with operation status, always true */ static public function deleteObject( $deleteIDArray, $moveToTrash = false ) { $ini = eZINI::instance(); $aNodes = eZContentObjectTreeNode::fetch( $deleteIDArray ); if( !is_array( $aNodes ) ) { $aNodes = array( $aNodes ); } $delayedIndexingValue = $ini->variable( 'SearchSettings', 'DelayedIndexing' ); if ( $delayedIndexingValue === 'enabled' || $delayedIndexingValue === 'classbased' ) { $pendingActionsToDelete = array(); $classList = $ini->variable( 'SearchSettings', 'DelayedIndexingClassList' ); // Will be used below if DelayedIndexing is classbased $assignedNodesByObject = array(); $nodesToDeleteByObject = array(); foreach ( $aNodes as $node ) { $object = $node->object(); $objectID = $object->attribute( 'id' ); $assignedNodes = $object->attribute( 'assigned_nodes' ); // Only delete pending action if this is the last object's node that is requested for deletion // But $deleteIDArray can also contain all the object's node (mainly if this method is called programmatically) // So if this is not the last node, then store its id in a temp array // This temp array will then be compared to the whole object's assigned nodes array if ( count( $assignedNodes ) > 1 ) { // $assignedNodesByObject will be used as a referent to check if we want to delete all lasting nodes if ( !isset( $assignedNodesByObject[$objectID] ) ) { $assignedNodesByObject[$objectID] = array(); foreach ( $assignedNodes as $assignedNode ) { $assignedNodesByObject[$objectID][] = $assignedNode->attribute( 'node_id' ); } } // Store the node assignment we want to delete // Then compare the array to the referent node assignment array $nodesToDeleteByObject[$objectID][] = $node->attribute( 'node_id' ); $diff = array_diff( $assignedNodesByObject[$objectID], $nodesToDeleteByObject[$objectID] ); if ( !empty( $diff ) ) // We still have more node assignments for object, pending action is not to be deleted considering this iteration { continue; } } if ( $delayedIndexingValue !== 'classbased' || ( is_array( $classList ) && in_array( $object->attribute( 'class_identifier' ), $classList ) ) ) { $pendingActionsToDelete[] = $objectID; } } if ( !empty( $pendingActionsToDelete ) ) { $filterConds = array( 'param' => array ( $pendingActionsToDelete ) ); eZPendingActions::removeByAction( 'index_object', $filterConds ); } } // Add assigned nodes to the clear cache list // This allows to clear assigned nodes separately (e.g. in reverse proxies) // as once content is removed, there is no more assigned nodes, and http cache clear is not possible any more. // See https://jira.ez.no/browse/EZP-22447 foreach ( $aNodes as $node ) { eZContentCacheManager::addAdditionalNodeIDPerObject( $node->attribute( 'contentobject_id' ), $node->attribute( 'node_id' ) ); } eZContentObjectTreeNode::removeSubtrees( $deleteIDArray, $moveToTrash ); return array( 'status' => true ); } /** * Changes an contentobject's status * * @param int $nodeID * * @return array An array with operation status, always true */ static public function changeHideStatus( $nodeID ) { $action = 'hide'; $curNode = eZContentObjectTreeNode::fetch( $nodeID ); if ( is_object( $curNode ) ) { if ( $curNode->attribute( 'is_hidden' ) ) { eZContentObjectTreeNode::unhideSubTree( $curNode ); $action = 'show'; } else eZContentObjectTreeNode::hideSubTree( $curNode ); } //call appropriate method from search engine eZSearch::updateNodeVisibility( $nodeID, $action ); return array( 'status' => true ); } /** * Swap a node with another one * * @param int $nodeID * @param int $selectedNodeID * @param array $nodeIdList * * @return array An array with operation status, always true */ static public function swapNode( $nodeID, $selectedNodeID, $nodeIdList = array() ) { $userClassIDArray = eZUser::contentClassIDs(); $node = eZContentObjectTreeNode::fetch( $nodeID ); $selectedNode = eZContentObjectTreeNode::fetch( $selectedNodeID ); $object = $node->object(); $nodeParentNodeID = $node->attribute( 'parent_node_id' ); $nodeParent = $node->attribute( 'parent' ); $objectID = $object->attribute( 'id' ); $objectVersion = $object->attribute( 'current_version' ); $selectedObject = $selectedNode->object(); $selectedObjectID = $selectedObject->attribute( 'id' ); $selectedObjectVersion = $selectedObject->attribute( 'current_version' ); $selectedNodeParentNodeID = $selectedNode->attribute( 'parent_node_id' ); $selectedNodeParent = $selectedNode->attribute( 'parent' ); $db = eZDB::instance(); $db->begin(); $node->setAttribute( 'contentobject_id', $selectedObjectID ); $node->setAttribute( 'contentobject_version', $selectedObjectVersion ); $selectedNode->setAttribute( 'contentobject_id', $objectID ); $selectedNode->setAttribute( 'contentobject_version', $objectVersion ); // fix main node id if ( $node->isMain() && !$selectedNode->isMain() ) { $node->setAttribute( 'main_node_id', $selectedNode->attribute( 'main_node_id' ) ); $selectedNode->setAttribute( 'main_node_id', $selectedNode->attribute( 'node_id' ) ); } else if ( $selectedNode->isMain() && !$node->isMain() ) { $selectedNode->setAttribute( 'main_node_id', $node->attribute( 'main_node_id' ) ); $node->setAttribute( 'main_node_id', $node->attribute( 'node_id' ) ); } $node->store(); $selectedNode->store(); // clear user policy cache if this was a user object if ( in_array( $object->attribute( 'contentclass_id' ), $userClassIDArray ) ) { eZUser::purgeUserCacheByUserId( $object->attribute( 'id' ) ); } if ( in_array( $selectedObject->attribute( 'contentclass_id' ), $userClassIDArray ) ) { eZUser::purgeUserCacheByUserId( $selectedObject->attribute( 'id' ) ); } // modify path string $changedOriginalNode = eZContentObjectTreeNode::fetch( $nodeID ); $changedOriginalNode->updateSubTreePath(); $changedTargetNode = eZContentObjectTreeNode::fetch( $selectedNodeID ); $changedTargetNode->updateSubTreePath(); // modify section if ( $changedOriginalNode->isMain() ) { $changedOriginalObject = $changedOriginalNode->object(); $parentObject = $nodeParent->object(); if ( $changedOriginalObject->attribute( 'section_id' ) != $parentObject->attribute( 'section_id' ) ) { eZContentObjectTreeNode::assignSectionToSubTree( $changedOriginalNode->attribute( 'main_node_id' ), $parentObject->attribute( 'section_id' ), $changedOriginalObject->attribute( 'section_id' ) ); } } if ( $changedTargetNode->isMain() ) { $changedTargetObject = $changedTargetNode->object(); $selectedParentObject = $selectedNodeParent->object(); if ( $changedTargetObject->attribute( 'section_id' ) != $selectedParentObject->attribute( 'section_id' ) ) { eZContentObjectTreeNode::assignSectionToSubTree( $changedTargetNode->attribute( 'main_node_id' ), $selectedParentObject->attribute( 'section_id' ), $changedTargetObject->attribute( 'section_id' ) ); } } eZContentObject::fixReverseRelations( $objectID, 'swap' ); eZContentObject::fixReverseRelations( $selectedObjectID, 'swap' ); $db->commit(); // clear cache for new placement. eZContentCacheManager::clearContentCacheIfNeeded( $objectID ); if ( !eZSearch::getEngine() instanceof eZSearchEngine ) { eZContentOperationCollection::registerSearchObject( $objectID ); } eZSearch::swapNode( $nodeID, $selectedNodeID, $nodeIdList = array() ); return array( 'status' => true ); } /** * Assigns a node to a section * * @param int $nodeID * @param int $selectedSectionID * @param bool $updateSearchIndexes * * @return void */ static public function updateSection( $nodeID, $selectedSectionID, $updateSearchIndexes = true ) { eZContentObjectTreeNode::assignSectionToSubTree( $nodeID, $selectedSectionID, false, $updateSearchIndexes ); } /** * Changes the status of a translation * * @param int $objectID * @param int $status * * @return array An array with operation status, always true */ static public function changeTranslationAvailableStatus( $objectID, $status = false ) { $object = eZContentObject::fetch( $objectID ); if ( !$object->canEdit() ) { return array( 'status' => false ); } if ( $object->isAlwaysAvailable() & $status == false ) { $object->setAlwaysAvailableLanguageID( false ); eZContentCacheManager::clearContentCacheIfNeeded( $objectID ); } else if ( !$object->isAlwaysAvailable() & $status == true ) { $object->setAlwaysAvailableLanguageID( $object->attribute( 'initial_language_id' ) ); eZContentCacheManager::clearContentCacheIfNeeded( $objectID ); } return array( 'status' => true ); } /** * Changes the sort order for a node * * @param int $nodeID * @param string $sortingField * @param bool $sortingOrder * * @return array An array with operation status, always true */ static public function changeSortOrder( $nodeID, $sortingField, $sortingOrder = false ) { $curNode = eZContentObjectTreeNode::fetch( $nodeID ); if ( is_object( $curNode ) ) { $db = eZDB::instance(); $db->begin(); $curNode->setAttribute( 'sort_field', $sortingField ); $curNode->setAttribute( 'sort_order', $sortingOrder ); $curNode->store(); $db->commit(); $object = $curNode->object(); eZContentCacheManager::clearContentCacheIfNeeded( $object->attribute( 'id' ) ); } return array( 'status' => true ); } /** * Updates the priority of a node * * @param int $parentNodeID * @param array $priorityArray * @param array $priorityIDArray * * @return array An array with operation status, always true */ static public function updatePriority( $parentNodeID, $priorityArray = array(), $priorityIDArray = array() ) { $curNode = eZContentObjectTreeNode::fetch( $parentNodeID ); if ( $curNode instanceof eZContentObjectTreeNode ) { $objectIDs = array(); $db = eZDB::instance(); $db->begin(); for ( $i = 0, $l = count( $priorityArray ); $i < $l; $i++ ) { $priority = (int) $priorityArray[$i]; $nodeID = (int) $priorityIDArray[$i]; $node = eZContentObjectTreeNode::fetch( $nodeID ); if ( !$node instanceof eZContentObjectTreeNode ) { continue; } $objectIDs[] = $node->attribute( 'contentobject_id' ); $db->query( "UPDATE ezcontentobject_tree SET priority={$priority} WHERE node_id={$nodeID} AND parent_node_id={$parentNodeID}" ); } $curNode->updateAndStoreModified(); $db->commit(); if ( !eZSearch::getEngine() instanceof eZSearchEngine ) { eZContentCacheManager::clearContentCacheIfNeeded( $objectIDs ); foreach ( $objectIDs as $objectID ) { eZContentOperationCollection::registerSearchObject( $objectID ); } } } return array( 'status' => true ); } /** * Update a node's main assignment * * @param int $mainAssignmentID * @param int $objectID * @param int $mainAssignmentParentID * * @return array An array with operation status, always true */ static public function updateMainAssignment( $mainAssignmentID, $objectID, $mainAssignmentParentID ) { eZContentObjectTreeNode::updateMainNodeID( $mainAssignmentID, $objectID, false, $mainAssignmentParentID ); eZContentCacheManager::clearContentCacheIfNeeded( $objectID ); if ( !eZSearch::getEngine() instanceof eZSearchEngine ) { eZContentOperationCollection::registerSearchObject( $objectID ); } return array( 'status' => true ); } /** * Updates an contentobject's initial language * * @param int $objectID * @param int $newInitialLanguageID * * @return array An array with operation status, always true */ static public function updateInitialLanguage( $objectID, $newInitialLanguageID ) { $object = eZContentObject::fetch( $objectID ); $language = eZContentLanguage::fetch( $newInitialLanguageID ); if ( $language and !$language->attribute( 'disabled' ) ) { $object->setAttribute( 'initial_language_id', $newInitialLanguageID ); $objectName = $object->name( false, $language->attribute( 'locale' ) ); $object->setAttribute( 'name', $objectName ); $object->store(); if ( $object->isAlwaysAvailable() ) { $object->setAlwaysAvailableLanguageID( $newInitialLanguageID ); } $nodes = $object->assignedNodes(); foreach ( $nodes as $node ) { $node->updateSubTreePath(); } } eZContentCacheManager::clearContentCacheIfNeeded( $objectID ); return array( 'status' => true ); } /** * Set the always available flag for a content object * * @param int $objectID * @param int $newAlwaysAvailable * @return array An array with operation status, always true */ static public function updateAlwaysAvailable( $objectID, $newAlwaysAvailable ) { $object = eZContentObject::fetch( $objectID ); $change = false; if ( $object->isAlwaysAvailable() & $newAlwaysAvailable == false ) { $object->setAlwaysAvailableLanguageID( false ); $change = true; } else if ( !$object->isAlwaysAvailable() & $newAlwaysAvailable == true ) { $object->setAlwaysAvailableLanguageID( $object->attribute( 'initial_language_id' ) ); $change = true; } if ( $change ) { eZContentCacheManager::clearContentCacheIfNeeded( $objectID ); if ( !eZSearch::getEngine() instanceof eZSearchEngine ) { eZContentOperationCollection::registerSearchObject( $objectID ); } } return array( 'status' => true ); } /** * Removes a translation for a contentobject * * @param int $objectID * @param array * @return array An array with operation status, always true */ static public function removeTranslation( $objectID, $languageIDArray ) { $object = eZContentObject::fetch( $objectID ); foreach( $languageIDArray as $languageID ) { if ( !$object->removeTranslation( $languageID ) ) { eZDebug::writeError( "Object with id $objectID: cannot remove the translation with language id $languageID!", __METHOD__ ); } } eZContentOperationCollection::registerSearchObject( $objectID ); eZContentCacheManager::clearContentCacheIfNeeded( $objectID ); return array( 'status' => true ); } /** * Update a contentobject's state * * @param int $objectID * @param int $selectedStateIDList * * @return array An array with operation status, always true */ static public function updateObjectState( $objectID, $selectedStateIDList ) { $object = eZContentObject::fetch( $objectID ); // we don't need to re-assign states the object currently already has assigned $currentStateIDArray = $object->attribute( 'state_id_array' ); $selectedStateIDList = array_diff( $selectedStateIDList, $currentStateIDArray ); // filter out any states the current user is not allowed to assign $canAssignStateIDList = $object->attribute( 'allowed_assign_state_id_list' ); $selectedStateIDList = array_intersect( $selectedStateIDList, $canAssignStateIDList ); foreach ( $selectedStateIDList as $selectedStateID ) { $state = eZContentObjectState::fetchById( $selectedStateID ); $object->assignState( $state ); } eZAudit::writeAudit( 'state-assign', array( 'Content object ID' => $object->attribute( 'id' ), 'Content object name' => $object->attribute( 'name' ), 'Selected State ID Array' => implode( ', ' , $selectedStateIDList ), 'Comment' => 'Updated states of the current object: eZContentOperationCollection::updateObjectState()' ) ); //call appropriate method from search engine eZSearch::updateObjectState($objectID, $selectedStateIDList); // Triggering content/state/assign event for persistence cache purge ezpEvent::getInstance()->notify( 'content/state/assign', array( $objectID, $selectedStateIDList ) ); eZContentCacheManager::clearContentCacheIfNeeded( $objectID ); return array( 'status' => true ); } /** * Executes the pre-publish trigger for this object, and handles * specific return statuses from the workflow * * @param int $objectID Object ID * @param int $version Version number * * @since 4.2 */ static public function executePrePublishTrigger( $objectID, $version ) { } /** * Creates a RSS/ATOM Feed export for a node * * @param int $nodeID Node ID * * @since 4.3 */ static public function createFeedForNode( $nodeID ) { $hasExport = eZRSSFunctionCollection::hasExportByNode( $nodeID ); if ( isset( $hasExport['result'] ) && $hasExport['result'] ) { eZDebug::writeError( 'There is already a rss/atom export feed for this node: ' . $nodeID, __METHOD__ ); return array( 'status' => false ); } $node = eZContentObjectTreeNode::fetch( $nodeID ); $currentClassIdentifier = $node->attribute( 'class_identifier' ); $config = eZINI::instance( 'site.ini' ); $feedItemClasses = $config->variable( 'RSSSettings', 'DefaultFeedItemClasses' ); if ( !$feedItemClasses || !isset( $feedItemClasses[ $currentClassIdentifier ] ) ) { eZDebug::writeError( "EnableRSS: content class $currentClassIdentifier is not defined in site.ini[RSSSettings]DefaultFeedItemClasses[<class_id>].", __METHOD__ ); return array( 'status' => false ); } $object = $node->object(); $objectID = $object->attribute('id'); $currentUserID = eZUser::currentUserID(); $rssExportItems = array(); $db = eZDB::instance(); $db->begin(); $rssExport = eZRSSExport::create( $currentUserID ); $rssExport->setAttribute( 'access_url', 'rss_feed_' . $nodeID ); $rssExport->setAttribute( 'node_id', $nodeID ); $rssExport->setAttribute( 'main_node_only', '1' ); $rssExport->setAttribute( 'number_of_objects', $config->variable( 'RSSSettings', 'NumberOfObjectsDefault' ) ); $rssExport->setAttribute( 'rss_version', $config->variable( 'RSSSettings', 'DefaultVersion' ) ); $rssExport->setAttribute( 'status', eZRSSExport::STATUS_VALID ); $rssExport->setAttribute( 'title', $object->name() ); $rssExport->store(); $rssExportID = $rssExport->attribute( 'id' ); foreach( explode( ';', $feedItemClasses[$currentClassIdentifier] ) as $classIdentifier ) { $iniSection = 'RSSSettings_' . $classIdentifier; if ( $config->hasVariable( $iniSection, 'FeedObjectAttributeMap' ) ) { $feedObjectAttributeMap = $config->variable( $iniSection, 'FeedObjectAttributeMap' ); $subNodesMap = $config->hasVariable( $iniSection, 'Subnodes' ) ? $config->variable( $iniSection, 'Subnodes' ) : array(); $rssExportItem = eZRSSExportItem::create( $rssExportID ); $rssExportItem->setAttribute( 'class_id', eZContentObjectTreeNode::classIDByIdentifier( $classIdentifier ) ); $rssExportItem->setAttribute( 'title', $feedObjectAttributeMap['title'] ); if ( isset( $feedObjectAttributeMap['description'] ) ) $rssExportItem->setAttribute( 'description', $feedObjectAttributeMap['description'] ); if ( isset( $feedObjectAttributeMap['category'] ) ) $rssExportItem->setAttribute( 'category', $feedObjectAttributeMap['category'] ); if ( isset( $feedObjectAttributeMap['enclosure'] ) ) $rssExportItem->setAttribute( 'enclosure', $feedObjectAttributeMap['enclosure'] ); $rssExportItem->setAttribute( 'source_node_id', $nodeID ); $rssExportItem->setAttribute( 'status', eZRSSExport::STATUS_VALID ); $rssExportItem->setAttribute( 'subnodes', isset( $subNodesMap[$currentClassIdentifier] ) && $subNodesMap[$currentClassIdentifier] === 'true' ); $rssExportItem->store(); } else { eZDebug::writeError( "site.ini[$iniSection]Source[] setting is not defined.", __METHOD__ ); } } $db->commit(); eZContentCacheManager::clearContentCacheIfNeeded( $objectID ); return array( 'status' => true ); } /** * Removes a RSS/ATOM Feed export for a node * * @param int $nodeID Node ID * * @since 4.3 */ static public function removeFeedForNode( $nodeID ) { $rssExport = eZPersistentObject::fetchObject( eZRSSExport::definition(), null, array( 'node_id' => $nodeID, 'status' => eZRSSExport::STATUS_VALID ), true ); if ( !$rssExport instanceof eZRSSExport ) { eZDebug::writeError( 'DisableRSS: There is no rss/atom feeds left to delete for this node: '. $nodeID, __METHOD__ ); return array( 'status' => false ); } $node = eZContentObjectTreeNode::fetch( $nodeID ); if ( !$node instanceof eZContentObjectTreeNode ) { eZDebug::writeError( 'DisableRSS: Could not fetch node: '. $nodeID, __METHOD__ ); return array( 'status' => false ); } $objectID = $node->attribute('contentobject_id'); $rssExport->removeThis(); eZContentCacheManager::clearContentCacheIfNeeded( $objectID ); return array( 'status' => true ); } /** * Sends the published object/version for publishing to the queue * Used by the content/publish operation * @param int $objectId * @param int $version * * @return array( status => int ) * @since 4.5 */ public static function sendToPublishingQueue( $objectId, $version ) { $behaviour = ezpContentPublishingBehaviour::getBehaviour(); if ( $behaviour->disableAsynchronousPublishing ) $asyncEnabled = false; else $asyncEnabled = ( eZINI::instance( 'content.ini' )->variable( 'PublishingSettings', 'AsynchronousPublishing' ) == 'enabled' ); $accepted = true; if ( $asyncEnabled === true ) { // Filter handlers $ini = eZINI::instance( 'content.ini' ); $filterHandlerClasses = $ini->variable( 'PublishingSettings', 'AsynchronousPublishingFilters' ); if ( count( $filterHandlerClasses ) ) { $versionObject = eZContentObjectVersion::fetchVersion( $version, $objectId ); foreach( $filterHandlerClasses as $filterHandlerClass ) { if ( !class_exists( $filterHandlerClass ) ) { eZDebug::writeError( "Unknown asynchronous publishing filter handler class '$filterHandlerClass'", __METHOD__ ); continue; } $handler = new $filterHandlerClass( $versionObject ); if ( !( $handler instanceof ezpAsynchronousPublishingFilterInterface ) ) { eZDebug::writeError( "Asynchronous publishing filter handler class '$filterHandlerClass' does not implement ezpAsynchronousPublishingFilterInterface", __METHOD__ ); continue; } $accepted = $handler->accept(); if ( !$accepted ) { eZDebugSetting::writeDebug( "Object #{$objectId}/{$version} was excluded from asynchronous publishing by $filterHandlerClass", __METHOD__ ); break; } } } unset( $filterHandlerClasses, $handler ); } if ( $asyncEnabled && $accepted ) { // if the object is already in the process queue, we move ahead // this test should NOT be necessary since http://issues.ez.no/17840 was fixed if ( ezpContentPublishingQueue::isQueued( $objectId, $version ) ) { return array( 'status' => eZModuleOperationInfo::STATUS_CONTINUE ); } // the object isn't in the process queue, this means this is the first time we execute this method // the object must be queued else { ezpContentPublishingQueue::add( $objectId, $version ); return array( 'status' => eZModuleOperationInfo::STATUS_HALTED, 'redirect_url' => "content/queued/{$objectId}/{$version}" ); } } else { return array( 'status' => eZModuleOperationInfo::STATUS_CONTINUE ); } } } ?>
pbek/ezpublish-legacy
kernel/content/ezcontentoperationcollection.php
PHP
gpl-2.0
64,392
[ 30522, 1026, 1029, 25718, 1013, 1008, 1008, 1008, 5371, 4820, 1996, 1041, 2480, 8663, 6528, 14399, 16754, 26895, 18491, 2465, 1012, 1008, 1008, 1030, 9385, 9385, 1006, 1039, 1007, 1041, 2480, 3001, 2004, 1012, 2035, 2916, 9235, 1012, 1008, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
--- layout: chem370 title: CHEM 191 Final Paper Information permalink: /archive/chem191-f2019/final-paper --- <a class="quicklink" href="#intro">Introduction</a> <a class="quicklink" href="#methods">Methods</a> <a class="quicklink" href="#results">Results and Discussion</a> <a class="quicklink" href="#conclusion">Conclusion</a> <a class="quicklink" href="#references">References</a> <a class="quicklink" href="#supplemental">Supplemental Info</a> # Useful Links on Writing ***FINAL REPORT TEMPLATE:*** [Download Word Doc](https://github.com/alphonse/alphonse.github.io/raw/master/archive/chem191-f2019/assignments/final-paper-template.docx) ### Class Standards - Dr. Fischer's [Writing Guide]({{ site.url }}/archive/chem191-f2019/guides/writing) - Dr. Fischer's [Report Rubric](https://github.com/alphonse/alphonse.github.io/raw/master/archive/chem191-f2019/pdf/lab-report-rubric.pdf) (PDF) - [SPIE: How to Write a Good Scientific Paper](https://doi.org/10.1117/3.2317707) ### Style and Language - *Elements of Style for Writing Scientific Journal Articles*, Stephen M Griffies, William A. Perrie, and Gaëlle Hull, free PDF [here](http://www.climatescience.org.au/sites/default/files/Elements_of_Style_for_journal_articles_A4_29Nov.pdf). - *Elements of Style*, William Strunk, Jr. (aka "Strunk and White") free html & ebook at [Project Gutenberg](http://www.gutenberg.org/ebooks/37134?msg=welcome_stranger) or free PDF [here](http://www.jlakes.org/ch/web/The-elements-of-style.pdf). - [IEEE Style Guide](https://www.tec.ac.cr/sites/default/files/media/doc/style_manual.pdf) ### Reference Manager - [Mendeley Info]({{ site.url }}/archive/chem191-f2019/guides/mendeley) # Class Data - Data for the project is available here: [https://github.com/dr-fischer/WheeCAIR](https://github.com/dr-fischer/WheeCAIR) 1. Go to the link above. 2. Click the **Clone or Download** button. 3. Choose **Download ZIP**. 4. Extract/unzip the file to a location on your computer. 5. Browse to the `data` folder for the data. You will then see folders for several locations. You will need data from `grsm-purchase/2019` (Purchase Knob) and `mack/2019` (Dillsboro, NC). You will also need the NOAA weather station data in `grsm-purchase/2019/weather_noaa` directory. ***Make sure you use the 10 minute average (10minAvg) versions of the data!*** <a id="intro"/> # Writing an Introduction The introduction to the paper serves to orient the reader to the topic at hand and provide an *very brief* overview of the study at hand. If you've written a research paper or 5-paragraph essay for a class before, the introduction is much the same. You can think of it as a 5-paragraph essay that makes up the first section of your paper (but don't necessarily limit yourself to the 5-paragraph format). Of course, this means you will have to do research to write the intro! It should convey what questions the study is asking, why it's asking those question, and what led the author's to ask those questions. It should also discuss any similar work that's been done previously and describe how the author's work relates to the previous studies. Provide context by citing relevant *scholarly* sources. There is no specific formula for what to include -- the intro is your chance to decide what you think is important for the reader to know. > The Introduction section should answer two questions: “What?” and “So what?” What is the paper about, and why should the reader care? [1] - Read *How to Write a Scientific Paper* by Chris Mack, section 2.2 for guidance. [1] - Look at [2] as an example of a good introduction. - Look at the introduction of [3] as another example (i.e. section I). Remember the pluses and minuses we talked about in class regarding this introduction. Try to avoid the minuses and repeat the pluses! **Style tips:** - Write in *present tense*. - Use active voice (first-person is OK, too). <a id="methods"/> # Writing a Methods Section The methods section provides the reader of your manuscript a *detailed* account of how you completed your study. It should contain enough information that the reader could complete your study with no other resources. However, it should *not* contain extraneous details or irrelevant minutia. More information about what constitutes appropriate detail is provided in Mack (2018). [1] > There are really two interrelated goals at work: the reader should be given the ability to reproduce the results and the ability to judge the results. [1] For this assignment, you should turn in a methods section to your final paper that details your sensor construction and deployment. **Style tips:** - Write in *past tense*. - Use active voice (first-person is OK, too). - All tables must have a title *above* the table and be numbered sequentially. - All figures (images or graphs) must have a caption (that includes a title and brief description of the figure) *below* the figure and be numbered sequentially. **Examples:** **Table 1: A table with a lot of useful information** | Column 1 | Column 2 | | ------------- | -------------- | | a bit of info | some more info | ![*Figure 1:* An example figure showing the Antarctic ozone hole. High ozone concentrations are shown in orange/red and low ozone concentrations are shown in purple.](./img/example-figure.png) *Figure 1:* An example figure showing the Antarctic ozone hole. High ozone concentrations are shown in orange/red and low ozone concentrations are shown in purple. ## Specific Instructions for Methods Your document should have the following sections: **II. Materials and Methods** *A. Hardware Components* - Include a table specifying the key components used (some of this information is in Table 1, below, but you will need to add info about the Teensy 3.5) - Include a *block diagram* showing how the components are connected together (See Fig. 1 in [3] as an example) - Include a photo of your sensor (you can include a place holder for now if you don't have a photo, see Fig 2 in [3] or p. 28 in [2]). Each of these figures should be explicitly referred to in the text, in order. This means you will also have to supply text discussing each figure in detail. This section should also provide a description of what was done to weatherproof the sensors and a description of how the sensor was assembled (you will be given a bill of materials to use as an appendix) Refer to Table 1 below for a review of the sensors used and measurements conducted. *B. Site Description* - Include the name a location of the site where you deployed your sensor. - Include GPS coordinates of the site (use UTM format - [Lat/Long to UTM conversion tool](http://www.rcn.montana.edu/resources/converter.aspx)). - Include the elevation of the site (in meters). - Include any additional information about the site that might be important. - Include information about the study as a whole, not just your sensor. How many sensors were deployed in total? Were there any additional instruments at the sampling site? - Include the approximate height above the ground at which you mounted your sensor. - You will use a sensor from Dillsboro as a comparison. Include the description of *Site B* (below) in your report and list your site as *Site A*. It's OK to copy this description exactly as it is below. **Example site description:** *Site B:* One sensor was deployed near Dillsboro, North Carolina, United States at an elevation of 770 m (17S 293055 3914390). Dillsboro is a small town near the Great Smoky Mountains of North Carolina and can be classified as a rural site. The sampling site is in a small grassy clearing between forest and a gravel road. Moreover, the site is in a cove with a rock quarry and asphalt plant, along with many residential wood fireplaces. The sensor was mounted 1 m from the ground on a metal pole. This site was chosen as a rural site with heavy anthropogenic influence. *C. Sampling Routine, Data Processing, and Data Storage* - Include how often a data point was collected. Remember, the sensors slept for 10 minutes, then woke for 30 seconds to get a measurement. - Include how the data was stored on the sensor. Remember, the sensor writes a raw text file to the SD card. - Include how the data were processed. (We'll use Excel -- you can leave this section blank for now since we haven't done it yet.) - Include where the data are stored. Use the following text: Data are available for download at https://github.com/alphonse/grsm-sensors. **Table 1: Sensors Used** | Measurement | Sensor | | ------------------------------- | ----------------------- | | Particulate Matter (PM$_{2.5}$) | Honeywell HPMA115S0-XXX | | Volatile Organic Carbon (VOC) | Bosch BME-680 | | Temperature | Bosch BME-680 | | Relative Humidity | Bosch BME-680 | | Pressure | Bosch BME-680 | <a id="results"/> # Results and Discussion The *Results and Discussion* section serves two purposes: (1) to present the results (data) and (2) to put those results into context with a thoughtful discussion about whether the results were anticipated, how they compare to previous work, and how they can be explained using models, theories, general knowledge, and reasoning. Note that the results section should be a *logical argument* based on evidence, not a chronological description of the experiment. > Evidence does not explain itself. The purpose of the Discussion section is to explain the results and show how they help to answer the research questions posed in the introduction. This discussion generally passes through the stages of summarizing the results, discussing whether results are expected or unexpected, comparing these results to previous work, interpreting and explaining the results (often by comparison to a theory or model), and hypothesizing about their generality. [1] You *must* present results supporting every conclusion you draw; likewise, you must use sound logic when interpreting the results to draw conclusions. Similarly you *must not* withhold results that don't support your hypothesis or conclusions; all results must be reconciled, whether they agree or not. Style tips (see the [writing guide](https://alphonse.github.io/archive/chem191-f2019/guides/writing) for more info): - Write in paste tense. - Be specific. - Avoid faulty and incomplete comparisons. Please see [1] for more information and [2] (section 3 "Results and Discussion") as an example of a results and discussion section. Ref [3], section V "Experimental Analysis" also provides an example of a results and discussion section. ### Data Processing 1. Look for any errors in your data: - Do the values seem correct? If not, can you explain why? - Is the timestamp correct? If not, you should fix it based on the start time from your deployment sheet. - Are the values zero or missing? If so, can you explain the missing data? *Note that there is a distinct difference between correcting errors (e.g. an incorrectly set clock) and "correcting" (making up) data; the first is necessary, the second is unethical.* 1. Most data can be used as-is. However, the pressure is measured and reported barometric pressure and must be converted to mean sea-level pressure for comparison to other data. Refer to this [PDF document](https://www.sandhurstweather.org.uk/barometric.pdf) for details on how to do this. ### Figures Include, at minimum, the following: 1. Plot *Temperature vs. Time*, *Relative Humidity vs. Time*, *Pressure vs. Time* (processed per instructions above), *VOC vs. Time*, and *PM vs. Time* on separate plots. 1. For Temperature, RH, and Pressure, you should include (1) your data, (2) data from another group's sensor, (3) data from Dillsboro, and (4) data from the NOAA weather station on each plot. For VOC and PM you should include (1) data from your sensor, (2) data from another group's sensor, and (3) data from the Dillsboro sensor. Make sure to include a legend on your plot. Remember to label your axes (and include units) and provide a caption below each figure with a number for each figure. Provide a summary of each figure in the main text, and refer to each figure by number where it's discussed; figures should appear/be numbered in the order in which they are discussed. When discussing each figure, provide not only a summary of the figure but also your *interpretation* of the data. Put the data in context. How do the data relate to other data or typical trends? Do your data agree with the NOAA ("gold-standard") sensors? Do the data from Purchase Knob and Dillsboro agree? Are the results expected and easily explained by common knowledge/theories, or are they unexpected? You do not have to specifically answer all these questions, but they should provide a starting point to help you think about *discussing* the data (it is the *Results and Discussion* section, after all!). <a id="conclusion"/> # Conclusion The conclusion should provide a brief summary of the results, highlighting the key breakthroughs or findings. It should specifically relate the conclusions back to the research questions posed in the introduction and explain their significance. Finally, it should provide recommendations for future improvements or expansions upon the study. It should not just repeat other portions of the paper. > The Conclusions section should allow for opportunistic reading. When writing this section, imagine a reader who reads the introduction, skims through the figures, then jumps to the conclusion. The conclusion should concisely provide the key message(s) the author wishes to convey. [1] <a id="references"/> # References Your references should be cited in IEEE format. You should only cite *scholarly* sources. Points may be deducted for sources that do not meet the guidelines outlined in the Scholarly Sources workshop in the library. Please refer to this [flowchart](https://www.library.illinois.edu/ugl/howdoi/scholarly/) to determine if your source counts as scholarly. If in doubt, it's probably *not* scholarly. <a id="supplemental"/> # Supplemental Information and Appendices You should include the following table as supplemental information. You can reference this table in your methods section as the bill of materials for the sensor. **Table S.1: Bill of Materials for Sensor** | Item | PN | Price | Qty | Supplier | | ----------------------------------------- | ---------------------- | ------- | --- | -------- | | Sensor, BME 680 | 1597-1653-ND | $20.910 | 1 | digikey | | Sensor, PM, Honeywell | 785-HPMA115SO-XXX | $26.340 | 1 | mouser | | Micro SD | SDSDQM-B35A | $4.500 | 1 | Amazon | | Teensy 3.5 | 1568-1443-ND | $26.250 | 1 | digikey | | USB Cable | WM25438-ND | $3.710 | 1 | digikey | | Case | Lowes | $7.150 | 1 | Lowes | | Case Port | Lowes | $1.690 | 0.5 | Lowes | | Breadboard | 1738-1326-ND | $2.990 | 1 | digikey | | Wire, Hookup, Assortment, 10x25' | 485-3174 | $29.950 | 0.1 | mouser | | Pin headers, Breakaway, 36 position, 0.1" | WM50014-36-ND | $0.901 | 2 | digikey | | LED, RGB | 1830-1014-ND | $0.829 | 1 | digikey | | Resistor, 220 ohm | CF12JT220RCT-ND | $0.072 | 1 | digikey | | Thermistor | BC2301-ND | $0.660 | 1 | digikey | | Resistor, 1k | S1KQTR-ND | $0.004 | 1 | digikey | | Capacitor, Electrolytic, 1000uF | P19639TB-ND | $0.310 | 1 | digikey | | Relay | TLP222AF-ND | $1.013 | 1 | digikey | | Header, 5 Position, 0.1 | S6103-ND | $0.443 | 1 | digikey | | Header, 24 Position, 0.1 | S7022-ND | $1.244 | 2 | digikey | | Retainer, Coin Cell, 12 MM, SMD | 36-3000CT-ND | $0.767 | 1 | digikey | | Terminal, 4 Position, 3.5 mm | WM7860-ND | $1.121 | 2 | digikey | | Terminal, 2 Position, 3.5 mm | WM7877-ND | $0.718 | 1 | digikey | | Batteries, AA, Duracell Procell, 2900 mAh | PC1500BKD | $0.520 | 6 | Grainger | | Batteries, Coin Cell, CR1220 | P033-ND | $0.828 | 1 | digikey | | Wire, PicoBlade, Pre-crimped, black | 0500798000-10-B8-ND | $0.676 | 1 | digikey | | Wire, PicoBlade, Pre-crimped, yellow | 0500798000-10-Y8-ND | $0.676 | 1 | digikey | | Wire, PicoBlade, Pre-crimped, red | 0500798000-10-R8-ND | $0.676 | 1 | digikey | | Wire, PicoBlade, Pre-crimped, violet | 0500798000-10-V8-ND | $0.676 | 1 | digikey | | PCB, Custom | WheeCAir v1.0 (custom) | $6.820 | 1 | OSH Park | # Further Reading [1] Mack, Chris A., *How to Write a Scientific Paper*. SPIE, 2018. doi: [10.1117/3.2317707](https://doi.org/10.1117/3.2317707) [2] Ardon-Dryer, Karin, Y Dryer, J.N. Williams, and N. Moghimi, "Measurements of PM$_{2.5}$ with PurpleAir under atmospheric conditions," *Atmospheric Measurement Techniques (Discussions)* (in review) doi:[10.5194/amt-2019-396](https://doi.org/10.5194/amt-2019-396). [3] Guisto, Edoardo, R Ferrero, F. Gandino, B. Montrucchio, M. Rebaudengo, and M. Zhang, "Particulate matter monitoring in mixed indoor/outdoor industrial applications: a case study," *Proceedings: 2018 IEEE 23rd International Conference on Emerging Technologies and Factory Automation, Sept. 4-7 2018, Turin, Italy.* doi: [10.1109/ETFA.2018.8502644](http://tinyurl.com/rt7vtvs).
alphonse/alphonse.github.io
archive/chem191-f2019/assignments/final-paper.md
Markdown
mit
18,313
[ 30522, 1011, 1011, 1011, 9621, 1024, 18178, 2213, 24434, 2692, 2516, 1024, 18178, 2213, 19871, 2345, 3259, 2592, 2566, 9067, 19839, 1024, 1013, 8756, 1013, 18178, 2213, 16147, 2487, 1011, 1042, 11387, 16147, 1013, 2345, 1011, 3259, 1011, 10...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
#pragma once #include <zlib.h> #include "istream.h" namespace nano { /// /// \brief zlib-based streaming of gzip-compressed binary data. /// struct NANO_PUBLIC zlib_istream_t final : public istream_t { explicit zlib_istream_t(istream_t& istream, const std::streamsize max_num_bytes = max_streamsize()); ~zlib_istream_t() override; io_status advance(const std::streamsize num_bytes, buffer_t& buffer) override; private: // attributes istream_t& m_istream; ///< input stream std::streamsize m_max_num_bytes; ///< maximum number of bytes to read from the input stream z_stream m_zstream; ///< zlib stream }; }
accosmin/nano
src/core/istream_zlib.h
C
mit
826
[ 30522, 1001, 10975, 8490, 2863, 2320, 1001, 2421, 1026, 1062, 29521, 1012, 1044, 1028, 1001, 2421, 1000, 21541, 16416, 2213, 1012, 1044, 1000, 3415, 15327, 28991, 1063, 1013, 1013, 1013, 1013, 1013, 1013, 1032, 4766, 1062, 29521, 1011, 2241...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* * MindmapsDB - A Distributed Semantic Database * Copyright (C) 2016 Mindmaps Research Ltd * * MindmapsDB 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. * * MindmapsDB 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 MindmapsDB. If not, see <http://www.gnu.org/licenses/gpl.txt>. */ package io.mindmaps.graph.internal; import io.mindmaps.concept.Resource; import io.mindmaps.concept.ResourceType; import io.mindmaps.exception.InvalidConceptValueException; import io.mindmaps.util.ErrorMessage; import io.mindmaps.util.Schema; import org.apache.tinkerpop.gremlin.structure.Vertex; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * A Resource Type which can hold different values. * @param <D> The data tyoe of this resource type. */ class ResourceTypeImpl<D> extends TypeImpl<ResourceType<D>, Resource<D>> implements ResourceType<D> { ResourceTypeImpl(Vertex v, AbstractMindmapsGraph mindmapsGraph) { super(v, mindmapsGraph); } ResourceTypeImpl(Vertex v, AbstractMindmapsGraph mindmapsGraph, DataType<D> type) { super(v, mindmapsGraph); setDataType(type); } /** * * @param type The data type of the resource */ private void setDataType(DataType<D> type) { setProperty(Schema.ConceptProperty.DATA_TYPE, type.getName()); } /** * @param regex The regular expression which instances of this resource must conform to. * @return The Resource Type itself. */ @Override public ResourceType<D> setRegex(String regex) { if(!getDataType().equals(DataType.STRING)){ throw new UnsupportedOperationException(ErrorMessage.REGEX_NOT_STRING.getMessage(toString())); } if(regex != null) { Pattern pattern = Pattern.compile(regex); Matcher matcher; for (Resource<D> resource : instances()) { String value = (String) resource.getValue(); matcher = pattern.matcher(value); if(!matcher.matches()){ throw new InvalidConceptValueException(ErrorMessage.REGEX_INSTANCE_FAILURE.getMessage(regex, resource.toString())); } } } return setProperty(Schema.ConceptProperty.REGEX, regex); } /** * @return The data type which instances of this resource must conform to. */ //This unsafe cast is suppressed because at this stage we do not know what the type is when reading from the rootGraph. @SuppressWarnings("unchecked") @Override public DataType<D> getDataType() { Object object = getProperty(Schema.ConceptProperty.DATA_TYPE); return (DataType<D>) DataType.SUPPORTED_TYPES.get(String.valueOf(object)); } /** * @return The regular expression which instances of this resource must conform to. */ @Override public String getRegex() { Object object = getProperty(Schema.ConceptProperty.REGEX); if(object == null) return null; return (String) object; } }
denislobanov/grakn
mindmaps-graph/src/main/java/io/mindmaps/graph/internal/ResourceTypeImpl.java
Java
gpl-3.0
3,522
[ 30522, 1013, 1008, 1008, 2568, 2863, 4523, 18939, 1011, 1037, 5500, 21641, 7809, 1008, 9385, 1006, 1039, 1007, 2355, 2568, 2863, 4523, 2470, 5183, 1008, 1008, 2568, 2863, 4523, 18939, 2003, 2489, 4007, 1024, 2017, 2064, 2417, 2923, 3089, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
package com.tocea.corolla.products.dao; import java.util.Collection; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.data.mongodb.repository.Query; import com.tocea.corolla.products.domain.ProjectBranch; public interface IProjectBranchDAO extends MongoRepository<ProjectBranch, String> { /** * Retrieves a ProjectBranch instance from its name and its project id * @param name * @return */ public ProjectBranch findByNameAndProjectId(String name, String projectId); /** * Retrieves all ProjectBranch instances from a project id * @param projectId * @return */ public Collection<ProjectBranch> findByProjectId(String projectId); /** * Retrieves the default branch of a given project * @param projectId * @return */ @Query(value="{ 'projectId': ?0, 'defaultBranch': true }") public ProjectBranch findDefaultBranch(String projectId); }
sleroy/jtestlink
corolla-backend/corolla-backend-application/src/main/java/com/tocea/corolla/products/dao/IProjectBranchDAO.java
Java
gpl-2.0
921
[ 30522, 7427, 4012, 1012, 2000, 21456, 1012, 2522, 28402, 2050, 1012, 3688, 1012, 4830, 2080, 1025, 12324, 9262, 1012, 21183, 4014, 1012, 3074, 1025, 12324, 8917, 1012, 3500, 15643, 6198, 1012, 2951, 1012, 12256, 3995, 18939, 1012, 22409, 10...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
// libjingle // Copyright 2004 Google Inc. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // 3. The name of the author may not be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO // EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Implementation of VideoRecorder and FileVideoCapturer. #include "talk/media/devices/filevideocapturer.h" #include "talk/base/bytebuffer.h" #include "talk/base/logging.h" #include "talk/base/thread.h" namespace cricket { ///////////////////////////////////////////////////////////////////// // Implementation of class VideoRecorder ///////////////////////////////////////////////////////////////////// bool VideoRecorder::Start(const std::string& filename, bool write_header) { Stop(); write_header_ = write_header; int err; if (!video_file_.Open(filename, "wb", &err)) { LOG(LS_ERROR) << "Unable to open file " << filename << " err=" << err; return false; } return true; } void VideoRecorder::Stop() { video_file_.Close(); } bool VideoRecorder::RecordFrame(const CapturedFrame& frame) { if (talk_base::SS_CLOSED == video_file_.GetState()) { LOG(LS_ERROR) << "File not opened yet"; return false; } uint32 size = 0; if (!frame.GetDataSize(&size)) { LOG(LS_ERROR) << "Unable to calculate the data size of the frame"; return false; } if (write_header_) { // Convert the frame header to bytebuffer. talk_base::ByteBuffer buffer; buffer.WriteUInt32(frame.width); buffer.WriteUInt32(frame.height); buffer.WriteUInt32(frame.fourcc); buffer.WriteUInt32(frame.pixel_width); buffer.WriteUInt32(frame.pixel_height); buffer.WriteUInt64(frame.elapsed_time); buffer.WriteUInt64(frame.time_stamp); buffer.WriteUInt32(size); // Write the bytebuffer to file. if (talk_base::SR_SUCCESS != video_file_.Write(buffer.Data(), buffer.Length(), NULL, NULL)) { LOG(LS_ERROR) << "Failed to write frame header"; return false; } } // Write the frame data to file. if (talk_base::SR_SUCCESS != video_file_.Write(frame.data, size, NULL, NULL)) { LOG(LS_ERROR) << "Failed to write frame data"; return false; } return true; } /////////////////////////////////////////////////////////////////////// // Definition of private class FileReadThread that periodically reads // frames from a file. /////////////////////////////////////////////////////////////////////// class FileVideoCapturer::FileReadThread : public talk_base::Thread, public talk_base::MessageHandler { public: explicit FileReadThread(FileVideoCapturer* capturer) : capturer_(capturer), finished_(false) { } // Override virtual method of parent Thread. Context: Worker Thread. virtual void Run() { // Read the first frame and start the message pump. The pump runs until // Stop() is called externally or Quit() is called by OnMessage(). int waiting_time_ms = 0; if (capturer_ && capturer_->ReadFrame(true, &waiting_time_ms)) { PostDelayed(waiting_time_ms, this); Thread::Run(); } finished_ = true; } // Override virtual method of parent MessageHandler. Context: Worker Thread. virtual void OnMessage(talk_base::Message* /*pmsg*/) { int waiting_time_ms = 0; if (capturer_ && capturer_->ReadFrame(false, &waiting_time_ms)) { PostDelayed(waiting_time_ms, this); } else { Quit(); } } // Check if Run() is finished. bool Finished() const { return finished_; } private: FileVideoCapturer* capturer_; bool finished_; DISALLOW_COPY_AND_ASSIGN(FileReadThread); }; ///////////////////////////////////////////////////////////////////// // Implementation of class FileVideoCapturer ///////////////////////////////////////////////////////////////////// static const int64 kNumNanoSecsPerMilliSec = 1000000; const char* FileVideoCapturer::kVideoFileDevicePrefix = "video-file:"; FileVideoCapturer::FileVideoCapturer() : frame_buffer_size_(0), file_read_thread_(NULL), repeat_(0), start_time_ns_(0), last_frame_timestamp_ns_(0), ignore_framerate_(false) { } FileVideoCapturer::~FileVideoCapturer() { Stop(); delete[] static_cast<char*>(captured_frame_.data); } bool FileVideoCapturer::Init(const Device& device) { if (!FileVideoCapturer::IsFileVideoCapturerDevice(device)) { return false; } std::string filename(device.name); if (IsRunning()) { LOG(LS_ERROR) << "The file video capturer is already running"; return false; } // Open the file. int err; if (!video_file_.Open(filename, "rb", &err)) { LOG(LS_ERROR) << "Unable to open the file " << filename << " err=" << err; return false; } // Read the first frame's header to determine the supported format. CapturedFrame frame; if (talk_base::SR_SUCCESS != ReadFrameHeader(&frame)) { LOG(LS_ERROR) << "Failed to read the first frame header"; video_file_.Close(); return false; } // Seek back to the start of the file. if (!video_file_.SetPosition(0)) { LOG(LS_ERROR) << "Failed to seek back to beginning of the file"; video_file_.Close(); return false; } // Enumerate the supported formats. We have only one supported format. We set // the frame interval to kMinimumInterval here. In Start(), if the capture // format's interval is greater than kMinimumInterval, we use the interval; // otherwise, we use the timestamp in the file to control the interval. VideoFormat format(frame.width, frame.height, VideoFormat::kMinimumInterval, frame.fourcc); std::vector<VideoFormat> supported; supported.push_back(format); SetId(device.id); SetSupportedFormats(supported); return true; } bool FileVideoCapturer::Init(const std::string& filename) { return Init(FileVideoCapturer::CreateFileVideoCapturerDevice(filename)); } CaptureState FileVideoCapturer::Start(const VideoFormat& capture_format) { if (IsRunning()) { LOG(LS_ERROR) << "The file video capturer is already running"; return CS_FAILED; } if (talk_base::SS_CLOSED == video_file_.GetState()) { LOG(LS_ERROR) << "File not opened yet"; return CS_NO_DEVICE; } else if (!video_file_.SetPosition(0)) { LOG(LS_ERROR) << "Failed to seek back to beginning of the file"; return CS_FAILED; } SetCaptureFormat(&capture_format); // Create a thread to read the file. file_read_thread_ = new FileReadThread(this); bool ret = file_read_thread_->Start(); start_time_ns_ = kNumNanoSecsPerMilliSec * static_cast<int64>(talk_base::Time()); if (ret) { LOG(LS_INFO) << "File video capturer '" << GetId() << "' started"; return CS_RUNNING; } else { LOG(LS_ERROR) << "File video capturer '" << GetId() << "' failed to start"; return CS_FAILED; } } bool FileVideoCapturer::IsRunning() { return file_read_thread_ && !file_read_thread_->Finished(); } void FileVideoCapturer::Stop() { if (file_read_thread_) { file_read_thread_->Stop(); file_read_thread_ = NULL; LOG(LS_INFO) << "File video capturer '" << GetId() << "' stopped"; } SetCaptureFormat(NULL); } bool FileVideoCapturer::GetPreferredFourccs(std::vector<uint32>* fourccs) { if (!fourccs) { return false; } fourccs->push_back(GetSupportedFormats()->at(0).fourcc); return true; } talk_base::StreamResult FileVideoCapturer::ReadFrameHeader( CapturedFrame* frame) { // We first read kFrameHeaderSize bytes from the file stream to a memory // buffer, then construct a bytebuffer from the memory buffer, and finally // read the frame header from the bytebuffer. char header[CapturedFrame::kFrameHeaderSize]; talk_base::StreamResult sr; size_t bytes_read; int error; sr = video_file_.Read(header, CapturedFrame::kFrameHeaderSize, &bytes_read, &error); LOG(LS_VERBOSE) << "Read frame header: stream_result = " << sr << ", bytes read = " << bytes_read << ", error = " << error; if (talk_base::SR_SUCCESS == sr) { if (CapturedFrame::kFrameHeaderSize != bytes_read) { return talk_base::SR_EOS; } talk_base::ByteBuffer buffer(header, CapturedFrame::kFrameHeaderSize); buffer.ReadUInt32(reinterpret_cast<uint32*>(&frame->width)); buffer.ReadUInt32(reinterpret_cast<uint32*>(&frame->height)); buffer.ReadUInt32(&frame->fourcc); buffer.ReadUInt32(&frame->pixel_width); buffer.ReadUInt32(&frame->pixel_height); buffer.ReadUInt64(reinterpret_cast<uint64*>(&frame->elapsed_time)); buffer.ReadUInt64(reinterpret_cast<uint64*>(&frame->time_stamp)); buffer.ReadUInt32(&frame->data_size); } return sr; } // Executed in the context of FileReadThread. bool FileVideoCapturer::ReadFrame(bool first_frame, int* wait_time_ms) { uint32 start_read_time_ms = talk_base::Time(); // 1. Signal the previously read frame to downstream. if (!first_frame) { captured_frame_.time_stamp = kNumNanoSecsPerMilliSec * static_cast<int64>(start_read_time_ms); captured_frame_.elapsed_time = captured_frame_.time_stamp - start_time_ns_; SignalFrameCaptured(this, &captured_frame_); } // 2. Read the next frame. if (talk_base::SS_CLOSED == video_file_.GetState()) { LOG(LS_ERROR) << "File not opened yet"; return false; } // 2.1 Read the frame header. talk_base::StreamResult result = ReadFrameHeader(&captured_frame_); if (talk_base::SR_EOS == result) { // Loop back if repeat. if (repeat_ != talk_base::kForever) { if (repeat_ > 0) { --repeat_; } else { return false; } } if (video_file_.SetPosition(0)) { result = ReadFrameHeader(&captured_frame_); } } if (talk_base::SR_SUCCESS != result) { LOG(LS_ERROR) << "Failed to read the frame header"; return false; } // 2.2 Reallocate memory for the frame data if necessary. if (frame_buffer_size_ < captured_frame_.data_size) { frame_buffer_size_ = captured_frame_.data_size; delete[] static_cast<char*>(captured_frame_.data); captured_frame_.data = new char[frame_buffer_size_]; } // 2.3 Read the frame adata. if (talk_base::SR_SUCCESS != video_file_.Read(captured_frame_.data, captured_frame_.data_size, NULL, NULL)) { LOG(LS_ERROR) << "Failed to read frame data"; return false; } // 3. Decide how long to wait for the next frame. *wait_time_ms = 0; // If the capture format's interval is not kMinimumInterval, we use it to // control the rate; otherwise, we use the timestamp in the file to control // the rate. if (!first_frame && !ignore_framerate_) { int64 interval_ns = GetCaptureFormat()->interval > VideoFormat::kMinimumInterval ? GetCaptureFormat()->interval : captured_frame_.time_stamp - last_frame_timestamp_ns_; int interval_ms = static_cast<int>(interval_ns / kNumNanoSecsPerMilliSec); interval_ms -= talk_base::Time() - start_read_time_ms; if (interval_ms > 0) { *wait_time_ms = interval_ms; } } // Keep the original timestamp read from the file. last_frame_timestamp_ns_ = captured_frame_.time_stamp; return true; } } // namespace cricket
wangscript/libjingle-1
trunk/talk/media/devices/filevideocapturer.cc
C++
bsd-3-clause
12,792
[ 30522, 1013, 1013, 5622, 2497, 29518, 2571, 1013, 1013, 9385, 2432, 8224, 4297, 1012, 1013, 1013, 1013, 1013, 25707, 1998, 2224, 1999, 3120, 1998, 12441, 3596, 1010, 2007, 2030, 2302, 1013, 1013, 14080, 1010, 2024, 7936, 3024, 2008, 1996, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
Ti=Intrusion 1.sec=As far back as 1890, future Supreme Court Justice Louis Brandeis published an article in the Harvard Law Review, making the case for a "Right to Privacy" in the United States. 2.sec=He warned: "Gossip is no longer the resource of the idle and of the vicious, but has become a trade." 3.sec=Today that trade has exploded into a data industrial complex. Our own information, from the everyday to the deeply personal, is being weaponized against us with military efficiency. 4.sec=Every day, billions of dollars change hands and countless decisions are made on the basis of our likes and dislikes, our friends and families, our relationships and conversations, our wishes and fears, our hopes and dreams. 5.sec=These scraps of data, each one harmless enough on its own, are carefully assembled, synthesized, traded and sold. 6.sec=Taken to its extreme, this process creates an enduring digital profile and lets companies know you better than you may know yourself. Your profile is then run through algorithms that can serve up increasingly extreme content, pounding our harmless preferences into hardened convictions. If green is your favorite color, you may find yourself reading a lot of articles — or watching a lot of videos — about the insidious threat from people who like orange. 7.sec=In the news almost every day, we bear witness to the harmful, even deadly, effects of these narrowed worldviews. 8.sec=We shouldn't sugarcoat the consequences. This is surveillance. And these stockpiles of personal data serve only to enrich the companies that collect them. 9.sec=This should make us very uncomfortable. It should unsettle us. And it illustrates the importance of our shared work and the challenges still ahead of us. =[G/Z/ol-none/s9]
CommonAccord/Cmacc-Org
Doc/G/ICDPPC/40th-TimCook/Sec/Intrusion/0.md
Markdown
mit
1,775
[ 30522, 14841, 1027, 24554, 1015, 1012, 10819, 1027, 2004, 2521, 2067, 2004, 6193, 1010, 2925, 4259, 2457, 3425, 3434, 4435, 17580, 2405, 2019, 3720, 1999, 1996, 5765, 2375, 3319, 1010, 2437, 1996, 2553, 2005, 1037, 1000, 2157, 2000, 9394, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* Copyright IBM Corp. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package msp import ( "bytes" "crypto/x509" "crypto/x509/pkix" "encoding/hex" "encoding/pem" "fmt" "github.com/golang/protobuf/proto" "github.com/hyperledger/fabric/bccsp" "github.com/hyperledger/fabric/bccsp/factory" "github.com/hyperledger/fabric/bccsp/signer" m "github.com/hyperledger/fabric/protos/msp" "github.com/pkg/errors" ) // mspSetupFuncType is the prototype of the setup function type mspSetupFuncType func(config *m.FabricMSPConfig) error // validateIdentityOUsFuncType is the prototype of the function to validate identity's OUs type validateIdentityOUsFuncType func(id *identity) error // This is an instantiation of an MSP that // uses BCCSP for its cryptographic primitives. type bccspmsp struct { // version specifies the behaviour of this msp version MSPVersion // The following function pointers are used to change the behaviour // of this MSP depending on its version. // internalSetupFunc is the pointer to the setup function internalSetupFunc mspSetupFuncType // internalValidateIdentityOusFunc is the pointer to the function to validate identity's OUs internalValidateIdentityOusFunc validateIdentityOUsFuncType // list of CA certs we trust rootCerts []Identity // list of intermediate certs we trust intermediateCerts []Identity // list of CA TLS certs we trust tlsRootCerts [][]byte // list of intermediate TLS certs we trust tlsIntermediateCerts [][]byte // certificationTreeInternalNodesMap whose keys correspond to the raw material // (DER representation) of a certificate casted to a string, and whose values // are boolean. True means that the certificate is an internal node of the certification tree. // False means that the certificate corresponds to a leaf of the certification tree. certificationTreeInternalNodesMap map[string]bool // list of signing identities signer SigningIdentity // list of admin identities admins []Identity // the crypto provider bccsp bccsp.BCCSP // the provider identifier for this MSP name string // verification options for MSP members opts *x509.VerifyOptions // list of certificate revocation lists CRL []*pkix.CertificateList // list of OUs ouIdentifiers map[string][][]byte // cryptoConfig contains cryptoConfig *m.FabricCryptoConfig // NodeOUs configuration ouEnforcement bool // These are the OUIdentifiers of the clients, peers and orderers. // They are used to tell apart these entities clientOU, peerOU, ordererOU *OUIdentifier } // newBccspMsp returns an MSP instance backed up by a BCCSP // crypto provider. It handles x.509 certificates and can // generate identities and signing identities backed by // certificates and keypairs func newBccspMsp(version MSPVersion) (MSP, error) { mspLogger.Debugf("Creating BCCSP-based MSP instance") bccsp := factory.GetDefault() theMsp := &bccspmsp{} theMsp.version = version theMsp.bccsp = bccsp switch version { case MSPv1_0: theMsp.internalSetupFunc = theMsp.setupV1 theMsp.internalValidateIdentityOusFunc = theMsp.validateIdentityOUsV1 case MSPv1_1: theMsp.internalSetupFunc = theMsp.setupV11 theMsp.internalValidateIdentityOusFunc = theMsp.validateIdentityOUsV11 default: return nil, errors.Errorf("Invalid MSP version [%v]", version) } return theMsp, nil } func (msp *bccspmsp) getCertFromPem(idBytes []byte) (*x509.Certificate, error) { if idBytes == nil { return nil, errors.New("getCertFromPem error: nil idBytes") } // Decode the pem bytes pemCert, _ := pem.Decode(idBytes) if pemCert == nil { return nil, errors.Errorf("getCertFromPem error: could not decode pem bytes [%v]", idBytes) } // get a cert var cert *x509.Certificate cert, err := x509.ParseCertificate(pemCert.Bytes) if err != nil { return nil, errors.Wrap(err, "getCertFromPem error: failed to parse x509 cert") } return cert, nil } func (msp *bccspmsp) getIdentityFromConf(idBytes []byte) (Identity, bccsp.Key, error) { // get a cert cert, err := msp.getCertFromPem(idBytes) if err != nil { return nil, nil, err } // get the public key in the right format certPubK, err := msp.bccsp.KeyImport(cert, &bccsp.X509PublicKeyImportOpts{Temporary: true}) mspId, err := newIdentity(cert, certPubK, msp) if err != nil { return nil, nil, err } return mspId, certPubK, nil } func (msp *bccspmsp) getSigningIdentityFromConf(sidInfo *m.SigningIdentityInfo) (SigningIdentity, error) { if sidInfo == nil { return nil, errors.New("getIdentityFromBytes error: nil sidInfo") } // Extract the public part of the identity idPub, pubKey, err := msp.getIdentityFromConf(sidInfo.PublicSigner) if err != nil { return nil, err } // Find the matching private key in the BCCSP keystore privKey, err := msp.bccsp.GetKey(pubKey.SKI()) // Less Secure: Attempt to import Private Key from KeyInfo, if BCCSP was not able to find the key if err != nil { mspLogger.Debugf("Could not find SKI [%s], trying KeyMaterial field: %+v\n", hex.EncodeToString(pubKey.SKI()), err) if sidInfo.PrivateSigner == nil || sidInfo.PrivateSigner.KeyMaterial == nil { return nil, errors.New("KeyMaterial not found in SigningIdentityInfo") } pemKey, _ := pem.Decode(sidInfo.PrivateSigner.KeyMaterial) privKey, err = msp.bccsp.KeyImport(pemKey.Bytes, &bccsp.ECDSAPrivateKeyImportOpts{Temporary: true}) if err != nil { return nil, errors.WithMessage(err, "getIdentityFromBytes error: Failed to import EC private key") } } // get the peer signer peerSigner, err := signer.New(msp.bccsp, privKey) if err != nil { return nil, errors.WithMessage(err, "getIdentityFromBytes error: Failed initializing bccspCryptoSigner") } return newSigningIdentity(idPub.(*identity).cert, idPub.(*identity).pk, peerSigner, msp) } // Setup sets up the internal data structures // for this MSP, given an MSPConfig ref; it // returns nil in case of success or an error otherwise func (msp *bccspmsp) Setup(conf1 *m.MSPConfig) error { if conf1 == nil { return errors.New("Setup error: nil conf reference") } // given that it's an msp of type fabric, extract the MSPConfig instance conf := &m.FabricMSPConfig{} err := proto.Unmarshal(conf1.Config, conf) if err != nil { return errors.Wrap(err, "failed unmarshalling fabric msp config") } // set the name for this msp msp.name = conf.Name mspLogger.Debugf("Setting up MSP instance %s", msp.name) // setup return msp.internalSetupFunc(conf) } // GetType returns the type for this MSP func (msp *bccspmsp) GetType() ProviderType { return FABRIC } // GetIdentifier returns the MSP identifier for this instance func (msp *bccspmsp) GetIdentifier() (string, error) { return msp.name, nil } // GetTLSRootCerts returns the root certificates for this MSP func (msp *bccspmsp) GetTLSRootCerts() [][]byte { return msp.tlsRootCerts } // GetTLSIntermediateCerts returns the intermediate root certificates for this MSP func (msp *bccspmsp) GetTLSIntermediateCerts() [][]byte { return msp.tlsIntermediateCerts } // GetDefaultSigningIdentity returns the // default signing identity for this MSP (if any) func (msp *bccspmsp) GetDefaultSigningIdentity() (SigningIdentity, error) { mspLogger.Debugf("Obtaining default signing identity") if msp.signer == nil { return nil, errors.New("this MSP does not possess a valid default signing identity") } return msp.signer, nil } // GetSigningIdentity returns a specific signing // identity identified by the supplied identifier func (msp *bccspmsp) GetSigningIdentity(identifier *IdentityIdentifier) (SigningIdentity, error) { // TODO return nil, errors.Errorf("no signing identity for %#v", identifier) } // Validate attempts to determine whether // the supplied identity is valid according // to this MSP's roots of trust; it returns // nil in case the identity is valid or an // error otherwise func (msp *bccspmsp) Validate(id Identity) error { mspLogger.Debugf("MSP %s validating identity", msp.name) switch id := id.(type) { // If this identity is of this specific type, // this is how I can validate it given the // root of trust this MSP has case *identity: return msp.validateIdentity(id) default: return errors.New("identity type not recognized") } } // DeserializeIdentity returns an Identity given the byte-level // representation of a SerializedIdentity struct func (msp *bccspmsp) DeserializeIdentity(serializedID []byte) (Identity, error) { mspLogger.Infof("Obtaining identity") // We first deserialize to a SerializedIdentity to get the MSP ID sId := &m.SerializedIdentity{} err := proto.Unmarshal(serializedID, sId) if err != nil { return nil, errors.Wrap(err, "could not deserialize a SerializedIdentity") } if sId.Mspid != msp.name { return nil, errors.Errorf("expected MSP ID %s, received %s", msp.name, sId.Mspid) } return msp.deserializeIdentityInternal(sId.IdBytes) } // deserializeIdentityInternal returns an identity given its byte-level representation func (msp *bccspmsp) deserializeIdentityInternal(serializedIdentity []byte) (Identity, error) { // This MSP will always deserialize certs this way bl, _ := pem.Decode(serializedIdentity) if bl == nil { return nil, errors.New("could not decode the PEM structure") } cert, err := x509.ParseCertificate(bl.Bytes) if err != nil { return nil, errors.Wrap(err, "parseCertificate failed") } // Now we have the certificate; make sure that its fields // (e.g. the Issuer.OU or the Subject.OU) match with the // MSP id that this MSP has; otherwise it might be an attack // TODO! // We can't do it yet because there is no standardized way // (yet) to encode the MSP ID into the x.509 body of a cert pub, err := msp.bccsp.KeyImport(cert, &bccsp.X509PublicKeyImportOpts{Temporary: true}) if err != nil { return nil, errors.WithMessage(err, "failed to import certificate's public key") } return newIdentity(cert, pub, msp) } // SatisfiesPrincipal returns null if the identity matches the principal or an error otherwise func (msp *bccspmsp) SatisfiesPrincipal(id Identity, principal *m.MSPPrincipal) error { switch principal.PrincipalClassification { // in this case, we have to check whether the // identity has a role in the msp - member or admin case m.MSPPrincipal_ROLE: // Principal contains the msp role mspRole := &m.MSPRole{} err := proto.Unmarshal(principal.Principal, mspRole) if err != nil { return errors.Wrap(err, "could not unmarshal MSPRole from principal") } // at first, we check whether the MSP // identifier is the same as that of the identity if mspRole.MspIdentifier != msp.name { return errors.Errorf("the identity is a member of a different MSP (expected %s, got %s)", mspRole.MspIdentifier, id.GetMSPIdentifier()) } // now we validate the different msp roles switch mspRole.Role { case m.MSPRole_MEMBER: // in the case of member, we simply check // whether this identity is valid for the MSP mspLogger.Debugf("Checking if identity satisfies MEMBER role for %s", msp.name) return msp.Validate(id) case m.MSPRole_ADMIN: mspLogger.Debugf("Checking if identity satisfies ADMIN role for %s", msp.name) // in the case of admin, we check that the // id is exactly one of our admins for _, admincert := range msp.admins { if bytes.Equal(id.(*identity).cert.Raw, admincert.(*identity).cert.Raw) { // we do not need to check whether the admin is a valid identity // according to this MSP, since we already check this at Setup time // if there is a match, we can just return return nil } } return errors.New("This identity is not an admin") default: return errors.Errorf("invalid MSP role type %d", int32(mspRole.Role)) } case m.MSPPrincipal_IDENTITY: // in this case we have to deserialize the principal's identity // and compare it byte-by-byte with our cert principalId, err := msp.DeserializeIdentity(principal.Principal) if err != nil { return errors.WithMessage(err, "invalid identity principal, not a certificate") } if bytes.Equal(id.(*identity).cert.Raw, principalId.(*identity).cert.Raw) { return principalId.Validate() } return errors.New("The identities do not match") case m.MSPPrincipal_ORGANIZATION_UNIT: // Principal contains the OrganizationUnit OU := &m.OrganizationUnit{} err := proto.Unmarshal(principal.Principal, OU) if err != nil { return errors.Wrap(err, "could not unmarshal OrganizationUnit from principal") } // at first, we check whether the MSP // identifier is the same as that of the identity if OU.MspIdentifier != msp.name { return errors.Errorf("the identity is a member of a different MSP (expected %s, got %s)", OU.MspIdentifier, id.GetMSPIdentifier()) } // we then check if the identity is valid with this MSP // and fail if it is not err = msp.Validate(id) if err != nil { return err } // now we check whether any of this identity's OUs match the requested one for _, ou := range id.GetOrganizationalUnits() { if ou.OrganizationalUnitIdentifier == OU.OrganizationalUnitIdentifier && bytes.Equal(ou.CertifiersIdentifier, OU.CertifiersIdentifier) { return nil } } // if we are here, no match was found, return an error return errors.New("The identities do not match") default: return errors.Errorf("invalid principal type %d", int32(principal.PrincipalClassification)) } } // getCertificationChain returns the certification chain of the passed identity within this msp func (msp *bccspmsp) getCertificationChain(id Identity) ([]*x509.Certificate, error) { mspLogger.Debugf("MSP %s getting certification chain", msp.name) switch id := id.(type) { // If this identity is of this specific type, // this is how I can validate it given the // root of trust this MSP has case *identity: return msp.getCertificationChainForBCCSPIdentity(id) default: return nil, errors.New("identity type not recognized") } } // getCertificationChainForBCCSPIdentity returns the certification chain of the passed bccsp identity within this msp func (msp *bccspmsp) getCertificationChainForBCCSPIdentity(id *identity) ([]*x509.Certificate, error) { if id == nil { return nil, errors.New("Invalid bccsp identity. Must be different from nil.") } // we expect to have a valid VerifyOptions instance if msp.opts == nil { return nil, errors.New("Invalid msp instance") } // CAs cannot be directly used as identities.. if id.cert.IsCA { return nil, errors.New("A CA certificate cannot be used directly by this MSP") } return msp.getValidationChain(id.cert, false) } func (msp *bccspmsp) getUniqueValidationChain(cert *x509.Certificate, opts x509.VerifyOptions) ([]*x509.Certificate, error) { // ask golang to validate the cert for us based on the options that we've built at setup time if msp.opts == nil { return nil, errors.New("the supplied identity has no verify options") } validationChains, err := cert.Verify(opts) if err != nil { return nil, errors.WithMessage(err, "the supplied identity is not valid") } // we only support a single validation chain; // if there's more than one then there might // be unclarity about who owns the identity if len(validationChains) != 1 { return nil, errors.Errorf("this MSP only supports a single validation chain, got %d", len(validationChains)) } return validationChains[0], nil } func (msp *bccspmsp) getValidationChain(cert *x509.Certificate, isIntermediateChain bool) ([]*x509.Certificate, error) { validationChain, err := msp.getUniqueValidationChain(cert, msp.getValidityOptsForCert(cert)) if err != nil { return nil, errors.WithMessage(err, "failed getting validation chain") } // we expect a chain of length at least 2 if len(validationChain) < 2 { return nil, errors.Errorf("expected a chain of length at least 2, got %d", len(validationChain)) } // check that the parent is a leaf of the certification tree // if validating an intermediate chain, the first certificate will the parent parentPosition := 1 if isIntermediateChain { parentPosition = 0 } if msp.certificationTreeInternalNodesMap[string(validationChain[parentPosition].Raw)] { return nil, errors.Errorf("invalid validation chain. Parent certificate should be a leaf of the certification tree [%v]", cert.Raw) } return validationChain, nil } // getCertificationChainIdentifier returns the certification chain identifier of the passed identity within this msp. // The identifier is computes as the SHA256 of the concatenation of the certificates in the chain. func (msp *bccspmsp) getCertificationChainIdentifier(id Identity) ([]byte, error) { chain, err := msp.getCertificationChain(id) if err != nil { return nil, errors.WithMessage(err, fmt.Sprintf("failed getting certification chain for [%v]", id)) } // chain[0] is the certificate representing the identity. // It will be discarded return msp.getCertificationChainIdentifierFromChain(chain[1:]) } func (msp *bccspmsp) getCertificationChainIdentifierFromChain(chain []*x509.Certificate) ([]byte, error) { // Hash the chain // Use the hash of the identity's certificate as id in the IdentityIdentifier hashOpt, err := bccsp.GetHashOpt(msp.cryptoConfig.IdentityIdentifierHashFunction) if err != nil { return nil, errors.WithMessage(err, "failed getting hash function options") } hf, err := msp.bccsp.GetHash(hashOpt) if err != nil { return nil, errors.WithMessage(err, "failed getting hash function when computing certification chain identifier") } for i := 0; i < len(chain); i++ { hf.Write(chain[i].Raw) } return hf.Sum(nil), nil } // sanitizeCert ensures that x509 certificates signed using ECDSA // do have signatures in Low-S. If this is not the case, the certificate // is regenerated to have a Low-S signature. func (msp *bccspmsp) sanitizeCert(cert *x509.Certificate) (*x509.Certificate, error) { if isECDSASignedCert(cert) { // Lookup for a parent certificate to perform the sanitization var parentCert *x509.Certificate if cert.IsCA { // at this point, cert might be a root CA certificate // or an intermediate CA certificate chain, err := msp.getUniqueValidationChain(cert, msp.getValidityOptsForCert(cert)) if err != nil { return nil, err } if len(chain) == 1 { // cert is a root CA certificate parentCert = cert } else { // cert is an intermediate CA certificate parentCert = chain[1] } } else { chain, err := msp.getUniqueValidationChain(cert, msp.getValidityOptsForCert(cert)) if err != nil { return nil, err } parentCert = chain[1] } // Sanitize var err error cert, err = sanitizeECDSASignedCert(cert, parentCert) if err != nil { return nil, err } } return cert, nil } // IsWellFormed checks if the given identity can be deserialized into its provider-specific form. // In this MSP implementation, well formed means that the PEM has a Type which is either // the string 'CERTIFICATE' or the Type is missing altogether. func (msp *bccspmsp) IsWellFormed(identity *m.SerializedIdentity) error { bl, _ := pem.Decode(identity.IdBytes) if bl == nil { return errors.New("PEM decoding resulted in an empty block") } // Important: This method looks very similar to getCertFromPem(idBytes []byte) (*x509.Certificate, error) // But we: // 1) Must ensure PEM block is of type CERTIFICATE or is empty // 2) Must not replace getCertFromPem with this method otherwise we will introduce // a change in validation logic which will result in a chain fork. if bl.Type != "CERTIFICATE" && bl.Type != "" { return errors.Errorf("pem type is %s, should be 'CERTIFICATE' or missing", bl.Type) } _, err := x509.ParseCertificate(bl.Bytes) return err }
mqshen/fabric
msp/mspimpl.go
GO
apache-2.0
19,757
[ 30522, 1013, 1008, 9385, 9980, 13058, 1012, 2035, 2916, 9235, 1012, 23772, 2595, 1011, 6105, 1011, 8909, 4765, 18095, 1024, 15895, 1011, 1016, 1012, 1014, 1008, 1013, 7427, 5796, 2361, 12324, 1006, 1000, 27507, 1000, 1000, 19888, 2080, 1013...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
// This file is part of rgtk. // // rgtk 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 3 of the License, or // (at your option) any later version. // // rgtk 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 rgtk. If not, see <http://www.gnu.org/licenses/>. //! A ToolItem subclass that displays buttons use std::ptr; use gtk::{mod, ffi}; /// ToolButton — A ToolItem subclass that displays buttons struct_Widget!(ToolButton) impl ToolButton { pub fn new<T: gtk::WidgetTrait>(icon_widget: Option<&T>, label: Option<&str>) -> Option<ToolButton> { let tmp_pointer = unsafe { match label { Some(l) => { l.with_c_str(|c_str| { match icon_widget { Some(i) => ffi::gtk_tool_button_new(i.get_widget(), c_str), None => ffi::gtk_tool_button_new(ptr::null_mut(), c_str) } }) }, None => { match icon_widget { Some(i) => ffi::gtk_tool_button_new(i.get_widget(), ptr::null()), None => ffi::gtk_tool_button_new(ptr::null_mut(), ptr::null()) } } } }; check_pointer!(tmp_pointer, ToolButton) } pub fn new_from_stock(stock_id: &str) -> Option<ToolButton> { let tmp_pointer = stock_id.with_c_str(|c_str| { unsafe { ffi::gtk_tool_button_new_from_stock(c_str) } }); check_pointer!(tmp_pointer, ToolButton) } } impl_drop!(ToolButton) impl_TraitWidget!(ToolButton) impl gtk::ContainerTrait for ToolButton {} impl gtk::BinTrait for ToolButton {} impl gtk::ToolItemTrait for ToolButton {} impl gtk::ToolButtonTrait for ToolButton {} impl_widget_events!(ToolButton) impl_button_events!(ToolButton)
zploskey/rgtk
src/gtk/widgets/toolbutton.rs
Rust
lgpl-3.0
2,306
[ 30522, 1013, 1013, 2023, 5371, 2003, 2112, 1997, 1054, 13512, 2243, 1012, 1013, 1013, 1013, 1013, 1054, 13512, 2243, 2003, 2489, 4007, 1024, 2017, 2064, 2417, 2923, 3089, 8569, 2618, 2009, 1998, 1013, 2030, 19933, 1013, 1013, 2009, 2104, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
# Plantago nivalis Jord. SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Plantaginaceae/Plantago/Plantago nivalis/README.md
Markdown
apache-2.0
172
[ 30522, 1001, 3269, 23692, 9152, 10175, 2483, 8183, 4103, 1012, 2427, 1001, 1001, 1001, 1001, 3570, 3970, 1001, 1001, 1001, 1001, 2429, 2000, 2248, 3269, 3415, 5950, 1001, 1001, 1001, 1001, 2405, 1999, 19701, 1001, 1001, 1001, 1001, 2434, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* * Licensed to Metamarkets Group Inc. (Metamarkets) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. Metamarkets 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 io.druid.query.timeboundary; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableMap; import io.druid.jackson.DefaultObjectMapper; import io.druid.query.Druids; import io.druid.query.Query; import org.junit.Assert; import org.junit.Test; import java.io.IOException; public class TimeBoundaryQueryTest { private static final ObjectMapper jsonMapper = new DefaultObjectMapper(); @Test public void testQuerySerialization() throws IOException { Query query = Druids.newTimeBoundaryQueryBuilder() .dataSource("testing") .build(); String json = jsonMapper.writeValueAsString(query); Query serdeQuery = jsonMapper.readValue(json, Query.class); Assert.assertEquals(query, serdeQuery); } @Test public void testContextSerde() throws Exception { final TimeBoundaryQuery query = Druids.newTimeBoundaryQueryBuilder() .dataSource("foo") .intervals("2013/2014") .context( ImmutableMap.<String, Object>of( "priority", 1, "useCache", true, "populateCache", true, "finalize", true ) ).build(); final ObjectMapper mapper = new DefaultObjectMapper(); final TimeBoundaryQuery serdeQuery = mapper.readValue( mapper.writeValueAsBytes( mapper.readValue( mapper.writeValueAsString( query ), TimeBoundaryQuery.class ) ), TimeBoundaryQuery.class ); Assert.assertEquals(1, serdeQuery.getContextValue("priority")); Assert.assertEquals(true, serdeQuery.getContextValue("useCache")); Assert.assertEquals(true, serdeQuery.getContextValue("populateCache")); Assert.assertEquals(true, serdeQuery.getContextValue("finalize")); } @Test public void testContextSerde2() throws Exception { final TimeBoundaryQuery query = Druids.newTimeBoundaryQueryBuilder() .dataSource("foo") .intervals("2013/2014") .context( ImmutableMap.<String, Object>of( "priority", "1", "useCache", "true", "populateCache", "true", "finalize", "true" ) ).build(); final ObjectMapper mapper = new DefaultObjectMapper(); final TimeBoundaryQuery serdeQuery = mapper.readValue( mapper.writeValueAsBytes( mapper.readValue( mapper.writeValueAsString( query ), TimeBoundaryQuery.class ) ), TimeBoundaryQuery.class ); Assert.assertEquals("1", serdeQuery.getContextValue("priority")); Assert.assertEquals("true", serdeQuery.getContextValue("useCache")); Assert.assertEquals("true", serdeQuery.getContextValue("populateCache")); Assert.assertEquals("true", serdeQuery.getContextValue("finalize")); } }
fjy/druid
processing/src/test/java/io/druid/query/timeboundary/TimeBoundaryQueryTest.java
Java
apache-2.0
4,859
[ 30522, 1013, 1008, 1008, 7000, 2000, 18804, 20285, 2015, 2177, 4297, 1012, 1006, 18804, 20285, 2015, 1007, 2104, 2028, 1008, 2030, 2062, 12130, 6105, 10540, 1012, 2156, 1996, 5060, 5371, 1008, 5500, 2007, 2023, 2147, 2005, 3176, 2592, 1008,...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<?php use Symfony\Component\Translation\MessageCatalogue; $catalogue = new MessageCatalogue('en', array ( )); return $catalogue;
marcosjavier/tfa
app/cache/dev/translations/catalogue.en.php
PHP
mit
134
[ 30522, 1026, 1029, 25718, 2224, 25353, 2213, 14876, 4890, 1032, 6922, 1032, 5449, 1032, 4471, 11266, 23067, 9077, 1025, 1002, 10161, 1027, 2047, 4471, 11266, 23067, 9077, 1006, 1005, 4372, 1005, 1010, 9140, 1006, 1007, 1007, 1025, 2709, 100...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
# Calostephane marlothiana O.Hoffm. SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Calostephane marlothiana/README.md
Markdown
apache-2.0
183
[ 30522, 1001, 10250, 14122, 13699, 28006, 9388, 10994, 14204, 2050, 1051, 1012, 7570, 4246, 2213, 1012, 2427, 1001, 1001, 1001, 1001, 3570, 3970, 1001, 1001, 1001, 1001, 2429, 2000, 2248, 3269, 3415, 5950, 1001, 1001, 1001, 1001, 2405, 1999,...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CommaExcess.Algae.Graphics { /// <summary> /// Defines a compiled material pass. /// </summary> interface ICompiledMaterialPass { /// <summary> /// Begins rendering the material pass. /// </summary> void Begin(); /// <summary> /// Applies any changes. /// </summary> void Apply(); /// <summary> /// Sets a parameter. /// </summary> /// <param name="parameter">The parameter.</param> /// <param name="value">The value.</param> void SetValue(string parameter, float value); /// <summary> /// Sets a parameter. /// </summary> /// <param name="parameter">The parameter.</param> /// <param name="value">The value.</param> void SetValue(string parameter, int value); /// <summary> /// Sets a parameter. /// </summary> /// <param name="parameter">The parameter.</param> /// <param name="value">The value.</param> void SetValue(string parameter, Vector2 value); /// <summary> /// Sets a parameter. /// </summary> /// <param name="parameter">The parameter.</param> /// <param name="value">The value.</param> void SetValue(string parameter, Vector3 value); /// <summary> /// Sets a parameter. /// </summary> /// <param name="parameter">The parameter.</param> /// <param name="value">The value.</param> void SetValue(string parameter, Vector4 value); /// <summary> /// Sets a parameter. /// </summary> /// <param name="parameter">The parameter.</param> /// <param name="value">The value.</param> void SetValue(string parameter, Matrix value); /// <summary> /// Seta a parameter. /// </summary> /// <param name="parameter">The parameter.</param> /// <param name="texture">The value.</param> void SetValue(string parameter, Texture texture); /// <summary> /// Ends the material pass. /// </summary> void End(); } /// <summary> /// Defines a compiled material. /// </summary> interface ICompiledMaterial : IEnumerable<ICompiledMaterialPass>, IDisposable { /// <summary> /// Gets the pass at the provided index. /// </summary> /// <param name="index">The index.</param> /// <returns>The pass.</returns> ICompiledMaterialPass this[int index] { get; } /// <summary> /// Gets the total amount of passes. /// </summary> int Count { get; } /// <summary> /// Uses the material. Call this before drawing a pass. /// </summary> void Use(); } }
aaronbolyard/Algae.Canvas
Source/Algae/Graphics/ICompiledMaterial.cs
C#
mit
2,495
[ 30522, 2478, 2291, 1025, 2478, 2291, 1012, 6407, 1012, 12391, 1025, 2478, 2291, 1012, 11409, 4160, 1025, 2478, 2291, 1012, 3793, 1025, 3415, 15327, 4012, 2863, 10288, 9623, 2015, 1012, 18670, 1012, 8389, 1063, 1013, 1013, 1013, 1026, 12654,...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* * Copyright 2015 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #ifndef GrVkRenderTarget_DEFINED #define GrVkRenderTarget_DEFINED #include "src/gpu/GrRenderTarget.h" #include "src/gpu/vk/GrVkImage.h" #include "include/gpu/vk/GrVkTypes.h" #include "src/gpu/vk/GrVkRenderPass.h" #include "src/gpu/vk/GrVkResourceProvider.h" class GrVkCommandBuffer; class GrVkFramebuffer; class GrVkGpu; class GrVkImageView; class GrVkSecondaryCommandBuffer; class GrVkStencilAttachment; struct GrVkImageInfo; #ifdef SK_BUILD_FOR_WIN // Windows gives bogus warnings about inheriting asTexture/asRenderTarget via dominance. #pragma warning(push) #pragma warning(disable: 4250) #endif class GrVkRenderTarget: public GrRenderTarget, public virtual GrVkImage { public: static sk_sp<GrVkRenderTarget> MakeWrappedRenderTarget(GrVkGpu*, const GrSurfaceDesc&, int sampleCnt, const GrVkImageInfo&, sk_sp<GrVkImageLayout>); static sk_sp<GrVkRenderTarget> MakeSecondaryCBRenderTarget(GrVkGpu*, const GrSurfaceDesc&, const GrVkDrawableInfo& vkInfo); ~GrVkRenderTarget() override; GrBackendFormat backendFormat() const override { return this->getBackendFormat(); } const GrVkFramebuffer* framebuffer() const { return fFramebuffer; } const GrVkImageView* colorAttachmentView() const { return fColorAttachmentView; } const GrVkResource* msaaImageResource() const { if (fMSAAImage) { return fMSAAImage->fResource; } return nullptr; } GrVkImage* msaaImage() { return fMSAAImage.get(); } const GrVkImageView* resolveAttachmentView() const { return fResolveAttachmentView; } const GrVkResource* stencilImageResource() const; const GrVkImageView* stencilAttachmentView() const; const GrVkRenderPass* simpleRenderPass() const { return fCachedSimpleRenderPass; } GrVkResourceProvider::CompatibleRPHandle compatibleRenderPassHandle() const { SkASSERT(!this->wrapsSecondaryCommandBuffer()); return fCompatibleRPHandle; } const GrVkRenderPass* externalRenderPass() const { SkASSERT(this->wrapsSecondaryCommandBuffer()); // We use the cached simple render pass to hold the external render pass. return fCachedSimpleRenderPass; } bool wrapsSecondaryCommandBuffer() const { return fSecondaryCommandBuffer != VK_NULL_HANDLE; } VkCommandBuffer getExternalSecondaryCommandBuffer() const { return fSecondaryCommandBuffer; } bool canAttemptStencilAttachment() const override { // We don't know the status of the stencil attachment for wrapped external secondary command // buffers so we just assume we don't have one. return !this->wrapsSecondaryCommandBuffer(); } GrBackendRenderTarget getBackendRenderTarget() const override; void getAttachmentsDescriptor(GrVkRenderPass::AttachmentsDescriptor* desc, GrVkRenderPass::AttachmentFlags* flags) const; void addResources(GrVkCommandBuffer& commandBuffer) const; protected: GrVkRenderTarget(GrVkGpu* gpu, const GrSurfaceDesc& desc, int sampleCnt, const GrVkImageInfo& info, sk_sp<GrVkImageLayout> layout, const GrVkImageInfo& msaaInfo, sk_sp<GrVkImageLayout> msaaLayout, const GrVkImageView* colorAttachmentView, const GrVkImageView* resolveAttachmentView, GrBackendObjectOwnership); GrVkRenderTarget(GrVkGpu* gpu, const GrSurfaceDesc& desc, const GrVkImageInfo& info, sk_sp<GrVkImageLayout> layout, const GrVkImageView* colorAttachmentView, GrBackendObjectOwnership); GrVkGpu* getVkGpu() const; void onAbandon() override; void onRelease() override; // This accounts for the texture's memory and any MSAA renderbuffer's memory. size_t onGpuMemorySize() const override { int numColorSamples = this->numSamples(); if (numColorSamples > 1) { // Add one to account for the resolved VkImage. numColorSamples += 1; } const GrCaps& caps = *this->getGpu()->caps(); return GrSurface::ComputeSize(caps, this->backendFormat(), this->width(), this->height(), numColorSamples, GrMipMapped::kNo); } void createFramebuffer(GrVkGpu* gpu); const GrVkImageView* fColorAttachmentView; std::unique_ptr<GrVkImage> fMSAAImage; const GrVkImageView* fResolveAttachmentView; private: GrVkRenderTarget(GrVkGpu* gpu, const GrSurfaceDesc& desc, int sampleCnt, const GrVkImageInfo& info, sk_sp<GrVkImageLayout> layout, const GrVkImageInfo& msaaInfo, sk_sp<GrVkImageLayout> msaaLayout, const GrVkImageView* colorAttachmentView, const GrVkImageView* resolveAttachmentView); GrVkRenderTarget(GrVkGpu* gpu, const GrSurfaceDesc& desc, const GrVkImageInfo& info, sk_sp<GrVkImageLayout> layout, const GrVkImageView* colorAttachmentView); GrVkRenderTarget(GrVkGpu* gpu, const GrSurfaceDesc& desc, const GrVkImageInfo& info, sk_sp<GrVkImageLayout> layout, const GrVkRenderPass* renderPass, VkCommandBuffer secondaryCommandBuffer); bool completeStencilAttachment() override; // In Vulkan we call the release proc after we are finished with the underlying // GrVkImage::Resource object (which occurs after the GPU has finished all work on it). void onSetRelease(sk_sp<GrRefCntedCallback> releaseHelper) override { // Forward the release proc on to GrVkImage this->setResourceRelease(std::move(releaseHelper)); } void releaseInternalObjects(); void abandonInternalObjects(); const GrVkFramebuffer* fFramebuffer; // This is a cached pointer to a simple render pass. The render target should unref it // once it is done with it. const GrVkRenderPass* fCachedSimpleRenderPass; // This is a handle to be used to quickly get compatible GrVkRenderPasses for this render target GrVkResourceProvider::CompatibleRPHandle fCompatibleRPHandle; // If this render target wraps an external VkCommandBuffer, then this handle will be that // VkCommandBuffer and not VK_NULL_HANDLE. In this case the render target will not be backed by // an actual VkImage and will thus be limited in terms of what it can be used for. VkCommandBuffer fSecondaryCommandBuffer = VK_NULL_HANDLE; }; #endif
youtube/cobalt
third_party/skia/src/gpu/vk/GrVkRenderTarget.h
C
bsd-3-clause
7,180
[ 30522, 1013, 1008, 1008, 9385, 2325, 8224, 4297, 1012, 1008, 1008, 2224, 1997, 2023, 3120, 3642, 2003, 9950, 2011, 1037, 18667, 2094, 1011, 2806, 6105, 2008, 2064, 2022, 1008, 2179, 1999, 1996, 6105, 5371, 1012, 1008, 1013, 1001, 2065, 13...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<?php /** * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Cloud_StorageService * @subpackage Adapter * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ require_once 'Zend/Cloud/StorageService/Adapter.php'; require_once 'Zend/Cloud/StorageService/Exception.php'; require_once 'Zend/Service/Rackspace/File.php'; require_once 'Zend/Service/Rackspace/Exception.php'; /** * Adapter for Rackspace cloud storage * * @category Zend * @package Zend_Cloud_StorageService * @subpackage Adapter * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Cloud_StorageService_Adapter_Rackspace implements Zend_Cloud_StorageService_Adapter { const USER = 'user'; const API_KEY = 'key'; const REMOTE_CONTAINER = 'container'; const DELETE_METADATA_KEY = 'ZF_metadata_deleted'; /** * The Rackspace adapter * @var Zend_Service_Rackspace_File */ protected $_rackspace; /** * Container in which files are stored * @var string */ protected $_container = 'default'; /** * Constructor * * @param array|Traversable $options * @return void */ function __construct($options = array()) { if ($options instanceof Zend_Config) { $options = $options->toArray(); } if (!is_array($options) || empty($options)) { throw new Zend_Cloud_StorageService_Exception('Invalid options provided'); } try { $this->_rackspace = new Zend_Service_Rackspace_File($options[self::USER], $options[self::API_KEY]); } catch (Zend_Service_Rackspace_Exception $e) { throw new Zend_Cloud_StorageService_Exception('Error on create: '.$e->getMessage(), $e->getCode(), $e); } if (isset($options[self::HTTP_ADAPTER])) { $this->_rackspace->getHttpClient()->setAdapter($options[self::HTTP_ADAPTER]); } if (!empty($options[self::REMOTE_CONTAINER])) { $this->_container = $options[self::REMOTE_CONTAINER]; } } /** * Get an item from the storage service. * * @param string $path * @param array $options * @return mixed */ public function fetchItem($path, $options = null) { $item = $this->_rackspace->getObject($this->_container,$path, $options); if (!$this->_rackspace->isSuccessful() && ($this->_rackspace->getErrorCode()!='404')) { throw new Zend_Cloud_StorageService_Exception('Error on fetch: '.$this->_rackspace->getErrorMsg()); } if (!empty($item)) { return $item->getContent(); } else { return false; } } /** * Store an item in the storage service. * * @param string $destinationPath * @param mixed $data * @param array $options * @return void */ public function storeItem($destinationPath, $data, $options = null) { $this->_rackspace->storeObject($this->_container,$destinationPath,$data,$options); if (!$this->_rackspace->isSuccessful()) { throw new Zend_Cloud_StorageService_Exception('Error on store: '.$this->_rackspace->getErrorMsg()); } } /** * Delete an item in the storage service. * * @param string $path * @param array $options * @return void */ public function deleteItem($path, $options = null) { $this->_rackspace->deleteObject($this->_container,$path); if (!$this->_rackspace->isSuccessful()) { throw new Zend_Cloud_StorageService_Exception('Error on delete: '.$this->_rackspace->getErrorMsg()); } } /** * Copy an item in the storage service to a given path. * * @param string $sourcePath * @param string $destination path * @param array $options * @return void */ public function copyItem($sourcePath, $destinationPath, $options = null) { $this->_rackspace->copyObject($this->_container,$sourcePath,$this->_container,$destinationPath,$options); if (!$this->_rackspace->isSuccessful()) { throw new Zend_Cloud_StorageService_Exception('Error on copy: '.$this->_rackspace->getErrorMsg()); } } /** * Move an item in the storage service to a given path. * WARNING: This operation is *very* expensive for services that do not * support moving an item natively. * * @param string $sourcePath * @param string $destination path * @param array $options * @return void */ public function moveItem($sourcePath, $destinationPath, $options = null) { try { $this->copyItem($sourcePath, $destinationPath, $options); } catch (Zend_Service_Rackspace_Exception $e) { throw new Zend_Cloud_StorageService_Exception('Error on move: '.$e->getMessage()); } try { $this->deleteItem($sourcePath); } catch (Zend_Service_Rackspace_Exception $e) { $this->deleteItem($destinationPath); throw new Zend_Cloud_StorageService_Exception('Error on move: '.$e->getMessage()); } } /** * Rename an item in the storage service to a given name. * * @param string $path * @param string $name * @param array $options * @return void */ public function renameItem($path, $name, $options = null) { require_once 'Zend/Cloud/OperationNotAvailableException.php'; throw new Zend_Cloud_OperationNotAvailableException('Renaming not implemented'); } /** * Get a key/value array of metadata for the given path. * * @param string $path * @param array $options * @return array An associative array of key/value pairs specifying the metadata for this object. * If no metadata exists, an empty array is returned. */ public function fetchMetadata($path, $options = null) { $result = $this->_rackspace->getMetadataObject($this->_container,$path); if (!$this->_rackspace->isSuccessful()) { throw new Zend_Cloud_StorageService_Exception('Error on fetch metadata: '.$this->_rackspace->getErrorMsg()); } $metadata = array(); if (isset($result['metadata'])) { $metadata = $result['metadata']; } // delete the self::DELETE_METADATA_KEY - this is a trick to remove all // the metadata information of an object (see deleteMetadata). // Rackspace doesn't have an API to remove the metadata of an object unset($metadata[self::DELETE_METADATA_KEY]); return $metadata; } /** * Store a key/value array of metadata at the given path. * WARNING: This operation overwrites any metadata that is located at * $destinationPath. * * @param string $destinationPath * @param array $metadata associative array specifying the key/value pairs for the metadata. * @param array $options * @return void */ public function storeMetadata($destinationPath, $metadata, $options = null) { $this->_rackspace->setMetadataObject($this->_container, $destinationPath, $metadata); if (!$this->_rackspace->isSuccessful()) { throw new Zend_Cloud_StorageService_Exception('Error on store metadata: '.$this->_rackspace->getErrorMsg()); } } /** * Delete a key/value array of metadata at the given path. * * @param string $path * @param array $metadata - An associative array specifying the key/value pairs for the metadata * to be deleted. If null, all metadata associated with the object will * be deleted. * @param array $options * @return void */ public function deleteMetadata($path, $metadata = null, $options = null) { if (empty($metadata)) { $newMetadata = array(self::DELETE_METADATA_KEY => true); try { $this->storeMetadata($path, $newMetadata); } catch (Zend_Service_Rackspace_Exception $e) { throw new Zend_Cloud_StorageService_Exception('Error on delete metadata: '.$e->getMessage()); } } else { try { $oldMetadata = $this->fetchMetadata($path); } catch (Zend_Service_Rackspace_Exception $e) { throw new Zend_Cloud_StorageService_Exception('Error on delete metadata: '.$e->getMessage()); } $newMetadata = array_diff_assoc($oldMetadata, $metadata); try { $this->storeMetadata($path, $newMetadata); } catch (Zend_Service_Rackspace_Exception $e) { throw new Zend_Cloud_StorageService_Exception('Error on delete metadata: '.$e->getMessage()); } } } /* * Recursively traverse all the folders and build an array that contains * the path names for each folder. * * @param string $path folder path to get the list of folders from. * @param array& $resultArray reference to the array that contains the path names * for each folder. * @return void */ private function getAllFolders($path, &$resultArray) { if (!empty($path)) { $options = array ( 'prefix' => $path ); } $files = $this->_rackspace->getObjects($this->_container,$options); if (!$this->_rackspace->isSuccessful()) { throw new Zend_Cloud_StorageService_Exception('Error on get all folders: '.$this->_rackspace->getErrorMsg()); } $resultArray = array(); foreach ($files as $file) { $resultArray[dirname($file->getName())] = true; } $resultArray = array_keys($resultArray); } /** * Return an array of the items contained in the given path. The items * returned are the files or objects that in the specified path. * * @param string $path * @param array $options * @return array */ public function listItems($path, $options = null) { if (!empty($path)) { $options = array ( 'prefix' => $path ); } $files = $this->_rackspace->getObjects($this->_container,$options); if (!$this->_rackspace->isSuccessful()) { throw new Zend_Cloud_StorageService_Exception('Error on list items: '.$this->_rackspace->getErrorMsg()); } $resultArray = array(); if (!empty($files)) { foreach ($files as $file) { $resultArray[] = $file->getName(); } } return $resultArray; } /** * Get the concrete client. * * @return Zend_Service_Rackspace_File */ public function getClient() { return $this->_rackspace; } }
Riges/KawaiViewModel
www/libs/Zend/Cloud/StorageService/Adapter/Rackspace.php
PHP
bsd-3-clause
12,075
[ 30522, 1026, 1029, 25718, 1013, 1008, 1008, 1008, 6105, 1008, 1008, 2023, 3120, 5371, 2003, 3395, 2000, 1996, 2047, 18667, 2094, 6105, 2008, 2003, 24378, 1008, 2007, 2023, 7427, 1999, 1996, 5371, 6105, 1012, 19067, 2102, 1012, 1008, 2009, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/** * File ./src/main/java/de/lemo/dms/connectors/lemo_0_8/mapping/LevelCourseLMS.java * Lemo-Data-Management-Server for learning analytics. * Copyright (C) 2015 * Leonard Kappe, Andreas Pursian, Sebastian Schwarzrock, Boris Wenzlaff * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ /** * File ./src/main/java/de/lemo/dms/connectors/lemo_0_8/mapping/LevelCourseLMS.java * Date 2015-01-05 * Project Lemo Learning Analytics */ package de.lemo.dms.connectors.lemo_0_8.mapping; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; /** * Represanting an object of the level of an hierarchy * @author Sebastian Schwarzrock * */ @Entity @Table(name = "level_course") public class LevelCourseLMS{ private long id; private long course; private long level; private Long platform; /** * standard getter for the attribute id * * @return the identifier for the association between department and resource */ @Id public long getId() { return this.id; } /** * standard setter for the attribute id * * @param id * the identifier for the association between department and resource */ public void setId(final long id) { this.id = id; } /** * standard getter for the attribute * * @return a department in which the resource is used */ @Column(name="course_id") public long getCourse() { return this.course; } public void setCourse(final long course) { this.course = course; } @Column(name="level_id") public long getLevel() { return this.level; } public void setLevel(final long degree) { this.level = degree; } @Column(name="platform") public Long getPlatform() { return this.platform; } public void setPlatform(final Long platform) { this.platform = platform; } }
LemoProject/Lemo-Data-Management-Server
src/main/java/de/lemo/dms/connectors/lemo_0_8/mapping/LevelCourseLMS.java
Java
gpl-3.0
2,522
[ 30522, 1013, 1008, 1008, 1008, 5371, 1012, 1013, 5034, 2278, 1013, 2364, 1013, 9262, 1013, 2139, 1013, 3393, 5302, 1013, 1040, 5244, 1013, 19400, 2015, 1013, 3393, 5302, 1035, 1014, 1035, 1022, 1013, 12375, 1013, 2504, 3597, 28393, 13728, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
from twitter_rec import Api import time USERNAME = "liaoyisheng89@sina.com" PASSWD = "bigdata" s = Api.Session(USERNAME, PASSWD, debug=False) s.connect() counter = 0 while True: _ = s.read("/AllenboChina/followers") if "eason" in _: print counter counter += 1 else: assert False
WeakGroup/twitter-rec
test/test_block.py
Python
gpl-2.0
304
[ 30522, 2013, 10474, 1035, 28667, 12324, 17928, 12324, 2051, 5310, 18442, 1027, 1000, 22393, 6977, 4509, 13159, 2620, 2683, 1030, 8254, 2050, 1012, 4012, 1000, 3413, 21724, 1027, 1000, 2502, 2850, 2696, 1000, 1055, 1027, 17928, 1012, 5219, 1...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
package org.openbase.bco.device.openhab.communication; /*- * #%L * BCO Openhab Device Manager * %% * Copyright (C) 2015 - 2021 openbase.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 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/gpl-3.0.html>. * #L% */ import com.google.gson.*; import org.eclipse.smarthome.core.internal.service.CommandDescriptionServiceImpl; import org.eclipse.smarthome.core.internal.types.CommandDescriptionImpl; import org.eclipse.smarthome.core.types.CommandDescription; import org.eclipse.smarthome.core.types.CommandDescriptionBuilder; import org.eclipse.smarthome.core.types.CommandOption; import org.openbase.bco.device.openhab.jp.JPOpenHABURI; import org.openbase.jps.core.JPService; import org.openbase.jps.exception.JPNotAvailableException; import org.openbase.jul.exception.InstantiationException; import org.openbase.jul.exception.*; import org.openbase.jul.exception.printer.ExceptionPrinter; import org.openbase.jul.exception.printer.LogLevel; import org.openbase.jul.iface.Shutdownable; import org.openbase.jul.pattern.Observable; import org.openbase.jul.pattern.ObservableImpl; import org.openbase.jul.pattern.Observer; import org.openbase.jul.schedule.GlobalScheduledExecutorService; import org.openbase.jul.schedule.SyncObject; import org.openbase.type.domotic.state.ConnectionStateType.ConnectionState; import org.openbase.type.domotic.state.ConnectionStateType.ConnectionState.State; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.ProcessingException; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.sse.InboundSseEvent; import javax.ws.rs.sse.SseEventSource; import java.lang.reflect.Type; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; public abstract class OpenHABRestConnection implements Shutdownable { public static final String SEPARATOR = "/"; public static final String REST_TARGET = "rest"; public static final String APPROVE_TARGET = "approve"; public static final String EVENTS_TARGET = "events"; public static final String TOPIC_KEY = "topic"; public static final String TOPIC_SEPARATOR = SEPARATOR; private static final Logger LOGGER = LoggerFactory.getLogger(OpenHABRestConnection.class); private final SyncObject topicObservableMapLock = new SyncObject("topicObservableMapLock"); private final SyncObject connectionStateSyncLock = new SyncObject("connectionStateSyncLock"); private final Map<String, ObservableImpl<Object, JsonObject>> topicObservableMap; private final Client restClient; private final WebTarget restTarget; private SseEventSource sseSource; private boolean shutdownInitiated = false; protected final JsonParser jsonParser; protected final Gson gson; private ScheduledFuture<?> connectionTask; protected ConnectionState.State openhabConnectionState = State.DISCONNECTED; public OpenHABRestConnection() throws InstantiationException { try { this.topicObservableMap = new HashMap<>(); this.gson = new GsonBuilder().setExclusionStrategies(new ExclusionStrategy() { @Override public boolean shouldSkipField(FieldAttributes fieldAttributes) { return false; } @Override public boolean shouldSkipClass(Class<?> aClass) { // ignore Command Description because its an interface and can not be serialized without any instance creator. if(aClass.equals(CommandDescription.class)) { return true; } return false; } }).create(); this.jsonParser = new JsonParser(); this.restClient = ClientBuilder.newClient(); this.restTarget = restClient.target(JPService.getProperty(JPOpenHABURI.class).getValue().resolve(SEPARATOR + REST_TARGET)); this.setConnectState(State.CONNECTING); } catch (JPNotAvailableException ex) { throw new InstantiationException(this, ex); } } private boolean isTargetReachable() { try { testConnection(); } catch (CouldNotPerformException e) { if (e.getCause() instanceof ProcessingException) { return false; } } return true; } protected abstract void testConnection() throws CouldNotPerformException; public void waitForConnectionState(final ConnectionState.State connectionState, final long timeout, final TimeUnit timeUnit) throws InterruptedException { synchronized (connectionStateSyncLock) { while (getOpenhabConnectionState() != connectionState) { connectionStateSyncLock.wait(timeUnit.toMillis(timeout)); } } } public void waitForConnectionState(final ConnectionState.State connectionState) throws InterruptedException { synchronized (connectionStateSyncLock) { while (getOpenhabConnectionState() != connectionState) { connectionStateSyncLock.wait(); } } } private void setConnectState(final ConnectionState.State connectState) { synchronized (connectionStateSyncLock) { // filter non changing states if (connectState == this.openhabConnectionState) { return; } LOGGER.trace("Openhab Connection State changed to: "+connectState); // update state this.openhabConnectionState = connectState; // handle state change switch (connectState) { case CONNECTING: LOGGER.info("Wait for openHAB..."); try { connectionTask = GlobalScheduledExecutorService.scheduleWithFixedDelay(() -> { if (isTargetReachable()) { // set connected setConnectState(State.CONNECTED); // cleanup own task connectionTask.cancel(false); } }, 0, 15, TimeUnit.SECONDS); } catch (NotAvailableException | RejectedExecutionException ex) { // if global executor service is not available we have no chance to connect. LOGGER.warn("Wait for openHAB...", ex); setConnectState(State.DISCONNECTED); } break; case CONNECTED: LOGGER.info("Connection to OpenHAB established."); initSSE(); break; case RECONNECTING: LOGGER.warn("Connection to OpenHAB lost!"); resetConnection(); setConnectState(State.CONNECTING); break; case DISCONNECTED: LOGGER.info("Connection to OpenHAB closed."); resetConnection(); break; } // notify state change connectionStateSyncLock.notifyAll(); // apply next state if required switch (connectState) { case RECONNECTING: setConnectState(State.CONNECTING); break; } } } private void initSSE() { // activate sse source if not already done if (sseSource != null) { LOGGER.warn("SSE already initialized!"); return; } final WebTarget webTarget = restTarget.path(EVENTS_TARGET); sseSource = SseEventSource.target(webTarget).reconnectingEvery(15, TimeUnit.SECONDS).build(); sseSource.open(); final Consumer<InboundSseEvent> evenConsumer = inboundSseEvent -> { // dispatch event try { final JsonObject payload = jsonParser.parse(inboundSseEvent.readData()).getAsJsonObject(); for (Entry<String, ObservableImpl<Object, JsonObject>> topicObserverEntry : topicObservableMap.entrySet()) { try { if (payload.get(TOPIC_KEY).getAsString().matches(topicObserverEntry.getKey())) { topicObserverEntry.getValue().notifyObservers(payload); } } catch (Exception ex) { ExceptionPrinter.printHistory(new CouldNotPerformException("Could not notify listeners on topic[" + topicObserverEntry.getKey() + "]", ex), LOGGER); } } } catch (Exception ex) { ExceptionPrinter.printHistory(new CouldNotPerformException("Could not handle SSE payload!", ex), LOGGER); } }; final Consumer<Throwable> errorHandler = ex -> { ExceptionPrinter.printHistory("Openhab connection error detected!", ex, LOGGER, LogLevel.DEBUG); checkConnectionState(); }; final Runnable reconnectHandler = () -> { checkConnectionState(); }; sseSource.register(evenConsumer, errorHandler, reconnectHandler); } public State getOpenhabConnectionState() { return openhabConnectionState; } public void checkConnectionState() { synchronized (connectionStateSyncLock) { // only validate if connected if (!isConnected()) { return; } // if not reachable init a reconnect if (!isTargetReachable()) { setConnectState(State.RECONNECTING); } } } public boolean isConnected() { return getOpenhabConnectionState() == State.CONNECTED; } public void addSSEObserver(Observer<Object, JsonObject> observer) { addSSEObserver(observer, ""); } public void addSSEObserver(final Observer<Object, JsonObject> observer, final String topicRegex) { synchronized (topicObservableMapLock) { if (topicObservableMap.containsKey(topicRegex)) { topicObservableMap.get(topicRegex).addObserver(observer); return; } final ObservableImpl<Object, JsonObject> observable = new ObservableImpl<>(this); observable.addObserver(observer); topicObservableMap.put(topicRegex, observable); } } public void removeSSEObserver(Observer<Object, JsonObject> observer) { removeSSEObserver(observer, ""); } public void removeSSEObserver(Observer<Object, JsonObject> observer, final String topicFilter) { synchronized (topicObservableMapLock) { if (topicObservableMap.containsKey(topicFilter)) { topicObservableMap.get(topicFilter).removeObserver(observer); } } } private void resetConnection() { // cancel ongoing connection task if (!connectionTask.isDone()) { connectionTask.cancel(false); } // close sse if (sseSource != null) { sseSource.close(); sseSource = null; } } public void validateConnection() throws CouldNotPerformException { if (!isConnected()) { throw new InvalidStateException("Openhab not reachable yet!"); } } private String validateResponse(final Response response) throws CouldNotPerformException, ProcessingException { return validateResponse(response, false); } private String validateResponse(final Response response, final boolean skipConnectionValidation) throws CouldNotPerformException, ProcessingException { final String result = response.readEntity(String.class); if (response.getStatus() == 200 || response.getStatus() == 201 || response.getStatus() == 202) { return result; } else if (response.getStatus() == 404) { if (!skipConnectionValidation) { checkConnectionState(); } throw new NotAvailableException("URL"); } else if (response.getStatus() == 503) { if (!skipConnectionValidation) { checkConnectionState(); } // throw a processing exception to indicate that openHAB is still not fully started, this is used to wait for openHAB throw new ProcessingException("OpenHAB server not ready"); } else { throw new CouldNotPerformException("Response returned with ErrorCode[" + response.getStatus() + "], Result[" + result + "] and ErrorMessage[" + response.getStatusInfo().getReasonPhrase() + "]"); } } protected String get(final String target) throws CouldNotPerformException { return get(target, false); } protected String get(final String target, final boolean skipValidation) throws CouldNotPerformException { try { // handle validation if (!skipValidation) { validateConnection(); } final WebTarget webTarget = restTarget.path(target); final Response response = webTarget.request().get(); return validateResponse(response, skipValidation); } catch (CouldNotPerformException | ProcessingException ex) { if (isShutdownInitiated()) { ExceptionProcessor.setInitialCause(ex, new ShutdownInProgressException(this)); } throw new CouldNotPerformException("Could not get sub-URL[" + target + "]", ex); } } protected String delete(final String target) throws CouldNotPerformException { try { validateConnection(); final WebTarget webTarget = restTarget.path(target); final Response response = webTarget.request().delete(); return validateResponse(response); } catch (CouldNotPerformException | ProcessingException ex) { if (isShutdownInitiated()) { ExceptionProcessor.setInitialCause(ex, new ShutdownInProgressException(this)); } throw new CouldNotPerformException("Could not delete sub-URL[" + target + "]", ex); } } protected String putJson(final String target, final Object value) throws CouldNotPerformException { return put(target, gson.toJson(value), MediaType.APPLICATION_JSON_TYPE); } protected String put(final String target, final String value, final MediaType mediaType) throws CouldNotPerformException { try { validateConnection(); final WebTarget webTarget = restTarget.path(target); final Response response = webTarget.request().put(Entity.entity(value, mediaType)); return validateResponse(response); } catch (CouldNotPerformException | ProcessingException ex) { if (isShutdownInitiated()) { ExceptionProcessor.setInitialCause(ex, new ShutdownInProgressException(this)); } throw new CouldNotPerformException("Could not put value[" + value + "] on sub-URL[" + target + "]", ex); } } protected String postJson(final String target, final Object value) throws CouldNotPerformException { return post(target, gson.toJson(value), MediaType.APPLICATION_JSON_TYPE); } protected String post(final String target, final String value, final MediaType mediaType) throws CouldNotPerformException { try { validateConnection(); final WebTarget webTarget = restTarget.path(target); final Response response = webTarget.request().post(Entity.entity(value, mediaType)); return validateResponse(response); } catch (CouldNotPerformException | ProcessingException ex) { if (isShutdownInitiated()) { ExceptionProcessor.setInitialCause(ex, new ShutdownInProgressException(this)); } throw new CouldNotPerformException("Could not post Value[" + value + "] of MediaType[" + mediaType + "] on sub-URL[" + target + "]", ex); } } public boolean isShutdownInitiated() { return shutdownInitiated; } @Override public void shutdown() { // prepare shutdown shutdownInitiated = true; setConnectState(State.DISCONNECTED); // stop rest service restClient.close(); // stop sse service synchronized (topicObservableMapLock) { for (final Observable<Object, JsonObject> jsonObjectObservable : topicObservableMap.values()) { jsonObjectObservable.shutdown(); } topicObservableMap.clear(); resetConnection(); } } }
DivineCooperation/bco.core-manager
openhab/src/main/java/org/openbase/bco/device/openhab/communication/OpenHABRestConnection.java
Java
lgpl-3.0
17,838
[ 30522, 7427, 8917, 1012, 2330, 15058, 1012, 4647, 2080, 1012, 5080, 1012, 2330, 25459, 1012, 4807, 1025, 1013, 1008, 1011, 1008, 1001, 1003, 1048, 1008, 4647, 2080, 2330, 25459, 5080, 3208, 1008, 1003, 1003, 1008, 9385, 1006, 1039, 1007, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
require 'xiki/mode' # Makes text in .deck files huge, and makes left and right arrow keys treat # headings as slides. class Deck def self.menu %` - .enable arrow keys/ - docs/ > Summary | Create a file with a ".deck" extension to create a lightweight | presentation. The left and right arrow keys will go back and forth | between the "slides". | | Make .deck files just like you make .notes files, with sections divided | by headings ("> foo" lines). The sections behave like slides. Only one | section is shown at a time. | > Keys | Use these keys to go back and forth between slides: | - right+arrow+key: show next slide (hiding everything else) | - left+arrow+key: show next slide | - custom+reminder: jump to corresponding heading at end | > Hints | To create and show hints that correspond to a section, create a section | near the bottom of the file with the same heading but starting with | ">>" instead of ">" | | Then, type open+related+heading to jump back and forth. | > To enable the deck keys in a .notes file - type: do+keys+deck - or use) @deck/enable arrow keys/ | ` end @@size = 10 def self.enable_arrow_keys options={} # If in an actual file, just enable for it if View.file $el.use_local_map $el.elvar.deck_mode_map return View.flash "- Enabling arrow keys" end last = View.files.find{|o| o =~ /\.notes$/} basename = File.basename(last) View.open last View.flash "- Enabling arrow keys!", :times=>4 unless options[:silent] $el.use_local_map $el.elvar.deck_mode_map end def self.keys # mode=:deck_mode_map return if ! $el $el.elvar.deck_mode_map = $el.make_sparse_keymap unless $el.boundp :deck_mode_map $el.set_keymap_parent $el.elvar.deck_mode_map, $el.elvar.notes_mode_map Keys.custom_reminder(:deck_mode_map) { Deck.open_related_heading } Keys.layout_uncover(:deck_mode_map) { View.status nil, :nth=>3 Hide.reveal } $el.define_key(:deck_mode_map, $el.kbd("<right>")) { Deck.right_arrow } $el.define_key(:deck_mode_map, $el.kbd("<left>")) { Deck.left_arrow } # TODO Get this to not add item at top of "Keys > Do" menu bar menu - how?! Keys.do_keys_deck { Deck.enable_arrow_keys } end def self.open_related_heading orig = Location.new was_hidden = View.hidden? Hide.reveal if was_hidden left, after_header, right = View.block_positions "^>" heading = View.txt left, after_header-1 delimeter = heading[/^>+/] delimeter.size > 1 ? heading.sub!(/./, '') : heading.sub!(/^/, '>') View.to_highest found = Search.forward "^#{$el.regexp_quote heading}$" if ! found orig.go return View.flash "- No related heading found" end Move.to_axis View.recenter_top Notes.narrow_block(:delimiter=>delimeter == ">" ? ">>" : ">") if was_hidden end def self.left_arrow Notes.narrow_block if ! View.hidden? # If not hidden, hide first, for simplicity column = View.column number = View.visible_line_number View.visible_line_number = 1 self.show_all Notes.to_block(:up) result = self.set_bars left, ignore, right = View.block_positions lines_in_block = Line.number(right) - Line.number(left) line = Line.number number = lines_in_block if number > lines_in_block View.line = line + number - 1 View.column = column Notes.narrow_block Effects.glow :fade_in=>1, :what=>:block if result[0] == 0 end def self.right_arrow Notes.narrow_block if ! View.hidden? # If not hidden, hide first, for simplicity column = View.column number = View.visible_line_number Move.backward if View.bottom == View.cursor # If at bottom of visible, back up one self.show_all Notes.to_block result = self.set_bars Notes.narrow_block View.visible_line_number = number View.column = column Effects.glow :fade_in=>1, :what=>:block if result[2] end # Sets little bars at bottom of window (mode line) def self.set_bars first_in_block = false my_line_number = View.line top_bar, bottom_bar = 0, 0 # remaining in group, remaining total header, header_match_count, my_header = nil, 0, nil View.txt.split("\n").each_with_index do |line, i| i = i + 1 is_header = line =~ /^> / if is_header if header == line # If same header as last header_match_count += 1 else header_match_count = 1 header = line end if my_header # If we found it, start accumulating top_bar += 1 if header == my_header bottom_bar += 1 end end # If line matched, remember it's this header if i == my_line_number # && ! my_line_number my_header = header first_in_block = true if header_match_count == 1 top_bar, bottom_bar = 0, 0 # remaining in group, remaining total end end View.status :bars=>[top_bar, bottom_bar] [top_bar, bottom_bar, first_in_block] end def self.init self.keys # Make deck mode happen for .deck files Mode.define(:deck, ".deck") do Notes.mode $el.use_local_map $el.elvar.deck_mode_map # Adds arrow keys onto notes map end end def self.show_all $el.widen Hide.show end end Deck.init # Define mode
kastner/xiki
menu/deck.rb
Ruby
mit
5,543
[ 30522, 5478, 1005, 8418, 3211, 1013, 5549, 1005, 1001, 3084, 3793, 1999, 1012, 5877, 6764, 4121, 1010, 1998, 3084, 2187, 1998, 2157, 8612, 6309, 7438, 1001, 5825, 2015, 2004, 14816, 1012, 2465, 5877, 13366, 2969, 1012, 12183, 1003, 1036, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
def load_keys(filepath): """ Loads the Twitter API keys into a dict. :param filepath: file path to config file with Twitter API keys. :return: keys_dict :raise: IOError """ try: keys_file = open(filepath, 'rb') keys = {} for line in keys_file: key, value = line.split('=') keys[key.strip()] = value.strip() except IOError: message = ('File {} cannot be opened.' ' Check that it exists and is binary.') print message.format(filepath) raise except: print "Error opening or unpickling file." raise return keys
nhatbui/LebronCoin
lebroncoin/key_loader.py
Python
mit
654
[ 30522, 13366, 7170, 1035, 6309, 1006, 5371, 15069, 30524, 2213, 5371, 15069, 1024, 5371, 4130, 2000, 9530, 8873, 2290, 5371, 2007, 10474, 17928, 6309, 1012, 1024, 2709, 1024, 6309, 1035, 4487, 6593, 1024, 5333, 1024, 22834, 2121, 29165, 100...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
var config = { type: Phaser.WEBGL, parent: 'phaser-example', scene: { preload: preload, create: create } }; var game = new Phaser.Game(config); function preload() { this.load.image('bunny', 'assets/sprites/bunny.png'); } function create() { var parent = this.add.image(0, 0, 'bunny'); var child = this.add.image(100, 100, 'bunny'); parent.alpha = 0.5; }
boniatillo-com/PhaserEditor
source/v2/phasereditor/phasereditor.resources.phaser.examples/phaser3-examples/public/src/archived/091 image parent alpha.js
JavaScript
epl-1.0
411
[ 30522, 13075, 9530, 8873, 2290, 1027, 1063, 2828, 1024, 4403, 2099, 1012, 4773, 23296, 1010, 6687, 1024, 1005, 4403, 2099, 1011, 2742, 1005, 1010, 3496, 1024, 1063, 3653, 11066, 1024, 3653, 11066, 1010, 3443, 1024, 3443, 1065, 1065, 1025, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<?php namespace TDN\DocumentBundle\Controller; /** * This code has been auto-generated by the JMSDiExtraBundle. * * Manual changes to it will be lost. */ class SliderController__JMSInjector { public static function inject($container) { $instance = new \TDN\DocumentBundle\Controller\SliderController(); return $instance; } }
HamzaBendidane/tdnold
cache/prod/jms_diextra/controller_injectors/TDNDocumentBundleControllerSliderController.php
PHP
mit
355
[ 30522, 1026, 1029, 25718, 3415, 15327, 14595, 2078, 1032, 6254, 27265, 2571, 1032, 11486, 1025, 1013, 1008, 1008, 1008, 2023, 3642, 2038, 2042, 8285, 1011, 7013, 2011, 1996, 1046, 5244, 10265, 18413, 2527, 27265, 2571, 1012, 1008, 1008, 641...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* * Copyright (c) 2017 * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ package jsettlers.main.android.core.controls; import org.androidannotations.annotations.AfterInject; import org.androidannotations.annotations.EBean; import org.androidannotations.annotations.res.StringRes; import jsettlers.main.android.R; import jsettlers.main.android.gameplay.ui.activities.GameActivity_; import jsettlers.main.android.mainmenu.navigation.Actions; import android.app.Notification; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.support.v4.app.NotificationCompat; /** * Created by Andreas Eberle on 13.05.2017. */ @EBean class NotificationBuilder { private final Context context; private NotificationCompat.Builder builder; @StringRes(R.string.notification_game_in_progress) String title; @StringRes(R.string.game_menu_quit) String quit; @StringRes(R.string.game_menu_quit_confirm) String quitConfirmString; @StringRes(R.string.save_string) String saveString; @StringRes(R.string.pause_string) String pauseString; @StringRes(R.string.game_menu_unpause) String unpauseString; public NotificationBuilder(Context context) { this.context = context; } @AfterInject void setupBuilder() { Intent gameActivityIntent = GameActivity_.intent(context).action(Actions.ACTION_RESUME_GAME).get(); PendingIntent gameActivityPendingIntent = PendingIntent.getActivity(context, 0, gameActivityIntent, 0); builder = new NotificationCompat.Builder(context) .setSmallIcon(R.drawable.icon) .setContentTitle(title) .setContentIntent(gameActivityPendingIntent); } public NotificationBuilder addQuitButton() { PendingIntent quitPendingIntent = PendingIntent.getBroadcast(context, 0, new Intent(Actions.ACTION_QUIT), 0); builder.addAction(R.drawable.ic_stop, quit, quitPendingIntent); return this; } public NotificationBuilder addQuitConfirmButton() { PendingIntent quitPendingIntent = PendingIntent.getBroadcast(context, 0, new Intent(Actions.ACTION_QUIT_CONFIRM), 0); builder.addAction(R.drawable.ic_stop, quitConfirmString, quitPendingIntent); return this; } public NotificationBuilder addSaveButton() { PendingIntent savePendingIntent = PendingIntent.getBroadcast(context, 0, new Intent(Actions.ACTION_SAVE), 0); builder.addAction(R.drawable.ic_save, saveString, savePendingIntent); return this; } public NotificationBuilder addPauseButton() { PendingIntent pausePendingIntent = PendingIntent.getBroadcast(context, 0, new Intent(Actions.ACTION_PAUSE), 0); builder.addAction(R.drawable.ic_pause, pauseString, pausePendingIntent); return this; } public NotificationBuilder addUnPauseButton() { PendingIntent unPausePendingIntent = PendingIntent.getBroadcast(context, 0, new Intent(Actions.ACTION_UNPAUSE), 0); builder.addAction(R.drawable.ic_play, unpauseString, unPausePendingIntent); return this; } public Notification build() { return builder.build(); } }
andreasb242/settlers-remake
jsettlers.main.android/src/main/java/jsettlers/main/android/core/controls/NotificationBuilder.java
Java
mit
3,999
[ 30522, 1013, 1008, 1008, 9385, 1006, 1039, 1007, 2418, 1008, 1008, 6656, 2003, 2182, 3762, 4379, 1010, 2489, 1997, 3715, 1010, 2000, 2151, 2711, 11381, 1037, 6100, 1997, 2023, 4007, 1998, 3378, 12653, 6764, 1006, 1996, 1000, 4007, 1000, 1...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* * Copyright (C) 2007 The Android Open Source Project * * 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 android.content; import android.net.Uri; /** * Utility methods useful for working with content {@link android.net.Uri}s, * those with a "content" scheme. */ public class ContentUris { /** * Converts the last path segment to a long. * * <p>This supports a common convention for content URIs where an ID is * stored in the last segment. * * @throws UnsupportedOperationException if this isn't a hierarchical URI * @throws NumberFormatException if the last segment isn't a number * * @return the long conversion of the last segment or -1 if the path is * empty */ public static long parseId(Uri contentUri) { String last = contentUri.getLastPathSegment(); return last == null ? -1 : Long.parseLong(last); } /** * Appends the given ID to the end of the path. * * @param builder to append the ID to * @param id to append * * @return the given builder */ public static Uri.Builder appendId(Uri.Builder builder, long id) { return builder.appendEncodedPath(String.valueOf(id)); } /** * Appends the given ID to the end of the path. * * @param contentUri to start with * @param id to append * * @return a new URI with the given ID appended to the end of the path */ public static Uri withAppendedId(Uri contentUri, long id) { return appendId(contentUri.buildUpon(), id).build(); } }
mateor/PDroidHistory
frameworks/base/core/java/android/content/ContentUris.java
Java
gpl-3.0
2,104
[ 30522, 1013, 1008, 1008, 9385, 1006, 1039, 1007, 2289, 1996, 11924, 2330, 3120, 2622, 1008, 1008, 7000, 2104, 1996, 15895, 6105, 1010, 2544, 1016, 1012, 1014, 1006, 1996, 1000, 6105, 1000, 1007, 1025, 1008, 2017, 2089, 30524, 6105, 1012, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
// +build go1.10,codegen package api import ( "encoding/json" "testing" ) func buildAPI() *API { a := &API{} stringShape := &Shape{ API: a, ShapeName: "string", Type: "string", } stringShapeRef := &ShapeRef{ API: a, ShapeName: "string", Shape: stringShape, } intShape := &Shape{ API: a, ShapeName: "int", Type: "int", } intShapeRef := &ShapeRef{ API: a, ShapeName: "int", Shape: intShape, } nestedComplexShape := &Shape{ API: a, ShapeName: "NestedComplexShape", MemberRefs: map[string]*ShapeRef{ "NestedField": stringShapeRef, }, Type: "structure", } nestedComplexShapeRef := &ShapeRef{ API: a, ShapeName: "NestedComplexShape", Shape: nestedComplexShape, } nestedListShape := &Shape{ API: a, ShapeName: "NestedListShape", MemberRef: *nestedComplexShapeRef, Type: "list", } nestedListShapeRef := &ShapeRef{ API: a, ShapeName: "NestedListShape", Shape: nestedListShape, } complexShape := &Shape{ API: a, ShapeName: "ComplexShape", MemberRefs: map[string]*ShapeRef{ "Field": stringShapeRef, "List": nestedListShapeRef, }, Type: "structure", } complexShapeRef := &ShapeRef{ API: a, ShapeName: "ComplexShape", Shape: complexShape, } listShape := &Shape{ API: a, ShapeName: "ListShape", MemberRef: *complexShapeRef, Type: "list", } listShapeRef := &ShapeRef{ API: a, ShapeName: "ListShape", Shape: listShape, } listsShape := &Shape{ API: a, ShapeName: "ListsShape", MemberRef: *listShapeRef, Type: "list", } listsShapeRef := &ShapeRef{ API: a, ShapeName: "ListsShape", Shape: listsShape, } input := &Shape{ API: a, ShapeName: "FooInput", MemberRefs: map[string]*ShapeRef{ "BarShape": stringShapeRef, "ComplexField": complexShapeRef, "ListField": listShapeRef, "ListsField": listsShapeRef, }, Type: "structure", } output := &Shape{ API: a, ShapeName: "FooOutput", MemberRefs: map[string]*ShapeRef{ "BazShape": intShapeRef, "ComplexField": complexShapeRef, "ListField": listShapeRef, "ListsField": listsShapeRef, }, Type: "structure", } inputRef := ShapeRef{ API: a, ShapeName: "FooInput", Shape: input, } outputRef := ShapeRef{ API: a, ShapeName: "FooOutput", Shape: output, } operations := map[string]*Operation{ "Foo": { API: a, Name: "Foo", ExportedName: "Foo", InputRef: inputRef, OutputRef: outputRef, }, } a.Operations = operations a.Shapes = map[string]*Shape{ "FooInput": input, "FooOutput": output, "string": stringShape, "int": intShape, "NestedComplexShape": nestedComplexShape, "NestedListShape": nestedListShape, "ComplexShape": complexShape, "ListShape": listShape, "ListsShape": listsShape, } a.Metadata = Metadata{ ServiceAbbreviation: "FooService", } a.BaseImportPath = "github.com/aws/aws-sdk-go/service/" a.Setup() return a } func TestExampleGeneration(t *testing.T) { example := ` { "version": "1.0", "examples": { "Foo": [ { "input": { "BarShape": "Hello world", "ComplexField": { "Field": "bar", "List": [ { "NestedField": "qux" } ] }, "ListField": [ { "Field": "baz" } ], "ListsField": [ [ { "Field": "baz" } ] ] }, "output": { "BazShape": 1 }, "comments": { "input": { }, "output": { } }, "description": "Foo bar baz qux", "title": "I pity the foo" } ] } } ` a := buildAPI() def := &ExamplesDefinition{} err := json.Unmarshal([]byte(example), def) if err != nil { t.Error(err) } def.API = a def.setup() expected := ` import ( "fmt" "strings" "time" "` + SDKImportRoot + `/aws" "` + SDKImportRoot + `/aws/awserr" "` + SDKImportRoot + `/aws/session" "` + SDKImportRoot + `/service/fooservice" ) var _ time.Duration var _ strings.Reader var _ aws.Config func parseTime(layout, value string) *time.Time { t, err := time.Parse(layout, value) if err != nil { panic(err) } return &t } // I pity the foo // // Foo bar baz qux func ExampleFooService_Foo_shared00() { svc := fooservice.New(session.New()) input := &fooservice.FooInput{ BarShape: aws.String("Hello world"), ComplexField: &fooservice.ComplexShape{ Field: aws.String("bar"), List: []*fooservice.NestedComplexShape{ { NestedField: aws.String("qux"), }, }, }, ListField: []*fooservice.ComplexShape{ { Field: aws.String("baz"), }, }, ListsField: [][]*fooservice.ComplexShape{ { { Field: aws.String("baz"), }, }, }, } result, err := svc.Foo(input) if err != nil { if aerr, ok := err.(awserr.Error); ok { switch aerr.Code() { default: fmt.Println(aerr.Error()) } } else { // Print the error, cast err to awserr.Error to get the Code and // Message from an error. fmt.Println(err.Error()) } return } fmt.Println(result) } ` if expected != a.ExamplesGoCode() { t.Errorf("Expected:\n%s\nReceived:\n%s\n", expected, a.ExamplesGoCode()) } } func TestBuildShape(t *testing.T) { a := buildAPI() cases := []struct { defs map[string]interface{} expected string }{ { defs: map[string]interface{}{ "barShape": "Hello World", }, expected: "BarShape: aws.String(\"Hello World\"),\n", }, { defs: map[string]interface{}{ "BarShape": "Hello World", }, expected: "BarShape: aws.String(\"Hello World\"),\n", }, } for _, c := range cases { ref := a.Operations["Foo"].InputRef shapeStr := defaultExamplesBuilder{}.BuildShape(&ref, c.defs, false) if c.expected != shapeStr { t.Errorf("Expected:\n%s\nReceived:\n%s", c.expected, shapeStr) } } }
Miciah/origin
vendor/github.com/aws/aws-sdk-go/private/model/api/example_test.go
GO
apache-2.0
6,120
[ 30522, 1013, 1013, 1009, 3857, 2175, 2487, 1012, 2184, 1010, 3642, 6914, 7427, 17928, 12324, 1006, 1000, 17181, 1013, 1046, 3385, 1000, 1000, 5604, 1000, 1007, 4569, 2278, 3857, 9331, 2072, 1006, 1007, 1008, 17928, 1063, 1037, 1024, 1027, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
./clean.sh javac -d build/modules \ --module-source-path src \ `find src -name "*.java"` jar --create --file=mlib/com.acme.bids.db@1.0.jar \ --module-version=1.0 -C build/modules/com.acme.bids.db . jar --create --file=mlib/com.acme.bids.service@1.0.jar \ --module-version=1.0 \ --main-class=com.acme.bids.service.api.UserService \ -C build/modules/com.acme.bids.service . jar --create --file=mlib/com.acme.bids.app@1.0.jar \ --module-version=1.0 \ --main-class=com.acme.bids.app.App \ -C build/modules/com.acme.bids.app .
codetojoy/talk_maritimedevcon_java_9_modules
eg_05_java_9_jlink/compile.sh
Shell
apache-2.0
531
[ 30522, 1012, 1013, 4550, 1012, 14021, 9262, 2278, 1011, 1040, 3857, 1013, 14184, 1032, 1011, 1011, 11336, 1011, 3120, 1011, 4130, 5034, 2278, 1032, 1036, 2424, 5034, 2278, 1011, 2171, 1000, 1008, 1012, 9262, 1000, 1036, 15723, 1011, 1011, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<?php namespace MoreSparetime\WordPress\PluginBuilder\Cron; use AndreasGlaser\Helpers\Validate\Expect; use MoreSparetime\WordPress\PluginBuilder\AttachableInterface; use MoreSparetime\WordPress\PluginBuilder\Plugin; use MoreSparetime\WordPress\PluginBuilder\PluginAwareTrait; /** * Class Cron * * @package MoreSparetime\WordPress\PluginBuilder\Cron * @author Andreas Glaser */ class Cron implements AttachableInterface { use PluginAwareTrait; /** * @var string */ protected $slug; /** * @var callable */ protected $controller; /** * @var string */ protected $recurrence; /** * Cron constructor. * * @param \MoreSparetime\WordPress\PluginBuilder\Plugin $plugin * @param string $slug * @param callable $controller * @param string $recurrence * * @author Andreas Glaser */ public function __construct(Plugin $plugin, $slug, $controller, $recurrence = 'hourly') { $this->setPlugin($plugin); $this->setSlug($slug); $this->setController($controller); $this->setRecurrence($recurrence); } /** * @return string * @author Andreas Glaser */ public function getSlug() { return $this->slug; } /** * @param string $slug * * @return Cron * @author Andreas Glaser */ public function setSlug($slug) { Expect::str($slug); $this->slug = $this->plugin->makeSlug('cron', $slug); return $this; } /** * @return callable * @author Andreas Glaser */ public function getController() { return $this->controller; } /** * @param callable $controller * * @return Cron * @author Andreas Glaser */ public function setController($controller) { Expect::isCallable($controller); $this->controller = $controller; return $this; } /** * @return string * @author Andreas Glaser */ public function getRecurrence() { return $this->recurrence; } /** * @param string $recurrence * * @return Cron * @author Andreas Glaser */ public function setRecurrence($recurrence) { Expect::str($recurrence); $this->recurrence = $recurrence; return $this; } /** * @return void * @author Andreas Glaser */ public function attachHooks() { // todo: this can probably be wrapped into activation hook if (!wp_next_scheduled($this->slug)) { wp_schedule_event(time(), $this->recurrence, $this->slug); } add_action($this->slug, $this->controller); // remove cron on deactivation register_deactivation_hook($this->plugin->getPluginFilePath(), function () { wp_clear_scheduled_hook($this->slug); }); } }
more-sparetime/wp-plugin-builder
src/Cron/Cron.php
PHP
mit
3,052
[ 30522, 1026, 1029, 25718, 3415, 15327, 2062, 27694, 20624, 4168, 1032, 2773, 20110, 1032, 13354, 2378, 8569, 23891, 2099, 1032, 13675, 2239, 1025, 2224, 12460, 23296, 11022, 2099, 1032, 2393, 2545, 1032, 9398, 3686, 1032, 5987, 1025, 2224, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
package org.hisp.dhis.sms.listener; /* * Copyright (c) 2004-2018, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import java.util.*; import org.apache.commons.lang3.StringUtils; import org.hisp.dhis.organisationunit.OrganisationUnit; import org.hisp.dhis.program.Program; import org.hisp.dhis.program.ProgramInstanceService; import org.hisp.dhis.sms.command.SMSCommand; import org.hisp.dhis.sms.command.SMSCommandService; import org.hisp.dhis.sms.command.code.SMSCode; import org.hisp.dhis.sms.incoming.IncomingSms; import org.hisp.dhis.sms.incoming.SmsMessageStatus; import org.hisp.dhis.sms.parse.ParserType; import org.hisp.dhis.sms.parse.SMSParserException; import org.hisp.dhis.system.util.SmsUtils; import org.hisp.dhis.trackedentity.TrackedEntityAttribute; import org.hisp.dhis.trackedentity.TrackedEntityInstance; import org.hisp.dhis.trackedentity.TrackedEntityInstanceService; import org.hisp.dhis.trackedentity.TrackedEntityTypeService; import org.hisp.dhis.trackedentityattributevalue.TrackedEntityAttributeValue; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; @Transactional public class TrackedEntityRegistrationSMSListener extends BaseSMSListener { private static final String SUCCESS_MESSAGE = "Tracked Entity Registered Successfully with uid. "; // ------------------------------------------------------------------------- // Dependencies // ------------------------------------------------------------------------- @Autowired private SMSCommandService smsCommandService; @Autowired private TrackedEntityTypeService trackedEntityTypeService; @Autowired private TrackedEntityInstanceService trackedEntityInstanceService; @Autowired private ProgramInstanceService programInstanceService; // ------------------------------------------------------------------------- // IncomingSmsListener implementation // ------------------------------------------------------------------------- @Override protected void postProcess( IncomingSms sms, SMSCommand smsCommand, Map<String, String> parsedMessage ) { String message = sms.getText(); Date date = SmsUtils.lookForDate( message ); String senderPhoneNumber = StringUtils.replace( sms.getOriginator(), "+", "" ); Collection<OrganisationUnit> orgUnits = getOrganisationUnits( sms ); Program program = smsCommand.getProgram(); OrganisationUnit orgUnit = SmsUtils.selectOrganisationUnit( orgUnits, parsedMessage, smsCommand ); if ( !program.hasOrganisationUnit( orgUnit ) ) { sendFeedback( SMSCommand.NO_OU_FOR_PROGRAM, senderPhoneNumber, WARNING ); throw new SMSParserException( SMSCommand.NO_OU_FOR_PROGRAM ); } TrackedEntityInstance trackedEntityInstance = new TrackedEntityInstance(); trackedEntityInstance.setOrganisationUnit( orgUnit ); trackedEntityInstance.setTrackedEntityType( trackedEntityTypeService.getTrackedEntityByName( smsCommand.getProgram().getTrackedEntityType().getName() ) ); Set<TrackedEntityAttributeValue> patientAttributeValues = new HashSet<>(); smsCommand.getCodes().stream() .filter( code -> parsedMessage.containsKey( code.getCode() ) ) .forEach( code -> { TrackedEntityAttributeValue trackedEntityAttributeValue = this.createTrackedEntityAttributeValue( parsedMessage, code, trackedEntityInstance) ; patientAttributeValues.add( trackedEntityAttributeValue ); }); int trackedEntityInstanceId = 0; if ( patientAttributeValues.size() > 0 ) { trackedEntityInstanceId = trackedEntityInstanceService.createTrackedEntityInstance( trackedEntityInstance, null, null, patientAttributeValues ); } else { sendFeedback( "No TrackedEntityAttribute found", senderPhoneNumber, WARNING ); } TrackedEntityInstance tei = trackedEntityInstanceService.getTrackedEntityInstance( trackedEntityInstanceId ); programInstanceService.enrollTrackedEntityInstance( tei, smsCommand.getProgram(), new Date(), date, orgUnit ); sendFeedback( StringUtils.defaultIfBlank( smsCommand.getSuccessMessage(), SUCCESS_MESSAGE + tei.getUid() ), senderPhoneNumber, INFO ); update( sms, SmsMessageStatus.PROCESSED, true ); } @Override protected SMSCommand getSMSCommand( IncomingSms sms ) { return smsCommandService.getSMSCommand( SmsUtils.getCommandString( sms ), ParserType.TRACKED_ENTITY_REGISTRATION_PARSER ); } private TrackedEntityAttributeValue createTrackedEntityAttributeValue( Map<String, String> parsedMessage, SMSCode code, TrackedEntityInstance trackedEntityInstance ) { String value = parsedMessage.get( code.getCode() ); TrackedEntityAttribute trackedEntityAttribute = code.getTrackedEntityAttribute(); TrackedEntityAttributeValue trackedEntityAttributeValue = new TrackedEntityAttributeValue(); trackedEntityAttributeValue.setAttribute( trackedEntityAttribute ); trackedEntityAttributeValue.setEntityInstance( trackedEntityInstance ); trackedEntityAttributeValue.setValue( value ); return trackedEntityAttributeValue; } }
msf-oca-his/dhis-core
dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/sms/listener/TrackedEntityRegistrationSMSListener.java
Java
bsd-3-clause
7,054
[ 30522, 7427, 8917, 1012, 2010, 2361, 1012, 28144, 2483, 1012, 22434, 1012, 19373, 1025, 1013, 1008, 1008, 9385, 1006, 1039, 1007, 2432, 1011, 2760, 1010, 2118, 1997, 9977, 1008, 2035, 2916, 9235, 1012, 1008, 1008, 25707, 1998, 2224, 1999, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
import itertools import os.path import sys import time from . import core from . import file_io from . import geometry from . import stringconv from . import version # # Functions # def save_output(profileli, opt): """ Save a summary of results of evaluated profiles """ def m(x, pixelwidth): return geometry.to_metric_units(x, pixelwidth) def m2(x, pixelwidth): # For area units... return geometry.to_metric_units(x, pixelwidth**2) def na(x): if x in (None, -1): return "N/A" else: return x def write_session_summary(): with file_io.FileWriter("session.summary", opt) as f: f.writerow(["%s version:" % version.title, "%s (Last modified %s %s, %s)" % ((version.version,) + version.date)]) f.writerow(["Number of evaluated profiles:", len(eval_proli)]) if err_fli: f.writerow(["Number of non-evaluated profiles:", len(err_fli)]) f.writerow(["Metric unit:", eval_proli[0].metric_unit]) f.writerow(["Spatial resolution:", opt.spatial_resolution, eval_proli[0].metric_unit]) f.writerow(["Shell width:", opt.shell_width, eval_proli[0].metric_unit]) f.writerow(["Interpoint distances calculated:", stringconv.yes_or_no(opt.determine_interpoint_dists)]) if opt.determine_interpoint_dists: f.writerow(["Interpoint distance mode:", opt.interpoint_dist_mode]) f.writerow(["Shortest interpoint distances:", stringconv.yes_or_no(opt.interpoint_shortest_dist)]) f.writerow(["Lateral interpoint distances:", stringconv.yes_or_no(opt.interpoint_lateral_dist)]) f.writerow(["Monte Carlo simulations performed:", stringconv.yes_or_no(opt.run_monte_carlo)]) if opt.run_monte_carlo: f.writerow(["Number of Monte Carlo runs:", opt.monte_carlo_runs]) f.writerow(["Monte Carlo simulation window:", opt.monte_carlo_simulation_window]) f.writerow(["Strict localization in simulation window:", stringconv.yes_or_no(opt.monte_carlo_strict_location)]) f.writerow(["Clusters determined:", stringconv.yes_or_no(opt.determine_clusters)]) if opt.determine_clusters: f.writerow(["Within-cluster distance:", opt.within_cluster_dist, eval_proli[0].metric_unit]) if clean_fli: f.writerow(["Input files processed cleanly:"]) f.writerows([[fn] for fn in clean_fli]) if nop_fli: f.writerow(["Input files processed but which generated no point distances:"]) f.writerows([[fn] for fn in nop_fli]) if warn_fli: f.writerow(["Input files processed but which generated " "warnings (see log for details):"]) f.writerows([[fn] for fn in warn_fli]) if err_fli: f.writerow(["Input files not processed or not included in " "summary (see log for details):"]) f.writerows([[fn] for fn in err_fli]) def write_profile_summary(): with file_io.FileWriter("profile.summary", opt) as f: f.writerow(["Postsynaptic element length", "Presynaptic element length", "Number of PSDs:", "Total postsynaptic membrane length incl perforations:", "Total postsynaptic membrane length excl perforations:", "Total PSD area:", "Particles (total)", "Particles in PSD", "Particles within %s %s of PSD" % (opt.spatial_resolution, eval_proli[0].metric_unit), "Shell particles strictly synaptic and postsynaptic", "Shell particles strictly synaptic and postsynaptic " "or associated with postsynaptic membrane", "Synaptic particles associated w/ postsynaptic " "membrane", "Synaptic particles associated w/ presynaptic membrane", "Perisynaptic particles associated w/ postsynaptic " "membrane", "Perisynaptic particles associated w/ presynaptic " "membrane", "Within-perforation particles associated w/ " "postsynaptic membrane", "Within-perforation particles associated w/ " "presynaptic membrane", "Presynaptic profile", "Postsynaptic profile", "ID", "Input file", "Comment"]) f.writerows([[m(pro.posel.length(), pro.pixelwidth), m(pro.prsel.length(), pro.pixelwidth), len(pro.psdli), m(pro.total_posm.length(), pro.pixelwidth), sum([m(psd.posm.length(), pro.pixelwidth) for psd in pro.psdli]), sum([m2(psd.psdposm.area(), pro.pixelwidth) for psd in pro.psdli]), len(pro.pli), len([p for p in pro.pli if p.is_within_psd]), len([p for p in pro.pli if p.is_associated_with_psd]), len([p for p in pro.pli if p.strict_lateral_location == "synaptic" and p.axodendritic_location == "postsynaptic" and p.is_within_postsynaptic_membrane_shell]), len([p for p in pro.pli if p.strict_lateral_location == "synaptic" and (p.axodendritic_location == "postsynaptic" and p.is_within_postsynaptic_membrane_shell) or p.is_postsynaptic_membrane_associated]), len([p for p in pro.pli if p.lateral_location == "synaptic" and p.is_postsynaptic_membrane_associated]), len([p for p in pro.pli if p.lateral_location == "synaptic" and p.is_presynaptic_membrane_associated]), len([p for p in pro.pli if p.lateral_location == "perisynaptic" and p.is_postsynaptic_membrane_associated]), len([p for p in pro.pli if p.lateral_location == "perisynaptic" and p.is_presynaptic_membrane_associated]), len([p for p in pro.pli if p.lateral_location == "within perforation" and p.is_postsynaptic_membrane_associated]), len([p for p in pro.pli if p.lateral_location == "within perforation" and p.is_presynaptic_membrane_associated]), pro.presyn_profile, pro.postsyn_profile, pro.id, pro.comment, os.path.basename(pro.inputfn)] for pro in eval_proli]) def write_point_summary(ptype): if ptype == "particle": pli = "pli" pstr = "particle" elif ptype == "random": if not opt.use_random: return else: pli = "randomli" pstr = "point" else: return with file_io.FileWriter("%s.summary" % ptype, opt) as f: f.writerow(["%s number (as appearing in input file)" % pstr.capitalize(), "Coordinates (in pixels)", "Axodendritic location", "Distance to postsynaptic element membrane", "Distance to presynaptic element membrane", "Lateral location", "Strict lateral location", "Lateral distance to nearest PSD center", "Normalized lateral distance to nearest PSD center", "Within PSD", "Within %s %s of PSD" % (opt.spatial_resolution, eval_proli[0].metric_unit), "Total postsynaptic membrane length incl perforations", "Total postsynaptic membrane length excl perforations", "Length of laterally closest PSD", "Presynaptic profile", "Postsynaptic profile", "Profile ID", "Input file", "Comment"]) f.writerows([[n+1, p, p.axodendritic_location, m(p.dist_to_posel, pro.pixelwidth), m(p.dist_to_prsel, pro.pixelwidth), p.lateral_location, p.strict_lateral_location, m(p.lateral_dist_psd, pro.pixelwidth), p.norm_lateral_dist_psd, stringconv.yes_or_no(p.is_within_psd), stringconv.yes_or_no(p.is_associated_with_psd), m(pro.total_posm.length(), pro.pixelwidth), m(sum([psd.posm.length() for psd in pro.psdli]), pro.pixelwidth), m(p.nearest_psd.posm.length(), pro.pixelwidth), pro.presyn_profile, pro.postsyn_profile, pro.id, os.path.basename(pro.inputfn), pro.comment] for pro in eval_proli for n, p in enumerate(pro.__dict__[pli])]) def write_cluster_summary(): if not opt.determine_clusters: return with file_io.FileWriter("cluster.summary", opt) as f: f.writerow(["Cluster number", "Number of particles in cluster", "Distance to postsynaptic membrane of centroid", "Distance to nearest cluster along postsynaptic element membrane", "Profile ID", "Input file", "Comment"]) f.writerows([[n + 1, len(c), m(c.dist_to_posel, pro.pixelwidth), m(na(c.dist_to_nearest_cluster), pro.pixelwidth), pro.id, os.path.basename(pro.inputfn), pro.comment]for pro in eval_proli for n, c in enumerate(pro.clusterli)]) def write_interpoint_summaries(): if not opt.determine_interpoint_dists: return ip_rels = dict([(key, val) for key, val in opt.interpoint_relations.items() if val and 'simulated' not in key]) if not opt.use_random: for key, val in opt.interpoint_relations.items(): if 'random' in key and val: del ip_rels[key] if (len(ip_rels) == 0 or not (opt.interpoint_shortest_dist or opt.interpoint_lateral_dist)): return table = [] if opt.interpoint_dist_mode == 'all': s = "all distances" else: s = "nearest neighbour distances" table.append(["Mode: " + s]) headerli = list(ip_rels.keys()) prefixli = [] for key, val in ip_rels.items(): prefix = key[0] + key[key.index("- ") + 2] + "_" prefixli.append(prefix) if opt.interpoint_shortest_dist and opt.interpoint_lateral_dist: headerli.extend(headerli) prefixli.extend([t + 'lat' for t in prefixli]) topheaderli = [] if opt.interpoint_shortest_dist: topheaderli.append("Shortest distances") if opt.interpoint_lateral_dist: topheaderli.extend([""] * (len(ip_rels) - 1)) if opt.interpoint_lateral_dist: topheaderli.append("Lateral distances along postsynaptic element " "membrane") table.extend([topheaderli, headerli]) cols = [[] for _ in prefixli] for pro in eval_proli: for n, li in enumerate([pro.__dict__[prefix + "distli"] for prefix in prefixli]): cols[n].extend([m(e, pro.pixelwidth) for e in li]) # transpose cols and append to table table.extend(list(itertools.zip_longest(*cols, fillvalue=""))) with file_io.FileWriter("interpoint.summary", opt) as f: f.writerows(table) def write_mc_dist_to_psd(dtype): if not opt.run_monte_carlo: return table = [] if dtype == 'metric': table.append(["Lateral distances in %s to center of the nearest PSD" % eval_proli[0].metric_unit]) elif dtype == 'normalized': table.append(["Normalized lateral distances to the center of the nearest PSD"]) table.append(["Run %d" % (n + 1) for n in range(0, opt.monte_carlo_runs)]) for pro in eval_proli: if dtype == 'metric': table.extend(zip(*[[m(p.lateral_dist_psd, pro.pixelwidth) for p in li["pli"]] for li in pro.mcli])) elif dtype == 'normalized': table.extend(zip(*[[p.norm_lateral_dist_psd for p in li["pli"]] for li in pro.mcli])) with file_io.FileWriter("simulated.PSD.%s.lateral.distances" % dtype, opt) as f: f.writerows(table) def write_mc_dist_to_posel(): if not opt.run_monte_carlo: return table = [["Run %d" % (n + 1) for n in range(0, opt.monte_carlo_runs)]] for pro in eval_proli: table.extend(itertools.zip_longest(*[[m(p.dist_to_posel, pro.pixelwidth) for p in li['pli']] for li in pro.mcli])) with file_io.FileWriter( "simulated.postsynaptic.element.membrane.distances", opt) as f: f.writerows(table) def write_mc_ip_dists(dist_type): def m_li(*_li): return [m(x, pro.pixelwidth) for x in _li] if not (opt.run_monte_carlo and opt.determine_interpoint_dists): return for ip_type in [key for key, val in opt.interpoint_relations.items() if 'simulated' in key and val]: if ((dist_type == 'shortest' and not opt.interpoint_shortest_dist) or (dist_type == 'lateral' and not opt.interpoint_lateral_dist)): return if dist_type == 'lateral': short_dist_type = 'lat' else: short_dist_type = '' table = [["Run %d" % (n + 1) for n in range(0, opt.monte_carlo_runs)]] for pro in eval_proli: table.extend(itertools.zip_longest(*[m(p, pro.pixelwidth) for li in pro.mcli for p in li[ip_type]["%sdist" % short_dist_type]])) with file_io.FileWriter("%s.interpoint.%s.distances" % (ip_type.replace(" ", ""), dist_type), opt) as f: f.writerows(table) def write_mc_cluster_summary(): if not (opt.determine_clusters and opt.run_monte_carlo): return table = [["N particles in cluster", "Run", "Distance to postsynaptic element membrane from centroid", "Distance to nearest cluster along postsynaptic element membrane", "Profile ID", "Input file", "Comment"]] for pro in eval_proli: for n in range(0, opt.monte_carlo_runs): for c in pro.mcli[n]["clusterli"]: table.append([len(c), n + 1, m(c.dist_to_posel, pro.pixelwidth), m(na(c.dist_to_nearest_cluster), pro.pixelwidth), pro.id, os.path.basename(pro.inputfn), pro.comment]) with file_io.FileWriter("simulated.clusters", opt) as f: f.writerows(table) sys.stdout.write("\nSaving summaries to %s:\n" % opt.output_dir) opt.save_result = {'any_saved': False, 'any_err': False} eval_proli = [profile for profile in profileli if not profile.errflag] clean_fli = [profile.inputfn for profile in profileli if not (profile.errflag or profile.warnflag)] warn_fli = [profile.inputfn for profile in profileli if profile.warnflag] err_fli = [profile.inputfn for profile in profileli if profile.errflag] nop_fli = [profile.inputfn for profile in eval_proli if not profile.pli] write_session_summary() write_profile_summary() write_point_summary('particle') write_point_summary('random') write_interpoint_summaries() write_cluster_summary() write_mc_dist_to_posel() write_mc_dist_to_psd('metric') write_mc_dist_to_psd('normalized') write_mc_ip_dists('shortest') write_mc_ip_dists('lateral') write_mc_cluster_summary() if opt.save_result['any_err']: sys.stdout.write("Note: One or more summaries could not be saved.\n") if opt.save_result['any_saved']: sys.stdout.write("Done.\n") else: sys.stdout.write("No summaries saved.\n") def reset_options(opt): """ Deletes certain options that should always be set anew for each run (each time the "Start" button is pressed) """ for optstr in ('metric_unit', 'use_random'): if hasattr(opt, optstr): delattr(opt, optstr) def show_options(opt): sys.stdout.write("{} version: {} (Last modified {} {}, {})\n".format( version.title, version.version, *version.date)) sys.stdout.write("Output file format: %s\n" % opt.output_file_format) sys.stdout.write("Suffix of output files: %s\n" % opt.output_filename_suffix) sys.stdout.write("Output directory: %s\n" % opt.output_dir) sys.stdout.write("Spatial resolution: %d\n" % opt.spatial_resolution) sys.stdout.write("Shell width: %d metric units\n" % opt.shell_width) sys.stdout.write("Interpoint distances calculated: %s\n" % stringconv.yes_or_no(opt.determine_interpoint_dists)) if opt.determine_interpoint_dists: sys.stdout.write("Interpoint distance mode: %s\n" % opt.interpoint_dist_mode.capitalize()) sys.stdout.write("Shortest interpoint distances: %s\n" % stringconv.yes_or_no(opt.interpoint_shortest_dist)) sys.stdout.write("Lateral interpoint distances: %s\n" % stringconv.yes_or_no(opt.interpoint_lateral_dist)) sys.stdout.write("Monte Carlo simulations performed: %s\n" % stringconv.yes_or_no(opt.run_monte_carlo)) if opt.run_monte_carlo: sys.stdout.write("Number of Monte Carlo runs: %d\n" % opt.monte_carlo_runs) sys.stdout.write("Monte Carlo simulation window: %s\n" % opt.monte_carlo_simulation_window) sys.stdout.write("Strict localization in simulation window: %s\n" % stringconv.yes_or_no(opt.monte_carlo_strict_location)) sys.stdout.write("Clusters determined: %s\n" % stringconv.yes_or_no(opt.determine_clusters)) if opt.determine_clusters: sys.stdout.write("Within-cluster distance: %d\n" % opt.within_cluster_dist) def get_output_format(opt): if opt.output_file_format == 'excel': try: import openpyxl except ImportError: sys.stdout.write("Unable to write Excel files: resorting to csv format.\n") opt.output_file_format = 'csv' if opt.output_file_format == 'csv': opt.output_filename_ext = '.csv' opt.csv_format = {'dialect': 'excel', 'lineterminator': '\n'} if opt.csv_delimiter == 'tab': opt.csv_format['delimiter'] = '\t' if opt.output_filename_date_suffix: from datetime import date opt.output_filename_suffix = "." + date.today().isoformat() if opt.output_filename_other_suffix != '': opt.output_filename_suffix += "." + opt.output_filename_other_suffix def main_proc(parent): """ Process profile data files """ opt = parent.opt if not opt.input_file_list: sys.stdout.write("No input files.\n") return 0 i, n = 0, 0 profileli = [] sys.stdout.write("--- Session started %s local time ---\n" % time.ctime()) for f in opt.input_file_list: if opt.input_file_list.count(f) > 1: sys.stdout.write("Duplicate input filename %s:\n => removing first occurrence in " "list\n" % f) opt.input_file_list.remove(f) get_output_format(opt) reset_options(opt) show_options(opt) while True: if i < len(opt.input_file_list): inputfn = opt.input_file_list[i] i += 1 else: sys.stdout.write("\nNo more input files...\n") break parent.process_queue.put(("new_file", inputfn)) profileli.append(core.ProfileData(inputfn, opt)) profileli[-1].process() if opt.stop_requested: sys.stdout.write("\n--- Session aborted by user %s local time ---\n" % time.ctime()) return 3 if not profileli[-1].errflag: n += 1 if profileli[-1].warnflag: sys.stdout.write("Warning(s) found while processing input file.\n") continue else: sys.stdout.write("Error(s) found while processing input file =>\n" " => No distances could be determined.\n") continue # no more input files errfli = [pro.inputfn for pro in profileli if pro.errflag] warnfli = [pro.inputfn for pro in profileli if pro.warnflag] if errfli: sys.stdout.write("\n%s input %s generated one or more errors:\n" % (stringconv.plurality("This", len(errfli)), stringconv.plurality("file", len(errfli)))) sys.stdout.write("%s\n" % "\n".join([fn for fn in errfli])) if warnfli: sys.stdout.write("\n%s input %s generated one or more warnings:\n" % (stringconv.plurality("This", len(warnfli)), stringconv.plurality("file", len(warnfli)))) sys.stdout.write("%s\n" % "\n".join([fn for fn in warnfli])) if n > 0: parent.process_queue.put(("saving_summaries", "")) save_output(profileli, opt) else: sys.stdout.write("\nNo files processed.\n") sys.stdout.write("--- Session ended %s local time ---\n" % time.ctime()) parent.process_queue.put(("done", "")) if errfli: return 0 elif warnfli: return 2 else: return 1 # End of main.py
maxdl/Synapse.py
synapse/main.py
Python
mit
24,280
[ 30522, 12324, 2009, 8743, 13669, 2015, 12324, 9808, 1012, 4130, 12324, 25353, 2015, 12324, 2051, 2013, 1012, 12324, 4563, 2013, 1012, 12324, 5371, 1035, 22834, 2013, 1012, 12324, 10988, 2013, 1012, 12324, 5164, 8663, 2615, 2013, 1012, 12324, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<?php /******************************/ /* Submission Form Management */ /******************************/ require_once("../includes/admin_init.php"); require_once("../includes/adminAccount.class.php"); require_once("../includes/subForm.class.php"); require_once("../includes/conference.class.php"); /* Intitalize and output header */ initHeader("Submission Form Management"); /* Lets create an instance of the AdminAccount class, which handles administrator's account */ $adminAccount = new AdminAccount(); /* Let's create an instance of the SubForm class, which handles settings for the submission form */ $subForm = new SubForm($adminAccount->getCurrentConference()); /* Let's create an instance of the Conference class, which handles operations with currently selected conference */ $conference = new Conference($adminAccount->getCurrentConference()); /* Initialize page's template file */ $tpl = new Template("../templates/admin/conference_subform.tpl"); /* On user's attempt to add a new topic */ if (isset($_POST["new_topic"])) { /* Check if Topic Title is entered */ $err_topic_title = empty($_POST["topic"]); /* If Page Title is entered, add a new topic */ if ( !$err_topic_title ) { /* Add topic to the DB */ $subForm->addTopic($_POST["topic"]); /* Send a success message to the user */ $msg_add_success = true; } } /* On user's attempt to delete a topic */ if (isset($_POST["delete_topic"])) { /* Delete that page */ $subForm->deleteTopic($_POST["delete_topic"]); /* Send a success message to the user */ $msg_delete_success = true; } /* On user's attempt to save submission form notes */ if (isset($_POST["edit_subform_notes"])) { /* Save notes to the database */ $subForm->editNotes($_POST["subform_notes"]); /* Show user a success message */ $msg_notes_success = true; } /* On user's attempt to save allowed file types */ if (isset($_POST["edit_file_types"])) { /* Save file types to the database */ $subForm->editFileTypes($_POST["file_types"]); /* Show user a success message */ $msg_file_types_success = true; } /* Lets assign each topic's data to the template file */ $result = $subForm->getAllTopics(); /* Are there any topics yet? */ if (mysqli_num_rows($result)) { $topics_found = true; $i = 1; while ($data = mysqli_fetch_array($result)) { /* If even iteration, we need to display different style of table */ if ($i % 2 == 0) { $even = ' class="even"'; } else { $even = ''; } /* Assign data for the loop */ $tpl->assignLoop(array( "TOPICS.ID" => $data['id'], "TOPICS.TITLE" => $data['topic'], "TOPICS.EVEN" => $even, )); $i++; } $tpl->parseLoop('TOPICS'); $tpl->parseIf(); /* No topics yet */ } else { $topics_not_found = true; } /* Parse the error/success message(s) */ $tpl->assignIf(array( "TOPICS_FOUND" => $topics_found, "TOPICS_NOT_FOUND" => $topics_not_found, "ERR_TOPIC_TITLE" => $err_topic_title, "MSG_DELETE_SUCCESS" => $msg_delete_success, "MSG_ADD_SUCCESS" => $msg_add_success, "MSG_NOTES_SUCCESS" => $msg_notes_success, "MSG_FILE_TYPES_SUCCESS" => $msg_file_types_success, )); $tpl->parseIf(); /* Get conference's configuration */ $conference_data = $conference->getConfiguration(); /* Assign and parse the submission form notes and allowed file types */ $tpl->assignStr(array( "SUBFORM_NOTES" => $conference_data['subform_notes'], "SUBFORM_FILE_TYPES" => $conference_data['subform_file_types'], )); $tpl->parseStr(); /* Output the final HTML code */ $tpl->output(); /* Intitalize and output footer */ initFooter(); ?>
jakkub/Confy
src/admin/conference_subform.php
PHP
mit
3,708
[ 30522, 1026, 1029, 25718, 1013, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1013, 1013, 1008, 12339, 2...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
# AUTOGENERATED FILE FROM balenalib/orbitty-tx2-debian:bullseye-build ENV GO_VERSION 1.15.8 RUN mkdir -p /usr/local/go \ && curl -SLO "https://storage.googleapis.com/golang/go$GO_VERSION.linux-arm64.tar.gz" \ && echo "0e31ea4bf53496b0f0809730520dee98c0ae5c530f3701a19df0ba0a327bf3d2 go$GO_VERSION.linux-arm64.tar.gz" | sha256sum -c - \ && tar -xzf "go$GO_VERSION.linux-arm64.tar.gz" -C /usr/local/go --strip-components=1 \ && rm -f go$GO_VERSION.linux-arm64.tar.gz ENV GOROOT /usr/local/go ENV GOPATH /go ENV PATH $GOPATH/bin:/usr/local/go/bin:$PATH RUN mkdir -p "$GOPATH/src" "$GOPATH/bin" && chmod -R 777 "$GOPATH" WORKDIR $GOPATH CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"] RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@golang.sh" \ && echo "Running test-stack@golang" \ && chmod +x test-stack@golang.sh \ && bash test-stack@golang.sh \ && rm -rf test-stack@golang.sh RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v8 \nOS: Debian Bullseye \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nGo v1.15.8 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && cp /bin/sh /bin/sh.real \ && mv /bin/sh-shim /bin/sh
nghiant2710/base-images
balena-base-images/golang/orbitty-tx2/debian/bullseye/1.15.8/build/Dockerfile
Dockerfile
apache-2.0
2,004
[ 30522, 1001, 8285, 6914, 16848, 5371, 2013, 28352, 30524, 2475, 1011, 2139, 15599, 1024, 12065, 17683, 1011, 3857, 4372, 2615, 2175, 1035, 2544, 1015, 1012, 2321, 1012, 1022, 2448, 12395, 4305, 2099, 1011, 1052, 1013, 2149, 2099, 1013, 2334...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32.SafeHandles; using System; using System.Runtime.InteropServices; internal partial class Interop { internal partial class Kernel32 { [DllImport(Libraries.Kernel32, SetLastError = true)] internal static extern bool SetFileInformationByHandle(SafeFileHandle hFile, FILE_INFO_BY_HANDLE_CLASS FileInformationClass, ref FILE_BASIC_INFO lpFileInformation, uint dwBufferSize); // Default values indicate "no change". Use defaults so that we don't force callsites to be aware of the default values internal static unsafe bool SetFileTime( SafeFileHandle hFile, long creationTime = -1, long lastAccessTime = -1, long lastWriteTime = -1, long changeTime = -1, uint fileAttributes = 0) { FILE_BASIC_INFO basicInfo = new FILE_BASIC_INFO() { CreationTime = creationTime, LastAccessTime = lastAccessTime, LastWriteTime = lastWriteTime, ChangeTime = changeTime, FileAttributes = fileAttributes }; return SetFileInformationByHandle(hFile, FILE_INFO_BY_HANDLE_CLASS.FileBasicInfo, ref basicInfo, (uint)sizeof(FILE_BASIC_INFO)); } internal struct FILE_BASIC_INFO { internal long CreationTime; internal long LastAccessTime; internal long LastWriteTime; internal long ChangeTime; internal uint FileAttributes; } internal enum FILE_INFO_BY_HANDLE_CLASS : uint { FileBasicInfo = 0x0u, FileStandardInfo = 0x1u, FileNameInfo = 0x2u, FileRenameInfo = 0x3u, FileDispositionInfo = 0x4u, FileAllocationInfo = 0x5u, FileEndOfFileInfo = 0x6u, FileStreamInfo = 0x7u, FileCompressionInfo = 0x8u, FileAttributeTagInfo = 0x9u, FileIdBothDirectoryInfo = 0xAu, FileIdBothDirectoryRestartInfo = 0xBu, FileIoPriorityHintInfo = 0xCu, FileRemoteProtocolInfo = 0xDu, FileFullDirectoryInfo = 0xEu, FileFullDirectoryRestartInfo = 0xFu, FileStorageInfo = 0x10u, FileAlignmentInfo = 0x11u, FileIdInfo = 0x12u, FileIdExtdDirectoryInfo = 0x13u, FileIdExtdDirectoryRestartInfo = 0x14u, MaximumFileInfoByHandleClass = 0x15u, } } }
nbarbettini/corefx
src/Common/src/Interop/Windows/kernel32/Interop.SetFileInformationByHandle.cs
C#
mit
2,745
[ 30522, 1013, 1013, 7000, 2000, 1996, 1012, 5658, 3192, 2104, 2028, 2030, 2062, 10540, 1012, 1013, 1013, 1996, 1012, 5658, 3192, 15943, 2023, 5371, 2000, 2017, 2104, 1996, 10210, 6105, 1012, 1013, 1013, 2156, 1996, 6105, 5371, 1999, 1996, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/***************************************************************** * This file is part of jot-lib (or "jot" for short): * <http://code.google.com/p/jot-lib/> * * jot-lib 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. * * jot-lib 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 jot-lib. If not, see <http://www.gnu.org/licenses/>.` *****************************************************************/ #ifndef FILE_SELECT_ICON_BLANK_H_INCLUDED #define FILE_SELECT_ICON_BLANK_H_INCLUDED int file_select_blank_icon[] = {20, 20, 200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200, 200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200, 200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200, 200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200, 200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200, 200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200, 200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200, 200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200, 200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200, 200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200, 200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200, 200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200, 200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200, 200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200, 200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200, 200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200, 200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200, 200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200, 200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200, 200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200 }; #endif
karmakat/jot-lib
src/widgets/file_select_icon_blank.hpp
C++
gpl-3.0
5,830
[ 30522, 1013, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 100...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
module PreferenceSections class FooterAndExternalLinksSection def name I18n.t('admin.contents.edit.footer_and_external_links') end def preferences [ :footer_logo, :footer_facebook_url, :footer_twitter_url, :footer_instagram_url, :footer_linkedin_url, :footer_googleplus_url, :footer_pinterest_url, :footer_email, :community_forum_url, :footer_links_md, :footer_about_url ] end end end
lin-d-hop/openfoodnetwork
app/models/preference_sections/footer_and_external_links_section.rb
Ruby
agpl-3.0
512
[ 30522, 11336, 18394, 18491, 2015, 2465, 3329, 23169, 3207, 18413, 11795, 8095, 19839, 11393, 7542, 13366, 2171, 1045, 15136, 2078, 1012, 1056, 1006, 1005, 4748, 10020, 1012, 8417, 1012, 10086, 1012, 3329, 2121, 1035, 1998, 1035, 6327, 1035, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
// // header.hpp // ~~~~~~~~~~ // // Copyright (c) 2003-2018 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 HTTP_SERVER3_HEADER_HPP #define HTTP_SERVER3_HEADER_HPP #include <string> namespace http { namespace server3 { struct header { std::string name; std::string value; }; } // namespace server3 } // namespace http #endif // HTTP_SERVER3_HEADER_HPP
vslavik/poedit
deps/boost/libs/asio/example/cpp03/http/server3/header.hpp
C++
mit
534
[ 30522, 1013, 1013, 1013, 1013, 20346, 1012, 6522, 2361, 1013, 1013, 1066, 1066, 1066, 1066, 1066, 1066, 1066, 1066, 1066, 1066, 1013, 1013, 1013, 1013, 9385, 1006, 1039, 1007, 2494, 1011, 2760, 5696, 1049, 1012, 12849, 7317, 17896, 1006, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
import { Type } from 'angular2/src/facade/lang'; import { SetterFn, GetterFn, MethodFn } from './types'; import { PlatformReflectionCapabilities } from './platform_reflection_capabilities'; export { SetterFn, GetterFn, MethodFn } from './types'; export { PlatformReflectionCapabilities } from './platform_reflection_capabilities'; /** * Reflective information about a symbol, including annotations, interfaces, and other metadata. */ export declare class ReflectionInfo { annotations: any[]; parameters: any[][]; factory: Function; interfaces: any[]; propMetadata: { [key: string]: any[]; }; constructor(annotations?: any[], parameters?: any[][], factory?: Function, interfaces?: any[], propMetadata?: { [key: string]: any[]; }); } /** * Provides access to reflection data about symbols. Used internally by Angular * to power dependency injection and compilation. */ export declare class Reflector { reflectionCapabilities: PlatformReflectionCapabilities; constructor(reflectionCapabilities: PlatformReflectionCapabilities); isReflectionEnabled(): boolean; /** * Causes `this` reflector to track keys used to access * {@link ReflectionInfo} objects. */ trackUsage(): void; /** * Lists types for which reflection information was not requested since * {@link #trackUsage} was called. This list could later be audited as * potential dead code. */ listUnusedKeys(): any[]; registerFunction(func: Function, funcInfo: ReflectionInfo): void; registerType(type: Type, typeInfo: ReflectionInfo): void; registerGetters(getters: { [key: string]: GetterFn; }): void; registerSetters(setters: { [key: string]: SetterFn; }): void; registerMethods(methods: { [key: string]: MethodFn; }): void; factory(type: Type): Function; parameters(typeOrFunc: any): any[][]; annotations(typeOrFunc: any): any[]; propMetadata(typeOrFunc: any): { [key: string]: any[]; }; interfaces(type: Type): any[]; getter(name: string): GetterFn; setter(name: string): SetterFn; method(name: string): MethodFn; importUri(type: Type): string; }
hbthegreat/interactively
node_modules/angular2/src/core/reflection/reflector.d.ts
TypeScript
mit
2,285
[ 30522, 12324, 1063, 2828, 1065, 2013, 1005, 16108, 2475, 1013, 5034, 2278, 1013, 8508, 1013, 11374, 1005, 1025, 12324, 1063, 2275, 3334, 2546, 2078, 1010, 2131, 3334, 2546, 2078, 1010, 4118, 2546, 2078, 1065, 2013, 1005, 1012, 1013, 4127, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the examples of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef FLOWLAYOUT_H #define FLOWLAYOUT_H #include <QLayout> #include <QRect> #include <QWidgetItem> //! [0] class FlowLayout : public QLayout { public: FlowLayout(QWidget *parent, int margin = -1, int hSpacing = -1, int vSpacing = -1); FlowLayout(int margin = -1, int hSpacing = -1, int vSpacing = -1); ~FlowLayout(); void addItem(QLayoutItem *item); int horizontalSpacing() const; int verticalSpacing() const; Qt::Orientations expandingDirections() const; bool hasHeightForWidth() const; int heightForWidth(int) const; int count() const; QLayoutItem *itemAt(int index) const; QSize minimumSize() const; void setGeometry(const QRect &rect); QSize sizeHint() const; QLayoutItem *takeAt(int index); private: int doLayout(const QRect &rect, bool testOnly) const; int smartSpacing(QStyle::PixelMetric pm) const; QList<QLayoutItem *> itemList; int m_hSpace; int m_vSpace; }; //! [0] #endif
librelab/qtmoko-test
qtopiacore/qt/examples/layouts/flowlayout/flowlayout.h
C
gpl-2.0
2,910
[ 30522, 1013, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 100...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
using System; namespace TestAPI.Areas.HelpPage { /// <summary> /// This represents an invalid sample on the help page. There's a display template named InvalidSample associated with this class. /// </summary> public class InvalidSample { public InvalidSample(string errorMessage) { if (errorMessage == null) { throw new ArgumentNullException("errorMessage"); } ErrorMessage = errorMessage; } public string ErrorMessage { get; private set; } public override bool Equals(object obj) { InvalidSample other = obj as InvalidSample; return other != null && ErrorMessage == other.ErrorMessage; } public override int GetHashCode() { return ErrorMessage.GetHashCode(); } public override string ToString() { return ErrorMessage; } } }
OasesOng/TestVS
TestAPI/TestAPI/Areas/HelpPage/SampleGeneration/InvalidSample.cs
C#
mit
969
[ 30522, 2478, 2291, 1025, 3415, 15327, 3231, 9331, 2072, 1012, 2752, 1012, 2393, 13704, 1063, 1013, 1013, 1013, 1026, 12654, 1028, 1013, 1013, 1013, 2023, 5836, 2019, 19528, 7099, 2006, 1996, 2393, 3931, 1012, 2045, 1005, 1055, 1037, 4653, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
# Github pages for DHGMS Solutions ## Introduction This is the branch for the [Github pages for the DHGMS Solutions project documentation](http://dhgms-solutions.github.io/). ## Viewing the documentation The documentation can be found at http://dhgms-solutions.github.io/ ## Contributing to the documentation It is likely you won't want to contribute to this repository, but one of the [actual project repositories](https://github.com/DHGMS-Solutions/). ### 1\. Fork the documentation See the [github help page for instructions on how to create a fork](http://help.github.com/fork-a-repo/). ### 2\. Write desired content Use your preffered method for carrying out work. ### 3\. Send a pull request See the [github help page for instructions on how to send pull requests](http://help.github.com/send-pull-requests/)
DHGMS-Solutions/dhgms-solutions.github.io
README.md
Markdown
apache-2.0
827
[ 30522, 1001, 21025, 2705, 12083, 5530, 2005, 28144, 21693, 2015, 7300, 1001, 1001, 4955, 2023, 2003, 1996, 3589, 2005, 1996, 1031, 21025, 2705, 12083, 5530, 2005, 1996, 28144, 21693, 2015, 7300, 2622, 12653, 1033, 1006, 8299, 1024, 1013, 10...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<!DOCTYPE html> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <title>Poster</title> <meta name="description" content="A poster" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="stylesheet" type="text/css" href="../../normalize.css" /> <script type="text/javascript" src="../../MathJax/MathJax.js?config=TeX-AMS-MML_HTMLorMML"> </script> <script src="../../pdf.js" type="text/javascript"></script> <link rel="stylesheet" type="text/css" href="../../postly.css" /> <script src="../../postly.js" type="text/javascript"></script> <link rel="stylesheet" type="text/css" href="../../wolverine.css" /> <style> /* Custom Styles */ </style> </head> <body> <main> <!-- header is the title box --> <header> <div class="header-background"> <!-- Images go here for both left and right --> <img src="logo.svg" class="logo" /> <div class="title-box"> <h1 class="title">Some Awesome Research</h1> <h2 class="author">Researcher <a href="mailto:researcher@instutio.org">researcher@institution.org</a></h2> </div> </div> </header> <div class="columns"> <div class="column"> <section class="box"> <h3 class="box-title">Introduction</h3> <div class="box-content"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas interdum id augue vel laoreet. Morbi vel odio enim. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent et risus ac ex consequat mollis in facilisis tortor. Phasellus dignissim bibendum sem. Nunc elit urna, ullamcorper id erat ut, pharetra euismod risus. Fusce interdum lectus velit, sed convallis nisi tempus in. Cras faucibus vitae sem sit amet facilisis. Duis ullamcorper felis quis enim laoreet, a vehicula leo iaculis. Curabitur ultrices lobortis nisi, volutpat dictum magna hendrerit pharetra. Mauris id velit eu odio faucibus gravida ac vel magna. Maecenas commodo imperdiet justo elementum elementum. Nam turpis risus, bibendum in eleifend vitae, aliquam quis erat. Nullam tristique arcu quis metus aliquam aliquam. </div> </section> <section class="box"> <h3 class="box-title">Methods</h3> <div class="box-content"> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas interdum id augue vel laoreet. Morbi vel odio enim. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent et risus ac ex consequat mollis in facilisis tortor. Phasellus dignissim bibendum sem. Nunc elit urna, ullamcorper id erat ut, pharetra euismod risus. Fusce interdum lectus velit, sed convallis nisi tempus in. Cras faucibus vitae sem sit amet facilisis. Duis ullamcorper felis quis enim laoreet, a vehicula leo iaculis. Curabitur ultrices lobortis nisi, volutpat dictum magna hendrerit pharetra. Mauris id velit eu odio faucibus gravida ac vel magna. Maecenas commodo imperdiet justo elementum elementum. Nam turpis risus, bibendum in eleifend vitae, aliquam quis erat. Nullam tristique arcu quis metus aliquam aliquam.</p> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas interdum id augue vel laoreet. Morbi vel odio enim. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent et risus ac ex consequat mollis in facilisis tortor. Phasellus dignissim bibendum sem. Nunc elit urna, ullamcorper id erat ut, pharetra euismod risus. Fusce interdum lectus velit, sed convallis nisi tempus in. Cras faucibus vitae sem sit amet facilisis. Duis ullamcorper felis quis enim laoreet, a vehicula leo iaculis. Curabitur ultrices lobortis nisi, volutpat dictum magna hendrerit pharetra. Mauris id velit eu odio faucibus gravida ac vel magna. Maecenas commodo imperdiet justo elementum elementum. Nam turpis risus, bibendum in eleifend vitae, aliquam quis erat. Nullam tristique arcu quis metus aliquam aliquam.</p> </div> </section> </div> <div class="column"> <section class="box"> <h3 class="box-title">Math</h3> <div class="box-content"> There's inline math like \(\sqrt{\alpha}\) and block math like: \[ \sum_i \frac{1 + e^\pi}{2^i} \] </div> </section> <section class="box"> <h3 class="box-title">Figures</h3> <div class="box-content"> Figures can be made with straight html like this: <!-- PDFs can be included as images, but this doesn't make them scale appropriately --> <img src="figure.pdf" class="figure" /> </div> </section> <section class="box"> <h3 class="box-title">Results</h3> <div class="box-content"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas interdum id augue vel laoreet. Morbi vel odio enim. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent et risus ac ex consequat mollis in facilisis tortor. Phasellus dignissim bibendum sem. Nunc elit urna, ullamcorper id erat ut, pharetra euismod risus. Fusce interdum lectus velit, sed convallis nisi tempus in. Cras faucibus vitae sem sit amet facilisis. Duis ullamcorper felis quis enim laoreet, a vehicula leo iaculis. Curabitur ultrices lobortis nisi, volutpat dictum magna hendrerit pharetra. Mauris id velit eu odio faucibus gravida ac vel magna. Maecenas commodo imperdiet justo elementum elementum. Nam turpis risus, bibendum in eleifend vitae, aliquam quis erat. Nullam tristique arcu quis metus aliquam aliquam. </div> </section> </div> <div class="column"> <section class="box"> <h3 class="box-title">Conclusion</h3> <div class="box-content"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas interdum id augue vel laoreet. Morbi vel odio enim. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent et risus ac ex consequat mollis in facilisis tortor. Phasellus dignissim bibendum sem. Nunc elit urna, ullamcorper id erat ut, pharetra euismod risus. Fusce interdum lectus velit, sed convallis nisi tempus in. Cras faucibus vitae sem sit amet facilisis. Duis ullamcorper felis quis enim laoreet, a vehicula leo iaculis. Curabitur ultrices lobortis nisi, volutpat dictum magna hendrerit pharetra. Mauris id velit eu odio faucibus gravida ac vel magna. Maecenas commodo imperdiet justo elementum elementum. Nam turpis risus, bibendum in eleifend vitae, aliquam quis erat. Nullam tristique arcu quis metus aliquam aliquam. </div> </section> </div> </div> </main> </body> </html>
erikbrinkman/postly
demos/wolverine/index.html
HTML
mit
7,754
[ 30522, 1026, 999, 9986, 13874, 16129, 1028, 1026, 2132, 1028, 1026, 18804, 25869, 13462, 1027, 1000, 21183, 2546, 1011, 1022, 1000, 1013, 1028, 1026, 18804, 8299, 1011, 1041, 15549, 2615, 1027, 1000, 1060, 1011, 25423, 1011, 11892, 1000, 41...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<?php require 'autoload.php'; /** * This example shows the basic usage of file filesystem it self to store scan information * about your scans. If you would use this code in real life please make sure you store the output file (data.yml) * in a secure location on your drive. */ $path = dirname(__FILE__)."/assets"; $newfile = $path.'/new.tmp'; $timefile = $path.'/time.txt'; $datafile = $path.'/data.yml'; /** * Oke lets instantiate a new service and scan the assets folder inside * our current folder and write the data.yml file to the filesystem using the Filesystem adapter. */ $scan = new Redbox\Scan\ScanService(new Redbox\Scan\Adapter\Filesystem($datafile)); if ($scan->index($path, 'Basic scan', date("Y-m-d H:i:s")) == false) { throw new Exception('Writing datafile failed.'); } /** * After indexing the directory let's create a new file and update an other so * we can see if the filesystem picks it up. */ file_put_contents($newfile, 'Hello world'); file_put_contents($timefile, time()); /** * Oke the changes have been made lets scan the assets directory again for changes. */ $report = $scan->scan(); /** * Do the cleanup. This is not needed if this where to be real code. */ unlink($newfile); /** * Output the changes since index action. */ if(php_sapi_name() == "cli") { echo "New files\n\n"; foreach ($report->getNewfiles() as $file) { echo $file->getFilename().' '.Redbox\Scan\Filesystem\FileInfo::getFileHash($file->getRealPath())."\n"; } echo "\nModified Files\n\n"; foreach ($report->getModifiedFiles() as $file) { echo $file->getFilename().' '.Redbox\Scan\Filesystem\FileInfo::getFileHash($file->getRealPath())."\n"; } echo "\n"; } else { echo '<h1>New files</h1>'; foreach ($report->getNewfiles() as $file) { echo '<li>'.$file->getFilename().' '.Redbox\Scan\Filesystem\FileInfo::getFileHash($file->getRealPath()).'</li>'; } echo '</ul>'; echo '<h1>Modified Files</h1>'; foreach ($report->getModifiedFiles() as $file) { echo '<li>'.$file->getFilename().' '.Redbox\Scan\Filesystem\FileInfo::getFileHash($file->getRealPath()).'</li>'; } echo '</ul>'; }
johnnymast/redbox-scan
examples/basic.php
PHP
mit
2,200
[ 30522, 1026, 1029, 25718, 5478, 1005, 8285, 11066, 1012, 25718, 1005, 1025, 1013, 1008, 1008, 1008, 2023, 2742, 3065, 1996, 3937, 8192, 1997, 5371, 6764, 27268, 6633, 2009, 2969, 2000, 3573, 13594, 2592, 1008, 2055, 2115, 27404, 1012, 2065,...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/*! * Bootstrap v4.0.0-alpha.6 (https://getbootstrap.com) * Copyright 2011-2017 The Bootstrap Authors * Copyright 2011-2017 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) */ /*! normalize.css v5.0.0 | MIT License | github.com/necolas/normalize.css */ html { font-family: sans-serif; line-height: 1.15; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%; } body { margin: 0; } article, aside, footer, header, nav, section { display: block; } h1 { font-size: 2em; margin: 0.67em 0; } figcaption, figure, main { display: block; } figure { margin: 1em 40px; } hr { -webkit-box-sizing: content-box; box-sizing: content-box; height: 0; overflow: visible; } pre { font-family: monospace, monospace; font-size: 1em; } a { background-color: transparent; -webkit-text-decoration-skip: objects; } a:active, a:hover { outline-width: 0; } abbr[title] { border-bottom: none; text-decoration: underline; text-decoration: underline dotted; } b, strong { font-weight: inherit; } b, strong { font-weight: bolder; } code, kbd, samp { font-family: monospace, monospace; font-size: 1em; } dfn { font-style: italic; } mark { background-color: #ff0; color: #000; } small { font-size: 80%; } sub, sup { font-size: 75%; line-height: 0; position: relative; vertical-align: baseline; } sub { bottom: -0.25em; } sup { top: -0.5em; } audio, video { display: inline-block; } audio:not([controls]) { display: none; height: 0; } img { border-style: none; } svg:not(:root) { overflow: hidden; } button, input, optgroup, select, textarea { font-family: sans-serif; font-size: 100%; line-height: 1.15; margin: 0; } button, input { overflow: visible; } button, select { text-transform: none; } button, html [type="button"], [type="reset"], [type="submit"] { -webkit-appearance: button; } button::-moz-focus-inner, [type="button"]::-moz-focus-inner, [type="reset"]::-moz-focus-inner, [type="submit"]::-moz-focus-inner { border-style: none; padding: 0; } button:-moz-focusring, [type="button"]:-moz-focusring, [type="reset"]:-moz-focusring, [type="submit"]:-moz-focusring { outline: 1px dotted ButtonText; } fieldset { border: 1px solid #c0c0c0; margin: 0 2px; padding: 0.35em 0.625em 0.75em; } legend { -webkit-box-sizing: border-box; box-sizing: border-box; color: inherit; display: table; max-width: 100%; padding: 0; white-space: normal; } progress { display: inline-block; vertical-align: baseline; } textarea { overflow: auto; } [type="checkbox"], [type="radio"] { -webkit-box-sizing: border-box; box-sizing: border-box; padding: 0; } [type="number"]::-webkit-inner-spin-button, [type="number"]::-webkit-outer-spin-button { height: auto; } [type="search"] { -webkit-appearance: textfield; outline-offset: -2px; } [type="search"]::-webkit-search-cancel-button, [type="search"]::-webkit-search-decoration { -webkit-appearance: none; } ::-webkit-file-upload-button { -webkit-appearance: button; font: inherit; } details, menu { display: block; } summary { display: list-item; } canvas { display: inline-block; } template { display: none; } [hidden] { display: none; } @media print { *, *::before, *::after, p::first-letter, div::first-letter, blockquote::first-letter, li::first-letter, p::first-line, div::first-line, blockquote::first-line, li::first-line { text-shadow: none !important; -webkit-box-shadow: none !important; box-shadow: none !important; } a, a:visited { text-decoration: underline; } abbr[title]::after { content: " (" attr(title) ")"; } pre { white-space: pre-wrap !important; } pre, blockquote { border: 1px solid #999; page-break-inside: avoid; } thead { display: table-header-group; } tr, img { page-break-inside: avoid; } p, h2, h3 { orphans: 3; widows: 3; } h2, h3 { page-break-after: avoid; } .navbar { display: none; } .badge { border: 1px solid #000; } .table { border-collapse: collapse !important; } .table td, .table th { background-color: #fff !important; } .table-bordered th, .table-bordered td { border: 1px solid #ddd !important; } } html { -webkit-box-sizing: border-box; box-sizing: border-box; } *, *::before, *::after { -webkit-box-sizing: inherit; box-sizing: inherit; } @-ms-viewport { width: device-width; } html { -ms-overflow-style: scrollbar; -webkit-tap-highlight-color: transparent; } body { font-family: -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; font-size: 1rem; font-weight: normal; line-height: 1.5; color: #292b2c; background-color: #fff; } [tabindex="-1"]:focus { outline: none !important; } h1, h2, h3, h4, h5, h6 { margin-top: 0; margin-bottom: .5rem; } p { margin-top: 0; margin-bottom: 1rem; } abbr[title], abbr[data-original-title] { cursor: help; } address { margin-bottom: 1rem; font-style: normal; line-height: inherit; } ol, ul, dl { margin-top: 0; margin-bottom: 1rem; } ol ol, ul ul, ol ul, ul ol { margin-bottom: 0; } dt { font-weight: bold; } dd { margin-bottom: .5rem; margin-left: 0; } blockquote { margin: 0 0 1rem; } a { color: #0275d8; text-decoration: none; } a:focus, a:hover { color: #014c8c; text-decoration: underline; } a:not([href]):not([tabindex]) { color: inherit; text-decoration: none; } a:not([href]):not([tabindex]):focus, a:not([href]):not([tabindex]):hover { color: inherit; text-decoration: none; } a:not([href]):not([tabindex]):focus { outline: 0; } pre { margin-top: 0; margin-bottom: 1rem; overflow: auto; } figure { margin: 0 0 1rem; } img { vertical-align: middle; } [role="button"] { cursor: pointer; } a, area, button, [role="button"], input, label, select, summary, textarea { -ms-touch-action: manipulation; touch-action: manipulation; } table { border-collapse: collapse; background-color: transparent; } caption { padding-top: 0.75rem; padding-bottom: 0.75rem; color: #636c72; text-align: left; caption-side: bottom; } th { text-align: left; } label { display: inline-block; margin-bottom: .5rem; } button:focus { outline: 1px dotted; outline: 5px auto -webkit-focus-ring-color; } input, button, select, textarea { line-height: inherit; } input[type="radio"]:disabled, input[type="checkbox"]:disabled { cursor: not-allowed; } input[type="date"], input[type="time"], input[type="datetime-local"], input[type="month"] { -webkit-appearance: listbox; } textarea { resize: vertical; } fieldset { min-width: 0; padding: 0; margin: 0; border: 0; } legend { display: block; width: 100%; padding: 0; margin-bottom: .5rem; font-size: 1.5rem; line-height: inherit; } input[type="search"] { -webkit-appearance: none; } output { display: inline-block; } [hidden] { display: none !important; } h1, h2, h3, h4, h5, h6, .h1, .h2, .h3, .h4, .h5, .h6 { margin-bottom: 0.5rem; font-family: inherit; font-weight: 500; line-height: 1.1; color: inherit; } h1, .h1 { font-size: 2.5rem; } h2, .h2 { font-size: 2rem; } h3, .h3 { font-size: 1.75rem; } h4, .h4 { font-size: 1.5rem; } h5, .h5 { font-size: 1.25rem; } h6, .h6 { font-size: 1rem; } .lead { font-size: 1.25rem; font-weight: 300; } .display-1 { font-size: 6rem; font-weight: 300; line-height: 1.1; } .display-2 { font-size: 5.5rem; font-weight: 300; line-height: 1.1; } .display-3 { font-size: 4.5rem; font-weight: 300; line-height: 1.1; } .display-4 { font-size: 3.5rem; font-weight: 300; line-height: 1.1; } hr { margin-top: 1rem; margin-bottom: 1rem; border: 0; border-top: 1px solid rgba(0, 0, 0, 0.1); } small, .small { font-size: 80%; font-weight: normal; } mark, .mark { padding: 0.2em; background-color: #fcf8e3; } .list-unstyled { padding-left: 0; list-style: none; } .list-inline { padding-left: 0; list-style: none; } .list-inline-item { display: inline-block; } .list-inline-item:not(:last-child) { margin-right: 5px; } .initialism { font-size: 90%; text-transform: uppercase; } .blockquote { padding: 0.5rem 1rem; margin-bottom: 1rem; font-size: 1.25rem; border-left: 0.25rem solid #eceeef; } .blockquote-footer { display: block; font-size: 80%; color: #636c72; } .blockquote-footer::before { content: "\2014 \00A0"; } .blockquote-reverse { padding-right: 1rem; padding-left: 0; text-align: right; border-right: 0.25rem solid #eceeef; border-left: 0; } .blockquote-reverse .blockquote-footer::before { content: ""; } .blockquote-reverse .blockquote-footer::after { content: "\00A0 \2014"; } .img-fluid { max-width: 100%; height: auto; } .img-thumbnail { padding: 0.25rem; background-color: #fff; border: 1px solid #ddd; border-radius: 0.25rem; -webkit-transition: all 0.2s ease-in-out; -o-transition: all 0.2s ease-in-out; transition: all 0.2s ease-in-out; max-width: 100%; height: auto; } .figure { display: inline-block; } .figure-img { margin-bottom: 0.5rem; line-height: 1; } .figure-caption { font-size: 90%; color: #636c72; } code, kbd, pre, samp { font-family: Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; } code { padding: 0.2rem 0.4rem; font-size: 90%; color: #bd4147; background-color: #f7f7f9; border-radius: 0.25rem; } a > code { padding: 0; color: inherit; background-color: inherit; } kbd { padding: 0.2rem 0.4rem; font-size: 90%; color: #fff; background-color: #292b2c; border-radius: 0.2rem; } kbd kbd { padding: 0; font-size: 100%; font-weight: bold; } pre { display: block; margin-top: 0; margin-bottom: 1rem; font-size: 90%; color: #292b2c; } pre code { padding: 0; font-size: inherit; color: inherit; background-color: transparent; border-radius: 0; } .pre-scrollable { max-height: 340px; overflow-y: scroll; } .container { position: relative; margin-left: auto; margin-right: auto; padding-right: 15px; padding-left: 15px; } @media (min-width: 576px) { .container { padding-right: 15px; padding-left: 15px; } } @media (min-width: 768px) { .container { padding-right: 15px; padding-left: 15px; } } @media (min-width: 992px) { .container { padding-right: 15px; padding-left: 15px; } } @media (min-width: 1200px) { .container { padding-right: 15px; padding-left: 15px; } } @media (min-width: 576px) { .container { width: 540px; max-width: 100%; } } @media (min-width: 768px) { .container { width: 720px; max-width: 100%; } } @media (min-width: 992px) { .container { width: 960px; max-width: 100%; } } @media (min-width: 1200px) { .container { width: 1140px; max-width: 100%; } } .container-fluid { position: relative; margin-left: auto; margin-right: auto; padding-right: 15px; padding-left: 15px; } @media (min-width: 576px) { .container-fluid { padding-right: 15px; padding-left: 15px; } } @media (min-width: 768px) { .container-fluid { padding-right: 15px; padding-left: 15px; } } @media (min-width: 992px) { .container-fluid { padding-right: 15px; padding-left: 15px; } } @media (min-width: 1200px) { .container-fluid { padding-right: 15px; padding-left: 15px; } } .row { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-flex-wrap: wrap; -ms-flex-wrap: wrap; flex-wrap: wrap; margin-right: -15px; margin-left: -15px; } @media (min-width: 576px) { .row { margin-right: -15px; margin-left: -15px; } } @media (min-width: 768px) { .row { margin-right: -15px; margin-left: -15px; } } @media (min-width: 992px) { .row { margin-right: -15px; margin-left: -15px; } } @media (min-width: 1200px) { .row { margin-right: -15px; margin-left: -15px; } } .no-gutters { margin-right: 0; margin-left: 0; } .no-gutters > .col, .no-gutters > [class*="col-"] { padding-right: 0; padding-left: 0; } .col-1, .col-2, .col-3, .col-4, .col-5, .col-6, .col-7, .col-8, .col-9, .col-10, .col-11, .col-12, .col, .col-sm-1, .col-sm-2, .col-sm-3, .col-sm-4, .col-sm-5, .col-sm-6, .col-sm-7, .col-sm-8, .col-sm-9, .col-sm-10, .col-sm-11, .col-sm-12, .col-sm, .col-md-1, .col-md-2, .col-md-3, .col-md-4, .col-md-5, .col-md-6, .col-md-7, .col-md-8, .col-md-9, .col-md-10, .col-md-11, .col-md-12, .col-md, .col-lg-1, .col-lg-2, .col-lg-3, .col-lg-4, .col-lg-5, .col-lg-6, .col-lg-7, .col-lg-8, .col-lg-9, .col-lg-10, .col-lg-11, .col-lg-12, .col-lg, .col-xl-1, .col-xl-2, .col-xl-3, .col-xl-4, .col-xl-5, .col-xl-6, .col-xl-7, .col-xl-8, .col-xl-9, .col-xl-10, .col-xl-11, .col-xl-12, .col-xl { position: relative; width: 100%; min-height: 1px; padding-right: 15px; padding-left: 15px; } @media (min-width: 576px) { .col-1, .col-2, .col-3, .col-4, .col-5, .col-6, .col-7, .col-8, .col-9, .col-10, .col-11, .col-12, .col, .col-sm-1, .col-sm-2, .col-sm-3, .col-sm-4, .col-sm-5, .col-sm-6, .col-sm-7, .col-sm-8, .col-sm-9, .col-sm-10, .col-sm-11, .col-sm-12, .col-sm, .col-md-1, .col-md-2, .col-md-3, .col-md-4, .col-md-5, .col-md-6, .col-md-7, .col-md-8, .col-md-9, .col-md-10, .col-md-11, .col-md-12, .col-md, .col-lg-1, .col-lg-2, .col-lg-3, .col-lg-4, .col-lg-5, .col-lg-6, .col-lg-7, .col-lg-8, .col-lg-9, .col-lg-10, .col-lg-11, .col-lg-12, .col-lg, .col-xl-1, .col-xl-2, .col-xl-3, .col-xl-4, .col-xl-5, .col-xl-6, .col-xl-7, .col-xl-8, .col-xl-9, .col-xl-10, .col-xl-11, .col-xl-12, .col-xl { padding-right: 15px; padding-left: 15px; } } @media (min-width: 768px) { .col-1, .col-2, .col-3, .col-4, .col-5, .col-6, .col-7, .col-8, .col-9, .col-10, .col-11, .col-12, .col, .col-sm-1, .col-sm-2, .col-sm-3, .col-sm-4, .col-sm-5, .col-sm-6, .col-sm-7, .col-sm-8, .col-sm-9, .col-sm-10, .col-sm-11, .col-sm-12, .col-sm, .col-md-1, .col-md-2, .col-md-3, .col-md-4, .col-md-5, .col-md-6, .col-md-7, .col-md-8, .col-md-9, .col-md-10, .col-md-11, .col-md-12, .col-md, .col-lg-1, .col-lg-2, .col-lg-3, .col-lg-4, .col-lg-5, .col-lg-6, .col-lg-7, .col-lg-8, .col-lg-9, .col-lg-10, .col-lg-11, .col-lg-12, .col-lg, .col-xl-1, .col-xl-2, .col-xl-3, .col-xl-4, .col-xl-5, .col-xl-6, .col-xl-7, .col-xl-8, .col-xl-9, .col-xl-10, .col-xl-11, .col-xl-12, .col-xl { padding-right: 15px; padding-left: 15px; } } @media (min-width: 992px) { .col-1, .col-2, .col-3, .col-4, .col-5, .col-6, .col-7, .col-8, .col-9, .col-10, .col-11, .col-12, .col, .col-sm-1, .col-sm-2, .col-sm-3, .col-sm-4, .col-sm-5, .col-sm-6, .col-sm-7, .col-sm-8, .col-sm-9, .col-sm-10, .col-sm-11, .col-sm-12, .col-sm, .col-md-1, .col-md-2, .col-md-3, .col-md-4, .col-md-5, .col-md-6, .col-md-7, .col-md-8, .col-md-9, .col-md-10, .col-md-11, .col-md-12, .col-md, .col-lg-1, .col-lg-2, .col-lg-3, .col-lg-4, .col-lg-5, .col-lg-6, .col-lg-7, .col-lg-8, .col-lg-9, .col-lg-10, .col-lg-11, .col-lg-12, .col-lg, .col-xl-1, .col-xl-2, .col-xl-3, .col-xl-4, .col-xl-5, .col-xl-6, .col-xl-7, .col-xl-8, .col-xl-9, .col-xl-10, .col-xl-11, .col-xl-12, .col-xl { padding-right: 15px; padding-left: 15px; } } @media (min-width: 1200px) { .col-1, .col-2, .col-3, .col-4, .col-5, .col-6, .col-7, .col-8, .col-9, .col-10, .col-11, .col-12, .col, .col-sm-1, .col-sm-2, .col-sm-3, .col-sm-4, .col-sm-5, .col-sm-6, .col-sm-7, .col-sm-8, .col-sm-9, .col-sm-10, .col-sm-11, .col-sm-12, .col-sm, .col-md-1, .col-md-2, .col-md-3, .col-md-4, .col-md-5, .col-md-6, .col-md-7, .col-md-8, .col-md-9, .col-md-10, .col-md-11, .col-md-12, .col-md, .col-lg-1, .col-lg-2, .col-lg-3, .col-lg-4, .col-lg-5, .col-lg-6, .col-lg-7, .col-lg-8, .col-lg-9, .col-lg-10, .col-lg-11, .col-lg-12, .col-lg, .col-xl-1, .col-xl-2, .col-xl-3, .col-xl-4, .col-xl-5, .col-xl-6, .col-xl-7, .col-xl-8, .col-xl-9, .col-xl-10, .col-xl-11, .col-xl-12, .col-xl { padding-right: 15px; padding-left: 15px; } } .col { -webkit-flex-basis: 0; -ms-flex-preferred-size: 0; flex-basis: 0; -webkit-box-flex: 1; -webkit-flex-grow: 1; -ms-flex-positive: 1; flex-grow: 1; max-width: 100%; } .col-auto { -webkit-box-flex: 0; -webkit-flex: 0 0 auto; -ms-flex: 0 0 auto; flex: 0 0 auto; width: auto; } .col-1 { -webkit-box-flex: 0; -webkit-flex: 0 0 8.333333%; -ms-flex: 0 0 8.333333%; flex: 0 0 8.333333%; max-width: 8.333333%; } .col-2 { -webkit-box-flex: 0; -webkit-flex: 0 0 16.666667%; -ms-flex: 0 0 16.666667%; flex: 0 0 16.666667%; max-width: 16.666667%; } .col-3 { -webkit-box-flex: 0; -webkit-flex: 0 0 25%; -ms-flex: 0 0 25%; flex: 0 0 25%; max-width: 25%; } .col-4 { -webkit-box-flex: 0; -webkit-flex: 0 0 33.333333%; -ms-flex: 0 0 33.333333%; flex: 0 0 33.333333%; max-width: 33.333333%; } .col-5 { -webkit-box-flex: 0; -webkit-flex: 0 0 41.666667%; -ms-flex: 0 0 41.666667%; flex: 0 0 41.666667%; max-width: 41.666667%; } .col-6 { -webkit-box-flex: 0; -webkit-flex: 0 0 50%; -ms-flex: 0 0 50%; flex: 0 0 50%; max-width: 50%; } .col-7 { -webkit-box-flex: 0; -webkit-flex: 0 0 58.333333%; -ms-flex: 0 0 58.333333%; flex: 0 0 58.333333%; max-width: 58.333333%; } .col-8 { -webkit-box-flex: 0; -webkit-flex: 0 0 66.666667%; -ms-flex: 0 0 66.666667%; flex: 0 0 66.666667%; max-width: 66.666667%; } .col-9 { -webkit-box-flex: 0; -webkit-flex: 0 0 75%; -ms-flex: 0 0 75%; flex: 0 0 75%; max-width: 75%; } .col-10 { -webkit-box-flex: 0; -webkit-flex: 0 0 83.333333%; -ms-flex: 0 0 83.333333%; flex: 0 0 83.333333%; max-width: 83.333333%; } .col-11 { -webkit-box-flex: 0; -webkit-flex: 0 0 91.666667%; -ms-flex: 0 0 91.666667%; flex: 0 0 91.666667%; max-width: 91.666667%; } .col-12 { -webkit-box-flex: 0; -webkit-flex: 0 0 100%; -ms-flex: 0 0 100%; flex: 0 0 100%; max-width: 100%; } .pull-0 { right: auto; } .pull-1 { right: 8.333333%; } .pull-2 { right: 16.666667%; } .pull-3 { right: 25%; } .pull-4 { right: 33.333333%; } .pull-5 { right: 41.666667%; } .pull-6 { right: 50%; } .pull-7 { right: 58.333333%; } .pull-8 { right: 66.666667%; } .pull-9 { right: 75%; } .pull-10 { right: 83.333333%; } .pull-11 { right: 91.666667%; } .pull-12 { right: 100%; } .push-0 { left: auto; } .push-1 { left: 8.333333%; } .push-2 { left: 16.666667%; } .push-3 { left: 25%; } .push-4 { left: 33.333333%; } .push-5 { left: 41.666667%; } .push-6 { left: 50%; } .push-7 { left: 58.333333%; } .push-8 { left: 66.666667%; } .push-9 { left: 75%; } .push-10 { left: 83.333333%; } .push-11 { left: 91.666667%; } .push-12 { left: 100%; } .offset-1 { margin-left: 8.333333%; } .offset-2 { margin-left: 16.666667%; } .offset-3 { margin-left: 25%; } .offset-4 { margin-left: 33.333333%; } .offset-5 { margin-left: 41.666667%; } .offset-6 { margin-left: 50%; } .offset-7 { margin-left: 58.333333%; } .offset-8 { margin-left: 66.666667%; } .offset-9 { margin-left: 75%; } .offset-10 { margin-left: 83.333333%; } .offset-11 { margin-left: 91.666667%; } @media (min-width: 576px) { .col-sm { -webkit-flex-basis: 0; -ms-flex-preferred-size: 0; flex-basis: 0; -webkit-box-flex: 1; -webkit-flex-grow: 1; -ms-flex-positive: 1; flex-grow: 1; max-width: 100%; } .col-sm-auto { -webkit-box-flex: 0; -webkit-flex: 0 0 auto; -ms-flex: 0 0 auto; flex: 0 0 auto; width: auto; } .col-sm-1 { -webkit-box-flex: 0; -webkit-flex: 0 0 8.333333%; -ms-flex: 0 0 8.333333%; flex: 0 0 8.333333%; max-width: 8.333333%; } .col-sm-2 { -webkit-box-flex: 0; -webkit-flex: 0 0 16.666667%; -ms-flex: 0 0 16.666667%; flex: 0 0 16.666667%; max-width: 16.666667%; } .col-sm-3 { -webkit-box-flex: 0; -webkit-flex: 0 0 25%; -ms-flex: 0 0 25%; flex: 0 0 25%; max-width: 25%; } .col-sm-4 { -webkit-box-flex: 0; -webkit-flex: 0 0 33.333333%; -ms-flex: 0 0 33.333333%; flex: 0 0 33.333333%; max-width: 33.333333%; } .col-sm-5 { -webkit-box-flex: 0; -webkit-flex: 0 0 41.666667%; -ms-flex: 0 0 41.666667%; flex: 0 0 41.666667%; max-width: 41.666667%; } .col-sm-6 { -webkit-box-flex: 0; -webkit-flex: 0 0 50%; -ms-flex: 0 0 50%; flex: 0 0 50%; max-width: 50%; } .col-sm-7 { -webkit-box-flex: 0; -webkit-flex: 0 0 58.333333%; -ms-flex: 0 0 58.333333%; flex: 0 0 58.333333%; max-width: 58.333333%; } .col-sm-8 { -webkit-box-flex: 0; -webkit-flex: 0 0 66.666667%; -ms-flex: 0 0 66.666667%; flex: 0 0 66.666667%; max-width: 66.666667%; } .col-sm-9 { -webkit-box-flex: 0; -webkit-flex: 0 0 75%; -ms-flex: 0 0 75%; flex: 0 0 75%; max-width: 75%; } .col-sm-10 { -webkit-box-flex: 0; -webkit-flex: 0 0 83.333333%; -ms-flex: 0 0 83.333333%; flex: 0 0 83.333333%; max-width: 83.333333%; } .col-sm-11 { -webkit-box-flex: 0; -webkit-flex: 0 0 91.666667%; -ms-flex: 0 0 91.666667%; flex: 0 0 91.666667%; max-width: 91.666667%; } .col-sm-12 { -webkit-box-flex: 0; -webkit-flex: 0 0 100%; -ms-flex: 0 0 100%; flex: 0 0 100%; max-width: 100%; } .pull-sm-0 { right: auto; } .pull-sm-1 { right: 8.333333%; } .pull-sm-2 { right: 16.666667%; } .pull-sm-3 { right: 25%; } .pull-sm-4 { right: 33.333333%; } .pull-sm-5 { right: 41.666667%; } .pull-sm-6 { right: 50%; } .pull-sm-7 { right: 58.333333%; } .pull-sm-8 { right: 66.666667%; } .pull-sm-9 { right: 75%; } .pull-sm-10 { right: 83.333333%; } .pull-sm-11 { right: 91.666667%; } .pull-sm-12 { right: 100%; } .push-sm-0 { left: auto; } .push-sm-1 { left: 8.333333%; } .push-sm-2 { left: 16.666667%; } .push-sm-3 { left: 25%; } .push-sm-4 { left: 33.333333%; } .push-sm-5 { left: 41.666667%; } .push-sm-6 { left: 50%; } .push-sm-7 { left: 58.333333%; } .push-sm-8 { left: 66.666667%; } .push-sm-9 { left: 75%; } .push-sm-10 { left: 83.333333%; } .push-sm-11 { left: 91.666667%; } .push-sm-12 { left: 100%; } .offset-sm-0 { margin-left: 0%; } .offset-sm-1 { margin-left: 8.333333%; } .offset-sm-2 { margin-left: 16.666667%; } .offset-sm-3 { margin-left: 25%; } .offset-sm-4 { margin-left: 33.333333%; } .offset-sm-5 { margin-left: 41.666667%; } .offset-sm-6 { margin-left: 50%; } .offset-sm-7 { margin-left: 58.333333%; } .offset-sm-8 { margin-left: 66.666667%; } .offset-sm-9 { margin-left: 75%; } .offset-sm-10 { margin-left: 83.333333%; } .offset-sm-11 { margin-left: 91.666667%; } } @media (min-width: 768px) { .col-md { -webkit-flex-basis: 0; -ms-flex-preferred-size: 0; flex-basis: 0; -webkit-box-flex: 1; -webkit-flex-grow: 1; -ms-flex-positive: 1; flex-grow: 1; max-width: 100%; } .col-md-auto { -webkit-box-flex: 0; -webkit-flex: 0 0 auto; -ms-flex: 0 0 auto; flex: 0 0 auto; width: auto; } .col-md-1 { -webkit-box-flex: 0; -webkit-flex: 0 0 8.333333%; -ms-flex: 0 0 8.333333%; flex: 0 0 8.333333%; max-width: 8.333333%; } .col-md-2 { -webkit-box-flex: 0; -webkit-flex: 0 0 16.666667%; -ms-flex: 0 0 16.666667%; flex: 0 0 16.666667%; max-width: 16.666667%; } .col-md-3 { -webkit-box-flex: 0; -webkit-flex: 0 0 25%; -ms-flex: 0 0 25%; flex: 0 0 25%; max-width: 25%; } .col-md-4 { -webkit-box-flex: 0; -webkit-flex: 0 0 33.333333%; -ms-flex: 0 0 33.333333%; flex: 0 0 33.333333%; max-width: 33.333333%; } .col-md-5 { -webkit-box-flex: 0; -webkit-flex: 0 0 41.666667%; -ms-flex: 0 0 41.666667%; flex: 0 0 41.666667%; max-width: 41.666667%; } .col-md-6 { -webkit-box-flex: 0; -webkit-flex: 0 0 50%; -ms-flex: 0 0 50%; flex: 0 0 50%; max-width: 50%; } .col-md-7 { -webkit-box-flex: 0; -webkit-flex: 0 0 58.333333%; -ms-flex: 0 0 58.333333%; flex: 0 0 58.333333%; max-width: 58.333333%; } .col-md-8 { -webkit-box-flex: 0; -webkit-flex: 0 0 66.666667%; -ms-flex: 0 0 66.666667%; flex: 0 0 66.666667%; max-width: 66.666667%; } .col-md-9 { -webkit-box-flex: 0; -webkit-flex: 0 0 75%; -ms-flex: 0 0 75%; flex: 0 0 75%; max-width: 75%; } .col-md-10 { -webkit-box-flex: 0; -webkit-flex: 0 0 83.333333%; -ms-flex: 0 0 83.333333%; flex: 0 0 83.333333%; max-width: 83.333333%; } .col-md-11 { -webkit-box-flex: 0; -webkit-flex: 0 0 91.666667%; -ms-flex: 0 0 91.666667%; flex: 0 0 91.666667%; max-width: 91.666667%; } .col-md-12 { -webkit-box-flex: 0; -webkit-flex: 0 0 100%; -ms-flex: 0 0 100%; flex: 0 0 100%; max-width: 100%; } .pull-md-0 { right: auto; } .pull-md-1 { right: 8.333333%; } .pull-md-2 { right: 16.666667%; } .pull-md-3 { right: 25%; } .pull-md-4 { right: 33.333333%; } .pull-md-5 { right: 41.666667%; } .pull-md-6 { right: 50%; } .pull-md-7 { right: 58.333333%; } .pull-md-8 { right: 66.666667%; } .pull-md-9 { right: 75%; } .pull-md-10 { right: 83.333333%; } .pull-md-11 { right: 91.666667%; } .pull-md-12 { right: 100%; } .push-md-0 { left: auto; } .push-md-1 { left: 8.333333%; } .push-md-2 { left: 16.666667%; } .push-md-3 { left: 25%; } .push-md-4 { left: 33.333333%; } .push-md-5 { left: 41.666667%; } .push-md-6 { left: 50%; } .push-md-7 { left: 58.333333%; } .push-md-8 { left: 66.666667%; } .push-md-9 { left: 75%; } .push-md-10 { left: 83.333333%; } .push-md-11 { left: 91.666667%; } .push-md-12 { left: 100%; } .offset-md-0 { margin-left: 0%; } .offset-md-1 { margin-left: 8.333333%; } .offset-md-2 { margin-left: 16.666667%; } .offset-md-3 { margin-left: 25%; } .offset-md-4 { margin-left: 33.333333%; } .offset-md-5 { margin-left: 41.666667%; } .offset-md-6 { margin-left: 50%; } .offset-md-7 { margin-left: 58.333333%; } .offset-md-8 { margin-left: 66.666667%; } .offset-md-9 { margin-left: 75%; } .offset-md-10 { margin-left: 83.333333%; } .offset-md-11 { margin-left: 91.666667%; } } @media (min-width: 992px) { .col-lg { -webkit-flex-basis: 0; -ms-flex-preferred-size: 0; flex-basis: 0; -webkit-box-flex: 1; -webkit-flex-grow: 1; -ms-flex-positive: 1; flex-grow: 1; max-width: 100%; } .col-lg-auto { -webkit-box-flex: 0; -webkit-flex: 0 0 auto; -ms-flex: 0 0 auto; flex: 0 0 auto; width: auto; } .col-lg-1 { -webkit-box-flex: 0; -webkit-flex: 0 0 8.333333%; -ms-flex: 0 0 8.333333%; flex: 0 0 8.333333%; max-width: 8.333333%; } .col-lg-2 { -webkit-box-flex: 0; -webkit-flex: 0 0 16.666667%; -ms-flex: 0 0 16.666667%; flex: 0 0 16.666667%; max-width: 16.666667%; } .col-lg-3 { -webkit-box-flex: 0; -webkit-flex: 0 0 25%; -ms-flex: 0 0 25%; flex: 0 0 25%; max-width: 25%; } .col-lg-4 { -webkit-box-flex: 0; -webkit-flex: 0 0 33.333333%; -ms-flex: 0 0 33.333333%; flex: 0 0 33.333333%; max-width: 33.333333%; } .col-lg-5 { -webkit-box-flex: 0; -webkit-flex: 0 0 41.666667%; -ms-flex: 0 0 41.666667%; flex: 0 0 41.666667%; max-width: 41.666667%; } .col-lg-6 { -webkit-box-flex: 0; -webkit-flex: 0 0 50%; -ms-flex: 0 0 50%; flex: 0 0 50%; max-width: 50%; } .col-lg-7 { -webkit-box-flex: 0; -webkit-flex: 0 0 58.333333%; -ms-flex: 0 0 58.333333%; flex: 0 0 58.333333%; max-width: 58.333333%; } .col-lg-8 { -webkit-box-flex: 0; -webkit-flex: 0 0 66.666667%; -ms-flex: 0 0 66.666667%; flex: 0 0 66.666667%; max-width: 66.666667%; } .col-lg-9 { -webkit-box-flex: 0; -webkit-flex: 0 0 75%; -ms-flex: 0 0 75%; flex: 0 0 75%; max-width: 75%; } .col-lg-10 { -webkit-box-flex: 0; -webkit-flex: 0 0 83.333333%; -ms-flex: 0 0 83.333333%; flex: 0 0 83.333333%; max-width: 83.333333%; } .col-lg-11 { -webkit-box-flex: 0; -webkit-flex: 0 0 91.666667%; -ms-flex: 0 0 91.666667%; flex: 0 0 91.666667%; max-width: 91.666667%; } .col-lg-12 { -webkit-box-flex: 0; -webkit-flex: 0 0 100%; -ms-flex: 0 0 100%; flex: 0 0 100%; max-width: 100%; } .pull-lg-0 { right: auto; } .pull-lg-1 { right: 8.333333%; } .pull-lg-2 { right: 16.666667%; } .pull-lg-3 { right: 25%; } .pull-lg-4 { right: 33.333333%; } .pull-lg-5 { right: 41.666667%; } .pull-lg-6 { right: 50%; } .pull-lg-7 { right: 58.333333%; } .pull-lg-8 { right: 66.666667%; } .pull-lg-9 { right: 75%; } .pull-lg-10 { right: 83.333333%; } .pull-lg-11 { right: 91.666667%; } .pull-lg-12 { right: 100%; } .push-lg-0 { left: auto; } .push-lg-1 { left: 8.333333%; } .push-lg-2 { left: 16.666667%; } .push-lg-3 { left: 25%; } .push-lg-4 { left: 33.333333%; } .push-lg-5 { left: 41.666667%; } .push-lg-6 { left: 50%; } .push-lg-7 { left: 58.333333%; } .push-lg-8 { left: 66.666667%; } .push-lg-9 { left: 75%; } .push-lg-10 { left: 83.333333%; } .push-lg-11 { left: 91.666667%; } .push-lg-12 { left: 100%; } .offset-lg-0 { margin-left: 0%; } .offset-lg-1 { margin-left: 8.333333%; } .offset-lg-2 { margin-left: 16.666667%; } .offset-lg-3 { margin-left: 25%; } .offset-lg-4 { margin-left: 33.333333%; } .offset-lg-5 { margin-left: 41.666667%; } .offset-lg-6 { margin-left: 50%; } .offset-lg-7 { margin-left: 58.333333%; } .offset-lg-8 { margin-left: 66.666667%; } .offset-lg-9 { margin-left: 75%; } .offset-lg-10 { margin-left: 83.333333%; } .offset-lg-11 { margin-left: 91.666667%; } } @media (min-width: 1200px) { .col-xl { -webkit-flex-basis: 0; -ms-flex-preferred-size: 0; flex-basis: 0; -webkit-box-flex: 1; -webkit-flex-grow: 1; -ms-flex-positive: 1; flex-grow: 1; max-width: 100%; } .col-xl-auto { -webkit-box-flex: 0; -webkit-flex: 0 0 auto; -ms-flex: 0 0 auto; flex: 0 0 auto; width: auto; } .col-xl-1 { -webkit-box-flex: 0; -webkit-flex: 0 0 8.333333%; -ms-flex: 0 0 8.333333%; flex: 0 0 8.333333%; max-width: 8.333333%; } .col-xl-2 { -webkit-box-flex: 0; -webkit-flex: 0 0 16.666667%; -ms-flex: 0 0 16.666667%; flex: 0 0 16.666667%; max-width: 16.666667%; } .col-xl-3 { -webkit-box-flex: 0; -webkit-flex: 0 0 25%; -ms-flex: 0 0 25%; flex: 0 0 25%; max-width: 25%; } .col-xl-4 { -webkit-box-flex: 0; -webkit-flex: 0 0 33.333333%; -ms-flex: 0 0 33.333333%; flex: 0 0 33.333333%; max-width: 33.333333%; } .col-xl-5 { -webkit-box-flex: 0; -webkit-flex: 0 0 41.666667%; -ms-flex: 0 0 41.666667%; flex: 0 0 41.666667%; max-width: 41.666667%; } .col-xl-6 { -webkit-box-flex: 0; -webkit-flex: 0 0 50%; -ms-flex: 0 0 50%; flex: 0 0 50%; max-width: 50%; } .col-xl-7 { -webkit-box-flex: 0; -webkit-flex: 0 0 58.333333%; -ms-flex: 0 0 58.333333%; flex: 0 0 58.333333%; max-width: 58.333333%; } .col-xl-8 { -webkit-box-flex: 0; -webkit-flex: 0 0 66.666667%; -ms-flex: 0 0 66.666667%; flex: 0 0 66.666667%; max-width: 66.666667%; } .col-xl-9 { -webkit-box-flex: 0; -webkit-flex: 0 0 75%; -ms-flex: 0 0 75%; flex: 0 0 75%; max-width: 75%; } .col-xl-10 { -webkit-box-flex: 0; -webkit-flex: 0 0 83.333333%; -ms-flex: 0 0 83.333333%; flex: 0 0 83.333333%; max-width: 83.333333%; } .col-xl-11 { -webkit-box-flex: 0; -webkit-flex: 0 0 91.666667%; -ms-flex: 0 0 91.666667%; flex: 0 0 91.666667%; max-width: 91.666667%; } .col-xl-12 { -webkit-box-flex: 0; -webkit-flex: 0 0 100%; -ms-flex: 0 0 100%; flex: 0 0 100%; max-width: 100%; } .pull-xl-0 { right: auto; } .pull-xl-1 { right: 8.333333%; } .pull-xl-2 { right: 16.666667%; } .pull-xl-3 { right: 25%; } .pull-xl-4 { right: 33.333333%; } .pull-xl-5 { right: 41.666667%; } .pull-xl-6 { right: 50%; } .pull-xl-7 { right: 58.333333%; } .pull-xl-8 { right: 66.666667%; } .pull-xl-9 { right: 75%; } .pull-xl-10 { right: 83.333333%; } .pull-xl-11 { right: 91.666667%; } .pull-xl-12 { right: 100%; } .push-xl-0 { left: auto; } .push-xl-1 { left: 8.333333%; } .push-xl-2 { left: 16.666667%; } .push-xl-3 { left: 25%; } .push-xl-4 { left: 33.333333%; } .push-xl-5 { left: 41.666667%; } .push-xl-6 { left: 50%; } .push-xl-7 { left: 58.333333%; } .push-xl-8 { left: 66.666667%; } .push-xl-9 { left: 75%; } .push-xl-10 { left: 83.333333%; } .push-xl-11 { left: 91.666667%; } .push-xl-12 { left: 100%; } .offset-xl-0 { margin-left: 0%; } .offset-xl-1 { margin-left: 8.333333%; } .offset-xl-2 { margin-left: 16.666667%; } .offset-xl-3 { margin-left: 25%; } .offset-xl-4 { margin-left: 33.333333%; } .offset-xl-5 { margin-left: 41.666667%; } .offset-xl-6 { margin-left: 50%; } .offset-xl-7 { margin-left: 58.333333%; } .offset-xl-8 { margin-left: 66.666667%; } .offset-xl-9 { margin-left: 75%; } .offset-xl-10 { margin-left: 83.333333%; } .offset-xl-11 { margin-left: 91.666667%; } } .table { width: 100%; max-width: 100%; margin-bottom: 1rem; } .table th, .table td { padding: 0.75rem; vertical-align: top; border-top: 1px solid #eceeef; } .table thead th { vertical-align: bottom; border-bottom: 2px solid #eceeef; } .table tbody + tbody { border-top: 2px solid #eceeef; } .table .table { background-color: #fff; } .table-sm th, .table-sm td { padding: 0.3rem; } .table-bordered { border: 1px solid #eceeef; } .table-bordered th, .table-bordered td { border: 1px solid #eceeef; } .table-bordered thead th, .table-bordered thead td { border-bottom-width: 2px; } .table-striped tbody tr:nth-of-type(odd) { background-color: rgba(0, 0, 0, 0.05); } .table-hover tbody tr:hover { background-color: rgba(0, 0, 0, 0.075); } .table-active, .table-active > th, .table-active > td { background-color: rgba(0, 0, 0, 0.075); } .table-hover .table-active:hover { background-color: rgba(0, 0, 0, 0.075); } .table-hover .table-active:hover > td, .table-hover .table-active:hover > th { background-color: rgba(0, 0, 0, 0.075); } .table-success, .table-success > th, .table-success > td { background-color: #dff0d8; } .table-hover .table-success:hover { background-color: #d0e9c6; } .table-hover .table-success:hover > td, .table-hover .table-success:hover > th { background-color: #d0e9c6; } .table-info, .table-info > th, .table-info > td { background-color: #d9edf7; } .table-hover .table-info:hover { background-color: #c4e3f3; } .table-hover .table-info:hover > td, .table-hover .table-info:hover > th { background-color: #c4e3f3; } .table-warning, .table-warning > th, .table-warning > td { background-color: #fcf8e3; } .table-hover .table-warning:hover { background-color: #faf2cc; } .table-hover .table-warning:hover > td, .table-hover .table-warning:hover > th { background-color: #faf2cc; } .table-danger, .table-danger > th, .table-danger > td { background-color: #f2dede; } .table-hover .table-danger:hover { background-color: #ebcccc; } .table-hover .table-danger:hover > td, .table-hover .table-danger:hover > th { background-color: #ebcccc; } .thead-inverse th { color: #fff; background-color: #292b2c; } .thead-default th { color: #464a4c; background-color: #eceeef; } .table-inverse { color: #fff; background-color: #292b2c; } .table-inverse th, .table-inverse td, .table-inverse thead th { border-color: #fff; } .table-inverse.table-bordered { border: 0; } .table-responsive { display: block; width: 100%; overflow-x: auto; -ms-overflow-style: -ms-autohiding-scrollbar; } .table-responsive.table-bordered { border: 0; } .form-control { display: block; width: 100%; padding: 0.5rem 0.75rem; font-size: 1rem; line-height: 1.25; color: #464a4c; background-color: #fff; background-image: none; -webkit-background-clip: padding-box; background-clip: padding-box; border: 1px solid rgba(0, 0, 0, 0.15); border-radius: 0.25rem; -webkit-transition: border-color ease-in-out 0.15s, -webkit-box-shadow ease-in-out 0.15s; transition: border-color ease-in-out 0.15s, -webkit-box-shadow ease-in-out 0.15s; -o-transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s; transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s; transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s, -webkit-box-shadow ease-in-out 0.15s; } .form-control::-ms-expand { background-color: transparent; border: 0; } .form-control:focus { color: #464a4c; background-color: #fff; border-color: #5cb3fd; outline: none; } .form-control::-webkit-input-placeholder { color: #636c72; opacity: 1; } .form-control::-moz-placeholder { color: #636c72; opacity: 1; } .form-control:-ms-input-placeholder { color: #636c72; opacity: 1; } .form-control::placeholder { color: #636c72; opacity: 1; } .form-control:disabled, .form-control[readonly] { background-color: #eceeef; opacity: 1; } .form-control:disabled { cursor: not-allowed; } select.form-control:not([size]):not([multiple]) { height: calc(2.25rem + 2px); } select.form-control:focus::-ms-value { color: #464a4c; background-color: #fff; } .form-control-file, .form-control-range { display: block; } .col-form-label { padding-top: calc(0.5rem - 1px * 2); padding-bottom: calc(0.5rem - 1px * 2); margin-bottom: 0; } .col-form-label-lg { padding-top: calc(0.75rem - 1px * 2); padding-bottom: calc(0.75rem - 1px * 2); font-size: 1.25rem; } .col-form-label-sm { padding-top: calc(0.25rem - 1px * 2); padding-bottom: calc(0.25rem - 1px * 2); font-size: 0.875rem; } .col-form-legend { padding-top: 0.5rem; padding-bottom: 0.5rem; margin-bottom: 0; font-size: 1rem; } .form-control-static { padding-top: 0.5rem; padding-bottom: 0.5rem; margin-bottom: 0; line-height: 1.25; border: solid transparent; border-width: 1px 0; } .form-control-static.form-control-sm, .input-group-sm > .form-control-static.form-control, .input-group-sm > .form-control-static.input-group-addon, .input-group-sm > .input-group-btn > .form-control-static.btn, .form-control-static.form-control-lg, .input-group-lg > .form-control-static.form-control, .input-group-lg > .form-control-static.input-group-addon, .input-group-lg > .input-group-btn > .form-control-static.btn { padding-right: 0; padding-left: 0; } .form-control-sm, .input-group-sm > .form-control, .input-group-sm > .input-group-addon, .input-group-sm > .input-group-btn > .btn { padding: 0.25rem 0.5rem; font-size: 0.875rem; border-radius: 0.2rem; } select.form-control-sm:not([size]):not([multiple]), .input-group-sm > select.form-control:not([size]):not([multiple]), .input-group-sm > select.input-group-addon:not([size]):not([multiple]), .input-group-sm > .input-group-btn > select.btn:not([size]):not([multiple]) { height: 1.8125rem; } .form-control-lg, .input-group-lg > .form-control, .input-group-lg > .input-group-addon, .input-group-lg > .input-group-btn > .btn { padding: 0.75rem 1.5rem; font-size: 1.25rem; border-radius: 0.3rem; } select.form-control-lg:not([size]):not([multiple]), .input-group-lg > select.form-control:not([size]):not([multiple]), .input-group-lg > select.input-group-addon:not([size]):not([multiple]), .input-group-lg > .input-group-btn > select.btn:not([size]):not([multiple]) { height: 3.166667rem; } .form-group { margin-bottom: 1rem; } .form-text { display: block; margin-top: 0.25rem; } .form-check { position: relative; display: block; margin-bottom: 0.5rem; } .form-check.disabled .form-check-label { color: #636c72; cursor: not-allowed; } .form-check-label { padding-left: 1.25rem; margin-bottom: 0; cursor: pointer; } .form-check-input { position: absolute; margin-top: 0.25rem; margin-left: -1.25rem; } .form-check-input:only-child { position: static; } .form-check-inline { display: inline-block; } .form-check-inline .form-check-label { vertical-align: middle; } .form-check-inline + .form-check-inline { margin-left: 0.75rem; } .form-control-feedback { margin-top: 0.25rem; } .form-control-success, .form-control-warning, .form-control-danger { padding-right: 2.25rem; background-repeat: no-repeat; background-position: center right 0.5625rem; -webkit-background-size: 1.125rem 1.125rem; background-size: 1.125rem 1.125rem; } .has-success .form-control-feedback, .has-success .form-control-label, .has-success .col-form-label, .has-success .form-check-label, .has-success .custom-control { color: #5cb85c; } .has-success .form-control { border-color: #5cb85c; } .has-success .input-group-addon { color: #5cb85c; border-color: #5cb85c; background-color: #eaf6ea; } .has-success .form-control-success { background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 8'%3E%3Cpath fill='%235cb85c' d='M2.3 6.73L.6 4.53c-.4-1.04.46-1.4 1.1-.8l1.1 1.4 3.4-3.8c.6-.63 1.6-.27 1.2.7l-4 4.6c-.43.5-.8.4-1.1.1z'/%3E%3C/svg%3E"); } .has-warning .form-control-feedback, .has-warning .form-control-label, .has-warning .col-form-label, .has-warning .form-check-label, .has-warning .custom-control { color: #f0ad4e; } .has-warning .form-control { border-color: #f0ad4e; } .has-warning .input-group-addon { color: #f0ad4e; border-color: #f0ad4e; background-color: white; } .has-warning .form-control-warning { background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 8'%3E%3Cpath fill='%23f0ad4e' d='M4.4 5.324h-.8v-2.46h.8zm0 1.42h-.8V5.89h.8zM3.76.63L.04 7.075c-.115.2.016.425.26.426h7.397c.242 0 .372-.226.258-.426C6.726 4.924 5.47 2.79 4.253.63c-.113-.174-.39-.174-.494 0z'/%3E%3C/svg%3E"); } .has-danger .form-control-feedback, .has-danger .form-control-label, .has-danger .col-form-label, .has-danger .form-check-label, .has-danger .custom-control { color: #d9534f; } .has-danger .form-control { border-color: #d9534f; } .has-danger .input-group-addon { color: #d9534f; border-color: #d9534f; background-color: #fdf7f7; } .has-danger .form-control-danger { background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='%23d9534f' viewBox='-2 -2 7 7'%3E%3Cpath stroke='%23d9534f' d='M0 0l3 3m0-3L0 3'/%3E%3Ccircle r='.5'/%3E%3Ccircle cx='3' r='.5'/%3E%3Ccircle cy='3' r='.5'/%3E%3Ccircle cx='3' cy='3' r='.5'/%3E%3C/svg%3E"); } .form-inline { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-flex-flow: row wrap; -ms-flex-flow: row wrap; flex-flow: row wrap; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; } .form-inline .form-check { width: 100%; } @media (min-width: 576px) { .form-inline label { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; -webkit-box-pack: center; -webkit-justify-content: center; -ms-flex-pack: center; justify-content: center; margin-bottom: 0; } .form-inline .form-group { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-flex: 0; -webkit-flex: 0 0 auto; -ms-flex: 0 0 auto; flex: 0 0 auto; -webkit-flex-flow: row wrap; -ms-flex-flow: row wrap; flex-flow: row wrap; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; margin-bottom: 0; } .form-inline .form-control { display: inline-block; width: auto; vertical-align: middle; } .form-inline .form-control-static { display: inline-block; } .form-inline .input-group { width: auto; } .form-inline .form-control-label { margin-bottom: 0; vertical-align: middle; } .form-inline .form-check { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; -webkit-box-pack: center; -webkit-justify-content: center; -ms-flex-pack: center; justify-content: center; width: auto; margin-top: 0; margin-bottom: 0; } .form-inline .form-check-label { padding-left: 0; } .form-inline .form-check-input { position: relative; margin-top: 0; margin-right: 0.25rem; margin-left: 0; } .form-inline .custom-control { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; -webkit-box-pack: center; -webkit-justify-content: center; -ms-flex-pack: center; justify-content: center; padding-left: 0; } .form-inline .custom-control-indicator { position: static; display: inline-block; margin-right: 0.25rem; vertical-align: text-bottom; } .form-inline .has-feedback .form-control-feedback { top: 0; } } .btn { display: inline-block; font-weight: normal; line-height: 1.25; text-align: center; white-space: nowrap; vertical-align: middle; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; border: 1px solid transparent; padding: 0.5rem 1rem; font-size: 1rem; border-radius: 0.25rem; -webkit-transition: all 0.2s ease-in-out; -o-transition: all 0.2s ease-in-out; transition: all 0.2s ease-in-out; } .btn:focus, .btn:hover { text-decoration: none; } .btn:focus, .btn.focus { outline: 0; -webkit-box-shadow: 0 0 0 2px rgba(2, 117, 216, 0.25); box-shadow: 0 0 0 2px rgba(2, 117, 216, 0.25); } .btn.disabled, .btn:disabled { cursor: not-allowed; opacity: .65; } .btn:active, .btn.active { background-image: none; } a.btn.disabled, fieldset[disabled] a.btn { pointer-events: none; } .btn-primary { color: #fff; background-color: #0275d8; border-color: #0275d8; } .btn-primary:hover { color: #fff; background-color: #025aa5; border-color: #01549b; } .btn-primary:focus, .btn-primary.focus { -webkit-box-shadow: 0 0 0 2px rgba(2, 117, 216, 0.5); box-shadow: 0 0 0 2px rgba(2, 117, 216, 0.5); } .btn-primary.disabled, .btn-primary:disabled { background-color: #0275d8; border-color: #0275d8; } .btn-primary:active, .btn-primary.active, .show > .btn-primary.dropdown-toggle { color: #fff; background-color: #025aa5; background-image: none; border-color: #01549b; } .btn-secondary { color: #292b2c; background-color: #fff; border-color: #ccc; } .btn-secondary:hover { color: #292b2c; background-color: #e6e6e6; border-color: #adadad; } .btn-secondary:focus, .btn-secondary.focus { -webkit-box-shadow: 0 0 0 2px rgba(204, 204, 204, 0.5); box-shadow: 0 0 0 2px rgba(204, 204, 204, 0.5); } .btn-secondary.disabled, .btn-secondary:disabled { background-color: #fff; border-color: #ccc; } .btn-secondary:active, .btn-secondary.active, .show > .btn-secondary.dropdown-toggle { color: #292b2c; background-color: #e6e6e6; background-image: none; border-color: #adadad; } .btn-info { color: #fff; background-color: #5bc0de; border-color: #5bc0de; } .btn-info:hover { color: #fff; background-color: #31b0d5; border-color: #2aabd2; } .btn-info:focus, .btn-info.focus { -webkit-box-shadow: 0 0 0 2px rgba(91, 192, 222, 0.5); box-shadow: 0 0 0 2px rgba(91, 192, 222, 0.5); } .btn-info.disabled, .btn-info:disabled { background-color: #5bc0de; border-color: #5bc0de; } .btn-info:active, .btn-info.active, .show > .btn-info.dropdown-toggle { color: #fff; background-color: #31b0d5; background-image: none; border-color: #2aabd2; } .btn-success { color: #fff; background-color: #5cb85c; border-color: #5cb85c; } .btn-success:hover { color: #fff; background-color: #449d44; border-color: #419641; } .btn-success:focus, .btn-success.focus { -webkit-box-shadow: 0 0 0 2px rgba(92, 184, 92, 0.5); box-shadow: 0 0 0 2px rgba(92, 184, 92, 0.5); } .btn-success.disabled, .btn-success:disabled { background-color: #5cb85c; border-color: #5cb85c; } .btn-success:active, .btn-success.active, .show > .btn-success.dropdown-toggle { color: #fff; background-color: #449d44; background-image: none; border-color: #419641; } .btn-warning { color: #fff; background-color: #f0ad4e; border-color: #f0ad4e; } .btn-warning:hover { color: #fff; background-color: #ec971f; border-color: #eb9316; } .btn-warning:focus, .btn-warning.focus { -webkit-box-shadow: 0 0 0 2px rgba(240, 173, 78, 0.5); box-shadow: 0 0 0 2px rgba(240, 173, 78, 0.5); } .btn-warning.disabled, .btn-warning:disabled { background-color: #f0ad4e; border-color: #f0ad4e; } .btn-warning:active, .btn-warning.active, .show > .btn-warning.dropdown-toggle { color: #fff; background-color: #ec971f; background-image: none; border-color: #eb9316; } .btn-danger { color: #fff; background-color: #d9534f; border-color: #d9534f; } .btn-danger:hover { color: #fff; background-color: #c9302c; border-color: #c12e2a; } .btn-danger:focus, .btn-danger.focus { -webkit-box-shadow: 0 0 0 2px rgba(217, 83, 79, 0.5); box-shadow: 0 0 0 2px rgba(217, 83, 79, 0.5); } .btn-danger.disabled, .btn-danger:disabled { background-color: #d9534f; border-color: #d9534f; } .btn-danger:active, .btn-danger.active, .show > .btn-danger.dropdown-toggle { color: #fff; background-color: #c9302c; background-image: none; border-color: #c12e2a; } .btn-outline-primary { color: #0275d8; background-image: none; background-color: transparent; border-color: #0275d8; } .btn-outline-primary:hover { color: #fff; background-color: #0275d8; border-color: #0275d8; } .btn-outline-primary:focus, .btn-outline-primary.focus { -webkit-box-shadow: 0 0 0 2px rgba(2, 117, 216, 0.5); box-shadow: 0 0 0 2px rgba(2, 117, 216, 0.5); } .btn-outline-primary.disabled, .btn-outline-primary:disabled { color: #0275d8; background-color: transparent; } .btn-outline-primary:active, .btn-outline-primary.active, .show > .btn-outline-primary.dropdown-toggle { color: #fff; background-color: #0275d8; border-color: #0275d8; } .btn-outline-secondary { color: #ccc; background-image: none; background-color: transparent; border-color: #ccc; } .btn-outline-secondary:hover { color: #fff; background-color: #ccc; border-color: #ccc; } .btn-outline-secondary:focus, .btn-outline-secondary.focus { -webkit-box-shadow: 0 0 0 2px rgba(204, 204, 204, 0.5); box-shadow: 0 0 0 2px rgba(204, 204, 204, 0.5); } .btn-outline-secondary.disabled, .btn-outline-secondary:disabled { color: #ccc; background-color: transparent; } .btn-outline-secondary:active, .btn-outline-secondary.active, .show > .btn-outline-secondary.dropdown-toggle { color: #fff; background-color: #ccc; border-color: #ccc; } .btn-outline-info { color: #5bc0de; background-image: none; background-color: transparent; border-color: #5bc0de; } .btn-outline-info:hover { color: #fff; background-color: #5bc0de; border-color: #5bc0de; } .btn-outline-info:focus, .btn-outline-info.focus { -webkit-box-shadow: 0 0 0 2px rgba(91, 192, 222, 0.5); box-shadow: 0 0 0 2px rgba(91, 192, 222, 0.5); } .btn-outline-info.disabled, .btn-outline-info:disabled { color: #5bc0de; background-color: transparent; } .btn-outline-info:active, .btn-outline-info.active, .show > .btn-outline-info.dropdown-toggle { color: #fff; background-color: #5bc0de; border-color: #5bc0de; } .btn-outline-success { color: #5cb85c; background-image: none; background-color: transparent; border-color: #5cb85c; } .btn-outline-success:hover { color: #fff; background-color: #5cb85c; border-color: #5cb85c; } .btn-outline-success:focus, .btn-outline-success.focus { -webkit-box-shadow: 0 0 0 2px rgba(92, 184, 92, 0.5); box-shadow: 0 0 0 2px rgba(92, 184, 92, 0.5); } .btn-outline-success.disabled, .btn-outline-success:disabled { color: #5cb85c; background-color: transparent; } .btn-outline-success:active, .btn-outline-success.active, .show > .btn-outline-success.dropdown-toggle { color: #fff; background-color: #5cb85c; border-color: #5cb85c; } .btn-outline-warning { color: #f0ad4e; background-image: none; background-color: transparent; border-color: #f0ad4e; } .btn-outline-warning:hover { color: #fff; background-color: #f0ad4e; border-color: #f0ad4e; } .btn-outline-warning:focus, .btn-outline-warning.focus { -webkit-box-shadow: 0 0 0 2px rgba(240, 173, 78, 0.5); box-shadow: 0 0 0 2px rgba(240, 173, 78, 0.5); } .btn-outline-warning.disabled, .btn-outline-warning:disabled { color: #f0ad4e; background-color: transparent; } .btn-outline-warning:active, .btn-outline-warning.active, .show > .btn-outline-warning.dropdown-toggle { color: #fff; background-color: #f0ad4e; border-color: #f0ad4e; } .btn-outline-danger { color: #d9534f; background-image: none; background-color: transparent; border-color: #d9534f; } .btn-outline-danger:hover { color: #fff; background-color: #d9534f; border-color: #d9534f; } .btn-outline-danger:focus, .btn-outline-danger.focus { -webkit-box-shadow: 0 0 0 2px rgba(217, 83, 79, 0.5); box-shadow: 0 0 0 2px rgba(217, 83, 79, 0.5); } .btn-outline-danger.disabled, .btn-outline-danger:disabled { color: #d9534f; background-color: transparent; } .btn-outline-danger:active, .btn-outline-danger.active, .show > .btn-outline-danger.dropdown-toggle { color: #fff; background-color: #d9534f; border-color: #d9534f; } .btn-link { font-weight: normal; color: #0275d8; border-radius: 0; } .btn-link, .btn-link:active, .btn-link.active, .btn-link:disabled { background-color: transparent; } .btn-link, .btn-link:focus, .btn-link:active { border-color: transparent; } .btn-link:hover { border-color: transparent; } .btn-link:focus, .btn-link:hover { color: #014c8c; text-decoration: underline; background-color: transparent; } .btn-link:disabled { color: #636c72; } .btn-link:disabled:focus, .btn-link:disabled:hover { text-decoration: none; } .btn-lg, .btn-group-lg > .btn { padding: 0.75rem 1.5rem; font-size: 1.25rem; border-radius: 0.3rem; } .btn-sm, .btn-group-sm > .btn { padding: 0.25rem 0.5rem; font-size: 0.875rem; border-radius: 0.2rem; } .btn-block { display: block; width: 100%; } .btn-block + .btn-block { margin-top: 0.5rem; } input[type="submit"].btn-block, input[type="reset"].btn-block, input[type="button"].btn-block { width: 100%; } .fade { opacity: 0; -webkit-transition: opacity 0.15s linear; -o-transition: opacity 0.15s linear; transition: opacity 0.15s linear; } .fade.show { opacity: 1; } .collapse { display: none; } .collapse.show { display: block; } tr.collapse.show { display: table-row; } tbody.collapse.show { display: table-row-group; } .collapsing { position: relative; height: 0; overflow: hidden; -webkit-transition: height 0.35s ease; -o-transition: height 0.35s ease; transition: height 0.35s ease; } .dropup, .dropdown { position: relative; } .dropdown-toggle::after { display: inline-block; width: 0; height: 0; margin-left: 0.3em; vertical-align: middle; content: ""; border-top: 0.3em solid; border-right: 0.3em solid transparent; border-left: 0.3em solid transparent; } .dropdown-toggle:focus { outline: 0; } .dropup .dropdown-toggle::after { border-top: 0; border-bottom: 0.3em solid; } .dropdown-menu { position: absolute; top: 100%; left: 0; z-index: 1000; display: none; float: left; min-width: 10rem; padding: 0.5rem 0; margin: 0.125rem 0 0; font-size: 1rem; color: #292b2c; text-align: left; list-style: none; background-color: #fff; -webkit-background-clip: padding-box; background-clip: padding-box; border: 1px solid rgba(0, 0, 0, 0.15); border-radius: 0.25rem; } .dropdown-divider { height: 1px; margin: 0.5rem 0; overflow: hidden; background-color: #eceeef; } .dropdown-item { display: block; width: 100%; padding: 3px 1.5rem; clear: both; font-weight: normal; color: #292b2c; text-align: inherit; white-space: nowrap; background: none; border: 0; } .dropdown-item:focus, .dropdown-item:hover { color: #1d1e1f; text-decoration: none; background-color: #f7f7f9; } .dropdown-item.active, .dropdown-item:active { color: #fff; text-decoration: none; background-color: #0275d8; } .dropdown-item.disabled, .dropdown-item:disabled { color: #636c72; cursor: not-allowed; background-color: transparent; } .show > .dropdown-menu { display: block; } .show > a { outline: 0; } .dropdown-menu-right { right: 0; left: auto; } .dropdown-menu-left { right: auto; left: 0; } .dropdown-header { display: block; padding: 0.5rem 1.5rem; margin-bottom: 0; font-size: 0.875rem; color: #636c72; white-space: nowrap; } .dropdown-backdrop { position: fixed; top: 0; right: 0; bottom: 0; left: 0; z-index: 990; } .dropup .dropdown-menu { top: auto; bottom: 100%; margin-bottom: 0.125rem; } .btn-group, .btn-group-vertical { position: relative; display: -webkit-inline-box; display: -webkit-inline-flex; display: -ms-inline-flexbox; display: inline-flex; vertical-align: middle; } .btn-group > .btn, .btn-group-vertical > .btn { position: relative; -webkit-box-flex: 0; -webkit-flex: 0 1 auto; -ms-flex: 0 1 auto; flex: 0 1 auto; } .btn-group > .btn:hover, .btn-group-vertical > .btn:hover { z-index: 2; } .btn-group > .btn:focus, .btn-group > .btn:active, .btn-group > .btn.active, .btn-group-vertical > .btn:focus, .btn-group-vertical > .btn:active, .btn-group-vertical > .btn.active { z-index: 2; } .btn-group .btn + .btn, .btn-group .btn + .btn-group, .btn-group .btn-group + .btn, .btn-group .btn-group + .btn-group, .btn-group-vertical .btn + .btn, .btn-group-vertical .btn + .btn-group, .btn-group-vertical .btn-group + .btn, .btn-group-vertical .btn-group + .btn-group { margin-left: -1px; } .btn-toolbar { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-pack: start; -webkit-justify-content: flex-start; -ms-flex-pack: start; justify-content: flex-start; } .btn-toolbar .input-group { width: auto; } .btn-group > .btn:not(:first-child):not(:last-child):not(.dropdown-toggle) { border-radius: 0; } .btn-group > .btn:first-child { margin-left: 0; } .btn-group > .btn:first-child:not(:last-child):not(.dropdown-toggle) { border-bottom-right-radius: 0; border-top-right-radius: 0; } .btn-group > .btn:last-child:not(:first-child), .btn-group > .dropdown-toggle:not(:first-child) { border-bottom-left-radius: 0; border-top-left-radius: 0; } .btn-group > .btn-group { float: left; } .btn-group > .btn-group:not(:first-child):not(:last-child) > .btn { border-radius: 0; } .btn-group > .btn-group:first-child:not(:last-child) > .btn:last-child, .btn-group > .btn-group:first-child:not(:last-child) > .dropdown-toggle { border-bottom-right-radius: 0; border-top-right-radius: 0; } .btn-group > .btn-group:last-child:not(:first-child) > .btn:first-child { border-bottom-left-radius: 0; border-top-left-radius: 0; } .btn-group .dropdown-toggle:active, .btn-group.open .dropdown-toggle { outline: 0; } .btn + .dropdown-toggle-split { padding-right: 0.75rem; padding-left: 0.75rem; } .btn + .dropdown-toggle-split::after { margin-left: 0; } .btn-sm + .dropdown-toggle-split, .btn-group-sm > .btn + .dropdown-toggle-split { padding-right: 0.375rem; padding-left: 0.375rem; } .btn-lg + .dropdown-toggle-split, .btn-group-lg > .btn + .dropdown-toggle-split { padding-right: 1.125rem; padding-left: 1.125rem; } .btn-group-vertical { display: -webkit-inline-box; display: -webkit-inline-flex; display: -ms-inline-flexbox; display: inline-flex; -webkit-box-orient: vertical; -webkit-box-direction: normal; -webkit-flex-direction: column; -ms-flex-direction: column; flex-direction: column; -webkit-box-align: start; -webkit-align-items: flex-start; -ms-flex-align: start; align-items: flex-start; -webkit-box-pack: center; -webkit-justify-content: center; -ms-flex-pack: center; justify-content: center; } .btn-group-vertical .btn, .btn-group-vertical .btn-group { width: 100%; } .btn-group-vertical > .btn + .btn, .btn-group-vertical > .btn + .btn-group, .btn-group-vertical > .btn-group + .btn, .btn-group-vertical > .btn-group + .btn-group { margin-top: -1px; margin-left: 0; } .btn-group-vertical > .btn:not(:first-child):not(:last-child) { border-radius: 0; } .btn-group-vertical > .btn:first-child:not(:last-child) { border-bottom-right-radius: 0; border-bottom-left-radius: 0; } .btn-group-vertical > .btn:last-child:not(:first-child) { border-top-right-radius: 0; border-top-left-radius: 0; } .btn-group-vertical > .btn-group:not(:first-child):not(:last-child) > .btn { border-radius: 0; } .btn-group-vertical > .btn-group:first-child:not(:last-child) > .btn:last-child, .btn-group-vertical > .btn-group:first-child:not(:last-child) > .dropdown-toggle { border-bottom-right-radius: 0; border-bottom-left-radius: 0; } .btn-group-vertical > .btn-group:last-child:not(:first-child) > .btn:first-child { border-top-right-radius: 0; border-top-left-radius: 0; } [data-toggle="buttons"] > .btn input[type="radio"], [data-toggle="buttons"] > .btn input[type="checkbox"], [data-toggle="buttons"] > .btn-group > .btn input[type="radio"], [data-toggle="buttons"] > .btn-group > .btn input[type="checkbox"] { position: absolute; clip: rect(0, 0, 0, 0); pointer-events: none; } .input-group { position: relative; display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; width: 100%; } .input-group .form-control { position: relative; z-index: 2; -webkit-box-flex: 1; -webkit-flex: 1 1 auto; -ms-flex: 1 1 auto; flex: 1 1 auto; width: 1%; margin-bottom: 0; } .input-group .form-control:focus, .input-group .form-control:active, .input-group .form-control:hover { z-index: 3; } .input-group-addon, .input-group-btn, .input-group .form-control { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-orient: vertical; -webkit-box-direction: normal; -webkit-flex-direction: column; -ms-flex-direction: column; flex-direction: column; -webkit-box-pack: center; -webkit-justify-content: center; -ms-flex-pack: center; justify-content: center; } .input-group-addon:not(:first-child):not(:last-child), .input-group-btn:not(:first-child):not(:last-child), .input-group .form-control:not(:first-child):not(:last-child) { border-radius: 0; } .input-group-addon, .input-group-btn { white-space: nowrap; vertical-align: middle; } .input-group-addon { padding: 0.5rem 0.75rem; margin-bottom: 0; font-size: 1rem; font-weight: normal; line-height: 1.25; color: #464a4c; text-align: center; background-color: #eceeef; border: 1px solid rgba(0, 0, 0, 0.15); border-radius: 0.25rem; } .input-group-addon.form-control-sm, .input-group-sm > .input-group-addon, .input-group-sm > .input-group-btn > .input-group-addon.btn { padding: 0.25rem 0.5rem; font-size: 0.875rem; border-radius: 0.2rem; } .input-group-addon.form-control-lg, .input-group-lg > .input-group-addon, .input-group-lg > .input-group-btn > .input-group-addon.btn { padding: 0.75rem 1.5rem; font-size: 1.25rem; border-radius: 0.3rem; } .input-group-addon input[type="radio"], .input-group-addon input[type="checkbox"] { margin-top: 0; } .input-group .form-control:not(:last-child), .input-group-addon:not(:last-child), .input-group-btn:not(:last-child) > .btn, .input-group-btn:not(:last-child) > .btn-group > .btn, .input-group-btn:not(:last-child) > .dropdown-toggle, .input-group-btn:not(:first-child) > .btn:not(:last-child):not(.dropdown-toggle), .input-group-btn:not(:first-child) > .btn-group:not(:last-child) > .btn { border-bottom-right-radius: 0; border-top-right-radius: 0; } .input-group-addon:not(:last-child) { border-right: 0; } .input-group .form-control:not(:first-child), .input-group-addon:not(:first-child), .input-group-btn:not(:first-child) > .btn, .input-group-btn:not(:first-child) > .btn-group > .btn, .input-group-btn:not(:first-child) > .dropdown-toggle, .input-group-btn:not(:last-child) > .btn:not(:first-child), .input-group-btn:not(:last-child) > .btn-group:not(:first-child) > .btn { border-bottom-left-radius: 0; border-top-left-radius: 0; } .form-control + .input-group-addon:not(:first-child) { border-left: 0; } .input-group-btn { position: relative; font-size: 0; white-space: nowrap; } .input-group-btn > .btn { position: relative; -webkit-box-flex: 1; -webkit-flex: 1 1 0%; -ms-flex: 1 1 0%; flex: 1 1 0%; } .input-group-btn > .btn + .btn { margin-left: -1px; } .input-group-btn > .btn:focus, .input-group-btn > .btn:active, .input-group-btn > .btn:hover { z-index: 3; } .input-group-btn:not(:last-child) > .btn, .input-group-btn:not(:last-child) > .btn-group { margin-right: -1px; } .input-group-btn:not(:first-child) > .btn, .input-group-btn:not(:first-child) > .btn-group { z-index: 2; margin-left: -1px; } .input-group-btn:not(:first-child) > .btn:focus, .input-group-btn:not(:first-child) > .btn:active, .input-group-btn:not(:first-child) > .btn:hover, .input-group-btn:not(:first-child) > .btn-group:focus, .input-group-btn:not(:first-child) > .btn-group:active, .input-group-btn:not(:first-child) > .btn-group:hover { z-index: 3; } .custom-control { position: relative; display: -webkit-inline-box; display: -webkit-inline-flex; display: -ms-inline-flexbox; display: inline-flex; min-height: 1.5rem; padding-left: 1.5rem; margin-right: 1rem; cursor: pointer; } .custom-control-input { position: absolute; z-index: -1; opacity: 0; } .custom-control-input:checked ~ .custom-control-indicator { color: #fff; background-color: #0275d8; } .custom-control-input:focus ~ .custom-control-indicator { -webkit-box-shadow: 0 0 0 1px #fff, 0 0 0 3px #0275d8; box-shadow: 0 0 0 1px #fff, 0 0 0 3px #0275d8; } .custom-control-input:active ~ .custom-control-indicator { color: #fff; background-color: #8fcafe; } .custom-control-input:disabled ~ .custom-control-indicator { cursor: not-allowed; background-color: #eceeef; } .custom-control-input:disabled ~ .custom-control-description { color: #636c72; cursor: not-allowed; } .custom-control-indicator { position: absolute; top: 0.25rem; left: 0; display: block; width: 1rem; height: 1rem; pointer-events: none; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; background-color: #ddd; background-repeat: no-repeat; background-position: center center; -webkit-background-size: 50% 50%; background-size: 50% 50%; } .custom-checkbox .custom-control-indicator { border-radius: 0.25rem; } .custom-checkbox .custom-control-input:checked ~ .custom-control-indicator { background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 8'%3E%3Cpath fill='%23fff' d='M6.564.75l-3.59 3.612-1.538-1.55L0 4.26 2.974 7.25 8 2.193z'/%3E%3C/svg%3E"); } .custom-checkbox .custom-control-input:indeterminate ~ .custom-control-indicator { background-color: #0275d8; background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 4 4'%3E%3Cpath stroke='%23fff' d='M0 2h4'/%3E%3C/svg%3E"); } .custom-radio .custom-control-indicator { border-radius: 50%; } .custom-radio .custom-control-input:checked ~ .custom-control-indicator { background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='-4 -4 8 8'%3E%3Ccircle r='3' fill='%23fff'/%3E%3C/svg%3E"); } .custom-controls-stacked { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-orient: vertical; -webkit-box-direction: normal; -webkit-flex-direction: column; -ms-flex-direction: column; flex-direction: column; } .custom-controls-stacked .custom-control { margin-bottom: 0.25rem; } .custom-controls-stacked .custom-control + .custom-control { margin-left: 0; } .custom-select { display: inline-block; max-width: 100%; height: calc(2.25rem + 2px); padding: 0.375rem 1.75rem 0.375rem 0.75rem; line-height: 1.25; color: #464a4c; vertical-align: middle; background: #fff url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 4 5'%3E%3Cpath fill='%23333' d='M2 0L0 2h4zm0 5L0 3h4z'/%3E%3C/svg%3E") no-repeat right 0.75rem center; -webkit-background-size: 8px 10px; background-size: 8px 10px; border: 1px solid rgba(0, 0, 0, 0.15); border-radius: 0.25rem; -moz-appearance: none; -webkit-appearance: none; } .custom-select:focus { border-color: #5cb3fd; outline: none; } .custom-select:focus::-ms-value { color: #464a4c; background-color: #fff; } .custom-select:disabled { color: #636c72; cursor: not-allowed; background-color: #eceeef; } .custom-select::-ms-expand { opacity: 0; } .custom-select-sm { padding-top: 0.375rem; padding-bottom: 0.375rem; font-size: 75%; } .custom-file { position: relative; display: inline-block; max-width: 100%; height: 2.5rem; margin-bottom: 0; cursor: pointer; } .custom-file-input { min-width: 14rem; max-width: 100%; height: 2.5rem; margin: 0; filter: alpha(opacity=0); opacity: 0; } .custom-file-control { position: absolute; top: 0; right: 0; left: 0; z-index: 5; height: 2.5rem; padding: 0.5rem 1rem; line-height: 1.5; color: #464a4c; pointer-events: none; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; background-color: #fff; border: 1px solid rgba(0, 0, 0, 0.15); border-radius: 0.25rem; } .custom-file-control:lang(en)::after { content: "Choose file..."; } .custom-file-control::before { position: absolute; top: -1px; right: -1px; bottom: -1px; z-index: 6; display: block; height: 2.5rem; padding: 0.5rem 1rem; line-height: 1.5; color: #464a4c; background-color: #eceeef; border: 1px solid rgba(0, 0, 0, 0.15); border-radius: 0 0.25rem 0.25rem 0; } .custom-file-control:lang(en)::before { content: "Browse"; } .nav { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; padding-left: 0; margin-bottom: 0; list-style: none; } .nav-link { display: block; padding: 0.5em 1em; } .nav-link:focus, .nav-link:hover { text-decoration: none; } .nav-link.disabled { color: #636c72; cursor: not-allowed; } .nav-tabs { border-bottom: 1px solid #ddd; } .nav-tabs .nav-item { margin-bottom: -1px; } .nav-tabs .nav-link { border: 1px solid transparent; border-top-right-radius: 0.25rem; border-top-left-radius: 0.25rem; } .nav-tabs .nav-link:focus, .nav-tabs .nav-link:hover { border-color: #eceeef #eceeef #ddd; } .nav-tabs .nav-link.disabled { color: #636c72; background-color: transparent; border-color: transparent; } .nav-tabs .nav-link.active, .nav-tabs .nav-item.show .nav-link { color: #464a4c; background-color: #fff; border-color: #ddd #ddd #fff; } .nav-tabs .dropdown-menu { margin-top: -1px; border-top-right-radius: 0; border-top-left-radius: 0; } .nav-pills .nav-link { border-radius: 0.25rem; } .nav-pills .nav-link.active, .nav-pills .nav-item.show .nav-link { color: #fff; cursor: default; background-color: #0275d8; } .nav-fill .nav-item { -webkit-box-flex: 1; -webkit-flex: 1 1 auto; -ms-flex: 1 1 auto; flex: 1 1 auto; text-align: center; } .nav-justified .nav-item { -webkit-box-flex: 1; -webkit-flex: 1 1 100%; -ms-flex: 1 1 100%; flex: 1 1 100%; text-align: center; } .tab-content > .tab-pane { display: none; } .tab-content > .active { display: block; } .navbar { position: relative; display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-orient: vertical; -webkit-box-direction: normal; -webkit-flex-direction: column; -ms-flex-direction: column; flex-direction: column; padding: 0.5rem 1rem; } .navbar-brand { display: inline-block; padding-top: .25rem; padding-bottom: .25rem; margin-right: 1rem; font-size: 1.25rem; line-height: inherit; white-space: nowrap; } .navbar-brand:focus, .navbar-brand:hover { text-decoration: none; } .navbar-nav { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-orient: vertical; -webkit-box-direction: normal; -webkit-flex-direction: column; -ms-flex-direction: column; flex-direction: column; padding-left: 0; margin-bottom: 0; list-style: none; } .navbar-nav .nav-link { padding-right: 0; padding-left: 0; } .navbar-text { display: inline-block; padding-top: .425rem; padding-bottom: .425rem; } .navbar-toggler { -webkit-align-self: flex-start; -ms-flex-item-align: start; align-self: flex-start; padding: 0.25rem 0.75rem; font-size: 1.25rem; line-height: 1; background: transparent; border: 1px solid transparent; border-radius: 0.25rem; } .navbar-toggler:focus, .navbar-toggler:hover { text-decoration: none; } .navbar-toggler-icon { display: inline-block; width: 1.5em; height: 1.5em; vertical-align: middle; content: ""; background: no-repeat center center; -webkit-background-size: 100% 100%; background-size: 100% 100%; } .navbar-toggler-left { position: absolute; left: 1rem; } .navbar-toggler-right { position: absolute; right: 1rem; } @media (max-width: 575px) { .navbar-toggleable .navbar-nav .dropdown-menu { position: static; float: none; } .navbar-toggleable > .container { padding-right: 0; padding-left: 0; } } @media (min-width: 576px) { .navbar-toggleable { -webkit-box-orient: horizontal; -webkit-box-direction: normal; -webkit-flex-direction: row; -ms-flex-direction: row; flex-direction: row; -webkit-flex-wrap: nowrap; -ms-flex-wrap: nowrap; flex-wrap: nowrap; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; } .navbar-toggleable .navbar-nav { -webkit-box-orient: horizontal; -webkit-box-direction: normal; -webkit-flex-direction: row; -ms-flex-direction: row; flex-direction: row; } .navbar-toggleable .navbar-nav .nav-link { padding-right: .5rem; padding-left: .5rem; } .navbar-toggleable > .container { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-flex-wrap: nowrap; -ms-flex-wrap: nowrap; flex-wrap: nowrap; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; } .navbar-toggleable .navbar-collapse { display: -webkit-box !important; display: -webkit-flex !important; display: -ms-flexbox !important; display: flex !important; width: 100%; } .navbar-toggleable .navbar-toggler { display: none; } } @media (max-width: 767px) { .navbar-toggleable-sm .navbar-nav .dropdown-menu { position: static; float: none; } .navbar-toggleable-sm > .container { padding-right: 0; padding-left: 0; } } @media (min-width: 768px) { .navbar-toggleable-sm { -webkit-box-orient: horizontal; -webkit-box-direction: normal; -webkit-flex-direction: row; -ms-flex-direction: row; flex-direction: row; -webkit-flex-wrap: nowrap; -ms-flex-wrap: nowrap; flex-wrap: nowrap; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; } .navbar-toggleable-sm .navbar-nav { -webkit-box-orient: horizontal; -webkit-box-direction: normal; -webkit-flex-direction: row; -ms-flex-direction: row; flex-direction: row; } .navbar-toggleable-sm .navbar-nav .nav-link { padding-right: .5rem; padding-left: .5rem; } .navbar-toggleable-sm > .container { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-flex-wrap: nowrap; -ms-flex-wrap: nowrap; flex-wrap: nowrap; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; } .navbar-toggleable-sm .navbar-collapse { display: -webkit-box !important; display: -webkit-flex !important; display: -ms-flexbox !important; display: flex !important; width: 100%; } .navbar-toggleable-sm .navbar-toggler { display: none; } } @media (max-width: 991px) { .navbar-toggleable-md .navbar-nav .dropdown-menu { position: static; float: none; } .navbar-toggleable-md > .container { padding-right: 0; padding-left: 0; } } @media (min-width: 992px) { .navbar-toggleable-md { -webkit-box-orient: horizontal; -webkit-box-direction: normal; -webkit-flex-direction: row; -ms-flex-direction: row; flex-direction: row; -webkit-flex-wrap: nowrap; -ms-flex-wrap: nowrap; flex-wrap: nowrap; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; } .navbar-toggleable-md .navbar-nav { -webkit-box-orient: horizontal; -webkit-box-direction: normal; -webkit-flex-direction: row; -ms-flex-direction: row; flex-direction: row; } .navbar-toggleable-md .navbar-nav .nav-link { padding-right: .5rem; padding-left: .5rem; } .navbar-toggleable-md > .container { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-flex-wrap: nowrap; -ms-flex-wrap: nowrap; flex-wrap: nowrap; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; } .navbar-toggleable-md .navbar-collapse { display: -webkit-box !important; display: -webkit-flex !important; display: -ms-flexbox !important; display: flex !important; width: 100%; } .navbar-toggleable-md .navbar-toggler { display: none; } } @media (max-width: 1199px) { .navbar-toggleable-lg .navbar-nav .dropdown-menu { position: static; float: none; } .navbar-toggleable-lg > .container { padding-right: 0; padding-left: 0; } } @media (min-width: 1200px) { .navbar-toggleable-lg { -webkit-box-orient: horizontal; -webkit-box-direction: normal; -webkit-flex-direction: row; -ms-flex-direction: row; flex-direction: row; -webkit-flex-wrap: nowrap; -ms-flex-wrap: nowrap; flex-wrap: nowrap; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; } .navbar-toggleable-lg .navbar-nav { -webkit-box-orient: horizontal; -webkit-box-direction: normal; -webkit-flex-direction: row; -ms-flex-direction: row; flex-direction: row; } .navbar-toggleable-lg .navbar-nav .nav-link { padding-right: .5rem; padding-left: .5rem; } .navbar-toggleable-lg > .container { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-flex-wrap: nowrap; -ms-flex-wrap: nowrap; flex-wrap: nowrap; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; } .navbar-toggleable-lg .navbar-collapse { display: -webkit-box !important; display: -webkit-flex !important; display: -ms-flexbox !important; display: flex !important; width: 100%; } .navbar-toggleable-lg .navbar-toggler { display: none; } } .navbar-toggleable-xl { -webkit-box-orient: horizontal; -webkit-box-direction: normal; -webkit-flex-direction: row; -ms-flex-direction: row; flex-direction: row; -webkit-flex-wrap: nowrap; -ms-flex-wrap: nowrap; flex-wrap: nowrap; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; } .navbar-toggleable-xl .navbar-nav .dropdown-menu { position: static; float: none; } .navbar-toggleable-xl > .container { padding-right: 0; padding-left: 0; } .navbar-toggleable-xl .navbar-nav { -webkit-box-orient: horizontal; -webkit-box-direction: normal; -webkit-flex-direction: row; -ms-flex-direction: row; flex-direction: row; } .navbar-toggleable-xl .navbar-nav .nav-link { padding-right: .5rem; padding-left: .5rem; } .navbar-toggleable-xl > .container { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-flex-wrap: nowrap; -ms-flex-wrap: nowrap; flex-wrap: nowrap; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; } .navbar-toggleable-xl .navbar-collapse { display: -webkit-box !important; display: -webkit-flex !important; display: -ms-flexbox !important; display: flex !important; width: 100%; } .navbar-toggleable-xl .navbar-toggler { display: none; } .navbar-light .navbar-brand, .navbar-light .navbar-toggler { color: rgba(0, 0, 0, 0.9); } .navbar-light .navbar-brand:focus, .navbar-light .navbar-brand:hover, .navbar-light .navbar-toggler:focus, .navbar-light .navbar-toggler:hover { color: rgba(0, 0, 0, 0.9); } .navbar-light .navbar-nav .nav-link { color: rgba(0, 0, 0, 0.5); } .navbar-light .navbar-nav .nav-link:focus, .navbar-light .navbar-nav .nav-link:hover { color: rgba(0, 0, 0, 0.7); } .navbar-light .navbar-nav .nav-link.disabled { color: rgba(0, 0, 0, 0.3); } .navbar-light .navbar-nav .open > .nav-link, .navbar-light .navbar-nav .active > .nav-link, .navbar-light .navbar-nav .nav-link.open, .navbar-light .navbar-nav .nav-link.active { color: rgba(0, 0, 0, 0.9); } .navbar-light .navbar-toggler { border-color: rgba(0, 0, 0, 0.1); } .navbar-light .navbar-toggler-icon { background-image: url("data:image/svg+xml;charset=utf8,%3Csvg viewBox='0 0 32 32' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath stroke='rgba(0, 0, 0, 0.5)' stroke-width='2' stroke-linecap='round' stroke-miterlimit='10' d='M4 8h24M4 16h24M4 24h24'/%3E%3C/svg%3E"); } .navbar-light .navbar-text { color: rgba(0, 0, 0, 0.5); } .navbar-inverse .navbar-brand, .navbar-inverse .navbar-toggler { color: white; } .navbar-inverse .navbar-brand:focus, .navbar-inverse .navbar-brand:hover, .navbar-inverse .navbar-toggler:focus, .navbar-inverse .navbar-toggler:hover { color: white; } .navbar-inverse .navbar-nav .nav-link { color: rgba(255, 255, 255, 0.5); } .navbar-inverse .navbar-nav .nav-link:focus, .navbar-inverse .navbar-nav .nav-link:hover { color: rgba(255, 255, 255, 0.75); } .navbar-inverse .navbar-nav .nav-link.disabled { color: rgba(255, 255, 255, 0.25); } .navbar-inverse .navbar-nav .open > .nav-link, .navbar-inverse .navbar-nav .active > .nav-link, .navbar-inverse .navbar-nav .nav-link.open, .navbar-inverse .navbar-nav .nav-link.active { color: white; } .navbar-inverse .navbar-toggler { border-color: rgba(255, 255, 255, 0.1); } .navbar-inverse .navbar-toggler-icon { background-image: url("data:image/svg+xml;charset=utf8,%3Csvg viewBox='0 0 32 32' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath stroke='rgba(255, 255, 255, 0.5)' stroke-width='2' stroke-linecap='round' stroke-miterlimit='10' d='M4 8h24M4 16h24M4 24h24'/%3E%3C/svg%3E"); } .navbar-inverse .navbar-text { color: rgba(255, 255, 255, 0.5); } .card { position: relative; display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-orient: vertical; -webkit-box-direction: normal; -webkit-flex-direction: column; -ms-flex-direction: column; flex-direction: column; background-color: #fff; border: 1px solid rgba(0, 0, 0, 0.125); border-radius: 0.25rem; } .card-block { -webkit-box-flex: 1; -webkit-flex: 1 1 auto; -ms-flex: 1 1 auto; flex: 1 1 auto; padding: 1.25rem; } .card-title { margin-bottom: 0.75rem; } .card-subtitle { margin-top: -0.375rem; margin-bottom: 0; } .card-text:last-child { margin-bottom: 0; } .card-link:hover { text-decoration: none; } .card-link + .card-link { margin-left: 1.25rem; } .card > .list-group:first-child .list-group-item:first-child { border-top-right-radius: 0.25rem; border-top-left-radius: 0.25rem; } .card > .list-group:last-child .list-group-item:last-child { border-bottom-right-radius: 0.25rem; border-bottom-left-radius: 0.25rem; } .card-header { padding: 0.75rem 1.25rem; margin-bottom: 0; background-color: #f7f7f9; border-bottom: 1px solid rgba(0, 0, 0, 0.125); } .card-header:first-child { border-radius: calc(0.25rem - 1px) calc(0.25rem - 1px) 0 0; } .card-footer { padding: 0.75rem 1.25rem; background-color: #f7f7f9; border-top: 1px solid rgba(0, 0, 0, 0.125); } .card-footer:last-child { border-radius: 0 0 calc(0.25rem - 1px) calc(0.25rem - 1px); } .card-header-tabs { margin-right: -0.625rem; margin-bottom: -0.75rem; margin-left: -0.625rem; border-bottom: 0; } .card-header-pills { margin-right: -0.625rem; margin-left: -0.625rem; } .card-primary { background-color: #0275d8; border-color: #0275d8; } .card-primary .card-header, .card-primary .card-footer { background-color: transparent; } .card-success { background-color: #5cb85c; border-color: #5cb85c; } .card-success .card-header, .card-success .card-footer { background-color: transparent; } .card-info { background-color: #5bc0de; border-color: #5bc0de; } .card-info .card-header, .card-info .card-footer { background-color: transparent; } .card-warning { background-color: #f0ad4e; border-color: #f0ad4e; } .card-warning .card-header, .card-warning .card-footer { background-color: transparent; } .card-danger { background-color: #d9534f; border-color: #d9534f; } .card-danger .card-header, .card-danger .card-footer { background-color: transparent; } .card-outline-primary { background-color: transparent; border-color: #0275d8; } .card-outline-secondary { background-color: transparent; border-color: #ccc; } .card-outline-info { background-color: transparent; border-color: #5bc0de; } .card-outline-success { background-color: transparent; border-color: #5cb85c; } .card-outline-warning { background-color: transparent; border-color: #f0ad4e; } .card-outline-danger { background-color: transparent; border-color: #d9534f; } .card-inverse { color: rgba(255, 255, 255, 0.65); } .card-inverse .card-header, .card-inverse .card-footer { background-color: transparent; border-color: rgba(255, 255, 255, 0.2); } .card-inverse .card-header, .card-inverse .card-footer, .card-inverse .card-title, .card-inverse .card-blockquote { color: #fff; } .card-inverse .card-link, .card-inverse .card-text, .card-inverse .card-subtitle, .card-inverse .card-blockquote .blockquote-footer { color: rgba(255, 255, 255, 0.65); } .card-inverse .card-link:focus, .card-inverse .card-link:hover { color: #fff; } .card-blockquote { padding: 0; margin-bottom: 0; border-left: 0; } .card-img { border-radius: calc(0.25rem - 1px); } .card-img-overlay { position: absolute; top: 0; right: 0; bottom: 0; left: 0; padding: 1.25rem; } .card-img-top { border-top-right-radius: calc(0.25rem - 1px); border-top-left-radius: calc(0.25rem - 1px); } .card-img-bottom { border-bottom-right-radius: calc(0.25rem - 1px); border-bottom-left-radius: calc(0.25rem - 1px); } @media (min-width: 576px) { .card-deck { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-flex-flow: row wrap; -ms-flex-flow: row wrap; flex-flow: row wrap; } .card-deck .card { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-flex: 1; -webkit-flex: 1 0 0%; -ms-flex: 1 0 0%; flex: 1 0 0%; -webkit-box-orient: vertical; -webkit-box-direction: normal; -webkit-flex-direction: column; -ms-flex-direction: column; flex-direction: column; } .card-deck .card:not(:first-child) { margin-left: 15px; } .card-deck .card:not(:last-child) { margin-right: 15px; } } @media (min-width: 576px) { .card-group { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-flex-flow: row wrap; -ms-flex-flow: row wrap; flex-flow: row wrap; } .card-group .card { -webkit-box-flex: 1; -webkit-flex: 1 0 0%; -ms-flex: 1 0 0%; flex: 1 0 0%; } .card-group .card + .card { margin-left: 0; border-left: 0; } .card-group .card:first-child { border-bottom-right-radius: 0; border-top-right-radius: 0; } .card-group .card:first-child .card-img-top { border-top-right-radius: 0; } .card-group .card:first-child .card-img-bottom { border-bottom-right-radius: 0; } .card-group .card:last-child { border-bottom-left-radius: 0; border-top-left-radius: 0; } .card-group .card:last-child .card-img-top { border-top-left-radius: 0; } .card-group .card:last-child .card-img-bottom { border-bottom-left-radius: 0; } .card-group .card:not(:first-child):not(:last-child) { border-radius: 0; } .card-group .card:not(:first-child):not(:last-child) .card-img-top, .card-group .card:not(:first-child):not(:last-child) .card-img-bottom { border-radius: 0; } } @media (min-width: 576px) { .card-columns { -webkit-column-count: 3; -moz-column-count: 3; column-count: 3; -webkit-column-gap: 1.25rem; -moz-column-gap: 1.25rem; column-gap: 1.25rem; } .card-columns .card { display: inline-block; width: 100%; margin-bottom: 0.75rem; } } .breadcrumb { padding: 0.75rem 1rem; margin-bottom: 1rem; list-style: none; background-color: #eceeef; border-radius: 0.25rem; } .breadcrumb::after { display: block; content: ""; clear: both; } .breadcrumb-item { float: left; } .breadcrumb-item + .breadcrumb-item::before { display: inline-block; padding-right: 0.5rem; padding-left: 0.5rem; color: #636c72; content: "/"; } .breadcrumb-item + .breadcrumb-item:hover::before { text-decoration: underline; } .breadcrumb-item + .breadcrumb-item:hover::before { text-decoration: none; } .breadcrumb-item.active { color: #636c72; } .pagination { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; padding-left: 0; list-style: none; border-radius: 0.25rem; } .page-item:first-child .page-link { margin-left: 0; border-bottom-left-radius: 0.25rem; border-top-left-radius: 0.25rem; } .page-item:last-child .page-link { border-bottom-right-radius: 0.25rem; border-top-right-radius: 0.25rem; } .page-item.active .page-link { z-index: 2; color: #fff; background-color: #0275d8; border-color: #0275d8; } .page-item.disabled .page-link { color: #636c72; pointer-events: none; cursor: not-allowed; background-color: #fff; border-color: #ddd; } .page-link { position: relative; display: block; padding: 0.5rem 0.75rem; margin-left: -1px; line-height: 1.25; color: #0275d8; background-color: #fff; border: 1px solid #ddd; } .page-link:focus, .page-link:hover { color: #014c8c; text-decoration: none; background-color: #eceeef; border-color: #ddd; } .pagination-lg .page-link { padding: 0.75rem 1.5rem; font-size: 1.25rem; } .pagination-lg .page-item:first-child .page-link { border-bottom-left-radius: 0.3rem; border-top-left-radius: 0.3rem; } .pagination-lg .page-item:last-child .page-link { border-bottom-right-radius: 0.3rem; border-top-right-radius: 0.3rem; } .pagination-sm .page-link { padding: 0.25rem 0.5rem; font-size: 0.875rem; } .pagination-sm .page-item:first-child .page-link { border-bottom-left-radius: 0.2rem; border-top-left-radius: 0.2rem; } .pagination-sm .page-item:last-child .page-link { border-bottom-right-radius: 0.2rem; border-top-right-radius: 0.2rem; } .badge { display: inline-block; padding: 0.25em 0.4em; font-size: 75%; font-weight: bold; line-height: 1; color: #fff; text-align: center; white-space: nowrap; vertical-align: baseline; border-radius: 0.25rem; } .badge:empty { display: none; } .btn .badge { position: relative; top: -1px; } a.badge:focus, a.badge:hover { color: #fff; text-decoration: none; cursor: pointer; } .badge-pill { padding-right: 0.6em; padding-left: 0.6em; border-radius: 10rem; } .badge-default { background-color: #636c72; } .badge-default[href]:focus, .badge-default[href]:hover { background-color: #4b5257; } .badge-primary { background-color: #0275d8; } .badge-primary[href]:focus, .badge-primary[href]:hover { background-color: #025aa5; } .badge-success { background-color: #5cb85c; } .badge-success[href]:focus, .badge-success[href]:hover { background-color: #449d44; } .badge-info { background-color: #5bc0de; } .badge-info[href]:focus, .badge-info[href]:hover { background-color: #31b0d5; } .badge-warning { background-color: #f0ad4e; } .badge-warning[href]:focus, .badge-warning[href]:hover { background-color: #ec971f; } .badge-danger { background-color: #d9534f; } .badge-danger[href]:focus, .badge-danger[href]:hover { background-color: #c9302c; } .jumbotron { padding: 2rem 1rem; margin-bottom: 2rem; background-color: #eceeef; border-radius: 0.3rem; } @media (min-width: 576px) { .jumbotron { padding: 4rem 2rem; } } .jumbotron-hr { border-top-color: #d0d5d8; } .jumbotron-fluid { padding-right: 0; padding-left: 0; border-radius: 0; } .alert { padding: 0.75rem 1.25rem; margin-bottom: 1rem; border: 1px solid transparent; border-radius: 0.25rem; } .alert-heading { color: inherit; } .alert-link { font-weight: bold; } .alert-dismissible .close { position: relative; top: -0.75rem; right: -1.25rem; padding: 0.75rem 1.25rem; color: inherit; } .alert-success { background-color: #dff0d8; border-color: #d0e9c6; color: #3c763d; } .alert-success hr { border-top-color: #c1e2b3; } .alert-success .alert-link { color: #2b542c; } .alert-info { background-color: #d9edf7; border-color: #bcdff1; color: #31708f; } .alert-info hr { border-top-color: #a6d5ec; } .alert-info .alert-link { color: #245269; } .alert-warning { background-color: #fcf8e3; border-color: #faf2cc; color: #8a6d3b; } .alert-warning hr { border-top-color: #f7ecb5; } .alert-warning .alert-link { color: #66512c; } .alert-danger { background-color: #f2dede; border-color: #ebcccc; color: #a94442; } .alert-danger hr { border-top-color: #e4b9b9; } .alert-danger .alert-link { color: #843534; } @-webkit-keyframes progress-bar-stripes { from { background-position: 1rem 0; } to { background-position: 0 0; } } @-o-keyframes progress-bar-stripes { from { background-position: 1rem 0; } to { background-position: 0 0; } } @keyframes progress-bar-stripes { from { background-position: 1rem 0; } to { background-position: 0 0; } } .progress { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; overflow: hidden; font-size: 0.75rem; line-height: 1rem; text-align: center; background-color: #eceeef; border-radius: 0.25rem; } .progress-bar { height: 1rem; color: #fff; background-color: #0275d8; } .progress-bar-striped { background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); -webkit-background-size: 1rem 1rem; background-size: 1rem 1rem; } .progress-bar-animated { -webkit-animation: progress-bar-stripes 1s linear infinite; -o-animation: progress-bar-stripes 1s linear infinite; animation: progress-bar-stripes 1s linear infinite; } .media { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-align: start; -webkit-align-items: flex-start; -ms-flex-align: start; align-items: flex-start; } .media-body { -webkit-box-flex: 1; -webkit-flex: 1 1 0%; -ms-flex: 1 1 0%; flex: 1 1 0%; } .list-group { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-orient: vertical; -webkit-box-direction: normal; -webkit-flex-direction: column; -ms-flex-direction: column; flex-direction: column; padding-left: 0; margin-bottom: 0; } .list-group-item-action { width: 100%; color: #464a4c; text-align: inherit; } .list-group-item-action .list-group-item-heading { color: #292b2c; } .list-group-item-action:focus, .list-group-item-action:hover { color: #464a4c; text-decoration: none; background-color: #f7f7f9; } .list-group-item-action:active { color: #292b2c; background-color: #eceeef; } .list-group-item { position: relative; display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-flex-flow: row wrap; -ms-flex-flow: row wrap; flex-flow: row wrap; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; padding: 0.75rem 1.25rem; margin-bottom: -1px; background-color: #fff; border: 1px solid rgba(0, 0, 0, 0.125); } .list-group-item:first-child { border-top-right-radius: 0.25rem; border-top-left-radius: 0.25rem; } .list-group-item:last-child { margin-bottom: 0; border-bottom-right-radius: 0.25rem; border-bottom-left-radius: 0.25rem; } .list-group-item:focus, .list-group-item:hover { text-decoration: none; } .list-group-item.disabled, .list-group-item:disabled { color: #636c72; cursor: not-allowed; background-color: #fff; } .list-group-item.disabled .list-group-item-heading, .list-group-item:disabled .list-group-item-heading { color: inherit; } .list-group-item.disabled .list-group-item-text, .list-group-item:disabled .list-group-item-text { color: #636c72; } .list-group-item.active { z-index: 2; color: #fff; background-color: #0275d8; border-color: #0275d8; } .list-group-item.active .list-group-item-heading, .list-group-item.active .list-group-item-heading > small, .list-group-item.active .list-group-item-heading > .small { color: inherit; } .list-group-item.active .list-group-item-text { color: #daeeff; } .list-group-flush .list-group-item { border-right: 0; border-left: 0; border-radius: 0; } .list-group-flush:first-child .list-group-item:first-child { border-top: 0; } .list-group-flush:last-child .list-group-item:last-child { border-bottom: 0; } .list-group-item-success { color: #3c763d; background-color: #dff0d8; } a.list-group-item-success, button.list-group-item-success { color: #3c763d; } a.list-group-item-success .list-group-item-heading, button.list-group-item-success .list-group-item-heading { color: inherit; } a.list-group-item-success:focus, a.list-group-item-success:hover, button.list-group-item-success:focus, button.list-group-item-success:hover { color: #3c763d; background-color: #d0e9c6; } a.list-group-item-success.active, button.list-group-item-success.active { color: #fff; background-color: #3c763d; border-color: #3c763d; } .list-group-item-info { color: #31708f; background-color: #d9edf7; } a.list-group-item-info, button.list-group-item-info { color: #31708f; } a.list-group-item-info .list-group-item-heading, button.list-group-item-info .list-group-item-heading { color: inherit; } a.list-group-item-info:focus, a.list-group-item-info:hover, button.list-group-item-info:focus, button.list-group-item-info:hover { color: #31708f; background-color: #c4e3f3; } a.list-group-item-info.active, button.list-group-item-info.active { color: #fff; background-color: #31708f; border-color: #31708f; } .list-group-item-warning { color: #8a6d3b; background-color: #fcf8e3; } a.list-group-item-warning, button.list-group-item-warning { color: #8a6d3b; } a.list-group-item-warning .list-group-item-heading, button.list-group-item-warning .list-group-item-heading { color: inherit; } a.list-group-item-warning:focus, a.list-group-item-warning:hover, button.list-group-item-warning:focus, button.list-group-item-warning:hover { color: #8a6d3b; background-color: #faf2cc; } a.list-group-item-warning.active, button.list-group-item-warning.active { color: #fff; background-color: #8a6d3b; border-color: #8a6d3b; } .list-group-item-danger { color: #a94442; background-color: #f2dede; } a.list-group-item-danger, button.list-group-item-danger { color: #a94442; } a.list-group-item-danger .list-group-item-heading, button.list-group-item-danger .list-group-item-heading { color: inherit; } a.list-group-item-danger:focus, a.list-group-item-danger:hover, button.list-group-item-danger:focus, button.list-group-item-danger:hover { color: #a94442; background-color: #ebcccc; } a.list-group-item-danger.active, button.list-group-item-danger.active { color: #fff; background-color: #a94442; border-color: #a94442; } .embed-responsive { position: relative; display: block; width: 100%; padding: 0; overflow: hidden; } .embed-responsive::before { display: block; content: ""; } .embed-responsive .embed-responsive-item, .embed-responsive iframe, .embed-responsive embed, .embed-responsive object, .embed-responsive video { position: absolute; top: 0; bottom: 0; left: 0; width: 100%; height: 100%; border: 0; } .embed-responsive-21by9::before { padding-top: 42.857143%; } .embed-responsive-16by9::before { padding-top: 56.25%; } .embed-responsive-4by3::before { padding-top: 75%; } .embed-responsive-1by1::before { padding-top: 100%; } .close { float: right; font-size: 1.5rem; font-weight: bold; line-height: 1; color: #000; text-shadow: 0 1px 0 #fff; opacity: .5; } .close:focus, .close:hover { color: #000; text-decoration: none; cursor: pointer; opacity: .75; } button.close { padding: 0; cursor: pointer; background: transparent; border: 0; -webkit-appearance: none; } .modal-open { overflow: hidden; } .modal { position: fixed; top: 0; right: 0; bottom: 0; left: 0; z-index: 1050; display: none; overflow: hidden; outline: 0; } .modal.fade .modal-dialog { -webkit-transition: -webkit-transform 0.3s ease-out; transition: -webkit-transform 0.3s ease-out; -o-transition: -o-transform 0.3s ease-out; transition: transform 0.3s ease-out; transition: transform 0.3s ease-out, -webkit-transform 0.3s ease-out, -o-transform 0.3s ease-out; -webkit-transform: translate(0, -25%); -o-transform: translate(0, -25%); transform: translate(0, -25%); } .modal.show .modal-dialog { -webkit-transform: translate(0, 0); -o-transform: translate(0, 0); transform: translate(0, 0); } .modal-open .modal { overflow-x: hidden; overflow-y: auto; } .modal-dialog { position: relative; width: auto; margin: 10px; } .modal-content { position: relative; display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-orient: vertical; -webkit-box-direction: normal; -webkit-flex-direction: column; -ms-flex-direction: column; flex-direction: column; background-color: #fff; -webkit-background-clip: padding-box; background-clip: padding-box; border: 1px solid rgba(0, 0, 0, 0.2); border-radius: 0.3rem; outline: 0; } .modal-backdrop { position: fixed; top: 0; right: 0; bottom: 0; left: 0; z-index: 1040; background-color: #000; } .modal-backdrop.fade { opacity: 0; } .modal-backdrop.show { opacity: 0.5; } .modal-header { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; -webkit-box-pack: justify; -webkit-justify-content: space-between; -ms-flex-pack: justify; justify-content: space-between; padding: 15px; border-bottom: 1px solid #eceeef; } .modal-title { margin-bottom: 0; line-height: 1.5; } .modal-body { position: relative; -webkit-box-flex: 1; -webkit-flex: 1 1 auto; -ms-flex: 1 1 auto; flex: 1 1 auto; padding: 15px; } .modal-footer { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; -webkit-box-pack: end; -webkit-justify-content: flex-end; -ms-flex-pack: end; justify-content: flex-end; padding: 15px; border-top: 1px solid #eceeef; } .modal-footer > :not(:first-child) { margin-left: .25rem; } .modal-footer > :not(:last-child) { margin-right: .25rem; } .modal-scrollbar-measure { position: absolute; top: -9999px; width: 50px; height: 50px; overflow: scroll; } @media (min-width: 576px) { .modal-dialog { max-width: 500px; margin: 30px auto; } .modal-sm { max-width: 300px; } } @media (min-width: 992px) { .modal-lg { max-width: 800px; } } .tooltip { position: absolute; z-index: 1070; display: block; font-family: -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; font-style: normal; font-weight: normal; letter-spacing: normal; line-break: auto; line-height: 1.5; text-align: left; text-align: start; text-decoration: none; text-shadow: none; text-transform: none; white-space: normal; word-break: normal; word-spacing: normal; font-size: 0.875rem; word-wrap: break-word; opacity: 0; } .tooltip.show { opacity: 0.9; } .tooltip.tooltip-top, .tooltip.bs-tether-element-attached-bottom { padding: 5px 0; margin-top: -3px; } .tooltip.tooltip-top .tooltip-inner::before, .tooltip.bs-tether-element-attached-bottom .tooltip-inner::before { bottom: 0; left: 50%; margin-left: -5px; content: ""; border-width: 5px 5px 0; border-top-color: #000; } .tooltip.tooltip-right, .tooltip.bs-tether-element-attached-left { padding: 0 5px; margin-left: 3px; } .tooltip.tooltip-right .tooltip-inner::before, .tooltip.bs-tether-element-attached-left .tooltip-inner::before { top: 50%; left: 0; margin-top: -5px; content: ""; border-width: 5px 5px 5px 0; border-right-color: #000; } .tooltip.tooltip-bottom, .tooltip.bs-tether-element-attached-top { padding: 5px 0; margin-top: 3px; } .tooltip.tooltip-bottom .tooltip-inner::before, .tooltip.bs-tether-element-attached-top .tooltip-inner::before { top: 0; left: 50%; margin-left: -5px; content: ""; border-width: 0 5px 5px; border-bottom-color: #000; } .tooltip.tooltip-left, .tooltip.bs-tether-element-attached-right { padding: 0 5px; margin-left: -3px; } .tooltip.tooltip-left .tooltip-inner::before, .tooltip.bs-tether-element-attached-right .tooltip-inner::before { top: 50%; right: 0; margin-top: -5px; content: ""; border-width: 5px 0 5px 5px; border-left-color: #000; } .tooltip-inner { max-width: 200px; padding: 3px 8px; color: #fff; text-align: center; background-color: #000; border-radius: 0.25rem; } .tooltip-inner::before { position: absolute; width: 0; height: 0; border-color: transparent; border-style: solid; } .popover { position: absolute; top: 0; left: 0; z-index: 1060; display: block; max-width: 276px; padding: 1px; font-family: -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; font-style: normal; font-weight: normal; letter-spacing: normal; line-break: auto; line-height: 1.5; text-align: left; text-align: start; text-decoration: none; text-shadow: none; text-transform: none; white-space: normal; word-break: normal; word-spacing: normal; font-size: 0.875rem; word-wrap: break-word; background-color: #fff; -webkit-background-clip: padding-box; background-clip: padding-box; border: 1px solid rgba(0, 0, 0, 0.2); border-radius: 0.3rem; } .popover.popover-top, .popover.bs-tether-element-attached-bottom { margin-top: -10px; } .popover.popover-top::before, .popover.popover-top::after, .popover.bs-tether-element-attached-bottom::before, .popover.bs-tether-element-attached-bottom::after { left: 50%; border-bottom-width: 0; } .popover.popover-top::before, .popover.bs-tether-element-attached-bottom::before { bottom: -11px; margin-left: -11px; border-top-color: rgba(0, 0, 0, 0.25); } .popover.popover-top::after, .popover.bs-tether-element-attached-bottom::after { bottom: -10px; margin-left: -10px; border-top-color: #fff; } .popover.popover-right, .popover.bs-tether-element-attached-left { margin-left: 10px; } .popover.popover-right::before, .popover.popover-right::after, .popover.bs-tether-element-attached-left::before, .popover.bs-tether-element-attached-left::after { top: 50%; border-left-width: 0; } .popover.popover-right::before, .popover.bs-tether-element-attached-left::before { left: -11px; margin-top: -11px; border-right-color: rgba(0, 0, 0, 0.25); } .popover.popover-right::after, .popover.bs-tether-element-attached-left::after { left: -10px; margin-top: -10px; border-right-color: #fff; } .popover.popover-bottom, .popover.bs-tether-element-attached-top { margin-top: 10px; } .popover.popover-bottom::before, .popover.popover-bottom::after, .popover.bs-tether-element-attached-top::before, .popover.bs-tether-element-attached-top::after { left: 50%; border-top-width: 0; } .popover.popover-bottom::before, .popover.bs-tether-element-attached-top::before { top: -11px; margin-left: -11px; border-bottom-color: rgba(0, 0, 0, 0.25); } .popover.popover-bottom::after, .popover.bs-tether-element-attached-top::after { top: -10px; margin-left: -10px; border-bottom-color: #f7f7f7; } .popover.popover-bottom .popover-title::before, .popover.bs-tether-element-attached-top .popover-title::before { position: absolute; top: 0; left: 50%; display: block; width: 20px; margin-left: -10px; content: ""; border-bottom: 1px solid #f7f7f7; } .popover.popover-left, .popover.bs-tether-element-attached-right { margin-left: -10px; } .popover.popover-left::before, .popover.popover-left::after, .popover.bs-tether-element-attached-right::before, .popover.bs-tether-element-attached-right::after { top: 50%; border-right-width: 0; } .popover.popover-left::before, .popover.bs-tether-element-attached-right::before { right: -11px; margin-top: -11px; border-left-color: rgba(0, 0, 0, 0.25); } .popover.popover-left::after, .popover.bs-tether-element-attached-right::after { right: -10px; margin-top: -10px; border-left-color: #fff; } .popover-title { padding: 8px 14px; margin-bottom: 0; font-size: 1rem; background-color: #f7f7f7; border-bottom: 1px solid #ebebeb; border-top-right-radius: calc(0.3rem - 1px); border-top-left-radius: calc(0.3rem - 1px); } .popover-title:empty { display: none; } .popover-content { padding: 9px 14px; } .popover::before, .popover::after { position: absolute; display: block; width: 0; height: 0; border-color: transparent; border-style: solid; } .popover::before { content: ""; border-width: 11px; } .popover::after { content: ""; border-width: 10px; } .carousel { position: relative; } .carousel-inner { position: relative; width: 100%; overflow: hidden; } .carousel-item { position: relative; display: none; width: 100%; } @media (-webkit-transform-3d) { .carousel-item { -webkit-transition: -webkit-transform 0.6s ease-in-out; transition: -webkit-transform 0.6s ease-in-out; -o-transition: -o-transform 0.6s ease-in-out; transition: transform 0.6s ease-in-out; transition: transform 0.6s ease-in-out, -webkit-transform 0.6s ease-in-out, -o-transform 0.6s ease-in-out; -webkit-backface-visibility: hidden; backface-visibility: hidden; -webkit-perspective: 1000px; perspective: 1000px; } } @supports ((-webkit-transform: translate3d(0, 0, 0)) or (transform: translate3d(0, 0, 0))) { .carousel-item { -webkit-transition: -webkit-transform 0.6s ease-in-out; transition: -webkit-transform 0.6s ease-in-out; -o-transition: -o-transform 0.6s ease-in-out; transition: transform 0.6s ease-in-out; transition: transform 0.6s ease-in-out, -webkit-transform 0.6s ease-in-out, -o-transform 0.6s ease-in-out; -webkit-backface-visibility: hidden; backface-visibility: hidden; -webkit-perspective: 1000px; perspective: 1000px; } } .carousel-item.active, .carousel-item-next, .carousel-item-prev { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; } .carousel-item-next, .carousel-item-prev { position: absolute; top: 0; } @media (-webkit-transform-3d) { .carousel-item-next.carousel-item-left, .carousel-item-prev.carousel-item-right { -webkit-transform: translate3d(0, 0, 0); transform: translate3d(0, 0, 0); } .carousel-item-next, .active.carousel-item-right { -webkit-transform: translate3d(100%, 0, 0); transform: translate3d(100%, 0, 0); } .carousel-item-prev, .active.carousel-item-left { -webkit-transform: translate3d(-100%, 0, 0); transform: translate3d(-100%, 0, 0); } } @supports ((-webkit-transform: translate3d(0, 0, 0)) or (transform: translate3d(0, 0, 0))) { .carousel-item-next.carousel-item-left, .carousel-item-prev.carousel-item-right { -webkit-transform: translate3d(0, 0, 0); transform: translate3d(0, 0, 0); } .carousel-item-next, .active.carousel-item-right { -webkit-transform: translate3d(100%, 0, 0); transform: translate3d(100%, 0, 0); } .carousel-item-prev, .active.carousel-item-left { -webkit-transform: translate3d(-100%, 0, 0); transform: translate3d(-100%, 0, 0); } } .carousel-control-prev, .carousel-control-next { position: absolute; top: 0; bottom: 0; display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; -webkit-box-pack: center; -webkit-justify-content: center; -ms-flex-pack: center; justify-content: center; width: 15%; color: #fff; text-align: center; opacity: 0.5; } .carousel-control-prev:focus, .carousel-control-prev:hover, .carousel-control-next:focus, .carousel-control-next:hover { color: #fff; text-decoration: none; outline: 0; opacity: .9; } .carousel-control-prev { left: 0; } .carousel-control-next { right: 0; } .carousel-control-prev-icon, .carousel-control-next-icon { display: inline-block; width: 20px; height: 20px; background: transparent no-repeat center center; -webkit-background-size: 100% 100%; background-size: 100% 100%; } .carousel-control-prev-icon { background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='%23fff' viewBox='0 0 8 8'%3E%3Cpath d='M4 0l-4 4 4 4 1.5-1.5-2.5-2.5 2.5-2.5-1.5-1.5z'/%3E%3C/svg%3E"); } .carousel-control-next-icon { background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='%23fff' viewBox='0 0 8 8'%3E%3Cpath d='M1.5 0l-1.5 1.5 2.5 2.5-2.5 2.5 1.5 1.5 4-4-4-4z'/%3E%3C/svg%3E"); } .carousel-indicators { position: absolute; right: 0; bottom: 10px; left: 0; z-index: 15; display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-pack: center; -webkit-justify-content: center; -ms-flex-pack: center; justify-content: center; padding-left: 0; margin-right: 15%; margin-left: 15%; list-style: none; } .carousel-indicators li { position: relative; -webkit-box-flex: 1; -webkit-flex: 1 0 auto; -ms-flex: 1 0 auto; flex: 1 0 auto; max-width: 30px; height: 3px; margin-right: 3px; margin-left: 3px; text-indent: -999px; cursor: pointer; background-color: rgba(255, 255, 255, 0.5); } .carousel-indicators li::before { position: absolute; top: -10px; left: 0; display: inline-block; width: 100%; height: 10px; content: ""; } .carousel-indicators li::after { position: absolute; bottom: -10px; left: 0; display: inline-block; width: 100%; height: 10px; content: ""; } .carousel-indicators .active { background-color: #fff; } .carousel-caption { position: absolute; right: 15%; bottom: 20px; left: 15%; z-index: 10; padding-top: 20px; padding-bottom: 20px; color: #fff; text-align: center; } .align-baseline { vertical-align: baseline !important; } .align-top { vertical-align: top !important; } .align-middle { vertical-align: middle !important; } .align-bottom { vertical-align: bottom !important; } .align-text-bottom { vertical-align: text-bottom !important; } .align-text-top { vertical-align: text-top !important; } .bg-faded { background-color: #f7f7f7; } .bg-primary { background-color: #0275d8 !important; } a.bg-primary:focus, a.bg-primary:hover { background-color: #025aa5 !important; } .bg-success { background-color: #5cb85c !important; } a.bg-success:focus, a.bg-success:hover { background-color: #449d44 !important; } .bg-info { background-color: #5bc0de !important; } a.bg-info:focus, a.bg-info:hover { background-color: #31b0d5 !important; } .bg-warning { background-color: #f0ad4e !important; } a.bg-warning:focus, a.bg-warning:hover { background-color: #ec971f !important; } .bg-danger { background-color: #d9534f !important; } a.bg-danger:focus, a.bg-danger:hover { background-color: #c9302c !important; } .bg-inverse { background-color: #292b2c !important; } a.bg-inverse:focus, a.bg-inverse:hover { background-color: #101112 !important; } .border-0 { border: 0 !important; } .border-top-0 { border-top: 0 !important; } .border-right-0 { border-right: 0 !important; } .border-bottom-0 { border-bottom: 0 !important; } .border-left-0 { border-left: 0 !important; } .rounded { border-radius: 0.25rem; } .rounded-top { border-top-right-radius: 0.25rem; border-top-left-radius: 0.25rem; } .rounded-right { border-bottom-right-radius: 0.25rem; border-top-right-radius: 0.25rem; } .rounded-bottom { border-bottom-right-radius: 0.25rem; border-bottom-left-radius: 0.25rem; } .rounded-left { border-bottom-left-radius: 0.25rem; border-top-left-radius: 0.25rem; } .rounded-circle { border-radius: 50%; } .rounded-0 { border-radius: 0; } .clearfix::after { display: block; content: ""; clear: both; } .d-none { display: none !important; } .d-inline { display: inline !important; } .d-inline-block { display: inline-block !important; } .d-block { display: block !important; } .d-table { display: table !important; } .d-table-cell { display: table-cell !important; } .d-flex { display: -webkit-box !important; display: -webkit-flex !important; display: -ms-flexbox !important; display: flex !important; } .d-inline-flex { display: -webkit-inline-box !important; display: -webkit-inline-flex !important; display: -ms-inline-flexbox !important; display: inline-flex !important; } @media (min-width: 576px) { .d-sm-none { display: none !important; } .d-sm-inline { display: inline !important; } .d-sm-inline-block { display: inline-block !important; } .d-sm-block { display: block !important; } .d-sm-table { display: table !important; } .d-sm-table-cell { display: table-cell !important; } .d-sm-flex { display: -webkit-box !important; display: -webkit-flex !important; display: -ms-flexbox !important; display: flex !important; } .d-sm-inline-flex { display: -webkit-inline-box !important; display: -webkit-inline-flex !important; display: -ms-inline-flexbox !important; display: inline-flex !important; } } @media (min-width: 768px) { .d-md-none { display: none !important; } .d-md-inline { display: inline !important; } .d-md-inline-block { display: inline-block !important; } .d-md-block { display: block !important; } .d-md-table { display: table !important; } .d-md-table-cell { display: table-cell !important; } .d-md-flex { display: -webkit-box !important; display: -webkit-flex !important; display: -ms-flexbox !important; display: flex !important; } .d-md-inline-flex { display: -webkit-inline-box !important; display: -webkit-inline-flex !important; display: -ms-inline-flexbox !important; display: inline-flex !important; } } @media (min-width: 992px) { .d-lg-none { display: none !important; } .d-lg-inline { display: inline !important; } .d-lg-inline-block { display: inline-block !important; } .d-lg-block { display: block !important; } .d-lg-table { display: table !important; } .d-lg-table-cell { display: table-cell !important; } .d-lg-flex { display: -webkit-box !important; display: -webkit-flex !important; display: -ms-flexbox !important; display: flex !important; } .d-lg-inline-flex { display: -webkit-inline-box !important; display: -webkit-inline-flex !important; display: -ms-inline-flexbox !important; display: inline-flex !important; } } @media (min-width: 1200px) { .d-xl-none { display: none !important; } .d-xl-inline { display: inline !important; } .d-xl-inline-block { display: inline-block !important; } .d-xl-block { display: block !important; } .d-xl-table { display: table !important; } .d-xl-table-cell { display: table-cell !important; } .d-xl-flex { display: -webkit-box !important; display: -webkit-flex !important; display: -ms-flexbox !important; display: flex !important; } .d-xl-inline-flex { display: -webkit-inline-box !important; display: -webkit-inline-flex !important; display: -ms-inline-flexbox !important; display: inline-flex !important; } } .flex-first { -webkit-box-ordinal-group: 0; -webkit-order: -1; -ms-flex-order: -1; order: -1; } .flex-last { -webkit-box-ordinal-group: 2; -webkit-order: 1; -ms-flex-order: 1; order: 1; } .flex-unordered { -webkit-box-ordinal-group: 1; -webkit-order: 0; -ms-flex-order: 0; order: 0; } .flex-row { -webkit-box-orient: horizontal !important; -webkit-box-direction: normal !important; -webkit-flex-direction: row !important; -ms-flex-direction: row !important; flex-direction: row !important; } .flex-column { -webkit-box-orient: vertical !important; -webkit-box-direction: normal !important; -webkit-flex-direction: column !important; -ms-flex-direction: column !important; flex-direction: column !important; } .flex-row-reverse { -webkit-box-orient: horizontal !important; -webkit-box-direction: reverse !important; -webkit-flex-direction: row-reverse !important; -ms-flex-direction: row-reverse !important; flex-direction: row-reverse !important; } .flex-column-reverse { -webkit-box-orient: vertical !important; -webkit-box-direction: reverse !important; -webkit-flex-direction: column-reverse !important; -ms-flex-direction: column-reverse !important; flex-direction: column-reverse !important; } .flex-wrap { -webkit-flex-wrap: wrap !important; -ms-flex-wrap: wrap !important; flex-wrap: wrap !important; } .flex-nowrap { -webkit-flex-wrap: nowrap !important; -ms-flex-wrap: nowrap !important; flex-wrap: nowrap !important; } .flex-wrap-reverse { -webkit-flex-wrap: wrap-reverse !important; -ms-flex-wrap: wrap-reverse !important; flex-wrap: wrap-reverse !important; } .justify-content-start { -webkit-box-pack: start !important; -webkit-justify-content: flex-start !important; -ms-flex-pack: start !important; justify-content: flex-start !important; } .justify-content-end { -webkit-box-pack: end !important; -webkit-justify-content: flex-end !important; -ms-flex-pack: end !important; justify-content: flex-end !important; } .justify-content-center { -webkit-box-pack: center !important; -webkit-justify-content: center !important; -ms-flex-pack: center !important; justify-content: center !important; } .justify-content-between { -webkit-box-pack: justify !important; -webkit-justify-content: space-between !important; -ms-flex-pack: justify !important; justify-content: space-between !important; } .justify-content-around { -webkit-justify-content: space-around !important; -ms-flex-pack: distribute !important; justify-content: space-around !important; } .align-items-start { -webkit-box-align: start !important; -webkit-align-items: flex-start !important; -ms-flex-align: start !important; align-items: flex-start !important; } .align-items-end { -webkit-box-align: end !important; -webkit-align-items: flex-end !important; -ms-flex-align: end !important; align-items: flex-end !important; } .align-items-center { -webkit-box-align: center !important; -webkit-align-items: center !important; -ms-flex-align: center !important; align-items: center !important; } .align-items-baseline { -webkit-box-align: baseline !important; -webkit-align-items: baseline !important; -ms-flex-align: baseline !important; align-items: baseline !important; } .align-items-stretch { -webkit-box-align: stretch !important; -webkit-align-items: stretch !important; -ms-flex-align: stretch !important; align-items: stretch !important; } .align-content-start { -webkit-align-content: flex-start !important; -ms-flex-line-pack: start !important; align-content: flex-start !important; } .align-content-end { -webkit-align-content: flex-end !important; -ms-flex-line-pack: end !important; align-content: flex-end !important; } .align-content-center { -webkit-align-content: center !important; -ms-flex-line-pack: center !important; align-content: center !important; } .align-content-between { -webkit-align-content: space-between !important; -ms-flex-line-pack: justify !important; align-content: space-between !important; } .align-content-around { -webkit-align-content: space-around !important; -ms-flex-line-pack: distribute !important; align-content: space-around !important; } .align-content-stretch { -webkit-align-content: stretch !important; -ms-flex-line-pack: stretch !important; align-content: stretch !important; } .align-self-auto { -webkit-align-self: auto !important; -ms-flex-item-align: auto !important; -ms-grid-row-align: auto !important; align-self: auto !important; } .align-self-start { -webkit-align-self: flex-start !important; -ms-flex-item-align: start !important; align-self: flex-start !important; } .align-self-end { -webkit-align-self: flex-end !important; -ms-flex-item-align: end !important; align-self: flex-end !important; } .align-self-center { -webkit-align-self: center !important; -ms-flex-item-align: center !important; -ms-grid-row-align: center !important; align-self: center !important; } .align-self-baseline { -webkit-align-self: baseline !important; -ms-flex-item-align: baseline !important; align-self: baseline !important; } .align-self-stretch { -webkit-align-self: stretch !important; -ms-flex-item-align: stretch !important; -ms-grid-row-align: stretch !important; align-self: stretch !important; } @media (min-width: 576px) { .flex-sm-first { -webkit-box-ordinal-group: 0; -webkit-order: -1; -ms-flex-order: -1; order: -1; } .flex-sm-last { -webkit-box-ordinal-group: 2; -webkit-order: 1; -ms-flex-order: 1; order: 1; } .flex-sm-unordered { -webkit-box-ordinal-group: 1; -webkit-order: 0; -ms-flex-order: 0; order: 0; } .flex-sm-row { -webkit-box-orient: horizontal !important; -webkit-box-direction: normal !important; -webkit-flex-direction: row !important; -ms-flex-direction: row !important; flex-direction: row !important; } .flex-sm-column { -webkit-box-orient: vertical !important; -webkit-box-direction: normal !important; -webkit-flex-direction: column !important; -ms-flex-direction: column !important; flex-direction: column !important; } .flex-sm-row-reverse { -webkit-box-orient: horizontal !important; -webkit-box-direction: reverse !important; -webkit-flex-direction: row-reverse !important; -ms-flex-direction: row-reverse !important; flex-direction: row-reverse !important; } .flex-sm-column-reverse { -webkit-box-orient: vertical !important; -webkit-box-direction: reverse !important; -webkit-flex-direction: column-reverse !important; -ms-flex-direction: column-reverse !important; flex-direction: column-reverse !important; } .flex-sm-wrap { -webkit-flex-wrap: wrap !important; -ms-flex-wrap: wrap !important; flex-wrap: wrap !important; } .flex-sm-nowrap { -webkit-flex-wrap: nowrap !important; -ms-flex-wrap: nowrap !important; flex-wrap: nowrap !important; } .flex-sm-wrap-reverse { -webkit-flex-wrap: wrap-reverse !important; -ms-flex-wrap: wrap-reverse !important; flex-wrap: wrap-reverse !important; } .justify-content-sm-start { -webkit-box-pack: start !important; -webkit-justify-content: flex-start !important; -ms-flex-pack: start !important; justify-content: flex-start !important; } .justify-content-sm-end { -webkit-box-pack: end !important; -webkit-justify-content: flex-end !important; -ms-flex-pack: end !important; justify-content: flex-end !important; } .justify-content-sm-center { -webkit-box-pack: center !important; -webkit-justify-content: center !important; -ms-flex-pack: center !important; justify-content: center !important; } .justify-content-sm-between { -webkit-box-pack: justify !important; -webkit-justify-content: space-between !important; -ms-flex-pack: justify !important; justify-content: space-between !important; } .justify-content-sm-around { -webkit-justify-content: space-around !important; -ms-flex-pack: distribute !important; justify-content: space-around !important; } .align-items-sm-start { -webkit-box-align: start !important; -webkit-align-items: flex-start !important; -ms-flex-align: start !important; align-items: flex-start !important; } .align-items-sm-end { -webkit-box-align: end !important; -webkit-align-items: flex-end !important; -ms-flex-align: end !important; align-items: flex-end !important; } .align-items-sm-center { -webkit-box-align: center !important; -webkit-align-items: center !important; -ms-flex-align: center !important; align-items: center !important; } .align-items-sm-baseline { -webkit-box-align: baseline !important; -webkit-align-items: baseline !important; -ms-flex-align: baseline !important; align-items: baseline !important; } .align-items-sm-stretch { -webkit-box-align: stretch !important; -webkit-align-items: stretch !important; -ms-flex-align: stretch !important; align-items: stretch !important; } .align-content-sm-start { -webkit-align-content: flex-start !important; -ms-flex-line-pack: start !important; align-content: flex-start !important; } .align-content-sm-end { -webkit-align-content: flex-end !important; -ms-flex-line-pack: end !important; align-content: flex-end !important; } .align-content-sm-center { -webkit-align-content: center !important; -ms-flex-line-pack: center !important; align-content: center !important; } .align-content-sm-between { -webkit-align-content: space-between !important; -ms-flex-line-pack: justify !important; align-content: space-between !important; } .align-content-sm-around { -webkit-align-content: space-around !important; -ms-flex-line-pack: distribute !important; align-content: space-around !important; } .align-content-sm-stretch { -webkit-align-content: stretch !important; -ms-flex-line-pack: stretch !important; align-content: stretch !important; } .align-self-sm-auto { -webkit-align-self: auto !important; -ms-flex-item-align: auto !important; -ms-grid-row-align: auto !important; align-self: auto !important; } .align-self-sm-start { -webkit-align-self: flex-start !important; -ms-flex-item-align: start !important; align-self: flex-start !important; } .align-self-sm-end { -webkit-align-self: flex-end !important; -ms-flex-item-align: end !important; align-self: flex-end !important; } .align-self-sm-center { -webkit-align-self: center !important; -ms-flex-item-align: center !important; -ms-grid-row-align: center !important; align-self: center !important; } .align-self-sm-baseline { -webkit-align-self: baseline !important; -ms-flex-item-align: baseline !important; align-self: baseline !important; } .align-self-sm-stretch { -webkit-align-self: stretch !important; -ms-flex-item-align: stretch !important; -ms-grid-row-align: stretch !important; align-self: stretch !important; } } @media (min-width: 768px) { .flex-md-first { -webkit-box-ordinal-group: 0; -webkit-order: -1; -ms-flex-order: -1; order: -1; } .flex-md-last { -webkit-box-ordinal-group: 2; -webkit-order: 1; -ms-flex-order: 1; order: 1; } .flex-md-unordered { -webkit-box-ordinal-group: 1; -webkit-order: 0; -ms-flex-order: 0; order: 0; } .flex-md-row { -webkit-box-orient: horizontal !important; -webkit-box-direction: normal !important; -webkit-flex-direction: row !important; -ms-flex-direction: row !important; flex-direction: row !important; } .flex-md-column { -webkit-box-orient: vertical !important; -webkit-box-direction: normal !important; -webkit-flex-direction: column !important; -ms-flex-direction: column !important; flex-direction: column !important; } .flex-md-row-reverse { -webkit-box-orient: horizontal !important; -webkit-box-direction: reverse !important; -webkit-flex-direction: row-reverse !important; -ms-flex-direction: row-reverse !important; flex-direction: row-reverse !important; } .flex-md-column-reverse { -webkit-box-orient: vertical !important; -webkit-box-direction: reverse !important; -webkit-flex-direction: column-reverse !important; -ms-flex-direction: column-reverse !important; flex-direction: column-reverse !important; } .flex-md-wrap { -webkit-flex-wrap: wrap !important; -ms-flex-wrap: wrap !important; flex-wrap: wrap !important; } .flex-md-nowrap { -webkit-flex-wrap: nowrap !important; -ms-flex-wrap: nowrap !important; flex-wrap: nowrap !important; } .flex-md-wrap-reverse { -webkit-flex-wrap: wrap-reverse !important; -ms-flex-wrap: wrap-reverse !important; flex-wrap: wrap-reverse !important; } .justify-content-md-start { -webkit-box-pack: start !important; -webkit-justify-content: flex-start !important; -ms-flex-pack: start !important; justify-content: flex-start !important; } .justify-content-md-end { -webkit-box-pack: end !important; -webkit-justify-content: flex-end !important; -ms-flex-pack: end !important; justify-content: flex-end !important; } .justify-content-md-center { -webkit-box-pack: center !important; -webkit-justify-content: center !important; -ms-flex-pack: center !important; justify-content: center !important; } .justify-content-md-between { -webkit-box-pack: justify !important; -webkit-justify-content: space-between !important; -ms-flex-pack: justify !important; justify-content: space-between !important; } .justify-content-md-around { -webkit-justify-content: space-around !important; -ms-flex-pack: distribute !important; justify-content: space-around !important; } .align-items-md-start { -webkit-box-align: start !important; -webkit-align-items: flex-start !important; -ms-flex-align: start !important; align-items: flex-start !important; } .align-items-md-end { -webkit-box-align: end !important; -webkit-align-items: flex-end !important; -ms-flex-align: end !important; align-items: flex-end !important; } .align-items-md-center { -webkit-box-align: center !important; -webkit-align-items: center !important; -ms-flex-align: center !important; align-items: center !important; } .align-items-md-baseline { -webkit-box-align: baseline !important; -webkit-align-items: baseline !important; -ms-flex-align: baseline !important; align-items: baseline !important; } .align-items-md-stretch { -webkit-box-align: stretch !important; -webkit-align-items: stretch !important; -ms-flex-align: stretch !important; align-items: stretch !important; } .align-content-md-start { -webkit-align-content: flex-start !important; -ms-flex-line-pack: start !important; align-content: flex-start !important; } .align-content-md-end { -webkit-align-content: flex-end !important; -ms-flex-line-pack: end !important; align-content: flex-end !important; } .align-content-md-center { -webkit-align-content: center !important; -ms-flex-line-pack: center !important; align-content: center !important; } .align-content-md-between { -webkit-align-content: space-between !important; -ms-flex-line-pack: justify !important; align-content: space-between !important; } .align-content-md-around { -webkit-align-content: space-around !important; -ms-flex-line-pack: distribute !important; align-content: space-around !important; } .align-content-md-stretch { -webkit-align-content: stretch !important; -ms-flex-line-pack: stretch !important; align-content: stretch !important; } .align-self-md-auto { -webkit-align-self: auto !important; -ms-flex-item-align: auto !important; -ms-grid-row-align: auto !important; align-self: auto !important; } .align-self-md-start { -webkit-align-self: flex-start !important; -ms-flex-item-align: start !important; align-self: flex-start !important; } .align-self-md-end { -webkit-align-self: flex-end !important; -ms-flex-item-align: end !important; align-self: flex-end !important; } .align-self-md-center { -webkit-align-self: center !important; -ms-flex-item-align: center !important; -ms-grid-row-align: center !important; align-self: center !important; } .align-self-md-baseline { -webkit-align-self: baseline !important; -ms-flex-item-align: baseline !important; align-self: baseline !important; } .align-self-md-stretch { -webkit-align-self: stretch !important; -ms-flex-item-align: stretch !important; -ms-grid-row-align: stretch !important; align-self: stretch !important; } } @media (min-width: 992px) { .flex-lg-first { -webkit-box-ordinal-group: 0; -webkit-order: -1; -ms-flex-order: -1; order: -1; } .flex-lg-last { -webkit-box-ordinal-group: 2; -webkit-order: 1; -ms-flex-order: 1; order: 1; } .flex-lg-unordered { -webkit-box-ordinal-group: 1; -webkit-order: 0; -ms-flex-order: 0; order: 0; } .flex-lg-row { -webkit-box-orient: horizontal !important; -webkit-box-direction: normal !important; -webkit-flex-direction: row !important; -ms-flex-direction: row !important; flex-direction: row !important; } .flex-lg-column { -webkit-box-orient: vertical !important; -webkit-box-direction: normal !important; -webkit-flex-direction: column !important; -ms-flex-direction: column !important; flex-direction: column !important; } .flex-lg-row-reverse { -webkit-box-orient: horizontal !important; -webkit-box-direction: reverse !important; -webkit-flex-direction: row-reverse !important; -ms-flex-direction: row-reverse !important; flex-direction: row-reverse !important; } .flex-lg-column-reverse { -webkit-box-orient: vertical !important; -webkit-box-direction: reverse !important; -webkit-flex-direction: column-reverse !important; -ms-flex-direction: column-reverse !important; flex-direction: column-reverse !important; } .flex-lg-wrap { -webkit-flex-wrap: wrap !important; -ms-flex-wrap: wrap !important; flex-wrap: wrap !important; } .flex-lg-nowrap { -webkit-flex-wrap: nowrap !important; -ms-flex-wrap: nowrap !important; flex-wrap: nowrap !important; } .flex-lg-wrap-reverse { -webkit-flex-wrap: wrap-reverse !important; -ms-flex-wrap: wrap-reverse !important; flex-wrap: wrap-reverse !important; } .justify-content-lg-start { -webkit-box-pack: start !important; -webkit-justify-content: flex-start !important; -ms-flex-pack: start !important; justify-content: flex-start !important; } .justify-content-lg-end { -webkit-box-pack: end !important; -webkit-justify-content: flex-end !important; -ms-flex-pack: end !important; justify-content: flex-end !important; } .justify-content-lg-center { -webkit-box-pack: center !important; -webkit-justify-content: center !important; -ms-flex-pack: center !important; justify-content: center !important; } .justify-content-lg-between { -webkit-box-pack: justify !important; -webkit-justify-content: space-between !important; -ms-flex-pack: justify !important; justify-content: space-between !important; } .justify-content-lg-around { -webkit-justify-content: space-around !important; -ms-flex-pack: distribute !important; justify-content: space-around !important; } .align-items-lg-start { -webkit-box-align: start !important; -webkit-align-items: flex-start !important; -ms-flex-align: start !important; align-items: flex-start !important; } .align-items-lg-end { -webkit-box-align: end !important; -webkit-align-items: flex-end !important; -ms-flex-align: end !important; align-items: flex-end !important; } .align-items-lg-center { -webkit-box-align: center !important; -webkit-align-items: center !important; -ms-flex-align: center !important; align-items: center !important; } .align-items-lg-baseline { -webkit-box-align: baseline !important; -webkit-align-items: baseline !important; -ms-flex-align: baseline !important; align-items: baseline !important; } .align-items-lg-stretch { -webkit-box-align: stretch !important; -webkit-align-items: stretch !important; -ms-flex-align: stretch !important; align-items: stretch !important; } .align-content-lg-start { -webkit-align-content: flex-start !important; -ms-flex-line-pack: start !important; align-content: flex-start !important; } .align-content-lg-end { -webkit-align-content: flex-end !important; -ms-flex-line-pack: end !important; align-content: flex-end !important; } .align-content-lg-center { -webkit-align-content: center !important; -ms-flex-line-pack: center !important; align-content: center !important; } .align-content-lg-between { -webkit-align-content: space-between !important; -ms-flex-line-pack: justify !important; align-content: space-between !important; } .align-content-lg-around { -webkit-align-content: space-around !important; -ms-flex-line-pack: distribute !important; align-content: space-around !important; } .align-content-lg-stretch { -webkit-align-content: stretch !important; -ms-flex-line-pack: stretch !important; align-content: stretch !important; } .align-self-lg-auto { -webkit-align-self: auto !important; -ms-flex-item-align: auto !important; -ms-grid-row-align: auto !important; align-self: auto !important; } .align-self-lg-start { -webkit-align-self: flex-start !important; -ms-flex-item-align: start !important; align-self: flex-start !important; } .align-self-lg-end { -webkit-align-self: flex-end !important; -ms-flex-item-align: end !important; align-self: flex-end !important; } .align-self-lg-center { -webkit-align-self: center !important; -ms-flex-item-align: center !important; -ms-grid-row-align: center !important; align-self: center !important; } .align-self-lg-baseline { -webkit-align-self: baseline !important; -ms-flex-item-align: baseline !important; align-self: baseline !important; } .align-self-lg-stretch { -webkit-align-self: stretch !important; -ms-flex-item-align: stretch !important; -ms-grid-row-align: stretch !important; align-self: stretch !important; } } @media (min-width: 1200px) { .flex-xl-first { -webkit-box-ordinal-group: 0; -webkit-order: -1; -ms-flex-order: -1; order: -1; } .flex-xl-last { -webkit-box-ordinal-group: 2; -webkit-order: 1; -ms-flex-order: 1; order: 1; } .flex-xl-unordered { -webkit-box-ordinal-group: 1; -webkit-order: 0; -ms-flex-order: 0; order: 0; } .flex-xl-row { -webkit-box-orient: horizontal !important; -webkit-box-direction: normal !important; -webkit-flex-direction: row !important; -ms-flex-direction: row !important; flex-direction: row !important; } .flex-xl-column { -webkit-box-orient: vertical !important; -webkit-box-direction: normal !important; -webkit-flex-direction: column !important; -ms-flex-direction: column !important; flex-direction: column !important; } .flex-xl-row-reverse { -webkit-box-orient: horizontal !important; -webkit-box-direction: reverse !important; -webkit-flex-direction: row-reverse !important; -ms-flex-direction: row-reverse !important; flex-direction: row-reverse !important; } .flex-xl-column-reverse { -webkit-box-orient: vertical !important; -webkit-box-direction: reverse !important; -webkit-flex-direction: column-reverse !important; -ms-flex-direction: column-reverse !important; flex-direction: column-reverse !important; } .flex-xl-wrap { -webkit-flex-wrap: wrap !important; -ms-flex-wrap: wrap !important; flex-wrap: wrap !important; } .flex-xl-nowrap { -webkit-flex-wrap: nowrap !important; -ms-flex-wrap: nowrap !important; flex-wrap: nowrap !important; } .flex-xl-wrap-reverse { -webkit-flex-wrap: wrap-reverse !important; -ms-flex-wrap: wrap-reverse !important; flex-wrap: wrap-reverse !important; } .justify-content-xl-start { -webkit-box-pack: start !important; -webkit-justify-content: flex-start !important; -ms-flex-pack: start !important; justify-content: flex-start !important; } .justify-content-xl-end { -webkit-box-pack: end !important; -webkit-justify-content: flex-end !important; -ms-flex-pack: end !important; justify-content: flex-end !important; } .justify-content-xl-center { -webkit-box-pack: center !important; -webkit-justify-content: center !important; -ms-flex-pack: center !important; justify-content: center !important; } .justify-content-xl-between { -webkit-box-pack: justify !important; -webkit-justify-content: space-between !important; -ms-flex-pack: justify !important; justify-content: space-between !important; } .justify-content-xl-around { -webkit-justify-content: space-around !important; -ms-flex-pack: distribute !important; justify-content: space-around !important; } .align-items-xl-start { -webkit-box-align: start !important; -webkit-align-items: flex-start !important; -ms-flex-align: start !important; align-items: flex-start !important; } .align-items-xl-end { -webkit-box-align: end !important; -webkit-align-items: flex-end !important; -ms-flex-align: end !important; align-items: flex-end !important; } .align-items-xl-center { -webkit-box-align: center !important; -webkit-align-items: center !important; -ms-flex-align: center !important; align-items: center !important; } .align-items-xl-baseline { -webkit-box-align: baseline !important; -webkit-align-items: baseline !important; -ms-flex-align: baseline !important; align-items: baseline !important; } .align-items-xl-stretch { -webkit-box-align: stretch !important; -webkit-align-items: stretch !important; -ms-flex-align: stretch !important; align-items: stretch !important; } .align-content-xl-start { -webkit-align-content: flex-start !important; -ms-flex-line-pack: start !important; align-content: flex-start !important; } .align-content-xl-end { -webkit-align-content: flex-end !important; -ms-flex-line-pack: end !important; align-content: flex-end !important; } .align-content-xl-center { -webkit-align-content: center !important; -ms-flex-line-pack: center !important; align-content: center !important; } .align-content-xl-between { -webkit-align-content: space-between !important; -ms-flex-line-pack: justify !important; align-content: space-between !important; } .align-content-xl-around { -webkit-align-content: space-around !important; -ms-flex-line-pack: distribute !important; align-content: space-around !important; } .align-content-xl-stretch { -webkit-align-content: stretch !important; -ms-flex-line-pack: stretch !important; align-content: stretch !important; } .align-self-xl-auto { -webkit-align-self: auto !important; -ms-flex-item-align: auto !important; -ms-grid-row-align: auto !important; align-self: auto !important; } .align-self-xl-start { -webkit-align-self: flex-start !important; -ms-flex-item-align: start !important; align-self: flex-start !important; } .align-self-xl-end { -webkit-align-self: flex-end !important; -ms-flex-item-align: end !important; align-self: flex-end !important; } .align-self-xl-center { -webkit-align-self: center !important; -ms-flex-item-align: center !important; -ms-grid-row-align: center !important; align-self: center !important; } .align-self-xl-baseline { -webkit-align-self: baseline !important; -ms-flex-item-align: baseline !important; align-self: baseline !important; } .align-self-xl-stretch { -webkit-align-self: stretch !important; -ms-flex-item-align: stretch !important; -ms-grid-row-align: stretch !important; align-self: stretch !important; } } .float-left { float: left !important; } .float-right { float: right !important; } .float-none { float: none !important; } @media (min-width: 576px) { .float-sm-left { float: left !important; } .float-sm-right { float: right !important; } .float-sm-none { float: none !important; } } @media (min-width: 768px) { .float-md-left { float: left !important; } .float-md-right { float: right !important; } .float-md-none { float: none !important; } } @media (min-width: 992px) { .float-lg-left { float: left !important; } .float-lg-right { float: right !important; } .float-lg-none { float: none !important; } } @media (min-width: 1200px) { .float-xl-left { float: left !important; } .float-xl-right { float: right !important; } .float-xl-none { float: none !important; } } .fixed-top { position: fixed; top: 0; right: 0; left: 0; z-index: 1030; } .fixed-bottom { position: fixed; right: 0; bottom: 0; left: 0; z-index: 1030; } .sticky-top { position: -webkit-sticky; position: sticky; top: 0; z-index: 1030; } .sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); border: 0; } .sr-only-focusable:active, .sr-only-focusable:focus { position: static; width: auto; height: auto; margin: 0; overflow: visible; clip: auto; } .w-25 { width: 25% !important; } .w-50 { width: 50% !important; } .w-75 { width: 75% !important; } .w-100 { width: 100% !important; } .h-25 { height: 25% !important; } .h-50 { height: 50% !important; } .h-75 { height: 75% !important; } .h-100 { height: 100% !important; } .mw-100 { max-width: 100% !important; } .mh-100 { max-height: 100% !important; } .m-0 { margin: 0 0 !important; } .mt-0 { margin-top: 0 !important; } .mr-0 { margin-right: 0 !important; } .mb-0 { margin-bottom: 0 !important; } .ml-0 { margin-left: 0 !important; } .mx-0 { margin-right: 0 !important; margin-left: 0 !important; } .my-0 { margin-top: 0 !important; margin-bottom: 0 !important; } .m-1 { margin: 0.25rem 0.25rem !important; } .mt-1 { margin-top: 0.25rem !important; } .mr-1 { margin-right: 0.25rem !important; } .mb-1 { margin-bottom: 0.25rem !important; } .ml-1 { margin-left: 0.25rem !important; } .mx-1 { margin-right: 0.25rem !important; margin-left: 0.25rem !important; } .my-1 { margin-top: 0.25rem !important; margin-bottom: 0.25rem !important; } .m-2 { margin: 0.5rem 0.5rem !important; } .mt-2 { margin-top: 0.5rem !important; } .mr-2 { margin-right: 0.5rem !important; } .mb-2 { margin-bottom: 0.5rem !important; } .ml-2 { margin-left: 0.5rem !important; } .mx-2 { margin-right: 0.5rem !important; margin-left: 0.5rem !important; } .my-2 { margin-top: 0.5rem !important; margin-bottom: 0.5rem !important; } .m-3 { margin: 1rem 1rem !important; } .mt-3 { margin-top: 1rem !important; } .mr-3 { margin-right: 1rem !important; } .mb-3 { margin-bottom: 1rem !important; } .ml-3 { margin-left: 1rem !important; } .mx-3 { margin-right: 1rem !important; margin-left: 1rem !important; } .my-3 { margin-top: 1rem !important; margin-bottom: 1rem !important; } .m-4 { margin: 1.5rem 1.5rem !important; } .mt-4 { margin-top: 1.5rem !important; } .mr-4 { margin-right: 1.5rem !important; } .mb-4 { margin-bottom: 1.5rem !important; } .ml-4 { margin-left: 1.5rem !important; } .mx-4 { margin-right: 1.5rem !important; margin-left: 1.5rem !important; } .my-4 { margin-top: 1.5rem !important; margin-bottom: 1.5rem !important; } .m-5 { margin: 3rem 3rem !important; } .mt-5 { margin-top: 3rem !important; } .mr-5 { margin-right: 3rem !important; } .mb-5 { margin-bottom: 3rem !important; } .ml-5 { margin-left: 3rem !important; } .mx-5 { margin-right: 3rem !important; margin-left: 3rem !important; } .my-5 { margin-top: 3rem !important; margin-bottom: 3rem !important; } .p-0 { padding: 0 0 !important; } .pt-0 { padding-top: 0 !important; } .pr-0 { padding-right: 0 !important; } .pb-0 { padding-bottom: 0 !important; } .pl-0 { padding-left: 0 !important; } .px-0 { padding-right: 0 !important; padding-left: 0 !important; } .py-0 { padding-top: 0 !important; padding-bottom: 0 !important; } .p-1 { padding: 0.25rem 0.25rem !important; } .pt-1 { padding-top: 0.25rem !important; } .pr-1 { padding-right: 0.25rem !important; } .pb-1 { padding-bottom: 0.25rem !important; } .pl-1 { padding-left: 0.25rem !important; } .px-1 { padding-right: 0.25rem !important; padding-left: 0.25rem !important; } .py-1 { padding-top: 0.25rem !important; padding-bottom: 0.25rem !important; } .p-2 { padding: 0.5rem 0.5rem !important; } .pt-2 { padding-top: 0.5rem !important; } .pr-2 { padding-right: 0.5rem !important; } .pb-2 { padding-bottom: 0.5rem !important; } .pl-2 { padding-left: 0.5rem !important; } .px-2 { padding-right: 0.5rem !important; padding-left: 0.5rem !important; } .py-2 { padding-top: 0.5rem !important; padding-bottom: 0.5rem !important; } .p-3 { padding: 1rem 1rem !important; } .pt-3 { padding-top: 1rem !important; } .pr-3 { padding-right: 1rem !important; } .pb-3 { padding-bottom: 1rem !important; } .pl-3 { padding-left: 1rem !important; } .px-3 { padding-right: 1rem !important; padding-left: 1rem !important; } .py-3 { padding-top: 1rem !important; padding-bottom: 1rem !important; } .p-4 { padding: 1.5rem 1.5rem !important; } .pt-4 { padding-top: 1.5rem !important; } .pr-4 { padding-right: 1.5rem !important; } .pb-4 { padding-bottom: 1.5rem !important; } .pl-4 { padding-left: 1.5rem !important; } .px-4 { padding-right: 1.5rem !important; padding-left: 1.5rem !important; } .py-4 { padding-top: 1.5rem !important; padding-bottom: 1.5rem !important; } .p-5 { padding: 3rem 3rem !important; } .pt-5 { padding-top: 3rem !important; } .pr-5 { padding-right: 3rem !important; } .pb-5 { padding-bottom: 3rem !important; } .pl-5 { padding-left: 3rem !important; } .px-5 { padding-right: 3rem !important; padding-left: 3rem !important; } .py-5 { padding-top: 3rem !important; padding-bottom: 3rem !important; } .m-auto { margin: auto !important; } .mt-auto { margin-top: auto !important; } .mr-auto { margin-right: auto !important; } .mb-auto { margin-bottom: auto !important; } .ml-auto { margin-left: auto !important; } .mx-auto { margin-right: auto !important; margin-left: auto !important; } .my-auto { margin-top: auto !important; margin-bottom: auto !important; } @media (min-width: 576px) { .m-sm-0 { margin: 0 0 !important; } .mt-sm-0 { margin-top: 0 !important; } .mr-sm-0 { margin-right: 0 !important; } .mb-sm-0 { margin-bottom: 0 !important; } .ml-sm-0 { margin-left: 0 !important; } .mx-sm-0 { margin-right: 0 !important; margin-left: 0 !important; } .my-sm-0 { margin-top: 0 !important; margin-bottom: 0 !important; } .m-sm-1 { margin: 0.25rem 0.25rem !important; } .mt-sm-1 { margin-top: 0.25rem !important; } .mr-sm-1 { margin-right: 0.25rem !important; } .mb-sm-1 { margin-bottom: 0.25rem !important; } .ml-sm-1 { margin-left: 0.25rem !important; } .mx-sm-1 { margin-right: 0.25rem !important; margin-left: 0.25rem !important; } .my-sm-1 { margin-top: 0.25rem !important; margin-bottom: 0.25rem !important; } .m-sm-2 { margin: 0.5rem 0.5rem !important; } .mt-sm-2 { margin-top: 0.5rem !important; } .mr-sm-2 { margin-right: 0.5rem !important; } .mb-sm-2 { margin-bottom: 0.5rem !important; } .ml-sm-2 { margin-left: 0.5rem !important; } .mx-sm-2 { margin-right: 0.5rem !important; margin-left: 0.5rem !important; } .my-sm-2 { margin-top: 0.5rem !important; margin-bottom: 0.5rem !important; } .m-sm-3 { margin: 1rem 1rem !important; } .mt-sm-3 { margin-top: 1rem !important; } .mr-sm-3 { margin-right: 1rem !important; } .mb-sm-3 { margin-bottom: 1rem !important; } .ml-sm-3 { margin-left: 1rem !important; } .mx-sm-3 { margin-right: 1rem !important; margin-left: 1rem !important; } .my-sm-3 { margin-top: 1rem !important; margin-bottom: 1rem !important; } .m-sm-4 { margin: 1.5rem 1.5rem !important; } .mt-sm-4 { margin-top: 1.5rem !important; } .mr-sm-4 { margin-right: 1.5rem !important; } .mb-sm-4 { margin-bottom: 1.5rem !important; } .ml-sm-4 { margin-left: 1.5rem !important; } .mx-sm-4 { margin-right: 1.5rem !important; margin-left: 1.5rem !important; } .my-sm-4 { margin-top: 1.5rem !important; margin-bottom: 1.5rem !important; } .m-sm-5 { margin: 3rem 3rem !important; } .mt-sm-5 { margin-top: 3rem !important; } .mr-sm-5 { margin-right: 3rem !important; } .mb-sm-5 { margin-bottom: 3rem !important; } .ml-sm-5 { margin-left: 3rem !important; } .mx-sm-5 { margin-right: 3rem !important; margin-left: 3rem !important; } .my-sm-5 { margin-top: 3rem !important; margin-bottom: 3rem !important; } .p-sm-0 { padding: 0 0 !important; } .pt-sm-0 { padding-top: 0 !important; } .pr-sm-0 { padding-right: 0 !important; } .pb-sm-0 { padding-bottom: 0 !important; } .pl-sm-0 { padding-left: 0 !important; } .px-sm-0 { padding-right: 0 !important; padding-left: 0 !important; } .py-sm-0 { padding-top: 0 !important; padding-bottom: 0 !important; } .p-sm-1 { padding: 0.25rem 0.25rem !important; } .pt-sm-1 { padding-top: 0.25rem !important; } .pr-sm-1 { padding-right: 0.25rem !important; } .pb-sm-1 { padding-bottom: 0.25rem !important; } .pl-sm-1 { padding-left: 0.25rem !important; } .px-sm-1 { padding-right: 0.25rem !important; padding-left: 0.25rem !important; } .py-sm-1 { padding-top: 0.25rem !important; padding-bottom: 0.25rem !important; } .p-sm-2 { padding: 0.5rem 0.5rem !important; } .pt-sm-2 { padding-top: 0.5rem !important; } .pr-sm-2 { padding-right: 0.5rem !important; } .pb-sm-2 { padding-bottom: 0.5rem !important; } .pl-sm-2 { padding-left: 0.5rem !important; } .px-sm-2 { padding-right: 0.5rem !important; padding-left: 0.5rem !important; } .py-sm-2 { padding-top: 0.5rem !important; padding-bottom: 0.5rem !important; } .p-sm-3 { padding: 1rem 1rem !important; } .pt-sm-3 { padding-top: 1rem !important; } .pr-sm-3 { padding-right: 1rem !important; } .pb-sm-3 { padding-bottom: 1rem !important; } .pl-sm-3 { padding-left: 1rem !important; } .px-sm-3 { padding-right: 1rem !important; padding-left: 1rem !important; } .py-sm-3 { padding-top: 1rem !important; padding-bottom: 1rem !important; } .p-sm-4 { padding: 1.5rem 1.5rem !important; } .pt-sm-4 { padding-top: 1.5rem !important; } .pr-sm-4 { padding-right: 1.5rem !important; } .pb-sm-4 { padding-bottom: 1.5rem !important; } .pl-sm-4 { padding-left: 1.5rem !important; } .px-sm-4 { padding-right: 1.5rem !important; padding-left: 1.5rem !important; } .py-sm-4 { padding-top: 1.5rem !important; padding-bottom: 1.5rem !important; } .p-sm-5 { padding: 3rem 3rem !important; } .pt-sm-5 { padding-top: 3rem !important; } .pr-sm-5 { padding-right: 3rem !important; } .pb-sm-5 { padding-bottom: 3rem !important; } .pl-sm-5 { padding-left: 3rem !important; } .px-sm-5 { padding-right: 3rem !important; padding-left: 3rem !important; } .py-sm-5 { padding-top: 3rem !important; padding-bottom: 3rem !important; } .m-sm-auto { margin: auto !important; } .mt-sm-auto { margin-top: auto !important; } .mr-sm-auto { margin-right: auto !important; } .mb-sm-auto { margin-bottom: auto !important; } .ml-sm-auto { margin-left: auto !important; } .mx-sm-auto { margin-right: auto !important; margin-left: auto !important; } .my-sm-auto { margin-top: auto !important; margin-bottom: auto !important; } } @media (min-width: 768px) { .m-md-0 { margin: 0 0 !important; } .mt-md-0 { margin-top: 0 !important; } .mr-md-0 { margin-right: 0 !important; } .mb-md-0 { margin-bottom: 0 !important; } .ml-md-0 { margin-left: 0 !important; } .mx-md-0 { margin-right: 0 !important; margin-left: 0 !important; } .my-md-0 { margin-top: 0 !important; margin-bottom: 0 !important; } .m-md-1 { margin: 0.25rem 0.25rem !important; } .mt-md-1 { margin-top: 0.25rem !important; } .mr-md-1 { margin-right: 0.25rem !important; } .mb-md-1 { margin-bottom: 0.25rem !important; } .ml-md-1 { margin-left: 0.25rem !important; } .mx-md-1 { margin-right: 0.25rem !important; margin-left: 0.25rem !important; } .my-md-1 { margin-top: 0.25rem !important; margin-bottom: 0.25rem !important; } .m-md-2 { margin: 0.5rem 0.5rem !important; } .mt-md-2 { margin-top: 0.5rem !important; } .mr-md-2 { margin-right: 0.5rem !important; } .mb-md-2 { margin-bottom: 0.5rem !important; } .ml-md-2 { margin-left: 0.5rem !important; } .mx-md-2 { margin-right: 0.5rem !important; margin-left: 0.5rem !important; } .my-md-2 { margin-top: 0.5rem !important; margin-bottom: 0.5rem !important; } .m-md-3 { margin: 1rem 1rem !important; } .mt-md-3 { margin-top: 1rem !important; } .mr-md-3 { margin-right: 1rem !important; } .mb-md-3 { margin-bottom: 1rem !important; } .ml-md-3 { margin-left: 1rem !important; } .mx-md-3 { margin-right: 1rem !important; margin-left: 1rem !important; } .my-md-3 { margin-top: 1rem !important; margin-bottom: 1rem !important; } .m-md-4 { margin: 1.5rem 1.5rem !important; } .mt-md-4 { margin-top: 1.5rem !important; } .mr-md-4 { margin-right: 1.5rem !important; } .mb-md-4 { margin-bottom: 1.5rem !important; } .ml-md-4 { margin-left: 1.5rem !important; } .mx-md-4 { margin-right: 1.5rem !important; margin-left: 1.5rem !important; } .my-md-4 { margin-top: 1.5rem !important; margin-bottom: 1.5rem !important; } .m-md-5 { margin: 3rem 3rem !important; } .mt-md-5 { margin-top: 3rem !important; } .mr-md-5 { margin-right: 3rem !important; } .mb-md-5 { margin-bottom: 3rem !important; } .ml-md-5 { margin-left: 3rem !important; } .mx-md-5 { margin-right: 3rem !important; margin-left: 3rem !important; } .my-md-5 { margin-top: 3rem !important; margin-bottom: 3rem !important; } .p-md-0 { padding: 0 0 !important; } .pt-md-0 { padding-top: 0 !important; } .pr-md-0 { padding-right: 0 !important; } .pb-md-0 { padding-bottom: 0 !important; } .pl-md-0 { padding-left: 0 !important; } .px-md-0 { padding-right: 0 !important; padding-left: 0 !important; } .py-md-0 { padding-top: 0 !important; padding-bottom: 0 !important; } .p-md-1 { padding: 0.25rem 0.25rem !important; } .pt-md-1 { padding-top: 0.25rem !important; } .pr-md-1 { padding-right: 0.25rem !important; } .pb-md-1 { padding-bottom: 0.25rem !important; } .pl-md-1 { padding-left: 0.25rem !important; } .px-md-1 { padding-right: 0.25rem !important; padding-left: 0.25rem !important; } .py-md-1 { padding-top: 0.25rem !important; padding-bottom: 0.25rem !important; } .p-md-2 { padding: 0.5rem 0.5rem !important; } .pt-md-2 { padding-top: 0.5rem !important; } .pr-md-2 { padding-right: 0.5rem !important; } .pb-md-2 { padding-bottom: 0.5rem !important; } .pl-md-2 { padding-left: 0.5rem !important; } .px-md-2 { padding-right: 0.5rem !important; padding-left: 0.5rem !important; } .py-md-2 { padding-top: 0.5rem !important; padding-bottom: 0.5rem !important; } .p-md-3 { padding: 1rem 1rem !important; } .pt-md-3 { padding-top: 1rem !important; } .pr-md-3 { padding-right: 1rem !important; } .pb-md-3 { padding-bottom: 1rem !important; } .pl-md-3 { padding-left: 1rem !important; } .px-md-3 { padding-right: 1rem !important; padding-left: 1rem !important; } .py-md-3 { padding-top: 1rem !important; padding-bottom: 1rem !important; } .p-md-4 { padding: 1.5rem 1.5rem !important; } .pt-md-4 { padding-top: 1.5rem !important; } .pr-md-4 { padding-right: 1.5rem !important; } .pb-md-4 { padding-bottom: 1.5rem !important; } .pl-md-4 { padding-left: 1.5rem !important; } .px-md-4 { padding-right: 1.5rem !important; padding-left: 1.5rem !important; } .py-md-4 { padding-top: 1.5rem !important; padding-bottom: 1.5rem !important; } .p-md-5 { padding: 3rem 3rem !important; } .pt-md-5 { padding-top: 3rem !important; } .pr-md-5 { padding-right: 3rem !important; } .pb-md-5 { padding-bottom: 3rem !important; } .pl-md-5 { padding-left: 3rem !important; } .px-md-5 { padding-right: 3rem !important; padding-left: 3rem !important; } .py-md-5 { padding-top: 3rem !important; padding-bottom: 3rem !important; } .m-md-auto { margin: auto !important; } .mt-md-auto { margin-top: auto !important; } .mr-md-auto { margin-right: auto !important; } .mb-md-auto { margin-bottom: auto !important; } .ml-md-auto { margin-left: auto !important; } .mx-md-auto { margin-right: auto !important; margin-left: auto !important; } .my-md-auto { margin-top: auto !important; margin-bottom: auto !important; } } @media (min-width: 992px) { .m-lg-0 { margin: 0 0 !important; } .mt-lg-0 { margin-top: 0 !important; } .mr-lg-0 { margin-right: 0 !important; } .mb-lg-0 { margin-bottom: 0 !important; } .ml-lg-0 { margin-left: 0 !important; } .mx-lg-0 { margin-right: 0 !important; margin-left: 0 !important; } .my-lg-0 { margin-top: 0 !important; margin-bottom: 0 !important; } .m-lg-1 { margin: 0.25rem 0.25rem !important; } .mt-lg-1 { margin-top: 0.25rem !important; } .mr-lg-1 { margin-right: 0.25rem !important; } .mb-lg-1 { margin-bottom: 0.25rem !important; } .ml-lg-1 { margin-left: 0.25rem !important; } .mx-lg-1 { margin-right: 0.25rem !important; margin-left: 0.25rem !important; } .my-lg-1 { margin-top: 0.25rem !important; margin-bottom: 0.25rem !important; } .m-lg-2 { margin: 0.5rem 0.5rem !important; } .mt-lg-2 { margin-top: 0.5rem !important; } .mr-lg-2 { margin-right: 0.5rem !important; } .mb-lg-2 { margin-bottom: 0.5rem !important; } .ml-lg-2 { margin-left: 0.5rem !important; } .mx-lg-2 { margin-right: 0.5rem !important; margin-left: 0.5rem !important; } .my-lg-2 { margin-top: 0.5rem !important; margin-bottom: 0.5rem !important; } .m-lg-3 { margin: 1rem 1rem !important; } .mt-lg-3 { margin-top: 1rem !important; } .mr-lg-3 { margin-right: 1rem !important; } .mb-lg-3 { margin-bottom: 1rem !important; } .ml-lg-3 { margin-left: 1rem !important; } .mx-lg-3 { margin-right: 1rem !important; margin-left: 1rem !important; } .my-lg-3 { margin-top: 1rem !important; margin-bottom: 1rem !important; } .m-lg-4 { margin: 1.5rem 1.5rem !important; } .mt-lg-4 { margin-top: 1.5rem !important; } .mr-lg-4 { margin-right: 1.5rem !important; } .mb-lg-4 { margin-bottom: 1.5rem !important; } .ml-lg-4 { margin-left: 1.5rem !important; } .mx-lg-4 { margin-right: 1.5rem !important; margin-left: 1.5rem !important; } .my-lg-4 { margin-top: 1.5rem !important; margin-bottom: 1.5rem !important; } .m-lg-5 { margin: 3rem 3rem !important; } .mt-lg-5 { margin-top: 3rem !important; } .mr-lg-5 { margin-right: 3rem !important; } .mb-lg-5 { margin-bottom: 3rem !important; } .ml-lg-5 { margin-left: 3rem !important; } .mx-lg-5 { margin-right: 3rem !important; margin-left: 3rem !important; } .my-lg-5 { margin-top: 3rem !important; margin-bottom: 3rem !important; } .p-lg-0 { padding: 0 0 !important; } .pt-lg-0 { padding-top: 0 !important; } .pr-lg-0 { padding-right: 0 !important; } .pb-lg-0 { padding-bottom: 0 !important; } .pl-lg-0 { padding-left: 0 !important; } .px-lg-0 { padding-right: 0 !important; padding-left: 0 !important; } .py-lg-0 { padding-top: 0 !important; padding-bottom: 0 !important; } .p-lg-1 { padding: 0.25rem 0.25rem !important; } .pt-lg-1 { padding-top: 0.25rem !important; } .pr-lg-1 { padding-right: 0.25rem !important; } .pb-lg-1 { padding-bottom: 0.25rem !important; } .pl-lg-1 { padding-left: 0.25rem !important; } .px-lg-1 { padding-right: 0.25rem !important; padding-left: 0.25rem !important; } .py-lg-1 { padding-top: 0.25rem !important; padding-bottom: 0.25rem !important; } .p-lg-2 { padding: 0.5rem 0.5rem !important; } .pt-lg-2 { padding-top: 0.5rem !important; } .pr-lg-2 { padding-right: 0.5rem !important; } .pb-lg-2 { padding-bottom: 0.5rem !important; } .pl-lg-2 { padding-left: 0.5rem !important; } .px-lg-2 { padding-right: 0.5rem !important; padding-left: 0.5rem !important; } .py-lg-2 { padding-top: 0.5rem !important; padding-bottom: 0.5rem !important; } .p-lg-3 { padding: 1rem 1rem !important; } .pt-lg-3 { padding-top: 1rem !important; } .pr-lg-3 { padding-right: 1rem !important; } .pb-lg-3 { padding-bottom: 1rem !important; } .pl-lg-3 { padding-left: 1rem !important; } .px-lg-3 { padding-right: 1rem !important; padding-left: 1rem !important; } .py-lg-3 { padding-top: 1rem !important; padding-bottom: 1rem !important; } .p-lg-4 { padding: 1.5rem 1.5rem !important; } .pt-lg-4 { padding-top: 1.5rem !important; } .pr-lg-4 { padding-right: 1.5rem !important; } .pb-lg-4 { padding-bottom: 1.5rem !important; } .pl-lg-4 { padding-left: 1.5rem !important; } .px-lg-4 { padding-right: 1.5rem !important; padding-left: 1.5rem !important; } .py-lg-4 { padding-top: 1.5rem !important; padding-bottom: 1.5rem !important; } .p-lg-5 { padding: 3rem 3rem !important; } .pt-lg-5 { padding-top: 3rem !important; } .pr-lg-5 { padding-right: 3rem !important; } .pb-lg-5 { padding-bottom: 3rem !important; } .pl-lg-5 { padding-left: 3rem !important; } .px-lg-5 { padding-right: 3rem !important; padding-left: 3rem !important; } .py-lg-5 { padding-top: 3rem !important; padding-bottom: 3rem !important; } .m-lg-auto { margin: auto !important; } .mt-lg-auto { margin-top: auto !important; } .mr-lg-auto { margin-right: auto !important; } .mb-lg-auto { margin-bottom: auto !important; } .ml-lg-auto { margin-left: auto !important; } .mx-lg-auto { margin-right: auto !important; margin-left: auto !important; } .my-lg-auto { margin-top: auto !important; margin-bottom: auto !important; } } @media (min-width: 1200px) { .m-xl-0 { margin: 0 0 !important; } .mt-xl-0 { margin-top: 0 !important; } .mr-xl-0 { margin-right: 0 !important; } .mb-xl-0 { margin-bottom: 0 !important; } .ml-xl-0 { margin-left: 0 !important; } .mx-xl-0 { margin-right: 0 !important; margin-left: 0 !important; } .my-xl-0 { margin-top: 0 !important; margin-bottom: 0 !important; } .m-xl-1 { margin: 0.25rem 0.25rem !important; } .mt-xl-1 { margin-top: 0.25rem !important; } .mr-xl-1 { margin-right: 0.25rem !important; } .mb-xl-1 { margin-bottom: 0.25rem !important; } .ml-xl-1 { margin-left: 0.25rem !important; } .mx-xl-1 { margin-right: 0.25rem !important; margin-left: 0.25rem !important; } .my-xl-1 { margin-top: 0.25rem !important; margin-bottom: 0.25rem !important; } .m-xl-2 { margin: 0.5rem 0.5rem !important; } .mt-xl-2 { margin-top: 0.5rem !important; } .mr-xl-2 { margin-right: 0.5rem !important; } .mb-xl-2 { margin-bottom: 0.5rem !important; } .ml-xl-2 { margin-left: 0.5rem !important; } .mx-xl-2 { margin-right: 0.5rem !important; margin-left: 0.5rem !important; } .my-xl-2 { margin-top: 0.5rem !important; margin-bottom: 0.5rem !important; } .m-xl-3 { margin: 1rem 1rem !important; } .mt-xl-3 { margin-top: 1rem !important; } .mr-xl-3 { margin-right: 1rem !important; } .mb-xl-3 { margin-bottom: 1rem !important; } .ml-xl-3 { margin-left: 1rem !important; } .mx-xl-3 { margin-right: 1rem !important; margin-left: 1rem !important; } .my-xl-3 { margin-top: 1rem !important; margin-bottom: 1rem !important; } .m-xl-4 { margin: 1.5rem 1.5rem !important; } .mt-xl-4 { margin-top: 1.5rem !important; } .mr-xl-4 { margin-right: 1.5rem !important; } .mb-xl-4 { margin-bottom: 1.5rem !important; } .ml-xl-4 { margin-left: 1.5rem !important; } .mx-xl-4 { margin-right: 1.5rem !important; margin-left: 1.5rem !important; } .my-xl-4 { margin-top: 1.5rem !important; margin-bottom: 1.5rem !important; } .m-xl-5 { margin: 3rem 3rem !important; } .mt-xl-5 { margin-top: 3rem !important; } .mr-xl-5 { margin-right: 3rem !important; } .mb-xl-5 { margin-bottom: 3rem !important; } .ml-xl-5 { margin-left: 3rem !important; } .mx-xl-5 { margin-right: 3rem !important; margin-left: 3rem !important; } .my-xl-5 { margin-top: 3rem !important; margin-bottom: 3rem !important; } .p-xl-0 { padding: 0 0 !important; } .pt-xl-0 { padding-top: 0 !important; } .pr-xl-0 { padding-right: 0 !important; } .pb-xl-0 { padding-bottom: 0 !important; } .pl-xl-0 { padding-left: 0 !important; } .px-xl-0 { padding-right: 0 !important; padding-left: 0 !important; } .py-xl-0 { padding-top: 0 !important; padding-bottom: 0 !important; } .p-xl-1 { padding: 0.25rem 0.25rem !important; } .pt-xl-1 { padding-top: 0.25rem !important; } .pr-xl-1 { padding-right: 0.25rem !important; } .pb-xl-1 { padding-bottom: 0.25rem !important; } .pl-xl-1 { padding-left: 0.25rem !important; } .px-xl-1 { padding-right: 0.25rem !important; padding-left: 0.25rem !important; } .py-xl-1 { padding-top: 0.25rem !important; padding-bottom: 0.25rem !important; } .p-xl-2 { padding: 0.5rem 0.5rem !important; } .pt-xl-2 { padding-top: 0.5rem !important; } .pr-xl-2 { padding-right: 0.5rem !important; } .pb-xl-2 { padding-bottom: 0.5rem !important; } .pl-xl-2 { padding-left: 0.5rem !important; } .px-xl-2 { padding-right: 0.5rem !important; padding-left: 0.5rem !important; } .py-xl-2 { padding-top: 0.5rem !important; padding-bottom: 0.5rem !important; } .p-xl-3 { padding: 1rem 1rem !important; } .pt-xl-3 { padding-top: 1rem !important; } .pr-xl-3 { padding-right: 1rem !important; } .pb-xl-3 { padding-bottom: 1rem !important; } .pl-xl-3 { padding-left: 1rem !important; } .px-xl-3 { padding-right: 1rem !important; padding-left: 1rem !important; } .py-xl-3 { padding-top: 1rem !important; padding-bottom: 1rem !important; } .p-xl-4 { padding: 1.5rem 1.5rem !important; } .pt-xl-4 { padding-top: 1.5rem !important; } .pr-xl-4 { padding-right: 1.5rem !important; } .pb-xl-4 { padding-bottom: 1.5rem !important; } .pl-xl-4 { padding-left: 1.5rem !important; } .px-xl-4 { padding-right: 1.5rem !important; padding-left: 1.5rem !important; } .py-xl-4 { padding-top: 1.5rem !important; padding-bottom: 1.5rem !important; } .p-xl-5 { padding: 3rem 3rem !important; } .pt-xl-5 { padding-top: 3rem !important; } .pr-xl-5 { padding-right: 3rem !important; } .pb-xl-5 { padding-bottom: 3rem !important; } .pl-xl-5 { padding-left: 3rem !important; } .px-xl-5 { padding-right: 3rem !important; padding-left: 3rem !important; } .py-xl-5 { padding-top: 3rem !important; padding-bottom: 3rem !important; } .m-xl-auto { margin: auto !important; } .mt-xl-auto { margin-top: auto !important; } .mr-xl-auto { margin-right: auto !important; } .mb-xl-auto { margin-bottom: auto !important; } .ml-xl-auto { margin-left: auto !important; } .mx-xl-auto { margin-right: auto !important; margin-left: auto !important; } .my-xl-auto { margin-top: auto !important; margin-bottom: auto !important; } } .text-justify { text-align: justify !important; } .text-nowrap { white-space: nowrap !important; } .text-truncate { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .text-left { text-align: left !important; } .text-right { text-align: right !important; } .text-center { text-align: center !important; } @media (min-width: 576px) { .text-sm-left { text-align: left !important; } .text-sm-right { text-align: right !important; } .text-sm-center { text-align: center !important; } } @media (min-width: 768px) { .text-md-left { text-align: left !important; } .text-md-right { text-align: right !important; } .text-md-center { text-align: center !important; } } @media (min-width: 992px) { .text-lg-left { text-align: left !important; } .text-lg-right { text-align: right !important; } .text-lg-center { text-align: center !important; } } @media (min-width: 1200px) { .text-xl-left { text-align: left !important; } .text-xl-right { text-align: right !important; } .text-xl-center { text-align: center !important; } } .text-lowercase { text-transform: lowercase !important; } .text-uppercase { text-transform: uppercase !important; } .text-capitalize { text-transform: capitalize !important; } .font-weight-normal { font-weight: normal; } .font-weight-bold { font-weight: bold; } .font-italic { font-style: italic; } .text-white { color: #fff !important; } .text-muted { color: #636c72 !important; } a.text-muted:focus, a.text-muted:hover { color: #4b5257 !important; } .text-primary { color: #0275d8 !important; } a.text-primary:focus, a.text-primary:hover { color: #025aa5 !important; } .text-success { color: #5cb85c !important; } a.text-success:focus, a.text-success:hover { color: #449d44 !important; } .text-info { color: #5bc0de !important; } a.text-info:focus, a.text-info:hover { color: #31b0d5 !important; } .text-warning { color: #f0ad4e !important; } a.text-warning:focus, a.text-warning:hover { color: #ec971f !important; } .text-danger { color: #d9534f !important; } a.text-danger:focus, a.text-danger:hover { color: #c9302c !important; } .text-gray-dark { color: #292b2c !important; } a.text-gray-dark:focus, a.text-gray-dark:hover { color: #101112 !important; } .text-hide { font: 0/0 a; color: transparent; text-shadow: none; background-color: transparent; border: 0; } .invisible { visibility: hidden !important; } .hidden-xs-up { display: none !important; } @media (max-width: 575px) { .hidden-xs-down { display: none !important; } } @media (min-width: 576px) { .hidden-sm-up { display: none !important; } } @media (max-width: 767px) { .hidden-sm-down { display: none !important; } } @media (min-width: 768px) { .hidden-md-up { display: none !important; } } @media (max-width: 991px) { .hidden-md-down { display: none !important; } } @media (min-width: 992px) { .hidden-lg-up { display: none !important; } } @media (max-width: 1199px) { .hidden-lg-down { display: none !important; } } @media (min-width: 1200px) { .hidden-xl-up { display: none !important; } } .hidden-xl-down { display: none !important; } .visible-print-block { display: none !important; } @media print { .visible-print-block { display: block !important; } } .visible-print-inline { display: none !important; } @media print { .visible-print-inline { display: inline !important; } } .visible-print-inline-block { display: none !important; } @media print { .visible-print-inline-block { display: inline-block !important; } } @media print { .hidden-print { display: none !important; } } btn-primary { color: #fff; background-color: #000000; border-color: #000000; } /* This is to stop CSS preprocessor, such as Sass, Less, or Stylus, from downloading the bootstrap map file. */ /*# sourceMappingURL= */
Sikilabs/sikilabs
static/css/bootstrap.css
CSS
mit
191,925
[ 30522, 1013, 1008, 999, 1008, 6879, 6494, 2361, 1058, 2549, 1012, 1014, 1012, 1014, 1011, 6541, 1012, 1020, 1006, 16770, 1024, 1013, 1013, 2131, 27927, 20528, 2361, 1012, 4012, 1007, 1008, 9385, 2249, 1011, 2418, 1996, 6879, 6494, 2361, 6...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<form action="action.php" method="post" target="postframe"> <table width="100%" class="table"> <colgroup> <col width="200" /> <col /> </colgroup> <tr class="tableheader"><td colspan="2">{LANG[TITLE_GALLERY_ADD]}</td></tr> {if SET_GALLERY_SUBGALS}<tr> <td>{LANG[CREATEIN]}:</td> <td><select name="parent" onchange="refresh_parent(this);" id="selectbox"><option value="root" style="font-weight:bold;">{LANG[ROOT]}</option>{if PARENT}<option value=""></option>{/if}{PARENT}</select></td> </tr>{/if} {if SET_SECTIONS}<tr id="row_section"> <td>{LANG[SECTION]}:<br /><small>({LANG[CTRLMULTI]})</small></td> <td><select name="secid[]" id="seclist" multiple="multiple">{SECTIONS(SECID)}</select></td> </tr>{/if} <tr> <td>{LANG[TITLE]}:</td> <td><input type="text" name="title" value="{TITLE}" class="input" maxlength="255" size="100" style="width:400px;" /></td> </tr> <tr> <td>{LANG[DESCRIPTION]}: <small>({LANG[OPTIONAL]})</small></td> <td><textarea name="description" cols="100" rows="8" style="width:98%;">{DESCRIPTION}</textarea></td> </tr> <tr id="row_password"> <td>{LANG[PASSWORD]}: <small>({LANG[OPTIONAL]})</small></td> <td><input type="text" name="password" value="{PASSWORD}" class="input" size="30" style="width:150px;" /></td> </tr> <tr> <td>{LANG[TAGS]}:<br /><small>({LANG[OPTIONAL]}, {LANG[TAGSINFO]})</small></td> <td><input type="text" name="tags" value="{TAGS}" size="30" class="input" style="width:400px;" /><div id="taglist" class="taglist"></div></td> </tr> <tr> <td>{LANG[META_DESCRIPTION]}: <small>({LANG[OPTIONAL]})</small></td> <td><textarea name="meta_description" rows="2" style="width:98%;">{META_DESCRIPTION}</textarea></td> </tr> {if MODULE_PRODUCTS}<tr> <td>{LANG[LINKPRODUCT]}: <small>({LANG[OPTIONAL]})</small></td> <td><select name="prodid">{PRODUCTS(PRODID)}</select></td> </tr>{/if} </table> <table width="100%" class="table" style="margin:10px 0;"> <tr class="tableheader"><td colspan="2">{LANG[OPTIONS]}</td></tr> <tr> <td> {if SET_GALLERY_SEARCHABLE}<input type="checkbox" name="searchable" id="ip_searchable" value="1"{if SEARCHABLE} checked="checked"{/if} /><label for="ip_searchable"> {LANG[SEARCHABLE]}</label><br />{/if} {if SET_GALLERY_GALCOMS}<input type="checkbox" name="allowcoms" id="ip_allowcoms" value="1"{if ALLOWCOMS} checked="checked"{/if} /><label for="ip_allowcoms"> {LANG[ALLOWCOMS]}</label><br />{/if} <span id="row_restricted"><input type="checkbox" name="restricted" id="ip_restricted" value="1"{if RESTRICTED} checked="checked"{/if} style="vertical-align:middle;" /><label for="ip_restricted"> {LANG[RESTRICTED]}</label><br /></span> {if RIGHT_GALLERY_ENABLE}<input type="checkbox" name="pubnow" id="ip_pubnow" value="1"{if PUBNOW} checked="checked"{/if} /><label for="ip_pubnow"> {LANG[PUBNOW]}</label>{/if} </td> </tr> </table> <table width="100%" class="table"> <tr class="submit"><td colspan="2"><input type="submit" name="apxsubmit" value="{LANG[SUBMIT_ADD]}" accesskey="s" class="button" />{if RIGHT_GALLERY_PADD} <input type="submit" name="submit2" value='{LANG[SUBMIT_ADDPICS]}' class="button" />{/if}</td></tr> </table> <input type="hidden" name="id" value="{ID}" /> <input type="hidden" name="action" value="gallery.add" /> <input type="hidden" name="send" value="1" /> <input type="hidden" name="updateparent" value="{UPDATEPARENT}" /> <input type="hidden" name="sectoken" value="{SECTOKEN}" /> {if !SET_GALLERY_SUBGALS}<input type="hidden" name="parent" value="root" />{/if} </form> <script type="text/javascript" src="../lib/yui/connection/connection-min.js"></script> <script type="text/javascript" src="../lib/yui/datasource/datasource-min.js"></script> <script type="text/javascript" src="../lib/yui/autocomplete/autocomplete-min.js"></script> <script type="text/javascript" src="../lib/javascript/tagsuggest.js"></script> <script type="text/javascript" src="../lib/javascript/objecttoolbox.js"></script> <script type="text/javascript"> function refresh_parent(obj) { sec=getobject('row_section'); pwd=getobject('row_password'); restr=getobject('row_restricted'); if ( obj.selectedIndex<=1 ) { if ( sec!=null ) sec.style.display=''; if ( pwd!=null ) pwd.style.display=''; if ( restr!=null ) restr.style.display=''; } else { if ( sec!=null ) sec.style.display='none'; if ( pwd!=null ) pwd.style.display='none'; if ( restr!=null ) restr.style.display='none'; } } sel=getobject('selectbox'); if ( sel!=null ) refresh_parent(sel); yEvent.onDOMReady(function() { new TagSuggest(document.forms[0].tags, yDom.get('taglist'), 200); {if RIGHT_PRODUCTS_ADD}new ObjectToolbox(document.forms[0].prodid, 'products.add');{/if} }); </script>
White4Shadow/open-apexx
src/modules/gallery/admin/add.html
HTML
lgpl-3.0
4,630
[ 30522, 1026, 2433, 2895, 1027, 1000, 2895, 1012, 25718, 1000, 4118, 1027, 1000, 2695, 1000, 4539, 1027, 1000, 2695, 15643, 1000, 1028, 1026, 2795, 9381, 1027, 1000, 2531, 1003, 1000, 2465, 1027, 1000, 2795, 1000, 1028, 1026, 8902, 17058, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
#include "base/testing.h" #include <iostream> GTEST_API_ int main(int argc, char** argv) { std::cout << "Running main() from testing_main.cc\n"; InitTest(&argc, &argv); return RUN_ALL_TESTS(); }
imos/gbase
src/base/testing_main.cc
C++
mit
203
[ 30522, 1001, 2421, 1000, 2918, 1013, 5604, 1012, 1044, 1000, 1001, 2421, 1026, 16380, 25379, 1028, 14181, 4355, 1035, 17928, 1035, 20014, 2364, 1006, 20014, 12098, 18195, 1010, 25869, 1008, 1008, 12098, 2290, 2615, 1007, 1063, 2358, 2094, 1...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<?php namespace App\Test\Fixture; use Cake\TestSuite\Fixture\TestFixture; /** * ParametersFixture * */ class ParametersFixture extends TestFixture { /** * Fields * * @var array */ // @codingStandardsIgnoreStart public $fields = [ 'id' => ['type' => 'integer', 'length' => 11, 'unsigned' => false, 'null' => false, 'default' => null, 'comment' => '', 'autoIncrement' => true, 'precision' => null], 'name' => ['type' => 'string', 'length' => 50, 'null' => false, 'default' => null, 'collate' => 'latin1_spanish_ci', 'comment' => '', 'precision' => null, 'fixed' => null], 'value' => ['type' => 'text', 'length' => null, 'null' => false, 'default' => null, 'collate' => 'latin1_spanish_ci', 'comment' => '', 'precision' => null], '_constraints' => [ 'primary' => ['type' => 'primary', 'columns' => ['id'], 'length' => []], ], '_options' => [ 'engine' => 'InnoDB', 'collation' => 'latin1_spanish_ci' ], ]; // @codingStandardsIgnoreEnd /** * Records * * @var array */ public $records = [ [ 'id' => 1, 'name' => 'Lorem ipsum dolor sit amet', 'value' => 'Lorem ipsum dolor sit amet, aliquet feugiat. Convallis morbi fringilla gravida, phasellus feugiat dapibus velit nunc, pulvinar eget sollicitudin venenatis cum nullam, vivamus ut a sed, mollitia lectus. Nulla vestibulum massa neque ut et, id hendrerit sit, feugiat in taciti enim proin nibh, tempor dignissim, rhoncus duis vestibulum nunc mattis convallis.' ], ]; }
jimolina/bakeangular
tests/Fixture/ParametersFixture.php
PHP
mit
1,636
[ 30522, 1026, 1029, 25718, 3415, 15327, 10439, 1032, 3231, 1032, 15083, 1025, 2224, 9850, 1032, 5852, 14663, 2063, 1032, 15083, 1032, 3231, 8873, 18413, 5397, 1025, 1013, 1008, 1008, 1008, 11709, 8873, 18413, 5397, 1008, 1008, 1013, 2465, 11...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* * A Command & Conquer: Renegade SSGM Plugin, containing all the single player mission scripts * Copyright(C) 2017 Neijwiert * * 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/>. */ #include "General.h" #include "M01_Nod_GuardTower_Tailgun_JDG.h" // This script is never used void M01_Nod_GuardTower_Tailgun_JDG::Created(GameObject *obj) { ActionParamsStruct params; params.Set_Basic(this, 100.0f, 17); Vector3 pos = Commands->Get_Position(obj); GameObject *starObj = Commands->Get_A_Star(pos); params.Set_Attack(starObj, 30.0f, 1.0f, true); Commands->Action_Attack(obj, params); } ScriptRegistrant<M01_Nod_GuardTower_Tailgun_JDG> M01_Nod_GuardTower_Tailgun_JDGRegistrant("M01_Nod_GuardTower_Tailgun_JDG", "");
Neijwiert/C-C-Renegade-Mission-Scripts
Source/Single Player Scripts/M01_Nod_GuardTower_Tailgun_JDG.cpp
C++
gpl-3.0
1,307
[ 30522, 1013, 1008, 1008, 1037, 3094, 1004, 16152, 1024, 28463, 7020, 21693, 13354, 2378, 1010, 4820, 2035, 1996, 2309, 2447, 3260, 14546, 1008, 9385, 1006, 1039, 1007, 2418, 11265, 28418, 9148, 8743, 1008, 1008, 2023, 2565, 2003, 2489, 4007...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
var Typeset = require("typeset"); module.exports = function typeset(req, res, next) { var send = res.send; res.send = function(string) { var html = string instanceof Buffer ? string.toString() : string; html = Typeset(html, { disable: ["hyphenate"] }); send.call(this, html); }; next(); };
davidmerfield/Blot-core
app/brochure/routes/tools/typeset.js
JavaScript
cc0-1.0
315
[ 30522, 13075, 4127, 3388, 1027, 5478, 1006, 1000, 4127, 3388, 1000, 1007, 1025, 11336, 1012, 14338, 1027, 3853, 4127, 3388, 1006, 2128, 4160, 1010, 24501, 1010, 2279, 1007, 1063, 13075, 4604, 1027, 24501, 1012, 4604, 1025, 24501, 1012, 4604...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
require File.expand_path(File.dirname(__FILE__) + '/helpers/speed_grader_common') describe "speed grader submissions" do it_should_behave_like "in-process server selenium tests" before (:each) do stub_kaltura course_with_teacher_logged_in outcome_with_rubric @assignment = @course.assignments.create(:name => 'assignment with rubric', :points_possible => 10) @association = @rubric.associate_with(@assignment, @course, :purpose => 'grading') end context "as a teacher" do it "should display submission of first student and then second student" do student_submission #create initial data for second student @student_2 = User.create!(:name => 'student 2') @student_2.register @student_2.pseudonyms.create!(:unique_id => 'student2@example.com', :password => 'qwerty', :password_confirmation => 'qwerty') @course.enroll_user(@student_2, "StudentEnrollment", :enrollment_state => 'active') @submission_2 = @assignment.submit_homework(@student_2, :body => 'second student submission text') get "/courses/#{@course.id}/gradebook/speed_grader?assignment_id=#{@assignment.id}#%7B%22student_id%22%3A#{@submission.student.id}%7D" keep_trying_until { f('#speedgrader_iframe') } #check for assignment title f('#assignment_url').should include_text(@assignment.title) #check for assignment text in speed grader iframe def check_first_student f('#combo_box_container .ui-selectmenu-item-header').should include_text(@student.name) in_frame 'speedgrader_iframe' do f('#main').should include_text(@submission.body) end end def check_second_student f('#combo_box_container .ui-selectmenu-item-header').should include_text(@student_2.name) in_frame 'speedgrader_iframe' do f('#main').should include_text(@submission_2.body) end end if f('#combo_box_container .ui-selectmenu-item-header').text.include?(@student_2.name) check_second_student f('#gradebook_header .next').click wait_for_ajax_requests check_first_student else check_first_student f('#gradebook_header .next').click wait_for_ajax_requests check_second_student end end it "should not error if there are no submissions" do student_in_course get "/courses/#{@course.id}/gradebook/speed_grader?assignment_id=#{@assignment.id}" wait_for_ajax_requests driver.execute_script("return INST.errorCount").should == 0 end it "should have a submission_history after a submitting a comment" do # a student without a submission @student_2 = User.create!(:name => 'student 2') @student_2.register @student_2.pseudonyms.create!(:unique_id => 'student2@example.com', :password => 'qwerty', :password_confirmation => 'qwerty') @course.enroll_user(@student_2, "StudentEnrollment", :enrollment_state => 'active') get "/courses/#{@course.id}/gradebook/speed_grader?assignment_id=#{@assignment.id}" wait_for_ajax_requests #add comment f('#add_a_comment > textarea').send_keys('grader comment') submit_form('#add_a_comment') keep_trying_until { f('#comments > .comment').should be_displayed } # the ajax from that add comment form comes back without a submission_history, the js should mimic it. driver.execute_script('return jsonData.studentsWithSubmissions[0].submission.submission_history.length').should == 1 end it "should display submission late notice message" do @assignment.due_at = Time.now - 2.days @assignment.save! student_submission get "/courses/#{@course.id}/gradebook/speed_grader?assignment_id=#{@assignment.id}" keep_trying_until { f('#speedgrader_iframe') } f('#submission_late_notice').should be_displayed end it "should not display a late message if an assignment has been overridden" do @assignment.update_attribute(:due_at, Time.now - 2.days) override = @assignment.assignment_overrides.build override.due_at = Time.now + 2.days override.due_at_overridden = true override.set = @course.course_sections.first override.save! student_submission get "/courses/#{@course.id}/gradebook/speed_grader?assignment_id=#{@assignment.id}" keep_trying_until { f('#speedgrader_iframe') } f('#submission_late_notice').should_not be_displayed end it "should display no submission message if student does not make a submission" do @student = user_with_pseudonym(:active_user => true, :username => 'student@example.com', :password => 'qwerty') @course.enroll_user(@student, "StudentEnrollment", :enrollment_state => 'active') get "/courses/#{@course.id}/gradebook/speed_grader?assignment_id=#{@assignment.id}" keep_trying_until do f('#submissions_container').should include_text(I18n.t('headers.no_submission', "This student does not have a submission for this assignment")) fj('#this_student_does_not_have_a_submission').should be_displayed end end it "should handle versions correctly" do submission1 = student_submission(:username => "student1@example.com", :body => 'first student, first version') submission2 = student_submission(:username => "student2@example.com", :body => 'second student') submission3 = student_submission(:username => "student3@example.com", :body => 'third student') # This is "no submissions" guy submission3.delete submission1.submitted_at = 10.minutes.from_now submission1.body = 'first student, second version' submission1.with_versioning(:explicit => true) { submission1.save } get "/courses/#{@course.id}/gradebook/speed_grader?assignment_id=#{@assignment.id}" wait_for_ajaximations # The first user should have multiple submissions. We want to make sure we go through the first student # because the original bug was caused by a user with multiple versions putting data on the page that # was carried through to other students, ones with only 1 version. f('#submission_to_view').find_elements(:css, 'option').length.should == 2 in_frame 'speedgrader_iframe' do f('#content').should include_text('first student, second version') end click_option('#submission_to_view', '0', :value) wait_for_ajaximations in_frame 'speedgrader_iframe' do wait_for_ajaximations f('#content').should include_text('first student, first version') end f('#gradebook_header .next').click wait_for_ajaximations # The second user just has one, and grading the user shouldn't trigger a page error. # (In the original bug, it would trigger a change on the select box for choosing submission versions, # which had another student's data in it, so it would try to load a version that didn't exist.) f('#submission_to_view').find_elements(:css, 'option').length.should == 1 f('#grade_container').find_element(:css, 'input').send_keys("5\n") wait_for_ajaximations in_frame 'speedgrader_iframe' do f('#content').should include_text('second student') end submission2.reload.score.should == 5 f('#gradebook_header .next').click wait_for_ajaximations f('#this_student_does_not_have_a_submission').should be_displayed end it "should leave the full rubric open when switching submissions" do student_submission(:username => "student1@example.com") student_submission(:username => "student2@example.com") get "/courses/#{@course.id}/gradebook/speed_grader?assignment_id=#{@assignment.id}" wait_for_ajaximations keep_trying_until { f('.toggle_full_rubric').should be_displayed } f('.toggle_full_rubric').click wait_for_ajaximations rubric = f('#rubric_full') rubric.should be_displayed first_criterion = rubric.find_element(:id, "criterion_#{@rubric.criteria[0][:id]}") first_criterion.find_element(:css, '.ratings .edge_rating').click second_criterion = rubric.find_element(:id, "criterion_#{@rubric.criteria[1][:id]}") second_criterion.find_element(:css, '.ratings .edge_rating').click rubric.find_element(:css, '.rubric_total').should include_text('8') f('#rubric_full .save_rubric_button').click wait_for_ajaximations f('.toggle_full_rubric').click wait_for_ajaximations f("#criterion_#{@rubric.criteria[0][:id]} input.criterion_points").should have_attribute("value", "3") f("#criterion_#{@rubric.criteria[1][:id]} input.criterion_points").should have_attribute("value", "5") f('#gradebook_header .next').click wait_for_ajaximations f('#rubric_full').should be_displayed f("#criterion_#{@rubric.criteria[0][:id]} input.criterion_points").should have_attribute("value", "") f("#criterion_#{@rubric.criteria[1][:id]} input.criterion_points").should have_attribute("value", "") f('#gradebook_header .prev').click wait_for_ajaximations f('#rubric_full').should be_displayed f("#criterion_#{@rubric.criteria[0][:id]} input.criterion_points").should have_attribute("value", "3") f("#criterion_#{@rubric.criteria[1][:id]} input.criterion_points").should have_attribute("value", "5") end it "should highlight submitted assignments and not non-submitted assignments for students" do pending('upgrade') student_submission create_and_enroll_students(1) get "/courses/#{@course.id}/gradebook/speed_grader?assignment_id=#{@assignment.id}" keep_trying_until { f('#speedgrader_iframe').should be_displayed } #check for assignment title f('#assignment_url').should include_text(@assignment.title) ff("#students_selectmenu-menu li")[0].should have_class("not_submitted") ff("#students_selectmenu-menu li")[1].should have_class("not_graded") end it "should display image submission in browser" do filename, fullpath, data = get_file("graded.png") create_and_enroll_students(1) @assignment.submission_types ='online_upload' @assignment.save! add_attachment_student_assignment(filename, @students[0], fullpath) get "/courses/#{@course.id}/gradebook/speed_grader?assignment_id=#{@assignment.id}" keep_trying_until { f('#speedgrader_iframe').should be_displayed } in_frame("speedgrader_iframe") do #validates the image\attachment is inside the iframe as expected f(".decoded").attribute("src").should include_text("download") end end it "should successfully download attachments" do filename, fullpath, data = get_file("testfile1.txt") create_and_enroll_students(1) @assignment.submission_types ='online_upload' @assignment.save! add_attachment_student_assignment(filename, @students[0], fullpath) get "/courses/#{@course.id}/gradebook/speed_grader?assignment_id=#{@assignment.id}" keep_trying_until { f('#speedgrader_iframe').should be_displayed } f(".submission-file-download").click #this assertion verifies the attachment was opened since its a .txt it just renders in the browser keep_trying_until { f("body pre").should include_text("63f46f1c") } end context "turnitin" do before(:each) do @assignment.turnitin_enabled = true @assignment.save! end it "should display a pending icon if submission status is pending" do student_submission set_turnitin_asset(@submission, {:status => 'pending'}) get "/courses/#{@course.id}/gradebook/speed_grader?assignment_id=#{@assignment.id}" wait_for_ajaximations turnitin_icon = f('#grade_container .submission_pending') turnitin_icon.should_not be_nil turnitin_icon.click wait_for_ajaximations f('#grade_container .turnitin_info').should_not be_nil end it "should display a score if submission has a similarity score" do student_submission set_turnitin_asset(@submission, {:similarity_score => 96, :state => 'failure', :status => 'scored'}) get "/courses/#{@course.id}/gradebook/speed_grader?assignment_id=#{@assignment.id}" wait_for_ajaximations f('#grade_container .turnitin_similarity_score').should include_text "96%" end it "should display an error icon if submission status is error" do student_submission set_turnitin_asset(@submission, {:status => 'error'}) get "/courses/#{@course.id}/gradebook/speed_grader?assignment_id=#{@assignment.id}" wait_for_ajaximations turnitin_icon = f('#grade_container .submission_error') turnitin_icon.should_not be_nil turnitin_icon.click wait_for_ajaximations f('#grade_container .turnitin_info').should_not be_nil f('#grade_container .turnitin_resubmit_button').should_not be_nil end it "should show turnitin score for attached files" do @user = user_with_pseudonym({:active_user => true, :username => 'student@example.com', :password => 'qwerty'}) attachment1 = @user.attachments.new :filename => "homework1.doc" attachment1.content_type = "application/msword" attachment1.size = 10093 attachment1.save! attachment2 = @user.attachments.new :filename => "homework2.doc" attachment2.content_type = "application/msword" attachment2.size = 10093 attachment2.save! student_submission({:user => @user, :submission_type => :online_upload, :attachments => [attachment1, attachment2]}) set_turnitin_asset(attachment1, {:similarity_score => 96, :state => 'failure', :status => 'scored'}) set_turnitin_asset(attachment2, {:status => 'pending'}) get "/courses/#{@course.id}/gradebook/speed_grader?assignment_id=#{@assignment.id}" wait_for_ajaximations ff('#submission_files_list .turnitin_similarity_score').map(&:text).join.should match /96%/ f('#submission_files_list .submission_pending').should_not be_nil end it "should successfully schedule resubmit when button is clicked" do student_submission set_turnitin_asset(@submission, {:status => 'error'}) get "/courses/#{@course.id}/gradebook/speed_grader?assignment_id=#{@assignment.id}" wait_for_ajaximations f('#grade_container .submission_error').click wait_for_ajaximations expect_new_page_load { f('#grade_container .turnitin_resubmit_button').click} wait_for_ajaximations Delayed::Job.find_by_tag('Submission#submit_to_turnitin').should_not be_nil f('#grade_container .submission_pending').should_not be_nil end end end end
wimemx/Canvas
spec/selenium/teacher_speed_grader_submission_spec.rb
Ruby
agpl-3.0
14,418
[ 30522, 5478, 5371, 1012, 7818, 1035, 4130, 1006, 5371, 1012, 16101, 18442, 1006, 1035, 1035, 5371, 1035, 1035, 1007, 1009, 1005, 1013, 2393, 2545, 1013, 3177, 1035, 3694, 2099, 1035, 2691, 1005, 1007, 6235, 1000, 3177, 3694, 2099, 27842, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<template name="resources"> <div class="container-fluid"> <div class="row" style="position:relative;"> <img class="img-responsive resource-image" style="min-height:200px;" src="/img/resource home page.jpeg"> <h2 class="resource-title" style="position:absolute;top:50px;left:75px;">Security Resource<br/>Center</h2> </div> </div> <div class="container"> <h3>Read More About Us</h3> <p class="lead">Century Security has been a valued partner of our company for approximately 10 years. Their consistent high level of service is what separates them from the competition. They have provided us security services for our events nationwide, large and small. This is a testament to the professionalism of their event managers and leadership. Cory Keith, Manager – Meeting and Event Security, McDonald’s Corporation</p> <blockquote> <p>At both the PGA Merchandise Show in Orlando and ISC West in Las Vegas, Century is one of the most responsive and accommodating firms I have worked with. I always feel confident that any situation or request will be given the proper attention and seen through to the end.</p> <footer>Jason Cedrone<br/><cite title="Source Title">Senior Operations Manager, Reed Exhibitions</cite></footer> </blockquote> <hr/> <blockquote> <p>Again thank you to you and your team for an exceptional security personnel, never have I seen such professional[ism] from a security team. Again thank you and we look forward to continuing working with you in the future.</p> <footer>Dania Echeverri<br/><cite title="Source Title">Universal Music Group, 2009 Latin Grammy Awards Universal After Party</cite></footer> </blockquote> <hr/> <blockquote> <p>Having used Century Security for several years on our American College of Cardiology annual meeting and expo (in addition to having worked with them prior to joining ACC), I’ve always appreciated the high level of professionalism and dedication to our account. Century’s event managers always seem to pride themselves on running a tight ship and being responsive to the needs of all the players on our large event management staff – including floor managers, general contractor, and other key vendors. The company’s management really becomes part of our “team” in advance of the meeting and on-site. Century knows what’s needed to ensure a safe and secure meeting for all participants, and I’ve enjoyed working with them.</p> <footer>Kent Riffert<br/><cite title="Source Title">Associate Director – Exposition Logistics, American College of Cardiology</cite></footer> </blockquote> <hr/> <blockquote> <p>We did receive excellent feedback on the service. We look forward to more and future cooperative venture.</p> <footer>John Engbeck<br/><cite title="Source Title">American Private Security, Inc., Andre Agassi Book Signing</cite></footer> </blockquote> </div> </template>
sscaff1/centurytradeshow
client/templates/pages/resources.html
HTML
gpl-2.0
2,981
[ 30522, 1026, 23561, 2171, 1027, 1000, 4219, 1000, 1028, 1026, 4487, 2615, 2465, 1027, 1000, 11661, 1011, 8331, 1000, 1028, 1026, 4487, 2615, 2465, 1027, 1000, 5216, 1000, 2806, 1027, 1000, 2597, 1024, 5816, 1025, 1000, 1028, 1026, 10047, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* * Forge SDK * * The Forge Platform contains an expanding collection of web service components that can be used with Autodesk cloud-based products or your own technologies. Take advantage of Autodesk’s expertise in design and engineering. * * OpenAPI spec version: 0.1.0 * Contact: forge.help@autodesk.com * Generated by: https://github.com/swagger-api/swagger-codegen.git * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace Autodesk.Forge.Model { /// <summary> /// RelRefMeta /// </summary> [DataContract] public partial class RelRefMeta : IEquatable<RelRefMeta> { /// <summary> /// Gets or Sets RefType /// </summary> [JsonConverter(typeof(StringEnumConverter))] public enum RefTypeEnum { /// <summary> /// Enum Derived for "derived" /// </summary> [EnumMember(Value = "derived")] Derived, /// <summary> /// Enum Dependencies for "dependencies" /// </summary> [EnumMember(Value = "dependencies")] Dependencies, /// <summary> /// Enum Auxiliary for "auxiliary" /// </summary> [EnumMember(Value = "auxiliary")] Auxiliary, /// <summary> /// Enum Xrefs for "xrefs" /// </summary> [EnumMember(Value = "xrefs")] Xrefs } /// <summary> /// describes the direction of the reference relative to the resource the refs are queried for /// </summary> /// <value>describes the direction of the reference relative to the resource the refs are queried for</value> [JsonConverter(typeof(StringEnumConverter))] public enum DirectionEnum { /// <summary> /// Enum From for "from" /// </summary> [EnumMember(Value = "from")] From, /// <summary> /// Enum To for "to" /// </summary> [EnumMember(Value = "to")] To } /// <summary> /// Gets or Sets FromType /// </summary> [JsonConverter(typeof(StringEnumConverter))] public enum FromTypeEnum { /// <summary> /// Enum Folders for "folders" /// </summary> [EnumMember(Value = "folders")] Folders, /// <summary> /// Enum Items for "items" /// </summary> [EnumMember(Value = "items")] Items, /// <summary> /// Enum Versions for "versions" /// </summary> [EnumMember(Value = "versions")] Versions } /// <summary> /// Gets or Sets ToType /// </summary> [JsonConverter(typeof(StringEnumConverter))] public enum ToTypeEnum { /// <summary> /// Enum Folders for "folders" /// </summary> [EnumMember(Value = "folders")] Folders, /// <summary> /// Enum Items for "items" /// </summary> [EnumMember(Value = "items")] Items, /// <summary> /// Enum Versions for "versions" /// </summary> [EnumMember(Value = "versions")] Versions } /// <summary> /// Gets or Sets RefType /// </summary> [DataMember(Name="refType", EmitDefaultValue=false)] public RefTypeEnum? RefType { get; set; } /// <summary> /// describes the direction of the reference relative to the resource the refs are queried for /// </summary> /// <value>describes the direction of the reference relative to the resource the refs are queried for</value> [DataMember(Name="direction", EmitDefaultValue=false)] public DirectionEnum? Direction { get; set; } /// <summary> /// Gets or Sets FromType /// </summary> [DataMember(Name="fromType", EmitDefaultValue=false)] public FromTypeEnum? FromType { get; set; } /// <summary> /// Gets or Sets ToType /// </summary> [DataMember(Name="toType", EmitDefaultValue=false)] public ToTypeEnum? ToType { get; set; } /// <summary> /// Initializes a new instance of the <see cref="RelRefMeta" /> class. /// </summary> [JsonConstructorAttribute] protected RelRefMeta() { } /// <summary> /// Initializes a new instance of the <see cref="RelRefMeta" /> class. /// </summary> /// <param name="RefType">RefType (required).</param> /// <param name="Direction">describes the direction of the reference relative to the resource the refs are queried for (required).</param> /// <param name="FromId">FromId (required).</param> /// <param name="FromType">FromType (required).</param> /// <param name="ToId">ToId (required).</param> /// <param name="ToType">ToType (required).</param> /// <param name="Extension">Extension (required).</param> public RelRefMeta(RefTypeEnum? RefType = null, DirectionEnum? Direction = null, string FromId = null, FromTypeEnum? FromType = null, string ToId = null, ToTypeEnum? ToType = null, BaseAttributesExtensionObject Extension = null) { // to ensure "RefType" is required (not null) if (RefType == null) { throw new InvalidDataException("RefType is a required property for RelRefMeta and cannot be null"); } else { this.RefType = RefType; } // to ensure "Direction" is required (not null) if (Direction == null) { throw new InvalidDataException("Direction is a required property for RelRefMeta and cannot be null"); } else { this.Direction = Direction; } // to ensure "FromId" is required (not null) if (FromId == null) { throw new InvalidDataException("FromId is a required property for RelRefMeta and cannot be null"); } else { this.FromId = FromId; } // to ensure "FromType" is required (not null) if (FromType == null) { throw new InvalidDataException("FromType is a required property for RelRefMeta and cannot be null"); } else { this.FromType = FromType; } // to ensure "ToId" is required (not null) if (ToId == null) { throw new InvalidDataException("ToId is a required property for RelRefMeta and cannot be null"); } else { this.ToId = ToId; } // to ensure "ToType" is required (not null) if (ToType == null) { throw new InvalidDataException("ToType is a required property for RelRefMeta and cannot be null"); } else { this.ToType = ToType; } // to ensure "Extension" is required (not null) if (Extension == null) { throw new InvalidDataException("Extension is a required property for RelRefMeta and cannot be null"); } else { this.Extension = Extension; } } /// <summary> /// Gets or Sets FromId /// </summary> [DataMember(Name="fromId", EmitDefaultValue=false)] public string FromId { get; set; } /// <summary> /// Gets or Sets ToId /// </summary> [DataMember(Name="toId", EmitDefaultValue=false)] public string ToId { get; set; } /// <summary> /// Gets or Sets Extension /// </summary> [DataMember(Name="extension", EmitDefaultValue=false)] public BaseAttributesExtensionObject Extension { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class RelRefMeta {\n"); sb.Append(" RefType: ").Append(RefType).Append("\n"); sb.Append(" Direction: ").Append(Direction).Append("\n"); sb.Append(" FromId: ").Append(FromId).Append("\n"); sb.Append(" FromType: ").Append(FromType).Append("\n"); sb.Append(" ToId: ").Append(ToId).Append("\n"); sb.Append(" ToType: ").Append(ToType).Append("\n"); sb.Append(" Extension: ").Append(Extension).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as RelRefMeta); } /// <summary> /// Returns true if RelRefMeta instances are equal /// </summary> /// <param name="other">Instance of RelRefMeta to be compared</param> /// <returns>Boolean</returns> public bool Equals(RelRefMeta other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.RefType == other.RefType || this.RefType != null && this.RefType.Equals(other.RefType) ) && ( this.Direction == other.Direction || this.Direction != null && this.Direction.Equals(other.Direction) ) && ( this.FromId == other.FromId || this.FromId != null && this.FromId.Equals(other.FromId) ) && ( this.FromType == other.FromType || this.FromType != null && this.FromType.Equals(other.FromType) ) && ( this.ToId == other.ToId || this.ToId != null && this.ToId.Equals(other.ToId) ) && ( this.ToType == other.ToType || this.ToType != null && this.ToType.Equals(other.ToType) ) && ( this.Extension == other.Extension || this.Extension != null && this.Extension.Equals(other.Extension) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.RefType != null) hash = hash * 59 + this.RefType.GetHashCode(); if (this.Direction != null) hash = hash * 59 + this.Direction.GetHashCode(); if (this.FromId != null) hash = hash * 59 + this.FromId.GetHashCode(); if (this.FromType != null) hash = hash * 59 + this.FromType.GetHashCode(); if (this.ToId != null) hash = hash * 59 + this.ToId.GetHashCode(); if (this.ToType != null) hash = hash * 59 + this.ToType.GetHashCode(); if (this.Extension != null) hash = hash * 59 + this.Extension.GetHashCode(); return hash; } } } }
Autodesk-Forge/forge-api-dotnet-client
src/Autodesk.Forge/Model/RelRefMeta.cs
C#
apache-2.0
13,760
[ 30522, 1013, 1008, 1008, 15681, 17371, 2243, 1008, 1008, 1996, 15681, 4132, 3397, 2019, 9186, 3074, 1997, 4773, 2326, 6177, 2008, 2064, 2022, 2109, 2007, 8285, 6155, 2243, 6112, 1011, 2241, 3688, 2030, 2115, 2219, 6786, 1012, 2202, 5056, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
using OWDARO.BLL.MediaBLL; using OWDARO.Settings; using OWDARO.Util; using System; using System.Threading.Tasks; using System.Web.UI; namespace OWDARO.UI.UserControls.Components.Others { public partial class ContactUsDetailsComponent : System.Web.UI.UserControl { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { this.Page.RegisterAsyncTask(new PageAsyncTask(async cancellationToken => { await LoadData(); })); } } private async Task LoadData() { var postQuery = await PostsBL.GetObjectByIDAsync(DataParser.IntParse(KeywordsHelper.GetKeywordValue("ContactUsPostID"))); if (postQuery != null) { string locale = postQuery.Locale; string direction = LanguageHelper.GetLocaleDirection(locale); TitleH1.Style.Add("direction", direction); TitleLiteral.Text = postQuery.Title; PostEmbedComponent1.PostContent = postQuery.PostContent; } } } }
owdaro/OFrameCMS-WebForms
UI/UserControls/Components/Others/ContactUsDetailsComponent.ascx.cs
C#
gpl-3.0
1,159
[ 30522, 2478, 27593, 7662, 2080, 1012, 1038, 3363, 1012, 2865, 16558, 2140, 1025, 2478, 27593, 7662, 2080, 1012, 10906, 1025, 2478, 27593, 7662, 2080, 1012, 21183, 4014, 1025, 2478, 2291, 1025, 2478, 2291, 1012, 11689, 2075, 1012, 8518, 1025...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/******************************************************************************* * Copyright (C) 2016 Kwaku Twumasi-Afriyie <kwaku.twumasi@quakearts.com>. * 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: * Kwaku Twumasi-Afriyie <kwaku.twumasi@quakearts.com> - initial API and implementation ******************************************************************************/ package com.quakearts.webapp.facelets.bootstrap.renderers; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.faces.component.UIColumn; import javax.faces.component.UIComponent; import javax.faces.component.UIData; import javax.faces.context.FacesContext; import javax.faces.context.ResponseWriter; import com.quakearts.webapp.facelets.bootstrap.components.BootTable; import com.quakearts.webapp.facelets.bootstrap.renderkit.Attribute; import com.quakearts.webapp.facelets.bootstrap.renderkit.AttributeManager; import com.quakearts.webapp.facelets.bootstrap.renderkit.html_basic.HtmlBasicRenderer; import com.quakearts.webapp.facelets.util.UtilityMethods; import static com.quakearts.webapp.facelets.bootstrap.renderkit.RenderKitUtils.*; public class BootTableRenderer extends HtmlBasicRenderer { private static final Attribute[] ATTRIBUTES = AttributeManager.getAttributes(AttributeManager.Key.DATATABLE); @Override public void encodeBegin(FacesContext context, UIComponent component) throws IOException { if (!shouldEncode(component)) { return; } BootTable data = (BootTable) component; data.setRowIndex(-1); ResponseWriter writer = context.getResponseWriter(); writer.startElement("table", component); writer.writeAttribute("id", component.getClientId(context), "id"); String styleClass = data.get("styleClass"); writer.writeAttribute("class","table "+(styleClass !=null?" "+styleClass:""), "styleClass"); renderHTML5DataAttributes(context, component); renderPassThruAttributes(context, writer, component, ATTRIBUTES); writer.writeText("\n", component, null); UIComponent caption = getFacet(component, "caption"); if (caption != null) { String captionClass = data.get("captionClass"); String captionStyle = data.get("captionStyle"); writer.startElement("caption", component); if (captionClass != null) { writer.writeAttribute("class", captionClass, "captionClass"); } if (captionStyle != null) { writer.writeAttribute("style", captionStyle, "captionStyle"); } encodeRecursive(context, caption); writer.endElement("caption"); } UIComponent colGroups = getFacet(component, "colgroups"); if (colGroups != null) { encodeRecursive(context, colGroups); } BootMetaInfo info = getMetaInfo(context, component); UIComponent header = getFacet(component, "header"); if (header != null || info.hasHeaderFacets) { String headerClass = data.get("headerClass"); writer.startElement("thead", component); writer.writeText("\n", component, null); if (header != null) { writer.startElement("tr", header); writer.startElement("th", header); if (headerClass != null) { writer.writeAttribute("class", headerClass, "headerClass"); } if (info.columns.size() > 1) { writer.writeAttribute("colspan", String.valueOf(info.columns.size()), null); } writer.writeAttribute("scope", "colgroup", null); encodeRecursive(context, header); writer.endElement("th"); writer.endElement("tr"); writer.write("\n"); } if (info.hasHeaderFacets) { writer.startElement("tr", component); writer.writeText("\n", component, null); for (UIColumn column : info.columns) { String columnHeaderClass = info.getCurrentHeaderClass(); writer.startElement("th", column); if (columnHeaderClass != null) { writer.writeAttribute("class", columnHeaderClass, "columnHeaderClass"); } else if (headerClass != null) { writer.writeAttribute("class", headerClass, "headerClass"); } writer.writeAttribute("scope", "col", null); UIComponent facet = getFacet(column, "header"); if (facet != null) { encodeRecursive(context, facet); } writer.endElement("th"); writer.writeText("\n", component, null); } writer.endElement("tr"); writer.write("\n"); } writer.endElement("thead"); writer.writeText("\n", component, null); } } @Override public void encodeChildren(FacesContext context, UIComponent component) throws IOException { if (!shouldEncodeChildren(component)) { return; } UIData data = (UIData) component; ResponseWriter writer = context.getResponseWriter(); BootMetaInfo info = getMetaInfo(context, data); if(info.columns.isEmpty()) { writer.startElement("tbody", component); renderEmptyTableRow(writer, component); writer.endElement("tbody"); return; } int processed = 0; int rowIndex = data.getFirst() - 1; int rows = data.getRows(); List<Integer> bodyRows = getBodyRows(context.getExternalContext().getApplicationMap(), data); boolean hasBodyRows = (bodyRows != null && !bodyRows.isEmpty()); boolean wroteTableBody = false; if (!hasBodyRows) { writer.startElement("tbody", component); writer.writeText("\n", component, null); } boolean renderedRow = false; while (true) { if ((rows > 0) && (++processed > rows)) { break; } data.setRowIndex(++rowIndex); if (!data.isRowAvailable()) { break; } if (hasBodyRows && bodyRows.contains(data.getRowIndex())) { if (wroteTableBody) { writer.endElement("tbody"); } writer.startElement("tbody", data); wroteTableBody = true; } writer.startElement("tr", component); if (info.rowClasses.length > 0) { writer.writeAttribute("class", info.getCurrentRowClass(), "rowClasses"); } writer.writeText("\n", component, null); info.newRow(); for (UIColumn column : info.columns) { boolean isRowHeader = Boolean.TRUE.equals(column.getAttributes() .get("rowHeader")); if (isRowHeader) { writer.startElement("th", column); writer.writeAttribute("scope", "row", null); } else { writer.startElement("td", column); } String columnClass = info.getCurrentColumnClass(); if (columnClass != null) { writer.writeAttribute("class", columnClass, "columnClasses"); } for (Iterator<UIComponent> gkids = getChildren(column); gkids .hasNext();) { encodeRecursive(context, gkids.next()); } if (isRowHeader) { writer.endElement("th"); } else { writer.endElement("td"); } writer.writeText("\n", component, null); } writer.endElement("tr"); writer.write("\n"); renderedRow = true; } if(!renderedRow) { renderEmptyTableRow(writer, data); } writer.endElement("tbody"); writer.writeText("\n", component, null); data.setRowIndex(-1); } @Override public void encodeEnd(FacesContext context, UIComponent component) throws IOException { if (!shouldEncode(component)) { return; } ResponseWriter writer = context.getResponseWriter(); BootMetaInfo info = getMetaInfo(context, component); UIComponent footer = getFacet(component, "footer"); if (footer != null || info.hasFooterFacets) { String footerClass = (String) component.getAttributes().get("footerClass"); writer.startElement("tfoot", component); writer.writeText("\n", component, null); if (info.hasFooterFacets) { writer.startElement("tr", component); writer.writeText("\n", component, null); for (UIColumn column : info.columns) { String columnFooterClass = (String) column.getAttributes().get( "footerClass"); writer.startElement("td", column); if (columnFooterClass != null) { writer.writeAttribute("class", columnFooterClass, "columnFooterClass"); } else if (footerClass != null) { writer.writeAttribute("class", footerClass, "footerClass"); } UIComponent facet = getFacet(column, "footer"); if (facet != null) { encodeRecursive(context, facet); } writer.endElement("td"); writer.writeText("\n", component, null); } writer.endElement("tr"); writer.write("\n"); } if (footer != null) { writer.startElement("tr", footer); writer.startElement("td", footer); if (footerClass != null) { writer.writeAttribute("class", footerClass, "footerClass"); } if (info.columns.size() > 1) { writer.writeAttribute("colspan", String.valueOf(info.columns.size()), null); } encodeRecursive(context, footer); writer.endElement("td"); writer.endElement("tr"); writer.write("\n"); } writer.endElement("tfoot"); writer.writeText("\n", component, null); } clearMetaInfo(context, component); ((UIData) component).setRowIndex(-1); writer.endElement("table"); writer.writeText("\n", component, null); } private List<Integer> getBodyRows(Map<String, Object> appMap, UIData data) { List<Integer> result = null; String bodyRows = (String) data.getAttributes().get("bodyrows"); if (bodyRows != null) { String [] rows = UtilityMethods.split(appMap, bodyRows, ","); if (rows != null) { result = new ArrayList<Integer>(rows.length); for (String curRow : rows) { result.add(Integer.valueOf(curRow)); } } } return result; } private void renderEmptyTableRow(final ResponseWriter writer, final UIComponent component) throws IOException { writer.startElement("tr", component); writer.startElement("td", component); writer.endElement("td"); writer.endElement("tr"); } protected BootTableRenderer.BootMetaInfo getMetaInfo(FacesContext context, UIComponent table) { String key = createKey(table); Map<Object, Object> attributes = context.getAttributes(); BootMetaInfo info = (BootMetaInfo) attributes .get(key); if (info == null) { info = new BootMetaInfo(table); attributes.put(key, info); } return info; } protected void clearMetaInfo(FacesContext context, UIComponent table) { context.getAttributes().remove(createKey(table)); } protected String createKey(UIComponent table) { return BootMetaInfo.KEY + '_' + table.hashCode(); } private static class BootMetaInfo { private static final UIColumn PLACE_HOLDER_COLUMN = new UIColumn(); private static final String[] EMPTY_STRING_ARRAY = new String[0]; public static final String KEY = BootMetaInfo.class.getName(); public final String[] rowClasses; public final String[] columnClasses; public final String[] headerClasses; public final List<UIColumn> columns; public final boolean hasHeaderFacets; public final boolean hasFooterFacets; public final int columnCount; public int columnStyleCounter; public int headerStyleCounter; public int rowStyleCounter; public BootMetaInfo(UIComponent table) { rowClasses = getRowClasses(table); columnClasses = getColumnClasses(table); headerClasses = getHeaderClasses(table); columns = getColumns(table); columnCount = columns.size(); hasHeaderFacets = hasFacet("header", columns); hasFooterFacets = hasFacet("footer", columns); } public void newRow() { columnStyleCounter = 0; headerStyleCounter = 0; } public String getCurrentColumnClass() { String style = null; if (columnStyleCounter < columnClasses.length && columnStyleCounter <= columnCount) { style = columnClasses[columnStyleCounter++]; } return ((style != null && style.length() > 0) ? style : null); } public String getCurrentHeaderClass() { String style = null; if (headerStyleCounter < headerClasses.length && headerStyleCounter <= columnCount) { style = headerClasses[headerStyleCounter++]; } return ((style != null && style.length() > 0) ? style : null); } public String getCurrentRowClass() { String style = rowClasses[rowStyleCounter++]; if (rowStyleCounter >= rowClasses.length) { rowStyleCounter = 0; } return style; } private static String[] getColumnClasses(UIComponent table) { String values = ((BootTable) table).get("columnClasses"); if (values == null) { return EMPTY_STRING_ARRAY; } Map<String, Object> appMap = FacesContext.getCurrentInstance() .getExternalContext().getApplicationMap(); return UtilityMethods.split(appMap, values.trim(), ","); } private static String[] getHeaderClasses(UIComponent table) { String values = ((BootTable) table).get("headerClasses"); if (values == null) { return EMPTY_STRING_ARRAY; } Map<String, Object> appMap = FacesContext.getCurrentInstance() .getExternalContext().getApplicationMap(); return UtilityMethods.split(appMap, values.trim(), ","); } private static List<UIColumn> getColumns(UIComponent table) { if (table instanceof UIData) { int childCount = table.getChildCount(); if (childCount > 0) { List<UIColumn> results = new ArrayList<UIColumn>(childCount); for (UIComponent kid : table.getChildren()) { if ((kid instanceof UIColumn) && kid.isRendered()) { results.add((UIColumn) kid); } } return results; } else { return Collections.emptyList(); } } else { int count; Object value = table.getAttributes().get("columns"); if ((value != null) && (value instanceof Integer)) { count = ((Integer) value); } else { count = 2; } if (count < 1) { count = 1; } List<UIColumn> result = new ArrayList<UIColumn>(count); for (int i = 0; i < count; i++) { result.add(PLACE_HOLDER_COLUMN); } return result; } } private static boolean hasFacet(String name, List<UIColumn> columns) { if (!columns.isEmpty()) { for (UIColumn column : columns) { if (column.getFacetCount() > 0) { if (column.getFacets().containsKey(name)) { return true; } } } } return false; } private static String[] getRowClasses(UIComponent table) { String values = ((BootTable) table).get("rowClasses"); if (values == null) { return (EMPTY_STRING_ARRAY); } Map<String, Object> appMap = FacesContext.getCurrentInstance() .getExternalContext().getApplicationMap(); return UtilityMethods.split(appMap, values.trim(), ","); } } }
kwakutwumasi/Quakearts-JSF-Webtools
qa-boot/src/main/java/com/quakearts/webapp/facelets/bootstrap/renderers/BootTableRenderer.java
Java
apache-2.0
15,874
[ 30522, 1013, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 100...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/service_worker/service_worker_storage.h" #include <stdint.h> #include <string> #include <utility> #include "base/files/file_util.h" #include "base/files/scoped_temp_dir.h" #include "base/logging.h" #include "base/macros.h" #include "base/run_loop.h" #include "base/thread_task_runner_handle.h" #include "build/build_config.h" #include "content/browser/browser_thread_impl.h" #include "content/browser/service_worker/embedded_worker_test_helper.h" #include "content/browser/service_worker/service_worker_context_core.h" #include "content/browser/service_worker/service_worker_disk_cache.h" #include "content/browser/service_worker/service_worker_registration.h" #include "content/browser/service_worker/service_worker_version.h" #include "content/common/service_worker/service_worker_status_code.h" #include "content/common/service_worker/service_worker_utils.h" #include "content/public/test/test_browser_thread_bundle.h" #include "ipc/ipc_message.h" #include "net/base/io_buffer.h" #include "net/base/net_errors.h" #include "net/base/test_completion_callback.h" #include "net/http/http_response_headers.h" #include "testing/gtest/include/gtest/gtest.h" using net::IOBuffer; using net::TestCompletionCallback; using net::WrappedIOBuffer; namespace content { namespace { typedef ServiceWorkerDatabase::RegistrationData RegistrationData; typedef ServiceWorkerDatabase::ResourceRecord ResourceRecord; void StatusAndQuitCallback(ServiceWorkerStatusCode* result, const base::Closure& quit_closure, ServiceWorkerStatusCode status) { *result = status; quit_closure.Run(); } void StatusCallback(bool* was_called, ServiceWorkerStatusCode* result, ServiceWorkerStatusCode status) { *was_called = true; *result = status; } ServiceWorkerStorage::StatusCallback MakeStatusCallback( bool* was_called, ServiceWorkerStatusCode* result) { return base::Bind(&StatusCallback, was_called, result); } void FindCallback( bool* was_called, ServiceWorkerStatusCode* result, scoped_refptr<ServiceWorkerRegistration>* found, ServiceWorkerStatusCode status, const scoped_refptr<ServiceWorkerRegistration>& registration) { *was_called = true; *result = status; *found = registration; } ServiceWorkerStorage::FindRegistrationCallback MakeFindCallback( bool* was_called, ServiceWorkerStatusCode* result, scoped_refptr<ServiceWorkerRegistration>* found) { return base::Bind(&FindCallback, was_called, result, found); } void GetAllCallback( bool* was_called, ServiceWorkerStatusCode* result, std::vector<scoped_refptr<ServiceWorkerRegistration>>* all_out, ServiceWorkerStatusCode status, const std::vector<scoped_refptr<ServiceWorkerRegistration>>& all) { *was_called = true; *result = status; *all_out = all; } void GetAllInfosCallback( bool* was_called, ServiceWorkerStatusCode* result, std::vector<ServiceWorkerRegistrationInfo>* all_out, ServiceWorkerStatusCode status, const std::vector<ServiceWorkerRegistrationInfo>& all) { *was_called = true; *result = status; *all_out = all; } ServiceWorkerStorage::GetRegistrationsCallback MakeGetRegistrationsCallback( bool* was_called, ServiceWorkerStatusCode* status, std::vector<scoped_refptr<ServiceWorkerRegistration>>* all) { return base::Bind(&GetAllCallback, was_called, status, all); } ServiceWorkerStorage::GetRegistrationsInfosCallback MakeGetRegistrationsInfosCallback( bool* was_called, ServiceWorkerStatusCode* status, std::vector<ServiceWorkerRegistrationInfo>* all) { return base::Bind(&GetAllInfosCallback, was_called, status, all); } void GetUserDataCallback( bool* was_called, std::string* data_out, ServiceWorkerStatusCode* status_out, const std::string& data, ServiceWorkerStatusCode status) { *was_called = true; *data_out = data; *status_out = status; } void GetUserDataForAllRegistrationsCallback( bool* was_called, std::vector<std::pair<int64_t, std::string>>* data_out, ServiceWorkerStatusCode* status_out, const std::vector<std::pair<int64_t, std::string>>& data, ServiceWorkerStatusCode status) { *was_called = true; *data_out = data; *status_out = status; } int WriteResponse(ServiceWorkerStorage* storage, int64_t id, const std::string& headers, IOBuffer* body, int length) { scoped_ptr<ServiceWorkerResponseWriter> writer = storage->CreateResponseWriter(id); scoped_ptr<net::HttpResponseInfo> info(new net::HttpResponseInfo); info->request_time = base::Time::Now(); info->response_time = base::Time::Now(); info->was_cached = false; info->headers = new net::HttpResponseHeaders(headers); scoped_refptr<HttpResponseInfoIOBuffer> info_buffer = new HttpResponseInfoIOBuffer(info.release()); int rv = 0; { TestCompletionCallback cb; writer->WriteInfo(info_buffer.get(), cb.callback()); rv = cb.WaitForResult(); if (rv < 0) return rv; } { TestCompletionCallback cb; writer->WriteData(body, length, cb.callback()); rv = cb.WaitForResult(); } return rv; } int WriteStringResponse(ServiceWorkerStorage* storage, int64_t id, const std::string& headers, const std::string& body) { scoped_refptr<IOBuffer> body_buffer(new WrappedIOBuffer(body.data())); return WriteResponse(storage, id, headers, body_buffer.get(), body.length()); } int WriteBasicResponse(ServiceWorkerStorage* storage, int64_t id) { const char kHttpHeaders[] = "HTTP/1.0 200 HONKYDORY\0Content-Length: 5\0\0"; const char kHttpBody[] = "Hello"; std::string headers(kHttpHeaders, arraysize(kHttpHeaders)); return WriteStringResponse(storage, id, headers, std::string(kHttpBody)); } int ReadResponseInfo(ServiceWorkerStorage* storage, int64_t id, HttpResponseInfoIOBuffer* info_buffer) { scoped_ptr<ServiceWorkerResponseReader> reader = storage->CreateResponseReader(id); TestCompletionCallback cb; reader->ReadInfo(info_buffer, cb.callback()); return cb.WaitForResult(); } bool VerifyBasicResponse(ServiceWorkerStorage* storage, int64_t id, bool expected_positive_result) { const std::string kExpectedHttpBody("Hello"); scoped_ptr<ServiceWorkerResponseReader> reader = storage->CreateResponseReader(id); scoped_refptr<HttpResponseInfoIOBuffer> info_buffer = new HttpResponseInfoIOBuffer(); int rv = ReadResponseInfo(storage, id, info_buffer.get()); if (expected_positive_result) EXPECT_LT(0, rv); if (rv <= 0) return false; std::string received_body; const int kBigEnough = 512; scoped_refptr<net::IOBuffer> buffer = new IOBuffer(kBigEnough); TestCompletionCallback cb; reader->ReadData(buffer.get(), kBigEnough, cb.callback()); rv = cb.WaitForResult(); EXPECT_EQ(static_cast<int>(kExpectedHttpBody.size()), rv); if (rv <= 0) return false; received_body.assign(buffer->data(), rv); bool status_match = std::string("HONKYDORY") == info_buffer->http_info->headers->GetStatusText(); bool data_match = kExpectedHttpBody == received_body; EXPECT_TRUE(status_match); EXPECT_TRUE(data_match); return status_match && data_match; } int WriteResponseMetadata(ServiceWorkerStorage* storage, int64_t id, const std::string& metadata) { scoped_refptr<IOBuffer> body_buffer(new WrappedIOBuffer(metadata.data())); scoped_ptr<ServiceWorkerResponseMetadataWriter> metadata_writer = storage->CreateResponseMetadataWriter(id); TestCompletionCallback cb; metadata_writer->WriteMetadata(body_buffer.get(), metadata.length(), cb.callback()); return cb.WaitForResult(); } int WriteMetadata(ServiceWorkerVersion* version, const GURL& url, const std::string& metadata) { const std::vector<char> data(metadata.begin(), metadata.end()); EXPECT_TRUE(version); TestCompletionCallback cb; version->script_cache_map()->WriteMetadata(url, data, cb.callback()); return cb.WaitForResult(); } int ClearMetadata(ServiceWorkerVersion* version, const GURL& url) { EXPECT_TRUE(version); TestCompletionCallback cb; version->script_cache_map()->ClearMetadata(url, cb.callback()); return cb.WaitForResult(); } bool VerifyResponseMetadata(ServiceWorkerStorage* storage, int64_t id, const std::string& expected_metadata) { scoped_ptr<ServiceWorkerResponseReader> reader = storage->CreateResponseReader(id); scoped_refptr<HttpResponseInfoIOBuffer> info_buffer = new HttpResponseInfoIOBuffer(); { TestCompletionCallback cb; reader->ReadInfo(info_buffer.get(), cb.callback()); int rv = cb.WaitForResult(); EXPECT_LT(0, rv); } const net::HttpResponseInfo* read_head = info_buffer->http_info.get(); if (!read_head->metadata.get()) return false; EXPECT_EQ(0, memcmp(expected_metadata.data(), read_head->metadata->data(), expected_metadata.length())); return true; } } // namespace class ServiceWorkerStorageTest : public testing::Test { public: ServiceWorkerStorageTest() : browser_thread_bundle_(TestBrowserThreadBundle::IO_MAINLOOP) { } void SetUp() override { InitializeTestHelper(); } void TearDown() override { helper_.reset(); base::RunLoop().RunUntilIdle(); } base::FilePath GetUserDataDirectory() { return user_data_directory_.path(); } bool InitUserDataDirectory() { return user_data_directory_.CreateUniqueTempDir(); } void InitializeTestHelper() { helper_.reset(new EmbeddedWorkerTestHelper(GetUserDataDirectory())); base::RunLoop().RunUntilIdle(); } ServiceWorkerContextCore* context() { return helper_->context(); } ServiceWorkerStorage* storage() { return helper_->context()->storage(); } // A static class method for friendliness. static void VerifyPurgeableListStatusCallback( ServiceWorkerDatabase* database, std::set<int64_t>* purgeable_ids, bool* was_called, ServiceWorkerStatusCode* result, ServiceWorkerStatusCode status) { *was_called = true; *result = status; EXPECT_EQ(ServiceWorkerDatabase::STATUS_OK, database->GetPurgeableResourceIds(purgeable_ids)); } protected: void LazyInitialize() { storage()->LazyInitialize(base::Bind(&base::DoNothing)); base::RunLoop().RunUntilIdle(); } ServiceWorkerStatusCode StoreRegistration( scoped_refptr<ServiceWorkerRegistration> registration, scoped_refptr<ServiceWorkerVersion> version) { bool was_called = false; ServiceWorkerStatusCode result = SERVICE_WORKER_ERROR_MAX_VALUE; storage()->StoreRegistration(registration.get(), version.get(), MakeStatusCallback(&was_called, &result)); EXPECT_FALSE(was_called); // always async base::RunLoop().RunUntilIdle(); EXPECT_TRUE(was_called); return result; } ServiceWorkerStatusCode DeleteRegistration(int64_t registration_id, const GURL& origin) { bool was_called = false; ServiceWorkerStatusCode result = SERVICE_WORKER_ERROR_MAX_VALUE; storage()->DeleteRegistration( registration_id, origin, MakeStatusCallback(&was_called, &result)); EXPECT_FALSE(was_called); // always async base::RunLoop().RunUntilIdle(); EXPECT_TRUE(was_called); return result; } ServiceWorkerStatusCode GetAllRegistrationsInfos( std::vector<ServiceWorkerRegistrationInfo>* registrations) { bool was_called = false; ServiceWorkerStatusCode result = SERVICE_WORKER_ERROR_MAX_VALUE; storage()->GetAllRegistrationsInfos( MakeGetRegistrationsInfosCallback(&was_called, &result, registrations)); EXPECT_FALSE(was_called); // always async base::RunLoop().RunUntilIdle(); EXPECT_TRUE(was_called); return result; } ServiceWorkerStatusCode GetRegistrationsForOrigin( const GURL& origin, std::vector<scoped_refptr<ServiceWorkerRegistration>>* registrations) { bool was_called = false; ServiceWorkerStatusCode result = SERVICE_WORKER_ERROR_MAX_VALUE; storage()->GetRegistrationsForOrigin( origin, MakeGetRegistrationsCallback(&was_called, &result, registrations)); EXPECT_FALSE(was_called); // always async base::RunLoop().RunUntilIdle(); EXPECT_TRUE(was_called); return result; } ServiceWorkerStatusCode GetUserData(int64_t registration_id, const std::string& key, std::string* data) { bool was_called = false; ServiceWorkerStatusCode result = SERVICE_WORKER_ERROR_MAX_VALUE; storage()->GetUserData( registration_id, key, base::Bind(&GetUserDataCallback, &was_called, data, &result)); EXPECT_FALSE(was_called); // always async base::RunLoop().RunUntilIdle(); EXPECT_TRUE(was_called); return result; } ServiceWorkerStatusCode StoreUserData(int64_t registration_id, const GURL& origin, const std::string& key, const std::string& data) { bool was_called = false; ServiceWorkerStatusCode result = SERVICE_WORKER_ERROR_MAX_VALUE; storage()->StoreUserData( registration_id, origin, key, data, MakeStatusCallback(&was_called, &result)); EXPECT_FALSE(was_called); // always async base::RunLoop().RunUntilIdle(); EXPECT_TRUE(was_called); return result; } ServiceWorkerStatusCode ClearUserData(int64_t registration_id, const std::string& key) { bool was_called = false; ServiceWorkerStatusCode result = SERVICE_WORKER_ERROR_MAX_VALUE; storage()->ClearUserData( registration_id, key, MakeStatusCallback(&was_called, &result)); EXPECT_FALSE(was_called); // always async base::RunLoop().RunUntilIdle(); EXPECT_TRUE(was_called); return result; } ServiceWorkerStatusCode GetUserDataForAllRegistrations( const std::string& key, std::vector<std::pair<int64_t, std::string>>* data) { bool was_called = false; ServiceWorkerStatusCode result = SERVICE_WORKER_ERROR_MAX_VALUE; storage()->GetUserDataForAllRegistrations( key, base::Bind(&GetUserDataForAllRegistrationsCallback, &was_called, data, &result)); EXPECT_FALSE(was_called); // always async base::RunLoop().RunUntilIdle(); EXPECT_TRUE(was_called); return result; } ServiceWorkerStatusCode UpdateToActiveState( const scoped_refptr<ServiceWorkerRegistration>& registration) { bool was_called = false; ServiceWorkerStatusCode result = SERVICE_WORKER_ERROR_MAX_VALUE; storage()->UpdateToActiveState(registration.get(), MakeStatusCallback(&was_called, &result)); EXPECT_FALSE(was_called); // always async base::RunLoop().RunUntilIdle(); EXPECT_TRUE(was_called); return result; } void UpdateLastUpdateCheckTime( const scoped_refptr<ServiceWorkerRegistration>& registration) { storage()->UpdateLastUpdateCheckTime(registration.get()); base::RunLoop().RunUntilIdle(); } ServiceWorkerStatusCode FindRegistrationForDocument( const GURL& document_url, scoped_refptr<ServiceWorkerRegistration>* registration) { bool was_called = false; ServiceWorkerStatusCode result = SERVICE_WORKER_ERROR_MAX_VALUE; storage()->FindRegistrationForDocument( document_url, MakeFindCallback(&was_called, &result, registration)); base::RunLoop().RunUntilIdle(); EXPECT_TRUE(was_called); return result; } ServiceWorkerStatusCode FindRegistrationForPattern( const GURL& scope, scoped_refptr<ServiceWorkerRegistration>* registration) { bool was_called = false; ServiceWorkerStatusCode result = SERVICE_WORKER_ERROR_MAX_VALUE; storage()->FindRegistrationForPattern( scope, MakeFindCallback(&was_called, &result, registration)); EXPECT_FALSE(was_called); // always async base::RunLoop().RunUntilIdle(); EXPECT_TRUE(was_called); return result; } ServiceWorkerStatusCode FindRegistrationForId( int64_t registration_id, const GURL& origin, scoped_refptr<ServiceWorkerRegistration>* registration) { bool was_called = false; ServiceWorkerStatusCode result = SERVICE_WORKER_ERROR_MAX_VALUE; storage()->FindRegistrationForId( registration_id, origin, MakeFindCallback(&was_called, &result, registration)); base::RunLoop().RunUntilIdle(); EXPECT_TRUE(was_called); return result; } ServiceWorkerStatusCode FindRegistrationForIdOnly( int64_t registration_id, scoped_refptr<ServiceWorkerRegistration>* registration) { bool was_called = false; ServiceWorkerStatusCode result = SERVICE_WORKER_ERROR_MAX_VALUE; storage()->FindRegistrationForIdOnly( registration_id, MakeFindCallback(&was_called, &result, registration)); base::RunLoop().RunUntilIdle(); EXPECT_TRUE(was_called); return result; } // user_data_directory_ must be declared first to preserve destructor order. base::ScopedTempDir user_data_directory_; scoped_ptr<EmbeddedWorkerTestHelper> helper_; TestBrowserThreadBundle browser_thread_bundle_; }; TEST_F(ServiceWorkerStorageTest, DisabledStorage) { const GURL kScope("http://www.example.com/scope/"); const GURL kScript("http://www.example.com/script.js"); const GURL kDocumentUrl("http://www.example.com/scope/document.html"); const int64_t kRegistrationId = 0; const int64_t kVersionId = 0; const int64_t kResourceId = 0; LazyInitialize(); storage()->Disable(); scoped_refptr<ServiceWorkerRegistration> found_registration; EXPECT_EQ(SERVICE_WORKER_ERROR_ABORT, FindRegistrationForDocument(kDocumentUrl, &found_registration)); EXPECT_EQ(SERVICE_WORKER_ERROR_ABORT, FindRegistrationForPattern(kScope, &found_registration)); EXPECT_EQ(SERVICE_WORKER_ERROR_ABORT, FindRegistrationForId(kRegistrationId, kScope.GetOrigin(), &found_registration)); EXPECT_EQ(SERVICE_WORKER_ERROR_ABORT, FindRegistrationForIdOnly(kRegistrationId, &found_registration)); EXPECT_FALSE(storage()->GetUninstallingRegistration(kScope.GetOrigin())); std::vector<scoped_refptr<ServiceWorkerRegistration>> found_registrations; EXPECT_EQ( SERVICE_WORKER_ERROR_ABORT, GetRegistrationsForOrigin(kScope.GetOrigin(), &found_registrations)); std::vector<ServiceWorkerRegistrationInfo> all_registrations; EXPECT_EQ(SERVICE_WORKER_ERROR_ABORT, GetAllRegistrationsInfos(&all_registrations)); scoped_refptr<ServiceWorkerRegistration> live_registration = new ServiceWorkerRegistration(kScope, kRegistrationId, context()->AsWeakPtr()); scoped_refptr<ServiceWorkerVersion> live_version = new ServiceWorkerVersion( live_registration.get(), kScript, kVersionId, context()->AsWeakPtr()); EXPECT_EQ(SERVICE_WORKER_ERROR_ABORT, StoreRegistration(live_registration, live_version)); EXPECT_EQ(SERVICE_WORKER_ERROR_ABORT, UpdateToActiveState(live_registration)); EXPECT_EQ(SERVICE_WORKER_ERROR_ABORT, DeleteRegistration(kRegistrationId, kScope.GetOrigin())); // Response reader and writer created by the disabled storage should fail to // access the disk cache. scoped_refptr<HttpResponseInfoIOBuffer> info_buffer = new HttpResponseInfoIOBuffer(); EXPECT_EQ(net::ERR_CACHE_MISS, ReadResponseInfo(storage(), kResourceId, info_buffer.get())); EXPECT_EQ(net::ERR_FAILED, WriteBasicResponse(storage(), kResourceId)); EXPECT_EQ(net::ERR_FAILED, WriteResponseMetadata(storage(), kResourceId, "foo")); const std::string kUserDataKey = "key"; std::string user_data_out; EXPECT_EQ(SERVICE_WORKER_ERROR_ABORT, GetUserData(kRegistrationId, kUserDataKey, &user_data_out)); EXPECT_EQ( SERVICE_WORKER_ERROR_ABORT, StoreUserData(kRegistrationId, kScope.GetOrigin(), kUserDataKey, "foo")); EXPECT_EQ(SERVICE_WORKER_ERROR_ABORT, ClearUserData(kRegistrationId, kUserDataKey)); std::vector<std::pair<int64_t, std::string>> data_list_out; EXPECT_EQ(SERVICE_WORKER_ERROR_ABORT, GetUserDataForAllRegistrations(kUserDataKey, &data_list_out)); EXPECT_FALSE( storage()->OriginHasForeignFetchRegistrations(kScope.GetOrigin())); // Next available ids should be invalid. EXPECT_EQ(kInvalidServiceWorkerRegistrationId, storage()->NewRegistrationId()); EXPECT_EQ(kInvalidServiceWorkerVersionId, storage()->NewVersionId()); EXPECT_EQ(kInvalidServiceWorkerResourceId, storage()->NewRegistrationId()); } TEST_F(ServiceWorkerStorageTest, StoreFindUpdateDeleteRegistration) { const GURL kScope("http://www.test.not/scope/"); const GURL kScript("http://www.test.not/script.js"); const GURL kDocumentUrl("http://www.test.not/scope/document.html"); const GURL kResource1("http://www.test.not/scope/resource1.js"); const int64_t kResource1Size = 1591234; const GURL kResource2("http://www.test.not/scope/resource2.js"); const int64_t kResource2Size = 51; const int64_t kRegistrationId = 0; const int64_t kVersionId = 0; const GURL kForeignFetchScope("http://www.test.not/scope/ff/"); const url::Origin kForeignFetchOrigin(GURL("https://example.com/")); const base::Time kToday = base::Time::Now(); const base::Time kYesterday = kToday - base::TimeDelta::FromDays(1); scoped_refptr<ServiceWorkerRegistration> found_registration; // We shouldn't find anything without having stored anything. EXPECT_EQ(SERVICE_WORKER_ERROR_NOT_FOUND, FindRegistrationForDocument(kDocumentUrl, &found_registration)); EXPECT_FALSE(found_registration.get()); EXPECT_EQ(SERVICE_WORKER_ERROR_NOT_FOUND, FindRegistrationForPattern(kScope, &found_registration)); EXPECT_FALSE(found_registration.get()); EXPECT_EQ(SERVICE_WORKER_ERROR_NOT_FOUND, FindRegistrationForId( kRegistrationId, kScope.GetOrigin(), &found_registration)); EXPECT_FALSE(found_registration.get()); std::vector<ServiceWorkerDatabase::ResourceRecord> resources; resources.push_back( ServiceWorkerDatabase::ResourceRecord(1, kResource1, kResource1Size)); resources.push_back( ServiceWorkerDatabase::ResourceRecord(2, kResource2, kResource2Size)); // Store something. scoped_refptr<ServiceWorkerRegistration> live_registration = new ServiceWorkerRegistration(kScope, kRegistrationId, context()->AsWeakPtr()); scoped_refptr<ServiceWorkerVersion> live_version = new ServiceWorkerVersion( live_registration.get(), kScript, kVersionId, context()->AsWeakPtr()); live_version->SetStatus(ServiceWorkerVersion::INSTALLED); live_version->script_cache_map()->SetResources(resources); live_version->set_foreign_fetch_scopes( std::vector<GURL>(1, kForeignFetchScope)); live_version->set_foreign_fetch_origins( std::vector<url::Origin>(1, kForeignFetchOrigin)); live_registration->SetWaitingVersion(live_version); live_registration->set_last_update_check(kYesterday); EXPECT_EQ(SERVICE_WORKER_OK, StoreRegistration(live_registration, live_version)); // Now we should find it and get the live ptr back immediately. EXPECT_EQ(SERVICE_WORKER_OK, FindRegistrationForDocument(kDocumentUrl, &found_registration)); EXPECT_EQ(live_registration, found_registration); EXPECT_EQ(kResource1Size + kResource2Size, live_registration->resources_total_size_bytes()); EXPECT_EQ(kResource1Size + kResource2Size, found_registration->resources_total_size_bytes()); found_registration = NULL; // But FindRegistrationForPattern is always async. EXPECT_EQ(SERVICE_WORKER_OK, FindRegistrationForPattern(kScope, &found_registration)); EXPECT_EQ(live_registration, found_registration); found_registration = NULL; // Can be found by id too. EXPECT_EQ(SERVICE_WORKER_OK, FindRegistrationForId( kRegistrationId, kScope.GetOrigin(), &found_registration)); ASSERT_TRUE(found_registration.get()); EXPECT_EQ(kRegistrationId, found_registration->id()); EXPECT_EQ(live_registration, found_registration); found_registration = NULL; // Can be found by just the id too. EXPECT_EQ(SERVICE_WORKER_OK, FindRegistrationForIdOnly(kRegistrationId, &found_registration)); ASSERT_TRUE(found_registration.get()); EXPECT_EQ(kRegistrationId, found_registration->id()); EXPECT_EQ(live_registration, found_registration); found_registration = NULL; // Drop the live registration, but keep the version live. live_registration = NULL; // Now FindRegistrationForDocument should be async. EXPECT_EQ(SERVICE_WORKER_OK, FindRegistrationForDocument(kDocumentUrl, &found_registration)); ASSERT_TRUE(found_registration.get()); EXPECT_EQ(kRegistrationId, found_registration->id()); EXPECT_TRUE(found_registration->HasOneRef()); // Check that sizes are populated correctly EXPECT_EQ(live_version.get(), found_registration->waiting_version()); EXPECT_EQ(kResource1Size + kResource2Size, found_registration->resources_total_size_bytes()); std::vector<ServiceWorkerRegistrationInfo> all_registrations; EXPECT_EQ(SERVICE_WORKER_OK, GetAllRegistrationsInfos(&all_registrations)); EXPECT_EQ(1u, all_registrations.size()); ServiceWorkerRegistrationInfo info = all_registrations[0]; EXPECT_EQ(kResource1Size + kResource2Size, info.stored_version_size_bytes); all_registrations.clear(); // Finding by origin should provide the same result if origin is kScope. std::vector<scoped_refptr<ServiceWorkerRegistration>> registrations_for_origin; EXPECT_EQ( SERVICE_WORKER_OK, GetRegistrationsForOrigin(kScope.GetOrigin(), &registrations_for_origin)); EXPECT_EQ(1u, registrations_for_origin.size()); registrations_for_origin.clear(); EXPECT_EQ(SERVICE_WORKER_OK, GetRegistrationsForOrigin(GURL("http://example.com/").GetOrigin(), &registrations_for_origin)); EXPECT_TRUE(registrations_for_origin.empty()); found_registration = NULL; // Drop the live version too. live_version = NULL; // And FindRegistrationForPattern is always async. EXPECT_EQ(SERVICE_WORKER_OK, FindRegistrationForPattern(kScope, &found_registration)); ASSERT_TRUE(found_registration.get()); EXPECT_EQ(kRegistrationId, found_registration->id()); EXPECT_TRUE(found_registration->HasOneRef()); EXPECT_FALSE(found_registration->active_version()); ASSERT_TRUE(found_registration->waiting_version()); EXPECT_EQ(kYesterday, found_registration->last_update_check()); EXPECT_EQ(ServiceWorkerVersion::INSTALLED, found_registration->waiting_version()->status()); EXPECT_EQ( 1u, found_registration->waiting_version()->foreign_fetch_scopes().size()); EXPECT_EQ(kForeignFetchScope, found_registration->waiting_version()->foreign_fetch_scopes()[0]); EXPECT_EQ( 1u, found_registration->waiting_version()->foreign_fetch_origins().size()); EXPECT_EQ(kForeignFetchOrigin, found_registration->waiting_version()->foreign_fetch_origins()[0]); // Update to active and update the last check time. scoped_refptr<ServiceWorkerVersion> temp_version = found_registration->waiting_version(); temp_version->SetStatus(ServiceWorkerVersion::ACTIVATED); found_registration->SetActiveVersion(temp_version); temp_version = NULL; EXPECT_EQ(SERVICE_WORKER_OK, UpdateToActiveState(found_registration)); found_registration->set_last_update_check(kToday); UpdateLastUpdateCheckTime(found_registration.get()); found_registration = NULL; // Trying to update a unstored registration to active should fail. scoped_refptr<ServiceWorkerRegistration> unstored_registration = new ServiceWorkerRegistration(kScope, kRegistrationId + 1, context()->AsWeakPtr()); EXPECT_EQ(SERVICE_WORKER_ERROR_NOT_FOUND, UpdateToActiveState(unstored_registration)); unstored_registration = NULL; // The Find methods should return a registration with an active version // and the expected update time. EXPECT_EQ(SERVICE_WORKER_OK, FindRegistrationForDocument(kDocumentUrl, &found_registration)); ASSERT_TRUE(found_registration.get()); EXPECT_EQ(kRegistrationId, found_registration->id()); EXPECT_TRUE(found_registration->HasOneRef()); EXPECT_FALSE(found_registration->waiting_version()); ASSERT_TRUE(found_registration->active_version()); EXPECT_EQ(ServiceWorkerVersion::ACTIVATED, found_registration->active_version()->status()); EXPECT_EQ(kToday, found_registration->last_update_check()); // Delete from storage but with a instance still live. EXPECT_TRUE(context()->GetLiveVersion(kRegistrationId)); EXPECT_EQ(SERVICE_WORKER_OK, DeleteRegistration(kRegistrationId, kScope.GetOrigin())); EXPECT_TRUE(context()->GetLiveVersion(kRegistrationId)); // Should no longer be found. EXPECT_EQ(SERVICE_WORKER_ERROR_NOT_FOUND, FindRegistrationForId( kRegistrationId, kScope.GetOrigin(), &found_registration)); EXPECT_FALSE(found_registration.get()); EXPECT_EQ(SERVICE_WORKER_ERROR_NOT_FOUND, FindRegistrationForIdOnly(kRegistrationId, &found_registration)); EXPECT_FALSE(found_registration.get()); // Deleting an unstored registration should succeed. EXPECT_EQ(SERVICE_WORKER_OK, DeleteRegistration(kRegistrationId + 1, kScope.GetOrigin())); } TEST_F(ServiceWorkerStorageTest, InstallingRegistrationsAreFindable) { const GURL kScope("http://www.test.not/scope/"); const GURL kScript("http://www.test.not/script.js"); const GURL kDocumentUrl("http://www.test.not/scope/document.html"); const int64_t kRegistrationId = 0; const int64_t kVersionId = 0; scoped_refptr<ServiceWorkerRegistration> found_registration; // Create an unstored registration. scoped_refptr<ServiceWorkerRegistration> live_registration = new ServiceWorkerRegistration(kScope, kRegistrationId, context()->AsWeakPtr()); scoped_refptr<ServiceWorkerVersion> live_version = new ServiceWorkerVersion( live_registration.get(), kScript, kVersionId, context()->AsWeakPtr()); live_version->SetStatus(ServiceWorkerVersion::INSTALLING); live_registration->SetWaitingVersion(live_version); // Should not be findable, including by GetAllRegistrationsInfos. EXPECT_EQ(SERVICE_WORKER_ERROR_NOT_FOUND, FindRegistrationForId( kRegistrationId, kScope.GetOrigin(), &found_registration)); EXPECT_FALSE(found_registration.get()); EXPECT_EQ(SERVICE_WORKER_ERROR_NOT_FOUND, FindRegistrationForIdOnly(kRegistrationId, &found_registration)); EXPECT_FALSE(found_registration.get()); EXPECT_EQ(SERVICE_WORKER_ERROR_NOT_FOUND, FindRegistrationForDocument(kDocumentUrl, &found_registration)); EXPECT_FALSE(found_registration.get()); EXPECT_EQ(SERVICE_WORKER_ERROR_NOT_FOUND, FindRegistrationForPattern(kScope, &found_registration)); EXPECT_FALSE(found_registration.get()); std::vector<ServiceWorkerRegistrationInfo> all_registrations; EXPECT_EQ(SERVICE_WORKER_OK, GetAllRegistrationsInfos(&all_registrations)); EXPECT_TRUE(all_registrations.empty()); std::vector<scoped_refptr<ServiceWorkerRegistration>> registrations_for_origin; EXPECT_EQ( SERVICE_WORKER_OK, GetRegistrationsForOrigin(kScope.GetOrigin(), &registrations_for_origin)); EXPECT_TRUE(registrations_for_origin.empty()); EXPECT_EQ(SERVICE_WORKER_OK, GetRegistrationsForOrigin(GURL("http://example.com/").GetOrigin(), &registrations_for_origin)); EXPECT_TRUE(registrations_for_origin.empty()); // Notify storage of it being installed. storage()->NotifyInstallingRegistration(live_registration.get()); // Now should be findable. EXPECT_EQ(SERVICE_WORKER_OK, FindRegistrationForId( kRegistrationId, kScope.GetOrigin(), &found_registration)); EXPECT_EQ(live_registration, found_registration); found_registration = NULL; EXPECT_EQ(SERVICE_WORKER_OK, FindRegistrationForIdOnly(kRegistrationId, &found_registration)); EXPECT_EQ(live_registration, found_registration); found_registration = NULL; EXPECT_EQ(SERVICE_WORKER_OK, FindRegistrationForDocument(kDocumentUrl, &found_registration)); EXPECT_EQ(live_registration, found_registration); found_registration = NULL; EXPECT_EQ(SERVICE_WORKER_OK, FindRegistrationForPattern(kScope, &found_registration)); EXPECT_EQ(live_registration, found_registration); found_registration = NULL; EXPECT_EQ(SERVICE_WORKER_OK, GetAllRegistrationsInfos(&all_registrations)); EXPECT_EQ(1u, all_registrations.size()); all_registrations.clear(); // Finding by origin should provide the same result if origin is kScope. EXPECT_EQ( SERVICE_WORKER_OK, GetRegistrationsForOrigin(kScope.GetOrigin(), &registrations_for_origin)); EXPECT_EQ(1u, registrations_for_origin.size()); registrations_for_origin.clear(); EXPECT_EQ(SERVICE_WORKER_OK, GetRegistrationsForOrigin(GURL("http://example.com/").GetOrigin(), &registrations_for_origin)); EXPECT_TRUE(registrations_for_origin.empty()); // Notify storage of installation no longer happening. storage()->NotifyDoneInstallingRegistration( live_registration.get(), NULL, SERVICE_WORKER_OK); // Once again, should not be findable. EXPECT_EQ(SERVICE_WORKER_ERROR_NOT_FOUND, FindRegistrationForId( kRegistrationId, kScope.GetOrigin(), &found_registration)); EXPECT_FALSE(found_registration.get()); EXPECT_EQ(SERVICE_WORKER_ERROR_NOT_FOUND, FindRegistrationForIdOnly(kRegistrationId, &found_registration)); EXPECT_FALSE(found_registration.get()); EXPECT_EQ(SERVICE_WORKER_ERROR_NOT_FOUND, FindRegistrationForDocument(kDocumentUrl, &found_registration)); EXPECT_FALSE(found_registration.get()); EXPECT_EQ(SERVICE_WORKER_ERROR_NOT_FOUND, FindRegistrationForPattern(kScope, &found_registration)); EXPECT_FALSE(found_registration.get()); EXPECT_EQ(SERVICE_WORKER_OK, GetAllRegistrationsInfos(&all_registrations)); EXPECT_TRUE(all_registrations.empty()); EXPECT_EQ( SERVICE_WORKER_OK, GetRegistrationsForOrigin(kScope.GetOrigin(), &registrations_for_origin)); EXPECT_TRUE(registrations_for_origin.empty()); EXPECT_EQ(SERVICE_WORKER_OK, GetRegistrationsForOrigin(GURL("http://example.com/").GetOrigin(), &registrations_for_origin)); EXPECT_TRUE(registrations_for_origin.empty()); } TEST_F(ServiceWorkerStorageTest, StoreUserData) { const GURL kScope("http://www.test.not/scope/"); const GURL kScript("http://www.test.not/script.js"); const int64_t kRegistrationId = 0; const int64_t kVersionId = 0; LazyInitialize(); // Store a registration. scoped_refptr<ServiceWorkerRegistration> live_registration = new ServiceWorkerRegistration(kScope, kRegistrationId, context()->AsWeakPtr()); scoped_refptr<ServiceWorkerVersion> live_version = new ServiceWorkerVersion( live_registration.get(), kScript, kVersionId, context()->AsWeakPtr()); std::vector<ServiceWorkerDatabase::ResourceRecord> records; records.push_back(ServiceWorkerDatabase::ResourceRecord( 1, live_version->script_url(), 100)); live_version->script_cache_map()->SetResources(records); live_version->SetStatus(ServiceWorkerVersion::INSTALLED); live_registration->SetWaitingVersion(live_version); EXPECT_EQ(SERVICE_WORKER_OK, StoreRegistration(live_registration, live_version)); // Store user data associated with the registration. std::string data_out; EXPECT_EQ(SERVICE_WORKER_OK, StoreUserData(kRegistrationId, kScope.GetOrigin(), "key", "data")); EXPECT_EQ(SERVICE_WORKER_OK, GetUserData(kRegistrationId, "key", &data_out)); EXPECT_EQ("data", data_out); EXPECT_EQ(SERVICE_WORKER_ERROR_NOT_FOUND, GetUserData(kRegistrationId, "unknown_key", &data_out)); std::vector<std::pair<int64_t, std::string>> data_list_out; EXPECT_EQ(SERVICE_WORKER_OK, GetUserDataForAllRegistrations("key", &data_list_out)); ASSERT_EQ(1u, data_list_out.size()); EXPECT_EQ(kRegistrationId, data_list_out[0].first); EXPECT_EQ("data", data_list_out[0].second); data_list_out.clear(); EXPECT_EQ(SERVICE_WORKER_OK, GetUserDataForAllRegistrations("unknown_key", &data_list_out)); EXPECT_EQ(0u, data_list_out.size()); EXPECT_EQ(SERVICE_WORKER_OK, ClearUserData(kRegistrationId, "key")); EXPECT_EQ(SERVICE_WORKER_ERROR_NOT_FOUND, GetUserData(kRegistrationId, "key", &data_out)); // User data should be deleted when the associated registration is deleted. ASSERT_EQ(SERVICE_WORKER_OK, StoreUserData(kRegistrationId, kScope.GetOrigin(), "key", "data")); ASSERT_EQ(SERVICE_WORKER_OK, GetUserData(kRegistrationId, "key", &data_out)); ASSERT_EQ("data", data_out); EXPECT_EQ(SERVICE_WORKER_OK, DeleteRegistration(kRegistrationId, kScope.GetOrigin())); EXPECT_EQ(SERVICE_WORKER_ERROR_NOT_FOUND, GetUserData(kRegistrationId, "key", &data_out)); data_list_out.clear(); EXPECT_EQ(SERVICE_WORKER_OK, GetUserDataForAllRegistrations("key", &data_list_out)); EXPECT_EQ(0u, data_list_out.size()); // Data access with an invalid registration id should be failed. EXPECT_EQ(SERVICE_WORKER_ERROR_FAILED, StoreUserData(kInvalidServiceWorkerRegistrationId, kScope.GetOrigin(), "key", "data")); EXPECT_EQ(SERVICE_WORKER_ERROR_FAILED, GetUserData(kInvalidServiceWorkerRegistrationId, "key", &data_out)); EXPECT_EQ(SERVICE_WORKER_ERROR_FAILED, ClearUserData(kInvalidServiceWorkerRegistrationId, "key")); // Data access with an empty key should be failed. EXPECT_EQ(SERVICE_WORKER_ERROR_FAILED, StoreUserData( kRegistrationId, kScope.GetOrigin(), std::string(), "data")); EXPECT_EQ(SERVICE_WORKER_ERROR_FAILED, GetUserData(kRegistrationId, std::string(), &data_out)); EXPECT_EQ(SERVICE_WORKER_ERROR_FAILED, ClearUserData(kRegistrationId, std::string())); data_list_out.clear(); EXPECT_EQ(SERVICE_WORKER_ERROR_FAILED, GetUserDataForAllRegistrations(std::string(), &data_list_out)); } class ServiceWorkerResourceStorageTest : public ServiceWorkerStorageTest { public: void SetUp() override { ServiceWorkerStorageTest::SetUp(); LazyInitialize(); scope_ = GURL("http://www.test.not/scope/"); script_ = GURL("http://www.test.not/script.js"); import_ = GURL("http://www.test.not/import.js"); document_url_ = GURL("http://www.test.not/scope/document.html"); registration_id_ = storage()->NewRegistrationId(); version_id_ = storage()->NewVersionId(); resource_id1_ = storage()->NewResourceId(); resource_id2_ = storage()->NewResourceId(); resource_id1_size_ = 239193; resource_id2_size_ = 59923; // Cons up a new registration+version with two script resources. RegistrationData data; data.registration_id = registration_id_; data.scope = scope_; data.script = script_; data.version_id = version_id_; data.is_active = false; std::vector<ResourceRecord> resources; resources.push_back( ResourceRecord(resource_id1_, script_, resource_id1_size_)); resources.push_back( ResourceRecord(resource_id2_, import_, resource_id2_size_)); registration_ = storage()->GetOrCreateRegistration(data, resources); registration_->waiting_version()->SetStatus(ServiceWorkerVersion::NEW); // Add the resources ids to the uncommitted list. storage()->StoreUncommittedResourceId(resource_id1_); storage()->StoreUncommittedResourceId(resource_id2_); base::RunLoop().RunUntilIdle(); std::set<int64_t> verify_ids; EXPECT_EQ(ServiceWorkerDatabase::STATUS_OK, storage()->database_->GetUncommittedResourceIds(&verify_ids)); EXPECT_EQ(2u, verify_ids.size()); // And dump something in the disk cache for them. WriteBasicResponse(storage(), resource_id1_); WriteBasicResponse(storage(), resource_id2_); EXPECT_TRUE(VerifyBasicResponse(storage(), resource_id1_, true)); EXPECT_TRUE(VerifyBasicResponse(storage(), resource_id2_, true)); // Storing the registration/version should take the resources ids out // of the uncommitted list. EXPECT_EQ( SERVICE_WORKER_OK, StoreRegistration(registration_, registration_->waiting_version())); verify_ids.clear(); EXPECT_EQ(ServiceWorkerDatabase::STATUS_OK, storage()->database_->GetUncommittedResourceIds(&verify_ids)); EXPECT_TRUE(verify_ids.empty()); } protected: GURL scope_; GURL script_; GURL import_; GURL document_url_; int64_t registration_id_; int64_t version_id_; int64_t resource_id1_; uint64_t resource_id1_size_; int64_t resource_id2_; uint64_t resource_id2_size_; scoped_refptr<ServiceWorkerRegistration> registration_; }; class ServiceWorkerResourceStorageDiskTest : public ServiceWorkerResourceStorageTest { public: void SetUp() override { ASSERT_TRUE(InitUserDataDirectory()); ServiceWorkerResourceStorageTest::SetUp(); } }; TEST_F(ServiceWorkerResourceStorageTest, WriteMetadataWithServiceWorkerResponseMetadataWriter) { const char kMetadata1[] = "Test metadata"; const char kMetadata2[] = "small"; int64_t new_resource_id_ = storage()->NewResourceId(); // Writing metadata to nonexistent resoirce ID must fail. EXPECT_GE(0, WriteResponseMetadata(storage(), new_resource_id_, kMetadata1)); // Check metadata is written. EXPECT_EQ(static_cast<int>(strlen(kMetadata1)), WriteResponseMetadata(storage(), resource_id1_, kMetadata1)); EXPECT_TRUE(VerifyResponseMetadata(storage(), resource_id1_, kMetadata1)); EXPECT_TRUE(VerifyBasicResponse(storage(), resource_id1_, true)); // Check metadata is written and truncated. EXPECT_EQ(static_cast<int>(strlen(kMetadata2)), WriteResponseMetadata(storage(), resource_id1_, kMetadata2)); EXPECT_TRUE(VerifyResponseMetadata(storage(), resource_id1_, kMetadata2)); EXPECT_TRUE(VerifyBasicResponse(storage(), resource_id1_, true)); // Check metadata is deleted. EXPECT_EQ(0, WriteResponseMetadata(storage(), resource_id1_, "")); EXPECT_FALSE(VerifyResponseMetadata(storage(), resource_id1_, "")); EXPECT_TRUE(VerifyBasicResponse(storage(), resource_id1_, true)); } TEST_F(ServiceWorkerResourceStorageTest, WriteMetadataWithServiceWorkerScriptCacheMap) { const char kMetadata1[] = "Test metadata"; const char kMetadata2[] = "small"; ServiceWorkerVersion* version = registration_->waiting_version(); EXPECT_TRUE(version); // Writing metadata to nonexistent URL must fail. EXPECT_GE(0, WriteMetadata(version, GURL("http://www.test.not/nonexistent.js"), kMetadata1)); // Clearing metadata of nonexistent URL must fail. EXPECT_GE(0, ClearMetadata(version, GURL("http://www.test.not/nonexistent.js"))); // Check metadata is written. EXPECT_EQ(static_cast<int>(strlen(kMetadata1)), WriteMetadata(version, script_, kMetadata1)); EXPECT_TRUE(VerifyResponseMetadata(storage(), resource_id1_, kMetadata1)); EXPECT_TRUE(VerifyBasicResponse(storage(), resource_id1_, true)); // Check metadata is written and truncated. EXPECT_EQ(static_cast<int>(strlen(kMetadata2)), WriteMetadata(version, script_, kMetadata2)); EXPECT_TRUE(VerifyResponseMetadata(storage(), resource_id1_, kMetadata2)); EXPECT_TRUE(VerifyBasicResponse(storage(), resource_id1_, true)); // Check metadata is deleted. EXPECT_EQ(0, ClearMetadata(version, script_)); EXPECT_FALSE(VerifyResponseMetadata(storage(), resource_id1_, "")); EXPECT_TRUE(VerifyBasicResponse(storage(), resource_id1_, true)); } TEST_F(ServiceWorkerResourceStorageTest, DeleteRegistration_NoLiveVersion) { bool was_called = false; ServiceWorkerStatusCode result = SERVICE_WORKER_ERROR_FAILED; std::set<int64_t> verify_ids; registration_->SetWaitingVersion(NULL); registration_ = NULL; // Deleting the registration should result in the resources being added to the // purgeable list and then doomed in the disk cache and removed from that // list. storage()->DeleteRegistration( registration_id_, scope_.GetOrigin(), base::Bind(&VerifyPurgeableListStatusCallback, base::Unretained(storage()->database_.get()), &verify_ids, &was_called, &result)); base::RunLoop().RunUntilIdle(); ASSERT_TRUE(was_called); EXPECT_EQ(SERVICE_WORKER_OK, result); EXPECT_EQ(2u, verify_ids.size()); verify_ids.clear(); EXPECT_EQ(ServiceWorkerDatabase::STATUS_OK, storage()->database_->GetPurgeableResourceIds(&verify_ids)); EXPECT_TRUE(verify_ids.empty()); EXPECT_FALSE(VerifyBasicResponse(storage(), resource_id1_, false)); EXPECT_FALSE(VerifyBasicResponse(storage(), resource_id2_, false)); } TEST_F(ServiceWorkerResourceStorageTest, DeleteRegistration_WaitingVersion) { bool was_called = false; ServiceWorkerStatusCode result = SERVICE_WORKER_ERROR_FAILED; std::set<int64_t> verify_ids; // Deleting the registration should result in the resources being added to the // purgeable list and then doomed in the disk cache and removed from that // list. storage()->DeleteRegistration( registration_->id(), scope_.GetOrigin(), base::Bind(&VerifyPurgeableListStatusCallback, base::Unretained(storage()->database_.get()), &verify_ids, &was_called, &result)); base::RunLoop().RunUntilIdle(); ASSERT_TRUE(was_called); EXPECT_EQ(SERVICE_WORKER_OK, result); EXPECT_EQ(2u, verify_ids.size()); verify_ids.clear(); EXPECT_EQ(ServiceWorkerDatabase::STATUS_OK, storage()->database_->GetPurgeableResourceIds(&verify_ids)); EXPECT_EQ(2u, verify_ids.size()); EXPECT_TRUE(VerifyBasicResponse(storage(), resource_id1_, false)); EXPECT_TRUE(VerifyBasicResponse(storage(), resource_id2_, false)); // Doom the version, now it happens. registration_->waiting_version()->Doom(); base::RunLoop().RunUntilIdle(); EXPECT_EQ(SERVICE_WORKER_OK, result); EXPECT_EQ(2u, verify_ids.size()); verify_ids.clear(); EXPECT_EQ(ServiceWorkerDatabase::STATUS_OK, storage()->database_->GetPurgeableResourceIds(&verify_ids)); EXPECT_TRUE(verify_ids.empty()); EXPECT_FALSE(VerifyBasicResponse(storage(), resource_id1_, false)); EXPECT_FALSE(VerifyBasicResponse(storage(), resource_id2_, false)); } TEST_F(ServiceWorkerResourceStorageTest, DeleteRegistration_ActiveVersion) { // Promote the worker to active and add a controllee. registration_->SetActiveVersion(registration_->waiting_version()); storage()->UpdateToActiveState( registration_.get(), base::Bind(&ServiceWorkerUtils::NoOpStatusCallback)); scoped_ptr<ServiceWorkerProviderHost> host(new ServiceWorkerProviderHost( 33 /* dummy render process id */, MSG_ROUTING_NONE, 1 /* dummy provider_id */, SERVICE_WORKER_PROVIDER_FOR_WINDOW, context()->AsWeakPtr(), NULL)); registration_->active_version()->AddControllee(host.get()); bool was_called = false; ServiceWorkerStatusCode result = SERVICE_WORKER_ERROR_FAILED; std::set<int64_t> verify_ids; // Deleting the registration should move the resources to the purgeable list // but keep them available. storage()->DeleteRegistration( registration_->id(), scope_.GetOrigin(), base::Bind(&VerifyPurgeableListStatusCallback, base::Unretained(storage()->database_.get()), &verify_ids, &was_called, &result)); base::RunLoop().RunUntilIdle(); ASSERT_TRUE(was_called); EXPECT_EQ(SERVICE_WORKER_OK, result); EXPECT_EQ(2u, verify_ids.size()); verify_ids.clear(); EXPECT_EQ(ServiceWorkerDatabase::STATUS_OK, storage()->database_->GetPurgeableResourceIds(&verify_ids)); EXPECT_EQ(2u, verify_ids.size()); EXPECT_TRUE(VerifyBasicResponse(storage(), resource_id1_, true)); EXPECT_TRUE(VerifyBasicResponse(storage(), resource_id2_, true)); // Removing the controllee should cause the resources to be deleted. registration_->active_version()->RemoveControllee(host.get()); registration_->active_version()->Doom(); base::RunLoop().RunUntilIdle(); verify_ids.clear(); EXPECT_EQ(ServiceWorkerDatabase::STATUS_OK, storage()->database_->GetPurgeableResourceIds(&verify_ids)); EXPECT_TRUE(verify_ids.empty()); EXPECT_FALSE(VerifyBasicResponse(storage(), resource_id1_, false)); EXPECT_FALSE(VerifyBasicResponse(storage(), resource_id2_, false)); } TEST_F(ServiceWorkerResourceStorageDiskTest, CleanupOnRestart) { // Promote the worker to active and add a controllee. registration_->SetActiveVersion(registration_->waiting_version()); registration_->SetWaitingVersion(NULL); storage()->UpdateToActiveState( registration_.get(), base::Bind(&ServiceWorkerUtils::NoOpStatusCallback)); scoped_ptr<ServiceWorkerProviderHost> host(new ServiceWorkerProviderHost( 33 /* dummy render process id */, MSG_ROUTING_NONE, 1 /* dummy provider_id */, SERVICE_WORKER_PROVIDER_FOR_WINDOW, context()->AsWeakPtr(), NULL)); registration_->active_version()->AddControllee(host.get()); bool was_called = false; ServiceWorkerStatusCode result = SERVICE_WORKER_ERROR_FAILED; std::set<int64_t> verify_ids; // Deleting the registration should move the resources to the purgeable list // but keep them available. storage()->DeleteRegistration( registration_->id(), scope_.GetOrigin(), base::Bind(&VerifyPurgeableListStatusCallback, base::Unretained(storage()->database_.get()), &verify_ids, &was_called, &result)); base::RunLoop().RunUntilIdle(); ASSERT_TRUE(was_called); EXPECT_EQ(SERVICE_WORKER_OK, result); EXPECT_EQ(2u, verify_ids.size()); verify_ids.clear(); EXPECT_EQ(ServiceWorkerDatabase::STATUS_OK, storage()->database_->GetPurgeableResourceIds(&verify_ids)); EXPECT_EQ(2u, verify_ids.size()); EXPECT_TRUE(VerifyBasicResponse(storage(), resource_id1_, true)); EXPECT_TRUE(VerifyBasicResponse(storage(), resource_id2_, true)); // Also add an uncommitted resource. int64_t kStaleUncommittedResourceId = storage()->NewResourceId(); storage()->StoreUncommittedResourceId(kStaleUncommittedResourceId); base::RunLoop().RunUntilIdle(); verify_ids.clear(); EXPECT_EQ(ServiceWorkerDatabase::STATUS_OK, storage()->database_->GetUncommittedResourceIds(&verify_ids)); EXPECT_EQ(1u, verify_ids.size()); WriteBasicResponse(storage(), kStaleUncommittedResourceId); EXPECT_TRUE( VerifyBasicResponse(storage(), kStaleUncommittedResourceId, true)); // Simulate browser shutdown. The purgeable and uncommitted resources are now // stale. InitializeTestHelper(); LazyInitialize(); // Store a new uncommitted resource. This triggers stale resource cleanup. int64_t kNewResourceId = storage()->NewResourceId(); WriteBasicResponse(storage(), kNewResourceId); storage()->StoreUncommittedResourceId(kNewResourceId); base::RunLoop().RunUntilIdle(); // The stale resources should be purged, but the new resource should persist. verify_ids.clear(); EXPECT_EQ(ServiceWorkerDatabase::STATUS_OK, storage()->database_->GetUncommittedResourceIds(&verify_ids)); ASSERT_EQ(1u, verify_ids.size()); EXPECT_EQ(kNewResourceId, *verify_ids.begin()); // Purging resources needs interactions with SimpleCache's worker thread, // so single RunUntilIdle() call may not be sufficient. while (storage()->is_purge_pending_) base::RunLoop().RunUntilIdle(); verify_ids.clear(); EXPECT_EQ(ServiceWorkerDatabase::STATUS_OK, storage()->database_->GetPurgeableResourceIds(&verify_ids)); EXPECT_TRUE(verify_ids.empty()); EXPECT_FALSE(VerifyBasicResponse(storage(), resource_id1_, false)); EXPECT_FALSE(VerifyBasicResponse(storage(), resource_id2_, false)); EXPECT_FALSE( VerifyBasicResponse(storage(), kStaleUncommittedResourceId, false)); EXPECT_TRUE(VerifyBasicResponse(storage(), kNewResourceId, true)); } TEST_F(ServiceWorkerResourceStorageDiskTest, DeleteAndStartOver) { EXPECT_FALSE(storage()->IsDisabled()); ASSERT_TRUE(base::DirectoryExists(storage()->GetDiskCachePath())); ASSERT_TRUE(base::DirectoryExists(storage()->GetDatabasePath())); base::RunLoop run_loop; ServiceWorkerStatusCode status = SERVICE_WORKER_ERROR_MAX_VALUE; storage()->DeleteAndStartOver( base::Bind(&StatusAndQuitCallback, &status, run_loop.QuitClosure())); run_loop.Run(); EXPECT_EQ(SERVICE_WORKER_OK, status); EXPECT_TRUE(storage()->IsDisabled()); EXPECT_FALSE(base::DirectoryExists(storage()->GetDiskCachePath())); EXPECT_FALSE(base::DirectoryExists(storage()->GetDatabasePath())); } TEST_F(ServiceWorkerResourceStorageDiskTest, DeleteAndStartOver_UnrelatedFileExists) { EXPECT_FALSE(storage()->IsDisabled()); ASSERT_TRUE(base::DirectoryExists(storage()->GetDiskCachePath())); ASSERT_TRUE(base::DirectoryExists(storage()->GetDatabasePath())); // Create an unrelated file in the database directory to make sure such a file // does not prevent DeleteAndStartOver. base::FilePath file_path; ASSERT_TRUE( base::CreateTemporaryFileInDir(storage()->GetDatabasePath(), &file_path)); ASSERT_TRUE(base::PathExists(file_path)); base::RunLoop run_loop; ServiceWorkerStatusCode status = SERVICE_WORKER_ERROR_MAX_VALUE; storage()->DeleteAndStartOver( base::Bind(&StatusAndQuitCallback, &status, run_loop.QuitClosure())); run_loop.Run(); EXPECT_EQ(SERVICE_WORKER_OK, status); EXPECT_TRUE(storage()->IsDisabled()); EXPECT_FALSE(base::DirectoryExists(storage()->GetDiskCachePath())); EXPECT_FALSE(base::DirectoryExists(storage()->GetDatabasePath())); } TEST_F(ServiceWorkerResourceStorageDiskTest, DeleteAndStartOver_OpenedFileExists) { EXPECT_FALSE(storage()->IsDisabled()); ASSERT_TRUE(base::DirectoryExists(storage()->GetDiskCachePath())); ASSERT_TRUE(base::DirectoryExists(storage()->GetDatabasePath())); // Create an unrelated opened file in the database directory to make sure such // a file does not prevent DeleteAndStartOver on non-Windows platforms. base::FilePath file_path; base::ScopedFILE file(base::CreateAndOpenTemporaryFileInDir( storage()->GetDatabasePath(), &file_path)); ASSERT_TRUE(file); ASSERT_TRUE(base::PathExists(file_path)); base::RunLoop run_loop; ServiceWorkerStatusCode status = SERVICE_WORKER_ERROR_MAX_VALUE; storage()->DeleteAndStartOver( base::Bind(&StatusAndQuitCallback, &status, run_loop.QuitClosure())); run_loop.Run(); #if defined(OS_WIN) // On Windows, deleting the directory containing an opened file should fail. EXPECT_EQ(SERVICE_WORKER_ERROR_FAILED, status); EXPECT_TRUE(storage()->IsDisabled()); EXPECT_TRUE(base::DirectoryExists(storage()->GetDiskCachePath())); EXPECT_TRUE(base::DirectoryExists(storage()->GetDatabasePath())); #else EXPECT_EQ(SERVICE_WORKER_OK, status); EXPECT_TRUE(storage()->IsDisabled()); EXPECT_FALSE(base::DirectoryExists(storage()->GetDiskCachePath())); EXPECT_FALSE(base::DirectoryExists(storage()->GetDatabasePath())); #endif } TEST_F(ServiceWorkerResourceStorageTest, UpdateRegistration) { // Promote the worker to active worker and add a controllee. registration_->SetActiveVersion(registration_->waiting_version()); storage()->UpdateToActiveState( registration_.get(), base::Bind(&ServiceWorkerUtils::NoOpStatusCallback)); scoped_ptr<ServiceWorkerProviderHost> host(new ServiceWorkerProviderHost( 33 /* dummy render process id */, MSG_ROUTING_NONE, 1 /* dummy provider_id */, SERVICE_WORKER_PROVIDER_FOR_WINDOW, context()->AsWeakPtr(), NULL)); registration_->active_version()->AddControllee(host.get()); bool was_called = false; ServiceWorkerStatusCode result = SERVICE_WORKER_ERROR_FAILED; std::set<int64_t> verify_ids; // Make an updated registration. scoped_refptr<ServiceWorkerVersion> live_version = new ServiceWorkerVersion( registration_.get(), script_, storage()->NewVersionId(), context()->AsWeakPtr()); live_version->SetStatus(ServiceWorkerVersion::NEW); registration_->SetWaitingVersion(live_version); std::vector<ServiceWorkerDatabase::ResourceRecord> records; records.push_back(ServiceWorkerDatabase::ResourceRecord( 10, live_version->script_url(), 100)); live_version->script_cache_map()->SetResources(records); // Writing the registration should move the old version's resources to the // purgeable list but keep them available. storage()->StoreRegistration( registration_.get(), registration_->waiting_version(), base::Bind(&VerifyPurgeableListStatusCallback, base::Unretained(storage()->database_.get()), &verify_ids, &was_called, &result)); base::RunLoop().RunUntilIdle(); ASSERT_TRUE(was_called); EXPECT_EQ(SERVICE_WORKER_OK, result); EXPECT_EQ(2u, verify_ids.size()); verify_ids.clear(); EXPECT_EQ(ServiceWorkerDatabase::STATUS_OK, storage()->database_->GetPurgeableResourceIds(&verify_ids)); EXPECT_EQ(2u, verify_ids.size()); EXPECT_TRUE(VerifyBasicResponse(storage(), resource_id1_, false)); EXPECT_TRUE(VerifyBasicResponse(storage(), resource_id2_, false)); // Removing the controllee should cause the old version's resources to be // deleted. registration_->active_version()->RemoveControllee(host.get()); registration_->active_version()->Doom(); base::RunLoop().RunUntilIdle(); verify_ids.clear(); EXPECT_EQ(ServiceWorkerDatabase::STATUS_OK, storage()->database_->GetPurgeableResourceIds(&verify_ids)); EXPECT_TRUE(verify_ids.empty()); EXPECT_FALSE(VerifyBasicResponse(storage(), resource_id1_, false)); EXPECT_FALSE(VerifyBasicResponse(storage(), resource_id2_, false)); } TEST_F(ServiceWorkerStorageTest, FindRegistration_LongestScopeMatch) { const GURL kDocumentUrl("http://www.example.com/scope/foo"); scoped_refptr<ServiceWorkerRegistration> found_registration; // Registration for "/scope/". const GURL kScope1("http://www.example.com/scope/"); const GURL kScript1("http://www.example.com/script1.js"); const int64_t kRegistrationId1 = 1; const int64_t kVersionId1 = 1; scoped_refptr<ServiceWorkerRegistration> live_registration1 = new ServiceWorkerRegistration(kScope1, kRegistrationId1, context()->AsWeakPtr()); scoped_refptr<ServiceWorkerVersion> live_version1 = new ServiceWorkerVersion( live_registration1.get(), kScript1, kVersionId1, context()->AsWeakPtr()); std::vector<ServiceWorkerDatabase::ResourceRecord> records1; records1.push_back(ServiceWorkerDatabase::ResourceRecord( 1, live_version1->script_url(), 100)); live_version1->script_cache_map()->SetResources(records1); live_version1->SetStatus(ServiceWorkerVersion::INSTALLED); live_registration1->SetWaitingVersion(live_version1); // Registration for "/scope/foo". const GURL kScope2("http://www.example.com/scope/foo"); const GURL kScript2("http://www.example.com/script2.js"); const int64_t kRegistrationId2 = 2; const int64_t kVersionId2 = 2; scoped_refptr<ServiceWorkerRegistration> live_registration2 = new ServiceWorkerRegistration(kScope2, kRegistrationId2, context()->AsWeakPtr()); scoped_refptr<ServiceWorkerVersion> live_version2 = new ServiceWorkerVersion( live_registration2.get(), kScript2, kVersionId2, context()->AsWeakPtr()); std::vector<ServiceWorkerDatabase::ResourceRecord> records2; records2.push_back(ServiceWorkerDatabase::ResourceRecord( 2, live_version2->script_url(), 100)); live_version2->script_cache_map()->SetResources(records2); live_version2->SetStatus(ServiceWorkerVersion::INSTALLED); live_registration2->SetWaitingVersion(live_version2); // Registration for "/scope/foobar". const GURL kScope3("http://www.example.com/scope/foobar"); const GURL kScript3("http://www.example.com/script3.js"); const int64_t kRegistrationId3 = 3; const int64_t kVersionId3 = 3; scoped_refptr<ServiceWorkerRegistration> live_registration3 = new ServiceWorkerRegistration(kScope3, kRegistrationId3, context()->AsWeakPtr()); scoped_refptr<ServiceWorkerVersion> live_version3 = new ServiceWorkerVersion( live_registration3.get(), kScript3, kVersionId3, context()->AsWeakPtr()); std::vector<ServiceWorkerDatabase::ResourceRecord> records3; records3.push_back(ServiceWorkerDatabase::ResourceRecord( 3, live_version3->script_url(), 100)); live_version3->script_cache_map()->SetResources(records3); live_version3->SetStatus(ServiceWorkerVersion::INSTALLED); live_registration3->SetWaitingVersion(live_version3); // Notify storage of they being installed. storage()->NotifyInstallingRegistration(live_registration1.get()); storage()->NotifyInstallingRegistration(live_registration2.get()); storage()->NotifyInstallingRegistration(live_registration3.get()); // Find a registration among installing ones. EXPECT_EQ(SERVICE_WORKER_OK, FindRegistrationForDocument(kDocumentUrl, &found_registration)); EXPECT_EQ(live_registration2, found_registration); found_registration = NULL; // Store registrations. EXPECT_EQ(SERVICE_WORKER_OK, StoreRegistration(live_registration1, live_version1)); EXPECT_EQ(SERVICE_WORKER_OK, StoreRegistration(live_registration2, live_version2)); EXPECT_EQ(SERVICE_WORKER_OK, StoreRegistration(live_registration3, live_version3)); // Notify storage of installations no longer happening. storage()->NotifyDoneInstallingRegistration( live_registration1.get(), NULL, SERVICE_WORKER_OK); storage()->NotifyDoneInstallingRegistration( live_registration2.get(), NULL, SERVICE_WORKER_OK); storage()->NotifyDoneInstallingRegistration( live_registration3.get(), NULL, SERVICE_WORKER_OK); // Find a registration among installed ones. EXPECT_EQ(SERVICE_WORKER_OK, FindRegistrationForDocument(kDocumentUrl, &found_registration)); EXPECT_EQ(live_registration2, found_registration); } class ServiceWorkerStorageDiskTest : public ServiceWorkerStorageTest { public: void SetUp() override { ASSERT_TRUE(InitUserDataDirectory()); ServiceWorkerStorageTest::SetUp(); } }; TEST_F(ServiceWorkerStorageDiskTest, OriginHasForeignFetchRegistrations) { LazyInitialize(); // Registration 1 for http://www.example.com const GURL kScope1("http://www.example.com/scope/"); const GURL kScript1("http://www.example.com/script1.js"); const int64_t kRegistrationId1 = 1; const int64_t kVersionId1 = 1; scoped_refptr<ServiceWorkerRegistration> live_registration1 = new ServiceWorkerRegistration(kScope1, kRegistrationId1, context()->AsWeakPtr()); scoped_refptr<ServiceWorkerVersion> live_version1 = new ServiceWorkerVersion( live_registration1.get(), kScript1, kVersionId1, context()->AsWeakPtr()); std::vector<ServiceWorkerDatabase::ResourceRecord> records1; records1.push_back(ServiceWorkerDatabase::ResourceRecord( 1, live_version1->script_url(), 100)); live_version1->script_cache_map()->SetResources(records1); live_version1->SetStatus(ServiceWorkerVersion::INSTALLED); live_version1->set_foreign_fetch_scopes(std::vector<GURL>(1, kScope1)); live_registration1->SetWaitingVersion(live_version1); // Registration 2 for http://www.example.com const GURL kScope2("http://www.example.com/scope/foo"); const GURL kScript2("http://www.example.com/script2.js"); const int64_t kRegistrationId2 = 2; const int64_t kVersionId2 = 2; scoped_refptr<ServiceWorkerRegistration> live_registration2 = new ServiceWorkerRegistration(kScope2, kRegistrationId2, context()->AsWeakPtr()); scoped_refptr<ServiceWorkerVersion> live_version2 = new ServiceWorkerVersion( live_registration2.get(), kScript2, kVersionId2, context()->AsWeakPtr()); std::vector<ServiceWorkerDatabase::ResourceRecord> records2; records2.push_back(ServiceWorkerDatabase::ResourceRecord( 2, live_version2->script_url(), 100)); live_version2->script_cache_map()->SetResources(records2); live_version2->SetStatus(ServiceWorkerVersion::INSTALLED); live_version2->set_foreign_fetch_scopes(std::vector<GURL>(1, kScope2)); live_registration2->SetWaitingVersion(live_version2); // Registration for http://www.test.com const GURL kScope3("http://www.test.com/scope/foobar"); const GURL kScript3("http://www.test.com/script3.js"); const int64_t kRegistrationId3 = 3; const int64_t kVersionId3 = 3; scoped_refptr<ServiceWorkerRegistration> live_registration3 = new ServiceWorkerRegistration(kScope3, kRegistrationId3, context()->AsWeakPtr()); scoped_refptr<ServiceWorkerVersion> live_version3 = new ServiceWorkerVersion( live_registration3.get(), kScript3, kVersionId3, context()->AsWeakPtr()); std::vector<ServiceWorkerDatabase::ResourceRecord> records3; records3.push_back(ServiceWorkerDatabase::ResourceRecord( 3, live_version3->script_url(), 100)); live_version3->script_cache_map()->SetResources(records3); live_version3->SetStatus(ServiceWorkerVersion::INSTALLED); live_registration3->SetWaitingVersion(live_version3); // Neither origin should have registrations before they are stored. const GURL kOrigin1 = kScope1.GetOrigin(); const GURL kOrigin2 = kScope3.GetOrigin(); EXPECT_FALSE(storage()->OriginHasForeignFetchRegistrations(kOrigin1)); EXPECT_FALSE(storage()->OriginHasForeignFetchRegistrations(kOrigin2)); // Store all registrations. EXPECT_EQ(SERVICE_WORKER_OK, StoreRegistration(live_registration1, live_version1)); EXPECT_EQ(SERVICE_WORKER_OK, StoreRegistration(live_registration2, live_version2)); EXPECT_EQ(SERVICE_WORKER_OK, StoreRegistration(live_registration3, live_version3)); // Now first origin should have foreign fetch registrations, second doesn't. EXPECT_TRUE(storage()->OriginHasForeignFetchRegistrations(kOrigin1)); EXPECT_FALSE(storage()->OriginHasForeignFetchRegistrations(kOrigin2)); // Remove one registration at first origin. EXPECT_EQ(SERVICE_WORKER_OK, DeleteRegistration(kRegistrationId1, kScope1.GetOrigin())); // First origin should still have a registration left. EXPECT_TRUE(storage()->OriginHasForeignFetchRegistrations(kOrigin1)); EXPECT_FALSE(storage()->OriginHasForeignFetchRegistrations(kOrigin2)); // Simulate browser shutdown and restart. live_registration1 = nullptr; live_version1 = nullptr; live_registration2 = nullptr; live_version2 = nullptr; live_registration3 = nullptr; live_version3 = nullptr; InitializeTestHelper(); LazyInitialize(); // First origin should still have a registration left. EXPECT_TRUE(storage()->OriginHasForeignFetchRegistrations(kOrigin1)); EXPECT_FALSE(storage()->OriginHasForeignFetchRegistrations(kOrigin2)); // Remove other registration at first origin. EXPECT_EQ(SERVICE_WORKER_OK, DeleteRegistration(kRegistrationId2, kScope2.GetOrigin())); // No foreign fetch registrations remain. EXPECT_FALSE(storage()->OriginHasForeignFetchRegistrations(kOrigin1)); EXPECT_FALSE(storage()->OriginHasForeignFetchRegistrations(kOrigin2)); } } // namespace content
ds-hwang/chromium-crosswalk
content/browser/service_worker/service_worker_storage_unittest.cc
C++
bsd-3-clause
69,087
[ 30522, 1013, 1013, 9385, 2286, 1996, 10381, 21716, 5007, 6048, 1012, 2035, 2916, 9235, 1012, 1013, 1013, 2224, 1997, 2023, 3120, 3642, 2003, 9950, 2011, 1037, 18667, 2094, 1011, 2806, 6105, 2008, 2064, 2022, 1013, 1013, 2179, 1999, 1996, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
#!/usr/bin/python import sys, os, urllib, argparse, base64, time, threading, re from gi.repository import Gtk, WebKit, Notify webView = None def refresh(widget, event): global webView webView.reload() window_title = '' def HandleTitleChanged(webview, title): global window_title window_title = title parent = webview while parent.get_parent() != None: parent = webview.get_parent() parent.set_title(title) return True def HandleCreateWebView(webview, frame): info = Gtk.Window() info.set_default_size(1000, 700) child = WebKit.WebView() child.connect('create-web-view', HandleCreateWebView) child.connect('close-web-view', HandleCloseWebView) child.connect('navigation-policy-decision-requested', HandleNavigationRequested) #child.connect('notify::title', HandleTitleChanged) info.set_title('') info.add(child) info.show_all() return child def HandleCloseWebView(webview): parent = webview while parent.get_parent() != None: parent = webview.get_parent() parent.destroy() def HandleNewWindowPolicyDecisionRequested(webview, frame, request, navigation_action, policy_decision): if '&URL=' in request.get_uri(): os.system('xdg-open "%s"' % urllib.unquote(request.get_uri().split('&URL=')[1]).decode('utf8')) def HandleNavigationRequested(webview, frame, request, navigation_action, policy_decision): if '&URL=' in request.get_uri(): HandleCloseWebView(webview) return 1 prefills = {} submit = False ignore_submit = [] def prefill_password(webview, frame): global prefills, submit should_ignore_submit = False dom = webview.get_dom_document() forms = dom.get_forms() for i in range(0, forms.get_length()): form = forms.item(i) elements = form.get_elements() is_form_modified = False for j in range(0, elements.get_length()): element = elements.item(j) element_name = element.get_name() if element_name in ignore_submit: should_ignore_submit = True for key in prefills.keys(): if element_name == key: if prefills[key].lower() == 'true': element.set_checked(True) is_form_modified = True else: element.set_value(prefills[key]) is_form_modified = True if is_form_modified and submit and not should_ignore_submit: form.submit() def HandleMimeType(webview, frame, request, mimetype, policy_decision): print 'Requested decision for mimetype:', mimetype return True stop_threads = False search_notifys = [] def SearchNotify(webview): global stop_threads global window_title global search_notifys while True: if stop_threads: break dom = webview.get_dom_document() if not dom: continue body = dom.get_body() if not body: continue body_html = body.get_inner_html() if not body_html: continue for notice in search_notifys: msgs = list(set(re.findall(notice, body_html))) if len(msgs) > 0: for msg in msgs: Notify.init(window_title) msg_notify = Notify.Notification.new(window_title, msg, "dialog-information") msg_notify.show() time.sleep(2) # Don't duplicate the notification time.sleep(2) if __name__ == "__main__": parser_epilog = ("Example:\n\n" "./simple_browse.py https://owa.example.com --useragent=\"Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0\" --stylesheet=~/simple_browse/sample_styles/owa_style.css --username=<webmail username> --b64pass=\"<base64 encoded password>\" --forminput=trusted:true --submit --notify=PHNwYW4gY2xhc3M9Im53SXRtVHh0U2JqIj4oW1x3IF0rKTwvc3Bhbj4=\n\n" "This command will open Outlook Web Access, set the user agent to allow it to \nload using pipelight (for silverlight support), login to webmail, then apply a \ncustom css style to make webmail look like a desktop app. When new emails\narrive, notification will be sent to gnome-shell.\n") parser = argparse.ArgumentParser(description="Simple Browser: A simple webkit browser written in Python", epilog=parser_epilog, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("url") parser.add_argument("--useragent", help="An optional user agent to apply to the main page") parser.add_argument("--stylesheet", help="An optional stylesheet to apply to the main page") parser.add_argument("--username", help="A username we'll try to use to sign in") parser.add_argument("--password", help="A password for signing in") parser.add_argument("--b64pass", help="An alternative b64 encoded password for sign on") parser.add_argument("--forminput", help="A form field name and value to prefill (seperated by a colon). Only one value for each key is allowed.", action='append') parser.add_argument("--submit", help="Submit the filled form when we've finished entering values", action="store_true") parser.add_argument("--ignore-submit", help="Ignore the submit if the form contains this key", action='append') parser.add_argument("--title", help="Title for the window") parser.add_argument("--notify", help="A regex search string, base64 encoded, which will display a notification when found, example: <span class=\"nwItmTxtSbj\">([\w ]+)</span>", action='append') args = parser.parse_args() url = args.url user_agent = None if args.useragent: user_agent = args.useragent stylesheet = None if args.stylesheet: stylesheet = 'file://localhost%s' % os.path.abspath(args.stylesheet) if args.username: prefills['username'] = args.username if args.b64pass: prefills['password'] = base64.b64decode(args.b64pass) elif args.password: prefills['password'] = args.password if args.submit: submit = True if args.forminput: for field in args.forminput: key, value = field.split(':') if key in prefills: parser.print_help() exit(1) prefills[key] = value if args.ignore_submit: ignore_submit.extend(args.ignore_submit) if args.notify: for notice in args.notify: search_notifys.append(base64.b64decode(notice)) win = Gtk.Window() scrolled = Gtk.ScrolledWindow() win.set_default_size(1500, 900) webView = WebKit.WebView() webView.load_uri(url) overlay = Gtk.Overlay() overlay.add(webView) # Apply Settings settings = WebKit.WebSettings() if user_agent: settings.set_property('user-agent', user_agent) settings.set_property('enable-spell-checking', True) if stylesheet: settings.set_property('user-stylesheet-uri', stylesheet) webView.set_settings(settings) # Add Signal handlers to the webview webView.connect('create-web-view', HandleCreateWebView) webView.connect('close-web-view', HandleCloseWebView) webView.connect('new-window-policy-decision-requested', HandleNewWindowPolicyDecisionRequested) webView.connect('navigation-policy-decision-requested', HandleNavigationRequested) #webView.connect('notify::title', HandleTitleChanged) webView.connect('mime-type-policy-decision-requested', HandleMimeType) webView.connect('load-finished', prefill_password) win.set_title('') # Add the Refresh button fixed = Gtk.Fixed() fixed.set_halign(Gtk.Align.START) fixed.set_valign(Gtk.Align.START) overlay.add_overlay(fixed) fixed.show() image = Gtk.Image() image.set_from_pixbuf(Gtk.IconTheme().load_icon('gtk-refresh', 10, 0)) imgevent = Gtk.EventBox() imgevent.add(image) imgevent.connect('button-press-event', refresh) fixed.put(imgevent, 10, 10) win.add(scrolled) scrolled.add(overlay) win.show_all() win.connect('destroy', Gtk.main_quit) if args.title: window_title = args.title win.set_title(args.title) if search_notifys: t = threading.Thread(target=SearchNotify, args=(webView,)) t.start() Gtk.main() stop_threads = True
DavidMulder/simple_browse
simple_browse.py
Python
gpl-2.0
8,391
[ 30522, 1001, 999, 1013, 2149, 2099, 1013, 8026, 1013, 18750, 12324, 25353, 2015, 1010, 9808, 1010, 24471, 6894, 2497, 1010, 12098, 21600, 11650, 2063, 1010, 2918, 21084, 1010, 2051, 1010, 11689, 2075, 1010, 2128, 2013, 21025, 1012, 22409, 1...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
twolistboxes ============ jQuery plugin with two list box method for extended selection of options Demo at http://magaran.com
jtabernik/twolistboxes
README.md
Markdown
mit
128
[ 30522, 2048, 9863, 8758, 2229, 1027, 1027, 1027, 1027, 1027, 1027, 1027, 1027, 1027, 1027, 1027, 1027, 1046, 4226, 2854, 13354, 2378, 2007, 2048, 2862, 3482, 4118, 2005, 3668, 4989, 1997, 7047, 9703, 2012, 8299, 1024, 1013, 1013, 23848, 2...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<!DOCTYPE html> <html> <head> <title>MathJax Dynamic Math Test Page</title> <!-- Copyright (c) 2010-2011 Design Science, Inc. --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" /> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ extensions: ["tex2jax.js"], jax: ["input/TeX","output/HTML-CSS"], }); </script> <script type="text/javascript" src="../MathJax.js"></script> <style> input {margin-top: .7em} .output { border: 1px solid black; padding: 1em; width: auto; position: absolute; top: 0; left: 2em; min-width: 20em; } .box {position: relative} </style> </head> <body> <script> // // Use a closure to hide the local variables from the // global namespace // (function () { var QUEUE = MathJax.Hub.queue; // shorthand for the queue var math = null, box = null; // the element jax for the math output, and the box it's in // // Hide and show the box (so it doesn't flicker as much) // var HIDEBOX = function () {box.style.visibility = "hidden"} var SHOWBOX = function () {box.style.visibility = "visible"} // // Get the element jax when MathJax has produced it. // QUEUE.Push(function () { math = MathJax.Hub.getAllJax("MathOutput")[0]; box = document.getElementById("box"); SHOWBOX(); // box is initially hidden so the braces don't show }); // // The onchange event handler that typesets the // math entered by the user // window.UpdateMath = function (TeX) { QUEUE.Push(HIDEBOX,["Text",math,"\\displaystyle{"+TeX+"}"],SHOWBOX); } // // IE doesn't fire onchange events for RETURN, so // use onkeypress to do a blur (and refocus) to // force the onchange to occur // if (MathJax.Hub.Browser.isMSIE) { window.MathInput.onkeypress = function () { if (window.event && window.event.keyCode === 13) {this.blur(); this.focus()} } } })(); </script> <p> Type some \(\rm\TeX\) code and press RETURN:<br /> <input id="MathInput" size="80" onchange="UpdateMath(this.value)" /> </p> <p>You typed:</p> <div class="box" id="box" style="visibility:hidden"> <div id="MathOutput" class="output">$${}$$</div> </div> </body> </html>
AKSW/SlideWiki
slidewiki/libraries/frontend/MathJax/test/sample-dynamic.html
HTML
apache-2.0
2,399
[ 30522, 1026, 999, 9986, 13874, 16129, 1028, 1026, 16129, 1028, 1026, 2132, 1028, 1026, 2516, 1028, 8785, 3900, 2595, 8790, 8785, 3231, 3931, 1026, 1013, 2516, 1028, 1026, 999, 1011, 1011, 9385, 1006, 1039, 1007, 2230, 1011, 2249, 2640, 26...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
package tcplog import ( "net" "strings" "sync" "testing" "github.com/stretchr/testify/assert" "github.com/vektra/cypress" "github.com/vektra/neko" ) type TestFormatter struct{} func (tf *TestFormatter) Format(m *cypress.Message) ([]byte, error) { return []byte(m.KVString()), nil } func TestRead(t *testing.T) { n := neko.Start(t) var l *Logger n.Setup(func() { l = NewLogger("", false, &TestFormatter{}) }) n.It("reads a byte slice", func() { ok := l.Read([]byte("This is a long line")) assert.NoError(t, ok) }) n.It("reads a string", func() { ok := l.Read("This is a long line") assert.NoError(t, ok) }) n.It("reads a cypress.Message", func() { message := NewMessage(t) ok := l.Read(message) assert.NoError(t, ok) }) n.It("does not read an int", func() { ok := l.Read(1) assert.Error(t, ok) }) n.Meow() } func TestWrite(t *testing.T) { n := neko.Start(t) var ( l *Logger line = []byte("This is a log line") ) n.Setup(func() { l = NewLogger("", false, &TestFormatter{}) }) n.It("adds a log line to the pump", func() { l.write(line) select { case pumpLine := <-l.Pump: assert.Equal(t, line, pumpLine) var zero uint64 = 0 assert.Equal(t, zero, l.PumpDropped) default: t.Fail() } }) n.It("adds an error line to the pump if lines were dropped", func() { l.PumpDropped = 1 l.write(line) select { case <-l.Pump: expected := "The tcplog pump dropped 1 log lines" actual := <-l.Pump assert.True(t, strings.Index(string(actual), expected) != -1) var zero uint64 = 0 assert.Equal(t, zero, l.PumpDropped) default: t.Fail() } }) n.It("does not add a log line and increments dropped counter if pump is full ", func() { l.Pump = make(chan []byte, 0) l.write(line) select { case <-l.Pump: t.Fail() default: var one uint64 = 1 assert.Equal(t, one, l.PumpDropped) } }) n.Meow() } func TestDial(t *testing.T) { s := NewTcpServer() go s.Run("127.0.0.1") l := NewLogger(<-s.Address, false, &TestFormatter{}) conn, _ := l.dial() _, ok := conn.(net.Conn) defer conn.Close() assert.True(t, ok, "returns a connection") } func TestSendLogs(t *testing.T) { n := neko.Start(t) var ( s *TcpServer l *Logger line = []byte("This is a log line") wg sync.WaitGroup ) n.Setup(func() { s = NewTcpServer() wg.Add(1) go func() { defer wg.Done() s.Run("127.0.0.1") }() l = NewLogger(<-s.Address, false, &TestFormatter{}) wg.Add(1) go func() { defer wg.Done() l.sendLogs() }() }) n.It("sends line from pipe to tcp server", func() { l.Pump <- line close(l.Pump) wg.Wait() select { case message := <-s.Messages: assert.Equal(t, string(line), string(message)) default: t.Fail() } }) n.Meow() }
vektra/addons
lib/tcplog/tcplog_test.go
GO
bsd-3-clause
2,811
[ 30522, 7427, 22975, 24759, 8649, 12324, 1006, 1000, 5658, 1000, 1000, 7817, 1000, 1000, 26351, 1000, 1000, 5604, 1000, 1000, 21025, 2705, 12083, 1012, 4012, 1013, 7683, 2099, 1013, 19919, 1013, 20865, 1000, 1000, 21025, 2705, 12083, 1012, 4...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* * Author: MontaVista Software, Inc. <source@mvista.com> * * 2005 (c) MontaVista Software, Inc. This file is licensed under * the terms of the GNU General Public License version 2. This program * is licensed "as is" without any warranty of any kind, whether express * or implied. */ #include <linux/init.h> #include <linux/mvl_patch.h> static __init int regpatch(void) { return mvl_register_patch(273); } module_init(regpatch);
fzqing/linux-2.6
mvl_patches/pro-0273.c
C
gpl-2.0
446
[ 30522, 1013, 1008, 1008, 3166, 1024, 18318, 18891, 9153, 4007, 1010, 4297, 1012, 1026, 3120, 1030, 19842, 11921, 1012, 4012, 1028, 1008, 1008, 2384, 1006, 1039, 1007, 30524, 2003, 7000, 1000, 2004, 2003, 1000, 2302, 2151, 10943, 2100, 1997,...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<!-- ignore the following lines, they are not important to this demo --> <jigsaw-demo-description [summary]="summary" [content]="description"> </jigsaw-demo-description> <!-- start to learn the demo from here --> <jigsaw-header [level]="2">演示步骤条的添加和删除节点的方法</jigsaw-header> <jigsaw-steps #jigsawSteps class="steps" [data]="data" (add)="addHandler($event)" (remove)="removeHandler($event)" (titleChange)="titleChangeHandler($event)"></jigsaw-steps> <div style="margin-top: 10px;"> 节点索引:<jigsaw-numeric-input [(value)]="deleteIndex" min="0" [max]="data.length - 1"></jigsaw-numeric-input> <jigsaw-button (click)="delete()" colorType="warning">删除</jigsaw-button> <jigsaw-button (click)="add()" colorType="primary" style="margin-left: 20px;">添加</jigsaw-button> <jigsaw-button (click)="rename()" colorType="primary" style="margin-left: 20px;">修改</jigsaw-button> </div>
rdkmaster/jigsaw
src/app/demo/pc/steps/events/demo.component.html
HTML
mit
949
[ 30522, 1026, 999, 1011, 1011, 8568, 1996, 2206, 3210, 1010, 2027, 2024, 2025, 2590, 2000, 2023, 9703, 1011, 1011, 1028, 1026, 10147, 5620, 10376, 1011, 9703, 1011, 6412, 1031, 12654, 1033, 1027, 1000, 12654, 1000, 1031, 4180, 1033, 1027, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
# -*- coding: utf-8 -*- # Generated by Django 1.10.8 on 2018-09-24 19:38 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('controlled_vocabularies', '0001_initial'), ] operations = [ migrations.AlterField( model_name='property', name='label', field=models.TextField(help_text=b'The value for the added property.'), ), migrations.AlterField( model_name='property', name='property_name', field=models.CharField(choices=[(b'definition', b'Definition'), (b'description', b'Description'), (b'note', b'Note'), (b'system', b'System')], help_text=b"The name of the added property; e.g., 'Description'.", max_length=50, verbose_name=b'Property Type'), ), migrations.AlterField( model_name='term', name='label', field=models.CharField(help_text=b'The human-readable name of the term.', max_length=255), ), migrations.AlterField( model_name='term', name='name', field=models.CharField(help_text=b'The name or key that uniquely identifies the term within the vocabulary.', max_length=50), ), migrations.AlterField( model_name='term', name='order', field=models.IntegerField(blank=True, help_text=b'The preferred order for viewing the term in the vocabulary.', null=True), ), migrations.AlterField( model_name='term', name='vocab_list', field=models.ForeignKey(help_text=b'The vocabulary that the term needs to be added to.', on_delete=django.db.models.deletion.CASCADE, to='controlled_vocabularies.Vocabulary', verbose_name=b'Vocabulary'), ), migrations.AlterField( model_name='vocabulary', name='definition', field=models.TextField(blank=True, help_text=b'A brief statement of the meaning of the vocabulary.'), ), migrations.AlterField( model_name='vocabulary', name='label', field=models.CharField(help_text=b'The human-readable name of the vocabulary.', max_length=255), ), migrations.AlterField( model_name='vocabulary', name='maintainer', field=models.CharField(help_text=b'The person responsible for creating and updating the vocabulary.', max_length=50), ), migrations.AlterField( model_name='vocabulary', name='maintainerEmail', field=models.CharField(help_text=b'E-mail address of maintainer.', max_length=50, verbose_name=b'Maintainer E-mail'), ), migrations.AlterField( model_name='vocabulary', name='name', field=models.CharField(help_text=b'The name or key that uniquely identifies the vocabulary.', max_length=50, unique=True), ), migrations.AlterField( model_name='vocabulary', name='order', field=models.CharField(choices=[(b'name', b'name'), (b'label', b'label'), (b'order', b'order')], help_text=b'The preferred order for viewing the UNTL list of controlled vocabularies.', max_length=10), ), ]
unt-libraries/django-controlled-vocabularies
controlled_vocabularies/migrations/0002_auto_20180924_1938.py
Python
bsd-3-clause
3,376
[ 30522, 1001, 1011, 1008, 1011, 16861, 1024, 21183, 2546, 1011, 1022, 1011, 1008, 1011, 1001, 7013, 2011, 6520, 23422, 1015, 30524, 2013, 6520, 23422, 1012, 16962, 12324, 9230, 2015, 1010, 4275, 12324, 6520, 23422, 1012, 16962, 1012, 4275, 1...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
// ----------------------------------------------------------------------------------------- // <copyright file="TableSasUnitTests.cs" company="Microsoft"> // Copyright 2013 Microsoft 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. // </copyright> // ----------------------------------------------------------------------------------------- using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Auth; using Microsoft.WindowsAzure.Storage.Shared.Protocol; using Microsoft.WindowsAzure.Storage.Table.Entities; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Threading; using System.Xml.Linq; namespace Microsoft.WindowsAzure.Storage.Table { #pragma warning disable 0618 [TestClass] public class TableSasUnitTests : TableTestBase { #region Locals + Ctors public TableSasUnitTests() { } private TestContext testContextInstance; /// <summary> ///Gets or sets the test context which provides ///information about and functionality for the current test run. ///</summary> public TestContext TestContext { get { return testContextInstance; } set { testContextInstance = value; } } #endregion #region Additional test attributes // // You can use the following additional attributes as you write your tests: // // Use ClassInitialize to run code before running the first test in the class // [ClassInitialize()] // public static void MyClassInitialize(TestContext testContext) { } // // Use ClassCleanup to run code after all tests in a class have run // [ClassCleanup()] // public static void MyClassCleanup() { } // // Use TestInitialize to run code before running each test // // // Use TestInitialize to run code before running each test [TestInitialize()] public void MyTestInitialize() { if (TestBase.TableBufferManager != null) { TestBase.TableBufferManager.OutstandingBufferCount = 0; } } // // Use TestCleanup to run code after each test has run [TestCleanup()] public void MyTestCleanup() { if (TestBase.TableBufferManager != null) { Assert.AreEqual(0, TestBase.TableBufferManager.OutstandingBufferCount); } } #endregion #region Constructor Tests [TestMethod] [Description("Test TableSas via various constructors")] [TestCategory(ComponentCategory.Table)] [TestCategory(TestTypeCategory.UnitTest)] [TestCategory(SmokeTestCategory.NonSmoke)] [TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)] public void TableSASConstructors() { CloudTableClient tableClient = GenerateCloudTableClient(); CloudTable table = tableClient.GetTableReference("T" + Guid.NewGuid().ToString("N")); try { table.Create(); table.Execute(TableOperation.Insert(new BaseEntity("PK", "RK"))); // Prepare SAS authentication with full permissions string sasToken = table.GetSharedAccessSignature( new SharedAccessTablePolicy { Permissions = SharedAccessTablePermissions.Add | SharedAccessTablePermissions.Delete | SharedAccessTablePermissions.Query, SharedAccessExpiryTime = DateTimeOffset.Now.AddMinutes(30) }, null /* accessPolicyIdentifier */, null /* startPk */, null /* startRk */, null /* endPk */, null /* endRk */); CloudStorageAccount sasAccount; StorageCredentials sasCreds; CloudTableClient sasClient; CloudTable sasTable; Uri baseUri = new Uri(TestBase.TargetTenantConfig.TableServiceEndpoint); // SAS via connection string parse sasAccount = CloudStorageAccount.Parse(string.Format("TableEndpoint={0};SharedAccessSignature={1}", baseUri.AbsoluteUri, sasToken)); sasClient = sasAccount.CreateCloudTableClient(); sasTable = sasClient.GetTableReference(table.Name); Assert.AreEqual(1, sasTable.ExecuteQuery(new TableQuery<BaseEntity>()).Count()); // SAS via account constructor sasCreds = new StorageCredentials(sasToken); sasAccount = new CloudStorageAccount(sasCreds, null, null, baseUri, null); sasClient = sasAccount.CreateCloudTableClient(); sasTable = sasClient.GetTableReference(table.Name); Assert.AreEqual(1, sasTable.ExecuteQuery(new TableQuery<BaseEntity>()).Count()); // SAS via client constructor URI + Creds sasCreds = new StorageCredentials(sasToken); sasClient = new CloudTableClient(baseUri, sasCreds); sasTable = sasClient.GetTableReference(table.Name); Assert.AreEqual(1, sasTable.ExecuteQuery(new TableQuery<BaseEntity>()).Count()); // SAS via CloudTable constructor Uri + Client sasCreds = new StorageCredentials(sasToken); sasTable = new CloudTable(table.Uri, tableClient.Credentials); sasClient = sasTable.ServiceClient; Assert.AreEqual(1, sasTable.ExecuteQuery(new TableQuery<BaseEntity>()).Count()); } finally { table.DeleteIfExists(); } } #endregion #region Permissions [TestMethod] [Description("Tests setting and getting table permissions")] [TestCategory(ComponentCategory.Table)] [TestCategory(TestTypeCategory.UnitTest)] [TestCategory(SmokeTestCategory.NonSmoke)] [TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)] public void TableSetGetPermissions() { CloudTableClient tableClient = GenerateCloudTableClient(); CloudTable table = tableClient.GetTableReference("T" + Guid.NewGuid().ToString("N")); try { table.Create(); table.Execute(TableOperation.Insert(new BaseEntity("PK", "RK"))); TablePermissions expectedPermissions = new TablePermissions(); TablePermissions testPermissions = table.GetPermissions(); AssertPermissionsEqual(expectedPermissions, testPermissions); // Add a policy, check setting and getting. expectedPermissions.SharedAccessPolicies.Add(Guid.NewGuid().ToString(), new SharedAccessTablePolicy { Permissions = SharedAccessTablePermissions.Query, SharedAccessStartTime = DateTimeOffset.Now - TimeSpan.FromHours(1), SharedAccessExpiryTime = DateTimeOffset.Now + TimeSpan.FromHours(1) }); table.SetPermissions(expectedPermissions); Thread.Sleep(30 * 1000); testPermissions = table.GetPermissions(); AssertPermissionsEqual(expectedPermissions, testPermissions); } finally { table.DeleteIfExists(); } } [TestMethod] [Description("Tests Null Access Policy")] [TestCategory(ComponentCategory.Table)] [TestCategory(TestTypeCategory.UnitTest)] [TestCategory(SmokeTestCategory.NonSmoke)] [TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)] public void TableSASNullAccessPolicy() { CloudTableClient tableClient = GenerateCloudTableClient(); CloudTable table = tableClient.GetTableReference("T" + Guid.NewGuid().ToString("N")); try { table.Create(); table.Execute(TableOperation.Insert(new BaseEntity("PK", "RK"))); TablePermissions expectedPermissions = new TablePermissions(); // Add a policy expectedPermissions.SharedAccessPolicies.Add(Guid.NewGuid().ToString(), new SharedAccessTablePolicy { Permissions = SharedAccessTablePermissions.Query | SharedAccessTablePermissions.Add, SharedAccessStartTime = DateTimeOffset.Now - TimeSpan.FromHours(1), SharedAccessExpiryTime = DateTimeOffset.Now + TimeSpan.FromHours(1) }); table.SetPermissions(expectedPermissions); Thread.Sleep(30 * 1000); // Generate the sasToken the user should use string sasToken = table.GetSharedAccessSignature(null, expectedPermissions.SharedAccessPolicies.First().Key, "AAAA", null, "AAAA", null); CloudTable sasTable = new CloudTable(table.Uri, new StorageCredentials(sasToken)); sasTable.Execute(TableOperation.Insert(new DynamicTableEntity("AAAA", "foo"))); TableResult result = sasTable.Execute(TableOperation.Retrieve("AAAA", "foo")); Assert.IsNotNull(result.Result); // revoke table permissions table.SetPermissions(new TablePermissions()); Thread.Sleep(30 * 1000); OperationContext opContext = new OperationContext(); try { sasTable.Execute(TableOperation.Insert(new DynamicTableEntity("AAAA", "foo2")), null, opContext); Assert.Fail(); } catch (Exception) { Assert.AreEqual(opContext.LastResult.HttpStatusCode, (int)HttpStatusCode.Forbidden); } opContext = new OperationContext(); try { result = sasTable.Execute(TableOperation.Retrieve("AAAA", "foo"), null, opContext); Assert.Fail(); } catch (Exception) { Assert.AreEqual(opContext.LastResult.HttpStatusCode, (int)HttpStatusCode.Forbidden); } } finally { table.DeleteIfExists(); } } #endregion #region SAS Operations [TestMethod] [Description("Tests table SAS with query permissions.")] [TestCategory(ComponentCategory.Table)] [TestCategory(TestTypeCategory.UnitTest)] [TestCategory(SmokeTestCategory.NonSmoke)] [TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)] public void TableSasQueryTestSync() { TestTableSas(SharedAccessTablePermissions.Query); } [TestMethod] [Description("Tests table SAS with delete permissions.")] [TestCategory(ComponentCategory.Table)] [TestCategory(TestTypeCategory.UnitTest)] [TestCategory(SmokeTestCategory.NonSmoke)] [TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)] public void TableSasDeleteTestSync() { TestTableSas(SharedAccessTablePermissions.Delete); } [TestMethod] [Description("Tests table SAS with process and update permissions.")] [TestCategory(ComponentCategory.Table)] [TestCategory(TestTypeCategory.UnitTest)] [TestCategory(SmokeTestCategory.NonSmoke)] [TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)] public void TableSasUpdateTestSync() { TestTableSas(SharedAccessTablePermissions.Update); } [TestMethod] [Description("Tests table SAS with add permissions.")] [TestCategory(ComponentCategory.Table)] [TestCategory(TestTypeCategory.UnitTest)] [TestCategory(SmokeTestCategory.NonSmoke)] [TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)] public void TableSasAddTestSync() { TestTableSas(SharedAccessTablePermissions.Add); } [TestMethod] [Description("Tests table SAS with full permissions.")] [TestCategory(ComponentCategory.Table)] [TestCategory(TestTypeCategory.UnitTest)] [TestCategory(SmokeTestCategory.NonSmoke)] [TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)] public void TableSasFullTestSync() { TestTableSas(SharedAccessTablePermissions.Query | SharedAccessTablePermissions.Delete | SharedAccessTablePermissions.Update | SharedAccessTablePermissions.Add); } /// <summary> /// Tests table access permissions with SAS, using a stored policy and using permissions on the URI. /// Various table range constraints are tested. /// </summary> /// <param name="accessPermissions">The permissions to test.</param> internal void TestTableSas(SharedAccessTablePermissions accessPermissions) { string startPk = "M"; string startRk = "F"; string endPk = "S"; string endRk = "T"; // No ranges specified TestTableSasWithRange(accessPermissions, null, null, null, null); // All ranges specified TestTableSasWithRange(accessPermissions, startPk, startRk, endPk, endRk); // StartPk & StartRK specified TestTableSasWithRange(accessPermissions, startPk, startRk, null, null); // StartPk specified TestTableSasWithRange(accessPermissions, startPk, null, null, null); // EndPk & EndRK specified TestTableSasWithRange(accessPermissions, null, null, endPk, endRk); // EndPk specified TestTableSasWithRange(accessPermissions, null, null, endPk, null); // StartPk and EndPk specified TestTableSasWithRange(accessPermissions, startPk, null, endPk, null); // StartRk and StartRK and EndPk specified TestTableSasWithRange(accessPermissions, startPk, startRk, endPk, null); // StartRk and EndPK and EndPk specified TestTableSasWithRange(accessPermissions, startPk, null, endPk, endRk); } /// <summary> /// Tests table access permissions with SAS, using a stored policy and using permissions on the URI. /// </summary> /// <param name="accessPermissions">The permissions to test.</param> /// <param name="startPk">The start partition key range.</param> /// <param name="startRk">The start row key range.</param> /// <param name="endPk">The end partition key range.</param> /// <param name="endRk">The end row key range.</param> internal void TestTableSasWithRange( SharedAccessTablePermissions accessPermissions, string startPk, string startRk, string endPk, string endRk) { CloudTableClient tableClient = GenerateCloudTableClient(); CloudTable table = tableClient.GetTableReference("T" + Guid.NewGuid().ToString("N")); try { table.Create(); // Set up a policy string identifier = Guid.NewGuid().ToString(); TablePermissions permissions = new TablePermissions(); permissions.SharedAccessPolicies.Add(identifier, new SharedAccessTablePolicy { Permissions = accessPermissions, SharedAccessExpiryTime = DateTimeOffset.Now.AddDays(1) }); table.SetPermissions(permissions); Thread.Sleep(30 * 1000); // Prepare SAS authentication using access identifier string sasString = table.GetSharedAccessSignature(new SharedAccessTablePolicy(), identifier, startPk, startRk, endPk, endRk); CloudTableClient identifierSasClient = new CloudTableClient(tableClient.BaseUri, new StorageCredentials(sasString)); // Prepare SAS authentication using explicit policy sasString = table.GetSharedAccessSignature( new SharedAccessTablePolicy { Permissions = accessPermissions, SharedAccessExpiryTime = DateTimeOffset.Now.AddMinutes(30) }, null, startPk, startRk, endPk, endRk); CloudTableClient explicitSasClient = new CloudTableClient(tableClient.BaseUri, new StorageCredentials(sasString)); // Point query TestPointQuery(identifierSasClient, table.Name, accessPermissions, startPk, startRk, endPk, endRk); TestPointQuery(explicitSasClient, table.Name, accessPermissions, startPk, startRk, endPk, endRk); // Add row TestAdd(identifierSasClient, table.Name, accessPermissions, startPk, startRk, endPk, endRk); TestAdd(explicitSasClient, table.Name, accessPermissions, startPk, startRk, endPk, endRk); // Update row (merge) TestUpdateMerge(identifierSasClient, table.Name, accessPermissions, startPk, startRk, endPk, endRk); TestUpdateMerge(explicitSasClient, table.Name, accessPermissions, startPk, startRk, endPk, endRk); // Update row (replace) TestUpdateReplace(identifierSasClient, table.Name, accessPermissions, startPk, startRk, endPk, endRk); TestUpdateReplace(explicitSasClient, table.Name, accessPermissions, startPk, startRk, endPk, endRk); // Delete row TestDelete(identifierSasClient, table.Name, accessPermissions, startPk, startRk, endPk, endRk); TestDelete(explicitSasClient, table.Name, accessPermissions, startPk, startRk, endPk, endRk); // Upsert row (merge) TestUpsertMerge(identifierSasClient, table.Name, accessPermissions, startPk, startRk, endPk, endRk); TestUpsertMerge(explicitSasClient, table.Name, accessPermissions, startPk, startRk, endPk, endRk); // Upsert row (replace) TestUpsertReplace(identifierSasClient, table.Name, accessPermissions, startPk, startRk, endPk, endRk); TestUpsertReplace(explicitSasClient, table.Name, accessPermissions, startPk, startRk, endPk, endRk); } finally { table.DeleteIfExists(); } } /// <summary> /// Test point queries entities inside and outside the given range. /// </summary> /// <param name="testClient">The table client to test.</param> /// <param name="tableName">The name of the table to test.</param> /// <param name="accessPermissions">The access permissions of the table client.</param> /// <param name="startPk">The start partition key range.</param> /// <param name="startRk">The start row key range.</param> /// <param name="endPk">The end partition key range.</param> /// <param name="endRk">The end row key range.</param> private void TestPointQuery( CloudTableClient testClient, string tableName, SharedAccessTablePermissions accessPermissions, string startPk, string startRk, string endPk, string endRk) { bool expectSuccess = ((accessPermissions & SharedAccessTablePermissions.Query) != 0); Action<BaseEntity, OperationContext> queryDelegate = (tableEntity, ctx) => { TableResult retrieveResult = testClient.GetTableReference(tableName).Execute(TableOperation.Retrieve<BaseEntity>(tableEntity.PartitionKey, tableEntity.RowKey), null, ctx); if (expectSuccess) { Assert.IsNotNull(retrieveResult.Result); } else { Assert.AreEqual(ctx.LastResult.HttpStatusCode, (int)HttpStatusCode.OK); } }; // Perform test TestOperationWithRange( tableName, startPk, startRk, endPk, endRk, queryDelegate, "point query", expectSuccess, expectSuccess ? HttpStatusCode.OK : HttpStatusCode.NotFound, false, expectSuccess); } /// <summary> /// Test update (merge) on entities inside and outside the given range. /// </summary> /// <param name="testClient">The table client to test.</param> /// <param name="tableName">The name of the table to test.</param> /// <param name="accessPermissions">The access permissions of the table client.</param> /// <param name="startPk">The start partition key range.</param> /// <param name="startRk">The start row key range.</param> /// <param name="endPk">The end partition key range.</param> /// <param name="endRk">The end row key range.</param> private void TestUpdateMerge( CloudTableClient testClient, string tableName, SharedAccessTablePermissions accessPermissions, string startPk, string startRk, string endPk, string endRk) { Action<BaseEntity, OperationContext> updateDelegate = (tableEntity, ctx) => { // Merge entity tableEntity.A = "10"; tableEntity.ETag = "*"; testClient.GetTableReference(tableName).Execute(TableOperation.Merge(tableEntity), null, ctx); }; bool expectSuccess = (accessPermissions & SharedAccessTablePermissions.Update) != 0; // Perform test TestOperationWithRange( tableName, startPk, startRk, endPk, endRk, updateDelegate, "update merge", expectSuccess, expectSuccess ? HttpStatusCode.NoContent : HttpStatusCode.Forbidden); } /// <summary> /// Test update (replace) on entities inside and outside the given range. /// </summary> /// <param name="testClient">The table client to test.</param> /// <param name="tableName">The name of the table to test.</param> /// <param name="accessPermissions">The access permissions of the table client.</param> /// <param name="startPk">The start partition key range.</param> /// <param name="startRk">The start row key range.</param> /// <param name="endPk">The end partition key range.</param> /// <param name="endRk">The end row key range.</param> private void TestUpdateReplace( CloudTableClient testClient, string tableName, SharedAccessTablePermissions accessPermissions, string startPk, string startRk, string endPk, string endRk) { Action<BaseEntity, OperationContext> updateDelegate = (tableEntity, ctx) => { // replace entity tableEntity.A = "20"; tableEntity.ETag = "*"; testClient.GetTableReference(tableName).Execute(TableOperation.Replace(tableEntity), null, ctx); }; bool expectSuccess = (accessPermissions & SharedAccessTablePermissions.Update) != 0; // Perform test TestOperationWithRange( tableName, startPk, startRk, endPk, endRk, updateDelegate, "update replace", expectSuccess, expectSuccess ? HttpStatusCode.NoContent : HttpStatusCode.Forbidden); } /// <summary> /// Test adding entities inside and outside the given range. /// </summary> /// <param name="testClient">The table client to test.</param> /// <param name="tableName">The name of the table to test.</param> /// <param name="accessPermissions">The access permissions of the table client.</param> /// <param name="startPk">The start partition key range.</param> /// <param name="startRk">The start row key range.</param> /// <param name="endPk">The end partition key range.</param> /// <param name="endRk">The end row key range.</param> private void TestAdd( CloudTableClient testClient, string tableName, SharedAccessTablePermissions accessPermissions, string startPk, string startRk, string endPk, string endRk) { Action<BaseEntity, OperationContext> addDelegate = (tableEntity, ctx) => { // insert entity tableEntity.A = "10"; testClient.GetTableReference(tableName).Execute(TableOperation.Insert(tableEntity), null, ctx); }; bool expectSuccess = (accessPermissions & SharedAccessTablePermissions.Add) != 0; // Perform test TestOperationWithRange( tableName, startPk, startRk, endPk, endRk, addDelegate, "add", expectSuccess, expectSuccess ? HttpStatusCode.Created : HttpStatusCode.Forbidden); } /// <summary> /// Test deleting entities inside and outside the given range. /// </summary> /// <param name="testClient">The table client to test.</param> /// <param name="tableName">The name of the table to test.</param> /// <param name="accessPermissions">The access permissions of the table client.</param> /// <param name="startPk">The start partition key range.</param> /// <param name="startRk">The start row key range.</param> /// <param name="endPk">The end partition key range.</param> /// <param name="endRk">The end row key range.</param> private void TestDelete( CloudTableClient testClient, string tableName, SharedAccessTablePermissions accessPermissions, string startPk, string startRk, string endPk, string endRk) { Action<BaseEntity, OperationContext> deleteDelegate = (tableEntity, ctx) => { // delete entity tableEntity.A = "10"; tableEntity.ETag = "*"; testClient.GetTableReference(tableName).Execute(TableOperation.Delete(tableEntity), null, ctx); }; bool expectSuccess = (accessPermissions & SharedAccessTablePermissions.Delete) != 0; // Perform test TestOperationWithRange( tableName, startPk, startRk, endPk, endRk, deleteDelegate, "delete", expectSuccess, expectSuccess ? HttpStatusCode.NoContent : HttpStatusCode.Forbidden); } /// <summary> /// Test upsert (insert or merge) on entities inside and outside the given range. /// </summary> /// <param name="testClient">The table client to test.</param> /// <param name="tableName">The name of the table to test.</param> /// <param name="accessPermissions">The access permissions of the table client.</param> /// <param name="startPk">The start partition key range.</param> /// <param name="startRk">The start row key range.</param> /// <param name="endPk">The end partition key range.</param> /// <param name="endRk">The end row key range.</param> private void TestUpsertMerge( CloudTableClient testClient, string tableName, SharedAccessTablePermissions accessPermissions, string startPk, string startRk, string endPk, string endRk) { Action<BaseEntity, OperationContext> upsertDelegate = (tableEntity, ctx) => { // insert or merge entity tableEntity.A = "10"; testClient.GetTableReference(tableName).Execute(TableOperation.InsertOrMerge(tableEntity), null, ctx); }; SharedAccessTablePermissions upsertPermissions = (SharedAccessTablePermissions.Update | SharedAccessTablePermissions.Add); bool expectSuccess = (accessPermissions & upsertPermissions) == upsertPermissions; // Perform test TestOperationWithRange( tableName, startPk, startRk, endPk, endRk, upsertDelegate, "upsert merge", expectSuccess, expectSuccess ? HttpStatusCode.NoContent : HttpStatusCode.Forbidden); } /// <summary> /// Test upsert (insert or replace) on entities inside and outside the given range. /// </summary> /// <param name="testClient">The table client to test.</param> /// <param name="tableName">The name of the table to test.</param> /// <param name="accessPermissions">The access permissions of the table client.</param> /// <param name="startPk">The start partition key range.</param> /// <param name="startRk">The start row key range.</param> /// <param name="endPk">The end partition key range.</param> /// <param name="endRk">The end row key range.</param> private void TestUpsertReplace( CloudTableClient testClient, string tableName, SharedAccessTablePermissions accessPermissions, string startPk, string startRk, string endPk, string endRk) { Action<BaseEntity, OperationContext> upsertDelegate = (tableEntity, ctx) => { // insert or replace entity tableEntity.A = "10"; testClient.GetTableReference(tableName).Execute(TableOperation.InsertOrReplace(tableEntity), null, ctx); }; SharedAccessTablePermissions upsertPermissions = (SharedAccessTablePermissions.Update | SharedAccessTablePermissions.Add); bool expectSuccess = (accessPermissions & upsertPermissions) == upsertPermissions; // Perform test TestOperationWithRange( tableName, startPk, startRk, endPk, endRk, upsertDelegate, "upsert replace", expectSuccess, expectSuccess ? HttpStatusCode.NoContent : HttpStatusCode.Forbidden); } /// <summary> /// Test a table operation on entities inside and outside the given range. /// </summary> /// <param name="tableName">The name of the table to test.</param> /// <param name="startPk">The start partition key range.</param> /// <param name="startRk">The start row key range.</param> /// <param name="endPk">The end partition key range.</param> /// <param name="endRk">The end row key range.</param> /// <param name="runOperationDelegate">A delegate with the table operation to test.</param> /// <param name="opName">The name of the operation being tested.</param> /// <param name="expectSuccess">Whether the operation should succeed on entities within the range.</param> private void TestOperationWithRange( string tableName, string startPk, string startRk, string endPk, string endRk, Action<BaseEntity, OperationContext> runOperationDelegate, string opName, bool expectSuccess, HttpStatusCode expectedStatusCode) { TestOperationWithRange( tableName, startPk, startRk, endPk, endRk, runOperationDelegate, opName, expectSuccess, expectedStatusCode, false /* isRangeQuery */); } /// <summary> /// Test a table operation on entities inside and outside the given range. /// </summary> /// <param name="tableName">The name of the table to test.</param> /// <param name="startPk">The start partition key range.</param> /// <param name="startRk">The start row key range.</param> /// <param name="endPk">The end partition key range.</param> /// <param name="endRk">The end row key range.</param> /// <param name="runOperationDelegate">A delegate with the table operation to test.</param> /// <param name="opName">The name of the operation being tested.</param> /// <param name="expectSuccess">Whether the operation should succeed on entities within the range.</param> /// <param name="expectedStatusCode">The status code expected for the response.</param> /// <param name="isRangeQuery">Specifies if the operation is a range query.</param> private void TestOperationWithRange( string tableName, string startPk, string startRk, string endPk, string endRk, Action<BaseEntity, OperationContext> runOperationDelegate, string opName, bool expectSuccess, HttpStatusCode expectedStatusCode, bool isRangeQuery) { TestOperationWithRange( tableName, startPk, startRk, endPk, endRk, runOperationDelegate, opName, expectSuccess, expectedStatusCode, isRangeQuery, false /* isPointQuery */); } /// <summary> /// Test a table operation on entities inside and outside the given range. /// </summary> /// <param name="tableName">The name of the table to test.</param> /// <param name="startPk">The start partition key range.</param> /// <param name="startRk">The start row key range.</param> /// <param name="endPk">The end partition key range.</param> /// <param name="endRk">The end row key range.</param> /// <param name="runOperationDelegate">A delegate with the table operation to test.</param> /// <param name="opName">The name of the operation being tested.</param> /// <param name="expectSuccess">Whether the operation should succeed on entities within the range.</param> /// <param name="expectedStatusCode">The status code expected for the response.</param> /// <param name="isRangeQuery">Specifies if the operation is a range query.</param> /// <param name="isPointQuery">Specifies if the operation is a point query.</param> private void TestOperationWithRange( string tableName, string startPk, string startRk, string endPk, string endRk, Action<BaseEntity, OperationContext> runOperationDelegate, string opName, bool expectSuccess, HttpStatusCode expectedStatusCode, bool isRangeQuery, bool isPointQuery) { CloudTableClient referenceClient = GenerateCloudTableClient(); string partitionKey = startPk ?? endPk ?? "M"; string rowKey = startRk ?? endRk ?? "S"; // if we expect a success for creation - avoid inserting duplicate entities BaseEntity tableEntity = new BaseEntity(partitionKey, rowKey); if (expectedStatusCode == HttpStatusCode.Created) { try { tableEntity.ETag = "*"; referenceClient.GetTableReference(tableName).Execute(TableOperation.Delete(tableEntity)); } catch (Exception) { } } else { // only for add we should not be adding the entity referenceClient.GetTableReference(tableName).Execute(TableOperation.InsertOrReplace(tableEntity)); } if (expectSuccess) { runOperationDelegate(tableEntity, null); } else { TestHelper.ExpectedException( (ctx) => runOperationDelegate(tableEntity, ctx), string.Format("{0} without appropriate permission.", opName), (int)HttpStatusCode.Forbidden); } if (startPk != null) { tableEntity.PartitionKey = "A"; if (startPk.CompareTo(tableEntity.PartitionKey) <= 0) { Assert.Inconclusive("Test error: partition key for this test must not be less than or equal to \"A\""); } TestHelper.ExpectedException( (ctx) => runOperationDelegate(tableEntity, ctx), string.Format("{0} before allowed partition key range", opName), (int)(isPointQuery ? HttpStatusCode.NotFound : HttpStatusCode.Forbidden)); tableEntity.PartitionKey = partitionKey; } if (endPk != null) { tableEntity.PartitionKey = "Z"; if (endPk.CompareTo(tableEntity.PartitionKey) >= 0) { Assert.Inconclusive("Test error: partition key for this test must not be greater than or equal to \"Z\""); } TestHelper.ExpectedException( (ctx) => runOperationDelegate(tableEntity, ctx), string.Format("{0} after allowed partition key range", opName), (int)(isPointQuery ? HttpStatusCode.NotFound : HttpStatusCode.Forbidden)); tableEntity.PartitionKey = partitionKey; } if (startRk != null) { if (isRangeQuery || startPk != null) { tableEntity.PartitionKey = startPk; tableEntity.RowKey = "A"; if (startRk.CompareTo(tableEntity.RowKey) <= 0) { Assert.Inconclusive("Test error: row key for this test must not be less than or equal to \"A\""); } TestHelper.ExpectedException( (ctx) => runOperationDelegate(tableEntity, ctx), string.Format("{0} before allowed row key range", opName), (int)(isPointQuery ? HttpStatusCode.NotFound : HttpStatusCode.Forbidden)); tableEntity.RowKey = rowKey; } } if (endRk != null) { if (isRangeQuery || endPk != null) { tableEntity.PartitionKey = endPk; tableEntity.RowKey = "Z"; if (endRk.CompareTo(tableEntity.RowKey) >= 0) { Assert.Inconclusive("Test error: row key for this test must not be greater than or equal to \"Z\""); } TestHelper.ExpectedException( (ctx) => runOperationDelegate(tableEntity, ctx), string.Format("{0} after allowed row key range", opName), (int)(isPointQuery ? HttpStatusCode.NotFound : HttpStatusCode.Forbidden)); tableEntity.RowKey = rowKey; } } } #endregion #region SAS Error Conditions //[TestMethod] // Disabled until service bug is fixed [Description("Attempt to use SAS to authenticate table operations that must not work with SAS.")] [TestCategory(ComponentCategory.Table)] [TestCategory(TestTypeCategory.UnitTest)] [TestCategory(SmokeTestCategory.NonSmoke)] [TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)] public void TableSasInvalidOperations() { CloudTableClient tableClient = GenerateCloudTableClient(); CloudTable table = tableClient.GetTableReference("T" + Guid.NewGuid().ToString("N")); try { table.Create(); // Prepare SAS authentication with full permissions string sasString = table.GetSharedAccessSignature( new SharedAccessTablePolicy { Permissions = SharedAccessTablePermissions.Delete, SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30) }, null, null, null, null, null); CloudTableClient sasClient = new CloudTableClient(tableClient.BaseUri, new StorageCredentials(sasString)); // Construct a valid set of service properties to upload. ServiceProperties properties = new ServiceProperties(); properties.Logging.Version = Constants.AnalyticsConstants.LoggingVersionV1; properties.HourMetrics.Version = Constants.AnalyticsConstants.MetricsVersionV1; properties.Logging.RetentionDays = 9; sasClient.GetServiceProperties(); sasClient.SetServiceProperties(properties); // Test invalid client operations // BUGBUG: ListTables hides the exception. We should fix this // TestHelpers.ExpectedException(() => sasClient.ListTablesSegmented(), "List tables with SAS", HttpStatusCode.Forbidden); TestHelper.ExpectedException((ctx) => sasClient.GetServiceProperties(), "Get service properties with SAS", (int)HttpStatusCode.Forbidden); TestHelper.ExpectedException((ctx) => sasClient.SetServiceProperties(properties), "Set service properties with SAS", (int)HttpStatusCode.Forbidden); CloudTable sasTable = sasClient.GetTableReference(table.Name); // Verify that creation fails with SAS TestHelper.ExpectedException((ctx) => sasTable.Create(null, ctx), "Create a table with SAS", (int)HttpStatusCode.Forbidden); // Create the table. table.Create(); // Test invalid table operations TestHelper.ExpectedException((ctx) => sasTable.Delete(null, ctx), "Delete a table with SAS", (int)HttpStatusCode.Forbidden); TestHelper.ExpectedException((ctx) => sasTable.GetPermissions(null, ctx), "Get ACL with SAS", (int)HttpStatusCode.Forbidden); TestHelper.ExpectedException((ctx) => sasTable.SetPermissions(new TablePermissions(), null, ctx), "Set ACL with SAS", (int)HttpStatusCode.Forbidden); } finally { table.DeleteIfExists(); } } #endregion #region Update SAS token [TestMethod] [Description("Update table SAS.")] [TestCategory(ComponentCategory.Table)] [TestCategory(TestTypeCategory.UnitTest)] [TestCategory(SmokeTestCategory.NonSmoke)] [TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)] public void TableUpdateSasTestSync() { CloudTableClient tableClient = GenerateCloudTableClient(); CloudTable table = tableClient.GetTableReference("T" + Guid.NewGuid().ToString("N")); try { table.Create(); BaseEntity entity = new BaseEntity("PK", "RK"); table.Execute(TableOperation.Insert(entity)); SharedAccessTablePolicy policy = new SharedAccessTablePolicy() { SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5), SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30), Permissions = SharedAccessTablePermissions.Delete, }; string sasToken = table.GetSharedAccessSignature(policy); StorageCredentials creds = new StorageCredentials(sasToken); CloudTable sasTable = new CloudTable(table.Uri, creds); TestHelper.ExpectedException( () => sasTable.Execute(TableOperation.Insert(new BaseEntity("PK", "RK2"))), "Try to insert an entity when SAS doesn't allow inserts", HttpStatusCode.Forbidden); sasTable.Execute(TableOperation.Delete(entity)); SharedAccessTablePolicy policy2 = new SharedAccessTablePolicy() { SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5), SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30), Permissions = SharedAccessTablePermissions.Delete | SharedAccessTablePermissions.Add, }; string sasToken2 = table.GetSharedAccessSignature(policy2); creds.UpdateSASToken(sasToken2); sasTable = new CloudTable(table.Uri, creds); sasTable.Execute(TableOperation.Insert(new BaseEntity("PK", "RK2"))); } finally { table.DeleteIfExists(); } } #endregion #region SasUri [TestMethod] [Description("Use table SasUri.")] [TestCategory(ComponentCategory.Table)] [TestCategory(TestTypeCategory.UnitTest)] [TestCategory(SmokeTestCategory.NonSmoke)] [TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)] public void TableSasUriTestSync() { CloudTableClient tableClient = GenerateCloudTableClient(); CloudTable table = tableClient.GetTableReference("T" + Guid.NewGuid().ToString("N")); try { table.Create(); BaseEntity entity = new BaseEntity("PK", "RK"); BaseEntity entity1 = new BaseEntity("PK", "RK1"); table.Execute(TableOperation.Insert(entity)); table.Execute(TableOperation.Insert(entity1)); SharedAccessTablePolicy policy = new SharedAccessTablePolicy() { SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5), SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30), Permissions = SharedAccessTablePermissions.Delete, }; string sasToken = table.GetSharedAccessSignature(policy); StorageCredentials creds = new StorageCredentials(sasToken); CloudStorageAccount sasAcc = new CloudStorageAccount(creds, null /* blobEndpoint */, null /* queueEndpoint */, new Uri(TestBase.TargetTenantConfig.TableServiceEndpoint), null /* fileEndpoint */); CloudTableClient client = sasAcc.CreateCloudTableClient(); CloudTable sasTable = new CloudTable(client.Credentials.TransformUri(table.Uri)); sasTable.Execute(TableOperation.Delete(entity)); CloudTable sasTable2 = new CloudTable(new Uri(table.Uri.ToString() + sasToken)); sasTable2.Execute(TableOperation.Delete(entity1)); } finally { table.DeleteIfExists(); } } [TestMethod] [Description("Use table SasUri.")] [TestCategory(ComponentCategory.Table)] [TestCategory(TestTypeCategory.UnitTest)] [TestCategory(SmokeTestCategory.NonSmoke)] [TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)] public void TableSasUriPkRkTestSync() { CloudTableClient tableClient = GenerateCloudTableClient(); CloudTable table = tableClient.GetTableReference("T" + Guid.NewGuid().ToString("N")); try { table.Create(); SharedAccessTablePolicy policy = new SharedAccessTablePolicy() { SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5), SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30), Permissions = SharedAccessTablePermissions.Add, }; string sasTokenPkRk = table.GetSharedAccessSignature(policy, null, "tables_batch_0", "00", "tables_batch_1", "04"); StorageCredentials credsPkRk = new StorageCredentials(sasTokenPkRk); // transform uri from credentials CloudTable sasTableTransformed = new CloudTable(credsPkRk.TransformUri(table.Uri)); // create uri by appending sas CloudTable sasTableDirect = new CloudTable(new Uri(table.Uri.ToString() + sasTokenPkRk)); BaseEntity pkrkEnt = new BaseEntity("tables_batch_0", "00"); sasTableTransformed.Execute(TableOperation.Insert(pkrkEnt)); pkrkEnt = new BaseEntity("tables_batch_0", "01"); sasTableDirect.Execute(TableOperation.Insert(pkrkEnt)); Action<BaseEntity, CloudTable, OperationContext> insertDelegate = (tableEntity, sasTable1, ctx) => { sasTable1.Execute(TableOperation.Insert(tableEntity), null, ctx); }; pkrkEnt = new BaseEntity("tables_batch_2", "00"); TestHelper.ExpectedException( (ctx) => insertDelegate(pkrkEnt, sasTableTransformed, ctx), string.Format("Inserted entity without appropriate SAS permissions."), (int)HttpStatusCode.Forbidden); TestHelper.ExpectedException( (ctx) => insertDelegate(pkrkEnt, sasTableDirect, ctx), string.Format("Inserted entity without appropriate SAS permissions."), (int)HttpStatusCode.Forbidden); pkrkEnt = new BaseEntity("tables_batch_1", "05"); TestHelper.ExpectedException( (ctx) => insertDelegate(pkrkEnt, sasTableTransformed, ctx), string.Format("Inserted entity without appropriate SAS permissions."), (int)HttpStatusCode.Forbidden); TestHelper.ExpectedException( (ctx) => insertDelegate(pkrkEnt, sasTableDirect, ctx), string.Format("Inserted entity without appropriate SAS permissions."), (int)HttpStatusCode.Forbidden); } finally { table.DeleteIfExists(); } } #endregion #region SASIPAddressTests /// <summary> /// Helper function for testing the IPAddressOrRange funcitonality for tables /// </summary> /// <param name="generateInitialIPAddressOrRange">Function that generates an initial IPAddressOrRange object to use. This is expected to fail on the service.</param> /// <param name="generateFinalIPAddressOrRange">Function that takes in the correct IP address (according to the service) and returns the IPAddressOrRange object /// that should be accepted by the service</param> public void CloudTableSASIPAddressHelper(Func<IPAddressOrRange> generateInitialIPAddressOrRange, Func<IPAddress, IPAddressOrRange> generateFinalIPAddressOrRange) { CloudTableClient tableClient = GenerateCloudTableClient(); CloudTable table = tableClient.GetTableReference("T" + Guid.NewGuid().ToString("N")); try { table.Create(); SharedAccessTablePolicy policy = new SharedAccessTablePolicy() { Permissions = SharedAccessTablePermissions.Query, SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5), SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30), }; DynamicTableEntity entity = new DynamicTableEntity("PK", "RK", null, new Dictionary<string, EntityProperty>() {{"prop", new EntityProperty(4)}}); table.Execute(new TableOperation(entity, TableOperationType.Insert)); // The plan then is to use an incorrect IP address to make a call to the service // ensure that we get an error message // parse the error message to get my actual IP (as far as the service sees) // then finally test the success case to ensure we can actually make requests IPAddressOrRange ipAddressOrRange = generateInitialIPAddressOrRange(); string tableToken = table.GetSharedAccessSignature(policy, null, null, null, null, null, null, ipAddressOrRange); StorageCredentials tableSAS = new StorageCredentials(tableToken); Uri tableSASUri = tableSAS.TransformUri(table.Uri); StorageUri tableSASStorageUri = tableSAS.TransformUri(table.StorageUri); CloudTable tableWithSAS = new CloudTable(tableSASUri); OperationContext opContext = new OperationContext(); IPAddress actualIP = null; bool exceptionThrown = false; TableResult result = null; DynamicTableEntity resultEntity = new DynamicTableEntity(); TableOperation retrieveOp = new TableOperation(resultEntity, TableOperationType.Retrieve); retrieveOp.RetrievePartitionKey = entity.PartitionKey; retrieveOp.RetrieveRowKey = entity.RowKey; try { result = tableWithSAS.Execute(retrieveOp, null, opContext); } catch (StorageException e) { string[] parts = e.RequestInformation.HttpStatusMessage.Split(' '); actualIP = IPAddress.Parse(parts[parts.Length - 1].Trim('.')); exceptionThrown = true; Assert.IsNotNull(actualIP); } Assert.IsTrue(exceptionThrown); ipAddressOrRange = generateFinalIPAddressOrRange(actualIP); tableToken = table.GetSharedAccessSignature(policy, null, null, null, null, null, null, ipAddressOrRange); tableSAS = new StorageCredentials(tableToken); tableSASUri = tableSAS.TransformUri(table.Uri); tableSASStorageUri = tableSAS.TransformUri(table.StorageUri); tableWithSAS = new CloudTable(tableSASUri); resultEntity = new DynamicTableEntity(); retrieveOp = new TableOperation(resultEntity, TableOperationType.Retrieve); retrieveOp.RetrievePartitionKey = entity.PartitionKey; retrieveOp.RetrieveRowKey = entity.RowKey; resultEntity = (DynamicTableEntity)tableWithSAS.Execute(retrieveOp).Result; Assert.AreEqual(entity.Properties["prop"].PropertyType, resultEntity.Properties["prop"].PropertyType); Assert.AreEqual(entity.Properties["prop"].Int32Value.Value, resultEntity.Properties["prop"].Int32Value.Value); Assert.IsTrue(table.StorageUri.PrimaryUri.Equals(tableWithSAS.Uri)); Assert.IsNull(tableWithSAS.StorageUri.SecondaryUri); tableWithSAS = new CloudTable(tableSASStorageUri, null); resultEntity = new DynamicTableEntity(); retrieveOp = new TableOperation(resultEntity, TableOperationType.Retrieve); retrieveOp.RetrievePartitionKey = entity.PartitionKey; retrieveOp.RetrieveRowKey = entity.RowKey; resultEntity = (DynamicTableEntity)tableWithSAS.Execute(retrieveOp).Result; Assert.AreEqual(entity.Properties["prop"].PropertyType, resultEntity.Properties["prop"].PropertyType); Assert.AreEqual(entity.Properties["prop"].Int32Value.Value, resultEntity.Properties["prop"].Int32Value.Value); Assert.IsTrue(table.StorageUri.Equals(tableWithSAS.StorageUri)); } finally { table.DeleteIfExists(); } } [TestMethod] [Description("Perform a SAS request specifying an IP address or range and ensure that everything works properly.")] [TestCategory(ComponentCategory.Table)] [TestCategory(TestTypeCategory.UnitTest)] [TestCategory(SmokeTestCategory.NonSmoke)] [TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)] public void CloudTableSASIPAddressQueryParam() { CloudTableSASIPAddressHelper(() => { // We need an IP address that will never be a valid source IPAddress invalidIP = IPAddress.Parse("255.255.255.255"); return new IPAddressOrRange(invalidIP.ToString()); }, (IPAddress actualIP) => { return new IPAddressOrRange(actualIP.ToString()); }); } [TestMethod] [Description("Perform a SAS request specifying an IP address or range and ensure that everything works properly.")] [TestCategory(ComponentCategory.Table)] [TestCategory(TestTypeCategory.UnitTest)] [TestCategory(SmokeTestCategory.NonSmoke)] [TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)] public void CloudTableSASIPRangeQueryParam() { CloudTableSASIPAddressHelper(() => { // We need an IP address that will never be a valid source IPAddress invalidIPBegin = IPAddress.Parse("255.255.255.0"); IPAddress invalidIPEnd = IPAddress.Parse("255.255.255.255"); return new IPAddressOrRange(invalidIPBegin.ToString(), invalidIPEnd.ToString()); }, (IPAddress actualIP) => { byte[] actualAddressBytes = actualIP.GetAddressBytes(); byte[] initialAddressBytes = actualAddressBytes.ToArray(); initialAddressBytes[0]--; byte[] finalAddressBytes = actualAddressBytes.ToArray(); finalAddressBytes[0]++; return new IPAddressOrRange(new IPAddress(initialAddressBytes).ToString(), new IPAddress(finalAddressBytes).ToString()); }); } #endregion #region SASHttpsTests [TestMethod] [Description("Perform a SAS request specifying a shared protocol and ensure that everything works properly.")] [TestCategory(ComponentCategory.Table)] [TestCategory(TestTypeCategory.UnitTest)] [TestCategory(SmokeTestCategory.NonSmoke)] [TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)] public void CloudTableSASSharedProtocolsQueryParam() { CloudTableClient tableClient = GenerateCloudTableClient(); CloudTable table = tableClient.GetTableReference("T" + Guid.NewGuid().ToString("N")); try { table.Create(); SharedAccessTablePolicy policy = new SharedAccessTablePolicy() { Permissions = SharedAccessTablePermissions.Query, SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5), SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30), }; DynamicTableEntity entity = new DynamicTableEntity("PK", "RK", null, new Dictionary<string, EntityProperty>() { { "prop", new EntityProperty(4) } }); table.Execute(new TableOperation(entity, TableOperationType.Insert)); foreach (SharedAccessProtocol? protocol in new SharedAccessProtocol?[] { null, SharedAccessProtocol.HttpsOrHttp, SharedAccessProtocol.HttpsOnly }) { string tableToken = table.GetSharedAccessSignature(policy, null, null, null, null, null, protocol, null); StorageCredentials tableSAS = new StorageCredentials(tableToken); Uri tableSASUri = new Uri(table.Uri + tableSAS.SASToken); StorageUri tableSASStorageUri = new StorageUri(new Uri(table.StorageUri.PrimaryUri + tableSAS.SASToken), new Uri(table.StorageUri.SecondaryUri + tableSAS.SASToken)); int httpPort = tableSASUri.Port; int securePort = 443; if (!string.IsNullOrEmpty(TestBase.TargetTenantConfig.TableSecurePortOverride)) { securePort = Int32.Parse(TestBase.TargetTenantConfig.TableSecurePortOverride); } var schemesAndPorts = new[] { new { scheme = Uri.UriSchemeHttp, port = httpPort}, new { scheme = Uri.UriSchemeHttps, port = securePort} }; CloudTable tableWithSAS = null; TableOperation retrieveOp = TableOperation.Retrieve(entity.PartitionKey, entity.RowKey); foreach (var item in schemesAndPorts) { tableSASUri = TransformSchemeAndPort(tableSASUri, item.scheme, item.port); tableSASStorageUri = new StorageUri(TransformSchemeAndPort(tableSASStorageUri.PrimaryUri, item.scheme, item.port), TransformSchemeAndPort(tableSASStorageUri.SecondaryUri, item.scheme, item.port)); if (protocol.HasValue && protocol.Value == SharedAccessProtocol.HttpsOnly && string.CompareOrdinal(item.scheme, Uri.UriSchemeHttp) == 0) { tableWithSAS = new CloudTable(tableSASUri); TestHelper.ExpectedException(() => tableWithSAS.Execute(retrieveOp), "Access a table using SAS with a shared protocols that does not match", HttpStatusCode.Unused); tableWithSAS = new CloudTable(tableSASStorageUri, null); TestHelper.ExpectedException(() => tableWithSAS.Execute(retrieveOp), "Access a table using SAS with a shared protocols that does not match", HttpStatusCode.Unused); } else { tableWithSAS = new CloudTable(tableSASUri); TableResult result = tableWithSAS.Execute(retrieveOp); Assert.AreEqual(entity.Properties["prop"], ((DynamicTableEntity)result.Result).Properties["prop"]); tableWithSAS = new CloudTable(tableSASStorageUri, null); result = tableWithSAS.Execute(retrieveOp); Assert.AreEqual(entity.Properties["prop"], ((DynamicTableEntity)result.Result).Properties["prop"]); } } } } finally { table.DeleteIfExists(); } } private static Uri TransformSchemeAndPort(Uri input, string scheme, int port) { UriBuilder builder = new UriBuilder(input); builder.Scheme = scheme; builder.Port = port; return builder.Uri; } #endregion #region Test Helpers internal static void AssertPermissionsEqual(TablePermissions permissions1, TablePermissions permissions2) { Assert.AreEqual(permissions1.SharedAccessPolicies.Count, permissions2.SharedAccessPolicies.Count); foreach (KeyValuePair<string, SharedAccessTablePolicy> pair in permissions1.SharedAccessPolicies) { SharedAccessTablePolicy policy1 = pair.Value; SharedAccessTablePolicy policy2 = permissions2.SharedAccessPolicies[pair.Key]; Assert.IsNotNull(policy1); Assert.IsNotNull(policy2); Assert.AreEqual(policy1.Permissions, policy2.Permissions); if (policy1.SharedAccessStartTime != null) { Assert.IsTrue(Math.Floor((policy1.SharedAccessStartTime.Value - policy2.SharedAccessStartTime.Value).TotalSeconds) == 0); } if (policy1.SharedAccessExpiryTime != null) { Assert.IsTrue(Math.Floor((policy1.SharedAccessExpiryTime.Value - policy2.SharedAccessExpiryTime.Value).TotalSeconds) == 0); } } } #endregion } #pragma warning restore 0618 }
MatthewSteeples/azure-storage-net
Test/ClassLibraryCommon/Table/SAS/TableSasUnitTests.cs
C#
apache-2.0
67,776
[ 30522, 1013, 1013, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 101...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
When /(.*) should receive: (.*) email/ do |email, preference_list| u = User.find_by(email:email) print(u) preference_list.split(",").each do |p| if p[1,p.length-2] == "internal" expect(u.internal).to be(false) end end end When /I should see correct flash message "([^"]*)"$/ do |message| expect(page).to have_css('flashNotice',text: message) end #New tests for iter 2-1 Then /I should receive an email/ do pending end Then /I should see title "([^"]*)"$/ do |title| pending end Then /I should see content "([^"]*)"$/ do |content| pending end Then /the database should( not)? have email with title "([^"]*)" and content "([^"]*)"$/ do |title, content| pending end #New Tests for iter 2-2 Then /I should see a MailRecord object with attribute "([^"]*)" and description "([^"]*)"$/ do |attr, desc| MailRecord.where.not(attr, nil).find_by(description: desc) end
hsp1324/communitygrows
features/step_definitions/email_digest_steps.rb
Ruby
mit
884
[ 30522, 2043, 1013, 1006, 1012, 1008, 1007, 2323, 4374, 1024, 1006, 1012, 1008, 1007, 10373, 1013, 2079, 1064, 10373, 1010, 12157, 1035, 2862, 1064, 1057, 1027, 5310, 1012, 2424, 1035, 2011, 1006, 10373, 1024, 10373, 1007, 6140, 1006, 1057, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
package com.silicolife.textmining.core.datastructures.dataaccess.database.dataaccess.implementation.model.core.entities; // Generated 23/Mar/2015 16:36:00 by Hibernate Tools 4.3.1 import javax.persistence.Column; import javax.persistence.Embeddable; /** * ClusterProcessHasLabelsId generated by hbm2java */ @Embeddable public class ClusterProcessHasLabelsId implements java.io.Serializable { private long cphClusterProcessId; private long cphClusterLabelId; public ClusterProcessHasLabelsId() { } public ClusterProcessHasLabelsId(long cphClusterProcessId, long cphClusterLabelId) { this.cphClusterProcessId = cphClusterProcessId; this.cphClusterLabelId = cphClusterLabelId; } @Column(name = "cph_cluster_process_id", nullable = false) public long getCphClusterProcessId() { return this.cphClusterProcessId; } public void setCphClusterProcessId(long cphClusterProcessId) { this.cphClusterProcessId = cphClusterProcessId; } @Column(name = "cph_cluster_label_id", nullable = false) public long getCphClusterLabelId() { return this.cphClusterLabelId; } public void setCphClusterLabelId(long cphClusterLabelId) { this.cphClusterLabelId = cphClusterLabelId; } public boolean equals(Object other) { if ((this == other)) return true; if ((other == null)) return false; if (!(other instanceof ClusterProcessHasLabelsId)) return false; ClusterProcessHasLabelsId castOther = (ClusterProcessHasLabelsId) other; return (this.getCphClusterProcessId() == castOther.getCphClusterProcessId()) && (this.getCphClusterLabelId() == castOther.getCphClusterLabelId()); } public int hashCode() { int result = 17; result = 37 * result + (int) this.getCphClusterProcessId(); result = 37 * result + (int) this.getCphClusterLabelId(); return result; } }
biotextmining/core
src/main/java/com/silicolife/textmining/core/datastructures/dataaccess/database/dataaccess/implementation/model/core/entities/ClusterProcessHasLabelsId.java
Java
lgpl-3.0
1,802
[ 30522, 7427, 4012, 1012, 9033, 10415, 10893, 7959, 1012, 3793, 25300, 3070, 1012, 4563, 1012, 2951, 3367, 6820, 14890, 2015, 1012, 2951, 6305, 9623, 2015, 1012, 7809, 1012, 2951, 6305, 9623, 2015, 1012, 7375, 1012, 2944, 1012, 4563, 1012, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * vspython@microsoft.com. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * ***************************************************************************/ using System; using System.IO; using System.Net.WebSockets; using System.Threading; using System.Threading.Tasks; namespace Microsoft.VisualStudioTools { /// <summary> /// Wraps a <see cref="WebSocket"/> instance and exposes its interface as a generic <see cref="Stream"/>. /// </summary> internal class WebSocketStream : Stream { private readonly WebSocket _webSocket; private bool _ownsSocket; public WebSocketStream(WebSocket webSocket, bool ownsSocket = false) { _webSocket = webSocket; _ownsSocket = ownsSocket; } protected override void Dispose(bool disposing) { base.Dispose(disposing); if (disposing && _ownsSocket) { _webSocket.Dispose(); } } public override bool CanRead { get { return true; } } public override bool CanWrite { get { return true; } } public override bool CanSeek { get { return false; } } public override void Flush() { } public override Task FlushAsync(CancellationToken cancellationToken) { return Task.FromResult(true); } public override int Read(byte[] buffer, int offset, int count) { return ReadAsync(buffer, offset, count).GetAwaiter().GetResult(); } public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { try { return (await _webSocket.ReceiveAsync(new ArraySegment<byte>(buffer, offset, count), cancellationToken).ConfigureAwait(false)).Count; } catch (WebSocketException ex) { throw new IOException(ex.Message, ex); } } public override void Write(byte[] buffer, int offset, int count) { WriteAsync(buffer, offset, count).GetAwaiter().GetResult(); } public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { try { await _webSocket.SendAsync(new ArraySegment<byte>(buffer, offset, count), WebSocketMessageType.Binary, true, cancellationToken).ConfigureAwait(false); } catch (WebSocketException ex) { throw new IOException(ex.Message, ex); } } public override long Length { get { throw new NotSupportedException(); } } public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } public override void SetLength(long value) { throw new NotSupportedException(); } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } } }
Microsoft/VisualStudio-SharedProject
Product/SharedProject/WebSocketStream.cs
C#
apache-2.0
3,623
[ 30522, 1013, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 100...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
// Copyright (c) 2014, ultramailman // This file is licensed under the MIT License. #include <assert.h> #include <stdio.h> #include <time.h> #include "rhtable.h" #include "rhtable_safe.h" typedef struct{ uint32_t n; } Key; typedef struct{ uint64_t index; } Val; int KeyEq(Key const * a, Key const * b) { return a->n == b->n; } uint32_t KeyHash(Key const * a) { return a->n * 65537; } RHTABLE_DEFINE_SAFE(hashtable, Key, Val, KeyEq, KeyHash) #define LENGTH 30000 // random data static inline unsigned random(unsigned x) { return (x * 16807) % ((2 << 31) - 1); } Key data [LENGTH]; unsigned membership[LENGTH]; void init(void) { unsigned seed = 10; for(int i = 0; i < LENGTH; i++) { seed = random(seed); data[i].n = seed; membership[i] = 0; } } static void testRemoval(hashtable * t, unsigned begin, unsigned end) { for(unsigned i = begin; i < end; i++) { int found = hashtable_get(t, data + i, 0, 0); if(membership[i]) { assert(found); hashtable_del(t, data + i); found = hashtable_get(t, data + i, 0, 0); assert(!found); membership[i] = 0; } } } static void testFind(hashtable * t) { for(int i = 0; i < LENGTH; i++) { Key rkey; Val rval; int found = hashtable_get(t, data + i, &rkey, &rval); if(membership[i]) { assert(found); assert(data[rval.index].n == rkey.n); assert(data[rval.index].n == data[i].n); } else { assert(!found); } } } static void testInsert(hashtable * t, unsigned begin, unsigned end) { for(int i = 0; i < LENGTH; i++) { Key key = data[i]; Val val = {i}; int good = hashtable_set(t, &key, &val); if(good) { Key rkey; Val rval; int found = hashtable_get(t, data + i, &rkey, &rval); assert(found); assert(rkey.n == key.n); assert(rval.index == val.index); assert(data[rval.index].n == rkey.n); assert(data[rval.index].n == data[i].n); membership[i] = 1; } else { printf("table full %d\n", i); } } printf("items in: %d\n", hashtable_count(t)); printf("total number of items: %d\n", LENGTH); printf("table capacity: %d\n", hashtable_slots(t)); float count = hashtable_count(t); float slots = hashtable_slots(t); float load = count / slots; float averageDib = hashtable_average_dib(t); fprintf(stdout, "load: %f\n", load); fprintf(stdout, "average dib: %f\n\n", averageDib); } static void testIterator(hashtable * t) { rh_for_safe(hashtable, t, iter) { Key rkey; Val rval; assert(hashtable_get(t, iter.key, &rkey, &rval)); assert(rkey.n == data[rval.index].n); assert(membership[rval.index]); } } int main(int argc, char ** argv) { init(); unsigned size = 45001; if(argc == 2) { sscanf(argv[1], "%ud", &size); } hashtable t = hashtable_create(size); clock_t t1 = clock(); testInsert(&t, 0, LENGTH); testFind(&t); testIterator(&t); testRemoval(&t, 0, LENGTH); clock_t t2 = clock(); printf("time: %lu\n", t2 - t1); }
ultramailman/rhtable
src/test_rhtable.c
C
mit
2,905
[ 30522, 1013, 1013, 9385, 1006, 1039, 1007, 2297, 1010, 11087, 21397, 2386, 1013, 1013, 2023, 5371, 2003, 7000, 2104, 1996, 10210, 6105, 1012, 1001, 2421, 1026, 20865, 1012, 1044, 1028, 1001, 2421, 1026, 2358, 20617, 1012, 1044, 1028, 1001, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<!DOCTYPE html> <html> <head> <!--conteudo do head--> </head> <body> <h1>Teste teste<h1> </body> </html>
matheusnovaes/redesocialblog
templates/profile/index.html
HTML
mit
139
[ 30522, 1026, 999, 9986, 13874, 16129, 1028, 1026, 16129, 1028, 1026, 2132, 1028, 1026, 999, 1011, 1011, 9530, 2618, 6784, 2080, 2079, 2132, 1011, 1011, 1028, 1026, 1013, 2132, 1028, 1026, 2303, 1028, 1026, 1044, 2487, 1028, 3231, 2063, 32...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
package alien4cloud.tosca.parser.impl.advanced; import java.util.Map; import javax.annotation.Resource; import org.alien4cloud.tosca.model.definitions.AbstractPropertyValue; import org.alien4cloud.tosca.model.definitions.Interface; import org.alien4cloud.tosca.model.templates.RelationshipTemplate; import org.springframework.stereotype.Component; import org.yaml.snakeyaml.nodes.MappingNode; import org.yaml.snakeyaml.nodes.Node; import org.yaml.snakeyaml.nodes.NodeTuple; import org.yaml.snakeyaml.nodes.ScalarNode; import alien4cloud.tosca.parser.INodeParser; import alien4cloud.tosca.parser.ParserUtils; import alien4cloud.tosca.parser.ParsingContextExecution; import alien4cloud.tosca.parser.ParsingError; import alien4cloud.tosca.parser.ParsingErrorLevel; import alien4cloud.tosca.parser.impl.ErrorCode; import alien4cloud.tosca.parser.impl.base.BaseParserFactory; import alien4cloud.tosca.parser.impl.base.MapParser; import alien4cloud.tosca.parser.impl.base.ScalarParser; /** * Parse a relationship */ @Deprecated @Component public class RelationshipTemplateParser implements INodeParser<RelationshipTemplate> { @Resource private ScalarParser scalarParser; @Resource private BaseParserFactory baseParserFactory; @Override public RelationshipTemplate parse(Node node, ParsingContextExecution context) { // To parse a relationship template we actually get the parent node to retrieve the requirement name; if (!(node instanceof MappingNode) || ((MappingNode) node).getValue().size() != 1) { ParserUtils.addTypeError(node, context.getParsingErrors(), "Requirement assignment"); } MappingNode assignmentNode = (MappingNode) node; RelationshipTemplate relationshipTemplate = new RelationshipTemplate(); relationshipTemplate.setRequirementName(scalarParser.parse(assignmentNode.getValue().get(0).getKeyNode(), context)); // Now parse the content of the relationship assignment. node = assignmentNode.getValue().get(0).getValueNode(); if (node instanceof ScalarNode) { // Short notation (host: compute) relationshipTemplate.setTarget(scalarParser.parse(node, context)); } else if (node instanceof MappingNode) { MappingNode mappingNode = (MappingNode) node; for (NodeTuple nodeTuple : mappingNode.getValue()) { String key = scalarParser.parse(nodeTuple.getKeyNode(), context); switch (key) { case "node": relationshipTemplate.setTarget(scalarParser.parse(nodeTuple.getValueNode(), context)); break; case "capability": relationshipTemplate.setTargetedCapabilityName(scalarParser.parse(nodeTuple.getValueNode(), context)); break; case "relationship": relationshipTemplate.setType(scalarParser.parse(nodeTuple.getValueNode(), context)); break; case "properties": INodeParser<AbstractPropertyValue> propertyValueParser = context.getRegistry().get("node_template_property"); MapParser<AbstractPropertyValue> mapParser = baseParserFactory.getMapParser(propertyValueParser, "node_template_property"); relationshipTemplate.setProperties(mapParser.parse(nodeTuple.getValueNode(), context)); break; case "interfaces": INodeParser<Map<String, Interface>> interfacesParser = context.getRegistry().get("interfaces"); relationshipTemplate.setInterfaces(interfacesParser.parse(nodeTuple.getValueNode(), context)); break; default: context.getParsingErrors().add(new ParsingError(ParsingErrorLevel.WARNING, ErrorCode.UNKNOWN_ARTIFACT_KEY, null, node.getStartMark(), "Unrecognized key while parsing implementation artifact", node.getEndMark(), key)); } } } else { ParserUtils.addTypeError(node, context.getParsingErrors(), "Requirement assignment"); } return relationshipTemplate; } }
alien4cloud/alien4cloud
alien4cloud-tosca/src/main/java/alien4cloud/tosca/parser/impl/advanced/RelationshipTemplateParser.java
Java
apache-2.0
4,234
[ 30522, 7427, 7344, 2549, 20464, 19224, 1012, 2000, 15782, 1012, 11968, 8043, 1012, 17727, 2140, 1012, 3935, 1025, 12324, 9262, 1012, 21183, 4014, 1012, 4949, 1025, 12324, 9262, 2595, 1012, 5754, 17287, 3508, 1012, 7692, 1025, 12324, 8917, 1...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
class CreateCollectSalaries < ActiveRecord::Migration def change create_table :collect_salaries do |t| t.belongs_to :user t.decimal :money, :precision => 10, :scale => 2 t.date :collect_date t.string :notes t.timestamps null: false end end end
mumaoxi/contract_works_api
db/migrate/20160204101820_create_collect_salaries.rb
Ruby
mit
286
[ 30522, 2465, 3443, 26895, 22471, 12002, 12086, 1026, 3161, 2890, 27108, 2094, 1024, 1024, 9230, 13366, 2689, 3443, 1035, 2795, 1024, 8145, 1035, 20566, 2079, 1064, 1056, 1064, 1056, 1012, 7460, 1035, 2000, 1024, 5310, 1056, 1012, 26066, 102...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
require_relative 'rules_factory_common' FactoryBot.define do factory :priority_bills, parent: :answers do factory :S6_H1_missed_payment_low, traits: [:country, :S6_H1_missed_payment_low_answers] factory :S6_H2_council_tax_severe, traits: [:country, :S6_H2_tax_severe_answers] factory :S6_H2_domestic_rates_severe, traits: [:country, :S6_H2_tax_severe_answers] factory :S6_H2_council_tax_temp_worried, traits: [:country, :S6_H2_tax_temp_worried_answers] factory :S6_H2_domestic_rates_temp_worried, traits: [:country, :S6_H2_tax_temp_worried_answers] factory :S6_H2_council_tax_temp_normal, traits: [:country, :S6_H2_tax_temp_normal_answers] factory :S6_H2_domestic_rates_temp_normal, traits: [:country, :S6_H2_tax_temp_normal_answers] factory :S6_H2_council_tax_no_change, traits: [:country, :S6_H2_tax_no_change_answers] factory :S6_H2_domestic_rates_no_change, traits: [:country, :S6_H2_tax_no_change_answers] factory :S6_H3_gas_electricity_severe, traits: [:country, :S6_H3_gas_electricity_severe_answers] factory :S6_H3_gas_electricity_temp_worried, traits: [:country, :S6_H3_gas_electricity_temp_worried_answers] factory :S6_H3_gas_electricity_temp_normal, traits: [:country, :S6_H3_gas_electricity_temp_normal_answers] factory :S6_H3_gas_electricity_no_change, traits: [:country, :S6_H3_gas_electricity_no_change_answers] factory :S6_H4_dmp_hmrc_severe, traits: [:country, :S6_H4_dmp_hmrc_severe_answers] factory :S6_H4_dmp_hmrc_temp_worried, traits: [:country, :S6_H4_dmp_hmrc_temp_worried_answers] factory :S6_H4_dmp_hmrc_temp_normal, traits: [:country, :S6_H4_dmp_hmrc_temp_normal_answers] factory :S6_H4_dmp_hmrc_no_change, traits: [:country, :S6_H4_dmp_hmrc_no_change_answers] factory :S6_H5_tv_licence_severe, traits: [:country, :S6_H5_tv_licence_severe_answers] factory :S6_H5_tv_licence_temp_worried, traits: [:country, :S6_H5_tv_licence_temp_worried_answers] factory :S6_H5_tv_licence_temp_normal, traits: [:country, :S6_H5_tv_licence_temp_normal_answers] factory :S6_H5_tv_licence_no_change, traits: [:country, :S6_H5_tv_licence_no_change_answers] factory :S6_H6_income_tax_severe, traits: [:country, :S6_H6_income_tax_severe_answers] factory :S6_H6_income_tax_temp_worried, traits: [:country, :S6_H6_income_tax_temp_worried_answers] factory :S6_H6_income_tax_temp_normal, traits: [:country, :S6_H6_income_tax_temp_normal_answers] factory :S6_H6_income_tax_no_change, traits: [:country, :S6_H6_income_tax_no_change_answers] factory :S6_H7_child_maintenance_severe, traits: [:country, :S6_H7_child_maintenance_severe_answers] factory :S6_H7_child_maintenance_temp_worried, traits: [:country, :S6_H7_child_maintenance_temp_worried_answers] factory :S6_H7_child_maintenance_temp_normal, traits: [:country, :S6_H7_child_maintenance_temp_normal_answers] factory :S6_H7_child_maintenance_no_change, traits: [:country, :S6_H7_child_maintenance_no_change_answers] factory :S6_H8_court_fines_severe, traits: [:country, :S6_H8_court_fines_severe_answers] factory :S6_H8_court_fines_temp_worried, traits: [:country, :S6_H8_court_fines_temp_worried_answers] factory :S6_H8_court_fines_temp_normal, traits: [:country, :S6_H8_court_fines_temp_normal_answers] factory :S6_H8_court_fines_temp_normal_ni, traits: [:country, :S6_H8_court_fines_temp_normal_ni_answers] factory :S6_H8_court_fines_temp_normal_scotland, traits: [:country, :S6_H8_court_fines_temp_normal_scotland_answers] factory :S6_H8_court_fines_no_change, traits: [:country, :S6_H8_court_fines_no_change_answers] factory :S6_H9_hire_purchase_severe, traits: [:country, :S6_H9_hire_purchase_severe_answers] factory :S6_H9_hire_purchase_temp_worried, traits: [:country, :S6_H9_hire_purchase_temp_worried_answers] factory :S6_H9_hire_purchase_temp_normal, traits: [:country, :S6_H9_hire_purchase_temp_normal_answers] factory :S6_H9_hire_purchase_no_change, traits: [:country, :S6_H9_hire_purchase_no_change_answers] factory :S6_H10_car_park_severe, traits: [:country, :S6_H10_car_park_severe_answers] factory :S6_H10_car_park_temp_worried, traits: [:country, :S6_H10_car_park_temp_worried_answers] factory :S6_H10_car_park_temp_normal, traits: [:country, :S6_H10_car_park_temp_normal_answers] factory :S6_H10_car_park_temp_normal_ni, traits: [:country, :S6_H10_car_park_temp_normal_ni_answers] factory :S6_H10_car_park_temp_normal_scotland, traits: [:country, :S6_H10_car_park_temp_normal_scotland_answers] factory :S6_H10_car_park_no_change, traits: [:country, :S6_H10_car_park_no_change_answers] trait :S6_H1_missed_payment_low_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', [], nil) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H2_tax_severe_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a1'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a1'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H2_tax_temp_worried_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a2'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a1'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H2_tax_temp_normal_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a3'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a1'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H2_tax_no_change_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a4'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a1'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H3_gas_electricity_severe_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a1'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a2'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H3_gas_electricity_temp_worried_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a2'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a2'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H3_gas_electricity_temp_normal_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a3'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a2'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H3_gas_electricity_no_change_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a4'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a2'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H4_dmp_hmrc_severe_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a1'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a3'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H4_dmp_hmrc_temp_worried_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a2'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a3'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H4_dmp_hmrc_temp_normal_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a3'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a3'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H4_dmp_hmrc_no_change_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a4'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a3'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H5_tv_licence_severe_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a1'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a4'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H5_tv_licence_temp_worried_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a2'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a4'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H5_tv_licence_temp_normal_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a3'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a4'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H5_tv_licence_no_change_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a4'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a4'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H6_income_tax_severe_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a1'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a5'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H6_income_tax_temp_worried_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a2'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a5'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H6_income_tax_temp_normal_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a3'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a5'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H6_income_tax_no_change_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a4'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a5'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H7_child_maintenance_severe_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a1'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a6'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H7_child_maintenance_temp_worried_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a2'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a6'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H7_child_maintenance_temp_normal_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a3'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a6'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H7_child_maintenance_no_change_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a4'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a6'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H8_court_fines_severe_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a1'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a7'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H8_court_fines_temp_worried_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a2'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a7'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H8_court_fines_temp_normal_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a3'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a7'], []) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H8_court_fines_temp_normal_ni_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a3'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a7'], []) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H8_court_fines_temp_normal_scotland_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a3'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a7'], []) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H8_court_fines_no_change_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a4'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a7'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H9_hire_purchase_severe_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a1'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a8'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H9_hire_purchase_temp_worried_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a2'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a8'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H9_hire_purchase_temp_normal_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a3'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a8'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H9_hire_purchase_no_change_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a4'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a8'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H10_car_park_severe_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a1'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a9'], []) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H10_car_park_temp_worried_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a2'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a9'], []) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H10_car_park_temp_normal_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a3'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a9'], nil) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H10_car_park_temp_normal_ni_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a3'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a9'], []) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H10_car_park_temp_normal_scotland_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a3'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a9'], []) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end trait :S6_H10_car_park_no_change_answers do q1 { answers_with_entropy('q1', [], nil) } q2 { answers_with_entropy('q2', [], nil) } q3 { answers_with_entropy('q3', [], nil) } q4 { answers_with_entropy('q4', ['a4'], []) } q5 { answers_with_entropy('q5', [], nil) } q6 { answers_with_entropy('q6', [], nil) } q7 { answers_with_entropy('q7', ['a9'],[] ) } q8 { answers_with_entropy('q8', [], nil) } q9 { answers_with_entropy('q9', [], nil) } q11 { answers_with_entropy('q11', [], nil) } q12 { answers_with_entropy('q12', [], nil) } q13 { answers_with_entropy('q13', [], nil) } q14 { answers_with_entropy('q14', [], nil) } end end end
moneyadviceservice/frontend
features/factories/money_navigator/priority_bills_rules.rb
Ruby
mit
33,882
[ 30522, 5478, 1035, 5816, 1005, 3513, 1035, 4713, 1035, 2691, 1005, 4713, 18384, 1012, 9375, 2079, 4713, 1024, 9470, 1035, 8236, 1010, 6687, 1024, 1024, 6998, 2079, 4713, 1024, 1055, 2575, 1035, 1044, 2487, 1035, 4771, 1035, 7909, 1035, 26...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
FROM midvalestudent/jupyter-scipy:latest USER root ENV HOME /root ADD requirements.txt /usr/local/share/requirements.txt RUN pip install --upgrade pip && pip install -r /usr/local/share/requirements.txt # Download/build/install ffmpeg ARG FFMPEG_VERSION ENV FFMPEG_VERSION ${FFMPEG_VERSION:-"3.2"} RUN DEBIAN_FRONTEND=noninteractive \ && REPO=http://www.deb-multimedia.org \ && echo "deb $REPO jessie main non-free\ndeb-src $REPO jessie main non-free" >> /etc/apt/sources.list \ && apt-get update && apt-get install -y --force-yes deb-multimedia-keyring && apt-get update \ && apt-get remove ffmpeg \ && apt-get install -yq --no-install-recommends \ build-essential \ libmp3lame-dev \ libvorbis-dev \ libtheora-dev \ libspeex-dev \ yasm \ pkg-config \ libfaac-dev \ libopenjpeg-dev \ libx264-dev \ && apt-get clean \ && rm -rf /var/lib/apt/lists/* \ && mkdir -p /usr/src/build && cd /usr/src/build \ && wget http://ffmpeg.org/releases/ffmpeg-$FFMPEG_VERSION.tar.gz \ && tar xzf ffmpeg-$FFMPEG_VERSION.tar.gz && cd ffmpeg-$FFMPEG_VERSION \ && ./configure \ --prefix=/usr/local \ --enable-gpl \ --enable-postproc \ --enable-swscale \ --enable-avfilter \ --enable-libmp3lame \ --enable-libvorbis \ --enable-libtheora \ --enable-libx264 \ --enable-libspeex \ --enable-shared \ --enable-pthreads \ --enable-libopenjpeg \ --enable-nonfree \ && make -j$(nproc) install && ldconfig \ && cd /usr/src/build && rm -rf ffmpeg-$FFMPEG_VERSION* \ && apt-get purge -y cmake && apt-get autoremove -y --purge # Download/build/install components for opencv ARG OPENCV_VERSION ENV OPENCV_VERSION ${OPENCV_VERSION:-"3.2.0"} RUN DEBIAN_FRONTEND=noninteractive \ && REPO=http://cdn-fastly.deb.debian.org \ && echo "deb $REPO/debian jessie main\ndeb $REPO/debian-security jessie/updates main" > /etc/apt/sources.list \ && apt-get update && apt-get -yq dist-upgrade \ && apt-get install -yq --no-install-recommends \ build-essential \ cmake \ git-core \ pkg-config \ libjpeg62-turbo-dev \ libtiff5-dev \ libjasper-dev \ libpng12-dev \ libavcodec-dev \ libavformat-dev \ libswscale-dev \ libv4l-dev \ libatlas-base-dev \ gfortran \ tesseract-ocr \ tesseract-ocr-eng \ libtesseract-dev \ libleptonica-dev \ && apt-get clean \ && rm -rf /var/lib/apt/lists/* \ && mkdir -p /usr/src/build && cd /usr/src/build \ && git clone -b $OPENCV_VERSION --depth 1 --recursive https://github.com/opencv/opencv.git \ && git clone -b $OPENCV_VERSION --depth 1 --recursive https://github.com/opencv/opencv_contrib.git \ && cd opencv && mkdir build && cd build \ && cmake \ -D CMAKE_BUILD_TYPE=RELEASE \ -D CMAKE_INSTALL_PREFIX=/usr/local \ -D INSTALL_C_EXAMPLES=OFF \ -D INSTALL_PYTHON_EXAMPLES=OFF \ -D OPENCV_EXTRA_MODULES_PATH=/usr/src/build/opencv_contrib/modules \ -D BUILD_EXAMPLES=OFF \ -D FFMPEG_INCLUDE_DIR=/usr/local/include \ -D FFMPEG_LIB_DIR=/usr/local/lib \ .. \ && make -j4 install && ldconfig \ && cd /usr/src/build && rm -rf opencv && rm -rf opencv_contrib \ && apt-get purge -y cmake && apt-get autoremove -y --purge # back to unpriviliged user ENV HOME /home/$NB_USER
midvalestudent/jupyter
docker/image/Dockerfile
Dockerfile
mit
3,569
[ 30522, 2013, 3054, 17479, 3367, 12672, 3372, 1013, 18414, 7685, 3334, 1011, 16596, 7685, 1024, 6745, 5310, 7117, 4372, 2615, 2188, 1013, 7117, 5587, 5918, 1012, 19067, 2102, 1013, 2149, 2099, 1013, 2334, 1013, 3745, 1013, 5918, 1012, 19067,...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
package lua type Metatable struct { IndexFunc Function NewindexFunc Function TostringFunc Function GCFunc Function } func (this *Metatable) Index() Function { return this.IndexFunc } func (this *Metatable) Newindex() Function { return this.NewindexFunc } func (this *Metatable) Tostring() Function { return this.TostringFunc } func (this *Metatable) GC() Function { return this.GCFunc }
admin36/leaf
src/_lua/Metatable.go
GO
mit
427
[ 30522, 7427, 11320, 2050, 2828, 18804, 10880, 2358, 6820, 6593, 1063, 5950, 11263, 12273, 3853, 2047, 22254, 10288, 11263, 12273, 3853, 2000, 3367, 4892, 11263, 12273, 3853, 1043, 2278, 11263, 12273, 3853, 1065, 4569, 2278, 1006, 2023, 1008, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* Primary expression subroutines Copyright (C) 2000-2014 Free Software Foundation, Inc. Contributed by Andy Vaught This file is part of GCC. GCC is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. GCC 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 GCC; see the file COPYING3. If not see <http://www.gnu.org/licenses/>. */ #include "config.h" #include "system.h" #include "coretypes.h" #include "flags.h" #include "gfortran.h" #include "arith.h" #include "match.h" #include "parse.h" #include "constructor.h" int matching_actual_arglist = 0; /* Matches a kind-parameter expression, which is either a named symbolic constant or a nonnegative integer constant. If successful, sets the kind value to the correct integer. The argument 'is_iso_c' signals whether the kind is an ISO_C_BINDING symbol like e.g. 'c_int'. */ static match match_kind_param (int *kind, int *is_iso_c) { char name[GFC_MAX_SYMBOL_LEN + 1]; gfc_symbol *sym; const char *p; match m; *is_iso_c = 0; m = gfc_match_small_literal_int (kind, NULL); if (m != MATCH_NO) return m; m = gfc_match_name (name); if (m != MATCH_YES) return m; if (gfc_find_symbol (name, NULL, 1, &sym)) return MATCH_ERROR; if (sym == NULL) return MATCH_NO; *is_iso_c = sym->attr.is_iso_c; if (sym->attr.flavor != FL_PARAMETER) return MATCH_NO; if (sym->value == NULL) return MATCH_NO; p = gfc_extract_int (sym->value, kind); if (p != NULL) return MATCH_NO; gfc_set_sym_referenced (sym); if (*kind < 0) return MATCH_NO; return MATCH_YES; } /* Get a trailing kind-specification for non-character variables. Returns: * the integer kind value or * -1 if an error was generated, * -2 if no kind was found. The argument 'is_iso_c' signals whether the kind is an ISO_C_BINDING symbol like e.g. 'c_int'. */ static int get_kind (int *is_iso_c) { int kind; match m; *is_iso_c = 0; if (gfc_match_char ('_') != MATCH_YES) return -2; m = match_kind_param (&kind, is_iso_c); if (m == MATCH_NO) gfc_error ("Missing kind-parameter at %C"); return (m == MATCH_YES) ? kind : -1; } /* Given a character and a radix, see if the character is a valid digit in that radix. */ int gfc_check_digit (char c, int radix) { int r; switch (radix) { case 2: r = ('0' <= c && c <= '1'); break; case 8: r = ('0' <= c && c <= '7'); break; case 10: r = ('0' <= c && c <= '9'); break; case 16: r = ISXDIGIT (c); break; default: gfc_internal_error ("gfc_check_digit(): bad radix"); } return r; } /* Match the digit string part of an integer if signflag is not set, the signed digit string part if signflag is set. If the buffer is NULL, we just count characters for the resolution pass. Returns the number of characters matched, -1 for no match. */ static int match_digits (int signflag, int radix, char *buffer) { locus old_loc; int length; char c; length = 0; c = gfc_next_ascii_char (); if (signflag && (c == '+' || c == '-')) { if (buffer != NULL) *buffer++ = c; gfc_gobble_whitespace (); c = gfc_next_ascii_char (); length++; } if (!gfc_check_digit (c, radix)) return -1; length++; if (buffer != NULL) *buffer++ = c; for (;;) { old_loc = gfc_current_locus; c = gfc_next_ascii_char (); if (!gfc_check_digit (c, radix)) break; if (buffer != NULL) *buffer++ = c; length++; } gfc_current_locus = old_loc; return length; } /* Match an integer (digit string and optional kind). A sign will be accepted if signflag is set. */ static match match_integer_constant (gfc_expr **result, int signflag) { int length, kind, is_iso_c; locus old_loc; char *buffer; gfc_expr *e; old_loc = gfc_current_locus; gfc_gobble_whitespace (); length = match_digits (signflag, 10, NULL); gfc_current_locus = old_loc; if (length == -1) return MATCH_NO; buffer = (char *) alloca (length + 1); memset (buffer, '\0', length + 1); gfc_gobble_whitespace (); match_digits (signflag, 10, buffer); kind = get_kind (&is_iso_c); if (kind == -2) kind = gfc_default_integer_kind; if (kind == -1) return MATCH_ERROR; if (kind == 4 && gfc_option.flag_integer4_kind == 8) kind = 8; if (gfc_validate_kind (BT_INTEGER, kind, true) < 0) { gfc_error ("Integer kind %d at %C not available", kind); return MATCH_ERROR; } e = gfc_convert_integer (buffer, kind, 10, &gfc_current_locus); e->ts.is_c_interop = is_iso_c; if (gfc_range_check (e) != ARITH_OK) { gfc_error ("Integer too big for its kind at %C. This check can be " "disabled with the option -fno-range-check"); gfc_free_expr (e); return MATCH_ERROR; } *result = e; return MATCH_YES; } /* Match a Hollerith constant. */ static match match_hollerith_constant (gfc_expr **result) { locus old_loc; gfc_expr *e = NULL; const char *msg; int num, pad; int i; old_loc = gfc_current_locus; gfc_gobble_whitespace (); if (match_integer_constant (&e, 0) == MATCH_YES && gfc_match_char ('h') == MATCH_YES) { if (!gfc_notify_std (GFC_STD_LEGACY, "Hollerith constant at %C")) goto cleanup; msg = gfc_extract_int (e, &num); if (msg != NULL) { gfc_error (msg); goto cleanup; } if (num == 0) { gfc_error ("Invalid Hollerith constant: %L must contain at least " "one character", &old_loc); goto cleanup; } if (e->ts.kind != gfc_default_integer_kind) { gfc_error ("Invalid Hollerith constant: Integer kind at %L " "should be default", &old_loc); goto cleanup; } else { gfc_free_expr (e); e = gfc_get_constant_expr (BT_HOLLERITH, gfc_default_character_kind, &gfc_current_locus); /* Calculate padding needed to fit default integer memory. */ pad = gfc_default_integer_kind - (num % gfc_default_integer_kind); e->representation.string = XCNEWVEC (char, num + pad + 1); for (i = 0; i < num; i++) { gfc_char_t c = gfc_next_char_literal (INSTRING_WARN); if (! gfc_wide_fits_in_byte (c)) { gfc_error ("Invalid Hollerith constant at %L contains a " "wide character", &old_loc); goto cleanup; } e->representation.string[i] = (unsigned char) c; } /* Now pad with blanks and end with a null char. */ for (i = 0; i < pad; i++) e->representation.string[num + i] = ' '; e->representation.string[num + i] = '\0'; e->representation.length = num + pad; e->ts.u.pad = pad; *result = e; return MATCH_YES; } } gfc_free_expr (e); gfc_current_locus = old_loc; return MATCH_NO; cleanup: gfc_free_expr (e); return MATCH_ERROR; } /* Match a binary, octal or hexadecimal constant that can be found in a DATA statement. The standard permits b'010...', o'73...', and z'a1...' where b, o, and z can be capital letters. This function also accepts postfixed forms of the constants: '01...'b, '73...'o, and 'a1...'z. An additional extension is the use of x for z. */ static match match_boz_constant (gfc_expr **result) { int radix, length, x_hex, kind; locus old_loc, start_loc; char *buffer, post, delim; gfc_expr *e; start_loc = old_loc = gfc_current_locus; gfc_gobble_whitespace (); x_hex = 0; switch (post = gfc_next_ascii_char ()) { case 'b': radix = 2; post = 0; break; case 'o': radix = 8; post = 0; break; case 'x': x_hex = 1; /* Fall through. */ case 'z': radix = 16; post = 0; break; case '\'': /* Fall through. */ case '\"': delim = post; post = 1; radix = 16; /* Set to accept any valid digit string. */ break; default: goto backup; } /* No whitespace allowed here. */ if (post == 0) delim = gfc_next_ascii_char (); if (delim != '\'' && delim != '\"') goto backup; if (x_hex && (!gfc_notify_std(GFC_STD_GNU, "Hexadecimal " "constant at %C uses non-standard syntax"))) return MATCH_ERROR; old_loc = gfc_current_locus; length = match_digits (0, radix, NULL); if (length == -1) { gfc_error ("Empty set of digits in BOZ constant at %C"); return MATCH_ERROR; } if (gfc_next_ascii_char () != delim) { gfc_error ("Illegal character in BOZ constant at %C"); return MATCH_ERROR; } if (post == 1) { switch (gfc_next_ascii_char ()) { case 'b': radix = 2; break; case 'o': radix = 8; break; case 'x': /* Fall through. */ case 'z': radix = 16; break; default: goto backup; } if (!gfc_notify_std (GFC_STD_GNU, "BOZ constant " "at %C uses non-standard postfix syntax")) return MATCH_ERROR; } gfc_current_locus = old_loc; buffer = (char *) alloca (length + 1); memset (buffer, '\0', length + 1); match_digits (0, radix, buffer); gfc_next_ascii_char (); /* Eat delimiter. */ if (post == 1) gfc_next_ascii_char (); /* Eat postfixed b, o, z, or x. */ /* In section 5.2.5 and following C567 in the Fortran 2003 standard, we find "If a data-stmt-constant is a boz-literal-constant, the corresponding variable shall be of type integer. The boz-literal-constant is treated as if it were an int-literal-constant with a kind-param that specifies the representation method with the largest decimal exponent range supported by the processor." */ kind = gfc_max_integer_kind; e = gfc_convert_integer (buffer, kind, radix, &gfc_current_locus); /* Mark as boz variable. */ e->is_boz = 1; if (gfc_range_check (e) != ARITH_OK) { gfc_error ("Integer too big for integer kind %i at %C", kind); gfc_free_expr (e); return MATCH_ERROR; } if (!gfc_in_match_data () && (!gfc_notify_std(GFC_STD_F2003, "BOZ used outside a DATA " "statement at %C"))) return MATCH_ERROR; *result = e; return MATCH_YES; backup: gfc_current_locus = start_loc; return MATCH_NO; } /* Match a real constant of some sort. Allow a signed constant if signflag is nonzero. */ static match match_real_constant (gfc_expr **result, int signflag) { int kind, count, seen_dp, seen_digits, is_iso_c; locus old_loc, temp_loc; char *p, *buffer, c, exp_char; gfc_expr *e; bool negate; old_loc = gfc_current_locus; gfc_gobble_whitespace (); e = NULL; count = 0; seen_dp = 0; seen_digits = 0; exp_char = ' '; negate = FALSE; c = gfc_next_ascii_char (); if (signflag && (c == '+' || c == '-')) { if (c == '-') negate = TRUE; gfc_gobble_whitespace (); c = gfc_next_ascii_char (); } /* Scan significand. */ for (;; c = gfc_next_ascii_char (), count++) { if (c == '.') { if (seen_dp) goto done; /* Check to see if "." goes with a following operator like ".eq.". */ temp_loc = gfc_current_locus; c = gfc_next_ascii_char (); if (c == 'e' || c == 'd' || c == 'q') { c = gfc_next_ascii_char (); if (c == '.') goto done; /* Operator named .e. or .d. */ } if (ISALPHA (c)) goto done; /* Distinguish 1.e9 from 1.eq.2 */ gfc_current_locus = temp_loc; seen_dp = 1; continue; } if (ISDIGIT (c)) { seen_digits = 1; continue; } break; } if (!seen_digits || (c != 'e' && c != 'd' && c != 'q')) goto done; exp_char = c; if (c == 'q') { if (!gfc_notify_std (GFC_STD_GNU, "exponent-letter 'q' in " "real-literal-constant at %C")) return MATCH_ERROR; else if (gfc_option.warn_real_q_constant) gfc_warning("Extension: exponent-letter 'q' in real-literal-constant " "at %C"); } /* Scan exponent. */ c = gfc_next_ascii_char (); count++; if (c == '+' || c == '-') { /* optional sign */ c = gfc_next_ascii_char (); count++; } if (!ISDIGIT (c)) { gfc_error ("Missing exponent in real number at %C"); return MATCH_ERROR; } while (ISDIGIT (c)) { c = gfc_next_ascii_char (); count++; } done: /* Check that we have a numeric constant. */ if (!seen_digits || (!seen_dp && exp_char == ' ')) { gfc_current_locus = old_loc; return MATCH_NO; } /* Convert the number. */ gfc_current_locus = old_loc; gfc_gobble_whitespace (); buffer = (char *) alloca (count + 1); memset (buffer, '\0', count + 1); p = buffer; c = gfc_next_ascii_char (); if (c == '+' || c == '-') { gfc_gobble_whitespace (); c = gfc_next_ascii_char (); } /* Hack for mpfr_set_str(). */ for (;;) { if (c == 'd' || c == 'q') *p = 'e'; else *p = c; p++; if (--count == 0) break; c = gfc_next_ascii_char (); } kind = get_kind (&is_iso_c); if (kind == -1) goto cleanup; switch (exp_char) { case 'd': if (kind != -2) { gfc_error ("Real number at %C has a 'd' exponent and an explicit " "kind"); goto cleanup; } kind = gfc_default_double_kind; if (kind == 4) { if (gfc_option.flag_real4_kind == 8) kind = 8; if (gfc_option.flag_real4_kind == 10) kind = 10; if (gfc_option.flag_real4_kind == 16) kind = 16; } if (kind == 8) { if (gfc_option.flag_real8_kind == 4) kind = 4; if (gfc_option.flag_real8_kind == 10) kind = 10; if (gfc_option.flag_real8_kind == 16) kind = 16; } break; case 'q': if (kind != -2) { gfc_error ("Real number at %C has a 'q' exponent and an explicit " "kind"); goto cleanup; } /* The maximum possible real kind type parameter is 16. First, try that for the kind, then fallback to trying kind=10 (Intel 80 bit) extended precision. If neither value works, just given up. */ kind = 16; if (gfc_validate_kind (BT_REAL, kind, true) < 0) { kind = 10; if (gfc_validate_kind (BT_REAL, kind, true) < 0) { gfc_error ("Invalid exponent-letter 'q' in " "real-literal-constant at %C"); goto cleanup; } } break; default: if (kind == -2) kind = gfc_default_real_kind; if (kind == 4) { if (gfc_option.flag_real4_kind == 8) kind = 8; if (gfc_option.flag_real4_kind == 10) kind = 10; if (gfc_option.flag_real4_kind == 16) kind = 16; } if (kind == 8) { if (gfc_option.flag_real8_kind == 4) kind = 4; if (gfc_option.flag_real8_kind == 10) kind = 10; if (gfc_option.flag_real8_kind == 16) kind = 16; } if (gfc_validate_kind (BT_REAL, kind, true) < 0) { gfc_error ("Invalid real kind %d at %C", kind); goto cleanup; } } e = gfc_convert_real (buffer, kind, &gfc_current_locus); if (negate) mpfr_neg (e->value.real, e->value.real, GFC_RND_MODE); e->ts.is_c_interop = is_iso_c; switch (gfc_range_check (e)) { case ARITH_OK: break; case ARITH_OVERFLOW: gfc_error ("Real constant overflows its kind at %C"); goto cleanup; case ARITH_UNDERFLOW: if (gfc_option.warn_underflow) gfc_warning ("Real constant underflows its kind at %C"); mpfr_set_ui (e->value.real, 0, GFC_RND_MODE); break; default: gfc_internal_error ("gfc_range_check() returned bad value"); } *result = e; return MATCH_YES; cleanup: gfc_free_expr (e); return MATCH_ERROR; } /* Match a substring reference. */ static match match_substring (gfc_charlen *cl, int init, gfc_ref **result) { gfc_expr *start, *end; locus old_loc; gfc_ref *ref; match m; start = NULL; end = NULL; old_loc = gfc_current_locus; m = gfc_match_char ('('); if (m != MATCH_YES) return MATCH_NO; if (gfc_match_char (':') != MATCH_YES) { if (init) m = gfc_match_init_expr (&start); else m = gfc_match_expr (&start); if (m != MATCH_YES) { m = MATCH_NO; goto cleanup; } m = gfc_match_char (':'); if (m != MATCH_YES) goto cleanup; } if (gfc_match_char (')') != MATCH_YES) { if (init) m = gfc_match_init_expr (&end); else m = gfc_match_expr (&end); if (m == MATCH_NO) goto syntax; if (m == MATCH_ERROR) goto cleanup; m = gfc_match_char (')'); if (m == MATCH_NO) goto syntax; } /* Optimize away the (:) reference. */ if (start == NULL && end == NULL) ref = NULL; else { ref = gfc_get_ref (); ref->type = REF_SUBSTRING; if (start == NULL) start = gfc_get_int_expr (gfc_default_integer_kind, NULL, 1); ref->u.ss.start = start; if (end == NULL && cl) end = gfc_copy_expr (cl->length); ref->u.ss.end = end; ref->u.ss.length = cl; } *result = ref; return MATCH_YES; syntax: gfc_error ("Syntax error in SUBSTRING specification at %C"); m = MATCH_ERROR; cleanup: gfc_free_expr (start); gfc_free_expr (end); gfc_current_locus = old_loc; return m; } /* Reads the next character of a string constant, taking care to return doubled delimiters on the input as a single instance of the delimiter. Special return values for "ret" argument are: -1 End of the string, as determined by the delimiter -2 Unterminated string detected Backslash codes are also expanded at this time. */ static gfc_char_t next_string_char (gfc_char_t delimiter, int *ret) { locus old_locus; gfc_char_t c; c = gfc_next_char_literal (INSTRING_WARN); *ret = 0; if (c == '\n') { *ret = -2; return 0; } if (gfc_option.flag_backslash && c == '\\') { old_locus = gfc_current_locus; if (gfc_match_special_char (&c) == MATCH_NO) gfc_current_locus = old_locus; if (!(gfc_option.allow_std & GFC_STD_GNU) && !inhibit_warnings) gfc_warning ("Extension: backslash character at %C"); } if (c != delimiter) return c; old_locus = gfc_current_locus; c = gfc_next_char_literal (NONSTRING); if (c == delimiter) return c; gfc_current_locus = old_locus; *ret = -1; return 0; } /* Special case of gfc_match_name() that matches a parameter kind name before a string constant. This takes case of the weird but legal case of: kind_____'string' where kind____ is a parameter. gfc_match_name() will happily slurp up all the underscores, which leads to problems. If we return MATCH_YES, the parse pointer points to the final underscore, which is not part of the name. We never return MATCH_ERROR-- errors in the name will be detected later. */ static match match_charkind_name (char *name) { locus old_loc; char c, peek; int len; gfc_gobble_whitespace (); c = gfc_next_ascii_char (); if (!ISALPHA (c)) return MATCH_NO; *name++ = c; len = 1; for (;;) { old_loc = gfc_current_locus; c = gfc_next_ascii_char (); if (c == '_') { peek = gfc_peek_ascii_char (); if (peek == '\'' || peek == '\"') { gfc_current_locus = old_loc; *name = '\0'; return MATCH_YES; } } if (!ISALNUM (c) && c != '_' && (c != '$' || !gfc_option.flag_dollar_ok)) break; *name++ = c; if (++len > GFC_MAX_SYMBOL_LEN) break; } return MATCH_NO; } /* See if the current input matches a character constant. Lots of contortions have to be done to match the kind parameter which comes before the actual string. The main consideration is that we don't want to error out too quickly. For example, we don't actually do any validation of the kinds until we have actually seen a legal delimiter. Using match_kind_param() generates errors too quickly. */ static match match_string_constant (gfc_expr **result) { char name[GFC_MAX_SYMBOL_LEN + 1], peek; int i, kind, length, warn_ampersand, ret; locus old_locus, start_locus; gfc_symbol *sym; gfc_expr *e; const char *q; match m; gfc_char_t c, delimiter, *p; old_locus = gfc_current_locus; gfc_gobble_whitespace (); c = gfc_next_char (); if (c == '\'' || c == '"') { kind = gfc_default_character_kind; start_locus = gfc_current_locus; goto got_delim; } if (gfc_wide_is_digit (c)) { kind = 0; while (gfc_wide_is_digit (c)) { kind = kind * 10 + c - '0'; if (kind > 9999999) goto no_match; c = gfc_next_char (); } } else { gfc_current_locus = old_locus; m = match_charkind_name (name); if (m != MATCH_YES) goto no_match; if (gfc_find_symbol (name, NULL, 1, &sym) || sym == NULL || sym->attr.flavor != FL_PARAMETER) goto no_match; kind = -1; c = gfc_next_char (); } if (c == ' ') { gfc_gobble_whitespace (); c = gfc_next_char (); } if (c != '_') goto no_match; gfc_gobble_whitespace (); c = gfc_next_char (); if (c != '\'' && c != '"') goto no_match; start_locus = gfc_current_locus; if (kind == -1) { q = gfc_extract_int (sym->value, &kind); if (q != NULL) { gfc_error (q); return MATCH_ERROR; } gfc_set_sym_referenced (sym); } if (gfc_validate_kind (BT_CHARACTER, kind, true) < 0) { gfc_error ("Invalid kind %d for CHARACTER constant at %C", kind); return MATCH_ERROR; } got_delim: /* Scan the string into a block of memory by first figuring out how long it is, allocating the structure, then re-reading it. This isn't particularly efficient, but string constants aren't that common in most code. TODO: Use obstacks? */ delimiter = c; length = 0; for (;;) { c = next_string_char (delimiter, &ret); if (ret == -1) break; if (ret == -2) { gfc_current_locus = start_locus; gfc_error ("Unterminated character constant beginning at %C"); return MATCH_ERROR; } length++; } /* Peek at the next character to see if it is a b, o, z, or x for the postfixed BOZ literal constants. */ peek = gfc_peek_ascii_char (); if (peek == 'b' || peek == 'o' || peek =='z' || peek == 'x') goto no_match; e = gfc_get_character_expr (kind, &start_locus, NULL, length); gfc_current_locus = start_locus; /* We disable the warning for the following loop as the warning has already been printed in the loop above. */ warn_ampersand = gfc_option.warn_ampersand; gfc_option.warn_ampersand = 0; p = e->value.character.string; for (i = 0; i < length; i++) { c = next_string_char (delimiter, &ret); if (!gfc_check_character_range (c, kind)) { gfc_free_expr (e); gfc_error ("Character '%s' in string at %C is not representable " "in character kind %d", gfc_print_wide_char (c), kind); return MATCH_ERROR; } *p++ = c; } *p = '\0'; /* TODO: C-style string is for development/debug purposes. */ gfc_option.warn_ampersand = warn_ampersand; next_string_char (delimiter, &ret); if (ret != -1) gfc_internal_error ("match_string_constant(): Delimiter not found"); if (match_substring (NULL, 0, &e->ref) != MATCH_NO) e->expr_type = EXPR_SUBSTRING; *result = e; return MATCH_YES; no_match: gfc_current_locus = old_locus; return MATCH_NO; } /* Match a .true. or .false. Returns 1 if a .true. was found, 0 if a .false. was found, and -1 otherwise. */ static int match_logical_constant_string (void) { locus orig_loc = gfc_current_locus; gfc_gobble_whitespace (); if (gfc_next_ascii_char () == '.') { char ch = gfc_next_ascii_char (); if (ch == 'f') { if (gfc_next_ascii_char () == 'a' && gfc_next_ascii_char () == 'l' && gfc_next_ascii_char () == 's' && gfc_next_ascii_char () == 'e' && gfc_next_ascii_char () == '.') /* Matched ".false.". */ return 0; } else if (ch == 't') { if (gfc_next_ascii_char () == 'r' && gfc_next_ascii_char () == 'u' && gfc_next_ascii_char () == 'e' && gfc_next_ascii_char () == '.') /* Matched ".true.". */ return 1; } } gfc_current_locus = orig_loc; return -1; } /* Match a .true. or .false. */ static match match_logical_constant (gfc_expr **result) { gfc_expr *e; int i, kind, is_iso_c; i = match_logical_constant_string (); if (i == -1) return MATCH_NO; kind = get_kind (&is_iso_c); if (kind == -1) return MATCH_ERROR; if (kind == -2) kind = gfc_default_logical_kind; if (gfc_validate_kind (BT_LOGICAL, kind, true) < 0) { gfc_error ("Bad kind for logical constant at %C"); return MATCH_ERROR; } e = gfc_get_logical_expr (kind, &gfc_current_locus, i); e->ts.is_c_interop = is_iso_c; *result = e; return MATCH_YES; } /* Match a real or imaginary part of a complex constant that is a symbolic constant. */ static match match_sym_complex_part (gfc_expr **result) { char name[GFC_MAX_SYMBOL_LEN + 1]; gfc_symbol *sym; gfc_expr *e; match m; m = gfc_match_name (name); if (m != MATCH_YES) return m; if (gfc_find_symbol (name, NULL, 1, &sym) || sym == NULL) return MATCH_NO; if (sym->attr.flavor != FL_PARAMETER) { gfc_error ("Expected PARAMETER symbol in complex constant at %C"); return MATCH_ERROR; } if (!gfc_numeric_ts (&sym->value->ts)) { gfc_error ("Numeric PARAMETER required in complex constant at %C"); return MATCH_ERROR; } if (sym->value->rank != 0) { gfc_error ("Scalar PARAMETER required in complex constant at %C"); return MATCH_ERROR; } if (!gfc_notify_std (GFC_STD_F2003, "PARAMETER symbol in " "complex constant at %C")) return MATCH_ERROR; switch (sym->value->ts.type) { case BT_REAL: e = gfc_copy_expr (sym->value); break; case BT_COMPLEX: e = gfc_complex2real (sym->value, sym->value->ts.kind); if (e == NULL) goto error; break; case BT_INTEGER: e = gfc_int2real (sym->value, gfc_default_real_kind); if (e == NULL) goto error; break; default: gfc_internal_error ("gfc_match_sym_complex_part(): Bad type"); } *result = e; /* e is a scalar, real, constant expression. */ return MATCH_YES; error: gfc_error ("Error converting PARAMETER constant in complex constant at %C"); return MATCH_ERROR; } /* Match a real or imaginary part of a complex number. */ static match match_complex_part (gfc_expr **result) { match m; m = match_sym_complex_part (result); if (m != MATCH_NO) return m; m = match_real_constant (result, 1); if (m != MATCH_NO) return m; return match_integer_constant (result, 1); } /* Try to match a complex constant. */ static match match_complex_constant (gfc_expr **result) { gfc_expr *e, *real, *imag; gfc_error_buf old_error; gfc_typespec target; locus old_loc; int kind; match m; old_loc = gfc_current_locus; real = imag = e = NULL; m = gfc_match_char ('('); if (m != MATCH_YES) return m; gfc_push_error (&old_error); m = match_complex_part (&real); if (m == MATCH_NO) { gfc_free_error (&old_error); goto cleanup; } if (gfc_match_char (',') == MATCH_NO) { gfc_pop_error (&old_error); m = MATCH_NO; goto cleanup; } /* If m is error, then something was wrong with the real part and we assume we have a complex constant because we've seen the ','. An ambiguous case here is the start of an iterator list of some sort. These sort of lists are matched prior to coming here. */ if (m == MATCH_ERROR) { gfc_free_error (&old_error); goto cleanup; } gfc_pop_error (&old_error); m = match_complex_part (&imag); if (m == MATCH_NO) goto syntax; if (m == MATCH_ERROR) goto cleanup; m = gfc_match_char (')'); if (m == MATCH_NO) { /* Give the matcher for implied do-loops a chance to run. This yields a much saner error message for (/ (i, 4=i, 6) /). */ if (gfc_peek_ascii_char () == '=') { m = MATCH_ERROR; goto cleanup; } else goto syntax; } if (m == MATCH_ERROR) goto cleanup; /* Decide on the kind of this complex number. */ if (real->ts.type == BT_REAL) { if (imag->ts.type == BT_REAL) kind = gfc_kind_max (real, imag); else kind = real->ts.kind; } else { if (imag->ts.type == BT_REAL) kind = imag->ts.kind; else kind = gfc_default_real_kind; } gfc_clear_ts (&target); target.type = BT_REAL; target.kind = kind; if (real->ts.type != BT_REAL || kind != real->ts.kind) gfc_convert_type (real, &target, 2); if (imag->ts.type != BT_REAL || kind != imag->ts.kind) gfc_convert_type (imag, &target, 2); e = gfc_convert_complex (real, imag, kind); e->where = gfc_current_locus; gfc_free_expr (real); gfc_free_expr (imag); *result = e; return MATCH_YES; syntax: gfc_error ("Syntax error in COMPLEX constant at %C"); m = MATCH_ERROR; cleanup: gfc_free_expr (e); gfc_free_expr (real); gfc_free_expr (imag); gfc_current_locus = old_loc; return m; } /* Match constants in any of several forms. Returns nonzero for a match, zero for no match. */ match gfc_match_literal_constant (gfc_expr **result, int signflag) { match m; m = match_complex_constant (result); if (m != MATCH_NO) return m; m = match_string_constant (result); if (m != MATCH_NO) return m; m = match_boz_constant (result); if (m != MATCH_NO) return m; m = match_real_constant (result, signflag); if (m != MATCH_NO) return m; m = match_hollerith_constant (result); if (m != MATCH_NO) return m; m = match_integer_constant (result, signflag); if (m != MATCH_NO) return m; m = match_logical_constant (result); if (m != MATCH_NO) return m; return MATCH_NO; } /* This checks if a symbol is the return value of an encompassing function. Function nesting can be maximally two levels deep, but we may have additional local namespaces like BLOCK etc. */ bool gfc_is_function_return_value (gfc_symbol *sym, gfc_namespace *ns) { if (!sym->attr.function || (sym->result != sym)) return false; while (ns) { if (ns->proc_name == sym) return true; ns = ns->parent; } return false; } /* Match a single actual argument value. An actual argument is usually an expression, but can also be a procedure name. If the argument is a single name, it is not always possible to tell whether the name is a dummy procedure or not. We treat these cases by creating an argument that looks like a dummy procedure and fixing things later during resolution. */ static match match_actual_arg (gfc_expr **result) { char name[GFC_MAX_SYMBOL_LEN + 1]; gfc_symtree *symtree; locus where, w; gfc_expr *e; char c; gfc_gobble_whitespace (); where = gfc_current_locus; switch (gfc_match_name (name)) { case MATCH_ERROR: return MATCH_ERROR; case MATCH_NO: break; case MATCH_YES: w = gfc_current_locus; gfc_gobble_whitespace (); c = gfc_next_ascii_char (); gfc_current_locus = w; if (c != ',' && c != ')') break; if (gfc_find_sym_tree (name, NULL, 1, &symtree)) break; /* Handle error elsewhere. */ /* Eliminate a couple of common cases where we know we don't have a function argument. */ if (symtree == NULL) { gfc_get_sym_tree (name, NULL, &symtree, false); gfc_set_sym_referenced (symtree->n.sym); } else { gfc_symbol *sym; sym = symtree->n.sym; gfc_set_sym_referenced (sym); if (sym->attr.flavor != FL_PROCEDURE && sym->attr.flavor != FL_UNKNOWN) break; if (sym->attr.in_common && !sym->attr.proc_pointer) { if (!gfc_add_flavor (&sym->attr, FL_VARIABLE, sym->name, &sym->declared_at)) return MATCH_ERROR; break; } /* If the symbol is a function with itself as the result and is being defined, then we have a variable. */ if (sym->attr.function && sym->result == sym) { if (gfc_is_function_return_value (sym, gfc_current_ns)) break; if (sym->attr.entry && (sym->ns == gfc_current_ns || sym->ns == gfc_current_ns->parent)) { gfc_entry_list *el = NULL; for (el = sym->ns->entries; el; el = el->next) if (sym == el->sym) break; if (el) break; } } } e = gfc_get_expr (); /* Leave it unknown for now */ e->symtree = symtree; e->expr_type = EXPR_VARIABLE; e->ts.type = BT_PROCEDURE; e->where = where; *result = e; return MATCH_YES; } gfc_current_locus = where; return gfc_match_expr (result); } /* Match a keyword argument. */ static match match_keyword_arg (gfc_actual_arglist *actual, gfc_actual_arglist *base) { char name[GFC_MAX_SYMBOL_LEN + 1]; gfc_actual_arglist *a; locus name_locus; match m; name_locus = gfc_current_locus; m = gfc_match_name (name); if (m != MATCH_YES) goto cleanup; if (gfc_match_char ('=') != MATCH_YES) { m = MATCH_NO; goto cleanup; } m = match_actual_arg (&actual->expr); if (m != MATCH_YES) goto cleanup; /* Make sure this name has not appeared yet. */ if (name[0] != '\0') { for (a = base; a; a = a->next) if (a->name != NULL && strcmp (a->name, name) == 0) { gfc_error ("Keyword '%s' at %C has already appeared in the " "current argument list", name); return MATCH_ERROR; } } actual->name = gfc_get_string (name); return MATCH_YES; cleanup: gfc_current_locus = name_locus; return m; } /* Match an argument list function, such as %VAL. */ static match match_arg_list_function (gfc_actual_arglist *result) { char name[GFC_MAX_SYMBOL_LEN + 1]; locus old_locus; match m; old_locus = gfc_current_locus; if (gfc_match_char ('%') != MATCH_YES) { m = MATCH_NO; goto cleanup; } m = gfc_match ("%n (", name); if (m != MATCH_YES) goto cleanup; if (name[0] != '\0') { switch (name[0]) { case 'l': if (strncmp (name, "loc", 3) == 0) { result->name = "%LOC"; break; } case 'r': if (strncmp (name, "ref", 3) == 0) { result->name = "%REF"; break; } case 'v': if (strncmp (name, "val", 3) == 0) { result->name = "%VAL"; break; } default: m = MATCH_ERROR; goto cleanup; } } if (!gfc_notify_std (GFC_STD_GNU, "argument list function at %C")) { m = MATCH_ERROR; goto cleanup; } m = match_actual_arg (&result->expr); if (m != MATCH_YES) goto cleanup; if (gfc_match_char (')') != MATCH_YES) { m = MATCH_NO; goto cleanup; } return MATCH_YES; cleanup: gfc_current_locus = old_locus; return m; } /* Matches an actual argument list of a function or subroutine, from the opening parenthesis to the closing parenthesis. The argument list is assumed to allow keyword arguments because we don't know if the symbol associated with the procedure has an implicit interface or not. We make sure keywords are unique. If sub_flag is set, we're matching the argument list of a subroutine. */ match gfc_match_actual_arglist (int sub_flag, gfc_actual_arglist **argp) { gfc_actual_arglist *head, *tail; int seen_keyword; gfc_st_label *label; locus old_loc; match m; *argp = tail = NULL; old_loc = gfc_current_locus; seen_keyword = 0; if (gfc_match_char ('(') == MATCH_NO) return (sub_flag) ? MATCH_YES : MATCH_NO; if (gfc_match_char (')') == MATCH_YES) return MATCH_YES; head = NULL; matching_actual_arglist++; for (;;) { if (head == NULL) head = tail = gfc_get_actual_arglist (); else { tail->next = gfc_get_actual_arglist (); tail = tail->next; } if (sub_flag && gfc_match_char ('*') == MATCH_YES) { m = gfc_match_st_label (&label); if (m == MATCH_NO) gfc_error ("Expected alternate return label at %C"); if (m != MATCH_YES) goto cleanup; if (!gfc_notify_std (GFC_STD_F95_OBS, "Alternate-return argument " "at %C")) goto cleanup; tail->label = label; goto next; } /* After the first keyword argument is seen, the following arguments must also have keywords. */ if (seen_keyword) { m = match_keyword_arg (tail, head); if (m == MATCH_ERROR) goto cleanup; if (m == MATCH_NO) { gfc_error ("Missing keyword name in actual argument list at %C"); goto cleanup; } } else { /* Try an argument list function, like %VAL. */ m = match_arg_list_function (tail); if (m == MATCH_ERROR) goto cleanup; /* See if we have the first keyword argument. */ if (m == MATCH_NO) { m = match_keyword_arg (tail, head); if (m == MATCH_YES) seen_keyword = 1; if (m == MATCH_ERROR) goto cleanup; } if (m == MATCH_NO) { /* Try for a non-keyword argument. */ m = match_actual_arg (&tail->expr); if (m == MATCH_ERROR) goto cleanup; if (m == MATCH_NO) goto syntax; } } next: if (gfc_match_char (')') == MATCH_YES) break; if (gfc_match_char (',') != MATCH_YES) goto syntax; } *argp = head; matching_actual_arglist--; return MATCH_YES; syntax: gfc_error ("Syntax error in argument list at %C"); cleanup: gfc_free_actual_arglist (head); gfc_current_locus = old_loc; matching_actual_arglist--; return MATCH_ERROR; } /* Used by gfc_match_varspec() to extend the reference list by one element. */ static gfc_ref * extend_ref (gfc_expr *primary, gfc_ref *tail) { if (primary->ref == NULL) primary->ref = tail = gfc_get_ref (); else { if (tail == NULL) gfc_internal_error ("extend_ref(): Bad tail"); tail->next = gfc_get_ref (); tail = tail->next; } return tail; } /* Match any additional specifications associated with the current variable like member references or substrings. If equiv_flag is set we only match stuff that is allowed inside an EQUIVALENCE statement. sub_flag tells whether we expect a type-bound procedure found to be a subroutine as part of CALL or a FUNCTION. For procedure pointer components, 'ppc_arg' determines whether the PPC may be called (with an argument list), or whether it may just be referred to as a pointer. */ match gfc_match_varspec (gfc_expr *primary, int equiv_flag, bool sub_flag, bool ppc_arg) { char name[GFC_MAX_SYMBOL_LEN + 1]; gfc_ref *substring, *tail; gfc_component *component; gfc_symbol *sym = primary->symtree->n.sym; match m; bool unknown; tail = NULL; gfc_gobble_whitespace (); if (gfc_peek_ascii_char () == '[') { if ((sym->ts.type != BT_CLASS && sym->attr.dimension) || (sym->ts.type == BT_CLASS && CLASS_DATA (sym) && CLASS_DATA (sym)->attr.dimension)) { gfc_error ("Array section designator, e.g. '(:)', is required " "besides the coarray designator '[...]' at %C"); return MATCH_ERROR; } if ((sym->ts.type != BT_CLASS && !sym->attr.codimension) || (sym->ts.type == BT_CLASS && CLASS_DATA (sym) && !CLASS_DATA (sym)->attr.codimension)) { gfc_error ("Coarray designator at %C but '%s' is not a coarray", sym->name); return MATCH_ERROR; } } /* For associate names, we may not yet know whether they are arrays or not. Thus if we have one and parentheses follow, we have to assume that it actually is one for now. The final decision will be made at resolution time, of course. */ if (sym->assoc && gfc_peek_ascii_char () == '(') sym->attr.dimension = 1; if ((equiv_flag && gfc_peek_ascii_char () == '(') || gfc_peek_ascii_char () == '[' || sym->attr.codimension || (sym->attr.dimension && sym->ts.type != BT_CLASS && !sym->attr.proc_pointer && !gfc_is_proc_ptr_comp (primary) && !(gfc_matching_procptr_assignment && sym->attr.flavor == FL_PROCEDURE)) || (sym->ts.type == BT_CLASS && sym->attr.class_ok && (CLASS_DATA (sym)->attr.dimension || CLASS_DATA (sym)->attr.codimension))) { gfc_array_spec *as; tail = extend_ref (primary, tail); tail->type = REF_ARRAY; /* In EQUIVALENCE, we don't know yet whether we are seeing an array, character variable or array of character variables. We'll leave the decision till resolve time. */ if (equiv_flag) as = NULL; else if (sym->ts.type == BT_CLASS && CLASS_DATA (sym)) as = CLASS_DATA (sym)->as; else as = sym->as; m = gfc_match_array_ref (&tail->u.ar, as, equiv_flag, as ? as->corank : 0); if (m != MATCH_YES) return m; gfc_gobble_whitespace (); if (equiv_flag && gfc_peek_ascii_char () == '(') { tail = extend_ref (primary, tail); tail->type = REF_ARRAY; m = gfc_match_array_ref (&tail->u.ar, NULL, equiv_flag, 0); if (m != MATCH_YES) return m; } } primary->ts = sym->ts; if (equiv_flag) return MATCH_YES; if (sym->ts.type == BT_UNKNOWN && gfc_peek_ascii_char () == '%' && gfc_get_default_type (sym->name, sym->ns)->type == BT_DERIVED) gfc_set_default_type (sym, 0, sym->ns); if (sym->ts.type == BT_UNKNOWN && gfc_match_char ('%') == MATCH_YES) { gfc_error ("Symbol '%s' at %C has no IMPLICIT type", sym->name); return MATCH_ERROR; } else if ((sym->ts.type != BT_DERIVED && sym->ts.type != BT_CLASS) && gfc_match_char ('%') == MATCH_YES) { gfc_error ("Unexpected '%%' for nonderived-type variable '%s' at %C", sym->name); return MATCH_ERROR; } if ((sym->ts.type != BT_DERIVED && sym->ts.type != BT_CLASS) || gfc_match_char ('%') != MATCH_YES) goto check_substring; sym = sym->ts.u.derived; for (;;) { bool t; gfc_symtree *tbp; m = gfc_match_name (name); if (m == MATCH_NO) gfc_error ("Expected structure component name at %C"); if (m != MATCH_YES) return MATCH_ERROR; if (sym->f2k_derived) tbp = gfc_find_typebound_proc (sym, &t, name, false, &gfc_current_locus); else tbp = NULL; if (tbp) { gfc_symbol* tbp_sym; if (!t) return MATCH_ERROR; gcc_assert (!tail || !tail->next); if (!(primary->expr_type == EXPR_VARIABLE || (primary->expr_type == EXPR_STRUCTURE && primary->symtree && primary->symtree->n.sym && primary->symtree->n.sym->attr.flavor))) return MATCH_ERROR; if (tbp->n.tb->is_generic) tbp_sym = NULL; else tbp_sym = tbp->n.tb->u.specific->n.sym; primary->expr_type = EXPR_COMPCALL; primary->value.compcall.tbp = tbp->n.tb; primary->value.compcall.name = tbp->name; primary->value.compcall.ignore_pass = 0; primary->value.compcall.assign = 0; primary->value.compcall.base_object = NULL; gcc_assert (primary->symtree->n.sym->attr.referenced); if (tbp_sym) primary->ts = tbp_sym->ts; else gfc_clear_ts (&primary->ts); m = gfc_match_actual_arglist (tbp->n.tb->subroutine, &primary->value.compcall.actual); if (m == MATCH_ERROR) return MATCH_ERROR; if (m == MATCH_NO) { if (sub_flag) primary->value.compcall.actual = NULL; else { gfc_error ("Expected argument list at %C"); return MATCH_ERROR; } } break; } component = gfc_find_component (sym, name, false, false); if (component == NULL) return MATCH_ERROR; tail = extend_ref (primary, tail); tail->type = REF_COMPONENT; tail->u.c.component = component; tail->u.c.sym = sym; primary->ts = component->ts; if (component->attr.proc_pointer && ppc_arg) { /* Procedure pointer component call: Look for argument list. */ m = gfc_match_actual_arglist (sub_flag, &primary->value.compcall.actual); if (m == MATCH_ERROR) return MATCH_ERROR; if (m == MATCH_NO && !gfc_matching_ptr_assignment && !gfc_matching_procptr_assignment && !matching_actual_arglist) { gfc_error ("Procedure pointer component '%s' requires an " "argument list at %C", component->name); return MATCH_ERROR; } if (m == MATCH_YES) primary->expr_type = EXPR_PPC; break; } if (component->as != NULL && !component->attr.proc_pointer) { tail = extend_ref (primary, tail); tail->type = REF_ARRAY; m = gfc_match_array_ref (&tail->u.ar, component->as, equiv_flag, component->as->corank); if (m != MATCH_YES) return m; } else if (component->ts.type == BT_CLASS && component->attr.class_ok && CLASS_DATA (component)->as && !component->attr.proc_pointer) { tail = extend_ref (primary, tail); tail->type = REF_ARRAY; m = gfc_match_array_ref (&tail->u.ar, CLASS_DATA (component)->as, equiv_flag, CLASS_DATA (component)->as->corank); if (m != MATCH_YES) return m; } if ((component->ts.type != BT_DERIVED && component->ts.type != BT_CLASS) || gfc_match_char ('%') != MATCH_YES) break; sym = component->ts.u.derived; } check_substring: unknown = false; if (primary->ts.type == BT_UNKNOWN && sym->attr.flavor != FL_DERIVED) { if (gfc_get_default_type (sym->name, sym->ns)->type == BT_CHARACTER) { gfc_set_default_type (sym, 0, sym->ns); primary->ts = sym->ts; unknown = true; } } if (primary->ts.type == BT_CHARACTER) { switch (match_substring (primary->ts.u.cl, equiv_flag, &substring)) { case MATCH_YES: if (tail == NULL) primary->ref = substring; else tail->next = substring; if (primary->expr_type == EXPR_CONSTANT) primary->expr_type = EXPR_SUBSTRING; if (substring) primary->ts.u.cl = NULL; break; case MATCH_NO: if (unknown) { gfc_clear_ts (&primary->ts); gfc_clear_ts (&sym->ts); } break; case MATCH_ERROR: return MATCH_ERROR; } } /* F2008, C727. */ if (primary->expr_type == EXPR_PPC && gfc_is_coindexed (primary)) { gfc_error ("Coindexed procedure-pointer component at %C"); return MATCH_ERROR; } return MATCH_YES; } /* Given an expression that is a variable, figure out what the ultimate variable's type and attribute is, traversing the reference structures if necessary. This subroutine is trickier than it looks. We start at the base symbol and store the attribute. Component references load a completely new attribute. A couple of rules come into play. Subobjects of targets are always targets themselves. If we see a component that goes through a pointer, then the expression must also be a target, since the pointer is associated with something (if it isn't core will soon be dumped). If we see a full part or section of an array, the expression is also an array. We can have at most one full array reference. */ symbol_attribute gfc_variable_attr (gfc_expr *expr, gfc_typespec *ts) { int dimension, codimension, pointer, allocatable, target; symbol_attribute attr; gfc_ref *ref; gfc_symbol *sym; gfc_component *comp; if (expr->expr_type != EXPR_VARIABLE && expr->expr_type != EXPR_FUNCTION) gfc_internal_error ("gfc_variable_attr(): Expression isn't a variable"); sym = expr->symtree->n.sym; attr = sym->attr; if (sym->ts.type == BT_CLASS && sym->attr.class_ok) { dimension = CLASS_DATA (sym)->attr.dimension; codimension = CLASS_DATA (sym)->attr.codimension; pointer = CLASS_DATA (sym)->attr.class_pointer; allocatable = CLASS_DATA (sym)->attr.allocatable; } else { dimension = attr.dimension; codimension = attr.codimension; pointer = attr.pointer; allocatable = attr.allocatable; } target = attr.target; if (pointer || attr.proc_pointer) target = 1; if (ts != NULL && expr->ts.type == BT_UNKNOWN) *ts = sym->ts; for (ref = expr->ref; ref; ref = ref->next) switch (ref->type) { case REF_ARRAY: switch (ref->u.ar.type) { case AR_FULL: dimension = 1; break; case AR_SECTION: allocatable = pointer = 0; dimension = 1; break; case AR_ELEMENT: /* Handle coarrays. */ if (ref->u.ar.dimen > 0) allocatable = pointer = 0; break; case AR_UNKNOWN: gfc_internal_error ("gfc_variable_attr(): Bad array reference"); } break; case REF_COMPONENT: comp = ref->u.c.component; attr = comp->attr; if (ts != NULL) { *ts = comp->ts; /* Don't set the string length if a substring reference follows. */ if (ts->type == BT_CHARACTER && ref->next && ref->next->type == REF_SUBSTRING) ts->u.cl = NULL; } if (comp->ts.type == BT_CLASS) { codimension = CLASS_DATA (comp)->attr.codimension; pointer = CLASS_DATA (comp)->attr.class_pointer; allocatable = CLASS_DATA (comp)->attr.allocatable; } else { codimension = comp->attr.codimension; pointer = comp->attr.pointer; allocatable = comp->attr.allocatable; } if (pointer || attr.proc_pointer) target = 1; break; case REF_SUBSTRING: allocatable = pointer = 0; break; } attr.dimension = dimension; attr.codimension = codimension; attr.pointer = pointer; attr.allocatable = allocatable; attr.target = target; attr.save = sym->attr.save; return attr; } /* Return the attribute from a general expression. */ symbol_attribute gfc_expr_attr (gfc_expr *e) { symbol_attribute attr; switch (e->expr_type) { case EXPR_VARIABLE: attr = gfc_variable_attr (e, NULL); break; case EXPR_FUNCTION: gfc_clear_attr (&attr); if (e->value.function.esym && e->value.function.esym->result) { gfc_symbol *sym = e->value.function.esym->result; attr = sym->attr; if (sym->ts.type == BT_CLASS) { attr.dimension = CLASS_DATA (sym)->attr.dimension; attr.pointer = CLASS_DATA (sym)->attr.class_pointer; attr.allocatable = CLASS_DATA (sym)->attr.allocatable; } } else attr = gfc_variable_attr (e, NULL); /* TODO: NULL() returns pointers. May have to take care of this here. */ break; default: gfc_clear_attr (&attr); break; } return attr; } /* Match a structure constructor. The initial symbol has already been seen. */ typedef struct gfc_structure_ctor_component { char* name; gfc_expr* val; locus where; struct gfc_structure_ctor_component* next; } gfc_structure_ctor_component; #define gfc_get_structure_ctor_component() XCNEW (gfc_structure_ctor_component) static void gfc_free_structure_ctor_component (gfc_structure_ctor_component *comp) { free (comp->name); gfc_free_expr (comp->val); free (comp); } /* Translate the component list into the actual constructor by sorting it in the order required; this also checks along the way that each and every component actually has an initializer and handles default initializers for components without explicit value given. */ static bool build_actual_constructor (gfc_structure_ctor_component **comp_head, gfc_constructor_base *ctor_head, gfc_symbol *sym) { gfc_structure_ctor_component *comp_iter; gfc_component *comp; for (comp = sym->components; comp; comp = comp->next) { gfc_structure_ctor_component **next_ptr; gfc_expr *value = NULL; /* Try to find the initializer for the current component by name. */ next_ptr = comp_head; for (comp_iter = *comp_head; comp_iter; comp_iter = comp_iter->next) { if (!strcmp (comp_iter->name, comp->name)) break; next_ptr = &comp_iter->next; } /* If an extension, try building the parent derived type by building a value expression for the parent derived type and calling self. */ if (!comp_iter && comp == sym->components && sym->attr.extension) { value = gfc_get_structure_constructor_expr (comp->ts.type, comp->ts.kind, &gfc_current_locus); value->ts = comp->ts; if (!build_actual_constructor (comp_head, &value->value.constructor, comp->ts.u.derived)) { gfc_free_expr (value); return false; } gfc_constructor_append_expr (ctor_head, value, NULL); continue; } /* If it was not found, try the default initializer if there's any; otherwise, it's an error. */ if (!comp_iter) { if (comp->initializer) { if (!gfc_notify_std (GFC_STD_F2003, "Structure constructor " "with missing optional arguments at %C")) return false; value = gfc_copy_expr (comp->initializer); } else { gfc_error ("No initializer for component '%s' given in the" " structure constructor at %C!", comp->name); return false; } } else value = comp_iter->val; /* Add the value to the constructor chain built. */ gfc_constructor_append_expr (ctor_head, value, NULL); /* Remove the entry from the component list. We don't want the expression value to be free'd, so set it to NULL. */ if (comp_iter) { *next_ptr = comp_iter->next; comp_iter->val = NULL; gfc_free_structure_ctor_component (comp_iter); } } return true; } bool gfc_convert_to_structure_constructor (gfc_expr *e, gfc_symbol *sym, gfc_expr **cexpr, gfc_actual_arglist **arglist, bool parent) { gfc_actual_arglist *actual; gfc_structure_ctor_component *comp_tail, *comp_head, *comp_iter; gfc_constructor_base ctor_head = NULL; gfc_component *comp; /* Is set NULL when named component is first seen */ const char* last_name = NULL; locus old_locus; gfc_expr *expr; expr = parent ? *cexpr : e; old_locus = gfc_current_locus; if (parent) ; /* gfc_current_locus = *arglist->expr ? ->where;*/ else gfc_current_locus = expr->where; comp_tail = comp_head = NULL; if (!parent && sym->attr.abstract) { gfc_error ("Can't construct ABSTRACT type '%s' at %L", sym->name, &expr->where); goto cleanup; } comp = sym->components; actual = parent ? *arglist : expr->value.function.actual; for ( ; actual; ) { gfc_component *this_comp = NULL; if (!comp_head) comp_tail = comp_head = gfc_get_structure_ctor_component (); else { comp_tail->next = gfc_get_structure_ctor_component (); comp_tail = comp_tail->next; } if (actual->name) { if (!gfc_notify_std (GFC_STD_F2003, "Structure" " constructor with named arguments at %C")) goto cleanup; comp_tail->name = xstrdup (actual->name); last_name = comp_tail->name; comp = NULL; } else { /* Components without name are not allowed after the first named component initializer! */ if (!comp) { if (last_name) gfc_error ("Component initializer without name after component" " named %s at %L!", last_name, actual->expr ? &actual->expr->where : &gfc_current_locus); else gfc_error ("Too many components in structure constructor at " "%L!", actual->expr ? &actual->expr->where : &gfc_current_locus); goto cleanup; } comp_tail->name = xstrdup (comp->name); } /* Find the current component in the structure definition and check its access is not private. */ if (comp) this_comp = gfc_find_component (sym, comp->name, false, false); else { this_comp = gfc_find_component (sym, (const char *)comp_tail->name, false, false); comp = NULL; /* Reset needed! */ } /* Here we can check if a component name is given which does not correspond to any component of the defined structure. */ if (!this_comp) goto cleanup; comp_tail->val = actual->expr; if (actual->expr != NULL) comp_tail->where = actual->expr->where; actual->expr = NULL; /* Check if this component is already given a value. */ for (comp_iter = comp_head; comp_iter != comp_tail; comp_iter = comp_iter->next) { gcc_assert (comp_iter); if (!strcmp (comp_iter->name, comp_tail->name)) { gfc_error ("Component '%s' is initialized twice in the structure" " constructor at %L!", comp_tail->name, comp_tail->val ? &comp_tail->where : &gfc_current_locus); goto cleanup; } } /* F2008, R457/C725, for PURE C1283. */ if (this_comp->attr.pointer && comp_tail->val && gfc_is_coindexed (comp_tail->val)) { gfc_error ("Coindexed expression to pointer component '%s' in " "structure constructor at %L!", comp_tail->name, &comp_tail->where); goto cleanup; } /* If not explicitly a parent constructor, gather up the components and build one. */ if (comp && comp == sym->components && sym->attr.extension && comp_tail->val && (comp_tail->val->ts.type != BT_DERIVED || comp_tail->val->ts.u.derived != this_comp->ts.u.derived)) { bool m; gfc_actual_arglist *arg_null = NULL; actual->expr = comp_tail->val; comp_tail->val = NULL; m = gfc_convert_to_structure_constructor (NULL, comp->ts.u.derived, &comp_tail->val, comp->ts.u.derived->attr.zero_comp ? &arg_null : &actual, true); if (!m) goto cleanup; if (comp->ts.u.derived->attr.zero_comp) { comp = comp->next; continue; } } if (comp) comp = comp->next; if (parent && !comp) break; if (actual) actual = actual->next; } if (!build_actual_constructor (&comp_head, &ctor_head, sym)) goto cleanup; /* No component should be left, as this should have caused an error in the loop constructing the component-list (name that does not correspond to any component in the structure definition). */ if (comp_head && sym->attr.extension) { for (comp_iter = comp_head; comp_iter; comp_iter = comp_iter->next) { gfc_error ("component '%s' at %L has already been set by a " "parent derived type constructor", comp_iter->name, &comp_iter->where); } goto cleanup; } else gcc_assert (!comp_head); if (parent) { expr = gfc_get_structure_constructor_expr (BT_DERIVED, 0, &gfc_current_locus); expr->ts.u.derived = sym; expr->value.constructor = ctor_head; *cexpr = expr; } else { expr->ts.u.derived = sym; expr->ts.kind = 0; expr->ts.type = BT_DERIVED; expr->value.constructor = ctor_head; expr->expr_type = EXPR_STRUCTURE; } gfc_current_locus = old_locus; if (parent) *arglist = actual; return true; cleanup: gfc_current_locus = old_locus; for (comp_iter = comp_head; comp_iter; ) { gfc_structure_ctor_component *next = comp_iter->next; gfc_free_structure_ctor_component (comp_iter); comp_iter = next; } gfc_constructor_free (ctor_head); return false; } match gfc_match_structure_constructor (gfc_symbol *sym, gfc_expr **result) { match m; gfc_expr *e; gfc_symtree *symtree; gfc_get_sym_tree (sym->name, NULL, &symtree, false); /* Can't fail */ e = gfc_get_expr (); e->symtree = symtree; e->expr_type = EXPR_FUNCTION; gcc_assert (sym->attr.flavor == FL_DERIVED && symtree->n.sym->attr.flavor == FL_PROCEDURE); e->value.function.esym = sym; e->symtree->n.sym->attr.generic = 1; m = gfc_match_actual_arglist (0, &e->value.function.actual); if (m != MATCH_YES) { gfc_free_expr (e); return m; } if (!gfc_convert_to_structure_constructor (e, sym, NULL, NULL, false)) { gfc_free_expr (e); return MATCH_ERROR; } *result = e; return MATCH_YES; } /* If the symbol is an implicit do loop index and implicitly typed, it should not be host associated. Provide a symtree from the current namespace. */ static match check_for_implicit_index (gfc_symtree **st, gfc_symbol **sym) { if ((*sym)->attr.flavor == FL_VARIABLE && (*sym)->ns != gfc_current_ns && (*sym)->attr.implied_index && (*sym)->attr.implicit_type && !(*sym)->attr.use_assoc) { int i; i = gfc_get_sym_tree ((*sym)->name, NULL, st, false); if (i) return MATCH_ERROR; *sym = (*st)->n.sym; } return MATCH_YES; } /* Procedure pointer as function result: Replace the function symbol by the auto-generated hidden result variable named "ppr@". */ static bool replace_hidden_procptr_result (gfc_symbol **sym, gfc_symtree **st) { /* Check for procedure pointer result variable. */ if ((*sym)->attr.function && !(*sym)->attr.external && (*sym)->result && (*sym)->result != *sym && (*sym)->result->attr.proc_pointer && (*sym) == gfc_current_ns->proc_name && (*sym) == (*sym)->result->ns->proc_name && strcmp ("ppr@", (*sym)->result->name) == 0) { /* Automatic replacement with "hidden" result variable. */ (*sym)->result->attr.referenced = (*sym)->attr.referenced; *sym = (*sym)->result; *st = gfc_find_symtree ((*sym)->ns->sym_root, (*sym)->name); return true; } return false; } /* Matches a variable name followed by anything that might follow it-- array reference, argument list of a function, etc. */ match gfc_match_rvalue (gfc_expr **result) { gfc_actual_arglist *actual_arglist; char name[GFC_MAX_SYMBOL_LEN + 1], argname[GFC_MAX_SYMBOL_LEN + 1]; gfc_state_data *st; gfc_symbol *sym; gfc_symtree *symtree; locus where, old_loc; gfc_expr *e; match m, m2; int i; gfc_typespec *ts; bool implicit_char; gfc_ref *ref; m = gfc_match_name (name); if (m != MATCH_YES) return m; if (gfc_find_state (COMP_INTERFACE) && !gfc_current_ns->has_import_set) i = gfc_get_sym_tree (name, NULL, &symtree, false); else i = gfc_get_ha_sym_tree (name, &symtree); if (i) return MATCH_ERROR; sym = symtree->n.sym; e = NULL; where = gfc_current_locus; replace_hidden_procptr_result (&sym, &symtree); /* If this is an implicit do loop index and implicitly typed, it should not be host associated. */ m = check_for_implicit_index (&symtree, &sym); if (m != MATCH_YES) return m; gfc_set_sym_referenced (sym); sym->attr.implied_index = 0; if (sym->attr.function && sym->result == sym) { /* See if this is a directly recursive function call. */ gfc_gobble_whitespace (); if (sym->attr.recursive && gfc_peek_ascii_char () == '(' && gfc_current_ns->proc_name == sym && !sym->attr.dimension) { gfc_error ("'%s' at %C is the name of a recursive function " "and so refers to the result variable. Use an " "explicit RESULT variable for direct recursion " "(12.5.2.1)", sym->name); return MATCH_ERROR; } if (gfc_is_function_return_value (sym, gfc_current_ns)) goto variable; if (sym->attr.entry && (sym->ns == gfc_current_ns || sym->ns == gfc_current_ns->parent)) { gfc_entry_list *el = NULL; for (el = sym->ns->entries; el; el = el->next) if (sym == el->sym) goto variable; } } if (gfc_matching_procptr_assignment) goto procptr0; if (sym->attr.function || sym->attr.external || sym->attr.intrinsic) goto function0; if (sym->attr.generic) goto generic_function; switch (sym->attr.flavor) { case FL_VARIABLE: variable: e = gfc_get_expr (); e->expr_type = EXPR_VARIABLE; e->symtree = symtree; m = gfc_match_varspec (e, 0, false, true); break; case FL_PARAMETER: /* A statement of the form "REAL, parameter :: a(0:10) = 1" will end up here. Unfortunately, sym->value->expr_type is set to EXPR_CONSTANT, and so the if () branch would be followed without the !sym->as check. */ if (sym->value && sym->value->expr_type != EXPR_ARRAY && !sym->as) e = gfc_copy_expr (sym->value); else { e = gfc_get_expr (); e->expr_type = EXPR_VARIABLE; } e->symtree = symtree; m = gfc_match_varspec (e, 0, false, true); if (sym->ts.is_c_interop || sym->ts.is_iso_c) break; /* Variable array references to derived type parameters cause all sorts of headaches in simplification. Treating such expressions as variable works just fine for all array references. */ if (sym->value && sym->ts.type == BT_DERIVED && e->ref) { for (ref = e->ref; ref; ref = ref->next) if (ref->type == REF_ARRAY) break; if (ref == NULL || ref->u.ar.type == AR_FULL) break; ref = e->ref; e->ref = NULL; gfc_free_expr (e); e = gfc_get_expr (); e->expr_type = EXPR_VARIABLE; e->symtree = symtree; e->ref = ref; } break; case FL_DERIVED: sym = gfc_use_derived (sym); if (sym == NULL) m = MATCH_ERROR; else goto generic_function; break; /* If we're here, then the name is known to be the name of a procedure, yet it is not sure to be the name of a function. */ case FL_PROCEDURE: /* Procedure Pointer Assignments. */ procptr0: if (gfc_matching_procptr_assignment) { gfc_gobble_whitespace (); if (!sym->attr.dimension && gfc_peek_ascii_char () == '(') /* Parse functions returning a procptr. */ goto function0; e = gfc_get_expr (); e->expr_type = EXPR_VARIABLE; e->symtree = symtree; m = gfc_match_varspec (e, 0, false, true); if (!e->ref && sym->attr.flavor == FL_UNKNOWN && sym->ts.type == BT_UNKNOWN && !gfc_add_flavor (&sym->attr, FL_PROCEDURE, sym->name, NULL)) { m = MATCH_ERROR; break; } break; } if (sym->attr.subroutine) { gfc_error ("Unexpected use of subroutine name '%s' at %C", sym->name); m = MATCH_ERROR; break; } /* At this point, the name has to be a non-statement function. If the name is the same as the current function being compiled, then we have a variable reference (to the function result) if the name is non-recursive. */ st = gfc_enclosing_unit (NULL); if (st != NULL && st->state == COMP_FUNCTION && st->sym == sym && !sym->attr.recursive) { e = gfc_get_expr (); e->symtree = symtree; e->expr_type = EXPR_VARIABLE; m = gfc_match_varspec (e, 0, false, true); break; } /* Match a function reference. */ function0: m = gfc_match_actual_arglist (0, &actual_arglist); if (m == MATCH_NO) { if (sym->attr.proc == PROC_ST_FUNCTION) gfc_error ("Statement function '%s' requires argument list at %C", sym->name); else gfc_error ("Function '%s' requires an argument list at %C", sym->name); m = MATCH_ERROR; break; } if (m != MATCH_YES) { m = MATCH_ERROR; break; } gfc_get_ha_sym_tree (name, &symtree); /* Can't fail */ sym = symtree->n.sym; replace_hidden_procptr_result (&sym, &symtree); e = gfc_get_expr (); e->symtree = symtree; e->expr_type = EXPR_FUNCTION; e->value.function.actual = actual_arglist; e->where = gfc_current_locus; if (sym->ts.type == BT_CLASS && sym->attr.class_ok && CLASS_DATA (sym)->as) e->rank = CLASS_DATA (sym)->as->rank; else if (sym->as != NULL) e->rank = sym->as->rank; if (!sym->attr.function && !gfc_add_function (&sym->attr, sym->name, NULL)) { m = MATCH_ERROR; break; } /* Check here for the existence of at least one argument for the iso_c_binding functions C_LOC, C_FUNLOC, and C_ASSOCIATED. The argument(s) given will be checked in gfc_iso_c_func_interface, during resolution of the function call. */ if (sym->attr.is_iso_c == 1 && (sym->from_intmod == INTMOD_ISO_C_BINDING && (sym->intmod_sym_id == ISOCBINDING_LOC || sym->intmod_sym_id == ISOCBINDING_FUNLOC || sym->intmod_sym_id == ISOCBINDING_ASSOCIATED))) { /* make sure we were given a param */ if (actual_arglist == NULL) { gfc_error ("Missing argument to '%s' at %C", sym->name); m = MATCH_ERROR; break; } } if (sym->result == NULL) sym->result = sym; m = MATCH_YES; break; case FL_UNKNOWN: /* Special case for derived type variables that get their types via an IMPLICIT statement. This can't wait for the resolution phase. */ if (gfc_peek_ascii_char () == '%' && sym->ts.type == BT_UNKNOWN && gfc_get_default_type (sym->name, sym->ns)->type == BT_DERIVED) gfc_set_default_type (sym, 0, sym->ns); /* If the symbol has a (co)dimension attribute, the expression is a variable. */ if (sym->attr.dimension || sym->attr.codimension) { if (!gfc_add_flavor (&sym->attr, FL_VARIABLE, sym->name, NULL)) { m = MATCH_ERROR; break; } e = gfc_get_expr (); e->symtree = symtree; e->expr_type = EXPR_VARIABLE; m = gfc_match_varspec (e, 0, false, true); break; } if (sym->ts.type == BT_CLASS && sym->attr.class_ok && (CLASS_DATA (sym)->attr.dimension || CLASS_DATA (sym)->attr.codimension)) { if (!gfc_add_flavor (&sym->attr, FL_VARIABLE, sym->name, NULL)) { m = MATCH_ERROR; break; } e = gfc_get_expr (); e->symtree = symtree; e->expr_type = EXPR_VARIABLE; m = gfc_match_varspec (e, 0, false, true); break; } /* Name is not an array, so we peek to see if a '(' implies a function call or a substring reference. Otherwise the variable is just a scalar. */ gfc_gobble_whitespace (); if (gfc_peek_ascii_char () != '(') { /* Assume a scalar variable */ e = gfc_get_expr (); e->symtree = symtree; e->expr_type = EXPR_VARIABLE; if (!gfc_add_flavor (&sym->attr, FL_VARIABLE, sym->name, NULL)) { m = MATCH_ERROR; break; } /*FIXME:??? gfc_match_varspec does set this for us: */ e->ts = sym->ts; m = gfc_match_varspec (e, 0, false, true); break; } /* See if this is a function reference with a keyword argument as first argument. We do this because otherwise a spurious symbol would end up in the symbol table. */ old_loc = gfc_current_locus; m2 = gfc_match (" ( %n =", argname); gfc_current_locus = old_loc; e = gfc_get_expr (); e->symtree = symtree; if (m2 != MATCH_YES) { /* Try to figure out whether we're dealing with a character type. We're peeking ahead here, because we don't want to call match_substring if we're dealing with an implicitly typed non-character variable. */ implicit_char = false; if (sym->ts.type == BT_UNKNOWN) { ts = gfc_get_default_type (sym->name, NULL); if (ts->type == BT_CHARACTER) implicit_char = true; } /* See if this could possibly be a substring reference of a name that we're not sure is a variable yet. */ if ((implicit_char || sym->ts.type == BT_CHARACTER) && match_substring (sym->ts.u.cl, 0, &e->ref) == MATCH_YES) { e->expr_type = EXPR_VARIABLE; if (sym->attr.flavor != FL_VARIABLE && !gfc_add_flavor (&sym->attr, FL_VARIABLE, sym->name, NULL)) { m = MATCH_ERROR; break; } if (sym->ts.type == BT_UNKNOWN && !gfc_set_default_type (sym, 1, NULL)) { m = MATCH_ERROR; break; } e->ts = sym->ts; if (e->ref) e->ts.u.cl = NULL; m = MATCH_YES; break; } } /* Give up, assume we have a function. */ gfc_get_sym_tree (name, NULL, &symtree, false); /* Can't fail */ sym = symtree->n.sym; e->expr_type = EXPR_FUNCTION; if (!sym->attr.function && !gfc_add_function (&sym->attr, sym->name, NULL)) { m = MATCH_ERROR; break; } sym->result = sym; m = gfc_match_actual_arglist (0, &e->value.function.actual); if (m == MATCH_NO) gfc_error ("Missing argument list in function '%s' at %C", sym->name); if (m != MATCH_YES) { m = MATCH_ERROR; break; } /* If our new function returns a character, array or structure type, it might have subsequent references. */ m = gfc_match_varspec (e, 0, false, true); if (m == MATCH_NO) m = MATCH_YES; break; generic_function: gfc_get_sym_tree (name, NULL, &symtree, false); /* Can't fail */ e = gfc_get_expr (); e->symtree = symtree; e->expr_type = EXPR_FUNCTION; if (sym->attr.flavor == FL_DERIVED) { e->value.function.esym = sym; e->symtree->n.sym->attr.generic = 1; } m = gfc_match_actual_arglist (0, &e->value.function.actual); break; default: gfc_error ("Symbol at %C is not appropriate for an expression"); return MATCH_ERROR; } if (m == MATCH_YES) { e->where = where; *result = e; } else gfc_free_expr (e); return m; } /* Match a variable, i.e. something that can be assigned to. This starts as a symbol, can be a structure component or an array reference. It can be a function if the function doesn't have a separate RESULT variable. If the symbol has not been previously seen, we assume it is a variable. This function is called by two interface functions: gfc_match_variable, which has host_flag = 1, and gfc_match_equiv_variable, with host_flag = 0, to restrict the match of the symbol to the local scope. */ static match match_variable (gfc_expr **result, int equiv_flag, int host_flag) { gfc_symbol *sym; gfc_symtree *st; gfc_expr *expr; locus where; match m; /* Since nothing has any business being an lvalue in a module specification block, an interface block or a contains section, we force the changed_symbols mechanism to work by setting host_flag to 0. This prevents valid symbols that have the name of keywords, such as 'end', being turned into variables by failed matching to assignments for, e.g., END INTERFACE. */ if (gfc_current_state () == COMP_MODULE || gfc_current_state () == COMP_INTERFACE || gfc_current_state () == COMP_CONTAINS) host_flag = 0; where = gfc_current_locus; m = gfc_match_sym_tree (&st, host_flag); if (m != MATCH_YES) return m; sym = st->n.sym; /* If this is an implicit do loop index and implicitly typed, it should not be host associated. */ m = check_for_implicit_index (&st, &sym); if (m != MATCH_YES) return m; sym->attr.implied_index = 0; gfc_set_sym_referenced (sym); switch (sym->attr.flavor) { case FL_VARIABLE: /* Everything is alright. */ break; case FL_UNKNOWN: { sym_flavor flavor = FL_UNKNOWN; gfc_gobble_whitespace (); if (sym->attr.external || sym->attr.procedure || sym->attr.function || sym->attr.subroutine) flavor = FL_PROCEDURE; /* If it is not a procedure, is not typed and is host associated, we cannot give it a flavor yet. */ else if (sym->ns == gfc_current_ns->parent && sym->ts.type == BT_UNKNOWN) break; /* These are definitive indicators that this is a variable. */ else if (gfc_peek_ascii_char () != '(' || sym->ts.type != BT_UNKNOWN || sym->attr.pointer || sym->as != NULL) flavor = FL_VARIABLE; if (flavor != FL_UNKNOWN && !gfc_add_flavor (&sym->attr, flavor, sym->name, NULL)) return MATCH_ERROR; } break; case FL_PARAMETER: if (equiv_flag) { gfc_error ("Named constant at %C in an EQUIVALENCE"); return MATCH_ERROR; } /* Otherwise this is checked for and an error given in the variable definition context checks. */ break; case FL_PROCEDURE: /* Check for a nonrecursive function result variable. */ if (sym->attr.function && !sym->attr.external && sym->result == sym && (gfc_is_function_return_value (sym, gfc_current_ns) || (sym->attr.entry && sym->ns == gfc_current_ns) || (sym->attr.entry && sym->ns == gfc_current_ns->parent))) { /* If a function result is a derived type, then the derived type may still have to be resolved. */ if (sym->ts.type == BT_DERIVED && gfc_use_derived (sym->ts.u.derived) == NULL) return MATCH_ERROR; break; } if (sym->attr.proc_pointer || replace_hidden_procptr_result (&sym, &st)) break; /* Fall through to error */ default: gfc_error ("'%s' at %C is not a variable", sym->name); return MATCH_ERROR; } /* Special case for derived type variables that get their types via an IMPLICIT statement. This can't wait for the resolution phase. */ { gfc_namespace * implicit_ns; if (gfc_current_ns->proc_name == sym) implicit_ns = gfc_current_ns; else implicit_ns = sym->ns; if (gfc_peek_ascii_char () == '%' && sym->ts.type == BT_UNKNOWN && gfc_get_default_type (sym->name, implicit_ns)->type == BT_DERIVED) gfc_set_default_type (sym, 0, implicit_ns); } expr = gfc_get_expr (); expr->expr_type = EXPR_VARIABLE; expr->symtree = st; expr->ts = sym->ts; expr->where = where; /* Now see if we have to do more. */ m = gfc_match_varspec (expr, equiv_flag, false, false); if (m != MATCH_YES) { gfc_free_expr (expr); return m; } *result = expr; return MATCH_YES; } match gfc_match_variable (gfc_expr **result, int equiv_flag) { return match_variable (result, equiv_flag, 1); } match gfc_match_equiv_variable (gfc_expr **result) { return match_variable (result, 1, 0); }
albertghtoun/gcc-libitm
gcc/fortran/primary.c
C
gpl-2.0
78,409
[ 30522, 1013, 1008, 3078, 3670, 4942, 22494, 10196, 2015, 9385, 1006, 1039, 1007, 2456, 1011, 2297, 2489, 4007, 3192, 1010, 4297, 1012, 5201, 2011, 5557, 12436, 18533, 2023, 5371, 2003, 2112, 1997, 1043, 9468, 1012, 1043, 9468, 2003, 2489, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...