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 © 2021 Cask Data, 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 io.cdap.delta.store; import io.cdap.delta.api.DeltaPipelineId; import io.cdap.delta.app.DeltaWorkerId; import io.cdap.delta.app.OffsetAndSequence; import java.io.IOException; import java.util.Collection; import java.util.HashMap; import java.util.Map; /** * A mock of statestore with stare as in-memory hashmaps */ public class MockStateStore implements StateStore { Map<DeltaWorkerId, OffsetAndSequence> inMemoryOffsetDbTable; Map<String, byte[]> inMemoryStateDbTable; public MockStateStore() { this.inMemoryOffsetDbTable = new HashMap<>(); this.inMemoryStateDbTable = new HashMap<>(); } @Override public OffsetAndSequence readOffset(DeltaWorkerId id) throws IOException { return inMemoryOffsetDbTable.getOrDefault(id, null); } @Override public void writeOffset(DeltaWorkerId id, OffsetAndSequence offset) throws IOException { inMemoryOffsetDbTable.put(id, offset); } @Override public byte[] readState(DeltaWorkerId id, String key) throws IOException { return inMemoryStateDbTable.getOrDefault(makeKey(id, key), new byte[0]); } @Override public void writeState(DeltaWorkerId id, String key, byte[] val) throws IOException { inMemoryStateDbTable.put(makeKey(id, key), val); } @Override public Long getLatestGeneration(String namespace, String pipelineName) throws IOException { return null; } @Override public Collection<Integer> getWorkerInstances(DeltaPipelineId pipelineId) throws IOException { return null; } protected String makeKey(DeltaWorkerId id, String key) { return String.format("%s/%s/%d/%d/%s", id.getPipelineId().getNamespace(), id.getPipelineId().getApp(), id.getPipelineId().getGeneration(), id.getInstanceId(), key); } }
data-integrations/delta
delta-app/src/test/java/io/cdap/delta/store/MockStateStore.java
Java
apache-2.0
2,472
var NAVTREEINDEX40 = { "a04062.html#a5f5772fd72c51be8c6c65a6b442d61f7":[3,0,425,67], "a04062.html#a5fac27fd4b6667de211ec0a12ef85169":[3,0,425,120], "a04062.html#a620c3ec802c8ddf9401a6940f542618e":[3,0,425,29], "a04062.html#a6365787ce52ef1c54d5a031c8436b027":[3,0,425,38], "a04062.html#a65659b4d35490f3e1c56aa0909d8f652":[3,0,425,114], "a04062.html#a668aeeabbdeacf60d9de3421998e56a8":[3,0,425,34], "a04062.html#a695c6503521aee77b82ded641ef4a7f7":[3,0,425,90], "a04062.html#a6960c3b1ab2f43b1fce0e3b2ba7f76ce":[3,0,425,106], "a04062.html#a6b6b33beb6b71f68e56f7f71d29920dc":[3,0,425,2], "a04062.html#a6f37ba61d67608b3bbe4ee059052ffa2":[3,0,425,87], "a04062.html#a6fb6b86210d1dbc4659b16fdbb0c8fb6":[3,0,425,79], "a04062.html#a7137b0679c03e0c5ac2c350470f7c443":[3,0,425,95], "a04062.html#a71f4bab94d9bc56d828c67fb64364c41":[3,0,425,103], "a04062.html#a731ae5deaa31664c9f6b8005a6ce59b4":[3,0,425,91], "a04062.html#a75a347ebcd7fb83bd64e082e0b2b4d8c":[3,0,425,16], "a04062.html#a79626f05c935e856a55d2eb791a327ff":[3,0,425,42], "a04062.html#a7a511c09c29cbbb292a10962ebf63096":[3,0,425,101], "a04062.html#a7b08905b886658665588d77dba7659b5":[3,0,425,12], "a04062.html#a7b52b091edd0c1f5e17539f0d6af0e88":[3,0,425,8], "a04062.html#a7ba0fd9ec420566647db6896ed43cca1":[3,0,425,53], "a04062.html#a7beaad890157210b63decfca37b803f8":[3,0,425,22], "a04062.html#a7c191fe85cb17776f4174d0f33dfb9b8":[3,0,425,93], "a04062.html#a7c9da85f009201434fc0a91c75f1fec7":[3,0,425,55], "a04062.html#a7cbfd800fe71082f0e7d58b7c25330bb":[3,0,425,3], "a04062.html#a7e27b0eba4eb0c2bc54a9f722f5c6f24":[3,0,425,73], "a04062.html#a8103689bf66dd1930cf03d0a1d797732":[3,0,425,69], "a04062.html#a825be92d5127eb24f6be6c9758e5ba4f":[3,0,425,105], "a04062.html#a827f75b58552cff542c08541d743b5cd":[3,0,425,44], "a04062.html#a82b84f1ca3b013768155e0f5da357f20":[3,0,425,4], "a04062.html#a831ce5759880b7296d6b3e98fa004e25":[3,0,425,112], "a04062.html#a83423718639fb7ebac3d0e953ba509dc":[3,0,425,111], "a04062.html#a87558079bfd2d08e0804b287a129f852":[3,0,425,48], "a04062.html#a8ed35ce8ac2e255cb54a2d4fa05a0c8a":[3,0,425,84], "a04062.html#a8fc89717f817046f011380fcbd59566d":[3,0,425,99], "a04062.html#a90e16291d078b5947b683130daf2d2e1":[3,0,425,26], "a04062.html#a94a0b55a15940c12f3dd0247404d681a":[3,0,425,23], "a04062.html#a94c054b76e7a90a0cad46076a493d2d4":[3,0,425,77], "a04062.html#a95da3118bde8cff6270e1e0900ad0b4a":[3,0,425,31], "a04062.html#a976209d578acab17ff9a542ad5b8a5d5":[3,0,425,118], "a04062.html#a98079b3ce062183388c653eee9838e3c":[3,0,425,32], "a04062.html#a9b53b68019f3b7d3c99514eaebfae906":[3,0,425,14], "a04062.html#a9fbe72d0f7a00e1145a663b9e8b8a297":[3,0,425,96], "a04062.html#aa002a9f5d76e241d8ad61a347a5fb734":[3,0,425,72], "a04062.html#aa04e8d42d89768d596556d54b98f4a4e":[3,0,425,28], "a04062.html#aa158fb90fb398c0ef583da1b5dd95c34":[3,0,425,10], "a04062.html#aa19fb595808fe4688c580334937dfa45":[3,0,425,64], "a04062.html#aa422e2b9b4b6e17ac52ac25d88d295db":[3,0,425,1], "a04062.html#aa7b98313c90597573df746f39466d694":[3,0,425,47], "a04062.html#aa7d69d3734c1dd18f8dd9faf34b1de28":[3,0,425,5], "a04062.html#aa9827f44b6199469f81fd3fba6afd94c":[3,0,425,27], "a04062.html#aaecc4315133c7591da37639a20edeb0a":[3,0,425,82], "a04062.html#ab35988d3b9b68bdfeb575845da6d8094":[3,0,425,71], "a04062.html#ab5198816dde686850da3530a1f8261fe":[3,0,425,117], "a04062.html#aba15715072b9c8e3e052eafa99baf24d":[3,0,425,102], "a04062.html#aba87ec0e057ba5195b84da5baa8531f4":[3,0,425,18], "a04062.html#abbbedcfa335cb79cd363306de9dd142a":[3,0,425,46], "a04062.html#abe507c60d543c38d1ac8e6c3b0d4aedb":[3,0,425,56], "a04062.html#abeeceb0e409edbde0695443d9d75e64d":[3,0,425,45], "a04062.html#ac1148cef18a324b1c1eeffaf354ab80f":[3,0,425,13], "a04062.html#ac704da42f758626cf6d24491b5ffb3e5":[3,0,425,81], "a04062.html#acbf8ddf6b543cada513e81416a6c45f9":[3,0,425,61], "a04062.html#aceea03a2d7bc9624b43b0df4a44f6b1b":[3,0,425,21], "a04062.html#ad019b4ee5376a6d413a8e4c72d7e4d7b":[3,0,425,41], "a04062.html#ad042e9120b341046971c5e478c4b7c34":[3,0,425,74], "a04062.html#ad7ede7020e2ae3a93758d7a31696a02c":[3,0,425,58], "a04062.html#ad9060160cd52065e89cbc8927454f525":[3,0,425,6], "a04062.html#adb332692009836a2d89e5fdf63f9765f":[3,0,425,109], "a04062.html#adb90590cd55c782ea614c810e96b11b6":[3,0,425,7], "a04062.html#adc8f0faa582fee9032d19f7f12ef9323":[3,0,425,37], "a04062.html#add8228caaf6c3d2c5b9209117161fa66":[3,0,425,49], "a04062.html#ae73eb409dc9bdc965a572c4fdd010e62":[3,0,425,62], "a04062.html#aeb2253dcb5f01c81fcba5f4af417eadf":[3,0,425,119], "a04062.html#aecb5fe27d6bc4bac136abf86c12dac7d":[3,0,425,89], "a04062.html#af066ba55fdc20f996eaaed05618b377e":[3,0,425,70], "a04062.html#af239030951851e407886701381c5118b":[3,0,425,92], "a04062.html#af299fffe9261cc732b15b4a2fc6b099a":[3,0,425,57], "a04062.html#af64bad78a3e9a130b3dbbf174eeab8f6":[3,0,425,9], "a04062.html#af6e13c8486db0c32d4b37b0b47a1d347":[3,0,425,19], "a04062.html#af7850990e9e52695607b18e8a54ef3c6":[3,0,425,36], "a04062.html#af832a68078714a16192b0b223553f4ec":[3,0,425,17], "a04062.html#afb472ed816e5f312692fa670f56dceb6":[3,0,425,35], "a04062.html#afed2df0331c84d6f820165d843180676":[3,0,425,50], "a04074.html":[3,0,427], "a04074.html#a0defa61aea3b236c9661185aedd558aa":[3,0,427,0], "a04078.html":[3,0,403], "a04078.html#a93992200ebfddd13e25d0e9122af9b5b":[3,0,403,2], "a04078.html#ab14faedd59339be64f3ba8ddab81c39b":[3,0,403,0], "a04078.html#acf720eb61d4a91e84d949a6f772ea7c5":[3,0,403,1], "a04082.html":[3,0,402], "a04082.html#a2ea5edb90b556766fce2105dcdfe3141":[3,0,402,3], "a04082.html#a441b843c3b024cd12b0ab4115a9fd159":[3,0,402,2], "a04082.html#a76b02dedaede2e6e34653155be6f8c7b":[3,0,402,0], "a04082.html#a973aee4e62bf2e6f6949b13020c984d8":[3,0,402,1], "a04082.html#ab21bd28ad8f7448dcdc327ac13dbe553":[3,0,402,4], "a04086.html":[3,0,356], "a04086.html#a81ce1dd96fbaed7c30c47bc6a1d19d92":[3,0,356,1], "a04086.html#ad64b24b19468c44594a84a71f5515bf8":[3,0,356,0], "a04090.html":[3,0,257], "a04090.html#a2327d1db8e954280ae274a0dc106f99c":[3,0,257,0], "a04090.html#a72bae94de2c63cca7f4e00ca8874b556":[3,0,257,1], "a04094.html":[3,0,254], "a04094.html#a0dd8b01d8c5cc59c77098cdb268ce1ea":[3,0,254,5], "a04094.html#a879b5ee2f46335fe784fd4c266f8a37c":[3,0,254,6], "a04094.html#a88d1300e6657fc7c98af721983018b36":[3,0,254,2], "a04094.html#aa829f657f996e38a441f5ce7fe1e4211":[3,0,254,0], "a04094.html#aa8ec9520f51dbc36a9eb6f71b2446254":[3,0,254,1], "a04094.html#ad19f8e0d6520b447871c5d958b367bf4":[3,0,254,4], "a04094.html#afe5769d3f67549e0938480aab2d2b1cd":[3,0,254,3], "a04098.html":[3,0,256], "a04098.html#a0256081fa31eb38b52b19788ca62e327":[3,0,256,0], "a04098.html#a592229e83546c1b6840e7862b92a0629":[3,0,256,4], "a04098.html#aa040fcd0981abbaead178f882a09e410":[3,0,256,1], "a04098.html#aa644a299b7046916ce731566866df325":[3,0,256,2], "a04098.html#ac4e39261d76ebdd092eeb754fe1e15c3":[3,0,256,3], "a04102.html":[3,0,255], "a04102.html#a0001ba6ce7c4b60fa02f197993823444":[3,0,255,4], "a04102.html#a2337435b9025523b387a526fabb269ff":[3,0,255,3], "a04102.html#a3906ac44f57d9a9d9c1bed4cab32a479":[3,0,255,8], "a04102.html#a450c3b1b225dfa0771edd50732e5d288":[3,0,255,1], "a04102.html#a51675e06d0ccbe1c649000a01445cbec":[3,0,255,6], "a04102.html#a815a36228769f4324d0851ed12fcf9f1":[3,0,255,2], "a04102.html#a96c25b6f847b7f8ebc3817ee73f73236":[3,0,255,5], "a04102.html#ab6a520c3c59a1f1a3f4d1c27bf5d3000":[3,0,255,7], "a04102.html#ae2a2992cb511460edd5e788ed68c86eb":[3,0,255,0], "a04106.html":[3,0,359], "a04106.html#a45ade2ad8d07fe98968e6a6795680f0a":[3,0,359,0], "a04106.html#a88e8ec3116b1ca5e8c0a57a2236f83ed":[3,0,359,2], "a04106.html#ab4a673ae9bd6272302ea460d336bc80e":[3,0,359,1], "a04110.html":[3,0,1,23], "a04110.html#a01a9b767032f48360fb57ba58efe00dd":[3,0,1,23,145], "a04110.html#a03058b2de39758d6455d238d8a059e89":[3,0,1,23,92], "a04110.html#a037af5ac1fbcb6326ab4dd787fba4880":[3,0,1,23,62], "a04110.html#a03c6f57fc6ce80fc38c2229836f52a37":[3,0,1,23,111], "a04110.html#a048eceaa95452969dc6cc5d29d97e5cf":[3,0,1,23,124], "a04110.html#a08295fdeacbf1d536337f542320e86e2":[3,0,1,23,87], "a04110.html#a08873fa3ea379656484c07f606f8a09c":[3,0,1,23,131], "a04110.html#a093af2c004819e86bfff80ad88f10c37":[3,0,1,23,125], "a04110.html#a0a2c418c138725aa9fbd2bc9559d7c84":[3,0,1,23,4], "a04110.html#a0be36efceb5fcf41dfbc032516af2ace":[3,0,1,23,149], "a04110.html#a0c8e4bf5e3032c6468b909b6aca7f416":[3,0,1,23,100], "a04110.html#a0cc90707377d9d37003f3fd6cc78505e":[3,0,1,23,86], "a04110.html#a0d1928e7dac3c17776220d35f08a48ec":[3,0,1,23,113], "a04110.html#a0d252009d9ff3f6997c27b533ea52550":[3,0,1,23,2], "a04110.html#a0e2ae78006c41a808b511d1cc55296a8":[3,0,1,23,26], "a04110.html#a0e35029ac0c77ad18d35f08c27c99d15":[3,0,1,23,65], "a04110.html#a0f934f0b39cb869d2a4973269fb696cf":[3,0,1,23,101], "a04110.html#a10595e84248f68a98f8e73bcdb6ae89a":[3,0,1,23,127], "a04110.html#a132e3e38f2fa27581c318e036778ac67":[3,0,1,23,18], "a04110.html#a15d6951abc586793270de0825bdb7dd7":[3,0,1,23,57], "a04110.html#a1718afe45a09c6631f11ae224e6d5db6":[3,0,1,23,80], "a04110.html#a1be5f58ba2dd177ba8882db479938a00":[3,0,1,23,50], "a04110.html#a1bf53ddfbca6c2ecc567a9e87d46b3f7":[3,0,1,23,14], "a04110.html#a1f21b989c93ff1d297b5bde442fc430c":[3,0,1,23,38], "a04110.html#a218c9e6d6d0b14fa65ec7602d35d3729":[3,0,1,23,79], "a04110.html#a22717c4d299d3a52683ad90114b20200":[3,0,1,23,141], "a04110.html#a2420bb00ab392215cbc8b5f72d9cf81a":[3,0,1,23,102], "a04110.html#a257f6644554cd6a4f9d67330ae80cfe5":[3,0,1,23,10], "a04110.html#a26b1c76382f418bf5a78bad15b23b8ad":[3,0,1,23,146], "a04110.html#a27fe54e49f64e61f40b4e50e8ff4084c":[3,0,1,23,117], "a04110.html#a28ddc270cb5d2613f5f0f24ad53a5a21":[3,0,1,23,55], "a04110.html#a2978b0c84798b68eb8a991bc79eb5dfd":[3,0,1,23,8], "a04110.html#a2b3d7dd5bfe31b752a9ed2a86174f5a2":[3,0,1,23,93], "a04110.html#a2f3faf7d282a1b58b10b3866693a4f08":[3,0,1,23,99], "a04110.html#a2f7694fc293ec920564ff792b7e57b93":[3,0,1,23,59], "a04110.html#a2fc1971dc1e42946245c98a9312326ae":[3,0,1,23,49], "a04110.html#a3205427bd0f3abae31ab6c3092ca0662":[3,0,1,23,21], "a04110.html#a33bc8d687ec0504c697ac0e1ace5567d":[3,0,1,23,133], "a04110.html#a342dfc4f244244bd1bc211ea910e2b12":[3,0,1,23,96], "a04110.html#a350f6cb6e7ce9f53ae468908a91c6148":[3,0,1,23,67], "a04110.html#a3a1062b97626a08de9736ac3a6bc513a":[3,0,1,23,76], "a04110.html#a3abc0b280fe8a88d57a35d2d578ef47a":[3,0,1,23,19], "a04110.html#a3bfadb1d56669868fe7d18e12a7716dc":[3,0,1,23,129], "a04110.html#a3d74369343952e81efa5ac8858d5e9d1":[3,0,1,23,91], "a04110.html#a3d9ace4f4ae0ddf01942ced19410adbe":[3,0,1,23,134], "a04110.html#a3e8b9d04ff249b5fe5dc190f08a43cc0":[3,0,1,23,115], "a04110.html#a3f89a54fbee53fa65e3d2c2947dab449":[3,0,1,23,109], "a04110.html#a406c1644ce61dfb376ae9975f89c54ba":[3,0,1,23,97], "a04110.html#a44e1b8840fb841e621b902f3abdd8522":[3,0,1,23,75], "a04110.html#a471b3e8f03ddc5281c167b37d8ddc5b5":[3,0,1,23,143], "a04110.html#a49b9210610b2eb4c1b2bceb8b7814797":[3,0,1,23,144], "a04110.html#a49c2bec2694a12cb6518001d8193d58d":[3,0,1,23,83], "a04110.html#a4a3fe30721c7f945fb4c5ebfe421639c":[3,0,1,23,1], "a04110.html#a4f60282758b6559dfa53f214b71069d0":[3,0,1,23,74], "a04110.html#a4ffd69a43ee88c26c2df49de2a92f6f4":[3,0,1,23,54], "a04110.html#a515345805094aab6de016c20231791ad":[3,0,1,23,13], "a04110.html#a52c6bf81f09a61859f999707e37c47f0":[3,0,1,23,118], "a04110.html#a54212a417ae117baf3f1613b72ef2951":[3,0,1,23,6], "a04110.html#a57e449d38b255fe82e61d88ded8b0020":[3,0,1,23,94], "a04110.html#a59900939784eac1e2e6ebfec1f82bb58":[3,0,1,23,51], "a04110.html#a59d2ce9a817ab97d37a459ca2459cf8e":[3,0,1,23,130], "a04110.html#a5a3045639a3db979a8d1eb6dc4343e3b":[3,0,1,23,68], "a04110.html#a5ad207ab75e8a69c35c225313268788b":[3,0,1,23,71], "a04110.html#a60807f4acb76d321a870264b42426287":[3,0,1,23,46], "a04110.html#a62597f182a5e23c3b8a030c06e699e99":[3,0,1,23,35], "a04110.html#a64383806f917e682c4a644efdd71d530":[3,0,1,23,140], "a04110.html#a67a98c273b9c1b7cc951fcb20e376bf3":[3,0,1,23,114], "a04110.html#a6e0102d0d21b6151893a199cc84a6e93":[3,0,1,23,98], "a04110.html#a6e36e01c8147d95bbd64c6609e1b8f45":[3,0,1,23,64], "a04110.html#a6ebcfd2968c704f99efd40075ecdb138":[3,0,1,23,121], "a04110.html#a727f2429705dabdd078d6748f0e81c42":[3,0,1,23,135], "a04110.html#a746dbbd1c99e99f3d213077cceedf80e":[3,0,1,23,148], "a04110.html#a74a007a46ac907d2c8f61e9885143465":[3,0,1,23,123], "a04110.html#a74aba3ded458496610487a3225ad9fc8":[3,0,1,23,11], "a04110.html#a7691700e9742ecdc10e0f8ee75682991":[3,0,1,23,104], "a04110.html#a76bc2aed534982a6b67afe8a6653b04f":[3,0,1,23,128], "a04110.html#a76f4e180bcab3a7cd2da75d42b524eba":[3,0,1,23,41], "a04110.html#a786c5f6e2a5cd8aac2ed4dd89af84fea":[3,0,1,23,78], "a04110.html#a7940573dfb85992433c6f51965a9fea5":[3,0,1,23,136], "a04110.html#a7bef23fa815b3c02261800ca82b05911":[3,0,1,23,95], "a04110.html#a7c8cb6fbaef7f126bcbea9266c3a2693":[3,0,1,23,12], "a04110.html#a7d0ccfd06421346d8cda0f1b76fd8516":[3,0,1,23,120], "a04110.html#a81e8a5e5adfc60146ea3eb5b60936dd9":[3,0,1,23,81], "a04110.html#a8373b3d764ce82b5be835abea34ebd32":[3,0,1,23,82], "a04110.html#a84d0021ef7ddbc98196801f9808fa33d":[3,0,1,23,37], "a04110.html#a85fcc9966cddbc38adf1014dd0cd778c":[3,0,1,23,147], "a04110.html#a88f8ff9caac17216207149574db5b63b":[3,0,1,23,108], "a04110.html#a8a68035cfc5ee866f2d39360072ab77c":[3,0,1,23,15], "a04110.html#a8b9a8fd61525abba2fe40733e1a4889c":[3,0,1,23,27], "a04110.html#a8cbc3c255f888cc49c713c0a7408d2ad":[3,0,1,23,56], "a04110.html#a8f49de2f8da7b066bd8ece0641edcca1":[3,0,1,23,17], "a04110.html#a8ffda27cc071fa6c63c406fe9749f276":[3,0,1,23,112], "a04110.html#a9453d913f6925f8313e4a8ce7a280cb8":[3,0,1,23,63], "a04110.html#a9477e67a4f14bf9f88a439ab6cf1a4ab":[3,0,1,23,36], "a04110.html#a96f1213af9f43f2ec0ab9e22f32da3b6":[3,0,1,23,150], "a04110.html#a9723b1f4a341f42ddfc68d2f531c7dd3":[3,0,1,23,126], "a04110.html#a974e5b3b4ee8b184a3af4ba782750dd7":[3,0,1,23,84], "a04110.html#a974fef059529c04a1814a1c994af1a6c":[3,0,1,23,39], "a04110.html#a9eaad1b9042e12ffd8f3f4aa3a72d395":[3,0,1,23,44], "a04110.html#aa08ead4bccd3a3c602f4c28b1c91bbe6":[3,0,1,23,77], "a04110.html#aa220c70c7e0b0f7b0276d421c95feedd":[3,0,1,23,89], "a04110.html#aa92ef2f6a1f0e726d576a59644c3cc63":[3,0,1,23,116], "a04110.html#aacb4b954a74e3845d6e638742516f532":[3,0,1,23,29], "a04110.html#ab2ed08d2587e66a131f7fcd229102566":[3,0,1,23,142], "a04110.html#ab39a42222f621c9a5f1bd1b31db3a930":[3,0,1,23,3], "a04110.html#ab51ed503c5a8490efaf909d7973880ed":[3,0,1,23,5], "a04110.html#ab6e270cecf7e7c62e1319e7889caf716":[3,0,1,23,34], "a04110.html#ab72b2fc763ff7151aafe41f68d759ae3":[3,0,1,23,137], "a04110.html#ab92981e0e78896a6492bd3c5e104cb80":[3,0,1,23,30], "a04110.html#ab9c25bf0ebc01c57728e19b2bbc980ef":[3,0,1,23,119], "a04110.html#aba896a485da240daf96d8f0896b2c11d":[3,0,1,23,9], "a04110.html#abdd8831d44ce5ea36f7bbee1ed9c4e8a":[3,0,1,23,106], "a04110.html#ac0de90c99552cdc286f934d344790085":[3,0,1,23,16], "a04110.html#ac4c2dfe9aa3c463964fdc61faec56a67":[3,0,1,23,0], "a04110.html#ac7e166d03061648ec8e7fc03adea3f37":[3,0,1,23,40], "a04110.html#acab8de2f560b04b48191f60099e4244b":[3,0,1,23,105], "a04110.html#aceda1d382b8685f07a16be25fb16e8ef":[3,0,1,23,61], "a04110.html#acf0658a5a3cf8ebc7d29f2b9213a8884":[3,0,1,23,45], "a04110.html#acf596b4f16672fbcafa0407f9700c251":[3,0,1,23,48], "a04110.html#ad0137683f38d768798a0b56fbee94a15":[3,0,1,23,42], "a04110.html#ad47099cfac2701d8fe3a24dd12eab0e1":[3,0,1,23,138] };
stweil/tesseract-ocr.github.io
4.0.0-beta.1/navtreeindex40.js
JavaScript
apache-2.0
15,280
### 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. param( [Parameter(Mandatory=$true,Position = 0)] [string] $Command="", [string] $D="", [switch] $Secure, [Parameter(ValueFromRemainingArguments = $true)][string[]]$args) # FUNCTIONS Function PrintUsage { param () Write-Output "Usage : oozie-setup.ps1 COMMAND [OPTIONS]" Write-Output " prepare-war [-d directory] [-secure] (-d identifies an alternative directory for processing jars" Write-Output " -secure will configure the war file to use HTTPS (SSL))" Write-Output " sharelib create -fs FS_URI [-locallib SHARED_LIBRARY] [-concurrency CONCURRENCY]" Write-Output " (create sharelib for oozie," Write-Output " FS_URI is the fs.default.name" Write-Output " for hdfs uri; SHARED_LIBRARY, path to the" Write-Output " Oozie sharelib to install, it can be a tarball" Write-Output " or an expanded version of it. If ommited," Write-Output " the Oozie sharelib tarball from the Oozie" Write-Output " installation directory will be used." Write-Output " CONCURRENCY is a number of threads to be used" Write-Output " for copy operations." Write-Output " By default 1 thread will be used)" Write-Output " (action failes if sharelib is already installed" Write-Output " in HDFS)" Write-Output " sharelib upgrade -fs FS_URI [-locallib SHARED_LIBRARY] ([deprecated]" Write-Output " [use create command to create new version]" Write-Output " upgrade existing sharelib, fails if there" Write-Output " is no existing sharelib installed in HDFS)" Write-Output " db create|upgrade|postupgrade -run [-sqlfile <FILE>] (create, upgrade or postupgrade oozie db with an" Write-Output " optional sql File)" Write-Output " EXTJS can be downloaded from http://www.extjs.com/learn/Ext_Version_Archives" } function Expand-ZIPFile($file, $destination){ $shell = new-object -com shell.application $zip = $shell.NameSpace($file) foreach($item in $zip.items()){ $shell.Namespace($destination).copyhere($item) } } # MAIN() # The script will terminate if any steps fail $ErrorActionPreference = "Stop" # Constants $EXT_SUBDIR = "ext-2.2" $OOZIE_HOME = (Split-Path $MyInvocation.MyCommand.Path) + "\.." $OOZIE_HOME = Resolve-Path $OOZIE_HOME $CATALINA_BASE = "" if ($env:CATALINA_BASE){ $CATALINA_BASE = "$env:CATALINA_BASE" }else{ $CATALINA_BASE = "$OOZIE_HOME\oozie-server" } # Finds JAR.EXE and Java $JAR_EXE="" $JAVA_BIN="" if ($env:JAVA_HOME) { $JAR_EXE = "$env:JAVA_HOME\bin\jar.exe" $JAVA_BIN = "$env:JAVA_HOME\bin\java.exe" } else { Write-Output "WARN: JAVA_HOME not defined. oozie-setup.ps1 will relay on the PATH environment variable to use JAR.exe" $JAR_EXE = "jar.exe" $JAVA_BIN = "java.exe" } if (($Command -eq "sharelib") -Or ($Command -eq "db") -Or ($Command -eq "import") -Or ($Command -eq "export")) { $OOZIE_OPTS="-Doozie.home.dir=$OOZIE_HOME"; $OOZIE_OPTS="$OOZIE_OPTS -Doozie.config.dir=$OOZIE_HOME\conf"; $OOZIE_OPTS="$OOZIE_OPTS -Doozie.log.dir=$OOZIE_HOME\log"; $OOZIE_OPTS="$OOZIE_OPTS -Doozie.data.dir=$OOZIE_HOME\data"; $OOZIE_OPTS="$OOZIE_OPTS -Dderby.stream.error.file=$OOZIE_HOME\log\derby.log" $OOZIECPPATH="" $OOZIECPPATH="$OOZIE_HOME\libtools\*;$OOZIE_HOME\lib\*;$OOZIE_HOME\..\extra_libs\*" $COMMAND_OPTS=[string]$args if ($Command -eq "sharelib") { Start-Process $JAVA_BIN -ArgumentList "$OOZIE_OPTS -cp $OOZIECPPATH org.apache.oozie.tools.OozieSharelibCLI $COMMAND_OPTS" -Wait -NoNewWindow } elseif ($Command -eq "db") { Start-Process $JAVA_BIN -ArgumentList "$OOZIE_OPTS -cp $OOZIECPPATH org.apache.oozie.tools.OozieDBCLI $COMMAND_OPTS" -Wait -NoNewWindow } elseif ($Command -eq "export"){ Start-Process $JAVA_BIN -ArgumentList "$OOZIE_OPTS -cp $OOZIECPPATH org.apache.oozie.tools.OozieDBExportCLI $COMMAND_OPTS" -Wait -NoNewWindow } elseif ($Command -eq "import"){ Start-Process $JAVA_BIN -ArgumentList "$OOZIE_OPTS -cp $OOZIECPPATH org.apache.oozie.tools.OozieDBImportCLI $COMMAND_OPTS" -Wait -NoNewWindow } exit 0 }elseif ($Command -eq "prepare-war"){ $InputWar = "$OOZIE_HOME\oozie.war" $OutputWar = "$OOZIE_HOME\oozie-server\webapps\oozie.war" $SecureConfigsDir="$CATALINA_BASE\conf\ssl" $ExtraLibs = Resolve-Path "$OOZIE_HOME\..\extra_libs" $EXTJS = "$ExtraLibs\ext-2.2.zip" # Validates the input\output wars if (!(Test-Path $InputWar)){ PrintUsage throw "Path '$InputWar' doesn't exist" } if (!$InputWar.ToLower().EndsWith(".war")){ PrintUsage throw "Invalid input war file '$InputWar'" } if (!$OutputWar.ToLower().EndsWith(".war")){ PrintUsage throw "Invalid input war file '$OutputWar'" } if ($OutputWar -ieq $InputWar){ PrintUsage throw "Invalid output\input war file. Both parameters cannot be the same file" } # Deletes previous output wars. if (Test-Path $OutputWar){ Write-Output "Deleting existing output .war '$OutputWar'" Remove-Item -Force -Path $OutputWar } # Selects\Creates the temp directory $OOZIE_TEMP = "$OOZIE_HOME\temp" $OOZIE_WEB_INF_LIB = "$OOZIE_TEMP\WEB-INF\lib" Write-Output "Creating OOZIE_TEMP directory '$OOZIE_TEMP'" if (Test-Path "$OOZIE_TEMP") { Remove-Item "$OOZIE_TEMP" -Force -Recurse } $x = New-Item "$OOZIE_TEMP" -type directory # Extract the InputWar pushd $OOZIE_TEMP cmd /c $JAR_EXE xvf $InputWar if ($LASTEXITCODE -ne 0) { throw "Unable to execute 'jar xvf'. Error ($LASTEXITCODE)" } popd # Copy EXT_JS files if ((Test-Path $EXTJS)) { $EXTJS_HOME = "$ExtraLibs\ext-2.2" if (Test-Path "$EXTJS_HOME") { Remove-Item "$EXTJS_HOME" -Force -Recurse } $x = New-Item "$EXTJS_HOME" -type directory Expand-ZIPFile -File $EXTJS -Destination $EXTJS_HOME cp -r "$EXTJS_HOME\ext-2.2" "$OOZIE_TEMP" }else{ Write-Output "INFO: Oozie webconsole disabled, ExtJS library not specified" } # Copy additional Jars if ($D -ne "") { $ExtraLibs = $D } Write-Output " Adding JarFiles: $ExtraLibs\*.jar" cp -r $ExtraLibs\*.jar $OOZIE_WEB_INF_LIB if ($Secure) { #Use the SSL version of server.xml in oozie-server if (Test-Path $SecureConfigsDir\ssl-server.xml){ cp $SecureConfigsDir\ssl-server.xml $CATALINA_BASE\conf\server.xml } #Inject the SSL version of web.xml in oozie war if (Test-Path $SecureConfigsDir\ssl-web.xml){ cp $SecureConfigsDir\ssl-web.xml $OOZIE_TEMP\WEB-INF\web.xml } Write-Output "INFO: Using secure server.xml and secure web.xml" }else{ #Use the regular version of server.xml in oozie-server if (Test-Path $SecureConfigsDir\server.xml){ cp $SecureConfigsDir\server.xml $CATALINA_BASE\conf\server.xml } #No need to restore web.xml because its already in the original WAR file } Write-Output "Recreating the new war file '$OutputWar'..." cmd /c $JAR_EXE cvf $OutputWar -C $OOZIE_TEMP '.' if ($LASTEXITCODE -ne 0) { throw "Unable to execute 'jar uvf'. Error ($LASTEXITCODE)" } Write-Output "Done! $counter files added" } else { PrintUsage exit -1 }
cbaenziger/oozie
distro/src/main/bin/oozie-setup.ps1
PowerShell
apache-2.0
9,356
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="de"> <head> <!-- Generated by javadoc (1.8.0_101) on Mon Aug 22 00:07:21 CEST 2016 --> <title>Uses of Class de.dhbw.wi13c.jguicreator.elemente.PieChartPanel</title> <meta name="date" content="2016-08-22"> <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 de.dhbw.wi13c.jguicreator.elemente.PieChartPanel"; } } 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="../../../../../../de/dhbw/wi13c/jguicreator/elemente/PieChartPanel.html" title="class in de.dhbw.wi13c.jguicreator.elemente">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?de/dhbw/wi13c/jguicreator/elemente/class-use/PieChartPanel.html" target="_top">Frames</a></li> <li><a href="PieChartPanel.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 de.dhbw.wi13c.jguicreator.elemente.PieChartPanel" class="title">Uses of Class<br>de.dhbw.wi13c.jguicreator.elemente.PieChartPanel</h2> </div> <div class="classUseContainer">No usage of de.dhbw.wi13c.jguicreator.elemente.PieChartPanel</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="../../../../../../de/dhbw/wi13c/jguicreator/elemente/PieChartPanel.html" title="class in de.dhbw.wi13c.jguicreator.elemente">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?de/dhbw/wi13c/jguicreator/elemente/class-use/PieChartPanel.html" target="_top">Frames</a></li> <li><a href="PieChartPanel.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 ======= --> </body> </html>
WI13C/Jgui-creator
code/framework/doc/de/dhbw/wi13c/jguicreator/elemente/class-use/PieChartPanel.html
HTML
apache-2.0
4,558
/************************************************************************************ * Copyright (c) 2016 All Rights Reserved. * CLR版本:4.0.30319.34209 * 机器名称:JIAN * 命名空间:JCE.Core.Dependency * 文件名:ISingletonDependency * 版本号:v1.0.0.0 * 唯一标识:e28c276b-85b2-457b-a297-9494fb387ca1 * 当前的用户域:jian * 创建人:简玄冰 * 电子邮箱:jianxuanhuo1@126.com * 创建时间:2016/7/13 星期三 15:32:28 * 描述: * * ===================================================================== * 修改标记: * 修改时间:2016/7/13 星期三 15:32:28 * 修改人:简玄冰 * 版本号:v1.0.0.0 * 描述: * /************************************************************************************/ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace JCE.Core.Dependency { /// <summary> /// 依赖注入——单例模式,实现此接口的类型将被注册为<see cref="LifetimeStyle.Singleton"/>模式 /// </summary> public interface ISingletonDependency:IDependency { } }
jianxuanbing/JCE
JCE.Core/Dependency/ISingletonDependency.cs
C#
apache-2.0
1,165
package cli import ( "errors" "fmt" "io" "os" "reflect" "strings" flag "github.com/get3w/get3w/pkg/mflag" ) // Cli represents a command line interface. type Cli struct { Stderr io.Writer handlers []Handler Usage func() } // Handler holds the different commands Cli will call // It should have methods with names starting with `Cmd` like: // func (h myHandler) CmdFoo(args ...string) error type Handler interface{} // Initializer can be optionally implemented by a Handler to // initialize before each call to one of its commands. type Initializer interface { Initialize() error } // New instantiates a ready-to-use Cli. func New(handlers ...Handler) *Cli { // make the generic Cli object the first cli handler // in order to handle `get3w help` appropriately cli := new(Cli) cli.handlers = append([]Handler{cli}, handlers...) return cli } // initErr is an error returned upon initialization of a handler implementing Initializer. type initErr struct{ error } func (err initErr) Error() string { return err.Error() } func (cli *Cli) command(args ...string) (func(...string) error, error) { for _, c := range cli.handlers { if c == nil { continue } camelArgs := make([]string, len(args)) for i, s := range args { if len(s) == 0 { return nil, errors.New("empty command") } camelArgs[i] = strings.ToUpper(s[:1]) + strings.ToLower(s[1:]) } methodName := "Cmd" + strings.Join(camelArgs, "") method := reflect.ValueOf(c).MethodByName(methodName) if method.IsValid() { if c, ok := c.(Initializer); ok { if err := c.Initialize(); err != nil { return nil, initErr{err} } } return method.Interface().(func(...string) error), nil } } return nil, errors.New("command not found") } // Run executes the specified command. func (cli *Cli) Run(args ...string) error { if len(args) > 1 { command, err := cli.command(args[:2]...) switch err := err.(type) { case nil: return command(args[2:]...) case initErr: return err.error } } if len(args) > 0 { command, err := cli.command(args[0]) switch err := err.(type) { case nil: return command(args[1:]...) case initErr: return err.error } cli.noSuchCommand(args[0]) } return cli.CmdHelp() } func (cli *Cli) noSuchCommand(command string) { if cli.Stderr == nil { cli.Stderr = os.Stderr } fmt.Fprintf(cli.Stderr, "get3w: '%s' is not a get3w command.\nSee 'get3w --help'.\n", command) os.Exit(1) } // CmdHelp displays information on a Get3W command. // // If more than one command is specified, information is only shown for the first command. // // Usage: get3w help COMMAND or get3w COMMAND --help func (cli *Cli) CmdHelp(args ...string) error { if len(args) > 1 { command, err := cli.command(args[:2]...) switch err := err.(type) { case nil: command("--help") return nil case initErr: return err.error } } if len(args) > 0 { command, err := cli.command(args[0]) switch err := err.(type) { case nil: command("--help") return nil case initErr: return err.error } cli.noSuchCommand(args[0]) } if cli.Usage == nil { flag.Usage() } else { cli.Usage() } return nil } // Subcmd is a subcommand of the main "get3w" command. // A subcommand represents an action that can be performed // from the Get3W command line client. // // To see all available subcommands, run "get3w --help". func Subcmd(name string, synopses []string, description string, exitOnError bool) *flag.FlagSet { var errorHandling flag.ErrorHandling if exitOnError { errorHandling = flag.ExitOnError } else { errorHandling = flag.ContinueOnError } flags := flag.NewFlagSet(name, errorHandling) flags.Usage = func() { flags.ShortUsage() flags.PrintDefaults() } flags.ShortUsage = func() { options := "" if flags.FlagCountUndeprecated() > 0 { options = " [OPTIONS]" } if len(synopses) == 0 { synopses = []string{""} } // Allow for multiple command usage synopses. for i, synopsis := range synopses { lead := "\t" if i == 0 { // First line needs the word 'Usage'. lead = "Usage:\t" } if synopsis != "" { synopsis = " " + synopsis } fmt.Fprintf(flags.Out(), "\n%sget3w %s%s%s", lead, name, options, synopsis) } fmt.Fprintf(flags.Out(), "\n\n%s\n", description) } return flags } // An StatusError reports an unsuccessful exit by a command. type StatusError struct { Status string StatusCode int } func (e StatusError) Error() string { return fmt.Sprintf("Status: %s, Code: %d", e.Status, e.StatusCode) }
get3w/get3w
cli/cli.go
GO
apache-2.0
4,566
# Stigmidium grex Alstrup & Olech SPECIES #### Status ACCEPTED #### According to Index Fungorum #### Published in Fragm. flor. geobot. (Kraków) 41(2): 749 (1996) #### Original name Stigmidium grex Alstrup & Olech ### Remarks null
mdoering/backbone
life/Fungi/Ascomycota/Dothideomycetes/Capnodiales/Mycosphaerellaceae/Stigmidium/Stigmidium grex/README.md
Markdown
apache-2.0
235
# Cucubalus angustifolius Mill. SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Caryophyllales/Caryophyllaceae/Cucubalus/Cucubalus angustifolius/README.md
Markdown
apache-2.0
179
# Santalodes diversifolium Kuntze SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Oxalidales/Connaraceae/Santalodes/Santalodes diversifolium/README.md
Markdown
apache-2.0
181
# Anomospermum nitidum Miers SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Ranunculales/Menispermaceae/Anomospermum/Anomospermum nitidum/README.md
Markdown
apache-2.0
176
# Goodenia arthrotricha F.Muell. ex Benth. SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Goodeniaceae/Goodenia/Goodenia arthrotricha/README.md
Markdown
apache-2.0
190
# Curtia gentianoides Cham. & Schltdl. SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Gentianales/Gentianaceae/Curtia/Curtia gentianoides/README.md
Markdown
apache-2.0
186
# Heteromma simplicifolium J.M.Wood & M.S.Evans SPECIES #### Status DOUBTFUL #### 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/Heteromma/Heteromma simplicifolium/README.md
Markdown
apache-2.0
203
# Tuberolabium rumphii (J.J.Sm.) J.J.Wood SPECIES #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name Saccolabium rumphii J.J.Sm. ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Tuberolabium/Tuberolabium rumphii/README.md
Markdown
apache-2.0
220
# Orobanche galiophya St Lager SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Orobanchaceae/Orobanche/Orobanche galiophya/README.md
Markdown
apache-2.0
178
# Amsinckia kennedyi Suksd. SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Boraginales/Boraginaceae/Amsinckia/Amsinckia kennedyi/README.md
Markdown
apache-2.0
175
# Brassaiopsis karmalaica Philipson 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/Apiales/Araliaceae/Brassaiopsis/Brassaiopsis shweliensis/ Syn. Brassaiopsis karmalaica/README.md
Markdown
apache-2.0
190
# Desmos dubius (Craib) Craib 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/Magnoliopsida/Magnoliales/Annonaceae/Desmos/Desmos dubius/README.md
Markdown
apache-2.0
185
# Blaeria equisetifolia G.Don SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Ericales/Ericaceae/Blaeria/Blaeria equisetifolia/README.md
Markdown
apache-2.0
177
# Hormopetalum werneri Lauterb. SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Sapindales/Rutaceae/Hormopetalum/Hormopetalum werneri/README.md
Markdown
apache-2.0
179
# Jacobaea conzyae (Griess.) Merino 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/Inula conyza/ Syn. Jacobaea conzyae/README.md
Markdown
apache-2.0
190
# Rhinanthus pindicus Soó SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Orobanchaceae/Rhinanthus/Rhinanthus pindicus/README.md
Markdown
apache-2.0
174
# Danzleria axillaris Bert. ex A.DC. SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Ericales/Ebenaceae/Danzleria/Danzleria axillaris/README.md
Markdown
apache-2.0
184
# Roussoella chilensis (Speg.) Y.M. Ju, J.D. Rogers & Huhndorf SPECIES #### Status ACCEPTED #### According to Index Fungorum #### Published in Mycotaxon 58: 445 (1996) #### Original name Valsaria chilensis Speg. ### Remarks null
mdoering/backbone
life/Fungi/Ascomycota/Dothideomycetes/Pleosporales/Didymosphaeriaceae/Roussoella/Roussoella chilensis/README.md
Markdown
apache-2.0
233
# Misanteca pittieri Mez SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Laurales/Lauraceae/Misanteca/Misanteca pittieri/README.md
Markdown
apache-2.0
172
# Ophiostoma tenellum (R.W. Davidson) M. Villarreal, 2005 SPECIES #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in Mycotaxon 92: 263 (2005) #### Original name Ceratocystis tenella R.W. Davidson, 1959 ### Remarks null
mdoering/backbone
life/Fungi/Ascomycota/Sordariomycetes/Ophiostomatales/Ophiostomataceae/Ophiostoma/Ophiostoma tenellum/README.md
Markdown
apache-2.0
269
# Copyright 2015, 2017 IBM Corp. # # 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 oslo_log import log as logging from pypowervm import exceptions as pvm_exc from pypowervm.tasks import scsi_mapper as pvm_smap from taskflow import task from taskflow.types import failure as task_fail from nova import exception from nova.virt.powervm import media from nova.virt.powervm import mgmt LOG = logging.getLogger(__name__) class CreateDiskForImg(task.Task): """The Task to create the disk from an image in the storage.""" def __init__(self, disk_dvr, context, instance, image_meta): """Create the Task. Provides the 'disk_dev_info' for other tasks. Comes from the disk_dvr create_disk_from_image method. :param disk_dvr: The storage driver. :param context: The context passed into the driver method. :param instance: The nova instance. :param nova.objects.ImageMeta image_meta: The metadata of the image of the instance. """ super(CreateDiskForImg, self).__init__( name='create_disk_from_img', provides='disk_dev_info') self.disk_dvr = disk_dvr self.instance = instance self.context = context self.image_meta = image_meta def execute(self): return self.disk_dvr.create_disk_from_image( self.context, self.instance, self.image_meta) def revert(self, result, flow_failures): # If there is no result, or its a direct failure, then there isn't # anything to delete. if result is None or isinstance(result, task_fail.Failure): return # Run the delete. The result is a single disk. Wrap into list # as the method works with plural disks. try: self.disk_dvr.delete_disks([result]) except pvm_exc.Error: # Don't allow revert exceptions to interrupt the revert flow. LOG.exception("Disk deletion failed during revert. Ignoring.", instance=self.instance) class AttachDisk(task.Task): """The task to attach the disk to the instance.""" def __init__(self, disk_dvr, instance, stg_ftsk): """Create the Task for the attach disk to instance method. Requires disk info through requirement of disk_dev_info (provided by crt_disk_from_img) :param disk_dvr: The disk driver. :param instance: The nova instance. :param stg_ftsk: FeedTask to defer storage connectivity operations. """ super(AttachDisk, self).__init__( name='attach_disk', requires=['disk_dev_info']) self.disk_dvr = disk_dvr self.instance = instance self.stg_ftsk = stg_ftsk def execute(self, disk_dev_info): self.disk_dvr.attach_disk(self.instance, disk_dev_info, self.stg_ftsk) def revert(self, disk_dev_info, result, flow_failures): try: self.disk_dvr.detach_disk(self.instance) except pvm_exc.Error: # Don't allow revert exceptions to interrupt the revert flow. LOG.exception("Disk detach failed during revert. Ignoring.", instance=self.instance) class DetachDisk(task.Task): """The task to detach the disk storage from the instance.""" def __init__(self, disk_dvr, instance): """Creates the Task to detach the storage adapters. Provides the stor_adpt_mappings. A list of pypowervm VSCSIMappings or VFCMappings (depending on the storage adapter). :param disk_dvr: The DiskAdapter for the VM. :param instance: The nova instance. """ super(DetachDisk, self).__init__( name='detach_disk', provides='stor_adpt_mappings') self.instance = instance self.disk_dvr = disk_dvr def execute(self): return self.disk_dvr.detach_disk(self.instance) class DeleteDisk(task.Task): """The task to delete the backing storage.""" def __init__(self, disk_dvr): """Creates the Task to delete the disk storage from the system. Requires the stor_adpt_mappings. :param disk_dvr: The DiskAdapter for the VM. """ super(DeleteDisk, self).__init__( name='delete_disk', requires=['stor_adpt_mappings']) self.disk_dvr = disk_dvr def execute(self, stor_adpt_mappings): self.disk_dvr.delete_disks(stor_adpt_mappings) class CreateAndConnectCfgDrive(task.Task): """The task to create the configuration drive.""" def __init__(self, adapter, instance, injected_files, network_info, stg_ftsk, admin_pass=None): """Create the Task that creates and connects the config drive. Requires the 'mgmt_cna' :param adapter: The adapter for the pypowervm API :param instance: The nova instance :param injected_files: A list of file paths that will be injected into the ISO. :param network_info: The network_info from the nova spawn method. :param stg_ftsk: FeedTask to defer storage connectivity operations. :param admin_pass (Optional, Default None): Password to inject for the VM. """ super(CreateAndConnectCfgDrive, self).__init__( name='cfg_drive', requires=['mgmt_cna']) self.adapter = adapter self.instance = instance self.injected_files = injected_files self.network_info = network_info self.stg_ftsk = stg_ftsk self.ad_pass = admin_pass self.mb = None def execute(self, mgmt_cna): self.mb = media.ConfigDrivePowerVM(self.adapter) self.mb.create_cfg_drv_vopt(self.instance, self.injected_files, self.network_info, self.stg_ftsk, admin_pass=self.ad_pass, mgmt_cna=mgmt_cna) def revert(self, mgmt_cna, result, flow_failures): # No media builder, nothing to do if self.mb is None: return # Delete the virtual optical media. We don't care if it fails try: self.mb.dlt_vopt(self.instance, self.stg_ftsk) except pvm_exc.Error: LOG.exception('VOpt removal (as part of reversion) failed.', instance=self.instance) class DeleteVOpt(task.Task): """The task to delete the virtual optical.""" def __init__(self, adapter, instance, stg_ftsk=None): """Creates the Task to delete the instance's virtual optical media. :param adapter: The adapter for the pypowervm API :param instance: The nova instance. :param stg_ftsk: FeedTask to defer storage connectivity operations. """ super(DeleteVOpt, self).__init__(name='vopt_delete') self.adapter = adapter self.instance = instance self.stg_ftsk = stg_ftsk def execute(self): media_builder = media.ConfigDrivePowerVM(self.adapter) media_builder.dlt_vopt(self.instance, stg_ftsk=self.stg_ftsk) class InstanceDiskToMgmt(task.Task): """The task to connect an instance's disk to the management partition." This task will connect the instance's disk to the management partition and discover it. We do these two pieces together because their reversion happens in the same order. """ def __init__(self, disk_dvr, instance): """Create the Task for connecting boot disk to mgmt partition. Provides: stg_elem: The storage element wrapper (pypowervm LU, PV, etc.) that was connected. vios_wrap: The Virtual I/O Server wrapper from which the storage element was mapped. disk_path: The local path to the mapped-and-discovered device, e.g. '/dev/sde'. :param disk_dvr: The disk driver. :param instance: The nova instance whose boot disk is to be connected. """ super(InstanceDiskToMgmt, self).__init__( name='instance_disk_to_mgmt', provides=['stg_elem', 'vios_wrap', 'disk_path']) self.disk_dvr = disk_dvr self.instance = instance self.stg_elem = None self.vios_wrap = None self.disk_path = None def execute(self): """Map the instance's boot disk and discover it.""" # Search for boot disk on the NovaLink partition. if self.disk_dvr.mp_uuid in self.disk_dvr._vios_uuids: dev_name = self.disk_dvr.get_bootdisk_path( self.instance, self.disk_dvr.mp_uuid) if dev_name is not None: return None, None, dev_name self.stg_elem, self.vios_wrap = ( self.disk_dvr.connect_instance_disk_to_mgmt(self.instance)) new_maps = pvm_smap.find_maps( self.vios_wrap.scsi_mappings, client_lpar_id=self.disk_dvr.mp_uuid, stg_elem=self.stg_elem) if not new_maps: raise exception.NewMgmtMappingNotFoundException( stg_name=self.stg_elem.name, vios_name=self.vios_wrap.name) # new_maps should be length 1, but even if it's not - i.e. we somehow # matched more than one mapping of the same dev to the management # partition from the same VIOS - it is safe to use the first one. mapping = new_maps[0] # Scan the SCSI bus, discover the disk, find its canonical path. LOG.info("Discovering device and path for mapping of %(dev_name)s " "on the management partition.", {'dev_name': self.stg_elem.name}, instance=self.instance) self.disk_path = mgmt.discover_vscsi_disk(mapping) return self.stg_elem, self.vios_wrap, self.disk_path def revert(self, result, flow_failures): """Unmap the disk and then remove it from the management partition. We use this order to avoid rediscovering the device in case some other thread scans the SCSI bus between when we remove and when we unmap. """ if self.vios_wrap is None or self.stg_elem is None: # We never even got connected - nothing to do. return LOG.warning("Unmapping boot disk %(disk_name)s from the management " "partition via Virtual I/O Server %(vioname)s.", {'disk_name': self.stg_elem.name, 'vioname': self.vios_wrap.name}, instance=self.instance) self.disk_dvr.disconnect_disk_from_mgmt(self.vios_wrap.uuid, self.stg_elem.name) if self.disk_path is None: # We did not discover the disk - nothing else to do. return LOG.warning("Removing disk %(dpath)s from the management partition.", {'dpath': self.disk_path}, instance=self.instance) try: mgmt.remove_block_dev(self.disk_path) except pvm_exc.Error: # Don't allow revert exceptions to interrupt the revert flow. LOG.exception("Remove disk failed during revert. Ignoring.", instance=self.instance) class RemoveInstanceDiskFromMgmt(task.Task): """Unmap and remove an instance's boot disk from the mgmt partition.""" def __init__(self, disk_dvr, instance): """Create task to unmap and remove an instance's boot disk from mgmt. Requires (from InstanceDiskToMgmt): stg_elem: The storage element wrapper (pypowervm LU, PV, etc.) that was connected. vios_wrap: The Virtual I/O Server wrapper. (pypowervm.wrappers.virtual_io_server.VIOS) from which the storage element was mapped. disk_path: The local path to the mapped-and-discovered device, e.g. '/dev/sde'. :param disk_dvr: The disk driver. :param instance: The nova instance whose boot disk is to be connected. """ self.disk_dvr = disk_dvr self.instance = instance super(RemoveInstanceDiskFromMgmt, self).__init__( name='remove_inst_disk_from_mgmt', requires=['stg_elem', 'vios_wrap', 'disk_path']) def execute(self, stg_elem, vios_wrap, disk_path): """Unmap and remove an instance's boot disk from the mgmt partition. Input parameters ('requires') provided by InstanceDiskToMgmt task. :param stg_elem: The storage element wrapper (pypowervm LU, PV, etc.) to be disconnected. :param vios_wrap: The Virtual I/O Server wrapper from which the mapping is to be removed. :param disk_path: The local path to the disk device to be removed, e.g. '/dev/sde' """ # stg_elem is None if boot disk was not mapped to management partition. if stg_elem is None: return LOG.info("Unmapping boot disk %(disk_name)s from the management " "partition via Virtual I/O Server %(vios_name)s.", {'disk_name': stg_elem.name, 'vios_name': vios_wrap.name}, instance=self.instance) self.disk_dvr.disconnect_disk_from_mgmt(vios_wrap.uuid, stg_elem.name) LOG.info("Removing disk %(disk_path)s from the management partition.", {'disk_path': disk_path}, instance=self.instance) mgmt.remove_block_dev(disk_path)
phenoxim/nova
nova/virt/powervm/tasks/storage.py
Python
apache-2.0
14,010
package net.voldrich.smscsim.server; public class FormatUtils { public static String formatAsHex(long msgId) { String msgIdStr = String.format("%07x", msgId); return msgIdStr.toLowerCase(); // just to be sure :) } public static String formatAsHexUppercase(long msgId) { return formatAsHex(msgId).toUpperCase(); } public static String formatAsDec(long msgId) { return String.format("%d", msgId); } }
MavoCz/smscsim
src/main/java/net/voldrich/smscsim/server/FormatUtils.java
Java
apache-2.0
422
var BSplineBuilder = (function () { var self = {}; self.build = function (order, controlPoints, knots) { return new BSpline(order, controlPoints, knots); }; self.interpolate = function (dataPoints, order, fittingStrategy) { var parameters = fittingStrategy.getParameters(dataPoints, 0.5,order); var knots = fittingStrategy.getKnots(order, dataPoints.length - 1, parameters); return Interpolator.interpolate(dataPoints, order, parameters, knots); }; self.approximate = function (dataPoints, order, numberOfControlPoints, fittingStrategy) { var h = numberOfControlPoints - 1; var parameters = fittingStrategy.getParameters(dataPoints, 0.5,order); var knots = fittingStrategy.getKnots(order, h, parameters); return Approximator.approximate(dataPoints, order, h, parameters, knots); }; self.iterativeAproximate = function (dataPoints, order, numberOfControlPoints, fittingStrategy, iterativeApproximationStrategy) { return IterativeApproximator.approximate(dataPoints, order, numberOfControlPoints - 1, fittingStrategy, iterativeApproximationStrategy); }; var Interpolator = (function (params) { var self = {}; self.interpolate = function (dataPoints, p, parameters, knots) { var n = dataPoints.length - 1; var N = computeN(n, p, parameters, knots); var dX = [], dY = []; for (var i = 0; i <= n; i++) { dX.push(dataPoints[i].x); dY.push(dataPoints[i].y); } var pX = math.lusolve(N, dX); var pY = math.lusolve(N, dY); var controlPoints = []; for (var j = 0; j <= n; j++) { controlPoints.push(new Point(pX[j][0], pY[j][0])); } var bspline = BSplineBuilder.build(p, controlPoints, knots); return { bspline: bspline, params: parameters }; } function computeN(n, p, parameters, knots) { var N = []; var basisFunction = new BasisFunction(knots); for (var i = 0; i <= n; i++) { N[i] = []; for (var j = 0; j <= n; j++) { N[i].push(basisFunction.compute(parameters[i], j, p)); } } return N; } return self; })(); var Approximator = (function () { var self = {}; self.approximate = function (dataPoints, p, h, parameters, knots) { var n = dataPoints.length - 1; var Q = computeQ(dataPoints, n, p, h, parameters, knots); var N = computeN(n, p, h, parameters, knots); var NT = math.transpose(N); var NTN = math.multiply(NT, N); var qX = []; var qY = []; for (var i = 0; i < h - 1; i++) { qX.push(Q[i].x); qY.push(Q[i].y); } var pX = null; var pY = null; try { pX = math.lusolve(NTN, qX); pY = math.lusolve(NTN, qY); } catch (e) { return { cp: [], knots: [], params: [], error: "singular matrix", order: p }; } var controlPoints = [dataPoints[0]]; for (var j = 0; j < h - 1; j++) { controlPoints.push(new Point(pX[j][0], pY[j][0])); } controlPoints.push(dataPoints[n]); var bspline = BSplineBuilder.build(p, controlPoints, knots); var error = computeErrors(bspline, dataPoints, parameters); return { bspline: bspline, params: parameters, error: error }; } function computeErrors(bspline, dataPoints, parameters) { var result = { distances: [], minDistance: 10000, maxDistance: 0, totalDistance: 0, totalLeastSquareDistance: 0 }; for (var i = 1; i < parameters.length - 1; i++) { var curvePoint = bspline.deboorEvaluation(parameters[i]); var distance = math.distance({ pointOneX: curvePoint.x, pointOneY: curvePoint.y }, { pointTwoX: dataPoints[i].x, pointTwoY: dataPoints[i].y }); result.distances.push(distance); if (distance < result.minDistance) result.minDistance = distance; if (distance > result.maxDistance) result.maxDistance = distance; result.totalDistance += distance; result.totalLeastSquareDistance += math.square(distance); } return result; } function computeQ(dataPoints, n, p, h, parameters, knots) { var Q = []; var basisFunction = new BasisFunction(knots); for (var i = 1; i < h; i++) { var sumX = 0; var sumY = 0; for (var k = 1; k < n; k++) { var basis = basisFunction.compute(parameters[k], i, p); var qK = computeqk(k, dataPoints, n, p, h, parameters, knots); sumX += basis * qK.x; sumY += basis * qK.y; } Q.push(new Point(sumX, sumY)); } return Q; } function computeqk(k, dataPoints, n, p, h, parameters, knots) { var basisFunction = new BasisFunction(knots); var basisZero = basisFunction.compute(parameters[k], 0, p); var basisH = basisFunction.compute(parameters[k], h, p); var x = dataPoints[k].x - basisZero * dataPoints[0].x - basisH * dataPoints[n].x; var y = dataPoints[k].y - basisZero * dataPoints[0].y - basisH * dataPoints[n].y; return new Point(x, y); } function computeN(n, p, h, parameters, knots) { var N = []; var basisFunction = new BasisFunction(knots); for (var i = 1; i < n; i++) { N[i - 1] = []; for (var j = 1; j < h; j++) { N[i - 1].push(basisFunction.compute(parameters[i], j, p)); } } return N; } return self; })(); var IterativeApproximator = (function () { var self = {}; self.approximate = function (dataPoints, p, h, fittingStrategy, iterativeApproximationStrategy) { if (iterativeApproximationStrategy.getEndConditionType() == 'error-bounded') { return iterate(dataPoints, p, h, fittingStrategy, iterativeApproximationStrategy, function (i, distance) { return distance > iterativeApproximationStrategy.getEndConditionValue(); }); } if (iterativeApproximationStrategy.getEndConditionType() == 'iteration-bounded') { return iterate(dataPoints, p, h, fittingStrategy, iterativeApproximationStrategy, function (i, distance) { return i <= iterativeApproximationStrategy.getEndConditionValue(); }); } } var iterate = function (dataPoints, p, h, fittingStrategy, iterativeApproximationStrategy, iterateCondition) { var result = { approximations: [], bestApproximation: null }; var n = dataPoints.length - 1; for (var i = iterativeApproximationStrategy.getInitialNumberOfControlPoints(); i <= n; i++) { var approximation = BSplineBuilder .approximate(dataPoints, p, i - 1, fittingStrategy); if (approximation.error == "singular matrix") continue; result.approximations.push(approximation); if (result.bestApproximation == null) result.bestApproximation = approximation; else if (result.bestApproximation.error.maxDistance > approximation.error.maxDistance) result.bestApproximation = approximation; if (!iterateCondition(i, approximation.error.maxDistance)) return result; } return result; } return self; })(); return self; })()
mirsaeedi/BSpline
wwwroot/js/BSpline/BSplineBuilder.js
JavaScript
apache-2.0
8,517
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Threading; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.Language.Intellisense.Utilities; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.OptionsExtensionMethods; using Microsoft.VisualStudio.Text.Formatting; using Microsoft.VisualStudio.Text.Operations; using Microsoft.VisualStudio.Text.Projection; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; namespace Microsoft.VisualStudio.InteractiveWindow { internal partial class InteractiveWindow { private sealed partial class UIThreadOnly : IDisposable { private const string BoxSelectionCutCopyTag = "MSDEVColumnSelect"; private const int SpansPerLineOfInput = 2; private static readonly object SuppressPromptInjectionTag = new object(); private readonly InteractiveWindow _window; private readonly IInteractiveWindowEditorFactoryService _factory; private readonly History _history = new History(); private string _historySearch; private readonly ISmartIndentationService _smartIndenterService; // Pending submissions to be processed whenever the REPL is ready to accept submissions. private readonly Queue<PendingSubmission> _pendingSubmissions = new Queue<PendingSubmission>(); private DispatcherTimer _executionTimer; private Cursor _oldCursor; private int _currentOutputProjectionSpan; private int _outputTrackingCaretPosition = -1; private readonly IRtfBuilderService2 _rtfBuilderService; // Read-only regions protecting initial span of the corresponding buffers: private readonly IReadOnlyRegion[] _standardInputProtection = new IReadOnlyRegion[2]; private readonly IReadOnlyRegion[] _outputProtection = new IReadOnlyRegion[2]; private string _uncommittedInput; /// <remarks>Always access through <see cref="GetStandardInputValue"/> and <see cref="SetStandardInputValue"/>.</remarks> private SnapshotSpan? _standardInputValue; /// <remarks>Don't reference directly.</remarks> private readonly SemaphoreSlim _standardInputValueGuard = new SemaphoreSlim(initialCount: 0, maxCount: 1); // State captured when we started reading standard input. private int _standardInputStart = -1; /// <remarks>Always access through <see cref="SessionStack"/>.</remarks> private IIntellisenseSessionStack _sessionStack; // TODO: remove private readonly IIntellisenseSessionStackMapService _intellisenseSessionStackMap; private bool _adornmentToMinimize; private readonly string _lineBreakString; private readonly IProjectionBuffer _projectionBuffer; private readonly IContentType _inertType; private readonly OutputBuffer _buffer; private readonly IWaitIndicator _waitIndicator; public readonly ITextBuffer OutputBuffer; public readonly ITextBuffer StandardInputBuffer; public ITextBuffer CurrentLanguageBuffer { get; private set; } public readonly TextWriter OutputWriter; public readonly InteractiveWindowWriter ErrorOutputWriter; // the language engine and content type of the active submission: public readonly IInteractiveEvaluator Evaluator; public readonly IWpfTextView TextView; /// <remarks>Always access through <see cref="EditorOperations"/>.</remarks> private IEditorOperations _editorOperations; public IEditorOperations EditorOperations { get { return _editorOperations; } set { Debug.Assert(_editorOperations == null, "Assignment only happens once."); Debug.Assert(value != null); _editorOperations = value; } } /// <remarks>Always access through <see cref="State"/>.</remarks> private State _state; public State State { get { return _state; } set { _window.StateChanged?.Invoke(value); _state = value; } } public UIThreadOnly( InteractiveWindow window, IInteractiveWindowEditorFactoryService factory, IContentTypeRegistryService contentTypeRegistry, ITextBufferFactoryService bufferFactory, IProjectionBufferFactoryService projectionBufferFactory, IEditorOperationsFactoryService editorOperationsFactory, ITextEditorFactoryService editorFactory, IRtfBuilderService rtfBuilderService, IIntellisenseSessionStackMapService intellisenseSessionStackMap, ISmartIndentationService smartIndenterService, IInteractiveEvaluator evaluator, IWaitIndicator waitIndicator) { _window = window; _factory = factory; _rtfBuilderService = (IRtfBuilderService2)rtfBuilderService; _intellisenseSessionStackMap = intellisenseSessionStackMap; _smartIndenterService = smartIndenterService; _waitIndicator = waitIndicator; Evaluator = evaluator; var replContentType = contentTypeRegistry.GetContentType(PredefinedInteractiveContentTypes.InteractiveContentTypeName); var replOutputContentType = contentTypeRegistry.GetContentType(PredefinedInteractiveContentTypes.InteractiveOutputContentTypeName); OutputBuffer = bufferFactory.CreateTextBuffer(replOutputContentType); StandardInputBuffer = bufferFactory.CreateTextBuffer(); _inertType = bufferFactory.InertContentType; _projectionBuffer = projectionBufferFactory.CreateProjectionBuffer( new EditResolver(window), Array.Empty<object>(), ProjectionBufferOptions.None, replContentType); _projectionBuffer.Properties.AddProperty(typeof(InteractiveWindow), window); AppendNewOutputProjectionBuffer(); _projectionBuffer.Changed += new EventHandler<TextContentChangedEventArgs>(ProjectionBufferChanged); var roleSet = editorFactory.CreateTextViewRoleSet( PredefinedTextViewRoles.Analyzable, PredefinedTextViewRoles.Editable, PredefinedTextViewRoles.Interactive, PredefinedTextViewRoles.Zoomable, PredefinedInteractiveTextViewRoles.InteractiveTextViewRole); TextView = factory.CreateTextView(window, _projectionBuffer, roleSet); TextView.Caret.PositionChanged += CaretPositionChanged; var options = TextView.Options; options.SetOptionValue(DefaultTextViewHostOptions.HorizontalScrollBarId, true); options.SetOptionValue(DefaultTextViewHostOptions.LineNumberMarginId, false); options.SetOptionValue(DefaultTextViewHostOptions.OutliningMarginId, false); options.SetOptionValue(DefaultTextViewHostOptions.GlyphMarginId, false); options.SetOptionValue(DefaultTextViewOptions.WordWrapStyleId, WordWrapStyles.None); _lineBreakString = options.GetNewLineCharacter(); EditorOperations = editorOperationsFactory.GetEditorOperations(TextView); _buffer = new OutputBuffer(window); OutputWriter = new InteractiveWindowWriter(window, spans: null); SortedSpans errorSpans = new SortedSpans(); ErrorOutputWriter = new InteractiveWindowWriter(window, errorSpans); OutputClassifierProvider.AttachToBuffer(OutputBuffer, errorSpans); } private bool ReadingStandardInput => State == State.ExecutingInputAndReadingStandardInput || State == State.WaitingForInputAndReadingStandardInput || State == State.ResettingAndReadingStandardInput; /// <summary>Implements <see cref="IInteractiveWindowOperations.ResetAsync"/>.</summary> public async Task<ExecutionResult> ResetAsync(bool initialize) { try { if (ReadingStandardInput) { MakeStandardInputReadonly(); CancelStandardInput(); } _buffer.Flush(); // Nothing to clear in WaitingForInputAndReadingStandardInput, since we cleared // the language prompt when we entered that state. if (State == State.WaitingForInput) { var snapshot = _projectionBuffer.CurrentSnapshot; var spanCount = snapshot.SpanCount; Debug.Assert(GetSpanKind(snapshot.GetSourceSpan(spanCount - 1)) == ReplSpanKind.Input); StoreUncommittedInput(); RemoveProjectionSpans(spanCount - 2, 2); CurrentLanguageBuffer = null; } State = State.Resetting; var executionResult = await Evaluator.ResetAsync(initialize).ConfigureAwait(true); Debug.Assert(_window.OnUIThread()); // ConfigureAwait should bring us back to the UI thread. Debug.Assert(State == State.Resetting, $"Unexpected state {State}"); FinishExecute(executionResult.IsSuccessful); return executionResult; } catch (Exception e) when (_window.ReportAndPropagateException(e)) { throw ExceptionUtilities.Unreachable; } } /// <summary>Implements <see cref="IInteractiveWindow.Close"/>.</summary> public void Close() { TextView.Caret.PositionChanged -= CaretPositionChanged; TextView.Close(); } /// <summary>Implements <see cref="IInteractiveWindowOperations.ClearHistory"/>.</summary> public void ClearHistory() { _history.Clear(); } /// <summary>Implements <see cref="IInteractiveWindowOperations.ClearView"/>.</summary> public void ClearView() { if (ReadingStandardInput) { CancelStandardInput(); State = GetStateBeforeReadingStandardInput(State); Debug.Assert(State == State.ExecutingInput || State == State.WaitingForInput); } _adornmentToMinimize = false; InlineAdornmentProvider.RemoveAllAdornments(TextView); // remove all the spans except our initial span from the projection buffer _uncommittedInput = null; // Clear the projection and buffers last as this might trigger events that might access other state of the REPL window: RemoveProtection(OutputBuffer, _outputProtection); RemoveProtection(StandardInputBuffer, _standardInputProtection); using (var edit = OutputBuffer.CreateEdit(EditOptions.None, null, SuppressPromptInjectionTag)) { edit.Delete(0, OutputBuffer.CurrentSnapshot.Length); edit.Apply(); } _buffer.Reset(); OutputClassifierProvider.ClearSpans(OutputBuffer); _outputTrackingCaretPosition = 0; using (var edit = StandardInputBuffer.CreateEdit(EditOptions.None, null, SuppressPromptInjectionTag)) { edit.Delete(0, StandardInputBuffer.CurrentSnapshot.Length); edit.Apply(); } RemoveProjectionSpans(0, _projectionBuffer.CurrentSnapshot.SpanCount); // Insert an empty output buffer. // We do it for two reasons: // 1) When output is written to asynchronously we need a buffer to store it. // This may happen when clearing screen while background thread is writing to the console. // 2) We need at least one non-inert span due to bugs in projection buffer. AppendNewOutputProjectionBuffer(); _history.ForgetOriginalBuffers(); // If we were waiting for input, we need to restore the prompt that we just cleared. // If we are in any other state, then we'll let normal transitions trigger the next prompt. if (State == State.WaitingForInput) { PrepareForInput(); } } private static State GetStateBeforeReadingStandardInput(State state) { switch (state) { case State.WaitingForInputAndReadingStandardInput: return State.WaitingForInput; case State.ExecutingInputAndReadingStandardInput: return State.ExecutingInput; case State.ResettingAndReadingStandardInput: return State.Resetting; default: throw ExceptionUtilities.UnexpectedValue(state); } } /// <summary>Implements the core of <see cref="IInteractiveWindow.ReadStandardInput"/>.</summary> public async Task<TextReader> ReadStandardInputAsync() { try { switch (State) { case State.Starting: case State.Initializing: throw new InvalidOperationException(InteractiveWindowResources.NotInitialized); case State.WaitingForInputAndReadingStandardInput: case State.ExecutingInputAndReadingStandardInput: case State.ResettingAndReadingStandardInput: // Guarded by semaphore. throw ExceptionUtilities.UnexpectedValue(State); case State.WaitingForInput: State = State.WaitingForInputAndReadingStandardInput; break; case State.ExecutingInput: State = State.ExecutingInputAndReadingStandardInput; break; case State.Resetting: State = State.ResettingAndReadingStandardInput; break; default: throw ExceptionUtilities.UnexpectedValue(State); } Debug.Assert(ReadingStandardInput); _buffer.Flush(); if (State == State.WaitingForInputAndReadingStandardInput) { var snapshot = _projectionBuffer.CurrentSnapshot; var spanCount = snapshot.SpanCount; if (spanCount > 0 && GetSpanKind(snapshot.GetSourceSpan(spanCount - 1)) == ReplSpanKind.Input) { // we need to remove our input prompt. RemoveLastInputPrompt(); } } AddStandardInputSpan(); TextView.Caret.EnsureVisible(); ResetCursor(); _uncommittedInput = null; _standardInputStart = StandardInputBuffer.CurrentSnapshot.Length; var value = await GetStandardInputValue().ConfigureAwait(true); Debug.Assert(_window.OnUIThread()); // ConfigureAwait should bring us back to the UI thread. return value.HasValue ? new StringReader(value.GetValueOrDefault().GetText()) : null; } catch (Exception e) when (_window.ReportAndPropagateException(e)) { throw ExceptionUtilities.Unreachable; } } private void CancelStandardInput() { SetStandardInputValue(null); } private void SetStandardInputValue(SnapshotSpan? value) { _standardInputValue = value; _standardInputValueGuard.Release(); } private async Task<SnapshotSpan?> GetStandardInputValue() { try { await _standardInputValueGuard.WaitAsync().ConfigureAwait(true); Debug.Assert(_window.OnUIThread()); // ConfigureAwait should bring us back to the UI thread. return _standardInputValue; } catch (Exception e) when (_window.ReportAndPropagateException(e)) { throw ExceptionUtilities.Unreachable; } } private Span GetStandardInputSpan() { return Span.FromBounds(_standardInputStart, StandardInputBuffer.CurrentSnapshot.Length); } private void MakeStandardInputReadonly() { AppendLineNoPromptInjection(StandardInputBuffer); // We can also have an interleaving output span, so we'll search back for the last input span. var sourceSpans = _projectionBuffer.CurrentSnapshot.GetSourceSpans(); int index = IndexOfLastStandardInputSpan(sourceSpans); Debug.Assert(index >= 0); RemoveProtection(StandardInputBuffer, _standardInputProtection); // replace previous span w/ a span that won't grow... var oldSpan = sourceSpans[index]; var newSpan = new CustomTrackingSpan(oldSpan.Snapshot, oldSpan.Span); ReplaceProjectionSpan(index, newSpan); ApplyProtection(StandardInputBuffer, _standardInputProtection, allowAppend: true); } private void AppendLineNoPromptInjection(ITextBuffer buffer) { using (var edit = buffer.CreateEdit(EditOptions.None, null, SuppressPromptInjectionTag)) { edit.Insert(buffer.CurrentSnapshot.Length, _lineBreakString); edit.Apply(); } } /// <summary>Implements <see cref="IInteractiveWindow.InsertCode"/>.</summary> public void InsertCode(string text) { if (ReadingStandardInput) { return; } if (State == State.ExecutingInput) { AppendUncommittedInput(text); } else { if (!TextView.Selection.IsEmpty) { CutOrDeleteSelection(isCut: false); } EditorOperations.InsertText(text); } } /// <summary>Implements the core of <see cref="IInteractiveWindow.SubmitAsync"/>.</summary> public void Submit(PendingSubmission[] pendingSubmissions) { if (!ReadingStandardInput) { if (State == State.WaitingForInput && CurrentLanguageBuffer != null) { StoreUncommittedInput(); PendSubmissions(pendingSubmissions); ProcessPendingSubmissions(); } else { PendSubmissions(pendingSubmissions); } } } private void StoreUncommittedInput() { if (_uncommittedInput == null) { string activeCode = GetActiveCode(); if (!string.IsNullOrEmpty(activeCode)) { _uncommittedInput = activeCode; } } } /// <summary> /// Returns the full text of the current active input. /// </summary> private string GetActiveCode() { return CurrentLanguageBuffer.CurrentSnapshot.GetText(); } private void PendSubmissions(IEnumerable<PendingSubmission> inputs) { foreach (var input in inputs) { _pendingSubmissions.Enqueue(input); } } /// <summary>Implements <see cref="IInteractiveWindow.FlushOutput"/>.</summary> public void FlushOutput() { _buffer.Flush(); } /// <summary>Implements <see cref="IInteractiveWindow.AddInput"/>.</summary> public void AddInput(string command) { // If the language buffer is readonly then input can not be added. Return immediately. // The language buffer gets marked as readonly in SubmitAsync method when input on the prompt // gets submitted. So it would be readonly when the user types #reset on the prompt. In that // case it is the right thing to bail out of this method. if (CurrentLanguageBuffer != null && CurrentLanguageBuffer.IsReadOnly(0)) { return; } if (State == State.ExecutingInput || CurrentLanguageBuffer == null) { AddLanguageBuffer(); CurrentLanguageBuffer.Insert(0, command); } else { StoreUncommittedInput(); SetActiveCode(command); } // Add command to history before calling FinishCurrentSubmissionInput as it adds newline // to the end of the command. _history.Add(CurrentLanguageBuffer.CurrentSnapshot.GetExtent()); FinishCurrentSubmissionInput(); } private void AppendUncommittedInput(string text) { if (string.IsNullOrEmpty(text)) { // Do nothing. } else if (string.IsNullOrEmpty(_uncommittedInput)) { _uncommittedInput = text; } else { _uncommittedInput += text; } } private void RestoreUncommittedInput() { if (_uncommittedInput != null) { SetActiveCode(_uncommittedInput); _uncommittedInput = null; } } /// <summary> /// Pastes from the clipboard into the text view /// Implements <see cref="IInteractiveWindowOperations.Paste"/>. /// </summary> public bool Paste() { if (!TextView.Selection.IsEmpty) { if (CutOrDeleteSelection(isCut: false)) { MoveCaretToClosestEditableBuffer(); } else { return false; } } else if (IsInActivePrompt(TextView.Caret.Position.BufferPosition)) { MoveCaretToClosestEditableBuffer(); } else if (MapToEditableBuffer(TextView.Caret.Position.BufferPosition) == null) { return false; } string format = Evaluator.FormatClipboard(); if (format != null) { InsertCode(format); } else if (_window.InteractiveWindowClipboard.ContainsData(ClipboardFormat)) { var blocks = BufferBlock.Deserialize((string)_window.InteractiveWindowClipboard.GetData(ClipboardFormat)); // Paste each block separately. foreach (var block in blocks) { switch (block.Kind) { case ReplSpanKind.Input: case ReplSpanKind.Output: case ReplSpanKind.StandardInput: InsertCode(block.Content); break; } } } else if (_window.InteractiveWindowClipboard.ContainsText()) { InsertCode(_window.InteractiveWindowClipboard.GetText()); } else { return false; } return true; } private void MoveCaretToClosestEditableBuffer() { SnapshotPoint currentPosition = TextView.Caret.Position.BufferPosition; SnapshotPoint newPosition = GetClosestEditablePoint(currentPosition); if (currentPosition != newPosition) { TextView.Caret.MoveTo(newPosition); } } /// <summary> /// Finds a point in an editable buffer that is the closest towards the end to the given projection point. /// </summary> private SnapshotPoint GetClosestEditablePoint(SnapshotPoint projectionPoint) { ITextBuffer editableBuffer = ReadingStandardInput ? StandardInputBuffer : CurrentLanguageBuffer; if (editableBuffer == null) { return new SnapshotPoint(_projectionBuffer.CurrentSnapshot, _projectionBuffer.CurrentSnapshot.Length); } SnapshotPoint? point = GetPositionInBuffer(projectionPoint, editableBuffer); if (point != null) { return projectionPoint; } var projectionLine = projectionPoint.GetContainingLine(); SnapshotPoint? lineEnd = TextView.BufferGraph.MapDownToBuffer( projectionLine.End, PointTrackingMode.Positive, editableBuffer, PositionAffinity.Successor); SnapshotPoint editablePoint; if (lineEnd == null) { editablePoint = new SnapshotPoint(editableBuffer.CurrentSnapshot, 0); } else { editablePoint = lineEnd.Value.GetContainingLine().Start; } return TextView.BufferGraph.MapUpToBuffer( editablePoint, PointTrackingMode.Positive, PositionAffinity.Successor, _projectionBuffer).Value; } /// <summary> /// Appends given text to the last input span (standard input or active code input). /// </summary> private void AppendInput(string text) { var snapshot = _projectionBuffer.CurrentSnapshot; var spanCount = snapshot.SpanCount; var inputSpan = snapshot.GetSourceSpan(spanCount - 1); Debug.Assert(GetSpanKind(inputSpan) == ReplSpanKind.Input || GetSpanKind(inputSpan) == ReplSpanKind.StandardInput); var buffer = inputSpan.Snapshot.TextBuffer; var span = inputSpan.Span; using (var edit = buffer.CreateEdit()) { edit.Insert(edit.Snapshot.Length, text); edit.Apply(); } var replSpan = new CustomTrackingSpan( buffer.CurrentSnapshot, new Span(span.Start, span.Length + text.Length), canAppend: true); ReplaceProjectionSpan(spanCount - 1, replSpan); TextView.Caret.EnsureVisible(); } public void PrepareForInput() { _buffer.Flush(); AddLanguageBuffer(); State = State.WaitingForInput; // we are prepared for processing any postponed submissions there might have been: ProcessPendingSubmissions(); } private void ProcessPendingSubmissions() { Debug.Assert(CurrentLanguageBuffer != null); if (_pendingSubmissions.Count == 0) { RestoreUncommittedInput(); // move to the end (it might have been in virtual space): TextView.Caret.MoveTo(GetLastLine(TextView.TextBuffer.CurrentSnapshot).End); TextView.Caret.EnsureVisible(); var ready = _window.ReadyForInput; if (ready != null) { ready(); } return; } var submission = _pendingSubmissions.Dequeue(); SetActiveCode(submission.Input); Debug.Assert(submission.Task == null, "Someone set PendingSubmission.Task before it was dequeued."); submission.Task = SubmitAsync(); if (submission.Completion != null) { // ContinueWith is safe since TaskCompletionSource.SetResult should not throw. // Therefore, we don't need to await the task (which we would normally do to // propagate any exceptions it might throw). We also don't need an NFW // exception filter around the continuation. submission.Task.ContinueWith(_ => submission.Completion.SetResult(null), TaskScheduler.Current); } } #region Editor Helpers private static ITextSnapshotLine GetLastLine(ITextSnapshot snapshot) { return snapshot.GetLineFromLineNumber(snapshot.LineCount - 1); } private static int IndexOfNonWhiteSpaceCharacter(ITextSnapshotLine line) { var snapshot = line.Snapshot; int start = line.Start.Position; int count = line.Length; for (int i = 0; i < count; i++) { if (!char.IsWhiteSpace(snapshot[start + i])) { return i; } } return -1; } #endregion private async Task SubmitAsync() { try { RequiresLanguageBuffer(); // TODO: queue submission // Ensure that the REPL doesn't try to execute if it is already // executing. If this invariant can no longer be maintained more of // the code in this method will need to be bullet-proofed if (State == State.ExecutingInput) { return; } // get command to save to history before calling FinishCurrentSubmissionInput // as it adds newline at the end var historySpan = CurrentLanguageBuffer.CurrentSnapshot.GetExtent(); FinishCurrentSubmissionInput(); _history.UncommittedInput = null; var snapshotSpan = CurrentLanguageBuffer.CurrentSnapshot.GetExtent(); var trimmedSpan = snapshotSpan.TrimEnd(); if (trimmedSpan.Length == 0) { // TODO: reuse the current language buffer PrepareForInput(); return; } else { _history.Add(historySpan); State = State.ExecutingInput; StartCursorTimer(); var executionResult = await Evaluator.ExecuteCodeAsync(snapshotSpan.GetText()).ConfigureAwait(true); Debug.Assert(_window.OnUIThread()); // ConfigureAwait should bring us back to the UI thread. // For reset command typed at prompt -> the state should be WaitingForInput. // For all other submissions on the prompt -> it should be Executing input. // If reset button is clicked during a long running submission -> it could be Resetting because // oldService is disposed first as part of resetting, which leads to await call above returning, and new service is // created after that as part of completing the resetting process. Debug.Assert(State == State.ExecutingInput || State == State.WaitingForInput || State == State.Resetting, $"Unexpected state {State}"); if (State == State.ExecutingInput) { FinishExecute(executionResult.IsSuccessful); } } } catch (Exception e) when (_window.ReportAndPropagateException(e)) { throw ExceptionUtilities.Unreachable; } } private void RequiresLanguageBuffer() { if (CurrentLanguageBuffer == null) { Environment.FailFast("Language buffer not available"); } } private void FinishCurrentSubmissionInput() { AppendLineNoPromptInjection(CurrentLanguageBuffer); ApplyProtection(CurrentLanguageBuffer, regions: null); if (_adornmentToMinimize) { // TODO (tomat): remember the index of the adornment(s) in the current output and minimize those instead of the last one InlineAdornmentProvider.MinimizeLastInlineAdornment(TextView); _adornmentToMinimize = false; } NewOutputBuffer(); } /// <summary> /// Marks the entire buffer as read-only. /// </summary> private void ApplyProtection(ITextBuffer buffer, IReadOnlyRegion[] regions, bool allowAppend = false) { using (var readonlyEdit = buffer.CreateReadOnlyRegionEdit()) { int end = buffer.CurrentSnapshot.Length; Span span = new Span(0, end); var region0 = allowAppend ? readonlyEdit.CreateReadOnlyRegion(span, SpanTrackingMode.EdgeExclusive, EdgeInsertionMode.Allow) : readonlyEdit.CreateReadOnlyRegion(span, SpanTrackingMode.EdgeExclusive, EdgeInsertionMode.Deny); // Create a second read-only region to prevent insert at start of buffer. var region1 = (end > 0) ? readonlyEdit.CreateReadOnlyRegion(new Span(0, 0), SpanTrackingMode.EdgeExclusive, EdgeInsertionMode.Deny) : null; readonlyEdit.Apply(); if (regions != null) { regions[0] = region0; regions[1] = region1; } } } /// <summary> /// Removes read-only region from buffer. /// </summary> private void RemoveProtection(ITextBuffer buffer, IReadOnlyRegion[] regions) { if (regions[0] != null) { Debug.Assert(regions[1] != null); foreach (var region in regions) { using (var readonlyEdit = buffer.CreateReadOnlyRegionEdit()) { readonlyEdit.RemoveReadOnlyRegion(region); readonlyEdit.Apply(); } } } } private void NewOutputBuffer() { // Stop growing the current output projection span. var sourceSpan = _projectionBuffer.CurrentSnapshot.GetSourceSpan(_currentOutputProjectionSpan); Debug.Assert(GetSpanKind(sourceSpan) == ReplSpanKind.Output); var nonGrowingSpan = new CustomTrackingSpan( sourceSpan.Snapshot, sourceSpan.Span); ReplaceProjectionSpan(_currentOutputProjectionSpan, nonGrowingSpan); AppendNewOutputProjectionBuffer(); _outputTrackingCaretPosition = TextView.Caret.Position.BufferPosition; } private void AppendNewOutputProjectionBuffer() { var currentSnapshot = OutputBuffer.CurrentSnapshot; var trackingSpan = new CustomTrackingSpan( currentSnapshot, new Span(currentSnapshot.Length, 0), canAppend: true); _currentOutputProjectionSpan = AppendProjectionSpan(trackingSpan); } private int AppendProjectionSpan(ITrackingSpan span) { int index = _projectionBuffer.CurrentSnapshot.SpanCount; InsertProjectionSpan(index, span); return index; } private void InsertProjectionSpan(int index, object span) { _projectionBuffer.ReplaceSpans(index, 0, new[] { span }, EditOptions.None, editTag: SuppressPromptInjectionTag); } private void ReplaceProjectionSpan(int spanToReplace, ITrackingSpan newSpan) { _projectionBuffer.ReplaceSpans(spanToReplace, 1, new[] { newSpan }, EditOptions.None, editTag: SuppressPromptInjectionTag); } private void RemoveProjectionSpans(int index, int count) { _projectionBuffer.ReplaceSpans(index, count, Array.Empty<object>(), EditOptions.None, SuppressPromptInjectionTag); } /// <summary> /// Appends text to the output buffer and updates projection buffer to include it. /// WARNING: this has to be the only method that writes to the output buffer so that /// the output buffering counters are kept in sync. /// </summary> internal void AppendOutput(IEnumerable<string> output) { Debug.Assert(output.Any()); // we maintain this invariant so that projections don't split "\r\n" in half: Debug.Assert(!OutputBuffer.CurrentSnapshot.EndsWith('\r')); var projectionSpans = _projectionBuffer.CurrentSnapshot.GetSourceSpans(); Debug.Assert(GetSpanKind(projectionSpans[_currentOutputProjectionSpan]) == ReplSpanKind.Output); int lineBreakProjectionSpanIndex = _currentOutputProjectionSpan + 1; // insert line break projection span if there is none and the output doesn't end with a line break: bool hasLineBreakProjection = false; if (lineBreakProjectionSpanIndex < projectionSpans.Count) { var oldSpan = projectionSpans[lineBreakProjectionSpanIndex]; hasLineBreakProjection = GetSpanKind(oldSpan) == ReplSpanKind.LineBreak; } Debug.Assert(output.Last().Last() != '\r'); bool endsWithLineBreak = output.Last().Last() == '\n'; // insert text to the subject buffer. int oldBufferLength = OutputBuffer.CurrentSnapshot.Length; InsertOutput(output, oldBufferLength); if (endsWithLineBreak && hasLineBreakProjection) { // Remove line break. RemoveProjectionSpans(lineBreakProjectionSpanIndex, 1); } else if (!endsWithLineBreak && !hasLineBreakProjection) { // Insert line break. InsertProjectionSpan(lineBreakProjectionSpanIndex, _lineBreakString); } // caret didn't move since last time we moved it to track output: if (_outputTrackingCaretPosition == TextView.Caret.Position.BufferPosition) { TextView.Caret.EnsureVisible(); _outputTrackingCaretPosition = TextView.Caret.Position.BufferPosition; } } private void InsertOutput(IEnumerable<string> output, int position) { RemoveProtection(OutputBuffer, _outputProtection); // append the text to output buffer and make sure it ends with a line break: using (var edit = OutputBuffer.CreateEdit(EditOptions.None, null, SuppressPromptInjectionTag)) { foreach (string text in output) { edit.Insert(position, text); } edit.Apply(); } ApplyProtection(OutputBuffer, _outputProtection); } private void FinishExecute(bool succeeded) { ResetCursor(); if (!succeeded && _history.Last != null) { _history.Last.Failed = true; } PrepareForInput(); } /// <summary>Implements <see cref="IInteractiveWindowOperations.ExecuteInput"/>.</summary> public async Task ExecuteInputAsync() { try { ITextBuffer languageBuffer = GetLanguageBuffer(TextView.Caret.Position.BufferPosition); if (languageBuffer == null) { return; } if (languageBuffer == CurrentLanguageBuffer) { // TODO (tomat): this should rather send an abstract "finish" command that various features // can implement as needed (IntelliSense, inline rename would commit, etc.). // For now, commit IntelliSense: var completionSession = SessionStack.TopSession as ICompletionSession; if (completionSession != null) { completionSession.Commit(); } await SubmitAsync().ConfigureAwait(true); Debug.Assert(_window.OnUIThread()); // ConfigureAwait should bring us back to the UI thread. } else { // append text of the target buffer to the current language buffer: string text = TrimTrailingEmptyLines(languageBuffer.CurrentSnapshot); CurrentLanguageBuffer.Replace(new Span(CurrentLanguageBuffer.CurrentSnapshot.Length, 0), text); EditorOperations.MoveToEndOfDocument(false); } } catch (Exception e) when (_window.ReportAndPropagateException(e)) { throw ExceptionUtilities.Unreachable; } } private IIntellisenseSessionStack SessionStack { get { if (_sessionStack == null) { _sessionStack = _intellisenseSessionStackMap.GetStackForTextView(TextView); } return _sessionStack; } } private static string TrimTrailingEmptyLines(ITextSnapshot snapshot) { var line = GetLastLine(snapshot); while (line != null && line.Length == 0) { line = GetPreviousLine(line); } if (line == null) { return string.Empty; } return line.Snapshot.GetText(0, line.Extent.End.Position); } private static ITextSnapshotLine GetPreviousLine(ITextSnapshotLine line) { return line.LineNumber > 0 ? line.Snapshot.GetLineFromLineNumber(line.LineNumber - 1) : null; } /// <summary> /// Returns the language or command text buffer that the specified point belongs to. /// If the point lays in a prompt returns the buffer corresponding to the prompt. /// </summary> /// <returns>The language or command buffer or null if the point doesn't belong to any.</returns> private ITextBuffer GetLanguageBuffer(SnapshotPoint point) { var sourceSpans = GetSourceSpans(point.Snapshot); int promptIndex = GetPromptIndexForPoint(sourceSpans, point); if (promptIndex < 0) { return null; } // Grab the span following the prompt (either language or standard input). var projectionSpan = sourceSpans[promptIndex + 1]; var kind = GetSpanKind(projectionSpan); if (kind != ReplSpanKind.Input) { Debug.Assert(kind == ReplSpanKind.StandardInput); return null; } var inputSnapshot = projectionSpan.Snapshot; var inputBuffer = inputSnapshot.TextBuffer; var projectedSpans = TextView.BufferGraph.MapUpToBuffer( new SnapshotSpan(inputSnapshot, 0, inputSnapshot.Length), SpanTrackingMode.EdgePositive, _projectionBuffer); Debug.Assert(projectedSpans.Count > 0); var projectedSpansStart = projectedSpans.First().Start; var projectedSpansEnd = projectedSpans.Last().End; if (point < projectedSpansStart.GetContainingLine().Start) { return null; } // If the buffer is the current buffer, the cursor might be in a virtual space behind the buffer // but logically it belongs to the current submission. Since the current language buffer is the last buffer in the // projection we don't need to check for its end. if (inputBuffer == CurrentLanguageBuffer) { return inputBuffer; } // if the point is at the end of the buffer it might be on the next line that doesn't logically belong to the input region: if (point > projectedSpansEnd || (point == projectedSpansEnd && projectedSpansEnd.GetContainingLine().LineBreakLength != 0)) { return null; } return inputBuffer; } private int GetPromptIndexForPoint(ReadOnlyCollection<SnapshotSpan> sourceSpans, SnapshotPoint point) { int index = GetSourceSpanIndex(sourceSpans, point); if (index == sourceSpans.Count) { index--; } // Find the nearest preceding prompt. while (index >= 0 && !IsPrompt(sourceSpans[index])) { index--; } return index; } private bool IsInActivePrompt(SnapshotPoint point) { var editableBuffer = ReadingStandardInput ? StandardInputBuffer : CurrentLanguageBuffer; if (editableBuffer == null) { return false; } var sourceSpans = GetSourceSpans(point.Snapshot); var index = GetSourceSpanIndex(sourceSpans, point); if (index == sourceSpans.Count) { index--; } if (!IsPrompt(sourceSpans[index])) { return false; } Debug.Assert(index + 1 < sourceSpans.Count); var followingSpan = sourceSpans[index + 1]; // if the following span is editable, then the prompt is active. return GetPositionInBuffer(followingSpan.Start, editableBuffer) != null; } /// <summary> /// Return the index of the span containing the point. Returns the /// length of the collection if the point is at the end of the last span. /// </summary> private int GetSourceSpanIndex(ReadOnlyCollection<SnapshotSpan> sourceSpans, SnapshotPoint point) { int low = 0; int high = sourceSpans.Count; while (low < high) { int mid = low + (high - low) / 2; int value = CompareToSpan(TextView, sourceSpans, mid, point); if (value == 0) { return mid; } else if (value < 0) { high = mid - 1; } else { low = mid + 1; } } Debug.Assert(low >= 0); Debug.Assert(low <= sourceSpans.Count); return low; } /// <summary> /// Returns negative value if the point is less than the span start, /// positive if greater than or equal to the span end, and 0 otherwise. /// </summary> private static int CompareToSpan(ITextView textView, ReadOnlyCollection<SnapshotSpan> sourceSpans, int index, SnapshotPoint point) { // If this span is zero-width and there are multiple projections of the // containing snapshot in the projection buffer, MapUpToBuffer will return // multiple (ambiguous) projection spans. To avoid that, we compare the // point to the end point of the nearest non-zero width span instead. int indexToCompare = index; while (sourceSpans[indexToCompare].IsEmpty) { if (indexToCompare == 0) { // Empty span at start of buffer. Point // must be to the right of span. return 1; } indexToCompare--; } var sourceSpan = sourceSpans[indexToCompare]; Debug.Assert(sourceSpan.Length > 0); var mappedSpans = textView.BufferGraph.MapUpToBuffer(sourceSpan, SpanTrackingMode.EdgeInclusive, textView.TextBuffer); Debug.Assert(mappedSpans.Count == 1); var mappedSpan = mappedSpans[0]; Debug.Assert(mappedSpan.Length == sourceSpan.Length); if (indexToCompare < index) { var result = point.CompareTo(mappedSpan.End); return (result == 0) ? 1 : result; } else { var result = point.CompareTo(mappedSpan.Start); if (result <= 0) { return result; } result = point.CompareTo(mappedSpan.End); return (result < 0) ? 0 : 1; } } private static ReadOnlyCollection<SnapshotSpan> GetSourceSpans(ITextSnapshot snapshot) { return ((IProjectionSnapshot)snapshot).GetSourceSpans(); } private bool IsPrompt(SnapshotSpan span) { return GetSpanKind(span) == ReplSpanKind.Prompt; } private void ResetCursor() { if (_executionTimer != null) { _executionTimer.Stop(); } if (_oldCursor != null) { ((ContentControl)TextView).Cursor = _oldCursor; } _oldCursor = null; _executionTimer = null; } private void StartCursorTimer() { var timer = new DispatcherTimer(); timer.Tick += SetRunningCursor; timer.Interval = TimeSpan.FromMilliseconds(250); _executionTimer = timer; timer.Start(); } private void SetRunningCursor(object sender, EventArgs e) { var view = (ContentControl)TextView; // Save the old value of the cursor so it can be restored // after execution has finished _oldCursor = view.Cursor; // TODO: Design work to come up with the correct cursor to use // Set the repl's cursor to the "executing" cursor view.Cursor = Cursors.Wait; // Stop the timer so it doesn't fire again if (_executionTimer != null) { _executionTimer.Stop(); } } private int IndexOfLastStandardInputSpan(ReadOnlyCollection<SnapshotSpan> sourceSpans) { for (int i = sourceSpans.Count - 1; i >= 0; i--) { if (GetSpanKind(sourceSpans[i]) == ReplSpanKind.StandardInput) { return i; } } return -1; } private void RemoveLastInputPrompt() { var snapshot = _projectionBuffer.CurrentSnapshot; var spanCount = snapshot.SpanCount; Debug.Assert(IsPrompt(snapshot.GetSourceSpan(spanCount - SpansPerLineOfInput))); // projection buffer update must be the last operation as it might trigger event that accesses prompt line mapping: RemoveProjectionSpans(spanCount - SpansPerLineOfInput, SpansPerLineOfInput); } /// <summary> /// Creates and adds a new language buffer to the projection buffer. /// </summary> private void AddLanguageBuffer() { ITextBuffer buffer = _factory.CreateAndActivateBuffer(_window); buffer.Properties.AddProperty(typeof(IInteractiveEvaluator), Evaluator); buffer.Properties.AddProperty(typeof(InteractiveWindow), _window); CurrentLanguageBuffer = buffer; var bufferAdded = _window.SubmissionBufferAdded; if (bufferAdded != null) { bufferAdded(_window, new SubmissionBufferAddedEventArgs(buffer)); } _window.LanguageBufferCounter++; // add the whole buffer to the projection buffer and set it up to expand to the right as text is appended var promptSpan = CreatePrimaryPrompt(); var languageSpan = new CustomTrackingSpan( CurrentLanguageBuffer.CurrentSnapshot, new Span(0, 0), canAppend: true); // projection buffer update must be the last operation as it might trigger event that accesses prompt line mapping: AppendProjectionSpans(promptSpan, languageSpan); } private void AppendProjectionSpans(object span1, object span2) { int index = _projectionBuffer.CurrentSnapshot.SpanCount; _projectionBuffer.ReplaceSpans(index, 0, new[] { span1, span2 }, EditOptions.None, editTag: SuppressPromptInjectionTag); } private bool TryGetCurrentLanguageBufferExtent(IProjectionSnapshot projectionSnapshot, out Span result) { if (projectionSnapshot.SpanCount == 0) { result = default(Span); return false; } // the last source snapshot is always a projection of a language buffer: var snapshot = projectionSnapshot.GetSourceSpan(projectionSnapshot.SpanCount - 1).Snapshot; if (snapshot.TextBuffer != CurrentLanguageBuffer) { result = default(Span); return false; } SnapshotPoint start = new SnapshotPoint(snapshot, 0); SnapshotPoint end = new SnapshotPoint(snapshot, snapshot.Length); // projection of the previous version of current language buffer snapshot: var surfaceSpans = projectionSnapshot.MapFromSourceSnapshot(new SnapshotSpan(start, end)); // the language buffer might be projected to multiple surface lines: Debug.Assert(surfaceSpans.Count > 0); result = new Span(surfaceSpans[0].Start, surfaceSpans.Last().End); return true; } private void ProjectionBufferChanged(object sender, TextContentChangedEventArgs e) { // this is an edit performed in this event: if (e.EditTag == SuppressPromptInjectionTag) { return; } // projection buffer is changed before language buffer is created (for example, output might be printed out during initialization): if (CurrentLanguageBuffer == null) { return; } var oldSnapshot = (IProjectionSnapshot)e.Before; var newSnapshot = (IProjectionSnapshot)e.After; Span oldSurfaceLanguageBufferExtent; Span newSurfaceLanguageBufferExtent; if (!TryGetCurrentLanguageBufferExtent(oldSnapshot, out oldSurfaceLanguageBufferExtent) || !TryGetCurrentLanguageBufferExtent(newSnapshot, out newSurfaceLanguageBufferExtent)) { return; } List<SpanRangeEdit> spanEdits = null; var oldProjectionSpans = oldSnapshot.GetSourceSpans(); int oldProjectionSpanCount = oldProjectionSpans.Count; // changes are sorted by position foreach (var change in e.Changes) { // Old/new span might be outside of the language buffer -- on the left of it, since // the language buffer always reaches to the end of the projection buffer. Span oldSurfaceIntersection = oldSurfaceLanguageBufferExtent.Intersection(change.OldSpan) ?? new Span(oldSurfaceLanguageBufferExtent.Start, 0); Span newSurfaceIntersection = newSurfaceLanguageBufferExtent.Intersection(change.NewSpan) ?? new Span(newSurfaceLanguageBufferExtent.Start, 0); // change doesn't affect the language buffer: if (oldSurfaceIntersection.IsEmpty && newSurfaceIntersection.IsEmpty) { continue; } var oldSurfaceStartLineNumber = oldSnapshot.GetLineNumberFromPosition(oldSurfaceIntersection.Start); var oldSurfaceEndLineNumber = oldSnapshot.GetLineNumberFromPosition(oldSurfaceIntersection.End); // The change doesn't include line breaks and is entirely within the current // language buffer. Note that we might need to proceed with span replacement even if // line count delta is zero: the tracking spans of all but last language buffer // projections need to stop growing. if (oldSurfaceStartLineNumber == oldSurfaceEndLineNumber && change.LineCountDelta == 0 && oldSurfaceIntersection == change.OldSpan && newSurfaceIntersection == change.NewSpan) { continue; } // calculate which prompts and language projection spans to remove and replace with new spans: int oldStartSpanIndex = GetProjectionSpanIndexFromEditableBufferPosition(oldSnapshot, oldProjectionSpanCount, oldSurfaceStartLineNumber); int oldEndSpanIndex = GetProjectionSpanIndexFromEditableBufferPosition(oldSnapshot, oldProjectionSpanCount, oldSurfaceEndLineNumber); int spansToReplace = oldEndSpanIndex - oldStartSpanIndex + 1; Debug.Assert(spansToReplace >= 1); var newSubjectStartLine = newSnapshot.MapToSourceSnapshot(newSurfaceIntersection.Start).GetContainingLine(); var newSubjectEndLine = newSnapshot.MapToSourceSnapshot(newSurfaceIntersection.End).GetContainingLine(); var newSubjectEndLineNumber = newSubjectEndLine.LineNumber; int i = 0; int lineBreakCount = newSubjectEndLineNumber - newSubjectStartLine.LineNumber; var newSpans = new object[lineBreakCount * SpansPerLineOfInput + 1]; var subjectLine = newSubjectStartLine; while (true) { if (subjectLine.LineNumber != newSubjectStartLine.LineNumber) { // TODO (crwilcox): do we need two prompts? Can I tell it to not do this? Or perhaps we do want this since we want different markings? newSpans[i++] = CreateSecondaryPrompt(); } newSpans[i++] = CreateLanguageSpanForLine(subjectLine); if (subjectLine.LineNumber == newSubjectEndLineNumber) { break; } subjectLine = subjectLine.Snapshot.GetLineFromLineNumber(subjectLine.LineNumber + 1); } Debug.Assert(i == newSpans.Length); if (spanEdits == null) { spanEdits = new List<SpanRangeEdit>(); } spanEdits.Add(new SpanRangeEdit(oldStartSpanIndex, spansToReplace, newSpans)); } if (spanEdits != null) { ReplaceProjectionSpans(oldProjectionSpans, spanEdits); } CheckProjectionSpans(); } // Verify spans and GetSourceSpanIndex. [Conditional("DEBUG")] private void CheckProjectionSpans() { var snapshot = _projectionBuffer.CurrentSnapshot; var sourceSpans = snapshot.GetSourceSpans(); int n = sourceSpans.Count; // Spans should be contiguous and span the entire buffer. int offset = 0; for (int i = 0; i < n; i++) { // Determine the index of the first non-zero width // span starting at the same point as current span. int expectedIndex = i; while (sourceSpans[expectedIndex].IsEmpty) { expectedIndex++; if (expectedIndex == n) { break; } } // Verify GetSourceSpanIndex returns the expected // index for the start of the span. int index = GetSourceSpanIndex(sourceSpans, new SnapshotPoint(snapshot, offset)); Debug.Assert(index == expectedIndex); // If this is a non-empty span, verify GetSourceSpanIndex // returns the index for the midpoint of the span. int length = sourceSpans[i].Length; if (length > 0) { index = GetSourceSpanIndex(sourceSpans, new SnapshotPoint(snapshot, offset + length / 2)); Debug.Assert(index == i); } offset += length; } Debug.Assert(offset == snapshot.Length); if (n > 0) { int index = GetSourceSpanIndex(sourceSpans, new SnapshotPoint(snapshot, snapshot.Length)); Debug.Assert(index == n); } } /// <remarks> /// This should only be called from within the current language buffer. If there are /// any output or standard input buffers between the specified line and the end of the /// surface buffer, then the result will be incorrect. /// </remarks> private int GetProjectionSpanIndexFromEditableBufferPosition(IProjectionSnapshot surfaceSnapshot, int projectionSpansCount, int surfaceLineNumber) { // The current language buffer is projected to a set of projections interleaved regularly by prompt projections // and ending at the end of the projection buffer, each language buffer projection is on a separate line: // [prompt)[language)...[prompt)[language)<end of projection buffer> int result = projectionSpansCount - (surfaceSnapshot.LineCount - surfaceLineNumber) * SpansPerLineOfInput + 1; Debug.Assert(GetSpanKind(surfaceSnapshot.GetSourceSpan(result)) == ReplSpanKind.Input); return result; } private void ReplaceProjectionSpans(ReadOnlyCollection<SnapshotSpan> oldProjectionSpans, List<SpanRangeEdit> spanEdits) { Debug.Assert(spanEdits.Count > 0); int start = spanEdits[0].Start; int end = spanEdits[spanEdits.Count - 1].End; var replacement = new List<object>(); replacement.AddRange(spanEdits[0].Replacement); int lastEnd = spanEdits[0].End; for (int i = 1; i < spanEdits.Count; i++) { SpanRangeEdit edit = spanEdits[i]; int gap = edit.Start - lastEnd; // there is always at least prompt span in between subsequent edits Debug.Assert(gap != 0); // spans can't share more then one span Debug.Assert(gap >= -1); if (gap == -1) { replacement.AddRange(edit.Replacement.Skip(1)); } else { replacement.AddRange(oldProjectionSpans.Skip(lastEnd).Take(gap).Select(CreateTrackingSpan)); replacement.AddRange(edit.Replacement); } lastEnd = edit.End; } _projectionBuffer.ReplaceSpans(start, end - start, replacement, EditOptions.None, SuppressPromptInjectionTag); } private object CreateTrackingSpan(SnapshotSpan snapshotSpan) { var snapshot = snapshotSpan.Snapshot; if (snapshot.ContentType == _inertType) { return snapshotSpan.GetText(); } return new CustomTrackingSpan(snapshot, snapshotSpan.Span); } private ITrackingSpan CreateLanguageSpanForLine(ITextSnapshotLine languageLine) { var span = languageLine.ExtentIncludingLineBreak; bool lastLine = (languageLine.LineNumber == languageLine.Snapshot.LineCount - 1); return new CustomTrackingSpan( CurrentLanguageBuffer.CurrentSnapshot, span, canAppend: lastLine); } private void ScrollToCaret() { var textView = TextView; var caretPosition = textView.Caret.Position.BufferPosition; var caretSpan = new SnapshotSpan(caretPosition.Snapshot, caretPosition, 0); textView.ViewScroller.EnsureSpanVisible(caretSpan); } private void CaretPositionChanged(object sender, CaretPositionChangedEventArgs e) { // make sure language buffer exist if (CurrentLanguageBuffer == null) { return; } var caretPoint = e.NewPosition.BufferPosition; // make sure caret is on the right line // 1. changes are on virtual space if (e.NewPosition.BufferPosition == e.OldPosition.BufferPosition) { return; } // 2. caret is at the end of the surface line if (caretPoint != caretPoint.GetContainingLine().End) { return; } // 3. subject line has length == 0 var point = e.NewPosition.Point.GetInsertionPoint(b => b == CurrentLanguageBuffer); if (!point.HasValue) { return; } var line = point.Value.GetContainingLine(); if (point.Value != line.End || line.Length != 0) { return; } try { // detach event handler TextView.Caret.PositionChanged -= CaretPositionChanged; IndentCurrentLine(caretPoint); } finally { // attach event handler TextView.Caret.PositionChanged += CaretPositionChanged; } } /// <summary> /// Indents the line where the caret is currently located. /// </summary> /// <remarks> /// We don't send this command to the editor since smart indentation doesn't work along with /// BufferChanged event. Instead, we need to implement indentation ourselves. We still use /// ISmartIndentProvider provided by the language. /// </remarks> private void IndentCurrentLine(SnapshotPoint caretPosition) { Debug.Assert(CurrentLanguageBuffer != null); var caretLine = caretPosition.GetContainingLine(); var indentation = _smartIndenterService.GetDesiredIndentation(TextView, caretLine); // When the user submits via ctrl-enter, the indenter service sometimes // gets confused and maps the subject position after the last newline in // a language buffer to the location *before* the next prompt in the // surface buffer. When this happens, indentation will be 0. Fortunately, // no indentation is required in such cases, so we can just do nothing. if (indentation != null && indentation != 0) { var sourceSpans = GetSourceSpans(caretPosition.Snapshot); var promptIndex = GetPromptIndexForPoint(sourceSpans, caretPosition); var promptSpan = sourceSpans[promptIndex]; Debug.Assert(IsPrompt(promptSpan)); int promptLength = promptSpan.Length; Debug.Assert(promptLength == 2 || promptLength == 0); // Not required, just expected. var adjustedIndentationValue = indentation.GetValueOrDefault() - promptLength; if (caretPosition == caretLine.End) { // create virtual space: TextView.Caret.MoveTo(new VirtualSnapshotPoint(caretPosition, adjustedIndentationValue)); } else { var langCaret = GetPositionInLanguageBuffer(caretPosition); if (langCaret == null) { return; } // insert whitespace indentation: var options = TextView.Options; string whitespace = GetWhiteSpaceForVirtualSpace(adjustedIndentationValue, options.IsConvertTabsToSpacesEnabled() ? default(int?) : options.GetTabSize()); CurrentLanguageBuffer.Insert(langCaret.Value, whitespace); } } } private SnapshotPoint? GetPositionInLanguageBuffer(SnapshotPoint point) { Debug.Assert(CurrentLanguageBuffer != null); return GetPositionInBuffer(point, CurrentLanguageBuffer); } private SnapshotPoint? GetPositionInStandardInputBuffer(SnapshotPoint point) { Debug.Assert(StandardInputBuffer != null); return GetPositionInBuffer(point, StandardInputBuffer); } private SnapshotPoint? GetPositionInBuffer(SnapshotPoint point, ITextBuffer buffer) { return TextView.BufferGraph.MapDownToBuffer( point, PointTrackingMode.Positive, buffer, PositionAffinity.Successor); } // Mimics EditorOperations.GetWhiteSpaceForPositionAndVirtualSpace. private static string GetWhiteSpaceForVirtualSpace(int virtualSpaces, int? tabSize) { string textToInsert; if (tabSize.HasValue) { int tabSizeInt = tabSize.GetValueOrDefault(); int spacesAfterPreviousTabStop = virtualSpaces % tabSizeInt; int columnOfPreviousTabStop = virtualSpaces - spacesAfterPreviousTabStop; int requiredTabs = (columnOfPreviousTabStop + tabSizeInt - 1) / tabSizeInt; if (requiredTabs > 0) { textToInsert = new string('\t', requiredTabs) + new string(' ', spacesAfterPreviousTabStop); } else { textToInsert = new string(' ', virtualSpaces); } } else { textToInsert = new string(' ', virtualSpaces); } return textToInsert; } /// <summary>Implements <see cref="IInteractiveWindowOperations.Cancel"/>.</summary> public void Cancel() { ClearInput(); EditorOperations.MoveToEndOfDocument(false); _uncommittedInput = null; _historySearch = null; } private void ClearInput() { if (ReadingStandardInput) { StandardInputBuffer.Delete(GetStandardInputSpan()); } else { CurrentLanguageBuffer.Delete(new Span(0, CurrentLanguageBuffer.CurrentSnapshot.Length)); } } /// <summary>Implements <see cref="IInteractiveWindowOperations.HistoryPrevious"/>.</summary> public void HistoryPrevious(string search) { if (CurrentLanguageBuffer == null) { return; } var previous = _history.GetPrevious(search); if (previous != null) { if (string.IsNullOrWhiteSpace(search)) { // don't store search as an uncommitted history item StoreUncommittedInputForHistory(); } SetActiveCodeToHistory(previous); EditorOperations.MoveToEndOfDocument(false); } } /// <summary>Implements <see cref="IInteractiveWindowOperations.HistoryNext"/>.</summary> public void HistoryNext(string search) { if (CurrentLanguageBuffer == null) { return; } var next = _history.GetNext(search); if (next != null) { if (string.IsNullOrWhiteSpace(search)) { // don't store search as an uncommitted history item StoreUncommittedInputForHistory(); } SetActiveCodeToHistory(next); EditorOperations.MoveToEndOfDocument(false); } else { string code = _history.UncommittedInput; _history.UncommittedInput = null; if (!string.IsNullOrEmpty(code)) { SetActiveCode(code); EditorOperations.MoveToEndOfDocument(false); } } } /// <summary> /// Sets the active code to the specified history entry. /// </summary> /// <param name="entry"></param> private void SetActiveCodeToHistory(History.Entry entry) { SetActiveCode(entry.Text); } /// <summary> /// Sets the active code to the specified text w/o executing it. /// </summary> private void SetActiveCode(string text) { // TODO (tomat): this should be handled by the language intellisense provider, not here: var completionSession = SessionStack.TopSession; if (completionSession != null) { completionSession.Dismiss(); } using (var edit = CurrentLanguageBuffer.CreateEdit(EditOptions.None, reiteratedVersionNumber: null, editTag: null)) { edit.Replace(new Span(0, CurrentLanguageBuffer.CurrentSnapshot.Length), text); edit.Apply(); } } /// <summary>Implements <see cref="IInteractiveWindowOperations.HistorySearchNext"/>.</summary> public void HistorySearchNext() { EnsureHistorySearch(); HistoryNext(_historySearch); } /// <summary>Implements <see cref="IInteractiveWindowOperations.HistorySearchPrevious"/>.</summary> public void HistorySearchPrevious() { EnsureHistorySearch(); HistoryPrevious(_historySearch); } private void EnsureHistorySearch() { if (_historySearch == null) { _historySearch = CurrentLanguageBuffer.CurrentSnapshot.GetText(); } } private void StoreUncommittedInputForHistory() { if (_history.UncommittedInput == null) { string activeCode = GetActiveCode(); // save uncommitted input for history even if it is empty else // on the next history navigation the previous history entry would // be saved as uncommitted input, which we do not want. Uncommitted // input is to save what ever user has typed and storing empty string // when he hasn't typed anything does no harm. _history.UncommittedInput = activeCode; } } /// <summary> /// Moves to the beginning of the line. /// Implements <see cref="IInteractiveWindowOperations.Home"/>. /// </summary> public void Home(bool extendSelection) { var caret = TextView.Caret; // map the end of subject buffer line: var subjectLineEnd = TextView.BufferGraph.MapDownToFirstMatch( caret.Position.BufferPosition.GetContainingLine().End, PointTrackingMode.Positive, snapshot => snapshot.TextBuffer != _projectionBuffer, PositionAffinity.Successor).Value; ITextSnapshotLine subjectLine = subjectLineEnd.GetContainingLine(); var projectedSubjectLineStart = TextView.BufferGraph.MapUpToBuffer( subjectLine.Start, PointTrackingMode.Positive, PositionAffinity.Successor, _projectionBuffer).Value; // If the caret is already at the first non-whitespace character or the line is // entirely whitespace, move to the start of the view line. See // (EditorOperations.MoveToHome). // // If the caret is in the prompt move the caret to the beginning of the language // line. int firstNonWhiteSpace = IndexOfNonWhiteSpaceCharacter(subjectLine); SnapshotPoint moveTo; if (firstNonWhiteSpace == -1 || projectedSubjectLineStart.Position + firstNonWhiteSpace == caret.Position.BufferPosition || caret.Position.BufferPosition < projectedSubjectLineStart.Position) { moveTo = projectedSubjectLineStart; } else { moveTo = projectedSubjectLineStart + firstNonWhiteSpace; } if (extendSelection) { VirtualSnapshotPoint anchor = TextView.Selection.AnchorPoint; caret.MoveTo(moveTo); TextView.Selection.Select(anchor.TranslateTo(TextView.TextSnapshot), TextView.Caret.Position.VirtualBufferPosition); } else { TextView.Selection.Clear(); caret.MoveTo(moveTo); } caret.EnsureVisible(); } /// <summary> /// Moves to the end of the line. /// Implements <see cref="IInteractiveWindowOperations.End"/>. /// </summary> public void End(bool extendSelection) { var caret = TextView.Caret; // map the end of the subject buffer line: var subjectLineEnd = TextView.BufferGraph.MapDownToFirstMatch( caret.Position.BufferPosition.GetContainingLine().End, PointTrackingMode.Positive, snapshot => snapshot.TextBuffer != _projectionBuffer, PositionAffinity.Successor).Value; ITextSnapshotLine subjectLine = subjectLineEnd.GetContainingLine(); var moveTo = TextView.BufferGraph.MapUpToBuffer( subjectLine.End, PointTrackingMode.Positive, PositionAffinity.Successor, _projectionBuffer).Value; if (extendSelection) { VirtualSnapshotPoint anchor = TextView.Selection.AnchorPoint; caret.MoveTo(moveTo); TextView.Selection.Select(anchor.TranslateTo(TextView.TextSnapshot), TextView.Caret.Position.VirtualBufferPosition); } else { TextView.Selection.Clear(); caret.MoveTo(moveTo); } caret.EnsureVisible(); } /// <summary>Implements <see cref="IInteractiveWindowOperations.SelectAll"/>.</summary> public void SelectAll() { SnapshotSpan? span = GetContainingRegion(TextView.Caret.Position.BufferPosition); var selection = TextView.Selection; // if the span is already selected select all text in the projection buffer: if (span == null || selection.SelectedSpans.Count == 1 && selection.SelectedSpans[0] == span.Value) { var currentSnapshot = TextView.TextBuffer.CurrentSnapshot; span = new SnapshotSpan(currentSnapshot, new Span(0, currentSnapshot.Length)); } TextView.Selection.Select(span.Value, isReversed: false); } /// <summary> /// Given a point in projection buffer calculate a span that includes the point and comprises of /// subsequent projection spans forming a region, i.e. a sequence of output spans in between two subsequent submissions, /// a language input block, or standard input block. /// </summary> private SnapshotSpan? GetContainingRegion(SnapshotPoint point) { var sourceSpans = GetSourceSpans(point.Snapshot); int promptIndex = GetPromptIndexForPoint(sourceSpans, point); if (promptIndex < 0) { return null; } // Grab the span following the prompt (either language or standard input). var projectionSpan = sourceSpans[promptIndex + 1]; var inputSnapshot = projectionSpan.Snapshot; var kind = GetSpanKind(projectionSpan); Debug.Assert(kind == ReplSpanKind.Input || kind == ReplSpanKind.StandardInput); // Language input block is a projection of the entire snapshot; // std input block is a projection of a single span: SnapshotPoint inputBufferEnd = (kind == ReplSpanKind.Input) ? new SnapshotPoint(inputSnapshot, inputSnapshot.Length) : projectionSpan.End; var bufferGraph = TextView.BufferGraph; var textBuffer = TextView.TextBuffer; SnapshotPoint projectedInputBufferEnd = bufferGraph.MapUpToBuffer( inputBufferEnd, PointTrackingMode.Positive, PositionAffinity.Predecessor, textBuffer).Value; // point is between the primary prompt (including) and the last character of the corresponding language/stdin buffer: if (point <= projectedInputBufferEnd) { var projectedLanguageBufferStart = bufferGraph.MapUpToBuffer( new SnapshotPoint(inputSnapshot, 0), PointTrackingMode.Positive, PositionAffinity.Successor, textBuffer).Value; var promptProjectionSpan = sourceSpans[promptIndex]; if (point < projectedLanguageBufferStart - promptProjectionSpan.Length) { // cursor is before the first language buffer: return new SnapshotSpan(new SnapshotPoint(textBuffer.CurrentSnapshot, 0), projectedLanguageBufferStart - promptProjectionSpan.Length); } // cursor is within the language buffer: return new SnapshotSpan(projectedLanguageBufferStart, projectedInputBufferEnd); } int nextPromptIndex = -1; for (int i = promptIndex + 1; i < sourceSpans.Count; i++) { if (IsPrompt(sourceSpans[i])) { nextPromptIndex = i; break; } } // this was the last primary/stdin prompt - select the part of the projection buffer behind the end of the language/stdin buffer: if (nextPromptIndex < 0) { var currentSnapshot = textBuffer.CurrentSnapshot; return new SnapshotSpan( projectedInputBufferEnd, new SnapshotPoint(currentSnapshot, currentSnapshot.Length)); } var lastSpanBeforeNextPrompt = sourceSpans[nextPromptIndex - 1]; Debug.Assert(GetSpanKind(lastSpanBeforeNextPrompt) == ReplSpanKind.Output); // select all text in between the language buffer and the next prompt: return new SnapshotSpan( projectedInputBufferEnd, bufferGraph.MapUpToBuffer( lastSpanBeforeNextPrompt.End, PointTrackingMode.Positive, PositionAffinity.Predecessor, textBuffer).Value); } private bool OverlapsWithEditableBuffer(NormalizedSnapshotSpanCollection spans) { var editableBuffer = (ReadingStandardInput) ? StandardInputBuffer : CurrentLanguageBuffer; foreach (var span in spans) { var editableSpans = TextView.BufferGraph.MapDownToBuffer(span, SpanTrackingMode.EdgeInclusive, editableBuffer); if (editableSpans.Count > 0) { return true; } } return false; } private bool ReduceBoxSelectionToEditableBox(bool isDelete = true) { Debug.Assert(TextView.Selection.Mode == TextSelectionMode.Box); VirtualSnapshotPoint anchor = TextView.Selection.AnchorPoint; VirtualSnapshotPoint active = TextView.Selection.ActivePoint; bool result; if (active < anchor) { result = ReduceBoxSelectionToEditableBox(ref active, ref anchor, isDelete); } else { result = ReduceBoxSelectionToEditableBox(ref anchor, ref active, isDelete); } TextView.Selection.Select(anchor, active); TextView.Caret.MoveTo(active); return result; } private bool ReduceBoxSelectionToEditableBox(ref VirtualSnapshotPoint selectionTop, ref VirtualSnapshotPoint selectionBottom, bool isDelete) { int selectionTopColumn, selectionBottomColumn; ITextSnapshotLine selectionTopLine, selectionBottomLine; selectionTop.GetLineAndColumn(out selectionTopLine, out selectionTopColumn); selectionBottom.GetLineAndColumn(out selectionBottomLine, out selectionBottomColumn); int selectionLeftColumn, selectionRightColumn; bool horizontallyReversed = selectionTopColumn > selectionBottomColumn; if (horizontallyReversed) { // bottom-left <-> top-right selectionLeftColumn = selectionBottomColumn; selectionRightColumn = selectionTopColumn; } else { // top-left <-> bottom-right selectionLeftColumn = selectionTopColumn; selectionRightColumn = selectionBottomColumn; } var selectionTopLeft = new VirtualSnapshotPoint(selectionTopLine, selectionLeftColumn); var selectionBottomRight = new VirtualSnapshotPoint(selectionBottomLine, selectionRightColumn); SnapshotPoint editable = GetClosestEditablePoint(selectionTopLeft.Position); int editableColumn; ITextSnapshotLine editableLine; editable.GetLineAndColumn(out editableLine, out editableColumn); Debug.Assert(selectionLeftColumn <= selectionRightColumn); Debug.Assert(selectionTopLine.LineNumber <= selectionBottomLine.LineNumber); if (editable > selectionBottomRight.Position) { // entirely within readonly output region: return false; } int minPromptLength, maxPromptLength; MeasurePrompts(editableLine.LineNumber, selectionBottomLine.LineNumber + 1, out minPromptLength, out maxPromptLength); bool result = true; if (isDelete) { if (selectionLeftColumn > maxPromptLength || maxPromptLength == minPromptLength) { selectionTopLine = editableLine; selectionLeftColumn = Math.Max(selectionLeftColumn, maxPromptLength); } } else { if (selectionRightColumn < minPromptLength) { // entirely within readonly prompt region: result = false; } else if (maxPromptLength > selectionRightColumn) { selectionTopLine = editableLine; selectionLeftColumn = maxPromptLength; selectionRightColumn = maxPromptLength; } else { selectionTopLine = editableLine; selectionLeftColumn = Math.Max(maxPromptLength, selectionLeftColumn); } } if (horizontallyReversed) { // bottom-left <-> top-right selectionTop = new VirtualSnapshotPoint(selectionTopLine, selectionRightColumn); selectionBottom = new VirtualSnapshotPoint(selectionBottomLine, selectionLeftColumn); } else { // top-left <-> bottom-right selectionTop = new VirtualSnapshotPoint(selectionTopLine, selectionLeftColumn); selectionBottom = new VirtualSnapshotPoint(selectionBottomLine, selectionRightColumn); } return result; } /// <summary> /// Returns the lengths of the longest and shortest prompts within the specified range of lines of the current submission buffer. /// </summary> private void MeasurePrompts(int startLine, int endLine, out int minPromptLength, out int maxPromptLength) { Debug.Assert(endLine > startLine); var projectionSnapshot = _projectionBuffer.CurrentSnapshot; var sourceSpans = projectionSnapshot.GetSourceSpans(); var promptSpanIndex = GetProjectionSpanIndexFromEditableBufferPosition(projectionSnapshot, sourceSpans.Count, startLine) - 1; var promptSpan = sourceSpans[promptSpanIndex]; Debug.Assert(IsPrompt(promptSpan)); minPromptLength = maxPromptLength = promptSpan.Length; } /// <summary>Implements <see cref="IInteractiveWindowOperations.Cut"/>.</summary> public void Cut() { if (!TextView.Selection.IsEmpty) { if (CutOrDeleteSelection(isCut: true)) { MoveCaretToClosestEditableBuffer(); } return; } var caretPosition = TextView.Caret.Position.BufferPosition; // don't cut and move caret if it's in readonly buffer (except in active prompt) if (MapToEditableBuffer(caretPosition) != null || IsInActivePrompt(caretPosition)) { CutOrDeleteCurrentLine(isCut: true); Home(false); } } /// <summary>Implements <see cref="IInteractiveWindowOperations.Delete"/>.</summary> public bool Delete() { _historySearch = null; bool handled = false; if (!TextView.Selection.IsEmpty) { if (CutOrDeleteSelection(isCut: false)) { MoveCaretToClosestEditableBuffer(); handled = true; } } else if (IsInActivePrompt(TextView.Caret.Position.BufferPosition)) { MoveCaretToClosestEditableBuffer(); } return handled; } /// <summary>Implements <see cref="IInteractiveWindowOperations2.DeleteLine"/>.</summary> public void DeleteLine() { _historySearch = null; CutOrDeleteLine(isCut: false); } /// <summary>Implements <see cref="IInteractiveWindowOperations2.CutLine"/>.</summary> public void CutLine() { _historySearch = null; CutOrDeleteLine(isCut: true); } /// <summary>Cut/Delete all selected lines, or the current line if no selection. </summary> private void CutOrDeleteLine(bool isCut) { if (TextView.Selection.IsEmpty) { var caret = TextView.Caret; var position = caret.Position.BufferPosition; if (MapToEditableBuffer(position) != null || IsInActivePrompt(position)) { CutOrDeleteCurrentLine(isCut); Home(extendSelection: false); } } else { var selection = TextView.Selection; var projectionSpans = TextView.BufferGraph.MapUpToSnapshot(new SnapshotSpan(selection.Start.Position.GetContainingLine().Start, selection.End.Position.GetContainingLine().EndIncludingLineBreak), SpanTrackingMode.EdgeInclusive, _projectionBuffer.CurrentSnapshot); if (OverlapsWithEditableBuffer(projectionSpans)) { CutOrDelete(projectionSpans, isCut); selection.Clear(); MoveCaretToClosestEditableBuffer(); TextView.Caret.EnsureVisible(); } } } private void CutOrDeleteCurrentLine(bool isCut) { ITextSnapshotLine line; int column; TextView.Caret.Position.VirtualBufferPosition.GetLineAndColumn(out line, out column); CutOrDelete(new[] { line.ExtentIncludingLineBreak }, isCut); TextView.Caret.MoveTo(new VirtualSnapshotPoint(TextView.TextBuffer.CurrentSnapshot.GetLineFromLineNumber(line.LineNumber), column)); } /// <summary> /// If any of currently selected text is editable, then deletes editable selection, optionally saves it /// to the clipboard. Otherwise do nothing (and preserve selection). /// </summary> private bool CutOrDeleteSelection(bool isCut) { var selection = TextView.Selection; if (!selection.IsEmpty) { // Even though `OverlapsWithEditableBuffer` and `CutOrDelete` is sufficient to // delete editable selection, we still need to handle box selection // differently to move caret to appropiate location after deletion. bool isEditable = selection.Mode == TextSelectionMode.Stream ? OverlapsWithEditableBuffer(selection.SelectedSpans) : ReduceBoxSelectionToEditableBox(); if (isEditable) { CutOrDelete(selection.SelectedSpans, isCut); // if the selection spans over prompts the prompts remain selected, so clear manually: selection.Clear(); return true; } } return false; } private void CutOrDelete(IEnumerable<SnapshotSpan> projectionSpans, bool isCut) { Debug.Assert(CurrentLanguageBuffer != null); StringBuilder deletedText = null; // split into multiple deletes that only affect the language/input buffer: ITextBuffer affectedBuffer = (ReadingStandardInput) ? StandardInputBuffer : CurrentLanguageBuffer; using (var edit = affectedBuffer.CreateEdit()) { foreach (var projectionSpan in projectionSpans) { var spans = TextView.BufferGraph.MapDownToBuffer(projectionSpan, SpanTrackingMode.EdgeInclusive, affectedBuffer); foreach (var span in spans) { if (isCut) { if (deletedText == null) { deletedText = new StringBuilder(); } deletedText.Append(span.GetText()); } edit.Delete(span); } } edit.Apply(); } // copy the deleted text to the clipboard: if (deletedText != null) { var data = new DataObject(); if (TextView.Selection.Mode == TextSelectionMode.Box) { data.SetData(BoxSelectionCutCopyTag, new object()); } data.SetText(deletedText.ToString()); _window.InteractiveWindowClipboard.SetDataObject(data, true); } } /// <summary>Implements <see cref="IInteractiveWindowOperations2.Copy"/>.</summary> public void Copy() { CopySelection(); } /// <summary> /// Copy the entire selection to the clipboard for RTF format and /// copy the selection minus any prompt text for other formats. /// That allows paste into code editors of just the code and /// paste of the entire content for editors that support RTF. /// </summary> private void CopySelection() { var spans = GetSelectionSpans(TextView); var data = Copy(spans); _window.InteractiveWindowClipboard.SetDataObject(data, true); } private static NormalizedSnapshotSpanCollection GetSelectionSpans(ITextView textView) { var selection = textView.Selection; if (selection.IsEmpty) { // Use the current line as the selection. var snapshotLine = textView.Caret.Position.VirtualBufferPosition.Position.GetContainingLine(); var span = new SnapshotSpan(snapshotLine.Start, snapshotLine.LengthIncludingLineBreak); return new NormalizedSnapshotSpanCollection(span); } return selection.SelectedSpans; } private DataObject Copy(NormalizedSnapshotSpanCollection spans) { var text = GetText(spans); var blocks = GetTextBlocks(spans); string rtf = null; try { rtf = GenerateRtf(spans); } catch (OperationCanceledException) { // Ignore cancellation when doing a copy. The user may not even want RTF text so preventing the normal text from being copied would be overkill. } var data = new DataObject(); data.SetData(DataFormats.StringFormat, text); data.SetData(DataFormats.Text, text); data.SetData(DataFormats.UnicodeText, text); if (rtf != null) { data.SetData(DataFormats.Rtf, rtf); } data.SetData(ClipboardFormat, blocks); return data; } private string GenerateRtf(NormalizedSnapshotSpanCollection spans) { // This behavior is consistent with VS editor. // Don't generate RTF for large spans (since it is expensive and probably not wanted). int length = spans.Sum((span) => span.Length); if (length < 1000000) { using (var dialog = _waitIndicator.StartWait(InteractiveWindowResources.WaitTitle, InteractiveWindowResources.WaitMessage, allowCancel: true)) { return _rtfBuilderService.GenerateRtf(spans, dialog.CancellationToken); } } else { return null; } } /// <summary> /// Get the text of the given spans as a simple concatenated string. /// </summary> private static string GetText(NormalizedSnapshotSpanCollection spans) { var builder = new StringBuilder(); foreach (var span in spans) { builder.Append(span.GetText()); } return builder.ToString(); } /// <summary> /// Get the text of the given spans as a serialized BufferBlock[]. /// </summary> private string GetTextBlocks(NormalizedSnapshotSpanCollection spans) { var blocks = new List<BufferBlock>(); foreach (var span in spans) { GetTextBlocks(blocks, span); } return BufferBlock.Serialize(blocks.ToArray()); } private void GetTextBlocks(List<BufferBlock> blocks, SnapshotSpan span) { // Find the range of source spans that cover the span. var sourceSpans = GetSourceSpans(span.Snapshot); int n = sourceSpans.Count; int index = GetSourceSpanIndex(sourceSpans, span.Start); if (index == n) { index--; } for (; index < n; index++) { var sourceSpan = sourceSpans[index]; if (sourceSpan.IsEmpty) { continue; } var sourceSnapshot = sourceSpan.Snapshot; var mappedSpans = TextView.BufferGraph.MapDownToBuffer(span, SpanTrackingMode.EdgeExclusive, sourceSnapshot.TextBuffer); bool added = false; foreach (var mappedSpan in mappedSpans) { var intersection = sourceSpan.Span.Intersection(mappedSpan); if (intersection.HasValue && !intersection.Value.IsEmpty) { var kind = GetSpanKind(sourceSpan); if (kind == ReplSpanKind.LineBreak) { kind = ReplSpanKind.Output; } var content = sourceSnapshot.GetText(intersection.Value); blocks.Add(new BufferBlock(kind, content)); added = true; } } if (!added) { break; } } } /// <summary>Implements <see cref="IInteractiveWindowOperations.Backspace"/>.</summary> public bool Backspace() { bool handled = false; if (!TextView.Selection.IsEmpty) { if (TextView.Selection.Mode == TextSelectionMode.Stream || ReduceBoxSelectionToEditableBox()) { if (CutOrDeleteSelection(isCut: false)) { MoveCaretToClosestEditableBuffer(); handled = true; } } } else if (TextView.Caret.Position.VirtualSpaces == 0) { if (IsInActivePrompt(TextView.Caret.Position.BufferPosition)) { MoveCaretToClosestEditableBuffer(); } if (DeletePreviousCharacter()) { handled = true; } } return handled; } /// <summary> /// Deletes characters preceding the current caret position in the current language buffer. /// /// Returns true if the previous character was deleted /// </summary> private bool DeletePreviousCharacter() { SnapshotPoint? point = MapToEditableBuffer(TextView.Caret.Position.BufferPosition); // We are not in an editable buffer, or we are at the start of the buffer, nothing to delete. if (point == null || point.Value == 0) { return false; } var line = point.Value.GetContainingLine(); int characterSize; if (line.Start.Position == point.Value.Position) { Debug.Assert(line.LineNumber != 0); characterSize = line.Snapshot.GetLineFromLineNumber(line.LineNumber - 1).LineBreakLength; } else { characterSize = 1; } point.Value.Snapshot.TextBuffer.Delete(new Span(point.Value.Position - characterSize, characterSize)); ScrollToCaret(); return true; } /// <summary> /// Maps point to the current language buffer or standard input buffer. /// </summary> private SnapshotPoint? MapToEditableBuffer(SnapshotPoint projectionPoint) { SnapshotPoint? result = null; if (CurrentLanguageBuffer != null) { result = GetPositionInLanguageBuffer(projectionPoint); } if (result != null) { return result; } if (StandardInputBuffer != null) { result = GetPositionInStandardInputBuffer(projectionPoint); } return result; } /// <summary>Implements <see cref="IInteractiveWindowOperations.TrySubmitStandardInput"/>.</summary> public bool TrySubmitStandardInput() { _historySearch = null; if (ReadingStandardInput) { if (InStandardInputRegion(TextView.Caret.Position.BufferPosition)) { SubmitStandardInput(); } return true; } return false; } private void SubmitStandardInput() { AppendLineNoPromptInjection(StandardInputBuffer); var inputSpan = new SnapshotSpan(StandardInputBuffer.CurrentSnapshot, GetStandardInputSpan()); _history.Add(inputSpan); SetStandardInputValue(inputSpan); MakeStandardInputReadonly(); // Subsequent input should appear after the input span we just finished. NewOutputBuffer(); if (State == State.WaitingForInputAndReadingStandardInput) { PrepareForInput(); // Will update State. } else { State = GetStateBeforeReadingStandardInput(State); } } private bool InStandardInputRegion(SnapshotPoint point) { if (!ReadingStandardInput) { return false; } var standardInputPoint = GetPositionInStandardInputBuffer(point); if (!standardInputPoint.HasValue) { return false; } var standardInputPosition = standardInputPoint.GetValueOrDefault().Position; var standardInputSpan = GetStandardInputSpan(); return standardInputSpan.Contains(standardInputPosition) || standardInputSpan.End == standardInputPosition; } /// <summary> /// Add a zero-width tracking span at the end of the projection buffer mapping to the end of the standard input buffer. /// </summary> private void AddStandardInputSpan() { var promptSpan = CreateStandardInputPrompt(); var currentSnapshot = StandardInputBuffer.CurrentSnapshot; var inputSpan = new CustomTrackingSpan( currentSnapshot, new Span(currentSnapshot.Length, 0), canAppend: true); AppendProjectionSpans(promptSpan, inputSpan); } /// <summary>Implements <see cref="IInteractiveWindowOperations.BreakLine"/>.</summary> public bool BreakLine() { return HandlePostServicesReturn(false); } /// <summary>Implements <see cref="IInteractiveWindowOperations.Return"/>.</summary> public bool Return() { _historySearch = null; return HandlePostServicesReturn(true); } private bool HandlePostServicesReturn(bool trySubmit) { if (CurrentLanguageBuffer == null) { return false; } if (!TextView.Selection.IsEmpty) { if (CutOrDeleteSelection(isCut: false)) { MoveCaretToClosestEditableBuffer(); } else { return false; } } else if (IsInActivePrompt(TextView.Caret.Position.BufferPosition)) { MoveCaretToClosestEditableBuffer(); } // handle "RETURN" command that is not handled by either editor or service var langCaret = GetPositionInLanguageBuffer(TextView.Caret.Position.BufferPosition); if (langCaret != null) { int caretPosition = langCaret.Value.Position; // note that caret might be located in virtual space behind the current buffer end: if (trySubmit && caretPosition >= CurrentLanguageBuffer.CurrentSnapshot.Length && CanExecuteActiveCode()) { var dummy = SubmitAsync(); } else { // insert new line (triggers secondary prompt injection in buffer changed event): CurrentLanguageBuffer.Insert(caretPosition, _lineBreakString); IndentCurrentLine(TextView.Caret.Position.BufferPosition); ScrollToCaret(); } return true; } return false; } private bool CanExecuteActiveCode() { Debug.Assert(CurrentLanguageBuffer != null); var input = GetActiveCode(); if (string.IsNullOrWhiteSpace(input)) { // Always allow "execution" of a blank line. // This will just close the current prompt and start a new one return true; } // Ignore any whitespace past the insertion point when determining // whether or not we're at the end of the input var pt = GetActiveCodeInsertionPosition(); var isEnd = (pt == input.Length) || (pt >= 0 && input.Substring(pt).Trim().Length == 0); if (!isEnd) { return false; } // If this throws, VS shows a dialog. return Evaluator.CanExecuteCode(input); } /// <summary> /// Returns the insertion point relative to the current language buffer. /// </summary> private int GetActiveCodeInsertionPosition() { Debug.Assert(CurrentLanguageBuffer != null); var langPoint = TextView.BufferGraph.MapDownToBuffer( new SnapshotPoint( _projectionBuffer.CurrentSnapshot, TextView.Caret.Position.BufferPosition.Position), PointTrackingMode.Positive, CurrentLanguageBuffer, PositionAffinity.Predecessor); if (langPoint != null) { return langPoint.Value; } return CurrentLanguageBuffer.CurrentSnapshot.Length; } private object CreateStandardInputPrompt() { return string.Empty; } private object CreatePrimaryPrompt() { return Evaluator.GetPrompt(); } private object CreateSecondaryPrompt() { // TODO (crwilcox) format prompt used to get a blank here but now gets "> " from get prompt. return Evaluator.GetPrompt(); } private ReplSpanKind GetSpanKind(SnapshotSpan span) { var textBuffer = span.Snapshot.TextBuffer; if (textBuffer == OutputBuffer) { return ReplSpanKind.Output; } if (textBuffer == StandardInputBuffer) { return ReplSpanKind.StandardInput; } if (textBuffer.ContentType == _inertType) { return (span.Length == _lineBreakString.Length) && string.Equals(span.GetText(), _lineBreakString) ? ReplSpanKind.LineBreak : ReplSpanKind.Prompt; } return ReplSpanKind.Input; } #region Output /// <summary>Implements <see cref="IInteractiveWindow.Write(string)"/>.</summary> public Span Write(string text) { int result = _buffer.Write(text); return new Span(result, (text != null ? text.Length : 0)); } /// <summary>Implements <see cref="IInteractiveWindow.WriteLine(string)"/>.</summary> public Span WriteLine(string text) { int result = _buffer.Write(text); _buffer.Write(_lineBreakString); return new Span(result, (text != null ? text.Length : 0) + _lineBreakString.Length); } /// <summary>Implements <see cref="IInteractiveWindow.WriteError(string)"/>.</summary> public Span WriteError(string text) { int result = _buffer.Write(text); var res = new Span(result, (text != null ? text.Length : 0)); ErrorOutputWriter.Spans.Add(res); return res; } /// <summary>Implements <see cref="IInteractiveWindow.WriteErrorLine(string)"/>.</summary> public Span WriteErrorLine(string text) { int result = _buffer.Write(text); _buffer.Write(_lineBreakString); var res = new Span(result, (text != null ? text.Length : 0) + _lineBreakString.Length); ErrorOutputWriter.Spans.Add(res); return res; } /// <summary>Implements <see cref="IInteractiveWindow.Write(UIElement)"/>.</summary> public void Write(UIElement element) { if (element == null) { return; } _buffer.Flush(); InlineAdornmentProvider.AddInlineAdornment(TextView, element, OnAdornmentLoaded); _adornmentToMinimize = true; WriteLine(string.Empty); WriteLine(string.Empty); } private void OnAdornmentLoaded(object source, EventArgs e) { // Make sure the caret line is rendered DoEvents(); TextView.Caret.EnsureVisible(); } #endregion void IDisposable.Dispose() { if (_buffer != null) { _buffer.Dispose(); } } } } }
oocx/roslyn
src/InteractiveWindow/Editor/InteractiveWindow.UIThreadOnly.cs
C#
apache-2.0
126,626
/* * Copyright 2021 HM Revenue & Customs * * 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 connectors import config.ApplicationConfig import javax.inject.Inject import models.deregister.{DeRegisterSubscriptionRequest, DeRegisterSubscriptionResponse} import models.payments._ import models.registrationdetails.RegistrationDetails import models.withdrawal.{WithdrawSubscriptionRequest, WithdrawSubscriptionResponse} import models.{AmendVariationRenewalResponse, _} import play.api.Logging import play.api.libs.json.{Json, Writes} import uk.gov.hmrc.http._ import uk.gov.hmrc.http.HttpReads.Implicits._ import scala.concurrent.{ExecutionContext, Future} class AmlsConnector @Inject()(val http: HttpClient, val appConfig: ApplicationConfig) extends Logging { private[connectors] val url: String = appConfig.subscriptionUrl private[connectors] val registrationUrl: String = s"${appConfig.amlsUrl}/amls/registration" private[connectors] val paymentUrl: String= s"${appConfig.amlsUrl}/amls/payment" def subscribe(subscriptionRequest: SubscriptionRequest, safeId: String, accountTypeId: (String, String)) (implicit headerCarrier: HeaderCarrier, ec: ExecutionContext, reqW: Writes[SubscriptionRequest], resW: Writes[SubscriptionResponse]): Future[SubscriptionResponse] = { val (accountType, accountId) = accountTypeId val postUrl = s"$url/$accountType/$accountId/$safeId" val prefix = "[AmlsConnector][subscribe]" // $COVERAGE-OFF$ logger.debug(s"$prefix - Request Body: ${Json.toJson(subscriptionRequest)}") // $COVERAGE-ON$ http.POST[SubscriptionRequest, SubscriptionResponse](postUrl, subscriptionRequest) map { response => // $COVERAGE-OFF$ logger.debug(s"$prefix - Response Body: ${Json.toJson(response)}") // $COVERAGE-ON$ response } } def status(amlsRegistrationNumber: String, accountTypeId: (String, String)) (implicit headerCarrier: HeaderCarrier, ec: ExecutionContext, reqW: Writes[ReadStatusResponse]): Future[ReadStatusResponse] = { val (accountType, accountId) = accountTypeId val getUrl = s"$url/$accountType/$accountId/$amlsRegistrationNumber/status" val prefix = "[AmlsConnector][status]" // $COVERAGE-OFF$ logger.debug(s"$prefix - Request : $amlsRegistrationNumber") // $COVERAGE-ON$ http.GET[ReadStatusResponse](getUrl) map { response => // $COVERAGE-OFF$ logger.debug(s"$prefix - Response Body: ${Json.toJson(response)}") // $COVERAGE-ON$ response } } def view(amlsRegistrationNumber: String, accountTypeId: (String, String)) (implicit headerCarrier: HeaderCarrier, ec: ExecutionContext, reqW: Writes[ViewResponse]): Future[ViewResponse] = { val (accountType, accountId) = accountTypeId val getUrl = s"$url/$accountType/$accountId/$amlsRegistrationNumber" val prefix = "[AmlsConnector][view]" // $COVERAGE-OFF$ logger.debug(s"$prefix - Request : $amlsRegistrationNumber") // $COVERAGE-ON$ http.GET[ViewResponse](getUrl) map { response => // $COVERAGE-OFF$ logger.debug(s"$prefix - Response Body: ${Json.toJson(response)}") // $COVERAGE-ON$ response } } def update(updateRequest: SubscriptionRequest, amlsRegistrationNumber: String, accountTypeId: (String, String)) (implicit headerCarrier: HeaderCarrier, ec: ExecutionContext, reqW: Writes[SubscriptionRequest], resW: Writes[AmendVariationRenewalResponse]): Future[AmendVariationRenewalResponse] = { val (accountType, accountId) = accountTypeId val postUrl = s"$url/$accountType/$accountId/$amlsRegistrationNumber/update" val prefix = "[AmlsConnector][update]" // $COVERAGE-OFF$ logger.debug(s"$prefix - Request Body: ${Json.toJson(updateRequest)}") // $COVERAGE-ON$ http.POST[SubscriptionRequest, AmendVariationRenewalResponse](postUrl, updateRequest) map { response => // $COVERAGE-OFF$ logger.debug(s"$prefix - Response Body: ${Json.toJson(response)}") // $COVERAGE-ON$ response } } def variation(updateRequest: SubscriptionRequest, amlsRegistrationNumber: String, accountTypeId: (String, String)) (implicit headerCarrier: HeaderCarrier, ec: ExecutionContext, reqW: Writes[SubscriptionRequest], resW: Writes[AmendVariationRenewalResponse]): Future[AmendVariationRenewalResponse] = { val (accountType, accountId) = accountTypeId val postUrl = s"$url/$accountType/$accountId/$amlsRegistrationNumber/variation" val prefix = "[AmlsConnector][variation]" // $COVERAGE-OFF$ logger.debug(s"$prefix - Request Body: ${Json.toJson(updateRequest)}") // $COVERAGE-ON$ http.POST[SubscriptionRequest, AmendVariationRenewalResponse](postUrl, updateRequest) map { response => // $COVERAGE-OFF$ logger.debug(s"$prefix - Response Body: ${Json.toJson(response)}") // $COVERAGE-ON$ response } } def renewal(subscriptionRequest: SubscriptionRequest, amlsRegistrationNumber: String, accountTypeId: (String, String)) (implicit headerCarrier: HeaderCarrier, ec: ExecutionContext): Future[AmendVariationRenewalResponse] = { val (accountType, accountId) = accountTypeId val postUrl = s"$url/$accountType/$accountId/$amlsRegistrationNumber/renewal" // $COVERAGE-OFF$ val log = (msg: String) => logger.debug(s"[AmlsConnector][renewal] $msg") log(s"Request body: ${Json.toJson(subscriptionRequest)}") // $COVERAGE-ON$ http.POST[SubscriptionRequest, AmendVariationRenewalResponse](postUrl, subscriptionRequest) map { response => // $COVERAGE-OFF$ log(s"Response body: ${Json.toJson(response)}") // $COVERAGE-ON$ response } } def renewalAmendment(subscriptionRequest: SubscriptionRequest, amlsRegistrationNumber: String, accountTypeId: (String, String)) (implicit headerCarrier: HeaderCarrier, ec: ExecutionContext): Future[AmendVariationRenewalResponse] = { val (accountType, accountId) = accountTypeId val postUrl = s"$url/$accountType/$accountId/$amlsRegistrationNumber/renewalAmendment" // $COVERAGE-OFF$ val log = (msg: String) => logger.debug(s"[AmlsConnector][renewalAmendment] $msg") log(s"Request body: ${Json.toJson(subscriptionRequest)}") // $COVERAGE-ON$ http.POST[SubscriptionRequest, AmendVariationRenewalResponse](postUrl, subscriptionRequest) map { response => // $COVERAGE-OFF$ log(s"Response body: ${Json.toJson(response)}") // $COVERAGE-ON$ response } } def withdraw(amlsRegistrationNumber: String, request: WithdrawSubscriptionRequest, accountTypeId: (String, String)) (implicit hc: HeaderCarrier, ec: ExecutionContext): Future[WithdrawSubscriptionResponse] = { val (accountType, accountId) = accountTypeId val postUrl = s"$url/$accountType/$accountId/$amlsRegistrationNumber/withdrawal" http.POST[WithdrawSubscriptionRequest, WithdrawSubscriptionResponse](postUrl, request) } def deregister(amlsRegistrationNumber: String, request: DeRegisterSubscriptionRequest, accountTypeId: (String, String)) (implicit hc: HeaderCarrier, ec: ExecutionContext): Future[DeRegisterSubscriptionResponse] = { val (accountType, accountId) = accountTypeId val postUrl = s"$url/$accountType/$accountId/$amlsRegistrationNumber/deregistration" http.POST[DeRegisterSubscriptionRequest, DeRegisterSubscriptionResponse](postUrl, request) } def savePayment(paymentId: String, amlsRefNo: String, safeId: String, accountTypeId: (String, String)) (implicit hc: HeaderCarrier, ec: ExecutionContext): Future[HttpResponse] = { val (accountType, accountId) = accountTypeId val postUrl = s"$paymentUrl/$accountType/$accountId/$amlsRefNo/$safeId" // $COVERAGE-OFF$ logger.debug(s"[AmlsConnector][savePayment]: Request to $postUrl with paymentId $paymentId") // $COVERAGE-ON$ http.POSTString[HttpResponse](postUrl, paymentId) } def getPaymentByPaymentReference(paymentReference: String, accountTypeId: (String, String)) (implicit hc: HeaderCarrier, ec: ExecutionContext): Future[Option[Payment]] = { val (accountType, accountId) = accountTypeId val getUrl = s"$paymentUrl/$accountType/$accountId/payref/$paymentReference" // $COVERAGE-OFF$ logger.debug(s"[AmlsConnector][getPaymentByPaymentReference]: Request to $getUrl with $paymentReference") // $COVERAGE-ON$ http.GET[Payment](getUrl) map { result => Some(result) } recover { case _: NotFoundException => None } } def getPaymentByAmlsReference(amlsRef: String, accountTypeId: (String, String)) (implicit hc: HeaderCarrier, ec: ExecutionContext): Future[Option[Payment]] = { val (accountType, accountId) = accountTypeId val getUrl = s"$paymentUrl/$accountType/$accountId/amlsref/$amlsRef" // $COVERAGE-OFF$ logger.debug(s"[AmlsConnector][getPaymentByAmlsReference]: Request to $getUrl with $amlsRef") // $COVERAGE-ON$ http.GET[Payment](getUrl) map { result => Some(result) } recover { case _: NotFoundException => None } } def refreshPaymentStatus(paymentReference: String, accountTypeId: (String, String)) (implicit hc: HeaderCarrier, ec: ExecutionContext): Future[PaymentStatusResult] = { val (accountType, accountId) = accountTypeId val putUrl = s"$paymentUrl/$accountType/$accountId/refreshstatus" // $COVERAGE-OFF$ logger.debug(s"[AmlsConnector][refreshPaymentStatus]: Request to $putUrl with $paymentReference") // $COVERAGE-ON$ http.PUT[RefreshPaymentStatusRequest, PaymentStatusResult](putUrl, RefreshPaymentStatusRequest(paymentReference)) } def registrationDetails(accountTypeId: (String, String), safeId: String)(implicit hc: HeaderCarrier, ec: ExecutionContext): Future[RegistrationDetails] = { val getUrl = s"$registrationUrl/${accountTypeId._1}/${accountTypeId._2}/details/$safeId" http.GET[RegistrationDetails](getUrl) } def updateBacsStatus(accountTypeId: (String, String), ref: String, request: UpdateBacsRequest)(implicit ec: ExecutionContext, hc: HeaderCarrier): Future[HttpResponse] = { val putUrl = s"$paymentUrl/${accountTypeId._1}/${accountTypeId._2}/$ref/bacs" http.PUT[UpdateBacsRequest, HttpResponse](putUrl, request) } def createBacsPayment(accountTypeId: (String, String), request: CreateBacsPaymentRequest)(implicit ec: ExecutionContext, hc: HeaderCarrier): Future[Payment] = { val postUrl = s"$paymentUrl/${accountTypeId._1}/${accountTypeId._2}/bacs" http.POST[CreateBacsPaymentRequest, Payment](postUrl, request) } }
hmrc/amls-frontend
app/connectors/AmlsConnector.scala
Scala
apache-2.0
11,388
package tailer import ( "path/filepath" "github.com/docker/infrakit/pkg/discovery" "github.com/docker/infrakit/pkg/launch/inproc" logutil "github.com/docker/infrakit/pkg/log" "github.com/docker/infrakit/pkg/plugin" "github.com/docker/infrakit/pkg/plugin/event/tailer" metadata_plugin "github.com/docker/infrakit/pkg/plugin/metadata" "github.com/docker/infrakit/pkg/run" "github.com/docker/infrakit/pkg/run/local" "github.com/docker/infrakit/pkg/types" ) const ( // Kind is the canonical name of the plugin for starting up, etc. Kind = "tailer" // EnvPath is the environment variable to set to tail when no additional configs are used. EnvPath = "INFRAKIT_TAILER_PATH" ) var ( log = logutil.New("module", "run/v0/tailer") ) func init() { inproc.Register(Kind, Run, DefaultOptions) } // DefaultOptions return an Options with default values filled in. var DefaultOptions = tailer.Options{ tailer.Rule{ Path: local.Getenv(EnvPath, filepath.Join(local.Getenv("PWD", ""), "test.log")), MustExist: false, }, } // Run runs the plugin, blocking the current thread. Error is returned immediately // if the plugin cannot be started. func Run(plugins func() discovery.Plugins, name plugin.Name, config *types.Any) (transport plugin.Transport, impls map[run.PluginCode]interface{}, onStop func(), err error) { options := DefaultOptions err = config.Decode(&options) if err != nil { return } if len(options) == 0 { options = DefaultOptions } var events *tailer.Tailer events, err = tailer.NewPlugin(options) if err != nil { return } transport.Name = name impls = map[run.PluginCode]interface{}{ run.Metadata: metadata_plugin.NewPluginFromData(events.Data()), run.Event: events, } onStop = func() { events.Stop() } return }
FrenchBen/infrakit
pkg/run/v0/tailer/tailer.go
GO
apache-2.0
1,777
<!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_66) on Mon Dec 14 16:02:04 CST 2015 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Uses of Class play.data.validation.MatchCheck (Play! API)</title> <meta name="date" content="2015-12-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="Uses of Class play.data.validation.MatchCheck (Play! 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="../../../../play/data/validation/MatchCheck.html" title="class in play.data.validation">Class</a></li> <li class="navBarCell1Rev">Use</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> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../index.html?play/data/validation/class-use/MatchCheck.html" target="_top">Frames</a></li> <li><a href="MatchCheck.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 play.data.validation.MatchCheck" class="title">Uses of Class<br>play.data.validation.MatchCheck</h2> </div> <div class="classUseContainer">No usage of play.data.validation.MatchCheck</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="../../../../play/data/validation/MatchCheck.html" title="class in play.data.validation">Class</a></li> <li class="navBarCell1Rev">Use</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> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../index.html?play/data/validation/class-use/MatchCheck.html" target="_top">Frames</a></li> <li><a href="MatchCheck.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><a href=http://guillaume.bort.fr>Guillaume Bort</a> &amp; <a href=http://www.zenexity.fr>zenexity</a> - Distributed under <a href=http://www.apache.org/licenses/LICENSE-2.0.html>Apache 2 licence</a>, without any warrantly</small></p> </body> </html>
play1-maven-plugin/play1-maven-plugin.github.io
external-apidocs/com/google/code/maven-play-plugin/org/playframework/play/1.3.3/play/data/validation/class-use/MatchCheck.html
HTML
apache-2.0
4,607
using System.Linq; using Graphite.Core; using Graphite.Core.Contracts.Data; using Graphite.Core.Domain; using NHibernate.Linq; namespace Graphite.Data.Repositories{ public class UserRepository : LinqRepository<User>, IUserRepository{ public User GetUser(string username) { return Session.Linq<User>().SingleOrDefault(m => m.Username == username); } public User GetUserByEmail(string email) { return Session.Linq<User>().SingleOrDefault(m => m.Email == email); } } }
chrisnicola/Graphite
app/Graphite.Data/Repositories/UserRepository.cs
C#
apache-2.0
486
# Stigmidium leucophlebiae Cl. Roux & Triebel, 1994 SPECIES #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in Bull. Soc. linn. Provence 45: 495 (1994) #### Original name Stigmidium leucophlebiae Cl. Roux & Triebel, 1994 ### Remarks null
mdoering/backbone
life/Fungi/Ascomycota/Dothideomycetes/Capnodiales/Mycosphaerellaceae/Stigmidium/Stigmidium leucophlebiae/README.md
Markdown
apache-2.0
288
using System; using BEPUphysics.Entities; using BEPUutilities; namespace BEPUphysics.Constraints.TwoEntity.Motors { /// <summary> /// Constrains anchors on two entities to move relative to each other on a line. /// </summary> public class LinearAxisMotor : Motor, I1DImpulseConstraintWithError, I1DJacobianConstraint { private readonly MotorSettings1D settings; private float accumulatedImpulse; private float biasVelocity; private Vector3 jAngularA, jAngularB; private Vector3 jLinearA, jLinearB; private Vector3 localAnchorA; private Vector3 localAnchorB; private float massMatrix; private float error; private Vector3 localAxis; private Vector3 worldAxis; private Vector3 rA; //Jacobian entry for entity A. private Vector3 worldAnchorA; private Vector3 worldAnchorB; private Vector3 worldOffsetA, worldOffsetB; /// <summary> /// Constrains anchors on two entities to move relative to each other on a line. /// To finish the initialization, specify the connections (ConnectionA and ConnectionB) /// as well as the AnchorA, AnchorB and the Axis (or their entity-local versions). /// This constructor sets the constraint's IsActive property to false by default. /// </summary> public LinearAxisMotor() { settings = new MotorSettings1D(this); IsActive = false; } /// <summary> /// Constrains anchors on two entities to move relative to each other on a line. /// </summary> /// <param name="connectionA">First connection of the pair.</param> /// <param name="connectionB">Second connection of the pair.</param> /// <param name="anchorA">World space point to attach to connection A that will be constrained.</param> /// <param name="anchorB">World space point to attach to connection B that will be constrained.</param> /// <param name="axis">Limited axis in world space to attach to connection A.</param> public LinearAxisMotor(Entity connectionA, Entity connectionB, Vector3 anchorA, Vector3 anchorB, Vector3 axis) { ConnectionA = connectionA; ConnectionB = connectionB; AnchorA = anchorA; AnchorB = anchorB; Axis = axis; settings = new MotorSettings1D(this); } /// <summary> /// Gets or sets the anchor point attached to entity A in world space. /// </summary> public Vector3 AnchorA { get { return worldAnchorA; } set { worldAnchorA = value; worldOffsetA = worldAnchorA - connectionA.position; Matrix3x3.TransformTranspose(ref worldOffsetA, ref connectionA.orientationMatrix, out localAnchorA); } } /// <summary> /// Gets or sets the anchor point attached to entity A in world space. /// </summary> public Vector3 AnchorB { get { return worldAnchorB; } set { worldAnchorB = value; worldOffsetB = worldAnchorB - connectionB.position; Matrix3x3.TransformTranspose(ref worldOffsetB, ref connectionB.orientationMatrix, out localAnchorB); } } /// <summary> /// Gets or sets the motorized axis in world space. /// </summary> public Vector3 Axis { get { return worldAxis; } set { worldAxis = Vector3.Normalize(value); Matrix3x3.TransformTranspose(ref worldAxis, ref connectionA.orientationMatrix, out localAxis); } } /// <summary> /// Gets or sets the limited axis in the local space of connection A. /// </summary> public Vector3 LocalAxis { get { return localAxis; } set { localAxis = Vector3.Normalize(value); Matrix3x3.Transform(ref localAxis, ref connectionA.orientationMatrix, out worldAxis); } } /// <summary> /// Gets or sets the offset from the first entity's center of mass to the anchor point in its local space. /// </summary> public Vector3 LocalOffsetA { get { return localAnchorA; } set { localAnchorA = value; Matrix3x3.Transform(ref localAnchorA, ref connectionA.orientationMatrix, out worldOffsetA); worldAnchorA = connectionA.position + worldOffsetA; } } /// <summary> /// Gets or sets the offset from the second entity's center of mass to the anchor point in its local space. /// </summary> public Vector3 LocalOffsetB { get { return localAnchorB; } set { localAnchorB = value; Matrix3x3.Transform(ref localAnchorB, ref connectionB.orientationMatrix, out worldOffsetB); worldAnchorB = connectionB.position + worldOffsetB; } } /// <summary> /// Gets or sets the offset from the first entity's center of mass to the anchor point in world space. /// </summary> public Vector3 OffsetA { get { return worldOffsetA; } set { worldOffsetA = value; worldAnchorA = connectionA.position + worldOffsetA; Matrix3x3.TransformTranspose(ref worldOffsetA, ref connectionA.orientationMatrix, out localAnchorA); //Looks weird, but localAnchorA is "localOffsetA." } } /// <summary> /// Gets or sets the offset from the second entity's center of mass to the anchor point in world space. /// </summary> public Vector3 OffsetB { get { return worldOffsetB; } set { worldOffsetB = value; worldAnchorB = connectionB.position + worldOffsetB; Matrix3x3.TransformTranspose(ref worldOffsetB, ref connectionB.orientationMatrix, out localAnchorB);//Looks weird, but localAnchorB is "localOffsetB." } } /// <summary> /// Gets the motor's velocity and servo settings. /// </summary> public MotorSettings1D Settings { get { return settings; } } #region I1DImpulseConstraintWithError Members /// <summary> /// Gets the current relative velocity between the connected entities with respect to the constraint. /// </summary> public float RelativeVelocity { get { float lambda, dot; Vector3.Dot(ref jLinearA, ref connectionA.linearVelocity, out lambda); Vector3.Dot(ref jAngularA, ref connectionA.angularVelocity, out dot); lambda += dot; Vector3.Dot(ref jLinearB, ref connectionB.linearVelocity, out dot); lambda += dot; Vector3.Dot(ref jAngularB, ref connectionB.angularVelocity, out dot); lambda += dot; return lambda; } } /// <summary> /// Gets the total impulse applied by this constraint. /// </summary> public float TotalImpulse { get { return accumulatedImpulse; } } /// <summary> /// Gets the current constraint error. /// If the motor is in velocity only mode, the error will be zero. /// </summary> public float Error { get { return error; } } #endregion //Jacobians #region I1DJacobianConstraint Members /// <summary> /// Gets the linear jacobian entry for the first connected entity. /// </summary> /// <param name="jacobian">Linear jacobian entry for the first connected entity.</param> public void GetLinearJacobianA(out Vector3 jacobian) { jacobian = jLinearA; } /// <summary> /// Gets the linear jacobian entry for the second connected entity. /// </summary> /// <param name="jacobian">Linear jacobian entry for the second connected entity.</param> public void GetLinearJacobianB(out Vector3 jacobian) { jacobian = jLinearB; } /// <summary> /// Gets the angular jacobian entry for the first connected entity. /// </summary> /// <param name="jacobian">Angular jacobian entry for the first connected entity.</param> public void GetAngularJacobianA(out Vector3 jacobian) { jacobian = jAngularA; } /// <summary> /// Gets the angular jacobian entry for the second connected entity. /// </summary> /// <param name="jacobian">Angular jacobian entry for the second connected entity.</param> public void GetAngularJacobianB(out Vector3 jacobian) { jacobian = jAngularB; } /// <summary> /// Gets the mass matrix of the constraint. /// </summary> /// <param name="outputMassMatrix">Constraint's mass matrix.</param> public void GetMassMatrix(out float outputMassMatrix) { outputMassMatrix = massMatrix; } #endregion /// <summary> /// Computes one iteration of the constraint to meet the solver updateable's goal. /// </summary> /// <returns>The rough applied impulse magnitude.</returns> public override float SolveIteration() { //Compute the current relative velocity. float lambda, dot; Vector3.Dot(ref jLinearA, ref connectionA.linearVelocity, out lambda); Vector3.Dot(ref jAngularA, ref connectionA.angularVelocity, out dot); lambda += dot; Vector3.Dot(ref jLinearB, ref connectionB.linearVelocity, out dot); lambda += dot; Vector3.Dot(ref jAngularB, ref connectionB.angularVelocity, out dot); lambda += dot; //Add in the constraint space bias velocity lambda = -lambda + biasVelocity - usedSoftness * accumulatedImpulse; //Transform to an impulse lambda *= massMatrix; //Clamp accumulated impulse float previousAccumulatedImpulse = accumulatedImpulse; accumulatedImpulse = MathHelper.Clamp(accumulatedImpulse + lambda, -maxForceDt, maxForceDt); lambda = accumulatedImpulse - previousAccumulatedImpulse; //Apply the impulse Vector3 impulse; if (connectionA.isDynamic) { Vector3.Multiply(ref jLinearA, lambda, out impulse); connectionA.ApplyLinearImpulse(ref impulse); Vector3.Multiply(ref jAngularA, lambda, out impulse); connectionA.ApplyAngularImpulse(ref impulse); } if (connectionB.isDynamic) { Vector3.Multiply(ref jLinearB, lambda, out impulse); connectionB.ApplyLinearImpulse(ref impulse); Vector3.Multiply(ref jAngularB, lambda, out impulse); connectionB.ApplyAngularImpulse(ref impulse); } return (Math.Abs(lambda)); } public override void Update(float dt) { //Compute the 'pre'-jacobians Matrix3x3.Transform(ref localAnchorA, ref connectionA.orientationMatrix, out worldOffsetA); Matrix3x3.Transform(ref localAnchorB, ref connectionB.orientationMatrix, out worldOffsetB); Vector3.Add(ref worldOffsetA, ref connectionA.position, out worldAnchorA); Vector3.Add(ref worldOffsetB, ref connectionB.position, out worldAnchorB); Vector3.Subtract(ref worldAnchorB, ref connectionA.position, out rA); Matrix3x3.Transform(ref localAxis, ref connectionA.orientationMatrix, out worldAxis); float updateRate = 1 / dt; if (settings.mode == MotorMode.Servomechanism) { //Compute error #if !WINDOWS Vector3 separation = new Vector3(); #else Vector3 separation; #endif separation.X = worldAnchorB.X - worldAnchorA.X; separation.Y = worldAnchorB.Y - worldAnchorA.Y; separation.Z = worldAnchorB.Z - worldAnchorA.Z; Vector3.Dot(ref separation, ref worldAxis, out error); //Compute error error = error - settings.servo.goal; //Compute bias float absErrorOverDt = Math.Abs(error * updateRate); float errorReduction; settings.servo.springSettings.ComputeErrorReductionAndSoftness(dt, updateRate, out errorReduction, out usedSoftness); biasVelocity = Math.Sign(error) * MathHelper.Min(settings.servo.baseCorrectiveSpeed, absErrorOverDt) + error * errorReduction; biasVelocity = MathHelper.Clamp(biasVelocity, -settings.servo.maxCorrectiveVelocity, settings.servo.maxCorrectiveVelocity); } else { biasVelocity = -settings.velocityMotor.goalVelocity; usedSoftness = settings.velocityMotor.softness * updateRate; error = 0; } //Compute jacobians jLinearA = worldAxis; jLinearB.X = -jLinearA.X; jLinearB.Y = -jLinearA.Y; jLinearB.Z = -jLinearA.Z; Vector3.Cross(ref rA, ref jLinearA, out jAngularA); Vector3.Cross(ref worldOffsetB, ref jLinearB, out jAngularB); //compute mass matrix float entryA, entryB; Vector3 intermediate; if (connectionA.isDynamic) { Matrix3x3.Transform(ref jAngularA, ref connectionA.inertiaTensorInverse, out intermediate); Vector3.Dot(ref intermediate, ref jAngularA, out entryA); entryA += connectionA.inverseMass; } else entryA = 0; if (connectionB.isDynamic) { Matrix3x3.Transform(ref jAngularB, ref connectionB.inertiaTensorInverse, out intermediate); Vector3.Dot(ref intermediate, ref jAngularB, out entryB); entryB += connectionB.inverseMass; } else entryB = 0; massMatrix = 1 / (entryA + entryB + usedSoftness); //Update the maximum force ComputeMaxForces(settings.maximumForce, dt); } /// <summary> /// Performs any pre-solve iteration work that needs exclusive /// access to the members of the solver updateable. /// Usually, this is used for applying warmstarting impulses. /// </summary> public override void ExclusiveUpdate() { //Warm starting Vector3 impulse; if (connectionA.isDynamic) { Vector3.Multiply(ref jLinearA, accumulatedImpulse, out impulse); connectionA.ApplyLinearImpulse(ref impulse); Vector3.Multiply(ref jAngularA, accumulatedImpulse, out impulse); connectionA.ApplyAngularImpulse(ref impulse); } if (connectionB.isDynamic) { Vector3.Multiply(ref jLinearB, accumulatedImpulse, out impulse); connectionB.ApplyLinearImpulse(ref impulse); Vector3.Multiply(ref jAngularB, accumulatedImpulse, out impulse); connectionB.ApplyAngularImpulse(ref impulse); } } } }
Anomalous-Software/BEPUPhysics
BEPUphysics/Constraints/TwoEntity/Motors/LinearAxisMotor.cs
C#
apache-2.0
16,509
<!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 (version 1.7.0_79) on Thu Sep 17 01:48:47 IST 2015 --> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Uses of Interface org.apache.solr.search.grouping.endresulttransformer.EndResultTransformer (Solr 5.3.1 API)</title> <meta name="date" content="2015-09-17"> <link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Interface org.apache.solr.search.grouping.endresulttransformer.EndResultTransformer (Solr 5.3.1 API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><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/apache/solr/search/grouping/endresulttransformer/EndResultTransformer.html" title="interface in org.apache.solr.search.grouping.endresulttransformer">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?org/apache/solr/search/grouping/endresulttransformer/class-use/EndResultTransformer.html" target="_top">Frames</a></li> <li><a href="EndResultTransformer.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../../allclasses-noframe.html">All 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 Interface org.apache.solr.search.grouping.endresulttransformer.EndResultTransformer" class="title">Uses of Interface<br>org.apache.solr.search.grouping.endresulttransformer.EndResultTransformer</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../../../org/apache/solr/search/grouping/endresulttransformer/EndResultTransformer.html" title="interface in org.apache.solr.search.grouping.endresulttransformer">EndResultTransformer</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.apache.solr.search.grouping.endresulttransformer">org.apache.solr.search.grouping.endresulttransformer</a></td> <td class="colLast"> <div class="block">APIs and classes for transforming result grouping results into the appropriate response format</div> </td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="org.apache.solr.search.grouping.endresulttransformer"> <!-- --> </a> <h3>Uses of <a href="../../../../../../../org/apache/solr/search/grouping/endresulttransformer/EndResultTransformer.html" title="interface in org.apache.solr.search.grouping.endresulttransformer">EndResultTransformer</a> in <a href="../../../../../../../org/apache/solr/search/grouping/endresulttransformer/package-summary.html">org.apache.solr.search.grouping.endresulttransformer</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation"> <caption><span>Classes in <a href="../../../../../../../org/apache/solr/search/grouping/endresulttransformer/package-summary.html">org.apache.solr.search.grouping.endresulttransformer</a> that implement <a href="../../../../../../../org/apache/solr/search/grouping/endresulttransformer/EndResultTransformer.html" title="interface in org.apache.solr.search.grouping.endresulttransformer">EndResultTransformer</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../../../org/apache/solr/search/grouping/endresulttransformer/GroupedEndResultTransformer.html" title="class in org.apache.solr.search.grouping.endresulttransformer">GroupedEndResultTransformer</a></strong></code> <div class="block">Implementation of <a href="../../../../../../../org/apache/solr/search/grouping/endresulttransformer/EndResultTransformer.html" title="interface in org.apache.solr.search.grouping.endresulttransformer"><code>EndResultTransformer</code></a> that keeps each grouped result separate in the final response.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../../../org/apache/solr/search/grouping/endresulttransformer/MainEndResultTransformer.html" title="class in org.apache.solr.search.grouping.endresulttransformer">MainEndResultTransformer</a></strong></code> <div class="block">Implementation of <a href="../../../../../../../org/apache/solr/search/grouping/endresulttransformer/EndResultTransformer.html" title="interface in org.apache.solr.search.grouping.endresulttransformer"><code>EndResultTransformer</code></a> that transforms the grouped result into the main result list in the response.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../../../org/apache/solr/search/grouping/endresulttransformer/SimpleEndResultTransformer.html" title="class in org.apache.solr.search.grouping.endresulttransformer">SimpleEndResultTransformer</a></strong></code> <div class="block">Implementation of <a href="../../../../../../../org/apache/solr/search/grouping/endresulttransformer/EndResultTransformer.html" title="interface in org.apache.solr.search.grouping.endresulttransformer"><code>EndResultTransformer</code></a> that transforms the grouped result into a single flat list.</div> </td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><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/apache/solr/search/grouping/endresulttransformer/EndResultTransformer.html" title="interface in org.apache.solr.search.grouping.endresulttransformer">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?org/apache/solr/search/grouping/endresulttransformer/class-use/EndResultTransformer.html" target="_top">Frames</a></li> <li><a href="EndResultTransformer.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../../allclasses-noframe.html">All 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> <i>Copyright &copy; 2000-2015 Apache Software Foundation. All Rights Reserved.</i> <script src='../../../../../../../prettify.js' type='text/javascript'></script> <script type='text/javascript'> (function(){ var oldonload = window.onload; if (typeof oldonload != 'function') { window.onload = prettyPrint; } else { window.onload = function() { oldonload(); prettyPrint(); } } })(); </script> </small></p> </body> </html>
TitasNandi/Summer_Project
solr-5.3.1/docs/solr-core/org/apache/solr/search/grouping/endresulttransformer/class-use/EndResultTransformer.html
HTML
apache-2.0
9,422
/*- * * * Copyright 2015 Skymind,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.nd4j.linalg.api.ops.impl.transforms; import org.nd4j.autodiff.samediff.SDVariable; import org.nd4j.autodiff.samediff.SameDiff; import org.nd4j.imports.NoOpNameFoundException; import org.nd4j.linalg.api.ndarray.INDArray; import org.nd4j.linalg.api.ops.BaseTransformOp; import java.util.Collections; import java.util.List; import java.util.UUID; /** * Identity function * * @author Adam Gibson */ public class OldIdentity extends BaseTransformOp { public OldIdentity(SameDiff sameDiff, SDVariable i_v, boolean inPlace) { super(sameDiff, i_v, inPlace); } public OldIdentity(SameDiff sameDiff, SDVariable i_v, int[] shape, boolean inPlace, Object[] extraArgs) { super(sameDiff, i_v, shape, inPlace, extraArgs); } public OldIdentity(SameDiff sameDiff, SDVariable i_v, Object[] extraArgs) { super(sameDiff, i_v, extraArgs); } public OldIdentity() {} public OldIdentity(INDArray x, INDArray z) { super(x, z); } public OldIdentity(INDArray x, INDArray z, long n) { super(x, z, n); } public OldIdentity(INDArray x, INDArray y, INDArray z, long n) { super(x, y, z, n); } public OldIdentity(INDArray x) { super(x); } @Override public int opNum() { return 27; } @Override public String opName() { return "old_identity"; } @Override public String onnxName() { throw new NoOpNameFoundException("This op does not work with onnx."); } @Override public String tensorflowName() { throw new NoOpNameFoundException("This op does not work with tensorflow."); } @Override public List<SDVariable> doDiff(List<SDVariable> i_v) { return Collections.singletonList(sameDiff.one("grad-" + UUID.randomUUID().toString(),i_v.get(0).getShape())); } }
smarthi/nd4j
nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/api/ops/impl/transforms/OldIdentity.java
Java
apache-2.0
2,541
<extend name="Admin@Public/common" /> <block name="header-ext"> <style> .fali{ color:#5c5c5e;padding-right:10px } </style> </block> <block name="body-main"> <div id="wrap-all"> <div id="main"> <div class="global_layout" style="background-image: none;"> <!--leftpanel start--> <include file="Admin@Public/leftpanel" /> <!--leftpanel end--> <div class="centerpanel"> <div class="layout_content ng-scope"> <div class="layout_content_main dashboard"> <!--navbar start--> <div class="mod-navbar"> <div class="main"> <div class="title"><h3> <?php if(isset($message)) {?> <i class="fa fa-check" style="color:green"></i><?php echo($message); ?> <?php }else{?> <i class="fa fa-close" style="color:red"></i><?php echo($error); ?> <?php }?> </h3></div> <div class="main_toolbar"></div> </div> </div> <!--navbar end--> <div class="height-nonav dashboard-body wt-scroll" style="top:54px;"> <dl class="frame"> <br/><br/><br/><br/><br/> <div class="row" style="b"> <div class="col-md-4"></div> <div class="col-md-4"> <h4>您现在可以:</h4> <h3><i class="fa fa-history fali"></i> <a href="<?php echo($_SERVER['HTTP_REFERER']); ?>">返回上一页</a></h3> <h3><i class="fa fa-home fali"></i> <a href="{:U('admin/index/index')}">回到控制面板首页</a></h3> <h3><i class="fa fa-play fali"></i> 页面自动 <a id="href" href="<?php echo($jumpUrl); ?>">跳转</a> 等待时间: <b id="wait" class="label label-danger"><?php echo($waitSecond); ?></b></h3> </div> <div class="col-md-4"></div> </div> </dl> </div> </div> </div> </div> </div> </div> </div> </block> <block name="footer-common"> <!--footer-common--> <js href="__STATIC__/js/jquery-1.9.1.js?v={$Think.APP_VERSION}"/> </block> <block name="footer-ext"> <!--footer-ext--> <js href="__STATIC__/js/common.js?v={$Think.APP_VERSION}"/> </block> <block name="footer-end"> <script type="text/javascript"> (function(){ var wait = document.getElementById('wait'),href = document.getElementById('href').href; var interval = setInterval(function(){ var time = --wait.innerHTML; if(time <= 0) { location.href = href; clearInterval(interval); }; }, 1000); })(); </script> </block>
biner88/BinerCms
Application/Admin/View/Public/dispatch_jump.html
HTML
apache-2.0
3,164
//===================================================================== // //File: $RCSfile: ModelImportWizard.java,v $ //Version: $Revision: 1.30 $ //Modified: $Date: 2013/05/10 05:12:22 $ // //(c) Copyright 2007-2014 by Mentor Graphics Corp. All rights reserved. // //===================================================================== // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. //===================================================================== package org.xtuml.bp.io.mdl.wizards; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import org.eclipse.core.resources.IWorkspaceRunnable; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Path; import org.eclipse.jface.dialogs.IDialogSettings; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.wizard.Wizard; import org.eclipse.ui.IImportWizard; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.PlatformUI; import org.xtuml.bp.core.CorePlugin; import org.xtuml.bp.core.Ooaofooa; import org.xtuml.bp.core.SystemModel_c; import org.xtuml.bp.core.common.BridgePointPreferencesStore; import org.xtuml.bp.core.common.ClassQueryInterface_c; import org.xtuml.bp.core.common.ComponentResourceListener; import org.xtuml.bp.core.common.InstanceList; import org.xtuml.bp.core.common.ModelRoot; import org.xtuml.bp.core.common.ModelStreamProcessor; import org.xtuml.bp.core.common.NonRootModelElement; import org.xtuml.bp.core.common.PersistableModelComponent; import org.xtuml.bp.core.common.PersistenceManager; import org.xtuml.bp.core.common.UpgradeJob; import org.xtuml.bp.core.ui.IModelImport; import org.xtuml.bp.core.ui.Selection; import org.xtuml.bp.core.util.UIUtil; import org.xtuml.bp.io.core.CoreImport; import org.xtuml.bp.io.core.ImportHelper; import org.xtuml.bp.ui.canvas.Diagram_c; import org.xtuml.bp.ui.canvas.Gr_c; import org.xtuml.bp.ui.canvas.Graphelement_c; import org.xtuml.bp.ui.canvas.GraphicalElement_c; import org.xtuml.bp.ui.canvas.GraphicsReconcilerLauncher; import org.xtuml.bp.ui.canvas.Graphnode_c; import org.xtuml.bp.ui.canvas.Model_c; import org.xtuml.bp.ui.canvas.Ooaofgraphics; import org.xtuml.bp.ui.canvas.Shape_c; /** * This wizard imports model data from a system level export file, or from on * older BridgePoint single file model */ public class ModelImportWizard extends Wizard implements IImportWizard { public ModelImportWizard() { super(); } @Override public boolean performFinish() { if (fImportPage.getSourceFilePath() != null) { fInputFile = new File(fImportPage.getSourceFilePath()); if (!fInputFile.exists()) { return false; } } else { return false; } try { getContainer().run(false, false, new IRunnableWithProgress() { public void run(IProgressMonitor monitor) { Object[] checkedSystems = fImportPage.getSelectedSystems(); for (int i = 0; i < checkedSystems.length; i++) { importModel((SystemModel_c) checkedSystems[i]); } } }); } catch (InvocationTargetException e) { org.xtuml.bp.io.core.CorePlugin.logError( "Unable to run import operation.", e); } catch (InterruptedException e) { org.xtuml.bp.io.core.CorePlugin.logError( "Unable to run import operation.", e); } UIUtil.refresh(null); Selection.getInstance().setSelection(fPreviousSelection); if (fImporter.getErrorMessage().equals("")) return true; else return false; } IStructuredSelection fPreviousSelection = null; private ModelImportPage fImportPage; public File fInputFile; public IModelImport fImporter; private ModelStreamProcessor fProcessor = new ModelStreamProcessor(); private SystemModel_c fSystem; public void init(IWorkbench workbench, IStructuredSelection selection) { fPreviousSelection = Selection.getInstance().getStructuredSelection(); setWindowTitle("Import"); setDefaultPageImageDescriptor(CorePlugin .getImageDescriptor("importsql_wiz.gif")); //$NON-NLS-1$ } public void addPages() { fImportPage = new ModelImportPage("BridgePoint Model", Selection .getInstance().getStructuredSelection()); addPage(fImportPage); } /* * (non-Javadoc) * * @see org.eclipse.jface.wizard.IWizard#getDialogSettings() */ public IDialogSettings getDialogSettings() { return org.xtuml.bp.io.core.CorePlugin.getDefault() .getDialogSettings(); } public boolean importModel(SystemModel_c system) { fSystem = system; ProgressMonitorDialog dialog = new ProgressMonitorDialog(getShell()); String templateFileName = fImportPage.getSourceFilePath(); final IPath templatePath = new Path(templateFileName); // import the domain file into the model root with the id of the full // path of the domain file if (templatePath.getFileExtension().equals(Ooaofooa.MODELS_EXT)) { final InputStream inStream; try { inStream = new FileInputStream(templatePath.toFile()); } catch (FileNotFoundException e) { CorePlugin.logError("Internal error: failed to open " + templateFileName, e); return false; } try { // turn off model change listeners ModelRoot.disableChangeNotification(); IPath sourceFileDirectory = templatePath.removeLastSegments(1); ImportStreamStatus iss = new ImportStreamStatus(inStream); if (getContainer() == null) { // for unit tests to prevent displaying progress dialogs iss.run(new NullProgressMonitor()); } else { dialog.run(true, false, iss); } } catch (InterruptedException e) { org.xtuml.bp.io.core.CorePlugin.logError( "Internal error: import was interrupted", e); //$NON-NLS-1$ return false; } catch (InvocationTargetException e) { org.xtuml.bp.io.core.CorePlugin.logError( "Internal error: plugin.doLoad not found", e); //$NON-NLS-1$ return false; } finally { ModelRoot.enableChangeNotification(); } // resolve component references and formalize interfaces in MASL projects ImportHelper helper = new ImportHelper((CoreImport)fImporter); NonRootModelElement[] elements = helper.resolveMASLproject( fImporter.getLoadedInstances() ); // load the MASL activities IPath sourceFileDirectory = templatePath.removeLastSegments(1); helper.loadMASLActivities((Ooaofooa)fImporter.getRootModelElement().getModelRoot(), sourceFileDirectory, elements); } return true; } private class ImportStreamStatus implements IRunnableWithProgress { InputStream fInStream; String fMessage; public ImportStreamStatus(InputStream inStream) { fInStream = inStream; } public void run(final IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { fProcessor.setDestinationElement(fSystem); // otherwise read the file contents into a string and // pass into a byte array stream importer FileInputStream fis = new FileInputStream(fInputFile); byte[] fileBytes = new byte[Long.valueOf(fInputFile.length()) .intValue()]; fis.read(fileBytes); fis.close(); String contents = new String(fileBytes); fProcessor.setContents(contents); ByteArrayInputStream is = new ByteArrayInputStream(fileBytes); Ooaofooa.getInstance(Ooaofooa.CLIPBOARD_MODEL_ROOT_NAME) .clearDatabase(monitor); fImporter = CorePlugin.getStreamImportFactory().create( is, Ooaofooa.getInstance( Ooaofooa.CLIPBOARD_MODEL_ROOT_NAME, false), true, fSystem.getPersistableComponent().getFile().getFullPath()); fProcessor.runImporter(fImporter, monitor); fProcessor.processFirstStep(monitor); handleImportedGraphicalElements(); fProcessor.processSecondStep(monitor); IPreferenceStore store = CorePlugin.getDefault().getPreferenceStore(); if (fImportPage.parseOnImport()) { // this must be run on the display thread PlatformUI.getWorkbench().getDisplay().syncExec( new Runnable() { public void run() { fProcessor.runParseOnImportedElements( fSystem.getTransactionManager(), monitor); } }); } // Make sure that all events in the asynchronous event queue // are dispatched. PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() { public void run() { // do nothing } }); // . . . . before trying to force persistence. // since this process is not contained within a // transaction we must force persistence of the // imported elements persistImportedElements(monitor); fMessage = fImporter.getErrorMessage(); String fileFormatVersion = fImporter.getHeader() .getFileFormatVersion(); if (PersistenceManager.requiresUpgradeBeforeUse( fileFormatVersion, "ModelClass")) { PersistenceManager.markSystemFileForUpgrade(fSystem.getPersistableComponent()); UpgradeJob job = new UpgradeJob("Disable system", fSystem.getPersistableComponent()); job.setRule(ResourcesPlugin.getWorkspace().getRoot()); job.schedule(); } boolean createGraphicsOnImport = store.getBoolean(BridgePointPreferencesStore.CREATE_GRAPHICS_DURING_IMPORT); if (createGraphicsOnImport) { // this must be run on the display thread PlatformUI.getWorkbench().getDisplay().syncExec( new Runnable() { public void run() { List<NonRootModelElement> systems = new ArrayList<NonRootModelElement>(); systems.add(fSystem); GraphicsReconcilerLauncher reconciler = new GraphicsReconcilerLauncher(systems); reconciler.runReconciler(false, true); } }); } } catch (IOException e) { org.xtuml.bp.io.core.CorePlugin.logError( "There was an exception loading the give source file.", e); } } String getMessage() { return fMessage; } } private GraphicalElement_c getGraphicalElementFor(NonRootModelElement element) { GraphicalElement_c[] elements = GraphicalElement_c .GraphicalElementInstances(Ooaofgraphics .getInstance(Ooaofgraphics.CLIPBOARD_MODEL_ROOT_NAME)); for(int i = 0; i < elements.length; i++) { if(elements[i].getRepresents() == element) { return elements[i]; } } return null; } public void persistImportedElements(IProgressMonitor monitor) { try { ComponentResourceListener.setIgnoreResourceChanges(true); ResourcesPlugin.getWorkspace().run(new IWorkspaceRunnable() { public void run(IProgressMonitor monitor) throws CoreException { NonRootModelElement[] elementsToBeImported = fProcessor .getCachedExportedElements(); monitor.beginTask("Persisting imported elements...", elementsToBeImported.length); for (int i = 0; i < elementsToBeImported.length; i++) { PersistableModelComponent component = elementsToBeImported[i] .getPersistableComponent(); try { component.persistSelfAndChildren(); monitor.worked(1); } catch (CoreException e) { } } fSystem.getPersistableComponent().persist(); } }, monitor); } catch (CoreException e) { org.xtuml.bp.io.core.CorePlugin.logError( "Unable to persist imported elements.", e); } } public void handleImportedGraphicalElements() { Model_c systemModel = getSystemModel(); GraphicalElement_c[] rootImportedElements = getRootImportedGraphicalElements(); for (int i = 0; i < rootImportedElements.length; i++) { // first move the imported GD_GE to the destination // GD_MD Model_c prevModel = Model_c .getOneGD_MDOnR1(rootImportedElements[i]); if (prevModel != null) { prevModel.unrelateAcrossR1From(rootImportedElements[i]); } systemModel.relateAcrossR1To(rootImportedElements[i]); // now guarantee that it's placement will not overlap any // other GD_GE updateGraphicalPlacement(systemModel, rootImportedElements[i]); } updateGraphicalElementRoots(systemModel); } public void updateGraphicalPlacement(Model_c systemModel, GraphicalElement_c importedElement) { ModelRoot.disableChangeNotification(); boolean isOver = doesElementOverlapExisting(systemModel, importedElement); while(isOver) { Graphelement_c elem = Graphelement_c.getOneDIM_GEOnR23(importedElement); elem.setPositionx(elem.getPositionx() + Ooaofgraphics.Getgridsnapincrement(systemModel .getModelRoot(), false)); isOver = doesElementOverlapExisting(systemModel, importedElement); } ModelRoot.enableChangeNotification(); } private boolean doesElementOverlapExisting(Model_c systemModel, GraphicalElement_c importedElement) { boolean overlaps = false; Diagram_c diagram = Diagram_c.getOneDIM_DIAOnR18(systemModel); Graphelement_c elem = Graphelement_c.getOneDIM_GEOnR23(importedElement); Graphnode_c node = Graphnode_c.getOneDIM_NDOnR19(Shape_c.getOneGD_SHPOnR2(importedElement)); GraphicalElement_c[] elements = GraphicalElement_c.getManyGD_GEsOnR1(systemModel); for(int i = 0; i < elements.length; i++) { // skip the imported element if(elements[i] == importedElement) continue; // first check to see if any of the points above // are over this element // first try the imported elements nw corner overlaps = elements[i].Isover(Gr_c.Scale((int) (elem .getPositionx() - diagram.getViewportx())), Gr_c.Scale((int) (elem.getPositiony() - diagram .getViewporty()))); if(!overlaps) { // now try the sw corner overlaps = elements[i].Isover(Gr_c.Scale((int) (elem .getPositionx() - diagram.getViewportx())), Gr_c .Scale((int) (elem.getPositiony() - diagram.getViewporty() + node.getHeight()))); if(!overlaps) { // and now the ne corner overlaps = elements[i].Isover(Gr_c.Scale((int) (elem .getPositionx() - diagram.getViewportx() + node.getWidth())), Gr_c .Scale((int) (elem.getPositiony() - diagram .getViewporty()))); if(!overlaps) { // and finally the se corner overlaps = elements[i].Isover(Gr_c.Scale((int) (elem .getPositionx() - diagram.getViewportx() + node.getWidth())), Gr_c.Scale((int) (elem.getPositiony() - diagram.getViewporty() + node .getHeight()))); } } } // now switch the coordinates if(!overlaps) { Graphelement_c thisElem = Graphelement_c.getOneDIM_GEOnR23(elements[i]); Graphnode_c thisNode = Graphnode_c.getOneDIM_NDOnR19(Shape_c.getOneGD_SHPOnR2(elements[i])); // first try the elements nw corner overlaps = importedElement.Isover(Gr_c.Scale((int) (thisElem .getPositionx() - diagram.getViewportx())), Gr_c.Scale((int) (thisElem.getPositiony() - diagram .getViewporty()))); if(!overlaps) { // now try the sw corner overlaps = importedElement.Isover(Gr_c.Scale((int) (thisElem .getPositionx() - diagram.getViewportx())), Gr_c .Scale((int) (thisElem.getPositiony() - diagram.getViewporty() + thisNode.getHeight()))); if(!overlaps) { // and now the ne corner overlaps = importedElement.Isover(Gr_c.Scale((int) (thisElem .getPositionx() - diagram.getViewportx() + thisNode.getWidth())), Gr_c .Scale((int) (thisElem.getPositiony() - diagram .getViewporty()))); if(!overlaps) { // and finally the se corner overlaps = importedElement.Isover(Gr_c.Scale((int) (thisElem .getPositionx() - diagram.getViewportx() + thisNode.getWidth())), Gr_c.Scale((int) (thisElem.getPositiony() - diagram.getViewporty() + thisNode .getHeight()))); } } } } if(overlaps) break; } return overlaps; } private Model_c getSystemModel() { Model_c model = Model_c.ModelInstance(Ooaofgraphics .getDefaultInstance(), new ClassQueryInterface_c() { public boolean evaluate(Object candidate) { return ((Model_c) candidate).getOoa_id().equals( fSystem.Get_ooa_id()); } }); return model; } private GraphicalElement_c[] getRootImportedGraphicalElements() { ArrayList<GraphicalElement_c> list = new ArrayList<GraphicalElement_c>(); GraphicalElement_c[] pastedElems = GraphicalElement_c .GraphicalElementInstances(Ooaofgraphics .getInstance(Ooaofooa.CLIPBOARD_MODEL_ROOT_NAME)); for (int i = 0; i < pastedElems.length; i++) { if (pastedElems[i].getRepresents() != null) if (fProcessor .isTypePartOfExport((NonRootModelElement) pastedElems[i] .getRepresents())) { list.add(pastedElems[i]); } } return list.toArray(new GraphicalElement_c[list.size()]); } private void updateGraphicalElementRoots(Model_c model) { NonRootModelElement[] elements = fProcessor.getImporter().getLoadedGraphicalInstances(); for (int i = 0; i < elements.length; i++) { InstanceList list = elements[i].getModelRoot().getInstanceList( elements[i].getClass()); synchronized (list) { list.remove(elements[i]); } InstanceList parentList = model.getModelRoot().getInstanceList( elements[i].getClass()); synchronized (list) { parentList.add(elements[i]); } parentList.put(elements[i].getInstanceKey(), elements[i]); elements[i].setModelRoot(model.getModelRoot()); } } }
nmohamad/bridgepoint
src/org.xtuml.bp.io.mdl/src/org/xtuml/bp/io/mdl/wizards/ModelImportWizard.java
Java
apache-2.0
18,398
""" Class representing an exponential distribution, allowing us to sample from it. """ from numpy.random import exponential # Exponential draws def exponential_draw(lambdax): scale = 1.0 / lambdax return exponential(scale=scale,size=None) ''' # Do 1000 draws and plot them import matplotlib.pyplot as plt import numpy as np scale = 2. s = [exponential_draw(1./scale) for i in range(0,1000)] s2 = np.random.exponential(scale, 1000) count, bins, ignored = plt.hist(s, 50, normed=True) count, bins, ignored = plt.hist(s2, 50, normed=True) plt.show() '''
ThomasBrouwer/BNMTF
code/models/distributions/exponential.py
Python
apache-2.0
569
/* * Copyright 2012-2017 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.glacier.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.glacier.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * VaultAccessPolicyMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class VaultAccessPolicyMarshaller { private static final MarshallingInfo<String> POLICY_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("Policy").build(); private static final VaultAccessPolicyMarshaller instance = new VaultAccessPolicyMarshaller(); public static VaultAccessPolicyMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(VaultAccessPolicy vaultAccessPolicy, ProtocolMarshaller protocolMarshaller) { if (vaultAccessPolicy == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(vaultAccessPolicy.getPolicy(), POLICY_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
dagnir/aws-sdk-java
aws-java-sdk-glacier/src/main/java/com/amazonaws/services/glacier/model/transform/VaultAccessPolicyMarshaller.java
Java
apache-2.0
1,962
/* * 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. * * Copyright 2013 Falco Labs LLC * */ package com.FalcoLabs.Fido.api.localization; import java.util.Locale; import java.util.ResourceBundle; // Constants for localizing error messages public class messages { public static final String KEYSPACE_LENGTH_ERROR = "KEYSPACE_LENGTH_ERROR"; public static final String MUST_SET_KEYSPACE_ERROR = "MUST_SET_KEYSPACE_ERROR"; public static final String FAILED_TO_GET_STACKTRACE_ERROR = "FAILED_TO_GET_STACKTRACE_ERROR"; public static final String MULTIVALID_PROPS_SAME_TYPE_ERROR = "MULTIVALID_PROPS_SAME_TYPE_ERROR"; public static final String KIND_REQUIRED_FOR_MULTIVALUED_PROP_ERROR = "KIND_REQUIRED_FOR_MULTIVALUED_PROP_ERROR"; public static final String NO_QUERY_SET_ERROR = "NO_QUERY_SET_ERROR"; public static final String ALL_KEYS_MUST_BE_SAME_KIND_ERROR = "ALL_KEYS_MUST_BE_SAME_KIND_ERROR"; public static final String MUST_CALL_SETKEYSPACE_ERROR = "MUST_CALL_SETKEYSPACE_ERROR"; public static final String INVALID_KEY_NAME_ERROR = "INVALID_KEY_NAME_ERROR"; public static final String NO_COLUMN_FOUND_FOR_TYPE_ERROR = "NO_COLUMN_FOUND_FOR_TYPE_ERROR"; /** * Gets the localized message for the specified key. * * @param key the key * @return the string */ public static String get(String key) { ResourceBundle messages = ResourceBundle.getBundle("messages", Locale.getDefault()); String value = messages.getString(key); return value; } }
lorenc/Fido
src/com/FalcoLabs/Fido/api/localization/messages.java
Java
apache-2.0
2,224
<html><body> <style> body, h1, h2, h3, div, span, p, pre, a { margin: 0; padding: 0; border: 0; font-weight: inherit; font-style: inherit; font-size: 100%; font-family: inherit; vertical-align: baseline; } body { font-size: 13px; padding: 1em; } h1 { font-size: 26px; margin-bottom: 1em; } h2 { font-size: 24px; margin-bottom: 1em; } h3 { font-size: 20px; margin-bottom: 1em; margin-top: 1em; } pre, code { line-height: 1.5; font-family: Monaco, 'DejaVu Sans Mono', 'Bitstream Vera Sans Mono', 'Lucida Console', monospace; } pre { margin-top: 0.5em; } h1, h2, h3, p { font-family: Arial, sans serif; } h1, h2, h3 { border-bottom: solid #CCC 1px; } .toc_element { margin-top: 0.5em; } .firstline { margin-left: 2 em; } .method { margin-top: 1em; border: solid 1px #CCC; padding: 1em; background: #EEE; } .details { font-weight: bold; font-size: 14px; } </style> <h1><a href="binaryauthorization_v1beta1.html">Binary Authorization API</a> . <a href="binaryauthorization_v1beta1.projects.html">projects</a></h1> <h2>Instance Methods</h2> <p class="toc_element"> <code><a href="binaryauthorization_v1beta1.projects.attestors.html">attestors()</a></code> </p> <p class="firstline">Returns the attestors Resource.</p> <p class="toc_element"> <code><a href="binaryauthorization_v1beta1.projects.policy.html">policy()</a></code> </p> <p class="firstline">Returns the policy Resource.</p> <p class="toc_element"> <code><a href="#close">close()</a></code></p> <p class="firstline">Close httplib2 connections.</p> <p class="toc_element"> <code><a href="#getPolicy">getPolicy(name, x__xgafv=None)</a></code></p> <p class="firstline">A policy specifies the attestors that must attest to a container image, before the project is allowed to deploy that image. There is at most one policy per project. All image admission requests are permitted if a project has no policy. Gets the policy for this project. Returns a default policy if the project does not have one.</p> <p class="toc_element"> <code><a href="#updatePolicy">updatePolicy(name, body=None, x__xgafv=None)</a></code></p> <p class="firstline">Creates or updates a project's policy, and returns a copy of the new policy. A policy is always updated as a whole, to avoid race conditions with concurrent policy enforcement (or management!) requests. Returns NOT_FOUND if the project does not exist, INVALID_ARGUMENT if the request is malformed.</p> <h3>Method Details</h3> <div class="method"> <code class="details" id="close">close()</code> <pre>Close httplib2 connections.</pre> </div> <div class="method"> <code class="details" id="getPolicy">getPolicy(name, x__xgafv=None)</code> <pre>A policy specifies the attestors that must attest to a container image, before the project is allowed to deploy that image. There is at most one policy per project. All image admission requests are permitted if a project has no policy. Gets the policy for this project. Returns a default policy if the project does not have one. Args: name: string, Required. The resource name of the policy to retrieve, in the format `projects/*/policy`. (required) x__xgafv: string, V1 error format. Allowed values 1 - v1 error format 2 - v2 error format Returns: An object of the form: { # A policy for Binary Authorization. &quot;admissionWhitelistPatterns&quot;: [ # Optional. Admission policy allowlisting. A matching admission request will always be permitted. This feature is typically used to exclude Google or third-party infrastructure images from Binary Authorization policies. { # An admission allowlist pattern exempts images from checks by admission rules. &quot;namePattern&quot;: &quot;A String&quot;, # An image name pattern to allowlist, in the form `registry/path/to/image`. This supports a trailing `*` as a wildcard, but this is allowed only in text after the `registry/` part. `*` wildcard does not match `/`, i.e., `gcr.io/nginx*` matches `gcr.io/nginx@latest`, but it does not match `gcr.io/nginx/image`. This also supports a trailing `**` wildcard which matches subdirectories, i.e., `gcr.io/nginx**` matches `gcr.io/nginx/image`. }, ], &quot;clusterAdmissionRules&quot;: { # Optional. Per-cluster admission rules. Cluster spec format: `location.clusterId`. There can be at most one admission rule per cluster spec. A `location` is either a compute zone (e.g. us-central1-a) or a region (e.g. us-central1). For `clusterId` syntax restrictions see https://cloud.google.com/container-engine/reference/rest/v1/projects.zones.clusters. &quot;a_key&quot;: { # An admission rule specifies either that all container images used in a pod creation request must be attested to by one or more attestors, that all pod creations will be allowed, or that all pod creations will be denied. Images matching an admission allowlist pattern are exempted from admission rules and will never block a pod creation. &quot;enforcementMode&quot;: &quot;A String&quot;, # Required. The action when a pod creation is denied by the admission rule. &quot;evaluationMode&quot;: &quot;A String&quot;, # Required. How this admission rule will be evaluated. &quot;requireAttestationsBy&quot;: [ # Optional. The resource names of the attestors that must attest to a container image, in the format `projects/*/attestors/*`. Each attestor must exist before a policy can reference it. To add an attestor to a policy the principal issuing the policy change request must be able to read the attestor resource. Note: this field must be non-empty when the evaluation_mode field specifies REQUIRE_ATTESTATION, otherwise it must be empty. &quot;A String&quot;, ], }, }, &quot;defaultAdmissionRule&quot;: { # An admission rule specifies either that all container images used in a pod creation request must be attested to by one or more attestors, that all pod creations will be allowed, or that all pod creations will be denied. Images matching an admission allowlist pattern are exempted from admission rules and will never block a pod creation. # Required. Default admission rule for a cluster without a per-cluster, per- kubernetes-service-account, or per-istio-service-identity admission rule. &quot;enforcementMode&quot;: &quot;A String&quot;, # Required. The action when a pod creation is denied by the admission rule. &quot;evaluationMode&quot;: &quot;A String&quot;, # Required. How this admission rule will be evaluated. &quot;requireAttestationsBy&quot;: [ # Optional. The resource names of the attestors that must attest to a container image, in the format `projects/*/attestors/*`. Each attestor must exist before a policy can reference it. To add an attestor to a policy the principal issuing the policy change request must be able to read the attestor resource. Note: this field must be non-empty when the evaluation_mode field specifies REQUIRE_ATTESTATION, otherwise it must be empty. &quot;A String&quot;, ], }, &quot;description&quot;: &quot;A String&quot;, # Optional. A descriptive comment. &quot;etag&quot;: &quot;A String&quot;, # Optional. Used to prevent updating the policy when another request has updated it since it was retrieved. &quot;globalPolicyEvaluationMode&quot;: &quot;A String&quot;, # Optional. Controls the evaluation of a Google-maintained global admission policy for common system-level images. Images not covered by the global policy will be subject to the project admission policy. This setting has no effect when specified inside a global admission policy. &quot;istioServiceIdentityAdmissionRules&quot;: { # Optional. Per-istio-service-identity admission rules. Istio service identity spec format: `spiffe:///ns//sa/` or `/ns//sa/` e.g. `spiffe://example.com/ns/test-ns/sa/default` &quot;a_key&quot;: { # An admission rule specifies either that all container images used in a pod creation request must be attested to by one or more attestors, that all pod creations will be allowed, or that all pod creations will be denied. Images matching an admission allowlist pattern are exempted from admission rules and will never block a pod creation. &quot;enforcementMode&quot;: &quot;A String&quot;, # Required. The action when a pod creation is denied by the admission rule. &quot;evaluationMode&quot;: &quot;A String&quot;, # Required. How this admission rule will be evaluated. &quot;requireAttestationsBy&quot;: [ # Optional. The resource names of the attestors that must attest to a container image, in the format `projects/*/attestors/*`. Each attestor must exist before a policy can reference it. To add an attestor to a policy the principal issuing the policy change request must be able to read the attestor resource. Note: this field must be non-empty when the evaluation_mode field specifies REQUIRE_ATTESTATION, otherwise it must be empty. &quot;A String&quot;, ], }, }, &quot;kubernetesNamespaceAdmissionRules&quot;: { # Optional. Per-kubernetes-namespace admission rules. K8s namespace spec format: `[a-z.-]+`, e.g. `some-namespace` &quot;a_key&quot;: { # An admission rule specifies either that all container images used in a pod creation request must be attested to by one or more attestors, that all pod creations will be allowed, or that all pod creations will be denied. Images matching an admission allowlist pattern are exempted from admission rules and will never block a pod creation. &quot;enforcementMode&quot;: &quot;A String&quot;, # Required. The action when a pod creation is denied by the admission rule. &quot;evaluationMode&quot;: &quot;A String&quot;, # Required. How this admission rule will be evaluated. &quot;requireAttestationsBy&quot;: [ # Optional. The resource names of the attestors that must attest to a container image, in the format `projects/*/attestors/*`. Each attestor must exist before a policy can reference it. To add an attestor to a policy the principal issuing the policy change request must be able to read the attestor resource. Note: this field must be non-empty when the evaluation_mode field specifies REQUIRE_ATTESTATION, otherwise it must be empty. &quot;A String&quot;, ], }, }, &quot;kubernetesServiceAccountAdmissionRules&quot;: { # Optional. Per-kubernetes-service-account admission rules. Service account spec format: `namespace:serviceaccount`. e.g. `test-ns:default` &quot;a_key&quot;: { # An admission rule specifies either that all container images used in a pod creation request must be attested to by one or more attestors, that all pod creations will be allowed, or that all pod creations will be denied. Images matching an admission allowlist pattern are exempted from admission rules and will never block a pod creation. &quot;enforcementMode&quot;: &quot;A String&quot;, # Required. The action when a pod creation is denied by the admission rule. &quot;evaluationMode&quot;: &quot;A String&quot;, # Required. How this admission rule will be evaluated. &quot;requireAttestationsBy&quot;: [ # Optional. The resource names of the attestors that must attest to a container image, in the format `projects/*/attestors/*`. Each attestor must exist before a policy can reference it. To add an attestor to a policy the principal issuing the policy change request must be able to read the attestor resource. Note: this field must be non-empty when the evaluation_mode field specifies REQUIRE_ATTESTATION, otherwise it must be empty. &quot;A String&quot;, ], }, }, &quot;name&quot;: &quot;A String&quot;, # Output only. The resource name, in the format `projects/*/policy`. There is at most one policy per project. &quot;updateTime&quot;: &quot;A String&quot;, # Output only. Time when the policy was last updated. }</pre> </div> <div class="method"> <code class="details" id="updatePolicy">updatePolicy(name, body=None, x__xgafv=None)</code> <pre>Creates or updates a project&#x27;s policy, and returns a copy of the new policy. A policy is always updated as a whole, to avoid race conditions with concurrent policy enforcement (or management!) requests. Returns NOT_FOUND if the project does not exist, INVALID_ARGUMENT if the request is malformed. Args: name: string, Output only. The resource name, in the format `projects/*/policy`. There is at most one policy per project. (required) body: object, The request body. The object takes the form of: { # A policy for Binary Authorization. &quot;admissionWhitelistPatterns&quot;: [ # Optional. Admission policy allowlisting. A matching admission request will always be permitted. This feature is typically used to exclude Google or third-party infrastructure images from Binary Authorization policies. { # An admission allowlist pattern exempts images from checks by admission rules. &quot;namePattern&quot;: &quot;A String&quot;, # An image name pattern to allowlist, in the form `registry/path/to/image`. This supports a trailing `*` as a wildcard, but this is allowed only in text after the `registry/` part. `*` wildcard does not match `/`, i.e., `gcr.io/nginx*` matches `gcr.io/nginx@latest`, but it does not match `gcr.io/nginx/image`. This also supports a trailing `**` wildcard which matches subdirectories, i.e., `gcr.io/nginx**` matches `gcr.io/nginx/image`. }, ], &quot;clusterAdmissionRules&quot;: { # Optional. Per-cluster admission rules. Cluster spec format: `location.clusterId`. There can be at most one admission rule per cluster spec. A `location` is either a compute zone (e.g. us-central1-a) or a region (e.g. us-central1). For `clusterId` syntax restrictions see https://cloud.google.com/container-engine/reference/rest/v1/projects.zones.clusters. &quot;a_key&quot;: { # An admission rule specifies either that all container images used in a pod creation request must be attested to by one or more attestors, that all pod creations will be allowed, or that all pod creations will be denied. Images matching an admission allowlist pattern are exempted from admission rules and will never block a pod creation. &quot;enforcementMode&quot;: &quot;A String&quot;, # Required. The action when a pod creation is denied by the admission rule. &quot;evaluationMode&quot;: &quot;A String&quot;, # Required. How this admission rule will be evaluated. &quot;requireAttestationsBy&quot;: [ # Optional. The resource names of the attestors that must attest to a container image, in the format `projects/*/attestors/*`. Each attestor must exist before a policy can reference it. To add an attestor to a policy the principal issuing the policy change request must be able to read the attestor resource. Note: this field must be non-empty when the evaluation_mode field specifies REQUIRE_ATTESTATION, otherwise it must be empty. &quot;A String&quot;, ], }, }, &quot;defaultAdmissionRule&quot;: { # An admission rule specifies either that all container images used in a pod creation request must be attested to by one or more attestors, that all pod creations will be allowed, or that all pod creations will be denied. Images matching an admission allowlist pattern are exempted from admission rules and will never block a pod creation. # Required. Default admission rule for a cluster without a per-cluster, per- kubernetes-service-account, or per-istio-service-identity admission rule. &quot;enforcementMode&quot;: &quot;A String&quot;, # Required. The action when a pod creation is denied by the admission rule. &quot;evaluationMode&quot;: &quot;A String&quot;, # Required. How this admission rule will be evaluated. &quot;requireAttestationsBy&quot;: [ # Optional. The resource names of the attestors that must attest to a container image, in the format `projects/*/attestors/*`. Each attestor must exist before a policy can reference it. To add an attestor to a policy the principal issuing the policy change request must be able to read the attestor resource. Note: this field must be non-empty when the evaluation_mode field specifies REQUIRE_ATTESTATION, otherwise it must be empty. &quot;A String&quot;, ], }, &quot;description&quot;: &quot;A String&quot;, # Optional. A descriptive comment. &quot;etag&quot;: &quot;A String&quot;, # Optional. Used to prevent updating the policy when another request has updated it since it was retrieved. &quot;globalPolicyEvaluationMode&quot;: &quot;A String&quot;, # Optional. Controls the evaluation of a Google-maintained global admission policy for common system-level images. Images not covered by the global policy will be subject to the project admission policy. This setting has no effect when specified inside a global admission policy. &quot;istioServiceIdentityAdmissionRules&quot;: { # Optional. Per-istio-service-identity admission rules. Istio service identity spec format: `spiffe:///ns//sa/` or `/ns//sa/` e.g. `spiffe://example.com/ns/test-ns/sa/default` &quot;a_key&quot;: { # An admission rule specifies either that all container images used in a pod creation request must be attested to by one or more attestors, that all pod creations will be allowed, or that all pod creations will be denied. Images matching an admission allowlist pattern are exempted from admission rules and will never block a pod creation. &quot;enforcementMode&quot;: &quot;A String&quot;, # Required. The action when a pod creation is denied by the admission rule. &quot;evaluationMode&quot;: &quot;A String&quot;, # Required. How this admission rule will be evaluated. &quot;requireAttestationsBy&quot;: [ # Optional. The resource names of the attestors that must attest to a container image, in the format `projects/*/attestors/*`. Each attestor must exist before a policy can reference it. To add an attestor to a policy the principal issuing the policy change request must be able to read the attestor resource. Note: this field must be non-empty when the evaluation_mode field specifies REQUIRE_ATTESTATION, otherwise it must be empty. &quot;A String&quot;, ], }, }, &quot;kubernetesNamespaceAdmissionRules&quot;: { # Optional. Per-kubernetes-namespace admission rules. K8s namespace spec format: `[a-z.-]+`, e.g. `some-namespace` &quot;a_key&quot;: { # An admission rule specifies either that all container images used in a pod creation request must be attested to by one or more attestors, that all pod creations will be allowed, or that all pod creations will be denied. Images matching an admission allowlist pattern are exempted from admission rules and will never block a pod creation. &quot;enforcementMode&quot;: &quot;A String&quot;, # Required. The action when a pod creation is denied by the admission rule. &quot;evaluationMode&quot;: &quot;A String&quot;, # Required. How this admission rule will be evaluated. &quot;requireAttestationsBy&quot;: [ # Optional. The resource names of the attestors that must attest to a container image, in the format `projects/*/attestors/*`. Each attestor must exist before a policy can reference it. To add an attestor to a policy the principal issuing the policy change request must be able to read the attestor resource. Note: this field must be non-empty when the evaluation_mode field specifies REQUIRE_ATTESTATION, otherwise it must be empty. &quot;A String&quot;, ], }, }, &quot;kubernetesServiceAccountAdmissionRules&quot;: { # Optional. Per-kubernetes-service-account admission rules. Service account spec format: `namespace:serviceaccount`. e.g. `test-ns:default` &quot;a_key&quot;: { # An admission rule specifies either that all container images used in a pod creation request must be attested to by one or more attestors, that all pod creations will be allowed, or that all pod creations will be denied. Images matching an admission allowlist pattern are exempted from admission rules and will never block a pod creation. &quot;enforcementMode&quot;: &quot;A String&quot;, # Required. The action when a pod creation is denied by the admission rule. &quot;evaluationMode&quot;: &quot;A String&quot;, # Required. How this admission rule will be evaluated. &quot;requireAttestationsBy&quot;: [ # Optional. The resource names of the attestors that must attest to a container image, in the format `projects/*/attestors/*`. Each attestor must exist before a policy can reference it. To add an attestor to a policy the principal issuing the policy change request must be able to read the attestor resource. Note: this field must be non-empty when the evaluation_mode field specifies REQUIRE_ATTESTATION, otherwise it must be empty. &quot;A String&quot;, ], }, }, &quot;name&quot;: &quot;A String&quot;, # Output only. The resource name, in the format `projects/*/policy`. There is at most one policy per project. &quot;updateTime&quot;: &quot;A String&quot;, # Output only. Time when the policy was last updated. } x__xgafv: string, V1 error format. Allowed values 1 - v1 error format 2 - v2 error format Returns: An object of the form: { # A policy for Binary Authorization. &quot;admissionWhitelistPatterns&quot;: [ # Optional. Admission policy allowlisting. A matching admission request will always be permitted. This feature is typically used to exclude Google or third-party infrastructure images from Binary Authorization policies. { # An admission allowlist pattern exempts images from checks by admission rules. &quot;namePattern&quot;: &quot;A String&quot;, # An image name pattern to allowlist, in the form `registry/path/to/image`. This supports a trailing `*` as a wildcard, but this is allowed only in text after the `registry/` part. `*` wildcard does not match `/`, i.e., `gcr.io/nginx*` matches `gcr.io/nginx@latest`, but it does not match `gcr.io/nginx/image`. This also supports a trailing `**` wildcard which matches subdirectories, i.e., `gcr.io/nginx**` matches `gcr.io/nginx/image`. }, ], &quot;clusterAdmissionRules&quot;: { # Optional. Per-cluster admission rules. Cluster spec format: `location.clusterId`. There can be at most one admission rule per cluster spec. A `location` is either a compute zone (e.g. us-central1-a) or a region (e.g. us-central1). For `clusterId` syntax restrictions see https://cloud.google.com/container-engine/reference/rest/v1/projects.zones.clusters. &quot;a_key&quot;: { # An admission rule specifies either that all container images used in a pod creation request must be attested to by one or more attestors, that all pod creations will be allowed, or that all pod creations will be denied. Images matching an admission allowlist pattern are exempted from admission rules and will never block a pod creation. &quot;enforcementMode&quot;: &quot;A String&quot;, # Required. The action when a pod creation is denied by the admission rule. &quot;evaluationMode&quot;: &quot;A String&quot;, # Required. How this admission rule will be evaluated. &quot;requireAttestationsBy&quot;: [ # Optional. The resource names of the attestors that must attest to a container image, in the format `projects/*/attestors/*`. Each attestor must exist before a policy can reference it. To add an attestor to a policy the principal issuing the policy change request must be able to read the attestor resource. Note: this field must be non-empty when the evaluation_mode field specifies REQUIRE_ATTESTATION, otherwise it must be empty. &quot;A String&quot;, ], }, }, &quot;defaultAdmissionRule&quot;: { # An admission rule specifies either that all container images used in a pod creation request must be attested to by one or more attestors, that all pod creations will be allowed, or that all pod creations will be denied. Images matching an admission allowlist pattern are exempted from admission rules and will never block a pod creation. # Required. Default admission rule for a cluster without a per-cluster, per- kubernetes-service-account, or per-istio-service-identity admission rule. &quot;enforcementMode&quot;: &quot;A String&quot;, # Required. The action when a pod creation is denied by the admission rule. &quot;evaluationMode&quot;: &quot;A String&quot;, # Required. How this admission rule will be evaluated. &quot;requireAttestationsBy&quot;: [ # Optional. The resource names of the attestors that must attest to a container image, in the format `projects/*/attestors/*`. Each attestor must exist before a policy can reference it. To add an attestor to a policy the principal issuing the policy change request must be able to read the attestor resource. Note: this field must be non-empty when the evaluation_mode field specifies REQUIRE_ATTESTATION, otherwise it must be empty. &quot;A String&quot;, ], }, &quot;description&quot;: &quot;A String&quot;, # Optional. A descriptive comment. &quot;etag&quot;: &quot;A String&quot;, # Optional. Used to prevent updating the policy when another request has updated it since it was retrieved. &quot;globalPolicyEvaluationMode&quot;: &quot;A String&quot;, # Optional. Controls the evaluation of a Google-maintained global admission policy for common system-level images. Images not covered by the global policy will be subject to the project admission policy. This setting has no effect when specified inside a global admission policy. &quot;istioServiceIdentityAdmissionRules&quot;: { # Optional. Per-istio-service-identity admission rules. Istio service identity spec format: `spiffe:///ns//sa/` or `/ns//sa/` e.g. `spiffe://example.com/ns/test-ns/sa/default` &quot;a_key&quot;: { # An admission rule specifies either that all container images used in a pod creation request must be attested to by one or more attestors, that all pod creations will be allowed, or that all pod creations will be denied. Images matching an admission allowlist pattern are exempted from admission rules and will never block a pod creation. &quot;enforcementMode&quot;: &quot;A String&quot;, # Required. The action when a pod creation is denied by the admission rule. &quot;evaluationMode&quot;: &quot;A String&quot;, # Required. How this admission rule will be evaluated. &quot;requireAttestationsBy&quot;: [ # Optional. The resource names of the attestors that must attest to a container image, in the format `projects/*/attestors/*`. Each attestor must exist before a policy can reference it. To add an attestor to a policy the principal issuing the policy change request must be able to read the attestor resource. Note: this field must be non-empty when the evaluation_mode field specifies REQUIRE_ATTESTATION, otherwise it must be empty. &quot;A String&quot;, ], }, }, &quot;kubernetesNamespaceAdmissionRules&quot;: { # Optional. Per-kubernetes-namespace admission rules. K8s namespace spec format: `[a-z.-]+`, e.g. `some-namespace` &quot;a_key&quot;: { # An admission rule specifies either that all container images used in a pod creation request must be attested to by one or more attestors, that all pod creations will be allowed, or that all pod creations will be denied. Images matching an admission allowlist pattern are exempted from admission rules and will never block a pod creation. &quot;enforcementMode&quot;: &quot;A String&quot;, # Required. The action when a pod creation is denied by the admission rule. &quot;evaluationMode&quot;: &quot;A String&quot;, # Required. How this admission rule will be evaluated. &quot;requireAttestationsBy&quot;: [ # Optional. The resource names of the attestors that must attest to a container image, in the format `projects/*/attestors/*`. Each attestor must exist before a policy can reference it. To add an attestor to a policy the principal issuing the policy change request must be able to read the attestor resource. Note: this field must be non-empty when the evaluation_mode field specifies REQUIRE_ATTESTATION, otherwise it must be empty. &quot;A String&quot;, ], }, }, &quot;kubernetesServiceAccountAdmissionRules&quot;: { # Optional. Per-kubernetes-service-account admission rules. Service account spec format: `namespace:serviceaccount`. e.g. `test-ns:default` &quot;a_key&quot;: { # An admission rule specifies either that all container images used in a pod creation request must be attested to by one or more attestors, that all pod creations will be allowed, or that all pod creations will be denied. Images matching an admission allowlist pattern are exempted from admission rules and will never block a pod creation. &quot;enforcementMode&quot;: &quot;A String&quot;, # Required. The action when a pod creation is denied by the admission rule. &quot;evaluationMode&quot;: &quot;A String&quot;, # Required. How this admission rule will be evaluated. &quot;requireAttestationsBy&quot;: [ # Optional. The resource names of the attestors that must attest to a container image, in the format `projects/*/attestors/*`. Each attestor must exist before a policy can reference it. To add an attestor to a policy the principal issuing the policy change request must be able to read the attestor resource. Note: this field must be non-empty when the evaluation_mode field specifies REQUIRE_ATTESTATION, otherwise it must be empty. &quot;A String&quot;, ], }, }, &quot;name&quot;: &quot;A String&quot;, # Output only. The resource name, in the format `projects/*/policy`. There is at most one policy per project. &quot;updateTime&quot;: &quot;A String&quot;, # Output only. Time when the policy was last updated. }</pre> </div> </body></html>
googleapis/google-api-python-client
docs/dyn/binaryauthorization_v1beta1.projects.html
HTML
apache-2.0
29,797
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <link rel="SHORTCUT ICON" href="../../../../../img/clover.ico" /> <link rel="stylesheet" href="../../../../../aui/css/aui.min.css" media="all"/> <link rel="stylesheet" href="../../../../../aui/css/aui-experimental.min.css" media="all"/> <!--[if IE 9]><link rel="stylesheet" href="../../../../../aui/css/aui-ie9.min.css" media="all"/><![endif]--> <style type="text/css" media="all"> @import url('../../../../../style.css'); @import url('../../../../../tree.css'); </style> <script src="../../../../../jquery-1.8.3.min.js" type="text/javascript"></script> <script src="../../../../../aui/js/aui.min.js" type="text/javascript"></script> <script src="../../../../../aui/js/aui-experimental.min.js" type="text/javascript"></script> <script src="../../../../../aui/js/aui-soy.min.js" type="text/javascript"></script> <script src="../../../../../package-nodes-tree.js" type="text/javascript"></script> <script src="../../../../../clover-tree.js" type="text/javascript"></script> <script src="../../../../../clover.js" type="text/javascript"></script> <script src="../../../../../clover-descriptions.js" type="text/javascript"></script> <script src="../../../../../cloud.js" type="text/javascript"></script> <title>ABA Route Transit Number Validator 1.0.1-SNAPSHOT</title> </head> <body> <div id="page"> <header id="header" role="banner"> <nav class="aui-header aui-dropdown2-trigger-group" role="navigation"> <div class="aui-header-inner"> <div class="aui-header-primary"> <h1 id="logo" class="aui-header-logo aui-header-logo-clover"> <a href="http://openclover.org" title="Visit OpenClover home page"><span class="aui-header-logo-device">OpenClover</span></a> </h1> </div> <div class="aui-header-secondary"> <ul class="aui-nav"> <li id="system-help-menu"> <a class="aui-nav-link" title="Open online documentation" target="_blank" href="http://openclover.org/documentation"> <span class="aui-icon aui-icon-small aui-iconfont-help">&#160;Help</span> </a> </li> </ul> </div> </div> </nav> </header> <div class="aui-page-panel"> <div class="aui-page-panel-inner"> <div class="aui-page-panel-nav aui-page-panel-nav-clover"> <div class="aui-page-header-inner" style="margin-bottom: 20px;"> <div class="aui-page-header-image"> <a href="http://cardatechnologies.com" target="_top"> <div class="aui-avatar aui-avatar-large aui-avatar-project"> <div class="aui-avatar-inner"> <img src="../../../../../img/clover_logo_large.png" alt="Clover icon"/> </div> </div> </a> </div> <div class="aui-page-header-main" > <h1> <a href="http://cardatechnologies.com" target="_top"> ABA Route Transit Number Validator 1.0.1-SNAPSHOT </a> </h1> </div> </div> <nav class="aui-navgroup aui-navgroup-vertical"> <div class="aui-navgroup-inner"> <ul class="aui-nav"> <li class=""> <a href="../../../../../dashboard.html">Project overview</a> </li> </ul> <div class="aui-nav-heading packages-nav-heading"> <strong>Packages</strong> </div> <div class="aui-nav project-packages"> <form method="get" action="#" class="aui package-filter-container"> <input type="text" autocomplete="off" class="package-filter text" placeholder="Type to filter packages..." name="package-filter" id="package-filter" title="Start typing package name (or part of the name) to search through the tree. Use arrow keys and the Enter key to navigate."/> </form> <p class="package-filter-no-results-message hidden"> <small>No results found.</small> </p> <div class="packages-tree-wrapper" data-root-relative="../../../../../" data-package-name="com.cardatechnologies.utils.validators.abaroutevalidator"> <div class="packages-tree-container"></div> <div class="clover-packages-lozenges"></div> </div> </div> </div> </nav> </div> <section class="aui-page-panel-content"> <div class="aui-page-panel-content-clover"> <div class="aui-page-header-main"><ol class="aui-nav aui-nav-breadcrumbs"> <li><a href="../../../../../dashboard.html"> Project Clover database Sat Aug 7 2021 12:29:33 MDT</a></li> <li><a href="test-pkg-summary.html">Package com.cardatechnologies.utils.validators.abaroutevalidator</a></li> <li><a href="test-Test_AbaRouteValidator_13b.html">Class Test_AbaRouteValidator_13b</a></li> </ol></div> <h1 class="aui-h2-clover"> Test testAbaNumberCheck_27385_good </h1> <table class="aui"> <thead> <tr> <th>Test</th> <th><label title="The test result. Either a Pass, Fail or Error.">Status</label></th> <th><label title="When the test execution was started">Start time</label></th> <th><label title="The total time in seconds taken to run this test.">Time (seconds)</label></th> <th><label title="A failure or error message if the test is not successful.">Message</label></th> </tr> </thead> <tbody> <tr> <td> <a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_13b.html?line=4504#src-4504" >testAbaNumberCheck_27385_good</a> </td> <td> <span class="sortValue">1</span><span class="aui-lozenge aui-lozenge-success">PASS</span> </td> <td> 7 Aug 12:42:34 </td> <td> 0.0 </td> <td> <div></div> <div class="errorMessage"></div> </td> </tr> </tbody> </table> <div>&#160;</div> <table class="aui aui-table-sortable"> <thead> <tr> <th style="white-space:nowrap;"><label title="A class that was directly hit by this test.">Target Class</label></th> <th colspan="4"><label title="The percentage of coverage contributed by each single test.">Coverage contributed by</label> testAbaNumberCheck_27385_good</th> </tr> </thead> <tbody> <tr> <td> <span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</span> &#160;&#160;<a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/AbaRouteValidator.html?id=9207#AbaRouteValidator" title="AbaRouteValidator" name="sl-47">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</a> </td> <td> <span class="sortValue">0.7352941</span>73.5% </td> <td class="align-middle" style="width: 100%" colspan="3"> <div> <div title="73.5% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:73.5%"></div></div></div> </td> </tr> </tbody> </table> </div> <!-- class="aui-page-panel-content-clover" --> <footer id="footer" role="contentinfo"> <section class="footer-body"> <ul> <li> Report generated by <a target="_new" href="http://openclover.org">OpenClover</a> v 4.4.1 on Sat Aug 7 2021 12:49:26 MDT using coverage data from Sat Aug 7 2021 12:47:23 MDT. </li> </ul> <ul> <li>OpenClover is free and open-source software. </li> </ul> </section> </footer> </section> <!-- class="aui-page-panel-content" --> </div> <!-- class="aui-page-panel-inner" --> </div> <!-- class="aui-page-panel" --> </div> <!-- id="page" --> </body> </html>
dcarda/aba.route.validator
target13/site/clover/com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_13b_testAbaNumberCheck_27385_good_73r.html
HTML
apache-2.0
9,181
package org.fabric3.samples.bigbank.api.backend.loan; import javax.xml.bind.annotation.XmlRootElement; import java.math.BigDecimal; /** * An internal loan application. */ @XmlRootElement public class LoanRequest { private String customerId; private String merchantId; private BigDecimal amount; private int term; private String division; public LoanRequest() { } public String getCustomerId() { return customerId; } public void setCustomerId(String customerId) { this.customerId = customerId; } public String getMerchantId() { return merchantId; } public void setMerchantId(String merchantId) { this.merchantId = merchantId; } public BigDecimal getAmount() { return amount; } public void setAmount(BigDecimal amount) { this.amount = amount; } public int getTerm() { return term; } public void setTerm(int term) { this.term = term; } public String getDivision() { return division; } public void setDivision(String division) { this.division = division; } }
Fabric3/samples-bigbank
backend-api/src/main/java/org/fabric3/samples/bigbank/api/backend/loan/LoanRequest.java
Java
apache-2.0
1,162
package com.ezpreferences; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
JeromeGL/EasyPreferences
app/src/androidTest/java/com/ezpreferences/ApplicationTest.java
Java
apache-2.0
348
# AUTOGENERATED FILE FROM balenalib/raspberrypicm4-ioboard-debian:buster-build RUN apt-get update \ && apt-get install -y --no-install-recommends \ ca-certificates \ curl \ \ # .NET Core dependencies libc6 \ libgcc1 \ libgssapi-krb5-2 \ libicu63 \ libssl1.1 \ libstdc++6 \ zlib1g \ && rm -rf /var/lib/apt/lists/* # Configure web servers to bind to port 80 when present ENV ASPNETCORE_URLS=http://+:80 \ # Enable detection of running in a container DOTNET_RUNNING_IN_CONTAINER=true # Install .NET Core ENV DOTNET_VERSION 3.1.12 RUN curl -SL --output dotnet.tar.gz "https://dotnetcli.blob.core.windows.net/dotnet/Runtime/$DOTNET_VERSION/dotnet-runtime-$DOTNET_VERSION-linux-arm64.tar.gz" \ && dotnet_sha512='1c7ca36af74524fa5ec49374983338ab3f1584a03aec11080943cf3bbc7e1fb36abf313549231e5be1c58c2252f27d4e001cac1464ee20702daf831ec61c92cf' \ && echo "$dotnet_sha512 dotnet.tar.gz" | sha512sum -c - \ && mkdir -p /usr/share/dotnet \ && tar -zxf dotnet.tar.gz -C /usr/share/dotnet \ && rm dotnet.tar.gz \ && ln -s /usr/share/dotnet/dotnet /usr/bin/dotnet CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"] RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@dotnet.sh" \ && echo "Running test-stack@dotnet" \ && chmod +x test-stack@dotnet.sh \ && bash test-stack@dotnet.sh \ && rm -rf test-stack@dotnet.sh RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v8 \nOS: Debian Buster \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \ndotnet 3.1-runtime \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && cp /bin/sh /bin/sh.real \ && mv /bin/sh-shim /bin/sh
nghiant2710/base-images
balena-base-images/dotnet/raspberrypicm4-ioboard/debian/buster/3.1-runtime/build/Dockerfile
Dockerfile
apache-2.0
2,541
asterisk-cpp [![Build Status](https://travis-ci.org/augcampos/asterisk-cpp.svg?branch=master)](https://travis-ci.org/augcampos/asterisk-cpp) ============ The free C++ library for Asterisk PBX integration. (asterisk-java ported) Check Example on <a href="https://github.com/augcampos/asterisk-cpp/wiki/Examples">wiki</a>
augcampos/asterisk-cpp
README.md
Markdown
apache-2.0
323
<!DOCTYPE html> <html lang="en"> <!-- Head tag --> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content="马浩珍在 Github 上的个人博客"> <meta name="keyword" content="haojen,马浩珍,前端,全栈,hexo,Anisina,blog,github"> <meta name="theme-color" content="#600090"> <meta name="msapplication-navbutton-color" content="#600090"> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-status-bar-style" content="#600090"> <link rel="shortcut icon" href="http://icons.iconarchive.com/icons/blackvariant/button-ui-requests-15/256/Amazon-Kindle-icon.png"> <link rel="alternate" type="application/atom+xml" title="Haojen" href="/atom.xml"> <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.min.css"> <link rel="stylesheet" href="//cdn.bootcss.com/font-awesome/4.6.3/css/font-awesome.css"> <title> Haojen&#39;s blog </title> <link rel="canonical" href="https://haojen.github.io/page/4/"> <!-- Bootstrap Core CSS --> <link rel="stylesheet" href="/css/bootstrap.min.css"> <!-- Custom CSS --> <link rel="stylesheet" href="/css/blog-style.css"> <!-- Pygments Github CSS --> <link rel="stylesheet" href="/css/syntax.css"> </head> <style> header.intro-header { background-image: url('//oco8bvfr8.qnssl.com/lion-blur-bg.jpg') } </style> <!-- hack iOS CSS :active style --> <body ontouchstart="" class="animated fadeIn"> <!-- Navigation --> <nav class="navbar navbar-default navbar-custom navbar-fixed-top " id="nav-top" data-ispost = "false" data-istags="false " data-ishome = "true" > <div class="container-fluid"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header page-scroll"> <button type="button" class="navbar-toggle"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand animated pulse" href="/"> <span class="brand-logo"> Haojen </span> 's Blog </a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <!-- Known Issue, found by Hux: <nav>'s height woule be hold on by its content. so, when navbar scale out, the <nav> will cover tags. also mask any touch event of tags, unfortunately. --> <!-- /.navbar-collapse --> <div id="huxblog_navbar"> <div class="navbar-collapse"> <ul class="nav navbar-nav navbar-right"> <li> <a href="/">Home</a> </li> <li> <a href="/my-works/">My works</a> </li> <li> <a href="/tags/">Tags</a> </li> </ul> </div> </div> </div> <!-- /.container --> </nav> <script> // Drop Bootstarp low-performance Navbar // Use customize navbar with high-quality material design animation // in high-perf jank-free CSS3 implementation // var $body = document.body; var $toggle = document.querySelector('.navbar-toggle'); var $navbar = document.querySelector('#huxblog_navbar'); var $collapse = document.querySelector('.navbar-collapse'); $toggle.addEventListener('click', handleMagic) function handleMagic(e){ if ($navbar.className.indexOf('in') > 0) { // CLOSE $navbar.className = " "; // wait until animation end. setTimeout(function(){ // prevent frequently toggle if($navbar.className.indexOf('in') < 0) { $collapse.style.height = "0px" } },400) }else{ // OPEN $collapse.style.height = "auto" $navbar.className += " in"; } } </script> <!-- Main Content --> <style> .custom-haojen-container .post-preview:nth-of-type(1), .custom-haojen-container .post-preview-poetry:nth-of-type(1) { text-align: center; background-repeat: no-repeat; border-radius: 3px; background-size: cover; padding: 0; height: 300px; display: table; width: 100%; background-color: rgba(0, 0, 0, 0.16); } /*去掉诗歌的背景图片*/ .custom-haojen-container .post-preview-poetry:nth-of-type(1) { background-image: none !important; background-color: rgba(255, 248, 220, 0.5); } .custom-haojen-container .post-preview:nth-child(1) h2, .custom-haojen-container .post-preview:nth-child(1) .post-meta, .custom-haojen-container .post-preview:nth-child(1) .post-subtitle { text-shadow: 0 0 40px rgba(0, 0, 0, 1); letter-spacing: 1px; color: #fff; margin-top: 0; padding-left: 60px; padding-right: 60px; } .custom-haojen-container .post-preview:nth-child(1) .post-meta { font-size: .9em; font-weight: 300; margin-top: 0; } .custom-haojen-container .post-preview-poetry:nth-child(1) .post-subtitle { letter-spacing: 6px; font-size: 18px; font-family: unset; font-weight: 400; color: rgba(0, 0, 0, .75) } /*不显示摘要*/ .custom-haojen-container .post-preview:nth-child(1) .post-content-preview { display: none } /*只第一个显示背景图片*/ .custom-haojen-container .post-preview:not(:nth-child(1)) { background-image: none !important; } /*第一个分界线去掉*/ .custom-haojen-container hr:nth-of-type(1) { display: none; } /*主题*/ .custom-haojen-container .post-preview:nth-of-type(1) > a { display: table-cell; vertical-align: middle; } /*诗词标题*/ .custom-haojen-container .post-preview-poetry:nth-child(1) h2 { font-size: 35px; font-family: STKaiti; color: rgba(0, 0, 0, .8); } .custom-haojen-container .post-preview-poetry:nth-of-type(1) .post-meta { color: #0e2231; } @media (max-width: 768px) { .custom-haojen-container .post-preview:nth-child(1) { height: 240px; } .custom-haojen-container .post-preview-poetry:nth-child(1) h2 { font-size: 28px !important; margin-top: 0; } .custom-haojen-container .post-preview:nth-child(1) .post-subtitle { font-size: 18px; font-weight: 400; padding-left: 0; padding-right: 0; } .custom-haojen-container .post-preview:nth-of-type(1) > a { padding: 20px } } /*手机屏幕*/ @media (max-width: 400px) { .custom-haojen-container .post-preview:nth-child(1) { height: 195px; } .custom-haojen-container .post-preview-poetry:nth-child(1) h2 { font-size: 20px !important; } .custom-haojen-container .post-preview:nth-child(1) .post-subtitle { font-size: 16px; } .custom-haojen-container .post-preview:nth-child(1) a { padding: 30px 20px; } } </style> <!-- Page Header --> <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1 visible-xs-block visible-sm-block"> <div class="row"> <header class="intro-header"> <div class="container"> <div class="site-heading text-center"> <div class="about-me"> <!--移动端头部显示--> <img src="//oco8bvfr8.qnssl.com/new_aman.jpg?imageView2/2/w/300/h/300/interlace/1/q/90"/> <h5><a href="/about/">Haojen Ma</a></h5> <p>求知若饥 虚心若愚</p> </div> </div> </div> </header> </div> </div> <!-- Main Content --> <div class="container custom-haojen-container"> <!-- Post Container --> <div class="row"> <div class="col-lg-8 col-lg-offset-1 col-md-8 col-md-offset-1 col-sm-12 col-xs-12 post-container"> <!-- Main Content --> <div class="post-preview " style="background-image: url('//oco8bvfr8.qnssl.com/16-8-new-bg.jpg?imageView2/1/w/800/h/300/interlace/1/q/80')"> <a href="/2015/12/11/复习整理/"> <h2 class="post-title"> HTML 初学复习笔记 </h2> <p class="post-meta"> <i class="fa fa-calendar" aria-hidden="true"></i> 2015-12-11 </p> <div class="post-content-preview"> <p> 第一阶段复习: HTML 重新认识到的 &lt;hr/&gt; 新元素 &lt;address&gt;这里可以添加地址,地址将呈现斜体字&lt;/address&gt; &lt;a href=&quot;mailto:someName@xxmail.com?subject=回复主题&amp; b.. </p> </div> </a> </div> <hr> <div class="post-preview " style="background-image: url('//oco8bvfr8.qnssl.com/16-8-new-bg.jpg?imageView2/1/w/800/h/300/interlace/1/q/80')"> <a href="/2015/12/10/我所不知道的_json/"> <h2 class="post-title"> 你所不知道的 JSON </h2> <p class="post-meta"> <i class="fa fa-calendar" aria-hidden="true"></i> 2015-12-10 </p> <div class="post-content-preview"> <p> JSON 里面的字符串必须使用双引号,而如果使用单引号的话会导致语法错误 不支持 undefined JSON 没有变量概念 没有末尾的分号,因为这不是 JS 语句,所以不需要分号 对象的属性必须加双引号 JSON 对象有两个方法:stringify() 和parse() , 这两个方法分别用.. </p> </div> </a> </div> <hr> <div class="post-preview " style="background-image: url('//oco8bvfr8.qnssl.com/16-8-new-bg.jpg?imageView2/1/w/800/h/300/interlace/1/q/80')"> <a href="/2015/12/10/BOM 概览/"> <h2 class="post-title"> BOM 概览 </h2> <p class="post-meta"> <i class="fa fa-calendar" aria-hidden="true"></i> 2015-12-10 </p> <h3 class="post-subtitle"> BOM 的简单介绍,也涉及到 DOM </h3> <div class="post-content-preview"> <p> window 对象 Javascript 的全局作用域 global location 对象 浏览器的 URL , 前进后退 navigator 对象 浏览器的版本信息,获取用户的平台, 配置等信息 history 对象 浏览器的历史记录 screen 对象 用户的显示器信息 DOM 需要了解的.. </p> </div> </a> </div> <hr> <div class="post-preview " style="background-image: url('//oco8bvfr8.qnssl.com/16-8-new-bg.jpg?imageView2/1/w/800/h/300/interlace/1/q/80')"> <a href="/2015/12/05/人类的性存在/"> <h2 class="post-title"> 人类的性存在 </h2> <p class="post-meta"> <i class="fa fa-calendar" aria-hidden="true"></i> 2015-12-05 </p> <h3 class="post-subtitle"> 一本包涵了世界各地性文化的书籍,客观严谨 </h3> <div class="post-content-preview"> <p> 第一章 性的视野 ###性研究发展史 ###性禁忌 在大多数地区,这些禁忌都是存在的 乱伦 婚外情 ###同性恋 同性恋的三条一般性规律 无论一个社会群体如何对待同性恋,同性恋的存在总是少数的,并且同性恋存在世界各地。 男人比女人更可能发生同性行为 在任何一个社会中,同性性行为从不是被学习.. </p> </div> </a> </div> <hr> <div class="post-preview " style="background-image: url('//oco8bvfr8.qnssl.com/16-8-new-bg.jpg?imageView2/1/w/800/h/300/interlace/1/q/80')"> <a href="/2015/12/05/聆听音乐_by_耶鲁大学/"> <h2 class="post-title"> 聆听音乐 </h2> <p class="post-meta"> <i class="fa fa-calendar" aria-hidden="true"></i> 2015-12-05 </p> <h3 class="post-subtitle"> 音乐是意志的本尊--叔本华 </h3> <div class="post-content-preview"> <p> 该笔记内容处理在该视频或书籍中学到的东西,整理出来帮助我更好的加深与理解,且在学习的过程中锻炼我在阅读书籍或者视频的过程中集中精力,更好的理解内容本身。 所以在记录的过程中, 只根据个人的判断对内容的重要性进行记录 &lt;!-- more --&gt; 1 导言 大脑中的哪里是处理声音的? 左.. </p> </div> </a> </div> <hr> <div class="post-preview " style="background-image: url('//oco8bvfr8.qnssl.com/16-8-new-bg.jpg?imageView2/1/w/800/h/300/interlace/1/q/80')"> <a href="/2015/11/25/一元运算符/"> <h2 class="post-title"> 一元运算符 </h2> <p class="post-meta"> <i class="fa fa-calendar" aria-hidden="true"></i> 2015-11-25 </p> <div class="post-content-preview"> <p> 前++ &amp; 前-- 在计算表达式之前将给定的值进行自增或自减操作 var a =2 var b =++a //b输出 3 后++ &amp; 后- - 在计算表达式之后将给定的值进行自增或自减操作 var a=2 var b=a-- //此时 b等于 a var c =b //c =.. </p> </div> </a> </div> <hr> <div class="post-preview " style="background-image: url('//oco8bvfr8.qnssl.com/16-8-new-bg.jpg?imageView2/1/w/800/h/300/interlace/1/q/80')"> <a href="/2015/11/11/js_命名规范/"> <h2 class="post-title"> Javascript 不同的数据类型命名规范 </h2> <p class="post-meta"> <i class="fa fa-calendar" aria-hidden="true"></i> 2015-11-11 </p> <div class="post-content-preview"> <p> Array 前缀 a aSomeArray //etc Boolean 前缀 b bSomeBoolean //etc 浮点数 前缀 f fSomeFloat //etc 函数 前缀 fn fnSomeFunction //etc 整数 前缀 i iSomeInteger //etc .. </p> </div> </a> </div> <hr> <div class="post-preview " style="background-image: url('//oco8bvfr8.qnssl.com/16-8-new-bg.jpg?imageView2/1/w/800/h/300/interlace/1/q/80')"> <a href="/2015/11/10/定时器学习/"> <h2 class="post-title"> 定时器 </h2> <p class="post-meta"> <i class="fa fa-calendar" aria-hidden="true"></i> 2015-11-10 </p> <div class="post-content-preview"> <p> setTimeOut var timer = setTimeOut(function(){},1000 )//第一个参数是需要执行的程序,第二个是执行前的等待时间 设定一个程序触发后,执行前的等待时间 clearTimeOut clearTimeOut(timer) 清除 setTimeOu.. </p> </div> </a> </div> <hr> <!-- 翻页 pager --> <ul class="pager"> <li class="previous"> <a href="/page/3/">&larr; Newer Posts</a> </li> <li class="next"> <a href="/page/5/">Older Posts &rarr;</a> </li> </ul> </div> <!-- Sidebar Container --> <div class=" col-lg-3 col-lg-offset-0 col-md-3 col-md-offset-0 col-sm-12 col-xs-12 sidebar-container "> <!-- About Me --> <section class="visible-md visible-lg" style="padding: 0 18px"> <div class="short-about"> <!--侧边栏头像--> <img src="//oco8bvfr8.qnssl.com/new_aman.jpg?imageView2/2/w/300/h/300/interlace/1/q/90"/> <h5><a href="/about/">Haojen Ma</a></h5> <p>求知若饥 虚心若愚</p> <hr> <!-- SNS Link 社交 --> <ul class="list-inline"> <li> <a target="_blank" href="https://twitter.com/ehazon"> <span class="fa-stack fa-lg"> <i class="fa fa-circle fa-stack-2x"></i> <i class="fa fa-twitter fa-stack-1x fa-inverse"></i> </span> </a> </li> <li> <a target="_blank" href="https://www.zhihu.com/people/megahertz"> <span class="fa-stack fa-lg"> <i class="fa fa-circle fa-stack-2x"></i> <i class="fa fa-stack-1x fa-inverse">知</i> </span> </a> </li> <li> <a target="_blank" href="http://weibo.com/haojen"> <span class="fa-stack fa-lg"> <i class="fa fa-circle fa-stack-2x"></i> <i class="fa fa-weibo fa-stack-1x fa-inverse"></i> </span> </a> </li> <li> <a target="_blank" href="https://github.com/haojen"> <span class="fa-stack fa-lg"> <i class="fa fa-circle fa-stack-2x"></i> <i class="fa fa-github fa-stack-1x fa-inverse"></i> </span> </a> </li> </ul> </div> </section> <!-- Featured Tags 标签 --> <section> <div class="tags"> <a href="/tags/#CSS" title="CSS" rel="4">CSS</a> <a href="/tags/#Anisina" title="Anisina" rel="2">Anisina</a> <a href="/tags/#JS" title="JS" rel="7">JS</a> <a href="/tags/#jQuery" title="jQuery" rel="2">jQuery</a> <a href="/tags/#HTML" title="HTML" rel="2">HTML</a> <a href="/tags/#Node.js" title="Node.js" rel="2">Node.js</a> <a href="/tags/#诗词" title="诗词" rel="2">诗词</a> </div> </section> <hr> <h5 style="text-align: center;">Friends</h5> <ul class="list-inline" style="text-align: center;"> <li><a href="http://blog.kaijun.rocks" target="_blank">Kaijun&#39;s Blog</a></li> <li><a href="http://huangxuan.me" target="_blank">Hux Blog</a></li> <li><a href="#" target="_blank">Foo</a></li> <li><a href="#" target="_blank">Bar</a></li> <li><a href="#" target="_blank">Example Friends</a></li> <li><a href="#" target="_blank">It helps SEO</a></li> </ul> </div> </div> </div> <!-- Footer --> <!-- Footer --> <footer> <div class="container"> <div class="row"> <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1 text-center"> <br> <ul class="list-inline text-center"> <li> <a target="_blank" href="https://twitter.com/ehazon"> <span class="fa-stack fa-lg"> <i class="fa fa-circle fa-stack-2x"></i> <i class="fa fa-twitter fa-stack-1x fa-inverse"></i> </span> </a> </li> <li> <a target="_blank" href="https://www.zhihu.com/people/megahertz"> <span class="fa-stack fa-lg"> <i class="fa fa-circle fa-stack-2x"></i> <i class="fa fa-stack-1x fa-inverse">知</i> </span> </a> </li> <li> <a target="_blank" href="http://weibo.com/haojen"> <span class="fa-stack fa-lg"> <i class="fa fa-circle fa-stack-2x"></i> <i class="fa fa-weibo fa-stack-1x fa-inverse"></i> </span> </a> </li> <li> <a target="_blank" href="https://github.com/haojen"> <span class="fa-stack fa-lg"> <i class="fa fa-circle fa-stack-2x"></i> <i class="fa fa-github fa-stack-1x fa-inverse"></i> </span> </a> </li> </ul> <p class="copyright text-muted"> Copyright &copy; Haojen 2016 <br> <span id="busuanzi_container_site_pv" style="font-size: 12px;">PV: <span id="busuanzi_value_site_pv"></span> Times</span> <br> Theme by <a href="https://haojen.github.io/">Haojen Ma</a> </p> </div> </div> </div> </footer> <!-- jQuery --> <script src="/js/jquery.min.js"></script> <!-- Bootstrap Core JavaScript --> <script src="/js/bootstrap.min.js"></script> <!-- Custom Theme JavaScript --> <script src="/js/blog.js"></script> <!-- async load function --> <script> function async(u, c) { var d = document, t = 'script', o = d.createElement(t), s = d.getElementsByTagName(t)[0]; o.src = u; if (c) { o.addEventListener('load', function (e) { c(null, e); }, false); } s.parentNode.insertBefore(o, s); } </script> <!-- jquery.tagcloud.js --> <script> // only load tagcloud.js in tag.html if($('#tag_cloud').length !== 0){ async("https://haojen.github.io/js/jquery.tagcloud.js",function(){ $.fn.tagcloud.defaults = { //size: {start: 1, end: 1, unit: 'em'}, color: {start: '#bbbbee', end: '#0085a1'}, }; $('#tag_cloud a').tagcloud(); }) } </script> <!--fastClick.js --> <script> async("//cdn.bootcss.com/fastclick/1.0.6/fastclick.min.js", function(){ var $nav = document.querySelector("nav"); if($nav) FastClick.attach($nav); }) </script> <!-- Google Analytics --> <script> // dynamic User by Hux var _gaId = 'UA-78633618-1'; var _gaDomain = 'auto'; // Originial (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', _gaId, _gaDomain); ga('send', 'pageview'); </script> <!-- Baidu Tongji --> <!-- swiftype --> <script type="text/javascript"> (function(w,d,t,u,n,s,e){w['SwiftypeObject']=n;w[n]=w[n]||function(){ (w[n].q=w[n].q||[]).push(arguments);};s=d.createElement(t); e=d.getElementsByTagName(t)[0];s.async=1;s.src=u;e.parentNode.insertBefore(s,e); })(window,document,'script','//s.swiftypecdn.com/install/v2/st.js','_st'); _st('install','Wedjzx3dn5qkFKLneXxt','2.0.0'); </script> <script async src="//dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script> <!--wechat title img--> <img class="wechat-title-img" src="//oco8bvfr8.qnssl.com/new_aman.jpg?imageView2/2/w/300/h/300/interlace/1/q/90"> </body> </html>
daringpig/daringpig.github.io
page/4/index.html
HTML
apache-2.0
27,150
define({tools:{search:{error:"Nie można odnaleźć lokalizacji",notWhatYouWanted:"Oczekiwano innej lokalizacji?",selectAnother:"Wybierz inną lokalizację",currentLocation:"Bieżąca lokalizacja",title:"Lokalizacja"},basemap:{label:"Mapa bazowa",title:"Wybierz mapę bazową",close:"Zamknij"},legend:{title:"Legenda"},details:{title:"Szczegóły",error:"Aktualizuj opis mapy internetowej za pomocą informacji wyświetlanych w tej sekcji."},popup:{title:"Informacje",instructions:"Wybierz obiekt na mapie, aby wyświetlić szczegóły."}},map:{toggle:"Przełącz panel boczny",error:"Nie można utworzyć mapy",licenseError:{message:"Twoje konto nie jest licencjonowane do korzystania z aplikacji konfigurowalnych, które nie są publiczne. Poproś administratora instytucji o przypisanie typu użytkownika, który obejmuje licencję na kluczowe aplikacje lub licencję na kluczowe aplikacje dodatkowe.",title:"Nie licencjonowano"}}});
Esri/embed-template
build/js/nls/pl/resources.js
JavaScript
apache-2.0
936
<?php /** * modelo para acondicionamiento */ class Acondicionamiento { /** * @param array $acondicionamiento contiene todos loa datos de acondicionamiento * */ public function insertAcondicionamiento(array $acondicionamiento){ $query = "INSERT INTO acondicionamiento (id_solicitud,nro_campo,fecha_emision,categoria_en_campo,rendimiento_estimado,"; $query .= "superficie,rendimiento_campo,nro_cupones,rango_cupones,planta_acondicionadora,peso_bruto_semilla,cultivo,variedad) VALUES ("; $query .= $acondicionamiento['isolicitud'].",'".$acondicionamiento['campo']."','".$acondicionamiento['fecha']."',".$acondicionamiento['categoria_en_campo'].","; $query .= $acondicionamiento['rendimiento_estimado'].",".$acondicionamiento['superficie'].",".$acondicionamiento['rendimiento_campo'].","; $query .= $acondicionamiento['cupones'].",'".$acondicionamiento['rango']."','".$acondicionamiento['planta']."',".$acondicionamiento['pesobruto'].","; $query .= $acondicionamiento['cultivo'].",".$acondicionamiento['variedad'].")"; DBConnector::ejecutar($query); if (DBConnector::nroError()){ echo "ERROR :: ".__METHOD__.":: $query ::",DBConnector::mensaje(); } } /**semillas de productores por bloque*/ public function getAcondicionamientoByBlock($area, $inicio = 0, $nroReg = 15) { $query = "SELECT * FROM view_acondicionamiento"; if ($area != 10) $query .= " WHERE id_sistema=$area AND gestion = '" . date('Y') . "'"; $query .= " ORDER BY id_solicitud DESC LIMIT $inicio,$nroReg"; #echo $query; return $query; } /** * devuelve el acondicionamiento segun el id de solicitud * */ public function getAcondicionamientoByIdSolicitud($id){ $query = "SELECT * FROM view_acondicionamiento "; $query .= "WHERE id_solicitud = $id"; DBConnector::ejecutar($query); if (DBConnector::nroError()){ echo "ERROR :: ".__METHOD__.":: $query ::",DBConnector::mensaje(); } } /** * eliminar acondicionamiento segun id_acondicionamiento o id_solicitud * */ public function deleteAcondicionamiento ($id,$tipo='acondicionamiento'){ if ($acondicionamiento == 'acondicionamiento'){ $query = "DELETE FROM acondicionamiento WHERE id_acondicionamiento = $id"; }else{ $query = "DELETE FROM acondicionamiento WHERE id_solicitud = $id"; } DBConnector::ejecutar($query); if (DBConnector::nroError()){ echo "ERROR :: ".__METHOD__.":: $query ::",DBConnector::mensaje(); } } } ?>
ewill15/usfx
modelo/Acondicionamiento.class.php
PHP
apache-2.0
2,738
--- description: Inspect information about a machine keywords: - machine, inspect, subcommand menu: main: identifier: machine.inspect parent: smn_machine_subcmds title: inspect --- # inspect Usage: docker-machine inspect [OPTIONS] [arg...] Inspect information about a machine Description: Argument is a machine name. Options: --format, -f Format the output using the given go template. By default, this will render information about a machine as JSON. If a format is specified, the given template will be executed for each result. Go's [text/template](http://golang.org/pkg/text/template/) package describes all the details of the format. In addition to the `text/template` syntax, there are some additional functions, `json` and `prettyjson`, which can be used to format the output as JSON (documented below). ## Examples **List all the details of a machine:** This is the default usage of `inspect`. $ docker-machine inspect dev { "DriverName": "virtualbox", "Driver": { "MachineName": "docker-host-128be8d287b2028316c0ad5714b90bcfc11f998056f2f790f7c1f43f3d1e6eda", "SSHPort": 55834, "Memory": 1024, "DiskSize": 20000, "Boot2DockerURL": "", "IPAddress": "192.168.5.99" }, ... } **Get a machine's IP address:** For the most part, you can pick out any field from the JSON in a fairly straightforward manner. {% raw %} $ docker-machine inspect --format='{{.Driver.IPAddress}}' dev 192.168.5.99 {% endraw %} **Formatting details:** If you want a subset of information formatted as JSON, you can use the `json` function in the template. {% raw %} $ docker-machine inspect --format='{{json .Driver}}' dev-fusion {"Boot2DockerURL":"","CPUS":8,"CPUs":8,"CaCertPath":"/Users/hairyhenderson/.docker/machine/certs/ca.pem","DiskSize":20000,"IPAddress":"172.16.62.129","ISO":"/Users/hairyhenderson/.docker/machine/machines/dev-fusion/boot2docker-1.5.0-GH747.iso","MachineName":"dev-fusion","Memory":1024,"PrivateKeyPath":"/Users/hairyhenderson/.docker/machine/certs/ca-key.pem","SSHPort":22,"SSHUser":"docker","SwarmDiscovery":"","SwarmHost":"tcp://0.0.0.0:3376","SwarmMaster":false} {% endraw %} While this is usable, it's not very human-readable. For this reason, there is `prettyjson`: {% raw %} $ docker-machine inspect --format='{{prettyjson .Driver}}' dev-fusion { "Boot2DockerURL": "", "CPUS": 8, "CPUs": 8, "CaCertPath": "/Users/hairyhenderson/.docker/machine/certs/ca.pem", "DiskSize": 20000, "IPAddress": "172.16.62.129", "ISO": "/Users/hairyhenderson/.docker/machine/machines/dev-fusion/boot2docker-1.5.0-GH747.iso", "MachineName": "dev-fusion", "Memory": 1024, "PrivateKeyPath": "/Users/hairyhenderson/.docker/machine/certs/ca-key.pem", "SSHPort": 22, "SSHUser": "docker", "SwarmDiscovery": "", "SwarmHost": "tcp://0.0.0.0:3376", "SwarmMaster": false } {% endraw %}
danix800/docker.github.io
machine/reference/inspect.md
Markdown
apache-2.0
3,116
# coding: utf-8 # # Copyright 2014 The Oppia Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Model for an Oppia exploration.""" import datetime from constants import constants import core.storage.base_model.gae_models as base_models import core.storage.user.gae_models as user_models import feconf from google.appengine.ext import ndb class ExplorationSnapshotMetadataModel(base_models.BaseSnapshotMetadataModel): """Storage model for the metadata for an exploration snapshot.""" pass class ExplorationSnapshotContentModel(base_models.BaseSnapshotContentModel): """Storage model for the content of an exploration snapshot.""" pass class ExplorationModel(base_models.VersionedModel): """Versioned storage model for an Oppia exploration. This class should only be imported by the exploration services file and the exploration model test file. """ SNAPSHOT_METADATA_CLASS = ExplorationSnapshotMetadataModel SNAPSHOT_CONTENT_CLASS = ExplorationSnapshotContentModel ALLOW_REVERT = True # What this exploration is called. title = ndb.StringProperty(required=True) # The category this exploration belongs to. category = ndb.StringProperty(required=True, indexed=True) # The objective of this exploration. objective = ndb.TextProperty(default='', indexed=False) # The ISO 639-1 code for the language this exploration is written in. language_code = ndb.StringProperty( default=constants.DEFAULT_LANGUAGE_CODE, indexed=True) # Tags (topics, skills, concepts, etc.) associated with this # exploration. tags = ndb.StringProperty(repeated=True, indexed=True) # A blurb for this exploration. blurb = ndb.TextProperty(default='', indexed=False) # 'Author notes' for this exploration. author_notes = ndb.TextProperty(default='', indexed=False) # The version of the states blob schema. states_schema_version = ndb.IntegerProperty( required=True, default=0, indexed=True) # The name of the initial state of this exploration. init_state_name = ndb.StringProperty(required=True, indexed=False) # A dict representing the states of this exploration. This dict should # not be empty. states = ndb.JsonProperty(default={}, indexed=False) # The dict of parameter specifications associated with this exploration. # Each specification is a dict whose keys are param names and whose values # are each dicts with a single key, 'obj_type', whose value is a string. param_specs = ndb.JsonProperty(default={}, indexed=False) # The list of parameter changes to be performed once at the start of a # reader's encounter with an exploration. param_changes = ndb.JsonProperty(repeated=True, indexed=False) # A boolean indicating whether automatic text-to-speech is enabled in # this exploration. auto_tts_enabled = ndb.BooleanProperty(default=True, indexed=True) # A boolean indicating whether correctness feedback is enabled in this # exploration. correctness_feedback_enabled = ndb.BooleanProperty( default=False, indexed=True) # DEPRECATED in v2.0.0.rc.2. Do not use. Retaining it here because deletion # caused GAE to raise an error on fetching a specific version of the # exploration model. # TODO(sll): Fix this error and remove this property. skill_tags = ndb.StringProperty(repeated=True, indexed=True) # DEPRECATED in v2.0.1. Do not use. # TODO(sll): Remove this property from the model. default_skin = ndb.StringProperty(default='conversation_v1') # DEPRECATED in v2.5.4. Do not use. skin_customizations = ndb.JsonProperty(indexed=False) @classmethod def get_exploration_count(cls): """Returns the total number of explorations.""" return cls.get_all().count() def _trusted_commit( self, committer_id, commit_type, commit_message, commit_cmds): """Record the event to the commit log after the model commit. Note that this extends the superclass method. Args: committer_id: str. The user_id of the user who committed the change. commit_type: str. The type of commit. Possible values are in core.storage.base_models.COMMIT_TYPE_CHOICES. commit_message: str. The commit description message. commit_cmds: list(dict). A list of commands, describing changes made in this model, which should give sufficient information to reconstruct the commit. Each dict always contains: cmd: str. Unique command. and then additional arguments for that command. """ super(ExplorationModel, self)._trusted_commit( committer_id, commit_type, commit_message, commit_cmds) committer_user_settings_model = ( user_models.UserSettingsModel.get_by_id(committer_id)) committer_username = ( committer_user_settings_model.username if committer_user_settings_model else '') exp_rights = ExplorationRightsModel.get_by_id(self.id) # TODO(msl): test if put_async() leads to any problems (make # sure summary dicts get updated correctly when explorations # are changed). exploration_commit_log = ExplorationCommitLogEntryModel.create( self.id, self.version, committer_id, committer_username, commit_type, commit_message, commit_cmds, exp_rights.status, exp_rights.community_owned ) exploration_commit_log.exploration_id = self.id exploration_commit_log.put() class ExplorationRightsSnapshotMetadataModel( base_models.BaseSnapshotMetadataModel): """Storage model for the metadata for an exploration rights snapshot.""" pass class ExplorationRightsSnapshotContentModel( base_models.BaseSnapshotContentModel): """Storage model for the content of an exploration rights snapshot.""" pass class ExplorationRightsModel(base_models.VersionedModel): """Storage model for rights related to an exploration. The id of each instance is the id of the corresponding exploration. """ SNAPSHOT_METADATA_CLASS = ExplorationRightsSnapshotMetadataModel SNAPSHOT_CONTENT_CLASS = ExplorationRightsSnapshotContentModel ALLOW_REVERT = False # The user_ids of owners of this exploration. owner_ids = ndb.StringProperty(indexed=True, repeated=True) # The user_ids of users who are allowed to edit this exploration. editor_ids = ndb.StringProperty(indexed=True, repeated=True) # The user_ids of users who are allowed to voiceover this exploration. voice_artist_ids = ndb.StringProperty(indexed=True, repeated=True) # The user_ids of users who are allowed to view this exploration. viewer_ids = ndb.StringProperty(indexed=True, repeated=True) # Whether this exploration is owned by the community. community_owned = ndb.BooleanProperty(indexed=True, default=False) # The exploration id which this exploration was cloned from. If None, this # exploration was created from scratch. cloned_from = ndb.StringProperty() # For private explorations, whether this exploration can be viewed # by anyone who has the URL. If the exploration is not private, this # setting is ignored. viewable_if_private = ndb.BooleanProperty(indexed=True, default=False) # Time, in milliseconds, when the exploration was first published. first_published_msec = ndb.FloatProperty(indexed=True, default=None) # The publication status of this exploration. status = ndb.StringProperty( default=constants.ACTIVITY_STATUS_PRIVATE, indexed=True, choices=[ constants.ACTIVITY_STATUS_PRIVATE, constants.ACTIVITY_STATUS_PUBLIC ] ) # DEPRECATED in v2.8.3. Do not use. translator_ids = ndb.StringProperty(indexed=True, repeated=True) def save(self, committer_id, commit_message, commit_cmds): """Saves a new version of the exploration, updating the Exploration datastore model. Args: committer_id: str. The user_id of the user who committed the change. commit_message: str. The commit description message. commit_cmds: list(dict). A list of commands, describing changes made in this model, which should give sufficient information to reconstruct the commit. Each dict always contains: cmd: str. The type of the command. A full list of command types can be found in core/domain/exp_domain.py. and then additional arguments for that command. For example: {'cmd': 'AUTO_revert_version_number', 'version_number': 4} """ super(ExplorationRightsModel, self).commit( committer_id, commit_message, commit_cmds) def _trusted_commit( self, committer_id, commit_type, commit_message, commit_cmds): """Record the event to the commit log after the model commit. Note that this extends the superclass method. Args: committer_id: str. The user_id of the user who committed the change. commit_type: str. The type of commit. Possible values are in core.storage.base_models.COMMIT_TYPE_CHOICES. commit_message: str. The commit description message. commit_cmds: list(dict). A list of commands, describing changes made in this model, should give sufficient information to reconstruct the commit. Each dict always contains: cmd: str. Unique command. and then additional arguments for that command. """ super(ExplorationRightsModel, self)._trusted_commit( committer_id, commit_type, commit_message, commit_cmds) # Create and delete events will already be recorded in the # ExplorationModel. if commit_type not in ['create', 'delete']: committer_user_settings_model = ( user_models.UserSettingsModel.get_by_id(committer_id)) committer_username = ( committer_user_settings_model.username if committer_user_settings_model else '') # TODO(msl): test if put_async() leads to any problems (make # sure summary dicts get updated correctly when explorations # are changed). ExplorationCommitLogEntryModel( id=('rights-%s-%s' % (self.id, self.version)), user_id=committer_id, username=committer_username, exploration_id=self.id, commit_type=commit_type, commit_message=commit_message, commit_cmds=commit_cmds, version=None, post_commit_status=self.status, post_commit_community_owned=self.community_owned, post_commit_is_private=( self.status == constants.ACTIVITY_STATUS_PRIVATE) ).put_async() class ExplorationCommitLogEntryModel(base_models.BaseCommitLogEntryModel): """Log of commits to explorations. A new instance of this model is created and saved every time a commit to ExplorationModel or ExplorationRightsModel occurs. The id for this model is of the form 'exploration-{{EXP_ID}}-{{EXP_VERSION}}'. """ # The id of the exploration being edited. exploration_id = ndb.StringProperty(indexed=True, required=True) @classmethod def get_multi(cls, exp_id, exp_versions): """Gets the ExplorationCommitLogEntryModels for the given exploration id and exploration versions. Args: exp_id: str. The id of the exploration. exp_versions: list(int). The versions of the exploration. Returns: list(ExplorationCommitLogEntryModel). The list of ExplorationCommitLogEntryModel instances which matches the given exp_id and exp_versions. """ instance_ids = [cls._get_instance_id(exp_id, exp_version) for exp_version in exp_versions] return super(ExplorationCommitLogEntryModel, cls).get_multi( instance_ids) @classmethod def _get_instance_id(cls, exp_id, exp_version): """Returns ID of the exploration commit log entry model. Args: exp_id: str. The exploration id whose states are mapped. exp_version: int. The version of the exploration. Returns: str. A string containing exploration ID and exploration version. """ return 'exploration-%s-%s' % (exp_id, exp_version) @classmethod def get_all_non_private_commits( cls, page_size, urlsafe_start_cursor, max_age=None): """Fetches a list of all the non-private commits sorted by their last updated attribute. Args: page_size: int. The maximum number of entities to be returned. urlsafe_start_cursor: str or None. If provided, the list of returned entities starts from this datastore cursor. Otherwise, the returned entities start from the beginning of the full list of entities. max_age: datetime.timedelta. The maximum time duration within which commits are needed. Returns: 3-tuple of (results, cursor, more) which were created which were created no earlier than max_age before the current time where: results: List of query results. cursor: str or None. A query cursor pointing to the next batch of results. If there are no more results, this will be None. more: bool. If True, there are (probably) more results after this batch. If False, there are no further results after this batch. """ if not isinstance(max_age, datetime.timedelta) and max_age is not None: raise ValueError( 'max_age must be a datetime.timedelta instance or None.') query = cls.query(cls.post_commit_is_private == False) # pylint: disable=singleton-comparison if max_age: query = query.filter( cls.last_updated >= datetime.datetime.utcnow() - max_age) return cls._fetch_page_sorted_by_last_updated( query, page_size, urlsafe_start_cursor) class ExpSummaryModel(base_models.BaseModel): """Summary model for an Oppia exploration. This should be used whenever the content blob of the exploration is not needed (e.g. in search results, etc). A ExpSummaryModel instance stores the following information: id, title, category, objective, language_code, tags, last_updated, created_on, status (private, public), community_owned, owner_ids, editor_ids, viewer_ids, version. The key of each instance is the exploration id. """ # What this exploration is called. title = ndb.StringProperty(required=True) # The category this exploration belongs to. category = ndb.StringProperty(required=True, indexed=True) # The objective of this exploration. objective = ndb.TextProperty(required=True, indexed=False) # The ISO 639-1 code for the language this exploration is written in. language_code = ndb.StringProperty(required=True, indexed=True) # Tags associated with this exploration. tags = ndb.StringProperty(repeated=True, indexed=True) # Aggregate user-assigned ratings of the exploration. ratings = ndb.JsonProperty(default=None, indexed=False) # Scaled average rating for the exploration. scaled_average_rating = ndb.FloatProperty(indexed=True) # Time when the exploration model was last updated (not to be # confused with last_updated, which is the time when the # exploration *summary* model was last updated). exploration_model_last_updated = ndb.DateTimeProperty(indexed=True) # Time when the exploration model was created (not to be confused # with created_on, which is the time when the exploration *summary* # model was created). exploration_model_created_on = ndb.DateTimeProperty(indexed=True) # Time when the exploration was first published. first_published_msec = ndb.FloatProperty(indexed=True) # The publication status of this exploration. status = ndb.StringProperty( default=constants.ACTIVITY_STATUS_PRIVATE, indexed=True, choices=[ constants.ACTIVITY_STATUS_PRIVATE, constants.ACTIVITY_STATUS_PUBLIC ] ) # Whether this exploration is owned by the community. community_owned = ndb.BooleanProperty(required=True, indexed=True) # The user_ids of owners of this exploration. owner_ids = ndb.StringProperty(indexed=True, repeated=True) # The user_ids of users who are allowed to edit this exploration. editor_ids = ndb.StringProperty(indexed=True, repeated=True) # The user_ids of users who are allowed to voiceover this exploration. voice_artist_ids = ndb.StringProperty(indexed=True, repeated=True) # The user_ids of users who are allowed to view this exploration. viewer_ids = ndb.StringProperty(indexed=True, repeated=True) # The user_ids of users who have contributed (humans who have made a # positive (not just a revert) change to the exploration's content). contributor_ids = ndb.StringProperty(indexed=True, repeated=True) # A dict representing the contributors of non-trivial commits to this # exploration. Each key of this dict is a user_id, and the corresponding # value is the number of non-trivial commits that the user has made. contributors_summary = ndb.JsonProperty(default={}, indexed=False) # The version number of the exploration after this commit. Only populated # for commits to an exploration (as opposed to its rights, etc.). version = ndb.IntegerProperty() # DEPRECATED in v2.8.3. Do not use. translator_ids = ndb.StringProperty(indexed=True, repeated=True) @classmethod def get_non_private(cls): """Returns an iterable with non-private ExpSummary models. Returns: iterable. An iterable with non-private ExpSummary models. """ return ExpSummaryModel.query().filter( ExpSummaryModel.status != constants.ACTIVITY_STATUS_PRIVATE ).filter( ExpSummaryModel.deleted == False # pylint: disable=singleton-comparison ).fetch(feconf.DEFAULT_QUERY_LIMIT) @classmethod def get_top_rated(cls, limit): """Fetches the top-rated exp summaries that are public in descending order of scaled_average_rating. Args: limit: int. The maximum number of results to return. Returns: iterable. An iterable with the top rated exp summaries that are public in descending order of scaled_average_rating. """ return ExpSummaryModel.query().filter( ExpSummaryModel.status == constants.ACTIVITY_STATUS_PUBLIC ).filter( ExpSummaryModel.deleted == False # pylint: disable=singleton-comparison ).order( -ExpSummaryModel.scaled_average_rating ).fetch(limit) @classmethod def get_private_at_least_viewable(cls, user_id): """Fetches private exp summaries that are at least viewable by the given user. Args: user_id: The id of the given user. Returns: iterable. An iterable with private exp summaries that are at least viewable by the given user. """ return ExpSummaryModel.query().filter( ExpSummaryModel.status == constants.ACTIVITY_STATUS_PRIVATE ).filter( ndb.OR(ExpSummaryModel.owner_ids == user_id, ExpSummaryModel.editor_ids == user_id, ExpSummaryModel.voice_artist_ids == user_id, ExpSummaryModel.viewer_ids == user_id) ).filter( ExpSummaryModel.deleted == False # pylint: disable=singleton-comparison ).fetch(feconf.DEFAULT_QUERY_LIMIT) @classmethod def get_at_least_editable(cls, user_id): """Fetches exp summaries that are at least editable by the given user. Args: user_id: The id of the given user. Returns: iterable. An iterable with exp summaries that are at least editable by the given user. """ return ExpSummaryModel.query().filter( ndb.OR(ExpSummaryModel.owner_ids == user_id, ExpSummaryModel.editor_ids == user_id) ).filter( ExpSummaryModel.deleted == False # pylint: disable=singleton-comparison ).fetch(feconf.DEFAULT_QUERY_LIMIT) @classmethod def get_recently_published(cls, limit): """Fetches exp summaries that are recently published. Args: limit: int. The maximum number of results to return. Returns: An iterable with exp summaries that are recently published. The returned list is sorted by the time of publication with latest being first in the list. """ return ExpSummaryModel.query().filter( ExpSummaryModel.status == constants.ACTIVITY_STATUS_PUBLIC ).filter( ExpSummaryModel.deleted == False # pylint: disable=singleton-comparison ).order( -ExpSummaryModel.first_published_msec ).fetch(limit) class StateIdMappingModel(base_models.BaseModel): """DEPRECATED: DO NOT USE. State ID model for Oppia explorations. This model maps each exploration version's state to a unique id. Note: use the state id only for derived data, but not for data that’s regarded as the source of truth, as the rules for assigning state id may change in future. The key of each instance is a combination of exploration id and version. """ # The exploration id whose states are mapped. exploration_id = ndb.StringProperty(indexed=True, required=True) # The version of the exploration. exploration_version = ndb.IntegerProperty(indexed=True, required=True) # A dict which maps each state name to a unique id. state_names_to_ids = ndb.JsonProperty(required=True) # Latest state id that has been assigned to any of the states in any of # of the versions of given exploration. New state IDs should be assigned # from this value + 1. largest_state_id_used = ndb.IntegerProperty(indexed=True, required=True) @classmethod def create( cls, exp_id, exp_version, state_names_to_ids, largest_state_id_used, overwrite=False): """Creates a new instance of state id mapping model. Args: exp_id: str. The exploration id whose states are mapped. exp_version: int. The version of that exploration. state_names_to_ids: dict. A dict storing state name to ids mapping. largest_state_id_used: int. The largest integer so far that has been used as a state ID for this exploration. overwrite: bool. Whether overwriting of an existing model should be allowed. Returns: StateIdMappingModel. Instance of the state id mapping model. """ instance_id = cls._generate_instance_id(exp_id, exp_version) if not overwrite and cls.get_by_id(instance_id): raise Exception( 'State id mapping model already exists for exploration %s,' ' version %d' % (exp_id, exp_version)) model = cls( id=instance_id, exploration_id=exp_id, exploration_version=exp_version, state_names_to_ids=state_names_to_ids, largest_state_id_used=largest_state_id_used) model.put() return model @classmethod def _generate_instance_id(cls, exp_id, exp_version): """Generates ID of the state id mapping model instance. Args: exp_id: str. The exploration id whose states are mapped. exp_version: int. The version of the exploration. Returns: str. A string containing exploration ID and exploration version. """ return '%s.%d' % (exp_id, exp_version) @classmethod def get_state_id_mapping_model(cls, exp_id, exp_version): """Retrieve state id mapping model from the datastore. Args: exp_id: str. The exploration id. exp_version: int. The exploration version. Returns: StateIdMappingModel. The model retrieved from the datastore. """ instance_id = cls._generate_instance_id(exp_id, exp_version) instance = cls.get(instance_id) return instance @classmethod def delete_state_id_mapping_models(cls, exp_id, exp_versions): """Removes state id mapping models present in state_id_mapping_models. Args: exp_id: str. The id of the exploration. exp_versions: list(int). A list of exploration versions for which the state id mapping model is to be deleted. """ keys = [ ndb.Key(cls, cls._generate_instance_id(exp_id, exp_version)) for exp_version in exp_versions] ndb.delete_multi(keys)
souravbadami/oppia
core/storage/exploration/gae_models.py
Python
apache-2.0
26,280
/* * Copyright 2010-2017 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. */ #pragma once #include <aws/alexaforbusiness/AlexaForBusiness_EXPORTS.h> #include <aws/core/AmazonSerializableWebServiceRequest.h> #include <aws/core/utils/UnreferencedParam.h> #include <aws/core/http/HttpRequest.h> namespace Aws { namespace AlexaForBusiness { class AWS_ALEXAFORBUSINESS_API AlexaForBusinessRequest : public Aws::AmazonSerializableWebServiceRequest { public: virtual ~AlexaForBusinessRequest () {} virtual Aws::String SerializePayload() const override = 0; void AddParametersToRequest(Aws::Http::HttpRequest& httpRequest) const { AWS_UNREFERENCED_PARAM(httpRequest); } inline Aws::Http::HeaderValueCollection GetHeaders() const override { auto headers = GetRequestSpecificHeaders(); if(headers.size() == 0 || (headers.size() > 0 && headers.count(Aws::Http::CONTENT_TYPE_HEADER) == 0)) { headers.insert(Aws::Http::HeaderValuePair(Aws::Http::CONTENT_TYPE_HEADER, Aws::AMZN_JSON_CONTENT_TYPE_1_1 )); } return headers; } protected: virtual Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const { return Aws::Http::HeaderValueCollection(); } }; } // namespace AlexaForBusiness } // namespace Aws
JoyIfBam5/aws-sdk-cpp
aws-cpp-sdk-alexaforbusiness/include/aws/alexaforbusiness/AlexaForBusinessRequest.h
C
apache-2.0
1,781
package com.devl.development.dockingbox.pdb; import org.biojava.bio.structure.*; import java.util.List; import java.util.Vector; /** * Copyright 2014 Dev Lakhani * <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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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. */ public class PDBStructureUtils { /** * Returns a given chain in a structure assuming that the chain ID's are unique * * @param structure * @param chainId */ public static Chain getChainFromStructure(Structure structure, String chainId) { for (Chain c : structure.getChains()) { System.out.println("Chain " + c.getName() + " details:"); System.out.println("Atom ligands: " + c.getAtomSequence()); if (c.getChainID().equals(chainId)) { return c; } } return null; } public static List<Atom> getAminoAtomsFromChain(Chain chain, int[] residuePositions) throws PDBStructureUtilsException { List<Group> groups = chain.getAtomGroups("amino"); List<Atom> allAtoms = new Vector<Atom>(); for (Group group : groups) { if (group instanceof AminoAcidImpl) { AminoAcidImpl aa = (AminoAcidImpl) group; for (int position : residuePositions) { //only select atoms for the residues we are interesed in if (aa.getResidueNumber().getSeqNum() == position) { allAtoms.addAll(aa.getAtoms()); System.out.println("Selecting Amino Acid " + aa.getAminoType() + " in chain" + chain.getChainID()); } } } else if (group instanceof AminoAcid) { AminoAcid aa = (AminoAcid) group; for (int position : residuePositions) { //only select atoms for the residues we are interesed in if (aa.getResidueNumber().getSeqNum() == position) { allAtoms.addAll(aa.getAtoms()); System.out.println("Selecting Amino Acid " + aa.getPDBName() + " in chain" + chain.getChainID()); } } } } if (allAtoms.isEmpty()) { throw new PDBStructureUtilsException("No matching atoms found "); } return allAtoms; } /** * Entry point to locate bounding box for a PDB structure given residue positions and a chain id. * The returned value is the width, height, depth of the box and its centre coordinates. Applys nt "padding" to * the box, the box is strictly bound to the selected amino acids * * @param structure * @param chainId * @param residues * @return double[] in the form of [maxX - minX, maxY - minY, maxZ - minZ, centreX, centreY, centreZ] */ public static double[] getBoundingBox(Structure structure, String chainId, int[] residues) throws PDBStructureUtilsException { return getBoundingBox(getAminoAtomsFromChain(getChainFromStructure(structure, chainId), residues),0 ); } /** * Entry point to locate bounding box for a PDB structure given residue positions and a chain id. * The returned value is the width, height, depth of the box and its centre coordinates. * * @param structure * @param chainId * @param residues * @param padding the extra room (in Angstroms) to leave for ligand translation and rotation * @return double[] in the form of [maxX - minX, maxY - minY, maxZ - minZ, centreX, centreY, centreZ] */ public static double[] getBoundingBoxWithPadding(Structure structure, String chainId, int[] residues,double padding) throws PDBStructureUtilsException { return getBoundingBox(getAminoAtomsFromChain(getChainFromStructure(structure, chainId), residues),padding ); } /** * Locates the maximum and minimum atomic positions and derives a bounding box centered around the residues of interest * * @param paddingInAngstroms the additional space to leave to allow ligand rotation, translation * @param atoms * @return */ public static double[] getBoundingBox(List<Atom> atoms, double paddingInAngstroms) { double minX = Double.POSITIVE_INFINITY; double maxX = Double.NEGATIVE_INFINITY; double minY = Double.POSITIVE_INFINITY; double maxY = Double.NEGATIVE_INFINITY; double minZ = Double.POSITIVE_INFINITY; double maxZ = Double.NEGATIVE_INFINITY; for (Atom atom : atoms) { if (atom.getX() < minX) { minX = atom.getX(); } if (atom.getX() > maxX) { maxX = atom.getX(); } if (atom.getY() < minY) { minY = atom.getY(); } if (atom.getY() > maxY) { maxY = atom.getY(); } if (atom.getZ() < minZ) { minZ = atom.getZ(); } if (atom.getZ() > maxZ) { maxZ = atom.getZ(); } } minX-=paddingInAngstroms; minY-=paddingInAngstroms; minZ-=paddingInAngstroms; maxX+=paddingInAngstroms; maxY+=paddingInAngstroms; maxZ+=paddingInAngstroms; double centreX = ((maxX - minX) / 2.0) + minX; double centreY = ((maxY - minY) / 2.0) + minY; double centreZ = ((maxZ - minZ) / 2.0) + minZ; double width = maxX - minX; double height = maxY - minY; double depth = maxZ - minZ; return new double[]{width, height, depth, centreX, centreY, centreZ}; } }
devldevelopment/dockingbox
src/main/java/com/devl/development/dockingbox/pdb/PDBStructureUtils.java
Java
apache-2.0
6,152
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Concurrent; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Reflection; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.E2ETesting; using Microsoft.Extensions.Internal; using Xunit.Abstractions; using Xunit.Sdk; namespace Microsoft.AspNetCore.E2ETesting { public class SauceConnectServer : IDisposable { private static readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1); private Process _process; private string _sentinelPath; private Process _sentinelProcess; private static IMessageSink _diagnosticsMessageSink; // 2h private const int SauceConnectProcessTimeout = 7200; public SauceConnectServer(IMessageSink diagnosticsMessageSink) { if (Instance != null || _diagnosticsMessageSink != null) { throw new InvalidOperationException("Sauce connect singleton already created."); } // The assembly level attribute AssemblyFixture takes care of this being being instantiated before tests run // and disposed after tests are run, gracefully shutting down the server when possible by calling Dispose on // the singleton. Instance = this; _diagnosticsMessageSink = diagnosticsMessageSink; } private void Initialize( Process process, string sentinelPath, Process sentinelProcess) { _process = process; _sentinelPath = sentinelPath; _sentinelProcess = sentinelProcess; } internal static SauceConnectServer Instance { get; private set; } public static async Task StartAsync(ITestOutputHelper output) { try { await _semaphore.WaitAsync(); if (Instance._process == null) { // No process was started, meaning the instance wasn't initialized. await InitializeInstance(output); } } finally { _semaphore.Release(); } } private static async Task InitializeInstance(ITestOutputHelper output) { var psi = new ProcessStartInfo { FileName = "npm", Arguments = "run sauce --" + $" --sauce-user {E2ETestOptions.Instance.Sauce.Username}" + $" --sauce-key {E2ETestOptions.Instance.Sauce.AccessKey}" + $" --sauce-tunnel {E2ETestOptions.Instance.Sauce.TunnelIdentifier}" + $" --use-hostname {E2ETestOptions.Instance.Sauce.HostName}", RedirectStandardOutput = true, RedirectStandardError = true, }; if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { psi.FileName = "cmd"; psi.Arguments = $"/c npm {psi.Arguments}"; } // It's important that we get the folder value before we start the process to prevent // untracked processes when the tracking folder is not correctly configure. var trackingFolder = GetProcessTrackingFolder(); if (!Directory.Exists(trackingFolder)) { throw new InvalidOperationException($"Invalid tracking folder. Set the 'SauceConnectProcessTrackingFolder' MSBuild property to a valid folder."); } Process process = null; Process sentinel = null; string pidFilePath = null; try { process = Process.Start(psi); pidFilePath = await WriteTrackingFileAsync(output, trackingFolder, process); sentinel = StartSentinelProcess(process, pidFilePath, SauceConnectProcessTimeout); } catch { ProcessCleanup(process, pidFilePath); ProcessCleanup(sentinel, pidFilePath: null); throw; } // Log output for sauce connect process. // This is for the case where the server fails to launch. var logOutput = new BlockingCollection<string>(); process.OutputDataReceived += LogOutput; process.ErrorDataReceived += LogOutput; process.BeginOutputReadLine(); process.BeginErrorReadLine(); // The Sauce connect server has to be up for the entirety of the tests and is only shutdown when the application (i.e. the test) exits. AppDomain.CurrentDomain.ProcessExit += (sender, args) => ProcessCleanup(process, pidFilePath); // Log void LogOutput(object sender, DataReceivedEventArgs e) { logOutput.TryAdd(e.Data); // We avoid logging on the output here because it is unreliable. We can only log in the diagnostics sink. lock (_diagnosticsMessageSink) { _diagnosticsMessageSink.OnMessage(new DiagnosticMessage(e.Data)); } } var uri = new UriBuilder("http", E2ETestOptions.Instance.Sauce.HostName, 4445).Uri; var httpClient = new HttpClient { Timeout = TimeSpan.FromSeconds(1), }; var retries = 0; do { await Task.Delay(1000); try { var response = await httpClient.GetAsync(uri); if (response.StatusCode == HttpStatusCode.OK) { output = null; Instance.Initialize(process, pidFilePath, sentinel); return; } } catch (OperationCanceledException) { } catch (HttpRequestException) { } retries++; } while (retries < 30); // Make output null so that we stop logging to it. output = null; logOutput.CompleteAdding(); var exitCodeString = process.HasExited ? process.ExitCode.ToString(CultureInfo.InvariantCulture) : "Process has not yet exited."; var message = $@"Failed to launch the server. ExitCode: {exitCodeString} Captured output lines: {string.Join(Environment.NewLine, logOutput.GetConsumingEnumerable())}."; // If we got here, we couldn't launch Sauce connect or get it to respond. So shut it down. ProcessCleanup(process, pidFilePath); throw new InvalidOperationException(message); } private static Process StartSentinelProcess(Process process, string sentinelFile, int timeout) { // This sentinel process will start and will kill any rouge sauce connect server that wasn't torn down via normal means. var psi = new ProcessStartInfo { FileName = "powershell", Arguments = $"-NoProfile -NonInteractive -Command \"Start-Sleep {timeout}; " + $"if(Test-Path {sentinelFile}){{ " + $"Write-Output 'Stopping process {process.Id}'; Stop-Process {process.Id}; }}" + $"else{{ Write-Output 'Sentinel file {sentinelFile} not found.'}}", }; return Process.Start(psi); } private static void ProcessCleanup(Process process, string pidFilePath) { try { if (process?.HasExited == false) { try { process?.KillTree(TimeSpan.FromSeconds(10)); process?.Dispose(); } catch { // Ignore errors here since we can't do anything } } if (pidFilePath != null && File.Exists(pidFilePath)) { File.Delete(pidFilePath); } } catch { // Ignore errors here since we can't do anything } } private static async Task<string> WriteTrackingFileAsync(ITestOutputHelper output, string trackingFolder, Process process) { var pidFile = Path.Combine(trackingFolder, $"{process.Id}.{Guid.NewGuid()}.pid"); for (var i = 0; i < 3; i++) { try { await File.WriteAllTextAsync(pidFile, process.Id.ToString(CultureInfo.InvariantCulture)); return pidFile; } catch { output.WriteLine($"Can't write file to process tracking folder: {trackingFolder}"); } } throw new InvalidOperationException($"Failed to write file for process {process.Id}"); } private static string GetProcessTrackingFolder() => typeof(SauceConnectServer).Assembly .GetCustomAttributes<AssemblyMetadataAttribute>() .Single(a => a.Key == "Microsoft.AspNetCore.Testing.SauceConnect.ProcessTracking").Value; public void Dispose() { ProcessCleanup(_process, _sentinelPath); ProcessCleanup(_sentinelProcess, pidFilePath: null); } } }
aspnet/AspNetCore
src/Shared/E2ETesting/SauceConnectServer.cs
C#
apache-2.0
9,894
using System; using System.Globalization; using System.Linq; using System.Reflection; using System.Web.Http.Controllers; using System.Web.Http.Description; using System.Xml.XPath; using WebApi2.Areas.HelpPage.ModelDescriptions; namespace WebApi2.Areas.HelpPage { /// <summary> /// A custom <see cref="IDocumentationProvider"/> that reads the API documentation from an XML documentation file. /// </summary> public class XmlDocumentationProvider : IDocumentationProvider, IModelDocumentationProvider { private XPathNavigator _documentNavigator; private const string TypeExpression = "/doc/members/member[@name='T:{0}']"; private const string MethodExpression = "/doc/members/member[@name='M:{0}']"; private const string PropertyExpression = "/doc/members/member[@name='P:{0}']"; private const string FieldExpression = "/doc/members/member[@name='F:{0}']"; private const string ParameterExpression = "param[@name='{0}']"; /// <summary> /// Initializes a new instance of the <see cref="XmlDocumentationProvider"/> class. /// </summary> /// <param name="documentPath">The physical path to XML document.</param> public XmlDocumentationProvider(string documentPath) { if (documentPath == null) { throw new ArgumentNullException("documentPath"); } XPathDocument xpath = new XPathDocument(documentPath); _documentNavigator = xpath.CreateNavigator(); } public string GetDocumentation(HttpControllerDescriptor controllerDescriptor) { XPathNavigator typeNode = GetTypeNode(controllerDescriptor.ControllerType); return GetTagValue(typeNode, "summary"); } public virtual string GetDocumentation(HttpActionDescriptor actionDescriptor) { XPathNavigator methodNode = GetMethodNode(actionDescriptor); return GetTagValue(methodNode, "summary"); } public virtual string GetDocumentation(HttpParameterDescriptor parameterDescriptor) { ReflectedHttpParameterDescriptor reflectedParameterDescriptor = parameterDescriptor as ReflectedHttpParameterDescriptor; if (reflectedParameterDescriptor != null) { XPathNavigator methodNode = GetMethodNode(reflectedParameterDescriptor.ActionDescriptor); if (methodNode != null) { string parameterName = reflectedParameterDescriptor.ParameterInfo.Name; XPathNavigator parameterNode = methodNode.SelectSingleNode(String.Format(CultureInfo.InvariantCulture, ParameterExpression, parameterName)); if (parameterNode != null) { return parameterNode.Value.Trim(); } } } return null; } public string GetResponseDocumentation(HttpActionDescriptor actionDescriptor) { XPathNavigator methodNode = GetMethodNode(actionDescriptor); return GetTagValue(methodNode, "returns"); } public string GetDocumentation(MemberInfo member) { string memberName = String.Format(CultureInfo.InvariantCulture, "{0}.{1}", GetTypeName(member.DeclaringType), member.Name); string expression = member.MemberType == MemberTypes.Field ? FieldExpression : PropertyExpression; string selectExpression = String.Format(CultureInfo.InvariantCulture, expression, memberName); XPathNavigator propertyNode = _documentNavigator.SelectSingleNode(selectExpression); return GetTagValue(propertyNode, "summary"); } public string GetDocumentation(Type type) { XPathNavigator typeNode = GetTypeNode(type); return GetTagValue(typeNode, "summary"); } private XPathNavigator GetMethodNode(HttpActionDescriptor actionDescriptor) { ReflectedHttpActionDescriptor reflectedActionDescriptor = actionDescriptor as ReflectedHttpActionDescriptor; if (reflectedActionDescriptor != null) { string selectExpression = String.Format(CultureInfo.InvariantCulture, MethodExpression, GetMemberName(reflectedActionDescriptor.MethodInfo)); return _documentNavigator.SelectSingleNode(selectExpression); } return null; } private static string GetMemberName(MethodInfo method) { string name = String.Format(CultureInfo.InvariantCulture, "{0}.{1}", GetTypeName(method.DeclaringType), method.Name); ParameterInfo[] parameters = method.GetParameters(); if (parameters.Length != 0) { string[] parameterTypeNames = parameters.Select(param => GetTypeName(param.ParameterType)).ToArray(); name += String.Format(CultureInfo.InvariantCulture, "({0})", String.Join(",", parameterTypeNames)); } return name; } private static string GetTagValue(XPathNavigator parentNode, string tagName) { if (parentNode != null) { XPathNavigator node = parentNode.SelectSingleNode(tagName); if (node != null) { return node.Value.Trim(); } } return null; } private XPathNavigator GetTypeNode(Type type) { string controllerTypeName = GetTypeName(type); string selectExpression = String.Format(CultureInfo.InvariantCulture, TypeExpression, controllerTypeName); return _documentNavigator.SelectSingleNode(selectExpression); } private static string GetTypeName(Type type) { string name = type.FullName; if (type.IsGenericType) { // Format the generic type name to something like: Generic{System.Int32,System.String} Type genericType = type.GetGenericTypeDefinition(); Type[] genericArguments = type.GetGenericArguments(); string genericTypeName = genericType.FullName; // Trim the generic parameter counts from the name genericTypeName = genericTypeName.Substring(0, genericTypeName.IndexOf('`')); string[] argumentTypeNames = genericArguments.Select(t => GetTypeName(t)).ToArray(); name = String.Format(CultureInfo.InvariantCulture, "{0}{{{1}}}", genericTypeName, String.Join(",", argumentTypeNames)); } if (type.IsNested) { // Changing the nested type name from OuterType+InnerType to OuterType.InnerType to match the XML documentation syntax. name = name.Replace("+", "."); } return name; } } }
optimized4u/WebAPICRUD
WebApi2/WebApi2/Areas/HelpPage/XmlDocumentationProvider.cs
C#
apache-2.0
7,018
(function(){ // hide everything externally to avoid name collisions // whether to display debugging output var svgDebug = true; // whether we are locally debugging (i.e. the page is downloaded to our // hard drive and served from a local server to ease development) var localDebug = true; // the full URL to where svg.js is located // Note: Update this before putting on production var svgSrcURL; if (localDebug) { svgSrcURL = 'http://brad.com:8080/src/svg.js'; //svgSrcURL = '/src/svg.js'; } else { svgSrcURL = 'http://codinginparadise.org/projects/svgweb-staging/src/svg.js'; } // whether the pan and zoom UI is initialized var svgUIReady = false; // a reference to the SVG OBJECT on the page var svgObject; // a reference to our zoom and pan controls var svgControls; // a reference to our SVG root tag var svgRoot; var isWebkit = (Math.max(navigator.appVersion.indexOf('WebKit'), navigator.appVersion.indexOf('Safari'), 0)); var isFF = false; if (navigator.userAgent.indexOf('Gecko') >= 0) { isFF = parseFloat(navigator.userAgent.split('Firefox/')[1]) || undefined; } // the URL to the proxy from which we can fetch SVG images within the same // domain as this page is served from // TODO: define once a proxy or API call is setup // the location of our images var imageBundle; if (localDebug) { // for local debugging var imageRoot = 'http://127.0.0.1:8080/tests/non-licensed/wikipedia/svgzoom/svgzoom-images/'; imageBundle = { 'searchtool': imageRoot + 'searchtool.png', 'controls-north-mini': imageRoot + 'north-mini.png', 'controls-west-mini': imageRoot + 'west-mini.png', 'controls-east-mini': imageRoot + 'east-mini.png', 'controls-south-mini': imageRoot + 'south-mini.png', 'controls-zoom-plus-mini': imageRoot + 'zoom-plus-mini.png', 'controls-zoom-world-mini': imageRoot + 'zoom-world-mini.png', 'controls-zoom-minus-mini': imageRoot + 'zoom-minus-mini.png' }; } else { // Note: update this before putting on production var imageRoot = 'http://codinginparadise.org/projects/svgweb-staging/tests/non-licensed/wikipedia/svgzoom/svgzoom-images/'; imageBundle = { 'searchtool': imageRoot + 'searchtool.png', 'controls-north-mini': imageRoot + 'north-mini.png', 'controls-west-mini': imageRoot + 'west-mini.png', 'controls-east-mini': imageRoot + 'east-mini.png', 'controls-south-mini': imageRoot + 'south-mini.png', 'controls-zoom-plus-mini': imageRoot + 'zoom-plus-mini.png', 'controls-zoom-world-mini': imageRoot + 'zoom-world-mini.png', 'controls-zoom-minus-mini': imageRoot + 'zoom-minus-mini.png' }; } // determines if we are at a Wikimedia Commons detail page for an SVG file function isSVGPage() { if (wgNamespaceNumber == 6 && wgTitle && wgTitle.indexOf('.svg') != -1 && wgAction == 'view') { return true; } else { return false; } } // Determines whether this page has image annotation enabled (i.e. the // Add Note button). If this is enabled the DOM changes slightly and we have // to account for it. Some SVG images have this (Tux.svg); others don't // (Commons-logo.svg, for example). function hasAnnotation() { if (document.getElementById('ImageAnnotationAddButton')) { return true; } else { return false; } } // inserts the SVG Web library into the page function insertSVGWeb() { document.write('<script type="text/javascript" ' + 'src="' + svgSrcURL + '" ' + 'data-path="../../../../src" ' /* Note: remove before production */ + 'data-debug="' + svgDebug + '"></script>'); } // adds a button that when pressed turns on the zoom and pan UI function addStartButton() { // are we already present? user could have hit back button on an old // loaded page if (document.getElementById('SVGZoom.startButton')) { return; } // insert ourselves beside the SVG thumbnail area var info = getSVGInfo(); var thumbnail = info.fileNode; if (hasAnnotation()) { thumbnail = thumbnail.childNodes[0].childNodes[0]; } // make the container element we will go into a bit larger to accommodate // the icon var infoWidth = Number(String(info.width).replace('px', '')); thumbnail.style.width = (infoWidth + 30) + 'px'; var img = document.createElement('img'); img.id = 'SVGZoom.startButton'; img.src = imageBundle['searchtool']; img.setAttribute('width', '30px'); img.setAttribute('height', '30px'); img.style.position = 'absolute'; img.style.cursor = 'pointer'; img.onclick = initUI; // some SVG pages have a spurious <br/> element; add before that if (thumbnail.lastChild.nodeType == 1 && thumbnail.lastChild.nodeName.toLowerCase() == 'br') { thumbnail.insertBefore(img, thumbnail.lastChild); } else { thumbnail.appendChild(img); } } // adds the pan and zoom UI and turns the PNG into an SVG object function initUI() { if (svgUIReady) { // already initialized return; } svgUIReady = true; // remove magnifying glass icon var startButton = document.getElementById('SVGZoom.startButton'); startButton.parentNode.removeChild(startButton); // get the thumbnail container and make it invisible var info = getSVGInfo(); var thumbnail = info.fileNode; if (hasAnnotation()) { thumbnail = thumbnail.childNodes[0].childNodes[0]; } var oldPNG = thumbnail.childNodes[0]; oldPNG.style.visibility = 'hidden'; oldPNG.style.zIndex = -1000; // store a reference to the SVG root to make subsequent accesses faster svgRoot = svgObject.contentDocument.rootElement; // Safari/Native has a bug where it doesn't respect the height/width of // the OBJECT when scaling the size of some objects (commons-logo.svg, // for example). A workaround is to manually set the size inside the SVG. if (isWebkit) { svgRoot.setAttribute('width', info.width); svgRoot.setAttribute('height', info.height); } // reveal the SVG object and controls svgObject.parentNode.style.zIndex = 1000; svgControls.style.display = 'block'; // make the cursor a hand when over the SVG; not all browsers support // this property yet svgRoot.setAttribute('cursor', 'pointer'); // TODO: Get hand cursor showing up in SVG Web's Flash renderer // add drag listeners on the SVG root svgRoot.addEventListener('mousedown', mouseDown, false); svgRoot.addEventListener('mousemove', mouseMove, false); svgRoot.addEventListener('mouseup', mouseUp, false); } // Creates the SVG OBJECT during page load so that when we swap the PNG // thumbnail and the SVG OBJECT it happens much faster function createSVGObject() { var info = getSVGInfo(); var thumbnail = info.fileNode; if (hasAnnotation()) { thumbnail = thumbnail.childNodes[0].childNodes[0]; } // create the SVG OBJECT that will replace our thumbnail container var obj = document.createElement('object', true); obj.setAttribute('type', 'image/svg+xml'); obj.setAttribute('data', info.url); obj.setAttribute('width', info.width); obj.setAttribute('height', info.height); obj.addEventListener('load', function() { // store a reference to the SVG OBJECT svgObject = this; // create the controls svgControls = createControls(); svgControls.style.display = 'none'; // now place the controls on top of the SVG object if (thumbnail.lastChild.nodeType == 1 && thumbnail.lastChild.nodeName.toLowerCase() == 'br') { thumbnail.insertBefore(svgControls, thumbnail.lastChild); } else { thumbnail.appendChild(svgControls); } // add our magnification icon addStartButton(); // set up the mouse scroll wheel; FF 3.5/Native has an annoying bug // where DOMMouseScroll events do not propagate to OBJECTs under // some situations! if (isFF && svgweb.getHandlerType() == 'native') { hookEvent(svgObject.contentDocument.rootElement, 'mousewheel', MouseWheel); } else { hookEvent('file', 'mousewheel', MouseWheel); } // prevent IE memory leaks thumbnail = obj = null; }, false); // ensure that the thumbnail container has relative positioning; this will // reset our absolutely positioned elements to be relative to our parent // so we have correct coordinates thumbnail.style.position = 'relative'; // position object behind the PNG image; do it in a DIV to avoid any // strange style + OBJECT interactions var container = document.createElement('div'); container.id = 'SVGZoom.container'; container.style.zIndex = -1000; container.style.position = 'absolute'; // FIXME: This is a hack; figure out why the Flash version of Commons-logo.svg // is off by one 1 pixel on x and y if (!hasAnnotation() && svgweb.getHandlerType() == 'flash') { container.style.top = '-1px'; container.style.left = '-1px'; } else { container.style.top = '0px'; container.style.left = '0px'; } if (thumbnail.lastChild.nodeType == 1 && thumbnail.lastChild.nodeName.toLowerCase() == 'br') { thumbnail.insertBefore(container, thumbnail.lastChild); } else { thumbnail.appendChild(container); } svgweb.appendChild(obj, container); } // Returns a DIV ready to append to the page with our zoom and pan controls function createControls() { var controls = document.createElement('div'); controls.id = 'SVGZoom.controls'; controls.innerHTML = '<div style="position: absolute; left: 4px; top: 4px; z-index: 1004;" unselectable="on">' + '<div id="SVGZoom.panup" style="position: absolute; left: 13px; top: 4px; width: 18px; height: 18px;">' + ' <img id="SVGZoom.panup.innerImage" style="position: relative; width: 18px; height: 18px;" ' + 'src="' + imageBundle['controls-north-mini'] + '"/>' + '</div>' + '<div id="SVGZoom.panleft" style="position: absolute; left: 4px; top: 22px; width: 18px; height: 18px;">' + ' <img id="SVGZoom.panleft.innerImage" style="position: relative; width: 18px; height: 18px;" ' + 'src="' + imageBundle['controls-west-mini'] + '"/>' + '</div>' + '<div id="SVGZoom.panright" style="position: absolute; left: 22px; top: 22px; width: 18px; height: 18px;">' + ' <img id="SVGZoom.panright.innerImage" style="position: relative; width: 18px; height: 18px;" ' + 'src="' + imageBundle['controls-east-mini'] + '"/>' + '</div>' + '<div id="SVGZoom.pandown" style="position: absolute; left: 13px; top: 40px; width: 18px; height: 18px;">' + ' <img id="SVGZoom.pandown.innerImage" style="position: relative; width: 18px; height: 18px;" ' + 'src="' + imageBundle['controls-south-mini'] + '"/>' + '</div>' + '<div id="SVGZoom.zoomin" style="position: absolute; left: 13px; top: 63px; width: 18px; height: 18px;">' + ' <img id="SVGZoom.zoomin.innerImage" style="position: relative; width: 18px; height: 18px;" ' + 'src="' + imageBundle['controls-zoom-plus-mini'] + '"/>' + '</div>' + '<div id="SVGZoom.zoomworld" style="position: absolute; left: 13px; top: 81px; width: 18px; height: 18px;">' + ' <img id="SVGZoom.zoomworld.innerImage" style="position: relative; width: 18px; height: 18px;" ' + 'src="' + imageBundle['controls-zoom-world-mini'] + '"/>' + '</div>' + '<div id="SVGZoom.zoomout" style="position: absolute; left: 13px; top: 99px; width: 18px; height: 18px;">' + ' <img id="SVGZoom.zoomout.innerImage" style="position: relative; width: 18px; height: 18px;" ' + 'src="' + imageBundle['controls-zoom-minus-mini'] + '"/>' + '</div>' + '</div>'; // attach event handlers controls.childNodes[0].childNodes[0].onclick = panUp; controls.childNodes[0].childNodes[1].onclick = panLeft; controls.childNodes[0].childNodes[2].onclick = panRight; controls.childNodes[0].childNodes[3].onclick = panDown; controls.childNodes[0].childNodes[4].onclick = zoomIn; controls.childNodes[0].childNodes[5].onclick = zoomWorld; controls.childNodes[0].childNodes[6].onclick = zoomOut; return controls; } function panUp() { svgRoot.currentTranslate.setY(svgRoot.currentTranslate.getY() - 25); } function panLeft() { svgRoot.currentTranslate.setX(svgRoot.currentTranslate.getX() - 25); } function panRight() { svgRoot.currentTranslate.setX(svgRoot.currentTranslate.getX() + 25); } function panDown() { svgRoot.currentTranslate.setY(svgRoot.currentTranslate.getY() + 25); } function zoomIn() { svgRoot.currentScale = svgRoot.currentScale * 1.1; } function zoomWorld() { svgRoot.currentScale = 1; svgRoot.currentTranslate.setXY(0, 0); } function zoomOut() { svgRoot.currentScale = svgRoot.currentScale / 1.1; } // variables used for dragging var x, y, rootX, rootY; var dragX = 0, dragY = 0; var dragging = false; function mouseDown(evt) { dragging = true; x = evt.clientX; y = evt.clientY; rootX = svgRoot.currentTranslate.getX(); rootY = svgRoot.currentTranslate.getY(); evt.preventDefault(true); } function mouseMove(evt) { if (!dragging) { return; } dragX = evt.clientX - x; dragY = evt.clientY - y; // Firefox and Webkit differ on the coordinates they return; Firefox // returns the mouse coordinates with no scaling, while Webkit and SVG Web // scale the mouse coordinates using the currentScale if (isWebkit || svgweb.getHandlerType() == 'flash') { dragX /= svgRoot.currentScale; dragY /= svgRoot.currentScale; } var newX = rootX + dragX; var newY = rootY + dragY; svgRoot.currentTranslate.setXY(newX, newY); evt.preventDefault(true); } function mouseUp(evt) { dragging = false; evt.preventDefault(true); } // Returns a data structure that has info about the SVG file on this page, including: // url - filename and URL necessary to fetch the SVG file // width and height - the width and height to make the SVG file // fileNode - the DOM node that has the top level PNG thumbnail in it to replace // imgNode - the actual IMG tag that has the PNG thumbnail inside of it // Note that this method returns null if there is no file node on the page. function getSVGInfo() { var fileNode = document.getElementById('file'); if (!fileNode) { return null; } var url; if (hasAnnotation()) { url = fileNode.childNodes[0].childNodes[0].childNodes[0].href; } else { url = fileNode.childNodes[0].href; } var imgNode = fileNode.getElementsByTagName('img')[0]; var width = imgNode.getAttribute('width'); var height = imgNode.getAttribute('height'); return { url: url, fileNode: fileNode, imgNode: imgNode, width: width, height: height }; } // Mousewheel Scrolling thanks to // http://blog.paranoidferret.com/index.php/2007/10/31/javascript-tutorial-the-scroll-wheel/ function hookEvent(element, eventName, callback) { if (typeof(element) == 'string') { element = document.getElementById(element); } if (element == null) { return; } if (element.addEventListener) { if (eventName == 'mousewheel') { element.addEventListener('DOMMouseScroll', callback, false); } element.addEventListener(eventName, callback, false); } else if (element.attachEvent) { element.attachEvent("on" + eventName, callback); } } function MouseWheel(e) { e = e ? e : window.event; var wheelData = e.detail ? e.detail * -1 : e.wheelDelta; if (wheelData > 0) { zoomIn(); } else { zoomOut(); } if (e.preventDefault) { e.preventDefault(); } return false; } // called when the page is loaded and ready to be manipulated function pageLoaded() { svgweb.addOnLoad(createSVGObject); } if (isSVGPage()) { insertSVGWeb(); addOnloadHook(pageLoaded); } // hide internal implementation details inside of a closure })();
leymannx/svgweb
tests/non-licensed/wikipedia/svgzoom/svgzoom.js
JavaScript
apache-2.0
15,871
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.InteropServices; using System.Windows.Forms; namespace JAJ.WinForm.Comm { public class HotKey { //如果函数执行成功,返回值不为0。 //如果函数执行失败,返回值为0。要得到扩展错误信息,调用GetLastError。 [DllImport("user32.dll", SetLastError = true)] public static extern bool RegisterHotKey( IntPtr hWnd, //要定义热键的窗口的句柄 int id, //定义热键ID(不能与其它ID重复) KeyModifiers fsModifiers, //标识热键是否在按Alt、Ctrl、Shift、Windows等键时才会生效 Keys vk //定义热键的内容 ); [DllImport("user32.dll", SetLastError = true)] public static extern bool UnregisterHotKey( IntPtr hWnd, //要取消热键的窗口的句柄 int id //要取消热键的ID ); //定义了辅助键的名称(将数字转变为字符以便于记忆,也可去除此枚举而直接使用数值) [Flags()] public enum KeyModifiers { None = 0, Alt = 1, Ctrl = 2, Shift = 4, WindowsKey = 8 } } }
posjaj/BugTrace
JAJ.WinForm/WinForm/Comm/HotKey.cs
C#
apache-2.0
1,435
require 'test_helper' class StoresControllerTest < ActionDispatch::IntegrationTest setup do @store = stores(:one) end test "should get index" do get stores_url assert_response :success end test "should get new" do get new_store_url assert_response :success end test "should create store" do assert_difference('Store.count') do post stores_url, params: { store: { name: @store.name } } end assert_redirected_to store_url(Store.last) end test "should show store" do get store_url(@store) assert_response :success end test "should get edit" do get edit_store_url(@store) assert_response :success end test "should update store" do patch store_url(@store), params: { store: { name: @store.name } } assert_redirected_to store_url(@store) end test "should destroy store" do assert_difference('Store.count', -1) do delete store_url(@store) end assert_redirected_to stores_url end end
cjryan/receipt_commander_5k
test/controllers/stores_controller_test.rb
Ruby
apache-2.0
998
package com.xqbase.java.exceptions; /** * Empty Tree Exception. * * @author Tony He */ public class EmptyTreeException extends Exception { public EmptyTreeException(String message) { super(message); } public EmptyTreeException(Throwable cause) { super(cause); } public EmptyTreeException(String message, Throwable cause) { super(message, cause); } }
AdoHe/Homework
Tree/src/com/xqbase/java/exceptions/EmptyTreeException.java
Java
apache-2.0
406
/** * File: consumer.js * Description: This is the AMQP consumer handles incoming * communication from clients publishing messages to a broker server. * Messages can be received over AMQP exchange types including one-to-one, * from broadcast pattern, or selectively using specified binding key. * * Author: Eamin Zhang * robomq.io (http://www.robomq.io) */ var amqp = require("amqplib"); var domain = require("domain"); var server = "hostname"; var port = "5672"; var vhost = "yourvhost"; //for "/" vhost, use "%2f" instead var username = "username"; var password = "password"; var exchangeName = "testEx"; var queueName = "testQ1"; var routingKey = "test.#"; //topic with wildcard //use domain module to handle reconnecting var consumer = null; var dom = domain.create(); dom.on("error", relisten); dom.run(listen); function listen() { consumer = amqp.connect("amqp://" + username + ":" + password + "@" + server + ":" + port + "/" + vhost + "?heartbeat=60"); consumer.then(function(conn) { return conn.createChannel().then(function(ch) { ch.assertExchange(exchangeName, "topic", {durable: false, autoDelete: true}); ch.assertQueue(queueName, {durable: false, autoDelete: true, exclusive: true}); ch.bindQueue(queueName, exchangeName, routingKey); ch.consume(queueName, function(message) { //callback funtion on receiving messages console.log(message.content.toString()); }, {noAck: true}); }); }).then(null, function(err) { console.error("Exception handled, reconnecting...\nDetail:\n" + err); setTimeout(listen, 5000); }); } function relisten() { consumer.then(function(conn) { conn.close(); }); setTimeout(listen, 5000); }
robomq/robomq.io
sdk/AMQP/Node.js/topic/consumer.js
JavaScript
apache-2.0
1,684
package esilegacy /* 200 ok object */ type GetUniverseRegionsRegionIdOk struct { /* constellations array */ Constellations []int32 `json:"constellations,omitempty"` /* description string */ Description string `json:"description,omitempty"` /* name string */ Name string `json:"name,omitempty"` /* region_id integer */ RegionId int32 `json:"region_id,omitempty"` }
antihax/mock-esi
legacy/go/model_get_universe_regions_region_id_ok.go
GO
apache-2.0
381
/** * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. 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. */ /** * Constants to be used by the siddhi server and the siddhi web worker * This is not directly imported by the web worker since some of the constants are initiated using the window object * The SiddhiEditor.constants in passed into the web worker when the siddhi worker is initialized */ define(function() { "use strict"; // JS strict mode /** * Constants used by the server */ var constants = { SOURCE: "source", IO: "io", MAP: "map", STORE: "store", FUNCTION_OPERATION: "functionOperation", FUNCTIONS: "functions", STREAM_PROCESSORS: "streamProcessors", WINDOW_PROCESSORS: "windowProcessors", STREAMS: "streams", INNER_STREAMS: "innerStreams", EVENT_TABLES: "eventTables", TRIGGERS: "eventTriggers", AGGREGATIONS: "aggregations", WINDOWS: "eventWindows", EVAL_SCRIPTS: "evalScripts", ATTRIBUTES: "attributes", LOGICAL_OPERATORS: "logicalOperators", DATA_TYPES: "dataTypes", SNIPPETS: "snippet", SNIPPET_SIDDHI_CONTEXT: "siddhi" // Context provided to the snippet manager to register the snippets }; // Server side validation related constants constants.SERVER_URL = window.location.protocol + "//" + window.location.host + "/server/"; constants.SERVER_SIDE_VALIDATION_DELAY = 1000; // Token tooltips are also updated after this delay constants.TOOLTIP_SHOW_DELAY = 1000; // Time the user needs to hover the mouse to get the tooltip // Constants related to the completion data generated by the data population listener constants.dataPopulation = { UNDEFINED_DATA_TYPE: "#" }; /* * Names displayed in the server */ constants.typeToDisplayNameMap = {}; constants.typeToDisplayNameMap[constants.FUNCTIONS] = "Function"; constants.typeToDisplayNameMap[constants.STREAM_PROCESSORS] = "Stream Processor"; constants.typeToDisplayNameMap[constants.WINDOW_PROCESSORS] = "Window Processor"; constants.typeToDisplayNameMap[constants.STREAMS] = "Stream"; constants.typeToDisplayNameMap[constants.INNER_STREAMS] = "Inner Stream"; constants.typeToDisplayNameMap[constants.EVENT_TABLES] = "Event Table"; constants.typeToDisplayNameMap[constants.TRIGGERS] = "Event Trigger"; constants.typeToDisplayNameMap[constants.WINDOWS] = "Event Window"; constants.typeToDisplayNameMap[constants.EVAL_SCRIPTS] = "Eval Script"; constants.typeToDisplayNameMap[constants.ATTRIBUTES] = "Attribute"; constants.typeToDisplayNameMap[constants.LOGICAL_OPERATORS] = "Logical Operator"; constants.typeToDisplayNameMap[constants.DATA_TYPES] = "Data Type"; constants.typeToDisplayNameMap[constants.SNIPPETS] = "Snippet"; constants.typeToDisplayNameMap[constants.AGGREGATIONS] = "Aggregation"; /* * Ace server library related constants */ constants.ace = { SNIPPET_MANAGER: "ace/snippets", LANG_TOOLS: "ace/ext/language_tools", SIDDHI_MODE: "ace/mode/siddhi", DEFAULT_THEME: "ace/theme/twilight", ACE_RANGE: "ace/range", LANG_LIB: "ace/lib/lang", TOKEN_TOOLTIP: "ace/token/tooltips" }; /* * ANTLR related constants */ constants.antlr = { INDEX: "antlr4-js-runtime/index", ROOT: "antlr/", SYNTAX_ERROR_LISTENER: "SyntaxErrorListener", SIDDHI_DATA_POPULATION_LISTENER: "DataPopulationListener", SIDDHI_TOKEN_TOOL_TIP_UPDATE_LISTENER: "TokenTooltipPointRecognitionListener", SIDDHI_PARSER: "gen/SiddhiQLParser", SIDDHI_LEXER: "gen/SiddhiQLLexer" }; /* * Web worker related constants * Used in declaring the message type */ constants.worker = { INIT: "INIT", EDITOR_CHANGE_EVENT: "EDITOR_CHANGE_EVENT", GENERATE_TOKEN_TOOLTIP: "GENERATE_TOKEN_TOOLTIP", PARSE_TREE_GENERATION_COMPLETION: "PARSE_TREE_GENERATION_COMPLETION", DATA_POPULATION_COMPLETION: "DATA_POPULATION_COMPLETION", TOKEN_TOOLTIP_POINT_RECOGNITION_COMPLETION: "TOKEN_TOOLTIP_POINT_RECOGNITION_COMPLETION" }; return constants; });
erangatl/carbon-analytics
components/org.wso2.carbon.siddhi.editor.core/src/main/resources/web/js/source-editor/constants.js
JavaScript
apache-2.0
4,890
.PHONY: clean clean: make -C dask_test clean make -C test_image clean make -C ritoy clean .PHONY: test clean: make -C dask_test test make -C test_image test make -C ritoy test
SKA-ScienceDataProcessor/algorithm-reference-library
cluster_tests/Makefile
Makefile
apache-2.0
185
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <meta name="description" content="API documentation for the Rust `SDL_PIXELFORMAT_BGRA5551` constant in crate `sdl2_sys`."> <meta name="keywords" content="rust, rustlang, rust-lang, SDL_PIXELFORMAT_BGRA5551"> <title>sdl2_sys::pixels::SDL_PIXELFORMAT_BGRA5551 - Rust</title> <link rel="stylesheet" type="text/css" href="../../normalize.css"> <link rel="stylesheet" type="text/css" href="../../rustdoc.css"> <link rel="stylesheet" type="text/css" href="../../main.css"> </head> <body class="rustdoc constant"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <nav class="sidebar"> <p class='location'><a href='../index.html'>sdl2_sys</a>::<wbr><a href='index.html'>pixels</a></p><script>window.sidebarCurrent = {name: 'SDL_PIXELFORMAT_BGRA5551', ty: 'constant', relpath: ''};</script><script defer src="sidebar-items.js"></script> </nav> <nav class="sub"> <form class="search-form js-only"> <div class="search-container"> <input class="search-input" name="search" autocomplete="off" placeholder="Click or press ‘S’ to search, ‘?’ for more options…" type="search"> </div> </form> </nav> <section id='main' class="content"> <h1 class='fqn'><span class='in-band'>Constant <a href='../index.html'>sdl2_sys</a>::<wbr><a href='index.html'>pixels</a>::<wbr><a class="constant" href=''>SDL_PIXELFORMAT_BGRA5551</a></span><span class='out-of-band'><span id='render-detail'> <a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs"> [<span class='inner'>&#x2212;</span>] </a> </span><a class='srclink' href='../../src/sdl2_sys/pixels.rs.html#65' title='goto source code'>[src]</a></span></h1> <pre class='rust const'>pub const SDL_PIXELFORMAT_BGRA5551: <a class="type" href="../../sdl2_sys/pixels/type.SDL_PixelFormatEnum.html" title="type sdl2_sys::pixels::SDL_PixelFormatEnum">SDL_PixelFormatEnum</a><code> = </code><code>360976386</code></pre></section> <section id='search' class="content hidden"></section> <section class="footer"></section> <aside id="help" class="hidden"> <div> <h1 class="hidden">Help</h1> <div class="shortcuts"> <h2>Keyboard Shortcuts</h2> <dl> <dt>?</dt> <dd>Show this help dialog</dd> <dt>S</dt> <dd>Focus the search field</dd> <dt>&larrb;</dt> <dd>Move up in search results</dd> <dt>&rarrb;</dt> <dd>Move down in search results</dd> <dt>&#9166;</dt> <dd>Go to active search result</dd> <dt>+</dt> <dd>Collapse/expand all sections</dd> </dl> </div> <div class="infos"> <h2>Search Tricks</h2> <p> Prefix searches with a type followed by a colon (e.g. <code>fn:</code>) to restrict the search to a given type. </p> <p> Accepted types are: <code>fn</code>, <code>mod</code>, <code>struct</code>, <code>enum</code>, <code>trait</code>, <code>type</code>, <code>macro</code>, and <code>const</code>. </p> <p> Search functions by type signature (e.g. <code>vec -> usize</code> or <code>* -> vec</code>) </p> </div> </div> </aside> <script> window.rootPath = "../../"; window.currentCrate = "sdl2_sys"; </script> <script src="../../jquery.js"></script> <script src="../../main.js"></script> <script defer src="../../search-index.js"></script> </body> </html>
nitro-devs/nitro-game-engine
docs/sdl2_sys/pixels/constant.SDL_PIXELFORMAT_BGRA5551.html
HTML
apache-2.0
4,396
/* * Copyright 2004-2014 H2 Group. Multiple-Licensed under the MPL 2.0, * and the EPL 1.0 (http://h2database.com/html/license.html). * Initial Developer: H2 Group */ package org.h2.server; import java.io.ByteArrayInputStream; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.net.Socket; import java.nio.ByteBuffer; import java.sql.SQLException; import java.util.ArrayList; import org.h2.api.ErrorCode; import org.h2.command.Command; import org.h2.engine.ConnectionInfo; import org.h2.engine.Constants; import org.h2.engine.Engine; import org.h2.engine.Session; import org.h2.engine.SessionRemote; import org.h2.engine.SysProperties; import org.h2.expression.Parameter; import org.h2.expression.ParameterInterface; import org.h2.expression.ParameterRemote; import org.h2.jdbc.JdbcSQLException; import org.h2.message.DbException; import org.h2.result.ResultColumn; import org.h2.result.ResultInterface; import org.h2.store.LobStorageInterface; import org.h2.util.IOUtils; import org.h2.util.SmallLRUCache; import org.h2.util.SmallMap; import org.h2.util.StringUtils; import org.h2.value.ByteBufferTool; import org.h2.value.Transfer; import org.h2.value.Value; import org.h2.value.ValueLobDb; /** * One server thread is opened per client connection. */ public class TcpServerThread { private final TcpServer server; private Session session; private boolean stop; private Thread thread; private Command commit; private final SmallMap cache = new SmallMap(SysProperties.SERVER_CACHED_OBJECTS); private final SmallLRUCache<Long, CachedInputStream> lobs = SmallLRUCache.newInstance(Math.max( SysProperties.SERVER_CACHED_OBJECTS, SysProperties.SERVER_RESULT_SET_FETCH_SIZE * 5)); private final int threadId; private int clientVersion; private String sessionId; TcpServerThread(TcpServer server, int id) { this.server = server; this.threadId = id; } private void trace(String s) { server.trace(this + " " + s); } private boolean needFileEncryptionKey = false; private ConnectionInfo ci = null; private String originalURL = null; public byte[] init(ByteBuffer bb) { //try { trace("Connect"); // TODO server: should support a list of allowed databases // and a list of allowed clients try { /*if (!server.allow(transfer.getSocket())) { throw DbException.get(ErrorCode.REMOTE_CONNECTION_NOT_ALLOWED); }*/ int minClientVersion = bb.getInt(); if (minClientVersion < Constants.TCP_PROTOCOL_VERSION_6) { throw DbException.get(ErrorCode.DRIVER_VERSION_ERROR_2, "" + clientVersion, "" + Constants.TCP_PROTOCOL_VERSION_6); } else if (minClientVersion > Constants.TCP_PROTOCOL_VERSION_15) { throw DbException.get(ErrorCode.DRIVER_VERSION_ERROR_2, "" + clientVersion, "" + Constants.TCP_PROTOCOL_VERSION_15); } int maxClientVersion = bb.getInt(); if (maxClientVersion >= Constants.TCP_PROTOCOL_VERSION_15) { clientVersion = Constants.TCP_PROTOCOL_VERSION_15; } else { clientVersion = minClientVersion; } //transfer.setVersion(clientVersion); String db = ByteBufferTool.getString(bb); originalURL = ByteBufferTool.getString(bb); if (db == null && originalURL == null) { throw new RuntimeException("Not implemented"); /*String targetSessionId = ByteBufferTool.getString(bb); int command = bb.getInt(); stop = true; if (command == SessionRemote.SESSION_CANCEL_STATEMENT) { // cancel a running statement int statementId = bb.getInt(); server.cancelStatement(targetSessionId, statementId); } else if (command == SessionRemote.SESSION_CHECK_KEY) { // check if this is the correct server db = server.checkKeyAndGetDatabaseName(targetSessionId); if (!targetSessionId.equals(db)) { transfer.writeInt(SessionRemote.STATUS_OK); } else { transfer.writeInt(SessionRemote.STATUS_ERROR); } }*/ } String baseDir = server.getBaseDir(); if (baseDir == null) { baseDir = SysProperties.getBaseDir(); } db = server.checkKeyAndGetDatabaseName(db); ci = new ConnectionInfo(db); ci.setOriginalURL(originalURL); System.out.println("iodine orignalURL="+originalURL); String userName = ByteBufferTool.getString(bb); System.out.println("iodine userName="+userName); ci.setUserName(userName); ci.setUserPasswordHash(ByteBufferTool.getBytes(bb)); ci.setFilePasswordHash(ByteBufferTool.getBytes(bb)); int len = bb.getInt(); for (int i = 0; i < len; i++) { ci.setProperty(ByteBufferTool.getString(bb), ByteBufferTool.getString(bb)); } // override client's requested properties with server settings if (baseDir != null) { ci.setBaseDir(baseDir); } if (server.getIfExists()) { ci.setProperty("IFEXISTS", "TRUE"); } byte[] resp = new byte[8]; ByteBuffer respBB = ByteBuffer.wrap(resp); respBB.putInt(SessionRemote.STATUS_OK); respBB.putInt(clientVersion); System.out.println("iodine clientVersion = "+clientVersion+" "+Constants.TCP_PROTOCOL_VERSION_13+" "+ci.getFilePasswordHash()); if (clientVersion >= Constants.TCP_PROTOCOL_VERSION_13 && ci.getFilePasswordHash() != null) { //if (ci.getFilePasswordHash() != null) { //ci.setFileEncryptionKey(transfer.readBytes()); this.needFileEncryptionKey = true; //} } else{ session = Engine.getInstance().createSession(ci); //transfer.setSession(session); server.addConnection(threadId, originalURL, ci.getUserName()); trace("Connected"); } //transfer.flush(); /*if (clientVersion >= Constants.TCP_PROTOCOL_VERSION_13) { if (ci.getFilePasswordHash() != null) { ci.setFileEncryptionKey(transfer.readBytes()); } }*/ return resp; } catch (Throwable e) { stop = true; e.printStackTrace(); return sendError(e); } /*while (!stop) { try { process(); } catch (Throwable e) { return sendError(e); } } trace("Disconnect");*/ /* } catch (Throwable e) { server.traceError(e); } finally { close(); return null; }*/ } private void closeSession() { if (session != null) { RuntimeException closeError = null; try { Command rollback = session.prepareLocal("ROLLBACK"); rollback.executeUpdate(); } catch (RuntimeException e) { closeError = e; server.traceError(e); } catch (Exception e) { server.traceError(e); } try { session.close(); server.removeConnection(threadId); } catch (RuntimeException e) { if (closeError == null) { closeError = e; server.traceError(e); } } catch (Exception e) { server.traceError(e); } finally { session = null; } if (closeError != null) { throw closeError; } } } /** * Close a connection. */ void close() { try { stop = true; closeSession(); } catch (Exception e) { server.traceError(e); } finally { //transfer.close(); trace("Close"); server.remove(this); } } private byte[] sendError(Throwable t) { try { byte[] resp = new byte[65536]; ByteBuffer bb = ByteBuffer.wrap(resp); SQLException e = DbException.convert(t).getSQLException(); StringWriter writer = new StringWriter(); e.printStackTrace(new PrintWriter(writer)); String trace = writer.toString(); String message; String sql; if (e instanceof JdbcSQLException) { JdbcSQLException j = (JdbcSQLException) e; message = j.getOriginalMessage(); sql = j.getSQL(); } else { message = e.getMessage(); sql = null; } bb.putInt(SessionRemote.STATUS_ERROR); ByteBufferTool.putString(bb, e.getSQLState()); ByteBufferTool.putString(bb, message); ByteBufferTool.putString(bb, sql); bb.putInt(e.getErrorCode()); ByteBufferTool.putString(bb, trace); return ByteBufferTool.convertBB(bb); } catch (Exception e2) { /*if (!transfer.isClosed()) { server.traceError(e2); }*/ // if writing the error does not work, close the connection stop = true; return null; } } private void setParameters(Command command, ByteBuffer bb) throws IOException { int len = bb.getInt(); ArrayList<? extends ParameterInterface> params = command.getParameters(); for (int i = 0; i < len; i++) { Parameter p = (Parameter) params.get(i); p.setValue(ByteBufferTool.readValue(bb, this.clientVersion, this.session)); } } public byte[] process(byte[] req) { try { ByteBuffer bb = ByteBuffer.wrap(req); byte[] resp = new byte[65536]; ByteBuffer retBB = ByteBuffer.wrap(resp); if(this.needFileEncryptionKey){ ci.setFileEncryptionKey(ByteBufferTool.getBytes(bb)); session = Engine.getInstance().createSession(ci); //transfer.setSession(session); server.addConnection(threadId, originalURL, ci.getUserName()); trace("Connected"); return new byte[0]; } int operation = bb.getInt(); switch (operation) { case SessionRemote.SESSION_PREPARE_READ_PARAMS: case SessionRemote.SESSION_PREPARE: { // System.out.println("iodine2 SESSION_PREPARE"); int id = bb.getInt(); String sql = ByteBufferTool.getString(bb); int old = session.getModificationId(); Command command = session.prepareLocal(sql); boolean readonly = command.isReadOnly(); cache.addObject(id, command); boolean isQuery = command.isQuery(); ArrayList<? extends ParameterInterface> params = command .getParameters(); retBB.putInt(getState(old)); ByteBufferTool.putBoolean(retBB, isQuery); ByteBufferTool.putBoolean(retBB, readonly); retBB.putInt(params.size()); //transfer.writeInt(getState(old)).writeBoolean(isQuery) // .writeBoolean(readonly).writeInt(params.size()); if (operation == SessionRemote.SESSION_PREPARE_READ_PARAMS) { for (ParameterInterface p : params) { ParameterRemote.writeMetaData(retBB, p); } } //transfer.flush(); //break; return ByteBufferTool.convertBB(retBB); } case SessionRemote.SESSION_CLOSE: { // System.out.println("iodine2 SESSION_CLOSE"); stop = true; closeSession(); //transfer.writeInt(SessionRemote.STATUS_OK).flush(); retBB.putInt(SessionRemote.STATUS_OK); close(); return ByteBufferTool.convertBB(retBB); } case SessionRemote.COMMAND_COMMIT: { throw new RuntimeException("Not implemented"); /*System.out.println("iodine COMMAND_COMMIT"); if (commit == null) { commit = session.prepareLocal("COMMIT"); } int old = session.getModificationId(); commit.executeUpdate(); transfer.writeInt(getState(old)).flush(); break;*/ } case SessionRemote.COMMAND_GET_META_DATA: { throw new RuntimeException("Not implemented"); /*System.out.println("iodine COMMAND_GET_META_DATA"); int id = transfer.readInt(); int objectId = transfer.readInt(); Command command = (Command) cache.getObject(id, false); ResultInterface result = command.getMetaData(); cache.addObject(objectId, result); int columnCount = result.getVisibleColumnCount(); transfer.writeInt(SessionRemote.STATUS_OK) .writeInt(columnCount).writeInt(0); for (int i = 0; i < columnCount; i++) { ByteBuffer bb = null; ResultColumn.writeColumn(bb, result, i); } transfer.flush(); break;*/ } case SessionRemote.COMMAND_EXECUTE_QUERY: { // System.out.println("iodine2 COMMAND_EXECUTE_QUERY"); long start = System.currentTimeMillis(); int id = bb.getInt(); int objectId = bb.getInt(); int maxRows = bb.getInt(); int fetchSize = bb.getInt(); Command command = (Command) cache.getObject(id, false); setParameters(command, bb); int old = session.getModificationId(); ResultInterface result; synchronized (session) { result = command.executeQuery(maxRows, false); } cache.addObject(objectId, result); int columnCount = result.getVisibleColumnCount(); int state = getState(old); retBB.putInt(state).putInt(columnCount); //transfer.writeInt(state).writeInt(columnCount); int rowCount = result.getRowCount(); retBB.putInt(rowCount); //transfer.writeInt(rowCount); for (int i = 0; i < columnCount; i++) { ResultColumn.writeColumn(retBB, result, i); } int fetch = Math.min(rowCount, fetchSize); for (int i = 0; i < fetch; i++) { sendRow(result, retBB); } //transfer.flush(); //break; //if(System.currentTimeMillis()-start>1000) // System.out.println("query time = "+(System.currentTimeMillis()-start)); return ByteBufferTool.convertBB(retBB); } case SessionRemote.COMMAND_EXECUTE_UPDATE: { // System.out.println("iodine2 COMMAND_EXECUTE_UPDATE"); long start = System.currentTimeMillis(); int id = bb.getInt(); Command command = (Command) cache.getObject(id, false); setParameters(command, bb); int old = session.getModificationId(); int updateCount; synchronized (session) { updateCount = command.executeUpdate(); } int status; if (session.isClosed()) { status = SessionRemote.STATUS_CLOSED; } else { status = getState(old); } retBB.putInt(status).putInt(updateCount); ByteBufferTool.putBoolean(retBB, session.getAutoCommit()); //transfer.writeInt(status).writeInt(updateCount) // .writeBoolean(session.getAutoCommit()); //transfer.flush(); //break; //if(System.currentTimeMillis()-start>1000) // System.out.println("update time = "+(System.currentTimeMillis()-start)); return ByteBufferTool.convertBB(retBB); } case SessionRemote.COMMAND_CLOSE: { // System.out.println("iodine2 COMMAND_CLOSE"); int id = bb.getInt(); Command command = (Command) cache.getObject(id, true); if (command != null) { command.close(); cache.freeObject(id); } return new byte[0]; } case SessionRemote.RESULT_FETCH_ROWS: { throw new RuntimeException("Not implemented"); /*System.out.println("iodine RESULT_FETCH_ROWS"); int id = transfer.readInt(); int count = transfer.readInt(); ResultInterface result = (ResultInterface) cache.getObject(id, false); transfer.writeInt(SessionRemote.STATUS_OK); for (int i = 0; i < count; i++) { sendRow(result); } transfer.flush(); break;*/ } case SessionRemote.RESULT_RESET: { throw new RuntimeException("Not implemented"); /*System.out.println("iodine RESULT_RESET"); int id = transfer.readInt(); ResultInterface result = (ResultInterface) cache.getObject(id, false); result.reset(); break;*/ } case SessionRemote.RESULT_CLOSE: { // System.out.println("iodine2 RESULT_CLOSE"); int id = bb.getInt(); ResultInterface result = (ResultInterface) cache.getObject(id, true); if (result != null) { result.close(); cache.freeObject(id); } return new byte[0]; } case SessionRemote.CHANGE_ID: { throw new RuntimeException("Not implemented"); /*System.out.println("iodine CHANGE_ID"); int oldId = transfer.readInt(); int newId = transfer.readInt(); Object obj = cache.getObject(oldId, false); cache.freeObject(oldId); cache.addObject(newId, obj); break;*/ } case SessionRemote.SESSION_SET_ID: { // System.out.println("iodine2 SESSION_SET_ID"); sessionId = ByteBufferTool.getString(bb);//transfer.readString(); retBB.putInt(SessionRemote.STATUS_OK); ByteBufferTool.putBoolean(retBB, session.getAutoCommit()); //transfer.writeBoolean(session.getAutoCommit()); //transfer.flush(); //break; return ByteBufferTool.convertBB(retBB); } case SessionRemote.SESSION_SET_AUTOCOMMIT: { // System.out.println("iodine2 SESSION_SET_AUTOCOMMIT"); boolean autoCommit = ByteBufferTool.getBoolean(bb);//transfer.readBoolean(); session.setAutoCommit(autoCommit); retBB.putInt(SessionRemote.STATUS_OK); return ByteBufferTool.convertBB(retBB); //transfer.writeInt(SessionRemote.STATUS_OK).flush(); //break; } case SessionRemote.SESSION_HAS_PENDING_TRANSACTION: { // System.out.println("iodine2 SESSION_HAS_PENDING_TRANSACTION"); retBB.putInt(SessionRemote.STATUS_OK) .putInt(session.hasPendingTransaction() ? 1 : 0); //.flush(); return ByteBufferTool.convertBB(retBB); //break; } case SessionRemote.LOB_READ: { throw new RuntimeException("Not implemented"); /*System.out.println("iodine LOB_READ"); long lobId = transfer.readLong(); byte[] hmac; CachedInputStream in; boolean verifyMac; if (clientVersion >= Constants.TCP_PROTOCOL_VERSION_11) { if (clientVersion >= Constants.TCP_PROTOCOL_VERSION_12) { hmac = transfer.readBytes(); verifyMac = true; } else { hmac = null; verifyMac = false; } in = lobs.get(lobId); if (in == null && verifyMac) { in = new CachedInputStream(null); lobs.put(lobId, in); } } else { verifyMac = false; hmac = null; in = lobs.get(lobId); } long offset = transfer.readLong(); int length = transfer.readInt(); if (verifyMac) { transfer.verifyLobMac(hmac, lobId); } if (in == null) { throw DbException.get(ErrorCode.OBJECT_CLOSED); } if (in.getPos() != offset) { LobStorageInterface lobStorage = session.getDataHandler() .getLobStorage(); // only the lob id is used ValueLobDb lob = ValueLobDb.create(Value.BLOB, null, -1, lobId, hmac, -1); InputStream lobIn = lobStorage .getInputStream(lob, hmac, -1); in = new CachedInputStream(lobIn); lobs.put(lobId, in); lobIn.skip(offset); } // limit the buffer size length = Math.min(16 * Constants.IO_BUFFER_SIZE, length); byte[] buff = new byte[length]; length = IOUtils.readFully(in, buff, length); transfer.writeInt(SessionRemote.STATUS_OK); transfer.writeInt(length); transfer.writeBytes(buff, 0, length); transfer.flush(); break;*/ } default: trace("Unknown operation: " + operation); closeSession(); close(); return new byte[0]; } } catch (IOException e) { return sendError(e); } } private int getState(int oldModificationId) { if (session.getModificationId() == oldModificationId) { return SessionRemote.STATUS_OK; } return SessionRemote.STATUS_OK_STATE_CHANGED; } private void sendRow(ResultInterface result, ByteBuffer bb) throws IOException { if (result.next()) { ByteBufferTool.putBoolean(bb, true); //bb.writeBoolean(true); Value[] v = result.currentRow(); for (int i = 0; i < result.getVisibleColumnCount(); i++) { if (clientVersion >= Constants.TCP_PROTOCOL_VERSION_12) { ByteBufferTool.writeValue(bb, v[i], clientVersion, session); } else { writeValue(bb, v[i]); } } } else { ByteBufferTool.putBoolean(bb, false); //transfer.writeBoolean(false); } } private void writeValue(ByteBuffer bb, Value v) throws IOException { if (v.getType() == Value.CLOB || v.getType() == Value.BLOB) { if (v instanceof ValueLobDb) { ValueLobDb lob = (ValueLobDb) v; if (lob.isStored()) { long id = lob.getLobId(); lobs.put(id, new CachedInputStream(null)); } } } ByteBufferTool.writeValue(bb, v, this.clientVersion, session); } void setThread(Thread thread) { this.thread = thread; } Thread getThread() { return thread; } /** * Cancel a running statement. * * @param targetSessionId the session id * @param statementId the statement to cancel */ void cancelStatement(String targetSessionId, int statementId) { if (StringUtils.equals(targetSessionId, this.sessionId)) { Command cmd = (Command) cache.getObject(statementId, false); cmd.cancel(); } } /** * An input stream with a position. */ static class CachedInputStream extends FilterInputStream { private static final ByteArrayInputStream DUMMY = new ByteArrayInputStream(new byte[0]); private long pos; CachedInputStream(InputStream in) { super(in == null ? DUMMY : in); if (in == null) { pos = -1; } } @Override public int read(byte[] buff, int off, int len) throws IOException { len = super.read(buff, off, len); if (len > 0) { pos += len; } return len; } @Override public int read() throws IOException { int x = in.read(); if (x >= 0) { pos++; } return x; } @Override public long skip(long n) throws IOException { n = super.skip(n); if (n > 0) { pos += n; } return n; } public long getPos() { return pos; } } }
vdr007/ThriftyPaxos
src/applications/h2/src/main/org/h2/server/TcpServerThread.java
Java
apache-2.0
23,808
package org.wikipedia.gallery; import android.graphics.Bitmap; import android.graphics.Color; import android.graphics.drawable.Animatable; import android.media.MediaPlayer; import android.net.Uri; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.MediaController; import android.widget.ProgressBar; import android.widget.VideoView; import com.facebook.drawee.backends.pipeline.Fresco; import com.facebook.drawee.controller.BaseControllerListener; import com.facebook.drawee.drawable.ScalingUtils; import com.facebook.drawee.generic.GenericDraweeHierarchy; import com.facebook.drawee.generic.GenericDraweeHierarchyBuilder; import com.facebook.drawee.view.SimpleDraweeView; import com.facebook.imagepipeline.image.ImageInfo; import com.facebook.samples.zoomable.DoubleTapGestureListener; import com.facebook.samples.zoomable.ZoomableDraweeView; import org.wikipedia.Constants; import org.wikipedia.R; import org.wikipedia.WikipediaApp; import org.wikipedia.dataclient.WikiSite; import org.wikipedia.page.PageTitle; import org.wikipedia.util.FeedbackUtil; import org.wikipedia.util.FileUtil; import org.wikipedia.util.PermissionUtil; import org.wikipedia.util.ShareUtil; import org.wikipedia.util.log.L; import java.io.File; import java.util.Map; import static org.wikipedia.util.PermissionUtil.hasWriteExternalStoragePermission; import static org.wikipedia.util.PermissionUtil.requestWriteStorageRuntimePermissions; public class GalleryItemFragment extends Fragment { public static final String ARG_PAGETITLE = "pageTitle"; public static final String ARG_MEDIATITLE = "imageTitle"; public static final String ARG_MIMETYPE = "mimeType"; public static final String ARG_FEED_FEATURED_IMAGE = "feedFeaturedImage"; public static final String ARG_AGE = "age"; private ProgressBar progressBar; private ZoomableDraweeView imageView; private View videoContainer; private VideoView videoView; private SimpleDraweeView videoThumbnail; private View videoPlayButton; private MediaController mediaController; @NonNull private WikipediaApp app = WikipediaApp.getInstance(); @Nullable private GalleryActivity parentActivity; @Nullable private PageTitle pageTitle; @SuppressWarnings("NullableProblems") @NonNull private PageTitle imageTitle; @Nullable private String mimeType; private int age; @Nullable private GalleryItem galleryItem; @Nullable public GalleryItem getGalleryItem() { return galleryItem; } public static GalleryItemFragment newInstance(@Nullable PageTitle pageTitle, @NonNull WikiSite wiki, @NonNull GalleryItem galleryItemProto) { GalleryItemFragment f = new GalleryItemFragment(); Bundle args = new Bundle(); args.putParcelable(ARG_PAGETITLE, pageTitle); args.putParcelable(ARG_MEDIATITLE, new PageTitle(galleryItemProto.getName(), wiki)); args.putString(ARG_MIMETYPE, galleryItemProto.getMimeType()); if (galleryItemProto instanceof FeaturedImageGalleryItem) { args.putBoolean(ARG_FEED_FEATURED_IMAGE, true); args.putInt(ARG_AGE, ((FeaturedImageGalleryItem) galleryItemProto).getAge()); } f.setArguments(args); return f; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); pageTitle = getArguments().getParcelable(ARG_PAGETITLE); //noinspection ConstantConditions imageTitle = getArguments().getParcelable(ARG_MEDIATITLE); mimeType = getArguments().getString(ARG_MIMETYPE); if (getArguments().getBoolean(ARG_FEED_FEATURED_IMAGE)) { age = getArguments().getInt(ARG_AGE); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_gallery_item, container, false); progressBar = (ProgressBar) rootView.findViewById(R.id.gallery_item_progress_bar); videoContainer = rootView.findViewById(R.id.gallery_video_container); videoView = (VideoView) rootView.findViewById(R.id.gallery_video); videoThumbnail = (SimpleDraweeView) rootView.findViewById(R.id.gallery_video_thumbnail); videoPlayButton = rootView.findViewById(R.id.gallery_video_play_button); imageView = (ZoomableDraweeView) rootView.findViewById(R.id.gallery_image); imageView.setTapListener(new DoubleTapGestureListener(imageView) { @Override public boolean onSingleTapConfirmed(MotionEvent e) { parentActivity.toggleControls(); return true; } }); GenericDraweeHierarchy hierarchy = new GenericDraweeHierarchyBuilder(getResources()) .setActualImageScaleType(ScalingUtils.ScaleType.FIT_CENTER) .build(); imageView.setHierarchy(hierarchy); return rootView; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setHasOptionsMenu(true); parentActivity = (GalleryActivity) getActivity(); // do we already have a prepopulated item in the gallery cache? galleryItem = parentActivity.getGalleryCache().get(imageTitle); if (galleryItem == null) { loadGalleryItem(); } else { loadMedia(); } } @Override public void onDestroyView() { super.onDestroyView(); imageView.setController(null); imageView.setOnClickListener(null); videoThumbnail.setController(null); videoThumbnail.setOnClickListener(null); } private void updateProgressBar(boolean visible, boolean indeterminate, int value) { progressBar.setIndeterminate(indeterminate); if (!indeterminate) { progressBar.setProgress(value); } progressBar.setVisibility(visible ? View.VISIBLE : View.GONE); } @Override public void onDestroy() { super.onDestroy(); app.getRefWatcher().watch(this); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { if (!isAdded()) { return; } inflater.inflate(R.menu.menu_gallery, menu); } @Override public void onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); if (!isAdded()) { return; } menu.findItem(R.id.menu_gallery_visit_page).setEnabled(galleryItem != null); menu.findItem(R.id.menu_gallery_share).setEnabled(galleryItem != null && imageView.getDrawable() != null); menu.findItem(R.id.menu_gallery_save).setEnabled(galleryItem != null && imageView.getDrawable() != null); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_gallery_visit_page: if (galleryItem != null) { parentActivity.finishWithPageResult(imageTitle); } return true; case R.id.menu_gallery_save: handleImageSaveRequest(); return true; case R.id.menu_gallery_share: shareImage(); return true; default: break; } return super.onOptionsItemSelected(item); } /** * Notifies this fragment that the current position of its containing ViewPager has changed. * * @param fragmentPosition This fragment's position in the ViewPager. * @param pagerPosition The pager's current position that is displayed to the user. */ public void onUpdatePosition(int fragmentPosition, int pagerPosition) { if (fragmentPosition != pagerPosition) { // update stuff if our position is not "current" within the ViewPager... if (mediaController != null) { if (videoView.isPlaying()) { videoView.pause(); } mediaController.hide(); } } else { // update stuff if our position is "current" if (mediaController != null) { if (!videoView.isPlaying()) { videoView.start(); } } } } private void handleImageSaveRequest() { if (!(hasWriteExternalStoragePermission(this.getActivity()))) { requestWriteExternalStoragePermission(); } else { saveImage(); } } private void requestWriteExternalStoragePermission() { requestWriteStorageRuntimePermissions(this, Constants.ACTIVITY_REQUEST_WRITE_EXTERNAL_STORAGE_PERMISSION); } /** * Perform a network request to load information and metadata for our gallery item. */ private void loadGalleryItem() { updateProgressBar(true, true, 0); new GalleryItemFetchTask(app.getAPIForSite(imageTitle.getWikiSite()), imageTitle.getWikiSite(), imageTitle, FileUtil.isVideo(mimeType)) { @Override public void onFinish(Map<PageTitle, GalleryItem> result) { if (!isAdded()) { return; } if (result.size() > 0) { galleryItem = (GalleryItem) result.values().toArray()[0]; parentActivity.getGalleryCache().put((PageTitle) result.keySet().toArray()[0], galleryItem); loadMedia(); } else { updateProgressBar(false, true, 0); parentActivity.showError(null, true); } } @Override public void onCatch(Throwable caught) { if (!isAdded()) { return; } updateProgressBar(false, true, 0); parentActivity.showError(caught, true); L.e(caught); } }.execute(); } /** * Load the actual media associated with our gallery item into the UI. */ private void loadMedia() { if (FileUtil.isVideo(mimeType)) { loadVideo(); } else { // it's actually OK to use the thumbUrl in all cases, and here's why: // - in the case of a JPG or PNG image: // - if the image is bigger than the requested thumbnail size, then the // thumbnail will correctly be a scaled-down version of the image, so // that it won't overload the device's bitmap buffer. // - if the image is smaller than the requested thumbnail size, then the // thumbnail url will be the same as the actual image url. // - in the case of an SVG file: // - we need the thumbnail image anyway, since the ImageView can't // display SVGs. loadImage(galleryItem.getThumbUrl()); } parentActivity.supportInvalidateOptionsMenu(); parentActivity.layOutGalleryDescription(); } private View.OnClickListener videoThumbnailClickListener = new View.OnClickListener() { private boolean loading = false; @Override public void onClick(View v) { if (loading) { return; } loading = true; L.d("Loading video from url: " + galleryItem.getUrl()); videoView.setVisibility(View.VISIBLE); mediaController = new MediaController(parentActivity); updateProgressBar(true, true, 0); videoView.setMediaController(mediaController); videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { updateProgressBar(false, true, 0); // ...update the parent activity, which will trigger us to start playing! parentActivity.layOutGalleryDescription(); // hide the video thumbnail, since we're about to start playback videoThumbnail.setVisibility(View.GONE); videoPlayButton.setVisibility(View.GONE); // and start! videoView.start(); loading = false; } }); videoView.setOnErrorListener(new MediaPlayer.OnErrorListener() { @Override public boolean onError(MediaPlayer mp, int what, int extra) { updateProgressBar(false, true, 0); FeedbackUtil.showMessage(getActivity(), R.string.gallery_error_video_failed); videoView.setVisibility(View.GONE); videoThumbnail.setVisibility(View.VISIBLE); videoPlayButton.setVisibility(View.VISIBLE); loading = false; return true; } }); videoView.setVideoURI(Uri.parse(galleryItem.getUrl())); } }; private void loadVideo() { videoContainer.setVisibility(View.VISIBLE); videoPlayButton.setVisibility(View.VISIBLE); videoView.setVisibility(View.GONE); if (TextUtils.isEmpty(galleryItem.getThumbUrl())) { videoThumbnail.setVisibility(View.GONE); } else { // show the video thumbnail while the video loads... videoThumbnail.setVisibility(View.VISIBLE); videoThumbnail.setController(Fresco.newDraweeControllerBuilder() .setUri(galleryItem.getThumbUrl()) .setAutoPlayAnimations(true) .setControllerListener(new BaseControllerListener<ImageInfo>() { @Override public void onFinalImageSet(String id, ImageInfo imageInfo, Animatable animatable) { updateProgressBar(false, true, 0); } @Override public void onFailure(String id, Throwable throwable) { updateProgressBar(false, true, 0); } }) .build()); } videoThumbnail.setOnClickListener(videoThumbnailClickListener); } private void loadImage(String url) { imageView.setVisibility(View.VISIBLE); L.v("Loading image from url: " + url); imageView.setController(Fresco.newDraweeControllerBuilder() .setUri(url) .setAutoPlayAnimations(true) .setControllerListener(new BaseControllerListener<ImageInfo>() { @Override public void onFinalImageSet(String id, ImageInfo imageInfo, Animatable animatable) { if (!isAdded()) { return; } updateProgressBar(false, true, 0); if (shouldHaveWhiteBackground(galleryItem.getMimeType())) { imageView.setBackgroundColor(Color.WHITE); } parentActivity.supportInvalidateOptionsMenu(); } @Override public void onFailure(String id, Throwable throwable) { if (!isAdded()) { return; } updateProgressBar(false, true, 0); FeedbackUtil.showMessage(getActivity(), R.string.gallery_error_draw_failed); } }) .build()); } /** * Share the current image using an activity chooser, so that the user can choose the * app with which to share the content. * This is done by saving the image to a temporary file in external storage, then specifying * that file in the share intent. The name of the temporary file is kept constant, so that * it's overwritten every time an image is shared from the app, so that it takes up a * constant amount of space. */ private void shareImage() { if (galleryItem == null) { return; } parentActivity.getFunnel().logGalleryShare(pageTitle, galleryItem.getName()); new ImagePipelineBitmapGetter(getActivity(), galleryItem.getThumbUrl()){ @Override public void onSuccess(@Nullable Bitmap bitmap) { if (!isAdded()) { return; } if (bitmap != null) { ShareUtil.shareImage(parentActivity, bitmap, new File(galleryItem.getUrl()).getName(), getShareSubject(), imageTitle.getCanonicalUri()); } else { ShareUtil.shareText(parentActivity, imageTitle); } } }.get(); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { switch (requestCode) { case Constants.ACTIVITY_REQUEST_WRITE_EXTERNAL_STORAGE_PERMISSION: if (PermissionUtil.isPermitted(grantResults)) { saveImage(); } else { L.e("Write permission was denied by user"); FeedbackUtil.showMessage(getActivity(), R.string.gallery_save_image_write_permission_rationale); } break; default: throw new RuntimeException("unexpected permission request code " + requestCode); } } @Nullable private String getShareSubject() { if (getArguments().getBoolean(ARG_FEED_FEATURED_IMAGE)) { return ShareUtil.getFeaturedImageShareSubject(getContext(), age); } return pageTitle != null ? pageTitle.getDisplayText() : null; } private void saveImage() { if (galleryItem == null) { return; } parentActivity.getFunnel().logGallerySave(pageTitle, galleryItem.getName()); parentActivity.getDownloadReceiver().download(galleryItem); } private boolean shouldHaveWhiteBackground(String mimeType) { return mimeType.contains("svg") || mimeType.contains("png") || mimeType.contains("gif"); } }
SAGROUP2/apps-android-wikipedia
app/src/main/java/org/wikipedia/gallery/GalleryItemFragment.java
Java
apache-2.0
19,258
package com.ndi.app; import com.fererlab.app.BaseApplication; import com.fererlab.app.EApplicationMode; import com.fererlab.db.EM; import com.fererlab.dto.Request; import com.fererlab.dto.Response; /** * acm */ public class NDI extends BaseApplication { @Override public void start() { if (EApplicationMode.DEVELOPMENT.equals(getMode())) { try { EM.start(property("persistence-unit")); } catch (Exception e) { e.printStackTrace(); } } } @Override public Response runApplication(final Request request) { // read the cookie to Session object request.getSession().fromCookie(this.getClass().getName(), property("sign")); // run application return super.runApplication(request); } @Override public void stop() { EM.stop(); } }
canmogol/NDIServer
src/main/java/com/ndi/app/NDI.java
Java
apache-2.0
891
<?php include(dirname(__FILE__).'/../../bootstrap/functional.php'); $browser = new sfTestFunctional(new sfBrowser()); $browser-> get('/comment_crud/index')-> with('request')->begin()-> isParameter('module', 'comment_crud')-> isParameter('action', 'index')-> end()-> with('response')->begin()-> isStatusCode(200)-> checkElement('body', '!/This is a temporary page/')-> end() ;
studiodev/archives
2012 - Portfolio V5/test/functional/frontend/comment_crudActionsTest.php
PHP
apache-2.0
426
# -*- coding: utf-8 -*- ''' The function cache system allows for data to be stored on the master so it can be easily read by other minions ''' # Import python libs import copy import logging # Import salt libs import salt.crypt import salt.payload log = logging.getLogger(__name__) def _auth(): ''' Return the auth object ''' if 'auth' not in __context__: __context__['auth'] = salt.crypt.SAuth(__opts__) return __context__['auth'] def update(clear=False): ''' Execute the configured functions and send the data back up to the master The functions to be executed are merged from the master config, pillar and minion config under the option "function_cache": .. code-block:: yaml mine_functions: network.ip_addrs: - eth0 disk.usage: [] The function cache will be populated with information from executing these functions CLI Example: .. code-block:: bash salt '*' mine.update ''' m_data = __salt__['config.option']('mine_functions', {}) data = {} for func in m_data: if func not in __salt__: log.error('Function {0} in mine_functions not available' .format(func)) continue try: if m_data[func] and isinstance(m_data[func], dict): data[func] = __salt__[func](**m_data[func]) elif m_data[func] and isinstance(m_data[func], list): data[func] = __salt__[func](*m_data[func]) else: data[func] = __salt__[func]() except Exception: log.error('Function {0} in mine_functions failed to execute' .format(func)) continue if __opts__['file_client'] == 'local': if not clear: old = __salt__['data.getval']('mine_cache') if isinstance(old, dict): old.update(data) data = old return __salt__['data.update']('mine_cache', data) auth = _auth() load = { 'cmd': '_mine', 'data': data, 'id': __opts__['id'], 'clear': clear, 'tok': auth.gen_token('salt'), } sreq = salt.payload.SREQ(__opts__['master_uri']) ret = sreq.send('aes', auth.crypticle.dumps(load)) return auth.crypticle.loads(ret) def send(func, *args, **kwargs): ''' Send a specific function to the mine. CLI Example: .. code-block:: bash salt '*' mine.send network.interfaces eth0 ''' if not func in __salt__: return False data = {} arg_data = salt.utils.arg_lookup(__salt__[func]) func_data = copy.deepcopy(kwargs) for ind, _ in enumerate(arg_data.get('args', [])): try: func_data[arg_data['args'][ind]] = args[ind] except IndexError: # Safe error, arg may be in kwargs pass f_call = salt.utils.format_call(__salt__[func], func_data) try: if 'kwargs' in f_call: data[func] = __salt__[func](*f_call['args'], **f_call['kwargs']) else: data[func] = __salt__[func](*f_call['args']) except Exception as exc: log.error('Function {0} in mine.send failed to execute: {1}' .format(func, exc)) return False if __opts__['file_client'] == 'local': old = __salt__['data.getval']('mine_cache') if isinstance(old, dict): old.update(data) data = old return __salt__['data.update']('mine_cache', data) auth = _auth() load = { 'cmd': '_mine', 'data': data, 'id': __opts__['id'], 'tok': auth.gen_token('salt'), } sreq = salt.payload.SREQ(__opts__['master_uri']) ret = sreq.send('aes', auth.crypticle.dumps(load)) return auth.crypticle.loads(ret) def get(tgt, fun, expr_form='glob'): ''' Get data from the mine based on the target, function and expr_form Targets can be matched based on any standard matching system that can be matched on the master via these keywords:: glob pcre grain grain_pcre CLI Example: .. code-block:: bash salt '*' mine.get '*' network.interfaces salt '*' mine.get 'os:Fedora' network.interfaces grain ''' if expr_form.lower == 'pillar': log.error('Pillar matching not supported on mine.get') return '' if __opts__['file_client'] == 'local': ret = {} is_target = {'glob': __salt__['match.glob'], 'pcre': __salt__['match.pcre'], 'list': __salt__['match.list'], 'grain': __salt__['match.grain'], 'grain_pcre': __salt__['match.grain_pcre'], 'compound': __salt__['match.compound'], 'ipcidr': __salt__['match.ipcidr'], }[expr_form](tgt) if is_target: data = __salt__['data.getval']('mine_cache') if isinstance(data, dict) and fun in data: ret[__opts__['id']] = data[fun] return ret auth = _auth() load = { 'cmd': '_mine_get', 'id': __opts__['id'], 'tgt': tgt, 'fun': fun, 'expr_form': expr_form, 'tok': auth.gen_token('salt'), } sreq = salt.payload.SREQ(__opts__['master_uri']) ret = sreq.send('aes', auth.crypticle.dumps(load)) return auth.crypticle.loads(ret) def delete(fun): ''' Remove specific function contents of minion. Returns True on success. CLI Example: .. code-block:: bash salt '*' mine.delete 'network.interfaces' ''' if __opts__['file_client'] == 'local': data = __salt__['data.getval']('mine_cache') if isinstance(data, dict) and fun in data: del data[fun] return __salt__['data.update']('mine_cache', data) auth = _auth() load = { 'cmd': '_mine_delete', 'id': __opts__['id'], 'fun': fun, 'tok': auth.gen_token('salt'), } sreq = salt.payload.SREQ(__opts__['master_uri']) ret = sreq.send('aes', auth.crypticle.dumps(load)) return auth.crypticle.loads(ret) def flush(): ''' Remove all mine contents of minion. Returns True on success. CLI Example: .. code-block:: bash salt '*' mine.flush ''' if __opts__['file_client'] == 'local': return __salt__['data.update']('mine_cache', {}) auth = _auth() load = { 'cmd': '_mine_flush', 'id': __opts__['id'], 'tok': auth.gen_token('salt'), } sreq = salt.payload.SREQ(__opts__['master_uri']) ret = sreq.send('aes', auth.crypticle.dumps(load)) return auth.crypticle.loads(ret)
victorywang80/Maintenance
saltstack/src/salt/modules/mine.py
Python
apache-2.0
6,869
/* * Copyright 2016 Lutz Fischer <l.fischer@ed.ac.uk>. * * 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 rappsilber.applications; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.text.ParseException; import java.util.Comparator; import rappsilber.ms.ToleranceUnit; import rappsilber.ms.dataAccess.BufferedSpectraAccess; import rappsilber.ms.dataAccess.SpectraAccess; import rappsilber.ms.dataAccess.msm.AbstractMSMAccess; import rappsilber.ms.dataAccess.msm.MSMIterator; import rappsilber.ms.dataAccess.output.MSMWriter; import rappsilber.ms.spectra.Spectra; import rappsilber.ms.spectra.SpectraPeak; import rappsilber.utils.SortedLinkedList; /** * * @author Lutz Fischer <l.fischer@ed.ac.uk> */ public class TopY1R1 { public static void main(String[] args) throws FileNotFoundException, IOException, ParseException { SpectraAccess msmit = AbstractMSMAccess.getMSMIterator(new File("/home/lfischer/Projects/IndicatorPeaks/Dundee/mgf/hcd50.msmlist"), new ToleranceUnit("10ppm"), 0, null); BufferedSpectraAccess bfa = new BufferedSpectraAccess(msmit, 10); msmit = bfa; MSMWriter mWriter = new MSMWriter( new File("/home/lfischer/Projects/IndicatorPeaks/Dundee/mgf/hcd50_Top800Y1R.msm") , null, null, null); final double targetmz = 175.119495287; int topN = 800; double targetIntensity = 3046; Comparator<Spectra> spectraCompare = new Comparator<Spectra>(){ @Override public int compare(Spectra o1, Spectra o2) { SpectraPeak sp1 = o1.getPeakAt(targetmz); SpectraPeak sp2 = o2.getPeakAt(targetmz); if (sp1 == null) { if (sp2 == null) return 0; return -1; } if (sp2 == null) return 1; double int1 = sp1.getIntensity(); double int2 = sp2.getIntensity(); if (int1 == int2) return 0; if (int1> int2) return 1; return -1; } }; SortedLinkedList<Spectra> topSpectra = new SortedLinkedList<Spectra>(spectraCompare); Spectra s = msmit.next(); topSpectra.add(s); while (msmit.hasNext()) { s = msmit.next(); if (topSpectra.size()< topN) topSpectra.add(s); else if (spectraCompare.compare(s, topSpectra.getLast()) >0 ) { topSpectra.add(s); topSpectra.removeLast(); } } mWriter.writeHeader(); for (Spectra ts : topSpectra) mWriter.writeSpectra(ts); mWriter.close(); } }
lutzfischer/XiSearch
src/main/java/rappsilber/applications/TopY1R1.java
Java
apache-2.0
3,415
/* * fifo.h * * Created on: 2014-09-25 * Author: QiuWeibo */ #ifndef FIFO_H_ #define FIFO_H_ #ifdef __cplusplus extern "C" { #endif #ifdef FIFO_GLOBALS #define FIFO_EXT #else #define FIFO_EXT extern #endif #include "stm32f10x.h" typedef struct { u8 *write_ptr; // дָÕë u8 *read_ptr; // ¶ÁÖ¸Õë u8 *buffer; // Ö¸ÏòFIFOÊ×ÔªËØµØÖ· u32 data_size; // FIFOÔªËØµÄ´óС u32 fifo_size; // FIFO´óС char fifo_empty; // FIFO¿Õ±êÖ¾ char fifo_full; // FIFOÂú±êÖ¾ } GP_FIFO_StructDef; typedef struct { int *write_ptr; // дָÕë int *read_ptr; // ¶ÁÖ¸Õë int *buffer; // Ö¸ÏòFIFOÊ×ÔªËØµØÖ· u32 fifo_size; // FIFO´óС(ints) char fifo_empty; // FIFO¿Õ±êÖ¾ char fifo_full; // FIFOÂú±êÖ¾ } INT_FIFO_StructDef; typedef struct { char *write_ptr; // дָÕë char *read_ptr; // ¶ÁÖ¸Õë char *buffer; // Ö¸ÏòFIFOÊ×ÔªËØµØÖ· u32 fifo_size; // FIFO´óС(bytes) char fifo_empty; // FIFO¿Õ±êÖ¾ char fifo_full; // FIFOÂú±êÖ¾ } CHAR_FIFO_StructDef; //genery purpuse fifo FIFO_EXT void gp_fifo_init( GP_FIFO_StructDef *fifo_ptr, void *buffer_ptr, u32 data_size, u32 fifo_size ); FIFO_EXT int gp_fifo_push(GP_FIFO_StructDef *fifo_ptr, void *buffer_ptr); FIFO_EXT int gp_fifo_pop(GP_FIFO_StructDef* fifo_ptr, void* buffer_ptr); FIFO_EXT u32 gp_fifo_count(GP_FIFO_StructDef *fifo_ptr); FIFO_EXT void gp_fifo_reset(GP_FIFO_StructDef *fifo_ptr); FIFO_EXT void int_fifo_init( INT_FIFO_StructDef *fifo_ptr, int *buffer_ptr, u32 fifo_size ); FIFO_EXT int int_fifo_push(INT_FIFO_StructDef *fifo_ptr, int *buffer_ptr); FIFO_EXT int int_fifo_pop(INT_FIFO_StructDef* fifo_ptr, int* buffer_ptr); FIFO_EXT u32 int_fifo_count(INT_FIFO_StructDef *fifo_ptr); FIFO_EXT void int_fifo_reset(INT_FIFO_StructDef *fifo_ptr); FIFO_EXT void char_fifo_init( CHAR_FIFO_StructDef *fifo_ptr, char *buffer_ptr, u32 fifo_size ); FIFO_EXT int char_fifo_push(CHAR_FIFO_StructDef *fifo_ptr, char *buffer_ptr); FIFO_EXT int char_fifo_pop(CHAR_FIFO_StructDef* fifo_ptr, char* buffer_ptr); FIFO_EXT u32 char_fifo_count(CHAR_FIFO_StructDef *fifo_ptr); FIFO_EXT void char_fifo_reset(CHAR_FIFO_StructDef *fifo_ptr); #ifdef __cplusplus } #endif #endif /* FIFO_H_ */
webom2008/freeRTOS.project
FreeRTOSstm32f105/project/Embedded/utilities/fifo.h
C
apache-2.0
2,379
/* * Copyright 2013 SHU4M * * 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.shu4m; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; @Mojo(name = "set-qualifier", requiresDirectInvocation = true, defaultPhase = LifecyclePhase.NONE) public class SetQualifier extends AbstractVersionManipulator { @Parameter(required = true, property = "qualifier") private String qualifier; public void execute() throws MojoExecutionException, MojoFailureException { getLog().info("Set qualifier to " + qualifier); Version version = Version.parseVersion(mavenProject.getVersion()); Version newVersion = new Version(version.getMajor(), version.getMinor(), version.getIncremental(), qualifier); executeSetVersion(newVersion); } }
mhueb/shu4m
src/main/java/org/shu4m/SetQualifier.java
Java
apache-2.0
1,522
--- layout: post title: Single Shot MultiBox Detector subtitle: SSD date: 2017-11-04 author: stephen zhou catalog: true tags: - computer vision - deep learning - object detection --- # related work ![](https://i.imgur.com/91Xrk1v.png) **figure 1:** classic network of object detection # model ![](https://i.imgur.com/va1IK8u.png) **figure 2:** the confrontation between YOLO and SSD # details **Multi-scale feature maps for detection** **Convolutional predictors for detection:** 3x3 kernel default boxes **Default boxes and aspect ratios:** scale: ![](https://i.imgur.com/MVbIfLL.png) aspect ratios: 4 or 6 mxn—>(c+4)kmn ![](https://i.imgur.com/kRD4QY1.png) **figure 3:** SSD working framework # loss **Matching strategy:** every ground truth match with IOU higher than a threshold(0.5) **Loss function:** ![](https://i.imgur.com/AQhiMxj.png) L(conf): softmax L(loc): Smooth L1 Loss # trick **Negative mining:** ratio between the negatives and positives is at most 3:1 **Data Augmentation:** For every image: >- Use the entire original input image. >- Sample a patch so that the minimum IOU overlap with the objects is 0.1, 0.3, 0.5, 0.7, or 0.9. >- Randomly sample a patch Then for every patch , horizontally flipped with probability of 0.5 mAP update from 65.4% to 74.3% # experiment result ![](https://i.imgur.com/G6SpcRB.png) **figure 4:** PASCAL VOC2007 test detection results ![](https://i.imgur.com/U5qrhwf.png) **figure 5:** PASCAL VOC2007 test detection results of different models ![](https://i.imgur.com/c1kbGJK.png) **figure 6:** Sensitivity and impact of different object characteristics on VOC2007 test set using ![](https://i.imgur.com/DEJkKPu.jpg) **figure 7:** Detection examples on COCO test-dev with SSD512 model # model analysis >- Data augmentation is crucial >- More default box shapes is better >- Atrous is faster >- Multiple output layers at different resolutions is better ![](https://i.imgur.com/BfQjB17.png) **figure 8:** Effects of various design choices and components on SSD performance ![](https://i.imgur.com/ZqUBNtC.png) **figure 9:** Effects of using multiple output layers # conclusion >- The core of SSD :predicting category scores and box offsets for a fixed set of default bounding boxes in multiscale >- Faster and better
lab301-readings/lab301-readings.github.io
_posts/2017-11-04-ssd-object detection.md
Markdown
apache-2.0
2,323
// Copyright 2014 The Cockroach 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. See the AUTHORS file // for names of contributors. // // Author: Spencer Kimball (spencer.kimball@gmail.com) package storage import ( "bytes" "encoding/gob" "reflect" "testing" "github.com/cockroachdb/cockroach/gossip" ) var ( testRangeDescriptor = RangeDescriptor{ StartKey: KeyMin, Replicas: []Replica{ { NodeID: 1, StoreID: 1, RangeID: 1, Attrs: Attributes([]string{"dc1", "mem"}), }, { NodeID: 2, StoreID: 1, RangeID: 1, Attrs: Attributes([]string{"dc2", "mem"}), }, }, } testDefaultAcctConfig = AcctConfig{} testDefaultPermConfig = PermConfig{ Perms: []Permission{ {Read: true, Write: true}, }, } testDefaultZoneConfig = ZoneConfig{ Replicas: []Attributes{ Attributes([]string{"dc1", "mem"}), Attributes([]string{"dc2", "mem"}), }, } ) // createTestEngine creates an in-memory engine and initializes some // default configuration settings. func createTestEngine(t *testing.T) Engine { engine := NewInMem(Attributes([]string{"dc1", "mem"}), 1<<20) if err := putI(engine, KeyConfigAccountingPrefix, testDefaultAcctConfig); err != nil { t.Fatal(err) } if err := putI(engine, KeyConfigPermissionPrefix, testDefaultPermConfig); err != nil { t.Fatal(err) } if err := putI(engine, KeyConfigZonePrefix, testDefaultZoneConfig); err != nil { t.Fatal(err) } return engine } // createTestRange creates a new range initialized to the full extent // of the keyspace. The gossip instance is also returned for testing. func createTestRange(engine Engine, t *testing.T) (*Range, *gossip.Gossip) { rm := RangeMetadata{ RangeID: 0, StartKey: KeyMin, EndKey: KeyMax, Replicas: testRangeDescriptor, } g := gossip.New() r := NewRange(rm, engine, nil, g) r.Start() return r, g } // TestRangeGossipFirstRange verifies that the first range gossips its location. func TestRangeGossipFirstRange(t *testing.T) { r, g := createTestRange(createTestEngine(t), t) defer r.Stop() info, err := g.GetInfo(gossip.KeyFirstRangeMetadata) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(info.(RangeDescriptor), testRangeDescriptor) { t.Errorf("expected gossipped range locations to be equal: %s vs %s", info.(RangeDescriptor), testRangeDescriptor) } } // TestRangeGossipAllConfigs verifies that all config types are // gossipped. func TestRangeGossipAllConfigs(t *testing.T) { r, g := createTestRange(createTestEngine(t), t) defer r.Stop() testData := []struct { gossipKey string configs []*prefixConfig }{ {gossip.KeyConfigAccounting, []*prefixConfig{&prefixConfig{KeyMin, &testDefaultAcctConfig}}}, {gossip.KeyConfigPermission, []*prefixConfig{&prefixConfig{KeyMin, &testDefaultPermConfig}}}, {gossip.KeyConfigZone, []*prefixConfig{&prefixConfig{KeyMin, &testDefaultZoneConfig}}}, } for _, test := range testData { info, err := g.GetInfo(test.gossipKey) if err != nil { t.Fatal(err) } configs := info.([]*prefixConfig) if !reflect.DeepEqual(configs, test.configs) { t.Errorf("expected gossiped configs to be equal %s vs %s", configs, test.configs) } } } // TestRangeGossipConfigWithMultipleKeyPrefixes verifies that multiple // key prefixes for a config are gossipped. func TestRangeGossipConfigWithMultipleKeyPrefixes(t *testing.T) { engine := createTestEngine(t) // Add a permission for a new key prefix. db1Perm := PermConfig{ Perms: []Permission{ {Users: []string{"spencer"}, Read: true, Write: true, Priority: 100.0}, {Users: []string{"foo", "bar", "baz"}, Read: true, Write: false, Priority: 10.0}, }, } key := MakeKey(KeyConfigPermissionPrefix, Key("/db1")) if err := putI(engine, key, db1Perm); err != nil { t.Fatal(err) } r, g := createTestRange(engine, t) defer r.Stop() info, err := g.GetInfo(gossip.KeyConfigPermission) if err != nil { t.Fatal(err) } configs := info.([]*prefixConfig) expConfigs := []*prefixConfig{ &prefixConfig{KeyMin, &testDefaultPermConfig}, &prefixConfig{Key("/db1"), &db1Perm}, } if !reflect.DeepEqual(configs, expConfigs) { t.Errorf("expected gossiped configs to be equal %s vs %s", configs, expConfigs) } } // TestRangeGossipConfigUpdates verifies that writes to the // permissions cause the updated configs to be re-gossipped. func TestRangeGossipConfigUpdates(t *testing.T) { r, g := createTestRange(createTestEngine(t), t) defer r.Stop() // Add a permission for a new key prefix. db1Perm := PermConfig{ Perms: []Permission{ {Users: []string{"spencer"}, Read: true, Write: true, Priority: 100.0}, }, } key := MakeKey(KeyConfigPermissionPrefix, Key("/db1")) reply := &PutResponse{} var buf bytes.Buffer if err := gob.NewEncoder(&buf).Encode(db1Perm); err != nil { t.Fatal(err) } r.Put(&PutRequest{Key: key, Value: Value{Bytes: buf.Bytes()}}, reply) if reply.Error != nil { t.Fatal(reply.Error) } info, err := g.GetInfo(gossip.KeyConfigPermission) if err != nil { t.Fatal(err) } configs := info.([]*prefixConfig) expConfigs := []*prefixConfig{ &prefixConfig{KeyMin, &testDefaultPermConfig}, &prefixConfig{Key("/db1"), &db1Perm}, } if !reflect.DeepEqual(configs, expConfigs) { t.Errorf("expected gossiped configs to be equal %s vs %s", configs, expConfigs) } }
gude/cockroach
storage/range_test.go
GO
apache-2.0
5,824
from setuptools import find_packages from os import path, environ import io import os import re from distutils.core import setup from distutils.extension import Extension from Cython.Build import cythonize import numpy as np def read(*names, **kwargs): with io.open( os.path.join(os.path.dirname(__file__), *names), encoding=kwargs.get("encoding", "utf8") ) as fp: return fp.read() # pip's single-source version method as described here: # https://python-packaging-user-guide.readthedocs.io/single_source_version/ def find_version(*file_paths): version_file = read(*file_paths) version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M) if version_match: return version_match.group(1) raise RuntimeError("Unable to find version string.") # fetch include and library directories inc_dirs = [np.get_include(), '/usr/local/include/librealsense'] lib_dirs = ['/usr/local/lib'] # windows environment variables if 'PYRS_INCLUDES' in environ: inc_dirs.append(environ['PYRS_INCLUDES']) if 'PYRS_LIBS' in environ: lib_dirs.append(environ['PYRS_LIBS']) # cython extension, dont build if docs on_rtd = environ.get('READTHEDOCS') == 'True' if on_rtd: module = [] else: module = cythonize( [Extension( name='pyrealsense.rsutilwrapper', sources=["pyrealsense/rsutilwrapper.pyx", "pyrealsense/rsutilwrapperc.cpp"], libraries=['realsense'], include_dirs=inc_dirs, library_dirs=lib_dirs, language="c++",)]) # create long description from readme for pypi here = path.abspath(path.dirname(__file__)) with io.open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() setup(name='pyrealsense', version=find_version('pyrealsense', '__init__.py'), description='Cross-platform ctypes/Cython wrapper to the librealsense library.', long_description=long_description, author='Antoine Loriette', author_email='antoine.loriette@gmail.com', url='https://github.com/toinsson/pyrealsense', license='Apache', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', # 'License :: OSem :: Hardware', ], keywords='realsense', packages=find_packages(), ext_modules=module, setup_requires=['numpy', 'cython'], install_requires=['numpy', 'cython', 'pycparser', 'six'])
toinsson/pyrealsense
setup.py
Python
apache-2.0
2,524
/********************************************************************************** * $URL: https://source.sakaiproject.org/svn/kernel/tags/sakai-10.1/api/src/main/java/org/sakaiproject/email/api/DigestMessage.java $ * $Id: DigestMessage.java 105077 2012-02-24 22:54:29Z ottenhoff@longsight.com $ *********************************************************************************** * * Copyright (c) 2003, 2004, 2005, 2006, 2008 Sakai Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ECL-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.sakaiproject.email.api; /** * <p> * DigestMessage is one message in a digest * </p> */ public interface DigestMessage { /** * Access the to (user id) of the message. * * @return The to (user id) of the message. */ String getTo(); /** * Set the to (user id) of the message. * * @param to * The to (user id) of the message. */ void setTo(String to); /** * Access the subject of the message. * * @return The subject of the message. */ String getSubject(); /** * Set the subject of the message * * @param subject * The subject of the message. */ void setSubject(String subject); /** * Access the body of the message. * * @return The body of the message. */ String getBody(); /** * Set the body of the message * * @param body * The subject of the message. */ void setBody(String body); }
harfalm/Sakai-10.1
kernel/api/src/main/java/org/sakaiproject/email/api/DigestMessage.java
Java
apache-2.0
2,012
/* * Copyright 2014 Guidewire Software, Inc. */ package gw.internal.gosu.ir.transform.expression; import gw.internal.gosu.ir.nodes.IRMethodFactory; import gw.internal.gosu.ir.nodes.JavaClassIRType; import gw.internal.gosu.ir.transform.ExpressionTransformer; import gw.internal.gosu.ir.transform.TopLevelTransformationContext; import gw.internal.gosu.parser.BeanAccess; import gw.internal.gosu.parser.Expression; import gw.internal.gosu.parser.expressions.ArithmeticExpression; import gw.lang.ir.IRExpression; import gw.lang.ir.IRStatement; import gw.lang.ir.IRSymbol; import gw.lang.ir.IRType; import gw.lang.ir.expression.IRArithmeticExpression; import gw.lang.ir.expression.IRCompositeExpression; import gw.lang.ir.statement.IRAssignmentStatement; import gw.lang.parser.StandardCoercionManager; import gw.lang.reflect.IMethodInfo; import gw.lang.reflect.IRelativeTypeInfo; import gw.lang.reflect.IType; import gw.lang.reflect.TypeSystem; import gw.lang.reflect.java.JavaTypes; import gw.util.Rational; import java.math.BigDecimal; import java.math.BigInteger; import java.math.MathContext; import java.util.Arrays; import java.util.Collections; /** */ abstract class ArithmeticExpressionTransformer<T extends ArithmeticExpression> extends AbstractExpressionTransformer<T> { public ArithmeticExpressionTransformer( TopLevelTransformationContext cc, T parsedElem ) { super( cc, parsedElem ); } final IRExpression compileNumericArithmetic() { IType type = _expr().getType(); boolean bNumeric = BeanAccess.isNumericType( type ); IMethodInfo operatorOverload = _expr().getOverride(); if( bNumeric && operatorOverload != null ) { // The operator is overloaded, call into it... IRExpression lhs = ExpressionTransformer.compile( _expr().getLHS(), _cc() ); IRExpression rhs = ExpressionTransformer.compile( _expr().getRHS(), _cc() ); IRExpression callOverload = callMethod( IRMethodFactory.createIRMethod( operatorOverload, null ), lhs, exprList( rhs ) ); if( type.isPrimitive() ) { return callOverload; } return buildCast( getDescriptor( type ), callOverload ); } else { if( isPrimitiveArithmetic() ) { return primitiveArithmetic(); } else { IType lhsType = _expr().getLHS().getType(); IType rhsType = _expr().getRHS().getType(); if( isMixedPrimitiveAndBoxedArithmetic( type, lhsType, rhsType ) ) { return mixedPrimitiveAndBoxedArithmetic( type, _expr().getLHS(), _expr().getRHS(), _expr().isNullSafe(), _expr().getOperator() ); } else if( isBigDecimalArithmetic( type, lhsType, rhsType ) || isBigIntegerArithmetic( type, lhsType, rhsType ) ) { return bigArithmetic(); } else if( isMixedBigDecimalArithmetic( type, lhsType, rhsType ) || isMixedBigIntegerArithmetic( type, lhsType, rhsType ) ) { return mixedBigArithmetic( type, _expr().getLHS(), _expr().getRHS(), _expr().isNullSafe(), _expr().getOperator() ); } else if( isMixedRationalArithmetic( type ) ) { return mixedRationalArithmetic( _expr().getLHS(), _expr().getRHS(), _expr().isNullSafe(), _expr().getOperator() ); } } } return null; } final boolean isPrimitiveArithmetic() { return isPrimitiveNumberType( _expr().getType() ) && isPrimitiveNumberType( _expr().getLHS().getType() ) && isPrimitiveNumberType( _expr().getRHS().getType() ); } final boolean isMixedPrimitiveAndBoxedArithmetic( IType type, IType lhsType, IType rhsType ) { return isNumberType( type ) && isNumberType( lhsType ) && isNumberType( rhsType ); } final boolean isBigDecimalArithmetic( IType type, IType lhsType, IType rhsType ) { return JavaTypes.BIG_DECIMAL().equals( type ) && JavaTypes.BIG_DECIMAL().equals( lhsType ) && JavaTypes.BIG_DECIMAL().equals( rhsType ); } final boolean isBigIntegerArithmetic( IType type, IType lhsType, IType rhsType ) { return JavaTypes.BIG_INTEGER().equals( type ) && JavaTypes.BIG_INTEGER().equals( lhsType ) && JavaTypes.BIG_INTEGER().equals( rhsType ); } final boolean isMixedBigDecimalArithmetic( IType type, IType lhsType, IType rhsType ) { return JavaTypes.BIG_DECIMAL().equals( type ) && (isNumberType( lhsType ) || JavaTypes.BIG_DECIMAL().equals( lhsType )) && (isNumberType( rhsType ) || JavaTypes.BIG_DECIMAL().equals( rhsType )); } final boolean isMixedBigIntegerArithmetic( IType type, IType lhsType, IType rhsType ) { return JavaTypes.BIG_INTEGER().equals( type ) && (isNumberType( lhsType ) || JavaTypes.BIG_INTEGER().equals( lhsType )) && (isNumberType( rhsType ) || JavaTypes.BIG_INTEGER().equals( rhsType )); } final boolean isMixedRationalArithmetic( IType type ) { return JavaTypes.RATIONAL().equals( type ); } final IRExpression mixedPrimitiveAndBoxedArithmetic( IType exprType, Expression lhsExpr, Expression rhsExpr, boolean bNullSafe, String strOp ) { IType primitiveType = exprType.isPrimitive() ? exprType : TypeSystem.getPrimitiveType( exprType ); if( bNullSafe ) { IRExpression lhs = ExpressionTransformer.compile( lhsExpr, _cc() ); IRExpression rhs = ExpressionTransformer.compile( rhsExpr, _cc() ); IRSymbol tempLhs = _cc().makeAndIndexTempSymbol( getDescriptor( lhsExpr.getType() ) ); IRAssignmentStatement tempLhsAssn = buildAssignment( tempLhs, lhs ); IRSymbol tempRhs = _cc().makeAndIndexTempSymbol( getDescriptor( rhsExpr.getType() ) ); IRAssignmentStatement tempRhsAssn = buildAssignment( tempRhs, rhs ); IRSymbol lhsPrim; IRSymbol rhsPrim; IRCompositeExpression compExpr = new IRCompositeExpression( tempLhsAssn, tempRhsAssn ); IRSymbol isNull = _cc().makeAndIndexTempSymbol( getDescriptor( boolean.class ) ); IRAssignmentStatement isNullAssn = buildAssignment( isNull, booleanLiteral( false ) ); compExpr.addElement( isNullAssn ); if( StandardCoercionManager.isBoxed( lhsExpr.getType() ) ) { IType lhsPrimType = TypeSystem.getPrimitiveType( lhsExpr.getType() ); lhsPrim = _cc().makeAndIndexTempSymbol( getDescriptor( primitiveType ) ); compExpr.addElement( buildAssignment( lhsPrim, convertNullToPrimitive( primitiveType ) ) ); compExpr.addElement( buildIfElse( buildEquals( identifier( tempLhs ), nullLiteral() ), buildAssignment( isNull, booleanLiteral( true ) ), buildAssignment( lhsPrim, numberConvert( lhsPrimType, primitiveType, unboxValueFromType( lhsExpr.getType(), identifier( tempLhs ) ) ) ) ) ); } else { lhsPrim = _cc().makeAndIndexTempSymbol( getDescriptor( primitiveType ) ); compExpr.addElement( buildAssignment( lhsPrim, numberConvert( lhsExpr.getType(), primitiveType, identifier( tempLhs ) ) ) ); } if( StandardCoercionManager.isBoxed( rhsExpr.getType() ) ) { IType rhsPrimType = TypeSystem.getPrimitiveType( rhsExpr.getType() ); rhsPrim = _cc().makeAndIndexTempSymbol( getDescriptor( primitiveType ) ); compExpr.addElement( buildAssignment( rhsPrim, convertNullToPrimitive( primitiveType ) ) ); compExpr.addElement( buildIfElse( buildEquals( identifier( tempRhs ), nullLiteral() ), buildAssignment( isNull, booleanLiteral( true ) ), buildAssignment( rhsPrim, numberConvert( rhsPrimType, primitiveType, unboxValueFromType( rhsExpr.getType(), identifier( tempRhs ) ) ) ) ) ); } else { rhsPrim = _cc().makeAndIndexTempSymbol( getDescriptor( primitiveType ) ); compExpr.addElement( buildAssignment( rhsPrim, numberConvert( rhsExpr.getType(), primitiveType, identifier( tempRhs ) ) ) ); } IRExpression expr = makeIRArithmeticExpression( primitiveType , identifier( lhsPrim ), identifier( rhsPrim ), isCheckedArithmeticEnabled() ); if( StandardCoercionManager.isBoxed( exprType ) ) { expr = boxValueToType( exprType, expr ); } expr = buildTernary( buildEquals( identifier( isNull ), booleanLiteral( true ) ), StandardCoercionManager.isBoxed( exprType ) ? nullLiteral() : numberConvert( JavaTypes.pINT(), exprType, pushConstant( 0 ) ), expr, getDescriptor( exprType ) ); compExpr.addElement( expr ); return compExpr; } else { IRExpression lhs = ExpressionTransformer.compile( lhsExpr, _cc() ); if( StandardCoercionManager.isBoxed( lhsExpr.getType() ) ) { lhs = unboxValueFromType( lhsExpr.getType(), lhs ); } lhs = numberConvert( lhs.getType(), getDescriptor( primitiveType ), lhs ); IRExpression rhs = ExpressionTransformer.compile( rhsExpr, _cc() ); if( StandardCoercionManager.isBoxed( rhsExpr.getType() ) ) { rhs = unboxValueFromType( rhsExpr.getType(), rhs ); } rhs = numberConvert( rhs.getType(), getDescriptor( primitiveType ), rhs ); IRExpression expr = makeIRArithmeticExpression( primitiveType , lhs, rhs, isCheckedArithmeticEnabled() ); if( StandardCoercionManager.isBoxed( exprType ) ) { expr = boxValueToType( exprType, expr ); } return expr; } } final IRExpression mixedBigArithmetic( IType bigType, Expression lhsExpr, Expression rhsExpr, boolean bNullSafe, String strOp ) { Class bigClass = bigType == JavaTypes.BIG_INTEGER() ? BigInteger.class : BigDecimal.class; assert bigType == JavaTypes.BIG_INTEGER() || bigType == JavaTypes.BIG_DECIMAL(); IRExpression lhs = ExpressionTransformer.compile( lhsExpr, _cc() ); IRExpression rhs = ExpressionTransformer.compile( rhsExpr, _cc() ); IRSymbol tempLhsInit = _cc().makeAndIndexTempSymbol( getDescriptor( lhsExpr.getType() ) ); IRAssignmentStatement tempLhsInitAssn = buildAssignment( tempLhsInit, lhs ); IRSymbol tempRhsInit = _cc().makeAndIndexTempSymbol( getDescriptor( rhsExpr.getType() ) ); IRAssignmentStatement tempRhsInitAssn = buildAssignment( tempRhsInit, rhs ); IRSymbol tempLhsRet = _cc().makeAndIndexTempSymbol( getDescriptor( bigType ) ); IRStatement tempLhsRetAssn = convertOperandToBig( bigType, bigClass, lhsExpr.getType(), identifier( tempLhsInit ), tempLhsRet ); IRSymbol tempRhsRet = _cc().makeAndIndexTempSymbol( getDescriptor( bigType ) ); IRStatement tempRhsRetAssn = convertOperandToBig( bigType, bigClass, rhsExpr.getType(), identifier( tempRhsInit ), tempRhsRet ); if( bNullSafe ) { return buildComposite( tempLhsInitAssn, tempRhsInitAssn, buildCast( getDescriptor( bigType ), buildTernary( lhs.getType().isPrimitive() ? booleanLiteral( false ) : buildEquals( identifier( tempLhsInit ), nullLiteral() ), nullLiteral(), buildTernary( rhs.getType().isPrimitive() ? booleanLiteral( false ) : buildEquals( identifier( tempRhsInit ), nullLiteral() ), nullLiteral(), buildComposite( tempLhsRetAssn, tempRhsRetAssn, makeBigExpression( bigClass, identifier( tempLhsRet ), identifier( tempRhsRet ), strOp ) ), getDescriptor( bigType ) ), getDescriptor( bigType ) ) ) ); } else { return buildComposite( tempLhsInitAssn, tempRhsInitAssn, tempLhsRetAssn, tempRhsRetAssn, makeBigExpression( bigClass, identifier( tempLhsRet ), identifier( tempRhsRet ), strOp ) ); } } final IRExpression mixedRationalArithmetic( Expression lhsExpr, Expression rhsExpr, boolean bNullSafe, String strOp ) { IRExpression lhs = ExpressionTransformer.compile( lhsExpr, _cc() ); IRExpression rhs = ExpressionTransformer.compile( rhsExpr, _cc() ); IRSymbol tempLhsInit = _cc().makeAndIndexTempSymbol( getDescriptor( lhsExpr.getType() ) ); IRAssignmentStatement tempLhsInitAssn = buildAssignment( tempLhsInit, lhs ); IRSymbol tempRhsInit = _cc().makeAndIndexTempSymbol( getDescriptor( rhsExpr.getType() ) ); IRAssignmentStatement tempRhsInitAssn = buildAssignment( tempRhsInit, rhs ); IRType rationalDesc = getDescriptor( Rational.class ); IRSymbol tempLhsRet = _cc().makeAndIndexTempSymbol( rationalDesc ); IRStatement tempLhsRetAssn = convertOperandToRational( lhsExpr.getType(), identifier( tempLhsInit ), tempLhsRet ); IRSymbol tempRhsRet = _cc().makeAndIndexTempSymbol( rationalDesc ); IRStatement tempRhsRetAssn = convertOperandToRational( rhsExpr.getType(), identifier( tempRhsInit ), tempRhsRet ); if( bNullSafe ) { return buildComposite( tempLhsInitAssn, tempRhsInitAssn, buildCast( rationalDesc, buildTernary( lhs.getType().isPrimitive() ? booleanLiteral( false ) : buildEquals( identifier( tempLhsInit ), nullLiteral() ), nullLiteral(), buildTernary( rhs.getType().isPrimitive() ? booleanLiteral( false ) : buildEquals( identifier( tempRhsInit ), nullLiteral() ), nullLiteral(), buildComposite( tempLhsRetAssn, tempRhsRetAssn, rationalArithmetic( identifier( tempLhsRet ), identifier( tempRhsRet ), strOp ) ), rationalDesc ), rationalDesc ) ) ); } else { return buildComposite( tempLhsInitAssn, tempRhsInitAssn, tempLhsRetAssn, tempRhsRetAssn, rationalArithmetic( identifier( tempLhsRet ), identifier( tempRhsRet ), strOp ) ); } } final IRExpression bigArithmetic() { IType bigType = _expr().getType(); if( bigType != JavaTypes.BIG_INTEGER() && bigType != JavaTypes.BIG_DECIMAL() ) { throw new AssertionError(); } Class bigClass = bigType == JavaTypes.BIG_INTEGER() ? BigInteger.class : BigDecimal.class; IRExpression lhs = ExpressionTransformer.compile( _expr().getLHS(), _cc() ); IRExpression rhs = ExpressionTransformer.compile( _expr().getRHS(), _cc() ); if( _expr().isNullSafe() ) { IRSymbol tempLhs = _cc().makeAndIndexTempSymbol( getDescriptor( bigType ) ); IRAssignmentStatement tempLhsAssn = buildAssignment( tempLhs, lhs ); IRSymbol tempRhs = _cc().makeAndIndexTempSymbol( getDescriptor( bigType ) ); IRAssignmentStatement tempRhsAssn = buildAssignment( tempRhs, rhs ); return buildComposite( tempLhsAssn, tempRhsAssn, buildCast( getDescriptor( bigType ), buildTernary( buildEquals( identifier( tempLhs ), nullLiteral() ), nullLiteral(), buildTernary( buildEquals( identifier( tempRhs ), nullLiteral() ), nullLiteral(), makeBigExpression( bigClass, identifier( tempLhs ), identifier( tempRhs ), _expr().getOperator() ), getDescriptor( bigType ) ), getDescriptor( bigType ) ) ) ); } else { return makeBigExpression( bigClass, lhs, rhs, _expr().getOperator() ); } } final IRExpression makeBigExpression( Class bigClass, IRExpression lhs, IRExpression rhs, String strOp ) { if( bigClass == BigDecimal.class ) { return bigDecimalArithmetic( lhs, rhs, strOp ); } else { return bigIntegerArithmetic( lhs, rhs, strOp ); } } final IRExpression bigDecimalArithmetic( IRExpression lhs, IRExpression rhs, String strOp ) { if( strOp.equals( "+" ) || strOp.equals( "?+" ) || strOp.equals( "!+" ) ) { return callMethod( BigDecimal.class, "add", new Class[] {BigDecimal.class}, lhs, Collections.singletonList( rhs ) ); } else if( strOp.equals( "-" ) || strOp.equals( "?-" ) || strOp.equals( "!-" ) ) { return callMethod( BigDecimal.class, "subtract", new Class[] {BigDecimal.class}, lhs, Collections.singletonList( rhs ) ); } else if( strOp.equals( "*" ) || strOp.equals( "?*" ) || strOp.equals( "!*" ) ) { return callMethod( BigDecimal.class, "multiply", new Class[] {BigDecimal.class}, lhs, Collections.singletonList( rhs ) ); } else if( strOp.equals( "/" ) || strOp.equals( "?/" ) ) { return callMethod( BigDecimal.class, "divide", new Class[] {BigDecimal.class, MathContext.class}, lhs, Arrays.asList( rhs, getStaticField( TypeSystem.get( MathContext.class ), "DECIMAL128", JavaClassIRType.get( MathContext.class ), IRelativeTypeInfo.Accessibility.PUBLIC ) ) ); } else if( strOp.equals( "%" ) || strOp.equals( "?%" ) ) { IRExpression remainder = callMethod( BigDecimal.class, "remainder", new Class[] {BigDecimal.class, MathContext.class}, lhs, Arrays.asList( rhs, getStaticField( TypeSystem.get( MathContext.class ), "DECIMAL128", JavaClassIRType.get( MathContext.class ), IRelativeTypeInfo.Accessibility.PUBLIC ) ) ); return callMethod( BigDecimal.class, "abs", new Class[] {}, remainder, Collections.<IRExpression>emptyList() ); } throw new IllegalStateException(); } final IRExpression bigIntegerArithmetic( IRExpression lhs, IRExpression rhs, String strOp ) { if( strOp.equals( "+" ) || strOp.equals( "?+" ) || strOp.equals( "!+" ) ) { return callMethod( BigInteger.class, "add", new Class[] {BigInteger.class}, lhs, Collections.singletonList( rhs ) ); } else if( strOp.equals( "-" ) || strOp.equals( "?-" ) || strOp.equals( "!-" ) ) { return callMethod( BigInteger.class, "subtract", new Class[] {BigInteger.class}, lhs, Collections.singletonList( rhs ) ); } else if( strOp.equals( "*" ) || strOp.equals( "?*" ) || strOp.equals( "!*" ) ) { return callMethod( BigInteger.class, "multiply", new Class[] {BigInteger.class}, lhs, Collections.singletonList( rhs ) ); } else if( strOp.equals( "/" ) || strOp.equals( "?/" ) ) { return callMethod( BigInteger.class, "divide", new Class[] {BigInteger.class}, lhs, Collections.singletonList( rhs ) ); } else if( strOp.equals( "%" ) || strOp.equals( "?%" ) ) { return callMethod( BigInteger.class, "mod", new Class[]{BigInteger.class}, lhs, Collections.singletonList( rhs ) ); } throw new IllegalStateException(); } final IRExpression rationalArithmetic( IRExpression lhs, IRExpression rhs, String strOp ) { if( strOp.equals( "+" ) || strOp.equals( "?+" ) || strOp.equals( "!+" ) ) { return callMethod( Rational.class, "add", new Class[] {Rational.class}, lhs, Collections.singletonList( rhs ) ); } else if( strOp.equals( "-" ) || strOp.equals( "?-" ) || strOp.equals( "!-" ) ) { return callMethod( Rational.class, "subtract", new Class[] {Rational.class}, lhs, Collections.singletonList( rhs ) ); } else if( strOp.equals( "*" ) || strOp.equals( "?*" ) || strOp.equals( "!*" ) ) { return callMethod( Rational.class, "multiply", new Class[] {Rational.class}, lhs, Collections.singletonList( rhs ) ); } else if( strOp.equals( "/" ) || strOp.equals( "?/" ) ) { return callMethod( Rational.class, "divide", new Class[] {Rational.class}, lhs, Collections.singletonList( rhs ) ); } else if( strOp.equals( "%" ) || strOp.equals( "?%" ) ) { return callMethod( Rational.class, "modulo", new Class[] {Rational.class}, lhs, Collections.singletonList( rhs ) ); } throw new IllegalStateException(); } final IRExpression primitiveArithmetic() { IType type = _expr().getType(); IRExpression lhs = ExpressionTransformer.compile( _expr().getLHS(), _cc() ); lhs = numberConvert( _expr().getLHS().getType(), type, lhs ); IRExpression rhs = ExpressionTransformer.compile( _expr().getRHS(), _cc() ); rhs = numberConvert( _expr().getRHS().getType(), type, rhs ); return makeIRArithmeticExpression( type, lhs, rhs, isCheckedArithmeticEnabled() ); } private IRExpression makeIRArithmeticExpression( IType type, IRExpression lhs, IRExpression rhs, boolean checked ) { IRType descriptor = getDescriptor( type ); IRArithmeticExpression.Operation op = IRArithmeticExpression.Operation.fromString( _expr().getOperator() ); if( checked && ( type == JavaTypes.pINT() || type == JavaTypes.pLONG() ) && !_expr().isUnchecked() ) { Class[] paramTypes = type == JavaTypes.pINT() ? new Class[]{int.class, int.class} : new Class[]{long.class, long.class}; switch( op ) { case Addition: return callStaticMethod( Math.class, "addExact", paramTypes, Arrays.asList( lhs, rhs ) ); case Subtraction: return callStaticMethod( Math.class, "subtractExact", paramTypes, Arrays.asList( lhs, rhs ) ); case Multiplication: return callStaticMethod( Math.class, "multiplyExact", paramTypes, Arrays.asList( lhs, rhs ) ); default: return new IRArithmeticExpression( descriptor, lhs, rhs, op ); } } return new IRArithmeticExpression( descriptor, lhs, rhs, op ); } }
gosu-lang/gosu-lang
gosu-core/src/main/java/gw/internal/gosu/ir/transform/expression/ArithmeticExpressionTransformer.java
Java
apache-2.0
21,846
# (C) Copyright 2017 Hewlett Packard Enterprise Development LP # # 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_relative '../../api300/synergy/logical_interconnect_group' module OneviewSDK module API500 module Synergy # Logical interconnect group resource implementation for API500 Synergy class LogicalInterconnectGroup < OneviewSDK::API300::Synergy::LogicalInterconnectGroup end end end end
HewlettPackard/oneview-sdk-ruby
lib/oneview-sdk/resource/api500/synergy/logical_interconnect_group.rb
Ruby
apache-2.0
920
# Briza toluccensis Kunth 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/Poales/Poaceae/Trisetum/Trisetum spicatum/ Syn. Briza toluccensis/README.md
Markdown
apache-2.0
180
<!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 (version 1.7.0_75) on Wed Jul 20 17:40:21 CDT 2016 --> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"> <title>Uses of Class org.gramar.tag.BodyTagHandler (org.gramar:gramar 1.0.0 API)</title> <meta name="date" content="2016-07-20"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.gramar.tag.BodyTagHandler (org.gramar:gramar 1.0.0 API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><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/gramar/tag/BodyTagHandler.html" title="class in org.gramar.tag">Class</a></li> <li class="navBarCell1Rev">Use</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> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/gramar/tag/class-use/BodyTagHandler.html" target="_top">Frames</a></li> <li><a href="BodyTagHandler.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../allclasses-noframe.html">All 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.gramar.tag.BodyTagHandler" class="title">Uses of Class<br>org.gramar.tag.BodyTagHandler</h2> </div> <div class="classUseContainer">No usage of org.gramar.tag.BodyTagHandler</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><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/gramar/tag/BodyTagHandler.html" title="class in org.gramar.tag">Class</a></li> <li class="navBarCell1Rev">Use</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> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/gramar/tag/class-use/BodyTagHandler.html" target="_top">Frames</a></li> <li><a href="BodyTagHandler.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../allclasses-noframe.html">All 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; 2016. All rights reserved.</small></p> </body> </html>
chrisGerken/gramar
core/gramar/apidocs/org/gramar/tag/class-use/BodyTagHandler.html
HTML
apache-2.0
4,212
/* ******************************************************************************* * Copyright (C) 2007-2009, International Business Machines Corporation and * * others. All Rights Reserved. * ******************************************************************************* */ package com.ibm.icu.impl.duration; import java.text.FieldPosition; import java.util.Date; import com.ibm.icu.text.DurationFormat; import com.ibm.icu.util.ULocale; /** * @author srl */ public class BasicDurationFormat extends DurationFormat { /** * */ private static final long serialVersionUID = -3146984141909457700L; transient DurationFormatter formatter; transient PeriodFormatter pformatter; transient PeriodFormatterService pfs = null; public static BasicDurationFormat getInstance(ULocale locale) { return new BasicDurationFormat(locale); } private static boolean checkXMLDuration = true; public StringBuffer format(Object object, StringBuffer toAppend, FieldPosition pos) { if(object instanceof Long) { String res = formatDurationFromNow(((Long)object).longValue()); return toAppend.append(res); } else if(object instanceof Date) { String res = formatDurationFromNowTo(((Date)object)); return toAppend.append(res); } if(checkXMLDuration) try { if(object instanceof javax.xml.datatype.Duration) { String res = formatDuration(object); return toAppend.append(res); } } catch ( NoClassDefFoundError ncdfe ) { System.err.println("Skipping XML capability"); checkXMLDuration = false; // don't try again } throw new IllegalArgumentException("Cannot format given Object as a Duration"); } public BasicDurationFormat() { pfs = BasicPeriodFormatterService.getInstance(); formatter = pfs.newDurationFormatterFactory().getFormatter(); pformatter = pfs.newPeriodFormatterFactory().setDisplayPastFuture(false).getFormatter(); } /** * */ public BasicDurationFormat(ULocale locale) { super(locale); pfs = BasicPeriodFormatterService.getInstance(); formatter = pfs.newDurationFormatterFactory().setLocale(locale.getName()).getFormatter(); pformatter = pfs.newPeriodFormatterFactory().setDisplayPastFuture(false).setLocale(locale.getName()).getFormatter(); } /* (non-Javadoc) * @see com.ibm.icu.text.DurationFormat#formatDurationFrom(long, long) */ public String formatDurationFrom(long duration, long referenceDate) { return formatter.formatDurationFrom(duration, referenceDate); } /* (non-Javadoc) * @see com.ibm.icu.text.DurationFormat#formatDurationFromNow(long) */ public String formatDurationFromNow(long duration) { return formatter.formatDurationFromNow(duration); } /* (non-Javadoc) * @see com.ibm.icu.text.DurationFormat#formatDurationFromNowTo(java.util.Date) */ public String formatDurationFromNowTo(Date targetDate) { return formatter.formatDurationFromNowTo(targetDate); } /** * JDK 1.5+ only * @param obj Object being passed. * @return The PeriodFormatter object formatted to the object passed. * @see "http://java.sun.com/j2se/1.5.0/docs/api/javax/xml/datatype/Duration.html" */ public String formatDuration(Object obj) { javax.xml.datatype.DatatypeConstants.Field inFields[] = { javax.xml.datatype.DatatypeConstants.YEARS, javax.xml.datatype.DatatypeConstants.MONTHS, javax.xml.datatype.DatatypeConstants.DAYS, javax.xml.datatype.DatatypeConstants.HOURS, javax.xml.datatype.DatatypeConstants.MINUTES, javax.xml.datatype.DatatypeConstants.SECONDS, }; TimeUnit outFields[] = { TimeUnit.YEAR, TimeUnit.MONTH, TimeUnit.DAY, TimeUnit.HOUR, TimeUnit.MINUTE, TimeUnit.SECOND, }; javax.xml.datatype.Duration inDuration = (javax.xml.datatype.Duration)obj; Period p = null; javax.xml.datatype.Duration duration = inDuration; boolean inPast = false; if(inDuration.getSign()<0) { duration = inDuration.negate(); inPast = true; } // convert a Duration to a Period boolean sawNonZero = false; // did we have a set, non-zero field? for(int i=0;i<inFields.length;i++) { if(duration.isSet(inFields[i])) { Number n = duration.getField(inFields[i]); if(n.intValue() == 0 && !sawNonZero) { continue; // ignore zero fields larger than the largest nonzero field } else { sawNonZero = true; } float floatVal = n.floatValue(); // is there a 'secondary' unit to set? TimeUnit alternateUnit = null; float alternateVal = 0; // see if there is a fractional part if(outFields[i]==TimeUnit.SECOND) { double fullSeconds = floatVal; double intSeconds = Math.floor(floatVal); double millis = (fullSeconds-intSeconds)*1000.0; if(millis > 0.0) { alternateUnit = TimeUnit.MILLISECOND; alternateVal=(float)millis; floatVal=(float)intSeconds; } } if(p == null) { p = Period.at(floatVal, outFields[i]); } else { p = p.and(floatVal, outFields[i]); } if(alternateUnit != null) { p = p.and(alternateVal, alternateUnit); // add in MILLISECONDs } } } if(p == null) { // no fields set = 0 seconds return formatDurationFromNow(0); } else { if(inPast) {// was negated, above. p = p.inPast(); } else { p = p.inFuture(); } } // now, format it. return pformatter.format(p); } }
UweTrottmann/QuickDic-Dictionary
jars/icu4j-4_8_1_1/main/classes/core/src/com/ibm/icu/impl/duration/BasicDurationFormat.java
Java
apache-2.0
6,551
/* Copyright 2021 Stanford University * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <cstdio> #include <cassert> #include <cstdlib> #include <unistd.h> #include <queue> #include "legion.h" #include "cgsolver.h" #include "cgtasks.h" #include "cgmapper.h" using namespace Legion; Logger log_app("app"); #define LOG_ASSERT(cond, logger, ...) do { \ if(!(cond)) { \ (logger).fatal(__VA_ARGS__); \ assert(false); \ } \ } while(0) enum { TOP_LEVEL_TASK_ID, SPMD_INIT_TASK_ID, SPMD_MAIN_TASK_ID, INIT_FIELD_TASK_ID, SPMV_FIELD_TASK_ID, DOTP_FIELD_TASK_ID, ADD_FIELD_TASK_ID, }; enum { TRACE_ID_CG_ITER = 1, }; enum { DIR_X = 0, DIR_Y = 1, DIR_Z = 2 }; enum { SIDE_MINUS = 0, SIDE_PLUS = 1, }; template <int DIM> static int volume(const Point<DIM>& p) { int v = 1; for(unsigned i = 0; i < DIM; i++) v *= p[i]; return v; } template <int DIM> inline Point<DIM> LEFT(const Point<DIM>& p) { Point<DIM> p2(p); p2[0]--; return p2; } template <int DIM> inline Point<DIM> RIGHT(const Point<DIM>& p) { Point<DIM> p2(p); p2[0]++; return p2; } template <int DIM> inline Point<DIM> UP(const Point<DIM>& p) { Point<DIM> p2(p); p2[1]--; return p2; } template <int DIM> inline Point<DIM> DOWN(const Point<DIM>& p) { Point<DIM> p2(p); p2[1]++; return p2; } template <int DIM> inline Point<DIM> FRONT(const Point<DIM>& p) { Point<DIM> p2(p); p2[2]--; return p2; } template <int DIM> inline Point<DIM> BACK(const Point<DIM>& p) { Point<DIM> p2(p); p2[2]++; return p2; } // a "reduction" op that "merges" together PhaseBarrier's created by each shard struct BarrierCombineReductionOp { static const ReductionOpID redop_id = 77; typedef PhaseBarrier LHS; typedef PhaseBarrier RHS; static const PhaseBarrier identity; static void combine(LHS& lhs, RHS rhs) { // no exists() method for PhaseBarrier... if(!(rhs == PhaseBarrier())) { assert(lhs == PhaseBarrier()); lhs = rhs; } } template <bool EXCL> static void apply(LHS& lhs, RHS rhs) { combine(lhs, rhs); } template <bool EXCL> static void fold(RHS& rhs1, RHS rhs2) { combine(rhs1, rhs2); } }; typedef ReductionAccessor<BarrierCombineReductionOp,true/*exclusive*/,3,coord_t, Realm::AffineAccessor<BarrierCombineReductionOp::RHS,3,coord_t> > AccessorRDpb; /*static*/ const PhaseBarrier BarrierCombineReductionOp::identity; struct DoubleAddReductionOp { static const ReductionOpID redop_id = 78; typedef double LHS; typedef double RHS; static const double identity; template <bool EXCL> static void apply(LHS& lhs, RHS rhs) { lhs += rhs; } template <bool EXCL> static void fold(RHS& rhs1, RHS rhs2) { rhs1 += rhs2; } }; /*static*/ const double DoubleAddReductionOp::identity = 0.0; template <typename T1, typename T2> struct FutureLessThan { static TaskID taskid; static void preregister_task(TaskID new_taskid = AUTO_GENERATE_ID); static Future compute(Runtime *runtime, Context ctx, Future lhs, Future rhs); static bool cpu_task(const Task *task, const std::vector<PhysicalRegion> &regions, Context ctx, Runtime *runtime); }; template <typename T1, typename T2> /*static*/ void FutureLessThan<T1,T2>::preregister_task(TaskID new_taskid /*= AUTO_GENERATE_ID*/) { taskid = ((new_taskid == AUTO_GENERATE_ID) ? Runtime::generate_static_task_id() : new_taskid); const char *name = "future_less_than"; TaskVariantRegistrar tvr(taskid, name); tvr.add_constraint(ProcessorConstraint(Processor::LOC_PROC)); tvr.set_leaf(true); Runtime::preregister_task_variant<bool, &FutureLessThan<T1,T2>::cpu_task>(tvr, name); } template <typename T1, typename T2> /*static*/ Future FutureLessThan<T1,T2>::compute(Runtime *runtime, Context ctx, Future lhs, Future rhs) { TaskLauncher launcher(taskid, TaskArgument()); launcher.add_future(lhs); launcher.add_future(rhs); return runtime->execute_task(ctx, launcher); } template <typename T1, typename T2> /*static*/ bool FutureLessThan<T1,T2>::cpu_task(const Task *task, const std::vector<PhysicalRegion> &regions, Context ctx, Runtime *runtime) { assert(task->futures.size() == 2); T1 lhs = Future(task->futures[0]).get_result<T1>(); T2 rhs = Future(task->futures[1]).get_result<T2>(); //std::cout << "FLT: " << lhs << " < " << rhs << "?\n"; return lhs < rhs; } typedef FutureLessThan<double,double> FLT_double; template <> /*static*/ TaskID FutureLessThan<double,double>::taskid = 0; template <typename TR, typename T1, typename T2> struct FutureDivide { static TaskID taskid; static void preregister_task(TaskID new_taskid = AUTO_GENERATE_ID); static Future compute(Runtime *runtime, Context ctx, Future lhs, Future rhs); static TR cpu_task(const Task *task, const std::vector<PhysicalRegion> &regions, Context ctx, Runtime *runtime); }; template <typename TR, typename T1, typename T2> /*static*/ void FutureDivide<TR,T1,T2>::preregister_task(TaskID new_taskid /*= AUTO_GENERATE_ID*/) { taskid = ((new_taskid == AUTO_GENERATE_ID) ? Runtime::generate_static_task_id() : new_taskid); const char *name = "future_divide"; TaskVariantRegistrar tvr(taskid, name); tvr.add_constraint(ProcessorConstraint(Processor::LOC_PROC)); tvr.set_leaf(true); Runtime::preregister_task_variant<TR, &FutureDivide<TR,T1,T2>::cpu_task>(tvr, name); } template <typename TR, typename T1, typename T2> /*static*/ Future FutureDivide<TR,T1,T2>::compute(Runtime *runtime, Context ctx, Future lhs, Future rhs) { TaskLauncher launcher(taskid, TaskArgument()); launcher.add_future(lhs); launcher.add_future(rhs); return runtime->execute_task(ctx, launcher); } template <typename TR, typename T1, typename T2> /*static*/ TR FutureDivide<TR,T1,T2>::cpu_task(const Task *task, const std::vector<PhysicalRegion> &regions, Context ctx, Runtime *runtime) { assert(task->futures.size() == 2); T1 lhs = Future(task->futures[0]).get_result<T1>(); T2 rhs = Future(task->futures[1]).get_result<T2>(); TR res = lhs / rhs; //std::cout << "FDV: " << lhs << " / " << rhs << " = " << res << "\n"; return res; } typedef FutureDivide<double,double,double> FDV_double; template <> /*static*/ TaskID FutureDivide<double,double,double>::taskid = 0; class FieldHelperBase { protected: // this is shared by all FieldHelper<T>'s static FieldID next_static_id; }; /*static*/ FieldID FieldHelperBase::next_static_id = 10000; template <typename T> class FieldHelper : protected FieldHelperBase { public: static const FieldID ASSIGN_STATIC_ID = AUTO_GENERATE_ID - 1; FieldHelper(const char *_name, FieldID _fid = ASSIGN_STATIC_ID) : name(_name), fid(_fid) { if(fid == ASSIGN_STATIC_ID) fid = next_static_id++; } ~FieldHelper(void) {} operator FieldID(void) const { assert(fid != AUTO_GENERATE_ID); return fid; } void allocate(Runtime *runtime, Context ctx, FieldSpace fs) { FieldAllocator fa = runtime->create_field_allocator(ctx, fs); fid = fa.allocate_field(sizeof(T), fid); runtime->attach_name(fs, fid, name); } template <PrivilegeMode PRIV> FieldAccessor<PRIV,T,3,coord_t,Realm::AffineAccessor<T,3,coord_t> > accessor(const PhysicalRegion& pr) { assert(fid != AUTO_GENERATE_ID); return FieldAccessor<PRIV,T,3,coord_t,Realm::AffineAccessor<T,3,coord_t> >(pr, fid); } template<typename REDOP, bool EXCLUSIVE> ReductionAccessor<REDOP,EXCLUSIVE,3,coord_t,Realm::AffineAccessor<T,3,coord_t> > fold_accessor(const PhysicalRegion& pr, int redop) { assert(fid != AUTO_GENERATE_ID); return ReductionAccessor<REDOP,EXCLUSIVE,3,coord_t,Realm::AffineAccessor<T,3,coord_t> >(pr, fid, redop); } protected: const char *name; FieldID fid; }; FieldHelper<int> fid_owner_shard("owner_shard"); FieldHelper<int> fid_neighbor_count("neighbor_count"); FieldHelper<PhaseBarrier> fid_ready_barrier("ready_barrier"); FieldHelper<PhaseBarrier> fid_done_barrier("done_barrier"); FieldHelper<double> fid_sol_b("sol_b"); FieldHelper<double> fid_sol_x("sol_x"); FieldHelper<double> fid_sol_p("sol_p"); FieldHelper<double> fid_sol_r("sol_r"); FieldHelper<double> fid_sol_Ap("sol_Ap"); struct SpmdInitArgs { Point<3> grid_dim, block_dim, blocks; int shard; }; struct SpmdMainArgs { Point<3> grid_dim, block_dim, blocks; DynamicCollective dc_reduction; int max_iters; int future_lag; int show_residuals; int use_tracing; bool verbose; }; void top_level_task(const Task *task, const std::vector<PhysicalRegion> &regions, Context ctx, Runtime *runtime) { Point<3> grid_dim, block_dim; int max_iters = 0; int future_lag = 0; int show_residuals = 1; int use_tracing = 1; bool verbose = false; // default is an 8^3 grid with 8 4^3 blocks grid_dim[0] = grid_dim[1] = grid_dim[2] = 8; block_dim[0] = block_dim[1] = block_dim[2] = 4; { const InputArgs &command_args = Runtime::get_input_args(); for(int i = 1; i < command_args.argc; i++) { if(!strcmp(command_args.argv[i], "-g")) { int g = atoi(command_args.argv[++i]); grid_dim[0] = grid_dim[1] = grid_dim[2] = g; continue; } if(!strcmp(command_args.argv[i], "-gx")) { int g = atoi(command_args.argv[++i]); grid_dim[0] = g; continue; } if(!strcmp(command_args.argv[i], "-gy")) { int g = atoi(command_args.argv[++i]); grid_dim[1] = g; continue; } if(!strcmp(command_args.argv[i], "-gz")) { int g = atoi(command_args.argv[++i]); grid_dim[2] = g; continue; } if(!strcmp(command_args.argv[i], "-b")) { int b = atoi(command_args.argv[++i]); block_dim[0] = block_dim[1] = block_dim[2] = b; continue; } if(!strcmp(command_args.argv[i], "-bx")) { int b = atoi(command_args.argv[++i]); block_dim[0] = b; continue; } if(!strcmp(command_args.argv[i], "-by")) { int b = atoi(command_args.argv[++i]); block_dim[1] = b; continue; } if(!strcmp(command_args.argv[i], "-bz")) { int b = atoi(command_args.argv[++i]); block_dim[2] = b; continue; } if(!strcmp(command_args.argv[i], "-m")) { max_iters = atoi(command_args.argv[++i]); continue; } if(!strcmp(command_args.argv[i], "-f")) { future_lag = atoi(command_args.argv[++i]); continue; } if(!strcmp(command_args.argv[i], "-r")) { show_residuals = atoi(command_args.argv[++i]); continue; } if(!strcmp(command_args.argv[i], "-t")) { use_tracing = atoi(command_args.argv[++i]); continue; } if(!strcmp(command_args.argv[i], "-v")) { verbose = true; continue; } } } // if the user hasn't set a max, a reasonable upper bound is based on the // manhattan distance across the grid if(max_iters == 0) max_iters = 2 * (grid_dim[0] + grid_dim[1] + grid_dim[2]); // compute the number of blocks in each direction Point<3> blocks; for(int i = 0; i < 3; i++) { int g = grid_dim[i]; int b = block_dim[i]; LOG_ASSERT((b != 0), log_app, "block size cannot be zero (dim=%d)", i); LOG_ASSERT(((g % b) == 0), log_app, "block size must evenly divide grid size (dim=%d, grid=%d, block=%d)", i, g, b); blocks[i] = g / b; } log_app.print() << "grid pts = " << volume(grid_dim) << ", block pts = " << volume(block_dim) << ", block count = " << volume(blocks); // define the main grid index space and its partition into blocks IndexSpaceT<3> is_grid = runtime->create_index_space(ctx, Rect<3>(Point<3>(0,0,0), grid_dim - Point<3>(1,1,1))); IndexPartition ip_grid = runtime->create_partition_by_blockify(ctx, is_grid, block_dim, 0/*color*/); // we also use an index space with an element per block to record things like which shard owns each block IndexSpace is_blks = runtime->create_index_space(ctx, Rect<3>(Point<3>(0,0,0), blocks - Point<3>(1,1,1))); FieldSpace fs_blks = runtime->create_field_space(ctx); fid_owner_shard.allocate(runtime, ctx, fs_blks); fid_neighbor_count.allocate(runtime, ctx, fs_blks); fid_ready_barrier.allocate(runtime, ctx, fs_blks); fid_done_barrier.allocate(runtime, ctx, fs_blks); LogicalRegion lr_blks = runtime->create_logical_region(ctx, is_blks, fs_blks); // assign blocks to shards // step 1: ask the mapper how many shards we should even have int num_shards = runtime->select_tunable_value(ctx, CGMapper::TID_NUM_SHARDS).get_result<int>(); // force for now log_app.print() << "shards = " << num_shards; // step 2: fill in the owner IDs and neighbor counts { InlineLauncher launcher(RegionRequirement(lr_blks, WRITE_DISCARD, EXCLUSIVE, lr_blks) .add_field(fid_owner_shard) .add_field(fid_neighbor_count)); PhysicalRegion pr_blks = runtime->map_region(ctx, launcher); pr_blks.wait_until_valid(); const AccessorWDint fa_owner = fid_owner_shard.accessor<WRITE_DISCARD>(pr_blks); const AccessorWDint fa_neighbors = fid_neighbor_count.accessor<WRITE_DISCARD>(pr_blks); int num_blks = volume(blocks); { int i = 0; for(PointInRectIterator<3> pir(Rect<3>( Point<3>(0,0,0), blocks - Point<3>(1,1,1))); pir(); ++pir) fa_owner[*pir] = (i++ * num_shards) / num_blks; } for(PointInRectIterator<3> pir(Rect<3>( Point<3>(0,0,0), blocks - Point<3>(1,1,1))); pir(); ++pir) { int owner = fa_owner[*pir]; int neighbors = 0; if((pir[0] > 0) && (owner != fa_owner[LEFT(*pir)])) neighbors++; if((pir[0] < blocks[0] - 1) && (owner != fa_owner[RIGHT(*pir)])) neighbors++; if((pir[1] > 0) && (owner != fa_owner[UP(*pir)])) neighbors++; if((pir[1] < blocks[1] - 1) && (owner != fa_owner[DOWN(*pir)])) neighbors++; if((pir[2] > 0) && (owner != fa_owner[FRONT(*pir)])) neighbors++; if((pir[2] < blocks[2] - 1) && (owner != fa_owner[BACK(*pir)])) neighbors++; fa_neighbors[*pir] = neighbors; } runtime->unmap_region(ctx, pr_blks); } // create a logical region that holds the residual "vector" - this will be shared between all shards FieldSpace fs_sol = runtime->create_field_space(ctx); fid_sol_p.allocate(runtime, ctx, fs_sol); LogicalRegion lr_sol = runtime->create_logical_region(ctx, is_grid, fs_sol); LogicalPartition lp_sol = runtime->get_logical_partition(ctx, lr_sol, ip_grid); // remap the blocks region as read-only to be compatible with subtask launches InlineLauncher launcher(RegionRequirement(lr_blks, READ_ONLY, EXCLUSIVE, lr_blks) .add_field(fid_owner_shard)); PhysicalRegion pr_blks = runtime->map_region(ctx, launcher); pr_blks.wait_until_valid(); const AccessorROint fa_owner = fid_owner_shard.accessor<READ_ONLY>(pr_blks); runtime->fill_field(ctx, lr_blks, lr_blks, fid_ready_barrier, PhaseBarrier()); runtime->fill_field(ctx, lr_blks, lr_blks, fid_done_barrier, PhaseBarrier()); { log_app.info() << "launching init tasks"; // launch init tasks on each shard that create the needed instances std::vector<Future> futures; for(int shard = 0; shard < num_shards; shard++) { SpmdInitArgs args; args.grid_dim = grid_dim; args.block_dim = block_dim; args.blocks = blocks; args.shard = shard; TaskLauncher launcher(SPMD_INIT_TASK_ID, TaskArgument(&args, sizeof(args)), Predicate::TRUE_PRED, 0 /*default mapper*/, CGMapper::SHARD_TAG(shard)); launcher.add_region_requirement(RegionRequirement(lr_blks, READ_ONLY, EXCLUSIVE, lr_blks) .add_field(fid_owner_shard) .add_field(fid_neighbor_count)); // we'll use "reductions" to allow each shard to fill in barriers for blocks it owns launcher.add_region_requirement(RegionRequirement(lr_blks, BarrierCombineReductionOp::redop_id, EXCLUSIVE, lr_blks) .add_field(fid_ready_barrier)); launcher.add_region_requirement(RegionRequirement(lr_blks, BarrierCombineReductionOp::redop_id, EXCLUSIVE, lr_blks) .add_field(fid_done_barrier)); for(PointInRectIterator<3> pir(Rect<3>( Point<3>(0,0,0), blocks - Point<3>(1,1,1))); pir(); ++pir) { if(fa_owner[*pir] != shard) continue; LogicalRegion lr_solblk = runtime->get_logical_subregion_by_color(ctx, lp_sol, *pir); launcher.add_region_requirement(RegionRequirement(lr_solblk, WRITE_DISCARD, EXCLUSIVE, lr_sol) .add_field(fid_sol_p)); } Future f = runtime->execute_task(ctx, launcher); futures.push_back(f); } log_app.info() << "waiting for init tasks"; // now wait on all the futures for(std::vector<Future>::iterator it = futures.begin(); it != futures.end(); it++) it->get_void_result(); log_app.info() << "init tasks complete"; } // now the main simulation, launched as a must epoch { SpmdMainArgs args; args.grid_dim = grid_dim; args.block_dim = block_dim; args.blocks = blocks; args.max_iters = max_iters; args.future_lag = future_lag; args.show_residuals = show_residuals; args.use_tracing = use_tracing; args.verbose = verbose; { double zero = 0.0; args.dc_reduction = runtime->create_dynamic_collective(ctx, volume(blocks), DoubleAddReductionOp::redop_id, &zero, sizeof(zero)); } Rect<3> blk_space(Point<3>(0,0,0), blocks - Point<3>(1,1,1)); MustEpochLauncher must; #define USE_SINGLE_TASK_LAUNCHES_IN_MUST_EPOCH #ifdef USE_SINGLE_TASK_LAUNCHES_IN_MUST_EPOCH for(int shard = 0; shard < num_shards; shard++) #endif { #ifdef USE_SINGLE_TASK_LAUNCHES_IN_MUST_EPOCH TaskLauncher launcher(SPMD_MAIN_TASK_ID, TaskArgument(&args, sizeof(args)), Predicate::TRUE_PRED, 0 /*default mapper*/, CGMapper::SHARD_TAG(shard)); #else IndexLauncher launcher(SPMD_MAIN_TASK_ID, Domain::from_rect<1>(Rect<1>(0, num_shards - 1)), TaskArgument(&args, sizeof(args)), ArgumentMap()); #endif launcher.add_region_requirement(RegionRequirement(lr_blks, READ_ONLY, EXCLUSIVE, lr_blks) .add_field(fid_owner_shard) .add_field(fid_neighbor_count) .add_field(fid_ready_barrier) .add_field(fid_done_barrier)); for(PointInRectIterator<3> pir(blk_space); pir(); ++pir) { LogicalRegion lr_solblk = runtime->get_logical_subregion_by_color(ctx, lp_sol, *pir); launcher.add_region_requirement(RegionRequirement(lr_solblk, READ_WRITE, SIMULTANEOUS, lr_sol, CGMapper::SHARD_TAG(fa_owner[*pir])) .add_field(fid_sol_p) .add_flags(NO_ACCESS_FLAG)); } #ifdef USE_SINGLE_TASK_LAUNCHES_IN_MUST_EPOCH must.add_single_task(DomainPoint::from_point<1>(shard), launcher); #else must.add_index_task(launcher); #endif } log_app.info() << "launching spmd tasks"; FutureMap fm = runtime->execute_must_epoch(ctx, must); log_app.info() << "waiting for spmd tasks"; // make sure all shard returned successful results bool ok = true; for(int shard = 0; shard < num_shards; shard++) { bool shard_ok = fm.get_result<bool>(DomainPoint::from_point<1>(shard)); if(!shard_ok) { log_app.print() << "error returned from shard " << shard; ok = false; } } if(ok) { log_app.print() << "spmd tasks complete"; } else { log_app.fatal() << "one or more spmd tasks failed"; exit(1); } } } void spmd_init_task(const Task *task, const std::vector<PhysicalRegion> &regions, Context ctx, Runtime *runtime) { const SpmdInitArgs& args = *(const SpmdInitArgs *)(task->args); log_app.print() << "in spmd_init_task, shard=" << args.shard << ", proc=" << runtime->get_executing_processor(ctx) << ", regions=" << regions.size(); const AccessorROint fa_owner = fid_owner_shard.accessor<READ_ONLY>(regions[0]); const AccessorROint fa_neighbors = fid_neighbor_count.accessor<READ_ONLY>(regions[0]); const AccessorRDpb fa_ready = fid_ready_barrier.fold_accessor<BarrierCombineReductionOp, true/*exclusive*/>(regions[1], BarrierCombineReductionOp::redop_id); const AccessorRDpb fa_done = fid_done_barrier.fold_accessor<BarrierCombineReductionOp, true/*exclusive*/>(regions[2], BarrierCombineReductionOp::redop_id); for(PointInRectIterator<3> pir(Rect<3>( Point<3>(0,0,0), args.blocks - Point<3>(1,1,1))); pir(); ++pir) { int owner = fa_owner[*pir]; if(owner != args.shard) continue; int neighbors = fa_neighbors[*pir]; if(neighbors > 0) { PhaseBarrier pb_ready = runtime->create_phase_barrier(ctx, 1); PhaseBarrier pb_done = runtime->create_phase_barrier(ctx, neighbors); log_app.info() << "pbs: shard=" << args.shard << " blk=" << *pir << " neighbors=" << neighbors << " ready=" << pb_ready << " done=" << pb_done; fa_ready[*pir] <<= pb_ready; fa_done[*pir] <<= pb_done; } } } std::ostream& operator<<(std::ostream& os, const BlockMetadata& bm) { os << "bounds=" << bm.bounds; os << " ispace=" << bm.ispace; os << " pvt=" << bm.lr_private << " shr=" << bm.lr_shared << "\n"; os << " " << bm.neighbors << " neighbors: ready=" << bm.pb_shared_ready << " done=" << bm.pb_shared_done; for(int dir = DIR_X; dir <= DIR_Z; dir++) for(int side = SIDE_MINUS; side <= SIDE_PLUS; side++) { const GhostInfo& g = bm.ghosts[dir][side]; os << "\n " << (char)('X' + dir) << ("-+"[side]) << ": gtype=" << g.gtype; os << " ready=" << g.pb_shared_ready << " done=" << g.pb_shared_done; } return os; } struct InitFieldArgs { Point<3> grid_dim; Rect<3> bounds; }; struct SpmvFieldArgs { Rect<3> bounds; GhostInfo::GhostType gtypes[3][2]; }; struct AddFieldArgs { Rect<3> bounds; }; bool spmd_main_task(const Task *task, const std::vector<PhysicalRegion> &regions, Context ctx, Runtime *runtime) { const SpmdMainArgs& args = *(const SpmdMainArgs *)(task->args); int shard = task->index_point.get_point<1>(); log_app.print() << "in spmd_main_task, shard=" << shard << ", proc=" << runtime->get_executing_processor(ctx) << ", regions=" << regions.size(); // iterate over the distribution info, capturing the info for the subblocks we own std::map<Point<3>, BlockMetadata> myblocks; FieldSpace fs_private = runtime->create_field_space(ctx); fid_sol_b.allocate(runtime, ctx, fs_private); fid_sol_x.allocate(runtime, ctx, fs_private); fid_sol_r.allocate(runtime, ctx, fs_private); fid_sol_Ap.allocate(runtime, ctx, fs_private); const AccessorROint fa_owner = fid_owner_shard.accessor<READ_ONLY>(regions[0]); const AccessorROint fa_neighbors = fid_neighbor_count.accessor<READ_ONLY>(regions[0]); const AccessorROpb fa_ready = fid_ready_barrier.accessor<READ_ONLY>(regions[0]); const AccessorROpb fa_done = fid_done_barrier.accessor<READ_ONLY>(regions[0]); Rect<3> blk_space(Point<3>(0,0,0), args.blocks - Point<3>(1,1,1)); int pr_idx = 1; const Point<3> blk_strides(1, (blk_space.hi[0] - blk_space.lo[0]) + 1, ((blk_space.hi[0] - blk_space.lo[0]) + 1) * ((blk_space.hi[1] - blk_space.lo[1]) + 1)); for(PointInRectIterator<3> pir(blk_space); pir(); ++pir, ++pr_idx) { int owner = fa_owner[*pir]; if(owner != shard) continue; assert((int)((blk_strides.dot(*pir))+1) == pr_idx); BlockMetadata& mdata = myblocks[*pir]; mdata.lr_shared = regions[pr_idx].get_logical_region(); mdata.ispace = mdata.lr_shared.get_index_space(); mdata.bounds = runtime->get_index_space_domain(ctx, mdata.ispace); mdata.lr_private = runtime->create_logical_region(ctx, mdata.ispace, fs_private); mdata.neighbors = fa_neighbors[*pir]; if(mdata.neighbors > 0) { mdata.pb_shared_ready = fa_ready[*pir]; mdata.pb_shared_done = fa_done[*pir]; } else { mdata.pb_shared_ready = PhaseBarrier(); mdata.pb_shared_done = PhaseBarrier(); } IndexSpaceT<1> color_space = runtime->create_index_space(ctx, Rect<1>(0, 0)); for(int dir = DIR_X; dir <= DIR_Z; dir++) { for(int side = SIDE_MINUS; side <= SIDE_PLUS; side++) { GhostInfo& g = mdata.ghosts[dir][side]; if(pir[dir] == ((side == SIDE_MINUS) ? 0 : args.blocks[dir] - 1)) { // boundary g.gtype = GhostInfo::GHOST_BOUNDARY; } else { Point<3> p2(*pir); if(side == SIDE_MINUS) p2[dir]--; else p2[dir]++; if(fa_owner[p2] == owner) { g.gtype = GhostInfo::GHOST_LOCAL; g.lr_parent = regions[blk_strides.dot(p2)+1].get_logical_region(); } else { g.gtype = GhostInfo::GHOST_REMOTE; g.lr_parent = regions[blk_strides.dot(p2)+1].get_logical_region(); g.pb_shared_ready = fa_ready[p2]; g.pb_shared_done = fa_done[p2]; } IndexSpaceT<3> is_parent(g.lr_parent.get_index_space()); Rect<3> r_parent = runtime->get_index_space_domain(ctx, is_parent); Rect<3> r_subset(r_parent); if(side == SIDE_MINUS) r_subset.lo[dir] = r_subset.hi[dir]; // just 1 plane else r_subset.hi[dir] = r_subset.lo[dir]; // just 1 plane //std::cout << "dir=" << dir << " side=" << side << " -> " << r_parent << " -> " << r_subset << "\n"; Transform<3,1> transform; transform[0][0] = 0; transform[1][0] = 0; transform[2][0] = 0; IndexPartition ip = runtime->create_partition_by_restriction(ctx, is_parent, color_space, transform, r_subset, COMPUTE_KIND, dir*2+side); IndexSpace is_subset = runtime->get_index_subspace(ctx, ip, 0); assert(runtime->get_index_space_domain(ctx, is_subset) == r_subset); g.ispace = is_subset; g.lr_shared = runtime->get_logical_subregion_by_tree(ctx, is_subset, g.lr_parent.get_field_space(), g.lr_parent.get_tree_id()); if(fa_owner[p2] == owner) { g.lr_ghost = g.lr_shared; } else { g.lr_ghost = runtime->create_logical_region(ctx, is_subset, g.lr_parent.get_field_space()); } } } } } // now that we're done with that, unmap all of our regions so that they // don't interfere with child task launches runtime->unmap_all_regions(ctx); log_app.info() << "my block count = " << myblocks.size(); for(std::map<Point<3>, BlockMetadata>::const_iterator it = myblocks.begin(); it != myblocks.end(); it++) log_app.info() << " " << it->first << ": " << it->second; // this shouldn't be necessary, but it seems to avoid some sort of memory corruption when // a shard has no work if(myblocks.empty()) return true; // initialize x, b for(std::map<Point<3>, BlockMetadata>::iterator it = myblocks.begin(); it != myblocks.end(); it++) { BlockMetadata& bm = it->second; { InitFieldArgs cargs; cargs.grid_dim = args.grid_dim; cargs.bounds = bm.bounds; TaskLauncher launcher(INIT_FIELD_TASK_ID, TaskArgument(&cargs, sizeof(cargs)), Predicate::TRUE_PRED, 0 /*default mapper*/, CGMapper::TAG_LOCAL_SHARD); launcher.add_region_requirement(RegionRequirement(bm.lr_private, WRITE_DISCARD, EXCLUSIVE, bm.lr_private) .add_field(fid_sol_b)); runtime->execute_task(ctx, launcher); } // initial solution is zero runtime->fill_field<double>(ctx, bm.lr_private, bm.lr_private, fid_sol_x, 0.0); // initial residual is equal to b { CopyLauncher copy; copy.add_copy_requirements(RegionRequirement(bm.lr_private, READ_ONLY, EXCLUSIVE, bm.lr_private) .add_field(fid_sol_b), RegionRequirement(bm.lr_private, WRITE_DISCARD, EXCLUSIVE, bm.lr_private) .add_field(fid_sol_r)); runtime->issue_copy_operation(ctx, copy); } // initial direction vector p is also equal to b { CopyLauncher copy; copy.add_copy_requirements(RegionRequirement(bm.lr_private, READ_ONLY, EXCLUSIVE, bm.lr_private) .add_field(fid_sol_b), RegionRequirement(bm.lr_shared, WRITE_DISCARD, EXCLUSIVE, bm.lr_shared) .add_field(fid_sol_p)); if(bm.neighbors > 0) { copy.add_arrival_barrier(bm.pb_shared_ready); bm.pb_shared_ready = runtime->advance_phase_barrier(ctx, bm.pb_shared_ready); } runtime->issue_copy_operation(ctx, copy); } } DynamicCollective dc_reduction = args.dc_reduction; // compute initial residual magnitude Future f_resold = DotProduct::compute(myblocks, dc_reduction, runtime, ctx, fid_sol_b, true /*private*/, fid_sol_b, true /*private*/); std::queue<Future> f_residuals; int res_iter = 0; // this lags the normal iteration count if(args.show_residuals > 0) { double resold = f_resold.get_result<double>(); if(shard == 0) log_app.info() << "resold = " << resold; } Future f_restarget = Future::from_value<double>(runtime, 1e-10); Predicate p_notdone = Predicate::TRUE_PRED; int iter = 0; bool ok = false; while(true) { iter++; if(args.use_tracing) runtime->begin_trace(ctx, TRACE_ID_CG_ITER); // compute Ap = A * p for(std::map<Point<3>, BlockMetadata>::iterator it = myblocks.begin(); it != myblocks.end(); it++) { BlockMetadata& bm = it->second; SpmvFieldArgs cargs; cargs.bounds = bm.bounds; for(int dir = DIR_X; dir <= DIR_Z; dir++) for(int side = SIDE_MINUS; side <= SIDE_PLUS; side++) cargs.gtypes[dir][side] = bm.ghosts[dir][side].gtype; TaskLauncher launcher(SPMV_FIELD_TASK_ID, TaskArgument(&cargs, sizeof(cargs)), p_notdone, 0 /*default mapper*/, CGMapper::TAG_LOCAL_SHARD); launcher.add_region_requirement(RegionRequirement(bm.lr_private, WRITE_DISCARD, EXCLUSIVE, bm.lr_private) .add_field(fid_sol_Ap)); launcher.add_region_requirement(RegionRequirement(bm.lr_shared, READ_ONLY, EXCLUSIVE, bm.lr_shared) .add_field(fid_sol_p)); for(int dir = DIR_X; dir <= DIR_Z; dir++) for(int side = SIDE_MINUS; side <= SIDE_PLUS; side++) { GhostInfo& g = bm.ghosts[dir][side]; switch(g.gtype) { case GhostInfo::GHOST_BOUNDARY: { // can't do empty region requirements right now #if 0 launcher.add_region_requirement(RegionRequirement(LogicalRegion::NO_REGION, NO_ACCESS, EXCLUSIVE, LogicalRegion::NO_REGION)); #endif break; } case GhostInfo::GHOST_LOCAL: { launcher.add_region_requirement(RegionRequirement(g.lr_shared, READ_ONLY, EXCLUSIVE, g.lr_parent) .add_field(fid_sol_p)); break; } case GhostInfo::GHOST_REMOTE: { CopyLauncher copy(p_notdone); copy.add_copy_requirements(RegionRequirement(g.lr_shared, READ_ONLY, EXCLUSIVE, g.lr_parent) .add_field(fid_sol_p), RegionRequirement(g.lr_ghost, WRITE_DISCARD, EXCLUSIVE, g.lr_ghost) .add_field(fid_sol_p)); g.pb_shared_ready = runtime->advance_phase_barrier(ctx, g.pb_shared_ready); copy.add_wait_barrier(g.pb_shared_ready); copy.add_arrival_barrier(g.pb_shared_done); g.pb_shared_done = runtime->advance_phase_barrier(ctx, g.pb_shared_done); runtime->issue_copy_operation(ctx, copy); launcher.add_region_requirement(RegionRequirement(g.lr_ghost, READ_ONLY, EXCLUSIVE, g.lr_ghost) .add_field(fid_sol_p)); break; } default: assert(0); } } runtime->execute_task(ctx, launcher); } // alpha = p' * Ap Future ff2 = DotProduct::compute(myblocks, dc_reduction, runtime, ctx, fid_sol_p, false /*!private*/, fid_sol_Ap, true /*private*/, p_notdone); Future f_alpha = FDV_double::compute(runtime, ctx, f_resold, ff2); //double alpha = resold / ff2.get_result<double>(); double alpha = f_alpha.get_result<double>(); //std::cout << "alpha = " << alpha << "\n"; // x += alpha * p VectorAcc::compute(myblocks, runtime, ctx, alpha, fid_sol_p, false /*!private*/, 1.0, fid_sol_x, true /*private*/, p_notdone); // r -= alpha * Ap VectorAcc::compute(myblocks, runtime, ctx, -alpha, fid_sol_Ap, true /*private*/, 1.0, fid_sol_r, true /*private*/, p_notdone); //PrintField::compute(myblocks, runtime, ctx, "r", fid_sol_r, true /*private*/); Future f_resnew = DotProduct::compute(myblocks, dc_reduction, runtime, ctx, fid_sol_r, true /*private*/, fid_sol_r, true /*private*/, p_notdone); f_residuals.push(f_resnew); if(f_residuals.size() > (size_t)args.future_lag) { Future f = f_residuals.front(); f_residuals.pop(); double resnew = f.get_result<double>(); ++res_iter; if((shard == 0) && (args.show_residuals > 0) && ((res_iter % args.show_residuals) == 0)) log_app.info() << "iter " << res_iter << ": resnew = " << resnew; if(resnew < 1e-10) { if(shard == 0) log_app.info() << "converged after " << res_iter << " iterations"; ok = true; break; } if(res_iter >= args.max_iters) { if(shard == 0) log_app.warning() << "failed to converge after " << res_iter << " iterations"; break; } } // never speculate past max_iters if(iter >= args.max_iters) { if(shard == 0) log_app.info() << "not speculating past " << iter << " iterations"; break; } if(args.future_lag > 0) { Future f_notdone = FLT_double::compute(runtime, ctx, f_restarget, f_resnew); p_notdone = runtime->predicate_and(ctx, p_notdone, runtime->create_predicate(ctx, f_notdone)); } // p = r + (resnew/resold)*p Future f_beta = FDV_double::compute(runtime, ctx, f_resnew, f_resold); double beta = f_beta.get_result<double>(); VectorAcc::compute(myblocks, runtime, ctx, 1.0, fid_sol_r, true /*private*/, beta, fid_sol_p, false /*!private*/, p_notdone); f_resold = f_resnew; if(args.use_tracing) runtime->end_trace(ctx, TRACE_ID_CG_ITER); } // last iteration of the loop above always breaks out early, so make sure we end the trace if(args.use_tracing) runtime->end_trace(ctx, TRACE_ID_CG_ITER); if(0) PrintField::compute(myblocks, runtime, ctx, "x", fid_sol_x, true /*private*/, 0);//1e-5); // check result // copy p = x for(std::map<Point<3>, BlockMetadata>::iterator it = myblocks.begin(); it != myblocks.end(); it++) { BlockMetadata& bm = it->second; CopyLauncher copy; copy.add_copy_requirements(RegionRequirement(bm.lr_private, READ_ONLY, EXCLUSIVE, bm.lr_private) .add_field(fid_sol_x), RegionRequirement(bm.lr_shared, WRITE_DISCARD, EXCLUSIVE, bm.lr_shared) .add_field(fid_sol_p)); if(bm.neighbors > 0) { bm.pb_shared_done = runtime->advance_phase_barrier(ctx, bm.pb_shared_done); copy.add_wait_barrier(bm.pb_shared_done); copy.add_arrival_barrier(bm.pb_shared_ready); bm.pb_shared_ready = runtime->advance_phase_barrier(ctx, bm.pb_shared_ready); } runtime->issue_copy_operation(ctx, copy); } // compute Ap = A * x for(std::map<Point<3>, BlockMetadata>::iterator it = myblocks.begin(); it != myblocks.end(); it++) { BlockMetadata& bm = it->second; SpmvFieldArgs cargs; cargs.bounds = bm.bounds; for(int dir = DIR_X; dir <= DIR_Z; dir++) for(int side = SIDE_MINUS; side <= SIDE_PLUS; side++) cargs.gtypes[dir][side] = bm.ghosts[dir][side].gtype; TaskLauncher launcher(SPMV_FIELD_TASK_ID, TaskArgument(&cargs, sizeof(cargs)), Predicate::TRUE_PRED, 0 /*default mapper*/, CGMapper::TAG_LOCAL_SHARD); launcher.add_region_requirement(RegionRequirement(bm.lr_private, READ_WRITE, EXCLUSIVE, bm.lr_private) .add_field(fid_sol_Ap)); launcher.add_region_requirement(RegionRequirement(bm.lr_shared, READ_ONLY, EXCLUSIVE, bm.lr_shared) .add_field(fid_sol_p)); for(int dir = DIR_X; dir <= DIR_Z; dir++) for(int side = SIDE_MINUS; side <= SIDE_PLUS; side++) { GhostInfo& g = bm.ghosts[dir][side]; switch(g.gtype) { case GhostInfo::GHOST_BOUNDARY: { // can't do empty region requirements right now #if 0 launcher.add_region_requirement(RegionRequirement(LogicalRegion::NO_REGION, NO_ACCESS, EXCLUSIVE, LogicalRegion::NO_REGION)); #endif break; } case GhostInfo::GHOST_LOCAL: { launcher.add_region_requirement(RegionRequirement(g.lr_shared, READ_ONLY, EXCLUSIVE, g.lr_parent) .add_field(fid_sol_p)); break; } case GhostInfo::GHOST_REMOTE: { CopyLauncher copy; copy.add_copy_requirements(RegionRequirement(g.lr_shared, READ_ONLY, EXCLUSIVE, g.lr_parent) .add_field(fid_sol_p), RegionRequirement(g.lr_ghost, WRITE_DISCARD, EXCLUSIVE, g.lr_ghost) .add_field(fid_sol_p)); g.pb_shared_ready = runtime->advance_phase_barrier(ctx, g.pb_shared_ready); copy.add_wait_barrier(g.pb_shared_ready); copy.add_arrival_barrier(g.pb_shared_done); g.pb_shared_done = runtime->advance_phase_barrier(ctx, g.pb_shared_done); runtime->issue_copy_operation(ctx, copy); launcher.add_region_requirement(RegionRequirement(g.lr_ghost, READ_ONLY, EXCLUSIVE, g.lr_ghost) .add_field(fid_sol_p)); break; } default: assert(0); } } runtime->execute_task(ctx, launcher); } // Ap -= b VectorAcc::compute(myblocks, runtime, ctx, -1.0, fid_sol_b, true /*private*/, 1.0, fid_sol_Ap, true /*private*/); if(args.verbose) PrintField::compute(myblocks, runtime, ctx, "check", fid_sol_Ap, true /*private*/, 1e-5); return ok; } void init_field_task(const Task *task, const std::vector<PhysicalRegion> &regions, Context ctx, Runtime *runtime) { const InitFieldArgs& args = *(const InitFieldArgs *)(task->args); log_app.debug() << "init_field task - bounds=" << args.bounds << ", fid=" << task->regions[0].instance_fields[0] << ", proc=" << runtime->get_executing_processor(ctx); const AccessorWDdouble fa(regions[0], task->regions[0].instance_fields[0]); for(PointInRectIterator<3> pir(args.bounds); pir(); ++pir) { #if 0 double v = 0.0; if((pir.p.x[0] == (args.grid_dim.x[0] / 2)) && (pir.p.x[1] == (args.grid_dim.x[1] / 2)) && (pir.p.x[2] == (args.grid_dim.x[2] / 2))) v = 1.0; #else srand48(pir[0] * 100000 + pir[1] * 1000 + pir[2]); double v = drand48(); #endif //double v = pir.p.x[0] * 10000 + pir.p.x[1] * 100 + pir.p.x[2]; //printf("%p <- %g\n", &fa[pir.p], v); fa[*pir] = v; } } void spmv_field_task(const Task *task, const std::vector<PhysicalRegion> &regions, Context ctx, Runtime *runtime) { const SpmvFieldArgs& args = *(const SpmvFieldArgs *)(task->args); log_app.debug() << "init_field task - bounds=" << args.bounds << ", fid=" << task->regions[0].instance_fields[0] << ", proc=" << runtime->get_executing_processor(ctx); const AccessorRWdouble fa_out(regions[0], task->regions[0].instance_fields[0]); const AccessorROdouble fa_in(regions[1], task->regions[1].instance_fields[0]); size_t pr_idx = 2; AccessorROdouble fa_ghost[3][2]; for(int dir = DIR_X; dir <= DIR_Z; dir++) for(int side = SIDE_MINUS; side <= SIDE_PLUS; side++) if(args.gtypes[dir][side] != GhostInfo::GHOST_BOUNDARY) { fa_ghost[dir][side] = AccessorROdouble(regions[pr_idx], task->regions[pr_idx].instance_fields[0]); pr_idx++; } assert(pr_idx == regions.size()); for(PointInRectIterator<3> pir(args.bounds); pir(); ++pir) { double v_neighbors[3][2]; for(int dir = DIR_X; dir <= DIR_Z; dir++) for(int side = SIDE_MINUS; side <= SIDE_PLUS; side++) { Point<3> p2(*pir); bool interior; if(side == SIDE_MINUS) { p2[dir]--; interior = (p2[dir] >= args.bounds.lo[dir]); } else { p2[dir]++; interior = (p2[dir] <= args.bounds.hi[dir]); } if(interior) { v_neighbors[dir][side] = fa_in[p2]; } else { if(args.gtypes[dir][side] == GhostInfo::GHOST_BOUNDARY) v_neighbors[dir][side] = 0.0; else v_neighbors[dir][side] = fa_ghost[dir][side][p2]; } } double v_in = fa_in[*pir]; double dx = 1.0; double dy = 1.0; double dz = 1.0; double v_out = (((-v_neighbors[DIR_X][SIDE_MINUS] + 2 * v_in - v_neighbors[DIR_X][SIDE_PLUS]) / (dx * dx)) + ((-v_neighbors[DIR_Y][SIDE_MINUS] + 2 * v_in - v_neighbors[DIR_Y][SIDE_PLUS]) / (dy * dy)) + ((-v_neighbors[DIR_Z][SIDE_MINUS] + 2 * v_in - v_neighbors[DIR_Z][SIDE_PLUS]) / (dz * dz))); #if 0 std::cout << pir.p << " " << v_out << " <- " << v_in << " x:(" << v_neighbors[DIR_X][SIDE_MINUS] << "," << v_neighbors[DIR_X][SIDE_PLUS] << ")" << " y:(" << v_neighbors[DIR_Y][SIDE_MINUS] << "," << v_neighbors[DIR_Y][SIDE_PLUS] << ")" << " z:(" << v_neighbors[DIR_Z][SIDE_MINUS] << "," << v_neighbors[DIR_Z][SIDE_PLUS] << ")\n"; #endif fa_out[*pir] = v_out; } } static void update_mappers(Machine machine, Runtime *runtime, const std::set<Processor> &local_procs) { for(std::set<Processor>::const_iterator it = local_procs.begin(); it != local_procs.end(); it++) runtime->replace_default_mapper(new CGMapper(machine, runtime, *it), *it); } int main(int argc, char **argv) { { TaskVariantRegistrar tvr(TOP_LEVEL_TASK_ID, "top_level_task"); tvr.add_constraint(ProcessorConstraint(Processor::LOC_PROC)); Runtime::preregister_task_variant<top_level_task>(tvr, "top_level_task"); Runtime::set_top_level_task_id(TOP_LEVEL_TASK_ID); } { TaskVariantRegistrar tvr(SPMD_INIT_TASK_ID, "spmd_init_task"); tvr.add_constraint(ProcessorConstraint(Processor::LOC_PROC)); tvr.set_leaf(true); Runtime::preregister_task_variant<spmd_init_task>(tvr, "spmd_init_task"); } { TaskVariantRegistrar tvr(SPMD_MAIN_TASK_ID, "spmd_main_task"); tvr.add_constraint(ProcessorConstraint(Processor::LOC_PROC)); Runtime::preregister_task_variant<bool, spmd_main_task>(tvr, "spmd_main_task"); } { TaskVariantRegistrar tvr(INIT_FIELD_TASK_ID, "init_field_task"); tvr.add_constraint(ProcessorConstraint(Processor::LOC_PROC)); tvr.set_leaf(true); Runtime::preregister_task_variant<init_field_task>(tvr, "init_field_task"); } { TaskVariantRegistrar tvr(SPMV_FIELD_TASK_ID, "spmv_field_task"); tvr.add_constraint(ProcessorConstraint(Processor::LOC_PROC)); tvr.set_leaf(true); Runtime::preregister_task_variant<spmv_field_task>(tvr, "spmv_field_task"); } PrintField::preregister_tasks(); DotProduct::preregister_tasks(); VectorAdd::preregister_tasks(); VectorAcc::preregister_tasks(); FLT_double::preregister_task(); FDV_double::preregister_task(); Runtime::add_registration_callback(update_mappers); Runtime::register_reduction_op<BarrierCombineReductionOp>(BarrierCombineReductionOp::redop_id); Runtime::register_reduction_op<DoubleAddReductionOp>(DoubleAddReductionOp::redop_id); return Runtime::start(argc, argv); }
StanfordLegion/legion
examples/spmd_cgsolver/cgsolver.cc
C++
apache-2.0
44,526
/* * Copyright 2015 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * 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.jbpm.integrationtests; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.io.Reader; import java.io.StringReader; import java.util.ArrayList; import java.util.List; import org.drools.compiler.compiler.DroolsError; import org.drools.compiler.compiler.PackageBuilderErrors; import org.drools.core.definitions.InternalKnowledgePackage; import org.jbpm.process.instance.ProcessInstance; import org.jbpm.test.util.AbstractBaseTest; import org.junit.Test; import org.kie.api.runtime.KieSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ProcessExceptionHandlerTest extends AbstractBaseTest { private static final Logger logger = LoggerFactory.getLogger(ProcessExceptionHandlerTest.class); @Test public void testFaultWithoutHandler() { Reader source = new StringReader( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<process xmlns=\"http://drools.org/drools-5.0/process\"\n" + " xmlns:xs=\"http://www.w3.org/2001/XMLSchema-instance\"\n" + " xs:schemaLocation=\"http://drools.org/drools-5.0/process drools-processes-5.0.xsd\"\n" + " type=\"RuleFlow\" name=\"flow\" id=\"org.drools.exception\" package-name=\"org.drools\" version=\"1\" >\n" + "\n" + " <header>\n" + " </header>\n" + "\n" + " <nodes>\n" + " <start id=\"1\" name=\"Start\" />\n" + " <fault id=\"2\" name=\"Fault\" faultName=\"myFault\" />\n" + " </nodes>\n" + "\n" + " <connections>\n" + " <connection from=\"1\" to=\"2\" />\n" + " </connections>\n" + "\n" + "</process>"); builder.addRuleFlow(source); InternalKnowledgePackage pkg = builder.getPackage(); PackageBuilderErrors errors = builder.getErrors(); if (errors != null && !errors.isEmpty()) { for (DroolsError error: errors.getErrors()) { logger.error(error.toString()); } fail("Package could not be compiled"); } KieSession session = createKieSession(builder.getPackage()); ProcessInstance processInstance = ( ProcessInstance ) session.startProcess("org.drools.exception"); assertEquals(ProcessInstance.STATE_ABORTED, processInstance.getState()); } @Test public void testProcessExceptionHandlerAction() { Reader source = new StringReader( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<process xmlns=\"http://drools.org/drools-5.0/process\"\n" + " xmlns:xs=\"http://www.w3.org/2001/XMLSchema-instance\"\n" + " xs:schemaLocation=\"http://drools.org/drools-5.0/process drools-processes-5.0.xsd\"\n" + " type=\"RuleFlow\" name=\"flow\" id=\"org.drools.exception\" package-name=\"org.drools\" version=\"1\" >\n" + "\n" + " <header>\n" + " <globals>\n" + " <global identifier=\"list\" type=\"java.util.List\" />\n" + " </globals>\n" + " <variables>\n" + " <variable name=\"SomeVar\" >\n" + " <type name=\"org.drools.core.process.core.datatype.impl.type.StringDataType\" />\n" + " <value>SomeValue</value>\n" + " </variable>\n" + " <variable name=\"faultVar\" >\n" + " <type name=\"org.drools.core.process.core.datatype.impl.type.StringDataType\" />\n" + " </variable>\n" + " </variables>\n" + " <exceptionHandlers>\n" + " <exceptionHandler faultName=\"myFault\" type=\"action\" faultVariable=\"faultVar\" >\n" + " <action type=\"expression\" name=\"Print\" dialect=\"java\" >list.add(context.getVariable(\"faultVar\"));</action>\n" + " </exceptionHandler>\n" + " </exceptionHandlers>\n" + " </header>\n" + "\n" + " <nodes>\n" + " <start id=\"1\" name=\"Start\" />\n" + " <fault id=\"2\" name=\"Fault\" faultName=\"myFault\" faultVariable=\"SomeVar\" />\n" + " </nodes>\n" + "\n" + " <connections>\n" + " <connection from=\"1\" to=\"2\" />\n" + " </connections>\n" + "\n" + "</process>"); builder.addRuleFlow(source); KieSession session = createKieSession(builder.getPackage()); List<String> list = new ArrayList<String>(); session.setGlobal("list", list); ProcessInstance processInstance = ( ProcessInstance ) session.startProcess("org.drools.exception"); assertEquals(ProcessInstance.STATE_ACTIVE, processInstance.getState()); assertEquals(1, list.size()); assertEquals("SomeValue", list.get(0)); } @Test public void testProcessExceptionHandlerTriggerNode() { Reader source = new StringReader( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<process xmlns=\"http://drools.org/drools-5.0/process\"\n" + " xmlns:xs=\"http://www.w3.org/2001/XMLSchema-instance\"\n" + " xs:schemaLocation=\"http://drools.org/drools-5.0/process drools-processes-5.0.xsd\"\n" + " type=\"RuleFlow\" name=\"flow\" id=\"org.drools.exception\" package-name=\"org.drools\" version=\"1\" >\n" + "\n" + " <header>\n" + " <globals>\n" + " <global identifier=\"list\" type=\"java.util.List\" />\n" + " </globals>\n" + " <exceptionHandlers>\n" + " <exceptionHandler faultName=\"myFault\" type=\"action\" >\n" + " <action type=\"expression\" name=\"Complete\" dialect=\"java\" >((org.jbpm.process.instance.ProcessInstance) context.getProcessInstance()).setState(org.jbpm.process.instance.ProcessInstance.STATE_COMPLETED);</action>\n" + " </exceptionHandler>\n" + " </exceptionHandlers>\n" + " </header>\n" + "\n" + " <nodes>\n" + " <start id=\"1\" name=\"Start\" />\n" + " <fault id=\"2\" name=\"Fault\" faultName=\"myFault\" />\n" + " </nodes>\n" + "\n" + " <connections>\n" + " <connection from=\"1\" to=\"2\" />\n" + " </connections>\n" + "\n" + "</process>"); builder.addRuleFlow(source); KieSession session = createKieSession(builder.getPackage()); ProcessInstance processInstance = ( ProcessInstance ) session.startProcess("org.drools.exception"); assertEquals(ProcessInstance.STATE_COMPLETED, processInstance.getState()); } @Test public void testCompositeNodeExceptionHandlerTriggerNode() { Reader source = new StringReader( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<process xmlns=\"http://drools.org/drools-5.0/process\"\n" + " xmlns:xs=\"http://www.w3.org/2001/XMLSchema-instance\"\n" + " xs:schemaLocation=\"http://drools.org/drools-5.0/process drools-processes-5.0.xsd\"\n" + " type=\"RuleFlow\" name=\"flow\" id=\"org.drools.exception\" package-name=\"org.drools\" version=\"1\" >\n" + "\n" + " <header>\n" + " <globals>\n" + " <global identifier=\"list\" type=\"java.util.List\" />\n" + " </globals>\n" + " </header>\n" + "\n" + " <nodes>\n" + " <start id=\"1\" name=\"Start\" />\n" + " <composite id=\"2\" name=\"Composite\" >\n" + " <variables>\n" + " <variable name=\"SomeVar\" >\n" + " <type name=\"org.drools.core.process.core.datatype.impl.type.StringDataType\" />\n" + " <value>SomeValue</value>\n" + " </variable>\n" + " <variable name=\"FaultVariable\" >\n" + " <type name=\"org.drools.core.process.core.datatype.impl.type.StringDataType\" />\n" + " </variable>\n" + " </variables>\n" + " <exceptionHandlers>\n" + " <exceptionHandler faultName=\"MyFault\" type=\"action\" faultVariable=\"FaultVariable\" >\n" + " <action type=\"expression\" name=\"Trigger\" dialect=\"java\" >context.getProcessInstance().signalEvent(\"MyEvent\", null);</action>\n" + " </exceptionHandler>\n" + " </exceptionHandlers>\n" + " <nodes>\n" + " <fault id=\"1\" name=\"Fault\" faultName=\"MyFault\" faultVariable=\"SomeVar\" />\n" + " <eventNode id=\"2\" name=\"Event\" >\n" + " <eventFilters>\n" + " <eventFilter type=\"eventType\" eventType=\"MyEvent\" />\n" + " </eventFilters>\n" + " </eventNode>\n" + " <actionNode id=\"3\" name=\"Action\" >\n" + " <action type=\"expression\" dialect=\"java\" >list.add(context.getVariable(\"FaultVariable\"));</action>\n" + " </actionNode>\n" + " </nodes>\n" + " <connections>\n" + " <connection from=\"2\" to=\"3\" />\n" + " </connections>\n" + " <in-ports>\n" + " <in-port type=\"DROOLS_DEFAULT\" nodeId=\"1\" nodeInType=\"DROOLS_DEFAULT\" />\n" + " </in-ports>\n" + " <out-ports>\n" + " <out-port type=\"DROOLS_DEFAULT\" nodeId=\"3\" nodeOutType=\"DROOLS_DEFAULT\" />\n" + " </out-ports>\n" + " </composite>\n" + " <end id=\"3\" name=\"End\" />" + " </nodes>\n" + "\n" + " <connections>\n" + " <connection from=\"1\" to=\"2\" />\n" + " <connection from=\"2\" to=\"3\" />\n" + " </connections>\n" + "\n" + "</process>"); builder.addRuleFlow(source); KieSession session = createKieSession(builder.getPackage()); List<String> list = new ArrayList<String>(); session.setGlobal("list", list); ProcessInstance processInstance = ( ProcessInstance ) session.startProcess("org.drools.exception"); assertEquals(1, list.size()); assertEquals("SomeValue", list.get(0)); assertEquals(ProcessInstance.STATE_COMPLETED, processInstance.getState()); } @Test public void testNestedExceptionHandler() { Reader source = new StringReader( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<process xmlns=\"http://drools.org/drools-5.0/process\"\n" + " xmlns:xs=\"http://www.w3.org/2001/XMLSchema-instance\"\n" + " xs:schemaLocation=\"http://drools.org/drools-5.0/process drools-processes-5.0.xsd\"\n" + " type=\"RuleFlow\" name=\"flow\" id=\"org.drools.exception\" package-name=\"org.drools\" version=\"1\" >\n" + "\n" + " <header>\n" + " <globals>\n" + " <global identifier=\"list\" type=\"java.util.List\" />\n" + " </globals>\n" + " <exceptionHandlers>\n" + " <exceptionHandler faultName=\"otherFault\" type=\"action\" >\n" + " <action type=\"expression\" name=\"Print\" dialect=\"java\" >list.add(\"Triggered global exception scope\");</action>\n" + " </exceptionHandler>\n" + " </exceptionHandlers>\n" + " </header>\n" + "\n" + " <nodes>\n" + " <start id=\"1\" name=\"Start\" />\n" + " <composite id=\"2\" name=\"Composite\" >\n" + " <variables>\n" + " <variable name=\"SomeVar\" >\n" + " <type name=\"org.drools.core.process.core.datatype.impl.type.StringDataType\" />\n" + " <value>SomeValue</value>\n" + " </variable>\n" + " <variable name=\"FaultVariable\" >\n" + " <type name=\"org.drools.core.process.core.datatype.impl.type.StringDataType\" />\n" + " </variable>\n" + " </variables>\n" + " <exceptionHandlers>\n" + " <exceptionHandler faultName=\"MyFault\" type=\"action\" faultVariable=\"FaultVariable\" >\n" + " <action type=\"expression\" name=\"Trigger\" dialect=\"java\" >((org.jbpm.workflow.instance.node.CompositeNodeInstance) context.getNodeInstance()).signalEvent(\"MyEvent\", null);</action>\n" + " </exceptionHandler>\n" + " </exceptionHandlers>\n" + " <nodes>\n" + " <fault id=\"1\" name=\"Fault\" faultName=\"MyFault\" faultVariable=\"SomeVar\" />\n" + " <eventNode id=\"2\" name=\"Event\" >\n" + " <eventFilters>\n" + " <eventFilter type=\"eventType\" eventType=\"MyEvent\" />\n" + " </eventFilters>\n" + " </eventNode>\n" + " <fault id=\"3\" name=\"Fault\" faultName=\"otherFault\" />\n" + " </nodes>\n" + " <connections>\n" + " <connection from=\"2\" to=\"3\" />\n" + " </connections>\n" + " <in-ports>\n" + " <in-port type=\"DROOLS_DEFAULT\" nodeId=\"1\" nodeInType=\"DROOLS_DEFAULT\" />\n" + " </in-ports>\n" + " </composite>\n" + " <end id=\"3\" name=\"End\" />" + " </nodes>\n" + "\n" + " <connections>\n" + " <connection from=\"1\" to=\"2\" />\n" + " <connection from=\"2\" to=\"3\" />\n" + " </connections>\n" + "\n" + "</process>"); builder.addRuleFlow(source); KieSession session = createKieSession(builder.getPackage()); List<String> list = new ArrayList<String>(); session.setGlobal("list", list); ProcessInstance processInstance = ( ProcessInstance ) session.startProcess("org.drools.exception"); assertEquals(1, list.size()); assertEquals(ProcessInstance.STATE_ACTIVE, processInstance.getState()); } }
livthomas/jbpm
jbpm-flow-builder/src/test/java/org/jbpm/integrationtests/ProcessExceptionHandlerTest.java
Java
apache-2.0
15,097
# Coronilla occidentalis Willd. 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/Fabales/Fabaceae/Sesbania/Sesbania emerus/ Syn. Coronilla occidentalis/README.md
Markdown
apache-2.0
186
# Erinus humilis Sessé & Moc. SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Plantaginaceae/Erinus/Erinus humilis/README.md
Markdown
apache-2.0
178
# Veryhachium pastoris Deunff, 1966 SPECIES #### Status ACCEPTED #### According to Interim Register of Marine and Nonmarine Genera #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Veryhachium/Veryhachium pastoris/README.md
Markdown
apache-2.0
199
# Trichomanes Linnaeus, 1753 GENUS #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Pteridophyta/Polypodiopsida/Hymenophyllales/Hymenophyllaceae/Trichomanes/README.md
Markdown
apache-2.0
182
# Aphanocapsa richteriana Hieronymus SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Bacteria/Cyanobacteria/Chroococcales/Microcystaceae/Microcystis/Microcystis richteriana/ Syn. Aphanocapsa richteriana/README.md
Markdown
apache-2.0
191
# Coleosanthus grandiflorus (Hook.) Kuntze 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/Brickellia/Brickellia grandiflora/ Syn. Coleosanthus grandiflorus/README.md
Markdown
apache-2.0
197
package com.github.apycazo.spring_rest_forge.sample.restRepository.components; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * @author Andres Picazo */ @SpringBootApplication public class RecordApplication { public static void main (String [] args) { SpringApplication.run(RecordApplication.class, args); } }
apycazo/spring-rest-forge
src/test/java/com/github/apycazo/spring_rest_forge/sample/restRepository/components/RecordApplication.java
Java
apache-2.0
411
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections.ObjectModel; namespace DeveloperTest.TreeClasses { public class TreeNode { public TreeNode Parent { get; private set; } private List<TreeNode> _internalChildren; private ReadOnlyCollection<TreeNode> _children; public ReadOnlyCollection<TreeNode> Children { get { if (_children == null) { _children = new ReadOnlyCollection<TreeNode>(_internalChildren); } return _children; } } public int Id { get; private set; } public TreeNode(int id) { Id = id; _internalChildren = new List<TreeNode>(); } public void AddChild(TreeNode id) { id.Parent = this; _internalChildren.Add(id); } public void Traverse(Action<TreeNode> visit) { visit(this); foreach (var child in Children) { child.Traverse(visit); } } } }
harshiscoolguy/Implementation
DeveloperTestTypes/TreeClasses/TreeNode.cs
C#
apache-2.0
1,190
/** * @license Apache-2.0 * * Copyright (c) 2020 The Stdlib 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. */ 'use strict'; // MODULES // var resolve = require( 'path' ).resolve; var tape = require( 'tape' ); var floor = require( '@stdlib/math/base/special/floor' ); var isnan = require( '@stdlib/math/base/assert/is-nan' ); var float64ToFloat32 = require( '@stdlib/number/float64/base/to-float32' ); var Float32Array = require( '@stdlib/array/float32' ); var tryRequire = require( '@stdlib/utils/try-require' ); // VARIABLES // var svariancech = tryRequire( resolve( __dirname, './../lib/svariancech.native.js' ) ); var opts = { 'skip': ( svariancech instanceof Error ) }; // TESTS // tape( 'main export is a function', opts, function test( t ) { t.ok( true, __filename ); t.strictEqual( typeof svariancech, 'function', 'main export is a function' ); t.end(); }); tape( 'the function has an arity of 4', opts, function test( t ) { t.strictEqual( svariancech.length, 4, 'has expected arity' ); t.end(); }); tape( 'the function calculates the population variance of a strided array', opts, function test( t ) { var x; var v; x = new Float32Array( [ 1.0, -2.0, -4.0, 5.0, 0.0, 3.0 ] ); v = svariancech( x.length, 0, x, 1 ); t.strictEqual( v, float64ToFloat32( 53.5/x.length ), 'returns expected value' ); x = new Float32Array( [ -4.0, -4.0 ] ); v = svariancech( x.length, 0, x, 1 ); t.strictEqual( v, 0.0, 'returns expected value' ); x = new Float32Array( [ NaN, 4.0 ] ); v = svariancech( x.length, 0, x, 1 ); t.strictEqual( isnan( v ), true, 'returns expected value' ); t.end(); }); tape( 'the function calculates the sample variance of a strided array', opts, function test( t ) { var x; var v; x = new Float32Array( [ 1.0, -2.0, -4.0, 5.0, 0.0, 3.0 ] ); v = svariancech( x.length, 1, x, 1 ); t.strictEqual( v, float64ToFloat32( 53.5/(x.length-1) ), 'returns expected value' ); x = new Float32Array( [ -4.0, -4.0 ] ); v = svariancech( x.length, 1, x, 1 ); t.strictEqual( v, 0.0, 'returns expected value' ); x = new Float32Array( [ NaN, 4.0 ] ); v = svariancech( x.length, 1, x, 1 ); t.strictEqual( isnan( v ), true, 'returns expected value' ); t.end(); }); tape( 'if provided an `N` parameter less than or equal to `0`, the function returns `NaN`', opts, function test( t ) { var x; var v; x = new Float32Array( [ 1.0, -2.0, -4.0, 5.0, 3.0 ] ); v = svariancech( 0, 1, x, 1 ); t.strictEqual( isnan( v ), true, 'returns expected value' ); v = svariancech( -1, 1, x, 1 ); t.strictEqual( isnan( v ), true, 'returns expected value' ); t.end(); }); tape( 'if provided an `N` parameter equal to `1`, the function returns a population variance of `0`', opts, function test( t ) { var x; var v; x = new Float32Array( [ 1.0, -2.0, -4.0, 5.0, 3.0 ] ); v = svariancech( 1, 0, x, 1 ); t.strictEqual( v, 0.0, 'returns expected value' ); t.end(); }); tape( 'if provided a `correction` parameter yielding `N-correction` less than or equal to `0`, the function returns `NaN`', opts, function test( t ) { var x; var v; x = new Float32Array( [ 1.0, -2.0, -4.0, 5.0, 3.0 ] ); v = svariancech( x.length, x.length, x, 1 ); t.strictEqual( isnan( v ), true, 'returns expected value' ); v = svariancech( x.length, x.length+1, x, 1 ); t.strictEqual( isnan( v ), true, 'returns expected value' ); t.end(); }); tape( 'the function supports a `stride` parameter', opts, function test( t ) { var N; var x; var v; x = new Float32Array([ 1.0, // 0 2.0, 2.0, // 1 -7.0, -2.0, // 2 3.0, 4.0, // 3 2.0 ]); N = floor( x.length / 2 ); v = svariancech( N, 1, x, 2 ); t.strictEqual( v, 6.25, 'returns expected value' ); t.end(); }); tape( 'the function supports a negative `stride` parameter', opts, function test( t ) { var N; var x; var v; x = new Float32Array([ 1.0, // 3 2.0, 2.0, // 2 -7.0, -2.0, // 1 3.0, 4.0, // 0 2.0 ]); N = floor( x.length / 2 ); v = svariancech( N, 1, x, -2 ); t.strictEqual( v, 6.25, 'returns expected value' ); t.end(); }); tape( 'if provided a `stride` parameter equal to `0`, the function returns `0`', opts, function test( t ) { var x; var v; x = new Float32Array( [ 1.0, -2.0, -4.0, 5.0, 3.0 ] ); v = svariancech( x.length, 1, x, 0 ); t.strictEqual( v, 0.0, 'returns expected value' ); t.end(); }); tape( 'the function supports view offsets', opts, function test( t ) { var x0; var x1; var N; var v; x0 = new Float32Array([ 2.0, 1.0, // 0 2.0, -2.0, // 1 -2.0, 2.0, // 2 3.0, 4.0, // 3 6.0 ]); x1 = new Float32Array( x0.buffer, x0.BYTES_PER_ELEMENT*1 ); // start at 2nd element N = floor(x1.length / 2); v = svariancech( N, 1, x1, 2 ); t.strictEqual( v, 6.25, 'returns expected value' ); t.end(); });
stdlib-js/stdlib
lib/node_modules/@stdlib/stats/base/svariancech/test/test.svariancech.native.js
JavaScript
apache-2.0
5,300
/** * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * * Copyright 2012-2013 the original author or authors. */ package org.assertj.jodatime.error; import java.util.Date; import org.assertj.core.error.BasicErrorMessageFactory; import org.assertj.core.error.ErrorMessageFactory; import org.assertj.core.internal.ComparisonStrategy; import org.assertj.core.internal.StandardComparisonStrategy; /** * Creates an error message indicating that an assertion that verifies that a {@link Date} is before another one failed. * * @author Joel Costigliola */ public class ShouldBeBefore extends BasicErrorMessageFactory { /** * Creates a new </code>{@link ShouldBeBefore}</code>. * @param actual the actual value in the failed assertion. * @param other the value used in the failed assertion to compare the actual value to. * @param comparisonStrategy the {@link ComparisonStrategy} used to evaluate assertion. * @return the created {@code ErrorMessageFactory}. */ public static ErrorMessageFactory shouldBeBefore(Object actual, Object other, ComparisonStrategy comparisonStrategy) { return new ShouldBeBefore(actual, other, comparisonStrategy); } /** * Creates a new </code>{@link ShouldBeBefore}</code>. * @param actual the actual value in the failed assertion. * @param other the value used in the failed assertion to compare the actual value to. * @return the created {@code ErrorMessageFactory}. */ public static ErrorMessageFactory shouldBeBefore(Object actual, Object other) { return new ShouldBeBefore(actual, other, StandardComparisonStrategy.instance()); } private ShouldBeBefore(Object actual, Object other, ComparisonStrategy comparisonStrategy) { super("\nExpecting:\n <%s>\nto be strictly before:\n <%s>\n%s", actual, other, comparisonStrategy); } }
PascalSchumacher/assertj-joda-time
src/main/java/org/assertj/jodatime/error/ShouldBeBefore.java
Java
apache-2.0
2,376
# UserInventoryAddRequest ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **note** | **String** | A note to be passed to the invoice or transaction | **overrides** | **List&lt;String&gt;** | A list of behaviors to ignore explicitely. Ex: &#39;limited_gettable&#39; | [optional] **skipInvoice** | **Boolean** | If set to true will cause the endpoint to skip creation of cart and invoice to track the inventory change | **sku** | **String** | The specific SKU of the item to be added to the inventory |
knetikmedia/knetikcloud-java-client
docs/UserInventoryAddRequest.md
Markdown
apache-2.0
572
--- layout: postag title: 'SCONJ' shortdef: 'subordinating conjunction' udver: '2' --- ### Definition A subordinating conjunction is a conjunction that links constructions by making one of them a constituent of the other. The subordinating conjunction typically marks the incorporated constituent which has the status of a (subordinate) clause. For _coordinating conjunctions,_ see [CCONJ](). ### The coordinating conjunctions of Naija include : - sey (that) : Make im make sure <b>sey</b> di brake dey okay. - wey : because na di vehicule <b>wey</b> una dey take move be dis. - if : So <b>if</b> we catch you make you no vex. - because : <b>Because</b> speed im dey lead to accident. - as : anoder thing wey i want follow una relate na di attitude of sey make we dey use phone <b>as</b> we dey drive.
PhyloStar/UDTelugu
_pcm-pos/SCONJ.md
Markdown
apache-2.0
807
package explorviz.live_trace_processing.configuration; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Enumeration; import java.util.Properties; public final class ConfigurationFactory implements Keys { private ConfigurationFactory() { } public static final Configuration createSingletonConfiguration() { final Configuration defaultConfiguration = ConfigurationFactory .defaultConfiguration(); // Searching for configuration file location passed to JVM String configurationFile = System .getProperty(Keys.CUSTOM_PROPERTIES_LOCATION_JVM); final Configuration loadConfiguration; if (configurationFile != null) { loadConfiguration = ConfigurationFactory.loadConfigurationFromFile( configurationFile, defaultConfiguration); } else { // No JVM property; Trying to find configuration file in classpath configurationFile = Keys.CUSTOM_PROPERTIES_LOCATION_CLASSPATH; loadConfiguration = ConfigurationFactory .loadConfigurationFromResource(configurationFile, defaultConfiguration); } // 1.JVM-params -> 2.properties file -> 3.default properties file return ConfigurationFactory.getSystemPropertiesStartingWith( Keys.PREFIX, loadConfiguration); } public static final Configuration createDefaultConfiguration() { return new Configuration(ConfigurationFactory.defaultConfiguration()); } public static final Configuration createConfigurationFromFile( final String configurationFile) { return ConfigurationFactory.loadConfigurationFromFile( configurationFile, ConfigurationFactory.defaultConfiguration()); } private static final Configuration defaultConfiguration() { return ConfigurationFactory.loadConfigurationFromResource( Keys.DEFAULT_PROPERTIES_LOCATION_CLASSPATH, null); } private static final Configuration loadConfigurationFromFile( final String propertiesFn, final Configuration defaultValues) { final Configuration properties = new Configuration(defaultValues); InputStream is = null; // NOPMD (null) try { try { is = new FileInputStream(propertiesFn); } catch (final FileNotFoundException ex) { // if not found as absolute path try within the classpath is = ConfigurationFactory.class.getClassLoader() .getResourceAsStream(propertiesFn); if (is == null) { return new Configuration(defaultValues); } } properties.load(is); return properties; } catch (final Exception ex) { // NOPMD NOCS (IllegalCatchCheck) } finally { if (is != null) { try { is.close(); } catch (final IOException ex) { } } } return new Configuration(defaultValues); } private static final Configuration loadConfigurationFromResource( final String propertiesFn, final Configuration defaultValues) { final InputStream is = ConfigurationFactory.class.getClassLoader() .getResourceAsStream(propertiesFn); if (is != null) { try { final Configuration properties = new Configuration( defaultValues); properties.load(is); return properties; } catch (final Exception ex) { // NOPMD NOCS (IllegalCatchCheck) } finally { try { is.close(); } catch (final IOException ex) { } } } return new Configuration(defaultValues); } private static final Configuration getSystemPropertiesStartingWith( final String prefix, final Configuration defaultValues) { final Configuration configuration = new Configuration(defaultValues); final Properties properties = System.getProperties(); final Enumeration<?> keys = properties.propertyNames(); while (keys.hasMoreElements()) { final String property = (String) keys.nextElement(); if (property.startsWith(prefix)) { configuration.setProperty(property, properties.getProperty(property)); } } return configuration; } }
ExplorViz/common
src/explorviz/live_trace_processing/configuration/ConfigurationFactory.java
Java
apache-2.0
4,001
from __future__ import absolute_import, division, print_function, unicode_literals import os import unittest from mock import patch from nose.tools import assert_equals, assert_raises import pygenie from ..utils import FakeRunningJob assert_equals.__self__.maxDiff = None @pygenie.adapter.genie_3.set_jobname def set_jobname(job): return dict() @patch.dict('os.environ', {'GENIE_BYPASS_HOME_CONFIG': '1'}) class TestingGenieJob(unittest.TestCase): """Test GenieJob.""" def test_default_command_tag(self): """Test GenieJob default command tags.""" job = pygenie.jobs.GenieJob() assert_equals( job.get('default_command_tags'), [u'type:genie'] ) def test_cmd_args_explicit(self): """Test GenieJob explicit cmd args.""" job = pygenie.jobs.GenieJob() \ .command_arguments('explicitly stating command args') assert_equals( job.cmd_args, u'explicitly stating command args' ) def test_cmd_args_constructed(self): """Test GenieJob constructed cmd args.""" with assert_raises(pygenie.exceptions.GenieJobError) as cm: pygenie.jobs.GenieJob().cmd_args @patch.dict('os.environ', {'GENIE_BYPASS_HOME_CONFIG': '1'}) class TestingGenieJobRepr(unittest.TestCase): """Test GenieJob repr.""" @patch('pygenie.jobs.core.is_file') def test_repr(self, is_file): """Test GenieJob repr.""" is_file.return_value = True job = pygenie.jobs.GenieJob() \ .applications('app1') \ .applications('app2') \ .archive(False) \ .cluster_tags('cluster1') \ .cluster_tags('cluster2') \ .command_arguments('genie job repr args') \ .command_tags('cmd1') \ .command_tags('cmd2') \ .dependencies('/dep1') \ .dependencies('/dep2') \ .description('description') \ .disable_archive() \ .genie_email('jsmith@email.com') \ .genie_setup_file('/setup.sh') \ .genie_timeout(999) \ .genie_url('http://asdfasdf') \ .genie_username('jsmith') \ .group('group1') \ .job_id('geniejob_repr') \ .job_name('geniejob_repr') \ .job_version('1.1.1') \ .parameter('param1', 'pval1') \ .parameter('param2', 'pval2') \ .parameters(param3='pval3', param4='pval4') \ .post_cmd_args('post1') \ .post_cmd_args(['post2', 'post3']) \ .tags('tag1') \ .tags('tag2') assert_equals( str(job), '.'.join([ 'GenieJob()', 'applications("app1")', 'applications("app2")', 'archive(False)', 'cluster_tags("cluster1")', 'cluster_tags("cluster2")', 'command_arguments("genie job repr args")', 'command_tags("cmd1")', 'command_tags("cmd2")', 'dependencies("/dep1")', 'dependencies("/dep2")', 'description("description")', 'genie_email("jsmith@email.com")', 'genie_setup_file("/setup.sh")', 'genie_timeout(999)', 'genie_url("http://asdfasdf")', 'genie_username("jsmith")', 'group("group1")', 'job_id("geniejob_repr")', 'job_name("geniejob_repr")', 'job_version("1.1.1")', 'parameter("param1", "pval1")', 'parameter("param2", "pval2")', 'parameter("param3", "pval3")', 'parameter("param4", "pval4")', 'post_cmd_args("post1")', "post_cmd_args([u'post2', u'post3'])", 'tags("tag1")', 'tags("tag2")' ]) ) def test_genie_cpu(self): """Test GenieJob repr (genie_cpu).""" job = pygenie.jobs.GenieJob() \ .job_id('123') \ .genie_username('user') \ .genie_cpu(12) assert_equals( '.'.join([ 'GenieJob()', 'genie_cpu(12)', 'genie_username("user")', 'job_id("123")' ]), str(job) ) def test_genie_memory(self): """Test GenieJob repr (genie_memory).""" job = pygenie.jobs.GenieJob() \ .job_id('123') \ .genie_username('user') \ .genie_memory(7000) assert_equals( '.'.join([ 'GenieJob()', 'genie_memory(7000)', 'genie_username("user")', 'job_id("123")' ]), str(job) ) @patch.dict('os.environ', {'GENIE_BYPASS_HOME_CONFIG': '1'}) class TestingGenieJobAdapters(unittest.TestCase): """Test adapting GenieJob to different clients.""" def setUp(self): self.dirname = os.path.dirname(os.path.realpath(__file__)) def test_genie3_payload(self): """Test GenieJob payload for Genie 3.""" with patch.dict('os.environ', {'GENIE_BYPASS_HOME_CONFIG': '1'}): genie3_conf = pygenie.conf.GenieConf() \ .load_config_file(os.path.join(self.dirname, 'genie3.ini')) job = pygenie.jobs.GenieJob(genie3_conf) \ .applications(['applicationid1']) \ .cluster_tags('type:cluster1') \ .command_arguments('command args for geniejob') \ .command_tags('type:geniecmd') \ .dependencies(['/file1', '/file2']) \ .description('this job is to test geniejob adapter') \ .archive(False) \ .genie_cpu(3) \ .genie_email('jdoe@email.com') \ .genie_memory(999) \ .genie_timeout(100) \ .genie_url('http://fdsafdsa') \ .genie_username('jdoe') \ .group('geniegroup1') \ .job_id('geniejob1') \ .job_name('testing_adapting_geniejob') \ .tags('tag1, tag2') \ .job_version('0.0.1alpha') assert_equals( pygenie.adapter.genie_3.get_payload(job), { 'applications': ['applicationid1'], 'attachments': [], 'clusterCriterias': [ {'tags': ['type:cluster1']}, {'tags': ['type:genie']}, ], 'commandArgs': 'command args for geniejob', 'commandCriteria': ['type:geniecmd'], 'cpu': 3, 'dependencies': ['/file1', '/file2'], 'description': 'this job is to test geniejob adapter', 'disableLogArchival': True, 'email': 'jdoe@email.com', 'group': 'geniegroup1', 'id': 'geniejob1', 'memory': 999, 'name': 'testing_adapting_geniejob', 'setupFile': None, 'tags': ['tag1', 'tag2'], 'timeout': 100, 'user': 'jdoe', 'version': '0.0.1alpha' } ) @patch.dict('os.environ', {'GENIE_BYPASS_HOME_CONFIG': '1'}) class TestingJobExecute(unittest.TestCase): """Test executing job.""" @patch('pygenie.jobs.core.reattach_job') @patch('pygenie.jobs.core.generate_job_id') @patch('pygenie.jobs.core.execute_job') def test_job_execute(self, exec_job, gen_job_id, reattach_job): """Testing job execution.""" job = pygenie.jobs.HiveJob() \ .job_id('exec') \ .genie_username('exectester') \ .script('select * from db.table') job.execute() gen_job_id.assert_not_called() reattach_job.assert_not_called() exec_job.assert_called_once_with(job) @patch('pygenie.jobs.core.reattach_job') @patch('pygenie.jobs.core.generate_job_id') @patch('pygenie.jobs.core.execute_job') def test_job_execute_retry(self, exec_job, gen_job_id, reattach_job): """Testing job execution with retry.""" job_id = 'exec-retry' new_job_id = '{}-5'.format(job_id) gen_job_id.return_value = new_job_id reattach_job.side_effect = pygenie.exceptions.GenieJobNotFoundError job = pygenie.jobs.HiveJob() \ .job_id(job_id) \ .genie_username('exectester') \ .script('select * from db.table') job.execute(retry=True) gen_job_id.assert_called_once_with(job_id, return_success=True, conf=job._conf) reattach_job.assert_called_once_with(new_job_id, conf=job._conf) exec_job.assert_called_once_with(job) assert_equals(new_job_id, job._job_id) @patch('pygenie.jobs.core.reattach_job') @patch('pygenie.jobs.core.generate_job_id') @patch('pygenie.jobs.core.execute_job') def test_job_execute_retry_force(self, exec_job, gen_job_id, reattach_job): """Testing job execution with force retry.""" job_id = 'exec-retry-force' new_job_id = '{}-8'.format(job_id) gen_job_id.return_value = new_job_id reattach_job.side_effect = pygenie.exceptions.GenieJobNotFoundError job = pygenie.jobs.HiveJob() \ .job_id(job_id) \ .genie_username('exectester') \ .script('select * from db.table') job.execute(retry=True, force=True) gen_job_id.assert_called_once_with(job_id, return_success=False, conf=job._conf) reattach_job.assert_called_once_with(new_job_id, conf=job._conf) exec_job.assert_called_once_with(job) assert_equals(new_job_id, job._job_id) @patch.dict('os.environ', {'GENIE_BYPASS_HOME_CONFIG': '1'}) class TestingSetJobName(unittest.TestCase): """Test setting job name from script.""" def test_set_job_name(self): """Test setting job name from script contents.""" assert_equals( {'name': 'SELECT * FROM db.table'}, set_jobname(pygenie.jobs.PrestoJob() \ .script('SELECT * FROM db.table')) ) def test_set_job_name_truncate(self): """Test setting job name from script contents (with truncate).""" job_name = set_jobname( pygenie.jobs.PrestoJob()\ .script(''.join([str(i) for i in range(100)])) ).get('name') or '' assert_equals( 40, len(job_name) ) def test_set_job_name_newline(self): """Test setting job name from script contents (with newline).""" assert_equals( {'name': 'SELECT * FROM db.table'}, set_jobname(pygenie.jobs.PrestoJob() \ .script("SELECT\n*\nFROM\ndb.table")) ) def test_set_job_name_parameter(self): """Test setting job name from script contents (with parameter).""" assert_equals( {'name': 'SELECT * FROM db.{table}'}, set_jobname(pygenie.jobs.PrestoJob() \ .script("SELECT * FROM db.${table}")) ) def test_set_job_name_semicolon(self): """Test setting job name from script contents (with semicolon).""" assert_equals( {'name': 'SELECT * FROM db.table'}, set_jobname(pygenie.jobs.PrestoJob() \ .script("SELECT * FROM db.table;")) ) def test_set_job_name_quotes(self): """Test setting job name from script contents (with quotes).""" assert_equals( {'name': 'min(values) r = foo order by date, hour'}, set_jobname(pygenie.jobs.PrestoJob() \ .script("min(\"values\") r = 'foo' order by date, hour;")) )
ajoymajumdar/genie
genie-client/src/main/python/tests/job_tests/test_geniejob.py
Python
apache-2.0
12,048