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
package org.scriptonbasestar.oauth.client.http; import lombok.experimental.UtilityClass; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.scriptonbasestar.oauth.client.util.OAuthEncodeUtil; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * @author archmagece * @since 2016-10-26 13 */ //@NoArgsConstructor(access = AccessLevel.PRIVATE) @UtilityClass public final class ParamUtil { private static final char QUERY_QUESTION = '?'; private static final char QUERY_AND = '&'; private static final char QUERY_EQUAL = '='; public static String generateOAuthQuery(String url, ParamList paramList) { return generateOAuthQuery(url, paramList.paramSet().toArray(new Param[paramList.paramSet().size()])); } public static String generateOAuthQuery(String url, Collection<Param> params) { return generateOAuthQuery(url, params.toArray(new Param[params.size()])); } public static String generateOAuthQuery(String url, Param... params) { StringBuilder sb = new StringBuilder(); sb.append(url).append(QUERY_QUESTION); for (Param param : params) { for (int j = 0; j < param.getValues().length; j++) { sb.append(param.getKey()).append(QUERY_EQUAL).append(OAuthEncodeUtil.encode(param.getValues()[j])); if (j < param.getValues().length) { sb.append(QUERY_AND); } } } sb.deleteCharAt(sb.length() - 1); return sb.toString(); } public static List<NameValuePair> generateNameValueList(ParamList paramList) { List<NameValuePair> formParams = new ArrayList<>(); for (Param param : paramList.paramSet()) { for (String value : param.getValues()) { formParams.add(new BasicNameValuePair(param.getKey(), value)); } } return formParams; } }
BeanSugar/bs-oauth-java
oauth-client/src/main/java/org/scriptonbasestar/oauth/client/http/ParamUtil.java
Java
apache-2.0
1,778
package com.codeforces.commons.text.similarity; import com.codeforces.commons.resource.ResourceUtil; import com.codeforces.commons.text.Patterns; import com.codeforces.commons.text.StringUtil; import org.apache.commons.text.similarity.LevenshteinDistance; import javax.annotation.Nonnull; import java.util.HashMap; import java.util.Map; class SimilarityUtil { private static final int DEFAULT_LEVENSHTEIN_THRESHOLD = 1; private static final LevenshteinDistance defaultLevenshtein = new LevenshteinDistance(DEFAULT_LEVENSHTEIN_THRESHOLD); private static final Map<String, Integer> protoRuEn; private static final Map<String, Integer> protoEn; private static final int[] skipTypes = new int[]{ Character.CONTROL, Character.FORMAT, Character.ENCLOSING_MARK, Character.LINE_SEPARATOR, Character.PARAGRAPH_SEPARATOR }; static boolean levenshteinCheck(String a, String b) { int distance = defaultLevenshtein.apply(a, b); if (distance < 0) { return false; } return distance < DEFAULT_LEVENSHTEIN_THRESHOLD; } static String normalizeByRuEnMap(String s) { return normalizeByMap(s, protoRuEn); } static String normalizeByEnMap(String s) { return normalizeByMap(s, protoEn); } private static String normalizeByMap(@Nonnull String s, Map<String, Integer> protoMap) { StringBuilder result = new StringBuilder(); for (int i = 0; i < s.length(); i++) { String key; if (i + 1 < s.length()) { char[] charBuf = new char[2]; charBuf[0] = s.charAt(i); charBuf[1] = s.charAt(i + 1); key = new String(charBuf); if (protoMap.containsKey(key)) { result.appendCodePoint(protoMap.get(key)); i++; continue; } } key = String.valueOf(s.charAt(i)); if (protoMap.containsKey(key)) { result.appendCodePoint(protoMap.get(key)); } else { result.append(key); } } return result.toString(); } @SuppressWarnings("unused") private static boolean isSkip(int codePoint) { int type = Character.getType(codePoint); for (int skipType : skipTypes) { if (type == skipType) { return true; } } return false; } private static Map<String, Integer> loadSimple(String resourceName) { Map<String, Integer> protoMap = new HashMap<>(); Patterns.LINE_BREAK_PATTERN.splitAsStream( ResourceUtil.getResourceAsString(SimilarityUtil.class, resourceName) ).filter(StringUtil::isNotBlank).forEach(line -> { String[] fields = line.split(" "); int proto = fields[0].codePointAt(0); for (int i = 1; i < fields.length; i++) { protoMap.put(fields[i], proto); } }); return protoMap; } private SimilarityUtil() {} static { protoRuEn = loadSimple("simpleRuEn.txt"); protoEn = loadSimple("simpleEn.txt"); } }
Codeforces/codeforces-commons
code/src/main/java/com/codeforces/commons/text/similarity/SimilarityUtil.java
Java
apache-2.0
3,276
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.arrow.vector; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.arrow.memory.BufferAllocator; import org.apache.arrow.vector.types.pojo.Field; import org.apache.arrow.vector.types.pojo.Schema; /** * Holder for a set of vectors to be loaded/unloaded */ public class VectorSchemaRoot implements AutoCloseable { private final Schema schema; private int rowCount; private final List<FieldVector> fieldVectors; private final Map<String, FieldVector> fieldVectorsMap = new HashMap<>(); public VectorSchemaRoot(FieldVector parent) { this(parent.getField().getChildren(), parent.getChildrenFromFields(), parent.getAccessor().getValueCount()); } public VectorSchemaRoot(List<Field> fields, List<FieldVector> fieldVectors, int rowCount) { if (fields.size() != fieldVectors.size()) { throw new IllegalArgumentException("Fields must match field vectors. Found " + fieldVectors.size() + " vectors and " + fields.size() + " fields"); } this.schema = new Schema(fields); this.rowCount = rowCount; this.fieldVectors = fieldVectors; for (int i = 0; i < schema.getFields().size(); ++i) { Field field = schema.getFields().get(i); FieldVector vector = fieldVectors.get(i); fieldVectorsMap.put(field.getName(), vector); } } public static VectorSchemaRoot create(Schema schema, BufferAllocator allocator) { List<FieldVector> fieldVectors = new ArrayList<>(); for (Field field : schema.getFields()) { FieldVector vector = field.createVector(allocator); fieldVectors.add(vector); } if (fieldVectors.size() != schema.getFields().size()) { throw new IllegalArgumentException("The root vector did not create the right number of children. found " + fieldVectors.size() + " expected " + schema.getFields().size()); } return new VectorSchemaRoot(schema.getFields(), fieldVectors, 0); } public List<FieldVector> getFieldVectors() { return fieldVectors; } public FieldVector getVector(String name) { return fieldVectorsMap.get(name); } public Schema getSchema() { return schema; } public int getRowCount() { return rowCount; } public void setRowCount(int rowCount) { this.rowCount = rowCount; } @Override public void close() { RuntimeException ex = null; for (FieldVector fieldVector : fieldVectors) { try { fieldVector.close(); } catch (RuntimeException e) { ex = chain(ex, e); } } if (ex!= null) { throw ex; } } private RuntimeException chain(RuntimeException root, RuntimeException e) { if (root == null) { root = e; } else { root.addSuppressed(e); } return root; } private void printRow(StringBuilder sb, List<Object> row) { boolean first = true; for (Object v : row) { if (first) { first = false; } else { sb.append("\t"); } sb.append(v); } sb.append("\n"); } public String contentToTSVString() { StringBuilder sb = new StringBuilder(); List<Object> row = new ArrayList<>(schema.getFields().size()); for (Field field : schema.getFields()) { row.add(field.getName()); } printRow(sb, row); for (int i = 0; i < rowCount; i++) { row.clear(); for (FieldVector v : fieldVectors) { row.add(v.getAccessor().getObject(i)); } printRow(sb, row); } return sb.toString(); } }
StevenMPhillips/arrow
java/vector/src/main/java/org/apache/arrow/vector/VectorSchemaRoot.java
Java
apache-2.0
4,351
# Br00jaBot A simple shitposter bot made by dirty hispanics to others dirty hispanics. Even when this repository is public, i have no intentions to make a public release, i just need a place for save my sh!t, ignore this readme as long as you can, maybe some day i'll put something util here. Enjoy. PD: Br00jaBot use [telebot-master](https://github.com/yukuku/telebot).
leothescrub/br00jabot
README.md
Markdown
apache-2.0
377
module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), jshint: { options: { reporter: require('jshint-stylish') }, // when this task is run, lint the Gruntfile and all js files ilisted build: ['Gruntfile.js', 'server.js', 'public/js/**/*.js', 'public/js/app.js','app/**/*.js', 'config/db.js'] }, csslint: { strict: { options: { "import": 2 } }, files: ['public/css/style.css'] }, autoprefixer: { options: { browsers: ['last 2 versions', 'ie 8', 'ie 9'] }, build: { files: { 'public/css/build/style.css': 'public/css/style.css' } } }, watch: { styles: { files: ['public/css/style.css'], tasks: ['autoprefixer', 'csslint'] }, // for scripts, run jshint scripts: { files: ['Gruntfile.js', 'server.js', 'public/js/**/*.js', 'public/js/app.js','app/**/*.js', 'config/db.js'], tasks: ['jshint'] } }, nodemon: { dev: { script: 'server.js' } }, // run watch and nodemon at the same time concurrent: { options: { logConcurrentOutput: true }, tasks: ['nodemon', 'watch'] } }); //closes grunt initconfig grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-autoprefixer'); grunt.loadNpmTasks('grunt-contrib-csslint'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-nodemon'); grunt.loadNpmTasks('grunt-concurrent'); grunt.registerTask('default', ['jshint', 'csslint', 'autoprefixer', 'concurrent']); };
ma3east/eStub2
Gruntfile.js
JavaScript
apache-2.0
1,927
/******************************************************************************* * Copyright 2016 Alrick Grandison (Algodal) alrickgrandison@gmail.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.algodal.gdxscreen.utils; import com.badlogic.gdx.utils.ArrayMap; import com.badlogic.gdx.utils.Disposable; import com.badlogic.gdx.utils.ObjectMap.Entry; /** * The class allows for the storage, loading and disposing of data * that is to be global and life span is to last the entirety of the * Game's life span. */ public class GdxLibrary { private final ArrayMap<String, Content<?>> contentMap; public final GdxDebug debug; public GdxLibrary(){ contentMap = new ArrayMap<>(); debug = new GdxDebug().setOn(true); } /** * Disposes all its contents. */ public final void destroy(){ for(Entry<String, Content<?>> entry : contentMap) if(!entry.value.independent) entry.value.dispose(); } /** * Initializes all its contents. */ public final void create(){ for(Entry<String, Content<?>> entry : contentMap) if(!entry.value.independent) entry.value.initialize(); } /** * Loads all its contents. */ public final void load(){ for(Entry<String, Content<?>> entry : contentMap) if(!entry.value.independent) entry.value.load(); } /** * Unloads all its contents. */ public final void unload(){ for(Entry<String, Content<?>> entry : contentMap) if(!entry.value.independent) entry.value.unload(); } /** * Get the content stored in the library. * @param ref Your unique defined reference string * @param <T> type of content - Any object. * @return the content you requested. */ @SuppressWarnings("unchecked") public final <T> Content<T> getContent(String ref){ debug.assertNotNull("content ref is not null", ref); debug.assertStringNotEmpty("content ref is not empty", (ref = ref.trim())); debug.assertTrue("content ref exists", contentMap.containsKey(ref)); return (Content<T>) contentMap.get(ref); } //for convenience public final <T> Content<T> getContent(String ref, Class<T> clazz){ return getContent(ref); } public final <T> void setContent(String ref, Content<T> content){ debug.assertNotNull("content ref is not null", ref); debug.assertNotNull("content is not null", content); debug.assertStringNotEmpty("content ref is not empty", (ref = ref.trim())); //Space is not valid reference debug.assertFalse("content ref is unique", contentMap.containsKey(ref)); //unique reference debug.assertFalse("content object is unique", contentMap.containsValue(content, true)); //add reference contentMap.put(ref, content); } /** * Content that is stored in the library. Remember to set the * variables initialized, object and loaded inside the respective method bodies. * The content allows you to initialize, load, unload and get the objects any time * you want. * * @param <T> type of content - Any object. */ public static abstract class Content <T> implements Disposable{ /** * Store your initialized object into this variable. The * contents of this variable is what get() returns. */ protected T object; /** * Set this to true when you call load or false * when you call unload. The value of this is what isLoaded() * returns. */ protected boolean loaded; /** * Set this to true when you call the initialized method. * Its value is what isInitialized() returns. */ protected boolean initialized; /** * Initialize the content. * @return this content */ abstract public Content<T> initialize(); private boolean independent; /** * Tells the library container not to process it when * it is processing contents in batch. * @return the independent */ public final boolean isIndependent() { return independent; } /** * Tells the library container not to process it when * it is processing contents in batch. * @param independent the independent to set * @return this content */ public final Content<T> setIndependent(boolean independent) { this.independent = independent; return this; } /** * * @return content of object */ public final T get(){ return object; } /** * * @return the content of loaded */ public final boolean isLoaded(){ return loaded; } /** * * @return the content of initialized */ public final boolean isInitialized(){ return initialized; } /** * Loads the content, i.e. make it usable. * @return this content. */ abstract public Content<T> load(); /** * Unloads the content, i.e. can not be used after unloading. */ abstract public void unload(); } public static abstract class ContentAdaptor<T> extends Content<T>{ @Override public Content<T> initialize() { onInitialize(); initialized = true; return this; } @Override public Content<T> load() { onLoad(); loaded = true; return this; } @Override public void unload() { onUnLoad(); loaded = false; } public abstract void onInitialize(); public abstract void onLoad(); public abstract void onUnLoad(); } }
Rickodesea/GdxScreen
GdxScreen/core/src/com/algodal/gdxscreen/utils/GdxLibrary.java
Java
apache-2.0
5,774
/* * Copyright 2015 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.template.soy.pysrc.internal; import static com.google.template.soy.pysrc.internal.SoyExprForPySubject.assertThatSoyExpr; import com.google.template.soy.exprtree.Operator; import com.google.template.soy.pysrc.restricted.PyExpr; import com.google.template.soy.pysrc.restricted.PyExprUtils; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Unit tests for GenPyExprsVisitor. * */ @RunWith(JUnit4.class) public final class GenPyExprsVisitorTest { @Test public void testRawText() { assertThatSoyExpr("I'm feeling lucky!") .compilesTo(new PyExpr("'I\\'m feeling lucky!'", Integer.MAX_VALUE)); } @Test public void testCss() { assertThatSoyExpr("{css('primary')}") .compilesTo( new PyExpr("sanitize.escape_html(runtime.get_css_name('primary'))", Integer.MAX_VALUE)); assertThatSoyExpr("{@param foo:?}\n{css($foo, 'bar')}") .compilesTo( new PyExpr( "sanitize.escape_html(runtime.get_css_name(data.get('foo'), 'bar'))", Integer.MAX_VALUE)); } @Test public void testXid() { assertThatSoyExpr("{xid('primary')}") .compilesTo( new PyExpr("sanitize.escape_html(runtime.get_xid_name('primary'))", Integer.MAX_VALUE)); } @Test public void testIf() { String soyNodeCode = "{@param boo:?}\n" + "{@param goo:?}\n" + "{if $boo}\n" + " Blah\n" + "{elseif not $goo}\n" + " Bleh\n" + "{else}\n" + " Bluh\n" + "{/if}\n"; String expectedPyExprText = "('Blah') if (data.get('boo')) else (('Bleh') if (not data.get('goo')) else ('Bluh'))"; assertThatSoyExpr(soyNodeCode) .compilesTo( new PyExpr( expectedPyExprText, PyExprUtils.pyPrecedenceForOperator(Operator.CONDITIONAL))); } @Test public void testIf_noelse() { String soyNodeCode = "{@param boo:?}\n" + "{@param goo:?}\n" + "{@param woo:?}\n" + "{if $boo}\n" + " Blah\n" + "{elseif not $goo}\n" + " Bleh\n" + "{elseif $woo}\n" + " Bluh\n" + "{/if}\n"; String expectedPyExprText = "('Blah') if (data.get('boo')) else " + "(('Bleh') if (not data.get('goo')) else (('Bluh') if (data.get('woo')) else ('')))"; assertThatSoyExpr(soyNodeCode) .compilesTo( new PyExpr( expectedPyExprText, PyExprUtils.pyPrecedenceForOperator(Operator.CONDITIONAL))); } @Test public void testIf_nested() { String soyNodeCode = "{@param boo:?}\n" + "{@param goo:?}\n" + "{if $boo}\n" + " {if $goo}\n" + " Blah\n" + " {/if}\n" + "{else}\n" + " Bleh\n" + "{/if}\n"; String expectedPyExprText = "(('Blah') if (data.get('goo')) else ('')) if (data.get('boo')) else ('Bleh')"; assertThatSoyExpr(soyNodeCode) .compilesTo( new PyExpr( expectedPyExprText, PyExprUtils.pyPrecedenceForOperator(Operator.CONDITIONAL))); } @Test public void testIf_double_nested() { String soyNodeCode = "{@param boo:?}\n" + "{@param foo:?}\n" + "{if $boo}\n" + " {if $foo}\n" + " bf\n" + " {else}\n" + " b\n" + " {/if}\n" + "{else}\n" + " {if $foo}\n" + " f\n" + " {else}\n" + " \n" + " {/if}\n" + "{/if}\n"; String expectedPyExprText = "(('bf') if (data.get('foo')) else ('b'))" + " if (data.get('boo')) else " + "(('f') if (data.get('foo')) else (''))"; assertThatSoyExpr(soyNodeCode) .compilesTo( new PyExpr( expectedPyExprText, PyExprUtils.pyPrecedenceForOperator(Operator.CONDITIONAL))); } @Test public void testSimpleMsgFallbackGroupNodeWithOneNode() { String soyCode = "{msg meaning=\"verb\" desc=\"Used as a verb.\"}\n" + " Archive\n" + "{/msg}\n"; String expectedPyCode = "translator_impl.render_literal(" + "translator_impl.prepare_literal(" + "###, " + "'Archive'), True)"; assertThatSoyExpr(soyCode).compilesTo(new PyExpr(expectedPyCode, Integer.MAX_VALUE)); } @Test public void testMsgFallbackGroupNodeWithTwoNodes() { String soyCode = "{msg meaning=\"verb\" desc=\"Used as a verb.\"}\n" + " archive\n" + "{fallbackmsg desc=\"\"}\n" + " ARCHIVE\n" + "{/msg}\n"; String expectedPyCode = "(translator_impl.render_literal(" + "translator_impl.prepare_literal(" + "###, " + "'archive'), True)) " + "if (translator_impl.is_msg_available(###) or " + "not translator_impl.is_msg_available(###)) " + "else (translator_impl.render_literal(" + "translator_impl.prepare_literal(###, 'ARCHIVE'), True))"; assertThatSoyExpr(soyCode) .compilesTo( new PyExpr(expectedPyCode, PyExprUtils.pyPrecedenceForOperator(Operator.CONDITIONAL))); } @Test public void testMsgOnlyLiteral() { String soyCode = "{msg meaning=\"verb\" desc=\"The word 'Archive' used as a verb.\"}" + "Archive" + "{/msg}\n"; String expectedPyCode = "translator_impl.render_literal(" + "translator_impl.prepare_literal(" + "###, " + "'Archive'), True)"; assertThatSoyExpr(soyCode).compilesTo(new PyExpr(expectedPyCode, Integer.MAX_VALUE)); } @Test public void testMsgOnlyLiteralWithBraces() { // Should escape '{' and '}' in format string. // @see https://docs.python.org/2/library/string.html#formatstrings String soyCode = "{msg meaning=\"verb\" desc=\"The word 'Archive' used as a verb.\"}" + "{lb}Archive{rb}" + "{/msg}\n"; String expectedPyCode = "translator_impl.render_literal(" + "translator_impl.prepare_literal(" + "###, " + "'{{Archive}}'), True)"; assertThatSoyExpr(soyCode).compilesTo(new PyExpr(expectedPyCode, Integer.MAX_VALUE)); } @Test public void testMsgOnlyLiteralWithApostrophe() { // Should escape '\'' in format string. String soyCode = "{msg meaning=\"verb\" desc=\"The word 'Archive' used as a verb.\"}" + "Archive's" + "{/msg}\n"; String expectedPyCode = "translator_impl.render_literal(" + "translator_impl.prepare_literal(" + "###, " + "'Archive\\'s'), True)"; assertThatSoyExpr(soyCode).compilesTo(new PyExpr(expectedPyCode, Integer.MAX_VALUE)); } @Test public void testMsgSimpleSoyExpression() { String soyCode = "{@param username:?}\n" + "{msg desc=\"var placeholder\"}" + "Hello {$username}" + "{/msg}\n"; String expectedPyCode = "translator_impl.render(" + "translator_impl.prepare(" + "###, " + "'Hello {USERNAME}', " + "('USERNAME',)), " + "{'USERNAME': str(sanitize.escape_html(data.get('username')))}, True)"; assertThatSoyExpr(soyCode).compilesTo(new PyExpr(expectedPyCode, Integer.MAX_VALUE)); } @Test public void testMsgMultipleSoyExpressions() { String soyCode = "{@param greet:?}\n" + "{@param username:?}\n" + "{msg desc=\"var placeholder\"}" + "{$greet} {$username}" + "{/msg}\n"; String expectedPyCode = "translator_impl.render(" + "translator_impl.prepare(" + "###, " + "'{GREET} {USERNAME}', " + "('GREET', 'USERNAME')), " + "{" + "'GREET': str(sanitize.escape_html(data.get('greet'))), " + "'USERNAME': str(sanitize.escape_html(data.get('username')))" + "}, True)"; assertThatSoyExpr(soyCode).compilesTo(new PyExpr(expectedPyCode, Integer.MAX_VALUE)); } @Test public void testMsgMultipleSoyExpressionsWithBraces() { String soyCode = "{@param username:?}\n" + "{@param greet:?}\n" + "{msg desc=\"var placeholder\"}" + "{$greet} {lb}{$username}{rb}" + "{/msg}\n"; String expectedPyCode = "translator_impl.render(" + "translator_impl.prepare(" + "###, " + "'{GREET} {{{USERNAME}}}', " + "('GREET', 'USERNAME')), " + "{" + "'GREET': str(sanitize.escape_html(data.get('greet'))), " + "'USERNAME': str(sanitize.escape_html(data.get('username')))" + "}, True)"; assertThatSoyExpr(soyCode).compilesTo(new PyExpr(expectedPyCode, Integer.MAX_VALUE)); } @Test public void testMsgNamespacedSoyExpression() { String soyCode = "{@param foo:?}\n" + "{msg desc=\"placeholder with namespace\"}" + "Hello {$foo.bar}" + "{/msg}\n"; String expectedPyCode = "translator_impl.render(" + "translator_impl.prepare(" + "###, " + "'Hello {BAR}', " + "('BAR',)), " + "{'BAR': str(sanitize.escape_html(data.get('foo').get('bar')))}, True)"; assertThatSoyExpr(soyCode).compilesTo(new PyExpr(expectedPyCode, Integer.MAX_VALUE)); } @Test public void testMsgWithArithmeticExpression() { String soyCode = "{@param username:?}\n" + "{msg desc=\"var placeholder\"}" + "Hello {$username + 1}" + "{/msg}\n"; String expectedPyCode = "translator_impl.render(" + "translator_impl.prepare(" + "###, " + "'Hello {XXX}', " + "('XXX',)), " + "{'XXX': str(sanitize.escape_html(runtime.type_safe_add(data.get('username'), 1)))}, " + "True)"; assertThatSoyExpr(soyCode).compilesTo(new PyExpr(expectedPyCode, Integer.MAX_VALUE)); } @Test public void testMsgWithHtmlNode() { // msg with HTML tags and raw texts String soyCode = "{@param url:?}\n" + "{msg desc=\"with link\"}" + "Please click <a href='{$url}'>here</a>." + "{/msg}"; String expectedPyCode = "translator_impl.render(" + "translator_impl.prepare(" + "###, " + "'Please click {START_LINK}here{END_LINK}.', " + "('START_LINK', 'END_LINK')), " + "{" + "'START_LINK': ''.join(['<a href=\\'',str(sanitize.escape_html_attribute(" + "sanitize.filter_normalize_uri(data.get('url')))),'\\'>']), " + "'END_LINK': '</a>'" + "}, True)"; assertThatSoyExpr(soyCode).compilesTo(new PyExpr(expectedPyCode, Integer.MAX_VALUE)); } @Test public void testMsgWithPlural() { String soyCode = "{@param numDrafts:?}\n" + "{msg desc=\"simple plural\"}" + "{plural $numDrafts}" + "{case 0}No drafts" + "{case 1}1 draft" + "{default}{$numDrafts} drafts" + "{/plural}" + "{/msg}"; String expectedPyCode = "translator_impl.render_plural(" + "translator_impl.prepare_plural(" + "###, " + "{" + "'=0': 'No drafts', " + "'=1': '1 draft', " + "'other': '{NUM_DRAFTS_2} drafts'" + "}, " + "('NUM_DRAFTS_1', 'NUM_DRAFTS_2')), " + "data.get('numDrafts'), " + "{" + "'NUM_DRAFTS_1': data.get('numDrafts'), " + "'NUM_DRAFTS_2': str(sanitize.escape_html(data.get('numDrafts')))" + "}, True)"; assertThatSoyExpr(soyCode).compilesTo(new PyExpr(expectedPyCode, Integer.MAX_VALUE)); } @Test public void testMsgWithPluralAndOffset() { String soyCode = "{@param numDrafts:?}\n" + "{msg desc=\"offset plural\"}" + "{plural $numDrafts offset=\"2\"}" + "{case 0}No drafts" + "{case 1}1 draft" + "{default}{remainder($numDrafts)} drafts" + "{/plural}" + "{/msg}"; String expectedPyCode = "translator_impl.render_plural(" + "translator_impl.prepare_plural(" + "###, " + "{" + "'=0': 'No drafts', " + "'=1': '1 draft', " + "'other': '{XXX} drafts'" + "}, " + "('NUM_DRAFTS', 'XXX')), " + "data.get('numDrafts'), " + "{" + "'NUM_DRAFTS': data.get('numDrafts'), " + "'XXX': str(sanitize.escape_html(data.get('numDrafts') - 2))" + "}, True)"; assertThatSoyExpr(soyCode).compilesTo(new PyExpr(expectedPyCode, Integer.MAX_VALUE)); } @Test public void testMsgWithSelect() { String soyCode = "{@param userGender:?}\n" + "{@param targetGender:?}\n" + "{msg desc=\"...\"}\n" + " {select $userGender}\n" + " {case 'female'}\n" + " {select $targetGender}\n" + " {case 'female'}Reply to her.\n" + " {case 'male'}Reply to him.\n" + " {default}Reply to them.\n" + " {/select}\n" + " {case 'male'}\n" + " {select $targetGender}\n" + " {case 'female'}Reply to her.\n" + " {case 'male'}Reply to him.\n" + " {default}Reply to them.\n" + " {/select}\n" + " {default}\n" + " {select $targetGender}\n" + " {case 'female'}Reply to her.\n" + " {case 'male'}Reply to him.\n" + " {default}Reply to them.\n" + " {/select}\n" + " {/select}\n" + "{/msg}\n"; String expectedPyCode = "translator_impl.render_icu(" + "translator_impl.prepare_icu(" + "###, " + "'{USER_GENDER,select," + "female{" + "{TARGET_GENDER,select," + "female{Reply to her.}" + "male{Reply to him.}" + "other{Reply to them.}}" + "}" + "male{" + "{TARGET_GENDER,select," + "female{Reply to her.}" + "male{Reply to him.}" + "other{Reply to them.}}" + "}" + "other{" + "{TARGET_GENDER,select," + "female{Reply to her.}" + "male{Reply to him.}" + "other{Reply to them.}}" + "}" + "}', " + "('USER_GENDER', 'TARGET_GENDER'), True), " + "{" + "'USER_GENDER': data.get('userGender'), " + "'TARGET_GENDER': data.get('targetGender')" + "})"; assertThatSoyExpr(soyCode).compilesTo(new PyExpr(expectedPyCode, Integer.MAX_VALUE)); } @Test public void testMsgWithPluralWithGender() { String soyCode = "{@param people:list<?>}\n" + "{msg genders=\"$people[0]?.gender, $people[1]?.gender\" desc=\"plural w offsets\"}\n" + " {plural length($people)}\n" + " {case 1}{$people[0].name} is attending\n" + " {case 2}{$people[0].name} and {$people[1]?.name} are attending\n" + " {case 3}{$people[0].name}, {$people[1]?.name}, and 1 other are attending\n" + " {default}{$people[0].name}, {$people[1]?.name}, and length($people) others\n" + " {/plural}\n" + "{/msg}\n"; String expectedPyCode = "translator_impl.render_icu" + "(translator_impl.prepare_icu(" + "###, " + "'{PEOPLE_0_GENDER,select," + "female{{PEOPLE_1_GENDER,select," + "female{{NUM,plural," + "=1{{NAME_1} is attending}" + "=2{{NAME_1} and {NAME_2} are attending}" + "=3{{NAME_1}, {NAME_2}, and 1 other are attending}" + "other{{NAME_1}, {NAME_2}, and length($people) others}}" + "}" + "male{{NUM,plural," + "=1{{NAME_1} is attending}" + "=2{{NAME_1} and {NAME_2} are attending}" + "=3{{NAME_1}, {NAME_2}, and 1 other are attending}" + "other{{NAME_1}, {NAME_2}, and length($people) others}}" + "}" + "other{{NUM,plural," + "=1{{NAME_1} is attending}" + "=2{{NAME_1} and {NAME_2} are attending}" + "=3{{NAME_1}, {NAME_2}, and 1 other are attending}" + "other{{NAME_1}, {NAME_2}, and length($people) others}}}" + "}" + "}" + "male{{PEOPLE_1_GENDER,select," + "female{{NUM,plural," + "=1{{NAME_1} is attending}" + "=2{{NAME_1} and {NAME_2} are attending}" + "=3{{NAME_1}, {NAME_2}, and 1 other are attending}" + "other{{NAME_1}, {NAME_2}, and length($people) others}}" + "}" + "male{{NUM,plural," + "=1{{NAME_1} is attending}" + "=2{{NAME_1} and {NAME_2} are attending}" + "=3{{NAME_1}, {NAME_2}, and 1 other are attending}" + "other{{NAME_1}, {NAME_2}, and length($people) others}}" + "}" + "other{{NUM,plural," + "=1{{NAME_1} is attending}" + "=2{{NAME_1} and {NAME_2} are attending}" + "=3{{NAME_1}, {NAME_2}, and 1 other are attending}" + "other{{NAME_1}, {NAME_2}, and length($people) others}}}" + "}" + "}" + "other{{PEOPLE_1_GENDER,select," + "female{{NUM,plural," + "=1{{NAME_1} is attending}" + "=2{{NAME_1} and {NAME_2} are attending}" + "=3{{NAME_1}, {NAME_2}, and 1 other are attending}" + "other{{NAME_1}, {NAME_2}, and length($people) others}}" + "}" + "male{{NUM,plural," + "=1{{NAME_1} is attending}" + "=2{{NAME_1} and {NAME_2} are attending}" + "=3{{NAME_1}, {NAME_2}, and 1 other are attending}" + "other{{NAME_1}, {NAME_2}, and length($people) others}}" + "}" + "other{{NUM,plural," + "=1{{NAME_1} is attending}" + "=2{{NAME_1} and {NAME_2} are attending}" + "=3{{NAME_1}, {NAME_2}, and 1 other are attending}" + "other{{NAME_1}, {NAME_2}, and length($people) others}}}" + "}" + "}" + "}', " + "('PEOPLE_0_GENDER', 'PEOPLE_1_GENDER', 'NUM', 'NAME_1', 'NAME_2'), True), " + "{" + "'PEOPLE_0_GENDER': None " + "if runtime.key_safe_data_access(data.get('people'), 0) is None " + "else runtime.key_safe_data_access(data.get('people'), 0).get('gender'), " + "'PEOPLE_1_GENDER': None " + "if runtime.key_safe_data_access(data.get('people'), 1) is None " + "else runtime.key_safe_data_access(data.get('people'), 1).get('gender'), " + "'NUM': len(data.get('people')), " + "'NAME_1': str(sanitize.escape_html(" + "runtime.key_safe_data_access(data.get('people'), 0).get('name'))), " + "'NAME_2': str(sanitize.escape_html(None " + "if runtime.key_safe_data_access(data.get('people'), 1) is None " + "else runtime.key_safe_data_access(data.get('people'), 1).get('name')))" + "}" + ")"; assertThatSoyExpr(soyCode).compilesTo(new PyExpr(expectedPyCode, Integer.MAX_VALUE)); } @Test public void testPrimaryAlternateWithFallbackAlternate() { String soyCode = "{msg meaning=\"verb\" desc=\"Used as a verb.\" alternateId=\"123456\"}\n" + " archive\n" + "{fallbackmsg desc=\"\" alternateId=\"654321\"}\n" + " ARCHIVE\n" + "{/msg}\n"; String expectedPyCode = "(translator_impl.render_literal(translator_impl.prepare_literal(###, 'archive'), True))" + " if (translator_impl.is_msg_available(###) or not" + " translator_impl.is_msg_available(###)) else" + " (translator_impl.render_literal(translator_impl.prepare_literal(###, 'archive')," + " True)) if (translator_impl.is_msg_available(###) or" + " translator_impl.is_msg_available(###) or (not" + " translator_impl.is_msg_available(###) and not" + " translator_impl.is_msg_available(###))) else" + " (translator_impl.render_literal(translator_impl.prepare_literal(###, 'ARCHIVE')," + " True)) if (translator_impl.is_msg_available(###) or not" + " translator_impl.is_msg_available(###)) else" + " (translator_impl.render_literal(translator_impl.prepare_literal(###, 'ARCHIVE')," + " True))"; assertThatSoyExpr(soyCode) .compilesTo( new PyExpr(expectedPyCode, PyExprUtils.pyPrecedenceForOperator(Operator.CONDITIONAL))); } @Test public void testPrimaryAlternateWithFallback() { String soyCode = "{msg meaning=\"verb\" desc=\"Used as a verb.\" alternateId=\"123456\"}\n" + " archive\n" + "{fallbackmsg desc=\"\"}\n" + " ARCHIVE\n" + "{/msg}\n"; String expectedPyCode = "(translator_impl.render_literal(translator_impl.prepare_literal(###, 'archive'), True))" + " if (translator_impl.is_msg_available(###) or not" + " translator_impl.is_msg_available(###)) else" + " (translator_impl.render_literal(translator_impl.prepare_literal(###, 'archive')," + " True)) if (translator_impl.is_msg_available(###) or" + " translator_impl.is_msg_available(###) or not" + " translator_impl.is_msg_available(###)) else" + " translator_impl.render_literal(translator_impl.prepare_literal(###, 'ARCHIVE')," + " True)"; assertThatSoyExpr(soyCode) .compilesTo( new PyExpr(expectedPyCode, PyExprUtils.pyPrecedenceForOperator(Operator.CONDITIONAL))); } @Test public void testPrimaryWithFallbackAlternate() { String soyCode = "{msg meaning=\"verb\" desc=\"Used as a verb.\"}\n" + " archive\n" + "{fallbackmsg desc=\"\" alternateId=\"654321\"}\n" + " ARCHIVE\n" + "{/msg}\n"; String expectedPyCode = "translator_impl.render_literal(translator_impl.prepare_literal(###, 'archive'), True) if" + " (translator_impl.is_msg_available(###) or (not" + " translator_impl.is_msg_available(###) and not" + " translator_impl.is_msg_available(###))) else" + " (translator_impl.render_literal(translator_impl.prepare_literal(###, 'ARCHIVE')," + " True)) if (translator_impl.is_msg_available(###) or not" + " translator_impl.is_msg_available(###)) else" + " (translator_impl.render_literal(translator_impl.prepare_literal(###, 'ARCHIVE')," + " True))"; assertThatSoyExpr(soyCode) .compilesTo( new PyExpr(expectedPyCode, PyExprUtils.pyPrecedenceForOperator(Operator.CONDITIONAL))); } @Test public void testPrimaryWithFallback() { String soyCode = "{msg meaning=\"verb\" desc=\"Used as a verb.\"}\n" + " archive\n" + "{fallbackmsg desc=\"\"}\n" + " ARCHIVE\n" + "{/msg}\n"; String expectedPyCode = "(translator_impl.render_literal(translator_impl.prepare_literal(###, 'archive'), True))" + " if (translator_impl.is_msg_available(###) or not" + " translator_impl.is_msg_available(###)) else" + " (translator_impl.render_literal(translator_impl.prepare_literal(###, 'ARCHIVE')," + " True))"; assertThatSoyExpr(soyCode) .compilesTo( new PyExpr(expectedPyCode, PyExprUtils.pyPrecedenceForOperator(Operator.CONDITIONAL))); } @Test public void testPrimaryAlternate() { String soyCode = "{msg meaning=\"verb\" desc=\"Used as a verb.\" alternateId=\"123456\"}\n" + " archive\n" + "{/msg}\n"; String expectedPyCode = "(translator_impl.render_literal(translator_impl.prepare_literal(###, 'archive'), True))" + " if (translator_impl.is_msg_available(###) or not" + " translator_impl.is_msg_available(###)) else" + " (translator_impl.render_literal(translator_impl.prepare_literal(###, 'archive')," + " True))"; assertThatSoyExpr(soyCode) .compilesTo( new PyExpr(expectedPyCode, PyExprUtils.pyPrecedenceForOperator(Operator.CONDITIONAL))); } @Test public void testPrimary() { String soyCode = "{msg meaning=\"verb\" desc=\"Used as a verb.\"}\n" + " archive\n" + "{/msg}\n"; String expectedPyCode = "translator_impl.render_literal(translator_impl.prepare_literal(###, 'archive'), True)"; assertThatSoyExpr(soyCode) .compilesTo(new PyExpr(expectedPyCode, Integer.MAX_VALUE)); } }
yext/closure-templates
java/tests/com/google/template/soy/pysrc/internal/GenPyExprsVisitorTest.java
Java
apache-2.0
26,248
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.codehaus.groovy.runtime; import groovy.io.FileType; import groovy.io.FileVisitResult; import groovy.io.GroovyPrintWriter; import groovy.lang.Closure; import groovy.lang.MetaClass; import groovy.lang.Writable; import groovy.transform.stc.ClosureParams; import groovy.transform.stc.FromString; import groovy.transform.stc.PickFirstResolver; import groovy.transform.stc.SimpleType; import org.codehaus.groovy.runtime.callsite.BooleanReturningMethodInvoker; import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.Closeable; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Reader; import java.io.Writer; import java.net.URI; import java.nio.charset.Charset; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import static java.nio.file.StandardOpenOption.APPEND; import static java.nio.file.StandardOpenOption.CREATE; import static org.codehaus.groovy.runtime.DefaultGroovyMethods.get; /** * This class defines new groovy methods for Readers, Writers, InputStreams and * OutputStreams which appear on normal JDK classes inside the Groovy environment. * Static methods are used with the first parameter being the destination class, * i.e. <code>public static T eachLine(InputStream self, Closure c)</code> * provides a <code>eachLine(Closure c)</code> method for <code>InputStream</code>. * <p/> * NOTE: While this class contains many 'public' static methods, it is * primarily regarded as an internal class (its internal package name * suggests this also). We value backwards compatibility of these * methods when used within Groovy but value less backwards compatibility * at the Java method call level. I.e. future versions of Groovy may * remove or move a method call in this file but would normally * aim to keep the method available from within Groovy. * * @author <a href="mailto:james@coredevelopers.net">James Strachan</a> * @author Jeremy Rayner * @author Sam Pullara * @author Rod Cope * @author Guillaume Laforge * @author John Wilson * @author Hein Meling * @author Dierk Koenig * @author Pilho Kim * @author Marc Guillemot * @author Russel Winder * @author bing ran * @author Jochen Theodorou * @author Paul King * @author Michael Baehr * @author Joachim Baumann * @author Alex Tkachman * @author Ted Naleid * @author Brad Long * @author Jim Jagielski * @author Rodolfo Velasco * @author jeremi Joslin * @author Hamlet D'Arcy * @author Cedric Champeau * @author Tim Yates * @author Dinko Srkoc * @author Paolo Di Tommaso <paolo.ditommaso@gmail.com> */ public class NioGroovyMethods extends DefaultGroovyMethodsSupport { /** * Provide the standard Groovy <code>size()</code> method for <code>Path</code>. * * @param self a {@code Path} object * @return the file's size (length) * @since 2.3.0 */ public static long size(Path self) throws IOException { return Files.size(self); } /** * Create an object output stream for this path. * * @param self a {@code Path} object * @return an object output stream * @throws java.io.IOException if an IOException occurs. * @since 2.3.0 */ public static ObjectOutputStream newObjectOutputStream(Path self) throws IOException { return new ObjectOutputStream(Files.newOutputStream(self)); } /** * Create a new ObjectOutputStream for this path and then pass it to the * closure. This method ensures the stream is closed after the closure * returns. * * @param self a Path * @param closure a closure * @return the value returned by the closure * @throws java.io.IOException if an IOException occurs. * @see IOGroovyMethods#withStream(java.io.OutputStream, groovy.lang.Closure) * @since 2.3.0 */ public static <T> T withObjectOutputStream(Path self, @ClosureParams(value = SimpleType.class, options = "java.io.ObjectOutputStream") Closure<T> closure) throws IOException { return IOGroovyMethods.withStream(newObjectOutputStream(self), closure); } /** * Create an object input stream for this file. * * @param self a {@code Path} object * @return an object input stream * @throws java.io.IOException if an IOException occurs. * @since 2.3.0 */ public static ObjectInputStream newObjectInputStream(Path self) throws IOException { return new ObjectInputStream(Files.newInputStream(self)); } /** * Create an object input stream for this path using the given class loader. * * @param self a {@code Path} object * @param classLoader the class loader to use when loading the class * @return an object input stream * @throws java.io.IOException if an IOException occurs. * @since 2.3.0 */ public static ObjectInputStream newObjectInputStream(Path self, final ClassLoader classLoader) throws IOException { return IOGroovyMethods.newObjectInputStream(Files.newInputStream(self), classLoader); } /** * Iterates through the given file object by object. * * @param self a {@code Path} object * @param closure a closure * @throws java.io.IOException if an IOException occurs. * @throws ClassNotFoundException if the class is not found. * @see org.codehaus.groovy.runtime.IOGroovyMethods#eachObject(java.io.ObjectInputStream, groovy.lang.Closure) * @since 2.3.0 */ public static void eachObject(Path self, Closure closure) throws IOException, ClassNotFoundException { IOGroovyMethods.eachObject(newObjectInputStream(self), closure); } /** * Create a new ObjectInputStream for this file and pass it to the closure. * This method ensures the stream is closed after the closure returns. * * @param path a Path * @param closure a closure * @return the value returned by the closure * @throws java.io.IOException if an IOException occurs. * @see org.codehaus.groovy.runtime.IOGroovyMethods#withStream(java.io.InputStream, groovy.lang.Closure) * @since 2.3.0 */ public static <T> T withObjectInputStream(Path path, @ClosureParams(value = SimpleType.class, options = "java.io.ObjectInputStream") Closure<T> closure) throws IOException { return IOGroovyMethods.withStream(newObjectInputStream(path), closure); } /** * Create a new ObjectInputStream for this file associated with the given class loader and pass it to the closure. * This method ensures the stream is closed after the closure returns. * * @param self a Path * @param classLoader the class loader to use when loading the class * @param closure a closure * @return the value returned by the closure * @throws java.io.IOException if an IOException occurs. * @see org.codehaus.groovy.runtime.IOGroovyMethods#withStream(java.io.InputStream, groovy.lang.Closure) * @since 2.3.0 */ public static <T> T withObjectInputStream(Path self, ClassLoader classLoader, @ClosureParams(value = SimpleType.class, options = "java.io.ObjectInputStream") Closure<T> closure) throws IOException { return IOGroovyMethods.withStream(newObjectInputStream(self, classLoader), closure); } /** * Iterates through this path line by line. Each line is passed to the * given 1 or 2 arg closure. The file is read using a reader which * is closed before this method returns. * * @param self a Path * @param closure a closure (arg 1 is line, optional arg 2 is line number starting at line 1) * @return the last value returned by the closure * @throws java.io.IOException if an IOException occurs. * @see #eachLine(Path, int, groovy.lang.Closure) * @since 2.3.0 */ public static <T> T eachLine(Path self, @ClosureParams(value = FromString.class, options = {"String", "String,Integer"}) Closure<T> closure) throws IOException { return eachLine(self, 1, closure); } /** * Iterates through this file line by line. Each line is passed to the * given 1 or 2 arg closure. The file is read using a reader which * is closed before this method returns. * * @param self a Path * @param charset opens the file with a specified charset * @param closure a closure (arg 1 is line, optional arg 2 is line number starting at line 1) * @return the last value returned by the closure * @throws java.io.IOException if an IOException occurs. * @see #eachLine(Path, String, int, groovy.lang.Closure) * @since 2.3.0 */ public static <T> T eachLine(Path self, String charset, @ClosureParams(value = FromString.class, options = {"String", "String,Integer"}) Closure<T> closure) throws IOException { return eachLine(self, charset, 1, closure); } /** * Iterates through this file line by line. Each line is passed * to the given 1 or 2 arg closure. The file is read using a reader * which is closed before this method returns. * * @param self a Path * @param firstLine the line number value used for the first line (default is 1, set to 0 to start counting from 0) * @param closure a closure (arg 1 is line, optional arg 2 is line number) * @return the last value returned by the closure * @throws java.io.IOException if an IOException occurs. * @see org.codehaus.groovy.runtime.IOGroovyMethods#eachLine(java.io.Reader, int, groovy.lang.Closure) * @since 2.3.0 */ public static <T> T eachLine(Path self, int firstLine, @ClosureParams(value = FromString.class, options = {"String", "String,Integer"}) Closure<T> closure) throws IOException { return IOGroovyMethods.eachLine(newReader(self), firstLine, closure); } /** * Iterates through this file line by line. Each line is passed * to the given 1 or 2 arg closure. The file is read using a reader * which is closed before this method returns. * * @param self a Path * @param charset opens the file with a specified charset * @param firstLine the line number value used for the first line (default is 1, set to 0 to start counting from 0) * @param closure a closure (arg 1 is line, optional arg 2 is line number) * @return the last value returned by the closure * @throws java.io.IOException if an IOException occurs. * @see org.codehaus.groovy.runtime.IOGroovyMethods#eachLine(java.io.Reader, int, groovy.lang.Closure) * @since 2.3.0 */ public static <T> T eachLine(Path self, String charset, int firstLine, @ClosureParams(value = FromString.class, options = {"String", "String,Integer"}) Closure<T> closure) throws IOException { return IOGroovyMethods.eachLine(newReader(self, charset), firstLine, closure); } /** * Iterates through this file line by line, splitting each line using * the given regex separator. For each line, the given closure is called with * a single parameter being the list of strings computed by splitting the line * around matches of the given regular expression. * Finally the resources used for processing the file are closed. * * @param self a Path * @param regex the delimiting regular expression * @param closure a closure * @return the last value returned by the closure * @throws java.io.IOException if an IOException occurs. * @throws java.util.regex.PatternSyntaxException * if the regular expression's syntax is invalid * @see org.codehaus.groovy.runtime.IOGroovyMethods#splitEachLine(java.io.Reader, String, groovy.lang.Closure) * @since 2.3.0 */ public static <T> T splitEachLine(Path self, String regex, @ClosureParams(value=FromString.class,options={"List<String>","String[]"},conflictResolutionStrategy=PickFirstResolver.class) Closure<T> closure) throws IOException { return IOGroovyMethods.splitEachLine(newReader(self), regex, closure); } /** * Iterates through this file line by line, splitting each line using * the given separator Pattern. For each line, the given closure is called with * a single parameter being the list of strings computed by splitting the line * around matches of the given regular expression Pattern. * Finally the resources used for processing the file are closed. * * @param self a Path * @param pattern the regular expression Pattern for the delimiter * @param closure a closure * @return the last value returned by the closure * @throws java.io.IOException if an IOException occurs. * @see org.codehaus.groovy.runtime.IOGroovyMethods#splitEachLine(java.io.Reader, java.util.regex.Pattern, groovy.lang.Closure) * @since 2.3.0 */ public static <T> T splitEachLine(Path self, Pattern pattern, @ClosureParams(value=FromString.class,options={"List<String>","String[]"},conflictResolutionStrategy=PickFirstResolver.class) Closure<T> closure) throws IOException { return IOGroovyMethods.splitEachLine(newReader(self), pattern, closure); } /** * Iterates through this file line by line, splitting each line using * the given regex separator. For each line, the given closure is called with * a single parameter being the list of strings computed by splitting the line * around matches of the given regular expression. * Finally the resources used for processing the file are closed. * * @param self a Path * @param regex the delimiting regular expression * @param charset opens the file with a specified charset * @param closure a closure * @return the last value returned by the closure * @throws java.io.IOException if an IOException occurs. * @throws java.util.regex.PatternSyntaxException * if the regular expression's syntax is invalid * @see org.codehaus.groovy.runtime.IOGroovyMethods#splitEachLine(java.io.Reader, String, groovy.lang.Closure) * @since 2.3.0 */ public static <T> T splitEachLine(Path self, String regex, String charset, @ClosureParams(value=FromString.class,options={"List<String>","String[]"},conflictResolutionStrategy=PickFirstResolver.class) Closure<T> closure) throws IOException { return IOGroovyMethods.splitEachLine(newReader(self, charset), regex, closure); } /** * Iterates through this file line by line, splitting each line using * the given regex separator Pattern. For each line, the given closure is called with * a single parameter being the list of strings computed by splitting the line * around matches of the given regular expression. * Finally the resources used for processing the file are closed. * * @param self a Path * @param pattern the regular expression Pattern for the delimiter * @param charset opens the file with a specified charset * @param closure a closure * @return the last value returned by the closure * @throws java.io.IOException if an IOException occurs. * @see org.codehaus.groovy.runtime.IOGroovyMethods#splitEachLine(java.io.Reader, java.util.regex.Pattern, groovy.lang.Closure) * @since 2.3.0 */ public static <T> T splitEachLine(Path self, Pattern pattern, String charset, @ClosureParams(value=FromString.class,options={"List<String>","String[]"},conflictResolutionStrategy=PickFirstResolver.class) Closure<T> closure) throws IOException { return IOGroovyMethods.splitEachLine(newReader(self, charset), pattern, closure); } /** * Reads the file into a list of Strings, with one item for each line. * * @param self a Path * @return a List of lines * @throws java.io.IOException if an IOException occurs. * @see org.codehaus.groovy.runtime.IOGroovyMethods#readLines(java.io.Reader) * @since 2.3.0 */ public static List<String> readLines(Path self) throws IOException { return IOGroovyMethods.readLines(newReader(self)); } /** * Reads the file into a list of Strings, with one item for each line. * * @param self a Path * @param charset opens the file with a specified charset * @return a List of lines * @throws java.io.IOException if an IOException occurs. * @see org.codehaus.groovy.runtime.IOGroovyMethods#readLines(java.io.Reader) * @since 2.3.0 */ public static List<String> readLines(Path self, String charset) throws IOException { return IOGroovyMethods.readLines(newReader(self, charset)); } /** * Read the content of the Path using the specified encoding and return it * as a String. * * @param self the file whose content we want to read * @param charset the charset used to read the content of the file * @return a String containing the content of the file * @throws java.io.IOException if an IOException occurs. * @since 2.3.0 */ public static String getText(Path self, String charset) throws IOException { return IOGroovyMethods.getText(newReader(self, charset)); } /** * Read the content of the Path and returns it as a String. * * @param self the file whose content we want to read * @return a String containing the content of the file * @throws java.io.IOException if an IOException occurs. * @since 2.3.0 */ public static String getText(Path self) throws IOException { return IOGroovyMethods.getText(newReader(self)); } /** * Read the content of the Path and returns it as a byte[]. * * @param self the file whose content we want to read * @return a String containing the content of the file * @throws java.io.IOException if an IOException occurs. * @since 2.3.0 */ public static byte[] getBytes(Path self) throws IOException { return IOGroovyMethods.getBytes(Files.newInputStream(self)); } /** * Write the bytes from the byte array to the Path. * * @param self the file to write to * @param bytes the byte[] to write to the file * @throws java.io.IOException if an IOException occurs. * @since 2.3.0 */ public static void setBytes(Path self, byte[] bytes) throws IOException { IOGroovyMethods.setBytes(Files.newOutputStream(self), bytes); } /** * Write the text to the Path without writing a BOM . * * @param self a Path * @param text the text to write to the Path * @throws java.io.IOException if an IOException occurs. * @since 2.3.0 */ public static void write(Path self, String text) throws IOException { write(self, text, false); } /** * Write the text to the Path. If the default charset is * "UTF-16BE" or "UTF-16LE" (or an equivalent alias) and * <code>writeBom</code> is <code>true</code>, the requisite byte order * mark is written to the file before the text. * * @param self a Path * @param text the text to write to the Path * @param writeBom whether to write the BOM * @throws java.io.IOException if an IOException occurs. * @since 2.5.0 */ public static void write(Path self, String text, boolean writeBom) throws IOException { write(self, text, Charset.defaultCharset().name(), writeBom); } /** * Synonym for write(text) allowing file.text = 'foo'. * * @param self a Path * @param text the text to write to the Path * @throws java.io.IOException if an IOException occurs. * @see #write(Path, String) * @since 2.3.0 */ public static void setText(Path self, String text) throws IOException { write(self, text); } /** * Synonym for write(text, charset) allowing: * <pre> * myFile.setText('some text', charset) * </pre> * or with some help from <code>ExpandoMetaClass</code>, you could do something like: * <pre> * myFile.metaClass.setText = { String s -> delegate.setText(s, 'UTF-8') } * myfile.text = 'some text' * </pre> * * @param self A Path * @param charset The charset used when writing to the file * @param text The text to write to the Path * @throws java.io.IOException if an IOException occurs. * @see #write(Path, String, String) * @since 2.3.0 */ public static void setText(Path self, String text, String charset) throws IOException { write(self, text, charset); } /** * Write the text to the Path. * * @param self a Path * @param text the text to write to the Path * @return the original file * @throws java.io.IOException if an IOException occurs. * @since 2.3.0 */ public static Path leftShift(Path self, Object text) throws IOException { append(self, text); return self; } /** * Write bytes to a Path. * * @param self a Path * @param bytes the byte array to append to the end of the Path * @return the original file * @throws java.io.IOException if an IOException occurs. * @since 2.3.0 */ public static Path leftShift(Path self, byte[] bytes) throws IOException { append(self, bytes); return self; } /** * Append binary data to the file. See {@link #append(Path, java.io.InputStream)} * * @param path a Path * @param data an InputStream of data to write to the file * @return the file * @throws java.io.IOException if an IOException occurs. * @since 2.3.0 */ public static Path leftShift(Path path, InputStream data) throws IOException { append(path, data); return path; } /** * Write the text to the Path without writing a BOM, using the specified encoding. * * @param self a Path * @param text the text to write to the Path * @param charset the charset used * @throws java.io.IOException if an IOException occurs. * @since 2.3.0 */ public static void write(Path self, String text, String charset) throws IOException { write(self, text, charset, false); } /** * Write the text to the Path, using the specified encoding. If the given * charset is "UTF-16BE" or "UTF-16LE" (or an equivalent alias) and * <code>writeBom</code> is <code>true</code>, the requisite byte order * mark is written to the file before the text. * * @param self a Path * @param text the text to write to the Path * @param charset the charset used * @param writeBom whether to write a BOM * @throws java.io.IOException if an IOException occurs. * @since 2.5.0 */ public static void write(Path self, String text, String charset, boolean writeBom) throws IOException { Writer writer = null; try { OutputStream out = Files.newOutputStream(self); if (writeBom) { IOGroovyMethods.writeUTF16BomIfRequired(out, charset); } writer = new OutputStreamWriter(out, Charset.forName(charset)); writer.write(text); writer.flush(); Writer temp = writer; writer = null; temp.close(); } finally { closeWithWarning(writer); } } /** * Append the text at the end of the Path without writing a BOM. * * @param self a Path * @param text the text to append at the end of the Path * @throws java.io.IOException if an IOException occurs. * @since 2.3.0 */ public static void append(Path self, Object text) throws IOException { append(self, text, Charset.defaultCharset().name(), false); } /** * Append the text supplied by the Writer at the end of the File without * writing a BOM. * * @param file a Path * @param reader the Reader supplying the text to append at the end of the File * @throws IOException if an IOException occurs. * @since 2.3.0 */ public static void append(Path file, Reader reader) throws IOException { append(file, reader, Charset.defaultCharset().name()); } /** * Append the text supplied by the Writer at the end of the File without writing a BOM. * * @param file a File * @param writer the Writer supplying the text to append at the end of the File * @throws IOException if an IOException occurs. * @since 2.3.0 */ public static void append(Path file, Writer writer) throws IOException { append(file, writer, Charset.defaultCharset().name()); } /** * Append bytes to the end of a Path. It <strong>will not</strong> be * interpreted as text. * * @param self a Path * @param bytes the byte array to append to the end of the Path * @throws java.io.IOException if an IOException occurs. * @since 2.3.0 */ public static void append(Path self, byte[] bytes) throws IOException { OutputStream stream = null; try { stream = Files.newOutputStream(self, CREATE, APPEND); stream.write(bytes, 0, bytes.length); stream.flush(); OutputStream temp = stream; stream = null; temp.close(); } finally { closeWithWarning(stream); } } /** * Append binary data to the file. It <strong>will not</strong> be * interpreted as text. * * @param self a Path * @param stream stream to read data from. * @throws java.io.IOException if an IOException occurs. * @since 2.3.0 */ public static void append(Path self, InputStream stream) throws IOException { OutputStream out = Files.newOutputStream(self, CREATE, APPEND); try { IOGroovyMethods.leftShift(out, stream); } finally { closeWithWarning(out); } } /** * Append the text at the end of the Path. If the default charset is * "UTF-16BE" or "UTF-16LE" (or an equivalent alias) and * <code>writeBom</code> is <code>true</code>, the requisite byte order * mark is written to the file before the text. * * @param self a Path * @param text the text to append at the end of the Path * @param writeBom whether to write the BOM * @throws java.io.IOException if an IOException occurs. * @since 2.5.0 */ public static void append(Path self, Object text, boolean writeBom) throws IOException { append(self, text, Charset.defaultCharset().name(), writeBom); } /** * Append the text at the end of the Path without writing a BOM, using a specified * encoding. * * @param self a Path * @param text the text to append at the end of the Path * @param charset the charset used * @throws java.io.IOException if an IOException occurs. * @since 2.3.0 */ public static void append(Path self, Object text, String charset) throws IOException { append(self, text, charset, false); } /** * Append the text at the end of the Path, using a specified encoding. If * the given charset is "UTF-16BE" or "UTF-16LE" (or an equivalent alias), * <code>writeBom</code> is <code>true</code>, and the file doesn't already * exist, the requisite byte order mark is written to the file before the * text is appended. * * @param self a Path * @param text the text to append at the end of the Path * @param charset the charset used * @param writeBom whether to write the BOM * @throws java.io.IOException if an IOException occurs. * @since 2.5.0 */ public static void append(Path self, Object text, String charset, boolean writeBom) throws IOException { Writer writer = null; try { Charset resolvedCharset = Charset.forName(charset); boolean shouldWriteBom = writeBom && !self.toFile().exists(); OutputStream out = Files.newOutputStream(self, CREATE, APPEND); if (shouldWriteBom) { IOGroovyMethods.writeUTF16BomIfRequired(out, resolvedCharset); } writer = new OutputStreamWriter(out, resolvedCharset); InvokerHelper.write(writer, text); writer.flush(); Writer temp = writer; writer = null; temp.close(); } finally { closeWithWarning(writer); } } /** * Append the text supplied by the Writer at the end of the File, using a specified encoding. * If the given charset is "UTF-16BE" or "UTF-16LE" (or an equivalent alias), * <code>writeBom</code> is <code>true</code>, and the file doesn't already * exist, the requisite byte order mark is written to the file before the * text is appended. * * @param file a File * @param writer the Writer supplying the text to append at the end of the File * @param writeBom whether to write the BOM * @throws IOException if an IOException occurs. * @since 2.5.0 */ public static void append(Path file, Writer writer, boolean writeBom) throws IOException { append(file, writer, Charset.defaultCharset().name(), writeBom); } /** * Append the text supplied by the Writer at the end of the File without writing a BOM, * using a specified encoding. * * @param file a File * @param writer the Writer supplying the text to append at the end of the File * @param charset the charset used * @throws IOException if an IOException occurs. * @since 2.3.0 */ public static void append(Path file, Writer writer, String charset) throws IOException { appendBuffered(file, writer, charset, false); } /** * Append the text supplied by the Writer at the end of the File, using a specified encoding. * If the given charset is "UTF-16BE" or "UTF-16LE" (or an equivalent alias), * <code>writeBom</code> is <code>true</code>, and the file doesn't already * exist, the requisite byte order mark is written to the file before the * text is appended. * * @param file a File * @param writer the Writer supplying the text to append at the end of the File * @param charset the charset used * @param writeBom whether to write the BOM * @throws IOException if an IOException occurs. * @since 2.5.0 */ public static void append(Path file, Writer writer, String charset, boolean writeBom) throws IOException { appendBuffered(file, writer, charset, writeBom); } /** * Append the text supplied by the Reader at the end of the File, using a specified encoding. * If the given charset is "UTF-16BE" or "UTF-16LE" (or an equivalent alias), * <code>writeBom</code> is <code>true</code>, and the file doesn't already * exist, the requisite byte order mark is written to the file before the * text is appended. * * @param file a File * @param reader the Reader supplying the text to append at the end of the File * @param writeBom whether to write the BOM * @throws IOException if an IOException occurs. * @since 2.5.0 */ public static void append(Path file, Reader reader, boolean writeBom) throws IOException { appendBuffered(file, reader, Charset.defaultCharset().name(), writeBom); } /** * Append the text supplied by the Reader at the end of the File without writing * a BOM, using a specified encoding. * * @param file a File * @param reader the Reader supplying the text to append at the end of the File * @param charset the charset used * @throws IOException if an IOException occurs. * @since 2.3.0 */ public static void append(Path file, Reader reader, String charset) throws IOException { append(file, reader, charset, false); } /** * Append the text supplied by the Reader at the end of the File, using a specified encoding. * If the given charset is "UTF-16BE" or "UTF-16LE" (or an equivalent alias), * <code>writeBom</code> is <code>true</code>, and the file doesn't already * exist, the requisite byte order mark is written to the file before the * text is appended. * * @param file a File * @param reader the Reader supplying the text to append at the end of the File * @param charset the charset used * @param writeBom whether to write the BOM * @throws IOException if an IOException occurs. * @since 2.5.0 */ public static void append(Path file, Reader reader, String charset, boolean writeBom) throws IOException { appendBuffered(file, reader, charset, writeBom); } private static void appendBuffered(Path file, Object text, String charset, boolean writeBom) throws IOException { BufferedWriter writer = null; try { boolean shouldWriteBom = writeBom && !file.toFile().exists(); writer = newWriter(file, charset, true); if (shouldWriteBom) { IOGroovyMethods.writeUTF16BomIfRequired(writer, charset); } InvokerHelper.write(writer, text); writer.flush(); Writer temp = writer; writer = null; temp.close(); } finally { closeWithWarning(writer); } } /** * This method is used to throw useful exceptions when the eachFile* and eachDir closure methods * are used incorrectly. * * @param self The directory to check * @throws java.io.FileNotFoundException if the given directory does not exist * @throws IllegalArgumentException if the provided Path object does not represent a directory * @since 2.3.0 */ private static void checkDir(Path self) throws FileNotFoundException, IllegalArgumentException { if (!Files.exists(self)) throw new FileNotFoundException(self.toAbsolutePath().toString()); if (!Files.isDirectory(self)) throw new IllegalArgumentException("The provided Path object is not a directory: " + self.toAbsolutePath()); } /** * Invokes the closure for each 'child' file in this 'parent' folder/directory. * Both regular files and subfolders/subdirectories can be processed depending * on the fileType enum value. * * @param self a Path (that happens to be a folder/directory) * @param fileType if normal files or directories or both should be processed * @param closure the closure to invoke * @throws java.io.FileNotFoundException if the given directory does not exist * @throws IllegalArgumentException if the provided Path object does not represent a directory * @since 2.3.0 */ public static void eachFile(final Path self, final FileType fileType, @ClosureParams(value = SimpleType.class, options = "java.nio.file.Path") final Closure closure) throws IOException { //throws FileNotFoundException, IllegalArgumentException { checkDir(self); // TODO GroovyDoc doesn't parse this file as our java.g doesn't handle this JDK7 syntax try (DirectoryStream<Path> stream = Files.newDirectoryStream(self)) { for (Path path : stream) { if (fileType == FileType.ANY || (fileType != FileType.FILES && Files.isDirectory(path)) || (fileType != FileType.DIRECTORIES && Files.isRegularFile(path))) { closure.call(path); } } } } /** * Invokes the closure for each 'child' file in this 'parent' folder/directory. * Both regular files and subfolders/subdirectories are processed. * * @param self a Path (that happens to be a folder/directory) * @param closure a closure (the parameter is the Path for the 'child' file) * @throws java.io.FileNotFoundException if the given directory does not exist * @throws IllegalArgumentException if the provided Path object does not represent a directory * @see #eachFile(Path, groovy.io.FileType, groovy.lang.Closure) * @since 2.3.0 */ public static void eachFile(final Path self, final Closure closure) throws IOException { // throws FileNotFoundException, IllegalArgumentException { eachFile(self, FileType.ANY, closure); } /** * Invokes the closure for each subdirectory in this directory, * ignoring regular files. * * @param self a Path (that happens to be a folder/directory) * @param closure a closure (the parameter is the Path for the subdirectory file) * @throws java.io.FileNotFoundException if the given directory does not exist * @throws IllegalArgumentException if the provided Path object does not represent a directory * @see #eachFile(Path, groovy.io.FileType, groovy.lang.Closure) * @since 2.3.0 */ public static void eachDir(Path self, @ClosureParams(value = SimpleType.class, options = "java.nio.file.Path") Closure closure) throws IOException { // throws FileNotFoundException, IllegalArgumentException { eachFile(self, FileType.DIRECTORIES, closure); } /** * Processes each descendant file in this directory and any sub-directories. * Processing consists of potentially calling <code>closure</code> passing it the current * file (which may be a normal file or subdirectory) and then if a subdirectory was encountered, * recursively processing the subdirectory. Whether the closure is called is determined by whether * the file was a normal file or subdirectory and the value of fileType. * * @param self a Path (that happens to be a folder/directory) * @param fileType if normal files or directories or both should be processed * @param closure the closure to invoke on each file * @throws java.io.FileNotFoundException if the given directory does not exist * @throws IllegalArgumentException if the provided Path object does not represent a directory * @since 2.3.0 */ public static void eachFileRecurse(final Path self, final FileType fileType, @ClosureParams(value = SimpleType.class, options = "java.nio.file.Path") final Closure closure) throws IOException { // throws FileNotFoundException, IllegalArgumentException { // throws FileNotFoundException, IllegalArgumentException { checkDir(self); try (DirectoryStream<Path> stream = Files.newDirectoryStream(self)) { for (Path path : stream) { if (Files.isDirectory(path)) { if (fileType != FileType.FILES) closure.call(path); eachFileRecurse(path, fileType, closure); } else if (fileType != FileType.DIRECTORIES) { closure.call(path); } } } } /** * Processes each descendant file in this directory and any sub-directories. * Processing consists of potentially calling <code>closure</code> passing it the current * file (which may be a normal file or subdirectory) and then if a subdirectory was encountered, * recursively processing the subdirectory. * * The traversal can be adapted by providing various options in the <code>options</code> Map according * to the following keys:<dl> * <dt>type</dt><dd>A {@link groovy.io.FileType} enum to determine if normal files or directories or both are processed</dd> * <dt>preDir</dt><dd>A {@link groovy.lang.Closure} run before each directory is processed and optionally returning a {@link groovy.io.FileVisitResult} value * which can be used to control subsequent processing.</dd> * <dt>preRoot</dt><dd>A boolean indicating that the 'preDir' closure should be applied at the root level</dd> * <dt>postDir</dt><dd>A {@link groovy.lang.Closure} run after each directory is processed and optionally returning a {@link groovy.io.FileVisitResult} value * which can be used to control subsequent processing.</dd> * <dt>postRoot</dt><dd>A boolean indicating that the 'postDir' closure should be applied at the root level</dd> * <dt>visitRoot</dt><dd>A boolean indicating that the given closure should be applied for the root dir * (not applicable if the 'type' is set to {@link groovy.io.FileType#FILES})</dd> * <dt>maxDepth</dt><dd>The maximum number of directory levels when recursing * (default is -1 which means infinite, set to 0 for no recursion)</dd> * <dt>filter</dt><dd>A filter to perform on traversed files/directories (using the {@link DefaultGroovyMethods#isCase(Object, Object)} method). If set, * only files/dirs which match are candidates for visiting.</dd> * <dt>nameFilter</dt><dd>A filter to perform on the name of traversed files/directories (using the {@link DefaultGroovyMethods#isCase(Object, Object)} method). If set, * only files/dirs which match are candidates for visiting. (Must not be set if 'filter' is set)</dd> * <dt>excludeFilter</dt><dd>A filter to perform on traversed files/directories (using the {@link DefaultGroovyMethods#isCase(Object, Object)} method). * If set, any candidates which match won't be visited.</dd> * <dt>excludeNameFilter</dt><dd>A filter to perform on the names of traversed files/directories (using the {@link DefaultGroovyMethods#isCase(Object, Object)} method). * If set, any candidates which match won't be visited. (Must not be set if 'excludeFilter' is set)</dd> * <dt>sort</dt><dd>A {@link groovy.lang.Closure} which if set causes the files and subdirectories for each directory to be processed in sorted order. * Note that even when processing only files, the order of visited subdirectories will be affected by this parameter.</dd> * </dl> * This example prints out file counts and size aggregates for groovy source files within a directory tree: * <pre> * def totalSize = 0 * def count = 0 * def sortByTypeThenName = { a, b -> * a.isFile() != b.isFile() ? a.isFile() <=> b.isFile() : a.name <=> b.name * } * rootDir.traverse( * type : FILES, * nameFilter : ~/.*\.groovy/, * preDir : { if (it.name == '.svn') return SKIP_SUBTREE }, * postDir : { println "Found $count files in $it.name totalling $totalSize bytes" * totalSize = 0; count = 0 }, * postRoot : true * sort : sortByTypeThenName * ) {it -> totalSize += it.size(); count++ } * </pre> * * @param self a Path (that happens to be a folder/directory) * @param options a Map of options to alter the traversal behavior * @param closure the Closure to invoke on each file/directory and optionally returning a {@link groovy.io.FileVisitResult} value * which can be used to control subsequent processing * @throws java.io.FileNotFoundException if the given directory does not exist * @throws IllegalArgumentException if the provided Path object does not represent a directory or illegal filter combinations are supplied * @see DefaultGroovyMethods#sort(java.util.Collection, groovy.lang.Closure) * @see groovy.io.FileVisitResult * @see groovy.io.FileType * @since 2.3.0 */ public static void traverse(final Path self, final Map<String, Object> options, @ClosureParams(value = SimpleType.class, options = "java.nio.file.Path") final Closure closure) throws IOException { // throws FileNotFoundException, IllegalArgumentException { Number maxDepthNumber = DefaultGroovyMethods.asType(options.remove("maxDepth"), Number.class); int maxDepth = maxDepthNumber == null ? -1 : maxDepthNumber.intValue(); Boolean visitRoot = DefaultGroovyMethods.asType(get(options, "visitRoot", false), Boolean.class); Boolean preRoot = DefaultGroovyMethods.asType(get(options, "preRoot", false), Boolean.class); Boolean postRoot = DefaultGroovyMethods.asType(get(options, "postRoot", false), Boolean.class); final Closure pre = (Closure) options.get("preDir"); final Closure post = (Closure) options.get("postDir"); final FileType type = (FileType) options.get("type"); final Object filter = options.get("filter"); final Object nameFilter = options.get("nameFilter"); final Object excludeFilter = options.get("excludeFilter"); final Object excludeNameFilter = options.get("excludeNameFilter"); Object preResult = null; if (preRoot && pre != null) { preResult = pre.call(self); } if (preResult == FileVisitResult.TERMINATE || preResult == FileVisitResult.SKIP_SUBTREE) return; FileVisitResult terminated = traverse(self, options, closure, maxDepth); if (type != FileType.FILES && visitRoot) { if (closure != null && notFiltered(self, filter, nameFilter, excludeFilter, excludeNameFilter)) { Object closureResult = closure.call(self); if (closureResult == FileVisitResult.TERMINATE) return; } } if (postRoot && post != null && terminated != FileVisitResult.TERMINATE) post.call(self); } private static boolean notFiltered(Path path, Object filter, Object nameFilter, Object excludeFilter, Object excludeNameFilter) { if (filter == null && nameFilter == null && excludeFilter == null && excludeNameFilter == null) return true; if (filter != null && nameFilter != null) throw new IllegalArgumentException("Can't set both 'filter' and 'nameFilter'"); if (excludeFilter != null && excludeNameFilter != null) throw new IllegalArgumentException("Can't set both 'excludeFilter' and 'excludeNameFilter'"); Object filterToUse = null; Object filterParam = null; if (filter != null) { filterToUse = filter; filterParam = path; } else if (nameFilter != null) { filterToUse = nameFilter; filterParam = path.getFileName().toString(); } Object excludeFilterToUse = null; Object excludeParam = null; if (excludeFilter != null) { excludeFilterToUse = excludeFilter; excludeParam = path; } else if (excludeNameFilter != null) { excludeFilterToUse = excludeNameFilter; excludeParam = path.getFileName().toString(); } final MetaClass filterMC = filterToUse == null ? null : InvokerHelper.getMetaClass(filterToUse); final MetaClass excludeMC = excludeFilterToUse == null ? null : InvokerHelper.getMetaClass(excludeFilterToUse); boolean included = filterToUse == null || DefaultTypeTransformation.castToBoolean(filterMC.invokeMethod(filterToUse, "isCase", filterParam)); boolean excluded = excludeFilterToUse != null && DefaultTypeTransformation.castToBoolean(excludeMC.invokeMethod(excludeFilterToUse, "isCase", excludeParam)); return included && !excluded; } /** * Processes each descendant file in this directory and any sub-directories. * Convenience method for {@link #traverse(Path, java.util.Map, groovy.lang.Closure)} when * no options to alter the traversal behavior are required. * * @param self a Path (that happens to be a folder/directory) * @param closure the Closure to invoke on each file/directory and optionally returning a {@link groovy.io.FileVisitResult} value * which can be used to control subsequent processing * @throws java.io.FileNotFoundException if the given directory does not exist * @throws IllegalArgumentException if the provided Path object does not represent a directory * @see #traverse(Path, java.util.Map, groovy.lang.Closure) * @since 2.3.0 */ public static void traverse(final Path self, @ClosureParams(value = SimpleType.class, options = "java.nio.file.Path") final Closure closure) throws IOException { traverse(self, new HashMap<String, Object>(), closure); } /** * Invokes the closure specified with key 'visit' in the options Map * for each descendant file in this directory tree. Convenience method * for {@link #traverse(Path, java.util.Map, groovy.lang.Closure)} allowing the 'visit' closure * to be included in the options Map rather than as a parameter. * * @param self a Path (that happens to be a folder/directory) * @param options a Map of options to alter the traversal behavior * @throws java.io.FileNotFoundException if the given directory does not exist * @throws IllegalArgumentException if the provided Path object does not represent a directory or illegal filter combinations are supplied * @see #traverse(Path, java.util.Map, groovy.lang.Closure) * @since 2.3.0 */ public static void traverse(final Path self, final Map<String, Object> options) throws IOException { final Closure visit = (Closure) options.remove("visit"); traverse(self, options, visit); } private static FileVisitResult traverse(final Path self, final Map<String, Object> options, @ClosureParams(value = SimpleType.class, options = "java.nio.file.Path") final Closure closure, final int maxDepth) throws IOException { checkDir(self); final Closure pre = (Closure) options.get("preDir"); final Closure post = (Closure) options.get("postDir"); final FileType type = (FileType) options.get("type"); final Object filter = options.get("filter"); final Object nameFilter = options.get("nameFilter"); final Object excludeFilter = options.get("excludeFilter"); final Object excludeNameFilter = options.get("excludeNameFilter"); final Closure sort = (Closure) options.get("sort"); try (DirectoryStream<Path> stream = Files.newDirectoryStream(self)) { final Iterator<Path> itr = stream.iterator(); List<Path> files = new LinkedList<Path>(); while (itr.hasNext()) { files.add(itr.next()); } if (sort != null) files = DefaultGroovyMethods.sort(files, sort); for (Path path : files) { if (Files.isDirectory(path)) { if (type != FileType.FILES) { if (closure != null && notFiltered(path, filter, nameFilter, excludeFilter, excludeNameFilter)) { Object closureResult = closure.call(path); if (closureResult == FileVisitResult.SKIP_SIBLINGS) break; if (closureResult == FileVisitResult.TERMINATE) return FileVisitResult.TERMINATE; } } if (maxDepth != 0) { Object preResult = null; if (pre != null) { preResult = pre.call(path); } if (preResult == FileVisitResult.SKIP_SIBLINGS) break; if (preResult == FileVisitResult.TERMINATE) return FileVisitResult.TERMINATE; if (preResult != FileVisitResult.SKIP_SUBTREE) { FileVisitResult terminated = traverse(path, options, closure, maxDepth - 1); if (terminated == FileVisitResult.TERMINATE) return terminated; } Object postResult = null; if (post != null) { postResult = post.call(path); } if (postResult == FileVisitResult.SKIP_SIBLINGS) break; if (postResult == FileVisitResult.TERMINATE) return FileVisitResult.TERMINATE; } } else if (type != FileType.DIRECTORIES) { if (closure != null && notFiltered(path, filter, nameFilter, excludeFilter, excludeNameFilter)) { Object closureResult = closure.call(path); if (closureResult == FileVisitResult.SKIP_SIBLINGS) break; if (closureResult == FileVisitResult.TERMINATE) return FileVisitResult.TERMINATE; } } } return FileVisitResult.CONTINUE; } } /** * Processes each descendant file in this directory and any sub-directories. * Processing consists of calling <code>closure</code> passing it the current * file (which may be a normal file or subdirectory) and then if a subdirectory was encountered, * recursively processing the subdirectory. * * @param self a Path (that happens to be a folder/directory) * @param closure a Closure * @throws java.io.FileNotFoundException if the given directory does not exist * @throws IllegalArgumentException if the provided Path object does not represent a directory * @see #eachFileRecurse(Path, groovy.io.FileType, groovy.lang.Closure) * @since 2.3.0 */ public static void eachFileRecurse(Path self, @ClosureParams(value = SimpleType.class, options = "java.nio.file.Path") Closure closure) throws IOException { // throws FileNotFoundException, IllegalArgumentException { eachFileRecurse(self, FileType.ANY, closure); } /** * Recursively processes each descendant subdirectory in this directory. * Processing consists of calling <code>closure</code> passing it the current * subdirectory and then recursively processing that subdirectory. * Regular files are ignored during traversal. * * @param self a Path (that happens to be a folder/directory) * @param closure a closure * @throws java.io.FileNotFoundException if the given directory does not exist * @throws IllegalArgumentException if the provided Path object does not represent a directory * @see #eachFileRecurse(Path, groovy.io.FileType, groovy.lang.Closure) * @since 2.3.0 */ public static void eachDirRecurse(final Path self, @ClosureParams(value = SimpleType.class, options = "java.nio.file.Path") final Closure closure) throws IOException { //throws FileNotFoundException, IllegalArgumentException { eachFileRecurse(self, FileType.DIRECTORIES, closure); } /** * Invokes the closure for each file whose name (file.name) matches the given nameFilter in the given directory * - calling the {@link org.codehaus.groovy.runtime.DefaultGroovyMethods#isCase(Object, Object)} method to determine if a match occurs. This method can be used * with different kinds of filters like regular expressions, classes, ranges etc. * Both regular files and subdirectories may be candidates for matching depending * on the value of fileType. * <pre> * // collect names of files in baseDir matching supplied regex pattern * import static groovy.io.FileType.* * def names = [] * baseDir.eachFileMatch FILES, ~/foo\d\.txt/, { names << it.name } * assert names == ['foo1.txt', 'foo2.txt'] * * // remove all *.bak files in baseDir * baseDir.eachFileMatch FILES, ~/.*\.bak/, { Path bak -> bak.delete() } * * // print out files > 4K in size from baseDir * baseDir.eachFileMatch FILES, { new Path(baseDir, it).size() > 4096 }, { println "$it.name ${it.size()}" } * </pre> * * @param self a Path (that happens to be a folder/directory) * @param fileType whether normal files or directories or both should be processed * @param nameFilter the filter to perform on the name of the file/directory (using the {@link org.codehaus.groovy.runtime.DefaultGroovyMethods#isCase(Object, Object)} method) * @param closure the closure to invoke * @throws java.io.FileNotFoundException if the given directory does not exist * @throws IllegalArgumentException if the provided Path object does not represent a directory * @since 2.3.0 */ public static void eachFileMatch(final Path self, final FileType fileType, final Object nameFilter, @ClosureParams(value = SimpleType.class, options = "java.nio.file.Path") final Closure closure) throws IOException { // throws FileNotFoundException, IllegalArgumentException { checkDir(self); try (DirectoryStream<Path> stream = Files.newDirectoryStream(self)) { Iterator<Path> itr = stream.iterator(); BooleanReturningMethodInvoker bmi = new BooleanReturningMethodInvoker("isCase"); while (itr.hasNext()) { Path currentPath = itr.next(); if ((fileType != FileType.FILES && Files.isDirectory(currentPath)) || (fileType != FileType.DIRECTORIES && Files.isRegularFile(currentPath))) { if (bmi.invoke(nameFilter, currentPath.getFileName().toString())) closure.call(currentPath); } } } } /** * Invokes the closure for each file whose name (file.name) matches the given nameFilter in the given directory * - calling the {@link org.codehaus.groovy.runtime.DefaultGroovyMethods#isCase(Object, Object)} method to determine if a match occurs. This method can be used * with different kinds of filters like regular expressions, classes, ranges etc. * Both regular files and subdirectories are matched. * * @param self a Path (that happens to be a folder/directory) * @param nameFilter the nameFilter to perform on the name of the file (using the {@link org.codehaus.groovy.runtime.DefaultGroovyMethods#isCase(Object, Object)} method) * @param closure the closure to invoke * @throws java.io.FileNotFoundException if the given directory does not exist * @throws IllegalArgumentException if the provided Path object does not represent a directory * @see #eachFileMatch(Path, groovy.io.FileType, Object, groovy.lang.Closure) * @since 2.3.0 */ public static void eachFileMatch(final Path self, final Object nameFilter, @ClosureParams(value = SimpleType.class, options = "java.nio.file.Path") final Closure closure) throws IOException { // throws FileNotFoundException, IllegalArgumentException { eachFileMatch(self, FileType.ANY, nameFilter, closure); } /** * Invokes the closure for each subdirectory whose name (dir.name) matches the given nameFilter in the given directory * - calling the {@link DefaultGroovyMethods#isCase(java.lang.Object, java.lang.Object)} method to determine if a match occurs. This method can be used * with different kinds of filters like regular expressions, classes, ranges etc. * Only subdirectories are matched; regular files are ignored. * * @param self a Path (that happens to be a folder/directory) * @param nameFilter the nameFilter to perform on the name of the directory (using the {@link org.codehaus.groovy.runtime.DefaultGroovyMethods#isCase(Object, Object)} method) * @param closure the closure to invoke * @throws java.io.FileNotFoundException if the given directory does not exist * @throws IllegalArgumentException if the provided Path object does not represent a directory * @see #eachFileMatch(Path, groovy.io.FileType, Object, groovy.lang.Closure) * @since 2.3.0 */ public static void eachDirMatch(final Path self, final Object nameFilter, @ClosureParams(value = SimpleType.class, options = "java.nio.file.Path") final Closure closure) throws IOException { // throws FileNotFoundException, IllegalArgumentException { eachFileMatch(self, FileType.DIRECTORIES, nameFilter, closure); } /** * Deletes a directory with all contained files and subdirectories. * <p>The method returns * <ul> * <li>true, when deletion was successful</li> * <li>true, when it is called for a non existing directory</li> * <li>false, when it is called for a file which isn't a directory</li> * <li>false, when directory couldn't be deleted</li> * </ul> * </p> * * @param self a Path * @return true if the file doesn't exist or deletion was successful * @since 2.3.0 */ public static boolean deleteDir(final Path self) { if (!Files.exists(self)) return true; if (!Files.isDirectory(self)) return false; // delete contained files try (DirectoryStream<Path> stream = Files.newDirectoryStream(self)) { for (Path path : stream) { if (Files.isDirectory(path)) { if (!deleteDir(path)) { return false; } } else { Files.delete(path); } } // now delete directory itself Files.delete(self); return true; } catch (IOException e) { return false; } } /** * Renames a file. * * @param self a Path * @param newPathName The new pathname for the named file * @return <code>true</code> if and only if the renaming succeeded; * <code>false</code> otherwise * @since 2.3.0 */ public static boolean renameTo(final Path self, String newPathName) { try { Files.move(self, Paths.get(newPathName)); return true; } catch (IOException e) { return false; } } /** * Renames a file. * * @param self a Path * @param newPathName The new target path specified as a URI object * @return <code>true</code> if and only if the renaming succeeded; * <code>false</code> otherwise * @since 2.3.0 */ public static boolean renameTo(final Path self, URI newPathName) { try { Files.move(self, Paths.get(newPathName)); return true; } catch (IOException e) { return false; } } /** * Converts this Path to a {@link groovy.lang.Writable}. * * @param self a Path * @return a Path which wraps the input file and which implements Writable * @since 2.3.0 */ public static Path asWritable(Path self) { return new WritablePath(self); } /** * Converts this Path to a {@link groovy.lang.Writable} or delegates to default * {@link org.codehaus.groovy.runtime.DefaultGroovyMethods#asType(Object, Class)}. * * @param path a Path * @param c the desired class * @return the converted object * @since 2.3.0 */ @SuppressWarnings("unchecked") public static <T> T asType(Path path, Class<T> c) { if (c == Writable.class) { return (T) asWritable(path); } return DefaultGroovyMethods.asType((Object) path, c); } /** * Allows a file to return a Writable implementation that can output itself * to a Writer stream. * * @param self a Path * @param encoding the encoding to be used when reading the file's contents * @return Path which wraps the input file and which implements Writable * @since 2.3.0 */ public static Path asWritable(Path self, String encoding) { return new WritablePath(self, encoding); } /** * Create a buffered reader for this file. * * @param self a Path * @return a BufferedReader * @throws java.io.IOException if an IOException occurs. * @since 2.3.0 */ public static BufferedReader newReader(Path self) throws IOException { return Files.newBufferedReader(self, Charset.defaultCharset()); } /** * Create a buffered reader for this file, using the specified * charset as the encoding. * * @param self a Path * @param charset the charset for this Path * @return a BufferedReader * @throws java.io.FileNotFoundException if the Path was not found * @throws java.io.UnsupportedEncodingException if the encoding specified is not supported * @since 2.3.0 */ public static BufferedReader newReader(Path self, String charset) throws IOException { return Files.newBufferedReader(self, Charset.forName(charset)); } /** * Create a new BufferedReader for this file and then * passes it into the closure, ensuring the reader is closed after the * closure returns. * * @param self a file object * @param closure a closure * @return the value returned by the closure * @throws java.io.IOException if an IOException occurs. * @since 2.3.0 */ public static <T> T withReader(Path self, @ClosureParams(value = SimpleType.class, options = "java.io.Reader") Closure<T> closure) throws IOException { return IOGroovyMethods.withReader(newReader(self), closure); } /** * Create a new BufferedReader for this file using the specified charset and then * passes it into the closure, ensuring the reader is closed after the * closure returns. The writer will use the given charset encoding, * but will not write a BOM. * * @param self a file object * @param charset the charset for this input stream * @param closure a closure * @return the value returned by the closure * @throws java.io.IOException if an IOException occurs. * @since 2.3.0 */ public static <T> T withReader(Path self, String charset, @ClosureParams(value = SimpleType.class, options = "java.io.Reader") Closure<T> closure) throws IOException { return IOGroovyMethods.withReader(newReader(self, charset), closure); } /** * Create a buffered output stream for this file. * * @param self a file object * @return the created OutputStream * @throws java.io.IOException if an IOException occurs. * @since 2.3.0 */ public static BufferedOutputStream newOutputStream(Path self) throws IOException { return new BufferedOutputStream(Files.newOutputStream(self)); } /** * Creates a new data output stream for this file. * * @param self a file object * @return the created DataOutputStream * @throws java.io.IOException if an IOException occurs. * @since 2.3.0 */ public static DataOutputStream newDataOutputStream(Path self) throws IOException { return new DataOutputStream(Files.newOutputStream(self)); } /** * Creates a new OutputStream for this file and passes it into the closure. * This method ensures the stream is closed after the closure returns. * * @param self a Path * @param closure a closure * @return the value returned by the closure * @throws java.io.IOException if an IOException occurs. * @see org.codehaus.groovy.runtime.IOGroovyMethods#withStream(java.io.OutputStream, groovy.lang.Closure) * @since 2.3.0 */ public static Object withOutputStream(Path self, @ClosureParams(value = SimpleType.class, options = "java.io.OutputStream") Closure closure) throws IOException { return IOGroovyMethods.withStream(newOutputStream(self), closure); } /** * Create a new InputStream for this file and passes it into the closure. * This method ensures the stream is closed after the closure returns. * * @param self a Path * @param closure a closure * @return the value returned by the closure * @throws java.io.IOException if an IOException occurs. * @see org.codehaus.groovy.runtime.IOGroovyMethods#withStream(java.io.InputStream, groovy.lang.Closure) * @since 2.3.0 */ public static Object withInputStream(Path self, @ClosureParams(value = SimpleType.class, options = "java.io.InputStream") Closure closure) throws IOException { return IOGroovyMethods.withStream(newInputStream(self), closure); } /** * Create a new DataOutputStream for this file and passes it into the closure. * This method ensures the stream is closed after the closure returns. * * @param self a Path * @param closure a closure * @return the value returned by the closure * @throws java.io.IOException if an IOException occurs. * @see org.codehaus.groovy.runtime.IOGroovyMethods#withStream(java.io.OutputStream, groovy.lang.Closure) * @since 2.3.0 */ public static <T> T withDataOutputStream(Path self, @ClosureParams(value = SimpleType.class, options = "java.io.DataOutputStream") Closure<T> closure) throws IOException { return IOGroovyMethods.withStream(newDataOutputStream(self), closure); } /** * Create a new DataInputStream for this file and passes it into the closure. * This method ensures the stream is closed after the closure returns. * * @param self a Path * @param closure a closure * @return the value returned by the closure * @throws java.io.IOException if an IOException occurs. * @see org.codehaus.groovy.runtime.IOGroovyMethods#withStream(java.io.InputStream, groovy.lang.Closure) * @since 2.3.0 */ public static <T> T withDataInputStream(Path self, @ClosureParams(value = SimpleType.class, options = "java.io.DataInputStream") Closure<T> closure) throws IOException { return IOGroovyMethods.withStream(newDataInputStream(self), closure); } /** * Create a buffered writer for this file. * * @param self a Path * @return a BufferedWriter * @throws java.io.IOException if an IOException occurs. * @since 2.3.0 */ public static BufferedWriter newWriter(Path self) throws IOException { return Files.newBufferedWriter(self, Charset.defaultCharset()); } /** * Creates a buffered writer for this file, optionally appending to the * existing file content. * * @param self a Path * @param append true if data should be appended to the file * @return a BufferedWriter * @throws java.io.IOException if an IOException occurs. * @since 2.3.0 */ public static BufferedWriter newWriter(Path self, boolean append) throws IOException { if (append) { return Files.newBufferedWriter(self, Charset.defaultCharset(), CREATE, APPEND); } return Files.newBufferedWriter(self, Charset.defaultCharset()); } /** * Helper method to create a buffered writer for a file without writing a BOM. * * @param self a Path * @param charset the name of the encoding used to write in this file * @param append true if in append mode * @return a BufferedWriter * @throws java.io.IOException if an IOException occurs. * @since 2.3.0 */ public static BufferedWriter newWriter(Path self, String charset, boolean append) throws IOException { return newWriter(self, charset, append, false); } /** * Helper method to create a buffered writer for a file. If the given * charset is "UTF-16BE" or "UTF-16LE" (or an equivalent alias), the * requisite byte order mark is written to the stream before the writer * is returned. * * @param self a Path * @param charset the name of the encoding used to write in this file * @param append true if in append mode * @param writeBom whether to write a BOM * @return a BufferedWriter * @throws java.io.IOException if an IOException occurs. * @since 2.5.0 */ public static BufferedWriter newWriter(Path self, String charset, boolean append, boolean writeBom) throws IOException { boolean shouldWriteBom = writeBom && !self.toFile().exists(); if (append) { BufferedWriter writer = Files.newBufferedWriter(self, Charset.forName(charset), CREATE, APPEND); if (shouldWriteBom) { IOGroovyMethods.writeUTF16BomIfRequired(writer, charset); } return writer; } else { OutputStream out = Files.newOutputStream(self); if (shouldWriteBom) { IOGroovyMethods.writeUTF16BomIfRequired(out, charset); } return new BufferedWriter(new OutputStreamWriter(out, Charset.forName(charset))); } } /** * Creates a buffered writer for this file without writing a BOM, writing data using the given * encoding. * * @param self a Path * @param charset the name of the encoding used to write in this file * @return a BufferedWriter * @throws java.io.IOException if an IOException occurs. * @since 2.3.0 */ public static BufferedWriter newWriter(Path self, String charset) throws IOException { return newWriter(self, charset, false); } /** * Creates a new BufferedWriter for this file, passes it to the closure, and * ensures the stream is flushed and closed after the closure returns. * The writer will not write a BOM. * * @param self a Path * @param closure a closure * @return the value returned by the closure * @throws java.io.IOException if an IOException occurs. * @since 2.3.0 */ public static <T> T withWriter(Path self, @ClosureParams(value = SimpleType.class, options = "java.io.Writer") Closure<T> closure) throws IOException { return withWriter(self, Charset.defaultCharset().name(), closure); } /** * Creates a new BufferedWriter for this file, passes it to the closure, and * ensures the stream is flushed and closed after the closure returns. * The writer will use the given charset encoding, but will not write a BOM. * * @param self a Path * @param charset the charset used * @param closure a closure * @return the value returned by the closure * @throws java.io.IOException if an IOException occurs. * @since 2.3.0 */ public static <T> T withWriter(Path self, String charset, @ClosureParams(value = SimpleType.class, options = "java.io.Writer") Closure<T> closure) throws IOException { return withWriter(self, charset, false, closure); } /** * Creates a new BufferedWriter for this file, passes it to the closure, and * ensures the stream is flushed and closed after the closure returns. * The writer will use the given charset encoding. If the given charset is * "UTF-16BE" or "UTF-16LE" (or an equivalent alias), <code>writeBom</code> * is <code>true</code>, and the file doesn't already exist, the requisite * byte order mark is written to the stream when the writer is created. * * @param self a Path * @param charset the charset used * @param writeBom whether to write the BOM * @param closure a closure * @return the value returned by the closure * @throws java.io.IOException if an IOException occurs. * @since 2.5.0 */ public static <T> T withWriter(Path self, String charset, boolean writeBom, @ClosureParams(value = SimpleType.class, options = "java.io.Writer") Closure<T> closure) throws IOException { return IOGroovyMethods.withWriter(newWriter(self, charset, false, writeBom), closure); } /** * Create a new BufferedWriter which will append to this * file. The writer is passed to the closure and will be closed before * this method returns. The writer will use the given charset encoding, * but will not write a BOM. * * @param self a Path * @param charset the charset used * @param closure a closure * @return the value returned by the closure * @throws java.io.IOException if an IOException occurs. * @since 2.3.0 */ public static <T> T withWriterAppend(Path self, String charset, @ClosureParams(value = SimpleType.class, options = "java.io.Writer") Closure<T> closure) throws IOException { return withWriterAppend(self, charset, false, closure); } /** * Create a new BufferedWriter which will append to this * file. The writer is passed to the closure and will be closed before * this method returns. The writer will use the given charset encoding. * If the given charset is "UTF-16BE" or "UTF-16LE" (or an equivalent alias), * <code>writeBom</code> is <code>true</code>, and the file doesn't already exist, * the requisite byte order mark is written to the stream when the writer is created. * * @param self a Path * @param charset the charset used * @param writeBom whether to write the BOM * @param closure a closure * @return the value returned by the closure * @throws java.io.IOException if an IOException occurs. * @since 2.5.0 */ public static <T> T withWriterAppend(Path self, String charset, boolean writeBom, @ClosureParams(value = SimpleType.class, options = "java.io.Writer") Closure<T> closure) throws IOException { return IOGroovyMethods.withWriter(newWriter(self, charset, true, writeBom), closure); } /** * Create a new BufferedWriter for this file in append mode. The writer * is passed to the closure and is closed after the closure returns. * The writer will not write a BOM. * * @param self a Path * @param closure a closure * @return the value returned by the closure * @throws java.io.IOException if an IOException occurs. * @since 2.3.0 */ public static <T> T withWriterAppend(Path self, @ClosureParams(value = SimpleType.class, options = "java.io.Writer") Closure<T> closure) throws IOException { return withWriterAppend(self, Charset.defaultCharset().name(), closure); } /** * Create a new PrintWriter for this file. * * @param self a Path * @return the created PrintWriter * @throws java.io.IOException if an IOException occurs. * @since 2.3.0 */ public static PrintWriter newPrintWriter(Path self) throws IOException { return new GroovyPrintWriter(newWriter(self)); } /** * Create a new PrintWriter for this file, using specified * charset. * * @param self a Path * @param charset the charset * @return a PrintWriter * @throws java.io.IOException if an IOException occurs. * @since 2.3.0 */ public static PrintWriter newPrintWriter(Path self, String charset) throws IOException { return new GroovyPrintWriter(newWriter(self, charset)); } /** * Create a new PrintWriter for this file which is then * passed it into the given closure. This method ensures its the writer * is closed after the closure returns. * * @param self a Path * @param closure the closure to invoke with the PrintWriter * @return the value returned by the closure * @throws java.io.IOException if an IOException occurs. * @since 2.3.0 */ public static <T> T withPrintWriter(Path self, @ClosureParams(value = SimpleType.class, options = "java.io.PrintWriter") Closure<T> closure) throws IOException { return IOGroovyMethods.withWriter(newPrintWriter(self), closure); } /** * Create a new PrintWriter with a specified charset for * this file. The writer is passed to the closure, and will be closed * before this method returns. * * @param self a Path * @param charset the charset * @param closure the closure to invoke with the PrintWriter * @return the value returned by the closure * @throws java.io.IOException if an IOException occurs. * @since 2.3.0 */ public static <T> T withPrintWriter(Path self, String charset, @ClosureParams(value = SimpleType.class, options = "java.io.PrintWriter") Closure<T> closure) throws IOException { return IOGroovyMethods.withWriter(newPrintWriter(self, charset), closure); } /** * Creates a buffered input stream for this file. * * @param self a Path * @return a BufferedInputStream of the file * @throws java.io.FileNotFoundException if the file is not found. * @since 2.3.0 */ public static BufferedInputStream newInputStream(Path self) throws IOException { // throws FileNotFoundException { return new BufferedInputStream(Files.newInputStream(self)); } /** * Create a data input stream for this file * * @param self a Path * @return a DataInputStream of the file * @throws java.io.FileNotFoundException if the file is not found. * @since 2.3.0 */ public static DataInputStream newDataInputStream(Path self) throws IOException { // throws FileNotFoundException { return new DataInputStream(Files.newInputStream(self)); } /** * Traverse through each byte of this Path * * @param self a Path * @param closure a closure * @throws java.io.IOException if an IOException occurs. * @see org.codehaus.groovy.runtime.IOGroovyMethods#eachByte(java.io.InputStream, groovy.lang.Closure) * @since 2.3.0 */ public static void eachByte(Path self, @ClosureParams(value = SimpleType.class, options = "byte") Closure closure) throws IOException { BufferedInputStream is = newInputStream(self); IOGroovyMethods.eachByte(is, closure); } /** * Traverse through the bytes of this Path, bufferLen bytes at a time. * * @param self a Path * @param bufferLen the length of the buffer to use. * @param closure a 2 parameter closure which is passed the byte[] and a number of bytes successfully read. * @throws java.io.IOException if an IOException occurs. * @see org.codehaus.groovy.runtime.IOGroovyMethods#eachByte(java.io.InputStream, int, groovy.lang.Closure) * @since 2.3.0 */ public static void eachByte(Path self, int bufferLen, @ClosureParams(value = FromString.class, options = "byte[],Integer") Closure closure) throws IOException { BufferedInputStream is = newInputStream(self); IOGroovyMethods.eachByte(is, bufferLen, closure); } /** * Filters the lines of a Path and creates a Writable in return to * stream the filtered lines. * * @param self a Path * @param closure a closure which returns a boolean indicating to filter * the line or not * @return a Writable closure * @throws java.io.IOException if <code>self</code> is not readable * @see org.codehaus.groovy.runtime.IOGroovyMethods#filterLine(java.io.Reader, groovy.lang.Closure) * @since 2.3.0 */ public static Writable filterLine(Path self, @ClosureParams(value = SimpleType.class, options = "java.lang.String") Closure closure) throws IOException { return IOGroovyMethods.filterLine(newReader(self), closure); } /** * Filters the lines of a Path and creates a Writable in return to * stream the filtered lines. * * @param self a Path * @param charset opens the file with a specified charset * @param closure a closure which returns a boolean indicating to filter * the line or not * @return a Writable closure * @throws java.io.IOException if an IOException occurs * @see org.codehaus.groovy.runtime.IOGroovyMethods#filterLine(java.io.Reader, groovy.lang.Closure) * @since 2.3.0 */ public static Writable filterLine(Path self, String charset, @ClosureParams(value = SimpleType.class, options = "java.lang.String") Closure closure) throws IOException { return IOGroovyMethods.filterLine(newReader(self, charset), closure); } /** * Filter the lines from this Path, and write them to the given writer based * on the given closure predicate. * * @param self a Path * @param writer a writer destination to write filtered lines to * @param closure a closure which takes each line as a parameter and returns * <code>true</code> if the line should be written to this writer. * @throws java.io.IOException if <code>self</code> is not readable * @see org.codehaus.groovy.runtime.IOGroovyMethods#filterLine(java.io.Reader, java.io.Writer, groovy.lang.Closure) * @since 2.3.0 */ public static void filterLine(Path self, Writer writer, @ClosureParams(value = SimpleType.class, options = "java.lang.String") Closure closure) throws IOException { IOGroovyMethods.filterLine(newReader(self), writer, closure); } /** * Filter the lines from this Path, and write them to the given writer based * on the given closure predicate. * * @param self a Path * @param writer a writer destination to write filtered lines to * @param charset opens the file with a specified charset * @param closure a closure which takes each line as a parameter and returns * <code>true</code> if the line should be written to this writer. * @throws java.io.IOException if an IO error occurs * @see org.codehaus.groovy.runtime.IOGroovyMethods#filterLine(java.io.Reader, java.io.Writer, groovy.lang.Closure) * @since 2.3.0 */ public static void filterLine(Path self, Writer writer, String charset, @ClosureParams(value = SimpleType.class, options = "java.lang.String") Closure closure) throws IOException { IOGroovyMethods.filterLine(newReader(self, charset), writer, closure); } /** * Reads the content of the file into a byte array. * * @param self a Path * @return a byte array with the contents of the file. * @throws java.io.IOException if an IOException occurs. * @since 2.3.0 */ public static byte[] readBytes(Path self) throws IOException { return Files.readAllBytes(self); } /** * #deprecated use the variant in IOGroovyMethods * @see org.codehaus.groovy.runtime.IOGroovyMethods#withCloseable(java.io.Closeable, groovy.lang.Closure) * @since 2.3.0 */ @Deprecated public static <T> T withCloseable(Closeable self, @ClosureParams(value = SimpleType.class, options = "java.io.Closeable") Closure<T> action) throws IOException { return IOGroovyMethods.withCloseable(self, action); } }
avafanasiev/groovy
subprojects/groovy-nio/src/main/java/org/codehaus/groovy/runtime/NioGroovyMethods.java
Java
apache-2.0
88,390
/** * Copyright (C) 2010-2013 Alibaba Group Holding Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.rocketmq.common.filter; import java.net.URL; import com.alibaba.rocketmq.common.protocol.heartbeat.SubscriptionData; /** * @author shijia.wxr<vintage.wang@gmail.com> * @since 2013-6-15 */ public class FilterAPI { public static String simpleClassName(final String className) { String simple = className; int index = className.lastIndexOf("."); if (index >= 0) { simple = className.substring(index + 1); } return simple; } public static URL classFile(final String className) { final String javaSource = simpleClassName(className) + ".java"; URL url = FilterAPI.class.getClassLoader().getResource(javaSource); return url; } public static boolean isFilterClassMode(final String subString) { try { if (subString.contains(".")) { Class<?> loadClass = FilterAPI.class.getClassLoader().loadClass(subString); Class<?>[] interfaces = loadClass.getInterfaces(); for (int i = 0; i < interfaces.length; i++) { if (interfaces[i].getCanonicalName().equals(MessageFilter.class.getCanonicalName())) { return true; } } } } catch (ClassNotFoundException e) { } return false; } public static SubscriptionData buildSubscriptionData(final String consumerGroup, String topic, String subString) throws Exception { SubscriptionData subscriptionData = new SubscriptionData(); subscriptionData.setTopic(topic); subscriptionData.setSubString(subString); if (null == subString || subString.equals(SubscriptionData.SUB_ALL) || subString.length() == 0) { subscriptionData.setSubString(SubscriptionData.SUB_ALL); } // eg: com.taobao.abc.FilterClassName else if (isFilterClassMode(subString)) { // if (null == classFile(subString)) { // throw new // Exception(String.format("The Filter Java Class Source[%s] not exist in class path", // subString + ".java")); // } subscriptionData.setClassFilterMode(true); } else { String[] tags = subString.split("\\|\\|"); if (tags != null && tags.length > 0) { for (String tag : tags) { if (tag.length() > 0) { String trimString = tag.trim(); if (trimString.length() > 0) { subscriptionData.getTagsSet().add(trimString); subscriptionData.getCodeSet().add(trimString.hashCode()); } } } } else { throw new Exception("subString split error"); } } return subscriptionData; } }
diwayou/rocketmq-all-trans
rocketmq-common/src/main/java/com/alibaba/rocketmq/common/filter/FilterAPI.java
Java
apache-2.0
3,598
# # Copyright (c) SAS Institute 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. # import logging import traceback from restlib import response from mint import logerror from mint import mint_error from mint.rest.api import models from mint.rest.modellib import converter log = logging.getLogger(__name__) class ErrorCallback(object): def __init__(self, controller): self.controller = controller def processException(self, request, excClass, exception, tb): message = '%s: %s' % (excClass.__name__, exception) if hasattr(exception, 'status'): status = exception.status else: status = 500 self.logError(request, excClass, exception, tb, doEmail=True) # Only send the traceback information if it's an unintentional # exception (i.e. a 500) if status == 500: tbString = 'Traceback:\n' + ''.join(traceback.format_tb(tb)) text = [message + '\n', tbString] else: tbString = None text = [message + '\n'] isFlash = 'HTTP_X_FLASH_VERSION' in request.headers or 'X-Wrap-Response-Codes' in request.headers if not getattr(request, 'contentType', None): request.contentType = 'text/xml' request.responseType = 'xml' if isFlash or request.contentType != 'text/plain': # for text/plain, just print out the traceback in the easiest to read # format. code = status if isFlash: # flash ignores all data sent with a non-200 error status = 200 error = models.Fault(code=code, message=message, traceback=tbString) text = converter.toText(request.responseType, error, self.controller, request) return response.Response(text, content_type=request.contentType, status=status) def logError(self, request, e_type, e_value, e_tb, doEmail=True): info = { 'uri' : request.thisUrl, 'path' : request.path, 'method' : request.method, 'headers_in' : request.headers, 'request_params' : request.GET, 'post_params' : request.POST, 'remote' : request.remote, } try: logerror.logErrorAndEmail(self.controller.cfg, e_type, e_value, e_tb, 'API call', info, doEmail=doEmail) except mint_error.MailError, err: log.error("Error sending mail: %s", str(err))
sassoftware/mint
mint/rest/middleware/error.py
Python
apache-2.0
3,212
/** * <copyright> * * Copyright (c) 2010 SAP AG. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Reiner Hille-Doering (SAP AG) - initial API and implementation and/or initial documentation * * </copyright> */ package org.eclipse.securebpmn2.provider; import java.util.Collection; import java.util.List; import org.eclipse.emf.common.notify.AdapterFactory; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.edit.provider.ComposeableAdapterFactory; import org.eclipse.emf.edit.provider.IEditingDomainItemProvider; import org.eclipse.emf.edit.provider.IItemLabelProvider; import org.eclipse.emf.edit.provider.IItemPropertyDescriptor; import org.eclipse.emf.edit.provider.IItemPropertySource; import org.eclipse.emf.edit.provider.IStructuredItemContentProvider; import org.eclipse.emf.edit.provider.ITreeItemContentProvider; import org.eclipse.securebpmn2.CompositeItemAwareElementAction; import org.eclipse.securebpmn2.Securebpmn2Package; /** * This is the item provider adapter for a {@link org.eclipse.securebpmn2.CompositeItemAwareElementAction} object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public class CompositeItemAwareElementActionItemProvider extends ItemAwareElementActionItemProvider implements IEditingDomainItemProvider, IStructuredItemContentProvider, ITreeItemContentProvider, IItemLabelProvider, IItemPropertySource { /** * This constructs an instance from a factory and a notifier. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public CompositeItemAwareElementActionItemProvider( AdapterFactory adapterFactory) { super(adapterFactory); } /** * This returns the property descriptors for the adapted class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) { if (itemPropertyDescriptors == null) { super.getPropertyDescriptors(object); addItemAwareElementActionsPropertyDescriptor(object); } return itemPropertyDescriptors; } /** * This adds a property descriptor for the Item Aware Element Actions feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void addItemAwareElementActionsPropertyDescriptor(Object object) { itemPropertyDescriptors .add(createItemPropertyDescriptor( ((ComposeableAdapterFactory) adapterFactory) .getRootAdapterFactory(), getResourceLocator(), getString("_UI_CompositeItemAwareElementAction_itemAwareElementActions_feature"), getString( "_UI_PropertyDescriptor_description", "_UI_CompositeItemAwareElementAction_itemAwareElementActions_feature", "_UI_CompositeItemAwareElementAction_type"), Securebpmn2Package.Literals.COMPOSITE_ITEM_AWARE_ELEMENT_ACTION__ITEM_AWARE_ELEMENT_ACTIONS, true, false, true, null, null, null)); } /** * This returns CompositeItemAwareElementAction.gif. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object getImage(Object object) { return overlayImage( object, getResourceLocator().getImage( "full/obj16/CompositeItemAwareElementAction")); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected boolean shouldComposeCreationImage() { return true; } /** * This returns the label text for the adapted class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String getText(Object object) { String label = ((CompositeItemAwareElementAction) object).getId(); return label == null || label.length() == 0 ? getString("_UI_CompositeItemAwareElementAction_type") : getString("_UI_CompositeItemAwareElementAction_type") + " " + label; } /** * This handles model notifications by calling {@link #updateChildren} to update any cached * children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void notifyChanged(Notification notification) { updateChildren(notification); super.notifyChanged(notification); } /** * This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children * that can be created under this object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected void collectNewChildDescriptors( Collection<Object> newChildDescriptors, Object object) { super.collectNewChildDescriptors(newChildDescriptors, object); } }
adbrucker/SecureBPMN
designer/src/org.activiti.designer.model.edit/src/org/eclipse/securebpmn2/provider/CompositeItemAwareElementActionItemProvider.java
Java
apache-2.0
4,878
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("ReplaysOfTheVoid")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Partouf")] [assembly: AssemblyProduct("replaysofthevoid")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.1.0.0")] [assembly: AssemblyFileVersion("1.1.0.0")]
partouf/ReplaysOfTheVoid
Properties/AssemblyInfo.cs
C#
apache-2.0
2,248
/* * Copyright 2016 Davide Maestroni * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.dm.jrt.android.v4.core; import android.content.Context; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.LoaderManager; import com.github.dm.jrt.core.util.ConstantConditions; import com.github.dm.jrt.core.util.Reflection; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.lang.ref.WeakReference; /** * Class representing an Android Loader context (like Activities or Fragments). * <p> * No strong reference to the wrapped objects will be retained by this class implementations. * <p> * Created by davide-maestroni on 07/08/2015. */ public abstract class LoaderContextCompat { /** * Avoid explicit instantiation. */ private LoaderContextCompat() { } /** * Returns a context wrapping the specified Fragment. * * @param fragment the Fragment instance. * @return the Loader context. */ @NotNull public static LoaderContextCompat loaderFrom(@NotNull final Fragment fragment) { return new FragmentContextCompat(fragment, fragment.getActivity()); } /** * Returns a context wrapping the specified Fragment, with the specified instance as the Loader * Context. * <br> * In order to prevent undesired leaks, the class of the specified Context must be static. * * @param fragment the Fragment instance. * @param context the Context used to get the application one. * @return the Loader context. * @throws java.lang.IllegalArgumentException if the class of the specified Context has not a * static scope. */ @NotNull public static LoaderContextCompat loaderFrom(@NotNull final Fragment fragment, @NotNull final Context context) { return new FragmentContextCompat(fragment, context); } /** * Returns a context wrapping the specified Activity. * * @param activity the Activity instance. * @return the Loader context. */ @NotNull public static LoaderContextCompat loaderFrom(@NotNull final FragmentActivity activity) { return new ActivityContextCompat(activity, activity); } /** * Returns a context wrapping the specified Activity, with the specified instance as the Loader * Context. * <br> * In order to prevent undesired leaks, the class of the specified Context must be static. * * @param activity the Activity instance. * @param context the Context used to get the application one. * @return the Loader context. * @throws java.lang.IllegalArgumentException if the class of the specified Context has not a * static scope. */ @NotNull public static LoaderContextCompat loaderFrom(@NotNull final FragmentActivity activity, @NotNull final Context context) { return new ActivityContextCompat(activity, context); } /** * Returns the wrapped component. * * @return the component or null. */ @Nullable public abstract Object getComponent(); /** * Returns the Loader Context. * * @return the Context or null. */ @Nullable public abstract Context getLoaderContext(); /** * Returns the Loader manager of the specific component. * * @return the Loader manager or null. */ @Nullable public abstract LoaderManager getLoaderManager(); /** * Loader context wrapping an Activity. */ private static class ActivityContextCompat extends LoaderContextCompat { private final WeakReference<FragmentActivity> mActivity; private final WeakReference<Context> mContext; /** * Constructor. * * @param activity the wrapped Activity. * @param context the wrapped Context. * @throws java.lang.IllegalArgumentException if the class of the specified Context has not * a static scope. */ private ActivityContextCompat(@NotNull final FragmentActivity activity, @NotNull final Context context) { mActivity = new WeakReference<FragmentActivity>(ConstantConditions.notNull("Activity", activity)); final Class<? extends Context> contextClass = context.getClass(); if (!Reflection.hasStaticScope(contextClass)) { throw new IllegalArgumentException( "the Context class must have a static scope: " + contextClass.getName()); } mContext = new WeakReference<Context>(context); } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof ActivityContextCompat)) { return false; } final ActivityContextCompat that = (ActivityContextCompat) o; final FragmentActivity activity = mActivity.get(); if ((activity == null) || !activity.equals(that.mActivity.get())) { return false; } final Context context = mContext.get(); return (context != null) && context.equals(that.mContext.get()); } @Nullable @Override public Object getComponent() { return mActivity.get(); } @Override public int hashCode() { final FragmentActivity activity = mActivity.get(); int result = (activity != null) ? activity.hashCode() : 0; final Context context = mContext.get(); result = 31 * result + (context != null ? context.hashCode() : 0); return result; } @Nullable @Override public Context getLoaderContext() { return mContext.get(); } @Nullable @Override public LoaderManager getLoaderManager() { final FragmentActivity activity = mActivity.get(); return (activity != null) ? activity.getSupportLoaderManager() : null; } } /** * Loader context wrapping a Fragment. */ private static class FragmentContextCompat extends LoaderContextCompat { private final WeakReference<Context> mContext; private final WeakReference<Fragment> mFragment; /** * Constructor. * * @param fragment the wrapped Fragment. * @param context the wrapped Context. * @throws java.lang.IllegalArgumentException if the class of the specified Context has not * a static scope. */ private FragmentContextCompat(@NotNull final Fragment fragment, @NotNull final Context context) { mFragment = new WeakReference<Fragment>(ConstantConditions.notNull("Fragment", fragment)); final Class<? extends Context> contextClass = context.getClass(); if (!Reflection.hasStaticScope(contextClass)) { throw new IllegalArgumentException( "the Context class must have a static scope: " + contextClass.getName()); } mContext = new WeakReference<Context>(context); } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof FragmentContextCompat)) { return false; } final FragmentContextCompat that = (FragmentContextCompat) o; final Fragment fragment = mFragment.get(); if ((fragment == null) || !fragment.equals(that.mFragment.get())) { return false; } final Context context = mContext.get(); return (context != null) && context.equals(that.mContext.get()); } @Override public int hashCode() { final Fragment fragment = mFragment.get(); int result = (fragment != null) ? fragment.hashCode() : 0; final Context context = mContext.get(); result = 31 * result + (context != null ? context.hashCode() : 0); return result; } @Nullable @Override public Context getLoaderContext() { return mContext.get(); } @Nullable @Override public LoaderManager getLoaderManager() { final Fragment fragment = mFragment.get(); return (fragment != null) ? fragment.getLoaderManager() : null; } @Nullable @Override public Object getComponent() { return mFragment.get(); } } }
davide-maestroni/jroutine
android-core/src/main/java/com/github/dm/jrt/android/v4/core/LoaderContextCompat.java
Java
apache-2.0
8,667
#include "objinterface.h" ObjLoader::ObjLoader() { pobj = new LibObjFile; } ObjLoader::ObjLoader(const string& objfile) { pobj = new LibObjFile; obj_load(objfile); } ObjLoader::~ObjLoader() { if (pobj) delete pobj; } ObjBool ObjLoader::obj_load(const string& objfile) { if (!pobj) return LIBOBJ_FALSE; return pobj->obj_file_load(objfile); }
priseup/obj_load
objinterface.cpp
C++
apache-2.0
384
exports.AppWindow = function(){ var self = Titanium.UI.createWindow({ backgroundColor: "#888888", title: "My List" }); return self; };
TShelton41/ListAndPicker
Resources/ui/AppWindow.js
JavaScript
apache-2.0
149
<!-- ~ Copyright (c) 2010-2013 Evolveum ~ ~ 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. --> <!DOCTYPE html> <html xmlns:wicket="http://wicket.apache.org"> <wicket:panel> <div class="row"> <div class="col-md-12"> <div wicket:id="basicSystemConfiguration" /> </div> </div> </wicket:panel> </html>
bshp/midPoint
gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/page/admin/configuration/component/SystemConfigPanel.html
HTML
apache-2.0
886
{% extends "base.html" %} {% load wagtailcore_tags %} {% load wagtailcore_tags snippets %} {% load wagtailimages_tags %} {% load static %} {% block body_class %}newsindexpage{% endblock %} {% block content %} <div class="banner-container"> <div class="banner-element"> Help support open science today. <a href="/donate/" class="btn banner-button" onClick="ga('send', 'event', 'marketing', 'click', 'COS Donate Banner')">Donate Now</a> </div> </div> <div class="page-container"> <!-- BEGIN CONTAINER --> <div class="container"> <h1><strong>{{ page.title }}</strong></h1> <p class="lead">{{ page.statement }}</p> <div class="loading-msg text-center"> <div id="loader"></div> <p>Loading news</p> </div> <div class="margin-bottom-20 grid" style="display: none"> {% include page_template %} </div> </div> </div> <div class="footer"> <div class="container"> <div class="row"> {# Have to specify content or it will just display the name of the footer #} {{ page.footer.content }} </div> </div> </div> {% endblock %} {% block extra_js %} <!-- END CORE PLUGINS --> <script type="text/javascript"> $(window).load(function() { $('.loading-msg').hide(); var grid = $('.grid').show().masonry({ itemSelector: '.service-box-v1', columnWidth: '.service-box-v1', percentPosition: true, }); grid.masonry(); $('.service-box-v1').removeClass('hidden-box'); grid.on('layoutComplete', function() { $('.service-box-v1').removeClass('hidden-box'); }); }); var paginate_scroll_margin = 400; if ($(window).width() < 500) { paginate_scroll_margin = 1000; } else if ($(window).width() < 900) { paginate_scroll_margin = 800; } $.endlessPaginate({ paginateOnScroll: true, paginateOnScrollMargin: paginate_scroll_margin, onCompleted: function(){ var masonry = $('.grid').data('masonry'); setTimeout(function() { masonry.reloadItems(); masonry.layout(); }, 200); } }) </script> {% endblock %} {% block extra_css %} <style> .endless_container{ display: none; position: absolute; bottom: 0; } .hidden-box { opacity: 0; } </style> {% endblock %}
baylee-d/cos.io
common/templates/common/news_index_page.html
HTML
apache-2.0
2,796
using UnityEngine; using System.Collections; using UnityEngine.UI; using UnityEngine.EventSystems; using UnityEngine.Events; public class UIHighlightHex : MonoBehaviour { /*Notes 1. Change the Hex to be under the parent of the Original Hex Material 2. When the mouse enters the Original Hex Matieral, change that material to whatever the hex is 3. When the mouse exit, change the material back to the original 4. When the hex is clicked, destory and move five to the position of the destoryed object, and move six to the fifth position 5. Randomize a new hex for the sixth position */ /* Script to show which hex is highlighted. The script should also be abled to be clicked on and show kind of hex is clicked */ //Public Variables public RawImage img; public Texture textureNoTexture; public Texture texture_dark; public Texture texture_wind; public Texture texture_fire; public Texture texture_ice; public Texture texture_light; public Texture texture_lightning; public void ShowingTexture() { foreach (Transform child in img.transform) { var rawImage = child.GetComponent<RawImage>(); if (rawImage.tag == "DarkHex") { Dark(); } if (rawImage.tag == "LightHex") { Light(); } if (rawImage.tag == "WindHex") { Wind(); } if (rawImage.tag == "FireHex") { Fire(); } if (rawImage.tag == "IceHex") { Ice(); } if (rawImage.tag == "LightningHex") { Lightning(); } } } public void Dark() { img.GetComponent<RawImage>().texture = texture_dark; } public void Light() { img.GetComponent<RawImage>().texture = texture_light; } public void Wind() { img.GetComponent<RawImage>().texture = texture_wind; } public void Fire() { img.GetComponent<RawImage>().texture = texture_fire; } public void Ice() { img.GetComponent<RawImage>().texture = texture_ice; } public void Lightning() { img.GetComponent<RawImage>().texture = texture_lightning; } public void NoShow() { img.GetComponent<RawImage>().texture = textureNoTexture; } }
rockpower/Project-Hexing_Tournament
Assets/Scripts/UI Scripts/UIHighlightHex.cs
C#
apache-2.0
2,524
/* * Copyright 2013 Future Systems * * 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.araqne.logdb.query.aggregator; import java.util.List; import org.araqne.logdb.Row; import org.araqne.logdb.query.command.NumberUtil; import org.araqne.logdb.query.expr.Expression; public class Sum extends AbstractAggregationFunction { protected Number sum = 0L; private Expression expr; public Sum(List<Expression> exprs) { super(exprs); this.expr = exprs.get(0); } @Override public String getName() { return "sum"; } @Override public void apply(Row map) { Object obj = expr.eval(map); if (obj == null || !(obj instanceof Number)) return; sum = NumberUtil.add(sum, obj); } @Override public Object eval() { return sum; } @Override public void merge(AggregationFunction func) { Sum other = (Sum) func; this.sum = NumberUtil.add(sum, other.sum); } @Override public void deserialize(Object[] values) { this.sum = (Number) values[0]; } @Override public Object[] serialize() { Object[] l = new Object[1]; l[0] = sum; return l; } @Override public void clean() { sum = null; } @Override public AggregationFunction clone() { Sum s = new Sum(this.exprs); s.sum = this.sum; return s; } @Override public String toString() { return "sum(" + expr + ")"; } @Override public boolean canBeDistributed() { return true; } @Override public AggregationFunction mapper(List<Expression> exprs) { return new Sum(exprs); } @Override public AggregationFunction reducer(List<Expression> exprs) { return new Sum(exprs); } }
araqne/logdb
araqne-logdb/src/main/java/org/araqne/logdb/query/aggregator/Sum.java
Java
apache-2.0
2,107
<!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_25) on Tue Apr 28 18:49:25 EEST 2015 --> <title>com.ohtu.wearable.wearabledataservice.list</title> <meta name="date" content="2015-04-28"> <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="com.ohtu.wearable.wearabledataservice.list"; } } 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 class="navBarCell1Rev">Package</li> <li>Class</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><a href="../../../../../com/ohtu/wearable/wearabledataservice/fragments/package-summary.html">Prev&nbsp;Package</a></li> <li><a href="../../../../../com/ohtu/wearable/wearabledataservice/sensors/package-summary.html">Next&nbsp;Package</a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?com/ohtu/wearable/wearabledataservice/list/package-summary.html" target="_top">Frames</a></li> <li><a href="package-summary.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"> <h1 title="Package" class="title">Package&nbsp;com.ohtu.wearable.wearabledataservice.list</h1> </div> <div class="contentContainer"> <ul class="blockList"> <li class="blockList"> <table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Class Summary table, listing classes, and an explanation"> <caption><span>Class Summary</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Class</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="../../../../../com/ohtu/wearable/wearabledataservice/list/WearableListAdapter.html" title="class in com.ohtu.wearable.wearabledataservice.list">WearableListAdapter</a></td> <td class="colLast"> <div class="block">Adapter class to pass selections of the sensors to the view.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../../../com/ohtu/wearable/wearabledataservice/list/WearableListAdapter.ItemViewHolder.html" title="class in com.ohtu.wearable.wearabledataservice.list">WearableListAdapter.ItemViewHolder</a></td> <td class="colLast"> <div class="block">A wrapper for the items displayed in the listView.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><a href="../../../../../com/ohtu/wearable/wearabledataservice/list/WearableListItemLayout.html" title="class in com.ohtu.wearable.wearabledataservice.list">WearableListItemLayout</a></td> <td class="colLast"> <div class="block">Contains layout for the List Items.</div> </td> </tr> </tbody> </table> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li class="navBarCell1Rev">Package</li> <li>Class</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><a href="../../../../../com/ohtu/wearable/wearabledataservice/fragments/package-summary.html">Prev&nbsp;Package</a></li> <li><a href="../../../../../com/ohtu/wearable/wearabledataservice/sensors/package-summary.html">Next&nbsp;Package</a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?com/ohtu/wearable/wearabledataservice/list/package-summary.html" target="_top">Frames</a></li> <li><a href="package-summary.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>
OhtuWearable/WearableDataServer
javadoc/com/ohtu/wearable/wearabledataservice/list/package-summary.html
HTML
apache-2.0
5,849
package io.quarkus.security.test.cdi.app; public class TestException extends RuntimeException { }
quarkusio/quarkus
extensions/security/deployment/src/test/java/io/quarkus/security/test/cdi/app/TestException.java
Java
apache-2.0
99
package com.cisco.axl.api._8; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for ListDirectedCallParkRes complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="ListDirectedCallParkRes"> * &lt;complexContent> * &lt;extension base="{http://www.cisco.com/AXL/API/8.0}APIResponse"> * &lt;sequence> * &lt;element name="return"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="directedCallPark" type="{http://www.cisco.com/AXL/API/8.0}LDirectedCallPark" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ListDirectedCallParkRes", propOrder = { "_return" }) public class ListDirectedCallParkRes extends APIResponse { @XmlElement(name = "return", required = true) protected ListDirectedCallParkRes.Return _return; /** * Gets the value of the return property. * * @return * possible object is * {@link ListDirectedCallParkRes.Return } * */ public ListDirectedCallParkRes.Return getReturn() { return _return; } /** * Sets the value of the return property. * * @param value * allowed object is * {@link ListDirectedCallParkRes.Return } * */ public void setReturn(ListDirectedCallParkRes.Return value) { this._return = value; } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="directedCallPark" type="{http://www.cisco.com/AXL/API/8.0}LDirectedCallPark" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "directedCallPark" }) public static class Return { protected List<LDirectedCallPark> directedCallPark; /** * Gets the value of the directedCallPark property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the directedCallPark property. * * <p> * For example, to add a new item, do as follows: * <pre> * getDirectedCallPark().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link LDirectedCallPark } * * */ public List<LDirectedCallPark> getDirectedCallPark() { if (directedCallPark == null) { directedCallPark = new ArrayList<LDirectedCallPark>(); } return this.directedCallPark; } } }
ox-it/cucm-http-api
src/main/java/com/cisco/axl/api/_8/ListDirectedCallParkRes.java
Java
apache-2.0
3,958
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_151) on Tue Feb 06 09:38:18 MST 2018 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Uses of Class org.wildfly.swarm.config.management.security_realm.PlugInAuthentication.PlugInAuthenticationResources (BOM: * : All 2017.10.2 API)</title> <meta name="date" content="2018-02-06"> <link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.wildfly.swarm.config.management.security_realm.PlugInAuthentication.PlugInAuthenticationResources (BOM: * : All 2017.10.2 API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../org/wildfly/swarm/config/management/security_realm/PlugInAuthentication.PlugInAuthenticationResources.html" title="class in org.wildfly.swarm.config.management.security_realm">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../../../../overview-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage">WildFly Swarm API, 2017.10.2</div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?org/wildfly/swarm/config/management/security_realm/class-use/PlugInAuthentication.PlugInAuthenticationResources.html" target="_top">Frames</a></li> <li><a href="PlugInAuthentication.PlugInAuthenticationResources.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.wildfly.swarm.config.management.security_realm.PlugInAuthentication.PlugInAuthenticationResources" class="title">Uses of Class<br>org.wildfly.swarm.config.management.security_realm.PlugInAuthentication.PlugInAuthenticationResources</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../../../org/wildfly/swarm/config/management/security_realm/PlugInAuthentication.PlugInAuthenticationResources.html" title="class in org.wildfly.swarm.config.management.security_realm">PlugInAuthentication.PlugInAuthenticationResources</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#org.wildfly.swarm.config.management.security_realm">org.wildfly.swarm.config.management.security_realm</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="org.wildfly.swarm.config.management.security_realm"> <!-- --> </a> <h3>Uses of <a href="../../../../../../../org/wildfly/swarm/config/management/security_realm/PlugInAuthentication.PlugInAuthenticationResources.html" title="class in org.wildfly.swarm.config.management.security_realm">PlugInAuthentication.PlugInAuthenticationResources</a> in <a href="../../../../../../../org/wildfly/swarm/config/management/security_realm/package-summary.html">org.wildfly.swarm.config.management.security_realm</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../../../org/wildfly/swarm/config/management/security_realm/package-summary.html">org.wildfly.swarm.config.management.security_realm</a> that return <a href="../../../../../../../org/wildfly/swarm/config/management/security_realm/PlugInAuthentication.PlugInAuthenticationResources.html" title="class in org.wildfly.swarm.config.management.security_realm">PlugInAuthentication.PlugInAuthenticationResources</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../../../org/wildfly/swarm/config/management/security_realm/PlugInAuthentication.PlugInAuthenticationResources.html" title="class in org.wildfly.swarm.config.management.security_realm">PlugInAuthentication.PlugInAuthenticationResources</a></code></td> <td class="colLast"><span class="typeNameLabel">PlugInAuthentication.</span><code><span class="memberNameLink"><a href="../../../../../../../org/wildfly/swarm/config/management/security_realm/PlugInAuthentication.html#subresources--">subresources</a></span>()</code>&nbsp;</td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../org/wildfly/swarm/config/management/security_realm/PlugInAuthentication.PlugInAuthenticationResources.html" title="class in org.wildfly.swarm.config.management.security_realm">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../../../../overview-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage">WildFly Swarm API, 2017.10.2</div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?org/wildfly/swarm/config/management/security_realm/class-use/PlugInAuthentication.PlugInAuthenticationResources.html" target="_top">Frames</a></li> <li><a href="PlugInAuthentication.PlugInAuthenticationResources.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2018 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p> </body> </html>
wildfly-swarm/wildfly-swarm-javadocs
2017.10.2/apidocs/org/wildfly/swarm/config/management/security_realm/class-use/PlugInAuthentication.PlugInAuthenticationResources.html
HTML
apache-2.0
8,345
import React from 'react'; import { Bluetooth as Memory, Storage, Trigger } from 'grommet-icons'; import { Box, Card, CardBody, CardFooter, Chart, Grid, Grommet, Text, } from 'grommet'; const theme = { themeMode: 'dark', global: { font: { family: `-apple-system, BlinkMacSystemFont, "Segoe UI"`, }, }, card: { hover: { container: { elevation: 'large', }, }, container: { elevation: 'medium', extend: `transition: all 0.2s ease-in-out;`, }, footer: { pad: { horizontal: 'medium', vertical: 'small' }, background: '#00000008', }, }, }; const gradient = [ { value: 28, color: 'status-ok' }, { value: 50, color: 'status-warning' }, { value: 80, color: 'status-critical' }, ]; const data = [ { icon: <Memory size="large" />, title: 'Memory (EEC)', subTitle: '8 GB @ 400Hz', message: 'Past 24hrs', type: 'bar', }, { icon: <Storage size="large" />, title: 'Storage', subTitle: 'Sub-system and Devices', message: '36.8 TB available', type: 'line', }, { icon: <Trigger size="large" />, title: 'Power (Watts)', subTitle: '720 Watt Service', message: 'Past 12hrs', type: 'point', }, ]; const ChartPreview = ({ type }) => ( <Box> <Chart type={type} id={type} dash={type === 'line'} round thickness="xsmall" bounds={[ [0, 6], [0, 100], ]} values={[ { value: [6, 100], label: 'one hundred' }, { value: [5, 70], label: 'seventy' }, { value: [4, 40], label: 'sixty' }, { value: [3, 80], label: 'eighty' }, { value: [2, 25], label: 'forty' }, { value: [1, 50], label: 'thirty' }, { value: [0, 25], label: 'sixty' }, ]} aria-label="chart card" color={gradient} size={{ height: 'xsmall' }} /> </Box> ); const Identifier = ({ children, title, subTitle, size, ...rest }) => ( <Box gap="small" align="center" direction="row" pad="small" {...rest}> {children} <Box> <Text size={size} weight="bold"> {title} </Text> <Text size={size}>{subTitle}</Text> </Box> </Box> ); export const Clickable = () => ( <Grommet theme={theme} full> <Box pad="large" height="100%"> <Grid gap="medium" columns={{ count: 'fit', size: 'small' }}> {data.map((value) => ( <Card key={value.title} onClick={() => { // eslint-disable-next-line no-alert alert('Card was Clicked!'); }} > <CardBody pad="small"> <Identifier title={value.title} subTitle={value.subTitle} size="small" > {value.icon} </Identifier> <ChartPreview type={value.type} /> </CardBody> <CardFooter pad={{ horizontal: 'medium', vertical: 'small' }}> <Text size="xsmall">{value.message}</Text> </CardFooter> </Card> ))} </Grid> </Box> </Grommet> ); Clickable.parameters = { chromatic: { disable: true }, }; export default { title: 'Layout/Card/Clickable', };
HewlettPackard/grommet
src/js/components/Card/stories/Clickable.js
JavaScript
apache-2.0
3,312
require File.expand_path('../boot', __FILE__) require 'rails/all' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module Sinthanai class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. # config.time_zone = 'Central Time (US & Canada)' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de end end
RameshRM/sinthanai
config/application.rb
Ruby
apache-2.0
980
/* * Copyright 2014-2019 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.logs.model; import java.io.Serializable; import javax.annotation.Generated; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DeleteResourcePolicy" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DeleteResourcePolicyResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof DeleteResourcePolicyResult == false) return false; DeleteResourcePolicyResult other = (DeleteResourcePolicyResult) obj; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; return hashCode; } @Override public DeleteResourcePolicyResult clone() { try { return (DeleteResourcePolicyResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
jentfoo/aws-sdk-java
aws-java-sdk-logs/src/main/java/com/amazonaws/services/logs/model/DeleteResourcePolicyResult.java
Java
apache-2.0
2,365
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* namespace Audiotica.Core.Windows.Messages { public class SkipNextMessage { } }
zumicts/Audiotica
Windows/Audiotica.Core.Windows/Messages/SkipNextMessage.cs
C#
apache-2.0
530
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cassandra.db.commitlog; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.EOFException; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.util.*; import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicInteger; import com.google.common.base.Predicate; import com.google.common.collect.HashMultimap; import com.google.common.collect.Iterables; import com.google.common.collect.Multimap; import com.google.common.collect.Ordering; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.tjake.ICRC32; import org.apache.cassandra.concurrent.Stage; import org.apache.cassandra.concurrent.StageManager; import org.apache.cassandra.config.CFMetaData; import org.apache.cassandra.config.Schema; import org.apache.cassandra.db.*; import org.apache.cassandra.exceptions.ConfigurationException; import org.apache.cassandra.io.compress.CompressionParameters; import org.apache.cassandra.io.compress.ICompressor; import org.apache.cassandra.io.util.ByteBufferDataInput; import org.apache.cassandra.io.util.FastByteArrayInputStream; import org.apache.cassandra.io.util.FileDataInput; import org.apache.cassandra.io.util.FileUtils; import org.apache.cassandra.io.util.RandomAccessReader; import org.apache.cassandra.utils.ByteBufferUtil; import org.apache.cassandra.utils.CRC32Factory; import org.apache.cassandra.utils.FBUtilities; import org.apache.cassandra.utils.JVMStabilityInspector; import org.apache.cassandra.utils.WrappedRunnable; import org.cliffc.high_scale_lib.NonBlockingHashSet; public class CommitLogReplayer { static final String IGNORE_REPLAY_ERRORS_PROPERTY = "cassandra.commitlog.ignorereplayerrors"; private static final Logger logger = LoggerFactory.getLogger(CommitLogReplayer.class); private static final int MAX_OUTSTANDING_REPLAY_COUNT = Integer.getInteger("cassandra.commitlog_max_outstanding_replay_count", 1024); private static final int LEGACY_END_OF_SEGMENT_MARKER = 0; private final Set<Keyspace> keyspacesRecovered; private final List<Future<?>> futures; private final Map<UUID, AtomicInteger> invalidMutations; private final AtomicInteger replayedCount; private final Map<UUID, ReplayPosition> cfPositions; private final ReplayPosition globalPosition; private final ICRC32 checksum; private byte[] buffer; private byte[] uncompressedBuffer; private final ReplayFilter replayFilter; private final CommitLogArchiver archiver; CommitLogReplayer(CommitLog commitLog, ReplayPosition globalPosition, Map<UUID, ReplayPosition> cfPositions, ReplayFilter replayFilter) { this.keyspacesRecovered = new NonBlockingHashSet<Keyspace>(); this.futures = new ArrayList<Future<?>>(); this.buffer = new byte[4096]; this.uncompressedBuffer = new byte[4096]; this.invalidMutations = new HashMap<UUID, AtomicInteger>(); // count the number of replayed mutation. We don't really care about atomicity, but we need it to be a reference. this.replayedCount = new AtomicInteger(); this.checksum = CRC32Factory.instance.create(); this.cfPositions = cfPositions; this.globalPosition = globalPosition; this.replayFilter = replayFilter; this.archiver = commitLog.archiver; } public static CommitLogReplayer construct(CommitLog commitLog) { // compute per-CF and global replay positions Map<UUID, ReplayPosition> cfPositions = new HashMap<UUID, ReplayPosition>(); Ordering<ReplayPosition> replayPositionOrdering = Ordering.from(ReplayPosition.comparator); ReplayFilter replayFilter = ReplayFilter.create(); for (ColumnFamilyStore cfs : ColumnFamilyStore.all()) { // it's important to call RP.gRP per-cf, before aggregating all the positions w/ the Ordering.min call // below: gRP will return NONE if there are no flushed sstables, which is important to have in the // list (otherwise we'll just start replay from the first flush position that we do have, which is not correct). ReplayPosition rp = ReplayPosition.getReplayPosition(cfs.getSSTables()); // but, if we've truncated the cf in question, then we need to need to start replay after the truncation ReplayPosition truncatedAt = SystemKeyspace.getTruncatedPosition(cfs.metadata.cfId); if (truncatedAt != null) { // Point in time restore is taken to mean that the tables need to be recovered even if they were // deleted at a later point in time. Any truncation record after that point must thus be cleared prior // to recovery (CASSANDRA-9195). long restoreTime = commitLog.archiver.restorePointInTime; long truncatedTime = SystemKeyspace.getTruncatedAt(cfs.metadata.cfId); if (truncatedTime > restoreTime) { if (replayFilter.includes(cfs.metadata)) { logger.info("Restore point in time is before latest truncation of table {}.{}. Clearing truncation record.", cfs.metadata.ksName, cfs.metadata.cfName); SystemKeyspace.removeTruncationRecord(cfs.metadata.cfId); } } else { rp = replayPositionOrdering.max(Arrays.asList(rp, truncatedAt)); } } cfPositions.put(cfs.metadata.cfId, rp); } ReplayPosition globalPosition = replayPositionOrdering.min(cfPositions.values()); logger.trace("Global replay position is {} from columnfamilies {}", globalPosition, FBUtilities.toString(cfPositions)); return new CommitLogReplayer(commitLog, globalPosition, cfPositions, replayFilter); } public void recover(File[] clogs) throws IOException { int i; for (i = 0; i < clogs.length; ++i) recover(clogs[i], i + 1 == clogs.length); } public int blockForWrites() { for (Map.Entry<UUID, AtomicInteger> entry : invalidMutations.entrySet()) logger.warn(String.format("Skipped %d mutations from unknown (probably removed) CF with id %s", entry.getValue().intValue(), entry.getKey())); // wait for all the writes to finish on the mutation stage FBUtilities.waitOnFutures(futures); logger.trace("Finished waiting on mutations from recovery"); // flush replayed keyspaces futures.clear(); for (Keyspace keyspace : keyspacesRecovered) futures.addAll(keyspace.flush()); FBUtilities.waitOnFutures(futures); return replayedCount.get(); } private int readSyncMarker(CommitLogDescriptor descriptor, int offset, RandomAccessReader reader, boolean tolerateTruncation) throws IOException { if (offset > reader.length() - CommitLogSegment.SYNC_MARKER_SIZE) { // There was no room in the segment to write a final header. No data could be present here. return -1; } reader.seek(offset); ICRC32 crc = CRC32Factory.instance.create(); crc.updateInt((int) (descriptor.id & 0xFFFFFFFFL)); crc.updateInt((int) (descriptor.id >>> 32)); crc.updateInt((int) reader.getPosition()); int end = reader.readInt(); long filecrc = reader.readInt() & 0xffffffffL; if (crc.getValue() != filecrc) { if (end != 0 || filecrc != 0) { handleReplayError(false, "Encountered bad header at position %d of commit log %s, with invalid CRC. " + "The end of segment marker should be zero.", offset, reader.getPath()); } return -1; } else if (end < offset || end > reader.length()) { handleReplayError(tolerateTruncation, "Encountered bad header at position %d of commit log %s, with bad position but valid CRC", offset, reader.getPath()); return -1; } return end; } abstract static class ReplayFilter { public abstract Iterable<ColumnFamily> filter(Mutation mutation); public abstract boolean includes(CFMetaData metadata); public static ReplayFilter create() { // If no replaylist is supplied an empty array of strings is used to replay everything. if (System.getProperty("cassandra.replayList") == null) return new AlwaysReplayFilter(); Multimap<String, String> toReplay = HashMultimap.create(); for (String rawPair : System.getProperty("cassandra.replayList").split(",")) { String[] pair = rawPair.trim().split("\\."); if (pair.length != 2) throw new IllegalArgumentException("Each table to be replayed must be fully qualified with keyspace name, e.g., 'system.peers'"); Keyspace ks = Schema.instance.getKeyspaceInstance(pair[0]); if (ks == null) throw new IllegalArgumentException("Unknown keyspace " + pair[0]); ColumnFamilyStore cfs = ks.getColumnFamilyStore(pair[1]); if (cfs == null) throw new IllegalArgumentException(String.format("Unknown table %s.%s", pair[0], pair[1])); toReplay.put(pair[0], pair[1]); } return new CustomReplayFilter(toReplay); } } private static class AlwaysReplayFilter extends ReplayFilter { public Iterable<ColumnFamily> filter(Mutation mutation) { return mutation.getColumnFamilies(); } public boolean includes(CFMetaData metadata) { return true; } } private static class CustomReplayFilter extends ReplayFilter { private Multimap<String, String> toReplay; public CustomReplayFilter(Multimap<String, String> toReplay) { this.toReplay = toReplay; } public Iterable<ColumnFamily> filter(Mutation mutation) { final Collection<String> cfNames = toReplay.get(mutation.getKeyspaceName()); if (cfNames == null) return Collections.emptySet(); return Iterables.filter(mutation.getColumnFamilies(), new Predicate<ColumnFamily>() { public boolean apply(ColumnFamily cf) { return cfNames.contains(cf.metadata().cfName); } }); } public boolean includes(CFMetaData metadata) { return toReplay.containsEntry(metadata.ksName, metadata.cfName); } } @SuppressWarnings("resource") public void recover(File file, boolean tolerateTruncation) throws IOException { CommitLogDescriptor desc = CommitLogDescriptor.fromFileName(file.getName()); RandomAccessReader reader = RandomAccessReader.open(new File(file.getAbsolutePath())); try { if (desc.version < CommitLogDescriptor.VERSION_21) { if (logAndCheckIfShouldSkip(file, desc)) return; if (globalPosition.segment == desc.id) reader.seek(globalPosition.position); replaySyncSection(reader, (int) reader.getPositionLimit(), desc, desc.fileName(), tolerateTruncation); return; } final long segmentId = desc.id; try { desc = CommitLogDescriptor.readHeader(reader); } catch (IOException e) { desc = null; } if (desc == null) { handleReplayError(false, "Could not read commit log descriptor in file %s", file); return; } if (segmentId != desc.id) { handleReplayError(false, "Segment id mismatch (filename %d, descriptor %d) in file %s", segmentId, desc.id, file); // continue processing if ignored. } if (logAndCheckIfShouldSkip(file, desc)) return; ICompressor compressor = null; if (desc.compression != null) { try { compressor = CompressionParameters.createCompressor(desc.compression); } catch (ConfigurationException e) { handleReplayError(false, "Unknown compression: %s", e.getMessage()); return; } } assert reader.length() <= Integer.MAX_VALUE; int end = (int) reader.getFilePointer(); int replayEnd = end; while ((end = readSyncMarker(desc, end, reader, tolerateTruncation)) >= 0) { int replayPos = replayEnd + CommitLogSegment.SYNC_MARKER_SIZE; if (logger.isTraceEnabled()) logger.trace("Replaying {} between {} and {}", file, reader.getFilePointer(), end); if (compressor != null) { int uncompressedLength = reader.readInt(); replayEnd = replayPos + uncompressedLength; } else { replayEnd = end; } if (segmentId == globalPosition.segment && replayEnd < globalPosition.position) // Skip over flushed section. continue; FileDataInput sectionReader = reader; String errorContext = desc.fileName(); // In the uncompressed case the last non-fully-flushed section can be anywhere in the file. boolean tolerateErrorsInSection = tolerateTruncation; if (compressor != null) { // In the compressed case we know if this is the last section. tolerateErrorsInSection &= end == reader.length() || end < 0; int start = (int) reader.getFilePointer(); try { int compressedLength = end - start; if (logger.isTraceEnabled()) logger.trace("Decompressing {} between replay positions {} and {}", file, replayPos, replayEnd); if (compressedLength > buffer.length) buffer = new byte[(int) (1.2 * compressedLength)]; reader.readFully(buffer, 0, compressedLength); int uncompressedLength = replayEnd - replayPos; if (uncompressedLength > uncompressedBuffer.length) uncompressedBuffer = new byte[(int) (1.2 * uncompressedLength)]; compressedLength = compressor.uncompress(buffer, 0, compressedLength, uncompressedBuffer, 0); sectionReader = new ByteBufferDataInput(ByteBuffer.wrap(uncompressedBuffer), reader.getPath(), replayPos, 0); errorContext = "compressed section at " + start + " in " + errorContext; } catch (IOException | ArrayIndexOutOfBoundsException e) { handleReplayError(tolerateErrorsInSection, "Unexpected exception decompressing section at %d: %s", start, e); continue; } } if (!replaySyncSection(sectionReader, replayEnd, desc, errorContext, tolerateErrorsInSection)) break; } } finally { FileUtils.closeQuietly(reader); logger.debug("Finished reading {}", file); } } public boolean logAndCheckIfShouldSkip(File file, CommitLogDescriptor desc) { logger.debug("Replaying {} (CL version {}, messaging version {}, compression {})", file.getPath(), desc.version, desc.getMessagingVersion(), desc.compression); if (globalPosition.segment > desc.id) { logger.trace("skipping replay of fully-flushed {}", file); return true; } return false; } /** * Replays a sync section containing a list of mutations. * * @return Whether replay should continue with the next section. */ private boolean replaySyncSection(FileDataInput reader, int end, CommitLogDescriptor desc, String errorContext, boolean tolerateErrors) throws IOException { /* read the logs populate Mutation and apply */ while (reader.getFilePointer() < end && !reader.isEOF()) { long mutationStart = reader.getFilePointer(); if (logger.isTraceEnabled()) logger.trace("Reading mutation at {}", mutationStart); long claimedCRC32; int serializedSize; try { // any of the reads may hit EOF serializedSize = reader.readInt(); if (serializedSize == LEGACY_END_OF_SEGMENT_MARKER) { logger.trace("Encountered end of segment marker at {}", reader.getFilePointer()); return false; } // Mutation must be at LEAST 10 bytes: // 3 each for a non-empty Keyspace and Key (including the // 2-byte length from writeUTF/writeWithShortLength) and 4 bytes for column count. // This prevents CRC by being fooled by special-case garbage in the file; see CASSANDRA-2128 if (serializedSize < 10) { handleReplayError(tolerateErrors, "Invalid mutation size %d at %d in %s", serializedSize, mutationStart, errorContext); return false; } long claimedSizeChecksum; if (desc.version < CommitLogDescriptor.VERSION_21) claimedSizeChecksum = reader.readLong(); else claimedSizeChecksum = reader.readInt() & 0xffffffffL; checksum.reset(); if (desc.version < CommitLogDescriptor.VERSION_20) checksum.update(serializedSize); else checksum.updateInt(serializedSize); if (checksum.getValue() != claimedSizeChecksum) { handleReplayError(tolerateErrors, "Mutation size checksum failure at %d in %s", mutationStart, errorContext); return false; } // ok. if (serializedSize > buffer.length) buffer = new byte[(int) (1.2 * serializedSize)]; reader.readFully(buffer, 0, serializedSize); if (desc.version < CommitLogDescriptor.VERSION_21) claimedCRC32 = reader.readLong(); else claimedCRC32 = reader.readInt() & 0xffffffffL; } catch (EOFException eof) { handleReplayError(tolerateErrors, "Unexpected end of segment", mutationStart, errorContext); return false; // last CL entry didn't get completely written. that's ok. } checksum.update(buffer, 0, serializedSize); if (claimedCRC32 != checksum.getValue()) { handleReplayError(tolerateErrors, "Mutation checksum failure at %d in %s", mutationStart, errorContext); continue; } replayMutation(buffer, serializedSize, reader.getFilePointer(), desc); } return true; } /** * Deserializes and replays a commit log entry. */ void replayMutation(byte[] inputBuffer, int size, final long entryLocation, final CommitLogDescriptor desc) throws IOException { final Mutation mutation; try (FastByteArrayInputStream bufIn = new FastByteArrayInputStream(inputBuffer, 0, size)) { mutation = Mutation.serializer.deserialize(new DataInputStream(bufIn), desc.getMessagingVersion(), ColumnSerializer.Flag.LOCAL); // doublecheck that what we read is [still] valid for the current schema for (ColumnFamily cf : mutation.getColumnFamilies()) for (Cell cell : cf) cf.getComparator().validate(cell.name()); } catch (UnknownColumnFamilyException ex) { if (ex.cfId == null) return; AtomicInteger i = invalidMutations.get(ex.cfId); if (i == null) { i = new AtomicInteger(1); invalidMutations.put(ex.cfId, i); } else i.incrementAndGet(); return; } catch (Throwable t) { JVMStabilityInspector.inspectThrowable(t); File f = File.createTempFile("mutation", "dat"); try (DataOutputStream out = new DataOutputStream(new FileOutputStream(f))) { out.write(inputBuffer, 0, size); } // Checksum passed so this error can't be permissible. handleReplayError(false, "Unexpected error deserializing mutation; saved to %s. " + "This may be caused by replaying a mutation against a table with the same name but incompatible schema. " + "Exception follows: %s", f.getAbsolutePath(), t); return; } if (logger.isTraceEnabled()) logger.trace("replaying mutation for {}.{}: {}", mutation.getKeyspaceName(), ByteBufferUtil.bytesToHex(mutation.key()), "{" + StringUtils.join(mutation.getColumnFamilies().iterator(), ", ") + "}"); Runnable runnable = new WrappedRunnable() { public void runMayThrow() throws IOException { if (Schema.instance.getKSMetaData(mutation.getKeyspaceName()) == null) return; if (pointInTimeExceeded(mutation)) return; final Keyspace keyspace = Keyspace.open(mutation.getKeyspaceName()); // Rebuild the mutation, omitting column families that // a) the user has requested that we ignore, // b) have already been flushed, // or c) are part of a cf that was dropped. // Keep in mind that the cf.name() is suspect. do every thing based on the cfid instead. Mutation newMutation = null; for (ColumnFamily columnFamily : replayFilter.filter(mutation)) { if (Schema.instance.getCF(columnFamily.id()) == null) continue; // dropped ReplayPosition rp = cfPositions.get(columnFamily.id()); // replay if current segment is newer than last flushed one or, // if it is the last known segment, if we are after the replay position if (desc.id > rp.segment || (desc.id == rp.segment && entryLocation > rp.position)) { if (newMutation == null) newMutation = new Mutation(mutation.getKeyspaceName(), mutation.key()); newMutation.add(columnFamily); replayedCount.incrementAndGet(); } } if (newMutation != null) { assert !newMutation.isEmpty(); Keyspace.open(newMutation.getKeyspaceName()).apply(newMutation, false); keyspacesRecovered.add(keyspace); } } }; futures.add(StageManager.getStage(Stage.MUTATION).submit(runnable)); if (futures.size() > MAX_OUTSTANDING_REPLAY_COUNT) { FBUtilities.waitOnFutures(futures); futures.clear(); } } protected boolean pointInTimeExceeded(Mutation fm) { long restoreTarget = archiver.restorePointInTime; for (ColumnFamily families : fm.getColumnFamilies()) { if (archiver.precision.toMillis(families.maxTimestamp()) > restoreTarget) return true; } return false; } static void handleReplayError(boolean permissible, String message, Object... messageArgs) throws IOException { String msg = String.format(message, messageArgs); IOException e = new CommitLogReplayException(msg); if (permissible) logger.error("Ignoring commit log replay error likely due to incomplete flush to disk", e); else if (Boolean.getBoolean(IGNORE_REPLAY_ERRORS_PROPERTY)) logger.error("Ignoring commit log replay error", e); else if (!CommitLog.handleCommitError("Failed commit log replay", e)) { logger.error("Replay stopped. If you wish to override this error and continue starting the node ignoring " + "commit log replay problems, specify -D" + IGNORE_REPLAY_ERRORS_PROPERTY + "=true " + "on the command line"); throw e; } } @SuppressWarnings("serial") public static class CommitLogReplayException extends IOException { public CommitLogReplayException(String message, Throwable cause) { super(message, cause); } public CommitLogReplayException(String message) { super(message); } } }
wreda/cassandra
src/java/org/apache/cassandra/db/commitlog/CommitLogReplayer.java
Java
apache-2.0
27,848
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateTopicsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('topics', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->text('bio')->nullable(); $table->integer('questionsCount')->default(0); $table->integer('followersCount')->default(0); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('topics'); } }
luisedware/Learning-Laravel
zhihu/database/migrations/2017_04_12_204500_create_topics_table.php
PHP
apache-2.0
788
package com.netopyr.reduxfx.vscenegraph.builders; import com.netopyr.reduxfx.vscenegraph.VNode; import com.netopyr.reduxfx.vscenegraph.event.VEventHandler; import com.netopyr.reduxfx.vscenegraph.event.VEventType; import com.netopyr.reduxfx.vscenegraph.property.VProperty; import javafx.geometry.Pos; import io.vavr.collection.Array; import io.vavr.collection.Map; import io.vavr.control.Option; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; public class HBoxBuilder<B extends HBoxBuilder<B>> extends PaneBuilder<B> { private static final String SPACING = "spacing"; private static final String ALIGNMENT = "alignment"; public HBoxBuilder(Class<?> nodeClass, Map<String, Array<VNode>> childrenMap, Map<String, Option<VNode>> singleChildMap, Map<String, VProperty> properties, Map<VEventType, VEventHandler> eventHandlers) { super(nodeClass, childrenMap, singleChildMap, properties, eventHandlers); } @SuppressWarnings("unchecked") @Override protected B create( Map<String, Array<VNode>> childrenMap, Map<String, Option<VNode>> singleChildMap, Map<String, VProperty> properties, Map<VEventType, VEventHandler> eventHandlers) { return (B) new HBoxBuilder<>(getNodeClass(), childrenMap, singleChildMap, properties, eventHandlers); } public B alignment(Pos value) { return property(ALIGNMENT, value); } public B spacing(double value) { return property(SPACING, value); } @Override public String toString() { return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE) .appendSuper(super.toString()) .toString(); } }
netopyr/reduxfx
reduxfx-view/src/main/java/com/netopyr/reduxfx/vscenegraph/builders/HBoxBuilder.java
Java
apache-2.0
1,864
package simulation.story.actions; import simulation.dialog.Dialog; import simulation.story.Actor; public class DialogActionType implements SceneActionType { Dialog dialog; public DialogActionType(String text) { this.dialog = new Dialog(text); } @Override public void start() { } @Override public boolean isDone() { return dialog.isDone(); } @Override public void update(float delta) { //dialog.update(delta); } public Dialog getDialog() { return dialog; } }
seanoneillcode/maze-of-doom
src/main/java/simulation/story/actions/DialogActionType.java
Java
apache-2.0
554
<!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_45) on Mon Mar 03 10:44:38 EST 2014 --> <title>Uses of Class org.hibernate.mapping.SingleTableSubclass (Hibernate JavaDocs)</title> <meta name="date" content="2014-03-03"> <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.hibernate.mapping.SingleTableSubclass (Hibernate JavaDocs)"; } //--> </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/hibernate/mapping/SingleTableSubclass.html" title="class in org.hibernate.mapping">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../overview-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/hibernate/mapping/class-use/SingleTableSubclass.html" target="_top">Frames</a></li> <li><a href="SingleTableSubclass.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.hibernate.mapping.SingleTableSubclass" class="title">Uses of Class<br>org.hibernate.mapping.SingleTableSubclass</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/hibernate/mapping/SingleTableSubclass.html" title="class in org.hibernate.mapping">SingleTableSubclass</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.hibernate.mapping">org.hibernate.mapping</a></td> <td class="colLast"> <div class="block"><div class="paragraph"></div> </td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="org.hibernate.mapping"> <!-- --> </a> <h3>Uses of <a href="../../../../org/hibernate/mapping/SingleTableSubclass.html" title="class in org.hibernate.mapping">SingleTableSubclass</a> in <a href="../../../../org/hibernate/mapping/package-summary.html">org.hibernate.mapping</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../org/hibernate/mapping/package-summary.html">org.hibernate.mapping</a> with parameters of type <a href="../../../../org/hibernate/mapping/SingleTableSubclass.html" title="class in org.hibernate.mapping">SingleTableSubclass</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="http://download.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a></code></td> <td class="colLast"><span class="strong">PersistentClassVisitor.</span><code><strong><a href="../../../../org/hibernate/mapping/PersistentClassVisitor.html#accept(org.hibernate.mapping.SingleTableSubclass)">accept</a></strong>(<a href="../../../../org/hibernate/mapping/SingleTableSubclass.html" title="class in org.hibernate.mapping">SingleTableSubclass</a>&nbsp;subclass)</code>&nbsp;</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/hibernate/mapping/SingleTableSubclass.html" title="class in org.hibernate.mapping">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../overview-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/hibernate/mapping/class-use/SingleTableSubclass.html" target="_top">Frames</a></li> <li><a href="SingleTableSubclass.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 &copy; 2001-2014 <a href="http://redhat.com">Red Hat, Inc.</a> All Rights Reserved.</small></p> </body> </html>
serious6/HibernateSimpleProject
javadoc/hibernate_Doc/org/hibernate/mapping/class-use/SingleTableSubclass.html
HTML
apache-2.0
6,547
package com.s24.search.solr.component.termstrategy; import org.apache.lucene.analysis.Analyzer; public class TermRankingStrategyBuilder { private AbstractTermRankingStrategy toBuild; private String q; private String extraTerms; private Analyzer analyzer; private String fields; private float boostFactor; private String queryType; public TermRankingStrategyBuilder multiplicativeTermRankingStrategy() { toBuild = new MultiplicativeTermRankingStrategy(); return this; } public TermRankingStrategyBuilder rerankTermRankingStrategy(int rerankDocCount) { toBuild = new RerankingTermRankingStrategy(rerankDocCount); return this; } public TermRankingStrategyBuilder additiveTermRankingStrategy() { toBuild = new AdditiveTermRankingStrategy(); return this; } public TermRankingStrategyBuilder forQuery(String q) { this.q = q; return this; } public TermRankingStrategyBuilder withExtraTerms(String extraTerms) { this.extraTerms = extraTerms; return this; } public TermRankingStrategyBuilder withQueryType(String queryType) { this.queryType = queryType; return this; } public TermRankingStrategyBuilder withAnalyzer(Analyzer analyzer) { this.analyzer = analyzer; return this; } public TermRankingStrategyBuilder withQueryField(String fields) { this.fields = fields; return this; } public TermRankingStrategyBuilder withFactor(float boostFactor) { this.boostFactor = boostFactor; return this; } public TermRankingStrategy build() { toBuild.setAnalyzer(analyzer); toBuild.setExtraTerms(extraTerms); toBuild.setFields(fields); toBuild.setQ(q); toBuild.setQueryType(queryType); toBuild.setBoostFactor(boostFactor); return toBuild; } }
shopping24/solr-bmax-queryparser
src/main/java/com/s24/search/solr/component/termstrategy/TermRankingStrategyBuilder.java
Java
apache-2.0
1,948
/* * * Copyright (c) 2016 Krupal Shah, Harsh Bhavsar * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.experiments.whereapp.config; import com.experiments.core.config.BaseConfig; import com.raizlabs.android.dbflow.annotation.Database; /** * Author : Krupal Shah * Date : 17-Apr-16 * <p> * configuration class specific for local db */ @Database(name = DbConfig.NAME, version = DbConfig.VERSION) public class DbConfig extends BaseConfig { public static final String NAME = "wheredb"; public static final int VERSION = 0; }
krupalshah/PinPlace
app/src/main/java/com/experiments/whereapp/config/DbConfig.java
Java
apache-2.0
1,076
/* * Copyright (c) 2021 MarkLogic Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.marklogic.client.dataservices; import com.marklogic.client.DatabaseClient; import com.marklogic.client.SessionState; import com.marklogic.client.dataservices.impl.HandleProvider; import com.marklogic.client.dataservices.impl.OutputEndpointImpl; import com.marklogic.client.io.InputStreamHandle; import com.marklogic.client.io.marker.JSONWriteHandle; import java.io.InputStream; /** * Provides an interface for calling an endpoint that returns output data structures. */ @Deprecated public interface OutputEndpoint extends OutputCaller<InputStream> { /** * Constructs an instance of the OutputEndpoint interface. * @param client the database client to use for making calls * @param apiDecl the JSON api declaration specifying how to call the endpoint * @return the OutputEndpoint instance for calling the endpoint. */ @Deprecated static OutputEndpoint on(DatabaseClient client, JSONWriteHandle apiDecl) { final class EndpointLocal<I> extends OutputEndpointImpl<I,InputStream> implements OutputEndpoint { private EndpointLocal(DatabaseClient client, JSONWriteHandle apiDecl) { super(client, apiDecl, new HandleProvider.ContentHandleProvider<>(null, new InputStreamHandle())); } public OutputEndpoint.BulkOutputCaller bulkCaller() { return new BulkLocal(this); } class BulkLocal extends OutputEndpointImpl.BulkOutputCallerImpl<I,InputStream> implements OutputEndpoint.BulkOutputCaller { private BulkLocal(EndpointLocal<I> endpoint) { super(endpoint); } } } return new EndpointLocal(client, apiDecl); } /** * Makes one call to the endpoint for the instance * @param endpointState the current mutable state of the endpoint (which must be null if not accepted by the endpoint) * @param session the identifier for the server cache of the endpoint (which must be null if not accepted by the endpoint) * @param workUnit the definition of a unit of work (which must be null if not accepted by the endpoint) * @return the endpoint state if produced by the endpoint followed by the response data from the endpoint */ @Deprecated InputStream[] call(InputStream endpointState, SessionState session, InputStream workUnit); @Override @Deprecated BulkOutputCaller bulkCaller(); /** * Provides an interface for completing a unit of work * by repeated calls to the output endpoint. */ @Deprecated interface BulkOutputCaller extends OutputCaller.BulkOutputCaller<InputStream> { } }
marklogic/java-client-api
marklogic-client-api/src/main/java/com/marklogic/client/dataservices/OutputEndpoint.java
Java
apache-2.0
3,339
/* * Copyright 2015 Caleb Brose, Chris Fogerty, Rob Sheehy, Zach Taylor, Nick Miller * * 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. */ // auth/init.js // Handles user session data and view access control. var authService = require('./authService'), sessionService = require('./sessionService'), loginController = require('./loginController'); var auth = angular.module('lighthouse.auth', []); auth.controller('loginController', loginController); auth.factory('authService', authService); auth.factory('sessionService', sessionService); module.exports = auth;
lighthouse/harbor
app/js/auth/init.js
JavaScript
apache-2.0
1,095
package com.mine.junit; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** JUnit 4 Spring Test (Spring框架中的test包) Spring 相关其他依赖包(不再赘述了,就是context等包) <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.9</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version> 3.2.4.RELEASE </version> <scope>provided</scope> </dependency> **/ @RunWith(SpringJUnit4ClassRunner.class) //使用junit4进行测试 @ContextConfiguration //({"/spring/app*.xml","/spring/service/app*.xml"}) //加载配置文件 //------------如果加入以下代码,所有继承该类的测试类都会遵循该配置,也可以不加,在测试类的方法上///控制事务,参见下一个实例 //这个非常关键,如果不加入这个注解配置,事务控制就会完全失效! //@Transactional //这里的事务关联到配置文件中的事务控制器(transactionManager = "transactionManager"),同时//指定自动回滚(defaultRollback = true)。这样做操作的数据才不会污染数据库! //@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true) //------------ public class BaseTest { }
luoyedaren/show-me-the-code
showmecode/src/main/java/com/mine/junit/BaseTest.java
Java
apache-2.0
1,578
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_151) on Wed Sep 05 03:08:44 MST 2018 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>org.wildfly.swarm.jaxrs.multipart.detect (BOM: * : All 2.2.0.Final API)</title> <meta name="date" content="2018-09-05"> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../../script.js"></script> </head> <body> <h1 class="bar"><a href="../../../../../../org/wildfly/swarm/jaxrs/multipart/detect/package-summary.html" target="classFrame">org.wildfly.swarm.jaxrs.multipart.detect</a></h1> <div class="indexContainer"> <h2 title="Classes">Classes</h2> <ul title="Classes"> <li><a href="JAXRSMultipartPackageDetector.html" title="class in org.wildfly.swarm.jaxrs.multipart.detect" target="classFrame">JAXRSMultipartPackageDetector</a></li> </ul> </div> </body> </html>
wildfly-swarm/wildfly-swarm-javadocs
2.2.0.Final/apidocs/org/wildfly/swarm/jaxrs/multipart/detect/package-frame.html
HTML
apache-2.0
1,052
<!DOCTYPE html> <html> <head> <meta content="text/html; charset=UTF-8" http-equiv="Content-Type"> <title>module nfs - RDoc Documentation</title> <link type="text/css" media="screen" href="./rdoc.css" rel="stylesheet"> <script type="text/javascript"> var rdoc_rel_prefix = "./"; </script> <script type="text/javascript" charset="utf-8" src="./js/jquery.js"></script> <script type="text/javascript" charset="utf-8" src="./js/navigation.js"></script> <script type="text/javascript" charset="utf-8" src="./js/search_index.js"></script> <script type="text/javascript" charset="utf-8" src="./js/search.js"></script> <script type="text/javascript" charset="utf-8" src="./js/searcher.js"></script> <script type="text/javascript" charset="utf-8" src="./js/darkfish.js"></script> <body id="top" class="module"> <nav id="metadata"> <nav id="home-section" class="section"> <h3 class="section-header"> <a href="./index.html">Home</a> <a href="./table_of_contents.html#classes">Classes</a> <a href="./table_of_contents.html#methods">Methods</a> </h3> </nav> <nav id="search-section" class="section project-section" class="initially-hidden"> <form action="#" method="get" accept-charset="utf-8"> <h3 class="section-header"> <input type="text" name="search" placeholder="Search" id="search-field" title="Type to search, Up and Down to navigate, Enter to load"> </h3> </form> <ul id="search-results" class="initially-hidden"></ul> </nav> <div id="file-metadata"> <nav id="file-list-section" class="section"> <h3 class="section-header">Defined In</h3> <ul> <li>modules/nfs/manifests/export.pp <li>modules/nfs/manifests/exports.pp <li>modules/nfs/manifests/server.pp <li>modules/nfs/manifests/server/debian.pp <li>modules/nfs/manifests/server/redhat.pp <li>modules/nfs/manifests/test.pp </ul> </nav> </div> <div id="class-metadata"> <!-- Method Quickref --> <nav id="method-list-section" class="section"> <h3 class="section-header">Methods</h3> <ul class="link-list"> <li ><a href="#method-i-export">#export</a> <li ><a href="#method-i-planfile">#planfile</a> </ul> </nav> </div> <div id="project-metadata"> <nav id="fileindex-section" class="section project-section"> <h3 class="section-header">Pages</h3> <ul> <li class="file"><a href="./modules/apache/CHANGELOG_md.html">CHANGELOG</a> <li class="file"><a href="./modules/apache/CONTRIBUTING_md.html">CONTRIBUTING</a> <li class="file"><a href="./modules/apache/Gemfile.html">Gemfile</a> <li class="file"><a href="./modules/apache/LICENSE.html">LICENSE</a> <li class="file"><a href="./modules/apache/README_md.html">README</a> <li class="file"><a href="./modules/apache/README_passenger_md.html">README.passenger</a> <li class="file"><a href="./modules/apache/Rakefile.html">Rakefile</a> <li class="file"><a href="./modules/apache/checksums_json.html">checksums.json</a> <li class="file"><a href="./modules/apache/metadata_json.html">metadata.json</a> <li class="file"><a href="./modules/apt/CHANGELOG_md.html">CHANGELOG</a> <li class="file"><a href="./modules/apt/CONTRIBUTING_md.html">CONTRIBUTING</a> <li class="file"><a href="./modules/apt/Gemfile.html">Gemfile</a> <li class="file"><a href="./modules/apt/LICENSE.html">LICENSE</a> <li class="file"><a href="./modules/apt/README_md.html">README</a> <li class="file"><a href="./modules/apt/Rakefile.html">Rakefile</a> <li class="file"><a href="./modules/apt/checksums_json.html">checksums.json</a> <li class="file"><a href="./modules/apt/metadata_json.html">metadata.json</a> <li class="file"><a href="./modules/base/Modulefile.html">Modulefile</a> <li class="file"><a href="./modules/base/README.html">README</a> <li class="file"><a href="./modules/concat/CHANGELOG_md.html">CHANGELOG</a> <li class="file"><a href="./modules/concat/CONTRIBUTING_md.html">CONTRIBUTING</a> <li class="file"><a href="./modules/concat/Gemfile.html">Gemfile</a> <li class="file"><a href="./modules/concat/LICENSE.html">LICENSE</a> <li class="file"><a href="./modules/concat/README_md.html">README</a> <li class="file"><a href="./modules/concat/Rakefile.html">Rakefile</a> <li class="file"><a href="./modules/concat/checksums_json.html">checksums.json</a> <li class="file"><a href="./modules/concat/metadata_json.html">metadata.json</a> <li class="file"><a href="./modules/firewall/CHANGELOG_md.html">CHANGELOG</a> <li class="file"><a href="./modules/firewall/CONTRIBUTING_md.html">CONTRIBUTING</a> <li class="file"><a href="./modules/firewall/Gemfile.html">Gemfile</a> <li class="file"><a href="./modules/firewall/LICENSE.html">LICENSE</a> <li class="file"><a href="./modules/firewall/README_markdown.html">README.markdown</a> <li class="file"><a href="./modules/firewall/Rakefile.html">Rakefile</a> <li class="file"><a href="./modules/firewall/checksums_json.html">checksums.json</a> <li class="file"><a href="./modules/firewall/metadata_json.html">metadata.json</a> <li class="file"><a href="./modules/heartbeat/Rakefile.html">Rakefile</a> <li class="file"><a href="./modules/module_data/Modulefile.html">Modulefile</a> <li class="file"><a href="./modules/module_data/README_md.html">README</a> <li class="file"><a href="./modules/module_data/metadata_json.html">metadata.json</a> <li class="file"><a href="./modules/mysql/CHANGELOG_md.html">CHANGELOG</a> <li class="file"><a href="./modules/mysql/Gemfile.html">Gemfile</a> <li class="file"><a href="./modules/mysql/Gemfile_lock.html">Gemfile.lock</a> <li class="file"><a href="./modules/mysql/LICENSE.html">LICENSE</a> <li class="file"><a href="./modules/mysql/README_md.html">README</a> <li class="file"><a href="./modules/mysql/Rakefile.html">Rakefile</a> <li class="file"><a href="./modules/mysql/TODO.html">TODO</a> <li class="file"><a href="./modules/mysql/checksums_json.html">checksums.json</a> <li class="file"><a href="./modules/mysql/metadata_json.html">metadata.json</a> <li class="file"><a href="./modules/nginx/CONTRIBUTING_md.html">CONTRIBUTING</a> <li class="file"><a href="./modules/nginx/Gemfile.html">Gemfile</a> <li class="file"><a href="./modules/nginx/Gemfile_lock.html">Gemfile.lock</a> <li class="file"><a href="./modules/nginx/LICENSE_md.html">LICENSE</a> <li class="file"><a href="./modules/nginx/README_markdown.html">README.markdown</a> <li class="file"><a href="./modules/nginx/Rakefile.html">Rakefile</a> <li class="file"><a href="./modules/nginx/checksums_json.html">checksums.json</a> <li class="file"><a href="./modules/nginx/composer_json.html">composer.json</a> <li class="file"><a href="./modules/nginx/data/common_yaml.html">common.yaml</a> <li class="file"><a href="./modules/nginx/data/hiera_yaml.html">hiera.yaml</a> <li class="file"><a href="./modules/nginx/data/operatingsystem/SmartOS_yaml.html">SmartOS.yaml</a> <li class="file"><a href="./modules/nginx/data/osfamily/Archlinux_yaml.html">Archlinux.yaml</a> <li class="file"><a href="./modules/nginx/data/osfamily/Debian_yaml.html">Debian.yaml</a> <li class="file"><a href="./modules/nginx/data/osfamily/FreeBSD_yaml.html">FreeBSD.yaml</a> <li class="file"><a href="./modules/nginx/data/osfamily/Solaris_yaml.html">Solaris.yaml</a> <li class="file"><a href="./modules/nginx/docs/hiera_md.html">hiera</a> <li class="file"><a href="./modules/nginx/metadata_json.html">metadata.json</a> <li class="file"><a href="./modules/profiles/Gemfile.html">Gemfile</a> <li class="file"><a href="./modules/profiles/README_md.html">README</a> <li class="file"><a href="./modules/profiles/Rakefile.html">Rakefile</a> <li class="file"><a href="./modules/profiles/metadata_json.html">metadata.json</a> <li class="file"><a href="./modules/roles/Gemfile.html">Gemfile</a> <li class="file"><a href="./modules/roles/README_md.html">README</a> <li class="file"><a href="./modules/roles/Rakefile.html">Rakefile</a> <li class="file"><a href="./modules/roles/metadata_json.html">metadata.json</a> <li class="file"><a href="./modules/stdlib/CHANGELOG_md.html">CHANGELOG</a> <li class="file"><a href="./modules/stdlib/CONTRIBUTING_md.html">CONTRIBUTING</a> <li class="file"><a href="./modules/stdlib/Gemfile.html">Gemfile</a> <li class="file"><a href="./modules/stdlib/LICENSE.html">LICENSE</a> <li class="file"><a href="./modules/stdlib/README_markdown.html">README.markdown</a> <li class="file"><a href="./modules/stdlib/README_DEVELOPER_markdown.html">README_DEVELOPER.markdown</a> <li class="file"><a href="./modules/stdlib/README_SPECS_markdown.html">README_SPECS.markdown</a> <li class="file"><a href="./modules/stdlib/RELEASE_PROCESS_markdown.html">RELEASE_PROCESS.markdown</a> <li class="file"><a href="./modules/stdlib/Rakefile.html">Rakefile</a> <li class="file"><a href="./modules/stdlib/checksums_json.html">checksums.json</a> <li class="file"><a href="./modules/stdlib/metadata_json.html">metadata.json</a> <li class="file"><a href="./modules/thing/Rakefile.html">Rakefile</a> <li class="file"><a href="./modules/thomas-base/Modulefile.html">Modulefile</a> <li class="file"><a href="./modules/thomas-base/README.html">README</a> <li class="file"><a href="./modules/thomas-profiles/Gemfile.html">Gemfile</a> <li class="file"><a href="./modules/thomas-profiles/README_md.html">README</a> <li class="file"><a href="./modules/thomas-profiles/Rakefile.html">Rakefile</a> <li class="file"><a href="./modules/thomas-profiles/metadata_json.html">metadata.json</a> <li class="file"><a href="./modules/thomas-roles/Gemfile.html">Gemfile</a> <li class="file"><a href="./modules/thomas-roles/README_md.html">README</a> <li class="file"><a href="./modules/thomas-roles/Rakefile.html">Rakefile</a> <li class="file"><a href="./modules/thomas-roles/metadata_json.html">metadata.json</a> </ul> </nav> <nav id="classindex-section" class="section project-section"> <h3 class="section-header">Class and Module Index</h3> <ul class="link-list"> <li><a href="./__site__.html">__site__</a> <li><a href="./admin.html">admin</a> <li><a href="./admin/__functions__.html">admin::__functions__</a> <li><a href="./admin/percona_repo.html">admin::percona_repo</a> <li><a href="./admin/stages.html">admin::stages</a> <li><a href="./admin/stages/me_first.html">admin::stages::me_first</a> <li><a href="./admin/stages/me_last.html">admin::stages::me_last</a> <li><a href="./admin_user.html">admin_user</a> <li><a href="./apache.html">apache</a> <li><a href="./apache.cookbook.html">apache.cookbook</a> <li><a href="./apache.cookbook/apache.html">apache.cookbook::apache</a> <li><a href="./apache/__types__.html">apache::__types__</a> <li><a href="./apache/confd.html">apache::confd</a> <li><a href="./apache/confd/no_accf.html">apache::confd::no_accf</a> <li><a href="./apache/default_confd_files.html">apache::default_confd_files</a> <li><a href="./apache/default_mods.html">apache::default_mods</a> <li><a href="./apache/dev.html">apache::dev</a> <li><a href="./apache/mod.html">apache::mod</a> <li><a href="./apache/mod/actions.html">apache::mod::actions</a> <li><a href="./apache/mod/alias.html">apache::mod::alias</a> <li><a href="./apache/mod/auth_basic.html">apache::mod::auth_basic</a> <li><a href="./apache/mod/auth_kerb.html">apache::mod::auth_kerb</a> <li><a href="./apache/mod/authnz_ldap.html">apache::mod::authnz_ldap</a> <li><a href="./apache/mod/autoindex.html">apache::mod::autoindex</a> <li><a href="./apache/mod/cache.html">apache::mod::cache</a> <li><a href="./apache/mod/cgi.html">apache::mod::cgi</a> <li><a href="./apache/mod/cgid.html">apache::mod::cgid</a> <li><a href="./apache/mod/dav.html">apache::mod::dav</a> <li><a href="./apache/mod/dav_fs.html">apache::mod::dav_fs</a> <li><a href="./apache/mod/dav_svn.html">apache::mod::dav_svn</a> <li><a href="./apache/mod/deflate.html">apache::mod::deflate</a> <li><a href="./apache/mod/dev.html">apache::mod::dev</a> <li><a href="./apache/mod/dir.html">apache::mod::dir</a> <li><a href="./apache/mod/disk_cache.html">apache::mod::disk_cache</a> <li><a href="./apache/mod/event.html">apache::mod::event</a> <li><a href="./apache/mod/expires.html">apache::mod::expires</a> <li><a href="./apache/mod/fastcgi.html">apache::mod::fastcgi</a> <li><a href="./apache/mod/fcgid.html">apache::mod::fcgid</a> <li><a href="./apache/mod/headers.html">apache::mod::headers</a> <li><a href="./apache/mod/include.html">apache::mod::include</a> <li><a href="./apache/mod/info.html">apache::mod::info</a> <li><a href="./apache/mod/itk.html">apache::mod::itk</a> <li><a href="./apache/mod/ldap.html">apache::mod::ldap</a> <li><a href="./apache/mod/mime.html">apache::mod::mime</a> <li><a href="./apache/mod/mime_magic.html">apache::mod::mime_magic</a> <li><a href="./apache/mod/negotiation.html">apache::mod::negotiation</a> <li><a href="./apache/mod/nss.html">apache::mod::nss</a> <li><a href="./apache/mod/pagespeed.html">apache::mod::pagespeed</a> <li><a href="./apache/mod/passenger.html">apache::mod::passenger</a> <li><a href="./apache/mod/perl.html">apache::mod::perl</a> <li><a href="./apache/mod/peruser.html">apache::mod::peruser</a> <li><a href="./apache/mod/php.html">apache::mod::php</a> <li><a href="./apache/mod/prefork.html">apache::mod::prefork</a> <li><a href="./apache/mod/proxy.html">apache::mod::proxy</a> <li><a href="./apache/mod/proxy_ajp.html">apache::mod::proxy_ajp</a> <li><a href="./apache/mod/proxy_balancer.html">apache::mod::proxy_balancer</a> <li><a href="./apache/mod/proxy_html.html">apache::mod::proxy_html</a> <li><a href="./apache/mod/proxy_http.html">apache::mod::proxy_http</a> <li><a href="./apache/mod/python.html">apache::mod::python</a> <li><a href="./apache/mod/reqtimeout.html">apache::mod::reqtimeout</a> <li><a href="./apache/mod/rewrite.html">apache::mod::rewrite</a> <li><a href="./apache/mod/rpaf.html">apache::mod::rpaf</a> <li><a href="./apache/mod/setenvif.html">apache::mod::setenvif</a> <li><a href="./apache/mod/speling.html">apache::mod::speling</a> <li><a href="./apache/mod/ssl.html">apache::mod::ssl</a> <li><a href="./apache/mod/status.html">apache::mod::status</a> <li><a href="./apache/mod/suexec.html">apache::mod::suexec</a> <li><a href="./apache/mod/suphp.html">apache::mod::suphp</a> <li><a href="./apache/mod/userdir.html">apache::mod::userdir</a> <li><a href="./apache/mod/vhost_alias.html">apache::mod::vhost_alias</a> <li><a href="./apache/mod/worker.html">apache::mod::worker</a> <li><a href="./apache/mod/wsgi.html">apache::mod::wsgi</a> <li><a href="./apache/mod/xsendfile.html">apache::mod::xsendfile</a> <li><a href="./apache/package.html">apache::package</a> <li><a href="./apache/params.html">apache::params</a> <li><a href="./apache/peruser.html">apache::peruser</a> <li><a href="./apache/php.html">apache::php</a> <li><a href="./apache/proxy.html">apache::proxy</a> <li><a href="./apache/python.html">apache::python</a> <li><a href="./apache/service.html">apache::service</a> <li><a href="./apache/ssl.html">apache::ssl</a> <li><a href="./apache/version.html">apache::version</a> <li><a href="./apt.html">apt</a> <li><a href="./apt/__facts__.html">apt::__facts__</a> <li><a href="./apt/__types__.html">apt::__types__</a> <li><a href="./apt/apt.html">apt::apt</a> <li><a href="./apt/backports.html">apt::backports</a> <li><a href="./apt/debian.html">apt::debian</a> <li><a href="./apt/debian/testing.html">apt::debian::testing</a> <li><a href="./apt/debian/unstable.html">apt::debian::unstable</a> <li><a href="./apt/params.html">apt::params</a> <li><a href="./apt/release.html">apt::release</a> <li><a href="./apt/unattended_upgrades.html">apt::unattended_upgrades</a> <li><a href="./apt/update.html">apt::update</a> <li><a href="./base.html">base</a> <li><a href="./base/base.html">base::base</a> <li><a href="./base/ssh_host.html">base::ssh_host</a> <li><a href="./concat.html">concat</a> <li><a href="./concat/__facts__.html">concat::__facts__</a> <li><a href="./concat/__functions__.html">concat::__functions__</a> <li><a href="./concat/setup.html">concat::setup</a> <li><a href="./cookbook.html">cookbook</a> <li><a href="./cookbook/__functions__.html">cookbook::__functions__</a> <li><a href="./cron.html">cron</a> <li><a href="./cron/cron.html">cron::cron</a> <li><a href="./db.html">db</a> <li><a href="./db/client.html">db::client</a> <li><a href="./db/server.html">db::server</a> <li><a href="./debug.html">debug</a> <li><a href="./debug/debug.html">debug::debug</a> <li><a href="./drupal.html">drupal</a> <li><a href="./drupal/drupal.html">drupal::drupal</a> <li><a href="./enc.html">enc</a> <li><a href="./enc/enc.html">enc::enc</a> <li><a href="./facts.html">facts</a> <li><a href="./firewall.html">firewall</a> <li><a href="./firewall/__types__.html">firewall::__types__</a> <li><a href="./firewall/firewall.html">firewall::firewall</a> <li><a href="./firewall/linux.html">firewall::linux</a> <li><a href="./firewall/linux/archlinux.html">firewall::linux::archlinux</a> <li><a href="./firewall/linux/debian.html">firewall::linux::debian</a> <li><a href="./firewall/linux/redhat.html">firewall::linux::redhat</a> <li><a href="./greeting.html">greeting</a> <li><a href="./greeting/greeting.html">greeting::greeting</a> <li><a href="./haproxy.html">haproxy</a> <li><a href="./haproxy/config.html">haproxy::config</a> <li><a href="./haproxy/master.html">haproxy::master</a> <li><a href="./haproxy/slave.html">haproxy::slave</a> <li><a href="./heartbeat.html">heartbeat</a> <li><a href="./heartbeat/heartbeat.html">heartbeat::heartbeat</a> <li><a href="./heartbeat/vip.html">heartbeat::vip</a> <li><a href="./jumpbox.html">jumpbox</a> <li><a href="./jumpbox/jumpbox.html">jumpbox::jumpbox</a> <li><a href="./lisa.html">lisa</a> <li><a href="./module_data.html">module_data</a> <li><a href="./myfw.html">myfw</a> <li><a href="./myfw/myfw.html">myfw::myfw</a> <li><a href="./myfw/post.html">myfw::post</a> <li><a href="./myfw/pre.html">myfw::pre</a> <li><a href="./mysql.html">mysql</a> <li><a href="./mysql.cookbook.html">mysql.cookbook</a> <li><a href="./mysql.cookbook/mysql.html">mysql.cookbook::mysql</a> <li><a href="./mysql/__functions__.html">mysql::__functions__</a> <li><a href="./mysql/__types__.html">mysql::__types__</a> <li><a href="./mysql/backup.html">mysql::backup</a> <li><a href="./mysql/bindings.html">mysql::bindings</a> <li><a href="./mysql/bindings/java.html">mysql::bindings::java</a> <li><a href="./mysql/bindings/perl.html">mysql::bindings::perl</a> <li><a href="./mysql/bindings/php.html">mysql::bindings::php</a> <li><a href="./mysql/bindings/python.html">mysql::bindings::python</a> <li><a href="./mysql/bindings/ruby.html">mysql::bindings::ruby</a> <li><a href="./mysql/client.html">mysql::client</a> <li><a href="./mysql/client/install.html">mysql::client::install</a> <li><a href="./mysql/params.html">mysql::params</a> <li><a href="./mysql/server.html">mysql::server</a> <li><a href="./mysql/server/account_security.html">mysql::server::account_security</a> <li><a href="./mysql/server/backup.html">mysql::server::backup</a> <li><a href="./mysql/server/config.html">mysql::server::config</a> <li><a href="./mysql/server/install.html">mysql::server::install</a> <li><a href="./mysql/server/monitor.html">mysql::server::monitor</a> <li><a href="./mysql/server/mysqltuner.html">mysql::server::mysqltuner</a> <li><a href="./mysql/server/providers.html">mysql::server::providers</a> <li><a href="./mysql/server/root_password.html">mysql::server::root_password</a> <li><a href="./mysql/server/service.html">mysql::server::service</a> <li><a href="./nfs.html">nfs</a> <li><a href="./nfs/exports.html">nfs::exports</a> <li><a href="./nfs/server.html">nfs::server</a> <li><a href="./nfs/server/debian.html">nfs::server::debian</a> <li><a href="./nfs/server/redhat.html">nfs::server::redhat</a> <li><a href="./nginx.html">nginx</a> <li><a href="./nginx/config.html">nginx::config</a> <li><a href="./nginx/nginx.html">nginx::nginx</a> <li><a href="./nginx/notice.html">nginx::notice</a> <li><a href="./nginx/notice/puppet_module_data.html">nginx::notice::puppet_module_data</a> <li><a href="./nginx/package.html">nginx::package</a> <li><a href="./nginx/package/archlinux.html">nginx::package::archlinux</a> <li><a href="./nginx/package/debian.html">nginx::package::debian</a> <li><a href="./nginx/package/freebsd.html">nginx::package::freebsd</a> <li><a href="./nginx/package/gentoo.html">nginx::package::gentoo</a> <li><a href="./nginx/package/redhat.html">nginx::package::redhat</a> <li><a href="./nginx/package/solaris.html">nginx::package::solaris</a> <li><a href="./nginx/package/suse.html">nginx::package::suse</a> <li><a href="./nginx/resource.html">nginx::resource</a> <li><a href="./nginx/resource/upstream.html">nginx::resource::upstream</a> <li><a href="./nginx/service.html">nginx::service</a> <li><a href="./nothing.html">nothing</a> <li><a href="./nothing/nothing.html">nothing::nothing</a> <li><a href="./one.html">one</a> <li><a href="./one/one.html">one::one</a> <li><a href="./profiles.html">profiles</a> <li><a href="./profiles/apache.html">profiles::apache</a> <li><a href="./profiles/base.html">profiles::base</a> <li><a href="./profiles/profiles.html">profiles::profiles</a> <li><a href="./puppet.html">puppet</a> <li><a href="./puppet/puppet.html">puppet::puppet</a> <li><a href="./roles.html">roles</a> <li><a href="./roles/roles.html">roles::roles</a> <li><a href="./roles/webserver.html">roles::webserver</a> <li><a href="./ssh_user.html">ssh_user</a> <li><a href="./stdlib.html">stdlib</a> <li><a href="./stdlib/__facts__.html">stdlib::__facts__</a> <li><a href="./stdlib/__functions__.html">stdlib::__functions__</a> <li><a href="./stdlib/__types__.html">stdlib::__types__</a> <li><a href="./stdlib/stages.html">stdlib::stages</a> <li><a href="./stdlib/stdlib.html">stdlib::stdlib</a> <li><a href="./thing.html">thing</a> <li><a href="./thing/thing.html">thing::thing</a> <li><a href="./thomas-base.html">thomas-base</a> <li><a href="./thomas-profiles.html">thomas-profiles</a> <li><a href="./thomas-roles.html">thomas-roles</a> <li><a href="./two.html">two</a> <li><a href="./two/two.html">two::two</a> <li><a href="./user.html">user</a> <li><a href="./user/developers.html">user::developers</a> <li><a href="./user/sysadmins.html">user::sysadmins</a> <li><a href="./user/virtual.html">user::virtual</a> <li><a href="./virtual.html">virtual</a> <li><a href="./virtual/virtual.html">virtual::virtual</a> <li><a href="./wordpress.html">wordpress</a> <li><a href="./wordpress/wordpress.html">wordpress::wordpress</a> </ul> </nav> </div> </nav> <div id="documentation"> <h1 class="module">module nfs</h1> <div id="description" class="description"> </div><!-- description --> <section id="5Buntitled-5D" class="documentation-section"> <!-- Methods --> <section id="public-instance-5Buntitled-5D-method-details" class="method-section section"> <h3 class="section-header">Public Instance Methods</h3> <div id="method-i-export" class="method-detail "> <div class="method-heading"> <span class="method-name">export</span><span class="method-args">( $where => 'title', $who => '*', $options => 'async,ro', $mount_options => 'defaults', $tag => 'nfs' )</span> </div> <div class="method-description"> </div> </div><!-- export-method --> <div id="method-i-planfile" class="method-detail "> <div class="method-heading"> <span class="method-name">planfile</span><span class="method-args">( $user => 'title', $content )</span> </div> <div class="method-description"> </div> </div><!-- planfile-method --> </section><!-- public-instance-method-details --> </section><!-- 5Buntitled-5D --> </div><!-- documentation --> <footer id="validator-badges"> <p><a href="http://validator.w3.org/check/referer">[Validate]</a> <p>Generated by <a href="https://github.com/rdoc/rdoc">RDoc</a> 4.0.1. <p>Generated with the <a href="http://deveiate.org/projects/Darkfish-Rdoc/">Darkfish Rdoc Generator</a> 3. </footer>
uphillian/puppetcookbook
10/doc/nfs.html
HTML
apache-2.0
26,502
<html> <head> <meta name="viewport" content="width=device-width, initial-scale=1" charset="UTF-8"> <title>DefaultSenderScheduler</title> <link href="../../../images/logo-icon.svg" rel="icon" type="image/svg"><script>var pathToRoot = "../../../";</script> <script>const storage = localStorage.getItem("dokka-dark-mode") const savedDarkMode = storage ? JSON.parse(storage) : false if(savedDarkMode === true){ document.getElementsByTagName("html")[0].classList.add("theme-dark") }</script> <script type="text/javascript" src="../../../scripts/sourceset_dependencies.js" async="async"></script><link href="../../../styles/style.css" rel="Stylesheet"><link href="../../../styles/jetbrains-mono.css" rel="Stylesheet"><link href="../../../styles/main.css" rel="Stylesheet"><link href="../../../styles/prism.css" rel="Stylesheet"><link href="../../../styles/logo-styles.css" rel="Stylesheet"><script type="text/javascript" src="../../../scripts/clipboard.js" async="async"></script><script type="text/javascript" src="../../../scripts/navigation-loader.js" async="async"></script><script type="text/javascript" src="../../../scripts/platform-content-handler.js" async="async"></script><script type="text/javascript" src="../../../scripts/main.js" defer="defer"></script><script type="text/javascript" src="../../../scripts/prism.js" async="async"></script> </head> <body> <div class="navigation-wrapper" id="navigation-wrapper"> <div id="leftToggler"><span class="icon-toggler"></span></div> <div class="library-name"><a href="../../../index.html">acra</a></div> <div></div> <div class="pull-right d-flex"> <div class="filter-section" id="filter-section"><button class="platform-tag platform-selector jvm-like" data-active="" data-filter=":acra-toast:dokkaHtml/release">androidJvm</button></div> <button id="theme-toggle-button"><span id="theme-toggle"></span></button> <div id="searchBar"></div> </div> </div> <div id="container"> <div id="leftColumn"> <div id="sideMenu"></div> </div> <div id="main"> <div class="main-content" id="content" pageIds="acra::org.acra.scheduler/DefaultSenderScheduler/DefaultSenderScheduler/#android.content.Context#org.acra.config.CoreConfiguration/PointingToDeclaration//-535716451"> <div class="breadcrumbs"><a href="../../../index.html">acra</a>/<a href="../index.html">org.acra.scheduler</a>/<a href="index.html">DefaultSenderScheduler</a>/<a href="-default-sender-scheduler.html">DefaultSenderScheduler</a></div> <div class="cover "> <h1 class="cover"><span>Default</span><wbr></wbr><span>Sender</span><wbr></wbr><span><span>Scheduler</span></span></h1> </div> <div class="platform-hinted with-platform-tabs" data-platform-hinted="data-platform-hinted"> <div class="platform-bookmarks-row" data-toggle-list="data-toggle-list"><button class="platform-bookmark jvm-like" data-filterable-current=":acra-toast:dokkaHtml/release" data-filterable-set=":acra-toast:dokkaHtml/release" data-active="" data-toggle=":acra-toast:dokkaHtml/release">androidJvm</button></div> <div class="content sourceset-depenent-content" data-active="" data-togglable=":acra-toast:dokkaHtml/release"><div class="symbol monospace"><span class="token keyword"></span><span class="token keyword">fun </span><a href="-default-sender-scheduler.html"><span class="token function">DefaultSenderScheduler</span></a><span class="token punctuation">(</span>context<span class="token operator">: </span><a href="https://developer.android.com/reference/kotlin/android/content/Context.html">Context</a><span class="token punctuation">, </span>config<span class="token operator">: </span><a href="../../org.acra.config/-core-configuration/index.html">CoreConfiguration</a><span class="token punctuation">)</span><span class="top-right-position"><span class="copy-icon"></span><div class="copy-popup-wrapper popup-to-left"><span class="copy-popup-icon"></span><span>Content copied to clipboard</span></div></span></div></div> </div> </div> <div class="footer"><span class="go-to-top-icon"><a href="#content" id="go-to-top-link"></a></span><span>© 2022 Copyright</span><span class="pull-right"><span>Generated by </span><a href="https://github.com/Kotlin/dokka"><span>dokka</span><span class="padded-icon"></span></a></span></div> </div> </div> </body> </html>
ACRA/acra
web/static/javadoc/5.9.0-rc2/acra/org.acra.scheduler/-default-sender-scheduler/-default-sender-scheduler.html
HTML
apache-2.0
4,462
/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.buck.cxx; import com.facebook.buck.core.build.execution.context.IsolatedExecutionContext; import com.facebook.buck.core.filesystems.RelPath; import com.facebook.buck.io.filesystem.ProjectFilesystem; import com.facebook.buck.step.isolatedsteps.shell.IsolatedShellStep; import com.facebook.buck.util.environment.Platform; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import java.nio.file.Path; class RanlibStep extends IsolatedShellStep { private final ImmutableMap<String, String> ranlibEnv; private final ImmutableList<String> ranlibPrefix; private final ImmutableList<String> ranlibFlags; private final Path output; public RanlibStep( ProjectFilesystem filesystem, ImmutableMap<String, String> ranlibEnv, ImmutableList<String> ranlibPrefix, ImmutableList<String> ranlibFlags, Path output, RelPath cellPath, boolean withDownwardApi) { super(filesystem.getRootPath(), cellPath, withDownwardApi); Preconditions.checkArgument(!output.isAbsolute()); this.ranlibEnv = ranlibEnv; this.ranlibPrefix = ranlibPrefix; this.ranlibFlags = ranlibFlags; this.output = output; } @Override public ImmutableMap<String, String> getEnvironmentVariables(Platform platform) { return ranlibEnv; } @Override protected ImmutableList<String> getShellCommandInternal(IsolatedExecutionContext context) { return ImmutableList.<String>builder() .addAll(ranlibPrefix) .addAll(ranlibFlags) .add(output.toString()) .build(); } @Override public String getShortName() { return "ranlib"; } }
JoelMarcey/buck
src/com/facebook/buck/cxx/RanlibStep.java
Java
apache-2.0
2,338
<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html> <head> <title>Stopper - ScalaTest 2.2.4 - org.scalatest.Stopper</title> <meta name="description" content="Stopper - ScalaTest 2.2.4 - org.scalatest.Stopper" /> <meta name="keywords" content="Stopper ScalaTest 2.2.4 org.scalatest.Stopper" /> <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> <link href="../../lib/template.css" media="screen" type="text/css" rel="stylesheet" /> <link href="../../lib/diagrams.css" media="screen" type="text/css" rel="stylesheet" id="diagrams-css" /> <script type="text/javascript" src="../../lib/jquery.js" id="jquery-js"></script> <script type="text/javascript" src="../../lib/jquery-ui.js"></script> <script type="text/javascript" src="../../lib/template.js"></script> <script type="text/javascript" src="../../lib/tools.tooltip.js"></script> <script type="text/javascript"> if(top === self) { var url = '../../index.html'; var hash = 'org.scalatest.Stopper$'; var anchor = window.location.hash; var anchor_opt = ''; if (anchor.length >= 1) anchor_opt = '@' + anchor.substring(1); window.location.href = url + '#' + hash + anchor_opt; } </script> <script> (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', 'UA-71294502-3', 'auto'); ga('send', 'pageview'); </script> </head> <body class="value"> <!-- Top of doc.scalatest.org [javascript] --> <script type="text/javascript"> var rnd = window.rnd || Math.floor(Math.random()*10e6); var pid204546 = window.pid204546 || rnd; var plc204546 = window.plc204546 || 0; var abkw = window.abkw || ''; var absrc = 'http://ab167933.adbutler-ikon.com/adserve/;ID=167933;size=468x60;setID=204546;type=js;sw='+screen.width+';sh='+screen.height+';spr='+window.devicePixelRatio+';kw='+abkw+';pid='+pid204546+';place='+(plc204546++)+';rnd='+rnd+';click=CLICK_MACRO_PLACEHOLDER'; document.write('<scr'+'ipt src="'+absrc+'" type="text/javascript"></scr'+'ipt>'); </script> <div id="definition"> <a href="Stopper.html" title="Go to companion"><img src="../../lib/object_to_trait_big.png" /></a> <p id="owner"><a href="../package.html" class="extype" name="org">org</a>.<a href="package.html" class="extype" name="org.scalatest">scalatest</a></p> <h1><a href="Stopper.html" title="Go to companion">Stopper</a></h1> </div> <h4 id="signature" class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">object</span> </span> <span class="symbol"> <span class="name">Stopper</span> </span> </h4> <div id="comment" class="fullcommenttop"><div class="comment cmt"><p>Companion object to Stopper that holds a factory method that produces a new <code>Stopper</code> whose <code>stopRequested</code> method returns false until after its <code>requestStop</code> has been invoked. </p></div><dl class="attributes block"> <dt>Source</dt><dd><a href="https://github.com/scalatest/scalatest/tree/release-2.2.4-for-scala-2.11-and-2.10/src/main/scala/org/scalatest/Stopper.scala" target="_blank">Stopper.scala</a></dd></dl><div class="toggleContainer block"> <span class="toggle">Linear Supertypes</span> <div class="superTypes hiddenContent"><span class="extype" name="scala.AnyRef">AnyRef</span>, <span class="extype" name="scala.Any">Any</span></div> </div></div> <div id="mbrsel"> <div id="textfilter"><span class="pre"></span><span class="input"><input id="mbrsel-input" type="text" accesskey="/" /></span><span class="post"></span></div> <div id="order"> <span class="filtertype">Ordering</span> <ol> <li class="alpha in"><span>Alphabetic</span></li> <li class="inherit out"><span>By inheritance</span></li> </ol> </div> <div id="ancestors"> <span class="filtertype">Inherited<br /> </span> <ol id="linearization"> <li class="in" name="org.scalatest.Stopper"><span>Stopper</span></li><li class="in" name="scala.AnyRef"><span>AnyRef</span></li><li class="in" name="scala.Any"><span>Any</span></li> </ol> </div><div id="ancestors"> <span class="filtertype"></span> <ol> <li class="hideall out"><span>Hide All</span></li> <li class="showall in"><span>Show all</span></li> </ol> <a href="http://docs.scala-lang.org/overviews/scaladoc/usage.html#members" target="_blank">Learn more about member selection</a> </div> <div id="visbl"> <span class="filtertype">Visibility</span> <ol><li class="public in"><span>Public</span></li><li class="all out"><span>All</span></li></ol> </div> </div> <div id="template"> <div id="allMembers"> <div id="values" class="values members"> <h3>Value Members</h3> <ol><li name="scala.AnyRef#!=" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="!=(x$1:AnyRef):Boolean"></a> <a id="!=(AnyRef):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span title="gt4s: $bang$eq" class="name">!=</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.Any#!=" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="!=(x$1:Any):Boolean"></a> <a id="!=(Any):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span title="gt4s: $bang$eq" class="name">!=</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div> </li><li name="scala.AnyRef###" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="##():Int"></a> <a id="##():Int"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span title="gt4s: $hash$hash" class="name">##</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Int">Int</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.AnyRef#==" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="==(x$1:AnyRef):Boolean"></a> <a id="==(AnyRef):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span title="gt4s: $eq$eq" class="name">==</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.Any#==" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="==(x$1:Any):Boolean"></a> <a id="==(Any):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span title="gt4s: $eq$eq" class="name">==</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div> </li><li name="scala.Any#asInstanceOf" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="asInstanceOf[T0]:T0"></a> <a id="asInstanceOf[T0]:T0"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">asInstanceOf</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="result">: <span class="extype" name="scala.Any.asInstanceOf.T0">T0</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div> </li><li name="scala.AnyRef#clone" visbl="prt" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="clone():Object"></a> <a id="clone():AnyRef"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">clone</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.AnyRef">AnyRef</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected[<a href="../../java$lang.html" class="extype" name="java.lang">java.lang</a>] </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">()</span> </dd></dl></div> </li><li name="org.scalatest.Stopper#default" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="default:org.scalatest.Stopper"></a> <a id="default:Stopper"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">default</span><span class="result">: <a href="Stopper.html" class="extype" name="org.scalatest.Stopper">Stopper</a></span> </span> </h4> <p class="shortcomment cmt">Factory method that produces a new <code>Stopper</code> whose <code>stopRequested</code> method returns false until after its <code>requestStop</code> has been invoked.</p><div class="fullcomment"><div class="comment cmt"><p>Factory method that produces a new <code>Stopper</code> whose <code>stopRequested</code> method returns false until after its <code>requestStop</code> has been invoked.</p><p>The <code>Stopper</code> returned by this method can be safely used by multiple threads concurrently.</p></div><dl class="paramcmts block"><dt>returns</dt><dd class="cmt"><p>a new default stopper </p></dd></dl></div> </li><li name="scala.AnyRef#eq" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="eq(x$1:AnyRef):Boolean"></a> <a id="eq(AnyRef):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">eq</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.AnyRef#equals" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="equals(x$1:Any):Boolean"></a> <a id="equals(Any):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">equals</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.AnyRef#finalize" visbl="prt" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="finalize():Unit"></a> <a id="finalize():Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">finalize</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected[<a href="../../java$lang.html" class="extype" name="java.lang">java.lang</a>] </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">()</span> </dd></dl></div> </li><li name="scala.AnyRef#getClass" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="getClass():Class[_]"></a> <a id="getClass():Class[_]"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">getClass</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.Class">Class</span>[_]</span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.AnyRef#hashCode" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="hashCode():Int"></a> <a id="hashCode():Int"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">hashCode</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Int">Int</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.Any#isInstanceOf" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="isInstanceOf[T0]:Boolean"></a> <a id="isInstanceOf[T0]:Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">isInstanceOf</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div> </li><li name="scala.AnyRef#ne" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="ne(x$1:AnyRef):Boolean"></a> <a id="ne(AnyRef):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">ne</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.AnyRef#notify" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="notify():Unit"></a> <a id="notify():Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">notify</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.AnyRef#notifyAll" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="notifyAll():Unit"></a> <a id="notifyAll():Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">notifyAll</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.AnyRef#synchronized" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="synchronized[T0](x$1:=&gt;T0):T0"></a> <a id="synchronized[T0](⇒T0):T0"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">synchronized</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="params">(<span name="arg0">arg0: ⇒ <span class="extype" name="java.lang.AnyRef.synchronized.T0">T0</span></span>)</span><span class="result">: <span class="extype" name="java.lang.AnyRef.synchronized.T0">T0</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.AnyRef#toString" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="toString():String"></a> <a id="toString():String"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">toString</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.String">String</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="wait():Unit"></a> <a id="wait():Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">wait</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">()</span> </dd></dl></div> </li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="wait(x$1:Long,x$2:Int):Unit"></a> <a id="wait(Long,Int):Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">wait</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Long">Long</span></span>, <span name="arg1">arg1: <span class="extype" name="scala.Int">Int</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">()</span> </dd></dl></div> </li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="wait(x$1:Long):Unit"></a> <a id="wait(Long):Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">wait</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Long">Long</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">()</span> </dd></dl></div> </li></ol> </div> </div> <div id="inheritedMembers"> <div class="parent" name="scala.AnyRef"> <h3>Inherited from <span class="extype" name="scala.AnyRef">AnyRef</span></h3> </div><div class="parent" name="scala.Any"> <h3>Inherited from <span class="extype" name="scala.Any">Any</span></h3> </div> </div> <div id="groupedMembers"> <div class="group" name="Ungrouped"> <h3>Ungrouped</h3> </div> </div> </div> <div id="tooltip"></div> <div id="footer"> </div> </body> </html>
scalatest/scalatest-website
public/scaladoc/2.2.4/org/scalatest/Stopper$.html
HTML
apache-2.0
23,647
#!/usr/local/bin/python3 # Find the number of elements of a list def lenOf(mylist): return (len(mylist)) print (lenOf("Hello")) print (lenOf("")) print (lenOf([123,123,123]))
mocovenwitch/haskell-learning-notes
python/problem04.py
Python
apache-2.0
181
//===--- GenStruct.cpp - Swift IR Generation For 'struct' Types -----------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This file implements IR generation for struct types. // //===----------------------------------------------------------------------===// #include "GenStruct.h" #include "swift/AST/Types.h" #include "swift/AST/Decl.h" #include "swift/AST/IRGenOptions.h" #include "swift/AST/Pattern.h" #include "swift/AST/SubstitutionMap.h" #include "swift/SIL/SILModule.h" #include "llvm/IR/DerivedTypes.h" #include "llvm/IR/Function.h" #include "clang/AST/ASTContext.h" #include "clang/AST/Decl.h" #include "clang/AST/RecordLayout.h" #include "clang/CodeGen/SwiftCallingConv.h" #include "GenMeta.h" #include "GenRecord.h" #include "GenType.h" #include "IRGenFunction.h" #include "IRGenModule.h" #include "Linking.h" #include "IndirectTypeInfo.h" #include "MemberAccessStrategy.h" #include "NonFixedTypeInfo.h" #include "ResilientTypeInfo.h" #include "StructMetadataLayout.h" #pragma clang diagnostic ignored "-Winconsistent-missing-override" using namespace swift; using namespace irgen; /// The kinds of TypeInfos implementing struct types. enum class StructTypeInfoKind { LoadableStructTypeInfo, FixedStructTypeInfo, ClangRecordTypeInfo, NonFixedStructTypeInfo, ResilientStructTypeInfo }; static StructTypeInfoKind getStructTypeInfoKind(const TypeInfo &type) { return (StructTypeInfoKind) type.getSubclassKind(); } namespace { class StructFieldInfo : public RecordField<StructFieldInfo> { public: StructFieldInfo(VarDecl *field, const TypeInfo &type) : RecordField(type), Field(field) {} /// The field. VarDecl * const Field; StringRef getFieldName() const { return Field->getName().str(); } SILType getType(IRGenModule &IGM, SILType T) const { return T.getFieldType(Field, IGM.getSILModule()); } }; /// A field-info implementation for fields of Clang types. class ClangFieldInfo : public RecordField<ClangFieldInfo> { public: ClangFieldInfo(VarDecl *swiftField, const ElementLayout &layout, unsigned explosionBegin, unsigned explosionEnd) : RecordField(layout, explosionBegin, explosionEnd), Field(swiftField) {} VarDecl * const Field; StringRef getFieldName() const { if (Field) return Field->getName().str(); return "<unimported>"; } SILType getType(IRGenModule &IGM, SILType T) const { if (Field) return T.getFieldType(Field, IGM.getSILModule()); // The Swift-field-less cases use opaque storage, which is // guaranteed to ignore the type passed to it. return {}; } }; /// A common base class for structs. template <class Impl, class Base, class FieldInfoType = StructFieldInfo> class StructTypeInfoBase : public RecordTypeInfo<Impl, Base, FieldInfoType> { typedef RecordTypeInfo<Impl, Base, FieldInfoType> super; protected: template <class... As> StructTypeInfoBase(StructTypeInfoKind kind, As &&...args) : super(std::forward<As>(args)...) { super::setSubclassKind((unsigned) kind); } using super::asImpl; public: const FieldInfoType &getFieldInfo(VarDecl *field) const { // FIXME: cache the physical field index in the VarDecl. for (auto &fieldInfo : asImpl().getFields()) { if (fieldInfo.Field == field) return fieldInfo; } llvm_unreachable("field not in struct?"); } /// Given a full struct explosion, project out a single field. void projectFieldFromExplosion(IRGenFunction &IGF, Explosion &in, VarDecl *field, Explosion &out) const { auto &fieldInfo = getFieldInfo(field); // If the field requires no storage, there's nothing to do. if (fieldInfo.isEmpty()) return; // Otherwise, project from the base. auto fieldRange = fieldInfo.getProjectionRange(); auto elements = in.getRange(fieldRange.first, fieldRange.second); out.add(elements); } /// Given the address of a tuple, project out the address of a /// single element. Address projectFieldAddress(IRGenFunction &IGF, Address addr, SILType T, VarDecl *field) const { auto &fieldInfo = getFieldInfo(field); if (fieldInfo.isEmpty()) return fieldInfo.getTypeInfo().getUndefAddress(); auto offsets = asImpl().getNonFixedOffsets(IGF, T); return fieldInfo.projectAddress(IGF, addr, offsets); } /// Return the constant offset of a field as a SizeTy, or nullptr if the /// field is not at a fixed offset. llvm::Constant *getConstantFieldOffset(IRGenModule &IGM, VarDecl *field) const { auto &fieldInfo = getFieldInfo(field); if (fieldInfo.getKind() == ElementLayout::Kind::Fixed) { return llvm::ConstantInt::get(IGM.SizeTy, fieldInfo.getFixedByteOffset().getValue()); } return nullptr; } MemberAccessStrategy getFieldAccessStrategy(IRGenModule &IGM, SILType T, VarDecl *field) const { auto &fieldInfo = getFieldInfo(field); switch (fieldInfo.getKind()) { case ElementLayout::Kind::Fixed: case ElementLayout::Kind::Empty: return MemberAccessStrategy::getDirectFixed( fieldInfo.getFixedByteOffset()); case ElementLayout::Kind::InitialNonFixedSize: return MemberAccessStrategy::getDirectFixed(Size(0)); case ElementLayout::Kind::NonFixed: return asImpl().getNonFixedFieldAccessStrategy(IGM, T, fieldInfo); } llvm_unreachable("bad field layout kind"); } unsigned getFieldIndex(IRGenModule &IGM, VarDecl *field) const { auto &fieldInfo = getFieldInfo(field); return fieldInfo.getStructIndex(); } // For now, just use extra inhabitants from the first field. // FIXME: generalize bool mayHaveExtraInhabitants(IRGenModule &IGM) const override { if (asImpl().getFields().empty()) return false; return asImpl().getFields()[0].getTypeInfo().mayHaveExtraInhabitants(IGM); } // This is dead code in NonFixedStructTypeInfo. unsigned getFixedExtraInhabitantCount(IRGenModule &IGM) const { if (asImpl().getFields().empty()) return 0; auto &fieldTI = cast<FixedTypeInfo>(asImpl().getFields()[0].getTypeInfo()); return fieldTI.getFixedExtraInhabitantCount(IGM); } // This is dead code in NonFixedStructTypeInfo. APInt getFixedExtraInhabitantValue(IRGenModule &IGM, unsigned bits, unsigned index) const { auto &fieldTI = cast<FixedTypeInfo>(asImpl().getFields()[0].getTypeInfo()); return fieldTI.getFixedExtraInhabitantValue(IGM, bits, index); } // This is dead code in NonFixedStructTypeInfo. APInt getFixedExtraInhabitantMask(IRGenModule &IGM) const { if (asImpl().getFields().empty()) return APInt(); // Currently we only use the first field's extra inhabitants. The other // fields can be ignored. const FixedTypeInfo &fieldTI = cast<FixedTypeInfo>(asImpl().getFields()[0].getTypeInfo()); auto targetSize = asImpl().getFixedSize().getValueInBits(); if (fieldTI.isKnownEmpty(ResilienceExpansion::Maximal)) return APInt(targetSize, 0); APInt fieldMask = fieldTI.getFixedExtraInhabitantMask(IGM); if (targetSize > fieldMask.getBitWidth()) fieldMask = fieldMask.zext(targetSize); return fieldMask; } llvm::Value *getExtraInhabitantIndex(IRGenFunction &IGF, Address structAddr, SILType structType) const override { auto &field = asImpl().getFields()[0]; Address fieldAddr = asImpl().projectFieldAddress(IGF, structAddr, structType, field.Field); return field.getTypeInfo().getExtraInhabitantIndex(IGF, fieldAddr, field.getType(IGF.IGM, structType)); } void storeExtraInhabitant(IRGenFunction &IGF, llvm::Value *index, Address structAddr, SILType structType) const override { auto &field = asImpl().getFields()[0]; Address fieldAddr = asImpl().projectFieldAddress(IGF, structAddr, structType, field.Field); field.getTypeInfo().storeExtraInhabitant(IGF, index, fieldAddr, field.getType(IGF.IGM, structType)); } }; /// A type implementation for loadable record types imported from Clang. class ClangRecordTypeInfo final : public StructTypeInfoBase<ClangRecordTypeInfo, LoadableTypeInfo, ClangFieldInfo> { const clang::RecordDecl *ClangDecl; public: ClangRecordTypeInfo(ArrayRef<ClangFieldInfo> fields, unsigned explosionSize, llvm::Type *storageType, Size size, SpareBitVector &&spareBits, Alignment align, const clang::RecordDecl *clangDecl) : StructTypeInfoBase(StructTypeInfoKind::ClangRecordTypeInfo, fields, explosionSize, storageType, size, std::move(spareBits), align, IsPOD, IsFixedSize), ClangDecl(clangDecl) { } void initializeFromParams(IRGenFunction &IGF, Explosion &params, Address addr, SILType T) const override { ClangRecordTypeInfo::initialize(IGF, params, addr); } void addToAggLowering(IRGenModule &IGM, SwiftAggLowering &lowering, Size offset) const override { lowering.addTypedData(ClangDecl, offset.asCharUnits()); } llvm::NoneType getNonFixedOffsets(IRGenFunction &IGF) const { return None; } llvm::NoneType getNonFixedOffsets(IRGenFunction &IGF, SILType T) const { return None; } MemberAccessStrategy getNonFixedFieldAccessStrategy(IRGenModule &IGM, SILType T, const ClangFieldInfo &field) const { llvm_unreachable("non-fixed field in Clang type?"); } }; /// A type implementation for loadable struct types. class LoadableStructTypeInfo final : public StructTypeInfoBase<LoadableStructTypeInfo, LoadableTypeInfo> { public: // FIXME: Spare bits between struct members. LoadableStructTypeInfo(ArrayRef<StructFieldInfo> fields, unsigned explosionSize, llvm::Type *storageType, Size size, SpareBitVector &&spareBits, Alignment align, IsPOD_t isPOD, IsFixedSize_t alwaysFixedSize) : StructTypeInfoBase(StructTypeInfoKind::LoadableStructTypeInfo, fields, explosionSize, storageType, size, std::move(spareBits), align, isPOD, alwaysFixedSize) {} void addToAggLowering(IRGenModule &IGM, SwiftAggLowering &lowering, Size offset) const override { for (auto &field : getFields()) { auto fieldOffset = offset + field.getFixedByteOffset(); cast<LoadableTypeInfo>(field.getTypeInfo()) .addToAggLowering(IGM, lowering, fieldOffset); } } void initializeFromParams(IRGenFunction &IGF, Explosion &params, Address addr, SILType T) const override { LoadableStructTypeInfo::initialize(IGF, params, addr); } llvm::NoneType getNonFixedOffsets(IRGenFunction &IGF) const { return None; } llvm::NoneType getNonFixedOffsets(IRGenFunction &IGF, SILType T) const { return None; } MemberAccessStrategy getNonFixedFieldAccessStrategy(IRGenModule &IGM, SILType T, const StructFieldInfo &field) const { llvm_unreachable("non-fixed field in loadable type?"); } }; /// A type implementation for non-loadable but fixed-size struct types. class FixedStructTypeInfo final : public StructTypeInfoBase<FixedStructTypeInfo, IndirectTypeInfo<FixedStructTypeInfo, FixedTypeInfo>> { public: // FIXME: Spare bits between struct members. FixedStructTypeInfo(ArrayRef<StructFieldInfo> fields, llvm::Type *T, Size size, SpareBitVector &&spareBits, Alignment align, IsPOD_t isPOD, IsBitwiseTakable_t isBT, IsFixedSize_t alwaysFixedSize) : StructTypeInfoBase(StructTypeInfoKind::FixedStructTypeInfo, fields, T, size, std::move(spareBits), align, isPOD, isBT, alwaysFixedSize) {} llvm::NoneType getNonFixedOffsets(IRGenFunction &IGF) const { return None; } llvm::NoneType getNonFixedOffsets(IRGenFunction &IGF, SILType T) const { return None; } MemberAccessStrategy getNonFixedFieldAccessStrategy(IRGenModule &IGM, SILType T, const StructFieldInfo &field) const { llvm_unreachable("non-fixed field in fixed struct?"); } }; struct GetStartOfFieldOffsets : StructMetadataScanner<GetStartOfFieldOffsets> { GetStartOfFieldOffsets(IRGenModule &IGM, StructDecl *target) : StructMetadataScanner(IGM, target) {} Size StartOfFieldOffsets = Size::invalid(); void noteAddressPoint() { assert(StartOfFieldOffsets == Size::invalid() && "found field offsets before address point?"); NextOffset = Size(0); } void noteStartOfFieldOffsets() { StartOfFieldOffsets = NextOffset; } }; /// Find the beginning of the field offset vector in a struct's metadata. static Address emitAddressOfFieldOffsetVector(IRGenFunction &IGF, StructDecl *S, llvm::Value *metadata) { // Find where the field offsets begin. GetStartOfFieldOffsets scanner(IGF.IGM, S); scanner.layout(); assert(scanner.StartOfFieldOffsets != Size::invalid() && "did not find start of field offsets?!"); Size StartOfFieldOffsets = scanner.StartOfFieldOffsets; // Find that offset into the metadata. llvm::Value *fieldVector = IGF.Builder.CreateBitCast(metadata, IGF.IGM.SizeTy->getPointerTo()); return IGF.Builder.CreateConstArrayGEP( Address(fieldVector, IGF.IGM.getPointerAlignment()), StartOfFieldOffsets / IGF.IGM.getPointerSize(), StartOfFieldOffsets); } /// Accessor for the non-fixed offsets of a struct type. class StructNonFixedOffsets : public NonFixedOffsetsImpl { SILType TheStruct; public: StructNonFixedOffsets(SILType type) : TheStruct(type) { assert(TheStruct.getStructOrBoundGenericStruct()); } llvm::Value *getOffsetForIndex(IRGenFunction &IGF, unsigned index) override { // Get the field offset vector from the struct metadata. llvm::Value *metadata = IGF.emitTypeMetadataRefForLayout(TheStruct); Address fieldVector = emitAddressOfFieldOffsetVector(IGF, TheStruct.getStructOrBoundGenericStruct(), metadata); // Grab the indexed offset. fieldVector = IGF.Builder.CreateConstArrayGEP(fieldVector, index, IGF.IGM.getPointerSize()); return IGF.Builder.CreateLoad(fieldVector); } MemberAccessStrategy getFieldAccessStrategy(IRGenModule &IGM, unsigned nonFixedIndex) { GetStartOfFieldOffsets scanner(IGM, TheStruct.getStructOrBoundGenericStruct()); scanner.layout(); Size indirectOffset = scanner.StartOfFieldOffsets + IGM.getPointerSize() * nonFixedIndex; return MemberAccessStrategy::getIndirectFixed(indirectOffset, MemberAccessStrategy::OffsetKind::Bytes_Word); } }; /// A type implementation for non-fixed struct types. class NonFixedStructTypeInfo final : public StructTypeInfoBase<NonFixedStructTypeInfo, WitnessSizedTypeInfo<NonFixedStructTypeInfo>> { public: NonFixedStructTypeInfo(ArrayRef<StructFieldInfo> fields, llvm::Type *T, Alignment align, IsPOD_t isPOD, IsBitwiseTakable_t isBT) : StructTypeInfoBase(StructTypeInfoKind::NonFixedStructTypeInfo, fields, T, align, isPOD, isBT) { } // We have an indirect schema. void getSchema(ExplosionSchema &s) const override { s.add(ExplosionSchema::Element::forAggregate(getStorageType(), getBestKnownAlignment())); } StructNonFixedOffsets getNonFixedOffsets(IRGenFunction &IGF, SILType T) const { return StructNonFixedOffsets(T); } MemberAccessStrategy getNonFixedFieldAccessStrategy(IRGenModule &IGM, SILType T, const StructFieldInfo &field) const { return StructNonFixedOffsets(T).getFieldAccessStrategy(IGM, field.getNonFixedElementIndex()); } void initializeMetadata(IRGenFunction &IGF, llvm::Value *metadata, llvm::Value *vwtable, SILType T) const override { // Get the field offset vector. llvm::Value *fieldVector = emitAddressOfFieldOffsetVector(IGF, T.getStructOrBoundGenericStruct(), metadata).getAddress(); // Collect the stored properties of the type. llvm::SmallVector<VarDecl*, 4> storedProperties; for (auto prop : T.getStructOrBoundGenericStruct() ->getStoredProperties()) { storedProperties.push_back(prop); } // Fill out an array with the field type layout records. Address fields = IGF.createAlloca( llvm::ArrayType::get(IGF.IGM.Int8PtrPtrTy, storedProperties.size()), IGF.IGM.getPointerAlignment(), "structFields"); IGF.Builder.CreateLifetimeStart(fields, IGF.IGM.getPointerSize() * storedProperties.size()); fields = IGF.Builder.CreateStructGEP(fields, 0, Size(0)); unsigned index = 0; for (auto prop : storedProperties) { auto propTy = T.getFieldType(prop, IGF.getSILModule()); llvm::Value *metadata = IGF.emitTypeLayoutRef(propTy); Address field = IGF.Builder.CreateConstArrayGEP(fields, index, IGF.IGM.getPointerSize()); IGF.Builder.CreateStore(metadata, field); ++index; } // Ask the runtime to lay out the struct. auto numFields = llvm::ConstantInt::get(IGF.IGM.SizeTy, storedProperties.size()); IGF.Builder.CreateCall(IGF.IGM.getInitStructMetadataUniversalFn(), {numFields, fields.getAddress(), fieldVector, vwtable}); IGF.Builder.CreateLifetimeEnd(fields, IGF.IGM.getPointerSize() * storedProperties.size()); } }; class StructTypeBuilder : public RecordTypeBuilder<StructTypeBuilder, StructFieldInfo, VarDecl*> { llvm::StructType *StructTy; CanType TheStruct; public: StructTypeBuilder(IRGenModule &IGM, llvm::StructType *structTy, CanType type) : RecordTypeBuilder(IGM), StructTy(structTy), TheStruct(type) { } LoadableStructTypeInfo *createLoadable(ArrayRef<StructFieldInfo> fields, StructLayout &&layout, unsigned explosionSize) { return LoadableStructTypeInfo::create(fields, explosionSize, layout.getType(), layout.getSize(), std::move(layout.getSpareBits()), layout.getAlignment(), layout.isPOD(), layout.isAlwaysFixedSize()); } FixedStructTypeInfo *createFixed(ArrayRef<StructFieldInfo> fields, StructLayout &&layout) { return FixedStructTypeInfo::create(fields, layout.getType(), layout.getSize(), std::move(layout.getSpareBits()), layout.getAlignment(), layout.isPOD(), layout.isBitwiseTakable(), layout.isAlwaysFixedSize()); } NonFixedStructTypeInfo *createNonFixed(ArrayRef<StructFieldInfo> fields, StructLayout &&layout) { return NonFixedStructTypeInfo::create(fields, layout.getType(), layout.getAlignment(), layout.isPOD(), layout.isBitwiseTakable()); } StructFieldInfo getFieldInfo(unsigned index, VarDecl *field, const TypeInfo &fieldTI) { return StructFieldInfo(field, fieldTI); } SILType getType(VarDecl *field) { assert(field->getDeclContext() == TheStruct->getAnyNominal()); auto silType = SILType::getPrimitiveAddressType(TheStruct); return silType.getFieldType(field, IGM.getSILModule()); } StructLayout performLayout(ArrayRef<const TypeInfo *> fieldTypes) { return StructLayout(IGM, TheStruct, LayoutKind::NonHeapObject, LayoutStrategy::Optimal, fieldTypes, StructTy); } }; /// A class for lowering Clang records. class ClangRecordLowering { IRGenModule &IGM; StructDecl *SwiftDecl; SILType SwiftType; const clang::RecordDecl *ClangDecl; const clang::ASTContext &ClangContext; const clang::ASTRecordLayout &ClangLayout; const Size TotalStride; const Alignment TotalAlignment; SpareBitVector SpareBits; SmallVector<llvm::Type *, 8> LLVMFields; SmallVector<ClangFieldInfo, 8> FieldInfos; Size NextOffset = Size(0); unsigned NextExplosionIndex = 0; public: ClangRecordLowering(IRGenModule &IGM, StructDecl *swiftDecl, const clang::RecordDecl *clangDecl, SILType swiftType) : IGM(IGM), SwiftDecl(swiftDecl), SwiftType(swiftType), ClangDecl(clangDecl), ClangContext(clangDecl->getASTContext()), ClangLayout(ClangContext.getASTRecordLayout(clangDecl)), TotalStride(Size(ClangLayout.getSize().getQuantity())), TotalAlignment(Alignment(ClangLayout.getAlignment().getQuantity())) { SpareBits.reserve(TotalStride.getValue() * 8); } void collectRecordFields() { if (ClangDecl->isUnion()) { collectUnionFields(); } else { collectStructFields(); } } const TypeInfo *createTypeInfo(llvm::StructType *llvmType) { llvmType->setBody(LLVMFields, /*packed*/ true); return ClangRecordTypeInfo::create(FieldInfos, NextExplosionIndex, llvmType, TotalStride, std::move(SpareBits), TotalAlignment, ClangDecl); } private: /// Collect all the fields of a union. void collectUnionFields() { addOpaqueField(Size(0), TotalStride); } static bool isImportOfClangField(VarDecl *swiftField, const clang::FieldDecl *clangField) { assert(swiftField->hasClangNode()); return (swiftField->getClangNode().castAsDecl() == clangField); } void collectStructFields() { auto cfi = ClangDecl->field_begin(), cfe = ClangDecl->field_end(); auto swiftProperties = SwiftDecl->getStoredProperties(); auto sfi = swiftProperties.begin(), sfe = swiftProperties.end(); while (cfi != cfe) { const clang::FieldDecl *clangField = *cfi++; // Bitfields are currently never mapped, but that doesn't mean // we don't have to copy them. if (clangField->isBitField()) { // Collect all of the following bitfields. unsigned bitStart = ClangLayout.getFieldOffset(clangField->getFieldIndex()); unsigned bitEnd = bitStart + clangField->getBitWidthValue(ClangContext); while (cfi != cfe && (*cfi)->isBitField()) { clangField = *cfi++; unsigned nextStart = ClangLayout.getFieldOffset(clangField->getFieldIndex()); assert(nextStart >= bitEnd && "laying out bit-fields out of order?"); // In a heuristic effort to reduce the number of weird-sized // fields, whenever we see a bitfield starting on a 32-bit // boundary, start a new storage unit. if (nextStart % 32 == 0) { addOpaqueBitField(bitStart, bitEnd); bitStart = nextStart; } bitEnd = nextStart + clangField->getBitWidthValue(ClangContext); } addOpaqueBitField(bitStart, bitEnd); continue; } VarDecl *swiftField; if (sfi != sfe) { swiftField = *sfi; if (isImportOfClangField(swiftField, clangField)) { ++sfi; } else { swiftField = nullptr; } } else { swiftField = nullptr; } // Try to position this field. If this fails, it's because we // didn't lay out padding correctly. addStructField(clangField, swiftField); } assert(sfi == sfe && "more Swift fields than there were Clang fields?"); // We never take advantage of tail padding, because that would prevent // us from passing the address of the object off to C, which is a pretty // likely scenario for imported C types. assert(NextOffset <= TotalStride); assert(SpareBits.size() <= TotalStride.getValueInBits()); if (NextOffset < TotalStride) { addPaddingField(TotalStride); } } /// Place the next struct field at its appropriate offset. void addStructField(const clang::FieldDecl *clangField, VarDecl *swiftField) { unsigned fieldOffset = ClangLayout.getFieldOffset(clangField->getFieldIndex()); assert(!clangField->isBitField()); Size offset(fieldOffset / 8); // If we have a Swift import of this type, use our lowered information. if (swiftField) { auto &fieldTI = cast<LoadableTypeInfo>( IGM.getTypeInfo(SwiftType.getFieldType(swiftField, IGM.getSILModule()))); addField(swiftField, offset, fieldTI); return; } // Otherwise, add it as an opaque blob. auto fieldSize = ClangContext.getTypeSizeInChars(clangField->getType()); return addOpaqueField(offset, Size(fieldSize.getQuantity())); } /// Add opaque storage for bitfields spanning the given range of bits. void addOpaqueBitField(unsigned bitBegin, unsigned bitEnd) { assert(bitBegin <= bitEnd); // No need to add storage for zero-width bitfields. if (bitBegin == bitEnd) return; // Round up to an even number of bytes. assert(bitBegin % 8 == 0); Size offset = Size(bitBegin / 8); Size byteLength = Size((bitEnd - bitBegin + 7) / 8); addOpaqueField(offset, byteLength); } /// Add opaque storage at the given offset. void addOpaqueField(Size offset, Size fieldSize) { // No need to add storage for zero-size fields (e.g. incomplete array // decls). if (fieldSize.isZero()) return; auto &opaqueTI = IGM.getOpaqueStorageTypeInfo(fieldSize, Alignment(1)); addField(nullptr, offset, opaqueTI); } /// Add storage for an (optional) Swift field at the given offset. void addField(VarDecl *swiftField, Size offset, const LoadableTypeInfo &fieldType) { assert(offset >= NextOffset && "adding fields out of order"); // Add a padding field if required. if (offset != NextOffset) addPaddingField(offset); addFieldInfo(swiftField, fieldType); } /// Add information to track a value field at the current offset. void addFieldInfo(VarDecl *swiftField, const LoadableTypeInfo &fieldType) { unsigned explosionSize = fieldType.getExplosionSize(); unsigned explosionBegin = NextExplosionIndex; NextExplosionIndex += explosionSize; unsigned explosionEnd = NextExplosionIndex; ElementLayout layout = ElementLayout::getIncomplete(fieldType); layout.completeFixed(fieldType.isPOD(ResilienceExpansion::Maximal), NextOffset, LLVMFields.size()); FieldInfos.push_back( ClangFieldInfo(swiftField, layout, explosionBegin, explosionEnd)); LLVMFields.push_back(fieldType.getStorageType()); NextOffset += fieldType.getFixedSize(); SpareBits.append(fieldType.getSpareBits()); } /// Add padding to get up to the given offset. void addPaddingField(Size offset) { assert(offset > NextOffset); Size count = offset - NextOffset; LLVMFields.push_back(llvm::ArrayType::get(IGM.Int8Ty, count.getValue())); NextOffset = offset; SpareBits.appendSetBits(count.getValueInBits()); } }; } // end anonymous namespace /// A convenient macro for delegating an operation to all of the /// various struct implementations. #define FOR_STRUCT_IMPL(IGF, type, op, ...) do { \ auto &structTI = IGF.getTypeInfo(type); \ switch (getStructTypeInfoKind(structTI)) { \ case StructTypeInfoKind::ClangRecordTypeInfo: \ return structTI.as<ClangRecordTypeInfo>().op(IGF, __VA_ARGS__); \ case StructTypeInfoKind::LoadableStructTypeInfo: \ return structTI.as<LoadableStructTypeInfo>().op(IGF, __VA_ARGS__); \ case StructTypeInfoKind::FixedStructTypeInfo: \ return structTI.as<FixedStructTypeInfo>().op(IGF, __VA_ARGS__); \ case StructTypeInfoKind::NonFixedStructTypeInfo: \ return structTI.as<NonFixedStructTypeInfo>().op(IGF, __VA_ARGS__); \ case StructTypeInfoKind::ResilientStructTypeInfo: \ llvm_unreachable("resilient structs are opaque"); \ } \ llvm_unreachable("bad struct type info kind!"); \ } while (0) Address irgen::projectPhysicalStructMemberAddress(IRGenFunction &IGF, Address base, SILType baseType, VarDecl *field) { FOR_STRUCT_IMPL(IGF, baseType, projectFieldAddress, base, baseType, field); } void irgen::projectPhysicalStructMemberFromExplosion(IRGenFunction &IGF, SILType baseType, Explosion &base, VarDecl *field, Explosion &out) { FOR_STRUCT_IMPL(IGF, baseType, projectFieldFromExplosion, base, field, out); } llvm::Constant *irgen::emitPhysicalStructMemberFixedOffset(IRGenModule &IGM, SILType baseType, VarDecl *field) { FOR_STRUCT_IMPL(IGM, baseType, getConstantFieldOffset, field); } MemberAccessStrategy irgen::getPhysicalStructMemberAccessStrategy(IRGenModule &IGM, SILType baseType, VarDecl *field) { FOR_STRUCT_IMPL(IGM, baseType, getFieldAccessStrategy, baseType, field); } unsigned irgen::getPhysicalStructFieldIndex(IRGenModule &IGM, SILType baseType, VarDecl *field) { FOR_STRUCT_IMPL(IGM, baseType, getFieldIndex, field); } void IRGenModule::emitStructDecl(StructDecl *st) { emitStructMetadata(*this, st); emitNestedTypeDecls(st->getMembers()); if (shouldEmitOpaqueTypeMetadataRecord(st)) { emitOpaqueTypeMetadataRecord(st); return; } emitFieldMetadataRecord(st); } namespace { /// A type implementation for resilient struct types. This is not a /// StructTypeInfoBase at all, since we don't know anything about /// the struct's fields. class ResilientStructTypeInfo : public ResilientTypeInfo<ResilientStructTypeInfo> { public: ResilientStructTypeInfo(llvm::Type *T) : ResilientTypeInfo(T) { setSubclassKind((unsigned) StructTypeInfoKind::ResilientStructTypeInfo); } }; } // end anonymous namespace const TypeInfo *TypeConverter::convertResilientStruct() { llvm::Type *storageType = IGM.OpaquePtrTy->getElementType(); return new ResilientStructTypeInfo(storageType); } const TypeInfo *TypeConverter::convertStructType(TypeBase *key, CanType type, StructDecl *D) { // All resilient structs have the same opaque lowering, since they are // indistinguishable as values. if (IGM.isResilient(D, ResilienceExpansion::Maximal)) return &getResilientStructTypeInfo(); // Create the struct type. auto ty = IGM.createNominalType(type); // Register a forward declaration before we look at any of the child types. addForwardDecl(key, ty); // Use different rules for types imported from C. if (D->hasClangNode()) { const clang::Decl *clangDecl = D->getClangNode().getAsDecl(); assert(clangDecl && "Swift struct from an imported C macro?"); if (auto clangRecord = dyn_cast<clang::RecordDecl>(clangDecl)) { ClangRecordLowering lowering(IGM, D, clangRecord, SILType::getPrimitiveObjectType(type)); lowering.collectRecordFields(); return lowering.createTypeInfo(ty); } else if (isa<clang::EnumDecl>(clangDecl)) { // Fall back to Swift lowering for the enum's representation as a struct. assert(std::distance(D->getStoredProperties().begin(), D->getStoredProperties().end()) == 1 && "Struct representation of a Clang enum should wrap one value"); } else if (clangDecl->hasAttr<clang::SwiftNewtypeAttr>()) { // Fall back to Swift lowering for the underlying type's // representation as a struct member. assert(std::distance(D->getStoredProperties().begin(), D->getStoredProperties().end()) == 1 && "Struct representation of a swift_newtype should wrap one value"); } else { llvm_unreachable("Swift struct represents unexpected imported type"); } } // Collect all the fields from the type. SmallVector<VarDecl*, 8> fields; for (VarDecl *VD : D->getStoredProperties()) fields.push_back(VD); // Build the type. StructTypeBuilder builder(IGM, ty, type); return builder.layout(fields); }
tardieu/swift
lib/IRGen/GenStruct.cpp
C++
apache-2.0
36,415
<!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 (version 1.7.0_11) on Thu Sep 05 22:50:45 CEST 2013 --> <title>Canonical (Groovy 2.1.7)</title> <meta name="date" content="2013-09-05"> <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="Canonical (Groovy 2.1.7)"; } //--> </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 class="navBarCell1Rev">Class</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><a href="../../groovy/transform/AutoExternalize.html" title="annotation in groovy.transform"><span class="strong">Prev Class</span></a></li> <li><a href="../../groovy/transform/CompilationUnitAware.html" title="interface in groovy.transform"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../index.html?groovy/transform/Canonical.html" target="_top">Frames</a></li> <li><a href="Canonical.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> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Required&nbsp;|&nbsp;</li> <li><a href="#annotation_type_optional_element_summary">Optional</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#annotation_type_element_detail">Element</a></li> </ul> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">groovy.transform</div> <h2 title="Annotation Type Canonical" class="title">Annotation Type Canonical</h2> </div> <div class="contentContainer"> <div class="description"> <ul class="blockList"> <li class="blockList"> <hr> <br> <pre><a href="http://docs.oracle.com/javase/7/docs/api/java/lang/annotation/Documented.html?is-external=true" title="class or interface in java.lang.annotation">@Documented</a> <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/annotation/Retention.html?is-external=true" title="class or interface in java.lang.annotation">@Retention</a>(<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/annotation/Retention.html?is-external=true#value()" title="class or interface in java.lang.annotation">value</a>=<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/annotation/RetentionPolicy.html?is-external=true#SOURCE" title="class or interface in java.lang.annotation">SOURCE</a>) <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/annotation/Target.html?is-external=true" title="class or interface in java.lang.annotation">@Target</a>(<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/annotation/Target.html?is-external=true#value()" title="class or interface in java.lang.annotation">value</a>=<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/annotation/ElementType.html?is-external=true#TYPE" title="class or interface in java.lang.annotation">TYPE</a>) public @interface <span class="strong">Canonical</span></pre> <div class="block">Class annotation used to assist in the creation of mutable classes. <p> It allows you to write classes in this shortened form: <pre> <code>@Canonical</code> class Customer { String first, last int age Date since Collection favItems = ['Food'] def object } def d = new Date() def anyObject = new Object() def c1 = new Customer(first:'Tom', last:'Jones', age:21, since:d, favItems:['Books', 'Games'], object: anyObject) def c2 = new Customer('Tom', 'Jones', 21, d, ['Books', 'Games'], anyObject) assert c1 == c2 </pre> If you set the autoDefaults flag to true, you don't need to provide all arguments in constructors calls, in this case all properties not present are initialized to the default value, e.g.: <pre> def c3 = new Customer(last: 'Jones', age: 21) def c4 = new Customer('Tom', 'Jones') assert null == c3.since assert 0 == c4.age assert c3.favItems == ['Food'] && c4.favItems == ['Food'] </pre> The <code>@Canonical</code> annotation instructs the compiler to execute an AST transformation which adds positional constructors, equals, hashCode and a pretty print toString to your class. There are additional annotations if you only need some of the functionality: <code>@EqualsAndHashCode</code>, <code>@ToString</code> and <code>@TupleConstructor</code>. In addition, you can add one of the other annotations if you need to further customize the behavior of the AST transformation. <p> A class created in this way has the following characteristics: <ul> <li>A no-arg constructor is provided which allows you to set properties by name using Groovy's normal bean conventions. <li>Tuple-style constructors are provided which allow you to set properties in the same order as they are defined. <li>Default <code>equals</code>, <code>hashCode</code> and <code>toString</code> methods are provided based on the property values. Though not normally required, you may write your own implementations of these methods. For <code>equals</code> and <code>hashCode</code>, if you do write your own method, it is up to you to obey the general contract for <code>equals</code> methods and supply a corresponding matching <code>hashCode</code> method. If you do provide one of these methods explicitly, the default implementation will be made available in a private "underscore" variant which you can call. E.g., you could provide a (not very elegant) multi-line formatted <code>toString</code> method for <code>Customer</code> above as follows: <pre> String toString() { _toString().replaceAll(/\(/, '(\n\t').replaceAll(/\)/, '\n)').replaceAll(/, /, '\n\t') } </pre> If an "underscore" version of the respective method already exists, then no default implementation is provided. </ul> <p> If you want similar functionality to what this annotation provides but also require immutability, see the <code>@</code><a href="../../groovy/transform/Immutable.html" title="annotation in groovy.transform"><code>Immutable</code></a> annotation. <p> Limitations: <ul> <li>If you explicitly add your own constructors, then the transformation will not add any other constructor to the class</li> <li>Groovy's normal map-style naming conventions will not be available if the first property has type <code>LinkedHashMap</code> or if there is a single Map, AbstractMap or HashMap property</li> </ul></div> <dl><dt><span class="strong">Since:</span></dt> <dd>1.8.0</dd> <dt><span class="strong">Author:</span></dt> <dd>Paulo Poiati, Paul King</dd> <dt><span class="strong">See Also:</span></dt><dd><a href="../../groovy/transform/EqualsAndHashCode.html" title="annotation in groovy.transform"><code>EqualsAndHashCode</code></a>, <a href="../../groovy/transform/ToString.html" title="annotation in groovy.transform"><code>ToString</code></a>, <a href="../../groovy/transform/TupleConstructor.html" title="annotation in groovy.transform"><code>TupleConstructor</code></a>, <a href="../../groovy/transform/Immutable.html" title="annotation in groovy.transform"><code>Immutable</code></a></dd></dl> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- =========== ANNOTATION TYPE OPTIONAL MEMBER SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="annotation_type_optional_element_summary"> <!-- --> </a> <h3>Optional Element Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Optional Element Summary table, listing optional elements, and an explanation"> <caption><span>Optional Elements</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Optional Element and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="http://docs.oracle.com/javase/7/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>[]</code></td> <td class="colLast"><code><strong><a href="../../groovy/transform/Canonical.html#excludes()">excludes</a></strong></code> <div class="block">List of field and/or property names to exclude.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="http://docs.oracle.com/javase/7/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>[]</code></td> <td class="colLast"><code><strong><a href="../../groovy/transform/Canonical.html#includes()">includes</a></strong></code> <div class="block">List of field and/or property names to include.</div> </td> </tr> </table> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ============ ANNOTATION TYPE MEMBER DETAIL =========== --> <ul class="blockList"> <li class="blockList"><a name="annotation_type_element_detail"> <!-- --> </a> <h3>Element Detail</h3> <a name="excludes()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>excludes</h4> <pre>public abstract&nbsp;<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>[]&nbsp;excludes</pre> <div class="block">List of field and/or property names to exclude. Must not be used if 'includes' is used. For convenience, a String with comma separated names can be used in addition to an array (using Groovy's literal list notation) of String values. If the <code>@Canonical</code> behavior is customised by using it in conjunction with one of the more specific related annotations (i.e. <code>@ToString</code>, <code>@EqualsAndHashCode</code> or <code>@TupleConstructor</code>), then the value of this attribute can be overriden within the more specific annotation.</div> <dl> <dt>Default:</dt> <dd>{}</dd> </dl> </li> </ul> <a name="includes()"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>includes</h4> <pre>public abstract&nbsp;<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>[]&nbsp;includes</pre> <div class="block">List of field and/or property names to include. Must not be used if 'excludes' is used. For convenience, a String with comma separated names can be used in addition to an array (using Groovy's literal list notation) of String values. If the <code>@Canonical</code> behavior is customised by using it in conjunction with one of the more specific related annotations (i.e. <code>@ToString</code>, <code>@EqualsAndHashCode</code> or <code>@TupleConstructor</code>), then the value of this attribute can be overriden within the more specific annotation.</div> <dl> <dt>Default:</dt> <dd>{}</dd> </dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= 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 class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../deprecated-list.html">Deprecated</a></li> <li><a href="../../index-all.html">Index</a></li> <li><a href="../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><em>Copyright &amp;copy; 2003-2013 The Codehaus. All rights reserved.</em></div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../groovy/transform/AutoExternalize.html" title="annotation in groovy.transform"><span class="strong">Prev Class</span></a></li> <li><a href="../../groovy/transform/CompilationUnitAware.html" title="interface in groovy.transform"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../index.html?groovy/transform/Canonical.html" target="_top">Frames</a></li> <li><a href="Canonical.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> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Required&nbsp;|&nbsp;</li> <li><a href="#annotation_type_optional_element_summary">Optional</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#annotation_type_element_detail">Element</a></li> </ul> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
Selventa/model-builder
tools/groovy/doc/html/api/groovy/transform/Canonical.html
HTML
apache-2.0
14,043
<!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_162) on Tue Oct 02 11:58:29 CEST 2018 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Uses of Class de.uni_mannheim.informatik.dws.winter.webtables.TableMapping (WInte.r 1.3 API)</title> <meta name="date" content="2018-10-02"> <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.uni_mannheim.informatik.dws.winter.webtables.TableMapping (WInte.r 1.3 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="../../../../../../../de/uni_mannheim/informatik/dws/winter/webtables/TableMapping.html" title="class in de.uni_mannheim.informatik.dws.winter.webtables">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?de/uni_mannheim/informatik/dws/winter/webtables/class-use/TableMapping.html" target="_top">Frames</a></li> <li><a href="TableMapping.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.uni_mannheim.informatik.dws.winter.webtables.TableMapping" class="title">Uses of Class<br>de.uni_mannheim.informatik.dws.winter.webtables.TableMapping</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../../../de/uni_mannheim/informatik/dws/winter/webtables/TableMapping.html" title="class in de.uni_mannheim.informatik.dws.winter.webtables">TableMapping</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="#de.uni_mannheim.informatik.dws.winter.webtables">de.uni_mannheim.informatik.dws.winter.webtables</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="#de.uni_mannheim.informatik.dws.winter.webtables.parsers">de.uni_mannheim.informatik.dws.winter.webtables.parsers</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="de.uni_mannheim.informatik.dws.winter.webtables"> <!-- --> </a> <h3>Uses of <a href="../../../../../../../de/uni_mannheim/informatik/dws/winter/webtables/TableMapping.html" title="class in de.uni_mannheim.informatik.dws.winter.webtables">TableMapping</a> in <a href="../../../../../../../de/uni_mannheim/informatik/dws/winter/webtables/package-summary.html">de.uni_mannheim.informatik.dws.winter.webtables</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../../../de/uni_mannheim/informatik/dws/winter/webtables/package-summary.html">de.uni_mannheim.informatik.dws.winter.webtables</a> that return <a href="../../../../../../../de/uni_mannheim/informatik/dws/winter/webtables/TableMapping.html" title="class in de.uni_mannheim.informatik.dws.winter.webtables">TableMapping</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../../../de/uni_mannheim/informatik/dws/winter/webtables/TableMapping.html" title="class in de.uni_mannheim.informatik.dws.winter.webtables">TableMapping</a></code></td> <td class="colLast"><span class="typeNameLabel">Table.</span><code><span class="memberNameLink"><a href="../../../../../../../de/uni_mannheim/informatik/dws/winter/webtables/Table.html#getMapping--">getMapping</a></span>()</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static <a href="../../../../../../../de/uni_mannheim/informatik/dws/winter/webtables/TableMapping.html" title="class in de.uni_mannheim.informatik.dws.winter.webtables">TableMapping</a></code></td> <td class="colLast"><span class="typeNameLabel">TableMapping.</span><code><span class="memberNameLink"><a href="../../../../../../../de/uni_mannheim/informatik/dws/winter/webtables/TableMapping.html#read-java.lang.String-">read</a></span>(<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>&nbsp;fileName)</code>&nbsp;</td> </tr> </tbody> </table> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../../../de/uni_mannheim/informatik/dws/winter/webtables/package-summary.html">de.uni_mannheim.informatik.dws.winter.webtables</a> with parameters of type <a href="../../../../../../../de/uni_mannheim/informatik/dws/winter/webtables/TableMapping.html" title="class in de.uni_mannheim.informatik.dws.winter.webtables">TableMapping</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><span class="typeNameLabel">Table.</span><code><span class="memberNameLink"><a href="../../../../../../../de/uni_mannheim/informatik/dws/winter/webtables/Table.html#setMapping-de.uni_mannheim.informatik.dws.winter.webtables.TableMapping-">setMapping</a></span>(<a href="../../../../../../../de/uni_mannheim/informatik/dws/winter/webtables/TableMapping.html" title="class in de.uni_mannheim.informatik.dws.winter.webtables">TableMapping</a>&nbsp;mapping)</code>&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"><a name="de.uni_mannheim.informatik.dws.winter.webtables.parsers"> <!-- --> </a> <h3>Uses of <a href="../../../../../../../de/uni_mannheim/informatik/dws/winter/webtables/TableMapping.html" title="class in de.uni_mannheim.informatik.dws.winter.webtables">TableMapping</a> in <a href="../../../../../../../de/uni_mannheim/informatik/dws/winter/webtables/parsers/package-summary.html">de.uni_mannheim.informatik.dws.winter.webtables.parsers</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../../../de/uni_mannheim/informatik/dws/winter/webtables/parsers/package-summary.html">de.uni_mannheim.informatik.dws.winter.webtables.parsers</a> that return <a href="../../../../../../../de/uni_mannheim/informatik/dws/winter/webtables/TableMapping.html" title="class in de.uni_mannheim.informatik.dws.winter.webtables">TableMapping</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../../../de/uni_mannheim/informatik/dws/winter/webtables/TableMapping.html" title="class in de.uni_mannheim.informatik.dws.winter.webtables">TableMapping</a></code></td> <td class="colLast"><span class="typeNameLabel">JsonTableMapping.</span><code><span class="memberNameLink"><a href="../../../../../../../de/uni_mannheim/informatik/dws/winter/webtables/parsers/JsonTableMapping.html#toTableMapping--">toTableMapping</a></span>()</code>&nbsp;</td> </tr> </tbody> </table> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../../../de/uni_mannheim/informatik/dws/winter/webtables/parsers/package-summary.html">de.uni_mannheim.informatik.dws.winter.webtables.parsers</a> with parameters of type <a href="../../../../../../../de/uni_mannheim/informatik/dws/winter/webtables/TableMapping.html" title="class in de.uni_mannheim.informatik.dws.winter.webtables">TableMapping</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>static <a href="../../../../../../../de/uni_mannheim/informatik/dws/winter/webtables/parsers/JsonTableMapping.html" title="class in de.uni_mannheim.informatik.dws.winter.webtables.parsers">JsonTableMapping</a></code></td> <td class="colLast"><span class="typeNameLabel">JsonTableMapping.</span><code><span class="memberNameLink"><a href="../../../../../../../de/uni_mannheim/informatik/dws/winter/webtables/parsers/JsonTableMapping.html#fromTableMapping-de.uni_mannheim.informatik.dws.winter.webtables.TableMapping-">fromTableMapping</a></span>(<a href="../../../../../../../de/uni_mannheim/informatik/dws/winter/webtables/TableMapping.html" title="class in de.uni_mannheim.informatik.dws.winter.webtables">TableMapping</a>&nbsp;mapping)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../../../../de/uni_mannheim/informatik/dws/winter/webtables/Table.html" title="class in de.uni_mannheim.informatik.dws.winter.webtables">Table</a></code></td> <td class="colLast"><span class="typeNameLabel">JsonTableParser.</span><code><span class="memberNameLink"><a href="../../../../../../../de/uni_mannheim/informatik/dws/winter/webtables/parsers/JsonTableParser.html#parseTable-de.uni_mannheim.informatik.dws.winter.webtables.parsers.JsonTableSchema-java.lang.String-de.uni_mannheim.informatik.dws.winter.webtables.TableMapping-">parseTable</a></span>(<a href="../../../../../../../de/uni_mannheim/informatik/dws/winter/webtables/parsers/JsonTableSchema.html" title="class in de.uni_mannheim.informatik.dws.winter.webtables.parsers">JsonTableSchema</a>&nbsp;data, <a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>&nbsp;fileName, <a href="../../../../../../../de/uni_mannheim/informatik/dws/winter/webtables/TableMapping.html" title="class in de.uni_mannheim.informatik.dws.winter.webtables">TableMapping</a>&nbsp;mapping)</code>&nbsp;</td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../de/uni_mannheim/informatik/dws/winter/webtables/TableMapping.html" title="class in de.uni_mannheim.informatik.dws.winter.webtables">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?de/uni_mannheim/informatik/dws/winter/webtables/class-use/TableMapping.html" target="_top">Frames</a></li> <li><a href="TableMapping.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2018. All rights reserved.</small></p> </body> </html>
olehmberg/winter
docs/javadoc/de/uni_mannheim/informatik/dws/winter/webtables/class-use/TableMapping.html
HTML
apache-2.0
14,178
#!/usr/bin/python #credits : https://gist.github.com/TheCrazyT/11263599 import socket import ssl import select import time import re import sys from thread import start_new_thread from struct import pack from random import randint from subprocess import call import os import fnmatch import argparse import logging class lakkucast: def __init__(self): self.status = None self.session_id = None self.protocolVersion = 0 self.source_id = "sender-0" self.destination_id = "receiver-0" self.chromecast_server = "192.168.1.23" #living room audio self.socket = 0 self.type_enum = 0 self.type_string = 2 self.type_bytes = self.type_string self.session = 0 self.play_state = None self.sleep_between_media = 5 self.content_id = None self.socket_fail_count = 100 def clean(self,s): return re.sub(r'[\x00-\x1F\x7F]', '?',s) def getType(self, fieldId,t): return (fieldId << 3) | t def getLenOf(self, s): x = "" l = len(s) while(l > 0x7F): x += pack("B",l & 0x7F | 0x80) l >>= 7 x += pack("B",l & 0x7F) return x def init_status(self): self.socket = socket.socket() self.socket = ssl.wrap_socket(self.socket) #print "connecting ..." self.socket.connect((self.chromecast_server,8009)) payloadType = 0 #0=string data = "{\"type\":\"CONNECT\",\"origin\":{}}" lnData = self.getLenOf(data) #print len(lnData),len(data),lnData.encode("hex") namespace = "urn:x-cast:com.google.cast.tp.connection" msg = pack(">BBBB%dsBB%dsBB%dsBBB%ds%ds" % (len(self.source_id), len(self.destination_id), len(namespace), len(lnData), len(data)), self.getType(1,self.type_enum), self.protocolVersion, self.getType(2,self.type_string), len(self.source_id), self.source_id, self.getType(3,self.type_string), len(self.destination_id), self.destination_id, self.getType(4,self.type_string), len(namespace), namespace, self.getType(5,self.type_enum), payloadType, self.getType(6,self.type_bytes), lnData, data) msg = pack(">I%ds" % (len(msg)),len(msg),msg) #print msg.encode("hex") #print "Connecting ..." self.socket.write(msg) payloadType = 0 #0=string data = "{\"type\":\"GET_STATUS\",\"requestId\":46479000}" lnData = self.getLenOf(data) namespace = "urn:x-cast:com.google.cast.receiver" msg = pack(">BBBB%dsBB%dsBB%dsBBB%ds%ds" % (len(self.source_id), len(self.destination_id), len(namespace), len(lnData), len(data)), self.getType(1,self.type_enum), self.protocolVersion, self.getType(2,self.type_string), len(self.source_id), self.source_id, self.getType(3,self.type_string), len(self.destination_id), self.destination_id, self.getType(4,self.type_string), len(namespace), namespace, self.getType(5,self.type_enum), payloadType, self.getType(6,self.type_bytes), lnData, data) msg = pack(">I%ds" % (len(msg)),len(msg),msg) #print "sending status request..." self.socket.write(msg) m1=None m3=None result="" count = 0 while m1==None and m3==None: lastresult = self.socket.read(2048) result += lastresult #print "#"+lastresult.encode("hex") #if lastresult != "": # print self.clean("\nH!"+lastresult) #print result m1 = re.search('"sessionId":"(?P<session>[^"]+)"', result) m2 = re.search('"statusText":"(?P<status>[^"]+)"', result) m3 = re.search('"playerState":"(?P<play_state>[^"]+)"', result) m4 = re.search('"contentId":"(?P<content_id>[^"]+)"', result) count = count + 1 if count > self.socket_fail_count: self.status = None self.play_state = None self.status = None break #print "#%i" % (m==None) if m1 != None: #print "session:",m1.group("session") self.session = m1.group("session") if m2 != None: #print "status:",m2.group("status") self.status = m2.group("status") if m3 != None: #print "play_state:",m3.group("play_state") self.play_state = m3.group("play_state") if m4 != None: #print "contentid:",m4.group("content_id") self.content_id = m4.group("content_id") payloadType = 0 #0=string data = "{MESSAGE_TYPE: 'SET_VOLUME','volume': {'level': 0.2}}" lnData = self.getLenOf(data) #print len(lnData),len(data),lnData.encode("hex") namespace = "urn:x-cast:com.google.cast.tp.connection" msg = pack(">BBBB%dsBB%dsBB%dsBBB%ds%ds" % (len(self.source_id), len(self.destination_id), len(namespace), len(lnData), len(data)), self.getType(1,self.type_enum), self.protocolVersion, self.getType(2,self.type_string), len(self.source_id), self.source_id, self.getType(3,self.type_string), len(self.destination_id), self.destination_id, self.getType(4,self.type_string), len(namespace), namespace, self.getType(5,self.type_enum), payloadType, self.getType(6,self.type_bytes), lnData, data) msg = pack(">I%ds" % (len(msg)),len(msg),msg) #print msg.encode("hex") #print "Connecting ..." self.socket.write(msg) def get_status(self): return " ".join(["main_status:" , self.get_main_status() , "play_status:" , self.get_play_status()]) def get_main_status(self): if self.status == None: status_str = "None" else: status_str = self.status return (status_str) def get_play_status(self): if self.play_state == None: play_state_str = "None" else: play_state_str = self.play_state return (play_state_str) def ready_to_play(self): if self.status == "Now Casting": return False if self.status == "Ready To Cast" or self.status == None or self.status == "Chromecast Home Screen": if self.play_state == None: return True if self.play_state == "IDLE": return True if self.play_state == "PLAYING": return False if self.play_state == "BUFFERING": return False return True else: return False def close_connection(self): self.socket.close() def play_url(self, url): payloadType = 0 #0=string data = "{\"type\":\"LAUNCH\",\"requestId\":46479001,\"appId\":\"CC1AD845\"}" lnData = self.getLenOf(data) namespace = "urn:x-cast:com.google.cast.receiver" msg = pack(">BBBB%dsBB%dsBB%dsBBB%ds%ds" % (len(self.source_id), len(self.destination_id), len(namespace), len(lnData), len(data)), self.getType(1,self.type_enum), self.protocolVersion, self.getType(2,self.type_string), len(self.source_id), self.source_id, self.getType(3,self.type_string), len(self.destination_id), self.destination_id, self.getType(4,self.type_string), len(namespace), namespace, self.getType(5,self.type_enum), payloadType, self.getType(6,self.type_bytes), lnData, data) msg = pack(">I%ds" % (len(msg)),len(msg),msg) #print msg.encode("hex") #print "sending ..." self.socket.write(msg) m=None result="" while m==None: lastresult = self.socket.read(2048) result += lastresult #print "#"+lastresult.encode("hex") #print clean("!"+lastresult) m = re.search('"transportId":"(?P<transportId>[^"]+)"', result) self.destination_id = m.group("transportId") payloadType = 0 #0=string data = "{\"type\":\"CONNECT\",\"origin\":{}}" lnData = self.getLenOf(data) #print len(lnData),len(data),lnData.encode("hex") namespace = "urn:x-cast:com.google.cast.tp.connection" msg = pack(">BBBB%dsBB%dsBB%dsBBB%ds%ds" % (len(self.source_id), len(self.destination_id), len(namespace), len(lnData), len(data)), self.getType(1,self.type_enum), self.protocolVersion, self.getType(2,self.type_string), len(self.source_id), self.source_id, self.getType(3,self.type_string), len(self.destination_id), self.destination_id, self.getType(4,self.type_string), len(namespace), namespace, self.getType(5,self.type_enum), payloadType, self.getType(6,self.type_bytes), lnData, data) msg = pack(">I%ds" % (len(msg)),len(msg),msg) #print msg.encode("hex") #print "sending ..." self.socket.write(msg) payloadType = 0 #0=string data = "{\"type\":\"LOAD\",\"requestId\":46479002,\"sessionId\":\""+self.session+"\",\"media\":{\"contentId\":\""+url+"\",\"streamType\":\"buffered\",\"contentType\":\"video/mp4\"},\"autoplay\":true,\"currentTime\":0,\"customData\":{\"payload\":{\"title:\":\"\"}}}" lnData = self.getLenOf(data) namespace = "urn:x-cast:com.google.cast.media" msg = pack(">BBBB%dsBB%dsBB%dsBBB%ds%ds" % (len(self.source_id), len(self.destination_id), len(namespace), len(lnData), len(data)), self.getType(1,self.type_enum), self.protocolVersion, self.getType(2,self.type_string), len(self.source_id), self.source_id, self.getType(3,self.type_string), len(self.destination_id), self.destination_id, self.getType(4,self.type_string), len(namespace), namespace, self.getType(5,self.type_enum), payloadType, self.getType(6,self.type_bytes), lnData, data) msg = pack(">I%ds" % (len(msg)),len(msg),msg) #print msg.encode("hex") #print "sending ..." #print "LOADING" self.socket.write(msg) payloadType = 0 #0=string volume = min(max(0, round(0.1, 1)), 1) data = "{MESSAGE_TYPE: 'SET_VOLUME','volume': {'level': volume}}" lnData = self.getLenOf(data) #print len(lnData),len(data),lnData.encode("hex") namespace = "urn:x-cast:com.google.cast.tp.connection" msg = pack(">BBBB%dsBB%dsBB%dsBBB%ds%ds" % (len(self.source_id), len(self.destination_id), len(namespace), len(lnData), len(data)), self.getType(1,self.type_enum), self.protocolVersion, self.getType(2,self.type_string), len(self.source_id), self.source_id, self.getType(3,self.type_string), len(self.destination_id), self.destination_id, self.getType(4,self.type_string), len(namespace), namespace, self.getType(5,self.type_enum), payloadType, self.getType(6,self.type_bytes), lnData, data) msg = pack(">I%ds" % (len(msg)),len(msg),msg) #print msg.encode("hex") #print "Connecting ..." self.socket.write(msg) self.close_connection() #try: # while True: # print "before lastresult" # lastresult = self.socket.read(2048) # if lastresult!="": # #print "#"+lastresult.encode("hex") # print self.clean("! In loop:"+lastresult) # finally: # print "final" # socket.close() # print "socket closed" class manage_lightwave: def __init__(self): self.room = "Main\ Bedroom" self.device = "Screen" self.lightwave_cmd = "/usr/local/bin/lightwaverf" def start_screen(self): cmd = " ".join([self.lightwave_cmd, self.room, self.device, "on", ">cmd.log", "2>&1"]) os.system(cmd) return(cmd) def stop_screen(self): cmd = " ".join([self.lightwave_cmd, self.room, self.device, "off", ">cmd.log", "2>&1"]) os.system(cmd) return(cmd) class lakkucast_media: def __init__(self): self.top_dir = "/data" self.top_url = "http://192.168.1.98" #self.media_dirs = ["media/test/sample1", "media/test/sample2"] self.media_dirs = ["media/TV-Shows/English/Friends", "media/TV-Shows/English/That 70s Show", "media/TV-Shows/English/Big Bang Theory"] self.media_data = "/data/webapps/lakku/lakkucast/media.dat" def random_play(self, num_play): count_dir = 0 num_dirs = len(self.media_dirs) while count_dir < num_dirs: rand_main = randint(0, (len(self.media_dirs)-1)) url_list = [] sel_dir = os.path.join(self.top_dir, self.media_dirs[rand_main]) if os.path.isdir(sel_dir): count_dir = count_dir + 1 matches = [] for root, dirnames, filenames in os.walk(sel_dir): for filename in fnmatch.filter(filenames, '*.mp4'): matches.append(os.path.join(root, filename).replace(self.top_dir,'')) count = 1 loop_count = 1 while count <= num_play: file_rand = randint(0, (len(matches)-1)) file_name = "".join([self.top_url , matches[file_rand]]) if self.played_before(file_name) == False: if file_name not in url_list: url_list.append(file_name) count = count + 1 loop_count = loop_count + 1 if loop_count == (len(matches)-1): break if count < num_play: continue else: fhand = open(self.media_data, 'a+') for u in url_list: fhand.write(u+'\n') fhand.close() return url_list def played_before(self, media_name): if media_name in open(self.media_data).read(): return True return False def reset_media_history(self): fhand = open(self.media_data, 'w') fhand.truncate() fhand.close() if __name__ == '__main__': parser = argparse.ArgumentParser(description="lakkucast") parser.add_argument("--play", help="Play x videos ") parser.add_argument("--stop", help="Stop playing and shutdown", action='store_true') parser.add_argument("--reset", help="Stop playing", action='store_true') parser.add_argument("--reset_media_history", help="Reset media history", action='store_true') args = parser.parse_args() log_file = "/data/webapps/lakku/lakkucast/lakkucast.log" log_level = logging.INFO logging.basicConfig(filename=log_file, level=log_level, format='%(asctime)s [%(levelname)s] %(message)s') logging.info("Starting lakkucast.") if args.play: num_play = int(args.play) * 2 logging.info("Play count: %s" % (args.play)) lm = lakkucast_media() lwrf = manage_lightwave() logging.info("Sending start command to lwrf") logging.info(lwrf.start_screen()) lwrf.start_screen() logging.info("Sleeping after lwrf start") url_list = lm.random_play(num_play) time.sleep(20) if url_list != None: logging.info("Got %d urls to play" % (len(url_list))) for u in url_list: logging.info("Trying URL: %s" % (u)) l = lakkucast() logging.info("Sleeping before main init") time.sleep(l.sleep_between_media) l.init_status() logging.info(l.get_status()) if l.ready_to_play(): logging.info("Playing URL: %s" % (u)) l.play_url(u) l.init_status() logging.info(l.get_status()) while not l.ready_to_play(): time.sleep(l.sleep_between_media) l.init_status() logging.info(l.get_status()) time.sleep(l.sleep_between_media) logging.info("Sending stop command to lwrf") logging.info(lwrf.stop_screen()) else: logging.info("No urls returned by player") l.play_url("http://192.168.1.98/media/test/water.mp4") time.sleep(l.sleep_between_media) lwrf = manage_lightwave() logging.info("Sending stop command to lwrf") logging.info(lwrf.stop_screen()) if args.stop: l = lakkucast() l.init_status() logging.info("Calling stop") logging.info(l.get_status()) l.play_url("http://192.168.1.98/media/test/water.mp4") time.sleep(10) lwrf = manage_lightwave() logging.info("Sending stop command to lwrf") logging.info(lwrf.stop_screen()) if args.reset: l = lakkucast() l.init_status() logging.info("Calling reset") logging.info(l.get_status()) l.play_url("http://192.168.1.98/media/test/water.mp4") if args.reset_media_history: logging.info("Calling Reset media history") lm = lakkucast_media() lm.reset_media_history()
srirajan/lakkucast
lakkucast.py
Python
apache-2.0
21,535
# Glyptopetalum Thwaites GENUS #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Celastrales/Celastraceae/Glyptopetalum/README.md
Markdown
apache-2.0
170
/* * Copyright 2014-2019 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.identitymanagement.model.transform; import javax.xml.stream.events.XMLEvent; import javax.annotation.Generated; import com.amazonaws.services.identitymanagement.model.*; import com.amazonaws.transform.Unmarshaller; import com.amazonaws.transform.StaxUnmarshallerContext; import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*; /** * PolicyUser StAX Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class PolicyUserStaxUnmarshaller implements Unmarshaller<PolicyUser, StaxUnmarshallerContext> { public PolicyUser unmarshall(StaxUnmarshallerContext context) throws Exception { PolicyUser policyUser = new PolicyUser(); int originalDepth = context.getCurrentDepth(); int targetDepth = originalDepth + 1; if (context.isStartOfDocument()) targetDepth += 1; while (true) { XMLEvent xmlEvent = context.nextEvent(); if (xmlEvent.isEndDocument()) return policyUser; if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) { if (context.testExpression("UserName", targetDepth)) { policyUser.setUserName(StringStaxUnmarshaller.getInstance().unmarshall(context)); continue; } if (context.testExpression("UserId", targetDepth)) { policyUser.setUserId(StringStaxUnmarshaller.getInstance().unmarshall(context)); continue; } } else if (xmlEvent.isEndElement()) { if (context.getCurrentDepth() < originalDepth) { return policyUser; } } } } private static PolicyUserStaxUnmarshaller instance; public static PolicyUserStaxUnmarshaller getInstance() { if (instance == null) instance = new PolicyUserStaxUnmarshaller(); return instance; } }
jentfoo/aws-sdk-java
aws-java-sdk-iam/src/main/java/com/amazonaws/services/identitymanagement/model/transform/PolicyUserStaxUnmarshaller.java
Java
apache-2.0
2,564
package bazilfuse import ( "bytes" "errors" "os/exec" ) func unmount(dir string) error { cmd := exec.Command("fusermount", "-u", dir) output, err := cmd.CombinedOutput() if err != nil { if len(output) > 0 { output = bytes.TrimRight(output, "\n") msg := err.Error() + ": " + string(output) err = errors.New(msg) } return err } return nil }
BanzaiMan/gcsfuse
vendor/github.com/jacobsa/bazilfuse/unmount_linux.go
GO
apache-2.0
364
package org.bigdata.yelp.yelpreco; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Properties; import org.bigdata.yelp.util.Property; import com.amazonaws.AmazonClientException; import com.amazonaws.AmazonServiceException; import com.amazonaws.auth.AWSCredentials; import com.amazonaws.auth.PropertiesCredentials; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3Client; import com.amazonaws.services.s3.model.Bucket; import com.amazonaws.services.s3.model.GetObjectRequest; import com.amazonaws.services.s3.model.ListObjectsRequest; import com.amazonaws.services.s3.model.ObjectListing; import com.amazonaws.services.s3.model.S3Object; import com.amazonaws.services.s3.model.S3ObjectSummary; public class RecoLister { private AWSCredentials credentials; public static AmazonS3Client s3Client = null; public static String bucketName = "yelpreco"; public RecoLister() { try { init(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } private void init() throws ClassNotFoundException { try { final Properties prop = Property.getPropInstance(); // read AWS credentials /*credentials = new PropertiesCredentials( RecoLister.class .getResourceAsStream("AwsCredentials.properties"));*/ credentials = new AWSCredentials() { public String getAWSSecretKey() { return prop.getProperty("SECRET_KEY"); } public String getAWSAccessKeyId() { return prop.getProperty("ACCESS_KEY"); } }; if (s3Client == null) s3Client = new AmazonS3Client(credentials); // System.out.println("Creating S3 client"); } catch (IOException e) { System.out.println(e.getMessage()); } } public ArrayList<String> getRecos(String userId) throws IOException { ArrayList<String> recoList = new ArrayList<String>(); String prefix = "yelp_output/" + userId + "/prediction/"; // String prefix = ""; String s3ObjectName = ""; try { ObjectListing objectListing = s3Client .listObjects(new ListObjectsRequest() .withBucketName(bucketName).withPrefix(prefix)); boolean skipFirst = true; for (S3ObjectSummary objectSummary : objectListing .getObjectSummaries()) { if(skipFirst) { skipFirst = false; continue; } System.out.println("Object is: " + objectSummary.getKey().toString()); s3ObjectName = objectSummary.getKey().toString(); break; } System.out.println("Downloading an object.."); S3Object s3object = s3Client.getObject(new GetObjectRequest( bucketName, s3ObjectName)); System.out.println("Content-Type: " + s3object.getObjectMetadata().getContentType()); // displayTextInputStream(s3object.getObjectContent()); } catch (AmazonServiceException ase) { printAmazonServiceException(ase); } catch (AmazonClientException ace) { printAmazonClientException(ace); } // TODO (optional): Calculate the distance from the user using lat and // long // TODO: Form and return the reco list return null; } private void displayTextInputStream(InputStream input) throws IOException { // Read one text line at a time and display. BufferedReader reader = new BufferedReader(new InputStreamReader(input)); while (true) { String line = reader.readLine(); if (line == null) break; System.out.println(" " + line); } System.out.println(); } private void printAmazonServiceException(AmazonServiceException ase) { System.out .println("Caught an AmazonServiceException, which means your request made it " + "to Amazon S3, but was rejected with an error response for some reason."); System.out.println("Error Message: " + ase.getMessage()); System.out.println("HTTP Status Code: " + ase.getStatusCode()); System.out.println("AWS Error Code: " + ase.getErrorCode()); System.out.println("Error Type: " + ase.getErrorType()); System.out.println("Request ID: " + ase.getRequestId()); } private void printAmazonClientException(AmazonClientException ace) { System.out .println("Caught an AmazonClientException, which means the client encountered " + "a serious internal problem while trying to communicate with S3, " + "such as not being able to access the network."); System.out.println("Error Message: " + ace.getMessage()); } public static void main(String args[]) { String userId = "kJyR4gT1pfCcNjEY9-YMoQ"; RecoLister recoLister = new RecoLister(); try { recoLister.getRecos(userId); } catch (IOException e) { e.printStackTrace(); } } }
Sapphirine/Yelp-Recommendation-Analysis
deprecated_project/src/main/java/org/bigdata/yelp/yelpreco/RecoLister.java
Java
apache-2.0
4,676
--- layout: post title: "从Docker v1.10.3升级到v1.13.0" subtitle: "Keep with the development of Docker, and enjoy its advantages" date: 2017-02-14 author: "Robin" header-img: "img/post-bg-2015.jpg" catalog: true tags: - Docker --- 从2015年3月份将Docker升级到v1.10.3,已经在生产环境中使用了近一年的时间。从整体上看,该版本还是比较稳定的,虽然没有出现过重大问题,但是,也发现了一些小的不足。随着Docker的快速发展,被其一些新的特性所吸引,所有决定将Docker进行一次大的升级,直接升级到最新版的v1.13.0。 ## Issues or shortages in Docker v1.10.3 * [Very slow when push or pull multiple images at the same time](https://github.com/supereagle/experience/issues/1) * Containers will stop when daemon shuts down ## Motivation to update Docker from v1.10.3 to v1.13.0 * Keep containers running when daemon shuts down * Support for live reloading daemon configuration through systemd * Configurable `maxUploadConcurrency` and `maxDownloadConcurrency` to speed up image pushing and pulling speed * [Key features in each Docker release](https://github.com/supereagle/experience/issues/5) * Performance is greatly improved ([Performance comparation between Docker v1.13.0 and v1.10.3](https://github.com/supereagle/experience/issues/10)) ## Steps to update Docker 1. Get docker-engine-1.13.0-1.el7.centos.x86_64.rpm and docker-engine-selinux-1.13.0-1.el7.centos.noarch.rpm from [Docker Stable Repository](https://yum.dockerproject.org/repo/main/centos/7/Packages/). 2. Download [aliyun yum repo](http://mirrors.aliyun.com/repo/Centos-7.repo) and place it in folder /etc/yum.repo.d/ 3. Create Docker Daemon config file: /etc/docker/daemon.json ```json { "disable-legacy-registry": true, "max-concurrent-downloads": 10, "max-concurrent-uploads": 20, "log-level": "warn", "log-opts": { "max-size": "2m", "max-file": "5" }, "storage-driver": "devicemapper", "storage-opts": [ "dm.fs=xfs", "dm.thinpooldev=/dev/mapper/docker--vg-docker--pool", "dm.use_deferred_removal=true", "dm.use_deferred_deletion=true" ], "insecure-registries": ["https://registry.robin.com"], "live-restore": true } ``` 4. Run update script ```shell #!/bin/bash set -ex # Stop docker & kubelet systemctl stop docker systemctl stop kubelet # Wait docker & kubelet to stop sleep 20 # Use aliyun yum repo for dependencies mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.bak mv CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo yum makecache # Uninstall the old Docker rpm -e --nodeps docker-1.10.3-10.el7.centos.x86_64 docker-selinux-1.10.3-10.el7.centos.x86_64 # Install the new Docker yum install -y docker-engine-selinux-1.13.0-1.el7.centos.noarch.rpm docker-engine-1.13.0-1.el7.centos.x86_64.rpm # Create the Daemon config file cp daemon.json /etc/docker/ # Start docker systemctl daemon-reload systemctl start docker ``` ## Troubleshootings * **Lack of dependencies** Use aliyun yum repo. ```shell $ mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.backup $ wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo $ yum makecache ``` * **Kubernetes-1.12 and kubernetes-node-1.12 are uninstalled while uninstalling old Docker 1.10.3** Kubernetes 1.12 on CentOS 7.1 depends docker.x86_64. Kubernetes-1.12 and kubernetes-node-1.12 are uninstalled when uninstall docker 1.10.3 by the command `yum erase -y docker docker-selinux`. At the same time, the uninstalled kubernetes-1.12 and kubernetes-node-1.12 can not be reinstalled after `docker-engine-1.13.0-1.el7.centos.x86_64.rpm` is installed, as they depend on **docker.x86_64**, not **docker-engine.x86_64**. Use command `rpm -e --nodeps docker-1.10.3-10.el7.centos.x86_64` to uninstall Docker instead of `yum erase -y docker`. * **Can not reload daemon configuration through systemd** Use `daemon.json` instead of config files such as `docker`, `docker-storage` and `docker-network` under `/etc/sysconfig/` for Docker daemon options. daemon.json is the recommended configuration in Docker 1.13. * **The default storage driver is changed from Device mapper to OverlayFS** Overlay requires the kernel 3.18+, and has known limitations with inode exhaustion and commit performance. The overlay2 driver addresses this limitation, but requires the kernel 4.0+. * **No effect on Docker daemon after change /usr/lib/systemd/system/docker.service** Run `systemctl daemon-reload` to flush changes before start Docker. ## Reference * [What’s New in Docker 1.13](https://blog.codeship.com/whats-new-docker-1-13/) * [时隔半年,Docker 再发重大版本 1.13](http://www.dockerinfo.net/4184.html)
supereagle/supereagle.github.io
_posts/2017/2017-02-14-update-docker.markdown
Markdown
apache-2.0
4,837
# Agaricus conchatus var. conchatus Bull., 1787 VARIETY #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in Herb. Fr. 7: tab. 298 (1787) #### Original name Agaricus conchatus var. conchatus Bull., 1787 ### Remarks null
mdoering/backbone
life/Fungi/Basidiomycota/Agaricomycetes/Polyporales/Polyporaceae/Panus/Panus conchatus/ Syn. Agaricus conchatus conchatus/README.md
Markdown
apache-2.0
267
<?php /* * This file is part of the Stinger Media Parser package. * * (c) Oliver Kotte <oliver.kotte@stinger-soft.net> * (c) Florian Meyer <florian.meyer@stinger-soft.net> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace StingerSoft\MediaParsingBundle\Parser; use Symfony\Component\HttpFoundation\File\File; interface MediaParserInterface { const SERVICE_TAG = 'stinger_soft_media_parser.mediaparser'; /** * Parses the given file and extract the meta data * @param File $file * @return MediaInformationInterface */ public function parseFile(File $file); /** * Checks whether this parser can handle the file or not * @param File $file * @return boolean if this parses is able to handle the given file */ public function canHandle(File $file); }
Stinger-Soft/MediaParsingBundle
Parser/MediaParserInterface.php
PHP
apache-2.0
875
import os import sys def test(arg): return os.system('bin/nosetests -s -d -v %s' % arg) def main(args): if not args: print("Run as bin/python run_failure.py <test>, for example: \n" "bin/python run_failure.py " "kazoo.tests.test_watchers:KazooChildrenWatcherTests") return arg = args[0] i = 0 while 1: i += 1 print('Run number: %s' % i) ret = test(arg) if ret != 0: break if __name__ == '__main__': main(sys.argv[1:])
bsanders/kazoo
run_failure.py
Python
apache-2.0
536
<?php namespace AnhNhan\Converge\Modules\Forum\Views\Objects; use AnhNhan\Converge as cv; use AnhNhan\Converge\Modules\Tag\Storage\Tag; use AnhNhan\Converge\Modules\Tag\Views\TagView; use AnhNhan\Converge\Views\Panel\Panel; /** * @author Anh Nhan Nguyen <anhnhan@outlook.com> */ class PaneledForumListing extends ForumListing { private $panelHeader; private $tags = array(); // @Override, we handle title ourself public function setTitle($title) { $this->panelHeader = $title; return $this; } public function addTag($tag) { if ($tag instanceof Tag) { $tag = link_tag($tag, TagLinkExtra_None); } else if (!($tag instanceof TagView)) { throw new \InvalidArgumentException; } $this->tags[] = $tag; return $this; } public function render() { $panel = new Panel; $panel->addClass("panel-forum-listing"); $panel->setHeader($this->panelHeader); $panel->append(parent::render()); if ($this->tags) { foreach ($this->tags as $tag) { $panel->midriff()->push($tag); } } return $panel; } }
AnhNhan/Converge
src/AnhNhan/Converge/Modules/Forum/Views/Objects/PaneledForumListing.php
PHP
apache-2.0
1,211
# coding=utf-8 # Copyright 2022 The Google Research 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. """Library containing Tokenizer definitions. The RougeScorer class can be instantiated with the tokenizers defined here. New tokenizers can be defined by creating a subclass of the Tokenizer abstract class and overriding the tokenize() method. """ import abc from nltk.stem import porter from rouge import tokenize class Tokenizer(abc.ABC): """Abstract base class for a tokenizer. Subclasses of Tokenizer must implement the tokenize() method. """ @abc.abstractmethod def tokenize(self, text): raise NotImplementedError("Tokenizer must override tokenize() method") class DefaultTokenizer(Tokenizer): """Default tokenizer which tokenizes on whitespace.""" def __init__(self, use_stemmer=False): """Constructor for DefaultTokenizer. Args: use_stemmer: boolean, indicating whether Porter stemmer should be used to strip word suffixes to improve matching. """ self._stemmer = porter.PorterStemmer() if use_stemmer else None def tokenize(self, text): return tokenize.tokenize(text, self._stemmer)
google-research/google-research
rouge/tokenizers.py
Python
apache-2.0
1,661
/* * Copyright(C) 2014 * NEC Corporation All rights reserved. * * No permission to use, copy, modify and distribute this software * and its documentation for any purpose is granted. * This software is provided under applicable license agreement only. */ package com.nec.harvest.repository; import com.nec.crud.CrudRepository; import com.nec.harvest.model.MonthlyPurchase; /** * Monthly Purchases repository that can be used to created, removed, updated or * something like that based on MonthlyPurchase type. * * @author hungpd * */ public interface MonthlyPurchasesRepository extends CrudRepository<MonthlyPurchase, String> { }
dangokuson/Harvest-JP
harvest/src/main/java/com/nec/harvest/repository/MonthlyPurchasesRepository.java
Java
apache-2.0
647
/** * Autogenerated by Thrift Compiler (1.0.0-dev) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ #ifndef ttmat_internal_CONSTANTS_H #define ttmat_internal_CONSTANTS_H #include "ttmat_internal_types.h" namespace ttmat { class ttmat_internalConstants { public: ttmat_internalConstants(); }; extern const ttmat_internalConstants g_ttmat_internal_constants; } // namespace #endif
treadstoneproject/tracethreat-nrml
src/msg/gen-cpp/ttmat_internal_constants.h
C
apache-2.0
431
package com.yuyh.library.utils; import android.content.Context; import android.os.Vibrator; /** * 振动器 * * @author yuyh. * @date 16/4/9. */ public class VibrateUtils { /** * 控制手机振动的毫秒数 * * @param context * @param milliseconds */ public static void vibrate(Context context, long milliseconds) { Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE); vibrator.vibrate(milliseconds); } /** * 指定手机以pattern模式振动 * * @param context * @param pattern new long[]{400,800,1200,1600},就是指定在400ms、800ms、1200ms、1600ms这些时间点交替启动、关闭手机振动器 * @param repeat 指定pattern数组的索引,指定pattern数组中从repeat索引开始的振动进行循环。-1表示只振动一次,非-1表示从 pattern的指定下标开始重复振动。 */ public static void vibrate(Context context, long[] pattern, int repeat) { Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE); vibrator.vibrate(pattern, repeat); } public static void cancel(Context context) { Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE); vibrator.cancel(); } }
xqgdmg/DavidNBA-master
CommonLibrary/src/main/java/com/yuyh/library/utils/VibrateUtils.java
Java
apache-2.0
1,337
/******************************************************************************* * Copyright 2017 Capital One Services, LLC and Bitwise, 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 hydrograph.ui.dataviewer.utilities; import java.io.File; import java.io.IOException; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.apache.commons.lang.StringUtils; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; import org.slf4j.Logger; import org.w3c.dom.Document; import org.xml.sax.SAXException; import hydrograph.ui.common.schema.Field; import hydrograph.ui.common.schema.Fields; import hydrograph.ui.common.schema.Schema; import hydrograph.ui.common.util.Constants; import hydrograph.ui.logging.factory.LogFactory; /** * The Class ViewDataSchemaHelper. * Used for schema file operations at watchers * * @author Bitwise * */ public class ViewDataSchemaHelper { private static final Logger logger = LogFactory.INSTANCE.getLogger(ViewDataSchemaHelper.class); public static ViewDataSchemaHelper INSTANCE = new ViewDataSchemaHelper(); private ViewDataSchemaHelper() { } /** * This function will read schema file and return schema fields * @param schemaFilePath * @return Fields */ public Fields getFieldsFromSchema(String schemaFilePath){ Fields fields = null; if(StringUtils.isNotBlank(schemaFilePath)){ String filePath=((IPath)new Path(schemaFilePath)).removeFileExtension().addFileExtension(Constants.XML_EXTENSION_FOR_IPATH).toString(); File file = new File(filePath); if(file.exists()){ try { DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); builderFactory.setExpandEntityReferences(false); builderFactory.setNamespaceAware(true); builderFactory.setFeature(Constants.DISALLOW_DOCTYPE_DECLARATION,true); DocumentBuilder documentBuilder = builderFactory.newDocumentBuilder(); Document document = documentBuilder.parse(file); JAXBContext jaxbContext = JAXBContext.newInstance(Schema.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); Schema schema = (Schema) jaxbUnmarshaller.unmarshal(document); fields = schema.getFields(); for(Field field : fields.getField()){ logger.debug("Type:{}, Name:{}, Format:{}" + field.getType(),field.getName(),field.getFormat()); } } catch (JAXBException | ParserConfigurationException | SAXException | IOException exception) { logger.error("Invalid xml file: ", exception); } } } return fields; } }
capitalone/Hydrograph
hydrograph.ui/hydrograph.ui.dataviewer/src/main/java/hydrograph/ui/dataviewer/utilities/ViewDataSchemaHelper.java
Java
apache-2.0
3,363
/** * @license Copyright 2017 Google Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ 'use strict'; /* global document ClipboardEvent getOuterHTMLSnippet */ const Gatherer = require('../gatherer.js'); const pageFunctions = require('../../../lib/page-functions.js'); // This is run in the page, not Lighthouse itself. /** * @return {LH.Artifacts['PasswordInputsWithPreventedPaste']} */ /* istanbul ignore next */ function findPasswordInputsWithPreventedPaste() { return Array.from(document.querySelectorAll('input[type="password"]')) .filter(passwordInput => !passwordInput.dispatchEvent( new ClipboardEvent('paste', {cancelable: true}) ) ) .map(passwordInput => ({ // @ts-ignore - getOuterHTMLSnippet put into scope via stringification snippet: getOuterHTMLSnippet(passwordInput), })); } class PasswordInputsWithPreventedPaste extends Gatherer { /** * @param {LH.Gatherer.PassContext} passContext * @return {Promise<LH.Artifacts['PasswordInputsWithPreventedPaste']>} */ afterPass(passContext) { return passContext.driver.evaluateAsync(`(() => { ${pageFunctions.getOuterHTMLSnippetString}; return (${findPasswordInputsWithPreventedPaste.toString()}()); })()`); } } module.exports = PasswordInputsWithPreventedPaste;
wardpeet/lighthouse
lighthouse-core/gather/gatherers/dobetterweb/password-inputs-with-prevented-paste.js
JavaScript
apache-2.0
1,814
# Roegneria turczaninovii var. pohuashanensis VARIETY #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Liliopsida/Poales/Poaceae/Elymus/Elymus gmelinii/ Syn. Roegneria turczaninovii pohuashanensis/README.md
Markdown
apache-2.0
200
/* * * ZDCFormCellSingleLine.h * ZDCChat * * Created by Zendesk on 29/01/2015. * * Copyright (c) 2016 Zendesk. All rights reserved. * * By downloading or using the Zendesk Mobile SDK, You agree to the Zendesk Master * Subscription Agreement https://www.zendesk.com/company/customers-partners/#master-subscription-agreement and Application Developer and API License * Agreement https://www.zendesk.com/company/customers-partners/#application-developer-api-license-agreement and * acknowledge that such terms govern Your use of and access to the Mobile SDK. * */ #import "ZDCFormCell.h" /** * Single line text entry cell for pre chat form fields which presents rows for name, * email and phone. */ @interface ZDCFormCellSingleLine : ZDCFormCell <UITextFieldDelegate> /** * The text field providing text entry. */ @property (nonatomic, strong) UITextField *textField; @end
mumabinggan/WeygoIPhone
Libraries/Zendesk/ZDCChat.framework/Headers/ZDCFormCellSingleLine.h
C
apache-2.0
906
#docker run -it --rm logstash logstash -e 'input { stdin { } } output { stdout { } }' #./logstash-1.5.0.rc2/bin/logstash agent -f ./logstash-opendata-donations.conf
ohsu-computational-biology/dms-es
services/logstash/config/start_logstash.sh
Shell
apache-2.0
165
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.ads.googleads.v9.services.stub; import com.google.ads.googleads.v9.resources.BiddingStrategySimulation; import com.google.ads.googleads.v9.services.GetBiddingStrategySimulationRequest; import com.google.api.gax.core.BackgroundResource; import com.google.api.gax.rpc.UnaryCallable; import javax.annotation.Generated; // AUTO-GENERATED DOCUMENTATION AND CLASS. /** * Base stub class for the BiddingStrategySimulationService service API. * * <p>This class is for advanced usage and reflects the underlying API directly. */ @Generated("by gapic-generator-java") public abstract class BiddingStrategySimulationServiceStub implements BackgroundResource { public UnaryCallable<GetBiddingStrategySimulationRequest, BiddingStrategySimulation> getBiddingStrategySimulationCallable() { throw new UnsupportedOperationException( "Not implemented: getBiddingStrategySimulationCallable()"); } @Override public abstract void close(); }
googleads/google-ads-java
google-ads-stubs-v9/src/main/java/com/google/ads/googleads/v9/services/stub/BiddingStrategySimulationServiceStub.java
Java
apache-2.0
1,570
# Copyright 2012 NetApp # 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. """Interface for shares extension.""" try: from urllib import urlencode # noqa except ImportError: from urllib.parse import urlencode # noqa from manilaclient import api_versions from manilaclient import base from manilaclient.common import constants from manilaclient.openstack.common.apiclient import base as common_base class ShareSnapshot(common_base.Resource): """Represent a snapshot of a share.""" def __repr__(self): return "<ShareSnapshot: %s>" % self.id def update(self, **kwargs): """Update this snapshot.""" self.manager.update(self, **kwargs) def reset_state(self, state): """Update the snapshot with the privided state.""" self.manager.reset_state(self, state) def delete(self): """Delete this snapshot.""" self.manager.delete(self) def force_delete(self): """Delete the specified snapshot ignoring its current state.""" self.manager.force_delete(self) class ShareSnapshotManager(base.ManagerWithFind): """Manage :class:`ShareSnapshot` resources.""" resource_class = ShareSnapshot def create(self, share, force=False, name=None, description=None): """Create a snapshot of the given share. :param share_id: The ID of the share to snapshot. :param force: If force is True, create a snapshot even if the share is busy. Default is False. :param name: Name of the snapshot :param description: Description of the snapshot :rtype: :class:`ShareSnapshot` """ body = {'snapshot': {'share_id': common_base.getid(share), 'force': force, 'name': name, 'description': description}} return self._create('/snapshots', body, 'snapshot') def get(self, snapshot): """Get a snapshot. :param snapshot: The :class:`ShareSnapshot` instance or string with ID of snapshot to delete. :rtype: :class:`ShareSnapshot` """ snapshot_id = common_base.getid(snapshot) return self._get('/snapshots/%s' % snapshot_id, 'snapshot') def list(self, detailed=True, search_opts=None, sort_key=None, sort_dir=None): """Get a list of snapshots of shares. :param search_opts: Search options to filter out shares. :param sort_key: Key to be sorted. :param sort_dir: Sort direction, should be 'desc' or 'asc'. :rtype: list of :class:`ShareSnapshot` """ if search_opts is None: search_opts = {} if sort_key is not None: if sort_key in constants.SNAPSHOT_SORT_KEY_VALUES: search_opts['sort_key'] = sort_key else: raise ValueError( 'sort_key must be one of the following: %s.' % ', '.join(constants.SNAPSHOT_SORT_KEY_VALUES)) if sort_dir is not None: if sort_dir in constants.SORT_DIR_VALUES: search_opts['sort_dir'] = sort_dir else: raise ValueError( 'sort_dir must be one of the following: %s.' % ', '.join(constants.SORT_DIR_VALUES)) if search_opts: query_string = urlencode( sorted([(k, v) for (k, v) in list(search_opts.items()) if v])) if query_string: query_string = "?%s" % (query_string,) else: query_string = '' if detailed: path = "/snapshots/detail%s" % (query_string,) else: path = "/snapshots%s" % (query_string,) return self._list(path, 'snapshots') def delete(self, snapshot): """Delete a snapshot of a share. :param snapshot: The :class:`ShareSnapshot` to delete. """ self._delete("/snapshots/%s" % common_base.getid(snapshot)) def _do_force_delete(self, snapshot, action_name="force_delete"): """Delete the specified snapshot ignoring its current state.""" return self._action(action_name, common_base.getid(snapshot)) @api_versions.wraps("1.0", "2.6") def force_delete(self, snapshot): return self._do_force_delete(snapshot, "os-force_delete") @api_versions.wraps("2.7") # noqa def force_delete(self, snapshot): return self._do_force_delete(snapshot, "force_delete") def update(self, snapshot, **kwargs): """Update a snapshot. :param snapshot: The :class:`ShareSnapshot` instance or string with ID of snapshot to delete. :rtype: :class:`ShareSnapshot` """ if not kwargs: return body = {'snapshot': kwargs, } snapshot_id = common_base.getid(snapshot) return self._update("/snapshots/%s" % snapshot_id, body) def _do_reset_state(self, snapshot, state, action_name="reset_status"): """Update the specified share snapshot with the provided state.""" return self._action(action_name, snapshot, {"status": state}) @api_versions.wraps("1.0", "2.6") def reset_state(self, snapshot, state): return self._do_reset_state(snapshot, state, "os-reset_status") @api_versions.wraps("2.7") # noqa def reset_state(self, snapshot, state): return self._do_reset_state(snapshot, state, "reset_status") def _action(self, action, snapshot, info=None, **kwargs): """Perform a snapshot 'action'.""" body = {action: info} self.run_hooks('modify_body_for_action', body, **kwargs) url = '/snapshots/%s/action' % common_base.getid(snapshot) return self.api.client.post(url, body=body)
sniperganso/python-manilaclient
manilaclient/v2/share_snapshots.py
Python
apache-2.0
6,363
using System; using System.Xml.Serialization; namespace Aop.Api.Domain { /// <summary> /// ZhimaCreditEpSceneAgreementUseModel Data Structure. /// </summary> [Serializable] public class ZhimaCreditEpSceneAgreementUseModel : AopObject { /// <summary> /// 特定业务场景传输的扩展参数,以JSON形式传输。具体业务场景需要传入参数请参考<a href="https://docs.open.alipay.com/11270#s3">业务场景传输的扩展参数</a> /// </summary> [XmlElement("biz_ext_param")] public string BizExtParam { get; set; } /// <summary> /// 业务时间,日期格式为 yyyy-MM-dd HH:mm:ss /// </summary> [XmlElement("biz_time")] public string BizTime { get; set; } /// <summary> /// 商户请求订单号,必须唯一。用于唯一标识商户的一笔业务请求。 /// </summary> [XmlElement("out_order_no")] public string OutOrderNo { get; set; } /// <summary> /// 条款编码。请参考<a href="https://docs.open.alipay.com/11270#s1">条款编码</a> /// </summary> [XmlElement("provision_code")] public string ProvisionCode { get; set; } /// <summary> /// 评估订单号。在用户完成信用评估后可以获取。信用评估流程关联接口见:zhima.credit.ep.scene.rating.initialize;zhima.credit.ep.scene.rating.apply。 /// </summary> [XmlElement("rating_order_no")] public string RatingOrderNo { get; set; } } }
329277920/Snail
Snail.Pay.Ali.Sdk/Domain/ZhimaCreditEpSceneAgreementUseModel.cs
C#
apache-2.0
1,586
package univers.torri.fr.service.mapper; import univers.torri.fr.domain.Authority; import univers.torri.fr.domain.User; import univers.torri.fr.service.dto.UserDTO; import org.springframework.stereotype.Service; import java.util.*; import java.util.stream.Collectors; /** * Mapper for the entity User and its DTO called UserDTO. * * Normal mappers are generated using MapStruct, this one is hand-coded as MapStruct * support is still in beta, and requires a manual step with an IDE. */ @Service public class UserMapper { public UserDTO userToUserDTO(User user) { return new UserDTO(user); } public List<UserDTO> usersToUserDTOs(List<User> users) { return users.stream() .filter(Objects::nonNull) .map(this::userToUserDTO) .collect(Collectors.toList()); } public User userDTOToUser(UserDTO userDTO) { if (userDTO == null) { return null; } else { User user = new User(); user.setId(userDTO.getId()); user.setLogin(userDTO.getLogin()); user.setFirstName(userDTO.getFirstName()); user.setLastName(userDTO.getLastName()); user.setEmail(userDTO.getEmail()); user.setImageUrl(userDTO.getImageUrl()); user.setActivated(userDTO.isActivated()); user.setLangKey(userDTO.getLangKey()); Set<Authority> authorities = this.authoritiesFromStrings(userDTO.getAuthorities()); if(authorities != null) { user.setAuthorities(authorities); } return user; } } public List<User> userDTOsToUsers(List<UserDTO> userDTOs) { return userDTOs.stream() .filter(Objects::nonNull) .map(this::userDTOToUser) .collect(Collectors.toList()); } public User userFromId(Long id) { if (id == null) { return null; } User user = new User(); user.setId(id); return user; } public Set<Authority> authoritiesFromStrings(Set<String> strings) { return strings.stream().map(string -> { Authority auth = new Authority(); auth.setName(string); return auth; }).collect(Collectors.toSet()); } }
PegazusFR/traveler-web-site
src/main/java/univers/torri/fr/service/mapper/UserMapper.java
Java
apache-2.0
2,313
/* * Copyright (c) 2018, The Modern Way. 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 com.themodernway.server.core.logging; import org.slf4j.Logger; import ch.qos.logback.classic.Level; @FunctionalInterface public interface IHasLogging { public Logger logger(); default Level getLoggingLevel() { return getLoggingLevel(logger()); } default Level getLoggingLevel(final Logger logger) { return LoggingOps.getLevel(logger); } default Logger setLoggingLevel(final Level level) { return setLoggingLevel(logger(), level); } default Logger setLoggingLevel(final String level) { return setLoggingLevel(logger(), level); } default Logger setLoggingLevel(final Logger logger, final Level level) { return LoggingOps.setLevel(logger, level); } default Logger setLoggingLevel(final Logger logger, final String level) { return LoggingOps.setLevel(logger, level); } }
themodernway/themodernway-server-core
src/main/groovy/com/themodernway/server/core/logging/IHasLogging.java
Java
apache-2.0
1,534
/* * Copyright 2000-2016 Vaadin Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.vaadin.shared.ui.datefield; /** * Shared state for the AbstractLocalDateField component. * * @author Vaadin Ltd * */ public class AbstractTextualDateFieldState extends AbstractDateFieldState { }
Legioth/vaadin
shared/src/main/java/com/vaadin/shared/ui/datefield/AbstractTextualDateFieldState.java
Java
apache-2.0
811
/* * Copyright (c) 2011-2012, Achim 'ahzf' Friedland <achim@graph-database.org> * This file is part of Styx <http://www.github.com/Vanaheimr/Styx> * * 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. */ #if !SILVERLIGHT #region Usings using System; using System.Collections.Generic; using System.Threading.Tasks; using System.Threading; #endregion namespace de.ahzf.Styx { /// <summary> /// The Sniper fetches messages/objects from a pipe, an IEnumerable or /// via an IEnumerator and sends them to the recipients. /// </summary> /// <typeparam name="TOut">The type of the emitted messages/objects.</typeparam> public class Sniper<TOut> : ISniper<TOut> { #region Data /// <summary> /// The internal source of messages/objects. /// </summary> private readonly IEnumerator<TOut> IEnumerator; #endregion #region Properties #region InitialDelay /// <summary> /// The initial delay before starting to fire asynchronously. /// </summary> public Nullable<TimeSpan> InitialDelay { get; private set; } #endregion #region IsTask /// <summary> /// Whether the sniper is running as its own task or not. /// </summary> public Boolean IsTask { get { return FireTask != null; } } #endregion #region FireCancellationTokenSource /// <summary> /// Signals to a FireCancellationToken that it should be canceled. /// </summary> public CancellationTokenSource FireCancellationTokenSource { get; private set; } #endregion #region FireCancellationToken /// <summary> /// Propogates notification that the asynchronous fireing should be canceled. /// </summary> public CancellationToken FireCancellationToken { get; private set; } #endregion #region FireTask /// <summary> /// The internal task for fireing the messages/objects. /// </summary> public Task FireTask { get; private set; } #endregion #region Intervall /// <summary> /// The intervall will throttle the automatic measurement of passive /// sensors and the event notifications of active sensors. /// </summary> public TimeSpan Intervall { get; set; } #endregion #region ThrottlingSleepDuration /// <summary> /// The amount of time in milliseconds a passive sensor /// will sleep if it is in throttling mode. /// </summary> public Int32 ThrottlingSleepDuration { get; set; } #endregion #region LastFireTime /// <summary> /// The last time the sniper fired. /// </summary> public DateTime LastFireTime { get; private set; } #endregion #endregion #region Events /// <summary> /// An event for message delivery. /// </summary> public event MessageRecipient<TOut> OnMessageAvailable; /// <summary> /// An event for signaling the completion of a message delivery. /// </summary> public event CompletionRecipient OnCompleted; /// <summary> /// An event for signaling an exception. /// </summary> public event ExceptionRecipient OnError; #endregion #region Constructor(s) #region Sniper(IEnumerable, Autostart = false, StartAsTask = false, InitialDelay = 0) /// <summary> /// The Sniper fetches messages/objects from the given IEnumerable /// and sends them to the recipients. /// </summary> /// <param name="IEnumerable">An IEnumerable&lt;S&gt; as element source.</param> /// <param name="Autostart">Start the sniper automatically.</param> /// <param name="StartAsTask">Start the sniper within its own task.</param> /// <param name="InitialDelay">Set the initial delay of the sniper in milliseconds.</param> public Sniper(IEnumerable<TOut> IEnumerable, Boolean Autostart = false, Boolean StartAsTask = false, Nullable<TimeSpan> InitialDelay = null) { #region Initial Checks if (IEnumerable == null) throw new ArgumentNullException("The given IEnumerable must not be null!"); #endregion this.IEnumerator = IEnumerable.GetEnumerator(); if (this.IEnumerator == null) throw new ArgumentNullException("IEnumerable.GetEnumerator() must not be null!"); this.InitialDelay = InitialDelay; if (Autostart) StartToFire(StartAsTask); } #endregion #region Sniper(IEnumerable, MessageRecipient.Recipient, Autostart = false, StartAsTask = false, InitialDelay = 0) /// <summary> /// The Sniper fetches messages/objects from the given IEnumerable /// and sends them to the recipients. /// </summary> /// <param name="IEnumerable">An IEnumerable&lt;S&gt; as element source.</param> /// <param name="Recipient">A recipient of the processed messages.</param> /// <param name="Autostart">Start the sniper automatically.</param> /// <param name="StartAsTask">Start the sniper within its own task.</param> /// <param name="InitialDelay">Set the initial delay of the sniper in milliseconds.</param> public Sniper(IEnumerable<TOut> IEnumerable, MessageRecipient<TOut> Recipient, Boolean Autostart = false, Boolean StartAsTask = false, Nullable<TimeSpan> InitialDelay = null) : this(IEnumerable, Autostart, StartAsTask, InitialDelay) { #region Initial Checks if (Recipient == null) throw new ArgumentNullException("The given Recipient must not be null!"); #endregion lock (this) { this.OnMessageAvailable += Recipient; } } #endregion #region Sniper(IEnumerable, IArrowReceiver.Recipient, Autostart = false, StartAsTask = false, InitialDelay = 0) /// <summary> /// The Sniper fetches messages/objects from the given IEnumerable /// and sends them to the recipients. /// </summary> /// <param name="IEnumerable">An IEnumerable&lt;S&gt; as element source.</param> /// <param name="Recipient">A recipient of the processed messages.</param> /// <param name="Autostart">Start the sniper automatically.</param> /// <param name="StartAsTask">Start the sniper within its own task.</param> /// <param name="InitialDelay">Set the initial delay of the sniper in milliseconds.</param> public Sniper(IEnumerable<TOut> IEnumerable, IArrowReceiver<TOut> Recipient, Boolean Autostart = false, Boolean StartAsTask = false, Nullable<TimeSpan> InitialDelay = null) : this(IEnumerable, Autostart, StartAsTask, InitialDelay) { #region Initial Checks if (Recipient == null) throw new ArgumentNullException("The given Recipient must not be null!"); #endregion lock (this) { this.OnMessageAvailable += Recipient.ReceiveMessage; } } #endregion #region Sniper(IEnumerator, Autostart = false, StartAsTask = false, InitialDelay = 0) /// <summary> /// The Sniper fetches messages/objects from the given IEnumerator /// and sends them to the recipients. /// </summary> /// <param name="IEnumerator">An IEnumerator&lt;S&gt; as element source.</param> /// <param name="Autostart">Start the sniper automatically.</param> /// <param name="StartAsTask">Start the sniper within its own task.</param> /// <param name="InitialDelay">Set the initial delay of the sniper in milliseconds.</param> public Sniper(IEnumerator<TOut> IEnumerator, Boolean Autostart = false, Boolean StartAsTask = false, Nullable<TimeSpan> InitialDelay = null) { #region Initial Checks if (IEnumerator == null) throw new ArgumentNullException("The given IEnumerator must not be null!"); #endregion this.IEnumerator = IEnumerator; this.InitialDelay = InitialDelay; if (Autostart) StartToFire(StartAsTask); } #endregion #region Sniper(IEnumerator, MessageRecipient.Recipient, Autostart = false, StartAsTask = false, InitialDelay = 0) /// <summary> /// The Sniper fetches messages/objects from the given IEnumerator /// and sends them to the recipients. /// </summary> /// <param name="IEnumerator">An IEnumerator&lt;S&gt; as element source.</param> /// <param name="Recipient">A recipient of the processed messages.</param> /// <param name="Autostart">Start the sniper automatically.</param> /// <param name="StartAsTask">Start the sniper within its own task.</param> /// <param name="InitialDelay">Set the initial delay of the sniper in milliseconds.</param> public Sniper(IEnumerator<TOut> IEnumerator, MessageRecipient<TOut> Recipient, Boolean Autostart = false, Boolean StartAsTask = false, Nullable<TimeSpan> InitialDelay = null) : this(IEnumerator, Autostart, StartAsTask, InitialDelay) { #region Initial Checks if (Recipient == null) throw new ArgumentNullException("The given Recipient must not be null!"); #endregion lock (this) { this.OnMessageAvailable += Recipient; } } #endregion #region Sniper(IEnumerator, IArrowReceiver.Recipient, Autostart = false, StartAsTask = false, InitialDelay = 0) /// <summary> /// The Sniper fetches messages/objects from the given IEnumerator /// and sends them to the recipients. /// </summary> /// <param name="IEnumerator">An IEnumerator&lt;S&gt; as element source.</param> /// <param name="Recipient">A recipient of the processed messages.</param> /// <param name="Autostart">Start the sniper automatically.</param> /// <param name="StartAsTask">Start the sniper within its own task.</param> /// <param name="InitialDelay">Set the initial delay of the sniper in milliseconds.</param> public Sniper(IEnumerator<TOut> IEnumerator, IArrowReceiver<TOut> Recipient, Boolean Autostart = false, Boolean StartAsTask = false, Nullable<TimeSpan> InitialDelay = null) : this(IEnumerator, Autostart, StartAsTask, InitialDelay) { #region Initial Checks if (Recipient == null) throw new ArgumentNullException("The given Recipient must not be null!"); #endregion lock (this) { this.OnMessageAvailable += Recipient.ReceiveMessage; } } #endregion #endregion #region SendTo(MessageRecipient.Recipients) /// <summary> /// Sends messages/objects to the given recipients. /// </summary> /// <param name="Recipients">The recipients of the processed messages.</param> public void SendTo(params MessageRecipient<TOut>[] Recipients) { lock (this) { if (Recipients != null) { foreach (var _Recipient in Recipients) this.OnMessageAvailable += _Recipient; } } } #endregion #region SendTo(IArrowReceiver.Recipients) /// <summary> /// Sends messages/objects to the given recipients. /// </summary> /// <param name="Recipients">The recipients of the processed messages.</param> public void SendTo(params IArrowReceiver<TOut>[] Recipients) { lock (this) { if (Recipients != null) { foreach (var _Recipient in Recipients) this.OnMessageAvailable += _Recipient.ReceiveMessage; } } } #endregion #region AsTask(TaskCreationOption = TaskCreationOptions.AttachedToParent) /// <summary> /// Create as task for the message/object fireing. /// </summary> /// <param name="TaskCreationOption">Specifies flags that control optional behavior for the creation and execution of tasks.</param> /// <returns>The created task.</returns> public Task AsTask(TaskCreationOptions TaskCreationOption = TaskCreationOptions.AttachedToParent) { FireCancellationTokenSource = new CancellationTokenSource(); FireCancellationToken = FireCancellationTokenSource.Token; FireTask = new Task(StartFireing, FireCancellationToken, TaskCreationOption); return FireTask; } #endregion #region (private) StartFireing() /// <summary> /// Starts the fireing. /// </summary> private void StartFireing() { try { if (IsTask) Thread.Sleep(InitialDelay.Value); if (OnMessageAvailable != null) { if (IEnumerator != null) { while (IEnumerator.MoveNext()) { OnMessageAvailable(this, IEnumerator.Current); // Sleep if we are in throttling mode while (LastFireTime + Intervall > DateTime.Now) Thread.Sleep(ThrottlingSleepDuration); LastFireTime = DateTime.Now; } } } if (OnCompleted != null) OnCompleted(this); } catch (Exception e) { if (OnError != null) OnError(this, e); } } #endregion #region StartToFire(StartAsTask = false) /// <summary> /// Starts the sniper fire! /// </summary> /// <param name="StartAsTask">Whether to run within a seperate task or not.</param> public void StartToFire(Boolean StartAsTask = false) { if (StartAsTask) { if (FireTask != null) FireTask.Start(); else { FireTask = AsTask(); FireTask.Start(); } } else StartFireing(); } #endregion } } #endif
Vanaheimr/Styx
Styx.MF/Arrows/Sniper.cs
C#
apache-2.0
16,469
using Foundation; using System; using UIKit; using de.upb.hip.mobile.pcl.BusinessLayer.Managers; using de.upb.hip.mobile.pcl.BusinessLayer.Models; using System.Collections.Generic; using CoreGraphics; namespace HiPMobile.iOS { public partial class ExhibitDetailsViewController : UIViewController { public Exhibit Exhibit { get; set; } public ExhibitDetailsViewController (IntPtr handle) : base (handle) { } public override void ViewDidLoad() { exhibitDetailsScrollView.Frame = new CoreGraphics.CGRect(0, 0, View.Frame.Width, View.Frame.Height); exhibitDetailsScrollView.ContentSize = new CoreGraphics.CGSize(exhibitDetailsScrollView.Frame.Size.Width * Exhibit.Pages.Count, exhibitDetailsScrollView.Frame.Size.Height); //exhibitDetailsScrollView.BackgroundColor = UIColor.Black; base.ViewDidLoad(); ScrollViewSource scrollViewSource = new ScrollViewSource(); scrollViewSource.DetailPages = Exhibit.Pages; // scrollViewSource.PageChanged += PageChanged; //will be needed for the audio control exhibitDetailsScrollView.Delegate = scrollViewSource; scrollViewSource.LoadInitialViews(exhibitDetailsScrollView); NavigationItem.Title = Exhibit.Name; } public override bool ShouldAutorotate() { return false; } public override UIInterfaceOrientationMask GetSupportedInterfaceOrientations() { return UIInterfaceOrientationMask.Portrait; } //void PageChanged(nint page) //{ // NavigationItem.Title = page.ToString(); //} private class ScrollViewSource : PagingScrollViewSource { public IList<Page> DetailPages; //internal event Action<nint> PageChanged; public override nint NumberOfPages() { return DetailPages.Count; } public override UIView GetPageView(UIScrollView scrollView, nint index) { Page page = DetailPages[(int)index]; //init view from xib instead this -> UIView pageView = new UIView(); pageView.BackgroundColor = index % 2 == 0? UIColor.Yellow: UIColor.Purple; //<-init view from xib instead this if (page.TimeSliderPage != null) { pageView = TimeSliderPageView.Create(page.TimeSliderPage); } return pageView; } public override void DecelerationEnded(UIScrollView scrollView) { base.DecelerationEnded(scrollView); // PageChanged(CurrentPage); } } } }
HiP-App/HiP-Mobile
HiPMobile/HiPMobile.iOS/ViewControllers/ExhibitDetailsViewController.cs
C#
apache-2.0
2,893
package hotelmania.ontology; import jade.content.*; import jade.util.leap.*; import jade.core.*; /** * Protege name: EndSimulation * @author ontology bean generator * @version 2014/05/23, 22:29:18 */ public class EndSimulation implements AgentAction { }
mklew/EMSE-Hotelmania-Ontology
ontology/src/main/java/hotelmania/ontology/EndSimulation.java
Java
apache-2.0
258
package com.gdn.venice.factory; import com.gdn.venice.persistence.VenOrderStatus; import com.gdn.venice.util.VeniceConstants; public class VenOrderStatusC { public static VenOrderStatus createVenOrderStatus(){ VenOrderStatus status = new VenOrderStatus(); status.setOrderStatusCode("C"); status.setOrderStatusId(VeniceConstants.VEN_ORDER_STATUS_C); return status; } }
yauritux/venice-legacy
Venice/Venice-Interface-Model/src/main/java/com/gdn/venice/factory/VenOrderStatusC.java
Java
apache-2.0
380
# Asterina marginalis Petr. SPECIES #### Status ACCEPTED #### According to Index Fungorum #### Published in null #### Original name Asterina marginalis Petr. ### Remarks null
mdoering/backbone
life/Fungi/Ascomycota/Dothideomycetes/Capnodiales/Asterinaceae/Asterina/Asterina marginalis/README.md
Markdown
apache-2.0
179
// flow-typed signature: f60a5f9217c7adc1d246cdf1c3ef0c39 // flow-typed version: <<STUB>>/eslint-plugin-react-native_v^3.1.0/flow_v0.53.0 /** * This is an autogenerated libdef stub for: * * 'eslint-plugin-react-native' * * Fill this stub out by replacing all the `any` types. * * Once filled out, we encourage you to share your work with the * community by sending a pull request to: * https://github.com/flowtype/flow-typed */ declare module 'eslint-plugin-react-native' { declare module.exports: any; } /** * We include stubs for each file inside this npm package in case you need to * require those files directly. Feel free to delete any files that aren't * needed. */ declare module 'eslint-plugin-react-native/lib/rules/no-color-literals' { declare module.exports: any; } declare module 'eslint-plugin-react-native/lib/rules/no-inline-styles' { declare module.exports: any; } declare module 'eslint-plugin-react-native/lib/rules/no-unused-styles' { declare module.exports: any; } declare module 'eslint-plugin-react-native/lib/rules/split-platform-components' { declare module.exports: any; } declare module 'eslint-plugin-react-native/lib/util/Components' { declare module.exports: any; } declare module 'eslint-plugin-react-native/lib/util/stylesheet' { declare module.exports: any; } declare module 'eslint-plugin-react-native/lib/util/variable' { declare module.exports: any; } // Filename aliases declare module 'eslint-plugin-react-native/index' { declare module.exports: $Exports<'eslint-plugin-react-native'>; } declare module 'eslint-plugin-react-native/index.js' { declare module.exports: $Exports<'eslint-plugin-react-native'>; } declare module 'eslint-plugin-react-native/lib/rules/no-color-literals.js' { declare module.exports: $Exports<'eslint-plugin-react-native/lib/rules/no-color-literals'>; } declare module 'eslint-plugin-react-native/lib/rules/no-inline-styles.js' { declare module.exports: $Exports<'eslint-plugin-react-native/lib/rules/no-inline-styles'>; } declare module 'eslint-plugin-react-native/lib/rules/no-unused-styles.js' { declare module.exports: $Exports<'eslint-plugin-react-native/lib/rules/no-unused-styles'>; } declare module 'eslint-plugin-react-native/lib/rules/split-platform-components.js' { declare module.exports: $Exports<'eslint-plugin-react-native/lib/rules/split-platform-components'>; } declare module 'eslint-plugin-react-native/lib/util/Components.js' { declare module.exports: $Exports<'eslint-plugin-react-native/lib/util/Components'>; } declare module 'eslint-plugin-react-native/lib/util/stylesheet.js' { declare module.exports: $Exports<'eslint-plugin-react-native/lib/util/stylesheet'>; } declare module 'eslint-plugin-react-native/lib/util/variable.js' { declare module.exports: $Exports<'eslint-plugin-react-native/lib/util/variable'>; }
kunall17/zulip-mobile
flow-typed/npm/eslint-plugin-react-native_vx.x.x.js
JavaScript
apache-2.0
2,864
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.googlecode.jtype.test; import java.lang.reflect.Type; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Set; import org.junit.Before; import com.googlecode.jtype.Types; /** * Provides support for testing with types. * * @author Mark Hobson */ public abstract class AbstractTypeTest { // fields ----------------------------------------------------------------- private Set<String> imports; // public methods --------------------------------------------------------- @Before public final void setUpAbstractTypeTest() { imports = Collections.unmodifiableSet(new HashSet<String>(createImports())); } // protected methods ------------------------------------------------------ protected void addImports(Set<Class<?>> imports) { // no-op } protected final Type type(String typeName) { return Types.valueOf(typeName, imports); } // private methods -------------------------------------------------------- private Set<String> createImports() { Set<Class<?>> classImports = new HashSet<Class<?>>(); addImports(classImports); return toClassNames(classImports); } private static Set<String> toClassNames(Collection<Class<?>> classes) { Set<String> names = new HashSet<String>(); for (Class<?> klass : classes) { names.add(klass.getName()); } return names; } }
markhobson/jtype
src/test/java/com/googlecode/jtype/test/AbstractTypeTest.java
Java
apache-2.0
1,956
package controllers.goods /** * Created by stanikol on 1/29/17. */ import javax.inject._ import akka.stream.Materializer import com.mohiva.play.silhouette.api.Silhouette import controllers.WebJarAssets import models.goods._ import play.api.Configuration import play.api.i18n.{ I18nSupport, Messages, MessagesApi } import play.api.libs.concurrent.Execution.Implicits._ import play.api.mvc._ import utils.auth.DefaultEnv class Goods @Inject() ( val goodsDAO: GoodsDAO, val goodsCategoriesDAO: GoodsCategoriesDAO, val silhouette: Silhouette[DefaultEnv], val config: Configuration, val messagesApi: MessagesApi, implicit val webJarAssets: WebJarAssets, implicit val mat: Materializer ) extends Controller with I18nSupport { val onSubmitMaxMemoryBuffer: Int = config.getBytes("blogOnSubmitMaxMemoryBuffer").getOrElse(512 * 1024L).asInstanceOf[Int] def showAllGoodsItems = silhouette.UserAwareAction.async { implicit request => goodsDAO.listAllGoods.map { goods: Seq[GoodsItemView] => Ok(views.html.goods.showAllGoodsItems(request.identity, goods)) } } def getGoodsItem(id: Long) = silhouette.UserAwareAction.async { implicit request => goodsDAO.getGoodsItem(id).map { goodsItemOpt => goodsItemOpt match { case None => Redirect(controllers.goods.routes.Goods.showAllGoodsItems()).flashing( "error" -> Messages("goods.item-not-found", id) ) case Some(goodsItem) => Ok(views.html.goods.showItem(request.identity, goodsItem)) } } } }
stanikol/walnuts
server/app/controllers/goods/Goods.scala
Scala
apache-2.0
1,543
"use strict"; var chai = require("chai"), checker = require("./password_checker"); let expect = chai.expect; describe("The password checker component", () => { describe("password encryption method", () => { it("can encrypt a password", () => { let input = "derp"; return checker.encryptPassword(input) .then(encrypted => expect(encrypted).to.not.equal(input)); }); it("throws an error if the password is undefined", () => { expect(() => checker.encryptPassword()).to.throw(); }); }); describe("password checking method", () => { it("throws an error if the test password is undefined", () => { expect(() => checker.isValidPassword(null, "some_hash")).to.throw(); }); it("throws an error if the hash is undefined", () => { expect(() => checker.isValidPassword("some_password")).to.throw(); }); it("can determine if an input password matches an encrypted password", () => { let existingPasswordPlain = "youshallnotpass"; return checker.encryptPassword(existingPasswordPlain) .then(encryptedPassword => checker.isValidPassword(existingPasswordPlain, encryptedPassword)) .then(isMatch => expect(isMatch).to.be.true); }); it("can determine if an input password does not match an encrypted password", () => { let existingPasswordPlain = "youshallnotpass"; return checker.encryptPassword(existingPasswordPlain) .then(encryptedPassword => checker.isValidPassword("derp derp", encryptedPassword)) .then(isMatch => expect(isMatch).to.be.false); }); }); });
atsid/drugfax-18f
server/components/password_checker.spec.js
JavaScript
apache-2.0
1,757
package it.prisma.businesslayer.bizlib.rest.apiclients.monitoring.zabbix.dsl.response; public class ErroreResponse { }
pon-prisma/PrismaDemo
BusinessLayer/src/main/java/it/prisma/businesslayer/bizlib/rest/apiclients/monitoring/zabbix/dsl/response/ErroreResponse.java
Java
apache-2.0
121
/* * JSR 354 JavaFX Binding Example */ package org.javamoney.examples.javafx; import javafx.beans.property.DoubleProperty; import javafx.beans.property.SimpleDoubleProperty; import org.javamoney.moneta.Money; import javax.money.CurrencyUnit; import javax.money.Monetary; /** * @author Werner Keil */ public class Bill { // Define the property private DoubleProperty amountDue = new SimpleDoubleProperty(); private double doubleValue = 10d; private CurrencyUnit currency = Monetary.getCurrency("DKK"); private Money newAmountDue = Money.of(doubleValue, currency); // Define a getter for the property's value public final double getAmountDue(){return amountDue.get();} public final Money getNewAmountDue() { return newAmountDue;} // Define a setter for the property's value public final void setAmountDue(double value){amountDue.set(value);} // Define a getter for the property itself public DoubleProperty amountDueProperty() {return amountDue;} }
JavaMoney/javamoney-examples
javafx/money-javafx-binding/src/main/java/org/javamoney/examples/javafx/Bill.java
Java
apache-2.0
1,041
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.sqoop.mapreduce; import java.io.IOException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.mapreduce.InputFormat; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.OutputFormat; import org.apache.sqoop.mapreduce.db.DBConfiguration; import org.apache.sqoop.mapreduce.db.DBOutputFormat; import com.cloudera.sqoop.manager.ConnManager; import com.cloudera.sqoop.manager.ExportJobContext; import com.google.common.base.Strings; /** * Run an export using JDBC (JDBC-based ExportCallOutputFormat) to * call the stored procedure. */ public class JdbcCallExportJob extends JdbcExportJob { public static final String SQOOP_EXPORT_CALL_KEY = "sqoop.export.call"; public static final Log LOG = LogFactory.getLog( JdbcCallExportJob.class.getName()); public JdbcCallExportJob(final ExportJobContext context) { super(context, null, null, ExportCallOutputFormat.class); } public JdbcCallExportJob(final ExportJobContext ctxt, final Class<? extends Mapper> mapperClass, final Class<? extends InputFormat> inputFormatClass, final Class<? extends OutputFormat> outputFormatClass) { super(ctxt, mapperClass, inputFormatClass, outputFormatClass); } /** * makes sure the job knows what stored procedure to call. */ @Override protected void propagateOptionsToJob(Job job) { super.propagateOptionsToJob(job); job.getConfiguration().set(SQOOP_EXPORT_CALL_KEY, options.getCall()); } @Override protected void configureOutputFormat(Job job, String tableName, String tableClassName) throws IOException { String procedureName = job.getConfiguration().get(SQOOP_EXPORT_CALL_KEY); ConnManager mgr = context.getConnManager(); try { if (Strings.isNullOrEmpty(options.getUsername())) { DBConfiguration.configureDB(job.getConfiguration(), mgr.getDriverClass(), options.getConnectString(), options.getConnectionParams()); } else { DBConfiguration.configureDB(job.getConfiguration(), mgr.getDriverClass(), options.getConnectString(), options.getUsername(), options.getPassword(), options.getConnectionParams()); } String [] colNames = options.getColumns(); if (null == colNames) { colNames = mgr.getColumnNamesForProcedure(procedureName); } DBOutputFormat.setOutput( job, mgr.escapeTableName(procedureName), mgr.escapeColNames(colNames)); job.setOutputFormatClass(getOutputFormatClass()); job.getConfiguration().set(SQOOP_EXPORT_TABLE_CLASS_KEY, tableClassName); } catch (ClassNotFoundException cnfe) { throw new IOException("Could not load OutputFormat", cnfe); } } }
bonnetb/sqoop
src/java/org/apache/sqoop/mapreduce/JdbcCallExportJob.java
Java
apache-2.0
3,709
import { Barman } from '.'; export class Service { id?: number; startAt: Date; endAt: Date; nbMax: number; // Association barmen?: Barman[]; constructor(values: Object = {}) { Object.assign(this, values); const castVal = values as Service; this.startAt = castVal.startAt ? new Date(castVal.startAt) : null; this.endAt = castVal.endAt ? new Date(castVal.endAt) : null; } isPassed(): boolean { return this.endAt.getTime() < Date.now(); } }
K-Fet/K-App
packages/client/src/app/shared/models/Service.ts
TypeScript
apache-2.0
486
#region Copyright /*Copyright (C) 2015 Wosad 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. */ #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace Wosad.Concrete.ACI318.Details.General { /// <summary> /// Interaction logic for Wosad.Concrete.ACI318.Details.RebarCastingPositionSelectionView.xaml /// </summary> public partial class RebarCastingPositionSelectionView: UserControl { public RebarCastingPositionSelectionView() { InitializeComponent(); } } }
Wosad/Wosad.Dynamo
Wosad.Dynamo.UI/Views/Concrete/ACI318/Details/RebarCastingPositionSelectionView.xaml.cs
C#
apache-2.0
1,380
#ifndef SimTK_UNITVEC_H #define SimTK_UNITVEC_H /* -------------------------------------------------------------------------- * * Simbody(tm): SimTKcommon * * -------------------------------------------------------------------------- * * This is part of the SimTK biosimulation toolkit originating from * * Simbios, the NIH National Center for Physics-Based Simulation of * * Biological Structures at Stanford, funded under the NIH Roadmap for * * Medical Research, grant U54 GM072970. See https://simtk.org/home/simbody. * * * * Portions copyright (c) 2005-12 Stanford University and the Authors. * * Authors: Michael Sherman * * Contributors: Paul Mitiguy * * * * 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. * * -------------------------------------------------------------------------- */ /** @file Declares and defines the UnitVec and UnitRow classes. **/ #include "SimTKcommon/SmallMatrix.h" #include "SimTKcommon/internal/CoordinateAxis.h" #include <iosfwd> // Forward declaration of iostream namespace SimTK { //----------------------------------------------------------------------------- // Forward declarations. These are templatized by precision P and and stride S // but always have length 3. TODO: this should be generalized to other lengths. template <class P, int S> class UnitVec; template <class P, int S> class UnitRow; // UnitVec3 is more intelligible name for UnitVec<Real,1>. typedef UnitVec<Real,1> UnitVec3; typedef UnitVec<float,1> fUnitVec3; typedef UnitVec<double,1> dUnitVec3; //----------------------------------------------------------------------------- /** * This class is a Vec3 plus an ironclad guarantee either that: * - the length is one (to within a very small tolerance), or * - all components are NaN. */ //----------------------------------------------------------------------------- template <class P, int S> class UnitVec : public Vec<3,P,S> { typedef P RealP; public: typedef Vec<3,P,S> BaseVec; typedef UnitRow<P,S> TransposeType; /// Default constructor initializes to all-NaN even in Release mode so that /// we maintain the above-promised contract. UnitVec() : BaseVec(NTraits<P>::getNaN()) {} /// Copy constructor does not require normalization since we know the /// source is a unit vector. UnitVec(const UnitVec& u) : BaseVec( static_cast<const BaseVec&>(u) ) {} /// Automatic conversion from UnitVec with different stride; no computation /// required. template <int S2> UnitVec(const UnitVec<P,S2>& u) : BaseVec( static_cast<const typename UnitVec<P,S2>::BaseVec&>(u) ) {} /// Explicit conversion from Vec to UnitVec, requiring expensive normalization. explicit UnitVec(const BaseVec& v) : BaseVec(v/v.norm()) {} /// Explicit conversion from Vec of any stride to this UnitVec, requiring /// expensive normalization. template <int S2> explicit UnitVec(const Vec<3,P,S2>& v) : BaseVec(v/v.norm()) {} /// Create a unit vector in the direction of the vector (x,y,z) whose measure /// numbers are supplied -- this requires an expensive normalization since /// we don't know that the supplied vector is normalized. UnitVec(const RealP& x, const RealP& y, const RealP& z) : BaseVec(x,y,z) { static_cast<BaseVec&>(*this) /= BaseVec::norm(); } /// Implicit conversion from a coordinate axis XAxis, YAxis, or ZAxis to /// a UnitVec3.\ Does not require any computation. UnitVec(const CoordinateAxis& axis) : BaseVec(0) { BaseVec::operator[](axis) = 1; } /// Implicit conversion from a coordinate axis direction to a /// UnitVec3.\ The axis direction is given by one of XAxis, YAxis, ZAxis /// or NegXAxis, NegYAxis, NegZAxis.\ Does not require any computation. UnitVec(const CoordinateDirection& dir) : BaseVec(0) { BaseVec::operator[](dir.getAxis()) = RealP(dir.getDirection()); } /// Construct a unit axis vector 100 010 001 given 0,1, or 2; this is not /// an implicit conversion. explicit UnitVec(int axis) : BaseVec(0) { assert(0 <= axis && axis <= 2); BaseVec::operator[](axis) = 1; } /// Copy assignment does not require normalization. UnitVec& operator=(const UnitVec& u) { BaseVec::operator=(static_cast<const BaseVec&>(u)); return *this; } /// Copy assignment from a UnitVec whose stride differs from this one; no /// normalization required. template <int S2> UnitVec& operator=(const UnitVec<P,S2>& u) { BaseVec::operator=(static_cast<const typename UnitVec<P,S2>::BaseVec&>(u)); return *this; } /// Return a reference to the underlying Vec3 (no copying here). const BaseVec& asVec3() const {return static_cast<const BaseVec&>(*this);} // Override Vec3 methods which preserve length. These return a // packed UnitVec regardless of our stride. /// Returns a new unit vector pointing in the opposite direction from this one; /// does \e not modify this UnitVec object. Cost is 3 flops. UnitVec<P,1> negate() const {return UnitVec<P,1>(-asVec3(),true);} /// Returns a new unit vector pointing in the opposite direction from this one. /// Cost is 3 flops. UnitVec<P,1> operator-() const {return negate();} /// Return a const reference to this unit vector re-expressed as a unit row; no /// computational cost. const TransposeType& operator~() const {return *reinterpret_cast<const TransposeType*>(this);} /// Return a writable reference to this unit vector re-expressed as a unit row; no /// computational cost. TransposeType& operator~() {return *reinterpret_cast<TransposeType*>(this);} // We have to define these here so that the non-const ones won't be // inherited. We don't trust anyone to write on one element of a UnitVec! /// Return one element of this unit vector as a const reference; there is no /// corresponding writable index function since changing a single element of /// a unit vector would violate the contract that it has unit length at all times. const RealP& operator[](int i) const { return BaseVec::operator[](i); } /// Return one element of this unit vector as a const reference; there is no /// corresponding writable index function since changing a single element of /// a unit vector would violate the contract that it has unit length at all times. const RealP& operator()(int i) const { return BaseVec::operator()(i); } /// Return a new unit vector whose measure numbers are the absolute values /// of the ones here. This will still have unit length but will be /// a reflection of this unit vector into the first octant (+x,+y,+z). /// Note that we are returning the packed form of UnitVec regardless /// of our stride here. UnitVec<P,1> abs() const {return UnitVec<P,1>( asVec3().abs(), true );} /// Return a new unit vector perpendicular to this one but otherwise /// arbitrary. Some care is taken to ensure good numerical conditioning /// for the result regardless of what goes in. Cost is about 50 flops. inline UnitVec<P,1> perp() const; /// This constructor is only for our friends whom we trust to /// give us an already-normalized vector which we simply accept as /// normalized without checking. UnitVec(const BaseVec& v, bool) : BaseVec(v) {} /// This constructor is only for our friends whom we trust to /// give us an already-normalized vector which we simply accept as /// normalized without checking (this version accepts an input /// vector of any stride). template <int S2> UnitVec(const Vec<3,RealP,S2>& v, bool) : BaseVec(v) { } }; template <class P, int S> inline UnitVec<P,1> UnitVec<P,S>::perp() const { // Choose the coordinate axis which makes the largest angle // with this vector, that is, has the "least u" along it. const UnitVec<P,1> u(abs()); // reflect to first octant const int minAxis = u[0] <= u[1] ? (u[0] <= u[2] ? 0 : 2) : (u[1] <= u[2] ? 1 : 2); // Cross returns a Vec3 result which is then normalized. return UnitVec<P,1>( *this % UnitVec<P,1>(minAxis) ); } /// Compare two UnitVec3 objects for exact, bitwise equality (not very useful). /// @relates UnitVec template <class P, int S1, int S2> inline bool operator==(const UnitVec<P,S1>& u1, const UnitVec<P,S2>& u2) { return u1.asVec3() == u2.asVec3(); } /// Compare two UnitVec3 objects and return true unless they are exactly /// bitwise equal (not very useful). /// @relates UnitVec template <class P, int S1, int S2> inline bool operator!=(const UnitVec<P,S1>& u1, const UnitVec<P,S2>& u2) { return !(u1==u2); } //----------------------------------------------------------------------------- /** * This type is used for the transpose of UnitVec, and as the returned row * type of a Rotation. Don't construct these directly. */ //----------------------------------------------------------------------------- template <class P, int S> class UnitRow : public Row<3,P,S> { typedef P RealP; public: typedef Row<3,P,S> BaseRow; typedef UnitVec<P,S> TransposeType; UnitRow() : BaseRow(NTraits<P>::getNaN()) { } /// Copy constructor does not require normalization. UnitRow(const UnitRow& u) : BaseRow(static_cast<const BaseRow&>(u)) {} /// Implicit conversion from UnitRow with different stride; no /// normalization required. template <int S2> UnitRow(const UnitRow<P,S2>& u) : BaseRow(static_cast<const typename UnitRow<P,S2>::BaseRow&>(u)) { } /// Copy assignment does not require normalization. UnitRow& operator=(const UnitRow& u) { BaseRow::operator=(static_cast<const BaseRow&>(u)); return *this; } /// Copy assignment from UnitRow with different stride; no computation needed. template <int S2> UnitRow& operator=(const UnitRow<P,S2>& u) { BaseRow::operator=(static_cast<const typename UnitRow<P,S2>::BaseRow&>(u)); return *this; } /// Explicit conversion from Row to UnitRow, requiring expensive normalization. explicit UnitRow(const BaseRow& v) : BaseRow(v/v.norm()) {} /// Explicit conversion from Row of any stride to UnitRow, requiring expensive /// normalization. template <int S2> explicit UnitRow(const Row<3,P,S2>& v) : BaseRow(v/v.norm()) {} /// Create a unit row from explicitly specified measure numbers (x,y,z); /// requires expensive normalization. UnitRow(const RealP& x, const RealP& y, const RealP& z) : BaseRow(x,y,z) { static_cast<BaseRow&>(*this) /= BaseRow::norm(); } /// Create a unit axis vector 100 010 001 given 0, 1, or 2. explicit UnitRow(int axis) : BaseRow(0) { assert(0 <= axis && axis <= 2); BaseRow::operator[](axis) = 1; } /// Return a const reference to the Row3 underlying this UnitRow. const BaseRow& asRow3() const {return static_cast<const BaseRow&>(*this);} // Override Row3 methods which preserve length. These return the // packed UnitRow regardless of our stride. /// Returns a new unit vector pointing in the opposite direction from this one; /// does \e not modify this UnitVec object. Cost is 3 flops. UnitRow<P,1> negate() const { return UnitRow<P,1>(-asRow3(),true); } /// Returns a new unit vector pointing in the opposite direction from this one. /// Cost is 3 flops. UnitRow<P,1> operator-() const { return negate();} /// Return a const reference to this UnitRow reinterpreted as a UnitVec; no /// computation requires since this is just a type cast. const TransposeType& operator~() const {return *reinterpret_cast<const TransposeType*>(this);} /// Return a writable reference to this UnitRow reinterpreted as a UnitVec; no /// computation requires since this is just a type cast. TransposeType& operator~() {return *reinterpret_cast<TransposeType*>(this);} // We have to define these here so that the non-const ones won't be // inherited. We don't trust anyone to write on one element of a UnitRow! /// Return one element of this unit row as a const reference; there is no /// corresponding writable index function since changing a single element of /// a unit vector would violate the contract that it has unit length at all times. const RealP& operator[](int i) const { return BaseRow::operator[](i); } /// Return one element of this unit row as a const reference; there is no /// corresponding writable index function since changing a single element of /// a unit vector would violate the contract that it has unit length at all times. const RealP& operator()(int i) const { return BaseRow::operator()(i); } /// Return a new UnitRow whose measure numbers are the absolute values /// of the ones here. This will still have unit length but will be /// a reflection of this unit vector into the first octant (+x,+y,+z). /// Note that we are returning the packed form of UnitRow regardless /// of our stride here. UnitRow<P,1> abs() const {return UnitRow<P,1>(asRow3().abs(),true);} /// Return a new UnitRow perpendicular to this one but otherwise /// arbitrary. Some care is taken to ensure good numerical conditioning /// for the result regardless of what goes in. Cost is about 50 flops. inline UnitRow<P,1> perp() const; // This constructor is only for our friends whom we trust to // give us an already-normalized vector. UnitRow( const BaseRow& v, bool ) : BaseRow(v) { } template <int S2> UnitRow( const Row<3,P,S2>& v, bool ) : BaseRow(v) { } }; template <class P, int S> inline UnitRow<P,1> UnitRow<P,S>::perp() const { // Choose the coordinate axis which makes the largest angle // with this vector, that is, has the "least u" along it. const UnitRow<P,1> u(abs()); // reflect to first octant const int minAxis = u[0] <= u[1] ? (u[0] <= u[2] ? 0 : 2) : (u[1] <= u[2] ? 1 : 2); // Cross returns a Row3 result which is then normalized. return UnitRow<P,1>(*this % UnitRow<P,1>(minAxis)); } /// Compare two UnitRow3 objects for exact, bitwise equality (not very useful). /// @relates UnitRow template <class P, int S1, int S2> inline bool operator==(const UnitRow<P,S1>& u1, const UnitRow<P,S2>& u2) { return u1.asRow3() == u2.asRow3(); } /// Compare two UnitRow3 objects and return true unless they are exactly /// bitwise equal (not very useful). /// @relates UnitRow template <class P, int S1, int S2> inline bool operator!=(const UnitRow<P,S1>& u1, const UnitRow<P,S2>& u2) { return !(u1==u2); } //------------------------------------------------------------------------------ } // End of namespace SimTK //-------------------------------------------------------------------------- #endif // SimTK_UNITVEC_H_ //--------------------------------------------------------------------------
opensim-org/opensim-metabolicsprobes
OpenSim 3.1/sdk/include/SimTK/include/SimTKcommon/internal/UnitVec.h
C
apache-2.0
16,378
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations from textwrap import dedent import pytest from pants.backend.docker.subsystems.dockerfile_parser import rules as parser_rules from pants.backend.docker.target_types import DockerImage from pants.backend.docker.util_rules.docker_build_context import ( DockerBuildContext, DockerBuildContextRequest, DockerVersionContextValue, ) from pants.backend.docker.util_rules.docker_build_context import rules as context_rules from pants.backend.python import target_types_rules from pants.backend.python.goals import package_pex_binary from pants.backend.python.goals.package_pex_binary import PexBinaryFieldSet from pants.backend.python.target_types import PexBinary from pants.backend.python.util_rules import pex_from_targets from pants.core.goals.package import BuiltPackage from pants.core.target_types import FilesGeneratorTarget from pants.core.target_types import rules as core_target_types_rules from pants.engine.addresses import Address from pants.engine.fs import Snapshot from pants.testutil.rule_runner import QueryRule, RuleRunner from pants.util.frozendict import FrozenDict @pytest.fixture def rule_runner() -> RuleRunner: rule_runner = RuleRunner( rules=[ *context_rules(), *core_target_types_rules(), *package_pex_binary.rules(), *parser_rules(), *pex_from_targets.rules(), *target_types_rules.rules(), QueryRule(BuiltPackage, [PexBinaryFieldSet]), QueryRule(DockerBuildContext, (DockerBuildContextRequest,)), ], target_types=[DockerImage, FilesGeneratorTarget, PexBinary], ) rule_runner.set_options([], env_inherit={"PATH", "PYENV_ROOT", "HOME"}) return rule_runner def assert_build_context( rule_runner: RuleRunner, address: Address, expected_files: list[str], expected_version_context: FrozenDict[str, DockerVersionContextValue] | None = None, ) -> None: context = rule_runner.request( DockerBuildContext, [ DockerBuildContextRequest( address=address, build_upstream_images=False, ) ], ) snapshot = rule_runner.request(Snapshot, [context.digest]) assert sorted(expected_files) == sorted(snapshot.files) if expected_version_context is not None: assert expected_version_context == context.version_context def test_file_dependencies(rule_runner: RuleRunner) -> None: # img_A -> files_A # img_A -> img_B -> files_B rule_runner.add_to_build_file( "src/a", dedent( """\ docker_image(name="img_A", dependencies=[":files_A", "src/b:img_B"]) files(name="files_A", sources=["files/**"]) """ ), ) rule_runner.add_to_build_file( "src/b", dedent( """\ docker_image(name="img_B", dependencies=[":files_B"]) files(name="files_B", sources=["files/**"]) """ ), ) rule_runner.create_files("src/a", ["Dockerfile"]) rule_runner.create_files("src/a/files", ["a01", "a02"]) rule_runner.create_files("src/b", ["Dockerfile"]) rule_runner.create_files("src/b/files", ["b01", "b02"]) # We want files_B in build context for img_B assert_build_context( rule_runner, Address("src/b", target_name="img_B"), expected_files=["src/b/Dockerfile", "src/b/files/b01", "src/b/files/b02"], ) # We want files_A in build context for img_A, but not files_B assert_build_context( rule_runner, Address("src/a", target_name="img_A"), expected_files=["src/a/Dockerfile", "src/a/files/a01", "src/a/files/a02"], ) # Mixed. rule_runner.add_to_build_file( "src/c", dedent( """\ docker_image(name="img_C", dependencies=["src/a:files_A", "src/b:files_B"]) """ ), ) rule_runner.create_files("src/c", ["Dockerfile"]) assert_build_context( rule_runner, Address("src/c", target_name="img_C"), expected_files=[ "src/c/Dockerfile", "src/a/files/a01", "src/a/files/a02", "src/b/files/b01", "src/b/files/b02", ], ) def test_files_out_of_tree(rule_runner: RuleRunner) -> None: # src/a:img_A -> res/static:files rule_runner.add_to_build_file( "src/a", dedent( """\ docker_image(name="img_A", dependencies=["res/static:files"]) """ ), ) rule_runner.add_to_build_file( "res/static", dedent( """\ files(name="files", sources=["!BUILD", "**/*"]) """ ), ) rule_runner.create_files("src/a", ["Dockerfile"]) rule_runner.create_files("res/static", ["s01", "s02"]) rule_runner.create_files("res/static/sub", ["s03"]) assert_build_context( rule_runner, Address("src/a", target_name="img_A"), expected_files=[ "src/a/Dockerfile", "res/static/s01", "res/static/s02", "res/static/sub/s03", ], ) def test_packaged_pex_path(rule_runner: RuleRunner) -> None: # This test is here to ensure that we catch if there is any change in the generated path where # built pex binaries go, as we rely on that for dependency inference in the Dockerfile. rule_runner.write_files( { "src/docker/BUILD": """docker_image(dependencies=["src/python/proj/cli:bin"])""", "src/docker/Dockerfile": """FROM python""", "src/python/proj/cli/BUILD": """pex_binary(name="bin", entry_point="main.py")""", "src/python/proj/cli/main.py": """print("cli main")""", } ) assert_build_context( rule_runner, Address("src/docker", target_name="docker"), expected_files=["src/docker/Dockerfile", "src.python.proj.cli/bin.pex"], ) def test_version_context_from_dockerfile(rule_runner: RuleRunner) -> None: rule_runner.write_files( { "src/docker/BUILD": """docker_image()""", "src/docker/Dockerfile": dedent( """\ FROM python:3.8 FROM alpine as interim FROM interim FROM scratch:1-1 as output """ ), } ) assert_build_context( rule_runner, Address("src/docker"), expected_files=["src/docker/Dockerfile"], expected_version_context=FrozenDict( { "baseimage": DockerVersionContextValue({"tag": "3.8"}), "stage0": DockerVersionContextValue({"tag": "3.8"}), "interim": DockerVersionContextValue({"tag": "latest"}), "stage2": DockerVersionContextValue({"tag": "latest"}), "output": DockerVersionContextValue({"tag": "1-1"}), } ), )
patricklaw/pants
src/python/pants/backend/docker/util_rules/docker_build_context_test.py
Python
apache-2.0
7,173
/** Appcelerator Kroll - licensed under the Apache Public License 2 see LICENSE * in the root folder for details on the license. Copyright (c) 2008 * Appcelerator, Inc. All Rights Reserved. */ #include <signal.h> #include "ruby_module.h" #include <Poco/Path.h> namespace kroll { KROLL_MODULE(RubyModule, STRING(MODULE_NAME), STRING(MODULE_VERSION)); RubyModule* RubyModule::instance_ = NULL; void RubyModule::Initialize() { RubyModule::instance_ = this; ruby_init(); ruby_init_loadpath(); // Add the application directoy to the Ruby include path so // that includes work in a intuitive way for application developers. ruby_incpush(host->GetApplication()->GetResourcesPath().c_str()); this->InitializeBinding(); host->AddModuleProvider(this); } void RubyModule::Stop() { KObjectRef global = this->host->GetGlobalObject(); global->Set("Ruby", Value::Undefined); Script::GetInstance()->RemoveScriptEvaluator(this->binding); this->binding = NULL; RubyModule::instance_ = NULL; ruby_cleanup(0); } void RubyModule::InitializeBinding() { // Expose the Ruby evaluator into Kroll KObjectRef global = this->host->GetGlobalObject(); this->binding = new RubyEvaluator(); global->Set("Ruby", Value::NewObject(binding)); Script::GetInstance()->AddScriptEvaluator(this->binding); // Bind the API global constant VALUE ruby_api_val = RubyUtils::KObjectToRubyValue(Value::NewObject(global)); rb_define_global_const(PRODUCT_NAME, ruby_api_val); } const static std::string ruby_suffix = "module.rb"; bool RubyModule::IsModule(std::string& path) { return (path.substr(path.length()-ruby_suffix.length()) == ruby_suffix); } Module* RubyModule::CreateModule(std::string& path) { rb_load_file(path.c_str()); ruby_exec(); // ruby_cleanup(); <-- at some point we need to call? Poco::Path p(path); std::string basename = p.getBaseName(); std::string name = basename.substr(0,basename.length()-ruby_suffix.length()+3); std::string moduledir = path.substr(0,path.length()-basename.length()-3); Logger *logger = Logger::Get("Ruby"); logger->Info("Loading Ruby path=%s", path.c_str()); return new RubyModuleInstance(host, path, moduledir, name); } }
mital/kroll
modules/ruby/ruby_module.cpp
C++
apache-2.0
2,229
/* * Copyright 2017-2018 the original author or 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. */ package example.springdata.jdbc.mybatis; /** * Age group for which a {@link LegoSet} is intended. * * @author Jens Schauder */ public enum AgeGroup { _0to3, _3to8, _8to12, _12andOlder }
thomasdarimont/spring-data-examples
jdbc/mybatis/src/main/java/example/springdata/jdbc/mybatis/AgeGroup.java
Java
apache-2.0
814
<!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_31) on Mon Oct 03 09:58:14 UTC 2016 --> <title>com.unity3d.ads.video Class Hierarchy (lib API)</title> <meta name="date" content="2016-10-03"> <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="com.unity3d.ads.video Class Hierarchy (lib 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>Class</li> <li class="navBarCell1Rev">Tree</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><a href="../../../../com/unity3d/ads/request/package-tree.html">Prev</a></li> <li><a href="../../../../com/unity3d/ads/webview/package-tree.html">Next</a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?com/unity3d/ads/video/package-tree.html" target="_top">Frames</a></li> <li><a href="package-tree.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"> <h1 class="title">Hierarchy For Package com.unity3d.ads.video</h1> <span class="packageHierarchyLabel">Package Hierarchies:</span> <ul class="horizontal"> <li><a href="../../../../overview-tree.html">All Packages</a></li> </ul> </div> <div class="contentContainer"> <h2 title="Class Hierarchy">Class Hierarchy</h2> <ul> <li type="circle">java.lang.<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang"><span class="typeNameLink">Object</span></a> <ul> <li type="circle">android.view.View (implements android.view.accessibility.AccessibilityEventSource, android.graphics.drawable.Drawable.Callback, android.view.KeyEvent.Callback) <ul> <li type="circle">android.view.SurfaceView <ul> <li type="circle">android.widget.VideoView (implements android.widget.MediaController.MediaPlayerControl) <ul> <li type="circle">com.unity3d.ads.video.<a href="../../../../com/unity3d/ads/video/VideoPlayerView.html" title="class in com.unity3d.ads.video"><span class="typeNameLink">VideoPlayerView</span></a> </li> </ul> </li> </ul> </li> </ul> </li> </ul> </li> </ul> <h2 title="Enum Hierarchy">Enum Hierarchy</h2> <ul> <li type="circle">java.lang.<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang"><span class="typeNameLink">Object</span></a> <ul> <li type="circle">java.lang.<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Enum.html?is-external=true" title="class or interface in java.lang"><span class="typeNameLink">Enum</span></a>&lt;E&gt; (implements java.lang.<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html?is-external=true" title="class or interface in java.lang">Comparable</a>&lt;T&gt;, java.io.<a href="http://docs.oracle.com/javase/7/docs/api/java/io/Serializable.html?is-external=true" title="class or interface in java.io">Serializable</a>) <ul> <li type="circle">com.unity3d.ads.video.<a href="../../../../com/unity3d/ads/video/VideoPlayerError.html" title="enum in com.unity3d.ads.video"><span class="typeNameLink">VideoPlayerError</span></a> </li> <li type="circle">com.unity3d.ads.video.<a href="../../../../com/unity3d/ads/video/VideoPlayerEvent.html" title="enum in com.unity3d.ads.video"><span class="typeNameLink">VideoPlayerEvent</span></a> </li> </ul> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li class="navBarCell1Rev">Tree</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><a href="../../../../com/unity3d/ads/request/package-tree.html">Prev</a></li> <li><a href="../../../../com/unity3d/ads/webview/package-tree.html">Next</a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?com/unity3d/ads/video/package-tree.html" target="_top">Frames</a></li> <li><a href="package-tree.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>
bradgearon/unity-ads-android
javadoc/com/unity3d/ads/video/package-tree.html
HTML
apache-2.0
6,491
package com.hpu.rule.bean; import android.content.Context; import cn.bmob.v3.BmobInstallation; public class MyBmobInstallation extends BmobInstallation { //设备 private String device; public MyBmobInstallation(Context context) { super(context); } public String getDevice() { return device; } public void setDevice(String device) { this.device = device; } }
hjshpu/zhidubao
app/src/main/java/com/hpu/rule/bean/MyBmobInstallation.java
Java
apache-2.0
421
import React, { Component, createRef } from 'react'; import PropTypes from 'prop-types'; import { FormattedMessage, injectIntl } from 'react-intl'; import { getExperiment, getParams, getRunInfo, getRunTags } from '../reducers/Reducers'; import { connect } from 'react-redux'; import './RunView.css'; import { HtmlTableView } from './HtmlTableView'; import { Link } from 'react-router-dom'; import Routes from '../routes'; import ArtifactPage from './ArtifactPage'; import { getLatestMetrics } from '../reducers/MetricReducer'; import { Experiment } from '../sdk/MlflowMessages'; import Utils from '../../common/utils/Utils'; import { NOTE_CONTENT_TAG, NoteInfo } from '../utils/NoteUtils'; import { RenameRunModal } from './modals/RenameRunModal'; import { EditableTagsTableView } from '../../common/components/EditableTagsTableView'; import { Button, Descriptions, message } from 'antd'; import { CollapsibleSection } from '../../common/components/CollapsibleSection'; import { EditableNote } from '../../common/components/EditableNote'; import { setTagApi, deleteTagApi } from '../actions'; import { PageHeader, OverflowMenu } from '../../shared/building_blocks/PageHeader'; export class RunViewImpl extends Component { static propTypes = { runUuid: PropTypes.string.isRequired, run: PropTypes.object.isRequired, experiment: PropTypes.instanceOf(Experiment).isRequired, experimentId: PropTypes.string.isRequired, params: PropTypes.object.isRequired, tags: PropTypes.object.isRequired, latestMetrics: PropTypes.object.isRequired, getMetricPagePath: PropTypes.func.isRequired, runDisplayName: PropTypes.string.isRequired, runName: PropTypes.string.isRequired, handleSetRunTag: PropTypes.func.isRequired, setTagApi: PropTypes.func.isRequired, deleteTagApi: PropTypes.func.isRequired, modelVersions: PropTypes.arrayOf(PropTypes.object), intl: PropTypes.shape({ formatMessage: PropTypes.func.isRequired }).isRequired, }; state = { showRunRenameModal: false, showNoteEditor: false, showTags: Utils.getVisibleTagValues(this.props.tags).length > 0, isTagsRequestPending: false, }; formRef = createRef(); componentDidMount() { const pageTitle = `${this.props.runDisplayName} - MLflow Run`; Utils.updatePageTitle(pageTitle); } handleRenameRunClick = () => { this.setState({ showRunRenameModal: true }); }; hideRenameRunModal = () => { this.setState({ showRunRenameModal: false }); }; handleAddTag = (values) => { const form = this.formRef.current; const { runUuid } = this.props; this.setState({ isTagsRequestPending: true }); this.props .setTagApi(runUuid, values.name, values.value) .then(() => { this.setState({ isTagsRequestPending: false }); form.resetFields(); }) .catch((ex) => { this.setState({ isTagsRequestPending: false }); console.error(ex); const errorMessage = ( <FormattedMessage defaultMessage='Failed to add tag. Error: {errorTrace}' description='Error message when add to tag feature fails' values={{ errorTrace: ex.getUserVisibleError() }} /> ); message.error(errorMessage); }); }; handleSaveEdit = ({ name, value }) => { const { runUuid } = this.props; return this.props.setTagApi(runUuid, name, value).catch((ex) => { console.error(ex); const errorMessage = ( <FormattedMessage defaultMessage='Failed to set tag. Error: {errorTrace}' description='Error message when updating or setting a tag feature fails' values={{ errorTrace: ex.getUserVisibleError() }} /> ); message.error(errorMessage); }); }; handleDeleteTag = ({ name }) => { const { runUuid } = this.props; return this.props.deleteTagApi(runUuid, name).catch((ex) => { console.error(ex); const errorMessage = ( <FormattedMessage defaultMessage='Failed to delete tag. Error: {errorTrace}' description='Error message when deleting a tag feature fails' values={{ errorTrace: ex.getUserVisibleError() }} /> ); message.error(errorMessage); }); }; getRunCommand() { const { tags, params } = this.props; let runCommand = null; const sourceName = Utils.getSourceName(tags); const sourceVersion = Utils.getSourceVersion(tags); const entryPointName = Utils.getEntryPointName(tags); const backend = Utils.getBackend(tags); if (Utils.getSourceType(tags) === 'PROJECT') { runCommand = 'mlflow run ' + shellEscape(sourceName); if (sourceVersion && sourceVersion !== 'latest') { runCommand += ' -v ' + shellEscape(sourceVersion); } if (entryPointName && entryPointName !== 'main') { runCommand += ' -e ' + shellEscape(entryPointName); } if (backend) { runCommand += ' -b ' + shellEscape(backend); } Object.values(params) .sort() .forEach((p) => { runCommand += ' -P ' + shellEscape(p.key + '=' + p.value); }); } return runCommand; } handleCancelEditNote = () => { this.setState({ showNoteEditor: false }); }; handleSubmitEditNote = (note) => { return this.props.handleSetRunTag(NOTE_CONTENT_TAG, note).then(() => { this.setState({ showNoteEditor: false }); }); }; startEditingDescription = (e) => { e.stopPropagation(); this.setState({ showNoteEditor: true }); }; static getRunStatusDisplayName(status) { return status !== 'RUNNING' ? status : 'UNFINISHED'; } handleCollapseChange() {} renderSectionTitle(title, count = 0) { if (count === 0) { return title; } return ( <> {title} ({count}) </> ); } render() { const { runUuid, run, params, tags, latestMetrics, getMetricPagePath, modelVersions, } = this.props; const { showNoteEditor, isTagsRequestPending } = this.state; const noteInfo = NoteInfo.fromTags(tags); const startTime = run.getStartTime() ? Utils.formatTimestamp(run.getStartTime()) : '(unknown)'; const duration = Utils.getDuration(run.getStartTime(), run.getEndTime()); const status = RunViewImpl.getRunStatusDisplayName(run.getStatus()); const lifecycleStage = run.getLifecycleStage(); const queryParams = window.location && window.location.search ? window.location.search : ''; const runCommand = this.getRunCommand(); const noteContent = noteInfo && noteInfo.content; const breadcrumbs = [ <Link to={Routes.getExperimentPageRoute(this.props.experiment.experiment_id)} data-test-id='experiment-runs-link' > {this.props.experiment.getName()} </Link>, this.props.runDisplayName, ]; /* eslint-disable prefer-const */ let feedbackForm; const plotTitle = this.props.intl.formatMessage({ defaultMessage: 'Plot chart', description: 'Link to the view the plot chart for the experiment run', }); return ( <div className='RunView'> <PageHeader title={<span data-test-id='runs-header'>{this.props.runDisplayName}</span>} breadcrumbs={breadcrumbs} feedbackForm={feedbackForm} > <OverflowMenu menu={[ { id: 'overflow-rename-button', onClick: this.handleRenameRunClick, itemName: ( <FormattedMessage defaultMessage='Rename' description='Menu item to rename an experiment run' /> ), }, ]} /> </PageHeader> <div className='header-container'> <RenameRunModal runUuid={runUuid} onClose={this.hideRenameRunModal} runName={this.props.runName} isOpen={this.state.showRunRenameModal} /> </div> {/* Metadata List */} <Descriptions className='metadata-list'> <Descriptions.Item label={this.props.intl.formatMessage({ defaultMessage: 'Date', description: 'Label for displaying the start time of the experiment ran', })} > {startTime} </Descriptions.Item> <Descriptions.Item label={this.props.intl.formatMessage({ defaultMessage: 'Source', description: 'Label for displaying source notebook of the experiment run', })} > <div style={{ display: 'flex', alignItems: 'center' }}> {Utils.renderSourceTypeIcon(tags)} {Utils.renderSource(tags, queryParams, runUuid)} </div> </Descriptions.Item> {Utils.getSourceVersion(tags) ? ( <Descriptions.Item label={this.props.intl.formatMessage({ defaultMessage: 'Git Commit', description: 'Label for displaying the tag or the commit hash of the git commit', })} > {Utils.renderVersion(tags, false)} </Descriptions.Item> ) : null} {Utils.getSourceType(tags) === 'PROJECT' ? ( <Descriptions.Item label={this.props.intl.formatMessage({ defaultMessage: 'Entry Point', description: 'Label for displaying entry point of the project', })} > {Utils.getEntryPointName(tags) || 'main'} </Descriptions.Item> ) : null} <Descriptions.Item label={this.props.intl.formatMessage({ defaultMessage: 'User', description: 'Label for displaying the user who created the experiment run', })} > {Utils.getUser(run, tags)} </Descriptions.Item> {duration ? ( <Descriptions.Item label={this.props.intl.formatMessage({ defaultMessage: 'Duration', description: 'Label for displaying the duration of the experiment run', })} > {duration} </Descriptions.Item> ) : null} <Descriptions.Item label={this.props.intl.formatMessage({ defaultMessage: 'Status', description: // eslint-disable-next-line max-len 'Label for displaying status of the experiment run to see if its running or finished', })} > {status} </Descriptions.Item> {lifecycleStage ? ( <Descriptions.Item label={this.props.intl.formatMessage({ defaultMessage: 'Lifecycle Stage', description: // eslint-disable-next-line max-len 'Label for displaying lifecycle stage of the experiment run to see if its active or deleted', })} > {lifecycleStage} </Descriptions.Item> ) : null} {tags['mlflow.parentRunId'] !== undefined ? ( <Descriptions.Item label={this.props.intl.formatMessage({ defaultMessage: 'Parent Run', description: 'Label for displaying a link to the parent experiment run if any present', })} > <Link to={Routes.getRunPageRoute( this.props.experimentId, tags['mlflow.parentRunId'].value, )} > {tags['mlflow.parentRunId'].value} </Link> </Descriptions.Item> ) : null} {tags['mlflow.databricks.runURL'] !== undefined ? ( <Descriptions.Item label={this.props.intl.formatMessage({ defaultMessage: 'Job Output', description: 'Label for displaying the output logs for the experiment run job', })} > <a href={Utils.setQueryParams(tags['mlflow.databricks.runURL'].value, queryParams)} target='_blank' > <FormattedMessage defaultMessage='Logs' description='Link to the logs for the job output' /> </a> </Descriptions.Item> ) : null} </Descriptions> {/* Page Sections */} <div className='RunView-info'> {runCommand ? ( <CollapsibleSection title={this.props.intl.formatMessage({ defaultMessage: 'Run Command', description: // eslint-disable-next-line max-len 'Label for the collapsible area to display the run command used for the experiment run', })} onChange={this.handleCollapseChange('runCommand')} data-test-id='run-command-section' > <textarea className='run-command text-area' readOnly value={runCommand} /> </CollapsibleSection> ) : null} <CollapsibleSection title={ <span> <FormattedMessage defaultMessage='Description' description='Label for the notes editable content for the experiment run' /> {!showNoteEditor && ( <> {' '} <Button type='link' onClick={this.startEditingDescription} data-test-id='edit-description-button' > <FormattedMessage defaultMessage='Edit' // eslint-disable-next-line max-len description='Text for the edit button next to the description section title on the run view' /> </Button> </> )} </span> } forceOpen={showNoteEditor} defaultCollapsed={!noteContent} onChange={this.handleCollapseChange('notes')} data-test-id='run-notes-section' > <EditableNote defaultMarkdown={noteContent} onSubmit={this.handleSubmitEditNote} onCancel={this.handleCancelEditNote} showEditor={showNoteEditor} /> </CollapsibleSection> <CollapsibleSection defaultCollapsed title={this.renderSectionTitle( this.props.intl.formatMessage({ defaultMessage: 'Parameters', description: // eslint-disable-next-line max-len 'Label for the collapsible area to display the parameters used during the experiment run', }), getParamValues(params).length, )} onChange={this.handleCollapseChange('parameters')} data-test-id='run-parameters-section' > <HtmlTableView testId='params-table' columns={[ { title: this.props.intl.formatMessage({ defaultMessage: 'Name', description: // eslint-disable-next-line max-len 'Column title for name column for displaying the params name for the experiment run', }), dataIndex: 'name', }, { title: this.props.intl.formatMessage({ defaultMessage: 'Value', description: // eslint-disable-next-line max-len 'Column title for value column for displaying the value of the params for the experiment run ', }), dataIndex: 'value', }, ]} values={getParamValues(params)} /> </CollapsibleSection> <CollapsibleSection defaultCollapsed title={this.renderSectionTitle( this.props.intl.formatMessage({ defaultMessage: 'Metrics', description: // eslint-disable-next-line max-len 'Label for the collapsible area to display the output metrics after the experiment run', }), getMetricValues(latestMetrics, getMetricPagePath, plotTitle).length, )} onChange={this.handleCollapseChange('metrics')} data-test-id='run-metrics-section' > <HtmlTableView testId='metrics-table' columns={[ { title: this.props.intl.formatMessage({ defaultMessage: 'Name', description: // eslint-disable-next-line max-len 'Column title for name column for displaying the metrics name for the experiment run', }), dataIndex: 'name', }, { title: this.props.intl.formatMessage({ defaultMessage: 'Value', description: // eslint-disable-next-line max-len 'Column title for value column for displaying the value of the metrics for the experiment run ', }), dataIndex: 'value', }, ]} values={getMetricValues(latestMetrics, getMetricPagePath, plotTitle)} /> </CollapsibleSection> <div data-test-id='tags-section'> <CollapsibleSection title={this.renderSectionTitle( this.props.intl.formatMessage({ defaultMessage: 'Tags', description: 'Label for the collapsible area to display the tags for the experiment run', }), Utils.getVisibleTagValues(tags).length, )} defaultCollapsed onChange={this.handleCollapseChange('tags')} data-test-id='run-tags-section' > <EditableTagsTableView innerRef={this.formRef} handleAddTag={this.handleAddTag} handleDeleteTag={this.handleDeleteTag} handleSaveEdit={this.handleSaveEdit} tags={tags} isRequestPending={isTagsRequestPending} /> </CollapsibleSection> </div> <CollapsibleSection title={this.props.intl.formatMessage({ defaultMessage: 'Artifacts', description: // eslint-disable-next-line max-len 'Label for the collapsible area to display the artifacts page', })} onChange={this.handleCollapseChange('artifacts')} data-test-id='run-artifacts-section' > <ArtifactPage runUuid={runUuid} modelVersions={modelVersions} runTags={tags} /> </CollapsibleSection> </div> </div> ); } handleSubmittedNote(err) { if (err) { // Do nothing; error is handled by the note editor view } else { // Successfully submitted note, close the editor this.setState({ showNotesEditor: false }); } } } const mapStateToProps = (state, ownProps) => { const { runUuid, experimentId } = ownProps; const run = getRunInfo(runUuid, state); const experiment = getExperiment(experimentId, state); const params = getParams(runUuid, state); const tags = getRunTags(runUuid, state); const latestMetrics = getLatestMetrics(runUuid, state); const runDisplayName = Utils.getRunDisplayName(tags, runUuid); const runName = Utils.getRunName(tags, runUuid); return { run, experiment, params, tags, latestMetrics, runDisplayName, runName }; }; const mapDispatchToProps = { setTagApi, deleteTagApi }; export const RunViewImplWithIntl = injectIntl(RunViewImpl); export const RunView = connect(mapStateToProps, mapDispatchToProps)(RunViewImplWithIntl); // Private helper functions. const getParamValues = (params) => { return Object.values(params) .sort() .map((p, index) => ({ key: `params-${index}`, name: p.getKey(), value: p.getValue() })); }; const getMetricValues = (latestMetrics, getMetricPagePath, plotTitle) => { return Object.values(latestMetrics) .sort() .map(({ key, value }, index) => { return { key: `metrics-${index}`, name: ( <Link to={getMetricPagePath(key)} title={plotTitle}> {key} <i className='fas fa-chart-line' style={{ paddingLeft: '6px' }} /> </Link> ), value: <span title={value}>{Utils.formatMetric(value)}</span>, }; }); }; const shellEscape = (str) => { if (/["\r\n\t ]/.test(str)) { return '"' + str.replace(/"/g, '\\"') + '"'; } return str; };
mlflow/mlflow
mlflow/server/js/src/experiment-tracking/components/RunView.js
JavaScript
apache-2.0
21,401
/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.support.v7.widget; import android.content.Context; import android.content.res.ColorStateList; import android.graphics.PorterDuff; import android.support.annotation.DrawableRes; import android.support.annotation.Nullable; import android.support.annotation.RequiresApi; import android.util.AttributeSet; import net.xpece.android.appcompatextra.R; import net.xpece.android.widget.TintableCompoundDrawableView; /** * {@link android.widget.EditText} which supports compound drawable tint on all platforms. */ public class XpAppCompatEditText extends AppCompatEditText implements TintableCompoundDrawableView { private final XpAppCompatCompoundDrawableHelper mTextCompoundDrawableHelper; public XpAppCompatEditText(Context context) { this(context, null); } public XpAppCompatEditText(Context context, AttributeSet attrs) { this(context, attrs, R.attr.editTextStyle); } public XpAppCompatEditText(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); mTextCompoundDrawableHelper = new XpAppCompatCompoundDrawableHelper(this); mTextCompoundDrawableHelper.loadFromAttributes(attrs, defStyleAttr); } @Override protected void drawableStateChanged() { super.drawableStateChanged(); if (mTextCompoundDrawableHelper != null) { mTextCompoundDrawableHelper.applySupportTint(); } } @RequiresApi(17) @Override public void setCompoundDrawablesRelativeWithIntrinsicBounds(@DrawableRes int start, @DrawableRes int top, @DrawableRes int end, @DrawableRes int bottom) { if (mTextCompoundDrawableHelper != null) { mTextCompoundDrawableHelper.setCompoundDrawablesRelativeWithIntrinsicBounds(start, top, end, bottom); } } @Override public void setCompoundDrawablesWithIntrinsicBounds(@DrawableRes int left, @DrawableRes int top, @DrawableRes int right, @DrawableRes int bottom) { if (mTextCompoundDrawableHelper != null) { mTextCompoundDrawableHelper.setCompoundDrawablesWithIntrinsicBounds(left, top, right, bottom); } } @Override public void setSupportCompoundDrawableTintList(@Nullable ColorStateList tint) { if (mTextCompoundDrawableHelper != null) { mTextCompoundDrawableHelper.setSupportTintList(tint); } } @Nullable @Override public ColorStateList getSupportCompoundDrawableTintList() { if (mTextCompoundDrawableHelper != null) { return mTextCompoundDrawableHelper.getSupportTintList(); } return null; } @Override public void setSupportCompoundDrawableTintMode(@Nullable PorterDuff.Mode tintMode) { if (mTextCompoundDrawableHelper != null) { mTextCompoundDrawableHelper.setSupportTintMode(tintMode); } } @Nullable @Override public PorterDuff.Mode getSupportCompoundDrawableTintMode() { if (mTextCompoundDrawableHelper != null) { return mTextCompoundDrawableHelper.getSupportTintMode(); } return null; } }
consp1racy/android-commons
appcompat-extra/src/main/java/android/support/v7/widget/XpAppCompatEditText.java
Java
apache-2.0
3,764
<!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 Wed Jul 20 08:39:15 PDT 2016 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Uses of Class com.fasterxml.jackson.databind.ext.DOMSerializer (jackson-databind 2.8.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 com.fasterxml.jackson.databind.ext.DOMSerializer (jackson-databind 2.8.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="../../../../../../com/fasterxml/jackson/databind/ext/DOMSerializer.html" title="class in com.fasterxml.jackson.databind.ext">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?com/fasterxml/jackson/databind/ext/class-use/DOMSerializer.html" target="_top">Frames</a></li> <li><a href="DOMSerializer.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 com.fasterxml.jackson.databind.ext.DOMSerializer" class="title">Uses of Class<br>com.fasterxml.jackson.databind.ext.DOMSerializer</h2> </div> <div class="classUseContainer">No usage of com.fasterxml.jackson.databind.ext.DOMSerializer</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="../../../../../../com/fasterxml/jackson/databind/ext/DOMSerializer.html" title="class in com.fasterxml.jackson.databind.ext">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?com/fasterxml/jackson/databind/ext/class-use/DOMSerializer.html" target="_top">Frames</a></li> <li><a href="DOMSerializer.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; 2008&#x2013;2016 <a href="http://fasterxml.com/">FasterXML</a>. All rights reserved.</small></p> </body> </html>
FasterXML/jackson-databind
docs/javadoc/2.8/com/fasterxml/jackson/databind/ext/class-use/DOMSerializer.html
HTML
apache-2.0
4,566
log("NOtification View.."); var win = Ti.UI.createWindow({ "backgroundColor": "yellow" }); function checkForIntent(){ var _intent = Ti.Android.currentActivity.getIntent(); log(JSON.stringify(_intent)); if (_intent.hasExtra('payload')) { Ti.API.info("*******found " + intent.getStringExtra('payload')); } } function log(msg){ Ti.API.info(msg); } win.addEventListener("open", function(e){ checkForIntent(); }); win.open();
linnal/TiAndroidNotification
app/assets/android/notificationView.js
JavaScript
apache-2.0
443
echo "-----------------------------------------------------------" execDir=. if [ "$1" = "" ] then echo "No directory given, default to current" Directory="." else echo "| Test id : $1" if [ -d "$1" ] then Directory="$1" else echo "$1 is not a directory. Exiting." exit 2 fi fi cd $Directory if [ -r "description" ] then echo "-----------------------------------------------------------" echo "Description :" fold -w 60 -s description echo "-----------------------------------------------------------" fi nTestCount=0 nSuccesfulTests=0 nStrResult="$1 " if [ -r "run" ] then sRun=`cat run` else echo "No run file found. Exiting." exit 2 fi echo $sRun # stdin has been specified if [ -r "std.in" ] then sRun="$sRun <std.in" fi # stdout has been specified if [ -r "std.out" ] then sRun="$sRun >temp.txt" fi # stderr has been specified if [ -r "stderr.out" ] then sRun="$sRun 2>temperr.txt" fi # execute the command line eval $sRun returnCode=$? resultGlobal="Ok" # compare return code if concerned resultRC="Non testé" if [ -r "returncode" ] then if [ "$returnCode" = `cat returncode` ] then echo " Return Code : PASSED" resultRC="Ok" else echo " Return Code : FAILED" resultRC="Echec" resultGlobal="Echec" fi fi # compare stdout if concerned resultOut="Non testé" if [ -r "std.out" ] then diff -wB temp.txt std.out >/dev/null if [ $? -eq 0 ] then echo " Stdout : PASSED" resultOut="Ok" else echo " Stdout : FAILED" resultOut="Echec" resultGlobal="Echec" fi # clean temporary out file rm temp.txt fi # compare stderr if concerned resultErr="Non testé" if [ -r "stderr.out" ] then diff -wB temperr.txt stderr.out >/dev/null if [ $? -eq 0 ] then echo " Stderr : PASSED" resultErr="Ok" else echo " Stderr : FAILED" resultErr="Echec" resultGlobal="Echec" fi # clean temporary out file rm temperr.txt fi # compare files created if concerned resultFiles="Non testé" if ls *.outfile &> /dev/null then number=1 for i in *.outfile do fileName=`basename $i .outfile` if [ -r $fileName ] then diff -wB $i $fileName if [ $? -eq 0 ] then echo " File #$number : PASSED" else echo " File #$number : FAILED" resultFiles="Echec" resultGlobal="Echec" fi rm $fileName else echo " File #$number : FAILED" resultFiles="Echec" resultGlobal="Echec" fi let "number=$number+1" done if [ $resultFiles = "Non testé" ] then resultFiles="Ok" fi fi echo " --------------------" if [ $resultGlobal = "Echec" ] then echo " Global : FAILED" else echo " Global : PASSED" fi echo "-----------------------------------------------------------" echo cd $execDir # log result in $2 if filename provided if [ "$2" != "" ] then if [ ! -w "$2" ] then touch $2 fi if [ -w "$2" ] then echo "$Directory;$resultRC;$resultOut;$resultErr;$resultFiles;$resultGlobal" >>$2 fi fi if [ $resultGlobal = "Echec" ] then exit 0 fi if [ $resultGlobal = "Ok" ] then exit 1 fi
bmarchon/LG_H4311
test/test.sh
Shell
apache-2.0
3,657
--- layout: page description: "It Is Never Too Late To Learn." --- {% for post in paginator.posts %} <div class="post-preview"> <a href="{{ post.url | prepend: site.baseurl }}"> <h2 class="post-title"> {{ post.title }} </h2> {% if post.subtitle %} <h3 class="post-subtitle"> {{ post.subtitle }} </h3> {% endif %} <div class="post-content-preview"> {{ post.content | strip_html | truncate:200 }} </div> </a> <p class="post-meta"> Posted by {% if post.author %}{{ post.author }}{% else %}{{ site.title }}{% endif %} on {{ post.date | date: "%B %-d, %Y" }} </p> </div> <hr> {% endfor %} <!-- Pager --> {% if paginator.total_pages > 1 %} <ul class="pager"> {% if paginator.previous_page %} <li class="previous"> <a href="{{ paginator.previous_page_path | prepend: site.baseurl | replace: '//', '/' }}">&larr; Newer Posts</a> </li> {% endif %} {% if paginator.next_page %} <li class="next"> <a href="{{ paginator.next_page_path | prepend: site.baseurl | replace: '//', '/' }}">Older Posts &rarr;</a> </li> {% endif %} </ul> {% endif %}
BoyuanZH/BoyuanZH.github.io
index.html
HTML
apache-2.0
1,205
package base; public class Player { private String name; private boolean AIControl; public Player(String name, boolean aIControl) { super(); this.name = name; AIControl = aIControl; } }
JayCee235/RTS-game
RTS game/src/base/Player.java
Java
apache-2.0
219
package io.stardog.email.emailers; import com.amazonaws.services.simpleemail.AmazonSimpleEmailService; import com.amazonaws.services.simpleemail.AmazonSimpleEmailServiceClient; import com.amazonaws.services.simpleemail.model.SendEmailResult; import com.google.common.collect.ImmutableMap; import io.stardog.email.data.EmailSendResult; import io.stardog.email.data.HandlebarsEmailTemplate; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class AmazonSesEmailerTest { private AmazonSimpleEmailServiceClient sesClient; private AmazonSesEmailer emailer; @Before public void setUp() throws Exception { sesClient = mock(AmazonSimpleEmailServiceClient.class); emailer = new AmazonSesEmailer(sesClient); } @Test public void sendTemplate() throws Exception { emailer.addTemplate(HandlebarsEmailTemplate.builder() .name("welcome") .fromEmail("support@example.com") .fromName("Support Team") .subject("Welcome, {name}") .contentHtml("{name}, welcome. You signed up with {email}. var={var} global={globalVar}") .build()); emailer.addGlobalVar("globalVar", "GLOBAL"); when(sesClient.sendEmail(any())).thenReturn(new SendEmailResult().withMessageId("123456")); EmailSendResult result = emailer.sendTemplate("welcome", "bob@example.com", "Bob Smith", ImmutableMap.of("var", "foo")); assertEquals("123456", result.getMessageId()); } }
stardogventures/templatemail
src/test/java/io/stardog/email/emailers/AmazonSesEmailerTest.java
Java
apache-2.0
1,678
/*! \file main.c \brief master send and slave receive data use interrupt mode */ /* Copyright (C) 2016 GigaDevice 2014-12-26, V1.0.0, firmware for GD32F1x0(x=3,5) 2016-01-15, V2.0.0, firmware for GD32F1x0(x=3,5,7,9) 2016-04-30, V3.0.0, firmware update for GD32F1x0(x=3,5,7,9) */ #include "gd32f1x0.h" #include "gd32f1x0_it.h" #include "gd32f1x0_eval.h" #define arraysize 10 uint32_t send_n = 0, receive_n = 0; uint8_t spi0_send_array[arraysize] = {0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 0xA8, 0xA9, 0xAA }; uint8_t spi1_receive_array[arraysize]; ErrStatus memory_compare(uint8_t* src, uint8_t* dst, uint8_t length); void rcu_config(void); void gpio_config(void); void spi_config(void); /*! \brief main function \param[in] none \param[out] none \retval none */ int main(void) { /* init led1 */ gd_eval_ledinit (LED1); /* NVIC config */ nvic_priority_group_set(NVIC_PRIGROUP_PRE1_SUB3); nvic_irq_enable(SPI0_IRQn,1,1); nvic_irq_enable(SPI1_IRQn,0,1); /* peripheral clock enable */ rcu_config(); /* GPIO config */ gpio_config(); /* SPI config */ spi_config(); /* SPI int enable */ spi_i2s_interrupt_enable(SPI0, SPI_I2S_INT_TBE); spi_i2s_interrupt_enable(SPI1, SPI_I2S_INT_RBNE); /* SPI enable */ spi_enable(SPI1); spi_enable(SPI0); /* wait transmit complete */ while(receive_n < arraysize); /* compare receive data with send data */ if(memory_compare(spi1_receive_array, spi0_send_array, arraysize)) gd_eval_ledon(LED1); else gd_eval_ledoff(LED1); while(1); } /*! \brief configure different peripheral clocks \param[in] none \param[out] none \retval none */ void rcu_config(void) { rcu_periph_clock_enable(RCU_GPIOA); rcu_periph_clock_enable(RCU_GPIOB); rcu_periph_clock_enable(RCU_SPI0); rcu_periph_clock_enable(RCU_SPI1); } /*! \brief configure the GPIO peripheral \param[in] none \param[out] none \retval none */ void gpio_config(void) { /* SPI0 GPIO config */ gpio_af_set(GPIOA, GPIO_AF_0, GPIO_PIN_5 | GPIO_PIN_6 | GPIO_PIN_7); gpio_mode_set(GPIOA, GPIO_MODE_AF, GPIO_PUPD_NONE, GPIO_PIN_5 | GPIO_PIN_6 | GPIO_PIN_7); gpio_output_options_set(GPIOA, GPIO_OTYPE_PP, GPIO_OSPEED_50MHZ, GPIO_PIN_5 | GPIO_PIN_6 | GPIO_PIN_7); /* SPI1 GPIO config */ gpio_af_set(GPIOB, GPIO_AF_0, GPIO_PIN_13 | GPIO_PIN_14 |GPIO_PIN_15); gpio_mode_set(GPIOB, GPIO_MODE_AF, GPIO_PUPD_NONE, GPIO_PIN_13 | GPIO_PIN_14 |GPIO_PIN_15); gpio_output_options_set(GPIOB, GPIO_OTYPE_PP, GPIO_OSPEED_50MHZ, GPIO_PIN_13 | GPIO_PIN_14 |GPIO_PIN_15); } /*! \brief configure the SPI peripheral \param[in] none \param[out] none \retval none */ void spi_config(void) { spi_parameter_struct spi_init_struct; /* SPI0 parameter config */ spi_init_struct.spi_transmode = SPI_TRANSMODE_FULLDUPLEX; spi_init_struct.spi_devicemode = SPI_MASTER;; spi_init_struct.spi_framesize = SPI_FRAMESIZE_8BIT;; spi_init_struct.spi_ck_pl_ph = SPI_CK_PL_HIGH_PH_2EDGE; spi_init_struct.spi_nss = SPI_NSS_SOFT; spi_init_struct.spi_psc = SPI_PSC_4 ; spi_init_struct.spi_endian = SPI_ENDIAN_MSB;; spi_init(SPI0, &spi_init_struct); /* SPI1 parameter config */ spi_init_struct.spi_devicemode = SPI_SLAVE; spi_init_struct.spi_nss = SPI_NSS_SOFT; spi_init(SPI1, &spi_init_struct); } /*! \brief memory compare function \param[in] src : source data pointer \param[in] dst : destination data pointer \param[in] length : the compare data length \param[out] none \retval ErrStatus : ERROR or SUCCESS */ ErrStatus memory_compare(uint8_t* src, uint8_t* dst, uint8_t length) { while (length--){ if (*src++ != *dst++) return ERROR; } return SUCCESS; }
liuxuming/trochili
firmware/GD32F1x0_Firmware_Library_V3.0.0/Examples/SPI/Master_transmit_slave_receive_interrupt/main.c
C
apache-2.0
3,919