repo_name
stringlengths
4
116
path
stringlengths
3
942
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
cat-chat/catchat-ios
Cat Chat/JDPCatThumbnailCell.h
296
// // JDPCatThumbnailCell.h // Cat Chat // // Created by Joel Parsons on 05/05/2014. // Copyright (c) 2014 Joel Parsons. All rights reserved. // #import <UIKit/UIKit.h> @interface JDPCatThumbnailCell : UICollectionViewCell @property (weak, nonatomic) IBOutlet UIImageView *imageView; @end
mpl-2.0
susaing/doc.servo.org
x11/xlib/fn.Xpermalloc.html
4099
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <meta name="description" content="API documentation for the Rust `Xpermalloc` fn in crate `x11`."> <meta name="keywords" content="rust, rustlang, rust-lang, Xpermalloc"> <title>x11::xlib::Xpermalloc - Rust</title> <link rel="stylesheet" type="text/css" href="../../main.css"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <section class="sidebar"> <p class='location'><a href='../index.html'>x11</a>::<wbr><a href='index.html'>xlib</a></p><script>window.sidebarCurrent = {name: 'Xpermalloc', ty: 'fn', relpath: ''};</script><script defer src="sidebar-items.js"></script> </section> <nav class="sub"> <form class="search-form js-only"> <div class="search-container"> <input class="search-input" name="search" autocomplete="off" placeholder="Click or press ‘S’ to search, ‘?’ for more options…" type="search"> </div> </form> </nav> <section id='main' class="content fn"> <h1 class='fqn'><span class='in-band'><a href='../index.html'>x11</a>::<wbr><a href='index.html'>xlib</a>::<wbr><a class='fn' href=''>Xpermalloc</a></span><span class='out-of-band'><span id='render-detail'> <a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs"> [<span class='inner'>&#x2212;</span>] </a> </span><a id='src-20947' class='srclink' href='../../src/x11/link.rs.html#14' title='goto source code'>[src]</a></span></h1> <pre class='rust fn'>pub unsafe extern fn Xpermalloc(_1: <a class='type' href='../../libc/types/os/arch/c95/type.c_uint.html' title='libc::types::os::arch::c95::c_uint'>c_uint</a>) -&gt; <a href='../../std/primitive.pointer.html'>*mut <a class='type' href='../../libc/types/os/arch/c95/type.c_char.html' title='libc::types::os::arch::c95::c_char'>c_char</a></a></pre></section> <section id='search' class="content hidden"></section> <section class="footer"></section> <div id="help" class="hidden"> <div> <div class="shortcuts"> <h1>Keyboard Shortcuts</h1> <dl> <dt>?</dt> <dd>Show this help dialog</dd> <dt>S</dt> <dd>Focus the search field</dd> <dt>&larrb;</dt> <dd>Move up in search results</dd> <dt>&rarrb;</dt> <dd>Move down in search results</dd> <dt>&#9166;</dt> <dd>Go to active search result</dd> </dl> </div> <div class="infos"> <h1>Search Tricks</h1> <p> Prefix searches with a type followed by a colon (e.g. <code>fn:</code>) to restrict the search to a given type. </p> <p> Accepted types are: <code>fn</code>, <code>mod</code>, <code>struct</code>, <code>enum</code>, <code>trait</code>, <code>type</code>, <code>macro</code>, and <code>const</code>. </p> <p> Search functions by type signature (e.g. <code>vec -> usize</code>) </p> </div> </div> </div> <script> window.rootPath = "../../"; window.currentCrate = "x11"; window.playgroundUrl = ""; </script> <script src="../../jquery.js"></script> <script src="../../main.js"></script> <script async src="../../search-index.js"></script> </body> </html>
mpl-2.0
ajschult/etomica
etomica-apps/src/main/java/etomica/normalmode/nptdemo/ColorSchemeScaledOverlap.java
4038
package etomica.normalmode.nptdemo; import java.awt.Color; import etomica.api.IAtom; import etomica.api.IAtomList; import etomica.api.IBoundary; import etomica.api.IBox; import etomica.api.IVector; import etomica.api.IVectorMutable; import etomica.graphics.ColorSchemeCollectiveAgent; import etomica.nbr.list.NeighborListManager; import etomica.nbr.list.PotentialMasterList; import etomica.normalmode.CoordinateDefinition; import etomica.space.ISpace; /** * Color atoms based on being neighbors of the reference atom * * @author Andrew Schultz */ public class ColorSchemeScaledOverlap extends ColorSchemeCollectiveAgent { public ColorSchemeScaledOverlap(ISpace space, PotentialMasterList potentialMaster, CoordinateDefinition coordinateDefinition) { super(coordinateDefinition.getBox()); this.coordinateDefinition = coordinateDefinition; IBox box = coordinateDefinition.getBox(); nOverlaps = new int[box.getLeafList().getAtomCount()]; neighborManager = potentialMaster.getNeighborManager(box); pi = space.makeVector(); pj = space.makeVector(); dr = space.makeVector(); } public void setPressure(double newPressure) { pressure = newPressure; } public double getPressure() { return pressure; } public void setDisplayDensity(double newDisplayDensity) { displayDensity = newDisplayDensity; } public double getDisplayDensity() { return displayDensity; } public synchronized void colorAllAtoms() { IBox box = coordinateDefinition.getBox(); IAtomList leafList = box.getLeafList(); double vOld = box.getBoundary().volume(); int nAtoms = box.getLeafList().getAtomCount(); double vNew = nAtoms/displayDensity; double rScale = Math.sqrt(vNew/vOld); double latticeScale = Math.exp((pressure*(vNew-vOld))/((nAtoms-1)*1*2))/rScale; // T=1, D=2 double sigma = 1.0; double scaledSig = sigma/rScale; double sig2 = scaledSig*scaledSig; //color all atoms according to their type int nLeaf = leafList.getAtomCount(); for (int iLeaf=0; iLeaf<nLeaf; iLeaf++) { nOverlaps[iLeaf] = 0; } IBoundary boundary = box.getBoundary(); for (int i=0; i<leafList.getAtomCount(); i++) { //color blue the neighbor atoms in same group IAtom atom = leafList.getAtom(i); pi.E(atom.getPosition()); IVector l = coordinateDefinition.getLatticePosition(atom); pi.ME(l); pi.TE(latticeScale); pi.PE(l); IAtomList list = neighborManager.getDownList(atom)[0]; for (int j=0; j<list.getAtomCount(); j++) { IAtom jAtom = list.getAtom(j); pj.E(jAtom.getPosition()); IVector lj = coordinateDefinition.getLatticePosition(jAtom); pj.ME(lj); pj.TE(latticeScale); pj.PE(lj); dr.Ev1Mv2(pi, pj); boundary.nearestImage(dr); double r2 = dr.squared(); if (r2 < sig2) { nOverlaps[i]++; nOverlaps[jAtom.getLeafIndex()]++; } } } for (int i=0; i<leafList.getAtomCount(); i++) { //color green the target atom agentManager.setAgent(leafList.getAtom(i), colors[nOverlaps[i]]); } } private static final long serialVersionUID = 1L; private final NeighborListManager neighborManager; protected final IVectorMutable dr; protected final IVectorMutable pi, pj; protected final int[] nOverlaps; protected double pressure, displayDensity; protected final CoordinateDefinition coordinateDefinition; protected Color[] colors = new Color[]{Color.RED, Color.BLUE, Color.GREEN, Color.BLACK, Color.CYAN, Color.PINK, new Color(0.5f, 0.0f, 0.5f)}; }
mpl-2.0
WolframG/Rhino-Prov-Mod
src/org/mozilla/javascript/orginal/ast/UnaryExpression.java
4690
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.javascript.orginal.ast; import org.mozilla.javascript.orginal.Token; /** * AST node representing unary operators such as {@code ++}, * {@code ~}, {@code typeof} and {@code delete}. The type field * is set to the appropriate Token type for the operator. The node length spans * from the operator to the end of the operand (for prefix operators) or from * the start of the operand to the operator (for postfix).<p> * * The {@code default xml namespace = &lt;expr&gt;} statement in E4X * (JavaScript 1.6) is represented as a {@code UnaryExpression} of node * type {@link Token#DEFAULTNAMESPACE}, wrapped with an * {@link ExpressionStatement}. */ public class UnaryExpression extends AstNode { private AstNode operand; private boolean isPostfix; public UnaryExpression() { } public UnaryExpression(int pos) { super(pos); } /** * Constructs a new postfix UnaryExpression */ public UnaryExpression(int pos, int len) { super(pos, len); } /** * Constructs a new prefix UnaryExpression. */ public UnaryExpression(int operator, int operatorPosition, AstNode operand) { this(operator, operatorPosition, operand, false); } /** * Constructs a new UnaryExpression with the specified operator * and operand. It sets the parent of the operand, and sets its own bounds * to encompass the operator and operand. * @param operator the node type * @param operatorPosition the absolute position of the operator. * @param operand the operand expression * @param postFix true if the operator follows the operand. Int * @throws IllegalArgumentException} if {@code operand} is {@code null} */ public UnaryExpression(int operator, int operatorPosition, AstNode operand, boolean postFix) { assertNotNull(operand); int beg = postFix ? operand.getPosition() : operatorPosition; // JavaScript only has ++ and -- postfix operators, so length is 2 int end = postFix ? operatorPosition + 2 : operand.getPosition() + operand.getLength(); setBounds(beg, end); setOperator(operator); setOperand(operand); isPostfix = postFix; } /** * Returns operator token &ndash; alias for {@link #getType} */ public int getOperator() { return type; } /** * Sets operator &ndash; same as {@link #setType}, but throws an * exception if the operator is invalid * @throws IllegalArgumentException if operator is not a valid * Token code */ public void setOperator(int operator) { if (!Token.isValidToken(operator)) throw new IllegalArgumentException("Invalid token: " + operator); setType(operator); } public AstNode getOperand() { return operand; } /** * Sets the operand, and sets its parent to be this node. * @throws IllegalArgumentException} if {@code operand} is {@code null} */ public void setOperand(AstNode operand) { assertNotNull(operand); this.operand = operand; operand.setParent(this); } /** * Returns whether the operator is postfix */ public boolean isPostfix() { return isPostfix; } /** * Returns whether the operator is prefix */ public boolean isPrefix() { return !isPostfix; } /** * Sets whether the operator is postfix */ public void setIsPostfix(boolean isPostfix) { this.isPostfix = isPostfix; } @Override public String toSource(int depth) { StringBuilder sb = new StringBuilder(); sb.append(makeIndent(depth)); int type = getType(); if (!isPostfix) { sb.append(operatorToString(type)); if (type == Token.TYPEOF || type == Token.DELPROP || type == Token.VOID) { sb.append(" "); } } sb.append(operand.toSource()); if (isPostfix) { sb.append(operatorToString(type)); } return sb.toString(); } /** * Visits this node, then the operand. */ @Override public void visit(NodeVisitor v) { if (v.visit(this)) { operand.visit(v); } } }
mpl-2.0
irrequietus/clause
clause/ppmpf/vxpp/slots/func/arty/arty74.hh
4493
/*~ * Copyright (C) 2013 - 2016 George Makrydakis <george@irrequietus.eu> * * This file is part of 'clause', a highly generic C++ meta-programming library, * subject to the terms and conditions of the Mozilla Public License v 2.0. If * a copy of the MPLv2 license text was not distributed with this file, you can * obtain it at: http://mozilla.org/MPL/2.0/. * * The 'clause' library is an experimental library in active development with * a source code repository at: https://github.com/irrequietus/clause.git and * issue tracker at https://github.com/irrequietus/clause/issues. * */ /*~ * @warn This file should not be included directly in code deploying library * constructs from 'clause'; it is part of a high level meta-macro * construct where multiple #if directives control its actual inclusion. */ #undef PPMPF_VXPP_S7F34 #undef PPMPF_VXPP_S7F33 #undef PPMPF_VXPP_S7F32 #undef PPMPF_VXPP_S7F31 #undef PPMPF_VXPP_S7F30 #if (_PPMPF_FARG73() / 10000) % 10 == 0 #define PPMPF_VXPP_S7F34 0 #elif (_PPMPF_FARG73() / 10000) % 10 == 1 #define PPMPF_VXPP_S7F34 1 #elif (_PPMPF_FARG73() / 10000) % 10 == 2 #define PPMPF_VXPP_S7F34 2 #elif (_PPMPF_FARG73() / 10000) % 10 == 3 #define PPMPF_VXPP_S7F34 3 #elif (_PPMPF_FARG73() / 10000) % 10 == 4 #define PPMPF_VXPP_S7F34 4 #elif (_PPMPF_FARG73() / 10000) % 10 == 5 #define PPMPF_VXPP_S7F34 5 #elif (_PPMPF_FARG73() / 10000) % 10 == 6 #define PPMPF_VXPP_S7F34 6 #elif (_PPMPF_FARG73() / 10000) % 10 == 7 #define PPMPF_VXPP_S7F34 7 #elif (_PPMPF_FARG73() / 10000) % 10 == 8 #define PPMPF_VXPP_S7F34 8 #elif (_PPMPF_FARG73() / 10000) % 10 == 9 #define PPMPF_VXPP_S7F34 9 #endif #if (_PPMPF_FARG73() / 1000) % 10 == 0 #define PPMPF_VXPP_S7F33 0 #elif (_PPMPF_FARG73() / 1000) % 10 == 1 #define PPMPF_VXPP_S7F33 1 #elif (_PPMPF_FARG73() / 1000) % 10 == 2 #define PPMPF_VXPP_S7F33 2 #elif (_PPMPF_FARG73() / 1000) % 10 == 3 #define PPMPF_VXPP_S7F33 3 #elif (_PPMPF_FARG73() / 1000) % 10 == 4 #define PPMPF_VXPP_S7F33 4 #elif (_PPMPF_FARG73() / 1000) % 10 == 5 #define PPMPF_VXPP_S7F33 5 #elif (_PPMPF_FARG73() / 1000) % 10 == 6 #define PPMPF_VXPP_S7F33 6 #elif (_PPMPF_FARG73() / 1000) % 10 == 7 #define PPMPF_VXPP_S7F33 7 #elif (_PPMPF_FARG73() / 1000) % 10 == 8 #define PPMPF_VXPP_S7F33 8 #elif (_PPMPF_FARG73() / 1000) % 10 == 9 #define PPMPF_VXPP_S7F33 9 #endif #if (_PPMPF_FARG73() / 100) % 10 == 0 #define PPMPF_VXPP_S7F32 0 #elif (_PPMPF_FARG73() / 100) % 10 == 1 #define PPMPF_VXPP_S7F32 1 #elif (_PPMPF_FARG73() / 100) % 10 == 2 #define PPMPF_VXPP_S7F32 2 #elif (_PPMPF_FARG73() / 100) % 10 == 3 #define PPMPF_VXPP_S7F32 3 #elif (_PPMPF_FARG73() / 100) % 10 == 4 #define PPMPF_VXPP_S7F32 4 #elif (_PPMPF_FARG73() / 100) % 10 == 5 #define PPMPF_VXPP_S7F32 5 #elif (_PPMPF_FARG73() / 100) % 10 == 6 #define PPMPF_VXPP_S7F32 6 #elif (_PPMPF_FARG73() / 100) % 10 == 7 #define PPMPF_VXPP_S7F32 7 #elif (_PPMPF_FARG73() / 100) % 10 == 8 #define PPMPF_VXPP_S7F32 8 #elif (_PPMPF_FARG73() / 100) % 10 == 9 #define PPMPF_VXPP_S7F32 9 #endif #if (_PPMPF_FARG73() / 10) % 10 == 0 #define PPMPF_VXPP_S7F31 0 #elif (_PPMPF_FARG73() / 10) % 10 == 1 #define PPMPF_VXPP_S7F31 1 #elif (_PPMPF_FARG73() / 10) % 10 == 2 #define PPMPF_VXPP_S7F31 2 #elif (_PPMPF_FARG73() / 10) % 10 == 3 #define PPMPF_VXPP_S7F31 3 #elif (_PPMPF_FARG73() / 10) % 10 == 4 #define PPMPF_VXPP_S7F31 4 #elif (_PPMPF_FARG73() / 10) % 10 == 5 #define PPMPF_VXPP_S7F31 5 #elif (_PPMPF_FARG73() / 10) % 10 == 6 #define PPMPF_VXPP_S7F31 6 #elif (_PPMPF_FARG73() / 10) % 10 == 7 #define PPMPF_VXPP_S7F31 7 #elif (_PPMPF_FARG73() / 10) % 10 == 8 #define PPMPF_VXPP_S7F31 8 #elif (_PPMPF_FARG73() / 10) % 10 == 9 #define PPMPF_VXPP_S7F31 9 #endif #if _PPMPF_FARG73() % 10 == 0 #define PPMPF_VXPP_S7F30 0 #elif _PPMPF_FARG73() % 10 == 1 #define PPMPF_VXPP_S7F30 1 #elif _PPMPF_FARG73() % 10 == 2 #define PPMPF_VXPP_S7F30 2 #elif _PPMPF_FARG73() % 10 == 3 #define PPMPF_VXPP_S7F30 3 #elif _PPMPF_FARG73() % 10 == 4 #define PPMPF_VXPP_S7F30 4 #elif _PPMPF_FARG73() % 10 == 5 #define PPMPF_VXPP_S7F30 5 #elif _PPMPF_FARG73() % 10 == 6 #define PPMPF_VXPP_S7F30 6 #elif _PPMPF_FARG73() % 10 == 7 #define PPMPF_VXPP_S7F30 7 #elif _PPMPF_FARG73() % 10 == 8 #define PPMPF_VXPP_S7F30 8 #elif _PPMPF_FARG73() % 10 == 9 #define PPMPF_VXPP_S7F30 9 #endif
mpl-2.0
joyent/sdc-hermes
lib/logsets.js
2593
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* * Copyright (c) 2019, Joyent, Inc. */ var mod_fs = require('fs'); var mod_path = require('path'); var mod_assert = require('assert-plus'); var DEFAULT_DEBOUNCE_TIME = 600; var DEFAULT_RETAIN_TIME = 0; var LOGSETS; function load_logsets() { var NAMES_SEEN = []; LOGSETS = JSON.parse(mod_fs.readFileSync(mod_path.join(__dirname, '..', 'etc', 'logsets.json'), 'utf8')); for (var i = 0; i < LOGSETS.length; i++) { var ls = LOGSETS[i]; ls.regex = new RegExp(ls.regex); mod_assert.optionalString( ls.search_dirs_pattern, 'search_dirs_pattern'); mod_assert.arrayOfString(ls.search_dirs, 'search_dirs'); mod_assert.optionalBool(ls.no_upload, 'no_upload'); mod_assert.string(ls.manta_path, 'manta_path'); mod_assert.optionalNumber(ls.debounce_time, 'debounce_time'); if (!ls.debounce_time) ls.debounce_time = DEFAULT_DEBOUNCE_TIME; mod_assert.optionalNumber(ls.retain_time, 'retain_time'); if (!ls.retain_time) ls.retain_time = DEFAULT_RETAIN_TIME; mod_assert.ok(NAMES_SEEN.indexOf(ls.name) === -1, 'duplicate logset name'); NAMES_SEEN.push(ls.name); } } var COPY_FIELDS = [ 'search_dirs', 'search_dirs_pattern', 'manta_path', 'date_string', 'date_adjustment', 'debounce_time', 'retain_time', 'customer_uuid', 'no_upload' ]; /* * Create a JSON-safe object for transport across the wire to the actor: */ function format_logset(logset, zonename, zonerole) { var o = { name: logset.name + (zonename ? '@' + zonename : ''), zonename: zonename || 'global', zonerole: zonerole || 'global', regex: logset.regex.source }; for (var i = 0; i < COPY_FIELDS.length; i++) { var cf = COPY_FIELDS[i]; o[cf] = logset[cf]; } return (o); } function logsets_for_server(zone_list_for_server) { var out = []; for (var i = 0; i < LOGSETS.length; i++) { var ls = LOGSETS[i]; /* * This logset applies to the global zone: */ if (ls.zones.indexOf('global') !== -1) { out.push(format_logset(ls)); } for (var j = 0; j < zone_list_for_server.length; j++) { var zz = zone_list_for_server[j]; if (ls.zones.indexOf(zz.role) !== -1) { out.push(format_logset(ls, zz.uuid, zz.role)); } } } return (out); } /* * Initialisation: */ load_logsets(); /* * API: */ module.exports = { logsets_for_server: logsets_for_server }; /* vim: set syntax=javascript ts=8 sts=8 sw=8 noet: */
mpl-2.0
iduartgomez/simag
simag_core/src/agent/lang/parser/test/bench.rs
2040
use std::time::Instant; use super::{ParseErrB, ParseTree, Parser}; #[test] #[ignore] fn remove_comments() -> Result<(), nom::Err<ParseErrB<'static>>> { const REPETITIONS: i32 = 10_000; const SOURCE: &[u8] = b" /* stuff */ # one line comment ( # first scope ( # second scope let x, y in professor[$Lucy=1] ) ) /* multi line comment */ "; let timer = Instant::now(); for _ in 0..REPETITIONS { Parser::remove_comments(SOURCE)?; } let iter_time = timer.elapsed().as_nanos() as f64 / 1e3 / REPETITIONS as f64; println!("took {} us/iter; {} iters/sec", iter_time, 1e6 / iter_time); Ok(()) } const CLEAN_SOURCE: &[u8] = b" (let x, y in (american[x=1] and hostile[z=1]) := criminal[x=1]) (let x, y in ((american[x=1] and hostile[z=1]) := criminal[x=1])) (let x, y in (american[x=1] and hostile[z=1]) := criminal[x=1]) "; #[test] #[ignore] fn form_ast() -> Result<(), ParseErrB<'static>> { const REPETITIONS: i32 = 10_000; let timer = Instant::now(); for _ in 0..REPETITIONS { Parser::get_blocks(CLEAN_SOURCE)?; } let iter_time = timer.elapsed().as_nanos() as f64 / 1e3 / REPETITIONS as f64; println!("took {} us/iter; {} iters/sec", iter_time, 1e6 / iter_time); Ok(()) } #[test] #[ignore] fn process_ast() -> Result<(), ParseErrB<'static>> { const REPETITIONS: usize = 1_000; let mut ast = vec![Parser::get_blocks(CLEAN_SOURCE)?; REPETITIONS]; let timer = Instant::now(); for _ in 0..REPETITIONS { let _ = ast .pop() .unwrap() .into_iter() .map(|ast| ParseTree::process_ast(&ast, true)) .collect::<Vec<_>>(); } let iter_time = timer.elapsed().as_nanos() as f64 / 1e3 / REPETITIONS as f64; println!("took {} us/iter; {} iters/sec", iter_time, 1e6 / iter_time); Ok(()) }
mpl-2.0
susaing/doc.servo.org
openssl_sys/fn.CRYPTO_num_locks.html
3896
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <meta name="description" content="API documentation for the Rust `CRYPTO_num_locks` fn in crate `openssl_sys`."> <meta name="keywords" content="rust, rustlang, rust-lang, CRYPTO_num_locks"> <title>openssl_sys::CRYPTO_num_locks - Rust</title> <link rel="stylesheet" type="text/css" href="../main.css"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <section class="sidebar"> <p class='location'><a href='index.html'>openssl_sys</a></p><script>window.sidebarCurrent = {name: 'CRYPTO_num_locks', ty: 'fn', relpath: ''};</script><script defer src="sidebar-items.js"></script> </section> <nav class="sub"> <form class="search-form js-only"> <div class="search-container"> <input class="search-input" name="search" autocomplete="off" placeholder="Click or press ‘S’ to search, ‘?’ for more options…" type="search"> </div> </form> </nav> <section id='main' class="content fn"> <h1 class='fqn'><span class='in-band'><a href='index.html'>openssl_sys</a>::<wbr><a class='fn' href=''>CRYPTO_num_locks</a></span><span class='out-of-band'><span id='render-detail'> <a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs"> [<span class='inner'>&#x2212;</span>] </a> </span><a id='src-1573' class='srclink' href='../src/openssl_sys/lib.rs.html#348' title='goto source code'>[src]</a></span></h1> <pre class='rust fn'>pub unsafe extern fn CRYPTO_num_locks() -&gt; <a class='type' href='../libc/types/os/arch/c95/type.c_int.html' title='libc::types::os::arch::c95::c_int'>c_int</a></pre></section> <section id='search' class="content hidden"></section> <section class="footer"></section> <div id="help" class="hidden"> <div> <div class="shortcuts"> <h1>Keyboard Shortcuts</h1> <dl> <dt>?</dt> <dd>Show this help dialog</dd> <dt>S</dt> <dd>Focus the search field</dd> <dt>&larrb;</dt> <dd>Move up in search results</dd> <dt>&rarrb;</dt> <dd>Move down in search results</dd> <dt>&#9166;</dt> <dd>Go to active search result</dd> </dl> </div> <div class="infos"> <h1>Search Tricks</h1> <p> Prefix searches with a type followed by a colon (e.g. <code>fn:</code>) to restrict the search to a given type. </p> <p> Accepted types are: <code>fn</code>, <code>mod</code>, <code>struct</code>, <code>enum</code>, <code>trait</code>, <code>type</code>, <code>macro</code>, and <code>const</code>. </p> <p> Search functions by type signature (e.g. <code>vec -> usize</code>) </p> </div> </div> </div> <script> window.rootPath = "../"; window.currentCrate = "openssl_sys"; window.playgroundUrl = ""; </script> <script src="../jquery.js"></script> <script src="../main.js"></script> <script async src="../search-index.js"></script> </body> </html>
mpl-2.0
Yukarumya/Yukarum-Redfoxes
dom/grid/GridTrack.h
1431
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef mozilla_dom_GridTrack_h #define mozilla_dom_GridTrack_h #include "mozilla/dom/GridBinding.h" #include "nsWrapperCache.h" namespace mozilla { namespace dom { class GridTracks; class GridTrack : public nsISupports , public nsWrapperCache { public: explicit GridTrack(GridTracks *parent); protected: virtual ~GridTrack(); public: NS_DECL_CYCLE_COLLECTING_ISUPPORTS NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS(GridTrack) virtual JSObject* WrapObject(JSContext* aCx, JS::Handle<JSObject*> aGivenProto) override; GridTracks* GetParentObject() { return mParent; } double Start() const; double Breadth() const; GridDeclaration Type() const; GridTrackState State() const; void SetTrackValues(double aStart, double aBreadth, GridDeclaration aType, GridTrackState aState); protected: RefPtr<GridTracks> mParent; double mStart; double mBreadth; GridDeclaration mType; GridTrackState mState; }; } // namespace dom } // namespace mozilla #endif /* mozilla_dom_GridTrack_h */
mpl-2.0
sirthias/swave
core/src/main/java/swave/core/impl/Statics.java
1574
/* * Copyright © 2016 Mathias Doenitz * * 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 swave.core.impl; final class Statics { static final Integer _0 = 0; static final Integer _1 = 1; static final Integer _2 = 2; static final Integer _3 = 3; static final Integer _4 = 4; static final Integer _5 = 5; static final Integer _6 = 6; static final Integer _7 = 7; static final Integer _8 = 8; static final Integer _9 = 9; static final Integer _10 = 10; static final Integer _11 = 11; static final Integer _12 = 12; static final java.lang.Integer[] NEG_INTS = { -1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12, -13, -14, -15, -16, -17, -18, -19, -20, -21, -22, -23, -24, -25, -26, -27, -28, -29, -30, -31, -32 }; static final java.lang.Integer[] INTS_PLUS_100 = { 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132 }; }
mpl-2.0
oracle/terraform-provider-baremetal
oci/kms_key_test.go
18702
// Copyright (c) 2017, 2021, Oracle and/or its affiliates. All rights reserved. // Licensed under the Mozilla Public License v2.0 package oci import ( "context" "fmt" "testing" "time" "github.com/hashicorp/terraform-plugin-sdk/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/terraform" "github.com/oracle/oci-go-sdk/v46/common" oci_kms "github.com/oracle/oci-go-sdk/v46/keymanagement" "github.com/terraform-providers/terraform-provider-oci/httpreplay" ) var ( KeyRequiredOnlyResource = KeyResourceDependencies + generateResourceFromRepresentationMap("oci_kms_key", "test_key", Required, Create, keyRepresentation) KeyResourceConfig = KeyResourceDependencies + generateResourceFromRepresentationMap("oci_kms_key", "test_key", Optional, Update, keyRepresentation) keySingularDataSourceRepresentation = map[string]interface{}{ "key_id": Representation{repType: Required, create: `${oci_kms_key.test_key.id}`}, "management_endpoint": Representation{repType: Required, create: `${data.oci_kms_vault.test_vault.management_endpoint}`}, } keyDataSourceRepresentation = map[string]interface{}{ "compartment_id": Representation{repType: Required, create: `${var.compartment_id}`}, "management_endpoint": Representation{repType: Required, create: `${data.oci_kms_vault.test_vault.management_endpoint}`}, "protection_mode": Representation{repType: Optional, create: `SOFTWARE`}, "algorithm": Representation{repType: Optional, create: `AES`}, "length": Representation{repType: Optional, create: `16`}, "filter": RepresentationGroup{Required, keyDataSourceFilterRepresentation}} keyDataSourceFilterRepresentation = map[string]interface{}{ "name": Representation{repType: Required, create: `id`}, "values": Representation{repType: Required, create: []string{`${oci_kms_key.test_key.id}`}}, } deletionTime = time.Now().UTC().AddDate(0, 0, 8).Truncate(time.Millisecond) keyRepresentation = map[string]interface{}{ "compartment_id": Representation{repType: Required, create: `${var.compartment_id}`}, "display_name": Representation{repType: Required, create: `Key C`, update: `displayName2`}, "key_shape": RepresentationGroup{Required, keyKeyShapeRepresentation}, "management_endpoint": Representation{repType: Required, create: `${data.oci_kms_vault.test_vault.management_endpoint}`}, "desired_state": Representation{repType: Optional, create: `ENABLED`, update: `DISABLED`}, "freeform_tags": Representation{repType: Optional, create: map[string]string{"Department": "Finance"}, update: map[string]string{"Department": "Accounting"}}, "protection_mode": Representation{repType: Optional, create: `SOFTWARE`}, "time_of_deletion": Representation{repType: Required, create: deletionTime.Format(time.RFC3339Nano)}, } keyKeyShapeRepresentation = map[string]interface{}{ "algorithm": Representation{repType: Required, create: `AES`}, "length": Representation{repType: Required, create: `16`}, } kmsVaultId = getEnvSettingWithBlankDefault("kms_vault_ocid") KmsVaultIdVariableStr = fmt.Sprintf("variable \"kms_vault_id\" { default = \"%s\" }\n", kmsVaultId) kmsKeyIdForCreate = getEnvSettingWithBlankDefault("key_ocid_for_create") kmsKeyIdCreateVariableStr = fmt.Sprintf("variable \"kms_key_id_for_create\" { default = \"%s\" }\n", kmsKeyIdForCreate) kmsKeyIdForUpdate = getEnvSettingWithBlankDefault("key_ocid_for_update") kmsKeyIdUpdateVariableStr = fmt.Sprintf("variable \"kms_key_id_for_update\" { default = \"%s\" }\n", kmsKeyIdForUpdate) kmsKeyCompartmentId = getEnvSettingWithBlankDefault("compartment_ocid") kmsKeyCompartmentIdVariableStr = fmt.Sprintf("variable \"kms_key_compartment_id\" { default = \"%s\" }\n", kmsKeyCompartmentId) // Should deprecate use of tenancy level resources KeyResourceDependencies = KmsVaultIdVariableStr + ` data "oci_kms_vault" "test_vault" { #Required vault_id = "${var.kms_vault_id}" } ` KeyResourceDependencyConfig = KeyResourceDependencies + ` data "oci_kms_keys" "test_keys_dependency" { #Required compartment_id = "${var.tenancy_ocid}" management_endpoint = "${data.oci_kms_vault.test_vault.management_endpoint}" algorithm = "AES" filter { name = "state" values = ["ENABLED", "UPDATING"] } } data "oci_kms_keys" "test_keys_dependency_RSA" { #Required compartment_id = "${var.tenancy_ocid}" management_endpoint = "${data.oci_kms_vault.test_vault.management_endpoint}" algorithm = "RSA" filter { name = "state" values = ["ENABLED", "UPDATING"] } } ` KeyResourceDependencyConfig2 = KeyResourceDependencies + kmsKeyCompartmentIdVariableStr + ` data "oci_kms_keys" "test_keys_dependency" { #Required compartment_id = "${var.kms_key_compartment_id}" management_endpoint = "${data.oci_kms_vault.test_vault.management_endpoint}" algorithm = "AES" filter { name = "state" values = ["ENABLED", "UPDATING"] } } data "oci_kms_keys" "test_keys_dependency_RSA" { #Required compartment_id = "${var.kms_key_compartment_id}" management_endpoint = "${data.oci_kms_vault.test_vault.management_endpoint}" algorithm = "RSA" filter { name = "state" values = ["ENABLED", "UPDATING"] } } ` ) // issue-routing-tag: kms/default func TestKmsKeyResource_basic(t *testing.T) { httpreplay.SetScenario("TestKmsKeyResource_basic") defer httpreplay.SaveScenario() provider := testAccProvider config := testProviderConfig() compartmentId := getEnvSettingWithBlankDefault("compartment_ocid") compartmentIdVariableStr := fmt.Sprintf("variable \"compartment_id\" { default = \"%s\" }\n", compartmentId) compartmentIdU := getEnvSettingWithDefault("compartment_id_for_update", compartmentId) compartmentIdUVariableStr := fmt.Sprintf("variable \"compartment_id_for_update\" { default = \"%s\" }\n", compartmentIdU) resourceName := "oci_kms_key.test_key" datasourceName := "data.oci_kms_keys.test_keys" singularDatasourceName := "data.oci_kms_key.test_key" var resId, resId2 string // Save TF content to create resource with optional properties. This has to be exactly the same as the config part in the "create with optionals" step in the test. saveConfigContent(config+compartmentIdVariableStr+KeyResourceDependencies+ generateResourceFromRepresentationMap("oci_kms_key", "test_key", Optional, Create, keyRepresentation), "keymanagement", "key", t) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, CheckDestroy: testAccCheckKMSKeyDestroy, Providers: map[string]terraform.ResourceProvider{ "oci": provider, }, Steps: []resource.TestStep{ // verify create { Config: config + compartmentIdVariableStr + KeyResourceDependencies + DefinedTagsDependencies + generateResourceFromRepresentationMap("oci_kms_key", "test_key", Required, Create, keyRepresentation), Check: ComposeAggregateTestCheckFuncWrapper( resource.TestCheckResourceAttr(resourceName, "compartment_id", compartmentId), resource.TestCheckResourceAttr(resourceName, "display_name", "Key C"), resource.TestCheckResourceAttr(resourceName, "key_shape.#", "1"), resource.TestCheckResourceAttr(resourceName, "key_shape.0.algorithm", "AES"), resource.TestCheckResourceAttr(resourceName, "key_shape.0.length", "16"), func(s *terraform.State) (err error) { resId, err = fromInstanceState(s, resourceName, "id") return err }, ), }, // delete before next create { Config: config + compartmentIdVariableStr + KeyResourceDependencies, }, // verify create with optionals { Config: config + compartmentIdVariableStr + KeyResourceDependencies + DefinedTagsDependencies + generateResourceFromRepresentationMap("oci_kms_key", "test_key", Optional, Create, keyRepresentation), Check: ComposeAggregateTestCheckFuncWrapper( resource.TestCheckResourceAttr(resourceName, "compartment_id", compartmentId), resource.TestCheckResourceAttrSet(resourceName, "current_key_version"), resource.TestCheckResourceAttr(resourceName, "display_name", "Key C"), resource.TestCheckResourceAttr(resourceName, "freeform_tags.%", "1"), resource.TestCheckResourceAttrSet(resourceName, "id"), resource.TestCheckResourceAttr(resourceName, "key_shape.#", "1"), resource.TestCheckResourceAttr(resourceName, "key_shape.0.algorithm", "AES"), resource.TestCheckResourceAttr(resourceName, "key_shape.0.length", "16"), resource.TestCheckResourceAttrSet(resourceName, "management_endpoint"), resource.TestCheckResourceAttr(resourceName, "protection_mode", "SOFTWARE"), resource.TestCheckResourceAttrSet(resourceName, "state"), resource.TestCheckResourceAttrSet(resourceName, "time_created"), resource.TestCheckResourceAttrSet(resourceName, "vault_id"), func(s *terraform.State) (err error) { resId, err = fromInstanceState(s, resourceName, "id") return err }, ), }, // verify update to the compartment (the compartment will be switched back in the next step) { Config: config + compartmentIdVariableStr + compartmentIdUVariableStr + KeyResourceDependencies + DefinedTagsDependencies + generateResourceFromRepresentationMap("oci_kms_key", "test_key", Optional, Create, representationCopyWithNewProperties(keyRepresentation, map[string]interface{}{ "compartment_id": Representation{repType: Required, create: `${var.compartment_id_for_update}`}, })), Check: ComposeAggregateTestCheckFuncWrapper( resource.TestCheckResourceAttr(resourceName, "compartment_id", compartmentIdU), resource.TestCheckResourceAttrSet(resourceName, "current_key_version"), resource.TestCheckResourceAttr(resourceName, "display_name", "Key C"), resource.TestCheckResourceAttr(resourceName, "freeform_tags.%", "1"), resource.TestCheckResourceAttrSet(resourceName, "id"), resource.TestCheckResourceAttr(resourceName, "key_shape.#", "1"), resource.TestCheckResourceAttr(resourceName, "key_shape.0.algorithm", "AES"), resource.TestCheckResourceAttr(resourceName, "key_shape.0.length", "16"), resource.TestCheckResourceAttr(resourceName, "protection_mode", "SOFTWARE"), resource.TestCheckResourceAttrSet(resourceName, "state"), resource.TestCheckResourceAttrSet(resourceName, "time_created"), resource.TestCheckResourceAttrSet(resourceName, "vault_id"), func(s *terraform.State) (err error) { resId2, err = fromInstanceState(s, resourceName, "id") if resId != resId2 { return fmt.Errorf("resource recreated when it was supposed to be updated") } return err }, ), }, // verify updates to updatable parameters { Config: config + compartmentIdVariableStr + KeyResourceDependencies + DefinedTagsDependencies + generateResourceFromRepresentationMap("oci_kms_key", "test_key", Optional, Update, keyRepresentation), Check: ComposeAggregateTestCheckFuncWrapper( resource.TestCheckResourceAttr(resourceName, "compartment_id", compartmentId), resource.TestCheckResourceAttrSet(resourceName, "current_key_version"), resource.TestCheckResourceAttr(resourceName, "display_name", "displayName2"), resource.TestCheckResourceAttr(resourceName, "freeform_tags.%", "1"), resource.TestCheckResourceAttrSet(resourceName, "id"), resource.TestCheckResourceAttr(resourceName, "key_shape.#", "1"), resource.TestCheckResourceAttr(resourceName, "key_shape.0.algorithm", "AES"), resource.TestCheckResourceAttr(resourceName, "key_shape.0.length", "16"), resource.TestCheckResourceAttr(resourceName, "protection_mode", "SOFTWARE"), resource.TestCheckResourceAttrSet(resourceName, "state"), resource.TestCheckResourceAttrSet(resourceName, "time_created"), resource.TestCheckResourceAttrSet(resourceName, "vault_id"), func(s *terraform.State) (err error) { resId2, err = fromInstanceState(s, resourceName, "id") if resId != resId2 { return fmt.Errorf("Resource recreated when it was supposed to be updated.") } return err }, ), }, // verify datasource { Config: config + generateDataSourceFromRepresentationMap("oci_kms_keys", "test_keys", Optional, Update, keyDataSourceRepresentation) + compartmentIdVariableStr + KeyResourceDependencies + DefinedTagsDependencies + generateResourceFromRepresentationMap("oci_kms_key", "test_key", Optional, Update, keyRepresentation), Check: ComposeAggregateTestCheckFuncWrapper( resource.TestCheckResourceAttr(datasourceName, "algorithm", "AES"), resource.TestCheckResourceAttr(datasourceName, "compartment_id", compartmentId), resource.TestCheckResourceAttrSet(datasourceName, "management_endpoint"), resource.TestCheckResourceAttr(datasourceName, "protection_mode", "SOFTWARE"), resource.TestCheckResourceAttr(datasourceName, "length", "16"), resource.TestCheckResourceAttr(datasourceName, "keys.#", "1"), resource.TestCheckResourceAttr(datasourceName, "keys.0.compartment_id", compartmentId), resource.TestCheckResourceAttr(datasourceName, "keys.0.display_name", "displayName2"), resource.TestCheckResourceAttr(datasourceName, "keys.0.freeform_tags.%", "1"), resource.TestCheckResourceAttrSet(datasourceName, "keys.0.id"), resource.TestCheckResourceAttr(datasourceName, "keys.0.protection_mode", "SOFTWARE"), resource.TestCheckResourceAttrSet(datasourceName, "keys.0.state"), resource.TestCheckResourceAttrSet(datasourceName, "keys.0.time_created"), resource.TestCheckResourceAttrSet(datasourceName, "keys.0.vault_id"), ), }, // verify singular datasource { Config: config + generateDataSourceFromRepresentationMap("oci_kms_key", "test_key", Required, Create, keySingularDataSourceRepresentation) + compartmentIdVariableStr + KeyResourceConfig + DefinedTagsDependencies, Check: ComposeAggregateTestCheckFuncWrapper( resource.TestCheckResourceAttrSet(singularDatasourceName, "key_id"), resource.TestCheckResourceAttr(singularDatasourceName, "compartment_id", compartmentId), resource.TestCheckResourceAttrSet(singularDatasourceName, "current_key_version"), resource.TestCheckResourceAttr(singularDatasourceName, "display_name", "displayName2"), resource.TestCheckResourceAttr(singularDatasourceName, "freeform_tags.%", "1"), resource.TestCheckResourceAttrSet(singularDatasourceName, "id"), resource.TestCheckResourceAttrSet(singularDatasourceName, "is_primary"), resource.TestCheckResourceAttr(singularDatasourceName, "key_shape.#", "1"), resource.TestCheckResourceAttr(singularDatasourceName, "key_shape.0.algorithm", "AES"), resource.TestCheckResourceAttr(singularDatasourceName, "key_shape.0.length", "16"), resource.TestCheckResourceAttr(singularDatasourceName, "protection_mode", "SOFTWARE"), resource.TestCheckResourceAttrSet(singularDatasourceName, "state"), resource.TestCheckResourceAttrSet(singularDatasourceName, "time_created"), resource.TestCheckResourceAttrSet(singularDatasourceName, "vault_id"), ), }, // remove singular datasource from previous step so that it doesn't conflict with import tests { Config: config + compartmentIdVariableStr + KeyResourceConfig + DefinedTagsDependencies, }, // revert the updates { Config: config + compartmentIdVariableStr + KeyResourceDependencies + DefinedTagsDependencies + generateResourceFromRepresentationMap("oci_kms_key", "test_key", Optional, Create, keyRepresentation), Check: ComposeAggregateTestCheckFuncWrapper( resource.TestCheckResourceAttr(resourceName, "display_name", "Key C"), resource.TestCheckResourceAttr(resourceName, "state", "ENABLED"), func(s *terraform.State) (err error) { resId2, err = fromInstanceState(s, resourceName, "id") if resId != resId2 { return fmt.Errorf("Resource recreated when it was supposed to be updated.") } return err }, ), }, // verify resource import { Config: config, ImportState: true, ImportStateVerify: true, ImportStateIdFunc: keyImportId, ImportStateVerifyIgnore: []string{ "desired_state", "time_of_deletion", "replica_details", }, ResourceName: resourceName, }, }, }) } func testAccCheckKMSKeyDestroy(s *terraform.State) error { noResourceFound := true for _, rs := range s.RootModule().Resources { if rs.Type == "oci_kms_key" { client, err := testAccProvider.Meta().(*OracleClients).KmsManagementClient(rs.Primary.Attributes["management_endpoint"]) if err != nil { return err } noResourceFound = false request := oci_kms.GetKeyRequest{} tmp := rs.Primary.ID request.KeyId = &tmp request.RequestMetadata.RetryPolicy = getRetryPolicy(true, "kms") response, err := client.GetKey(context.Background(), request) if err == nil { deletedLifecycleStates := map[string]bool{ string(oci_kms.KeyLifecycleStateSchedulingDeletion): true, string(oci_kms.KeyLifecycleStatePendingDeletion): true, } if _, ok := deletedLifecycleStates[string(response.LifecycleState)]; !ok { //resource lifecycle state is not in expected deleted lifecycle states. return fmt.Errorf("resource lifecycle state: %s is not in expected deleted lifecycle states", response.LifecycleState) } if !response.TimeOfDeletion.Equal(deletionTime) && !httpreplay.ModeRecordReplay() { return fmt.Errorf("resource time_of_deletion: %s is not set to %s", response.TimeOfDeletion.Format(time.RFC3339Nano), deletionTime.Format(time.RFC3339Nano)) } //resource lifecycle state is in expected deleted lifecycle states. continue with next one. continue } //Verify that exception is for '404 not found'. if failure, isServiceError := common.IsServiceError(err); !isServiceError || failure.GetHTTPStatusCode() != 404 { return err } } } if noResourceFound { return fmt.Errorf("at least one resource was expected from the state file, but could not be found") } return nil } func keyImportId(state *terraform.State) (string, error) { for _, rs := range state.RootModule().Resources { if rs.Type == "oci_kms_key" { return fmt.Sprintf("managementEndpoint/%s/keys/%s", rs.Primary.Attributes["management_endpoint"], rs.Primary.ID), nil } } return "", fmt.Errorf("unable to create import id as no resource of type oci_kms_key in state") }
mpl-2.0
zhougithui/bookstore-single
src/test/java/org/bear/bookstore/concurrent/PriorityQueueTest.java
831
package org.bear.bookstore.concurrent; import java.util.PriorityQueue; public class PriorityQueueTest { public static void main(String[] args) { PriorityQueue<String> queue = new PriorityQueue<>((a,b)->{ return a.compareTo(b); }); queue.add("a"); queue.add("x"); queue.add("c"); queue.add("e"); queue.add("a"); System.out.println(queue.poll()); System.out.println(queue.poll()); System.out.println(queue.poll()); int x = 15 & (("abcd".hashCode()) ^ ("abcd".hashCode() >>> 16)); System.out.println(Integer.toBinaryString("abcd".hashCode())); System.out.println(Integer.toBinaryString("abcd".hashCode() >>> 16)); System.out.println(Integer.toBinaryString(("abcd".hashCode()) ^ ("abcd".hashCode() >>> 16))); System.out.println(Integer.toBinaryString(15)); System.out.println(x); } }
mpl-2.0
hartsock/vault
vendor/google.golang.org/genproto/googleapis/monitoring/v3/alert.pb.go
58646
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.22.0 // protoc v3.11.2 // source: google/monitoring/v3/alert.proto package monitoring import ( reflect "reflect" sync "sync" proto "github.com/golang/protobuf/proto" duration "github.com/golang/protobuf/ptypes/duration" wrappers "github.com/golang/protobuf/ptypes/wrappers" _ "google.golang.org/genproto/googleapis/api/annotations" status "google.golang.org/genproto/googleapis/rpc/status" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) // This is a compile-time assertion that a sufficiently up-to-date version // of the legacy proto package is being used. const _ = proto.ProtoPackageIsVersion4 // Operators for combining conditions. type AlertPolicy_ConditionCombinerType int32 const ( // An unspecified combiner. AlertPolicy_COMBINE_UNSPECIFIED AlertPolicy_ConditionCombinerType = 0 // Combine conditions using the logical `AND` operator. An // incident is created only if all the conditions are met // simultaneously. This combiner is satisfied if all conditions are // met, even if they are met on completely different resources. AlertPolicy_AND AlertPolicy_ConditionCombinerType = 1 // Combine conditions using the logical `OR` operator. An incident // is created if any of the listed conditions is met. AlertPolicy_OR AlertPolicy_ConditionCombinerType = 2 // Combine conditions using logical `AND` operator, but unlike the regular // `AND` option, an incident is created only if all conditions are met // simultaneously on at least one resource. AlertPolicy_AND_WITH_MATCHING_RESOURCE AlertPolicy_ConditionCombinerType = 3 ) // Enum value maps for AlertPolicy_ConditionCombinerType. var ( AlertPolicy_ConditionCombinerType_name = map[int32]string{ 0: "COMBINE_UNSPECIFIED", 1: "AND", 2: "OR", 3: "AND_WITH_MATCHING_RESOURCE", } AlertPolicy_ConditionCombinerType_value = map[string]int32{ "COMBINE_UNSPECIFIED": 0, "AND": 1, "OR": 2, "AND_WITH_MATCHING_RESOURCE": 3, } ) func (x AlertPolicy_ConditionCombinerType) Enum() *AlertPolicy_ConditionCombinerType { p := new(AlertPolicy_ConditionCombinerType) *p = x return p } func (x AlertPolicy_ConditionCombinerType) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (AlertPolicy_ConditionCombinerType) Descriptor() protoreflect.EnumDescriptor { return file_google_monitoring_v3_alert_proto_enumTypes[0].Descriptor() } func (AlertPolicy_ConditionCombinerType) Type() protoreflect.EnumType { return &file_google_monitoring_v3_alert_proto_enumTypes[0] } func (x AlertPolicy_ConditionCombinerType) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use AlertPolicy_ConditionCombinerType.Descriptor instead. func (AlertPolicy_ConditionCombinerType) EnumDescriptor() ([]byte, []int) { return file_google_monitoring_v3_alert_proto_rawDescGZIP(), []int{0, 0} } // A description of the conditions under which some aspect of your system is // considered to be "unhealthy" and the ways to notify people or services about // this state. For an overview of alert policies, see // [Introduction to Alerting](https://cloud.google.com/monitoring/alerts/). type AlertPolicy struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // Required if the policy exists. The resource name for this policy. The // format is: // // projects/[PROJECT_ID_OR_NUMBER]/alertPolicies/[ALERT_POLICY_ID] // // `[ALERT_POLICY_ID]` is assigned by Stackdriver Monitoring when the policy // is created. When calling the // [alertPolicies.create][google.monitoring.v3.AlertPolicyService.CreateAlertPolicy] // method, do not include the `name` field in the alerting policy passed as // part of the request. Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // A short name or phrase used to identify the policy in dashboards, // notifications, and incidents. To avoid confusion, don't use the same // display name for multiple policies in the same project. The name is // limited to 512 Unicode characters. DisplayName string `protobuf:"bytes,2,opt,name=display_name,json=displayName,proto3" json:"display_name,omitempty"` // Documentation that is included with notifications and incidents related to // this policy. Best practice is for the documentation to include information // to help responders understand, mitigate, escalate, and correct the // underlying problems detected by the alerting policy. Notification channels // that have limited capacity might not show this documentation. Documentation *AlertPolicy_Documentation `protobuf:"bytes,13,opt,name=documentation,proto3" json:"documentation,omitempty"` // User-supplied key/value data to be used for organizing and // identifying the `AlertPolicy` objects. // // The field can contain up to 64 entries. Each key and value is limited to // 63 Unicode characters or 128 bytes, whichever is smaller. Labels and // values can contain only lowercase letters, numerals, underscores, and // dashes. Keys must begin with a letter. UserLabels map[string]string `protobuf:"bytes,16,rep,name=user_labels,json=userLabels,proto3" json:"user_labels,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` // A list of conditions for the policy. The conditions are combined by AND or // OR according to the `combiner` field. If the combined conditions evaluate // to true, then an incident is created. A policy can have from one to six // conditions. // If `condition_time_series_query_language` is present, it must be the only // `condition`. Conditions []*AlertPolicy_Condition `protobuf:"bytes,12,rep,name=conditions,proto3" json:"conditions,omitempty"` // How to combine the results of multiple conditions to determine if an // incident should be opened. // If `condition_time_series_query_language` is present, this must be // `COMBINE_UNSPECIFIED`. Combiner AlertPolicy_ConditionCombinerType `protobuf:"varint,6,opt,name=combiner,proto3,enum=google.monitoring.v3.AlertPolicy_ConditionCombinerType" json:"combiner,omitempty"` // Whether or not the policy is enabled. On write, the default interpretation // if unset is that the policy is enabled. On read, clients should not make // any assumption about the state if it has not been populated. The // field should always be populated on List and Get operations, unless // a field projection has been specified that strips it out. Enabled *wrappers.BoolValue `protobuf:"bytes,17,opt,name=enabled,proto3" json:"enabled,omitempty"` // Read-only description of how the alert policy is invalid. OK if the alert // policy is valid. If not OK, the alert policy will not generate incidents. Validity *status.Status `protobuf:"bytes,18,opt,name=validity,proto3" json:"validity,omitempty"` // Identifies the notification channels to which notifications should be sent // when incidents are opened or closed or when new violations occur on // an already opened incident. Each element of this array corresponds to // the `name` field in each of the // [`NotificationChannel`][google.monitoring.v3.NotificationChannel] // objects that are returned from the [`ListNotificationChannels`] // [google.monitoring.v3.NotificationChannelService.ListNotificationChannels] // method. The format of the entries in this field is: // // projects/[PROJECT_ID_OR_NUMBER]/notificationChannels/[CHANNEL_ID] NotificationChannels []string `protobuf:"bytes,14,rep,name=notification_channels,json=notificationChannels,proto3" json:"notification_channels,omitempty"` // A read-only record of the creation of the alerting policy. If provided // in a call to create or update, this field will be ignored. CreationRecord *MutationRecord `protobuf:"bytes,10,opt,name=creation_record,json=creationRecord,proto3" json:"creation_record,omitempty"` // A read-only record of the most recent change to the alerting policy. If // provided in a call to create or update, this field will be ignored. MutationRecord *MutationRecord `protobuf:"bytes,11,opt,name=mutation_record,json=mutationRecord,proto3" json:"mutation_record,omitempty"` } func (x *AlertPolicy) Reset() { *x = AlertPolicy{} if protoimpl.UnsafeEnabled { mi := &file_google_monitoring_v3_alert_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *AlertPolicy) String() string { return protoimpl.X.MessageStringOf(x) } func (*AlertPolicy) ProtoMessage() {} func (x *AlertPolicy) ProtoReflect() protoreflect.Message { mi := &file_google_monitoring_v3_alert_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use AlertPolicy.ProtoReflect.Descriptor instead. func (*AlertPolicy) Descriptor() ([]byte, []int) { return file_google_monitoring_v3_alert_proto_rawDescGZIP(), []int{0} } func (x *AlertPolicy) GetName() string { if x != nil { return x.Name } return "" } func (x *AlertPolicy) GetDisplayName() string { if x != nil { return x.DisplayName } return "" } func (x *AlertPolicy) GetDocumentation() *AlertPolicy_Documentation { if x != nil { return x.Documentation } return nil } func (x *AlertPolicy) GetUserLabels() map[string]string { if x != nil { return x.UserLabels } return nil } func (x *AlertPolicy) GetConditions() []*AlertPolicy_Condition { if x != nil { return x.Conditions } return nil } func (x *AlertPolicy) GetCombiner() AlertPolicy_ConditionCombinerType { if x != nil { return x.Combiner } return AlertPolicy_COMBINE_UNSPECIFIED } func (x *AlertPolicy) GetEnabled() *wrappers.BoolValue { if x != nil { return x.Enabled } return nil } func (x *AlertPolicy) GetValidity() *status.Status { if x != nil { return x.Validity } return nil } func (x *AlertPolicy) GetNotificationChannels() []string { if x != nil { return x.NotificationChannels } return nil } func (x *AlertPolicy) GetCreationRecord() *MutationRecord { if x != nil { return x.CreationRecord } return nil } func (x *AlertPolicy) GetMutationRecord() *MutationRecord { if x != nil { return x.MutationRecord } return nil } // A content string and a MIME type that describes the content string's // format. type AlertPolicy_Documentation struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // The text of the documentation, interpreted according to `mime_type`. // The content may not exceed 8,192 Unicode characters and may not exceed // more than 10,240 bytes when encoded in UTF-8 format, whichever is // smaller. Content string `protobuf:"bytes,1,opt,name=content,proto3" json:"content,omitempty"` // The format of the `content` field. Presently, only the value // `"text/markdown"` is supported. See // [Markdown](https://en.wikipedia.org/wiki/Markdown) for more information. MimeType string `protobuf:"bytes,2,opt,name=mime_type,json=mimeType,proto3" json:"mime_type,omitempty"` } func (x *AlertPolicy_Documentation) Reset() { *x = AlertPolicy_Documentation{} if protoimpl.UnsafeEnabled { mi := &file_google_monitoring_v3_alert_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *AlertPolicy_Documentation) String() string { return protoimpl.X.MessageStringOf(x) } func (*AlertPolicy_Documentation) ProtoMessage() {} func (x *AlertPolicy_Documentation) ProtoReflect() protoreflect.Message { mi := &file_google_monitoring_v3_alert_proto_msgTypes[1] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use AlertPolicy_Documentation.ProtoReflect.Descriptor instead. func (*AlertPolicy_Documentation) Descriptor() ([]byte, []int) { return file_google_monitoring_v3_alert_proto_rawDescGZIP(), []int{0, 0} } func (x *AlertPolicy_Documentation) GetContent() string { if x != nil { return x.Content } return "" } func (x *AlertPolicy_Documentation) GetMimeType() string { if x != nil { return x.MimeType } return "" } // A condition is a true/false test that determines when an alerting policy // should open an incident. If a condition evaluates to true, it signifies // that something is wrong. type AlertPolicy_Condition struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // Required if the condition exists. The unique resource name for this // condition. Its format is: // // projects/[PROJECT_ID_OR_NUMBER]/alertPolicies/[POLICY_ID]/conditions/[CONDITION_ID] // // `[CONDITION_ID]` is assigned by Stackdriver Monitoring when the // condition is created as part of a new or updated alerting policy. // // When calling the // [alertPolicies.create][google.monitoring.v3.AlertPolicyService.CreateAlertPolicy] // method, do not include the `name` field in the conditions of the // requested alerting policy. Stackdriver Monitoring creates the // condition identifiers and includes them in the new policy. // // When calling the // [alertPolicies.update][google.monitoring.v3.AlertPolicyService.UpdateAlertPolicy] // method to update a policy, including a condition `name` causes the // existing condition to be updated. Conditions without names are added to // the updated policy. Existing conditions are deleted if they are not // updated. // // Best practice is to preserve `[CONDITION_ID]` if you make only small // changes, such as those to condition thresholds, durations, or trigger // values. Otherwise, treat the change as a new condition and let the // existing condition be deleted. Name string `protobuf:"bytes,12,opt,name=name,proto3" json:"name,omitempty"` // A short name or phrase used to identify the condition in dashboards, // notifications, and incidents. To avoid confusion, don't use the same // display name for multiple conditions in the same policy. DisplayName string `protobuf:"bytes,6,opt,name=display_name,json=displayName,proto3" json:"display_name,omitempty"` // Only one of the following condition types will be specified. // // Types that are assignable to Condition: // *AlertPolicy_Condition_ConditionThreshold // *AlertPolicy_Condition_ConditionAbsent Condition isAlertPolicy_Condition_Condition `protobuf_oneof:"condition"` } func (x *AlertPolicy_Condition) Reset() { *x = AlertPolicy_Condition{} if protoimpl.UnsafeEnabled { mi := &file_google_monitoring_v3_alert_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *AlertPolicy_Condition) String() string { return protoimpl.X.MessageStringOf(x) } func (*AlertPolicy_Condition) ProtoMessage() {} func (x *AlertPolicy_Condition) ProtoReflect() protoreflect.Message { mi := &file_google_monitoring_v3_alert_proto_msgTypes[2] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use AlertPolicy_Condition.ProtoReflect.Descriptor instead. func (*AlertPolicy_Condition) Descriptor() ([]byte, []int) { return file_google_monitoring_v3_alert_proto_rawDescGZIP(), []int{0, 1} } func (x *AlertPolicy_Condition) GetName() string { if x != nil { return x.Name } return "" } func (x *AlertPolicy_Condition) GetDisplayName() string { if x != nil { return x.DisplayName } return "" } func (m *AlertPolicy_Condition) GetCondition() isAlertPolicy_Condition_Condition { if m != nil { return m.Condition } return nil } func (x *AlertPolicy_Condition) GetConditionThreshold() *AlertPolicy_Condition_MetricThreshold { if x, ok := x.GetCondition().(*AlertPolicy_Condition_ConditionThreshold); ok { return x.ConditionThreshold } return nil } func (x *AlertPolicy_Condition) GetConditionAbsent() *AlertPolicy_Condition_MetricAbsence { if x, ok := x.GetCondition().(*AlertPolicy_Condition_ConditionAbsent); ok { return x.ConditionAbsent } return nil } type isAlertPolicy_Condition_Condition interface { isAlertPolicy_Condition_Condition() } type AlertPolicy_Condition_ConditionThreshold struct { // A condition that compares a time series against a threshold. ConditionThreshold *AlertPolicy_Condition_MetricThreshold `protobuf:"bytes,1,opt,name=condition_threshold,json=conditionThreshold,proto3,oneof"` } type AlertPolicy_Condition_ConditionAbsent struct { // A condition that checks that a time series continues to // receive new data points. ConditionAbsent *AlertPolicy_Condition_MetricAbsence `protobuf:"bytes,2,opt,name=condition_absent,json=conditionAbsent,proto3,oneof"` } func (*AlertPolicy_Condition_ConditionThreshold) isAlertPolicy_Condition_Condition() {} func (*AlertPolicy_Condition_ConditionAbsent) isAlertPolicy_Condition_Condition() {} // Specifies how many time series must fail a predicate to trigger a // condition. If not specified, then a `{count: 1}` trigger is used. type AlertPolicy_Condition_Trigger struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // A type of trigger. // // Types that are assignable to Type: // *AlertPolicy_Condition_Trigger_Count // *AlertPolicy_Condition_Trigger_Percent Type isAlertPolicy_Condition_Trigger_Type `protobuf_oneof:"type"` } func (x *AlertPolicy_Condition_Trigger) Reset() { *x = AlertPolicy_Condition_Trigger{} if protoimpl.UnsafeEnabled { mi := &file_google_monitoring_v3_alert_proto_msgTypes[4] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *AlertPolicy_Condition_Trigger) String() string { return protoimpl.X.MessageStringOf(x) } func (*AlertPolicy_Condition_Trigger) ProtoMessage() {} func (x *AlertPolicy_Condition_Trigger) ProtoReflect() protoreflect.Message { mi := &file_google_monitoring_v3_alert_proto_msgTypes[4] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use AlertPolicy_Condition_Trigger.ProtoReflect.Descriptor instead. func (*AlertPolicy_Condition_Trigger) Descriptor() ([]byte, []int) { return file_google_monitoring_v3_alert_proto_rawDescGZIP(), []int{0, 1, 0} } func (m *AlertPolicy_Condition_Trigger) GetType() isAlertPolicy_Condition_Trigger_Type { if m != nil { return m.Type } return nil } func (x *AlertPolicy_Condition_Trigger) GetCount() int32 { if x, ok := x.GetType().(*AlertPolicy_Condition_Trigger_Count); ok { return x.Count } return 0 } func (x *AlertPolicy_Condition_Trigger) GetPercent() float64 { if x, ok := x.GetType().(*AlertPolicy_Condition_Trigger_Percent); ok { return x.Percent } return 0 } type isAlertPolicy_Condition_Trigger_Type interface { isAlertPolicy_Condition_Trigger_Type() } type AlertPolicy_Condition_Trigger_Count struct { // The absolute number of time series that must fail // the predicate for the condition to be triggered. Count int32 `protobuf:"varint,1,opt,name=count,proto3,oneof"` } type AlertPolicy_Condition_Trigger_Percent struct { // The percentage of time series that must fail the // predicate for the condition to be triggered. Percent float64 `protobuf:"fixed64,2,opt,name=percent,proto3,oneof"` } func (*AlertPolicy_Condition_Trigger_Count) isAlertPolicy_Condition_Trigger_Type() {} func (*AlertPolicy_Condition_Trigger_Percent) isAlertPolicy_Condition_Trigger_Type() {} // A condition type that compares a collection of time series // against a threshold. type AlertPolicy_Condition_MetricThreshold struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // A [filter](https://cloud.google.com/monitoring/api/v3/filters) that // identifies which time series should be compared with the threshold. // // The filter is similar to the one that is specified in the // [`ListTimeSeries` // request](https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.timeSeries/list) // (that call is useful to verify the time series that will be retrieved / // processed) and must specify the metric type and optionally may contain // restrictions on resource type, resource labels, and metric labels. // This field may not exceed 2048 Unicode characters in length. Filter string `protobuf:"bytes,2,opt,name=filter,proto3" json:"filter,omitempty"` // Specifies the alignment of data points in individual time series as // well as how to combine the retrieved time series together (such as // when aggregating multiple streams on each resource to a single // stream for each resource or when aggregating streams across all // members of a group of resrouces). Multiple aggregations // are applied in the order specified. // // This field is similar to the one in the [`ListTimeSeries` // request](https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.timeSeries/list). // It is advisable to use the `ListTimeSeries` method when debugging this // field. Aggregations []*Aggregation `protobuf:"bytes,8,rep,name=aggregations,proto3" json:"aggregations,omitempty"` // A [filter](https://cloud.google.com/monitoring/api/v3/filters) that // identifies a time series that should be used as the denominator of a // ratio that will be compared with the threshold. If a // `denominator_filter` is specified, the time series specified by the // `filter` field will be used as the numerator. // // The filter must specify the metric type and optionally may contain // restrictions on resource type, resource labels, and metric labels. // This field may not exceed 2048 Unicode characters in length. DenominatorFilter string `protobuf:"bytes,9,opt,name=denominator_filter,json=denominatorFilter,proto3" json:"denominator_filter,omitempty"` // Specifies the alignment of data points in individual time series // selected by `denominatorFilter` as // well as how to combine the retrieved time series together (such as // when aggregating multiple streams on each resource to a single // stream for each resource or when aggregating streams across all // members of a group of resources). // // When computing ratios, the `aggregations` and // `denominator_aggregations` fields must use the same alignment period // and produce time series that have the same periodicity and labels. DenominatorAggregations []*Aggregation `protobuf:"bytes,10,rep,name=denominator_aggregations,json=denominatorAggregations,proto3" json:"denominator_aggregations,omitempty"` // The comparison to apply between the time series (indicated by `filter` // and `aggregation`) and the threshold (indicated by `threshold_value`). // The comparison is applied on each time series, with the time series // on the left-hand side and the threshold on the right-hand side. // // Only `COMPARISON_LT` and `COMPARISON_GT` are supported currently. Comparison ComparisonType `protobuf:"varint,4,opt,name=comparison,proto3,enum=google.monitoring.v3.ComparisonType" json:"comparison,omitempty"` // A value against which to compare the time series. ThresholdValue float64 `protobuf:"fixed64,5,opt,name=threshold_value,json=thresholdValue,proto3" json:"threshold_value,omitempty"` // The amount of time that a time series must violate the // threshold to be considered failing. Currently, only values // that are a multiple of a minute--e.g., 0, 60, 120, or 300 // seconds--are supported. If an invalid value is given, an // error will be returned. When choosing a duration, it is useful to // keep in mind the frequency of the underlying time series data // (which may also be affected by any alignments specified in the // `aggregations` field); a good duration is long enough so that a single // outlier does not generate spurious alerts, but short enough that // unhealthy states are detected and alerted on quickly. Duration *duration.Duration `protobuf:"bytes,6,opt,name=duration,proto3" json:"duration,omitempty"` // The number/percent of time series for which the comparison must hold // in order for the condition to trigger. If unspecified, then the // condition will trigger if the comparison is true for any of the // time series that have been identified by `filter` and `aggregations`, // or by the ratio, if `denominator_filter` and `denominator_aggregations` // are specified. Trigger *AlertPolicy_Condition_Trigger `protobuf:"bytes,7,opt,name=trigger,proto3" json:"trigger,omitempty"` } func (x *AlertPolicy_Condition_MetricThreshold) Reset() { *x = AlertPolicy_Condition_MetricThreshold{} if protoimpl.UnsafeEnabled { mi := &file_google_monitoring_v3_alert_proto_msgTypes[5] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *AlertPolicy_Condition_MetricThreshold) String() string { return protoimpl.X.MessageStringOf(x) } func (*AlertPolicy_Condition_MetricThreshold) ProtoMessage() {} func (x *AlertPolicy_Condition_MetricThreshold) ProtoReflect() protoreflect.Message { mi := &file_google_monitoring_v3_alert_proto_msgTypes[5] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use AlertPolicy_Condition_MetricThreshold.ProtoReflect.Descriptor instead. func (*AlertPolicy_Condition_MetricThreshold) Descriptor() ([]byte, []int) { return file_google_monitoring_v3_alert_proto_rawDescGZIP(), []int{0, 1, 1} } func (x *AlertPolicy_Condition_MetricThreshold) GetFilter() string { if x != nil { return x.Filter } return "" } func (x *AlertPolicy_Condition_MetricThreshold) GetAggregations() []*Aggregation { if x != nil { return x.Aggregations } return nil } func (x *AlertPolicy_Condition_MetricThreshold) GetDenominatorFilter() string { if x != nil { return x.DenominatorFilter } return "" } func (x *AlertPolicy_Condition_MetricThreshold) GetDenominatorAggregations() []*Aggregation { if x != nil { return x.DenominatorAggregations } return nil } func (x *AlertPolicy_Condition_MetricThreshold) GetComparison() ComparisonType { if x != nil { return x.Comparison } return ComparisonType_COMPARISON_UNSPECIFIED } func (x *AlertPolicy_Condition_MetricThreshold) GetThresholdValue() float64 { if x != nil { return x.ThresholdValue } return 0 } func (x *AlertPolicy_Condition_MetricThreshold) GetDuration() *duration.Duration { if x != nil { return x.Duration } return nil } func (x *AlertPolicy_Condition_MetricThreshold) GetTrigger() *AlertPolicy_Condition_Trigger { if x != nil { return x.Trigger } return nil } // A condition type that checks that monitored resources // are reporting data. The configuration defines a metric and // a set of monitored resources. The predicate is considered in violation // when a time series for the specified metric of a monitored // resource does not include any data in the specified `duration`. type AlertPolicy_Condition_MetricAbsence struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // A [filter](https://cloud.google.com/monitoring/api/v3/filters) that // identifies which time series should be compared with the threshold. // // The filter is similar to the one that is specified in the // [`ListTimeSeries` // request](https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.timeSeries/list) // (that call is useful to verify the time series that will be retrieved / // processed) and must specify the metric type and optionally may contain // restrictions on resource type, resource labels, and metric labels. // This field may not exceed 2048 Unicode characters in length. Filter string `protobuf:"bytes,1,opt,name=filter,proto3" json:"filter,omitempty"` // Specifies the alignment of data points in individual time series as // well as how to combine the retrieved time series together (such as // when aggregating multiple streams on each resource to a single // stream for each resource or when aggregating streams across all // members of a group of resrouces). Multiple aggregations // are applied in the order specified. // // This field is similar to the one in the [`ListTimeSeries` // request](https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.timeSeries/list). // It is advisable to use the `ListTimeSeries` method when debugging this // field. Aggregations []*Aggregation `protobuf:"bytes,5,rep,name=aggregations,proto3" json:"aggregations,omitempty"` // The amount of time that a time series must fail to report new // data to be considered failing. Currently, only values that // are a multiple of a minute--e.g. 60, 120, or 300 // seconds--are supported. If an invalid value is given, an // error will be returned. The `Duration.nanos` field is // ignored. Duration *duration.Duration `protobuf:"bytes,2,opt,name=duration,proto3" json:"duration,omitempty"` // The number/percent of time series for which the comparison must hold // in order for the condition to trigger. If unspecified, then the // condition will trigger if the comparison is true for any of the // time series that have been identified by `filter` and `aggregations`. Trigger *AlertPolicy_Condition_Trigger `protobuf:"bytes,3,opt,name=trigger,proto3" json:"trigger,omitempty"` } func (x *AlertPolicy_Condition_MetricAbsence) Reset() { *x = AlertPolicy_Condition_MetricAbsence{} if protoimpl.UnsafeEnabled { mi := &file_google_monitoring_v3_alert_proto_msgTypes[6] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *AlertPolicy_Condition_MetricAbsence) String() string { return protoimpl.X.MessageStringOf(x) } func (*AlertPolicy_Condition_MetricAbsence) ProtoMessage() {} func (x *AlertPolicy_Condition_MetricAbsence) ProtoReflect() protoreflect.Message { mi := &file_google_monitoring_v3_alert_proto_msgTypes[6] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use AlertPolicy_Condition_MetricAbsence.ProtoReflect.Descriptor instead. func (*AlertPolicy_Condition_MetricAbsence) Descriptor() ([]byte, []int) { return file_google_monitoring_v3_alert_proto_rawDescGZIP(), []int{0, 1, 2} } func (x *AlertPolicy_Condition_MetricAbsence) GetFilter() string { if x != nil { return x.Filter } return "" } func (x *AlertPolicy_Condition_MetricAbsence) GetAggregations() []*Aggregation { if x != nil { return x.Aggregations } return nil } func (x *AlertPolicy_Condition_MetricAbsence) GetDuration() *duration.Duration { if x != nil { return x.Duration } return nil } func (x *AlertPolicy_Condition_MetricAbsence) GetTrigger() *AlertPolicy_Condition_Trigger { if x != nil { return x.Trigger } return nil } var File_google_monitoring_v3_alert_proto protoreflect.FileDescriptor var file_google_monitoring_v3_alert_proto_rawDesc = []byte{ 0x0a, 0x20, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x6d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x2f, 0x76, 0x33, 0x2f, 0x61, 0x6c, 0x65, 0x72, 0x74, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x14, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x6d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x2e, 0x76, 0x33, 0x1a, 0x19, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x21, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x6d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x2f, 0x76, 0x33, 0x2f, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x2a, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x6d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x2f, 0x76, 0x33, 0x2f, 0x6d, 0x75, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x72, 0x65, 0x63, 0x6f, 0x72, 0x64, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x64, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x77, 0x72, 0x61, 0x70, 0x70, 0x65, 0x72, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x17, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x72, 0x70, 0x63, 0x2f, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0xf7, 0x13, 0x0a, 0x0b, 0x41, 0x6c, 0x65, 0x72, 0x74, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x21, 0x0a, 0x0c, 0x64, 0x69, 0x73, 0x70, 0x6c, 0x61, 0x79, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x64, 0x69, 0x73, 0x70, 0x6c, 0x61, 0x79, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x55, 0x0a, 0x0d, 0x64, 0x6f, 0x63, 0x75, 0x6d, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x0d, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2f, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x6d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x2e, 0x76, 0x33, 0x2e, 0x41, 0x6c, 0x65, 0x72, 0x74, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x2e, 0x44, 0x6f, 0x63, 0x75, 0x6d, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0d, 0x64, 0x6f, 0x63, 0x75, 0x6d, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x52, 0x0a, 0x0b, 0x75, 0x73, 0x65, 0x72, 0x5f, 0x6c, 0x61, 0x62, 0x65, 0x6c, 0x73, 0x18, 0x10, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x31, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x6d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x2e, 0x76, 0x33, 0x2e, 0x41, 0x6c, 0x65, 0x72, 0x74, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x2e, 0x55, 0x73, 0x65, 0x72, 0x4c, 0x61, 0x62, 0x65, 0x6c, 0x73, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x52, 0x0a, 0x75, 0x73, 0x65, 0x72, 0x4c, 0x61, 0x62, 0x65, 0x6c, 0x73, 0x12, 0x4b, 0x0a, 0x0a, 0x63, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x0c, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x2b, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x6d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x2e, 0x76, 0x33, 0x2e, 0x41, 0x6c, 0x65, 0x72, 0x74, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x2e, 0x43, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0a, 0x63, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x53, 0x0a, 0x08, 0x63, 0x6f, 0x6d, 0x62, 0x69, 0x6e, 0x65, 0x72, 0x18, 0x06, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x37, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x6d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x2e, 0x76, 0x33, 0x2e, 0x41, 0x6c, 0x65, 0x72, 0x74, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x2e, 0x43, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x43, 0x6f, 0x6d, 0x62, 0x69, 0x6e, 0x65, 0x72, 0x54, 0x79, 0x70, 0x65, 0x52, 0x08, 0x63, 0x6f, 0x6d, 0x62, 0x69, 0x6e, 0x65, 0x72, 0x12, 0x34, 0x0a, 0x07, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x18, 0x11, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x42, 0x6f, 0x6f, 0x6c, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x07, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x12, 0x2e, 0x0a, 0x08, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x69, 0x74, 0x79, 0x18, 0x12, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x12, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x72, 0x70, 0x63, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x08, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x69, 0x74, 0x79, 0x12, 0x33, 0x0a, 0x15, 0x6e, 0x6f, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x63, 0x68, 0x61, 0x6e, 0x6e, 0x65, 0x6c, 0x73, 0x18, 0x0e, 0x20, 0x03, 0x28, 0x09, 0x52, 0x14, 0x6e, 0x6f, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x43, 0x68, 0x61, 0x6e, 0x6e, 0x65, 0x6c, 0x73, 0x12, 0x4d, 0x0a, 0x0f, 0x63, 0x72, 0x65, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x72, 0x65, 0x63, 0x6f, 0x72, 0x64, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x24, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x6d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x2e, 0x76, 0x33, 0x2e, 0x4d, 0x75, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x63, 0x6f, 0x72, 0x64, 0x52, 0x0e, 0x63, 0x72, 0x65, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x63, 0x6f, 0x72, 0x64, 0x12, 0x4d, 0x0a, 0x0f, 0x6d, 0x75, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x72, 0x65, 0x63, 0x6f, 0x72, 0x64, 0x18, 0x0b, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x24, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x6d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x2e, 0x76, 0x33, 0x2e, 0x4d, 0x75, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x63, 0x6f, 0x72, 0x64, 0x52, 0x0e, 0x6d, 0x75, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x63, 0x6f, 0x72, 0x64, 0x1a, 0x46, 0x0a, 0x0d, 0x44, 0x6f, 0x63, 0x75, 0x6d, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x18, 0x0a, 0x07, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x12, 0x1b, 0x0a, 0x09, 0x6d, 0x69, 0x6d, 0x65, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x6d, 0x69, 0x6d, 0x65, 0x54, 0x79, 0x70, 0x65, 0x1a, 0xf4, 0x0a, 0x0a, 0x09, 0x43, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x0c, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x21, 0x0a, 0x0c, 0x64, 0x69, 0x73, 0x70, 0x6c, 0x61, 0x79, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x06, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x64, 0x69, 0x73, 0x70, 0x6c, 0x61, 0x79, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x6e, 0x0a, 0x13, 0x63, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x74, 0x68, 0x72, 0x65, 0x73, 0x68, 0x6f, 0x6c, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x3b, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x6d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x2e, 0x76, 0x33, 0x2e, 0x41, 0x6c, 0x65, 0x72, 0x74, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x2e, 0x43, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x4d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x54, 0x68, 0x72, 0x65, 0x73, 0x68, 0x6f, 0x6c, 0x64, 0x48, 0x00, 0x52, 0x12, 0x63, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x54, 0x68, 0x72, 0x65, 0x73, 0x68, 0x6f, 0x6c, 0x64, 0x12, 0x66, 0x0a, 0x10, 0x63, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x61, 0x62, 0x73, 0x65, 0x6e, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x39, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x6d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x2e, 0x76, 0x33, 0x2e, 0x41, 0x6c, 0x65, 0x72, 0x74, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x2e, 0x43, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x4d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x41, 0x62, 0x73, 0x65, 0x6e, 0x63, 0x65, 0x48, 0x00, 0x52, 0x0f, 0x63, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x41, 0x62, 0x73, 0x65, 0x6e, 0x74, 0x1a, 0x45, 0x0a, 0x07, 0x54, 0x72, 0x69, 0x67, 0x67, 0x65, 0x72, 0x12, 0x16, 0x0a, 0x05, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x05, 0x48, 0x00, 0x52, 0x05, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x1a, 0x0a, 0x07, 0x70, 0x65, 0x72, 0x63, 0x65, 0x6e, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x01, 0x48, 0x00, 0x52, 0x07, 0x70, 0x65, 0x72, 0x63, 0x65, 0x6e, 0x74, 0x42, 0x06, 0x0a, 0x04, 0x74, 0x79, 0x70, 0x65, 0x1a, 0xf2, 0x03, 0x0a, 0x0f, 0x4d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x54, 0x68, 0x72, 0x65, 0x73, 0x68, 0x6f, 0x6c, 0x64, 0x12, 0x16, 0x0a, 0x06, 0x66, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x66, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x12, 0x45, 0x0a, 0x0c, 0x61, 0x67, 0x67, 0x72, 0x65, 0x67, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x08, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x21, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x6d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x2e, 0x76, 0x33, 0x2e, 0x41, 0x67, 0x67, 0x72, 0x65, 0x67, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0c, 0x61, 0x67, 0x67, 0x72, 0x65, 0x67, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x2d, 0x0a, 0x12, 0x64, 0x65, 0x6e, 0x6f, 0x6d, 0x69, 0x6e, 0x61, 0x74, 0x6f, 0x72, 0x5f, 0x66, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x18, 0x09, 0x20, 0x01, 0x28, 0x09, 0x52, 0x11, 0x64, 0x65, 0x6e, 0x6f, 0x6d, 0x69, 0x6e, 0x61, 0x74, 0x6f, 0x72, 0x46, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x12, 0x5c, 0x0a, 0x18, 0x64, 0x65, 0x6e, 0x6f, 0x6d, 0x69, 0x6e, 0x61, 0x74, 0x6f, 0x72, 0x5f, 0x61, 0x67, 0x67, 0x72, 0x65, 0x67, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x0a, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x21, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x6d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x2e, 0x76, 0x33, 0x2e, 0x41, 0x67, 0x67, 0x72, 0x65, 0x67, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x17, 0x64, 0x65, 0x6e, 0x6f, 0x6d, 0x69, 0x6e, 0x61, 0x74, 0x6f, 0x72, 0x41, 0x67, 0x67, 0x72, 0x65, 0x67, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x44, 0x0a, 0x0a, 0x63, 0x6f, 0x6d, 0x70, 0x61, 0x72, 0x69, 0x73, 0x6f, 0x6e, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x24, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x6d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x2e, 0x76, 0x33, 0x2e, 0x43, 0x6f, 0x6d, 0x70, 0x61, 0x72, 0x69, 0x73, 0x6f, 0x6e, 0x54, 0x79, 0x70, 0x65, 0x52, 0x0a, 0x63, 0x6f, 0x6d, 0x70, 0x61, 0x72, 0x69, 0x73, 0x6f, 0x6e, 0x12, 0x27, 0x0a, 0x0f, 0x74, 0x68, 0x72, 0x65, 0x73, 0x68, 0x6f, 0x6c, 0x64, 0x5f, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x05, 0x20, 0x01, 0x28, 0x01, 0x52, 0x0e, 0x74, 0x68, 0x72, 0x65, 0x73, 0x68, 0x6f, 0x6c, 0x64, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x12, 0x35, 0x0a, 0x08, 0x64, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x06, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x08, 0x64, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x4d, 0x0a, 0x07, 0x74, 0x72, 0x69, 0x67, 0x67, 0x65, 0x72, 0x18, 0x07, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x33, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x6d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x2e, 0x76, 0x33, 0x2e, 0x41, 0x6c, 0x65, 0x72, 0x74, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x2e, 0x43, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x54, 0x72, 0x69, 0x67, 0x67, 0x65, 0x72, 0x52, 0x07, 0x74, 0x72, 0x69, 0x67, 0x67, 0x65, 0x72, 0x1a, 0xf4, 0x01, 0x0a, 0x0d, 0x4d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x41, 0x62, 0x73, 0x65, 0x6e, 0x63, 0x65, 0x12, 0x16, 0x0a, 0x06, 0x66, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x66, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x12, 0x45, 0x0a, 0x0c, 0x61, 0x67, 0x67, 0x72, 0x65, 0x67, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x05, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x21, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x6d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x2e, 0x76, 0x33, 0x2e, 0x41, 0x67, 0x67, 0x72, 0x65, 0x67, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0c, 0x61, 0x67, 0x67, 0x72, 0x65, 0x67, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x35, 0x0a, 0x08, 0x64, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x08, 0x64, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x4d, 0x0a, 0x07, 0x74, 0x72, 0x69, 0x67, 0x67, 0x65, 0x72, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x33, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x6d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x2e, 0x76, 0x33, 0x2e, 0x41, 0x6c, 0x65, 0x72, 0x74, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x2e, 0x43, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x54, 0x72, 0x69, 0x67, 0x67, 0x65, 0x72, 0x52, 0x07, 0x74, 0x72, 0x69, 0x67, 0x67, 0x65, 0x72, 0x3a, 0x97, 0x02, 0xea, 0x41, 0x93, 0x02, 0x0a, 0x2e, 0x6d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x41, 0x6c, 0x65, 0x72, 0x74, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x43, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x46, 0x70, 0x72, 0x6f, 0x6a, 0x65, 0x63, 0x74, 0x73, 0x2f, 0x7b, 0x70, 0x72, 0x6f, 0x6a, 0x65, 0x63, 0x74, 0x7d, 0x2f, 0x61, 0x6c, 0x65, 0x72, 0x74, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x69, 0x65, 0x73, 0x2f, 0x7b, 0x61, 0x6c, 0x65, 0x72, 0x74, 0x5f, 0x70, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x7d, 0x2f, 0x63, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x7b, 0x63, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x7d, 0x12, 0x50, 0x6f, 0x72, 0x67, 0x61, 0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x7b, 0x6f, 0x72, 0x67, 0x61, 0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x7d, 0x2f, 0x61, 0x6c, 0x65, 0x72, 0x74, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x69, 0x65, 0x73, 0x2f, 0x7b, 0x61, 0x6c, 0x65, 0x72, 0x74, 0x5f, 0x70, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x7d, 0x2f, 0x63, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x7b, 0x63, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x7d, 0x12, 0x44, 0x66, 0x6f, 0x6c, 0x64, 0x65, 0x72, 0x73, 0x2f, 0x7b, 0x66, 0x6f, 0x6c, 0x64, 0x65, 0x72, 0x7d, 0x2f, 0x61, 0x6c, 0x65, 0x72, 0x74, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x69, 0x65, 0x73, 0x2f, 0x7b, 0x61, 0x6c, 0x65, 0x72, 0x74, 0x5f, 0x70, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x7d, 0x2f, 0x63, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x7b, 0x63, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x7d, 0x12, 0x01, 0x2a, 0x42, 0x0b, 0x0a, 0x09, 0x63, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x1a, 0x3d, 0x0a, 0x0f, 0x55, 0x73, 0x65, 0x72, 0x4c, 0x61, 0x62, 0x65, 0x6c, 0x73, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a, 0x02, 0x38, 0x01, 0x22, 0x61, 0x0a, 0x15, 0x43, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x43, 0x6f, 0x6d, 0x62, 0x69, 0x6e, 0x65, 0x72, 0x54, 0x79, 0x70, 0x65, 0x12, 0x17, 0x0a, 0x13, 0x43, 0x4f, 0x4d, 0x42, 0x49, 0x4e, 0x45, 0x5f, 0x55, 0x4e, 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x07, 0x0a, 0x03, 0x41, 0x4e, 0x44, 0x10, 0x01, 0x12, 0x06, 0x0a, 0x02, 0x4f, 0x52, 0x10, 0x02, 0x12, 0x1e, 0x0a, 0x1a, 0x41, 0x4e, 0x44, 0x5f, 0x57, 0x49, 0x54, 0x48, 0x5f, 0x4d, 0x41, 0x54, 0x43, 0x48, 0x49, 0x4e, 0x47, 0x5f, 0x52, 0x45, 0x53, 0x4f, 0x55, 0x52, 0x43, 0x45, 0x10, 0x03, 0x3a, 0xc9, 0x01, 0xea, 0x41, 0xc5, 0x01, 0x0a, 0x25, 0x6d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x41, 0x6c, 0x65, 0x72, 0x74, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x12, 0x2f, 0x70, 0x72, 0x6f, 0x6a, 0x65, 0x63, 0x74, 0x73, 0x2f, 0x7b, 0x70, 0x72, 0x6f, 0x6a, 0x65, 0x63, 0x74, 0x7d, 0x2f, 0x61, 0x6c, 0x65, 0x72, 0x74, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x69, 0x65, 0x73, 0x2f, 0x7b, 0x61, 0x6c, 0x65, 0x72, 0x74, 0x5f, 0x70, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x7d, 0x12, 0x39, 0x6f, 0x72, 0x67, 0x61, 0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x7b, 0x6f, 0x72, 0x67, 0x61, 0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x7d, 0x2f, 0x61, 0x6c, 0x65, 0x72, 0x74, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x69, 0x65, 0x73, 0x2f, 0x7b, 0x61, 0x6c, 0x65, 0x72, 0x74, 0x5f, 0x70, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x7d, 0x12, 0x2d, 0x66, 0x6f, 0x6c, 0x64, 0x65, 0x72, 0x73, 0x2f, 0x7b, 0x66, 0x6f, 0x6c, 0x64, 0x65, 0x72, 0x7d, 0x2f, 0x61, 0x6c, 0x65, 0x72, 0x74, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x69, 0x65, 0x73, 0x2f, 0x7b, 0x61, 0x6c, 0x65, 0x72, 0x74, 0x5f, 0x70, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x7d, 0x12, 0x01, 0x2a, 0x42, 0xc2, 0x01, 0x0a, 0x18, 0x63, 0x6f, 0x6d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x6d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x2e, 0x76, 0x33, 0x42, 0x0a, 0x41, 0x6c, 0x65, 0x72, 0x74, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x3e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x67, 0x65, 0x6e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2f, 0x6d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x2f, 0x76, 0x33, 0x3b, 0x6d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0xaa, 0x02, 0x1a, 0x47, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x43, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x4d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x2e, 0x56, 0x33, 0xca, 0x02, 0x1a, 0x47, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x5c, 0x43, 0x6c, 0x6f, 0x75, 0x64, 0x5c, 0x4d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x5c, 0x56, 0x33, 0xea, 0x02, 0x1d, 0x47, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x3a, 0x3a, 0x43, 0x6c, 0x6f, 0x75, 0x64, 0x3a, 0x3a, 0x4d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x3a, 0x3a, 0x56, 0x33, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_google_monitoring_v3_alert_proto_rawDescOnce sync.Once file_google_monitoring_v3_alert_proto_rawDescData = file_google_monitoring_v3_alert_proto_rawDesc ) func file_google_monitoring_v3_alert_proto_rawDescGZIP() []byte { file_google_monitoring_v3_alert_proto_rawDescOnce.Do(func() { file_google_monitoring_v3_alert_proto_rawDescData = protoimpl.X.CompressGZIP(file_google_monitoring_v3_alert_proto_rawDescData) }) return file_google_monitoring_v3_alert_proto_rawDescData } var file_google_monitoring_v3_alert_proto_enumTypes = make([]protoimpl.EnumInfo, 1) var file_google_monitoring_v3_alert_proto_msgTypes = make([]protoimpl.MessageInfo, 7) var file_google_monitoring_v3_alert_proto_goTypes = []interface{}{ (AlertPolicy_ConditionCombinerType)(0), // 0: google.monitoring.v3.AlertPolicy.ConditionCombinerType (*AlertPolicy)(nil), // 1: google.monitoring.v3.AlertPolicy (*AlertPolicy_Documentation)(nil), // 2: google.monitoring.v3.AlertPolicy.Documentation (*AlertPolicy_Condition)(nil), // 3: google.monitoring.v3.AlertPolicy.Condition nil, // 4: google.monitoring.v3.AlertPolicy.UserLabelsEntry (*AlertPolicy_Condition_Trigger)(nil), // 5: google.monitoring.v3.AlertPolicy.Condition.Trigger (*AlertPolicy_Condition_MetricThreshold)(nil), // 6: google.monitoring.v3.AlertPolicy.Condition.MetricThreshold (*AlertPolicy_Condition_MetricAbsence)(nil), // 7: google.monitoring.v3.AlertPolicy.Condition.MetricAbsence (*wrappers.BoolValue)(nil), // 8: google.protobuf.BoolValue (*status.Status)(nil), // 9: google.rpc.Status (*MutationRecord)(nil), // 10: google.monitoring.v3.MutationRecord (*Aggregation)(nil), // 11: google.monitoring.v3.Aggregation (ComparisonType)(0), // 12: google.monitoring.v3.ComparisonType (*duration.Duration)(nil), // 13: google.protobuf.Duration } var file_google_monitoring_v3_alert_proto_depIdxs = []int32{ 2, // 0: google.monitoring.v3.AlertPolicy.documentation:type_name -> google.monitoring.v3.AlertPolicy.Documentation 4, // 1: google.monitoring.v3.AlertPolicy.user_labels:type_name -> google.monitoring.v3.AlertPolicy.UserLabelsEntry 3, // 2: google.monitoring.v3.AlertPolicy.conditions:type_name -> google.monitoring.v3.AlertPolicy.Condition 0, // 3: google.monitoring.v3.AlertPolicy.combiner:type_name -> google.monitoring.v3.AlertPolicy.ConditionCombinerType 8, // 4: google.monitoring.v3.AlertPolicy.enabled:type_name -> google.protobuf.BoolValue 9, // 5: google.monitoring.v3.AlertPolicy.validity:type_name -> google.rpc.Status 10, // 6: google.monitoring.v3.AlertPolicy.creation_record:type_name -> google.monitoring.v3.MutationRecord 10, // 7: google.monitoring.v3.AlertPolicy.mutation_record:type_name -> google.monitoring.v3.MutationRecord 6, // 8: google.monitoring.v3.AlertPolicy.Condition.condition_threshold:type_name -> google.monitoring.v3.AlertPolicy.Condition.MetricThreshold 7, // 9: google.monitoring.v3.AlertPolicy.Condition.condition_absent:type_name -> google.monitoring.v3.AlertPolicy.Condition.MetricAbsence 11, // 10: google.monitoring.v3.AlertPolicy.Condition.MetricThreshold.aggregations:type_name -> google.monitoring.v3.Aggregation 11, // 11: google.monitoring.v3.AlertPolicy.Condition.MetricThreshold.denominator_aggregations:type_name -> google.monitoring.v3.Aggregation 12, // 12: google.monitoring.v3.AlertPolicy.Condition.MetricThreshold.comparison:type_name -> google.monitoring.v3.ComparisonType 13, // 13: google.monitoring.v3.AlertPolicy.Condition.MetricThreshold.duration:type_name -> google.protobuf.Duration 5, // 14: google.monitoring.v3.AlertPolicy.Condition.MetricThreshold.trigger:type_name -> google.monitoring.v3.AlertPolicy.Condition.Trigger 11, // 15: google.monitoring.v3.AlertPolicy.Condition.MetricAbsence.aggregations:type_name -> google.monitoring.v3.Aggregation 13, // 16: google.monitoring.v3.AlertPolicy.Condition.MetricAbsence.duration:type_name -> google.protobuf.Duration 5, // 17: google.monitoring.v3.AlertPolicy.Condition.MetricAbsence.trigger:type_name -> google.monitoring.v3.AlertPolicy.Condition.Trigger 18, // [18:18] is the sub-list for method output_type 18, // [18:18] is the sub-list for method input_type 18, // [18:18] is the sub-list for extension type_name 18, // [18:18] is the sub-list for extension extendee 0, // [0:18] is the sub-list for field type_name } func init() { file_google_monitoring_v3_alert_proto_init() } func file_google_monitoring_v3_alert_proto_init() { if File_google_monitoring_v3_alert_proto != nil { return } file_google_monitoring_v3_common_proto_init() file_google_monitoring_v3_mutation_record_proto_init() if !protoimpl.UnsafeEnabled { file_google_monitoring_v3_alert_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*AlertPolicy); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_google_monitoring_v3_alert_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*AlertPolicy_Documentation); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_google_monitoring_v3_alert_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*AlertPolicy_Condition); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_google_monitoring_v3_alert_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*AlertPolicy_Condition_Trigger); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_google_monitoring_v3_alert_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*AlertPolicy_Condition_MetricThreshold); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_google_monitoring_v3_alert_proto_msgTypes[6].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*AlertPolicy_Condition_MetricAbsence); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } file_google_monitoring_v3_alert_proto_msgTypes[2].OneofWrappers = []interface{}{ (*AlertPolicy_Condition_ConditionThreshold)(nil), (*AlertPolicy_Condition_ConditionAbsent)(nil), } file_google_monitoring_v3_alert_proto_msgTypes[4].OneofWrappers = []interface{}{ (*AlertPolicy_Condition_Trigger_Count)(nil), (*AlertPolicy_Condition_Trigger_Percent)(nil), } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_google_monitoring_v3_alert_proto_rawDesc, NumEnums: 1, NumMessages: 7, NumExtensions: 0, NumServices: 0, }, GoTypes: file_google_monitoring_v3_alert_proto_goTypes, DependencyIndexes: file_google_monitoring_v3_alert_proto_depIdxs, EnumInfos: file_google_monitoring_v3_alert_proto_enumTypes, MessageInfos: file_google_monitoring_v3_alert_proto_msgTypes, }.Build() File_google_monitoring_v3_alert_proto = out.File file_google_monitoring_v3_alert_proto_rawDesc = nil file_google_monitoring_v3_alert_proto_goTypes = nil file_google_monitoring_v3_alert_proto_depIdxs = nil }
mpl-2.0
selimekizoglu/gotry
gotry_test.go
1117
package gotry import ( "errors" "testing" "time" ) func TestTry_noError(t *testing.T) { r := Retry{} attempt := 0 err := Try(func() error { attempt++ return nil }, r) if err != nil { t.Fatal(err) } expected := 1 if attempt != expected { t.Errorf("expected attempt to be %d got %d", expected, attempt) } } func TestTry_error(t *testing.T) { r := Retry{Max: 1} attempt := 0 err := Try(func() error { attempt++ return errors.New("error") }, r) if err == nil { t.Error("expected error") } expected := 2 if attempt != expected { t.Errorf("expected attempt to be %d got %d", expected, attempt) } } func TestTry_timeout(t *testing.T) { r := Retry{Max: 1, Timeout: 2 * time.Millisecond} start := time.Now() attempt := 0 err := Try(func() error { attempt++ return errors.New("error") }, r) if err == nil { t.Error("expected error") } expected := 2 if attempt != expected { t.Errorf("expected attempt to be %d got %d", expected, attempt) } diff := time.Now().Sub(start) if diff < r.Timeout { t.Errorf("expected %s to be less than %s", r.Timeout, diff) } }
mpl-2.0
awest1339/multiscanner
utils/api.py
30509
#!/usr/bin/env python ''' THIS APP IS NOT PRODUCTION READY!! DO NOT USE! Flask app that provides a RESTful API to MultiScanner. Supported operations: GET / ---> Test functionality. {'Message': 'True'} GET /api/v1/files/<sha256>?raw={t|f} ----> download sample, defaults to passwd protected zip GET /api/v1/modules ---> Receive list of modules available GET /api/v1/tags ----> Receive list of all tags in use GET /api/v1/tasks ---> Receive list of tasks in MultiScanner POST /api/v1/tasks ---> POST file and receive report id Sample POST usage: curl -i -X POST http://localhost:8080/api/v1/tasks -F file=@/bin/ls GET /api/v1/tasks/<task_id> ---> receive task in JSON format DELETE /api/v1/tasks/<task_id> ----> delete task_id GET /api/v1/tasks/search/ ---> receive list of most recent report for matching samples GET /api/v1/tasks/search/history ---> receive list of most all reports for matching samples GET /api/v1/tasks/<task_id>/file?raw={t|f} ----> download sample, defaults to passwd protected zip GET /api/v1/tasks/<task_id>/maec ----> download the Cuckoo MAEC 5.0 report, if it exists GET /api/v1/tasks/<task_id>/notes ---> Receive list of this task's notes POST /api/v1/tasks/<task_id>/notes ---> Add a note to task PUT /api/v1/tasks/<task_id>/notes/<note_id> ---> Edit a note DELETE /api/v1/tasks/<task_id>/notes/<note_id> ---> Delete a note GET /api/v1/tasks/<task_id>/report?d={t|f}---> receive report in JSON, set d=t to download GET /api/v1/tasks/<task_id>/pdf ---> Receive PDF report POST /api/v1/tasks/<task_id>/tags ---> Add tags to task DELETE /api/v1/tasks/<task_id>/tags ---> Remove tags from task GET /api/v1/analytics/ssdeep_compare---> Run ssdeep.compare analytic GET /api/v1/analytics/ssdeep_group---> Receive list of sample hashes grouped by ssdeep hash The API endpoints all have Cross Origin Resource Sharing (CORS) enabled. By default it will allow requests from any port on localhost. Change this setting by modifying the 'cors' setting in the 'api' section of the api config file. TODO: * Add doc strings to functions ''' from __future__ import print_function import os import sys import time import hashlib import codecs import configparser import json import multiprocessing import subprocess import queue import shutil from datetime import datetime from flask_cors import CORS from flask import Flask, jsonify, make_response, request, abort from flask.json import JSONEncoder from jinja2 import Markup from six import PY3 import rarfile import zipfile import requests MS_WD = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) if os.path.join(MS_WD, 'storage') not in sys.path: sys.path.insert(0, os.path.join(MS_WD, 'storage')) if os.path.join(MS_WD, 'analytics') not in sys.path: sys.path.insert(0, os.path.join(MS_WD, 'analytics')) if os.path.join(MS_WD, 'libs') not in sys.path: sys.path.insert(0, os.path.join(MS_WD, 'libs')) if MS_WD not in sys.path: sys.path.insert(0, os.path.join(MS_WD)) import multiscanner import sql_driver as database import elasticsearch_storage import common from utils.pdf_generator import create_pdf_document TASK_NOT_FOUND = {'Message': 'No task or report with that ID found!'} INVALID_REQUEST = {'Message': 'Invalid request parameters'} HTTP_OK = 200 HTTP_CREATED = 201 HTTP_BAD_REQUEST = 400 HTTP_NOT_FOUND = 404 DEFAULTCONF = { 'host': 'localhost', 'port': 8080, 'upload_folder': '/mnt/samples/', 'distributed': True, 'web_loc': 'http://localhost:80', 'cors': 'https?://localhost(:\d+)?', 'batch_size': 100, 'batch_interval': 60 # Number of seconds to wait for additional files # submitted to the create/ API } # Customize timestamp format output of jsonify() class CustomJSONEncoder(JSONEncoder): def default(self, obj): if isinstance(obj, datetime): if obj.utcoffset() is not None: obj = obj - obj.utcoffset() return str(obj) else: return JSONEncoder.default(self, obj) app = Flask(__name__) app.json_encoder = CustomJSONEncoder api_config_object = configparser.SafeConfigParser() api_config_object.optionxform = str api_config_file = multiscanner.common.get_config_path(multiscanner.CONFIG, 'api') api_config_object.read(api_config_file) if not api_config_object.has_section('api') or not os.path.isfile(api_config_file): # Write default config api_config_object.add_section('api') for key in DEFAULTCONF: api_config_object.set('api', key, str(DEFAULTCONF[key])) conffile = codecs.open(api_config_file, 'w', 'utf-8') api_config_object.write(conffile) conffile.close() api_config = multiscanner.common.parse_config(api_config_object) # Needs api_config in order to function properly from celery_worker import multiscanner_celery, ssdeep_compare_celery from ssdeep_analytics import SSDeepAnalytic db = database.Database(config=api_config.get('Database')) # To run under Apache, we need to set up the DB outside of __main__ db.init_db() storage_conf = multiscanner.common.get_config_path(multiscanner.CONFIG, 'storage') storage_handler = multiscanner.storage.StorageHandler(configfile=storage_conf) for handler in storage_handler.loaded_storage: if isinstance(handler, elasticsearch_storage.ElasticSearchStorage): break ms_config_object = configparser.SafeConfigParser() ms_config_object.optionxform = str ms_configfile = multiscanner.CONFIG ms_config_object.read(ms_configfile) ms_config = common.parse_config(ms_config_object) try: DISTRIBUTED = api_config['api']['distributed'] except KeyError: DISTRIBUTED = False if not DISTRIBUTED: work_queue = multiprocessing.Queue() try: cors_origins = api_config['api']['cors'] except KeyError: cors_origins = DEFAULTCONF['cors'] CORS(app, origins=cors_origins) batch_size = api_config['api']['batch_size'] batch_interval = api_config['api']['batch_interval'] # Add `delete_after_scan = True` to api_config.ini to delete samples after scan has completed delete_after_scan = api_config['api'].get('delete_after_scan', False) def multiscanner_process(work_queue, exit_signal): '''Not used in distributed mode. ''' metadata_list = [] time_stamp = None while True: time.sleep(1) try: metadata_list.append(work_queue.get_nowait()) if not time_stamp: time_stamp = time.time() while len(metadata_list) < batch_size: metadata_list.append(work_queue.get_nowait()) except queue.Empty: if metadata_list and time_stamp: if len(metadata_list) >= batch_size: pass elif time.time() - time_stamp > batch_interval: pass else: continue else: continue filelist = [item[0] for item in metadata_list] #modulelist = [item[5] for item in metadata_list] resultlist = multiscanner.multiscan( filelist, configfile=multiscanner.CONFIG #module_list ) results = multiscanner.parse_reports(resultlist, python=True) scan_time = datetime.now().isoformat() if delete_after_scan: for file_name in results: os.remove(file_name) for item in metadata_list: # Use the original filename as the index instead of the full path results[item[1]] = results[item[0]] del results[item[0]] results[item[1]]['Scan Time'] = scan_time results[item[1]]['Metadata'] = item[4] db.update_task( task_id=item[2], task_status='Complete', timestamp=scan_time, ) metadata_list = [] storage_handler.store(results, wait=False) filelist = [] time_stamp = None storage_handler.close() @app.errorhandler(HTTP_BAD_REQUEST) def invalid_request(error): '''Return a 400 with the INVALID_REQUEST message.''' return make_response(jsonify(INVALID_REQUEST), HTTP_BAD_REQUEST) @app.errorhandler(HTTP_NOT_FOUND) def not_found(error): '''Return a 404 with a TASK_NOT_FOUND message.''' return make_response(jsonify(TASK_NOT_FOUND), HTTP_NOT_FOUND) @app.route('/') def index(): ''' Return a default standard message for testing connectivity. ''' return jsonify({'Message': 'True'}) @app.route('/api/v1/modules', methods=['GET']) def modules(): ''' Return a list of module names available for MultiScanner to use, and whether or not they are enabled in the config. ''' files = multiscanner.parseDir(multiscanner.MODULEDIR, True) filenames = [os.path.splitext(os.path.basename(f)) for f in files] module_names = [m[0] for m in filenames if m[1] == '.py'] ms_config = configparser.SafeConfigParser() ms_config.optionxform = str ms_config.read(multiscanner.CONFIG) modules = {} for module in module_names: try: modules[module] = ms_config.get(module, 'ENABLED') except (configparser.NoSectionError, configparser.NoOptionError): pass return jsonify({'Modules': modules}) @app.route('/api/v1/tasks', methods=['GET']) def task_list(): ''' Return a JSON dictionary containing all the tasks in the tasks DB. ''' return jsonify({'Tasks': db.get_all_tasks()}) def search(params, get_all=False): # Pass search term to Elasticsearch, get back list of sample_ids sample_id = params.get('sha256') if sample_id: task_id = db.exists(sample_id) if task_id: return { 'TaskID' : task_id } else: return TASK_NOT_FOUND search_term = params.get('search[value]') search_type = params.pop('search_type', 'default') if not search_term: es_result = None else: es_result = handler.search(search_term, search_type) # Search the task db for the ids we got from Elasticsearch if get_all: return db.search(params, es_result, return_all=True) else: return db.search(params, es_result) @app.route('/api/v1/tasks/search/history', methods=['GET']) def task_search_history(): ''' Handle query between jQuery Datatables, the task DB, and Elasticsearch. Return all reports for matching samples. ''' params = request.args.to_dict() resp = search(params, get_all=True) return jsonify(resp) @app.route('/api/v1/tasks/search', methods=['GET']) def task_search(): ''' Handle query between jQuery Datatables, the task DB, and Elasticsearch. Return only the most recent report for each of the matching samples. ''' params = request.args.to_dict() resp = search(params) return jsonify(resp) @app.route('/api/v1/tasks/<int:task_id>', methods=['GET']) def get_task(task_id): ''' Return a JSON dictionary corresponding to the given task ID. ''' task = db.get_task(task_id) if task: return jsonify({'Task': task.to_dict()}) else: abort(HTTP_NOT_FOUND) @app.route('/api/v1/tasks/<int:task_id>', methods=['DELETE']) def delete_task(task_id): ''' Delete the specified task. Return deleted message. ''' result = db.delete_task(task_id) if not result: abort(HTTP_NOT_FOUND) return jsonify({'Message': 'Deleted'}) def save_hashed_filename(f, zipped=False): ''' Save given file to the upload folder, with its SHA256 hash as its filename. ''' f_name = hashlib.sha256(f.read()).hexdigest() # Reset the file pointer to the beginning to allow us to save it f.seek(0) # TODO: should we check if the file is already there # and skip this step if it is? file_path = os.path.join(api_config['api']['upload_folder'], f_name) full_path = os.path.join(MS_WD, file_path) if zipped: shutil.copy2(f.name, full_path) else: f.save(file_path) return (f_name, full_path) class InvalidScanTimeFormatError(ValueError): pass def import_task(file_): ''' Import a JSON report that was downloaded from MultiScanner. ''' report = json.loads(file_.read().decode('utf-8')) try: report['Scan Time'] = datetime.strptime(report['Scan Time'], '%Y-%m-%dT%H:%M:%S.%f') except ValueError: raise InvalidScanTimeFormatError() task_id = db.add_task( sample_id=report['SHA256'], task_status='Complete', timestamp=report['Scan Time'], ) storage_handler.store({report['filename']: report}, wait=False) return task_id def queue_task(original_filename, f_name, full_path, metadata, rescan=False): ''' Queue up a single new task, for a single non-archive file. ''' # If option set, or no scan exists for this sample, skip and scan sample again # Otherwise, pull latest scan for this sample if (not rescan): t_exists = db.exists(f_name) if t_exists: return t_exists # Add task to sqlite DB # Make the sample_id equal the sha256 hash task_id = db.add_task(sample_id=f_name) if DISTRIBUTED: # Publish the task to Celery multiscanner_celery.delay(full_path, original_filename, task_id, f_name, metadata, config=multiscanner.CONFIG) else: # Put the task on the queue work_queue.put((full_path, original_filename, task_id, f_name, metadata)) return task_id @app.route('/api/v1/tasks', methods=['POST']) def create_task(): ''' Create a new task for a submitted file. Save the submitted file to UPLOAD_FOLDER, optionally unzipping it. Return task id and 201 status. ''' file_ = request.files['file'] if request.form.get('upload_type', None) == 'import': try: task_id = import_task(file_) except KeyError: return make_response( jsonify({'Message': 'Cannot import report missing \'Scan Time\' field!'}), HTTP_BAD_REQUEST) except InvalidScanTimeFormatError: return make_response( jsonify({'Message': 'Cannot import report with \'Scan Time\' of invalid format!'}), HTTP_BAD_REQUEST) except (UnicodeDecodeError, ValueError): return make_response( jsonify({'Message': 'Cannot import non-JSON files!'}), HTTP_BAD_REQUEST) return make_response( jsonify({'Message': {'task_ids': [task_id]}}), HTTP_CREATED ) original_filename = file_.filename metadata = {} task_id_list = [] extract_dir = None rescan = False for key in request.form.keys(): if key in ['file_id', 'archive-password', 'upload_type'] or request.form[key] == '': continue elif key == 'duplicate': if request.form[key] == 'latest': rescan = False elif request.form[key] == 'rescan': rescan = True elif key == 'modules': module_names = request.form[key] files = multiscanner.parseDir(multiscanner.MODULEDIR, True) modules = [] for f in files: split = os.path.splitext(os.path.basename(f)) if split[0] in module_names and split[1] == '.py': modules.append(f) elif key == 'archive-analyze' and request.form[key] == 'true': extract_dir = api_config['api']['upload_folder'] if not os.path.isdir(extract_dir): return make_response( jsonify({'Message': "'upload_folder' in API config is not " "a valid folder!"}), HTTP_BAD_REQUEST) # Get password if present if 'archive-password' in request.form: password = request.form['archive-password'] if PY3: password = bytes(password, 'utf-8') else: password = '' else: metadata[key] = request.form[key] if extract_dir: # Extract a zip if zipfile.is_zipfile(file_): z = zipfile.ZipFile(file_) try: # NOTE: zipfile module prior to Py 2.7.4 is insecure! # https://docs.python.org/2/library/zipfile.html#zipfile.ZipFile.extract z.extractall(path=extract_dir, pwd=password) for uzfile in z.namelist(): unzipped_file = open(os.path.join(extract_dir, uzfile)) f_name, full_path = save_hashed_filename(unzipped_file, True) tid = queue_task(uzfile, f_name, full_path, metadata, rescan=rescan) task_id_list.append(tid) except RuntimeError as e: msg = "ERROR: Failed to extract " + str(file_) + ' - ' + str(e) return make_response( jsonify({'Message': msg}), HTTP_BAD_REQUEST) # Extract a rar elif rarfile.is_rarfile(file_): r = rarfile.RarFile(file_) try: r.extractall(path=extract_dir, pwd=password) for urfile in r.namelist(): unrarred_file = open(os.path.join(extract_dir, urfile)) f_name, full_path = save_hashed_filename(unrarred_file, True) tid = queue_task(urfile, f_name, full_path, metadata, rescan=rescan) task_id_list.append(tid) except RuntimeError as e: msg = "ERROR: Failed to extract " + str(file_) + ' - ' + str(e) return make_response( jsonify({'Message': msg}), HTTP_BAD_REQUEST) else: # File was not an archive to extract f_name, full_path = save_hashed_filename(file_) tid = queue_task(original_filename, f_name, full_path, metadata, rescan=rescan) task_id_list = [tid] msg = {'task_ids': task_id_list} return make_response( jsonify({'Message': msg}), HTTP_CREATED ) @app.route('/api/v1/tasks/<task_id>/report', methods=['GET']) def get_report(task_id): ''' Return a JSON dictionary corresponding to the given task ID. ''' download = request.args.get('d', default='False', type=str)[0].lower() report_dict, success = get_report_dict(task_id) if success: if (download == 't' or download == 'y' or download == '1'): # raw JSON response = make_response(jsonify(report_dict)) response.headers['Content-Type'] = 'application/json' response.headers['Content-Disposition'] = 'attachment; filename=%s.json' % task_id return response else: # processed JSON intended for web UI report_dict = _pre_process(report_dict) return jsonify(report_dict) else: return jsonify(report_dict) def _pre_process(report_dict={}): ''' Returns a JSON dictionary where a series of pre-processing steps are executed on report_dict. ''' # pop unecessary keys if report_dict.get('Report', {}).get('ssdeep', {}): for k in ['chunksize', 'chunk', 'double_chunk']: try: report_dict['Report']['ssdeep'].pop(k) except KeyError as e: pass report_dict = _add_links(report_dict) return report_dict def _add_links(report_dict): ''' Returns a JSON dictionary where certain keys and/or values are replaced with hyperlinks. ''' web_loc = api_config['api']['web_loc'] # ssdeep matches matches_dict = report_dict.get('Report', {}) \ .get('ssdeep', {}) \ .get('matches', {}) if matches_dict: links_dict = {} # k=SHA256, v=ssdeep.compare result for k, v in matches_dict.items(): t_id = db.exists(k) if t_id: url = '{h}/report/{t_id}'.format(h=web_loc, t_id=t_id) href = _linkify(k, url, True) links_dict[href] = v else: links_dict[k] = v # replace with updated dict report_dict['Report']['ssdeep']['matches'] = links_dict return report_dict #TODO: should we move these helper functions to separate file? def _linkify(s, url, new_tab=True): ''' Return string s as HTML a tag with href pointing to url. ''' return '<a{new_tab} href="{url}">{s}</a>'.format( new_tab=' target="_blank"' if new_tab else '', url=url, s=s) @app.route('/api/v1/tasks/<task_id>/file', methods=['GET']) def files_get_task(task_id): # try to get report dict report_dict, success = get_report_dict(task_id) if not success: return jsonify(report_dict) # okay, we have report dict; get sha256 sha256 = report_dict.get('Report', {}).get('SHA256') if sha256: return files_get_sha256_helper( sha256, request.args.get('raw', default=None)) else: return jsonify({'Error': 'sha256 not in report!'}) @app.route('/api/v1/tasks/<task_id>/maec', methods=['GET']) def get_maec_report(task_id): # try to get report dict report_dict, success = get_report_dict(task_id) if not success: return jsonify(report_dict) # okay, we have report dict; get cuckoo task ID try: cuckoo_task_id = report_dict['Report']['Cuckoo Sandbox']['info']['id'] except KeyError: return jsonify({'Error': 'No MAEC report found for that task!'}) # Get the MAEC report from Cuckoo try: maec_report = requests.get( '{}/v1/tasks/report/{}/maec'.format(ms_config.get('Cuckoo', {}).get('API URL', ''), cuckoo_task_id) ) except: return jsonify({'Error': 'No MAEC report found for that task!'}) # raw JSON response = make_response(jsonify(maec_report.json())) response.headers['Content-Type'] = 'application/json' response.headers['Content-Disposition'] = 'attachment; filename=%s.json' % task_id return response def get_report_dict(task_id): task = db.get_task(task_id) if not task: abort(HTTP_NOT_FOUND) if task.task_status == 'Complete': return {'Report': handler.get_report(task.sample_id, task.timestamp)}, True elif task.task_status == 'Pending': return {'Report': 'Task still pending'}, False else: return {'Report': 'Task failed'}, False @app.route('/api/v1/tasks/<task_id>', methods=['DELETE']) def delete_report(task_id): ''' Delete the specified task. Return deleted message. ''' task = db.get_task(task_id) if not task: abort(HTTP_NOT_FOUND) if handler.delete(task.report_id): return jsonify({'Message': 'Deleted'}) else: abort(HTTP_NOT_FOUND) @app.route('/api/v1/tags/', methods=['GET']) def taglist(): ''' Return a list of all tags currently in use. ''' response = handler.get_tags() return jsonify({'Tags': response}) @app.route('/api/v1/tasks/<task_id>/tags', methods=['POST', 'DELETE']) def tags(task_id): ''' Add/Remove the specified tag to the specified task. ''' task = db.get_task(task_id) if not task: abort(HTTP_NOT_FOUND) tag = request.values.get('tag', '') if request.method == 'POST': response = handler.add_tag(task.sample_id, tag) if not response: abort(HTTP_BAD_REQUEST) return jsonify({'Message': 'Tag Added'}) elif request.method == 'DELETE': response = handler.remove_tag(task.sample_id, tag) if not response: abort(HTTP_BAD_REQUEST) return jsonify({'Message': 'Tag Removed'}) @app.route('/api/v1/tasks/<task_id>/notes', methods=['GET']) def get_notes(task_id): ''' Get one or more analyst notes/comments associated with the specified task. ''' task = db.get_task(task_id) if not task: abort(HTTP_NOT_FOUND) if ('ts' in request.args and 'uid' in request.args): ts = request.args.get('ts', '') uid = request.args.get('uid', '') response = handler.get_notes(task.sample_id, [ts, uid]) else: response = handler.get_notes(task.sample_id) if not response: abort(HTTP_BAD_REQUEST) if 'hits' in response and 'hits' in response['hits']: response = response['hits']['hits'] try: for hit in response: hit['_source']['text'] = Markup.escape(hit['_source']['text']) except: pass return jsonify(response) @app.route('/api/v1/tasks/<task_id>/notes', methods=['POST']) def add_note(task_id): ''' Add an analyst note/comment to the specified task. ''' task = db.get_task(task_id) if not task: abort(HTTP_NOT_FOUND) response = handler.add_note(task.sample_id, request.form.to_dict()) if not response: abort(HTTP_BAD_REQUEST) return jsonify(response) @app.route('/api/v1/tasks/<task_id>/notes/<note_id>', methods=['PUT', 'DELETE']) def edit_note(task_id, note_id): ''' Modify/remove the specified analyst note/comment. ''' task = db.get_task(task_id) if not task: abort(HTTP_NOT_FOUND) if request.method == 'PUT': response = handler.edit_note(task.sample_id, note_id, Markup(request.form.get('text', '')).striptags()) elif request.method == 'DELETE': response = handler.delete_note(task.sample_id, note_id) if not response: abort(HTTP_BAD_REQUEST) return jsonify(response) @app.route('/api/v1/files/<sha256>', methods=['GET']) # get raw file - /api/v1/files/get/<sha256>?raw=true def files_get_sha256(sha256): ''' Returns binary from storage. Defaults to password protected zipfile. ''' # is there a robust way to just get this as a bool? raw = request.args.get('raw', default='False', type=str) return files_get_sha256_helper(sha256, raw) def files_get_sha256_helper(sha256, raw=None): ''' Returns binary from storage. Defaults to password protected zipfile. ''' file_path = os.path.join(api_config['api']['upload_folder'], sha256) if not os.path.exists(file_path): abort(HTTP_NOT_FOUND) with open(file_path, "rb") as fh: fh_content = fh.read() raw = raw[0].lower() if raw == 't' or raw == 'y' or raw == '1': response = make_response(fh_content) response.headers['Content-Type'] = 'application/octet-stream; charset=UTF-8' response.headers['Content-Disposition'] = 'inline; filename={}.bin'.format(sha256) # better way to include fname? else: # ref: https://github.com/crits/crits/crits/core/data_tools.py#L122 rawname = sha256 + '.bin' with open(os.path.join('/tmp/', rawname), 'wb') as raw_fh: raw_fh.write(fh_content) zipname = sha256 + '.zip' args = ['/usr/bin/zip', '-j', os.path.join('/tmp', zipname), os.path.join('/tmp', rawname), '-P', 'infected'] proc = subprocess.Popen(args) wait_seconds = 30 while proc.poll() is None and wait_seconds: time.sleep(1) wait_seconds -= 1 if proc.returncode: return make_response(jsonify({'Error': 'Failed to create zip ()'.format(proc.returncode)})) elif not wait_seconds: proc.terminate() return make_response(jsonify({'Error': 'Process timed out'})) else: with open(os.path.join('/tmp', zipname), 'rb') as zip_fh: zip_data = zip_fh.read() if len(zip_data) == 0: return make_response(jsonify({'Error': 'Zip file empty'})) response = make_response(zip_data) response.headers['Content-Type'] = 'application/zip; charset=UTF-8' response.headers['Content-Disposition'] = 'inline; filename={}.zip'.format(sha256) return response @app.route('/api/v1/analytics/ssdeep_compare', methods=['GET']) def run_ssdeep_compare(): ''' Runs ssdeep compare analytic and returns success / error message. ''' try: if DISTRIBUTED: # Publish task to Celery ssdeep_compare_celery.delay() return make_response(jsonify({ 'Message': 'Success' })) else: ssdeep_analytic = SSDeepAnalytic() ssdeep_analytic.ssdeep_compare() return make_response(jsonify({ 'Message': 'Success' })) except Exception as e: return make_response( jsonify({'Message': 'Unable to complete request.'}), HTTP_BAD_REQUEST) @app.route('/api/v1/analytics/ssdeep_group', methods=['GET']) def run_ssdeep_group(): ''' Runs ssdeep group analytic and returns list of groups as a list. ''' try: ssdeep_analytic = SSDeepAnalytic() groups = ssdeep_analytic.ssdeep_group() return make_response(jsonify({ 'groups': groups })) except Exception as e: return make_response( jsonify({'Message': 'Unable to complete request.'}), HTTP_BAD_REQUEST) @app.route('/api/v1/tasks/<task_id>/pdf', methods=['GET']) def get_pdf_report(task_id): ''' Generates a PDF version of a JSON report. ''' report_dict, success = get_report_dict(task_id) if not success: return jsonify(report_dict) pdf = create_pdf_document(MS_WD, report_dict) response = make_response(pdf) response.headers['Content-Type'] = 'application/pdf' response.headers['Content-Disposition'] = 'attachment; filename=%s.pdf' % task_id return response if __name__ == '__main__': if not os.path.isdir(api_config['api']['upload_folder']): print('Creating upload dir') os.makedirs(api_config['api']['upload_folder']) if not DISTRIBUTED: exit_signal = multiprocessing.Value('b') exit_signal.value = False ms_process = multiprocessing.Process( target=multiscanner_process, args=(work_queue, exit_signal) ) ms_process.start() app.run(host=api_config['api']['host'], port=api_config['api']['port']) if not DISTRIBUTED: ms_process.join()
mpl-2.0
seedstack/w20-business-theme
modules/main.js
11739
/* * Copyright (c) 2013-2016, The SeedStack authors <http://seedstack.org> * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ define([ 'require', 'module', 'jquery', '{lodash}/lodash', '{angular}/angular', '[text]!{w20-business-theme}/templates/topbar.html', '[text]!{w20-business-theme}/templates/sidebar.html', '{angular-sanitize}/angular-sanitize', '{w20-core}/modules/ui', '{w20-core}/modules/notifications', '{w20-core}/modules/culture', '{w20-core}/modules/utils' ], function (require, module, $, _, angular, topbarTemplate, sidebarTemplate) { 'use strict'; var w20BusinessTheme = angular.module('w20BusinessTheme', ['w20CoreCulture', 'w20CoreUtils', 'w20CoreUI', 'w20CoreNotifications', 'ngSanitize']), _config = module && module.config() || {}, showTopbar = true, showSidebar = _config.sidebar && typeof _config.sidebar.show === 'boolean' ? _config.show : true, includes = _.contains || _.includes; w20BusinessTheme.directive('w20Topbar', ['ApplicationService', 'EventService', 'EnvironmentService', 'DisplayService', 'MenuService', 'NavigationService', function (applicationService, eventService, environmentService, displayService, menuService, navigationService) { return { template: topbarTemplate, replace: true, restrict: 'A', scope: true, link: function (scope, iElement, iAttrs) { scope.navActions = menuService.getActions; scope.navAction = menuService.getAction; scope.envtype = environmentService.environment; scope.buildLink = navigationService.buildLink; scope.title = iAttrs.title || '\'' + applicationService.applicationId + '\''; scope.description = iAttrs.subtitle || ''; scope.logo = _config.logo; scope.brandFixedWidth = true; if (_config.brand) { scope.brandFixedWidth = _config.brand.fixedWidth === false ? _config.brand.fixedWidth : true; scope.brandBackgroundColor = _config.brand.backgroundColor ? _config.brand.backgroundColor : undefined; scope.brandTextColor = _config.brand.textColor ? _config.brand.textColor : undefined; } scope.showTopbar = function () { return showTopbar; }; scope.toggleSidebar = function () { eventService.emit('SidebarToggleEvent'); }; displayService.registerContentShiftCallback(function () { return [showTopbar ? 50 : 0, 0, 0, 0]; }); } }; }]); w20BusinessTheme.directive('w20Sidebar', ['EventService', 'DisplayService', 'NavigationService', 'MenuService', '$location', '$window', function (eventService, displayService, navigationService, menuService, $location, $window) { return { template: sidebarTemplate, replace: true, restrict: 'A', scope: true, link: function (scope) { var previousSidebarState = showSidebar; if (_config.sidebar) { scope.sideBarWidth = _config.sidebar.width ? _config.sidebar.width : undefined; } scope.menuSections = menuService.getSections; scope.menuActiveSectionName = scope.menuSections()[0]; scope.showSidebar = function () { return showSidebar; }; scope.menuSection = function (name) { return name ? menuService.getSection(name) : null; }; eventService.on('SidebarToggleEvent', function () { showSidebar = !showSidebar; previousSidebarState = showSidebar; displayService.computeContentShift(); }); displayService.registerContentShiftCallback(function () { return [10, 0, 0, showSidebar ? (scope.sideBarWidth || 270) : 0]; }); angular.element($window).bind('resize', function () { showSidebar = $(window).width() < 768 ? false : previousSidebarState; scope.$apply(); displayService.computeContentShift(); }); } }; }]); w20BusinessTheme.filter('routeFilter', ['CultureService', 'SecurityExpressionService', function (cultureService, securityExpressionService) { function isRouteVisible(route) { return !route.hidden && (typeof route.security === 'undefined' || securityExpressionService.evaluate(route.security)); } return function (routes, expected) { if (!expected) { return; } return _.filter(routes, function (route) { if (isRouteVisible(route) && cultureService.displayName(route).toLowerCase().indexOf(expected.toLowerCase()) !== -1) { return route; } }); }; }]); w20BusinessTheme.controller('W20btViewsController', ['$scope', 'NavigationService', 'CultureService', '$route', '$location', function ($scope, navigationService, cultureService, $route, $location) { var openedCategories = navigationService.expandedRouteCategories(); function recursiveOpen(tree) { openedCategories.push(tree.categoryName); for (var key in tree) { if (tree.hasOwnProperty(key)) { var subTree = tree[key]; if (subTree instanceof Array) { recursiveOpen(subTree); } } } } $scope.routes = $route.routes; $scope.filteredRoutes = []; $scope.menuTree = navigationService.routeTree; $scope.subMenuTree = navigationService.computeSubTree; $scope.topLevelCategories = navigationService.topLevelRouteCategories; $scope.topLevelRoutes = navigationService.topLevelRoutes; $scope.routesFromCategory = navigationService.routesFromCategory; $scope.displayName = cultureService.displayName; $scope.buildLink = navigationService.buildLink; if (_config.brand) { $scope.brandColor = _config.brand.backgroundColor ? _config.brand.backgroundColor : undefined; } $scope.activeRoutePath = function () { return $location.path(); }; $scope.localizeCategory = function (categoryName) { var lastPartIndex = categoryName.lastIndexOf('.'); if (lastPartIndex !== -1) { return cultureService.localize('application.viewcategory.' + categoryName, undefined, null) || cultureService.localize('application.viewcategory.' + categoryName.substring(lastPartIndex + 1)); } else { return cultureService.localize('application.viewcategory.' + categoryName); } }; $scope.toggleTree = function (tree) { if ($scope.isOpened(tree.categoryName)) { openedCategories.splice(openedCategories.indexOf(tree.categoryName), 1); } else { openedCategories.push(tree.categoryName); } }; $scope.isOpened = function (categoryName) { return includes(openedCategories, categoryName); }; $scope.routeSortKey = function (route) { return route.sortKey || route.path; }; }]); w20BusinessTheme.run(['$rootScope', 'EventService', 'DisplayService', 'MenuService', 'CultureService', function ($rootScope, eventService, displayService, menuService, cultureService) { $rootScope.$on('$routeChangeSuccess', function (event, routeInfo) { if (routeInfo && routeInfo.$$route) { switch (routeInfo.$$route.navigation) { case 'none': showSidebar = false; showTopbar = false; break; case 'sidebar': showSidebar = true; showTopbar = false; break; case 'topbar': showSidebar = false; showTopbar = true; break; case 'full': /* falls through */ default: break; } displayService.computeContentShift(); } }); if (!_config.hideSecurity) { if (!_config.profileChooser) { menuService.addAction('login', 'w20-login', { sortKey: 100 }); } else { menuService.addAction('profile', 'w20-profile', { sortKey: 100 }); } } if (!_config.hideConnectivity) { menuService.addAction('connectivity', 'w20-connectivity', { sortKey: 200 }); } if (!_config.hideCulture) { menuService.addAction('culture', 'w20-culture', { sortKey: 300 }); } _.each(_config.links, function (link, idx) { if (idx < 10) { menuService.addAction('link-' + idx, 'w20-link', _.extend(link, { sortKey: 400 + idx })); } }); if (!_config.hideSecurity && !_config.profileChooser) { menuService.addAction('logout', 'w20-logout', { sortKey: 1000 }); } menuService.addSection('views', 'w20-views', { templateUrl: '{w20-business-theme}/templates/sidebar-views.html' }); eventService.on('w20.security.authenticated', function () { displayService.computeContentShift(); }); eventService.on('w20.security.deauthenticated', function () { displayService.computeContentShift(); }); eventService.on('w20.security.refreshed', function () { displayService.computeContentShift(); }); }]); return { angularModules: ['w20BusinessTheme'], lifecycle: { pre: function (modules, fragments, callback) { angular.element('body').addClass('w20-top-shift-padding w20-right-shift-padding w20-bottom-shift-padding w20-left-shift-padding'); callback(module); } } }; });
mpl-2.0
kjmkznr/terraform-provider-aws
aws/data_source_aws_subnet_test.go
11340
package aws import ( "fmt" "testing" "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" "github.com/hashicorp/terraform-plugin-sdk/helper/resource" ) func TestAccDataSourceAwsSubnet_basic(t *testing.T) { rInt := acctest.RandIntRange(0, 256) cidr := fmt.Sprintf("172.%d.123.0/24", rInt) tag := "tf-acc-subnet-data-source" snResourceName := "aws_subnet.test" vpcResourceName := "aws_vpc.test" ds1ResourceName := "data.aws_subnet.by_id" ds2ResourceName := "data.aws_subnet.by_cidr" ds3ResourceName := "data.aws_subnet.by_tag" ds4ResourceName := "data.aws_subnet.by_vpc" ds5ResourceName := "data.aws_subnet.by_filter" ds6ResourceName := "data.aws_subnet.by_az_id" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckVpcDestroy, Steps: []resource.TestStep{ { Config: testAccDataSourceAwsSubnetConfig(rInt), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(ds1ResourceName, "id", snResourceName, "id"), resource.TestCheckResourceAttrPair(ds1ResourceName, "owner_id", snResourceName, "owner_id"), resource.TestCheckResourceAttrPair(ds1ResourceName, "availability_zone", snResourceName, "availability_zone"), resource.TestCheckResourceAttrPair(ds1ResourceName, "availability_zone_id", snResourceName, "availability_zone_id"), resource.TestCheckResourceAttrPair(ds1ResourceName, "vpc_id", vpcResourceName, "id"), resource.TestCheckResourceAttr(ds1ResourceName, "cidr_block", cidr), resource.TestCheckResourceAttr(ds1ResourceName, "tags.Name", tag), resource.TestCheckResourceAttrPair(ds1ResourceName, "arn", snResourceName, "arn"), resource.TestCheckResourceAttrPair(ds1ResourceName, "outpost_arn", snResourceName, "outpost_arn"), resource.TestCheckResourceAttrPair(ds2ResourceName, "id", snResourceName, "id"), resource.TestCheckResourceAttrPair(ds2ResourceName, "owner_id", snResourceName, "owner_id"), resource.TestCheckResourceAttrPair(ds2ResourceName, "availability_zone", snResourceName, "availability_zone"), resource.TestCheckResourceAttrPair(ds2ResourceName, "availability_zone_id", snResourceName, "availability_zone_id"), resource.TestCheckResourceAttrPair(ds2ResourceName, "vpc_id", vpcResourceName, "id"), resource.TestCheckResourceAttr(ds2ResourceName, "cidr_block", cidr), resource.TestCheckResourceAttr(ds2ResourceName, "tags.Name", tag), resource.TestCheckResourceAttrPair(ds2ResourceName, "arn", snResourceName, "arn"), resource.TestCheckResourceAttrPair(ds2ResourceName, "outpost_arn", snResourceName, "outpost_arn"), resource.TestCheckResourceAttrPair(ds3ResourceName, "id", snResourceName, "id"), resource.TestCheckResourceAttrPair(ds3ResourceName, "owner_id", snResourceName, "owner_id"), resource.TestCheckResourceAttrPair(ds3ResourceName, "availability_zone", snResourceName, "availability_zone"), resource.TestCheckResourceAttrPair(ds3ResourceName, "availability_zone_id", snResourceName, "availability_zone_id"), resource.TestCheckResourceAttrPair(ds3ResourceName, "vpc_id", vpcResourceName, "id"), resource.TestCheckResourceAttr(ds3ResourceName, "cidr_block", cidr), resource.TestCheckResourceAttr(ds3ResourceName, "tags.Name", tag), resource.TestCheckResourceAttrPair(ds3ResourceName, "arn", snResourceName, "arn"), resource.TestCheckResourceAttrPair(ds3ResourceName, "outpost_arn", snResourceName, "outpost_arn"), resource.TestCheckResourceAttrPair(ds4ResourceName, "id", snResourceName, "id"), resource.TestCheckResourceAttrPair(ds4ResourceName, "owner_id", snResourceName, "owner_id"), resource.TestCheckResourceAttrPair(ds4ResourceName, "availability_zone", snResourceName, "availability_zone"), resource.TestCheckResourceAttrPair(ds4ResourceName, "availability_zone_id", snResourceName, "availability_zone_id"), resource.TestCheckResourceAttrPair(ds4ResourceName, "vpc_id", vpcResourceName, "id"), resource.TestCheckResourceAttr(ds4ResourceName, "cidr_block", cidr), resource.TestCheckResourceAttr(ds4ResourceName, "tags.Name", tag), resource.TestCheckResourceAttrPair(ds4ResourceName, "arn", snResourceName, "arn"), resource.TestCheckResourceAttrPair(ds4ResourceName, "outpost_arn", snResourceName, "outpost_arn"), resource.TestCheckResourceAttrPair(ds5ResourceName, "id", snResourceName, "id"), resource.TestCheckResourceAttrPair(ds5ResourceName, "owner_id", snResourceName, "owner_id"), resource.TestCheckResourceAttrPair(ds5ResourceName, "availability_zone", snResourceName, "availability_zone"), resource.TestCheckResourceAttrPair(ds5ResourceName, "availability_zone_id", snResourceName, "availability_zone_id"), resource.TestCheckResourceAttrPair(ds5ResourceName, "vpc_id", vpcResourceName, "id"), resource.TestCheckResourceAttr(ds5ResourceName, "cidr_block", cidr), resource.TestCheckResourceAttr(ds5ResourceName, "tags.Name", tag), resource.TestCheckResourceAttrPair(ds5ResourceName, "arn", snResourceName, "arn"), resource.TestCheckResourceAttrPair(ds5ResourceName, "outpost_arn", snResourceName, "outpost_arn"), resource.TestCheckResourceAttrPair(ds6ResourceName, "id", snResourceName, "id"), resource.TestCheckResourceAttrPair(ds6ResourceName, "owner_id", snResourceName, "owner_id"), resource.TestCheckResourceAttrPair(ds6ResourceName, "availability_zone", snResourceName, "availability_zone"), resource.TestCheckResourceAttrPair(ds6ResourceName, "availability_zone_id", snResourceName, "availability_zone_id"), resource.TestCheckResourceAttrPair(ds6ResourceName, "vpc_id", vpcResourceName, "id"), resource.TestCheckResourceAttr(ds6ResourceName, "cidr_block", cidr), resource.TestCheckResourceAttr(ds6ResourceName, "tags.Name", tag), resource.TestCheckResourceAttrPair(ds6ResourceName, "arn", snResourceName, "arn"), resource.TestCheckResourceAttrPair(ds6ResourceName, "outpost_arn", snResourceName, "outpost_arn"), ), }, }, }) } func TestAccDataSourceAwsSubnet_ipv6ByIpv6Filter(t *testing.T) { rInt := acctest.RandIntRange(0, 256) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, Steps: []resource.TestStep{ { Config: testAccDataSourceAwsSubnetConfigIpv6(rInt), }, { Config: testAccDataSourceAwsSubnetConfigIpv6WithDataSourceFilter(rInt), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrSet("data.aws_subnet.by_ipv6_cidr", "ipv6_cidr_block_association_id"), resource.TestCheckResourceAttrSet("data.aws_subnet.by_ipv6_cidr", "ipv6_cidr_block"), ), }, }, }) } func TestAccDataSourceAwsSubnet_ipv6ByIpv6CidrBlock(t *testing.T) { rInt := acctest.RandIntRange(0, 256) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, Steps: []resource.TestStep{ { Config: testAccDataSourceAwsSubnetConfigIpv6(rInt), }, { Config: testAccDataSourceAwsSubnetConfigIpv6WithDataSourceIpv6CidrBlock(rInt), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrSet("data.aws_subnet.by_ipv6_cidr", "ipv6_cidr_block_association_id"), ), }, }, }) } func testAccDataSourceAwsSubnetConfig(rInt int) string { return fmt.Sprintf(` data "aws_availability_zones" "available" { state = "available" filter { name = "opt-in-status" values = ["opt-in-not-required"] } } resource "aws_vpc" "test" { cidr_block = "172.%d.0.0/16" tags = { Name = "terraform-testacc-subnet-data-source" } } resource "aws_subnet" "test" { vpc_id = "${aws_vpc.test.id}" cidr_block = "172.%d.123.0/24" availability_zone = "${data.aws_availability_zones.available.names[0]}" tags = { Name = "tf-acc-subnet-data-source" } } data "aws_subnet" "by_id" { id = "${aws_subnet.test.id}" } data "aws_subnet" "by_cidr" { vpc_id = "${aws_subnet.test.vpc_id}" cidr_block = "${aws_subnet.test.cidr_block}" } data "aws_subnet" "by_tag" { vpc_id = "${aws_subnet.test.vpc_id}" tags = { Name = "${aws_subnet.test.tags["Name"]}" } } data "aws_subnet" "by_vpc" { vpc_id = "${aws_subnet.test.vpc_id}" } data "aws_subnet" "by_filter" { filter { name = "vpc-id" values = ["${aws_subnet.test.vpc_id}"] } } data "aws_subnet" "by_az_id" { vpc_id = "${aws_subnet.test.vpc_id}" availability_zone_id = "${aws_subnet.test.availability_zone_id}" } `, rInt, rInt) } func testAccDataSourceAwsSubnetConfigIpv6(rInt int) string { return fmt.Sprintf(` data "aws_availability_zones" "available" { state = "available" filter { name = "opt-in-status" values = ["opt-in-not-required"] } } resource "aws_vpc" "test" { cidr_block = "172.%d.0.0/16" assign_generated_ipv6_cidr_block = true tags = { Name = "terraform-testacc-subnet-data-source-ipv6" } } resource "aws_subnet" "test" { vpc_id = "${aws_vpc.test.id}" cidr_block = "172.%d.123.0/24" availability_zone = "${data.aws_availability_zones.available.names[0]}" ipv6_cidr_block = "${cidrsubnet(aws_vpc.test.ipv6_cidr_block, 8, 1)}" tags = { Name = "tf-acc-subnet-data-source-ipv6" } } `, rInt, rInt) } func testAccDataSourceAwsSubnetConfigIpv6WithDataSourceFilter(rInt int) string { return fmt.Sprintf(` data "aws_availability_zones" "available" { state = "available" filter { name = "opt-in-status" values = ["opt-in-not-required"] } } resource "aws_vpc" "test" { cidr_block = "172.%d.0.0/16" assign_generated_ipv6_cidr_block = true tags = { Name = "terraform-testacc-subnet-data-source-ipv6-with-ds-filter" } } resource "aws_subnet" "test" { vpc_id = "${aws_vpc.test.id}" cidr_block = "172.%d.123.0/24" availability_zone = "${data.aws_availability_zones.available.names[0]}" ipv6_cidr_block = "${cidrsubnet(aws_vpc.test.ipv6_cidr_block, 8, 1)}" tags = { Name = "tf-acc-subnet-data-source-ipv6-with-ds-filter" } } data "aws_subnet" "by_ipv6_cidr" { filter { name = "ipv6-cidr-block-association.ipv6-cidr-block" values = ["${aws_subnet.test.ipv6_cidr_block}"] } } `, rInt, rInt) } func testAccDataSourceAwsSubnetConfigIpv6WithDataSourceIpv6CidrBlock(rInt int) string { return fmt.Sprintf(` data "aws_availability_zones" "available" { state = "available" filter { name = "opt-in-status" values = ["opt-in-not-required"] } } resource "aws_vpc" "test" { cidr_block = "172.%d.0.0/16" assign_generated_ipv6_cidr_block = true tags = { Name = "terraform-testacc-subnet-data-source-ipv6-cidr-block" } } resource "aws_subnet" "test" { vpc_id = "${aws_vpc.test.id}" cidr_block = "172.%d.123.0/24" availability_zone = "${data.aws_availability_zones.available.names[0]}" ipv6_cidr_block = "${cidrsubnet(aws_vpc.test.ipv6_cidr_block, 8, 1)}" tags = { Name = "tf-acc-subnet-data-source-ipv6-cidr-block" } } data "aws_subnet" "by_ipv6_cidr" { ipv6_cidr_block = "${aws_subnet.test.ipv6_cidr_block}" } `, rInt, rInt) }
mpl-2.0
catherineting/openhim-console
app/views/logs.html
2522
<div class="page-content"> <div class="row"> <!-- include the sidebar --> <div ng-include="'views/sidebar.html'"></div> <div class="col-md-10"> <div class="content-box-large"> <div class="panel-heading"> <div class="panel-title"> <h2><i class="glyphicon glyphicon-cog"></i>&nbsp;&nbsp;Server Logs</h2> </div> </div> <div class="panel-body"> <!-- Filter options --> <form class="form-inline logs-filter" role="form"> <div class="form-group"> <label class="sr-only">Log level</label> <select class="form-control" ng-model="params.level" ng-change="reload()"> <option value="info">info</option> <option value="debug">debug</option> <option value="warn">warn</option> <option value="error">error</option> </select> </div> <div class="form-group"> <label class="sr-only">From</label> <input type="text" class="form-control" ng-model="params.from" placeholder="from" ng-blur="reload()" datetimepicker datetimepicker-options="{ format: 'YYYY-MM-DD HH:mm', useCurrent: 'day' }"> </div> <div class="form-group"> <label class="sr-only">Until</label> <input type="text" class="form-control" ng-model="params.until" placeholder="until" ng-blur="reload()" datetimepicker datetimepicker-options="{ format: 'YYYY-MM-DD HH:mm', useCurrent: 'day' }"> </div> <div class="form-group checkbox"> <label> <input class="form-control" type="checkbox" ng-model="tailLogs"> Tail logs </label> </div> <i tooltip-placement="top" tooltip="Only a maximum of 100 000 log messages will ever be shown at once, queries longer than that will be truncated. Also, note that log messages with the exact same timestamp MAY be displayed out of order." class="glyphicon glyphicon-question-sign tooltip-wide"></i> <div class="pull-right"> <button class="btn btn-warning" ng-click="reset()">Clear Filters</button> </div> </form> <!-- log viewer --> <div> <textarea id="textarea" class="log-viewer" rows="40" ng-model="logs" ng-style="{'overflow': tailLogs ? 'hidden' : 'auto'}" readonly></textarea> </div> </div> </div> </div> </div> </div>
mpl-2.0
Yukarumya/Yukarum-Redfoxes
addon-sdk/source/test/addons/simple-prefs/lib/main.js
5341
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 'use strict'; const { Cu } = require('chrome'); const sp = require('sdk/simple-prefs'); const app = require('sdk/system/xul-app'); const { id, preferencesBranch } = require('sdk/self'); const { open } = require('sdk/preferences/utils'); const { getTabForId } = require('sdk/tabs/utils'); const { modelFor } = require('sdk/model/core'); const { getAddonByID } = require('sdk/addon/manager'); const { AddonManager } = Cu.import('resource://gre/modules/AddonManager.jsm', {}); require('sdk/tabs'); exports.testDefaultValues = function (assert) { assert.equal(sp.prefs.myHiddenInt, 5, 'myHiddenInt default is 5'); assert.equal(sp.prefs.myInteger, 8, 'myInteger default is 8'); assert.equal(sp.prefs.somePreference, 'TEST', 'somePreference default is correct'); } exports.testOptionsType = function*(assert) { let addon = yield getAddonByID(id); assert.equal(addon.optionsType, AddonManager.OPTIONS_TYPE_INLINE, 'options type is inline'); } exports.testButton = function(assert, done) { open({ id: id }).then(({ tabId, document }) => { let tab = modelFor(getTabForId(tabId)); sp.once('sayHello', _ => { assert.pass('The button was pressed!'); tab.close(done); }); tab.attach({ contentScript: 'unsafeWindow.document.querySelector("button[label=\'Click me!\']").click();' }); }); } if (app.is('Firefox')) { exports.testAOM = function(assert, done) { open({ id: id }).then(({ tabId }) => { let tab = modelFor(getTabForId(tabId)); assert.pass('the add-on prefs page was opened.'); tab.attach({ contentScriptWhen: "end", contentScript: 'self.postMessage({\n' + 'someCount: unsafeWindow.document.querySelectorAll("setting[title=\'some-title\']").length,\n' + 'somePreference: getAttributes(unsafeWindow.document.querySelector("setting[title=\'some-title\']")),\n' + 'myInteger: getAttributes(unsafeWindow.document.querySelector("setting[title=\'my-int\']")),\n' + 'myHiddenInt: getAttributes(unsafeWindow.document.querySelector("setting[title=\'hidden-int\']")),\n' + 'sayHello: getAttributes(unsafeWindow.document.querySelector("button[label=\'Click me!\']"))\n' + '});\n' + 'function getAttributes(ele) {\n' + 'if (!ele) return {};\n' + 'return {\n' + 'pref: ele.getAttribute("pref"),\n' + 'type: ele.getAttribute("type"),\n' + 'title: ele.getAttribute("title"),\n' + 'desc: ele.getAttribute("desc"),\n' + '"data-jetpack-id": ele.getAttribute(\'data-jetpack-id\')\n' + '}\n' + '}\n', onMessage: msg => { // test against doc caching assert.equal(msg.someCount, 1, 'there is exactly one <setting> node for somePreference'); // test somePreference assert.equal(msg.somePreference.type, 'string', 'some pref is a string'); assert.equal(msg.somePreference.pref, 'extensions.' + id + '.somePreference', 'somePreference path is correct'); assert.equal(msg.somePreference.title, 'some-title', 'somePreference title is correct'); assert.equal(msg.somePreference.desc, 'Some short description for the preference', 'somePreference description is correct'); assert.equal(msg.somePreference['data-jetpack-id'], id, 'data-jetpack-id attribute value is correct'); // test myInteger assert.equal(msg.myInteger.type, 'integer', 'myInteger is a int'); assert.equal(msg.myInteger.pref, 'extensions.' + id + '.myInteger', 'extensions.test-simple-prefs.myInteger'); assert.equal(msg.myInteger.title, 'my-int', 'myInteger title is correct'); assert.equal(msg.myInteger.desc, 'How many of them we have.', 'myInteger desc is correct'); assert.equal(msg.myInteger['data-jetpack-id'], id, 'data-jetpack-id attribute value is correct'); // test myHiddenInt assert.equal(msg.myHiddenInt.type, undefined, 'myHiddenInt was not displayed'); assert.equal(msg.myHiddenInt.pref, undefined, 'myHiddenInt was not displayed'); assert.equal(msg.myHiddenInt.title, undefined, 'myHiddenInt was not displayed'); assert.equal(msg.myHiddenInt.desc, undefined, 'myHiddenInt was not displayed'); // test sayHello assert.equal(msg.sayHello['data-jetpack-id'], id, 'data-jetpack-id attribute value is correct'); tab.close(done); } }); }) } // run it again, to test against inline options document caching // and duplication of <setting> nodes upon re-entry to about:addons exports.testAgainstDocCaching = exports.testAOM; } exports.testDefaultPreferencesBranch = function(assert) { assert.equal(preferencesBranch, id, 'preferencesBranch default the same as self.id'); } require('sdk/test/runner').runTestsFromModule(module);
mpl-2.0
jsyeo/rubinius
machine/memory/immix_collector.hpp
4136
#ifndef RBX_GC_IMMIX_HPP #define RBX_GC_IMMIX_HPP #include "memory/address.hpp" #include "memory/immix_region.hpp" #include "memory/gc.hpp" #include "exception.hpp" #include "object_position.hpp" namespace rubinius { class Memory; namespace memory { class ImmixGC; class ImmixMarker; /** * ImmixGC uses the immix memory management strategy to perform garbage * collection on the mature objects in the immix space. */ class ImmixGC : public GarbageCollector { public: class Diagnostics : public diagnostics::MemoryDiagnostics { public: int64_t collections_; int64_t total_bytes_; int64_t chunks_; int64_t holes_; double percentage_; Diagnostics(); void update(); }; private: /** * Class used as an interface to the Rubinius specific object memory layout * by the (general purpose) Immix memory manager. By imposing this interface * between Memory and the utility Immix memory manager, the latter can * be made reusable. * * The Immix memory manager delegates to this class to: * - determine the size of an object at a particular memory address * - copy an object * - return the forwarding pointer for an object * - set the forwarding pointer for an object that it moves * - mark an address as visited * - determine if an object is pinned and cannot be moved * - walk all root pointers * * It will also notify this class when: * - it adds chunks * - allocates from the last free block, indicating a collection is needed */ class ObjectDescriber { Memory* memory_; ImmixGC* gc_; public: ObjectDescriber() : memory_(0) , gc_(NULL) {} void set_object_memory(Memory* om, ImmixGC* gc) { memory_ = om; gc_ = gc; } void added_chunk(int count); void last_block() { } void set_forwarding_pointer(Address from, Address to); Address forwarding_pointer(Address cur) { Object* obj = cur.as<Object>(); if(obj->forwarded_p()) return obj->forward(); return Address::null(); } bool pinned(Address addr) { return addr.as<Object>()->pinned_p(); } Address copy(Address original, ImmixAllocator& alloc); void walk_pointers(Address addr, Marker<ObjectDescriber>& mark) { Object* obj = addr.as<Object>(); if(obj) gc_->scan_object(obj); } Address update_pointer(Address addr); int size(Address addr); /** * Called when the GC object wishes to mark an object. * * @returns true if the object is not already marked, and in the Immix * space; otherwise false. */ bool mark_address(Address addr, MarkStack& ms, bool push = true); }; GC<ObjectDescriber> gc_; ExpandingAllocator allocator_; Memory* memory_; ImmixMarker* marker_; int chunks_left_; int chunks_before_collection_; Diagnostics* diagnostics_; public: ImmixGC(Memory* om); virtual ~ImmixGC(); Object* allocate(size_t bytes, bool& collect_now); Object* move_object(Object* orig, size_t bytes, bool& collect_now); virtual Object* saw_object(Object*); virtual void scanned_object(Object*); virtual bool mature_gc_in_progress(); void collect(GCData* data); void collect_start(GCData* data); void collect_finish(GCData* data); void sweep(); void walk_finalizers(); ObjectPosition validate_object(Object*); public: // Inline Memory* memory() { return memory_; } size_t& bytes_allocated() { return gc_.bytes_allocated(); } int dec_chunks_left() { return --chunks_left_; } void reset_chunks_left() { chunks_left_ = chunks_before_collection_; } Diagnostics* diagnostics() { return diagnostics_; } void start_marker(STATE, GCData* data); bool process_mark_stack(); bool process_mark_stack(bool& exit); MarkStack& mark_stack(); private: void collect_scan(GCData* data); }; } } #endif
mpl-2.0
shssoichiro/servo
components/layout/table_colgroup.rs
4289
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! CSS table formatting contexts. #![deny(unsafe_code)] use app_units::Au; use context::LayoutContext; use display_list_builder::DisplayListBuildState; use euclid::Point2D; use flow::{BaseFlow, Flow, FlowClass, ForceNonfloatedFlag, OpaqueFlow}; use fragment::{Fragment, FragmentBorderBoxIterator, Overflow, SpecificFragmentInfo}; use layout_debug; use std::cmp::max; use std::fmt; use style::logical_geometry::LogicalSize; use style::properties::ComputedValues; use style::values::computed::LengthOrPercentageOrAuto; /// A table formatting context. pub struct TableColGroupFlow { /// Data common to all flows. pub base: BaseFlow, /// The associated fragment. pub fragment: Option<Fragment>, /// The table column fragments pub cols: Vec<Fragment>, /// The specified inline-sizes of table columns. (We use `LengthOrPercentageOrAuto` here in /// lieu of `ColumnInlineSize` because column groups do not establish minimum or preferred /// inline sizes.) pub inline_sizes: Vec<LengthOrPercentageOrAuto>, } impl TableColGroupFlow { pub fn from_fragments(fragment: Fragment, fragments: Vec<Fragment>) -> TableColGroupFlow { let writing_mode = fragment.style().writing_mode; TableColGroupFlow { base: BaseFlow::new(Some(fragment.style()), writing_mode, ForceNonfloatedFlag::ForceNonfloated), fragment: Some(fragment), cols: fragments, inline_sizes: vec!(), } } } impl Flow for TableColGroupFlow { fn class(&self) -> FlowClass { FlowClass::TableColGroup } fn as_mut_table_colgroup(&mut self) -> &mut TableColGroupFlow { self } fn bubble_inline_sizes(&mut self) { let _scope = layout_debug_scope!("table_colgroup::bubble_inline_sizes {:x}", self.base.debug_id()); for fragment in &self.cols { // Retrieve the specified value from the appropriate CSS property. let inline_size = fragment.style().content_inline_size(); let span = match fragment.specific { SpecificFragmentInfo::TableColumn(col_fragment) => max(col_fragment.span, 1), _ => panic!("non-table-column fragment inside table column?!"), }; for _ in 0..span { self.inline_sizes.push(inline_size) } } } /// Table column inline-sizes are assigned in the table flow and propagated to table row flows /// and/or rowgroup flows. Therefore, table colgroup flows do not need to assign inline-sizes. fn assign_inline_sizes(&mut self, _: &LayoutContext) { } /// Table columns do not have block-size. fn assign_block_size(&mut self, _: &LayoutContext) { } fn update_late_computed_inline_position_if_necessary(&mut self, _: Au) {} fn update_late_computed_block_position_if_necessary(&mut self, _: Au) {} // Table columns are invisible. fn build_display_list(&mut self, _: &mut DisplayListBuildState) { } fn collect_stacking_contexts(&mut self, _: &mut DisplayListBuildState) {} fn repair_style(&mut self, _: &::ServoArc<ComputedValues>) {} fn compute_overflow(&self) -> Overflow { Overflow::new() } fn generated_containing_block_size(&self, _: OpaqueFlow) -> LogicalSize<Au> { panic!("Table column groups can't be containing blocks!") } fn iterate_through_fragment_border_boxes(&self, _: &mut FragmentBorderBoxIterator, _: i32, _: &Point2D<Au>) {} fn mutate_fragments(&mut self, _: &mut FnMut(&mut Fragment)) {} } impl fmt::Debug for TableColGroupFlow { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.fragment { Some(ref rb) => write!(f, "TableColGroupFlow: {:?}", rb), None => write!(f, "TableColGroupFlow"), } } }
mpl-2.0
AccroGaming/Accro-DarkRP
DarkRP/gamemode/cl_init.lua
16674
GM.Version = "2.4.3" GM.Name = "DarkRP" GM.Author = "By Rickster, Updated: Pcwizdan, Sibre, philxyz, [GNC] Matt, Chrome Bolt, FPtje Falco, Eusion, Drakehawke" DeriveGamemode("sandbox") util.PrecacheSound("earthquake.mp3") CUR = "$" /*--------------------------------------------------------------------------- Names ---------------------------------------------------------------------------*/ -- Make sure the client sees the RP name where they expect to see the name local pmeta = FindMetaTable("Player") pmeta.SteamName = pmeta.SteamName or pmeta.Name function pmeta:Name() return GAMEMODE.Config.allowrpnames and self.DarkRPVars and self:getDarkRPVar("rpname") or self:SteamName() end pmeta.GetName = pmeta.Name pmeta.Nick = pmeta.Name -- End function GM:DrawDeathNotice(x, y) if not GAMEMODE.Config.showdeaths then return end self.BaseClass:DrawDeathNotice(x, y) end local function DisplayNotify(msg) local txt = msg:ReadString() GAMEMODE:AddNotify(txt, msg:ReadShort(), msg:ReadLong()) surface.PlaySound("buttons/lightswitch2.wav") -- Log to client console print(txt) end usermessage.Hook("_Notify", DisplayNotify) local function LoadModules() local root = GM.FolderName.."/gamemode/modules/" local _, folders = file.Find(root.."*", "LUA") for _, folder in SortedPairs(folders, true) do if GM.Config.DisabledModules[folder] then continue end for _, File in SortedPairs(file.Find(root .. folder .."/sh_*.lua", "LUA"), true) do if File == "sh_interface.lua" then continue end include(root.. folder .. "/" ..File) end for _, File in SortedPairs(file.Find(root .. folder .."/cl_*.lua", "LUA"), true) do if File == "cl_interface.lua" then continue end include(root.. folder .. "/" ..File) end end end GM.Config = {} -- config table include("config.lua") include("sh_interfaceloader.lua") include("client/help.lua") include("client/cl_chatlisteners.lua") include("client/DRPDermaSkin.lua") include("client/helpvgui.lua") include("client/hud.lua") include("client/showteamtabs.lua") include("client/vgui.lua") include("shared/player_class.lua") include("shared/animations.lua") include("shared/commands.lua") include("shared/entity.lua") include("shared/MakeThings.lua") include("shared/Workarounds.lua") include("shared.lua") include("addentities.lua") include("ammotypes.lua") include("fpp/sh_settings.lua") include("fpp/client/FPP_Menu.lua") include("fpp/client/FPP_HUD.lua") include("fpp/client/FPP_Buddies.lua") include("fpp/sh_CPPI.lua") LoadModules() DarkRP.finish() surface.CreateFont("AckBarWriting", { size = 20, weight = 500, antialias = true, shadow = false, font = "akbar"}) -- Copy from FESP(made by FPtje Falco) -- This is no stealing since I made FESP myself. local vector = FindMetaTable("Vector") function vector:RPIsInSight(v, ply) ply = ply or LocalPlayer() local trace = {} trace.start = ply:EyePos() trace.endpos = self trace.filter = v trace.mask = -1 local TheTrace = util.TraceLine(trace) if TheTrace.Hit then return false, TheTrace.HitPos else return true, TheTrace.HitPos end end function GM:HUDShouldDraw(name) if name == "CHudHealth" or name == "CHudBattery" or name == "CHudSuitPower" or (HelpToggled and name == "CHudChat") then return false else return true end end function GM:HUDDrawTargetID() return false end function GM:FindPlayer(info) if not info or info == "" then return nil end local pls = player.GetAll() for k = 1, #pls do -- Proven to be faster than pairs loop. local v = pls[k] if tonumber(info) == v:UserID() then return v end if info == v:SteamID() then return v end if string.find(string.lower(v:SteamName()), string.lower(tostring(info)), 1, true) ~= nil then return v end if string.find(string.lower(v:Name()), string.lower(tostring(info)), 1, true) ~= nil then return v end end return nil end local GUIToggled = false local HelpToggled = false local HelpVGUI function GM:ShowHelp() if not HelpVGUI then HelpVGUI = vgui.Create("HelpVGUI") end HelpToggled = not HelpToggled HelpVGUI.HelpX = HelpVGUI.StartHelpX HelpVGUI:FillHelpInfo() HelpVGUI:SetVisible(HelpToggled) gui.EnableScreenClicker(HelpToggled) end local mouseX, mouseY = ScrW() / 2, ScrH() / 2 function GM:ShowSpare1() GUIToggled = not GUIToggled if GUIToggled then gui.SetMousePos(mouseX, mouseY) else mouseX, mouseY = gui.MousePos() end gui.EnableScreenClicker(GUIToggled) end local function blackScreen(um) local toggle = um:ReadBool() if toggle then local black = Color(0, 0, 0) local w, h = ScrW(), ScrH() hook.Add("HUDPaintBackground", "BlackScreen", function() surface.SetDrawColor(black) surface.DrawRect(0, 0, w, h) end) else hook.Remove("HUDPaintBackground", "BlackScreen") end end usermessage.Hook("blackScreen", blackScreen) function GM:PlayerStartVoice(ply) if ply == LocalPlayer() then ply.DRPIsTalking = true return -- Not the original rectangle for yourself! ugh! end self.BaseClass:PlayerStartVoice(ply) end function GM:PlayerEndVoice(ply) if ply == LocalPlayer() then ply.DRPIsTalking = false return end self.BaseClass:PlayerEndVoice(ply) end function GM:OnPlayerChat() end local FKeyBinds = { ["gm_showhelp"] = "ShowHelp", ["gm_showteam"] = "ShowTeam", ["gm_showspare1"] = "ShowSpare1", ["gm_showspare2"] = "ShowSpare2" } function GM:PlayerBindPress(ply, bind, pressed) self.BaseClass:PlayerBindPress(ply, bind, pressed) if ply == LocalPlayer() and IsValid(ply:GetActiveWeapon()) and string.find(string.lower(bind), "attack2") and ply:GetActiveWeapon():GetClass() == "weapon_bugbait" then LocalPlayer():ConCommand("_hobo_emitsound") end local bnd = string.match(string.lower(bind), "gm_[a-z]+[12]?") if bnd and FKeyBinds[bnd] and GAMEMODE[FKeyBinds[bnd]] then GAMEMODE[FKeyBinds[bnd]](GAMEMODE) end return end local function AddToChat(msg) local col1 = Color(msg:ReadShort(), msg:ReadShort(), msg:ReadShort()) local prefixText = msg:ReadString() local ply = msg:ReadEntity() ply = IsValid(ply) and ply or LocalPlayer() if prefixText == "" or not prefixText then prefixText = ply:Nick() prefixText = prefixText ~= "" and prefixText or ply:SteamName() end local col2 = Color(msg:ReadShort(), msg:ReadShort(), msg:ReadShort()) local text = msg:ReadString() local shouldShow if text and text ~= "" then if IsValid(ply) then shouldShow = hook.Call("OnPlayerChat", nil, ply, text, false, not ply:Alive(), prefixText, col1, col2) end if shouldShow ~= true then chat.AddText(col1, prefixText, col2, ": "..text) end else shouldShow = hook.Call("ChatText", nil, "0", prefixText, prefixText, "none") if shouldShow ~= true then chat.AddText(col1, prefixText) end end chat.PlaySound() end usermessage.Hook("DarkRP_Chat", AddToChat) local function GetAvailableVehicles() print("Available vehicles for custom vehicles:") for k,v in pairs(list.Get("Vehicles")) do print("\""..k.."\"") end end concommand.Add("rp_getvehicles", GetAvailableVehicles) local function AdminLog(um) local colour = Color(um:ReadShort(), um:ReadShort(), um:ReadShort()) local text = um:ReadString() .. "\n" MsgC(Color(255,0,0), "[DarkRP] ") MsgC(colour, text) end usermessage.Hook("DRPLogMsg", AdminLog) local function RetrieveDoorData(len) local door = net.ReadEntity() local doorData = net.ReadTable() if not door or not door.IsValid or not IsValid(door) or not doorData then return end if doorData.TeamOwn then local tdata = {} for k, v in pairs(string.Explode("\n", doorData.TeamOwn or "")) do if v and v != "" then tdata[tonumber(v)] = true end end doorData.TeamOwn = tdata else doorData.TeamOwn = nil end door.DoorData = doorData end net.Receive("DarkRP_DoorData", RetrieveDoorData) local function UpdateDoorData(um) local door = um:ReadEntity() if not IsValid(door) then return end local var, value = um:ReadString(), um:ReadString() value = tonumber(value) or value if string.match(tostring(value), "Entity .([0-9]*)") then value = Entity(string.match(value, "Entity .([0-9]*)")) end if string.match(tostring(value), "Player .([0-9]*)") then value = Entity(string.match(value, "Player .([0-9]*)")) end if value == "true" or value == "false" then value = tobool(value) end if value == "nil" then value = nil end if var == "TeamOwn" then local decoded = {} for k, v in pairs(string.Explode("\n", value or "")) do if v and v != "" then decoded[tonumber(v)] = true end end if table.Count(decoded) == 0 then value = nil else value = decoded end end door.DoorData = door.DoorData or {} door.DoorData[var] = value end usermessage.Hook("DRP_UpdateDoorData", UpdateDoorData) local function RetrievePlayerVar(entIndex, var, value, tries) local ply = Entity(entIndex) -- Usermessages _can_ arrive before the player is valid. -- In this case, chances are huge that this player will become valid. if not IsValid(ply) then if tries >= 5 then return end timer.Simple(0.5, function() RetrievePlayerVar(entIndex, var, value, tries + 1) end) return end ply.DarkRPVars = ply.DarkRPVars or {} local stringvalue = value value = tonumber(value) or value if string.match(stringvalue, "Entity .([0-9]*)") then value = Entity(string.match(stringvalue, "Entity .([0-9]*)")) end if string.match(stringvalue, "^Player .([0-9]+).") then value = player.GetAll()[tonumber(string.match(stringvalue, "^Player .([0-9]+)."))] end if stringvalue == "NULL" then value = NULL end if string.match(stringvalue, [[(-?[0-9]+.[0-9]+) (-?[0-9]+.[0-9]+) (-?[0-9]+.[0-9]+)]]) then local x,y,z = string.match(value, [[(-?[0-9]+.[0-9]+) (-?[0-9]+.[0-9]+) (-?[0-9]+.[0-9]+)]]) value = Vector(x,y,z) end if stringvalue == "true" or stringvalue == "false" then value = tobool(value) end if stringvalue == "nil" then value = nil end hook.Call("DarkRPVarChanged", nil, ply, var, ply.DarkRPVars[var], value) ply.DarkRPVars[var] = value end function pmeta:getDarkRPVar(var) self.DarkRPVars = self.DarkRPVars or {} return self.DarkRPVars[var] end /*--------------------------------------------------------------------------- Retrieve a player var. Read the usermessage and attempt to set the DarkRP var ---------------------------------------------------------------------------*/ local function doRetrieve(um) local entIndex = um:ReadShort() local var, value = um:ReadString(), um:ReadString() RetrievePlayerVar(entIndex, var, value, 0) end usermessage.Hook("DarkRP_PlayerVar", doRetrieve) local function InitializeDarkRPVars(len) local vars = net.ReadTable() if not vars then return end for k,v in pairs(vars) do if not IsValid(k) then continue end k.DarkRPVars = k.DarkRPVars or {} -- Merge the tables for a, b in pairs(v) do k.DarkRPVars[a] = b end end end net.Receive("DarkRP_InitializeVars", InitializeDarkRPVars) function GM:InitPostEntity() RunConsoleCommand("_sendDarkRPvars") timer.Create("DarkRPCheckifitcamethrough", 15, 0, function() for k,v in pairs(player.GetAll()) do if v.DarkRPVars and v:getDarkRPVar("rpname") then continue end RunConsoleCommand("_sendDarkRPvars") return end end) hook.Call("TeamChanged", GAMEMODE, 1, 1) end function GM:TeamChanged(before, after) self:RemoveHelpCategory(0) if RPExtraTeams[after] and RPExtraTeams[after].help then self:AddHelpCategory(0, RPExtraTeams[after].name .. " help") self:AddHelpLabels(0, RPExtraTeams[after].help) end end local function OnChangedTeam(um) hook.Call("TeamChanged", GAMEMODE, um:ReadShort(), um:ReadShort()) end usermessage.Hook("OnChangedTeam", OnChangedTeam) function GM:TextWrap(text, font, pxWidth) local total = 0 surface.SetFont(font) text = text:gsub(".", function(char) if char == "\n" then total = 0 end total = total + surface.GetTextSize(char) -- Wrap around when the max width is reached if total >= pxWidth then total = 0 return "\n" .. char end return char end) return text end -- Please only ADD to the credits -- Removing people from the credits will make at least one person very angry. local creds = [[LightRP: Rick darkalonio DarkRP: Rickster Picwizdan Sibre PhilXYZ [GNC] Matt Chromebolt A.K.A. unib5 (STEAM_0:1:19045957) Falco A.K.A. FPtje (STEAM_0:0:8944068) Eusion (STEAM_0:0:20450406) Drakehawke (STEAM_0:0:22342869)]] local function credits(um) chat.AddText(Color(255,0,0,255), "CREDITS FOR DARKRP", Color(0,0,255,255), creds) end usermessage.Hook("DarkRP_Credits", credits) -- DarkRP plugin for FAdmin. It's this simple to make a plugin. If FAdmin isn't installed, this code won't bother anyone include(GM.FolderName.."/gamemode/shared/fadmin_darkrp.lua") local function formatNumber(n) if not n then return "" end if n >= 1e14 then return tostring(n) end n = tostring(n) local sep = sep or "," local dp = string.find(n, "%.") or #n+1 for i=dp-4, 1, -3 do n = n:sub(1, i) .. sep .. n:sub(i+1) end return n end if not FAdmin or not FAdmin.StartHooks then return end FAdmin.StartHooks["DarkRP"] = function() -- DarkRP information: FAdmin.ScoreBoard.Player:AddInformation("Steam name", function(ply) return ply:SteamName() end, true) FAdmin.ScoreBoard.Player:AddInformation("Money", function(ply) if LocalPlayer():IsAdmin() and ply.DarkRPVars and ply:getDarkRPVar("money") then return GAMEMODE.Config.currency..formatNumber(ply:getDarkRPVar("money")) end end) FAdmin.ScoreBoard.Player:AddInformation("Wanted", function(ply) if ply.DarkRPVars and ply:getDarkRPVar("wanted") then return tostring(ply:getDarkRPVar("wantedReason") or "N/A") end end) FAdmin.ScoreBoard.Player:AddInformation("Community link", function(ply) return FAdmin.SteamToProfile(ply) end) FAdmin.ScoreBoard.Player:AddInformation("Rank", function(ply) if FAdmin.Access.PlayerHasPrivilege(LocalPlayer(), "SeeAdmins") then return ply:GetNWString("usergroup") end end) -- Warrant FAdmin.ScoreBoard.Player:AddActionButton("Warrant", "FAdmin/icons/Message", Color(0, 0, 200, 255), function(ply) return LocalPlayer():IsCP() end, function(ply, button) Derma_StringRequest("Warrant reason", "Enter the reason for the warrant", "", function(Reason) RunConsoleCommand("darkrp", "/warrant", ply:SteamID(), Reason) end) end) --wanted FAdmin.ScoreBoard.Player:AddActionButton(function(ply) return ((ply:getDarkRPVar("wanted") and "Unw") or "W") .. "anted" end, function(ply) return "FAdmin/icons/jail", ply:getDarkRPVar("wanted") and "FAdmin/icons/disable" end, Color(0, 0, 200, 255), function(ply) return LocalPlayer():IsCP() end, function(ply, button) if not ply:getDarkRPVar("wanted") then Derma_StringRequest("wanted reason", "Enter the reason to arrest this player", "", function(Reason) RunConsoleCommand("darkrp", "/wanted", ply:SteamID(), Reason) end) else RunConsoleCommand("darkrp", "/unwanted", ply:UserID()) end end) --Teamban local function teamban(ply, button) local menu = DermaMenu() local Title = vgui.Create("DLabel") Title:SetText(" Jobs:\n") Title:SetFont("UiBold") Title:SizeToContents() Title:SetTextColor(color_black) local command = "rp_teamban" menu:AddPanel(Title) for k,v in SortedPairsByMemberValue(RPExtraTeams, "name") do local submenu = menu:AddSubMenu(v.name) submenu:AddOption("2 minutes", function() RunConsoleCommand(command, ply:UserID(), k, 120) end) submenu:AddOption("Half an hour", function() RunConsoleCommand(command, ply:UserID(), k, 1800) end) submenu:AddOption("An hour", function() RunConsoleCommand(command, ply:UserID(), k, 3600) end) submenu:AddOption("Until restart", function() RunConsoleCommand(command, ply:UserID(), k, 0) end) end menu:Open() end FAdmin.ScoreBoard.Player:AddActionButton("Ban from job", "FAdmin/icons/changeteam", Color(200, 0, 0, 255), function(ply) return FAdmin.Access.PlayerHasPrivilege(LocalPlayer(), "rp_commands", ply) end, teamban) local function teamunban(ply, button) local menu = DermaMenu() local Title = vgui.Create("DLabel") Title:SetText(" Jobs:\n") Title:SetFont("UiBold") Title:SizeToContents() Title:SetTextColor(color_black) local command = "rp_teamunban" menu:AddPanel(Title) for k,v in SortedPairsByMemberValue(RPExtraTeams, "name") do menu:AddOption(v.name, function() RunConsoleCommand(command, ply:UserID(), k) end) end menu:Open() end FAdmin.ScoreBoard.Player:AddActionButton("Unban from job", function() return "FAdmin/icons/changeteam", "FAdmin/icons/disable" end, Color(200, 0, 0, 255), function(ply) return FAdmin.Access.PlayerHasPrivilege(LocalPlayer(), "rp_commands", ply) end, teamunban) end
mpl-2.0
yonadev/yona-app-android
openvpn/src/main/java/de/blinkt/openvpn/api/ExternalAppDatabase.java
1694
/* * Copyright (c) 2012-2016 Arne Schwabe * Distributed under the GNU GPL v2 with additional terms. For full terms see the file doc/LICENSE.txt */ package de.blinkt.openvpn.api; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.preference.PreferenceManager; import java.util.HashSet; import java.util.Set; public class ExternalAppDatabase { private final String PREFERENCES_KEY = "PREFERENCES_KEY"; Context mContext; public ExternalAppDatabase(Context c) { mContext = c; } boolean isAllowed(String packagename) { Set<String> allowedapps = getExtAppList(); return allowedapps.contains(packagename); } public Set<String> getExtAppList() { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext); return prefs.getStringSet(PREFERENCES_KEY, new HashSet<String>()); } void addApp(String packagename) { Set<String> allowedapps = getExtAppList(); allowedapps.add(packagename); saveExtAppList(allowedapps); } private void saveExtAppList(Set<String> allowedapps) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext); Editor prefedit = prefs.edit(); prefedit.putStringSet(PREFERENCES_KEY, allowedapps); prefedit.apply(); } public void clearAllApiApps() { saveExtAppList(new HashSet<String>()); } public void removeApp(String packagename) { Set<String> allowedapps = getExtAppList(); allowedapps.remove(packagename); saveExtAppList(allowedapps); } }
mpl-2.0
Lootyhoof/xmoon
README.md
774
# XMoon ![Preview](https://i.imgur.com/PTebvce.png) Fork of the theme "MacOSX Theme" by GOLF-AT for Pale Moon. ## Building Simply download the contents of the "src" folder and pack the contents into a .zip file. Then, rename the file to .xpi and drag into the browser. On Unix systems (or Windows 10, with [WSL](https://docs.microsoft.com/en-us/windows/wsl/about)) you can optionally run `build.sh` instead. Running this as-is will produce a .xpi file ending in `-dev`, and if run from the command line and appending a number (e.g. `./build.sh 2`) will append that number to the filename instead. ## Download You can grab the latest release either from the Releases section of this repository, or the [Pale Moon Add-Ons Site](https://addons.palemoon.org/addon/xmoon/).
mpl-2.0
youhong316/consul
website/config.rb
2474
set :base_url, "https://www.consul.io/" activate :hashicorp do |h| h.name = "consul" h.version = "1.4.0" h.github_slug = "hashicorp/consul" end helpers do # Returns a segment tracking ID such that local development is not # tracked to production systems. def segmentId() if (ENV['ENV'] == 'production') 'IyzLrqXkox5KJ8XL4fo8vTYNGfiKlTCm' else '0EXTgkNx0Ydje2PGXVbRhpKKoe5wtzcE' end end # Returns the FQDN of the image URL. # # @param [String] path # # @return [String] def image_url(path) File.join(base_url, image_path(path)) end # Get the title for the page. # # @param [Middleman::Page] page # # @return [String] def title_for(page) if page && page.data.page_title return "#{page.data.page_title} - Consul by HashiCorp" end "Consul by HashiCorp" end # Get the description for the page # # @param [Middleman::Page] page # # @return [String] def description_for(page) description = (page.data.description || "Consul by HashiCorp") .gsub('"', '') .gsub(/\n+/, ' ') .squeeze(' ') return escape_html(description) end # This helps by setting the "active" class for sidebar nav elements # if the YAML frontmatter matches the expected value. def sidebar_current(expected) current = current_page.data.sidebar_current || "" if current.start_with?(expected) return " class=\"active\"" else return "" end end # Returns the id for this page. # @return [String] def body_id_for(page) if !(name = page.data.sidebar_current).blank? return "page-#{name.strip}" end if page.url == "/" || page.url == "/index.html" return "page-home" end if !(title = page.data.page_title).blank? return title .downcase .gsub('"', '') .gsub(/[^\w]+/, '-') .gsub(/_+/, '-') .squeeze('-') .squeeze(' ') end return "" end # Returns the list of classes for this page. # @return [String] def body_classes_for(page) classes = [] if !(layout = page.data.layout).blank? classes << "layout-#{page.data.layout}" end if !(title = page.data.page_title).blank? title = title .downcase .gsub('"', '') .gsub(/[^\w]+/, '-') .gsub(/_+/, '-') .squeeze('-') .squeeze(' ') classes << "page-#{title}" end return classes.join(" ") end end
mpl-2.0
terraform-providers/terraform-provider-google
google/resource_compute_instance_group_named_port_sweeper_test.go
4472
// ---------------------------------------------------------------------------- // // *** AUTO GENERATED CODE *** AUTO GENERATED CODE *** // // ---------------------------------------------------------------------------- // // This file is automatically generated by Magic Modules and manual // changes will be clobbered when the file is regenerated. // // Please read more about how to change this file in // .github/CONTRIBUTING.md. // // ---------------------------------------------------------------------------- package google import ( "context" "log" "strings" "testing" "github.com/hashicorp/terraform-plugin-sdk/helper/resource" ) func init() { resource.AddTestSweepers("ComputeInstanceGroupNamedPort", &resource.Sweeper{ Name: "ComputeInstanceGroupNamedPort", F: testSweepComputeInstanceGroupNamedPort, }) } // At the time of writing, the CI only passes us-central1 as the region func testSweepComputeInstanceGroupNamedPort(region string) error { resourceName := "ComputeInstanceGroupNamedPort" log.Printf("[INFO][SWEEPER_LOG] Starting sweeper for %s", resourceName) config, err := sharedConfigForRegion(region) if err != nil { log.Printf("[INFO][SWEEPER_LOG] error getting shared config for region: %s", err) return err } err = config.LoadAndValidate(context.Background()) if err != nil { log.Printf("[INFO][SWEEPER_LOG] error loading: %s", err) return err } t := &testing.T{} billingId := getTestBillingAccountFromEnv(t) // Setup variables to replace in list template d := &ResourceDataMock{ FieldsInSchema: map[string]interface{}{ "project": config.Project, "region": region, "location": region, "zone": "-", "billing_account": billingId, }, } listTemplate := strings.Split("https://www.googleapis.com/compute/v1/projects/{{project}}/aggregated/instanceGroups/{{group}}", "?")[0] listUrl, err := replaceVars(d, config, listTemplate) if err != nil { log.Printf("[INFO][SWEEPER_LOG] error preparing sweeper list url: %s", err) return nil } res, err := sendRequest(config, "GET", config.Project, listUrl, nil) if err != nil { log.Printf("[INFO][SWEEPER_LOG] Error in response from request %s: %s", listUrl, err) return nil } resourceList, ok := res["namedPorts"] if !ok { log.Printf("[INFO][SWEEPER_LOG] Nothing found in response.") return nil } var rl []interface{} zones := resourceList.(map[string]interface{}) // Loop through every zone in the list response for _, zonesValue := range zones { zone := zonesValue.(map[string]interface{}) for k, v := range zone { // Zone map either has resources or a warning stating there were no resources found in the zone if k != "warning" { resourcesInZone := v.([]interface{}) rl = append(rl, resourcesInZone...) } } } log.Printf("[INFO][SWEEPER_LOG] Found %d items in %s list response.", len(rl), resourceName) // Keep count of items that aren't sweepable for logging. nonPrefixCount := 0 for _, ri := range rl { obj := ri.(map[string]interface{}) if obj["name"] == nil { log.Printf("[INFO][SWEEPER_LOG] %s resource name was nil", resourceName) return nil } name := GetResourceNameFromSelfLink(obj["name"].(string)) // Skip resources that shouldn't be sweeped if !isSweepableTestResource(name) { nonPrefixCount++ continue } deleteTemplate := "https://www.googleapis.com/compute/v1/projects/{{project}}/zones/{{zone}}/instanceGroups/{{group}}/setNamedPorts" if obj["zone"] == nil { log.Printf("[INFO][SWEEPER_LOG] %s resource zone was nil", resourceName) return nil } zone := GetResourceNameFromSelfLink(obj["zone"].(string)) deleteTemplate = strings.Replace(deleteTemplate, "{{zone}}", zone, -1) deleteUrl, err := replaceVars(d, config, deleteTemplate) if err != nil { log.Printf("[INFO][SWEEPER_LOG] error preparing delete url: %s", err) return nil } deleteUrl = deleteUrl + name // Don't wait on operations as we may have a lot to delete _, err = sendRequest(config, "DELETE", config.Project, deleteUrl, nil) if err != nil { log.Printf("[INFO][SWEEPER_LOG] Error deleting for url %s : %s", deleteUrl, err) } else { log.Printf("[INFO][SWEEPER_LOG] Sent delete request for %s resource: %s", resourceName, name) } } if nonPrefixCount > 0 { log.Printf("[INFO][SWEEPER_LOG] %d items were non-sweepable and skipped.", nonPrefixCount) } return nil }
mpl-2.0
servo/doc.servo.org
servo/gl/GetRenderbufferParameteriv/fn.load_with.html
4662
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <meta name="description" content="API documentation for the Rust `load_with` fn in crate `servo`."> <meta name="keywords" content="rust, rustlang, rust-lang, load_with"> <title>servo::gl::GetRenderbufferParameteriv::load_with - Rust</title> <link rel="stylesheet" type="text/css" href="../../../rustdoc.css"> <link rel="stylesheet" type="text/css" href="../../../main.css"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <nav class="sidebar"> <p class='location'><a href='../../index.html'>servo</a>::<wbr><a href='../index.html'>gl</a>::<wbr><a href='index.html'>GetRenderbufferParameteriv</a></p><script>window.sidebarCurrent = {name: 'load_with', ty: 'fn', relpath: ''};</script><script defer src="sidebar-items.js"></script> </nav> <nav class="sub"> <form class="search-form js-only"> <div class="search-container"> <input class="search-input" name="search" autocomplete="off" placeholder="Click or press ‘S’ to search, ‘?’ for more options…" type="search"> </div> </form> </nav> <section id='main' class="content fn"> <h1 class='fqn'><span class='in-band'>Function <a href='../../index.html'>servo</a>::<wbr><a href='../index.html'>gl</a>::<wbr><a href='index.html'>GetRenderbufferParameteriv</a>::<wbr><a class='fn' href=''>load_with</a></span><span class='out-of-band'><span id='render-detail'> <a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs"> [<span class='inner'>&#x2212;</span>] </a> </span><a id='src-5916' class='srclink' href='../../../gleam/ffi/GetRenderbufferParameteriv/fn.load_with.html?gotosrc=5916' title='goto source code'>[src]</a></span></h1> <pre class='rust fn'>pub fn load_with&lt;F&gt;(loadfn: F) <span class='where'>where F: <a class='trait' href='../../../core/ops/trait.FnMut.html' title='core::ops::FnMut'>FnMut</a>(&amp;<a class='primitive' href='../../../std/primitive.str.html'>str</a>) -&gt; <a class='primitive' href='../../../std/primitive.pointer.html'>*const </a><a class='enum' href='../../../std/os/raw/enum.c_void.html' title='std::os::raw::c_void'>c_void</a></span></pre></section> <section id='search' class="content hidden"></section> <section class="footer"></section> <aside id="help" class="hidden"> <div> <h1 class="hidden">Help</h1> <div class="shortcuts"> <h2>Keyboard Shortcuts</h2> <dl> <dt>?</dt> <dd>Show this help dialog</dd> <dt>S</dt> <dd>Focus the search field</dd> <dt>&larrb;</dt> <dd>Move up in search results</dd> <dt>&rarrb;</dt> <dd>Move down in search results</dd> <dt>&#9166;</dt> <dd>Go to active search result</dd> <dt>+</dt> <dd>Collapse/expand all sections</dd> </dl> </div> <div class="infos"> <h2>Search Tricks</h2> <p> Prefix searches with a type followed by a colon (e.g. <code>fn:</code>) to restrict the search to a given type. </p> <p> Accepted types are: <code>fn</code>, <code>mod</code>, <code>struct</code>, <code>enum</code>, <code>trait</code>, <code>type</code>, <code>macro</code>, and <code>const</code>. </p> <p> Search functions by type signature (e.g. <code>vec -> usize</code> or <code>* -> vec</code>) </p> </div> </div> </aside> <script> window.rootPath = "../../../"; window.currentCrate = "servo"; window.playgroundUrl = ""; </script> <script src="../../../jquery.js"></script> <script src="../../../main.js"></script> <script defer src="../../../search-index.js"></script> </body> </html>
mpl-2.0
susaing/doc.servo.org
gleam/ffi/types/type.GLhalf.html
4108
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <meta name="description" content="API documentation for the Rust `GLhalf` type in crate `gleam`."> <meta name="keywords" content="rust, rustlang, rust-lang, GLhalf"> <title>gleam::ffi::types::GLhalf - Rust</title> <link rel="stylesheet" type="text/css" href="../../../main.css"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <section class="sidebar"> <p class='location'><a href='../../index.html'>gleam</a>::<wbr><a href='../index.html'>ffi</a>::<wbr><a href='index.html'>types</a></p><script>window.sidebarCurrent = {name: 'GLhalf', ty: 'type', relpath: ''};</script><script defer src="sidebar-items.js"></script> </section> <nav class="sub"> <form class="search-form js-only"> <div class="search-container"> <input class="search-input" name="search" autocomplete="off" placeholder="Click or press ‘S’ to search, ‘?’ for more options…" type="search"> </div> </form> </nav> <section id='main' class="content type"> <h1 class='fqn'><span class='in-band'><a href='../../index.html'>gleam</a>::<wbr><a href='../index.html'>ffi</a>::<wbr><a href='index.html'>types</a>::<wbr><a class='type' href=''>GLhalf</a></span><span class='out-of-band'><span id='render-detail'> <a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs"> [<span class='inner'>&#x2212;</span>] </a> </span><a id='src-2030' class='srclink' href='../../../src/gleam///home/servo/buildbot/slave/doc/build/target/debug/build/gleam-9662459d59abad25/out/gl_bindings.rs.html#52' title='goto source code'>[src]</a></span></h1> <pre class='rust typedef'>type GLhalf = <a class='type' href='../../../libc/types/os/arch/c95/type.c_ushort.html' title='libc::types::os::arch::c95::c_ushort'>c_ushort</a>;</pre></section> <section id='search' class="content hidden"></section> <section class="footer"></section> <div id="help" class="hidden"> <div> <div class="shortcuts"> <h1>Keyboard Shortcuts</h1> <dl> <dt>?</dt> <dd>Show this help dialog</dd> <dt>S</dt> <dd>Focus the search field</dd> <dt>&larrb;</dt> <dd>Move up in search results</dd> <dt>&rarrb;</dt> <dd>Move down in search results</dd> <dt>&#9166;</dt> <dd>Go to active search result</dd> </dl> </div> <div class="infos"> <h1>Search Tricks</h1> <p> Prefix searches with a type followed by a colon (e.g. <code>fn:</code>) to restrict the search to a given type. </p> <p> Accepted types are: <code>fn</code>, <code>mod</code>, <code>struct</code>, <code>enum</code>, <code>trait</code>, <code>type</code>, <code>macro</code>, and <code>const</code>. </p> <p> Search functions by type signature (e.g. <code>vec -> usize</code>) </p> </div> </div> </div> <script> window.rootPath = "../../../"; window.currentCrate = "gleam"; window.playgroundUrl = ""; </script> <script src="../../../jquery.js"></script> <script src="../../../main.js"></script> <script async src="../../../search-index.js"></script> </body> </html>
mpl-2.0
kjmkznr/terraform-provider-aws
website/docs/r/vpc_peering_connection_accepter.html.markdown
5000
--- subcategory: "VPC" layout: "aws" page_title: "AWS: aws_vpc_peering_connection_accepter" description: |- Manage the accepter's side of a VPC Peering Connection. --- # Resource: aws_vpc_peering_connection_accepter Provides a resource to manage the accepter's side of a VPC Peering Connection. When a cross-account (requester's AWS account differs from the accepter's AWS account) or an inter-region VPC Peering Connection is created, a VPC Peering Connection resource is automatically created in the accepter's account. The requester can use the `aws_vpc_peering_connection` resource to manage its side of the connection and the accepter can use the `aws_vpc_peering_connection_accepter` resource to "adopt" its side of the connection into management. ## Example Usage ```hcl provider "aws" { region = "us-east-1" # Requester's credentials. } provider "aws" { alias = "peer" region = "us-west-2" # Accepter's credentials. } resource "aws_vpc" "main" { cidr_block = "10.0.0.0/16" } resource "aws_vpc" "peer" { provider = "aws.peer" cidr_block = "10.1.0.0/16" } data "aws_caller_identity" "peer" { provider = "aws.peer" } # Requester's side of the connection. resource "aws_vpc_peering_connection" "peer" { vpc_id = "${aws_vpc.main.id}" peer_vpc_id = "${aws_vpc.peer.id}" peer_owner_id = "${data.aws_caller_identity.peer.account_id}" peer_region = "us-west-2" auto_accept = false tags = { Side = "Requester" } } # Accepter's side of the connection. resource "aws_vpc_peering_connection_accepter" "peer" { provider = "aws.peer" vpc_peering_connection_id = "${aws_vpc_peering_connection.peer.id}" auto_accept = true tags = { Side = "Accepter" } } ``` ## Argument Reference The following arguments are supported: * `vpc_peering_connection_id` - (Required) The VPC Peering Connection ID to manage. * `auto_accept` - (Optional) Whether or not to accept the peering request. Defaults to `false`. * `tags` - (Optional) A map of tags to assign to the resource. ### Removing `aws_vpc_peering_connection_accepter` from your configuration AWS allows a cross-account VPC Peering Connection to be deleted from either the requester's or accepter's side. However, Terraform only allows the VPC Peering Connection to be deleted from the requester's side by removing the corresponding `aws_vpc_peering_connection` resource from your configuration. Removing a `aws_vpc_peering_connection_accepter` resource from your configuration will remove it from your statefile and management, **but will not destroy the VPC Peering Connection.** ## Attributes Reference All of the argument attributes except `auto_accept` are also exported as result attributes. * `id` - The ID of the VPC Peering Connection. * `accept_status` - The status of the VPC Peering Connection request. * `vpc_id` - The ID of the accepter VPC. * `peer_vpc_id` - The ID of the requester VPC. * `peer_owner_id` - The AWS account ID of the owner of the requester VPC. * `peer_region` - The region of the accepter VPC. * `accepter` - A configuration block that describes [VPC Peering Connection] (https://docs.aws.amazon.com/vpc/latest/peering/what-is-vpc-peering.html) options set for the accepter VPC. * `requester` - A configuration block that describes [VPC Peering Connection] (https://docs.aws.amazon.com/vpc/latest/peering/what-is-vpc-peering.html) options set for the requester VPC. #### Accepter and Requester Attributes Reference * `allow_remote_vpc_dns_resolution` - Indicates whether a local VPC can resolve public DNS hostnames to private IP addresses when queried from instances in a peer VPC. * `allow_classic_link_to_remote_vpc` - Indicates whether a local ClassicLink connection can communicate with the peer VPC over the VPC Peering Connection. * `allow_vpc_to_remote_classic_link` - Indicates whether a local VPC can communicate with a ClassicLink connection in the peer VPC over the VPC Peering Connection. ## Attributes Reference In addition to all arguments above, the following attributes are exported: * `id` - The ID of the VPC Peering Connection. ## Import VPC Peering Connection Accepters can be imported by using the Peering Connection ID, e.g. ```sh $ terraform import aws_vpc_peering_connection_accepter.example pcx-12345678 ``` Certain resource arguments, like `auto_accept`, do not have an EC2 API method for reading the information after peering connection creation. If the argument is set in the Terraform configuration on an imported resource, Terraform will always show a difference. To workaround this behavior, either omit the argument from the Terraform configuration or use [`ignore_changes`](/docs/configuration/resources.html#ignore_changes) to hide the difference, e.g. ```hcl resource "aws_vpc_peering_connection_accepter" "example" { # ... other configuration ... # There is no AWS EC2 API for reading auto_accept lifecycle { ignore_changes = ["auto_accept"] } } ```
mpl-2.0
yonadev/yona-app-android
app/src/main/java/nu/yona/app/enums/UserStatus.java
448
/* * <?xml version="1.0" encoding="utf-8"?><!-- * ~ Copyright (c) 2018 Stichting Yona Foundation * ~ * ~ This Source Code Form is subject to the terms of the Mozilla Public * ~ License, v. 2.0. If a copy of the MPL was not distributed with this * ~ file, You can obtain one at https://mozilla.org/MPL/2.0/. * --> */ package nu.yona.app.enums; public enum UserStatus { ACTIVE, NUMBER_NOT_CONFIRMED, NOT_REGISTERED, BLOCKED }
mpl-2.0
poparteu/popsift
src/popsift/s_desc_notile.h
500
/* * Copyright 2016-2017, Simula Research Laboratory * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #include "sift_pyramid.h" #include "sift_octave.h" #include "sift_extremum.h" #include "common/debug_macros.h" namespace popsift { bool start_ext_desc_notile( const int octave, Octave& oct_obj ); }; // namespace popsift
mpl-2.0
mozilla-iam/auth0-deploy
rules/GHE-Groups.js
4302
function (user, context, callback) { // dictionary of applications and their related mozillians groups to worry about const applicationGroupMapping = { 'EnEylt4OZW6i7yCWzZmCxyCxDRp6lOY0': 'mozilliansorg_ghe_saml-test-integrations_users', }; const fetch = require('node-fetch@2.6.0'); const AUTH0_TIMEOUT = 5000; // milliseconds const PERSONAPI_BEARER_TOKEN_REFRESH_AGE = 64770; // 18 hours - 30 seconds for refresh timeout allowance const PERSONAPI_TIMEOUT = 5000; // milliseconds const USER_ID = context.primaryUser || user.user_id; const getBearerToken = async () => { // if we have the bearer token stored, we don't need to fetch it again if (global.personapi_bearer_token && global.personapi_bearer_token_creation_time && Date.now() - global.personapi_bearer_token_creation_time < PERSONAPI_BEARER_TOKEN_REFRESH_AGE) { return global.personapi_bearer_token; } const options = { method: 'POST', headers: { 'Content-Type': 'application/json', }, timeout: AUTH0_TIMEOUT, body: JSON.stringify({ audience: configuration.personapi_audience, client_id: configuration.personapi_read_profile_api_client_id, client_secret: configuration.personapi_read_profile_api_secret, grant_type: 'client_credentials', }) }; try { //console.log(configuration.personapi_oauth_url); const response = await fetch(configuration.personapi_oauth_url, options); const data = await response.json(); // store the bearer token in the global object, so it's not constantly retrieved global.personapi_bearer_token = data.access_token; global.personapi_bearer_token_creation_time = Date.now(); console.log(`Successfully retrieved bearer token from Auth0`); return global.personapi_bearer_token; } catch (error) { throw Error(`Unable to retrieve bearer token from Auth0: ${error.message}`); } }; const getPersonProfile = async () => { // Retrieve a bearer token to gain access to the person api // return the profile data const bearer = await getBearerToken(); const options = { method: 'GET', headers: { 'Authorization': `Bearer ${bearer}`, }, timeout: PERSONAPI_TIMEOUT, }; const url = `${configuration.personapi_url}/v2/user/user_id/${encodeURI(USER_ID)}`; //console.log(`Fetching person profile of ${USER_ID}`); //console.log("url is " + url); const response = await fetch(url, options); return await response.json(); }; // We only care about SSO applications that exist in the applicationGroupMapping // If the SSO ID is undefined in applicationGroupMapping, skip processing and return callback() if(applicationGroupMapping[context.clientID] !== undefined) { getPersonProfile().then(profile => { let githubUsername = null; // Get githubUsername from person api, otherwise we'll redirect try { githubUsername = profile.usernames.values['HACK#GITHUB']; // Explicitely setting githubUsername to null if undefined if(githubUsername === undefined) { githubUsername = null; } // If somehow dinopark allows a user to store an empty value // Let's set to null to be redirected later if(githubUsername.length === 0) { console.log("empty HACK#GITHUB"); githubUsername = null; } //console.log("githubUsername: " + githubUsername); } catch (e) { // Unable to do the githubUsername lookup } // Confirm the user has the group defined from mozillians matching the application id // confirm the user has a githubUsername stored in mozillians, otherwise redirect if(!user.app_metadata.groups.includes(applicationGroupMapping[context.clientID]) || githubUsername === null) { context.redirect = { url: configuration.github_enterprise_wiki_url }; } return callback(null, user, context); }); // Nothing matched, return callback() and proceed rules processing } else { return callback(null, user, context); } }
mpl-2.0
araraloren/FunctionFind
cpplogger/cllogger.cpp
8085
#include <cllogger.h> #include <stdarg.h> #ifdef CC_PF_WIN32 # include <process.h> #endif cl::ClLogger::ClLogger() : m_write_interval(CL_INIT_WRITE_INTERVAL), m_check_interval(CL_INIT_CHECK_INTERVAL), m_stop_times(CL_INIT_STOP_TIMES), m_stop_count(CL_INIT_STOP_COUNT), m_write_flag(false), m_check_flag(false), m_msg_queue() { m_msg_queue.init(); } cl::ClLogger::ClLogger(size_t queue_size, int queue_waits) : m_write_interval(CL_INIT_WRITE_INTERVAL), m_check_interval(CL_INIT_CHECK_INTERVAL), m_stop_times(CL_INIT_STOP_TIMES), m_stop_count(CL_INIT_STOP_COUNT), m_write_flag(false), m_check_flag(false), m_msg_queue(queue_size, queue_waits) { m_msg_queue.init(); } bool cl::ClLogger::start() { bool ret = false; if (__start()) { for(std::vector<ClInfoPtr>::iterator it = m_infos_reg.begin(); it != m_infos_reg.end();it ++){ cl::ClInfoPtr& cip = *it; ret = ret && cip->startWork(); } } return ret; } void cl::ClLogger::stop() { cc::microSleep(m_stop_times); m_write_flag = m_check_flag = false; #if __cplusplus >= 201103L m_write_thr.detach(); m_check_thr.join(); #else # if (defined CC_PF_LINUX) || (defined CC_PF_MINGW32) pthread_detach(m_write_thr); pthread_join(m_check_thr, 0); # elif (defined CC_PF_WIN32) static const int S_WAIT_FOR = 5000; if (WAIT_TIMEOUT == WaitForSingleObject(m_check_thr, S_WAIT_FOR)){ TerminateThread(m_check_thr, 1); } # endif #endif } bool cl::ClLogger::start(const size_t &id) { if(id == 0 || id > m_infos_reg.size()){ return false; } if(__start()){ return m_infos_reg[id]->startWork(); }else{ return false; } } bool cl::ClLogger::start(const string &name) { ClInfoPtr curr_info = m_infos_reg[name]; if(curr_info == nullptr){ return false; } if(__start()){ return curr_info->startWork(); }else{ return false; } } void cl::ClLogger::stop(const size_t &id) { if(id == 0 || id > m_infos_reg.size()){ return; } if(m_write_flag && m_check_flag){ m_infos_reg[id]->stopWork(); } } void cl::ClLogger::stop(const string &name) { ClInfoPtr curr_info = m_infos_reg[name]; if(curr_info == nullptr){ return; } if(m_write_flag && m_check_flag){ curr_info->stopWork(); } } size_t cl::ClLogger::registerLogInfo(const cl::ClInfoPtr &clinfo) { return m_infos_reg.registerInfo(clinfo); } size_t cl::ClLogger::registerLogInfo(const string &name) { ClInfoPtr clinfo = new ClInfo(name); return m_infos_reg.registerInfo(clinfo); } size_t cl::ClLogger::registerLogInfo(const string &name, const string &prefix, const string &postfix) { ClInfoPtr clinfo = new ClInfo(name); clinfo->m_prefix = prefix; clinfo->m_postfix = postfix; return m_infos_reg.registerInfo(clinfo); } size_t cl::ClLogger::registerLogInfo(const string &name, const string &path, const string &feed, const cl::log_mode_t &mode) { ClInfoPtr clinfo = new ClInfo(name, path, feed, mode); return m_infos_reg.registerInfo(clinfo); } size_t cl::ClLogger::registerLogInfo(const string &name, const string &prefix, const string &postfix, const string &path, const string &feed, const cl::log_mode_t &mode) { ClInfoPtr clinfo = new ClInfo(name, path, feed, mode); clinfo->m_prefix = prefix; clinfo->m_postfix = postfix; return m_infos_reg.registerInfo(clinfo); } bool cl::ClLogger::writef(const size_t &id, const char *format, ...) { static const size_t S_BUFF_SIZE = 4096; if(id == 0 || id > m_infos_reg.size()){ return false; } if(!m_infos_reg[id]->isWork()){ return false; } va_list argslist; char buff[S_BUFF_SIZE]; int ret = 0; va_start(argslist, format); #if (defined CC_PF_LINUX) || (defined CC_PF_MINGW32) ret = std::vsnprintf(buff, S_BUFF_SIZE, format, argslist); #elif (defined CC_PF_WIN32) ret = _vsnprintf_s(buff, S_BUFF_SIZE, format, argslist); #endif va_end(argslist); if(ret <= 0){ return false; } ClMessage message(id, string(buff, ret)); m_msg_queue.push(message); return true; } bool cl::ClLogger::writef(const string &name, const char *format, ...) { static const size_t S_BUFF_SIZE = 4096; size_t id = m_infos_reg.getLogId(name); if(id == 0 || !m_infos_reg[id]->isWork()){ return false; } va_list argslist; char buff[S_BUFF_SIZE]; int ret = 0; va_start(argslist, format); #if (defined CC_PF_LINUX) || (defined CC_PF_MINGW32) ret = std::vsnprintf(buff, S_BUFF_SIZE, format, argslist); #elif (defined CC_PF_WIN32) ret = _vsnprintf_s(buff, S_BUFF_SIZE, format, argslist); #endif va_end(argslist); if(ret <= 0){ return false; } ClMessage message(id, string(buff, ret)); m_msg_queue.push(message); return true; } bool cl::ClLogger::write(const size_t &id, const string &msg) { if(id == 0 || id > m_infos_reg.size()){ return false; } if(!m_infos_reg[id]->isWork()){ return false; } ClMessage message(id, msg); m_msg_queue.push(message); return true; } bool cl::ClLogger::write(const string &name, const string &msg) { size_t id = m_infos_reg.getLogId(name); if(id == 0 || !m_infos_reg[id]->isWork()){ return false; } ClMessage message(id, msg); m_msg_queue.push(message); return true; } bool cl::ClLogger::__start() { if(m_write_flag && m_check_flag){ return true; } if(!m_write_flag){ m_write_flag = true; if(!__startThread(m_write_thr, cl::ClLogger::s_write, static_cast<cc::thread_para_t>(this))){ m_write_flag = false; return false; } } if(!m_check_flag){ m_check_flag = true; if(!__startThread(m_check_thr, cl::ClLogger::s_check, static_cast<cc::thread_para_t>(this))){ m_check_flag = false; return false; } } return true; } bool cl::ClLogger::__startThread(cc::thread_t &thread, cc::thread_func *pfunc, cc::thread_para_t para) { #if __cplusplus >= 201103L cc::thread_t thr(pfunc, para); thread.swap(thr); #else # if (defined CC_PF_LINUX) || (defined CC_PF_MINGW32) int ret = pthread_create(&thread, 0, pfunc, para); if(ret != 0){ return false; } # elif (defined CC_PF_WIN32) thread = (cc::thread_t)_beginthreadex(0, 0, pfunc, para, 0, 0); # endif #endif return true; } cc::thread_ret_t CC_THREAD cl::ClLogger::s_write(cc::thread_para_t para) { cl::ClLogger* logger = static_cast<cl::ClLogger*>(para); cc::SeqQueue<cl::ClMessage>& msgqueue = logger->m_msg_queue; cl::ClInfoRegistry& registry = logger->m_infos_reg; cl::ClMessage message; bool& is_write = logger->m_write_flag; int& sleep_tm = logger->m_write_interval; int quit_wait = logger->m_stop_count; for(;is_write || quit_wait;is_write ? quit_wait : quit_wait --){ msgqueue.pop(message); ClInfoPtr curr_info = registry[message.m_id]; curr_info->write(message.m_msg); message.reset(); cc::microSleep(sleep_tm); } return static_cast<cc::thread_ret_t>(0); } cc::thread_ret_t CC_THREAD cl::ClLogger::s_check(cc::thread_para_t para) { cl::ClLogger* logger = static_cast<cl::ClLogger*>(para); cl::ClInfoRegistry& registry = logger->m_infos_reg; bool& is_check = logger->m_check_flag; int& sleep_tm = logger->m_check_interval; int quit_wait = logger->m_stop_count; for(;is_check || quit_wait;is_check ? quit_wait : quit_wait --){ for(std::vector<ClInfoPtr>::iterator it = registry.begin(); it != registry.end();it ++){ cl::ClInfoPtr& cip = *it; if(cip && cip->isWork()){ cip->check(); } } cc::microSleep(sleep_tm); } return static_cast<cc::thread_ret_t>(0); }
mpl-2.0
mozilla/webmaker.org
lib/makeapi.js
4168
var toolURL = { 'application/x-popcorn': 'https://popcorn.webmaker.org', 'application/x-thimble': 'https://thimble.webmaker.org', 'application/x-x-ray-goggles': 'https://goggles.mozilla.org' }; module.exports = function (options) { var moment = require('moment'); var MakeClient = require('makeapi-client'); function generateGravatar(hash) { var DEFAULT_AVATAR = 'https%3A%2F%2Fstuff.webmaker.org%2Favatars%2Fwebmaker-avatar-44x44.png', DEFAULT_SIZE = 44; return 'https://secure.gravatar.com/avatar/' + hash + '?s=' + DEFAULT_SIZE + '&d=' + DEFAULT_AVATAR; } // Create a make client with or without auth function createMakeClient(url, hawk) { var options = { apiURL: url }; if (hawk) { options.hawk = hawk; } var makeClient = new MakeClient(options); // Moment.js default language is 'en'. This function will override // the default language globally on the coming request for the homepage makeClient.setLang = function (lang) { moment.lang(lang); }; // Given a prefix for an app tag (e.g. "webmaker:p-") sort an array of makes based on that tag // The tag must be of the format "prefix-1", "prefix-2", etc. makeClient.sortByPriority = function (prefix, data) { var sortedData = [], duplicates = [], priorityIndex, regex = new RegExp('^' + prefix + '(\\d+)$'); function extractStickyPriority(tags) { var res; for (var i = tags.length - 1; i >= 0; i--) { res = regex.exec(tags[i]); if (res) { return +res[1]; } } } for (var i = 0; i < data.length; i++) { priorityIndex = extractStickyPriority(data[i].appTags); data[i].index = priorityIndex; if (sortedData[priorityIndex - 1]) { duplicates.push('Duplicate found for ' + prefix + priorityIndex); } else { sortedData[priorityIndex - 1] = data[i]; } } return { results: sortedData, errors: duplicates }; }; makeClient.process = function (callback, id) { makeClient.then(function (err, data, totalHits) { if (err) { return callback(err); } if (!Array.isArray(data)) { return callback('There was no data returned'); } data.forEach(function (make) { // Set the tool make.tool = make.contentType.replace(/application\/x\-/g, ''); make.toolurl = toolURL[make.contentType]; // Convert tags and set the "make.type" if (make.taggedWithAny(['guide'])) { make.type = 'guide'; } else if (make.taggedWithAny(['webmaker:template'])) { make.type = 'template'; } else if (make.contentType) { make.type = make.tool; } if (make.taggedWithAny(['beginner'])) { make.level = 'beginner'; } else if (make.taggedWithAny(['intermediate'])) { make.level = 'intermediate'; } else if (make.taggedWithAny(['advanced'])) { make.level = 'advanced'; } // Remove tutorial tags make.prettyTags = make.rawTags.filter(function (tag) { return !(tag.match(/^tutorial-/)); }); if (id) { make.hasBeenLiked = make.likes.some(function (like) { return like.userId === +id; }); } // Convert the created at and updated at to human time make.updatedAt = moment(make.updatedAt).fromNow(); make.createdAt = moment(make.createdAt).fromNow(); // Set the remix URL if (make.type !== 'Appmaker') { make.remixurl = make.url + '/remix'; } // Create a function for generating the avatar make.avatar = generateGravatar(make.emailHash); }); callback(err, data, totalHits); }); }; return makeClient; } module.exports = { authenticated: createMakeClient(options.authenticatedURL, options.hawk), readOnly: createMakeClient(options.readOnlyURL) }; };
mpl-2.0
MapWindow/MapWinGIS
src/Ogr/Shape2Ogr.h
2223
#pragma once #include "ogr_feature.h" #include <set> class Shape2Ogr { public: static bool Shapefile2OgrLayer(IShapefile* sf, OGRLayer* poLayer, bool saveLabels, ICallback* callback = NULL); static int SaveShapefileChanges(OGRLayer* poLayer, IShapefile* shapefile, long shapeCmnIndex, tkOgrSaveType saveType, bool validateShapes, bool safeToDelete, vector<OgrUpdateError>& errors); private: static int RemoveDeletedFeatures(OGRLayer* layer, IShapefile* sf, long shapeCmnIndex); static bool ShapeRecord2Feature(IShapefile* sf, long shapeIndex, OGRFeature* feature, OGRFeatureDefn* fields, tkOgrSaveType saveType, bool editing, CString& validationError, bool validateShape, vector<int>* fieldMap); static bool ShapefileFieldsToOgr(IShapefile* sf, OGRLayer* poLayer); static void ShapesToOgr(IShapefile* sf, OGRLayer* layer, ICallback* callback); static void RecreateFieldsFromShapefile(OGRLayer* layer, IShapefile* sf); static OGRFieldType ShapeFieldType2OgrFieldType(FieldType fieldType); static void CopyRecordAttributes(IShapefile* sf, long shapeIndex, OGRFeature* feature, bool editing, OGRFeatureDefn* fields, vector<int>* fieldMap); static bool SaveShape(OGRLayer* poLayer, OGRFeature* ft, OGRFeatureDefn* fields, IShapefile* shapefile, int shapeIndex, long shapeCmnIndex, tkOgrSaveType saveType, bool validateShapes, vector<OgrUpdateError>& errors, vector<int>& fieldMap); static OGRFeature* GetFeature(OGRLayer* poLayer, IShapefile* shapefile, long shapeCmnIndex, long shapeIndex, long& featId); static void CreateField(IField* field, OGRLayer* layer); static void GetOldFields(IShapefile* sf, std::set<int>& indices); static void RemovedStaleFields(OGRLayer* layer, IShapefile* sf, int fieldCount); static void CreateNewFields(OGRLayer* layer, IShapefile* sf); static void GetNewFields(IShapefile* sf, std::set<int>& indices); static void CopyShapeData(IShapefile* shapefile, OGRLayer* poLayer, long shapeCmnIndex, tkOgrSaveType saveType, bool validateShapes, vector<OgrUpdateError>& errors, int& shapeCount, int& rowCount); static void BuildFieldMap(IShapefile* sf, vector<int>& indices); static void UpdateModifiedFields(IShapefile* sf, OGRLayer* layer); };
mpl-2.0
changwoo/hunspell-dict-ko
utils/findduplicates.py
1426
#!/usr/bin/python3 from lxml import etree import sys class Word: def __init__(self): self.word = '' self.pos = '' self.props = [] def __hash__(self): return (self.word + self.pos).__hash__() def __cmp__(self, other): n = cmp(self.word, other.word) if n != 0: return n n = cmp(self.pos, other.pos) if n != 0: return n # FIXME: 이렇게 하면 순서가 다를텐데. set에서 뭐가 먼저 나올지 알고... if self.pos == '명사': return 0 for prop in other.props: if not prop in self.props: return -1 for prop in self.props: if not prop in other.props: return 1 return 0 ###################################################################### if len(sys.argv) < 1: sys.exit(1) filename = sys.argv[1] doc = etree.parse(open(filename)) root = doc.getroot() wordset = set() for item in root: w = Word() for field in item: if field.tag == 'word': w.word = field.text elif field.tag == 'pos': w.pos = field.text elif field.tag == 'props' and field.text: w.props = field.text.split(',') w.props.sort() if w in wordset: sys.stderr.write(('%s (%s)\n' % (w.word, w.pos)).encode('UTF-8')) else: wordset.add(w)
mpl-2.0
territorium/fluid
src/demo/iconcategorymodel.h
902
/* * This file is part of Fluid. * * Copyright (C) 2017 Pier Luigi Fiorini <pierluigi.fiorini@gmail.com> * * $BEGIN_LICENSE:MPL2$ * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * $END_LICENSE$ */ #pragma once #include <QAbstractListModel> class IconCategoryModel : public QAbstractListModel { Q_OBJECT public: enum Role { Category = Qt::UserRole + 1 }; explicit IconCategoryModel(QObject *parent = nullptr); QHash<int, QByteArray> roleNames() const override; int rowCount(const QModelIndex &parent = QModelIndex()) const override; QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; private: QStringList m_items; private Q_SLOTS: void readFile(); };
mpl-2.0
jeffreybrayne/TheBreakContest
modules/jrUser/quota.php
5055
<?php /** * Jamroom 5 User Accounts module * * copyright 2003 - 2015 * by The Jamroom Network * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. Please see the included "license.html" file. * * This module may include works that are not developed by * The Jamroom Network * and are used under license - any licenses are included and * can be found in the "contrib" directory within this module. * * Jamroom may use modules and skins that are licensed by third party * developers, and licensed under a different license - please * reference the individual module or skin license that is included * with your installation. * * This software is provided "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 Jamroom Network 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 from the use of this * software, even if advised of the possibility of such damage. * Some jurisdictions may not allow disclaimers of implied warranties * and certain statements in the above disclaimer may not apply to * you as regards implied warranties; the other terms and conditions * remain enforceable notwithstanding. In some jurisdictions it is * not permitted to limit liability and therefore such limitations * may not apply to you. * * @copyright 2012 Talldude Networks, LLC. */ // make sure we are not being called directly defined('APP_DIR') or exit(); /** * quota_config */ function jrUser_quota_config() { // Allow Signups $_tmp = array( 'name' => 'allow_signups', 'type' => 'checkbox', 'validate' => 'onoff', 'label' => 'allow signups', 'help' => 'If the &quot;Allow Signups&quot; option is <b>checked</b>, then new users signing up for your system will be able to signup directly to this Profile Quota.', 'default' => 'off', 'order' => 1 ); jrProfile_register_quota_setting('jrUser', $_tmp); // Signup Method $_als = array( 'instant' => 'Instant Validation', 'email' => 'Email Validation', 'admin' => 'Admin Validation' ); $_tmp = array( 'name' => 'signup_method', 'type' => 'select', 'options' => $_als, 'default' => 'email', 'required' => 'on', 'label' => 'signup method', 'help' => 'How should users signup for this Quota?<br><br><b>Instant Validation</b> - The new user account and profile are activated on signup.<br><b>Email Validation</b> - An activation email is sent on signup to activate the new account.', 'order' => 2 ); jrProfile_register_quota_setting('jrUser', $_tmp); // device notice $_tmp = array( 'name' => 'device_notice', 'type' => 'checkbox', 'default' => 'off', 'validate' => 'onoff', 'label' => 'new device notice', 'help' => 'If this option is checked, when a user logs in for the first time on a new device, they will be sent an email notification letting them know about the login.', 'order' => 3 ); jrProfile_register_quota_setting('jrUser', $_tmp); // Power User $_tmp = array( 'name' => 'power_user', 'type' => 'checkbox', 'validate' => 'onoff', 'label' => 'power user enabled', 'help' => 'If this option is checked, User Accounts belonging to profiles in this Quota will be Power Users that can create new profiles.', 'default' => 'off', 'section' => 'power user', 'order' => 10 ); jrProfile_register_quota_setting('jrUser', $_tmp); // Power User Profiles $_tmp = array( 'name' => 'power_user_max', 'type' => 'text', 'validate' => 'number_nz', 'label' => 'max profiles', 'help' => 'How many profiles can a Power User in this quota create?', 'default' => 2, 'section' => 'power user', 'order' => 11 ); jrProfile_register_quota_setting('jrUser', $_tmp); // Power User Quotas $_tmp = array( 'name' => 'power_user_quotas', 'type' => 'select_multiple', 'label' => 'allowed quotas', 'help' => 'When a Power User in this Quota creates a new Profile, what Quotas can they select for their new profile?', 'options' => 'jrProfile_get_quotas', 'default' => 0, 'section' => 'power user', 'order' => 12 ); jrProfile_register_quota_setting('jrUser', $_tmp); return true; }
mpl-2.0
legatoproject/legato-docs
17_08/le__flash__interface_8h.html
17566
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html data-context="Build Apps" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta content="text/html; charset=utf-8" http-equiv="Content-Type"/> <title>le_flash_interface.h File Reference - Legato Docs</title> <meta content="legato™ is an open source Linux-based embedded platform designed to simplify connected IoT application development" name="description"/> <meta content="legato, iot" name="keywords"/> <meta content="17.08.1" name="legato-version"/> <meta content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" name="viewport"/> <link href="resources/images/legato.ico" rel="shortcut icon"/> <link href="resources/images/legato.ico" rel="icon" type="image/x-icon"/> <link href="resources/images/legato.ico" rel="shortcut icon" type="image/x-icon"/> <link href="resources/images/legato.ico" rel="apple-touch-icon" type="image/x-icon"/> <link href="resources/css/style.css" media="screen" rel="stylesheet" type="text/css"/> <link href="resources/css/font-awesome.css" rel="stylesheet" type="text/css"/> <!--[if IE]> <script src="resources/js/html5shiv.js"></script> <script src="resources/js/respond.js"></script> <![endif]--> <script src="https://code.jquery.com/jquery-2.2.3.min.js"></script> <script src="resources/js/main.js"></script> <script src="tocs/Build_Apps_API_Guides.json"></script> </head> <body> <noscript> <input class="modal-closing-trick" id="modal-closing-trick" type="checkbox"/> <div id="nojs"> <label for="modal-closing-trick"> <span>You seem to not have Javascript <a href="http://enable-javascript.com">enabled</a>, so site functionality like the search and navigation tree won't work.</span> </label> </div> </noscript> <div class="wrapper"> <div class="fa fa-bars documentation" id="menu-trigger"></div> <div id="top"> <header> <nav> <a class="navlink" href="/">Introduction</a><a class="navlink selected" href="buildAppsMain.html">Build Apps</a><a class="navlink" href="buildPlatformMain.html">Build Platform</a><a class="navlink" href="aboutMain.html">About</a> </nav> </header> </div> <div class="white" id="menudocumentation"> <header> <a href="/"> <img alt="Back to Legato Homepage" id="logo" src="resources/images/legato_logo.png"/></a> <h2>/ Build Apps</h2> <nav class="secondary"> <a href="buildAppsConcepts.html">Concepts</a><a class="link-selected" href="apiGuidesMain.html">API Guides</a><a href="tools.html">Tools</a><a href="external_proj_mainpage.html">WiFi Plugin</a> </nav> <nav class="ui-front"> <i class="fa fa-search" id="search-icon"></i> <input id="searchbox" placeholder="Search"/> </nav> </header> </div> <div id="resizable"> <div id="left"> <div id="tree1"></div> </div> </div> <div class="content"> <div class="header"> <div class="summary"> <a href="#define-members">Macros</a> | <a href="#typedef-members">Typedefs</a> | <a href="#func-members">Functions</a> </div> <div class="headertitle"> <h1 class="title">le_flash_interface.h File Reference</h1> </div> </div><div class="contents"> <div class="textblock"><code>#include "<a class="el" href="legato_8h_source.html">legato.h</a>"</code><br/> </div> <p><a href="le__flash__interface_8h_source.html">Go to the source code of this file.</a></p> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="define-members"></a> Macros</h2></td></tr> <tr class="memitem:a88870cd753ea312e179d05e6b907b3ec"><td align="right" class="memItemLeft" valign="top">#define </td><td class="memItemRight" valign="bottom"><a class="el" href="le__flash__interface_8h.html#a88870cd753ea312e179d05e6b907b3ec">LE_FLASH_IMAGE_NAME_MAX_LEN</a>   32</td></tr> <tr class="separator:a88870cd753ea312e179d05e6b907b3ec"><td class="memSeparator" colspan="2"> </td></tr> <tr class="memitem:a218731fc7b8388a1cf70e2b28ebcc1dc"><td align="right" class="memItemLeft" valign="top">#define </td><td class="memItemRight" valign="bottom"><a class="el" href="le__flash__interface_8h.html#a218731fc7b8388a1cf70e2b28ebcc1dc">LE_FLASH_IMAGE_NAME_MAX_BYTES</a>   33</td></tr> <tr class="separator:a218731fc7b8388a1cf70e2b28ebcc1dc"><td class="memSeparator" colspan="2"> </td></tr> </table><table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="typedef-members"></a> Typedefs</h2></td></tr> <tr class="memitem:a05155447383d2c0ff254170f4f63ff01"><td align="right" class="memItemLeft" valign="top">typedef void(* </td><td class="memItemRight" valign="bottom"><a class="el" href="le__flash__interface_8h.html#a05155447383d2c0ff254170f4f63ff01">le_flash_DisconnectHandler_t</a>) (void *)</td></tr> <tr class="separator:a05155447383d2c0ff254170f4f63ff01"><td class="memSeparator" colspan="2"> </td></tr> <tr class="memitem:a40ecd021d6dc0a748d2a5a27dab4f9c0"><td align="right" class="memItemLeft" valign="top">typedef struct le_flash_BadImageDetectionHandler * </td><td class="memItemRight" valign="bottom"><a class="el" href="le__flash__interface_8h.html#a40ecd021d6dc0a748d2a5a27dab4f9c0">le_flash_BadImageDetectionHandlerRef_t</a></td></tr> <tr class="separator:a40ecd021d6dc0a748d2a5a27dab4f9c0"><td class="memSeparator" colspan="2"> </td></tr> <tr class="memitem:abab63a8767f0091513f3edbac029705d"><td align="right" class="memItemLeft" valign="top">typedef void(* </td><td class="memItemRight" valign="bottom"><a class="el" href="le__flash__interface_8h.html#abab63a8767f0091513f3edbac029705d">le_flash_BadImageDetectionHandlerFunc_t</a>) (const char *LE_NONNULL imageName, void *contextPtr)</td></tr> <tr class="separator:abab63a8767f0091513f3edbac029705d"><td class="memSeparator" colspan="2"> </td></tr> </table><table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="func-members"></a> Functions</h2></td></tr> <tr class="memitem:a54bc299ab07842170f062e5ab7a13d11"><td align="right" class="memItemLeft" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="le__flash__interface_8h.html#a54bc299ab07842170f062e5ab7a13d11">le_flash_ConnectService</a> (void)</td></tr> <tr class="separator:a54bc299ab07842170f062e5ab7a13d11"><td class="memSeparator" colspan="2"> </td></tr> <tr class="memitem:a1b3e2c090f38b2869bbba6e7d3899c14"><td align="right" class="memItemLeft" valign="top"><a class="el" href="le__basics_8h.html#a1cca095ed6ebab24b57a636382a6c86c">le_result_t</a> </td><td class="memItemRight" valign="bottom"><a class="el" href="le__flash__interface_8h.html#a1b3e2c090f38b2869bbba6e7d3899c14">le_flash_TryConnectService</a> (void)</td></tr> <tr class="separator:a1b3e2c090f38b2869bbba6e7d3899c14"><td class="memSeparator" colspan="2"> </td></tr> <tr class="memitem:abed326ceddfd48fc36cf99182eae8d36"><td align="right" class="memItemLeft" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="le__flash__interface_8h.html#abed326ceddfd48fc36cf99182eae8d36">le_flash_SetServerDisconnectHandler</a> (<a class="el" href="le__flash__interface_8h.html#a05155447383d2c0ff254170f4f63ff01">le_flash_DisconnectHandler_t</a> disconnectHandler, void *contextPtr)</td></tr> <tr class="separator:abed326ceddfd48fc36cf99182eae8d36"><td class="memSeparator" colspan="2"> </td></tr> <tr class="memitem:a2317ee626cffbe20200d329db2c5bebe"><td align="right" class="memItemLeft" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="le__flash__interface_8h.html#a2317ee626cffbe20200d329db2c5bebe">le_flash_DisconnectService</a> (void)</td></tr> <tr class="separator:a2317ee626cffbe20200d329db2c5bebe"><td class="memSeparator" colspan="2"> </td></tr> <tr class="memitem:a95574e6e395ef5dc5877ebf9b4e2a19f"><td align="right" class="memItemLeft" valign="top"><a class="el" href="le__flash__interface_8h.html#a40ecd021d6dc0a748d2a5a27dab4f9c0">le_flash_BadImageDetectionHandlerRef_t</a> </td><td class="memItemRight" valign="bottom"><a class="el" href="le__flash__interface_8h.html#a95574e6e395ef5dc5877ebf9b4e2a19f">le_flash_AddBadImageDetectionHandler</a> (<a class="el" href="le__flash__interface_8h.html#abab63a8767f0091513f3edbac029705d">le_flash_BadImageDetectionHandlerFunc_t</a> handlerPtr, void *contextPtr)</td></tr> <tr class="separator:a95574e6e395ef5dc5877ebf9b4e2a19f"><td class="memSeparator" colspan="2"> </td></tr> <tr class="memitem:a9e395cd7955381a119bd353cc1023554"><td align="right" class="memItemLeft" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="le__flash__interface_8h.html#a9e395cd7955381a119bd353cc1023554">le_flash_RemoveBadImageDetectionHandler</a> (<a class="el" href="le__flash__interface_8h.html#a40ecd021d6dc0a748d2a5a27dab4f9c0">le_flash_BadImageDetectionHandlerRef_t</a> handlerRef)</td></tr> <tr class="separator:a9e395cd7955381a119bd353cc1023554"><td class="memSeparator" colspan="2"> </td></tr> </table> <a id="details" name="details"></a><h2 class="groupheader">Detailed Description</h2> <div class="textblock"><p>Legato <a class="el" href="c_flash.html">Flash API</a> include file.</p> <p class="copyright">Copyright (C) Sierra Wireless Inc. </p> </div><h2 class="groupheader">Macro Definition Documentation</h2> <a class="anchor" id="a218731fc7b8388a1cf70e2b28ebcc1dc"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define LE_FLASH_IMAGE_NAME_MAX_BYTES   33</td> </tr> </table> </div><div class="memdoc"> <p>Image length maximum length. One extra byte is added for the null character. </p> </div> </div> <a class="anchor" id="a88870cd753ea312e179d05e6b907b3ec"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">#define LE_FLASH_IMAGE_NAME_MAX_LEN   32</td> </tr> </table> </div><div class="memdoc"> <p>Image length maximum length. </p> </div> </div> <h2 class="groupheader">Typedef Documentation</h2> <a class="anchor" id="abab63a8767f0091513f3edbac029705d"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">typedef void(* le_flash_BadImageDetectionHandlerFunc_t) (const char *LE_NONNULL imageName,void *contextPtr)</td> </tr> </table> </div><div class="memdoc"> <p>Handler for bad image detection.</p> <dl class="section note"><dt>Note</dt><dd>The image names are platform dependent. </dd></dl> </div> </div> <a class="anchor" id="a40ecd021d6dc0a748d2a5a27dab4f9c0"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">typedef struct le_flash_BadImageDetectionHandler* <a class="el" href="le__flash__interface_8h.html#a40ecd021d6dc0a748d2a5a27dab4f9c0">le_flash_BadImageDetectionHandlerRef_t</a></td> </tr> </table> </div><div class="memdoc"> <p>Reference type used by Add/Remove functions for EVENT 'le_flash_BadImageDetection' </p> </div> </div> <a class="anchor" id="a05155447383d2c0ff254170f4f63ff01"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">typedef void(* le_flash_DisconnectHandler_t) (void *)</td> </tr> </table> </div><div class="memdoc"> <p>Type for handler called when a server disconnects. </p> </div> </div> <h2 class="groupheader">Function Documentation</h2> <a class="anchor" id="a95574e6e395ef5dc5877ebf9b4e2a19f"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname"><a class="el" href="le__flash__interface_8h.html#a40ecd021d6dc0a748d2a5a27dab4f9c0">le_flash_BadImageDetectionHandlerRef_t</a> le_flash_AddBadImageDetectionHandler </td> <td>(</td> <td class="paramtype"><a class="el" href="le__flash__interface_8h.html#abab63a8767f0091513f3edbac029705d">le_flash_BadImageDetectionHandlerFunc_t</a> </td> <td class="paramname"><em>handlerPtr</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">void * </td> <td class="paramname"><em>contextPtr</em> </td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td> </tr> </table> </div><div class="memdoc"> <p>Add handler function for EVENT 'le_flash_BadImageDetection'</p> <p>This event provides information on bad image status. </p> <dl class="params"><dt>Parameters</dt><dd> <table class="params"> <tr><td class="paramdir">[in]</td><td class="paramname">handlerPtr</td><td></td></tr> <tr><td class="paramdir">[in]</td><td class="paramname">contextPtr</td><td></td></tr> </table> </dd> </dl> </div> </div> <a class="anchor" id="a54bc299ab07842170f062e5ab7a13d11"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">void le_flash_ConnectService </td> <td>(</td> <td class="paramtype">void </td> <td class="paramname"></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p>Connect the current client thread to the service providing this API. Block until the service is available.</p> <p>For each thread that wants to use this API, either ConnectService or TryConnectService must be called before any other functions in this API. Normally, ConnectService is automatically called for the main thread, but not for any other thread. For details, see <a class="el" href="apiFilesC.html#apiFilesC_client">Client-specific Functions</a>.</p> <p>This function is created automatically. </p> </div> </div> <a class="anchor" id="a2317ee626cffbe20200d329db2c5bebe"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">void le_flash_DisconnectService </td> <td>(</td> <td class="paramtype">void </td> <td class="paramname"></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p>Disconnect the current client thread from the service providing this API.</p> <p>Normally, this function doesn't need to be called. After this function is called, there's no longer a connection to the service, and the functions in this API can't be used. For details, see <a class="el" href="apiFilesC.html#apiFilesC_client">Client-specific Functions</a>.</p> <p>This function is created automatically. </p> </div> </div> <a class="anchor" id="a9e395cd7955381a119bd353cc1023554"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">void le_flash_RemoveBadImageDetectionHandler </td> <td>(</td> <td class="paramtype"><a class="el" href="le__flash__interface_8h.html#a40ecd021d6dc0a748d2a5a27dab4f9c0">le_flash_BadImageDetectionHandlerRef_t</a> </td> <td class="paramname"><em>handlerRef</em></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p>Remove handler function for EVENT 'le_flash_BadImageDetection' </p> <dl class="params"><dt>Parameters</dt><dd> <table class="params"> <tr><td class="paramdir">[in]</td><td class="paramname">handlerRef</td><td></td></tr> </table> </dd> </dl> </div> </div> <a class="anchor" id="abed326ceddfd48fc36cf99182eae8d36"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">void le_flash_SetServerDisconnectHandler </td> <td>(</td> <td class="paramtype"><a class="el" href="le__flash__interface_8h.html#a05155447383d2c0ff254170f4f63ff01">le_flash_DisconnectHandler_t</a> </td> <td class="paramname"><em>disconnectHandler</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">void * </td> <td class="paramname"><em>contextPtr</em> </td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td> </tr> </table> </div><div class="memdoc"> <p>Set handler called when server disconnection is detected.</p> <p>When a server connection is lost, call this handler then exit with LE_FATAL. If a program wants to continue without exiting, it should call longjmp() from inside the handler. </p> </div> </div> <a class="anchor" id="a1b3e2c090f38b2869bbba6e7d3899c14"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname"><a class="el" href="le__basics_8h.html#a1cca095ed6ebab24b57a636382a6c86c">le_result_t</a> le_flash_TryConnectService </td> <td>(</td> <td class="paramtype">void </td> <td class="paramname"></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p>Try to connect the current client thread to the service providing this API. Return with an error if the service is not available.</p> <p>For each thread that wants to use this API, either ConnectService or TryConnectService must be called before any other functions in this API. Normally, ConnectService is automatically called for the main thread, but not for any other thread. For details, see <a class="el" href="apiFilesC.html#apiFilesC_client">Client-specific Functions</a>.</p> <p>This function is created automatically.</p> <dl class="section return"><dt>Returns</dt><dd><ul> <li>LE_OK if the client connected successfully to the service.</li> <li>LE_UNAVAILABLE if the server is not currently offering the service to which the client is bound.</li> <li>LE_NOT_PERMITTED if the client interface is not bound to any service (doesn't have a binding).</li> <li>LE_COMM_ERROR if the Service Directory cannot be reached. </li> </ul> </dd></dl> </div> </div> </div> <br clear="left"/> </div> </div> <link href="resources/css/jqtree.css" rel="stylesheet" type="text/css"/> <script src="resources/js/tree.jquery.js" type="text/javascript"></script> <script src="resources/js/jquery.cookie.js"></script> <script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script> <link href="resources/css/perfect-scrollbar.min.css" rel="stylesheet"/> <script src="resources/js/perfect-scrollbar.jquery.min.js"></script> </body> </html>
mpl-2.0
Hub-of-all-Things/Rumpel
src/app/settings/settings-page/settings-page.component.ts
649
/* * Copyright (C) 2019 DataSwift Ltd - All Rights Reserved * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * Written by Eleftherios Myteletsis <eleftherios.myteletsis@dataswift.io> 3, 2019 */ import { Component, OnInit } from '@angular/core'; @Component({ selector: 'rum-settings-page', templateUrl: './settings-page.component.html', styleUrls: ['./settings-page.component.scss'] }) export class SettingsPageComponent implements OnInit { constructor() { } ngOnInit() { } }
mpl-2.0
ChicagoDev/Android_CTA_Bus_Tracker
app/src/main/java/io/chicagoan/ctawaittime/SmsStateListener.java
833
/* Created by Blake Gideon. <blake at chicagoan.io> * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package io.chicagoan.ctawaittime; import android.telephony.PhoneStateListener; import android.telephony.ServiceState; public class SmsStateListener extends PhoneStateListener { ServiceState serviceState; public SmsStateListener () { serviceState = new ServiceState(); } @Override public void onServiceStateChanged(ServiceState serviceState) { super.onServiceStateChanged(serviceState); this.serviceState.setState(serviceState.getState()); } public int getState() { return serviceState.getState(); } }
mpl-2.0
nstockton/mapperproxy-mume
mapper/delays.py
3316
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # Future Modules: from __future__ import annotations # Built-in Modules: import threading from collections.abc import Callable from typing import Any, Union class BaseDelay(threading.Thread): """ Implements the base delay class. """ _delays: list[threading.Thread] = [] def __init__( self, duration: float, count: Union[int, None], function: Callable[..., Any], *args: Any, **kwargs: Any, ) -> None: """ Defines the constructor for the object. Args: duration: The amount of time (in seconds) to delay between iterations. count: The number of iterations to delay, or None to repeat indefinitely. function: The function to be called at each iteration. *args: Positional arguments to be passed to the called function. **kwargs: Key-word only arguments to be passed to the called function. """ if count is not None and count < 0: raise ValueError("count must be a positive number or None.") super().__init__() self.daemon: bool = True self._duration: float = duration self._count: Union[int, None] = count self._function: Callable[..., Any] = function self._args: tuple[Any, ...] = args self._kwargs: dict[str, Any] = kwargs self._finished: threading.Event = threading.Event() def stop(self) -> None: """Stops an active delay.""" self._finished.set() def run(self) -> None: try: self._delays.append(self) while not self._finished.is_set() and self._count != 0: self._finished.wait(self._duration) if not self._finished.is_set(): self._function(*self._args, **self._kwargs) if self._count is not None: self._count -= 1 finally: del self._function, self._args, self._kwargs self._delays.remove(self) if not self._finished.is_set(): self.stop() class Delay(BaseDelay): """ Implements a delay which automatically starts upon creation. """ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) self.start() class OneShot(Delay): """ Implements a delay which is run only once. """ def __init__(self, duration: float, function: Callable[..., Any], *args: Any, **kwargs: Any) -> None: """ Defines the constructor for the object. Args: duration: The amount of time (in seconds) to delay. function: The function to be called when the delay completes. *args: Positional arguments to be passed to the called function. **kwargs: Key-word only arguments to be passed to the called function. """ super().__init__(duration, 1, function, *args, **kwargs) class Repeating(Delay): """ Implements a delay which runs indefinitely. """ def __init__(self, duration: float, function: Callable[..., Any], *args: Any, **kwargs: Any) -> None: """ Defines the constructor for the object. Args: duration: The amount of time (in seconds) to delay between iterations. function: The function to be called at each iteration. *args: Positional arguments to be passed to the called function. **kwargs: Key-word only arguments to be passed to the called function. """ super().__init__(duration, None, function, *args, **kwargs)
mpl-2.0
mbrubeck/servo
tests/wpt/web-platform-tests/WebCryptoAPI/generateKey/failures_AES-CTR.https.any.js
108
// META: timeout=long // META: script=../util/helpers.js // META: script=failures.js run_test(["AES-CTR"]);
mpl-2.0
jclgoodwin/bustimes.org.uk
busstops/management/commands/update_search_indexes.py
1072
from tqdm import tqdm from django.core.management.base import BaseCommand from django.db.models import Exists, OuterRef from ...models import Locality, Operator, Service class Command(BaseCommand): def handle(self, *args, **options): for locality in tqdm(Locality.objects.with_documents()): locality.search_vector = locality.document locality.save(update_fields=['search_vector']) has_services = Exists(Service.objects.filter(current=True, operator=OuterRef('pk'))) for operator in tqdm(Operator.objects.with_documents().filter(has_services)): operator.search_vector = operator.document operator.save(update_fields=['search_vector']) print(Operator.objects.filter(~has_services).update(search_vector=None)) for service in tqdm(Service.objects.with_documents().filter(current=True)): service.search_vector = service.document service.save(update_fields=['search_vector']) print(Service.objects.filter(current=False).update(search_vector=None))
mpl-2.0
os2webscanner/os2webscanner
django-os2webscanner/os2webscanner/migrations/0014_auto_20180501_1010.py
408
# -*- coding: utf-8 -*- # Generated by Django 1.11.9 on 2018-05-01 08:10 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('os2webscanner', '0013_auto_20180501_1006'), ] operations = [ migrations.AlterModelTable( name='scan', table='os2webscanner_scan', ), ]
mpl-2.0
Abpaula/ccc
package-res/ccc/core/base/chart/chart.visualRoles.js
7092
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ pvc.BaseChart .add({ /** * A map of {@link pvc.visual.Role} by name. * Do NOT modify the returned object. * @type Object<string,pvc.visual.Role> */ visualRoles: null, /** * The array of all {@link pvc.visual.Role} instances used by the chart. * Do NOT modify the returned array. * @type pvc.visual.Role[] */ visualRoleList: null, /** * The array of all {@link pvc.visual.Role} instances used by the chart * that are considered measures. * @type pvc.visual.Role[] * @private */ _measureVisualRoles: null, /** * Obtains an existing visual role given its name. * An error is thrown if a role with the specified name is not defined. * * The specified name may be: * <ul> * <li>the name of a chart visual role, </li> * <li>the local name of a visual role of the chart's main plot, or</li> * <li>the fully qualified name of a plot's visual role: "<plot name or id>.<local role name>".</li> * </ul> * * @param {string} roleName The visual role name. * @type pvc.visual.Role */ visualRole: function(roleName) { var role = def.getOwn(this.visualRoles, roleName); if(!role) throw def.error.operationInvalid('roleName', "There is no visual role with name '{0}'.", [roleName]); return role; }, /** * Obtains the array of all {@link pvc.visual.Role} instances used by the chart * that are considered measures. * * This is made lazily because the effective "measure" status * depends on the binding of the visual role, and * of it becoming discrete or continuous. * * Do NOT modify the returned array. * * @return {pvc.visual.Role[]} The array of measure visual roles. */ measureVisualRoles: function() { if(this.parent) return this.parent.measureVisualRoles(); return this._measureVisualRoles || (this._measureVisualRoles = this.visualRoleList.filter(function(r) { return r.isBound() && !r.isDiscrete() && r.isMeasure; })); }, measureDimensionsNames: function() { return def.query(this.measureVisualRoles()) .selectMany(function(r) { return r.grouping.dimensionNames(); }) .distinct() .array(); }, /** * Obtains the chart-level visual roles played by a given dimension name, in definition order. * Do NOT modify the returned array. * @param {string} dimName The name of the dimension. * @return {pvc.visual.Role[]} The array of visual roles or <tt>null</tt>, if none. */ visualRolesOf: function(dimName) { var visualRolesByDim = this._visRolesByDim; if(!visualRolesByDim) { visualRolesByDim = this._visRolesByDim = {}; this.visualRoleList.forEach(function(r) { if(!r.plot) { var g = r.grouping; if (g) g.dimensionNames().forEach(function (n) { def.array.lazy(visualRolesByDim, n).push(r); }); } }); } return def.getOwn(visualRolesByDim, dimName, null); }, _constructVisualRoles: function(/*options*/) { var parent = this.parent; if(parent) { this.visualRoles = parent.visualRoles; this.visualRoleList = parent.visualRoleList; } else { this.visualRoles = {}; this.visualRoleList = []; } }, _addVisualRole: function(name, keyArgs) { keyArgs = def.set(keyArgs, 'index', this.visualRoleList.length); var role = new pvc.visual.Role(name, keyArgs), names = [name]; // There's a way to refer to chart visual roles without danger // of matching the main plot's visual roles. if(!role.plot) names.push("$." + name); return this._addVisualRoleCore(role, names); }, _addVisualRoleCore: function(role, names) { if(!names) names = role.name; this.visualRoleList.push(role); if(def.array.is(names)) names.forEach(function(name) { this.visualRoles[name] = role; }, this); else this.visualRoles[names] = role; return role; }, /** * Initializes the chart-level visual roles. * @virtual */ _initChartVisualRoles: function() { this._addVisualRole('multiChart', { defaultDimension: 'multiChart*', requireIsDiscrete: true }); this._addVisualRole('dataPart', { defaultDimension: 'dataPart', requireIsDiscrete: true, requireSingleDimension: true, dimensionDefaults: {isHidden: true, comparer: def.compare} }); }, _getDataPartDimName: function(useDefault) { var role = this.visualRoles.dataPart, preGrouping; return role.isBound() ? role.lastDimensionName() : (preGrouping = role.preBoundGrouping()) ? preGrouping.lastDimensionName() : useDefault ? role.defaultDimensionGroup : null; }, /** * Processes a view specification. * * An error is thrown if the specified view specification does * not have at least one of the properties <i>role</i> or <i>dims</i>. * * @param {Object} viewSpec The view specification. * @param {string} [viewSpec.role] The name of a visual role. * @param {string|string[]} [viewSpec.dims] The name or names of the view's dimensions. */ _processViewSpec: function(viewSpec) { // If not yet processed if(!viewSpec.dimsKeys) { if(viewSpec.role) { var role = this.visualRoles[viewSpec.role], grouping = role && role.grouping; if(grouping) { viewSpec.dimNames = grouping.dimensionNames().slice().sort(); viewSpec.dimsKey = viewSpec.dimNames.join(","); } } else if(viewSpec.dims) { viewSpec.dimNames = viewSpec_normalizeDims(viewSpec.dims); viewSpec.dimsKey = String(viewSpec.dimNames); } else { throw def.error.argumentInvalid( "viewSpec", "Invalid view spec. No 'role' or 'dims' property."); } } } }); // TODO: expand dim* function viewSpec_normalizeDims(dims) { // Assume already normalized if(def.string.is(dims)) dims = dims.split(","); else if(!def.array.is(dims)) throw def.error.argumentInvalid('dims', "Must be a string or an array of strings."); return def.query(dims).distinct().sort().array(); }
mpl-2.0
mdn/webextensions-examples
session-state/background.js
1698
/** * Add a context menu item to borderify the current tab. */ browser.menus.create({ id: "borderify-current-tab", title: "Borderify current tab", contexts: ["all"] }); /** * The borderify CSS. */ const borderCSS = 'body { border: 5px solid red };'; /* * Borderifies the current tab, and, using setTabValue, stores the fact * that this tab was borderified. */ async function borderify() { let tabArray = await browser.tabs.query({currentWindow: true, active: true}); let tabId = tabArray[0].id; await browser.tabs.insertCSS(tabId, {code: borderCSS}); await browser.sessions.setTabValue(tabId, "border-css", borderCSS); } browser.menus.onClicked.addListener(borderify); /* * When new tabs are created, we want to check, using getTabValue, whether * the tab has the borderified state. That would mean it was borderified, then * closed, then reopened, so we want to reapply the borderify CSS. * * But we can't insertCSS in onCreated, it's too early. So instead we make * an onUpdated listener, just for this tab. In onUpdated we check the tab ID, * and if this is our tab, insert the CSS and remove the listener. */ browser.tabs.onCreated.addListener((tab) => { async function borderifyRestored(targetTabId, thisTabId) { if (targetTabId === thisTabId) { let stored = await browser.sessions.getTabValue(targetTabId, "border-css"); if (stored) { let result = await browser.tabs.insertCSS(targetTabId, {code: stored}); } browser.tabs.onUpdated.removeListener(thisBorderifyRestored); } } let thisBorderifyRestored = borderifyRestored.bind(null, tab.id); browser.tabs.onUpdated.addListener(thisBorderifyRestored); });
mpl-2.0
phw198/OutlookGoogleCalendarSync
src/OutlookGoogleCalendarSync/OutlookOgcs/OutlookInterface.cs
1665
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Office.Interop.Outlook; using Google.Apis.Calendar.v3.Data; namespace OutlookGoogleCalendarSync.OutlookOgcs { public interface Interface { void Connect(); void Disconnect(Boolean onlyWhenNoGUI = false); Boolean NoGUIexists(); Folders Folders(); Dictionary<string, MAPIFolder> CalendarFolders(); MAPIFolder UseOutlookCalendar(); void UseOutlookCalendar(MAPIFolder set); NameSpace GetCurrentUser(NameSpace oNS); String CurrentUserSMTP(); String CurrentUserName(); Boolean Offline(); void RefreshCategories(); String GetRecipientEmail(Recipient recipient); OlExchangeConnectionMode ExchangeConnectionMode(); String GetGlobalApptID(AppointmentItem ai); Event IANAtimezone_set(Event ev, AppointmentItem ai); void WindowsTimeZone_get(AppointmentItem ai, out String startTz, out String endTz); AppointmentItem WindowsTimeZone_set(AppointmentItem ai, Event ev, String attr = "Both", Boolean onlyTZattribute = false); /// <summary> /// Filter Outlook Item according to specified filter. /// </summary> /// <param name="outlookItems">Items to be filtered</param> /// <param name="filter">The logic by which to perform filter</param> /// <returns>Filtered items</returns> List<Object> FilterItems(Items outlookItems, String filter); MAPIFolder GetFolderByID(String entryID); void GetAppointmentByID(String entryID, out AppointmentItem ai); } }
mpl-2.0
EvilBeaver/OneScript
src/oscript/MeasureBehavior.cs
1029
/*---------------------------------------------------------- This Source Code Form is subject to the terms of the Mozilla Public License, v.2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. ----------------------------------------------------------*/ using System; using System.Diagnostics; namespace oscript { internal class MeasureBehavior : ExecuteScriptBehavior { public MeasureBehavior(string path, string[] args) : base(path, args) { } public override int Execute() { var sw = new Stopwatch(); Output.WriteLine("Script started: " + DateTime.Now + "\n"); sw.Start(); var exitCode = base.Execute(); sw.Stop(); Output.WriteLine("\nScript completed: " + DateTime.Now); Output.WriteLine("\nDuration: " + sw.Elapsed); return exitCode; } public static AppBehavior Create(CmdLineHelper helper) { var path = helper.Next(); return path != null ? new MeasureBehavior(path, helper.Tail()) : null; } } }
mpl-2.0
servo/doc.servo.org
gleam/gl/fn.MultiTexCoordP2uiv.html
4604
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <meta name="description" content="API documentation for the Rust `MultiTexCoordP2uiv` fn in crate `gleam`."> <meta name="keywords" content="rust, rustlang, rust-lang, MultiTexCoordP2uiv"> <title>gleam::gl::MultiTexCoordP2uiv - Rust</title> <link rel="stylesheet" type="text/css" href="../../rustdoc.css"> <link rel="stylesheet" type="text/css" href="../../main.css"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <nav class="sidebar"> <p class='location'><a href='../index.html'>gleam</a>::<wbr><a href='index.html'>gl</a></p><script>window.sidebarCurrent = {name: 'MultiTexCoordP2uiv', ty: 'fn', relpath: ''};</script><script defer src="sidebar-items.js"></script> </nav> <nav class="sub"> <form class="search-form js-only"> <div class="search-container"> <input class="search-input" name="search" autocomplete="off" placeholder="Click or press ‘S’ to search, ‘?’ for more options…" type="search"> </div> </form> </nav> <section id='main' class="content fn"> <h1 class='fqn'><span class='in-band'>Function <a href='../index.html'>gleam</a>::<wbr><a href='index.html'>gl</a>::<wbr><a class='fn' href=''>MultiTexCoordP2uiv</a></span><span class='out-of-band'><span id='render-detail'> <a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs"> [<span class='inner'>&#x2212;</span>] </a> </span><a id='src-3799' class='srclink' href='../../src/gleam/home/servo/buildbot/slave/doc/build/target/debug/build/gleam-8cc6d4d4d5b87928/out/gl_bindings.rs.html#1788' title='goto source code'>[src]</a></span></h1> <pre class='rust fn'>pub unsafe fn MultiTexCoordP2uiv(texture: <a class='type' href='../../gleam/gl/types/type.GLenum.html' title='gleam::gl::types::GLenum'>GLenum</a>, type_: <a class='type' href='../../gleam/gl/types/type.GLenum.html' title='gleam::gl::types::GLenum'>GLenum</a>, coords: <a class='primitive' href='../../std/primitive.pointer.html'>*const </a><a class='type' href='../../gleam/gl/types/type.GLuint.html' title='gleam::gl::types::GLuint'>GLuint</a>)</pre></section> <section id='search' class="content hidden"></section> <section class="footer"></section> <aside id="help" class="hidden"> <div> <h1 class="hidden">Help</h1> <div class="shortcuts"> <h2>Keyboard Shortcuts</h2> <dl> <dt>?</dt> <dd>Show this help dialog</dd> <dt>S</dt> <dd>Focus the search field</dd> <dt>&larrb;</dt> <dd>Move up in search results</dd> <dt>&rarrb;</dt> <dd>Move down in search results</dd> <dt>&#9166;</dt> <dd>Go to active search result</dd> <dt>+</dt> <dd>Collapse/expand all sections</dd> </dl> </div> <div class="infos"> <h2>Search Tricks</h2> <p> Prefix searches with a type followed by a colon (e.g. <code>fn:</code>) to restrict the search to a given type. </p> <p> Accepted types are: <code>fn</code>, <code>mod</code>, <code>struct</code>, <code>enum</code>, <code>trait</code>, <code>type</code>, <code>macro</code>, and <code>const</code>. </p> <p> Search functions by type signature (e.g. <code>vec -> usize</code> or <code>* -> vec</code>) </p> </div> </div> </aside> <script> window.rootPath = "../../"; window.currentCrate = "gleam"; window.playgroundUrl = ""; </script> <script src="../../jquery.js"></script> <script src="../../main.js"></script> <script defer src="../../search-index.js"></script> </body> </html>
mpl-2.0
HydraInteractive/Hydra
hydra_graphics/include/hydra/view/sdlview.hpp
433
/** * An implementation for the IView, using SDL. * * License: Mozilla Public License Version 2.0 (https://www.mozilla.org/en-US/MPL/2.0/ OR See accompanying file LICENSE) * Authors: * - Dan Printzell */ #pragma once #include <hydra/ext/api.hpp> #include <hydra/view/view.hpp> #include <memory> namespace Hydra::View { namespace SDLView { HYDRA_GRAPHICS_API std::unique_ptr<IView> create(const std::string& title); }; }
mpl-2.0
susaing/doc.servo.org
wayland_kbd/keysyms/constant.XKB_KEY_F28.html
3958
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <meta name="description" content="API documentation for the Rust `XKB_KEY_F28` constant in crate `wayland_kbd`."> <meta name="keywords" content="rust, rustlang, rust-lang, XKB_KEY_F28"> <title>wayland_kbd::keysyms::XKB_KEY_F28 - Rust</title> <link rel="stylesheet" type="text/css" href="../../main.css"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <section class="sidebar"> <p class='location'><a href='../index.html'>wayland_kbd</a>::<wbr><a href='index.html'>keysyms</a></p><script>window.sidebarCurrent = {name: 'XKB_KEY_F28', ty: 'constant', relpath: ''};</script><script defer src="sidebar-items.js"></script> </section> <nav class="sub"> <form class="search-form js-only"> <div class="search-container"> <input class="search-input" name="search" autocomplete="off" placeholder="Click or press ‘S’ to search, ‘?’ for more options…" type="search"> </div> </form> </nav> <section id='main' class="content constant"> <h1 class='fqn'><span class='in-band'><a href='../index.html'>wayland_kbd</a>::<wbr><a href='index.html'>keysyms</a>::<wbr><a class='constant' href=''>XKB_KEY_F28</a></span><span class='out-of-band'><span id='render-detail'> <a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs"> [<span class='inner'>&#x2212;</span>] </a> </span><a id='src-446' class='srclink' href='../../src/wayland_kbd/ffi/keysyms.rs.html#301' title='goto source code'>[src]</a></span></h1> <pre class='rust const'>pub const XKB_KEY_F28: <a href='../../std/primitive.u32.html'>u32</a><code> = </code><code>0xffd9</code></pre></section> <section id='search' class="content hidden"></section> <section class="footer"></section> <div id="help" class="hidden"> <div> <div class="shortcuts"> <h1>Keyboard Shortcuts</h1> <dl> <dt>?</dt> <dd>Show this help dialog</dd> <dt>S</dt> <dd>Focus the search field</dd> <dt>&larrb;</dt> <dd>Move up in search results</dd> <dt>&rarrb;</dt> <dd>Move down in search results</dd> <dt>&#9166;</dt> <dd>Go to active search result</dd> </dl> </div> <div class="infos"> <h1>Search Tricks</h1> <p> Prefix searches with a type followed by a colon (e.g. <code>fn:</code>) to restrict the search to a given type. </p> <p> Accepted types are: <code>fn</code>, <code>mod</code>, <code>struct</code>, <code>enum</code>, <code>trait</code>, <code>type</code>, <code>macro</code>, and <code>const</code>. </p> <p> Search functions by type signature (e.g. <code>vec -> usize</code>) </p> </div> </div> </div> <script> window.rootPath = "../../"; window.currentCrate = "wayland_kbd"; window.playgroundUrl = ""; </script> <script src="../../jquery.js"></script> <script src="../../main.js"></script> <script async src="../../search-index.js"></script> </body> </html>
mpl-2.0
BYU-ODH/vocal-abduction
app/js/Beam.js
8135
define(['Container', 'NumberStyle'], function(Container, NumberStyle) { /** * Percentage, between cow and ship, that the beam should end at * @const * @type number */ var MAX_BEAM_DISTANCE = 100; /** * Percentage, between ship and cow, that the beam should start at * @const * @type number */ var MIN_BEAM_DISTANCE = 0; /** * how long the cow should stay tinted before earning a point * @const * @type number */ var COW_GET_DELAY = 250; /** * The color of the cow when it has been hit by the tractor beam * @type number * @const */ var COW_TINT = 0x77FF77; /** * The saucer profile that measures how close a player is to abducting a cow. * When the player has retrieved a cow, this emits an 'abduct' event. * * @param {Object=} options Configuration options * @param {number=} [options.color] The color for the ship. @see Color * @param {number=} [options.speed=3] how quickly the beam should descend or * ascend, between 1 and 5, 5 being the fastest. * * @example * var b = new Beam(); * b.on('abduct', functon doSomething(){console.log('something'}); * b.active = true; * * @constructor * @name Beam */ function Beam(options) { var _this = this, _ship = new PIXI.Sprite.fromFrame('purpleSaucer.png'), _beam = new PIXI.Sprite.fromFrame('tractorBeam.png'), _cow = new PIXI.Sprite.fromFrame('cowProfile.png'), /** * The color of the ship. @see Color * @name color * @memberof Beam * @type number */ _color, /** * Whether or not the ascent and descent functions should respond. * If this is true, tractor beam will neither ascend nor descend. * The beam will pause momentarily when the cow has been hit. * @type boolean * @private */ _paused = false, /** * How many cows the user has retrieved * @type number * @name points * @memberof Beam */ _points = 0, /** * The holder for the points */ _pointsText = new PIXI.Text(_points, NumberStyle), /** * A number between MIN_BEAM_DISTANCE and MAX_BEAM_DISTANCE, representing how close the beam is to the cow * @private * @memberof Beam * @type number */ _distance = MIN_BEAM_DISTANCE, /** * Whether or not the beam should be descending * @name active * @memberof Beam * @type boolean */ _enabled = false, /** * Maps chosen speeds to times * @type Object */ _speeds = { 1: 1000, 2: 850, 3: 700, 4: 650, 5: 500 }, _ascentInterval = null, _descentInterval = null, /** * The maximum height the beam can be before it touches the cow. * @type number */ _maxBeamHeight = null, options = options || {}, /** * The speed that the tractor beam moves * @memberof Beam * @type number * @name speed */ _speed = _speeds[3]; PIXI.DisplayObjectContainer.call(_this); function _init() { var pad_x = 10; // tall enough to fit the cow, the ship, with room for the beam var box_width = _ship.width + pad_x; var box_height = (_cow.height + _ship.height)*2.5 + 5; var box = new Container('Cow Meter', box_width, box_height); var height = box_height - box.textHeight; _this.addChild(box); _cow.anchor.x = 0.5; _cow.y = height - _cow.height; _cow.x = box_width/2; _ship.anchor.x = 0.5; _ship.x = box_width/2; _ship.y = box.textHeight; _beam.anchor.x = 0.5; _beam.y = _ship.y + _ship.height - 10; _beam.x = box_width/2; _beam.height = 0; _beam.opacity = 0.7; _maxBeamHeight = height - _cow.height - _beam.y; _pointsText.y = _cow.y + _cow.height + 5; _pointsText.x = box.width/2 - _pointsText.width/2 + box.getBounds().x; _this.addChild(_ship); _this.addChild(_beam); _this.addChild(_cow); _this.addChild(_pointsText); window.t = _pointsText; Beam._index++; // so we can dispatch events (@see _retrieveCow) PIXI.EventTarget.call(_this); }; /** * Sets the distance of the tractor beam * @param number value Must be between MIN_BEAM_DISTANCE and MAX_BEAM_DISTANCE * @see score */ function _setDistance(value) { if(Number.parseInt(value) < MIN_BEAM_DISTANCE || Number.parseInt(value) > MAX_BEAM_DISTANCE) { throw "Tractor beam distance must be between " + MIN_BEAM_DISTANCE + '-' + MAX_BEAM_DISTANCE + ". Given: " + value; } _distance = value; _beam.height = (_distance/100)*_maxBeamHeight; }; /** * Sets the speed of the tractor beam * @param number value A number, from 1 to 5, representing how fast the * tractor beam should move * @see speed * @private */ function _setSpeed(value) { var speed = _speeds[value]; if(speed === undefined) { throw "Tractor beam speed must be between 1-5. Given: " + value; } _speed = speed; _resetMotion(); }; /** * Sets the total score * @see points * @private */ function _setPoints(points) { if(isNaN(parseInt(points, 10))) { return; } _points = points;; _pointsText.setText(""+points); } /** * Resets tractor beam's motion, which depends on whether or not the beam * is enabled and the current speed of the beam */ function _resetMotion() { clearInterval(_descentInterval); clearInterval(_ascentInterval); if(_enabled) { _descentInterval = setInterval(_descend, _this.speed); } else { _ascentInterval = setInterval(_ascend, _this.speed); } } /** * Gets the speed of the tractor beam * @return number A number, from 1 to 5, representing how fast the tractor * beam is moving * @see speed */ function _getSpeed() { for(key in _speeds) { if(_speeds[key] === _speed) { return key; } } }; function _ascend() { if(_paused) { return; } if(_distance <= MIN_BEAM_DISTANCE) { return; } _setDistance(_distance-1); }; function _descend() { if(_paused) { return; } if(_distance >= MAX_BEAM_DISTANCE) { _retrieveCow(); return; } _setDistance(_distance+1); }; /** * @param boolean value Whether or not the beam should be enabled */ function _setEnabled(value) { if(value == _enabled) { return; } _enabled = !!value; _resetMotion(); }; /** * Used when a beam hits the cow */ function _retrieveCow() { _paused = true; _cow.tint = COW_TINT; setTimeout(function() { _cow.tint = 0xFFFFFF; _paused = false; _setDistance(MIN_BEAM_DISTANCE); _this.points++; _this.emit({type: 'abduct'}); }, COW_GET_DELAY); }; Object.defineProperties(_this, { color: { enumerable: true, get: function() { return _color; } }, speed: { enumerable: true, get: _getSpeed, set: _setSpeed }, active: { enumerable: true, get: function() { return _enabled; }, set: _setEnabled }, points: { enumerable: true, get: function() { return _points; }, set: _setPoints } }); _init(); }; /** * Keeps track of how many saucers have been created (for colorization's sake) * @type number */ Beam._index = 0; Beam.prototype = Object.create(PIXI.DisplayObjectContainer.prototype); Beam.prototype.constructor = Beam; return Beam; });
mpl-2.0
hashicorp/terraform-provider-google
google/resource_container_aws_node_pool_generated_test.go
11175
// ---------------------------------------------------------------------------- // // *** AUTO GENERATED CODE *** Type: DCL *** // // ---------------------------------------------------------------------------- // // This file is managed by Magic Modules (https://github.com/GoogleCloudPlatform/magic-modules) // and is based on the DCL (https://github.com/GoogleCloudPlatform/declarative-resource-client-library). // Changes will need to be made to the DCL or Magic Modules instead of here. // // We are not currently able to accept contributions to this file. If changes // are required, please file an issue at https://github.com/hashicorp/terraform-provider-google/issues/new/choose // // ---------------------------------------------------------------------------- package google import ( "context" "fmt" dcl "github.com/GoogleCloudPlatform/declarative-resource-client-library/dcl" containeraws "github.com/GoogleCloudPlatform/declarative-resource-client-library/services/google/containeraws" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" "strings" "testing" ) func TestAccContainerAwsNodePool_BasicHandWritten(t *testing.T) { t.Parallel() context := map[string]interface{}{ "aws_acct_id": "111111111111", "aws_db_key": "00000000-0000-0000-0000-17aad2f0f61f", "aws_region": "us-west-2", "aws_sg": "sg-0b3f63cb91b247628", "aws_subnet": "subnet-0b3f63cb91b247628", "aws_vol_key": "00000000-0000-0000-0000-17aad2f0f61f", "aws_vpc": "vpc-0b3f63cb91b247628", "byo_prefix": "mmv2", "project_name": getTestProjectFromEnv(), "project_number": getTestProjectNumberFromEnv(), "service_acct": getTestServiceAccountFromEnv(t), "random_suffix": randString(t, 10), } vcrTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckContainerAwsNodePoolDestroyProducer(t), Steps: []resource.TestStep{ { Config: testAccContainerAwsNodePool_BasicHandWritten(context), }, { ResourceName: "google_container_aws_node_pool.primary", ImportState: true, ImportStateVerify: true, ImportStateVerifyIgnore: []string{"fleet.0.project"}, }, { Config: testAccContainerAwsNodePool_BasicHandWrittenUpdate0(context), }, { ResourceName: "google_container_aws_node_pool.primary", ImportState: true, ImportStateVerify: true, ImportStateVerifyIgnore: []string{"fleet.0.project"}, }, }, }) } func testAccContainerAwsNodePool_BasicHandWritten(context map[string]interface{}) string { return Nprintf(` data "google_container_aws_versions" "versions" { project = "%{project_name}" location = "us-west1" } resource "google_container_aws_cluster" "primary" { authorization { admin_users { username = "%{service_acct}" } } aws_region = "%{aws_region}" control_plane { aws_services_authentication { role_arn = "arn:aws:iam::%{aws_acct_id}:role/%{byo_prefix}-1p-dev-oneplatform" role_session_name = "%{byo_prefix}-1p-dev-session" } config_encryption { kms_key_arn = "arn:aws:kms:%{aws_region}:%{aws_acct_id}:key/%{aws_db_key}" } database_encryption { kms_key_arn = "arn:aws:kms:%{aws_region}:%{aws_acct_id}:key/%{aws_db_key}" } iam_instance_profile = "%{byo_prefix}-1p-dev-controlplane" subnet_ids = ["%{aws_subnet}"] version = "${data.google_container_aws_versions.versions.valid_versions[0]}" instance_type = "t3.medium" main_volume { iops = 3000 kms_key_arn = "arn:aws:kms:%{aws_region}:%{aws_acct_id}:key/%{aws_vol_key}" size_gib = 10 volume_type = "GP3" } proxy_config { secret_arn = "arn:aws:secretsmanager:us-west-2:126285863215:secret:proxy_config20210824150329476300000001-ABCDEF" secret_version = "12345678-ABCD-EFGH-IJKL-987654321098" } root_volume { iops = 3000 kms_key_arn = "arn:aws:kms:%{aws_region}:%{aws_acct_id}:key/%{aws_vol_key}" size_gib = 10 volume_type = "GP3" } security_group_ids = ["%{aws_sg}"] ssh_config { ec2_key_pair = "%{byo_prefix}-1p-dev-ssh" } tags = { owner = "%{service_acct}" } } fleet { project = "%{project_number}" } location = "us-west1" name = "tf-test-name%{random_suffix}" networking { pod_address_cidr_blocks = ["10.2.0.0/16"] service_address_cidr_blocks = ["10.1.0.0/16"] vpc_id = "%{aws_vpc}" } annotations = { label-one = "value-one" } description = "A sample aws cluster" project = "%{project_name}" } resource "google_container_aws_node_pool" "primary" { autoscaling { max_node_count = 5 min_node_count = 1 } cluster = google_container_aws_cluster.primary.name config { config_encryption { kms_key_arn = "arn:aws:kms:%{aws_region}:%{aws_acct_id}:key/%{aws_db_key}" } iam_instance_profile = "%{byo_prefix}-1p-dev-nodepool" instance_type = "t3.medium" labels = { label-one = "value-one" } root_volume { iops = 3000 kms_key_arn = "arn:aws:kms:%{aws_region}:%{aws_acct_id}:key/%{aws_vol_key}" size_gib = 10 volume_type = "GP3" } security_group_ids = ["%{aws_sg}"] ssh_config { ec2_key_pair = "%{byo_prefix}-1p-dev-ssh" } tags = { tag-one = "value-one" } taints { effect = "PREFER_NO_SCHEDULE" key = "taint-key" value = "taint-value" } } location = "us-west1" max_pods_constraint { max_pods_per_node = 110 } name = "tf-test-node-pool-name%{random_suffix}" subnet_id = "%{aws_subnet}" version = "${data.google_container_aws_versions.versions.valid_versions[0]}" annotations = { label-one = "value-one" } project = "%{project_name}" } `, context) } func testAccContainerAwsNodePool_BasicHandWrittenUpdate0(context map[string]interface{}) string { return Nprintf(` data "google_container_aws_versions" "versions" { project = "%{project_name}" location = "us-west1" } resource "google_container_aws_cluster" "primary" { authorization { admin_users { username = "%{service_acct}" } } aws_region = "%{aws_region}" control_plane { aws_services_authentication { role_arn = "arn:aws:iam::%{aws_acct_id}:role/%{byo_prefix}-1p-dev-oneplatform" role_session_name = "%{byo_prefix}-1p-dev-session" } config_encryption { kms_key_arn = "arn:aws:kms:%{aws_region}:%{aws_acct_id}:key/%{aws_db_key}" } database_encryption { kms_key_arn = "arn:aws:kms:%{aws_region}:%{aws_acct_id}:key/%{aws_db_key}" } iam_instance_profile = "%{byo_prefix}-1p-dev-controlplane" subnet_ids = ["%{aws_subnet}"] version = "${data.google_container_aws_versions.versions.valid_versions[0]}" instance_type = "t3.medium" main_volume { iops = 3000 kms_key_arn = "arn:aws:kms:%{aws_region}:%{aws_acct_id}:key/%{aws_vol_key}" size_gib = 10 volume_type = "GP3" } proxy_config { secret_arn = "arn:aws:secretsmanager:us-west-2:126285863215:secret:proxy_config20210824150329476300000001-ABCDEF" secret_version = "12345678-ABCD-EFGH-IJKL-987654321098" } root_volume { iops = 3000 kms_key_arn = "arn:aws:kms:%{aws_region}:%{aws_acct_id}:key/%{aws_vol_key}" size_gib = 10 volume_type = "GP3" } security_group_ids = ["%{aws_sg}"] ssh_config { ec2_key_pair = "%{byo_prefix}-1p-dev-ssh" } tags = { owner = "%{service_acct}" } } fleet { project = "%{project_number}" } location = "us-west1" name = "tf-test-name%{random_suffix}" networking { pod_address_cidr_blocks = ["10.2.0.0/16"] service_address_cidr_blocks = ["10.1.0.0/16"] vpc_id = "%{aws_vpc}" } annotations = { label-one = "value-one" } description = "A sample aws cluster" project = "%{project_name}" } resource "google_container_aws_node_pool" "primary" { autoscaling { max_node_count = 5 min_node_count = 1 } cluster = google_container_aws_cluster.primary.name config { config_encryption { kms_key_arn = "arn:aws:kms:%{aws_region}:%{aws_acct_id}:key/%{aws_db_key}" } iam_instance_profile = "%{byo_prefix}-1p-dev-nodepool" instance_type = "t3.medium" labels = { label-one = "value-one" } root_volume { iops = 3000 kms_key_arn = "arn:aws:kms:%{aws_region}:%{aws_acct_id}:key/%{aws_vol_key}" size_gib = 10 volume_type = "GP3" } security_group_ids = ["%{aws_sg}"] ssh_config { ec2_key_pair = "%{byo_prefix}-1p-dev-ssh" } tags = { tag-one = "value-one" } taints { effect = "PREFER_NO_SCHEDULE" key = "taint-key" value = "taint-value" } } location = "us-west1" max_pods_constraint { max_pods_per_node = 110 } name = "tf-test-node-pool-name%{random_suffix}" subnet_id = "%{aws_subnet}" version = "${data.google_container_aws_versions.versions.valid_versions[0]}" annotations = { label-two = "value-two" } project = "%{project_name}" } `, context) } func testAccCheckContainerAwsNodePoolDestroyProducer(t *testing.T) func(s *terraform.State) error { return func(s *terraform.State) error { for name, rs := range s.RootModule().Resources { if rs.Type != "rs.google_container_aws_node_pool" { continue } if strings.HasPrefix(name, "data.") { continue } config := googleProviderConfig(t) billingProject := "" if config.BillingProject != "" { billingProject = config.BillingProject } obj := &containeraws.NodePool{ Cluster: dcl.String(rs.Primary.Attributes["cluster"]), Location: dcl.String(rs.Primary.Attributes["location"]), Name: dcl.String(rs.Primary.Attributes["name"]), SubnetId: dcl.String(rs.Primary.Attributes["subnet_id"]), Version: dcl.String(rs.Primary.Attributes["version"]), Project: dcl.StringOrNil(rs.Primary.Attributes["project"]), CreateTime: dcl.StringOrNil(rs.Primary.Attributes["create_time"]), Etag: dcl.StringOrNil(rs.Primary.Attributes["etag"]), Reconciling: dcl.Bool(rs.Primary.Attributes["reconciling"] == "true"), State: containeraws.NodePoolStateEnumRef(rs.Primary.Attributes["state"]), Uid: dcl.StringOrNil(rs.Primary.Attributes["uid"]), UpdateTime: dcl.StringOrNil(rs.Primary.Attributes["update_time"]), } client := NewDCLContainerAwsClient(config, config.userAgent, billingProject, 0) _, err := client.GetNodePool(context.Background(), obj) if err == nil { return fmt.Errorf("google_container_aws_node_pool still exists %v", obj) } } return nil } }
mpl-2.0
SparkleNetworks/SparkleNetworks
src/SparkleNetworks.Database/Schema Objects/Schemas/dbo/Tables/CompanyProfileFields.table.sql
1205
 -- Resulting entity class must implement IProfileFieldValue CREATE TABLE [dbo].CompanyProfileFields ( [Id] INT NOT NULL IDENTITY (1, 1), CompanyId INT NOT NULL, -- [ProfileFieldId] INT NOT NULL, -- [Value] NVARCHAR(MAX) NOT NULL, -- main/display value [DateCreatedUtc] SMALLDATETIME NOT NULL, -- [DateUpdatedUtc] SMALLDATETIME NULL, -- [UpdateCount] SMALLINT NOT NULL DEFAULT 0, -- nuber of changes of this field [Source] TINYINT NOT NULL DEFAULT 1, -- latest source for the value (user input, linkedin, ...) Data NVARCHAR(MAX) NULL, -- extra JSON'ish data: serialized string CONSTRAINT [PK_dbo_CompanyProfileFields] PRIMARY KEY CLUSTERED ([Id] ASC), CONSTRAINT [FK_dbo_CompanyProfileFields_Users] FOREIGN KEY (CompanyId) REFERENCES [dbo].Companies ([Id]), CONSTRAINT [FK_dbo_CompanyProfileFields_ProfileFields] FOREIGN KEY ([ProfileFieldId]) REFERENCES [dbo].[ProfileFields] ([Id]), ) GO
mpl-2.0
hashicorp/consul
agent/structs/structs_oss.go
5467
//go:build !consulent // +build !consulent package structs import ( "hash" "github.com/hashicorp/consul/acl" "github.com/hashicorp/consul/types" ) var emptyEnterpriseMeta = EnterpriseMeta{} // EnterpriseMeta stub type EnterpriseMeta struct{} func (m *EnterpriseMeta) ToEnterprisePolicyMeta() *acl.EnterprisePolicyMeta { return nil } func (m *EnterpriseMeta) estimateSize() int { return 0 } func (m *EnterpriseMeta) addToHash(_ hash.Hash, _ bool) { // do nothing } func (m *EnterpriseMeta) Merge(_ *EnterpriseMeta) { // do nothing } func (m *EnterpriseMeta) MergeNoWildcard(_ *EnterpriseMeta) { // do nothing } func (m *EnterpriseMeta) Matches(_ *EnterpriseMeta) bool { return true } func (m *EnterpriseMeta) IsSame(_ *EnterpriseMeta) bool { return true } func (m *EnterpriseMeta) LessThan(_ *EnterpriseMeta) bool { return false } func (m *EnterpriseMeta) WithWildcardNamespace() *EnterpriseMeta { return &emptyEnterpriseMeta } func (m *EnterpriseMeta) UnsetPartition() { // do nothing } // TODO(partition): stop using this func NewEnterpriseMetaInDefaultPartition(_ string) EnterpriseMeta { return emptyEnterpriseMeta } func NewEnterpriseMetaWithPartition(_, _ string) EnterpriseMeta { return emptyEnterpriseMeta } func (m *EnterpriseMeta) NamespaceOrDefault() string { return IntentionDefaultNamespace } func NamespaceOrDefault(_ string) string { return IntentionDefaultNamespace } func (m *EnterpriseMeta) NamespaceOrEmpty() string { return "" } func (m *EnterpriseMeta) InDefaultNamespace() bool { return true } func (m *EnterpriseMeta) PartitionOrDefault() string { return "default" } func EqualPartitions(_, _ string) bool { return true } func IsDefaultPartition(partition string) bool { return true } func PartitionOrDefault(_ string) string { return "default" } func (m *EnterpriseMeta) PartitionOrEmpty() string { return "" } func (m *EnterpriseMeta) InDefaultPartition() bool { return true } // ReplicationEnterpriseMeta stub func ReplicationEnterpriseMeta() *EnterpriseMeta { return &emptyEnterpriseMeta } // TODO(partition): stop using this func DefaultEnterpriseMetaInDefaultPartition() *EnterpriseMeta { return &emptyEnterpriseMeta } // DefaultEnterpriseMetaInPartition stub func DefaultEnterpriseMetaInPartition(_ string) *EnterpriseMeta { return &emptyEnterpriseMeta } func NodeEnterpriseMetaInPartition(_ string) *EnterpriseMeta { return &emptyEnterpriseMeta } // TODO(partition): stop using this func NodeEnterpriseMetaInDefaultPartition() *EnterpriseMeta { return &emptyEnterpriseMeta } // TODO(partition): stop using this func WildcardEnterpriseMetaInDefaultPartition() *EnterpriseMeta { return &emptyEnterpriseMeta } // WildcardEnterpriseMetaInPartition stub func WildcardEnterpriseMetaInPartition(_ string) *EnterpriseMeta { return &emptyEnterpriseMeta } // FillAuthzContext stub func (_ *EnterpriseMeta) FillAuthzContext(_ *acl.AuthorizerContext) {} func (_ *Node) FillAuthzContext(_ *acl.AuthorizerContext) {} func (_ *Coordinate) FillAuthzContext(_ *acl.AuthorizerContext) {} func (_ *NodeInfo) FillAuthzContext(_ *acl.AuthorizerContext) {} func (_ *EnterpriseMeta) Normalize() {} // FillAuthzContext stub func (_ *DirEntry) FillAuthzContext(_ *acl.AuthorizerContext) {} // FillAuthzContext stub func (_ *RegisterRequest) FillAuthzContext(_ *acl.AuthorizerContext) {} func (_ *RegisterRequest) GetEnterpriseMeta() *EnterpriseMeta { return nil } // OSS Stub func (op *TxnNodeOp) FillAuthzContext(ctx *acl.AuthorizerContext) {} // OSS Stub func (_ *TxnServiceOp) FillAuthzContext(_ *acl.AuthorizerContext) {} // OSS Stub func (_ *TxnCheckOp) FillAuthzContext(_ *acl.AuthorizerContext) {} func NodeNameString(node string, _ *EnterpriseMeta) string { return node } func ServiceIDString(id string, _ *EnterpriseMeta) string { return id } func ParseServiceIDString(input string) (string, *EnterpriseMeta) { return input, DefaultEnterpriseMetaInDefaultPartition() } func (sid ServiceID) String() string { return sid.ID } func ServiceIDFromString(input string) ServiceID { id, _ := ParseServiceIDString(input) return ServiceID{ID: id} } func ParseServiceNameString(input string) (string, *EnterpriseMeta) { return input, DefaultEnterpriseMetaInDefaultPartition() } func (n ServiceName) String() string { return n.Name } func ServiceNameFromString(input string) ServiceName { id, _ := ParseServiceNameString(input) return ServiceName{Name: id} } func (cid CheckID) String() string { return string(cid.ID) } func (_ *HealthCheck) Validate() error { return nil } func enterpriseRequestType(m MessageType) (string, bool) { return "", false } // CheckIDs returns the IDs for all checks associated with a session, regardless of type func (s *Session) CheckIDs() []types.CheckID { // Merge all check IDs into a single slice, since they will be handled the same way checks := make([]types.CheckID, 0, len(s.Checks)+len(s.NodeChecks)+len(s.ServiceChecks)) checks = append(checks, s.Checks...) for _, c := range s.NodeChecks { checks = append(checks, types.CheckID(c)) } for _, c := range s.ServiceChecks { checks = append(checks, types.CheckID(c.ID)) } return checks } func (t *Intention) HasWildcardSource() bool { return t.SourceName == WildcardSpecifier } func (t *Intention) HasWildcardDestination() bool { return t.DestinationName == WildcardSpecifier } func (s *ServiceNode) NodeIdentity() Identity { return Identity{ID: s.Node} }
mpl-2.0
heliogabalo/The-side-of-the-source
Codigo/Games/Efects/3D-wirelib/wirelib.js
7221
var wirelib = (function() { var canvas, context, width, height, lines = [], cx, cy, cz, fl = 250, interval, loopCallback, running; function initWithCanvas(aCanvas) { canvas = aCanvas; if(canvas !== undefined) { width = canvas.width; height = canvas.height; cx = width / 2; cy = height / 2; cz = fl * 2; context = canvas.getContext("2d"); } } // fl stands for Focal length function project(p3d) { var p2d = {}, scale = fl / (fl + p3d.z + cz); p2d.x = cx + p3d.x * scale; p2d.y = cy + p3d.y * scale; return p2d; } function addLine() { var i, numPoints, points, line; points = (typeof arguments[0] === "object") ? arguments[0] : arguments; numPoints = points.length; if(numPoints >= 6) { line = {style:this.strokeStyle, width:this.lineWidth, points:[]}; lines.push(line); for(i = 0; i < numPoints; i += 3) { line.points.push({x:points[i], y:points[i + 1], z:points[i + 2]}); } } else { console.error("wirelib.addLine: You need to add at least two 3d points (6 numbers) to make a line."); } return line; } function addBox(x, y, z, w, h, d) { this.addLine(x - w / 2, y - h / 2, z - d / 2, x + w / 2, y - h / 2, z - d / 2, x + w / 2, y + h / 2, z - d / 2, x - w / 2, y + h / 2, z - d / 2, x - w / 2, y - h / 2, z - d / 2); this.addLine(x - w / 2, y - h / 2, z + d / 2, x + w / 2, y - h / 2, z + d / 2, x + w / 2, y + h / 2, z + d / 2, x - w / 2, y + h / 2, z + d / 2, x - w / 2, y - h / 2, z + d / 2); this.addLine(x - w / 2, y - h / 2, z - d / 2, x - w / 2, y - h / 2, z + d / 2); this.addLine(x + w / 2, y - h / 2, z - d / 2, x + w / 2, y - h / 2, z + d / 2); this.addLine(x + w / 2, y + h / 2, z - d / 2, x + w / 2, y + h / 2, z + d / 2); this.addLine(x - w / 2, y + h / 2, z - d / 2, x - w / 2, y + h / 2, z + d / 2); } function addRect(x, y, z, w, h) { this.addLine(x - w / 2, y - h / 2, z, x + w / 2, y - h / 2, z, x + w / 2, y + h / 2, z, x - w / 2, y + h / 2, z, x - w / 2, y - h / 2, z); } function addCircle(x, y, z, radius, segments) { var i, points = [], a; for(i = 0; i < segments; i += 1) { a = Math.PI * 2 * i / segments; points.push(x + Math.cos(a) * radius, y + Math.sin(a) * radius, z); } points.push(points[0], points[1], points[2]); this.addLine(points); } function draw() { var i, j, line, p2d; if(this.clearCanvas) { context.clearRect(0, 0, width, height); } for(i = 0; i < lines.length; i += 1) { context.beginPath(); line = lines[i]; p2d = project(line.points[0]); context.moveTo(p2d.x, p2d.y); for(j = 1; j < line.points.length; j += 1) { p2d = project(line.points[j]); context.lineTo(p2d.x, p2d.y); } context.lineWidth = line.width; context.strokeStyle = line.style; context.stroke(); } if(this.showCenter) { p2d = project({x:0, y:0, z:0}); context.strokeStyle = "#ff0000"; context.lineWidth = 0.5; context.beginPath(); context.arc(p2d.x, p2d.y, 5, 0, Math.PI * 2, false); context.stroke(); } } function loop(fps, callback) { if(!running) { var wl = this; running = true; loopCallback = callback; interval = setInterval(function() { loopCallback(); wl.draw(); }, 1000 / fps); } } function stop() { running = false; clearInterval(interval); } function rotateX(radians) { var i, j, p, y1, z1, line, cos = Math.cos(radians), sin = Math.sin(radians); for(i = 0; i < lines.length; i += 1) { line = lines[i]; for(j = 0; j < line.points.length; j += 1) { p = line.points[j]; y1 = p.y * cos - p.z * sin; z1 = p.z * cos + p.y * sin; p.y = y1; p.z = z1; } } } function rotateY(radians) { var i, j, p, x1, z1, line, cos = Math.cos(radians), sin = Math.sin(radians); for(i = 0; i < lines.length; i += 1) { line = lines[i]; for(j = 0; j < line.points.length; j += 1) { p = line.points[j]; z1 = p.z * cos - p.x * sin; x1 = p.x * cos + p.z * sin; p.x = x1; p.z = z1; } } } function rotateZ(radians) { var i, j, p, x1, y1, line, cos = Math.cos(radians), sin = Math.sin(radians); for(i = 0; i < lines.length; i += 1) { line = lines[i]; for(j = 0; j < line.points.length; j += 1) { p = line.points[j]; y1 = p.y * cos - p.x * sin; x1 = p.x * cos + p.y * sin; p.x = x1; p.y = y1; } } } function translate(x, y, z) { var i, j, p, line; for(i = 0; i < lines.length; i += 1) { line = lines[i]; for(j = 0; j < line.points.length; j += 1) { p = line.points[j]; p.x += x; p.y += y; p.z += z; } } } function jitter(amount) { var i, j, line; for(i = 0; i < lines.length; i += 1) { line = lines[i]; for(j = 0; j < line.points.length; j += 1) { p = line.points[j]; p.x += Math.random() * amount * 2 - amount; p.y += Math.random() * amount * 2 - amount; p.z += Math.random() * amount * 2 - amount; } } } function setCenter(x, y, z) { cx = x === null ? cx : x; cy = y === null ? cy : y; cz = z === null ? cz : z; } return {initWithCanvas:initWithCanvas, addLine:addLine, addBox:addBox, addRect:addRect, addCircle:addCircle, draw:draw, rotateX:rotateX, rotateY:rotateY, rotateZ:rotateZ, translate:translate, jitter:jitter, clearCanvas:true, strokeStyle:"#000000", lineWidth:1, loop:loop, stop:stop, showCenter:false, setCenter:setCenter }; }());
mpl-2.0
drewt/navi-scheme
lib.h
4523
/* Copyright 2014-2015 Drew Thoreson * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef _NAVI_LIB_H #define _NAVI_LIB_H #include "internal.h" #include "macros.h" DECLARE(lambda); DECLARE(caselambda); DECLARE(define); DECLARE(define_syntax); DECLARE(define_values); DECLARE(defmacro); DECLARE(define_library); DECLARE(import); DECLARE(begin); DECLARE(include); DECLARE(include_ci); DECLARE(let); DECLARE(sequential_let); DECLARE(let_values); DECLARE(set); DECLARE(quote); DECLARE(unquote); DECLARE(quasiquote); DECLARE(case); DECLARE(cond); DECLARE(if); DECLARE(and); DECLARE(or); DECLARE(delay); DECLARE(make_parameter); DECLARE(parameterize); DECLARE(command_line); DECLARE(emergency_exit); DECLARE(exit); DECLARE(get_environment_variable); DECLARE(get_environment_variables); DECLARE(current_second); DECLARE(current_jiffy); DECLARE(jiffies_per_second); DECLARE(gensym); DECLARE(eval); DECLARE(apply); DECLARE(force); DECLARE(promisep); DECLARE(make_promise); DECLARE(call_ec); DECLARE(values); DECLARE(call_with_values); DECLARE(with_exception_handler); DECLARE(raise); DECLARE(raise_continuable); DECLARE(error); DECLARE(error_objectp); DECLARE(error_object_message); DECLARE(error_object_irritants); DECLARE(read_errorp); DECLARE(input_portp); DECLARE(output_portp); DECLARE(portp); DECLARE(input_port_openp); DECLARE(output_port_openp); DECLARE(current_input_port); DECLARE(current_output_port); DECLARE(current_error_port); DECLARE(open_input_file); DECLARE(open_output_file); DECLARE(open_input_string); DECLARE(open_output_string); DECLARE(get_output_string); DECLARE(close_port); DECLARE(close_input_port); DECLARE(close_output_port); DECLARE(eof_objectp); DECLARE(eof_object); DECLARE(read_u8); DECLARE(peek_u8); DECLARE(read_char); DECLARE(peek_char); DECLARE(read); DECLARE(write_u8); DECLARE(write_char); DECLARE(write_string); DECLARE(write); DECLARE(display); DECLARE(newline); DECLARE(eqvp); DECLARE(eqp); DECLARE(equalp); DECLARE(add); DECLARE(sub); DECLARE(mul); DECLARE(div); DECLARE(quotient); DECLARE(remainder); DECLARE(lt); DECLARE(gt); DECLARE(lte); DECLARE(gte); DECLARE(numeq); DECLARE(zerop); DECLARE(positivep); DECLARE(negativep); DECLARE(oddp); DECLARE(evenp); DECLARE(number_to_string); DECLARE(string_to_number); DECLARE(not); DECLARE(booleanp); DECLARE(boolean_eq); DECLARE(cons); DECLARE(car); DECLARE(cdr); DECLARE(set_car); DECLARE(set_cdr); DECLARE(pairp); DECLARE(listp); DECLARE(nullp); DECLARE(list); DECLARE(make_list); DECLARE(length); DECLARE(append); DECLARE(reverse); DECLARE(list_tail); DECLARE(list_ref); DECLARE(list_set); DECLARE(memq); DECLARE(memv); DECLARE(member); DECLARE(assq); DECLARE(assv); DECLARE(assoc); DECLARE(list_copy); DECLARE(for_each); DECLARE(map); DECLARE(charp); DECLARE(char_lt); DECLARE(char_gt); DECLARE(char_eq); DECLARE(char_lte); DECLARE(char_gte); DECLARE(char_ci_lt); DECLARE(char_ci_gt); DECLARE(char_ci_eq); DECLARE(char_ci_lte); DECLARE(char_ci_gte); DECLARE(char_upcase); DECLARE(char_downcase); DECLARE(stringp); DECLARE(make_string); DECLARE(string_length); DECLARE(string); DECLARE(string_ref); DECLARE(string_set); DECLARE(string_lt); DECLARE(string_gt); DECLARE(string_eq); DECLARE(string_lte); DECLARE(string_gte); DECLARE(string_ci_lt); DECLARE(string_ci_gt); DECLARE(string_ci_eq); DECLARE(string_ci_lte); DECLARE(string_ci_gte); DECLARE(string_upcase); DECLARE(string_downcase); DECLARE(string_foldcase); DECLARE(substring); DECLARE(string_append); DECLARE(string_to_list); DECLARE(list_to_string); DECLARE(string_to_vector); DECLARE(vector_to_string); DECLARE(string_fill); DECLARE(string_copy); DECLARE(string_copy_to); DECLARE(vectorp); DECLARE(make_vector); DECLARE(vector); DECLARE(vector_length); DECLARE(vector_ref); DECLARE(vector_set); DECLARE(vector_to_list); DECLARE(list_to_vector); DECLARE(vector_fill); DECLARE(vector_copy); DECLARE(vector_copy_to); DECLARE(vector_for_each); DECLARE(vector_map); DECLARE(vector_map_ip); DECLARE(bytevectorp); DECLARE(make_bytevector); DECLARE(bytevector); DECLARE(bytevector_length); DECLARE(bytevector_u8_ref); DECLARE(bytevector_u8_set); DECLARE(bytevector_append); DECLARE(bytevector_copy); DECLARE(bytevector_copy_to); DECLARE(utf8_to_string); DECLARE(string_to_utf8); DECLARE(env_list); DECLARE(env_count); DECLARE(env_show); DECLARE(gc_collect); DECLARE(gc_count); DECLARE(gc_stats); #endif
mpl-2.0
adrienlauer/seed
web/core/src/main/java/org/seedstack/seed/web/internal/websocket/SeedClientEndpointConfigurator.java
837
/** * Copyright (c) 2013-2016, The SeedStack authors <http://seedstack.org> * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.seedstack.seed.web.internal.websocket; import com.google.inject.Injector; import javax.inject.Inject; import javax.websocket.ClientEndpointConfig; /** * Endpoint configurator that makes WebSocket client endpoints injectable. */ public class SeedClientEndpointConfigurator extends ClientEndpointConfig.Configurator { @Inject private static Injector injector; /** * Creates the endpoint configurator. */ public SeedClientEndpointConfigurator() { super(); injector.injectMembers(this); } }
mpl-2.0
mdn/webextensions-examples
http-response/background.js
667
function listener(details) { let filter = browser.webRequest.filterResponseData(details.requestId); let decoder = new TextDecoder("utf-8"); let encoder = new TextEncoder(); filter.ondata = event => { let str = decoder.decode(event.data, {stream: true}); // Just change any instance of Example in the HTTP response // to WebExtension Example. str = str.replace(/Example/g, 'WebExtension Example'); filter.write(encoder.encode(str)); filter.disconnect(); } return {}; } browser.webRequest.onBeforeRequest.addListener( listener, {urls: ["https://example.com/*"], types: ["main_frame"]}, ["blocking"] );
mpl-2.0
brendanhay/gogol
gogol-android-enterprise/gen/Network/Google/Resource/AndroidEnterprise/Devices/Update.hs
7071
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.AndroidEnterprise.Devices.Update -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Updates the device policy. To ensure the policy is properly enforced, -- you need to prevent unmanaged accounts from accessing Google Play by -- setting the allowed_accounts in the managed configuration for the Google -- Play package. See restrict accounts in Google Play. When provisioning a -- new device, you should set the device policy using this method before -- adding the managed Google Play Account to the device, otherwise the -- policy will not be applied for a short period of time after adding the -- account to the device. -- -- /See:/ <https://developers.google.com/android/work/play/emm-api Google Play EMM API Reference> for @androidenterprise.devices.update@. module Network.Google.Resource.AndroidEnterprise.Devices.Update ( -- * REST Resource DevicesUpdateResource -- * Creating a Request , devicesUpdate , DevicesUpdate -- * Request Lenses , duXgafv , duUploadProtocol , duUpdateMask , duEnterpriseId , duAccessToken , duUploadType , duPayload , duUserId , duDeviceId , duCallback ) where import Network.Google.AndroidEnterprise.Types import Network.Google.Prelude -- | A resource alias for @androidenterprise.devices.update@ method which the -- 'DevicesUpdate' request conforms to. type DevicesUpdateResource = "androidenterprise" :> "v1" :> "enterprises" :> Capture "enterpriseId" Text :> "users" :> Capture "userId" Text :> "devices" :> Capture "deviceId" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "updateMask" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] Device :> Put '[JSON] Device -- | Updates the device policy. To ensure the policy is properly enforced, -- you need to prevent unmanaged accounts from accessing Google Play by -- setting the allowed_accounts in the managed configuration for the Google -- Play package. See restrict accounts in Google Play. When provisioning a -- new device, you should set the device policy using this method before -- adding the managed Google Play Account to the device, otherwise the -- policy will not be applied for a short period of time after adding the -- account to the device. -- -- /See:/ 'devicesUpdate' smart constructor. data DevicesUpdate = DevicesUpdate' { _duXgafv :: !(Maybe Xgafv) , _duUploadProtocol :: !(Maybe Text) , _duUpdateMask :: !(Maybe Text) , _duEnterpriseId :: !Text , _duAccessToken :: !(Maybe Text) , _duUploadType :: !(Maybe Text) , _duPayload :: !Device , _duUserId :: !Text , _duDeviceId :: !Text , _duCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'DevicesUpdate' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'duXgafv' -- -- * 'duUploadProtocol' -- -- * 'duUpdateMask' -- -- * 'duEnterpriseId' -- -- * 'duAccessToken' -- -- * 'duUploadType' -- -- * 'duPayload' -- -- * 'duUserId' -- -- * 'duDeviceId' -- -- * 'duCallback' devicesUpdate :: Text -- ^ 'duEnterpriseId' -> Device -- ^ 'duPayload' -> Text -- ^ 'duUserId' -> Text -- ^ 'duDeviceId' -> DevicesUpdate devicesUpdate pDuEnterpriseId_ pDuPayload_ pDuUserId_ pDuDeviceId_ = DevicesUpdate' { _duXgafv = Nothing , _duUploadProtocol = Nothing , _duUpdateMask = Nothing , _duEnterpriseId = pDuEnterpriseId_ , _duAccessToken = Nothing , _duUploadType = Nothing , _duPayload = pDuPayload_ , _duUserId = pDuUserId_ , _duDeviceId = pDuDeviceId_ , _duCallback = Nothing } -- | V1 error format. duXgafv :: Lens' DevicesUpdate (Maybe Xgafv) duXgafv = lens _duXgafv (\ s a -> s{_duXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). duUploadProtocol :: Lens' DevicesUpdate (Maybe Text) duUploadProtocol = lens _duUploadProtocol (\ s a -> s{_duUploadProtocol = a}) -- | Mask that identifies which fields to update. If not set, all modifiable -- fields will be modified. When set in a query parameter, this field -- should be specified as updateMask=,,... duUpdateMask :: Lens' DevicesUpdate (Maybe Text) duUpdateMask = lens _duUpdateMask (\ s a -> s{_duUpdateMask = a}) -- | The ID of the enterprise. duEnterpriseId :: Lens' DevicesUpdate Text duEnterpriseId = lens _duEnterpriseId (\ s a -> s{_duEnterpriseId = a}) -- | OAuth access token. duAccessToken :: Lens' DevicesUpdate (Maybe Text) duAccessToken = lens _duAccessToken (\ s a -> s{_duAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). duUploadType :: Lens' DevicesUpdate (Maybe Text) duUploadType = lens _duUploadType (\ s a -> s{_duUploadType = a}) -- | Multipart request metadata. duPayload :: Lens' DevicesUpdate Device duPayload = lens _duPayload (\ s a -> s{_duPayload = a}) -- | The ID of the user. duUserId :: Lens' DevicesUpdate Text duUserId = lens _duUserId (\ s a -> s{_duUserId = a}) -- | The ID of the device. duDeviceId :: Lens' DevicesUpdate Text duDeviceId = lens _duDeviceId (\ s a -> s{_duDeviceId = a}) -- | JSONP duCallback :: Lens' DevicesUpdate (Maybe Text) duCallback = lens _duCallback (\ s a -> s{_duCallback = a}) instance GoogleRequest DevicesUpdate where type Rs DevicesUpdate = Device type Scopes DevicesUpdate = '["https://www.googleapis.com/auth/androidenterprise"] requestClient DevicesUpdate'{..} = go _duEnterpriseId _duUserId _duDeviceId _duXgafv _duUploadProtocol _duUpdateMask _duAccessToken _duUploadType _duCallback (Just AltJSON) _duPayload androidEnterpriseService where go = buildClient (Proxy :: Proxy DevicesUpdateResource) mempty
mpl-2.0
brendanhay/gogol
gogol-commentanalyzer/gen/Network/Google/CommentAnalyzer.hs
4253
{-# LANGUAGE DataKinds #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} -- | -- Module : Network.Google.CommentAnalyzer -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- The Perspective Comment Analyzer API provides information about the -- potential impact of a comment on a conversation (e.g. it can provide a -- score for the \"toxicity\" of a comment). Users can leverage the -- \"SuggestCommentScore\" method to submit corrections to improve -- Perspective over time. Users can set the \"doNotStore\" flag to ensure -- that all submitted comments are automatically deleted after scores are -- returned. -- -- /See:/ <https://github.com/conversationai/perspectiveapi/blob/master/README.md Perspective Comment Analyzer API Reference> module Network.Google.CommentAnalyzer ( -- * Service Configuration commentAnalyzerService -- * OAuth Scopes , userInfoEmailScope -- * API Declaration , CommentAnalyzerAPI -- * Resources -- ** commentanalyzer.comments.analyze , module Network.Google.Resource.CommentAnalyzer.Comments.Analyze -- ** commentanalyzer.comments.suggestscore , module Network.Google.Resource.CommentAnalyzer.Comments.Suggestscore -- * Types -- ** SpanScore , SpanScore , spanScore , ssBegin , ssScore , ssEnd -- ** AnalyzeCommentResponse , AnalyzeCommentResponse , analyzeCommentResponse , acrDetectedLanguages , acrClientToken , acrLanguages , acrAttributeScores -- ** SuggestCommentScoreResponse , SuggestCommentScoreResponse , suggestCommentScoreResponse , scsrDetectedLanguages , scsrClientToken , scsrRequestedLanguages -- ** Context , Context , context , cEntries , cArticleAndParentComment -- ** Score , Score , score , sValue , sType -- ** ArticleAndParentComment , ArticleAndParentComment , articleAndParentComment , aapcArticle , aapcParentComment -- ** AttributeParameters , AttributeParameters , attributeParameters , apScoreThreshold , apScoreType -- ** TextEntry , TextEntry , textEntry , teText , teType -- ** AttributeScores , AttributeScores , attributeScores , asSummaryScore , asSpanScores -- ** Xgafv , Xgafv (..) -- ** ScoreType , ScoreType (..) -- ** AnalyzeCommentResponseAttributeScores , AnalyzeCommentResponseAttributeScores , analyzeCommentResponseAttributeScores , acrasAddtional -- ** SuggestCommentScoreRequest , SuggestCommentScoreRequest , suggestCommentScoreRequest , sContext , sClientToken , sLanguages , sAttributeScores , sSessionId , sComment , sCommUnityId -- ** AttributeParametersScoreType , AttributeParametersScoreType (..) -- ** AnalyzeCommentRequest , AnalyzeCommentRequest , analyzeCommentRequest , aContext , aClientToken , aSpanAnnotations , aDoNotStore , aLanguages , aRequestedAttributes , aSessionId , aComment , aCommUnityId -- ** SuggestCommentScoreRequestAttributeScores , SuggestCommentScoreRequestAttributeScores , suggestCommentScoreRequestAttributeScores , scsrasAddtional -- ** AnalyzeCommentRequestRequestedAttributes , AnalyzeCommentRequestRequestedAttributes , analyzeCommentRequestRequestedAttributes , acrraAddtional -- ** TextEntryType , TextEntryType (..) ) where import Network.Google.Prelude import Network.Google.CommentAnalyzer.Types import Network.Google.Resource.CommentAnalyzer.Comments.Analyze import Network.Google.Resource.CommentAnalyzer.Comments.Suggestscore {- $resources TODO -} -- | Represents the entirety of the methods and resources available for the Perspective Comment Analyzer API service. type CommentAnalyzerAPI = CommentsSuggestscoreResource :<|> CommentsAnalyzeResource
mpl-2.0
slanska/nauth2
test/09_RoleManagement.ts
938
/** * Created by slanska on 2016-12-30. */ ///<reference path="../typings/tsd.d.ts"/> import {TestService} from './helper'; describe('rolesManagement', () => { it('create a new role', (done) => { done(); }); it('delete non referenced role', (done) => { done(); }); it('cannot delete system role', (done) => { done(); }); it(`fetch all roles for the user, using user's own credentials`, (done) => { done(); }); it(`fetch all roles, using admin's roles`, (done) => { done(); }); it(`cannot fetch roles by non authorized user`, (done) => { done(); }); it(`cannot fetch roles by non authenticated client`, (done) => { done(); }); it('create domain specific role', (done) => { done(); }); it('delete domain specific role', (done) => { done(); }); });
mpl-2.0
servo/doc.servo.org
libc/unix/notbsd/constant.NOSTR.html
4539
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <meta name="description" content="API documentation for the Rust `NOSTR` constant in crate `libc`."> <meta name="keywords" content="rust, rustlang, rust-lang, NOSTR"> <title>libc::unix::notbsd::NOSTR - Rust</title> <link rel="stylesheet" type="text/css" href="../../../rustdoc.css"> <link rel="stylesheet" type="text/css" href="../../../main.css"> <link rel="shortcut icon" href="https://doc.rust-lang.org/favicon.ico"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <nav class="sidebar"> <a href='../../../libc/index.html'><img src='https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png' alt='logo' width='100'></a> <p class='location'><a href='../../index.html'>libc</a>::<wbr><a href='../index.html'>unix</a>::<wbr><a href='index.html'>notbsd</a></p><script>window.sidebarCurrent = {name: 'NOSTR', ty: 'constant', relpath: ''};</script><script defer src="sidebar-items.js"></script> </nav> <nav class="sub"> <form class="search-form js-only"> <div class="search-container"> <input class="search-input" name="search" autocomplete="off" placeholder="Click or press ‘S’ to search, ‘?’ for more options…" type="search"> </div> </form> </nav> <section id='main' class="content constant"> <h1 class='fqn'><span class='in-band'><a href='../../index.html'>libc</a>::<wbr><a href='../index.html'>unix</a>::<wbr><a href='index.html'>notbsd</a>::<wbr><a class='constant' href=''>NOSTR</a></span><span class='out-of-band'><span id='render-detail'> <a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs"> [<span class='inner'>&#x2212;</span>] </a> </span><a id='src-2227' class='srclink' href='../../../src/libc/unix/notbsd/linux/mod.rs.html#252' title='goto source code'>[src]</a></span></h1> <pre class='rust const'>pub const NOSTR: <a class='type' href='../../../libc/unix/notbsd/linux/type.nl_item.html' title='libc::unix::notbsd::linux::nl_item'>nl_item</a><code> = </code><code>327683</code></pre></section> <section id='search' class="content hidden"></section> <section class="footer"></section> <aside id="help" class="hidden"> <div> <h1 class="hidden">Help</h1> <div class="shortcuts"> <h2>Keyboard Shortcuts</h2> <dl> <dt>?</dt> <dd>Show this help dialog</dd> <dt>S</dt> <dd>Focus the search field</dd> <dt>&larrb;</dt> <dd>Move up in search results</dd> <dt>&rarrb;</dt> <dd>Move down in search results</dd> <dt>&#9166;</dt> <dd>Go to active search result</dd> <dt>+</dt> <dd>Collapse/expand all sections</dd> </dl> </div> <div class="infos"> <h2>Search Tricks</h2> <p> Prefix searches with a type followed by a colon (e.g. <code>fn:</code>) to restrict the search to a given type. </p> <p> Accepted types are: <code>fn</code>, <code>mod</code>, <code>struct</code>, <code>enum</code>, <code>trait</code>, <code>type</code>, <code>macro</code>, and <code>const</code>. </p> <p> Search functions by type signature (e.g. <code>vec -> usize</code> or <code>* -> vec</code>) </p> </div> </div> </aside> <script> window.rootPath = "../../../"; window.currentCrate = "libc"; window.playgroundUrl = ""; </script> <script src="../../../jquery.js"></script> <script src="../../../main.js"></script> <script defer src="../../../search-index.js"></script> </body> </html>
mpl-2.0
jeffreystarr/plainsight-addon
test/test-caesar.js
1791
/** * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, you can obtain one at http://mozilla.org/MPL/2.0/. */ var caesar = require("./caesar"); exports["test encrypt/decrypt"] = function(assert) { /* verify decrypting the result of encryption yields the original response */ assert.strictEqual(caesar.decrypt(caesar.encrypt("flee at once", "errorscanocc"), "errorscanocc"), "flee at once", "fail if cannot decrypt encrypted text"); }; exports["test encrypt 0"] = function(assert) { /* !!!!! is equivalent to an offset of zero */ assert.strictEqual(caesar.encrypt("01234", "!!!!!"), "01234", "encrypt identity"); }; exports["test decrypt 0"] = function(assert) { /* !!!!! is equivalent to an offset of zero */ assert.strictEqual(caesar.decrypt("QRSTU", "!!!!!"), "QRSTU", "decrypt identity"); }; exports["test encrypt 3"] = function(assert) { /* $$$$$ is equivalent to an offset of three */ assert.strictEqual(caesar.encrypt("01234", "$$$$$"), "34567", "encrypt by 3"); }; exports["test decrypt 3"] = function(assert) { /* $$$$$ is equivalent to an offset of three */ assert.strictEqual(caesar.decrypt("34567", "$$$$$"), "01234", "decrypt by 3"); }; exports["test encrypt wrap"] = function(assert) { assert.strictEqual(caesar.encrypt("z", "$"), "#", "encrypt wrap"); }; exports["test decrypt wrap"] = function(assert) { assert.strictEqual(caesar.decrypt("#", "$"), "z", "decrypt wrap"); }; exports["test encrypt not a no-op"] = function(assert) { /* verify we cannot pass with a no op */ assert.notStrictEqual(caesar.encrypt("flee at once", "errors can o"), "flee at once", "fail if no-op"); }; require("sdk/test").run(exports);
mpl-2.0
ElSaico/lipwig
README.md
59
# lipwig Gerenciador financeiro para dispositivos móveis.
mpl-2.0
EngineQ/gf
.example/i18n/gi18n/gi18n.go
417
package main import ( "context" "fmt" "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/i18n/gi18n" ) func main() { var ( orderId = 865271654 orderAmount = 99.8 ) fmt.Println(g.I18n().Tf( gi18n.WithLanguage(context.TODO(), `en`), `{#OrderPaid}`, orderId, orderAmount, )) fmt.Println(g.I18n().Tf( gi18n.WithLanguage(context.TODO(), `zh-CN`), `{#OrderPaid}`, orderId, orderAmount, )) }
mpl-2.0
susaing/doc.servo.org
js/jsapi/fn.JS_GetUint32ArrayData.html
4323
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <meta name="description" content="API documentation for the Rust `JS_GetUint32ArrayData` fn in crate `js`."> <meta name="keywords" content="rust, rustlang, rust-lang, JS_GetUint32ArrayData"> <title>js::jsapi::JS_GetUint32ArrayData - Rust</title> <link rel="stylesheet" type="text/css" href="../../main.css"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <section class="sidebar"> <p class='location'><a href='../index.html'>js</a>::<wbr><a href='index.html'>jsapi</a></p><script>window.sidebarCurrent = {name: 'JS_GetUint32ArrayData', ty: 'fn', relpath: ''};</script><script defer src="sidebar-items.js"></script> </section> <nav class="sub"> <form class="search-form js-only"> <div class="search-container"> <input class="search-input" name="search" autocomplete="off" placeholder="Click or press ‘S’ to search, ‘?’ for more options…" type="search"> </div> </form> </nav> <section id='main' class="content fn"> <h1 class='fqn'><span class='in-band'>Function <a href='../index.html'>js</a>::<wbr><a href='index.html'>jsapi</a>::<wbr><a class='fn' href=''>JS_GetUint32ArrayData</a></span><span class='out-of-band'><span id='render-detail'> <a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs"> [<span class='inner'>&#x2212;</span>] </a> </span><a id='src-38448' class='srclink' href='../../src/js/jsapi.rs.html#11303-11307' title='goto source code'>[src]</a></span></h1> <pre class='rust fn'>pub unsafe extern fn JS_GetUint32ArrayData(obj: <a href='../../std/primitive.pointer.html'>*mut <a class='enum' href='../../js/jsapi/enum.JSObject.html' title='js::jsapi::JSObject'>JSObject</a></a>, arg1: <a href='../../std/primitive.pointer.html'>*const <a class='struct' href='../../js/jsapi/struct.AutoCheckCannotGC.html' title='js::jsapi::AutoCheckCannotGC'>AutoCheckCannotGC</a></a>) -&gt; <a href='../../std/primitive.pointer.html'>*mut <a href='../../std/primitive.u32.html'>u32</a></a></pre></section> <section id='search' class="content hidden"></section> <section class="footer"></section> <div id="help" class="hidden"> <div> <div class="shortcuts"> <h1>Keyboard Shortcuts</h1> <dl> <dt>?</dt> <dd>Show this help dialog</dd> <dt>S</dt> <dd>Focus the search field</dd> <dt>&larrb;</dt> <dd>Move up in search results</dd> <dt>&rarrb;</dt> <dd>Move down in search results</dd> <dt>&#9166;</dt> <dd>Go to active search result</dd> </dl> </div> <div class="infos"> <h1>Search Tricks</h1> <p> Prefix searches with a type followed by a colon (e.g. <code>fn:</code>) to restrict the search to a given type. </p> <p> Accepted types are: <code>fn</code>, <code>mod</code>, <code>struct</code>, <code>enum</code>, <code>trait</code>, <code>type</code>, <code>macro</code>, and <code>const</code>. </p> <p> Search functions by type signature (e.g. <code>vec -> usize</code>) </p> </div> </div> </div> <script> window.rootPath = "../../"; window.currentCrate = "js"; window.playgroundUrl = ""; </script> <script src="../../jquery.js"></script> <script src="../../main.js"></script> <script async src="../../search-index.js"></script> </body> </html>
mpl-2.0
Yukarumya/Yukarum-Redfoxes
layout/style/nsCSSPropertyID.h
3590
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* enum types for CSS properties and their values */ #ifndef nsCSSPropertyID_h___ #define nsCSSPropertyID_h___ #include <nsHashKeys.h> /* Declare the enum list using the magic of preprocessing enum values are "eCSSProperty_foo" (where foo is the property) To change the list of properties, see nsCSSPropList.h */ enum nsCSSPropertyID { eCSSProperty_UNKNOWN = -1, #define CSS_PROP(name_, id_, method_, flags_, pref_, parsevariant_, \ kwtable_, stylestruct_, stylestructoffset_, animtype_) \ eCSSProperty_##id_, #define CSS_PROP_LIST_INCLUDE_LOGICAL #include "nsCSSPropList.h" #undef CSS_PROP_LIST_INCLUDE_LOGICAL #undef CSS_PROP eCSSProperty_COUNT_no_shorthands, // Make the count continue where it left off: eCSSProperty_COUNT_DUMMY = eCSSProperty_COUNT_no_shorthands - 1, #define CSS_PROP_SHORTHAND(name_, id_, method_, flags_, pref_) \ eCSSProperty_##id_, #include "nsCSSPropList.h" #undef CSS_PROP_SHORTHAND eCSSProperty_COUNT, // Make the count continue where it left off: eCSSProperty_COUNT_DUMMY2 = eCSSProperty_COUNT - 1, #define CSS_PROP_ALIAS(aliasname_, id_, method_, pref_) \ eCSSPropertyAlias_##method_, #include "nsCSSPropAliasList.h" #undef CSS_PROP_ALIAS eCSSProperty_COUNT_with_aliases, // Make the count continue where it left off: eCSSProperty_COUNT_DUMMY3 = eCSSProperty_COUNT_with_aliases - 1, // Some of the values below could probably overlap with each other // if we had a need for them to do so. // Extra values for use in the values of the 'transition-property' // property. eCSSPropertyExtra_no_properties, eCSSPropertyExtra_all_properties, // Extra dummy values for nsCSSParser internal use. eCSSPropertyExtra_x_none_value, eCSSPropertyExtra_x_auto_value, // Extra value to represent custom properties (--*). eCSSPropertyExtra_variable, // Extra value for use in the DOM API's eCSSProperty_DOM }; namespace mozilla { template<> inline PLDHashNumber Hash<nsCSSPropertyID>(const nsCSSPropertyID& aValue) { return uint32_t(aValue); } } // namespace mozilla // The "descriptors" that can appear in a @font-face rule. // They have the syntax of properties but different value rules. enum nsCSSFontDesc { eCSSFontDesc_UNKNOWN = -1, #define CSS_FONT_DESC(name_, method_) eCSSFontDesc_##method_, #include "nsCSSFontDescList.h" #undef CSS_FONT_DESC eCSSFontDesc_COUNT }; // The "descriptors" that can appear in a @counter-style rule. // They have the syntax of properties but different value rules. enum nsCSSCounterDesc { eCSSCounterDesc_UNKNOWN = -1, #define CSS_COUNTER_DESC(name_, method_) eCSSCounterDesc_##method_, #include "nsCSSCounterDescList.h" #undef CSS_COUNTER_DESC eCSSCounterDesc_COUNT }; enum nsCSSPropertyLogicalGroup { eCSSPropertyLogicalGroup_UNKNOWN = -1, #define CSS_PROP_LOGICAL_GROUP_AXIS(name_) \ eCSSPropertyLogicalGroup_##name_, #define CSS_PROP_LOGICAL_GROUP_BOX(name_) \ eCSSPropertyLogicalGroup_##name_, #define CSS_PROP_LOGICAL_GROUP_SHORTHAND(name_) \ eCSSPropertyLogicalGroup_##name_, #include "nsCSSPropLogicalGroupList.h" #undef CSS_PROP_LOGICAL_GROUP_SHORTHAND #undef CSS_PROP_LOGICAL_GROUP_BOX #undef CSS_PROP_LOGICAL_GROUP_AXIS eCSSPropertyLogicalGroup_COUNT }; #endif /* nsCSSPropertyID_h___ */
mpl-2.0
Yukarumya/Yukarum-Redfoxes
tools/leak-gauge/leak-gauge.html
11520
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <!-- vim:sw=4:ts=4:et: This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> <html lang="en-US"> <head> <meta charset="UTF-8" /> <title>Leak Gauge</title> <style type="text/css"> pre { margin: 0; } pre.output { border: medium solid; padding: 1em; margin: 1em; } </style> <script type="text/javascript"> function runfile(file) { var result = "Results of processing log " + file.fileName + " :\n"; var fileReader = new FileReader(); fileReader.onload = function(e) { runContents(result, e.target.result); } fileReader.readAsText(file, "iso-8859-1"); } function runContents(result, contents) { // A hash of objects (keyed by the first word of the line in the log) // that have two public methods, handle_line and dump (to be called using // call, above), along with any private data they need. var handlers = { "DOMWINDOW": { count: 0, windows: {}, handle_line: function(line) { var match = line.match(/^([0-9a-f]*) (\S*)(.*)/); if (match) { var addr = match[1]; var verb = match[2]; var rest = match[3]; if (verb == "created") { var m = rest.match(/ outer=([0-9a-f]*)$/); if (!m) throw "outer expected"; this.windows[addr] = { outer: m[1] }; ++this.count; } else if (verb == "destroyed") { delete this.windows[addr]; } else if (verb == "SetNewDocument") { var m = rest.match(/^ (.*)$/); if (!m) throw "URI expected"; this.windows[addr][m[1]] = true; } } }, dump: function() { for (var addr in this.windows) { var winobj = this.windows[addr]; var outer = winobj.outer; delete winobj.outer; result += "Leaked " + (outer == "0" ? "outer" : "inner") + " window " + addr + " " + (outer == "0" ? "" : "(outer " + outer + ") ") + "at address " + addr + ".\n"; for (var uri in winobj) { result += " ... with URI \"" + uri + "\".\n"; } } }, summary: function() { var len = 0; for (var w in this.windows) ++len; result += 'Leaked ' + len + ' out of ' + this.count + " DOM Windows\n"; } }, "DOCUMENT": { count: 0, docs: {}, handle_line: function(line) { var match = line.match(/^([0-9a-f]*) (\S*)(.*)/); if (match) { var addr = match[1]; var verb = match[2]; var rest = match[3]; if (verb == "created") { this.docs[addr] = {}; ++this.count; } else if (verb == "destroyed") { delete this.docs[addr]; } else if (verb == "ResetToURI" || verb == "StartDocumentLoad") { var m = rest.match(/^ (.*)$/); if (!m) throw "URI expected"; var uri = m[1]; var doc_info = this.docs[addr]; doc_info[uri] = true; if ("nim" in doc_info) { doc_info["nim"][uri] = true; } } } }, dump: function() { for (var addr in this.docs) { var doc = this.docs[addr]; result += "Leaked document at address " + addr + ".\n"; for (var uri in doc) { if (uri != "nim") { result += " ... with URI \"" + uri + "\".\n"; } } } }, summary: function() { var len = 0; for (var w in this.docs) ++len; result += 'Leaked ' + len + ' out of ' + this.count + " documents\n"; } }, "DOCSHELL": { count: 0, shells: {}, handle_line: function(line) { var match = line.match(/^([0-9a-f]*) (\S*)(.*)/); if (match) { var addr = match[1]; var verb = match[2]; var rest = match[3]; if (verb == "created") { this.shells[addr] = {}; ++this.count; } else if (verb == "destroyed") { delete this.shells[addr]; } else if (verb == "InternalLoad" || verb == "SetCurrentURI") { var m = rest.match(/^ (.*)$/); if (!m) throw "URI expected"; this.shells[addr][m[1]] = true; } } }, dump: function() { for (var addr in this.shells) { var doc = this.shells[addr]; result += "Leaked docshell at address " + addr + ".\n"; for (var uri in doc) { result += " ... which loaded URI \"" + uri + "\".\n"; } } }, summary: function() { var len = 0; for (var w in this.shells) ++len; result += 'Leaked ' + len + ' out of ' + this.count + " docshells\n"; } }, "NODEINFOMANAGER": { count: 0, nims: {}, handle_line: function(line) { var match = line.match(/^([0-9a-f]*) (\S*)(.*)/); if (match) { var addr = match[1]; var verb = match[2]; var rest = match[3]; if (verb == "created") { this.nims[addr] = {}; ++this.count; } else if (verb == "destroyed") { delete this.nims[addr]; } else if (verb == "Init") { var m = rest.match(/^ document=(.*)$/); if (!m) throw "document pointer expected"; var nim_info = this.nims[addr]; var doc = m[1]; if (doc != "0") { var doc_info = handlers["DOCUMENT"].docs[doc]; for (var uri in doc_info) { nim_info[uri] = true; } doc_info["nim"] = nim_info; } } } }, dump: function() { for (var addr in this.nims) { var nim = this.nims[addr]; result += "Leaked content nodes associated with node info manager at address " + addr + ".\n"; for (var uri in nim) { result += " ... with document URI \"" + uri + "\".\n"; } } }, summary: function() { var len = 0; for (var w in this.nims) ++len; result += 'Leaked content nodes in ' + len + ' out of ' + this.count + " documents\n"; } } }; var lines = contents.split(/[\r\n]+/); for (var j in lines) { var line = lines[j]; // strip off initial "-", thread id, and thread pointer; separate // first word and rest var matches = line.match(/^\-?[0-9]*\[[0-9a-f]*\]: (\S*) (.*)$/); if (matches) { var handler = matches[1]; var data = matches[2]; if (typeof(handlers[handler]) != "undefined") { handlers[handler].handle_line(data); } } } for (var handler in handlers) handlers[handler].dump(); if (result.length) result += "\n"; result += "Summary:\n"; for (var handler in handlers) handlers[handler].summary(); result += "\n"; var out = document.createElement("pre"); out.className = "output"; out.appendChild(document.createTextNode(result)); document.body.appendChild(out); } function run() { var input = document.getElementById("fileinput"); var files = input.files; for (var i = 0; i < files.length; ++i) runfile(files[i]); // So the user can process the same filename again (after // overwriting the log), clear the value on the form input so we // will always get an onchange event. input.value = ""; } </script> </head> <body> <h1>Leak Gauge</h1> <pre>$Id: leak-gauge.html,v 1.8 2008/02/08 19:55:34 dbaron%dbaron.org Exp $</pre> <p>This script is designed to help testers isolate and simplify testcases for many classes of leaks (those that involve large graphs of core data structures) in Mozilla-based browsers. It is designed to print information about what has leaked by processing a log taken while running the browser. Such a log can be taken over a long session of normal browsing and then the log can be processed to find sites that leak. Once a site is known to leak, the logging can then be repeated to figure out under what conditions the leak occurs.</p> <p>The way to create this log is to set the environment variables:</p> <pre> MOZ_LOG=DOMLeak:5,DocumentLeak:5,nsDocShellLeak:5,NodeInfoManagerLeak:5 MOZ_LOG_FILE=nspr.log <i>(or any other filename of your choice)</i></pre> <p>in your shell and then run the program.</p> <ul> <li>In a Windows command prompt, set environment variables with <pre> set VAR=value</pre></li> <li> In an sh-based shell such as bash, set environment variables with <pre> export VAR=value</pre></li> <li>In a csh-based shell such as tcsh, set environment variables with <pre> setenv VAR value</pre></li> </ul> <p>Once you have this log from a complete run of the browser (you have to exit; otherwise it will look like everything leaked), you can load this page (be careful not to overwrite the log when starting the browser to load this page) and enter the filename of the log:</p> <p><input type="file" id="fileinput" onchange="run()"></p> <p>Then you'll see the output below, which will tell you which of certain core objects leaked and the URLs associated with those objects.</p> </body> </html>
mpl-2.0
KIWIKIGMBH/kiwierp
kiwierp-backend/app/contexts/AuthenticationContext.scala
982
package contexts import models.{AccessToken, User} import play.api.libs.concurrent.Execution.Implicits.defaultContext import roles.AuthenticatedUser import scalikejdbc.async.{AsyncDB, AsyncDBSession} import utils.Password import utils.exceptions.InvalidUser import scala.concurrent.Future class AuthenticationContext private (user: User, password: Password)(implicit tx: AsyncDBSession) { private def authenticate(): Future[AccessToken] = { val authenticatedUser = new User(user) with AuthenticatedUser authenticatedUser.checkPassword(password) authenticatedUser.createAccessToken() } } object AuthenticationContext extends KiwiERPContext { def apply(name: String, password: String): Future[AccessToken] = AsyncDB localTx { implicit tx => User.findByName(name) flatMap { case Some(user) => val cxt = new AuthenticationContext(user, new Password(password)) cxt.authenticate() case None => throw new InvalidUser } } }
mpl-2.0
araraloren/FunctionFind
src/main.cpp
874
#include <iostream> #include <cpplogger/cllogger.h> #include <ccsseqqueue.h> #include <cctest.h> #include <functional> #include <ffoption.h> using namespace std; int main(int argc, char** argv) { ff::CommandOption *ffop = ff::CommandOption::getInstance(); ffop->parseArgv(argc, argv); ffop->debugOption(); cc::SSeqQueue<int> squeue; squeue.init(); squeue.push(1); //cout <<FF_TO_SRTING(squeue)<<" size -> "<<squeue.count()<<endl; int x = 0; squeue.pop(x); cout <<"get x -> "<<x<<endl; //cout <<FF_TO_SRTING(squeue)<<" size -> "<<squeue.count()<<endl; #if __cplusplus >= 201103L cc::println(cc::splitString(string("1 2 4 dksja ida qwd www"), string("\\s+"))); #else cc::println(cc::splitString(string("1 2 4 dksja ida qwd www"))); #endif cout <<cc::trim(string(" ; "))<<endl; return 0; }
mpl-2.0
rem7/pushr
config_validate_timestamp_test.go
3623
package main import ( "fmt" "testing" ) var config ConfigFile = ConfigFile{} var strmCfg = StreamConfig{ "streamName", "name", "type", "url", "StreamApiKey", "RecordFormatString", nil, nil, } /* * Valid configuration - take timestamp as is */ func TestValidateEmtpySrcDest(t *testing.T) { var attrs = []Attribute{{"key", "timestamp", 16, "", ""}} strmCfg.RecordFormat = attrs config.Streams = []StreamConfig{strmCfg} err := config.validate() if err != nil { fmt.Println(err) t.Fail() } } /* * Valid configuration - valid timestamp formats */ func TestValidateCorrectSrcDest(t *testing.T) { var attrs = []Attribute{{"key", "timestamp", 16, "2006-01-02T15:04:05.999Z", "2006-01-02T15:04:05.999Z"}} strmCfg.RecordFormat = attrs config.Streams = []StreamConfig{strmCfg} err := config.validate() if err != nil { fmt.Println(err) t.Fail() } } /* * Valid configuration - slash formats to dash formats */ func TestValidateVariousDelimiterDate(t *testing.T) { var attrs = []Attribute{{"key", "timestamp", 16, "2006/01/02 15:04:05", "2006-01-02T15:04:05.999Z"}} strmCfg.RecordFormat = attrs config.Streams = []StreamConfig{strmCfg} err := config.validate() if err != nil { t.Fail() fmt.Println(err) } } /* * Invalid Config - valid source but no destination format */ func TestValidateNoDestinationFormat(t *testing.T) { var attrs = []Attribute{{"key", "timestamp", 16, "2006-01-02T15:04:05.999Z", ""}} strmCfg.RecordFormat = attrs config.Streams = []StreamConfig{strmCfg} err := config.validate() expected := "must specify Source & Destination Timestamp Format when datatype is Timestamp" if err.Error() != expected { t.Fail() } } /* * Invalid configuration - valid destination but no source format */ func TestValidateNoSourceFormat(t *testing.T) { var attrs = []Attribute{{"key", "timestamp", 16, "", "2006-01-02T15:04:05.999Z"}} strmCfg.RecordFormat = attrs config.Streams = []StreamConfig{strmCfg} err := config.validate() expected := "must specify Source Timestamp Format when datatype is Timestamp" if err.Error() != expected { t.Fail() fmt.Println(err) } } /* * Invalid configuration - invalid source format */ func TestValidateInvalidSource(t *testing.T) { var attrs = []Attribute{{"key", "timestamp", 16, "2006-01-02T15::05.999Z", "2006-01-02T15:04:05.999Z"}} strmCfg.RecordFormat = attrs config.Streams = []StreamConfig{strmCfg} err := config.validate() if err == nil { t.Fail() fmt.Println(err) } } /* * Invalid configuration - invalid destination format */ func TestValidateInvalidDestination(t *testing.T) { var attrs = []Attribute{{"key", "timestamp", 16, "2006-01-02T15:04:05.999Z", "2006-01-02T15::05.999Z"}} strmCfg.RecordFormat = attrs config.Streams = []StreamConfig{strmCfg} err := config.validate() if err == nil { t.Fail() fmt.Println(err) } } /* * Long source to short destination * Result - warns of a possible invalid format */ func TestValidateShortDestination(t *testing.T) { var attrs = []Attribute{{"key", "timestamp", 16, "2006-01-02T15:04:05.999Z", "2006-01-02"}} strmCfg.RecordFormat = attrs config.Streams = []StreamConfig{strmCfg} err := config.validate() if err != nil { t.Fail() fmt.Println(err) } } /* * Short Date to long date * Result - warns of a possible invalid format */ func TestValidateShortSource(t *testing.T) { var attrs = []Attribute{{"key", "timestamp", 16, "2006-01-02", "2006-01-02T15:04:05.999Z"}} strmCfg.RecordFormat = attrs config.Streams = []StreamConfig{strmCfg} err := config.validate() if err != nil { t.Fail() fmt.Println(err) } }
mpl-2.0
mhaessig/servo
components/style/properties/longhand/background.mako.rs
8891
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <% data.new_style_struct("Background", inherited=False) %> ${helpers.predefined_type( "background-color", "Color", "computed_value::T::transparent()", initial_specified_value="SpecifiedValue::transparent()", spec="https://drafts.csswg.org/css-backgrounds/#background-color", animation_value_type="AnimatedColor", ignored_when_colors_disabled=True, allow_quirks=True, flags="""PropertyFlags::APPLIES_TO_FIRST_LETTER PropertyFlags::APPLIES_TO_FIRST_LINE PropertyFlags::APPLIES_TO_PLACEHOLDER""", )} ${helpers.predefined_type("background-image", "ImageLayer", initial_value="Either::First(None_)", initial_specified_value="Either::First(None_)", spec="https://drafts.csswg.org/css-backgrounds/#the-background-image", vector="True", animation_value_type="discrete", ignored_when_colors_disabled="True", flags="""PropertyFlags::APPLIES_TO_FIRST_LETTER PropertyFlags::APPLIES_TO_FIRST_LINE PropertyFlags::APPLIES_TO_PLACEHOLDER""")} % for (axis, direction, initial) in [("x", "Horizontal", "left"), ("y", "Vertical", "top")]: ${helpers.predefined_type( "background-position-" + axis, "position::" + direction + "Position", initial_value="computed::LengthOrPercentage::zero()", initial_specified_value="SpecifiedValue::initial_specified_value()", spec="https://drafts.csswg.org/css-backgrounds-4/#propdef-background-position-" + axis, animation_value_type="ComputedValue", vector=True, flags="""PropertyFlags::APPLIES_TO_FIRST_LETTER PropertyFlags::APPLIES_TO_FIRST_LINE PropertyFlags::APPLIES_TO_PLACEHOLDER""", )} % endfor <%helpers:vector_longhand name="background-repeat" animation_value_type="discrete" spec="https://drafts.csswg.org/css-backgrounds/#the-background-repeat" flags="""PropertyFlags::APPLIES_TO_FIRST_LETTER PropertyFlags::APPLIES_TO_FIRST_LINE PropertyFlags::APPLIES_TO_PLACEHOLDER"""> use std::fmt; use style_traits::ToCss; define_css_keyword_enum!(RepeatKeyword: "repeat" => Repeat, "space" => Space, "round" => Round, "no-repeat" => NoRepeat); #[derive(Clone, Debug, MallocSizeOf, PartialEq, ToCss)] pub enum SpecifiedValue { RepeatX, RepeatY, Other(RepeatKeyword, Option<RepeatKeyword>), } pub mod computed_value { pub use super::RepeatKeyword; #[derive(Clone, Debug, MallocSizeOf, PartialEq)] pub struct T(pub RepeatKeyword, pub RepeatKeyword); } impl ToCss for computed_value::T { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { match (self.0, self.1) { (RepeatKeyword::Repeat, RepeatKeyword::NoRepeat) => dest.write_str("repeat-x"), (RepeatKeyword::NoRepeat, RepeatKeyword::Repeat) => dest.write_str("repeat-y"), (horizontal, vertical) => { horizontal.to_css(dest)?; if horizontal != vertical { dest.write_str(" ")?; vertical.to_css(dest)?; } Ok(()) }, } } } #[inline] pub fn get_initial_value() -> computed_value::T { computed_value::T(RepeatKeyword::Repeat, RepeatKeyword::Repeat) } #[inline] pub fn get_initial_specified_value() -> SpecifiedValue { SpecifiedValue::Other(RepeatKeyword::Repeat, None) } impl ToComputedValue for SpecifiedValue { type ComputedValue = computed_value::T; #[inline] fn to_computed_value(&self, _context: &Context) -> computed_value::T { match *self { SpecifiedValue::RepeatX => computed_value::T(RepeatKeyword::Repeat, RepeatKeyword::NoRepeat), SpecifiedValue::RepeatY => computed_value::T(RepeatKeyword::NoRepeat, RepeatKeyword::Repeat), SpecifiedValue::Other(horizontal, vertical) => computed_value::T(horizontal, vertical.unwrap_or(horizontal)) } } #[inline] fn from_computed_value(computed: &computed_value::T) -> Self { match (computed.0, computed.1) { (RepeatKeyword::Repeat, RepeatKeyword::NoRepeat) => SpecifiedValue::RepeatX, (RepeatKeyword::NoRepeat, RepeatKeyword::Repeat) => SpecifiedValue::RepeatY, (horizontal, vertical) => SpecifiedValue::Other(horizontal, Some(vertical)), } } } pub fn parse<'i, 't>(_context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<SpecifiedValue, ParseError<'i>> { let ident = input.expect_ident_cloned()?; (match_ignore_ascii_case! { &ident, "repeat-x" => Ok(SpecifiedValue::RepeatX), "repeat-y" => Ok(SpecifiedValue::RepeatY), _ => Err(()), }).or_else(|()| { let horizontal: Result<_, ParseError> = RepeatKeyword::from_ident(&ident) .map_err(|()| input.new_custom_error(SelectorParseErrorKind::UnexpectedIdent(ident.clone()))); let horizontal = horizontal?; let vertical = input.try(RepeatKeyword::parse).ok(); Ok(SpecifiedValue::Other(horizontal, vertical)) }) } </%helpers:vector_longhand> ${helpers.single_keyword("background-attachment", "scroll fixed" + (" local" if product == "gecko" else ""), vector=True, gecko_constant_prefix="NS_STYLE_IMAGELAYER_ATTACHMENT", spec="https://drafts.csswg.org/css-backgrounds/#the-background-attachment", animation_value_type="discrete", flags="""PropertyFlags::APPLIES_TO_FIRST_LETTER PropertyFlags::APPLIES_TO_FIRST_LINE PropertyFlags::APPLIES_TO_PLACEHOLDER""")} ${helpers.single_keyword("background-clip", "border-box padding-box content-box", extra_gecko_values="text", vector=True, extra_prefixes="webkit", gecko_enum_prefix="StyleGeometryBox", spec="https://drafts.csswg.org/css-backgrounds/#the-background-clip", animation_value_type="discrete", flags="""PropertyFlags::APPLIES_TO_FIRST_LETTER PropertyFlags::APPLIES_TO_FIRST_LINE PropertyFlags::APPLIES_TO_PLACEHOLDER""")} ${helpers.single_keyword("background-origin", "padding-box border-box content-box", vector=True, extra_prefixes="webkit", gecko_enum_prefix="StyleGeometryBox", spec="https://drafts.csswg.org/css-backgrounds/#the-background-origin", animation_value_type="discrete", flags="""PropertyFlags::APPLIES_TO_FIRST_LETTER PropertyFlags::APPLIES_TO_FIRST_LINE PropertyFlags::APPLIES_TO_PLACEHOLDER""")} ${helpers.predefined_type("background-size", "BackgroundSize", initial_value="computed::BackgroundSize::auto()", initial_specified_value="specified::BackgroundSize::auto()", spec="https://drafts.csswg.org/css-backgrounds/#the-background-size", vector=True, animation_value_type="BackgroundSizeList", need_animatable=True, flags="""PropertyFlags::APPLIES_TO_FIRST_LETTER PropertyFlags::APPLIES_TO_FIRST_LINE PropertyFlags::APPLIES_TO_PLACEHOLDER""", extra_prefixes="webkit")} // https://drafts.fxtf.org/compositing/#background-blend-mode ${helpers.single_keyword("background-blend-mode", """normal multiply screen overlay darken lighten color-dodge color-burn hard-light soft-light difference exclusion hue saturation color luminosity""", gecko_constant_prefix="NS_STYLE_BLEND", vector=True, products="gecko", animation_value_type="discrete", spec="https://drafts.fxtf.org/compositing/#background-blend-mode", flags="""PropertyFlags::APPLIES_TO_FIRST_LETTER PropertyFlags::APPLIES_TO_FIRST_LINE PropertyFlags::APPLIES_TO_PLACEHOLDER""")}
mpl-2.0
servo/doc.servo.org
libc/linux/other/constant.FIONREAD.html
4584
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <meta name="description" content="API documentation for the Rust `FIONREAD` constant in crate `libc`."> <meta name="keywords" content="rust, rustlang, rust-lang, FIONREAD"> <title>libc::linux::other::FIONREAD - Rust</title> <link rel="stylesheet" type="text/css" href="../../../rustdoc.css"> <link rel="stylesheet" type="text/css" href="../../../main.css"> <link rel="shortcut icon" href="https://doc.rust-lang.org/favicon.ico"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <nav class="sidebar"> <a href='../../../libc/index.html'><img src='https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png' alt='logo' width='100'></a> <p class='location'><a href='../../index.html'>libc</a>::<wbr><a href='../index.html'>linux</a>::<wbr><a href='index.html'>other</a></p><script>window.sidebarCurrent = {name: 'FIONREAD', ty: 'constant', relpath: ''};</script><script defer src="sidebar-items.js"></script> </nav> <nav class="sub"> <form class="search-form js-only"> <div class="search-container"> <input class="search-input" name="search" autocomplete="off" placeholder="Click or press ‘S’ to search, ‘?’ for more options…" type="search"> </div> </form> </nav> <section id='main' class="content constant"> <h1 class='fqn'><span class='in-band'><a href='../../index.html'>libc</a>::<wbr><a href='../index.html'>linux</a>::<wbr><a href='index.html'>other</a>::<wbr><a class='constant' href=''>FIONREAD</a></span><span class='out-of-band'><span id='render-detail'> <a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs"> [<span class='inner'>&#x2212;</span>] </a> </span><a id='src-3108' class='srclink' href='../../../src/libc/unix/notbsd/linux/other/mod.rs.html#470' title='goto source code'>[src]</a></span></h1> <pre class='rust const'>pub const FIONREAD: <a class='type' href='../../../libc/unix/notbsd/linux/other/b64/type.c_ulong.html' title='libc::unix::notbsd::linux::other::b64::c_ulong'>c_ulong</a><code> = </code><code>21531</code></pre></section> <section id='search' class="content hidden"></section> <section class="footer"></section> <aside id="help" class="hidden"> <div> <h1 class="hidden">Help</h1> <div class="shortcuts"> <h2>Keyboard Shortcuts</h2> <dl> <dt>?</dt> <dd>Show this help dialog</dd> <dt>S</dt> <dd>Focus the search field</dd> <dt>&larrb;</dt> <dd>Move up in search results</dd> <dt>&rarrb;</dt> <dd>Move down in search results</dd> <dt>&#9166;</dt> <dd>Go to active search result</dd> <dt>+</dt> <dd>Collapse/expand all sections</dd> </dl> </div> <div class="infos"> <h2>Search Tricks</h2> <p> Prefix searches with a type followed by a colon (e.g. <code>fn:</code>) to restrict the search to a given type. </p> <p> Accepted types are: <code>fn</code>, <code>mod</code>, <code>struct</code>, <code>enum</code>, <code>trait</code>, <code>type</code>, <code>macro</code>, and <code>const</code>. </p> <p> Search functions by type signature (e.g. <code>vec -> usize</code> or <code>* -> vec</code>) </p> </div> </div> </aside> <script> window.rootPath = "../../../"; window.currentCrate = "libc"; window.playgroundUrl = ""; </script> <script src="../../../jquery.js"></script> <script src="../../../main.js"></script> <script defer src="../../../search-index.js"></script> </body> </html>
mpl-2.0
honeybee/honeybee
src/Infrastructure/Migration/FileSystemLoader.php
2574
<?php namespace Honeybee\Infrastructure\Migration; use Honeybee\Common\Error\RuntimeError; use Honeybee\Common\Util\PhpClassParser; use Honeybee\Common\Util\StringToolkit; use Honeybee\Infrastructure\Config\ConfigInterface; use Honeybee\ServiceLocatorInterface; use Symfony\Component\Finder\Finder; class FileSystemLoader implements MigrationLoaderInterface { protected $config; protected $service_locator; protected $file_finder; public function __construct( ConfigInterface $config, ServiceLocatorInterface $service_locator, Finder $file_finder = null ) { $this->config = $config; $this->service_locator = $service_locator; $this->file_finder= $file_finder?: new Finder; } /** * @return MigrationList */ public function loadMigrations() { $migration_dir = $this->config->get('directory'); if (!is_dir($migration_dir) || !is_readable($migration_dir)) { throw new RuntimeError(sprintf('Given migration path is not a readable directory: %s', $migration_dir)); } $migrations = []; $pattern = $this->config->get('pattern', '*.php'); $migration_files = $this->file_finder->create()->files()->name($pattern)->in($migration_dir)->sortByName(); foreach ($migration_files as $migration_file) { $class_parser = new PhpClassParser; $migration_class_info = $class_parser->parse((string)$migration_file); $migration_class = $migration_class_info->getFullyQualifiedClassName(); $migration_class_name = $migration_class_info->getClassName(); $class_format = $this->config->get('format', '#(?<version>\d{14}).(?<name>.+)$#'); if (!preg_match($class_format, $migration_class_name, $matches) || !isset($matches['name']) || !isset($matches['version']) ) { throw new RuntimeError('Invalid class name format for ' . $migration_class_name); } if (!class_exists($migration_class)) { require_once $migration_class_info->getFilePath(); } $migrations[] = $this->service_locator->make( $migration_class, [ ':state' => [ 'name' => StringToolkit::asSnakeCase($matches['name']), 'version' => $matches['version'] ] ] ); } return new MigrationList($migrations); } }
mpl-2.0
susaing/doc.servo.org
js/jsapi/fn.JS_TraceChildren.html
4300
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <meta name="description" content="API documentation for the Rust `JS_TraceChildren` fn in crate `js`."> <meta name="keywords" content="rust, rustlang, rust-lang, JS_TraceChildren"> <title>js::jsapi::JS_TraceChildren - Rust</title> <link rel="stylesheet" type="text/css" href="../../main.css"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <section class="sidebar"> <p class='location'><a href='../index.html'>js</a>::<wbr><a href='index.html'>jsapi</a></p><script>window.sidebarCurrent = {name: 'JS_TraceChildren', ty: 'fn', relpath: ''};</script><script defer src="sidebar-items.js"></script> </section> <nav class="sub"> <form class="search-form js-only"> <div class="search-container"> <input class="search-input" name="search" autocomplete="off" placeholder="Click or press ‘S’ to search, ‘?’ for more options…" type="search"> </div> </form> </nav> <section id='main' class="content fn"> <h1 class='fqn'><span class='in-band'>Function <a href='../index.html'>js</a>::<wbr><a href='index.html'>jsapi</a>::<wbr><a class='fn' href=''>JS_TraceChildren</a></span><span class='out-of-band'><span id='render-detail'> <a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs"> [<span class='inner'>&#x2212;</span>] </a> </span><a id='src-25380' class='srclink' href='../../src/js/jsapi.rs.html#6836-6840' title='goto source code'>[src]</a></span></h1> <pre class='rust fn'>pub unsafe extern fn JS_TraceChildren(trc: <a href='../../std/primitive.pointer.html'>*mut <a class='struct' href='../../js/jsapi/struct.JSTracer.html' title='js::jsapi::JSTracer'>JSTracer</a></a>, thing: <a href='../../std/primitive.pointer.html'>*mut <a class='enum' href='../../libc/types/common/c95/enum.c_void.html' title='libc::types::common::c95::c_void'>c_void</a></a>, kind: <a class='enum' href='../../js/jsapi/enum.JSGCTraceKind.html' title='js::jsapi::JSGCTraceKind'>JSGCTraceKind</a>)</pre></section> <section id='search' class="content hidden"></section> <section class="footer"></section> <div id="help" class="hidden"> <div> <div class="shortcuts"> <h1>Keyboard Shortcuts</h1> <dl> <dt>?</dt> <dd>Show this help dialog</dd> <dt>S</dt> <dd>Focus the search field</dd> <dt>&larrb;</dt> <dd>Move up in search results</dd> <dt>&rarrb;</dt> <dd>Move down in search results</dd> <dt>&#9166;</dt> <dd>Go to active search result</dd> </dl> </div> <div class="infos"> <h1>Search Tricks</h1> <p> Prefix searches with a type followed by a colon (e.g. <code>fn:</code>) to restrict the search to a given type. </p> <p> Accepted types are: <code>fn</code>, <code>mod</code>, <code>struct</code>, <code>enum</code>, <code>trait</code>, <code>type</code>, <code>macro</code>, and <code>const</code>. </p> <p> Search functions by type signature (e.g. <code>vec -> usize</code>) </p> </div> </div> </div> <script> window.rootPath = "../../"; window.currentCrate = "js"; window.playgroundUrl = ""; </script> <script src="../../jquery.js"></script> <script src="../../main.js"></script> <script async src="../../search-index.js"></script> </body> </html>
mpl-2.0
taotetek/zchannel
bindings/ruby/lib/zchannel/ffi.rb
1821
################################################################################ # THIS FILE IS 100% GENERATED BY ZPROJECT; DO NOT EDIT EXCEPT EXPERIMENTALLY # # Please refer to the README for information about making permanent changes. # ################################################################################ require 'ffi' require_relative 'ffi/version' module Zchannel module FFI extend ::FFI::Library def self.available? @available end begin lib_name = 'libzchannel' lib_paths = ['/usr/local/lib', '/opt/local/lib', '/usr/lib64'] .map { |path| "#{path}/#{lib_name}.#{::FFI::Platform::LIBSUFFIX}" } ffi_lib lib_paths + [lib_name] @available = true rescue LoadError warn "" warn "WARNING: ::Zchannel::FFI is not available without libzchannel." warn "" @available = false end if available? opts = { blocking: true # only necessary on MRI to deal with the GIL. } attach_function :zchanneler_new, [:string], :pointer, **opts attach_function :zchanneler_destroy, [:pointer], :void, **opts attach_function :zchanneler_send, [:pointer, :pointer, :int], :int, **opts attach_function :zchanneler_recv, [:pointer], :pointer, **opts attach_function :zchanneler_print, [:pointer], :void, **opts attach_function :zchanneler_test, [:bool], :void, **opts require_relative 'ffi/zchanneler' end end end ################################################################################ # THIS FILE IS 100% GENERATED BY ZPROJECT; DO NOT EDIT EXCEPT EXPERIMENTALLY # # Please refer to the README for information about making permanent changes. # ################################################################################
mpl-2.0
fiji-flo/servo
components/style/values/computed/font.rs
27408
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Computed values for font properties use Atom; use app_units::Au; use byteorder::{BigEndian, ByteOrder}; use cssparser::{CssStringWriter, Parser, serialize_identifier}; #[cfg(feature = "gecko")] use gecko_bindings::{bindings, structs}; #[cfg(feature = "gecko")] use gecko_bindings::sugar::refptr::RefPtr; #[cfg(feature = "gecko")] use malloc_size_of::{MallocSizeOf, MallocSizeOfOps}; use std::fmt::{self, Write}; #[cfg(feature = "gecko")] use std::hash::{Hash, Hasher}; #[cfg(feature = "servo")] use std::slice; use style_traits::{CssWriter, ParseError, ToCss}; use values::CSSFloat; use values::animated::{ToAnimatedValue, ToAnimatedZero}; use values::computed::{Context, NonNegativeLength, ToComputedValue, Integer, Number}; use values::generics::font::{FontSettings, FeatureTagValue}; use values::generics::font::{KeywordInfo as GenericKeywordInfo, VariationValue}; use values::specified::font as specified; use values::specified::length::{FontBaseSize, NoCalcLength}; pub use values::computed::Length as MozScriptMinSize; pub use values::specified::font::{XTextZoom, XLang, MozScriptSizeMultiplier, FontSynthesis}; /// As of CSS Fonts Module Level 3, only the following values are /// valid: 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900 /// /// However, system fonts may provide other values. Pango /// may provide 350, 380, and 1000 (on top of the existing values), for example. #[derive(Clone, ComputeSquaredDistance, Copy, Debug, Eq, Hash, MallocSizeOf, PartialEq, ToCss)] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] pub struct FontWeight(pub u16); #[derive(Animate, ComputeSquaredDistance, MallocSizeOf, ToAnimatedZero)] #[derive(Clone, Copy, Debug, PartialEq)] /// The computed value of font-size pub struct FontSize { /// The size. pub size: NonNegativeLength, /// If derived from a keyword, the keyword and additional transformations applied to it pub keyword_info: Option<KeywordInfo>, } /// Additional information for computed keyword-derived font sizes. pub type KeywordInfo = GenericKeywordInfo<NonNegativeLength>; impl FontWeight { /// Value for normal pub fn normal() -> Self { FontWeight(400) } /// Value for bold pub fn bold() -> Self { FontWeight(700) } /// Convert from an integer to Weight pub fn from_int(n: i32) -> Result<Self, ()> { if n >= 100 && n <= 900 && n % 100 == 0 { Ok(FontWeight(n as u16)) } else { Err(()) } } /// Convert from an Gecko weight pub fn from_gecko_weight(weight: u16) -> Self { // we allow a wider range of weights than is parseable // because system fonts may provide custom values FontWeight(weight) } /// Weither this weight is bold pub fn is_bold(&self) -> bool { self.0 > 500 } /// Return the bolder weight pub fn bolder(self) -> Self { if self.0 < 400 { FontWeight(400) } else if self.0 < 600 { FontWeight(700) } else { FontWeight(900) } } /// Returns the lighter weight pub fn lighter(self) -> Self { if self.0 < 600 { FontWeight(100) } else if self.0 < 800 { FontWeight(400) } else { FontWeight(700) } } } impl FontSize { /// The actual computed font size. pub fn size(self) -> Au { self.size.into() } #[inline] /// Get default value of font size. pub fn medium() -> Self { Self { size: Au::from_px(specified::FONT_MEDIUM_PX).into(), keyword_info: Some(KeywordInfo::medium()) } } /// FIXME(emilio): This is very complex. Also, it should move to /// StyleBuilder. pub fn cascade_inherit_font_size(context: &mut Context) { // If inheriting, we must recompute font-size in case of language // changes using the font_size_keyword. We also need to do this to // handle mathml scriptlevel changes let kw_inherited_size = context.builder.get_parent_font() .clone_font_size() .keyword_info.map(|info| { specified::FontSize::Keyword(info).to_computed_value(context).size }); let mut font = context.builder.take_font(); font.inherit_font_size_from(context.builder.get_parent_font(), kw_inherited_size, context.builder.device); context.builder.put_font(font); } /// Cascade the initial value for the `font-size` property. /// /// FIXME(emilio): This is the only function that is outside of the /// `StyleBuilder`, and should really move inside! /// /// Can we move the font stuff there? pub fn cascade_initial_font_size(context: &mut Context) { // font-size's default ("medium") does not always // compute to the same value and depends on the font let computed = specified::FontSize::medium().to_computed_value(context); context.builder.mutate_font().set_font_size(computed); #[cfg(feature = "gecko")] { let device = context.builder.device; context.builder.mutate_font().fixup_font_min_size(device); } } } impl ToCss for FontSize { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: fmt::Write { self.size.to_css(dest) } } /// XXXManishearth it might be better to /// animate this as computed, however this complicates /// clamping and might not be the right thing to do. /// We should figure it out. impl ToAnimatedValue for FontSize { type AnimatedValue = NonNegativeLength; #[inline] fn to_animated_value(self) -> Self::AnimatedValue { self.size } #[inline] fn from_animated_value(animated: Self::AnimatedValue) -> Self { FontSize { size: animated.clamp(), keyword_info: None, } } } #[derive(Clone, Debug, Eq, Hash, PartialEq)] #[cfg_attr(feature = "servo", derive(MallocSizeOf))] /// Specifies a prioritized list of font family names or generic family names. pub struct FontFamily(pub FontFamilyList); impl FontFamily { #[inline] /// Get default font family as `serif` which is a generic font-family pub fn serif() -> Self { FontFamily( FontFamilyList::new(Box::new([SingleFontFamily::Generic(atom!("serif"))])) ) } } #[cfg(feature = "gecko")] impl MallocSizeOf for FontFamily { fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize { // SharedFontList objects are generally shared from the pointer // stored in the specified value. So only count this if the // SharedFontList is unshared. unsafe { bindings::Gecko_SharedFontList_SizeOfIncludingThisIfUnshared( (self.0).0.get() ) } } } impl ToCss for FontFamily { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: fmt::Write { let mut iter = self.0.iter(); iter.next().unwrap().to_css(dest)?; for family in iter { dest.write_str(", ")?; family.to_css(dest)?; } Ok(()) } } #[derive(Clone, Debug, Eq, Hash, MallocSizeOf, PartialEq)] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] /// The name of a font family of choice pub struct FamilyName { /// Name of the font family pub name: Atom, /// Syntax of the font family pub syntax: FamilyNameSyntax, } impl ToCss for FamilyName { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: fmt::Write { match self.syntax { FamilyNameSyntax::Quoted => { dest.write_char('"')?; write!(CssStringWriter::new(dest), "{}", self.name)?; dest.write_char('"') } FamilyNameSyntax::Identifiers => { let mut first = true; for ident in self.name.to_string().split(' ') { if first { first = false; } else { dest.write_char(' ')?; } debug_assert!(!ident.is_empty(), "Family name with leading, \ trailing, or consecutive white spaces should \ have been marked quoted by the parser"); serialize_identifier(ident, dest)?; } Ok(()) } } } } #[derive(Clone, Debug, Eq, Hash, MallocSizeOf, PartialEq)] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] /// Font family names must either be given quoted as strings, /// or unquoted as a sequence of one or more identifiers. pub enum FamilyNameSyntax { /// The family name was specified in a quoted form, e.g. "Font Name" /// or 'Font Name'. Quoted, /// The family name was specified in an unquoted form as a sequence of /// identifiers. Identifiers, } #[derive(Clone, Debug, Eq, Hash, MallocSizeOf, PartialEq)] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] /// A set of faces that vary in weight, width or slope. pub enum SingleFontFamily { /// The name of a font family of choice. FamilyName(FamilyName), /// Generic family name. Generic(Atom), } impl SingleFontFamily { #[inline] /// Get font family name as Atom pub fn atom(&self) -> &Atom { match *self { SingleFontFamily::FamilyName(ref family_name) => &family_name.name, SingleFontFamily::Generic(ref name) => name, } } #[inline] #[cfg(not(feature = "gecko"))] // Gecko can't borrow atoms as UTF-8. /// Get font family name pub fn name(&self) -> &str { self.atom() } #[cfg(not(feature = "gecko"))] // Gecko can't borrow atoms as UTF-8. /// Get the corresponding font-family with Atom pub fn from_atom(input: Atom) -> SingleFontFamily { match input { atom!("serif") | atom!("sans-serif") | atom!("cursive") | atom!("fantasy") | atom!("monospace") => { return SingleFontFamily::Generic(input) } _ => {} } match_ignore_ascii_case! { &input, "serif" => return SingleFontFamily::Generic(atom!("serif")), "sans-serif" => return SingleFontFamily::Generic(atom!("sans-serif")), "cursive" => return SingleFontFamily::Generic(atom!("cursive")), "fantasy" => return SingleFontFamily::Generic(atom!("fantasy")), "monospace" => return SingleFontFamily::Generic(atom!("monospace")), _ => {} } // We don't know if it's quoted or not. So we set it to // quoted by default. SingleFontFamily::FamilyName(FamilyName { name: input, syntax: FamilyNameSyntax::Quoted, }) } /// Parse a font-family value pub fn parse<'i, 't>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> { if let Ok(value) = input.try(|i| i.expect_string_cloned()) { return Ok(SingleFontFamily::FamilyName(FamilyName { name: Atom::from(&*value), syntax: FamilyNameSyntax::Quoted, })) } let first_ident = input.expect_ident()?.clone(); // FIXME(bholley): The fast thing to do here would be to look up the // string (as lowercase) in the static atoms table. We don't have an // API to do that yet though, so we do the simple thing for now. let mut css_wide_keyword = false; match_ignore_ascii_case! { &first_ident, "serif" => return Ok(SingleFontFamily::Generic(atom!("serif"))), "sans-serif" => return Ok(SingleFontFamily::Generic(atom!("sans-serif"))), "cursive" => return Ok(SingleFontFamily::Generic(atom!("cursive"))), "fantasy" => return Ok(SingleFontFamily::Generic(atom!("fantasy"))), "monospace" => return Ok(SingleFontFamily::Generic(atom!("monospace"))), #[cfg(feature = "gecko")] "-moz-fixed" => return Ok(SingleFontFamily::Generic(atom!("-moz-fixed"))), // https://drafts.csswg.org/css-fonts/#propdef-font-family // "Font family names that happen to be the same as a keyword value // (`inherit`, `serif`, `sans-serif`, `monospace`, `fantasy`, and `cursive`) // must be quoted to prevent confusion with the keywords with the same names. // The keywords ‘initial’ and ‘default’ are reserved for future use // and must also be quoted when used as font names. // UAs must not consider these keywords as matching the <family-name> type." "inherit" => css_wide_keyword = true, "initial" => css_wide_keyword = true, "unset" => css_wide_keyword = true, "default" => css_wide_keyword = true, _ => {} } let mut value = first_ident.as_ref().to_owned(); // These keywords are not allowed by themselves. // The only way this value can be valid with with another keyword. if css_wide_keyword { let ident = input.expect_ident()?; value.push(' '); value.push_str(&ident); } while let Ok(ident) = input.try(|i| i.expect_ident_cloned()) { value.push(' '); value.push_str(&ident); } let syntax = if value.starts_with(' ') || value.ends_with(' ') || value.contains(" ") { // For font family names which contains special white spaces, e.g. // `font-family: \ a\ \ b\ \ c\ ;`, it is tricky to serialize them // as identifiers correctly. Just mark them quoted so we don't need // to worry about them in serialization code. FamilyNameSyntax::Quoted } else { FamilyNameSyntax::Identifiers }; Ok(SingleFontFamily::FamilyName(FamilyName { name: Atom::from(value), syntax })) } #[cfg(feature = "gecko")] /// Return the generic ID for a given generic font name pub fn generic(name: &Atom) -> (structs::FontFamilyType, u8) { use gecko_bindings::structs::FontFamilyType; if *name == atom!("serif") { (FontFamilyType::eFamily_serif, structs::kGenericFont_serif) } else if *name == atom!("sans-serif") { (FontFamilyType::eFamily_sans_serif, structs::kGenericFont_sans_serif) } else if *name == atom!("cursive") { (FontFamilyType::eFamily_cursive, structs::kGenericFont_cursive) } else if *name == atom!("fantasy") { (FontFamilyType::eFamily_fantasy, structs::kGenericFont_fantasy) } else if *name == atom!("monospace") { (FontFamilyType::eFamily_monospace, structs::kGenericFont_monospace) } else if *name == atom!("-moz-fixed") { (FontFamilyType::eFamily_moz_fixed, structs::kGenericFont_moz_fixed) } else { panic!("Unknown generic {}", name); } } #[cfg(feature = "gecko")] /// Get the corresponding font-family with family name fn from_font_family_name(family: &structs::FontFamilyName) -> SingleFontFamily { use gecko_bindings::structs::FontFamilyType; match family.mType { FontFamilyType::eFamily_sans_serif => SingleFontFamily::Generic(atom!("sans-serif")), FontFamilyType::eFamily_serif => SingleFontFamily::Generic(atom!("serif")), FontFamilyType::eFamily_monospace => SingleFontFamily::Generic(atom!("monospace")), FontFamilyType::eFamily_cursive => SingleFontFamily::Generic(atom!("cursive")), FontFamilyType::eFamily_fantasy => SingleFontFamily::Generic(atom!("fantasy")), FontFamilyType::eFamily_moz_fixed => SingleFontFamily::Generic(Atom::from("-moz-fixed")), FontFamilyType::eFamily_named => { let name = Atom::from(&*family.mName); SingleFontFamily::FamilyName(FamilyName { name, syntax: FamilyNameSyntax::Identifiers, }) }, FontFamilyType::eFamily_named_quoted => SingleFontFamily::FamilyName(FamilyName { name: (&*family.mName).into(), syntax: FamilyNameSyntax::Quoted, }), _ => panic!("Found unexpected font FontFamilyType"), } } } impl ToCss for SingleFontFamily { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: fmt::Write { match *self { SingleFontFamily::FamilyName(ref name) => name.to_css(dest), // All generic values accepted by the parser are known to not require escaping. SingleFontFamily::Generic(ref name) => { #[cfg(feature = "gecko")] { // We should treat -moz-fixed as monospace if name == &atom!("-moz-fixed") { return dest.write_str("monospace"); } } write!(dest, "{}", name) }, } } } #[cfg(feature = "servo")] #[derive(Clone, Debug, Eq, Hash, MallocSizeOf, PartialEq)] /// A list of SingleFontFamily pub struct FontFamilyList(Box<[SingleFontFamily]>); #[cfg(feature = "gecko")] #[derive(Clone, Debug)] /// A list of SingleFontFamily pub struct FontFamilyList(pub RefPtr<structs::SharedFontList>); #[cfg(feature = "gecko")] impl Hash for FontFamilyList { fn hash<H>(&self, state: &mut H) where H: Hasher { for name in self.0.mNames.iter() { name.mType.hash(state); name.mName.hash(state); } } } #[cfg(feature = "gecko")] impl PartialEq for FontFamilyList { fn eq(&self, other: &FontFamilyList) -> bool { if self.0.mNames.len() != other.0.mNames.len() { return false; } for (a, b) in self.0.mNames.iter().zip(other.0.mNames.iter()) { if a.mType != b.mType || &*a.mName != &*b.mName { return false; } } true } } #[cfg(feature = "gecko")] impl Eq for FontFamilyList {} impl FontFamilyList { #[cfg(feature = "servo")] /// Return FontFamilyList with a vector of SingleFontFamily pub fn new(families: Box<[SingleFontFamily]>) -> FontFamilyList { FontFamilyList(families) } #[cfg(feature = "gecko")] /// Return FontFamilyList with a vector of SingleFontFamily pub fn new(families: Box<[SingleFontFamily]>) -> FontFamilyList { let fontlist; let names; unsafe { fontlist = bindings::Gecko_SharedFontList_Create(); names = &mut (*fontlist).mNames; names.ensure_capacity(families.len()); }; for family in families.iter() { match *family { SingleFontFamily::FamilyName(ref f) => { let quoted = matches!(f.syntax, FamilyNameSyntax::Quoted); unsafe { bindings::Gecko_nsTArray_FontFamilyName_AppendNamed( names, f.name.as_ptr(), quoted ); } } SingleFontFamily::Generic(ref name) => { let (family_type, _generic) = SingleFontFamily::generic(name); unsafe { bindings::Gecko_nsTArray_FontFamilyName_AppendGeneric( names, family_type ); } } } } FontFamilyList(unsafe { RefPtr::from_addrefed(fontlist) }) } #[cfg(feature = "servo")] /// Return iterator of SingleFontFamily pub fn iter(&self) -> slice::Iter<SingleFontFamily> { self.0.iter() } #[cfg(feature = "gecko")] /// Return iterator of SingleFontFamily pub fn iter(&self) -> FontFamilyNameIter { FontFamilyNameIter { names: &self.0.mNames, cur: 0, } } #[cfg(feature = "gecko")] /// Return the generic ID if it is a single generic font pub fn single_generic(&self) -> Option<u8> { let mut iter = self.iter(); if let Some(SingleFontFamily::Generic(ref name)) = iter.next() { if iter.next().is_none() { return Some(SingleFontFamily::generic(name).1); } } None } } #[cfg(feature = "gecko")] /// Iterator of FontFamily pub struct FontFamilyNameIter<'a> { names: &'a structs::nsTArray<structs::FontFamilyName>, cur: usize, } #[cfg(feature = "gecko")] impl<'a> Iterator for FontFamilyNameIter<'a> { type Item = SingleFontFamily; fn next(&mut self) -> Option<Self::Item> { if self.cur < self.names.len() { let item = SingleFontFamily::from_font_family_name(&self.names[self.cur]); self.cur += 1; Some(item) } else { None } } } #[derive(Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, ToCss)] /// Preserve the readability of text when font fallback occurs pub enum FontSizeAdjust { #[animation(error)] /// None variant None, /// Number variant Number(CSSFloat), } impl FontSizeAdjust { #[inline] /// Default value of font-size-adjust pub fn none() -> Self { FontSizeAdjust::None } /// Get font-size-adjust with float number pub fn from_gecko_adjust(gecko: f32) -> Self { if gecko == -1.0 { FontSizeAdjust::None } else { FontSizeAdjust::Number(gecko) } } } impl ToAnimatedZero for FontSizeAdjust { #[inline] // FIXME(emilio): why? fn to_animated_zero(&self) -> Result<Self, ()> { Err(()) } } impl ToAnimatedValue for FontSizeAdjust { type AnimatedValue = Self; #[inline] fn to_animated_value(self) -> Self { self } #[inline] fn from_animated_value(animated: Self::AnimatedValue) -> Self { match animated { FontSizeAdjust::Number(number) => FontSizeAdjust::Number(number.max(0.)), _ => animated } } } /// Use VariantAlternatesList as computed type of FontVariantAlternates pub type FontVariantAlternates = specified::VariantAlternatesList; impl FontVariantAlternates { #[inline] /// Get initial value with VariantAlternatesList pub fn get_initial_value() -> Self { specified::VariantAlternatesList(vec![].into_boxed_slice()) } } /// Use VariantEastAsian as computed type of FontVariantEastAsian pub type FontVariantEastAsian = specified::VariantEastAsian; /// Use VariantLigatures as computed type of FontVariantLigatures pub type FontVariantLigatures = specified::VariantLigatures; /// Use VariantNumeric as computed type of FontVariantNumeric pub type FontVariantNumeric = specified::VariantNumeric; /// Use FontSettings as computed type of FontFeatureSettings. pub type FontFeatureSettings = FontSettings<FeatureTagValue<Integer>>; /// The computed value for font-variation-settings. pub type FontVariationSettings = FontSettings<VariationValue<Number>>; /// font-language-override can only have a single three-letter /// OpenType "language system" tag, so we should be able to compute /// it and store it as a 32-bit integer /// (see http://www.microsoft.com/typography/otspec/languagetags.htm). #[derive(Clone, Copy, Debug, Eq, MallocSizeOf, PartialEq)] pub struct FontLanguageOverride(pub u32); impl FontLanguageOverride { #[inline] /// Get computed default value of `font-language-override` with 0 pub fn zero() -> FontLanguageOverride { FontLanguageOverride(0) } } impl ToCss for FontLanguageOverride { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: fmt::Write { use std::str; if self.0 == 0 { return dest.write_str("normal") } let mut buf = [0; 4]; BigEndian::write_u32(&mut buf, self.0); // Safe because we ensure it's ASCII during computing let slice = if cfg!(debug_assertions) { str::from_utf8(&buf).unwrap() } else { unsafe { str::from_utf8_unchecked(&buf) } }; slice.trim_right().to_css(dest) } } #[cfg(feature = "gecko")] impl From<u32> for FontLanguageOverride { fn from(bits: u32) -> FontLanguageOverride { FontLanguageOverride(bits) } } #[cfg(feature = "gecko")] impl From<FontLanguageOverride> for u32 { fn from(v: FontLanguageOverride) -> u32 { v.0 } } impl ToComputedValue for specified::MozScriptMinSize { type ComputedValue = MozScriptMinSize; fn to_computed_value(&self, cx: &Context) -> MozScriptMinSize { // this value is used in the computation of font-size, so // we use the parent size let base_size = FontBaseSize::InheritedStyle; match self.0 { NoCalcLength::FontRelative(value) => { value.to_computed_value(cx, base_size) } NoCalcLength::ServoCharacterWidth(value) => { value.to_computed_value(base_size.resolve(cx)) } ref l => { l.to_computed_value(cx) } } } fn from_computed_value(other: &MozScriptMinSize) -> Self { specified::MozScriptMinSize(ToComputedValue::from_computed_value(other)) } } /// The computed value of the -moz-script-level property. pub type MozScriptLevel = i8; #[cfg(feature = "gecko")] impl ToComputedValue for specified::MozScriptLevel { type ComputedValue = MozScriptLevel; fn to_computed_value(&self, cx: &Context) -> i8 { use properties::longhands::_moz_math_display::SpecifiedValue as DisplayValue; use std::{cmp, i8}; let int = match *self { specified::MozScriptLevel::Auto => { let parent = cx.builder.get_parent_font().clone__moz_script_level() as i32; let display = cx.builder.get_parent_font().clone__moz_math_display(); if display == DisplayValue::Inline { parent + 1 } else { parent } } specified::MozScriptLevel::Relative(rel) => { let parent = cx.builder.get_parent_font().clone__moz_script_level(); parent as i32 + rel } specified::MozScriptLevel::MozAbsolute(abs) => abs, }; cmp::min(int, i8::MAX as i32) as i8 } fn from_computed_value(other: &i8) -> Self { specified::MozScriptLevel::MozAbsolute(*other as i32) } }
mpl-2.0
VolumetricPixels/Questy
src/test/java/com/volumetricpixels/questy/test/EventsTest.java
1392
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.volumetricpixels.questy.test; import org.junit.Assert; import org.junit.Test; import com.volumetricpixels.questy.SimpleQuestManager; import com.volumetricpixels.questy.event.EventManager; import com.volumetricpixels.questy.event.Listen; import com.volumetricpixels.questy.event.quest.QuestAbandonEvent; import com.volumetricpixels.questy.event.quest.QuestStartEvent; public class EventsTest { @Test public void testEvents() { EventManager evtMgr = new SimpleQuestManager(null).getEventManager(); TestListener test = new TestListener(); Assert.assertTrue(evtMgr.register(test)); Assert.assertFalse(testBool); evtMgr.fire(new QuestStartEvent(null)); Assert.assertTrue(testBool); testBool = false; evtMgr.unregister(test); evtMgr.fire(new QuestStartEvent(null)); Assert.assertFalse(testBool); evtMgr.fire(new QuestAbandonEvent(null)); Assert.assertFalse(testBool); } private boolean testBool = false; public class TestListener { @Listen public void onQuestStart(QuestStartEvent event) { testBool = true; } } }
mpl-2.0
ajschult/etomica
etomica-core/src/main/java/etomica/data/meter/MeterKineticEnergyFromIntegrator.java
1108
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package etomica.data.meter; import etomica.data.DataSourceScalar; import etomica.integrator.IntegratorMD; import etomica.units.Energy; /** * Acts as a DataSource to retrieve the energy from the integrator */ public class MeterKineticEnergyFromIntegrator extends DataSourceScalar { public MeterKineticEnergyFromIntegrator() { super("Kinetic Energy",Energy.DIMENSION); } public MeterKineticEnergyFromIntegrator(IntegratorMD aIntegrator) { this(); setIntegrator(aIntegrator); } public void setIntegrator(IntegratorMD newIntegrator) { integrator = newIntegrator; } public IntegratorMD getIntegrator() { return integrator; } public double getDataAsScalar() { return integrator.getKineticEnergy(); } private static final long serialVersionUID = 1L; private IntegratorMD integrator; }
mpl-2.0
jogubern/random
README.md
86
# random Aplicación que determina si un número entre 0 y 1 es mayor o menor que 0,5
mpl-2.0
Yukarumya/Yukarum-Redfoxes
dom/html/test/test_bug566046.html
7469
<!DOCTYPE HTML> <html> <!-- https://bugzilla.mozilla.org/show_bug.cgi?id=566046 --> <head> <title>Test for Bug 566046</title> <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> <script type="application/javascript" src="/tests/SimpleTest/EventUtils.js"></script> <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> <base> <base target='frame2'> <base target=''> </head> <body> <a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=566046">Mozilla Bug 566046</a> <p id="display"></p> <style> iframe { width: 130px; height: 100px;} </style> <iframe name='frame1' id='frame1'></iframe> <iframe name='frame2' id='frame2'></iframe> <iframe name='frame3' id='frame3'></iframe> <iframe name='frame4' id='frame4'></iframe> <iframe name='frame5' id='frame5'></iframe> <iframe name='frame5bis' id='frame5bis'></iframe> <iframe name='frame6' id='frame6'></iframe> <iframe name='frame7' id='frame7'></iframe> <iframe name='frame8' id='frame8'></iframe> <iframe name='frame9' id='frame9'></iframe> <div id="content"> <form target='frame1' action="data:text/html," method="GET"> <input name='foo' value='foo'> </form> <form action="data:text/html," method="GET"> <input name='bar' value='bar'> </form> <form target=""> </form> <!-- submit controls with formtarget that are validated with a CLICK --> <form target="tulip" action="data:text/html," method="GET"> <input name='tulip' value='tulip'> <input type='submit' id='is' formtarget='frame3'> </form> <form action="data:text/html," method="GET"> <input name='foobar' value='foobar'> <input type='image' id='ii' formtarget='frame4'> </form> <form action="data:text/html," method="GET"> <input name='tulip2' value='tulip2'> <button type='submit' id='bs' formtarget='frame5'>submit</button> </form> <form action="data:text/html," method="GET"> <input name='tulip3' value='tulip3'> <button type='submit' id='bsbis' formtarget='frame5bis'>submit</button> </form> <!-- submit controls with formtarget that are validated with ENTER --> <form target="tulip" action="data:text/html," method="GET"> <input name='footulip' value='footulip'> <input type='submit' id='is2' formtarget='frame6'> </form> <form action="data:text/html," method="GET"> <input name='tulipfoobar' value='tulipfoobar'> <input type='image' id='ii2' formtarget='frame7'> </form> <form action="data:text/html," method="GET"> <input name='tulipbar' value='tulipbar'> <button type='submit' id='bs2' formtarget='frame8'>submit</button> </form> <!-- check that a which is not a submit control do not use @formtarget --> <form target='frame9' action="data:text/html," method="GET"> <input id='enter' name='input' value='enter' formtarget='frame6'> </form> </div> <pre id="test"> <script type="application/javascript"> /** Test for Bug 566046 **/ SimpleTest.waitForExplicitFinish(); addLoadEvent(function() { setTimeout(runTests, 0); }); var gTestResults = { frame1: "data:text/html,?foo=foo", frame2: "data:text/html,?bar=bar", frame3: "data:text/html,?tulip=tulip", frame4: "data:text/html,?foobar=foobar&x=0&y=0", frame5: "data:text/html,?tulip2=tulip2", frame5bis: "data:text/html,?tulip3=tulip3", frame6: "data:text/html,?footulip=footulip", frame7: "data:text/html,?tulipfoobar=tulipfoobar&x=0&y=0", frame8: "data:text/html,?tulipbar=tulipbar", frame9: "data:text/html,?input=enter", }; var gPendingLoad = 0; // Has to be set after depending on the frames number. function runTests() { // Check the target IDL attribute. for (var i=0; i<document.forms.length; ++i) { var testValue = document.forms[i].getAttribute('target'); is(document.forms[i].target, testValue ? testValue : "", "target IDL attribute should reflect the target content attribute"); } // We add a load event for the frames which will be called when the forms // will be submitted. var frames = [ document.getElementById('frame1'), document.getElementById('frame2'), document.getElementById('frame3'), document.getElementById('frame4'), document.getElementById('frame5'), document.getElementById('frame5bis'), document.getElementById('frame6'), document.getElementById('frame7'), document.getElementById('frame8'), document.getElementById('frame9'), ]; gPendingLoad = frames.length; for (var i=0; i<frames.length; i++) { frames[i].setAttribute('onload', "frameLoaded(this);"); } // Submitting only the forms with a valid target. document.forms[0].submit(); document.forms[1].submit(); /** * We are going to focus each element before interacting with either for * simulating the ENTER key (synthesizeKey) or a click (synthesizeMouse) or * using .click(). This because it may be needed (ENTER) and because we want * to have the element visible in the iframe. * * Focusing the first element (id='is') is launching the tests. */ document.getElementById('is').addEventListener('focus', function(aEvent) { aEvent.target.removeEventListener('focus', arguments.callee); synthesizeMouse(document.getElementById('is'), 5, 5, {}); document.getElementById('ii').focus(); }); document.getElementById('ii').addEventListener('focus', function(aEvent) { aEvent.target.removeEventListener('focus', arguments.callee); synthesizeMouse(document.getElementById('ii'), 5, 5, {}); document.getElementById('bs').focus(); }); document.getElementById('bs').addEventListener('focus', function(aEvent) { aEvent.target.removeEventListener('focus', arguments.callee); synthesizeMouse(document.getElementById('bs'), 5, 5, {}); document.getElementById('bsbis').focus(); }); document.getElementById('bsbis').addEventListener('focus', function(aEvent) { aEvent.target.removeEventListener('focus', arguments.callee); document.getElementById('bsbis').click(); document.getElementById('is2').focus(); }); document.getElementById('is2').addEventListener('focus', function(aEvent) { aEvent.target.removeEventListener('focus', arguments.callee); synthesizeKey("VK_RETURN", {}); document.getElementById('ii2').focus(); }); document.getElementById('ii2').addEventListener('focus', function(aEvent) { aEvent.target.removeEventListener('focus', arguments.callee); synthesizeKey("VK_RETURN", {}); document.getElementById('bs2').focus(); }); document.getElementById('bs2').addEventListener('focus', function(aEvent) { aEvent.target.removeEventListener('focus', arguments.callee); synthesizeKey("VK_RETURN", {}); document.getElementById('enter').focus(); }); document.getElementById('enter').addEventListener('focus', function(aEvent) { aEvent.target.removeEventListener('focus', arguments.callee); synthesizeKey("VK_RETURN", {}); }); document.getElementById('is').focus(); } function frameLoaded(aFrame) { // Check if when target is unspecified, it fallback correctly to the base // element target attribute. is(aFrame.contentWindow.location.href, gTestResults[aFrame.name], "the target attribute doesn't have the correct behavior"); if (--gPendingLoad == 0) { SimpleTest.finish(); } } </script> </pre> </body> </html>
mpl-2.0
spil-peter-forgacs/weebubble
src/TitleScreen.js
1827
/** * The title screen. */ // SDK imports import ui.View; import ui.ImageView; import ui.TextView as TextView; import ui.widget.ButtonView as ButtonView; exports = Class(ui.ImageView, function (supr) { this.init = function (opts) { this._config = JSON.parse(CACHE['resources/conf/config.json']); opts = merge(opts, { x: 0, y: 0, width: this._config.screenWidth, height: this._config.screenHeight, image: "resources/images/bg1.jpg" }); supr(this, 'init', [opts]); this.build(); }; this.build = function() { var buttonWidth = 294; var buttonHeight = 61; var deviceWidth = this._config.screenWidth; var deviceHeight = this._config.screenHeight; var textview = new TextView({ superview: this, x: 0, y: 15, width: this._config.screenWidth, height: 50, text: "WeeBubble", autoSize: false, size: 38, verticalAlign: 'middle', horizontalAlign: 'center', wrap: false, color: '#000099' }); var buttonview = new ButtonView({ superview: this, width: buttonWidth, height: buttonHeight, x: (deviceWidth - buttonWidth) / 2, y: 3 * deviceHeight / 4, images: { down: "resources/images/start_button_selected.jpg", up: "resources/images/start_button_unselected.jpg" }, on: { down: bind(this, function () { }), up: bind(this, function () { this.emit('titlescreen:start'); }) } }); }; });
mpl-2.0
5y/MozStumbler
src/org/mozilla/mozstumbler/AboutActivity.java
1423
package org.mozilla.mozstumbler; import android.net.Uri; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.view.Menu; import android.view.View; import android.widget.TextView; public class AboutActivity extends Activity { private static final String ABOUT_PAGE_URL = "https://location.services.mozilla.com/"; private static final String ABOUT_MAPBOX_URL = "https://www.mapbox.com/about/maps/"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_about); } @Override protected void onStart() { super.onStart(); TextView textView = (TextView) findViewById(R.id.about_version); String str = getResources().getString(R.string.about_version); str = String.format(str, PackageUtils.getAppVersion(this)); textView.setText(str); } public void onClick_ViewMore(View v) { Intent openAboutPage = new Intent(Intent.ACTION_VIEW, Uri.parse(ABOUT_PAGE_URL)); startActivity(openAboutPage); } public void onClick_ViewMapboxAttribution(View v) { Intent openMapboxPage = new Intent(Intent.ACTION_VIEW, Uri.parse(ABOUT_MAPBOX_URL)); startActivity(openMapboxPage); } @Override public boolean onCreateOptionsMenu(Menu menu) { return false; } }
mpl-2.0
brendanhay/gogol
gogol-speech/gen/Network/Google/Resource/Speech/Speech/Recognize.hs
4663
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Speech.Speech.Recognize -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Performs synchronous speech recognition: receive results after all audio -- has been sent and processed. -- -- /See:/ <https://cloud.google.com/speech-to-text/docs/quickstart-protocol Cloud Speech-to-Text API Reference> for @speech.speech.recognize@. module Network.Google.Resource.Speech.Speech.Recognize ( -- * REST Resource SpeechRecognizeResource -- * Creating a Request , speechRecognize , SpeechRecognize -- * Request Lenses , srXgafv , srUploadProtocol , srAccessToken , srUploadType , srPayload , srCallback ) where import Network.Google.Prelude import Network.Google.Speech.Types -- | A resource alias for @speech.speech.recognize@ method which the -- 'SpeechRecognize' request conforms to. type SpeechRecognizeResource = "v1p1beta1" :> "speech:recognize" :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] RecognizeRequest :> Post '[JSON] RecognizeResponse -- | Performs synchronous speech recognition: receive results after all audio -- has been sent and processed. -- -- /See:/ 'speechRecognize' smart constructor. data SpeechRecognize = SpeechRecognize' { _srXgafv :: !(Maybe Xgafv) , _srUploadProtocol :: !(Maybe Text) , _srAccessToken :: !(Maybe Text) , _srUploadType :: !(Maybe Text) , _srPayload :: !RecognizeRequest , _srCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'SpeechRecognize' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'srXgafv' -- -- * 'srUploadProtocol' -- -- * 'srAccessToken' -- -- * 'srUploadType' -- -- * 'srPayload' -- -- * 'srCallback' speechRecognize :: RecognizeRequest -- ^ 'srPayload' -> SpeechRecognize speechRecognize pSrPayload_ = SpeechRecognize' { _srXgafv = Nothing , _srUploadProtocol = Nothing , _srAccessToken = Nothing , _srUploadType = Nothing , _srPayload = pSrPayload_ , _srCallback = Nothing } -- | V1 error format. srXgafv :: Lens' SpeechRecognize (Maybe Xgafv) srXgafv = lens _srXgafv (\ s a -> s{_srXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). srUploadProtocol :: Lens' SpeechRecognize (Maybe Text) srUploadProtocol = lens _srUploadProtocol (\ s a -> s{_srUploadProtocol = a}) -- | OAuth access token. srAccessToken :: Lens' SpeechRecognize (Maybe Text) srAccessToken = lens _srAccessToken (\ s a -> s{_srAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). srUploadType :: Lens' SpeechRecognize (Maybe Text) srUploadType = lens _srUploadType (\ s a -> s{_srUploadType = a}) -- | Multipart request metadata. srPayload :: Lens' SpeechRecognize RecognizeRequest srPayload = lens _srPayload (\ s a -> s{_srPayload = a}) -- | JSONP srCallback :: Lens' SpeechRecognize (Maybe Text) srCallback = lens _srCallback (\ s a -> s{_srCallback = a}) instance GoogleRequest SpeechRecognize where type Rs SpeechRecognize = RecognizeResponse type Scopes SpeechRecognize = '["https://www.googleapis.com/auth/cloud-platform"] requestClient SpeechRecognize'{..} = go _srXgafv _srUploadProtocol _srAccessToken _srUploadType _srCallback (Just AltJSON) _srPayload speechService where go = buildClient (Proxy :: Proxy SpeechRecognizeResource) mempty
mpl-2.0
ArtMares/PQStudio
Builder/plastiq/include/widgets/PlastiQQVBoxLayout/plastiqqvboxlayout.cpp
4622
#include "plastiqmethod.h" #include "plastiqqvboxlayout.h" #include "widgets/PlastiQQBoxLayout/plastiqqboxlayout.h" #include <QVBoxLayout> QHash<QByteArray, PlastiQMethod> PlastiQQVBoxLayout::plastiqConstructors = { { "QVBoxLayout()", { "QVBoxLayout", "", "QVBoxLayout*", 0, PlastiQMethod::Public, PlastiQMethod::Constructor } }, { "QVBoxLayout(QWidget*)", { "QVBoxLayout", "QWidget*", "QVBoxLayout*", 1, PlastiQMethod::Public, PlastiQMethod::Constructor } }, }; QHash<QByteArray, PlastiQMethod> PlastiQQVBoxLayout::plastiqMethods = { }; QHash<QByteArray, PlastiQMethod> PlastiQQVBoxLayout::plastiqSignals = { }; QHash<QByteArray, PlastiQProperty> PlastiQQVBoxLayout::plastiqProperties = { }; QHash<QByteArray, long> PlastiQQVBoxLayout::plastiqConstants = { }; QVector<PlastiQMetaObject*> PlastiQQVBoxLayout::plastiqInherits = { &PlastiQQBoxLayout::plastiq_static_metaObject }; const PlastiQ::ObjectType PlastiQQVBoxLayout::plastiq_static_objectType = PlastiQ::IsQObject; PlastiQMetaObject PlastiQQVBoxLayout::plastiq_static_metaObject = { { &PlastiQQBoxLayout::plastiq_static_metaObject, &plastiqInherits, "QVBoxLayout", &plastiq_static_objectType, &plastiqConstructors, &plastiqMethods, &plastiqSignals, &plastiqProperties, &plastiqConstants, plastiq_static_metacall } }; const PlastiQMetaObject *PlastiQQVBoxLayout::plastiq_metaObject() const { return &plastiq_static_metaObject; } void PlastiQQVBoxLayout::plastiq_static_metacall(PlastiQObject *object, PlastiQMetaObject::Call call, int id, const PMOGStack &stack) { if(call == PlastiQMetaObject::CreateInstance) { QVBoxLayout *o = Q_NULLPTR; switch(id) { case 0: o = new QVBoxLayout(); break; case 1: o = new QVBoxLayout(reinterpret_cast<QWidget*>(stack[1].s_voidp)); break; default: ; } /*%UPDATEWRAPPER%*/ PlastiQQVBoxLayout *p = new PlastiQQVBoxLayout(); p->plastiq_setData(reinterpret_cast<void*>(o), p); PlastiQObject *po = static_cast<PlastiQObject*>(p); *reinterpret_cast<PlastiQObject**>(stack[0].s_voidpp) = po; } else if(call == PlastiQMetaObject::CreateDataInstance) { PlastiQQVBoxLayout *p = new PlastiQQVBoxLayout(); p->plastiq_setData(stack[1].s_voidp, p); *reinterpret_cast<PlastiQObject**>(stack[0].s_voidpp) = p; } else if(call == PlastiQMetaObject::InvokeMethod || call == PlastiQMetaObject::InvokeStaticMember) { if(id >= 0) { id -= 0; PlastiQQBoxLayout::plastiq_static_metaObject.d.static_metacall(object, call, id, stack); return; } bool sc = call == PlastiQMetaObject::InvokeStaticMember; bool isWrapper = sc ? false : object->isWrapper(); QVBoxLayout *o = sc ? Q_NULLPTR : reinterpret_cast<QVBoxLayout*>(object->plastiq_data()); switch(id) { default: ; } } else if(call == PlastiQMetaObject::CreateConnection) { if(id >= 0) { id -= 0; PlastiQQBoxLayout::plastiq_static_metaObject.d.static_metacall(object, call, id, stack); return; } QVBoxLayout *o = reinterpret_cast<QVBoxLayout*>(object->plastiq_data()); PQObjectWrapper *sender = reinterpret_cast<PQObjectWrapper *>(stack[1].s_voidp); PQObjectWrapper *receiver = reinterpret_cast<PQObjectWrapper *>(stack[2].s_voidp); QByteArray slot = stack[3].s_bytearray; switch(id) { default: ; } } else if(call == PlastiQMetaObject::ToQObject) { QVBoxLayout *o = reinterpret_cast<QVBoxLayout*>(object->plastiq_data()); QObject *qo = qobject_cast<QObject*>(o); *reinterpret_cast<QObject**>(stack[0].s_voidpp) = qo; } else if(call == PlastiQMetaObject::HaveParent) { QVBoxLayout *o = reinterpret_cast<QVBoxLayout*>(object->plastiq_data()); stack[0].s_bool = o->parent() != Q_NULLPTR; } else if(call == PlastiQMetaObject::DownCast) { QByteArray className = stack[1].s_bytearray; QVBoxLayout *o = reinterpret_cast<QVBoxLayout*>(object->plastiq_data()); if(className == "QBoxLayout") { stack[0].s_voidp = static_cast<QBoxLayout*>(o); } else { stack[0].s_voidp = Q_NULLPTR; stack[0].name = "Q_NULLPTR"; } } } PlastiQQVBoxLayout::~PlastiQQVBoxLayout() { QVBoxLayout* o = reinterpret_cast<QVBoxLayout*>(plastiq_data()); if(o != Q_NULLPTR) { delete o; } o = Q_NULLPTR; plastiq_setData(Q_NULLPTR, Q_NULLPTR); }
mpl-2.0
regexident/cargo-modules
tests/generate_tree.rs
9150
#[macro_use] mod util; mod colors { mod plain { test_cmd!( args: "generate tree", success: true, color_mode: ColorMode::Plain, project: smoke ); } } mod default { mod pass { test_cmds!( args: "generate tree", success: true, color_mode: ColorMode::Plain, projects: [ package_bin_target, package_lib_target, virtual_workspace_single_package_lib_target, virtual_workspace_single_package_bin_target, workspace_single_package_lib_target, workspace_single_package_bin_target, ] ); } mod fail { test_cmds!( args: "generate tree", success: false, color_mode: ColorMode::Plain, projects: [ package_multi_target, virtual_workspace_single_package_multi_target, workspace_single_package_multi_target, ] ); } } mod lib { mod pass { test_cmds!( args: "generate tree \ --lib", success: true, color_mode: ColorMode::Plain, projects: [ package_lib_target, package_multi_target, virtual_workspace_single_package_lib_target, virtual_workspace_single_package_multi_target, workspace_single_package_lib_target, workspace_single_package_multi_target, ] ); } mod fail { test_cmds!( args: "generate tree \ --lib", // does not exist success: false, color_mode: ColorMode::Plain, projects: [ package_bin_target, virtual_workspace_single_package_bin_target, workspace_single_package_bin_target, ] ); } } mod bin { mod pass { test_cmds!( args: "generate tree \ --bin package_bin_target", success: true, color_mode: ColorMode::Plain, projects: [ package_bin_target, virtual_workspace_single_package_bin_target, workspace_single_package_bin_target, ] ); test_cmds!( args: "generate tree \ --bin package_multi_target", success: true, color_mode: ColorMode::Plain, projects: [ package_multi_target, virtual_workspace_single_package_multi_target, workspace_single_package_multi_target, ] ); } mod fail { test_cmds!( args: "generate tree \ --bin foobar", // does not exist success: false, color_mode: ColorMode::Plain, projects: [ package_lib_target, package_multi_target, virtual_workspace_multi_package, virtual_workspace_single_package_lib_target, virtual_workspace_single_package_multi_target, workspace_multi_package, workspace_single_package_lib_target, workspace_single_package_multi_target, ] ); } } mod package { mod pass { test_cmds!( args: "generate tree \ --package package_lib_target", success: true, color_mode: ColorMode::Plain, projects: [ package_lib_target, virtual_workspace_single_package_lib_target, workspace_single_package_lib_target, ] ); test_cmds!( args: "generate tree \ --package package_bin_target", success: true, color_mode: ColorMode::Plain, projects: [ package_bin_target, virtual_workspace_single_package_bin_target, workspace_single_package_bin_target, ] ); } mod fail { test_cmds!( args: "generate tree \ --package foobar", success: false, color_mode: ColorMode::Plain, projects: [ package_bin_target, package_lib_target, package_multi_target, virtual_workspace_multi_package, virtual_workspace_single_package_bin_target, virtual_workspace_single_package_lib_target, virtual_workspace_single_package_multi_target, workspace_multi_package, workspace_single_package_bin_target, workspace_single_package_lib_target, workspace_single_package_multi_target, ] ); } } mod package_lib { mod pass { test_cmds!( args: "generate tree \ --package package_lib_target \ --lib", success: true, color_mode: ColorMode::Plain, projects: [ package_lib_target, workspace_single_package_lib_target, virtual_workspace_single_package_lib_target, ] ); test_cmds!( args: "generate tree \ --package package_multi_target \ --lib", success: true, color_mode: ColorMode::Plain, projects: [ package_multi_target, workspace_single_package_multi_target, virtual_workspace_single_package_multi_target, ] ); } mod fail { test_cmds!( args: "generate tree \ --package package_bin_target \ --lib", // does not exist success: false, color_mode: ColorMode::Plain, projects: [ package_bin_target, workspace_single_package_bin_target, virtual_workspace_single_package_bin_target, ] ); } } mod package_bin { mod pass { test_cmds!( args: "generate tree \ --package package_bin_target \ --bin package_bin_target", success: true, color_mode: ColorMode::Plain, projects: [ package_bin_target, workspace_single_package_bin_target, virtual_workspace_single_package_bin_target, ] ); test_cmds!( args: "generate tree \ --package package_multi_target \ --bin package_multi_target", success: true, color_mode: ColorMode::Plain, projects: [ package_multi_target, workspace_single_package_multi_target, virtual_workspace_single_package_multi_target, ] ); } mod fail { test_cmds!( args: "generate tree \ --package workspace-package \ --bin foobar", // does not exist success: false, color_mode: ColorMode::Plain, projects: [ package_bin_target, package_lib_target, package_multi_target, virtual_workspace_multi_package, virtual_workspace_single_package_bin_target, virtual_workspace_single_package_lib_target, virtual_workspace_single_package_multi_target, workspace_multi_package, workspace_single_package_bin_target, workspace_single_package_lib_target, workspace_single_package_multi_target, ] ); } } mod with_orphans { test_cmd!( args: "generate tree \ --with-orphans", success: true, color_mode: ColorMode::Plain, project: smoke ); } mod with_tests { test_cmd!( args: "generate tree \ --with-tests", success: true, color_mode: ColorMode::Plain, project: smoke ); } mod with_types { test_cmd!( args: "generate tree \ --with-types", success: true, color_mode: ColorMode::Plain, project: smoke ); } mod github_issue_80 { mod with_tests { test_cmd!( args: "generate tree \ --with-types \ --with-tests", success: true, color_mode: ColorMode::Plain, project: github_issue_80 ); } mod without_tests { test_cmd!( args: "generate tree \ --with-types", success: true, color_mode: ColorMode::Plain, project: github_issue_80 ); } }
mpl-2.0
servo/doc.servo.org
wayland_kbd/ffi/keysyms/constant.XKB_KEY_Kcedilla.html
4368
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <meta name="description" content="API documentation for the Rust `XKB_KEY_Kcedilla` constant in crate `wayland_kbd`."> <meta name="keywords" content="rust, rustlang, rust-lang, XKB_KEY_Kcedilla"> <title>wayland_kbd::ffi::keysyms::XKB_KEY_Kcedilla - Rust</title> <link rel="stylesheet" type="text/css" href="../../../rustdoc.css"> <link rel="stylesheet" type="text/css" href="../../../main.css"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <nav class="sidebar"> <p class='location'><a href='../../index.html'>wayland_kbd</a>::<wbr><a href='../index.html'>ffi</a>::<wbr><a href='index.html'>keysyms</a></p><script>window.sidebarCurrent = {name: 'XKB_KEY_Kcedilla', ty: 'constant', relpath: ''};</script><script defer src="sidebar-items.js"></script> </nav> <nav class="sub"> <form class="search-form js-only"> <div class="search-container"> <input class="search-input" name="search" autocomplete="off" placeholder="Click or press ‘S’ to search, ‘?’ for more options…" type="search"> </div> </form> </nav> <section id='main' class="content constant"> <h1 class='fqn'><span class='in-band'><a href='../../index.html'>wayland_kbd</a>::<wbr><a href='../index.html'>ffi</a>::<wbr><a href='index.html'>keysyms</a>::<wbr><a class='constant' href=''>XKB_KEY_Kcedilla</a></span><span class='out-of-band'><span id='render-detail'> <a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs"> [<span class='inner'>&#x2212;</span>] </a> </span><a id='src-656' class='srclink' href='../../../src/wayland_kbd/ffi/keysyms.rs.html#861' title='goto source code'>[src]</a></span></h1> <pre class='rust const'>pub const XKB_KEY_Kcedilla: <a class='primitive' href='../../../std/primitive.u32.html'>u32</a><code> = </code><code>979</code></pre></section> <section id='search' class="content hidden"></section> <section class="footer"></section> <aside id="help" class="hidden"> <div> <h1 class="hidden">Help</h1> <div class="shortcuts"> <h2>Keyboard Shortcuts</h2> <dl> <dt>?</dt> <dd>Show this help dialog</dd> <dt>S</dt> <dd>Focus the search field</dd> <dt>&larrb;</dt> <dd>Move up in search results</dd> <dt>&rarrb;</dt> <dd>Move down in search results</dd> <dt>&#9166;</dt> <dd>Go to active search result</dd> <dt>+</dt> <dd>Collapse/expand all sections</dd> </dl> </div> <div class="infos"> <h2>Search Tricks</h2> <p> Prefix searches with a type followed by a colon (e.g. <code>fn:</code>) to restrict the search to a given type. </p> <p> Accepted types are: <code>fn</code>, <code>mod</code>, <code>struct</code>, <code>enum</code>, <code>trait</code>, <code>type</code>, <code>macro</code>, and <code>const</code>. </p> <p> Search functions by type signature (e.g. <code>vec -> usize</code> or <code>* -> vec</code>) </p> </div> </div> </aside> <script> window.rootPath = "../../../"; window.currentCrate = "wayland_kbd"; window.playgroundUrl = ""; </script> <script src="../../../jquery.js"></script> <script src="../../../main.js"></script> <script defer src="../../../search-index.js"></script> </body> </html>
mpl-2.0
bugzilla/bugzilla
t/Support/Templates.pm
3111
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # # This Source Code Form is "Incompatible With Secondary Licenses", as # defined by the Mozilla Public License, v. 2.0. package Support::Templates; use 5.10.1; use strict; use warnings; use lib 't'; use base qw(Exporter); @Support::Templates::EXPORT = qw(@languages @include_paths @english_default_include_paths @referenced_files %actual_files $num_actual_files); use Bugzilla; use Bugzilla::Constants; use Bugzilla::Install::Util qw(template_include_path); use Support::Files; use File::Find; use File::Spec; # English default include paths our @english_default_include_paths = (File::Spec->catdir(bz_locations()->{'templatedir'}, 'en', 'default')); # And the extensions too foreach my $extension (@Support::Files::extensions) { my $dir = File::Spec->catdir($extension, 'template', 'en', 'default'); if (-e $dir) { push @english_default_include_paths, $dir; } } # Files which are referenced in the cgi files our @referenced_files = (); # All files sorted by include_path our %actual_files = (); # total number of actual_files our $num_actual_files = 0; # Set the template available languages and include paths our @languages = @{Bugzilla->languages}; our @include_paths = @{template_include_path({language => Bugzilla->languages})}; our @files; # Local subroutine used with File::Find sub find_templates { # Prune CVS directories if (-d $_ && $_ eq 'CVS') { $File::Find::prune = 1; return; } # Only include files ending in '.tmpl' if (-f $_ && $_ =~ m/\.tmpl$/i) { my $filename; my $local_dir = File::Spec->abs2rel($File::Find::dir, $File::Find::topdir); # File::Spec 3.13 and newer return "." instead of "" if both # arguments of abs2rel() are identical. $local_dir = "" if ($local_dir eq "."); if ($local_dir) { $filename = File::Spec->catfile($local_dir, $_); } else { $filename = $_; } push(@files, $filename); } } # Scan the given template include path for templates sub find_actual_files { my $include_path = $_[0]; @files = (); find(\&find_templates, $include_path); return @files; } foreach my $include_path (@include_paths) { $actual_files{$include_path} = [find_actual_files($include_path)]; $num_actual_files += scalar(@{$actual_files{$include_path}}); } # Scan Bugzilla's perl code looking for templates used and put them # in the @referenced_files array to be used by the 004template.t test. my %seen; foreach my $file (@Support::Files::testitems) { open(FILE, $file); my @lines = <FILE>; close(FILE); foreach my $line (@lines) { if ($line =~ m/template->process\(\"(.+?)\", .+?\)/) { my $template = $1; # Ignore templates with $ in the name, since they're # probably vars, not real files next if $template =~ m/\$/; next if $seen{$template}; push(@referenced_files, $template); $seen{$template} = 1; } } } 1;
mpl-2.0
ricardclau/packer
builder/azure/arm/step_set_certificate.go
941
package arm import ( "context" "github.com/hashicorp/packer-plugin-sdk/multistep" packersdk "github.com/hashicorp/packer-plugin-sdk/packer" "github.com/hashicorp/packer/builder/azure/common/constants" ) type StepSetCertificate struct { config *Config say func(message string) error func(e error) } func NewStepSetCertificate(config *Config, ui packersdk.Ui) *StepSetCertificate { var step = &StepSetCertificate{ config: config, say: func(message string) { ui.Say(message) }, error: func(e error) { ui.Error(e.Error()) }, } return step } func (s *StepSetCertificate) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction { s.say("Setting the certificate's URL ...") var winRMCertificateUrl = state.Get(constants.ArmCertificateUrl).(string) s.config.tmpWinRMCertificateUrl = winRMCertificateUrl return multistep.ActionContinue } func (*StepSetCertificate) Cleanup(multistep.StateBag) { }
mpl-2.0
susaing/doc.servo.org
js/jsapi/fn._Z28JS_DecodeInterpretedFunctionP9JSContextPKvj.html
4564
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <meta name="description" content="API documentation for the Rust `_Z28JS_DecodeInterpretedFunctionP9JSContextPKvj` fn in crate `js`."> <meta name="keywords" content="rust, rustlang, rust-lang, _Z28JS_DecodeInterpretedFunctionP9JSContextPKvj"> <title>js::jsapi::_Z28JS_DecodeInterpretedFunctionP9JSContextPKvj - Rust</title> <link rel="stylesheet" type="text/css" href="../../main.css"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <section class="sidebar"> <p class='location'><a href='../index.html'>js</a>::<wbr><a href='index.html'>jsapi</a></p><script>window.sidebarCurrent = {name: '_Z28JS_DecodeInterpretedFunctionP9JSContextPKvj', ty: 'fn', relpath: ''};</script><script defer src="sidebar-items.js"></script> </section> <nav class="sub"> <form class="search-form js-only"> <div class="search-container"> <input class="search-input" name="search" autocomplete="off" placeholder="Click or press ‘S’ to search, ‘?’ for more options…" type="search"> </div> </form> </nav> <section id='main' class="content fn"> <h1 class='fqn'><span class='in-band'><a href='../index.html'>js</a>::<wbr><a href='index.html'>jsapi</a>::<wbr><a class='fn' href=''>_Z28JS_DecodeInterpretedFunctionP9JSContextPKvj</a></span><span class='out-of-band'><span id='render-detail'> <a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs"> [<span class='inner'>&#x2212;</span>] </a> </span><a id='src-21854' class='srclink' href='../../src/js/jsapi.rs.html#5531-5535' title='goto source code'>[src]</a></span></h1> <pre class='rust fn'>unsafe extern fn _Z28JS_DecodeInterpretedFunctionP9JSContextPKvj(cx: <a href='../../std/primitive.pointer.html'>*mut <a class='enum' href='../../js/jsapi/enum.JSContext.html' title='js::jsapi::JSContext'>JSContext</a></a>, data: <a href='../../std/primitive.pointer.html'>*const <a class='enum' href='../../libc/types/common/c95/enum.c_void.html' title='libc::types::common::c95::c_void'>c_void</a></a>, length: <a href='../../std/primitive.u32.html'>u32</a>) -&gt; <a href='../../std/primitive.pointer.html'>*mut <a class='enum' href='../../js/jsapi/enum.JSObject.html' title='js::jsapi::JSObject'>JSObject</a></a></pre></section> <section id='search' class="content hidden"></section> <section class="footer"></section> <div id="help" class="hidden"> <div> <div class="shortcuts"> <h1>Keyboard Shortcuts</h1> <dl> <dt>?</dt> <dd>Show this help dialog</dd> <dt>S</dt> <dd>Focus the search field</dd> <dt>&larrb;</dt> <dd>Move up in search results</dd> <dt>&rarrb;</dt> <dd>Move down in search results</dd> <dt>&#9166;</dt> <dd>Go to active search result</dd> </dl> </div> <div class="infos"> <h1>Search Tricks</h1> <p> Prefix searches with a type followed by a colon (e.g. <code>fn:</code>) to restrict the search to a given type. </p> <p> Accepted types are: <code>fn</code>, <code>mod</code>, <code>struct</code>, <code>enum</code>, <code>trait</code>, <code>type</code>, <code>macro</code>, and <code>const</code>. </p> <p> Search functions by type signature (e.g. <code>vec -> usize</code>) </p> </div> </div> </div> <script> window.rootPath = "../../"; window.currentCrate = "js"; window.playgroundUrl = ""; </script> <script src="../../jquery.js"></script> <script src="../../main.js"></script> <script async src="../../search-index.js"></script> </body> </html>
mpl-2.0
susaing/doc.servo.org
freetype/freetype/constant.FT_Err_Post_Table_Missing.html
4026
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <meta name="description" content="API documentation for the Rust `FT_Err_Post_Table_Missing` constant in crate `freetype`."> <meta name="keywords" content="rust, rustlang, rust-lang, FT_Err_Post_Table_Missing"> <title>freetype::freetype::FT_Err_Post_Table_Missing - Rust</title> <link rel="stylesheet" type="text/css" href="../../main.css"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <section class="sidebar"> <p class='location'><a href='../index.html'>freetype</a>::<wbr><a href='index.html'>freetype</a></p><script>window.sidebarCurrent = {name: 'FT_Err_Post_Table_Missing', ty: 'constant', relpath: ''};</script><script defer src="sidebar-items.js"></script> </section> <nav class="sub"> <form class="search-form js-only"> <div class="search-container"> <input class="search-input" name="search" autocomplete="off" placeholder="Click or press ‘S’ to search, ‘?’ for more options…" type="search"> </div> </form> </nav> <section id='main' class="content constant"> <h1 class='fqn'><span class='in-band'><a href='../index.html'>freetype</a>::<wbr><a href='index.html'>freetype</a>::<wbr><a class='constant' href=''>FT_Err_Post_Table_Missing</a></span><span class='out-of-band'><span id='render-detail'> <a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs"> [<span class='inner'>&#x2212;</span>] </a> </span><a id='src-1397' class='srclink' href='../../src/freetype/freetype.rs.html#624' title='goto source code'>[src]</a></span></h1> <pre class='rust const'>pub const FT_Err_Post_Table_Missing: <a href='../../std/primitive.u32.html'>u32</a><code> = </code><code>148_u32</code></pre></section> <section id='search' class="content hidden"></section> <section class="footer"></section> <div id="help" class="hidden"> <div> <div class="shortcuts"> <h1>Keyboard Shortcuts</h1> <dl> <dt>?</dt> <dd>Show this help dialog</dd> <dt>S</dt> <dd>Focus the search field</dd> <dt>&larrb;</dt> <dd>Move up in search results</dd> <dt>&rarrb;</dt> <dd>Move down in search results</dd> <dt>&#9166;</dt> <dd>Go to active search result</dd> </dl> </div> <div class="infos"> <h1>Search Tricks</h1> <p> Prefix searches with a type followed by a colon (e.g. <code>fn:</code>) to restrict the search to a given type. </p> <p> Accepted types are: <code>fn</code>, <code>mod</code>, <code>struct</code>, <code>enum</code>, <code>trait</code>, <code>type</code>, <code>macro</code>, and <code>const</code>. </p> <p> Search functions by type signature (e.g. <code>vec -> usize</code>) </p> </div> </div> </div> <script> window.rootPath = "../../"; window.currentCrate = "freetype"; window.playgroundUrl = ""; </script> <script src="../../jquery.js"></script> <script src="../../main.js"></script> <script async src="../../search-index.js"></script> </body> </html>
mpl-2.0
ckprice/bedrock
bedrock/mozorg/templates/mozorg/contact/communities/united-kingdom.html
1212
{# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. #} {% extends "mozorg/contact/contact-base.html" %} {% block page_title %}{{ _('Contacts, Spaces and Communities') }} — {{ _('United Kingdom') }}{% endblock %} {% block contact_entry %} <div id="entry-container"> <section class="entry entry-community" id="united-kingdom" data-tab="communities"> <div class="card"> <img class="logo" src="{{ static('img/contact/logo-united-kingdom.png') }}" alt=""> <h2>{{ _('United Kingdom') }}</h2> <ul class="extra"> <li><a href="https://mozilla.org.uk/" class="website">mozilla.org.uk</a></li> <li><a href="irc://irc.mozilla.org/uk" class="irc">IRC: #uk</a></li> <li><a href="https://lists.mozilla.org/listinfo/community-uk" class="email">{{ _('Mailing list') }}</a></li> </ul> <figure class="feature-img"> <img src="//api.tiles.mapbox.com/v3/{{ settings.MAPBOX_TOKEN }}/-3.12,54.18,4/380x250.png" alt=""> </figure> </div> </section> </div> {% endblock %}
mpl-2.0
MapWindow/MapWinGIS
src/Control/Map_Cursors.cpp
5919
#include "stdafx.h" #include "Map.h" #include "ShapeEditor.h" #include "EditorHelper.h" #include "MeasuringHelper.h" // ******************************************************* // OnSetCursor() // ******************************************************* BOOL CMapView::OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message) { HCURSOR NewCursor = NULL; if( nHitTest != HTCLIENT ) { COleControl::OnSetCursor( pWnd, nHitTest, message ); return TRUE; } bool hasGuiCursor = true; if (_copyrightLinkActive) { NewCursor = LoadCursor(NULL, IDC_HAND); } else { switch (_lastZooombarPart) { case ZoombarHandle: NewCursor = LoadCursor(NULL, IDC_SIZENS); break; case ZoombarMinus: case ZoombarPlus: case ZoombarBar: NewCursor = LoadCursor(NULL, IDC_HAND); break; default: hasGuiCursor = false; } } if (!hasGuiCursor) { NewCursor = GetCursorIcon(); if (!NewCursor) { m_mapCursor = crsrMapDefault; NewCursor = GetCursorIcon(); } } if (NewCursor != NULL) ::SetCursor( NewCursor ); else COleControl::OnSetCursor( pWnd, nHitTest, message ); return TRUE; } // ******************************************************* // GetCursorIcon() // ******************************************************* HCURSOR CMapView::GetCursorIcon() { HCURSOR newCursor = NULL; switch (m_mapCursor) { case crsrMapDefault: switch (m_cursorMode) { case cmZoomIn: newCursor = _reverseZooming ? _cursorZoomout : _cursorZoomin; break; case cmZoomOut: newCursor = _reverseZooming ? _cursorZoomin : _cursorZoomout; break; case cmPan: newCursor = (_useAlternatePanCursor == TRUE) ? _cursorAlternatePan : _cursorPan; break; case cmSelection: case cmSelectByPolygon: newCursor = _cursorSelect; break; case cmMeasure: newCursor = _cursorMeasure; break; case cmAddShape: newCursor = _cursorDigitize; break; case cmEditShape: newCursor = _cursorVertex; break; case cmIdentify: newCursor = _cursorIdentify; break; // don't look good enough /*case cmSelectByPolygon: NewCursor = _cursorSelect2; break; case cmRotateShapes: NewCursor = _cursorRotate; break; case cmMoveShapes: NewCursor = _cursorMove; break;*/ case cmNone: newCursor = (HCURSOR)m_uDCursorHandle; break; } break; case crsrAppStarting: newCursor = LoadCursor(NULL, IDC_APPSTARTING); break; case crsrArrow: newCursor = LoadCursor(NULL, IDC_ARROW); break; case crsrCross: newCursor = LoadCursor(NULL, IDC_CROSS); break; case crsrHelp: newCursor = LoadCursor(NULL, IDC_HELP); break; case crsrIBeam: newCursor = LoadCursor(NULL, IDC_IBEAM); break; case crsrNo: newCursor = LoadCursor(NULL, IDC_NO); break; case crsrSizeAll: newCursor = LoadCursor(NULL, IDC_SIZEALL); break; case crsrSizeNESW: newCursor = LoadCursor(NULL, IDC_SIZENESW); break; case crsrSizeNS: newCursor = LoadCursor(NULL, IDC_SIZENS); break; case crsrSizeNWSE: newCursor = LoadCursor(NULL, IDC_SIZENWSE); break; case crsrSizeWE: newCursor = LoadCursor(NULL, IDC_SIZEWE); break; case crsrUpArrow: newCursor = LoadCursor(NULL, IDC_UPARROW); break; case crsrHand: newCursor = LoadCursor(NULL, IDC_HAND); break; case crsrWait: if (!_disableWaitCursor) newCursor = LoadCursor(NULL, IDC_WAIT); break; case crsrUserDefined: newCursor = (HCURSOR)m_uDCursorHandle; break; } return newCursor; } // ******************************************************* // OnMapCursorChanged() // ******************************************************* void CMapView::OnMapCursorChanged() { OnSetCursor(this,0,0); } // ******************************************************* // GetCursorMode() // ******************************************************* tkCursorMode CMapView::GetCursorMode() { return (tkCursorMode)m_cursorMode; } // ******************************************************* // SetCursorMode() // ******************************************************* void CMapView::SetCursorMode(tkCursorMode mode) { UpdateCursor(mode, true); } // ******************************************************* // UpdateCursor() // ******************************************************* void CMapView::UpdateCursor(tkCursorMode newCursor, bool clearEditor) { if (newCursor == m_cursorMode) return; if (newCursor == cmRotateShapes) { if (!InitRotationTool()) return; } bool refreshNeeded = newCursor == cmRotateShapes || m_cursorMode == cmRotateShapes; if (MeasuringHelper::OnCursorChanged(_measuring, newCursor)) refreshNeeded = true; if (!EditorHelper::OnCursorChanged(_shapeEditor, clearEditor, newCursor, refreshNeeded)) return; m_cursorMode = newCursor; OnSetCursor(this, HTCLIENT, 0); if (refreshNeeded) RedrawCore(RedrawSkipDataLayers, true); } // ********************************************************* // SetWaitCursor() // ********************************************************* HCURSOR CMapView::SetWaitCursor() { if (_disableWaitCursor) return NULL; HCURSOR oldCursor = ::GetCursor(); CPoint cpos; GetCursorPos(&cpos); CRect wrect; GetWindowRect(&wrect); HWND wndActive = ::GetActiveWindow(); if ((wndActive == this->GetSafeHwnd()) || (wndActive == this->GetParentOwner()->GetSafeHwnd())) { if( wrect.PtInRect(cpos) && (m_mapCursor != crsrUserDefined) && !_disableWaitCursor) { ::SetCursor(LoadCursor(NULL, IDC_WAIT) ); } } return oldCursor; }
mpl-2.0
Yukarumya/Yukarum-Redfoxes
dom/worklet/tests/common.js
604
window.onload = function() { // We are the parent. Let's load the test. if (parent == this || location.search.indexOf("worklet_iframe") == -1) { SimpleTest.waitForExplicitFinish(); configureTest().then(() => { var iframe = document.createElement('iframe'); iframe.src = location.href + "?worklet_iframe"; document.body.appendChild(iframe); }); return; } // Here we are in the iframe. window.SimpleTest = parent.SimpleTest; window.is = parent.is; window.isnot = parent.isnot; window.ok = parent.ok; window.info = parent.info; runTestInIframe(); }
mpl-2.0
servo/doc.servo.org
libc/linux/constant.EPOLLRDHUP.html
4402
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <meta name="description" content="API documentation for the Rust `EPOLLRDHUP` constant in crate `libc`."> <meta name="keywords" content="rust, rustlang, rust-lang, EPOLLRDHUP"> <title>libc::linux::EPOLLRDHUP - Rust</title> <link rel="stylesheet" type="text/css" href="../../rustdoc.css"> <link rel="stylesheet" type="text/css" href="../../main.css"> <link rel="shortcut icon" href="https://doc.rust-lang.org/favicon.ico"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <nav class="sidebar"> <a href='../../libc/index.html'><img src='https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png' alt='logo' width='100'></a> <p class='location'><a href='../index.html'>libc</a>::<wbr><a href='index.html'>linux</a></p><script>window.sidebarCurrent = {name: 'EPOLLRDHUP', ty: 'constant', relpath: ''};</script><script defer src="sidebar-items.js"></script> </nav> <nav class="sub"> <form class="search-form js-only"> <div class="search-container"> <input class="search-input" name="search" autocomplete="off" placeholder="Click or press ‘S’ to search, ‘?’ for more options…" type="search"> </div> </form> </nav> <section id='main' class="content constant"> <h1 class='fqn'><span class='in-band'><a href='../index.html'>libc</a>::<wbr><a href='index.html'>linux</a>::<wbr><a class='constant' href=''>EPOLLRDHUP</a></span><span class='out-of-band'><span id='render-detail'> <a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs"> [<span class='inner'>&#x2212;</span>] </a> </span><a id='src-2388' class='srclink' href='../../src/libc/unix/notbsd/linux/mod.rs.html#439' title='goto source code'>[src]</a></span></h1> <pre class='rust const'>pub const EPOLLRDHUP: <a class='type' href='../../libc/type.c_int.html' title='libc::c_int'>c_int</a><code> = </code><code>8192</code></pre></section> <section id='search' class="content hidden"></section> <section class="footer"></section> <aside id="help" class="hidden"> <div> <h1 class="hidden">Help</h1> <div class="shortcuts"> <h2>Keyboard Shortcuts</h2> <dl> <dt>?</dt> <dd>Show this help dialog</dd> <dt>S</dt> <dd>Focus the search field</dd> <dt>&larrb;</dt> <dd>Move up in search results</dd> <dt>&rarrb;</dt> <dd>Move down in search results</dd> <dt>&#9166;</dt> <dd>Go to active search result</dd> <dt>+</dt> <dd>Collapse/expand all sections</dd> </dl> </div> <div class="infos"> <h2>Search Tricks</h2> <p> Prefix searches with a type followed by a colon (e.g. <code>fn:</code>) to restrict the search to a given type. </p> <p> Accepted types are: <code>fn</code>, <code>mod</code>, <code>struct</code>, <code>enum</code>, <code>trait</code>, <code>type</code>, <code>macro</code>, and <code>const</code>. </p> <p> Search functions by type signature (e.g. <code>vec -> usize</code> or <code>* -> vec</code>) </p> </div> </div> </aside> <script> window.rootPath = "../../"; window.currentCrate = "libc"; window.playgroundUrl = ""; </script> <script src="../../jquery.js"></script> <script src="../../main.js"></script> <script defer src="../../search-index.js"></script> </body> </html>
mpl-2.0
chombourger/efup
external/nss/tests/pk11_gtests/pk11_gtests.sh
2411
#! /bin/bash # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. ######################################################################## # # tests/pk11_gtests/pk11_gtests.sh # # Script to drive the PKCS#11 gtest unit tests # # needs to work on all Unix and Windows platforms # # special strings # --------------- # FIXME ... known problems, search for this string # NOTE .... unexpected behavior # ######################################################################## ############################## pk11_gtest_init ########################## # local shell function to initialize this script ######################################################################## pk11_gtest_init() { SCRIPTNAME=pk11_gtest.sh # sourced - $0 would point to all.sh if [ -z "${CLEANUP}" ] ; then # if nobody else is responsible for CLEANUP="${SCRIPTNAME}" # cleaning this script will do it fi if [ -z "${INIT_SOURCED}" -o "${INIT_SOURCED}" != "TRUE" ]; then cd ../common . ./init.sh fi SCRIPTNAME=pk11_gtest.sh html_head PKCS\#11 Gtests if [ ! -d "${PK11GTESTDIR}" ]; then mkdir -p "${PK11GTESTDIR}" fi cd "${PK11GTESTDIR}" } ########################## pk11_gtest_start ######################### # Local function to actually start the test #################################################################### pk11_gtest_start() { if [ ! -f ${BINDIR}/pk11_gtest ]; then html_unknown "Skipping pk11_gtest (not built)" return fi # Temporarily disable asserts for PKCS#11 slot leakage (Bug 1168425) unset NSS_STRICT_SHUTDOWN PK11GTESTREPORT="${PK11GTESTDIR}/report.xml" ${BINDIR}/pk11_gtest -d "${PK11GTESTDIR}" --gtest_output=xml:"${PK11GTESTREPORT}" html_msg $? 0 "pk11_gtest run successfully" sed -f ${COMMON}/parsegtestreport.sed "${PK11GTESTREPORT}" | \ while read result name; do if [ "$result" = "notrun" ]; then echo "$name" SKIPPED elif [ "$result" = "run" ]; then html_passed "$name" > /dev/null else html_failed "$name" fi done } pk11_gtest_cleanup() { cd ${QADIR} . common/cleanup.sh } ################## main ################################################# cd "$(dirname "$0")" pk11_gtest_init pk11_gtest_start pk11_gtest_cleanup
mpl-2.0
terraform-providers/terraform-provider-google
google/resource_compute_router_nat_sweeper_test.go
3727
// ---------------------------------------------------------------------------- // // *** AUTO GENERATED CODE *** AUTO GENERATED CODE *** // // ---------------------------------------------------------------------------- // // This file is automatically generated by Magic Modules and manual // changes will be clobbered when the file is regenerated. // // Please read more about how to change this file in // .github/CONTRIBUTING.md. // // ---------------------------------------------------------------------------- package google import ( "context" "log" "strings" "testing" "github.com/hashicorp/terraform-plugin-sdk/helper/resource" ) func init() { resource.AddTestSweepers("ComputeRouterNat", &resource.Sweeper{ Name: "ComputeRouterNat", F: testSweepComputeRouterNat, }) } // At the time of writing, the CI only passes us-central1 as the region func testSweepComputeRouterNat(region string) error { resourceName := "ComputeRouterNat" log.Printf("[INFO][SWEEPER_LOG] Starting sweeper for %s", resourceName) config, err := sharedConfigForRegion(region) if err != nil { log.Printf("[INFO][SWEEPER_LOG] error getting shared config for region: %s", err) return err } err = config.LoadAndValidate(context.Background()) if err != nil { log.Printf("[INFO][SWEEPER_LOG] error loading: %s", err) return err } t := &testing.T{} billingId := getTestBillingAccountFromEnv(t) // Setup variables to replace in list template d := &ResourceDataMock{ FieldsInSchema: map[string]interface{}{ "project": config.Project, "region": region, "location": region, "zone": "-", "billing_account": billingId, }, } listTemplate := strings.Split("https://www.googleapis.com/compute/v1/projects/{{project}}/regions/{{region}}/routers/{{router}}", "?")[0] listUrl, err := replaceVars(d, config, listTemplate) if err != nil { log.Printf("[INFO][SWEEPER_LOG] error preparing sweeper list url: %s", err) return nil } res, err := sendRequest(config, "GET", config.Project, listUrl, nil) if err != nil { log.Printf("[INFO][SWEEPER_LOG] Error in response from request %s: %s", listUrl, err) return nil } resourceList, ok := res["nats"] if !ok { log.Printf("[INFO][SWEEPER_LOG] Nothing found in response.") return nil } rl := resourceList.([]interface{}) log.Printf("[INFO][SWEEPER_LOG] Found %d items in %s list response.", len(rl), resourceName) // Keep count of items that aren't sweepable for logging. nonPrefixCount := 0 for _, ri := range rl { obj := ri.(map[string]interface{}) if obj["name"] == nil { log.Printf("[INFO][SWEEPER_LOG] %s resource name was nil", resourceName) return nil } name := GetResourceNameFromSelfLink(obj["name"].(string)) // Skip resources that shouldn't be sweeped if !isSweepableTestResource(name) { nonPrefixCount++ continue } deleteTemplate := "https://www.googleapis.com/compute/v1/projects/{{project}}/regions/{{region}}/routers/{{router}}" deleteUrl, err := replaceVars(d, config, deleteTemplate) if err != nil { log.Printf("[INFO][SWEEPER_LOG] error preparing delete url: %s", err) return nil } deleteUrl = deleteUrl + name // Don't wait on operations as we may have a lot to delete _, err = sendRequest(config, "DELETE", config.Project, deleteUrl, nil) if err != nil { log.Printf("[INFO][SWEEPER_LOG] Error deleting for url %s : %s", deleteUrl, err) } else { log.Printf("[INFO][SWEEPER_LOG] Sent delete request for %s resource: %s", resourceName, name) } } if nonPrefixCount > 0 { log.Printf("[INFO][SWEEPER_LOG] %d items were non-sweepable and skipped.", nonPrefixCount) } return nil }
mpl-2.0
ricardclau/packer
builder/openstack/step_update_image_visibility.go
1429
package openstack import ( "context" "fmt" imageservice "github.com/gophercloud/gophercloud/openstack/imageservice/v2/images" "github.com/hashicorp/packer-plugin-sdk/multistep" packersdk "github.com/hashicorp/packer-plugin-sdk/packer" ) type stepUpdateImageVisibility struct{} func (s *stepUpdateImageVisibility) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction { ui := state.Get("ui").(packersdk.Ui) config := state.Get("config").(*Config) if config.SkipCreateImage { ui.Say("Skipping image update visibility...") return multistep.ActionContinue } imageId := state.Get("image").(string) if config.ImageVisibility == "" { return multistep.ActionContinue } imageClient, err := config.imageV2Client() if err != nil { err = fmt.Errorf("Error initializing image service client: %s", err) state.Put("error", err) return multistep.ActionHalt } ui.Say(fmt.Sprintf("Updating image visibility to %s", config.ImageVisibility)) r := imageservice.Update( imageClient, imageId, imageservice.UpdateOpts{ imageservice.UpdateVisibility{ Visibility: config.ImageVisibility, }, }, ) if _, err = r.Extract(); err != nil { err = fmt.Errorf("Error updating image visibility: %s", err) state.Put("error", err) return multistep.ActionHalt } return multistep.ActionContinue } func (s *stepUpdateImageVisibility) Cleanup(multistep.StateBag) { // No cleanup... }
mpl-2.0