code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
/** * Copyright 2015 Benjamin Navetta * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.bennavetta.aeneas.mesos.slave; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import mousio.etcd4j.EtcdClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.bennavetta.aeneas.Etcd; import com.bennavetta.aeneas.Networking; import com.bennavetta.aeneas.mesos.slave.docker.Docker; import com.bennavetta.aeneas.zookeeper.ServerRegistry; import com.bennavetta.aeneas.zookeeper.Servers; import com.bennavetta.aeneas.zookeeper.ZkException; import com.bennavetta.aeneas.zookeeper.impl.etcd.EtcdServerRegistry; public class Main { private static final Logger LOG = LoggerFactory.getLogger(Main.class); public static void main(String[] args) throws IOException { EtcdClient etcd = Etcd.createClient(); LOG.info("Connected to etcd - {}", etcd.getVersion()); try { ServerRegistry registry = new EtcdServerRegistry(etcd); Path mesosPrefix = Paths.get(System.getenv().getOrDefault("MESOS_PREFIX", "/usr/local")); Path executable = mesosPrefix.resolve("sbin/mesos-slave"); MesosSlave slave = new MesosSlave(executable); slave.setIp(Networking.getLocalAddress().getHostAddress()); slave.setPort(5051); slave.setMaster(Servers.toConnectionString(true, registry.getServers(), "aeneas/mesos")); slave.configureFromEnvironment(); if(Docker.startDocker()) { slave.setContainerizers("docker", "mesos"); } LOG.info("Starting Mesos slave"); slave.launch(); int result = slave.waitFor(); LOG.info("Mesos exited with value {}", result); } catch (InterruptedException e) { LOG.error("Error waiting for Mesos to complete", e); } catch (ZkException e) { LOG.error("Error obtaining ZooKeeper node list", e); } finally { if(etcd != null) { etcd.close(); } } } }
roguePanda/Aeneas
mesos/mesos-slave/src/main/java/com/bennavetta/aeneas/mesos/slave/Main.java
Java
apache-2.0
2,411
module MetsStructure def structure structure_type('Logical') || default_structure end def structure_for_volume(volume_id) return {} if structureless? volume = logical_node_for_volume(volume_id) || volume_nodes.find { |vol| vol.attribute("ID").value == volume_id } { nodes: structure_for_nodeset(volume.element_children) } end def file_label(file_id) struct = structure_map('Physical') node = struct.xpath(".//mets:fptr[@FILEID='#{file_id}']").first if struct (label_from_hierarchy(node.parent) if node) || label_from_related_objects(file_id) end private def logical_node_for_volume(volume_id) logical_node = @mets.xpath("/mets:mets/mets:structLink/mets:smLink[@xlink:from='#{volume_id}']")[0] return if logical_node.blank? @mets.xpath("//mets:div[@ID='#{logical_node['xlink:to']}']")[0] end def structure_map(type) @mets.xpath("/mets:mets/mets:structMap[@TYPE='#{type}']").first end def structureless? false end def structure_type(type) return nil unless structure_map(type) top = structure_map(type).xpath("mets:div/mets:div") return nil unless top.length > 0 { nodes: structure_for_nodeset(top) } end def default_structure { nodes: structure_for_nodeset(structure_map('RelatedObjects').xpath("mets:div/mets:div[@TYPE = 'OrderedList']/mets:div")) } end def structure_for_nodeset(nodeset) nodes = [] nodeset.each do |node| nodes << structure_recurse(node) end nodes end def structure_recurse(node) children = node.element_children return single_file_object(children.first) if !section(node) && single_file(children) child_nodes = [] if single_file(children) child_nodes = [single_file_object(children.first)] else children.each do |child| child_nodes << structure_recurse(child) end end { label: node['LABEL'], nodes: child_nodes } end def section(node) node.attributes["TYPE"].try(:value) == "Section" end def single_file(nodeset) nodeset.length == 1 && nodeset.first.name == 'fptr' end def single_file_object(node) id = node['FILEID'] label = label_from_hierarchy(node.parent) || label_from_related_objects(id) { label: label, proxy: id } end def label_from_hierarchy(node) return nil unless node['LABEL'] current = node label = current['LABEL'] while current.parent['LABEL'] && in_scope(current.parent) label = "#{current.parent['LABEL']}. #{label}" current = current.parent end label end def in_scope(node) multi_volume? ? node.parent.parent.name == 'div' : node.parent.name == 'div' end def label_from_related_objects(id) @mets.xpath("/mets:mets/mets:structMap[@TYPE='RelatedObjects']//mets:div[mets:fptr/@FILEID='#{id}']/@LABEL").to_s end end
pulibrary/plum
app/models/concerns/mets_structure.rb
Ruby
apache-2.0
2,974
#!/usr/bin/env bash while read SCRIPT do echo "Checking for script $SCRIPT.sh" if [ -e $SCRIPT.sh ] then echo "Running $SCRIPT.sh" source ./$SCRIPT.sh $@ && echo "$SCRIPT.sh succeeded" || (echo "$SCRIPT.sh failed" && exit 1) fi done < ../../node_tags
dhague/maas-k8s
scripts/run_node_tag_scripts.sh
Shell
apache-2.0
284
# Sciobia H.G.L. Reichenbach, 1841 GENUS #### Status ACCEPTED #### According to IRMNG Homonym List #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Rosales/Urticaceae/Sciobia/README.md
Markdown
apache-2.0
167
# Taraxacum fulvum f. fulvum FORM #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Taraxacum/ Syn. Taraxacum fulvum fulvum/README.md
Markdown
apache-2.0
180
# Stipa kyzylkiensis Kotukhov SPECIES #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Liliopsida/Poales/Poaceae/Stipa/Stipa kyzylkiensis/README.md
Markdown
apache-2.0
185
# Fleischeria geropogon Hochst. & Steud. ex Boiss. SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Scorzonera/Scorzonera elata/ Syn. Fleischeria geropogon/README.md
Markdown
apache-2.0
205
# Anacamptis pyramidalis f. nivea FORM #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Anacamptis/Anacamptis pyramidalis/ Syn. Anacamptis pyramidalis nivea/README.md
Markdown
apache-2.0
185
# Leucosphaera Henryk Raabe, 1940 GENUS #### Status ACCEPTED #### According to IRMNG Homonym List #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Chlorophyta/Leucosphaera/README.md
Markdown
apache-2.0
166
# Ruprechtia laurifolia C.A.Mey. SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Ranunculales/Ranunculaceae/Ruprechtia/Ruprechtia laurifolia/README.md
Markdown
apache-2.0
180
# Sophora flavescens var. favescens Aiton VARIETY #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Fabaceae/Sophora/Sophora flavescens/ Syn. Sophora flavescens favescens/README.md
Markdown
apache-2.0
196
# Oakesia floridana (Chapm.) J.F.Macbr. SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Liliopsida/Liliales/Colchicaceae/Uvularia/Uvularia floridana/ Syn. Oakesia floridana/README.md
Markdown
apache-2.0
194
# Rhynchosia caribaea var. picta (E. Mey.) Baker f. VARIETY #### Status ACCEPTED #### According to GRIN Taxonomy for Plants #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Fabaceae/Rhynchosia/Rhynchosia caribaea/Rhynchosia caribaea picta/README.md
Markdown
apache-2.0
192
# Dasyscyphus agassizii var. agassizii VARIETY #### Status ACCEPTED #### According to Index Fungorum #### Published in Syll. fung. (Abellini) 8: 438 (1889) #### Original name Dasyscyphus agassizii var. agassizii ### Remarks null
mdoering/backbone
life/Fungi/Ascomycota/Leotiomycetes/Helotiales/Hyaloscyphaceae/Lachnellula/Lachnellula agassizii/Dasyscyphus agassizii agassizii/README.md
Markdown
apache-2.0
233
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.machinelearning.model.transform; import java.util.Map; import java.util.Map.Entry; import com.amazonaws.services.machinelearning.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * RedshiftDatabase JSON Unmarshaller */ public class RedshiftDatabaseJsonUnmarshaller implements Unmarshaller<RedshiftDatabase, JsonUnmarshallerContext> { public RedshiftDatabase unmarshall(JsonUnmarshallerContext context) throws Exception { RedshiftDatabase redshiftDatabase = new RedshiftDatabase(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) return null; while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("DatabaseName", targetDepth)) { context.nextToken(); redshiftDatabase.setDatabaseName(StringJsonUnmarshaller .getInstance().unmarshall(context)); } if (context.testExpression("ClusterIdentifier", targetDepth)) { context.nextToken(); redshiftDatabase .setClusterIdentifier(StringJsonUnmarshaller .getInstance().unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals( currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return redshiftDatabase; } private static RedshiftDatabaseJsonUnmarshaller instance; public static RedshiftDatabaseJsonUnmarshaller getInstance() { if (instance == null) instance = new RedshiftDatabaseJsonUnmarshaller(); return instance; } }
trasa/aws-sdk-java
aws-java-sdk-machinelearning/src/main/java/com/amazonaws/services/machinelearning/model/transform/RedshiftDatabaseJsonUnmarshaller.java
Java
apache-2.0
3,130
<!DOCTYPE html> <html lang="en"> <head> <title>User ID Modules Example</title> <script> var FAILSAFE_TIMEOUT = 2000; var adUnits = [ { code: 'test-div', mediaTypes: { banner: { sizes: [[300, 250], [300, 600], [728, 90]] } }, bids: [ { bidder: 'rubicon', params: { accountId: '1001', siteId: '113932', zoneId: '535510' } } ] } ]; var pbjs = pbjs || {}; pbjs.que = pbjs.que || []; </script> <script src="../../build/dev/prebid.js" async></script> <script> function getHashedEmail() { } var googletag = googletag || {}; googletag.cmd = googletag.cmd || []; googletag.cmd.push(function () { googletag.pubads().disableInitialLoad(); }); pbjs.que.push(function () { pbjs.setConfig({ "debug": true, // ************************************************************************* // ** COMMENT consentManagement BLOCK IF YOU DO NOT WANT TO SIMULATE GDPR ** // ************************************************************************* "consentManagement": { "cmpApi": "static", "consentData": { "getTCData": { "tcString": "CO-HDlqO-HDlqAKAXCENBDCsAP_AAH_AACiQHKNd_X_fb39j-_59_9t0eY1f9_7_v20zjgeds-8Nyd_X_L8X42M7vF36pq4KuR4Eu3LBIQFlHOHcTUmw6IkVqTPsak2Mr7NKJ7PEinMbe2dYGHtfn9VTuZKYr97s___z__-__v__75f_r-3_3_vp9V---_fA5QAkw1L4CLMSxwJJo0qhRAhCuJDoAQAUUIwtE1hASuCnZXAR-ggYAIDUBGBECDEFGLIIAAAAAkoiAkAPBAIgCIBAACAFSAhAARoAgsAJAwCAAUA0LACKAIQJCDI4KjlMCAiRaKCeSMASi72MMIQyigBoFH4AAAAA.cAAAAAAAAAAA", "cmpId": 10, "cmpVersion": 23, "tcfPolicyVersion": 2, "gdprApplies": true, "cmpStatus": "loaded", "eventStatus": "tcloaded", "purpose": { "consents": { "1": true, "2": true } }, "vendor": { "consents": { // add your GVL ID here and set to true to give consent within pbjs "52": true, // rubicon for adserving "21": true, // unifiedId "131": true, // id5Id "929": true, // parrableId "97": true, // identityLink "887": true, // uid2 "95": true, // lotamePanoramaId "301": true, // zeotapIdPlus "91": true, // criteo "737": true, // amxId } } } } }, "userSync": { "userIds": [ { "name": "pubProvidedId", "params": { "eids": [ { "source": "domain.com", "uids": [ { "id": "value read from cookie or local storage", "atype": 1, "ext": { "stype": "ppuid" // allowable options are sha256email, DMP, ppuid for now } } ] }, { "source": "3rdpartyprovided.com", "uids": [ { "id": "value read from cookie or local storage", "atype": 3, "ext": { "stype": "sha256email" } } ] } ], "eidsFunction": getHashedEmail // any user defined function that exists in the page } }, { "name": "unifiedId", "params": { "partner": "prebid", "url": "http://match.adsrvr.org/track/rid?ttd_pid=prebid&fmt=json" }, "storage": { "type": "html5", "name": "unifiedid", "expires": 30 } }, { "name": "intentIqId", "params": { "partner": 0 // Set your real IntentIQ partner ID here for production. }, "storage": { "type": "cookie", "name": "intentIqId", "expires": 30 } }, { "name": "id5Id", "params": { "partner": 173 // Set your real ID5 partner ID here for production, please ask for one at http://id5.io/prebid }, "storage": { "type": "html5", "name": "id5id", "expires": 90, "refreshInSeconds": 10// 8*3600 // Refresh frequency of cookies } }, { "name": "merkleId", "params": { "vendor": "sdfg", "sv_cid": "dfg", "sv_pubid": "xcv", "sv_domain": "zxv" }, "storage": { "type": "html5", "name": "merkleId", "expires": 30 } }, { "name": "parrableId", "params": { // change to Parrable Partner Client ID(s) you received from the Parrable Partners you are using "partner": "30182847-e426-4ff9-b2b5-9ca1324ea09b" } }, { "name": "pubCommonId", "storage": { "type": "cookie", "name": "pubcid", "expires": 365 } // value: { // foo: '9879878907987', // bar:'93939' // } }, { "name": "identityLink", "params": { "pid": "14" // Set your real identityLink placement ID here // use3P: false // true/false - If you want to use 3P endpoint to retrieve envelope. If you do not set this property to true, 3p endpoint will not be fired. By default this property is undefined and 3p request will not be fired. }, "storage": { "type": "cookie", "name": "idl_env", "expires": 30 } }, { "name": "lotamePanoramaId" }, { "name": "liveIntentId", "params": { "publisherId": "9896876" }, "storage": { "type": "cookie", "name": "_li_pbid", "expires": 28 } }, { "name": "zeotapIdPlus" }, { "name": "haloId", "storage": { "type": "cookie", "name": "haloId", "expires": 28 } }, { "name": "quantcastId" }, { "name": "criteo" }, { "name": "amxId", "storage": { "type": "html5", "name": "amxId", "expires": 14 } }, { "name": "uid2" } ,{ name: "flocId", params: { // Default sharedid.org token : "A3dHTSoNUMjjERBLlrvJSelNnwWUCwVQhZ5tNQ+sll7y+LkPPVZXtB77u2y7CweRIxiYaGwGXNlW1/dFp8VMEgIAAAB+eyJvcmlnaW4iOiJodHRwczovL3NoYXJlZGlkLm9yZzo0NDMiLCJmZWF0dXJlIjoiSW50ZXJlc3RDb2hvcnRBUEkiLCJleHBpcnkiOjE2MjYyMjA3OTksImlzU3ViZG9tYWluIjp0cnVlLCJpc1RoaXJkUGFydHkiOnRydWV9" // To get new token, register https://developer.chrome.com/origintrials/#/trials/active for Federated Learning of Cohorts token: "A3dHTSoNUMjjERBLlrvJSelNnwWUCwVQhZ5tNQ+sll7y+LkPPVZXtB77u2y7CweRIxiYaGwGXNlW1/dFp8VMEgIAAAB+eyJvcmlnaW4iOiJodHRwczovL3NoYXJlZGlkLm9yZzo0NDMiLCJmZWF0dXJlIjoiSW50ZXJlc3RDb2hvcnRBUEkiLCJleHBpcnkiOjE2MjYyMjA3OTksImlzU3ViZG9tYWluIjp0cnVlLCJpc1RoaXJkUGFydHkiOnRydWV9" } } ], "syncDelay": 5000, "auctionDelay": 1000 } }); pbjs.addAdUnits(adUnits); pbjs.requestBids({ bidsBackHandler: sendAdserverRequest }); }); function sendAdserverRequest() { if (pbjs.adserverRequestSent) return; pbjs.adserverRequestSent = true; googletag.cmd.push(function () { pbjs.que.push(function () { pbjs.setTargetingForGPTAsync(); googletag.pubads().refresh(); }); }); } setTimeout(function () { sendAdserverRequest(); }, FAILSAFE_TIMEOUT); </script> <script> (function () { var gads = document.createElement('script'); gads.async = true; gads.type = 'text/javascript'; var useSSL = 'https:' == document.location.protocol; gads.src = (useSSL ? 'https:' : 'http:') + '//www.googletagservices.com/tag/js/gpt.js'; var node = document.getElementsByTagName('script')[0]; node.parentNode.insertBefore(gads, node); })(); </script> <script> googletag.cmd.push(function () { googletag.defineSlot('/112115922/FL_PB_MedRect', [[300, 250], [300, 600], [728, 90]], 'test-div').addService(googletag.pubads()); googletag.pubads().enableSingleRequest(); googletag.enableServices(); }); </script> </head> <body> <h2>User ID Modules Example</h2> <h4>Generated EIDs</h4> <script> pbjs.que.push(function () { var idsDiv = document.getElementById('ids-div'); idsDiv.innerHTML = JSON.stringify(pbjs.getUserIdsAsEids(), null, ' '); }); </script> <pre id="ids-div" style="border:1px solid #333; padding:5px; overflow: scroll"></pre> <h4>Ad Slot</h4> <div id="test-div" style="border:1px solid #333; padding:5px;"> <script> googletag.cmd.push(function () { googletag.display('test-div'); }); </script> </div> </body> </html>
tchibirev/Prebid.js
integrationExamples/gpt/userId_example.html
HTML
apache-2.0
10,441
package hr.istratech.bixolon.driver.command.print; import org.junit.Assert; import org.junit.Test; import java.util.Arrays; /** * @author ksaric */ public class PrintTest { @Test public void testInitCommand() throws Exception { //Before final byte[] printLineFeedCommand = new byte[]{(byte) 27, (byte) 64}; //When final byte[] command = Print.INITIALIZATION.getCommand(); //Then Assert.assertEquals( Arrays.toString( printLineFeedCommand ), Arrays.toString( command ) ); } @Test public void testPrintCommand() throws Exception { //Before final byte[] printLineFeedCommand = new byte[]{(byte) 10}; //When final byte[] command = Print.PRINT_LINE_FEED.getCommand(); //Then Assert.assertEquals( Arrays.toString( printLineFeedCommand ), Arrays.toString( command ) ); } }
IstraTech/bixolon-driver
bixolon-driver/src/test/java/hr/istratech/bixolon/driver/command/print/PrintTest.java
Java
apache-2.0
898
#ifndef _MEMORY_H_ #define _MEMORY_H_ #include <stdint.h> struct memory; struct memory* memory_new(); void memory_read(struct memory* memory, uint32_t addr, int bytes, uint8_t *data); void memory_write(struct memory* memory, uint32_t addr, int bytes, uint8_t *data); #endif // _MEMORY_H_
floh1695/vm
src/memory.h
C
apache-2.0
308
--- layout: model title: Fast Neural Machine Translation Model from English to Afro-Asiatic Languages author: John Snow Labs name: opus_mt_en_afa date: 2020-12-28 task: Translation language: xx edition: Spark NLP 2.7.0 spark_version: 2.4 tags: [open_source, seq2seq, translation, en, afa, xx] supported: true article_header: type: cover use_language_switcher: "Python-Scala-Java" --- ## Description Marian is an efficient, free Neural Machine Translation framework written in pure C++ with minimal dependencies. It is mainly being developed by the Microsoft Translator team. Many academic (most notably the University of Edinburgh and in the past the Adam Mickiewicz University in Poznań) and commercial contributors help with its development. It is currently the engine behind the Microsoft Translator Neural Machine Translation services and being deployed by many companies, organizations and research projects (see below for an incomplete list). - source languages: `en` - target languages: `afa` {:.btn-box} <button class="button button-orange" disabled>Live Demo</button> <button class="button button-orange" disabled>Open in Colab</button> [Download](https://s3.amazonaws.com/auxdata.johnsnowlabs.com/public/models/opus_mt_en_afa_xx_2.7.0_2.4_1609169665906.zip){:.button.button-orange.button-orange-trans.arr.button-icon} ## How to use <div class="tabs-box" markdown="1"> {% include programmingLanguageSelectScalaPythonNLU.html %} ```python documentAssembler = DocumentAssembler()\ .setInputCol("text")\ .setOutputCol("document") sentencerDL = SentenceDetectorDLModel.pretrained("sentence_detector_dl", "xx")\ .setInputCols(["document"])\ .setOutputCol("sentences") marian = MarianTransformer.pretrained("opus_mt_en_afa", "xx")\ .setInputCols(["sentence"])\ .setOutputCol("translation") marian_pipeline = Pipeline(stages=[documentAssembler, sentencerDL, marian]) light_pipeline = LightPipeline(marian_pipeline.fit(spark.createDataFrame([[""]]).toDF("text"))) result = light_pipeline.fullAnnotate(data) ``` ```scala val documentAssembler = new DocumentAssembler() .setInputCol("text") .setOutputCol("document") val sentence = SentenceDetectorDLModel.pretrained("sentence_detector_dl", "xx") .setInputCols("document") .setOutputCol("sentence") val marian = MarianTransformer.pretrained("opus_mt_en_afa", "xx") .setInputCols(["sentence"]) .setOutputCol("translation") val pipeline = new Pipeline().setStages(Array(documentAssembler, sentence, marian)) val result = pipeline.fit(Seq.empty[String].toDS.toDF("text")).transform(data) ``` {:.nlu-block} ```python import nlu text = ["text to translate"] opus_df = nlu.load('xx.en.marian.translate_to.afa').predict(text, output_level='sentence') opus_df ``` </div> {:.model-param} ## Model Information {:.table-model} |---|---| |Model Name:|opus_mt_en_afa| |Compatibility:|Spark NLP 2.7.0+| |Edition:|Official| |Input Labels:|[sentence]| |Output Labels:|[translation]| |Language:|xx| ## Data Source [https://huggingface.co/Helsinki-NLP/opus-mt-en-afa](https://huggingface.co/Helsinki-NLP/opus-mt-en-afa)
JohnSnowLabs/spark-nlp
docs/_posts/maziyarpanahi/2020-12-28-opus_mt_en_afa_xx.md
Markdown
apache-2.0
3,098
/** * Appcelerator Titanium Mobile * Copyright (c) 2010 by opensauce, Inc. All Rights Reserved. * Licensed under the terms of the Apache Public License * Please see the LICENSE included with this distribution for details. * * WARNING: This is generated code. Modify at your own risk and without support. */ #import "TiUIView.h" #if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_0 #ifdef USE_TI_UIIOSADVIEW #import <iAd/iAd.h> @interface TiUIiOSAdView : TiUIView<ADBannerViewDelegate> { @private ADBannerView *adview; } @end #endif #endif
bennpearson/opensauce
build/iphone/Classes/TiUIiOSAdView.h
C
apache-2.0
556
/* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.flowable.engine.impl.agenda; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.flowable.bpmn.model.Activity; import org.flowable.bpmn.model.BoundaryEvent; import org.flowable.bpmn.model.CompensateEventDefinition; import org.flowable.bpmn.model.FlowElement; import org.flowable.bpmn.model.FlowNode; import org.flowable.bpmn.model.SequenceFlow; import org.flowable.bpmn.model.SubProcess; import org.flowable.common.engine.api.FlowableException; import org.flowable.common.engine.api.delegate.event.FlowableEngineEventType; import org.flowable.common.engine.api.delegate.event.FlowableEventDispatcher; import org.flowable.common.engine.impl.interceptor.CommandContext; import org.flowable.common.engine.impl.util.CollectionUtil; import org.flowable.engine.delegate.ExecutionListener; import org.flowable.engine.delegate.event.impl.FlowableEventBuilder; import org.flowable.engine.impl.cfg.ProcessEngineConfigurationImpl; import org.flowable.engine.impl.delegate.ActivityBehavior; import org.flowable.engine.impl.jobexecutor.AsyncContinuationJobHandler; import org.flowable.engine.impl.persistence.entity.ExecutionEntity; import org.flowable.engine.impl.persistence.entity.ExecutionEntityManager; import org.flowable.engine.impl.util.CommandContextUtil; import org.flowable.engine.impl.util.ProcessDefinitionUtil; import org.flowable.engine.logging.LogMDC; import org.flowable.job.api.Job; import org.flowable.job.service.JobService; import org.flowable.job.service.impl.persistence.entity.JobEntity; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Operation that takes the current {@link FlowElement} set on the {@link ExecutionEntity} and executes the associated {@link ActivityBehavior}. In the case of async, schedules a {@link Job}. * * Also makes sure the {@link ExecutionListener} instances are called. * * @author Joram Barrez * @author Tijs Rademakers */ public class ContinueProcessOperation extends AbstractOperation { private static final Logger LOGGER = LoggerFactory.getLogger(ContinueProcessOperation.class); protected boolean forceSynchronousOperation; protected boolean inCompensation; public ContinueProcessOperation(CommandContext commandContext, ExecutionEntity execution, boolean forceSynchronousOperation, boolean inCompensation) { super(commandContext, execution); this.forceSynchronousOperation = forceSynchronousOperation; this.inCompensation = inCompensation; } public ContinueProcessOperation(CommandContext commandContext, ExecutionEntity execution) { this(commandContext, execution, false, false); } @Override public void run() { FlowElement currentFlowElement = getCurrentFlowElement(execution); if (currentFlowElement instanceof FlowNode) { continueThroughFlowNode((FlowNode) currentFlowElement); } else if (currentFlowElement instanceof SequenceFlow) { continueThroughSequenceFlow((SequenceFlow) currentFlowElement); } else { throw new FlowableException("Programmatic error: no current flow element found or invalid type: " + currentFlowElement + ". Halting."); } } protected void executeProcessStartExecutionListeners() { org.flowable.bpmn.model.Process process = ProcessDefinitionUtil.getProcess(execution.getProcessDefinitionId()); executeExecutionListeners(process, execution.getParent(), ExecutionListener.EVENTNAME_START); } protected void continueThroughFlowNode(FlowNode flowNode) { execution.setActive(true); // Check if it's the initial flow element. If so, we must fire the execution listeners for the process too if (flowNode.getIncomingFlows() != null && flowNode.getIncomingFlows().size() == 0 && flowNode.getSubProcess() == null) { executeProcessStartExecutionListeners(); } // For a subprocess, a new child execution is created that will visit the steps of the subprocess // The original execution that arrived here will wait until the subprocess is finished // and will then be used to continue the process instance. if (flowNode instanceof SubProcess) { createChildExecutionForSubProcess((SubProcess) flowNode); } if (flowNode instanceof Activity && ((Activity) flowNode).hasMultiInstanceLoopCharacteristics()) { // the multi instance execution will look at async executeMultiInstanceSynchronous(flowNode); } else if (forceSynchronousOperation || !flowNode.isAsynchronous()) { executeSynchronous(flowNode); } else { executeAsynchronous(flowNode); } } protected void createChildExecutionForSubProcess(SubProcess subProcess) { ExecutionEntity parentScopeExecution = findFirstParentScopeExecution(execution); // Create the sub process execution that can be used to set variables // We create a new execution and delete the incoming one to have a proper scope that // does not conflict anything with any existing scopes ExecutionEntity subProcessExecution = CommandContextUtil.getExecutionEntityManager(commandContext).createChildExecution(parentScopeExecution); subProcessExecution.setCurrentFlowElement(subProcess); subProcessExecution.setScope(true); CommandContextUtil.getExecutionEntityManager(commandContext).deleteRelatedDataForExecution(execution, null); CommandContextUtil.getExecutionEntityManager(commandContext).delete(execution); execution = subProcessExecution; } protected void executeSynchronous(FlowNode flowNode) { CommandContextUtil.getActivityInstanceEntityManager(commandContext).recordActivityStart(execution); // Execution listener: event 'start' if (CollectionUtil.isNotEmpty(flowNode.getExecutionListeners())) { executeExecutionListeners(flowNode, ExecutionListener.EVENTNAME_START); } // Create any boundary events, sub process boundary events will be created from the activity behavior List<ExecutionEntity> boundaryEventExecutions = null; List<BoundaryEvent> boundaryEvents = null; if (!inCompensation && flowNode instanceof Activity) { // Only activities can have boundary events boundaryEvents = ((Activity) flowNode).getBoundaryEvents(); if (CollectionUtil.isNotEmpty(boundaryEvents)) { boundaryEventExecutions = createBoundaryEvents(boundaryEvents, execution); } } // Execute actual behavior ActivityBehavior activityBehavior = (ActivityBehavior) flowNode.getBehavior(); if (activityBehavior != null) { executeActivityBehavior(activityBehavior, flowNode); executeBoundaryEvents(boundaryEvents, boundaryEventExecutions); } else { executeBoundaryEvents(boundaryEvents, boundaryEventExecutions); LOGGER.debug("No activityBehavior on activity '{}' with execution {}", flowNode.getId(), execution.getId()); CommandContextUtil.getAgenda().planTakeOutgoingSequenceFlowsOperation(execution, true); } } protected void executeAsynchronous(FlowNode flowNode) { JobService jobService = CommandContextUtil.getJobService(commandContext); JobEntity job = jobService.createJob(); job.setExecutionId(execution.getId()); job.setProcessInstanceId(execution.getProcessInstanceId()); job.setProcessDefinitionId(execution.getProcessDefinitionId()); job.setJobHandlerType(AsyncContinuationJobHandler.TYPE); // Inherit tenant id (if applicable) if (execution.getTenantId() != null) { job.setTenantId(execution.getTenantId()); } execution.getJobs().add(job); jobService.createAsyncJob(job, flowNode.isExclusive()); jobService.scheduleAsyncJob(job); } protected void executeMultiInstanceSynchronous(FlowNode flowNode) { // Execution listener: event 'start' if (CollectionUtil.isNotEmpty(flowNode.getExecutionListeners())) { executeExecutionListeners(flowNode, ExecutionListener.EVENTNAME_START); } if (!hasMultiInstanceRootExecution(execution, flowNode)) { execution = createMultiInstanceRootExecution(execution); } // Create any boundary events, sub process boundary events will be created from the activity behavior List<ExecutionEntity> boundaryEventExecutions = null; List<BoundaryEvent> boundaryEvents = null; if (!inCompensation && flowNode instanceof Activity) { // Only activities can have boundary events boundaryEvents = ((Activity) flowNode).getBoundaryEvents(); if (CollectionUtil.isNotEmpty(boundaryEvents)) { boundaryEventExecutions = createBoundaryEvents(boundaryEvents, execution); } } // Execute the multi instance behavior ActivityBehavior activityBehavior = (ActivityBehavior) flowNode.getBehavior(); if (activityBehavior != null) { executeActivityBehavior(activityBehavior, flowNode); executeBoundaryEvents(boundaryEvents, boundaryEventExecutions); } else { throw new FlowableException("Expected an activity behavior in flow node " + flowNode.getId()); } } protected boolean hasMultiInstanceRootExecution(ExecutionEntity execution, FlowNode flowNode) { ExecutionEntity currentExecution = execution.getParent(); while (currentExecution != null) { if (currentExecution.isMultiInstanceRoot() && flowNode.getId().equals(currentExecution.getActivityId())) { return true; } currentExecution = currentExecution.getParent(); } return false; } protected ExecutionEntity createMultiInstanceRootExecution(ExecutionEntity execution) { ExecutionEntity parentExecution = execution.getParent(); FlowElement flowElement = execution.getCurrentFlowElement(); ExecutionEntityManager executionEntityManager = CommandContextUtil.getExecutionEntityManager(); executionEntityManager.deleteRelatedDataForExecution(execution, null); executionEntityManager.delete(execution); ExecutionEntity multiInstanceRootExecution = executionEntityManager.createChildExecution(parentExecution); multiInstanceRootExecution.setCurrentFlowElement(flowElement); multiInstanceRootExecution.setMultiInstanceRoot(true); multiInstanceRootExecution.setActive(false); return multiInstanceRootExecution; } protected void executeActivityBehavior(ActivityBehavior activityBehavior, FlowNode flowNode) { LOGGER.debug("Executing activityBehavior {} on activity '{}' with execution {}", activityBehavior.getClass(), flowNode.getId(), execution.getId()); ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(); FlowableEventDispatcher eventDispatcher = null; if (processEngineConfiguration != null) { eventDispatcher = processEngineConfiguration.getEventDispatcher(); } if (eventDispatcher != null && eventDispatcher.isEnabled()) { if (flowNode instanceof Activity && ((Activity) flowNode).hasMultiInstanceLoopCharacteristics()) { processEngineConfiguration.getEventDispatcher().dispatchEvent( FlowableEventBuilder.createMultiInstanceActivityEvent(FlowableEngineEventType.MULTI_INSTANCE_ACTIVITY_STARTED, flowNode.getId(), flowNode.getName(), execution.getId(), execution.getProcessInstanceId(), execution.getProcessDefinitionId(), flowNode)); } else { processEngineConfiguration.getEventDispatcher().dispatchEvent( FlowableEventBuilder.createActivityEvent(FlowableEngineEventType.ACTIVITY_STARTED, flowNode.getId(), flowNode.getName(), execution.getId(), execution.getProcessInstanceId(), execution.getProcessDefinitionId(), flowNode)); } } try { activityBehavior.execute(execution); } catch (RuntimeException e) { if (LogMDC.isMDCEnabled()) { LogMDC.putMDCExecution(execution); } throw e; } } protected void continueThroughSequenceFlow(SequenceFlow sequenceFlow) { // Execution listener. Sequenceflow only 'take' makes sense ... but we've supported all three since the beginning if (CollectionUtil.isNotEmpty(sequenceFlow.getExecutionListeners())) { executeExecutionListeners(sequenceFlow, ExecutionListener.EVENTNAME_START); executeExecutionListeners(sequenceFlow, ExecutionListener.EVENTNAME_TAKE); executeExecutionListeners(sequenceFlow, ExecutionListener.EVENTNAME_END); } // Firing event that transition is being taken ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(); FlowableEventDispatcher eventDispatcher = null; if (processEngineConfiguration != null) { eventDispatcher = processEngineConfiguration.getEventDispatcher(); } if (eventDispatcher != null && eventDispatcher.isEnabled()) { FlowElement sourceFlowElement = sequenceFlow.getSourceFlowElement(); FlowElement targetFlowElement = sequenceFlow.getTargetFlowElement(); processEngineConfiguration.getEventDispatcher().dispatchEvent( FlowableEventBuilder.createSequenceFlowTakenEvent( execution, FlowableEngineEventType.SEQUENCEFLOW_TAKEN, sequenceFlow.getId(), sourceFlowElement != null ? sourceFlowElement.getId() : null, sourceFlowElement != null ? sourceFlowElement.getName() : null, sourceFlowElement != null ? sourceFlowElement.getClass().getName() : null, sourceFlowElement != null ? ((FlowNode) sourceFlowElement).getBehavior() : null, targetFlowElement != null ? targetFlowElement.getId() : null, targetFlowElement != null ? targetFlowElement.getName() : null, targetFlowElement != null ? targetFlowElement.getClass().getName() : null, targetFlowElement != null ? ((FlowNode) targetFlowElement).getBehavior() : null)); } CommandContextUtil.getActivityInstanceEntityManager(commandContext).recordSequenceFlowTaken(execution); FlowElement targetFlowElement = sequenceFlow.getTargetFlowElement(); execution.setCurrentFlowElement(targetFlowElement); LOGGER.debug("Sequence flow '{}' encountered. Continuing process by following it using execution {}", sequenceFlow.getId(), execution.getId()); execution.setActive(false); //agenda.planContinueProcessOperation(execution); if (targetFlowElement instanceof FlowNode) { continueThroughFlowNode((FlowNode) targetFlowElement); } else { agenda.planContinueProcessOperation(execution); } } protected List<ExecutionEntity> createBoundaryEvents(List<BoundaryEvent> boundaryEvents, ExecutionEntity execution) { List<ExecutionEntity> boundaryEventExecutions = new ArrayList<>(boundaryEvents.size()); // The parent execution becomes a scope, and a child execution is created for each of the boundary events for (BoundaryEvent boundaryEvent : boundaryEvents) { if (CollectionUtil.isEmpty(boundaryEvent.getEventDefinitions()) || (boundaryEvent.getEventDefinitions().get(0) instanceof CompensateEventDefinition)) { continue; } // A Child execution of the current execution is created to represent the boundary event being active ExecutionEntity childExecutionEntity = CommandContextUtil.getExecutionEntityManager(commandContext).createChildExecution(execution); childExecutionEntity.setParentId(execution.getId()); childExecutionEntity.setCurrentFlowElement(boundaryEvent); childExecutionEntity.setScope(false); boundaryEventExecutions.add(childExecutionEntity); } return boundaryEventExecutions; } protected void executeBoundaryEvents(List<BoundaryEvent> boundaryEvents, List<ExecutionEntity> boundaryEventExecutions) { if (!CollectionUtil.isEmpty(boundaryEventExecutions)) { Iterator<BoundaryEvent> boundaryEventsIterator = boundaryEvents.iterator(); Iterator<ExecutionEntity> boundaryEventExecutionsIterator = boundaryEventExecutions.iterator(); while (boundaryEventsIterator.hasNext() && boundaryEventExecutionsIterator.hasNext()) { BoundaryEvent boundaryEvent = boundaryEventsIterator.next(); ExecutionEntity boundaryEventExecution = boundaryEventExecutionsIterator.next(); ActivityBehavior boundaryEventBehavior = ((ActivityBehavior) boundaryEvent.getBehavior()); LOGGER.debug("Executing boundary event activityBehavior {} with execution {}", boundaryEventBehavior.getClass(), boundaryEventExecution.getId()); boundaryEventBehavior.execute(boundaryEventExecution); } } } }
yvoswillens/flowable-engine
modules/flowable-engine/src/main/java/org/flowable/engine/impl/agenda/ContinueProcessOperation.java
Java
apache-2.0
18,441
/** Copyright 2015 TappingStone, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.predictionio.data.webhooks import org.apache.predictionio.data.storage.Event import org.apache.predictionio.data.storage.EventJson4sSupport import org.json4s.Formats import org.json4s.DefaultFormats import org.json4s.JObject import org.json4s.native.Serialization.read import org.json4s.native.Serialization.write private[predictionio] object ConnectorUtil { implicit val eventJson4sFormats: Formats = DefaultFormats + new EventJson4sSupport.APISerializer // intentionally use EventJson4sSupport.APISerializer to convert // from JSON to Event object. Don't allow connector directly create // Event object so that the Event object formation is consistent // by enforcing JSON format def toEvent(connector: JsonConnector, data: JObject): Event = { read[Event](write(connector.toEventJson(data))) } def toEvent(connector: FormConnector, data: Map[String, String]): Event = { read[Event](write(connector.toEventJson(data))) } }
alex9311/PredictionIO
data/src/main/scala/org/apache/predictionio/data/webhooks/ConnectorUtil.scala
Scala
apache-2.0
1,596
# Senecio uintahensis (A.Nelson) Greenm. SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Packera/Packera multilobata/ Syn. Senecio uintahensis/README.md
Markdown
apache-2.0
195
// Code generated by GoVPP's binapi-generator. DO NOT EDIT. // source: /usr/share/vpp/api/core/syslog.api.json /* Package syslog is a generated VPP binary API for 'syslog' module. It consists of: 5 enums 5 aliases 6 types 1 union 8 messages 4 services */ package syslog import ( "bytes" "context" "io" "strconv" api "git.fd.io/govpp.git/api" struc "github.com/lunixbochs/struc" ) const ( // ModuleName is the name of this module. ModuleName = "syslog" // APIVersion is the API version of this module. APIVersion = "1.0.0" // VersionCrc is the CRC of this module. VersionCrc = 0x95b7380f ) // AddressFamily represents VPP binary API enum 'address_family'. type AddressFamily uint8 const ( ADDRESS_IP4 AddressFamily = 0 ADDRESS_IP6 AddressFamily = 1 ) var AddressFamily_name = map[uint8]string{ 0: "ADDRESS_IP4", 1: "ADDRESS_IP6", } var AddressFamily_value = map[string]uint8{ "ADDRESS_IP4": 0, "ADDRESS_IP6": 1, } func (x AddressFamily) String() string { s, ok := AddressFamily_name[uint8(x)] if ok { return s } return strconv.Itoa(int(x)) } // IPDscp represents VPP binary API enum 'ip_dscp'. type IPDscp uint8 const ( IP_API_DSCP_CS0 IPDscp = 0 IP_API_DSCP_CS1 IPDscp = 8 IP_API_DSCP_AF11 IPDscp = 10 IP_API_DSCP_AF12 IPDscp = 12 IP_API_DSCP_AF13 IPDscp = 14 IP_API_DSCP_CS2 IPDscp = 16 IP_API_DSCP_AF21 IPDscp = 18 IP_API_DSCP_AF22 IPDscp = 20 IP_API_DSCP_AF23 IPDscp = 22 IP_API_DSCP_CS3 IPDscp = 24 IP_API_DSCP_AF31 IPDscp = 26 IP_API_DSCP_AF32 IPDscp = 28 IP_API_DSCP_AF33 IPDscp = 30 IP_API_DSCP_CS4 IPDscp = 32 IP_API_DSCP_AF41 IPDscp = 34 IP_API_DSCP_AF42 IPDscp = 36 IP_API_DSCP_AF43 IPDscp = 38 IP_API_DSCP_CS5 IPDscp = 40 IP_API_DSCP_EF IPDscp = 46 IP_API_DSCP_CS6 IPDscp = 48 IP_API_DSCP_CS7 IPDscp = 50 ) var IPDscp_name = map[uint8]string{ 0: "IP_API_DSCP_CS0", 8: "IP_API_DSCP_CS1", 10: "IP_API_DSCP_AF11", 12: "IP_API_DSCP_AF12", 14: "IP_API_DSCP_AF13", 16: "IP_API_DSCP_CS2", 18: "IP_API_DSCP_AF21", 20: "IP_API_DSCP_AF22", 22: "IP_API_DSCP_AF23", 24: "IP_API_DSCP_CS3", 26: "IP_API_DSCP_AF31", 28: "IP_API_DSCP_AF32", 30: "IP_API_DSCP_AF33", 32: "IP_API_DSCP_CS4", 34: "IP_API_DSCP_AF41", 36: "IP_API_DSCP_AF42", 38: "IP_API_DSCP_AF43", 40: "IP_API_DSCP_CS5", 46: "IP_API_DSCP_EF", 48: "IP_API_DSCP_CS6", 50: "IP_API_DSCP_CS7", } var IPDscp_value = map[string]uint8{ "IP_API_DSCP_CS0": 0, "IP_API_DSCP_CS1": 8, "IP_API_DSCP_AF11": 10, "IP_API_DSCP_AF12": 12, "IP_API_DSCP_AF13": 14, "IP_API_DSCP_CS2": 16, "IP_API_DSCP_AF21": 18, "IP_API_DSCP_AF22": 20, "IP_API_DSCP_AF23": 22, "IP_API_DSCP_CS3": 24, "IP_API_DSCP_AF31": 26, "IP_API_DSCP_AF32": 28, "IP_API_DSCP_AF33": 30, "IP_API_DSCP_CS4": 32, "IP_API_DSCP_AF41": 34, "IP_API_DSCP_AF42": 36, "IP_API_DSCP_AF43": 38, "IP_API_DSCP_CS5": 40, "IP_API_DSCP_EF": 46, "IP_API_DSCP_CS6": 48, "IP_API_DSCP_CS7": 50, } func (x IPDscp) String() string { s, ok := IPDscp_name[uint8(x)] if ok { return s } return strconv.Itoa(int(x)) } // IPEcn represents VPP binary API enum 'ip_ecn'. type IPEcn uint8 const ( IP_API_ECN_NONE IPEcn = 0 IP_API_ECN_ECT0 IPEcn = 1 IP_API_ECN_ECT1 IPEcn = 2 IP_API_ECN_CE IPEcn = 3 ) var IPEcn_name = map[uint8]string{ 0: "IP_API_ECN_NONE", 1: "IP_API_ECN_ECT0", 2: "IP_API_ECN_ECT1", 3: "IP_API_ECN_CE", } var IPEcn_value = map[string]uint8{ "IP_API_ECN_NONE": 0, "IP_API_ECN_ECT0": 1, "IP_API_ECN_ECT1": 2, "IP_API_ECN_CE": 3, } func (x IPEcn) String() string { s, ok := IPEcn_name[uint8(x)] if ok { return s } return strconv.Itoa(int(x)) } // IPProto represents VPP binary API enum 'ip_proto'. type IPProto uint8 const ( IP_API_PROTO_HOPOPT IPProto = 0 IP_API_PROTO_ICMP IPProto = 1 IP_API_PROTO_IGMP IPProto = 2 IP_API_PROTO_TCP IPProto = 6 IP_API_PROTO_UDP IPProto = 17 IP_API_PROTO_GRE IPProto = 47 IP_API_PROTO_ESP IPProto = 50 IP_API_PROTO_AH IPProto = 51 IP_API_PROTO_ICMP6 IPProto = 58 IP_API_PROTO_EIGRP IPProto = 88 IP_API_PROTO_OSPF IPProto = 89 IP_API_PROTO_SCTP IPProto = 132 IP_API_PROTO_RESERVED IPProto = 255 ) var IPProto_name = map[uint8]string{ 0: "IP_API_PROTO_HOPOPT", 1: "IP_API_PROTO_ICMP", 2: "IP_API_PROTO_IGMP", 6: "IP_API_PROTO_TCP", 17: "IP_API_PROTO_UDP", 47: "IP_API_PROTO_GRE", 50: "IP_API_PROTO_ESP", 51: "IP_API_PROTO_AH", 58: "IP_API_PROTO_ICMP6", 88: "IP_API_PROTO_EIGRP", 89: "IP_API_PROTO_OSPF", 132: "IP_API_PROTO_SCTP", 255: "IP_API_PROTO_RESERVED", } var IPProto_value = map[string]uint8{ "IP_API_PROTO_HOPOPT": 0, "IP_API_PROTO_ICMP": 1, "IP_API_PROTO_IGMP": 2, "IP_API_PROTO_TCP": 6, "IP_API_PROTO_UDP": 17, "IP_API_PROTO_GRE": 47, "IP_API_PROTO_ESP": 50, "IP_API_PROTO_AH": 51, "IP_API_PROTO_ICMP6": 58, "IP_API_PROTO_EIGRP": 88, "IP_API_PROTO_OSPF": 89, "IP_API_PROTO_SCTP": 132, "IP_API_PROTO_RESERVED": 255, } func (x IPProto) String() string { s, ok := IPProto_name[uint8(x)] if ok { return s } return strconv.Itoa(int(x)) } // SyslogSeverity represents VPP binary API enum 'syslog_severity'. type SyslogSeverity uint32 const ( SYSLOG_API_SEVERITY_EMERG SyslogSeverity = 0 SYSLOG_API_SEVERITY_ALERT SyslogSeverity = 1 SYSLOG_API_SEVERITY_CRIT SyslogSeverity = 2 SYSLOG_API_SEVERITY_ERR SyslogSeverity = 3 SYSLOG_API_SEVERITY_WARN SyslogSeverity = 4 SYSLOG_API_SEVERITY_NOTICE SyslogSeverity = 5 SYSLOG_API_SEVERITY_INFO SyslogSeverity = 6 SYSLOG_API_SEVERITY_DBG SyslogSeverity = 7 ) var SyslogSeverity_name = map[uint32]string{ 0: "SYSLOG_API_SEVERITY_EMERG", 1: "SYSLOG_API_SEVERITY_ALERT", 2: "SYSLOG_API_SEVERITY_CRIT", 3: "SYSLOG_API_SEVERITY_ERR", 4: "SYSLOG_API_SEVERITY_WARN", 5: "SYSLOG_API_SEVERITY_NOTICE", 6: "SYSLOG_API_SEVERITY_INFO", 7: "SYSLOG_API_SEVERITY_DBG", } var SyslogSeverity_value = map[string]uint32{ "SYSLOG_API_SEVERITY_EMERG": 0, "SYSLOG_API_SEVERITY_ALERT": 1, "SYSLOG_API_SEVERITY_CRIT": 2, "SYSLOG_API_SEVERITY_ERR": 3, "SYSLOG_API_SEVERITY_WARN": 4, "SYSLOG_API_SEVERITY_NOTICE": 5, "SYSLOG_API_SEVERITY_INFO": 6, "SYSLOG_API_SEVERITY_DBG": 7, } func (x SyslogSeverity) String() string { s, ok := SyslogSeverity_name[uint32(x)] if ok { return s } return strconv.Itoa(int(x)) } // AddressWithPrefix represents VPP binary API alias 'address_with_prefix'. type AddressWithPrefix Prefix // IP4Address represents VPP binary API alias 'ip4_address'. type IP4Address [4]uint8 // IP4AddressWithPrefix represents VPP binary API alias 'ip4_address_with_prefix'. type IP4AddressWithPrefix IP4Prefix // IP6Address represents VPP binary API alias 'ip6_address'. type IP6Address [16]uint8 // IP6AddressWithPrefix represents VPP binary API alias 'ip6_address_with_prefix'. type IP6AddressWithPrefix IP6Prefix // Address represents VPP binary API type 'address'. type Address struct { Af AddressFamily Un AddressUnion } func (*Address) GetTypeName() string { return "address" } // IP4Prefix represents VPP binary API type 'ip4_prefix'. type IP4Prefix struct { Address IP4Address Len uint8 } func (*IP4Prefix) GetTypeName() string { return "ip4_prefix" } // IP6Prefix represents VPP binary API type 'ip6_prefix'. type IP6Prefix struct { Address IP6Address Len uint8 } func (*IP6Prefix) GetTypeName() string { return "ip6_prefix" } // Mprefix represents VPP binary API type 'mprefix'. type Mprefix struct { Af AddressFamily GrpAddressLength uint16 GrpAddress AddressUnion SrcAddress AddressUnion } func (*Mprefix) GetTypeName() string { return "mprefix" } // Prefix represents VPP binary API type 'prefix'. type Prefix struct { Address Address Len uint8 } func (*Prefix) GetTypeName() string { return "prefix" } // PrefixMatcher represents VPP binary API type 'prefix_matcher'. type PrefixMatcher struct { Le uint8 Ge uint8 } func (*PrefixMatcher) GetTypeName() string { return "prefix_matcher" } // AddressUnion represents VPP binary API union 'address_union'. type AddressUnion struct { XXX_UnionData [16]byte } func (*AddressUnion) GetTypeName() string { return "address_union" } func AddressUnionIP4(a IP4Address) (u AddressUnion) { u.SetIP4(a) return } func (u *AddressUnion) SetIP4(a IP4Address) { var b = new(bytes.Buffer) if err := struc.Pack(b, &a); err != nil { return } copy(u.XXX_UnionData[:], b.Bytes()) } func (u *AddressUnion) GetIP4() (a IP4Address) { var b = bytes.NewReader(u.XXX_UnionData[:]) struc.Unpack(b, &a) return } func AddressUnionIP6(a IP6Address) (u AddressUnion) { u.SetIP6(a) return } func (u *AddressUnion) SetIP6(a IP6Address) { var b = new(bytes.Buffer) if err := struc.Pack(b, &a); err != nil { return } copy(u.XXX_UnionData[:], b.Bytes()) } func (u *AddressUnion) GetIP6() (a IP6Address) { var b = bytes.NewReader(u.XXX_UnionData[:]) struc.Unpack(b, &a) return } // SyslogGetFilter represents VPP binary API message 'syslog_get_filter'. type SyslogGetFilter struct{} func (m *SyslogGetFilter) Reset() { *m = SyslogGetFilter{} } func (*SyslogGetFilter) GetMessageName() string { return "syslog_get_filter" } func (*SyslogGetFilter) GetCrcString() string { return "51077d14" } func (*SyslogGetFilter) GetMessageType() api.MessageType { return api.RequestMessage } // SyslogGetFilterReply represents VPP binary API message 'syslog_get_filter_reply'. type SyslogGetFilterReply struct { Retval int32 Severity SyslogSeverity } func (m *SyslogGetFilterReply) Reset() { *m = SyslogGetFilterReply{} } func (*SyslogGetFilterReply) GetMessageName() string { return "syslog_get_filter_reply" } func (*SyslogGetFilterReply) GetCrcString() string { return "eb1833f8" } func (*SyslogGetFilterReply) GetMessageType() api.MessageType { return api.ReplyMessage } // SyslogGetSender represents VPP binary API message 'syslog_get_sender'. type SyslogGetSender struct{} func (m *SyslogGetSender) Reset() { *m = SyslogGetSender{} } func (*SyslogGetSender) GetMessageName() string { return "syslog_get_sender" } func (*SyslogGetSender) GetCrcString() string { return "51077d14" } func (*SyslogGetSender) GetMessageType() api.MessageType { return api.RequestMessage } // SyslogGetSenderReply represents VPP binary API message 'syslog_get_sender_reply'. type SyslogGetSenderReply struct { Retval int32 SrcAddress IP4Address CollectorAddress IP4Address CollectorPort uint16 VrfID uint32 MaxMsgSize uint32 } func (m *SyslogGetSenderReply) Reset() { *m = SyslogGetSenderReply{} } func (*SyslogGetSenderReply) GetMessageName() string { return "syslog_get_sender_reply" } func (*SyslogGetSenderReply) GetCrcString() string { return "d3da60ac" } func (*SyslogGetSenderReply) GetMessageType() api.MessageType { return api.ReplyMessage } // SyslogSetFilter represents VPP binary API message 'syslog_set_filter'. type SyslogSetFilter struct { Severity SyslogSeverity } func (m *SyslogSetFilter) Reset() { *m = SyslogSetFilter{} } func (*SyslogSetFilter) GetMessageName() string { return "syslog_set_filter" } func (*SyslogSetFilter) GetCrcString() string { return "571348c3" } func (*SyslogSetFilter) GetMessageType() api.MessageType { return api.RequestMessage } // SyslogSetFilterReply represents VPP binary API message 'syslog_set_filter_reply'. type SyslogSetFilterReply struct { Retval int32 } func (m *SyslogSetFilterReply) Reset() { *m = SyslogSetFilterReply{} } func (*SyslogSetFilterReply) GetMessageName() string { return "syslog_set_filter_reply" } func (*SyslogSetFilterReply) GetCrcString() string { return "e8d4e804" } func (*SyslogSetFilterReply) GetMessageType() api.MessageType { return api.ReplyMessage } // SyslogSetSender represents VPP binary API message 'syslog_set_sender'. type SyslogSetSender struct { SrcAddress IP4Address CollectorAddress IP4Address CollectorPort uint16 VrfID uint32 MaxMsgSize uint32 } func (m *SyslogSetSender) Reset() { *m = SyslogSetSender{} } func (*SyslogSetSender) GetMessageName() string { return "syslog_set_sender" } func (*SyslogSetSender) GetCrcString() string { return "bb641285" } func (*SyslogSetSender) GetMessageType() api.MessageType { return api.RequestMessage } // SyslogSetSenderReply represents VPP binary API message 'syslog_set_sender_reply'. type SyslogSetSenderReply struct { Retval int32 } func (m *SyslogSetSenderReply) Reset() { *m = SyslogSetSenderReply{} } func (*SyslogSetSenderReply) GetMessageName() string { return "syslog_set_sender_reply" } func (*SyslogSetSenderReply) GetCrcString() string { return "e8d4e804" } func (*SyslogSetSenderReply) GetMessageType() api.MessageType { return api.ReplyMessage } func init() { api.RegisterMessage((*SyslogGetFilter)(nil), "syslog.SyslogGetFilter") api.RegisterMessage((*SyslogGetFilterReply)(nil), "syslog.SyslogGetFilterReply") api.RegisterMessage((*SyslogGetSender)(nil), "syslog.SyslogGetSender") api.RegisterMessage((*SyslogGetSenderReply)(nil), "syslog.SyslogGetSenderReply") api.RegisterMessage((*SyslogSetFilter)(nil), "syslog.SyslogSetFilter") api.RegisterMessage((*SyslogSetFilterReply)(nil), "syslog.SyslogSetFilterReply") api.RegisterMessage((*SyslogSetSender)(nil), "syslog.SyslogSetSender") api.RegisterMessage((*SyslogSetSenderReply)(nil), "syslog.SyslogSetSenderReply") } // Messages returns list of all messages in this module. func AllMessages() []api.Message { return []api.Message{ (*SyslogGetFilter)(nil), (*SyslogGetFilterReply)(nil), (*SyslogGetSender)(nil), (*SyslogGetSenderReply)(nil), (*SyslogSetFilter)(nil), (*SyslogSetFilterReply)(nil), (*SyslogSetSender)(nil), (*SyslogSetSenderReply)(nil), } } // RPCService represents RPC service API for syslog module. type RPCService interface { SyslogGetFilter(ctx context.Context, in *SyslogGetFilter) (*SyslogGetFilterReply, error) SyslogGetSender(ctx context.Context, in *SyslogGetSender) (*SyslogGetSenderReply, error) SyslogSetFilter(ctx context.Context, in *SyslogSetFilter) (*SyslogSetFilterReply, error) SyslogSetSender(ctx context.Context, in *SyslogSetSender) (*SyslogSetSenderReply, error) } type serviceClient struct { ch api.Channel } func NewServiceClient(ch api.Channel) RPCService { return &serviceClient{ch} } func (c *serviceClient) SyslogGetFilter(ctx context.Context, in *SyslogGetFilter) (*SyslogGetFilterReply, error) { out := new(SyslogGetFilterReply) err := c.ch.SendRequest(in).ReceiveReply(out) if err != nil { return nil, err } return out, nil } func (c *serviceClient) SyslogGetSender(ctx context.Context, in *SyslogGetSender) (*SyslogGetSenderReply, error) { out := new(SyslogGetSenderReply) err := c.ch.SendRequest(in).ReceiveReply(out) if err != nil { return nil, err } return out, nil } func (c *serviceClient) SyslogSetFilter(ctx context.Context, in *SyslogSetFilter) (*SyslogSetFilterReply, error) { out := new(SyslogSetFilterReply) err := c.ch.SendRequest(in).ReceiveReply(out) if err != nil { return nil, err } return out, nil } func (c *serviceClient) SyslogSetSender(ctx context.Context, in *SyslogSetSender) (*SyslogSetSenderReply, error) { out := new(SyslogSetSenderReply) err := c.ch.SendRequest(in).ReceiveReply(out) if err != nil { return nil, err } return out, nil } // This is a compile-time assertion to ensure that this generated file // is compatible with the GoVPP api package it is being compiled against. // A compilation error at this line likely means your copy of the // GoVPP api package needs to be updated. const _ = api.GoVppAPIPackageIsVersion1 // please upgrade the GoVPP api package // Reference imports to suppress errors if they are not otherwise used. var _ = api.RegisterMessage var _ = bytes.NewBuffer var _ = context.Background var _ = io.Copy var _ = strconv.Itoa var _ = struc.Pack
VladoLavor/vpp-agent
examples/customize/custom_vpp_plugin/binapi/syslog/syslog.ba.go
GO
apache-2.0
16,205
# CYXSwift2.0 - Swift基本语法汇总(每周更新) - 01 变量、常量 - 02 元祖 - 03 分支 - 04 可选类型 - 05 循环 - 06 数组 - 07 字典 - 08 字符串 - 09 函数 - 10 闭包 - 11 Block - 12 闭包循环引用 - 13 懒加载 - 14 构造函数 - 15 属性
CYXiang/CYXSwift2.0
README.md
Markdown
apache-2.0
273
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.geode.internal.cache.map; import org.apache.logging.log4j.Logger; import org.apache.geode.cache.CacheWriterException; import org.apache.geode.cache.EntryNotFoundException; import org.apache.geode.cache.TimeoutException; import org.apache.geode.cache.query.internal.index.IndexManager; import org.apache.geode.internal.Assert; import org.apache.geode.internal.cache.EntryEventImpl; import org.apache.geode.internal.cache.HARegion; import org.apache.geode.internal.cache.InternalRegion; import org.apache.geode.internal.cache.RegionClearedException; import org.apache.geode.internal.cache.RegionEntry; import org.apache.geode.internal.cache.Token; import org.apache.geode.internal.cache.versions.ConcurrentCacheModificationException; import org.apache.geode.internal.cache.versions.VersionStamp; import org.apache.geode.internal.cache.versions.VersionTag; import org.apache.geode.internal.logging.LogService; import org.apache.geode.internal.logging.log4j.LogMarker; import org.apache.geode.internal.offheap.annotations.Released; import org.apache.geode.internal.sequencelog.EntryLogger; /** * RegionMap Destroy operation. * * <p> * Extracted from AbstractRegionMap. */ public class RegionMapDestroy { private static final Logger logger = LogService.getLogger(); static Runnable testHookRunnableForConcurrentOperation; private final InternalRegion internalRegion; private final FocusedRegionMap focusedRegionMap; private final CacheModificationLock cacheModificationLock; private EntryEventImpl event; private boolean inTokenMode; private boolean duringRI; private boolean cacheWrite; private boolean isEviction; private Object expectedOldValue; private boolean removeRecoveredEntry; private boolean retry = true; private boolean opCompleted = false; private boolean doPart3 = false; private boolean retainForConcurrency = false; private boolean abortDestroyAndReturnFalse; private RegionEntry oldRegionEntry; private RegionEntry newRegionEntry; private RegionEntry regionEntry; private RegionEntry tombstone; private boolean haveTombstone; private boolean doContinue; public RegionMapDestroy(InternalRegion internalRegion, FocusedRegionMap focusedRegionMap, CacheModificationLock cacheModificationLock) { this.internalRegion = internalRegion; this.focusedRegionMap = focusedRegionMap; this.cacheModificationLock = cacheModificationLock; } public boolean destroy(final EntryEventImpl eventArg, final boolean inTokenModeArg, final boolean duringRIArg, final boolean cacheWriteArg, final boolean isEvictionArg, final Object expectedOldValueArg, final boolean removeRecoveredEntryArg) throws CacheWriterException, EntryNotFoundException, TimeoutException { if (internalRegion == null) { Assert.assertTrue(false, "The internalRegion for RegionMap " + this // "fix" for bug 32440 + " is null for event " + event); } event = eventArg; inTokenMode = inTokenModeArg; duringRI = duringRIArg; cacheWrite = cacheWriteArg; isEviction = isEvictionArg; expectedOldValue = expectedOldValueArg; removeRecoveredEntry = removeRecoveredEntryArg; if (event.isFromRILocalDestroy()) { // for RI local-destroy we don't want to keep tombstones. // In order to simplify things we just set this recovery // flag to true to force the entry to be removed removeRecoveredEntry = true; } cacheModificationLock.lockForCacheModification(internalRegion, event); try { while (retry) { retry = false; opCompleted = false; tombstone = null; haveTombstone = false; doContinue = false; abortDestroyAndReturnFalse = false; regionEntry = focusedRegionMap.getEntry(event); invokeTestHookForConcurrentOperation(); try { if (logger.isTraceEnabled(LogMarker.LRU_TOMBSTONE_COUNT) && !(internalRegion instanceof HARegion)) { logger.trace(LogMarker.LRU_TOMBSTONE_COUNT, "ARM.destroy() inTokenMode={}; duringRI={}; riLocalDestroy={}; withRepl={}; fromServer={}; concurrencyEnabled={}; isOriginRemote={}; isEviction={}; operation={}; re={}", inTokenMode, duringRI, event.isFromRILocalDestroy(), internalRegion.getDataPolicy().withReplication(), event.isFromServer(), internalRegion.getConcurrencyChecksEnabled(), event.isOriginRemote(), isEviction, event.getOperation(), regionEntry); } // the logic in this method is already very involved, and adding tombstone // permutations to (re != null) greatly complicates it. So, we check // for a tombstone here and, if found, pretend for a bit that the entry is null if (regionEntry != null && regionEntry.isTombstone() && !removeRecoveredEntry) { tombstone = regionEntry; haveTombstone = true; regionEntry = null; } if (regionEntry == null) { checkTombstoneAndConcurrency(); if (inTokenMode || retainForConcurrency) { handleMissingRegionEntry(); } } else { handleExistingRegionEntry(); } if (abortDestroyAndReturnFalse) { return false; } if (doContinue) { continue; } if (opCompleted) { EntryLogger.logDestroy(event); } return opCompleted; } finally { try { triggerDistributionAndListenerNotification(); } finally { cancelExpiryTaskIfRegionEntryExisted(); } } } // retry loop } finally { cacheModificationLock.releaseCacheModificationLock(internalRegion, event); } return false; } private void checkTombstoneAndConcurrency() { if (regionEntry == null) { // we need to create an entry if in token mode or if we've received // a destroy from a peer or WAN gateway and we need to retain version // information for concurrency checks retainForConcurrency = (!haveTombstone && (internalRegion.getDataPolicy().withReplication() || event.isFromServer()) && internalRegion.getConcurrencyChecksEnabled() && (event.isOriginRemote() /* destroy received from other must create tombstone */ || event.isFromWANAndVersioned() /* wan event must create a tombstone */ || event.isBridgeEvent())); /* * event from client must create a tombstone so client has * a version # */ if (!inTokenMode && !retainForConcurrency) { retryRemoveWithTombstone(); } } } private void handleExistingRegionEntry() { IndexManager oqlIndexManager = internalRegion.getIndexManager(); if (oqlIndexManager != null) { oqlIndexManager.waitForIndexInit(); } try { synchronized (regionEntry) { internalRegion.checkReadiness(); // if the entry is a tombstone and the event is from a peer or a client // then we allow the operation to be performed so that we can update the // version stamp. Otherwise we would retain an old version stamp and may allow // an operation that is older than the destroy() to be applied to the cache // Bug 45170: If removeRecoveredEntry, we treat tombstone as regular entry to be // deleted boolean createTombstoneForConflictChecks = (internalRegion.getConcurrencyChecksEnabled() && (event.isOriginRemote() || event.getContext() != null || removeRecoveredEntry)); if (!regionEntry.isRemoved() || createTombstoneForConflictChecks) { retryIfIsRemovedPhase2(); if (doContinue) { return; } abortLocalExpirationIfEntryIsInUseByTransaction(); if (abortDestroyAndReturnFalse) { return; } event.setRegionEntry(regionEntry); // See comment above about eviction checks confirmEvictionDestroy(); if (abortDestroyAndReturnFalse) { return; } destroyExistingEntry(); } else { // already removed updateVersionTagOnEntryWithTombstone(); if (expectedOldValue != null) { abortDestroyAndReturnFalse = true; return; } if (!inTokenMode && !isEviction) { internalRegion.checkEntryNotFound(event.getKey()); } } } // synchronized re } catch (ConcurrentCacheModificationException e) { VersionTag tag = event.getVersionTag(); if (tag != null && tag.isTimeStampUpdated()) { // Notify gateways of new time-stamp. internalRegion.notifyTimestampsToGateways(event); } throw e; } finally { if (oqlIndexManager != null) { oqlIndexManager.countDownIndexUpdaters(); } } // No need to call lruUpdateCallback since the only lru action // we may have taken was lruEntryDestroy. This fixes bug 31759. } private void cancelExpiryTaskIfRegionEntryExisted() { if (opCompleted) { if (regionEntry != null) { // we only want to cancel if concurrency-check is not enabled // regionEntry will be null when concurrency-check is enable and removeTombstone // method // will call cancelExpiryTask on regionEntry internalRegion.cancelExpiryTask(regionEntry); } } } private void triggerDistributionAndListenerNotification() { // If concurrency conflict is there and event contains gateway version tag then // do NOT distribute. if (event.isConcurrencyConflict() && (event.getVersionTag() != null && event.getVersionTag().isGatewayTag())) { doPart3 = false; } // distribution and listener notification if (doPart3) { internalRegion.basicDestroyPart3(regionEntry, event, inTokenMode, duringRI, true, expectedOldValue); } } private void updateVersionTagOnEntryWithTombstone() { if (regionEntry.isTombstone() && event.getVersionTag() != null) { // if we're dealing with a tombstone and this is a remote event // (e.g., from cache client update thread) we need to update // the tombstone's version information // TODO use destroyEntry() here focusedRegionMap.processVersionTag(regionEntry, event); try { regionEntry.makeTombstone(internalRegion, event.getVersionTag()); } catch (RegionClearedException e) { // that's okay - when writing a tombstone into a disk, the // region has been cleared (including this tombstone) } } } private void confirmEvictionDestroy() { if (isEviction) { assert expectedOldValue == null; if (!focusedRegionMap.confirmEvictionDestroy(regionEntry)) { opCompleted = false; abortDestroyAndReturnFalse = true; } } } private void abortLocalExpirationIfEntryIsInUseByTransaction() { if (!event.isOriginRemote() && event.getOperation().isExpiration()) { // If this expiration started locally then only do it if the RE is not being // used by a tx. if (regionEntry.isInUseByTransaction()) { opCompleted = false; abortDestroyAndReturnFalse = true; } } } private void retryIfIsRemovedPhase2() { if (regionEntry.isRemovedPhase2()) { focusedRegionMap.getEntryMap().remove(event.getKey(), regionEntry); internalRegion.getCachePerfStats().incRetries(); retry = true; doContinue = true; } } private void retryRemoveWithTombstone() { if (!isEviction || internalRegion.getConcurrencyChecksEnabled()) { // The following ensures that there is not a concurrent operation // on the entry and leaves behind a tombstone if concurrencyChecksEnabled. // It fixes bug #32467 by propagating the destroy to the server even though // the entry isn't in the client newRegionEntry = haveTombstone ? tombstone : focusedRegionMap.getEntryFactory().createEntry(internalRegion, event.getKey(), Token.REMOVED_PHASE1); synchronized (newRegionEntry) { if (haveTombstone && !tombstone.isTombstone()) { // we have to check this again under synchronization since it may have changed retry = true; doContinue = true; return; } regionEntry = (RegionEntry) focusedRegionMap.getEntryMap().putIfAbsent(event.getKey(), newRegionEntry); if (regionEntry != null && regionEntry != tombstone) { // concurrent change - try again retry = true; doContinue = true; return; } else if (!isEviction) { try { handleEntryNotFound(); } finally { removeEntryOrLeaveTombstone(); } } } // synchronized(newRegionEntry) } } private void invokeTestHookForConcurrentOperation() { /* * Execute the test hook runnable inline (not threaded) if it is not null. */ if (null != testHookRunnableForConcurrentOperation) { testHookRunnableForConcurrentOperation.run(); } } private void destroyExistingEntry() { boolean removed = false; try { opCompleted = destroyEntry(regionEntry, event, inTokenMode, cacheWrite, expectedOldValue, false, removeRecoveredEntry); if (opCompleted) { // It is very, very important for Partitioned Regions to keep // the entry in the map until after distribution occurs so that other // threads performing a create on this entry wait until the destroy // distribution is finished. // keeping backup copies consistent. Fix for bug 35906. internalRegion.basicDestroyBeforeRemoval(regionEntry, event); // do this before basicDestroyPart2 to fix bug 31786 if (!inTokenMode) { if (regionEntry.getVersionStamp() == null) { regionEntry.removePhase2(); focusedRegionMap.removeEntry(event.getKey(), regionEntry, true, event, internalRegion); removed = true; } } if (inTokenMode && !duringRI) { event.inhibitCacheListenerNotification(true); } doPart3 = true; internalRegion.basicDestroyPart2(regionEntry, event, inTokenMode, false /* conflict with clear */, duringRI, true); focusedRegionMap.lruEntryDestroy(regionEntry); } else { if (!inTokenMode) { EntryLogger.logDestroy(event); internalRegion.recordEvent(event); if (regionEntry.getVersionStamp() == null) { regionEntry.removePhase2(); focusedRegionMap.removeEntry(event.getKey(), regionEntry, true, event, internalRegion); focusedRegionMap.lruEntryDestroy(regionEntry); } else { if (regionEntry.isTombstone()) { // the entry is already a tombstone, but we're destroying it // again, so we need to reschedule the tombstone's expiration if (event.isOriginRemote()) { internalRegion.rescheduleTombstone(regionEntry, regionEntry.getVersionStamp().asVersionTag()); } } } focusedRegionMap.lruEntryDestroy(regionEntry); opCompleted = true; } } } catch (RegionClearedException rce) { // Ignore. The exception will ensure that we do not update // the LRU List opCompleted = true; internalRegion.recordEvent(event); if (inTokenMode && !duringRI) { event.inhibitCacheListenerNotification(true); } internalRegion.basicDestroyPart2(regionEntry, event, inTokenMode, true /* conflict with clear */, duringRI, true); doPart3 = true; } finally { internalRegion.checkReadiness(); if (regionEntry.isRemoved() && !regionEntry.isTombstone()) { if (!removed) { focusedRegionMap.removeEntry(event.getKey(), regionEntry, true, event, internalRegion); } } } } private void removeEntryOrLeaveTombstone() { // either remove the entry or leave a tombstone try { if (!event.isOriginRemote() && event.getVersionTag() != null && internalRegion.getConcurrencyChecksEnabled()) { // this shouldn't fail since we just created the entry. // it will either generate a tag or apply a server's version tag focusedRegionMap.processVersionTag(newRegionEntry, event); if (doPart3) { internalRegion.generateAndSetVersionTag(event, newRegionEntry); } try { internalRegion.recordEvent(event); newRegionEntry.makeTombstone(internalRegion, event.getVersionTag()); } catch (RegionClearedException e) { // that's okay - when writing a tombstone into a disk, the // region has been cleared (including this tombstone) } opCompleted = true; // lruEntryCreate(newRegionEntry); } else if (!haveTombstone) { try { assert newRegionEntry != tombstone; newRegionEntry.setValue(internalRegion, Token.REMOVED_PHASE2); focusedRegionMap.removeEntry(event.getKey(), newRegionEntry, false); } catch (RegionClearedException e) { // that's okay - we just need to remove the new entry } } else if (event.getVersionTag() != null) { // haveTombstone - update the // tombstone version info focusedRegionMap.processVersionTag(tombstone, event); if (doPart3) { internalRegion.generateAndSetVersionTag(event, newRegionEntry); } // This is not conflict, we need to persist the tombstone again with new // version tag try { tombstone.setValue(internalRegion, Token.TOMBSTONE); } catch (RegionClearedException e) { // that's okay - when writing a tombstone into a disk, the // region has been cleared (including this tombstone) } internalRegion.recordEvent(event); internalRegion.rescheduleTombstone(tombstone, event.getVersionTag()); internalRegion.basicDestroyPart2(tombstone, event, inTokenMode, true /* conflict with clear */, duringRI, true); opCompleted = true; } else { Assert.assertTrue(event.getVersionTag() == null); Assert.assertTrue(newRegionEntry == tombstone); event.setVersionTag(getVersionTagFromStamp(tombstone.getVersionStamp())); } } catch (ConcurrentCacheModificationException e) { VersionTag tag = event.getVersionTag(); if (tag != null && tag.isTimeStampUpdated()) { // Notify gateways of new time-stamp. internalRegion.notifyTimestampsToGateways(event); } throw e; } } private void handleEntryNotFound() { boolean throwException = false; EntryNotFoundException entryNotFoundException = null; if (!cacheWrite) { throwException = true; } else { try { if (!removeRecoveredEntry) { throwException = !internalRegion.bridgeWriteBeforeDestroy(event, expectedOldValue); } } catch (EntryNotFoundException e) { throwException = true; entryNotFoundException = e; } } if (throwException) { if (!event.isOriginRemote() && !event.getOperation().isLocal() && (event.isFromBridgeAndVersioned() || // if this is a replayed client // event that already has a // version event.isFromWANAndVersioned())) { // or if this is a WAN event that // has been applied in another // system // we must distribute these since they will update the version information // in peers if (logger.isDebugEnabled()) { logger.debug("ARM.destroy is allowing wan/client destroy of {} to continue", event.getKey()); } throwException = false; event.setIsRedestroyedEntry(true); // Distribution of this op happens on re and re might me null here before // distributing this destroy op. if (regionEntry == null) { regionEntry = newRegionEntry; } doPart3 = true; } } if (throwException) { if (entryNotFoundException == null) { // Fix for 48182, check cache state and/or region state before sending // entry not found. // this is from the server and any exceptions will propogate to the client internalRegion.checkEntryNotFound(event.getKey()); } else { throw entryNotFoundException; } } } private void handleMissingRegionEntry() { // removeRecoveredEntry should be false in this case newRegionEntry = focusedRegionMap.getEntryFactory().createEntry(internalRegion, event.getKey(), Token.REMOVED_PHASE1); IndexManager oqlIndexManager = internalRegion.getIndexManager(); if (oqlIndexManager != null) { oqlIndexManager.waitForIndexInit(); } try { synchronized (newRegionEntry) { oldRegionEntry = focusedRegionMap.putEntryIfAbsent(event.getKey(), newRegionEntry); // what is this doing? removeRegionEntryUntilCompleted(); if (abortDestroyAndReturnFalse) { return; } if (!opCompleted) { // The following try has a finally that cleans up the newRegionEntry. // This is only needed if newRegionEntry was added to the map which only // happens if we didn't get completed with oldRegionEntry in the above while // loop. try { regionEntry = newRegionEntry; event.setRegionEntry(newRegionEntry); try { // if concurrency checks are enabled, destroy will set the version tag if (isEviction) { opCompleted = false; abortDestroyAndReturnFalse = true; return; } destroyEntryInternal(newRegionEntry, oldRegionEntry); } catch (RegionClearedException rce) { handleRegionClearedExceptionDuringDestroyEntryInternal(newRegionEntry); } catch (ConcurrentCacheModificationException ccme) { VersionTag tag = event.getVersionTag(); if (tag != null && tag.isTimeStampUpdated()) { // Notify gateways of new time-stamp. internalRegion.notifyTimestampsToGateways(event); } throw ccme; } // Note no need for LRU work since the entry is destroyed // and will be removed when gii completes } finally { if (!opCompleted && !haveTombstone /* to fix bug 51583 do this for all operations */ ) { focusedRegionMap.removeEntry(event.getKey(), newRegionEntry, false); } if (!opCompleted && isEviction) { focusedRegionMap.removeEntry(event.getKey(), newRegionEntry, false); } } } // !opCompleted } // synchronized newRegionEntry } finally { if (oqlIndexManager != null) { oqlIndexManager.countDownIndexUpdaters(); } } } private void removeRegionEntryUntilCompleted() { while (!opCompleted && oldRegionEntry != null) { synchronized (oldRegionEntry) { if (oldRegionEntry.isRemovedPhase2()) { internalRegion.getCachePerfStats().incRetries(); focusedRegionMap.getEntryMap().remove(event.getKey(), oldRegionEntry); oldRegionEntry = focusedRegionMap.putEntryIfAbsent(event.getKey(), newRegionEntry); } else { event.setRegionEntry(oldRegionEntry); // Last transaction related eviction check. This should // prevent // transaction conflict (caused by eviction) when the entry // is being added to transaction state. if (isEviction) { if (!focusedRegionMap.confirmEvictionDestroy(oldRegionEntry)) { opCompleted = false; abortDestroyAndReturnFalse = true; return; } } try { // if concurrency checks are enabled, destroy will set the version tag boolean destroyed = destroyEntry(oldRegionEntry, event, inTokenMode, cacheWrite, expectedOldValue, false, removeRecoveredEntry); if (destroyed) { if (retainForConcurrency) { internalRegion.basicDestroyBeforeRemoval(oldRegionEntry, event); } internalRegion.basicDestroyPart2(oldRegionEntry, event, inTokenMode, false /* conflict with clear */, duringRI, true); focusedRegionMap.lruEntryDestroy(oldRegionEntry); doPart3 = true; } } catch (RegionClearedException rce) { // Ignore. The exception will ensure that we do not update // the LRU List internalRegion.basicDestroyPart2(oldRegionEntry, event, inTokenMode, true/* conflict with clear */, duringRI, true); doPart3 = true; } catch (ConcurrentCacheModificationException ccme) { // TODO: GEODE-3967: change will go here VersionTag tag = event.getVersionTag(); if (tag != null && tag.isTimeStampUpdated()) { // Notify gateways of new time-stamp. internalRegion.notifyTimestampsToGateways(event); } throw ccme; } regionEntry = oldRegionEntry; opCompleted = true; } } // synchronized oldRegionEntry } // while } private void handleRegionClearedExceptionDuringDestroyEntryInternal(RegionEntry newRegionEntry) { // Ignore. The exception will ensure that we do not update the LRU List opCompleted = true; EntryLogger.logDestroy(event); internalRegion.basicDestroyPart2(newRegionEntry, event, inTokenMode, true, duringRI, true); doPart3 = true; } private void destroyEntryInternal(RegionEntry newRegionEntry, RegionEntry oldRegionEntry) throws RegionClearedException { opCompleted = destroyEntry(newRegionEntry, event, inTokenMode, cacheWrite, expectedOldValue, true, removeRecoveredEntry); if (opCompleted) { // This is a new entry that was created because we are in // token mode or are accepting a destroy operation by adding // a tombstone. There is no oldValue, so we don't need to // call updateSizeOnRemove // internalRegion.recordEvent(event); event.setIsRedestroyedEntry(true); // native clients need to know if the // entry didn't exist if (retainForConcurrency) { internalRegion.basicDestroyBeforeRemoval(oldRegionEntry, event); } internalRegion.basicDestroyPart2(newRegionEntry, event, inTokenMode, false, duringRI, true); doPart3 = true; } } private boolean destroyEntry(RegionEntry re, EntryEventImpl event, boolean inTokenMode, boolean cacheWrite, @Released Object expectedOldValue, boolean forceDestroy, boolean removeRecoveredEntry) throws CacheWriterException, TimeoutException, EntryNotFoundException, RegionClearedException { focusedRegionMap.processVersionTag(re, event); final int oldSize = internalRegion.calculateRegionEntryValueSize(re); boolean retVal = re.destroy(event.getLocalRegion(), event, inTokenMode, cacheWrite, expectedOldValue, forceDestroy, removeRecoveredEntry); if (retVal) { EntryLogger.logDestroy(event); internalRegion.updateSizeOnRemove(event.getKey(), oldSize); } return retVal; } private VersionTag getVersionTagFromStamp(VersionStamp stamp) { VersionTag tag = VersionTag.create(stamp.getMemberID()); tag.setEntryVersion(stamp.getEntryVersion()); tag.setRegionVersion(stamp.getRegionVersion()); tag.setVersionTimeStamp(stamp.getVersionTimeStamp()); tag.setDistributedSystemId(stamp.getDistributedSystemId()); return tag; } }
smanvi-pivotal/geode
geode-core/src/main/java/org/apache/geode/internal/cache/map/RegionMapDestroy.java
Java
apache-2.0
29,181
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.medialive.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.medialive.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * InputDeviceSummary JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class InputDeviceSummaryJsonUnmarshaller implements Unmarshaller<InputDeviceSummary, JsonUnmarshallerContext> { public InputDeviceSummary unmarshall(JsonUnmarshallerContext context) throws Exception { InputDeviceSummary inputDeviceSummary = new InputDeviceSummary(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return null; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("arn", targetDepth)) { context.nextToken(); inputDeviceSummary.setArn(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("connectionState", targetDepth)) { context.nextToken(); inputDeviceSummary.setConnectionState(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("deviceSettingsSyncState", targetDepth)) { context.nextToken(); inputDeviceSummary.setDeviceSettingsSyncState(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("deviceUpdateStatus", targetDepth)) { context.nextToken(); inputDeviceSummary.setDeviceUpdateStatus(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("hdDeviceSettings", targetDepth)) { context.nextToken(); inputDeviceSummary.setHdDeviceSettings(InputDeviceHdSettingsJsonUnmarshaller.getInstance().unmarshall(context)); } if (context.testExpression("id", targetDepth)) { context.nextToken(); inputDeviceSummary.setId(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("macAddress", targetDepth)) { context.nextToken(); inputDeviceSummary.setMacAddress(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("name", targetDepth)) { context.nextToken(); inputDeviceSummary.setName(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("networkSettings", targetDepth)) { context.nextToken(); inputDeviceSummary.setNetworkSettings(InputDeviceNetworkSettingsJsonUnmarshaller.getInstance().unmarshall(context)); } if (context.testExpression("serialNumber", targetDepth)) { context.nextToken(); inputDeviceSummary.setSerialNumber(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("type", targetDepth)) { context.nextToken(); inputDeviceSummary.setType(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("uhdDeviceSettings", targetDepth)) { context.nextToken(); inputDeviceSummary.setUhdDeviceSettings(InputDeviceUhdSettingsJsonUnmarshaller.getInstance().unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return inputDeviceSummary; } private static InputDeviceSummaryJsonUnmarshaller instance; public static InputDeviceSummaryJsonUnmarshaller getInstance() { if (instance == null) instance = new InputDeviceSummaryJsonUnmarshaller(); return instance; } }
aws/aws-sdk-java
aws-java-sdk-medialive/src/main/java/com/amazonaws/services/medialive/model/transform/InputDeviceSummaryJsonUnmarshaller.java
Java
apache-2.0
5,561
/* Copyright 2015 Sindre Ilebekk Johansen and Andreas Sløgedal Løvland * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include "GameFramework/SpectatorPawn.h" #include "VehicleSpectatorPawn.generated.h" UCLASS(config = Game, Blueprintable, BlueprintType) class AVehicleSpectatorPawn : public ASpectatorPawn { GENERATED_UCLASS_BODY() virtual void SetupPlayerInputComponent(UInputComponent* InputComponent) override; };
HighwayFlocking/HighwayFlocking
Source/HighwayFlocking/VehicleSpectatorPawn.h
C
apache-2.0
936
/* * Copyright (c) 2008-2016 Haulmont. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.haulmont.cuba.web.test.ds.api.consistency; import com.google.common.collect.ImmutableMap; import com.haulmont.cuba.core.sys.AppContext; import com.haulmont.cuba.gui.components.ds.api.consistency.LookupFieldDsTest; import com.haulmont.cuba.web.gui.WebComponentsFactory; import com.vaadin.v7.data.util.converter.DefaultConverterFactory; import com.vaadin.server.VaadinSession; import mockit.Mocked; import mockit.Expectations; import org.junit.Ignore; import java.util.Locale; @Ignore public class WebLookupFieldDsTest extends LookupFieldDsTest { @Mocked protected VaadinSession vaadinSession; public WebLookupFieldDsTest() { factory = new WebComponentsFactory(); } @Override protected void initExpectations() { super.initExpectations(); new Expectations() { { vaadinSession.getLocale(); result = Locale.ENGLISH; minTimes = 0; VaadinSession.getCurrent(); result = vaadinSession; minTimes = 0; vaadinSession.getConverterFactory(); result = new DefaultConverterFactory(); minTimes = 0; globalConfig.getAvailableLocales(); result = ImmutableMap.of("en", Locale.ENGLISH); minTimes = 0; AppContext.getProperty("cuba.mainMessagePack"); result = "com.haulmont.cuba.web"; minTimes = 0; } }; } }
dimone-kun/cuba
modules/web/test/com/haulmont/cuba/web/test/ds/api/consistency/WebLookupFieldDsTest.java
Java
apache-2.0
1,973
/* * ============================================================================= * * Copyright (c) 2011-2014, The THYMELEAF team (http://www.thymeleaf.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * ============================================================================= */ package org.thymeleaf.engine; import java.io.IOException; import java.io.Writer; import org.thymeleaf.IEngineConfiguration; import org.thymeleaf.model.IUnmatchedCloseElementTag; import org.thymeleaf.templatemode.TemplateMode; import org.thymeleaf.util.Validate; /** * * @author Daniel Fern&aacute;ndez * @since 3.0.0 * */ final class UnmatchedCloseElementTag extends AbstractElementTag implements IUnmatchedCloseElementTag, IEngineTemplateHandlerEvent { /* * Objects of this class are meant to both be reused by the engine and also created fresh by the processors. This * should allow reducing the number of instances of this class to the minimum. */ // Meant to be called only from the template handler adapter UnmatchedCloseElementTag( final TemplateMode templateMode, final ElementDefinitions elementDefinitions) { super(templateMode, elementDefinitions); } // Meant to be called only from the model factory UnmatchedCloseElementTag( final TemplateMode templateMode, final ElementDefinitions elementDefinitions, final String elementName) { super(templateMode, elementDefinitions, elementName); } // Meant to be called only from the cloneElementTag method private UnmatchedCloseElementTag() { super(); } // Meant to be called only from within the engine void setUnmatchedCloseElementTag( final String elementName, final String templateName, final int line, final int col) { resetElementTag(elementName, templateName, line, col); } public void write(final Writer writer) throws IOException { // We will write exactly the same as for non-unmatched close elements, because that does not matter from the markup point Validate.notNull(writer, "Writer cannot be null"); writer.write("</"); writer.write(this.elementName); writer.write('>'); } public UnmatchedCloseElementTag cloneElementTag() { final UnmatchedCloseElementTag clone = new UnmatchedCloseElementTag(); clone.resetAsCloneOf(this); return clone; } // Meant to be called only from within the engine void resetAsCloneOf(final UnmatchedCloseElementTag from) { super.resetAsCloneOfElementTag(from); } // Meant to be called only from within the engine static UnmatchedCloseElementTag asEngineUnmatchedCloseElementTag( final TemplateMode templateMode, final IEngineConfiguration configuration, final IUnmatchedCloseElementTag unmatchedCloseElementTag, final boolean cloneAlways) { if (unmatchedCloseElementTag instanceof UnmatchedCloseElementTag) { if (cloneAlways) { return ((UnmatchedCloseElementTag) unmatchedCloseElementTag).cloneElementTag(); } return (UnmatchedCloseElementTag) unmatchedCloseElementTag; } final UnmatchedCloseElementTag newInstance = new UnmatchedCloseElementTag(templateMode, configuration.getElementDefinitions()); newInstance.setUnmatchedCloseElementTag(unmatchedCloseElementTag.getElementName(), unmatchedCloseElementTag.getTemplateName(), unmatchedCloseElementTag.getLine(), unmatchedCloseElementTag.getCol()); return newInstance; } }
magat/thymeleaf
src/main/java/org/thymeleaf/engine/UnmatchedCloseElementTag.java
Java
apache-2.0
4,224
<!--Charts styles--> <link type="text/css" rel="stylesheet" href="<?php echo base_url() ?>assets/ishan/css/charts.css"> <!--end chart style--> <!--my styles--> <link type="text/css" rel="stylesheet" href="<?php echo base_url() ?>assets/ishan/css/style.css"> <!--end my style--> <!--pagination styles--> <link type="text/css" rel="stylesheet" href="<?php echo base_url() ?>assets/ishan/css/pagination.css"> <!--end pagination stye--> <!--static chart--> <script src="<?php echo base_url() ?>assets/admin/js/Chart.min.js"></script> <!--//charts--> <!--inner block start here--> <div class="inner-block"> <div class="chart-main-block"> <div style="background-color: #9acfea;padding: 15px;"> <h3>Most Visited Places</h3> </div> <div class="row" style="padding: 25px;"> <h4>Filter your result</h4> <p>Select one or more options to get the result</p> </div> <div class="row" style="padding: 25px;"> <form action="<?php echo site_url() ?>Charts/search" method="post"> <div class="col-md-3"> <label>Search a place</label> <input value="<?php if(isset($filled["place"])){echo $filled["place"]; }?>" name="place_name" placeholder="Type a place name" class="form-control"> </div> <div class="col-md-3"> <label>Monthly wise</label> <select name="month" class="form-control"> <option value="0" <?php if(isset($filled["month"]) && $filled["month"]=='0'){echo 'selected'; }?> >Select a month</option> <option value="1" <?php if(isset($filled["month"]) && $filled["month"]=='1'){echo 'selected'; }?> >January</option> <option value="2" <?php if(isset($filled["month"]) && $filled["month"]=='2'){echo 'selected'; }?> >February</option> <option value="3" <?php if(isset($filled["month"]) && $filled["month"]=='3'){echo 'selected'; }?> >March</option> <option value="4" <?php if(isset($filled["month"]) && $filled["month"]=='4'){echo 'selected'; }?> >April</option> <option value="5" <?php if(isset($filled["month"]) && $filled["month"]=='5'){echo 'selected'; }?> >May</option> <option value="6" <?php if(isset($filled["month"]) && $filled["month"]=='6'){echo 'selected'; }?> >June</option> <option value="7" <?php if(isset($filled["month"]) && $filled["month"]=='7'){echo 'selected'; }?> >July</option> <option value="8" <?php if(isset($filled["month"]) && $filled["month"]=='8'){echo 'selected'; }?> >August</option> <option value="9" <?php if(isset($filled["month"]) && $filled["month"]=='9'){echo 'selected'; }?> >September</option> <option value="10" <?php if(isset($filled["month"]) && $filled["month"]=='10'){echo 'selected'; }?> >October</option> <option value="11" <?php if(isset($filled["month"]) && $filled["month"]=='11'){echo 'selected'; }?> >November</option> <option value="12" <?php if(isset($filled["month"]) && $filled["month"]=='12'){echo 'selected'; }?> >December</option> </select> </div> <div class="col-md-3"> <label>Category wise</label> <select name="category" class="form-control"> <option value="0" selected="">Select a category</option> <?php foreach ($category as $cat): ?> <option <?php if(isset($filled["category"]) && $filled["category"]==$cat->ca_id){echo 'selected'; }?> value="<?php echo $cat->ca_id ?>" ><?php echo $cat->ca_name ?></option> <?php endforeach; ?> </select> </div> <div class="col-md-3"> <label>Click here for search</label> <input type="submit" class="form-control btn-info" value="Seacrh"> </div> </form> </div> <!--most visited all list--> <div id="defaultResult"> <?php if(isset($list)){ if($list){ ?> <!--Pagination links--> <div class="row" id="pagination" style="padding: 10px;"> <div class="col-md-3"></div> <div class="col-md-6"> <ul class="tsc_pagination"> <!-- Show pagination links --> <?php foreach ($links as $link) { echo "<li class='myPagination'>". $link. "</li>"; } ?> </ul> </div> <div class="col-md-3"></div> </div> <table style="border: 1px solid"> <tr> <th>Place Name</th> <th>Total Visits</th> <th>Category</th> </tr> <?php foreach ($list as $res): ?> <tr> <td><?php echo $res->pl_name ?></td> <td><?php echo $res->tour_count ?></td> <td><?php echo $res->ca_name ?></td> </tr> <?php endforeach; ?> </table> <?php } else { ?> <p>No Results found</p> <?php } } ?> </div> <div id="searchResult" class="row" style="padding: 30px 15px 15px 15px;"> <?php if(isset($search)){ if($search!=FALSE){ ?> <!-- Pagination links <div class="row" id="pagination" style="padding: 10px;"> <div class="col-md-3"></div> <div class="col-md-6"> <ul class="tsc_pagination"> </ul> </div> <div class="col-md-3"></div> </div>--> <table style="border: 1px solid"> <tr> <th>Place Name</th> <th>Category</th> <th>Total Visits</th> </tr> <?php foreach ($search as $res): ?> <tr> <td><?php echo $res->pl_name ?></td> <td><?php echo $res->ca_name ?></td> <td><?php echo $res->tour_count ?></td> </tr> <?php endforeach; ?> </table> <?php } else { ?> <div style="background-color: #ff4242;"> <p style="color: white;font-weight: bold;font-size: 20px; padding: 25px;" class="">No Results found</p> </div> <?php } } ?> </div> <?php if(isset($mstVisitedPlc[0])) { $value1=$mstVisitedPlc[0]->pl_count; $name1=$mstVisitedPlc[0]->pl_name; } if(isset($mstVisitedPlc[1])) { $value2=$mstVisitedPlc[1]->pl_count; $name2=$mstVisitedPlc[1]->pl_name; } if(isset($mstVisitedPlc[2])) { $value3=$mstVisitedPlc[2]->pl_count; $name3=$mstVisitedPlc[2]->pl_name; } if(isset($mstVisitedPlc[3])) { $value4=$mstVisitedPlc[3]->pl_count; $name4=$mstVisitedPlc[3]->pl_name; } ?> <div class="row" style="padding: 20px;"> <div class="row" style="padding: 20px;"> <label>Most popular four places</label> </div> <div class="col-sm-2"> <!--Item1--> <div style="width:30px; height: 30px; background: #337AB7;"></div> <?php if(isset($mstVisitedPlc[0])){ echo $name1;}?> </div> <div class="col-sm-2"> <!--Item2--> <div style="width:30px; height: 30px; background: #929292;"></div> <?php if(isset($mstVisitedPlc[1])){ echo $name2;}?> </div> <div class="col-sm-2"> <!--Item3--> <div style="width:30px; height: 30px; background: #FC8213;"></div> <?php if(isset($mstVisitedPlc[2])){ echo $name3;}?> </div> <div class="col-sm-2"> <!--Item4--> <div style="width:30px; height: 30px; background: #68AE00;"></div> <?php if(isset($mstVisitedPlc[3])){ echo $name4;}?> </div> </div> <div style="background-color: #9acfea;padding: 15px;"> <h3>Charts</h3> </div> <div class="chart-first-line"> <div class="col-md-6 chart-blo-1"> <div class="dygno"> <h2>Doughnut</h2> <canvas id="doughnut" height="300" width="470" style="width: 470px; height: 300px;"></canvas> <script> var doughnutData = [ { value: <?php if(isset($mstVisitedPlc[0])){ echo $value1; } ?>, color:"#337AB7" }, { value : <?php if(isset($mstVisitedPlc[0])){ echo $value2; } ?>, color : "#929292" }, { value : <?php if(isset($mstVisitedPlc[0])){ echo $value3; } ?>, color : "#FC8213" }, { value : <?php if(isset($mstVisitedPlc[0])){ echo $value4; } ?>, color : "#68AE00" } ]; new Chart(document.getElementById("doughnut").getContext("2d")).Doughnut(doughnutData); </script> </div> </div> <div class="col-md-6 chart-blo-1"> <div class="chart-other"> <h3>Pie</h3> <canvas id="pie" height="315" width="470" style="width: 470px; height: 315px;"></canvas> <script> var pieData = [ { value: <?php if(isset($mstVisitedPlc[0])){ echo $value1; } ?>, color:"#337AB7" }, { value : <?php if(isset($mstVisitedPlc[1])){ echo $value2; } ?>, color : "#929292" }, { value : <?php if(isset($mstVisitedPlc[2])){ echo $value3; } ?>, color : "#FC8213" }, { value : <?php if(isset($mstVisitedPlc[3])){ echo $value4; } ?>, color : "#8BC34A" } ]; new Chart(document.getElementById("pie").getContext("2d")).Pie(pieData); </script> </div> </div> <div class="clearfix"> </div> </div> <div class="chart-second-line"> <div class="col-md-6 chart-blo-1"> <div class="polararea"> <h3>Polar Chart</h3> <canvas id="polarArea" height="300" width="300" style="width: 300px; height: 300px;"></canvas> <script> var chartData = [ { value : <?php if(isset($mstVisitedPlc[0])){ echo $value1; } ?>, color: "#337AB7" }, { value : <?php if(isset($mstVisitedPlc[1])){ echo $value2; } ?>, color: "#929292" }, { value : <?php if(isset($mstVisitedPlc[2])){ echo $value3; } ?>, color: "#FC8213" }, { value : <?php if(isset($mstVisitedPlc[3])){ echo $value3; } ?>, color: "#8BC34A" } ]; new Chart(document.getElementById("polarArea").getContext("2d")).PolarArea(chartData); </script> </div> </div> <div class="col-md-6 chart-blo-1"> </div> <div class="clearfix"> </div> </div> </div> </div> <!--inner block end here--> <!--copy rights start here--> <div class="copyrights"> <p>© 2016 Shoppy. All Rights Reserved | Design by <a href="http://w3layouts.com/" target="_blank">W3layouts</a> </p> </div> <!--COPY rights end here--> </div> </div>
sepProjectTeam/TourismApplication
sep_ii_pro/application/views/admin/charts.php
PHP
apache-2.0
13,224
<!-- Copyright (C) 2010-2013 Andrei Pozolotin <Andrei.Pozolotin@gmail.com> All rights reserved. Licensed under the OSI BSD License. http://www.opensource.org/licenses/bsd-license.php --> jwrapper-maven-plugin ===================== JWrapper Maven plugin.
jwrapper/jwrapper-maven-plugin
readme.md
Markdown
apache-2.0
271
// CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("distfs/codemirror/lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["distfs/codemirror/lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("apl", function() { var builtInOps = { ".": "innerProduct", "\\": "scan", "/": "reduce", "⌿": "reduce1Axis", "⍀": "scan1Axis", "¨": "each", "⍣": "power" }; var builtInFuncs = { "+": ["conjugate", "add"], "−": ["negate", "subtract"], "×": ["signOf", "multiply"], "÷": ["reciprocal", "divide"], "⌈": ["ceiling", "greaterOf"], "⌊": ["floor", "lesserOf"], "∣": ["absolute", "residue"], "⍳": ["indexGenerate", "indexOf"], "?": ["roll", "deal"], "⋆": ["exponentiate", "toThePowerOf"], "⍟": ["naturalLog", "logToTheBase"], "○": ["piTimes", "circularFuncs"], "!": ["factorial", "binomial"], "⌹": ["matrixInverse", "matrixDivide"], "<": [null, "lessThan"], "≤": [null, "lessThanOrEqual"], "=": [null, "equals"], ">": [null, "greaterThan"], "≥": [null, "greaterThanOrEqual"], "≠": [null, "notEqual"], "≡": ["depth", "match"], "≢": [null, "notMatch"], "∈": ["enlist", "membership"], "⍷": [null, "find"], "∪": ["unique", "union"], "∩": [null, "intersection"], "∼": ["not", "without"], "∨": [null, "or"], "∧": [null, "and"], "⍱": [null, "nor"], "⍲": [null, "nand"], "⍴": ["shapeOf", "reshape"], ",": ["ravel", "catenate"], "⍪": [null, "firstAxisCatenate"], "⌽": ["reverse", "rotate"], "⊖": ["axis1Reverse", "axis1Rotate"], "⍉": ["transpose", null], "↑": ["first", "take"], "↓": [null, "drop"], "⊂": ["enclose", "partitionWithAxis"], "⊃": ["diclose", "pick"], "⌷": [null, "index"], "⍋": ["gradeUp", null], "⍒": ["gradeDown", null], "⊤": ["encode", null], "⊥": ["decode", null], "⍕": ["format", "formatByExample"], "⍎": ["execute", null], "⊣": ["stop", "left"], "⊢": ["pass", "right"] }; var isOperator = /[\.\/⌿⍀¨⍣]/; var isNiladic = /⍬/; var isFunction = /[\+−×÷⌈⌊∣⍳\?⋆⍟○!⌹<≤=>≥≠≡≢∈⍷∪∩∼∨∧⍱⍲⍴,⍪⌽⊖⍉↑↓⊂⊃⌷⍋⍒⊤⊥⍕⍎⊣⊢]/; var isArrow = /←/; var isComment = /[⍝#].*$/; var stringEater = function(type) { var prev; prev = false; return function(c) { prev = c; if (c === type) { return prev === "\\"; } return true; }; }; return { startState: function() { return { prev: false, func: false, op: false, string: false, escape: false }; }, token: function(stream, state) { var ch, funcName, word; if (stream.eatSpace()) { return null; } ch = stream.next(); if (ch === '"' || ch === "'") { stream.eatWhile(stringEater(ch)); stream.next(); state.prev = true; return "string"; } if (/[\[{\(]/.test(ch)) { state.prev = false; return null; } if (/[\]}\)]/.test(ch)) { state.prev = true; return null; } if (isNiladic.test(ch)) { state.prev = false; return "niladic"; } if (/[¯\d]/.test(ch)) { if (state.func) { state.func = false; state.prev = false; } else { state.prev = true; } stream.eatWhile(/[\w\.]/); return "number"; } if (isOperator.test(ch)) { return "operator apl-" + builtInOps[ch]; } if (isArrow.test(ch)) { return "apl-arrow"; } if (isFunction.test(ch)) { funcName = "apl-"; if (builtInFuncs[ch] != null) { if (state.prev) { funcName += builtInFuncs[ch][1]; } else { funcName += builtInFuncs[ch][0]; } } state.func = true; state.prev = false; return "function " + funcName; } if (isComment.test(ch)) { stream.skipToEnd(); return "comment"; } if (ch === "∘" && stream.peek() === ".") { stream.next(); return "function jot-dot"; } stream.eatWhile(/[\w\$_]/); word = stream.current(); state.prev = true; return "keyword"; } }; }); CodeMirror.defineMIME("text/apl", "apl"); });
feaster83/elasticsearch-distfs
src/_site/codemirror/mode/apl/apl.js
JavaScript
apache-2.0
4,797
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.backends.android; import android.media.AudioManager; import android.media.SoundPool; import com.badlogic.gdx.audio.Sound; import com.badlogic.gdx.utils.IntArray; final class AndroidSound implements Sound { final SoundPool soundPool; final AudioManager manager; final int soundId; final IntArray streamIds = new IntArray(8); AndroidSound (SoundPool pool, AudioManager manager, int soundId) { this.soundPool = pool; this.manager = manager; this.soundId = soundId; } @Override public void dispose () { soundPool.unload(soundId); } @Override public void play () { play(1); } @Override public void play (float volume) { if (streamIds.size == 8) streamIds.pop(); streamIds.add(soundPool.play(soundId, volume, volume, 1, 0, 1)); } public void stop () { for (int i = 0, n = streamIds.size; i < n; i++) soundPool.stop(streamIds.get(i)); } }
aevum/libgdx-cpp
src/gdx-cpp/backends/android/android_support/src/com/badlogic/gdx/backends/android/AndroidSound.java
Java
apache-2.0
1,710
package co.com.codesoftware.beans.productos; import java.util.Date; import java.util.List; import javax.annotation.PostConstruct; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; import javax.faces.context.FacesContext; import org.primefaces.context.RequestContext; import org.primefaces.event.CellEditEvent; import co.com.codesoftware.logica.SolicitudesLogica; import co.com.codesoftware.servicio.producto.ExistenciaXSedeEntity; import co.com.codesoftware.servicio.producto.RespuestaEntity; import co.com.codesoftware.servicio.producto.SolicitudEntity; import co.com.codesoftware.servicio.producto.SolicitudProdEntity; import co.com.codesoftware.servicio.usuario.UsuarioEntity; import co.com.codesoftware.utilities.ErrorEnum; import co.com.codesoftware.utilities.GeneralBean; @ManagedBean @ViewScoped public class SolicitudesBean implements GeneralBean { private UsuarioEntity objetoSesion; private ErrorEnum enumer; private Date fechaInicial; private Date fechaFinal; private String estado; private List<SolicitudEntity> solicitudes; private SolicitudesLogica logica; private List<SolicitudProdEntity> productosSolicitud; private String estadoSolicitud; private String sedeNombreSelec; private List<ExistenciaXSedeEntity> listaExistencia; @Override @PostConstruct public void init() { logica = new SolicitudesLogica(); this.estadoSolicitud = "P"; } /** * metodo que consulta las solicitudes por estado */ public void consultaSolicitudes() { try { this.solicitudes = logica.consultaSolicitudes(fechaInicial, fechaFinal, estado); } catch (Exception e) { e.printStackTrace(); } } /** * metodo que consulta el detalle de la solicitud * * @param idSolicitud * @return */ public void consultaDetalle(Integer idSolicitud, String nombreSedeOrigen) { this.sedeNombreSelec = nombreSedeOrigen; try { productosSolicitud = logica.consultaProductosEspecificos(idSolicitud); RequestContext requestContext = RequestContext.getCurrentInstance(); this.estadoSolicitud = productosSolicitud.get(0).getSolicitud().getEstado(); requestContext.execute("PF('wdetalleProductos').show()"); } catch (Exception e) { e.printStackTrace(); } } /** * envia al formulario de detalle de productos de la solicitud * * @param idSolicitud */ public String consultaDetalleSolicitud(Integer idSolicitud) { String rta = ""; try { FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("idSolicitud", idSolicitud); rta = "/ACTION/SOLICITUDES/detalleSolicitud.jsf"; } catch (Exception e) { e.printStackTrace(); } return rta; } /** * metodo que evalua el cambio de la tabla editable * * @param event */ public void onCellEdit(CellEditEvent event) { } /** * metodo que acutaliza los datos del pedido */ public void actualizaPedido() { RespuestaEntity respuestaActualizacion = logica.actualizaSolicitud(1, this.productosSolicitud); if (respuestaActualizacion.getCodigoRespuesta() == 0) { this.enumer = enumer.ERROR; } else { this.enumer = enumer.SUCCESS; } messageBean(respuestaActualizacion.getDescripcionRespuesta()); } /** * metodo que consulta las existencias por todas las sedes * * @param idProducto */ public void consultaExistenciaSedes(Integer idProducto) { this.listaExistencia = logica.consultaExistenciasXId(idProducto); } public UsuarioEntity getObjetoSesion() { return objetoSesion; } public void setObjetoSesion(UsuarioEntity objetoSesion) { this.objetoSesion = objetoSesion; } public ErrorEnum getEnumer() { return enumer; } public void setEnumer(ErrorEnum enumer) { this.enumer = enumer; } public Date getFechaInicial() { return fechaInicial; } public void setFechaInicial(Date fechaInicial) { this.fechaInicial = fechaInicial; } public Date getFechaFinal() { return fechaFinal; } public void setFechaFinal(Date fechaFinal) { this.fechaFinal = fechaFinal; } public String getEstado() { return estado; } public void setEstado(String estado) { this.estado = estado; } public List<SolicitudEntity> getSolicitudes() { return solicitudes; } public void setSolicitudes(List<SolicitudEntity> solicitudes) { this.solicitudes = solicitudes; } public List<SolicitudProdEntity> getProductosSolicitud() { return productosSolicitud; } public void setProductosSolicitud(List<SolicitudProdEntity> productosSolicitud) { this.productosSolicitud = productosSolicitud; } public String getEstadoSolicitud() { return estadoSolicitud; } public void setEstadoSolicitud(String estadoSolicitud) { this.estadoSolicitud = estadoSolicitud; } public void messageBean(String message) { switch (this.enumer) { case ERROR: FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error!", message)); break; case FATAL: FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_FATAL, "Fatal!", "Error de sistema")); break; case SUCCESS: FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Ok!", message)); break; default: break; } } public String getSedeNombreSelec() { return sedeNombreSelec; } public void setSedeNombreSelec(String sedeNombreSelec) { this.sedeNombreSelec = sedeNombreSelec; } public List<ExistenciaXSedeEntity> getListaExistencia() { return listaExistencia; } public void setListaExistencia(List<ExistenciaXSedeEntity> listaExistencia) { this.listaExistencia = listaExistencia; } }
codesoftware/NSIGEMCO
src/main/java/co/com/codesoftware/beans/productos/SolicitudesBean.java
Java
apache-2.0
5,674
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_151) on Tue Aug 14 15:31:45 MST 2018 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>CustomRealmMapperConsumer (BOM: * : All 2.1.0.Final API)</title> <meta name="date" content="2018-08-14"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="CustomRealmMapperConsumer (BOM: * : All 2.1.0.Final API)"; } } catch(err) { } //--> var methods = {"i0":6,"i1":18}; var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],4:["t3","Abstract Methods"],16:["t5","Default Methods"]}; var altColor = "altColor"; var rowColor = "rowColor"; var tableTab = "tableTab"; var activeTableTab = "activeTableTab"; </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/CustomRealmMapperConsumer.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage">Thorntail API, 2.1.0.Final</div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../org/wildfly/swarm/config/elytron/CustomRealmMapper.html" title="class in org.wildfly.swarm.config.elytron"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../../../org/wildfly/swarm/config/elytron/CustomRealmMapperSupplier.html" title="interface in org.wildfly.swarm.config.elytron"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/wildfly/swarm/config/elytron/CustomRealmMapperConsumer.html" target="_top">Frames</a></li> <li><a href="CustomRealmMapperConsumer.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">org.wildfly.swarm.config.elytron</div> <h2 title="Interface CustomRealmMapperConsumer" class="title">Interface CustomRealmMapperConsumer&lt;T extends <a href="../../../../../org/wildfly/swarm/config/elytron/CustomRealmMapper.html" title="class in org.wildfly.swarm.config.elytron">CustomRealmMapper</a>&lt;T&gt;&gt;</h2> </div> <div class="contentContainer"> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>Functional Interface:</dt> <dd>This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.</dd> </dl> <hr> <br> <pre><a href="http://docs.oracle.com/javase/8/docs/api/java/lang/FunctionalInterface.html?is-external=true" title="class or interface in java.lang">@FunctionalInterface</a> public interface <span class="typeNameLabel">CustomRealmMapperConsumer&lt;T extends <a href="../../../../../org/wildfly/swarm/config/elytron/CustomRealmMapper.html" title="class in org.wildfly.swarm.config.elytron">CustomRealmMapper</a>&lt;T&gt;&gt;</span></pre> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method.summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd">&nbsp;</span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t3" class="tableTab"><span><a href="javascript:show(4);">Abstract Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t5" class="tableTab"><span><a href="javascript:show(16);">Default Methods</a></span><span class="tabEnd">&nbsp;</span></span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr id="i0" class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/wildfly/swarm/config/elytron/CustomRealmMapperConsumer.html#accept-T-">accept</a></span>(<a href="../../../../../org/wildfly/swarm/config/elytron/CustomRealmMapperConsumer.html" title="type parameter in CustomRealmMapperConsumer">T</a>&nbsp;value)</code> <div class="block">Configure a pre-constructed instance of CustomRealmMapper resource</div> </td> </tr> <tr id="i1" class="rowColor"> <td class="colFirst"><code>default <a href="../../../../../org/wildfly/swarm/config/elytron/CustomRealmMapperConsumer.html" title="interface in org.wildfly.swarm.config.elytron">CustomRealmMapperConsumer</a>&lt;<a href="../../../../../org/wildfly/swarm/config/elytron/CustomRealmMapperConsumer.html" title="type parameter in CustomRealmMapperConsumer">T</a>&gt;</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/wildfly/swarm/config/elytron/CustomRealmMapperConsumer.html#andThen-org.wildfly.swarm.config.elytron.CustomRealmMapperConsumer-">andThen</a></span>(<a href="../../../../../org/wildfly/swarm/config/elytron/CustomRealmMapperConsumer.html" title="interface in org.wildfly.swarm.config.elytron">CustomRealmMapperConsumer</a>&lt;<a href="../../../../../org/wildfly/swarm/config/elytron/CustomRealmMapperConsumer.html" title="type parameter in CustomRealmMapperConsumer">T</a>&gt;&nbsp;after)</code>&nbsp;</td> </tr> </table> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method.detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="accept-org.wildfly.swarm.config.elytron.CustomRealmMapper-"> <!-- --> </a><a name="accept-T-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>accept</h4> <pre>void&nbsp;accept(<a href="../../../../../org/wildfly/swarm/config/elytron/CustomRealmMapperConsumer.html" title="type parameter in CustomRealmMapperConsumer">T</a>&nbsp;value)</pre> <div class="block">Configure a pre-constructed instance of CustomRealmMapper resource</div> </li> </ul> <a name="andThen-org.wildfly.swarm.config.elytron.CustomRealmMapperConsumer-"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>andThen</h4> <pre>default&nbsp;<a href="../../../../../org/wildfly/swarm/config/elytron/CustomRealmMapperConsumer.html" title="interface in org.wildfly.swarm.config.elytron">CustomRealmMapperConsumer</a>&lt;<a href="../../../../../org/wildfly/swarm/config/elytron/CustomRealmMapperConsumer.html" title="type parameter in CustomRealmMapperConsumer">T</a>&gt;&nbsp;andThen(<a href="../../../../../org/wildfly/swarm/config/elytron/CustomRealmMapperConsumer.html" title="interface in org.wildfly.swarm.config.elytron">CustomRealmMapperConsumer</a>&lt;<a href="../../../../../org/wildfly/swarm/config/elytron/CustomRealmMapperConsumer.html" title="type parameter in CustomRealmMapperConsumer">T</a>&gt;&nbsp;after)</pre> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/CustomRealmMapperConsumer.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage">Thorntail API, 2.1.0.Final</div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../org/wildfly/swarm/config/elytron/CustomRealmMapper.html" title="class in org.wildfly.swarm.config.elytron"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../../../org/wildfly/swarm/config/elytron/CustomRealmMapperSupplier.html" title="interface in org.wildfly.swarm.config.elytron"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/wildfly/swarm/config/elytron/CustomRealmMapperConsumer.html" target="_top">Frames</a></li> <li><a href="CustomRealmMapperConsumer.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2018 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p> </body> </html>
wildfly-swarm/wildfly-swarm-javadocs
2.1.0.Final/apidocs/org/wildfly/swarm/config/elytron/CustomRealmMapperConsumer.html
HTML
apache-2.0
11,498
package com.morgan.design.activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.database.DataSetObserver; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnKeyListener; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.google.common.base.Strings; import com.morgan.design.R; import com.morgan.design.TeaApplication; import com.morgan.design.adaptor.PlayerAdaptor; import com.morgan.design.db.domain.BrewGroup; import com.morgan.design.db.domain.BrewPlayer; import com.morgan.design.dialog.fragment.ManageGroupDialogFragment; import com.morgan.design.dialog.fragment.ManageGroupDialogFragment.ManageGroupDialogFragmentActions; import com.morgan.design.helpers.ContactsLoader; import com.morgan.design.utils.Prefs; import com.morgan.design.utils.StringUtils; import com.morgan.design.utils.Utils; import java.util.ArrayList; import java.util.Collection; import static com.morgan.design.utils.ObjectUtils.isNotNull; public class TeaRoundHomeActivity extends BaseBrewFragmentActivity implements ManageGroupDialogFragmentActions { private AutoCompleteTextView addPlayerEditText; private Button runTeaRoundButton; private TextView playerDetailHeader; private ListView playersListAdapter; private PlayerAdaptor playerAdaptor; private BrewGroup brewGroup; private Collection<BrewPlayer> brewPlayers; private DataSetObserver dataSetObserver; @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.tea_round_home); findAllViewsById(); // Bind focus listener to attach to add player text box addPlayerEditText.setOnKeyListener(new EnterPlayerClickListener()); // Load the Contact Name from List into the AutoCompleteTextView addPlayerEditText.setAdapter(new ArrayAdapter<String>(getApplicationContext(), R.layout.single_contact_view, R.id.single_contact_view_name, ContactsLoader.getAllContactNames(getContentResolver()))); playerAdaptor = new PlayerAdaptor(this, new ArrayList<BrewPlayer>(), new TrashClickHandler()); dataSetObserver = new DataSetObserver() { @Override public void onChanged() { super.onChanged(); enableDisableButtonRunTeaRound(); setPlayerDetailHeader(); } }; playerAdaptor.registerDataSetObserver(dataSetObserver); playersListAdapter.setAdapter(playerAdaptor); final Bundle bundle = getIntent().getExtras(); if (isNotNull(bundle)) { final Integer groupId = bundle.getInt(TeaApplication.GROUP_ID); if (null != groupId) { loadGroup(groupId); } } else { loadLastRunPlayers(); } } @Override public void onDestroy() { super.onDestroy(); playerAdaptor.unregisterDataSetObserver(dataSetObserver); } @Override public boolean onPrepareOptionsMenu(final Menu menu) { menu.clear(); final MenuInflater inflater = getMenuInflater(); if (null != brewGroup) { inflater.inflate(R.menu.brew_round_menu_edit_group, menu); } else { inflater.inflate(R.menu.brew_round_menu_add_group, menu); } return true; } @Override public boolean onOptionsItemSelected(final MenuItem item) { switch (item.getItemId()) { case R.id.br_manage_groups: final Intent intent = new Intent(this, DashboardFragmentActivity.class); intent.putExtra(TeaApplication.EXTRA_DASHBOARD_VIEW, DashboardFragmentActivity.DASHBOARD_GROUPS); startActivityForResult(intent, TeaApplication.ACTIVITY_GROUP); return true; case R.id.br_credits: Utils.openCredits(this); return true; case R.id.br_feedback: Utils.openFeedback(this); return true; case R.id.br_settings: Prefs.openPreferenecesActivity(this); return true; case R.id.br_add_group: if (validNumberOfPlayers()) { showManageGroupDialog(false); } else { shortToast("Not enough players, minimum 2!"); } return true; case R.id.br_edit_group: if (validNumberOfPlayers()) { showManageGroupDialog(true); } return true; default: return super.onOptionsItemSelected(item); } } @Override protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) { // See which child activity is calling us back. switch (requestCode) { case TeaApplication.ACTIVITY_RUNNING: { if (resultCode == RESULT_OK) { final Intent resultsIntent = new Intent(this, TeaRoundResultsActivity.class); final ArrayList<Integer> playerIds = new ArrayList<Integer>(); for (final BrewPlayer player : brewPlayers) { playerIds.add(player.getId()); } final Bundle bundle = new Bundle(); bundle.putIntegerArrayList(TeaApplication.PLAYER_IDS, playerIds); resultsIntent.putExtras(bundle); startActivityForResult(resultsIntent, TeaApplication.ACTIVITY_RESULTS); } break; } case TeaApplication.ACTIVITY_RESULTS: { if (resultCode == RESULT_OK) { loadLastRunPlayers(); } break; } case TeaApplication.ACTIVITY_GROUP: { if (resultCode == RESULT_OK) { final Integer groupId = data.getIntExtra(TeaApplication.GROUP_ID, 0); if (0 != groupId && null != groupId) { loadGroup(groupId); } } break; } default: break; } } public void enableDisableButtonRunTeaRound() { runTeaRoundButton.setEnabled(validNumberOfPlayers()); } private void clearBrewBroupIfRequired() { if (playerAdaptor.isEmpty() && null != brewGroup) { brewGroup = null; } } public void onAddPlayer(final View view) { addPlayer(); } public void onRunTeaRound(final View view) { runTeaRound(); } public void setPlayerDetailHeader() { final StringBuilder builder = new StringBuilder(); if (playerAdaptor.isEmpty()) { builder.append(getResources().getString(R.string.no_players)); } else { builder.append("Players(" + playerAdaptor.getCount() + ")"); if (null != brewGroup && StringUtils.isNotBlank(brewGroup.getName())) { builder.append(" | Group: ").append(brewGroup.getName()); } } playerDetailHeader.setText(builder.toString()); } private void addPlayer() { final String playerName = addPlayerEditText.getText().toString(); if (notNullEmpyOrValue(playerName, R.string.add_player)) { shortToast("Invalid player name"); return; } final BrewPlayer player = new BrewPlayer(); player.setName(playerName); if (!checkAlreadyPlaying(player)) { log.debug("Added player, name: {}", player.getName()); brewPlayers.add(player); playerAdaptor.add(player); addPlayerEditText.setText(""); addPlayerEditText.clearComposingText(); addPlayerEditText.requestFocus(); // TODO set brew group if present getBrewRepository().saveBrewPlayer(player); } else { shortToast(player.getName() + " already playing"); log.debug("{} already playing", player.getName()); } enableDisableButtonRunTeaRound(); setPlayerDetailHeader(); } private boolean checkAlreadyPlaying(final BrewPlayer player) { if (null == brewPlayers) { return false; } for (final BrewPlayer existingPlayer : brewPlayers) { if (existingPlayer.getName().equals(player.getName())) { return true; } } return false; } private void findAllViewsById() { playerDetailHeader = (TextView) findViewById(R.id.player_detail_header); addPlayerEditText = (AutoCompleteTextView) findViewById(R.id.add_player_text); runTeaRoundButton = (Button) findViewById(R.id.run_tea_round); playersListAdapter = (ListView) findViewById(R.id.players_list_adator); } private void loadGroup(final Integer groupId) { brewGroup = getBrewRepository().findGroupById(groupId); if (null != brewGroup) { brewPlayers = brewGroup.getBrewPlayers(); playerAdaptor.clear(); for (final BrewPlayer player : brewGroup.getBrewPlayers()) { playerAdaptor.add(player); } } setPlayerDetailHeader(); enableDisableButtonRunTeaRound(); } private void loadLastRunPlayers() { brewPlayers = getBrewRepository().findLastRunPlayers(); if (null != brewPlayers && !brewPlayers.isEmpty() && null != brewPlayers.iterator().next().getBrewGroup()) { brewGroup = brewPlayers.iterator().next().getBrewGroup(); } if (brewPlayers != null && !brewPlayers.isEmpty()) { playerAdaptor.clear(); for (final BrewPlayer player : brewPlayers) { playerAdaptor.add(player); } } // Set no players enableDisableButtonRunTeaRound(); setPlayerDetailHeader(); } private boolean notNullEmpyOrValue(final String value, final int resource) { return Strings.isNullOrEmpty(value) || getResources().getString(resource).equals(value); } private void runTeaRound() { final Intent splash = new Intent(this, TeaRoundRunningActivity.class); startActivityForResult(splash, TeaApplication.ACTIVITY_RUNNING); } private void showManageGroupDialog(final boolean editing) { FragmentManager fm = getSupportFragmentManager(); ManageGroupDialogFragment editNameDialog = new ManageGroupDialogFragment(this); Bundle bundle = new Bundle(); bundle.putBoolean(ManageGroupDialogFragment.EDIT_MODE, editing); if (editing) { bundle.putString(ManageGroupDialogFragment.BREW_GROUP_NAME, brewGroup.getName()); } editNameDialog.setArguments(bundle); editNameDialog.show(fm, ManageGroupDialogFragment.TAG); } @Override public void createBrewGroup(final String groupName) { if (notNullEmpyOrValue(groupName, R.string.group_management)) { shortToast("Invalid Group Name"); return; } brewGroup = getBrewRepository().saveGroup(groupName, brewPlayers); shortToast("Created Group: " + groupName); setPlayerDetailHeader(); } @Override public void updateBrewGroup(final String groupName) { brewGroup.setName(groupName); getBrewRepository().updateGroup(brewGroup); shortToast("Updated Group: " + groupName); } private boolean validNumberOfPlayers() { return playerAdaptor.getCount() >= 2; } public class TrashClickHandler implements OnClickListener { @Override public void onClick(final View v) { final Integer position = (Integer) v.getTag(); log.debug("Trash clicked, position {}", position); final BrewPlayer player = playerAdaptor.getItem(position); if (0 != player.getId()) { final AlertDialog.Builder builder = new AlertDialog.Builder(TeaRoundHomeActivity.this); builder.setMessage("Click 'Remove' to remove from this game, 'Delete' to delete completely").setCancelable(true) .setPositiveButton("Remove", new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface dialog, final int id) { removeFromGame(player, position); } }).setNegativeButton("Delete", new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface dialog, final int id) { deletePlayer(player, position); } }).create().show(); } else { removeFromGame(player, position); } } } private void deletePlayer(final BrewPlayer player, final int playerPosition) { shortToast("Deleted " + player.getName() + " from game"); playerAdaptor.remove(player); getBrewRepository().deletePlayer(player); getBrewRepository().removePlayerStats(player); clearBrewBroupIfRequired(); } private void removeFromGame(final BrewPlayer player, final int playerPosition) { shortToast("Removed " + player.getName() + " from game"); playerAdaptor.remove(player); clearBrewBroupIfRequired(); } @Override public void shortToast(final CharSequence message) { Toast.makeText(this, message, Toast.LENGTH_SHORT).show(); } private class EnterPlayerClickListener implements OnKeyListener { @Override public boolean onKey(final View v, final int keyCode, final KeyEvent event) { if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { addPlayer(); addPlayerEditText.setFocusableInTouchMode(true); addPlayerEditText.requestFocusFromTouch(); addPlayerEditText.setSelected(true); return true; } return false; } } }
jamesmorgan/WhosMakingTheBrew
src/com/morgan/design/activity/TeaRoundHomeActivity.java
Java
apache-2.0
14,803
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_151) on Mon Jan 15 08:36:51 MST 2018 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Uses of Class org.wildfly.swarm.config.elytron.AuthenticationConfiguration.ForwardingMode (BOM: * : All 2018.1.0 API)</title> <meta name="date" content="2018-01-15"> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.wildfly.swarm.config.elytron.AuthenticationConfiguration.ForwardingMode (BOM: * : All 2018.1.0 API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../org/wildfly/swarm/config/elytron/AuthenticationConfiguration.ForwardingMode.html" title="enum in org.wildfly.swarm.config.elytron">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../../../overview-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage">WildFly Swarm API, 2018.1.0</div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/wildfly/swarm/config/elytron/class-use/AuthenticationConfiguration.ForwardingMode.html" target="_top">Frames</a></li> <li><a href="AuthenticationConfiguration.ForwardingMode.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.wildfly.swarm.config.elytron.AuthenticationConfiguration.ForwardingMode" class="title">Uses of Class<br>org.wildfly.swarm.config.elytron.AuthenticationConfiguration.ForwardingMode</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../../org/wildfly/swarm/config/elytron/AuthenticationConfiguration.ForwardingMode.html" title="enum in org.wildfly.swarm.config.elytron">AuthenticationConfiguration.ForwardingMode</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#org.wildfly.swarm.config.elytron">org.wildfly.swarm.config.elytron</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="org.wildfly.swarm.config.elytron"> <!-- --> </a> <h3>Uses of <a href="../../../../../../org/wildfly/swarm/config/elytron/AuthenticationConfiguration.ForwardingMode.html" title="enum in org.wildfly.swarm.config.elytron">AuthenticationConfiguration.ForwardingMode</a> in <a href="../../../../../../org/wildfly/swarm/config/elytron/package-summary.html">org.wildfly.swarm.config.elytron</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../../org/wildfly/swarm/config/elytron/package-summary.html">org.wildfly.swarm.config.elytron</a> that return <a href="../../../../../../org/wildfly/swarm/config/elytron/AuthenticationConfiguration.ForwardingMode.html" title="enum in org.wildfly.swarm.config.elytron">AuthenticationConfiguration.ForwardingMode</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../../org/wildfly/swarm/config/elytron/AuthenticationConfiguration.ForwardingMode.html" title="enum in org.wildfly.swarm.config.elytron">AuthenticationConfiguration.ForwardingMode</a></code></td> <td class="colLast"><span class="typeNameLabel">AuthenticationConfiguration.</span><code><span class="memberNameLink"><a href="../../../../../../org/wildfly/swarm/config/elytron/AuthenticationConfiguration.html#forwardingMode--">forwardingMode</a></span>()</code> <div class="block">The type of security identity forwarding to use.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static <a href="../../../../../../org/wildfly/swarm/config/elytron/AuthenticationConfiguration.ForwardingMode.html" title="enum in org.wildfly.swarm.config.elytron">AuthenticationConfiguration.ForwardingMode</a></code></td> <td class="colLast"><span class="typeNameLabel">AuthenticationConfiguration.ForwardingMode.</span><code><span class="memberNameLink"><a href="../../../../../../org/wildfly/swarm/config/elytron/AuthenticationConfiguration.ForwardingMode.html#valueOf-java.lang.String-">valueOf</a></span>(<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>&nbsp;name)</code> <div class="block">Returns the enum constant of this type with the specified name.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static <a href="../../../../../../org/wildfly/swarm/config/elytron/AuthenticationConfiguration.ForwardingMode.html" title="enum in org.wildfly.swarm.config.elytron">AuthenticationConfiguration.ForwardingMode</a>[]</code></td> <td class="colLast"><span class="typeNameLabel">AuthenticationConfiguration.ForwardingMode.</span><code><span class="memberNameLink"><a href="../../../../../../org/wildfly/swarm/config/elytron/AuthenticationConfiguration.ForwardingMode.html#values--">values</a></span>()</code> <div class="block">Returns an array containing the constants of this enum type, in the order they are declared.</div> </td> </tr> </tbody> </table> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../../org/wildfly/swarm/config/elytron/package-summary.html">org.wildfly.swarm.config.elytron</a> with parameters of type <a href="../../../../../../org/wildfly/swarm/config/elytron/AuthenticationConfiguration.ForwardingMode.html" title="enum in org.wildfly.swarm.config.elytron">AuthenticationConfiguration.ForwardingMode</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../../org/wildfly/swarm/config/elytron/AuthenticationConfiguration.html" title="type parameter in AuthenticationConfiguration">T</a></code></td> <td class="colLast"><span class="typeNameLabel">AuthenticationConfiguration.</span><code><span class="memberNameLink"><a href="../../../../../../org/wildfly/swarm/config/elytron/AuthenticationConfiguration.html#forwardingMode-org.wildfly.swarm.config.elytron.AuthenticationConfiguration.ForwardingMode-">forwardingMode</a></span>(<a href="../../../../../../org/wildfly/swarm/config/elytron/AuthenticationConfiguration.ForwardingMode.html" title="enum in org.wildfly.swarm.config.elytron">AuthenticationConfiguration.ForwardingMode</a>&nbsp;value)</code> <div class="block">The type of security identity forwarding to use.</div> </td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../org/wildfly/swarm/config/elytron/AuthenticationConfiguration.ForwardingMode.html" title="enum in org.wildfly.swarm.config.elytron">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../../../overview-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage">WildFly Swarm API, 2018.1.0</div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/wildfly/swarm/config/elytron/class-use/AuthenticationConfiguration.ForwardingMode.html" target="_top">Frames</a></li> <li><a href="AuthenticationConfiguration.ForwardingMode.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2018 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p> </body> </html>
wildfly-swarm/wildfly-swarm-javadocs
2018.1.0/apidocs/org/wildfly/swarm/config/elytron/class-use/AuthenticationConfiguration.ForwardingMode.html
HTML
apache-2.0
10,798
package com.fishercoder.solutions; import java.util.ArrayList; import java.util.List; public class _294 { public static class Solution1 { public boolean canWin(String s) { List<String> res = new ArrayList<>(); char[] charArray = s.toCharArray(); for (int i = 0; i < s.length() - 1; i++) { if (charArray[i] == '+' && charArray[i + 1] == '+') { //change these two bits to '-' charArray[i] = '-'; charArray[i + 1] = '-'; res.add(String.valueOf(charArray)); //change these two bits back to '+' for its next move charArray[i] = '+'; charArray[i + 1] = '+'; } } /**The above part is the same of Flip Game I. * The only added part is the following piece of logic (so-called backtracking.)*/ for (String str : res) { if (!canWin(str)) { return true; } } return false; } } }
fishercoder1534/Leetcode
src/main/java/com/fishercoder/solutions/_294.java
Java
apache-2.0
1,127
<table border='1'> <tr> <th>Class name</th> <th>Method name</th> <th>Groups</th> </tr><tr> <td>parallel.test1</td> <td>&nbsp;</td><td>&nbsp;</td></tr> <tr> <td align='center' colspan='3'>@Test</td> </tr> <tr> <td>&nbsp;</td> <td>f</td> <td>&nbsp;</td></tr> <tr> <td align='center' colspan='3'>@BeforeClass</td> </tr> <tr> <td align='center' colspan='3'>@BeforeMethod</td> </tr> <tr> <td align='center' colspan='3'>@AfterMethod</td> </tr> <tr> <td align='center' colspan='3'>@AfterClass</td> </tr> <tr> <td>parallel.test2</td> <td>&nbsp;</td><td>&nbsp;</td></tr> <tr> <td align='center' colspan='3'>@Test</td> </tr> <tr> <td>&nbsp;</td> <td>f</td> <td>&nbsp;</td></tr> <tr> <td align='center' colspan='3'>@BeforeClass</td> </tr> <tr> <td align='center' colspan='3'>@BeforeMethod</td> </tr> <tr> <td align='center' colspan='3'>@AfterMethod</td> </tr> <tr> <td align='center' colspan='3'>@AfterClass</td> </tr> </table>
dagiguevara/seleniumTests
test-output/old/aqua gem parallel/classes.html
HTML
apache-2.0
917
package com.SqsHipchatRouter; import java.util.HashMap; import java.util.Map; /** * Created by marlow on 10/5/15. */ public class SqsHipchatRouterConst { public static final String AWS_ACCOUNT_NUMBER = "999999999999"; public static final String SQS_BASE_URL = "https://queue.amazonaws.com/" + AWS_ACCOUNT_NUMBER + "/"; public static String AWS_SQS_PREFIX = SQS_BASE_URL + "hipchat-"; public enum MessageQueues {Q1, Q2, Q3, Q4}; public final static Map<MessageQueues, String> roomNames = new HashMap<>(); public final static Map<MessageQueues, String> queueNames = new HashMap<>(); static { roomNames.put(MessageQueues.Q1, "Room1"); roomNames.put(MessageQueues.Q2, "Room2"); roomNames.put(MessageQueues.Q3, "Room3"); roomNames.put(MessageQueues.Q4, "Room4"); queueNames.put(MessageQueues.Q1, "Q1"); queueNames.put(MessageQueues.Q1, "Q2"); queueNames.put(MessageQueues.Q1, "Q3"); queueNames.put(MessageQueues.Q1, "Q4"); } }
catblade/SqsHipchatRouter
src/main/java/com/SqsHipchatRouter/SqsHipchatRouterConst.java
Java
apache-2.0
1,028
// stdafx.h : include file for standard system include files, // or project specific include files that are used frequently, but // are changed infrequently // #pragma once #include "targetver.h" #include <stdio.h> #include <tchar.h> #include <list> #include <fstream> using namespace std; static const double Pi = 3.14159265358979323846264338327950288419716939937511; const char* Ttc(const _TCHAR* str); // TODO: reference additional headers your program requires here
JohnyEngine/CNC
libarea/pocket/stdafx.h
C
apache-2.0
478
////////////////////////////////////////////////////////// // This class has been automatically generated on // Tue Sep 27 10:49:47 2011 by ROOT version 4.00/08 // from TChain Photon/ ////////////////////////////////////////////////////////// #ifndef ydarkp_h #define ydarkp_h #include <TROOT.h> #include <TChain.h> #include <TFile.h> class ydarkp { public : TTree *fChain; //!pointer to the analyzed TTree or TChain Int_t fCurrent; //!current Tree number in a TChain // Declaration of leave types Int_t ph_Npho; Float_t ph_E[3]; //[ph_Npho] Float_t ph_Et[3]; //[ph_Npho] Float_t ph_Etc[3]; //[ph_Npho] Float_t ph_Cesx[3]; //[ph_Npho] Float_t ph_Cesz[3]; //[ph_Npho] Float_t ph_Deta[3]; //[ph_Npho] Float_t ph_Eta[3]; //[ph_Npho] Float_t ph_Phi[3]; //[ph_Npho] Float_t ph_SinTheta[3]; //[ph_Npho] Int_t ph_N3d[3]; //[ph_Npho] Float_t ph_Chi2[3]; //[ph_Npho] Float_t ph_NIsoTrk[3]; //[ph_Npho] Float_t ph_Pt[3]; //[ph_Npho] Float_t ph_Tiso[3]; //[ph_Npho] Int_t e_NElectrons; Int_t e_Good[7]; //[e_NElectrons] Float_t e_TotalEt[7]; //[e_NElectrons] Float_t e_Et[7]; //[e_NElectrons] Float_t e_E[7]; //[e_NElectrons] Float_t e_TrackPt[7]; //[e_NElectrons] Float_t e_Nasl[7]; //[e_NElectrons] Float_t e_Nssl[7]; //[e_NElectrons] Float_t e_HadEm[7]; //[e_NElectrons] Float_t e_Iso[7]; //[e_NElectrons] Float_t e_Lshr[7]; //[e_NElectrons] Float_t e_EP[7]; //[e_NElectrons] Float_t e_DelXQ[7]; //[e_NElectrons] Float_t e_DelZ[7]; //[e_NElectrons] Float_t e_Z0[7]; //[e_NElectrons] Float_t e_Chi2Strip[7]; //[e_NElectrons] Int_t e_DetectorCode; Int_t e_TrackNumber; Float_t e_ClusterEmEt[7]; //[e_NElectrons] Float_t e_ClusterHadEt[7]; //[e_NElectrons] Float_t e_Charge[7]; //[e_NElectrons] Float_t e_TrackEta[7]; //[e_NElectrons] Float_t e_TrackPhi[7]; //[e_NElectrons] Float_t e_TrackPhi2[7]; //[e_NElectrons] Float_t e_Px[7]; //[e_NElectrons] Float_t e_Py[7]; //[e_NElectrons] Float_t e_Pz[7]; //[e_NElectrons] Float_t e_P0[7]; //[e_NElectrons] Int_t eb_NPositrons; Int_t eb_Good[10]; //[eb_NPositrons] Float_t eb_TotalEt[10]; //[eb_NPositrons] Float_t eb_Et[10]; //[eb_NPositrons] Float_t eb_E[10]; //[eb_NPositrons] Float_t eb_TrackPt[10]; //[eb_NPositrons] Float_t eb_Nasl[10]; //[eb_NPositrons] Float_t eb_Nssl[10]; //[eb_NPositrons] Float_t eb_HadEm[10]; //[eb_NPositrons] Float_t eb_Iso[10]; //[eb_NPositrons] Float_t eb_Lshr[10]; //[eb_NPositrons] Float_t eb_EP[10]; //[eb_NPositrons] Float_t eb_DelXQ[10]; //[eb_NPositrons] Float_t eb_DelZ[10]; //[eb_NPositrons] Float_t eb_Z0[10]; //[eb_NPositrons] Float_t eb_Chi2Strip[10]; //[eb_NPositrons] Int_t eb_DetectorCode; Int_t eb_TrackNumber; Float_t eb_ClusterEmEt[10]; //[eb_NPositrons] Float_t eb_ClusterHadEt[10]; //[eb_NPositrons] Float_t eb_Charge[10]; //[eb_NPositrons] Float_t eb_TrackEta[10]; //[eb_NPositrons] Float_t eb_TrackPhi[10]; //[eb_NPositrons] Float_t eb_TrackPhi2[10]; //[eb_NPositrons] Float_t eb_Px[10]; //[eb_NPositrons] Float_t eb_Py[10]; //[eb_NPositrons] Float_t eb_Pz[10]; //[eb_NPositrons] Float_t eb_P0[10]; //[eb_NPositrons] Int_t m_NMuons; Int_t m_Good[11]; //[m_NMuons] Int_t m_TrackNumber[11]; //[m_NMuons] Int_t m_NCmuHits[11]; //[m_NMuons] Int_t m_NCmpHits[11]; //[m_NMuons] Int_t m_NCmxHits[11]; //[m_NMuons] Int_t m_NBmuHits[11]; //[m_NMuons] Float_t m_TrackPt[11]; //[m_NMuons] Float_t m_Iso[11]; //[m_NMuons] Float_t m_CmuDelX[11]; //[m_NMuons] Float_t m_CmpDelX[11]; //[m_NMuons] Float_t m_CmxDelX[11]; //[m_NMuons] Float_t m_BmuDelX[11]; //[m_NMuons] Float_t m_HasCmuStub[11]; //[m_NMuons] Float_t m_HasCmpStub[11]; //[m_NMuons] Float_t m_HasCmxStub[11]; //[m_NMuons] Float_t m_HasBmuStub[11]; //[m_NMuons] Float_t m_TrackBcPt[11]; //[m_NMuons] Float_t m_EmEnergy[11]; //[m_NMuons] Float_t m_HadEnergy[11]; //[m_NMuons] Float_t m_Z0[11]; //[m_NMuons] Float_t m_D0[11]; //[m_NMuons] Float_t m_mupt[11]; //[m_NMuons] Int_t m_NSvxHits[11]; //[m_NMuons] Float_t m_d0Corr[11]; //[m_NMuons] Float_t m_Charge[11]; //[m_NMuons] Float_t m_TrackEta[11]; //[m_NMuons] Float_t m_TrackPhi[11]; //[m_NMuons] Float_t m_TrackPhi2[11]; //[m_NMuons] Float_t m_Px[11]; //[m_NMuons] Float_t m_Py[11]; //[m_NMuons] Float_t m_Pz[11]; //[m_NMuons] Float_t m_P0[11]; //[m_NMuons] Int_t mb_NAMuons; Int_t mb_Good[13]; //[mb_NAMuons] Int_t mb_TrackNumber[13]; //[mb_NAMuons] Int_t mb_NCmuHits[13]; //[mb_NAMuons] Int_t mb_NCmpHits[13]; //[mb_NAMuons] Int_t mb_NCmxHits[13]; //[mb_NAMuons] Int_t mb_NBmuHits[13]; //[mb_NAMuons] Float_t mb_TrackPt[13]; //[mb_NAMuons] Float_t mb_Iso[13]; //[mb_NAMuons] Float_t mb_CmuDelX[13]; //[mb_NAMuons] Float_t mb_CmpDelX[13]; //[mb_NAMuons] Float_t mb_CmxDelX[13]; //[mb_NAMuons] Float_t mb_BmuDelX[13]; //[mb_NAMuons] Float_t mb_HasCmuStub[13]; //[mb_NAMuons] Float_t mb_HasCmpStub[13]; //[mb_NAMuons] Float_t mb_HasCmxStub[13]; //[mb_NAMuons] Float_t mb_HasBmuStub[13]; //[mb_NAMuons] Float_t mb_TrackBcPt[13]; //[mb_NAMuons] Float_t mb_EmEnergy[13]; //[mb_NAMuons] Float_t mb_HadEnergy[13]; //[mb_NAMuons] Float_t mb_Z0[13]; //[mb_NAMuons] Float_t mb_D0[13]; //[mb_NAMuons] Float_t mb_mupt[11]; //[m_NMuons] Int_t mb_NSvxHits[11]; //[m_NMuons] Float_t mb_d0Corr[11]; //[m_NMuons] Float_t mb_Charge[13]; //[mb_NAMuons] Float_t mb_TrackEta[13]; //[mb_NAMuons] Float_t mb_TrackPhi[13]; //[mb_NAMuons] Float_t mb_TrackPhi2[13]; //[mb_NAMuons] Float_t mb_Px[13]; //[mb_NAMuons] Float_t mb_Py[13]; //[mb_NAMuons] Float_t mb_Pz[13]; //[mb_NAMuons] Float_t mb_P0[13]; //[mb_NAMuons] Float_t mi_Met; Float_t mi_MetPhi; Float_t mi_Ht; Float_t mi_HtCorr; // List of branches TBranch *b_ph_Npho; //! TBranch *b_ph_E; //! TBranch *b_ph_Et; //! TBranch *b_ph_Etc; //! TBranch *b_ph_Cesx; //! TBranch *b_ph_Cesz; //! TBranch *b_ph_Deta; //! TBranch *b_ph_Eta; //! TBranch *b_ph_Phi; //! TBranch *b_ph_SinTheta; //! TBranch *b_ph_N3d; //! TBranch *b_ph_Chi2; //! TBranch *b_ph_NIsoTrk; //! TBranch *b_ph_Pt; //! TBranch *b_ph_Tiso; //! TBranch *b_e_NElectrons; //! TBranch *b_e_Good; //! TBranch *b_e_TotalEt; //! TBranch *b_e_Et; //! TBranch *b_e_E; //! TBranch *b_e_TrackPt; //! TBranch *b_e_Nasl; //! TBranch *b_e_Nssl; //! TBranch *b_e_HadEm; //! TBranch *b_e_Iso; //! TBranch *b_e_Lshr; //! TBranch *b_e_EP; //! TBranch *b_e_DelXQ; //! TBranch *b_e_DelZ; //! TBranch *b_e_Z0; //! TBranch *b_e_Chi2Strip; //! TBranch *b_e_DetectorCode; //! TBranch *b_e_TrackNumber; //! TBranch *b_e_ClusterEmEt; //! TBranch *b_e_ClusterHadEt; //! TBranch *b_e_Charge; //! TBranch *b_e_TrackEta; //! TBranch *b_e_TrackPhi; //! TBranch *b_e_TrackPhi2; //! TBranch *b_e_Px; //! TBranch *b_e_Py; //! TBranch *b_e_Pz; //! TBranch *b_e_P0; //! TBranch *b_eb_NPositrons; //! TBranch *b_eb_Good; //! TBranch *b_eb_TotalEt; //! TBranch *b_eb_Et; //! TBranch *b_eb_E; //! TBranch *b_eb_TrackPt; //! TBranch *b_eb_Nasl; //! TBranch *b_eb_Nssl; //! TBranch *b_eb_HadEm; //! TBranch *b_eb_Iso; //! TBranch *b_eb_Lshr; //! TBranch *b_eb_EP; //! TBranch *b_eb_DelXQ; //! TBranch *b_eb_DelZ; //! TBranch *b_eb_Z0; //! TBranch *b_eb_Chi2Strip; //! TBranch *b_eb_DetectorCode; //! TBranch *b_eb_TrackNumber; //! TBranch *b_eb_ClusterEmEt; //! TBranch *b_eb_ClusterHadEt; //! TBranch *b_eb_Charge; //! TBranch *b_eb_TrackEta; //! TBranch *b_eb_TrackPhi; //! TBranch *b_eb_TrackPhi2; //! TBranch *b_eb_Px; //! TBranch *b_eb_Py; //! TBranch *b_eb_Pz; //! TBranch *b_eb_P0; //! TBranch *b_m_NMuons; //! TBranch *b_m_Good; //! TBranch *b_m_TrackNumber; //! TBranch *b_m_NCmuHits; //! TBranch *b_m_NCmpHits; //! TBranch *b_m_NCmxHits; //! TBranch *b_m_NBmuHits; //! TBranch *b_m_TrackPt; //! TBranch *b_m_Iso; //! TBranch *b_m_CmuDelX; //! TBranch *b_m_CmpDelX; //! TBranch *b_m_CmxDelX; //! TBranch *b_m_BmuDelX; //! TBranch *b_m_HasCmuStub; //! TBranch *b_m_HasCmpStub; //! TBranch *b_m_HasCmxStub; //! TBranch *b_m_HasBmuStub; //! TBranch *b_m_TrackBcPt; //! TBranch *b_m_EmEnergy; //! TBranch *b_m_HadEnergy; //! TBranch *b_m_Z0; //! TBranch *b_m_D0; //! TBranch *b_m_mupt; //! TBranch *b_m_NSvxHits; //! TBranch *b_m_d0Corr; //! TBranch *b_m_Charge; //! TBranch *b_m_TrackEta; //! TBranch *b_m_TrackPhi; //! TBranch *b_m_TrackPhi2; //! TBranch *b_m_Px; //! TBranch *b_m_Py; //! TBranch *b_m_Pz; //! TBranch *b_m_P0; //! TBranch *b_mb_NAMuons; //! TBranch *b_mb_Good; //! TBranch *b_mb_TrackNumber; //! TBranch *b_mb_NCmuHits; //! TBranch *b_mb_NCmpHits; //! TBranch *b_mb_NCmxHits; //! TBranch *b_mb_NBmuHits; //! TBranch *b_mb_TrackPt; //! TBranch *b_mb_Iso; //! TBranch *b_mb_CmuDelX; //! TBranch *b_mb_CmpDelX; //! TBranch *b_mb_CmxDelX; //! TBranch *b_mb_BmuDelX; //! TBranch *b_mb_HasCmuStub; //! TBranch *b_mb_HasCmpStub; //! TBranch *b_mb_HasCmxStub; //! TBranch *b_mb_HasBmuStub; //! TBranch *b_mb_TrackBcPt; //! TBranch *b_mb_EmEnergy; //! TBranch *b_mb_HadEnergy; //! TBranch *b_mb_Z0; //! TBranch *b_mb_D0; //! TBranch *b_mb_mupt; //! TBranch *b_mb_NSvxHits; //! TBranch *b_mb_d0Corr; //! TBranch *b_mb_Charge; //! TBranch *b_mb_TrackEta; //! TBranch *b_mb_TrackPhi; //! TBranch *b_mb_TrackPhi2; //! TBranch *b_mb_Px; //! TBranch *b_mb_Py; //! TBranch *b_mb_Pz; //! TBranch *b_mb_P0; //! TBranch *b_mi_Met; //! TBranch *b_mi_MetPhi; //! TBranch *b_mi_Ht; //! TBranch *b_mi_HtCorr; //! ydarkp(TTree *tree=0); ~ydarkp(); Int_t Cut(Int_t entry); Int_t GetEntry(Int_t entry); Int_t LoadTree(Int_t entry); void Init(TTree *tree); void Loop(); Bool_t Notify(); void Show(Int_t entry = -1); }; #endif #ifdef ydarkp_cxx ydarkp::ydarkp(TTree *tree) { // if parameter tree is not specified (or zero), connect the file // used to generate this class and read the Tree. if (tree == 0) { #ifdef SINGLE_TREE // The following code should be used if you want this class to access // a single tree instead of a chain TFile *f = (TFile*)gROOT->GetListOfFiles()->FindObject("Memory Directory"); if (!f) { f = new TFile("Memory Directory"); f->cd("Rint:/"); } tree = (TTree*)gDirectory->Get("Photon"); #else // SINGLE_TREE // The following code should be used if you want this class to access a chain // of trees. TChain * chain = new TChain("Photon",""); chain->Add("TDarkPhoton_Ntuple_1.root/Photon"); chain->Add("TDarkPhoton_Ntuple_2.root/Photon"); chain->Add("TDarkPhoton_Ntuple_3.root/Photon"); chain->Add("./TDarkPhoton_Ntuple_4.root/Photon"); chain->Add("./TDarkPhoton_Ntuple_5.root/Photon"); chain->Add("./TDarkPhoton_Ntuple_6.root/Photon"); chain->Add("./TDarkPhoton_Ntuple_7.root/Photon"); chain->Add("./TDarkPhoton_Ntuple_8.root/Photon"); chain->Add("./TDarkPhoton_Ntuple_9.root/Photon"); chain->Add("./TDarkPhoton_Ntuple_10.root/Photon"); chain->Add("./TDarkPhoton_Ntuple_11.root/Photon"); chain->Add("./TDarkPhoton_Ntuple_12.root/Photon"); chain->Add("./TDarkPhoton_Ntuple_13.root/Photon"); chain->Add("./TDarkPhoton_Ntuple_14.root/Photon"); chain->Add("./TDarkPhoton_Ntuple_15.root/Photon"); chain->Add("./TDarkPhoton_Ntuple_16.root/Photon"); chain->Add("./TDarkPhoton_Ntuple_17.root/Photon"); chain->Add("./TDarkPhoton_Ntuple_18.root/Photon"); chain->Add("./TDarkPhoton_Ntuple_19.root/Photon"); chain->Add("./TDarkPhoton_Ntuple_20.root/Photon"); chain->Add("./TDarkPhoton_Ntuple_21.root/Photon"); chain->Add("./TDarkPhoton_Ntuple_22.root/Photon"); chain->Add("./TDarkPhoton_Ntuple_23.root/Photon"); chain->Add("./TDarkPhoton_Ntuple_24.root/Photon"); chain->Add("./TDarkPhoton_Ntuple_25.root/Photon"); chain->Add("./TDarkPhoton_Ntuple_26.root/Photon"); chain->Add("./TDarkPhoton_Ntuple_27.root/Photon"); chain->Add("./TDarkPhoton_Ntuple_28.root/Photon"); chain->Add("./TDarkPhoton_Ntuple_29.root/Photon"); chain->Add("./TDarkPhoton_Ntuple_30.root/Photon"); /*chain->Add("./TDarkPhoton_Ntuple_31.root/Photon"); chain->Add("./TDarkPhoton_Ntuple_32.root/Photon"); chain->Add("./TDarkPhoton_Ntuple_33.root/Photon"); chain->Add("./TDarkPhoton_Ntuple_34.root/Photon"); chain->Add("./TDarkPhoton_Ntuple_35.root/Photon"); chain->Add("./TDarkPhoton_Ntuple_36.root/Photon"); chain->Add("./TDarkPhoton_Ntuple_37.root/Photon"); chain->Add("./TDarkPhoton_Ntuple_38.root/Photon"); chain->Add("./TDarkPhoton_Ntuple_39.root/Photon"); chain->Add("./TDarkPhoton_Ntuple_40.root/Photon"); chain->Add("./TDarkPhoton_Ntuple_41.root/Photon"); chain->Add("./TDarkPhoton_Ntuple_42.root/Photon"); chain->Add("./TDarkPhoton_Ntuple_43.root/Photon"); chain->Add("./TDarkPhoton_Ntuple_44.root/Photon"); chain->Add("./TDarkPhoton_Ntuple_45.root/Photon"); chain->Add("./TDarkPhoton_Ntuple_46.root/Photon"); chain->Add("./TDarkPhoton_Ntuple_47.root/Photon"); chain->Add("./TDarkPhoton_Ntuple_48.root/Photon"); chain->Add("./TDarkPhoton_Ntuple_49.root/Photon"); chain->Add("./TDarkPhoton_Ntuple_50.root/Photon");*/ tree = chain; #endif // SINGLE_TREE } Init(tree); } ydarkp::~ydarkp() { if (!fChain) return; delete fChain->GetCurrentFile(); } Int_t ydarkp::GetEntry(Int_t entry) { // Read contents of entry. if (!fChain) return 0; return fChain->GetEntry(entry); } Int_t ydarkp::LoadTree(Int_t entry) { // Set the environment to read one entry if (!fChain) return -5; Int_t centry = fChain->LoadTree(entry); if (centry < 0) return centry; if (fChain->IsA() != TChain::Class()) return centry; TChain *chain = (TChain*)fChain; if (chain->GetTreeNumber() != fCurrent) { fCurrent = chain->GetTreeNumber(); Notify(); } return centry; } void ydarkp::Init(TTree *tree) { // The Init() function is called when the selector needs to initialize // a new tree or chain. Typically here the branch addresses of the tree // will be set. It is normaly not necessary to make changes to the // generated code, but the routine can be extended by the user if needed. // Init() will be called many times when running with PROOF. // Set branch addresses if (tree == 0) return; fChain = tree; fCurrent = -1; fChain->SetMakeClass(1); fChain->SetBranchAddress("ph_Npho",&ph_Npho); fChain->SetBranchAddress("ph_E",ph_E); fChain->SetBranchAddress("ph_Et",ph_Et); fChain->SetBranchAddress("ph_Etc",ph_Etc); fChain->SetBranchAddress("ph_Cesx",ph_Cesx); fChain->SetBranchAddress("ph_Cesz",ph_Cesz); fChain->SetBranchAddress("ph_Deta",ph_Deta); fChain->SetBranchAddress("ph_Eta",ph_Eta); fChain->SetBranchAddress("ph_Phi",ph_Phi); fChain->SetBranchAddress("ph_SinTheta",ph_SinTheta); fChain->SetBranchAddress("ph_N3d",ph_N3d); fChain->SetBranchAddress("ph_Chi2",ph_Chi2); fChain->SetBranchAddress("ph_NIsoTrk",ph_NIsoTrk); fChain->SetBranchAddress("ph_Pt",ph_Pt); fChain->SetBranchAddress("ph_Tiso",ph_Tiso); fChain->SetBranchAddress("e_NElectrons",&e_NElectrons); fChain->SetBranchAddress("e_Good",e_Good); fChain->SetBranchAddress("e_TotalEt",e_TotalEt); fChain->SetBranchAddress("e_Et",e_Et); fChain->SetBranchAddress("e_E",e_E); fChain->SetBranchAddress("e_TrackPt",e_TrackPt); fChain->SetBranchAddress("e_Nasl",e_Nasl); fChain->SetBranchAddress("e_Nssl",e_Nssl); fChain->SetBranchAddress("e_HadEm",e_HadEm); fChain->SetBranchAddress("e_Iso",e_Iso); fChain->SetBranchAddress("e_Lshr",e_Lshr); fChain->SetBranchAddress("e_EP",e_EP); fChain->SetBranchAddress("e_DelXQ",e_DelXQ); fChain->SetBranchAddress("e_DelZ",e_DelZ); fChain->SetBranchAddress("e_Z0",e_Z0); fChain->SetBranchAddress("e_Chi2Strip",e_Chi2Strip); fChain->SetBranchAddress("e_DetectorCode",&e_DetectorCode); fChain->SetBranchAddress("e_TrackNumber",&e_TrackNumber); fChain->SetBranchAddress("e_ClusterEmEt",e_ClusterEmEt); fChain->SetBranchAddress("e_ClusterHadEt",e_ClusterHadEt); fChain->SetBranchAddress("e_Charge",e_Charge); fChain->SetBranchAddress("e_TrackEta",e_TrackEta); fChain->SetBranchAddress("e_TrackPhi",e_TrackPhi); fChain->SetBranchAddress("e_TrackPhi2",e_TrackPhi2); fChain->SetBranchAddress("e_Px",e_Px); fChain->SetBranchAddress("e_Py",e_Py); fChain->SetBranchAddress("e_Pz",e_Pz); fChain->SetBranchAddress("e_P0",e_P0); fChain->SetBranchAddress("eb_NPositrons",&eb_NPositrons); fChain->SetBranchAddress("eb_Good",eb_Good); fChain->SetBranchAddress("eb_TotalEt",eb_TotalEt); fChain->SetBranchAddress("eb_Et",eb_Et); fChain->SetBranchAddress("eb_E",eb_E); fChain->SetBranchAddress("eb_TrackPt",eb_TrackPt); fChain->SetBranchAddress("eb_Nasl",eb_Nasl); fChain->SetBranchAddress("eb_Nssl",eb_Nssl); fChain->SetBranchAddress("eb_HadEm",eb_HadEm); fChain->SetBranchAddress("eb_Iso",eb_Iso); fChain->SetBranchAddress("eb_Lshr",eb_Lshr); fChain->SetBranchAddress("eb_EP",eb_EP); fChain->SetBranchAddress("eb_DelXQ",eb_DelXQ); fChain->SetBranchAddress("eb_DelZ",eb_DelZ); fChain->SetBranchAddress("eb_Z0",eb_Z0); fChain->SetBranchAddress("eb_Chi2Strip",eb_Chi2Strip); fChain->SetBranchAddress("eb_DetectorCode",&eb_DetectorCode); fChain->SetBranchAddress("eb_TrackNumber",&eb_TrackNumber); fChain->SetBranchAddress("eb_ClusterEmEt",eb_ClusterEmEt); fChain->SetBranchAddress("eb_ClusterHadEt",eb_ClusterHadEt); fChain->SetBranchAddress("eb_Charge",eb_Charge); fChain->SetBranchAddress("eb_TrackEta",eb_TrackEta); fChain->SetBranchAddress("eb_TrackPhi",eb_TrackPhi); fChain->SetBranchAddress("eb_TrackPhi2",eb_TrackPhi2); fChain->SetBranchAddress("eb_Px",eb_Px); fChain->SetBranchAddress("eb_Py",eb_Py); fChain->SetBranchAddress("eb_Pz",eb_Pz); fChain->SetBranchAddress("eb_P0",eb_P0); fChain->SetBranchAddress("m_NMuons",&m_NMuons); fChain->SetBranchAddress("m_Good",m_Good); fChain->SetBranchAddress("m_TrackNumber",m_TrackNumber); fChain->SetBranchAddress("m_NCmuHits",m_NCmuHits); fChain->SetBranchAddress("m_NCmpHits",m_NCmpHits); fChain->SetBranchAddress("m_NCmxHits",m_NCmxHits); fChain->SetBranchAddress("m_NBmuHits",m_NBmuHits); fChain->SetBranchAddress("m_TrackPt",m_TrackPt); fChain->SetBranchAddress("m_Iso",m_Iso); fChain->SetBranchAddress("m_CmuDelX",m_CmuDelX); fChain->SetBranchAddress("m_CmpDelX",m_CmpDelX); fChain->SetBranchAddress("m_CmxDelX",m_CmxDelX); fChain->SetBranchAddress("m_BmuDelX",m_BmuDelX); fChain->SetBranchAddress("m_HasCmuStub",m_HasCmuStub); fChain->SetBranchAddress("m_HasCmpStub",m_HasCmpStub); fChain->SetBranchAddress("m_HasCmxStub",m_HasCmxStub); fChain->SetBranchAddress("m_HasBmuStub",m_HasBmuStub); fChain->SetBranchAddress("m_TrackBcPt",m_TrackBcPt); fChain->SetBranchAddress("m_EmEnergy",m_EmEnergy); fChain->SetBranchAddress("m_HadEnergy",m_HadEnergy); fChain->SetBranchAddress("m_Z0",m_Z0); fChain->SetBranchAddress("m_D0",m_D0); fChain->SetBranchAddress("m_mupt",m_mupt); fChain->SetBranchAddress("m_NSvxHits",m_NSvxHits); fChain->SetBranchAddress("m_d0Corr",m_d0Corr); fChain->SetBranchAddress("m_Charge",m_Charge); fChain->SetBranchAddress("m_TrackEta",m_TrackEta); fChain->SetBranchAddress("m_TrackPhi",m_TrackPhi); fChain->SetBranchAddress("m_TrackPhi2",m_TrackPhi2); fChain->SetBranchAddress("m_Px",m_Px); fChain->SetBranchAddress("m_Py",m_Py); fChain->SetBranchAddress("m_Pz",m_Pz); fChain->SetBranchAddress("m_P0",m_P0); fChain->SetBranchAddress("mb_NAMuons",&mb_NAMuons); fChain->SetBranchAddress("mb_Good",mb_Good); fChain->SetBranchAddress("mb_TrackNumber",mb_TrackNumber); fChain->SetBranchAddress("mb_NCmuHits",mb_NCmuHits); fChain->SetBranchAddress("mb_NCmpHits",mb_NCmpHits); fChain->SetBranchAddress("mb_NCmxHits",mb_NCmxHits); fChain->SetBranchAddress("mb_NBmuHits",mb_NBmuHits); fChain->SetBranchAddress("mb_TrackPt",mb_TrackPt); fChain->SetBranchAddress("mb_Iso",mb_Iso); fChain->SetBranchAddress("mb_CmuDelX",mb_CmuDelX); fChain->SetBranchAddress("mb_CmpDelX",mb_CmpDelX); fChain->SetBranchAddress("mb_CmxDelX",mb_CmxDelX); fChain->SetBranchAddress("mb_BmuDelX",mb_BmuDelX); fChain->SetBranchAddress("mb_HasCmuStub",mb_HasCmuStub); fChain->SetBranchAddress("mb_HasCmpStub",mb_HasCmpStub); fChain->SetBranchAddress("mb_HasCmxStub",mb_HasCmxStub); fChain->SetBranchAddress("mb_HasBmuStub",mb_HasBmuStub); fChain->SetBranchAddress("mb_TrackBcPt",mb_TrackBcPt); fChain->SetBranchAddress("mb_EmEnergy",mb_EmEnergy); fChain->SetBranchAddress("mb_HadEnergy",mb_HadEnergy); fChain->SetBranchAddress("mb_Z0",mb_Z0); fChain->SetBranchAddress("mb_D0",mb_D0); fChain->SetBranchAddress("mb_mupt",mb_mupt); fChain->SetBranchAddress("mb_NSvxHits",mb_NSvxHits); fChain->SetBranchAddress("mb_d0Corr",mb_d0Corr); fChain->SetBranchAddress("mb_Charge",mb_Charge); fChain->SetBranchAddress("mb_TrackEta",mb_TrackEta); fChain->SetBranchAddress("mb_TrackPhi",mb_TrackPhi); fChain->SetBranchAddress("mb_TrackPhi2",mb_TrackPhi2); fChain->SetBranchAddress("mb_Px",mb_Px); fChain->SetBranchAddress("mb_Py",mb_Py); fChain->SetBranchAddress("mb_Pz",mb_Pz); fChain->SetBranchAddress("mb_P0",mb_P0); fChain->SetBranchAddress("mi_Met",&mi_Met); fChain->SetBranchAddress("mi_MetPhi",&mi_MetPhi); fChain->SetBranchAddress("mi_Ht",&mi_Ht); fChain->SetBranchAddress("mi_HtCorr",&mi_HtCorr); Notify(); } Bool_t ydarkp::Notify() { // The Notify() function is called when a new file is opened. This // can be either for a new TTree in a TChain or when when a new TTree // is started when using PROOF. Typically here the branch pointers // will be retrieved. It is normaly not necessary to make changes // to the generated code, but the routine can be extended by the // user if needed. // Get branch pointers b_ph_Npho = fChain->GetBranch("ph_Npho"); b_ph_E = fChain->GetBranch("ph_E"); b_ph_Et = fChain->GetBranch("ph_Et"); b_ph_Etc = fChain->GetBranch("ph_Etc"); b_ph_Cesx = fChain->GetBranch("ph_Cesx"); b_ph_Cesz = fChain->GetBranch("ph_Cesz"); b_ph_Deta = fChain->GetBranch("ph_Deta"); b_ph_Eta = fChain->GetBranch("ph_Eta"); b_ph_Phi = fChain->GetBranch("ph_Phi"); b_ph_SinTheta = fChain->GetBranch("ph_SinTheta"); b_ph_N3d = fChain->GetBranch("ph_N3d"); b_ph_Chi2 = fChain->GetBranch("ph_Chi2"); b_ph_NIsoTrk = fChain->GetBranch("ph_NIsoTrk"); b_ph_Pt = fChain->GetBranch("ph_Pt"); b_ph_Tiso = fChain->GetBranch("ph_Tiso"); b_e_NElectrons = fChain->GetBranch("e_NElectrons"); b_e_Good = fChain->GetBranch("e_Good"); b_e_TotalEt = fChain->GetBranch("e_TotalEt"); b_e_Et = fChain->GetBranch("e_Et"); b_e_E = fChain->GetBranch("e_E"); b_e_TrackPt = fChain->GetBranch("e_TrackPt"); b_e_Nasl = fChain->GetBranch("e_Nasl"); b_e_Nssl = fChain->GetBranch("e_Nssl"); b_e_HadEm = fChain->GetBranch("e_HadEm"); b_e_Iso = fChain->GetBranch("e_Iso"); b_e_Lshr = fChain->GetBranch("e_Lshr"); b_e_EP = fChain->GetBranch("e_EP"); b_e_DelXQ = fChain->GetBranch("e_DelXQ"); b_e_DelZ = fChain->GetBranch("e_DelZ"); b_e_Z0 = fChain->GetBranch("e_Z0"); b_e_Chi2Strip = fChain->GetBranch("e_Chi2Strip"); b_e_DetectorCode = fChain->GetBranch("e_DetectorCode"); b_e_TrackNumber = fChain->GetBranch("e_TrackNumber"); b_e_ClusterEmEt = fChain->GetBranch("e_ClusterEmEt"); b_e_ClusterHadEt = fChain->GetBranch("e_ClusterHadEt"); b_e_Charge = fChain->GetBranch("e_Charge"); b_e_TrackEta = fChain->GetBranch("e_TrackEta"); b_e_TrackPhi = fChain->GetBranch("e_TrackPhi"); b_e_TrackPhi2 = fChain->GetBranch("e_TrackPhi2"); b_e_Px = fChain->GetBranch("e_Px"); b_e_Py = fChain->GetBranch("e_Py"); b_e_Pz = fChain->GetBranch("e_Pz"); b_e_P0 = fChain->GetBranch("e_P0"); b_eb_NPositrons = fChain->GetBranch("eb_NPositrons"); b_eb_Good = fChain->GetBranch("eb_Good"); b_eb_TotalEt = fChain->GetBranch("eb_TotalEt"); b_eb_Et = fChain->GetBranch("eb_Et"); b_eb_E = fChain->GetBranch("eb_E"); b_eb_TrackPt = fChain->GetBranch("eb_TrackPt"); b_eb_Nasl = fChain->GetBranch("eb_Nasl"); b_eb_Nssl = fChain->GetBranch("eb_Nssl"); b_eb_HadEm = fChain->GetBranch("eb_HadEm"); b_eb_Iso = fChain->GetBranch("eb_Iso"); b_eb_Lshr = fChain->GetBranch("eb_Lshr"); b_eb_EP = fChain->GetBranch("eb_EP"); b_eb_DelXQ = fChain->GetBranch("eb_DelXQ"); b_eb_DelZ = fChain->GetBranch("eb_DelZ"); b_eb_Z0 = fChain->GetBranch("eb_Z0"); b_eb_Chi2Strip = fChain->GetBranch("eb_Chi2Strip"); b_eb_DetectorCode = fChain->GetBranch("eb_DetectorCode"); b_eb_TrackNumber = fChain->GetBranch("eb_TrackNumber"); b_eb_ClusterEmEt = fChain->GetBranch("eb_ClusterEmEt"); b_eb_ClusterHadEt = fChain->GetBranch("eb_ClusterHadEt"); b_eb_Charge = fChain->GetBranch("eb_Charge"); b_eb_TrackEta = fChain->GetBranch("eb_TrackEta"); b_eb_TrackPhi = fChain->GetBranch("eb_TrackPhi"); b_eb_TrackPhi2 = fChain->GetBranch("eb_TrackPhi2"); b_eb_Px = fChain->GetBranch("eb_Px"); b_eb_Py = fChain->GetBranch("eb_Py"); b_eb_Pz = fChain->GetBranch("eb_Pz"); b_eb_P0 = fChain->GetBranch("eb_P0"); b_m_NMuons = fChain->GetBranch("m_NMuons"); b_m_Good = fChain->GetBranch("m_Good"); b_m_TrackNumber = fChain->GetBranch("m_TrackNumber"); b_m_NCmuHits = fChain->GetBranch("m_NCmuHits"); b_m_NCmpHits = fChain->GetBranch("m_NCmpHits"); b_m_NCmxHits = fChain->GetBranch("m_NCmxHits"); b_m_NBmuHits = fChain->GetBranch("m_NBmuHits"); b_m_TrackPt = fChain->GetBranch("m_TrackPt"); b_m_Iso = fChain->GetBranch("m_Iso"); b_m_CmuDelX = fChain->GetBranch("m_CmuDelX"); b_m_CmpDelX = fChain->GetBranch("m_CmpDelX"); b_m_CmxDelX = fChain->GetBranch("m_CmxDelX"); b_m_BmuDelX = fChain->GetBranch("m_BmuDelX"); b_m_HasCmuStub = fChain->GetBranch("m_HasCmuStub"); b_m_HasCmpStub = fChain->GetBranch("m_HasCmpStub"); b_m_HasCmxStub = fChain->GetBranch("m_HasCmxStub"); b_m_HasBmuStub = fChain->GetBranch("m_HasBmuStub"); b_m_TrackBcPt = fChain->GetBranch("m_TrackBcPt"); b_m_EmEnergy = fChain->GetBranch("m_EmEnergy"); b_m_HadEnergy = fChain->GetBranch("m_HadEnergy"); b_m_Z0 = fChain->GetBranch("m_Z0"); b_m_D0 = fChain->GetBranch("m_D0"); b_m_mupt = fChain->GetBranch("m_mupt"); b_m_NSvxHits = fChain->GetBranch("m_NSvxHits"); b_m_d0Corr = fChain->GetBranch("m_d0Corr"); b_m_Charge = fChain->GetBranch("m_Charge"); b_m_TrackEta = fChain->GetBranch("m_TrackEta"); b_m_TrackPhi = fChain->GetBranch("m_TrackPhi"); b_m_TrackPhi2 = fChain->GetBranch("m_TrackPhi2"); b_m_Px = fChain->GetBranch("m_Px"); b_m_Py = fChain->GetBranch("m_Py"); b_m_Pz = fChain->GetBranch("m_Pz"); b_m_P0 = fChain->GetBranch("m_P0"); b_mb_NAMuons = fChain->GetBranch("mb_NAMuons"); b_mb_Good = fChain->GetBranch("mb_Good"); b_mb_TrackNumber = fChain->GetBranch("mb_TrackNumber"); b_mb_NCmuHits = fChain->GetBranch("mb_NCmuHits"); b_mb_NCmpHits = fChain->GetBranch("mb_NCmpHits"); b_mb_NCmxHits = fChain->GetBranch("mb_NCmxHits"); b_mb_NBmuHits = fChain->GetBranch("mb_NBmuHits"); b_mb_TrackPt = fChain->GetBranch("mb_TrackPt"); b_mb_Iso = fChain->GetBranch("mb_Iso"); b_mb_CmuDelX = fChain->GetBranch("mb_CmuDelX"); b_mb_CmpDelX = fChain->GetBranch("mb_CmpDelX"); b_mb_CmxDelX = fChain->GetBranch("mb_CmxDelX"); b_mb_BmuDelX = fChain->GetBranch("mb_BmuDelX"); b_mb_HasCmuStub = fChain->GetBranch("mb_HasCmuStub"); b_mb_HasCmpStub = fChain->GetBranch("mb_HasCmpStub"); b_mb_HasCmxStub = fChain->GetBranch("mb_HasCmxStub"); b_mb_HasBmuStub = fChain->GetBranch("mb_HasBmuStub"); b_mb_TrackBcPt = fChain->GetBranch("mb_TrackBcPt"); b_mb_EmEnergy = fChain->GetBranch("mb_EmEnergy"); b_mb_HadEnergy = fChain->GetBranch("mb_HadEnergy"); b_mb_Z0 = fChain->GetBranch("mb_Z0"); b_mb_D0 = fChain->GetBranch("mb_D0"); b_mb_mupt = fChain->GetBranch("mb_mupt"); b_mb_NSvxHits = fChain->GetBranch("mb_NSvxHits"); b_mb_d0Corr = fChain->GetBranch("mb_d0Corr"); b_mb_Charge = fChain->GetBranch("mb_Charge"); b_mb_TrackEta = fChain->GetBranch("mb_TrackEta"); b_mb_TrackPhi = fChain->GetBranch("mb_TrackPhi"); b_mb_TrackPhi2 = fChain->GetBranch("mb_TrackPhi2"); b_mb_Px = fChain->GetBranch("mb_Px"); b_mb_Py = fChain->GetBranch("mb_Py"); b_mb_Pz = fChain->GetBranch("mb_Pz"); b_mb_P0 = fChain->GetBranch("mb_P0"); b_mi_Met = fChain->GetBranch("mi_Met"); b_mi_MetPhi = fChain->GetBranch("mi_MetPhi"); b_mi_Ht = fChain->GetBranch("mi_Ht"); b_mi_HtCorr = fChain->GetBranch("mi_HtCorr"); return kTRUE; } void ydarkp::Show(Int_t entry) { // Print contents of entry. // If entry is not specified, print current entry if (!fChain) return; fChain->Show(entry); } Int_t ydarkp::Cut(Int_t entry) { // This function may be called from Loop. // returns 1 if entry is accepted. // returns -1 otherwise. return 1; } #endif // #ifdef ydarkp_cxx
iamaris/CDFCodes
results/ydarkp.h
C
apache-2.0
32,375
package com.yunos.alicontacts.sim; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; public class SimContactLoadReceiver extends BroadcastReceiver { private static final String TAG = "SimContactLoadReceiver"; @Override public void onReceive(Context context, Intent intent) { if (SimUtil.IS_YUNOS) { final String action = intent.getAction(); int slotId = SimContactUtils.getSlotIdFromSimStateChangedIntent(intent); Log.d(TAG, "onReceive() action:" + action + ", dualSimMode:" + SimUtil.MULTISIM_ENABLE + "; slotId="+slotId); if (SimContactUtils.ACTION_SIM_STATE_CHANGED.equals(action)) { SimContactUtils.handleSimState(intent); } String handleSimContactsAction = null; int op = SimContactUtils.needToLoadSimContactsToPhone(intent, action); if (op == SimContactUtils.OPERATION_LOAD_SIM_CONTACTS_TO_PHONE_DB) { // If the app is launched by a broadcast to this receiver, // then the App.onCreate might start the service. // If it is this case, then the loaded count will be SCHEDULE_LOAD_COUNT, // we need to skip start service again. if (SimContactLoadService.getSimLoadedCount(slotId) == SimContactLoadService.SCHEDULE_LOAD_COUNT) { Log.i(TAG, "onReceive: already scheduled loading. quit."); return; } handleSimContactsAction = SimContactLoadService.ACTION_LOAD_SIM_CONTACTS_TO_PHONE_DB; } else if (op == SimContactUtils.OPERATION_DELETE_SIM_CONTACTS_FROM_PHONE_DB) { handleSimContactsAction = SimContactLoadService.ACTION_DELETE_SIM_CONTACTS_FROM_PHONE_DB; } else { Log.d(TAG, "onReceive: nothing to do, quit."); return; } handleSimContacts(context, action, handleSimContactsAction, slotId); } } private void handleSimContacts(Context context, String receiverAction, String handleSimContactsAction, int slotId) { if (slotId == SimUtil.INVALID_SLOT_ID) { Log.i(TAG, "handleSimContacts: got invalid slot id. receiverAction="+receiverAction); if (Intent.ACTION_AIRPLANE_MODE_CHANGED.equals(receiverAction)) { handleSimContactsForSlot(context, handleSimContactsAction, SimUtil.SLOT_ID_1); if (SimUtil.MULTISIM_ENABLE) { handleSimContactsForSlot(context, handleSimContactsAction, SimUtil.SLOT_ID_2); } } else { Log.e(TAG, "handleSimContacts: can NOT determine which slot to handle. quit."); return; } } else { Log.i(TAG, "handleSimContacts: slotId="+slotId+"; action="+handleSimContactsAction); handleSimContactsForSlot(context, handleSimContactsAction, slotId); } } private void handleSimContactsForSlot(Context context, String action, int slotId) { // If the receiver gets broadcast during app running, // then we don't need to change the count. if (SimContactLoadService.getSimLoadedCount(slotId) == SimContactLoadService.NOT_LOADED_COUNT) { Log.i(TAG, "handleSimContactsForSlot: set sim loaded count to schedule loading for slot "+slotId); SimContactLoadService.setSimScheduleLoading(slotId); } Intent handleIntent = new Intent(action); handleIntent.setClass(context.getApplicationContext(), SimContactLoadService.class); handleIntent.putExtra(SimContactLoadService.INTENT_KEY_SLOT_ID, slotId); Log.i(TAG, "handleSimContactsForSlot: send intent "+handleIntent+" for slot "+slotId); context.startService(handleIntent); } }
miswenwen/My_bird_work
Bird_work/我的项目/Contacts/Contacts_liuqipeng/src/com/yunos/alicontacts/sim/SimContactLoadReceiver.java
Java
apache-2.0
3,908
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Strings for component 'qtype_match', language 'zh_tw', branch 'MOODLE_22_STABLE' * * @package qtype_match * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); $string['addmoreqblanks'] = '增加 {no} 個空白配合項目'; $string['answer'] = '答案{$a}'; $string['availablechoices'] = '可用的選項'; $string['correctansweris'] = '正確答案是:{$a}'; $string['filloutthreeqsandtwoas'] = '您必須至少提供兩個問題和三個答案。你可以藉由增加空白問題來提供額外的錯誤答案。若問題與對應的答案都空白石,該題會被忽略。'; $string['nomatchinganswer'] = '您必須指定一個答案來配對這一問題"{$a}"'; $string['nomatchinganswerforq'] = '您必須為這個題目指定一個答案。'; $string['notenoughqsandas'] = '你必須只少提供{$a->q} 個問題和 {$a->a} 個答案'; $string['notenoughquestions'] = '您必須提供至少{$a}個配對的題目與答案。'; $string['pleaseananswerallparts'] = '請回答這一試題的所有小題'; $string['pluginname'] = '配合題'; $string['pluginnameadding'] = '新增一配合題'; $string['pluginnameediting'] = '編輯一配合題'; $string['pluginname_help'] = '配合題要求作答者將一清單上的名字或敘述(問題)和另外一清單上的名字或敘述(答案)依照某種規則正確地配對起來。'; $string['pluginnamesummary'] = '一小題的答案都需要從可能答案的清單中選出來。'; $string['shuffle'] = '隨機排列'; $string['shuffle_help'] = '若啟用,每次作答時,答案項的順序都會重新隨機排列。它需要在測驗活動設定時啟用"在試題內隨機排列"。';
carnegiespeech/translations
zh_tw/qtype_match.php
PHP
apache-2.0
2,487
# Copyright 2013 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import random import time import mock from mox3 import mox from os_xenapi.client import XenAPI from nova.compute import utils as compute_utils from nova import context from nova import exception from nova.tests.unit.virt.xenapi import stubs from nova.virt.xenapi import driver as xenapi_conn from nova.virt.xenapi import fake from nova.virt.xenapi.image import glance from nova.virt.xenapi import vm_utils class TestGlanceStore(stubs.XenAPITestBaseNoDB): def setUp(self): super(TestGlanceStore, self).setUp() self.store = glance.GlanceStore() self.flags(api_servers=['http://localhost:9292'], group='glance') self.flags(connection_url='test_url', connection_password='test_pass', group='xenserver') self.context = context.RequestContext( 'user', 'project', auth_token='foobar') fake.reset() stubs.stubout_session(self.stubs, fake.SessionBase) driver = xenapi_conn.XenAPIDriver(False) self.session = driver._session self.stubs.Set( vm_utils, 'get_sr_path', lambda *a, **kw: '/fake/sr/path') self.instance = {'uuid': 'blah', 'system_metadata': [], 'auto_disk_config': True, 'os_type': 'default', 'xenapi_use_agent': 'true'} def _get_params(self): return {'image_id': 'fake_image_uuid', 'endpoint': 'http://localhost:9292', 'sr_path': '/fake/sr/path', 'api_version': 2, 'extra_headers': {'X-Auth-Token': 'foobar', 'X-Roles': '', 'X-Tenant-Id': 'project', 'X-User-Id': 'user', 'X-Identity-Status': 'Confirmed'}} def _get_download_params(self): params = self._get_params() params['uuid_stack'] = ['uuid1'] return params def test_download_image(self): params = self._get_download_params() self.stubs.Set(vm_utils, '_make_uuid_stack', lambda *a, **kw: ['uuid1']) self.mox.StubOutWithMock(self.session, 'call_plugin_serialized') self.session.call_plugin_serialized('glance.py', 'download_vhd2', **params) self.mox.ReplayAll() self.store.download_image(self.context, self.session, self.instance, 'fake_image_uuid') self.mox.VerifyAll() @mock.patch.object(vm_utils, '_make_uuid_stack', return_value=['uuid1']) @mock.patch.object(random, 'shuffle') @mock.patch.object(time, 'sleep') @mock.patch.object(compute_utils, 'add_instance_fault_from_exc') def test_download_image_retry(self, mock_fault, mock_sleep, mock_shuffle, mock_make_uuid_stack): params = self._get_download_params() self.flags(num_retries=2, group='glance') params.pop("endpoint") calls = [mock.call('glance.py', 'download_vhd2', endpoint='http://10.0.1.1:9292', **params), mock.call('glance.py', 'download_vhd2', endpoint='http://10.0.0.1:9293', **params)] glance_api_servers = ['10.0.1.1:9292', 'http://10.0.0.1:9293'] self.flags(api_servers=glance_api_servers, group='glance') with (mock.patch.object(self.session, 'call_plugin_serialized') ) as mock_call_plugin_serialized: error_details = ["", "", "RetryableError", ""] error = self.session.XenAPI.Failure(details=error_details) mock_call_plugin_serialized.side_effect = [error, "success"] self.store.download_image(self.context, self.session, self.instance, 'fake_image_uuid') mock_call_plugin_serialized.assert_has_calls(calls) self.assertEqual(1, mock_fault.call_count) def _get_upload_params(self, auto_disk_config=True, expected_os_type='default'): params = self._get_params() params['vdi_uuids'] = ['fake_vdi_uuid'] params['properties'] = {'auto_disk_config': auto_disk_config, 'os_type': expected_os_type} return params def _test_upload_image(self, auto_disk_config, expected_os_type='default'): params = self._get_upload_params(auto_disk_config, expected_os_type) self.mox.StubOutWithMock(self.session, 'call_plugin_serialized') self.session.call_plugin_serialized('glance.py', 'upload_vhd2', **params) self.mox.ReplayAll() self.store.upload_image(self.context, self.session, self.instance, 'fake_image_uuid', ['fake_vdi_uuid']) self.mox.VerifyAll() def test_upload_image(self): self._test_upload_image(True) def test_upload_image_None_os_type(self): self.instance['os_type'] = None self._test_upload_image(True, 'linux') def test_upload_image_no_os_type(self): del self.instance['os_type'] self._test_upload_image(True, 'linux') def test_upload_image_auto_config_disk_disabled(self): sys_meta = [{"key": "image_auto_disk_config", "value": "Disabled"}] self.instance["system_metadata"] = sys_meta self._test_upload_image("disabled") def test_upload_image_raises_exception(self): params = self._get_upload_params() self.mox.StubOutWithMock(self.session, 'call_plugin_serialized') self.session.call_plugin_serialized('glance.py', 'upload_vhd2', **params).AndRaise(RuntimeError) self.mox.ReplayAll() self.assertRaises(RuntimeError, self.store.upload_image, self.context, self.session, self.instance, 'fake_image_uuid', ['fake_vdi_uuid']) self.mox.VerifyAll() def test_upload_image_retries_then_raises_exception(self): self.flags(num_retries=2, group='glance') params = self._get_upload_params() self.mox.StubOutWithMock(self.session, 'call_plugin_serialized') self.mox.StubOutWithMock(time, 'sleep') self.mox.StubOutWithMock(compute_utils, 'add_instance_fault_from_exc') error_details = ["", "", "RetryableError", ""] error = self.session.XenAPI.Failure(details=error_details) self.session.call_plugin_serialized('glance.py', 'upload_vhd2', **params).AndRaise(error) compute_utils.add_instance_fault_from_exc(self.context, self.instance, error, (XenAPI.Failure, error, mox.IgnoreArg())) time.sleep(0.5) self.session.call_plugin_serialized('glance.py', 'upload_vhd2', **params).AndRaise(error) compute_utils.add_instance_fault_from_exc(self.context, self.instance, error, (XenAPI.Failure, error, mox.IgnoreArg())) time.sleep(1) self.session.call_plugin_serialized('glance.py', 'upload_vhd2', **params).AndRaise(error) compute_utils.add_instance_fault_from_exc(self.context, self.instance, error, (XenAPI.Failure, error, mox.IgnoreArg())) self.mox.ReplayAll() self.assertRaises(exception.CouldNotUploadImage, self.store.upload_image, self.context, self.session, self.instance, 'fake_image_uuid', ['fake_vdi_uuid']) self.mox.VerifyAll() def test_upload_image_retries_on_signal_exception(self): self.flags(num_retries=2, group='glance') params = self._get_upload_params() self.mox.StubOutWithMock(self.session, 'call_plugin_serialized') self.mox.StubOutWithMock(time, 'sleep') self.mox.StubOutWithMock(compute_utils, 'add_instance_fault_from_exc') error_details = ["", "task signaled", "", ""] error = self.session.XenAPI.Failure(details=error_details) self.session.call_plugin_serialized('glance.py', 'upload_vhd2', **params).AndRaise(error) compute_utils.add_instance_fault_from_exc(self.context, self.instance, error, (XenAPI.Failure, error, mox.IgnoreArg())) time.sleep(0.5) # Note(johngarbutt) XenServer 6.1 and later has this error error_details = ["", "signal: SIGTERM", "", ""] error = self.session.XenAPI.Failure(details=error_details) self.session.call_plugin_serialized('glance.py', 'upload_vhd2', **params).AndRaise(error) compute_utils.add_instance_fault_from_exc(self.context, self.instance, error, (XenAPI.Failure, error, mox.IgnoreArg())) time.sleep(1) self.session.call_plugin_serialized('glance.py', 'upload_vhd2', **params) self.mox.ReplayAll() self.store.upload_image(self.context, self.session, self.instance, 'fake_image_uuid', ['fake_vdi_uuid']) self.mox.VerifyAll()
hanlind/nova
nova/tests/unit/virt/xenapi/image/test_glance.py
Python
apache-2.0
10,892
\documentclass{standalone} %----------------------------------------------------------------------------------------------% % Packages and basic declarations %----------------------------------------------------------------------------------------------% \usepackage[utf8]{inputenc} \usepackage{pgfplots} \usepackage{tikz} \usepackage{nicefrac} %----------------------------------------------------------------------------------------------% %----------------------------------------------------------------------------------------------% % DOCUMENT STARTS %----------------------------------------------------------------------------------------------% %----------------------------------------------------------------------------------------------% \begin{document} \def\markersize{4.5pt} \def\linewidth{2.5pt} %Tikz picture starts% \begin{tikzpicture} %Tikz axis starts% \begin{axis}[width=30cm, % SCALE scale=0.5, % STYLE %title style={font=\fontsize{40}{8}\selectfont}, xlabel style={at={(axis description cs:0.5,-0.025)},anchor=north,font=\fontsize{48}{40}\selectfont}, ylabel style={at={(axis description cs:-0.05,.5)},anchor=south,font=\fontsize{48}{40}\selectfont}, tick align=outside, tick label style={font=\huge}, legend style={at={(axis description cs:0.45,0.45)},anchor=south west,draw=white!80.0!black,font=\fontsize{16}{14}\selectfont,row sep=7.5pt}, legend image post style={xscale=1.1,yscale=1.1}, legend cell align={left}, clip mode=individual, % GRID STYLE xmajorgrids, x grid style={lightgray!92.026143790849673!black}, ymajorgrids, y grid style={lightgray!92.026143790849673!black}, line width=0.75mm, % GRID SIZE xmin=0.0, xmax=90.0, ymin=0.0, ymax=9.25, xtick={0.0,10.0,20.0,30.0,40.0,50.0,60.0,70.0,80.0,90.0}, % CONTENT %title={\bf{$\frac{G_{I}}{G_{0}}$ as function of debond's size $\Delta\theta$, in-house VCCT routine}}, xlabel={$\Delta\theta\left[^{\circ}\right]$}, ylabel={$G_{I}\left[\nicefrac{J}{m^{2}}\right]$}, % LEGEND ENTRIES legend entries={}, ] % 11x3 - 1T90- clustered \addplot[line width=\linewidth,mark size=\markersize,black,smooth,mark=*] table{ 10 4.168256 20 4.341164 30 3.242491 40 2.077658 50 1.151100 60 0.400073 70 0.018134 80 0.000044 90 0.000071 100 0.000077 110 0.000039 120 0.000016 130 0.000005 140 0.000000 150 0.016460 }; \addlegendentry{$11\times 3-1\cdot t_{90^ {\circ}}$, cluster}; % 11x5 - 1T90 - clustered \addplot[line width=\linewidth,mark size=\markersize,black,smooth,mark=square*,] table{ 10 3.736854 20 3.945278 30 2.947752 40 1.866407 50 1.027633 60 0.356710 70 0.016392 80 0.000040 90 0.000065 100 0.000070 110 0.000035 120 0.000015 130 0.000005 140 0.000000 150 0.014364 }; \addlegendentry{$11\times 5-1\cdot t_{90^ {\circ}}$, cluster}; % 11x7 - 1T90 - clustered \addplot[line width=\linewidth,mark size=\markersize,black,smooth,mark=triangle*] table{ 10 3.749864 20 3.878398 30 2.861314 40 1.807215 50 0.983747 60 0.333590 70 0.011829 80 0.000041 90 0.000066 100 0.000070 110 0.000035 120 0.000015 130 0.000005 140 0.000000 150 0.013959 }; \addlegendentry{$11\times 7-1\cdot t_{90^ {\circ}}$, cluster}; % 11x11 - 1T90 - clustered \addplot[line width=\linewidth,mark size=\markersize,black,smooth,mark=diamond*] table{ 10 3.764169 20 3.950387 30 2.910752 40 1.804045 50 0.961672 60 0.312616 70 0.006084 80 0.000046 90 0.000070 100 0.000073 110 0.000035 120 0.000015 130 0.000005 140 0.000000 150 0.014704 }; \addlegendentry{$11\times 11-1\cdot t_{90^ {\circ}}$, cluster}; % 11x3 - 1T90 - homogeneous \addplot[line width=\linewidth,mark size=\markersize,blue,smooth,mark=*,mark options={fill=white}] table{ 10 6.573287 20 8.492317 30 6.019651 40 3.632297 50 2.409097 60 1.185425 70 0.222977 80 0.000038 90 0.000079 100 0.000064 110 0.000032 120 0.000015 130 0.000004 140 0.000000 150 0.008791 }; \addlegendentry{$11\times 3-1\cdot t_{90^ {\circ}}$, homogeneous $70\%$}; % 11x5 - 1T90 - homogeneous \addplot[line width=\linewidth,mark size=\markersize,blue,smooth,mark=square*,mark options={fill=white}] table{ 10 6.581882 20 8.572629 30 6.004670 40 3.645788 50 2.426733 60 1.201098 70 0.199733 80 0.000037 90 0.000069 100 0.000076 110 0.000045 120 0.000016 130 0.000004 140 0.000000 150 0.009135 }; \addlegendentry{$11\times 5-1\cdot t_{90^ {\circ}}$, homogeneous $70\%$}; % 11x7 - 1T90 - homogeneous \addplot[line width=\linewidth,mark size=\markersize,blue,smooth,mark=triangle*,mark options={fill=white}] table{ 10 6.580116 20 8.514992 30 6.049000 40 3.660323 50 2.443054 60 1.170430 70 0.214937 80 0.000036 90 0.000077 100 0.000063 110 0.000030 120 0.000015 130 0.000005 140 0.000000 150 0.009222 }; \addlegendentry{$11\times 7-1\cdot t_{90^ {\circ}}$, homogeneous $70\%$}; % 11x11 - 1T90 - homogeneous \addplot[line width=\linewidth,mark size=\markersize,blue,smooth,mark=diamond*,mark options={fill=white}] table{ 10 6.606424 20 8.518618 30 6.452988 40 3.776565 50 2.452888 60 1.287093 70 0.167092 80 0.000030 90 0.000075 100 0.000075 110 0.000044 120 0.000014 130 0.000004 140 0.000000 150 0.009264 }; \addlegendentry{$11\times 11-1\cdot t_{90^ {\circ}}$, homogeneous $70\%$}; \end{axis} %Tikz axis ends% \end{tikzpicture} %Tikz picture ends% \end{document} %----------------------------------------------------------------------------------------------% %----------------------------------------------------------------------------------------------% % DOCUMENT ENDS %----------------------------------------------------------------------------------------------% %----------------------------------------------------------------------------------------------%
LucaDiStasio/thinPlyMechanics
tex/04_Preprints/16_debonds-microstructure-clustering/11xk-1t90-vf70-GI.tex
TeX
apache-2.0
5,682
# Allantodia yaoshanicola Ching SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Pteridophyta/Polypodiopsida/Polypodiales/Woodsiaceae/Allantodia/Allantodia yaoshanicola/README.md
Markdown
apache-2.0
179
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("GenerateDocsFromSintacticParser")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("GenerateDocsFromSintacticParser")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("bfcfb58d-c7e3-4c6d-97d8-a9df90e14b2c")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
gcvalderrama/Jarvis
Lincoln/01DocumentExpansion/Jarvis/GenerateDocsFromSintacticParser/Properties/AssemblyInfo.cs
C#
apache-2.0
1,438
# Stirtonia psoromica Aptroot & Wolseley SPECIES #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Fungi/Ascomycota/Arthoniomycetes/Arthoniales/Arthoniaceae/Stirtonia/Stirtonia psoromica/README.md
Markdown
apache-2.0
196
# Sedum annuum subsp. gussonei Brullo & Spamp. SUBSPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Saxifragales/Crassulaceae/Sedum/Sedum annuum/Sedum annuum gussonei/README.md
Markdown
apache-2.0
197
require 'spec_helper' describe 'kubernetes::proxy' do context 'with default values for all parameters' do it { should contain_class('kubernetes::proxy') } it 'should install kube-proxy package' do is_expected.to contain_package('kube-proxy') end it 'should configure upstart' do is_expected.to contain_file('/etc/init/kube-proxy.conf') end it 'should configure opts' do is_expected.to contain_file('/etc/default/kube-proxy') end it 'should start kube-proxy service' do is_expected.to contain_service('kube-proxy') end end end
mwhahaha/fuel-plugin-kubernetes
deployment_scripts/puppet/modules/kubernetes/spec/classes/proxy_spec.rb
Ruby
apache-2.0
594
name "cloudify-agent" ENV['CORE_TAG_NAME'] || raise('CORE_TAG_NAME environment variable not set') default_version ENV['CORE_TAG_NAME'] source :git => "https://github.com/cloudify-cosmo/cloudify-agent" build do command ["#{install_dir}/embedded/bin/pip", "install", "--build=#{project_dir}/cloudify-agent", "."] end
isaac-s/cloudify-manager
packaging/mgmtworker/omnibus/config/software/cloudify-agent.rb
Ruby
apache-2.0
330
package org.ssh.pm.common.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang.StringUtils; /** * 用户请求过滤器,用以判断当前用户的Session是否超时,若超时则跳转至登录页面 */ public class CheckSessionFilter implements Filter { public static final String EXCLUDE_URI = "excludeUri"; public static final String INCLUDE_SUFFIXS_NAME = "includeSuffixs"; public static final String LOGIN_URI_NAME = "loginUri"; private static final String[] DEFAULT_EXCLUDE_URI = { "login.htm", "logon.htm", "main.htm", "logout.htm", "initData.htm", "updatepassword.htm" }; private static final String[] DEFAULT_INCLUDE_SUFFIXS = { ".htm" }; private static final String DEFAULT_LOGIN_URI = "login.htm"; private String[] excludeUri = DEFAULT_EXCLUDE_URI; private String[] includeSuffixs = DEFAULT_INCLUDE_SUFFIXS; private String loginUri = DEFAULT_LOGIN_URI; private FilterConfig filterConfig = null; @Override public void init(FilterConfig arg0) throws ServletException { this.filterConfig = arg0; String excludeUriStr = this.filterConfig.getInitParameter(EXCLUDE_URI); String incluedSuffixs = this.filterConfig .getInitParameter(INCLUDE_SUFFIXS_NAME); String loginUriName = this.filterConfig .getInitParameter(LOGIN_URI_NAME); if (StringUtils.isNotBlank(excludeUriStr)) { excludeUri = excludeUriStr.split(","); } if (StringUtils.isNotBlank(incluedSuffixs)) { this.includeSuffixs = incluedSuffixs.split(","); // 处理匹配字符串为".后缀名" for (int i = 0; i < includeSuffixs.length; i++) { includeSuffixs[i] = "." + includeSuffixs[i]; } } if (StringUtils.isNotBlank(loginUriName)) { loginUri = loginUriName; } } @Override public void destroy() { filterConfig = null; } /** * 当Session超时时,跳转至登录页面 */ @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpservletrequest = (HttpServletRequest) request; String uriStr = httpservletrequest.getServletPath().toLowerCase(); boolean needCheck = false; for (String suffix : includeSuffixs) { if (uriStr.endsWith(suffix)) { needCheck = true; } } if (needCheck) { for (String uri : excludeUri) { if (uriStr.indexOf(uri.toLowerCase()) > 0) { needCheck = false; break; } } } if (needCheck) { Object userId = httpservletrequest.getSession(true).getAttribute( "userId"); if (userId == null || "".equals(userId.toString())) { String contPath = httpservletrequest.getContextPath() + loginUri; StringBuffer sb = new StringBuffer(); sb.append("<html>"); sb.append("<script language='javascript'>"); sb.append("window.top.open ('" + contPath + "','_top');"); sb.append("</script>"); sb.append("</html>"); response.getWriter().println(sb.toString()); response.getWriter().flush(); } else { chain.doFilter(request, response); } } else { chain.doFilter(request, response); } } }
yangjiandong/sshapp
application/pm/src/main/java/org/ssh/pm/common/filter/CheckSessionFilter.java
Java
apache-2.0
3,480
package com.googlecode.totallylazy; import com.googlecode.totallylazy.time.Dates; import org.junit.Test; import static com.googlecode.totallylazy.Arrays.list; import static com.googlecode.totallylazy.Sequences.sequence; import static com.googlecode.totallylazy.Strings.join; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; public class IteratorsTest { @Test public void supportsEquality() throws Exception { assertThat(Iterators.equalsTo(list(1, 2, 3).iterator(), list(1, 2, 3).iterator()), is(true)); assertThat(Iterators.equalsTo(list(1, 2, 3).iterator(), list(3, 2, 1).iterator()), is(false)); assertThat(Iterators.equalsTo(list(1, 2, 3).iterator(), list("1", "2", "3").iterator()), is(false)); assertThat(Iterators.equalsTo(list(1, 2).iterator(), list(1, 2, 3).iterator()), is(false)); assertThat(Iterators.equalsTo(list(1, 2, 3).iterator(), list(1, 2).iterator()), is(false)); assertThat(Iterators.equalsTo(sequence(1, 2, 3).iterator(), list(1, 2, 3).iterator()), is(true)); assertThat(Iterators.equalsTo(sequence(Dates.date(2000, 1, 1), 1).iterator(), sequence(Dates.date(2000, 1, 1), 1).iterator()), is(true)); assertThat(Iterators.equalsTo(sequence(Dates.date(2000, 1, 1), 1).iterator(), sequence(null, 1).iterator()), is(false)); assertThat(Iterators.equalsTo(sequence(null, 1).iterator(), sequence(Dates.date(2000, 1, 1), 1).iterator()), is(false)); assertThat(Iterators.equalsTo(sequence(1, null, 3).iterator(), sequence(1, 2, 3).iterator()), is(false)); assertThat(Iterators.equalsTo(sequence(1, 2, 3).iterator(), sequence(1, null, 3).iterator()), is(false)); assertThat(Iterators.equalsTo(sequence(1, null, 3).iterator(), sequence(1, null, 3).iterator()), is(true)); } }
bodar/totallylazy
test/com/googlecode/totallylazy/IteratorsTest.java
Java
apache-2.0
1,840
<?php require('core.php'); $filename = dirname($_SERVER['SCRIPT_FILENAME']); $f = file_get_contents($filename . '/groc'); $gl = unserialize($f) ; print "<pre>"; print_r($gl); print "</pre>";
shavez00/groceryList
test2.php
PHP
apache-2.0
194
var Portfolio = function () { this.performance = []; this.dateToIndexMap = []; var index = 0; for (var i = 0; i <= 30; i++) { var date = moment().subtract(30 - i, 'days'); if (date.day() != 0 && date.day() != 6) { var formattedDate = date.format("YYYY-MM-DD"); this.performance[index] = {date: formattedDate, portfolio: new PortfolioFIFO()}; this.dateToIndexMap[formattedDate] = index; index++; } } } Portfolio.prototype = { buyStock: function (symbol, amount, price, date) { var dateObject = moment(date, "YYYY-MM-DD"); if (dateObject.isBefore(this.performance[0].date)) { for (var i = 0; i < this.performance.length; i++) { this.performance[i].portfolio.push(symbol, amount, price); } } else { for (var i = 0; i < 30; i++) { var formattedDate = dateObject.format("YYYY-MM-DD"); if (formattedDate in this.dateToIndexMap) { this.performance[this.dateToIndexMap[formattedDate]].portfolio.push(symbol, amount, price); } dateObject.add(1, 'days'); } } }, sellStock: function (symbol, amount, date) { // Adjust date to a weekday var dateObject = moment(date, "YYYY-MM-DD"); if (dateObject.isBefore(this.performance[0].date)) { for (var i = 0; i < this.performance.length; i++) { this.performance[i].portfolio.pop(symbol, amount); } } else { for (var i = 0; i < this.performance.length; i++) { var formattedDate = dateObject.format("YYYY-MM-DD"); if (formattedDate in this.dateToIndexMap) { this.performance[this.dateToIndexMap[formattedDate]].portfolio.pop(symbol, amount); } dateObject.add(1, 'days'); } } }, cost: function (date) { if (date in this.dateToIndexMap) { var dayData = this.performance[this.dateToIndexMap[date]]; return dayData.portfolio.cost(); } else { console.log("cost(): Oops. Didn't find day in history data [" + date + "]"); return 0; } }, value: function (date) { if (date in this.dateToIndexMap) { var dayData = this.performance[this.dateToIndexMap[date]]; return dayData.portfolio.value(); } else { console.log("value(): Oops. Didn't find day in history data [" + date + "]"); return 0; } }, setClosePrice: function (symbol, closePrice, date) { if (date in this.dateToIndexMap) { var dayData = this.performance[this.dateToIndexMap[date]]; dayData.portfolio.setClosePrice(symbol, closePrice); } else { console.log("setClosePrice(): Oops. Didn't find day in history data [" + date + "]"); } }, getHistoryPerformance: function () { this._padMissingDays(); var history = []; for (var i = 0; i < this.performance.length; i++) { var value = this.performance[i].portfolio.value(); var cost = this.performance[i].portfolio.cost(); if(value > 0 && cost > 0) { var relative = (100 * value / cost); history.push(relative); } } return history; }, getPortfolio: function () { return this.performance[this.performance.length - 1].portfolio; }, /** * Use previous day's close price if close price is missing (e.g. public holiday) * @private */ _padMissingDays: function () { var previousDay = this.performance[0].portfolio.getStockAndClose(); for (var i = 1; i < this.performance.length; i++) { var portfolio = this.performance[i].portfolio; var stockClosePrices = portfolio.getStockAndClose(); for (var symbol in stockClosePrices) { if (stockClosePrices[symbol] == undefined && symbol in previousDay) { stockClosePrices[symbol] = previousDay[symbol]; portfolio.setClosePrice(symbol, previousDay[symbol]); } } previousDay = stockClosePrices; } }, _adjustToWeekday: function (moment) { if (moment.day() == 0) { moment.add(1, 'days'); } else if (date.day() == 6) { moment.add(2, 'days'); } return moment; } };
vaadin-kim/stockwatcher-polymer
src/portfolio.js
JavaScript
apache-2.0
4,619
# Docker Hub Enterprise用户指南 本指南包含Docker DHE需要知道的功能和任务,例如push或者pull镜像等。对于DHE管理员需要完成的任务,例如配置和管理DHE,请阅读[DHE管理员指南](adminguide.md) ## 概述 对于DHE使用者最基础的使用示例就是push和pull镜像。例如,你可能pull官方镜像从Docker Hub,定制它通过配置相应的参数,然后push定制的镜像到你的DHE镜像存储,以提供给其他开发人员pull和使用。 Push和pull镜像的工作性质很像其他Docker registry:你使用docker pull命令获取镜像,dockerpush命令添加一个镜像到DHE私有库中去。为了了解docker镜像,请看用户指南:[了解Docker镜像](../Userguide/dockerimages.md)。为了一步步了解全部过程,请查看[快速开始:基本工作流指南](quick-start.md) > 说明:如果你的DHE实例需要有权限认证,你将需要使用你的命令行登录<dhe-hostname> (例如docker login dhe.yourdomain.com)。失败的认证会是这样的: > > $ docker pull dhe.yourdomain.com/hello-world > > Pulling repository dhe.yourdomain.com/hello-world > > FATA[0001] Error: image hello-world:latest not found > > $ docker push dhe.yourdomain.com/hello-world > > The push refers to a repository [dhe.yourdomain.com/hello-world] (len: 1) > > e45a5af57b00: Image push failed > > FATA[0001] Error pushing to registry: token auth attempt for registry > > https://dhe.yourdomain.com/v2/: > > https://dhe.yourdomain.com/auth/v2/token/?scope= > > repository%3Ahello-world%3Apull%2Cpush&service=dhe.yourdomain.com > > request failed with status: 401 Unauthorized ## Push镜像 通过使用Docker push命令将镜像push到DHE上去。 你可以给你的镜像打一个tag,因此你可以更多容易从很多版本中识别它。 `$ docker tag hello-world:latest dhe.yourdomain.com/yourusername/hello-mine:latest` 命令中的标签`hello-world:latest`镜像使用了一个新的tag,以 `[REGISTRYHOST/][USERNAME/]NAME[:TAG]`的形式。在例子中,REGISTRYHOST是你的DHE服务器,`dhe.yourdomain.com`。USERNAME是你的用户名。最后,镜像tag就设置的是`hello-mine:latest`。 一旦镜像被tag,你可以push它到DHE上,使用如下命令行: `$ docker push dhe.yourdomain.com/demouser/hello-mine:latest` 说明:如果docker daemon,push的权限错误,你将得到一个相似的错误信息: $ docker push dhe.yourdomain.com/demouser/hello-world FATA[0000] Error response from daemon: v1 ping attempt failed with error: Get https://dhe.yourdomain.com/v1/_ping: x509: certificate signed by unknown authority. If this private registry supports only HTTP or HTTPS with an unknown CA certificate, please add `--insecure-registry dhe.yourdomain.com` to the daemon's arguments. In the case of HTTPS, if you have access to the registry's CA certificate, no need for the flag; simply place the CA certificate at /etc/docker/certs.d/dhe.yourdomain.com/ca.crt ## Pull镜像 你可以获取一个镜像通过docker pull命令,或者获取一个镜像并启动容器通过docker run命令。 为了获取镜像从DHE,启动容器,docker run命令需要添加如下的信息: $ docker run dhe.yourdomain.com/yourusername/hello-mine latest: Pulling from dhe.yourdomain.com/yourusername/hello-mine 511136ea3c5a: Pull complete 31cbccb51277: Pull complete e45a5af57b00: Already exists Digest: sha256:45f0de377f861694517a1440c74aa32eecc3295ea803261d62f950b1b757bed1 Status: Downloaded newer image for dhe.yourdomain.com/demouser/hello-mine:latest 注意,如果你没有指定了版本号,默认将pull latest版本的镜像。 如果你运行docker images,你将看到hello-mine镜像。 $ docker images REPOSITORY TAG IMAGE ID CREATED VIRTUAL SIZE dhe.yourdomain.com/yourusername/hello-mine latest e45a5af57b00 3 months ago 910 B 为了不使用构建容器的方式pull镜像,使用docker pull指定你的DHE私有库来添加镜像。 $ docker pull dhe.yourdomain.com/yourusername/hello-mine ## 下一步 为了了解更多管理DHE,请阅读[DHE管理员指南](adminguide.md)
liuhong1happy/dockerdocs
DockerHubEnterprise/userguide.md
Markdown
apache-2.0
4,250
# Baccharis rufescens Spreng. SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Baccharis/Baccharis rufescens/README.md
Markdown
apache-2.0
177
<!-- THIS IS AUTO-GENERATED CONTENT. DO NOT MANUALLY EDIT. --> This image is part of the [balena.io][balena] base image series for IoT devices. The image is optimized for use with [balena.io][balena] and [balenaOS][balena-os], but can be used in any Docker environment running on the appropriate architecture. ![balenalogo](https://avatars2.githubusercontent.com/u/6157842?s=200&v=4). Some notable features in `balenalib` base images: - Helpful package installer script called `install_packages` that abstracts away the specifics of the underlying package managers. It will install the named packages with smallest number of dependencies (ignore optional dependencies), clean up the package manager medata and retry if package install fails. - Working with dynamically plugged devices: each `balenalib` base image has a default `ENTRYPOINT` which is defined as `ENTRYPOINT ["/usr/bin/entry.sh"]`, it checks if the `UDEV` flag is set to true or not (by adding `ENV UDEV=1`) and if true, it will start `udevd` daemon and the relevant device nodes in the container /dev will appear. For more details, please check the [features overview](https://www.balena.io/docs/reference/base-images/base-images/#features-overview) in our documentation. # [Image Variants][variants] The `balenalib` images come in many flavors, each designed for a specific use case. ## `:<version>` or `:<version>-run` This is the defacto image. The `run` variant is designed to be a slim and minimal variant with only runtime essentials packaged into it. ## `:<version>-build` The build variant is a heavier image that includes many of the tools required for building from source. This reduces the number of packages that you will need to manually install in your Dockerfile, thus reducing the overall size of all images on your system. [variants]: https://www.balena.io/docs/reference/base-images/base-images/#run-vs-build?ref=dockerhub # How to use this image with Balena This [guide][getting-started] can help you get started with using this base image with balena, there are also some cool [example projects][example-projects] that will give you an idea what can be done with balena. # What is Go? Go (a.k.a., Golang) is a programming language first developed at Google. It is a statically-typed language with syntax loosely derived from C, but with additional features such as garbage collection, type safety, some dynamic-typing capabilities, additional built-in types (e.g., variable-length arrays and key-value maps), and a large standard library. > [wikipedia.org/wiki/Go_(programming_language)](http://en.wikipedia.org/wiki/Go_%28programming_language%29) ![logo](https://raw.githubusercontent.com/docker-library/docs/01c12653951b2fe592c1f93a13b4e289ada0e3a1/golang/logo.png) # Supported versions and respective `Dockerfile` links : [&#x60;1.6 (latest)&#x60;, &#x60;1.15.8&#x60;, &#x60;1.14.14&#x60;](https://github.com/balena-io-library/base-images/tree/master/balena-base-images/golang/raspberry-pi2/alpine/) For more information about this image and its history, please see the [relevant manifest file (`raspberry-pi2-alpine-golang`)](https://github.com/balena-io-library/official-images/blob/master/library/raspberry-pi2-alpine-golang) in the [`balena-io-library/official-images` GitHub repo](https://github.com/balena-io-library/official-images). # How to use this image ## Start a Go instance in your app The most straightforward way to use this image is to use a Go container as both the build and runtime environment. In your `Dockerfile`, writing something along the lines of the following will compile and run your project: ```dockerfile FROM balenalib/raspberry-pi2-alpine-golang:latest WORKDIR /go/src/app COPY . . RUN go get -d -v ./... RUN go install -v ./... CMD ["app"] ``` You can then build and run the Docker image: ```console $ docker build -t my-golang-app . $ docker run -it --rm --name my-running-app my-golang-app ``` ## Compile your app inside the Docker container There may be occasions where it is not appropriate to run your app inside a container. To compile, but not run your app inside the Docker instance, you can write something like: ```console $ docker run --rm -v "$PWD":/usr/src/myapp -w /usr/src/myapp balenalib/raspberry-pi2-alpine-golang:latest go build -v ``` This will add your current directory as a volume to the container, set the working directory to the volume, and run the command `go build` which will tell go to compile the project in the working directory and output the executable to `myapp`. [example-projects]: https://www.balena.io/docs/learn/getting-started/raspberry-pi2/go/#example-projects?ref=dockerhub [getting-started]: https://www.balena.io/docs/learn/getting-started/raspberry-pi2/go/?ref=dockerhub # User Feedback ## Issues If you have any problems with or questions about this image, please contact us through a [GitHub issue](https://github.com/balena-io-library/base-images/issues). ## Contributing You are invited to contribute new features, fixes, or updates, large or small; we are always thrilled to receive pull requests, and do our best to process them as fast as we can. Before you start to code, we recommend discussing your plans through a [GitHub issue](https://github.com/balena-io-library/base-images/issues), especially for more ambitious contributions. This gives other contributors a chance to point you in the right direction, give you feedback on your design, and help you find out if someone else is working on the same thing. ## Documentation Documentation for this image is stored in the [base images documentation][docs]. Check it out for list of all of our base images including many specialised ones for e.g. node, python, go, smaller images, etc. You can also find more details about new features in `balenalib` base images in this [blog post][migration-docs] [docs]: https://www.balena.io/docs/reference/base-images/base-images/#balena-base-images?ref=dockerhub [variants]: https://www.balena.io/docs/reference/base-images/base-images/#run-vs-build?ref=dockerhub [migration-docs]: https://www.balena.io/blog/new-year-new-balena-base-images/?ref=dockerhub [balena]: https://balena.io/?ref=dockerhub [balena-os]: https://www.balena.io/os/?ref=dockerhub
nghiant2710/base-images
balena-base-images/docs/dockerhub/raspberry-pi2-alpine-golang-full-description.md
Markdown
apache-2.0
6,267
<!-- Portfolio Grid Section --> <section id="portfolio"> <div class="container"> <div class="row"> <div class="col-lg-12 text-center"> <h2>Apartment Communities</h2> <h4> (Click for more info) </h4> <!-- <hr class="star-primary"> --> </div> </div> <div class="row"> {% for post in site.posts %} <div class="col-sm-4 portfolio-item"> <h3>{{ post.title }}</h3> <a href="#portfolioModal-{{ post.modal-id }}" class="portfolio-link" data-toggle="modal"> <div class="caption"> <div class="caption-content"> <i class="fa fa-search-plus fa-3x"></i> </div> </div> <img src="img/apartments/{{ post.img }}" class="img-responsive" alt="{{ post.alt }}"> </a> </div> {% endfor %} </div> </div> </section>
themezzilla/kramer-saxl
_includes/apartments.html
HTML
apache-2.0
1,113
package com.intuso.housemate.client.v1_0.proxy.object; import com.google.inject.Inject; import com.google.inject.assistedinject.Assisted; import com.intuso.housemate.client.v1_0.api.object.Parameter; import com.intuso.housemate.client.v1_0.api.object.Tree; import com.intuso.housemate.client.v1_0.api.object.view.ParameterView; import com.intuso.housemate.client.v1_0.api.object.view.View; import com.intuso.housemate.client.v1_0.messaging.api.Receiver; import com.intuso.utilities.collection.ManagedCollection; import com.intuso.utilities.collection.ManagedCollectionFactory; import org.slf4j.Logger; import java.util.List; /** * @param <PARAMETER> the type of the parameter */ public abstract class ProxyParameter<TYPE extends ProxyType<?>, PARAMETER extends ProxyParameter<TYPE, PARAMETER>> extends ProxyObject<Parameter.Data, Parameter.Listener<? super PARAMETER>, ParameterView> implements Parameter<TYPE, PARAMETER> { /** * @param logger {@inheritDoc} */ public ProxyParameter(Logger logger, String path, String name, ManagedCollectionFactory managedCollectionFactory, Receiver.Factory receiverFactory) { super(logger, path, name, Parameter.Data.class, managedCollectionFactory, receiverFactory); } @Override public ParameterView createView(View.Mode mode) { return new ParameterView(mode); } @Override public Tree getTree(ParameterView view, Tree.ReferenceHandler referenceHandler, Tree.Listener listener, List<ManagedCollection.Registration> listenerRegistrations) { // register the listener addTreeListener(view, listener, listenerRegistrations); return new Tree(getData()); } @Override public TYPE getType() { return null; // todo get the type from somewhere } @Override public ProxyObject<?, ?, ?> getChild(String id) { return null; } /** * Created with IntelliJ IDEA. * User: tomc * Date: 14/01/14 * Time: 13:17 * To change this template use File | Settings | File Templates. */ public static final class Simple extends ProxyParameter<ProxyType.Simple, Simple> { @Inject public Simple(@Assisted Logger logger, @Assisted("path") String path, @Assisted("name") String name, ManagedCollectionFactory managedCollectionFactory, Receiver.Factory receiverFactory) { super(logger, path, name, managedCollectionFactory, receiverFactory); } } }
Intuso/housemate-client
proxy/src/main/java/com/intuso/housemate/client/v1_0/proxy/object/ProxyParameter.java
Java
apache-2.0
2,681
export default { name: "Zena", x: 0, y: 0, control: "us", zone: "green", star: { spectrum: "K", temperature: "0", size: "V" }, planets: [ { name: "Marider", shape: "terrestrial", size: "medium", atmosphere: "trace", hydrosphere: "dry", biosphere: "remnants", population: "6", government: "corporation", laws: "heavy", tech: "advanced", temperature: "cold", resources: "abundant", infrastructure: "high", spaceport: "10", satellites: "3", description: "Marider is controlled by various Thurid companies and boasts some of the best shipyards in US space.", tags: ["Multi-Corporate Control"] }, { name: "Thurid", shape: "terrestrial", size: "medium", atmosphere: "standard", hydrosphere: "moderate", biosphere: "compatible", population: "8", government: "representative", laws: "heavy", tech: "interstellar", temperature: "cold", resources: "high", infrastructure: "substantial", spaceport: "9", satellites: "1", description: "Thurid is known for it’s industrial output and lenient trading laws. The US council chambers are located here.", tags: [] }, { name: "Pikos", shape: "jovian", size: "colossal", atmosphere: "exotic", hydrosphere: "none", biosphere: "none", population: "0", government: "none", laws: "none", tech: "none", temperature: "varied", resources: "none", infrastructure: "none", spaceport: "0", satellites: "0", description: "Only gas giant in the system and a source of starship fuel.", tags: [] }, { name: "Central Command", shape: "station", size: "micro", atmosphere: "standard", hydrosphere: "none", biosphere: "engineered", population: "5", government: "participatory", laws: "extreme", tech: "foundational", temperature: "temperate", resources: "none", infrastructure: "covered", spaceport: "4", satellites: "0", description: "Central Command is the political capitol of the United Systems. It is a space station located at the edge of the \ Zena system, and is governed solely by the United Systems council.", tags: ["US Capital"] } ], description: "While Al-Taleqani and Careeno are the superpowers of \ interstellar politics, Zena is the close third. It’s position in the middle of the \ United Systems’ territory has meant that it has become the de-facto capital." }
almightynassar/BrokenStarsAndroid
src/data/regions/us-zena.js
JavaScript
apache-2.0
2,680
# # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER # # Copyright (c) 2015 Juniper Networks, Inc. # All rights reserved. # # Use is subject to license terms. # # Licensed under the Apache License, Version 2.0 (the ?License?); you may not # use this file except in compliance with the License. You may obtain a copy of # the License at http://www.apache.org/licenses/LICENSE-2.0. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # """ This module defines the Connection class. """ from __future__ import unicode_literals from __future__ import print_function from future import standard_library standard_library.install_aliases() from builtins import object import requests import logging class Connection(object): """ Creates a connection to Space Platform mimicking a GUI login. This class is **not** thread-safe. It is up to the users of the class to ensure thread safety. The ``rest.Space`` class uses this class for supporting session-based connections to Junos Space. Thread-safety requirements are met by that class. """ def __init__(self, homeurl, username=None, password=None, cert=None, our_ip=None): self._logger = logging.getLogger('root') self.homeurl = homeurl + '/mainui' self.authurl = homeurl + '/mainui/j_security_check' self.session = None if username is not None: if password is None: raise ValueError('password is mandatory along with username') if cert is not None: raise ValueError('You must provide only one of username+password or cert') else: if password is not None: raise ValueError('password is valid only along with username') if cert is None: raise ValueError('You must provide one of username+password or cert') self.username = username self.password = password self.our_ip = our_ip self.cert = cert self._logger.debug("Connection: Initiating login to %s", self.homeurl) self.login() def login(self): """ Login to Space """ self.session = requests.Session() sess = self.session if self.our_ip is None: resp = sess.get(self.homeurl, cert=self.cert, verify=False) #self._logger.debug(resp.status_code) #self._logger.debug(resp.headers) #self._logger.debug(resp.text) # Extract the ipAddr and code variables embbed in the form validation code ip_addr_start_idx = resp.text.find("var ipAddr = ") if ip_addr_start_idx < 0: self.check_login_status() return ip_addr_end_idx = resp.text.find("\n", ip_addr_start_idx) ip_addr_line = resp.text[ip_addr_start_idx : ip_addr_end_idx] ip_addr_items = ip_addr_line.split("=", 2) ip_addr = ip_addr_items[1].strip("'; ").strip() #codeStartIdx = r.text.find("var code = ", ip_addr_end_idx); #codeEndIdx = r.text.find("\n", codeStartIdx); #codeLine = r.text[codeStartIdx : codeEndIdx] #codeItems = codeLine.split("=", 2); #code = codeItems[1].strip("'; ").strip();''' #form_username = self.username + '%' + code + '@' + ip_addr; else: resp = sess.get(self.homeurl, cert=self.cert, verify=False) ip_addr = self.our_ip form_username = self.username + '@' + ip_addr data = { "j_screen_username" : self.username, "j_username" : form_username, "j_password" : self.password } self._logger.debug(data) resp = sess.post(self.authurl, data=data, cert=self.cert, verify=False) #self._logger.debug(resp.status_code) #self._logger.debug(resp.headers) #self._logger.debug(resp.text) self.check_login_status() def is_logged_in(self): """ Checks if a login has been established """ return self.session is not None def check_login_status(self): """ Check login-status """ if not self.is_logged_in(): raise Exception("Not logged in") resp = self.session.get(self.homeurl, verify=False) ip_addr_start_idx = resp.text.find("var ipAddr = ") if ip_addr_start_idx >= 0: raise Exception("Not in a logged-in session.") def get_session(self): """ Return the HTTP session object """ if self.is_logged_in(): return self.session else: raise Exception("Not logged in") def logout(self): """ Logout from Space Server """ logout_url = self.homeurl + "/unsecured/logout.jsp" resp = self.session.get(logout_url, verify=False) #self._logger.debug(resp.status_code) #self._logger.debug(resp.headers) #self._logger.debug(resp.text) if resp.status_code == 200: self.session = None
Juniper/py-space-platform
jnpr/space/connection.py
Python
apache-2.0
5,362
import Utils from Utils import printe class CommandBuilder(object): def __init__(self, *command_args): self.command_args = list(command_args) def append(self, *args): for arg in args: if isinstance(arg, str): self.command_args += [arg] elif isinstance(arg, list) or isinstance(arg, tuple): for sub_arg in arg: self.append(sub_arg) else: printe('Error appending argument of unknown type: {}'.format( str(type(arg))), terminate=True) return self def debug(self): return Utils.debug(*self.command_args) def run(self, replaceForeground=False): return Utils.run(*self.command_args, replaceForeground=replaceForeground)
bytejive/lazy-docker
CommandBuilder.py
Python
apache-2.0
828
/** * Copyright 2014 Christian Kreutzfeldt * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.mnxfst.streams.webtrends.kafka.socket; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.Date; import java.util.HashMap; import java.util.Map; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import org.apache.commons.codec.binary.Base64; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; /** * Describes the request to be initiated with {@linkplain http://streams.webtrends.com webtrends stream api} in order * to fetch a token required for further communication. See {@linkplain https://github.com/Webtrends/Streams-OAuth-Libraries} for * more detailed information * @author mnxfst * @since 28.02.2014 */ public class WebtrendsTokenRequest { protected final String REQUEST_PARAM_CLIENT_ID = "client_id"; protected final String REQUEST_PARAM_CLIENT_ASSERTION = "client_assertion"; public String audience = "auth.webtrends.com"; public String scope = "sapi.webtrends.com"; public String authUrl = "https://sauth.webtrends.com/v1/token"; public String expiration; private String clientId; private String clientSecret; public WebtrendsTokenRequest(String authUrl, String audience, String scope, String clientId, String clientSecret) { this.authUrl = authUrl; this.audience = audience; this.scope = scope; this.clientId = clientId; this.clientSecret = clientSecret; expiration = String.valueOf((new Date()).getTime() + (30 * 60)); } public String execute() throws Exception { final String assertion = buildAssertion(); final Map<String, String> requestParams = new HashMap<String, String>() { private static final long serialVersionUID = 1919397363313726934L; { put(REQUEST_PARAM_CLIENT_ID, clientId); put(REQUEST_PARAM_CLIENT_ASSERTION, java.net.URLEncoder.encode(assertion, "UTF-8")); } }; final String result = httpPost(requestParams); ObjectMapper mapper = new ObjectMapper(); JsonFactory factory = mapper.getFactory(); JsonParser jp = factory.createParser(result); JsonNode obj = mapper.readTree(jp); JsonNode error = obj.findValue("Error"); if (error != null) throw new Exception(obj.findValue("Description").asText()); return obj.findValue("access_token").asText(); } private String buildAssertion() { // Json representation of the header final String header = "{\"typ\":\"JWT\", \"alg\":\"HS256\"}"; // Token will expire in one day // Json representation of the claims set final String claims = "{\"iss\":\"" + clientId + "\",\"prn\":\"" + clientId + "\",\"aud\":\"" + audience + "\",\"exp\":" + expiration + ",\"scope\":\"" + scope + "\" }"; // Base64Encode the component parts final String encodedHeader = base64Encode(header); final String encodedClaims = base64Encode(claims); // The content to be hashed final String message = String.format("%s.%s", encodedHeader, encodedClaims); final String signature = getHMAC256(message, clientSecret); return String.format("%s.%s.%s", encodedHeader, encodedClaims, signature); } private static String base64Encode(final String input) { return new String(Base64.encodeBase64(input.getBytes())); } private static String base64Encode(final byte[] input) { return new String(Base64.encodeBase64(input)); } private String getHMAC256(final String input, final String secret) { String temp = null; final SecretKeySpec keySpec = new SecretKeySpec(secret.getBytes(), "HmacSHA256"); try { final Mac mac = Mac.getInstance("HmacSHA256"); mac.init(keySpec); // update method adds the given byte to the Mac's input data. mac.update(input.getBytes()); final byte[] m = mac.doFinal(); // The base64-encoder in Commons Codec temp = base64Encode(m); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } return temp; } private String httpPost(Map<String, String> requestParams) throws Exception { final URL url = new URL(authUrl); final StringBuilder data = new StringBuilder(); for (String key : requestParams.keySet()) data.append(String.format("%s=%s&", key, requestParams.get(key))); final String dataString = data.toString(); final String formData = dataString.substring(0, dataString.length() - 1); final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded"); connection.setDoOutput(true); final OutputStream outputStream = connection.getOutputStream(); final OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream); outputStreamWriter.write(formData); outputStreamWriter.flush(); InputStream is = connection.getResponseCode() != 400 ? connection.getInputStream() : connection.getErrorStream(); final BufferedReader rd = new BufferedReader(new InputStreamReader(is)); final StringBuffer stringBuffer = new StringBuffer(); String line; while ((line = rd.readLine()) != null) stringBuffer.append(line); outputStreamWriter.close(); rd.close(); if (connection.getResponseCode() == 400) throw new Exception("error: " + stringBuffer.toString()); return stringBuffer.toString(); } }
mnxfst/webtrends-kafka-producer
src/main/java/com/mnxfst/streams/webtrends/kafka/socket/WebtrendsTokenRequest.java
Java
apache-2.0
6,519
/* * Copyright 2014 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Text; namespace ZXing.Client.Result { /// <summary> /// Represents a parsed result that encodes a Vehicle Identification Number (VIN). /// </summary> public class VINParsedResult : ParsedResult { public String VIN { get; private set; } public String WorldManufacturerID { get; private set; } public String VehicleDescriptorSection { get; private set; } public String VehicleIdentifierSection { get; private set; } public String CountryCode { get; private set; } public String VehicleAttributes { get; private set; } public int ModelYear { get; private set; } public char PlantCode { get; private set; } public String SequentialNumber { get; private set; } public VINParsedResult(String vin, String worldManufacturerID, String vehicleDescriptorSection, String vehicleIdentifierSection, String countryCode, String vehicleAttributes, int modelYear, char plantCode, String sequentialNumber) : base(ParsedResultType.VIN) { VIN = vin; WorldManufacturerID = worldManufacturerID; VehicleDescriptorSection = vehicleDescriptorSection; VehicleIdentifierSection = vehicleIdentifierSection; CountryCode = countryCode; VehicleAttributes = vehicleAttributes; ModelYear = modelYear; PlantCode = plantCode; SequentialNumber = sequentialNumber; } public override string DisplayResult { get { var result = new StringBuilder(50); result.Append(WorldManufacturerID).Append(' '); result.Append(VehicleDescriptorSection).Append(' '); result.Append(VehicleIdentifierSection).Append('\n'); if (CountryCode != null) { result.Append(CountryCode).Append(' '); } result.Append(ModelYear).Append(' '); result.Append(PlantCode).Append(' '); result.Append(SequentialNumber).Append('\n'); return result.ToString(); } } } }
bsoja/ZXing.Net
Source/lib/client/result/VINParsedResult.cs
C#
apache-2.0
2,999
include_recipe 'bcpc-hadoop::hadoop_config' include_recipe 'bcpc-hadoop::hive_config' node.default['bcpc']['hadoop']['copylog']['datanode'] = { 'logfile' => "/var/log/hadoop-hdfs/hadoop-hdfs-datanode-#{node.hostname}.log", 'docopy' => true } %w{hadoop-yarn-nodemanager hadoop-hdfs-datanode hadoop-mapreduce hadoop-client sqoop lzop hadoop-lzo}.each do |pkg| package pkg do action :upgrade end end user_ulimit "root" do filehandle_limit 32769 process_limit 65536 end user_ulimit "hdfs" do filehandle_limit 32769 process_limit 65536 end user_ulimit "mapred" do filehandle_limit 32769 process_limit 65536 end user_ulimit "yarn" do filehandle_limit 32769 process_limit 65536 end template "/etc/init.d/hadoop-hdfs-datanode" do source "hdp_hadoop-hdfs-datanode-initd.erb" mode 0655 end template "/etc/init.d/hadoop-yarn-nodemanager" do source "hdp_hadoop-yarn-nodemanager-initd.erb" mode 0655 end directory "/usr/hdp/current/hadoop-client/lib/native/Linux-amd64-64" do action :create mode 0755 recursive true end link "/usr/hdp/current/hadoop-client/lib/hadoop-lzo-0.6.0.jar" do to "/usr/lib/hadoop/lib/hadoop-lzo-0.6.0.jar" end link "/usr/hdp/current/hadoop-client/lib/native/Linux-amd64-64/libgplcompression.la" do to "/usr/lib/hadoop/lib/native/Linux-amd64-64/libgplcompression.la" end link "/usr/hdp/current/hadoop-client/lib/native/Linux-amd64-64/libgplcompression.a" do to "/usr/lib/hadoop/lib/native/Linux-amd64-64/libgplcompression.a" end link "/usr/hdp/current/hadoop-client/lib/native/Linux-amd64-64/libgplcompression.so" do to "/usr/lib/hadoop/lib/native/Linux-amd64-64/libgplcompression.so.0.0.0" end link "/usr/hdp/current/hadoop-client/lib/native/liblzo2.so" do to "/usr/lib/x86_64-linux-gnu/liblzo2.so.2.0.0" end # Install YARN Bits template "/etc/hadoop/conf/container-executor.cfg" do source "hdp_container-executor.cfg.erb" owner "root" group "yarn" mode "0400" variables(:mounts => node[:bcpc][:hadoop][:mounts]) action :create notifies :run, "bash[verify-container-executor]", :immediate end bash "verify-container-executor" do code "/usr/lib/hadoop-yarn/bin/container-executor --checksetup" group "yarn" action :nothing only_if { File.exists?("/usr/lib/hadoop-yarn/bin/container-executor") } end # Install Sqoop Bits template "/etc/sqoop/conf/sqoop-env.sh" do source "sq_sqoop-env.sh.erb" mode "0444" action :create end # Install Hive Bits # workaround for hcatalog dpkg not creating the hcat user it requires user "hcat" do username "hcat" system true shell "/bin/bash" home "/usr/lib/hcatalog" supports :manage_home => false end package 'hive-hcatalog' do action :upgrade end link "/usr/hdp/current/hive-metastore/lib/mysql-connector-java.jar" do to "/usr/share/java/mysql-connector-java.jar" end link "/usr/hdp/current/hive-server2/lib/mysql-connector-java.jar" do to "/usr/share/java/mysql-connector-java.jar" end # Setup datanode and nodemanager bits if node[:bcpc][:hadoop][:mounts].length <= node[:bcpc][:hadoop][:hdfs][:failed_volumes_tolerated] Chef::Application.fatal!("You have fewer #{node[:bcpc][:hadoop][:disks]} than #{node[:bcpc][:hadoop][:hdfs][:failed_volumes_tolerated]}! See comments of HDFS-4442.") end # Build nodes for HDFS storage node[:bcpc][:hadoop][:mounts].each do |i| directory "/disk/#{i}/dfs" do owner "hdfs" group "hdfs" mode 0700 action :create end directory "/disk/#{i}/dfs/dn" do owner "hdfs" group "hdfs" mode 0700 action :create end end # Build nodes for YARN log storage node[:bcpc][:hadoop][:mounts].each do |i| directory "/disk/#{i}/yarn/" do owner "yarn" group "yarn" mode 0755 action :create end %w{mapred-local local logs}.each do |d| directory "/disk/#{i}/yarn/#{d}" do owner "yarn" group "hadoop" mode 0755 action :create end end end # # When there is a need to restart datanode, a lock need to be taken so that the restart is sequenced preventing all DNs being down at the sametime # If there is a failure in acquiring a lock with in a certian period, the restart is scheduled for the next run on chef-client on the node. # To determine whether the prev restart failed is the node attribute node[:bcpc][:hadoop][:datanode][:restart_failed] is set to true # This ruby block is to check whether this node attribute is set to true and if it is set then gets the DN restart process in motion. # ruby_block "handle_prev_datanode_restart_failure" do block do Chef::Log.info "Need to restart DN since it failed during the previous run. Another node's DN restart process failure is a possible reason" end action :create only_if { node[:bcpc][:hadoop][:datanode][:restart_failed] } end # # Since string with all the zookeeper nodes is used multiple times this variable is populated once and reused reducing calls to Chef server # zk_hosts = (get_node_attributes(HOSTNAME_ATTR_SRCH_KEYS,"zookeeper_server","bcpc-hadoop").map{|zkhost| "#{float_host(zkhost['hostname'])}:#{node[:bcpc][:hadoop][:zookeeper][:port]}"}).join(",") # # znode is used as the locking mechnism to control restart of services. The following code is to build the path # to create the znode before initiating the restart of HDFS datanode service # if (! node[:bcpc][:hadoop][:restart_lock].attribute?(:root) or node[:bcpc][:hadoop][:restart_lock][:root].nil?) lock_znode_path = "/hadoop-hdfs-datanode" elsif (node[:bcpc][:hadoop][:restart_lock][:root] == "/") lock_znode_path = "/hadoop-hdfs-datanode" else lock_znode_path = "#{node[:bcpc][:hadoop][:restart_lock][:root]}/hadoop-hdfs-datanode" end # # All datanode restart situations like changes in config files or restart due to previous failures invokes this ruby_block # This ruby block tries to acquire a lock and if not able to acquire the lock, sets the restart_failed node attribute to true # ruby_block "acquire_lock_to_restart_datanode" do block do tries = 0 Chef::Log.info("#{node[:hostname]}: Acquring lock at #{lock_znode_path}") while true lock = acquire_restart_lock(lock_znode_path, zk_hosts, node[:fqdn]) if lock break else tries += 1 if tries >= node[:bcpc][:hadoop][:restart_lock_acquire][:max_tries] Chef::Log.info("Couldn't acquire lock to restart datanode with in the #{node[:bcpc][:hadoop][:restart_lock_acquire][:max_tries] * node[:bcpc][:hadoop][:restart_lock_acquire][:sleep_time]} secs.") Chef::Log.info("Node #{get_restart_lock_holder(lock_znode_path, zk_hosts)} may have died during datanode restart.") node.set[:bcpc][:hadoop][:datanode][:restart_failed] = true node.save break end sleep(node[:bcpc][:hadoop][:restart_lock_acquire][:sleep_time]) end end end action :nothing subscribes :create, "template[/etc/hadoop/conf/hdfs-site.xml]", :immediate subscribes :create, "template[/etc/hadoop/conf/hadoop-env.sh]", :immediate subscribes :create, "template[/etc/hadoop/conf/topology]", :immediate subscribes :create, "user_ulimit[hdfs]", :immediate subscribes :create, "user_ulimit[root]", :immediate subscribes :create, "ruby_block[handle_prev_datanode_restart_failure]", :immediate end # # If lock to restart datanode is acquired by the node, this ruby_block executes which is primarily used to notify the datanode service to restart # ruby_block "coordinate_datanode_restart" do block do Chef::Log.info("Data node will be restarted in node #{node[:fqdn]}") end action :create only_if { my_restart_lock?(lock_znode_path, zk_hosts, node[:fqdn]) } end service "hadoop-hdfs-datanode" do supports :status => true, :restart => true, :reload => false action [:enable, :start] subscribes :restart, "ruby_block[coordinate_datanode_restart]", :immediate end # # Once the datanode service restart is complete, the following block releases the lock if the node executing is the one which holds the lock # ruby_block "release_datanode_restart_lock" do block do Chef::Log.info("#{node[:hostname]}: Releasing lock at #{lock_znode_path}") lock_rel = rel_restart_lock(lock_znode_path, zk_hosts, node[:fqdn]) if lock_rel node.set[:bcpc][:hadoop][:datanode][:restart_failed] = false node.save end end action :create only_if { my_restart_lock?(lock_znode_path, zk_hosts, node[:fqdn]) } end service "hadoop-yarn-nodemanager" do supports :status => true, :restart => true, :reload => false action [:enable, :start] subscribes :restart, "template[/etc/hadoop/conf/hadoop-env.sh]", :delayed subscribes :restart, "template[/etc/hadoop/conf/yarn-env.sh]", :delayed subscribes :restart, "template[/etc/hadoop/conf/yarn-site.xml]", :delayed subscribes :restart, "user_ulimit[yarn]", :delayed end
mlongob/chef-bach
cookbooks/bcpc-hadoop/recipes/datanode.rb
Ruby
apache-2.0
8,861
package life.catalogue.api.model; import java.util.Objects; public class RematchRequest extends RequestScope { private Integer decisionKey; private Integer estimateKey; public static RematchRequest all() { RematchRequest req = new RematchRequest(); req.setAll(true); return req; } public static RematchRequest sector(int sectorKey) { RematchRequest req = new RematchRequest(); req.setSectorKey(sectorKey); return req; } public static RematchRequest decision(int decisionKey) { RematchRequest req = new RematchRequest(); req.setDecisionKey(decisionKey); return req; } public static RematchRequest estimate(int estimateKey) { RematchRequest req = new RematchRequest(); req.setEstimateKey(estimateKey); return req; } public static RematchRequest dataset(int datasetKey) { RematchRequest req = new RematchRequest(); req.setDatasetKey(datasetKey); return req; } public Integer getDecisionKey() { return decisionKey; } public void setDecisionKey(Integer decisionKey) { this.decisionKey = decisionKey; } public Integer getEstimateKey() { return estimateKey; } public void setEstimateKey(Integer estimateKey) { this.estimateKey = estimateKey; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; RematchRequest that = (RematchRequest) o; return Objects.equals(decisionKey, that.decisionKey) && Objects.equals(estimateKey, that.estimateKey); } @Override public int hashCode() { return Objects.hash(super.hashCode(), decisionKey, estimateKey); } }
Sp2000/colplus-backend
colplus-api/src/main/java/life/catalogue/api/model/RematchRequest.java
Java
apache-2.0
1,757
/* * Copyright 2013 Square Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.squareup.wire; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.TypeAdapter; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; import com.google.gson.stream.JsonWriter; import java.io.IOException; import java.lang.reflect.Type; import java.math.BigInteger; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import okio.ByteString; import static com.squareup.wire.Message.Datatype; import static com.squareup.wire.Message.Label; import static java.util.Collections.unmodifiableMap; class MessageTypeAdapter<M extends Message<M>, B extends Message.Builder<M, B>> extends TypeAdapter<M> { enum UnknownFieldType { VARINT, FIXED32, FIXED64, LENGTH_DELIMITED; public static UnknownFieldType of(String name) { if ("varint".equals(name)) return VARINT; if ("fixed32".equals(name)) return FIXED32; if ("fixed64".equals(name)) return FIXED64; if ("length-delimited".equals(name)) return LENGTH_DELIMITED; throw new IllegalArgumentException("Unknown type " + name); } } // 2^64, used to convert sint64 values >= 2^63 to unsigned decimal form private static final BigInteger POWER_64 = new BigInteger("18446744073709551616"); private final Gson gson; private final RuntimeMessageAdapter<M, B> messageAdapter; private final Map<String, FieldBinding<M, B>> fieldBindings; private final Map<String, RegisteredExtension> extensions; @SuppressWarnings("unchecked") public MessageTypeAdapter(Wire wire, Gson gson, TypeToken<M> type) { this.gson = gson; this.messageAdapter = wire.messageAdapter((Class<M>) type.getRawType()); Map<String, FieldBinding<M, B>> fieldBindings = new LinkedHashMap<String, FieldBinding<M, B>>(); for (FieldBinding<M, B> binding : messageAdapter.fieldBindings().values()) { fieldBindings.put(binding.name, binding); } this.fieldBindings = unmodifiableMap(fieldBindings); Map<String, RegisteredExtension> extensions = new LinkedHashMap<String, RegisteredExtension>(); for (RegisteredExtension extension : messageAdapter.extensions().values()) { extensions.put(extension.name, extension); } this.extensions = extensions; } @SuppressWarnings("unchecked") @Override public void write(JsonWriter out, M message) throws IOException { if (message == null) { out.nullValue(); return; } out.beginObject(); for (FieldBinding<M, B> tagBinding : messageAdapter.fieldBindings().values()) { Object value = tagBinding.get(message); if (value == null) { continue; } out.name(tagBinding.name); emitJson(out, value, tagBinding.datatype, tagBinding.label); } TagMap tagMap = message.tagMap(); if (tagMap != null) { for (Extension<?, ?> extension : tagMap.extensions(true)) { if (extension.isUnknown()) { List<?> values = (List<?>) tagMap.get(extension); if (values.isEmpty()) continue; out.name(Integer.toString(extension.getTag())); out.beginArray(); switch (extension.getDatatype()) { case UINT64: out.value("varint"); for (Object o : values) { out.value((Long) o); } break; case FIXED32: out.value("fixed32"); for (Object o : values) { out.value((Integer) o); } break; case FIXED64: out.value("fixed64"); for (Object o : values) { out.value((Long) o); } break; case BYTES: out.value("length-delimited"); for (Object o : values) { out.value(((ByteString) o).base64()); } break; default: throw new AssertionError("Unknown wire type " + extension.getDatatype()); } out.endArray(); } else { Object value = tagMap.get(extension); out.name(extension.getName()); emitJson(out, value, extension.getDatatype(), extension.getLabel()); } } } out.endObject(); } @SuppressWarnings("unchecked") private void emitJson(JsonWriter out, Object value, Datatype datatype, Label label) throws IOException { if (datatype == Datatype.UINT64) { if (label.isRepeated()) { List<Long> longs = (List<Long>) value; out.beginArray(); for (int i = 0, count = longs.size(); i < count; i++) { emitUint64(longs.get(i), out); } out.endArray(); } else { emitUint64((Long) value, out); } } else { gson.toJson(value, value.getClass(), out); } } private void emitUint64(Long value, JsonWriter out) throws IOException { if (value < 0) { BigInteger unsigned = POWER_64.add(BigInteger.valueOf(value)); out.value(unsigned); } else { out.value(value); } } @SuppressWarnings("unchecked") @Override public M read(JsonReader in) throws IOException { if (in.peek() == JsonToken.NULL) { in.nextNull(); return null; } B builder = messageAdapter.newBuilder(); in.beginObject(); while (in.peek() == JsonToken.NAME) { String name = in.nextName(); FieldBinding<M, B> fieldBinding = fieldBindings.get(name); if (fieldBinding != null) { Object value = parseValue(fieldBinding.label, singleType(fieldBinding), parse(in)); fieldBinding.set(builder, value); continue; } RegisteredExtension registeredExtension = extensions.get(name); if (registeredExtension != null) { Object value = parseValue(registeredExtension.extension.getLabel(), registeredExtension.adapter.javaType, parse(in)); builder.setExtension((Extension) registeredExtension.extension, value); continue; } parseUnknownField(in, builder, Integer.parseInt(name)); } in.endObject(); return builder.build(); } private JsonElement parse(JsonReader in) { return gson.fromJson(in, JsonElement.class); } private Object parseValue(Label label, Type valueType, JsonElement valueElement) { if (label.isRepeated()) { List<Object> valueList = new ArrayList<Object>(); for (JsonElement element : valueElement.getAsJsonArray()) { valueList.add(readJson(valueType, element)); } return valueList; } else { return readJson(valueType, valueElement); } } private void parseUnknownField(JsonReader in, B builder, int tag) throws IOException { in.beginArray(); UnknownFieldType type = UnknownFieldType.of(in.nextString()); while (in.peek() != JsonToken.END_ARRAY) { switch (type) { case VARINT: builder.addVarint(tag, in.nextInt()); break; case FIXED32: builder.addFixed32(tag, in.nextInt()); break; case FIXED64: builder.addFixed64(tag, in.nextInt()); break; case LENGTH_DELIMITED: builder.addLengthDelimited(tag, ByteString.decodeBase64(in.nextString())); break; default: throw new AssertionError("Unknown field type " + type); } } in.endArray(); } private Object readJson(Type valueType, JsonElement element) { return gson.fromJson(element, valueType); } private Type singleType(FieldBinding<M, B> tagBinding) { return tagBinding.singleAdapter.javaType; } }
cailingxiao/wire
wire-gson-support/src/main/java/com/squareup/wire/MessageTypeAdapter.java
Java
apache-2.0
8,290
package com.wusong.mygobang.myview; import com.wusong.mygobang.R; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.util.Log; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.widget.Toast; @SuppressLint("ClickableViewAccessibility") public class GobangView extends View { private Activity mainActivity; protected static int GRID_SIZE = 15; protected static int GRID_WIDTH = 45; // 棋盘格的宽度 protected static int CHESS_DIAMETER = 43; // 棋的直径 protected static int mStartX;// 棋盘定位的左上角X protected static int mStartY;// 棋盘定位的左上角Y private Bitmap[] mChessBW; // 黑棋和白棋 private static int[][] mGridArray; // 网格 boolean key = false; int wbflag = 1; // 该下白棋了=2,该下黑棋了=1. 这里先下黑棋(黑棋以后设置为机器自动下的棋子) int mLevel = 1; // 游戏难度 int mWinFlag = 0; private final int BLACK = 1; private final int WHITE = 2; int mGameState = GAMESTATE_RUN; // 游戏阶段:0=尚未游戏,1=正在进行游戏,2=游戏结束 /** 游戏状态:准备阶段 */ public static final int GAMESTATE_PRE = 0; /** 游戏状态:进行中 */ public static final int GAMESTATE_RUN = 1; /** 游戏状态:暂停 */ public static final int GAMESTATE_PAUSE = 2; /** 游戏状态:结束 */ public static final int GAMESTATE_END = 3; private final Paint mPaint = new Paint(); private Drawable bgPanel; CharSequence STRING_WIN = "白棋胜,点击确定重新开始!"; CharSequence STRING_LOSE = "黑棋胜,点击确定重新开始!"; CharSequence STRING_EQUAL = "不可思议,你们竟然平局,真是棋逢对手啊!点击确定重新开始!"; public GobangView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public GobangView(Context context, AttributeSet attrs) { // 好像调用的是这个构造函数,为什么不是前面的呢 super(context, attrs); this.setFocusable(true); // 20090530 this.setFocusableInTouchMode(true); this.setBackgroundColor(0x000000); if (this.isInEditMode() == false) { init(); } else { bgPanel = context.getResources().getDrawable(R.drawable.panel); } } // 这里画棋子后来没有用图片画,而是直接画了圆。因为我做的图片不好看。 // 初始化黑白棋的Bitmap public void init() { mGameState = 1; // 设置游戏为开始状态 wbflag = BLACK; // 初始为先下黑棋 mWinFlag = 0; // 清空输赢标志。 mGridArray = new int[GRID_SIZE][GRID_SIZE]; mChessBW = new Bitmap[2]; Resources r = this.getContext().getResources(); Bitmap bitmap1 = Bitmap.createBitmap(CHESS_DIAMETER, CHESS_DIAMETER, Bitmap.Config.ARGB_8888); Canvas canvas1 = new Canvas(bitmap1); Drawable tile1 = r.getDrawable(R.drawable.black); tile1.setBounds(0, 0, CHESS_DIAMETER, CHESS_DIAMETER); tile1.draw(canvas1); mChessBW[0] = bitmap1; Bitmap bitmap2 = Bitmap.createBitmap(CHESS_DIAMETER, CHESS_DIAMETER, Bitmap.Config.ARGB_8888); Canvas canvas2 = new Canvas(bitmap2); Drawable tile2 = r.getDrawable(R.drawable.white); tile2.setBounds(0, 0, CHESS_DIAMETER, CHESS_DIAMETER); tile2.draw(canvas2); mChessBW[1] = bitmap2; bgPanel = r.getDrawable(R.drawable.panel); } @Override public boolean onTouchEvent(MotionEvent event) { switch (mGameState) { case GAMESTATE_PRE: break; case GAMESTATE_RUN: { int x; int y; float x0 = GRID_WIDTH - (event.getX() - mStartX) % GRID_WIDTH; float y0 = GRID_WIDTH - (event.getY() - mStartY) % GRID_WIDTH; x = (int) ((event.getX() - mStartX) / GRID_WIDTH); if (x0 < GRID_WIDTH / 2) { x = (int) ((event.getX() - mStartX) / GRID_WIDTH); } else { x = (int) ((event.getX() - mStartX) / GRID_WIDTH) - 1; } y = (int) ((event.getY() - mStartY) / GRID_WIDTH); if (y0 < GRID_WIDTH / 2) { y = (int) ((event.getY() - mStartY) / GRID_WIDTH); } else { y = (int) ((event.getY() - mStartY) / GRID_WIDTH) - 1; } if ((x >= 0 && x < GRID_SIZE) && (y >= 0 && y < GRID_SIZE)) { if (mGridArray[x][y] == 0) { if (wbflag == BLACK) { putChess(x, y, BLACK); if (checkWin(BLACK)) { // 如果是黑棋赢了 mGameState = GAMESTATE_END; showOverText(STRING_LOSE); } else if (checkFull()) {// 如果棋盘满了 mGameState = GAMESTATE_END; showOverText(STRING_EQUAL); } wbflag = WHITE; } else if (wbflag == WHITE) { putChess(x, y, WHITE); if (checkWin(WHITE)) { mGameState = GAMESTATE_END; showOverText(STRING_WIN); } else if (checkFull()) {// 如果棋盘满了 mGameState = GAMESTATE_END; showOverText(STRING_EQUAL); } wbflag = BLACK; } } } } break; case GAMESTATE_PAUSE: break; case GAMESTATE_END: break; } this.invalidate(); return true; } @Override public boolean onKeyDown(int keyCode, KeyEvent msg) { Log.e("KeyEvent.KEYCODE_DPAD_CENTER", " " + keyCode); if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) { switch (mGameState) { case GAMESTATE_PRE: break; case GAMESTATE_RUN: break; case GAMESTATE_PAUSE: break; case GAMESTATE_END: // 游戏结束后,按CENTER键继续 reStartGame(); break; } } return super.onKeyDown(keyCode, msg); } /** * 重新开始游戏 */ public void reStartGame() { mGameState = GAMESTATE_RUN; this.setVisibility(View.VISIBLE); this.init(); this.invalidate(); } @Override public void onDraw(Canvas canvas) { mStartX = (this.getWidth() - GRID_WIDTH * GRID_SIZE)/2; mStartY = (this.getHeight() - GRID_WIDTH * GRID_SIZE) - GRID_WIDTH / 2; if (this.isInEditMode() == false) { bgPanel.setBounds(mStartX, mStartY, mStartX + GRID_WIDTH * GRID_SIZE, mStartY + GRID_WIDTH * GRID_SIZE); bgPanel.draw(canvas); mStartX = 0 - mStartX; mStartY = mStartY - GRID_WIDTH / 2; // 画棋子 for (int i = 0; i < GRID_SIZE; i++) { for (int j = 0; j < GRID_SIZE; j++) { if (mGridArray[i][j] == BLACK) { // 通过图片来画 canvas.drawBitmap(mChessBW[0], mStartX + (i + 1) * GRID_WIDTH - CHESS_DIAMETER / 2, mStartY + (j + 1) * GRID_WIDTH - CHESS_DIAMETER / 2, mPaint); } else if (mGridArray[i][j] == WHITE) { // 通过图片来画 canvas.drawBitmap(mChessBW[1], mStartX + (i + 1) * GRID_WIDTH - CHESS_DIAMETER / 2, mStartY + (j + 1) * GRID_WIDTH - CHESS_DIAMETER / 2, mPaint); } } } } else { bgPanel.setBounds(mStartX, mStartY, mStartX + GRID_WIDTH * GRID_SIZE, mStartY + GRID_WIDTH * GRID_SIZE); bgPanel.draw(canvas); } } /** * 放置棋子 * @param x X坐标 * @param y Y坐标 * @param blackwhite 棋子类型 */ public void putChess(int x, int y, int blackwhite) { mGridArray[x][y] = blackwhite; } public boolean checkWin(int wbflag) { for (int i = 0; i < GRID_SIZE; i++) // i表示列(根据宽度算出来的) for (int j = 0; j < GRID_SIZE; j++) {// i表示行(根据高度算出来的) // 检测横轴五个相连 if (((i + 4) < (GRID_SIZE)) && (mGridArray[i][j] == wbflag) && (mGridArray[i + 1][j] == wbflag) && (mGridArray[i + 2][j] == wbflag) && (mGridArray[i + 3][j] == wbflag) && (mGridArray[i + 4][j] == wbflag)) { Log.e("check win or loss:", wbflag + " win"); mWinFlag = wbflag; } // 纵轴5个相连 if (((j + 4) < (GRID_SIZE)) && (mGridArray[i][j] == wbflag) && (mGridArray[i][j + 1] == wbflag) && (mGridArray[i][j + 2] == wbflag) && (mGridArray[i][j + 3] == wbflag) && (mGridArray[i][j + 4] == wbflag)) { Log.e("check win or loss:", wbflag + " win"); mWinFlag = wbflag; } // 左上到右下5个相连 if (((j + 4) < (GRID_SIZE)) && ((i + 4) < (GRID_SIZE)) && (mGridArray[i][j] == wbflag) && (mGridArray[i + 1][j + 1] == wbflag) && (mGridArray[i + 2][j + 2] == wbflag) && (mGridArray[i + 3][j + 3] == wbflag) && (mGridArray[i + 4][j + 4] == wbflag)) { Log.e("check win or loss:", wbflag + " win"); mWinFlag = wbflag; } // 右上到左下5个相连 if (((i - 4) >= 0) && ((j + 4) < (GRID_SIZE)) && (mGridArray[i][j] == wbflag) && (mGridArray[i - 1][j + 1] == wbflag) && (mGridArray[i - 2][j + 2] == wbflag) && (mGridArray[i - 3][j + 3] == wbflag) && (mGridArray[i - 4][j + 4] == wbflag)) { Log.e("check win or loss:", wbflag + " win"); mWinFlag = wbflag; } } if (mWinFlag == wbflag) { return true; } else return false; } public boolean checkFull() { int mNotEmpty = 0; for (int i = 0; i < GRID_SIZE; i++) for (int j = 0; j < GRID_SIZE; j++) { if (mGridArray[i][j] != 0) mNotEmpty += 1; } if (mNotEmpty == GRID_SIZE*GRID_SIZE) return true; else return false; } public void showOverText(CharSequence mT) { AlertDialog.Builder builder = new AlertDialog.Builder(mainActivity); builder.setIcon(android.R.drawable.ic_dialog_alert); builder.setTitle("游戏结束"); builder.setMessage(mT); builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // 这里添加点击确定后的逻辑 reStartGame(); } }); builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // 这里添加点击确定后的逻辑 Toast.makeText(mainActivity, "单击返回按钮也可以重新开始", Toast.LENGTH_SHORT).show(); } }); builder.create().show(); } public void setMainActivity(Activity mainActivity) { this.mainActivity = mainActivity; } /** * @return 返回当前游戏状态 */ public int getGameState() { return mGameState; } }
rookieWu/gobang
src/com/wusong/mygobang/myview/GobangView.java
Java
apache-2.0
10,736
import React from "react" import PropTypes from "prop-types" import { FontAwesomeIcon } from "@fortawesome/react-fontawesome" import Link from "./Link" const BoxNav = ({ navItems }) => ( <div className="card-footer"> {navItems.map((navItem, navIndex) => ( <Link href={navItem.link} className="card-footer-item" key={navIndex}> {navItem.fa && <span className="icon"> <FontAwesomeIcon icon={["fab", navItem.fa]} /> </span> } {navItem.name} </Link> ))} </div> ) BoxNav.propTypes = { navItems: PropTypes.arrayOf( PropTypes.shape({ link: PropTypes.string.isRequired, name: PropTypes.string, fa: PropTypes.string, }) ) } export default BoxNav
aokashi/aokashi_home
src/components/BoxNav.js
JavaScript
apache-2.0
767
package v3public import ( "github.com/rancher/norman/lifecycle" "github.com/rancher/norman/resource" "k8s.io/apimachinery/pkg/runtime" ) type AuthProviderLifecycle interface { Create(obj *AuthProvider) (runtime.Object, error) Remove(obj *AuthProvider) (runtime.Object, error) Updated(obj *AuthProvider) (runtime.Object, error) } type authProviderLifecycleAdapter struct { lifecycle AuthProviderLifecycle } func (w *authProviderLifecycleAdapter) HasCreate() bool { o, ok := w.lifecycle.(lifecycle.ObjectLifecycleCondition) return !ok || o.HasCreate() } func (w *authProviderLifecycleAdapter) HasFinalize() bool { o, ok := w.lifecycle.(lifecycle.ObjectLifecycleCondition) return !ok || o.HasFinalize() } func (w *authProviderLifecycleAdapter) Create(obj runtime.Object) (runtime.Object, error) { o, err := w.lifecycle.Create(obj.(*AuthProvider)) if o == nil { return nil, err } return o, err } func (w *authProviderLifecycleAdapter) Finalize(obj runtime.Object) (runtime.Object, error) { o, err := w.lifecycle.Remove(obj.(*AuthProvider)) if o == nil { return nil, err } return o, err } func (w *authProviderLifecycleAdapter) Updated(obj runtime.Object) (runtime.Object, error) { o, err := w.lifecycle.Updated(obj.(*AuthProvider)) if o == nil { return nil, err } return o, err } func NewAuthProviderLifecycleAdapter(name string, clusterScoped bool, client AuthProviderInterface, l AuthProviderLifecycle) AuthProviderHandlerFunc { if clusterScoped { resource.PutClusterScoped(AuthProviderGroupVersionResource) } adapter := &authProviderLifecycleAdapter{lifecycle: l} syncFn := lifecycle.NewObjectLifecycleAdapter(name, clusterScoped, adapter, client.ObjectClient()) return func(key string, obj *AuthProvider) (runtime.Object, error) { newObj, err := syncFn(key, obj) if o, ok := newObj.(runtime.Object); ok { return o, err } return nil, err } }
cjellick/rancher
vendor/github.com/rancher/types/apis/management.cattle.io/v3public/zz_generated_auth_provider_lifecycle_adapter.go
GO
apache-2.0
1,898
/* * Copyright 2017 Mirko Sertic * * 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 de.mirkosertic.bytecoder.core; public class BytecodeUnknownAttributeInfo implements BytecodeAttributeInfo { private final BytecodeUtf8Constant attributeName; private final byte[] attributeData; public BytecodeUnknownAttributeInfo(BytecodeUtf8Constant aAttributeName, byte[] aAttributeData) { attributeName = aAttributeName; attributeData = aAttributeData; } }
mirkosertic/Bytecoder
core/src/main/java/de/mirkosertic/bytecoder/core/BytecodeUnknownAttributeInfo.java
Java
apache-2.0
1,001
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.geode.management.internal.cli.commands; import org.springframework.shell.core.annotation.CliCommand; import org.apache.geode.management.cli.CliMetaData; import org.apache.geode.management.internal.cli.LogWrapper; import org.apache.geode.management.internal.cli.i18n.CliStrings; import org.apache.geode.management.internal.cli.result.model.InfoResultModel; import org.apache.geode.management.internal.cli.result.model.ResultModel; import org.apache.geode.management.internal.cli.shell.Gfsh; import org.apache.geode.management.internal.cli.shell.OperationInvoker; public class DisconnectCommand extends OfflineGfshCommand { @CliCommand(value = {CliStrings.DISCONNECT}, help = CliStrings.DISCONNECT__HELP) @CliMetaData(shellOnly = true, relatedTopic = {CliStrings.TOPIC_GFSH, CliStrings.TOPIC_GEODE_JMX, CliStrings.TOPIC_GEODE_MANAGER}) public ResultModel disconnect() { if (getGfsh() != null && !getGfsh().isConnectedAndReady()) { return ResultModel.createInfo("Not connected."); } ResultModel result = new ResultModel(); InfoResultModel infoResultData = result.addInfo(); Gfsh gfshInstance = getGfsh(); if (gfshInstance.isConnectedAndReady()) { OperationInvoker operationInvoker = gfshInstance.getOperationInvoker(); Gfsh.println("Disconnecting from: " + operationInvoker); operationInvoker.stop(); infoResultData.addLine(CliStrings.format(CliStrings.DISCONNECT__MSG__DISCONNECTED, operationInvoker.toString())); LogWrapper.getInstance().info(CliStrings .format(CliStrings.DISCONNECT__MSG__DISCONNECTED, operationInvoker.toString())); if (!gfshInstance.isHeadlessMode()) { gfshInstance.setPromptPath(gfshInstance.getEnvAppContextPath()); } } else { infoResultData.addLine(CliStrings.DISCONNECT__MSG__NOTCONNECTED); } return result; } }
PurelyApplied/geode
geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DisconnectCommand.java
Java
apache-2.0
2,685
// Copyright 2016 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package hawkular import ( "net/url" "sync" "github.com/adfin/statster/metrics/core" hawkular "github.com/hawkular/hawkular-client-go/metrics" ) type Filter func(ms *core.MetricSet, metricName string) bool type FilterType int const ( // Filter by label's value Label FilterType = iota // Filter by metric name Name // Unknown filter type Unknown ) func (f FilterType) From(s string) FilterType { switch s { case "label": return Label case "name": return Name default: return Unknown } } type hawkularSink struct { client *hawkular.Client models map[string]*hawkular.MetricDefinition // Model definitions regLock sync.RWMutex reg map[string]*hawkular.MetricDefinition // Real definitions uri *url.URL labelTenant string labelNodeId string labelTagPrefix string modifiers []hawkular.Modifier filters []Filter disablePreCaching bool batchSize int } func heapsterTypeToHawkularType(t core.MetricType) hawkular.MetricType { switch t { case core.MetricCumulative: return hawkular.Counter case core.MetricGauge: return hawkular.Gauge default: return hawkular.Gauge } }
adfin/statster
metrics/sinks/hawkular/types.go
GO
apache-2.0
1,757
module.exports = checkQuote function checkQuote(context) { var marker = context.options.quote || '"' if (marker !== '"' && marker !== "'") { throw new Error( 'Cannot serialize title with `' + marker + '` for `options.quote`, expected `"`, or `\'`' ) } return marker }
kyleterry/sufr
pkg/ui/node_modules/mdast-util-to-markdown/lib/util/check-quote.js
JavaScript
apache-2.0
309
# Orthosiphon debilis Hemsl. SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Lamiaceae/Orthosiphon/Orthosiphon debilis/README.md
Markdown
apache-2.0
176
package org.mingy.jmud.model.pkuxkx; import org.eclipse.swt.SWT; import org.mingy.jmud.model.Constants; import org.mingy.jmud.model.Context; import org.mingy.jmud.model.Scope; import org.mingy.jmud.ui.pkuxkx.CharacterView; /** * 北大侠客行的通用配置定义。 * * @author Mingy * @since 1.0.0 */ public class Configuration extends org.mingy.jmud.model.Configuration { public static final String HP_PATTERN_S = "^(?:> |)≡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━≡$"; public static final String HP_PATTERN1 = "^【 精神 】\\s*(\\d+)\\s*/\\s*(\\d+)\\s*\\[\\s*(\\d+)%\\s*\\]\\s*【 精力 】\\s*(\\d+)\\s*/\\s*(\\d+)\\s*\\(\\+\\s*(\\d+)\\s*\\)$"; public static final String HP_PATTERN2 = "^【 气血 】\\s*(\\d+)\\s*/\\s*(\\d+)\\s*\\[\\s*(\\d+)%\\s*\\]\\s*【 内力 】\\s*(\\d+)\\s*/\\s*(\\d+)\\s*\\(\\+\\s*(\\d+)\\s*\\)$"; public static final String HP_PATTERN3 = "^【 食物 】\\s*(\\d+)\\s*/\\s*(\\d+)\\s*\\[\\s*(.+)\\s*\\]\\s*【 潜能 】\\s*(\\d+)\\s*$"; public static final String HP_PATTERN4 = "^【 饮水 】\\s*(\\d+)\\s*/\\s*(\\d+)\\s*\\[\\s*(.+)\\s*\\]\\s*【 经验 】\\s*(\\d+)\\s*$"; public static final String HP_PATTERN5 = "^【 状态 】\\s*(.+)\\s*$"; public static final String HP_PATTERN_E = "^≡━━━━━━━━━━━━━━━━━━━━━━━◎北大侠客行◎━━≡$"; public static final String HPBRIEF_PATTERN1 = "^(?:> |)#(\\d+),(\\d+),(\\d+),(\\d+),(\\d+),(\\d+)$"; public static final String HPBRIEF_PATTERN2 = "^#(\\d+),(\\d+),(\\d+),(\\d+),(\\d+),(\\d+)$"; @Override public String getName() { return "pkuxkx.net"; } @Override public void inject(Context context) { context.setShortKey(SWT.KEYPAD_0, "hp"); Scope loginModule = context.getScope(Constants.MODULE_LOGIN); loginModule.addTrigger(Constants.TRIGGER_GROUP_LOGIN, "^您的英文名字(要注册新人物请输入new):", "@" + Constants.VAR_CHARACTER); loginModule.addTrigger(Constants.TRIGGER_GROUP_LOGIN, "此ID档案已存在,请输入密码:", "@" + Constants.VAR_PASSWORD); loginModule.addTrigger(Constants.TRIGGER_GROUP_LOGIN, "^目前权限:\\(player\\)$", "#set " + Constants.VAR_LOGIN_OK + " 1;#t- " + Constants.TRIGGER_GROUP_LOGIN); loginModule.addTrigger(Constants.TRIGGER_GROUP_LOGIN, "^重新连线完毕。$", "#set " + Constants.VAR_LOGIN_OK + " 2;#t- " + Constants.TRIGGER_GROUP_LOGIN); loginModule.addTrigger(Constants.TRIGGER_GROUP_LOGIN, "^您要将另一个连线中的相同人物赶出去,取而代之吗?\\(y/n\\)", "#set " + Constants.VAR_LOGIN_OK + " 3;y;#t- " + Constants.TRIGGER_GROUP_LOGIN); loginModule.addTrigger(null, "^==\\s*未完继续\\s*\\d+%\\s*==\\s*\\(q 离开,b 前一页,其他继续下一页\\)", "q"); loginModule.addTrigger(null, "^有人从别处\\(\\s*(\\d+\\.\\d+\\.\\d+\\.\\d+)\\s*\\)连线取代你所控制的人物。$", "#set " + Constants.VAR_IP_RECORD + " '%1'"); loginModule .addWatcher(Constants.VAR_LOGIN_OK, "#if {%2 > 0} {hpbrief}"); } @Override public String getCharacterViewId() { return CharacterView.ID; } }
wuzhengmao/jmud
src/org/mingy/jmud/model/pkuxkx/Configuration.java
Java
apache-2.0
3,198
/** * <copyright> * </copyright> * * $Id$ */ package net.opengis.citygml.relief.util; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.emf.ecore.resource.impl.ResourceFactoryImpl; import org.eclipse.emf.ecore.xmi.XMLResource; /** * <!-- begin-user-doc --> * The <b>Resource Factory</b> associated with the package. * <!-- end-user-doc --> * @see net.opengis.citygml.relief.util.ReliefResourceImpl * @generated */ public class ReliefResourceFactoryImpl extends ResourceFactoryImpl { /** * Creates an instance of the resource factory. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ReliefResourceFactoryImpl() { super(); } /** * Creates an instance of the resource. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Resource createResource(URI uri) { XMLResource result = new ReliefResourceImpl(uri); result.getDefaultSaveOptions().put(XMLResource.OPTION_EXTENDED_META_DATA, Boolean.TRUE); result.getDefaultLoadOptions().put(XMLResource.OPTION_EXTENDED_META_DATA, Boolean.TRUE); result.getDefaultSaveOptions().put(XMLResource.OPTION_SCHEMA_LOCATION, Boolean.TRUE); result.getDefaultLoadOptions().put(XMLResource.OPTION_USE_ENCODED_ATTRIBUTE_STYLE, Boolean.TRUE); result.getDefaultSaveOptions().put(XMLResource.OPTION_USE_ENCODED_ATTRIBUTE_STYLE, Boolean.TRUE); result.getDefaultLoadOptions().put(XMLResource.OPTION_USE_LEXICAL_HANDLER, Boolean.TRUE); return result; } } //ReliefResourceFactoryImpl
markus1978/citygml4emf
de.hub.citygml.emf.ecore/src/net/opengis/citygml/relief/util/ReliefResourceFactoryImpl.java
Java
apache-2.0
1,576
/* First created by JCasGen Fri Jan 03 13:40:15 CST 2014 */ package org.apache.ctakes.typesystem.type.refsem; import org.apache.uima.jcas.JCas; import org.apache.uima.jcas.JCasRegistry; import org.apache.uima.jcas.cas.TOP_Type; /** The amount of time after which a medication should stop being used, e.g., "2 weeks" in "one 5 mg tablet twice-a-day for 2 weeks" * Updated by JCasGen Fri Jan 03 13:40:15 CST 2014 * XML source: C:/WKT/git/schorndorfer/uima-components/annotator-parent/type-system/src/main/resources/org/apache/ctakes/typesystem/types/TypeSystem.xml * @generated */ public class MedicationDuration extends Attribute { /** @generated * @ordered */ @SuppressWarnings ("hiding") public final static int typeIndexID = JCasRegistry.register(MedicationDuration.class); /** @generated * @ordered */ @SuppressWarnings ("hiding") public final static int type = typeIndexID; /** @generated */ @Override public int getTypeIndexID() {return typeIndexID;} /** Never called. Disable default constructor * @generated */ protected MedicationDuration() {/* intentionally empty block */} /** Internal - constructor used by generator * @generated */ public MedicationDuration(int addr, TOP_Type type) { super(addr, type); readObject(); } /** @generated */ public MedicationDuration(JCas jcas) { super(jcas); readObject(); } /** <!-- begin-user-doc --> * Write your own initialization here * <!-- end-user-doc --> @generated modifiable */ private void readObject() {/*default - does nothing empty block */} //*--------------* //* Feature: value /** getter for value - gets * @generated */ public String getValue() { if (MedicationDuration_Type.featOkTst && ((MedicationDuration_Type)jcasType).casFeat_value == null) jcasType.jcas.throwFeatMissing("value", "org.apache.ctakes.typesystem.type.refsem.MedicationDuration"); return jcasType.ll_cas.ll_getStringValue(addr, ((MedicationDuration_Type)jcasType).casFeatCode_value);} /** setter for value - sets * @generated */ public void setValue(String v) { if (MedicationDuration_Type.featOkTst && ((MedicationDuration_Type)jcasType).casFeat_value == null) jcasType.jcas.throwFeatMissing("value", "org.apache.ctakes.typesystem.type.refsem.MedicationDuration"); jcasType.ll_cas.ll_setStringValue(addr, ((MedicationDuration_Type)jcasType).casFeatCode_value, v);} }
schorndorfer/uima-components
annotator-parent/type-system/src/main/java/org/apache/ctakes/typesystem/type/refsem/MedicationDuration.java
Java
apache-2.0
2,512
# Copyright:: Copyright (c) Chef Software Inc. # License:: Apache License, Version 2.0 # # 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. module ChefConfig CHEFCONFIG_ROOT = File.expand_path("..", __dir__) VERSION = "17.1.11".freeze end
gene1wood/chef
chef-config/lib/chef-config/version.rb
Ruby
apache-2.0
737
package de.schub.docker_controller.Metadata.Storage; import de.schub.docker_controller.Metadata.ContainerService; import java.util.Map; public interface ServiceDiscoveryStorage { /** * @return all services running in the cluster. Container ID as key */ Map<String, ContainerService> getServices(); }
Marmelatze/docker-controller
docker-controller/src/main/java/de/schub/docker_controller/Metadata/Storage/ServiceDiscoveryStorage.java
Java
apache-2.0
321
/* * Copyright 2001-2009 The Apache Software Foundation. * * 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. * */ /** * <p>Java class for Node type. Specific to juddi. * * @author <a href="mailto:kstam@apache.org">Kurt T Stam</a> * */ package org.apache.juddi.api_v3; import java.io.Serializable; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlTransient; import javax.xml.bind.annotation.XmlType; @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "node", propOrder = { "name", "managerName", "description", "custodyTransferUrl", "inquiryUrl", "publishUrl", "securityUrl", "subscriptionUrl", "subscriptionListenerUrl", "juddiApiUrl", "proxyTransport", "factoryInitial", "factoryURLPkgs", "factoryNamingProvider" }) public class Node implements Serializable{ @XmlTransient private static final long serialVersionUID = -4601378453000384721L; private String name; private String managerName; private String description; private String custodyTransferUrl; private String inquiryUrl; private String publishUrl; private String securityUrl; private String subscriptionUrl; private String subscriptionListenerUrl; private String juddiApiUrl; private String proxyTransport; private String factoryInitial; private String factoryURLPkgs; private String factoryNamingProvider; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getManagerName() { return managerName; } public void setManagerName(String managerName) { this.managerName = managerName; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getCustodyTransferUrl() { return custodyTransferUrl; } public void setCustodyTransferUrl(String custodyTransferUrl) { this.custodyTransferUrl = custodyTransferUrl; } public String getInquiryUrl() { return inquiryUrl; } public void setInquiryUrl(String inquiryUrl) { this.inquiryUrl = inquiryUrl; } public String getPublishUrl() { return publishUrl; } public void setPublishUrl(String publishUrl) { this.publishUrl = publishUrl; } public String getSecurityUrl() { return securityUrl; } public void setSecurityUrl(String securityUrl) { this.securityUrl = securityUrl; } public String getSubscriptionUrl() { return subscriptionUrl; } public void setSubscriptionUrl(String subscriptionUrl) { this.subscriptionUrl = subscriptionUrl; } public String getProxyTransport() { return proxyTransport; } public void setProxyTransport(String proxyTransport) { this.proxyTransport = proxyTransport; } public String getJuddiApiUrl() { return juddiApiUrl; } public void setJuddiApiUrl(String juddiApiUrl) { this.juddiApiUrl = juddiApiUrl; } public String getSubscriptionListenerUrl() { return subscriptionListenerUrl; } public void setSubscriptionListenerUrl(String subscriptionListenerUrl) { this.subscriptionListenerUrl = subscriptionListenerUrl; } public String getFactoryInitial() { return factoryInitial; } public void setFactoryInitial(String factoryInitial) { this.factoryInitial = factoryInitial; } public String getFactoryURLPkgs() { return factoryURLPkgs; } public void setFactoryURLPkgs(String factoryURLPkgs) { this.factoryURLPkgs = factoryURLPkgs; } public String getFactoryNamingProvider() { return factoryNamingProvider; } public void setFactoryNamingProvider(String factoryNamingProvider) { this.factoryNamingProvider = factoryNamingProvider; } }
KurtStam/juddi
uddi-ws/src/main/java/org/apache/juddi/api_v3/Node.java
Java
apache-2.0
4,184
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hbase.rest; import java.io.IOException; import java.util.List; import javax.ws.rs.GET; import javax.ws.rs.Produces; import javax.ws.rs.core.CacheControl; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; import javax.ws.rs.core.UriInfo; import org.apache.hadoop.hbase.HRegionLocation; import org.apache.hadoop.hbase.ServerName; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.TableNotFoundException; import org.apache.hadoop.hbase.client.Connection; import org.apache.hadoop.hbase.client.ConnectionFactory; import org.apache.hadoop.hbase.client.RegionInfo; import org.apache.hadoop.hbase.client.RegionLocator; import org.apache.hadoop.hbase.rest.model.TableInfoModel; import org.apache.hadoop.hbase.rest.model.TableRegionModel; import org.apache.yetus.audience.InterfaceAudience; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @InterfaceAudience.Private public class RegionsResource extends ResourceBase { private static final Logger LOG = LoggerFactory.getLogger(RegionsResource.class); static CacheControl cacheControl; static { cacheControl = new CacheControl(); cacheControl.setNoCache(true); cacheControl.setNoTransform(false); } TableResource tableResource; /** * Constructor * @param tableResource * @throws IOException */ public RegionsResource(TableResource tableResource) throws IOException { super(); this.tableResource = tableResource; } @GET @Produces({MIMETYPE_TEXT, MIMETYPE_XML, MIMETYPE_JSON, MIMETYPE_PROTOBUF, MIMETYPE_PROTOBUF_IETF}) public Response get(final @Context UriInfo uriInfo) { if (LOG.isTraceEnabled()) { LOG.trace("GET " + uriInfo.getAbsolutePath()); } servlet.getMetrics().incrementRequests(1); try { TableName tableName = TableName.valueOf(tableResource.getName()); if (!tableResource.exists()) { throw new TableNotFoundException(tableName); } TableInfoModel model = new TableInfoModel(tableName.getNameAsString()); List<HRegionLocation> locs; try (Connection connection = ConnectionFactory.createConnection(servlet.getConfiguration()); RegionLocator locator = connection.getRegionLocator(tableName)) { locs = locator.getAllRegionLocations(); } for (HRegionLocation loc : locs) { RegionInfo hri = loc.getRegion(); ServerName addr = loc.getServerName(); model.add(new TableRegionModel(tableName.getNameAsString(), hri.getRegionId(), hri.getStartKey(), hri.getEndKey(), addr.getAddress().toString())); } ResponseBuilder response = Response.ok(model); response.cacheControl(cacheControl); servlet.getMetrics().incrementSucessfulGetRequests(1); return response.build(); } catch (TableNotFoundException e) { servlet.getMetrics().incrementFailedGetRequests(1); return Response.status(Response.Status.NOT_FOUND) .type(MIMETYPE_TEXT).entity("Not found" + CRLF) .build(); } catch (IOException e) { servlet.getMetrics().incrementFailedGetRequests(1); return Response.status(Response.Status.SERVICE_UNAVAILABLE) .type(MIMETYPE_TEXT).entity("Unavailable" + CRLF) .build(); } } }
HubSpot/hbase
hbase-rest/src/main/java/org/apache/hadoop/hbase/rest/RegionsResource.java
Java
apache-2.0
4,132
<!doctype html> <html lang="en-us"> <head> <meta charset="utf-8"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Emscripten-Generated Code</title> <style> .emscripten { padding-right: 0; margin-left: auto; margin-right: auto; display: block; } textarea.emscripten { font-family: monospace; width: 80%; } div.emscripten { text-align: center; } div.emscripten_border { border: 1px solid black; } /* the canvas *must not* have any border or padding, or mouse coords will be wrong */ canvas.emscripten { border: 0px none; } </style> </head> <body> <hr/> <div class="emscripten" id="status">Downloading...</div> <div class="emscripten"> <progress value="0" max="100" id="progress" hidden=1></progress> </div> <div class="emscripten_border"> <!-- Pass custom width/height to test that SDL_SetVideoMode(0,0, ...) will use these. --> <canvas class="emscripten" id="canvas" width="700" height="200" oncontextmenu="event.preventDefault()"></canvas> </div> <hr/> <div class="emscripten"> <input type="checkbox" id="resize">Resize canvas <input type="checkbox" id="pointerLock" checked>Lock/hide mouse pointer &nbsp;&nbsp;&nbsp; <input type="button" value="Fullscreen" onclick="Module.requestFullScreen(document.getElementById('pointerLock').checked, document.getElementById('resize').checked)"> </div> <hr/> <textarea class="emscripten" id="output" rows="8"></textarea> <hr> <script type='text/javascript'> // connect to canvas var Module = { preRun: [], postRun: [], print: (function() { var element = document.getElementById('output'); element.value = ''; // clear browser cache return function(text) { if (arguments.length > 1) text = Array.prototype.slice.call(arguments).join(' '); // These replacements are necessary if you render to raw HTML //text = text.replace(/&/g, "&amp;"); //text = text.replace(/</g, "&lt;"); //text = text.replace(/>/g, "&gt;"); //text = text.replace('\n', '<br>', 'g'); element.value += text + "\n"; element.scrollTop = element.scrollHeight; // focus on bottom }; })(), printErr: function(text) { if (arguments.length > 1) text = Array.prototype.slice.call(arguments).join(' '); if (0) { // XXX disabled for safety typeof dump == 'function') { dump(text + '\n'); // fast, straight to the real console } else { console.log(text); } }, canvas: document.getElementById('canvas'), setStatus: function(text) { if (Module.setStatus.interval) clearInterval(Module.setStatus.interval); var m = text.match(/([^(]+)\((\d+(\.\d+)?)\/(\d+)\)/); var statusElement = document.getElementById('status'); var progressElement = document.getElementById('progress'); if (m) { text = m[1]; progressElement.value = parseInt(m[2])*100; progressElement.max = parseInt(m[4])*100; progressElement.hidden = false; } else { progressElement.value = null; progressElement.max = null; progressElement.hidden = true; } statusElement.innerHTML = text; }, totalDependencies: 0, monitorRunDependencies: function(left) { this.totalDependencies = Math.max(this.totalDependencies, left); Module.setStatus(left ? 'Preparing... (' + (this.totalDependencies-left) + '/' + this.totalDependencies + ')' : 'All downloads complete.'); } }; Module.setStatus('Downloading...'); </script> {{{ SCRIPT }}} </body> </html>
slightperturbation/Cobalt
ext/emsdk_portable/emscripten/tag-1.34.1/tests/sdl_canvas_size.html
HTML
apache-2.0
3,978
# Copyright (c) 2015-2016 Tigera, Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import copy import os import re import socket import sys import tempfile from datetime import datetime from subprocess import CalledProcessError from subprocess import check_output, STDOUT import termios import json import logging from pprint import pformat import yaml from deepdiff import DeepDiff LOCAL_IP_ENV = "MY_IP" LOCAL_IPv6_ENV = "MY_IPv6" logger = logging.getLogger(__name__) ETCD_SCHEME = os.environ.get("ETCD_SCHEME", "http") ETCD_CA = os.environ.get("ETCD_CA_CERT_FILE", "") ETCD_CERT = os.environ.get("ETCD_CERT_FILE", "") ETCD_KEY = os.environ.get("ETCD_KEY_FILE", "") ETCD_HOSTNAME_SSL = "etcd-authority-ssl" KUBECONFIG = "/home/user/certs/kubeconfig" API_VERSION = 'projectcalico.org/v3' ERROR_CONFLICT = "update conflict" NOT_FOUND = "resource does not exist" NOT_NAMESPACED = "is not namespaced" SET_DEFAULT = "Cannot set" NOT_SUPPORTED = "is not supported on" KUBERNETES_NP = "kubernetes network policies must be managed through the kubernetes API" NOT_LOCKED = "Datastore is not locked. Run the `calicoctl datastore migrate lock` command in order to begin migration." NOT_KUBERNETES = "Invalid datastore type: etcdv3 to import to for datastore migration. Datastore type must be kubernetes" NO_IPAM = "No IPAM resources specified in file" class CalicoctlOutput: """ CalicoctlOutput contains the output from running a calicoctl command using the calicoctl function below. This class contains the command, output and error code (if it failed) along with YAML/JSON decoded output if the output could be decoded. """ def __init__(self, command, output, error=None): self.command = command self.output = output self.error = error # Attempt to decode the output and store the output format. self.decoded, self.decoded_format = decode_json_yaml(self.output) def assert_data(self, data, format="yaml", text=None): """ Assert the decoded output from the calicoctl command matches the supplied data and the expected decoder format. Args: data: The data to compare format: The expected output format of the data. text: (optional) Expected text in the command output. """ self.assert_no_error(text) assert self.decoded is not None, "No value was decoded from calicoctl response." if isinstance(data, str): data, _ = decode_json_yaml(data) assert data is not None, "String data did not decode" if format is not None: assert format == self.decoded_format, "Decoded format is different. " \ "expect %s; got %s" % (format, self.decoded_format) # Copy and clean the decoded data to allow it to be comparable. cleaned = clean_calico_data(self.decoded) assert cmp(cleaned, data) == 0, \ "Items are not the same. Difference is:\n %s" % \ pformat(DeepDiff(cleaned, data), indent=2) def assert_empty_list(self, kind, format="yaml", text=None): """ Assert the calicoctl command output an empty list of the specified kind. Args: kind: The resource kind. format: The expected output format of the data. text: (optional) Expected text in the command output. Returns: """ data = make_list(kind, []) self.assert_data(data, format=format, text=text) def assert_list(self, kind, items, format="yaml", text=None): """ Assert the calicoctl command output a list of the specified kind. Args: kind: The resource kind. items: A list of the items in the list. format: The expected output format of the data. text: (optional) Expected text in the command output. Returns: """ data = make_list(kind, items) self.assert_data(data, format=format, text=text) def assert_error(self, text=None): """ Assert the calicoctl command exited with an error and did not panic Args: text: (optional) Expected text in the command output. """ assert self.error, "Expected error running command; \n" \ "command=" + self.command + "\noutput=" + self.output assert not "panic" in self.output, "Exited with an error due to a panic" self.assert_output_contains(text) def assert_no_error(self, text=None): """ Assert the calicoctl command did not exit with an error code. Args: text: (optional) Expected text in the command output. """ assert not self.error, "Expected no error running command; \n" \ "command=" + self.command + "\noutput=" + self.output # If text is supplied, assert it appears in the output if text: self.assert_output_contains(text) def assert_output_equals(self, text): """ Assert the calicoctl command output is exactly the supplied text. Args: text: Expected text in the command output. """ if not text: return assert text == self.output, "Expected output to exactly match; \n" + \ "command=" + self.command + "\noutput=\n" + self.output + \ "\nexpected=\n" + text def assert_output_equals_ignore_res_version(self, text): """ Assert the calicoctl command output is exactly the supplied text. Args: text: Expected text in the command output. """ if not text: return text = re.sub('resourceVersion: ".*?"', 'resourceVersion: "<ignored>"', text) out = re.sub('resourceVersion: ".*?"', 'resourceVersion: "<ignored>"', self.output) assert text == out, "Expected output to match after ignoring resource version; \n" + \ "command=" + self.command + "\noutput=\n" + out + \ "\nexpected=\n" + text def assert_output_contains(self, text): """ Assert the calicoctl command output contains the supplied text. Args: text: Expected text in the command output. """ if not text: return assert text in self.output, "Expected text in output; \n" + \ "command=" + self.command + "\noutput=\n" + self.output + \ "\nexpected=\n" + text def assert_output_not_contains(self, text): """ Assert the calicoctl command output does not contain the supplied text. Args: text: Expected text in the command output. """ if not text: return assert not text in self.output, "Unexpected text in output; \n" + \ "command=" + self.command + "\noutput=\n" + self.output + \ "\nunexpected=\n" + text def calicoctl(command, data=None, load_as_stdin=False, format="yaml", only_stdout=False, no_config=False, kdd=False, allowVersionMismatch=True): """ Convenience function for abstracting away calling the calicoctl command. :param command: The calicoctl command line parms as a single string. :param data: Input data either as a string or a JSON serializable Python object. :param load_as_stdin: Load the input data through stdin rather than by loading from file. :param format: Specify the format for loading the data. :param only_stdout: Return only the stdout :return: The output from the command with leading and trailing whitespace removed. """ # If input data is specified, save it to file in the required format. if isinstance(data, str): data, _ = decode_json_yaml(data) assert data is not None, "String data did not decode" if data is not None: if format == "yaml": writeyaml("/tmp/input-data", data) else: writejson("/tmp/input-data", data) stdin = '' option_file = '' if data and load_as_stdin: stdin = 'cat /tmp/input-data | ' option_file = ' -f -' elif data and not load_as_stdin: option_file = ' -f /tmp/input-data' calicoctl_bin = os.environ.get("CALICOCTL", "/code/bin/calicoctl-linux-amd64") if allowVersionMismatch: calicoctl_bin += " --allow-version-mismatch" if ETCD_SCHEME == "https": etcd_auth = "%s:2379" % ETCD_HOSTNAME_SSL else: etcd_auth = "%s:2379" % get_ip() # Export the environment, in case the command has multiple parts, e.g. # use of | or ; # # Pass in all etcd params, the values will be empty if not set anyway calicoctl_env_cmd = "export ETCD_ENDPOINTS=%s; " \ "export ETCD_CA_CERT_FILE=%s; " \ "export ETCD_CERT_FILE=%s; " \ "export ETCD_KEY_FILE=%s; " \ "export DATASTORE_TYPE=%s; %s %s" % \ (ETCD_SCHEME+"://"+etcd_auth, ETCD_CA, ETCD_CERT, ETCD_KEY, "etcdv3", stdin, calicoctl_bin) if kdd: calicoctl_env_cmd = "export DATASTORE_TYPE=kubernetes; " \ "export KUBECONFIG=%s; %s %s" % \ (KUBECONFIG, stdin, calicoctl_bin) if no_config : calicoctl_env_cmd = calicoctl_bin full_cmd = calicoctl_env_cmd + " " + command + option_file try: output = log_and_run(full_cmd, stderr=(None if only_stdout else STDOUT)) return CalicoctlOutput(full_cmd, output) except CalledProcessError as e: return CalicoctlOutput(full_cmd, e.output, error=e.returncode) def clean_calico_data(data, extra_keys_to_remove=None): """ Clean the data returned from a calicoctl get command to remove empty structs, null values and non-configurable fields. This makes comparison with the input data much simpler. Args: data: The data to clean. extra_keys_to_remove: more keys to remove if needed. Returns: The cleaned data. """ new = copy.deepcopy(data) # Recursively delete empty structs / nil values and non-configurable # fields. def clean_elem(elem, extra_keys): if isinstance(elem, list): # Loop through each element in the list for i in elem: clean_elem(i, extra_keys) if isinstance(elem, dict): # Remove non-settable fields, and recursively clean each value of # the dictionary, removing nil values or values that are empty # dicts after cleaning. del_keys = ['creationTimestamp', 'resourceVersion', 'uid'] if extra_keys is not None: for extra_key in extra_keys: del_keys.append(extra_key) for k, v in elem.iteritems(): clean_elem(v, extra_keys) if v is None or v == {}: del_keys.append(k) for k in del_keys: if k in elem: del(elem[k]) clean_elem(new, extra_keys_to_remove) return new def decode_json_yaml(value): try: decoded = json.loads(value) # fix the python datetime back into isoformat with empty timezone information decoded = find_and_format_creation_timestamp(decoded) return decoded, "json" except ValueError: pass try: decoded = yaml.safe_load(value) # fix the python datetime back into isoformat with empty timezone information decoded = find_and_format_creation_timestamp(decoded) return decoded, "yaml" except yaml.YAMLError: pass return None, None def find_and_format_creation_timestamp(decoded): if decoded: if 'items' in decoded: for i in xrange(len(decoded['items'])): decoded['items'][i] = format_creation_timestamp(decoded['items'][i]) else: decoded = format_creation_timestamp(decoded) return decoded def format_creation_timestamp(decoded): if isinstance(decoded, dict) and 'metadata' in decoded and 'creationTimestamp' in decoded['metadata']: if isinstance(decoded['metadata']['creationTimestamp'], datetime): decoded['metadata']['creationTimestamp'] = decoded.get('metadata', {}). \ get('creationTimestamp', datetime.utcnow()).isoformat() + 'Z' return decoded def writeyaml(filename, data): """ Converts a python dict to yaml and outputs to a file. :param filename: filename to write :param data: dictionary to write out as yaml """ with open(filename, 'w') as f: text = yaml.dump(data, default_flow_style=False) logger.debug("Writing %s: \n%s" % (filename, truncate_for_log(text, 4000))) f.write(text) def writejson(filename, data): """ Converts a python dict to json and outputs to a file. :param filename: filename to write :param data: dictionary to write out as json """ with open(filename, 'w') as f: text = json.dumps(data, sort_keys=True, indent=2, separators=(',', ': ')) logger.debug("Writing %s: \n%s" % (filename, truncate_for_log(text, 4000))) f.write(text) def truncate_for_log(text, length): if len(text) <=length: return text return text[:length] + "... <truncated>" def get_ip(v6=False): """ Return a string of the IP of the hosts interface. Try to get the local IP from the environment variables. This allows testers to specify the IP address in cases where there is more than one configured IP address for the test system. """ env = LOCAL_IPv6_ENV if v6 else LOCAL_IP_ENV ip = os.environ.get(env) if not ip: logger.debug("%s not set; try to auto detect IP.", env) socket_type = socket.AF_INET6 if v6 else socket.AF_INET s = socket.socket(socket_type, socket.SOCK_DGRAM) remote_ip = "2001:4860:4860::8888" if v6 else "8.8.8.8" s.connect((remote_ip, 0)) ip = s.getsockname()[0] s.close() else: logger.debug("Got local IP from %s=%s", env, ip) return ip # Some of the commands we execute like to mess with the TTY configuration, # which can break the output formatting. As a wrokaround, save off the # terminal settings and restore them after each command. _term_settings = termios.tcgetattr(sys.stdin.fileno()) def log_and_run(command, raise_exception_on_failure=True, stderr=STDOUT): def log_output(results): if results is None: logger.info(" # <no output>") lines = results.split("\n") for line in lines: logger.info(" # %s", line.rstrip()) try: logger.info("%s", command) try: results = check_output(command, shell=True, stderr=stderr).rstrip() finally: # Restore terminal settings in case the command we ran manipulated # them. Note: under concurrent access, this is still not a perfect # solution since another thread's child process may break the # settings again before we log below. termios.tcsetattr(sys.stdin.fileno(), termios.TCSADRAIN, _term_settings) log_output(results) return results except CalledProcessError as e: # Wrap the original exception with one that gives a better error # message (including command output). logger.info(" # Return code: %s", e.returncode) log_output(e.output) if raise_exception_on_failure: raise e def curl_etcd(path, options=None, recursive=True, ip=None): """ Perform a curl to etcd, returning JSON decoded response. :param path: The key path to query :param options: Additional options to include in the curl :param recursive: Whether we want recursive query or not :return: The JSON decoded response. """ if options is None: options = [] if ETCD_SCHEME == "https": # Etcd is running with SSL/TLS, require key/certificates rc = check_output( "curl --cacert %s --cert %s --key %s " "-sL https://%s:2379/v2/keys/%s?recursive=%s %s" % (ETCD_CA, ETCD_CERT, ETCD_KEY, ETCD_HOSTNAME_SSL, path, str(recursive).lower(), " ".join(options)), shell=True) else: rc = check_output( "curl -sL http://%s:2379/v2/keys/%s?recursive=%s %s" % (ip, path, str(recursive).lower(), " ".join(options)), shell=True) logger.info("etcd RC: %s" % rc.strip()) return json.loads(rc.strip()) def wipe_etcd(ip): # Delete /calico if it exists. This ensures each test has an empty data # store at start of day. curl_etcd("calico", options=["-XDELETE"], ip=ip) # Disable Usage Reporting to usage.projectcalico.org # We want to avoid polluting analytics data with unit test noise curl_etcd("calico/v1/config/UsageReportingEnabled", options=["-XPUT -d value=False"], ip=ip) etcd_container_name = "calico-etcd" tls_vars = "" if ETCD_SCHEME == "https": # Etcd is running with SSL/TLS, require key/certificates etcd_container_name = "calico-etcd-ssl" tls_vars = ("ETCDCTL_CACERT=/etc/calico/certs/ca.pem " + "ETCDCTL_CERT=/etc/calico/certs/client.pem " + "ETCDCTL_KEY=/etc/calico/certs/client-key.pem ") check_output("docker exec " + etcd_container_name + " sh -c '" + tls_vars + "ETCDCTL_API=3 etcdctl del --prefix /calico" + "'", shell=True) def make_list(kind, items): """ Convert the list of resources into a single List resource type. Args: items: A list of the resources in the List object. Returns: None """ assert isinstance(items, list) if "List" not in kind: kind = kind + "List" return { 'kind': kind, 'apiVersion': API_VERSION, 'items': items, } def name(data): """ Returns the name of the resource in the supplied data Args: data: A dictionary containing the resource. Returns: The resource name. """ return data['metadata']['name'] def namespace(data): """ Returns the namespace of the resource in the supplied data Args: data: A dictionary containing the resource. Returns: The resource name. """ return data['metadata']['namespace'] def set_cluster_version(calico_version="", kdd=False): """ Set Calico version in ClusterInformation using the calico_version_helper go app. Args: calico_version: string with version to set kdd: optional bool to indicate use of kubernetes datastore (default False) Returns: The command output """ if ETCD_SCHEME == "https": etcd_auth = "%s:2379" % ETCD_HOSTNAME_SSL else: etcd_auth = "%s:2379" % get_ip() calico_helper_bin = "/code/tests/fv/helper/bin/calico_version_helper" full_cmd = "export ETCD_ENDPOINTS=%s; " \ "export ETCD_CA_CERT_FILE=%s; " \ "export ETCD_CERT_FILE=%s; " \ "export ETCD_KEY_FILE=%s; " \ "export DATASTORE_TYPE=%s; %s" % \ (ETCD_SCHEME+"://"+etcd_auth, ETCD_CA, ETCD_CERT, ETCD_KEY, "etcdv3", calico_helper_bin) if kdd: full_cmd = "export DATASTORE_TYPE=kubernetes; " \ "export KUBECONFIG=%s; %s" % \ (KUBECONFIG, calico_helper_bin) if calico_version: full_cmd += " -v " + calico_version try: output = log_and_run(full_cmd, stderr=STDOUT) return CalicoctlOutput(full_cmd, output) except CalledProcessError as e: return CalicoctlOutput(full_cmd, e.output, error=e.returncode)
projectcalico/calico
calicoctl/tests/st/utils/utils.py
Python
apache-2.0
20,521
body { margin: 0px; } #reply_main { width: 1000px; margin: auto; font-family: "方正大黑"; font-size: 20px; color: #666666; } #message { width: 960px; padding: 30px; margin: auto; } #reply_main textarea { width: 960px; height: 250px; margin: auto; }
hfutxqd/keding_website
css/reply.css
CSS
apache-2.0
295
python manage.py collectstatic python manage.py runserver --nostatic urlpatterns += patterns('', (r'^static/suit/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.DJANGO_SUIT_TEMPLATE}), ) urlpatterns += patterns('', (r'^static/admin/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.DJANGO_ADMIN_TEMPLATE}), ) SITE_PATH = os.path.dirname(__file__) REPO_ROOT = os.path.normpath(os.path.join(SITE_PATH, '..')) MEDIA_ROOT = os.path.join(REPO_ROOT, 'public/media') DJANGO_SUIT_TEMPLATE = os.path.join(REPO_ROOT, 'static/suit') DJANGO_EDITOR = os.path.join(REPO_ROOT, 'static/django_summernote') DJANGO_ADMIN_TEMPLATE = os.path.join(REPO_ROOT, 'static/admin')
pisun2/python
static.py
Python
apache-2.0
711
package com.wolfsoft.epower; import android.app.ActionBar; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.TextView; public class Total extends Activity{ int total; String badge; Integer img; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.total); // get action bar ActionBar actionBar = getActionBar(); // Enabling Up / Back navigation actionBar.setDisplayHomeAsUpEnabled(true); TextView score = (TextView)findViewById(R.id.score); ImageView iView = (ImageView) findViewById(R.id.badge); //getting variable total from previous question using intent Intent intent = getIntent(); total = intent.getIntExtra("total", 0); if(total==0) { badge="Learner"; img=R.drawable.badge_learner; iView.setImageResource(img); score.setText("You won : " +badge+" Bagde.You need to learn how to save energy!! Your Score is " +total); } if(total>0&&total<20) { img=R.drawable.badge_newbee; iView.setImageResource(img); badge="Newbee"; score.setText("You won : " +badge+" Bagde.You know how to save energy!! Your Score is " +total); } if(total>=20) { img=R.drawable.badge_greenbee; iView.setImageResource(img); badge="Greenbee"; score.setText("You won : " +badge+" Bagde.You are expert in saving energy!! Your Score is " +total); } } public void share(View v) { if(total==0) { Uri imageUri = Uri.parse("android.resource://com.wolfsoft.epower/drawable/badge_learner"); Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("image/png"); intent.putExtra(Intent.EXTRA_STREAM, imageUri); startActivity(Intent.createChooser(intent , "Share")); } if(total>0&&total<20) { Uri imageUri = Uri.parse("android.resource://com.wolfsoft.epower/drawable/badge_newbee"); Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("image/png"); intent.putExtra(Intent.EXTRA_STREAM, imageUri); startActivity(Intent.createChooser(intent , "Share")); } if(total>=20) { Uri imageUri = Uri.parse("android.resource://com.wolfsoft.epower/drawable/badge_greenbee"); Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("image/png"); intent.putExtra(Intent.EXTRA_STREAM, imageUri); startActivity(Intent.createChooser(intent , "Share")); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: Intent intent = new Intent(this,MainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); overridePendingTransition(R.anim.anim_slide_in_left, R.anim.anim_slide_out_right); default: return super.onOptionsItemSelected(item); } } public void tips(View V) { Intent intent2 = new Intent(this, Tips.class); startActivity(intent2); overridePendingTransition(R.anim.anim_slide_in_left, R.anim.anim_slide_out_right); } }
harshdattani/power-consumption-android
src/com/wolfsoft/epower/Total.java
Java
apache-2.0
3,462
using System.Collections.Generic; namespace ServerMonitoring.WindowsAgent.Services.CPU { public interface ICpuNameService { IEnumerable<string> GetCPUNames(); } }
ZOXEXIVO/ServerMonitoring
src/Agents/ServerMonitoring.WindowsAgent/Services/CPU/ICPUNameService.cs
C#
apache-2.0
196
#!/usr/bin/env python # Copyright 2015 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import from importlib import import_module import logging import os import sys import click from colorlog import ColoredFormatter logger = logging.getLogger(__name__) def setup_logging(): # pragma: no cover root_logger = logging.getLogger() root_logger.setLevel(logging.INFO) handler = logging.StreamHandler() formatter = ColoredFormatter( "%(log_color)s%(levelname)-8s%(reset)s %(asctime)s %(green)s%(name)s" "%(reset)s %(message)s", reset=True, log_colors={ 'DEBUG': 'cyan', 'INFO': 'blue', 'WARNING': 'yellow', 'ERROR': 'red', 'CRITICAL': 'red,bg_white', } ) handler.setFormatter(formatter) root_logger.addHandler(handler) def import_queue(location): module, attr = location.rsplit('.', 1) module = import_module(module) queue = getattr(module, attr) if hasattr(queue, '__call__'): queue = queue() return queue @click.command() @click.option( '--path', '-p', help='Import path. By default, this is the current working directory.') @click.option( '--pid', help='Write the process ID to the specified file.') @click.argument( 'queue', nargs=1, required=True) def main(path, pid, queue): """ Standalone PSQ worker. The queue argument must be the full importable path to a psq.Queue instance. Example usage: psqworker config.q psqworker --path /opt/app queues.fast """ setup_logging() if pid: with open(os.path.expanduser(pid), "w") as f: f.write(str(os.getpid())) if not path: path = os.getcwd() sys.path.insert(0, path) queue = import_queue(queue) import psq worker = psq.Worker(queue=queue) worker.listen() if __name__ == '__main__': main()
GoogleCloudPlatform/psq
psq/psqworker.py
Python
apache-2.0
2,499
"use strict"; /** @test {index} */ describe("index", () => { });
Product-Foundry/business-elements-angular
test/index_test.js
JavaScript
apache-2.0
66
/* * SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD * * SPDX-License-Identifier: Apache-2.0 */ #ifndef FREERTOS_CONFIG_SMP_H #define FREERTOS_CONFIG_SMP_H #include "sdkconfig.h" /* This file get's pulled into assembly sources. Therefore, some includes need to be wrapped in #ifndef __ASSEMBLER__ */ #ifndef __ASSEMBLER__ #include <assert.h> //For configASSERT() #endif /* def __ASSEMBLER__ */ /* Required for configuration-dependent settings. */ #include "xtensa_config.h" /* -------------------------------------------- Xtensa Additional Config ---------------------------------------------- * - Provide Xtensa definitions usually given by -D option when building with xt-make (see readme_xtensa.txt) * - xtensa_rtos.h and xtensa_timer.h will default some of these values * - XT_SIMULATOR configXT_SIMULATOR * - XT_BOARD configXT_BOARD * - XT_CLOCK_FREQ Should not be defined as we are using XT_BOARD mode * - XT_TICK_PER_SEC Defaults to configTICK_RATE_HZ * - XT_TIMER_INDEX Defaults to configXT_TIMER_INDEX * - XT_INTEXC_HOOKS Defaults to configXT_INTEXC_HOOKS * - XT_USE_OVLY We don't define this (unused) * - XT_USE_SWPRI We don't define this (unused) * ------------------------------------------------------------------------------------------------------------------ */ #define configXT_SIMULATOR 0 #define configXT_BOARD 1 /* Board mode */ #if CONFIG_FREERTOS_CORETIMER_0 #define configXT_TIMER_INDEX 0 #elif CONFIG_FREERTOS_CORETIMER_1 #define configXT_TIMER_INDEX 1 #endif #define configXT_INTEXC_HOOKS 0 #define configBENCHMARK 0 /* ------------------------------------------------ ESP-IDF Additions -------------------------------------------------- * * ------------------------------------------------------------------------------------------------------------------ */ /* The Xtensa port uses a separate interrupt stack. Adjust the stack size * to suit the needs of your specific application. * Size needs to be aligned to the stack increment, since the location of * the stack for the 2nd CPU will be calculated using configISR_STACK_SIZE. */ #define configSTACK_ALIGNMENT 16 #ifndef configISR_STACK_SIZE #define configISR_STACK_SIZE ((CONFIG_FREERTOS_ISR_STACKSIZE + configSTACK_ALIGNMENT - 1) & (~(configSTACK_ALIGNMENT - 1))) #endif /* ----------------------------------------------------- Helpers ------------------------------------------------------- * - Macros that the FreeRTOS configuration macros depend on * ------------------------------------------------------------------------------------------------------------------ */ /* Higher stack checker modes cause overhead on each function call */ #if CONFIG_STACK_CHECK_ALL || CONFIG_STACK_CHECK_STRONG #define STACK_OVERHEAD_CHECKER 256 #else #define STACK_OVERHEAD_CHECKER 0 #endif /* with optimizations disabled, scheduler uses additional stack */ #if CONFIG_COMPILER_OPTIMIZATION_NONE #define STACK_OVERHEAD_OPTIMIZATION 320 #else #define STACK_OVERHEAD_OPTIMIZATION 0 #endif /* apptrace mdule increases minimum stack usage */ #if CONFIG_APPTRACE_ENABLE #define STACK_OVERHEAD_APPTRACE 1280 #else #define STACK_OVERHEAD_APPTRACE 0 #endif /* Stack watchpoint decreases minimum usable stack size by up to 60 bytes. See FreeRTOS FREERTOS_WATCHPOINT_END_OF_STACK option in Kconfig. */ #if CONFIG_FREERTOS_WATCHPOINT_END_OF_STACK #define STACK_OVERHEAD_WATCHPOINT 60 #else #define STACK_OVERHEAD_WATCHPOINT 0 #endif #define configSTACK_OVERHEAD_TOTAL ( \ STACK_OVERHEAD_CHECKER + \ STACK_OVERHEAD_OPTIMIZATION + \ STACK_OVERHEAD_APPTRACE + \ STACK_OVERHEAD_WATCHPOINT \ ) /* ----------------------------------------------------- Helpers ------------------------------------------------------- * - Macros that the FreeRTOS configuration macros depend on * ------------------------------------------------------------------------------------------------------------------ */ /* ------------------------------------------------- FreeRTOS Config --------------------------------------------------- * - All Vanilla FreeRTOS configuration goes into this section * - Keep this section in-sync with the corresponding version of single-core upstream version of FreeRTOS * - Don't put any SMP or ESP-IDF exclusive FreeRTOS configurations here. Those go into the next section * - Not all FreeRTOS configuration are listed. Some configurations have default values set in FreeRTOS.h thus don't * need to be explicitly defined. * ------------------------------------------------------------------------------------------------------------------ */ /*----------------------------------------------------------- * Application specific definitions. * * These definitions should be adjusted for your particular hardware and * application requirements. * * THESE PARAMETERS ARE DESCRIBED WITHIN THE 'CONFIGURATION' SECTION OF THE * FreeRTOS API DOCUMENTATION AVAILABLE ON THE FreeRTOS.org WEB SITE. * * See http://www.freertos.org/a00110.html *----------------------------------------------------------*/ // ------------------ Scheduler Related -------------------- #define configUSE_PREEMPTION 1 #define configUSE_TASK_PREEMPTION_DISABLE 1 #define configUSE_TICKLESS_IDLE 0 #define configCPU_CLOCK_HZ (CONFIG_ESP32_DEFAULT_CPU_FREQ_MHZ * 1000000) #define configTICK_RATE_HZ CONFIG_FREERTOS_HZ #define configMAX_PRIORITIES ( 25 ) //This has impact on speed of search for highest priority #define configMINIMAL_STACK_SIZE ( 768 + configSTACK_OVERHEAD_TOTAL ) #define configUSE_TIME_SLICING 1 #define configUSE_16_BIT_TICKS 0 #define configIDLE_SHOULD_YIELD 0 //Todo: Check this #define configKERNEL_INTERRUPT_PRIORITY 1 //Todo: This currently isn't used anywhere #define configMAX_API_CALL_INTERRUPT_PRIORITY XCHAL_EXCM_LEVEL #define configUSE_PORT_OPTIMISED_TASK_SELECTION 0 //SMP currently does not support optimized selection // -------------------- FreeRTOS SMP ----------------------- #ifdef CONFIG_FREERTOS_UNICORE #define configNUM_CORES 1 #else #define configNUM_CORES 2 #endif #define configUSE_CORE_AFFINITY 1 #define configRUN_MULTIPLE_PRIORITIES 1 #define configUSE_MINIMAL_IDLE_HOOK 1 // ------------- Synchronization Primitives ---------------- #define configUSE_MUTEXES 1 #define configUSE_RECURSIVE_MUTEXES 1 #define configUSE_COUNTING_SEMAPHORES 1 #define configUSE_QUEUE_SETS 1 #define configQUEUE_REGISTRY_SIZE CONFIG_FREERTOS_QUEUE_REGISTRY_SIZE #define configUSE_TASK_NOTIFICATIONS 1 #define configTASK_NOTIFICATION_ARRAY_ENTRIES 1 // ----------------------- System -------------------------- #define configMAX_TASK_NAME_LEN CONFIG_FREERTOS_MAX_TASK_NAME_LEN #define configNUM_THREAD_LOCAL_STORAGE_POINTERS CONFIG_FREERTOS_THREAD_LOCAL_STORAGE_POINTERS #define configSTACK_DEPTH_TYPE uint32_t #define configUSE_NEWLIB_REENTRANT 1 #define configENABLE_BACKWARD_COMPATIBILITY 0 #define configASSERT(a) assert(a) #define configINCLUDE_FREERTOS_TASK_C_ADDITIONS_H 1 // ----------------------- Memory ------------------------- #define configSUPPORT_STATIC_ALLOCATION 1 #define configSUPPORT_DYNAMIC_ALLOCATION 1 //We define the heap to span all of the non-statically-allocated shared RAM. ToDo: Make sure there //is some space left for the app and main cpu when running outside of a thread. #define configTOTAL_HEAP_SIZE (&_heap_end - &_heap_start)//( ( size_t ) (64 * 1024) ) #define configAPPLICATION_ALLOCATED_HEAP 1 #define configSTACK_ALLOCATION_FROM_SEPARATE_HEAP 0 //Todo: Check this // ------------------------ Hooks -------------------------- #define configUSE_IDLE_HOOK 1 #define configUSE_TICK_HOOK 1 #if CONFIG_FREERTOS_CHECK_STACKOVERFLOW_NONE #define configCHECK_FOR_STACK_OVERFLOW 0 #elif CONFIG_FREERTOS_CHECK_STACKOVERFLOW_PTRVAL #define configCHECK_FOR_STACK_OVERFLOW 1 #elif CONFIG_FREERTOS_CHECK_STACKOVERFLOW_CANARY #define configCHECK_FOR_STACK_OVERFLOW 2 #endif #define configRECORD_STACK_HIGH_ADDRESS 1 // ------------------- Run-time Stats ---------------------- #ifdef CONFIG_FREERTOS_GENERATE_RUN_TIME_STATS #define configGENERATE_RUN_TIME_STATS 1 /* Used by vTaskGetRunTimeStats() */ #endif #ifdef CONFIG_FREERTOS_USE_TRACE_FACILITY #define configUSE_TRACE_FACILITY 1 /* Used by uxTaskGetSystemState(), and other trace facility functions */ #endif #ifdef CONFIG_FREERTOS_USE_STATS_FORMATTING_FUNCTIONS #define configUSE_STATS_FORMATTING_FUNCTIONS 1 /* Used by vTaskList() */ #endif // -------------------- Co-routines ----------------------- #define configUSE_CO_ROUTINES 0 #define configMAX_CO_ROUTINE_PRIORITIES 2 // ------------------- Software Timer ---------------------- #define configUSE_TIMERS 1 #define configTIMER_TASK_PRIORITY CONFIG_FREERTOS_TIMER_TASK_PRIORITY #define configTIMER_QUEUE_LENGTH CONFIG_FREERTOS_TIMER_QUEUE_LENGTH #define configTIMER_TASK_STACK_DEPTH CONFIG_FREERTOS_TIMER_TASK_STACK_DEPTH // -------------------- API Includes ----------------------- #define configENABLE_BACKWARD_COMPATIBILITY 0 #define INCLUDE_vTaskPrioritySet 1 #define INCLUDE_uxTaskPriorityGet 1 #define INCLUDE_vTaskDelete 1 #define INCLUDE_vTaskSuspend 1 #define INCLUDE_xTaskDelayUntil 1 #define INCLUDE_vTaskDelay 1 #define INCLUDE_xTaskGetIdleTaskHandle 1 #define INCLUDE_xTaskAbortDelay 1 #define INCLUDE_xSemaphoreGetMutexHolder 1 #define INCLUDE_xTaskGetHandle 1 #define INCLUDE_uxTaskGetStackHighWaterMark 1 #define INCLUDE_uxTaskGetStackHighWaterMark2 0 #define INCLUDE_eTaskGetState 1 #define INCLUDE_xTaskResumeFromISR 1 #define INCLUDE_xTimerPendFunctionCall 1 #define INCLUDE_xTaskGetSchedulerState 1 #define INCLUDE_xTaskGetCurrentTaskHandle 1 // -------------------- Trace Macros ----------------------- /* For trace macros. Note: Include trace macros here and not above as trace macros are dependent on some of the FreeRTOS configs */ #ifndef __ASSEMBLER__ #if CONFIG_SYSVIEW_ENABLE #include "SEGGER_SYSVIEW_FreeRTOS.h" #undef INLINE // to avoid redefinition #endif //CONFIG_SYSVIEW_ENABLE #endif /* def __ASSEMBLER__ */ /* Default values for trace macros added by ESP-IDF and are not part of Vanilla FreeRTOS */ #ifndef traceISR_EXIT #define traceISR_EXIT() #endif #ifndef traceISR_ENTER #define traceISR_ENTER(_n_) #endif /* ------------------------------------------------ IDF Compatibility -------------------------------------------------- * - We need these in order for ESP-IDF to compile * ------------------------------------------------------------------------------------------------------------------ */ #define portNUM_PROCESSORS configNUM_CORES #ifdef CONFIG_FREERTOS_VTASKLIST_INCLUDE_COREID #define configTASKLIST_INCLUDE_COREID 1 #endif #define configTHREAD_LOCAL_STORAGE_DELETE_CALLBACKS 1 #ifndef __ASSEMBLER__ #if CONFIG_APPTRACE_SV_ENABLE extern uint32_t port_switch_flag[]; #define os_task_switch_is_pended(_cpu_) (port_switch_flag[_cpu_]) #else #define os_task_switch_is_pended(_cpu_) (false) #endif #endif // ---------------------- Features ------------------------- #ifdef CONFIG_FREERTOS_ENABLE_TASK_SNAPSHOT #define configENABLE_TASK_SNAPSHOT 1 #else #define configENABLE_TASK_SNAPSHOT 0 #endif /* These currently aren't required, but could be useful additions in the future */ #if 0 #ifndef configIDLE_TASK_STACK_SIZE #define configIDLE_TASK_STACK_SIZE CONFIG_FREERTOS_IDLE_TASK_STACKSIZE #endif #if CONFIG_FREERTOS_CHECK_MUTEX_GIVEN_BY_OWNER #define configCHECK_MUTEX_GIVEN_BY_OWNER 1 #else #define configCHECK_MUTEX_GIVEN_BY_OWNER 0 #endif #ifndef __ASSEMBLER__ #if CONFIG_FREERTOS_ENABLE_STATIC_TASK_CLEAN_UP extern void vPortCleanUpTCB ( void *pxTCB ); #define portCLEAN_UP_TCB( pxTCB ) vPortCleanUpTCB( pxTCB ) #endif #endif #endif //0 // -------------------- Compatibility ---------------------- // backward compatibility for 4.4 #define xTaskRemoveFromUnorderedEventList vTaskRemoveFromUnorderedEventList #endif /* FREERTOS_CONFIG_SMP_H */
espressif/esp-idf
components/freertos/FreeRTOS-Kernel-SMP/portable/xtensa/include/freertos/FreeRTOSConfig_smp.h
C
apache-2.0
14,236
// Copyright (C) 2016 History in Paderborn App - Universität Paderborn // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Threading; using System.Threading.Tasks; using MvvmHelpers; using PaderbornUniversity.SILab.Hip.Mobile.Shared.BusinessLayer.DtoToModelConverters; using PaderbornUniversity.SILab.Hip.Mobile.Shared.BusinessLayer.FeatureToggling; using PaderbornUniversity.SILab.Hip.Mobile.Shared.BusinessLayer.Managers; using PaderbornUniversity.SILab.Hip.Mobile.Shared.Common; using PaderbornUniversity.SILab.Hip.Mobile.Shared.DataAccessLayer; using PaderbornUniversity.SILab.Hip.Mobile.Shared.Helpers; using PaderbornUniversity.SILab.Hip.Mobile.UI.Navigation; using PaderbornUniversity.SILab.Hip.Mobile.UI.ViewModels.Views; using Xamarin.Forms; namespace PaderbornUniversity.SILab.Hip.Mobile.UI.ViewModels { public abstract class NavigationViewModel : BaseViewModel { protected readonly INavigationService Navigation = IoCManager.Resolve<INavigationService>(); protected readonly AchievementNotificationViewModel AchievementNotification = IoCManager.Resolve<AchievementNotificationViewModel>(); /// <summary> /// Method called when the view disappears. Note that this method is not called automatically for every view. /// </summary> public virtual void OnDisappearing() { StopAutoCheckForAchievements(); } /// <summary> /// Method called when the view appears for the first time. Note that this method is not called automatically for every view. /// </summary> public virtual void OnAppearing() { AchievementNotification.ReloadDisplayedData(); StartAutoCheckForAchievements(); } /// <summary> /// Method called when the view is hidden, for example another page is pushed on top of the view. /// </summary> public virtual void OnHidden() { StopAutoCheckForAchievements(); } /// <summary> /// Method called when the view is visible again, after it was hidden. /// </summary> public virtual void OnRevealed() { AchievementNotification.ReloadDisplayedData(); StartAutoCheckForAchievements(); } private int isAutoChecking = 0; private IDisposable achievementFeatureSubscription; private void StartAutoCheckForAchievements() { if (Interlocked.Exchange(ref isAutoChecking, 1) == 1) { return; } var featureObserver = new CachingObserver<bool>(); achievementFeatureSubscription = IoCManager.Resolve<IFeatureToggleRouter>() .IsFeatureEnabled(FeatureId.Achievements) .Subscribe(featureObserver); async Task DequeueAndRepeatAsync() { try { if (featureObserver.Last /* feature is enabled */) { await BackupData.WaitForInitAsync(); var pending = await AchievementManager.DequeuePendingAchievementNotifications(); AchievementNotification.QueueAchievementNotifications(pending); } } catch (InvalidTransactionException) { // Safe to ignore in this case, just retry later. // This can happen because the auto-refresh can interleave // with other transactions that execute asynchronous code // inside them. } await Task.Delay(5000); if (isAutoChecking == 1) { Device.BeginInvokeOnMainThread(async () => await DequeueAndRepeatAsync()); } } Device.BeginInvokeOnMainThread(async () => await DequeueAndRepeatAsync()); } private void StopAutoCheckForAchievements() { if (Interlocked.Exchange(ref isAutoChecking, 0) == 0) { return; } achievementFeatureSubscription?.Dispose(); achievementFeatureSubscription = null; } } }
HiP-App/HiP-Forms
Sources/HipMobileUI/ViewModels/NavigationViewModel.cs
C#
apache-2.0
4,919
package com.sync.sz.web.servlet.session; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * Created by Administrator on 2016/12/15 0015. */ public class SessionDemo2 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setCharacterEncoding("UTF-8"); resp.setContentType("text/html;charset=UTF-8"); PrintWriter out = resp.getWriter(); HttpSession session = req.getSession(false); String product = (String) session.getAttribute("name"); out.write("您购买的商品是:" + product); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doGet(req, resp); } }
MariShunxiang/JavaWebSample
sample-servlet/src/main/java/com/sync/sz/web/servlet/session/SessionDemo2.java
Java
apache-2.0
990
# rustfmt [![Build Status](https://travis-ci.org/rust-lang-nursery/rustfmt.svg)](https://travis-ci.org/rust-lang-nursery/rustfmt) [![Build Status](https://ci.appveyor.com/api/projects/status/github/rust-lang-nursery/rustfmt?svg=true)](https://ci.appveyor.com/api/projects/status/github/rust-lang-nursery/rustfmt) A tool for formatting Rust code according to style guidelines. If you'd like to help out (and you should, it's a fun project!), see [Contributing.md](Contributing.md). ## Quick start To install: ``` cargo install rustfmt ``` to run on a cargo project in the current working directory: ``` cargo fmt ``` ## Installation > **Note:** this method currently requires you to be running cargo 0.6.0 or > newer. ``` cargo install rustfmt ``` or if you're using [`rustup.rs`](https://www.rustup.rs/) ``` rustup run nightly cargo install rustfmt ``` Usually cargo-fmt, which enables usage of Cargo subcommand `cargo fmt`, is installed alongside rustfmt. To only install rustfmt run ``` cargo install --no-default-features rustfmt ``` ## Installing from source To install from source, first checkout to the tag or branch you want to install, then issue ``` cargo install --path . ``` This will install `rustfmt` in your `~/.cargo/bin`. Make sure to add `~/.cargo/bin` directory to your PATH variable. ## Running You can run Rustfmt by just typing `rustfmt filename` if you used `cargo install`. This runs rustfmt on the given file, if the file includes out of line modules, then we reformat those too. So to run on a whole module or crate, you just need to run on the root file (usually mod.rs or lib.rs). Rustfmt can also read data from stdin. Alternatively, you can use `cargo fmt` to format all binary and library targets of your crate. You'll probably want to specify the write mode. Currently, there are modes for diff, replace, overwrite, display, coverage, and checkstyle. * `replace` Is the default and overwrites the original files after creating backups of the files. * `overwrite` Overwrites the original files _without_ creating backups. * `display` Will print the formatted files to stdout. * `diff` Will print a diff between the original files and formatted files to stdout. Will also exit with an error code if there are any differences. * `checkstyle` Will output the lines that need to be corrected as a checkstyle XML file, that can be used by tools like Jenkins. The write mode can be set by passing the `--write-mode` flag on the command line. For example `rustfmt --write-mode=display src/filename.rs` `cargo fmt` uses `--write-mode=replace` by default. If you want to restrict reformatting to specific sets of lines, you can use the `--file-lines` option. Its argument is a JSON array of objects with `file` and `range` properties, where `file` is a file name, and `range` is an array representing a range of lines like `[7,13]`. Ranges are 1-based and inclusive of both end points. Specifying an empty array will result in no files being formatted. For example, ``` rustfmt --file-lines '[ {"file":"src/lib.rs","range":[7,13]}, {"file":"src/lib.rs","range":[21,29]}, {"file":"src/foo.rs","range":[10,11]}, {"file":"src/foo.rs","range":[15,15]}]' ``` would format lines `7-13` and `21-29` of `src/lib.rs`, and lines `10-11`, and `15` of `src/foo.rs`. No other files would be formatted, even if they are included as out of line modules from `src/lib.rs`. If `rustfmt` successfully reformatted the code it will exit with `0` exit status. Exit status `1` signals some unexpected error, like an unknown option or a failure to read a file. Exit status `2` is returned if there are syntax errors in the input files. `rustfmt` can't format syntatically invalid code. Finally, exit status `3` is returned if there are some issues which can't be resolved automatically. For example, if you have a very long comment line `rustfmt` doesn't split it. Instead it prints a warning and exits with `3`. You can run `rustfmt --help` for more information. ## Running Rustfmt from your editor * [Vim](https://github.com/rust-lang/rust.vim#formatting-with-rustfmt) * [Emacs](https://github.com/rust-lang/rust-mode) * [Sublime Text 3](https://packagecontrol.io/packages/BeautifyRust) * [Atom](atom.md) * Visual Studio Code using [RustyCode](https://github.com/saviorisdead/RustyCode) or [vsc-rustfmt](https://github.com/Connorcpu/vsc-rustfmt) ## Checking style on a CI server To keep your code base consistently formatted, it can be helpful to fail the CI build when a pull request contains unformatted code. Using `--write-mode=diff` instructs rustfmt to exit with an error code if the input is not formatted correctly. It will also print any found differences. A minimal Travis setup could look like this: ```yaml language: rust cache: cargo before_script: - export PATH="$PATH:$HOME/.cargo/bin" - which rustfmt || cargo install rustfmt script: - cargo fmt -- --write-mode=diff - cargo build - cargo test ``` Note that using `cache: cargo` is optional but highly recommended to speed up the installation. ## How to build and test `cargo build` to build. `cargo test` to run all tests. To run rustfmt after this, use `cargo run --bin rustfmt -- filename`. See the notes above on running rustfmt. ## Configuring Rustfmt Rustfmt is designed to be very configurable. You can create a TOML file called `rustfmt.toml` or `.rustfmt.toml`, place it in the project or any other parent directory and it will apply the options in that file. See `rustfmt --config-help` for the options which are available, or if you prefer to see source code, [src/config.rs](src/config.rs). By default, Rustfmt uses a style which (mostly) conforms to the [Rust style guidelines](https://doc.rust-lang.org/1.12.0/style/README.html). There are many details which the style guidelines do not cover, and in these cases we try to adhere to a style similar to that used in the [Rust repo](https://github.com/rust-lang/rust). Once Rustfmt is more complete, and able to re-format large repositories like Rust, we intend to go through the Rust RFC process to nail down the default style in detail. If there are styling choices you don't agree with, we are usually happy to add options covering different styles. File an issue, or even better, submit a PR. ## Tips * For things you do not want rustfmt to mangle, use one of ```rust #[rustfmt_skip] // requires nightly and #![feature(custom_attribute)] in crate root #[cfg_attr(rustfmt, rustfmt_skip)] // works in stable ``` * When you run rustfmt, place a file named `rustfmt.toml` or `.rustfmt.toml` in target file directory or its parents to override the default settings of rustfmt. * After successful compilation, a `rustfmt` executable can be found in the target directory. * If you're having issues compiling Rustfmt (or compile errors when trying to install), make sure you have the most recent version of Rust installed. ## License Rustfmt is distributed under the terms of both the MIT license and the Apache License (Version 2.0). See [LICENSE-APACHE](LICENSE-APACHE) and [LICENSE-MIT](LICENSE-MIT) for details.
Emilgardis/rustfmt
README.md
Markdown
apache-2.0
7,146
--- layout: post title: "Linux Command" subtitle: "awk" date: 2017-09-25 12:00:00 author: "Dingding" header-img: "img/post/thrift-header.jpg" header-mask: 0.3 catalog: true tags: - awk - linux command --- 引用自:[三十分钟学会AWK](http://blog.jobbole.com/109089/) ## awk pattern scanning and text processing language 工作流程 ```flow st=>start: Excute AWK commands from BEGIN block e=>end: Excute AWK commands from END block read=>operation: Read a line from input stream execute=>operation: Execute AWK commands on a line cond=>condition: Is it End of File st->read->execute->cond cond(yes)->e cond(no,right)->read ``` *** 程序框架 注意:BEGIN/End是awk的关键字,必须大写 ```bash BEGIN {awk-commands} /pattern/ {awk-commands} END {awk-commands} ``` ## awk example 将最后一列的日期型字符串转为时间戳 ```sh #!/bin/bash awk '{ for (i=1;i<NF;i++){ printf $i "\t"; } cmd=("date +%Y-%m-%d-%H -d @" $NF); system(cmd); printf("\n"); }' $1; ```
DingdingZhou/dingdingzhou.github.io
_posts/2017-10-01-LinuxCommand-awk.md
Markdown
apache-2.0
1,032
# -*- coding: utf-8 -*- # --------------------------------------------------------------------------- # # # socialdata.rb # # Copyright (c) 2013 clown. # # 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. # # --------------------------------------------------------------------------- # require 'socialdata/version' require 'socialdata/uri' require 'socialdata/shortenurl' require 'socialdata/facebook' require 'socialdata/feedly' require 'socialdata/google' require 'socialdata/linkedin' require 'socialdata/pinterest' require 'socialdata/twitter' # API wrapper for Japanese services require 'socialdata/hatena' require 'socialdata/livedoor'
clown/socialdata
lib/socialdata.rb
Ruby
apache-2.0
1,145
# Copyright (c) 2013 Hewlett-Packard Development Company, L.P. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. import json import tempfile import fixtures from lxml import etree from oslo_config import cfg import requests import testtools from testtools import content as test_content from testtools import matchers import urllib.parse as urlparse from os_collect_config import cfn from os_collect_config import collect from os_collect_config import exc META_DATA = {u'int1': 1, u'strfoo': u'foo', u'map_ab': { u'a': 'apple', u'b': 'banana', }} SOFTWARE_CONFIG_DATA = { u'old-style': u'value', u'deployments': [ { u'inputs': [ { u'type': u'String', u'name': u'input1', u'value': u'value1' } ], u'group': 'Heat::Ungrouped', u'name': 'dep-name1', u'outputs': None, u'options': None, u'config': { u'config1': 'value1' } }, { u'inputs': [ { u'type': u'String', u'name': u'input1', u'value': u'value1' } ], u'group': 'os-apply-config', u'name': 'dep-name2', u'outputs': None, u'options': None, u'config': { u'config2': 'value2' } }, { u'inputs': [ { u'type': u'String', u'name': u'input1', u'value': u'value1' } ], u'name': 'dep-name3', u'outputs': None, u'options': None, u'config': { u'config3': 'value3' } }, { u'inputs': [], u'group': 'ignore_me', u'name': 'ignore_me_name', u'outputs': None, u'options': None, u'config': 'ignore_me_config' } ] } SOFTWARE_CONFIG_IMPOSTER_DATA = { u'old-style': u'value', u'deployments': { u"not": u"a list" } } class FakeResponse(dict): def __init__(self, text): self.text = text def raise_for_status(self): pass class FakeReqSession(object): SESSION_META_DATA = META_DATA def __init__(self, testcase, expected_netloc): self._test = testcase self._expected_netloc = expected_netloc self.verify = False def get(self, url, params, headers, verify=None, timeout=None): self._test.addDetail('url', test_content.text_content(url)) url = urlparse.urlparse(url) self._test.assertEqual(self._expected_netloc, url.netloc) self._test.assertEqual('/v1/', url.path) self._test.assertEqual('application/json', headers['Content-Type']) self._test.assertIn('SignatureVersion', params) self._test.assertEqual('2', params['SignatureVersion']) self._test.assertIn('Signature', params) self._test.assertIn('Action', params) self._test.assertEqual('DescribeStackResource', params['Action']) self._test.assertIn('LogicalResourceId', params) self._test.assertEqual('foo', params['LogicalResourceId']) self._test.assertEqual(10, timeout) root = etree.Element('DescribeStackResourceResponse') result = etree.SubElement(root, 'DescribeStackResourceResult') detail = etree.SubElement(result, 'StackResourceDetail') metadata = etree.SubElement(detail, 'Metadata') metadata.text = json.dumps(self.SESSION_META_DATA) if verify is not None: self.verify = True return FakeResponse(etree.tostring(root)) class FakeRequests(object): exceptions = requests.exceptions def __init__(self, testcase, expected_netloc='192.0.2.1:8000'): self._test = testcase self._expected_netloc = expected_netloc def Session(self): return FakeReqSession(self._test, self._expected_netloc) class FakeReqSessionSoftwareConfig(FakeReqSession): SESSION_META_DATA = SOFTWARE_CONFIG_DATA class FakeRequestsSoftwareConfig(FakeRequests): FAKE_SESSION = FakeReqSessionSoftwareConfig def Session(self): return self.FAKE_SESSION(self._test, self._expected_netloc) class FakeReqSessionConfigImposter(FakeReqSession): SESSION_META_DATA = SOFTWARE_CONFIG_IMPOSTER_DATA class FakeRequestsConfigImposter(FakeRequestsSoftwareConfig): FAKE_SESSION = FakeReqSessionConfigImposter class FakeFailRequests(object): exceptions = requests.exceptions class Session(object): def get(self, url, params, headers, verify=None, timeout=None): raise requests.exceptions.HTTPError(403, 'Forbidden') class TestCfnBase(testtools.TestCase): def setUp(self): super(TestCfnBase, self).setUp() self.log = self.useFixture(fixtures.FakeLogger()) self.useFixture(fixtures.NestedTempfile()) self.hint_file = tempfile.NamedTemporaryFile() self.hint_file.write(u'http://192.0.2.1:8000'.encode('utf-8')) self.hint_file.flush() self.addCleanup(self.hint_file.close) collect.setup_conf() cfg.CONF.cfn.heat_metadata_hint = self.hint_file.name cfg.CONF.cfn.metadata_url = None cfg.CONF.cfn.path = ['foo.Metadata'] cfg.CONF.cfn.access_key_id = '0123456789ABCDEF' cfg.CONF.cfn.secret_access_key = 'FEDCBA9876543210' class TestCfn(TestCfnBase): def test_collect_cfn(self): cfn_md = cfn.Collector(requests_impl=FakeRequests(self)).collect() self.assertThat(cfn_md, matchers.IsInstance(list)) self.assertEqual('cfn', cfn_md[0][0]) cfn_md = cfn_md[0][1] for k in ('int1', 'strfoo', 'map_ab'): self.assertIn(k, cfn_md) self.assertEqual(cfn_md[k], META_DATA[k]) self.assertEqual('', self.log.output) def test_collect_with_ca_cert(self): cfn.CONF.cfn.ca_certificate = "foo" collector = cfn.Collector(requests_impl=FakeRequests(self)) collector.collect() self.assertTrue(collector._session.verify) def test_collect_cfn_fail(self): cfn_collect = cfn.Collector(requests_impl=FakeFailRequests) self.assertRaises(exc.CfnMetadataNotAvailable, cfn_collect.collect) self.assertIn('Forbidden', self.log.output) def test_collect_cfn_no_path(self): cfg.CONF.cfn.path = None cfn_collect = cfn.Collector(requests_impl=FakeRequests(self)) self.assertRaises(exc.CfnMetadataNotConfigured, cfn_collect.collect) self.assertIn('No path configured', self.log.output) def test_collect_cfn_bad_path(self): cfg.CONF.cfn.path = ['foo'] cfn_collect = cfn.Collector(requests_impl=FakeRequests(self)) self.assertRaises(exc.CfnMetadataNotConfigured, cfn_collect.collect) self.assertIn('Path not in format', self.log.output) def test_collect_cfn_no_metadata_url(self): cfg.CONF.cfn.heat_metadata_hint = None cfn_collect = cfn.Collector(requests_impl=FakeRequests(self)) self.assertRaises(exc.CfnMetadataNotConfigured, cfn_collect.collect) self.assertIn('No metadata_url configured', self.log.output) def test_collect_cfn_missing_sub_path(self): cfg.CONF.cfn.path = ['foo.Metadata.not_there'] cfn_collect = cfn.Collector(requests_impl=FakeRequests(self)) self.assertRaises(exc.CfnMetadataNotAvailable, cfn_collect.collect) self.assertIn('Sub-key not_there does not exist', self.log.output) def test_collect_cfn_sub_path(self): cfg.CONF.cfn.path = ['foo.Metadata.map_ab'] cfn_collect = cfn.Collector(requests_impl=FakeRequests(self)) content = cfn_collect.collect() self.assertThat(content, matchers.IsInstance(list)) self.assertEqual('cfn', content[0][0]) content = content[0][1] self.assertIn(u'b', content) self.assertEqual(u'banana', content[u'b']) def test_collect_cfn_metadata_url_overrides_hint(self): cfg.CONF.cfn.metadata_url = 'http://127.0.1.1:8000/v1/' cfn_collect = cfn.Collector( requests_impl=FakeRequests(self, expected_netloc='127.0.1.1:8000')) cfn_collect.collect() class TestCfnSoftwareConfig(TestCfnBase): def test_collect_cfn_software_config(self): cfn_md = cfn.Collector( requests_impl=FakeRequestsSoftwareConfig(self)).collect() self.assertThat(cfn_md, matchers.IsInstance(list)) self.assertEqual('cfn', cfn_md[0][0]) cfn_config = cfn_md[0][1] self.assertThat(cfn_config, matchers.IsInstance(dict)) self.assertEqual(set(['old-style', 'deployments']), set(cfn_config.keys())) self.assertIn('deployments', cfn_config) self.assertThat(cfn_config['deployments'], matchers.IsInstance(list)) self.assertEqual(4, len(cfn_config['deployments'])) deployment = cfn_config['deployments'][0] self.assertIn('inputs', deployment) self.assertThat(deployment['inputs'], matchers.IsInstance(list)) self.assertEqual(1, len(deployment['inputs'])) self.assertEqual('dep-name1', cfn_md[1][0]) self.assertEqual('value1', cfn_md[1][1]['config1']) self.assertEqual('dep-name2', cfn_md[2][0]) self.assertEqual('value2', cfn_md[2][1]['config2']) def test_collect_cfn_deployments_not_list(self): cfn_md = cfn.Collector( requests_impl=FakeRequestsConfigImposter(self)).collect() self.assertEqual(1, len(cfn_md)) self.assertEqual('cfn', cfn_md[0][0]) self.assertIn('not', cfn_md[0][1]['deployments']) self.assertEqual('a list', cfn_md[0][1]['deployments']['not'])
openstack/os-collect-config
os_collect_config/tests/test_cfn.py
Python
apache-2.0
10,601