code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
// Copyright 2016 The Periph Authors. All rights reserved. // Use of this source code is governed under the Apache License, Version 2.0 // that can be found in the LICENSE file. package driverskeleton import ( "strings" "testing" "periph.io/x/periph" "periph.io/x/periph/conn/i2c/i2ctest" ) func TestDriverSkeleton(t *testing.T) { // FIXME: Try to include basic code coverage. You can use "replay" tests by // leveraging i2ctest and spitest. bus := i2ctest.Playback{ Ops: []i2ctest.IO{ // Initial detection in New(). {Addr: 42, W: []byte("in"), R: []byte("IN")}, // Read(). {Addr: 42, W: []byte("what"), R: []byte("Hello world!")}, }, DontPanic: true, } dev, err := New(&bus) if err != nil { t.Fatal(err) } if data := dev.Read(); data != "Hello world!" { t.Fatal(data) } // Playback is empty. if data := dev.Read(); !strings.HasPrefix(data, "i2ctest: unexpected Tx()") { t.Fatal(data) } } func TestDriverSkeleton_empty(t *testing.T) { if dev, err := New(&i2ctest.Playback{DontPanic: true}); dev != nil || err == nil { t.Fatal("Tx should have failed") } } func TestDriverSkeleton_init_failed(t *testing.T) { bus := i2ctest.Playback{ Ops: []i2ctest.IO{ {Addr: 42, W: []byte("in"), R: []byte("xx")}, }, } if dev, err := New(&bus); dev != nil || err == nil { t.Fatal("New should have failed") } } func TestInit(t *testing.T) { if state, err := periph.Init(); err != nil { t.Fatal(state, err) } }
google/periph
experimental/driverskeleton/driverskeleton_test.go
GO
apache-2.0
1,462
emailForm = function() { var remite = prompt("Introduzca correo de contacto: "); document.getElementById("remite").value; if (remite != '' && remite != null && nombre != '' && nombre != null && telefono != '' && telefono != null) { itemsString = ""; esubtotal = 0; egastos = 0; etotal = 0; for( var current in this.items ){ var item = this.items[current]; esubtotal = item.quantity * item.price; itemsString += item.name; if (item.size) itemsString += " " + item.size + "\n"; itemsString += item.quantity + " x " + item.price + " = " + String(esubtotal) + " " + me.currency + "\n"; etotal += esubtotal; }; itemsString += "\nSubtotal = " + etotal + " " + me.currency +"\n"; var gastos = me.shippingCost; if (formapago == "Contra-reembolso") { gastos += 8; etotal += 8; } if (gastos){ itemsString += "Gastos de envio = " + gastos + " " + me.currency +"\n"; etotal += me.shippingCost; } else {itemsString += "Gastos de envio = GRATIS\n";} itemsString +="\nTOTAL: " + String(etotal) + me.currency + "\n\n" + "Remitente: " + remite; itemsString +="\n\nNOMBRE: " + nombre + "\nTelefono: " + telefono; itemsString +="\nDIRECCION: " + direccion; itemsString +="\nCIUDAD/PAIS: " + codigo + " " + ciudad + " - " + provincia + " (" + pais + ")"; itemsString +="\n\nOBSERVACIONES: " + observaciones; itemsString +="\n\nFORMA DE PAGO: " + formapago; var form = document.createElement("form"); form.style.display = "none"; form.method = "POST"; form.action = "http://kamillustore.16mb.com/emailform.php"; form.acceptCharset = "utf-8"; form.appendChild(this.createHiddenElement("jcitems", itemsString)); form.appendChild(this.createHiddenElement("jcremite", remite)); document.body.appendChild(form); me.empty(); form.submit(); document.body.removeChild(form); if (p == null || p==''); } return; };
Kamillu/kamillu.github.io
emailform.js
JavaScript
apache-2.0
2,020
# Hieracium montserratii Mateo SPECIES #### Status ACCEPTED #### According to Euro+Med Plantbase #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Hieracium/Hieracium montserratii/README.md
Markdown
apache-2.0
165
/* // Licensed to Julian Hyde under one or more contributor license // agreements. See the NOTICE file distributed with this work for // additional information regarding copyright ownership. // // Julian Hyde 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 net.hydromatic.optiq.model; import net.hydromatic.optiq.*; import net.hydromatic.optiq.impl.*; import net.hydromatic.optiq.impl.jdbc.JdbcSchema; import net.hydromatic.optiq.jdbc.OptiqConnection; import net.hydromatic.optiq.jdbc.OptiqSchema; import org.eigenbase.util.Pair; import org.eigenbase.util.Util; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableList; import java.io.File; import java.io.IOException; import java.sql.SQLException; import java.util.*; import javax.sql.DataSource; import static org.eigenbase.util.Stacks.*; /** * Reads a model and creates schema objects accordingly. */ public class ModelHandler { private final OptiqConnection connection; private final List<Pair<String, SchemaPlus>> schemaStack = new ArrayList<Pair<String, SchemaPlus>>(); public ModelHandler(OptiqConnection connection, String uri) throws IOException { super(); this.connection = connection; final ObjectMapper mapper = new ObjectMapper(); mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true); mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true); JsonRoot root; if (uri.startsWith("inline:")) { root = mapper.readValue( uri.substring("inline:".length()), JsonRoot.class); } else { root = mapper.readValue(new File(uri), JsonRoot.class); } visit(root); } /** Creates and validates a ScalarFunctionImpl. */ public static void create(SchemaPlus schema, String functionName, List<String> path, String className, String methodName) { final Class<?> clazz; try { clazz = Class.forName(className); } catch (ClassNotFoundException e) { throw new RuntimeException("UDF class '" + className + "' not found"); } // Must look for TableMacro before ScalarFunction. Both have an "eval" // method. final TableFunction tableFunction = TableFunctionImpl.create(clazz); if (tableFunction != null) { schema.add(functionName, tableFunction); return; } final TableMacro macro = TableMacroImpl.create(clazz); if (macro != null) { schema.add(functionName, macro); return; } if (methodName != null && methodName.equals("*")) { for (Map.Entry<String, ScalarFunction> entry : ScalarFunctionImpl.createAll(clazz).entries()) { schema.add(entry.getKey(), entry.getValue()); } return; } else { final ScalarFunction function = ScalarFunctionImpl.create(clazz, Util.first(methodName, "eval")); if (function != null) { schema.add(Util.first(functionName, methodName), function); return; } } if (methodName == null) { final AggregateFunction aggFunction = AggregateFunctionImpl.create(clazz); if (aggFunction != null) { schema.add(functionName, aggFunction); return; } } throw new RuntimeException("Not a valid function class: " + clazz + ". Scalar functions and table macros have an 'eval' method; " + "aggregate functions have 'init' and 'add' methods, and optionally " + "'initAdd', 'merge' and 'result' methods."); } public void visit(JsonRoot root) { final Pair<String, SchemaPlus> pair = Pair.of(null, connection.getRootSchema()); push(schemaStack, pair); for (JsonSchema schema : root.schemas) { schema.accept(this); } pop(schemaStack, pair); if (root.defaultSchema != null) { try { connection.setSchema(root.defaultSchema); } catch (SQLException e) { throw new RuntimeException(e); } } } public void visit(JsonMapSchema jsonSchema) { final SchemaPlus parentSchema = currentMutableSchema("schema"); final SchemaPlus schema = parentSchema.add(jsonSchema.name, new AbstractSchema()); if (jsonSchema.path != null) { schema.setPath(stringListList(jsonSchema.path)); } populateSchema(jsonSchema, schema); if (schema.getName().equals("mat")) { // Inject by hand a Star Table. Later we'll add a JSON model element. final List<Table> tables = new ArrayList<Table>(); final String[] tableNames = { "sales_fact_1997", "time_by_day", "product", "product_class" }; final SchemaPlus schema2 = parentSchema.getSubSchema("foodmart"); for (String tableName : tableNames) { tables.add(schema2.getTable(tableName)); } final String tableName = "star"; schema.add(tableName, StarTable.of(tables)); } } private static ImmutableList<ImmutableList<String>> stringListList( List path) { final ImmutableList.Builder<ImmutableList<String>> builder = ImmutableList.builder(); for (Object s : path) { builder.add(stringList(s)); } return builder.build(); } private static ImmutableList<String> stringList(Object s) { if (s instanceof String) { return ImmutableList.of((String) s); } else if (s instanceof List) { final ImmutableList.Builder<String> builder2 = ImmutableList.builder(); for (Object o : (List) s) { if (o instanceof String) { builder2.add((String) o); } else { throw new RuntimeException("Invalid path element " + o + "; was expecting string"); } } return builder2.build(); } else { throw new RuntimeException("Invalid path element " + s + "; was expecting string or list of string"); } } private void populateSchema(JsonSchema jsonSchema, SchemaPlus schema) { boolean cache = jsonSchema.cache == null || jsonSchema.cache; schema.setCacheEnabled(cache); final Pair<String, SchemaPlus> pair = Pair.of(jsonSchema.name, schema); push(schemaStack, pair); jsonSchema.visitChildren(this); pop(schemaStack, pair); } public void visit(JsonCustomSchema jsonSchema) { try { final SchemaPlus parentSchema = currentMutableSchema("sub-schema"); final Class clazz = Class.forName(jsonSchema.factory); final SchemaFactory schemaFactory = (SchemaFactory) clazz.newInstance(); final Schema schema = schemaFactory.create( parentSchema, jsonSchema.name, jsonSchema.operand); final SchemaPlus optiqSchema = parentSchema.add(jsonSchema.name, schema); populateSchema(jsonSchema, optiqSchema); } catch (Exception e) { throw new RuntimeException("Error instantiating " + jsonSchema, e); } } public void visit(JsonJdbcSchema jsonSchema) { final SchemaPlus parentSchema = currentMutableSchema("jdbc schema"); final DataSource dataSource = JdbcSchema.dataSource(jsonSchema.jdbcUrl, jsonSchema.jdbcDriver, jsonSchema.jdbcUser, jsonSchema.jdbcPassword); JdbcSchema schema = JdbcSchema.create(parentSchema, jsonSchema.name, dataSource, jsonSchema.jdbcCatalog, jsonSchema.jdbcSchema); final SchemaPlus optiqSchema = parentSchema.add(jsonSchema.name, schema); populateSchema(jsonSchema, optiqSchema); } public void visit(JsonMaterialization jsonMaterialization) { try { final SchemaPlus schema = currentSchema(); if (!schema.isMutable()) { throw new RuntimeException( "Cannot define materialization; parent schema '" + currentSchemaName() + "' is not a SemiMutableSchema"); } OptiqSchema optiqSchema = OptiqSchema.from(schema); schema.add(jsonMaterialization.view, MaterializedViewTable.create( optiqSchema, jsonMaterialization.sql, null, jsonMaterialization.table)); } catch (Exception e) { throw new RuntimeException("Error instantiating " + jsonMaterialization, e); } } public void visit(JsonCustomTable jsonTable) { try { final SchemaPlus schema = currentMutableSchema("table"); final Class clazz = Class.forName(jsonTable.factory); final TableFactory tableFactory = (TableFactory) clazz.newInstance(); final Table table = tableFactory.create(schema, jsonTable.name, jsonTable.operand, null); schema.add(jsonTable.name, table); } catch (Exception e) { throw new RuntimeException("Error instantiating " + jsonTable, e); } } public void visit(JsonView jsonView) { try { final SchemaPlus schema = currentMutableSchema("view"); final List<String> path = Util.first(jsonView.path, currentSchemaPath()); schema.add(jsonView.name, ViewTable.viewMacro(schema, jsonView.sql, path)); } catch (Exception e) { throw new RuntimeException("Error instantiating " + jsonView, e); } } private List<String> currentSchemaPath() { return Collections.singletonList(peek(schemaStack).left); } private SchemaPlus currentSchema() { return peek(schemaStack).right; } private String currentSchemaName() { return peek(schemaStack).left; } private SchemaPlus currentMutableSchema(String elementType) { final SchemaPlus schema = currentSchema(); if (!schema.isMutable()) { throw new RuntimeException( "Cannot define " + elementType + "; parent schema '" + schema.getName() + "' is not mutable"); } return schema; } public void visit(JsonFunction jsonFunction) { try { final SchemaPlus schema = currentMutableSchema("function"); final List<String> path = Util.first(jsonFunction.path, currentSchemaPath()); create(schema, jsonFunction.name, path, jsonFunction.className, jsonFunction.methodName); } catch (Exception e) { throw new RuntimeException("Error instantiating " + jsonFunction, e); } } } // End ModelHandler.java
mprudhom/incubator-optiq
core/src/main/java/net/hydromatic/optiq/model/ModelHandler.java
Java
apache-2.0
10,744
/* Copyright 2006 Jerry Huxtable 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.osgeo.proj4j.units; import java.text.DecimalFormat; import java.text.FieldPosition; import java.text.NumberFormat; import java.text.ParsePosition; import org.osgeo.proj4j.util.ProjectionMath; /** * A NumberFormat for formatting Angles in various commonly-found mapping styles. */ public class AngleFormat extends NumberFormat { public final static String ddmmssPattern = "DdM"; public final static String ddmmssPattern2 = "DdM'S\""; public final static String ddmmssLongPattern = "DdM'S\"W"; public final static String ddmmssLatPattern = "DdM'S\"N"; public final static String ddmmssPattern4 = "DdMmSs"; public final static String decimalPattern = "D.F"; private DecimalFormat format; private String pattern; private boolean isDegrees; public AngleFormat() { this(ddmmssPattern); } public AngleFormat(String pattern) { this(pattern, false); } public AngleFormat(String pattern, boolean isDegrees) { this.pattern = pattern; this.isDegrees = isDegrees; format = new DecimalFormat(); format.setMaximumFractionDigits(0); format.setGroupingUsed(false); } public StringBuffer format(long number, StringBuffer result, FieldPosition fieldPosition) { return format((double)number, result, fieldPosition); } public StringBuffer format(double number, StringBuffer result, FieldPosition fieldPosition) { int length = pattern.length(); int f; boolean negative = false; if (number < 0) { for (int i = length-1; i >= 0; i--) { char c = pattern.charAt(i); if (c == 'W' || c == 'N') { number = -number; negative = true; break; } } } double ddmmss = isDegrees ? number : Math.toDegrees(number); int iddmmss = (int)Math.round(ddmmss * 3600); if (iddmmss < 0) iddmmss = -iddmmss; int fraction = iddmmss % 3600; for (int i = 0; i < length; i++) { char c = pattern.charAt(i); switch (c) { case 'R': result.append(number); break; case 'D': result.append((int)ddmmss); break; case 'M': f = fraction / 60; if (f < 10) result.append('0'); result.append(f); break; case 'S': f = fraction % 60; if (f < 10) result.append('0'); result.append(f); break; case 'F': result.append(fraction); break; case 'W': if (negative) result.append('W'); else result.append('E'); break; case 'N': if (negative) result.append('S'); else result.append('N'); break; default: result.append(c); break; } } return result; } public Number parse(String text, ParsePosition parsePosition) { double d = 0, m = 0, s = 0; double result; boolean negate = false; int length = text.length(); if (length > 0) { char c = Character.toUpperCase(text.charAt(length-1)); switch (c) { case 'W': case 'S': negate = true; // Fall into... case 'E': case 'N': text = text.substring(0, length-1); break; } } int i = text.indexOf('d'); if (i == -1) i = text.indexOf('\u00b0'); if (i != -1) { String dd = text.substring(0, i); String mmss = text.substring(i+1); d = Double.valueOf(dd).doubleValue(); i = mmss.indexOf('m'); if (i == -1) i = mmss.indexOf('\''); if (i != -1) { if (i != 0) { String mm = mmss.substring(0, i); m = Double.valueOf(mm).doubleValue(); } if (mmss.endsWith("s") || mmss.endsWith("\"")) mmss = mmss.substring(0, mmss.length()-1); if (i != mmss.length()-1) { String ss = mmss.substring(i+1); s = Double.valueOf(ss).doubleValue(); } if (m < 0 || m > 59) throw new NumberFormatException("Minutes must be between 0 and 59"); if (s < 0 || s >= 60) throw new NumberFormatException("Seconds must be between 0 and 59"); } else if (i != 0) m = Double.valueOf(mmss).doubleValue(); if (isDegrees) result = ProjectionMath.dmsToDeg(d, m, s); else result = ProjectionMath.dmsToRad(d, m, s); } else { result = Double.parseDouble(text); if (!isDegrees) result = Math.toRadians(result); } if (parsePosition != null) parsePosition.setIndex(text.length()); if (negate) result = -result; return new Double(result); } }
ndamiens/proj4j-android
src/org/osgeo/proj4j/units/AngleFormat.java
Java
apache-2.0
4,782
# AUTOGENERATED FILE FROM balenalib/up-squared-debian:sid-run ENV GO_VERSION 1.16.3 # gcc for cgo RUN apt-get update && apt-get install -y --no-install-recommends \ g++ \ gcc \ libc6-dev \ make \ pkg-config \ git \ && rm -rf /var/lib/apt/lists/* RUN set -x \ && fetchDeps=' \ curl \ ' \ && apt-get update && apt-get install -y $fetchDeps --no-install-recommends && rm -rf /var/lib/apt/lists/* \ && mkdir -p /usr/local/go \ && curl -SLO "https://storage.googleapis.com/golang/go$GO_VERSION.linux-amd64.tar.gz" \ && echo "951a3c7c6ce4e56ad883f97d9db74d3d6d80d5fec77455c6ada6c1f7ac4776d2 go$GO_VERSION.linux-amd64.tar.gz" | sha256sum -c - \ && tar -xzf "go$GO_VERSION.linux-amd64.tar.gz" -C /usr/local/go --strip-components=1 \ && rm -f go$GO_VERSION.linux-amd64.tar.gz ENV GOROOT /usr/local/go ENV GOPATH /go ENV PATH $GOPATH/bin:/usr/local/go/bin:$PATH RUN mkdir -p "$GOPATH/src" "$GOPATH/bin" && chmod -R 777 "$GOPATH" WORKDIR $GOPATH CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"] RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@golang.sh" \ && echo "Running test-stack@golang" \ && chmod +x test-stack@golang.sh \ && bash test-stack@golang.sh \ && rm -rf test-stack@golang.sh RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: Intel 64-bit (x86-64) \nOS: Debian Sid \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nGo v1.16.3 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && cp /bin/sh /bin/sh.real \ && mv /bin/sh-shim /bin/sh
nghiant2710/base-images
balena-base-images/golang/up-squared/debian/sid/1.16.3/run/Dockerfile
Dockerfile
apache-2.0
2,334
/* * Copyright 2015 Raffael Herzog * * 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 ch.raffael.guards.plugins.idea.model; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import com.intellij.codeInsight.AnnotationUtil; import com.intellij.openapi.module.Module; import com.intellij.psi.JavaPsiFacade; import com.intellij.psi.PsiClass; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.searches.AnnotatedElementsSearch; import com.intellij.util.Processor; import ch.raffael.guards.NoNulls; import ch.raffael.guards.NotNull; import ch.raffael.guards.Nullable; import ch.raffael.guards.analysis.Context; import ch.raffael.guards.analysis.Type; import ch.raffael.guards.definition.Guard; /** * @author <a href="mailto:herzog@raffael.ch">Raffael Herzog</a> */ public class PsiGuardContext extends Context<PsiGuardModel> { @NotNull private final Module module; private final JavaPsiFacade javaPsiFacade; private volatile boolean didFindAll = false; public PsiGuardContext(Module module) { super(); this.module = module; javaPsiFacade = JavaPsiFacade.getInstance(module.getProject()); } @Nullable @Override protected Type findType(@NotNull String name) { // FIXME: Not implemented return null; } @Nullable @Override public PsiGuardModel findGuard(@NotNull String name) { PsiClass psiClass = javaPsiFacade.findClass(name, searchScope()); if ( psiClass == null ) { return null; } if ( !psiClass.isAnnotationType() ) { return null; } if ( psiClass.getModifierList() == null ) { return null; } PsiClass guardAnnotation = guardAnnotation(); if ( guardAnnotation == null ) { return null; } return findGuard(psiClass); } @Nullable protected PsiGuardModel findGuard(@NotNull PsiClass psiClass) { if ( !psiClass.isAnnotationType() ) { return null; } if ( psiClass.getModifierList() == null ) { return null; } PsiClass guardAnnotation = guardAnnotation(); if ( guardAnnotation == null ) { return null; } assert guardAnnotation.getQualifiedName() != null; if ( AnnotationUtil.isAnnotated(psiClass, guardAnnotation.getQualifiedName(), false) ) { return new PsiGuardModel(this, psiClass); } else { return null; } } @NotNull @NoNulls public Collection<PsiGuardModel> findAllGuards() { if ( didFindAll ) { return getKnownGuards(); } else { final PsiClass annotation = guardAnnotation(); if ( annotation == null ) { return Collections.emptyList(); } assert annotation.getQualifiedName() != null; final List<PsiGuardModel> result = new ArrayList<>(); AnnotatedElementsSearch.searchElements(annotation, searchScope(), PsiClass.class).forEach(new Processor<PsiClass>() { @Override public boolean process(PsiClass psiClass) { if ( psiClass.getQualifiedName() == null ) { return true; } if ( !psiClass.isAnnotationType() ) { return true; } if ( AnnotationUtil.isAnnotated(psiClass, annotation.getQualifiedName(), false) ) { result.add(add(new PsiGuardModel(PsiGuardContext.this, psiClass))); } return true; } }); didFindAll = true; return Collections.unmodifiableCollection(result); } } @Nullable private PsiClass guardAnnotation() { return javaPsiFacade.findClass(Guard.class.getName(), searchScope()); } public GlobalSearchScope searchScope() { return module.getModuleWithDependenciesAndLibrariesScope(false); } }
Abnaxos/guards
plugins/idea/src/main/java/ch/raffael/guards/plugins/idea/model/PsiGuardContext.java
Java
apache-2.0
4,696
/*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2016 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ // Provides class sap.ui.model.odata.ODataAnnotations sap.ui.define(['./AnnotationParser', 'jquery.sap.global', 'sap/ui/Device', 'sap/ui/base/EventProvider'], function(AnnotationParser, jQuery, Device, EventProvider) { "use strict"; /*global ActiveXObject */ /** * @param {string|string[]} aAnnotationURI The annotation-URL or an array of URLS that should be parsed and merged * @param {sap.ui.model.odata.ODataMetadata} oMetadata * @param {object} mParams * * @class Implementation to access oData Annotations * * @author SAP SE * @version * 1.38.7 * * @constructor * @public * @alias sap.ui.model.odata.ODataAnnotations * @extends sap.ui.base.EventProvider */ var ODataAnnotations = EventProvider.extend("sap.ui.model.odata.ODataAnnotations", /** @lends sap.ui.model.odata.ODataAnnotations.prototype */ { // constructor : function(aAnnotationURI, oMetadata, mParams) { constructor : function(mOptions) { EventProvider.apply(this, arguments); if (arguments.length !== 1) { // Old constructor argument syntax if (typeof arguments[2] === "object") { mOptions = arguments[2]; } mOptions.urls = arguments[0]; mOptions.metadata = arguments[1]; } this.oMetadata = mOptions.metadata; this.oAnnotations = mOptions.annotationData ? mOptions.annotationData : {}; this.bLoaded = false; this.bAsync = mOptions && mOptions.async; this.xPath = null; this.oError = null; this.bValidXML = true; this.oRequestHandles = []; this.oLoadEvent = null; this.oFailedEvent = null; this.mCustomHeaders = mOptions.headers ? jQuery.extend({}, mOptions.headers) : {}; if (mOptions.urls) { this.addUrl(mOptions.urls); if (!this.bAsync) { // Synchronous loading, we can directly check for errors jQuery.sap.assert( !jQuery.isEmptyObject(this.oMetadata), "Metadata must be available for synchronous annotation loading" ); if (this.oError) { jQuery.sap.log.error( "OData annotations could not be loaded: " + this.oError.message ); } } } }, metadata : { publicMethods : ["parse", "getAnnotationsData", "attachFailed", "detachFailed", "attachLoaded", "detachLoaded"] } }); ///////////////////////////////////////////////// Prototype Members //////////////////////////////////////////////// /** * returns the raw annotation data * * @public * @returns {object} returns annotations data */ ODataAnnotations.prototype.getAnnotationsData = function() { return this.oAnnotations; }; /** * Checks whether annotations from at least one source are available * * @public * @returns {boolean} returns whether annotations is already loaded */ ODataAnnotations.prototype.isLoaded = function() { return this.bLoaded; }; /** * Checks whether annotations loading of at least one of the given URLs has already failed. * Note: For asynchronous annotations {@link #attachFailed} has to be used. * * @public * @returns {boolean} whether annotations request has failed */ ODataAnnotations.prototype.isFailed = function() { return this.oError !== null; }; /** * Fire event loaded to attached listeners. * * @param {map} [mArguments] Map of arguments that will be given as parameters to teh event handler * @return {sap.ui.model.odata.ODataAnnotations} <code>this</code> to allow method chaining * @protected */ ODataAnnotations.prototype.fireLoaded = function(mArguments) { this.fireEvent("loaded", mArguments); return this; }; /** * Attach event-handler <code>fnFunction</code> to the 'loaded' event of this <code>sap.ui.model.odata.ODataAnnotations</code>. * * * @param {object} * [oData] The object, that should be passed along with the event-object when firing the event. * @param {function} * fnFunction The function to call, when the event occurs. This function will be called on the * oListener-instance (if present) or in a 'static way'. * @param {object} * [oListener] Object on which to call the given function. If empty, the global context (window) is used. * * @return {sap.ui.model.odata.ODataAnnotations} <code>this</code> to allow method chaining * @public */ ODataAnnotations.prototype.attachLoaded = function(oData, fnFunction, oListener) { this.attachEvent("loaded", oData, fnFunction, oListener); return this; }; /** * Detach event-handler <code>fnFunction</code> from the 'loaded' event of this <code>sap.ui.model.odata.ODataAnnotations</code>. * * The passed function and listener object must match the ones previously used for event registration. * * @param {function} * fnFunction The function to call, when the event occurs. * @param {object} * oListener Object on which the given function had to be called. * @return {sap.ui.model.odata.ODataAnnotations} <code>this</code> to allow method chaining * @public */ ODataAnnotations.prototype.detachLoaded = function(fnFunction, oListener) { this.detachEvent("loaded", fnFunction, oListener); return this; }; /** * Fire event failed to attached listeners. * * @param {object} [mArguments] the arguments to pass along with the event. * @param {string} [mArguments.message] A text that describes the failure. * @param {string} [mArguments.statusCode] HTTP status code returned by the request (if available) * @param {string} [mArguments.statusText] The status as a text, details not specified, intended only for diagnosis output * @param {string} [mArguments.responseText] Response that has been received for the request ,as a text string * * @return {sap.ui.model.odata.ODataAnnotations} <code>this</code> to allow method chaining * @protected */ ODataAnnotations.prototype.fireFailed = function(mArguments) { this.fireEvent("failed", mArguments); return this; }; /** * Attach event-handler <code>fnFunction</code> to the 'failed' event of this <code>sap.ui.model.odata.ODataAnnotations</code>. * * * @param {object} * [oData] The object, that should be passed along with the event-object when firing the event. * @param {function} * fnFunction The function to call, when the event occurs. This function will be called on the * oListener-instance (if present) or in a 'static way'. * @param {object} * [oListener] Object on which to call the given function. If empty, the global context (window) is used. * * @return {sap.ui.model.odata.ODataAnnotations} <code>this</code> to allow method chaining * @public */ ODataAnnotations.prototype.attachFailed = function(oData, fnFunction, oListener) { this.attachEvent("failed", oData, fnFunction, oListener); return this; }; /** * Detach event-handler <code>fnFunction</code> from the 'failed' event of this <code>sap.ui.model.odata.ODataAnnotations</code>. * * The passed function and listener object must match the ones previously used for event registration. * * @param {function} * fnFunction The function to call, when the event occurs. * @param {object} * oListener Object on which the given function had to be called. * @return {sap.ui.model.odata.ODataAnnotations} <code>this</code> to allow method chaining * @public */ ODataAnnotations.prototype.detachFailed = function(fnFunction, oListener) { this.detachEvent("failed", fnFunction, oListener); return this; }; /** * Set custom headers which are provided in a key/value map. These headers are used for all requests. * The Accept-Language header cannot be modified and is set using the Core's language setting. * * To remove these headers simply set the mHeaders parameter to {}. Please also note that when calling this method * again all previous custom headers are removed unless they are specified again in the mCustomHeaders parameter. * * @param {map} mHeaders the header name/value map. * @public */ ODataAnnotations.prototype.setHeaders = function(mHeaders) { // Copy headers (dont use reference to mHeaders map) this.mCustomHeaders = jQuery.extend({}, mHeaders); }; /** * Creates an XML document that can be used by this parser from the given XML content. * * @param {object|string} vXML Either an XML Document to be used for parsing or a string that should be parsed as an XML document. In case the first parameter is an object, the second parameter must be set to ensure browser compatibility * @param {string} [sXMLContent] Fallback XML content as string in case the first parameter was an object and could not be used * @returns {object} The compatible XML document object * @private */ ODataAnnotations.prototype._createXMLDocument = function(vXML, sXMLContent) { var oXMLDoc = null; if (typeof vXML === "string") { sXMLContent = vXML; vXML = null; } if (sap.ui.Device.browser.internet_explorer) { // IE creates an XML Document, but we cannot use it since it does not support the // evaluate-method. So we have to create a new document from the XML string every time. // This also leads to using a difference XPath implementation @see getXPath oXMLDoc = new ActiveXObject("Microsoft.XMLDOM"); // ??? "Msxml2.DOMDocument.6.0" oXMLDoc.preserveWhiteSpace = true; // The MSXML implementation does not parse documents with the technically correct "xmlns:xml"-attribute // So if a document contains 'xmlns:xml="http://www.w3.org/XML/1998/namespace"', IE will stop working. // This hack removes the XML namespace declaration which is then implicitly set to the default one. if (sXMLContent.indexOf(" xmlns:xml=") > -1) { sXMLContent = sXMLContent .replace(' xmlns:xml="http://www.w3.org/XML/1998/namespace"', "") .replace(" xmlns:xml='http://www.w3.org/XML/1998/namespace'", ""); } oXMLDoc.loadXML(sXMLContent); } else if (vXML) { oXMLDoc = vXML; } else if (window.DOMParser) { oXMLDoc = new DOMParser().parseFromString(sXMLContent, 'application/xml'); } else { jQuery.sap.log.fatal("The browser does not support XML parsing. Annotations are not available."); } return oXMLDoc; }; /** * Checks the given XML document for parse errors * * @param {object} oXMLDoc The XML document object * @return {boolean} true if errors exist false otherwise */ ODataAnnotations.prototype._documentHasErrors = function(oXMLDoc) { return ( // All browsers including IE oXMLDoc.getElementsByTagName("parsererror").length > 0 // IE 11 special case || (oXMLDoc.parseError && oXMLDoc.parseError.errorCode !== 0) ); }; /** * Merges the newly parsed annotation data into the already existing one. * The merge operates on Terms and overwrites existing annotations on that level. * * @param {map} mAnnotations The new annotations that should be merged into the ones in this instance * @param {boolean} [bSuppressEvents] if set to true, the "loaded"-event is not fired * @returns {void} */ ODataAnnotations.prototype._mergeAnnotationData = function(mAnnotations, bSuppressEvents) { if (!this.oAnnotations) { this.oAnnotations = {}; } // Merge must be done on Term level, this is why the original line does not suffice any more: // jQuery.extend(true, this.oAnnotations, mAnnotations); // Terms are defined on different levels, the main one is below the target level, which is directly // added as property to the annotations object and then in the same way inside two special properties // named "propertyAnnotations" and "EntityContainer" function mergeAnnotation(sName, mSource, mTarget) { // Everythin in here must be on Term level, so we overwrite the target with the data from the source if (Array.isArray(mSource[sName])) { // This is a collection - make sure it stays one mTarget[sName] = mSource[sName].slice(0); } else { // Make sure the map exists in the target mTarget[sName] = mTarget[sName] || {}; for (var sKey in mSource[sName]) { mTarget[sName][sKey] = mSource[sName][sKey]; } } } var sTarget, sTerm; var aSpecialCases = ["propertyAnnotations", "EntityContainer", "annotationReferences"]; // First merge standard annotations for (sTarget in mAnnotations) { if (aSpecialCases.indexOf(sTarget) !== -1) { // Skip these as they are special properties that contain Target level definitions continue; } // ...all others contain Term level definitions mergeAnnotation(sTarget, mAnnotations, this.oAnnotations); } // Now merge special cases for (var i = 0; i < aSpecialCases.length; ++i) { var sSpecialCase = aSpecialCases[i]; this.oAnnotations[sSpecialCase] = this.oAnnotations[sSpecialCase] || {}; // Make sure the the target namespace exists for (sTarget in mAnnotations[sSpecialCase]) { for (sTerm in mAnnotations[sSpecialCase][sTarget]) { // Now merge every term this.oAnnotations[sSpecialCase][sTarget] = this.oAnnotations[sSpecialCase][sTarget] || {}; mergeAnnotation(sTerm, mAnnotations[sSpecialCase][sTarget], this.oAnnotations[sSpecialCase][sTarget]); } } } this.bLoaded = true; if (!bSuppressEvents) { this.fireLoaded({ annotations: mAnnotations }); } }; /** * Sets an XML document * * @param {object} oXMLDocument The XML document to parse for annotations * @param {string} sXMLContent The XML content as string to parse for annotations * @param {map} [mOptions] Additional options * @param {fuction} [mOptions.success] Success callback gets an objec as argument with the * properties "annotations" containing the parsed annotations and "xmlDoc" * containing the XML-Document that was returned by the request. * @param {fuction} [mOptions.error] Error callback gets an objec as argument with the * property "xmlDoc" containing the XML-Document that was returned by the * request and could not be correctly parsed. * @param {boolean} [mOptions.fireEvents] If this option is set to true, events are fired as if the annotations * were loaded from a URL * @return {boolean} Whether or not parsing was successful * @public */ ODataAnnotations.prototype.setXML = function(oXMLDocument, sXMLContent, mOptions) { // Make sure there are always callable handlers var mDefaultOptions = { success: function() {}, error: function() {}, fireEvents: false }; mOptions = jQuery.extend({}, mDefaultOptions, mOptions); var oXMLDoc = this._createXMLDocument(oXMLDocument, sXMLContent); var fnParseDocument = function(oXMLDoc) { var mResult = { xmlDoc : oXMLDoc }; var oAnnotations = AnnotationParser.parse(this.oMetadata, oXMLDoc); if (oAnnotations) { mResult.annotations = oAnnotations; mOptions.success(mResult); this._mergeAnnotationData(oAnnotations, !mOptions.fireEvents); } else { mOptions.error(mResult); if (mOptions.fireEvents) { this.fireFailed(mResult); } } }.bind(this, oXMLDoc); if (this._documentHasErrors(oXMLDoc)) { // Malformed XML, notify application of the problem // This seems to be needed since with some jQuery versions the XML document // is partly parsed and with some it is not parsed at all. We now choose the // "safe" approach and only accept completely valid documents. mOptions.error({ xmlDoc : oXMLDoc }); return false; } else { // Check if Metadata is loaded on the model. We need the Metadata to parse the annotations var oMetadata = this.oMetadata.getServiceMetadata(); if (!oMetadata || jQuery.isEmptyObject(oMetadata)) { // Metadata is not loaded, wait for it before trying to parse this.oMetadata.attachLoaded(fnParseDocument); } else { fnParseDocument(); } return true; } }; /** * Adds either one URL or an array of URLs to be loaded and parsed. The result will be merged into the annotations * data which can be retrieved using the getAnnotations-method. * * @param {string|sting[]} vUrl Either one URL as string or an array of URL strings * @return {Promise} The Promise to load the given URL(s), resolved if all URLs have been loaded, rejected if at * least one failed to load. The argument is an object containing the annotations object, success (an array * of sucessfully loaded URLs), fail (an array ob of failed URLs). * @public */ ODataAnnotations.prototype.addUrl = function(vUrl) { var that = this; var aUris = vUrl; if (Array.isArray(vUrl) && vUrl.length == 0) { return Promise.resolve({annotations: this.oAnnotations}); } if (!Array.isArray(vUrl)) { aUris = [ vUrl ]; } return new Promise(function(fnResolve, fnReject) { var iLoadCount = 0; var mResults = { annotations: null, success: [], fail: [] }; var fnRequestCompleted = function(mResult) { iLoadCount++; if (mResult.type === "success") { mResults.success.push(mResult); } else { mResults.fail.push(mResult); } if (iLoadCount === aUris.length) { // Finished loading all URIs mResults.annotations = that.oAnnotations; if (mResults.success.length > 0) { // For compatibility reasons, we fire the loaded event if at least one has been loaded... var mSuccess = { annotations: that.oAnnotations, results: mResults }; that.fireLoaded(mSuccess); } if (mResults.success.length < aUris.length) { // firefailed is called for every failed URL in _loadFromUrl var oError = new Error("At least one annotation failed to load/parse/merge"); oError.annotations = mResults.annotations; oError.success = mResults.success; oError.fail = mResults.fail; fnReject(oError); } else { // All URLs could be loaded and parsed fnResolve(mResults); } } }; var i = 0; if (that.bAsync) { var promiseChain = Promise.resolve(); for (i = 0; i < aUris.length; ++i) { var fnLoadNext = that._loadFromUrl.bind(that, aUris[i]); promiseChain = promiseChain .then(fnLoadNext, fnLoadNext) .then(fnRequestCompleted, fnRequestCompleted); } } else { for (i = 0; i < aUris.length; ++i) { that._loadFromUrl(aUris[i]).then(fnRequestCompleted, fnRequestCompleted); } } }); }; /** * Returns a promise to load and parse annotations from a single URL, resolves if the URL could be loaded and parsed, rejects * otherwise * * @param {string} sUrl The URL to load * @return {Promise} The promise to load the URL. Argument contains information about the failed or succeeded request */ ODataAnnotations.prototype._loadFromUrl = function(sUrl) { var that = this; return new Promise(function(fnResolve, fnReject) { var mAjaxOptions = { url: sUrl, async: that.bAsync, headers: jQuery.extend({}, that.mCustomHeaders, { "Accept-Language": sap.ui.getCore().getConfiguration().getLanguageTag() // Always overwrite }) }; var oRequestHandle; var fnFail = function(oJQXHR, sStatusText) { if (oRequestHandle && oRequestHandle.bSuppressErrorHandlerCall) { return; } that.oError = { type: "fail", url: sUrl, message: sStatusText, statusCode: oJQXHR.statusCode, statusText: oJQXHR.statusText, responseText: oJQXHR.responseText }; if (that.bAsync) { that.oFailedEvent = jQuery.sap.delayedCall(0, that, that.fireFailed, [ that.oError ]); } else { that.fireFailed(that.oError); } fnReject(that.oError); }; var fnSuccess = function(sData, sStatusText, oJQXHR) { that.setXML(oJQXHR.responseXML, oJQXHR.responseText, { success: function(mData) { fnResolve({ type: "success", url: sUrl, message: sStatusText, statusCode: oJQXHR.statusCode, statusText: oJQXHR.statusText, responseText: oJQXHR.responseText }); }, error : function(mData) { fnFail(oJQXHR, "Malformed XML document"); }, url: sUrl }); }; jQuery.ajax(mAjaxOptions).done(fnSuccess).fail(fnFail); }); }; ODataAnnotations.prototype.destroy = function() { // Abort pending xml request for (var i = 0; i < this.oRequestHandles.length; ++i) { if (this.oRequestHandles[i]) { this.oRequestHandles[i].bSuppressErrorHandlerCall = true; this.oRequestHandles[i].abort(); this.oRequestHandles[i] = null; } } EventProvider.prototype.destroy.apply(this, arguments); if (this.oLoadEvent) { jQuery.sap.clearDelayedCall(this.oLoadEvent); } if (this.oFailedEvent) { jQuery.sap.clearDelayedCall(this.oFailedEvent); } }; return ODataAnnotations; });
SuicidePreventionSquad/SeniorProject
resources/sap/ui/model/odata/ODataAnnotations-dbg.js
JavaScript
apache-2.0
21,015
/** 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 com.heliosapm.streams.collector.groovy; import java.util.Collections; import java.util.EnumMap; import java.util.EnumSet; import java.util.Map; import java.util.Set; import javax.management.AttributeChangeNotification; import javax.management.MBeanNotificationInfo; /** * <p>Title: ScriptState</p> * <p>Description: Enumerates the possible states of a {@link ManagedScript}</p> * @author Whitehead (nwhitehead AT heliosdev DOT org) * <p><code>com.heliosapm.streams.collector.groovy.ScriptState</code></p> */ public enum ScriptState { /** The initial state of a newly created script */ INIT("The script was just initialized"), /** Script execution is paused */ PAUSED("The script is scheduled but paused"), /** Script is in a scheduled steady state */ SCHEDULED("The script is in scheduled steady state"), /** Script is in collecting */ EXECUTING("The script is executing"), /** Script is compiled but has no schedule */ PASSIVE("The script is compiled but has no schedule"), /** Script is compiled but has not confirmed init-check */ NOINIT("The script is compiled but has not confirmed init-check"), /** Script is waiting for dependency injection */ WAITING("The script is waiting on dependencies"), /** Script is steady state but throwing some errors */ ERRORS("The script is steady state but throwing errors"), /** Script is steady state but cannot connect to a resource */ DISCONNECT("The script is steady state but cannot connect to a resource"), /** Script is being destroyed */ DESTROY("The script is being destroyed"); private ScriptState(final String description) { this.description = description; this.notifType = "collector.script.state." + name().toLowerCase(); } /** A map of script state jmx notification infos keyed by the associated script state */ public static final Map<ScriptState, MBeanNotificationInfo> NOTIF_INFOS; private static final ScriptState[] values = values(); /** The script state description */ public final String description; /** The jmx notification type */ public final String notifType; /** States that this state can transition to */ private static final Map<ScriptState, Set<ScriptState>> transitionTo; static { Map<ScriptState, MBeanNotificationInfo> tmpNotifs = new EnumMap<ScriptState, MBeanNotificationInfo>(ScriptState.class); final EnumMap<ScriptState, Set<ScriptState>> tmpMap = new EnumMap<ScriptState, Set<ScriptState>>(ScriptState.class); for(ScriptState st: values) { st.transitionTo(tmpMap, values); tmpNotifs.put(st, new MBeanNotificationInfo(new String[]{st.notifType}, AttributeChangeNotification.class.getName(), st.description)); } tmpMap.get(DESTROY).clear(); for(ScriptState st: values) { Set<ScriptState> set = tmpMap.remove(st); tmpMap.put(st, Collections.unmodifiableSet(set)); } transitionTo = Collections.unmodifiableMap(tmpMap); NOTIF_INFOS = Collections.unmodifiableMap(tmpNotifs); } private ScriptState transitionTo(final EnumMap<ScriptState, Set<ScriptState>> map, final ScriptState...states) { final EnumSet<ScriptState> set = EnumSet.noneOf(ScriptState.class); Collections.addAll(set, states); set.remove(this); set.remove(INIT); map.put(this, set); return this; } /** * Indicates if a script state transition should issue a notification event. * This is mostly to supress notifications for transitions between {@link #SCHEDULED} and {@link #EXECUTING} states. * @param from The from script state * @param to The to script state * @return true if a script state transition should issue a notification event, false otherwise. */ public static boolean shouldNotify(final ScriptState from, final ScriptState to) { if(from==null) throw new IllegalArgumentException("The passed from ScriptState was null"); if(to==null) throw new IllegalArgumentException("The passed to ScriptState was null"); if(from==SCHEDULED) { if(to==EXECUTING) return false; } else if(from==EXECUTING) { if(to==SCHEDULED) return false; } return true; } public boolean canTransitionTo(final ScriptState state) { return transitionTo.get(this).contains(state); } public static void main(String[] args) { for(ScriptState s: ScriptState.values()) { System.out.println(s.name() + ": " + transitionTo.get(s)); } } }
nickman/HeliosStreams
collector-server/src/main/java/com/heliosapm/streams/collector/groovy/ScriptState.java
Java
apache-2.0
5,216
/** * TargetOutrankShareBiddingScheme.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter. */ package com.google.api.ads.adwords.axis.v201601.cm; /** * Target Outrank Share bidding strategy is an automated bidding strategy * which automatically sets * bids so that the customer's ads appear above a specified * competitors' ads for a specified target * fraction of the advertiser's eligible impressions on Google.com. * <span class="constraint AdxEnabled">This is disabled for AdX.</span> */ public class TargetOutrankShareBiddingScheme extends com.google.api.ads.adwords.axis.v201601.cm.BiddingScheme implements java.io.Serializable { /* Specifies the target fraction (in micros) of auctions where * the advertiser should outrank the * competitor. The advertiser outranks the competitor * in an auction if either the advertiser * appears above the competitor in the search results, * or appears in the search results when the * competitor does not. * <span class="constraint Selectable">This field * can be selected using the value "TargetOutrankShare".</span><span * class="constraint Filterable">This field can be filtered on.</span> * <span class="constraint InRange">This field must be between 1 and * 1000000, inclusive.</span> * <span class="constraint Required">This field is * required and should not be {@code null}.</span> */ private java.lang.Integer targetOutrankShare; /* Competitor's visible domain URL. * <span class="constraint Selectable">This field * can be selected using the value "TargetOutrankShareCompetitorDomain".</span><span * class="constraint Filterable">This field can be filtered on.</span> * <span class="constraint Required">This field is required and should * not be {@code null}.</span> */ private java.lang.String competitorDomain; /* Ceiling on max CPC bids. * <span class="constraint Selectable">This field * can be selected using the value "TargetOutrankShareMaxCpcBidCeiling".</span><span * class="constraint Filterable">This field can be filtered on.</span> * <span class="constraint Required">This field is required and should * not be {@code null}.</span> */ private com.google.api.ads.adwords.axis.v201601.cm.Money maxCpcBidCeiling; /* Controls whether the strategy always follows bid estimate changes, * or only increases. If false, * always sets a keyword's new bid to the estimate * that will meet the target. If true, only * updates a keyword's bid if the current bid estimate * is greater than the current bid. * <span class="constraint Selectable">This field * can be selected using the value "TargetOutrankShareBidChangesForRaisesOnly".</span><span * class="constraint Filterable">This field can be filtered on.</span> * <span class="constraint Required">This field is required and should * not be {@code null}.</span> */ private java.lang.Boolean bidChangesForRaisesOnly; /* Controls whether the strategy is allowed to raise bids on keywords * with lower-range quality * scores. * <span class="constraint Selectable">This field * can be selected using the value "TargetOutrankShareRaiseBidWhenLowQualityScore".</span><span * class="constraint Filterable">This field can be filtered on.</span> * <span class="constraint Required">This field is required and should * not be {@code null}.</span> */ private java.lang.Boolean raiseBidWhenLowQualityScore; public TargetOutrankShareBiddingScheme() { } public TargetOutrankShareBiddingScheme( java.lang.String biddingSchemeType, java.lang.Integer targetOutrankShare, java.lang.String competitorDomain, com.google.api.ads.adwords.axis.v201601.cm.Money maxCpcBidCeiling, java.lang.Boolean bidChangesForRaisesOnly, java.lang.Boolean raiseBidWhenLowQualityScore) { super( biddingSchemeType); this.targetOutrankShare = targetOutrankShare; this.competitorDomain = competitorDomain; this.maxCpcBidCeiling = maxCpcBidCeiling; this.bidChangesForRaisesOnly = bidChangesForRaisesOnly; this.raiseBidWhenLowQualityScore = raiseBidWhenLowQualityScore; } /** * Gets the targetOutrankShare value for this TargetOutrankShareBiddingScheme. * * @return targetOutrankShare * Specifies the target fraction (in micros) of auctions where * the advertiser should outrank the * competitor. The advertiser outranks the competitor * in an auction if either the advertiser * appears above the competitor in the search results, * or appears in the search results when the * competitor does not. * <span class="constraint Selectable">This field * can be selected using the value "TargetOutrankShare".</span><span * class="constraint Filterable">This field can be filtered on.</span> * <span class="constraint InRange">This field must be between 1 and * 1000000, inclusive.</span> * <span class="constraint Required">This field is * required and should not be {@code null}.</span> */ public java.lang.Integer getTargetOutrankShare() { return targetOutrankShare; } /** * Sets the targetOutrankShare value for this TargetOutrankShareBiddingScheme. * * @param targetOutrankShare * Specifies the target fraction (in micros) of auctions where * the advertiser should outrank the * competitor. The advertiser outranks the competitor * in an auction if either the advertiser * appears above the competitor in the search results, * or appears in the search results when the * competitor does not. * <span class="constraint Selectable">This field * can be selected using the value "TargetOutrankShare".</span><span * class="constraint Filterable">This field can be filtered on.</span> * <span class="constraint InRange">This field must be between 1 and * 1000000, inclusive.</span> * <span class="constraint Required">This field is * required and should not be {@code null}.</span> */ public void setTargetOutrankShare(java.lang.Integer targetOutrankShare) { this.targetOutrankShare = targetOutrankShare; } /** * Gets the competitorDomain value for this TargetOutrankShareBiddingScheme. * * @return competitorDomain * Competitor's visible domain URL. * <span class="constraint Selectable">This field * can be selected using the value "TargetOutrankShareCompetitorDomain".</span><span * class="constraint Filterable">This field can be filtered on.</span> * <span class="constraint Required">This field is required and should * not be {@code null}.</span> */ public java.lang.String getCompetitorDomain() { return competitorDomain; } /** * Sets the competitorDomain value for this TargetOutrankShareBiddingScheme. * * @param competitorDomain * Competitor's visible domain URL. * <span class="constraint Selectable">This field * can be selected using the value "TargetOutrankShareCompetitorDomain".</span><span * class="constraint Filterable">This field can be filtered on.</span> * <span class="constraint Required">This field is required and should * not be {@code null}.</span> */ public void setCompetitorDomain(java.lang.String competitorDomain) { this.competitorDomain = competitorDomain; } /** * Gets the maxCpcBidCeiling value for this TargetOutrankShareBiddingScheme. * * @return maxCpcBidCeiling * Ceiling on max CPC bids. * <span class="constraint Selectable">This field * can be selected using the value "TargetOutrankShareMaxCpcBidCeiling".</span><span * class="constraint Filterable">This field can be filtered on.</span> * <span class="constraint Required">This field is required and should * not be {@code null}.</span> */ public com.google.api.ads.adwords.axis.v201601.cm.Money getMaxCpcBidCeiling() { return maxCpcBidCeiling; } /** * Sets the maxCpcBidCeiling value for this TargetOutrankShareBiddingScheme. * * @param maxCpcBidCeiling * Ceiling on max CPC bids. * <span class="constraint Selectable">This field * can be selected using the value "TargetOutrankShareMaxCpcBidCeiling".</span><span * class="constraint Filterable">This field can be filtered on.</span> * <span class="constraint Required">This field is required and should * not be {@code null}.</span> */ public void setMaxCpcBidCeiling(com.google.api.ads.adwords.axis.v201601.cm.Money maxCpcBidCeiling) { this.maxCpcBidCeiling = maxCpcBidCeiling; } /** * Gets the bidChangesForRaisesOnly value for this TargetOutrankShareBiddingScheme. * * @return bidChangesForRaisesOnly * Controls whether the strategy always follows bid estimate changes, * or only increases. If false, * always sets a keyword's new bid to the estimate * that will meet the target. If true, only * updates a keyword's bid if the current bid estimate * is greater than the current bid. * <span class="constraint Selectable">This field * can be selected using the value "TargetOutrankShareBidChangesForRaisesOnly".</span><span * class="constraint Filterable">This field can be filtered on.</span> * <span class="constraint Required">This field is required and should * not be {@code null}.</span> */ public java.lang.Boolean getBidChangesForRaisesOnly() { return bidChangesForRaisesOnly; } /** * Sets the bidChangesForRaisesOnly value for this TargetOutrankShareBiddingScheme. * * @param bidChangesForRaisesOnly * Controls whether the strategy always follows bid estimate changes, * or only increases. If false, * always sets a keyword's new bid to the estimate * that will meet the target. If true, only * updates a keyword's bid if the current bid estimate * is greater than the current bid. * <span class="constraint Selectable">This field * can be selected using the value "TargetOutrankShareBidChangesForRaisesOnly".</span><span * class="constraint Filterable">This field can be filtered on.</span> * <span class="constraint Required">This field is required and should * not be {@code null}.</span> */ public void setBidChangesForRaisesOnly(java.lang.Boolean bidChangesForRaisesOnly) { this.bidChangesForRaisesOnly = bidChangesForRaisesOnly; } /** * Gets the raiseBidWhenLowQualityScore value for this TargetOutrankShareBiddingScheme. * * @return raiseBidWhenLowQualityScore * Controls whether the strategy is allowed to raise bids on keywords * with lower-range quality * scores. * <span class="constraint Selectable">This field * can be selected using the value "TargetOutrankShareRaiseBidWhenLowQualityScore".</span><span * class="constraint Filterable">This field can be filtered on.</span> * <span class="constraint Required">This field is required and should * not be {@code null}.</span> */ public java.lang.Boolean getRaiseBidWhenLowQualityScore() { return raiseBidWhenLowQualityScore; } /** * Sets the raiseBidWhenLowQualityScore value for this TargetOutrankShareBiddingScheme. * * @param raiseBidWhenLowQualityScore * Controls whether the strategy is allowed to raise bids on keywords * with lower-range quality * scores. * <span class="constraint Selectable">This field * can be selected using the value "TargetOutrankShareRaiseBidWhenLowQualityScore".</span><span * class="constraint Filterable">This field can be filtered on.</span> * <span class="constraint Required">This field is required and should * not be {@code null}.</span> */ public void setRaiseBidWhenLowQualityScore(java.lang.Boolean raiseBidWhenLowQualityScore) { this.raiseBidWhenLowQualityScore = raiseBidWhenLowQualityScore; } private java.lang.Object __equalsCalc = null; public synchronized boolean equals(java.lang.Object obj) { if (!(obj instanceof TargetOutrankShareBiddingScheme)) return false; TargetOutrankShareBiddingScheme other = (TargetOutrankShareBiddingScheme) obj; if (obj == null) return false; if (this == obj) return true; if (__equalsCalc != null) { return (__equalsCalc == obj); } __equalsCalc = obj; boolean _equals; _equals = super.equals(obj) && ((this.targetOutrankShare==null && other.getTargetOutrankShare()==null) || (this.targetOutrankShare!=null && this.targetOutrankShare.equals(other.getTargetOutrankShare()))) && ((this.competitorDomain==null && other.getCompetitorDomain()==null) || (this.competitorDomain!=null && this.competitorDomain.equals(other.getCompetitorDomain()))) && ((this.maxCpcBidCeiling==null && other.getMaxCpcBidCeiling()==null) || (this.maxCpcBidCeiling!=null && this.maxCpcBidCeiling.equals(other.getMaxCpcBidCeiling()))) && ((this.bidChangesForRaisesOnly==null && other.getBidChangesForRaisesOnly()==null) || (this.bidChangesForRaisesOnly!=null && this.bidChangesForRaisesOnly.equals(other.getBidChangesForRaisesOnly()))) && ((this.raiseBidWhenLowQualityScore==null && other.getRaiseBidWhenLowQualityScore()==null) || (this.raiseBidWhenLowQualityScore!=null && this.raiseBidWhenLowQualityScore.equals(other.getRaiseBidWhenLowQualityScore()))); __equalsCalc = null; return _equals; } private boolean __hashCodeCalc = false; public synchronized int hashCode() { if (__hashCodeCalc) { return 0; } __hashCodeCalc = true; int _hashCode = super.hashCode(); if (getTargetOutrankShare() != null) { _hashCode += getTargetOutrankShare().hashCode(); } if (getCompetitorDomain() != null) { _hashCode += getCompetitorDomain().hashCode(); } if (getMaxCpcBidCeiling() != null) { _hashCode += getMaxCpcBidCeiling().hashCode(); } if (getBidChangesForRaisesOnly() != null) { _hashCode += getBidChangesForRaisesOnly().hashCode(); } if (getRaiseBidWhenLowQualityScore() != null) { _hashCode += getRaiseBidWhenLowQualityScore().hashCode(); } __hashCodeCalc = false; return _hashCode; } // Type metadata private static org.apache.axis.description.TypeDesc typeDesc = new org.apache.axis.description.TypeDesc(TargetOutrankShareBiddingScheme.class, true); static { typeDesc.setXmlType(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201601", "TargetOutrankShareBiddingScheme")); org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("targetOutrankShare"); elemField.setXmlName(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201601", "targetOutrankShare")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "int")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("competitorDomain"); elemField.setXmlName(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201601", "competitorDomain")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("maxCpcBidCeiling"); elemField.setXmlName(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201601", "maxCpcBidCeiling")); elemField.setXmlType(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201601", "Money")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("bidChangesForRaisesOnly"); elemField.setXmlName(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201601", "bidChangesForRaisesOnly")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "boolean")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("raiseBidWhenLowQualityScore"); elemField.setXmlName(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201601", "raiseBidWhenLowQualityScore")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "boolean")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); } /** * Return type metadata object */ public static org.apache.axis.description.TypeDesc getTypeDesc() { return typeDesc; } /** * Get Custom Serializer */ public static org.apache.axis.encoding.Serializer getSerializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanSerializer( _javaType, _xmlType, typeDesc); } /** * Get Custom Deserializer */ public static org.apache.axis.encoding.Deserializer getDeserializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanDeserializer( _javaType, _xmlType, typeDesc); } }
gawkermedia/googleads-java-lib
modules/adwords_axis/src/main/java/com/google/api/ads/adwords/axis/v201601/cm/TargetOutrankShareBiddingScheme.java
Java
apache-2.0
19,423
/* * Copyright 2010-2016 Steve Chaloner * * 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 be.objectify.deadbolt.java.views.rbpTest; import be.objectify.deadbolt.java.AbstractFakeApplicationTest; import be.objectify.deadbolt.java.DeadboltHandler; import be.objectify.deadbolt.java.NoPreAuthDeadboltHandler; import be.objectify.deadbolt.java.cache.HandlerCache; import be.objectify.deadbolt.java.models.Permission; import be.objectify.deadbolt.java.models.Subject; import be.objectify.deadbolt.java.testsupport.TestHandlerCache; import be.objectify.deadbolt.java.testsupport.TestPermission; import be.objectify.deadbolt.java.testsupport.TestSubject; import org.junit.Assert; import org.junit.Test; import play.mvc.Http; import play.test.Helpers; import play.twirl.api.Content; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; /** * @author Steve Chaloner (steve@objectify.be) */ public class RoleBasedPermissionsOrTest extends AbstractFakeApplicationTest { @Test public void testNoPermissionsForRole() { final DeadboltHandler deadboltHandler = new NoPreAuthDeadboltHandler(ecProvider()) { @Override public CompletionStage<Optional<? extends Subject>> getSubject(final Http.Context context) { return CompletableFuture.supplyAsync(() -> Optional.of(new TestSubject.Builder().permission(new TestPermission("bar")) .build())); } @Override public CompletionStage<List<? extends Permission>> getPermissionsForRole(final String roleName) { return CompletableFuture.completedFuture(Collections.emptyList()); } }; final Content html = be.objectify.deadbolt.java.views.html.rbpTest.roleBasedPermissionsOrContent.render("foo", deadboltHandler); final String content = Helpers.contentAsString(html); Assert.assertTrue(content.contains("This is before the constraint.")); Assert.assertFalse(content.contains("This is protected by the constraint.")); Assert.assertTrue(content.contains("This is default content in case the constraint denies access to the protected content.")); Assert.assertTrue(content.contains("This is after the constraint.")); } @Test public void testMatchingPermissionsForRole() { final DeadboltHandler deadboltHandler = new NoPreAuthDeadboltHandler(ecProvider()) { @Override public CompletionStage<Optional<? extends Subject>> getSubject(final Http.Context context) { return CompletableFuture.supplyAsync(() -> Optional.of(new TestSubject.Builder().permission(new TestPermission("bar")) .build())); } @Override public CompletionStage<List<? extends Permission>> getPermissionsForRole(final String roleName) { return CompletableFuture.completedFuture(Collections.singletonList(new TestPermission("bar"))); } }; final Content html = be.objectify.deadbolt.java.views.html.rbpTest.roleBasedPermissionsOrContent.render("foo", deadboltHandler); final String content = Helpers.contentAsString(html); Assert.assertTrue(content.contains("This is before the constraint.")); Assert.assertTrue(content.contains("This is protected by the constraint.")); Assert.assertFalse(content.contains("This is default content in case the constraint denies access to the protected content.")); Assert.assertTrue(content.contains("This is after the constraint.")); } @Test public void testNoMatchingPermissionsForRole() { final DeadboltHandler deadboltHandler = new NoPreAuthDeadboltHandler(ecProvider()) { @Override public CompletionStage<Optional<? extends Subject>> getSubject(final Http.Context context) { return CompletableFuture.supplyAsync(() -> Optional.of(new TestSubject.Builder().permission(new TestPermission("bar")) .build())); } @Override public CompletionStage<List<? extends Permission>> getPermissionsForRole(final String roleName) { return CompletableFuture.completedFuture(Collections.singletonList(new TestPermission("hurdy"))); } }; final Content html = be.objectify.deadbolt.java.views.html.rbpTest.roleBasedPermissionsOrContent.render("foo", deadboltHandler); final String content = Helpers.contentAsString(html); Assert.assertTrue(content.contains("This is before the constraint.")); Assert.assertFalse(content.contains("This is protected by the constraint.")); Assert.assertTrue(content.contains("This is default content in case the constraint denies access to the protected content.")); Assert.assertTrue(content.contains("This is after the constraint.")); } @Test public void testNoSubject() { final DeadboltHandler deadboltHandler = new NoPreAuthDeadboltHandler(ecProvider()) { @Override public CompletionStage<Optional<? extends Subject>> getSubject(final Http.Context context) { return CompletableFuture.completedFuture(Optional.empty()); } @Override public CompletionStage<List<? extends Permission>> getPermissionsForRole(final String roleName) { return CompletableFuture.completedFuture(Collections.singletonList(new TestPermission("hurdy"))); } }; final Content html = be.objectify.deadbolt.java.views.html.rbpTest.roleBasedPermissionsOrContent.render("foo", deadboltHandler); final String content = Helpers.contentAsString(html); Assert.assertTrue(content.contains("This is before the constraint.")); Assert.assertFalse(content.contains("This is protected by the constraint.")); Assert.assertTrue(content.contains("This is default content in case the constraint denies access to the protected content.")); Assert.assertTrue(content.contains("This is after the constraint.")); } public HandlerCache handlers() { return new TestHandlerCache(null, new HashMap<>()); } }
schaloner/deadbolt-2-java-global-state
test/be/objectify/deadbolt/java/views/rbpTest/RoleBasedPermissionsOrTest.java
Java
apache-2.0
7,722
#region copyright // Copyright 2015 Habart Thierry // // 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 SimpleIdentityServer.Store; using System; using System.Threading.Tasks; namespace SimpleIdentityServer.Core.WebSite.Authenticate.Actions { public interface IValidateConfirmationCodeAction { Task<bool> Execute(string code); } internal class ValidateConfirmationCodeAction : IValidateConfirmationCodeAction { private readonly IConfirmationCodeStore _confirmationCodeStore; public ValidateConfirmationCodeAction(IConfirmationCodeStore confirmationCodeStore) { _confirmationCodeStore = confirmationCodeStore; } public async Task<bool> Execute(string code) { if (string.IsNullOrWhiteSpace(code)) { throw new ArgumentNullException(nameof(code)); } var confirmationCode = await _confirmationCodeStore.Get(code); if (confirmationCode == null) { return false; } var expirationDateTime = confirmationCode.IssueAt.AddSeconds(confirmationCode.ExpiresIn); return DateTime.UtcNow < expirationDateTime; } } }
thabart/SimpleIdentityServer
SimpleIdentityServer/src/Apis/SimpleIdServer/SimpleIdentityServer.Core/WebSite/Authenticate/Actions/ValidateConfirmationCodeAction.cs
C#
apache-2.0
1,774
# Pomatocalpa bhutanicum N.P.Balakr. SPECIES #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Pomatocalpa/Pomatocalpa bhutanicum/README.md
Markdown
apache-2.0
192
# Clinogyne comorensis (Brongn. ex Gris) H.Perrier SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Liliopsida/Zingiberales/Marantaceae/Marantochloa/Marantochloa comorensis/ Syn. Clinogyne comorensis/README.md
Markdown
apache-2.0
205
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.secretsmanager.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.secretsmanager.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * ReplicaRegionTypeMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class ReplicaRegionTypeMarshaller { private static final MarshallingInfo<String> REGION_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("Region").build(); private static final MarshallingInfo<String> KMSKEYID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("KmsKeyId").build(); private static final ReplicaRegionTypeMarshaller instance = new ReplicaRegionTypeMarshaller(); public static ReplicaRegionTypeMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(ReplicaRegionType replicaRegionType, ProtocolMarshaller protocolMarshaller) { if (replicaRegionType == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(replicaRegionType.getRegion(), REGION_BINDING); protocolMarshaller.marshall(replicaRegionType.getKmsKeyId(), KMSKEYID_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
aws/aws-sdk-java
aws-java-sdk-secretsmanager/src/main/java/com/amazonaws/services/secretsmanager/model/transform/ReplicaRegionTypeMarshaller.java
Java
apache-2.0
2,282
_base_ = './cascade_mask_rcnn_r50_fpn_mstrain_3x_coco.py' model = dict( backbone=dict( type='ResNeXt', depth=101, groups=32, base_width=8, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=False), style='pytorch', init_cfg=dict( type='Pretrained', checkpoint='open-mmlab://detectron2/resnext101_32x8d'))) # ResNeXt-101-32x8d model trained with Caffe2 at FB, # so the mean and std need to be changed. img_norm_cfg = dict( mean=[103.530, 116.280, 123.675], std=[57.375, 57.120, 58.395], to_rgb=False) # In mstrain 3x config, img_scale=[(1333, 640), (1333, 800)], # multiscale_mode='range' train_pipeline = [ dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', with_bbox=True, with_mask=True), dict( type='Resize', img_scale=[(1333, 640), (1333, 800)], multiscale_mode='range', keep_ratio=True), dict(type='RandomFlip', flip_ratio=0.5), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels', 'gt_masks']), ] test_pipeline = [ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(1333, 800), flip=False, transforms=[ dict(type='Resize', keep_ratio=True), dict(type='RandomFlip'), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']), ]) ] data = dict( train=dict(dataset=dict(pipeline=train_pipeline)), val=dict(pipeline=test_pipeline), test=dict(pipeline=test_pipeline))
open-mmlab/mmdetection
configs/cascade_rcnn/cascade_mask_rcnn_x101_32x8d_fpn_mstrain_3x_coco.py
Python
apache-2.0
1,878
/* * Copyright (C) FuseSource, Inc. * http://fusesource.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 io.fabric8.internal; import java.io.PrintStream; import io.fabric8.api.CreationStateListener; public class PrintStreamCreationStateListener implements CreationStateListener { PrintStream printStream; public PrintStreamCreationStateListener(PrintStream printStream) { this.printStream = printStream; } /** * Called when the state is changed. * * @param message The message describing the current state of the creation process. */ @Override public void onStateChange(String message) { printStream.println(message); } }
alexeev/jboss-fuse-mirror
fabric/fabric-core/src/main/java/io/fabric8/internal/PrintStreamCreationStateListener.java
Java
apache-2.0
1,238
var app = { initialize: function() { this.bind(); this.run(); }, bind: function() { var self = this; document.getElementById("page-request-form").addEventListener('submit', function(e) { var address = document.getElementById("page-request-address"); self.loadPageRequest(address.value); return false; }); }, run: function() { this.showLoading(true); this.load(); this.showLoading(false); }, load: function() { if (this.hasWarnings()) { this.loadWarnings(); } else if (this.hasApiRequest()) { this.loadApiRequest(); } else { this.loadPageRequest(); } }, hasWarnings: function() { return !(this.isBrowserSupported() && this.hasRipplez()); }, loadWarnings: function() { if (!this.isBrowserSupported()) { this.show('browser-warning'); } else if (!this.hasRipplez()) { this.show('ripple-warning'); } }, isBrowserSupported: function() { return !!window.chrome; }, hasRipplez: function () { // we do not use window.chrome.isInstalled(id) // because Ripple has two IDs (hosted and Chrome Store) // and local dev installations have unique IDs. return !!document.getElementById("tinyhippos-injected"); }, hasApiRequest: function() { return !!this.queryString().match(/url=/); }, loadApiRequest: function() { var uri = this.queryString().match(/url=([^&]*)/)[1]; uri = decodeURIComponent(uri); this.goto(uri); }, loadPageRequest: function(uri) { if (uri) { this.goto(uri); } else { this.show('content'); } }, goto: function (uri) { uri = uri.replace('platform=', 'enableripple='); if (!uri.match(/enableripple=/)) { uri += uri.match(/\?/) ? "&" : "?"; uri += 'enableripple=cordova'; } if (!uri.match(/^http[s]?:\/\//)) { uri = "http://" + uri; } this.redirect(uri); }, redirect: function(uri) { window.location.href = uri; }, show: function (id) { document.getElementById(id).setAttribute("style", ""); }, hide: function (id) { document.getElementById(id).setAttribute("style", "display: none"); }, visible: function(id) { return (document.getElementById(id).style.display === ''); }, queryString: function() { return window.location.search; }, showLoading: function(loading) { if (loading) { this.show('loading'); } else { this.hide('loading'); } } }; var page = { initialize: function() { document.body.addEventListener('click', function(e) { var el = e.target; if (el.href && el.href.match(/#$/)) { e.preventDefault(); if (el.text.match(/^emulate\./)) { app.redirect(el.text); } else { app.goto(el.text); } } }); } };
phonegap/emulate.phonegap.com
public/js/index.js
JavaScript
apache-2.0
3,293
/** * Copyright 2011-2021 Asakusa Framework Team. * * 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.asakusafw.directio.hive.parquet.v1; import java.util.List; import com.asakusafw.directio.hive.serde.PropertyDescriptor; import com.asakusafw.runtime.value.ValueOption; import parquet.io.api.Converter; import parquet.io.api.GroupConverter; /** * An implementation of parquet file data converter for Asakusa data models. * @since 0.7.0 */ public class DataModelConverter extends GroupConverter { private final PropertyDescriptor[] properties; private Object currentObject; private final ValueOption<?>[] values; private final ValueConverter[] converters; /** * Creates a new instance. * @param properties the properties in the target data model */ public DataModelConverter(List<? extends PropertyDescriptor> properties) { this.properties = properties.toArray(new PropertyDescriptor[properties.size()]); this.converters = new ValueConverter[properties.size()]; this.values = new ValueOption<?>[properties.size()]; for (int i = 0, n = this.properties.length; i < n; i++) { PropertyDescriptor property = this.properties[i]; this.converters[i] = ParquetValueDrivers.of(property.getTypeInfo(), property.getValueClass()) .getConverter(); } } /** * Sets the next target data model. * @param nextObject the next target data model */ public void prepare(Object nextObject) { if (currentObject != nextObject) { PropertyDescriptor[] ps = properties; ValueOption<?>[] vs = values; ValueConverter[] cs = converters; for (int i = 0; i < ps.length; i++) { ValueOption<?> value = ps[i].extract(nextObject); vs[i] = value; cs[i].set(value); } currentObject = nextObject; } } /** * Returns the current object. * @return the current object */ public Object getCurrentObject() { return currentObject; } @SuppressWarnings("deprecation") @Override public void start() { ValueOption<?>[] vs = values; for (int i = 0; i < vs.length; i++) { ValueOption<?> v = vs[i]; if (v != null) { v.setNull(); } } } @Override public void end() { // nothing to do } @Override public Converter getConverter(int index) { return converters[index]; } }
asakusafw/asakusafw
hive-project/core-v1/src/main/java/com/asakusafw/directio/hive/parquet/v1/DataModelConverter.java
Java
apache-2.0
3,108
/** * Copyright 1996-2013 Founder International Co.,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. * * @author kenshin */ package com.founder.fix.fixflow.core.impl; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.ThreadPoolExecutor; import org.quartz.JobDetail; import org.quartz.JobExecutionContext; import org.quartz.JobKey; import org.quartz.Scheduler; import org.quartz.SchedulerException; import org.quartz.SchedulerFactory; import org.quartz.Trigger; import org.quartz.TriggerKey; import org.quartz.impl.matchers.GroupMatcher; import com.founder.fix.fixflow.core.ProcessEngineManagement; import com.founder.fix.fixflow.core.ScheduleService; import com.founder.fix.fixflow.core.exception.FixFlowException; import com.founder.fix.fixflow.core.exception.FixFlowScheduleException; import com.founder.fix.fixflow.core.impl.cmd.ExecuteConnectorTimeJobCmd; import com.founder.fix.fixflow.core.impl.cmd.GetSchedulerFactoryCmd; import com.founder.fix.fixflow.core.impl.cmd.GetThreadPoolExecutorCmd; import com.founder.fix.fixflow.core.impl.cmd.SaveJobCmd; import com.founder.fix.fixflow.core.impl.job.JobEntity; import com.founder.fix.fixflow.core.impl.util.StringUtil; import com.founder.fix.fixflow.core.internationalization.ExceptionCode; import com.founder.fix.fixflow.core.job.Job; public class ScheduleServiceImpl extends ServiceImpl implements ScheduleService { public SchedulerFactory getSchedulerFactory() { return commandExecutor.execute(new GetSchedulerFactoryCmd()); } public boolean getIsEnabled(){ return StringUtil.getBoolean(ProcessEngineManagement.getDefaultProcessEngine().getProcessEngineConfiguration().getQuartzConfig().getIsEnable()); } public Scheduler getScheduler() { return ProcessEngineManagement.getDefaultProcessEngine().getProcessEngineConfiguration().getScheduler(); } public void schedulerRestart() { if(!getIsEnabled()){ throw new FixFlowScheduleException(ExceptionCode.QUARZTEXCEPTION_ISENABLE); } Scheduler scheduler; try { scheduler = getScheduler(); if(scheduler.isInStandbyMode()){ scheduler.start(); }else{ scheduler.standby(); scheduler.start(); } } catch (SchedulerException e) { throw new FixFlowException(e.getMessage(),e); } } public void schedulerStart() { if(!getIsEnabled()){ throw new FixFlowScheduleException(ExceptionCode.QUARZTEXCEPTION_ISENABLE); } Scheduler scheduler; try { scheduler = getScheduler(); if(scheduler.isInStandbyMode()){ scheduler.start(); } } catch (SchedulerException e) { throw new FixFlowException(e.getMessage(),e); } } public void schedulerShutdown() { if(!getIsEnabled()){ throw new FixFlowScheduleException(ExceptionCode.QUARZTEXCEPTION_ISENABLE); } Scheduler scheduler; try { scheduler = getScheduler(); if(!scheduler.isInStandbyMode()){ scheduler.standby(); } } catch (SchedulerException e) { throw new FixFlowException(e.getMessage(),e); } } public ThreadPoolExecutor getThreadPoolExecutor() { return commandExecutor.execute(new GetThreadPoolExecutorCmd(null)); } public ThreadPoolExecutor getThreadPoolExecutor(String threadPoolKey) { return commandExecutor.execute(new GetThreadPoolExecutorCmd(threadPoolKey)); } public Job createJob() { Job job=new JobEntity(); return job; } public void saveJob(Job job) { commandExecutor.execute(new SaveJobCmd(job, false)); } public void saveJob(Job job,boolean isNowPerform) { commandExecutor.execute(new SaveJobCmd(job, isNowPerform)); } public void executeConnectorTimeJob(JobExecutionContext jobExecutionContext) { commandExecutor.execute(new ExecuteConnectorTimeJobCmd(jobExecutionContext)); } public List<JobDetail> getJobList(String queryId){ if(!getIsEnabled()){ throw new FixFlowScheduleException(ExceptionCode.QUARZTEXCEPTION_ISENABLE); } Scheduler scheduler = getScheduler(); List<JobDetail> jobList = new ArrayList<JobDetail>(); Set<JobKey> set = new HashSet<JobKey>(); try { //如果queryId不为空,则返回queryId对应的job,否则返回所有job if(StringUtil.isNotEmpty(queryId)){ set = scheduler.getJobKeys(GroupMatcher.jobGroupContains(queryId)); }else{ List<String> groupNames = scheduler.getJobGroupNames(); for(String groupName:groupNames){ set.addAll(scheduler.getJobKeys(GroupMatcher.jobGroupEquals(groupName))); } } for(JobKey key :set){ JobDetail job = scheduler.getJobDetail(key); jobList.add(job); } }catch (SchedulerException e) { throw new FixFlowException(e.getMessage(),e); } return jobList; } public void suspendJob(String name, String group) { if(!getIsEnabled()){ throw new FixFlowScheduleException(ExceptionCode.QUARZTEXCEPTION_ISENABLE); } Scheduler scheduler = getScheduler(); try { scheduler.pauseJob(new JobKey(name,group)); } catch (SchedulerException e) { throw new FixFlowException(e.getMessage(),e); } } public void continueJob(String name, String group) { if(!getIsEnabled()){ throw new FixFlowScheduleException(ExceptionCode.QUARZTEXCEPTION_ISENABLE); } Scheduler scheduler = getScheduler(); try { scheduler.resumeJob(new JobKey(name,group)); } catch (SchedulerException e) { throw new FixFlowException(e.getMessage(),e); } } public List<Trigger> getTriggerList(String jobName, String jobGroup) { if(!getIsEnabled()){ throw new FixFlowScheduleException(ExceptionCode.QUARZTEXCEPTION_ISENABLE); } Scheduler scheduler = getScheduler(); try{ @SuppressWarnings("unchecked") List<Trigger> triggers = (List<Trigger>) scheduler.getTriggersOfJob(new JobKey(jobName,jobGroup)); return triggers; }catch(Exception e){ throw new FixFlowException(e.getMessage(),e); } } public void suspendTrigger(String triggerName, String triggerGroup) { if(!getIsEnabled()){ throw new FixFlowScheduleException(ExceptionCode.QUARZTEXCEPTION_ISENABLE); } Scheduler scheduler = getScheduler(); TriggerKey tKey = new TriggerKey(triggerName,triggerGroup); try { scheduler.pauseTrigger(tKey); } catch (SchedulerException e) { throw new FixFlowException(e.getMessage(),e); } } public void continueTrigger(String triggerName, String triggerGroup) { if(!getIsEnabled()){ throw new FixFlowScheduleException(ExceptionCode.QUARZTEXCEPTION_ISENABLE); } Scheduler scheduler = getScheduler(); TriggerKey tKey = new TriggerKey(triggerName,triggerGroup); try { scheduler.resumeTrigger(tKey); } catch (SchedulerException e) { throw new FixFlowException(e.getMessage(),e); } } }
summer0581/sumflow
modules/fixflow-core/src/main/java/com/founder/fix/fixflow/core/impl/ScheduleServiceImpl.java
Java
apache-2.0
7,186
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'maxim' import os # noinspection PyUnresolvedReferences from models import * from util import * class ModelInfo(object): def __init__(self, path, model_class, model_params, run_params): self.path = path self.model_class = model_class self.model_params = model_params self.run_params = run_params def is_available(self): return self.model_class is not None def __repr__(self): return repr({'path': self.path, 'class': self.model_class}) def get_model_info(path, strict=True): model_params = _read_dict(os.path.join(path, 'model-params.txt')) run_params = _read_dict(os.path.join(path, 'run-params.txt')) model_class = run_params['model_class'] resolved_class = globals()[model_class] if strict and resolved_class is None: raise ModelNotAvailable(model_class) return ModelInfo(path, resolved_class, model_params, run_params) def _read_dict(path): with open(path, 'r') as file_: content = file_.read() return str_to_obj(content) class ModelNotAvailable(BaseException): def __init__(self, model_class, *args): super(ModelNotAvailable, self).__init__(*args) self.model_class = model_class
maxim5/time-series-machine-learning
predict/model_io.py
Python
apache-2.0
1,222
/* * 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.flink.table.planner.plan.nodes.exec.batch; import org.apache.flink.api.dag.Transformation; import org.apache.flink.streaming.api.operators.OneInputStreamOperator; import org.apache.flink.streaming.api.transformations.OneInputTransformation; import org.apache.flink.table.data.RowData; import org.apache.flink.table.planner.codegen.CodeGeneratorContext; import org.apache.flink.table.planner.codegen.agg.batch.AggWithoutKeysCodeGenerator; import org.apache.flink.table.planner.codegen.agg.batch.SortAggCodeGenerator; import org.apache.flink.table.planner.delegation.PlannerBase; import org.apache.flink.table.planner.plan.nodes.exec.ExecEdge; import org.apache.flink.table.planner.plan.nodes.exec.ExecNode; import org.apache.flink.table.planner.plan.nodes.exec.ExecNodeBase; import org.apache.flink.table.planner.plan.nodes.exec.InputProperty; import org.apache.flink.table.planner.plan.utils.AggregateInfoList; import org.apache.flink.table.planner.plan.utils.AggregateUtil; import org.apache.flink.table.planner.utils.JavaScalaConversionUtil; import org.apache.flink.table.runtime.generated.GeneratedOperator; import org.apache.flink.table.runtime.operators.CodeGenOperatorFactory; import org.apache.flink.table.runtime.typeutils.InternalTypeInfo; import org.apache.flink.table.types.logical.RowType; import org.apache.calcite.rel.core.AggregateCall; import java.util.Arrays; import java.util.Collections; /** Batch {@link ExecNode} for (global) sort-based aggregate operator. */ public class BatchExecSortAggregate extends ExecNodeBase<RowData> implements BatchExecNode<RowData> { private final int[] grouping; private final int[] auxGrouping; private final AggregateCall[] aggCalls; private final RowType aggInputRowType; private final boolean isMerge; private final boolean isFinal; public BatchExecSortAggregate( int[] grouping, int[] auxGrouping, AggregateCall[] aggCalls, RowType aggInputRowType, boolean isMerge, boolean isFinal, InputProperty inputProperty, RowType outputType, String description) { super(Collections.singletonList(inputProperty), outputType, description); this.grouping = grouping; this.auxGrouping = auxGrouping; this.aggCalls = aggCalls; this.aggInputRowType = aggInputRowType; this.isMerge = isMerge; this.isFinal = isFinal; } @SuppressWarnings("unchecked") @Override protected Transformation<RowData> translateToPlanInternal(PlannerBase planner) { final ExecEdge inputEdge = getInputEdges().get(0); final Transformation<RowData> inputTransform = (Transformation<RowData>) inputEdge.translateToPlan(planner); final RowType inputRowType = (RowType) inputEdge.getOutputType(); final RowType outputRowType = (RowType) getOutputType(); final CodeGeneratorContext ctx = new CodeGeneratorContext(planner.getTableConfig()); final AggregateInfoList aggInfos = AggregateUtil.transformToBatchAggregateInfoList( aggInputRowType, JavaScalaConversionUtil.toScala(Arrays.asList(aggCalls)), null, null); final GeneratedOperator<OneInputStreamOperator<RowData, RowData>> generatedOperator; if (grouping.length == 0) { generatedOperator = AggWithoutKeysCodeGenerator.genWithoutKeys( ctx, planner.getRelBuilder(), aggInfos, inputRowType, outputRowType, isMerge, isFinal, "NoGrouping"); } else { generatedOperator = SortAggCodeGenerator.genWithKeys( ctx, planner.getRelBuilder(), aggInfos, inputRowType, outputRowType, grouping, auxGrouping, isMerge, isFinal); } return new OneInputTransformation<>( inputTransform, getDescription(), new CodeGenOperatorFactory<>(generatedOperator), InternalTypeInfo.of(outputRowType), inputTransform.getParallelism()); } }
kl0u/flink
flink-table/flink-table-planner-blink/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/batch/BatchExecSortAggregate.java
Java
apache-2.0
5,461
# Thielavia terrestris (Apinis) Malloch & Cain, 1972 SPECIES #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in Can. J. Bot. 50(1): 66 (1972) #### Original name Allescheria terrestris Apinis, 1963 ### Remarks null
mdoering/backbone
life/Fungi/Ascomycota/Sordariomycetes/Sordariales/Chaetomiaceae/Thielavia/Thielavia terrestris/README.md
Markdown
apache-2.0
264
--- layout: post title: 짐승의 이름들 author: drkim date: 2004-12-11 12:56:15 +0900 tags: [깨달음의대화] --- **앤디 드레이크** 앤디는 착한 소년이다. 누구나 앤디를 좋아한다. 그러면서도 다들 앤디를 괴롭혔다. 왜냐하면 그것이 앤디를 상대하는 우리들의 방식이었으므로. 앤디는 그래도 잘 받아들였다. 5학년인 우리에게 앤디는 감정의 배출구였다. 앤디는 거지왕자이야기의 왕자를 대신해 매맞는 소년과도 같았다. 우리패거리에 그를 끼어주는 것만으로도 앤디는 그 특별대우를 잘 감수하였다. 사회복지수당으로 근근히 살아가는 앤디가족, 남루한 옷, 지저분한 손발, 그는 언제나 우리의 놀림감이었지만 그래도 대항 한 번 하지 않았다. 물론 누구도 앤디를 괴롭히자고 모의하지는 않았다. 단지 그렇게 되었을 뿐이다. 그래도 다들 앤디를 좋아했는데 어느날 누군가가 말했다. “앤디는 우리와는 달라. 우린 걔가 싫어. 안그러니?” 누가 우리들 마음 속에 잠들어있는 야만적인 심성을 두드려 깨웠는지 알수가 없다. 내가 먼저 시작한건 아니다. 그러나 그 죄의식으로부터 자유로울 수는 없다. 『유죄! 지옥의 가장 고통스런 장소는 위기의 순간에 중립을 지킨 자를 위해 예약되어 있다.』 주말에 우리 소년탐험대는 근처의 숲으로 캠핑을 가기로 했다. 타이어 대신 정원에서 쓰는 호스를 잘라 끼운 고물 자전거를 끌고 앤디가 나타났다. 내게 그 임무가 주어졌다. 앤디는 즐거운 인사를 건네왔고 나는 우리들 일동을 대표하여 앤디에게 말했다. “앤디, 우린 널 원치 않아.” 내가 텐트 안으로 들어갔을 때 아직도 그 일의 심각성을 느끼지 못한 한 친구가 앤디를 놀리는 그 치졸한 노래를 또다시 부르기 시작했다. “앤디 드레이크는 케이크를 못먹는데요. 걔네 여동생은 파이를 못 먹는 대요. 사회복지 수당이 없으면 드레이크네 식구들은 모두 굶어 죽어요.” 그러자 모두가 느꼈다. 아무도 말하지 않았지만 너무나 끔직하고 잔인한 잘못을 저질렀음을 우리는 뒤늦게 깨닫고 몸서리를 쳤다. 한 순진한 인간을 어리석음으로 파괴했다. 우리 마음속에 지울수 없는 상처로 남았다. 그가 언제부터 우리들 시야에서 사라져 버렸는지는 알 수 없다. 그 후 다시는 앤디를 만날 수 없었다. 아니 내가 앤디를 만나지 못했다고 말하는 것은 정확한 표현이 아니다. 알칸사스에서의 그 가을날 이후, 나는 지난 이삼십년 동안 수천 명이 넘는 앤디 드레이크와 마주쳤다.(하략) 마음을 열어주는 101가지 이야기에 나오는 글입니다. 원문은 훨씬 긴 내용인데 압축했습니다. 원문을 보시려면 클릭해 주십시오. 이지메에 대하여 이야기하려는 것이 아닙니다. 집단무의식에 대해서 이야기하려는 것입니다. “정신차려 우리가 지금 무슨 짓을 저질렀지?” 깨달아야 합니다. 줄의 맨 첫 번째 자리에 선 사람이 1°의 각도로 비뚤게 서면 그 뒤로 줄줄이 틀리게 된다는 사실을 깨닫기입니다. 나 한 사람의 잘못은 아무것도 아닙니다. 난 단지 약간 비뚤게 줄을 섰을 뿐이지요. 그러나 내가 선 위치가 하필이면 맨 앞자리였기 때문에 내 뒤로 줄을 선 100명이 모두 틀려버린 것입니다. 철없는 소년의 말 한마디로 해서 '앤디 드레이크'라는 한 사람의 운명이 바뀌어버린 것입니다. 물론 그 시절에는 그것을 깨닫지 못했던 거지요. \### 너무 큰 것을 얻어맞아서 뭐라고 글을 쓸수가 없습니다. 비통할 뿐입니다. 한나라당의 저 바보들이 매양 바보짓을 일삼고 있지만 '야 이 바보들아' 하고 비웃어줄 기운도 없습니다. 차라리 이회창에게 날마다 창자를 씹히는게 나을 지경입니다. 도무지 정치를 모르는.. 박근혜, 전여옥들. 개망나니 초재선들. 인간에 대한 환멸입니다. 원희룡, 고진화, 배일도, 이재오, 김문수, 김덕룡들.. 어제의 동지를 간첩이라고 욕하는 무리들. 인간이 어찌 그럴 수가 있다는 말이오. 밀양의 그 가해자 부모말이 차라리 맞을 듯 합니다. 피해자 너 하나만 참으면 밀양천지가 조용해 지는데.. 피해자 너 한 사람이 참으면 대한민국이 조용해 지는데.. 피해자 너 하나가 떠들고 나서서 대한민국이 세계적으로 개망신을 당하고 있는데.. 빨갱이 너 사실은 죄 없는 줄 알지만 그래도 너 하나 희생시켜서 나라의 기강을 잡으면 나라가 조용해 지고 수출이 잘될 판인데.. 너 하나만 희생하면, 너 하나만 희생하면, 너 하나만 희생하면.. 그렇게 말하면서 우리는 무수히 많은 죄 없는 유태인 드레퓌스대위를, 죄 없는 소년 앤디 드레이크를, 아무 죄 없는 이철우의원을.. 죄 없는 밀양의 어린 소녀들에게 돌을 던져왔던 것입니다. 월남이라고 말하면 표현이 적절하지 않으므로 이라크에 파병된 미군이라고 칩시다. 1만명이 투입되면 그 중 1천명이 죽거나 부상을 당합니다. 제비뽑기와 같습니다. 죽거나 부상당한 사람은 단지 재수가 없었던 뿐입니다. 그 불행한 1천명의 몫을 나머지 9천명이 전투수당으로 나눠갖는 것입니다. 그 먼 이라크 까지 갈 필요가 있습니까? 그냥 플로리다에 모여 앉아서 가위바위보를 하는 것입니다. 한 명이 선택되면 그 한 명의 동료를 때려죽이고 그 한 명이 소지한 것을 나머지 아홉명이 나눠가지면 됩니다. 지금 미군이 이라크에서 자행하고 있는 짓이 바로 그런 짓입니다. 소년탐험대의 어린이들이 마을에서는 그러지 못하고 숲 속으로 캠프를 가서 그 못된 짓을 저질렀듯이 벼룩도 낯짝이 있는지라 플로리다에서는 그러지 못하고 이라크까지 가서 그 짓을 벌이는 것입니다. 앤디 드레이크는 마을마다 한 명씩 꼭 있습니다. 이것이 전통적인 인류의 관습법입니다. 10만년 전부터 인류는 그래왔던 것입니다. 그 야만의 사슬을 이제는 끊어야 합니다. 감정이 격앙되어 더 쓰지 못하겠군요. 이 하늘아래 이 땅 위에서 짐승이 아닌 인간으로 살아내기가 이렇게도 힘들다는 말입니까?
gujoron/gujoron.github.io
_posts/2004-12-11-짐승의-이름들.md
Markdown
apache-2.0
6,934
// Code generated by counterfeiter. DO NOT EDIT. package routerfakes import ( "sync" "code.cloudfoundry.org/cli/api/router" ) type FakeConnection struct { MakeStub func(*router.Request, *router.Response) error makeMutex sync.RWMutex makeArgsForCall []struct { arg1 *router.Request arg2 *router.Response } makeReturns struct { result1 error } makeReturnsOnCall map[int]struct { result1 error } invocations map[string][][]interface{} invocationsMutex sync.RWMutex } func (fake *FakeConnection) Make(arg1 *router.Request, arg2 *router.Response) error { fake.makeMutex.Lock() ret, specificReturn := fake.makeReturnsOnCall[len(fake.makeArgsForCall)] fake.makeArgsForCall = append(fake.makeArgsForCall, struct { arg1 *router.Request arg2 *router.Response }{arg1, arg2}) fake.recordInvocation("Make", []interface{}{arg1, arg2}) fake.makeMutex.Unlock() if fake.MakeStub != nil { return fake.MakeStub(arg1, arg2) } if specificReturn { return ret.result1 } fakeReturns := fake.makeReturns return fakeReturns.result1 } func (fake *FakeConnection) MakeCallCount() int { fake.makeMutex.RLock() defer fake.makeMutex.RUnlock() return len(fake.makeArgsForCall) } func (fake *FakeConnection) MakeCalls(stub func(*router.Request, *router.Response) error) { fake.makeMutex.Lock() defer fake.makeMutex.Unlock() fake.MakeStub = stub } func (fake *FakeConnection) MakeArgsForCall(i int) (*router.Request, *router.Response) { fake.makeMutex.RLock() defer fake.makeMutex.RUnlock() argsForCall := fake.makeArgsForCall[i] return argsForCall.arg1, argsForCall.arg2 } func (fake *FakeConnection) MakeReturns(result1 error) { fake.makeMutex.Lock() defer fake.makeMutex.Unlock() fake.MakeStub = nil fake.makeReturns = struct { result1 error }{result1} } func (fake *FakeConnection) MakeReturnsOnCall(i int, result1 error) { fake.makeMutex.Lock() defer fake.makeMutex.Unlock() fake.MakeStub = nil if fake.makeReturnsOnCall == nil { fake.makeReturnsOnCall = make(map[int]struct { result1 error }) } fake.makeReturnsOnCall[i] = struct { result1 error }{result1} } func (fake *FakeConnection) Invocations() map[string][][]interface{} { fake.invocationsMutex.RLock() defer fake.invocationsMutex.RUnlock() fake.makeMutex.RLock() defer fake.makeMutex.RUnlock() copiedInvocations := map[string][][]interface{}{} for key, value := range fake.invocations { copiedInvocations[key] = value } return copiedInvocations } func (fake *FakeConnection) recordInvocation(key string, args []interface{}) { fake.invocationsMutex.Lock() defer fake.invocationsMutex.Unlock() if fake.invocations == nil { fake.invocations = map[string][][]interface{}{} } if fake.invocations[key] == nil { fake.invocations[key] = [][]interface{}{} } fake.invocations[key] = append(fake.invocations[key], args) } var _ router.Connection = new(FakeConnection)
cloudfoundry/cli
api/router/routerfakes/fake_connection.go
GO
apache-2.0
2,911
# Notocactus linkii (Lehm.) Herter SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Caryophyllales/Cactaceae/Notocactus/Notocactus linkii/README.md
Markdown
apache-2.0
182
# Nigritella nigra subsp. gallica SUBSPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Gymnadenia/Gymnadenia austriaca/ Syn. Nigritella nigra gallica/README.md
Markdown
apache-2.0
191
# Rosa gallicoides var. pseudobibracteata Rouy VARIETY #### Status DOUBTFUL #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Rosales/Rosaceae/Rosa/Rosa gallicoides/Rosa gallicoides pseudobibracteata/README.md
Markdown
apache-2.0
202
# Pinalia foliosa (Brongn.) Kuntze SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Pseuderia/Pseuderia foliosa/ Syn. Pinalia foliosa/README.md
Markdown
apache-2.0
189
# Caloplaca subochracea var. subochracea VARIETY #### Status ACCEPTED #### According to Index Fungorum #### Published in null #### Original name Caloplaca subochracea var. subochracea ### Remarks null
mdoering/backbone
life/Fungi/Ascomycota/Lecanoromycetes/Teloschistales/Teloschistaceae/Caloplaca/Caloplaca subochracea/Caloplaca subochracea subochracea/README.md
Markdown
apache-2.0
205
# Evactoma stellata var. scabrella Nieuwl. VARIETY #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Caryophyllales/Caryophyllaceae/Evactoma/Evactoma stellata/Evactoma stellata scabrella/README.md
Markdown
apache-2.0
190
# Orchis cassidea M.Bieb. SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Anacamptis/Anacamptis coriophora/ Syn. Orchis cassidea/README.md
Markdown
apache-2.0
180
package com.alibaba.fastjson.serializer; import java.io.ByteArrayOutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.lang.reflect.Field; import java.util.logging.Logger; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.util.IOUtils; public class SerializeWriterTest { private final Logger logger = Logger.getLogger(SerializeWriterTest.class.getSimpleName()); private final ByteArrayOutputStream baos = new ByteArrayOutputStream(); private final SerializeWriter writer = new SerializeWriter(new OutputStreamWriter(baos)); @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @Test public void testWriteLiteBasicStr() throws UnsupportedEncodingException { String targetStr = new String(IOUtils.DIGITS); this.doTestWrite(targetStr); } private String doTestWrite(String input) throws UnsupportedEncodingException { writer.writeString(input, (char) 0); writer.flush(); String result = this.baos.toString("UTF-8"); Assert.assertEquals(input, JSON.parse(result)); logger.info(result); return result; } @Test public void testWriteLiteSpecilaStr() throws UnsupportedEncodingException { this.doTestWrite(this.makeSpecialChars()); } private String makeSpecialChars() { StringBuilder strBuilder = new StringBuilder(128); for (char c = 128; c <= 160; c++) { strBuilder.append(c); } return strBuilder.toString(); } @Test public void testWriteLargeBasicStr() throws UnsupportedEncodingException { String str = createLargeBasicStr(); this.doTestWrite(str); } private String createLargeBasicStr() { String tmp = new String(IOUtils.DIGITS); StringBuilder builder = new StringBuilder(); for (int i = 0; i < 400; i++) { builder.append(tmp); } return builder.toString(); } @Test public void testWriteLargeSpecialStr() throws UnsupportedEncodingException { String tmp = this.makeSpecialChars(); StringBuilder builder = new StringBuilder(); for (int i = 0; i < 200; i++) { builder.append(tmp); } this.doTestWrite(builder.toString()); } @Test public void test_large() throws Exception { SerializeWriter writer = new SerializeWriter(); for (int i = 0; i < 1024 * 1024; ++i) { writer.write(i); } writer.close(); } @Test public void testBytesBufLocal() throws Exception { String str = createLargeBasicStr(); SerializeWriter writer = new SerializeWriter(); //写入大于12K的字符串 writer.writeString(str); writer.writeString(str); byte[] bytes = writer.toBytes("UTF-8"); writer.close(); //检查bytesLocal大小,如果缓存成功应该大于等于输出的bytes长度 Field bytesBufLocalField = SerializeWriter.class.getDeclaredField("bytesBufLocal"); bytesBufLocalField.setAccessible(true); ThreadLocal<byte[]> bytesBufLocal = (ThreadLocal<byte[]>) bytesBufLocalField.get(null); byte[] bytesLocal = bytesBufLocal.get(); Assert.assertNotNull("bytesLocal is null", bytesLocal); Assert.assertTrue("bytesLocal is smaller than expected", bytesLocal.length >= bytes.length); } }
alibaba/fastjson
src/test/java/com/alibaba/fastjson/serializer/SerializeWriterTest.java
Java
apache-2.0
3,615
/** * Copyright 2013-2018 the original author or authors from the JHipster project. * * This file is part of the JHipster project, see https://www.jhipster.tech/ * for more information. * * 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. */ /* eslint-disable consistent-return */ const BaseGenerator = require('../generator-base'); const writeFiles = require('./files').writeFiles; const packagejs = require('../../package.json'); const constants = require('../generator-constants'); let useBlueprint; module.exports = class extends BaseGenerator { constructor(args, opts) { super(args, opts); this.configOptions = this.options.configOptions || {}; // This adds support for a `--from-cli` flag this.option('from-cli', { desc: 'Indicates the command is run from JHipster CLI', type: Boolean, defaults: false }); this.setupServerOptions(this); const blueprint = this.options.blueprint || this.configOptions.blueprint || this.config.get('blueprint'); if (!opts.fromBlueprint) { // use global variable since getters dont have access to instance property useBlueprint = this.composeBlueprint(blueprint, 'common', { 'from-cli': this.options['from-cli'], configOptions: this.configOptions, force: this.options.force }); } else { useBlueprint = false; } } // Public API method used by the getter and also by Blueprints _initializing() { return { validateFromCli() { if (!this.options['from-cli']) { this.error('This JHipster subgenerator is not intented for standalone use.'); } }, setupConsts() { // Make constants available in templates this.TEST_DIR = constants.TEST_DIR; this.CLIENT_MAIN_SRC_DIR = constants.CLIENT_MAIN_SRC_DIR; this.SERVER_MAIN_RES_DIR = constants.SERVER_MAIN_RES_DIR; this.packagejs = packagejs; const configuration = this.getAllJhipsterConfig(this, true); this.applicationType = configuration.get('applicationType') || this.configOptions.applicationType; if (!this.applicationType) { this.applicationType = 'monolith'; } this.serverPort = configuration.get('serverPort'); if (this.serverPort === undefined) { this.serverPort = '8080'; } this.enableSwaggerCodegen = configuration.get('enableSwaggerCodegen'); this.serviceDiscoveryType = configuration.get('serviceDiscoveryType') === 'no' ? false : configuration.get('serviceDiscoveryType'); if (this.serviceDiscoveryType === undefined) { this.serviceDiscoveryType = false; } this.databaseType = configuration.get('databaseType'); if (this.databaseType === 'mongodb') { this.prodDatabaseType = 'mongodb'; } else if (this.databaseType === 'couchbase') { this.prodDatabaseType = 'couchbase'; } else if (this.databaseType === 'cassandra') { this.prodDatabaseType = 'cassandra'; } else if (this.databaseType === 'no') { // no database, only available for microservice applications this.prodDatabaseType = 'no'; } else { // sql this.prodDatabaseType = configuration.get('prodDatabaseType'); } this.buildTool = configuration.get('buildTool'); this.jhipsterVersion = packagejs.version; if (this.jhipsterVersion === undefined) { this.jhipsterVersion = configuration.get('jhipsterVersion'); } this.authenticationType = configuration.get('authenticationType'); this.clientFramework = configuration.get('clientFramework'); const testFrameworks = configuration.get('testFrameworks'); if (testFrameworks) { this.testFrameworks = testFrameworks; } const baseName = configuration.get('baseName'); if (baseName) { // to avoid overriding name from configOptions this.baseName = baseName; } // Make documentation URL available in templates this.DOCUMENTATION_URL = constants.JHIPSTER_DOCUMENTATION_URL; this.DOCUMENTATION_ARCHIVE_URL = `${constants.JHIPSTER_DOCUMENTATION_URL + constants.JHIPSTER_DOCUMENTATION_ARCHIVE_PATH}v${ this.jhipsterVersion }`; } }; } get initializing() { if (useBlueprint) return; return this._initializing(); } // Public API method used by the getter and also by Blueprints _prompting() { return {}; } get prompting() { if (useBlueprint) return; return this._prompting(); } // Public API method used by the getter and also by Blueprints _configuring() { return { setSharedConfigOptions() { // Make dist dir available in templates if (this.buildTool === 'maven') { this.BUILD_DIR = 'target/'; } else { this.BUILD_DIR = 'build/'; } this.CLIENT_DIST_DIR = this.BUILD_DIR + constants.CLIENT_DIST_DIR; } }; } get configuring() { if (useBlueprint) return; return this._configuring(); } // Public API method used by the getter and also by Blueprints _default() { return { getSharedConfigOptions() { if (this.configOptions.clientFramework) { this.clientFramework = this.configOptions.clientFramework; } this.testFrameworks = []; if (this.configOptions.testFrameworks) { this.testFrameworks = this.configOptions.testFrameworks; } this.protractorTests = this.testFrameworks.includes('protractor'); this.gatlingTests = this.testFrameworks.includes('gatling'); } }; } get default() { if (useBlueprint) return; return this._default(); } // Public API method used by the getter and also by Blueprints _writing() { return writeFiles(); } get writing() { if (useBlueprint) return; return this._writing(); } _install() { return {}; } get install() { if (useBlueprint) return; return this._install(); } // Public API method used by the getter and also by Blueprints _end() { return {}; } get end() { if (useBlueprint) return; return this._end(); } };
sohibegit/generator-jhipster
generators/common/index.js
JavaScript
apache-2.0
7,756
/* * Copyright (C) 2017 TypeFox and others. * * 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 */ import { ContainerModule, Container } from 'inversify'; import { BackendApplicationContribution } from '@theia/core/lib/node'; import { TerminalBackendContribution } from "./terminal-backend-contribution"; import { ConnectionHandler, JsonRpcConnectionHandler } from "@theia/core/lib/common/messaging"; import { ShellProcess, ShellProcessFactory, ShellProcessOptions } from './shell-process'; import { ITerminalServer, terminalPath } from '../common/terminal-protocol'; import { IBaseTerminalClient } from '../common/base-terminal-protocol'; import { TerminalServer } from './terminal-server'; import { ILogger } from '@theia/core/lib/common/logger'; import { IShellTerminalServer, shellTerminalPath } from '../common/shell-terminal-protocol'; import { ShellTerminalServer } from '../node/shell-terminal-server'; export default new ContainerModule(bind => { bind(BackendApplicationContribution).to(TerminalBackendContribution); bind(ITerminalServer).to(TerminalServer).inSingletonScope(); bind(IShellTerminalServer).to(ShellTerminalServer).inSingletonScope(); bind(ShellProcess).toSelf().inTransientScope(); bind(ShellProcessFactory).toFactory(ctx => (options: ShellProcessOptions) => { const child = new Container({ defaultScope: 'Singleton' }); child.parent = ctx.container; const logger = ctx.container.get<ILogger>(ILogger); const loggerChild = logger.child({ 'module': 'terminal-backend' }); child.bind(ShellProcessOptions).toConstantValue({}); child.bind(ILogger).toConstantValue(loggerChild); return child.get(ShellProcess); } ); bind(ConnectionHandler).toDynamicValue(ctx => new JsonRpcConnectionHandler<IBaseTerminalClient>(terminalPath, client => { const terminalServer = ctx.container.get<ITerminalServer>(ITerminalServer); terminalServer.setClient(client); return terminalServer; }) ).inSingletonScope(); bind(ConnectionHandler).toDynamicValue(ctx => new JsonRpcConnectionHandler<IBaseTerminalClient>(shellTerminalPath, client => { const shellTerminalServer = ctx.container.get<ITerminalServer>(IShellTerminalServer); shellTerminalServer.setClient(client); return shellTerminalServer; }) ).inSingletonScope(); });
lmcgupe/theia
packages/terminal/src/node/terminal-backend-module.ts
TypeScript
apache-2.0
2,644
/* * #%L * %% * Copyright (C) 2017 BMW Car IT GmbH * %% * 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. * #L% */ 'use strict'; import test from 'ava'; const cartesianProduct = require('cartesian-product'); const Setup = require('./setup.helper.js'); function runEchoTest(config) { const setup = config[0]; const message = config[1]; const testName = 'message is sent to server and received again; connection: ' + setup.name + ', datatype: ' + typeof message; test.cb(testName, t => { setup.init().then((setup) => { setup.server.on('connection', (ws) => { ws.on('message', (message) => { ws.send(message); }); }); setup.client.onerror = (e) => { t.fail('onerror callback invoked with ' + JSON.stringify(e)); }; setup.client.onclose = () => { t.end(); }; setup.client.onopen = () => { setup.client.send(config[1]); }; setup.client.onmessage = (msg) => { t.deepEqual(msg.data, message); setup.client.close(); } }); }); } function sequentialNumberArray(count) { return Array.from(Array(count).keys()); } function flattenArray(array) { return [].concat.apply([], array) } const shortNumberArray = sequentialNumberArray(10); const longNumberArray = sequentialNumberArray(1000); const inputList = [shortNumberArray, longNumberArray]; const inputPreprocessorFunctions = [JSON.stringify, Buffer.from]; const preprocessedInput = inputList.map((input) => { return inputPreprocessorFunctions.map((fun) => { return fun(input); }); }); const messages = flattenArray(preprocessedInput); function initTlsCommunicationEncrypted() { const serverSuffix = '1'; const clientSuffix = '1'; return Setup.initTlsCommunicationEncrypted(serverSuffix, clientSuffix); } function initTlsCommunicationUnencrypted() { const serverSuffix = '1'; const clientSuffix = '1'; return Setup.initTlsCommunicationUnencrypted(serverSuffix, clientSuffix); } const nonTlsConfig = { name: 'non TLS', init: Setup.initNonTlsCommunication }; const tlsConfigEncrypted = { name: 'TLSEncrypted', init: initTlsCommunicationEncrypted }; const tlsConfigUnencrypted = { name: 'TLSUnencrypted', init: initTlsCommunicationUnencrypted }; const configs = [nonTlsConfig, tlsConfigEncrypted, tlsConfigUnencrypted]; const allTestCases = cartesianProduct([configs, messages]); allTestCases.forEach(testCase => runEchoTest(testCase));
bmwcarit/wscpp
test/js/echo.test.js
JavaScript
apache-2.0
2,988
module TreeKids extend ActiveSupport::Concern module ClassMethods def has_kids_for(klass, method_and_arguments) kids_generators[klass] = method_and_arguments end def kids_generators @kids_generators ||= superclass.try(:kids_generators).try(:dup) || { Hash => %i[x_get_tree_custom_kids], } end end # Get objects (or count) to [put into a tree under a parent node. # TODO: Perhaps push the object sorting down to SQL, if possible -- no point where there are few items. # parent --- Parent object for which we need child tree nodes returned # parents --- an Array of parent object ids, starting from tree root + 1, ending with parent's parent; only available when full_ids and not lazy def x_get_tree_kids(parent, count_only, parents) generator = self.class.kids_generators.detect { |k, v| v if parent.kind_of?(k) } return nil unless generator method = generator[1][0] attributes = generator[1][1..-1].collect do |attribute_name| case attribute_name when :parents then parents end end send(method, *([parent, count_only] + attributes)) end end
ManageIQ/manageiq-ui-classic
app/presenters/tree_kids.rb
Ruby
apache-2.0
1,146
// fieldFiltering.js // ------------------------------------------------------------------ // // Logic for filtering fields (include or exclude) from a JSON hash. // There is one public method that gets exposed. // // function applyFieldFilter(action, obj, fields) {...} // // @action : 'include' or 'exclude' // @obj : a JS hash // @fields: an array of strings, referring to fields within the hash // // Example 1: // assume a JS hash like this: // { // prop1 : 7, // prop2 : [ 1, 2, 3, 4], // prop3 : { // key1 : 'A', // key2 : null, // key3 : true // } // } // // With action = 'include' and the fields array like this: // ['prop1', 'prop3.key1'] // // ...the output will be a hash like so: // // { // prop1 : 7, // prop3 : { // key1 : 'A' // } // } // // Example 1a: // The same result can be achieved using a GraphQL expression. The equivalent to // the above example is: // // "{ prop1 prop3 { key1 } }" // // // Example 2: // assume a JS hash like this: // { // prop1 : 7, // prop2 : [ 1, 2, 3, 4], // data : [{ // key1 : 'A', // key2 : null, // key3 : true // },{ // key1 : 'B', // key2 : null, // key3 : null // },{ // key1 : 'C', // key2 : null, // key3 : false // }] // } // // With action = 'include' and the fields array like this: // ['prop2', 'data.key1'] // // ...the output will be: // // { // prop2 : [ 1, 2, 3, 4], // data : [{ // key1 : 'A' // },{ // key1 : 'B', // },{ // key1 : 'C', // }] // } // // // Example 3: // assume the same JS hash as above. // // With action = 'exclude' and the fields array like this: // ['prop2', 'data.key1'] // // ...the output will be: // // { // prop1 : 7, // data : [{ // key2 : null, // key3 : true // },{ // key2 : null, // key3 : null // },{ // key2 : null, // key3 : false // }] // } // // // created: Mon Apr 11 17:48:59 2016 // last saved: <2016-April-15 17:41:03> (function (){ function _produceHash(fieldname) { var parent = { "x" : {} }, currenthash = parent, currentprop = 'x', parts = fieldname.split('.'); parts.forEach(function(part){ if ( currenthash[currentprop] === true) { currenthash[currentprop] = {}; } currenthash[currentprop][part] = true; currenthash = currenthash[currentprop]; currentprop = part; }); return parent.x; } function _deepmerge() { var destination = {}, sources = [].slice.call( arguments, 0 ); sources.forEach(function( source ) { var prop; Object.keys(source).forEach(function(prop) { if ( prop in destination && Array.isArray( destination[ prop ] ) ) { // Concat Arrays destination[ prop ] = destination[ prop ].concat( source[ prop ] ); } else if ( prop in destination && typeof destination[ prop ] === "object" ) { // Merge Objects destination[ prop ] = _deepmerge( destination[ prop ], source[ prop ] ); } else { // Set new values destination[ prop ] = source[ prop ]; } }); }); return destination; } function _elaborateFields(fields, prefix) { // input is either an array of field names // or a graphql expression. if (Array.isArray(fields) ) { // in: ['prop1', 'prop3.key1'] // out: { "prop1": true, "prop3" : { "key1" : true } } fields.sort(); prefix = prefix || ""; // elaborate the field list to find references to nested fields var elabfields = {}; fields.forEach(function(field) { elabfields = _deepmerge(elabfields, _produceHash(field)); }); return elabfields; } if (typeof fields === 'string' ){ // transform GraphQL string into a hash of the desired kind. // in: { prop1 prop3 { key1 } } // out: { "prop1": true, "prop3" : { "key1" : true } } // fields = fields.replace(new RegExp('\\s+', 'g'), ' ') .replace(new RegExp('(.){', 'g'), '$1: {') .replace(new RegExp('([a-zA-Z_$][\\w$]*)(\\s+)', 'g'), '"$1" ') .replace(new RegExp('"\\s+(?!:)', 'g'), '" : true,') .replace(new RegExp(',\\s*}', 'g'), '}'); return JSON.parse(fields); } return null; } function _includeFields(obj, fieldset) { if (Array.isArray(obj)) { return obj.map(function(item) { _includeFields(item, fieldset); }); } var newObj = {}; Object.keys(fieldset).forEach(function(key) { if (obj.hasOwnProperty(key)) { if (fieldset[key] === true) { // pass the property through unchanged newObj[key] = obj[key]; } else { // means this is a set of nested fields var o = obj[key]; newObj[key] = (Array.isArray(o)) ? // o, the child in the source object, is an array. // Therefore apply the included fields o.map(function(item) { return _includeFields(item, fieldset[key]); }) : // the child is not an array; presume a nested hash _includeFields(o, fieldset[key]); } } }); return newObj; } function _excludeFields(obj, fieldset) { if (Array.isArray(obj)) { return obj.map(function(item) { _excludeFields(item, fieldset); }); } var newObj = {}; Object.keys(obj).forEach(function(key){ if ( ! fieldset.hasOwnProperty(key)) { // copy through properties not explicitly excluded newObj[key] = obj[key]; } else if (fieldset[key] !== true) { // means this is a set of nested fields to exclude var o = obj[key]; newObj[key] = (Array.isArray(o)) ? // o, the child in the source object, is an array. // Therefore apply the excluded fields. o.map(function(item) { return _excludeFields(item, fieldset[key]); }): // the child is not an array; presume a nested hash newObj[key] = _excludeFields(o, fieldset[key]); } }); return newObj; } function applyFieldFilter(action, obj, fields) { if ( !fields || fields.length === 0) { return obj; // no change } var elabfields = _elaborateFields(fields); var newObj = ((action == 'exclude')?_excludeFields:_includeFields)(obj, elabfields); return newObj; } // export into the global namespace if (typeof exports === "object" && exports) { // works for nodejs exports.applyFieldFilter = applyFieldFilter; } else { // works in rhino var globalScope = (function(){ return this; }).call(null); globalScope.applyFieldFilter = applyFieldFilter; } }());
apigee/apigeelint
test/fixtures/resources/sample-proxy-with-issues/response-shaping/apiproxy/resources/jsc/fieldFiltering.js
JavaScript
apache-2.0
6,685
''' Created on Apr 30, 2012 @author: h87966 ''' from unit5.blog_datastore_memory import BlogMemoryDataStore from unit5.blog_datastore_appengine import BlogAppengineDataStore class BlogDataStoreFactory(): ''' classdocs ''' storage_implementations = {'memory':BlogMemoryDataStore(), 'appengine':BlogAppengineDataStore()} def __init__(self, storage_impl='appengine'): ''' Constructor ''' self.storage = self.storage_implementations[storage_impl] def set_storage(self, blog_storage): self.storage = blog_storage def get_storage(self): return self.storage
cdoremus/udacity-python_web_development-cs253
src/unit5/blog_datastore_factory.py
Python
apache-2.0
683
"""ACME protocol messages.""" import collections import six from acme import challenges from acme import errors from acme import fields from acme import jose from acme import util OLD_ERROR_PREFIX = "urn:acme:error:" ERROR_PREFIX = "urn:ietf:params:acme:error:" ERROR_CODES = { 'badCSR': 'The CSR is unacceptable (e.g., due to a short key)', 'badNonce': 'The client sent an unacceptable anti-replay nonce', 'connection': ('The server could not connect to the client to verify the' ' domain'), 'dnssec': 'The server could not validate a DNSSEC signed domain', # deprecate invalidEmail 'invalidEmail': 'The provided email for a registration was invalid', 'invalidContact': 'The provided contact URI was invalid', 'malformed': 'The request message was malformed', 'rateLimited': 'There were too many requests of a given type', 'serverInternal': 'The server experienced an internal error', 'tls': 'The server experienced a TLS error during domain verification', 'unauthorized': 'The client lacks sufficient authorization', 'unknownHost': 'The server could not resolve a domain name', } ERROR_TYPE_DESCRIPTIONS = dict( (ERROR_PREFIX + name, desc) for name, desc in ERROR_CODES.items()) ERROR_TYPE_DESCRIPTIONS.update(dict( # add errors with old prefix, deprecate me (OLD_ERROR_PREFIX + name, desc) for name, desc in ERROR_CODES.items())) def is_acme_error(err): """Check if argument is an ACME error.""" if isinstance(err, Error) and (err.typ is not None): return (ERROR_PREFIX in err.typ) or (OLD_ERROR_PREFIX in err.typ) else: return False @six.python_2_unicode_compatible class Error(jose.JSONObjectWithFields, errors.Error): """ACME error. https://tools.ietf.org/html/draft-ietf-appsawg-http-problem-00 :ivar unicode typ: :ivar unicode title: :ivar unicode detail: """ typ = jose.Field('type', omitempty=True, default='about:blank') title = jose.Field('title', omitempty=True) detail = jose.Field('detail', omitempty=True) @classmethod def with_code(cls, code, **kwargs): """Create an Error instance with an ACME Error code. :unicode code: An ACME error code, like 'dnssec'. :kwargs: kwargs to pass to Error. """ if code not in ERROR_CODES: raise ValueError("The supplied code: %s is not a known ACME error" " code" % code) typ = ERROR_PREFIX + code return cls(typ=typ, **kwargs) @property def description(self): """Hardcoded error description based on its type. :returns: Description if standard ACME error or ``None``. :rtype: unicode """ return ERROR_TYPE_DESCRIPTIONS.get(self.typ) @property def code(self): """ACME error code. Basically self.typ without the ERROR_PREFIX. :returns: error code if standard ACME code or ``None``. :rtype: unicode """ code = str(self.typ).split(':')[-1] if code in ERROR_CODES: return code def __str__(self): return b' :: '.join( part.encode('ascii', 'backslashreplace') for part in (self.typ, self.description, self.detail, self.title) if part is not None).decode() class _Constant(jose.JSONDeSerializable, collections.Hashable): # type: ignore """ACME constant.""" __slots__ = ('name',) POSSIBLE_NAMES = NotImplemented def __init__(self, name): self.POSSIBLE_NAMES[name] = self self.name = name def to_partial_json(self): return self.name @classmethod def from_json(cls, value): if value not in cls.POSSIBLE_NAMES: raise jose.DeserializationError( '{0} not recognized'.format(cls.__name__)) return cls.POSSIBLE_NAMES[value] def __repr__(self): return '{0}({1})'.format(self.__class__.__name__, self.name) def __eq__(self, other): return isinstance(other, type(self)) and other.name == self.name def __hash__(self): return hash((self.__class__, self.name)) def __ne__(self, other): return not self == other class Status(_Constant): """ACME "status" field.""" POSSIBLE_NAMES = {} # type: dict STATUS_UNKNOWN = Status('unknown') STATUS_PENDING = Status('pending') STATUS_PROCESSING = Status('processing') STATUS_VALID = Status('valid') STATUS_INVALID = Status('invalid') STATUS_REVOKED = Status('revoked') class IdentifierType(_Constant): """ACME identifier type.""" POSSIBLE_NAMES = {} # type: dict IDENTIFIER_FQDN = IdentifierType('dns') # IdentifierDNS in Boulder class Identifier(jose.JSONObjectWithFields): """ACME identifier. :ivar IdentifierType typ: :ivar unicode value: """ typ = jose.Field('type', decoder=IdentifierType.from_json) value = jose.Field('value') class Directory(jose.JSONDeSerializable): """Directory.""" _REGISTERED_TYPES = {} # type: dict class Meta(jose.JSONObjectWithFields): """Directory Meta.""" terms_of_service = jose.Field('terms-of-service', omitempty=True) website = jose.Field('website', omitempty=True) caa_identities = jose.Field('caa-identities', omitempty=True) @classmethod def _canon_key(cls, key): return getattr(key, 'resource_type', key) @classmethod def register(cls, resource_body_cls): """Register resource.""" resource_type = resource_body_cls.resource_type assert resource_type not in cls._REGISTERED_TYPES cls._REGISTERED_TYPES[resource_type] = resource_body_cls return resource_body_cls def __init__(self, jobj): canon_jobj = util.map_keys(jobj, self._canon_key) # TODO: check that everything is an absolute URL; acme-spec is # not clear on that self._jobj = canon_jobj def __getattr__(self, name): try: return self[name.replace('_', '-')] except KeyError as error: raise AttributeError(str(error) + ': ' + name) def __getitem__(self, name): try: return self._jobj[self._canon_key(name)] except KeyError: raise KeyError('Directory field not found') def to_partial_json(self): return self._jobj @classmethod def from_json(cls, jobj): jobj['meta'] = cls.Meta.from_json(jobj.pop('meta', {})) return cls(jobj) class Resource(jose.JSONObjectWithFields): """ACME Resource. :ivar acme.messages.ResourceBody body: Resource body. """ body = jose.Field('body') class ResourceWithURI(Resource): """ACME Resource with URI. :ivar unicode uri: Location of the resource. """ uri = jose.Field('uri') # no ChallengeResource.uri class ResourceBody(jose.JSONObjectWithFields): """ACME Resource Body.""" class Registration(ResourceBody): """Registration Resource Body. :ivar acme.jose.jwk.JWK key: Public key. :ivar tuple contact: Contact information following ACME spec, `tuple` of `unicode`. :ivar unicode agreement: """ # on new-reg key server ignores 'key' and populates it based on # JWS.signature.combined.jwk key = jose.Field('key', omitempty=True, decoder=jose.JWK.from_json) contact = jose.Field('contact', omitempty=True, default=()) agreement = jose.Field('agreement', omitempty=True) status = jose.Field('status', omitempty=True) phone_prefix = 'tel:' email_prefix = 'mailto:' @classmethod def from_data(cls, phone=None, email=None, **kwargs): """Create registration resource from contact details.""" details = list(kwargs.pop('contact', ())) if phone is not None: details.append(cls.phone_prefix + phone) if email is not None: details.append(cls.email_prefix + email) kwargs['contact'] = tuple(details) return cls(**kwargs) def _filter_contact(self, prefix): return tuple( detail[len(prefix):] for detail in self.contact if detail.startswith(prefix)) @property def phones(self): """All phones found in the ``contact`` field.""" return self._filter_contact(self.phone_prefix) @property def emails(self): """All emails found in the ``contact`` field.""" return self._filter_contact(self.email_prefix) @Directory.register class NewRegistration(Registration): """New registration.""" resource_type = 'new-reg' resource = fields.Resource(resource_type) class UpdateRegistration(Registration): """Update registration.""" resource_type = 'reg' resource = fields.Resource(resource_type) class RegistrationResource(ResourceWithURI): """Registration Resource. :ivar acme.messages.Registration body: :ivar unicode new_authzr_uri: Deprecated. Do not use. :ivar unicode terms_of_service: URL for the CA TOS. """ body = jose.Field('body', decoder=Registration.from_json) new_authzr_uri = jose.Field('new_authzr_uri', omitempty=True) terms_of_service = jose.Field('terms_of_service', omitempty=True) class ChallengeBody(ResourceBody): """Challenge Resource Body. .. todo:: Confusingly, this has a similar name to `.challenges.Challenge`, as well as `.achallenges.AnnotatedChallenge`. Please use names such as ``challb`` to distinguish instances of this class from ``achall``. :ivar acme.challenges.Challenge: Wrapped challenge. Conveniently, all challenge fields are proxied, i.e. you can call ``challb.x`` to get ``challb.chall.x`` contents. :ivar acme.messages.Status status: :ivar datetime.datetime validated: :ivar messages.Error error: """ __slots__ = ('chall',) uri = jose.Field('uri') status = jose.Field('status', decoder=Status.from_json, omitempty=True, default=STATUS_PENDING) validated = fields.RFC3339Field('validated', omitempty=True) error = jose.Field('error', decoder=Error.from_json, omitempty=True, default=None) def to_partial_json(self): jobj = super(ChallengeBody, self).to_partial_json() jobj.update(self.chall.to_partial_json()) return jobj @classmethod def fields_from_json(cls, jobj): jobj_fields = super(ChallengeBody, cls).fields_from_json(jobj) jobj_fields['chall'] = challenges.Challenge.from_json(jobj) return jobj_fields def __getattr__(self, name): return getattr(self.chall, name) class ChallengeResource(Resource): """Challenge Resource. :ivar acme.messages.ChallengeBody body: :ivar unicode authzr_uri: URI found in the 'up' ``Link`` header. """ body = jose.Field('body', decoder=ChallengeBody.from_json) authzr_uri = jose.Field('authzr_uri') @property def uri(self): # pylint: disable=missing-docstring,no-self-argument # bug? 'method already defined line None' # pylint: disable=function-redefined return self.body.uri # pylint: disable=no-member class Authorization(ResourceBody): """Authorization Resource Body. :ivar acme.messages.Identifier identifier: :ivar list challenges: `list` of `.ChallengeBody` :ivar tuple combinations: Challenge combinations (`tuple` of `tuple` of `int`, as opposed to `list` of `list` from the spec). :ivar acme.messages.Status status: :ivar datetime.datetime expires: """ identifier = jose.Field('identifier', decoder=Identifier.from_json) challenges = jose.Field('challenges', omitempty=True) combinations = jose.Field('combinations', omitempty=True) status = jose.Field('status', omitempty=True, decoder=Status.from_json) # TODO: 'expires' is allowed for Authorization Resources in # general, but for Key Authorization '[t]he "expires" field MUST # be absent'... then acme-spec gives example with 'expires' # present... That's confusing! expires = fields.RFC3339Field('expires', omitempty=True) @challenges.decoder def challenges(value): # pylint: disable=missing-docstring,no-self-argument return tuple(ChallengeBody.from_json(chall) for chall in value) @property def resolved_combinations(self): """Combinations with challenges instead of indices.""" return tuple(tuple(self.challenges[idx] for idx in combo) for combo in self.combinations) @Directory.register class NewAuthorization(Authorization): """New authorization.""" resource_type = 'new-authz' resource = fields.Resource(resource_type) class AuthorizationResource(ResourceWithURI): """Authorization Resource. :ivar acme.messages.Authorization body: :ivar unicode new_cert_uri: Deprecated. Do not use. """ body = jose.Field('body', decoder=Authorization.from_json) new_cert_uri = jose.Field('new_cert_uri', omitempty=True) @Directory.register class CertificateRequest(jose.JSONObjectWithFields): """ACME new-cert request. :ivar acme.jose.util.ComparableX509 csr: `OpenSSL.crypto.X509Req` wrapped in `.ComparableX509` """ resource_type = 'new-cert' resource = fields.Resource(resource_type) csr = jose.Field('csr', decoder=jose.decode_csr, encoder=jose.encode_csr) class CertificateResource(ResourceWithURI): """Certificate Resource. :ivar acme.jose.util.ComparableX509 body: `OpenSSL.crypto.X509` wrapped in `.ComparableX509` :ivar unicode cert_chain_uri: URI found in the 'up' ``Link`` header :ivar tuple authzrs: `tuple` of `AuthorizationResource`. """ cert_chain_uri = jose.Field('cert_chain_uri') authzrs = jose.Field('authzrs') @Directory.register class Revocation(jose.JSONObjectWithFields): """Revocation message. :ivar .ComparableX509 certificate: `OpenSSL.crypto.X509` wrapped in `.ComparableX509` """ resource_type = 'revoke-cert' resource = fields.Resource(resource_type) certificate = jose.Field( 'certificate', decoder=jose.decode_cert, encoder=jose.encode_cert) reason = jose.Field('reason')
jsha/letsencrypt
acme/acme/messages.py
Python
apache-2.0
14,264
@CHARSET "UTF-8"; body{ margin: 0; background-color: #f3f3f4; color: #676a6c; font-size: 16px; margin: 0; } .loginbar{ width: 300px; margin: 0 auto; padding-top: 60px; } .loginbar .logo-txt{ margin: 0; color: #e6e6e6; font-size: 100px; font-weight: bold; } .loginbar .loginbar-tip{ font-weight: bold; } .loginbar .login-username{ width:100%; height:40px; padding:12px; margin-bottom:10px; } .margin-bottom{ margin-bottom: 15px; } .checkbox{ margin-bottom: 10px; padding-left: 20px; } .login-btn{ width: 100%; height: 34px; background-color: #1ab394; border-radius: 3px; border: 1px solid transparent; cursor: pointer; color: #FFF; font-size: 16px; }
chenweixin/ketao
src/main/webapp/css/login.css
CSS
apache-2.0
680
# Sebastiania corniculata var. major VARIETY #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Malpighiales/Euphorbiaceae/Microstachys/Microstachys hispida/ Syn. Sebastiania corniculata major/README.md
Markdown
apache-2.0
191
using System; using System.Xml.Serialization; namespace Aop.Api.Domain { /// <summary> /// InboundOrderLine Data Structure. /// </summary> [Serializable] public class InboundOrderLine : AopObject { /// <summary> /// 批次编号 /// </summary> [XmlElement("batch_code")] public string BatchCode { get; set; } /// <summary> /// 货品过期日期 /// </summary> [XmlElement("expire_date")] public string ExpireDate { get; set; } /// <summary> /// 货品编码 /// </summary> [XmlElement("goods_code")] public string GoodsCode { get; set; } /// <summary> /// ZP("正品"),CC("残次"), JS("机损"),XS("箱损"),ZT("在途库存"); /// </summary> [XmlElement("inventory_type")] public string InventoryType { get; set; } /// <summary> /// 计划入库量 /// </summary> [XmlElement("plan_quantity")] public long PlanQuantity { get; set; } /// <summary> /// 价格(单位元,保留2为小数) /// </summary> [XmlElement("price")] public string Price { get; set; } /// <summary> /// 货品生产日期 /// </summary> [XmlElement("product_date")] public string ProductDate { get; set; } /// <summary> /// 备注信息 /// </summary> [XmlElement("remark")] public string Remark { get; set; } } }
329277920/Snail
Snail.Pay.Ali.Sdk/Domain/InboundOrderLine.cs
C#
apache-2.0
1,547
/** * List Component: Basic Usage */ import React from 'react'; import NavList from '../NavList'; import NavListSection from '../../NavListSection'; import NavListItem from '../../NavListItem'; export default () => ( <div> <NavList> <NavListSection label="Settings" activeLink="#organization"> <NavListItem>Users</NavListItem> <NavListItem>Items</NavListItem> <NavListItem>Check out</NavListItem> <NavListItem href="#organization">Organization</NavListItem> <NavListItem>Circulation</NavListItem> </NavListSection> </NavList> <br /> <br /> <NavList> <NavListSection activeLink="#organization" label="Using striped style" striped> <NavListItem>Users</NavListItem> <NavListItem>Items</NavListItem> <NavListItem>Check out</NavListItem> <NavListItem href="#organization">Organization</NavListItem> <NavListItem>Circulation</NavListItem> </NavListSection> </NavList> <br /> <br /> <NavList aria-label="example navigation list"> <NavListSection activeLink="#organization" label="Using aria-label"> <NavListItem>Users</NavListItem> <NavListItem>Items</NavListItem> </NavListSection> </NavList> </div> );
folio-org/stripes-components
lib/NavList/stories/BasicUsage.js
JavaScript
apache-2.0
1,277
package Web::Summarizer::Sequence::Featurizer; use strict; use warnings; use Moose; use namespace::autoclean; # TODO : see parent class, is there a way to effectively recurse over all _id methods to build to the final id ? sub _id { my $this = shift; return join( '::' , __PACKAGE__ ); } sub run { my $this = shift; my $object = shift; # 2 - vectorize sentence # CURRENT : we need to be able to produce representations that are more than just unigrams # TODO : should correspond to weight_callback ? , coordinate_weighter => $this->coordinate_weighter my $sentence_vectorized = $object->get_ngrams( 1 , return_vector => 1 , surface_only => 1 ); return $sentence_vectorized; } with( 'Featurizer' ); __PACKAGE__->meta->make_immutable; 1;
ypetinot/web-summarization
src/perl/Web/Summarizer/Sequence/Featurizer.pm
Perl
apache-2.0
787
# Peperomia balansana C.DC. SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Piperales/Piperaceae/Peperomia/Peperomia balansana/README.md
Markdown
apache-2.0
175
<!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_112) on Thu Jul 06 10:54:06 MST 2017 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Uses of Class org.wildfly.swarm.config.infinispan.Dialect (Public javadocs 2017.7.0 API)</title> <meta name="date" content="2017-07-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.infinispan.Dialect (Public javadocs 2017.7.0 API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../org/wildfly/swarm/config/infinispan/Dialect.html" title="enum in org.wildfly.swarm.config.infinispan">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.7.0</div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/wildfly/swarm/config/infinispan/class-use/Dialect.html" target="_top">Frames</a></li> <li><a href="Dialect.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.infinispan.Dialect" class="title">Uses of Class<br>org.wildfly.swarm.config.infinispan.Dialect</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/infinispan/Dialect.html" title="enum in org.wildfly.swarm.config.infinispan">Dialect</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.infinispan">org.wildfly.swarm.config.infinispan</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="#org.wildfly.swarm.config.infinispan.cache_container">org.wildfly.swarm.config.infinispan.cache_container</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.infinispan"> <!-- --> </a> <h3>Uses of <a href="../../../../../../org/wildfly/swarm/config/infinispan/Dialect.html" title="enum in org.wildfly.swarm.config.infinispan">Dialect</a> in <a href="../../../../../../org/wildfly/swarm/config/infinispan/package-summary.html">org.wildfly.swarm.config.infinispan</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/infinispan/package-summary.html">org.wildfly.swarm.config.infinispan</a> that return <a href="../../../../../../org/wildfly/swarm/config/infinispan/Dialect.html" title="enum in org.wildfly.swarm.config.infinispan">Dialect</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="../../../../../../org/wildfly/swarm/config/infinispan/Dialect.html" title="enum in org.wildfly.swarm.config.infinispan">Dialect</a></code></td> <td class="colLast"><span class="typeNameLabel">Dialect.</span><code><span class="memberNameLink"><a href="../../../../../../org/wildfly/swarm/config/infinispan/Dialect.html#valueOf-java.lang.String-">valueOf</a></span>(<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>&nbsp;name)</code> <div class="block">Returns the enum constant of this type with the specified name.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static <a href="../../../../../../org/wildfly/swarm/config/infinispan/Dialect.html" title="enum in org.wildfly.swarm.config.infinispan">Dialect</a>[]</code></td> <td class="colLast"><span class="typeNameLabel">Dialect.</span><code><span class="memberNameLink"><a href="../../../../../../org/wildfly/swarm/config/infinispan/Dialect.html#values--">values</a></span>()</code> <div class="block">Returns an array containing the constants of this enum type, in the order they are declared.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"><a name="org.wildfly.swarm.config.infinispan.cache_container"> <!-- --> </a> <h3>Uses of <a href="../../../../../../org/wildfly/swarm/config/infinispan/Dialect.html" title="enum in org.wildfly.swarm.config.infinispan">Dialect</a> in <a href="../../../../../../org/wildfly/swarm/config/infinispan/cache_container/package-summary.html">org.wildfly.swarm.config.infinispan.cache_container</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/infinispan/cache_container/package-summary.html">org.wildfly.swarm.config.infinispan.cache_container</a> that return <a href="../../../../../../org/wildfly/swarm/config/infinispan/Dialect.html" title="enum in org.wildfly.swarm.config.infinispan">Dialect</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/infinispan/Dialect.html" title="enum in org.wildfly.swarm.config.infinispan">Dialect</a></code></td> <td class="colLast"><span class="typeNameLabel">MixedJDBCStore.</span><code><span class="memberNameLink"><a href="../../../../../../org/wildfly/swarm/config/infinispan/cache_container/MixedJDBCStore.html#dialect--">dialect</a></span>()</code> <div class="block">The dialect of this datastore.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../../../org/wildfly/swarm/config/infinispan/Dialect.html" title="enum in org.wildfly.swarm.config.infinispan">Dialect</a></code></td> <td class="colLast"><span class="typeNameLabel">BinaryJDBCStore.</span><code><span class="memberNameLink"><a href="../../../../../../org/wildfly/swarm/config/infinispan/cache_container/BinaryJDBCStore.html#dialect--">dialect</a></span>()</code> <div class="block">The dialect of this datastore.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../../org/wildfly/swarm/config/infinispan/Dialect.html" title="enum in org.wildfly.swarm.config.infinispan">Dialect</a></code></td> <td class="colLast"><span class="typeNameLabel">StringJDBCStore.</span><code><span class="memberNameLink"><a href="../../../../../../org/wildfly/swarm/config/infinispan/cache_container/StringJDBCStore.html#dialect--">dialect</a></span>()</code> <div class="block">The dialect of this datastore.</div> </td> </tr> </tbody> </table> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../../org/wildfly/swarm/config/infinispan/cache_container/package-summary.html">org.wildfly.swarm.config.infinispan.cache_container</a> with parameters of type <a href="../../../../../../org/wildfly/swarm/config/infinispan/Dialect.html" title="enum in org.wildfly.swarm.config.infinispan">Dialect</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/infinispan/cache_container/MixedJDBCStore.html" title="type parameter in MixedJDBCStore">T</a></code></td> <td class="colLast"><span class="typeNameLabel">MixedJDBCStore.</span><code><span class="memberNameLink"><a href="../../../../../../org/wildfly/swarm/config/infinispan/cache_container/MixedJDBCStore.html#dialect-org.wildfly.swarm.config.infinispan.Dialect-">dialect</a></span>(<a href="../../../../../../org/wildfly/swarm/config/infinispan/Dialect.html" title="enum in org.wildfly.swarm.config.infinispan">Dialect</a>&nbsp;value)</code> <div class="block">The dialect of this datastore.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../../../org/wildfly/swarm/config/infinispan/cache_container/BinaryJDBCStore.html" title="type parameter in BinaryJDBCStore">T</a></code></td> <td class="colLast"><span class="typeNameLabel">BinaryJDBCStore.</span><code><span class="memberNameLink"><a href="../../../../../../org/wildfly/swarm/config/infinispan/cache_container/BinaryJDBCStore.html#dialect-org.wildfly.swarm.config.infinispan.Dialect-">dialect</a></span>(<a href="../../../../../../org/wildfly/swarm/config/infinispan/Dialect.html" title="enum in org.wildfly.swarm.config.infinispan">Dialect</a>&nbsp;value)</code> <div class="block">The dialect of this datastore.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../../org/wildfly/swarm/config/infinispan/cache_container/StringJDBCStore.html" title="type parameter in StringJDBCStore">T</a></code></td> <td class="colLast"><span class="typeNameLabel">StringJDBCStore.</span><code><span class="memberNameLink"><a href="../../../../../../org/wildfly/swarm/config/infinispan/cache_container/StringJDBCStore.html#dialect-org.wildfly.swarm.config.infinispan.Dialect-">dialect</a></span>(<a href="../../../../../../org/wildfly/swarm/config/infinispan/Dialect.html" title="enum in org.wildfly.swarm.config.infinispan">Dialect</a>&nbsp;value)</code> <div class="block">The dialect of this datastore.</div> </td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../org/wildfly/swarm/config/infinispan/Dialect.html" title="enum in org.wildfly.swarm.config.infinispan">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.7.0</div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/wildfly/swarm/config/infinispan/class-use/Dialect.html" target="_top">Frames</a></li> <li><a href="Dialect.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; 2017 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p> </body> </html>
wildfly-swarm/wildfly-swarm-javadocs
2017.7.0/apidocs/org/wildfly/swarm/config/infinispan/class-use/Dialect.html
HTML
apache-2.0
13,539
# Copyright 2015, A10 Networks # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from django.conf.urls import patterns from django.conf.urls import url from a10_horizon.dashboard.a10networks.a10appliances import views urlpatterns = patterns( 'a10_horizon.dashboard.a10networks.a10appliances.views', url(r'^$', views.IndexView.as_view(), name='index') # url(r'^deleteappliance$', views.DeleteApplianceView.as_view(), name='deleteappliance') # url(r'^addimage$', views.AddImageView.as_view(), name="addimage") )
a10networks/a10-horizon
a10_horizon/dashboard/a10networks/a10appliances/urls.py
Python
apache-2.0
1,056
/** * Copyright 2016 Henning Treu * * 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 debug from 'debug'; let logger = debug('SitemapParser'); class SitemapParser { constructor() { // nop } parseSitemap(sitemap) { let widgets = [].concat(sitemap.homepage.widget); let result = []; for (let i = 0; i < widgets.length; i++) { let widget = widgets[i]; // parse Frames (Outlets) if (this.looksLikeOutletFrame(widget)) { let outlets = this.parseOutlets([].concat(widget.widget)); result = result.concat(outlets); continue; } let parsedWidget = this.parseWidget(widget); if (parsedWidget) { result.push(parsedWidget); } } return result; } parseOutlets(widgets) { let result = []; for (let i = 0; i < widgets.length; i++) { let parsedWidget = this.parseWidget(widgets[i]); if (parsedWidget) { parsedWidget.itemType = 'OutletItem'; result.push(parsedWidget); } } return result; } parseWidget(widget) { if (!widget.item) { /* istanbul ignore next */ if (process.env.NODE_ENV !== 'test') { logger("WARN: The widget '" + widget.label + "' does not reference an item."); } return; } return { type: widget.type, itemType: widget.item.type, name: widget.label, link: widget.item.link, state: widget.item.state } } looksLikeOutletFrame(widget) { return widget.type === 'Frame' && (widget.icon === 'outlet' || widget.label === 'outlet'); } }; export { SitemapParser };
htreu/OpenHAB-HomeKit-Bridge
lib/SitemapParser.js
JavaScript
apache-2.0
2,139
# AUTOGENERATED FILE FROM balenalib/vab820-quad-alpine:edge-build # remove several traces of python RUN apk del python* # http://bugs.python.org/issue19846 # > At the moment, setting "LANG=C" on a Linux system *fundamentally breaks Python 3*, and that's not OK. ENV LANG C.UTF-8 # key 63C7CC90: public key "Simon McVittie <smcv@pseudorandom.co.uk>" imported # key 3372DCFA: public key "Donald Stufft (dstufft) <donald@stufft.io>" imported RUN gpg --keyserver keyring.debian.org --recv-keys 4DE8FF2A63C7CC90 \ && gpg --keyserver keyserver.ubuntu.com --recv-key 6E3CBCE93372DCFA \ && gpg --keyserver keyserver.ubuntu.com --recv-keys 0x52a43a1e4b77b059 # point Python at a system-provided certificate database. Otherwise, we might hit CERTIFICATE_VERIFY_FAILED. # https://www.python.org/dev/peps/pep-0476/#trust-database ENV SSL_CERT_FILE /etc/ssl/certs/ca-certificates.crt ENV PYTHON_VERSION 3.9.7 # if this is called "PIP_VERSION", pip explodes with "ValueError: invalid truth value '<VERSION>'" ENV PYTHON_PIP_VERSION 21.2.4 ENV SETUPTOOLS_VERSION 58.0.0 RUN set -x \ && curl -SLO "http://resin-packages.s3.amazonaws.com/python/v$PYTHON_VERSION/Python-$PYTHON_VERSION.linux-alpine-armv7hf-libffi3.3.tar.gz" \ && echo "ac2bb1a87f649ab92d472e5fa6899205dc4a49d5ada39bb6a6a0702c1b8b1cfa Python-$PYTHON_VERSION.linux-alpine-armv7hf-libffi3.3.tar.gz" | sha256sum -c - \ && tar -xzf "Python-$PYTHON_VERSION.linux-alpine-armv7hf-libffi3.3.tar.gz" --strip-components=1 \ && rm -rf "Python-$PYTHON_VERSION.linux-alpine-armv7hf-libffi3.3.tar.gz" \ && if [ ! -e /usr/local/bin/pip3 ]; then : \ && curl -SLO "https://raw.githubusercontent.com/pypa/get-pip/430ba37776ae2ad89f794c7a43b90dc23bac334c/get-pip.py" \ && echo "19dae841a150c86e2a09d475b5eb0602861f2a5b7761ec268049a662dbd2bd0c get-pip.py" | sha256sum -c - \ && python3 get-pip.py \ && rm get-pip.py \ ; fi \ && pip3 install --no-cache-dir --upgrade --force-reinstall pip=="$PYTHON_PIP_VERSION" setuptools=="$SETUPTOOLS_VERSION" \ && find /usr/local \ \( -type d -a -name test -o -name tests \) \ -o \( -type f -a -name '*.pyc' -o -name '*.pyo' \) \ -exec rm -rf '{}' + \ && cd / \ && rm -rf /usr/src/python ~/.cache # install "virtualenv", since the vast majority of users of this image will want it RUN pip3 install --no-cache-dir virtualenv ENV PYTHON_DBUS_VERSION 1.2.18 # install dbus-python dependencies RUN apk add --no-cache \ dbus-dev \ dbus-glib-dev # install dbus-python RUN set -x \ && mkdir -p /usr/src/dbus-python \ && curl -SL "http://dbus.freedesktop.org/releases/dbus-python/dbus-python-$PYTHON_DBUS_VERSION.tar.gz" -o dbus-python.tar.gz \ && curl -SL "http://dbus.freedesktop.org/releases/dbus-python/dbus-python-$PYTHON_DBUS_VERSION.tar.gz.asc" -o dbus-python.tar.gz.asc \ && gpg --verify dbus-python.tar.gz.asc \ && tar -xzC /usr/src/dbus-python --strip-components=1 -f dbus-python.tar.gz \ && rm dbus-python.tar.gz* \ && cd /usr/src/dbus-python \ && PYTHON_VERSION=$(expr match "$PYTHON_VERSION" '\([0-9]*\.[0-9]*\)') ./configure \ && make -j$(nproc) \ && make install -j$(nproc) \ && cd / \ && rm -rf /usr/src/dbus-python # make some useful symlinks that are expected to exist RUN cd /usr/local/bin \ && ln -sf pip3 pip \ && { [ -e easy_install ] || ln -s easy_install-* easy_install; } \ && ln -sf idle3 idle \ && ln -sf pydoc3 pydoc \ && ln -sf python3 python \ && ln -sf python3-config python-config CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"] RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@python.sh" \ && echo "Running test-stack@python" \ && chmod +x test-stack@python.sh \ && bash test-stack@python.sh \ && rm -rf test-stack@python.sh RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo $'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v7 \nOS: Alpine Linux edge \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nPython v3.9.7, Pip v21.2.4, Setuptools v58.0.0 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info RUN echo $'#!/bin/bash\nbalena-info\nbusybox ln -sf /bin/busybox /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && ln -f /bin/sh /bin/sh.real \ && ln -f /bin/sh-shim /bin/sh
resin-io-library/base-images
balena-base-images/python/vab820-quad/alpine/edge/3.9.7/build/Dockerfile
Dockerfile
apache-2.0
4,835
# Birthday ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **year** | **Integer** | | [optional] **month** | **Integer** | | [optional] **day** | **Integer** | | [optional]
PitneyBowes/LocationIntelligenceSDK-Java
docs/Birthday.md
Markdown
apache-2.0
245
/* * Copyright (c) 2013 Juniper Networks, Inc. All rights reserved. */ #ifndef vnsw_agent_uve_base_h #define vnsw_agent_uve_base_h #include <sandesh/sandesh_types.h> #include <sandesh/sandesh.h> #include "nodeinfo_types.h" #include <base/connection_info.h> #include <uve/vn_uve_table_base.h> #include <uve/vm_uve_table_base.h> #include <uve/vrouter_uve_entry_base.h> #include <uve/prouter_uve_table.h> #include <uve/interface_uve_table.h> #include <boost/scoped_ptr.hpp> class VrouterStatsCollector; //The class to drive UVE module initialization for agent. //Defines objects required for statistics collection from vrouter and //objects required for sending UVE information to collector. class AgentUveBase { public: /* Number of UVEs to be sent each time, the timer callback is Run */ static const uint32_t kUveCountPerTimer = 64; /* The interval at which timer is fired */ static const uint32_t kDefaultInterval = (30 * 1000); // time in millisecs /* When timer is Run, we send atmost 'kUveCountPerTimer' UVEs. If there * are more UVEs to be sent, we reschedule timer at the following shorter * interval*/ static const uint32_t kIncrementalInterval = (1000); // time in millisecs static const uint64_t kBandwidthInterval = (1000000); // time in microseconds AgentUveBase(Agent *agent, uint64_t intvl, uint32_t default_intvl, uint32_t incremental_intvl); virtual ~AgentUveBase(); virtual void Shutdown(); uint64_t bandwidth_intvl() const { return bandwidth_intvl_; } VnUveTableBase* vn_uve_table() const { return vn_uve_table_.get(); } VmUveTableBase* vm_uve_table() const { return vm_uve_table_.get(); } Agent* agent() const { return agent_; } VrouterUveEntryBase* vrouter_uve_entry() const { return vrouter_uve_entry_.get(); } ProuterUveTable* prouter_uve_table() const { return prouter_uve_table_.get(); } InterfaceUveTable* interface_uve_table() const { return interface_uve_table_.get(); } VrouterStatsCollector *vrouter_stats_collector() const { return vrouter_stats_collector_.get(); } void Init(); virtual void InitDone() {} virtual void RegisterDBClients(); static AgentUveBase *GetInstance() {return singleton_;} uint8_t ExpectedConnections(uint8_t &num_c_nodes, uint8_t &num_d_servers); uint32_t default_interval() const { return default_interval_; } uint32_t incremental_interval() const { return incremental_interval_; } protected: boost::scoped_ptr<VnUveTableBase> vn_uve_table_; boost::scoped_ptr<VmUveTableBase> vm_uve_table_; boost::scoped_ptr<VrouterUveEntryBase> vrouter_uve_entry_; boost::scoped_ptr<ProuterUveTable> prouter_uve_table_; boost::scoped_ptr<InterfaceUveTable> interface_uve_table_; uint32_t default_interval_; uint32_t incremental_interval_; static AgentUveBase *singleton_; private: friend class UveTest; void VrouterAgentProcessState( const std::vector<process::ConnectionInfo> &c, process::ProcessState::type &state, std::string &message); void UpdateMessage(const process::ConnectionInfo &info, std::string &message); Agent *agent_; uint64_t bandwidth_intvl_; //in microseconds process::ConnectionStateManager *connection_state_manager_; DISALLOW_COPY_AND_ASSIGN(AgentUveBase); protected: boost::scoped_ptr<VrouterStatsCollector> vrouter_stats_collector_; }; #endif //vnsw_agent_uve_base_h
tcpcloud/contrail-controller
src/vnsw/agent/uve/agent_uve_base.h
C
apache-2.0
3,528
package com.gunsoft.rivercrossing; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.media.MediaPlayer; import android.os.Bundle; import android.os.Handler; import android.support.v7.app.ActionBarActivity; import android.util.Log; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.animation.TranslateAnimation; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; public class Level1Activity extends ActionBarActivity { TextView txtPetani, txtKucing, txtAnjing, txtDaging, txtStep; LinearLayout linearlayout, seberangKiri, perahuKiri, perahuKanan, seberangKanan, sisiPerahuSekarang; String letakPerahu = "kiri"; int step = 0; MediaPlayer mpLevel1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getSupportActionBar().hide(); // << hide title bar setContentView(R.layout.activity_level1); linearlayout = (LinearLayout) findViewById(R.id.linearlayout); seberangKiri = (LinearLayout) findViewById(R.id.linearSeberangKiri); seberangKanan = (LinearLayout) findViewById(R.id.linearSeberangKanan); perahuKiri = (LinearLayout) findViewById(R.id.linearPerahuKiri); perahuKanan = (LinearLayout) findViewById(R.id.linearPerahuKanan); // default perahu ada di kiri sisiPerahuSekarang = perahuKiri; final Button btnCross = (Button) findViewById(R.id.btnCross); Button btnReset = (Button) findViewById(R.id.btnReset); txtStep = (TextView) findViewById(R.id.txtStep); // hide perahu kanan perahuKanan.setVisibility(View.INVISIBLE); //Urutan Logika IF // IF pertama seberang Kiri // Kedua perahu kiri // Ketiga perahu kanan // Keempat seberang kanan txtPetani = (TextView) findViewById(R.id.txtPetani); txtPetani.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { int eventaction = event.getAction(); switch (eventaction) { case MotionEvent.ACTION_DOWN: // check condition where boat where object in the same side if(!checkCondition(txtPetani)) return false; // start condition if(((ViewGroup)txtPetani.getParent()) == seberangKiri && letakPerahu.equals("kiri")) { ((ViewGroup)txtPetani.getParent()).removeView(txtPetani); perahuKiri.addView(txtPetani); } else if(((ViewGroup)txtPetani.getParent()) == perahuKiri) { ((ViewGroup)txtPetani.getParent()).removeView(txtPetani); seberangKiri.addView(txtPetani); } else if(((ViewGroup)txtPetani.getParent()) == perahuKanan) { ((ViewGroup)txtPetani.getParent()).removeView(txtPetani); seberangKanan.addView(txtPetani); } else if(((ViewGroup)txtPetani.getParent()) == seberangKanan && letakPerahu.equals("kanan")) { ((ViewGroup)txtPetani.getParent()).removeView(txtPetani); perahuKanan.addView(txtPetani); } return true; } return false; } }); txtKucing = (TextView) findViewById(R.id.txtKucing); txtKucing.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { int eventaction = event.getAction(); switch (eventaction) { case MotionEvent.ACTION_DOWN: // check condition where boat where object in the same side if(!checkCondition(txtKucing)) return false; // start condition if(((ViewGroup)txtKucing.getParent()) == seberangKiri && letakPerahu.equals("kiri")) { if(((ViewGroup)txtAnjing.getParent()) == perahuKiri) { Toast.makeText(getApplicationContext(), "Kucing tidak bisa bersama dengan anjing", Toast.LENGTH_SHORT).show(); return false; } ((ViewGroup)txtKucing.getParent()).removeView(txtKucing); perahuKiri.addView(txtKucing); } else if(((ViewGroup)txtKucing.getParent()) == perahuKiri) { ((ViewGroup)txtKucing.getParent()).removeView(txtKucing); seberangKiri.addView(txtKucing); } else if(((ViewGroup)txtKucing.getParent()) == perahuKanan) { ((ViewGroup)txtKucing.getParent()).removeView(txtKucing); seberangKanan.addView(txtKucing); } else if(((ViewGroup)txtKucing.getParent()) == seberangKanan && letakPerahu.equals("kanan")) { if(((ViewGroup)txtAnjing.getParent()) == perahuKanan) { Toast.makeText(getApplicationContext(), "Kucing tidak bisa bersama dengan anjing", Toast.LENGTH_SHORT).show(); return false; } ((ViewGroup)txtKucing.getParent()).removeView(txtKucing); perahuKanan.addView(txtKucing); } return true; } return false; } }); txtAnjing = (TextView) findViewById(R.id.txtAnjing); txtAnjing.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { int eventaction = event.getAction(); switch (eventaction) { case MotionEvent.ACTION_DOWN: // check condition where boat where object in the same side if(!checkCondition(txtAnjing)) return false; // start condition if(((ViewGroup)txtAnjing.getParent()) == seberangKiri && letakPerahu.equals("kiri")) { if(((ViewGroup)txtKucing.getParent()) == perahuKiri) { Toast.makeText(getApplicationContext(), "Anjing tidak bisa bersama dengan Kucing", Toast.LENGTH_SHORT).show(); return false; } else if(((ViewGroup)txtDaging.getParent()) == perahuKiri) { Toast.makeText(getApplicationContext(), "Anjing tidak bisa bersama dengan Daging", Toast.LENGTH_SHORT).show(); return false; } ((ViewGroup)txtAnjing.getParent()).removeView(txtAnjing); perahuKiri.addView(txtAnjing); } else if(((ViewGroup)txtAnjing.getParent()) == perahuKiri) { ((ViewGroup)txtAnjing.getParent()).removeView(txtAnjing); seberangKiri.addView(txtAnjing); } else if(((ViewGroup)txtAnjing.getParent()) == perahuKanan) { ((ViewGroup)txtAnjing.getParent()).removeView(txtAnjing); seberangKanan.addView(txtAnjing); } else if(((ViewGroup)txtAnjing.getParent()) == seberangKanan && letakPerahu.equals("kanan")) { if(((ViewGroup)txtKucing.getParent()) == perahuKanan) { Toast.makeText(getApplicationContext(), "Anjing tidak bisa bersama dengan kucing", Toast.LENGTH_SHORT).show(); return false; } else if(((ViewGroup)txtDaging.getParent()) == perahuKanan) { Toast.makeText(getApplicationContext(), "Anjing tidak bisa bersama dengan Daging", Toast.LENGTH_SHORT).show(); return false; } ((ViewGroup)txtAnjing.getParent()).removeView(txtAnjing); perahuKanan.addView(txtAnjing); } return true; } return false; } }); txtDaging = (TextView) findViewById(R.id.txtDaging); txtDaging.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { int eventaction = event.getAction(); switch (eventaction) { case MotionEvent.ACTION_DOWN: // check condition where boat where object in the same side if(!checkCondition(txtDaging)) return false; // start condition if(((ViewGroup)txtDaging.getParent()) == seberangKiri && letakPerahu.equals("kiri")) { if(((ViewGroup)txtAnjing.getParent()) == perahuKiri) { Toast.makeText(getApplicationContext(), "Daging tidak bisa bersama dengan anjing", Toast.LENGTH_SHORT).show(); return false; } ((ViewGroup)txtDaging.getParent()).removeView(txtDaging); perahuKiri.addView(txtDaging); } else if(((ViewGroup)txtDaging.getParent()) == perahuKiri) { ((ViewGroup)txtDaging.getParent()).removeView(txtDaging); seberangKiri.addView(txtDaging); } else if(((ViewGroup)txtDaging.getParent()) == perahuKanan) { ((ViewGroup)txtDaging.getParent()).removeView(txtDaging); seberangKanan.addView(txtDaging); } else if(((ViewGroup)txtDaging.getParent()) == seberangKanan && letakPerahu.equals("kanan")) { if(((ViewGroup)txtAnjing.getParent()) == perahuKanan) { Toast.makeText(getApplicationContext(), "Daging tidak bisa bersama dengan anjing", Toast.LENGTH_SHORT).show(); return false; } ((ViewGroup)txtDaging.getParent()).removeView(txtDaging); perahuKanan.addView(txtDaging); } return true; } return false; } }); btnReset.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { reset(); } }); btnCross.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { LinearLayout seberang; int count = sisiPerahuSekarang.getChildCount(); // initialize current position if (letakPerahu.equals("kiri")) { seberang = seberangKiri; sisiPerahuSekarang = perahuKiri; } else { seberang = seberangKanan; sisiPerahuSekarang = perahuKanan; } if (count == 0) { Toast.makeText(getApplicationContext(), "Tidak bisa menyebrang tidak ada objek", Toast.LENGTH_SHORT).show(); return; } else if (((ViewGroup) txtPetani.getParent()) != sisiPerahuSekarang) { Toast.makeText(getApplicationContext(), "Petani perlu ada di kapal", Toast.LENGTH_SHORT).show(); return; } if (((ViewGroup) txtAnjing.getParent()) == seberang && ((ViewGroup) txtKucing.getParent()) == seberang) { Toast.makeText(getApplicationContext(), "Anjing dan Kucing tidak bisa bersama", Toast.LENGTH_SHORT).show(); return; } else if (((ViewGroup) txtAnjing.getParent()) == seberang && ((ViewGroup) txtDaging.getParent()) == seberang) { Toast.makeText(getApplicationContext(), "Anjing dan Daging tidak bisa bersama", Toast.LENGTH_SHORT).show(); return; } btnCross.setEnabled(false); // pindah perahu ke kanan if (letakPerahu.equals("kiri")) { TranslateAnimation animationboat = new TranslateAnimation(0, 320, 0, 0); animationboat.setDuration(1000); animationboat.setFillAfter(false); perahuKiri.startAnimation(animationboat); // move objects to right for (int i = 0; count > i; i++) { TranslateAnimation animationobjects = new TranslateAnimation(0, 0, 0, 0); animationobjects.setDuration(1000); animationobjects.setFillAfter(true); TextView t = (TextView) sisiPerahuSekarang.getChildAt(i); t.startAnimation(animationobjects); } new Handler().postDelayed(new Runnable() { public void run() { perahuKiri.setVisibility(View.INVISIBLE); perahuKanan.setVisibility(View.VISIBLE); } }, 1000); // remove object from left and add object to right for (int i = 0; count > i; i++) { TextView t = (TextView) sisiPerahuSekarang.getChildAt(0); ((ViewGroup) t.getParent()).removeView(t); perahuKanan.addView(t); } letakPerahu = "kanan"; sisiPerahuSekarang = perahuKanan; } else // pindah perahu ke kiri { TranslateAnimation animationboat = new TranslateAnimation(0, -320, 0, 0); animationboat.setDuration(1000); animationboat.setFillAfter(false); perahuKanan.startAnimation(animationboat); // move objects to left for (int i = 0; count > i; i++) { TranslateAnimation animationobjects = new TranslateAnimation(0, 0, 0, 0); animationobjects.setDuration(1000); animationobjects.setFillAfter(true); TextView t = (TextView) sisiPerahuSekarang.getChildAt(i); t.startAnimation(animationobjects); } new Handler().postDelayed(new Runnable() { public void run() { perahuKanan.setVisibility(View.INVISIBLE); perahuKiri.setVisibility(View.VISIBLE); } }, 1000); // remove object from right and add object to left for (int i = 0; count > i; i++) { TextView t = (TextView) sisiPerahuSekarang.getChildAt(0); ((ViewGroup) t.getParent()).removeView(t); perahuKiri.addView(t); } letakPerahu = "kiri"; sisiPerahuSekarang = perahuKiri; } new Handler().postDelayed(new Runnable() { public void run() { btnCross.setEnabled(true); } }, 1000); // check if win if (seberangKiri.getChildCount() == 0) { tryagain(); } } }); mpLevel1 = MediaPlayer.create(this, R.raw.bgm1); mpLevel1.setLooping(true); mpLevel1.start(); } @Override protected void onPause() { super.onPause(); mpLevel1.pause(); } @Override protected void onResume() { super.onResume(); mpLevel1.start(); } public boolean checkCondition(TextView object) { ViewGroup parentObject = (ViewGroup)object.getParent(); if(((parentObject == seberangKiri || parentObject == perahuKiri) && sisiPerahuSekarang == perahuKiri) || ((parentObject == seberangKanan || parentObject == perahuKanan) && sisiPerahuSekarang == perahuKanan)) { // jika kapal diisi oleh lebih dari 3 objek maka ditolak if((((ViewGroup)object.getParent()) == seberangKiri || ((ViewGroup)object.getParent()) == seberangKanan) && !checkPerahu()) return false; // if condition is right then add step txtStep.setText(++step + ""); } return true; } public boolean checkPerahu() { if(sisiPerahuSekarang.getChildCount() < 2) { return true; } Toast.makeText(getApplicationContext(), "Perahu tidak bisa diisi lebih dari 2 objek", Toast.LENGTH_SHORT).show(); return false; } public void reset() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Reset ?"); builder.setMessage("Coba lagi ?"); builder.setPositiveButton("YES", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // Code that is executed when clicking YES ((ViewGroup)txtPetani.getParent()).removeView(txtPetani); ((ViewGroup)txtKucing.getParent()).removeView(txtKucing); ((ViewGroup)txtDaging.getParent()).removeView(txtDaging); ((ViewGroup)txtAnjing.getParent()).removeView(txtAnjing); seberangKiri.addView(txtPetani); seberangKiri.addView(txtKucing); seberangKiri.addView(txtDaging); seberangKiri.addView(txtAnjing); sisiPerahuSekarang = perahuKiri; letakPerahu = "kiri"; // hide perahu kanan perahuKanan.setVisibility(View.INVISIBLE); // show perahu kiri perahuKiri.setVisibility(View.VISIBLE); // reset step step = 0; txtStep.setText("0"); dialog.dismiss(); } }); builder.setNegativeButton("NO", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // Code that is executed when clicking NO dialog.dismiss(); } }); AlertDialog alert = builder.create(); alert.show(); } public void tryagain() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Try Again"); builder.setMessage("You WIN Brooo, Try Again ?"); builder.setPositiveButton("YES", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // Code that is executed when clicking YES ((ViewGroup)txtPetani.getParent()).removeView(txtPetani); ((ViewGroup)txtKucing.getParent()).removeView(txtKucing); ((ViewGroup)txtDaging.getParent()).removeView(txtDaging); ((ViewGroup)txtAnjing.getParent()).removeView(txtAnjing); seberangKiri.addView(txtPetani); seberangKiri.addView(txtKucing); seberangKiri.addView(txtDaging); seberangKiri.addView(txtAnjing); sisiPerahuSekarang = perahuKiri; letakPerahu = "kiri"; // hide perahu kanan perahuKanan.setVisibility(View.INVISIBLE); // show perahu kiri perahuKiri.setVisibility(View.VISIBLE); // reset step step = 0; txtStep.setText("0"); dialog.dismiss(); } }); builder.setNegativeButton("NO", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // Code that is executed when clicking NO dialog.dismiss(); Intent intent = new Intent(Level1Activity.this, MenuActivity.class); startActivity(intent); } }); AlertDialog alert = builder.create(); alert.show(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override public boolean onTouchEvent(MotionEvent event) { int eventaction = event.getAction(); switch (eventaction) { case MotionEvent.ACTION_DOWN: // finger touches the screen Log.e("Action Down", "Action Down"); break; case MotionEvent.ACTION_MOVE: // finger moves on the screen Log.e("Action Move", "Action Move"); break; case MotionEvent.ACTION_UP: // finger leaves the screen Log.e("Action Up", "Action Up"); break; } // tell the system that we handled the event and no further processing is required return true; } }
gunantosteven/RiverCrossing
app/src/main/java/com/gunsoft/rivercrossing/Level1Activity.java
Java
apache-2.0
24,111
# Eugenia eurychila var. eurychila VARIETY #### Status ACCEPTED #### According to NUB Generator [autonym] #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Myrtales/Myrtaceae/Eugenia/Eugenia eurychila/Eugenia eurychila eurychila/README.md
Markdown
apache-2.0
174
package com.bingeweather.app.model; import java.util.ArrayList; import java.util.List; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.bingeweather.app.db.BingeWeatherOpenHelper; public class BingeWeatherDB { /** * Êý¾Ý¿âÃû */ public static final String DB_NAME = "binge_weather"; /** * Êý¾Ý¿â°æ±¾ */ public static final int VERSION = 1; private static BingeWeatherDB bingeWeatherDB; private SQLiteDatabase db; /** * ½«¹¹Ôì·½·¨Ë½Óл¯ */ private BingeWeatherDB(Context context) { BingeWeatherOpenHelper dbHelper = new BingeWeatherOpenHelper(context, DB_NAME, null, VERSION); db = dbHelper.getWritableDatabase(); } /** * »ñÈ¡BingeWeatherDBµÄʵÀý */ public synchronized static BingeWeatherDB getInstance(Context context) { if (bingeWeatherDB == null) { bingeWeatherDB = new BingeWeatherDB(context); } return bingeWeatherDB; } /** * ½«ProvinceʵÀý´æ´¢µ½Êý¾Ý¿â */ public void saveProvince(Province province) { if (province != null) { ContentValues values = new ContentValues(); values.put("province_name", province.getProvinceName()); values.put("province_code", province.getProvinceCode()); db.insert("Province", null, values); } } /** * ´ÓÊý¾Ý¿â¶Áȡȫ¹úËùÓеÄÊ¡·ÝÐÅÏ¢ */ public List<Province> loadProvinces() { List<Province> list = new ArrayList<Province>(); Cursor cursor = db.query("Province", null, null, null, null, null, null); if (cursor.moveToFirst()) { do { Province province = new Province(); province.setId(cursor.getInt(cursor.getColumnIndex("id"))); province.setProvinceName(cursor.getString(cursor.getColumnIndex("province_name"))); province.setProvinceCode(cursor.getString(cursor.getColumnIndex("province_code"))); list.add(province); } while (cursor.moveToNext()); } if (cursor != null) { cursor.close(); } return list; } /** * ½«CityʵÀý´æ´¢µ½Êý¾Ý¿â */ public void saveCity(City city) { if (city != null) { ContentValues values = new ContentValues(); values.put("city_name", city.getCityName()); values.put("city_code", city.getCityCode()); values.put("province_id", city.getProvinceId()); db.insert("City", null, values); } } /** * ´ÓÊý¾Ý¿â¶ÁȡijʡÏÂËùÓеijÇÊÐÐÅÏ¢ */ public List<City> loadCities(int provinceId) { List<City> list = new ArrayList<City>(); Cursor cursor = db.query("City", null, "province_id = ?", new String[] {String.valueOf(provinceId)}, null, null, null); if (cursor.moveToFirst()) { do { City city = new City(); city.setId(cursor.getInt(cursor.getColumnIndex("id"))); city.setCityName(cursor.getString(cursor.getColumnIndex("city_name"))); city.setCityCode(cursor.getString(cursor.getColumnIndex("city_code"))); city.setProvinceId(provinceId); list.add(city); } while (cursor.moveToNext()); } if (cursor != null) { cursor.close(); } return list; } /** * ½«CountyʵÀý´æ´¢µ½Êý¾Ý¿â */ public void saveCounty(County county) { if (county != null) { ContentValues values = new ContentValues(); values.put("county_name", county.getCountyName()); values.put("county_code", county.getCountyCode()); values.put("city_id", county.getCityId()); db.insert("County", null, values); } } /** * ´ÓÊý¾Ý¿â¶Áȡij³ÇÊÐÏÂËùÓеÄÏØÐÅÏ¢ */ public List<County> loadCounties(int cityId) { List<County> list = new ArrayList<County>(); Cursor cursor = db.query("County", null, "city_id = ?", new String[] {String.valueOf(cityId)}, null, null, null); if (cursor.moveToFirst()) { do { County county = new County(); county.setId(cursor.getInt(cursor.getColumnIndex("id"))); county.setCountyName(cursor.getString(cursor.getColumnIndex("county_name"))); county.setCountyCode(cursor.getString(cursor.getColumnIndex("county_code"))); county.setCityId(cityId); list.add(county); } while (cursor.moveToNext()); } if (cursor != null) { cursor.close(); } return list; } }
bingeCraft/bingeweather
src/com/bingeweather/app/model/BingeWeatherDB.java
Java
apache-2.0
4,084
import os import random import time import json from locust import HttpLocust, TaskSet, task from lib.baseTaskSet import baseTaskSet # TODO - make these config-driven from lib.openstack.keystone import get_auth_token from lib.openstack.nova import list_servers from lib.openstack.nova import list_servers_detail from lib.openstack.nova import list_server_detail from lib.openstack.nova import create_server from lib.openstack.nova import delete_server from lib.openstack.nova import reboot_server from lib.openstack.nova import resize_server from lib.openstack.nova import confirm_resize_server from lib.openstack.nova import revert_resize_server from lib.openstack.nova import list_limits from lib.openstack.nova import nova_get_server_id class UserBehavior(baseTaskSet): def on_start(self): super(UserBehavior, self).on_start() self.server_count = 0 self.min_server_count = 7 self.max_server_count = 10 self.auth_token, self.tenant_id, self.service_catalog = get_auth_token(self) @task(2) def nova_create_server(self): flavor_id = random.choice([42,84]) response = create_server(self, flavor_id=flavor_id, name="server-%s-%s" % (self.id, self.server_count)) server_id = json.loads(response.content)['server']['id'] self.server_count += 1 time.sleep(random.choice([1,1,3,3,3,5,5,5,5,5,5,10,10,10,10,25])) self.nova_resize_server() self.output("server id: %s" % server_id) @task(5) def nova_resize_server(self): server_id = nova_get_server_id(self) flavor_id = random.choice([42,84, 9999, 9999, 9999, 9999, 9998, 9998, 9998, 9998, 451, 451, 451]) self.output("Resize server | %s | %s " % (server_id, flavor_id)) if server_id: resize_server(self, server_id, flavor_id) time.sleep(random.choice([5,9,9,9,9,10,10,10,10,10,10,10,10,15,15,15,25,25,25,25])) choices = [1,1,1,1,1,2,2] #if random.choice(choices) %2 != 0: if choices: self.output("RESIZE YUSSSS!") confirm_resize_server(self, server_id) else: revert_resize_server(self,server_id) else: pass @task(1) def nova_confirm_resize_server(self): server_id = nova_get_server_id(self) confirm_resize_server(self, server_id) @task(1) def nova_revert_resize_server(self): server_id = nova_get_server_id(self) revert_resize_server(self, server_id) @task(2) def nova_reboot_server(self): server_id = nova_get_server_id(self) reboot_server(self, server_id) time.sleep(random.choice([1,1,1,1,3,3,3,5,10,25])) #@task(1) def nova_delete_server(self): server_id = nova_get_server_id(self) delete_server(self, server_id) @task(3) def nova_list_servers(self): self.output("LIST_SERVERS") response = list_servers(self) @task(3) def check_server_pool(self): response = list_servers(self) servers = json.loads(response.content)['servers'] if len(servers) < self.min_server_count: self.nova_create_server() elif len(servers) == self.max_server_count: self.nova_delete_server() @task(4) def nova_list_servers_detail(self): self.output("LIST_SERVERS_DETAIL") list_servers_detail(self) @task(4) def nova_list_limits(self): list_limits(self) @task(3) def keystone_auth_token(self): self.auth_token, self.tenant_id, self.service_catalog = get_auth_token(self) class WebsiteUser(HttpLocust): task_set = UserBehavior min_wait=500 max_wait=5000
pcrews/rannsaka
test_files/server_exp2.py
Python
apache-2.0
3,914
/* * Copyright (C) 2017-2019 Dremio 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.dremio.plugins.azure; import static com.dremio.common.utils.PathUtils.removeLeadingSlash; import static com.dremio.common.utils.PathUtils.removeTrailingSlash; import static com.dremio.plugins.azure.AzureAuthenticationType.ACCESS_KEY; import static com.dremio.plugins.azure.AzureAuthenticationType.AZURE_ACTIVE_DIRECTORY; import java.io.IOException; import java.util.Arrays; import java.util.Map; import java.util.Objects; import java.util.stream.Stream; import org.apache.arrow.util.VisibleForTesting; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.asynchttpclient.AsyncHttpClient; import com.dremio.common.AutoCloseables; import com.dremio.common.util.Retryer; import com.dremio.exec.hadoop.MayProvideAsyncStream; import com.dremio.exec.store.dfs.DremioFileSystemCache; import com.dremio.exec.store.dfs.FileSystemConf; import com.dremio.http.AsyncHttpClientProvider; import com.dremio.io.AsyncByteReader; import com.dremio.plugins.azure.AzureStorageConf.AccountKind; import com.dremio.plugins.util.ContainerFileSystem; import com.google.common.base.Joiner; /** * A container file system implementation for Azure Storage. * <p> * Supports both Blob containers and Hierarchical containers */ public class AzureStorageFileSystem extends ContainerFileSystem implements MayProvideAsyncStream { private static final String CONTAINER_HUMAN_NAME = "Container"; static final String ACCOUNT = "dremio.azure.account"; static final String KEY = "dremio.azure.key"; static final String MODE = "dremio.azure.mode"; static final String SECURE = "dremio.azure.secure"; static final String CONTAINER_LIST = "dremio.azure.container_list"; static final String ROOT_PATH = "dremio.azure.rootPath"; static final String CREDENTIALS_TYPE = "dremio.azure.credentialsType"; static final String CLIENT_ID = "dremio.azure.clientId"; static final String TOKEN_ENDPOINT = "dremio.azure.tokenEndpoint"; static final String CLIENT_SECRET = "dremio.azure.clientSecret"; static final String AZURE_ENDPOINT = "fs.azure.endpoint"; private String azureEndpoint; private String account; private String key = null; private AzureAuthenticationType credentialsType; private String clientID; private String tokenEndpoint; private String clientSecret; private boolean secure; private AccountKind accountKind; private Prototype proto; private Configuration parentConf; private ContainerProvider containerProvider; private AzureAuthTokenProvider authProvider; private final DremioFileSystemCache fsCache = new DremioFileSystemCache(); private AsyncHttpClient asyncHttpClient; @Override public void close() throws IOException { AutoCloseables.close(IOException.class, () -> fsCache.closeAll(true), super::close); } protected AzureStorageFileSystem() { super(FileSystemConf.CloudFileSystemScheme.AZURE_STORAGE_FILE_SYSTEM_SCHEME.getScheme(), CONTAINER_HUMAN_NAME, a -> true); } @Override protected void setup(Configuration conf) throws IOException { parentConf = conf; conf.setIfUnset(CREDENTIALS_TYPE, ACCESS_KEY.name()); credentialsType = AzureAuthenticationType.valueOf(conf.get(CREDENTIALS_TYPE)); // TODO: check if following are needed accountKind = AccountKind.valueOf(conf.get(MODE)); secure = conf.getBoolean(SECURE, true); proto = accountKind.getPrototype(secure); conf.setIfUnset(AZURE_ENDPOINT, proto.getEndpointSuffix()); azureEndpoint = conf.get(AZURE_ENDPOINT); // -- End -- account = Objects.requireNonNull(conf.get(ACCOUNT)); asyncHttpClient = AsyncHttpClientProvider.getInstance(); if (credentialsType == AZURE_ACTIVE_DIRECTORY) { clientID = Objects.requireNonNull(conf.get(CLIENT_ID)); tokenEndpoint = Objects.requireNonNull(conf.get(TOKEN_ENDPOINT)); clientSecret = Objects.requireNonNull(conf.get(CLIENT_SECRET)); this.authProvider = new AzureOAuthTokenProvider(tokenEndpoint, clientID, clientSecret); } else if (credentialsType == ACCESS_KEY) { key = Objects.requireNonNull(conf.get(KEY)); this.authProvider = new AzureSharedKeyAuthTokenProvider(account, key); } else { throw new IOException("Unrecognized credential type"); } final String[] containerList; String rootPath = conf.get(ROOT_PATH); if (rootPath != null) { rootPath = removeLeadingSlash(rootPath); rootPath = removeTrailingSlash(rootPath); } if (rootPath != null && rootPath.length()>0) { containerList = getContainerNameFromRootPath(rootPath).split(" "); rootPath = getPathWithoutContainer(rootPath); } else { containerList = getContainerNames(conf.get(CONTAINER_LIST)); rootPath = null; } if (accountKind == AccountKind.STORAGE_V2) { containerProvider = new AzureAsyncContainerProvider(asyncHttpClient, azureEndpoint, account, authProvider, this, secure, containerList, rootPath); } else { final String connection = String.format("%s://%s.%s", proto.getEndpointScheme(), account, azureEndpoint); switch (credentialsType) { case ACCESS_KEY: containerProvider = new BlobContainerProvider(this, connection, account, key, containerList); break; case AZURE_ACTIVE_DIRECTORY: try { containerProvider = new BlobContainerProviderOAuth(this, connection, account, (AzureOAuthTokenProvider) authProvider, containerList); } catch (Exception e) { throw new IOException("Unable to establish connection to Storage V1 account with Azure Active Directory"); } break; default: break; } } containerProvider.verfiyContainersExist(); } private String[] getContainerNames(String value) { if (value == null) { return null; } String[] values = value.split(","); if (values.length == 0) { return null; } return values; } private String getContainerNameFromRootPath (String path) { final String[] pathComponents = path.split(Path.SEPARATOR); if (pathComponents.length == 0) { return null; } return pathComponents[0]; } private String getPathWithoutContainer (String path) { String[] pathComponents = path.split(Path.SEPARATOR); if (pathComponents.length == 1) { return null; } return Joiner.on(Path.SEPARATOR).join( Arrays.copyOfRange(pathComponents, 1, pathComponents.length)); } @Override protected Stream<ContainerCreator> getContainerCreators() throws IOException { return containerProvider.getContainerCreators(); } static final class ContainerCreatorImpl extends ContainerCreator { private final String container; private final AzureStorageFileSystem parent; public ContainerCreatorImpl(AzureStorageFileSystem parent, String container) { this.container = container; this.parent = parent; } @VisibleForTesting @Override protected String getName() { return container; } @Override protected ContainerHolder toContainerHolder() throws IOException { return new ContainerHolder(container, new FileSystemSupplierImpl(container)); } private final class FileSystemSupplierImpl extends FileSystemSupplier { private final String containerName; public FileSystemSupplierImpl(String containerName) { this.containerName = containerName; } @Override public FileSystem create() throws IOException { final Configuration conf = new Configuration(parent.parentConf); AzureAuthenticationType credentialsType = AzureAuthenticationType.valueOf(conf.get(CREDENTIALS_TYPE)); final String location = parent.proto.getLocation(parent.account, containerName, parent.azureEndpoint); if (credentialsType == AZURE_ACTIVE_DIRECTORY) { parent.proto.setImpl(conf, parent.account, parent.clientID, parent.tokenEndpoint, parent.clientSecret, parent.azureEndpoint); return parent.fsCache.get(new Path(location).toUri(), conf, AzureStorageConf.AZURE_AD_PROPS); } parent.proto.setImpl(conf, parent.account, parent.key, parent.azureEndpoint); return parent.fsCache.get(new Path(location).toUri(), conf, AzureStorageConf.KEY_AUTH_PROPS); } } } @Override protected ContainerHolder getUnknownContainer(String containerName) throws IOException { try { containerProvider.assertContainerExists(containerName); } catch (Retryer.OperationFailedAfterRetriesException e) { throw e.getWrappedCause(IOException.class, ex -> new IOException(ex)); } return new ContainerCreatorImpl(this, containerName).toContainerHolder(); } @Override public boolean supportsAsync() { return accountKind == AccountKind.STORAGE_V2; } @Override public AsyncByteReader getAsyncByteReader(Path path, String version, Map<String, String> options) { return new AzureAsyncReader(azureEndpoint, account, path, authProvider, version, secure, asyncHttpClient); } }
dremio/dremio-oss
plugins/azure/src/main/java/com/dremio/plugins/azure/AzureStorageFileSystem.java
Java
apache-2.0
9,732
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DiscoverHollywood.Import { /// <summary> /// The MovieLens csv files loader. /// </summary> public class MovieLensFileLoader { /// <summary> /// Gets or sets a value indicating whether need load references information. /// </summary> public bool LoadLinks { get; set; } /// <summary> /// Gets or sets the directory path. /// </summary> public string DirPath { get; set; } = "data"; /// <summary> /// Loads the list from file. /// </summary> /// <returns>A collection of movie loaded.</returns> public IEnumerable<Models.Movie> Load() { IEnumerator<string> linkEnum = null; var loadLinks = LoadLinks; if (loadLinks) { var links = ReadLines("links.csv"); if (links != null) linkEnum = links.GetEnumerator(); } foreach (var line in ReadLines("movies.csv")) { var model = new Models.Movie(); var fields = Data.CsvParser.Instance.ParseLine(line); if (fields.Count < 2) { if (loadLinks) loadLinks = linkEnum.MoveNext(); continue; } int modelId; if (!int.TryParse(fields[0], out modelId)) { if (loadLinks) loadLinks = linkEnum.MoveNext(); continue; } model.Id = modelId; model.Name = fields[1]; if (model.Name.Length > 6 && model.Name[model.Name.Length - 6] == '(' && model.Name[model.Name.Length - 1] == ')') { int year; if (int.TryParse(model.Name.Substring(model.Name.Length - 5, 4), out year)) { model.Name = model.Name.Substring(0, model.Name.Length - 6); model.Year = year; } } if (fields.Count == 3) model.GenresStr = fields[2].Replace("|", ";"); if (!loadLinks) { yield return model; continue; } loadLinks = linkEnum.MoveNext(); var linkStr = linkEnum.Current; if (string.IsNullOrWhiteSpace(linkStr)) { yield return model; continue; } var linkFields = Data.CsvParser.Instance.ParseLine(linkStr); if (linkFields.Count < 3 || !int.TryParse(linkFields[0], out modelId) || modelId != model.Id) { yield return model; continue; } if (int.TryParse(linkFields[1], out modelId)) model.ImdbId = modelId; if (int.TryParse(linkFields[2], out modelId)) model.TmdbId = modelId; yield return model; } } /// <summary> /// Loads the list from file. /// </summary> /// <returns>A collection of movie loaded.</returns> public IEnumerable<Models.MovieGenres> LoadGenres() { foreach (var line in ReadLines("movies.csv")) { var fields = Data.CsvParser.Instance.ParseLine(line); if (fields.Count < 3) { continue; } int modelId; if (!int.TryParse(fields[0], out modelId)) { continue; } var GenresArr = fields[2].Trim().Split(new[] { "|" }, StringSplitOptions.RemoveEmptyEntries); foreach (var genre in GenresArr) { var model = new Models.MovieGenres(); model.MovieId = modelId; model.Genre = genre; yield return model; } } } public IEnumerable<Models.RatingSummary> LoadRatings() { var dict = new Dictionary<string, Models.RatingSummary>(); foreach (var line in ReadLines("ratings.csv")) { var fields = Data.CsvParser.Instance.ParseLine(line); if (fields.Count < 4) continue; var item = new Models.Rating(); int num; if (!int.TryParse(fields[0], out num)) continue; item.UserId = num; if (!int.TryParse(fields[1], out num)) continue; item.MovieId = num; float num2; if (!float.TryParse(fields[2], out num2)) continue; item.Value = num2; item.Created = Data.DateTimeUtils.ParseFromJava(fields[3], 1000); var dictId = string.Format("{0}-{1}", item.MovieId, item.Created.Year); if (!dict.ContainsKey(dictId)) dict[dictId] = new Models.RatingSummary(); var record = dict[dictId]; record.MovieId = item.MovieId; record.CreatedYear = item.Created.Year; record.Value += item.Value; record.Count++; } return dict.Values; } public IEnumerable<Models.Tag> LoadTags() { foreach (var line in ReadLines("tags.csv")) { var fields = Data.CsvParser.Instance.ParseLine(line); if (fields.Count < 4) continue; int num; if (!int.TryParse(fields[0], out num)) continue; var item = new Models.Tag(); item.UserId = num; if (!int.TryParse(fields[1], out num)) continue; item.MovieId = num; item.Value = fields[2]; item.Created = Data.DateTimeUtils.ParseFromJava(fields[3], 1000); yield return item; } } IEnumerable<string> ReadLines(string fileName) { return File.ReadLines(DirPath + Path.DirectorySeparatorChar + fileName); } } }
kingcean/DiscoverHollywood
DiscoverHollywood/Import/MovieLens.cs
C#
apache-2.0
6,391
"""Base class for IKEA TRADFRI.""" from __future__ import annotations from collections.abc import Callable from functools import wraps import logging from typing import Any from pytradfri.command import Command from pytradfri.device import Device from pytradfri.device.air_purifier import AirPurifier from pytradfri.device.air_purifier_control import AirPurifierControl from pytradfri.device.blind import Blind from pytradfri.device.blind_control import BlindControl from pytradfri.device.light import Light from pytradfri.device.light_control import LightControl from pytradfri.device.signal_repeater_control import SignalRepeaterControl from pytradfri.device.socket import Socket from pytradfri.device.socket_control import SocketControl from pytradfri.error import PytradfriError from homeassistant.core import callback from homeassistant.helpers.entity import DeviceInfo, Entity from .const import DOMAIN _LOGGER = logging.getLogger(__name__) def handle_error( func: Callable[[Command | list[Command]], Any] ) -> Callable[[str], Any]: """Handle tradfri api call error.""" @wraps(func) async def wrapper(command: Command | list[Command]) -> None: """Decorate api call.""" try: await func(command) except PytradfriError as err: _LOGGER.error("Unable to execute command %s: %s", command, err) return wrapper class TradfriBaseClass(Entity): """Base class for IKEA TRADFRI. All devices and groups should ultimately inherit from this class. """ _attr_should_poll = False def __init__( self, device: Device, api: Callable[[Command | list[Command]], Any], gateway_id: str, ) -> None: """Initialize a device.""" self._api = handle_error(api) self._device: Device = device self._device_control: BlindControl | LightControl | SocketControl | SignalRepeaterControl | AirPurifierControl | None = ( None ) self._device_data: Socket | Light | Blind | AirPurifier | None = None self._gateway_id = gateway_id self._refresh(device) @callback def _async_start_observe(self, exc: Exception | None = None) -> None: """Start observation of device.""" if exc: self.async_write_ha_state() _LOGGER.warning("Observation failed for %s", self._attr_name, exc_info=exc) try: cmd = self._device.observe( callback=self._observe_update, err_callback=self._async_start_observe, duration=0, ) self.hass.async_create_task(self._api(cmd)) except PytradfriError as err: _LOGGER.warning("Observation failed, trying again", exc_info=err) self._async_start_observe() async def async_added_to_hass(self) -> None: """Start thread when added to hass.""" self._async_start_observe() @callback def _observe_update(self, device: Device) -> None: """Receive new state data for this device.""" self._refresh(device) self.async_write_ha_state() def _refresh(self, device: Device) -> None: """Refresh the device data.""" self._device = device self._attr_name = device.name class TradfriBaseDevice(TradfriBaseClass): """Base class for a TRADFRI device. All devices should inherit from this class. """ @property def device_info(self) -> DeviceInfo: """Return the device info.""" info = self._device.device_info return DeviceInfo( identifiers={(DOMAIN, self._device.id)}, manufacturer=info.manufacturer, model=info.model_number, name=self._attr_name, sw_version=info.firmware_version, via_device=(DOMAIN, self._gateway_id), ) def _refresh(self, device: Device) -> None: """Refresh the device data.""" super()._refresh(device) self._attr_available = device.reachable
aronsky/home-assistant
homeassistant/components/tradfri/base_class.py
Python
apache-2.0
4,045
<!doctype html> <html class="default no-js"> <head> <meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>LogCDF | stdlib</title> <meta name="description" content="stdlib is a standard library for JavaScript and Node.js, with an emphasis on numerical and scientific computing."> <meta name="author" content="stdlib"> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent"> <!-- Icons --> <link rel="apple-touch-icon" sizes="180x180" href="../apple-touch-icon.png"> <link rel="icon" type="image/png" sizes="32x32" href="../favicon-32x32.png"> <link rel="icon" type="image/png" sizes="16x16" href="../favicon-16x16.png"> <link rel="manifest" href="../manifest.json"> <link rel="mask-icon" href="../safari-pinned-tab.svg" color="#5bbad5"> <meta name="theme-color" content="#ffffff"> <!-- Facebook Open Graph --> <meta property="og:type" content="website"> <meta property="og:site_name" content="stdlib"> <meta property="og:url" content="https://stdlib.io/"> <meta property="og:title" content="A standard library for JavaScript and Node.js."> <meta property="og:description" content="stdlib is a standard library for JavaScript and Node.js, with an emphasis on numerical and scientific computing."> <meta property="og:locale" content="en_US"> <meta property="og:image" content=""> <!-- Twitter --> <meta name="twitter:card" content="A standard library for JavaScript and Node.js."> <meta name="twitter:site" content="@stdlibjs"> <meta name="twitter:url" content="https://stdlib.io/"> <meta name="twitter:title" content="stdlib"> <meta name="twitter:description" content="stdlib is a standard library for JavaScript and Node.js, with an emphasis on numerical and scientific computing."> <meta name="twitter:image" content=""> <link rel="stylesheet" href="../assets/css/main.css"> <link rel="stylesheet" href="../assets/css/theme.css"> </head> <body> <header> <div class="tsd-page-toolbar"> <div class="container"> <div class="table-wrap"> <div class="table-cell" id="tsd-search" data-index="../assets/js/search.js" data-base=".."> <div class="field"> <label for="tsd-search-field" class="tsd-widget search no-caption">Search</label> <input id="tsd-search-field" type="text" /> </div> <ul class="results"> <li class="state loading">Preparing search index...</li> <li class="state failure">The search index is not available</li> </ul> <a href="../index.html" class="title"><img src="../logo_white.svg" alt="stdlib"></a> </div> <div class="table-cell" id="tsd-widgets"> <div id="tsd-filter"> <a href="#" class="tsd-widget options no-caption" data-toggle="options">Options</a> <div class="tsd-filter-group"> <div class="tsd-select" id="tsd-filter-visibility"> <span class="tsd-select-label">All</span> <ul class="tsd-select-list"> <li data-value="public">Public</li> <li data-value="protected">Public/Protected</li> <li data-value="private" class="selected">All</li> </ul> </div> <input type="checkbox" id="tsd-filter-inherited" checked /> <label class="tsd-widget" for="tsd-filter-inherited">Inherited</label> <input type="checkbox" id="tsd-filter-only-exported" /> <label class="tsd-widget" for="tsd-filter-only-exported">Only exported</label> </div> </div> <a href="#" class="tsd-widget menu no-caption" data-toggle="menu">Menu</a> </div> </div> </div> </div> <div class="tsd-page-title"> <div class="container"> <ul class="tsd-breadcrumb"> <li> <a href="../globals.html">Globals</a> </li> <li> <a href="../modules/_stats_base_dists_levy_logcdf_docs_types_index_d_.html">&quot;stats/base/dists/levy/logcdf/docs/types/index.d&quot;</a> </li> <li> <a href="_stats_base_dists_levy_logcdf_docs_types_index_d_.logcdf.html">LogCDF</a> </li> </ul> <h1>Interface LogCDF</h1> </div> </div> </header> <div class="container container-main"> <div class="row"> <div class="col-8 col-content"> <section class="tsd-panel tsd-comment"> <div class="tsd-comment tsd-typography"> <div class="lead"> <p>Interface for the natural logarithm of the cumulative distribution function (CDF) of a Lévy distribution.</p> </div> </div> </section> <section class="tsd-panel tsd-hierarchy"> <h3>Hierarchy</h3> <ul class="tsd-hierarchy"> <li> <span class="target">LogCDF</span> </li> </ul> </section> <section class="tsd-panel"> <h3 class="tsd-before-signature">Callable</h3> <ul class="tsd-signatures tsd-kind-interface tsd-parent-kind-external-module tsd-is-not-exported"> <li class="tsd-signature tsd-kind-icon">__call<span class="tsd-signature-symbol">(</span>x<span class="tsd-signature-symbol">: </span><span class="tsd-signature-type">number</span>, mu<span class="tsd-signature-symbol">: </span><span class="tsd-signature-type">number</span>, c<span class="tsd-signature-symbol">: </span><span class="tsd-signature-type">number</span><span class="tsd-signature-symbol">)</span><span class="tsd-signature-symbol">: </span><span class="tsd-signature-type">number</span></li> </ul> <ul class="tsd-descriptions"> <li class="tsd-description"> <aside class="tsd-sources"> <ul> <li>Defined in <a href="https://github.com/stdlib-js/stdlib/blob/61b1a8a068/lib/node_modules/@stdlib/stats/base/dists/levy/logcdf/docs/types/index.d.ts#L32">lib/node_modules/@stdlib/stats/base/dists/levy/logcdf/docs/types/index.d.ts:32</a></li> </ul> </aside> <div class="tsd-comment tsd-typography"> <div class="lead"> <p>Evaluates the logarithm of the cumulative distribution function (CDF) for a Lévy distribution with location parameter <code>mu</code> and scale parameter <code>c</code> at value <code>x</code>.</p> </div> <a href="#notes" id="notes" style="color: inherit; text-decoration: none;"> <h2>Notes</h2> </a> <ul> <li>If provided <code>c &lt;= 0</code>, the function returns <code>NaN</code>.</li> </ul> </div> <h4 class="tsd-parameters-title">Parameters</h4> <ul class="tsd-parameters"> <li> <h5>x: <span class="tsd-signature-type">number</span></h5> <div class="tsd-comment tsd-typography"> <p>input value</p> </div> </li> <li> <h5>mu: <span class="tsd-signature-type">number</span></h5> <div class="tsd-comment tsd-typography"> <p>location parameter</p> </div> </li> <li> <h5>c: <span class="tsd-signature-type">number</span></h5> <div class="tsd-comment tsd-typography"> <p>scale parameter</p> </div> </li> </ul> <h4 class="tsd-returns-title">Returns <span class="tsd-signature-type">number</span> </h4> <p>evaluated logCDF</p> <h4 class="tsd-example-title">Example</h4> <div><pre><code class="language-javascript"><span class="hljs-keyword">var</span> y = logcdf( <span class="hljs-number">2.0</span>, <span class="hljs-number">0.0</span>, <span class="hljs-number">1.0</span> ); <span class="hljs-comment">// returns ~-0.735</span></code></pre> </div> <h4 class="tsd-example-title">Example</h4> <div><pre><code class="language-javascript"><span class="hljs-keyword">var</span> y = logcdf( <span class="hljs-number">12.0</span>, <span class="hljs-number">10.0</span>, <span class="hljs-number">3.0</span> ); <span class="hljs-comment">// returns ~-1.51</span></code></pre> </div> <h4 class="tsd-example-title">Example</h4> <div><pre><code class="language-javascript"><span class="hljs-keyword">var</span> y = logcdf( <span class="hljs-number">9.0</span>, <span class="hljs-number">10.0</span>, <span class="hljs-number">3.0</span> ); <span class="hljs-comment">// returns -Infinity</span></code></pre> </div> <h4 class="tsd-example-title">Example</h4> <div><pre><code class="language-javascript"><span class="hljs-keyword">var</span> y = logcdf( <span class="hljs-literal">NaN</span>, <span class="hljs-number">0.0</span>, <span class="hljs-number">1.0</span> ); <span class="hljs-comment">// returns NaN</span></code></pre> </div> <h4 class="tsd-example-title">Example</h4> <div><pre><code class="language-javascript"><span class="hljs-keyword">var</span> y = logcdf( <span class="hljs-number">2</span>, <span class="hljs-literal">NaN</span>, <span class="hljs-number">1.0</span> ); <span class="hljs-comment">// returns NaN</span></code></pre> </div> <h4 class="tsd-example-title">Example</h4> <div><pre><code class="language-javascript"><span class="hljs-keyword">var</span> y = logcdf( <span class="hljs-number">2.0</span>, <span class="hljs-number">0.0</span>, <span class="hljs-literal">NaN</span> ); <span class="hljs-comment">// returns NaN</span></code></pre> </div> <h4 class="tsd-example-title">Example</h4> <div><pre><code class="language-javascript"><span class="hljs-comment">// Negative scale parameter:</span> <span class="hljs-keyword">var</span> y = logcdf( <span class="hljs-number">2.0</span>, <span class="hljs-number">0.0</span>, <span class="hljs-number">-1.0</span> ); <span class="hljs-comment">// returns NaN</span></code></pre> </div> </li> </ul> </section> <section class="tsd-panel-group tsd-index-group"> <h2>Index</h2> <section class="tsd-panel tsd-index-panel"> <div class="tsd-index-content"> <section class="tsd-index-section tsd-is-not-exported"> <h3>Methods</h3> <ul class="tsd-index-list"> <li class="tsd-kind-method tsd-parent-kind-interface tsd-is-not-exported"><a href="_stats_base_dists_levy_logcdf_docs_types_index_d_.logcdf.html#factory" class="tsd-kind-icon">factory</a></li> </ul> </section> </div> </section> </section> <section class="tsd-panel-group tsd-member-group tsd-is-not-exported"> <h2>Methods</h2> <section class="tsd-panel tsd-member tsd-kind-method tsd-parent-kind-interface tsd-is-not-exported"> <a name="factory" class="tsd-anchor"></a> <h3>factory</h3> <ul class="tsd-signatures tsd-kind-method tsd-parent-kind-interface tsd-is-not-exported"> <li class="tsd-signature tsd-kind-icon">factory<span class="tsd-signature-symbol">(</span>mu<span class="tsd-signature-symbol">: </span><span class="tsd-signature-type">number</span>, c<span class="tsd-signature-symbol">: </span><span class="tsd-signature-type">number</span><span class="tsd-signature-symbol">)</span><span class="tsd-signature-symbol">: </span><a href="../modules/_stats_base_dists_levy_logcdf_docs_types_index_d_.html#unary" class="tsd-signature-type">Unary</a></li> </ul> <ul class="tsd-descriptions"> <li class="tsd-description"> <aside class="tsd-sources"> <ul> <li>Defined in <a href="https://github.com/stdlib-js/stdlib/blob/61b1a8a068/lib/node_modules/@stdlib/stats/base/dists/levy/logcdf/docs/types/index.d.ts#L92">lib/node_modules/@stdlib/stats/base/dists/levy/logcdf/docs/types/index.d.ts:92</a></li> </ul> </aside> <div class="tsd-comment tsd-typography"> <div class="lead"> <p>Returns a function for evaluating the logarithm of the cumulative distribution function (CDF) for a Lévy distribution with location parameter <code>mu</code> and scale parameter <code>c</code>.</p> </div> </div> <h4 class="tsd-parameters-title">Parameters</h4> <ul class="tsd-parameters"> <li> <h5>mu: <span class="tsd-signature-type">number</span></h5> <div class="tsd-comment tsd-typography"> <p>location parameter</p> </div> </li> <li> <h5>c: <span class="tsd-signature-type">number</span></h5> <div class="tsd-comment tsd-typography"> <p>scale parameter</p> </div> </li> </ul> <h4 class="tsd-returns-title">Returns <a href="../modules/_stats_base_dists_levy_logcdf_docs_types_index_d_.html#unary" class="tsd-signature-type"> Unary </a> </h4> <p>logCDF</p> <h4 class="tsd-example-title">Example</h4> <div><pre><code class="language-javascript"><span class="hljs-keyword">var</span> mylogcdf = logcdf.factory( <span class="hljs-number">3.0</span>, <span class="hljs-number">1.5</span> ); <span class="hljs-keyword">var</span> y = mylogcdf( <span class="hljs-number">4.0</span> ); <span class="hljs-comment">// returns ~-1.511</span> y = mylogcdf( <span class="hljs-number">2.0</span> ); <span class="hljs-comment">// returns -Infinity</span></code></pre> </div> </li> </ul> </section> </section> </div> <div class="col-4 col-menu menu-sticky-wrap menu-highlight"> <nav class="tsd-navigation primary"> <ul> <li class="globals "> <a href="../globals.html"><em>Packages</em></a> </li> <li class="current tsd-kind-external-module"> <a href="../modules/_stats_base_dists_levy_logcdf_docs_types_index_d_.html">&quot;stats/base/dists/levy/logcdf/docs/types/index.d&quot;</a> </li> </ul> </nav> <nav class="tsd-navigation secondary menu-sticky"> <ul class="before-current"> </ul> <ul class="current"> <li class="current tsd-kind-interface tsd-parent-kind-external-module tsd-is-not-exported"> <a href="_stats_base_dists_levy_logcdf_docs_types_index_d_.logcdf.html" class="tsd-kind-icon">LogCDF</a> <ul> <li class=" tsd-kind-method tsd-parent-kind-interface tsd-is-not-exported"> <a href="_stats_base_dists_levy_logcdf_docs_types_index_d_.logcdf.html#factory" class="tsd-kind-icon">factory</a> </li> </ul> </li> </ul> <ul class="after-current"> <li class=" tsd-kind-type-alias tsd-parent-kind-external-module tsd-is-not-exported"> <a href="../modules/_stats_base_dists_levy_logcdf_docs_types_index_d_.html#unary" class="tsd-kind-icon">Unary</a> </li> <li class=" tsd-kind-variable tsd-parent-kind-external-module tsd-is-not-exported"> <a href="../modules/_stats_base_dists_levy_logcdf_docs_types_index_d_.html#logcdf-1" class="tsd-kind-icon">logCDF</a> </li> </ul> </nav> </div> </div> </div> <footer> <div class="container"> <h2>Legend</h2> <div class="tsd-legend-group"> <ul class="tsd-legend"> <li class="tsd-kind-module"><span class="tsd-kind-icon">Module</span></li> <li class="tsd-kind-object-literal"><span class="tsd-kind-icon">Object literal</span></li> <li class="tsd-kind-variable"><span class="tsd-kind-icon">Variable</span></li> <li class="tsd-kind-function"><span class="tsd-kind-icon">Function</span></li> <li class="tsd-kind-function tsd-has-type-parameter"><span class="tsd-kind-icon">Function with type parameter</span></li> <li class="tsd-kind-index-signature"><span class="tsd-kind-icon">Index signature</span></li> <li class="tsd-kind-type-alias"><span class="tsd-kind-icon">Type alias</span></li> <li class="tsd-kind-type-alias tsd-has-type-parameter"><span class="tsd-kind-icon">Type alias with type parameter</span></li> </ul> <ul class="tsd-legend"> <li class="tsd-kind-enum"><span class="tsd-kind-icon">Enumeration</span></li> <li class="tsd-kind-enum-member"><span class="tsd-kind-icon">Enumeration member</span></li> <li class="tsd-kind-property tsd-parent-kind-enum"><span class="tsd-kind-icon">Property</span></li> <li class="tsd-kind-method tsd-parent-kind-enum"><span class="tsd-kind-icon">Method</span></li> </ul> <ul class="tsd-legend"> <li class="tsd-kind-interface"><span class="tsd-kind-icon">Interface</span></li> <li class="tsd-kind-interface tsd-has-type-parameter"><span class="tsd-kind-icon">Interface with type parameter</span></li> <li class="tsd-kind-constructor tsd-parent-kind-interface"><span class="tsd-kind-icon">Constructor</span></li> <li class="tsd-kind-property tsd-parent-kind-interface"><span class="tsd-kind-icon">Property</span></li> <li class="tsd-kind-method tsd-parent-kind-interface"><span class="tsd-kind-icon">Method</span></li> <li class="tsd-kind-index-signature tsd-parent-kind-interface"><span class="tsd-kind-icon">Index signature</span></li> </ul> <ul class="tsd-legend"> <li class="tsd-kind-class"><span class="tsd-kind-icon">Class</span></li> <li class="tsd-kind-class tsd-has-type-parameter"><span class="tsd-kind-icon">Class with type parameter</span></li> <li class="tsd-kind-constructor tsd-parent-kind-class"><span class="tsd-kind-icon">Constructor</span></li> <li class="tsd-kind-property tsd-parent-kind-class"><span class="tsd-kind-icon">Property</span></li> <li class="tsd-kind-method tsd-parent-kind-class"><span class="tsd-kind-icon">Method</span></li> <li class="tsd-kind-accessor tsd-parent-kind-class"><span class="tsd-kind-icon">Accessor</span></li> <li class="tsd-kind-index-signature tsd-parent-kind-class"><span class="tsd-kind-icon">Index signature</span></li> </ul> <ul class="tsd-legend"> <li class="tsd-kind-constructor tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited constructor</span></li> <li class="tsd-kind-property tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited property</span></li> <li class="tsd-kind-method tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited method</span></li> <li class="tsd-kind-accessor tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited accessor</span></li> </ul> <ul class="tsd-legend"> <li class="tsd-kind-property tsd-parent-kind-class tsd-is-protected"><span class="tsd-kind-icon">Protected property</span></li> <li class="tsd-kind-method tsd-parent-kind-class tsd-is-protected"><span class="tsd-kind-icon">Protected method</span></li> <li class="tsd-kind-accessor tsd-parent-kind-class tsd-is-protected"><span class="tsd-kind-icon">Protected accessor</span></li> </ul> <ul class="tsd-legend"> <li class="tsd-kind-property tsd-parent-kind-class tsd-is-private"><span class="tsd-kind-icon">Private property</span></li> <li class="tsd-kind-method tsd-parent-kind-class tsd-is-private"><span class="tsd-kind-icon">Private method</span></li> <li class="tsd-kind-accessor tsd-parent-kind-class tsd-is-private"><span class="tsd-kind-icon">Private accessor</span></li> </ul> <ul class="tsd-legend"> <li class="tsd-kind-property tsd-parent-kind-class tsd-is-static"><span class="tsd-kind-icon">Static property</span></li> <li class="tsd-kind-call-signature tsd-parent-kind-class tsd-is-static"><span class="tsd-kind-icon">Static method</span></li> </ul> </div> </div> <div class="bottom-nav center border-top"> <a href="https://www.patreon.com/athan">Donate</a> / <a href="/docs/api/">Docs</a> / <a href="https://gitter.im/stdlib-js/stdlib">Chat</a> / <a href="https://twitter.com/stdlibjs">Twitter</a> / <a href="https://github.com/stdlib-js/stdlib">Contribute</a> </div> </footer> <div class="overlay"></div> <script src="../assets/js/main.js"></script> <script src="../assets/js/theme.js"></script> <script>if (location.protocol == 'file:') document.write('<script src="../assets/js/search.js"><' + '/script>');</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-105890493-1', 'auto'); ga('send', 'pageview'); </script> </body> </html>
stdlib-js/www
public/docs/ts/latest/interfaces/_stats_base_dists_levy_logcdf_docs_types_index_d_.logcdf.html
HTML
apache-2.0
20,218
var _ = require("underscore"), Util = require("../lib/util.js"), rethinkdb = require("rethinkdb"); var defaultOptions = { host : "localhost", port : 28015, dbName : "test", tableName : "user" } var initializeOptions = function( options ){ if(!_.isNull(options) && _.isObject(options)){ return _.extend(defaultOptions, options); } return defaultOptions; } // Constructor var User = function( options, callback ){ var self = this; var optionals = initializeOptions( options ); // TODO - implement connection etc in user-db.js rethinkdb.connect( {host : optionals.host, port : optionals.port}, function(err, conn) { if (err){ throw new Error("Unable to connect to database. " + err.stack()); } self.connection = conn; self.dbName = optionals.dbName; self.tableName = optionals.tableName; Util.executeSafely(callback); }); }; User.prototype.registerUser = function( user, callBack, options ){ Util.checkIsObject( user, "Cannot save an empty user." ); Util.checkIsFunction( callBack, "Must supply a valid callback."); var optionals = options == undefined ? {upsert: true, return_vals: true} : options; Util.setId( user ); rethinkdb .db(this.dbName) .table(this.tableName) .insert( user, optionals ) .run(this.connection, function(err, result){ callBack(err, result); }); }; User.prototype.updateUser = function( id, changes, callBack, options ){ Util.checkNotEmpty( id, "Cannot update a user without a valid userId." ); Util.checkIsObject( changes, "Cannot update an empty user." ); Util.checkIsFunction( callBack, "Must supply a valid callback." ); var optionals = options != null ? options : {return_vals : true}; rethinkdb .db(this.dbName) .table(this.tableName) .get( id ) .update( changes, optionals ) .run(this.connection, function(err, result){ callBack(err, result); }); }; User.prototype.getUserById = function( id, callBack ){ Util.checkNotEmpty( id, "Cannot retrieve a user without a valid userId."); Util.checkIsFunction( callBack, "Must supply a valid callback."); rethinkdb .db(this.dbName) .table(this.tableName) .get( id ) .run(this.connection, function(err, result){ callBack(err, result); }); }; User.prototype.deleteUser = function( id, callBack ){ Util.checkNotEmpty( id, "Cannot delete a user without a valid userId."); Util.checkIsFunction( callBack, "Must supply a valid callback."); rethinkdb .db(this.dbName) .table(this.tableName) .get( id ) .delete({durability: 'hard'}) .run(this.connection, function(err, result){ callBack(err, result); }); }; module.exports.createInstance = function( options, callback ){ return new User( options, callback ); };
aaroneast1/user-service
lib/user-db.js
JavaScript
apache-2.0
2,710
# ReversiGame Simple android game called reversi,reversi is strategy board game for two players, played on an 8×8 unchecked board. Players take turns placing disks on the board with their assigned color facing up. During a play, any disks of the opponent's color that are in a straight line and bounded by the disk just placed and another disk of the current player's color are turned over to the current player's color.The object of the game is to have the majority of disks turned to display your color when the last playable empty square is filled.
moamen-mohamed/ReversiGame
README.md
Markdown
apache-2.0
553
/* * Copyright 2005-2017 ECMWF. * * This software is licensed under the terms of the Apache Licence Version 2.0 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. * * In applying this licence, ECMWF does not waive the privileges and immunities granted to it by * virtue of its status as an intergovernmental organisation nor does it submit to any jurisdiction. */ #include "grib_api_internal.h" /* This is used by make_class.pl START_CLASS_DEF CLASS = accessor SUPER = grib_accessor_class_long IMPLEMENTS = unpack_long;pack_long IMPLEMENTS = init;dump MEMBERS = const char* start_step MEMBERS = const char* unit MEMBERS = const char* year MEMBERS = const char* month MEMBERS = const char* day MEMBERS = const char* hour MEMBERS = const char* minute MEMBERS = const char* second MEMBERS = const char* year_of_end_of_interval MEMBERS = const char* month_of_end_of_interval MEMBERS = const char* day_of_end_of_interval MEMBERS = const char* hour_of_end_of_interval MEMBERS = const char* minute_of_end_of_interval MEMBERS = const char* second_of_end_of_interval MEMBERS = const char* coded_unit MEMBERS = const char* coded_time_range MEMBERS = const char* typeOfTimeIncrement MEMBERS = const char* numberOfTimeRange END_CLASS_DEF */ /* START_CLASS_IMP */ /* Don't edit anything between START_CLASS_IMP and END_CLASS_IMP Instead edit values between START_CLASS_DEF and END_CLASS_DEF or edit "accessor.class" and rerun ./make_class.pl */ static int pack_long(grib_accessor*, const long* val,size_t *len); static int unpack_long(grib_accessor*, long* val,size_t *len); static void dump(grib_accessor*, grib_dumper*); static void init(grib_accessor*,const long, grib_arguments* ); static void init_class(grib_accessor_class*); typedef struct grib_accessor_g2end_step { grib_accessor att; /* Members defined in gen */ /* Members defined in long */ /* Members defined in g2end_step */ const char* start_step; const char* unit; const char* year; const char* month; const char* day; const char* hour; const char* minute; const char* second; const char* year_of_end_of_interval; const char* month_of_end_of_interval; const char* day_of_end_of_interval; const char* hour_of_end_of_interval; const char* minute_of_end_of_interval; const char* second_of_end_of_interval; const char* coded_unit; const char* coded_time_range; const char* typeOfTimeIncrement; const char* numberOfTimeRange; } grib_accessor_g2end_step; extern grib_accessor_class* grib_accessor_class_long; static grib_accessor_class _grib_accessor_class_g2end_step = { &grib_accessor_class_long, /* super */ "g2end_step", /* name */ sizeof(grib_accessor_g2end_step), /* size */ 0, /* inited */ &init_class, /* init_class */ &init, /* init */ 0, /* post_init */ 0, /* free mem */ &dump, /* describes himself */ 0, /* get length of section */ 0, /* get length of string */ 0, /* get number of values */ 0, /* get number of bytes */ 0, /* get offset to bytes */ 0, /* get native type */ 0, /* get sub_section */ 0, /* grib_pack procedures long */ 0, /* grib_pack procedures long */ &pack_long, /* grib_pack procedures long */ &unpack_long, /* grib_unpack procedures long */ 0, /* grib_pack procedures double */ 0, /* grib_unpack procedures double */ 0, /* grib_pack procedures string */ 0, /* grib_unpack procedures string */ 0, /* grib_pack procedures bytes */ 0, /* grib_unpack procedures bytes */ 0, /* pack_expression */ 0, /* notify_change */ 0, /* update_size */ 0, /* preferred_size */ 0, /* resize */ 0, /* nearest_smaller_value */ 0, /* next accessor */ 0, /* compare vs. another accessor */ 0, /* unpack only ith value */ 0, /* unpack a subarray */ 0, /* clear */ }; grib_accessor_class* grib_accessor_class_g2end_step = &_grib_accessor_class_g2end_step; static void init_class(grib_accessor_class* c) { c->next_offset = (*(c->super))->next_offset; c->string_length = (*(c->super))->string_length; c->value_count = (*(c->super))->value_count; c->byte_count = (*(c->super))->byte_count; c->byte_offset = (*(c->super))->byte_offset; c->get_native_type = (*(c->super))->get_native_type; c->sub_section = (*(c->super))->sub_section; c->pack_missing = (*(c->super))->pack_missing; c->is_missing = (*(c->super))->is_missing; c->pack_double = (*(c->super))->pack_double; c->unpack_double = (*(c->super))->unpack_double; c->pack_string = (*(c->super))->pack_string; c->unpack_string = (*(c->super))->unpack_string; c->pack_bytes = (*(c->super))->pack_bytes; c->unpack_bytes = (*(c->super))->unpack_bytes; c->pack_expression = (*(c->super))->pack_expression; c->notify_change = (*(c->super))->notify_change; c->update_size = (*(c->super))->update_size; c->preferred_size = (*(c->super))->preferred_size; c->resize = (*(c->super))->resize; c->nearest_smaller_value = (*(c->super))->nearest_smaller_value; c->next = (*(c->super))->next; c->compare = (*(c->super))->compare; c->unpack_double_element = (*(c->super))->unpack_double_element; c->unpack_double_subarray = (*(c->super))->unpack_double_subarray; c->clear = (*(c->super))->clear; } /* END_CLASS_IMP */ static void init(grib_accessor* a,const long l, grib_arguments* c) { grib_accessor_g2end_step* self = (grib_accessor_g2end_step*)a; int n = 0; self->start_step = grib_arguments_get_name(a->parent->h,c,n++); self->unit = grib_arguments_get_name(a->parent->h,c,n++); self->year = grib_arguments_get_name(a->parent->h,c,n++); self->month = grib_arguments_get_name(a->parent->h,c,n++); self->day = grib_arguments_get_name(a->parent->h,c,n++); self->hour = grib_arguments_get_name(a->parent->h,c,n++); self->minute = grib_arguments_get_name(a->parent->h,c,n++); self->second = grib_arguments_get_name(a->parent->h,c,n++); self->year_of_end_of_interval = grib_arguments_get_name(a->parent->h,c,n++); self->month_of_end_of_interval = grib_arguments_get_name(a->parent->h,c,n++); self->day_of_end_of_interval = grib_arguments_get_name(a->parent->h,c,n++); self->hour_of_end_of_interval = grib_arguments_get_name(a->parent->h,c,n++); self->minute_of_end_of_interval = grib_arguments_get_name(a->parent->h,c,n++); self->second_of_end_of_interval = grib_arguments_get_name(a->parent->h,c,n++); self->coded_unit = grib_arguments_get_name(a->parent->h,c,n++); self->coded_time_range = grib_arguments_get_name(a->parent->h,c,n++); self->typeOfTimeIncrement = grib_arguments_get_name(a->parent->h,c,n++); self->numberOfTimeRange = grib_arguments_get_name(a->parent->h,c,n++); } static void dump(grib_accessor* a, grib_dumper* dumper) { grib_dump_double(dumper,a,NULL); } static int u2s2[] = { 60, /* (0) minutes */ 3600, /* (1) hour */ 86400, /* (2) day */ 2592000, /* (3) month */ -1, /* (4) */ -1, /* (5) */ -1, /* (6) */ -1, /* (7) */ -1, /* (8) */ -1, /* (9) */ 10800, /* (10) 3 hours */ 21600, /* (11) 6 hours */ 43200, /* (12) 12 hours */ 1 /* (13) seconds */ }; static int u2s[] = { 60, /* (0) minutes */ 3600, /* (1) hour */ 86400, /* (2) day */ 2592000, /* (3) month */ -1, /* (4) */ -1, /* (5) */ -1, /* (6) */ -1, /* (7) */ -1, /* (8) */ -1, /* (9) */ 10800, /* (10) 3 hours */ 21600, /* (11) 6 hours */ 43200, /* (12) 12 hours */ 1, /* (13) seconds */ 900, /* (14) 15 minutes */ 1800 /* (15) 30 minutes */ }; /* See GRIB-488 */ static int is_special_expver(grib_handle* h) { int ret = 0; char strExpVer[50]={0,}; size_t slen=50; ret = grib_get_string(h, "experimentVersionNumber", strExpVer, &slen); if (ret == GRIB_SUCCESS && !strcmp(strExpVer, "1605")) { return 1; /* Special case of expVer 1605! */ } return 0; } static int convert_time_range( grib_handle* h, long stepUnits, /* unit */ long indicatorOfUnitForTimeRange, /* coded_unit */ long* lengthOfTimeRange /* coded_time_range */ ) { Assert(lengthOfTimeRange != NULL); if (indicatorOfUnitForTimeRange != stepUnits) { long u2sf_step_unit; long coded_time_range_sec = (*lengthOfTimeRange)*u2s2[indicatorOfUnitForTimeRange]; if (coded_time_range_sec < 0) { long u2sf; int factor = 60; if (u2s2[indicatorOfUnitForTimeRange] % factor) return GRIB_DECODING_ERROR; if (u2s[stepUnits] % factor) return GRIB_DECODING_ERROR; u2sf = u2s2[indicatorOfUnitForTimeRange]/factor; coded_time_range_sec = (*lengthOfTimeRange)*u2sf; u2sf_step_unit = u2s[stepUnits]/factor; } else { u2sf_step_unit = u2s[stepUnits]; } if (coded_time_range_sec % u2sf_step_unit != 0) { grib_context_log(h->context,GRIB_LOG_ERROR,"unable to convert endStep in stepUnits"); return GRIB_WRONG_STEP_UNIT; } *lengthOfTimeRange = coded_time_range_sec / u2sf_step_unit; } return GRIB_SUCCESS; } static int unpack_one_time_range(grib_accessor* a, long* val, size_t *len) { grib_accessor_g2end_step* self = (grib_accessor_g2end_step*)a; int err = 0; long start_step; long unit; long coded_unit; long coded_time_range, typeOfTimeIncrement; int add_time_range = 1; /* whether we add lengthOfTimeRange */ grib_handle* h = a->parent->h; if((err = grib_get_long_internal(h,self->start_step,&start_step))) return err; if((err = grib_get_long_internal(h,self->unit,&unit))) return err; if((err = grib_get_long_internal(h,self->coded_unit,&coded_unit))) return err; if((err = grib_get_long_internal(h,self->coded_time_range, &coded_time_range))) return err; if((err = grib_get_long_internal(h,self->typeOfTimeIncrement, &typeOfTimeIncrement))) return err; err = convert_time_range(h, unit, coded_unit, &coded_time_range); if (err != GRIB_SUCCESS) return err; if (typeOfTimeIncrement == 1) { /* See GRIB-488 */ /* Note: For this case, lengthOfTimeRange is not related to step and should not be used to calculate step */ add_time_range = 0; if (is_special_expver(h)) { add_time_range = 1; } } if (add_time_range) { *val = start_step + coded_time_range; } else { *val = start_step; } return GRIB_SUCCESS; } #define MAX_NUM_TIME_RANGES 16 /* maximum number of time range specifications */ static int unpack_multiple_time_ranges(grib_accessor* a, long* val, size_t *len) { grib_accessor_g2end_step* self = (grib_accessor_g2end_step*)a; int i = 0, err = 0; grib_handle* h = a->parent->h; long numberOfTimeRange = 0, unit = 0, start_step = 0; size_t count = 0; long arr_typeOfTimeIncrement[MAX_NUM_TIME_RANGES] = {0,}; long arr_coded_unit[MAX_NUM_TIME_RANGES] = {0,}; long arr_coded_time_range[MAX_NUM_TIME_RANGES] = {0,}; if((err = grib_get_long_internal(h,self->start_step,&start_step))) return err; if((err = grib_get_long_internal(h,self->unit,&unit))) return err; if((err = grib_get_long_internal(h,self->numberOfTimeRange, &numberOfTimeRange))) return err; if (numberOfTimeRange > MAX_NUM_TIME_RANGES) { grib_context_log(h->context, GRIB_LOG_ERROR, "Too many time range specifications!"); return GRIB_DECODING_ERROR; } count = numberOfTimeRange; /* Get the arrays for the N time ranges */ if ((err = grib_get_long_array(h, self->typeOfTimeIncrement, arr_typeOfTimeIncrement, &count))) return err; if ((err = grib_get_long_array(h, self->coded_unit, arr_coded_unit, &count))) return err; if ((err = grib_get_long_array(h, self->coded_time_range, arr_coded_time_range, &count))) return err; /* Look in the array of typeOfTimeIncrements for first entry whose typeOfTimeIncrement == 2 */ for(i=0; i<count; i++) { if (arr_typeOfTimeIncrement[i] == 2) { /* Found the required time range. Get the other two keys from it */ long the_coded_unit = arr_coded_unit[i]; long the_coded_time_range = arr_coded_time_range[i]; err = convert_time_range(h, unit, the_coded_unit, &the_coded_time_range); if (err != GRIB_SUCCESS) return err; *val = start_step + the_coded_time_range; return GRIB_SUCCESS; } } grib_context_log(h->context, GRIB_LOG_ERROR, "Cannot calculate endStep. No time range specification with typeOfTimeIncrement = 2"); return GRIB_DECODING_ERROR; } static int unpack_long(grib_accessor* a, long* val, size_t *len) { grib_accessor_g2end_step* self = (grib_accessor_g2end_step*)a; int err = 0; long start_step; long numberOfTimeRange; grib_handle* h=a->parent->h; if((err = grib_get_long_internal(h,self->start_step,&start_step))) return err; /* point in time */ if (self->year == NULL) { *val=start_step; return 0; } Assert(self->numberOfTimeRange); if((err = grib_get_long_internal(h,self->numberOfTimeRange, &numberOfTimeRange))) return err; Assert(numberOfTimeRange == 1 || numberOfTimeRange == 2); if (numberOfTimeRange == 1) { return unpack_one_time_range(a,val,len); } else { return unpack_multiple_time_ranges(a,val,len); } } #if 0 static int unpack_long(grib_accessor* a, long* val, size_t *len) { grib_accessor_g2end_step* self = (grib_accessor_g2end_step*)a; int err = 0; long start_step; long unit; long coded_unit; long coded_time_range, typeOfTimeIncrement, numberOfTimeRange; long coded_time_range_sec=0; int factor; long u2sf,u2sf_step_unit; int add_time_range = 1; /* whether we add lengthOfTimeRange */ grib_handle* h=a->parent->h; if((err = grib_get_long_internal(h,self->start_step,&start_step))) return err; /*point in time */ if (self->year == NULL) { *val=start_step; return 0; } if((err = grib_get_long_internal(h,self->unit,&unit))) return err; if((err = grib_get_long_internal(h,self->coded_unit,&coded_unit))) return err; if((err = grib_get_long_internal(h,self->coded_time_range, &coded_time_range))) return err; if((err = grib_get_long_internal(h,self->typeOfTimeIncrement, &typeOfTimeIncrement))) return err; if((err = grib_get_long_internal(h,self->numberOfTimeRange, &numberOfTimeRange))) return err; Assert(numberOfTimeRange == 1 || numberOfTimeRange == 2); err = convert_time_range(h, unit, coded_unit, &coded_time_range); if (err != GRIB_SUCCESS) return err; #if 0 if (coded_unit!=unit) { coded_time_range_sec=coded_time_range*u2s2[coded_unit]; if (coded_time_range_sec<0) { factor=60; if (u2s2[coded_unit] % factor) return GRIB_DECODING_ERROR; if (u2s[unit] % factor) return GRIB_DECODING_ERROR; u2sf=u2s2[coded_unit]/factor; coded_time_range_sec=coded_time_range*u2sf; u2sf_step_unit=u2s[unit]/factor; } else { u2sf_step_unit=u2s[unit]; } if (coded_time_range_sec % u2sf_step_unit!=0) { grib_context_log(h->context,GRIB_LOG_ERROR,"unable to convert endStep in stepUnits"); return GRIB_WRONG_STEP_UNIT; } coded_time_range = coded_time_range_sec / u2sf_step_unit; } #endif if (typeOfTimeIncrement == 1) { /* See GRIB-488 */ /* Note: For this case, lengthOfTimeRange is not related to step and should not be used to calculate step */ add_time_range = 0; if (is_special_expver(h)) { add_time_range = 1; } } if (add_time_range) { *val = start_step + coded_time_range; } else { *val = start_step; } return GRIB_SUCCESS; } #endif static int pack_long(grib_accessor* a, const long* val, size_t *len) { grib_accessor_g2end_step* self = (grib_accessor_g2end_step*)a; grib_handle* h=a->parent->h; int err = 0; long year; long month; long day; long hour; long minute; long second; long start_step; long unit,coded_unit; long year_of_end_of_interval; long month_of_end_of_interval; long day_of_end_of_interval; long hour_of_end_of_interval; long minute_of_end_of_interval = 0; long second_of_end_of_interval = 0; long coded_time_range,time_range, typeOfTimeIncrement; double dend, dstep; /*point in time */ if (self->year == NULL) { err = grib_set_long_internal(h,self->start_step,*val); return err; } if((err = grib_get_long_internal(h,self->coded_unit,&coded_unit))) return err; if((err = grib_get_long_internal(h,self->unit,&unit))) return err; if((err = grib_get_long_internal(h,self->year,&year))) return err; if((err = grib_get_long_internal(h,self->month,&month))) return err; if((err = grib_get_long_internal(h,self->day,&day))) return err; if((err = grib_get_long_internal(h,self->hour,&hour))) return err; if((err = grib_get_long_internal(h,self->minute,&minute))) return err; if((err = grib_get_long_internal(h,self->second,&second))) return err; if((err = grib_get_long_internal(h,self->start_step,&start_step))) return err; if((err = grib_get_long_internal(h,self->typeOfTimeIncrement, &typeOfTimeIncrement))) return err; time_range = *val-start_step; if (time_range<0){ grib_context_log(h->context,GRIB_LOG_ERROR, "endStep < startStep (%ld < %ld)",*val,start_step); return GRIB_WRONG_STEP; } err=grib_datetime_to_julian(year,month,day,hour,minute,second,&dend); if (err!=GRIB_SUCCESS) return err; dstep=(((double)(*val))*u2s[unit])/u2s[2]; dend+=dstep; err=grib_julian_to_datetime(dend,&year_of_end_of_interval,&month_of_end_of_interval, &day_of_end_of_interval,&hour_of_end_of_interval, &minute_of_end_of_interval,&second_of_end_of_interval); if (err!=GRIB_SUCCESS) return err; if((err = grib_set_long_internal(a->parent->h,self->year_of_end_of_interval, year_of_end_of_interval))) return err; if((err = grib_set_long_internal(a->parent->h,self->month_of_end_of_interval, month_of_end_of_interval))) return err; if((err = grib_set_long_internal(a->parent->h,self->day_of_end_of_interval, day_of_end_of_interval))) return err; if((err = grib_set_long_internal(a->parent->h,self->hour_of_end_of_interval, hour_of_end_of_interval))) return err; if((err = grib_set_long_internal(a->parent->h,self->minute_of_end_of_interval, minute_of_end_of_interval))) return err; if((err = grib_set_long_internal(a->parent->h,self->second_of_end_of_interval, second_of_end_of_interval))) return err; if (time_range*u2s[unit]%u2s2[coded_unit]) { coded_unit=unit; if((err = grib_set_long_internal(a->parent->h,self->coded_unit, coded_unit))) return err; coded_time_range=time_range; } else coded_time_range=(time_range*u2s[unit])/u2s2[coded_unit]; if (typeOfTimeIncrement != 1) { /* 1 means "Successive times processed have same forecast time, start time of forecast is incremented" */ /* Note: For this case, length of timeRange is not related to step and so should NOT be used to calculate step */ if((err = grib_set_long_internal(a->parent->h,self->coded_time_range, coded_time_range))) return err; } return GRIB_SUCCESS; }
weathersource/grib_api
src/grib_accessor_class_g2end_step.c
C
apache-2.0
20,871
<!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_91) on Mon Jun 06 14:51:11 EDT 2016 --> <title>Cassandra.AsyncClient.describe_snitch_call (apache-cassandra API)</title> <meta name="date" content="2016-06-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="Cassandra.AsyncClient.describe_snitch_call (apache-cassandra API)"; } } catch(err) { } //--> var methods = {"i0":10,"i1":10}; var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],8:["t4","Concrete Methods"]}; var altColor = "altColor"; var rowColor = "rowColor"; var tableTab = "tableTab"; var activeTableTab = "activeTableTab"; </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/Cassandra.AsyncClient.describe_snitch_call.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../org/apache/cassandra/thrift/Cassandra.AsyncClient.describe_schema_versions_call.html" title="class in org.apache.cassandra.thrift"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../../org/apache/cassandra/thrift/Cassandra.AsyncClient.describe_splits_call.html" title="class in org.apache.cassandra.thrift"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/apache/cassandra/thrift/Cassandra.AsyncClient.describe_snitch_call.html" target="_top">Frames</a></li> <li><a href="Cassandra.AsyncClient.describe_snitch_call.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li><a href="#nested.classes.inherited.from.class.org.apache.thrift.async.TAsyncMethodCall">Nested</a>&nbsp;|&nbsp;</li> <li><a href="#fields.inherited.from.class.org.apache.thrift.async.TAsyncMethodCall">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">org.apache.cassandra.thrift</div> <h2 title="Class Cassandra.AsyncClient.describe_snitch_call" class="title">Class Cassandra.AsyncClient.describe_snitch_call</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>org.apache.thrift.async.TAsyncMethodCall</li> <li> <ul class="inheritance"> <li>org.apache.cassandra.thrift.Cassandra.AsyncClient.describe_snitch_call</li> </ul> </li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>Enclosing class:</dt> <dd><a href="../../../../org/apache/cassandra/thrift/Cassandra.AsyncClient.html" title="class in org.apache.cassandra.thrift">Cassandra.AsyncClient</a></dd> </dl> <hr> <br> <pre>public static class <span class="typeNameLabel">Cassandra.AsyncClient.describe_snitch_call</span> extends org.apache.thrift.async.TAsyncMethodCall</pre> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ======== NESTED CLASS SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="nested.class.summary"> <!-- --> </a> <h3>Nested Class Summary</h3> <ul class="blockList"> <li class="blockList"><a name="nested.classes.inherited.from.class.org.apache.thrift.async.TAsyncMethodCall"> <!-- --> </a> <h3>Nested classes/interfaces inherited from class&nbsp;org.apache.thrift.async.TAsyncMethodCall</h3> <code>org.apache.thrift.async.TAsyncMethodCall.State</code></li> </ul> </li> </ul> <!-- =========== FIELD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="field.summary"> <!-- --> </a> <h3>Field Summary</h3> <ul class="blockList"> <li class="blockList"><a name="fields.inherited.from.class.org.apache.thrift.async.TAsyncMethodCall"> <!-- --> </a> <h3>Fields inherited from class&nbsp;org.apache.thrift.async.TAsyncMethodCall</h3> <code>client, transport</code></li> </ul> </li> </ul> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.summary"> <!-- --> </a> <h3>Constructor Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><span class="memberNameLink"><a href="../../../../org/apache/cassandra/thrift/Cassandra.AsyncClient.describe_snitch_call.html#describe_snitch_call-org.apache.thrift.async.AsyncMethodCallback-org.apache.thrift.async.TAsyncClient-org.apache.thrift.protocol.TProtocolFactory-org.apache.thrift.transport.TNonblockingTransport-">describe_snitch_call</a></span>(org.apache.thrift.async.AsyncMethodCallback&nbsp;resultHandler, org.apache.thrift.async.TAsyncClient&nbsp;client, org.apache.thrift.protocol.TProtocolFactory&nbsp;protocolFactory, org.apache.thrift.transport.TNonblockingTransport&nbsp;transport)</code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method.summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd">&nbsp;</span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd">&nbsp;</span></span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr id="i0" class="altColor"> <td class="colFirst"><code>java.lang.String</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/apache/cassandra/thrift/Cassandra.AsyncClient.describe_snitch_call.html#getResult--">getResult</a></span>()</code>&nbsp;</td> </tr> <tr id="i1" class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/apache/cassandra/thrift/Cassandra.AsyncClient.describe_snitch_call.html#write_args-org.apache.thrift.protocol.TProtocol-">write_args</a></span>(org.apache.thrift.protocol.TProtocol&nbsp;prot)</code>&nbsp;</td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods.inherited.from.class.org.apache.thrift.async.TAsyncMethodCall"> <!-- --> </a> <h3>Methods inherited from class&nbsp;org.apache.thrift.async.TAsyncMethodCall</h3> <code>getClient, getFrameBuffer, getSequenceId, getStartTime, getState, getTimeoutTimestamp, hasTimeout, isFinished, onError, prepareMethodCall, transition</code></li> </ul> <ul class="blockList"> <li class="blockList"><a name="methods.inherited.from.class.java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="describe_snitch_call-org.apache.thrift.async.AsyncMethodCallback-org.apache.thrift.async.TAsyncClient-org.apache.thrift.protocol.TProtocolFactory-org.apache.thrift.transport.TNonblockingTransport-"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>describe_snitch_call</h4> <pre>public&nbsp;describe_snitch_call(org.apache.thrift.async.AsyncMethodCallback&nbsp;resultHandler, org.apache.thrift.async.TAsyncClient&nbsp;client, org.apache.thrift.protocol.TProtocolFactory&nbsp;protocolFactory, org.apache.thrift.transport.TNonblockingTransport&nbsp;transport) throws org.apache.thrift.TException</pre> <dl> <dt><span class="throwsLabel">Throws:</span></dt> <dd><code>org.apache.thrift.TException</code></dd> </dl> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method.detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="write_args-org.apache.thrift.protocol.TProtocol-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>write_args</h4> <pre>public&nbsp;void&nbsp;write_args(org.apache.thrift.protocol.TProtocol&nbsp;prot) throws org.apache.thrift.TException</pre> <dl> <dt><span class="overrideSpecifyLabel">Specified by:</span></dt> <dd><code>write_args</code>&nbsp;in class&nbsp;<code>org.apache.thrift.async.TAsyncMethodCall</code></dd> <dt><span class="throwsLabel">Throws:</span></dt> <dd><code>org.apache.thrift.TException</code></dd> </dl> </li> </ul> <a name="getResult--"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>getResult</h4> <pre>public&nbsp;java.lang.String&nbsp;getResult() throws org.apache.thrift.TException</pre> <dl> <dt><span class="throwsLabel">Throws:</span></dt> <dd><code>org.apache.thrift.TException</code></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> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/Cassandra.AsyncClient.describe_snitch_call.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../org/apache/cassandra/thrift/Cassandra.AsyncClient.describe_schema_versions_call.html" title="class in org.apache.cassandra.thrift"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../../org/apache/cassandra/thrift/Cassandra.AsyncClient.describe_splits_call.html" title="class in org.apache.cassandra.thrift"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/apache/cassandra/thrift/Cassandra.AsyncClient.describe_snitch_call.html" target="_top">Frames</a></li> <li><a href="Cassandra.AsyncClient.describe_snitch_call.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li><a href="#nested.classes.inherited.from.class.org.apache.thrift.async.TAsyncMethodCall">Nested</a>&nbsp;|&nbsp;</li> <li><a href="#fields.inherited.from.class.org.apache.thrift.async.TAsyncMethodCall">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &copy; 2016 The Apache Software Foundation</small></p> </body> </html>
jasonwee/videoOnCloud
lib/cassandra/apache-cassandra-3.7/javadoc/org/apache/cassandra/thrift/Cassandra.AsyncClient.describe_snitch_call.html
HTML
apache-2.0
14,184
/** * Copyright 2011-2019 Asakusa Framework Team. * * 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.asakusafw.lang.compiler.extension.hive.testing; import com.asakusafw.info.hive.TableInfo; import com.asakusafw.info.hive.FieldType.TypeName; import com.asakusafw.runtime.directio.DataFormat; @SuppressWarnings("javadoc") public abstract class MockDataFormat implements DataFormat<MockDataModel>, TableInfo.Provider { MockDataFormat() { return; } @Override public Class<MockDataModel> getSupportedType() { return MockDataModel.class; } @Override public TableInfo getSchema() { return new TableInfo.Builder(getClass().getSimpleName()) .withColumn("COL", TypeName.INT) .build(); } public static final class A extends MockDataFormat { public A() { return; } } public static final class B extends MockDataFormat { public B() { return; } } public static final class C extends MockDataFormat { public C() { return; } } public static final class D extends MockDataFormat { public D() { return; } } }
ashigeru/asakusafw-compiler
compiler-project/extension-hive/src/test/java/com/asakusafw/lang/compiler/extension/hive/testing/MockDataFormat.java
Java
apache-2.0
1,757
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head> <meta name="viewport" content="width=device-width, initial-scale=1.0"/> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <style type="text/css">*:not(br):not(tr):not(html) { font-family: Arial, 'Helvetica Neue', Helvetica, sans-serif !important; -webkit-box-sizing: border-box !important; box-sizing: border-box !important }cite:before { content: "\2014 \0020" !important }@media only screen and (max-width: 600px){ .email-body_inner, .email-footer { width: 100% !important } } @media only screen and (max-width: 500px){ .button { width: 100% !important } } </style></head> <body dir="ltr" style="height:100%;margin:0;line-height:1.4;background-color:#F2F4F6;color:#74787E;-webkit-text-size-adjust:none;width:100%"> <table class="email-wrapper" width="100%" cellpadding="0" cellspacing="0" style="width:100%;margin:0;padding:0;background-color:#F2F4F6"> <tbody><tr> <td class="content" style="color:#74787E;font-size:15px;line-height:18px;align:center;padding:0"> <table class="email-content" width="100%" cellpadding="0" cellspacing="0" style="width:100%;margin:0;padding:0"> <tbody><tr> <td class="email-masthead" style="color:#74787E;font-size:15px;line-height:18px;padding:25px 0;text-align:center"> <a class="email-masthead_name" href="https://example-hermes.com/" target="_blank" style="font-size:16px;font-weight:bold;color:#2F3133;text-decoration:none;text-shadow:0 1px 0 white"> <img src="https://github.com/matcornic/hermes/blob/master/examples/gopher.png?raw=true" class="email-logo" style="max-height:50px"/> </a> </td> </tr> <tr> <td class="email-body" width="100%" style="color:#74787E;font-size:15px;line-height:18px;width:100%;margin:0;padding:0;border-top:1px solid #EDEFF2;border-bottom:1px solid #EDEFF2;background-color:#FFF"> <table class="email-body_inner" align="center" width="570" cellpadding="0" cellspacing="0" style="width:570px;margin:0 auto;padding:0"> <tbody><tr> <td class="content-cell" style="color:#74787E;font-size:15px;line-height:18px;padding:35px"> <h1 style="margin-top:0;color:#2F3133;font-size:19px;font-weight:bold">Hi Jon Snow,</h1> <p style="margin-top:0;color:#74787E;font-size:16px;line-height:1.5em">Your order has been processed successfully.</p> <table class="data-wrapper" width="100%" cellpadding="0" cellspacing="0" style="width:100%;margin:0;padding:35px 0"> <tbody><tr> <td colspan="2" style="padding:10px 5px;color:#74787E;font-size:15px;line-height:18px"> <table class="data-table" width="100%" cellpadding="0" cellspacing="0" style="width:100%;margin:0"> <tbody><tr> <th width="20%" style="text-align:left;padding:0px 5px;padding-bottom:8px;border-bottom:1px solid #EDEFF2"> <p style="margin-top:0;line-height:1.5em;margin:0;color:#9BA2AB;font-size:12px">Item</p> </th> <th style="text-align:left;padding:0px 5px;padding-bottom:8px;border-bottom:1px solid #EDEFF2"> <p style="margin-top:0;line-height:1.5em;margin:0;color:#9BA2AB;font-size:12px">Description</p> </th> <th width="15%" style="padding:0px 5px;padding-bottom:8px;border-bottom:1px solid #EDEFF2;text-align:right"> <p style="margin-top:0;line-height:1.5em;margin:0;color:#9BA2AB;font-size:12px">Price</p> </th> </tr> <tr> <td style="padding:10px 5px;color:#74787E;font-size:15px;line-height:18px"> Golang </td> <td style="padding:10px 5px;color:#74787E;font-size:15px;line-height:18px"> Open source programming language that makes it easy to build simple, reliable, and efficient software </td> <td style="padding:10px 5px;color:#74787E;font-size:15px;line-height:18px;text-align:right"> $10.99 </td> </tr> <tr> <td style="padding:10px 5px;color:#74787E;font-size:15px;line-height:18px"> Hermes </td> <td style="padding:10px 5px;color:#74787E;font-size:15px;line-height:18px"> Programmatically create beautiful e-mails using Golang. </td> <td style="padding:10px 5px;color:#74787E;font-size:15px;line-height:18px;text-align:right"> $1.99 </td> </tr> </tbody></table> </td> </tr> </tbody></table> <p style="margin-top:0;color:#74787E;font-size:16px;line-height:1.5em">You can check the status of your order and more in your dashboard:</p> <!--[if mso]> <div style="margin: 30px auto;v-text-anchor:middle;text-align:center"> <v:roundrect xmlns:v="urn:schemas-microsoft-com:vml" xmlns:w="urn:schemas-microsoft-com:office:word" href="https://hermes-example.com/dashboard" style="height:45px;v-text-anchor:middle;width:200px;background-color:#3869D4;" arcsize="10%" strokecolor="#3869D4" fillcolor="#3869D4" > <w:anchorlock/> <center style="color: #FFFFFF;font-size: 15px;text-align: center;font-family:sans-serif;font-weight:bold;"> Go to Dashboard </center> </v:roundrect> </div> <![endif]--> <!--[if !mso]><!-- --> <table class="body-action" align="center" width="100%" cellpadding="0" cellspacing="0" style="width:100%;margin:30px auto;padding:0;text-align:center"> <tbody><tr> <td align="center" style="padding:10px 5px;color:#74787E;font-size:15px;line-height:18px"> <div> <a href="https://hermes-example.com/dashboard" class="button" style="display:inline-block;background-color:#3869D4;border-radius:3px;font-size:15px;line-height:45px;text-align:center;text-decoration:none;-webkit-text-size-adjust:none;mso-hide:all;color:#ffffff;width:200px" target="_blank" width="200"> Go to Dashboard </a> </div> </td> </tr> </tbody></table> <!--[endif]----> <p style="margin-top:0;color:#74787E;font-size:16px;line-height:1.5em"> Yours truly, <br/> Hermes </p> <table class="body-sub" style="width:100%;margin-top:25px;padding-top:25px;border-top:1px solid #EDEFF2;table-layout:fixed"> <tbody> <tr> <td style="padding:10px 5px;color:#74787E;font-size:15px;line-height:18px"> <p class="sub" style="margin-top:0;color:#74787E;line-height:1.5em;font-size:12px">If you’re having trouble with the button &#39;Go to Dashboard&#39;, copy and paste the URL below into your web browser.</p> <p class="sub" style="margin-top:0;color:#74787E;line-height:1.5em;font-size:12px"><a href="https://hermes-example.com/dashboard" style="color:#3869D4;word-break:break-all">https://hermes-example.com/dashboard</a></p> </td> </tr> </tbody> </table> </td> </tr> </tbody></table> </td> </tr> <tr> <td style="padding:10px 5px;color:#74787E;font-size:15px;line-height:18px"> <table class="email-footer" align="center" width="570" cellpadding="0" cellspacing="0" style="width:570px;margin:0 auto;padding:0;text-align:center"> <tbody><tr> <td class="content-cell" style="color:#74787E;font-size:15px;line-height:18px;padding:35px"> <p class="sub center" style="margin-top:0;line-height:1.5em;color:#AEAEAE;font-size:12px;text-align:center"> Copyright © 2020 Hermes. All rights reserved. </p> </td> </tr> </tbody></table> </td> </tr> </tbody></table> </td> </tr> </tbody></table> </body></html>
matcornic/hermes
examples/default/default.receipt.html
HTML
apache-2.0
12,151
/* * Licensed to The Apereo Foundation under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * The Apereo Foundation 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 com.dytech.gui; import java.awt.Toolkit; import javax.swing.JTextField; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.PlainDocument; /** @author Nicholas Read */ public class JNumberTextField extends JTextField { public JNumberTextField(int maxNumber) { super(new NumberDocument(maxNumber), null, 0); } public void clear() { ((NumberDocument) getDocument()).clear(); } @Override public void setText(String t) { if (t == null || t.length() == 0) { clear(); } else { super.setText(t); } } public int getNumber() { return getNumber(-1); } public int getNumber(int defaultValue) { String t = getText(); return t.length() == 0 ? defaultValue : Integer.parseInt(t); } private static class NumberDocument extends PlainDocument { private int maxNumber; public NumberDocument(int maxNumber) { this.maxNumber = maxNumber; } public void clear() { try { super.remove(0, getLength()); } catch (BadLocationException ex) { throw new RuntimeException("This should never happen", ex); } } @Override public void insertString(int offset, String s, AttributeSet attributeSet) throws BadLocationException { try { int value = Integer.parseInt(s); if (value < 0) { Toolkit.getDefaultToolkit().beep(); return; } } catch (NumberFormatException ex) { Toolkit.getDefaultToolkit().beep(); return; } super.insertString(offset, s, attributeSet); if (Integer.parseInt(getText(0, getLength())) > maxNumber) { Toolkit.getDefaultToolkit().beep(); super.remove(offset, s.length()); } } } }
equella/Equella
Source/Plugins/Platform/com.tle.platform.swing/src/com/dytech/gui/JNumberTextField.java
Java
apache-2.0
2,604
import urllib import twython def Crowd_twitter(query): consumer_key = '*****'; consumer_secret = '*****'; access_token = '******'; access_token_secret = '******'; client_args = {'proxies': {'https': 'http://10.93.0.37:3333'}} t = twython.Twython(app_key=consumer_key, app_secret=consumer_secret, oauth_token=access_token, oauth_token_secret=access_token_secret, client_args = client_args) # query=raw_input("What do you want to search for?"); # query.replace(" ","+"); output = t.search(q=query, result_type='popular', count=10) #purposely restricted to 10 users to protect from Spamming the Twitter server which could cause blacklisting of our server #print output; aggregater = [] for i in range(10): aggregater.append(output[u'statuses'][i][u'text']); happy = open("positive-words.txt",'r') sad = open("negative-words.txt",'r') ha = happy.readlines() sa = sad.readlines() happy.close() sad.close() for i in range(len(ha)): ha[i]=ha[i].rstrip() for i in range(len(sa)): sa[i]=sa[i].rstrip() #Put basic sentiment analysis on tweet posi = 0; negi = 0; for i in range(10): for j in range(len(ha)): if(ha[j] in aggregater[i]): posi += 1; for j in range(len(sa)): if(sa[j] in aggregater[i]): negi += 1; #print "<!DOCTYPE html>\n<html>\n<title>Crowd likes!</title>" if posi > negi: return "<h1>CROWD LOVES IT!!:-)</h1>" elif posi<negi: return "<h1>CROWD DOESN'T LIKE IT!! :-( </h1>" else: return "<h1>CROWD CAN'T DECIDE :-| !!</h1>" def buildwebpage(product_fk,product_cr,product_am,product_eb,search_query): # return images,links,names,prices print "<!DOCTYPE html>\n<html>"; print "\n<h1><em><ul>WELCOME TO DEALERSITE - ONE STOP FOR ALL YOUR SHOPPING</ul></em></h1>\n<body>" print "<h1>THIS IS WHAT THE CROWD THINKS OF "+search_query+":</h1>" print Crowd_twitter(search_query) print "\n<h1>AMAZON</h1>"; for i in range(3): print "\n<h2>"+product_am[2][i]+"</h2>" print "<img border=\"0\" src=\""+product_am[0][i]+"\" alt=\"Amazon\">" print "<a href=\""+product_am[1][i]+"\">CLICK THIS TO TAKE YOU TO AMAZONS PAGE TO BUY THE PRODUCT</a>" print "\n<p>PRICE : Rs."+product_am[3][i]+"</p>"; print "\n<h1>EBAY</h1>"; for i in range(3): print "\n<h2>"+product_eb[2][i]+"</h2>" print "<img border=\"0\" src=\""+product_eb[0][i]+"\" alt=\"EBay\">" print "<a href=\""+product_eb[1][i]+"\">CLICK THIS TO TAKE YOU TO EBAYS PAGE TO BUY THE PRODUCT</a>" print "\n<p>PRICE : Rs."+product_eb[3][i]+"</p>"; print "\n<h1>FLIPKART</h1>"; for i in range(3): print "\n<h2>"+product_fk[2][i]+"</h2>" print "<img border=\"0\" src=\""+product_fk[0][i]+"\" alt=\"Flipkart\">" print "<a href=\""+product_fk[1][i]+"\">CLICK THIS TO TAKE YOU TO FLIPKARTS PAGE TO BUY THE PRODUCT</a>" print "\n<p>PRICE : Rs."+product_fk[3][i]+"</p>"; print "\n<h1>CROMA RETAIL</h1>"; for i in range(3): print "\n<h2>"+product_cr[2][i]+"</h2>" print "<img border=\"0\" src=\""+product_cr[0][i]+"\" alt=\"CROMA\">" print "<a href=\""+product_cr[1][i]+"\">CLICK THIS TO TAKE YOU TO CROMA PAGE TO BUY THE PRODUCT</a>" print "\n<p>PRICE : "+product_cr[3][i]+"</p>"; print "<a href=\"/comparison.html\"><em><b>CLICK HERE FOR A COMPARISON OF DIFFERENT BRANDS</b></em></a>" # print "<a href=\"/crowd.html\">CLICK HERE FOR WHAT THE CROWD THINKS OF THE PRODUCT</a>" print "</body>\n</html>" def link_fk_actu(product_image): Flipkart_query = "http://www.flipkart.com/all-categories/pr?p%5B%5D=sort%3Drelevance&sid=search.flipkart.com&q="; # print "\n\n\n\n\nLINK FK ACTUAL"; # print product_image; names = []; for i in range(3): ind = product_image[i].index("data-pid=")+len("data-pid=\""); indend = product_image[i].index("data-tracking-products",ind) - 2; names.append(Flipkart_query + product_image[i][ind:indend]); return names; def price_fk(product_image): # print "\n\n\n\n\nPRICE FK"; # print product_image; names = []; for i in range(3): indend = product_image[i].index(";;"); ind = product_image[i].rfind(";",0,indend-1); names.append(product_image[i][ind+1:indend]); return names; def name_fk(product_image): # print "\n\n\n\n\nNAME FK"; # print product_image; names = []; for i in range(3): ind = product_image[i].index("alt")+len("alt=\""); names.append(product_image[i][ind:].split()[0]); # product_image[i][ind:indend]); return names; def link_fk(product_link): # print "\n\n\n\n\nLINK FK"; # print product_link; beg_string = "www.flipkart.com"; links = []; for i in range(3): ind = product_link[i].index("a href=")+len("a href=\""); indend = product_link[i].index("class") - 2; links.append(beg_string+product_link[i][ind:indend]); return links; def image_fk(product_image): img = []; counter = 0; for i in range(len(product_image)): # print product_image[i]; try: ind = product_image[i].index("data-src")+len("data-src=\""); ind_end1 = 10000; ind_end2 = 10000; try: ind_end1 = product_image[i].index("\"",ind); except ValueError: ind_end2 = product_image[i].index("\'",ind); if ind_end2 < ind_end1: ind_end = ind_end2; else: ind_end = ind_end1; img.append(product_image[i][ind:ind_end]); ++counter; except ValueError: ind = product_image[i].index("src=")+len("src=\""); ind_end1 = 10000; ind_end2 = 10000; try: ind_end1 = product_image[i].index("\"",ind); except ValueError: ind_end2 = product_image[i].index("\'",ind); if ind_end2 < ind_end1: ind_end = ind_end2; else: ind_end = ind_end1; img.append(product_image[i][ind:ind_end]); ++counter; if counter == 3: break; return img[:3]; def process_fk(fk_lines): product_image = []; product_name = []; product_otherone = []; flag = 0; counter = 0; prev_line = ""; linenum = 0; for l in fk_lines: # print l; # if "<div class=\'product" in l: # flag = 1; linenum += 1; if "<div class='product" in l: product_name.append(l); flag = 1; # if flag == 0 and "<img src=" in l: # flag =1; # continue; if flag == 1 and "<img src=" in l: product_image.append(l); product_otherone.append(prev_line); ++counter; if(counter==12): break; flag = 0; prev_line = l; product_image = product_image[1:11]; product_name = product_name[1:11]; product_otherone = product_otherone[0:10]; if(len(product_name)>=10): teer = link_fk_actu(product_name); else: teer = link_fk(product_otherone); return image_fk(product_image),teer,name_fk(product_image),price_fk(product_name); ##################################################################################################### def process_am(am_lines): # print am_lines; links = []; images = []; names = []; prices = []; flag = 0; counter = 0; #urllib has a very strange behaviour when retrieving webpages - The server hands out slightly difficult code to parse. flag = 0; for l in am_lines: # print 1; try: if ("<div id=\"srProductTitle" in l) and ("<a href=\"" in l) and ("src=\"" in l) and ("<br clear=\"all\" />" in l): # print l; # break; ind =l.index("<a href=\"")+len("<a href=\""); # print ind; indend = l.index("\"",ind+1); links.append(l[ind:indend]); # i += 1; ind =l.index("src=\"")+len("src=\""); indend = l.index("\"",ind); images.append(l[ind:indend]); # i+=1; ind =l.index("<br clear=\"all\" />")+len("<br clear=\"all\" />"); indend = l.index("</a",ind); names.append(l[ind:indend]); flag = 1; # print links,images,names; # for j in range(10): #generally keep going and stop when you find the necessary key word # i += 1; if ("<div class=\"newPrice\">" in l) or ("<div class=\"usedPrice\">" in l): if flag == 1: # print flag; indend =l.index("</span></span></div>"); ind = l.rfind("</span>",0,indend) + len("</span>"); prices.append(l[ind:indend]); # flag = 1; counter +=1; flag = 0; except ValueError: continue; # break; # if flag ==1: # break; if counter == 3: break; return images,links,names,prices; ########################################################################################################### def process_cr(cr_lines): links = []; images = []; names = []; prices = []; flag = 0; counter = 0; #urllib has a very strange behaviour when retrieving webpages - The server hands out slightly difficult code to parse. flag = 0; base = "http://www.cromaretail.com" for l in cr_lines: # print l; try: if ("<article><a title=" in l) and ("href" in l) and ("<img src=\"" in l): # print l; ind =l.index("<article><a title=")+len("<article><a title=\""); indend = l.index("\"",ind+1); names.append(l[ind:indend]); ind =l.index("href=\"")+len("href=\""); indend = l.index("\"",ind+1); links.append(base+"/"+l[ind:indend]); ind =l.index("<img src=\"")+len("<img src=\""); indend = l.index("\"",ind+1); images.append(base+l[ind:indend]); flag =1; if ("</span>" in l) and flag ==1: ind =l.index("</span>")+len("</span>"); indend = l.index("<",ind+1); prices.append(l[ind:indend]); counter += 1; flag =0; except ValueError: continue; if counter == 3: break; return images,links,names,prices; ####################################################################################################################### def process_eb(eb_lines): links = []; images = []; names = []; prices = []; flag = 0; counter = 0; #urllib has a very strange behaviour when retrieving webpages - The server hands out slightly difficult code to parse. for i in range(len(eb_lines)): # print l; l = eb_lines[i]; try: if (" class=\"lv-1st\"></a>" in l): Link = eb_lines[i+12]; Image = eb_lines[i+14]; Name = eb_lines[i+14]; Price = eb_lines[i+45]; # print Link,Image,Name,Price,"\n\n\n=======================\n\n\n"; ind =Link.index("<a href=\"")+len("<a href=\""); indend = Link.index("\"",ind+1); links.append(Link[ind:indend]); ind =Image.index("src=")+len("src=\""); indend = Image.index("class",ind+1); images.append(Image[ind:indend-2]); ind =Name.index("alt=")+len("alt=\""); indend = Name.index(" />",ind+1); names.append(Name[ind:indend-1]); ind =Price.index("</b>")+len("</b>"); indend = Price.index("<",ind+1); prices.append(Price[ind:indend]); counter += 1; i += 50; except ValueError: continue; if counter == 3: # print images,"\n\n\n=======================\n\n\n",links,"\n\n\n=======================\n\n\n",names,"\n\n\n=======================\n\n\n",prices; return images,links,names,prices; # break; if __name__=="__main__": proxy = 'http://10.93.0.37:3333'; search_query = raw_input("Enter the name to compare : "); search_query = search_query.replace(" ","+"); Flipkart_query = "http://www.flipkart.com/all-categories/pr?p%5B%5D=sort%3Drelevance&sid=search.flipkart.com&q="+search_query; Amazon_query = "http://www.amazon.in/s/ref=nb_sb_noss_1?url=search-alias%3Daps&field-keywords="+search_query+"&rh=i%3Aaps%2Ck%3A"+search_query; Croma_query = "http://www.cromaretail.com/productsearch.aspx?txtSearch="+search_query+"&x=-808&y=-85"; Ebay_query = "http://www.ebay.in/sch/i.html?_trksid=p2050601.m570.l1313.TR0.TRC0.X"+search_query+"&_nkw="+search_query+"&_sacat=0&_from=R40"; Flipkart = urllib.urlopen(Flipkart_query, proxies={'http': proxy}) Amazon = urllib.urlopen(Amazon_query, proxies={'http': proxy}) Croma = urllib.urlopen(Croma_query, proxies={'http': proxy}) Ebay = urllib.urlopen(Ebay_query, proxies={'http': proxy}) fk_lines = Flipkart.readlines(); am_lines = Amazon.readlines(); cr_lines = Croma.readlines(); eb_lines = Ebay.readlines(); product_fk = process_fk(fk_lines); product_am = process_am(am_lines); product_cr = process_cr(cr_lines); product_eb = process_eb(eb_lines); buildwebpage(product_fk,product_cr,product_am,product_eb,search_query); # Crowd_twitter();
SuFizz/Dealer-Loves-Code
starter_first.py
Python
apache-2.0
14,255
/********************************************************************************************************************** * 描述: * 批量获取用户基本信息 结果模型。 * * 变更历史: * 作者:李亮 时间:2016年12月25日 新建 * *********************************************************************************************************************/ using System.Collections.Generic; using Newtonsoft.Json; namespace Wlitsoft.Framework.WeixinSDK.Model.UserManagementApiModel { /// <summary> /// 批量获取用户基本信息 结果模型。 /// </summary> public class GetUserInfosResultModel : ResultModelBase { /// <summary> /// 获取或设置 用户基本信息列表。 /// </summary> [JsonProperty("user_info_list")] public List<GetUserInfoResultModel> UserInfoList { get; set; } } }
Wlitsoft/WeixinSDK
src/WeixinSDK/Model/UserManagementApiModel/GetUserInfosResultModel.cs
C#
apache-2.0
903
# Unonopsis costanensis Maas & Westra SPECIES #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Magnoliales/Annonaceae/Unonopsis/Unonopsis costanensis/README.md
Markdown
apache-2.0
193
# Cyrtandra kraemeri Reinecke SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Gesneriaceae/Cyrtandra/Cyrtandra samoensis/ Syn. Cyrtandra kraemeri/README.md
Markdown
apache-2.0
184
# Saxifraga rhaetica Kern. SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Saxifragales/Saxifragaceae/Saxifraga/Saxifraga rhaetica/README.md
Markdown
apache-2.0
174
# Cuphea thymoides var. satureoides A. St.-Hil. VARIETY #### Status ACCEPTED #### According to GRIN Taxonomy for Plants #### Published in Fl. Bras. merid. 3:83. 1833 #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Myrtales/Lythraceae/Cuphea/Cuphea thymoides/Cuphea thymoides satureoides/README.md
Markdown
apache-2.0
211
# Populus trichocarpa var. cupulata S. Watson VARIETY #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Malpighiales/Salicaceae/Populus/Populus trichocarpa/ Syn. Populus trichocarpa cupulata/README.md
Markdown
apache-2.0
200
# Polygonum declinatum Vell. SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Caryophyllales/Polygonaceae/Polygonum/Polygonum declinatum/README.md
Markdown
apache-2.0
176
# Virgaria setiformis (Wallr.) Sacc., 1886 SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in Syll. fung. (Abellini) 4: 282 (1886) #### Original name Helminthosporium setiforme Wallr., 1833 ### Remarks null
mdoering/backbone
life/Fungi/Ascomycota/Dothideomycetes/Hysteriales/Hysteriaceae/Acrogenospora/Acrogenospora setiformis/ Syn. Virgaria setiformis/README.md
Markdown
apache-2.0
264
# Viola papilionacea var. aberrans Stone VARIETY #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Malpighiales/Violaceae/Viola/Viola sororia/Viola sororia sororia/Viola papilionacea aberrans/README.md
Markdown
apache-2.0
188
# Pseudocercospora calotropidis (Ellis & Everh.) Haldar & J.B. Ray, 2001 SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in Journal of Mycopathological Research 39(1): 43 (2001) #### Original name Cercospora calotropidis Ellis & Everh., 1898 ### Remarks null
mdoering/backbone
life/Fungi/Ascomycota/Dothideomycetes/Capnodiales/Mycosphaerellaceae/Passalora/Passalora calotropidis/ Syn. Pseudocercospora calotropidis/README.md
Markdown
apache-2.0
316
/** * Copyright (c) 2016 Intel 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. */ (function () { 'use strict'; App.factory('ApplicationRegisterHelpers', function(ApplicationRegisterResource, NotificationService) { return { getOfferingsOfApp: function(appGuid) { return ApplicationRegisterResource .withErrorMessage('Failed to retrieve service offerings from catalog') .getClonedApplication(appGuid) .then(function (response) { return response.plain(); }); }, registerApp: function(request) { return ApplicationRegisterResource .withErrorMessage('Failed to register application in marketplace') .registerApplication(request) .then(function (response) { NotificationService.success('Application has been registered in marketplace'); return response.plain(); }); } }; }); })();
trustedanalytics/console
app/ui/app/applications/application/register/ApplicationRegisterHelpers.js
JavaScript
apache-2.0
1,639
package items; import java.sql.*; import utils.ImportantMethods; public class CreateItem { //this class manages items. //we'll take some of the logic from CreateUser.java's implementation. private Connection mariadb_default; private String item_name; private String item_description; private int item_id; private double item_price; private Statement do_queries; public CreateItem(String item_name, String item_description, double item_price) throws SQLException, ClassNotFoundException{ mariadb_default = utils.ImportantMethods.getRegularPOSDBConnection(); do_queries = mariadb_default.createStatement(); this.item_name = item_name.trim(); this.item_description = item_description; this.item_price = item_price; String previous_id_query = "SELECT id FROM pos_items ORDER BY id DESC LIMIT 1"; ResultSet last_id_result = do_queries.executeQuery(previous_id_query); int last_id = 0; while (last_id_result.next()) { last_id = last_id_result.getInt("id"); } this.item_id = last_id + 1; } public boolean create() throws SQLException, ItemNotCreatedException{ //let's try the StringBuilder! String check_item_exists = ImportantMethods.getResultString(mariadb_default, "pos_items", "name", "name", item_name); if (check_item_exists.equals(item_name)) { throw new ItemNotCreatedException("Item exists"); } StringBuilder build_insert_query = new StringBuilder(); build_insert_query.append("INSERT INTO pos_items VALUES("); build_insert_query.append("\""); build_insert_query.append(item_name); build_insert_query.append("\",\""); build_insert_query.append(item_description); build_insert_query.append("\","); build_insert_query.append(item_id); build_insert_query.append(","); build_insert_query.append(item_price); build_insert_query.append(");"); //yeah, that was fun...... I think I'll build a class to do this for me. String insert_query = build_insert_query.toString(); do_queries.executeQuery(insert_query); do_queries.close(); return true; } }
cdknight/POSReady
src/items/CreateItem.java
Java
apache-2.0
2,060
# Excoecaria sambesica Pax & K.Hoffm. SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Malpighiales/Euphorbiaceae/Excoecaria/Excoecaria bussei/ Syn. Excoecaria sambesica/README.md
Markdown
apache-2.0
192
onimm ===== svg mindmap d3.js
Elfhir/onimm
README.md
Markdown
apache-2.0
31
# Install script for directory: /home/hryu/runos/test # Set the install prefix if(NOT DEFINED CMAKE_INSTALL_PREFIX) set(CMAKE_INSTALL_PREFIX "/usr/local") endif() string(REGEX REPLACE "/$" "" CMAKE_INSTALL_PREFIX "${CMAKE_INSTALL_PREFIX}") # Set the install configuration name. if(NOT DEFINED CMAKE_INSTALL_CONFIG_NAME) if(BUILD_TYPE) string(REGEX REPLACE "^[^A-Za-z0-9_]+" "" CMAKE_INSTALL_CONFIG_NAME "${BUILD_TYPE}") else() set(CMAKE_INSTALL_CONFIG_NAME "Debug") endif() message(STATUS "Install configuration: \"${CMAKE_INSTALL_CONFIG_NAME}\"") endif() # Set the component getting installed. if(NOT CMAKE_INSTALL_COMPONENT) if(COMPONENT) message(STATUS "Install component: \"${COMPONENT}\"") set(CMAKE_INSTALL_COMPONENT "${COMPONENT}") else() set(CMAKE_INSTALL_COMPONENT) endif() endif() # Install shared libraries without execute permission? if(NOT DEFINED CMAKE_INSTALL_SO_NO_EXE) set(CMAKE_INSTALL_SO_NO_EXE "1") endif() if(NOT CMAKE_INSTALL_LOCAL_ONLY) # Include the install script for each subdirectory. include("/home/hryu/runos/cmake-build-debug/test/gmock-1.7.0/cmake_install.cmake") include("/home/hryu/runos/cmake-build-debug/test/types/cmake_install.cmake") include("/home/hryu/runos/cmake-build-debug/test/oxm/cmake_install.cmake") include("/home/hryu/runos/cmake-build-debug/test/maple/cmake_install.cmake") endif()
ElenaOshkina/runos
cmake-build-debug/test/cmake_install.cmake
CMake
apache-2.0
1,398
/** * Copyright 2015 IBM Corp. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.ibm.watson.developer_cloud.language_translator.v2; import static com.ibm.watson.developer_cloud.language_translator.v2.model.Language.ENGLISH; import static com.ibm.watson.developer_cloud.language_translator.v2.model.Language.SPANISH; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.io.File; import java.util.List; import java.util.Map; import org.junit.Before; import org.junit.Test; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.ibm.watson.developer_cloud.WatsonServiceTest; import com.ibm.watson.developer_cloud.language_translator.v2.model.CreateModelOptions; import com.ibm.watson.developer_cloud.language_translator.v2.model.IdentifiableLanguage; import com.ibm.watson.developer_cloud.language_translator.v2.model.IdentifiedLanguage; import com.ibm.watson.developer_cloud.language_translator.v2.model.TranslationModel; import com.ibm.watson.developer_cloud.language_translator.v2.model.TranslationResult; /** * Language Translation integration test. */ public class LanguageTranslatorIT extends WatsonServiceTest { private static final String ENGLISH_TO_SPANISH = "en-es"; private static final String RESOURCE = "src/test/resources/language_translation/"; private LanguageTranslator service; private final Map<String, String> translations = ImmutableMap.of( "The IBM Watson team is awesome", "El equipo es increíble IBM Watson", "Welcome to the cognitive era", "Bienvenido a la era cognitiva"); private final List<String> texts = ImmutableList.copyOf(translations.keySet()); /* * (non-Javadoc) * * @see com.ibm.watson.developercloud.WatsonServiceTest#setUp() */ @Override @Before public void setUp() throws Exception { super.setUp(); service = new LanguageTranslator(); service.setUsernameAndPassword(getValidProperty("language_translation.username"), getValidProperty("language_translation.password")); service.setEndPoint(getValidProperty("language_translation.url")); service.setDefaultHeaders(getDefaultHeaders()); } /** * Test create and delete model. */ @Test public void testCreateAndDeleteModel() { CreateModelOptions options = new CreateModelOptions.Builder() .name("integration-test") .baseModelId("en-es") .forcedGlossary(new File(RESOURCE + "glossary.tmx")) .build(); TranslationModel model = null; try { model = service.createModel(options).execute(); Thread.sleep(3000); assertNotNull(model); } catch (InterruptedException e) { e.printStackTrace(); } finally { if (model != null) service.deleteModel(model.getId()).execute(); } } /** * Test Get Identifiable languages. */ @Test public void testGetIdentifiableLanguages() { final List<IdentifiableLanguage> languages = service.getIdentifiableLanguages().execute(); assertNotNull(languages); assertTrue(!languages.isEmpty()); } /** * Test Get model by id. */ @Test public void testGetModel() { final TranslationModel model = service.getModel(ENGLISH_TO_SPANISH).execute(); assertNotNull(model); } /** * Test Get Models. */ @Test public void testGetModels() { final List<TranslationModel> models = service.getModels().execute(); assertNotNull(models); assertFalse(models.isEmpty()); } /** * Test Identify. */ @Test public void testIdentify() { final List<IdentifiedLanguage> identifiedLanguages = service.identify(texts.get(0)).execute(); assertNotNull(identifiedLanguages); assertFalse(identifiedLanguages.isEmpty()); } /** * Test translate. */ @Test public void testTranslate() { for(String text : texts) { testTranslationResult(text, translations.get(text), service.translate(text, ENGLISH_TO_SPANISH).execute()); testTranslationResult(text, translations.get(text), service.translate(text, ENGLISH, SPANISH).execute()); } } /** * Test translate multiple. */ @Test public void testTranslateMultiple() { TranslationResult results = service.translate(texts, ENGLISH_TO_SPANISH).execute(); assertEquals(2, results.getTranslations().size()); assertEquals(translations.get(texts.get(0)), results.getTranslations().get(0).getTranslation()); assertEquals(translations.get(texts.get(1)), results.getTranslations().get(1).getTranslation()); results = service.translate(texts, ENGLISH, SPANISH).execute(); assertEquals(2, results.getTranslations().size()); assertEquals(translations.get(texts.get(0)), results.getTranslations().get(0).getTranslation()); assertEquals(translations.get(texts.get(1)), results.getTranslations().get(1).getTranslation()); } private void testTranslationResult(String text, String result, TranslationResult translationResult) { assertNotNull(translationResult); assertEquals(translationResult.getWordCount().intValue(), text.split(" ").length); assertNotNull(translationResult.getTranslations()); assertNotNull(translationResult.getTranslations().get(0).getTranslation()); assertEquals(result, translationResult.getTranslations().get(0).getTranslation()); } }
m2fd/java-sdk
src/test/java/com/ibm/watson/developer_cloud/language_translator/v2/LanguageTranslatorIT.java
Java
apache-2.0
5,978
/** * Copyright 2015 Santhosh Kumar Tekuri * * The JLibs authors license 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 jlibs.core.graph.sequences; import jlibs.core.graph.Sequence; import org.testng.annotations.Factory; public class SequenceTestFactory{ @Factory @SuppressWarnings({"unchecked"}) public static SequenceTest[] createTests(){ Sequence sequences[] = new Sequence[]{ new TOCSequence(1, 10), new IterableSequence(System.getProperties().entrySet()), new ArraySequence(System.getProperties().entrySet().toArray()), }; SequenceTest tests[] = new SequenceTest[sequences.length]; for(int i=0; i<sequences.length; i++) tests[i] = new SequenceTest(sequences[i]); return tests; } }
santhosh-tekuri/jlibs
core/src/test/java/jlibs/core/graph/sequences/SequenceTestFactory.java
Java
apache-2.0
1,321
/* SystemJS module definition */ declare var module: NodeModule; interface NodeModule { id: string; [ key: string ]: any; } declare module '*.json' { const value: any; export default value; }
rogerthat-platform/gae-plugin-framework
src/framework/client/typings.d.ts
TypeScript
apache-2.0
203
/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var tape = require( 'tape' ); var abs = require( '@stdlib/math/base/special/abs' ); var isnan = require( '@stdlib/math/base/assert/is-nan' ); var PINF = require( '@stdlib/constants/float64/pinf' ); var NINF = require( '@stdlib/constants/float64/ninf' ); var EPS = require( '@stdlib/constants/float64/eps' ); var variance = require( './../lib' ); // FIXTURES // var data = require( './fixtures/julia/data.json' ); // TESTS // tape( 'main export is a function', function test( t ) { t.ok( true, __filename ); t.equal( typeof variance, 'function', 'main export is a function' ); t.end(); }); tape( 'if provided `NaN` for any parameter, the function returns `NaN`', function test( t ) { var v = variance( NaN, 0.5 ); t.equal( isnan( v ), true, 'returns NaN' ); v = variance( 10.0, NaN ); t.equal( isnan( v ), true, 'returns NaN' ); t.end(); }); tape( 'if provided `k <= 0`, the function returns `NaN`', function test( t ) { var y; y = variance( -1.0, 2.0 ); t.equal( isnan( y ), true, 'returns NaN' ); y = variance( NINF, 1.0 ); t.equal( isnan( y ), true, 'returns NaN' ); y = variance( NINF, PINF ); t.equal( isnan( y ), true, 'returns NaN' ); y = variance( NINF, NINF ); t.equal( isnan( y ), true, 'returns NaN' ); y = variance( NINF, NaN ); t.equal( isnan( y ), true, 'returns NaN' ); t.end(); }); tape( 'if provided `lambda <= 0`, the function returns `NaN`', function test( t ) { var y; y = variance( 2.0, -1.0 ); t.equal( isnan( y ), true, 'returns NaN' ); y = variance( 1.0, NINF ); t.equal( isnan( y ), true, 'returns NaN' ); y = variance( PINF, NINF ); t.equal( isnan( y ), true, 'returns NaN' ); y = variance( NINF, NINF ); t.equal( isnan( y ), true, 'returns NaN' ); y = variance( NaN, NINF ); t.equal( isnan( y ), true, 'returns NaN' ); t.end(); }); tape( 'the function returns the variance of a Weibull distribution', function test( t ) { var expected; var lambda; var delta; var tol; var k; var i; var y; expected = data.expected; k = data.k; lambda = data.lambda; for ( i = 0; i < expected.length; i++ ) { y = variance( k[i], lambda[i] ); if ( y === expected[i] ) { t.equal( y, expected[i], 'k: '+k[i]+', lambda: '+lambda[i]+', y: '+y+', expected: '+expected[i] ); } else { delta = abs( y - expected[ i ] ); tol = 300.0 * EPS * abs( expected[ i ] ); t.ok( delta <= tol, 'within tolerance. k: '+k[i]+'. lambda: '+lambda[i]+'. y: '+y+'. E: '+expected[ i ]+'. Δ: '+delta+'. tol: '+tol+'.' ); } } t.end(); });
stdlib-js/stdlib
lib/node_modules/@stdlib/stats/base/dists/weibull/variance/test/test.js
JavaScript
apache-2.0
3,156
package com.pdsl.testcases; import com.pdsl.specifications.TestSpecification; import java.util.Collection; /** * A factory that is able to convert TestSpecification objects into TestCases that are used as inputs for * * @code{PolymorphicDslTestExecutor}s. */ public interface TestCaseFactory { /** * Converts test specifications into test cases. * * @param testCaseSpecification The blueprint for creating the test cases * @return A collection of Test Cases */ Collection<TestCase> processTestSpecification(Collection<TestSpecification> testCaseSpecification); }
google/polymorphicDSL
src/main/java/com/pdsl/testcases/TestCaseFactory.java
Java
apache-2.0
603
/* * author: Thomas Yao */ #ifndef _WCHAR_LIST_H_ #define _WCHAR_LIST_H_ #include <wchar.h> struct _wchar_list_node { struct _wchar_list_node* next; struct _wchar_list_node* prev; wchar_t* data; int index; }; struct _wchar_list { struct _wchar_list_node* curr; int size; }; struct _wchar_list* wchar_list_initial(); void wchar_list_add(struct _wchar_list* _s, wchar_t* _data); struct _wchar_list* wchar_list_initial_by_array(wchar_t* _array[], int _size); void wchar_list_rm_curr(struct _wchar_list* _s); wchar_t* wchar_list_get_index(struct _wchar_list* s, int _index); void wchar_list_destory(struct _wchar_list* _s); void wchar_list_rmall_by_data(struct _wchar_list* _s, wchar_t* _data); void wchar_list_print(struct _wchar_list* _s); #endif
thomasyaoonline/lucenec
kirani/utils/wchar_list.h
C
apache-2.0
822
#ifndef __SDHASH_THREADS_H #define __SDHASH_THREADS_H void *thread_sdbf_hashfile( void *task_param) ; void sdbf_hash_files( char **filenames, uint32_t file_count, int32_t thread_cnt, sdbf_set *addto); sdbf_set *sdbf_hash_stdin( ); void sdbf_hash_files_dd( char **filenames, uint32_t file_count, uint32_t dd_block_size, uint64_t chunk_size, sdbf_set *addto) ; #endif
stiandre/sdhash-integration
sdhash-src/sdhash_threads.h
C
apache-2.0
370
/* * Copyright 2017 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 org.gradle.internal.operations.trace; import com.google.common.collect.ImmutableMap; import org.gradle.internal.operations.OperationIdentifier; import org.gradle.internal.operations.OperationProgressEvent; import java.util.Map; import static org.gradle.internal.operations.trace.BuildOperationTrace.toSerializableModel; class SerializedOperationProgress implements SerializedOperation { final long id; final long time; final Object details; final String detailsClassName; SerializedOperationProgress(OperationIdentifier id, OperationProgressEvent progressEvent) { this.id = id.getId(); this.time = progressEvent.getTime(); this.details = toSerializableModel(progressEvent.getDetails()); this.detailsClassName = details == null ? null : progressEvent.getDetails().getClass().getName(); } SerializedOperationProgress(Map<String, ?> map) { this.id = ((Integer) map.get("id")).longValue(); this.time = (Long) map.get("time"); this.details = map.get("details"); this.detailsClassName = (String) map.get("detailsClassName"); } public Map<String, ?> toMap() { ImmutableMap.Builder<String, Object> map = ImmutableMap.builder(); // Order is optimised for humans looking at the log. if (details != null) { map.put("details", details); map.put("detailsClassName", detailsClassName); } map.put("id", id); map.put("time", time); return map.build(); } }
lsmaira/gradle
subprojects/core/src/main/java/org/gradle/internal/operations/trace/SerializedOperationProgress.java
Java
apache-2.0
2,162
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common Development * and Distribution License("CDDL") (collectively, the "License"). You * may not use this file except in compliance with the License. You can * obtain a copy of the License at * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html * or packager/legal/LICENSE.txt. See the License for the specific * language governing permissions and limitations under the License. * * When distributing the software, include this License Header Notice in each * file and include the License file at packager/legal/LICENSE.txt. * * GPL Classpath Exception: * Oracle designates this particular file as subject to the "Classpath" * exception as provided by Oracle in the GPL Version 2 section of the License * file that accompanied this code. * * Modifications: * If applicable, add the following below the License Header, with the fields * enclosed by brackets [] replaced by your own identifying information: * "Portions Copyright [year] [name of copyright owner]" * * Contributor(s): * If you wish your version of this file to be governed by only the CDDL or * only the GPL Version 2, indicate your decision by adding "[Contributor] * elects to include this software in this distribution under the [CDDL or GPL * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * and therefore, elected the GPL Version 2 license, then the option applies * only if the new code is made subject to such option by the copyright * holder. */ package org.javaee7.cdi.bean.scopes; import javax.enterprise.context.RequestScoped; /** * @author Arun Gupta */ @RequestScoped public class MyApplicationScopedBean { public String getID() { return this + ""; } }
ftomassetti/JavaIncrementalParser
src/test/resources/javaee7-samples/cdi/scopes/src/main/java/org/javaee7/cdi/bean/scopes/MyApplicationScopedBean.java
Java
apache-2.0
2,212
package com.github.anthonime.testbot.definitions.actions; import com.github.anthonime.testbot.definitions.elements.HasElementIdentifier; import java.time.Duration; /** * Created by schio on 9/14/2017. */ public class Actions { public static ActionDefinition click() { return new AbstractActionDefinition(Verb.click, null, null, null); } public static ActionDefinition click(HasElementIdentifier element) { return new AbstractActionDefinition(Verb.click, element.getElementIdentifier(), null, null); } public static ActionDefinition pause(Duration duration) { return new AbstractActionDefinition(Verb.pause, null, null, duration); } //KEYBOARD VERBS //keyDown [elmt] string/keys //keyUp [elmt] string/keys //MOUSE VERBS //click elmt //dragndrop //move from element to element //move by coords //click elmt //rightclick elmt //click //rightclick //middleclick //doubleclick elmt //doubleclick //take elmt (click&hold) //moveBy x,y //moveTo x,y //moveTo elmt //moveTo elmt x,y //release (drop) //releaseOn elmt (dropOn) //drag elmt //drag elmt x,y //drag elmt elmt //dropOn elmt //dropAt x,y //dragNDrop elmt to elmt //dragNDrop elmt by b,y //HIGHLEVEL (no keyboard, no mouse) //pause 5s //any of (keyboard, mouse) //scroll elmt //scrollToVisible elmt }
anthonime/testbot
src/main/java/com/github/anthonime/testbot/definitions/actions/Actions.java
Java
apache-2.0
1,451
/* * Copyright 2012-2013 inBloom, 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 org.slc.sli.api.security.context.validator; import org.slc.sli.api.security.context.PagingRepositoryDelegate; import org.slc.sli.api.util.SecurityUtil; import org.slc.sli.common.constants.EntityNames; import org.slc.sli.common.constants.ParameterConstants; import org.slc.sli.common.util.datetime.DateHelper; import org.slc.sli.domain.Entity; import org.slc.sli.domain.NeutralCriteria; import org.slc.sli.domain.NeutralQuery; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.*; import static org.slc.sli.common.constants.ParameterConstants.STUDENT_RECORD_ACCESS; @Component public class StudentValidatorHelper { @Autowired private DateHelper dateHelper; @Autowired private PagingRepositoryDelegate<Entity> repo; public List<String> getStudentIds() { Entity principal = SecurityUtil.getSLIPrincipal().getEntity(); Set<String> ids = new TreeSet<String>(); ids.addAll(findAccessibleThroughSection(principal)); ids.addAll(findAccessibleThroughCohort(principal)); ids.addAll(findAccessibleThroughProgram(principal)); return new ArrayList<String>(ids); } public List<String> getTeachersSectionIds(Entity teacher) { return getTeachersSectionIds(teacher, true); } public List<String> getTeachersSectionIds(Entity teacher, boolean useGracePeriod) { List<String> sectionIds = new ArrayList<String>(); // teacher -> teacherSectionAssociation NeutralQuery query = new NeutralQuery(new NeutralCriteria(ParameterConstants.TEACHER_ID, NeutralCriteria.OPERATOR_EQUAL, teacher.getEntityId())); Iterable<Entity> teacherSectionAssociations = repo.findAll(EntityNames.TEACHER_SECTION_ASSOCIATION, query); for (Entity assoc : teacherSectionAssociations) { if (!dateHelper.isFieldExpired(assoc.getBody(), ParameterConstants.END_DATE, useGracePeriod)) { sectionIds.add((String) assoc.getBody().get(ParameterConstants.SECTION_ID)); } } return sectionIds; } private List<String> findAccessibleThroughSection(Entity principal) { List<String> sectionIds = getTeachersSectionIds(principal); NeutralQuery query = new NeutralQuery(); query.setLimit(0); query.setOffset(0); query.addCriteria(new NeutralCriteria(ParameterConstants.ID, NeutralCriteria.CRITERIA_IN, sectionIds)); query.setEmbeddedFields(Arrays.asList(EntityNames.STUDENT_SECTION_ASSOCIATION)); Iterable<Entity> sections = repo.findAll(EntityNames.SECTION, query); List<Entity> studentSectionAssociations = new ArrayList<Entity>(); for (Entity section : sections) { Map<String, List<Entity>> embeddedData = section.getEmbeddedData(); if (embeddedData != null) { List<Entity> associations = embeddedData.get(EntityNames.STUDENT_SECTION_ASSOCIATION); if (associations != null) { studentSectionAssociations.addAll(associations); } } } // filter on end_date to get list of students List<String> studentIds = new ArrayList<String>(); for (Entity assoc : studentSectionAssociations) { if (!dateHelper.isFieldExpired(assoc.getBody(), ParameterConstants.END_DATE, true)) { studentIds.add((String) assoc.getBody().get(ParameterConstants.STUDENT_ID)); } } List<String> returnIds = new ArrayList<String>(); returnIds.addAll(studentIds); returnIds.addAll(sectionIds); return returnIds; } private List<String> findAccessibleThroughProgram(Entity principal) { // teacher -> staffProgramAssociation NeutralQuery query = new NeutralQuery(new NeutralCriteria(ParameterConstants.STAFF_ID, NeutralCriteria.OPERATOR_EQUAL, principal.getEntityId())); Iterable<Entity> staffProgramAssociations = repo.findAll(EntityNames.STAFF_PROGRAM_ASSOCIATION, query); // filter on end_date to get list of programIds List<String> programIds = new ArrayList<String>(); for (Entity assoc : staffProgramAssociations) { Object studentRecordAccess = assoc.getBody().get(STUDENT_RECORD_ACCESS); if (studentRecordAccess != null && (Boolean) studentRecordAccess) { if (!dateHelper.isFieldExpired(assoc.getBody(), ParameterConstants.END_DATE, false)) { programIds.add((String) assoc.getBody().get(ParameterConstants.PROGRAM_ID)); } } } // program -> studentProgramAssociation query = new NeutralQuery(new NeutralCriteria(ParameterConstants.PROGRAM_ID, NeutralCriteria.CRITERIA_IN, programIds)); Iterable<Entity> studentProgramAssociations = repo.findAll(EntityNames.STUDENT_PROGRAM_ASSOCIATION, query); // filter on end_date to get list of students List<String> studentIds = new ArrayList<String>(); for (Entity assoc : studentProgramAssociations) { if (!dateHelper.isFieldExpired(assoc.getBody(), ParameterConstants.END_DATE, false)) { studentIds.add((String) assoc.getBody().get(ParameterConstants.STUDENT_ID)); } } List<String> returnIds = new ArrayList<String>(); returnIds.addAll(studentIds); returnIds.addAll(programIds); return returnIds; } private List<String> findAccessibleThroughCohort(Entity principal) { // teacher -> staffCohortAssociation NeutralQuery query = new NeutralQuery(new NeutralCriteria(ParameterConstants.STAFF_ID, NeutralCriteria.OPERATOR_EQUAL, principal.getEntityId())); Iterable<Entity> staffCohortAssociations = repo.findAll(EntityNames.STAFF_COHORT_ASSOCIATION, query); List<String> cohortIds = new ArrayList<String>(); for (Entity assoc : staffCohortAssociations) { Object studentRecordAccess = assoc.getBody().get(STUDENT_RECORD_ACCESS); if (studentRecordAccess != null && (Boolean) assoc.getBody().get(STUDENT_RECORD_ACCESS)) { if (!dateHelper.isFieldExpired(assoc.getBody(), ParameterConstants.END_DATE, false)) { cohortIds.add((String) assoc.getBody().get(ParameterConstants.COHORT_ID)); } } } // cohort -> studentCohortAssociation query = new NeutralQuery(new NeutralCriteria(ParameterConstants.COHORT_ID, NeutralCriteria.CRITERIA_IN, cohortIds)); Iterable<Entity> studentList = repo.findAll(EntityNames.STUDENT_COHORT_ASSOCIATION, query); Set<String> studentIds = new HashSet<String>(); // filter on end_date to get list of students for (Entity student : studentList) { if (!dateHelper.isFieldExpired(student.getBody(), ParameterConstants.END_DATE, false)) { studentIds.add((String) student.getBody().get(ParameterConstants.STUDENT_ID)); } } List<String> returnIds = new ArrayList<String>(); returnIds.addAll(studentIds); returnIds.addAll(cohortIds); return returnIds; } }
inbloom/secure-data-service
sli/api/src/main/java/org/slc/sli/api/security/context/validator/StudentValidatorHelper.java
Java
apache-2.0
7,964
/** * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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. */ import { async, ComponentFixture, TestBed, inject } from '@angular/core/testing'; import { SolveDialogComponent } from './solve-dialog.component'; import { DialogCloseButtonComponent } from '../dialog-close-button/dialog-close-button.component'; import { RadioListComponent } from '../radio-list/radio-list.component'; import { DialogService } from '../dialog.service'; import { By } from '@angular/platform-browser'; import { IncompleteSolutionDialogComponent } from '../incomplete-solution-dialog/incomplete-solution-dialog.component'; import { IncorrectSolutionDialogComponent } from '../incorrect-solution-dialog/incorrect-solution-dialog.component'; import { WinDialogComponent } from '../win-dialog/win-dialog.component'; describe('SolveDialogComponent', () => { let component: SolveDialogComponent; let fixture: ComponentFixture<SolveDialogComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ SolveDialogComponent, DialogCloseButtonComponent, RadioListComponent, ], }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(SolveDialogComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should open incomplete solution dialog', inject( [DialogService], (dialogService: DialogService) => { spyOn(dialogService, 'open'); fixture.debugElement.query( By.css('input[type="radio"][value="Mrs. Bluejay"]') ).nativeElement.click(); fixture.debugElement.query(By.css('.submit-button')).nativeElement.click(); expect(dialogService.open).toHaveBeenCalledWith(IncompleteSolutionDialogComponent); } )); it('should open incorrect solution dialog', inject( [DialogService], (dialogService: DialogService) => { spyOn(dialogService, 'open'); fixture.debugElement.query( By.css('input[type="radio"][value="Mrs. Bluejay"]') ).nativeElement.click(); fixture.debugElement.query( By.css('input[type="radio"][value="Living Room"]') ).nativeElement.click(); fixture.debugElement.query( By.css('input[type="radio"][value="A Hollow Bible"]') ).nativeElement.click(); fixture.debugElement.query(By.css('.submit-button')).nativeElement.click(); expect(dialogService.open).toHaveBeenCalledWith(IncorrectSolutionDialogComponent); } )); it('should open win dialog', inject( [DialogService], (dialogService: DialogService) => { spyOn(dialogService, 'open'); fixture.debugElement.query( By.css('input[type="radio"][value="Professor Pluot"]') ).nativeElement.click(); fixture.debugElement.query( By.css('input[type="radio"][value="Living Room"]') ).nativeElement.click(); fixture.debugElement.query( By.css('input[type="radio"][value="A Hollow Bible"]') ).nativeElement.click(); fixture.debugElement.query(By.css('.submit-button')).nativeElement.click(); expect(dialogService.open).toHaveBeenCalledWith(WinDialogComponent); } )); it('should close the dialog when "No" button is clicked', inject( [DialogService], async (dialogService: DialogService) => { let resetCalled = false; fixture.debugElement.nativeElement.addEventListener('reset', () => { resetCalled = true; }); spyOn(dialogService, 'close'); fixture.debugElement.query( By.css('input[type="radio"][value="Professor Pluot"]') ).nativeElement.click(); fixture.debugElement.query( By.css('input[type="radio"][value="Living Room"]') ).nativeElement.click(); fixture.debugElement.query( By.css('input[type="radio"][value="A Hollow Bible"]') ).nativeElement.click(); fixture.debugElement.query(By.css('.cancel-button')).nativeElement.click(); expect(dialogService.close).toHaveBeenCalled(); expect(resetCalled).toBe(true); } )); });
google/mysteryofthreebots
src/app/solve-dialog/solve-dialog.component.spec.ts
TypeScript
apache-2.0
4,680
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package model; import java.util.Calendar; /** * * @author Jonas */ public class Week { private int id; private Calendar cal; private Weekday[] weekdays; public Week(int id, Calendar cal, Weekday[] weekdays) { this.id = id; this.cal = cal; this.weekdays = weekdays; } public int getId() { return id; } public int getDate() { return cal.get(Calendar.WEEK_OF_YEAR); } public Calendar getCal() { return cal; } public Weekday[] getWeekdays() { return weekdays; } @Override public String toString() { return getDate() + " (" + cal.get(Calendar.YEAR) + ")"; } }
Joasis/WeeklyFoodPlanner
src/model/Week.java
Java
apache-2.0
926
Folders ============= This node.js package implements the folders.io synthetic file system. This Folders Module is directly connecting to The HiveServer2 using thrift. The Thrift interface definition language (IDL) for HiveServer2 is available at https://github.com/apache/hive/blob/trunk/service/if/TCLIService.thrift. Thrift documentation is available at http://thrift.apache.org/docs/. Module can be installed via "npm install folders-hive". ##Folders-hive Basic Usage ### Configuration In order to connect to HiveServer2, specify the following args. ```json { "host" : "hive_server2_hostname", "port" : "hive_server2_port", "username" : "conn_username", "password" : "conn_password", "auth" : "nosasl" } ``` **Auth mode** we now support only 'None'(uses plain SASL), NOSASL Authentication. [HiveServer2 Authentication/Security Configuration](https://cwiki.apache.org/confluence/display/Hive/Setting+Up+HiveServer2#SettingUpHiveServer2-Authentication/SecurityConfiguration) ### Constructor Provider constuctor, could pass the special option/param in the config param. ```js var prefix = 'folders.io_0:hive'; var config = { "host" : "hive_server2_hostname", "port" : "hive_server2_port", "username" : "conn_username", "password" : "conn_password", "auth" : "nosasl" }; var foldersHive = new FoldersHive(prefix, config); ``` ### ls ls the database, tables as folders. ```js /** * list db metadata in folders.io format * * @param uri, * the uri for db. /${database}/${table}/ eg: * <li>'/' , show the root path, show the databases/schemas</li> * <li>'/test-db', show all the tables in database 'test-db' </li> * <li>'/test-db/test-table', show the metadata of table we support 'test-table' in database 'test-db';</li> * all the path could also start with {prefix}, '/folders.io_0:hive/test-db' * @param cb, * callback function(err, result) function. result will be a file info array. [{}, ... {}] <br> * a example file information <code> * { * name: 'default', * fullPath: 'default', * meta: {}, * uri: 'folders.io_0:hive/default', * size: 0, * extension: '+folder', * modificationTime: 0 * } * </code> */ FoldersHive.prototype.ls = function(path, cb) foldersHive.ls('/', function cb(error, databases) { if (error) { console.log("error in ls /"); console.log(error); } console.log("ls databases success, ", databases); }; ``` ### Cat cat columns metadata,records or create sql of the specified table. ```js /** * @param uri, the file uri to cat * @param cb, callback function(err, result) function. * example for result. * { * stream: .., // a readable 'request' stream * size : .. , // file size * name: path * } * * cat(uri,cb) */ foldersHive.cat('/folders/test/columns.md', function cb(error,columns) { if (error) { console.log('error in cat table columns'); console.log(error); } console.log('cat table columns success, \n', columns); }); ``` currently we support three types of files. ['columns.md', 'create_table.md', 'select.md'] - 'columns.md' The file data will be a markdown table, show the metadata of columns, include the column type, name, nullable... ```txt | TABLE_SCHEM | TABLE_NAME | COLUMN_NAME | TYPE_NAME | IS_NULLABLE | | ----------- | ---------- | ----------- | --------- | ----------- | | folders | test | col1 | STRING | YES | | folders | test | col2 | STRING | YES | ``` - 'create_table.md' The file data will be a sql, show the create sql statement of the table. ```sql CREATE EXTERNAL TABLE `folders.test`( `col1` string, `col2` string) ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' STORED AS INPUTFORMAT 'org.apache.hadoop.mapred.TextInputFormat' OUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat' LOCATION 'hdfs://cluster-1-m:8020/tmp/example' TBLPROPERTIES ( 'COLUMN_STATS_ACCURATE'='false', 'numFiles'='0', 'numRows'='-1', 'rawDataSize'='-1', 'totalSize'='0', 'transient_lastDdlTime'='1452669800') ``` - select.md The file show a **limited number(10)** rows of the table records. ```txt | test.col1 | test.col2 | | --------- | --------- | | row1-col1 | row1-col2 | | row2-col1 | row2-col2 | ```
foldersjs/folders-hive
README.md
Markdown
apache-2.0
4,489
<?php namespace Numbers\Users\Users\Helper; class Roles { /** * Create role * * @param array $data * @param array $organizations * @return bool */ public static function createRole(array $data, array $organizations) : bool { // create role $role = \Numbers\Users\Users\Model\Roles::getStatic([ 'where' => [ 'um_role_code' => $data['um_role_code'] ], 'pk' => null, 'single_row' => true, ]); if (empty($role)) { $temp = \Numbers\Users\Users\Model\Roles::collectionStatic()->merge($data); $role['um_role_id'] = $temp['new_serials']['um_role_id']; } // add new organizations to roles $old_role_organizations = \Numbers\Users\Users\Model\Role\Organizations::getStatic([ 'where' => [ 'um_rolorg_role_id' => $role['um_role_id'], ], 'pk' => ['um_rolorg_organization_id'] ]); $all_roles = array_unique(array_merge($organizations, array_keys($old_role_organizations))); foreach ($all_roles as $k => $v) { \Numbers\Users\Users\Model\Role\Organizations::collectionStatic()->merge([ 'um_rolorg_role_id' => $role['um_role_id'], 'um_rolorg_organization_id' => $v, 'um_rolorg_inactive' => 0 ]); } return true; } }
volodymyr-volynets/users
Users/Helper/Roles.php
PHP
apache-2.0
1,191
/* * Copyright (C) Lightbend Inc. <https://www.lightbend.com> */ package com.lightbend.lagom.internal.server.status; import com.codahale.metrics.Snapshot; import com.lightbend.lagom.internal.client.CircuitBreakerMetricsImpl; import com.lightbend.lagom.internal.client.CircuitBreakerMetricsProviderImpl; import com.lightbend.lagom.internal.spi.CircuitBreakerMetricsProvider; import akka.NotUsed; import com.lightbend.lagom.javadsl.api.ServiceCall; import com.lightbend.lagom.javadsl.api.transport.NotFound; import com.lightbend.lagom.javadsl.server.status.CircuitBreakerStatus; import com.lightbend.lagom.javadsl.server.status.Latency; import com.lightbend.lagom.javadsl.server.status.MetricsService; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.concurrent.CompletableFuture; import javax.inject.Inject; import akka.actor.ActorSystem; import akka.stream.javadsl.Source; public class MetricsServiceImpl implements MetricsService { private final Optional<CircuitBreakerMetricsProviderImpl> provider; @Inject public MetricsServiceImpl(CircuitBreakerMetricsProvider metricsProvider, ActorSystem system) { // TODO it would be better to do this in ServiceGuiceSupport.bindService, // but I'm not sure how to access config from there boolean statusEnabled = system.settings().config().getBoolean("lagom.status-endpoint.enabled"); if (statusEnabled && metricsProvider instanceof CircuitBreakerMetricsProviderImpl) provider = Optional.of((CircuitBreakerMetricsProviderImpl) metricsProvider); else provider = Optional.empty(); } @Override public ServiceCall<NotUsed, List<CircuitBreakerStatus>> currentCircuitBreakers() { return request -> { if (!provider.isPresent()) throw new NotFound("No metrics"); return CompletableFuture.completedFuture(allCircuitBreakerStatus()); }; } @Override public ServiceCall<NotUsed, Source<List<CircuitBreakerStatus>, ?>> circuitBreakers() { return request -> { if (!provider.isPresent()) throw new NotFound("No metrics"); Source<List<CircuitBreakerStatus>, ?> source = Source.tick(Duration.ofMillis(100), Duration.ofSeconds(2), "tick") .map(tick -> allCircuitBreakerStatus()); return CompletableFuture.completedFuture(source); }; } private List<CircuitBreakerStatus> allCircuitBreakerStatus() { List<CircuitBreakerStatus> all = new ArrayList<>(); for (CircuitBreakerMetricsImpl m : provider.get().allMetrics()) { try { all.add(circuitBreakerStatus(m)); } catch (Exception e) { // might happen if the circuit breaker is removed, just ignore } } return all; } private CircuitBreakerStatus circuitBreakerStatus(CircuitBreakerMetricsImpl m) { Snapshot latencyHistogram = m.latency().getSnapshot(); Latency latency = Latency.builder() .median(latencyHistogram.getMedian()) .percentile98th(latencyHistogram.get98thPercentile()) .percentile99th(latencyHistogram.get99thPercentile()) .percentile999th(latencyHistogram.get999thPercentile()) .min(latencyHistogram.getMin()) .max(latencyHistogram.getMax()) .mean(latencyHistogram.getMean()) .build(); return CircuitBreakerStatus.builder() .id(m.breakerId()) .state(m.state().getValue()) .totalSuccessCount(m.successCount().getCount()) .totalFailureCount(m.failureCount().getCount()) .throughputOneMinute(m.throughput().getOneMinuteRate()) .failedThroughputOneMinute(m.failureThroughput().getOneMinuteRate()) .latencyMicros(latency) .build(); } }
lagom/lagom
service/javadsl/server/src/main/java/com/lightbend/lagom/internal/server/status/MetricsServiceImpl.java
Java
apache-2.0
3,752
package com.projects.benjisora.tubapp.adapter; import android.graphics.Color; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.amulyakhare.textdrawable.TextDrawable; import com.like.LikeButton; import com.like.OnLikeListener; import com.projects.benjisora.tubapp.R; import com.projects.benjisora.tubapp.data.database.Utils; import com.projects.benjisora.tubapp.data.model.Favorites; import com.projects.benjisora.tubapp.data.model.Path; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; /** * Adapter class for the RecyclerView's {@link com.projects.benjisora.tubapp.fragment.SchedulesFragment} */ public class SchedulesAdapter extends RecyclerView.Adapter<SchedulesAdapter.MySchedulesViewHolder> { private List<Path> list; /** * Default constructor. * Initializes the list with the database */ public SchedulesAdapter() { list = Utils.getinstance().getAllPaths(); } /** * {@inheritDoc} */ @Override public MySchedulesViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // create a new view View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.schedules_item, parent, false); return new MySchedulesViewHolder(view); } /** * {@inheritDoc} * <p> * Binds every ressource to the corresponding holder on the RecyclerView */ @Override public void onBindViewHolder(final MySchedulesViewHolder holder, int position) { holder.titleTextView.setText(list.get(position).getLabel()); if (Utils.getinstance().pathIsFav(list.get(position).getId())) { holder.likeImageView.setLiked(true); } else { holder.likeImageView.setLiked(false); } TextDrawable drawable = TextDrawable.builder() .buildRect(String.valueOf(list.get(position).getNumber()), Color.parseColor(list.get(position).getColor())); holder.backgroundImageView.setImageDrawable(drawable); } /** * {@inheritDoc} */ @Override public int getItemCount() { return list.size(); } /** * Class destined to be held by the RecyclerView, and will represent the list's rows */ class MySchedulesViewHolder extends RecyclerView.ViewHolder { @BindView(R.id.titleTextView) TextView titleTextView; @BindView(R.id.backgroundImageView) ImageView backgroundImageView; @BindView(R.id.likeImageView) LikeButton likeImageView; /** * Default constructor. * Creates the view and sets the click listeners */ MySchedulesViewHolder(View v) { super(v); ButterKnife.bind(this, v); /* // Commented due to the lack of Schedules on the API server. // The DetailsActivity is useless until schedules are set on the server v.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Context context = view.getContext(); Intent intent = new Intent(context, DetailsActivity.class); context.startActivity(intent); } }); */ likeImageView.setOnLikeListener(new OnLikeListener() { @Override public void liked(LikeButton likeButton) { Favorites fav = new Favorites(); fav.setId_path(list.get(getAdapterPosition()).getId()); fav.save(); } @Override public void unLiked(LikeButton likeButton) { Utils.getinstance().getFavorite(list.get(getAdapterPosition()).getId()).delete(); } }); } } }
benjisora/Tub
TubApp/app/src/main/java/com/projects/benjisora/tubapp/adapter/SchedulesAdapter.java
Java
apache-2.0
4,065