repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
srotya/sidewinder
core/src/main/java/com/srotya/sidewinder/core/storage/DataPoint.java
1941
/** * Copyright Ambud Sharma * * 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.srotya.sidewinder.core.storage; import java.io.Serializable; import java.util.Date; /** * Object representation of a {@link DataPoint}. This class services DAO and DTO * needs inside Sidewinder. * * @author ambud */ public class DataPoint implements Serializable { private static final long serialVersionUID = 1L; private long timestamp; private long value; public DataPoint() { } public DataPoint(long timestamp, long value) { this.timestamp = timestamp; this.value = value; } public DataPoint(long timestamp, double value) { this.timestamp = timestamp; setValue(value); } /** * @return the timestamp */ public long getTimestamp() { return timestamp; } /** * @param timestamp * the timestamp to set */ public void setTimestamp(long timestamp) { this.timestamp = timestamp; } /** * @return */ public long getLongValue() { return value; } /** * @return the value */ public double getValue() { return Double.longBitsToDouble(value); } public void setValue(double value) { this.value = Double.doubleToLongBits(value); } /** * @param value * the value to set */ public void setLongValue(long value) { this.value = value; } @Override public String toString() { return "[ts:" + new Date(timestamp) + " v:" + value + "]"; } }
apache-2.0
Otsimo/distribution
db/mongodb/tarball.go
1366
package mongodb import ( "github.com/otsimo/distribution/models" mgo "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" ) type tarballRepo struct { driver *MongoDBDriver } func (m *tarballRepo) Put(d models.TarballUrl) error { c := m.driver.Session.DB("").C(TarballCollection) ls, _ := m.All(d.GameID, d.Version) if len(ls) > 0 { for _, t := range ls { if t.Storage == d.Storage { return models.ErrorDuplicateTarball } } } return toOtsimoError(c.Insert(d)) } func (m *tarballRepo) All(gameId string, version string) ([]*models.TarballUrl, error) { c := m.driver.Session.DB("").C(TarballCollection) all := []*models.TarballUrl{} if err := c.Find(bson.M{"game_id": gameId, "version": version}).All(&all); err != nil { if err == mgo.ErrNotFound { return nil, models.ErrorNotFound } return nil, err } if len(all) == 0 { return nil, models.ErrorNotFound } return all, nil } func (m *tarballRepo) One(gameId string, version string) (*models.TarballUrl, error) { c := m.driver.Session.DB("").C(TarballCollection) one := models.TarballUrl{} if err := c.Find(bson.M{"game_id": gameId, "version": version}).One(&one); err != nil { if err == mgo.ErrNotFound { return nil, models.ErrorNotFound } return nil, err } return &one, nil } func newTarballRepo(d *MongoDBDriver) *tarballRepo { return &tarballRepo{ driver: d, } }
apache-2.0
marius-bardan/encryptedprefs
library/src/main/java/ro/omen/encryptedprefs/utils/FixedSecureRandom.java
492
package ro.omen.encryptedprefs.utils; import java.security.SecureRandom; /** * Child implementation of SecureRandom that runs the needed fix before generating byte arrays. * Client code should only use nextBytes (as it's the only method using the fix). * {@see SecureRandomFix} */ public class FixedSecureRandom extends SecureRandom { @Override public synchronized void nextBytes(byte[] bytes) { SecureRandomFix.tryApplyFixes(); super.nextBytes(bytes); } }
apache-2.0
somi92/eKlub
src/main/java/rs/fon/eklub/controllers/CategoryController.java
2262
/* * 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 rs.fon.eklub.controllers; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Component; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import rs.fon.eklub.constants.ServiceAPI; import rs.fon.eklub.core.entities.Category; import rs.fon.eklub.core.exceptions.ServiceException; import rs.fon.eklub.core.services.CategoryService; import rs.fon.eklub.envelopes.ServiceResponse; /** * * @author milos */ @RestController @Component public class CategoryController { private CategoryService interactor; @Autowired public CategoryController(CategoryService interactor) { this.interactor = interactor; } @PreAuthorize(value = "#oauth2.hasAnyScope('global')") @RequestMapping(value = ServiceAPI.Category.GET_ALL_CATEGORIES, method = RequestMethod.GET) public ResponseEntity getAllCategories() throws ServiceException { List<Category> categories = interactor.getAllCategories(); HttpStatus httpStatus = null; String responseMessage = null; if(categories.size() <= 0) { httpStatus = HttpStatus.NOT_FOUND; responseMessage = ServiceAPI.DefaultResponseMessages.RESOURCE_NOT_FOUND; } else { httpStatus = HttpStatus.OK; responseMessage = ServiceAPI.DefaultResponseMessages.RESOURCE_FOUND; } ServiceResponse<List<Category>> response = new ServiceResponse(); response.setStatus(httpStatus.toString()); response.setMessage(responseMessage); response.setRequestUri(ServiceAPI.Category.GET_ALL_CATEGORIES); response.setPayload(categories); return new ResponseEntity<>(response, httpStatus); } }
apache-2.0
openprocurement/openprocurement.edge
openprocurement/edge/couch_views/auctions/views/real_by_dateModified/map.js
391
function(doc) { if(doc.doc_type == 'Auction' && doc.status != 'draft' && !doc.mode) { var fields=['auctionPeriod', 'status', 'auctionID', 'lots', 'procurementMethodType', 'next_check'], data={}; for (var i in fields) { if (doc[fields[i]]) { data[fields[i]] = doc[fields[i]] } } emit(doc.dateModified, data); } }
apache-2.0
toddfast/mutagen-cassandra
src/main/java/com/toddfast/mutagen/cassandra/CassandraMutagen.java
381
package com.toddfast.mutagen.cassandra; import com.netflix.astyanax.Keyspace; import com.toddfast.mutagen.Plan; import java.io.IOException; /** * * * @author Todd Fast */ public interface CassandraMutagen { /** * * */ public void initialize(String rootResourcePath) throws IOException; /** * * */ public Plan.Result<Integer> mutate(Keyspace keyspace); }
apache-2.0
TanayParikh/foam2
src/foam/dao/LastModifiedAwareDAO.java
406
/** * @license * Copyright 2017 The FOAM Authors. All Rights Reserved. * http://www.apache.org/licenses/LICENSE-2.0 */ package foam.dao; import foam.dao.*; import foam.core.*; import java.util.Date; public class LastModifiedAwareDAO extends ProxyDAO { public FObject put_(X x, FObject value) { ((LastModifiedAware) value).setLastModified(new Date()); return super.put_(x, value); } }
apache-2.0
woosungpil/epcis
epcis-client/src/main/java/org/oliot/epcis_client/VocabularyType.java
1522
package org.oliot.epcis_client; /** * Copyright (C) 2014-16 Jaewook Byun * * This project is part of Oliot (oliot.org), pursuing the implementation of * Electronic Product Code Information Service(EPCIS) v1.1 specification in * EPCglobal. * [http://www.gs1.org/gsmp/kc/epcglobal/epcis/epcis_1_1-standard-20140520.pdf] * * * @author Jaewook Jack Byun, Ph.D student * * Korea Advanced Institute of Science and Technology (KAIST) * * Real-time Embedded System Laboratory(RESL) * * bjw0829@kaist.ac.kr, bjw0829@gmail.com */ // See EPCIS v1.1 857 line public enum VocabularyType { ReadPointID("urn:epcglobal:epcis:vtype:ReadPoint"), BusinessLocationID( "urn:epcglobal:epcis:vtype:BusinessLocation"), BusinessStepID( "urn:epcglobal:epcis:vtype:BusinessStep"), DispositionID( "urn:epcglobal:epcis:vtype:Disposition"), BusinessTransaction( "urn:epcglobal:epcis:vtype:BusinessTransaction"), BusinessTrasactionTypeID( "urn:epcglobal:epcis:vtype:BusinessTransactionType"), SourceDestTypeID( "urn:epcglobal:epcis:vtype:SourceDestType"), SourceDestID( "urn:epcglobal:epcis:vtype:SourceDest"), EPCClass( "urn:epcglobal:epcis:vtype:EPCClass"), EPCInstance( "urn:epcglobal:epcis:vtype:EPCInstance"); private String vocabularyType; private VocabularyType(String vocabularyType) { this.vocabularyType = vocabularyType; } public String getVocabularyType() { return vocabularyType; } }
apache-2.0
Nickname0806/Test_Q4
test/org/apache/catalina/webresources/TestJarInputStreamWrapper.java
4662
/* * 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.catalina.webresources; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; import java.util.jar.JarFile; import java.util.zip.ZipEntry; import org.junit.Assert; import org.junit.Test; import org.apache.catalina.WebResource; public class TestJarInputStreamWrapper { @Test public void testReadAfterClose() throws Exception { Method m = InputStream.class.getMethod("read", (Class<?>[]) null); testMethodAfterClose(m, (Object[]) null); } @Test public void testSkipAfterClose() throws Exception { Method m = InputStream.class.getMethod("skip", long.class); testMethodAfterClose(m, Long.valueOf(1)); } @Test public void testAvailableAfterClose() throws Exception { Method m = InputStream.class.getMethod("available", (Class<?>[]) null); testMethodAfterClose(m, (Object[]) null); } @Test public void testCloseAfterClose() throws Exception { Method m = InputStream.class.getMethod("close", (Class<?>[]) null); testMethodAfterClose(m, (Object[]) null); } @Test public void testMarkAfterClose() throws Exception { Method m = InputStream.class.getMethod("mark", int.class); testMethodAfterClose(m, Integer.valueOf(1)); } @Test public void testResetAfterClose() throws Exception { Method m = InputStream.class.getMethod("reset", (Class<?>[]) null); testMethodAfterClose(m, (Object[]) null); } @Test public void testMarkSupportedAfterClose() throws Exception { Method m = InputStream.class.getMethod("markSupported", (Class<?>[]) null); testMethodAfterClose(m, (Object[]) null); } private void testMethodAfterClose(Method m, Object... params) throws IOException { InputStream unwrapped = getUnwrappedClosedInputStream(); InputStream wrapped = getWrappedClosedInputStream(); Object unwrappedReturn = null; Exception unwrappedException = null; Object wrappedReturn = null; Exception wrappedException = null; try { unwrappedReturn = m.invoke(unwrapped, params); } catch (Exception e) { unwrappedException = e; } try { wrappedReturn = m.invoke(wrapped, params); } catch (Exception e) { wrappedException = e; } if (unwrappedReturn == null) { Assert.assertNull(wrappedReturn); } else { Assert.assertNotNull(wrappedReturn); Assert.assertEquals(unwrappedReturn, wrappedReturn); } if (unwrappedException == null) { Assert.assertNull(wrappedException); } else { Assert.assertNotNull(wrappedException); Assert.assertEquals(unwrappedException.getClass(), wrappedException.getClass()); } } private InputStream getUnwrappedClosedInputStream() throws IOException { File file = new File("test/webresources/non-static-resources.jar"); JarFile jarFile = new JarFile(file); ZipEntry jarEntry = jarFile.getEntry("META-INF/MANIFEST.MF"); InputStream unwrapped = jarFile.getInputStream(jarEntry); unwrapped.close(); jarFile.close(); return unwrapped; } private InputStream getWrappedClosedInputStream() throws IOException { StandardRoot root = new StandardRoot(); root.setCachingAllowed(false); JarResourceSet jarResourceSet = new JarResourceSet(root, "/", "test/webresources/non-static-resources.jar", "/"); WebResource webResource = jarResourceSet.getResource("/META-INF/MANIFEST.MF"); InputStream wrapped = webResource.getInputStream(); wrapped.close(); return wrapped; } }
apache-2.0
multi-os-engine/moe-core
moe.apple/moe.platform.ios/src/main/java/apple/uikit/protocol/UIAccessibilityContainerDataTableCell.java
1031
package apple.uikit.protocol; import apple.foundation.struct.NSRange; import org.moe.natj.general.ann.ByValue; import org.moe.natj.general.ann.Generated; import org.moe.natj.general.ann.Library; import org.moe.natj.general.ann.Runtime; import org.moe.natj.objc.ObjCRuntime; import org.moe.natj.objc.ann.ObjCProtocolName; import org.moe.natj.objc.ann.Selector; /** * The UIAccessibilityContainerDataTable and UIAccessibilityContainerDataTableCell protocols * convey more information specific to tables that contain structured data. */ @Generated @Library("UIKit") @Runtime(ObjCRuntime.class) @ObjCProtocolName("UIAccessibilityContainerDataTableCell") public interface UIAccessibilityContainerDataTableCell { @Generated @Selector("accessibilityColumnRange") @ByValue NSRange accessibilityColumnRange(); /** * The row/column index + the row/column span. * default == { NSNotFound, 0 } */ @Generated @Selector("accessibilityRowRange") @ByValue NSRange accessibilityRowRange(); }
apache-2.0
bit-zyl/Alluxio-Nvdimm
core/common/src/main/java/alluxio/RuntimeConstants.java
1648
/* * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0 * (the "License"). You may not use this work except in compliance with the License, which is * available at www.apache.org/licenses/LICENSE-2.0 * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied, as more fully set forth in the License. * * See the NOTICE file distributed with this work for information regarding copyright ownership. */ package alluxio; /** * System constants that are determined during runtime. */ public final class RuntimeConstants { static { VERSION = Configuration.get(PropertyKey.VERSION); if (Configuration.get(PropertyKey.VERSION).endsWith("SNAPSHOT")) { ALLUXIO_DOCS_URL = "http://www.alluxio.org/docs/master"; } else { String[] majorMinor = Configuration.get(PropertyKey.VERSION).split("\\."); ALLUXIO_DOCS_URL = String.format( "http://www.alluxio.org/docs/%s.%s", majorMinor[0], majorMinor[1]); } } /** The version of this Alluxio instance. */ public static final String VERSION; /** The relative path to the Alluxio target jar. */ public static final String ALLUXIO_JAR = "target/alluxio-" + VERSION + "-jar-with-dependencies.jar"; /** The URL of Alluxio documentation for this version on project web site. */ public static final String ALLUXIO_DOCS_URL; /** The URL of Alluxio debugging documentation. */ public static final String ALLUXIO_DEBUG_DOCS_URL = ALLUXIO_DOCS_URL + "/en/Debugging-Guide.html"; private RuntimeConstants() {} // prevent instantiation }
apache-2.0
googleinterns/knative-source-mongodb
pkg/client/injection/client/fake/fake.go
1705
/* Copyright 2020 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Code generated by injection-gen. DO NOT EDIT. package fake import ( context "context" fake "github.com/googleinterns/knative-source-mongodb/pkg/client/clientset/versioned/fake" client "github.com/googleinterns/knative-source-mongodb/pkg/client/injection/client" runtime "k8s.io/apimachinery/pkg/runtime" rest "k8s.io/client-go/rest" injection "knative.dev/pkg/injection" logging "knative.dev/pkg/logging" ) func init() { injection.Fake.RegisterClient(withClient) } func withClient(ctx context.Context, cfg *rest.Config) context.Context { ctx, _ = With(ctx) return ctx } func With(ctx context.Context, objects ...runtime.Object) (context.Context, *fake.Clientset) { cs := fake.NewSimpleClientset(objects...) return context.WithValue(ctx, client.Key{}, cs), cs } // Get extracts the Kubernetes client from the context. func Get(ctx context.Context) *fake.Clientset { untyped := ctx.Value(client.Key{}) if untyped == nil { logging.FromContext(ctx).Panic( "Unable to fetch github.com/googleinterns/knative-source-mongodb/pkg/client/clientset/versioned/fake.Clientset from context.") } return untyped.(*fake.Clientset) }
apache-2.0
multi-os-engine/moe-core
moe.apple/moe.platform.ios/src/main/java/apple/sensorkit/enums/SRNotificationEvent.java
1597
package apple.sensorkit.enums; import org.moe.natj.general.ann.Generated; import org.moe.natj.general.ann.NInt; @Generated public final class SRNotificationEvent { @Generated private SRNotificationEvent() { } @Generated @NInt public static final long Unknown = 0x0000000000000000L; @Generated @NInt public static final long Received = 0x0000000000000001L; @Generated @NInt public static final long DefaultAction = 0x0000000000000002L; @Generated @NInt public static final long SupplementaryAction = 0x0000000000000003L; @Generated @NInt public static final long Clear = 0x0000000000000004L; @Generated @NInt public static final long NotificationCenterClearAll = 0x0000000000000005L; @Generated @NInt public static final long Removed = 0x0000000000000006L; @Generated @NInt public static final long Hide = 0x0000000000000007L; @Generated @NInt public static final long LongLook = 0x0000000000000008L; @Generated @NInt public static final long Silence = 0x0000000000000009L; @Generated @NInt public static final long AppLaunch = 0x000000000000000AL; @Generated @NInt public static final long Expired = 0x000000000000000BL; @Generated @NInt public static final long BannerPulldown = 0x000000000000000CL; @Generated @NInt public static final long TapCoalesce = 0x000000000000000DL; @Generated @NInt public static final long Deduped = 0x000000000000000EL; @Generated @NInt public static final long DeviceActivated = 0x000000000000000FL; @Generated @NInt public static final long DeviceUnlocked = 0x0000000000000010L; }
apache-2.0
Coreoz/Plume-file
plume-file-core/src/main/java/com/coreoz/plume/file/db/FileDao.java
669
package com.coreoz.plume.file.db; import com.querydsl.core.types.EntityPath; import com.querydsl.core.types.dsl.NumberPath; public interface FileDao { FileEntry upload(String fileType, byte[] fileData, String fileName); long delete(Long fileId); /** * Fetch the file name corresponding to the file identifier. * * @return The file name if the file exists and the file name is not null. * If the file name is null an empty string is returned. * If the file is null, null is returned */ String fileName(Long fileId); FileEntry findById(Long fileId); Long deleteUnreferenced(String fileType, EntityPath<?> fileEntity, NumberPath<Long> column); }
apache-2.0
stdlib-js/stdlib
lib/node_modules/@stdlib/stats/base/dists/hypergeometric/stdev/benchmark/benchmark.js
1433
/** * @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 bench = require( '@stdlib/bench' ); var floor = require( '@stdlib/math/base/special/floor' ); var randu = require( '@stdlib/random/base/randu' ); var ceil = require( '@stdlib/math/base/special/ceil' ); var isnan = require( '@stdlib/math/base/assert/is-nan' ); var pkg = require( './../package.json' ).name; var stdev = require( './../lib' ); // MAIN // bench( pkg, function benchmark( b ) { var N; var K; var n; var y; var i; b.tic(); for ( i = 0; i < b.iterations; i++ ) { N = ceil( randu()*100.0 ) + 1.0; K = floor( randu()*N ); n = floor( randu()*N ); y = stdev( N, K, n ); if ( isnan( y ) ) { b.fail( 'should not return NaN' ); } } b.toc(); if ( isnan( y ) ) { b.fail( 'should not return NaN' ); } b.pass( 'benchmark finished' ); b.end(); });
apache-2.0
dylan-foundry/DeftIDEA
gen/org/dylanfoundry/deft/filetypes/dylan/psi/DylanSubstitution.java
530
// This is a generated file. Not intended for manual editing. package org.dylanfoundry.deft.filetypes.dylan.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface DylanSubstitution extends DylanCompositeElement { @Nullable DylanNamePrefix getNamePrefix(); @Nullable DylanNameStringOrSymbol getNameStringOrSymbol(); @Nullable DylanNameSuffix getNameSuffix(); @Nullable DylanSeparator getSeparator(); @Nullable DylanWordName getWordName(); }
apache-2.0
utcompling/fieldspring
src/main/java/opennlp/fieldspring/tr/app/BaseApp.java
19845
/* * Base app for running resolvers and/or other functionality such as evaluation and visualization generation. */ package opennlp.fieldspring.tr.app; import org.apache.commons.cli.*; import opennlp.fieldspring.tr.topo.*; import java.io.*; public class BaseApp { private Options options = new Options(); private String inputPath = null; private String additionalInputPath = null; private String graphInputPath = null; private String outputPath = null; private String xmlInputPath = null; private String kmlOutputPath = null; private String dKmlOutputPath = null; private String logFilePath = null; private boolean outputGoldLocations = false; private boolean outputUserKML = false; protected boolean useGoldToponyms = false; private String geoGazetteerFilename = null; private String serializedGazetteerPath = null; private String serializedCorpusInputPath = null; private String serializedCorpusOutputPath = null; private String maxentModelDirInputPath = null; private String marketProbPath = null; private String articleInfoPath = null; private String linkPath = null; private double popComponentCoefficient = 0.0; private boolean dgProbOnly = false; private boolean meProbOnly = false; private boolean doOracleEval = false; private int sentsPerDocument = -1; private boolean highRecallNER = false; private Region boundingBox = null; protected boolean doKMeans = false; private String graphOutputPath = null; private String seedOutputPath = null; private String wikiInputPath = null; private String stoplistInputPath = null; private int numIterations = 1; private boolean readWeightsFromFile = false; private int knnForLP = -1; private double dpc = 10; private double threshold = -1.0; // sentinel value indicating NOT to use threshold, not real default public static enum RESOLVER_TYPE { RANDOM, POPULATION, BASIC_MIN_DIST, WEIGHTED_MIN_DIST, DOC_DIST, TOPO_AS_DOC_DIST, LABEL_PROP, LABEL_PROP_DEFAULT_RULE, LABEL_PROP_CONTEXT_SENSITIVE, LABEL_PROP_COMPLEX, MAXENT, PROB, BAYES_RULE, CONSTRUCTION_TPP, ACO_TPP, HEURISTIC_TPP } protected Enum<RESOLVER_TYPE> resolverType = RESOLVER_TYPE.BASIC_MIN_DIST; public static enum CORPUS_FORMAT { PLAIN, TRCONLL, GEOTEXT, WIKITEXT } protected Enum<CORPUS_FORMAT> corpusFormat = CORPUS_FORMAT.PLAIN; protected void initializeOptionsFromCommandLine(String[] args) throws Exception { options.addOption("i", "input", true, "input path"); options.addOption("ix", "input-xml", true, "xml input path"); options.addOption("im", "input-models", true, "maxent model input directory"); options.addOption("ia", "input-additional", true, "path to additional input data to be used in training but not evaluation"); options.addOption("ig", "input-graph", true, "path to input graph for label propagation resolvers"); options.addOption("r", "resolver", true, "resolver (RandomResolver, BasicMinDistResolver, WeightedMinDistResolver, LabelPropDefaultRuleResolver, LabelPropContextSensitiveResolver, LabelPropComplexResolver) [default = BasicMinDistResolver]"); options.addOption("it", "iterations", true, "number of iterations for iterative models [default = 1]"); options.addOption("rwf", "read-weights-file", false, "read initial weights from probToWMD.dat"); options.addOption("o", "output", true, "output path"); options.addOption("ok", "output-kml", true, "kml output path"); options.addOption("okd", "output-kml-dynamic", true, "dynamic kml output path"); options.addOption("oku", "output-kml-users", false, "output user-based KML rather than toponym-based KML"); options.addOption("gold", "output-gold-locations", false, "output gold locations rather than system locations in KML"); options.addOption("gt", "gold-toponyms", false, "use gold toponyms (named entities) if available"); options.addOption("g", "geo-gazetteer-filename", true, "GeoNames gazetteer filename"); options.addOption("sg", "serialized-gazetteer-path", true, "path to serialized GeoNames gazetteer"); options.addOption("sci", "serialized-corpus-input-path", true, "path to serialized corpus for input"); //options.addOption("sgci", "serialized-gold-corpus-input-path", true, "path to serialized gold corpus for input"); options.addOption("sco", "serialized-corpus-output-path", true, "path to serialized corpus for output"); //options.addOption("tr", "tr-conll", false, "read input path as TR-CoNLL directory"); options.addOption("cf", "corpus-format", true, "corpus format (Plain, TrCoNLL, GeoText) [default = Plain]"); options.addOption("oracle", "oracle", false, "use oracle evaluation"); options.addOption("spd", "sentences-per-document", true, "sentences per document (-1 for unlimited) [default = -1]"); options.addOption("pc", "pop-comp-coeff", true, "population component coefficient (for PROBABILISTIC resolver)"); options.addOption("pdg", "prob-doc-geo", false, "use probability from document geolocator only (for PROBABILISTIC resolver)"); options.addOption("pme", "prob-maxent", false, "use probability from MaxEnt local context component only (for PROBABILISTIC resolver)"); options.addOption("minlat", "minimum-latitude", true, "minimum latitude for bounding box"); options.addOption("maxlat", "maximum-latitude", true, "maximum latitude for bounding box"); options.addOption("minlon", "minimum-longitude", true, "minimum longitude for bounding box"); options.addOption("maxlon", "maximum-longitude", true, "maximum longitude for bounding box"); options.addOption("dkm", "do-k-means-multipoints", false, "(import-gazetteer only) run k-means and create multipoint representations of regions (e.g. countries)"); options.addOption("og", "output-graph", true, "(preprocess-labelprop only) path to output graph file"); options.addOption("os", "output-seed", true, "(preprocess-labelprop only) path to output seed file"); options.addOption("iw", "input-wiki", true, "(preprocess-labelprop only) path to wikipedia file (article titles, article IDs, and word lists)"); options.addOption("is", "input-stoplist", true, "(preprocess-labelprob only) path to stop list input file (one stop word per line)"); options.addOption("l", "log-file-input", true, "log file input, from document geolocation"); options.addOption("knn", "knn", true, "k nearest neighbors to consider from document geolocation log file"); options.addOption("dpc", "degrees-per-cell", true, "degrees per cell for grid-based TPP resolvers"); options.addOption("t", "threshold", true, "threshold in kilometers for agglomerative clustering"); options.addOption("m", "market-prob", true, "path to market probabilities from LinkTravelWriter"); options.addOption("a", "article-info", true, "path to article info file from Wiki preprocess"); options.addOption("li", "links", true, "path to link file from Wiki preprocess"); options.addOption("ner", "named-entity-recognizer", true, "option for using High Recall NER"); options.addOption("h", "help", false, "print help"); Double minLat = null; Double maxLat = null; Double minLon = null; Double maxLon = null; CommandLineParser optparse = new PosixParser(); CommandLine cline = optparse.parse(options, args); if (cline.hasOption('h')) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("fieldspring [command] ", options); System.exit(0); } for (Option option : cline.getOptions()) { String value = option.getValue(); switch (option.getOpt().charAt(0)) { case 'i': if(option.getOpt().equals("i")) inputPath = value; else if(option.getOpt().equals("it")) numIterations = Integer.parseInt(value); else if(option.getOpt().equals("ia")) additionalInputPath = value; else if(option.getOpt().equals("ig")) graphInputPath = value; else if(option.getOpt().equals("iw")) wikiInputPath = value; else if(option.getOpt().equals("is")) stoplistInputPath = value; else if(option.getOpt().equals("ix")) xmlInputPath = value; else if(option.getOpt().equals("im")) maxentModelDirInputPath = value; break; case 'o': if(option.getOpt().equals("o")) outputPath = value; else if(option.getOpt().equals("og")) graphOutputPath = value; else if(option.getOpt().equals("ok")) kmlOutputPath = value; else if(option.getOpt().equals("oku")) outputUserKML = true; else if(option.getOpt().equals("okd")) dKmlOutputPath = value; else if(option.getOpt().equals("os")) seedOutputPath = value; else if(option.getOpt().equals("oracle")) doOracleEval = true; break; case 'r': if(option.getOpt().equals("r")) { if(value.toLowerCase().startsWith("r")) resolverType = RESOLVER_TYPE.RANDOM; else if(value.toLowerCase().startsWith("w")) resolverType = RESOLVER_TYPE.WEIGHTED_MIN_DIST; else if(value.toLowerCase().startsWith("d")) resolverType = RESOLVER_TYPE.DOC_DIST; else if(value.toLowerCase().startsWith("t")) resolverType = RESOLVER_TYPE.TOPO_AS_DOC_DIST; else if(value.equalsIgnoreCase("labelprop")) resolverType = RESOLVER_TYPE.LABEL_PROP; else if(value.toLowerCase().startsWith("labelpropd")) resolverType = RESOLVER_TYPE.LABEL_PROP_DEFAULT_RULE; else if(value.toLowerCase().startsWith("labelpropcontext")) resolverType = RESOLVER_TYPE.LABEL_PROP_CONTEXT_SENSITIVE; else if(value.toLowerCase().startsWith("labelpropcomplex")) resolverType = RESOLVER_TYPE.LABEL_PROP_COMPLEX; else if(value.toLowerCase().startsWith("m")) resolverType = RESOLVER_TYPE.MAXENT; else if(value.toLowerCase().startsWith("pr")) resolverType = RESOLVER_TYPE.PROB; else if(value.toLowerCase().startsWith("po")) resolverType = RESOLVER_TYPE.POPULATION; else if(value.toLowerCase().startsWith("bayes")) resolverType = RESOLVER_TYPE.BAYES_RULE; else if(value.toLowerCase().startsWith("h")) resolverType = RESOLVER_TYPE.HEURISTIC_TPP; else if(value.toLowerCase().startsWith("c")) resolverType = RESOLVER_TYPE.CONSTRUCTION_TPP; else if(value.toLowerCase().startsWith("a")) resolverType = RESOLVER_TYPE.ACO_TPP; else resolverType = RESOLVER_TYPE.BASIC_MIN_DIST; } else if(option.getOpt().equals("rwf")) { readWeightsFromFile = true; } break; case 'g': if(option.getOpt().equals("g")) geoGazetteerFilename = value; else if(option.getOpt().equals("gold")) outputGoldLocations = true; else if(option.getOpt().equals("gt")) useGoldToponyms = true; break; case 's': if(option.getOpt().equals("sg")) serializedGazetteerPath = value; else if(option.getOpt().equals("sci")) serializedCorpusInputPath = value; else if(option.getOpt().equals("sco")) serializedCorpusOutputPath = value; else if(option.getOpt().equals("spd")) sentsPerDocument = Integer.parseInt(value); //else if(option.getOpt().equals("sgci")) // serializedGoldCorpusInputPath = value; break; case 'c': if(value.toLowerCase().startsWith("t")) corpusFormat = CORPUS_FORMAT.TRCONLL; else if(value.toLowerCase().startsWith("g")) corpusFormat = CORPUS_FORMAT.GEOTEXT; else//if(value.toLowerCase().startsWith("p")) corpusFormat = CORPUS_FORMAT.PLAIN; break; case 'l': if(option.getOpt().equals("l")) logFilePath = value; else if(option.getOpt().equals("li")) linkPath = value; break; case 'a': if(option.getOpt().equals("a")) articleInfoPath = value; break; case 'k': if(option.getOpt().equals("knn")) knnForLP = Integer.parseInt(value); break; case 'm': if(option.getOpt().equals("m")) marketProbPath = value; else if(option.getOpt().equals("minlat")) minLat = Double.parseDouble(value.replaceAll("n", "-")); else if(option.getOpt().equals("maxlat")) maxLat = Double.parseDouble(value.replaceAll("n", "-")); else if(option.getOpt().equals("minlon")) minLon = Double.parseDouble(value.replaceAll("n", "-")); else if(option.getOpt().equals("maxlon")) maxLon = Double.parseDouble(value.replaceAll("n", "-")); break; case 'n': if(option.getOpt().equals("ner")) setHighRecallNER(new Integer(value)!=0); break; case 'd': if(option.getOpt().equals("dkm")) doKMeans = true; else if(option.getOpt().equals("dpc")) dpc = Double.parseDouble(value); break; case 't': threshold = Double.parseDouble(value); break; case 'p': if(option.getOpt().equals("pc")) popComponentCoefficient = Double.parseDouble(value); else if(option.getOpt().equals("pme")) meProbOnly = true; else dgProbOnly = true; } } if(minLat != null && maxLat != null && minLon != null && maxLon != null) boundingBox = RectRegion.fromDegrees(minLat, maxLat, minLon, maxLon); } public static void checkExists(String filename) throws Exception { if(filename == null) { System.out.println("Null filename; aborting."); System.exit(0); } File f = new File(filename); if(!f.exists()) { System.out.println(filename + " doesn't exist; aborting."); System.exit(0); } } public String getInputPath() { return inputPath; } public String getXMLInputPath() { return xmlInputPath; } public String getAdditionalInputPath() { return additionalInputPath; } public String getMaxentModelDirInputPath() { return maxentModelDirInputPath; } public String getGraphInputPath() { return graphInputPath; } public Enum<RESOLVER_TYPE> getResolverType() { return resolverType; } public int getNumIterations() { return numIterations; } public boolean getReadWeightsFromFile() { return readWeightsFromFile; } public String getOutputPath() { return outputPath; } public String getKMLOutputPath() { return kmlOutputPath; } public String getDKMLOutputPath() { return dKmlOutputPath; } public boolean getOutputGoldLocations() { return outputGoldLocations; } public boolean getUseGoldToponyms() { return useGoldToponyms; } public boolean getOutputUserKML() { return outputUserKML; } public String getGeoGazetteerFilename() { return geoGazetteerFilename; } public String getSerializedGazetteerPath() { return serializedGazetteerPath; } public String getSerializedCorpusInputPath() { return serializedCorpusInputPath; } public String getSerializedCorpusOutputPath() { return serializedCorpusOutputPath; } public Enum<CORPUS_FORMAT> getCorpusFormat() { return corpusFormat; } public int getSentsPerDocument() { return sentsPerDocument; } public boolean isDoingKMeans() { return doKMeans; } public String getGraphOutputPath() { return graphOutputPath; } public String getSeedOutputPath() { return seedOutputPath; } public String getWikiInputPath() { return wikiInputPath; } public String getStoplistInputPath() { return stoplistInputPath; } public String getLogFilePath() { return logFilePath; } public int getKnnForLP() { return knnForLP; } public Region getBoundingBox() { return boundingBox; } public double getPopComponentCoefficient() { return popComponentCoefficient; } public boolean getDGProbOnly() { return dgProbOnly; } public boolean getMEProbOnly() { return meProbOnly; } public boolean getDoOracleEval() { return doOracleEval; } public double getDPC() { return dpc; } public double getThreshold() { return threshold; } public String getArticleInfoPath() { return articleInfoPath; } public String getLinkPath() { return linkPath; } public String getMarketProbPath() { return marketProbPath; } public void setHighRecallNER(boolean highRecallNER) { highRecallNER = highRecallNER; } public boolean isHighRecallNER() { return highRecallNER; } }
apache-2.0
toddlipcon/helenus
src/java/com/facebook/infrastructure/loader/Importer.java
3077
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.3 in JDK 1.6 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2007.10.19 at 01:36:41 PM PDT // package com.facebook.infrastructure.loader; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p> * Java class for anonymous complex type. * * <p> * The following schema fragment specifies the expected content contained within * this class. * * <pre> * &lt;complexType&gt; * &lt;complexContent&gt; * &lt;restriction base=&quot;{http://www.w3.org/2001/XMLSchema}anyType&quot;&gt; * &lt;sequence&gt; * &lt;element name=&quot;Table&quot; type=&quot;{http://www.w3.org/2001/XMLSchema}string&quot;/&gt; * &lt;element name=&quot;Key&quot; type=&quot;{}KeyType&quot;/&gt; * &lt;element name=&quot;ColumnFamily&quot; type=&quot;{}ColumnFamilyType&quot;/&gt; * &lt;/sequence&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "table", "key", "columnFamily" }) @XmlRootElement(name = "Importer") public class Importer { @XmlElement(name = "Table", required = true) protected String table; @XmlElement(name = "Key", required = true) protected KeyType key; @XmlElement(name = "ColumnFamily", required = true) protected ColumnFamilyType columnFamily; /** * Gets the value of the table property. * * @return possible object is {@link String } * */ public String getTable() { return table; } /** * Sets the value of the table property. * * @param value * allowed object is {@link String } * */ public void setTable(String value) { this.table = value; } /** * Gets the value of the key property. * * @return possible object is {@link KeyType } * */ public KeyType getKey() { return key; } /** * Sets the value of the key property. * * @param value * allowed object is {@link KeyType } * */ public void setKey(KeyType value) { this.key = value; } /** * Gets the value of the columnFamily property. * * @return possible object is {@link ColumnFamilyType } * */ public ColumnFamilyType getColumnFamily() { return columnFamily; } /** * Sets the value of the columnFamily property. * * @param value * allowed object is {@link ColumnFamilyType } * */ public void setColumnFamily(ColumnFamilyType value) { this.columnFamily = value; } }
apache-2.0
equella/Equella
Source/Plugins/Core/com.equella.base/src/com/tle/common/filesystem/handle/ExportFile.java
1232
/* * 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.tle.common.filesystem.handle; import com.tle.annotation.NonNullByDefault; import com.tle.common.filesystem.FileHandleUtils; /** @author aholland */ @NonNullByDefault public class ExportFile extends AbstractFile implements TemporaryFileHandle { private static final long serialVersionUID = 1L; public ExportFile(String name) { super(new AllExportFile(), name); FileHandleUtils.checkPath(name); } }
apache-2.0
RUB-NDS/EccPlayground
src/main/java/de/rub/nds/eccjava/view/curve/CurveGraphPanel.java
2684
package de.rub.nds.eccjava.view.curve; import de.rub.nds.eccjava.controller.AppController; import de.rub.nds.eccjava.curve.Curve; import de.rub.nds.eccjava.curve.DivisionException; import de.rub.nds.eccjava.curve.Oracle; import de.rub.nds.eccjava.curve.Point; import java.awt.Color; import java.math.BigInteger; import java.util.List; import org.apache.log4j.Logger; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.annotations.XYTextAnnotation; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.renderer.xy.XYItemRenderer; import org.jfree.data.xy.XYDataItem; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; /** * * @author Juraj Somorovsky - juraj.somorovsky@rub.de * @version 0.1 */ public class CurveGraphPanel extends ChartPanel { private static CurveGraphPanel INSTANCE = null; private static final AppController appController = new AppController(); private static XYSeries eccSeries; private static final Logger LOG = Logger.getLogger(CurveGraphPanel.class); private CurveGraphPanel(JFreeChart chart) { super(chart); } public static CurveGraphPanel getInstance() { if (INSTANCE == null) { eccSeries = new XYSeries("ecc", false); XYSeriesCollection dataset = new XYSeriesCollection(); dataset.addSeries(eccSeries); JFreeChart chart = ChartFactory.createScatterPlot(null, null, null, dataset, PlotOrientation.VERTICAL, false, true, false); INSTANCE = new CurveGraphPanel(chart); XYItemRenderer renderer = chart.getXYPlot().getRenderer(); renderer.setSeriesPaint(2, Color.BLACK); } return INSTANCE; } public void showAnnotations() { XYItemRenderer renderer = getChart().getXYPlot().getRenderer(); renderer.removeAnnotations(); for (int i = 0; i < eccSeries.getItemCount(); i++) { XYDataItem item = (XYDataItem) eccSeries.getDataItem(i); XYTextAnnotation annon = new XYTextAnnotation(new Integer(i).toString(), item.getX().longValue(), item .getY().longValue()); renderer.addAnnotation(annon); } } public void removeAnnotations() { XYItemRenderer renderer = getChart().getXYPlot().getRenderer(); renderer.removeAnnotations(); } public void updateSeries(Point point) { if (!point.isInfinity()) { eccSeries.add(point.getX(), point.getY()); } } public void clearSeries() { eccSeries.clear(); } }
apache-2.0
eskatos/qipki
crypto/src/main/java/org/qipki/crypto/algorithms/BlockCipherModeOfOperation.java
3686
/* * Copyright (c) 2010, Paul Merlin. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.qipki.crypto.algorithms; /** * Block Cipher Mode Of Operation. * * See http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation */ public enum BlockCipherModeOfOperation implements Algorithm { /** * Segmented Integer Counter (SIC) mode is also known as CTR mode (CM) and Integer Counter Mode (ICM). * * Turns a block cipher into a stream cipher. It generates the next keystream block by encrypting successive * values of a "counter". The counter can be any function which produces a sequence which is guaranteed not * to repeat for a long time, although an actual counter is the simplest and most popular. * The usage of a simple deterministic input function used to be controversial; critics argued that * "deliberately exposing a cryptosystem to a known systematic input represents an unnecessary risk." * By now, SIC mode is widely accepted, and problems resulting from the input function are recognized as a * weakness of the underlying block cipher instead of the SIC mode. * Nevertheless, there are specialised attacks like a Hardware Fault Attack that is based on the usage of a * simple counter function as input. * SIC mode has similar characteristics to OFB, but also allows a random access property during decryption. * SIC mode is well suited to operation on a multi-processor machine where blocks can be encrypted in parallel. */ SIC( "SIC" ), /** * Each block of plaintext is XORed with the previous ciphertext block before being encrypted. * This way, each ciphertext block is dependent on all plaintext blocks processed up to that point. * Also, to make each message unique, an initialization vector must be used in the first block. */ CBC( "CBC" ), /** * Close relative of CBC, makes a block cipher into a self-synchronizing stream cipher. * Operation is very similar; in particular, CFB decryption is almost identical to CBC encryption performed * in reverse */ CFB( "CFB" ), /** * Makes a block cipher into a synchronous stream cipher. It generates keystream blocks, which are then XORed * with the plaintext blocks to get the ciphertext. Just as with other stream ciphers, flipping a bit in the * ciphertext produces a flipped bit in the plaintext at the same location. * This property allows many error correcting codes to function normally even when applied before encryption. */ OFB( "OFB" ), /** * The simplest of the encryption modes is the electronic codebook (ECB) mode. * The message is divided into blocks and each block is encrypted separately. * * @deprecated This mode do not support initialization vectors which are considered mandatory for good encryption. */ @Deprecated ECB( "ECB" ); private String jcaString; private BlockCipherModeOfOperation( String jcaString ) { this.jcaString = jcaString; } @Override public String jcaString() { return jcaString; } }
apache-2.0
DaanHoogland/cloudstack
test/integration/smoke/test_diagnostics.py
22974
# 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. """ BVT tests for remote diagnostics of system VMs """ import urllib from marvin.cloudstackAPI import (runDiagnostics, getDiagnosticsData) from marvin.cloudstackTestCase import cloudstackTestCase # Import Local Modules from marvin.codes import FAILED from marvin.lib.base import (Account, ServiceOffering, VirtualMachine) from marvin.lib.common import (get_domain, get_zone, get_test_template, list_ssvms, list_routers) from marvin.lib.utils import (cleanup_resources) from nose.plugins.attrib import attr class TestRemoteDiagnostics(cloudstackTestCase): """ Test remote diagnostics with system VMs and VR as root admin """ @classmethod def setUpClass(cls): testClient = super(TestRemoteDiagnostics, cls).getClsTestClient() cls.apiclient = testClient.getApiClient() cls.services = testClient.getParsedTestDataConfig() # Get Zone, Domain and templates cls.domain = get_domain(cls.apiclient) cls.zone = get_zone(cls.apiclient, testClient.getZoneForTests()) cls.hypervisor = testClient.getHypervisorInfo() cls.services['mode'] = cls.zone.networktype template = get_test_template( cls.apiclient, cls.zone.id, cls.hypervisor ) if template == FAILED: cls.fail("get_test_template() failed to return template") cls.services["virtual_machine"]["zoneid"] = cls.zone.id # Create an account, network, VM and IP addresses cls.account = Account.create( cls.apiclient, cls.services["account"], domainid=cls.domain.id ) cls.service_offering = ServiceOffering.create( cls.apiclient, cls.services["service_offerings"]["tiny"] ) cls.vm_1 = VirtualMachine.create( cls.apiclient, cls.services["virtual_machine"], templateid=template.id, accountid=cls.account.name, domainid=cls.account.domainid, serviceofferingid=cls.service_offering.id ) cls.cleanup = [ cls.account, cls.service_offering ] @classmethod def tearDownClass(cls): try: cls.apiclient = super( TestRemoteDiagnostics, cls ).getClsTestClient().getApiClient() # Clean up, terminate the created templates cleanup_resources(cls.apiclient, cls.cleanup) except Exception as e: raise Exception("Warning: Exception during cleanup : %s" % e) def setUp(self): self.apiclient = self.testClient.getApiClient() self.hypervisor = self.testClient.getHypervisorInfo() @attr(tags=["advanced", "advancedns", "ssh", "smoke"], required_hardware="true") def test_01_ping_in_vr_success(self): ''' Test Ping command execution in VR ''' # Validate the following: # 1. Ping command is executed remotely on VR list_router_response = list_routers( self.apiclient, account=self.account.name, domainid=self.account.domainid ) self.assertEqual( isinstance(list_router_response, list), True, "Check list response returns a valid list" ) router = list_router_response[0] self.debug('Starting the router with ID: %s' % router.id) cmd = runDiagnostics.runDiagnosticsCmd() cmd.targetid = router.id cmd.ipaddress = '8.8.8.8' cmd.type = 'ping' cmd_response = self.apiclient.runDiagnostics(cmd) self.assertEqual( '0', cmd_response.exitcode, 'Failed to run remote Ping in VR') @attr(tags=["advanced", "advancedns", "ssh", "smoke"], required_hardware="true") def test_02_ping_in_vr_failure(self): ''' Test Ping command execution in VR ''' # Validate the following: # 1. Ping command is executed remotely on VR # 2. Validate Ping command execution with a non-existent/pingable IP address if self.hypervisor.lower() == 'simulator': raise self.skipTest("Skipping negative test case for Simulator hypervisor") list_router_response = list_routers( self.apiclient, account=self.account.name, domainid=self.account.domainid ) self.assertEqual( isinstance(list_router_response, list), True, "Check list response returns a valid list" ) router = list_router_response[0] self.debug('Starting the router with ID: %s' % router.id) cmd = runDiagnostics.runDiagnosticsCmd() cmd.targetid = router.id cmd.ipaddress = '192.0.2.2' cmd.type = 'ping' cmd_response = self.apiclient.runDiagnostics(cmd) self.assertNotEqual( '0', cmd_response.exitcode, 'Check diagnostics command returns a non-zero exit code') @attr(tags=["advanced", "advancedns", "ssh", "smoke"], required_hardware="true") def test_03_ping_in_ssvm_success(self): ''' Test Ping command execution in SSVM ''' # Validate the following: # 1. Ping command is executed remotely on SSVM list_ssvm_response = list_ssvms( self.apiclient, systemvmtype='secondarystoragevm', state='Running', ) self.assertEqual( isinstance(list_ssvm_response, list), True, 'Check list response returns a valid list' ) ssvm = list_ssvm_response[0] self.debug('Setting up SSVM with ID %s' % ssvm.id) cmd = runDiagnostics.runDiagnosticsCmd() cmd.targetid = ssvm.id cmd.ipaddress = '8.8.8.8' cmd.type = 'ping' cmd_response = self.apiclient.runDiagnostics(cmd) self.assertEqual( '0', cmd_response.exitcode, 'Failed to run remote Ping in SSVM' ) @attr(tags=["advanced", "advancedns", "ssh", "smoke"], required_hardware="true") def test_04_ping_in_ssvm_failure(self): ''' Test Ping command execution in SSVM ''' # Validate the following: # 1. Ping command is executed remotely on SSVM # 2. Validate Ping command execution with a non-existent/pingable IP address if self.hypervisor.lower() == 'simulator': raise self.skipTest("Skipping negative test case for Simulator hypervisor") list_ssvm_response = list_ssvms( self.apiclient, systemvmtype='secondarystoragevm', state='Running', ) self.assertEqual( isinstance(list_ssvm_response, list), True, 'Check list response returns a valid list' ) ssvm = list_ssvm_response[0] self.debug('Setting up SSVM with ID %s' % ssvm.id) cmd = runDiagnostics.runDiagnosticsCmd() cmd.targetid = ssvm.id cmd.ipaddress = '192.0.2.2' cmd.type = 'ping' cmd_response = self.apiclient.runDiagnostics(cmd) self.assertNotEqual( '0', cmd_response.exitcode, 'Failed to run remote Ping in SSVM' ) @attr(tags=["advanced", "advancedns", "ssh", "smoke"], required_hardware="true") def test_05_ping_in_cpvm_success(self): ''' Test Ping command execution in CPVM ''' # Validate the following: # 1. Ping command is executed remotely on CPVM list_ssvm_response = list_ssvms( self.apiclient, systemvmtype='consoleproxy', state='Running', ) self.assertEqual( isinstance(list_ssvm_response, list), True, 'Check list response returns a valid list' ) cpvm = list_ssvm_response[0] self.debug('Setting up CPVM with ID %s' % cpvm.id) cmd = runDiagnostics.runDiagnosticsCmd() cmd.targetid = cpvm.id cmd.ipaddress = '8.8.8.8' cmd.type = 'ping' cmd_response = self.apiclient.runDiagnostics(cmd) self.assertEqual( '0', cmd_response.exitcode, 'Failed to run remote Ping in CPVM' ) @attr(tags=["advanced", "advancedns", "ssh", "smoke"], required_hardware="true") def test_06_ping_in_cpvm_failure(self): ''' Test Ping command execution in CPVM ''' # Validate the following: # 1. Ping command is executed remotely on CPVM # 2. Validate Ping command execution with a non-existent/pingable IP address if self.hypervisor.lower() == 'simulator': raise self.skipTest("Skipping negative test case for Simulator hypervisor") list_ssvm_response = list_ssvms( self.apiclient, systemvmtype='consoleproxy', state='Running', ) self.assertEqual( isinstance(list_ssvm_response, list), True, 'Check list response returns a valid list' ) cpvm = list_ssvm_response[0] self.debug('Setting up CPVM with ID %s' % cpvm.id) cmd = runDiagnostics.runDiagnosticsCmd() cmd.targetid = cpvm.id cmd.ipaddress = '192.0.2.2' cmd.type = 'ping' cmd_response = self.apiclient.runDiagnostics(cmd) self.assertNotEqual( '0', cmd_response.exitcode, 'Check diagnostics command returns a non-zero exit code' ) @attr(tags=["advanced", "advancedns", "ssh", "smoke"], required_hardware="true") def test_07_arping_in_vr(self): ''' Test Arping command execution in VR ''' # Validate the following: # 1. Arping command is executed remotely on VR list_router_response = list_routers( self.apiclient, account=self.account.name, domainid=self.account.domainid ) self.assertEqual( isinstance(list_router_response, list), True, "Check list response returns a valid list" ) router = list_router_response[0] self.debug('Starting the router with ID: %s' % router.id) cmd = runDiagnostics.runDiagnosticsCmd() cmd.targetid = router.id cmd.ipaddress = router.gateway cmd.type = 'arping' cmd.params = "-I eth2" cmd_response = self.apiclient.runDiagnostics(cmd) self.assertEqual( '0', cmd_response.exitcode, 'Failed to run remote Arping in VR') @attr(tags=["advanced", "advancedns", "ssh", "smoke"], required_hardware="true") def test_08_arping_in_ssvm(self): ''' Test Arping command execution in SSVM ''' # Validate the following: # 1. Arping command is executed remotely on SSVM list_ssvm_response = list_ssvms( self.apiclient, systemvmtype='secondarystoragevm', state='Running', ) self.assertEqual( isinstance(list_ssvm_response, list), True, 'Check list response returns a valid list' ) ssvm = list_ssvm_response[0] self.debug('Setting up SSVM with ID %s' % ssvm.id) cmd = runDiagnostics.runDiagnosticsCmd() cmd.targetid = ssvm.id cmd.ipaddress = ssvm.gateway cmd.type = 'arping' cmd.params = '-I eth2' cmd_response = self.apiclient.runDiagnostics(cmd) self.assertEqual( '0', cmd_response.exitcode, 'Failed to run remote Arping in SSVM' ) @attr(tags=["advanced", "advancedns", "ssh", "smoke"], required_hardware="true") def test_09_arping_in_cpvm(self): ''' Test Arping command execution in CPVM ''' # Validate the following: # 1. Arping command is executed remotely on CPVM list_cpvm_response = list_ssvms( self.apiclient, systemvmtype='secondarystoragevm', state='Running', ) self.assertEqual( isinstance(list_cpvm_response, list), True, 'Check list response returns a valid list' ) cpvm = list_cpvm_response[0] self.debug('Setting up CPVM with ID %s' % cpvm.id) cmd = runDiagnostics.runDiagnosticsCmd() cmd.targetid = cpvm.id cmd.ipaddress = cpvm.gateway cmd.type = 'arping' cmd.params = '-I eth2' cmd_response = self.apiclient.runDiagnostics(cmd) self.assertEqual( '0', cmd_response.exitcode, 'Failed to run remote Arping in CPVM' ) @attr(tags=["advanced", "advancedns", "ssh", "smoke"], required_hardware="true") def test_10_traceroute_in_vr(self): ''' Test Arping command execution in VR ''' # Validate the following: # 1. Arping command is executed remotely on VR list_router_response = list_routers( self.apiclient, account=self.account.name, domainid=self.account.domainid ) self.assertEqual( isinstance(list_router_response, list), True, "Check list response returns a valid list" ) router = list_router_response[0] self.debug('Starting the router with ID: %s' % router.id) cmd = runDiagnostics.runDiagnosticsCmd() cmd.targetid = router.id cmd.ipaddress = '8.8.4.4' cmd.type = 'traceroute' cmd.params = "-m 10" cmd_response = self.apiclient.runDiagnostics(cmd) self.assertEqual( '0', cmd_response.exitcode, 'Failed to run remote Arping in VR') @attr(tags=["advanced", "advancedns", "ssh", "smoke"], required_hardware="true") def test_11_traceroute_in_ssvm(self): ''' Test Traceroute command execution in SSVM ''' # Validate the following: # 1. Traceroute command is executed remotely on SSVM list_ssvm_response = list_ssvms( self.apiclient, systemvmtype='secondarystoragevm', state='Running', ) self.assertEqual( isinstance(list_ssvm_response, list), True, 'Check list response returns a valid list' ) ssvm = list_ssvm_response[0] self.debug('Setting up SSVM with ID %s' % ssvm.id) cmd = runDiagnostics.runDiagnosticsCmd() cmd.targetid = ssvm.id cmd.ipaddress = '8.8.4.4' cmd.type = 'traceroute' cmd.params = '-m 10' cmd_response = self.apiclient.runDiagnostics(cmd) self.assertEqual( '0', cmd_response.exitcode, 'Failed to run remote Traceroute in SSVM' ) @attr(tags=["advanced", "advancedns", "ssh", "smoke"], required_hardware="true") def test_12_traceroute_in_cpvm(self): ''' Test Traceroute command execution in CPVMM ''' # Validate the following: # 1. Traceroute command is executed remotely on CPVM list_cpvm_response = list_ssvms( self.apiclient, systemvmtype='consoleproxy', state='Running', ) self.assertEqual( isinstance(list_cpvm_response, list), True, 'Check list response returns a valid list' ) cpvm = list_cpvm_response[0] self.debug('Setting up CPVMM with ID %s' % cpvm.id) cmd = runDiagnostics.runDiagnosticsCmd() cmd.targetid = cpvm.id cmd.ipaddress = '8.8.4.4' cmd.type = 'traceroute' cmd.params = '-m 10' cmd_response = self.apiclient.runDiagnostics(cmd) self.assertEqual( '0', cmd_response.exitcode, 'Failed to run remote Traceroute in CPVM' ) ''' Add Get Diagnostics data BVT ''' @attr(tags=["advanced", "advancedns", "ssh", "smoke"], required_hardware="true") def test_13_retrieve_vr_default_files(self): list_router_response = list_routers( self.apiclient, account=self.account.name, domainid=self.account.domainid ) self.assertEqual( isinstance(list_router_response, list), True, "Check list response returns a valid list" ) router = list_router_response[0] self.debug('Setting up VR with ID %s' % router.id) cmd = getDiagnosticsData.getDiagnosticsDataCmd() cmd.targetid = router.id response = self.apiclient.getDiagnosticsData(cmd) is_valid_url = self.check_url(response.url) self.assertEqual( True, is_valid_url, msg="Failed to create valid download url response" ) def check_url(self, url): import urllib2 try: r = urllib.urlopen(url) if r.code == 200: return True except urllib2.HTTPError: return False except urllib2.URLError: return False return True @attr(tags=["advanced", "advancedns", "ssh", "smoke"], required_hardware="true") def test_14_retrieve_vr_one_file(self): list_router_response = list_routers( self.apiclient, account=self.account.name, domainid=self.account.domainid ) self.assertEqual( isinstance(list_router_response, list), True, "Check list response returns a valid list" ) router = list_router_response[0] self.debug('Setting up VR with ID %s' % router.id) cmd = getDiagnosticsData.getDiagnosticsDataCmd() cmd.targetid = router.id cmd.type = "/var/log/cloud.log" response = self.apiclient.getDiagnosticsData(cmd) is_valid_url = self.check_url(response.url) self.assertEqual( True, is_valid_url, msg="Failed to create valid download url response" ) @attr(tags=["advanced", "advancedns", "ssh", "smoke"], required_hardware="true") def test_15_retrieve_ssvm_default_files(self): list_ssvm_response = list_ssvms( self.apiclient, systemvmtype='secondarystoragevm', state='Running', ) self.assertEqual( isinstance(list_ssvm_response, list), True, 'Check list response returns a valid list' ) ssvm = list_ssvm_response[0] self.debug('Setting up SSVM with ID %s' % ssvm.id) cmd = getDiagnosticsData.getDiagnosticsDataCmd() cmd.targetid = ssvm.id response = self.apiclient.getDiagnosticsData(cmd) is_valid_url = self.check_url(response.url) self.assertEqual( True, is_valid_url, msg="Failed to create valid download url response" ) @attr(tags=["advanced", "advancedns", "ssh", "smoke"], required_hardware="true") def test_16_retrieve_ssvm_single_file(self): list_ssvm_response = list_ssvms( self.apiclient, systemvmtype='secondarystoragevm', state='Running', ) self.assertEqual( isinstance(list_ssvm_response, list), True, 'Check list response returns a valid list' ) ssvm = list_ssvm_response[0] self.debug('Setting up SSVM with ID %s' % ssvm.id) cmd = getDiagnosticsData.getDiagnosticsDataCmd() cmd.targetid = ssvm.id cmd.type = "/var/log/cloud.log" response = self.apiclient.getDiagnosticsData(cmd) is_valid_url = self.check_url(response.url) self.assertEqual( True, is_valid_url, msg="Failed to create valid download url response" ) @attr(tags=["advanced", "advancedns", "ssh", "smoke"], required_hardware="true") def test_17_retrieve_cpvm_default_files(self): list_cpvm_response = list_ssvms( self.apiclient, systemvmtype='consoleproxy', state='Running', ) self.assertEqual( isinstance(list_cpvm_response, list), True, 'Check list response returns a valid list' ) cpvm = list_cpvm_response[0] self.debug('Setting up CPVM with ID %s' % cpvm.id) cmd = getDiagnosticsData.getDiagnosticsDataCmd() cmd.targetid = cpvm.id response = self.apiclient.getDiagnosticsData(cmd) is_valid_url = self.check_url(response.url) self.assertEqual( True, is_valid_url, msg="Failed to create valid download url response" ) @attr(tags=["advanced", "advancedns", "ssh", "smoke"], required_hardware="true") def test_18_retrieve_cpvm_single_file(self): list_cpvm_response = list_ssvms( self.apiclient, systemvmtype='consoleproxy', state='Running', ) self.assertEqual( isinstance(list_cpvm_response, list), True, 'Check list response returns a valid list' ) cpvm = list_cpvm_response[0] self.debug('Setting up CPVM with ID %s' % cpvm.id) cmd = getDiagnosticsData.getDiagnosticsDataCmd() cmd.targetid = cpvm.id cmd.type = "/var/log/cloud.log" response = self.apiclient.getDiagnosticsData(cmd) is_valid_url = self.check_url(response.url) self.assertEqual( True, is_valid_url, msg="Failed to create valid download url response" )
apache-2.0
dcarbone/php-fhir-generated
src/DCarbone/PHPFHIRGenerated/R4/PHPFHIRTests/FHIRElement/FHIRBackboneElement/FHIRSubstanceSpecification/FHIRSubstanceSpecificationMoietyTest.php
3683
<?php namespace DCarbone\PHPFHIRGenerated\R4\PHPFHIRTests\FHIRElement\FHIRBackboneElement\FHIRSubstanceSpecification; /*! * This class was generated with the PHPFHIR library (https://github.com/dcarbone/php-fhir) using * class definitions from HL7 FHIR (https://www.hl7.org/fhir/) * * Class creation date: December 26th, 2019 15:44+0000 * * PHPFHIR Copyright: * * Copyright 2016-2019 Daniel Carbone (daniel.p.carbone@gmail.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * * FHIR Copyright Notice: * * Copyright (c) 2011+, HL7, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of HL7 nor the names of its contributors may be used to * endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * * Generated on Fri, Nov 1, 2019 09:29+1100 for FHIR v4.0.1 * * Note: the schemas & schematrons do not contain all of the rules about what makes resources * valid. Implementers will still need to be familiar with the content of the specification and with * any profiles that apply to the resources in order to make a conformant implementation. * */ use PHPUnit\Framework\TestCase; use DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRBackboneElement\FHIRSubstanceSpecification\FHIRSubstanceSpecificationMoiety; /** * Class FHIRSubstanceSpecificationMoietyTest * @package \DCarbone\PHPFHIRGenerated\R4\PHPFHIRTests\FHIRElement\FHIRBackboneElement\FHIRSubstanceSpecification */ class FHIRSubstanceSpecificationMoietyTest extends TestCase { public function testCanConstructTypeNoArgs() { $type = new FHIRSubstanceSpecificationMoiety(); $this->assertInstanceOf('\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRBackboneElement\FHIRSubstanceSpecification\FHIRSubstanceSpecificationMoiety', $type); } }
apache-2.0
backerman/evego
pkg/routing/sql_test.go
4399
/* Copyright © 2014–5 Brad Ackerman. 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 routing_test import ( "database/sql" "sync" "testing" "github.com/backerman/evego" "github.com/backerman/evego/pkg/dbaccess" "github.com/backerman/evego/pkg/routing" . "github.com/backerman/evego/pkg/test" . "github.com/smartystreets/goconvey/convey" "github.com/spf13/viper" // Register SQLite3 and PgSQL drivers _ "github.com/lib/pq" "github.com/mattn/go-sqlite3" ) var testDbDriver, testDbPath string func init() { viper.SetDefault("DBDriver", "sqlite3") viper.SetDefault("DBPath", "../../testdb.sqlite") viper.SetEnvPrefix("EVEGO_TEST") viper.AutomaticEnv() testDbDriver = viper.GetString("DBDriver") testDbPath = viper.GetString("DBPath") } var ( registerDriver sync.Once ) func TestSQLRouting(t *testing.T) { Convey("Open a database connection.", t, func() { var router evego.Router var db evego.Database cacheData := &CacheData{} switch testDbDriver { case "sqlite3": // Register a custom SQLite3 driver with the Spatialite extension. // Has to be wrapped in a Once because this is executed multiple // times by GoConvey. registerDriver.Do(func() { sql.Register("sqlite3_spatialite", &sqlite3.SQLiteDriver{ Extensions: []string{ SpatialiteModulePath(), }, }) }) router = routing.SQLRouter("sqlite3_spatialite", testDbPath, Cache(cacheData)) db = dbaccess.SQLDatabase("sqlite3_spatialite", testDbPath) case "postgres": router = routing.SQLRouter(testDbDriver, testDbPath, Cache(cacheData)) db = dbaccess.SQLDatabase(testDbDriver, testDbPath) default: Println("The database under test does not yet support routing; skipping.") return } defer db.Close() defer router.Close() Convey("Given a start and end system", func() { startSys, err := db.SolarSystemForName("Orvolle") // system ID 30003830 So(err, ShouldBeNil) endSys, err := db.SolarSystemForName("RF-GGF") // system ID 30003333 So(err, ShouldBeNil) Convey("The path is calculated correctly.", func() { numJumps, err := router.NumJumps(startSys, endSys) So(err, ShouldBeNil) So(numJumps, ShouldEqual, 5) Convey("The result is correctly stored in the cache.", func() { So(cacheData.GetKeys, ShouldContainKey, "numjumps:30003830:30003333") So(cacheData.PutKeys, ShouldContainKey, "numjumps:30003830:30003333") So(cacheData.NumPuts, ShouldEqual, 1) So(cacheData.NumGets, ShouldEqual, 1) }) }) }) Convey("Given an adjacent start and end system", func() { startSys, err := db.SolarSystemForName("BMNV-P") So(err, ShouldBeNil) endSys, err := db.SolarSystemForName("X-M2LR") So(err, ShouldBeNil) Convey("The path is calculated correctly.", func() { numJumps, err := router.NumJumps(startSys, endSys) So(err, ShouldBeNil) So(numJumps, ShouldEqual, 1) }) }) Convey("Given a start and end system that are the same", func() { startSys, err := db.SolarSystemForName("Orvolle") So(err, ShouldBeNil) endSys, err := db.SolarSystemForName("Orvolle") So(err, ShouldBeNil) Convey("The path is calculated correctly.", func() { numJumps, err := router.NumJumps(startSys, endSys) So(err, ShouldBeNil) So(numJumps, ShouldEqual, 0) }) }) Convey("Given an end system that cannot be reached from the start", func() { startSys, err := db.SolarSystemForName("Orvolle") // system ID 30003830 So(err, ShouldBeNil) endSys, err := db.SolarSystemForName("Polaris") // system ID 30000380 So(err, ShouldBeNil) Convey("Unreachability is correctly indicated.", func() { numJumps, err := router.NumJumps(startSys, endSys) So(err, ShouldBeNil) So(numJumps, ShouldEqual, -1) Convey("The result is cached.", func() { So(cacheData.PutKeys, ShouldContainKey, "numjumps:30003830:30000380") }) }) }) }) }
apache-2.0
googleapis/google-api-php-client-services
src/CloudTrace/Link.php
1885
<?php /* * Copyright 2014 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ namespace Google\Service\CloudTrace; class Link extends \Google\Model { protected $attributesType = Attributes::class; protected $attributesDataType = ''; /** * @var string */ public $spanId; /** * @var string */ public $traceId; /** * @var string */ public $type; /** * @param Attributes */ public function setAttributes(Attributes $attributes) { $this->attributes = $attributes; } /** * @return Attributes */ public function getAttributes() { return $this->attributes; } /** * @param string */ public function setSpanId($spanId) { $this->spanId = $spanId; } /** * @return string */ public function getSpanId() { return $this->spanId; } /** * @param string */ public function setTraceId($traceId) { $this->traceId = $traceId; } /** * @return string */ public function getTraceId() { return $this->traceId; } /** * @param string */ public function setType($type) { $this->type = $type; } /** * @return string */ public function getType() { return $this->type; } } // Adding a class alias for backwards compatibility with the previous class name. class_alias(Link::class, 'Google_Service_CloudTrace_Link');
apache-2.0
reynoldsm88/drools
drools-workbench-models/drools-workbench-models-test-scenarios/src/main/java/org/drools/workbench/models/testscenarios/backend/ScenarioRunner.java
8857
/* * Copyright 2010 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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.drools.workbench.models.testscenarios.backend; import java.lang.reflect.InvocationTargetException; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.drools.core.impl.InternalKnowledgeBase; import org.drools.workbench.models.testscenarios.backend.populators.FactPopulator; import org.drools.workbench.models.testscenarios.backend.populators.FactPopulatorFactory; import org.drools.workbench.models.testscenarios.shared.ActivateRuleFlowGroup; import org.drools.workbench.models.testscenarios.shared.CallMethod; import org.drools.workbench.models.testscenarios.shared.ExecutionTrace; import org.drools.workbench.models.testscenarios.shared.Expectation; import org.drools.workbench.models.testscenarios.shared.FactData; import org.drools.workbench.models.testscenarios.shared.Fixture; import org.drools.workbench.models.testscenarios.shared.RetractFact; import org.drools.workbench.models.testscenarios.shared.Scenario; import org.kie.api.KieBase; import org.kie.api.runtime.KieSession; import org.kie.soup.project.datamodel.commons.types.ClassTypeResolver; import org.mvel2.MVEL; /** * This actually runs the test scenarios. */ public class ScenarioRunner { private final KieSession ksession; private final int maximumAmountOfRuleFirings; private TestScenarioKSessionWrapper workingMemoryWrapper; private FactPopulatorFactory factPopulatorFactory; private FactPopulator factPopulator; /** * This constructor is normally used by Guvnor for running tests on a users * request. * * @param ksession A populated type resolved to be used to resolve the types in * the scenario. * <p/> * For info on how to invoke this, see * ContentPackageAssemblerTest.testPackageWithRuleflow in * guvnor-webapp This requires that the classloader for the * thread context be set appropriately. The PackageBuilder can * provide a suitable TypeResolver for a given package header, * and the Package config can provide a classloader. */ public ScenarioRunner(final KieSession ksession) throws ClassNotFoundException { this(ksession, 0); } /** * @param ksession A populated type resolved to be used to resolve the types in * the scenario. * @param maximumAmountOfRuleFirings Limit for amount of rules that can fire. To prevent infinite loops. * @throws ClassNotFoundException */ public ScenarioRunner(final KieSession ksession, final int maximumAmountOfRuleFirings) throws ClassNotFoundException { this.ksession = ksession; this.maximumAmountOfRuleFirings = maximumAmountOfRuleFirings; } public void run(final Scenario scenario) throws ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException, InvalidClockTypeException { final Map<String, Object> populatedData = new HashMap<String, Object>(); final Map<String, Object> globalData = new HashMap<String, Object>(); // This looks safe! final KieBase kieBase = ksession.getKieBase(); final ClassLoader classloader2 = ((InternalKnowledgeBase) kieBase).getRootClassLoader(); final ClassTypeResolver resolver = new ClassTypeResolver(getImports(scenario), classloader2); this.workingMemoryWrapper = new TestScenarioKSessionWrapper(ksession, resolver, populatedData, globalData, scenarioUsesTimeWalk(scenario)); this.factPopulatorFactory = new FactPopulatorFactory(populatedData, globalData, resolver); this.factPopulator = new FactPopulator(ksession, populatedData); MVEL.COMPILER_OPT_ALLOW_NAKED_METH_CALL = true; scenario.setLastRunResult(new Date()); populateGlobals(scenario.getGlobals()); applyFixtures(scenario.getFixtures(), createScenarioSettings(scenario)); } private boolean scenarioUsesTimeWalk(Scenario scenario) { for (Fixture fixture : scenario.getFixtures()) { if (fixture instanceof ExecutionTrace) { if (((ExecutionTrace) fixture).getScenarioSimulatedDate() != null) { return true; } } } return false; } private Set<String> getImports(final Scenario scenario) { final Set<String> imports = new HashSet<String>(); imports.addAll(scenario.getImports().getImportStrings()); if (scenario.getPackageName() != null && !scenario.getPackageName().isEmpty()) { imports.add(scenario.getPackageName() + ".*"); } return imports; } private ScenarioSettings createScenarioSettings(final Scenario scenario) { final ScenarioSettings scenarioSettings = new ScenarioSettings(); scenarioSettings.setRuleList(scenario.getRules()); scenarioSettings.setInclusive(scenario.isInclusive()); scenarioSettings.setMaxRuleFirings(getMaxRuleFirings(scenario)); return scenarioSettings; } private int getMaxRuleFirings(final Scenario scenario) { if (maximumAmountOfRuleFirings <= 0) { return scenario.getMaxRuleFirings(); } else { return maximumAmountOfRuleFirings; } } private void applyFixtures(final List<Fixture> fixtures, final ScenarioSettings scenarioSettings) throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, InvalidClockTypeException { for (Iterator<Fixture> iterator = fixtures.iterator(); iterator.hasNext(); ) { Fixture fixture = iterator.next(); if (fixture instanceof FactData) { factPopulator.add(factPopulatorFactory.createFactPopulator((FactData) fixture)); } else if (fixture instanceof RetractFact) { factPopulator.retractFact(((RetractFact) fixture).getName()); } else if (fixture instanceof CallMethod) { workingMemoryWrapper.executeMethod((CallMethod) fixture); } else if (fixture instanceof ActivateRuleFlowGroup) { workingMemoryWrapper.activateRuleFlowGroup(((ActivateRuleFlowGroup) fixture).getName()); } else if (fixture instanceof ExecutionTrace) { factPopulator.populate(); workingMemoryWrapper.executeSubScenario((ExecutionTrace) fixture, scenarioSettings); } else if (fixture instanceof Expectation) { factPopulator.populate(); workingMemoryWrapper.verifyExpectation((Expectation) fixture); } else { throw new IllegalArgumentException("Not sure what to do with " + fixture); } } factPopulator.populate(); } private void populateGlobals(final List<FactData> globals) throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { for (final FactData fact : globals) { factPopulator.add( factPopulatorFactory.createGlobalFactPopulator(fact)); } factPopulator.populate(); } }
apache-2.0
LQJJ/demo
126-go-common-master/app/admin/main/block/model/model.go
5392
package model import ( "time" ) // BlockStatus 封禁状态 0. 未封禁 1. 永久封禁 2. 限时封禁 type BlockStatus uint8 const ( // BlockStatusFalse 未封禁 BlockStatusFalse BlockStatus = iota // BlockStatusForever 永久封禁 BlockStatusForever // BlockStatusLimit 限时封禁 BlockStatusLimit // BlockStatusCredit 小黑屋封禁 BlockStatusCredit ) // BlockSource 封禁来源 1. 小黑屋(小黑屋和manager后台封禁) 2. 系统封禁(反作弊及监控系统上报) 3.解封 (所有后台,用户前台自助的解封) type BlockSource uint8 // Contain . func (b BlockSource) Contain() bool { switch b { case BlockSourceBlackHouse, BlockSourceSys, BlockSourceRemove: return true default: return false } } const ( // BlockSourceBlackHouse 小黑屋封禁 BlockSourceBlackHouse BlockSource = iota + 1 // BlockSourceSys 系统封禁 BlockSourceSys // BlockSourceRemove 解封 BlockSourceRemove ) // String . func (b BlockSource) String() string { switch b { case BlockSourceBlackHouse: return "小黑屋封禁" case BlockSourceSys: return "系统封禁" case BlockSourceRemove: return "解封" default: return "" } } const ( // BlockLogBizID 用户审核日志 BlockLogBizID int = 122 ) // BlockArea 封禁业务 type BlockArea uint8 // Contain . func (b BlockArea) Contain() bool { switch b { case BlockAreaNone, BlockAreaReply, BlockAreaDanmaku, BlockAreaMessage, BlockAreaTag, BlockAreaProfile, BlockAreaArchive, BlockAreaMusic, BlockAreaArticle, BlockAreaSpaceBanner, BlockAreaDynamic, BlockAreaAlbum, BlockAreaQuickVideo: return true default: return false } } func (b BlockArea) String() string { switch b { case BlockAreaReply: return "评论" case BlockAreaDanmaku: return "弹幕" case BlockAreaMessage: return "私信" case BlockAreaTag: return "标签" case BlockAreaProfile: return "个人资料" case BlockAreaArchive: return "投稿" case BlockAreaMusic: return "音频" case BlockAreaArticle: return "专栏" case BlockAreaSpaceBanner: return "空间头图" case BlockAreaDynamic: return "动态" case BlockAreaAlbum: return "相册" case BlockAreaQuickVideo: return "小视频" default: return "" } } // const . const ( BlockAreaNone BlockArea = iota BlockAreaReply BlockAreaDanmaku BlockAreaMessage BlockAreaTag BlockAreaProfile // 个人资料 BlockAreaArchive BlockAreaMusic BlockAreaArticle BlockAreaSpaceBanner // 空间头图 BlockAreaDynamic // 动态 BlockAreaAlbum // 相册 BlockAreaQuickVideo //小视频 ) // BlockAction . type BlockAction uint8 const ( // BlockActionLimit 限时封禁 BlockActionLimit BlockAction = iota + 1 // BlockActionForever 永久封禁 BlockActionForever // BlockActionAdminRemove 后台解封 BlockActionAdminRemove // BlockActionSelfRemove 自动解封 BlockActionSelfRemove ) // String . func (b BlockAction) String() string { switch b { case BlockActionLimit: return "限时封禁" case BlockActionForever: return "永久封禁" case BlockActionAdminRemove: return "后台解封" case BlockActionSelfRemove: return "自动解封" default: return "" } } // BlockInfo 封禁信息 type BlockInfo struct { MID int64 `json:"mid"` Nickname string `json:"nickname"` Username string `json:"username"` // 注册生成时不可更改的username Tel string `json:"tel"` TelStatus int32 `json:"tel_status"` Mail string `json:"mail"` // 绑定的邮箱 Level int32 `json:"level"` SpyScore int8 `json:"spy_score"` FigureRank int8 `json:"figure_rank"` RegTime int64 `json:"reg_time"` BlockStatus BlockStatus `json:"block_status"` // blockStatus 封禁状态 0. 未封禁 1. 永久封禁 2. 限时封禁 BlockCount int `json:"block_count"` } // ParseStatus . func (b *BlockInfo) ParseStatus(db *DBUser) { switch db.Status { case BlockStatusCredit: b.BlockStatus = BlockStatusLimit default: b.BlockStatus = db.Status } } // BlockHistory 封禁历史 type BlockHistory struct { Source BlockSource `json:"type"` Operator string `json:"operator"` // 操作人 Reason string `json:"reason"` // 封禁原因 Action BlockAction `json:"action"` // 操作类型 ActionTime int64 `json:"action_time"` // 操作时间 RemoveTime int64 `json:"remove_time"` // 解封时间 Comment string `json:"comment"` } // ParseDB . func (b *BlockHistory) ParseDB(data *DBHistory) { b.Source = data.Source b.Operator = data.AdminName if data.Area.String() == "" { b.Reason = data.Reason } else { b.Reason = data.Area.String() + " - " + data.Reason } b.Action = data.Action b.ActionTime = data.StartTime.Unix() if b.Action == BlockActionLimit { b.RemoveTime = data.StartTime.Add(time.Second * time.Duration(data.Duration)).Unix() } b.Comment = data.Comment } // BlockMessage 通知消息体 type BlockMessage struct { MID int64 `json:"mid"` // 用户mid Area BlockArea `json:"area"` // BlockArea 封禁类型 1. 小黑屋(小黑屋和manager后台封禁) 2. 系统封禁(反作弊及监控系统上报) 3.解封 (所有后台,用户前台自助的解封) Status BlockStatus `json:"status"` // blockStatus 封禁状态 0. 未封禁 1. 永久封禁 2. 限时封禁 }
apache-2.0
mjn19172/Savu
savu/plugins/fastxrf_fitting.py
10769
# Copyright 2014 Diamond Light Source 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. """ .. module:: FastXRF fitting :platform: Unix :synopsis: A plugin to fit XRF spectra quickly .. moduleauthor:: Aaron D. Parsons <scientificsoftware@diamond.ac.uk> """ import logging from flupy.xrf_data_handling.xrf_io import xrfreader from flupy.xrf_data_handling import XRFDataset import numpy as np from savu.plugins.filter import Filter from savu.plugins.driver.cpu_plugin import CpuPlugin from savu.plugins.utils import register_plugin @register_plugin class FastxrfFitting(Filter, CpuPlugin): """ fast fluorescence fitting with FastXRF. Needs to be on the path :param fit_elements: The elements to fit. Default: 'Zn,Cu,Fe,Cr,Cl,Br,Kr'. :param detector_type: The type of detector we are using. Default: 'Vortex_SDD_Xspress'. :param sample_attenuators: A dictionary of the attentuators used and their thickness. Default: ''. :param detector_distance: sample distance to the detector in mm. Default: 70. :param exit_angle: in degrees. Default: 90.0. :param incident_angle: in degrees. Default: 0.0. :param flux: flux in. Default: 649055.0. :param background: type of background subtraction. Default: 'strip'. :param fit_range: energy of the fit range. Default: [2., 18.]. :param include_pileup: Should we included pileup effects. Default: 1. :param include_escape: Should we included escape peaks in the fit. Default: 1. :param average_spectrum: pass it an average to do the strip/snipping on. Default: None. """ def __init__(self): logging.debug("Starting fast fitter") super(FastxrfFitting, self).__init__("FastxrfFitting") def get_filter_padding(self): return {} def get_max_frames(self): return 1 def pre_process(self, exp): """ This method is called after the plugin has been created by the pipeline framework as a pre-processing step. """ in_data_list = self.parameters["in_datasets"] in_d1 = exp.index["in_data"][in_data_list[0]] mData = in_d1.meta_data # the metadata # populate the dictionary from the input parameters xrfd=XRFDataset() # now to overide the experiment xrfd.paramdict["Experiment"]={} xrfd.paramdict["Experiment"]["incident_energy_keV"] = mData.get_meta_data("mono_energy")/1000. xrfd.paramdict["Experiment"]["collection_time"] = 1 xrfd.paramdict["Experiment"]['Attenuators'] = self.parameters['sample_attenuators'] xrfd.paramdict["Experiment"]['detector_distance'] = self.parameters['detector_distance'] xrfd.paramdict["Experiment"]['elements'] = self.parameters['fit_elements'].split(',')#['Zn', 'Cu', 'Fe', 'Cr', 'Cl', 'Br', 'Kr']# xrfd.paramdict["Experiment"]['incident_angle'] = self.parameters['incident_angle'] xrfd.paramdict["Experiment"]['exit_angle'] = self.parameters['exit_angle'] xrfd.paramdict["Experiment"]['photon_flux'] = self.parameters['flux'] # overide the detector # xrfd.paramdict["Detectors"]={} # xrfd.paramdict["Detectors"]["type"] = 'Vortex_SDD_Xspress'#str(self.parameters['detector_type']) # overide the fitting parameters xrfd.paramdict["FitParams"]["background"] = 'strip'#self.parameters['background'] xrfd.paramdict["FitParams"]["fitted_energy_range_keV"] = [2., 18.]#self.parameters['fit_range'] xrfd.paramdict["FitParams"]["include_pileup"] = 1#self.parameters['include_pileup'] xrfd.paramdict["FitParams"]["include_escape"] = 1#self.parameters['include_escape'] datadict = {} datadict["rows"] = self.get_max_frames() datadict["cols"] = 1 datadict["average_spectrum"] = mData.get_meta_data("average")#self.parameters['average_spectrum'] datadict["Detectors"]={} datadict["Detectors"]["type"] = 'Vortex_SDD_Xspress' xrfd.xrfdata(datadict) xrfd._createSpectraMatrix() #I only know the output shape here!xrfd.matrixdict['Total_Matrix'].shape params = [xrfd] return params def filter_frame(self, data, params): logging.debug("Running azimuthal integration") xrfd = params[0] print np.squeeze(data).shape xrfd.datadict['data'] = np.squeeze(data) print "I'm here" xrfd.fitbatch() characteristic_curves=xrfd.matrixdict["Total_Matrix"] weights = xrfd.fitdict['parameters'] op = characteristic_curves*weights op = op.swapaxes(0,1) return op def setup(self, experiment): chunk_size = self.get_max_frames() #-------------------setup input datasets------------------------- # get a list of input dataset names required for this plugin in_data_list = self.parameters["in_datasets"] # get all input dataset objects in_d1 = experiment.index["in_data"][in_data_list[0]] # set all input data patterns in_d1.set_current_pattern_name("SPECTRUM") # we take in a pattern # set frame chunk in_d1.set_nFrames(chunk_size) #---------------------------------------------------------------- #------------------setup output datasets------------------------- # get a list of output dataset names created by this plugin ''' This type of dataset should output a few things I think. 1/ Concentration/sum map (including the channel name) 2/ The average fit 3/ The background/scattering fit 4/ The chisq 5/ The residual (another spectrum I guess...) if I have these: for i,j in enumerate(xrfd.matrixdict['Descriptions']):print i,j DICT -descriptions xrfd.matrixdict['Total_Matrix'] # CHARACTERISTIC CURVES xrfd.fitdict['parameters'] # WEIGHTS xrfd.fitdict['chisq'] - NUMBER xrfd.fitdict['resid'] SPECTRUM - the rest is easy (ish) for now, will just hack it slightly...(sorry :-S) ''' # will force the code to tell me what it will output!DO IT mData = in_d1.meta_data datadict = {} xrfd=XRFDataset() # first chuck in the fitting parameters xrfd.paramdict["FitParams"]["background"] = self.parameters['background'] xrfd.paramdict["FitParams"]["fitted_energy_range_keV"] = self.parameters['fit_range'] xrfd.paramdict["FitParams"]["include_pileup"] = self.parameters['include_pileup'] xrfd.paramdict["FitParams"]["include_escape"] = self.parameters['include_escape'] xrfd.paramdict["Experiment"]['elements'] = self.parameters['fit_elements'].split(',') print xrfd.paramdict["Experiment"]['elements'],type(xrfd.paramdict["Experiment"]['elements']) datadict["cols"] = 1 datadict["rows"] = 1 datadict["Experiment"]={} datadict["Experiment"]["incident_energy_keV"] = mData.get_meta_data("mono_energy")/1000. datadict["Experiment"]["collection_time"] =1. #or indeed anything. This isn't used! datadict["Detectors"]={} datadict["Detectors"]["type"] = self.parameters['detector_type'] npts = xrfd.paramdict['Detectors'][datadict["Detectors"]["type"]]['no_of_pixels'] datadict["average_spectrum"] = np.zeros((npts,))#mData.get_meta_data("average") xrfd.xrfdata(datadict) #print type(datadict["Experiment"]["incident_energy_keV"]) xrfd._createSpectraMatrix() metadata=xrfd.matrixdict['Descriptions'] num_els = len(xrfd.matrixdict['Descriptions']) spectrum_length = len(xrfd.paramdict["FitParams"]["mca_channels_used"][0]) out_data_list = self.parameters["out_datasets"] out_d1 = experiment.create_data_object("out_data", out_data_list[0]) out_d1.meta_data.copy_dictionary(in_d1.meta_data.get_dictionary(), rawFlag=True) out_d1.meta_data.set_meta_data('Curve_names',metadata) characteristic_curves=xrfd.matrixdict["Total_Matrix"] out_d1.meta_data.set_meta_data('Characteristic_curves',characteristic_curves) # set pattern for this plugin and the shape out_d1.set_current_pattern_name("SPECTRUM_STACK") inshape = in_d1.get_shape() outshape = inshape[:3]+(num_els, spectrum_length) out_d1.set_shape(outshape)# # now to set the output data patterns out_d1.add_pattern("SPECTRUM_STACK", core_dir = (-2,-1), slice_dir = range(len(outshape)-2))# for some reason I HAVE to have this.... annoying out_d1.add_pattern("SPECTRUM", core_dir = (-1,), slice_dir = range(len(outshape)-1)) out_d1.add_pattern("CHANNEL", core_dir = (-2,), slice_dir = range(len(outshape)-2).append(-1)) # we haven't changed the motors yet so... motor_type=mData.get_meta_data("motor_type") projection = [] projection_slice = [] for item,key in enumerate(motor_type): if key == 'translation': projection.append(item) elif key !='translation': projection_slice.append(item) if key == 'rotation': rotation = item # we will assume one rotation for now to save my headache projdir = tuple(projection) projsli = tuple(projection_slice) if mData.get_meta_data("is_map"): ndims = range(len(outshape)) ovs = [] for i in ndims: if i!=projdir[0]: if i!=projdir[1]: ovs.append(i) out_d1.add_pattern("PROJECTION", core_dir = projdir, slice_dir = ovs)# two translation axes if mData.get_meta_data("is_tomo"): ndims = range(len(outshape)) ovs = [] for i in ndims: if i!=rotation: if i!=projdir[1]: ovs.append(i) out_d1.add_pattern("SINOGRAM", core_dir = (rotation,projdir[-1]), slice_dir = ovs)#rotation and fast axis # set frame chunk print outshape out_d1.set_nFrames(chunk_size)
apache-2.0
jthurne/kanban-salad
scanner-client-core/src/test/java/org/kanbansalad/scanner/client/ListModelTest.java
8715
/** * Copyright 2013 Jim Hurne and Joseph Kramer * * 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.kanbansalad.scanner.client; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import java.io.File; import java.io.IOException; import java.util.Calendar; import java.util.Date; import java.util.List; import org.apache.commons.io.FileUtils; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.kanbansalad.scanner.client.ListModel; import org.kanbansalad.scanner.client.tag.CellTag; import org.kanbansalad.scanner.client.tag.EmptyTag; import org.kanbansalad.scanner.client.tag.IncorrectlyFormattedTag; import org.kanbansalad.scanner.client.tag.ScanableTag; import org.kanbansalad.scanner.client.tag.TaskTag; public class ListModelTest { private static final int NONE = -1; @Rule public TemporaryFolder folder = new TemporaryFolder(); private ListModel model; private File csvFile; private int lineIndex; @Before public void given_a_model() throws Exception { File tempFile = folder.newFile(); String filenameTemplate = tempFile.toString() + "-%tF-%<tH%<tM.csv"; model = new ListModel(filenameTemplate); } @Test public void adds_header_to_csv_file() throws Exception { when.model_dumped_to_csv(); then.line(0).should_be_equal_to( "Date\tTime\tSwimlane\tQueue\tID\tName\tSize"); } @Test public void uses_date_in_resulting_file_name() throws Exception { when.model_dumped_to_csv_with(date_april_12_2013_at_13_23()); then.the_generated_file_name_should_contain("2013-04-12-1323"); } @Test public void writes_cell_and_tasks_on_one_line() throws Exception { given.the_model_contains( new CellTag("Wings", "Review"), new TaskTag("12345", "John can move the flap", "2") ); when.model_dumped_to_csv_with(date_april_12_2013_at_13_23()); then.line(1) .should_be_equal_to( "2013-04-12\t13:23\tWings\tReview\t12345\tJohn can move the flap\t2"); } @Test public void writes_multiple_tasks_following_a_cell() throws Exception { given.the_model_contains( new CellTag("Wings", "Review"), new TaskTag("12345", "John can move the flap", "2"), new TaskTag("54321", "Jane can fill the wing with gas", "8") ); when.model_dumped_to_csv_with(date_april_12_2013_at_13_23()); then.line(1) .should_be_equal_to( "2013-04-12\t13:23\tWings\tReview\t12345\tJohn can move the flap\t2"); then.line(2) .should_be_equal_to( "2013-04-12\t13:23\tWings\tReview\t54321\tJane can fill the wing with gas\t8"); } @Test public void writes_multiple_cell_and_task_clusters() throws Exception { given.the_model_contains( new CellTag("Wings", "Review"), new TaskTag("12345", "John can move the flap", "2"), new TaskTag("54321", "Jane can fill the wing with gas", "8"), new CellTag("Flight Control", "Done"), new TaskTag("45433", "Jill can read the speed", "XL") ); when.model_dumped_to_csv_with(date_april_12_2013_at_13_23()); then.line(1) .should_be_equal_to( "2013-04-12\t13:23\tWings\tReview\t12345\tJohn can move the flap\t2"); then.line(2) .should_be_equal_to( "2013-04-12\t13:23\tWings\tReview\t54321\tJane can fill the wing with gas\t8"); then.line(3) .should_be_equal_to( "2013-04-12\t13:23\tFlight Control\tDone\t45433\tJill can read the speed\tXL"); } @Test public void skips_empty_cells() throws Exception { given.the_model_contains( new CellTag("Empty", "No Tasks"), new CellTag("Wings", "Review"), new TaskTag("12345", "John can move the flap", "2"), new TaskTag("54321", "Jane can fill the wing with gas", "8") ); when.model_dumped_to_csv_with(date_april_12_2013_at_13_23()); then.line(1) .should_be_equal_to( "2013-04-12\t13:23\tWings\tReview\t12345\tJohn can move the flap\t2"); then.line(2) .should_be_equal_to( "2013-04-12\t13:23\tWings\tReview\t54321\tJane can fill the wing with gas\t8"); } @Test public void ignores_empty_tags() throws Exception { given.the_model_contains( new CellTag("Wings", "Review"), new TaskTag("12345", "John can move the flap", "2"), new EmptyTag(), new TaskTag("54321", "Jane can fill the wing with gas", "8") ); when.model_dumped_to_csv_with(date_april_12_2013_at_13_23()); then.line(1) .should_be_equal_to( "2013-04-12\t13:23\tWings\tReview\t12345\tJohn can move the flap\t2"); then.line(2) .should_be_equal_to( "2013-04-12\t13:23\tWings\tReview\t54321\tJane can fill the wing with gas\t8"); } @Test public void ignores_incorrectly_formatted_tags() throws Exception { given.the_model_contains( new CellTag("Wings", "Review"), new TaskTag("12345", "John can move the flap", "2"), new IncorrectlyFormattedTag("bad data"), new TaskTag("54321", "Jane can fill the wing with gas", "8") ); when.model_dumped_to_csv_with(date_april_12_2013_at_13_23()); then.line(1) .should_be_equal_to( "2013-04-12\t13:23\tWings\tReview\t12345\tJohn can move the flap\t2"); then.line(2) .should_be_equal_to( "2013-04-12\t13:23\tWings\tReview\t54321\tJane can fill the wing with gas\t8"); } @Test public void resets_the_selected_tag__when_the_model_is_cleared() throws Exception { given.the_model_contains( new TaskTag("12345", "John can move the flap", "2"), new TaskTag("54321", "Jane can fill the wing with gas", "8") ); and.the_selected_tag_is(1); when.model.clear(); then.the_selected_tag_should_be(NONE); } private void the_selected_tag_should_be(int expected) { assertThat(model.getSelectedTagIndex(), is(equalTo(expected))); } private void the_selected_tag_is(int selectedTagIndex) { model.setSelectedTag(selectedTagIndex); } private void the_model_contains(ScanableTag... scanables) { for (ScanableTag scanable : scanables) { model.add(scanable); } } private Date date_april_12_2013_at_13_23() { Calendar cal = Calendar.getInstance(); cal.set(2013, 3, 12, 13, 23); return cal.getTime(); } private void model_dumped_to_csv() throws IOException { csvFile = model.dumpToCsv(); } private void model_dumped_to_csv_with(Date currentDate) throws IOException { csvFile = model.dumpToCsv(currentDate); } private void should_be_equal_to(String expectedContent) throws Exception { List<String> lines = FileUtils.readLines(csvFile); assertThat(lines.get(lineIndex), is(equalTo(expectedContent))); } private void the_generated_file_name_should_contain(String dateString) { assertThat(csvFile.toString(), containsString(dateString)); } private ListModelTest line(int i) { this.lineIndex = i; return this; } @SuppressWarnings("unused") private ListModelTest given = this, when = this, then = this, and = this, with = this; }
apache-2.0
QNJR-GROUP/EasyTransaction
easytrans-core/src/main/java/com/yiqiniu/easytrans/idgen/impl/ConstantBusinessCodeGenerator.java
258
package com.yiqiniu.easytrans.idgen.impl; import com.yiqiniu.easytrans.idgen.BusinessCodeGenerator; public class ConstantBusinessCodeGenerator implements BusinessCodeGenerator { @Override public String getCurrentBusinessCode() { return "default"; } }
apache-2.0
brain461/ar_too
ar_too/__init__.py
197
# -*- coding: utf-8 -*- from .api import get_artifactory_config_from_url, update_ldapSettings_from_dict, update_artifactory_config, cr_repository, update_password, get_repo_configs, get_repo_list
apache-2.0
gubaijin/single
ui/src/main/java/com.gplucky.ui/controller/TaskController.java
1371
package com.gplucky.ui.controller; import com.gplucky.ui.service.TaskService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; /** * Created by ehsy_it on 2017/3/11. */ @Controller public class TaskController { @Autowired private TaskService taskService; @RequestMapping("/task") public String task() { return "task"; } @RequestMapping("/init1") @ResponseBody public String init1(String pwd) { return taskService.initSHList(pwd); } @RequestMapping("/init2") @ResponseBody public String init2(String pwd) { return taskService.initSZList(pwd); } @RequestMapping("/init3") @ResponseBody public String init3(String pwd) { return taskService.resetStockUpAndDown(pwd); } @RequestMapping("/init4") @ResponseBody public String init4(String pwd) { return taskService.initStockToMongo(pwd); } @RequestMapping("/base1") @ResponseBody public String base1() { return taskService.fetchStockInfo(); } @RequestMapping("/base2") @ResponseBody public String base2() { return taskService.fetchCompensation(); } }
apache-2.0
frincon/openeos
modules/org.openeos.services.ui/src/main/java/org/openeos/services/ui/ConstraintViolationExceptionResolver.java
1224
/** * Copyright 2014 Fernando Rincon Martin <frm.rincon@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openeos.services.ui; import org.hibernate.exception.ConstraintViolationException; public abstract class ConstraintViolationExceptionResolver implements ThrowableToMessageResolver { @Override public String resolveMessage(Throwable t) { if (t instanceof ConstraintViolationException) { String constraintName = ((ConstraintViolationException) t).getConstraintName(); if (constraintName != null) { return resolveMessageForConstraintName(constraintName); } } return null; } protected abstract String resolveMessageForConstraintName(String constraintName); }
apache-2.0
mosuka/indigo
server/rest/handler/bulk.go
3079
// Copyright (c) 2017 Minoru Osuka // // 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 handler import ( "encoding/json" "github.com/buger/jsonparser" "github.com/mosuka/indigo/client" log "github.com/sirupsen/logrus" "golang.org/x/net/context" "io/ioutil" "net/http" "strconv" ) type BulkHandler struct { client *client.IndigoClientWrapper } func NewBulkHandler(c *client.IndigoClientWrapper) *BulkHandler { return &BulkHandler{ client: c, } } func (h *BulkHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) { log.WithFields(log.Fields{ "req": req, }).Info("") // read request data, err := ioutil.ReadAll(req.Body) if err != nil { log.WithFields(log.Fields{ "err": err, }).Error("failed to read request body") Error(w, err.Error(), http.StatusBadRequest) return } // get batch_size batchSize, err := jsonparser.GetInt(data, "batch_size") if err != nil { log.WithFields(log.Fields{ "err": err, }).Error("failed to get batch size") Error(w, err.Error(), http.StatusBadRequest) return } // get requests requestsBytes, _, _, err := jsonparser.Get(data, "requests") if err != nil { log.WithFields(log.Fields{ "err": err, }).Error("failed to get update requests") Error(w, err.Error(), http.StatusBadRequest) return } var requests []map[string]interface{} err = json.Unmarshal(requestsBytes, &requests) if err != nil { log.WithFields(log.Fields{ "err": err, }).Error("failed to create update requests") Error(w, err.Error(), http.StatusBadRequest) return } // overwrite request if req.URL.Query().Get("batchSize") != "" { i, err := strconv.Atoi(req.URL.Query().Get("batchSize")) if err != nil { log.WithFields(log.Fields{ "err": err, }).Error("failed to set batch size") Error(w, err.Error(), http.StatusBadRequest) return } batchSize = int64(i) } if batchSize <= 0 { batchSize = int64(DefaultBatchSize) } // request resp, err := h.client.Bulk(context.Background(), requests, int32(batchSize)) if err != nil { log.WithFields(log.Fields{ "err": err, }).Error("failed to index documents in bulk") Error(w, err.Error(), http.StatusServiceUnavailable) return } // output response output, err := json.MarshalIndent(resp, "", " ") if err != nil { log.WithFields(log.Fields{ "err": err, }).Error("failed to create response") Error(w, err.Error(), http.StatusServiceUnavailable) return } w.Header().Set("Content-Type", "application/json; charset=utf-8") w.WriteHeader(http.StatusOK) w.Write(output) return }
apache-2.0
NextGenIntelligence/gerrit
gerrit-gwtui/src/main/java/com/google/gerrit/client/changes/ChangeTable.java
17961
// Copyright (C) 2008 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.client.changes; import static com.google.gerrit.client.FormatUtil.relativeFormat; import static com.google.gerrit.client.FormatUtil.shortFormat; import com.google.gerrit.client.Gerrit; import com.google.gerrit.client.account.AccountInfo; import com.google.gerrit.client.changes.ChangeInfo.LabelInfo; import com.google.gerrit.client.ui.AccountLinkPanel; import com.google.gerrit.client.ui.BranchLink; import com.google.gerrit.client.ui.ChangeLink; import com.google.gerrit.client.ui.NavigationTable; import com.google.gerrit.client.ui.NeedsSignInKeyCommand; import com.google.gerrit.client.ui.ProjectLink; import com.google.gerrit.common.PageLinks; import com.google.gerrit.extensions.client.ListChangesOption; import com.google.gerrit.reviewdb.client.AccountGeneralPreferences.ReviewCategoryStrategy; import com.google.gerrit.reviewdb.client.Change; import com.google.gwt.dom.client.Element; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.KeyPressEvent; import com.google.gwt.user.client.ui.FlexTable.FlexCellFormatter; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.HTMLTable.Cell; import com.google.gwt.user.client.ui.HTMLTable.CellFormatter; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.InlineLabel; import com.google.gwt.user.client.ui.SimplePanel; import com.google.gwt.user.client.ui.UIObject; import com.google.gwt.user.client.ui.Widget; import java.util.ArrayList; import java.util.Collections; import java.util.EnumSet; import java.util.List; import java.util.Set; public class ChangeTable extends NavigationTable<ChangeInfo> { // If changing default options, also update in // ChangeIT#defaultSearchDoesNotTouchDatabase(). static final Set<ListChangesOption> OPTIONS = Collections.unmodifiableSet(EnumSet.of( ListChangesOption.LABELS, ListChangesOption.DETAILED_ACCOUNTS)); private static final int C_STAR = 1; private static final int C_ID = 2; private static final int C_SUBJECT = 3; private static final int C_STATUS = 4; private static final int C_OWNER = 5; private static final int C_PROJECT = 6; private static final int C_BRANCH = 7; private static final int C_LAST_UPDATE = 8; private static final int C_SIZE = 9; private static final int BASE_COLUMNS = 10; private final List<Section> sections; private int columns; private boolean showLegacyId; private List<String> labelNames; public ChangeTable() { super(Util.C.changeItemHelp()); columns = BASE_COLUMNS; labelNames = Collections.emptyList(); if (Gerrit.isSignedIn()) { keysAction.add(new StarKeyCommand(0, 's', Util.C.changeTableStar())); showLegacyId = Gerrit.getUserAccount() .getGeneralPreferences() .isLegacycidInChangeTable(); } sections = new ArrayList<>(); table.setText(0, C_STAR, ""); table.setText(0, C_ID, Util.C.changeTableColumnID()); table.setText(0, C_SUBJECT, Util.C.changeTableColumnSubject()); table.setText(0, C_STATUS, Util.C.changeTableColumnStatus()); table.setText(0, C_OWNER, Util.C.changeTableColumnOwner()); table.setText(0, C_PROJECT, Util.C.changeTableColumnProject()); table.setText(0, C_BRANCH, Util.C.changeTableColumnBranch()); table.setText(0, C_LAST_UPDATE, Util.C.changeTableColumnLastUpdate()); table.setText(0, C_SIZE, Util.C.changeTableColumnSize()); final FlexCellFormatter fmt = table.getFlexCellFormatter(); fmt.addStyleName(0, C_STAR, Gerrit.RESOURCES.css().iconHeader()); for (int i = C_ID; i < columns; i++) { fmt.addStyleName(0, i, Gerrit.RESOURCES.css().dataHeader()); } if (!showLegacyId) { fmt.addStyleName(0, C_ID, Gerrit.RESOURCES.css().dataHeaderHidden()); } table.addClickHandler(new ClickHandler() { @Override public void onClick(final ClickEvent event) { final Cell cell = table.getCellForEvent(event); if (cell == null) { return; } if (cell.getCellIndex() == C_STAR) { // Don't do anything (handled by star itself). } else if (cell.getCellIndex() == C_STATUS) { // Don't do anything. } else if (cell.getCellIndex() == C_OWNER) { // Don't do anything. } else if (getRowItem(cell.getRowIndex()) != null) { movePointerTo(cell.getRowIndex()); } } }); } @Override protected Object getRowItemKey(final ChangeInfo item) { return item.legacyId(); } @Override protected void onOpenRow(final int row) { final ChangeInfo c = getRowItem(row); final Change.Id id = c.legacyId(); Gerrit.display(PageLinks.toChange(id)); } private void insertNoneRow(final int row) { insertRow(row); table.setText(row, 0, Util.C.changeTableNone()); final FlexCellFormatter fmt = table.getFlexCellFormatter(); fmt.setColSpan(row, 0, columns); fmt.setStyleName(row, 0, Gerrit.RESOURCES.css().emptySection()); } private void insertChangeRow(final int row) { insertRow(row); applyDataRowStyle(row); } @Override protected void applyDataRowStyle(final int row) { super.applyDataRowStyle(row); final CellFormatter fmt = table.getCellFormatter(); fmt.addStyleName(row, C_STAR, Gerrit.RESOURCES.css().iconCell()); for (int i = C_ID; i < columns; i++) { fmt.addStyleName(row, i, Gerrit.RESOURCES.css().dataCell()); } if (!showLegacyId) { fmt.addStyleName(row, C_ID, Gerrit.RESOURCES.css().dataCellHidden()); } fmt.addStyleName(row, C_SUBJECT, Gerrit.RESOURCES.css().cSUBJECT()); fmt.addStyleName(row, C_STATUS, Gerrit.RESOURCES.css().cSTATUS()); fmt.addStyleName(row, C_OWNER, Gerrit.RESOURCES.css().cOWNER()); fmt.addStyleName(row, C_LAST_UPDATE, Gerrit.RESOURCES.css().cLastUpdate()); fmt.addStyleName(row, C_SIZE, Gerrit.RESOURCES.css().cSIZE()); for (int i = C_SIZE + 1; i < columns; i++) { fmt.addStyleName(row, i, Gerrit.RESOURCES.css().cAPPROVAL()); } } public void updateColumnsForLabels(ChangeList... lists) { labelNames = new ArrayList<>(); for (ChangeList list : lists) { for (int i = 0; i < list.length(); i++) { for (String name : list.get(i).labels()) { if (!labelNames.contains(name)) { labelNames.add(name); } } } } Collections.sort(labelNames); int baseColumns = BASE_COLUMNS; if (baseColumns + labelNames.size() < columns) { int n = columns - (baseColumns + labelNames.size()); for (int row = 0; row < table.getRowCount(); row++) { table.removeCells(row, columns, n); } } columns = baseColumns + labelNames.size(); FlexCellFormatter fmt = table.getFlexCellFormatter(); for (int i = 0; i < labelNames.size(); i++) { String name = labelNames.get(i); int col = baseColumns + i; String abbrev = getAbbreviation(name, "-"); table.setText(0, col, abbrev); table.getCellFormatter().getElement(0, col).setTitle(name); fmt.addStyleName(0, col, Gerrit.RESOURCES.css().dataHeader()); } for (Section s : sections) { if (s.titleRow >= 0) { fmt.setColSpan(s.titleRow, 0, columns); } } } private void populateChangeRow(final int row, final ChangeInfo c, boolean highlightUnreviewed) { CellFormatter fmt = table.getCellFormatter(); if (Gerrit.isSignedIn()) { table.setWidget(row, C_STAR, StarredChanges.createIcon( c.legacyId(), c.starred())); } table.setWidget(row, C_ID, new TableChangeLink(String.valueOf(c.legacyId()), c)); String subject = Util.cropSubject(c.subject()); table.setWidget(row, C_SUBJECT, new TableChangeLink(subject, c)); Change.Status status = c.status(); if (status != Change.Status.NEW) { table.setText(row, C_STATUS, Util.toLongString(status)); } else if (!c.mergeable()) { table.setText(row, C_STATUS, Util.C.changeTableNotMergeable()); } if (c.owner() != null) { table.setWidget(row, C_OWNER, new AccountLinkPanel(c.owner(), status)); } else { table.setText(row, C_OWNER, ""); } table.setWidget(row, C_PROJECT, new ProjectLink(c.projectNameKey())); table.setWidget(row, C_BRANCH, new BranchLink(c.projectNameKey(), c .status(), c.branch(), c.topic())); if (Gerrit.isSignedIn() && Gerrit.getUserAccount().getGeneralPreferences() .isRelativeDateInChangeTable()) { table.setText(row, C_LAST_UPDATE, relativeFormat(c.updated())); } else { table.setText(row, C_LAST_UPDATE, shortFormat(c.updated())); } int col = C_SIZE; if (Gerrit.isSignedIn() && !Gerrit.getUserAccount().getGeneralPreferences() .isSizeBarInChangeTable()) { table.setText(row, col, Util.M.insertionsAndDeletions(c.insertions(), c.deletions())); } else { table.setWidget(row, col, getSizeWidget(c)); fmt.getElement(row, col).setTitle( Util.M.insertionsAndDeletions(c.insertions(), c.deletions())); } col++; for (int idx = 0; idx < labelNames.size(); idx++, col++) { String name = labelNames.get(idx); LabelInfo label = c.label(name); if (label == null) { fmt.getElement(row, col).setTitle(Gerrit.C.labelNotApplicable()); fmt.addStyleName(row, col, Gerrit.RESOURCES.css().labelNotApplicable()); continue; } String user; String info; ReviewCategoryStrategy reviewCategoryStrategy = Gerrit.isSignedIn() ? Gerrit.getUserAccount().getGeneralPreferences() .getReviewCategoryStrategy() : ReviewCategoryStrategy.NONE; if (label.rejected() != null) { user = label.rejected().name(); info = getReviewCategoryDisplayInfo(reviewCategoryStrategy, label.rejected()); if (info != null) { FlowPanel panel = new FlowPanel(); panel.add(new Image(Gerrit.RESOURCES.redNot())); panel.add(new InlineLabel(info)); table.setWidget(row, col, panel); } else { table.setWidget(row, col, new Image(Gerrit.RESOURCES.redNot())); } } else if (label.approved() != null) { user = label.approved().name(); info = getReviewCategoryDisplayInfo(reviewCategoryStrategy, label.approved()); if (info != null) { FlowPanel panel = new FlowPanel(); panel.add(new Image(Gerrit.RESOURCES.greenCheck())); panel.add(new InlineLabel(info)); table.setWidget(row, col, panel); } else { table.setWidget(row, col, new Image(Gerrit.RESOURCES.greenCheck())); } } else if (label.disliked() != null) { user = label.disliked().name(); info = getReviewCategoryDisplayInfo(reviewCategoryStrategy, label.disliked()); String vstr = String.valueOf(label._value()); if (info != null) { vstr = vstr + " " + info; } fmt.addStyleName(row, col, Gerrit.RESOURCES.css().negscore()); table.setText(row, col, vstr); } else if (label.recommended() != null) { user = label.recommended().name(); info = getReviewCategoryDisplayInfo(reviewCategoryStrategy, label.recommended()); String vstr = "+" + label._value(); if (info != null) { vstr = vstr + " " + info; } fmt.addStyleName(row, col, Gerrit.RESOURCES.css().posscore()); table.setText(row, col, vstr); } else { table.clearCell(row, col); continue; } fmt.addStyleName(row, col, Gerrit.RESOURCES.css().singleLine()); if (user != null) { // Some web browsers ignore the embedded newline; some like it; // so we include a space before the newline to accommodate both. fmt.getElement(row, col).setTitle(name + " \nby " + user); } } boolean needHighlight = false; if (highlightUnreviewed && !c.reviewed()) { needHighlight = true; } final Element tr = fmt.getElement(row, 0).getParentElement(); UIObject.setStyleName(tr, Gerrit.RESOURCES.css().needsReview(), needHighlight); setRowItem(row, c); } private static String getReviewCategoryDisplayInfo( ReviewCategoryStrategy reviewCategoryStrategy, AccountInfo accountInfo) { switch (reviewCategoryStrategy) { case NAME: return accountInfo.name(); case EMAIL: return accountInfo.email(); case USERNAME: return accountInfo.username(); case ABBREV: return getAbbreviation(accountInfo.name(), " "); default: return null; } } private static String getAbbreviation(String name, String token) { StringBuilder abbrev = new StringBuilder(); if (name != null) { for (String t : name.split(token)) { abbrev.append(t.substring(0, 1).toUpperCase()); } } return abbrev.toString(); } private static Widget getSizeWidget(ChangeInfo c) { int largeChangeSize = Gerrit.getConfig().getLargeChangeSize(); int changedLines = c.insertions() + c.deletions(); int p = 100; if (changedLines < largeChangeSize) { p = changedLines * 100 / largeChangeSize; } int width = Math.max(2, 70 * p / 100); int red = p >= 50 ? 255 : (int) Math.round((p) * 5.12); int green = p <= 50 ? 255 : (int) Math.round(256 - (p - 50) * 5.12); String bg = "#" + toHex(red) + toHex(green) + "00"; SimplePanel panel = new SimplePanel(); panel.setStyleName(Gerrit.RESOURCES.css().changeSize()); panel.setWidth(width + "px"); panel.getElement().getStyle().setBackgroundColor(bg); return panel; } private static String toHex(int i) { String hex = Integer.toHexString(i); return hex.length() == 1 ? "0" + hex : hex; } public void addSection(final Section s) { assert s.parent == null; s.parent = this; s.titleRow = table.getRowCount(); if (s.displayTitle()) { final FlexCellFormatter fmt = table.getFlexCellFormatter(); fmt.setColSpan(s.titleRow, 0, columns); fmt.addStyleName(s.titleRow, 0, Gerrit.RESOURCES.css().sectionHeader()); } else { s.titleRow = -1; } s.dataBegin = table.getRowCount(); insertNoneRow(s.dataBegin); sections.add(s); } private int insertRow(final int beforeRow) { for (final Section s : sections) { if (beforeRow <= s.titleRow) { s.titleRow++; } if (beforeRow < s.dataBegin) { s.dataBegin++; } } return table.insertRow(beforeRow); } private void removeRow(final int row) { for (final Section s : sections) { if (row < s.titleRow) { s.titleRow--; } if (row < s.dataBegin) { s.dataBegin--; } } table.removeRow(row); } public class StarKeyCommand extends NeedsSignInKeyCommand { public StarKeyCommand(int mask, char key, String help) { super(mask, key, help); } @Override public void onKeyPress(final KeyPressEvent event) { int row = getCurrentRow(); ChangeInfo c = getRowItem(row); if (c != null && Gerrit.isSignedIn()) { ((StarredChanges.Icon) table.getWidget(row, C_STAR)).toggleStar(); } } } private final class TableChangeLink extends ChangeLink { private TableChangeLink(final String text, final ChangeInfo c) { super(text, c.legacyId()); } @Override public void go() { movePointerTo(cid); super.go(); } } public static class Section { ChangeTable parent; String titleText; Widget titleWidget; int titleRow = -1; int dataBegin; int rows; private boolean highlightUnreviewed; public void setHighlightUnreviewed(boolean value) { this.highlightUnreviewed = value; } public void setTitleText(final String text) { titleText = text; titleWidget = null; if (titleRow >= 0) { parent.table.setText(titleRow, 0, titleText); } } public void setTitleWidget(final Widget title) { titleWidget = title; titleText = null; if (titleRow >= 0) { parent.table.setWidget(titleRow, 0, title); } } public boolean displayTitle() { if (titleText != null) { setTitleText(titleText); return true; } else if(titleWidget != null) { setTitleWidget(titleWidget); return true; } return false; } public void display(ChangeList changeList) { final int sz = changeList != null ? changeList.length() : 0; final boolean hadData = rows > 0; if (hadData) { while (sz < rows) { parent.removeRow(dataBegin); rows--; } } else { parent.removeRow(dataBegin); } if (sz == 0) { parent.insertNoneRow(dataBegin); return; } while (rows < sz) { parent.insertChangeRow(dataBegin + rows); rows++; } for (int i = 0; i < sz; i++) { parent.populateChangeRow(dataBegin + i, changeList.get(i), highlightUnreviewed); } } } }
apache-2.0
rhaschke/catkin_tools
catkin_tools/context.py
34962
# Copyright 2014 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module implements a class for representing a catkin workspace context""" from __future__ import print_function import os import re import sys from . import metadata from .common import getcwd from .common import printed_fill from .common import remove_ansi_escape from .common import terminal_width from .metadata import find_enclosing_workspace from .resultspace import get_resultspace_environment from .terminal_color import ColorMapper color_mapper = ColorMapper() clr = color_mapper.clr class Context(object): """Encapsulates a catkin workspace's settings which affect build results. This class will validate some of the settings on assignment using the filesystem, but it will never modify the filesystem. For instance, it will raise an exception if the source space does not exist, but it will not create a folder for the build space if it does not already exist. This context can be locked, so that changing the members is prevented. """ CATKIN_SPACES_GROUP = 'catkin_tools.spaces' SPACES = {} STORED_KEYS = [ 'extend_path', 'devel_layout', 'install', 'isolate_install', 'cmake_args', 'make_args', 'jobs_args', 'use_internal_make_jobserver', 'use_env_cache', 'catkin_make_args', 'whitelist', 'blacklist', 'authors', 'maintainers', 'licenses', 'extends', ] EXTRA_KEYS = [ 'workspace', 'profile', 'space_suffix', ] KEYS = [] @classmethod def _create_space_methods(cls, space): def space_abs_getter(self): return getattr(self, '__%s_space_abs' % space) def space_getter(self): return getattr(self, '__%s_space' % space) def space_setter(self, value): if self.__locked: raise RuntimeError("Setting of context members is not allowed while locked.") setattr(self, '__%s_space' % space, value) setattr(self, '__%s_space_abs' % space, os.path.join(self.__workspace, value)) def space_exists(self): """ Returns true if the space exists. """ space_abs = getattr(self, '__%s_space_abs' % space) return os.path.exists(space_abs) and os.path.isdir(space_abs) setattr(cls, '%s_space' % space, property(space_getter, space_setter)) setattr(cls, '%s_space_abs' % space, property(space_abs_getter)) setattr(cls, '%s_space_exists' % space, space_exists) @classmethod def setup_space_keys(cls): """ To be called one time on initial use. Initializes the SPACE_KEYS class members and associated member functions based on available space plugins. """ if cls.KEYS: return from pkg_resources import iter_entry_points for entry_point in iter_entry_points(group=cls.CATKIN_SPACES_GROUP): ep_dict = entry_point.load() cls.STORED_KEYS.append(entry_point.name + '_space') cls.SPACES[entry_point.name] = ep_dict cls._create_space_methods(entry_point.name) cls.KEYS = cls.STORED_KEYS + cls.EXTRA_KEYS @classmethod def load( cls, workspace_hint=None, profile=None, opts=None, strict=False, append=False, remove=False, load_env=True ): """Load a context from a given workspace and profile with optional modifications. This function will try to load a given context from the specified workspace with the following resolution strategy: - existing workspace enclosing given workspace path - existing workspace enclosing "." - given workspace path - "." If a workspace cannot be found, it will assume that the user is specifying a new workspace, unless `strict=True` is given. In this latter case, this function will return None. :param workspace_hint: The hint used to find a workspace (see description for more details) :type workspace_hint: str :param profile: The profile to load the context from, if the profile is None, the active profile is used :type profile: str :param opts: An argparse options namespace containing context keys to override stored context keys :type opts: namespace :param strict: Causes this function to return None if a workspace isn't found :type strict: bool :param append: Appends any list-type opts to existing opts :type append: bool :param remove: Removes any list-type opts from existing opts :type remove: bool :param load_env: Control whether the context loads the resultspace environment for the full build context :type load_env: bool :returns: A potentially valid Context object constructed from the given arguments :rtype: Context """ Context.setup_space_keys() # Initialize dictionary version of opts namespace opts_vars = vars(opts) if opts else {} # Get the workspace (either the given directory or the enclosing ws) workspace_hint = workspace_hint or opts_vars.get('workspace', None) or getcwd() workspace = find_enclosing_workspace(workspace_hint) if not workspace: if strict or not workspace_hint: return None else: workspace = workspace_hint opts_vars['workspace'] = workspace # Get the active profile profile = profile or opts_vars.get('profile', None) or metadata.get_active_profile(workspace) opts_vars['profile'] = profile # Initialize empty metadata/args config_metadata = {} context_args = {} # Get the metadata stored in the workspace if it was found if workspace: key_origins = {} visited_profiles = [] def get_metadata_recursive(profile): config_metadata = metadata.get_metadata(workspace, profile, 'config') visited_profiles.append(profile) if "extends" in config_metadata.keys() and config_metadata["extends"] is not None: base_profile = config_metadata["extends"] if base_profile in visited_profiles: raise IOError("Profile dependency circle detected at dependency from '%s' to '%s'!" % (profile, base_profile)) base = get_metadata_recursive(base_profile) base.update(config_metadata) for key in config_metadata.keys(): key_origins[key] = profile return base for key in config_metadata.keys(): key_origins[key] = profile return config_metadata config_metadata = get_metadata_recursive(profile) context_args.update(config_metadata) # User-supplied args are used to update stored args # Only update context args with given opts which are not none for (k, v) in opts_vars.items(): if k in Context.KEYS and v is not None: # Handle list-type arguments with append/remove functionality if type(context_args.get(k, None)) is list and type(v) is list: if append: context_args[k] += v elif remove: context_args[k] = [w for w in context_args[k] if w not in v] else: context_args[k] = v if workspace: key_origins[k] = profile else: context_args[k] = v if workspace: key_origins[k] = profile context_args["key_origins"] = key_origins # Create the build context ctx = Context(**context_args) # Don't load the cmake config if it's not needed if load_env: ctx.load_env() return ctx @classmethod def save(cls, context): """Save a context in the associated workspace and profile.""" data = context.get_stored_dict() files = {} def save_in_file(file, key, value): if file in files.keys(): files[file][key] = value else: files[file] = {key: value} for key, val in data.items(): if key in context.key_origins: save_in_file(context.key_origins[key], key, val) else: save_in_file(context.profile, key, val) for profile, content in files.items(): metadata.update_metadata( context.workspace, profile, 'config', content) def get_stored_dict(self): """Get the context parameters which should be stored persistently.""" return dict([(k, getattr(self, k)) for k in Context.STORED_KEYS]) def __init__( self, workspace=None, profile=None, extend_path=None, devel_layout=None, install=False, isolate_install=False, cmake_args=None, make_args=None, jobs_args=None, use_internal_make_jobserver=True, use_env_cache=False, catkin_make_args=None, space_suffix=None, whitelist=None, blacklist=None, authors=None, maintainers=None, licenses=None, extends=None, key_origins={}, **kwargs ): """Creates a new Context object, optionally initializing with parameters :param workspace: root of the workspace, defaults to the enclosing workspace :type workspace: str :param profile: profile name, defaults to the default profile :type profile: str :param extend_path: catkin result-space to extend :type extend_path: str :param source_space: relative location of source space, defaults to '<workspace>/src' :type source_space: str :param log_space: relative location of log space, defaults to '<workspace>/logs' :type log_space: str :param build_space: relativetarget location of build space, defaults to '<workspace>/build' :type build_space: str :param devel_space: relative target location of devel space, defaults to '<workspace>/devel' :type devel_space: str :param install_space: relative target location of install space, defaults to '<workspace>/install' :type install_space: str :param isolate_devel: each package will have its own develspace if True, default is False :type isolate_devel: bool :param install: packages will be installed by invoking ``make install``, defaults to False :type install: bool :param isolate_install: packages will be installed to separate folders if True, defaults to False :type isolate_install: bool :param cmake_args: extra cmake arguments to be passed to cmake for each package :type cmake_args: list :param make_args: extra make arguments to be passed to make for each package :type make_args: list :param jobs_args: -j and -l jobs args :type jobs_args: list :param use_internal_make_jobserver: true if this configuration should use an internal make jobserv :type use_internal_make_jobserver: bool :param use_env_cache: true if this configuration should cache job environments loaded from resultspaces :type use_env_cache: bool :param catkin_make_args: extra make arguments to be passed to make for each catkin package :type catkin_make_args: list :param space_suffix: suffix for build, devel, and install spaces which are not explicitly set. :type space_suffix: str :param whitelist: a list of packages to build by default :type whitelist: list :param blacklist: a list of packages to ignore by default :type blacklist: list :raises: ValueError if workspace or source space does not exist :type authors: list :param authors: a list of default authors :type maintainers: list :param maintainers: a list of default maintainers :type licenses: list :param licenses: a list of default licenses :type extends: string :param extends: the name of a profile to use as a base and inherit settings from """ self.__locked = False # Validation is done on assignment self.workspace = workspace self.extend_path = extend_path if extend_path else None self.key_origins = key_origins self.profile = profile # Handle *space assignment and defaults for space, space_dict in Context.SPACES.items(): key_name = space + '_space' default = space_dict['default'] value = kwargs.pop(key_name, default) if value == default and space_suffix and space != 'source': value += space_suffix setattr(self, key_name, value) # Check for unhandled context options if len(kwargs) > 0: print('Warning: Unhandled config context options: {}'.format(kwargs), file=sys.stderr) self.destdir = os.environ['DESTDIR'] if 'DESTDIR' in os.environ else None # Handle package whitelist/blacklist self.whitelist = whitelist or [] self.blacklist = blacklist or [] # Handle default authors/maintainers self.authors = authors or [] self.maintainers = maintainers or [] self.licenses = licenses or 'TODO' # Handle build options self.devel_layout = devel_layout if devel_layout else 'linked' self.install = install self.isolate_install = isolate_install # Handle additional cmake and make arguments self.cmake_args = cmake_args or [] self.make_args = make_args or [] self.jobs_args = jobs_args or [] self.use_internal_make_jobserver = use_internal_make_jobserver self.use_env_cache = use_env_cache self.catkin_make_args = catkin_make_args or [] # List of packages in the workspace is set externally self.packages = [] # List of warnings about the workspace is set internally self.warnings = [] # Initialize environment settings set by load_env self.manual_cmake_prefix_path = None self.cached_cmake_prefix_path = None self.env_cmake_prefix_path = None self.cmake_prefix_path = None self.extends = extends def load_env(self): # Check for CMAKE_PREFIX_PATH in manual cmake args self.manual_cmake_prefix_path = '' for cmake_arg in self.cmake_args: prefix_path_match = re.findall('-DCMAKE_PREFIX_PATH.*?=(.+)', cmake_arg) if len(prefix_path_match) > 0: self.manual_cmake_prefix_path = prefix_path_match[0] # Load and update mirror of 'sticky' CMake information if self.install: sticky_env = get_resultspace_environment(self.install_space_abs, quiet=True) else: sticky_env = get_resultspace_environment(self.devel_space_abs, quiet=True) self.cached_cmake_prefix_path = '' if 'CMAKE_PREFIX_PATH' in sticky_env: split_result_cmake_prefix_path = sticky_env.get('CMAKE_PREFIX_PATH', '').split(':') if len(split_result_cmake_prefix_path) > 1: self.cached_cmake_prefix_path = ':'.join(split_result_cmake_prefix_path[1:]) # Either load an explicit environment or get it from the current environment self.env_cmake_prefix_path = '' if self.extend_path: extended_env = get_resultspace_environment(self.extend_path, quiet=False) self.env_cmake_prefix_path = extended_env.get('CMAKE_PREFIX_PATH', '') if not self.env_cmake_prefix_path: print(clr("@!@{rf}Error:@| Could not load environment from workspace: '%s', " "target environment (env.sh) does not provide 'CMAKE_PREFIX_PATH'" % self.extend_path)) print(extended_env) sys.exit(1) else: # Get the current CMAKE_PREFIX_PATH if 'CMAKE_PREFIX_PATH' in os.environ: split_result_cmake_prefix_path = os.environ['CMAKE_PREFIX_PATH'].split(':') if len(split_result_cmake_prefix_path) > 1 and ( (not self.install and split_result_cmake_prefix_path[0] == self.devel_space_abs) or (self.install and split_result_cmake_prefix_path[0] == self.install_space_abs)): self.env_cmake_prefix_path = ':'.join(split_result_cmake_prefix_path[1:]) else: self.env_cmake_prefix_path = os.environ.get('CMAKE_PREFIX_PATH', '').rstrip(':') # Add warning for empty extend path if (self.devel_layout == 'linked' and (self.extend_path is None and not self.cached_cmake_prefix_path and not self.env_cmake_prefix_path)): self.warnings += [clr( "Your workspace is not extending any other result space, but " "it is set to use a `linked` devel space layout. This " "requires the `catkin` CMake package in your source space " "in order to be built.")] # Add warnings based on conflicing CMAKE_PREFIX_PATH elif self.cached_cmake_prefix_path and self.extend_path: ep_not_in_lcpp = any([self.extend_path in p for p in self.cached_cmake_prefix_path.split(':')]) if not ep_not_in_lcpp: self.warnings += [clr( "Your workspace is configured to explicitly extend a " "workspace which yields a CMAKE_PREFIX_PATH which is " "different from the cached CMAKE_PREFIX_PATH used last time " "this workspace was built.\\n\\n" "If you want to use a different CMAKE_PREFIX_PATH you " "should call @{yf}`catkin clean`@| to remove all " "references to the previous CMAKE_PREFIX_PATH.\\n\\n" "@{cf}Cached CMAKE_PREFIX_PATH:@|\\n\\t@{yf}%s@|\\n" "@{cf}Other workspace to extend:@|\\n\\t@{yf}{_Context__extend_path}@|\\n" "@{cf}Other workspace's CMAKE_PREFIX_PATH:@|\\n\\t@{yf}%s@|" % (self.cached_cmake_prefix_path, self.env_cmake_prefix_path))] elif self.env_cmake_prefix_path and\ self.cached_cmake_prefix_path and\ self.env_cmake_prefix_path != self.cached_cmake_prefix_path: self.warnings += [clr( "Your current environment's CMAKE_PREFIX_PATH is different " "from the cached CMAKE_PREFIX_PATH used the last time this " "workspace was built.\\n\\n" "If you want to use a different CMAKE_PREFIX_PATH you should " "call @{yf}`catkin clean`@| to remove all references to " "the previous CMAKE_PREFIX_PATH.\\n\\n" "@{cf}Cached CMAKE_PREFIX_PATH:@|\\n\\t@{yf}%s@|\\n" "@{cf}Current CMAKE_PREFIX_PATH:@|\\n\\t@{yf}%s@|" % (self.cached_cmake_prefix_path, self.env_cmake_prefix_path))] # Check if prefix path is different from the environment prefix path if self.manual_cmake_prefix_path: self.cmake_prefix_path = self.manual_cmake_prefix_path elif self.cached_cmake_prefix_path: self.cmake_prefix_path = self.cached_cmake_prefix_path else: self.cmake_prefix_path = self.env_cmake_prefix_path def summary(self, notes=[]): # Add warnings (missing dirs in CMAKE_PREFIX_PATH, etc) summary_warnings = self.warnings if not self.initialized(): summary_warnings += [clr( "Workspace `@{yf}{_Context__workspace}@|` is not yet " "initialized. Use the `catkin init` or run `catkin config " "--init`.")] if not self.source_space_exists(): summary_warnings += [clr( "Source space `@{yf}{__source_space_abs}@|` does not yet exist.")] spaces_summary = [] for space, space_dict in sorted(Context.SPACES.items()): spaces_summary.append( clr('@{cf}' + space_dict['space'] + ':@|' + ' ' * (18 - len(space_dict['space'])) + '{' + space + '_missing} @{yf}{__' + space + '_space_abs}@|')) summary = [ [ clr("@{cf}Profile:@| @{yf}{profile}@|"), clr("@{cf}Extending:@| {extend_mode} @{yf}{extend}@|"), clr("@{cf}Workspace:@| @{yf}{_Context__workspace}@|"), ], spaces_summary + [ clr("@{cf}DESTDIR:@| {destdir_missing} @{yf}{_Context__destdir}@|") ], [ clr("@{cf}Devel Space Layout:@| @{yf}{_Context__devel_layout}@|"), clr("@{cf}Install Space Layout:@| @{yf}{install_layout}@|"), ], [ clr("@{cf}Additional CMake Args:@| @{yf}{cmake_args}@|"), clr("@{cf}Additional Make Args:@| @{yf}{make_args}@|"), clr("@{cf}Additional catkin Make Args:@| @{yf}{catkin_make_args}@|"), clr("@{cf}Internal Make Job Server:@| @{yf}{_Context__use_internal_make_jobserver}@|"), clr("@{cf}Cache Job Environments:@| @{yf}{_Context__use_env_cache}@|"), ], [ clr("@{cf}Whitelisted Packages:@| @{yf}{whitelisted_packages}@|"), clr("@{cf}Blacklisted Packages:@| @{yf}{blacklisted_packages}@|"), ] ] # Construct string for extend value if self.extend_path: extend_value = self.extend_path extend_mode = clr('@{gf}[explicit]@|') elif self.cached_cmake_prefix_path: extend_value = self.cmake_prefix_path extend_mode = clr(' @{gf}[cached]@|') elif (self.env_cmake_prefix_path and self.env_cmake_prefix_path != self.devel_space_abs and self.env_cmake_prefix_path != self.install_space_abs): extend_value = self.cmake_prefix_path extend_mode = clr(' @{gf}[env]@|') else: extend_value = 'None' extend_mode = clr(' ') def existence_str(path, used=True): if used: return clr(' @{gf}[exists]@|' if os.path.exists(path) else '@{rf}[missing]@|') else: return clr(' @{bf}[unused]@|') install_layout = 'None' if self.__install: install_layout = 'merged' if not self.__isolate_install else 'isolated' subs = { 'profile': self.profile, 'extend_mode': extend_mode, 'extend': extend_value, 'install_layout': install_layout, 'cmake_prefix_path': (self.cmake_prefix_path or ['Empty']), 'cmake_args': ' '.join(self.__cmake_args or ['None']), 'make_args': ' '.join(self.__make_args + self.__jobs_args or ['None']), 'catkin_make_args': ', '.join(self.__catkin_make_args or ['None']), 'source_missing': existence_str(self.source_space_abs), 'log_missing': existence_str(self.log_space_abs), 'build_missing': existence_str(self.build_space_abs), 'devel_missing': existence_str(self.devel_space_abs), 'install_missing': existence_str(self.install_space_abs, used=self.__install), 'destdir_missing': existence_str(self.destdir, used=self.destdir), 'whitelisted_packages': ' '.join(self.__whitelist or ['None']), 'blacklisted_packages': ' '.join(self.__blacklist or ['None']), } subs.update(**self.__dict__) # Get the width of the shell width = terminal_width() max_length = 0 groups = [] for group in summary: for index, line in enumerate(group): group[index] = line.format(**subs) max_length = min(width, max(max_length, len(remove_ansi_escape(group[index])))) groups.append("\n".join(group)) divider = clr('@{pf}' + ('-' * max_length) + '@|') warning_divider = clr('@{rf}' + ('-' * max_length) + '@|') # Format warnings if len(summary_warnings) == 0: notes = [clr("@!@{cf}Workspace configuration appears valid.@|")] + notes warnings_joined = '' else: warnings_formatted = [ printed_fill(clr('@!@{rf}WARNING:@| ') + sw.format(**subs), max_length) for sw in summary_warnings] warnings_joined = ( "\n\n" + warning_divider + "\n" + ("\n" + warning_divider + "\n").join(warnings_formatted) + "\n" + warning_divider + "\n") return (divider + "\n" + ("\n" + divider + "\n").join(groups) + "\n" + divider + "\n" + ((("\n\n").join(notes) + "\n" + divider) if notes else '') + warnings_joined) @property def workspace(self): return self.__workspace @workspace.setter def workspace(self, value): if self.__locked: raise RuntimeError("Setting of context members is not allowed while locked.") # Validate Workspace if not os.path.exists(value): raise ValueError("Workspace path '{0}' does not exist.".format(value)) self.__workspace = os.path.abspath(value) @property def extend_path(self): return self.__extend_path @extend_path.setter def extend_path(self, value): if value is not None: if not os.path.isabs(value): value = os.path.join(self.workspace, value) # remove double or trailing slashes value = os.path.normpath(value) if not os.path.exists(value): raise ValueError("Resultspace path '{0}' does not exist.".format(value)) self.__extend_path = value def initialized(self): """Check if this context is initialized.""" return self.workspace == find_enclosing_workspace(self.workspace) @property def destdir(self): return self.__destdir @destdir.setter def destdir(self, value): if self.__locked: raise RuntimeError("Setting of context members is not allowed while locked.") self.__destdir = value @property def devel_layout(self): return self.__devel_layout @devel_layout.setter def devel_layout(self, value): if self.__locked: raise RuntimeError("Setting of context members is not allowed while locked.") self.__devel_layout = value @property def merge_devel(self): return self.devel_layout == 'merged' @property def link_devel(self): return self.devel_layout == 'linked' @property def isolate_devel(self): return self.devel_layout == 'isolated' @property def install(self): return self.__install @install.setter def install(self, value): if self.__locked: raise RuntimeError("Setting of context members is not allowed while locked.") self.__install = value @property def merge_install(self): return not self.__isolate_install @property def isolate_install(self): return self.__isolate_install @isolate_install.setter def isolate_install(self, value): if self.__locked: raise RuntimeError("Setting of context members is not allowed while locked.") self.__isolate_install = value @property def cmake_args(self): return self.__cmake_args @cmake_args.setter def cmake_args(self, value): if self.__locked: raise RuntimeError("Setting of context members is not allowed while locked.") self.__cmake_args = value @property def make_args(self): return self.__make_args @make_args.setter def make_args(self, value): if self.__locked: raise RuntimeError("Setting of context members is not allowed while locked.") self.__make_args = value @property def jobs_args(self): return self.__jobs_args @jobs_args.setter def jobs_args(self, value): if self.__locked: raise RuntimeError("Setting of context members is not allowed while locked.") self.__jobs_args = value @property def use_internal_make_jobserver(self): return self.__use_internal_make_jobserver @use_internal_make_jobserver.setter def use_internal_make_jobserver(self, value): if self.__locked: raise RuntimeError("Setting of context members is not allowed while locked.") self.__use_internal_make_jobserver = value @property def use_env_cache(self): return self.__use_env_cache @use_env_cache.setter def use_env_cache(self, value): if self.__locked: raise RuntimeError("Setting of context members is not allowed while locked.") self.__use_env_cache = value @property def catkin_make_args(self): return self.__catkin_make_args @catkin_make_args.setter def catkin_make_args(self, value): if self.__locked: raise RuntimeError("Setting of context members is not allowed while locked.") self.__catkin_make_args = value @property def packages(self): return self.__packages @packages.setter def packages(self, value): if self.__locked: raise RuntimeError("Setting of context members is not allowed while locked.") self.__packages = value @property def whitelist(self): return self.__whitelist @whitelist.setter def whitelist(self, value): self.__whitelist = value @property def blacklist(self): return self.__blacklist @blacklist.setter def blacklist(self, value): self.__blacklist = value @property def authors(self): return self.__authors @authors.setter def authors(self, value): self.__authors = value @property def maintainers(self): return self.__maintainers @maintainers.setter def maintainers(self, value): self.__maintainers = value @property def licenses(self): return self.__licenses @licenses.setter def licenses(self, value): self.__licenses = value @property def extends(self): return self.__extends @extends.setter def extends(self, value): self.__extends = value @property def private_devel_path(self): """The path to the hidden directory in the develspace that contains the symbollically-linked isolated develspaces.""" return os.path.join(self.devel_space_abs, '.private') def package_private_devel_path(self, package): """The path to the linked devel space for a given package.""" return os.path.join(self.private_devel_path, package.name) def package_build_space(self, package): """Get the build directory for a specific package.""" return os.path.join(self.build_space_abs, package.name) def package_devel_space(self, package): """Get the devel directory for a specific package. This is the root of the FHS layout where products are generated. """ if self.merge_devel: return self.devel_space_abs elif self.isolate_devel: return os.path.join(self.devel_space_abs, package.name) elif self.link_devel: return os.path.join(self.private_devel_path, package.name) else: raise ValueError('Unkown devel space layout: {}'.format(self.devel_layout)) def package_install_space(self, package): """Get the install directory for a specific package. This is the root of the FHS layout where products are installed. """ if self.merge_install: return self.install_space_abs elif self.isolate_install: return os.path.join(self.install_space_abs, package.name) else: raise ValueError('Unkown install space layout: {}'.format(self.devel_layout)) def package_dest_path(self, package): """Get the intermediate destination into which a specific package is built.""" if self.destdir is None: return self.package_final_path(package) else: return os.path.join( self.destdir, self.package_install_space(package).lstrip(os.sep)) def package_final_path(self, package): """Get the final destination into which a specific package is deployed.""" if self.install: return self.package_install_space(package) else: if self.link_devel: return self.devel_space_abs else: return self.package_devel_space(package) def metadata_path(self): """Get the path to the metadata directory for this profile.""" profile_path, _ = metadata.get_paths(self.workspace, self.profile) return profile_path def package_metadata_path(self, package=None): """Get the workspace and profile-specific metadata path for a package""" profile_path, _ = metadata.get_paths(self.workspace, self.profile) if package is None: return os.path.join(profile_path, 'packages') return os.path.join(profile_path, 'packages', package.name)
apache-2.0
Vilsol/NMSWrapper
src/main/java/me/vilsol/nmswrapper/wraps/unparsed/NMSFileIOThread.java
902
package me.vilsol.nmswrapper.wraps.unparsed; import me.vilsol.nmswrapper.*; import me.vilsol.nmswrapper.reflections.*; import me.vilsol.nmswrapper.wraps.*; @ReflectiveClass(name = "FileIOThread") public class NMSFileIOThread extends NMSWrap implements Runnable { public NMSFileIOThread(Object nmsObject){ super(nmsObject); } /** * TODO Find correct name * @see net.minecraft.server.v1_9_R1.FileIOThread#a(net.minecraft.server.v1_9_R1.IAsyncChunkSaver) */ @ReflectiveMethod(name = "a", types = {NMSIAsyncChunkSaver.class}) public void a(NMSIAsyncChunkSaver iAsyncChunkSaver){ NMSWrapper.getInstance().exec(nmsObject, iAsyncChunkSaver); } /** * @see net.minecraft.server.v1_9_R1.FileIOThread#run() */ @ReflectiveMethod(name = "run", types = {}) public void run(){ NMSWrapper.getInstance().exec(nmsObject); } }
apache-2.0
lklong/fuckproject
src/com/zhigu/service/data/impl/CategoryRefServiceImpl.java
1560
/** * @ClassName: CategoryRefServiceImpl.java * @Author: liukailong * @Description: * @Date: 2015年4月14日 * */ package com.zhigu.service.data.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.zhigu.mapper.CategoryRefMapper; import com.zhigu.model.CategoryRef; import com.zhigu.service.data.CategoryRefService; /** * @author Administrator * */ @Service public class CategoryRefServiceImpl implements CategoryRefService { @Autowired private CategoryRefMapper categoryRefMapper; public CategoryRef add(CategoryRef ref) { categoryRefMapper.insertSelective(ref); return ref; } public List<CategoryRef> selectAll() { return categoryRefMapper.selectAll(); } /* * (non-Javadoc) * * @see * com.zhigu.service.datamanager.CategoryRefService#getById(java.lang.Integer * ) */ @Override public CategoryRef getById(Integer id) { return categoryRefMapper.selectByPrimaryKey(id); } /* * (non-Javadoc) * * @see * com.zhigu.service.datamanager.CategoryRefService#deleteByPrimaryKey(java * .lang.Integer) */ @Override public int deleteByPrimaryKey(Integer id) { return categoryRefMapper.deleteByPrimaryKey(id); } /* * (non-Javadoc) * * @see * com.zhigu.service.data.CategoryRefService#selectTBCatByPlat(java.lang * .Integer) */ @Override public CategoryRef selectTBCatByPlat(Integer catId) { CategoryRef catRef = categoryRefMapper.selectTBCatByPlat(catId); return catRef; } }
apache-2.0
castagna/dataset-movies
src/main/java/com/kasabi/data/movies/imdb/IMDBMovieScraper.java
8178
/* * 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.kasabi.data.movies.imdb; import java.io.OutputStream; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import com.hp.hpl.jena.datatypes.BaseDatatype; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.Resource; import com.hp.hpl.jena.rdf.model.ResourceFactory; import com.hp.hpl.jena.sparql.vocabulary.FOAF; import com.hp.hpl.jena.vocabulary.DCTerms; import com.hp.hpl.jena.vocabulary.RDF; import com.kasabi.data.movies.MoviesCommon; import com.kasabi.data.movies.Scraper; import com.kasabi.labs.datasets.Utils; public class IMDBMovieScraper implements Scraper { private String base; private OutputStream out; private final String LINKEDMDB_SCHEMA_NS = MoviesCommon.LINKEDMDB_NS; private final String KASABI_SCHEMA_NS = MoviesCommon.KASABI_MOVIES_SCHEMA; public IMDBMovieScraper ( String base, OutputStream out ) { this.base = base; this.out = out; } @Override public Model scrape(Element element) { Model model = MoviesCommon.createModel(); String href = element.select("td.title a[href^=/title/]").attr("href"); String year = element.select("td.title span.year_type").first().text().replaceAll("\\(", "").replaceAll("\\)", "").substring(0,4); String title = element.select("td.title a[href^=/title/]").first().text(); if ( ( title != null ) && ( title.length() > 0 ) ) { Resource subject = ResourceFactory.createResource(MoviesCommon.KASABI_MOVIES_NS + getMovieSlug(title, year)); model.add ( subject, RDF.type, ResourceFactory.createResource(LINKEDMDB_SCHEMA_NS + "Film") ); model.add ( subject, FOAF.isPrimaryTopicOf, ResourceFactory.createResource(base + href) ); model.add ( subject, DCTerms.title, title ); if ( year != null ) model.add ( subject, ResourceFactory.createProperty(LINKEDMDB_SCHEMA_NS, "initial_release_date"), year, new BaseDatatype("http://www.w3.org/2001/XMLSchema#year") ); Double rating = getRating(element); if ( rating != null ) model.add ( model.createLiteralStatement( subject, ResourceFactory.createProperty(KASABI_SCHEMA_NS, "imdbRatingAvg"), rating ) ); Integer votes = getVotes(element); if ( votes != null ) model.add ( model.createLiteralStatement( subject, ResourceFactory.createProperty(KASABI_SCHEMA_NS, "imdbRatingVotes"), votes ) ); String certificate = getCertificate(element); if ( certificate != null ) model.add ( subject, ResourceFactory.createProperty(KASABI_SCHEMA_NS, "mpaaCertificate"), certificate ); String runtime = getRuntime(element); if ( runtime != null ) model.add ( subject, ResourceFactory.createProperty(LINKEDMDB_SCHEMA_NS, "runtime"), runtime, new BaseDatatype("http://www.w3.org/2001/XMLSchema#duration") ); scrapeDirectors ( element, subject, model ); scrapeActors ( element, subject, model ); scrapeGenres ( element, subject, model ); model.write (System.out, "TURTLE"); model.write ( out, "N-TRIPLES" ); } return model; } private String getMovieSlug(String title, String year) { return Utils.toSlug( title + "-" + year ); } private void scrapeActors ( Element el, Resource subject, Model model ) { Elements elements = el.select("span.credit"); for (Element element : elements) { String str = element.toString(); int indexWith = str.indexOf("With: "); if ( indexWith > 0 ) { Document doc = Jsoup.parse(str.substring(indexWith).replaceAll("</span>", "")); Elements elements2 = doc.select("a"); for (Element element2 : elements2) { String href = element2.attr("href"); String name = element2.text(); Resource actor = ResourceFactory.createResource(MoviesCommon.KASABI_ACTORS_NS + Utils.toSlug(name) ); model.add ( actor, FOAF.isPrimaryTopicOf, ResourceFactory.createResource(base + href) ); model.add ( actor, RDF.type, FOAF.Person ); model.add ( actor, RDF.type, ResourceFactory.createResource(KASABI_SCHEMA_NS + "Actor") ); model.add ( actor, FOAF.name, name ); model.add ( subject, ResourceFactory.createProperty(LINKEDMDB_SCHEMA_NS, "actor"), actor ); model.add ( actor, ResourceFactory.createProperty(KASABI_SCHEMA_NS, "featured_in"), subject ); } } } } private void scrapeDirectors ( Element el, Resource subject, Model model ) { Elements elements = el.select("span.credit"); for (Element element : elements) { String str = element.toString(); int indexDir = str.indexOf("Dir: "); int indexWith = str.indexOf("With: "); if ( ( indexDir > 0 ) && ( indexWith > 0 ) ) { Document doc = Jsoup.parse(str.substring(indexDir + 4, indexWith)); Elements elements2 = doc.select("a"); for (Element element2 : elements2) { String href = element2.attr("href"); String name = element2.text(); Resource director = ResourceFactory.createResource(MoviesCommon.KASABI_ACTORS_NS + Utils.toSlug(name) ); model.add ( director, FOAF.isPrimaryTopicOf, ResourceFactory.createResource(base + href) ); model.add ( director, RDF.type, FOAF.Person ); model.add ( director, RDF.type, ResourceFactory.createResource(KASABI_SCHEMA_NS + "Director") ); model.add ( director, FOAF.name, name ); model.add ( subject, ResourceFactory.createProperty(LINKEDMDB_SCHEMA_NS, "director"), director ); model.add ( director, FOAF.made, subject ); } } } } private void scrapeGenres ( Element el, Resource subject, Model model ) { Elements elements = el.select("span.genre a"); for (Element element : elements) { String href = element.attr("href"); model.add ( subject, ResourceFactory.createProperty(KASABI_SCHEMA_NS, "genre"), ResourceFactory.createResource(KASABI_SCHEMA_NS + href.substring(1).replaceAll("_", "-")) ); } } private Double getRating(Element element) { Double rating = null; Elements elements = element.select("span.rating-rating span.value"); if ( !elements.isEmpty() ) { try { rating = Double.parseDouble( elements.first().text().trim() ); } catch ( NumberFormatException e ) {} } return rating; } private String getRuntime(Element element) { String runtime = null; Elements elements = element.select("span.runtime"); if ( !elements.isEmpty() ) { try { int minutes = Integer.parseInt( elements.first().text().replaceAll(" mins\\.", "").trim() ); runtime = "PT" + ( minutes / 60 ) + "H" + ( minutes % 60 ) + "M"; } catch ( NumberFormatException e ) {} } return runtime; } private Integer getVotes(Element el) { Integer votes = null; Elements elements = el.select("div[class=rating rating-list]"); if ( !elements.isEmpty() ) { String str = elements.first().attr("title").trim(); int indexStart = str.indexOf('('); if ( indexStart > 0 ) { str = str.substring(indexStart + 1); int indexEnd = str.indexOf(" votes)"); if ( indexEnd > 0 ) { str = str.substring(0, indexEnd); str = str.replaceAll(",", ""); try { votes = Integer.parseInt( str.trim() ); } catch ( NumberFormatException e ) {} } } } return votes; } private String getCertificate(Element el) { String certificate = null; Elements elements = el.select("span.certificate img"); if ( !elements.isEmpty() ) { certificate = elements.first().attr("title").trim().replaceAll("_", "-"); } return certificate; } }
apache-2.0
classano/googleads
src/Google/Api/Ads/Dfp/v201311/ContentService.php
78423
<?php /** * Contains all client objects for the ContentService * service. * * PHP version 5 * * Copyright 2014, Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @package GoogleApiAdsDfp * @subpackage v201311 * @category WebServices * @copyright 2014, Google Inc. All Rights Reserved. * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, * Version 2.0 */ require_once "Google/Api/Ads/Dfp/Lib/DfpSoapClient.php"; if (!class_exists("ApiError", false)) { /** * The API error base class that provides details about an error that occurred * while processing a service request. * * <p>The OGNL field path is provided for parsers to identify the request data * element that may have caused the error.</p> * @package GoogleApiAdsDfp * @subpackage v201311 */ class ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201311"; const XSI_TYPE = "ApiError"; /** * @access public * @var string */ public $fieldPath; /** * @access public * @var string */ public $trigger; /** * @access public * @var string */ public $errorString; /** * @access public * @var string */ public $ApiErrorType; private $_parameterMap = array( "ApiError.Type" => "ApiErrorType", ); /** * Provided for setting non-php-standard named variables * @param $var Variable name to set * @param $value Value to set */ public function __set($var, $value) { $this->{$this->_parameterMap[$var]} = $value; } /** * Provided for getting non-php-standard named variables * @param $var Variable name to get * @return mixed Variable value */ public function __get($var) { if (!isset($this->_parameterMap[$var])) { return null; } return $this->{$this->_parameterMap[$var]}; } /** * Provided for getting non-php-standard named variables * @return array parameter map */ protected function getParameterMap() { return $this->_parameterMap; } /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) { $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } } } if (!class_exists("ApiVersionError", false)) { /** * Errors related to the usage of API versions. * @package GoogleApiAdsDfp * @subpackage v201311 */ class ApiVersionError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201311"; const XSI_TYPE = "ApiVersionError"; /** * @access public * @var tnsApiVersionErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } } } if (!class_exists("ApplicationException", false)) { /** * Base class for exceptions. * @package GoogleApiAdsDfp * @subpackage v201311 */ class ApplicationException { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201311"; const XSI_TYPE = "ApplicationException"; /** * @access public * @var string */ public $message; /** * @access public * @var string */ public $ApplicationExceptionType; private $_parameterMap = array( "ApplicationException.Type" => "ApplicationExceptionType", ); /** * Provided for setting non-php-standard named variables * @param $var Variable name to set * @param $value Value to set */ public function __set($var, $value) { $this->{$this->_parameterMap[$var]} = $value; } /** * Provided for getting non-php-standard named variables * @param $var Variable name to get * @return mixed Variable value */ public function __get($var) { if (!isset($this->_parameterMap[$var])) { return null; } return $this->{$this->_parameterMap[$var]}; } /** * Provided for getting non-php-standard named variables * @return array parameter map */ protected function getParameterMap() { return $this->_parameterMap; } /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($message = null, $ApplicationExceptionType = null) { $this->message = $message; $this->ApplicationExceptionType = $ApplicationExceptionType; } } } if (!class_exists("Authentication", false)) { /** * A representation of the authentication protocols that can be used. * @package GoogleApiAdsDfp * @subpackage v201311 */ class Authentication { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201311"; const XSI_TYPE = "Authentication"; /** * @access public * @var string */ public $AuthenticationType; private $_parameterMap = array( "Authentication.Type" => "AuthenticationType", ); /** * Provided for setting non-php-standard named variables * @param $var Variable name to set * @param $value Value to set */ public function __set($var, $value) { $this->{$this->_parameterMap[$var]} = $value; } /** * Provided for getting non-php-standard named variables * @param $var Variable name to get * @return mixed Variable value */ public function __get($var) { if (!isset($this->_parameterMap[$var])) { return null; } return $this->{$this->_parameterMap[$var]}; } /** * Provided for getting non-php-standard named variables * @return array parameter map */ protected function getParameterMap() { return $this->_parameterMap; } /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($AuthenticationType = null) { $this->AuthenticationType = $AuthenticationType; } } } if (!class_exists("AuthenticationError", false)) { /** * An error for an exception that occurred when authenticating. * @package GoogleApiAdsDfp * @subpackage v201311 */ class AuthenticationError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201311"; const XSI_TYPE = "AuthenticationError"; /** * @access public * @var tnsAuthenticationErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } } } if (!class_exists("ClientLogin", false)) { /** * The credentials for the {@code ClientLogin} API authentication protocol. * * See {@link http://code.google.com/apis/accounts/docs/AuthForInstalledApps.html}. * @package GoogleApiAdsDfp * @subpackage v201311 */ class ClientLogin extends Authentication { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201311"; const XSI_TYPE = "ClientLogin"; /** * @access public * @var string */ public $token; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($token = null, $AuthenticationType = null) { parent::__construct(); $this->token = $token; $this->AuthenticationType = $AuthenticationType; } } } if (!class_exists("CmsContent", false)) { /** * Contains information about {@link Content} from the CMS it was ingested from. * @package GoogleApiAdsDfp * @subpackage v201311 */ class CmsContent { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201311"; const XSI_TYPE = "CmsContent"; /** * @access public * @var integer */ public $id; /** * @access public * @var string */ public $displayName; /** * @access public * @var string */ public $cmsContentId; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($id = null, $displayName = null, $cmsContentId = null) { $this->id = $id; $this->displayName = $displayName; $this->cmsContentId = $cmsContentId; } } } if (!class_exists("CommonError", false)) { /** * A place for common errors that can be used across services. * @package GoogleApiAdsDfp * @subpackage v201311 */ class CommonError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201311"; const XSI_TYPE = "CommonError"; /** * @access public * @var tnsCommonErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } } } if (!class_exists("Content", false)) { /** * A {@code Content} represents video metadata from a publisher's * Content Management System (CMS) that has been synced to DFP. * <p> * Video line items can be targeted to {@code Content} * to indicate what ads should match when the {@code Content} is being played. * @package GoogleApiAdsDfp * @subpackage v201311 */ class Content { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201311"; const XSI_TYPE = "Content"; /** * @access public * @var integer */ public $id; /** * @access public * @var string */ public $name; /** * @access public * @var tnsContentStatus */ public $status; /** * @access public * @var tnsContentStatusDefinedBy */ public $statusDefinedBy; /** * @access public * @var DateTime */ public $lastModifiedDateTime; /** * @access public * @var integer[] */ public $userDefinedCustomTargetingValueIds; /** * @access public * @var integer[] */ public $mappingRuleDefinedCustomTargetingValueIds; /** * @access public * @var CmsContent[] */ public $cmsSources; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($id = null, $name = null, $status = null, $statusDefinedBy = null, $lastModifiedDateTime = null, $userDefinedCustomTargetingValueIds = null, $mappingRuleDefinedCustomTargetingValueIds = null, $cmsSources = null) { $this->id = $id; $this->name = $name; $this->status = $status; $this->statusDefinedBy = $statusDefinedBy; $this->lastModifiedDateTime = $lastModifiedDateTime; $this->userDefinedCustomTargetingValueIds = $userDefinedCustomTargetingValueIds; $this->mappingRuleDefinedCustomTargetingValueIds = $mappingRuleDefinedCustomTargetingValueIds; $this->cmsSources = $cmsSources; } } } if (!class_exists("ContentPage", false)) { /** * Captures a page of {@code Content} objects. * @package GoogleApiAdsDfp * @subpackage v201311 */ class ContentPage { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201311"; const XSI_TYPE = "ContentPage"; /** * @access public * @var integer */ public $totalResultSetSize; /** * @access public * @var integer */ public $startIndex; /** * @access public * @var Content[] */ public $results; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($totalResultSetSize = null, $startIndex = null, $results = null) { $this->totalResultSetSize = $totalResultSetSize; $this->startIndex = $startIndex; $this->results = $results; } } } if (!class_exists("ContentPartnerError", false)) { /** * The content partner related validation errors. * @package GoogleApiAdsDfp * @subpackage v201311 */ class ContentPartnerError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201311"; const XSI_TYPE = "ContentPartnerError"; /** * @access public * @var tnsContentPartnerErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } } } if (!class_exists("Date", false)) { /** * Represents a date. * @package GoogleApiAdsDfp * @subpackage v201311 */ class Date { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201311"; const XSI_TYPE = "Date"; /** * @access public * @var integer */ public $year; /** * @access public * @var integer */ public $month; /** * @access public * @var integer */ public $day; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($year = null, $month = null, $day = null) { $this->year = $year; $this->month = $month; $this->day = $day; } } } if (!class_exists("DfpDateTime", false)) { /** * Represents a date combined with the time of day. * @package GoogleApiAdsDfp * @subpackage v201311 */ class DfpDateTime { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201311"; const XSI_TYPE = "DateTime"; /** * @access public * @var Date */ public $date; /** * @access public * @var integer */ public $hour; /** * @access public * @var integer */ public $minute; /** * @access public * @var integer */ public $second; /** * @access public * @var string */ public $timeZoneID; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($date = null, $hour = null, $minute = null, $second = null, $timeZoneID = null) { $this->date = $date; $this->hour = $hour; $this->minute = $minute; $this->second = $second; $this->timeZoneID = $timeZoneID; } } } if (!class_exists("FeatureError", false)) { /** * Errors related to feature management. If you attempt using a feature that is not available to * the current network you'll receive a FeatureError with the missing feature as the trigger. * @package GoogleApiAdsDfp * @subpackage v201311 */ class FeatureError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201311"; const XSI_TYPE = "FeatureError"; /** * @access public * @var tnsFeatureErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } } } if (!class_exists("InternalApiError", false)) { /** * Indicates that a server-side error has occured. {@code InternalApiError}s * are generally not the result of an invalid request or message sent by the * client. * @package GoogleApiAdsDfp * @subpackage v201311 */ class InternalApiError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201311"; const XSI_TYPE = "InternalApiError"; /** * @access public * @var tnsInternalApiErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } } } if (!class_exists("InvalidUrlError", false)) { /** * Lists all errors associated with URLs. * @package GoogleApiAdsDfp * @subpackage v201311 */ class InvalidUrlError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201311"; const XSI_TYPE = "InvalidUrlError"; /** * @access public * @var tnsInvalidUrlErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } } } if (!class_exists("NotNullError", false)) { /** * Caused by supplying a null value for an attribute that cannot be null. * @package GoogleApiAdsDfp * @subpackage v201311 */ class NotNullError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201311"; const XSI_TYPE = "NotNullError"; /** * @access public * @var tnsNotNullErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } } } if (!class_exists("DfpOAuth", false)) { /** * The credentials for the {@code OAuth} authentication protocol. * * See {@link http://oauth.net/}. * @package GoogleApiAdsDfp * @subpackage v201311 */ class DfpOAuth extends Authentication { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201311"; const XSI_TYPE = "OAuth"; /** * @access public * @var string */ public $parameters; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($parameters = null, $AuthenticationType = null) { parent::__construct(); $this->parameters = $parameters; $this->AuthenticationType = $AuthenticationType; } } } if (!class_exists("PermissionError", false)) { /** * Errors related to incorrect permission. * @package GoogleApiAdsDfp * @subpackage v201311 */ class PermissionError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201311"; const XSI_TYPE = "PermissionError"; /** * @access public * @var tnsPermissionErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } } } if (!class_exists("PublisherQueryLanguageContextError", false)) { /** * An error that occurs while executing a PQL query contained in * a {@link Statement} object. * @package GoogleApiAdsDfp * @subpackage v201311 */ class PublisherQueryLanguageContextError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201311"; const XSI_TYPE = "PublisherQueryLanguageContextError"; /** * @access public * @var tnsPublisherQueryLanguageContextErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } } } if (!class_exists("PublisherQueryLanguageSyntaxError", false)) { /** * An error that occurs while parsing a PQL query contained in a * {@link Statement} object. * @package GoogleApiAdsDfp * @subpackage v201311 */ class PublisherQueryLanguageSyntaxError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201311"; const XSI_TYPE = "PublisherQueryLanguageSyntaxError"; /** * @access public * @var tnsPublisherQueryLanguageSyntaxErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } } } if (!class_exists("QuotaError", false)) { /** * Describes a client-side error on which a user is attempting * to perform an action to which they have no quota remaining. * @package GoogleApiAdsDfp * @subpackage v201311 */ class QuotaError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201311"; const XSI_TYPE = "QuotaError"; /** * @access public * @var tnsQuotaErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } } } if (!class_exists("RequiredCollectionError", false)) { /** * A list of all errors to be used for validating sizes of collections. * @package GoogleApiAdsDfp * @subpackage v201311 */ class RequiredCollectionError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201311"; const XSI_TYPE = "RequiredCollectionError"; /** * @access public * @var tnsRequiredCollectionErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } } } if (!class_exists("RequiredNumberError", false)) { /** * A list of all errors to be used in conjunction with required number * validators. * @package GoogleApiAdsDfp * @subpackage v201311 */ class RequiredNumberError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201311"; const XSI_TYPE = "RequiredNumberError"; /** * @access public * @var tnsRequiredNumberErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } } } if (!class_exists("ServerError", false)) { /** * Errors related to the server. * @package GoogleApiAdsDfp * @subpackage v201311 */ class ServerError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201311"; const XSI_TYPE = "ServerError"; /** * @access public * @var tnsServerErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } } } if (!class_exists("SoapRequestHeader", false)) { /** * Represents the SOAP request header used by API requests. * @package GoogleApiAdsDfp * @subpackage v201311 */ class SoapRequestHeader { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201311"; const XSI_TYPE = "SoapRequestHeader"; /** * @access public * @var string */ public $networkCode; /** * @access public * @var string */ public $applicationName; /** * @access public * @var Authentication */ public $authentication; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($networkCode = null, $applicationName = null, $authentication = null) { $this->networkCode = $networkCode; $this->applicationName = $applicationName; $this->authentication = $authentication; } } } if (!class_exists("SoapResponseHeader", false)) { /** * Represents the SOAP request header used by API responses. * @package GoogleApiAdsDfp * @subpackage v201311 */ class SoapResponseHeader { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201311"; const XSI_TYPE = "SoapResponseHeader"; /** * @access public * @var string */ public $requestId; /** * @access public * @var integer */ public $responseTime; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($requestId = null, $responseTime = null) { $this->requestId = $requestId; $this->responseTime = $responseTime; } } } if (!class_exists("Statement", false)) { /** * Captures the {@code WHERE}, {@code ORDER BY} and {@code LIMIT} clauses of a * PQL query. Statements are typically used to retrieve objects of a predefined * domain type, which makes SELECT clause unnecessary. * <p> * An example query text might be {@code "WHERE status = 'ACTIVE' ORDER BY id * LIMIT 30"}. * </p> * <p> * Statements support bind variables. These are substitutes for literals * and can be thought of as input parameters to a PQL query. * </p> * <p> * An example of such a query might be {@code "WHERE id = :idValue"}. * </p> * <p> * Statements also support use of the LIKE keyword. This provides partial and * wildcard string matching. * </p> * <p> * An example of such a query might be {@code "WHERE name LIKE 'startswith%'"}. * </p> * If using an API version newer than V201010, the value for the variable * idValue must then be set with an object of type {@link Value} and is one of * {@link NumberValue}, {@link TextValue} or {@link BooleanValue}. * <p> * If using an API version older than or equal to V201010, the value for the * variable idValue must then be set with an object of type {@link Param} and is * one of {@link DoubleParam}, {@link LongParam} or {@link StringParam}. * </p> * @package GoogleApiAdsDfp * @subpackage v201311 */ class Statement { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201311"; const XSI_TYPE = "Statement"; /** * @access public * @var string */ public $query; /** * @access public * @var String_ValueMapEntry[] */ public $values; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($query = null, $values = null) { $this->query = $query; $this->values = $values; } } } if (!class_exists("StatementError", false)) { /** * An error that occurs while parsing {@link Statement} objects. * @package GoogleApiAdsDfp * @subpackage v201311 */ class StatementError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201311"; const XSI_TYPE = "StatementError"; /** * @access public * @var tnsStatementErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } } } if (!class_exists("StringLengthError", false)) { /** * Errors for Strings which do not meet given length constraints. * @package GoogleApiAdsDfp * @subpackage v201311 */ class StringLengthError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201311"; const XSI_TYPE = "StringLengthError"; /** * @access public * @var tnsStringLengthErrorReason */ public $reason; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($reason = null, $fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) { parent::__construct(); $this->reason = $reason; $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } } } if (!class_exists("String_ValueMapEntry", false)) { /** * This represents an entry in a map with a key of type String * and value of type Value. * @package GoogleApiAdsDfp * @subpackage v201311 */ class String_ValueMapEntry { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201311"; const XSI_TYPE = "String_ValueMapEntry"; /** * @access public * @var string */ public $key; /** * @access public * @var Value */ public $value; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($key = null, $value = null) { $this->key = $key; $this->value = $value; } } } if (!class_exists("TypeError", false)) { /** * An error for a field which is an invalid type. * @package GoogleApiAdsDfp * @subpackage v201311 */ class TypeError extends ApiError { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201311"; const XSI_TYPE = "TypeError"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($fieldPath = null, $trigger = null, $errorString = null, $ApiErrorType = null) { parent::__construct(); $this->fieldPath = $fieldPath; $this->trigger = $trigger; $this->errorString = $errorString; $this->ApiErrorType = $ApiErrorType; } } } if (!class_exists("Value", false)) { /** * {@code Value} represents a value. * @package GoogleApiAdsDfp * @subpackage v201311 */ class Value { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201311"; const XSI_TYPE = "Value"; /** * @access public * @var string */ public $ValueType; private $_parameterMap = array( "Value.Type" => "ValueType", ); /** * Provided for setting non-php-standard named variables * @param $var Variable name to set * @param $value Value to set */ public function __set($var, $value) { $this->{$this->_parameterMap[$var]} = $value; } /** * Provided for getting non-php-standard named variables * @param $var Variable name to get * @return mixed Variable value */ public function __get($var) { if (!isset($this->_parameterMap[$var])) { return null; } return $this->{$this->_parameterMap[$var]}; } /** * Provided for getting non-php-standard named variables * @return array parameter map */ protected function getParameterMap() { return $this->_parameterMap; } /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($ValueType = null) { $this->ValueType = $ValueType; } } } if (!class_exists("ApiVersionErrorReason", false)) { /** * Indicates that the operation is not allowed in the version the request * was made in. * @package GoogleApiAdsDfp * @subpackage v201311 */ class ApiVersionErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201311"; const XSI_TYPE = "ApiVersionError.Reason"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("AuthenticationErrorReason", false)) { /** * The SOAP message contains a request header with an ambiguous definition * of the authentication header fields. This means either the {@code * authToken} and {@code oAuthToken} fields were both null or both were * specified. Exactly one value should be specified with each request. * @package GoogleApiAdsDfp * @subpackage v201311 */ class AuthenticationErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201311"; const XSI_TYPE = "AuthenticationError.Reason"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("CommonErrorReason", false)) { /** * Describes reasons for common errors * @package GoogleApiAdsDfp * @subpackage v201311 */ class CommonErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201311"; const XSI_TYPE = "CommonError.Reason"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("ContentPartnerErrorReason", false)) { /** * Describes reason for {@code ContentPartnerError}s. * @package GoogleApiAdsDfp * @subpackage v201311 */ class ContentPartnerErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201311"; const XSI_TYPE = "ContentPartnerError.Reason"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("ContentStatus", false)) { /** * Describes the status of a {@link Content} object. * @package GoogleApiAdsDfp * @subpackage v201311 */ class ContentStatus { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201311"; const XSI_TYPE = "ContentStatus"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("FeatureErrorReason", false)) { /** * A feature is being used that is not enabled on the current network. * @package GoogleApiAdsDfp * @subpackage v201311 */ class FeatureErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201311"; const XSI_TYPE = "FeatureError.Reason"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("InternalApiErrorReason", false)) { /** * The single reason for the internal API error. * @package GoogleApiAdsDfp * @subpackage v201311 */ class InternalApiErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201311"; const XSI_TYPE = "InternalApiError.Reason"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("InvalidUrlErrorReason", false)) { /** * The URL contains invalid characters. * @package GoogleApiAdsDfp * @subpackage v201311 */ class InvalidUrlErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201311"; const XSI_TYPE = "InvalidUrlError.Reason"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("NotNullErrorReason", false)) { /** * The reasons for the target error. * @package GoogleApiAdsDfp * @subpackage v201311 */ class NotNullErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201311"; const XSI_TYPE = "NotNullError.Reason"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("PermissionErrorReason", false)) { /** * Describes reasons for permission errors. * @package GoogleApiAdsDfp * @subpackage v201311 */ class PermissionErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201311"; const XSI_TYPE = "PermissionError.Reason"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("PublisherQueryLanguageContextErrorReason", false)) { /** * The reasons for the target error. * @package GoogleApiAdsDfp * @subpackage v201311 */ class PublisherQueryLanguageContextErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201311"; const XSI_TYPE = "PublisherQueryLanguageContextError.Reason"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("PublisherQueryLanguageSyntaxErrorReason", false)) { /** * The reasons for the target error. * @package GoogleApiAdsDfp * @subpackage v201311 */ class PublisherQueryLanguageSyntaxErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201311"; const XSI_TYPE = "PublisherQueryLanguageSyntaxError.Reason"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("QuotaErrorReason", false)) { /** * The number of requests made per second is too high and has exceeded the * allowable limit. The recommended approach to handle this error is to wait * about 5 seconds and then retry the request. Note that this does not * guarantee the request will succeed. If it fails again, try increasing the * wait time. * <p> * Another way to mitigate this error is to limit requests to 2 per second for * Small Business networks, or 8 per second for Premium networks. Once again * this does not guarantee that every request will succeed, but may help * reduce the number of times you receive this error. * </p> * @package GoogleApiAdsDfp * @subpackage v201311 */ class QuotaErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201311"; const XSI_TYPE = "QuotaError.Reason"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("RequiredCollectionErrorReason", false)) { /** * A required collection is missing. * @package GoogleApiAdsDfp * @subpackage v201311 */ class RequiredCollectionErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201311"; const XSI_TYPE = "RequiredCollectionError.Reason"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("RequiredNumberErrorReason", false)) { /** * Describes reasons for a number to be invalid. * @package GoogleApiAdsDfp * @subpackage v201311 */ class RequiredNumberErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201311"; const XSI_TYPE = "RequiredNumberError.Reason"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("ServerErrorReason", false)) { /** * Describes reasons for server errors * @package GoogleApiAdsDfp * @subpackage v201311 */ class ServerErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201311"; const XSI_TYPE = "ServerError.Reason"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("StatementErrorReason", false)) { /** * A bind variable has not been bound to a value. * @package GoogleApiAdsDfp * @subpackage v201311 */ class StatementErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201311"; const XSI_TYPE = "StatementError.Reason"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("ContentStatusDefinedBy", false)) { /** * Describes who defined the effective status of the {@code Content}. * @package GoogleApiAdsDfp * @subpackage v201311 */ class ContentStatusDefinedBy { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201311"; const XSI_TYPE = "ContentStatusDefinedBy"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("StringLengthErrorReason", false)) { /** * The value returned if the actual value is not exposed by the requested API version. * @package GoogleApiAdsDfp * @subpackage v201311 */ class StringLengthErrorReason { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201311"; const XSI_TYPE = "StringLengthError.Reason"; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct() { } } } if (!class_exists("GetContentByStatement", false)) { /** * Gets a {@link ContentPage} of {@link Content} objects that satisfy the * given {@link Statement#query}. The following fields are supported for * filtering: * * <table> * <tr> * <th scope="col">PQL Property</th> <th scope="col">Object Property</th> * </tr> * <tr> * <td>{@code id}</td> * <td>{@link Content#id}</td> * </tr> * <tr> * <td>{@code status}</td> * <td>{@link Content#status}</td> * </tr> * <tr> * <td>{@code name}</td> * <td>{@link Content#name}</td> * </tr> * <tr> * <td>{@code lastModifiedDateTime}</td> * <td>{@link Content#lastModifiedDateTime}: Requires indexed content search to be enabled.</td> * </tr> * </table> * * @params filterStatement a Publisher Query Language statement used to * filter a set of content * @return the content that matches the given filter * @package GoogleApiAdsDfp * @subpackage v201311 */ class GetContentByStatement { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201311"; const XSI_TYPE = ""; /** * @access public * @var Statement */ public $statement; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($statement = null) { $this->statement = $statement; } } } if (!class_exists("GetContentByStatementResponse", false)) { /** * * @package GoogleApiAdsDfp * @subpackage v201311 */ class GetContentByStatementResponse { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201311"; const XSI_TYPE = ""; /** * @access public * @var ContentPage */ public $rval; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($rval = null) { $this->rval = $rval; } } } if (!class_exists("GetContentByStatementAndCustomTargetingValue", false)) { /** * Gets a {@link ContentPage} of {@link Content} objects that satisfy the * given {@link Statement#query}. Additionally, filters on the given value ID * and key ID that the value belongs to. * * The following fields are supported for filtering: * <table> * <tr> * <th scope="col">PQL Property</th> <th scope="col">Object Property</th> * </tr> * <tr> * <td>{@code id}</td> * <td>{@link Content#id}</td> * </tr> * <tr> * <td>{@code status}</td> * <td>{@link Content#status}</td> * </tr> * <tr> * <td>{@code name}</td> * <td>{@link Content#name}</td> * </tr> * <tr> * <td>{@code lastModifiedDateTime}</td> * <td>{@link Content#lastModifiedDateTime>}: Requires indexed content search to be enabled.</td> * </tr> * </table> * * @params filterStatement a Publisher Query Language statement used to * filter a set of content * @param customTargetingValueId the id of the value to match * @return the content that matches the given filter * @package GoogleApiAdsDfp * @subpackage v201311 */ class GetContentByStatementAndCustomTargetingValue { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201311"; const XSI_TYPE = ""; /** * @access public * @var Statement */ public $filterStatement; /** * @access public * @var integer */ public $customTargetingValueId; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($filterStatement = null, $customTargetingValueId = null) { $this->filterStatement = $filterStatement; $this->customTargetingValueId = $customTargetingValueId; } } } if (!class_exists("GetContentByStatementAndCustomTargetingValueResponse", false)) { /** * * @package GoogleApiAdsDfp * @subpackage v201311 */ class GetContentByStatementAndCustomTargetingValueResponse { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201311"; const XSI_TYPE = ""; /** * @access public * @var ContentPage */ public $rval; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($rval = null) { $this->rval = $rval; } } } if (!class_exists("ApiException", false)) { /** * Exception class for holding a list of service errors. * @package GoogleApiAdsDfp * @subpackage v201311 */ class ApiException extends ApplicationException { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201311"; const XSI_TYPE = "ApiException"; /** * @access public * @var ApiError[] */ public $errors; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($errors = null, $message = null, $ApplicationExceptionType = null) { parent::__construct(); $this->errors = $errors; $this->message = $message; $this->ApplicationExceptionType = $ApplicationExceptionType; } } } if (!class_exists("BooleanValue", false)) { /** * Contains a boolean value. * @package GoogleApiAdsDfp * @subpackage v201311 */ class BooleanValue extends Value { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201311"; const XSI_TYPE = "BooleanValue"; /** * @access public * @var boolean */ public $value; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($value = null, $ValueType = null) { parent::__construct(); $this->value = $value; $this->ValueType = $ValueType; } } } if (!class_exists("DateTimeValue", false)) { /** * Contains a date-time value. * @package GoogleApiAdsDfp * @subpackage v201311 */ class DateTimeValue extends Value { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201311"; const XSI_TYPE = "DateTimeValue"; /** * @access public * @var DateTime */ public $value; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($value = null, $ValueType = null) { parent::__construct(); $this->value = $value; $this->ValueType = $ValueType; } } } if (!class_exists("DateValue", false)) { /** * Contains a date value. * @package GoogleApiAdsDfp * @subpackage v201311 */ class DateValue extends Value { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201311"; const XSI_TYPE = "DateValue"; /** * @access public * @var Date */ public $value; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($value = null, $ValueType = null) { parent::__construct(); $this->value = $value; $this->ValueType = $ValueType; } } } if (!class_exists("NumberValue", false)) { /** * Contains a numeric value. * @package GoogleApiAdsDfp * @subpackage v201311 */ class NumberValue extends Value { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201311"; const XSI_TYPE = "NumberValue"; /** * @access public * @var string */ public $value; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($value = null, $ValueType = null) { parent::__construct(); $this->value = $value; $this->ValueType = $ValueType; } } } if (!class_exists("SetValue", false)) { /** * Contains a set of {@link Value Values}. May not contain duplicates. * @package GoogleApiAdsDfp * @subpackage v201311 */ class SetValue extends Value { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201311"; const XSI_TYPE = "SetValue"; /** * @access public * @var Value[] */ public $values; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($values = null, $ValueType = null) { parent::__construct(); $this->values = $values; $this->ValueType = $ValueType; } } } if (!class_exists("TextValue", false)) { /** * Contains a string value. * @package GoogleApiAdsDfp * @subpackage v201311 */ class TextValue extends Value { const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201311"; const XSI_TYPE = "TextValue"; /** * @access public * @var string */ public $value; /** * Gets the namesapce of this class * @return the namespace of this class */ public function getNamespace() { return self::WSDL_NAMESPACE; } /** * Gets the xsi:type name of this class * @return the xsi:type name of this class */ public function getXsiTypeName() { return self::XSI_TYPE; } public function __construct($value = null, $ValueType = null) { parent::__construct(); $this->value = $value; $this->ValueType = $ValueType; } } } if (!class_exists("ContentService", false)) { /** * ContentService * @package GoogleApiAdsDfp * @subpackage v201311 */ class ContentService extends DfpSoapClient { const SERVICE_NAME = "ContentService"; const WSDL_NAMESPACE = "https://www.google.com/apis/ads/publisher/v201311"; const ENDPOINT = "https://ads.google.com/apis/ads/publisher/v201311/ContentService"; /** * The endpoint of the service * @var string */ public static $endpoint = "https://ads.google.com/apis/ads/publisher/v201311/ContentService"; /** * Default class map for wsdl=>php * @access private * @var array */ public static $classmap = array( "ApiError" => "ApiError", "ApiException" => "ApiException", "ApiVersionError" => "ApiVersionError", "ApplicationException" => "ApplicationException", "Authentication" => "Authentication", "AuthenticationError" => "AuthenticationError", "BooleanValue" => "BooleanValue", "ClientLogin" => "ClientLogin", "CmsContent" => "CmsContent", "CommonError" => "CommonError", "Content" => "Content", "ContentPage" => "ContentPage", "ContentPartnerError" => "ContentPartnerError", "Date" => "Date", "DateTime" => "DfpDateTime", "DateTimeValue" => "DateTimeValue", "DateValue" => "DateValue", "FeatureError" => "FeatureError", "InternalApiError" => "InternalApiError", "InvalidUrlError" => "InvalidUrlError", "NotNullError" => "NotNullError", "NumberValue" => "NumberValue", "OAuth" => "DfpOAuth", "PermissionError" => "PermissionError", "PublisherQueryLanguageContextError" => "PublisherQueryLanguageContextError", "PublisherQueryLanguageSyntaxError" => "PublisherQueryLanguageSyntaxError", "QuotaError" => "QuotaError", "RequiredCollectionError" => "RequiredCollectionError", "RequiredNumberError" => "RequiredNumberError", "ServerError" => "ServerError", "SetValue" => "SetValue", "SoapRequestHeader" => "SoapRequestHeader", "SoapResponseHeader" => "SoapResponseHeader", "Statement" => "Statement", "StatementError" => "StatementError", "StringLengthError" => "StringLengthError", "String_ValueMapEntry" => "String_ValueMapEntry", "TextValue" => "TextValue", "TypeError" => "TypeError", "Value" => "Value", "ApiVersionError.Reason" => "ApiVersionErrorReason", "AuthenticationError.Reason" => "AuthenticationErrorReason", "CommonError.Reason" => "CommonErrorReason", "ContentPartnerError.Reason" => "ContentPartnerErrorReason", "ContentStatus" => "ContentStatus", "FeatureError.Reason" => "FeatureErrorReason", "InternalApiError.Reason" => "InternalApiErrorReason", "InvalidUrlError.Reason" => "InvalidUrlErrorReason", "NotNullError.Reason" => "NotNullErrorReason", "PermissionError.Reason" => "PermissionErrorReason", "PublisherQueryLanguageContextError.Reason" => "PublisherQueryLanguageContextErrorReason", "PublisherQueryLanguageSyntaxError.Reason" => "PublisherQueryLanguageSyntaxErrorReason", "QuotaError.Reason" => "QuotaErrorReason", "RequiredCollectionError.Reason" => "RequiredCollectionErrorReason", "RequiredNumberError.Reason" => "RequiredNumberErrorReason", "ServerError.Reason" => "ServerErrorReason", "StatementError.Reason" => "StatementErrorReason", "ContentStatusDefinedBy" => "ContentStatusDefinedBy", "StringLengthError.Reason" => "StringLengthErrorReason", "getContentByStatement" => "GetContentByStatement", "getContentByStatementResponse" => "GetContentByStatementResponse", "getContentByStatementAndCustomTargetingValue" => "GetContentByStatementAndCustomTargetingValue", "getContentByStatementAndCustomTargetingValueResponse" => "GetContentByStatementAndCustomTargetingValueResponse", ); /** * Constructor using wsdl location and options array * @param string $wsdl WSDL location for this service * @param array $options Options for the SoapClient */ public function __construct($wsdl, $options, $user) { $options["classmap"] = self::$classmap; parent::__construct($wsdl, $options, $user, self::SERVICE_NAME, self::WSDL_NAMESPACE); } /** * Gets a {@link ContentPage} of {@link Content} objects that satisfy the * given {@link Statement#query}. The following fields are supported for * filtering: * * <table> * <tr> * <th scope="col">PQL Property</th> <th scope="col">Object Property</th> * </tr> * <tr> * <td>{@code id}</td> * <td>{@link Content#id}</td> * </tr> * <tr> * <td>{@code status}</td> * <td>{@link Content#status}</td> * </tr> * <tr> * <td>{@code name}</td> * <td>{@link Content#name}</td> * </tr> * <tr> * <td>{@code lastModifiedDateTime}</td> * <td>{@link Content#lastModifiedDateTime}: Requires indexed content search to be enabled.</td> * </tr> * </table> * * @params filterStatement a Publisher Query Language statement used to * filter a set of content * @return the content that matches the given filter */ public function getContentByStatement($statement) { $args = new GetContentByStatement($statement); $result = $this->__soapCall("getContentByStatement", array($args)); return $result->rval; } /** * Gets a {@link ContentPage} of {@link Content} objects that satisfy the * given {@link Statement#query}. Additionally, filters on the given value ID * and key ID that the value belongs to. * * The following fields are supported for filtering: * <table> * <tr> * <th scope="col">PQL Property</th> <th scope="col">Object Property</th> * </tr> * <tr> * <td>{@code id}</td> * <td>{@link Content#id}</td> * </tr> * <tr> * <td>{@code status}</td> * <td>{@link Content#status}</td> * </tr> * <tr> * <td>{@code name}</td> * <td>{@link Content#name}</td> * </tr> * <tr> * <td>{@code lastModifiedDateTime}</td> * <td>{@link Content#lastModifiedDateTime>}: Requires indexed content search to be enabled.</td> * </tr> * </table> * * @params filterStatement a Publisher Query Language statement used to * filter a set of content * @param customTargetingValueId the id of the value to match * @return the content that matches the given filter */ public function getContentByStatementAndCustomTargetingValue($filterStatement, $customTargetingValueId) { $args = new GetContentByStatementAndCustomTargetingValue($filterStatement, $customTargetingValueId); $result = $this->__soapCall("getContentByStatementAndCustomTargetingValue", array($args)); return $result->rval; } } }
apache-2.0
LADOSSIFPB/nutrif
nutrif-web/lib/angular/i18n/angular-locale_en-sh.js
2595
'use strict'; angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; function getDecimals(n) { n = n + ''; var i = n.indexOf('.'); return (i == -1) ? 0 : n.length - i - 1; } function getVF(n, opt_precision) { var v = opt_precision; if (undefined === v) { v = Math.min(getDecimals(n), 3); } var base = Math.pow(10, v); var f = ((n * base) | 0) % base; return {v: v, f: f}; } $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "AM", "PM" ], "DAY": [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ], "ERANAMES": [ "Before Christ", "Anno Domini" ], "ERAS": [ "BC", "AD" ], "FIRSTDAYOFWEEK": 0, "MONTH": [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ], "SHORTDAY": [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ], "SHORTMONTH": [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ], "WEEKENDRANGE": [ 5, 6 ], "fullDate": "EEEE, d MMMM y", "longDate": "d MMMM y", "medium": "d MMM y h:mm:ss a", "mediumDate": "d MMM y", "mediumTime": "h:mm:ss a", "short": "dd/MM/y h:mm a", "shortDate": "dd/MM/y", "shortTime": "h:mm a" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "\u00a3", "DECIMAL_SEP": ".", "GROUP_SEP": ",", "PATTERNS": [ { "gSize": 3, "lgSize": 3, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, { "gSize": 3, "lgSize": 3, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "-\u00a4", "negSuf": "", "posPre": "\u00a4", "posSuf": "" } ] }, "id": "en-sh", "pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;} }); }]);
apache-2.0
jmccrae/lemon.patterns
src/main/java/net/lemonmodel/patterns/parser/Absyn/EThirdPerson.java
534
package net.lemonmodel.patterns.parser.Absyn; // Java Package generated by the BNF Converter. public class EThirdPerson extends Category { public EThirdPerson() { } public <R,A> R accept(net.lemonmodel.patterns.parser.Absyn.Category.Visitor<R,A> v, A arg) { return v.visit(this, arg); } public boolean equals(Object o) { if (this == o) return true; if (o instanceof net.lemonmodel.patterns.parser.Absyn.EThirdPerson) { return true; } return false; } public int hashCode() { return 37; } }
apache-2.0
JamesEarle/PersonalWebsite
js/hideme.js
642
$(document).ready(function() { /* Every time the window is scrolled ... */ $(window).scroll( function(){ /* Check the location of each desired element */ $('.hideme').each( function(i){ var bottom_of_object = $(this).position().top + $(this).outerHeight(); var bottom_of_window = $(window).scrollTop() + $(window).height(); /* If the object is completely visible in the window, fade it it */ if( bottom_of_window > bottom_of_object ){ $(this).animate({'opacity':'1'},500); } }); }); });
apache-2.0
digitick/Collection
Test/Digitick/Tests/Foundation/Collection/BaseScalarSetTest.php
3080
<?php namespace Digitick\Tests\Foundation\Collection; use Digitick\Foundation\Collection\BaseScalarSet; /* * */ class BaseScalarSetTest extends \PHPUnit_Framework_TestCase { /** @var BaseScalarSet */ protected $emptySet; /** @var BaseScalarSet */ protected $set; const SET_SIZE = 5; public function testListMustNotBeEmptyAfterAdd() { $this->emptySet->add(10); $this->assertFalse($this->emptySet->isEmpty()); } public function testAddAll() { $this->emptySet->addAll($this->set); $this->assertTrue($this->emptySet->containsAll($this->set)); $this->set->add(6); $this->assertFalse($this->emptySet->containsAll($this->set)); } public function testEmpty() { $this->assertTrue($this->emptySet->isEmpty()); $this->assertFalse($this->set->isEmpty()); } public function testContains() { $this->assertFalse($this->set->contains(0)); $this->assertTrue($this->set->contains(2)); $this->assertFalse($this->set->contains(6)); $this->assertFalse($this->set->contains("text")); $this->assertFalse($this->set->contains((boolean)true)); $this->assertFalse($this->set->contains(-1)); } public function testContainsAll() { } public function testListMustBeEmptyAfterClear() { $this->assertFalse($this->set->isEmpty()); $this->set->clear(); $this->assertTrue($this->set->isEmpty()); $this->assertEquals(0, $this->set->count()); } public function testSize() { $this->assertEquals(self::SET_SIZE, $this->set->count()); } public function testRemove () { $this->emptySet->add ("tonton"); $this->assertTrue($this->emptySet->contains("tonton")); $this->assertTrue($this->emptySet->remove("tonton")); $this->assertFalse($this->emptySet->contains("tonton")); } public function testRemoveNonExists() { $this->assertFalse($this->emptySet->remove("tonton")); } public function testToArray () { $array = $this->set->toArray(); foreach ($array as $item) { $this->assertTrue($this->set->contains($item)); } } /** * @expectedException \Digitick\Foundation\Collection\Exception\UnexpectedTypeException */ public function testAddNonScalar () { $this->emptySet->add(new BaseScalarSet()); } public function testAddNonExists () { $this->assertTrue($this->emptySet->add("tonton")); } public function testAddExists () { $this->emptySet->add("tonton"); $this->assertFalse($this->emptySet->add("tonton")); } protected function setUp() { $this->set = $this->generateList(self::SET_SIZE); $this->emptySet = new BaseScalarSet(self::SET_SIZE); } protected function generateList($size) { $list = new BaseScalarSet($size); for ($i = 0; $i < $size; $i++) { $list->add($i + 1); } return $list; } }
apache-2.0
Simbacode/csrosa
csrosa/core/src/org/javarosa/xform/util/XFormAnswerDataParser.cs
6436
/* * Copyright (C) 2009 JavaRosa ,Copyright (C) 2014 Simbacode * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ using org.javarosa.core.model; using org.javarosa.core.model.data; using org.javarosa.core.model.data.helper; using org.javarosa.core.model.utils; using System; using System.Collections; using System.Collections.Generic; namespace org.javarosa.xform.util { /** * The XFormAnswerDataParser is responsible for taking XForms elements and * parsing them into a specific type of IAnswerData. * * @author Acellam Guy , Clayton Sims * */ /* int text float datetime date time choice choice list */ public class XFormAnswerDataParser { //FIXME: the QuestionDef parameter is a hack until we find a better way to represent AnswerDatas for select questions public static IAnswerData getAnswerData(String text, int dataType) { return getAnswerData(text, dataType, null); } public static IAnswerData getAnswerData(String text, int dataType, QuestionDef q) { String trimmedText = text.Trim(); if (trimmedText.Length == 0) trimmedText = null; switch (dataType) { case Constants.DATATYPE_NULL: case Constants.DATATYPE_UNSUPPORTED: case Constants.DATATYPE_TEXT: case Constants.DATATYPE_BARCODE: case Constants.DATATYPE_BINARY: return new StringData(text); case Constants.DATATYPE_INTEGER: try { return (trimmedText == null ? null : new IntegerData(int.Parse(trimmedText))); } catch (FormatException nfe) { return null; } case Constants.DATATYPE_LONG: try { return (trimmedText == null ? null : new LongData(long.Parse(trimmedText))); } catch (FormatException nfe) { return null; } case Constants.DATATYPE_DECIMAL: try { return (trimmedText == null ? null : new DecimalData(Double.Parse(trimmedText))); } catch (FormatException nfe) { return null; } case Constants.DATATYPE_CHOICE: ArrayList selections = getSelections(text, q); return (selections.Count == 0 ? null : new SelectOneData((Selection)selections[0])); case Constants.DATATYPE_CHOICE_LIST: return new SelectMultiData(getSelections(text, q)); case Constants.DATATYPE_DATE_TIME: DateTime dt = (trimmedText == null ? DateTime.Now : DateUtils.parseDateTime(trimmedText)); return (dt == null ? null : new DateTimeData(ref dt)); case Constants.DATATYPE_DATE: DateTime d = (trimmedText == null ? DateTime.Now : DateUtils.parseDate(trimmedText)); return (d == null ? null : new DateData(ref d)); case Constants.DATATYPE_TIME: DateTime t = (trimmedText == null ? DateTime.Now : DateUtils.parseTime(trimmedText)); return (t == null ? null : new TimeData(ref t)); case Constants.DATATYPE_BOOLEAN: if (trimmedText == null) { return null; } else { if (trimmedText.Equals("1")) { return new BooleanData(true); } if (trimmedText.Equals("0")) { return new BooleanData(false); } return trimmedText.Equals("t") ? new BooleanData(true) : new BooleanData(false); } case Constants.DATATYPE_GEOPOINT: try { List<String> gpv = (trimmedText == null ? null : DateUtils.split(trimmedText, " ", false)); int len = gpv.Count; double[] gp = new double[len]; for (int i = 0; i < len; i++) { gp[i] = Double.Parse(((String)gpv[i])); } return new GeoPointData(gp); } catch (FormatException nfe) { return null; } default: return new UncastData(trimmedText); } } private static ArrayList getSelections(String text, QuestionDef q) { ArrayList v = new ArrayList(); List<String> choices = DateUtils.split(text, XFormAnswerDataSerializer.DELIMITER, true); for (int i = 0; i < choices.Count; i++) { Selection s = getSelection((String)choices[i], q); if (s != null) v.Add(s); } return v; } private static Selection getSelection(String choiceValue, QuestionDef q) { Selection s; if (q == null || q.getDynamicChoices() != null) { s = new Selection(choiceValue); } else { SelectChoice choice = q.getChoiceForValue(choiceValue); s = (choice != null ? choice.selection() : null); } return s; } } }
apache-2.0
jrivets/log4g
console_appender_test.go
1273
package log4g import ( "time" . "gopkg.in/check.v1" ) type cAppenderSuite struct { msg string signal chan bool } var _ = Suite(&cAppenderSuite{}) func (cas *cAppenderSuite) Write(p []byte) (n int, err error) { cas.msg = string(p) cas.signal <- true return len(p), nil } func (s *cAppenderSuite) TestNewAppender(c *C) { a, err := caFactory.NewAppender(map[string]string{}) c.Assert(a, IsNil) c.Assert(err, NotNil) a, err = caFactory.NewAppender(map[string]string{"abcd": "1234"}) c.Assert(a, IsNil) c.Assert(err, NotNil) a, err = caFactory.NewAppender(map[string]string{"layout": "%c %p"}) c.Assert(a, NotNil) c.Assert(err, IsNil) } func (s *cAppenderSuite) TestAppend(c *C) { s.signal = make(chan bool, 1) caFactory.out = s a, _ := caFactory.NewAppender(map[string]string{"layout": "[%d{15:04:05.000}] %p %c: %m"}) testTime := time.Unix(123456, 0) expectedTime := testTime.Format("[15:04:05.000]") appended := a.Append(&Event{FATAL, testTime, "a.b.c", "", "Hello Console!"}) c.Assert(appended, Equals, true) <-s.signal c.Assert(s.msg, Equals, expectedTime+" FATAL a.b.c: Hello Console!\n") caFactory.Shutdown() appended = a.Append(&Event{FATAL, time.Unix(0, 0), "a.b.c", "", "Never delivered"}) c.Assert(appended, Equals, false) }
apache-2.0
m4rkmckenna/brooklyn-ui-update
src/app/applications/entity-details/entity-activities/entity-activities.component.ts
313
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-entity-activities', templateUrl: './entity-activities.component.html', styleUrls: ['./entity-activities.component.scss'] }) export class EntityActivitiesComponent implements OnInit { constructor() { } ngOnInit() { } }
apache-2.0
illicitonion/buck
src/com/facebook/buck/d/DLibrary.java
3141
/* * Copyright 2015-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.d; import com.facebook.buck.cxx.Archive; import com.facebook.buck.cxx.CxxDescriptionEnhancer; import com.facebook.buck.cxx.CxxPlatform; import com.facebook.buck.cxx.Linker; import com.facebook.buck.cxx.NativeLinkable; import com.facebook.buck.cxx.NativeLinkableInput; import com.facebook.buck.parser.NoSuchBuildTargetException; import com.facebook.buck.rules.BuildRuleParams; import com.facebook.buck.rules.BuildRuleResolver; import com.facebook.buck.rules.NoopBuildRule; import com.facebook.buck.rules.SourcePath; import com.facebook.buck.rules.SourcePathResolver; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; public class DLibrary extends NoopBuildRule implements NativeLinkable { private final BuildRuleResolver buildRuleResolver; private final DIncludes includes; public DLibrary( BuildRuleParams params, BuildRuleResolver buildRuleResolver, SourcePathResolver sourcePathResolver, DIncludes includes) { super(params, sourcePathResolver); this.buildRuleResolver = buildRuleResolver; this.includes = includes; } @Override public Iterable<NativeLinkable> getNativeLinkableDeps(CxxPlatform cxxPlatform) { return ImmutableList.of(); } @Override public Iterable<NativeLinkable> getNativeLinkableExportedDeps(CxxPlatform cxxPlatform) { return FluentIterable.from(getDeclaredDeps()) .filter(NativeLinkable.class); } @Override public NativeLinkableInput getNativeLinkableInput( CxxPlatform cxxPlatform, Linker.LinkableDepType type) throws NoSuchBuildTargetException { Archive archive = (Archive) buildRuleResolver.requireRule( getBuildTarget().withFlavors( cxxPlatform.getFlavor(), CxxDescriptionEnhancer.STATIC_FLAVOR)); return NativeLinkableInput.of( ImmutableList.of(archive.toArg()), ImmutableSet.of(), ImmutableSet.of()); } @Override public NativeLinkable.Linkage getPreferredLinkage(CxxPlatform cxxPlatform) { return Linkage.STATIC; } @Override public ImmutableMap<String, SourcePath> getSharedLibraries(CxxPlatform cxxPlatform) { return ImmutableMap.of(); } public DIncludes getIncludes() throws NoSuchBuildTargetException { buildRuleResolver.requireRule(getBuildTarget().withFlavors(DDescriptionUtils.SOURCE_LINK_TREE)); return includes; } }
apache-2.0
ArseniyJ4J/akulikov
chapter_005/src/main/java/ru/job4j/collectionspro/list/SimpleLinkedList.java
5984
package ru.job4j.collectionspro.list; import java.util.Iterator; import java.util.NoSuchElementException; /** Класс SimpleLinkedList. * @author Arseniy Kulkiov * @since 28.08.2017 * @version 1 * @param <E> - параметризованный тип. */ public class SimpleLinkedList<E> implements Iterable { /** * Поле класса size - текущее количество элементов в контейнере. */ private int size = 0; /** * Поле класса first - первый элемент контейнера. */ private Node<E> first; /** * Поле класса last - последний элемент контейнера. */ private Node<E> last; /** * Поле класса counter - счетчик положения каретки итератора. */ private int counter = 0; /** * Конструктор. */ public SimpleLinkedList() { last = new Node<E>(null, null); first = new Node<E>(null, this.last); } /** * Геттер для поля size. * @return - возврат значения. */ public int getSize() { return size; } /** * Метод добавления элемента в контейнер. * @param value - добавляемое значение. */ public void add(E value) { Node<E> prev = last; prev.setItem(value); last = new Node<>(null, null); prev.setNext(last); size++; } /** * Метод возвращающий значние по индексу. * @param index - индекс. * @return - возврат значения. */ public E get(int index) { if (index < size) { Node<E> target = this.first.getNext(); for (int i = 0; i < index; i++) { target = target.getNext(); } return target.getItem(); } else { throw new NoSuchElementException(); } } /** * Метод удаляющий и возвращающий элемент из контейнера. * @param index - индекс элемента. * @return - возврат значения. */ public E delete(int index) { if (index < size) { E result = this.get(index); Node<E> target = this.first.getNext(); for (int i = 0; i <= index; i++) { if (index == 0) { Node<E> prev = target.getNext(); this.first.setNext(prev); target.setNext(null); size--; break; } if (i >= index - 1) { Node<E> prev = target.getNext().getNext(); target.getNext().setNext(null); target.setNext(prev); this.size--; break; } else { target = target.getNext(); } } return result; } else { throw new NoSuchElementException(); } } /** * Внутренний класс Node. * @param <E> - параметризированный тип. */ private class Node<E> { /** * Поле класса item. Значение элемента контейнера. */ private E item; /** * Ссылка на следующий связанный элемент. */ private Node<E> next; /** * Конструктор. * @param item - item. * @param next - next. */ Node(E item, Node<E> next) { this.item = item; this.next = next; } /** * Геттер для поля класса Item. * @return - возврат значения. */ public E getItem() { return item; } /** * Сеттер для поля item. * @param item - параметр. */ public void setItem(E item) { this.item = item; } /** * Геттер для поля Next. * @return - возврат значения. */ public Node<E> getNext() { return next; } /** * Сеттер для поля next. * @param next - параметр. */ public void setNext(Node<E> next) { this.next = next; } } /** * Returns an iterator over elements of type {@code T}. * * @return an Iterator. */ @Override public Iterator iterator() { return new LinkedListIterator<E>(); } /** * Внутренний класс LinkedListIterator. * @param <E> - параметризированный тип. */ public class LinkedListIterator<E> implements Iterator { /** * Returns {@code true} if the iteration has more elements. * (In other words, returns {@code true} if {@link #next} would * return an element rather than throwing an exception.) * * @return {@code true} if the iteration has more elements */ @Override public boolean hasNext() { return counter < size; } /** * Returns the next element in the iteration. * * @return the next element in the iteration * @throws NoSuchElementException if the iteration has no more elements */ @Override public Object next() throws NoSuchElementException { if (hasNext()) { return get(counter++); } else { throw new NoSuchElementException(); } } } }
apache-2.0
vdemeester/containerd
runtime/v2/shim.go
12965
/* Copyright The containerd 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 v2 import ( "context" "io" "io/ioutil" "os" "path/filepath" "time" eventstypes "github.com/containerd/containerd/api/events" "github.com/containerd/containerd/api/types" tasktypes "github.com/containerd/containerd/api/types/task" "github.com/containerd/containerd/errdefs" "github.com/containerd/containerd/events/exchange" "github.com/containerd/containerd/identifiers" "github.com/containerd/containerd/log" "github.com/containerd/containerd/namespaces" "github.com/containerd/containerd/pkg/timeout" "github.com/containerd/containerd/runtime" client "github.com/containerd/containerd/runtime/v2/shim" "github.com/containerd/containerd/runtime/v2/task" "github.com/containerd/ttrpc" ptypes "github.com/gogo/protobuf/types" "github.com/pkg/errors" "github.com/sirupsen/logrus" ) const ( loadTimeout = "io.containerd.timeout.shim.load" cleanupTimeout = "io.containerd.timeout.shim.cleanup" shutdownTimeout = "io.containerd.timeout.shim.shutdown" ) func init() { timeout.Set(loadTimeout, 5*time.Second) timeout.Set(cleanupTimeout, 5*time.Second) timeout.Set(shutdownTimeout, 3*time.Second) } func loadAddress(path string) (string, error) { data, err := ioutil.ReadFile(path) if err != nil { return "", err } return string(data), nil } func loadShim(ctx context.Context, bundle *Bundle, events *exchange.Exchange, rt *runtime.TaskList, onClose func()) (_ *shim, err error) { address, err := loadAddress(filepath.Join(bundle.Path, "address")) if err != nil { return nil, err } conn, err := client.Connect(address, client.AnonReconnectDialer) if err != nil { return nil, err } defer func() { if err != nil { conn.Close() } }() shimCtx, cancelShimLog := context.WithCancel(ctx) defer func() { if err != nil { cancelShimLog() } }() f, err := openShimLog(shimCtx, bundle, client.AnonReconnectDialer) if err != nil { return nil, errors.Wrap(err, "open shim log pipe when reload") } defer func() { if err != nil { f.Close() } }() // open the log pipe and block until the writer is ready // this helps with synchronization of the shim // copy the shim's logs to containerd's output go func() { defer f.Close() _, err := io.Copy(os.Stderr, f) // To prevent flood of error messages, the expected error // should be reset, like os.ErrClosed or os.ErrNotExist, which // depends on platform. err = checkCopyShimLogError(ctx, err) if err != nil { log.G(ctx).WithError(err).Error("copy shim log after reload") } }() onCloseWithShimLog := func() { onClose() cancelShimLog() f.Close() } client := ttrpc.NewClient(conn, ttrpc.WithOnClose(onCloseWithShimLog)) defer func() { if err != nil { client.Close() } }() s := &shim{ client: client, task: task.NewTaskClient(client), bundle: bundle, events: events, rtTasks: rt, } ctx, cancel := timeout.WithContext(ctx, loadTimeout) defer cancel() if err := s.Connect(ctx); err != nil { return nil, err } return s, nil } func cleanupAfterDeadShim(ctx context.Context, id, ns string, rt *runtime.TaskList, events *exchange.Exchange, binaryCall *binary) { ctx = namespaces.WithNamespace(ctx, ns) ctx, cancel := timeout.WithContext(ctx, cleanupTimeout) defer cancel() log.G(ctx).WithFields(logrus.Fields{ "id": id, "namespace": ns, }).Warn("cleaning up after shim disconnected") response, err := binaryCall.Delete(ctx) if err != nil { log.G(ctx).WithError(err).WithFields(logrus.Fields{ "id": id, "namespace": ns, }).Warn("failed to clean up after shim disconnected") } if _, err := rt.Get(ctx, id); err != nil { // Task was never started or was already successfully deleted // No need to publish events return } var ( pid uint32 exitStatus uint32 exitedAt time.Time ) if response != nil { pid = response.Pid exitStatus = response.Status exitedAt = response.Timestamp } else { exitStatus = 255 exitedAt = time.Now() } events.Publish(ctx, runtime.TaskExitEventTopic, &eventstypes.TaskExit{ ContainerID: id, ID: id, Pid: pid, ExitStatus: exitStatus, ExitedAt: exitedAt, }) events.Publish(ctx, runtime.TaskDeleteEventTopic, &eventstypes.TaskDelete{ ContainerID: id, Pid: pid, ExitStatus: exitStatus, ExitedAt: exitedAt, }) } type shim struct { bundle *Bundle client *ttrpc.Client task task.TaskService taskPid int events *exchange.Exchange rtTasks *runtime.TaskList } func (s *shim) Connect(ctx context.Context) error { response, err := s.task.Connect(ctx, &task.ConnectRequest{ ID: s.ID(), }) if err != nil { return err } s.taskPid = int(response.TaskPid) return nil } func (s *shim) Shutdown(ctx context.Context) error { _, err := s.task.Shutdown(ctx, &task.ShutdownRequest{ ID: s.ID(), }) if err != nil && !errors.Is(err, ttrpc.ErrClosed) { return errdefs.FromGRPC(err) } return nil } func (s *shim) waitShutdown(ctx context.Context) error { ctx, cancel := timeout.WithContext(ctx, shutdownTimeout) defer cancel() return s.Shutdown(ctx) } // ID of the shim/task func (s *shim) ID() string { return s.bundle.ID } // PID of the task func (s *shim) PID() uint32 { return uint32(s.taskPid) } func (s *shim) Namespace() string { return s.bundle.Namespace } func (s *shim) Close() error { return s.client.Close() } func (s *shim) Delete(ctx context.Context) (*runtime.Exit, error) { response, shimErr := s.task.Delete(ctx, &task.DeleteRequest{ ID: s.ID(), }) if shimErr != nil { log.G(ctx).WithField("id", s.ID()).WithError(shimErr).Debug("failed to delete task") if !errors.Is(shimErr, ttrpc.ErrClosed) { shimErr = errdefs.FromGRPC(shimErr) if !errdefs.IsNotFound(shimErr) { return nil, shimErr } } } // NOTE: If the shim has been killed and ttrpc connection has been // closed, the shimErr will not be nil. For this case, the event // subscriber, like moby/moby, might have received the exit or delete // events. Just in case, we should allow ttrpc-callback-on-close to // send the exit and delete events again. And the exit status will // depend on result of shimV2.Delete. // // If not, the shim has been delivered the exit and delete events. // So we should remove the record and prevent duplicate events from // ttrpc-callback-on-close. if shimErr == nil { s.rtTasks.Delete(ctx, s.ID()) } if err := s.waitShutdown(ctx); err != nil { log.G(ctx).WithField("id", s.ID()).WithError(err).Error("failed to shutdown shim") } s.Close() s.client.UserOnCloseWait(ctx) // remove self from the runtime task list // this seems dirty but it cleans up the API across runtimes, tasks, and the service s.rtTasks.Delete(ctx, s.ID()) if err := s.bundle.Delete(); err != nil { log.G(ctx).WithField("id", s.ID()).WithError(err).Error("failed to delete bundle") } if shimErr != nil { return nil, shimErr } return &runtime.Exit{ Status: response.ExitStatus, Timestamp: response.ExitedAt, Pid: response.Pid, }, nil } func (s *shim) Create(ctx context.Context, opts runtime.CreateOpts) (runtime.Task, error) { topts := opts.TaskOptions if topts == nil { topts = opts.RuntimeOptions } request := &task.CreateTaskRequest{ ID: s.ID(), Bundle: s.bundle.Path, Stdin: opts.IO.Stdin, Stdout: opts.IO.Stdout, Stderr: opts.IO.Stderr, Terminal: opts.IO.Terminal, Checkpoint: opts.Checkpoint, Options: topts, } for _, m := range opts.Rootfs { request.Rootfs = append(request.Rootfs, &types.Mount{ Type: m.Type, Source: m.Source, Options: m.Options, }) } response, err := s.task.Create(ctx, request) if err != nil { return nil, errdefs.FromGRPC(err) } s.taskPid = int(response.Pid) return s, nil } func (s *shim) Pause(ctx context.Context) error { if _, err := s.task.Pause(ctx, &task.PauseRequest{ ID: s.ID(), }); err != nil { return errdefs.FromGRPC(err) } return nil } func (s *shim) Resume(ctx context.Context) error { if _, err := s.task.Resume(ctx, &task.ResumeRequest{ ID: s.ID(), }); err != nil { return errdefs.FromGRPC(err) } return nil } func (s *shim) Start(ctx context.Context) error { response, err := s.task.Start(ctx, &task.StartRequest{ ID: s.ID(), }) if err != nil { return errdefs.FromGRPC(err) } s.taskPid = int(response.Pid) return nil } func (s *shim) Kill(ctx context.Context, signal uint32, all bool) error { if _, err := s.task.Kill(ctx, &task.KillRequest{ ID: s.ID(), Signal: signal, All: all, }); err != nil { return errdefs.FromGRPC(err) } return nil } func (s *shim) Exec(ctx context.Context, id string, opts runtime.ExecOpts) (runtime.Process, error) { if err := identifiers.Validate(id); err != nil { return nil, errors.Wrapf(err, "invalid exec id %s", id) } request := &task.ExecProcessRequest{ ID: s.ID(), ExecID: id, Stdin: opts.IO.Stdin, Stdout: opts.IO.Stdout, Stderr: opts.IO.Stderr, Terminal: opts.IO.Terminal, Spec: opts.Spec, } if _, err := s.task.Exec(ctx, request); err != nil { return nil, errdefs.FromGRPC(err) } return &process{ id: id, shim: s, }, nil } func (s *shim) Pids(ctx context.Context) ([]runtime.ProcessInfo, error) { resp, err := s.task.Pids(ctx, &task.PidsRequest{ ID: s.ID(), }) if err != nil { return nil, errdefs.FromGRPC(err) } var processList []runtime.ProcessInfo for _, p := range resp.Processes { processList = append(processList, runtime.ProcessInfo{ Pid: p.Pid, Info: p.Info, }) } return processList, nil } func (s *shim) ResizePty(ctx context.Context, size runtime.ConsoleSize) error { _, err := s.task.ResizePty(ctx, &task.ResizePtyRequest{ ID: s.ID(), Width: size.Width, Height: size.Height, }) if err != nil { return errdefs.FromGRPC(err) } return nil } func (s *shim) CloseIO(ctx context.Context) error { _, err := s.task.CloseIO(ctx, &task.CloseIORequest{ ID: s.ID(), Stdin: true, }) if err != nil { return errdefs.FromGRPC(err) } return nil } func (s *shim) Wait(ctx context.Context) (*runtime.Exit, error) { response, err := s.task.Wait(ctx, &task.WaitRequest{ ID: s.ID(), }) if err != nil { return nil, errdefs.FromGRPC(err) } return &runtime.Exit{ Pid: uint32(s.taskPid), Timestamp: response.ExitedAt, Status: response.ExitStatus, }, nil } func (s *shim) Checkpoint(ctx context.Context, path string, options *ptypes.Any) error { request := &task.CheckpointTaskRequest{ ID: s.ID(), Path: path, Options: options, } if _, err := s.task.Checkpoint(ctx, request); err != nil { return errdefs.FromGRPC(err) } return nil } func (s *shim) Update(ctx context.Context, resources *ptypes.Any, annotations map[string]string) error { if _, err := s.task.Update(ctx, &task.UpdateTaskRequest{ ID: s.ID(), Resources: resources, Annotations: annotations, }); err != nil { return errdefs.FromGRPC(err) } return nil } func (s *shim) Stats(ctx context.Context) (*ptypes.Any, error) { response, err := s.task.Stats(ctx, &task.StatsRequest{ ID: s.ID(), }) if err != nil { return nil, errdefs.FromGRPC(err) } return response.Stats, nil } func (s *shim) Process(ctx context.Context, id string) (runtime.Process, error) { p := &process{ id: id, shim: s, } if _, err := p.State(ctx); err != nil { return nil, err } return p, nil } func (s *shim) State(ctx context.Context) (runtime.State, error) { response, err := s.task.State(ctx, &task.StateRequest{ ID: s.ID(), }) if err != nil { if !errors.Is(err, ttrpc.ErrClosed) { return runtime.State{}, errdefs.FromGRPC(err) } return runtime.State{}, errdefs.ErrNotFound } var status runtime.Status switch response.Status { case tasktypes.StatusCreated: status = runtime.CreatedStatus case tasktypes.StatusRunning: status = runtime.RunningStatus case tasktypes.StatusStopped: status = runtime.StoppedStatus case tasktypes.StatusPaused: status = runtime.PausedStatus case tasktypes.StatusPausing: status = runtime.PausingStatus } return runtime.State{ Pid: response.Pid, Status: status, Stdin: response.Stdin, Stdout: response.Stdout, Stderr: response.Stderr, Terminal: response.Terminal, ExitStatus: response.ExitStatus, ExitedAt: response.ExitedAt, }, nil }
apache-2.0
ScripterRon/BitcoinWallet
src/main/java/org/ScripterRon/BitcoinWallet/ReceiveTransaction.java
5800
/** * Copyright 2013-2016 Ronald W Hoffman * * 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.ScripterRon.BitcoinWallet; import org.ScripterRon.BitcoinCore.Address; import org.ScripterRon.BitcoinCore.Sha256Hash; import java.math.BigInteger; /** * A ReceiveTransction represents coins sent to the wallet and is created * from a transaction output that references one of the wallet addresses. */ public class ReceiveTransaction extends WalletTransaction { /** Transaction output index */ private int txIndex; /** Transaction output script bytes */ private byte[] scriptBytes; /** Transaction spent status */ private boolean isSpent; /** Transaction is change returned for a send transaction */ private boolean isChange; /** Transaction is a coinbase transaction */ private boolean isCoinBase; /** Transaction is in the safe */ private boolean inSafe; /** * Creates a ReceiveTransaction * * @param normID Normalized transaction ID * @param txHash Transaction output hash * @param txIndex Transaction output index * @param txTime Transaction timestamp * @param blockHash Chain block containing the transaction or null * @param address Receiving public key address * @param value Transaction value * @param scriptBytes Transaction output script bytes * @param isChange TRUE if change transaction * @param isCoinBase TRUE if coinbase transaction */ public ReceiveTransaction(Sha256Hash normID, Sha256Hash txHash, int txIndex, long txTime, Sha256Hash blockHash, Address address, BigInteger value, byte[] scriptBytes, boolean isChange, boolean isCoinBase) { this(normID, txHash, txIndex, txTime, blockHash, address, value, scriptBytes, false, isChange, isCoinBase, false); } /** * Creates a ReceiveTransaction * * @param normID Normalized transaction ID * @param txHash Transaction output hash * @param txIndex Transaction output index * @param txTime Transaction timestamp * @param blockHash Chain block containing the transaction or null * @param address Receiving public key address * @param value Transaction value * @param scriptBytes Transaction output script bytes * @param isSpent TRUE if transaction value has been spent * @param isChange TRUE if the transaction represents change from a send transaction * @param isCoinBase TRUE if coinbase transaction * @param inSafe TRUE if the transaction is in the safe */ public ReceiveTransaction(Sha256Hash normID, Sha256Hash txHash, int txIndex, long txTime, Sha256Hash blockHash, Address address, BigInteger value, byte[] scriptBytes, boolean isSpent, boolean isChange, boolean isCoinBase, boolean inSafe) { super(normID, txHash, txTime, blockHash, address, value); this.txIndex = txIndex; this.scriptBytes = scriptBytes; this.isSpent = isSpent; this.isChange = isChange; this.isCoinBase = isCoinBase; this.inSafe = inSafe; } /** * Returns the transaction output index * * @return Transaction output index */ public int getTxIndex() { return txIndex; } /** * Returns the transaction output script bytes * * @return Script bytes */ public byte[] getScriptBytes() { return scriptBytes; } /** * Checks if the transaction value has been spent * * @return TRUE if value has been spent */ public boolean isSpent() { return isSpent; } /** * Sets the transaction spent status * * @param isSpent TRUE if the value has been spent */ public void setSpent(boolean isSpent) { this.isSpent = isSpent; } /** * Checks if this is a change transaction * * @return TRUE if this is a change transaction */ public boolean isChange() { return isChange; } /** * Checks if this is a coinbase transaction * * @return TRUE if this is a coinbase transaction */ public boolean isCoinBase() { return isCoinBase; } /** * Checks if the transaction is in the safe * * @return TRUE if the transaction is in the safe */ public boolean inSafe() { return inSafe; } /** * Sets the transaction safe status * * @param inSafe TRUE if the transaction is in the safe */ public void setSafe(boolean inSafe) { this.inSafe = inSafe; } }
apache-2.0
consulo/consulo-dotnet
msil-psi-impl/src/main/java/consulo/msil/lang/psi/impl/MsilArrayDimensionImpl.java
1639
package consulo.msil.lang.psi.impl; import javax.annotation.Nonnull; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.stubs.IStubElementType; import com.intellij.util.ArrayFactory; import consulo.annotation.access.RequiredReadAction; import consulo.msil.lang.psi.MsilArrayDimension; import consulo.msil.lang.psi.MsilTokens; import consulo.msil.lang.psi.impl.elementType.stub.MsilArrayDimensionStub; /** * @author VISTALL * @since 10.12.14 */ public class MsilArrayDimensionImpl extends MsilStubElementImpl<MsilArrayDimensionStub> implements MsilArrayDimension { public static final MsilArrayDimensionImpl[] EMPTY_ARRAY = new MsilArrayDimensionImpl[0]; public static ArrayFactory<MsilArrayDimensionImpl> ARRAY_FACTORY = new ArrayFactory<MsilArrayDimensionImpl>() { @Nonnull @Override public MsilArrayDimensionImpl[] create(int count) { return count == 0 ? EMPTY_ARRAY : new MsilArrayDimensionImpl[count]; } }; public MsilArrayDimensionImpl(@Nonnull ASTNode node) { super(node); } public MsilArrayDimensionImpl(@Nonnull MsilArrayDimensionStub stub, @Nonnull IStubElementType nodeType) { super(stub, nodeType); } @Override @RequiredReadAction public int getLowerValue() { MsilArrayDimensionStub stub = getGreenStub(); if(stub != null) { return stub.getLowerValue(); } PsiElement numberElement = findChildByType(MsilTokens.NUMBER_LITERAL); if(numberElement == null) { return -1; } return Integer.parseInt(numberElement.getText()); } @Override public void accept(MsilVisitor visitor) { visitor.visitArrayDimension(this); } }
apache-2.0
keyvank/pooljs
django_project/static/js/processor.js
5922
(function (context) { var WEBSOCKET_HOST = "pooljs.ir"; var WEBSOCKET_PORT = 12121; var WEBSOCKET_ADDRESS = "wss://" + WEBSOCKET_HOST + ":" + WEBSOCKET_PORT; var TURBOJS_URL = "https://turbo.github.io/js/turbo.js"; if(window && "WebSocket" in window && typeof(Worker) !== "undefined") { function loadScript(url, callback) { var head = document.getElementsByTagName('head')[0]; var script = document.createElement('script'); script.type = 'text/javascript'; script.src = url; script.onload = callback; head.appendChild(script); } loadScript(TURBOJS_URL,function() { if(turbojs) { // Turbo.js has now been loaded! // Create a Worker by a function function createWorker(foo) { var str = foo.toString().match(/^\s*function\s*\(\s*\)\s*\{(([\s\S](?!\}$))*[\s\S])/)[1]; return new Worker(window.URL.createObjectURL(new Blob([str],{type:'text/javascript'}))); } function now() { return new Date().getTime(); } var MAX_SUBPROCESS_TIME = 4000; // Maximum amount of time for a Worker to return the result in miliseconds var workerPool = []; var subprocesses = []; function fillPool() { while(workerPool.length < navigator.hardwareConcurrency) { var worker = createWorker(function(){ var self = this; var lastProcessId = undefined; var fn; this.addEventListener("message", function(event) { var subprocess = event.data; if(subprocess.process_id !== lastProcessId) { var src = "fn = " + subprocess.code; eval(src); lastProcessId = subprocess.process_id; } var subprocess_result = { "id": subprocess.id, "result": fn.apply(this, subprocess.args), "error": false }; self.postMessage(subprocess_result); }, false); }); worker.subprocessCreatedTime = null; worker.subprocess = null; workerPool.push(worker); } } fillPool(); context.worker = {} var sock = null; function freeWorkersCount() { var count = 0; for(var i = 0; i < workerPool.length; i++) { if(!workerPool[i].subprocess) { count++; } } return count; } // Notify that there is a free Worker to execute a new SubProcess function notify() { for(var i = 0; i < freeWorkersCount(); i++) { var new_subprocess = subprocesses.shift(); if(new_subprocess) balance(new_subprocess,false); } } function response(event,worker) { var subprocess_result = event.data; worker.subprocessCreatedTime = null; worker.subprocess = null; sock.send(JSON.stringify(subprocess_result)); notify(); // The Worker is now free } function balance(subprocess,isnew) { if(isnew && subprocesses.length > 0){ // Older undone SubProcesses have more priority than new SubProcesses subprocesses.push(subprocess); subprocess = subprocesses.shift(); } var done = false; // Find a free Worker and pass a SubProcess to it for(var i = 0; i < workerPool.length; i++) { var w = workerPool[i]; if(!w.subprocess) { w.subprocessCreatedTime = now(); w.subprocess = subprocess; w.onmessage = function(event) { response(event,w); }; w.postMessage(subprocess); done = true; break; } } // If there was no free Worker then push the subprocess in the queue for further execution if(!done) { subprocesses.push(subprocess); } } // Run GPU Subprocesses via Turbo.js var lastGPUProcessId = undefined; var lastGPUKernel = undefined; function balanceGPU(subprocess) { if(subprocess.process_id == lastGPUProcessId) subprocess.code = lastGPUKernel; else { lastGPUProcessId = subprocess.process_id; lastGPUKernel = subprocess.code; } var size = subprocess.args[1] - subprocess.args[0]; var foo = turbojs.alloc(size * 4); for (var i = 0; i < size; i++) foo.data[4*i] = subprocess.args[0] + i; var has_error = false; try { turbojs.run(foo, subprocess.code + 'void main(void) { ' + 'commit(f(int(read().r)));' + '}'); } catch(err) { has_error = true; } var res = foo.data.subarray(0,size * 4); var arr = []; for(var i=0;i<size;i++) arr.push([res[4*i],res[4*i+1],res[4*i+2],res[4*i+3]]); var subprocess_result = { "id": subprocess.id, "result": has_error?null:arr, "error": has_error }; sock.send(JSON.stringify(subprocess_result)); } function startSocket() { sock = new WebSocket(WEBSOCKET_ADDRESS); sock.onopen = function() { }; sock.onmessage = function(event) { var subprocess = JSON.parse(event.data); if(subprocess.is_GPU) balanceGPU(subprocess); else balance(subprocess,true); }; sock.onclose = function() { setTimeout(startSocket,5000); }; } startSocket(); // Kill the Workers running SubProcesses that take too long to respond function badSubProcessKiller() { for(var i = 0; i < workerPool.length; i++) { if(workerPool[i].subprocessCreatedTime) { // If the Worker is busy if(now() - workerPool[i].subprocessCreatedTime > MAX_SUBPROCESS_TIME) { var w = workerPool[i]; w.terminate(); workerPool.splice(i,1); if(sock) { var subprocess_result = { "id": w.subprocess.id, "result": null, "error": true }; // Send null as the result of SubProcesses taking too long to respond sock.send(JSON.stringify(subprocess_result)); } } } } fillPool(); // Fill the pool as some Workers have been terminated and removed notify(); setTimeout(badSubProcessKiller, MAX_SUBPROCESS_TIME/2); } badSubProcessKiller(); } }); } }(this));
apache-2.0
gleb619/webcam
src/main/java/org/test/webcam/model/dao/secure/UserDao.java
4854
/* * */ package org.test.webcam.model.dao.secure; import java.util.ArrayList; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.springframework.dao.DataAccessException; import org.springframework.stereotype.Repository; import org.test.webcam.model.domain.entity.secure.User; // TODO: Auto-generated Javadoc /** * The Class UserDao. */ @Repository public class UserDao { /** The em. */ @PersistenceContext private EntityManager em; public User findByToken(String token) { List<User> users = em.createQuery("SELECT u FROM User u where u.token = :token", User.class) .setParameter("token", token) .setMaxResults(1) .getResultList(); if (users.size() > 0) { return users.get(0); } else { return null; } } /** * Find by user name. * * @param username the username * @return the user * @throws DataAccessException the data access exception */ public User findByUserName(String username) throws DataAccessException { List<User> user = new ArrayList<User>(); user = em.createQuery("SELECT u FROM User u where u.username = :username", User.class) .setParameter("username", username) .setMaxResults(1) .getResultList(); if (user.size() > 0) { return user.get(0); } else { return null; } } /** * Creates the. * * @param User the user * @return the user */ public User create(User User) { em.persist(User); return User; } /** * Update. * * @param User the user * @return the user */ public User update(User User) { return em.merge(User); } /** * Find all. * * @return the list */ public List<User> findAll() { return em.createQuery("SELECT use0 FROM User use0" , User.class).getResultList(); } /** * Find by id. * * @param id the id * @return the user */ public User findById(Integer id) { User User = em.createQuery("SELECT use0 FROM User use0 where use0.id = :id" , User.class) .setParameter("id", id) .getSingleResult(); //return em.find(User.class, id); return User; } /** * Delete. * * @param id the id * @return the boolean */ public Boolean delete(Integer id) { try { em.remove(em.getReference(User.class, id)); return true; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } } // ---------------------------------- /** * Find all. * * @param initDicts the init dicts * @return the list */ public List<User> findAll(Boolean initDicts) { List<User> User = em.createQuery("SELECT use0 FROM User use0" , User.class).getResultList(); if (initDicts) { for (User item : User) { item.initDicts(); } } return User; } /** * Find all. * * @param initDicts the init dicts * @param firmid the firmid * @return the list */ public List<User> findAll(Boolean initDicts, Integer firmid) { List<User> User = em.createQuery("SELECT use0 FROM User use0 WHERE use0.firmid = :firmid" , User.class) .setParameter("firmid", firmid) .getResultList(); if (initDicts) { for (User item : User) { item.initDicts(); } } return User; } /** * Find all scrollable. * * @param initDicts the init dicts * @param initLists the init lists * @param firmid the firmid * @param pageNumber the page number * @param pageSize the page size * @return the list */ public List<User> findAllScrollable(Boolean initDicts, Boolean initLists, Integer firmid, Integer pageNumber, Integer pageSize) { List<User> User = em.createQuery("SELECT use0 FROM User use0 WHERE use0.firmid = :firmid" , User.class) .setParameter("firmid", firmid) .setFirstResult((pageNumber - 1) * pageSize) .setMaxResults(pageSize) .getResultList(); Boolean check = false; if(initLists || initDicts){ check = true; } if (check) { for (User item : User) { if (initDicts) { item.initDicts(); } if (initLists) { item.initList(); } } } return User; } /** * Find all scrollable. * * @param initDicts the init dicts * @param initLists the init lists * @param pageNumber the page number * @param pageSize the page size * @return the list */ public List<User> findAllScrollable(Boolean initDicts, Boolean initLists, Integer pageNumber, Integer pageSize) { List<User> User = em.createQuery("SELECT use0 FROM User use0" , User.class) .setFirstResult((pageNumber - 1) * pageSize) .setMaxResults(pageSize) .getResultList(); Boolean check = false; if(initLists || initDicts){ check = true; } if (check) { for (User item : User) { if (initDicts) { item.initDicts(); } if (initLists) { item.initList(); } } } return User; } }
apache-2.0
noundla/Sunny_android_samples
src/com/vl/samples/animation/DrawableAnimationActivity.java
1439
package com.vl.samples.animation; import android.app.Activity; import android.graphics.drawable.AnimationDrawable; import android.os.Bundle; import android.widget.ImageView; import com.vl.samples.R; public class DrawableAnimationActivity extends Activity { AnimationDrawable rocketAnimation; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.drawable_anim); ImageView rocketImage = (ImageView) findViewById(R.id.rocket_image); rocketImage.setBackgroundResource(R.drawable.rocket_thrust); rocketAnimation = (AnimationDrawable) rocketImage.getBackground(); } /** * If we need to start our animation, we have wait upto user interaction. * Because we must call the start() method on AnimationDrawable object to start animation. * Ex: rocketAnimation.start(); * */ /*@Override public boolean onTouchEvent(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { rocketAnimation.start(); return true; } return super.onTouchEvent(event); }*/ /**The below method will be called when the activity get/loss focus. * So we can start our animation in this by without user interaction. * */ @Override public void onWindowFocusChanged(boolean hasFocus) { if(hasFocus){ rocketAnimation.start(); } super.onWindowFocusChanged(hasFocus); } }
apache-2.0
cstamas/httpclient
httpmime/src/main/java/org/apache/http/entity/mime/MultipartEntity.java
5895
/* * ==================================================================== * 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.entity.mime; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.charset.Charset; import java.util.Iterator; import java.util.List; import java.util.Random; import org.apache.http.annotation.ThreadSafe; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.entity.mime.content.ContentBody; import org.apache.http.message.BasicHeader; import org.apache.http.protocol.HTTP; import org.apache.james.mime4j.field.Fields; import org.apache.james.mime4j.message.Message; /** * Multipart/form coded HTTP entity consisting of multiple * body parts. * * * @since 4.0 */ @ThreadSafe public class MultipartEntity implements HttpEntity { /** * The pool of ASCII chars to be used for generating a multipart boundary. */ private final static char[] MULTIPART_CHARS = "-_1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" .toCharArray(); private final Message message; private final HttpMultipart multipart; private final Header contentType; private long length; private volatile boolean dirty; // used to decide whether to recalculate length public MultipartEntity( HttpMultipartMode mode, final String boundary, final Charset charset) { super(); this.multipart = new HttpMultipart("form-data"); this.contentType = new BasicHeader( HTTP.CONTENT_TYPE, generateContentType(boundary, charset)); this.dirty = true; this.message = new Message(); org.apache.james.mime4j.message.Header header = new org.apache.james.mime4j.message.Header(); this.message.setHeader(header); this.multipart.setParent(message); if (mode == null) { mode = HttpMultipartMode.STRICT; } this.multipart.setMode(mode); this.message.getHeader().addField(Fields.contentType(this.contentType.getValue())); } public MultipartEntity(final HttpMultipartMode mode) { this(mode, null, null); } public MultipartEntity() { this(HttpMultipartMode.STRICT, null, null); } protected String generateContentType( final String boundary, final Charset charset) { StringBuilder buffer = new StringBuilder(); buffer.append("multipart/form-data; boundary="); if (boundary != null) { buffer.append(boundary); } else { Random rand = new Random(); int count = rand.nextInt(11) + 30; // a random size from 30 to 40 for (int i = 0; i < count; i++) { buffer.append(MULTIPART_CHARS[rand.nextInt(MULTIPART_CHARS.length)]); } } if (charset != null) { buffer.append("; charset="); buffer.append(charset.name()); } return buffer.toString(); } public void addPart(final String name, final ContentBody contentBody) { this.multipart.addBodyPart(new FormBodyPart(name, contentBody)); this.dirty = true; } public boolean isRepeatable() { List<?> parts = this.multipart.getBodyParts(); for (Iterator<?> it = parts.iterator(); it.hasNext(); ) { FormBodyPart part = (FormBodyPart) it.next(); ContentBody body = (ContentBody) part.getBody(); if (body.getContentLength() < 0) { return false; } } return true; } public boolean isChunked() { return !isRepeatable(); } public boolean isStreaming() { return !isRepeatable(); } public long getContentLength() { if (this.dirty) { this.length = this.multipart.getTotalLength(); this.dirty = false; } return this.length; } public Header getContentType() { return this.contentType; } public Header getContentEncoding() { return null; } public void consumeContent() throws IOException, UnsupportedOperationException{ if (isStreaming()) { throw new UnsupportedOperationException( "Streaming entity does not implement #consumeContent()"); } } public InputStream getContent() throws IOException, UnsupportedOperationException { throw new UnsupportedOperationException( "Multipart form entity does not implement #getContent()"); } public void writeTo(final OutputStream outstream) throws IOException { this.multipart.writeTo(outstream); } }
apache-2.0
thinking-github/nbone
nbone/nbone-core/src/main/java/org/nbone/component/logger/LogVoFactory.java
595
package org.nbone.component.logger; import java.util.Date; import org.nbone.component.logger.vo.LogVo; import org.nbone.constants.NboneConstants; /** * * @author Thinking 2014-8-8 * */ public class LogVoFactory { /** * 返回默认的LogVo 操作成功的 * @return */ public static LogVo getDefaultNewLogVO() { LogVo logVo = new LogVo(new Date(),NboneConstants.OPERATE_RESULT_SUCCESS); return logVo; } public static LogVo getOperateFailedNewLogVO() { LogVo logVo = new LogVo(new Date(),NboneConstants.OPERATE_RESULT_FAILED); return logVo; } }
apache-2.0
AKSW/SlideWiki
slidewiki/libraries/frontend/MathJax/fonts/HTML-CSS/TeX/png/AMS/Regular/unpacked/SpacingModLetters.js
1724
/************************************************************* * * MathJax/fonts/HTML-CSS/TeX/png/AMS/Regular/SpacingModLetters.js * * Defines the image size data needed for the HTML-CSS OutputJax * to display mathematics using fallback images when the fonts * are not availble to the client browser. * * --------------------------------------------------------------------- * * Copyright (c) 2009-2010 Design Science, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the * * 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. * */ MathJax.OutputJax["HTML-CSS"].defineImageData({ "MathJax_AMS": { 0x2C6: [ // MODIFIER LETTER CIRCUMFLEX ACCENT [18,3,-3],[21,3,-4],[25,3,-5],[29,4,-6],[34,5,-8],[40,5,-9],[47,6,-11],[56,8,-12], [66,8,-16],[79,10,-19],[93,12,-21],[110,14,-26],[131,17,-30],[156,20,-36] ], 0x2DC: [ // SMALL TILDE [17,2,-4],[21,2,-5],[24,4,-5],[29,5,-7],[34,4,-9],[40,5,-10],[47,6,-12],[56,6,-15], [66,8,-17],[78,9,-21],[93,11,-25],[110,13,-29],[130,15,-35],[155,18,-41] ] } }); MathJax.Ajax.loadComplete(MathJax.OutputJax["HTML-CSS"].imgDir+"/AMS/Regular"+ MathJax.OutputJax["HTML-CSS"].imgPacked+"/SpacingModLetters.js");
apache-2.0
Driox/sorus
app/helpers/SorusPlay.scala
4809
package helpers.sorus import helpers.sorus.SorusDSL._ import play.api.Logging import play.api.mvc._ import play.api.mvc.Results._ import play.api.data.Form import scala.concurrent.Future import play.api.data.validation.ValidationError import play.api.libs.json._ import scalaz._ import java.security.SecureRandom import scala.language.implicitConversions case class FailWithResult( override val message: String, val result: Result, override val cause: Option[\/[Throwable, Fail]] = None) extends Fail(message, cause) { override def withEx(fail: Fail): FailWithResult = new FailWithResult(this.message, result, Some(\/-(fail))) } trait FormatErrorResult[T <: Request[_]] { def failToResult(fail: Fail)(implicit request: Request[_]): Result = BadRequest(fail.userMessage()) def formatJsonValidationErrorToResult(errors: Seq[(JsPath, Seq[ValidationError])]): Result = { val translated_error = errors.map(a_path => (a_path._1, a_path._2.map(err => err.message))) BadRequest(toJson(translated_error)) } private[this] def toJson(errors: Seq[(JsPath, Seq[String])]): JsObject = { errors.foldLeft(Json.obj()) { (obj, error) => obj ++ Json.obj(error._1.toJsonString -> error._2.reduce((s1, s2) => s"$s1, $s2")) } } } /** * This trait allow you to use the ?| operator in your Play controller and get a Future[Result] instead of a Future[Fail \/ T] * * Usage : * * class MyController extends Controller with FormatErrorResult with SorusPlay * * You may override default serialization of Fail into Error by extending FormatErrorResult. */ trait SorusPlay[T <: Request[_]] extends Sorus with Logging { self: FormatErrorResult[T] => private[SorusPlay] def fromForm[A](onError: Form[A] => Fail)(form: Form[A]): Step[A] = EitherT[Future, Fail, A](Future.successful(form.fold(onError andThen \/.left, \/.right))) implicit def formToStepOps[A](form: Form[A]): StepOps[A, Form[A]] = new StepOps[A, Form[A]] { override def orFailWith(failureHandler: (Form[A]) => Fail) = fromForm(failureHandler)(form) } implicit def resultStepToResult(step: Step[Result])(implicit request: T): Future[Result] = { step.run.map { s => s.leftMap(addExceptionCode) .leftMap { f => log(f); f } .leftMap(transformFail2Result) .toEither .merge }(executionContext) } private def addExceptionCode(fail: Fail): Fail = { fail.getRootException() .map(_ => Fail(s"#${StringUtils.randomAlphanumericString(8)} ${fail.message}", fail.cause)) .getOrElse(fail) } protected def log(fail: Fail): Unit = { fail.getRootException().foreach(ex => logger.error(fail.userMessage, ex)) } private[this] def transformFail2Result(fail: Fail)(implicit request: T): Result = { fail match { case f: FailWithResult => f.result case f: Fail => failToResult(f) } } /** * Allow this kind of mapping with result on the left * ?|> don't stop the flow but replace the result if the first one fail * * criteria <- eventSearchForm.bindFromRequest ?| (formWithErrors => Ok(views.html.analyzer.index(formWithErrors))) */ implicit def result2Fail(result: Result): FailWithResult = { FailWithResult("result from ctrl", result) } /** * Avoid to write mapping like that * * consumer <- consumerService.loadByKey(key) ?| (err:Unit => NotFound) */ implicit def result2FailFromUnit(result: Result): Unit => FailWithResult = { _: Unit => FailWithResult("result from ctrl", result) } /** * Allow this kind of mapping * * consumers <- consumerService.search(q) ?| NotFound * * without the need to do * * consumers <- consumerService.search(q) ?| (err:Throwable => NotFound(err.getMessage).withEx(err)) * * For now you can't override the body of the response * * consumers <- consumerService.search(q) ?| NotFound("this will be erased") */ implicit def result2FailFunction(result: Result): Throwable => FailWithResult = { t: Throwable => { val rez_with_body = Status(result.header.status)(t.getMessage) FailWithResult("result from ctrl", rez_with_body, Some(-\/(t))) } } } private object StringUtils { /** * Elegant random string generation in Scala -> http://www.bindschaedler.com/2012/04/07/elegant-random-string-generation-in-scala/ */ //Random Generator private[this] val random = new SecureRandom() // Generate a random string of length n from the given alphabet private[this] def randomString(alphabet: String)(n: Int): String = { (1 to n).map(_ => random.nextInt(alphabet.size)).map(alphabet).mkString } // Generate a random alphabnumeric string of length n def randomAlphanumericString(n: Int): String = { randomString("abcdefghijklmnopqrstuvwxyz0123456789")(n) } }
apache-2.0
amahule/aws-sdk-for-android
src/com/amazonaws/services/s3/model/S3Object.java
4162
/* * Copyright 2010 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.s3.model; import java.io.InputStream; /** * Represents an object stored in Amazon S3. This object contains * the data content * and the object metadata stored by Amazon S3, such as content type, * content length, etc. * * @see ObjectMetadata */ public class S3Object { private static final long serialVersionUID = -2883501141593631181L; /** The key under which this object is stored */ private String key = null; /** The name of the bucket in which this object is contained */ private String bucketName = null; /** The metadata stored by Amazon S3 for this object */ private ObjectMetadata metadata = new ObjectMetadata(); /** The stream containing the contents of this object from S3 */ private InputStream objectContent; /** * Gets the metadata stored by Amazon S3 for this object. The * {@link ObjectMetadata} object includes any custom user metadata supplied by the * caller when the object was uploaded, as well as HTTP metadata such as * content length and content type. * * @return The metadata stored by Amazon S3 for this object. * * @see S3Object#getObjectContent() */ public ObjectMetadata getObjectMetadata() { return metadata; } /** * Gets an input stream containing the contents of this object. Callers * should close this input stream as soon as possible, because the * object contents aren't buffered in memory and stream directly from Amazon * S3. * * @return An input stream containing the contents of this object. * * @see S3Object#getObjectMetadata() * @see S3Object#setObjectContent(InputStream) */ public InputStream getObjectContent() { return objectContent; } /** * Sets the input stream containing this object's contents. * * @param objectContent * The input stream containing this object's contents. * * @see S3Object#getObjectContent() */ public void setObjectContent(InputStream objectContent) { this.objectContent = objectContent; } /** * Gets the name of the bucket in which this object is contained. * * @return The name of the bucket in which this object is contained. * * @see S3Object#setBucketName(String) */ public String getBucketName() { return bucketName; } /** * Sets the name of the bucket in which this object is contained. * * @param bucketName * The name of the bucket containing this object. * * @see S3Object#getBucketName() */ public void setBucketName(String bucketName) { this.bucketName = bucketName; } /** * Gets the key under which this object is stored. * * @return The key under which this object is stored. * * @see S3Object#setKey(String) */ public String getKey() { return key; } /** * Sets the key under which this object is stored. * * @param key * The key under which this object is stored. * * @see S3Object#getKey() */ public void setKey(String key) { this.key = key; } /** * @see java.lang.Object#toString() */ public String toString() { return "S3Object [key=" + getKey() + ",bucket=" + (bucketName == null ? "<Unknown>" : bucketName) + "]"; } }
apache-2.0
consulo/consulo-xml
xml-dom-api/src/main/java/com/intellij/util/xml/ui/CompositeCommittable.java
1556
/* * Copyright 2000-2009 JetBrains s.r.o. * * 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.intellij.util.xml.ui; import consulo.disposer.Disposer; import java.util.ArrayList; import java.util.List; /** * author: lesya */ public class CompositeCommittable implements Committable, Highlightable { private final List<Committable> myComponents = new ArrayList<Committable>(); public final <T extends Committable> T addComponent(T panel) { myComponents.add(panel); Disposer.register(this, panel); return panel; } public void commit() { for (final Committable committable : myComponents) { committable.commit(); } } public void reset() { for (final Committable committable : myComponents) { committable.reset(); } } public void dispose() { } public List<Committable> getChildren() { return myComponents; } public void updateHighlighting() { for (final Committable component : myComponents) { CommittableUtil.updateHighlighting(component); } } }
apache-2.0
martin-g/wicket-osgi
wicket-core/src/test/java/org/apache/wicket/protocol/http/WicketURLTest.java
1981
/* * 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.wicket.protocol.http; import org.apache.wicket.request.UrlDecoder; import org.apache.wicket.request.UrlEncoder; import org.junit.Assert; import org.junit.Test; /** * @author Doug Donohoe */ public class WicketURLTest extends Assert { /** * testPathEncoder() */ @Test public void pathEncoder() { assertEquals("+", UrlEncoder.PATH_INSTANCE.encode("+", "UTF-8")); assertEquals("%20", UrlEncoder.PATH_INSTANCE.encode(" ", "UTF-8")); } /** * testQueryEncoder() */ @Test public void queryEncoder() { assertEquals("+", UrlEncoder.QUERY_INSTANCE.encode(" ", "UTF-8")); assertEquals("%2B", UrlEncoder.QUERY_INSTANCE.encode("+", "UTF-8")); } /** * testPathDecoder() */ @Test public void pathDecoder() { assertEquals("+", UrlDecoder.PATH_INSTANCE.decode("+", "UTF-8")); assertEquals(" ", UrlDecoder.PATH_INSTANCE.decode("%20", "UTF-8")); } /** * testQueryDecoder() */ @Test public void queryDecoder() { assertEquals(" ", UrlDecoder.QUERY_INSTANCE.decode("+", "UTF-8")); assertEquals("+", UrlDecoder.QUERY_INSTANCE.decode("%2B", "UTF-8")); } }
apache-2.0
Brocade-OpenSource/OpenStack-DNRM
dnrm/openstack/common/exception.py
3312
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 OpenStack Foundation. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """ Exceptions common to OpenStack projects """ import logging from dnrm.openstack.common.gettextutils import _ # noqa _FATAL_EXCEPTION_FORMAT_ERRORS = False class Error(Exception): def __init__(self, message=None): super(Error, self).__init__(message) class ApiError(Error): def __init__(self, message='Unknown', code='Unknown'): self.api_message = message self.code = code super(ApiError, self).__init__('%s: %s' % (code, message)) class NotFound(Error): pass class UnknownScheme(Error): msg_fmt = "Unknown scheme '%s' found in URI" def __init__(self, scheme): msg = self.msg_fmt % scheme super(UnknownScheme, self).__init__(msg) class BadStoreUri(Error): msg_fmt = "The Store URI %s was malformed. Reason: %s" def __init__(self, uri, reason): msg = self.msg_fmt % (uri, reason) super(BadStoreUri, self).__init__(msg) class Duplicate(Error): pass class NotAuthorized(Error): pass class NotEmpty(Error): pass class Invalid(Error): pass class BadInputError(Exception): """Error resulting from a client sending bad input to a server""" pass class MissingArgumentError(Error): pass class DatabaseMigrationError(Error): pass class ClientConnectionError(Exception): """Error resulting from a client connecting to a server""" pass def wrap_exception(f): def _wrap(*args, **kw): try: return f(*args, **kw) except Exception as e: if not isinstance(e, Error): logging.exception(_('Uncaught exception')) raise Error(str(e)) raise _wrap.func_name = f.func_name return _wrap class OpenstackException(Exception): """Base Exception class. To correctly use this class, inherit from it and define a 'msg_fmt' property. That message will get printf'd with the keyword arguments provided to the constructor. """ msg_fmt = "An unknown exception occurred" def __init__(self, **kwargs): try: self._error_string = self.msg_fmt % kwargs except Exception: if _FATAL_EXCEPTION_FORMAT_ERRORS: raise else: # at least get the core message out if something happened self._error_string = self.msg_fmt def __str__(self): return self._error_string class MalformedRequestBody(OpenstackException): msg_fmt = "Malformed message body: %(reason)s" class InvalidContentType(OpenstackException): msg_fmt = "Invalid content type %(content_type)s"
apache-2.0
UBOdin/jitd-synthesis
src/main/scala/jitd/example/CppStdLib.scala
601
package jitd.example import jitd.spec._ import jitd.typecheck.FunctionSignature object CppStdLib { val functions = Seq( FunctionSignature("std::begin", Seq(TArray(TRecord())), TIterator()), FunctionSignature("std::end", Seq(TArray(TRecord())), TIterator()), FunctionSignature("std::find", Seq(TIterator(), TIterator(), TKey()), TIterator()), FunctionSignature("std::lower_bound", Seq(TIterator(), TIterator(), TKey()), TIterator()), FunctionSignature("std::vector<Record>", Seq(), TArray(TRecord())), FunctionSignature("std::sort", Seq(TIterator(), TIterator())) ) }
apache-2.0
smartsheet-platform/smartsheet-java-sdk
src/main/java/com/smartsheet/api/AccessTokenExpiredException.java
1364
package com.smartsheet.api; /* * #[license] * Smartsheet SDK for Java * %% * Copyright (C) 2014 Smartsheet * %% * 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. * %[license] */ import com.smartsheet.api.models.Error; /** * <p>This is the exception to indicate that an access token expired error returned from Smartsheet REST API. This * exception will be thrown when the Smartsheet REST API generates a "1003 Your Access Token has expired" error.</p> * * <p>Thread safety: Exceptions are not thread safe.</p> */ public class AccessTokenExpiredException extends AuthorizationException { private static final long serialVersionUID = 1L; /** * Instantiates a new access token expired exception. * * @param error the error */ public AccessTokenExpiredException(Error error) { super(error); } }
apache-2.0
hep-gc/cloudscheduler
cli/bin/csv2_my.py
2791
from csv2_common import check_keys, requests, show_active_user_groups, show_table, verify_yaml_file, yaml_full_load from subprocess import Popen, PIPE import filecmp import os import csv2_defaults KEY_MAP = { '-gn': 'default_group', '-upw': 'password', '-sfv': 'flag_show_foreign_global_vms', '-sgs': 'flag_global_status', '-sjta': 'flag_jobs_by_target_alias', '-sri': 'status_refresh_interval', '-ssd': 'flag_show_slot_detail', '-ssf': 'flag_show_slot_flavors', } def settings(gvar): """ Modify the specified user. """ mandatory = [] required = [] optional = ['-CSEP', '-CSV', '-gn', '-H', '-h', '-NV', '-ok', '-r', '-s', '-sfv', '-sgs', '-sjta', '-sri', '-ssd', '-ssf', '-upw', '-V', '-VC', '-v','-x509', '-xA'] if gvar['retrieve_options']: return mandatory + required + optional # Check for missing arguments or help required. form_data = check_keys( gvar, mandatory, required, optional, key_map=KEY_MAP) # if len(form_data) < 1: # print('Error: "%s my settings" requires at least one option to update.' % gvar['command_name']) # exit(1) # Create the user. response = requests( gvar, '/user/settings/', form_data ) if response['message']: print(response['message']) if response['response_code'] == 0 and 'user-password' in gvar['user_settings']: if 'server' not in gvar['command_args']: gvar['command_args']['server'] = gvar['pid_defaults']['server'] # If the user in defaults is changing their password, update it locally for them. with open(os.path.expanduser('~/.csv2/{}/settings.yaml').format(gvar['command_args']['server'])) as settings_file: saved_user = yaml_full_load(settings_file)['server-user'] if gvar['user_settings']['server-user'] == saved_user: gvar['user_settings']['server-password'] = gvar['user_settings']['user-password'] del gvar['user_settings']['user-password'] csv2_defaults.set(gvar) # Print report. show_active_user_groups(gvar, response) show_table( gvar, response['user_list'], [ 'username/Username,k', 'cert_cn/Cert Common Name', 'default_group/Default Group', 'flag_show_foreign_global_vms/Foreign VMs/Status', 'flag_global_status/Global Switch/Status', 'flag_jobs_by_target_alias/Jobs by Target Alias/Status', 'status_refresh_interval/Refresh Interval/Status', 'flag_show_slot_detail/Slot Detail/Status', 'flag_show_slot_flavors/Slot Flavors/Status', ], title="Settings", )
apache-2.0
phhusson/Apktool
brut.apktool/apktool-lib/src/main/java/brut/androlib/res/AndrolibResources.java
31692
/** * Copyright 2014 Ryszard Wiśniewski <brut.alll@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package brut.androlib.res; import brut.androlib.AndrolibException; import brut.androlib.ApkOptions; import brut.androlib.err.CantFindFrameworkResException; import brut.androlib.meta.PackageInfo; import brut.androlib.meta.VersionInfo; import brut.androlib.res.data.*; import brut.androlib.res.decoder.*; import brut.androlib.res.decoder.ARSCDecoder.ARSCData; import brut.androlib.res.decoder.ARSCDecoder.FlagsOffset; import brut.directory.ExtFile; import brut.androlib.res.util.ExtMXSerializer; import brut.androlib.res.util.ExtXmlSerializer; import brut.androlib.res.xml.ResValuesXmlSerializable; import brut.androlib.res.xml.ResXmlPatcher; import brut.common.BrutException; import brut.directory.Directory; import brut.directory.DirectoryException; import brut.directory.FileDirectory; import brut.util.Duo; import brut.util.Jar; import brut.util.OS; import brut.util.OSDetection; import org.apache.commons.io.IOUtils; import org.xmlpull.v1.XmlSerializer; import java.io.*; import java.util.*; import java.util.logging.Logger; import java.util.zip.CRC32; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipOutputStream; /** * @author Ryszard Wiśniewski <brut.alll@gmail.com> */ final public class AndrolibResources { public ResTable getResTable(ExtFile apkFile) throws AndrolibException { return getResTable(apkFile, true); } public ResTable getResTable(ExtFile apkFile, boolean loadMainPkg) throws AndrolibException { ResTable resTable = new ResTable(this); if (loadMainPkg) { loadMainPkg(resTable, apkFile); } return resTable; } public ResPackage loadMainPkg(ResTable resTable, ExtFile apkFile) throws AndrolibException { LOGGER.info("Loading resource table..."); ResPackage[] pkgs = getResPackagesFromApk(apkFile, resTable, sKeepBroken); ResPackage pkg = null; switch (pkgs.length) { case 1: pkg = pkgs[0]; break; case 2: if (pkgs[0].getName().equals("android")) { LOGGER.warning("Skipping \"android\" package group"); pkg = pkgs[1]; break; } else if (pkgs[0].getName().equals("com.htc")) { LOGGER.warning("Skipping \"htc\" package group"); pkg = pkgs[1]; break; } default: pkg = selectPkgWithMostResSpecs(pkgs); break; } if (pkg == null) { throw new AndrolibException("arsc files with zero packages or no arsc file found."); } resTable.addPackage(pkg, true); return pkg; } public ResPackage selectPkgWithMostResSpecs(ResPackage[] pkgs) throws AndrolibException { int id = 0; int value = 0; for (ResPackage resPackage : pkgs) { if (resPackage.getResSpecCount() > value && ! resPackage.getName().equalsIgnoreCase("android")) { value = resPackage.getResSpecCount(); id = resPackage.getId(); } } // if id is still 0, we only have one pkgId which is "android" -> 1 return (id == 0) ? pkgs[0] : pkgs[1]; } public ResPackage loadFrameworkPkg(ResTable resTable, int id, String frameTag) throws AndrolibException { File apk = getFrameworkApk(id, frameTag); LOGGER.info("Loading resource table from file: " + apk); mFramework = new ExtFile(apk); ResPackage[] pkgs = getResPackagesFromApk(mFramework, resTable, true); ResPackage pkg; if (pkgs.length > 1) { pkg = selectPkgWithMostResSpecs(pkgs); } else if (pkgs.length == 0) { throw new AndrolibException("Arsc files with zero or multiple packages"); } else { pkg = pkgs[0]; } if (pkg.getId() != id) { throw new AndrolibException("Expected pkg of id: " + String.valueOf(id) + ", got: " + pkg.getId()); } resTable.addPackage(pkg, false); return pkg; } public void decodeManifest(ResTable resTable, ExtFile apkFile, File outDir) throws AndrolibException { Duo<ResFileDecoder, AXmlResourceParser> duo = getManifestFileDecoder(); ResFileDecoder fileDecoder = duo.m1; // Set ResAttrDecoder duo.m2.setAttrDecoder(new ResAttrDecoder()); ResAttrDecoder attrDecoder = duo.m2.getAttrDecoder(); // Fake ResPackage attrDecoder.setCurrentPackage(new ResPackage(resTable, 0, null)); Directory inApk, out; try { inApk = apkFile.getDirectory(); out = new FileDirectory(outDir); LOGGER.info("Decoding AndroidManifest.xml with only framework resources..."); fileDecoder.decodeManifest(inApk, "AndroidManifest.xml", out, "AndroidManifest.xml"); } catch (DirectoryException ex) { throw new AndrolibException(ex); } } public void adjustPackageManifest(ResTable resTable, String filePath) throws AndrolibException { // compare resources.arsc package name to the one present in AndroidManifest ResPackage resPackage = resTable.getCurrentResPackage(); String packageOriginal = resPackage.getName(); mPackageRenamed = resTable.getPackageRenamed(); resTable.setPackageId(resPackage.getId()); resTable.setPackageOriginal(packageOriginal); // 1) Check if packageOriginal === mPackageRenamed // 2) Check if packageOriginal is ignored via IGNORED_PACKAGES // 2a) If its ignored, make sure the mPackageRenamed isn't explicitly allowed if (packageOriginal.equalsIgnoreCase(mPackageRenamed) || (Arrays.asList(IGNORED_PACKAGES).contains(packageOriginal) && ! Arrays.asList(ALLOWED_PACKAGES).contains(mPackageRenamed))) { LOGGER.info("Regular manifest package..."); } else { LOGGER.info("Renamed manifest package found! Replacing " + mPackageRenamed + " with " + packageOriginal); ResXmlPatcher.renameManifestPackage(new File(filePath), packageOriginal); } } public void decodeManifestWithResources(ResTable resTable, ExtFile apkFile, File outDir) throws AndrolibException { Duo<ResFileDecoder, AXmlResourceParser> duo = getResFileDecoder(); ResFileDecoder fileDecoder = duo.m1; ResAttrDecoder attrDecoder = duo.m2.getAttrDecoder(); attrDecoder.setCurrentPackage(resTable.listMainPackages().iterator().next()); Directory inApk, in = null, out; try { inApk = apkFile.getDirectory(); out = new FileDirectory(outDir); LOGGER.info("Decoding AndroidManifest.xml with resources..."); fileDecoder.decodeManifest(inApk, "AndroidManifest.xml", out, "AndroidManifest.xml"); // Remove versionName / versionCode (aapt API 16) if (!resTable.getAnalysisMode()) { // check for a mismatch between resources.arsc package and the package listed in AndroidManifest // also remove the android::versionCode / versionName from manifest for rebuild // this is a required change to prevent aapt warning about conflicting versions // it will be passed as a parameter to aapt like "--min-sdk-version" via apktool.yml adjustPackageManifest(resTable, outDir.getAbsolutePath() + File.separator + "AndroidManifest.xml"); ResXmlPatcher.removeManifestVersions(new File( outDir.getAbsolutePath() + File.separator + "AndroidManifest.xml")); mPackageId = String.valueOf(resTable.getPackageId()); } } catch (DirectoryException ex) { throw new AndrolibException(ex); } } public void decode(ResTable resTable, ExtFile apkFile, File outDir) throws AndrolibException { Duo<ResFileDecoder, AXmlResourceParser> duo = getResFileDecoder(); ResFileDecoder fileDecoder = duo.m1; ResAttrDecoder attrDecoder = duo.m2.getAttrDecoder(); attrDecoder.setCurrentPackage(resTable.listMainPackages().iterator().next()); Directory inApk, in = null, out; try { out = new FileDirectory(outDir); inApk = apkFile.getDirectory(); out = out.createDir("res"); if (inApk.containsDir("res")) { in = inApk.getDir("res"); } if (in == null && inApk.containsDir("r")) { in = inApk.getDir("r"); } if (in == null && inApk.containsDir("R")) { in = inApk.getDir("R"); } } catch (DirectoryException ex) { throw new AndrolibException(ex); } ExtMXSerializer xmlSerializer = getResXmlSerializer(); for (ResPackage pkg : resTable.listMainPackages()) { attrDecoder.setCurrentPackage(pkg); LOGGER.info("Decoding file-resources..."); for (ResResource res : pkg.listFiles()) { fileDecoder.decode(res, in, out); } LOGGER.info("Decoding values */* XMLs..."); for (ResValuesFile valuesFile : pkg.listValuesFiles()) { generateValuesFile(valuesFile, out, xmlSerializer); } generatePublicXml(pkg, out, xmlSerializer); } AndrolibException decodeError = duo.m2.getFirstError(); if (decodeError != null) { throw decodeError; } } public void setSdkInfo(Map<String, String> map) { if (map != null) { mMinSdkVersion = map.get("minSdkVersion"); mTargetSdkVersion = map.get("targetSdkVersion"); mMaxSdkVersion = map.get("maxSdkVersion"); } } public void setVersionInfo(VersionInfo versionInfo) { if (versionInfo != null) { mVersionCode = versionInfo.versionCode; mVersionName = versionInfo.versionName; } } public void setPackageRenamed(PackageInfo packageInfo) { if (packageInfo != null) { mPackageRenamed = packageInfo.renameManifestPackage; } } public void setPackageId(PackageInfo packageInfo) { if (packageInfo != null) { mPackageId = packageInfo.forcedPackageId; } } public void setSharedLibrary(boolean flag) { mSharedLibrary = flag; } public void aaptPackage(File apkFile, File manifest, File resDir, File rawDir, File assetDir, File[] include) throws AndrolibException { boolean customAapt = false; String aaptPath = apkOptions.aaptPath; List<String> cmd = new ArrayList<String>(); // path for aapt binary if (! aaptPath.isEmpty()) { File aaptFile = new File(aaptPath); if (aaptFile.canRead() && aaptFile.exists()) { aaptFile.setExecutable(true); cmd.add(aaptFile.getPath()); customAapt = true; if (apkOptions.verbose) { LOGGER.info(aaptFile.getPath() + " being used as aapt location."); } } else { LOGGER.warning("aapt location could not be found. Defaulting back to default"); try { cmd.add(getAaptBinaryFile().getAbsolutePath()); } catch (BrutException ignored) { cmd.add("aapt"); } } } else { try { cmd.add(getAaptBinaryFile().getAbsolutePath()); } catch (BrutException ignored) { cmd.add("aapt"); } } cmd.add("p"); if (apkOptions.verbose) { // output aapt verbose cmd.add("-v"); } if (apkOptions.updateFiles) { cmd.add("-u"); } if (apkOptions.debugMode) { // inject debuggable="true" into manifest cmd.add("--debug-mode"); } // force package id so that some frameworks build with correct id // disable if user adds own aapt (can't know if they have this feature) if (mPackageId != null && ! customAapt && ! mSharedLibrary) { cmd.add("--forced-package-id"); cmd.add(mPackageId); } if (mSharedLibrary) { cmd.add("--shared-lib"); } if (mMinSdkVersion != null) { cmd.add("--min-sdk-version"); cmd.add(mMinSdkVersion); } if (mTargetSdkVersion != null) { cmd.add("--target-sdk-version"); cmd.add(mTargetSdkVersion); } if (mMaxSdkVersion != null) { cmd.add("--max-sdk-version"); cmd.add(mMaxSdkVersion); // if we have max sdk version, set --max-res-version // so we can ignore anything over that during build. cmd.add("--max-res-version"); cmd.add(mMaxSdkVersion); } if (mPackageRenamed != null) { cmd.add("--rename-manifest-package"); cmd.add(mPackageRenamed); } if (mVersionCode != null) { cmd.add("--version-code"); cmd.add(mVersionCode); } if (mVersionName != null) { cmd.add("--version-name"); cmd.add(mVersionName); } cmd.add("--no-version-vectors"); cmd.add("-F"); cmd.add(apkFile.getAbsolutePath()); if (apkOptions.isFramework) { cmd.add("-x"); } if (apkOptions.doNotCompress != null) { for (String file : apkOptions.doNotCompress) { cmd.add("-0"); cmd.add(file); } } if (!apkOptions.resourcesAreCompressed) { cmd.add("-0"); cmd.add("arsc"); } if (include != null) { for (File file : include) { cmd.add("-I"); cmd.add(file.getPath()); } } if (resDir != null) { cmd.add("-S"); cmd.add(resDir.getAbsolutePath()); } if (manifest != null) { cmd.add("-M"); cmd.add(manifest.getAbsolutePath()); } if (assetDir != null) { cmd.add("-A"); cmd.add(assetDir.getAbsolutePath()); } if (rawDir != null) { cmd.add(rawDir.getAbsolutePath()); } try { OS.exec(cmd.toArray(new String[0])); if (apkOptions.verbose) { LOGGER.info("command ran: "); LOGGER.info(cmd.toString()); } } catch (BrutException ex) { throw new AndrolibException(ex); } } public boolean detectWhetherAppIsFramework(File appDir) throws AndrolibException { File publicXml = new File(appDir, "res/values/public.xml"); if (! publicXml.exists()) { return false; } Iterator<String> it; try { it = IOUtils.lineIterator(new FileReader(new File(appDir, "res/values/public.xml"))); } catch (FileNotFoundException ex) { throw new AndrolibException( "Could not detect whether app is framework one", ex); } it.next(); it.next(); return it.next().contains("0x01"); } public void tagSmaliResIDs(ResTable resTable, File smaliDir) throws AndrolibException { new ResSmaliUpdater().tagResIDs(resTable, smaliDir); } public void updateSmaliResIDs(ResTable resTable, File smaliDir) throws AndrolibException { new ResSmaliUpdater().updateResIDs(resTable, smaliDir); } public Duo<ResFileDecoder, AXmlResourceParser> getResFileDecoder() { ResStreamDecoderContainer decoders = new ResStreamDecoderContainer(); decoders.setDecoder("raw", new ResRawStreamDecoder()); decoders.setDecoder("9patch", new Res9patchStreamDecoder()); AXmlResourceParser axmlParser = new AXmlResourceParser(); axmlParser.setAttrDecoder(new ResAttrDecoder()); decoders.setDecoder("xml", new XmlPullStreamDecoder(axmlParser, getResXmlSerializer())); return new Duo<ResFileDecoder, AXmlResourceParser>(new ResFileDecoder(decoders), axmlParser); } public Duo<ResFileDecoder, AXmlResourceParser> getManifestFileDecoder() { ResStreamDecoderContainer decoders = new ResStreamDecoderContainer(); AXmlResourceParser axmlParser = new AXmlResourceParser(); decoders.setDecoder("xml", new XmlPullStreamDecoder(axmlParser,getResXmlSerializer())); return new Duo<ResFileDecoder, AXmlResourceParser>(new ResFileDecoder(decoders), axmlParser); } public ExtMXSerializer getResXmlSerializer() { ExtMXSerializer serial = new ExtMXSerializer(); serial.setProperty(ExtXmlSerializer.PROPERTY_SERIALIZER_INDENTATION, " "); serial.setProperty(ExtXmlSerializer.PROPERTY_SERIALIZER_LINE_SEPARATOR, System.getProperty("line.separator")); serial.setProperty(ExtXmlSerializer.PROPERTY_DEFAULT_ENCODING, "utf-8"); serial.setDisabledAttrEscape(true); return serial; } private void generateValuesFile(ResValuesFile valuesFile, Directory out, ExtXmlSerializer serial) throws AndrolibException { try { OutputStream outStream = out.getFileOutput(valuesFile.getPath()); serial.setOutput((outStream), null); serial.startDocument(null, null); serial.startTag(null, "resources"); for (ResResource res : valuesFile.listResources()) { if (valuesFile.isSynthesized(res)) { continue; } ((ResValuesXmlSerializable) res.getValue()).serializeToResValuesXml(serial, res); } serial.endTag(null, "resources"); serial.newLine(); serial.endDocument(); serial.flush(); outStream.close(); } catch (IOException | DirectoryException ex) { throw new AndrolibException("Could not generate: " + valuesFile.getPath(), ex); } } private void generatePublicXml(ResPackage pkg, Directory out, XmlSerializer serial) throws AndrolibException { try { OutputStream outStream = out.getFileOutput("values/public.xml"); serial.setOutput(outStream, null); serial.startDocument(null, null); serial.startTag(null, "resources"); for (ResResSpec spec : pkg.listResSpecs()) { serial.startTag(null, "public"); serial.attribute(null, "type", spec.getType().getName()); serial.attribute(null, "name", spec.getName()); serial.attribute(null, "id", String.format("0x%08x", spec.getId().id)); serial.endTag(null, "public"); } serial.endTag(null, "resources"); serial.endDocument(); serial.flush(); outStream.close(); } catch (IOException | DirectoryException ex) { throw new AndrolibException("Could not generate public.xml file", ex); } } private ResPackage[] getResPackagesFromApk(ExtFile apkFile,ResTable resTable, boolean keepBroken) throws AndrolibException { try { Directory dir = apkFile.getDirectory(); BufferedInputStream bfi = new BufferedInputStream(dir.getFileInput("resources.arsc")); try { return ARSCDecoder.decode(bfi, false, keepBroken, resTable).getPackages(); } finally { try { bfi.close(); } catch (IOException ignored) {} } } catch (DirectoryException ex) { throw new AndrolibException("Could not load resources.arsc from file: " + apkFile, ex); } } public File getFrameworkApk(int id, String frameTag) throws AndrolibException { File dir = getFrameworkDir(); File apk; if (frameTag != null) { apk = new File(dir, String.valueOf(id) + '-' + frameTag + ".apk"); if (apk.exists()) { return apk; } } apk = new File(dir, String.valueOf(id) + ".apk"); if (apk.exists()) { return apk; } if (id == 1) { try (InputStream in = AndrolibResources.class.getResourceAsStream("/brut/androlib/android-framework.jar"); OutputStream out = new FileOutputStream(apk)) { IOUtils.copy(in, out); return apk; } catch (IOException ex) { throw new AndrolibException(ex); } } throw new CantFindFrameworkResException(id); } public void emptyFrameworkDirectory() throws AndrolibException { File dir = getFrameworkDir(); File apk; apk = new File(dir, "1.apk"); if (! apk.exists()) { LOGGER.warning("Can't empty framework directory, no file found at: " + apk.getAbsolutePath()); } else { try { if (apk.exists() && dir.listFiles().length > 1 && ! apkOptions.forceDeleteFramework) { LOGGER.warning("More than default framework detected. Please run command with `--force` parameter to wipe framework directory."); } else { for (File file : dir.listFiles()) { if (file.isFile() && file.getName().endsWith(".apk")) { LOGGER.info("Removing " + file.getName() + " framework file..."); file.delete(); } } } } catch (NullPointerException e) { throw new AndrolibException(e); } } } public void installFramework(File frameFile) throws AndrolibException { installFramework(frameFile, apkOptions.frameworkTag); } public void installFramework(File frameFile, String tag) throws AndrolibException { InputStream in = null; ZipOutputStream out = null; try { ZipFile zip = new ZipFile(frameFile); ZipEntry entry = zip.getEntry("resources.arsc"); if (entry == null) { throw new AndrolibException("Can't find resources.arsc file"); } in = zip.getInputStream(entry); byte[] data = IOUtils.toByteArray(in); ARSCData arsc = ARSCDecoder.decode(new ByteArrayInputStream(data), true, true); publicizeResources(data, arsc.getFlagsOffsets()); File outFile = new File(getFrameworkDir(), String.valueOf(arsc .getOnePackage().getId()) + (tag == null ? "" : '-' + tag) + ".apk"); out = new ZipOutputStream(new FileOutputStream(outFile)); out.setMethod(ZipOutputStream.STORED); CRC32 crc = new CRC32(); crc.update(data); entry = new ZipEntry("resources.arsc"); entry.setSize(data.length); entry.setCrc(crc.getValue()); out.putNextEntry(entry); out.write(data); out.closeEntry(); //Write fake AndroidManifest.xml file to support original aapt entry = zip.getEntry("AndroidManifest.xml"); if (entry != null) { in = zip.getInputStream(entry); byte[] manifest = IOUtils.toByteArray(in); CRC32 manifestCrc = new CRC32(); manifestCrc.update(manifest); entry.setSize(manifest.length); entry.setCompressedSize(-1); entry.setCrc(manifestCrc.getValue()); out.putNextEntry(entry); out.write(manifest); out.closeEntry(); } zip.close(); LOGGER.info("Framework installed to: " + outFile); } catch (IOException ex) { throw new AndrolibException(ex); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } } public void publicizeResources(File arscFile) throws AndrolibException { byte[] data = new byte[(int) arscFile.length()]; try(InputStream in = new FileInputStream(arscFile); OutputStream out = new FileOutputStream(arscFile)) { in.read(data); publicizeResources(data); out.write(data); } catch (IOException ex){ throw new AndrolibException(ex); } } public void publicizeResources(byte[] arsc) throws AndrolibException { publicizeResources(arsc, ARSCDecoder.decode(new ByteArrayInputStream(arsc), true, true).getFlagsOffsets()); } public void publicizeResources(byte[] arsc, FlagsOffset[] flagsOffsets) throws AndrolibException { for (FlagsOffset flags : flagsOffsets) { int offset = flags.offset + 3; int end = offset + 4 * flags.count; while (offset < end) { arsc[offset] |= (byte) 0x40; offset += 4; } } } public File getFrameworkDir() throws AndrolibException { if (mFrameworkDirectory != null) { return mFrameworkDirectory; } String path; // if a framework path was specified on the command line, use it if (apkOptions.frameworkFolderLocation != null) { path = apkOptions.frameworkFolderLocation; } else { File parentPath = new File(System.getProperty("user.home")); if (! parentPath.canWrite()) { LOGGER.severe(String.format("WARNING: Could not write to $HOME (%s), using %s instead...", parentPath.getAbsolutePath(), System.getProperty("java.io.tmpdir"))); LOGGER.severe("Please be aware this is a volatile directory and frameworks could go missing, " + "please utilize --frame-path if the default storage directory is unavailable"); parentPath = new File(System.getProperty("java.io.tmpdir")); } if (OSDetection.isMacOSX()) { path = parentPath.getAbsolutePath() + String.format("%1$sLibrary%1$sapktool%1$sframework", File.separatorChar); } else if (OSDetection.isWindows()) { path = parentPath.getAbsolutePath() + String.format("%1$sAppData%1$sLocal%1$sapktool%1$sframework", File.separatorChar); } else { path = parentPath.getAbsolutePath() + String.format("%1$s.local%1$sshare%1$sapktool%1$sframework", File.separatorChar); } } File dir = new File(path); if (dir.getParentFile() != null && dir.getParentFile().isFile()) { LOGGER.severe("Please remove file at " + dir.getParentFile()); System.exit(1); } if (! dir.exists()) { if (! dir.mkdirs()) { if (apkOptions.frameworkFolderLocation != null) { LOGGER.severe("Can't create Framework directory: " + dir); } throw new AndrolibException("Can't create directory: " + dir); } } mFrameworkDirectory = dir; return dir; } /** * Using a prebuilt aapt and forcing its use, allows us to prevent bugs from older aapt's * along with having a finer control over the build procedure. * * Aapt can still be overridden via --aapt/-a on build, but specific features will be disabled * * @url https://github.com/iBotPeaches/platform_frameworks_base * @throws AndrolibException */ public File getAaptBinaryFile() throws AndrolibException { File aaptBinary; try { if (OSDetection.isMacOSX()) { if (OSDetection.is64Bit()) { aaptBinary = Jar.getResourceAsFile("/prebuilt/aapt/macosx/64/aapt"); } else { aaptBinary = Jar.getResourceAsFile("/prebuilt/aapt/macosx/32/aapt"); } } else if (OSDetection.isUnix()) { if (OSDetection.is64Bit()) { aaptBinary = Jar.getResourceAsFile("/prebuilt/aapt/linux/64/aapt"); } else { aaptBinary = Jar.getResourceAsFile("/prebuilt/aapt/linux/32/aapt"); } } else if (OSDetection.isWindows()) { aaptBinary = Jar.getResourceAsFile("/prebuilt/aapt/windows/aapt.exe"); } else { LOGGER.warning("Unknown Operating System: " + OSDetection.returnOS()); return null; } } catch (BrutException ex) { throw new AndrolibException(ex); } if (aaptBinary.setExecutable(true)) { return aaptBinary; } System.err.println("Can't set aapt binary as executable"); throw new AndrolibException("Can't set aapt binary as executable"); } public File getAndroidResourcesFile() throws AndrolibException { try { return Jar.getResourceAsFile("/brut/androlib/android-framework.jar"); } catch (BrutException ex) { throw new AndrolibException(ex); } } public void close() throws IOException { if (mFramework != null) { mFramework.close(); } } public ApkOptions apkOptions; // TODO: dirty static hack. I have to refactor decoding mechanisms. public static boolean sKeepBroken = false; private final static Logger LOGGER = Logger.getLogger(AndrolibResources.class.getName()); private File mFrameworkDirectory = null; private ExtFile mFramework = null; private String mMinSdkVersion = null; private String mMaxSdkVersion = null; private String mTargetSdkVersion = null; private String mVersionCode = null; private String mVersionName = null; private String mPackageRenamed = null; private String mPackageId = null; private boolean mSharedLibrary = false; private final static String[] IGNORED_PACKAGES = new String[] { "android", "com.htc", "miui", "com.lge", "com.lge.internal", "yi", "com.miui.core", "flyme", "air.com.adobe.appentry" }; private final static String[] ALLOWED_PACKAGES = new String[] { "com.miui" }; }
apache-2.0
tautschnig/fshell
fshell2/fql/concepts/trace_automaton.hpp
3040
/* -*- Mode: C++; tab-width: 4 -*- */ /* vi: set ts=4 sw=4 noexpandtab: */ /******************************************************************************* * FShell 2 * Copyright 2009 Michael Tautschnig, tautschnig@forsyte.de * * 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. *******************************************************************************/ #ifndef FSHELL2__FQL__CONCEPTS__TRACE_AUTOMATON_HPP #define FSHELL2__FQL__CONCEPTS__TRACE_AUTOMATON_HPP /*! \file fshell2/fql/concepts/trace_automaton.hpp * \brief TODO * * $Id$ * \author Michael Tautschnig <tautschnig@forsyte.de> * \date Tue Oct 27 20:09:04 CET 2009 */ #include <fshell2/config/config.hpp> #include <fshell2/fql/concepts/target_graph.hpp> #include <map> #include <set> #include <astl/include/nfa_mmap_backedge.h> FSHELL2_NAMESPACE_BEGIN; FSHELL2_FQL_NAMESPACE_BEGIN; /*! \brief TODO */ class Target_Graph_Index { /*! \copydoc doc_self */ typedef Target_Graph_Index Self; public: typedef int char_type; Target_Graph_Index(); void init(target_graph_t const* id_tgg); void clear(); int to_index(target_graph_t const* f); static bool lt(const char_type x, const char_type y) { return x < y; } int id_index() const { return 0; } static const int epsilon = -1; int epsilon_index() const { return epsilon; } int lookup_target_graph(target_graph_t const* f) const; target_graph_t const* lookup_index(int index) const; private: bool m_initialized; int m_next_index; ::std::map< target_graph_t const*, int > m_target_graph_to_int; ::std::map< int, target_graph_t const* > m_int_to_target_graph; /*! \copydoc copy_constructor */ Target_Graph_Index(Self const& rhs); /*! \copydoc assignment_op */ Self& operator=(Self const& rhs); }; typedef ::astl::NFA_mmap_backedge< Target_Graph_Index > trace_automaton_t; typedef trace_automaton_t::state_type ta_state_t; typedef ::std::set< ta_state_t > ta_state_set_t; typedef ::std::map< ta_state_t, ta_state_t > ta_state_map_t; ::std::pair< ta_state_set_t, ta_state_set_t > copy_automaton(trace_automaton_t const& src, trace_automaton_t & dest); void simplify_automaton(trace_automaton_t & aut, bool compact); void compact_state_numbers(trace_automaton_t const& aut, ta_state_map_t & s_map, ta_state_map_t & reverse_s_map, ta_state_set_t & finals); ::std::ostream & print_trace_automaton(trace_automaton_t const& aut, ::std::ostream & os); FSHELL2_FQL_NAMESPACE_END; FSHELL2_NAMESPACE_END; #endif /* FSHELL2__FQL__CONCEPTS__TRACE_AUTOMATON_HPP */
apache-2.0
mcvendrell/alloy
Alloy/alloy.js
4798
/** * Alloy * Copyright (c) 2012 by Appcelerator, Inc. All Rights Reserved. * See LICENSE for more information on licensing. */ var program = require('commander'), logger = require("./logger"), os = require('os'), U = require('./utils'), colors = require("colors"), _ = require("./lib/alloy/underscore")._, pkginfo = require('pkginfo')(module, 'version'), path = require('path'), fs = require('fs'), CONST = require('./common/constants'); // patch to remove the warning in node >=0.8 path.existsSync = fs.existsSync || path.existsSync; // avoid io issues on Windows in nodejs 0.10.X: https://github.com/joyent/node/issues/3584 if (process.env.ALLOY_TESTS && /^win/i.test(os.platform())) { console.error = function(m) { fs.writeSync(2, m); } console.log = console.warn = console.info = function(m) { fs.writeSync(1, m); } } //////////////////////////////////// ////////// MAIN EXECUTION ////////// //////////////////////////////////// // Process command line input program .version(module.exports.version, '-v, --version') .description('Alloy command line') .usage('COMMAND [ARGS] [OPTIONS]') .option('-a, --app <app>', 'Test app folder for running "alloy test"') .option('-A, --apply', 'Applies command changes [extract-i18n]') .option('-b, --noBanner', 'Disable the banner') .option('-c, --config <config>','Pass in compiler configuration') .option('-f, --force','Force the command to execute') .option('-l, --logLevel <logLevel>', 'Log level (default: 3 [DEBUG])') .option('-n, --no-colors','Turn off colors') .option('-o, --outputPath <outputPath>', 'Output path for generated code') .option('-p, --project-dir <project-dir>', 'Titanium project directory') .option('-q, --platform <platform>', 'Target mobile platform [android,ios,mobileweb]') .option('-s, --spec <spec>', 'test spec to use with "alloy test"') .option('-w, --all','require flag for generate styles') .option('-x, --column <column>', 'Column for source map query', 1) .option('-y, --line <line>', 'Line for source map query', 1) .option('-z, --source <source>', 'Source original file for source map query') .option('--widgetname <name>', 'Widget name, used with generate command'); program.command('new'.blue+' <dir>'.white) .description(' create a new alloy project'.grey); program.command('compile'.blue+' [dir]'.white) .description(' compile into titanium source code'.grey); program.command('extract-i18n'.blue+' <language>'.white) .description(' extracts i18n strings from the source code (js and tss files)'.grey); program.command('generate'.blue+' <type> <name>'.white) .description(' generate a new alloy type such as a controller'.grey); program.parse(process.argv); // Setup up logging output Error.stackTraceLimit = Infinity; logger.stripColors = program['colors'] === false; logger.logLevel = program['logLevel'] || logger.TRACE; if(program.config && program.config.indexOf('logLevel')!==-1) { logger.logLevel = -1; } if (!program.noBanner && program.args[0] !== 'info' && (program.config && program.config.indexOf('noBanner')===-1)) { banner(); } if (program.args.length === 0) { var help = program.helpInformation(); help = help.replace('Usage: alloy COMMAND [ARGS] [OPTIONS]','Usage: '+'alloy'.blue+' COMMAND'.white+' [ARGS] [OPTIONS]'.grey); help = logger.stripColors ? colors.stripColors(help) : help; console.log(help); process.exit(0); } if (program.platform && !_.contains(CONST.PLATFORM_FOLDERS_ALLOY, program.platform)) { U.die('Invalid platform "' + program.platform + '" specified, must be [' + CONST.PLATFORM_FOLDERS_ALLOY.join(',') + ']'); } // Validate the given command var command = program.args[0]; if (!_.contains(getCommands(), command)) { U.die('Unknown command: ' + command.red); } // Launch command with given arguments and options (require('./commands/' + command + '/index'))(program.args.slice(1), program); /////////////////////////////// ////////// FUNCTIONS ////////// /////////////////////////////// function banner() { var str = " .__ .__ \n"+ "_____ | | | | ____ ___.__.\n"+ "\\__ \\ | | | | / _ < | |\n"+ " / __ \\| |_| |_( <_> )___ |\n"+ "(____ /____/____/\\____// ____|\n"+ " \\/ \\/"; if (!program.dump) { console.log(logger.stripColors ? str : str.blue); var m = "Alloy " + module.exports.version + " by Appcelerator. The MVC app framework for Titanium.\n".white; console.log(logger.stripColors ? colors.stripColors(m) : m); } } function getCommands() { try { var commandsPath = path.join(__dirname,'commands'); return _.filter(fs.readdirSync(commandsPath), function(file) { return path.existsSync(path.join(commandsPath,file,'index.js')); }); } catch (e) { U.die('Error getting command list', e); } }
apache-2.0
uddhavgautam/dynamic-resourceUpdateCheck
app/src/main/java/edu/ualr/cpsc7398/updatechecker/controller/recyclerviewadapter/ConclusionAdapter.java
4388
package edu.ualr.cpsc7398.updatechecker.controller.recyclerviewadapter; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.text.InputType; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import java.util.Collections; import java.util.List; import edu.ualr.cpsc7398.updatechecker.R; import edu.ualr.cpsc7398.updatechecker.model.UrlDataConclusion; /** * Provide views to RecyclerView with data from mDataSet. */ public class ConclusionAdapter extends RecyclerView.Adapter<ConclusionAdapter.ViewHolder> { private static final String TAG = "ConclusionAdapter"; List<UrlDataConclusion> listUrlDataConclusion = Collections.emptyList(); //if we want to delete/add, we need to update listUrlDataConclusion list Context context; public ConclusionAdapter(List<UrlDataConclusion> listUrlDataConclusion, Context applicationContext) { this.listUrlDataConclusion = listUrlDataConclusion; this.context = applicationContext; } @Override public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) { //I created the viewholder for my custom row View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row_for_conclusion_adapter, viewGroup, false); ViewHolder holder = new ViewHolder(v); return holder; } @Override public void onBindViewHolder(ViewHolder viewHolder, final int position) { // Log.d(TAG, "Element " + position + " set."); switch (position) { case 0: viewHolder.getEditText1().setRawInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE); break; default: viewHolder.getEditText1().setRawInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE); } viewHolder.getEditText1().setText(listUrlDataConclusion.get(position).getValue()); } @Override public void onAttachedToRecyclerView(RecyclerView recyclerView) { super.onAttachedToRecyclerView(recyclerView); } // Insert a new item to the RecyclerView on a predefined position public void insert(int position, UrlDataConclusion data) { listUrlDataConclusion.add(position, data); notifyItemInserted(listUrlDataConclusion.size() - 1); // notifyItemInserted(position); } public void update(int position, UrlDataConclusion data) { listUrlDataConclusion.remove(position); notifyItemRemoved(position); insert(position, data); } public void updateOnlyValue(int position, UrlDataConclusion data) { listUrlDataConclusion.add(position, data); notifyItemChanged(position, data); listUrlDataConclusion.remove(listUrlDataConclusion.size() - 1); notifyItemRemoved(listUrlDataConclusion.size() - 1); } //get item from predefined position public UrlDataConclusion getItemFromPredefinedPosition(int position) { return listUrlDataConclusion.get(position); } //remove all public void removeAll() { for (int i = 0; i < listUrlDataConclusion.size() - 1; i++) { listUrlDataConclusion.remove(i); notifyItemRemoved(i); } } // Remove a RecyclerView item containing a specified Data object public void remove(UrlDataConclusion data) { int position = listUrlDataConclusion.indexOf(data); listUrlDataConclusion.remove(position); notifyItemRemoved(position); } @Override public int getItemCount() { return listUrlDataConclusion.size(); } public static class ViewHolder extends RecyclerView.ViewHolder { //can be as separate class private EditText editText1; public ViewHolder(View v) { super(v); // Define click listener for the ViewHolder's View. v.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.d(TAG, "Element " + getAdapterPosition() + " clicked."); } }); editText1 = (EditText) v.findViewById(R.id.rowRecyclerViewConclusionLayoutEditText); } public EditText getEditText1() { return editText1; } } }
apache-2.0
google-code-export/google-api-dfp-java
src/com/google/api/ads/dfp/v201306/BaseRate.java
9708
/** * BaseRate.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter. */ package com.google.api.ads.dfp.v201306; /** * A base rate that applies to a product template or product belonging * to rate * card. */ public abstract class BaseRate implements java.io.Serializable { /* The ID of the {@link RateCard} object to which this base rate * belongs. * * This attribute is required and cannot be changed after * creation. */ private java.lang.Long rateCardId; /* Uniquely identifies the {@code BaseRate} object. * * This attribute is read-only and is assigned by Google * when a base rate is * created. */ private java.lang.Long id; /* The status of the {@code BaseRate}. This attribute is read-only * and is * assigned by Google. */ private com.google.api.ads.dfp.v201306.BaseRateStatus status; /* Indicates that this instance is a subtype of BaseRate. * Although this field is returned in the response, it * is ignored on input * and cannot be selected. Specify xsi:type instead. */ private java.lang.String baseRateType; public BaseRate() { } public BaseRate( java.lang.Long rateCardId, java.lang.Long id, com.google.api.ads.dfp.v201306.BaseRateStatus status, java.lang.String baseRateType) { this.rateCardId = rateCardId; this.id = id; this.status = status; this.baseRateType = baseRateType; } /** * Gets the rateCardId value for this BaseRate. * * @return rateCardId * The ID of the {@link RateCard} object to which this base rate * belongs. * * This attribute is required and cannot be changed after * creation. */ public java.lang.Long getRateCardId() { return rateCardId; } /** * Sets the rateCardId value for this BaseRate. * * @param rateCardId * The ID of the {@link RateCard} object to which this base rate * belongs. * * This attribute is required and cannot be changed after * creation. */ public void setRateCardId(java.lang.Long rateCardId) { this.rateCardId = rateCardId; } /** * Gets the id value for this BaseRate. * * @return id * Uniquely identifies the {@code BaseRate} object. * * This attribute is read-only and is assigned by Google * when a base rate is * created. */ public java.lang.Long getId() { return id; } /** * Sets the id value for this BaseRate. * * @param id * Uniquely identifies the {@code BaseRate} object. * * This attribute is read-only and is assigned by Google * when a base rate is * created. */ public void setId(java.lang.Long id) { this.id = id; } /** * Gets the status value for this BaseRate. * * @return status * The status of the {@code BaseRate}. This attribute is read-only * and is * assigned by Google. */ public com.google.api.ads.dfp.v201306.BaseRateStatus getStatus() { return status; } /** * Sets the status value for this BaseRate. * * @param status * The status of the {@code BaseRate}. This attribute is read-only * and is * assigned by Google. */ public void setStatus(com.google.api.ads.dfp.v201306.BaseRateStatus status) { this.status = status; } /** * Gets the baseRateType value for this BaseRate. * * @return baseRateType * Indicates that this instance is a subtype of BaseRate. * Although this field is returned in the response, it * is ignored on input * and cannot be selected. Specify xsi:type instead. */ public java.lang.String getBaseRateType() { return baseRateType; } /** * Sets the baseRateType value for this BaseRate. * * @param baseRateType * Indicates that this instance is a subtype of BaseRate. * Although this field is returned in the response, it * is ignored on input * and cannot be selected. Specify xsi:type instead. */ public void setBaseRateType(java.lang.String baseRateType) { this.baseRateType = baseRateType; } private java.lang.Object __equalsCalc = null; public synchronized boolean equals(java.lang.Object obj) { if (!(obj instanceof BaseRate)) return false; BaseRate other = (BaseRate) obj; if (obj == null) return false; if (this == obj) return true; if (__equalsCalc != null) { return (__equalsCalc == obj); } __equalsCalc = obj; boolean _equals; _equals = true && ((this.rateCardId==null && other.getRateCardId()==null) || (this.rateCardId!=null && this.rateCardId.equals(other.getRateCardId()))) && ((this.id==null && other.getId()==null) || (this.id!=null && this.id.equals(other.getId()))) && ((this.status==null && other.getStatus()==null) || (this.status!=null && this.status.equals(other.getStatus()))) && ((this.baseRateType==null && other.getBaseRateType()==null) || (this.baseRateType!=null && this.baseRateType.equals(other.getBaseRateType()))); __equalsCalc = null; return _equals; } private boolean __hashCodeCalc = false; public synchronized int hashCode() { if (__hashCodeCalc) { return 0; } __hashCodeCalc = true; int _hashCode = 1; if (getRateCardId() != null) { _hashCode += getRateCardId().hashCode(); } if (getId() != null) { _hashCode += getId().hashCode(); } if (getStatus() != null) { _hashCode += getStatus().hashCode(); } if (getBaseRateType() != null) { _hashCode += getBaseRateType().hashCode(); } __hashCodeCalc = false; return _hashCode; } // Type metadata private static org.apache.axis.description.TypeDesc typeDesc = new org.apache.axis.description.TypeDesc(BaseRate.class, true); static { typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201306", "BaseRate")); org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("rateCardId"); elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201306", "rateCardId")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "long")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("id"); elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201306", "id")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "long")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("status"); elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201306", "status")); elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201306", "BaseRateStatus")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("baseRateType"); elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201306", "BaseRate.Type")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string")); 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); } }
apache-2.0
skunkiferous/Hacktors
src/com/blockwithme/hacktors/Level.java
7994
/* * Copyright (C) 2013 Sebastien Diot. * * 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.blockwithme.hacktors; import javax.annotation.ParametersAreNonnullByDefault; import lombok.Data; /** * Represents a game level/floor. * * Almost all the game state is stored in levels. * To limit memory and CPU usage, levels are broken in chunks, * which are lazily loaded, and generated at runtime on demand. * * @author monster */ @ParametersAreNonnullByDefault @Data public class Level { /** Size in X axis. */ public static final int X = 16; /** Size in Y axis. */ public static final int Y = 16; /** Size in total. */ public static final int SIZE = X * Y; /** The level position */ private final Position position = new Position(); /** The chunk Generator. */ private final Generator generator; /** All the chunks. */ private final Chunk[] chunks = new Chunk[SIZE]; /** Number of mobiles contained. */ private int mobileCount; /** Checks that the index are valid. */ private void check(final int x, final int y) { if ((x < 0) || (x >= X)) { throw new IllegalArgumentException("x must be withing [0," + X + "]"); } if ((y < 0) || (y >= Y)) { throw new IllegalArgumentException("y must be withing [0," + Y + "]"); } } /** computes the linear array index in blocks, from the coordinates. */ private int index(final int x, final int y) { check(x, y); return x + X * y; } /** Returns the number of mobiles contained. */ public int getMobileCount() { return mobileCount; } /** Updates the mobile count. */ public void updateMobileCount(final int change) { if (change != 0) { mobileCount += change; final World world = position.getWorld(); if (world != null) { world.updateMobileCount(change); } } } /** Returns a Chunk, using chunk position. */ public Chunk getChunk(final int x, final int y) { return chunks[index(x, y)]; } /** Returns a Chunk, using global position. */ public Chunk getChunkOf(final int x, final int y) { return getChunk(x / Chunk.X, y / Chunk.Y); } /** Returns a Chunk, using chunk position. Creates it if needed. */ public Chunk getOrCreateChunk(final int x, final int y) { final int index = index(x, y); Chunk result = chunks[index]; if (result == null) { result = new Chunk(); setChunk(x, y, result); generator.fill(result); } return result; } /** Returns a Chunk, using global position. Creates it if needed. */ public Chunk getOrCreateChunkOf(final int x, final int y) { return getOrCreateChunk(x / Chunk.X, y / Chunk.Y); } /** Updates the Chunk position! */ private void updateChunkPosition(final int x, final int y, final Chunk chunk) { final Position pos = chunk.getPosition(); final World oldWorld = pos.getWorld(); if (oldWorld != null) { final Level oldLevel = oldWorld.getLevel(pos.getZ()); if (oldLevel != null) { final Chunk other = oldLevel.getChunkOf(pos.getX(), pos.getY()); if (other == chunk) { oldLevel.setChunkOf(pos.getX(), pos.getY(), null); } } } pos.setX(x * X); pos.setY(y * Y); pos.setZ(position.getZ()); pos.setWorld(position.getWorld()); chunk.updatedPosition(); } /** Sets a chunk, using chunk position. */ public void setChunk(final int x, final int y, final Chunk chunk) { final int index = index(x, y); final Chunk before = chunks[index]; if (before != chunk) { chunks[index] = chunk; if (before != null) { // Detach old chunk before.getPosition().setWorld(null); before.updatedPosition(); } if (chunk != null) { updateChunkPosition(x, y, chunk); } if (before != null) { updateMobileCount(-before.getMobileCount()); } if (chunk != null) { updateMobileCount(chunk.getMobileCount()); } } } /** Sets a chunk, using global position. */ public void setChunkOf(final int x, final int y, final Chunk chunk) { setChunk(x / Chunk.X, y / Chunk.Y, chunk); } /** Informs the Mobile that it's position was updated. */ public void updatedPosition() { for (int x = 0; x < X; x++) { for (int y = 0; y < Y; y++) { final Chunk chunk = getChunk(x, y); if (chunk != null) { updateChunkPosition(x, y, chunk); } } } } /** Handles missile firing. */ public void handleMissile(final Item missile, final int startX, final int startY, final Direction direction) { int range = missile.getType().getRange(); Position pos = position.clone(); pos.setX(startX); pos.setY(startY); pos.setDirection(direction); Position next = pos.next(); final World world = pos.getWorld(); final boolean egg = (missile.getType().getCategory() == ItemCategory.Egg); while (world.isValid(next) && (range > 0)) { final int x = next.getX(); final int y = next.getY(); final Chunk chunk = getOrCreateChunkOf(x, y); if (chunk.occupied(x, y)) { final Mobile mobile = chunk.getMobile(x, y); if ((mobile != null) && !egg) { mobile.hitBy(missile); return; } else { // Solid block or egg ... break; } } else { range--; pos = next; next = pos.next(); } } // We should not be on a solid block. final Mobile mobile = missile.getType().spawn(); final int x = pos.getX(); final int y = pos.getY(); if (mobile == null) { if (!missile.use()) { final Chunk chunk = getOrCreateChunkOf(x, y); chunk.addItem(x, y, missile); } } else { final Chunk chunk = getOrCreateChunkOf(x, y); chunk.setMobile(x, y, mobile); } } /** Runs an update cycle. */ public void update() { if (mobileCount > 0) { for (final Chunk chunk : chunks) { if (chunk != null) { chunk.update(); } } } } /** Passes all mobiles to the visitor. */ public void visitMobiles(final MobileVisitor visitor) { if (mobileCount > 0) { for (final Chunk chunk : chunks) { if (chunk != null) { chunk.visitMobiles(visitor); } } } } }
apache-2.0
optivo-org/commons-dbcp
src/java/org/apache/commons/dbcp/DriverManagerConnectionFactory.java
3269
/* * 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.commons.dbcp; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; /** * A {@link DriverManager}-based implementation of {@link ConnectionFactory}. * * @author Rodney Waldhoff * @author Ignacio J. Ortega * @author Dirk Verbeeck * @version $Revision: 746827 $ $Date: 2009-02-22 22:41:52 +0100 (So, 22 Feb 2009) $ */ public class DriverManagerConnectionFactory implements ConnectionFactory { static { // Related to DBCP-212 // Driver manager does not sync loading of drivers that use the service // provider interface. This will cause issues is multi-threaded // environments. This hack makes sure the drivers are loaded before // DBCP tries to use them. DriverManager.getDrivers(); } /** * Constructor for DriverManagerConnectionFactory. * @param connectUri a database url of the form * <code> jdbc:<em>subprotocol</em>:<em>subname</em></code> * @param props a list of arbitrary string tag/value pairs as * connection arguments; normally at least a "user" and "password" * property should be included. */ public DriverManagerConnectionFactory(String connectUri, Properties props) { _connectUri = connectUri; _props = props; } /** * Constructor for DriverManagerConnectionFactory. * @param connectUri a database url of the form * <code>jdbc:<em>subprotocol</em>:<em>subname</em></code> * @param uname the database user * @param passwd the user's password */ public DriverManagerConnectionFactory(String connectUri, String uname, String passwd) { _connectUri = connectUri; _uname = uname; _passwd = passwd; } public Connection createConnection() throws SQLException { if(null == _props) { if((_uname == null) && (_passwd == null)) { return DriverManager.getConnection(_connectUri); } else { return DriverManager.getConnection(_connectUri,_uname,_passwd); } } else { return DriverManager.getConnection(_connectUri,_props); } } protected String _connectUri = null; protected String _uname = null; protected String _passwd = null; protected Properties _props = null; }
apache-2.0
mpushpav/chorus
spec/javascripts/models/dataset_filter_maps_spec.js
13627
describe("chorus.models.DatasetFilterMaps", function() { function itReturnsTheRightClauseFor(key, columnName, inputValue, expected, ignoreEmptyCase) { it("returns the right clause for " + key, function() { expect(this.datasetFilterMap.comparators[key].generate(columnName, inputValue)).toBe(expected); }); if(!ignoreEmptyCase) { it("returns an empty string when input is empty for " + key, function() { expect(this.datasetFilterMap.comparators[key].generate(columnName, "")).toBe(""); }); } } describe("String", function() { beforeEach(function() { this.datasetFilterMap = new chorus.models.DatasetFilterMaps.String(); }); itReturnsTheRightClauseFor("equal", "column_name", "some_v'alue", "column_name = 'some_v''alue'"); itReturnsTheRightClauseFor("not_equal", "column_name", "some_value", "column_name != 'some_value'"); itReturnsTheRightClauseFor("like", "column_name", "some_value", "column_name LIKE 'some_value'"); itReturnsTheRightClauseFor("begin_with", "column_name", "some_value", "column_name LIKE 'some_value%'"); itReturnsTheRightClauseFor("end_with", "column_name", "some_value", "column_name LIKE '%some_value'"); itReturnsTheRightClauseFor("alpha_after", "column_name", "some_value", "column_name > 'some_value'"); itReturnsTheRightClauseFor("alpha_after_equal", "column_name", "some_value", "column_name >= 'some_value'"); itReturnsTheRightClauseFor("alpha_before", "column_name", "some_value", "column_name < 'some_value'"); itReturnsTheRightClauseFor("alpha_before_equal", "column_name", "some_value", "column_name <= 'some_value'"); itReturnsTheRightClauseFor("not_null", "column_name", "some_value", "column_name IS NOT NULL", true); itReturnsTheRightClauseFor("null", "column_name", "some_value", "column_name IS NULL", true); it("marks all strings as valid", function() { expect(this.datasetFilterMap.performValidation({ value: "" })).toBeTruthy(); expect(this.datasetFilterMap.performValidation({ value: "2342gegrerger*(&^%" })).toBeTruthy(); expect(this.datasetFilterMap.performValidation({ value: "';DROP TABLE users;--" })).toBeTruthy(); expect(this.datasetFilterMap.performValidation({ value: "\n \t" })).toBeTruthy(); }); }); describe("Boolean", function() { beforeEach(function() { this.datasetFilterMap = new chorus.models.DatasetFilterMaps.Boolean(); }); itReturnsTheRightClauseFor("true", "column_name", "some_value", "column_name = TRUE", true); itReturnsTheRightClauseFor("false", "column_name", "some_value", "column_name = FALSE", true); itReturnsTheRightClauseFor("not_null", "column_name", "some_value", "column_name IS NOT NULL", true); itReturnsTheRightClauseFor("null", "column_name", "some_value", "column_name IS NULL", true); }); describe("Numeric", function() { beforeEach(function() { this.datasetFilterMap = new chorus.models.DatasetFilterMaps.Numeric(); }); itReturnsTheRightClauseFor("equal", "column_name", "some_value", "column_name = 'some_value'"); itReturnsTheRightClauseFor("not_equal", "column_name", "some_value", "column_name != 'some_value'"); itReturnsTheRightClauseFor("greater", "column_name", "some_value", "column_name > 'some_value'"); itReturnsTheRightClauseFor("greater_equal", "column_name", "some_value", "column_name >= 'some_value'"); itReturnsTheRightClauseFor("less", "column_name", "some_value", "column_name < 'some_value'"); itReturnsTheRightClauseFor("less_equal", "column_name", "some_value", "column_name <= 'some_value'"); itReturnsTheRightClauseFor("not_null", "column_name", "some_value", "column_name IS NOT NULL", true); itReturnsTheRightClauseFor("null", "column_name", "some_value", "column_name IS NULL", true); it("marks whole numbers as valid", function() { expect(this.datasetFilterMap.performValidation({ value: "1234" })).toBeTruthy(); }); it("marks floating comma numbers as valid", function() { expect(this.datasetFilterMap.performValidation({ value: "4,5" })).toBeTruthy(); }); it("marks floating point numbers as valid", function() { expect(this.datasetFilterMap.performValidation({ value: "4.5" })).toBeTruthy(); }); it("marks non-numerical strings as invalid", function() { expect(this.datasetFilterMap.performValidation({ value: "I'm the string" })).toBeFalsy(); }); it("marks negative numbers as valid", function() { expect(this.datasetFilterMap.performValidation({ value: "-1" })).toBeTruthy(); }); it("marks numbers with lots of dashes as invalid", function() { expect(this.datasetFilterMap.performValidation({ value: "--1" })).toBeFalsy(); expect(this.datasetFilterMap.performValidation({ value: "-1-" })).toBeFalsy(); expect(this.datasetFilterMap.performValidation({ value: "-" })).toBeFalsy(); expect(this.datasetFilterMap.performValidation({ value: "-1,2,.-" })).toBeFalsy(); expect(this.datasetFilterMap.performValidation({ value: "1-" })).toBeFalsy(); }); it("marks the empty field valid", function() { expect(this.datasetFilterMap.performValidation({ value: "" })).toBeTruthy(); }); }); describe("Other", function() { beforeEach(function() { this.datasetFilterMap = new chorus.models.DatasetFilterMaps.Other(); }); itReturnsTheRightClauseFor("equal", "column_name", "some_value", "column_name = 'some_value'"); itReturnsTheRightClauseFor("not_equal", "column_name", "some_value", "column_name != 'some_value'"); itReturnsTheRightClauseFor("greater", "column_name", "some_value", "column_name > 'some_value'"); itReturnsTheRightClauseFor("greater_equal", "column_name", "some_value", "column_name >= 'some_value'"); itReturnsTheRightClauseFor("less", "column_name", "some_value", "column_name < 'some_value'"); itReturnsTheRightClauseFor("less_equal", "column_name", "some_value", "column_name <= 'some_value'"); itReturnsTheRightClauseFor("not_null", "column_name", "some_value", "column_name IS NOT NULL", true); itReturnsTheRightClauseFor("null", "column_name", "some_value", "column_name IS NULL", true); it("marks whole numbers as valid", function() { expect(this.datasetFilterMap.performValidation({ value: "1234" })).toBeTruthy(); }); it("marks floating comma numbers as valid", function() { expect(this.datasetFilterMap.performValidation({ value: "4,5" })).toBeTruthy(); }); it("marks floating point numbers as valid", function() { expect(this.datasetFilterMap.performValidation({ value: "4.5" })).toBeTruthy(); }); it("marks non-numerical strings as valid", function() { expect(this.datasetFilterMap.performValidation({ value: "I'm the string" })).toBeTruthy(); }); it("marks negative numbers as valid", function() { expect(this.datasetFilterMap.performValidation({ value: "-1" })).toBeTruthy(); }); it("marks the empty field valid", function() { expect(this.datasetFilterMap.performValidation({ value: "" })).toBeTruthy(); }); it("marks all kinds of random strings as valid", function() { expect(this.datasetFilterMap.performValidation({ value: "#$%^&*(HGgfhweg" })).toBeTruthy(); }); }); describe("Timestamp", function() { beforeEach(function() { this.datasetFilterMap = new chorus.models.DatasetFilterMaps.Timestamp(); }); itReturnsTheRightClauseFor("equal", "column_name", "some_value", "column_name = 'some_value'"); itReturnsTheRightClauseFor("not_equal", "column_name", "some_value", "column_name != 'some_value'"); itReturnsTheRightClauseFor("greater", "column_name", "some_value", "column_name > 'some_value'"); itReturnsTheRightClauseFor("greater_equal", "column_name", "some_value", "column_name >= 'some_value'"); itReturnsTheRightClauseFor("less", "column_name", "some_value", "column_name < 'some_value'"); itReturnsTheRightClauseFor("less_equal", "column_name", "some_value", "column_name <= 'some_value'"); itReturnsTheRightClauseFor("not_null", "column_name", "some_value", "column_name IS NOT NULL", true); itReturnsTheRightClauseFor("null", "column_name", "some_value", "column_name IS NULL", true); it("marks all values as valid", function() { expect(this.datasetFilterMap.performValidation({ value: "" })).toBeTruthy(); expect(this.datasetFilterMap.performValidation({ value: "2342gegrerger*(&^%" })).toBeTruthy(); expect(this.datasetFilterMap.performValidation({ value: "';DROP TABLE users;--" })).toBeTruthy(); expect(this.datasetFilterMap.performValidation({ value: "\n \t" })).toBeTruthy(); }); }); describe("Time", function() { beforeEach(function() { this.datasetFilterMap = new chorus.models.DatasetFilterMaps.Time(); }); itReturnsTheRightClauseFor("equal", "column_name", "some_value", "column_name = 'some_value'"); itReturnsTheRightClauseFor("before", "column_name", "some_value", "column_name < 'some_value'"); itReturnsTheRightClauseFor("after", "column_name", "some_value", "column_name > 'some_value'"); itReturnsTheRightClauseFor("not_null", "column_name", "some_value", "column_name IS NOT NULL", true); itReturnsTheRightClauseFor("null", "column_name", "some_value", "column_name IS NULL", true); it("marks times as valid", function() { expect(this.datasetFilterMap.performValidation({ value: "13:37" })).toBeTruthy(); expect(this.datasetFilterMap.performValidation({ value: "13:13:37" })).toBeTruthy(); }); it("marks anything but times as invalid", function() { expect(this.datasetFilterMap.performValidation({ value: "4,5" })).toBeFalsy(); expect(this.datasetFilterMap.performValidation({ value: "Greetings" })).toBeFalsy(); expect(this.datasetFilterMap.performValidation({ value: "www.google.com" })).toBeFalsy(); expect(this.datasetFilterMap.performValidation({ value: "13.45" })).toBeFalsy(); expect(this.datasetFilterMap.performValidation({ value: "12am" })).toBeFalsy(); }); it("marks the empty field valid", function() { expect(this.datasetFilterMap.performValidation({ value: "" })).toBeTruthy(); }); }); describe("Date", function() { beforeEach(function() { this.datasetFilterMap = new chorus.models.DatasetFilterMaps.Date(); }); itReturnsTheRightClauseFor("on", "column_name", "some_value", "column_name = 'some_value'"); itReturnsTheRightClauseFor("before", "column_name", "some_value", "column_name < 'some_value'"); itReturnsTheRightClauseFor("after", "column_name", "some_value", "column_name > 'some_value'"); itReturnsTheRightClauseFor("not_null", "column_name", "some_value", "column_name IS NOT NULL", true); itReturnsTheRightClauseFor("null", "column_name", "some_value", "column_name IS NULL", true); it("marks dates as valid", function() { expect(this.datasetFilterMap.performValidation({ month: "02", day: "14", year: "2012" })).toBeTruthy(); }); it("marks anything else as invalid", function() { expect(this.datasetFilterMap.performValidation({ month: "hi", day: "14", year: "2012" })).toBeFalsy(); expect(this.datasetFilterMap.performValidation({ month: "1", day: "&^", year: "2012" })).toBeFalsy(); expect(this.datasetFilterMap.performValidation({ month: "1", day: "31", year: "google" })).toBeFalsy(); }); it("has the right error messages", function() { this.datasetFilterMap.performValidation({ month: "hi", day: "14", year: "2012" }); expect(this.datasetFilterMap.errors.month).toMatchTranslation("dataset.filter.month_required"); expect(this.datasetFilterMap.performValidation({ month: "1", day: "&^", year: "2012" })).toBeFalsy(); expect(this.datasetFilterMap.errors.day).toMatchTranslation("dataset.filter.day_required"); expect(this.datasetFilterMap.performValidation({ month: "1", day: "31", year: "google" })).toBeFalsy(); expect(this.datasetFilterMap.errors.year).toMatchTranslation("dataset.filter.year_required"); }); it("is not valid if there are empty and non-empty parts", function() { expect(this.datasetFilterMap.performValidation({ month: "", day: "14", year: "2012" })).toBeFalsy(); expect(this.datasetFilterMap.performValidation({ month: "5", day: "", year: "2012" })).toBeFalsy(); expect(this.datasetFilterMap.performValidation({ month: "5", day: "14", year: "" })).toBeFalsy(); }); it("is valid when all fields are empty", function() { expect(this.datasetFilterMap.performValidation({ month: "", day: "", year: "" })).toBeTruthy(); }); }); });
apache-2.0
EMBL-EBI-SUBS/subs
subs-repository/src/main/java/uk/ac/ebi/subs/repository/repos/status/ProcessingStatusBulkOperations.java
2260
package uk.ac.ebi.subs.repository.repos.status; import com.mongodb.BulkWriteResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.mongodb.core.BulkOperations; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Update; import org.springframework.stereotype.Component; import uk.ac.ebi.subs.data.Submission; import uk.ac.ebi.subs.data.status.ProcessingStatusEnum; import uk.ac.ebi.subs.data.submittable.Submittable; import uk.ac.ebi.subs.repository.model.ProcessingStatus; import java.util.Collection; import java.util.stream.Stream; import static org.springframework.data.mongodb.core.query.Criteria.where; import static org.springframework.data.mongodb.core.query.Query.query; import static org.springframework.data.mongodb.core.query.Update.update; /** * Created by davidr on 26/06/2017. */ @Component public class ProcessingStatusBulkOperations { private final Logger logger = LoggerFactory.getLogger(this.getClass()); private MongoTemplate mongoTemplate; public ProcessingStatusBulkOperations(MongoTemplate mongoTemplate) { this.mongoTemplate = mongoTemplate; } public void updateProcessingStatus(Collection<String> statusesToApplyTo, Stream<Submittable> submittables, Submission submission, ProcessingStatusEnum processingStatusEnum) { BulkOperations ops = mongoTemplate.bulkOps(BulkOperations.BulkMode.UNORDERED, ProcessingStatus.class); Update update = update("status", processingStatusEnum.name()); submittables .map(submittable -> query( where("submissionId").is(submission.getId()) .and("submittableId").is(submittable.getId()) .and("status").in(statusesToApplyTo) )) .forEach(query -> ops.updateOne(query, update) ); BulkWriteResult writeResult = ops.execute(); logger.info("Setting processing status to {} for certs for {} items in submission {}", processingStatusEnum, writeResult.getModifiedCount(), submission.getId() ); } }
apache-2.0
wfuedu/Inotado
inotado-api/api/src/java/edu/wfu/inotado/api/WinProfileRequest.java
1992
/*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 edu.wfu.inotado.api; import java.util.ArrayList; import java.util.List; /** * This is an object to hold properties * * @author zhuy * */ public class WinProfileRequest { private String webServiceUrl; private String remotePhotoLocation; private String requesterUserId; private String requesterUserType; private List<String> winUsers = new ArrayList<String>(); public String getWebServiceUrl() { return webServiceUrl; } public void setWebServiceUrl(String webServiceUrl) { this.webServiceUrl = webServiceUrl; } public String getRequesterUserId() { return requesterUserId; } public void setRequesterUserId(String requesterUserId) { this.requesterUserId = requesterUserId; } public String getRequesterUserType() { return requesterUserType; } public void setRequesterUserType(String requesterUserType) { this.requesterUserType = requesterUserType; } public List<String> getWinUsers() { return winUsers; } public void setWinUsers(List<String> users) { this.winUsers = users; } public String getRemotePhotoLocation() { return remotePhotoLocation; } public void setRemotePhotoLocation(String remotePhotoLocation) { this.remotePhotoLocation = remotePhotoLocation; } }
apache-2.0
srinivasiyerb/Scholst
target/Scholastic/static/js/ext/src/widgets/grid/PivotGrid.js
13425
/*! * Ext JS Library 3.3.1 * Copyright(c) 2006-2010 Sencha Inc. * licensing@sencha.com * http://www.sencha.com/license */ /** * @class Ext.grid.PivotGrid * @extends Ext.grid.GridPanel * <p>The PivotGrid component enables rapid summarization of large data sets. It provides a way to reduce a large set of * data down into a format where trends and insights become more apparent. A classic example is in sales data; a company * will often have a record of all sales it makes for a given period - this will often encompass thousands of rows of * data. The PivotGrid allows you to see how well each salesperson performed, which cities generate the most revenue, * how products perform between cities and so on.</p> * <p>A PivotGrid is composed of two axes (left and top), one {@link #measure} and one {@link #aggregator aggregation} * function. Each axis can contain one or more {@link #dimension}, which are ordered into a hierarchy. Dimensions on the * left axis can also specify a width. Each dimension in each axis can specify its sort ordering, defaulting to "ASC", * and must specify one of the fields in the {@link Ext.data.Record Record} used by the PivotGrid's * {@link Ext.data.Store Store}.</p> <pre><code> // This is the record representing a single sale var SaleRecord = Ext.data.Record.create([ {name: 'person', type: 'string'}, {name: 'product', type: 'string'}, {name: 'city', type: 'string'}, {name: 'state', type: 'string'}, {name: 'year', type: 'int'}, {name: 'value', type: 'int'} ]); // A simple store that loads SaleRecord data from a url var myStore = new Ext.data.Store({ url: 'data.json', autoLoad: true, reader: new Ext.data.JsonReader({ root: 'rows', idProperty: 'id' }, SaleRecord) }); // Create the PivotGrid itself, referencing the store var pivot = new Ext.grid.PivotGrid({ store : myStore, aggregator: 'sum', measure : 'value', leftAxis: [ { width: 60, dataIndex: 'product' }, { width: 120, dataIndex: 'person', direction: 'DESC' } ], topAxis: [ { dataIndex: 'year' } ] }); </code></pre> * <p>The specified {@link #measure} is the field from SaleRecord that is extracted from each combination * of product and person (on the left axis) and year on the top axis. There may be several SaleRecords in the * data set that share this combination, so an array of measure fields is produced. This array is then * aggregated using the {@link #aggregator} function.</p> * <p>The default aggregator function is sum, which simply adds up all of the extracted measure values. Other * built-in aggregator functions are count, avg, min and max. In addition, you can specify your own function. * In this example we show the code used to sum the measures, but you can return any value you like. See * {@link #aggregator} for more details.</p> <pre><code> new Ext.grid.PivotGrid({ aggregator: function(records, measure) { var length = records.length, total = 0, i; for (i = 0; i < length; i++) { total += records[i].get(measure); } return total; }, renderer: function(value) { return Math.round(value); }, //your normal config here }); </code></pre> * <p><u>Renderers</u></p> * <p>PivotGrid optionally accepts a {@link #renderer} function which can modify the data in each cell before it * is rendered. The renderer is passed the value that would usually be placed in the cell and is expected to return * the new value. For example let's imagine we had height data expressed as a decimal - here's how we might use a * renderer to display the data in feet and inches notation:</p> <pre><code> new Ext.grid.PivotGrid({ //in each case the value is a decimal number of feet renderer : function(value) { var feet = Math.floor(value), inches = Math.round((value - feet) * 12); return String.format("{0}' {1}\"", feet, inches); }, //normal config here }); </code></pre> * <p><u>Reconfiguring</u></p> * <p>All aspects PivotGrid's configuration can be updated at runtime. It is easy to change the {@link #setMeasure measure}, * {@link #setAggregator aggregation function}, {@link #setLeftAxis left} and {@link #setTopAxis top} axes and refresh the grid.</p> * <p>In this case we reconfigure the PivotGrid to have city and year as the top axis dimensions, rendering the average sale * value into the cells:</p> <pre><code> //the left axis can also be changed pivot.topAxis.setDimensions([ {dataIndex: 'city', direction: 'DESC'}, {dataIndex: 'year', direction: 'ASC'} ]); pivot.setMeasure('value'); pivot.setAggregator('avg'); pivot.view.refresh(true); </code></pre> * <p>See the {@link Ext.grid.PivotAxis PivotAxis} documentation for further detail on reconfiguring axes.</p> */ Ext.grid.PivotGrid = Ext.extend(Ext.grid.GridPanel, { /** * @cfg {String|Function} aggregator The aggregation function to use to combine the measures extracted * for each dimension combination. Can be any of the built-in aggregators (sum, count, avg, min, max). * Can also be a function which accepts two arguments (an array of Records to aggregate, and the measure * to aggregate them on) and should return a String. */ aggregator: 'sum', /** * @cfg {Function} renderer Optional renderer to pass values through before they are rendered to the dom. This * gives an opportunity to modify cell contents after the value has been computed. */ renderer: undefined, /** * @cfg {String} measure The field to extract from each Record when pivoting around the two axes. See the class * introduction docs for usage */ /** * @cfg {Array|Ext.grid.PivotAxis} leftAxis Either and array of {@link #dimension} to use on the left axis, or * a {@link Ext.grid.PivotAxis} instance. If an array is passed, it is turned into a PivotAxis internally. */ /** * @cfg {Array|Ext.grid.PivotAxis} topAxis Either and array of {@link #dimension} to use on the top axis, or * a {@link Ext.grid.PivotAxis} instance. If an array is passed, it is turned into a PivotAxis internally. */ //inherit docs initComponent: function() { Ext.grid.PivotGrid.superclass.initComponent.apply(this, arguments); this.initAxes(); //no resizing of columns is allowed yet in PivotGrid this.enableColumnResize = false; this.viewConfig = Ext.apply(this.viewConfig || {}, { forceFit: true }); //TODO: dummy col model that is never used - GridView is too tightly integrated with ColumnModel //in 3.x to remove this altogether. this.colModel = new Ext.grid.ColumnModel({}); }, /** * Returns the function currently used to aggregate the records in each Pivot cell * @return {Function} The current aggregator function */ getAggregator: function() { if (typeof this.aggregator == 'string') { return Ext.grid.PivotAggregatorMgr.types[this.aggregator]; } else { return this.aggregator; } }, /** * Sets the function to use when aggregating data for each cell. * @param {String|Function} aggregator The new aggregator function or named function string */ setAggregator: function(aggregator) { this.aggregator = aggregator; }, /** * Sets the field name to use as the Measure in this Pivot Grid * @param {String} measure The field to make the measure */ setMeasure: function(measure) { this.measure = measure; }, /** * Sets the left axis of this pivot grid. Optionally refreshes the grid afterwards. * @param {Ext.grid.PivotAxis} axis The pivot axis * @param {Boolean} refresh True to immediately refresh the grid and its axes (defaults to false) */ setLeftAxis: function(axis, refresh) { /** * The configured {@link Ext.grid.PivotAxis} used as the left Axis for this Pivot Grid * @property leftAxis * @type Ext.grid.PivotAxis */ this.leftAxis = axis; if (refresh) { this.view.refresh(); } }, /** * Sets the top axis of this pivot grid. Optionally refreshes the grid afterwards. * @param {Ext.grid.PivotAxis} axis The pivot axis * @param {Boolean} refresh True to immediately refresh the grid and its axes (defaults to false) */ setTopAxis: function(axis, refresh) { /** * The configured {@link Ext.grid.PivotAxis} used as the top Axis for this Pivot Grid * @property topAxis * @type Ext.grid.PivotAxis */ this.topAxis = axis; if (refresh) { this.view.refresh(); } }, /** * @private * Creates the top and left axes. Should usually only need to be called once from initComponent */ initAxes: function() { var PivotAxis = Ext.grid.PivotAxis; if (!(this.leftAxis instanceof PivotAxis)) { this.setLeftAxis(new PivotAxis({ orientation: 'vertical', dimensions : this.leftAxis || [], store : this.store })); }; if (!(this.topAxis instanceof PivotAxis)) { this.setTopAxis(new PivotAxis({ orientation: 'horizontal', dimensions : this.topAxis || [], store : this.store })); }; }, /** * @private * @return {Array} 2-dimensional array of cell data */ extractData: function() { var records = this.store.data.items, recCount = records.length, cells = [], record, i, j, k; if (recCount == 0) { return []; } var leftTuples = this.leftAxis.getTuples(), leftCount = leftTuples.length, topTuples = this.topAxis.getTuples(), topCount = topTuples.length, aggregator = this.getAggregator(); for (i = 0; i < recCount; i++) { record = records[i]; for (j = 0; j < leftCount; j++) { cells[j] = cells[j] || []; if (leftTuples[j].matcher(record) === true) { for (k = 0; k < topCount; k++) { cells[j][k] = cells[j][k] || []; if (topTuples[k].matcher(record)) { cells[j][k].push(record); } } } } } var rowCount = cells.length, colCount, row; for (i = 0; i < rowCount; i++) { row = cells[i]; colCount = row.length; for (j = 0; j < colCount; j++) { cells[i][j] = aggregator(cells[i][j], this.measure); } } return cells; }, /** * Returns the grid's GridView object. * @return {Ext.grid.PivotGridView} The grid view */ getView: function() { if (!this.view) { this.view = new Ext.grid.PivotGridView(this.viewConfig); } return this.view; } }); Ext.reg('pivotgrid', Ext.grid.PivotGrid); Ext.grid.PivotAggregatorMgr = new Ext.AbstractManager(); Ext.grid.PivotAggregatorMgr.registerType('sum', function(records, measure) { var length = records.length, total = 0, i; for (i = 0; i < length; i++) { total += records[i].get(measure); } return total; }); Ext.grid.PivotAggregatorMgr.registerType('avg', function(records, measure) { var length = records.length, total = 0, i; for (i = 0; i < length; i++) { total += records[i].get(measure); } return (total / length) || 'n/a'; }); Ext.grid.PivotAggregatorMgr.registerType('min', function(records, measure) { var data = [], length = records.length, i; for (i = 0; i < length; i++) { data.push(records[i].get(measure)); } return Math.min.apply(this, data) || 'n/a'; }); Ext.grid.PivotAggregatorMgr.registerType('max', function(records, measure) { var data = [], length = records.length, i; for (i = 0; i < length; i++) { data.push(records[i].get(measure)); } return Math.max.apply(this, data) || 'n/a'; }); Ext.grid.PivotAggregatorMgr.registerType('count', function(records, measure) { return records.length; });
apache-2.0
faint32/snowflake-1
Snowflake.Shell.Windows/electron/download.js
4432
var $ = require("jQuery") var exports = module.exports = {}; exports.queue = []; exports.lock = false; exports.counter = 0; exports.downloadFile = function(url, description){ var queuedDownload = function() { $('.download-progress-status').each(function(index){ $(this).html("Updating " + description); }); window.setTimeout(function(){ fs.mkdir((process.env.APPDATA || (process.platform == 'darwin' ? process.env.HOME + 'Library/Preference' : '/var/local')) + "/Snowflake/staging/", function(err){}); var fullpath = (process.env.APPDATA || (process.platform == 'darwin' ? process.env.HOME + 'Library/Preference' : '/var/local')) + "/Snowflake/staging/" + (url ? url.split('/').pop().split('#').shift().split('?').shift() : null); description = description || (url ? url.split('/').pop().split('#').shift().split('?').shift() : null); exports.lock = true; $.ajax({ url: url, success: function(data){ console.log("success"); fs.writeFile(fullpath, data, function(err){ if (err) { $('.download-progress-bar').each(function(index){ $(this).addClass("progress-bar-danger"); }); $('.download-progress-status').each(function(index){ $(this).html("Error downloading " + description); }); } else { console.log("Saved to " + fullpath); $('.download-progress-bar').each(function(index){ $(this).css({width :"100%"}); }); $('.download-progress-bar-label').each(function(index){ $(this).html("100%"); }); $('.download-progress-status').each(function(index){ $(this).html("Updated " + description); }); } exports.queue.shift(); delete exports.current; window.setTimeout(function(){ exports.lock = false; }, 1000); window.dispatchEvent(new Event('downloadcomplete')); }); }, cache: false, error: function (xhr, ajaxOptions, thrownError) { console.log(xhr.responseText); console.log(thrownError); $('.download-progress-status').each(function(index){ $(this).html("Error downloading " + description); }); $('.download-progress-bar').each(function(index){ $(this).addClass("progress-bar-danger"); }); console.warn("Could not download file " + url); exports.queue.shift(); delete exports.current; window.setTimeout(function(){ exports.lock = false; }, 1000); window.dispatchEvent(new Event('downloaderror')); }, xhr: function() { var xhr = new window.XMLHttpRequest(); xhr.addEventListener("progress", function(event){ if (event.lengthComputable) { var percentComplete = event.loaded / event.total; $('.download-progress-bar').each(function(index){ $(this).css({width : percentComplete * 100 + "%"}); }); $('.download-progress-bar-label').each(function(index){ $(this).html(Math.floor(percentComplete * 100) + "%"); }); } }, false); return xhr; } }); }, 1000); } exports.queue.push(queuedDownload); } exports.worker = window.setInterval(function(){ if(!exports.lock && exports.queue[0] !== undefined && exports.current === undefined){ $('.download-progress-bar').each(function(index){ $(this).css({width : "0%"}); }); $('.download-progress-bar').each(function(index){ $(this).removeClass("progress-bar-warning"); $(this).removeClass("progress-bar-danger"); }); $('.download-progress-status').each(function(index){ $(this).html("<br/>"); }); $('.download-progress-bar-label').each(function(index){ $(this).html("0%"); }); exports.current = window.setTimeout(function(){ exports.queue[0](); }, 2000); } }, 0);
apache-2.0
aleo72/ww-ceem-radar
src/main/java/gov/nasa/worldwind/cache/MemoryCacheSet.java
686
/* * Copyright (C) 2012 United States Government as represented by the Administrator of the * National Aeronautics and Space Administration. * All Rights Reserved. */ package gov.nasa.worldwind.cache; import gov.nasa.worldwind.util.PerformanceStatistic; import java.util.*; /** * @author tag * @version $Id: MemoryCacheSet.java 1171 2013-02-11 21:45:02Z dcollins $ */ public interface MemoryCacheSet { boolean containsCache(String key); MemoryCache getCache(String cacheKey); MemoryCache addCache(String key, MemoryCache cache); Collection<PerformanceStatistic> getPerformanceStatistics(); void clear(); Map<String, MemoryCache> getAllCaches(); }
apache-2.0
marcusportmann/mmp-java
src/mmp-application-sms/src/main/java/com/mymobileapi/api5/SentDSSTR.java
4832
package com.mymobileapi.api5; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAnyElement; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="Username" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="Password" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="Data" minOccurs="0"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;any maxOccurs="2"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "username", "password", "data" }) @XmlRootElement(name = "Sent_DS_STR") public class SentDSSTR { @XmlElement(name = "Username") protected String username; @XmlElement(name = "Password") protected String password; @XmlElement(name = "Data") protected SentDSSTR.Data data; /** * Gets the value of the username property. * * @return * possible object is * {@link String } * */ public String getUsername() { return username; } /** * Sets the value of the username property. * * @param value * allowed object is * {@link String } * */ public void setUsername(String value) { this.username = value; } /** * Gets the value of the password property. * * @return * possible object is * {@link String } * */ public String getPassword() { return password; } /** * Sets the value of the password property. * * @param value * allowed object is * {@link String } * */ public void setPassword(String value) { this.password = value; } /** * Gets the value of the data property. * * @return * possible object is * {@link SentDSSTR.Data } * */ public SentDSSTR.Data getData() { return data; } /** * Sets the value of the data property. * * @param value * allowed object is * {@link SentDSSTR.Data } * */ public void setData(SentDSSTR.Data value) { this.data = value; } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;any maxOccurs="2"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "any" }) public static class Data { @XmlAnyElement(lax = true) protected List<Object> any; /** * Gets the value of the any property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the any property. * * <p> * For example, to add a new item, do as follows: * <pre> * getAny().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link Object } * * */ public List<Object> getAny() { if (any == null) { any = new ArrayList<Object>(); } return this.any; } } }
apache-2.0
BoomBoobs/chrome-extension
src/components/Basic/LoadingSpinner/LoadingSpinner.js
67
export default from 'buildo-react-components/src/loading-spinner';
apache-2.0
ty1er/incubator-asterixdb
asterixdb/asterix-metadata/src/main/java/org/apache/asterix/metadata/entitytupletranslators/LibraryTupleTranslator.java
5481
/* * 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.asterix.metadata.entitytupletranslators; import java.io.ByteArrayInputStream; import java.io.DataInput; import java.io.DataInputStream; import java.util.Calendar; import org.apache.asterix.formats.nontagged.SerializerDeserializerProvider; import org.apache.asterix.metadata.bootstrap.MetadataPrimaryIndexes; import org.apache.asterix.metadata.bootstrap.MetadataRecordTypes; import org.apache.asterix.metadata.entities.Library; import org.apache.asterix.om.base.ARecord; import org.apache.asterix.om.base.AString; import org.apache.hyracks.algebricks.common.exceptions.AlgebricksException; import org.apache.hyracks.api.dataflow.value.ISerializerDeserializer; import org.apache.hyracks.api.exceptions.HyracksDataException; import org.apache.hyracks.dataflow.common.data.accessors.ITupleReference; /** * Translates a Library metadata entity to an ITupleReference and vice versa. */ public class LibraryTupleTranslator extends AbstractTupleTranslator<Library> { // Field indexes of serialized Library in a tuple. // First key field. public static final int LIBRARY_DATAVERSENAME_TUPLE_FIELD_INDEX = 0; // Second key field. public static final int LIBRARY_NAME_TUPLE_FIELD_INDEX = 1; // Payload field containing serialized Library. public static final int LIBRARY_PAYLOAD_TUPLE_FIELD_INDEX = 2; @SuppressWarnings("unchecked") private ISerializerDeserializer<ARecord> recordSerDes = SerializerDeserializerProvider.INSTANCE.getSerializerDeserializer(MetadataRecordTypes.LIBRARY_RECORDTYPE); protected LibraryTupleTranslator(boolean getTuple) { super(getTuple, MetadataPrimaryIndexes.LIBRARY_DATASET.getFieldCount()); } @Override public Library getMetadataEntityFromTuple(ITupleReference frameTuple) throws HyracksDataException { byte[] serRecord = frameTuple.getFieldData(LIBRARY_PAYLOAD_TUPLE_FIELD_INDEX); int recordStartOffset = frameTuple.getFieldStart(LIBRARY_PAYLOAD_TUPLE_FIELD_INDEX); int recordLength = frameTuple.getFieldLength(LIBRARY_PAYLOAD_TUPLE_FIELD_INDEX); ByteArrayInputStream stream = new ByteArrayInputStream(serRecord, recordStartOffset, recordLength); DataInput in = new DataInputStream(stream); ARecord libraryRecord = recordSerDes.deserialize(in); return createLibraryFromARecord(libraryRecord); } private Library createLibraryFromARecord(ARecord libraryRecord) { String dataverseName = ((AString) libraryRecord.getValueByPos(MetadataRecordTypes.LIBRARY_ARECORD_DATAVERSENAME_FIELD_INDEX)) .getStringValue(); String libraryName = ((AString) libraryRecord.getValueByPos(MetadataRecordTypes.LIBRARY_ARECORD_NAME_FIELD_INDEX)) .getStringValue(); return new Library(dataverseName, libraryName); } @Override public ITupleReference getTupleFromMetadataEntity(Library library) throws HyracksDataException, AlgebricksException { // write the key in the first 2 fields of the tuple tupleBuilder.reset(); aString.setValue(library.getDataverseName()); stringSerde.serialize(aString, tupleBuilder.getDataOutput()); tupleBuilder.addFieldEndOffset(); aString.setValue(library.getName()); stringSerde.serialize(aString, tupleBuilder.getDataOutput()); tupleBuilder.addFieldEndOffset(); // write the pay-load in the third field of the tuple recordBuilder.reset(MetadataRecordTypes.LIBRARY_RECORDTYPE); // write field 0 fieldValue.reset(); aString.setValue(library.getDataverseName()); stringSerde.serialize(aString, fieldValue.getDataOutput()); recordBuilder.addField(MetadataRecordTypes.LIBRARY_ARECORD_DATAVERSENAME_FIELD_INDEX, fieldValue); // write field 1 fieldValue.reset(); aString.setValue(library.getName()); stringSerde.serialize(aString, fieldValue.getDataOutput()); recordBuilder.addField(MetadataRecordTypes.LIBRARY_ARECORD_NAME_FIELD_INDEX, fieldValue); // write field 2 fieldValue.reset(); aString.setValue(Calendar.getInstance().getTime().toString()); stringSerde.serialize(aString, fieldValue.getDataOutput()); recordBuilder.addField(MetadataRecordTypes.LIBRARY_ARECORD_TIMESTAMP_FIELD_INDEX, fieldValue); // write record recordBuilder.write(tupleBuilder.getDataOutput(), true); tupleBuilder.addFieldEndOffset(); tuple.reset(tupleBuilder.getFieldEndOffsets(), tupleBuilder.getByteArray()); return tuple; } }
apache-2.0
pdxrunner/geode
geode-core/src/main/java/org/apache/geode/internal/cache/xmlcache/DiskStoreAttributesCreation.java
11926
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.geode.internal.cache.xmlcache; import java.io.File; import java.io.Serializable; import org.apache.geode.cache.DiskStore; import org.apache.geode.cache.DiskStoreFactory; import org.apache.geode.internal.cache.DiskStoreAttributes; import org.apache.geode.internal.cache.DiskStoreFactoryImpl; import org.apache.geode.internal.cache.UserSpecifiedDiskStoreAttributes; /** * Represents {@link DiskStoreAttributes} that are created declaratively. Notice that it implements * the {@link DiskStore} interface so that this class must be updated when {@link DiskStore} is * modified. This class is public for testing purposes. * * * @since GemFire prPersistSprint2 */ public class DiskStoreAttributesCreation extends UserSpecifiedDiskStoreAttributes implements Serializable, DiskStore { /** * An <code>AttributesFactory</code> for creating default <code>RegionAttribute</code>s */ // private static final DiskStoreFactory defaultFactory = new DiskStoreFactoryImpl(); /** * Creates a new <code>DiskStoreCreation</code> with the default region attributes. */ public DiskStoreAttributesCreation() {} /** * Creates a new <code>DiskStoreAttributesCreation</code> with the given disk store attributes. * NOTE: Currently attrs will not be an instance of DiskStoreAttributesCreation. If it could be * then this code should be changed to use attrs' hasXXX methods to initialize the has booleans * when defaults is false. * * @param attrs the attributes with which to initialize this DiskStore. */ public DiskStoreAttributesCreation(DiskStoreAttributes attrs) { this.name = attrs.getName(); this.autoCompact = attrs.getAutoCompact(); this.compactionThreshold = attrs.getCompactionThreshold(); this.allowForceCompaction = attrs.getAllowForceCompaction(); this.maxOplogSizeInBytes = attrs.getMaxOplogSizeInBytes(); this.timeInterval = attrs.getTimeInterval(); this.writeBufferSize = attrs.getWriteBufferSize(); this.queueSize = attrs.getQueueSize(); this.diskDirs = attrs.getDiskDirs(); this.diskDirSizes = attrs.getDiskDirSizes(); setDiskUsageWarningPercentage(attrs.getDiskUsageWarningPercentage()); setDiskUsageCriticalPercentage(attrs.getDiskUsageCriticalPercentage()); if (attrs instanceof UserSpecifiedDiskStoreAttributes) { // Selectively set has* fields to true, propagating those non-default // (aka user specified) fields as such UserSpecifiedDiskStoreAttributes nonDefault = (UserSpecifiedDiskStoreAttributes) attrs; initHasFields(nonDefault); } else { // Set all fields to true setAllHasFields(true); } } ////////////////////// Instance Methods ////////////////////// /** * Returns whether or not two objects are {@linkplain Object#equals equals} taking * <code>null</code> into account. */ static boolean equal(Object o1, Object o2) { if (o1 == null) { if (o2 != null) { return false; } else { return true; } } else { return o1.equals(o2); } } /** * returns true if two long[] are equal * * @return true if equal */ private boolean equal(long[] array1, long[] array2) { if (array1.length != array2.length) { return false; } for (int i = 0; i < array1.length; i++) { if (array1[i] != array2[i]) { return false; } } return true; } /** * returns true if two int[] are equal * * @return true if equal */ private boolean equal(int[] array1, int[] array2) { if (array1.length != array2.length) { return false; } for (int i = 0; i < array1.length; i++) { if (array1[i] != array2[i]) { return false; } } return true; } /** * Returns whether or not two <code>File</code> arrays specify the same files. */ private boolean equal(File[] array1, File[] array2) { if (array1.length != array2.length) { return false; } for (int i = 0; i < array1.length; i++) { boolean found = false; for (int j = 0; j < array2.length; j++) { if (equal(array1[i].getAbsoluteFile(), array2[j].getAbsoluteFile())) { found = true; break; } } if (!found) { StringBuffer sb = new StringBuffer(); sb.append("Didn't find "); sb.append(array1[i]); sb.append(" in "); for (int k = 0; k < array2.length; k++) { sb.append(array2[k]); sb.append(" "); } System.out.println(sb); return false; } } return true; } /** * Returns whether or not this <code>DiskStoreCreation</code> is equivalent to another * <code>DiskStore</code>. */ public boolean sameAs(DiskStore other) { if (this.autoCompact != other.getAutoCompact()) { throw new RuntimeException( String.format("AutoCompact of disk store %s is not the same: this: %s other: %s", new Object[] {name, this.autoCompact, other.getAutoCompact()})); } if (this.compactionThreshold != other.getCompactionThreshold()) { throw new RuntimeException( String.format( "CompactionThreshold of disk store %s is not the same: this: %s other: %s", new Object[] {name, this.compactionThreshold, other.getCompactionThreshold()})); } if (this.allowForceCompaction != other.getAllowForceCompaction()) { throw new RuntimeException( String.format( "AllowForceCompaction of disk store %s is not the same: this: %s other: %s", new Object[] {name, this.allowForceCompaction, other.getAllowForceCompaction()})); } if (this.maxOplogSizeInBytes != other.getMaxOplogSize() * 1024 * 1024) { throw new RuntimeException( String.format("MaxOpLogSize of disk store %s is not the same: this: %s other: %s", new Object[] {name, this.maxOplogSizeInBytes / 1024 / 1024, other.getMaxOplogSize()})); } if (this.timeInterval != other.getTimeInterval()) { throw new RuntimeException( String.format("TimeInterval of disk store %s is not the same: this: %s other: %s", new Object[] {name, this.timeInterval, other.getTimeInterval()})); } if (this.writeBufferSize != other.getWriteBufferSize()) { throw new RuntimeException( String.format("WriteBufferSize of disk store %s is not the same: this: %s other: %s", new Object[] {name, this.writeBufferSize, other.getWriteBufferSize()})); } if (this.queueSize != other.getQueueSize()) { throw new RuntimeException( String.format("QueueSize of disk store %s is not the same: this: %s other: %s", new Object[] {name, this.queueSize, other.getQueueSize()})); } if (!equal(this.diskDirs, other.getDiskDirs())) { throw new RuntimeException( String.format("Disk Dirs of disk store %s are not the same", name)); } if (!equal(this.diskDirSizes, other.getDiskDirSizes())) { throw new RuntimeException( String.format("Disk Dir Sizes of disk store %s are not the same", name)); } if (!equal(getDiskUsageWarningPercentage(), other.getDiskUsageWarningPercentage())) { throw new RuntimeException( String.format("Disk usage warning percentages of disk store %s are not the same", name)); } if (!equal(getDiskUsageCriticalPercentage(), other.getDiskUsageCriticalPercentage())) { throw new RuntimeException( String.format("Disk usage critical percentages of disk store %s are not the same", name)); } return true; } public void setName(String name) { this.name = name; } public void setAutoCompact(boolean autoCompact) { this.autoCompact = autoCompact; this.setHasAutoCompact(true); } public void setCompactionThreshold(int compactionThreshold) { this.compactionThreshold = compactionThreshold; this.setHasCompactionThreshold(true); } public void setAllowForceCompaction(boolean allowForceCompaction) { this.allowForceCompaction = allowForceCompaction; this.setHasAllowForceCompaction(true); } public void setMaxOplogSize(long maxOplogSize) { this.maxOplogSizeInBytes = maxOplogSize * 1024 * 1024; this.setHasMaxOplogSize(true); } public void setTimeInterval(long timeInterval) { this.timeInterval = timeInterval; this.setHasTimeInterval(true); } public void setWriteBufferSize(int writeBufferSize) { this.writeBufferSize = writeBufferSize; this.setHasWriteBufferSize(true); } public void setQueueSize(int queueSize) { this.queueSize = queueSize; this.setHasQueueSize(true); } public void setDiskDirs(File[] diskDirs) { checkIfDirectoriesExist(diskDirs); this.diskDirs = diskDirs; this.diskDirSizes = new int[diskDirs.length]; for (int i = 0; i < diskDirs.length; i++) { this.diskDirSizes[i] = DiskStoreFactory.DEFAULT_DISK_DIR_SIZE; } setHasDiskDirs(true); } public void setDiskDirsAndSize(File[] diskDirs, int[] sizes) { checkIfDirectoriesExist(diskDirs); this.diskDirs = diskDirs; if (sizes.length != this.diskDirs.length) { throw new IllegalArgumentException( String.format( "Number of diskSizes is %s which is not equal to number of disk Dirs which is %s", new Object[] {Integer.valueOf(sizes.length), Integer.valueOf(diskDirs.length)})); } verifyNonNegativeDirSize(sizes); this.diskDirSizes = sizes; this.setHasDiskDirs(true); } public void setDiskUsageWarningPercentage(float diskUsageWarningPercentage) { super.setDiskUsageWarningPercentage(diskUsageWarningPercentage); this.setHasDiskUsageWarningPercentage(true); } public void setDiskUsageCriticalPercentage(float diskUsageCriticalPercentage) { super.setDiskUsageCriticalPercentage(diskUsageCriticalPercentage); this.setHasDiskUsageCriticalPercentage(true); } /** * Checks if directories exist * */ private void checkIfDirectoriesExist(File[] disk_dirs) { // for (int i=0; i < disk_dirs.length; i++) { // if (! disk_dirs[i].isDirectory()) { //// throw new // IllegalArgumentException(String.format("%s was not an existing directory for disk store // %s.",new // Object[] {disk_dirs[i], name})); // if (!diskDirs[i].mkdirs()) { // throw new RuntimeException("Cannot create directory" + diskDirs[i].getAbsolutePath() + "Num // disk dirs to be created : " + disk_dirs.length + " Dir Name " + disk_dirs[i].getName()); // } // } // } DiskStoreFactoryImpl.checkIfDirectoriesExist(disk_dirs); } private void verifyNonNegativeDirSize(int[] sizes) { for (int i = 0; i < sizes.length; i++) { if (sizes[i] < 0) { throw new IllegalArgumentException( String.format("Dir size cannot be negative : %s for disk store %s", new Object[] {Integer.valueOf(sizes[i]), name})); } } } }
apache-2.0
fnklabs/splac
splac-http-server/src/main/java/com/fnklabs/splac/Path.java
209
package com.fnklabs.splac; import java.lang.annotation.*; /** * Servlet url path */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Path { String value(); }
apache-2.0
SE-Group1/HookedUp
HookedUp/api/tools.php
5864
<?php $_PUT; $_DELETE; /** * Returns a mysqli object with a valid connection to the server's database */ function mysqlConnect() { $servername = "127.0.0.1"; $username = "root"; $password = "hookedup"; $dbname = "hookedup"; $conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { failure("Connection failed: " . $conn->connect_error); } return $conn; } /** * Gets the sessionId from header data */ function getSessionId() { return getAllHeaders()['X-Session-Id']; } /** * Returns request data that has been scrubbed using htmlspecialchars() */ function getMethod() { return htmlspecialchars($_SERVER['REQUEST_METHOD']); } function getGETSafe($key) { $val = htmlspecialchars($_GET[$key]); return empty($val) ? NULL : $val; } function getPOSTSafe($key) { $val = htmlspecialchars($_POST[$key]); return empty($val) ? NULL : $val; } function getPUTSafe($key) { global $_PUT; if(!isset($_PUT)) { parse_str(file_get_contents("php://input"), $_PUT); } $val = htmlspecialchars($_PUT[$key]); return empty($val) ? NULL : $val; } function getDELETESafe($key) { global $_DELETE; if(!isset($_DELETE)) { parse_str(file_get_contents("php://input"), $_DELETE); } $val = htmlspecialchars($_DELETE[$key]); return empty($val) ? NULL : $val; } /** * Returns json with an error message */ function failure($error) { $data = array(); $data['success'] = false; $data['error'] = $error; exit(json_encode($data)); } /** * Returns json for success with the result if provided */ function success($resultArr = array()) { $data = array(); $data['success'] = true; $data['result'] = $resultArr; exit(json_encode($data)); } /** * Returns true if the user is logged in */ function isLoggedIn() { return isset($_SESSION['userId']); } function userProperties($root = "user") { $root = $root."."; return $root."id, ".$root."createdAt, ".$root."username, ".$root."firstName, ".$root."lastName, " .$root."email, ".$root."phoneNumber, ".$root."birthday, ".$root."profileImageId"; } function companyProperties($root = "company") { $root = $root."."; return $root."id, ".$root."createdAt, ".$root."name, ".$root."birthday, ".$root."managerUserId ," .$root."profileImageId, ".$root."isPremium"; } function exec_stmt($query, $type = null, $param = null , $param2 = null, $param3 = null, $param4 = null) { $conn = mysqlConnect(); if (!$stmt = $conn->prepare($query)) { failure("Prepare failed: " . $conn->error); } if ($type != null) { if ($param4 != null) { $stmt->bind_param($type, $param, $param2, $param3, $param4); } else if ($param3 != null) { $stmt->bind_param($type, $param, $param2, $param3); } else if ($param2 != null) { $stmt->bind_param($type, $param, $param2); } else { $stmt->bind_param($type, $param); } } if (!$stmt->execute()) { failure("Execute failed: " . $stmt->error); } $result = $stmt->get_result(); if($result === false) { return null; } $array = array(); while ($row = $result->fetch_assoc()) { $array[] = $row; } return $array; } function getRootUrl() { if (strpos($_SERVER['HTTP_HOST'], "localhost:8000") !== FALSE) { return "http://localhost:8001"; } return $_SERVER['HTTP_HOST']; } function requireLoggedIn($userId, $sessionId) { if(!isUserLoggedIn($userId, $sessionId)) { failure("Not logged in"); } } function checkLoggedIn($userId, $sessionId) { if(isUserLoggedIn($userId, $sessionId)) { failure("Already logged in"); } } function isUserLoggedIn($userId, $sessionId) { session_start(); if(!isset($sessionId)) { return false; } $url = "/api/auth/authenticate.php"; $fields = array( 'id' => $userId, 'sessionId' => $sessionId ); $result = curl_post($url, $fields); return $result['result']; } /** * Send a POST requst using cURL * Reference: Davic from Code2Design.com http://php.net/manual/en/function.curl-exec.php */ function curl_post($urlPart, array $post = NULL, array $options = array()) { $url = getRootUrl() . $urlPart; $defaults = array( CURLOPT_POST => 1, CURLOPT_HEADER => 0, CURLOPT_URL => $url, CURLOPT_FRESH_CONNECT => 1, CURLOPT_RETURNTRANSFER => 1, CURLOPT_FORBID_REUSE => 1, CURLOPT_TIMEOUT => 4, CURLOPT_POSTFIELDS => http_build_query($post) ); $ch = curl_init(); curl_setopt_array($ch, ($options + $defaults)); if( ! $result = curl_exec($ch)) { trigger_error(curl_error($ch)); } curl_close($ch); return json_decode($result, true); } /** * Send a GET requst using cURL * Reference: Davic from Code2Design.com http://php.net/manual/en/function.curl-exec.php */ function curl_get($urlPart, array $get = NULL, array $options = array()) { $url = getRootUrl() . $urlPart; $defaults = array( CURLOPT_URL => $url. (strpos($url, '?') === FALSE ? '?' : ''). http_build_query($get), CURLOPT_HEADER => 0, CURLOPT_RETURNTRANSFER => TRUE, CURLOPT_TIMEOUT => 4 ); $ch = curl_init(); curl_setopt_array($ch, ($options + $defaults)); if( ! $result = curl_exec($ch)) { trigger_error(curl_error($ch)); } curl_close($ch); return json_decode($result, true); }
apache-2.0
googleapis/kiosk
server/kiosk.go
6613
// Copyright 2018 Google LLC. 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 main import ( "errors" "fmt" "sync" "time" google_protobuf "github.com/golang/protobuf/ptypes/empty" pb "github.com/googleapis/kiosk/generated" context "golang.org/x/net/context" ) // DisplayServer manages a collection of kiosks. type DisplayServer struct { SessionLifetime time.Duration kiosks map[int32]*pb.Kiosk signs map[int32]*pb.Sign signIdsForKioskIds map[int32]int32 subscribers map[int32]map[chan int32]bool nextKioskId int32 nextSignId int32 mux sync.Mutex } // NewDisplayServer creates and returns a new DisplayServer. func NewDisplayServer() *DisplayServer { return &DisplayServer{ SessionLifetime: 24 * time.Hour, kiosks: make(map[int32]*pb.Kiosk), signs: make(map[int32]*pb.Sign), signIdsForKioskIds: make(map[int32]int32), subscribers: make(map[int32]map[chan int32]bool), nextKioskId: 1, nextSignId: 1, } } // CreateKiosk creates and enrolls a kiosk for sign display. func (s *DisplayServer) CreateKiosk(c context.Context, kiosk *pb.Kiosk) (*pb.Kiosk, error) { s.mux.Lock() defer s.mux.Unlock() kiosk.Id = s.nextKioskId s.kiosks[kiosk.Id] = kiosk s.nextKioskId++ return kiosk, nil } // ListKiosks returns a list of active kiosks. func (s *DisplayServer) ListKiosks(c context.Context, x *google_protobuf.Empty) (*pb.ListKiosksResponse, error) { s.mux.Lock() defer s.mux.Unlock() response := &pb.ListKiosksResponse{} for _, k := range s.kiosks { if k != nil { response.Kiosks = append(response.Kiosks, k) } } return response, nil } // GetKiosk returns a kiosk whose ID is r.Id. func (s *DisplayServer) GetKiosk(c context.Context, r *pb.GetKioskRequest) (*pb.Kiosk, error) { s.mux.Lock() defer s.mux.Unlock() i := r.Id if s.kiosks[i] != nil { return s.kiosks[i], nil } else { return nil, errors.New("invalid kiosk id") } } // DeleteKiosk deletes the kiosk with ID r.Id. func (s *DisplayServer) DeleteKiosk(c context.Context, r *pb.DeleteKioskRequest) (*google_protobuf.Empty, error) { s.mux.Lock() defer s.mux.Unlock() i := r.Id if s.kiosks[i] != nil { delete(s.kiosks, i) if len(s.kiosks) == 0 { s.nextKioskId = 1 } return &google_protobuf.Empty{}, nil } else { return nil, errors.New("invalid kiosk id") } } // CreateSign creates and enrolls a sign for sign display. func (s *DisplayServer) CreateSign(c context.Context, sign *pb.Sign) (*pb.Sign, error) { s.mux.Lock() defer s.mux.Unlock() sign.Id = s.nextSignId s.signs[sign.Id] = sign s.nextSignId++ return sign, nil } // ListSigns returns a list of active signs. func (s *DisplayServer) ListSigns(c context.Context, x *google_protobuf.Empty) (*pb.ListSignsResponse, error) { s.mux.Lock() defer s.mux.Unlock() response := &pb.ListSignsResponse{} for _, k := range s.signs { if k != nil { response.Signs = append(response.Signs, k) } } return response, nil } // GetSign returns the sign with ID r.Id. func (s *DisplayServer) GetSign(c context.Context, r *pb.GetSignRequest) (*pb.Sign, error) { s.mux.Lock() defer s.mux.Unlock() i := r.Id if s.signs[i] != nil { return s.signs[i], nil } return nil, errors.New("invalid sign id") } // DeleteSign deletes the sign with ID r.Id. func (s *DisplayServer) DeleteSign(c context.Context, r *pb.DeleteSignRequest) (*google_protobuf.Empty, error) { s.mux.Lock() defer s.mux.Unlock() i := r.Id if s.signs[i] != nil { delete(s.signs, i) if len(s.signs) == 0 { s.nextSignId = 1 } return &google_protobuf.Empty{}, nil } return nil, errors.New("invalid sign id") } // SetSignIdForKioskIds sets a sign for display on one or more kiosks. func (s *DisplayServer) SetSignIdForKioskIds(c context.Context, r *pb.SetSignIdForKioskIdsRequest) (*google_protobuf.Empty, error) { s.mux.Lock() defer s.mux.Unlock() for _, kioskID := range r.KioskIds { s.signIdsForKioskIds[kioskID] = r.SignId if s.subscribers[kioskID] != nil { for c := range s.subscribers[kioskID] { c <- r.SignId } } } if len(r.KioskIds) == 0 { var kioskID int32 for kioskID = 1; kioskID < s.nextKioskId; kioskID++ { s.signIdsForKioskIds[kioskID] = r.SignId if s.subscribers[kioskID] != nil { for c := range s.subscribers[kioskID] { c <- r.SignId } } } } return &google_protobuf.Empty{}, nil } // GetSignIdForKioskId gets the sign that should be displayed on a kiosk. func (s *DisplayServer) GetSignIdForKioskId(c context.Context, r *pb.GetSignIdForKioskIdRequest) (*pb.GetSignIdResponse, error) { s.mux.Lock() defer s.mux.Unlock() kioskID := r.KioskId if s.kiosks[kioskID] == nil { return nil, errors.New("invalid kiosk id") } signID := s.signIdsForKioskIds[kioskID] response := &pb.GetSignIdResponse{ SignId: signID, } return response, nil } // GetSignIdsForKioskId gets the signs that should be displayed on a kiosk. Streams. func (s *DisplayServer) GetSignIdsForKioskId(r *pb.GetSignIdForKioskIdRequest, stream pb.Display_GetSignIdsForKioskIdServer) error { s.mux.Lock() defer s.mux.Unlock() kioskID := r.KioskId if s.kiosks[kioskID] == nil { return errors.New("invalid kiosk id") } signID := s.signIdsForKioskIds[kioskID] response := &pb.GetSignIdResponse{ SignId: signID, } stream.Send(response) ch := make(chan int32) if s.subscribers[kioskID] == nil { s.subscribers[kioskID] = make(map[chan int32]bool) } s.subscribers[kioskID][ch] = true s.mux.Unlock() // unlock to wait for sign updates timer := time.NewTimer(s.SessionLifetime) running := true for running { select { case <-timer.C: running = false break case signID, ok := <-ch: response := &pb.GetSignIdResponse{ SignId: signID, } err := stream.Send(response) if !ok || err != nil { fmt.Printf("error %+v\n", err) running = false break } } } s.mux.Lock() // relock to unsubscribe fmt.Printf("removing subscriber for kiosk %d\n", kioskID) delete(s.subscribers[kioskID], ch) return nil }
apache-2.0
vaclav/voicemenu
languages/jetbrains.mps.samples.VoiceMenu/source_gen/jetbrains/mps/samples/VoiceMenu/editor/RefreshFileTextRecognition_Timeout.java
4990
package jetbrains.mps.samples.VoiceMenu.editor; /*Generated by MPS */ import org.apache.log4j.Logger; import org.apache.log4j.LogManager; import jetbrains.mps.editor.runtime.cells.AbstractCellAction; import org.jetbrains.mps.openapi.model.SNode; import jetbrains.mps.openapi.editor.EditorContext; import java.nio.file.Files; import java.nio.file.Paths; import java.io.File; import jetbrains.mps.lang.smodel.generator.smodelAdapter.SPropertyOperations; import jetbrains.mps.baseLanguage.logging.runtime.model.LoggingRuntime; import org.apache.log4j.Level; import jetbrains.mps.editor.runtime.selection.SelectionUtil; import jetbrains.mps.openapi.editor.selection.SelectionManager; import jetbrains.mps.openapi.editor.cells.EditorCell; import jetbrains.mps.openapi.editor.cells.CellAction; import jetbrains.mps.openapi.editor.cells.CellActionType; import jetbrains.mps.nodeEditor.cellProviders.AbstractCellListHandler; import java.util.Objects; import org.jetbrains.mps.openapi.language.SProperty; import jetbrains.mps.smodel.adapter.structure.MetaAdapterFactory; public class RefreshFileTextRecognition_Timeout { private static final Logger LOG = LogManager.getLogger(RefreshFileTextRecognition_Timeout.class); /*package*/ static AbstractCellAction createAction_CLICK(final SNode node) { return new AbstractCellAction() { public void execute(EditorContext editorContext) { this.execute_internal(editorContext, node); } public void execute_internal(EditorContext editorContext, SNode node) { String path = System.getProperty("user.home") + "/MPS_ASTERISK"; if (!(Files.exists(Paths.get(path)))) { new File(path).mkdir(); } path = System.getProperty("user.home") + "/MPS_ASTERISK"; if (Files.exists(Paths.get(path))) { } else { new File(path).mkdir(); } try { File tmp = new File(path + "/" + SPropertyOperations.getString(node, PROPS.playback$Veml)); if (tmp.isFile()) { SPropertyOperations.assign(node, PROPS.PBisFile$pJJo, true); LoggingRuntime.logMsgView(Level.DEBUG, "Found -> File", RefreshFileTextRecognition_Timeout.class, null, null); } else { SPropertyOperations.assign(node, PROPS.PBisFile$pJJo, false); LoggingRuntime.logMsgView(Level.DEBUG, "Not Found -> Text", RefreshFileTextRecognition_Timeout.class, null, null); } } catch (Exception e) { SPropertyOperations.assign(node, PROPS.PBisFile$pJJo, false); } SelectionUtil.selectCell(editorContext, node, SelectionManager.FIRST_ERROR_CELL + "|" + SelectionManager.FOCUS_POLICY_CELL + "|" + SelectionManager.FIRST_EDITABLE_CELL + "|" + SelectionManager.FIRST_CELL); } }; } public static void setCellActions(EditorCell editorCell, SNode node, EditorContext context) { CellAction originalDelete = editorCell.getAction(CellActionType.DELETE); CellAction originalBackspace = editorCell.getAction(CellActionType.BACKSPACE); // set actions that were actually defined setDefinedCellActions(editorCell, node, context); // If we set a DELETE action but no BACKSPACE action, // use the DELETE action for BACKSPACE as well. CellAction delete = editorCell.getAction(CellActionType.DELETE); CellAction backspace = editorCell.getAction(CellActionType.BACKSPACE); if (delete != originalDelete && backspace == originalBackspace) { editorCell.setAction(CellActionType.BACKSPACE, delete); } if (delete != originalDelete) { editorCell.putUserObject(AbstractCellListHandler.ELEMENT_CELL_DELETE_SET, OB); } if (backspace != originalBackspace) { editorCell.putUserObject(AbstractCellListHandler.ELEMENT_CELL_BACKSPACE_SET, OB); } } private static final Object OB = new Object(); public static void setDefinedCellActions(EditorCell editorCell, SNode node, EditorContext context) { // set cell actions from all imported action maps // set cell actions defined directly in this action map editorCell.setAction(CellActionType.CLICK, createAction_CLICK(node)); } public static void setDefinedCellActionsOfType(EditorCell editorCell, SNode node, EditorContext context, CellActionType actionType) { // set cell action(s) of the given type from imported action maps // set cell action of the given type defined directly in this action map if (Objects.equals(actionType, CellActionType.CLICK)) { editorCell.setAction(actionType, createAction_CLICK(node)); } } private static final class PROPS { /*package*/ static final SProperty playback$Veml = MetaAdapterFactory.getProperty(0x4bc750d756884f52L, 0xb7d5b263a3393a24L, 0xbed5e5797b645b9L, 0x34fad0c9f5b34402L, "playback"); /*package*/ static final SProperty PBisFile$pJJo = MetaAdapterFactory.getProperty(0x4bc750d756884f52L, 0xb7d5b263a3393a24L, 0xbed5e5797b645b9L, 0x54e798cf44bec9edL, "PBisFile"); } }
apache-2.0
sagivo/Unity2d-Game
Assets/Resources/Scripts/Canons/CrosshairsController.cs
595
using UnityEngine; using System.Collections; public class CrosshairsController : MonoBehaviour { //public public GameObject cursor; //private private bool isShowns = true; private GameObject mouseCursor; void Awake () { Cursor.visible = false; if (!mouseCursor) mouseCursor = (GameObject)Instantiate (cursor); } void Update () { if (isShowns && mouseCursor) { Vector3 mousePos = Input.mousePosition; Vector3 wantedPosition = Camera.main.ScreenToWorldPoint (new Vector3 (mousePos.x, mousePos.y, 1f)); mouseCursor.transform.position = wantedPosition; } } }
apache-2.0
slavnovdv/Testing
sandbox/src/main/java/com/testing/sandbox/HelloWorld.java
140
package com.testing.sandbox; public class HelloWorld { public static void main(String[] args){ System.out.println("Hello world!"); } }
apache-2.0
bencaldwell/automatalib
core/src/main/java/net/automatalib/automata/transout/impl/FastMooreState.java
1522
/* Copyright (C) 2013 TU Dortmund * This file is part of AutomataLib, http://www.automatalib.net/. * * 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 net.automatalib.automata.transout.impl; import net.automatalib.automata.base.fast.FastDetState; /** * A state in a {@link FastMoore} automaton. * * @author Malte Isberner * * @param <O> output symbol class. */ public final class FastMooreState<O> extends FastDetState<FastMooreState<O>,FastMooreState<O>> { private O output; /** * Constructor. * @param numInputs number of input symbols. * @param output output symbol. */ public FastMooreState(int numInputs, O output) { super(numInputs); this.output = output; } /** * Retrieves the output symbol generated by this state. * @return the output symbol. */ public O getOutput() { return output; } /** * Sets the output symbol generated by this state. * @param output the output symbol. */ public void setOutput(O output) { this.output = output; } }
apache-2.0
ninthridge/deeviar
src/main/java/com/ninthridge/deeviar/api/SystemResource.java
916
package com.ninthridge.deeviar.api; import java.util.Date; import java.util.HashMap; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping("/api") public class SystemResource { protected final Log log = LogFactory.getLog(getClass()); @RequestMapping(method = RequestMethod.GET) public @ResponseBody ResponseEntity<?> get() { Map<String, Object> map = new HashMap<>(); map.put("sysdate", new Date()); map.put("version", 1.0); return new ResponseEntity<>(map, HttpStatus.OK); } }
apache-2.0
yuya-oc/desktop
src/main/permissionRequestHandler.js
1979
// Copyright (c) 2015-2016 Yuya Ochiai // Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {URL} from 'url'; import {ipcMain} from 'electron'; function dequeueRequests(requestQueue, permissionManager, origin, permission, status) { switch (status) { case 'allow': permissionManager.grant(origin, permission); break; case 'block': permissionManager.deny(origin, permission); break; default: break; } if (status === 'allow' || status === 'block') { const newQueue = requestQueue.filter((request) => { if (request.origin === origin && request.permission === permission) { request.callback(status === 'allow'); return false; } return true; }); requestQueue.splice(0, requestQueue.length, ...newQueue); } else { const index = requestQueue.findIndex((request) => { return request.origin === origin && request.permission === permission; }); requestQueue[index].callback(false); requestQueue.splice(index, 1); } } export default function permissionRequestHandler(mainWindow, permissionManager) { const requestQueue = []; ipcMain.on('update-permission', (event, origin, permission, status) => { dequeueRequests(requestQueue, permissionManager, origin, permission, status); }); return (webContents, permission, callback) => { let targetURL; try { targetURL = new URL(webContents.getURL()); } catch (err) { console.log(err); callback(false); return; } if (permissionManager.isDenied(targetURL.origin, permission)) { callback(false); return; } if (permissionManager.isGranted(targetURL.origin, permission)) { callback(true); return; } requestQueue.push({ origin: targetURL.origin, permission, callback, }); mainWindow.webContents.send('request-permission', targetURL.origin, permission); }; }
apache-2.0
dbflute-test/dbflute-test-dbms-mysql
src/main/java/org/docksidestage/mysql/dbflute/bsbhv/loader/LoaderOfWhiteAllInOneClsCategory.java
6406
/* * Copyright 2004-2013 the Seasar Foundation and the 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 * * 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.docksidestage.mysql.dbflute.bsbhv.loader; import java.util.List; import org.dbflute.bhv.*; import org.dbflute.bhv.referrer.*; import org.docksidestage.mysql.dbflute.exbhv.*; import org.docksidestage.mysql.dbflute.exentity.*; import org.docksidestage.mysql.dbflute.cbean.*; /** * The referrer loader of WHITE_ALL_IN_ONE_CLS_CATEGORY as TABLE. <br> * <pre> * [primary key] * CLS_CATEGORY_CODE * * [column] * CLS_CATEGORY_CODE, CLS_CATEGORY_NAME, DESCRIPTION * * [sequence] * * * [identity] * * * [version-no] * * * [foreign table] * * * [referrer table] * WHITE_ALL_IN_ONE_CLS_ELEMENT * * [foreign property] * * * [referrer property] * whiteAllInOneClsElementList * </pre> * @author DBFlute(AutoGenerator) */ public class LoaderOfWhiteAllInOneClsCategory { // =================================================================================== // Attribute // ========= protected List<WhiteAllInOneClsCategory> _selectedList; protected BehaviorSelector _selector; protected WhiteAllInOneClsCategoryBhv _myBhv; // lazy-loaded // =================================================================================== // Ready for Loading // ================= public LoaderOfWhiteAllInOneClsCategory ready(List<WhiteAllInOneClsCategory> selectedList, BehaviorSelector selector) { _selectedList = selectedList; _selector = selector; return this; } protected WhiteAllInOneClsCategoryBhv myBhv() { if (_myBhv != null) { return _myBhv; } else { _myBhv = _selector.select(WhiteAllInOneClsCategoryBhv.class); return _myBhv; } } // =================================================================================== // Load Referrer // ============= protected List<WhiteAllInOneClsElement> _referrerWhiteAllInOneClsElement; /** * Load referrer of whiteAllInOneClsElementList by the set-upper of referrer. <br> * WHITE_ALL_IN_ONE_CLS_ELEMENT by CLS_CATEGORY_CODE, named 'whiteAllInOneClsElementList'. * <pre> * <span style="color: #0000C0">whiteAllInOneClsCategoryBhv</span>.<span style="color: #994747">load</span>(<span style="color: #553000">whiteAllInOneClsCategoryList</span>, <span style="color: #553000">categoryLoader</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">categoryLoader</span>.<span style="color: #CC4747">loadWhiteAllInOneClsElement</span>(<span style="color: #553000">elementCB</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">elementCB</span>.setupSelect... * <span style="color: #553000">elementCB</span>.query().set... * <span style="color: #553000">elementCB</span>.query().addOrderBy... * }); <span style="color: #3F7E5E">// you can load nested referrer from here</span> * <span style="color: #3F7E5E">//}).withNestedReferrer(<span style="color: #553000">elementLoader</span> -&gt; {</span> * <span style="color: #3F7E5E">// elementLoader.load...</span> * <span style="color: #3F7E5E">//});</span> * }); * for (WhiteAllInOneClsCategory whiteAllInOneClsCategory : <span style="color: #553000">whiteAllInOneClsCategoryList</span>) { * ... = whiteAllInOneClsCategory.<span style="color: #CC4747">getWhiteAllInOneClsElementList()</span>; * } * </pre> * About internal policy, the value of primary key (and others too) is treated as case-insensitive. <br> * The condition-bean, which the set-upper provides, has settings before callback as follows: * <pre> * cb.query().setClsCategoryCode_InScope(pkList); * cb.query().addOrderBy_ClsCategoryCode_Asc(); * </pre> * @param refCBLambda The callback to set up referrer condition-bean for loading referrer. (NotNull) * @return The callback interface which you can load nested referrer by calling withNestedReferrer(). (NotNull) */ public NestedReferrerLoaderGateway<LoaderOfWhiteAllInOneClsElement> loadWhiteAllInOneClsElement(ConditionBeanSetupper<WhiteAllInOneClsElementCB> refCBLambda) { myBhv().loadWhiteAllInOneClsElement(_selectedList, refCBLambda).withNestedReferrer(refLs -> _referrerWhiteAllInOneClsElement = refLs); return hd -> hd.handle(new LoaderOfWhiteAllInOneClsElement().ready(_referrerWhiteAllInOneClsElement, _selector)); } // =================================================================================== // Pull out Foreign // ================ // =================================================================================== // Accessor // ======== public List<WhiteAllInOneClsCategory> getSelectedList() { return _selectedList; } public BehaviorSelector getSelector() { return _selector; } }
apache-2.0
twitter-forks/presto
presto-verifier/src/test/java/com/facebook/presto/verifier/checksum/TestChecksumValidator.java
27572
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.verifier.checksum; import com.facebook.presto.block.BlockEncodingManager; import com.facebook.presto.common.type.ArrayType; import com.facebook.presto.common.type.SqlVarbinary; import com.facebook.presto.common.type.Type; import com.facebook.presto.metadata.FunctionManager; import com.facebook.presto.sql.analyzer.FeaturesConfig; import com.facebook.presto.sql.parser.SqlParser; import com.facebook.presto.sql.parser.SqlParserOptions; import com.facebook.presto.sql.tree.DereferenceExpression; import com.facebook.presto.sql.tree.Identifier; import com.facebook.presto.sql.tree.QualifiedName; import com.facebook.presto.sql.tree.Query; import com.facebook.presto.sql.tree.Statement; import com.facebook.presto.type.TypeRegistry; import com.facebook.presto.verifier.framework.Column; import com.facebook.presto.verifier.framework.VerifierConfig; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import org.testng.annotations.Test; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import static com.facebook.presto.common.type.BigintType.BIGINT; import static com.facebook.presto.common.type.DoubleType.DOUBLE; import static com.facebook.presto.common.type.IntegerType.INTEGER; import static com.facebook.presto.common.type.RealType.REAL; import static com.facebook.presto.common.type.TypeSignature.parseTypeSignature; import static com.facebook.presto.common.type.VarcharType.VARCHAR; import static com.facebook.presto.sql.SqlFormatter.formatSql; import static com.facebook.presto.sql.parser.IdentifierSymbol.AT_SIGN; import static com.facebook.presto.sql.parser.IdentifierSymbol.COLON; import static com.facebook.presto.verifier.VerifierTestUtil.createChecksumValidator; import static com.facebook.presto.verifier.framework.VerifierUtil.PARSING_OPTIONS; import static com.facebook.presto.verifier.framework.VerifierUtil.delimitedIdentifier; import static com.google.common.collect.ImmutableList.toImmutableList; import static java.util.Arrays.asList; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; public class TestChecksumValidator { private static final TypeRegistry typeRegistry = new TypeRegistry(); static { new FunctionManager(typeRegistry, new BlockEncodingManager(typeRegistry), new FeaturesConfig()); } private static final Column BIGINT_COLUMN = createColumn("bigint", BIGINT); private static final Column VARCHAR_COLUMN = createColumn("varchar", VARCHAR); private static final Column DOUBLE_COLUMN = createColumn("double", DOUBLE); private static final Column REAL_COLUMN = createColumn("real", REAL); private static final Column INT_ARRAY_COLUMN = createColumn("int_array", new ArrayType(INTEGER)); private static final Column ROW_ARRAY_COLUMN = createColumn("row_array", typeRegistry.getType(parseTypeSignature("array(row(a int,b varchar))"))); private static final Column MAP_ARRAY_COLUMN = createColumn("map_array", typeRegistry.getType(parseTypeSignature("array(map(int,varchar))"))); private static final Column MAP_COLUMN = createColumn("map", typeRegistry.getType(parseTypeSignature("map(int,array(varchar))"))); private static final Column MAP_NON_ORDERABLE_COLUMN = createColumn("map_non_orderable", typeRegistry.getType(parseTypeSignature("map(map(int,varchar),map(int,varchar))"))); private static final Column ROW_COLUMN = createColumn("row", typeRegistry.getType(parseTypeSignature("row(i int, varchar, d double, a array(int), r row(double, b bigint))"))); private static final double RELATIVE_ERROR_MARGIN = 1e-4; private static final double ABSOLUTE_ERROR_MARGIN = 1e-12; private static final Map<String, Object> FLOATING_POINT_COUNTS = ImmutableMap.<String, Object>builder() .put("double$nan_count", 2L) .put("double$pos_inf_count", 3L) .put("double$neg_inf_count", 4L) .put("real$nan_count", 2L) .put("real$pos_inf_count", 3L) .put("real$neg_inf_count", 4L) .build(); private static final Map<String, Object> ROW_COLUMN_CHECKSUMS = ImmutableMap.<String, Object>builder() .put("row.i$checksum", new SqlVarbinary(new byte[] {0xa})) .put("row._col2$checksum", new SqlVarbinary(new byte[] {0xb})) .put("row.d$nan_count", 2L) .put("row.d$pos_inf_count", 3L) .put("row.d$neg_inf_count", 4L) .put("row.d$sum", 0.0) .put("row.a$checksum", new SqlVarbinary(new byte[] {0xc})) .put("row.a$cardinality_checksum", new SqlVarbinary(new byte[] {0xd})) .put("row.a$cardinality_sum", 2L) .put("row.r._col1$nan_count", 2L) .put("row.r._col1$pos_inf_count", 3L) .put("row.r._col1$neg_inf_count", 4L) .put("row.r._col1$sum", 0.0) .put("row.r.b$checksum", new SqlVarbinary(new byte[] {0xe})) .build(); private static final SqlParser sqlParser = new SqlParser(new SqlParserOptions().allowIdentifierSymbol(COLON, AT_SIGN)); private final ChecksumValidator checksumValidator = createChecksumValidator(new VerifierConfig() .setRelativeErrorMargin(RELATIVE_ERROR_MARGIN) .setAbsoluteErrorMargin(ABSOLUTE_ERROR_MARGIN)); @Test public void testChecksumQuery() { Query checksumQuery = checksumValidator.generateChecksumQuery( QualifiedName.of("test:di"), ImmutableList.of( BIGINT_COLUMN, VARCHAR_COLUMN, DOUBLE_COLUMN, REAL_COLUMN, INT_ARRAY_COLUMN, ROW_ARRAY_COLUMN, MAP_ARRAY_COLUMN, MAP_COLUMN, MAP_NON_ORDERABLE_COLUMN, ROW_COLUMN)); Statement expectedChecksumQuery = sqlParser.createStatement( "SELECT\n" + " \"count\"(*)\n" + ", \"checksum\"(\"bigint\") \"bigint$checksum\"\n" + ", \"checksum\"(\"varchar\") \"varchar$checksum\"\n" + ", \"sum\"(\"double\") FILTER (WHERE \"is_finite\"(\"double\")) \"double$sum\"\n" + ", \"count\"(\"double\") FILTER (WHERE \"is_nan\"(\"double\")) \"double$nan_count\"\n" + ", \"count\"(\"double\") FILTER (WHERE (\"double\" = \"infinity\"())) \"double$pos_inf_count\"\n" + ", \"count\"(\"double\") FILTER (WHERE (\"double\" = -\"infinity\"())) \"double$neg_inf_count\"\n" + ", \"sum\"(CAST(\"real\" AS double)) FILTER (WHERE \"is_finite\"(\"real\")) \"real$sum\"\n" + ", \"count\"(\"real\") FILTER (WHERE \"is_nan\"(\"real\")) \"real$nan_count\"\n" + ", \"count\"(\"real\") FILTER (WHERE (\"real\" = \"infinity\"())) \"real$pos_inf_count\"\n" + ", \"count\"(\"real\") FILTER (WHERE (\"real\" = -\"infinity\"())) \"real$neg_inf_count\"\n" + ", \"checksum\"(\"array_sort\"(\"int_array\")) \"int_array$checksum\"\n" + ", \"checksum\"(\"cardinality\"(\"int_array\")) \"int_array$cardinality_checksum\"\n" + ", COALESCE(\"sum\"(\"cardinality\"(\"int_array\")), 0) \"int_array$cardinality_sum\"\n" + ", COALESCE(\"checksum\"(TRY(\"array_sort\"(\"row_array\"))), \"checksum\"(\"row_array\")) \"row_array$checksum\"\n" + ", \"checksum\"(\"cardinality\"(\"row_array\")) \"row_array$cardinality_checksum\"\n" + ", COALESCE(\"sum\"(\"cardinality\"(\"row_array\")), 0) \"row_array$cardinality_sum\"\n" + ", \"checksum\"(\"map_array\") \"map_array$checksum\"\n" + ", \"checksum\"(\"cardinality\"(\"map_array\")) \"map_array$cardinality_checksum\"\n" + ", COALESCE(\"sum\"(\"cardinality\"(\"map_array\")), 0) \"map_array$cardinality_sum\"\n" + ", \"checksum\"(\"map\") \"map$checksum\"\n" + ", \"checksum\"(\"array_sort\"(\"map_keys\"(\"map\"))) \"map$keys_checksum\"\n" + ", COALESCE(\"checksum\"(TRY(\"array_sort\"(\"map_values\"(\"map\")))), \"checksum\"(\"map_values\"(\"map\"))) \"map$values_checksum\"\n" + ", \"checksum\"(\"cardinality\"(\"map\")) \"map$cardinality_checksum\"\n" + ", COALESCE(\"sum\"(\"cardinality\"(\"map\")), 0) \"map$cardinality_sum\"\n" + ", \"checksum\"(\"map_non_orderable\") \"map_non_orderable$checksum\"\n" + ", \"checksum\"(\"map_keys\"(\"map_non_orderable\")) \"map_non_orderable$keys_checksum\"\n" + ", \"checksum\"(\"map_values\"(\"map_non_orderable\")) \"map_non_orderable$values_checksum\"\n" + ", \"checksum\"(\"cardinality\"(\"map_non_orderable\")) \"map_non_orderable$cardinality_checksum\"\n" + ", COALESCE(\"sum\"(\"cardinality\"(\"map_non_orderable\")), 0) \"map_non_orderable$cardinality_sum\"\n" + ", \"checksum\"(\"row\".\"i\") \"row.i$checksum\"\n" + ", \"checksum\"(\"row\"[2]) \"row._col2$checksum\"\n" + ", \"sum\"(\"row\".\"d\") FILTER (WHERE \"is_finite\"(\"row\".\"d\")) \"row.d$sum\"\n" + ", \"count\"(\"row\".\"d\") FILTER (WHERE \"is_nan\"(\"row\".\"d\")) \"row.d$nan_count\"\n" + ", \"count\"(\"row\".\"d\") FILTER (WHERE (\"row\".\"d\" = \"infinity\"())) \"row.d$pos_inf_count\"\n" + ", \"count\"(\"row\".\"d\") FILTER (WHERE (\"row\".\"d\" = -\"infinity\"())) \"row.d$neg_inf_count\"\n" + ", \"checksum\"(\"array_sort\"(\"row\".\"a\")) \"row.a$checksum\"\n" + ", \"checksum\"(\"cardinality\"(\"row\".\"a\")) \"row.a$cardinality_checksum\"\n" + ", COALESCE(\"sum\"(\"cardinality\"(\"row\".\"a\")), 0) \"row.a$cardinality_sum\"\n" + ", \"sum\"(\"row\".\"r\"[1]) FILTER (WHERE \"is_finite\"(\"row\".\"r\"[1])) \"row.r._col1$sum\"\n" + ", \"count\"(\"row\".\"r\"[1]) FILTER (WHERE \"is_nan\"(\"row\".\"r\"[1])) \"row.r._col1$nan_count\"\n" + ", \"count\"(\"row\".\"r\"[1]) FILTER (WHERE (\"row\".\"r\"[1] = \"infinity\"())) \"row.r._col1$pos_inf_count\"\n" + ", \"count\"(\"row\".\"r\"[1]) FILTER (WHERE (\"row\".\"r\"[1] = -\"infinity\"())) \"row.r._col1$neg_inf_count\"\n" + ", \"checksum\"(\"row\".\"r\".\"b\") \"row.r.b$checksum\"\n" + "FROM\n" + " \"test:di\"\n", PARSING_OPTIONS); assertEquals(formatSql(checksumQuery, Optional.empty()), formatSql(expectedChecksumQuery, Optional.empty())); } @Test public void testSimple() { List<Column> columns = ImmutableList.of(BIGINT_COLUMN, VARCHAR_COLUMN); ChecksumResult controlChecksum = new ChecksumResult( 5, ImmutableMap.<String, Object>builder() .put("bigint$checksum", new SqlVarbinary(new byte[] {0xa})) .put("varchar$checksum", new SqlVarbinary(new byte[] {0xb})) .build()); // Matched assertTrue(checksumValidator.getMismatchedColumns(columns, controlChecksum, controlChecksum).isEmpty()); // Mismatched ChecksumResult testChecksum = new ChecksumResult( 5, ImmutableMap.<String, Object>builder() .put("bigint$checksum", new SqlVarbinary(new byte[] {0x1a})) .put("varchar$checksum", new SqlVarbinary(new byte[] {0x1b})) .build()); assertMismatchedColumns(columns, controlChecksum, testChecksum, BIGINT_COLUMN, VARCHAR_COLUMN); } @Test public void testFloatingPoint() { List<Column> columns = ImmutableList.of(DOUBLE_COLUMN, REAL_COLUMN); ChecksumResult controlChecksum = new ChecksumResult( 5, ImmutableMap.<String, Object>builder() .putAll(FLOATING_POINT_COUNTS) .put("double$sum", 1.0) .put("real$sum", 1.0) .build()); // Matched ChecksumResult testChecksum = new ChecksumResult( 5, ImmutableMap.<String, Object>builder() .putAll(FLOATING_POINT_COUNTS) .put("double$sum", 1 + RELATIVE_ERROR_MARGIN) .put("real$sum", 1 - RELATIVE_ERROR_MARGIN + RELATIVE_ERROR_MARGIN * RELATIVE_ERROR_MARGIN) .build()); assertTrue(checksumValidator.getMismatchedColumns(columns, controlChecksum, testChecksum).isEmpty()); // Mismatched testChecksum = new ChecksumResult( 5, ImmutableMap.<String, Object>builder() .put("double$sum", 1.0) .put("double$nan_count", 0L) .put("double$pos_inf_count", 3L) .put("double$neg_inf_count", 4L) .put("real$sum", 1.0) .put("real$nan_count", 2L) .put("real$pos_inf_count", 0L) .put("real$neg_inf_count", 4L) .build()); assertMismatchedColumns(columns, controlChecksum, testChecksum, DOUBLE_COLUMN, REAL_COLUMN); testChecksum = new ChecksumResult( 5, ImmutableMap.<String, Object>builder() .put("double$sum", 1.0) .put("double$nan_count", 2L) .put("double$pos_inf_count", 3L) .put("double$neg_inf_count", 0L) .put("real$sum", 1 - RELATIVE_ERROR_MARGIN) .put("real$nan_count", 2L) .put("real$pos_inf_count", 3L) .put("real$neg_inf_count", 4L) .build()); List<ColumnMatchResult<?>> mismatchedColumns = assertMismatchedColumns(columns, controlChecksum, testChecksum, DOUBLE_COLUMN, REAL_COLUMN); assertEquals(mismatchedColumns.get(1).getMessage(), Optional.of("relative error: 1.0000500025000149E-4")); } @Test public void testFloatingPointWithNull() { List<Column> columns = ImmutableList.of(DOUBLE_COLUMN, REAL_COLUMN); Map<String, Object> controlResult = new HashMap<>(FLOATING_POINT_COUNTS); controlResult.put("double$sum", 1.0); controlResult.put("real$sum", null); ChecksumResult controlChecksum = new ChecksumResult(5, controlResult); Map<String, Object> testResult = new HashMap<>(FLOATING_POINT_COUNTS); testResult.put("double$sum", null); testResult.put("real$sum", 1.0); ChecksumResult testChecksum = new ChecksumResult(5, testResult); assertMismatchedColumns(columns, controlChecksum, testChecksum, DOUBLE_COLUMN, REAL_COLUMN); } @Test public void testFloatingPointCloseToZero() { List<Column> columns = ImmutableList.of(DOUBLE_COLUMN, REAL_COLUMN); // Matched ChecksumResult controlChecksum = new ChecksumResult( 5, ImmutableMap.<String, Object>builder() .putAll(FLOATING_POINT_COUNTS) .put("double$sum", -4.9e-12) .put("real$sum", 4.9e-12) .build()); ChecksumResult testChecksum = new ChecksumResult( 5, ImmutableMap.<String, Object>builder() .putAll(FLOATING_POINT_COUNTS) .put("double$sum", 4.9e-12) .put("real$sum", 0.0) .build()); assertTrue(checksumValidator.getMismatchedColumns(columns, controlChecksum, testChecksum).isEmpty()); // Mismatched controlChecksum = new ChecksumResult( 5, ImmutableMap.<String, Object>builder() .putAll(FLOATING_POINT_COUNTS) .put("double$sum", 0.0) .put("real$sum", 5.1e-12) .build()); testChecksum = new ChecksumResult( 5, ImmutableMap.<String, Object>builder() .putAll(FLOATING_POINT_COUNTS) .put("double$sum", 5.1e-12) .put("real$sum", 0.0) .build()); assertMismatchedColumns(columns, controlChecksum, testChecksum, DOUBLE_COLUMN, REAL_COLUMN); } @Test public void testArray() { List<Column> columns = ImmutableList.of(INT_ARRAY_COLUMN, MAP_ARRAY_COLUMN); ChecksumResult controlChecksum = new ChecksumResult( 5, ImmutableMap.<String, Object>builder() .put("int_array$checksum", new SqlVarbinary(new byte[] {0xa})) .put("int_array$cardinality_checksum", new SqlVarbinary(new byte[] {0xb})) .put("int_array$cardinality_sum", 1L) .put("map_array$checksum", new SqlVarbinary(new byte[] {0xc})) .put("map_array$cardinality_checksum", new SqlVarbinary(new byte[] {0xd})) .put("map_array$cardinality_sum", 2L) .build()); // Matched assertTrue(checksumValidator.getMismatchedColumns(columns, controlChecksum, controlChecksum).isEmpty()); // Mismatched different elements ChecksumResult testChecksum = new ChecksumResult( 5, ImmutableMap.<String, Object>builder() .put("int_array$checksum", new SqlVarbinary(new byte[] {0x1a})) .put("int_array$cardinality_checksum", new SqlVarbinary(new byte[] {0xb})) .put("int_array$cardinality_sum", 1L) .put("map_array$checksum", new SqlVarbinary(new byte[] {0x1c})) .put("map_array$cardinality_checksum", new SqlVarbinary(new byte[] {0xd})) .put("map_array$cardinality_sum", 2L) .build()); assertMismatchedColumns(columns, controlChecksum, testChecksum, INT_ARRAY_COLUMN, MAP_ARRAY_COLUMN); // Mismatched different cardinality checksum testChecksum = new ChecksumResult( 5, ImmutableMap.<String, Object>builder() .put("int_array$checksum", new SqlVarbinary(new byte[] {0xa})) .put("int_array$cardinality_checksum", new SqlVarbinary(new byte[] {0x1b})) .put("int_array$cardinality_sum", 1L) .put("map_array$checksum", new SqlVarbinary(new byte[] {0xc})) .put("map_array$cardinality_checksum", new SqlVarbinary(new byte[] {0x1d})) .put("map_array$cardinality_sum", 2L) .build()); assertMismatchedColumns(columns, controlChecksum, testChecksum, INT_ARRAY_COLUMN, MAP_ARRAY_COLUMN); // Mismatched different cardinality sum testChecksum = new ChecksumResult( 5, ImmutableMap.<String, Object>builder() .put("int_array$checksum", new SqlVarbinary(new byte[] {0xa})) .put("int_array$cardinality_checksum", new SqlVarbinary(new byte[] {0xb})) .put("int_array$cardinality_sum", 3L) .put("map_array$checksum", new SqlVarbinary(new byte[] {0xc})) .put("map_array$cardinality_checksum", new SqlVarbinary(new byte[] {0xd})) .put("map_array$cardinality_sum", 4L) .build()); assertMismatchedColumns(columns, controlChecksum, testChecksum, INT_ARRAY_COLUMN, MAP_ARRAY_COLUMN); } @Test public void testRow() { List<Column> columns = ImmutableList.of(ROW_COLUMN); ChecksumResult controlChecksum = new ChecksumResult(ROW_COLUMN_CHECKSUMS.size(), ROW_COLUMN_CHECKSUMS); assertTrue(checksumValidator.getMismatchedColumns(columns, controlChecksum, controlChecksum).isEmpty()); // Mismatched different elements ChecksumResult testChecksum = new ChecksumResult( ROW_COLUMN_CHECKSUMS.size(), merge(ROW_COLUMN_CHECKSUMS, ImmutableMap.<String, Object>builder() .put("row.i$checksum", new SqlVarbinary(new byte[] {0x1a})) .put("row.r.b$checksum", new SqlVarbinary(new byte[] {0x1d})) .build())); Column aFieldColumn = Column.create("row.i", new DereferenceExpression(ROW_COLUMN.getExpression(), new Identifier("i")), INTEGER); Column rbFieldColumn = Column.create("row.r.b", new DereferenceExpression(new DereferenceExpression(ROW_COLUMN.getExpression(), new Identifier("r")), new Identifier("b")), BIGINT); assertMismatchedColumns(columns, controlChecksum, testChecksum, aFieldColumn, rbFieldColumn); } @Test public void testMap() { List<Column> columns = ImmutableList.of(MAP_COLUMN); ChecksumResult controlChecksum = new ChecksumResult( 5, ImmutableMap.<String, Object>builder() .put("map$checksum", new SqlVarbinary(new byte[] {0xa})) .put("map$keys_checksum", new SqlVarbinary(new byte[] {0xb})) .put("map$values_checksum", new SqlVarbinary(new byte[] {0xc})) .put("map$cardinality_sum", 3L) .put("map$cardinality_checksum", new SqlVarbinary(new byte[] {0xd})) .build()); // Matched assertTrue(checksumValidator.getMismatchedColumns(columns, controlChecksum, controlChecksum).isEmpty()); // Mismatched map checksum ChecksumResult testChecksum = new ChecksumResult( 5, ImmutableMap.<String, Object>builder() .put("map$checksum", new SqlVarbinary(new byte[] {0x1a})) .put("map$keys_checksum", new SqlVarbinary(new byte[] {0xb})) .put("map$values_checksum", new SqlVarbinary(new byte[] {0xc})) .put("map$cardinality_sum", 3L) .put("map$cardinality_checksum", new SqlVarbinary(new byte[] {0xd})) .build()); assertMismatchedColumns(columns, controlChecksum, testChecksum, MAP_COLUMN); // Mismatched keys checksum testChecksum = new ChecksumResult( 5, ImmutableMap.<String, Object>builder() .put("map$checksum", new SqlVarbinary(new byte[] {0xa})) .put("map$keys_checksum", new SqlVarbinary(new byte[] {0x1b})) .put("map$values_checksum", new SqlVarbinary(new byte[] {0xc})) .put("map$cardinality_checksum", new SqlVarbinary(new byte[] {0xd})) .put("map$cardinality_sum", 3L) .build()); assertMismatchedColumns(columns, controlChecksum, testChecksum, MAP_COLUMN); // Mismatched values checksum testChecksum = new ChecksumResult( 5, ImmutableMap.<String, Object>builder() .put("map$checksum", new SqlVarbinary(new byte[] {0xa})) .put("map$keys_checksum", new SqlVarbinary(new byte[] {0xb})) .put("map$values_checksum", new SqlVarbinary(new byte[] {0x1c})) .put("map$cardinality_checksum", new SqlVarbinary(new byte[] {0xd})) .put("map$cardinality_sum", 3L) .build()); assertMismatchedColumns(columns, controlChecksum, testChecksum, MAP_COLUMN); // Mismatched cardinality checksum testChecksum = new ChecksumResult( 5, ImmutableMap.<String, Object>builder() .put("map$checksum", new SqlVarbinary(new byte[] {0xa})) .put("map$keys_checksum", new SqlVarbinary(new byte[] {0xb})) .put("map$values_checksum", new SqlVarbinary(new byte[] {0xc})) .put("map$cardinality_checksum", new SqlVarbinary(new byte[] {0x1d})) .put("map$cardinality_sum", 3L) .build()); assertMismatchedColumns(columns, controlChecksum, testChecksum, MAP_COLUMN); // Mismatched cardinality sum testChecksum = new ChecksumResult( 5, ImmutableMap.<String, Object>builder() .put("map$checksum", new SqlVarbinary(new byte[] {0xa})) .put("map$keys_checksum", new SqlVarbinary(new byte[] {0xb})) .put("map$values_checksum", new SqlVarbinary(new byte[] {0xc})) .put("map$cardinality_checksum", new SqlVarbinary(new byte[] {0xd})) .put("map$cardinality_sum", 4L) .build()); assertMismatchedColumns(columns, controlChecksum, testChecksum, MAP_COLUMN); } private List<ColumnMatchResult<?>> assertMismatchedColumns(List<Column> columns, ChecksumResult controlChecksum, ChecksumResult testChecksum, Column... expected) { List<ColumnMatchResult<?>> mismatchedColumns = ImmutableList.copyOf(checksumValidator.getMismatchedColumns(columns, controlChecksum, testChecksum)); List<Column> actual = mismatchedColumns.stream() .map(ColumnMatchResult::getColumn) .collect(toImmutableList()); assertEquals(actual, asList(expected)); return mismatchedColumns; } //ImmutableMap.builder() does not allow overlapping keys private Map<String, Object> merge(Map<String, Object> origin, Map<String, Object> layer) { HashMap<String, Object> result = new HashMap<>(origin); result.putAll(layer); return result; } private static Column createColumn(String name, Type type) { return Column.create(name, delimitedIdentifier(name), type); } }
apache-2.0
tensorflow/federated
tensorflow_federated/python/core/test/static_assert_test.py
4045
# Copyright 2020, The TensorFlow Federated 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. from absl.testing import absltest from tensorflow_federated.python.core.api import computations from tensorflow_federated.python.core.impl.federated_context import intrinsics from tensorflow_federated.python.core.impl.types import placements from tensorflow_federated.python.core.test import static_assert @computations.federated_computation def no_aggregation(): return () @computations.federated_computation def secure_aggregation(): data_at_clients = intrinsics.federated_value(1, placements.CLIENTS) bitwidth = 1 return intrinsics.federated_secure_sum_bitwidth(data_at_clients, bitwidth) @computations.federated_computation def unsecure_aggregation(): data_at_clients = intrinsics.federated_value(1, placements.CLIENTS) return intrinsics.federated_sum(data_at_clients) @computations.federated_computation def secure_and_unsecure_aggregation(): return (secure_aggregation, unsecure_aggregation) class AssertContainsSecAggTest(absltest.TestCase): def test_fails_on_noagg(self): with self.assertRaises(AssertionError): static_assert.assert_contains_secure_aggregation(no_aggregation) def test_passes_on_secagg(self): static_assert.assert_contains_secure_aggregation(secure_aggregation) def test_fails_on_unsecagg(self): with self.assertRaises(AssertionError): static_assert.assert_contains_secure_aggregation(unsecure_aggregation) def test_passes_on_bothagg(self): static_assert.assert_contains_secure_aggregation( secure_and_unsecure_aggregation) class AssertNotContainsSecAggTest(absltest.TestCase): def test_passes_on_noagg(self): static_assert.assert_not_contains_secure_aggregation(no_aggregation) def test_fails_on_secagg(self): with self.assertRaises(AssertionError): static_assert.assert_not_contains_secure_aggregation(secure_aggregation) def test_passes_on_unsecagg(self): static_assert.assert_not_contains_secure_aggregation(unsecure_aggregation) def test_fails_on_bothagg(self): with self.assertRaises(AssertionError): static_assert.assert_not_contains_secure_aggregation( secure_and_unsecure_aggregation) class AssertContainsUnsecAggTest(absltest.TestCase): def test_fails_on_noagg(self): with self.assertRaises(AssertionError): static_assert.assert_contains_unsecure_aggregation(no_aggregation) def test_fails_on_secagg(self): with self.assertRaises(AssertionError): static_assert.assert_contains_unsecure_aggregation(secure_aggregation) def test_passes_on_unsecagg(self): static_assert.assert_contains_unsecure_aggregation(unsecure_aggregation) def test_passes_on_bothagg(self): static_assert.assert_contains_unsecure_aggregation( secure_and_unsecure_aggregation) class AssertNotContainsUnsecAggTest(absltest.TestCase): def test_passes_on_noagg(self): static_assert.assert_not_contains_unsecure_aggregation(no_aggregation) def test_passes_on_secagg(self): static_assert.assert_not_contains_unsecure_aggregation(secure_aggregation) def test_fails_on_unsecagg(self): with self.assertRaises(AssertionError): static_assert.assert_not_contains_unsecure_aggregation( unsecure_aggregation) def test_fails_on_bothagg(self): with self.assertRaises(AssertionError): static_assert.assert_not_contains_unsecure_aggregation( secure_and_unsecure_aggregation) if __name__ == '__main__': absltest.main()
apache-2.0
mperdeck/cgtcalculator
cgtcalculator/cgtcalculator/Calculator.cs
4204
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace cgtcalculator { public class Calculator { public static List<ResultCsv> Calculate(List<Transaction> transactions) { return CalculateGainsPerShare(transactions); } public static List<ResultCsv> CalculateGainsPerShare(List<Transaction> transactions) { List<Transaction> sales = transactions.Where(t => t.Amount > 0).OrderBy(t => t.TransactionDate).ToList(); List<Transaction> buys = transactions.Where(t => t.Amount <= 0).OrderBy(t => t.TransactionDate).ToList(); List<ResultCsv> results = new List<ResultCsv>(); foreach (Transaction sale in sales) { var saleResultCsv = new ResultCsv(sale.TransactionDate, sale.ShareCode, sale.Reference, sale.Quantity, sale.Amount, sale.Quantity, sale.Amount); results.Add(saleResultCsv); // ------ List<Transaction> potentialMatchingBuys = buys.Where(t => (t.TransactionDate <= sale.TransactionDate) && (t.ShareCode == sale.ShareCode)).OrderBy(t => t.TransactionDate).ToList(); int nbrPotentialMatches = potentialMatchingBuys.Count(); int quantityToBeMatched = sale.Quantity; decimal gain = sale.Amount; DateTime earliestMatchingBuy = DateTime.MaxValue; for (int i = 0; (i < nbrPotentialMatches) && (quantityToBeMatched > 0); i++) { Transaction potentialMatch = potentialMatchingBuys[i]; if (potentialMatch.Quantity != 0) { decimal amount = 0; int quantity = 0; if (potentialMatch.Quantity > quantityToBeMatched) { // Quantity of this buy exceeds quantity that was still to be matched. quantity = quantityToBeMatched; amount = potentialMatch.Amount * ((decimal)quantity / (decimal)potentialMatch.Quantity); } else { amount = potentialMatch.Amount; quantity = potentialMatch.Quantity; } gain += amount; quantityToBeMatched -= quantity; if (earliestMatchingBuy > potentialMatch.TransactionDate) { earliestMatchingBuy = potentialMatch.TransactionDate; } // ---------- var buyResultCsv = new ResultCsv(potentialMatch.TransactionDate, potentialMatch.ShareCode, potentialMatch.Reference, potentialMatch.Quantity, potentialMatch.Amount, quantity, amount); results.Add(buyResultCsv); // Adjust quantity so this match will taken into account for subsequent matches potentialMatch.Quantity -= quantity; } } if (quantityToBeMatched > 0) { // Not enough buys to match the sale var errorResultCsv = new ResultCsv(null, null, string.Format("*** Not Matched: {0} ***", quantityToBeMatched), null, null, null, null); results.Add(errorResultCsv); } else { TimeSpan periodShareHeld = saleResultCsv.TransactionDate.Value - earliestMatchingBuy; bool attractsDiscount = (periodShareHeld.TotalDays > 366) && (gain > 0); saleResultCsv.SetTotals(gain, attractsDiscount); } // ------------------ ResultCsv emptyResultCsv = new ResultCsv(null, null, null, null, null, null, null); results.Add(emptyResultCsv); } return results; } } }
apache-2.0
spring-cloud/spring-cloud-stream
spring-cloud-stream/src/test/java/org/springframework/cloud/stream/binder/InputOutputBindingOrderTest.java
3677
/* * Copyright 2015-2022 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.stream.binder; import java.util.function.Function; import org.junit.Test; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.WebApplicationType; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.SmartLifecycle; import org.springframework.context.annotation.Bean; import org.springframework.messaging.MessageChannel; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; /** * @author Marius Bogoevici * @author Ilayaperumal Gopinathan * @author Janne Valkealahti * @author Soby Chacko */ public class InputOutputBindingOrderTest { @SuppressWarnings({ "rawtypes", "unchecked" }) @Test public void testInputOutputBindingOrder() { ConfigurableApplicationContext applicationContext = new SpringApplicationBuilder( TestSource.class).web(WebApplicationType.NONE).run( "--spring.cloud.stream.defaultBinder=mock", "--spring.jmx.enabled=false"); Binder binder = applicationContext.getBean(BinderFactory.class).getBinder(null, MessageChannel.class); // input is bound after the context has been started verify(binder).bindConsumer(eq("processor-in-0"), isNull(), Mockito.any(MessageChannel.class), Mockito.any()); SomeLifecycle someLifecycle = applicationContext.getBean(SomeLifecycle.class); assertThat(someLifecycle.isRunning()); applicationContext.close(); assertThat(someLifecycle.isRunning()).isFalse(); applicationContext.close(); } @EnableAutoConfiguration public static class TestSource { @Bean public SomeLifecycle someLifecycle() { return new SomeLifecycle(); } @Bean public Function<String, String> processor() { return s -> s; } } public static class SomeLifecycle implements SmartLifecycle { @Autowired private BinderFactory binderFactory; private boolean running; @Override @SuppressWarnings({ "rawtypes", "unchecked" }) public synchronized void start() { Binder binder = this.binderFactory.getBinder(null, MessageChannel.class); verify(binder).bindProducer(eq("processor-out-0"), Mockito.any(MessageChannel.class), Mockito.any()); // input was not bound yet verifyNoMoreInteractions(binder); this.running = true; } @Override public synchronized void stop() { this.running = false; } @Override public synchronized boolean isRunning() { return this.running; } @Override public boolean isAutoStartup() { return true; } @Override public void stop(Runnable callback) { stop(); if (callback != null) { callback.run(); } } @Override public int getPhase() { return 0; } } }
apache-2.0
ionutbarau/petstore
petstore-app/src/main/resources/static/node_modules/bower/lib/node_modules/osenv/test/windows.js
2540
// only run this test on windows // pretending to be another platform is too hacky, since it breaks // how the underlying system looks up module paths and runs // child processes, and all that stuff is cached. if (process.platform !== 'win32') { console.log('TAP version 13\n' + '1..0 # Skip windows tests, this is not windows\n') return } // load this before clubbing the platform name. var tap = require('tap') process.env.windir = 'c:\\windows' process.env.USERDOMAIN = 'some-domain' process.env.USERNAME = 'sirUser' process.env.USERPROFILE = 'C:\\Users\\sirUser' process.env.COMPUTERNAME = 'my-machine' process.env.TMPDIR = 'C:\\tmpdir' process.env.TMP = 'C:\\tmp' process.env.TEMP = 'C:\\temp' process.env.Path = 'C:\\Program Files\\;C:\\Binary Stuff\\bin' process.env.PROMPT = '(o_o) $ ' process.env.EDITOR = 'edit' process.env.VISUAL = 'visualedit' process.env.ComSpec = 'some-com' tap.test('basic windows sanity test', function (t) { var osenv = require('../osenv.js') t.equal(osenv.user(), process.env.USERDOMAIN + '\\' + process.env.USERNAME) t.equal(osenv.home(), process.env.USERPROFILE) t.equal(osenv.hostname(), process.env.COMPUTERNAME) t.same(osenv.path(), process.env.Path.split(';')) t.equal(osenv.prompt(), process.env.PROMPT) t.equal(osenv.tmpdir(), process.env.TMPDIR) // mildly evil, but it's for a test. process.env.TMPDIR = '' delete require.cache[require.resolve('../osenv.js')] var osenv = require('../osenv.js') t.equal(osenv.tmpdir(), process.env.TMP) process.env.TMP = '' delete require.cache[require.resolve('../osenv.js')] var osenv = require('../osenv.js') t.equal(osenv.tmpdir(), process.env.TEMP) process.env.TEMP = '' delete require.cache[require.resolve('../osenv.js')] var osenv = require('../osenv.js') osenv.home = function () { return null } t.equal(osenv.tmpdir(), 'c:\\windows\\temp') t.equal(osenv.editor(), 'edit') process.env.EDITOR = '' delete require.cache[require.resolve('../osenv.js')] var osenv = require('../osenv.js') t.equal(osenv.editor(), 'visualedit') process.env.VISUAL = '' delete require.cache[require.resolve('../osenv.js')] var osenv = require('../osenv.js') t.equal(osenv.editor(), 'notepad.exe') t.equal(osenv.shell(), 'some-com') process.env.ComSpec = '' delete require.cache[require.resolve('../osenv.js')] var osenv = require('../osenv.js') t.equal(osenv.shell(), 'cmd') t.end() })
apache-2.0
LivotovLabs/SORM
sorm-sample/src/main/java/com/example/sorm/sormexample/DbUtils.java
2162
package com.example.sorm.sormexample; import android.content.Context; import java.util.List; import eu.livotov.labs.android.sorm.EntityManager; import eu.livotov.labs.android.sorm.EntityManagerFactory; import eu.livotov.labs.android.sorm.core.config.EntityManagerConfiguration; public class DbUtils { // If you use gradle build variants, provide package name manually. Since it differs from application id public static void init(Context context) { EntityManagerConfiguration configuration = new EntityManagerConfiguration(); configuration.setEntitiesPackage(BuildConfig.PACKAGE_NAME); EntityManagerFactory.getEntityManager(context, configuration); } private static EntityManager em(Context c) { return EntityManagerFactory.getEntityManager(c); } public static long saveCard(Context c, Card card) { em(c).create(card); saveActions(c, card); return card.id; } private static void saveActions(Context c, Card card) { for (Action action : card.actions) { action.cardId = card.id; em(c).create(action); } } private static List<Action> getActions(Context c, long cardId) { return em(c).createQuery(Action.class).where("CARD_ID").isEqualTo(cardId).load(); } public static Card getCardById(Context c, long id) { Card card = em(c).find(Card.class, id); card.actions = getActions(c, card.id); return card; } public static Card getCard(Context c, String guid) { Card card = em(c).createQuery(Card.class).where("GUID").isEqualTo(guid).loadSingle(); card.actions = getActions(c, card.id); return card; } public static void updateCard(Context c, Card card) { em(c).save(card); deleteActions(c, card.id); saveActions(c, card); } private static void deleteActions(Context c, long cardId) { em(c).createQuery(Action.class).where("CARD_ID").isEqualTo(cardId).delete(); } public static void deleteCard(Context c, long id) { deleteActions(c, id); em(c).delete(Card.class, id); } }
apache-2.0
hmrc/amls-frontend
test/views/businessdetails/registered_office_ukSpec.scala
2766
/* * Copyright 2021 HM Revenue & Customs * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package views.businessdetails import forms.{EmptyForm, Form2, InvalidForm, ValidForm} import jto.validation.{Path, ValidationError} import models.businessdetails.{RegisteredOffice, RegisteredOfficeUK} import org.scalatest.MustMatchers import play.api.i18n.Messages import utils.{AmlsViewSpec, AutoCompleteServiceMocks} import views.Fixture import views.html.businessdetails.registered_office_uk class registered_office_ukSpec extends AmlsViewSpec with MustMatchers { trait ViewFixture extends Fixture with AutoCompleteServiceMocks { lazy val registered_office_uk = app.injector.instanceOf[registered_office_uk] implicit val requestWithToken = addTokenForView() } "registered_office view" must { "have correct title" in new ViewFixture { val form2: ValidForm[RegisteredOffice] = Form2(RegisteredOfficeUK("line1","line2",None,None,"AB12CD")) def view = registered_office_uk(form2, true) doc.title must startWith(Messages("businessdetails.registeredoffice.where.title") + " - " + Messages("summary.businessdetails")) } "have correct headings" in new ViewFixture { val form2: ValidForm[RegisteredOffice] = Form2(RegisteredOfficeUK("line1","line2",None,None,"AB12CD")) def view = registered_office_uk(form2, true) heading.html must be(Messages("businessdetails.registeredoffice.where.title")) subHeading.html must include(Messages("summary.businessdetails")) } "show errors in the correct locations" in new ViewFixture { val form2: InvalidForm = InvalidForm(Map.empty, Seq( (Path \ "postCode-fieldset") -> Seq(ValidationError("not a message Key")) )) def view = registered_office_uk(form2, true) errorSummary.html() must include("not a message Key") doc.getElementById("postCode-fieldset") .getElementsByClass("error-notification").first().html() must include("not a message Key") } "have a back link" in new ViewFixture { val form2: Form2[_] = EmptyForm def view = registered_office_uk(form2, true) doc.getElementsByAttributeValue("class", "link-back") must not be empty } } }
apache-2.0