code
stringlengths 2
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 4
991
| language
stringclasses 9
values | license
stringclasses 15
values | size
int32 2
1.05M
|
---|---|---|---|---|---|
class Catalog::PlatformsController < Base::PlatformsController
before_filter :find_catalog_and_platform
def index
@platforms = Cms::Relation.all(:params => {:ciId => @catalog.ciId,
:direction => 'from',
:targetClassName => 'catalog.Platform',
:relatioShortnName => 'ComposedOf'}).map(&:toCi)
render :json => @platforms
end
private
def find_catalog_and_platform
@catalog = Cms::Ci.locate(params[:catalog_id], catalogs_ns_path, 'account.Design') ||
Cms::Ci.locate(params[:catalog_id], private_catalogs_ns_path, 'account.Design')
platform_id = params[:id]
if platform_id.present?
@platform = Cms::Ci.locate(platform_id, catalog_ns_path(@catalog), 'catalog.Platform')
@platform = nil if @platform && @platform.ciClassName != 'catalog.Platform'
end
end
end
| subaan/display | app/controllers/catalog/platforms_controller.rb | Ruby | apache-2.0 | 991 |
package com.mesosphere.sdk.specification.yaml;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Raw YAML port.
*/
public class RawPort {
private final Integer port;
private final String envKey;
private final RawVip vip;
private RawPort(
@JsonProperty("port") Integer port,
@JsonProperty("env-key") String envKey,
@JsonProperty("vip") RawVip vip) {
this.port = port;
this.envKey = envKey;
this.vip = vip;
}
public Integer getPort() {
return port;
}
public String getEnvKey() {
return envKey;
}
public RawVip getVip() {
return vip;
}
}
| adragomir/dcos-commons | sdk/scheduler/src/main/java/com/mesosphere/sdk/specification/yaml/RawPort.java | Java | apache-2.0 | 682 |
#
# Copyright (C) 2014 Dell, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import sys
PYTHON26 = sys.version_info < (2, 7)
if PYTHON26:
import unittest2 as unittest
else:
import unittest
__all__ = ['unittest']
| aidanhs/blockade | blockade/tests/__init__.py | Python | apache-2.0 | 731 |
/// Copyright (c) 2009 Microsoft Corporation
///
/// 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 Microsoft 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 OWNER 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.
ES5Harness.registerTest({
id: "15.10.4.1-2",
path: "TestCases/chapter15/15.10/15.10.4/15.10.4.1-2.js",
description: "RegExp - the thrown error is SyntaxError instead of RegExpError when the characters of 'P' do not have the syntactic form Pattern",
test: function testcase() {
try {
var regExpObj = new RegExp('\\');
return false;
} catch (e) {
return e instanceof SyntaxError;
}
},
precondition: function prereq() {
return true;
}
});
| hnafar/IronJS | Src/Tests/ietestcenter/chapter15/15.10/15.10.4/15.10.4.1-2.js | JavaScript | apache-2.0 | 2,097 |
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Disposable, Command, EventEmitter, Event, workspace, Uri } from 'vscode';
import { Repository, Operation } from './repository';
import { anyEvent, dispose, filterEvent } from './util';
import * as nls from 'vscode-nls';
import { Branch } from './api/git';
const localize = nls.loadMessageBundle();
class CheckoutStatusBar {
private _onDidChange = new EventEmitter<void>();
get onDidChange(): Event<void> { return this._onDidChange.event; }
private disposables: Disposable[] = [];
constructor(private repository: Repository) {
repository.onDidRunGitStatus(this._onDidChange.fire, this._onDidChange, this.disposables);
}
get command(): Command | undefined {
const rebasing = !!this.repository.rebaseCommit;
const title = `$(git-branch) ${this.repository.headLabel}${rebasing ? ` (${localize('rebasing', 'Rebasing')})` : ''}`;
return {
command: 'git.checkout',
tooltip: `${this.repository.headLabel}`,
title,
arguments: [this.repository.sourceControl]
};
}
dispose(): void {
this.disposables.forEach(d => d.dispose());
}
}
interface SyncStatusBarState {
enabled: boolean;
isSyncRunning: boolean;
hasRemotes: boolean;
HEAD: Branch | undefined;
}
class SyncStatusBar {
private static StartState: SyncStatusBarState = {
enabled: true,
isSyncRunning: false,
hasRemotes: false,
HEAD: undefined
};
private _onDidChange = new EventEmitter<void>();
get onDidChange(): Event<void> { return this._onDidChange.event; }
private disposables: Disposable[] = [];
private _state: SyncStatusBarState = SyncStatusBar.StartState;
private get state() { return this._state; }
private set state(state: SyncStatusBarState) {
this._state = state;
this._onDidChange.fire();
}
constructor(private repository: Repository) {
repository.onDidRunGitStatus(this.onModelChange, this, this.disposables);
repository.onDidChangeOperations(this.onOperationsChange, this, this.disposables);
const onEnablementChange = filterEvent(workspace.onDidChangeConfiguration, e => e.affectsConfiguration('git.enableStatusBarSync'));
onEnablementChange(this.updateEnablement, this, this.disposables);
this.updateEnablement();
this._onDidChange.fire();
}
private updateEnablement(): void {
const config = workspace.getConfiguration('git', Uri.file(this.repository.root));
const enabled = config.get<boolean>('enableStatusBarSync', true);
this.state = { ... this.state, enabled };
}
private onOperationsChange(): void {
const isSyncRunning = this.repository.operations.isRunning(Operation.Sync) ||
this.repository.operations.isRunning(Operation.Push) ||
this.repository.operations.isRunning(Operation.Pull);
this.state = { ...this.state, isSyncRunning };
}
private onModelChange(): void {
this.state = {
...this.state,
hasRemotes: this.repository.remotes.length > 0,
HEAD: this.repository.HEAD
};
}
get command(): Command | undefined {
if (!this.state.enabled || !this.state.hasRemotes) {
return undefined;
}
const HEAD = this.state.HEAD;
let icon = '$(sync)';
let text = '';
let command = '';
let tooltip = '';
if (HEAD && HEAD.name && HEAD.commit) {
if (HEAD.upstream) {
if (HEAD.ahead || HEAD.behind) {
text += this.repository.syncLabel;
}
const config = workspace.getConfiguration('git', Uri.file(this.repository.root));
const rebaseWhenSync = config.get<string>('rebaseWhenSync');
command = rebaseWhenSync ? 'git.syncRebase' : 'git.sync';
tooltip = localize('sync changes', "Synchronize Changes");
} else {
icon = '$(cloud-upload)';
command = 'git.publish';
tooltip = localize('publish changes', "Publish Changes");
}
} else {
command = '';
tooltip = '';
}
if (this.state.isSyncRunning) {
icon = '$(sync~spin)';
command = '';
tooltip = localize('syncing changes', "Synchronizing Changes...");
}
return {
command,
title: [icon, text].join(' ').trim(),
tooltip,
arguments: [this.repository.sourceControl]
};
}
dispose(): void {
this.disposables.forEach(d => d.dispose());
}
}
export class StatusBarCommands {
private syncStatusBar: SyncStatusBar;
private checkoutStatusBar: CheckoutStatusBar;
private disposables: Disposable[] = [];
constructor(repository: Repository) {
this.syncStatusBar = new SyncStatusBar(repository);
this.checkoutStatusBar = new CheckoutStatusBar(repository);
}
get onDidChange(): Event<void> {
return anyEvent(
this.syncStatusBar.onDidChange,
this.checkoutStatusBar.onDidChange
);
}
get commands(): Command[] {
const result: Command[] = [];
const checkout = this.checkoutStatusBar.command;
if (checkout) {
result.push(checkout);
}
const sync = this.syncStatusBar.command;
if (sync) {
result.push(sync);
}
return result;
}
dispose(): void {
this.syncStatusBar.dispose();
this.checkoutStatusBar.dispose();
this.disposables = dispose(this.disposables);
}
}
| leafclick/intellij-community | plugins/textmate/lib/bundles/git/src/statusbar.ts | TypeScript | apache-2.0 | 5,303 |
/**
* Copyright 2012 Comcast Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.comcast.cns.controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import com.amazonaws.services.sns.model.GetSubscriptionAttributesRequest;
import com.amazonaws.services.sns.model.GetSubscriptionAttributesResult;
import com.amazonaws.services.sns.model.SetSubscriptionAttributesRequest;
import com.comcast.cmb.common.controller.AdminServletBase;
import com.comcast.cmb.common.controller.CMBControllerServlet;
/**
* Admin page for editing subscription delivery policy
* @author tina, aseem, bwolf
*
*/
public class CNSRawMessageDeliveryPolicyPage extends AdminServletBase {
private static final long serialVersionUID = 1L;
private static Logger logger = Logger.getLogger(CNSRawMessageDeliveryPolicyPage.class);
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if (redirectUnauthenticatedUser(request, response)) {
return;
}
CMBControllerServlet.valueAccumulator.initializeAllCounters();
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String subArn = request.getParameter("subscriptionArn");
String userId = request.getParameter("userId");
Map<?, ?> params = request.getParameterMap();
connect(request);
out.println("<html>");
simpleHeader(request, out, "Raw Message Delivery Policy");
if (params.containsKey("Update")) {
String rawMessageDeliveryParam = request.getParameter("rawmessage");
Boolean rawMessageDelivery = false;
if (rawMessageDeliveryParam.trim().length() > 0) {
rawMessageDelivery = Boolean.parseBoolean(rawMessageDeliveryParam.trim());
}
try {
SetSubscriptionAttributesRequest setSubscriptionAttributesRequest = new SetSubscriptionAttributesRequest(subArn, "RawMessageDelivery", rawMessageDelivery.toString());
sns.setSubscriptionAttributes(setSubscriptionAttributesRequest);
logger.debug("event=set_raw_message_delivery_policy sub_arn=" + subArn + " user_id= " + userId);
} catch (Exception ex) {
logger.error("event=set_raw_message_delivery_policy sub_arn=" + subArn + " user_id= " + userId, ex);
throw new ServletException(ex);
}
out.println("<body onload='javascript:window.opener.location.reload();window.close();'>");
} else {
Boolean rawMessageDelivery = false;
if (subArn != null) {
Map<String, String> attributes = null;
try {
GetSubscriptionAttributesRequest getSubscriptionAttributesRequest = new GetSubscriptionAttributesRequest(subArn);
GetSubscriptionAttributesResult getSubscriptionAttributesResult = sns.getSubscriptionAttributes(getSubscriptionAttributesRequest);
attributes = getSubscriptionAttributesResult.getAttributes();
String rawMessageDeliveryStr = attributes.get("RawMessageDelivery");
if(rawMessageDeliveryStr != null && !rawMessageDeliveryStr.isEmpty()){
rawMessageDelivery = Boolean.parseBoolean(rawMessageDeliveryStr);
}
} catch (Exception ex) {
logger.error("event=get_raw_message_delivery_attribute sub_arn=" + subArn + " user_id= " + userId, ex);
throw new ServletException(ex);
}
}
out.println("<body>");
out.println("<h1>Raw Message Delivery Policy</h1>");
out.println("<form action=\"/webui/cnsuser/subscription/rawmessagedeliverypolicy?subscriptionArn="+subArn+"\" method=POST>");
out.println("<input type='hidden' name='userId' value='"+ userId +"'>");
out.println("<table width='98%'");
out.println("<tr><td colspan=2><b><font color='orange'>Raw Message Delivery</font></b></td></tr>");
out.println("<tr><td ><input type='radio' name='rawmessage' value='true' " + (rawMessageDelivery?"checked='true'":"") + ">True</td>");
out.println("<td ><input type='radio' name='rawmessage' value='false' " + (rawMessageDelivery?"":"checked='true'") + ">False</td></tr>");
out.println("<tr><td> </td><td> </td></tr>");
out.println("<tr><td colspan=2><hr/></td></tr>");
out.println("<tr><td colspan=2 align=right><input type='button' onclick='window.close()' value='Cancel'><input type='submit' name='Update' value='Update'></td></tr></table></form>");
}
out.println("</body></html>");
CMBControllerServlet.valueAccumulator.deleteAllCounters();
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
| KrithikaGanesh/cmb | src/com/comcast/cns/controller/CNSRawMessageDeliveryPolicyPage.java | Java | apache-2.0 | 5,387 |
/*
* 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.spark.examples.ml;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.sql.SQLContext;
// $example on$
import java.util.Arrays;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.ml.feature.PolynomialExpansion;
import org.apache.spark.mllib.linalg.VectorUDT;
import org.apache.spark.mllib.linalg.Vectors;
import org.apache.spark.sql.DataFrame;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.RowFactory;
import org.apache.spark.sql.types.Metadata;
import org.apache.spark.sql.types.StructField;
import org.apache.spark.sql.types.StructType;
// $example off$
public class JavaPolynomialExpansionExample {
public static void main(String[] args) {
SparkConf conf = new SparkConf().setAppName("JavaPolynomialExpansionExample");
JavaSparkContext jsc = new JavaSparkContext(conf);
SQLContext jsql = new SQLContext(jsc);
// $example on$
PolynomialExpansion polyExpansion = new PolynomialExpansion()
.setInputCol("features")
.setOutputCol("polyFeatures")
.setDegree(3);
JavaRDD<Row> data = jsc.parallelize(Arrays.asList(
RowFactory.create(Vectors.dense(-2.0, 2.3)),
RowFactory.create(Vectors.dense(0.0, 0.0)),
RowFactory.create(Vectors.dense(0.6, -1.1))
));
StructType schema = new StructType(new StructField[]{
new StructField("features", new VectorUDT(), false, Metadata.empty()),
});
DataFrame df = jsql.createDataFrame(data, schema);
DataFrame polyDF = polyExpansion.transform(df);
Row[] row = polyDF.select("polyFeatures").take(3);
for (Row r : row) {
System.out.println(r.get(0));
}
// $example off$
jsc.stop();
}
} | chenc10/Spark-PAF | examples/src/main/java/org/apache/spark/examples/ml/JavaPolynomialExpansionExample.java | Java | apache-2.0 | 2,545 |
/*
* JBoss, Home of Professional Open Source
* Copyright 2009 Red Hat Inc. and/or its affiliates and other
* contributors as indicated by the @author tags. All rights reserved.
* See the copyright.txt in the distribution for a full listing of
* individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.infinispan.loaders.decorators;
import org.infinispan.Cache;
import org.infinispan.CacheException;
import org.infinispan.container.entries.InternalCacheEntry;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.infinispan.test.fwk.TestInternalCacheEntryFactory;
import org.infinispan.loaders.CacheLoaderConfig;
import org.infinispan.loaders.CacheLoaderException;
import org.infinispan.loaders.CacheLoaderMetadata;
import org.infinispan.loaders.CacheStore;
import org.infinispan.loaders.dummy.DummyInMemoryCacheStore;
import org.infinispan.loaders.modifications.Clear;
import org.infinispan.loaders.modifications.Modification;
import org.infinispan.loaders.modifications.Remove;
import org.infinispan.loaders.modifications.Store;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.test.AbstractInfinispanTest;
import org.infinispan.test.CacheManagerCallable;
import org.infinispan.test.TestingUtil;
import org.infinispan.transaction.xa.GlobalTransaction;
import org.infinispan.transaction.xa.TransactionFactory;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;
import static org.infinispan.test.TestingUtil.k;
import static org.infinispan.test.TestingUtil.v;
@Test(groups = "unit", testName = "loaders.decorators.AsyncStoreTest", sequential=true)
public class AsyncStoreTest extends AbstractInfinispanTest {
private static final Log log = LogFactory.getLog(AsyncStoreTest.class);
AsyncStore store;
ExecutorService asyncExecutor;
DummyInMemoryCacheStore underlying;
AsyncStoreConfig asyncConfig;
DummyInMemoryCacheStore.Cfg dummyCfg;
@BeforeMethod
public void setUp() throws CacheLoaderException {
underlying = new DummyInMemoryCacheStore();
asyncConfig = new AsyncStoreConfig().threadPoolSize(10);
store = new AsyncStore(underlying, asyncConfig);
dummyCfg = new DummyInMemoryCacheStore.Cfg().storeName(AsyncStoreTest.class.getName());
store.init(dummyCfg, null, null);
store.start();
asyncExecutor = (ExecutorService) TestingUtil.extractField(store, "executor");
}
@AfterMethod(alwaysRun = true)
public void tearDown() throws CacheLoaderException {
if (store != null) store.stop();
}
@Test(timeOut=10000)
public void testPutRemove() throws Exception {
TestCacheManagerFactory.backgroundTestStarted(this);
final int number = 1000;
String key = "testPutRemove-k-";
String value = "testPutRemove-v-";
doTestPut(number, key, value);
doTestRemove(number, key);
}
@Test(timeOut=10000)
public void testPutClearPut() throws Exception {
TestCacheManagerFactory.backgroundTestStarted(this);
final int number = 1000;
String key = "testPutClearPut-k-";
String value = "testPutClearPut-v-";
doTestPut(number, key, value);
doTestClear(number, key);
value = "testPutClearPut-v[2]-";
doTestPut(number, key, value);
doTestRemove(number, key);
}
@Test(timeOut=10000)
public void testMultiplePutsOnSameKey() throws Exception {
TestCacheManagerFactory.backgroundTestStarted(this);
final int number = 1000;
String key = "testMultiplePutsOnSameKey-k";
String value = "testMultiplePutsOnSameKey-v-";
doTestSameKeyPut(number, key, value);
doTestSameKeyRemove(key);
}
@Test(timeOut=10000)
public void testRestrictionOnAddingToAsyncQueue() throws Exception {
TestCacheManagerFactory.backgroundTestStarted(this);
store.remove("blah");
final int number = 10;
String key = "testRestrictionOnAddingToAsyncQueue-k";
String value = "testRestrictionOnAddingToAsyncQueue-v-";
doTestPut(number, key, value);
// stop the cache store
store.stop();
try {
store.store(null);
assert false : "Should have restricted this entry from being made";
}
catch (CacheException expected) {
}
// clean up
store.start();
doTestRemove(number, key);
}
public void testThreadSafetyWritingDiffValuesForKey(Method m) throws Exception {
try {
final String key = "k1";
final CountDownLatch v1Latch = new CountDownLatch(1);
final CountDownLatch v2Latch = new CountDownLatch(1);
final CountDownLatch endLatch = new CountDownLatch(1);
DummyInMemoryCacheStore underlying = new DummyInMemoryCacheStore();
store = new MockAsyncStore(key, v1Latch, v2Latch, endLatch, underlying, asyncConfig);
dummyCfg = new DummyInMemoryCacheStore.Cfg();
dummyCfg.setStoreName(m.getName());
store.init(dummyCfg, null, null);
store.start();
store.store(TestInternalCacheEntryFactory.create(key, "v1"));
v2Latch.await();
store.store(TestInternalCacheEntryFactory.create(key, "v2"));
endLatch.await();
assert store.load(key).getValue().equals("v2");
} finally {
store.delegate.clear();
store.stop();
store = null;
}
}
public void testTransactionalModificationsHappenInDiffThread(Method m) throws Exception {
final int waitTimeout = 10;
final TimeUnit waitUnit = TimeUnit.SECONDS;
try {
final TransactionFactory gtf = new TransactionFactory();
gtf.init(false, false, true, false);
final String k1 = k(m, 1), k2 = k(m, 2), v1 = v(m, 1), v2 = v(m, 2);
final ConcurrentMap<Object, Modification> localMods = new ConcurrentHashMap<Object, Modification>();
final CyclicBarrier barrier = new CyclicBarrier(2);
DummyInMemoryCacheStore underlying = new DummyInMemoryCacheStore();
store = new AsyncStore(underlying, asyncConfig) {
@Override
protected void applyModificationsSync(List<Modification> mods) throws CacheLoaderException {
for (Modification mod : mods)
localMods.put(getKey(mod), mod);
super.applyModificationsSync(mods);
try {
barrier.await(waitTimeout, waitUnit);
} catch (TimeoutException e) {
assert false : "Timed out applying for modifications";
} catch (Exception e) {
throw new CacheLoaderException("Barrier failed", e);
}
}
private Object getKey(Modification modification) {
switch (modification.getType()) {
case STORE:
return ((Store) modification).getStoredEntry().getKey();
case REMOVE:
return ((Remove) modification).getKey();
default:
return null;
}
}
};
dummyCfg = new DummyInMemoryCacheStore.Cfg();
dummyCfg.setStoreName(m.getName());
store.init(dummyCfg, null, null);
store.start();
List<Modification> mods = new ArrayList<Modification>();
mods.add(new Store(TestInternalCacheEntryFactory.create(k1, v1)));
mods.add(new Store(TestInternalCacheEntryFactory.create(k2, v2)));
mods.add(new Remove(k1));
GlobalTransaction tx = gtf.newGlobalTransaction(null, false);
store.prepare(mods, tx, false);
assert 0 == localMods.size();
assert !store.containsKey(k1);
assert !store.containsKey(k2);
store.commit(tx);
barrier.await(waitTimeout, waitUnit); // Wait for store
barrier.await(waitTimeout, waitUnit); // Wait for remove
assert store.load(k2).getValue().equals(v2);
assert !store.containsKey(k1);
assert 2 == localMods.size();
assert new Remove(k1).equals(localMods.get(k1));
} finally {
store.delegate.clear();
store.stop();
store = null;
}
}
public void testTransactionalModificationsAreCoalesced(Method m) throws Exception {
final int waitTimeout = 10;
final TimeUnit waitUnit = TimeUnit.SECONDS;
try {
final TransactionFactory gtf = new TransactionFactory();
gtf.init(false, false, true, false);
final String k1 = k(m, 1), k2 = k(m, 2), k3 = k(m, 3), v1 = v(m, 1), v2 = v(m, 2), v3 = v(m, 3);
final AtomicInteger storeCount = new AtomicInteger();
final AtomicInteger removeCount = new AtomicInteger();
final AtomicInteger clearCount = new AtomicInteger();
final CyclicBarrier barrier = new CyclicBarrier(2);
DummyInMemoryCacheStore underlying = new DummyInMemoryCacheStore() {
@Override
public void store(InternalCacheEntry ed) {
super.store(ed);
storeCount.getAndIncrement();
}
@Override
public boolean remove(Object key) {
boolean ret = super.remove(key);
removeCount.getAndIncrement();
return ret;
}
@Override
public void clear() {
super.clear();
clearCount.getAndIncrement();
}
};
store = new AsyncStore(underlying, asyncConfig) {
@Override
protected void applyModificationsSync(List<Modification> mods)
throws CacheLoaderException {
super.applyModificationsSync(mods);
try {
log.tracef("Wait to apply modifications: %s", mods);
barrier.await(waitTimeout, waitUnit);
} catch (TimeoutException e) {
assert false : "Timed out applying for modifications";
} catch (Exception e) {
throw new CacheLoaderException("Barrier failed", e);
}
}
};
dummyCfg = new DummyInMemoryCacheStore.Cfg();
dummyCfg.setStoreName(m.getName());
store.init(dummyCfg, null, null);
store.start();
List<Modification> mods = new ArrayList<Modification>();
mods.add(new Store(TestInternalCacheEntryFactory.create(k1, v1)));
mods.add(new Store(TestInternalCacheEntryFactory.create(k1, v2)));
mods.add(new Store(TestInternalCacheEntryFactory.create(k2, v1)));
mods.add(new Store(TestInternalCacheEntryFactory.create(k2, v2)));
mods.add(new Remove(k1));
GlobalTransaction tx = gtf.newGlobalTransaction(null, false);
store.prepare(mods, tx, false);
Thread.sleep(200); //verify that work is not performed until commit
assert 0 == storeCount.get();
assert 0 == removeCount.get();
assert 0 == clearCount.get();
store.commit(tx);
log.tracef("Wait for modifications to be queued: %s", mods);
barrier.await(waitTimeout, waitUnit); // Wait for single store to be applied
barrier.await(waitTimeout, waitUnit); // Wait for single remove to be applied
assert 1 == storeCount.get() : "Store count was " + storeCount.get();
assert 1 == removeCount.get();
assert 0 == clearCount.get();
storeCount.set(0);
removeCount.set(0);
clearCount.set(0);
mods = new ArrayList<Modification>();
mods.add(new Store(TestInternalCacheEntryFactory.create(k1, v1)));
mods.add(new Remove(k1));
mods.add(new Clear());
mods.add(new Store(TestInternalCacheEntryFactory.create(k2, v2)));
mods.add(new Remove(k2));
tx = gtf.newGlobalTransaction(null, false);
store.prepare(mods, tx, false);
Thread.sleep(200); //verify that work is not performed until commit
assert 0 == storeCount.get();
assert 0 == removeCount.get();
assert 0 == clearCount.get();
store.commit(tx);
barrier.await(waitTimeout, waitUnit);
assert 0 == storeCount.get() : "Store count was " + storeCount.get();
assert 1 == removeCount.get();
assert 1 == clearCount.get();
storeCount.set(0);
removeCount.set(0);
clearCount.set(0);
mods = new ArrayList<Modification>();
mods.add(new Store(TestInternalCacheEntryFactory.create(k1, v1)));
mods.add(new Remove(k1));
mods.add(new Store(TestInternalCacheEntryFactory.create(k2, v2)));
mods.add(new Remove(k2));
mods.add(new Store(TestInternalCacheEntryFactory.create(k3, v3)));
tx = gtf.newGlobalTransaction(null, false);
store.prepare(mods, tx, false);
Thread.sleep(200);
assert 0 == storeCount.get();
assert 0 == removeCount.get();
assert 0 == clearCount.get();
store.commit(tx);
barrier.await(waitTimeout, waitUnit); // Wait for store to be applied
barrier.await(waitTimeout, waitUnit); // Wait for first removal to be applied
barrier.await(waitTimeout, waitUnit); // Wait for second removal to be applied
assert 1 == storeCount.get() : "Store count was " + storeCount.get();
assert 2 == removeCount.get();
assert 0 == clearCount.get();
storeCount.set(0);
removeCount.set(0);
clearCount.set(0);
mods = new ArrayList<Modification>();
mods.add(new Clear());
mods.add(new Remove(k1));
tx = gtf.newGlobalTransaction(null, false);
store.prepare(mods, tx, false);
Thread.sleep(200);
assert 0 == storeCount.get();
assert 0 == removeCount.get();
assert 0 == clearCount.get();
store.commit(tx);
barrier.await(waitTimeout, waitUnit);
assert 0 == storeCount.get() : "Store count was " + storeCount.get();
assert 1 == removeCount.get();
assert 1 == clearCount.get();
storeCount.set(0);
removeCount.set(0);
clearCount.set(0);
mods = new ArrayList<Modification>();
mods.add(new Clear());
mods.add(new Store(TestInternalCacheEntryFactory.create(k1, v1)));
tx = gtf.newGlobalTransaction(null, false);
store.prepare(mods, tx, false);
Thread.sleep(200);
assert 0 == storeCount.get();
assert 0 == removeCount.get();
assert 0 == clearCount.get();
store.commit(tx);
barrier.await(waitTimeout, waitUnit);
assert 1 == storeCount.get() : "Store count was " + storeCount.get();
assert 0 == removeCount.get();
assert 1 == clearCount.get();
} finally {
store.delegate.clear();
store.stop();
store = null;
}
}
private void doTestPut(int number, String key, String value) throws Exception {
for (int i = 0; i < number; i++) {
InternalCacheEntry cacheEntry = TestInternalCacheEntryFactory.create(key + i, value + i);
store.store(cacheEntry);
}
for (int i = 0; i < number; i++) {
InternalCacheEntry ice = store.load(key + i);
assert ice != null && (value + i).equals(ice.getValue());
}
}
private void doTestSameKeyPut(int number, String key, String value) throws Exception {
for (int i = 0; i < number; i++) {
store.store(TestInternalCacheEntryFactory.create(key, value + i));
}
InternalCacheEntry ice = store.load(key);
assert ice != null && (value + (number - 1)).equals(ice.getValue());
}
private void doTestRemove(int number, String key) throws Exception {
for (int i = 0; i < number; i++) store.remove(key + i);
for (int i = 0; i < number; i++) {
String loadKey = key + i;
assert store.load(loadKey) == null : loadKey + " still in store";
}
}
private void doTestSameKeyRemove(String key) throws Exception {
store.remove(key);
assert store.load(key) == null;
}
private void doTestClear(int number, String key) throws Exception {
store.clear();
for (int i = 0; i < number; i++) {
assert store.load(key + i) == null;
}
}
static class MockAsyncStore extends AsyncStore {
volatile boolean block = true;
final CountDownLatch v1Latch;
final CountDownLatch v2Latch;
final CountDownLatch endLatch;
final Object key;
MockAsyncStore(Object key, CountDownLatch v1Latch, CountDownLatch v2Latch, CountDownLatch endLatch,
CacheStore delegate, AsyncStoreConfig asyncStoreConfig) {
super(delegate, asyncStoreConfig);
this.v1Latch = v1Latch;
this.v2Latch = v2Latch;
this.endLatch = endLatch;
this.key = key;
}
@Override
protected void applyModificationsSync(List<Modification> mods) throws CacheLoaderException {
boolean keyFound = findModificationForKey(key, mods) != null;
if (keyFound && block) {
log.trace("Wait for v1 latch");
try {
v2Latch.countDown();
block = false;
v1Latch.await(2, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
super.applyModificationsSync(mods);
} else if (keyFound && !block) {
log.trace("Do v2 modification and unleash v1 latch");
super.applyModificationsSync(mods);
v1Latch.countDown();
endLatch.countDown();
}
}
private Modification findModificationForKey(Object key, List<Modification> mods) {
for (Modification modification : mods) {
switch (modification.getType()) {
case STORE:
Store store = (Store) modification;
if (store.getStoredEntry().getKey().equals(key))
return store;
break;
case REMOVE:
Remove remove = (Remove) modification;
if (remove.getKey().equals(key))
return remove;
break;
default:
return null;
}
}
return null;
}
}
private final static ThreadLocal<LockableCacheStore> STORE = new ThreadLocal<LockableCacheStore>();
public static class LockableCacheStoreConfig extends DummyInMemoryCacheStore.Cfg {
private static final long serialVersionUID = 1L;
public LockableCacheStoreConfig() {
setCacheLoaderClassName(LockableCacheStore.class.getName());
}
}
@CacheLoaderMetadata(configurationClass = LockableCacheStoreConfig.class)
public static class LockableCacheStore extends DummyInMemoryCacheStore {
private final ReentrantLock lock = new ReentrantLock();
public LockableCacheStore() {
super();
STORE.set(this);
}
@Override
public Class<? extends CacheLoaderConfig> getConfigurationClass() {
return LockableCacheStoreConfig.class;
}
@Override
public void store(InternalCacheEntry ed) {
lock.lock();
try {
super.store(ed);
} finally {
lock.unlock();
}
}
@Override
public boolean remove(Object key) {
lock.lock();
try {
return super.remove(key);
} finally {
lock.unlock();
}
}
}
public void testModificationQueueSize(final Method m) throws Exception {
LockableCacheStore underlying = new LockableCacheStore();
asyncConfig.modificationQueueSize(10);
store = new AsyncStore(underlying, asyncConfig);
store.init(new LockableCacheStoreConfig(), null, null);
store.start();
try {
final CountDownLatch done = new CountDownLatch(1);
underlying.lock.lock();
try {
Thread t = new Thread() {
@Override
public void run() {
try {
for (int i = 0; i < 100; i++)
store.store(TestInternalCacheEntryFactory.create(k(m, i), v(m, i)));
} catch (Exception e) {
log.error("Error storing entry", e);
}
done.countDown();
}
};
t.start();
assert !done.await(1, TimeUnit.SECONDS) : "Background thread should have blocked after adding 10 entries";
} finally {
underlying.lock.unlock();
}
} finally {
store.stop();
}
}
private static abstract class OneEntryCacheManagerCallable extends CacheManagerCallable {
protected final Cache<String, String> cache;
protected final LockableCacheStore store;
private static ConfigurationBuilder config(boolean passivation) {
ConfigurationBuilder config = new ConfigurationBuilder();
config.eviction().maxEntries(1).loaders().passivation(passivation).addStore()
.cacheStore(new LockableCacheStore()).async().enable();
return config;
}
OneEntryCacheManagerCallable(boolean passivation) {
super(TestCacheManagerFactory.createCacheManager(config(passivation)));
cache = cm.getCache();
store = STORE.get();
}
}
public void testEndToEndPutPutPassivation() throws Exception {
doTestEndToEndPutPut(true);
}
public void testEndToEndPutPut() throws Exception {
doTestEndToEndPutPut(false);
}
private void doTestEndToEndPutPut(boolean passivation) throws Exception {
TestingUtil.withCacheManager(new OneEntryCacheManagerCallable(passivation) {
@Override
public void call() {
cache.put("X", "1");
cache.put("Y", "1"); // force eviction of "X"
// wait for X == 1 to appear in store
while (store.load("X") == null)
TestingUtil.sleepThread(10);
// simulate slow back end store
store.lock.lock();
try {
cache.put("X", "2");
cache.put("Y", "2"); // force eviction of "X"
assert "2".equals(cache.get("X")) : "cache must return X == 2";
} finally {
store.lock.unlock();
}
}
});
}
public void testEndToEndPutRemovePassivation() throws Exception {
doTestEndToEndPutRemove(true);
}
public void testEndToEndPutRemove() throws Exception {
doTestEndToEndPutRemove(false);
}
private void doTestEndToEndPutRemove(boolean passivation) throws Exception {
TestingUtil.withCacheManager(new OneEntryCacheManagerCallable(passivation) {
@Override
public void call() {
cache.put("X", "1");
cache.put("Y", "1"); // force eviction of "X"
// wait for "X" to appear in store
while (store.load("X") == null)
TestingUtil.sleepThread(10);
// simulate slow back end store
store.lock.lock();
try {
cache.remove("X");
assert null == cache.get("X") : "cache must return X == null";
} finally {
store.lock.unlock();
}
}
});
}
}
| nmldiegues/stibt | infinispan/core/src/test/java/org/infinispan/loaders/decorators/AsyncStoreTest.java | Java | apache-2.0 | 24,964 |
/*
* Copyright (c) 2010-2015 Pivotal Software, 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. See accompanying
* LICENSE file.
*/
package versioning.newWan;
import versioning.VersionBB;
import newWan.WANOperationsClientBB;
import hydra.Log;
import com.gemstone.gemfire.LogWriter;
import com.gemstone.gemfire.cache.util.GatewayConflictHelper;
import com.gemstone.gemfire.cache.util.GatewayConflictResolver;
import com.gemstone.gemfire.cache.util.TimestampedEntryEvent;
import com.gemstone.gemfire.pdx.PdxInstance;
/**
* Custom wan conflict resolver
* @author rdiyewar
*
*/
public class WANConflictResolver implements GatewayConflictResolver {
LogWriter log = Log.getLogWriter();
WANOperationsClientBB bb = WANOperationsClientBB.getBB();
public void onEvent(TimestampedEntryEvent event, GatewayConflictHelper helper) {
bb.getSharedCounters().increment(WANOperationsClientBB.WanEventResolved);
log.info("WANConflictResolver: existing timestamp=" + event.getOldTimestamp() + " existing value=" + event.getOldValue()
+ "\n proposed timestamp=" + event.getNewTimestamp() + " proposed value=" + event.getNewValue());
// use the default timestamp and ID based resolution
if (event.getOldTimestamp() > event.getNewTimestamp()) {
log.info("New event is older, disallow the event " + event);
helper.disallowEvent();
}
if (event.getOldTimestamp() == event.getNewTimestamp()
&& event.getOldDistributedSystemID() > event.getNewDistributedSystemID()) {
log.info("Both event has same timestamp, but new event's ds id small. Thus dissallow the event " + event);
helper.disallowEvent();
}
}
}
| papicella/snappy-store | tests/core/src/main/java/versioning/newWan/WANConflictResolver.java | Java | apache-2.0 | 2,212 |
/*
* 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.beam.sdk.io.kinesis;
import static org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Preconditions.checkArgument;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.cloudwatch.AmazonCloudWatch;
import com.amazonaws.services.cloudwatch.AmazonCloudWatchClientBuilder;
import com.amazonaws.services.kinesis.AmazonKinesis;
import com.amazonaws.services.kinesis.AmazonKinesisClientBuilder;
import com.amazonaws.services.kinesis.producer.IKinesisProducer;
import com.amazonaws.services.kinesis.producer.KinesisProducer;
import com.amazonaws.services.kinesis.producer.KinesisProducerConfiguration;
import java.net.URI;
import org.checkerframework.checker.nullness.qual.Nullable;
/** Basic implementation of {@link AWSClientsProvider} used by default in {@link KinesisIO}. */
class BasicKinesisProvider implements AWSClientsProvider {
private final String accessKey;
private final String secretKey;
private final Regions region;
private final @Nullable String serviceEndpoint;
private final boolean verifyCertificate;
BasicKinesisProvider(
String accessKey,
String secretKey,
Regions region,
@Nullable String serviceEndpoint,
boolean verifyCertificate) {
checkArgument(accessKey != null, "accessKey can not be null");
checkArgument(secretKey != null, "secretKey can not be null");
checkArgument(region != null, "region can not be null");
this.accessKey = accessKey;
this.secretKey = secretKey;
this.region = region;
this.serviceEndpoint = serviceEndpoint;
this.verifyCertificate = verifyCertificate;
}
BasicKinesisProvider(
String accessKey, String secretKey, Regions region, @Nullable String serviceEndpoint) {
this(accessKey, secretKey, region, serviceEndpoint, true);
}
private AWSCredentialsProvider getCredentialsProvider() {
return new AWSStaticCredentialsProvider(new BasicAWSCredentials(accessKey, secretKey));
}
@Override
public AmazonKinesis getKinesisClient() {
AmazonKinesisClientBuilder clientBuilder =
AmazonKinesisClientBuilder.standard().withCredentials(getCredentialsProvider());
if (serviceEndpoint == null) {
clientBuilder.withRegion(region);
} else {
clientBuilder.withEndpointConfiguration(
new AwsClientBuilder.EndpointConfiguration(serviceEndpoint, region.getName()));
}
return clientBuilder.build();
}
@Override
public AmazonCloudWatch getCloudWatchClient() {
AmazonCloudWatchClientBuilder clientBuilder =
AmazonCloudWatchClientBuilder.standard().withCredentials(getCredentialsProvider());
if (serviceEndpoint == null) {
clientBuilder.withRegion(region);
} else {
clientBuilder.withEndpointConfiguration(
new AwsClientBuilder.EndpointConfiguration(serviceEndpoint, region.getName()));
}
return clientBuilder.build();
}
@Override
public IKinesisProducer createKinesisProducer(KinesisProducerConfiguration config) {
config.setRegion(region.getName());
config.setCredentialsProvider(getCredentialsProvider());
if (serviceEndpoint != null) {
URI uri = URI.create(serviceEndpoint);
config.setKinesisEndpoint(uri.getHost());
config.setKinesisPort(uri.getPort());
}
config.setVerifyCertificate(verifyCertificate);
return new KinesisProducer(config);
}
}
| lukecwik/incubator-beam | sdks/java/io/kinesis/src/main/java/org/apache/beam/sdk/io/kinesis/BasicKinesisProvider.java | Java | apache-2.0 | 4,391 |
<?php
/**
* Created by IntelliJ IDEA.
* User: Nikolay Chervyakov
* Date: 02.12.2014
* Time: 18:21
*/
namespace VulnModule\Vulnerability;
use VulnModule\Vulnerability;
/**
* Class SQL
* @package VulnModule\Vulnerability
* @Vuln\Vulnerability(name="Cross-site request forgery", "A type of malicious exploit of a website whereby
* unauthorized commands are transmitted from a user that the website trusts. Unlike cross-site scripting (XSS),
* which exploits the trust a user has for a particular site, CSRF exploits the trust that a site has in a user's browser.")
*/
class CSRF extends Vulnerability
{
public static $targets = [self::TARGET_CONTEXT];
} | AdrienKuhn/hackazon | modules/vulninjection/classes/VulnModule/Vulnerability/CSRF.php | PHP | apache-2.0 | 695 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.michelboudreau.test;
import com.amazonaws.services.dynamodb.datamodeling.DynamoDBAttribute;
import com.amazonaws.services.dynamodb.datamodeling.DynamoDBHashKey;
import com.amazonaws.services.dynamodb.datamodeling.DynamoDBRangeKey;
import com.amazonaws.services.dynamodb.datamodeling.DynamoDBTable;
@DynamoDBTable(tableName = "mapper.TestClassWithRangeHashKey")
public class TestClassWithHashRangeKey
{
private String hashCode;
private String rangeCode;
private String stringData;
private int intData;
@DynamoDBHashKey(attributeName = "hashCode")
public final String getHashCode()
{
return hashCode;
}
public final void setHashCode(String hashCode)
{
this.hashCode = hashCode;
}
@DynamoDBRangeKey(attributeName = "rangeCode")
public final String getRangeCode()
{
return rangeCode;
}
public final void setRangeCode(String rangeCode)
{
this.rangeCode = rangeCode;
}
@DynamoDBAttribute(attributeName = "stringData")
public String getStringData()
{
return stringData;
}
public void setStringData(String stringData)
{
this.stringData = stringData;
}
@DynamoDBAttribute(attributeName = "intData")
public int getIntData()
{
return intData;
}
public void setIntData(int intData)
{
this.intData = intData;
}
}
| mboudreau/Alternator | src/test/java/com/michelboudreau/test/TestClassWithHashRangeKey.java | Java | apache-2.0 | 1,515 |
/*
* Copyright (c) 2010-2015 Pivotal Software, 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. See accompanying
* LICENSE file.
*/
package com.pivotal.gemfirexd.internal.engine.management;
/**
* This MBean provide different Statistics aggregate for StatementStats. It only
* provide details about query node.
*
* This MBean will show only rate between two sampling interval. Sampling
* interval being DistributionConfig.JMX_MANAGER_UPDATE_RATE_NAME.
* {jmx-manager-update-rate}. Default interval is 2 secs.
*
* e.g. if Sample:1{NumExecution = 2} & Sample:2 {NumExecution = 5} this MBean
* will show a value of 3 if queried after Sample :2 & before Sample:3
*
*
* @author rishim
*
*/
public interface AggregateStatementMXBean {
/**
* Number of times this statement is compiled (including recompilations)
* between two sampling interval.
*
*/
public long getNumTimesCompiled();
/**
* Number of times this statement is executed between two sampling interval.
*/
public long getNumExecution();
/**
* Statements that are actively being processed during the statistics snapshot
* between two sampling interval.
*/
public long getNumExecutionsInProgress();
/**
* Number of times global index lookup message exchanges occurred between two
* sampling interval.
*
*/
public long getNumTimesGlobalIndexLookup();
/**
* Number of rows modified by DML operation of insert/delete/update between
* two sampling interval.
*
*/
public long getNumRowsModified();
/**
* Time spent(in milliseconds) in parsing the query string between two
* sampling interval.
*
*/
public long getParseTime();
/**
* Time spent (in milliseconds) mapping this statement with database object's
* metadata (bind) between two sampling interval.
*
*/
public long getBindTime();
/**
* Time spent (in milliseconds) determining the best execution path for this
* statement (optimize) between two sampling interval.
*
*/
public long getOptimizeTime();
/**
* Time spent (in milliseconds) compiling details about routing information of
* query strings to data node(s) (processQueryInfo) between two sampling interval.
*
*/
public long getRoutingInfoTime();
/**
* Time spent (in milliseconds) to generate query execution plan definition
* (activation class) between two sampling interval.
*
*/
public long getGenerateTime();
/**
* Total compilation time (in milliseconds) of the statement on this node
* (prepMinion) between two sampling interval.
*
*/
public long getTotalCompilationTime();
/**
* Time spent (in nanoseconds) in creation of all the layers of query
* processing (ac.execute) between two sampling interval.
*
*/
public long getExecutionTime();
/**
* Time to apply (in nanoseconds) the projection and additional filters
* between two sampling interval.
*
*/
public long getProjectionTime();
/**
* Total execution time (in nanoseconds) taken to process the statement on
* this node (execute/open/next/close) between two sampling interval.
*
*/
public long getTotalExecutionTime();
/**
* Time taken (in nanoseconds) to modify rows by DML operation of
* insert/delete/update between two sampling interval.
*
*/
public long getRowsModificationTime();
/**
* Number of rows returned from remote nodes (ResultHolder/Get convertibles)
* between two sampling interval.
*
*/
public long getQNNumRowsSeen();
/**
* TCP send time (in nanoseconds) of all the messages including serialization
* time and queue wait time between two sampling interval.
*
*/
public long getQNMsgSendTime();
/**
* Serialization time (in nanoseconds) for all the messages while sending to
* remote node(s) between two sampling interval.
*
*/
public long getQNMsgSerTime();
/**
* Response message deserialization time (in nano seconds ) from remote
* node(s) excluding resultset deserialization between two sampling interval.
*
*/
public long getQNRespDeSerTime();
}
| papicella/snappy-store | gemfirexd/core/src/main/java/com/pivotal/gemfirexd/internal/engine/management/AggregateStatementMXBean.java | Java | apache-2.0 | 4,681 |
/*
Copyright (C) 2010,2011 Wei Dong <wdong.pku@gmail.com>. All Rights Reserved.
DISTRIBUTION OF THIS PROGRAM IN EITHER BINARY OR SOURCE CODE FORM MUST BE
PERMITTED BY THE AUTHOR.
*/
#ifndef KGRAPH_VALUE_TYPE
#define KGRAPH_VALUE_TYPE float
#endif
#include <cctype>
#include <type_traits>
#include <iostream>
#include <boost/timer/timer.hpp>
#include <boost/program_options.hpp>
#include <kgraph.h>
#include <kgraph-data.h>
using namespace std;
using namespace boost;
using namespace kgraph;
namespace po = boost::program_options;
typedef KGRAPH_VALUE_TYPE value_type;
int main (int argc, char *argv[]) {
string input_path;
string query_path;
string output_path;
string eval_path;
unsigned K, P;
po::options_description desc_visible("General options");
desc_visible.add_options()
("help,h", "produce help message.")
("data", po::value(&input_path), "input path")
("query", po::value(&query_path), "query path")
("eval", po::value(&eval_path), "eval path")
(",K", po::value(&K)->default_value(default_K), "")
(",P", po::value(&P)->default_value(default_P), "")
;
po::options_description desc("Allowed options");
desc.add(desc_visible);
po::positional_options_description p;
p.add("data", 1);
p.add("query", 1);
po::variables_map vm;
po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm);
po::notify(vm);
if (vm.count("help") || vm.count("data") == 0 || vm.count("query") == 0) {
cout << "search <data> <index> <query> [output]" << endl;
cout << desc_visible << endl;
return 0;
}
if (P < K) {
P = K;
}
Matrix<value_type> data;
Matrix<value_type> query;
Matrix<unsigned> result;
data.load_lshkit(input_path);
query.load_lshkit(query_path);
unsigned dim = data.dim();
VectorOracle<Matrix<value_type>, value_type const*> oracle(data,
[dim](value_type const *a, value_type const *b)
{
float r = 0;
for (unsigned i = 0; i < dim; ++i) {
float v = float(a[i]) - (b[i]);
r += v * v;
}
return r;
});
float recall = 0;
float cost = 0;
float time = 0;
result.resize(query.size(), K);
KGraph::SearchParams params;
params.K = K;
params.P = P;
KGraph *kgraph = KGraph::create();
{
KGraph::IndexParams params;
kgraph->build(oracle, params, NULL);
}
boost::timer::auto_cpu_timer timer;
cerr << "Searching..." << endl;
#pragma omp parallel for reduction(+:cost)
for (unsigned i = 0; i < query.size(); ++i) {
KGraph::SearchInfo info;
kgraph->search(oracle.query(query[i]), params, result[i], &info);
cost += info.cost;
}
cost /= query.size();
time = timer.elapsed().wall / 1e9;
delete kgraph;
if (eval_path.size()) {
Matrix<unsigned> gs;
gs.load_lshkit(eval_path);
BOOST_VERIFY(gs.dim() >= K);
BOOST_VERIFY(gs.size() >= query.size());
kgraph::Matrix<float> gs_dist(query.size(), K);
kgraph::Matrix<float> result_dist(query.size(), K);
#pragma omp parallel for
for (unsigned i = 0; i < query.size(); ++i) {
auto const Q = oracle.query(query[i]);
float *gs_dist_row = gs_dist[i];
float *result_dist_row = result_dist[i];
unsigned const *gs_row = gs[i];
unsigned const *result_row = result[i];
for (unsigned k = 0; k < K; ++k) {
gs_dist_row[k] = Q(gs_row[k]);
result_dist_row[k] = Q(result_row[k]);
}
sort(gs_dist_row, gs_dist_row + K);
sort(result_dist_row, result_dist_row + K);
}
recall = AverageRecall(gs_dist, result_dist, K);
}
cout << "Time: " << time << " Recall: " << recall << " Cost: " << cost << endl;
return 0;
}
| jonbakerfish/kgraph | test.cpp | C++ | bsd-2-clause | 4,008 |
/*************************************************************************
* Copyright (c) 2015, Synopsys, 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: *
* *
* 1. Redistributions of source code must retain the above copyright *
* notice, this list of conditions and the following disclaimer. *
* *
* 2. 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. *
* *
* 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. *
*************************************************************************/
#ifndef _application_h_
#define _application_h_
// standard
#include <string.h>
class application {
public:
application(char* name = " ");
virtual ~application();
virtual void giveName(char* name);
virtual char* getName();
virtual void save(char* );
virtual void restore(char* );
protected:
char* name;
};
#endif
| kit-transue/software-emancipation-discover | psethome/lib/Learn/src/ttt/include/application.H | C++ | bsd-2-clause | 2,370 |
// Copyright WRLD Ltd (2018-), All Rights Reserved
#include "SearchWidgetController.h"
#include "SearchResultSectionItemSelectedMessage.h"
#include "SearchServicesResult.h"
#include "IMenuSectionViewModel.h"
#include "NavigateToMessage.h"
#include "IMenuView.h"
#include "IMenuOption.h"
#include "MenuItemModel.h"
#include "IMenuModel.h"
#include "ISearchResultsRepository.h"
#include "SearchNavigationData.h"
namespace ExampleApp
{
namespace SearchMenu
{
namespace View
{
SearchWidgetController::SearchWidgetController(ISearchWidgetView& view,
ISearchResultsRepository& resultsRepository,
Modality::View::IModalBackgroundView& modalBackgroundView,
Menu::View::IMenuViewModel& viewModel,
ExampleAppMessaging::TMessageBus& messageBus,
ISearchProvider& searchProvider)
: m_view(view)
, m_modalBackgroundView(modalBackgroundView)
, m_viewModel(viewModel)
, m_messageBus(messageBus)
, m_resultsRepository(resultsRepository)
, m_onSearchResultsClearedCallback(this, &SearchWidgetController::OnSearchResultsCleared)
, m_onSearchResultSelectedCallback(this, &SearchWidgetController::OnSearchResultSelected)
, m_onNavigationRequestedCallback(this, &SearchWidgetController::OnNavigationRequested)
, m_onSearchQueryClearRequestHandler(this, &SearchWidgetController::OnSearchQueryClearRequest)
, m_onSearchQueryRefreshedHandler(this, &SearchWidgetController::OnSearchQueryRefreshedMessage)
, m_onSearchQueryResultsLoadedHandler(this, &SearchWidgetController::OnSearchResultsLoaded)
, m_deepLinkRequestedHandler(this, &SearchWidgetController::OnSearchRequestedMessage)
, m_menuContentsChanged(true)
, m_inInteriorMode(false)
, m_onAppModeChanged(this, &SearchWidgetController::OnAppModeChanged)
, m_onItemSelectedCallback(this, &SearchWidgetController::OnItemSelected)
, m_onItemAddedCallback(this, &SearchWidgetController::OnItemAdded)
, m_onItemRemovedCallback(this, &SearchWidgetController::OnItemRemoved)
, m_onScreenStateChanged(this, &SearchWidgetController::OnScreenControlStateChanged)
, m_onOpenableStateChanged(this, &SearchWidgetController::OnOpenableStateChanged)
, m_onModalBackgroundTouchCallback(this, &SearchWidgetController::OnModalBackgroundTouch)
, m_onViewOpenedCallback(this, &SearchWidgetController::OnViewOpened)
, m_onViewClosedCallback(this, &SearchWidgetController::OnViewClosed)
, m_tagCollection(m_messageBus)
, m_previousVisibleTextFromTagSearch("")
, m_shouldSelectFirstResult(false)
{
m_view.InsertSearchClearedCallback(m_onSearchResultsClearedCallback);
m_view.InsertResultSelectedCallback(m_onSearchResultSelectedCallback);
m_view.InsertOnItemSelected(m_onItemSelectedCallback);
m_view.InsertOnViewClosed(m_onViewClosedCallback);
m_view.InsertOnViewOpened(m_onViewOpenedCallback);
m_view.InsertOnNavigationRequestedCallback(m_onNavigationRequestedCallback);
m_viewModel.InsertOpenStateChangedCallback(m_onOpenableStateChanged);
m_viewModel.InsertOnScreenStateChangedCallback(m_onScreenStateChanged);
m_modalBackgroundView.InsertTouchCallback(m_onModalBackgroundTouchCallback);
m_messageBus.SubscribeUi(m_onSearchQueryRefreshedHandler);
m_messageBus.SubscribeUi(m_onSearchQueryResultsLoadedHandler);
m_messageBus.SubscribeUi(m_onSearchQueryClearRequestHandler);
m_messageBus.SubscribeUi(m_deepLinkRequestedHandler);
m_messageBus.SubscribeUi(m_onAppModeChanged);
for(size_t i = 0; i < m_viewModel.SectionsCount(); ++ i)
{
Menu::View::IMenuSectionViewModel& section(m_viewModel.GetMenuSection(static_cast<int>(i)));
SetGroupStart(section);
Menu::View::IMenuModel& menuModel = section.GetModel();
menuModel.InsertItemAddedCallback(m_onItemAddedCallback);
menuModel.InsertItemRemovedCallback(m_onItemRemovedCallback);
}
searchProvider.InsertSearchPerformedCallback(m_modalBackgroundView.GetSearchPerformedCallback());
}
SearchWidgetController::~SearchWidgetController()
{
for(int i = static_cast<int>(m_viewModel.SectionsCount()); --i >= 0;)
{
Menu::View::IMenuSectionViewModel& section(m_viewModel.GetMenuSection(i));
Menu::View::IMenuModel& menuModel = section.GetModel();
menuModel.RemoveItemAddedCallback(m_onItemAddedCallback);
menuModel.RemoveItemRemovedCallback(m_onItemRemovedCallback);
}
m_messageBus.UnsubscribeUi(m_onAppModeChanged);
m_messageBus.UnsubscribeUi(m_onSearchQueryRefreshedHandler);
m_messageBus.UnsubscribeUi(m_onSearchQueryClearRequestHandler);
m_messageBus.UnsubscribeUi(m_onSearchQueryResultsLoadedHandler);
m_messageBus.UnsubscribeUi(m_deepLinkRequestedHandler);
m_modalBackgroundView.RemoveTouchCallback(m_onModalBackgroundTouchCallback);
m_viewModel.RemoveOnScreenStateChangedCallback(m_onScreenStateChanged);
m_viewModel.RemoveOpenStateChangedCallback(m_onOpenableStateChanged);
m_view.RemoveOnNavigationRequestedCallback(m_onNavigationRequestedCallback);
m_view.RemoveOnViewClosed(m_onViewClosedCallback);
m_view.RemoveResultSelectedCallback(m_onSearchResultSelectedCallback);
m_view.RemoveSearchClearedCallback(m_onSearchResultsClearedCallback);
m_view.RemoveOnItemSelected(m_onItemSelectedCallback);
m_view.RemoveOnItemSelected(m_onItemSelectedCallback);
}
void SearchWidgetController::SetGroupStart(Menu::View::IMenuSectionViewModel& section)
{
if (section.Name() == "Find" ||
section.Name() == "Drop Pin" ||
section.Name() == "Weather")
{
section.SetGroupStart(true);
}
}
void SearchWidgetController::OnItemAdded(Menu::View::MenuItemModel& item) {
m_menuContentsChanged = true;
}
void SearchWidgetController::OnItemRemoved(Menu::View::MenuItemModel& item){
m_menuContentsChanged = true;
}
void SearchWidgetController::OnSearchResultsCleared()
{
m_messageBus.Publish(SearchResultSection::SearchResultViewClearedMessage());
}
void SearchWidgetController::OnSearchResultSelected(int& index)
{
const SearchServicesResult::TSdkSearchResult& sdkSearchResult = m_resultsRepository.GetSdkSearchResultByIndex(index);
m_messageBus.Publish(SearchResultSection::SearchResultSectionItemSelectedMessage(
sdkSearchResult.GetLocation().ToECEF(),
sdkSearchResult.IsInterior(),
sdkSearchResult.GetBuildingId(),
sdkSearchResult.GetFloor(),
m_resultsRepository.GetResultOriginalIndexFromCurrentIndex(index),
sdkSearchResult.GetIdentifier()));
}
void SearchWidgetController::OnNavigationRequested(const int& index)
{
const SearchServicesResult::TSdkSearchResult& sdkSearchResult = m_resultsRepository.GetSdkSearchResultByIndex(index);
const NavRouting::SearchNavigationData searchNavigationData(sdkSearchResult);
m_messageBus.Publish(NavRouting::NavigateToMessage(searchNavigationData));
}
void SearchWidgetController::OnSearchResultsLoaded(const Search::SearchQueryResponseReceivedMessage& message)
{
if (m_shouldSelectFirstResult && message.GetResults().size() > 0){
int val = 0;
OnSearchResultSelected(val);
m_shouldSelectFirstResult = false;
}
}
void SearchWidgetController::OnSearchQueryRefreshedMessage(const Search::SearchQueryRefreshedMessage& message)
{
const Search::SdkModel::SearchQuery &query = message.Query();
std::string visibleText = query.Query();
std::string tagText = "";
if (query.IsTag())
{
tagText = visibleText;
visibleText = m_previousVisibleTextFromTagSearch;
}
m_view.PerformSearch(visibleText,
QueryContext(false,
query.IsTag(),
tagText,
query.ShouldTryInteriorSearch(),
message.Location(),
message.Radius()));
}
void SearchWidgetController::OnSearchQueryClearRequest(const Search::SearchQueryClearRequestMessage &message)
{
m_view.ClearSearchResults();
}
void SearchWidgetController::OnSearchRequestedMessage(const Search::SearchQueryRequestMessage& message)
{
// needed to avoid a reentrant call on the reactor logic on startup queries / deeplinks
m_view.CloseMenu();
auto query = message.Query();
auto clearPreviousResults = false;
std::string visibleText = query.Query();
std::string tagText = "";
if (query.IsTag())
{
tagText = visibleText;
if (m_tagCollection.HasText(tagText))
{
const TagCollection::TagInfo& tagInfo = m_tagCollection.GetInfoByTag(tagText);
visibleText = tagInfo.VisibleText();
}
}
m_previousVisibleTextFromTagSearch = visibleText;
auto queryContext = QueryContext(clearPreviousResults,
query.IsTag(),
tagText,
query.ShouldTryInteriorSearch(),
query.Location(),
query.Radius());
m_shouldSelectFirstResult = query.SelectFirstResult();
m_view.PerformSearch(visibleText, queryContext);
}
void SearchWidgetController::UpdateUiThread(float dt)
{
RefreshPresentation();
}
void SearchWidgetController::OnAppModeChanged(const AppModes::AppModeChangedMessage &message)
{
m_menuContentsChanged = true;
m_inInteriorMode = message.GetAppMode() == AppModes::SdkModel::AppMode::InteriorMode;
RefreshPresentation();
}
void SearchWidgetController::OnItemSelected(const std::string& menuText, int& sectionIndex, int& itemIndex)
{
Menu::View::IMenuSectionViewModel& section = m_viewModel.GetMenuSection(sectionIndex);
if (m_tagCollection.HasTag(menuText))
{
m_view.ClearSearchResults();
TagCollection::TagInfo tagInfo = m_tagCollection.GetInfoByText(menuText);
m_previousVisibleTextFromTagSearch = menuText;
m_view.PerformSearch(menuText,
QueryContext(true, true, tagInfo.Tag(),
tagInfo.ShouldTryInterior()));
}
else if(!section.IsExpandable() || section.GetTotalItemCount()>0)
{
section.GetItemAtIndex(itemIndex).MenuOption().Select();
}
}
void SearchWidgetController::RefreshPresentation()
{
if (!m_menuContentsChanged)
{
return;
}
m_menuContentsChanged = false;
const size_t numSections = m_viewModel.SectionsCount();
Menu::View::TSections sections;
sections.reserve(numSections);
for(size_t groupIndex = 0; groupIndex < numSections; groupIndex++)
{
Menu::View::IMenuSectionViewModel& section = m_viewModel.GetMenuSection(static_cast<int>(groupIndex));
if (section.Name() != "Discover" || !m_inInteriorMode)
{
sections.push_back(§ion);
}
}
m_view.UpdateMenuSectionViews(sections);
}
void SearchWidgetController::OnOpenableStateChanged(OpenableControl::View::IOpenableControlViewModel& viewModel)
{
if(m_viewModel.IsOnScreen())
{
if (m_viewModel.IsOpen())
{
m_view.SetOnScreen();
}
}
else
{
m_view.SetOffScreen();
}
}
void SearchWidgetController::OnScreenControlStateChanged(ScreenControl::View::IScreenControlViewModel& viewModel)
{
if (m_viewModel.IsOnScreen())
{
m_view.SetOnScreen();
}
else if (m_viewModel.IsOffScreen())
{
m_view.SetOffScreen();
}
}
void SearchWidgetController::OnViewOpened()
{
if(!m_viewModel.IsOpen())
{
m_viewModel.Open();
}
}
void SearchWidgetController::OnViewClosed()
{
if(!m_viewModel.IsClosed())
{
m_viewModel.Close();
}
}
void SearchWidgetController::OnModalBackgroundTouch()
{
// the modal background goes away after the first touch, so no need to throttle
m_view.CloseMenu();
}
}
}
}
| eegeo/eegeo-example-app | src/SearchMenu/View/SearchWidgetController.cpp | C++ | bsd-2-clause | 14,669 |
#!/usr/bin/env python
"""
@package mi.dataset.parser.metbk_a_dcl
@file marine-integrations/mi/dataset/parser/metbk_a_dcl.py
@author Ronald Ronquillo
@brief Parser for the metbk_a_dcl dataset driver
This file contains code for the metbk_a_dcl parsers and code to produce data particles.
For telemetered data, there is one parser which produces one type of data particle.
For recovered data, there is one parser which produces one type of data particle.
The input files and the content of the data particles are the same for both
recovered and telemetered.
Only the names of the output particle streams are different.
The input file is ASCII and contains 2 types of records.
Records are separated by a newline.
All records start with a timestamp.
Metadata records: timestamp [text] more text newline.
Sensor Data records: timestamp sensor_data newline.
Only sensor data records produce particles if properly formed.
Mal-formed sensor data records and all metadata records produce no particles.
Release notes:
Initial Release
"""
import re
from mi.core.log import get_logger
from mi.core.common import BaseEnum
from mi.dataset.parser.dcl_file_common import \
DclInstrumentDataParticle, \
DclFileCommonParser
from mi.core.instrument.dataset_data_particle import DataParticleKey
from mi.core.exceptions import UnexpectedDataException
log = get_logger()
__author__ = 'Phillip Tran'
__license__ = 'Apache 2.0'
# SENSOR_DATA_MATCHER produces the following groups.
# The following are indices into groups() produced by SENSOR_DATA_MATCHER
# incremented after common timestamp values.
# i.e, match.groups()[INDEX]
SENSOR_GROUP_BAROMETRIC_PRESSURE = 1
SENSOR_GROUP_RELATIVE_HUMIDITY = 2
SENSOR_GROUP_AIR_TEMPERATURE = 3
SENSOR_GROUP_LONGWAVE_IRRADIANCE = 4
SENSOR_GROUP_PRECIPITATION = 5
SENSOR_GROUP_SEA_SURFACE_TEMPERATURE = 6
SENSOR_GROUP_SEA_SURFACE_CONDUCTIVITY = 7
SENSOR_GROUP_SHORTWAVE_IRRADIANCE = 8
SENSOR_GROUP_EASTWARD_WIND_VELOCITY = 9
SENSOR_GROUP_NORTHWARD_WIND_VELOCITY = 10
# This table is used in the generation of the instrument data particle.
# This will be a list of tuples with the following columns.
# Column 1 - particle parameter name
# Column 2 - group number (index into raw_data)
# Column 3 - data encoding function (conversion required - int, float, etc)
INSTRUMENT_PARTICLE_MAP = [
('barometric_pressure', SENSOR_GROUP_BAROMETRIC_PRESSURE, float),
('relative_humidity', SENSOR_GROUP_RELATIVE_HUMIDITY, float),
('air_temperature', SENSOR_GROUP_AIR_TEMPERATURE, float),
('longwave_irradiance', SENSOR_GROUP_LONGWAVE_IRRADIANCE, float),
('precipitation', SENSOR_GROUP_PRECIPITATION, float),
('sea_surface_temperature', SENSOR_GROUP_SEA_SURFACE_TEMPERATURE, float),
('sea_surface_conductivity', SENSOR_GROUP_SEA_SURFACE_CONDUCTIVITY, float),
('shortwave_irradiance', SENSOR_GROUP_SHORTWAVE_IRRADIANCE, float),
('eastward_wind_velocity', SENSOR_GROUP_EASTWARD_WIND_VELOCITY, float),
('northward_wind_velocity', SENSOR_GROUP_NORTHWARD_WIND_VELOCITY, float)
]
class DataParticleType(BaseEnum):
REC_INSTRUMENT_PARTICLE = 'metbk_a_dcl_instrument_recovered'
TEL_INSTRUMENT_PARTICLE = 'metbk_a_dcl_instrument'
class MetbkADclInstrumentDataParticle(DclInstrumentDataParticle):
"""
Class for generating the Metbk_a instrument particle.
"""
def __init__(self, raw_data, *args, **kwargs):
super(MetbkADclInstrumentDataParticle, self).__init__(
raw_data,
INSTRUMENT_PARTICLE_MAP,
*args, **kwargs)
def _build_parsed_values(self):
"""
Build parsed values for Recovered and Telemetered Instrument Data Particle.
Will only append float values and ignore strings.
Returns the list.
"""
data_list = []
for name, group, func in INSTRUMENT_PARTICLE_MAP:
if isinstance(self.raw_data[group], func):
data_list.append(self._encode_value(name, self.raw_data[group], func))
return data_list
class MetbkADclRecoveredInstrumentDataParticle(MetbkADclInstrumentDataParticle):
"""
Class for generating Offset Data Particles from Recovered data.
"""
_data_particle_type = DataParticleType.REC_INSTRUMENT_PARTICLE
class MetbkADclTelemeteredInstrumentDataParticle(MetbkADclInstrumentDataParticle):
"""
Class for generating Offset Data Particles from Telemetered data.
"""
_data_particle_type = DataParticleType.TEL_INSTRUMENT_PARTICLE
class MetbkADclParser(DclFileCommonParser):
"""
This is the entry point for the Metbk_a_dcl parser.
"""
def __init__(self,
config,
stream_handle,
exception_callback):
super(MetbkADclParser, self).__init__(config,
stream_handle,
exception_callback,
'',
'')
self.particle_classes = None
self.instrument_particle_map = INSTRUMENT_PARTICLE_MAP
self.raw_data_length = 14
def parse_file(self):
"""
This method reads the file and parses the data within, and at
the end of this method self._record_buffer will be filled with all the particles in the file.
"""
# If not set from config & no InstrumentParameterException error from constructor
if self.particle_classes is None:
self.particle_classes = (self._particle_class,)
for particle_class in self.particle_classes:
for line in self._stream_handle:
if not re.findall(r'.*\[.*\]:\b[^\W\d_]+\b', line) and line is not None: # Disregard anything that has a word after [metbk2:DLOGP6]:
line = re.sub(r'\[.*\]:', '', line)
raw_data = line.split()
if len(raw_data) != self.raw_data_length: # The raw data should have a length of 14
self.handle_unknown_data(line)
continue
if re.findall(r'[a-zA-Z][0-9]|[0-9][a-zA-Z]', line):
self.handle_unknown_data(line)
continue
raw_data[0:2] = [' '.join(raw_data[0:2])] # Merge the first and second elements to form a timestamp
if raw_data is not None:
for i in range(1, len(raw_data)): # Ignore 0th element, because that is the timestamp
raw_data[i] = self.select_type(raw_data[i])
particle = self._extract_sample(particle_class,
None,
raw_data,
preferred_ts=DataParticleKey.PORT_TIMESTAMP)
self._record_buffer.append(particle)
def handle_unknown_data(self, line):
# Otherwise generate warning for unknown data.
error_message = 'Unknown data found in chunk %s' % line
log.warn(error_message)
self._exception_callback(UnexpectedDataException(error_message))
@staticmethod
def select_type(raw_list_element):
"""
This function will return the float value if possible
"""
try:
return float(raw_list_element)
except ValueError:
return None
| renegelinas/mi-instrument | mi/dataset/parser/metbk_a_dcl.py | Python | bsd-2-clause | 7,536 |
// Package csr implements certificate requests for CFSSL.
package csr
import (
"crypto"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"errors"
"net"
"net/mail"
"strings"
cferr "github.com/cloudflare/cfssl/errors"
"github.com/cloudflare/cfssl/helpers"
"github.com/cloudflare/cfssl/log"
)
const (
curveP256 = 256
curveP384 = 384
curveP521 = 521
)
// A Name contains the SubjectInfo fields.
type Name struct {
C string // Country
ST string // State
L string // Locality
O string // OrganisationName
OU string // OrganisationalUnitName
}
// A KeyRequest is a generic request for a new key.
type KeyRequest interface {
Algo() string
Size() int
Generate() (crypto.PrivateKey, error)
SigAlgo() x509.SignatureAlgorithm
}
// A BasicKeyRequest contains the algorithm and key size for a new private key.
type BasicKeyRequest struct {
A string `json:"algo"`
S int `json:"size"`
}
// NewBasicKeyRequest returns a default BasicKeyRequest.
func NewBasicKeyRequest() *BasicKeyRequest {
return &BasicKeyRequest{"ecdsa", curveP256}
}
// Algo returns the requested key algorithm represented as a string.
func (kr *BasicKeyRequest) Algo() string {
return kr.A
}
// Size returns the requested key size.
func (kr *BasicKeyRequest) Size() int {
return kr.S
}
// Generate generates a key as specified in the request. Currently,
// only ECDSA and RSA are supported.
func (kr *BasicKeyRequest) Generate() (crypto.PrivateKey, error) {
log.Debugf("generate key from request: algo=%s, size=%d", kr.Algo(), kr.Size())
switch kr.Algo() {
case "rsa":
if kr.Size() < 2048 {
return nil, errors.New("RSA key is too weak")
}
if kr.Size() > 8192 {
return nil, errors.New("RSA key size too large")
}
return rsa.GenerateKey(rand.Reader, kr.Size())
case "ecdsa":
var curve elliptic.Curve
switch kr.Size() {
case curveP256:
curve = elliptic.P256()
case curveP384:
curve = elliptic.P384()
case curveP521:
curve = elliptic.P521()
default:
return nil, errors.New("invalid curve")
}
return ecdsa.GenerateKey(curve, rand.Reader)
default:
return nil, errors.New("invalid algorithm")
}
}
// SigAlgo returns an appropriate X.509 signature algorithm given the
// key request's type and size.
func (kr *BasicKeyRequest) SigAlgo() x509.SignatureAlgorithm {
switch kr.Algo() {
case "rsa":
switch {
case kr.Size() >= 4096:
return x509.SHA512WithRSA
case kr.Size() >= 3072:
return x509.SHA384WithRSA
case kr.Size() >= 2048:
return x509.SHA256WithRSA
default:
return x509.SHA1WithRSA
}
case "ecdsa":
switch kr.Size() {
case curveP521:
return x509.ECDSAWithSHA512
case curveP384:
return x509.ECDSAWithSHA384
case curveP256:
return x509.ECDSAWithSHA256
default:
return x509.ECDSAWithSHA1
}
default:
return x509.UnknownSignatureAlgorithm
}
}
// CAConfig is a section used in the requests initialising a new CA.
type CAConfig struct {
PathLength int `json:"pathlen"`
Expiry string `json:"expiry"`
}
// A CertificateRequest encapsulates the API interface to the
// certificate request functionality.
type CertificateRequest struct {
CN string
Names []Name `json:"names"`
Hosts []string `json:"hosts"`
KeyRequest KeyRequest `json:"key,omitempty"`
CA *CAConfig `json:"ca,omitempty"`
}
// New returns a new, empty CertificateRequest with a
// BasicKeyRequest.
func New() *CertificateRequest {
return &CertificateRequest{
KeyRequest: NewBasicKeyRequest(),
}
}
// appendIf appends to a if s is not an empty string.
func appendIf(s string, a *[]string) {
if s != "" {
*a = append(*a, s)
}
}
// Name returns the PKIX name for the request.
func (cr *CertificateRequest) Name() pkix.Name {
var name pkix.Name
name.CommonName = cr.CN
for _, n := range cr.Names {
appendIf(n.C, &name.Country)
appendIf(n.ST, &name.Province)
appendIf(n.L, &name.Locality)
appendIf(n.O, &name.Organization)
appendIf(n.OU, &name.OrganizationalUnit)
}
return name
}
// ParseRequest takes a certificate request and generates a key and
// CSR from it. It does no validation -- caveat emptor. It will,
// however, fail if the key request is not valid (i.e., an unsupported
// curve or RSA key size). The lack of validation was specifically
// chosen to allow the end user to define a policy and validate the
// request appropriately before calling this function.
func ParseRequest(req *CertificateRequest) (csr, key []byte, err error) {
log.Info("received CSR")
if req.KeyRequest == nil {
req.KeyRequest = NewBasicKeyRequest()
}
log.Infof("generating key: %s-%d", req.KeyRequest.Algo(), req.KeyRequest.Size())
priv, err := req.KeyRequest.Generate()
if err != nil {
err = cferr.Wrap(cferr.PrivateKeyError, cferr.GenerationFailed, err)
return
}
switch priv := priv.(type) {
case *rsa.PrivateKey:
key = x509.MarshalPKCS1PrivateKey(priv)
block := pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: key,
}
key = pem.EncodeToMemory(&block)
case *ecdsa.PrivateKey:
key, err = x509.MarshalECPrivateKey(priv)
if err != nil {
err = cferr.Wrap(cferr.PrivateKeyError, cferr.Unknown, err)
return
}
block := pem.Block{
Type: "EC PRIVATE KEY",
Bytes: key,
}
key = pem.EncodeToMemory(&block)
default:
panic("Generate should have failed to produce a valid key.")
}
var tpl = x509.CertificateRequest{
Subject: req.Name(),
SignatureAlgorithm: req.KeyRequest.SigAlgo(),
}
for i := range req.Hosts {
if ip := net.ParseIP(req.Hosts[i]); ip != nil {
tpl.IPAddresses = append(tpl.IPAddresses, ip)
} else if email, err := mail.ParseAddress(req.Hosts[i]); err == nil && email != nil {
tpl.EmailAddresses = append(tpl.EmailAddresses, req.Hosts[i])
} else {
tpl.DNSNames = append(tpl.DNSNames, req.Hosts[i])
}
}
csr, err = x509.CreateCertificateRequest(rand.Reader, &tpl, priv)
if err != nil {
log.Errorf("failed to generate a CSR: %v", err)
err = cferr.Wrap(cferr.CSRError, cferr.BadRequest, err)
return
}
block := pem.Block{
Type: "CERTIFICATE REQUEST",
Bytes: csr,
}
log.Info("encoded CSR")
csr = pem.EncodeToMemory(&block)
return
}
// ExtractCertificateRequest extracts a CertificateRequest from
// x509.Certificate. It is aimed to used for generating a new certificate
// from an existing certificate. For a root certificate, the CA expiry
// length is calculated as the duration between cert.NotAfter and cert.NotBefore.
func ExtractCertificateRequest(cert *x509.Certificate) *CertificateRequest {
req := New()
req.CN = cert.Subject.CommonName
req.Names = getNames(cert.Subject)
req.Hosts = getHosts(cert)
if cert.IsCA {
req.CA = new(CAConfig)
// CA expiry length is calculated based on the input cert
// issue date and expiry date.
req.CA.Expiry = cert.NotAfter.Sub(cert.NotBefore).String()
req.CA.PathLength = cert.MaxPathLen
}
return req
}
func getHosts(cert *x509.Certificate) []string {
var hosts []string
for _, ip := range cert.IPAddresses {
hosts = append(hosts, ip.String())
}
for _, dns := range cert.DNSNames {
hosts = append(hosts, dns)
}
for _, email := range cert.EmailAddresses {
hosts = append(hosts, email)
}
return hosts
}
// getNames returns an array of Names from the certificate
// It onnly cares about Country, Organization, OrganizationalUnit, Locality, Province
func getNames(sub pkix.Name) []Name {
// anonymous func for finding the max of a list of interger
max := func(v1 int, vn ...int) (max int) {
max = v1
for i := 0; i < len(vn); i++ {
if vn[i] > max {
max = vn[i]
}
}
return max
}
nc := len(sub.Country)
norg := len(sub.Organization)
nou := len(sub.OrganizationalUnit)
nl := len(sub.Locality)
np := len(sub.Province)
n := max(nc, norg, nou, nl, np)
names := make([]Name, n)
for i := range names {
if i < nc {
names[i].C = sub.Country[i]
}
if i < norg {
names[i].O = sub.Organization[i]
}
if i < nou {
names[i].OU = sub.OrganizationalUnit[i]
}
if i < nl {
names[i].L = sub.Locality[i]
}
if i < np {
names[i].ST = sub.Province[i]
}
}
return names
}
// A Generator is responsible for validating certificate requests.
type Generator struct {
Validator func(*CertificateRequest) error
}
// ProcessRequest validates and processes the incoming request. It is
// a wrapper around a validator and the ParseRequest function.
func (g *Generator) ProcessRequest(req *CertificateRequest) (csr, key []byte, err error) {
log.Info("generate received request")
err = g.Validator(req)
if err != nil {
log.Warningf("invalid request: %v", err)
return
}
csr, key, err = ParseRequest(req)
if err != nil {
return nil, nil, err
}
return
}
// IsNameEmpty returns true if the name has no identifying information in it.
func IsNameEmpty(n Name) bool {
empty := func(s string) bool { return strings.TrimSpace(s) == "" }
if empty(n.C) && empty(n.ST) && empty(n.L) && empty(n.O) && empty(n.OU) {
return true
}
return false
}
// Regenerate uses the provided CSR as a template for signing a new
// CSR using priv.
func Regenerate(priv crypto.Signer, csr []byte) ([]byte, error) {
req, extra, err := helpers.ParseCSR(csr)
if err != nil {
return nil, err
} else if len(extra) > 0 {
return nil, errors.New("csr: trailing data in certificate request")
}
return x509.CreateCertificateRequest(rand.Reader, req, priv)
}
// Generate creates a new CSR from a CertificateRequest structure and
// an existing key. The KeyRequest field is ignored.
func Generate(priv crypto.Signer, req *CertificateRequest) (csr []byte, err error) {
sigAlgo := helpers.SignerAlgo(priv, crypto.SHA256)
if sigAlgo == x509.UnknownSignatureAlgorithm {
return nil, cferr.New(cferr.PrivateKeyError, cferr.Unavailable)
}
var tpl = x509.CertificateRequest{
Subject: req.Name(),
SignatureAlgorithm: sigAlgo,
}
for i := range req.Hosts {
if ip := net.ParseIP(req.Hosts[i]); ip != nil {
tpl.IPAddresses = append(tpl.IPAddresses, ip)
} else if email, err := mail.ParseAddress(req.Hosts[i]); err == nil && email != nil {
tpl.EmailAddresses = append(tpl.EmailAddresses, email.Address)
} else {
tpl.DNSNames = append(tpl.DNSNames, req.Hosts[i])
}
}
csr, err = x509.CreateCertificateRequest(rand.Reader, &tpl, priv)
if err != nil {
log.Errorf("failed to generate a CSR: %v", err)
err = cferr.Wrap(cferr.CSRError, cferr.BadRequest, err)
return
}
block := pem.Block{
Type: "CERTIFICATE REQUEST",
Bytes: csr,
}
log.Info("encoded CSR")
csr = pem.EncodeToMemory(&block)
return
}
| rolandshoemaker/cfssl | csr/csr.go | GO | bsd-2-clause | 10,628 |
class AmazonEcsCli < Formula
desc "CLI for Amazon ECS to manage clusters and tasks for development"
homepage "https://aws.amazon.com/ecs"
url "https://github.com/aws/amazon-ecs-cli/archive/v1.7.0.tar.gz"
sha256 "b25d3defae2977aa696532b0e68afebd1e587f90eb4c39c64883a4c15906e19b"
bottle do
cellar :any_skip_relocation
sha256 "5a4783469233b2a9535b98b1b351f151deecdfe2d0bc30f8abb3002a73bc7145" => :mojave
sha256 "c84a85efdba3e5b6205dd13cf62c1c7c0a56ad9a6277c6009e52688d3c09c292" => :high_sierra
sha256 "658f4033ebda28ac671895dea8c132f62a96fe6dd4dd91de10b394b9dff8e245" => :sierra
sha256 "6f9d3c50e8fa4b59720ec701fd83831600526787c1e908bb9dc269f646907c58" => :el_capitan
end
depends_on "go" => :build
def install
ENV["GOPATH"] = buildpath
(buildpath/"src/github.com/aws/amazon-ecs-cli").install buildpath.children
cd "src/github.com/aws/amazon-ecs-cli" do
system "make", "build"
system "make", "test"
bin.install "bin/local/ecs-cli"
prefix.install_metafiles
end
end
test do
assert_match version.to_s, shell_output("#{bin}/ecs-cli -v")
end
end
| DomT4/homebrew-core | Formula/amazon-ecs-cli.rb | Ruby | bsd-2-clause | 1,127 |
from __future__ import absolute_import
from django.conf.urls import include, url
from django.conf import settings
from django.conf.urls.static import static
from . import views
from . import settings as wooey_settings
wooey_patterns = [
url(r'^jobs/command$', views.celery_task_command, name='celery_task_command'),
url(r'^jobs/queue/global/json$', views.global_queue_json, name='global_queue_json'),
url(r'^jobs/queue/user/json$', views.user_queue_json, name='user_queue_json'),
url(r'^jobs/results/user/json$', views.user_results_json, name='user_results_json'),
url(r'^jobs/queue/all/json', views.all_queues_json, name='all_queues_json'),
url(r'^jobs/queue/global', views.GlobalQueueView.as_view(), name='global_queue'),
url(r'^jobs/queue/user', views.UserQueueView.as_view(), name='user_queue'),
url(r'^jobs/results/user', views.UserResultsView.as_view(), name='user_results'),
url(r'^jobs/(?P<job_id>[0-9\-]+)/$', views.JobView.as_view(), name='celery_results'),
url(r'^jobs/(?P<job_id>[0-9\-]+)/json$', views.JobJSON.as_view(), name='celery_results_json'),
# Global public access via uuid
url(r'^jobs/(?P<uuid>[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89aAbB][a-f0-9]{3}-[a-f0-9]{12})/$', views.JobView.as_view(), name='celery_results_uuid'),
url(r'^jobs/(?P<uuid>[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89aAbB][a-f0-9]{3}-[a-f0-9]{12})/json$', views.JobJSON.as_view(), name='celery_results_json_uuid'),
url(r'^scripts/(?P<slug>[a-zA-Z0-9\-\_]+)/$', views.WooeyScriptView.as_view(), name='wooey_script'),
url(r'^scripts/(?P<slug>[a-zA-Z0-9\-\_]+)/version/(?P<script_version>[A-Za-z\.0-9]+)$', views.WooeyScriptView.as_view(), name='wooey_script'),
url(r'^scripts/(?P<slug>[a-zA-Z0-9\-\_]+)/version/(?P<script_version>[A-Za-z\.0-9]+)/iteration/(?P<script_iteration>\d+)$', views.WooeyScriptView.as_view(), name='wooey_script'),
url(r'^scripts/(?P<slug>[a-zA-Z0-9\-\_]+)/jobs/(?P<job_id>[a-zA-Z0-9\-]+)$', views.WooeyScriptView.as_view(), name='wooey_script_clone'),
url(r'^scripts/(?P<slug>[a-zA-Z0-9\-\_]+)/$', views.WooeyScriptJSON.as_view(), name='wooey_script_json'),
url(r'^scripts/search/json$', views.WooeyScriptSearchJSON.as_view(), name='wooey_search_script_json'),
url(r'^scripts/search/jsonhtml$', views.WooeyScriptSearchJSONHTML.as_view(), name='wooey_search_script_jsonhtml'),
url(r'^profile/$', views.WooeyProfileView.as_view(), name='profile_home'),
url(r'^profile/(?P<username>[a-zA-Z0-9\-]+)$', views.WooeyProfileView.as_view(), name='profile'),
url(r'^$', views.WooeyHomeView.as_view(), name='wooey_home'),
url(r'^$', views.WooeyHomeView.as_view(), name='wooey_job_launcher'),
url('^{}'.format(wooey_settings.WOOEY_LOGIN_URL.lstrip('/')), views.wooey_login, name='wooey_login'),
url('^{}'.format(wooey_settings.WOOEY_REGISTER_URL.lstrip('/')), views.WooeyRegister.as_view(), name='wooey_register'),
url(r'^favorite/toggle$', views.toggle_favorite, name='toggle_favorite'),
url(r'^scrapbook$', views.WooeyScrapbookView.as_view(), name='scrapbook'),
]
urlpatterns = [
url('^', include(wooey_patterns, namespace='wooey')),
url('^', include('django.contrib.auth.urls')),
]
| alexkolar/Wooey | wooey/urls.py | Python | bsd-3-clause | 3,225 |
/*
* Copyright (c) 1999-2015, Ecole des Mines de Nantes
* 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 the Ecole des Mines de Nantes 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 REGENTS 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 REGENTS AND 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.
*/
package org.chocosolver.solver.search;
import org.chocosolver.memory.copy.EnvironmentCopying;
import org.chocosolver.solver.ResolutionPolicy;
import org.chocosolver.solver.Solver;
import org.chocosolver.solver.constraints.IntConstraintFactory;
import org.chocosolver.solver.search.loop.monitors.IMonitorSolution;
import org.chocosolver.solver.variables.IntVar;
import org.chocosolver.solver.variables.VariableFactory;
import org.testng.Assert;
import org.testng.annotations.Test;
/**
* Created by cprudhom on 18/02/15.
* Project: choco.
*/
public class ParetoTest {
//******************************************************************
// CP VARIABLES
//******************************************************************
// --- CP Solver
private Solver s;
// --- Decision variables
private IntVar[] occurrences;
// --- Cumulated profit_1 of selected items
private IntVar totalProfit_1;
// --- Cumulated profit_2 of selected items
private IntVar totalProfit_2;
// --- Cumulated weight of selected items
private IntVar totalWeight;
//******************************************************************
// DATA
//******************************************************************
// --- Capacity of the knapsack
private final int capacity;
// --- Maximal profit_1 of the knapsack
private int maxProfit_1;
// --- Maximal profit_2 of the knapsack
private int maxProfit_2;
// --- Number of items in each category
private final int[] nbItems;
// --- Weight of items in each category
private final int[] weights;
// --- Profit_1 of items in each category
private final int[] profits_1;
// --- Profit_2 of items in each category
private final int[] profits_2;
//******************************************************************
// CONSTRUCTOR
//******************************************************************
public ParetoTest(final int capacity, final String... items) {
this.capacity = capacity;
this.nbItems = new int[items.length];
this.weights = new int[items.length];
this.profits_1 = new int[items.length];
this.profits_2 = new int[items.length];
this.maxProfit_1 = 0;
this.maxProfit_2 = 0;
for (int it = 0; it < items.length; it++) {
String item = items[it];
item = item.trim();
final String[] itemData = item.split(";");
this.nbItems[it] = Integer.parseInt(itemData[0]);
this.weights[it] = Integer.parseInt(itemData[1]);
this.profits_1[it] = Integer.parseInt(itemData[2]);
this.profits_2[it] = Integer.parseInt(itemData[3]);
this.maxProfit_1 += this.nbItems[it] * this.profits_1[it];
this.maxProfit_2 += this.nbItems[it] * this.profits_2[it];
}
}
//******************************************************************
// METHODS
//******************************************************************
private void createSolver() {
// --- Creates a solver
s = new Solver(new EnvironmentCopying(), "Knapsack");
}
private void buildModel() {
createVariables();
postConstraints();
}
private void createVariables() {
// --- Creates decision variables
occurrences = new IntVar[nbItems.length];
for (int i = 0; i < nbItems.length; i++) {
occurrences[i] = VariableFactory.bounded("occurrences_" + i, 0, nbItems[i], s);
}
totalWeight = VariableFactory.bounded("totalWeight", 0, capacity, s);
totalProfit_1 = VariableFactory.bounded("totalProfit_1", 0, maxProfit_1, s);
totalProfit_2 = VariableFactory.bounded("totalProfit_2", 0, maxProfit_2, s);
}
private void postConstraints() {
// --- Posts a knapsack constraint on profit_1
s.post(IntConstraintFactory.knapsack(occurrences, totalWeight, totalProfit_1, weights, profits_1));
// --- Posts a knapsack constraint on profit_2
s.post(IntConstraintFactory.knapsack(occurrences, totalWeight, totalProfit_2, weights, profits_2));
}
static int bestProfit1 = 0;
private void solve() {
// --- Solves the problem
s.plugMonitor((IMonitorSolution) () -> bestProfit1 = Math.max(bestProfit1, totalProfit_1.getValue()));
// Chatterbox.showSolutions(s);
s.findParetoFront(ResolutionPolicy.MAXIMIZE, totalProfit_1, totalProfit_2);
}
//******************************************************************
// MAIN
//******************************************************************
@Test
public static void main() {
ParetoTest instance = new ParetoTest(30, "10;1;2;5", "5;3;7;4", "2;5;11;3");
instance.createSolver();
instance.buildModel();
instance.solve();
Assert.assertTrue(bestProfit1 > 60);
}
}
| piyushsh/choco3 | choco-solver/src/test/java/org/chocosolver/solver/search/ParetoTest.java | Java | bsd-3-clause | 6,565 |
<?php
use yii\helpers\Html;
use yii\widgets\DetailView;
/* @var $this yii\web\View */
/* @var $model frontend\models\Penjualan */
$this->title = $model->idpenjualan;
$this->params['breadcrumbs'][] = ['label' => 'Penjualans', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="penjualan-view">
<h1><?= Html::encode($this->title) ?></h1>
<p>
<?= Html::a('Update', ['update', 'id' => $model->idpenjualan], ['class' => 'btn btn-primary']) ?>
<?= Html::a('Delete', ['delete', 'id' => $model->idpenjualan], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => 'Are you sure you want to delete this item?',
'method' => 'post',
],
]) ?>
</p>
<?= DetailView::widget([
'model' => $model,
'attributes' => [
'idpenjualan',
'tglpenjualan',
'jmlbarang',
'ttlbayar',
'idpelanggan',
],
]) ?>
</div>
| programerjakarta/tokojaya | frontend/views/transaksi/view.php | PHP | bsd-3-clause | 1,021 |
<?php
use yii\widgets\Menu;
/* @var $this yii\web\View */
/* @var $items array */
?>
<div class="panel panel-default">
<div class="panel-heading">Категории</div>
<?= Menu::widget([
'options' => ['class' => 'nav nav-pills nav-stacked'],
'items' => $items,
'submenuTemplate' => "\n<ul class='nav nav-pills nav-stacked'>\n{items}\n</ul>\n"
]); ?>
</div>
| peskovsb/shopgit | widgets/views/categories.php | PHP | bsd-3-clause | 404 |
from django.contrib.admin.views.decorators import staff_member_required
from django.shortcuts import get_object_or_404
from pdfdocument.utils import pdf_response
import plata
import plata.reporting.product
import plata.reporting.order
@staff_member_required
def product_xls(request):
"""
Returns an XLS containing product information
"""
return plata.reporting.product.product_xls().to_response('products.xlsx')
@staff_member_required
def invoice_pdf(request, order_id):
"""
Returns the invoice PDF
"""
order = get_object_or_404(plata.shop_instance().order_model, pk=order_id)
pdf, response = pdf_response('invoice-%09d' % order.id)
plata.reporting.order.invoice_pdf(pdf, order)
return response
@staff_member_required
def packing_slip_pdf(request, order_id):
"""
Returns the packing slip PDF
"""
order = get_object_or_404(plata.shop_instance().order_model, pk=order_id)
pdf, response = pdf_response('packing-slip-%09d' % order.id)
plata.reporting.order.packing_slip_pdf(pdf, order)
return response
| ixc/plata | plata/reporting/views.py | Python | bsd-3-clause | 1,080 |
// d. ii. If k + 2 is greater than or equal to strLen, throw a URIError exception.
decodeURI('%1');
| daejunpark/jsaf | tests/bug_detector_tests/urierror1.js | JavaScript | bsd-3-clause | 100 |
package org.jmock.test.acceptance;
import static org.hamcrest.Matchers.isEmptyOrNullString;
import static org.junit.Assert.assertThat;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.lang.ref.WeakReference;
import org.jmock.Mockery;
import org.jmock.api.Imposteriser;
import org.jmock.lib.concurrent.Synchroniser;
import org.jmock.test.unit.lib.legacy.CodeGeneratingImposteriserParameterResolver;
import org.jmock.test.unit.lib.legacy.ImposteriserParameterResolver;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ArgumentsSource;
/**
* Nasty test to show GitHub #36 is fixed.
*/
public class MockeryFinalizationAcceptanceTests
{
private static final int FINALIZE_COUNT = 10; // consistently shows a problem before GitHub #36 was fixed
private final Mockery mockery = new Mockery() {{
setThreadingPolicy(new Synchroniser());
}};
private final ErrorStream capturingErr = new ErrorStream();
@BeforeAll
public static void clearAnyOutstandingMessages() {
ErrorStream localErr = new ErrorStream();
localErr.install();
String error = null;
try {
finalizeUntilMessageOrCount(localErr, FINALIZE_COUNT);
error = localErr.output();
} finally {
localErr.uninstall();
}
if (error != null)
System.err.println("WARNING - a previous test left output in finalization [" + error + "]");
}
@BeforeEach
public void captureSysErr() {
capturingErr.install();
}
@AfterEach
public void replaceSysErr() {
capturingErr.uninstall();
}
@ParameterizedTest
@ArgumentsSource(ImposteriserParameterResolver.class)
public void mockedInterfaceDoesntWarnOnFinalize(Imposteriser imposterImpl) {
mockery.setImposteriser(imposterImpl);
checkNoFinalizationMessage(mockery, CharSequence.class);
}
@ParameterizedTest
@ArgumentsSource(CodeGeneratingImposteriserParameterResolver.class)
public void mockedClassDoesntWarnOnFinalize(Imposteriser imposterImpl) {
mockery.setImposteriser(imposterImpl);
checkNoFinalizationMessage(mockery, Object.class);
}
public interface TypeThatMakesFinalizePublic {
public void finalize();
}
@ParameterizedTest
@ArgumentsSource(ImposteriserParameterResolver.class)
public void mockedTypeThatMakesFinalizePublicDoesntWarnOnFinalize(Imposteriser imposterImpl) {
mockery.setImposteriser(imposterImpl);
checkNoFinalizationMessage(mockery, TypeThatMakesFinalizePublic.class);
}
private void checkNoFinalizationMessage(Mockery mockery, Class<?> typeToMock) {
WeakReference<Object> mockHolder = new WeakReference<Object>(mockery.mock(typeToMock));
while (mockHolder.get() != null) {
System.gc();
System.runFinalization();
}
finalizeUntilMessageOrCount(capturingErr, FINALIZE_COUNT);
assertThat(capturingErr.output(), isEmptyOrNullString());
}
private static void finalizeUntilMessageOrCount(ErrorStream capturingErr, int count) {
for (int i = 0; i < count && capturingErr.output().isEmpty(); i++) {
System.gc();
System.runFinalization();
}
}
private static class ErrorStream extends PrintStream {
private PrintStream oldSysErr;
public ErrorStream() {
super(new ByteArrayOutputStream());
}
public void install() {
oldSysErr = System.err;
System.setErr(this);
}
public void uninstall() {
System.setErr(oldSysErr);
}
public String output() {
return new String(((ByteArrayOutputStream) out).toByteArray());
}
}
} | jmock-developers/jmock-library | jmock-imposters-tests/src/test/java/org/jmock/test/acceptance/MockeryFinalizationAcceptanceTests.java | Java | bsd-3-clause | 3,971 |
// Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/interest_group/storage_interest_group.h"
#include "content/services/auction_worklet/public/mojom/bidder_worklet.mojom.h"
namespace content {
StorageInterestGroup::StorageInterestGroup() = default;
StorageInterestGroup::StorageInterestGroup(
auction_worklet::mojom::BiddingInterestGroupPtr group) {
this->bidding_group = std::move(group);
}
StorageInterestGroup::StorageInterestGroup(StorageInterestGroup&&) = default;
StorageInterestGroup::~StorageInterestGroup() = default;
std::ostream& operator<<(std::ostream& out,
const StorageInterestGroup::KAnonymityData& kanon) {
return out << "KAnonymityData[key=`" << kanon.key << "`, k=" << kanon.k
<< ", last_updated=`" << kanon.last_updated << "`]";
}
} // namespace content
| scheib/chromium | content/browser/interest_group/storage_interest_group.cc | C++ | bsd-3-clause | 966 |
#ifndef BOOST_SIMD_INCLUDE_FUNCTIONS_SIMD_INSERT_HPP_INCLUDED
#define BOOST_SIMD_INCLUDE_FUNCTIONS_SIMD_INSERT_HPP_INCLUDED
#include <boost/simd/memory/include/functions/simd/insert.hpp>
#endif
| hainm/pythran | third_party/boost/simd/include/functions/simd/insert.hpp | C++ | bsd-3-clause | 196 |
<?php
/**
* Phergie
*
* PHP version 5
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.
* It is also available through the world-wide-web at this URL:
* http://phergie.org/license
*
* @category Phergie
* @package Phergie_Tests
* @author Phergie Development Team <team@phergie.org>
* @copyright 2008-2012 Phergie Development Team (http://phergie.org)
* @license http://phergie.org/license New BSD License
* @link http://pear.phergie.org/package/Phergie_Tests
*/
/**
* Unit test suite for Phergie_Event_Handler.
*
* @category Phergie
* @package Phergie_Tests
* @author Phergie Development Team <team@phergie.org>
* @license http://phergie.org/license New BSD License
* @link http://pear.phergie.org/package/Phergie_Tests
*/
class Phergie_Event_HandlerTest extends PHPUnit_Framework_TestCase
{
/**
* Instance of the class to test
*
* @var Phergie_Event_Handler
*/
private $events;
/**
* Plugin associated with an event added to the handler
*
* @var Phergie_Plugin_Abstract
*/
private $plugin;
/**
* Type of event added to the handler
*
* @var string
*/
private $type = 'privmsg';
/**
* Arguments for an event added to the handler
*
* @var array
*/
private $args = array('#channel', 'text');
/**
* Instantiates the class to test.
*
* @return void
*/
public function setUp()
{
$this->events = new Phergie_Event_Handler;
$this->plugin = $this->getMockForAbstractClass('Phergie_Plugin_Abstract');
}
/**
* Tests that the handler contains no events by default.
*
* @return void
*/
public function testGetEvents()
{
$expected = array();
$actual = $this->events->getEvents();
$this->assertEquals($expected, $actual);
}
/**
* Adds a mock event to the handler.
*
* @return void
*/
private function addMockEvent($type = null, $args = null)
{
if (!$type) {
$type = $this->type;
$args = $this->args;
}
$this->events->addEvent($this->plugin, $type, $args);
}
/**
* Data provider for methods requiring a valid event type and a
* corresponding set of arguments.
*
* @return array Enumerated array of enumerated arrays each containing
* a string for an event type and an enumerated array of
* arguments for that event type
*/
public function dataProviderEventTypesAndArguments()
{
return array(
array('nick', array('nickname')),
array('oper', array('username', 'password')),
array('quit', array()),
array('quit', array('message')),
array('join', array('#channel1,#channel2')),
array('join', array('#channel1,#channel2', 'key1,key2')),
array('part', array('#channel1,#channel2')),
array('mode', array('#channel', '-l', '20')),
array('topic', array('#channel', 'message')),
array('names', array('#channel1,#channel2')),
array('list', array('#channel1,#channel2')),
array('invite', array('nickname', '#channel')),
array('kick', array('#channel', 'username1,username2')),
array('kick', array('#channel', 'username', 'comment')),
array('version', array('nick_or_server')),
array('version', array('nick', 'reply')),
array('stats', array('c')),
array('stats', array('c', 'server')),
array('links', array('mask')),
array('links', array('server', 'mask')),
array('time', array('nick_or_server')),
array('time', array('nick', 'reply')),
array('connect', array('server')),
array('connect', array('server', '6667')),
array('connect', array('target', '6667', 'remote')),
array('trace', array()),
array('trace', array('server')),
array('admin', array()),
array('admin', array('server')),
array('info', array()),
array('info', array('server')),
array('privmsg', array('receiver1,receiver2', 'text')),
array('notice', array('nickname', 'text')),
array('who', array('name')),
array('who', array('name', 'o')),
array('whois', array('mask1,mask2')),
array('whois', array('server', 'mask')),
array('whowas', array('nickname')),
array('whowas', array('nickname', '9')),
array('whowas', array('nickname', '9', 'server')),
array('kill', array('nickname', 'comment')),
array('ping', array('server1')),
array('ping', array('server1', 'server2')),
array('pong', array('daemon')),
array('pong', array('daemon', 'daemon2')),
array('finger', array('nick')),
array('finger', array('nick', 'reply')),
array('error', array('message')),
);
}
/**
* Tests that the handler can receive a new event.
*
* @param string $type Event type
* @param array $args Event arguments
* @dataProvider dataProviderEventTypesAndArguments
* @return void
*/
public function testAddEventWithValidData($type, array $args)
{
$this->addMockEvent($type, $args);
$events = $this->events->getEvents();
$event = array_shift($events);
$this->assertInstanceOf('Phergie_Event_Command', $event);
$this->assertSame($this->plugin, $event->getPlugin());
$this->assertSame($type, $event->getType());
$this->assertSame($args, $event->getArguments());
}
/**
* Tests that attempting to add an event to the handler with an invalid
* type results in an exception.
*
* @return void
*/
public function testAddEventWithInvalidType()
{
$type = 'foo';
try {
$this->events->addEvent($this->plugin, $type);
$this->fail('Expected exception was not thrown');
} catch (Phergie_Event_Exception $e) {
if ($e->getCode() != Phergie_Event_Exception::ERR_UNKNOWN_EVENT_TYPE) {
$this->fail('Unexpected exception code ' . $e->getCode());
}
}
}
/**
* Tests that the events contained within the handler can be
* collectively removed.
*
* @return void
* @depends testGetEvents
* @depends testAddEventWithValidData
*/
public function testClearEvents()
{
$this->addMockEvent();
$this->events->clearEvents();
$expected = array();
$actual = $this->events->getEvents();
$this->assertSame($expected, $actual);
}
/**
* Tests that the events contained within the handler can be replaced
* with a different set of events.
*
* @return void
* @depends testAddEventWithValidData
*/
public function testReplaceEvents()
{
$this->addMockEvent();
$expected = array();
$this->events->replaceEvents($expected);
$actual = $this->events->getEvents();
$this->assertSame($expected, $actual);
}
/**
* Tests that the handler can accurately identify whether it has an
* event of a specified type.
*
* @return void
* @depends testAddEventWithValidData
*/
public function testHasEventOfType()
{
$this->assertFalse($this->events->hasEventOfType($this->type));
$this->addMockEvent();
$this->assertTrue($this->events->hasEventOfType($this->type));
}
/**
* Tests that the handler can return events it contains that are of a
* specified type.
*
* @return void
* @depends testAddEventWithValidData
*/
public function testGetEventsOfType()
{
$expected = array();
$actual = $this->events->getEventsOfType($this->type);
$this->assertSame($expected, $actual);
$this->addMockEvent();
$expected = $this->events->getEvents();
$actual = $this->events->getEventsOfType($this->type);
$this->assertSame($expected, $actual);
}
/**
* Tests that an event can be removed from the handler.
*
* @return void
* @depends testAddEventWithValidData
*/
public function testRemoveEvent()
{
$this->addMockEvent();
$events = $this->events->getEvents();
$event = array_shift($events);
$this->events->removeEvent($event);
$expected = array();
$actual = $this->events->getEvents();
$this->assertSame($expected, $actual);
}
/**
* Tests that the handler supports iteration of the events it contains.
*
* @return void
* @depends testAddEventWithValidData
*/
public function testImplementsGetIterator()
{
$reflector = new ReflectionClass('Phergie_Event_Handler');
$this->assertTrue($reflector->implementsInterface('IteratorAggregate'));
$this->addMockEvent();
$events = $this->events->getEvents();
$expected = array_shift($events);
foreach ($this->events as $actual) {
$this->assertSame($expected, $actual);
}
}
/**
* Tests that the handler supports returning a count of the events it
* contains.
*
* @return void
* @depends testAddEventWithValidData
*/
public function testImplementsCountable()
{
$reflector = new ReflectionClass('Phergie_Event_Handler');
$this->assertTrue($reflector->implementsInterface('Countable'));
$expected = 0;
$actual = count($this->events);
$this->assertSame($expected, $actual);
$this->addMockEvent();
$expected = 1;
$actual = count($this->events);
$this->assertSame($expected, $actual);
}
}
| sudounlv/ircbot-php | Tests/Phergie/Event/HandlerTest.php | PHP | bsd-3-clause | 10,066 |
<?php
namespace Symbiote\QueuedJobs\Services;
use Symbiote\QueuedJobs\DataObjects\QueuedJobDescriptor;
/**
* Default method for handling items run via the cron
*
* @author marcus@symbiote.com.au
* @license BSD License http://silverstripe.org/bsd-license/
*/
class DefaultQueueHandler
{
public function startJobOnQueue(QueuedJobDescriptor $job)
{
$job->activateOnQueue();
}
public function scheduleJob(QueuedJobDescriptor $job, $date)
{
// noop
}
}
| nyeholt/silverstripe-queuedjobs | src/Services/DefaultQueueHandler.php | PHP | bsd-3-clause | 497 |
<?php
namespace Payment\Controller;
use Eva\Mvc\Controller\ActionController,
Payment\Service\Exception,
Eva\View\Model\ViewModel;
class ResponseController extends ActionController
{
protected $addResources = array(
);
public function indexAction()
{
$adapter = $this->params()->fromQuery('adapter');
$callback = $this->params()->fromQuery('callback');
$amount = $this->params()->fromQuery('amount');
$secretKey = $this->params()->fromQuery('secretKey');
$requestTime = $this->params()->fromQuery('time');
$signed = $this->params()->fromQuery('signed');
$responseData = $this->params()->fromQuery();
if (!$responseData) {
$responseData = $this->params()->fromPost();
}
if (isset($responseData['notify_id']) && isset($responseData['trade_status'])) {
return $this->alipayResponse();
}
if(!$amount){
throw new Exception\InvalidArgumentException(sprintf(
'No payment amount found'
));
}
if(!$adapter){
throw new Exception\InvalidArgumentException(sprintf(
'No payment adapter key found'
));
}
if(!$callback){
throw new Exception\InvalidArgumentException(sprintf(
'No payment callback found'
));
}
if(!$secretKey){
throw new Exception\InvalidArgumentException(sprintf(
'No payment secretKey found'
));
}
if(!$requestTime){
throw new Exception\InvalidArgumentException(sprintf(
'No payment request time found'
));
}
if(!$signed){
throw new Exception\InvalidArgumentException(sprintf(
'No payment signed time found'
));
}
if (!$this->authenticate($this->params()->fromQuery())) {
throw new Exception\InvalidArgumentException(sprintf(
'Signed not match'
));
return;
}
$adapter = $adapter == 'paypalec' ? 'PaypalEc' : 'AlipayEc';
$pay = new \Payment\Service\Payment($adapter);
$pay->setServiceLocator($this->getServiceLocator());
$pay->setStep('response');
$pay->saveResponseLog($secretKey, $responseData);
if ($callback == 'notify') {
return;
}
if($callback){
return $this->redirect()->toUrl($callback);
}
}
public function authenticate($params)
{
$adapter = $params['adapter'];
$callback = $params['callback'];
$amount = $params['amount'];
$secretKey = $params['secretKey'];
$requestTime = $params['time'];
$signed = $params['signed'];
$itemModel = \Eva\Api::_()->getModel('Payment\Model\Log');
$log = $itemModel->getLog($secretKey, array(
'self' => array(
'*',
'unserializeRequestData()',
'unserializeResponseData()',
),
));
if (!$log) {
return false;
}
$adapter = $adapter == 'paypalec' ? 'PaypalEc' : 'AlipayEc';
$pay = new \Payment\Service\Payment($adapter);
$pay->setServiceLocator($this->getServiceLocator());
$authenticate = $pay->setAmount($amount)
->setRequestTime($requestTime)
->setlogData($log['requestData'])
->setStep('response')
->getSigned();
if ($authenticate !== $signed) {
return false;
}
return true;
}
public function alipayResponse()
{
$callback = $this->params()->fromQuery('callback');
$responseData = $this->params()->fromQuery();
if (!isset($responseData['notify_id'])) {
$responseData = $this->params()->fromPost();
$method = 'notify';
}
$config = \Eva\Api::_()->getModuleConfig('Payment');
$options = $config['payment']['alipay'];
$pay = new \Payment\Service\Payment('AlipayEc', false ,$options);
$verify_result = $pay->verify();
if ($verify_result) {
$pay->setStep('response');
$pay->saveResponseLog($responseData['out_trade_no'], $responseData);
}
if ($callback == 'notify') {
return;
}
if($callback){
return $this->redirect()->toUrl($callback);
}
}
}
| Brother-Simon/eva-engine | module/Payment/src/Payment/Controller/ResponseController.php | PHP | bsd-3-clause | 4,610 |
import sys
import os
import glob
import shutil
import datetime
assert 'pymel' not in sys.modules or 'PYMEL_INCLUDE_EXAMPLES' in os.environ, "to generate docs PYMEL_INCLUDE_EXAMPLES env var must be set before pymel is imported"
# remember, the processed command examples are not version specific. you must
# run cmdcache.fixCodeExamples() to bring processed examples in from the raw
# version-specific example caches
os.environ['PYMEL_INCLUDE_EXAMPLES'] = 'True'
pymel_root = os.path.dirname(os.path.dirname(sys.modules[__name__].__file__))
docsdir = os.path.join(pymel_root, 'docs')
stubdir = os.path.join(pymel_root, 'extras', 'completion', 'py')
useStubs = False
if useStubs:
sys.path.insert(0, stubdir)
import pymel
print pymel.__file__
else:
import pymel
# make sure dynamic modules are fully loaded
from pymel.core.uitypes import *
from pymel.core.nodetypes import *
version = pymel.__version__.rsplit('.',1)[0]
SOURCE = 'source'
BUILD_ROOT = 'build'
BUILD = os.path.join(BUILD_ROOT, version)
sourcedir = os.path.join(docsdir, SOURCE)
gendir = os.path.join(sourcedir, 'generated')
buildrootdir = os.path.join(docsdir, BUILD_ROOT)
builddir = os.path.join(docsdir, BUILD)
from pymel.internal.cmdcache import fixCodeExamples
def generate(clean=True):
"delete build and generated directories and generate a top-level documentation source file for each module."
print "generating %s - %s" % (docsdir, datetime.datetime.now())
from sphinx.ext.autosummary.generate import main as sphinx_autogen
if clean:
clean_build()
clean_generated()
os.chdir(sourcedir)
sphinx_autogen( [''] + '--templates ../templates modules.rst'.split() )
sphinx_autogen( [''] + '--templates ../templates'.split() + glob.glob('generated/pymel.*.rst') )
print "...done generating %s - %s" % (docsdir, datetime.datetime.now())
def clean_build():
"delete existing build directory"
if os.path.exists(buildrootdir):
print "removing %s - %s" % (buildrootdir, datetime.datetime.now())
shutil.rmtree(buildrootdir)
def clean_generated():
"delete existing generated directory"
if os.path.exists(gendir):
print "removing %s - %s" % (gendir, datetime.datetime.now())
shutil.rmtree(gendir)
def find_dot():
if os.name == 'posix':
dot_bin = 'dot'
else:
dot_bin = 'dot.exe'
for p in os.environ['PATH'].split(os.pathsep):
d = os.path.join(p, dot_bin)
if os.path.exists(d):
return d
raise TypeError('cannot find graphiz dot executable in the path (%s)' % os.environ['PATH'])
def copy_changelog():
changelog = os.path.join(pymel_root, 'CHANGELOG.rst')
whatsnew = os.path.join(pymel_root, 'docs', 'source', 'whats_new.rst')
shutil.copy2(changelog, whatsnew)
def build(clean=True, **kwargs):
from sphinx import main as sphinx_build
print "building %s - %s" % (docsdir, datetime.datetime.now())
if not os.path.isdir(gendir):
generate()
os.chdir( docsdir )
if clean:
clean_build()
copy_changelog()
#mkdir -p build/html build/doctrees
#import pymel.internal.cmdcache as cmdcache
#cmdcache.fixCodeExamples()
opts = ['']
opts += '-b html -d build/doctrees'.split()
# set some defaults
if not kwargs.get('graphviz_dot', None):
kwargs['graphviz_dot'] = find_dot()
for key, value in kwargs.iteritems():
opts.append('-D')
opts.append( key.strip() + '=' + value.strip() )
opts.append('-P')
opts.append(SOURCE)
opts.append(BUILD)
sphinx_build(opts)
print "...done building %s - %s" % (docsdir, datetime.datetime.now())
| shrtcww/pymel | maintenance/docs.py | Python | bsd-3-clause | 3,694 |
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/modules/webcodecs/codec_logger.h"
#include <string>
#include "media/base/media_util.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/core/inspector/inspector_media_context_impl.h"
#include "third_party/blink/renderer/platform/wtf/wtf.h"
namespace blink {
CodecLogger::CodecLogger(
ExecutionContext* context,
scoped_refptr<base::SingleThreadTaskRunner> task_runner) {
DCHECK(context);
// Owners of |this| should be ExecutionLifeCycleObservers, and should call
// Neuter() if |context| is destroyed. The MediaInspectorContextImpl must
// outlive |parent_media_log_|. If |context| is already destroyed, owners
// might never call Neuter(), and MediaInspectorContextImpl* could be garbage
// collected before |parent_media_log_| is destroyed.
if (!context->IsContextDestroyed()) {
parent_media_log_ = Platform::Current()->GetMediaLog(
MediaInspectorContextImpl::From(*context), task_runner,
/*is_on_worker=*/!IsMainThread());
}
// NullMediaLog silently and safely does nothing.
if (!parent_media_log_)
parent_media_log_ = std::make_unique<media::NullMediaLog>();
// This allows us to destroy |parent_media_log_| and stop logging,
// without causing problems to |media_log_| users.
media_log_ = parent_media_log_->Clone();
}
DOMException* CodecLogger::MakeException(std::string error_msg,
media::Status status) {
media_log_->NotifyError(status);
if (status_code_ == media::StatusCode::kOk) {
DCHECK(!status.is_ok());
status_code_ = status.code();
}
return MakeGarbageCollected<DOMException>(DOMExceptionCode::kOperationError,
error_msg.c_str());
}
DOMException* CodecLogger::MakeException(std::string error_msg,
media::StatusCode code,
const base::Location& location) {
if (status_code_ == media::StatusCode::kOk) {
DCHECK_NE(code, media::StatusCode::kOk);
status_code_ = code;
}
return MakeException(error_msg, media::Status(code, error_msg, location));
}
CodecLogger::~CodecLogger() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
}
void CodecLogger::Neuter() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
parent_media_log_ = nullptr;
}
} // namespace blink
| scheib/chromium | third_party/blink/renderer/modules/webcodecs/codec_logger.cc | C++ | bsd-3-clause | 2,677 |
package org.broadinstitute.hellbender.utils.dragstr;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.util.Arrays;
import java.util.Iterator;
import java.util.stream.IntStream;
/**
* Unit tests for {@link DoubleSequence}
*/
public class DoubleSequenceTest {
@Test(dataProvider = "correctSequenceData")
public void testCorrectSequence(final String spec, final double[] expectedValues, final double epsilon) {
final DoubleSequence subject = new DoubleSequence(spec);
Assert.assertEquals(subject.size(), expectedValues.length);
// check single value access:
for (int i = 0; i < expectedValues.length; i++) {
Assert.assertEquals(subject.get(i), expectedValues[i], epsilon);
}
// check array access:
final double[] actualValues = subject.toDoubleArray();
Assert.assertNotNull(actualValues);
Assert.assertEquals(actualValues, expectedValues, epsilon);
}
@Test(dataProvider = "badSpecsData", expectedExceptions = RuntimeException.class)
public void testBadSpecs(final String spec) {
new DoubleSequence(spec);
}
@DataProvider(name = "badSpecsData")
public Iterator<Object[]> badSpecsData() {
return Arrays.stream(new String[] {null, "", "::", "1:2", "2:2:2:2:2", "2,2", "4;5;100", "10:-1:100"})
.map(s -> new Object[] { s }).iterator();
}
@DataProvider(name = "correctSequenceData")
public Iterator<Object[]> correctSequenceData() {
final String STD_EPSILON = "0.001";
final String[] testCases = {
"0:1:10", "0,1,2,3,4,5,6,7,8,9,10", STD_EPSILON,
"-1:2.5:5", "-1,1.5,4", STD_EPSILON,
"1:1e-1:2.3", "1,1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2.0,2.1,2.2,2.3", STD_EPSILON,
"5:-1:1", "5,4,3,2,1", STD_EPSILON,
"1:0.00001:1", "1", STD_EPSILON,
"5:-123:5", "5", STD_EPSILON,
"8:1:10.00001", "8,9,10.00001", "0.0000000001",
};
return IntStream.range(0, testCases.length / 3)
.map(i -> 3 * i)
.mapToObj(i -> {
final String spec = testCases[i++];
final String strValues = testCases[i++];
final double epsilon = Double.parseDouble(testCases[i]);
final double[] dblValues = Arrays.stream(strValues.split("\\s*,\\s*")).mapToDouble(Double::parseDouble).toArray();
return new Object[]{spec, dblValues, epsilon};
}).iterator();
}
}
| broadinstitute/hellbender | src/test/java/org/broadinstitute/hellbender/utils/dragstr/DoubleSequenceTest.java | Java | bsd-3-clause | 2,666 |
// -*-Mode: C++;-*-
// * BeginRiceCopyright *****************************************************
//
// $HeadURL$
// $Id$
//
// --------------------------------------------------------------------------
// Part of HPCToolkit (hpctoolkit.org)
//
// Information about sources of support for research and development of
// HPCToolkit is at 'hpctoolkit.org' and in 'README.Acknowledgments'.
// --------------------------------------------------------------------------
//
// Copyright ((c)) 2002-2015, Rice University
// 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 Rice University (RICE) 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 RICE 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 RICE 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.
//
// ******************************************************* EndRiceCopyright *
//***************************************************************************
//
// File:
// $HeadURL$
//
// Purpose:
// [The purpose of this file]
//
// Description:
// [The set of functions, macros, etc. defined in the file]
//
//***************************************************************************
#ifndef LRULIST_H_
#define LRULIST_H_
#include <vector>
#include <list>
using std::list;
using std::vector;
namespace TraceviewerServer {
template <typename T>
class LRUList {
private:
int totalPages;
int usedPages;
int currentFront;
list<T*> useOrder;
list<T*> removed;
vector<typename list<T*>::iterator> iters;
public:
/**
* It's a special data structure that uses a little extra memory in exchange
* for all operations running in constant time. Objects are added to the
* data structure and given an index that identifies them.
* Once added, objects are not deleted; they are either on the "in use" list,
* which for VersatileMemoryPage corresponds to being mapped, or they are on
* the "not in use" list, which corresponds to not being mapped. An object
* must only be added with addNew() once. If it is removed from the list
* with remove(), it must be added with reAdd(). It is not necessary to call
* putOnTop() after adding an element as it will already be on top.
*/
LRUList(int expectedMaxSize)//Up to linear time
{
iters.reserve(expectedMaxSize);
totalPages = 0;
usedPages = 0;
currentFront = -1;
}
int addNew(T* toAdd)//constant time
{
useOrder.push_front(toAdd);
int index = totalPages++;
currentFront = index;
iters.push_back(useOrder.begin());
usedPages++;
return index;
}
int addNewUnused(T* toAdd)//constant time
{
removed.push_front(toAdd);
int index = totalPages++;
iters.push_back(removed.begin());
return index;
}
void putOnTop(int index)//Constant time
{
if (index == currentFront) return;
typename list<T*>::iterator it;
it = iters[index];
useOrder.splice(useOrder.begin(), useOrder, it);
currentFront = index;
}
T* getLast()
{
return useOrder.back();
}
void removeLast()//Constant time
{
removed.splice(removed.end(), useOrder, --useOrder.end());
usedPages--;
}
void reAdd(int index)//Constant time
{
typename list<T*>::iterator it = iters[index];
useOrder.splice(useOrder.begin(), removed, it);
currentFront = index;
usedPages++;
}
int getTotalPageCount()//Constant time
{
return totalPages;
}
int getUsedPageCount()
{
return usedPages;
}
virtual ~LRUList()
{
}
/*int dump()
{
int x = 0;
puts("Objects \"in use\" from most recently used to least recently used");
typename list<T*>::iterator it = useOrder.begin();
for(; it != useOrder.end(); ++it){
printf("%d\n", ((TestData*)*it)->index);
x++;
}
puts("Objects \"not in use\" from most recently used to least recently used");
it = removed.begin();
for(; it != removed.end(); ++it){
printf("%d\n", ((TestData*)*it)->index);
}
cout << "Used count: " << usedPages <<" supposed to be " << x<<endl;
return x;
}*/
};
} /* namespace TraceviewerServer */
#endif /* LRULIST_H_ */
| zcth428/hpctoolkit111 | src/tool/hpcserver/LRUList.hpp | C++ | bsd-3-clause | 5,239 |
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/core/layout/ng/ng_base_layout_algorithm_test.h"
#include <sstream>
#include "third_party/blink/renderer/core/dom/tag_collection.h"
#include "third_party/blink/renderer/core/layout/layout_block_flow.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_box_state.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_break_token.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_child_layout_context.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_cursor.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_node.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_physical_line_box_fragment.h"
#include "third_party/blink/renderer/core/layout/ng/ng_box_fragment_builder.h"
#include "third_party/blink/renderer/core/layout/ng/ng_constraint_space_builder.h"
#include "third_party/blink/renderer/core/layout/ng/ng_layout_result.h"
#include "third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.h"
namespace blink {
namespace {
const NGPhysicalLineBoxFragment* FindBlockInInlineLineBoxFragment(
Element* container) {
NGInlineCursor cursor(*To<LayoutBlockFlow>(container->GetLayoutObject()));
for (cursor.MoveToFirstLine(); cursor; cursor.MoveToNextLine()) {
const NGPhysicalLineBoxFragment* fragment =
cursor.Current()->LineBoxFragment();
DCHECK(fragment);
if (fragment->IsBlockInInline())
return fragment;
}
return nullptr;
}
class NGInlineLayoutAlgorithmTest : public NGBaseLayoutAlgorithmTest {
protected:
static std::string AsFragmentItemsString(const LayoutBlockFlow& root) {
std::ostringstream ostream;
ostream << std::endl;
for (NGInlineCursor cursor(root); cursor; cursor.MoveToNext()) {
const auto& item = *cursor.CurrentItem();
ostream << item << " " << item.RectInContainerFragment() << std::endl;
}
return ostream.str();
}
};
TEST_F(NGInlineLayoutAlgorithmTest, Types) {
SetBodyInnerHTML(R"HTML(
<!DOCTYPE html>
<div id="normal">normal</div>
<div id="empty"><span></span></div>
)HTML");
NGInlineCursor normal(
*To<LayoutBlockFlow>(GetLayoutObjectByElementId("normal")));
normal.MoveToFirstLine();
EXPECT_FALSE(normal.Current()->LineBoxFragment()->IsEmptyLineBox());
NGInlineCursor empty(
*To<LayoutBlockFlow>(GetLayoutObjectByElementId("empty")));
empty.MoveToFirstLine();
EXPECT_TRUE(empty.Current()->LineBoxFragment()->IsEmptyLineBox());
}
TEST_F(NGInlineLayoutAlgorithmTest, TypesForBlockInInline) {
ScopedLayoutNGBlockInInlineForTest block_in_inline_scope(true);
SetBodyInnerHTML(R"HTML(
<!DOCTYPE html>
<div id="block-in-inline">
<span><div>normal</div></span>
</div>
<div id="block-in-inline-empty">
<span><div></div></span>
</div>
<div id="block-in-inline-height">
<span><div style="height: 100px"></div></span>
</div>
)HTML");
// Regular block-in-inline.
NGInlineCursor block_in_inline(
*To<LayoutBlockFlow>(GetLayoutObjectByElementId("block-in-inline")));
block_in_inline.MoveToFirstLine();
EXPECT_TRUE(block_in_inline.Current()->LineBoxFragment()->IsEmptyLineBox());
EXPECT_FALSE(block_in_inline.Current()->LineBoxFragment()->IsBlockInInline());
block_in_inline.MoveToNextLine();
EXPECT_FALSE(block_in_inline.Current()->LineBoxFragment()->IsEmptyLineBox());
EXPECT_TRUE(block_in_inline.Current()->LineBoxFragment()->IsBlockInInline());
int block_count = 0;
for (NGInlineCursor children = block_in_inline.CursorForDescendants();
children; children.MoveToNext()) {
if (children.Current()->BoxFragment() &&
children.Current()->BoxFragment()->IsBlockInInline())
++block_count;
}
EXPECT_EQ(block_count, 1);
block_in_inline.MoveToNextLine();
EXPECT_TRUE(block_in_inline.Current()->LineBoxFragment()->IsEmptyLineBox());
EXPECT_FALSE(block_in_inline.Current()->LineBoxFragment()->IsBlockInInline());
// If the block is empty and self-collapsing, |IsEmptyLineBox| should be set.
NGInlineCursor block_in_inline_empty(*To<LayoutBlockFlow>(
GetLayoutObjectByElementId("block-in-inline-empty")));
block_in_inline_empty.MoveToFirstLine();
block_in_inline_empty.MoveToNextLine();
EXPECT_TRUE(
block_in_inline_empty.Current()->LineBoxFragment()->IsEmptyLineBox());
EXPECT_TRUE(
block_in_inline_empty.Current()->LineBoxFragment()->IsBlockInInline());
// Test empty but non-self-collapsing block in an inline box.
NGInlineCursor block_in_inline_height(*To<LayoutBlockFlow>(
GetLayoutObjectByElementId("block-in-inline-height")));
block_in_inline_height.MoveToFirstLine();
block_in_inline_height.MoveToNextLine();
EXPECT_FALSE(
block_in_inline_height.Current()->LineBoxFragment()->IsEmptyLineBox());
EXPECT_TRUE(
block_in_inline_height.Current()->LineBoxFragment()->IsBlockInInline());
}
TEST_F(NGInlineLayoutAlgorithmTest, BreakToken) {
LoadAhem();
SetBodyInnerHTML(R"HTML(
<!DOCTYPE html>
<style>
html {
font: 10px/1 Ahem;
}
#container {
width: 50px; height: 20px;
}
</style>
<div id=container>123 456 789</div>
)HTML");
// Perform 1st Layout.
auto* block_flow =
To<LayoutBlockFlow>(GetLayoutObjectByElementId("container"));
NGInlineNode inline_node(block_flow);
LogicalSize size(LayoutUnit(50), LayoutUnit(20));
NGConstraintSpaceBuilder builder(
WritingMode::kHorizontalTb,
{WritingMode::kHorizontalTb, TextDirection::kLtr},
/* is_new_fc */ false);
builder.SetAvailableSize(size);
NGConstraintSpace constraint_space = builder.ToConstraintSpace();
NGInlineChildLayoutContext context;
NGBoxFragmentBuilder container_builder(
block_flow, block_flow->Style(),
block_flow->Style()->GetWritingDirection());
NGFragmentItemsBuilder items_builder(inline_node,
container_builder.GetWritingDirection());
container_builder.SetItemsBuilder(&items_builder);
context.SetItemsBuilder(&items_builder);
scoped_refptr<const NGLayoutResult> layout_result =
inline_node.Layout(constraint_space, nullptr, &context);
const auto& line1 = layout_result->PhysicalFragment();
EXPECT_TRUE(line1.BreakToken());
// Perform 2nd layout with the break token from the 1st line.
scoped_refptr<const NGLayoutResult> layout_result2 =
inline_node.Layout(constraint_space, line1.BreakToken(), &context);
const auto& line2 = layout_result2->PhysicalFragment();
EXPECT_TRUE(line2.BreakToken());
// Perform 3rd layout with the break token from the 2nd line.
scoped_refptr<const NGLayoutResult> layout_result3 =
inline_node.Layout(constraint_space, line2.BreakToken(), &context);
const auto& line3 = layout_result3->PhysicalFragment();
EXPECT_FALSE(line3.BreakToken());
}
// This test ensures box fragments are generated when necessary, even when the
// line is empty. One such case is when the line contains a containing box of an
// out-of-flow object.
TEST_F(NGInlineLayoutAlgorithmTest,
EmptyLineWithOutOfFlowInInlineContainingBlock) {
SetBodyInnerHTML(R"HTML(
<!DOCTYPE html>
<style>
oof-container {
position: relative;
}
oof {
position: absolute;
width: 100px;
height: 100px;
}
html, body { margin: 0; }
html {
font-size: 10px;
}
</style>
<div id=container>
<oof-container id=target>
<oof></oof>
</oof-container>
</div>
)HTML");
auto* block_flow =
To<LayoutBlockFlow>(GetLayoutObjectByElementId("container"));
const NGPhysicalBoxFragment* container = block_flow->GetPhysicalFragment(0);
ASSERT_TRUE(container);
EXPECT_EQ(LayoutUnit(), container->Size().height);
NGInlineCursor line_box(*block_flow);
ASSERT_TRUE(line_box);
ASSERT_TRUE(line_box.Current().IsLineBox());
EXPECT_EQ(PhysicalSize(), line_box.Current().Size());
NGInlineCursor off_container(line_box);
off_container.MoveToNext();
ASSERT_TRUE(off_container);
ASSERT_EQ(GetLayoutObjectByElementId("target"),
off_container.Current().GetLayoutObject());
EXPECT_EQ(PhysicalSize(), off_container.Current().Size());
}
// This test ensures that if an inline box generates (or does not generate) box
// fragments for a wrapped line, it should consistently do so for other lines
// too, when the inline box is fragmented to multiple lines.
TEST_F(NGInlineLayoutAlgorithmTest, BoxForEndMargin) {
LoadAhem();
SetBodyInnerHTML(R"HTML(
<!DOCTYPE html>
<style>
html, body { margin: 0; }
#container {
font: 10px/1 Ahem;
width: 50px;
}
span {
border-right: 10px solid blue;
}
</style>
<!-- This line wraps, and only 2nd line has a border. -->
<div id=container>12 <span id=span>3 45</span> 6</div>
)HTML");
auto* block_flow =
To<LayoutBlockFlow>(GetLayoutObjectByElementId("container"));
NGInlineCursor line_box(*block_flow);
ASSERT_TRUE(line_box) << "line_box is at start of first line.";
ASSERT_TRUE(line_box.Current().IsLineBox());
line_box.MoveToNextLine();
ASSERT_TRUE(line_box) << "line_box is at start of second line.";
NGInlineCursor cursor(line_box);
ASSERT_TRUE(line_box.Current().IsLineBox());
cursor.MoveToNext();
ASSERT_TRUE(cursor);
EXPECT_EQ(GetLayoutObjectByElementId("span"),
cursor.Current().GetLayoutObject());
// The <span> generates a box fragment for the 2nd line because it has a
// right border. It should also generate a box fragment for the 1st line even
// though there's no borders on the 1st line.
const NGPhysicalBoxFragment* box_fragment = cursor.Current().BoxFragment();
ASSERT_TRUE(box_fragment);
EXPECT_EQ(NGPhysicalFragment::kFragmentBox, box_fragment->Type());
line_box.MoveToNextLine();
ASSERT_FALSE(line_box) << "block_flow has two lines.";
}
// A block with inline children generates fragment tree as follows:
// - A box fragment created by NGBlockNode
// - A wrapper box fragment created by NGInlineNode
// - Line box fragments.
// This test verifies that borders/paddings are applied to the wrapper box.
TEST_F(NGInlineLayoutAlgorithmTest, ContainerBorderPadding) {
SetBodyInnerHTML(R"HTML(
<!DOCTYPE html>
<style>
html, body { margin: 0; }
div {
padding-left: 5px;
padding-top: 10px;
display: flow-root;
}
</style>
<div id=container>test</div>
)HTML");
auto* block_flow =
To<LayoutBlockFlow>(GetLayoutObjectByElementId("container"));
NGBlockNode block_node(block_flow);
NGConstraintSpace space =
NGConstraintSpace::CreateFromLayoutObject(*block_flow);
scoped_refptr<const NGLayoutResult> layout_result = block_node.Layout(space);
EXPECT_TRUE(layout_result->BfcBlockOffset().has_value());
EXPECT_EQ(0, *layout_result->BfcBlockOffset());
EXPECT_EQ(0, layout_result->BfcLineOffset());
PhysicalOffset line_offset =
layout_result->PhysicalFragment().Children()[0].Offset();
EXPECT_EQ(5, line_offset.left);
EXPECT_EQ(10, line_offset.top);
}
// The test leaks memory. crbug.com/721932
#if defined(ADDRESS_SANITIZER)
#define MAYBE_VerticalAlignBottomReplaced DISABLED_VerticalAlignBottomReplaced
#else
#define MAYBE_VerticalAlignBottomReplaced VerticalAlignBottomReplaced
#endif
TEST_F(NGInlineLayoutAlgorithmTest, MAYBE_VerticalAlignBottomReplaced) {
SetBodyInnerHTML(R"HTML(
<!DOCTYPE html>
<style>
html { font-size: 10px; }
img { vertical-align: bottom; }
#container { display: flow-root; }
</style>
<div id=container><img src="#" width="96" height="96"></div>
)HTML");
auto* block_flow =
To<LayoutBlockFlow>(GetLayoutObjectByElementId("container"));
NGInlineCursor cursor(*block_flow);
ASSERT_TRUE(cursor);
EXPECT_EQ(LayoutUnit(96), cursor.Current().Size().height);
cursor.MoveToNext();
ASSERT_TRUE(cursor);
EXPECT_EQ(LayoutUnit(0), cursor.Current().OffsetInContainerFragment().top)
<< "Offset top of <img> should be zero.";
}
// Verifies that text can flow correctly around floats that were positioned
// before the inline block.
TEST_F(NGInlineLayoutAlgorithmTest, TextFloatsAroundFloatsBefore) {
SetBodyInnerHTML(R"HTML(
<!DOCTYPE html>
<style>
* {
font-family: "Arial", sans-serif;
font-size: 20px;
}
#container {
height: 200px; width: 200px; outline: solid blue;
}
#left-float1 {
float: left; width: 30px; height: 30px; background-color: blue;
}
#left-float2 {
float: left; width: 10px; height: 10px;
background-color: purple;
}
#right-float {
float: right; width: 40px; height: 40px; background-color: yellow;
}
</style>
<div id="container">
<div id="left-float1"></div>
<div id="left-float2"></div>
<div id="right-float"></div>
<span id="text">The quick brown fox jumps over the lazy dog</span>
</div>
)HTML");
// ** Run LayoutNG algorithm **
NGConstraintSpace space;
scoped_refptr<const NGPhysicalBoxFragment> html_fragment;
std::tie(html_fragment, space) = RunBlockLayoutAlgorithmForElement(
GetDocument().getElementsByTagName("html")->item(0));
auto* body_fragment =
To<NGPhysicalBoxFragment>(html_fragment->Children()[0].get());
auto* container_fragment =
To<NGPhysicalBoxFragment>(body_fragment->Children()[0].get());
Vector<PhysicalOffset> line_offsets;
for (const auto& child : container_fragment->Children()) {
if (!child->IsLineBox())
continue;
line_offsets.push_back(child.Offset());
}
// Line break points may vary by minor differences in fonts.
// The test is valid as long as we have 3 or more lines and their positions
// are correct.
EXPECT_GE(line_offsets.size(), 3UL);
// 40 = #left-float1' width 30 + #left-float2 10
EXPECT_EQ(LayoutUnit(40), line_offsets[0].left);
// 40 = #left-float1' width 30
EXPECT_EQ(LayoutUnit(30), line_offsets[1].left);
EXPECT_EQ(LayoutUnit(), line_offsets[2].left);
}
// Verifies that text correctly flows around the inline float that fits on
// the same text line.
TEST_F(NGInlineLayoutAlgorithmTest, TextFloatsAroundInlineFloatThatFitsOnLine) {
SetBodyInnerHTML(R"HTML(
<!DOCTYPE html>
<style>
* {
font-family: "Arial", sans-serif;
font-size: 18px;
}
#container {
height: 200px; width: 200px; outline: solid orange;
}
#narrow-float {
float: left; width: 30px; height: 30px; background-color: blue;
}
</style>
<div id="container">
<span id="text">
The quick <div id="narrow-float"></div> brown fox jumps over the lazy
</span>
</div>
)HTML");
auto* block_flow =
To<LayoutBlockFlow>(GetLayoutObjectByElementId("container"));
const NGPhysicalBoxFragment* block_box = block_flow->GetPhysicalFragment(0);
ASSERT_TRUE(block_box);
// Two lines.
ASSERT_EQ(2u, block_box->Children().size());
PhysicalOffset first_line_offset = block_box->Children()[1].Offset();
// 30 == narrow-float's width.
EXPECT_EQ(LayoutUnit(30), first_line_offset.left);
Element* span = GetDocument().getElementById("text");
// 38 == narrow-float's width + body's margin.
EXPECT_EQ(LayoutUnit(38), span->OffsetLeft());
Element* narrow_float = GetDocument().getElementById("narrow-float");
// 8 == body's margin.
EXPECT_EQ(8, narrow_float->OffsetLeft());
EXPECT_EQ(8, narrow_float->OffsetTop());
}
// Verifies that the inline float got pushed to the next line if it doesn't
// fit the current line.
TEST_F(NGInlineLayoutAlgorithmTest,
TextFloatsAroundInlineFloatThatDoesNotFitOnLine) {
SetBodyInnerHTML(R"HTML(
<!DOCTYPE html>
<style>
* {
font-family: "Arial", sans-serif;
font-size: 19px;
}
#container {
height: 200px; width: 200px; outline: solid orange;
}
#wide-float {
float: left; width: 160px; height: 30px; background-color: red;
}
</style>
<div id="container">
<span id="text">
The quick <div id="wide-float"></div> brown fox jumps over the lazy dog
</span>
</div>
)HTML");
Element* wide_float = GetDocument().getElementById("wide-float");
// 8 == body's margin.
EXPECT_EQ(8, wide_float->OffsetLeft());
}
// Verifies that if an inline float pushed to the next line then all others
// following inline floats positioned with respect to the float's top edge
// alignment rule.
TEST_F(NGInlineLayoutAlgorithmTest,
FloatsArePositionedWithRespectToTopEdgeAlignmentRule) {
SetBodyInnerHTML(R"HTML(
<!DOCTYPE html>
<style>
* {
font-family: "Arial", sans-serif;
font-size: 19px;
}
#container {
height: 200px; width: 200px; outline: solid orange;
}
#left-narrow {
float: left; width: 5px; height: 30px; background-color: blue;
}
#left-wide {
float: left; width: 160px; height: 30px; background-color: red;
}
</style>
<div id="container">
<span id="text">
The quick <div id="left-wide"></div> brown <div id="left-narrow"></div>
fox jumps over the lazy dog
</span>
</div>
)HTML");
Element* wide_float = GetDocument().getElementById("left-wide");
// 8 == body's margin.
EXPECT_EQ(8, wide_float->OffsetLeft());
Element* narrow_float = GetDocument().getElementById("left-narrow");
// 160 float-wide's width + 8 body's margin.
EXPECT_EQ(160 + 8, narrow_float->OffsetLeft());
// On the same line.
EXPECT_EQ(wide_float->OffsetTop(), narrow_float->OffsetTop());
}
// Block-in-inline is not reusable. See |EndOfReusableItems|.
TEST_F(NGInlineLayoutAlgorithmTest, BlockInInlineAppend) {
ScopedLayoutNGBlockInInlineForTest scoped_for_test(true);
SetBodyInnerHTML(R"HTML(
<!DOCTYPE html>
<style>
:root {
font-size: 10px;
}
#container {
width: 10ch;
}
</style>
<div id="container">
<span id="span">
12345678
<div>block</div>
12345678
</span>
12345678
</div>
)HTML");
Element* container_element = GetElementById("container");
scoped_refptr<const NGPhysicalLineBoxFragment> before_append =
FindBlockInInlineLineBoxFragment(container_element);
ASSERT_TRUE(before_append);
Document& doc = GetDocument();
container_element->appendChild(doc.createTextNode("12345678"));
UpdateAllLifecyclePhasesForTest();
scoped_refptr<const NGPhysicalLineBoxFragment> after_append =
FindBlockInInlineLineBoxFragment(container_element);
EXPECT_NE(before_append, after_append);
}
// Verifies that InlineLayoutAlgorithm positions floats with respect to their
// margins.
TEST_F(NGInlineLayoutAlgorithmTest, PositionFloatsWithMargins) {
SetBodyInnerHTML(R"HTML(
<!DOCTYPE html>
<style>
#container {
height: 200px; width: 200px; outline: solid orange;
}
#left {
float: left; width: 5px; height: 30px; background-color: blue;
margin: 10%;
}
</style>
<div id="container">
<span id="text">
The quick <div id="left"></div> brown fox jumps over the lazy dog
</span>
</div>
)HTML");
Element* span = GetElementById("text");
// 53 = sum of left's inline margins: 40 + left's width: 5 + body's margin: 8
EXPECT_EQ(LayoutUnit(53), span->OffsetLeft());
}
// Test glyph bounding box causes ink overflow.
TEST_F(NGInlineLayoutAlgorithmTest, InkOverflow) {
LoadAhem();
SetBodyInnerHTML(R"HTML(
<!DOCTYPE html>
<style>
#container {
font: 20px/.5 Ahem;
display: flow-root;
}
</style>
<div id="container">Hello</div>
)HTML");
auto* block_flow =
To<LayoutBlockFlow>(GetLayoutObjectByElementId("container"));
const NGPhysicalBoxFragment& box_fragment =
*block_flow->GetPhysicalFragment(0);
EXPECT_EQ(LayoutUnit(10), box_fragment.Size().height);
NGInlineCursor cursor(*block_flow);
PhysicalRect ink_overflow = cursor.Current().InkOverflow();
EXPECT_EQ(LayoutUnit(-5), ink_overflow.offset.top);
EXPECT_EQ(LayoutUnit(20), ink_overflow.size.height);
}
// See also NGInlineLayoutAlgorithmTest.TextCombineFake
TEST_F(NGInlineLayoutAlgorithmTest, TextCombineBasic) {
ScopedLayoutNGTextCombineForTest enable_layout_ng_text_combine(true);
LoadAhem();
InsertStyleElement(
"body { margin: 0px; font: 100px/110px Ahem; }"
"c { text-combine-upright: all; }"
"div { writing-mode: vertical-rl; }");
SetBodyInnerHTML("<div id=root>a<c id=target>01234</c>b</div>");
EXPECT_EQ(R"DUMP(
{Line #descendants=5 LTR Standard} "0,0 110x300"
{Text 0-1 LTR Standard} "5,0 100x100"
{Box #descendants=2 Standard} "5,100 100x100"
{Box #descendants=1 AtomicInlineLTR Standard} "5,100 100x100"
{Text 2-3 LTR Standard} "5,200 100x100"
)DUMP",
AsFragmentItemsString(
*To<LayoutBlockFlow>(GetLayoutObjectByElementId("root"))));
EXPECT_EQ(R"DUMP(
{Line #descendants=2 LTR Standard} "0,0 100x100"
{Text 0-5 LTR Standard} "0,0 500x100"
)DUMP",
AsFragmentItemsString(*To<LayoutBlockFlow>(
GetLayoutObjectByElementId("target")->SlowFirstChild())));
}
// See also NGInlineLayoutAlgorithmTest.TextCombineBasic
TEST_F(NGInlineLayoutAlgorithmTest, TextCombineFake) {
ScopedLayoutNGTextCombineForTest enable_layout_ng_text_combine(true);
LoadAhem();
InsertStyleElement(
"body { margin: 0px; font: 100px/110px Ahem; }"
"c {"
" display: inline-block;"
" width: 1em; height: 1em;"
" writing-mode: horizontal-tb;"
"}"
"div { writing-mode: vertical-rl; }");
SetBodyInnerHTML("<div id=root>a<c id=target>0</c>b</div>");
EXPECT_EQ(R"DUMP(
{Line #descendants=4 LTR Standard} "0,0 110x300"
{Text 0-1 LTR Standard} "5,0 100x100"
{Box #descendants=1 AtomicInlineLTR Standard} "5,100 100x100"
{Text 2-3 LTR Standard} "5,200 100x100"
)DUMP",
AsFragmentItemsString(
*To<LayoutBlockFlow>(GetLayoutObjectByElementId("root"))));
EXPECT_EQ(R"DUMP(
{Line #descendants=2 LTR Standard} "0,0 100x110"
{Text 0-1 LTR Standard} "0,5 100x100"
)DUMP",
AsFragmentItemsString(
*To<LayoutBlockFlow>(GetLayoutObjectByElementId("target"))));
}
#undef MAYBE_VerticalAlignBottomReplaced
} // namespace
} // namespace blink
| scheib/chromium | third_party/blink/renderer/core/layout/ng/inline/ng_inline_layout_algorithm_test.cc | C++ | bsd-3-clause | 22,622 |
/*
* Copyright (c) 2015, University of Oslo
*
* 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 the HISP project 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 OWNER 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.
*/
package org.hisp.dhis.android.sdk.persistence.models;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.raizlabs.android.dbflow.annotation.Column;
import com.raizlabs.android.dbflow.annotation.PrimaryKey;
import com.raizlabs.android.dbflow.annotation.Table;
import com.raizlabs.android.dbflow.structure.BaseModel;
import org.hisp.dhis.android.sdk.persistence.Dhis2Database;
/**
* @author Simen Skogly Russnes on 24.02.15.
*/
@Table(databaseName = Dhis2Database.NAME)
public class ImportCount extends BaseModel{
@Column
@PrimaryKey(autoincrement = true)
protected int id;
@JsonProperty("imported")
@Column
private int imported;
@JsonProperty("updated")
@Column
private int updated;
@JsonProperty("ignored")
@Column
private int ignored;
@JsonProperty("deleted")
@Column
private int deleted;
@JsonAnySetter
public void handleUnknown(String key, Object value) {
// do something: put to a Map; log a warning, whatever
}
public int getId() {
return id;
}
public int getImported() {
return imported;
}
public int getUpdated() {
return updated;
}
public int getIgnored() {
return ignored;
}
public int getDeleted() {
return deleted;
}
public void setDeleted(int deleted) {
this.deleted = deleted;
}
public void setIgnored(int ignored) {
this.ignored = ignored;
}
public void setUpdated(int updated) {
this.updated = updated;
}
public void setImported(int imported) {
this.imported = imported;
}
public void setId(int id) {
this.id = id;
}
}
| arthurgwatidzo/dhis2-android-sdk | app/src/main/java/org/hisp/dhis/android/sdk/persistence/models/ImportCount.java | Java | bsd-3-clause | 3,317 |
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/common/gpu/media/mft_angle_video_device.h"
#include <d3d9.h>
#include "media/base/video_frame.h"
#include "third_party/angle/src/libGLESv2/main.h"
MftAngleVideoDevice::MftAngleVideoDevice()
: device_(reinterpret_cast<egl::Display*>(
eglGetCurrentDisplay())->getDevice()) {
}
void* MftAngleVideoDevice::GetDevice() {
return device_;
}
bool MftAngleVideoDevice::CreateVideoFrameFromGlTextures(
size_t width, size_t height, media::VideoFrame::Format format,
const std::vector<media::VideoFrame::GlTexture>& textures,
scoped_refptr<media::VideoFrame>* frame) {
media::VideoFrame::GlTexture texture_array[media::VideoFrame::kMaxPlanes];
memset(texture_array, 0, sizeof(texture_array));
for (size_t i = 0; i < textures.size(); ++i) {
texture_array[i] = textures[i];
}
media::VideoFrame::CreateFrameGlTexture(format,
width,
height,
texture_array,
frame);
return *frame != NULL;
}
void MftAngleVideoDevice::ReleaseVideoFrame(
const scoped_refptr<media::VideoFrame>& frame) {
// We didn't need to anything here because we didn't allocate any resources
// for the VideoFrame(s) generated.
}
bool MftAngleVideoDevice::ConvertToVideoFrame(
void* buffer, scoped_refptr<media::VideoFrame> frame) {
gl::Context* context = (gl::Context*)eglGetCurrentContext();
// TODO(hclam): Connect ANGLE to upload the surface to texture when changes
// to ANGLE is done.
return true;
}
| Crystalnix/house-of-life-chromium | content/common/gpu/media/mft_angle_video_device.cc | C++ | bsd-3-clause | 1,786 |
/*
* File: AbstractStatefulEvaluatorTest.java
* Authors: Kevin R. Dixon
* Company: Sandia National Laboratories
* Project: Cognitive Foundry
*
* Copyright Jul 7, 2009, Sandia Corporation.
* Under the terms of Contract DE-AC04-94AL85000, there is a non-exclusive
* license for use of this work by or on behalf of the U.S. Government.
* Export of this program may require a license from the United States
* Government. See CopyrightHistory.txt for complete details.
*
*/
package gov.sandia.cognition.evaluator;
import gov.sandia.cognition.math.matrix.Vector;
import gov.sandia.cognition.math.matrix.mtj.Vector3;
import gov.sandia.cognition.util.ObjectUtil;
import junit.framework.TestCase;
import java.util.Random;
/**
* Unit tests for AbstractStatefulEvaluatorTest.
*
* @author krdixon
*/
public class AbstractStatefulEvaluatorTest
extends TestCase
{
/**
* Random number generator to use for a fixed random seed.
*/
public final Random RANDOM = new Random( 1 );
/**
* Default tolerance of the regression tests, {@value}.
*/
public final double TOLERANCE = 1e-5;
/**
* Tests for class AbstractStatefulEvaluatorTest.
* @param testName Name of the test.
*/
public AbstractStatefulEvaluatorTest(
String testName)
{
super(testName);
}
public static class StatefulFunction
extends AbstractStatefulEvaluator<Vector,Vector,Vector>
{
public StatefulFunction()
{
super();
}
public StatefulFunction(
Vector state )
{
super( state );
}
public Vector createDefaultState()
{
return new Vector3(1.0,2.0,3.0);
}
public Vector evaluate(
Vector input)
{
this.getState().plusEquals(input);
return this.getState();
}
}
public Vector createRandomInput()
{
return Vector3.createRandom(RANDOM);
}
public StatefulFunction createInstance()
{
return new StatefulFunction(this.createRandomInput());
}
/**
* Tests the constructors of class AbstractStatefulEvaluatorTest.
*/
public void testConstructors()
{
System.out.println( "Constructors" );
StatefulFunction f = new StatefulFunction();
assertEquals( f.createDefaultState(), f.getState() );
Vector x = this.createRandomInput();
f = new StatefulFunction( x );
assertSame( x, f.getState() );
}
/**
* Test of clone method, of class AbstractStatefulEvaluator.
*/
public void testClone()
{
System.out.println("clone");
StatefulFunction f = this.createInstance();
StatefulFunction clone = (StatefulFunction) f.clone();
System.out.println( "f:\n" + ObjectUtil.toString(f) );
System.out.println( "clone:\n" + ObjectUtil.toString(clone) );
assertNotNull( clone );
assertNotSame( f, clone );
assertNotNull( clone.getState() );
assertNotSame( f.getState(), clone.getState() );
assertEquals( f.getState(), clone.getState() );
assertFalse( clone.getState().equals( clone.createDefaultState() ) );
Vector originalState = f.getState().clone();
assertEquals( originalState, f.getState() );
assertEquals( originalState, clone.getState() );
clone.getState().scaleEquals(RANDOM.nextDouble());
assertEquals( originalState, f.getState() );
assertFalse( originalState.equals( clone.getState() ) );
}
/**
* evaluate(state)
*/
public void testEvaluateState()
{
System.out.println( "evaluate(State)" );
StatefulFunction f = this.createInstance();
Vector defaultState = f.createDefaultState();
f.resetState();
Vector input = this.createRandomInput();
Vector o1 = f.evaluate(input);
Vector o2 = f.evaluate(input, defaultState );
assertNotSame( o1, o2 );
assertEquals( o1, o2 );
}
/**
* Test of evaluate method, of class AbstractStatefulEvaluator.
*/
public void testEvaluate()
{
System.out.println("evaluate");
StatefulFunction f = this.createInstance();
Vector originalState = f.getState().clone();
f.evaluate(this.createRandomInput());
assertFalse( originalState.equals( f.getState() ) );
}
/**
* Test of getState method, of class AbstractStatefulEvaluator.
*/
public void testGetState()
{
System.out.println("getState");
StatefulFunction f = this.createInstance();
assertNotNull( f.getState() );
}
/**
* Test of setState method, of class AbstractStatefulEvaluator.
*/
public void testSetState()
{
System.out.println("setState");
StatefulFunction f = this.createInstance();
Vector s = this.createRandomInput();
f.setState(s);
assertSame( s, f.getState() );
}
/**
* Test of resetState method, of class AbstractStatefulEvaluator.
*/
public void testResetState()
{
System.out.println("resetState");
StatefulFunction f = this.createInstance();
Vector v = f.createDefaultState();
assertFalse( v.equals( f.getState() ) );
f.resetState();
assertEquals( v, f.getState() );
}
}
| codeaudit/Foundry | Components/CommonCore/Test/gov/sandia/cognition/evaluator/AbstractStatefulEvaluatorTest.java | Java | bsd-3-clause | 5,498 |
//2
var __result1 = 2; // for SAFE
var __expect1 = 2; // for SAFE
| darkrsw/safe | tests/typing_tests/TAJS_micro/test2.js | JavaScript | bsd-3-clause | 68 |
<?php
/**
* Model for the Primary Term table.
*
* @package Yoast\YoastSEO\Models
*/
namespace Yoast\WP\SEO\Models;
use Yoast\WP\Lib\Model;
/**
* Primary Term model definition.
*
* @property int $id Identifier.
* @property int $post_id Post ID.
* @property int $term_id Term ID.
* @property string $taxonomy Taxonomy.
* @property int $blog_id Blog ID.
*
* @property string $created_at
* @property string $updated_at
*/
class Primary_Term extends Model {
/**
* Whether nor this model uses timestamps.
*
* @var bool
*/
protected $uses_timestamps = true;
/**
* Which columns contain int values.
*
* @var array
*/
protected $int_columns = [
'id',
'post_id',
'term_id',
'blog_id',
];
}
| mandino/www.bloggingshakespeare.com | wp-content/plugins/wordpress-seo/src/models/primary-term.php | PHP | mit | 750 |
<?php
declare(strict_types=1);
/*
* This file is part of SolidInvoice project.
*
* (c) Pierre du Plessis <open-source@solidworx.co>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace SolidInvoice\CoreBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\HttpFoundation\File\UploadedFile;
class ImageUploadType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->addModelTransformer(new class() implements DataTransformerInterface {
private $file;
public function transform($value)
{
if (null !== $value) {
$this->file = $value;
}
return new File('', false);
}
public function reverseTransform($value)
{
if (null === $value && null !== $this->file) {
return $this->file;
}
if (!$value instanceof UploadedFile) {
return;
}
if (!$value->isValid()) {
throw new TransformationFailedException();
}
return $value->guessExtension().'|'.base64_encode(file_get_contents($value->getPathname()));
}
});
}
public function getParent(): string
{
return FileType::class;
}
public function getBlockPrefix()
{
return 'image_upload';
}
}
| pierredup/CSBill | src/CoreBundle/Form/Type/ImageUploadType.php | PHP | mit | 1,863 |
package org.politicos.config;
import com.fasterxml.jackson.datatype.jsr310.ser.ZonedDateTimeSerializer;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
@Configuration
public class JacksonConfiguration {
public static final DateTimeFormatter ISO_FIXED_FORMAT =
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(ZoneId.of("Z"));
@Bean
public Jackson2ObjectMapperBuilderCustomizer jacksonCustomizer() {
return new Jackson2ObjectMapperBuilderCustomizer() {
@Override
public void customize(Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder) {
jackson2ObjectMapperBuilder.serializers(new ZonedDateTimeSerializer(ISO_FIXED_FORMAT));
}
};
}
}
| lucasa/Politicos | src/main/java/org/politicos/config/JacksonConfiguration.java | Java | mit | 1,060 |
using System;
using System.Collections.Generic;
using FFImageLoading.Transformations;
using FFImageLoading.Work;
namespace FFImageLoading.MvvmCross.Sample.Core
{
public class Image
{
public string Url { get; }
public double DownsampleWidth => 200d;
public List<ITransformation> Transformations => new List<ITransformation> { new CircleTransformation() };
public Image(string url)
{
Url = url;
}
}
}
| luberda-molinet/FFImageLoading | samples/ImageLoading.MvvmCross.Sample/FFImageLoading.MvvmCross.Sample.Core/ViewModels/Image.cs | C# | mit | 476 |
/* Copyright (c) 2006-2009 Jan S. Rellermeyer
* Systems Group,
* Department of Computer Science, ETH Zurich.
* 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 ETH Zurich 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 OWNER 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.
*/
package ch.ethz.iks.util;
/**
* Interface for listeners of the Scheduler utility.
*
* @author Jan S. Rellermeyer, ETH Zurich
*/
public interface ScheduleListener {
/**
* called, when a scheduled object is due.
*
* @param scheduler
* the scheduler that has scheduled the object.
* @param timestamp
* the timestamp for which the object was scheduled.
* @param object
* the scheduled object.
*/
void due(final Scheduler scheduler, final long timestamp,
final Object object);
}
| nmizoguchi/pfg-r-osgi | ch.ethz.iks.r_osgi.remote/src/main/java/ch/ethz/iks/util/ScheduleListener.java | Java | mit | 2,191 |
/*global todomvc */
(function () {
'use strict';
/**
* The main controller for the app. The controller:
* - retrieves and persists the model via the todoStorage service
* - exposes the model to the template and provides event handlers
*/
todomvc.controller('TodoCtrl', function TodoCtrl($scope, $location, todoStorage, filterFilter, $speechRecognition) {
var todos = $scope.todos = todoStorage.get();
$scope.newTodo = '';
$scope.remainingCount = filterFilter(todos, {completed: false}).length;
$scope.editedTodo = null;
if ($location.path() === '') {
$location.path('/');
}
$scope.location = $location;
$scope.$watch('location.path()', function (path) {
$scope.statusFilter = (path === '/active') ?
{ completed: false } : (path === '/completed') ?
{ completed: true } : null;
});
$scope.$watch('remainingCount == 0', function (val) {
$scope.allChecked = val;
});
$scope.addTodo = function () {
var newTodo = $scope.newTodo.trim();
console.log(newTodo);
if (newTodo.length === 0) {
return;
}
todos.push({
title: newTodo,
completed: false
});
todoStorage.put(todos);
console.log(todos);
$scope.newTodo = '';
$scope.remainingCount++;
};
$scope.editTodo = function (todo) {
$scope.editedTodo = todo;
};
$scope.doneEditing = function (todo) {
$scope.editedTodo = null;
todo.title = todo.title.trim();
if (!todo.title) {
$scope.removeTodo(todo);
}
todoStorage.put(todos);
};
$scope.removeTodo = function (todo) {
$scope.remainingCount -= todo.completed ? 0 : 1;
todos.splice(todos.indexOf(todo), 1);
todoStorage.put(todos);
};
$scope.todoCompleted = function (todo) {
if (todo.completed) {
$scope.remainingCount--;
} else {
$scope.remainingCount++;
}
todoStorage.put(todos);
};
$scope.clearCompletedTodos = function () {
$scope.todos = todos = todos.filter(function (val) {
return !val.completed;
});
todoStorage.put(todos);
};
$scope.markAll = function (completed) {
todos.forEach(function (todo) {
todo.completed = completed;
});
$scope.remainingCount = completed ? 0 : todos.length;
todoStorage.put(todos);
};
/**
* Need to be added for speech recognition
*/
var findTodo = function(title){
for (var i=0; i<todos.length; i++){
if (todos[i].title === title) {
return todos[i];
}
}
return null;
};
var completeTodo = function(title){
for (var i=0; i<todos.length; i++){
if (todos[i].title === title) {
todos[i].completed = ! todos[i].completed;
$scope.todoCompleted(todos[i]);
$scope.$apply();
return true;
}
}
};
var LANG = 'en-US';
$speechRecognition.onstart(function(e){
$speechRecognition.speak('Yes? How can I help you?');
});
$speechRecognition.onerror(function(e){
var error = (e.error || '');
alert('An error occurred ' + error);
});
$speechRecognition.payAttention();
// $speechRecognition.setLang(LANG);
$speechRecognition.listen();
$scope.recognition = {};
$scope.recognition['en-US'] = {
'addToList': {
'regex': /^do .+/gi,
'lang': 'en-US',
'call': function(utterance){
var parts = utterance.split(' ');
if (parts.length > 1) {
$scope.newTodo = parts.slice(1).join(' ');
$scope.addTodo();
$scope.$apply();
}
}
},
'show-all': {
'regex': /show.*all/gi,
'lang': 'en-US',
'call': function(utterance){
$location.path('/');
$scope.$apply();
}
},
'show-active': {
'regex': /show.*active/gi,
'lang': 'en-US',
'call': function(utterance){
$location.path('/active');
$scope.$apply();
}
},
'show-completed': {
'regex': /show.*complete/gi,
'lang': 'en-US',
'call': function(utterance){
$location.path('/completed');
$scope.$apply();
}
},
'mark-all': {
'regex': /^mark/gi,
'lang': 'en-US',
'call': function(utterance){
$scope.markAll(1);
$scope.$apply();
}
},
'unmark-all': {
'regex': /^unmark/gi,
'lang': 'en-US',
'call': function(utterance){
$scope.markAll(1);
$scope.$apply();
}
},
'clear-completed': {
'regex': /clear.*/gi,
'lang': 'en-US',
'call': function(utterance){
$scope.clearCompletedTodos();
$scope.$apply();
}
},
'listTasks': [{
'regex': /^complete .+/gi,
'lang': 'en-US',
'call': function(utterance){
var parts = utterance.split(' ');
if (parts.length > 1) {
completeTodo(parts.slice(1).join(' '));
}
}
},{
'regex': /^remove .+/gi,
'lang': 'en-US',
'call': function(utterance){
var parts = utterance.split(' ');
if (parts.length > 1) {
var todo = findTodo(parts.slice(1).join(' '));
console.log(todo);
if (todo) {
$scope.removeTodo(todo);
$scope.$apply();
}
}
}
}]
};
var ignoreUtterance = {};
ignoreUtterance['addToList'] = $speechRecognition.listenUtterance($scope.recognition['en-US']['addToList']);
ignoreUtterance['show-all'] = $speechRecognition.listenUtterance($scope.recognition['en-US']['show-all']);
ignoreUtterance['show-active'] = $speechRecognition.listenUtterance($scope.recognition['en-US']['show-active']);
ignoreUtterance['show-completed'] = $speechRecognition.listenUtterance($scope.recognition['en-US']['show-completed']);
ignoreUtterance['mark-all'] = $speechRecognition.listenUtterance($scope.recognition['en-US']['mark-all']);
ignoreUtterance['unmark-all'] = $speechRecognition.listenUtterance($scope.recognition['en-US']['unmark-all']);
ignoreUtterance['clear-completed'] = $speechRecognition.listenUtterance($scope.recognition['en-US']['clear-completed']);
/*
to ignore listener call returned function
*/
// ignoreUtterance['addToList']();
});
}()); | xtrasmal/adaptive-speech | demo/js/controllers/todoCtrl.js | JavaScript | mit | 5,691 |
'use strict';
var gulp = require('gulp');
var shell = require('gulp-shell');
module.exports = function () {
gulp.task('git-add', function () {
return gulp.src('*.js', {
read: false
}).pipe(shell(['git ls-files --others docroot/sites/all | egrep \'.css|.js|.png|.map\' | xargs git add -f']));
});
};
| six519/disclose.ph | gulp/git.js | JavaScript | mit | 318 |
module Rack
class Offline
class Config
def initialize(root, &block)
@cache = []
@network = []
@fallback = {}
@root = root
instance_eval(&block) if block_given?
end
def cache(*names)
@cache.concat(names)
end
def network(*names)
@network.concat(names)
end
def fallback(hash = {})
@fallback.merge!(hash)
end
def root
@root
end
end
end
end
| kakra/rack-offline | lib/rack/offline/config.rb | Ruby | mit | 490 |
#!/usr/bin/env node
'use strict';
/**
* bitcoind.js example
*/
process.title = 'bitcoind.js';
/**
* daemon
*/
var daemon = require('../').daemon({
datadir: process.env.BITCOINDJS_DIR || '~/.bitcoin',
});
daemon.on('ready', function() {
console.log('ready');
});
daemon.on('tx', function(txid) {
console.log('txid', txid);
});
daemon.on('error', function(err) {
daemon.log('error="%s"', err.message);
});
daemon.on('open', function(status) {
daemon.log('status="%s"', status);
});
| bankonme/bitcoind.js | example/index.js | JavaScript | mit | 502 |
require 'spec_helper'
RSpec.describe RailsAdmin::Config::Fields::Types::StringLike do
describe '#treat_empty_as_nil?', active_record: true do
context 'with a nullable field' do
subject do
RailsAdmin.config('Team').fields.detect do |f|
f.name == :name
end.with(object: Team.new)
end
it 'is true' do
expect(subject.treat_empty_as_nil?).to be true
end
end
context 'with a non-nullable field' do
subject do
RailsAdmin.config('Team').fields.detect do |f|
f.name == :manager
end.with(object: Team.new)
end
it 'is false' do
expect(subject.treat_empty_as_nil?).to be false
end
end
end
describe '#parse_input' do
subject do
RailsAdmin.config('FieldTest').fields.detect do |f|
f.name == :string_field
end.with(object: FieldTest.new)
end
context 'with treat_empty_as_nil being true' do
before do
RailsAdmin.config FieldTest do
field :string_field do
treat_empty_as_nil true
end
end
end
context 'when value is empty' do
let(:params) { {string_field: ''} }
it 'makes the value nil' do
subject.parse_input(params)
expect(params.key?(:string_field)).to be true
expect(params[:string_field]).to be nil
end
end
context 'when value does not exist in params' do
let(:params) { {} }
it 'does not touch params' do
subject.parse_input(params)
expect(params.key?(:string_field)).to be false
end
end
end
context 'with treat_empty_as_nil being false' do
before do
RailsAdmin.config FieldTest do
field :string_field do
treat_empty_as_nil false
end
end
end
let(:params) { {string_field: ''} }
it 'keeps the value untouched' do
subject.parse_input(params)
expect(params.key?(:string_field)).to be true
expect(params[:string_field]).to eq ''
end
end
end
end
| widgetworks/rails_admin | spec/rails_admin/config/fields/types/string_like_spec.rb | Ruby | mit | 2,109 |
<?php
class Node_BreakStmt extends NodeAbstract
{
} | VelvetMirror/test | vendor/bundles/Sensio/Bundle/GeneratorBundle/PHP-Parser/lib/Node/BreakStmt.php | PHP | mit | 52 |
#!/usr/bin/env python
#
# Electrum - lightweight Bitcoin client
# Copyright (C) 2015 Thomas Voegtlin
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# Check DNSSEC trust chain.
# Todo: verify expiration dates
#
# Based on
# http://backreference.org/2010/11/17/dnssec-verification-with-dig/
# https://github.com/rthalley/dnspython/blob/master/tests/test_dnssec.py
import dns
import dns.name
import dns.query
import dns.dnssec
import dns.message
import dns.resolver
import dns.rdatatype
import dns.rdtypes.ANY.NS
import dns.rdtypes.ANY.CNAME
import dns.rdtypes.ANY.DLV
import dns.rdtypes.ANY.DNSKEY
import dns.rdtypes.ANY.DS
import dns.rdtypes.ANY.NSEC
import dns.rdtypes.ANY.NSEC3
import dns.rdtypes.ANY.NSEC3PARAM
import dns.rdtypes.ANY.RRSIG
import dns.rdtypes.ANY.SOA
import dns.rdtypes.ANY.TXT
import dns.rdtypes.IN.A
import dns.rdtypes.IN.AAAA
from .logging import get_logger
_logger = get_logger(__name__)
# hard-coded trust anchors (root KSKs)
trust_anchors = [
# KSK-2017:
dns.rrset.from_text('.', 1 , 'IN', 'DNSKEY', '257 3 8 AwEAAaz/tAm8yTn4Mfeh5eyI96WSVexTBAvkMgJzkKTOiW1vkIbzxeF3+/4RgWOq7HrxRixHlFlExOLAJr5emLvN7SWXgnLh4+B5xQlNVz8Og8kvArMtNROxVQuCaSnIDdD5LKyWbRd2n9WGe2R8PzgCmr3EgVLrjyBxWezF0jLHwVN8efS3rCj/EWgvIWgb9tarpVUDK/b58Da+sqqls3eNbuv7pr+eoZG+SrDK6nWeL3c6H5Apxz7LjVc1uTIdsIXxuOLYA4/ilBmSVIzuDWfdRUfhHdY6+cn8HFRm+2hM8AnXGXws9555KrUB5qihylGa8subX2Nn6UwNR1AkUTV74bU='),
# KSK-2010:
dns.rrset.from_text('.', 15202, 'IN', 'DNSKEY', '257 3 8 AwEAAagAIKlVZrpC6Ia7gEzahOR+9W29euxhJhVVLOyQbSEW0O8gcCjF FVQUTf6v58fLjwBd0YI0EzrAcQqBGCzh/RStIoO8g0NfnfL2MTJRkxoX bfDaUeVPQuYEhg37NZWAJQ9VnMVDxP/VHL496M/QZxkjf5/Efucp2gaD X6RS6CXpoY68LsvPVjR0ZSwzz1apAzvN9dlzEheX7ICJBBtuA6G3LQpz W5hOA2hzCTMjJPJ8LbqF6dsV6DoBQzgul0sGIcGOYl7OyQdXfZ57relS Qageu+ipAdTTJ25AsRTAoub8ONGcLmqrAmRLKBP1dfwhYB4N7knNnulq QxA+Uk1ihz0='),
]
def _check_query(ns, sub, _type, keys):
q = dns.message.make_query(sub, _type, want_dnssec=True)
response = dns.query.tcp(q, ns, timeout=5)
assert response.rcode() == 0, 'No answer'
answer = response.answer
assert len(answer) != 0, ('No DNS record found', sub, _type)
assert len(answer) != 1, ('No DNSSEC record found', sub, _type)
if answer[0].rdtype == dns.rdatatype.RRSIG:
rrsig, rrset = answer
elif answer[1].rdtype == dns.rdatatype.RRSIG:
rrset, rrsig = answer
else:
raise Exception('No signature set in record')
if keys is None:
keys = {dns.name.from_text(sub):rrset}
dns.dnssec.validate(rrset, rrsig, keys)
return rrset
def _get_and_validate(ns, url, _type):
# get trusted root key
root_rrset = None
for dnskey_rr in trust_anchors:
try:
# Check if there is a valid signature for the root dnskey
root_rrset = _check_query(ns, '', dns.rdatatype.DNSKEY, {dns.name.root: dnskey_rr})
break
except dns.dnssec.ValidationFailure:
# It's OK as long as one key validates
continue
if not root_rrset:
raise dns.dnssec.ValidationFailure('None of the trust anchors found in DNS')
keys = {dns.name.root: root_rrset}
# top-down verification
parts = url.split('.')
for i in range(len(parts), 0, -1):
sub = '.'.join(parts[i-1:])
name = dns.name.from_text(sub)
# If server is authoritative, don't fetch DNSKEY
query = dns.message.make_query(sub, dns.rdatatype.NS)
response = dns.query.udp(query, ns, 3)
assert response.rcode() == dns.rcode.NOERROR, "query error"
rrset = response.authority[0] if len(response.authority) > 0 else response.answer[0]
rr = rrset[0]
if rr.rdtype == dns.rdatatype.SOA:
continue
# get DNSKEY (self-signed)
rrset = _check_query(ns, sub, dns.rdatatype.DNSKEY, None)
# get DS (signed by parent)
ds_rrset = _check_query(ns, sub, dns.rdatatype.DS, keys)
# verify that a signed DS validates DNSKEY
for ds in ds_rrset:
for dnskey in rrset:
htype = 'SHA256' if ds.digest_type == 2 else 'SHA1'
good_ds = dns.dnssec.make_ds(name, dnskey, htype)
if ds == good_ds:
break
else:
continue
break
else:
raise Exception("DS does not match DNSKEY")
# set key for next iteration
keys = {name: rrset}
# get TXT record (signed by zone)
rrset = _check_query(ns, url, _type, keys)
return rrset
def query(url, rtype):
# 8.8.8.8 is Google's public DNS server
nameservers = ['8.8.8.8']
ns = nameservers[0]
try:
out = _get_and_validate(ns, url, rtype)
validated = True
except Exception as e:
_logger.info(f"DNSSEC error: {repr(e)}")
out = dns.resolver.resolve(url, rtype)
validated = False
return out, validated
| wakiyamap/electrum-mona | electrum_mona/dnssec.py | Python | mit | 5,922 |
module MigrationConstraintHelpers
# Creates a foreign key from +table+.+field+ against referenced_table.referenced_field
#
# table: The tablename
# field: A field of the table
# referenced_table: The table which contains the field referenced
# referenced_field: The field (which should be part of the primary key) of the referenced table
# cascade: delete & update on cascade?
def foreign_key(table, field, referenced_table, referenced_field = :id, cascade = true)
execute "ALTER TABLE #{table} ADD CONSTRAINT #{constraint_name(table, field)}
FOREIGN KEY #{constraint_name(table, field)} (#{field_list(field)})
REFERENCES #{referenced_table}(#{field_list(referenced_field)})
#{(cascade ? 'ON DELETE CASCADE ON UPDATE CASCADE' : '')}"
end
# Drops a foreign key from +table+.+field+ that has been created before with
# foreign_key method
#
# table: The table name
# field: A field (or array of fields) of the table
def drop_foreign_key(table, field)
execute "ALTER TABLE #{table} DROP FOREIGN KEY #{constraint_name(table, field)}"
end
# Creates a primary key for +table+, which right now HAS NOT primary key defined
#
# table: The table name
# field: A field (or array of fields) of the table that will be part of the primary key
def primary_key(table, field)
execute "ALTER TABLE #{table} ADD PRIMARY KEY(#{field_list(field)})"
end
private
# Creates a constraint name for table and field given as parameters
#
# table: The table name
# field: A field of the table
def constraint_name(table, field)
"fk_#{table}_#{field_list_name(field)}"
end
def field_list(fields)
fields.is_a?(Array) ? fields.join(',') : fields
end
def field_list_name(fields)
fields.is_a?(Array) ? fields.join('_') : fields
end
end
| beachyapp/standalone-migrations | vendor/migration_helpers/lib/migration_helper.rb | Ruby | mit | 1,887 |
package ru.atom.model.dao;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import ru.atom.model.data.Match;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
public class MatchDao implements Dao<Match> {
private static final Logger log = LogManager.getLogger(MatchDao.class);
@Override
public List<Match> getAll() {
throw new NotImplementedException();
}
@Override
public List<Match> getAllWhere(String... hqlConditions) {
throw new NotImplementedException();
}
@Override
public void insert(Match match) {
}
}
| Bragaman/atom | lecture6/source/src/main/java/ru/atom/model/dao/MatchDao.java | Java | mit | 737 |
/**
* Copyright MaDgIK Group 2010 - 2015.
*/
package madgik.exareme.master.engine.rmi;
/**
* @author heraldkllapi
*/
public class OptimizerConstants {
public static boolean USE_SKETCH = false;
public static int MAX_TABLE_PARTS = 2;
}
| XristosMallios/cache | exareme-master/src/main/java/madgik/exareme/master/engine/rmi/OptimizerConstants.java | Java | mit | 248 |
version https://git-lfs.github.com/spec/v1
oid sha256:3e7e8daeb7e94086c854616e881862ffc0555684031d339b30c0b67afa82b530
size 492
| yogeshsaroya/new-cdnjs | ajax/libs/bootstrap-datepicker/1.2.0-rc.1/js/locales/bootstrap-datepicker.et.min.js | JavaScript | mit | 128 |
var searchData=
[
['w',['w',['../structedda_1_1dist_1_1GMMTuple.html#a3f52857178189dcb76b5132a60c0a50a',1,'edda::dist::GMMTuple']]],
['weights',['weights',['../classedda_1_1dist_1_1JointGMM.html#a479a4af061d7414da3a2b42df3f2e87f',1,'edda::dist::JointGMM']]],
['width',['width',['../structBMPImage.html#a35875dd635eb414965fd87e169b8fb25',1,'BMPImage']]]
];
| GRAVITYLab/edda | html/search/variables_15.js | JavaScript | mit | 362 |
<?php
namespace App\Exceptions;
use Exception;
use Illuminate\Validation\ValidationException;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Laravel\Lumen\Exceptions\Handler as ExceptionHandler;
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that should not be reported.
*
* @var array
*/
protected $dontReport = [
AuthorizationException::class,
HttpException::class,
ModelNotFoundException::class,
ValidationException::class,
];
/**
* Report or log an exception.
*
* This is a great spot to send exceptions to Sentry, Bugsnag, etc.
*
* @param \Exception $e
* @return void
*/
public function report(Exception $e)
{
parent::report($e);
}
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $e
* @return \Illuminate\Http\Response
*/
public function render($request, Exception $e)
{
// support friendly urls for files within the application
$path = $request->path();
if(strpos($path, 'sites/') !== FALSE) {
if(strpos($path, '.html') === FALSE) {
$file = app()->basePath('public/'.$path.'.html');
if(file_exists($file)) {
return file_get_contents($file);
}
}
}
return parent::render($request, $e);
}
}
| OnekO/respond | app/Exceptions/Handler.php | PHP | mit | 1,610 |
package org.spongycastle;
/**
* The Bouncy Castle License
*
* Copyright (c) 2000-2015 The Legion Of The Bouncy Castle Inc. (http://www.bouncycastle.org)
* <p>
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
* <p>
* The above copyright notice and this permission notice shall be included in all copies or substantial
* portions of the Software.
* <p>
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
public class LICENSE
{
public static String licenseText =
"Copyright (c) 2000-2015 The Legion of the Bouncy Castle Inc. (http://www.bouncycastle.org) "
+ System.getProperty("line.separator")
+ System.getProperty("line.separator")
+ "Permission is hereby granted, free of charge, to any person obtaining a copy of this software "
+ System.getProperty("line.separator")
+ "and associated documentation files (the \"Software\"), to deal in the Software without restriction, "
+ System.getProperty("line.separator")
+ "including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, "
+ System.getProperty("line.separator")
+ "and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,"
+ System.getProperty("line.separator")
+ "subject to the following conditions:"
+ System.getProperty("line.separator")
+ System.getProperty("line.separator")
+ "The above copyright notice and this permission notice shall be included in all copies or substantial"
+ System.getProperty("line.separator")
+ "portions of the Software."
+ System.getProperty("line.separator")
+ System.getProperty("line.separator")
+ "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,"
+ System.getProperty("line.separator")
+ "INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR"
+ System.getProperty("line.separator")
+ "PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE"
+ System.getProperty("line.separator")
+ "LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR"
+ System.getProperty("line.separator")
+ "OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER"
+ System.getProperty("line.separator")
+ "DEALINGS IN THE SOFTWARE.";
public static void main(
String[] args)
{
System.out.println(licenseText);
}
}
| savichris/spongycastle | core/src/main/java/org/spongycastle/LICENSE.java | Java | mit | 3,397 |
var Data = {};
Data.matrix = {
valueName: 'Wert',
stakeholdersName : 'Berührungs​gruppe',
negativeCriteriaName : 'Negativ-Kriterien',
values : [
'Menschen​würde',
'Solidarität',
'Ökologische Nachhaltigkeit',
'Soziale Gerechtigkeit',
'Demokratische Mitbestimmung & Transparenz'
],
stakeholders : [
{
shortcode : 'A',
name: 'Lieferant​Innen',
values: [
{
shortcode : 'A1',
shortcodeSlug : 'a1',
title: 'Ethisches Beschaffungsmanagement',
content: 'Aktive Auseinandersetzung mit den Risiken zugekaufter Produkte / Dienstleistungen, Berücksichtigung sozialer und ökologischer Aspekte bei der Auswahl von LieferantInnen und DienstleistungsnehmerInnen.',
points: 90,
soleProprietorship: true
}
]
},
{
shortcode : 'B',
name: 'Geldgeber​Innen',
values: [
{
shortcode : 'B1',
shortcodeSlug : 'b1',
title: 'Ethisches Finanzmanagement',
content: 'Berücksichtigung sozialer und ökologischer Aspekte bei der Auswahl der Finanzdienstleistungen; gemeinwohlorienterte Veranlagung und Finanzierung',
points: 30,
soleProprietorship: true
}
]
},
{
shortcode : 'C',
name: 'Mitarbeiter​Innen inklusive Eigentümer​Innen',
values: [
{
shortcode : 'C1',
shortcodeSlug : 'c1',
title: 'Arbeitsplatz​qualität und Gleichstellung',
content: 'Mitarbeiter​orientierte Organisations-kultur und –strukturen, Faire Beschäftigungs- und Entgeltpolitik, Arbeitsschutz und Gesundheits​förderung einschließlich Work-Life-Balance/flexible Arbeitszeiten, Gleichstellung und Diversität',
points: 90,
soleProprietorship: true
},
{
shortcode : 'C2',
shortcodeSlug : 'c2',
title: 'Gerechte Verteilung der Erwerbsarbeit',
content: 'Abbau von Überstunden, Verzicht auf All-inclusive-Verträge, Reduktion der Regelarbeitszeit, Beitrag zur Reduktion der Arbeitslosigkeit',
points: 50,
soleProprietorship: true
},
{
shortcode : 'C3',
shortcodeSlug : 'c3',
title: 'Förderung ökologischen Verhaltens der Mitarbeiter​Innen',
content: 'Aktive Förderung eines nachhaltigen Lebensstils der MitarbeiterInnen (Mobilität, Ernährung), Weiterbildung und Bewusstsein schaffende Maßnahmen, nachhaltige Organisationskultur',
points: 30,
soleProprietorship: true
},
{
shortcode : 'C4',
shortcodeSlug : 'c4',
title: 'Gerechte Verteilung des Einkommens',
content: 'Geringe innerbetriebliche Einkommens​spreizung (netto), Einhaltung von Mindest​einkommen und Höchst​einkommen',
points: 60,
soleProprietorship: false
},
{
shortcode : 'C5',
shortcodeSlug : 'c5',
title: 'Inner​betriebliche Demokratie und Transparenz',
content: 'Umfassende innerbetriebliche Transparenz, Wahl der Führungskräfte durch die Mitarbeiter, konsensuale Mitbestimmung bei Grundsatz- und Rahmen​entscheidungen, Übergabe Eigentum an MitarbeiterInnen. Z.B. Soziokratie',
points: 90,
soleProprietorship: false
}
]
},
{
shortcode : 'D',
name: 'KundInnen / Produkte / Dienst​leistungen / Mit​unternehmen',
values: [
{
shortcode : 'D1',
shortcodeSlug : 'd1',
title: 'Ethische Kunden​beziehung',
content: 'Ethischer Umgang mit KundInnen, KundInnen​orientierung/ - mitbestimmung, gemeinsame Produkt​entwicklung, hohe Servicequalität, hohe Produkt​transparenz',
points: 50,
soleProprietorship: true
},
{
shortcode : 'D2',
shortcodeSlug : 'd2',
title: 'Solidarität mit Mit​unternehmen',
content: 'Weitergabe von Information, Know-how, Arbeitskräften, Aufträgen, zinsfreien Krediten; Beteiligung an kooperativem Marketing und kooperativer Krisenbewältigung',
points: 70,
soleProprietorship: true
},
{
shortcode : 'D3',
shortcodeSlug : 'd3',
title: 'Ökologische Gestaltung der Produkte und Dienst​leistungen',
content: 'Angebot ökologisch höherwertiger Produkte / Dienstleistungen; Bewusstsein schaffende Maßnahmen; Berücksichtigung ökologischer Aspekte bei der KundInnenwahl',
points: 90,
soleProprietorship: true
},
{
shortcode : 'D4',
shortcodeSlug : 'd4',
title: 'Soziale Gestaltung der Produkte und Dienst​leistungen',
content: 'Informationen / Produkten / Dienstleistungen für benachteiligte KundInnen-Gruppen. Unterstützung förderungs​würdiger Marktstrukturen.',
points: 30,
soleProprietorship: true
},
{
shortcode : 'D5',
shortcodeSlug : 'd5',
title: 'Erhöhung der sozialen und ökologischen Branchen​standards',
content: 'Vorbildwirkung, Entwicklung von höheren Standards mit MitbewerberInnen, Lobbying',
points: 30,
soleProprietorship: true
}
]
},
{
shortcode : 'E',
name: 'Gesell​schaftliches Umfeld:',
explanation: 'Region, Souverän, zukünftige Generationen, Zivil​gesellschaft, Mitmenschen und Natur',
values: [
{
shortcode : 'E1',
shortcodeSlug : 'e1',
title: 'Sinn und Gesell​schaftliche Wirkung der Produkte / Dienst​leistungen',
content: 'P/DL decken den Grundbedarf oder dienen der Entwicklung der Menschen / der Gemeinschaft / der Erde und generieren positiven Nutzen.',
points: 50,
soleProprietorship: true
},
{
shortcode : 'E2',
shortcodeSlug : 'e2',
title: 'Beitrag zum Gemeinwesen',
content: 'Gegenseitige Unterstützung und Kooperation durch Finanzmittel, Dienstleistungen, Produkte, Logistik, Zeit, Know-How, Wissen, Kontakte, Einfluss',
points: 40,
soleProprietorship: true
},
{
shortcode : 'E3',
shortcodeSlug : 'e3',
title: 'Reduktion ökologischer Auswirkungen',
content: 'Reduktion der Umwelt​auswirkungen auf ein zukunftsfähiges Niveau: Ressourcen, Energie & Klima, Emissionen, Abfälle etc.',
points: 70,
soleProprietorship: true
},
{
shortcode : 'E4',
shortcodeSlug : 'e4',
title: 'Gemeinwohl​orientierte Gewinn-Verteilung',
content: 'Sinkende / keine Gewinn​ausschüttung an Externe, Ausschüttung an Mitarbeiter, Stärkung des Eigenkapitals, sozial-ökologische Investitionen',
points: 60,
soleProprietorship: false
},
{
shortcode : 'E5',
shortcodeSlug : 'e5',
title: 'Gesellschaft​liche Transparenz und Mitbestimmung',
content: 'Gemeinwohl- oder Nachhaltigkeits​bericht, Mitbestimmung von regionalen und zivilgesell​schaftlichen Berührungs​gruppen',
points: 30,
soleProprietorship: true
}
]
}
],
negativeCriteria : [
{
values: [
{
shortcode : 'N1',
shortcodeSlug : 'n1',
titleShort: 'Verletzung der ILO-Arbeitsnormen / Menschenrechte',
points: -200,
soleProprietorship: true
},
{
shortcode : 'N2',
shortcodeSlug : 'n2',
titleShort: 'Menschen​unwürdige Produkte, z.B. Tretminen, Atomstrom, GMO',
title: 'Menschenunwürdige Produkte und Dienstleistungen',
points: -200,
soleProprietorship: true
},
{
shortcode : 'N3',
shortcodeSlug : 'n3',
titleShort: 'Beschaffung bei / Kooperation mit Unternehmen, welche die Menschenwürde verletzen',
title: 'Menschenunwürdige Produkte und Dienstbeschaffung bei bzt. Kooperation mit Unternehmen, welche die Menschenwürde verletzen',
points: -150,
soleProprietorship: true
}
]
},
{
values: [
{
shortcode : 'N4',
shortcodeSlug : 'n4',
titleShort: 'Feindliche Übernahme',
title: 'Feindliche Übernahme',
points: -200,
soleProprietorship: true
},
{
shortcode : 'N5',
shortcodeSlug : 'n5',
titleShort: 'Sperrpatente',
title: 'Sperrpatente',
points: -100,
soleProprietorship: true
},
{
shortcode : 'N6',
shortcodeSlug : 'n6',
titleShort: 'Dumping​preise',
title: 'Dumpingpreise',
points: -200,
soleProprietorship: true
}
]
},
{
values: [
{
shortcode : 'N7',
shortcodeSlug : 'n7',
titleShort: 'Illegitime Umweltbelastungen',
title: 'Illegitime Umweltbelastungen',
points: -200,
soleProprietorship: true
},
{
shortcode : 'N8',
shortcodeSlug : 'n8',
titleShort: 'Verstöße gegen Umweltauflagen',
title: 'Verstöße gegen Umweltauflagen',
points: -200,
soleProprietorship: true
},
{
shortcode : 'N9',
shortcodeSlug : 'n9',
titleShort: 'Geplante Obsoleszenz (kurze Lebensdauer der Produkte)',
title: 'Geplante Obsoleszenz',
points: -100,
soleProprietorship: true
}
]
},
{
values: [
{
shortcode : 'N10',
shortcodeSlug : 'n10',
titleShort: 'Arbeits​rechtliches Fehlverhalten seitens des Unternehmens',
title: 'Arbeitsrechtliches Fehlverhalten seitens des Unternehmens',
points: -200,
soleProprietorship: true
},
{
shortcode : 'N11',
shortcodeSlug : 'n11',
titleShort: 'Arbeitsplatz​abbau oder Standortverlagerung bei Gewinn',
title: 'Arbeitsplatzabbau oder Standortverlagerung trotz Gewinn',
points: -150,
soleProprietorship: true
},
{
shortcode : 'N12',
shortcodeSlug : 'n12',
titleShort: 'Umgehung der Steuerpflicht',
title: 'Arbeitsplatzabbau oder Standortverlagerung trotz Gewinn',
points: -200,
soleProprietorship: true
},
{
shortcode : 'N13',
shortcodeSlug : 'n13',
titleShort: 'Keine unangemessene Verzinsung für nicht mitarbeitende Gesellschafter',
title: 'Keine unangemessene Verzinsung für nicht mitarbeitende Gesellschafter',
points: -200,
soleProprietorship: true
}
]
},
{
values: [
{
shortcode : 'N14',
shortcodeSlug : 'n14',
titleShort: 'Nicht​offenlegung aller Beteiligungen und Töchter',
title: 'Nichtoffenlegung aller Beteiligungen und Töchter',
points: -100,
soleProprietorship: true
},
{
shortcode : 'N15',
shortcodeSlug : 'n15',
titleShort: 'Verhinderung eines Betriebsrats',
title: 'Verhinderung eines Betriebsrats',
points: -150,
soleProprietorship: true
},
{
shortcode : 'N16',
shortcodeSlug : 'n16',
titleShort: 'Nicht​offenlegung aller Finanzflüsse an Lobbies / Eintragung in das EU-Lobbyregister',
title: 'Nichtoffenlegung aller Finanzflüsse an Lobbyisten und Lobby-Organisationen / Nichteintragung ins Lobby-Register der EU',
points: -200,
soleProprietorship: true
},
{
shortcode : 'N17',
shortcodeSlug : 'n17',
titleShort: 'Exzessive Einkommensspreizung',
title: 'Exzessive Einkommensspreizung',
points: -100,
soleProprietorship: true
}
]
}
]
};
exports.Data = Data;
| sinnwerkstatt/common-good-online-balance | ecg_balancing/templates/ecg_balancing/dustjs/gwoe-matrix-data_en.js | JavaScript | mit | 15,425 |
#!/usr/bin/env python
class PivotFilter(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually."""
def __init__(self):
"""
Attributes:
swaggerTypes (dict): The key is attribute name and the value is attribute type.
attributeMap (dict): The key is attribute name and the value is json key in definition.
"""
self.swaggerTypes = {
'AutoFilter': 'AutoFilter',
'EvaluationOrder': 'int',
'FieldIndex': 'int',
'FilterType': 'str',
'MeasureFldIndex': 'int',
'MemberPropertyFieldIndex': 'int',
'Name': 'str',
'Value1': 'str',
'Value2': 'str'
}
self.attributeMap = {
'AutoFilter': 'AutoFilter','EvaluationOrder': 'EvaluationOrder','FieldIndex': 'FieldIndex','FilterType': 'FilterType','MeasureFldIndex': 'MeasureFldIndex','MemberPropertyFieldIndex': 'MemberPropertyFieldIndex','Name': 'Name','Value1': 'Value1','Value2': 'Value2'}
self.AutoFilter = None # AutoFilter
self.EvaluationOrder = None # int
self.FieldIndex = None # int
self.FilterType = None # str
self.MeasureFldIndex = None # int
self.MemberPropertyFieldIndex = None # int
self.Name = None # str
self.Value1 = None # str
self.Value2 = None # str
| aspose-cells/Aspose.Cells-for-Cloud | SDKs/Aspose.Cells-Cloud-SDK-for-Python/asposecellscloud/models/PivotFilter.py | Python | mit | 1,456 |
Experiment(description='No with centred periodic',
data_dir='../data/tsdlr/',
max_depth=8,
random_order=False,
k=1,
debug=False,
local_computation=False,
n_rand=9,
sd=4,
max_jobs=600,
verbose=False,
make_predictions=False,
skip_complete=True,
results_dir='../results/2013-09-07/',
iters=250,
base_kernels='StepTanh,CenPer,Cos,Lin,SE,Const,MT5,IMT3Lin',
zero_mean=True,
random_seed=1,
period_heuristic=5,
subset=True,
subset_size=250,
full_iters=0,
bundle_size=5)
| jamesrobertlloyd/gpss-research | experiments/2013-09-07.py | Python | mit | 710 |
import { noop as css } from '../../helpers/noop-template'
const styles = css`
[data-nextjs-dialog] {
display: flex;
flex-direction: column;
width: 100%;
margin-right: auto;
margin-left: auto;
outline: none;
background: white;
border-radius: var(--size-gap);
box-shadow: 0 var(--size-gap-half) var(--size-gap-double)
rgba(0, 0, 0, 0.25);
max-height: calc(100% - 56px);
overflow-y: hidden;
}
@media (max-height: 812px) {
[data-nextjs-dialog-overlay] {
max-height: calc(100% - 15px);
}
}
@media (min-width: 576px) {
[data-nextjs-dialog] {
max-width: 540px;
box-shadow: 0 var(--size-gap) var(--size-gap-quad) rgba(0, 0, 0, 0.25);
}
}
@media (min-width: 768px) {
[data-nextjs-dialog] {
max-width: 720px;
}
}
@media (min-width: 992px) {
[data-nextjs-dialog] {
max-width: 960px;
}
}
[data-nextjs-dialog-banner] {
position: relative;
}
[data-nextjs-dialog-banner].banner-warning {
border-color: var(--color-ansi-yellow);
}
[data-nextjs-dialog-banner].banner-error {
border-color: var(--color-ansi-red);
}
[data-nextjs-dialog-banner]::after {
z-index: 2;
content: '';
position: absolute;
top: 0;
right: 0;
width: 100%;
/* banner width: */
border-top-width: var(--size-gap-half);
border-bottom-width: 0;
border-top-style: solid;
border-bottom-style: solid;
border-top-color: inherit;
border-bottom-color: transparent;
}
[data-nextjs-dialog-content] {
overflow-y: auto;
border: none;
margin: 0;
/* calc(padding + banner width offset) */
padding: calc(var(--size-gap-double) + var(--size-gap-half))
var(--size-gap-double);
height: 100%;
display: flex;
flex-direction: column;
}
[data-nextjs-dialog-content] > [data-nextjs-dialog-header] {
flex-shrink: 0;
margin-bottom: var(--size-gap-double);
}
[data-nextjs-dialog-content] > [data-nextjs-dialog-body] {
position: relative;
flex: 1 1 auto;
}
`
export { styles }
| flybayer/next.js | packages/react-dev-overlay/src/internal/components/Dialog/styles.ts | TypeScript | mit | 2,088 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information
namespace Dnn.Modules.ResourceManager.Services.Dto
{
using System.Runtime.Serialization;
/// <summary>
/// Represents a request for folder details.
/// </summary>
public class FolderDetailsRequest
{
/// <summary>
/// Gets or sets the id of the folder.
/// </summary>
[DataMember(Name = "folderId")]
public int FolderId { get; set; }
/// <summary>
/// Gets or sets the name of the folder.
/// </summary>
[DataMember(Name = "folderName")]
public string FolderName { get; set; }
/// <summary>
/// Gets or sets the <see cref="FolderPermissions"/>.
/// </summary>
[DataMember(Name = "permissions")]
public FolderPermissions Permissions { get; set; }
}
}
| dnnsoftware/Dnn.Platform | DNN Platform/Modules/ResourceManager/Services/Dto/FolderDetailsRequest.cs | C# | mit | 1,005 |
<div class="container-fluid">
<div class="row">
<div class="col-xs-6 col-xs-offset-3">
<div class="page-header" style="border:none;margin: 0px;">
<h1><?= $this->slogan ?></h1>
</div>
</div>
</div>
<div class="row" style="margin-bottom: 2em;">
<div class="col-xs-6 col-xs-offset-3">
<form action="/user/register_submit" method="post">
<div class="form-group">
<input type="email" class="form-control" name="email" placeholder="请您输入用户名">
</div>
<div class="form-group">
<input type="password" class="form-control" name="password" placeholder="请您输入密码">
</div>
<button type="submit" class="col-xs-12 col-sm-12 btn btn-success">注册</button>
</form>
<br/> <br/> <br/>
<a href="/user/login" class="col-xs-4 col-sm-4 btn btn-link">登入</a>
<span class="col-xs-4 col-sm-4 "></span>
<a href="#" class="col-xs-4 col-sm-4 btn btn-link">忘记密码?</a>
</div>
</div>
</div> | tecshuttle/tiegan | application/views_dev/user/register.php | PHP | mit | 1,180 |
require 'ruboto/util/toast'
# Services are complicated and don't really make sense unless you
# show the interaction between the Service and other parts of your
# app.
# For now, just take a look at the explanation and example in
# online:
# http://developer.android.com/reference/android/app/Service.html
class SampleService
def onStartCommand(intent, flags, startId)
toast 'Hello from the service'
android.app.Service::START_NOT_STICKY
end
end
| lucasallan/ruboto | assets/samples/sample_service.rb | Ruby | mit | 459 |
/*
* The MIT License
*
* Copyright (c) 2015 The Broad Institute
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package picard.analysis;
import htsjdk.samtools.reference.ReferenceSequence;
import htsjdk.samtools.reference.ReferenceSequenceFile;
import htsjdk.samtools.reference.ReferenceSequenceFileFactory;
import htsjdk.samtools.util.SequenceUtil;
import htsjdk.samtools.util.StringUtil;
import java.io.File;
/** Utilities to calculate GC Bias
* Created by kbergin on 9/23/15.
*/
public class GcBiasUtils {
/////////////////////////////////////////////////////////////////////////////
// Calculates GC as a number from 0 to 100 in the specified window.
// If the window includes more than five no-calls then -1 is returned.
/////////////////////////////////////////////////////////////////////////////
public static int calculateGc(final byte[] bases, final int startIndex, final int endIndex, final CalculateGcState state) {
if (state.init) {
state.init = false;
state.gcCount = 0;
state.nCount = 0;
for (int i = startIndex; i < endIndex; ++i) {
final byte base = bases[i];
if (SequenceUtil.basesEqual(base, (byte)'G') || SequenceUtil.basesEqual(base, (byte)'C')) ++state.gcCount;
else if (SequenceUtil.basesEqual(base, (byte)'N')) ++state.nCount;
}
} else {
final byte newBase = bases[endIndex - 1];
if (SequenceUtil.basesEqual(newBase, (byte)'G') || SequenceUtil.basesEqual(newBase, (byte)'C')) ++state.gcCount;
else if (newBase == 'N') ++state.nCount;
if (SequenceUtil.basesEqual(state.priorBase, (byte)'G') || SequenceUtil.basesEqual(state.priorBase, (byte)'C')) --state.gcCount;
else if (SequenceUtil.basesEqual(state.priorBase, (byte)'N')) --state.nCount;
}
state.priorBase = bases[startIndex];
if (state.nCount > 4) return -1;
else return (state.gcCount * 100) / (endIndex - startIndex);
}
/////////////////////////////////////////////////////////////////////////////
// Calculate number of 100bp windows in the refBases passed in that fall into
// each gc content bin (0-100% gc)
/////////////////////////////////////////////////////////////////////////////
public static int[] calculateRefWindowsByGc(final int windows, final File referenceSequence, final int windowSize) {
final ReferenceSequenceFile refFile = ReferenceSequenceFileFactory.getReferenceSequenceFile(referenceSequence);
ReferenceSequence ref;
final int [] windowsByGc = new int [windows];
while ((ref = refFile.nextSequence()) != null) {
final byte[] refBases = ref.getBases();
StringUtil.toUpperCase(refBases);
final int refLength = refBases.length;
final int lastWindowStart = refLength - windowSize;
final CalculateGcState state = new GcBiasUtils().new CalculateGcState();
for (int i = 1; i < lastWindowStart; ++i) {
final int windowEnd = i + windowSize;
final int gcBin = calculateGc(refBases, i, windowEnd, state);
if (gcBin != -1) windowsByGc[gcBin]++;
}
}
return windowsByGc;
}
/////////////////////////////////////////////////////////////////////////////
// Calculate all the GC values for all windows
/////////////////////////////////////////////////////////////////////////////
public static byte [] calculateAllGcs(final byte[] refBases, final int lastWindowStart, final int windowSize) {
final CalculateGcState state = new GcBiasUtils().new CalculateGcState();
final int refLength = refBases.length;
final byte[] gc = new byte[refLength + 1];
for (int i = 1; i < lastWindowStart; ++i) {
final int windowEnd = i + windowSize;
final int windowGc = calculateGc(refBases, i, windowEnd, state);
gc[i] = (byte) windowGc;
}
return gc;
}
/////////////////////////////////////////////////////////////////////////////
// Keeps track of current GC calculation state
/////////////////////////////////////////////////////////////////////////////
class CalculateGcState {
boolean init = true;
int nCount;
int gcCount;
byte priorBase;
}
}
| annkupi/picard | src/main/java/picard/analysis/GcBiasUtils.java | Java | mit | 5,467 |
var util = require('util');
/**
* @class Recorder
* @param {{retention: <Number>}} [options]
*/
var Recorder = function(options) {
this._records = [];
this._options = _.defaults(options || {}, {
retention: 300, // seconds
recordMaxSize: 200, // nb records
jsonMaxSize: 50,
format: '[{date} {level}] {message}'
});
};
Recorder.prototype = {
/**
* @returns {String}
*/
getFormattedRecords: function() {
return _.map(this.getRecords(), function(record) {
return this._recordFormatter(record);
}, this).join('\n');
},
/**
* @returns {{date: {Date}, messages: *[], context: {Object}}[]}
*/
getRecords: function() {
return this._records;
},
/**
* @param {*[]} messages
* @param {Object} context
*/
addRecord: function(messages, context) {
var record = {
date: this._getDate(),
messages: messages,
context: context
};
this._records.push(record);
this._cleanupRecords();
},
flushRecords: function() {
this._records = [];
},
/**
* @private
*/
_cleanupRecords: function() {
var retention = this._options.retention;
var recordMaxSize = this._options.recordMaxSize;
if (retention > 0) {
var retentionTime = this._getDate() - (retention * 1000);
this._records = _.filter(this._records, function(record) {
return record.date > retentionTime;
});
}
if (recordMaxSize > 0 && this._records.length > recordMaxSize) {
this._records = this._records.slice(-recordMaxSize);
}
},
/**
* @param {{date: {Date}, messages: *[], context: {Object}}} record
* @returns {String}
* @private
*/
_recordFormatter: function(record) {
var log = this._options.format;
_.each({
date: record.date.toISOString(),
level: record.context.level.name,
message: this._messageFormatter(record.messages)
}, function(value, key) {
var pattern = new RegExp('{' + key + '}', 'g');
log = log.replace(pattern, value);
});
return log;
},
/**
* @param {*[]} messages
* @returns {String}
* @private
*/
_messageFormatter: function(messages) {
var clone = _.toArray(messages);
var index, value, encoded;
for (index = 0; index < clone.length; index++) {
encoded = value = clone[index];
if (_.isString(value) && 0 === index) {
// about console.log and util.format substitution,
// see https://developers.google.com/web/tools/chrome-devtools/debug/console/console-write#string-substitution-and-formatting
// and https://nodejs.org/api/util.html#util_util_format_format
value = value.replace(/%[idfoO]/g, '%s');
} else if (value instanceof RegExp) {
value = value.toString();
} else if (value instanceof Date) {
value = value.toISOString();
} else if (_.isObject(value) && value._class) {
value = '[' + value._class + (value._id && value._id.id ? ':' + value._id.id : '') + ']';
} else if (_.isObject(value) && /^\[object ((?!Object).)+\]$/.test(value.toString())) {
value = value.toString();
}
try {
if (_.isString(value) || _.isNumber(value)) {
encoded = value;
} else {
encoded = JSON.stringify(value);
if (encoded.length > this._options.jsonMaxSize) {
encoded = encoded.slice(0, this._options.jsonMaxSize - 4) + '…' + encoded[encoded.length - 1];
}
}
} catch (e) {
if (_.isUndefined(value)) {
encoded = 'undefined';
} else if (_.isNull(value)) {
encoded = 'null';
} else {
encoded = '[unknown]'
}
}
clone[index] = encoded;
}
return util.format.apply(util.format, clone);
},
/**
* @returns {Date}
* @private
*/
_getDate: function() {
return new Date();
}
};
module.exports = Recorder;
| njam/CM | client-vendor/source/logger/handlers/recorder.js | JavaScript | mit | 3,930 |
ReactDOM.render(React.createElement(
'div',
null,
React.createElement(Content, null)
), document.getElementById('content')); | azat-co/react-quickly | spare-parts/ch05-es5/logger/js/script.js | JavaScript | mit | 130 |
export * from './components/ajax-bar/index.js'
export * from './components/avatar/index.js'
export * from './components/badge/index.js'
export * from './components/banner/index.js'
export * from './components/bar/index.js'
export * from './components/breadcrumbs/index.js'
export * from './components/btn/index.js'
export * from './components/btn-dropdown/index.js'
export * from './components/btn-group/index.js'
export * from './components/btn-toggle/index.js'
export * from './components/card/index.js'
export * from './components/carousel/index.js'
export * from './components/chat/index.js'
export * from './components/checkbox/index.js'
export * from './components/chip/index.js'
export * from './components/circular-progress/index.js'
export * from './components/color/index.js'
export * from './components/date/index.js'
export * from './components/dialog/index.js'
export * from './components/drawer/index.js'
export * from './components/editor/index.js'
export * from './components/expansion-item/index.js'
export * from './components/fab/index.js'
export * from './components/field/index.js'
export * from './components/file/index.js'
export * from './components/footer/index.js'
export * from './components/form/index.js'
export * from './components/header/index.js'
export * from './components/icon/index.js'
export * from './components/img/index.js'
export * from './components/infinite-scroll/index.js'
export * from './components/inner-loading/index.js'
export * from './components/input/index.js'
export * from './components/intersection/index.js'
export * from './components/item/index.js'
export * from './components/knob/index.js'
export * from './components/layout/index.js'
export * from './components/markup-table/index.js'
export * from './components/menu/index.js'
export * from './components/no-ssr/index.js'
export * from './components/option-group/index.js'
export * from './components/page/index.js'
export * from './components/page-scroller/index.js'
export * from './components/page-sticky/index.js'
export * from './components/pagination/index.js'
export * from './components/parallax/index.js'
export * from './components/popup-edit/index.js'
export * from './components/popup-proxy/index.js'
export * from './components/linear-progress/index.js'
export * from './components/pull-to-refresh/index.js'
export * from './components/radio/index.js'
export * from './components/range/index.js'
export * from './components/rating/index.js'
export * from './components/resize-observer/index.js'
export * from './components/responsive/index.js'
export * from './components/scroll-area/index.js'
export * from './components/scroll-observer/index.js'
export * from './components/select/index.js'
export * from './components/separator/index.js'
export * from './components/skeleton/index.js'
export * from './components/slide-item/index.js'
export * from './components/slide-transition/index.js'
export * from './components/slider/index.js'
export * from './components/space/index.js'
export * from './components/spinner/index.js'
export * from './components/splitter/index.js'
export * from './components/stepper/index.js'
export * from './components/tab-panels/index.js'
export * from './components/table/index.js'
export * from './components/tabs/index.js'
export * from './components/time/index.js'
export * from './components/timeline/index.js'
export * from './components/toggle/index.js'
export * from './components/toolbar/index.js'
export * from './components/tooltip/index.js'
export * from './components/tree/index.js'
export * from './components/uploader/index.js'
export * from './components/video/index.js'
export * from './components/virtual-scroll/index.js'
| rstoenescu/quasar-framework | ui/src/components.js | JavaScript | mit | 3,696 |
/**
* Copyright (c) 2015-present, Alibaba Group Holding Limited.
* All rights reserved.
*
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* @providesModule ReactNavigatorNavigationBarStylesAndroid
*/
'use strict';
import buildStyleInterpolator from './polyfills/buildStyleInterpolator';
import merge from './polyfills/merge';
// Android Material Design
var NAV_BAR_HEIGHT = 56;
var TITLE_LEFT = 72;
var BUTTON_SIZE = 24;
var TOUCH_TARGT_SIZE = 48;
var BUTTON_HORIZONTAL_MARGIN = 16;
var BUTTON_EFFECTIVE_MARGIN = BUTTON_HORIZONTAL_MARGIN - (TOUCH_TARGT_SIZE - BUTTON_SIZE) / 2;
var NAV_ELEMENT_HEIGHT = NAV_BAR_HEIGHT;
var BASE_STYLES = {
Title: {
position: 'absolute',
bottom: 0,
left: 0,
right: 0,
alignItems: 'flex-start',
height: NAV_ELEMENT_HEIGHT,
backgroundColor: 'transparent',
marginLeft: TITLE_LEFT,
},
LeftButton: {
position: 'absolute',
top: 0,
left: BUTTON_EFFECTIVE_MARGIN,
overflow: 'hidden',
height: NAV_ELEMENT_HEIGHT,
backgroundColor: 'transparent',
},
RightButton: {
position: 'absolute',
top: 0,
right: BUTTON_EFFECTIVE_MARGIN,
overflow: 'hidden',
alignItems: 'flex-end',
height: NAV_ELEMENT_HEIGHT,
backgroundColor: 'transparent',
},
};
// There are 3 stages: left, center, right. All previous navigation
// items are in the left stage. The current navigation item is in the
// center stage. All upcoming navigation items are in the right stage.
// Another way to think of the stages is in terms of transitions. When
// we move forward in the navigation stack, we perform a
// right-to-center transition on the new navigation item and a
// center-to-left transition on the current navigation item.
var Stages = {
Left: {
Title: merge(BASE_STYLES.Title, { opacity: 0 }),
LeftButton: merge(BASE_STYLES.LeftButton, { opacity: 0 }),
RightButton: merge(BASE_STYLES.RightButton, { opacity: 0 }),
},
Center: {
Title: merge(BASE_STYLES.Title, { opacity: 1 }),
LeftButton: merge(BASE_STYLES.LeftButton, { opacity: 1 }),
RightButton: merge(BASE_STYLES.RightButton, { opacity: 1 }),
},
Right: {
Title: merge(BASE_STYLES.Title, { opacity: 0 }),
LeftButton: merge(BASE_STYLES.LeftButton, { opacity: 0 }),
RightButton: merge(BASE_STYLES.RightButton, { opacity: 0 }),
},
};
var opacityRatio = 100;
function buildSceneInterpolators(startStyles, endStyles) {
return {
Title: buildStyleInterpolator({
opacity: {
type: 'linear',
from: startStyles.Title.opacity,
to: endStyles.Title.opacity,
min: 0,
max: 1,
},
left: {
type: 'linear',
from: startStyles.Title.left,
to: endStyles.Title.left,
min: 0,
max: 1,
extrapolate: true,
},
}),
LeftButton: buildStyleInterpolator({
opacity: {
type: 'linear',
from: startStyles.LeftButton.opacity,
to: endStyles.LeftButton.opacity,
min: 0,
max: 1,
round: opacityRatio,
},
left: {
type: 'linear',
from: startStyles.LeftButton.left,
to: endStyles.LeftButton.left,
min: 0,
max: 1,
},
}),
RightButton: buildStyleInterpolator({
opacity: {
type: 'linear',
from: startStyles.RightButton.opacity,
to: endStyles.RightButton.opacity,
min: 0,
max: 1,
round: opacityRatio,
},
left: {
type: 'linear',
from: startStyles.RightButton.left,
to: endStyles.RightButton.left,
min: 0,
max: 1,
extrapolate: true,
},
}),
};
}
var Interpolators = {
// Animating *into* the center stage from the right
RightToCenter: buildSceneInterpolators(Stages.Right, Stages.Center),
// Animating out of the center stage, to the left
CenterToLeft: buildSceneInterpolators(Stages.Center, Stages.Left),
// Both stages (animating *past* the center stage)
RightToLeft: buildSceneInterpolators(Stages.Right, Stages.Left),
};
module.exports = {
General: {
NavBarHeight: NAV_BAR_HEIGHT,
StatusBarHeight: 0,
TotalNavHeight: NAV_BAR_HEIGHT,
},
Interpolators,
Stages,
};
| typesettin/NativeCMS | node_modules/react-web/Libraries/Navigator/NavigatorNavigationBarStylesAndroid.js | JavaScript | mit | 4,250 |
package net.anotheria.moskito.webui.threads.api;
import net.anotheria.anoplass.api.APIFactory;
import net.anotheria.anoplass.api.APIFinder;
import net.anotheria.anoprise.metafactory.ServiceFactory;
/**
* TODO comment this class
*
* @author lrosenberg
* @since 14.02.13 11:46
*/
public class ThreadAPIFactory implements APIFactory<ThreadAPI>, ServiceFactory<ThreadAPI> {
@Override
public ThreadAPI createAPI() {
return new ThreadAPIImpl();
}
@Override
public ThreadAPI create() {
APIFinder.addAPIFactory(ThreadAPI.class, this);
return APIFinder.findAPI(ThreadAPI.class);
}
}
| esmakula/moskito | moskito-webui/src/main/java/net/anotheria/moskito/webui/threads/api/ThreadAPIFactory.java | Java | mit | 594 |
require "spec_helper"
require "hamster/sorted_set"
describe Hamster::SortedSet do
describe "#disjoint?" do
[
[[], [], true],
[["A"], [], true],
[[], ["A"], true],
[["A"], ["A"], false],
[%w[A B C], ["B"], false],
[["B"], %w[A B C], false],
[%w[A B C], %w[D E], true],
[%w[F G H I], %w[A B C], true],
[%w[A B C], %w[A B C], false],
[%w[A B C], %w[A B C D], false],
[%w[D E F G], %w[A B C], true],
].each do |a, b, expected|
context "for #{a.inspect} and #{b.inspect}" do
it "returns #{expected}" do
Hamster.sorted_set(*a).disjoint?(Hamster.sorted_set(*b)).should be(expected)
end
end
end
end
end | dzjuck/hamster | spec/lib/hamster/sorted_set/disjoint_spec.rb | Ruby | mit | 715 |
<?php
/**
*
*/
namespace Mvc5\Plugin\Gem;
interface Copy
extends Gem
{
/**
* @return object
*/
function config();
}
| devosc/mvc5 | src/Plugin/Gem/Copy.php | PHP | mit | 142 |
# frozen_string_literal: true
class AvatarUploader < GitlabUploader
include UploaderHelper
include RecordsUploads::Concern
include ObjectStorage::Concern
prepend ObjectStorage::Extension::RecordsUploads
MIME_WHITELIST = %w[image/png image/jpeg image/gif image/bmp image/tiff image/vnd.microsoft.icon].freeze
def exists?
model.avatar.file && model.avatar.file.present?
end
def move_to_store
false
end
def move_to_cache
false
end
def absolute_path
self.class.absolute_path(upload)
end
def mounted_as
super || 'avatar'
end
def content_type_whitelist
MIME_WHITELIST
end
private
def dynamic_segment
File.join(model.class.underscore, mounted_as.to_s, model.id.to_s)
end
end
| mmkassem/gitlabhq | app/uploaders/avatar_uploader.rb | Ruby | mit | 746 |
<?php defined('BX_DOL') or die('hack attempt');
/**
* Copyright (c) BoonEx Pty Limited - http://www.boonex.com/
* CC-BY License - http://creativecommons.org/licenses/by/3.0/
*
* @defgroup Accounts Accounts
* @ingroup DolphinModules
*
* @{
*/
class BxAccntConfig extends BxBaseModGeneralConfig
{
protected $_oDb;
protected $_aHtmlIds;
/**
* Constructor
*/
public function __construct($aModule)
{
parent::__construct($aModule);
$this->CNF = array (
// page URIs
'URL_MANAGE_ADMINISTRATION' => 'page.php?i=accounts-administration',
// objects
'OBJECT_MENU_MANAGE_TOOLS' => 'bx_accounts_menu_manage_tools', //manage menu in content administration tools
'OBJECT_GRID_ADMINISTRATION' => 'bx_accounts_administration',
'OBJECT_GRID_MODERATION' => 'bx_accounts_moderation',
// some language keys
'T' => array (
'grid_action_err_delete' => '_bx_accnt_grid_action_err_delete',
'grid_action_err_perform' => '_bx_accnt_grid_action_err_perform',
'filter_item_active' => '_bx_accnt_grid_filter_item_title_adm_active',
'filter_item_pending' => '_bx_accnt_grid_filter_item_title_adm_pending',
'filter_item_suspended' => '_bx_accnt_grid_filter_item_title_adm_suspended',
'filter_item_select_one_filter1' => '_bx_accnt_grid_filter_item_title_adm_select_one_filter1',
)
);
$this->_aObjects = array(
'alert' => $this->_sName,
);
$this->_aJsClass = array(
'manage_tools' => 'BxAccntManageTools'
);
$this->_aJsObjects = array(
'manage_tools' => 'oBxAccntManageTools'
);
$this->_aGridObjects = array(
'moderation' => $this->CNF['OBJECT_GRID_MODERATION'],
'administration' => $this->CNF['OBJECT_GRID_ADMINISTRATION'],
);
$sHtmlPrefix = str_replace('_', '-', $this->_sName);
$this->_aHtmlIds = array(
'profile' => $sHtmlPrefix . '-profile-',
'profile_more_popup' => $sHtmlPrefix . '-profile-more-popup-',
);
}
public function init(&$oDb)
{
$this->_oDb = &$oDb;
}
public function getHtmlIds($sKey = '')
{
if(empty($sKey))
return $this->_aHtmlIds;
return isset($this->_aHtmlIds[$sKey]) ? $this->_aHtmlIds[$sKey] : '';
}
}
/** @} */
| camperjz/trident | modules/boonex/accounts/updates/8.0.1_8.0.2/source/classes/BxAccntConfig.php | PHP | mit | 2,465 |
# Copyright (c) 2005 Zed A. Shaw
# You can redistribute it and/or modify it under the same terms as Ruby.
#
# Additional work donated by contributors. See http://mongrel.rubyforge.org/attributions.html
# for more information.
require 'test/testhelp'
include Mongrel
class URIClassifierTest < Test::Unit::TestCase
def test_uri_finding
uri_classifier = URIClassifier.new
uri_classifier.register("/test", 1)
script_name, path_info, value = uri_classifier.resolve("/test")
assert_equal 1, value
assert_equal "/test", script_name
end
def test_root_handler_only
uri_classifier = URIClassifier.new
uri_classifier.register("/", 1)
script_name, path_info, value = uri_classifier.resolve("/test")
assert_equal 1, value
assert_equal "/", script_name
assert_equal "/test", path_info
end
def test_uri_prefix_ops
test = "/pre/fix/test"
prefix = "/pre"
uri_classifier = URIClassifier.new
uri_classifier.register(prefix,1)
script_name, path_info, value = uri_classifier.resolve(prefix)
script_name, path_info, value = uri_classifier.resolve(test)
assert_equal 1, value
assert_equal prefix, script_name
assert_equal test[script_name.length .. -1], path_info
assert uri_classifier.inspect
assert_equal prefix, uri_classifier.uris[0]
end
def test_not_finding
test = "/cant/find/me"
uri_classifier = URIClassifier.new
uri_classifier.register(test, 1)
script_name, path_info, value = uri_classifier.resolve("/nope/not/here")
assert_nil script_name
assert_nil path_info
assert_nil value
end
def test_exceptions
uri_classifier = URIClassifier.new
uri_classifier.register("/test", 1)
failed = false
begin
uri_classifier.register("/test", 1)
rescue => e
failed = true
end
assert failed
failed = false
begin
uri_classifier.register("", 1)
rescue => e
failed = true
end
assert failed
end
def test_register_unregister
uri_classifier = URIClassifier.new
100.times do
uri_classifier.register("/stuff", 1)
value = uri_classifier.unregister("/stuff")
assert_equal 1, value
end
uri_classifier.register("/things",1)
script_name, path_info, value = uri_classifier.resolve("/things")
assert_equal 1, value
uri_classifier.unregister("/things")
script_name, path_info, value = uri_classifier.resolve("/things")
assert_nil value
end
def test_uri_branching
uri_classifier = URIClassifier.new
uri_classifier.register("/test", 1)
uri_classifier.register("/test/this",2)
script_name, path_info, handler = uri_classifier.resolve("/test")
script_name, path_info, handler = uri_classifier.resolve("/test/that")
assert_equal "/test", script_name, "failed to properly find script off branch portion of uri"
assert_equal "/that", path_info
assert_equal 1, handler, "wrong result for branching uri"
end
def test_all_prefixing
tests = ["/test","/test/that","/test/this"]
uri = "/test/this/that"
uri_classifier = URIClassifier.new
current = ""
uri.each_byte do |c|
current << c.chr
uri_classifier.register(current, c)
end
# Try to resolve everything with no asserts as a fuzzing
tests.each do |prefix|
current = ""
prefix.each_byte do |c|
current << c.chr
script_name, path_info, handler = uri_classifier.resolve(current)
assert script_name
assert path_info
assert handler
end
end
# Assert that we find stuff
tests.each do |t|
script_name, path_info, handler = uri_classifier.resolve(t)
assert handler
end
# Assert we don't find stuff
script_name, path_info, handler = uri_classifier.resolve("chicken")
assert_nil handler
assert_nil script_name
assert_nil path_info
end
# Verifies that a root mounted ("/") handler resolves
# such that path info matches the original URI.
# This is needed to accommodate real usage of handlers.
def test_root_mounted
uri_classifier = URIClassifier.new
root = "/"
path = "/this/is/a/test"
uri_classifier.register(root, 1)
script_name, path_info, handler = uri_classifier.resolve(root)
assert_equal 1, handler
assert_equal root, path_info
assert_equal root, script_name
script_name, path_info, handler = uri_classifier.resolve(path)
assert_equal path, path_info
assert_equal root, script_name
assert_equal 1, handler
end
# Verifies that a root mounted ("/") handler
# is the default point, doesn't matter the order we use
# to register the URIs
def test_classifier_order
tests = ["/before", "/way_past"]
root = "/"
path = "/path"
uri_classifier = URIClassifier.new
uri_classifier.register(path, 1)
uri_classifier.register(root, 2)
tests.each do |uri|
script_name, path_info, handler = uri_classifier.resolve(uri)
assert_equal root, script_name, "#{uri} did not resolve to #{root}"
assert_equal uri, path_info
assert_equal 2, handler
end
end
if ENV['BENCHMARK']
# Eventually we will have a suite of benchmarks instead of lamely installing a test
def test_benchmark
# This URI set should favor a TST. Both versions increase linearly until you hit 14
# URIs, then the TST flattens out.
@uris = %w(
/
/dag /dig /digbark /dog /dogbark /dog/bark /dug /dugbarking /puppy
/c /cat /cat/tree /cat/tree/mulberry /cats /cot /cot/tree/mulberry /kitty /kittycat
# /eag /eig /eigbark /eog /eogbark /eog/bark /eug /eugbarking /iuppy
# /f /fat /fat/tree /fat/tree/mulberry /fats /fot /fot/tree/mulberry /jitty /jittyfat
# /gag /gig /gigbark /gog /gogbark /gog/bark /gug /gugbarking /kuppy
# /h /hat /hat/tree /hat/tree/mulberry /hats /hot /hot/tree/mulberry /litty /littyhat
# /ceag /ceig /ceigbark /ceog /ceogbark /ceog/cbark /ceug /ceugbarking /ciuppy
# /cf /cfat /cfat/ctree /cfat/ctree/cmulberry /cfats /cfot /cfot/ctree/cmulberry /cjitty /cjittyfat
# /cgag /cgig /cgigbark /cgog /cgogbark /cgog/cbark /cgug /cgugbarking /ckuppy
# /ch /chat /chat/ctree /chat/ctree/cmulberry /chats /chot /chot/ctree/cmulberry /citty /cittyhat
)
@requests = %w(
/
/dig
/digging
/dogging
/dogbarking/
/puppy/barking
/c
/cat
/cat/shrub
/cat/tree
/cat/tree/maple
/cat/tree/mulberry/tree
/cat/tree/oak
/cats/
/cats/tree
/cod
/zebra
)
@classifier = URIClassifier.new
@uris.each do |uri|
@classifier.register(uri, 1)
end
puts "#{@uris.size} URIs / #{@requests.size * 10000} requests"
Benchmark.bm do |x|
x.report do
# require 'ruby-prof'
# profile = RubyProf.profile do
10000.times do
@requests.each do |request|
@classifier.resolve(request)
end
end
# end
# File.open("profile.html", 'w') { |file| RubyProf::GraphHtmlPrinter.new(profile).print(file, 0) }
end
end
end
end
end
| claudiobm/ClockingIT-In-CapellaDesign | vendor/gems/mongrel-1.1.5/test/test_uriclassifier.rb | Ruby | mit | 7,361 |
require 'uri'
module Idobata::Hook
class PivotalTracker
module Helper
filters = [
::HTML::Pipeline::MarkdownFilter
]
filters << ::HTML::Pipeline::SyntaxHighlightFilter if defined?(Linguist) # This filter doesn't work on heroku
Pipeline = ::HTML::Pipeline.new(filters, gfm: true, base_url: 'https://www.pivotaltracker.com/')
def md(source)
result = Pipeline.call(source)
result[:output].to_s.html_safe
end
def new_value(kind)
new_values(kind).first
end
def new_values(kind)
payload.changes.select {|change| change.kind == kind.to_s }.map(&:new_values).compact
end
def download_url(attachment)
download_url = URI.parse(attachment.download_url)
# XXX Current API returns only path info.
unless download_url.host
download_url.scheme = 'https'
download_url.host = 'www.pivotaltracker.com'
end
download_url.query = {inline: true}.to_param unless download_url.query
download_url.to_s
end
end
end
end
| SuzukiMasashi/idobata-hooks | lib/hooks/pivotal_tracker/helper.rb | Ruby | mit | 1,098 |
import { __decorate } from 'tslib';
import { NgModule } from '@angular/core';
import { ANGULARTICS2_TOKEN, RouterlessTracking, Angulartics2, Angulartics2OnModule } from 'angulartics2';
var Angulartics2RouterlessModule_1;
let Angulartics2RouterlessModule = Angulartics2RouterlessModule_1 = class Angulartics2RouterlessModule {
static forRoot(settings = {}) {
return {
ngModule: Angulartics2RouterlessModule_1,
providers: [
{ provide: ANGULARTICS2_TOKEN, useValue: { settings } },
RouterlessTracking,
Angulartics2,
],
};
}
};
Angulartics2RouterlessModule = Angulartics2RouterlessModule_1 = __decorate([
NgModule({
imports: [Angulartics2OnModule],
})
], Angulartics2RouterlessModule);
export { Angulartics2RouterlessModule };
//# sourceMappingURL=angulartics2-routerlessmodule.js.map
| cdnjs/cdnjs | ajax/libs/angulartics2/8.3.0/routerlessmodule/fesm2015/angulartics2-routerlessmodule.js | JavaScript | mit | 907 |
/*******************************************************************************
* Copyright (c) 2010, 2011 Sean Muir
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Sean Muir (JKM Software) - initial API and implementation
*******************************************************************************/
package org.openhealthtools.mdht.uml.cda.builder.test;
import org.junit.Assert;
import org.junit.Test;
import org.openhealthtools.mdht.uml.cda.ClinicalDocument;
import org.openhealthtools.mdht.uml.cda.Section;
import org.openhealthtools.mdht.uml.cda.builder.CDABuilderFactory;
import org.openhealthtools.mdht.uml.cda.builder.DocumentBuilder;
import org.openhealthtools.mdht.uml.cda.builder.SectionBuilder;
import org.openhealthtools.mdht.uml.cda.util.CDAUtil;
public class TestCDABuilderFactory {
@Test
public void testCreateClinicalDocumentBuilder() throws Exception {
DocumentBuilder<ClinicalDocument> clinicalDocumentBuilder = CDABuilderFactory.createClinicalDocumentBuilder();
ClinicalDocument clinicalDocument = clinicalDocumentBuilder.buildDocument();
Assert.assertNotNull(clinicalDocument);
CDAUtil.save(clinicalDocument, System.out);
}
@Test
public void testCreateSectionBuilder() throws Exception {
DocumentBuilder<ClinicalDocument> clinicalDocumentBuilder = CDABuilderFactory.createClinicalDocumentBuilder();
SectionBuilder<Section> sectionBuilder = CDABuilderFactory.createSectionBuilder();
Section section = sectionBuilder.buildSection();
Assert.assertNotNull(section);
CDAUtil.save(clinicalDocumentBuilder.with(section).buildDocument(), System.out);
}
}
| drbgfc/mdht | cda/examples/org.openhealthtools.mdht.cda.builder/src/org/openhealthtools/mdht/uml/cda/builder/test/TestCDABuilderFactory.java | Java | epl-1.0 | 1,871 |
/*******************************************************************************
* Copyright (c) 2012 David A Carlson.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* David A Carlson (XMLmodeling.com) - initial API and implementation
*******************************************************************************/
package org.openhealthtools.mdht.cts2.codesystem.impl;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.impl.EFactoryImpl;
import org.eclipse.emf.ecore.plugin.EcorePlugin;
import org.openhealthtools.mdht.cts2.codesystem.CodeSystemCatalogEntry;
import org.openhealthtools.mdht.cts2.codesystem.CodeSystemCatalogEntryDirectory;
import org.openhealthtools.mdht.cts2.codesystem.CodeSystemCatalogEntryList;
import org.openhealthtools.mdht.cts2.codesystem.CodeSystemCatalogEntryListEntry;
import org.openhealthtools.mdht.cts2.codesystem.CodeSystemCatalogEntryMsg;
import org.openhealthtools.mdht.cts2.codesystem.CodeSystemCatalogEntrySummary;
import org.openhealthtools.mdht.cts2.codesystem.CodeSystemFactory;
import org.openhealthtools.mdht.cts2.codesystem.CodeSystemPackage;
import org.openhealthtools.mdht.cts2.codesystem.DocumentRoot;
/**
* <!-- begin-user-doc -->
* An implementation of the model <b>Factory</b>.
* <!-- end-user-doc -->
*
* @generated
*/
public class CodeSystemFactoryImpl extends EFactoryImpl implements CodeSystemFactory {
/**
* Creates the default factory implementation.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
public static CodeSystemFactory init() {
try {
CodeSystemFactory theCodeSystemFactory = (CodeSystemFactory) EPackage.Registry.INSTANCE.getEFactory("http://schema.omg.org/spec/CTS2/1.0/CodeSystem");
if (theCodeSystemFactory != null) {
return theCodeSystemFactory;
}
} catch (Exception exception) {
EcorePlugin.INSTANCE.log(exception);
}
return new CodeSystemFactoryImpl();
}
/**
* Creates an instance of the factory.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
public CodeSystemFactoryImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public EObject create(EClass eClass) {
switch (eClass.getClassifierID()) {
case CodeSystemPackage.CODE_SYSTEM_CATALOG_ENTRY:
return createCodeSystemCatalogEntry();
case CodeSystemPackage.CODE_SYSTEM_CATALOG_ENTRY_DIRECTORY:
return createCodeSystemCatalogEntryDirectory();
case CodeSystemPackage.CODE_SYSTEM_CATALOG_ENTRY_LIST:
return createCodeSystemCatalogEntryList();
case CodeSystemPackage.CODE_SYSTEM_CATALOG_ENTRY_LIST_ENTRY:
return createCodeSystemCatalogEntryListEntry();
case CodeSystemPackage.CODE_SYSTEM_CATALOG_ENTRY_MSG:
return createCodeSystemCatalogEntryMsg();
case CodeSystemPackage.CODE_SYSTEM_CATALOG_ENTRY_SUMMARY:
return createCodeSystemCatalogEntrySummary();
case CodeSystemPackage.DOCUMENT_ROOT:
return createDocumentRoot();
default:
throw new IllegalArgumentException("The class '" + eClass.getName() + "' is not a valid classifier");
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
public CodeSystemCatalogEntry createCodeSystemCatalogEntry() {
CodeSystemCatalogEntryImpl codeSystemCatalogEntry = new CodeSystemCatalogEntryImpl();
return codeSystemCatalogEntry;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
public CodeSystemCatalogEntryDirectory createCodeSystemCatalogEntryDirectory() {
CodeSystemCatalogEntryDirectoryImpl codeSystemCatalogEntryDirectory = new CodeSystemCatalogEntryDirectoryImpl();
return codeSystemCatalogEntryDirectory;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
public CodeSystemCatalogEntryList createCodeSystemCatalogEntryList() {
CodeSystemCatalogEntryListImpl codeSystemCatalogEntryList = new CodeSystemCatalogEntryListImpl();
return codeSystemCatalogEntryList;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
public CodeSystemCatalogEntryListEntry createCodeSystemCatalogEntryListEntry() {
CodeSystemCatalogEntryListEntryImpl codeSystemCatalogEntryListEntry = new CodeSystemCatalogEntryListEntryImpl();
return codeSystemCatalogEntryListEntry;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
public CodeSystemCatalogEntryMsg createCodeSystemCatalogEntryMsg() {
CodeSystemCatalogEntryMsgImpl codeSystemCatalogEntryMsg = new CodeSystemCatalogEntryMsgImpl();
return codeSystemCatalogEntryMsg;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
public CodeSystemCatalogEntrySummary createCodeSystemCatalogEntrySummary() {
CodeSystemCatalogEntrySummaryImpl codeSystemCatalogEntrySummary = new CodeSystemCatalogEntrySummaryImpl();
return codeSystemCatalogEntrySummary;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
public DocumentRoot createDocumentRoot() {
DocumentRootImpl documentRoot = new DocumentRootImpl();
return documentRoot;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
public CodeSystemPackage getCodeSystemPackage() {
return (CodeSystemPackage) getEPackage();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @deprecated
* @generated
*/
@Deprecated
public static CodeSystemPackage getPackage() {
return CodeSystemPackage.eINSTANCE;
}
} // CodeSystemFactoryImpl
| drbgfc/mdht | cts2/plugins/org.openhealthtools.mdht.cts2.core/src/org/openhealthtools/mdht/cts2/codesystem/impl/CodeSystemFactoryImpl.java | Java | epl-1.0 | 5,866 |
package io.liveoak.scripts.resourcetriggered.interceptor;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import io.liveoak.common.DefaultResourceErrorResponse;
import io.liveoak.scripts.objects.Util;
import io.liveoak.scripts.objects.impl.exception.LiveOakException;
import io.liveoak.scripts.resourcetriggered.manager.ResourceScriptManager;
import io.liveoak.spi.Application;
import io.liveoak.spi.ResourceErrorResponse;
import io.liveoak.spi.ResourcePath;
import io.liveoak.spi.ResourceRequest;
import io.liveoak.spi.ResourceResponse;
import io.liveoak.spi.container.interceptor.DefaultInterceptor;
import io.liveoak.spi.container.interceptor.InboundInterceptorContext;
import io.liveoak.spi.container.interceptor.OutboundInterceptorContext;
import org.dynjs.exception.ThrowException;
/**
* @author <a href="mailto:mwringe@redhat.com">Matt Wringe</a>
*/
public class ScriptInterceptor extends DefaultInterceptor {
Map<String, ResourceScriptManager> managers;
private static final String DYNJS_ERROR_PREFIX = "Error: ";
public ScriptInterceptor() {
managers = new HashMap<>();
}
@Override
public void onInbound(InboundInterceptorContext context) throws Exception {
try {
String applicationName = getApplicationName(context.request());
ResourceScriptManager manager = managers.get(applicationName);
if (manager != null) {
Object reply = manager.executeScripts(context.request());
if (reply instanceof ResourceRequest) {
context.forward((ResourceRequest) reply);
} else if (reply instanceof ResourceResponse) {
context.replyWith((ResourceResponse) reply);
} else {
context.forward();
}
} else {
context.forward();
}
} catch (Exception e) {
e.printStackTrace();
String message = "Error processing request";
if (e.getMessage() != null && !e.getMessage().equals(DYNJS_ERROR_PREFIX)) {
message = e.getMessage();
if (message.startsWith(DYNJS_ERROR_PREFIX)) {
message = message.substring(DYNJS_ERROR_PREFIX.length());
context.replyWith(new DefaultResourceErrorResponse(context.request(), ResourceErrorResponse.ErrorType.INTERNAL_ERROR, message));
return;
}
} else if (e instanceof ThrowException) {
Object value = ((ThrowException)e).getValue();
if (value instanceof LiveOakException) {
context.replyWith(Util.getErrorResponse(context.request(), (LiveOakException)value));
return;
}
}
context.replyWith(new DefaultResourceErrorResponse(context.request(), ResourceErrorResponse.ErrorType.INTERNAL_ERROR, "Error processing script"));
}
}
@Override
public void onOutbound(OutboundInterceptorContext context) throws Exception {
try {
String applicationName = getApplicationName(context.response().inReplyTo());
ResourceScriptManager manager = managers.get(applicationName);
if (manager != null) {
Object reply = manager.executeScripts(context.response());
if (reply instanceof ResourceResponse) {
context.forward((ResourceResponse) reply);
} else {
context.forward();
}
} else {
context.forward();
}
} catch (Exception e) {
e.printStackTrace();
String message = "Error processing response";
//TODO: remove the "Error: " check here, its because DynJS for some reason uses a crappy empty error message.
if (e.getMessage() != null && !e.getMessage().equals(DYNJS_ERROR_PREFIX)) {
message = e.getMessage();
if (message.startsWith(DYNJS_ERROR_PREFIX)) {
message = message.substring(DYNJS_ERROR_PREFIX.length());
}
} else if (e instanceof ThrowException) {
Object value = ((ThrowException)e).getValue();
if (value instanceof LiveOakException) {
context.forward(Util.getErrorResponse(context.response().inReplyTo(), (LiveOakException)value));
return;
}
}
context.forward(new DefaultResourceErrorResponse(context.response().inReplyTo(), ResourceErrorResponse.ErrorType.INTERNAL_ERROR, "Error processing script"));
}
}
@Override
public void onComplete(UUID requestId) {
//currently do nothing.
}
private String getApplicationName(ResourceRequest request) {
//TODO: once we have the application actually being added to the requestContext remove getting the name from the ResourcePath
List<ResourcePath.Segment> resourcePaths = request.resourcePath().segments();
String applicationName = "/";
if (resourcePaths.size() > 0) {
applicationName = resourcePaths.get(0).name();
}
// TODO: This is proper way to check, but application is currently not set
Application application = request.requestContext().application();
if (application != null) {
applicationName = application.id();
}
return applicationName;
}
public void addManager(String applicationName, ResourceScriptManager manager) {
managers.put(applicationName, manager);
}
public void removeManager(String applicationName) {
managers.remove(applicationName);
}
}
| liveoak-io/liveoak | modules/scripts/src/main/java/io/liveoak/scripts/resourcetriggered/interceptor/ScriptInterceptor.java | Java | epl-1.0 | 5,830 |
var armorSetPvPSuperior = new armorSetObject("pvpsuperior");
armorSetPvPSuperior.slotsArray = new Array();
t = 0;
armorSetPvPSuperior.slotsArray[t] = "head"; t++;
armorSetPvPSuperior.slotsArray[t] = "shoulder"; t++;
armorSetPvPSuperior.slotsArray[t] = "chest"; t++;
armorSetPvPSuperior.slotsArray[t] = "hands"; t++;
armorSetPvPSuperior.slotsArray[t] = "legs"; t++;
armorSetPvPSuperior.slotsArray[t] = "feet"; t++;
armorSetPvPSuperior.slotsNumber = armorSetPvPSuperior.slotsArray.length;
armorSetPvPSuperior.statsArray = new Array();
armorSetPvPSuperior.itemNameArray = new Array();
armorSetPvPSuperior.setNameArray = new Array();
t = 0;
armorSetPvPSuperior.setNamesArray = new Array();
x = 0;
armorSetPvPSuperior.setNamesArray[x] = "Refuge"; x++;
armorSetPvPSuperior.setNamesArray[x] = "Pursuance"; x++;
armorSetPvPSuperior.setNamesArray[x] = "Arcanum"; x++;
armorSetPvPSuperior.setNamesArray[x] = "Redoubt"; x++;
armorSetPvPSuperior.setNamesArray[x] = "Investiture"; x++;
armorSetPvPSuperior.setNamesArray[x] = "Guard"; x++;
armorSetPvPSuperior.setNamesArray[x] = "Stormcaller"; x++;
armorSetPvPSuperior.setNamesArray[x] = "Dreadgear"; x++;
armorSetPvPSuperior.setNamesArray[x] = "Battlearmor"; x++;
classCounter = 0;
//DONT LOCALIZE ABOVE THIS COMMENT LINE
//LOCALIZE EVERYTHING BELOW THIS COMMENT LINE
//druid begin
var sanctuaryBlue = '<span class = "myGreen">\
(2) Set: +40 Attack Power<br>\
(4) Set: Increases your movement speed by 15% while in Bear, Cat, or Travel Form. Only active outdoors.<br>\
(6) Set: +20 Stamina\
</span>';
armorSetPvPSuperior.setNameArray[classCounter] = ['<span class = "myYellow">\
Lieutenant Commander\'s Refuge (0/6)<br>\
</span><span class = "myGray">\
Lieutenant Commander\'s Dragonhide Shoulders<br>\
Lieutenant Commander\'s Dragonhide Headguard<br>\
Knight-Captain\'s Dragonhide Leggings<br>\
Knight-Captain\'s Dragonhide Chestpiece<br>\
Knight-Lieutenant\'s Dragonhide Treads<br>\
Knight-Lieutenant\'s Dragonhide Grips<br>\
</span>'+ sanctuaryBlue, '<span class = "myYellow">\
Champion\'s Refuge (0/6)<br>\
</span><span class = "myGray">\
Blood Guard\'s Dragonhide Treads<br>\
Blood Guard\'s Dragonhide Grips<br>\
Legionnaire\'s Dragonhide Chestpiece<br>\
Legionnaire\'s Dragonhide Leggings<br>\
Champion\'s Dragonhide Headguard<br>\
Champion\'s Dragonhide Shoulders<br>\
</span>'+ sanctuaryBlue];
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Dragonhide Headguard', '<span class = "myBlue">\
Champion\'s Dragonhide Headguard'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Head\
</span></td><td align = "right"><span class = "myTable">\
Leather\
</span></td></tr></table>\
198 Armor<br>\
+16 Strength<br>\
+12 Agility<br>\
+16 Stamina<br>\
+16 Intellect<br>\
+8 Spirit<br>\
Classes: Druid<br>\
Durability 60/60<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 18.</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Dragonhide Shoulders', '<span class = "myBlue">\
Champion\'s Dragonhide Shoulders'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Shoulders\
</span></td><td align = "right"><span class = "myTable">\
Leather\
</span></td></tr></table>\
206 Armor<br>\
+12 Strength<br>\
+6 Agility<br>\
+12 Stamina<br>\
+12 Intellect<br>\
+6 Spirit<br>\
Classes: Druid<br>\
Durability 60/60<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 14.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Dragonhide Chestpiece', '<span class = "myBlue">\
Legionnaire\'s Dragonhide Chestpiece'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Chest\
</span></td><td align = "right"><span class = "myTable">\
Leather\
</span></td></tr></table>\
218 Armor<br>\
+13 Strength<br>\
+12 Agility<br>\
+13 Stamina<br>\
+12 Intellect<br>\
Classes: Druid<br>\
Durability 100/100<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 1%.<br>\
Equip: Increases damage and healing done by magical spells and effects by up to 15.</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Dragonhide Grips', '<span class = "myBlue">\
Blood Guard\'s Dragonhide Grips'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Hands\
</span></td><td align = "right"><span class = "myTable">\
Leather\
</span></td></tr></table>\
115 Armor<br>\
+13 Strength<br>\
+10 Agility<br>\
+12 Stamina<br>\
+9 Intellect<br>\
Classes: Druid<br>\
Durability 35/35<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Slightly increases your stealth detection.</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Dragonhide Leggings', '<span class = "myBlue">\
Legionnaire\'s Dragonhide Leggings'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Legs\
</span></td><td align = "right"><span class = "myTable">\
Leather\
</span></td></tr></table>\
215 Armor<br>\
+12 Strength<br>\
+12 Agility<br>\
+12 Stamina<br>\
+12 Intellect<br>\
+5 Spirit<br>\
Classes: Druid<br>\
Durability 75/75<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike with spells by 1%.<br>\
Equip: Increases damage and healing done by magical spells and effects by up to 14.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Dragonhide Treads', '<span class = "myBlue">\
Blood Guard\'s Dragonhide Treads'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Feet\
</span></td><td align = "right"><span class = "myTable">\
Leather\
</span></td></tr></table>\
126 Armor<br>\
+13 Strength<br>\
+6 Agility<br>\
+13 Stamina<br>\
+6 Intellect<br>\
+6 Spirit<br>\
Classes: Druid<br>\
Durability 50/50<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 14.</span>\
<p>';
//druid end
classCounter++;
//hunter begin
var pursuitBlue = '<span class = "myGreen">\
(2) Set: +20 Agility.<br>\
(4) Set: Reduces the cooldown of your Concussive Shot by 1 sec.<br>\
(6) Set: +20 Stamina.\
</span>';
armorSetPvPSuperior.setNameArray[classCounter] = ['<span class = "myYellow">\
Lieutenant Commander\'s Pursuance (0/6)<br>\
</span><span class = "myGray">\
Lieutenant Commander\'s Chain Shoulders<br>\
Lieutenant Commander\'s Chain Helm<br>\
Knight-Captain\'s Chain Legguards<br>\
Knight-Captain\'s Chain Hauberk<br>\
Knight-Lieutenant\'s Chain Greaves<br>\
Knight-Lieutenant\'s Chain Vices<br>\
</span>'+ pursuitBlue, '<span class = "myYellow">\
Champion\'s Pursuance (0/6)<br>\
</span><span class = "myGray">\
Blood Guard\'s Chain Greaves<br>\
Blood Guard\'s Chain Vices<br>\
Legionnaire\'s Chain Hauberk<br>\
Legionnaire\'s Chain Legguards<br>\
Champion\'s Chain Helm<br>\
Champion\'s Chain Shoulders<br>\
</span>'+ pursuitBlue];
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Chain Helm', '<span class = "myBlue">\
Champion\'s Chain Helm'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Head\
</span></td><td align = "right"><span class = "myTable">\
Mail\
</span></td></tr></table>\
337 Armor<br>\
+18 Agility<br>\
+14 Stamina<br>\
+9 Intellect<br>\
Classes: Hunter<br>\
Durability 70/70<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 2%.</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Chain Shoulders', '<span class = "myBlue">\
Champion\'s Chain Shoulders'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Shoulders\
</span></td><td align = "right"><span class = "myTable">\
Mail\
</span></td></tr></table>\
311 Armor<br>\
+18 Agility<br>\
+13 Stamina<br>\
Classes: Hunter<br>\
Durability 70/70<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 1%.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Chain Hauberk', '<span class = "myBlue">\
Legionnaire\'s Chain Hauberk'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Chest\
</span></td><td align = "right"><span class = "myTable">\
Mail\
</span></td></tr></table>\
398 Armor<br>\
+16 Agility<br>\
+13 Stamina<br>\
+6 Intellect<br>\
Classes: Hunter<br>\
Durability 120/120<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 2%.\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Chain Vices', '<span class = "myBlue">\
Blood Guard\'s Chain Vices'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Hands\
</span></td><td align = "right"><span class = "myTable">\
Mail\
</span></td></tr></table>\
242 Armor<br>\
+18 Agility<br>\
+16 Stamina<br>\
Classes: Hunter<br>\
Durability 40/40<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Increases the damage done by your Multi-Shot by 4%.</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Chain Legguards', '<span class = "myBlue">\
Legionnaire\'s Chain Legguards'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Legs\
</span></td><td align = "right"><span class = "myTable">\
Mail\
</span></td></tr></table>\
348 Armor<br>\
+16 Agility<br>\
+13 Stamina<br>\
+6 Intellect<br>\
Classes: Hunter<br>\
Durability 90/90<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 2%.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Chain Greaves', '<span class = "myBlue">\
Blood Guard\'s Chain Greaves'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Feet\
</span></td><td align = "right"><span class = "myTable">\
Mail\
</span></td></tr></table>\
266 Armor<br>\
+20 Agility<br>\
+19 Stamina<br>\
Classes: Hunter<br>\
Durability 60/60<br>\
Requires Level 60<br>\
Requires Rank 7\
<span class = "myGreen">\
</span>\
<p>';
//hunter end
classCounter++;
//mage begin
var regaliaBlue = '<span class = "myGreen">\
(2) Set: Increases damage and healing done by magical spells and effects by up to 23.<br>\
(4) Set: Reduces the cooldown of your Blink spell by 1.5 sec.<br>\
(6) Set: +20 Stamina.\
</span>';
armorSetPvPSuperior.setNameArray[classCounter] = ['<span class = "myYellow">\
Lieutenant Commander\'s Arcanum (0/6)<br>\
</span><span class = "myGray">\
Lieutenant Commander\'s Silk Mantle<br>\
Lieutenant Commander\'s Silk Cowl<br>\
Knight-Captain\'s Silk Legguards<br>\
Knight-Captain\'s Silk Tunic<br>\
Knight-Lieutenant\'s Silk Walkers<br>\
Knight-Lieutenant\'s Silk Handwraps<br>\
</span>'+ regaliaBlue, '<span class = "myYellow">\
Champion\'s Arcanum (0/6)<br>\
</span><span class = "myGray">\
Blood Guard\'s Silk Walkers<br>\
Blood Guard\'s Silk Handwraps<br>\
Legionnaire\'s Silk Tunic<br>\
Legionnaire\'s Silk Legguards<br>\
Champion\'s Silk Cowl<br>\
Champion\'s Silk Mantle<br>\
</span>'+ regaliaBlue];
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Silk Cowl', '<span class = "myBlue">\
Champion\'s Silk Cowl'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Head\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
141 Armor<br>\
+19 Stamina<br>\
+18 Intellect<br>\
+6 Spirit<br>\
Classes: Mage<br>\
Durability 50/50<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike with spells by 1%.<br>\
Equip: Increases damage and healing done by magical spells and effects by up to 21.</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Silk Mantle', '<span class = "myBlue">\
Champion\'s Silk Mantle'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Shoulders\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
135 Armor<br>\
+14 Stamina<br>\
+11 Intellect<br>\
+4 Spirit<br>\
Classes: Mage<br>\
Durability 50/50<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 15.<br>\
Equp: Improves your chance to get a critical strike with spells by 1%.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Silk Tunic', '<span class = "myBlue">\
Legionnaires\'s Silk Tunic'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Chest\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
156 Armor<br>\
+18 Stamina<br>\
+17 Intellect<br>\
+5 Spirit<br>\
Classes: Mage<br>\
Durability 80/80<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike with spells by 1%.<br>\
Equip: Increases damage and healing done by magical spells and effects by up to 21.\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Silk Handwraps', '<span class = "myBlue">\
Blood Guard\'s Silk Handwraps'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Hands\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
98 Armor<br>\
+12 Stamina<br>\
+10 Intellect<br>\
Classes: Mage<br>\
Durability 30/30<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Increases the damage absorbed by your Mana Shield by 285.<br>\
Equip: Increases damage and healing done by magical spells and effects by up to 18.</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Silk Legguards', '<span class = "myBlue">\
Legionnaire\'s Silk Legguards'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Legs\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
144 Armor<br>\
+18 Stamina<br>\
+17 Intellect<br>\
+5 Spirit<br>\
Classes: Mage<br>\
Durability 65/65<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 21.<br>\
Equip: Improves your chance to get a critical strike with spells by 1%.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Silk Walkers', '<span class = "myBlue">\
Blood Guard\'s Silk Walkers'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Feet\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
104 Armor<br>\
+15 Stamina<br>\
+10 Intellect<br>\
Classes: Mage<br>\
Durability 40/40<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 15.<br>\
Equip: Improves your chance to hit with spells by 1%.</span>\
<p>';
//mage end
classCounter++;
//paladin begin
var aegisBlue = '<span class = "myGreen">\
(2) Set: Increases damage and healing done by magical spells and effects by up to 23.<br>\
(4) Set: Reduces the cooldown of your Hammer of Justice by 10 sec.<br>\
(6) Set: +20 Stamina.\
</span>';
armorSetPvPSuperior.setNameArray[classCounter] = ['<span class = "myYellow">\
Lieutenant Commander\'s Redoubt (0/6)<br>\
</span><span class = "myGray">\
Lieutenant Commander\'s Lamellar Shoulders<br>\
Lieutenant Commander\'s Lamellar Headguard<br>\
Knight-Captain\'s Lamellar Leggings<br>\
Knight-Captain\'s Lamellar Breastplate<br>\
Knight-Lieutenant\'s Lamellar Sabatons<br>\
Knight-Lieutenant\'s Lamellar Gauntlets<br>\
</span>'+ aegisBlue, ''];
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Lamellar Headguard', ''];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Head\
</span></td><td align = "right"><span class = "myTable">\
Plate\
</span></td></tr></table>\
598 Armor<br>\
+18 Strength<br>\
+19 Stamina<br>\
+12 Intellect<br>\
Classes: Paladin<br>\
Durability 80/80<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Increases damage and healing done by magical spells and effects by up to 26.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Lamellar Shoulders', ''];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Shoulders\
</span></td><td align = "right"><span class = "myTable">\
Plate\
</span></td></tr></table>\
552 Armor<br>\
+14 Strength<br>\
+14 Stamina<br>\
+8 Intellect<br>\
Classes: Paladin<br>\
Durability 80/80<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 20.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Lamellar Breastplate', ''];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Chest\
</span></td><td align = "right"><span class = "myTable">\
Plate\
</span></td></tr></table>\
706 Armor<br>\
+17 Strength<br>\
+18 Stamina<br>\
+12 Intellect<br>\
Classes: Paladin<br>\
Durability 135/135<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 25.\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Lamellar Gauntlets', ''];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Hands\
</span></td><td align = "right"><span class = "myTable">\
Plate\
</span></td></tr></table>\
429 Armor<br>\
+12 Strength<br>\
+13 Stamina<br>\
Classes: Paladin<br>\
Durability 45/45<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Increases the Holy damage bonus of your Judgement of the Crusader by 10.<br>\
Equip: Improves your chance to get a critical strike by 1%.</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Lamellar Leggings', ''];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Legs\
</span></td><td align = "right"><span class = "myTable">\
Plate\
</span></td></tr></table>\
618 Armor<br>\
+18 Strength<br>\
+17 Stamina<br>\
+12 Intellect<br>\
Classes: Paladin<br>\
Durability 100/100<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 25.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Lamellar Sabatons', ''];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Feet\
</span></td><td align = "right"><span class = "myTable">\
Plate\
</span></td></tr></table>\
472 Armor<br>\
+12 Strength<br>\
+12 Stamina<br>\
+12 Intellect<br>\
Classes: Paladin<br>\
Durability 65/65<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 15.\
</span>\
<p>';
//Paladin end
classCounter++;
//priest begin
var raimentBlue = '<span class = "myGreen">\
(2) Set: Increases damage and healing done by magical spells and effects by up to 23.<br>\
(4) Set: Increases the duration of your Psychic Scream spell by 1 sec.<br>\
(6) Set: +20 Stamina.\
</span>';
armorSetPvPSuperior.setNameArray[classCounter] = ['<span class = "myYellow">\
Lieutenant Commander\'s Investiture (0/6)<br>\
</span><span class = "myGray">\
Lieutenant Commander\'s Satin Mantle<br>\
Lieutenant Commander\'s Satin Hood<br>\
Knight-Captain\'s Satin Legguards<br>\
Knight-Captain\'s Satin Tunic<br>\
Knight-Lieutenant\'s Satin Walkers<br>\
Knight-Lieutenant\'s Satin Handwraps<br>\
</span>'+ raimentBlue, '<span class = "myYellow">\
Champion\'s Investiture (0/6)<br>\
</span><span class = "myGray">\
Blood Guard\'s Satin Walkers<br>\
Blood Guard\'s Satin Handwraps<br>\
Legionnaire\'s Satin Tunic<br>\
Legionnaire\'s Satin Legguards<br>\
Champion\'s Satin Hood<br>\
Champion\'s Satin Mantle<br>\
</span>'+ raimentBlue];
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Satin Hood', '<span class = "myBlue">\
Champion\'s Satin Hood'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Head\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
131 Armor<br>\
+20 Stamina<br>\
+18 Intellect<br>\
Classes: Priest<br>\
Durability 50/50<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 21.<br>\
Equip: Restores 6 mana per 5 sec.\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Satin Mantle', '<span class = "myBlue">\
Champion\'s Satin Mantle'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Shoulders\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
115 Armor<br>\
+14 Stamina<br>\
+12 Intellect<br>\
Classes: Priest<br>\
Durability 50/50<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 16.<br>\
Equip: Restores 6 mana per 5 sec.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Satin Tunic', '<span class = "myBlue">\
Legionnaire\'s Satin Tunic'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Chest\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
156 Armor<br>\
+19 Stamina<br>\
+15 Intellect<br>\
Classes: Priest<br>\
Durability 80/80<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 21.<br>\
Equip: Restores 6 mana per 5 sec.\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Satin Handwraps', '<span class = "myBlue">\
Blood Guard\'s Satin Handwraps'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Hands\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
98 Armor<br>\
+12 Stamina<br>\
+5 Intellect<br>\
Classes: Priest<br>\
Durability 30/30<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Gives you a 50% chance to avoid interruption caused by damage while casting Mind Blast.<br>\
Equip: Increases damage and healing done by magical spells and effects by up to 21.</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Satin Legguards', '<span class = "myBlue">\
Legionnaire\'s Satin Legguards'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Legs\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
144 Armor<br>\
+19 Stamina<br>\
+15 Intellect<br>\
Classes: Priest<br>\
Durability 65/65<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 21.<br>\
Equip: Restores 6 mana per 5 sec.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Satin Walkers', '<span class = "myBlue">\
Blood Guard\'s Satin Walkers'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Feet\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
64 Armor<br>\
+17 Stamina<br>\
+15 Intellect<br>\
Classes: Priest<br>\
Durability 40/40<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 14.</span>\
<p>';
//priest end
classCounter++;
//rogue begin
var vestmentsBlue = '<span class = "myGreen">\
(2) Set: +40 Attack Power.<br>\
(4) Set: Reduces the cooldown of your Gouge ability by 1 sec.<br>\
(6) Set: +20 Stamina.\
</span>';
armorSetPvPSuperior.setNameArray[classCounter] = ['<span class = "myYellow">\
Lieutenant Commander\'s Guard (0/6)<br>\
</span><span class = "myGray">\
Lieutenant Commander\'s Leather Helm<br>\
Lieutenant Commander\'s Leather Shoulders<br>\
Knight-Captain\'s Leather Legguards<br>\
Knight-Captain\'s Leather Chestpiece<br>\
Knight-Lieutenant\'s Leather Walkers<br>\
Knight-Lieutenant\'s Leather Grips<br>\
</span>'+ vestmentsBlue, '<span class = "myYellow">\
Champion\'s Guard (0/6)<br>\
</span><span class = "myGray">\
Blood Guard\'s Leather Walkers<br>\
Blood Guard\'s Leather Grips<br>\
Legionnaire\'s Leather Chestpiece<br>\
Legionnaire\'s Leather Legguards<br>\
Champion\'s Leather Helm<br>\
Champion\'s Leather Shoulders<br>\
</span>'+ vestmentsBlue];
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Leather Helm', '<span class = "myBlue">\
Champion\'s Leather Helm'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Head\
</span></td><td align = "right"><span class = "myTable">\
Leather\
</span></td></tr></table>\
238 Armor<br>\
+23 Stamina<br>\
Classes: Rogue<br>\
Durability 60/60<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 1%.<br>\
Equip: +36 Attack Power.<br>\
Equip: Improves your chance to hit by 1%.</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Leather Shoulders', '<span class = "myBlue">\
Champion\'s Leather Shoulders'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Shoulders\
</span></td><td align = "right"><span class = "myTable">\
Leather\
</span></td></tr></table>\
196 Armor<br>\
+17 Stamina<br>\
Classes: Rogue<br>\
Durability 60/60<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: +22 Attack Power.<br>\
Equip: Improves your chance to get a critical strike by 1%.<br>\
Equip: Improves your chance to hit by 1%.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Leather Chestpiece', '<span class = "myBlue">\
Legionnaire\'s Leather Chestpiece'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Chest\
</span></td><td align = "right"><span class = "myTable">\
Leather\
</span></td></tr></table>\
248 Armor<br>\
+22 Stamina<br>\
Classes: Rogue<br>\
Durability 100/100<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 1%.<br>\
Equip: Improves your chance to hit by 1%.<br>\
Equip: +34 Attack Power.\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Leather Grips', '<span class = "myBlue">\
Blood Guard\'s Leather Grips'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Hands\
</span></td><td align = "right"><span class = "myTable">\
Leather\
</span></td></tr></table>\
155 Armor<br>\
+18 Stamina<br>\
Classes: Rogue<br>\
Durability 35/35<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: +20 Attack Power.<br>\
Equip: Improves your chance to get a critical strike by 1%.</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Leather Legguards', '<span class = "myBlue">\
Legionnaire\'s Leather Legguards'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Legs\
</span></td><td align = "right"><span class = "myTable">\
Leather\
</span></td></tr></table>\
225 Armor<br>\
+22 Stamina<br>\
Classes: Rogue<br>\
Durability 75/75<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 1%.<br>\
Equip: Improves your chance to hit by 1%.<br>\
Equip: +34 Attack Power.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Leather Walkers', '<span class = "myBlue">\
Blood Guard\'s Leather Walkers'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Feet\
</span></td><td align = "right"><span class = "myTable">\
Leather\
</span></td></tr></table>\
166 Armor<br>\
+18 Stamina<br>\
Classes: Rogue<br>\
Durability 50/50<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Increases the duration of your Sprint ability by 3 sec.<br>\
Equip: +28 Attack Power.\
</span>\
<p>';
//Rogue end
classCounter++;
//shaman begin
var earthshakerBlue = '<span class = "myGreen">\
(2) Set: +40 Attack Power.<br>\
(4) Set: Improves your chance to get a critical strike with all Shock spells by 2%.<br>\
(6) Set: +20 Stamina.\
</span>';
armorSetPvPSuperior.setNameArray[classCounter] = ['', '<span class = "myYellow">\
Champion\'s Stormcaller (0/6)<br>\
</span><span class = "myGray">\
Blood Guard\'s Mail Greaves<br>\
Blood Guard\'s Mail Vices<br>\
Legionnaire\'s Mail Hauberk<br>\
Legionnaire\'s Mail Legguards<br>\
Champion\'s Mail Headguard<br>\
Champion\'s Mail Pauldrons<br>\
</span>'+ earthshakerBlue];
t++;
armorSetPvPSuperior.itemNameArray[t] = ['', '<span class = "myBlue">\
Champion\'s Mail Headguard'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Head\
</span></td><td align = "right"><span class = "myTable">\
Mail\
</span></td></tr></table>\
337 Armor<br>\
+6 Strength<br>\
+24 Stamina<br>\
+16 Intellect<br>\
Classes: Shaman<br>\
Durability 70/70<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 1%.<br>\
Equip: Improves your chance to get a critical strike with spells by 1%.\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['', '<span class = "myBlue">\
Champion\'s Mail Pauldrons'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Shoulders\
</span></td><td align = "right"><span class = "myTable">\
Mail\
</span></td></tr></table>\
311 Armor<br>\
+5 Strength<br>\
+16 Stamina<br>\
+10 Intellect<br>\
Classes: Shaman<br>\
Durability 70/70<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 15.<br>\
Equip: Improves your chance to get a critical strike with spells by 1%.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['', '<span class = "myBlue">\
Legionnaire\'s Mail Hauberk'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Chest\
</span></td><td align = "right"><span class = "myTable">\
Mail\
</span></td></tr></table>\
398 Armor<br>\
+17 Strength<br>\
+18 Stamina<br>\
+18 Intellect<br>\
Classes: Shaman<br>\
Durability 120/120<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 1%.\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['', '<span class = "myBlue">\
Blood Guard\'s Mail Vices'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Hands\
</span></td><td align = "right"><span class = "myTable">\
Mail\
</span></td></tr></table>\
242 Armor<br>\
+15 Stamina<br>\
+9 Intellect<br>\
Classes: Shaman<br>\
Durability 40/40<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 13.<br>\
Equip: Improves your chance to get a critical strike with spells by 1%.\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['', '<span class = "myBlue">\
Legionnaire\'s Mail Legguards'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Legs\
</span></td><td align = "right"><span class = "myTable">\
Mail\
</span></td></tr></table>\
348 Armor<br>\
+18 Stamina<br>\
+17 Intellect<br>\
Classes: Shaman<br>\
Durability 90/90<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 21.<br>\
Equip: Improves your chance to get a critical strike with spells by 1%.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['', '<span class = "myBlue">\
Blood Guard\'s Mail Greaves'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Feet\
</span></td><td align = "right"><span class = "myTable">\
Mail\
</span></td></tr></table>\
266 Armor<br>\
+13 Strength<br>\
+14 Stamina<br>\
+12 Intellect<br>\
Classes: Shaman<br>\
Durability 60/60<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Increases the speed of your Ghost Wolf ability by 15%.</span>\
<p>';
//Shaman end
classCounter++;
//warlock begin
var threadsBlue = '<span class = "myGreen">\
(2) Set: Increases damage and healing done by magical spells and effects by up to 23.<br>\
(4) Set: Reduces the casting time of your Immolate spell by 0.2 sec.<br>\
(6) Set: +20 Stamina.\
</span>';
armorSetPvPSuperior.setNameArray[classCounter] = ['<span class = "myYellow">\
Lieutenant Commander\'s Dreadgear (0/6)<br>\
</span><span class = "myGray">\
Lieutenant Commander\'s Dreadweave Spaulders<br>\
Lieutenant Commander\'s Dreadweave Cowl<br>\
Knight-Captain\'s Dreadweave Legguards<br>\
Knight-Captain\'s Dreadweave Tunic<br>\
Knight-Lieutenant\'s Dreadweave Walkers<br>\
Knight-Lieutenant\'s Dreadweave Handwraps<br>\
</span>'+ threadsBlue, '<span class = "myYellow">\
Champion\'s Dreadgear (0/6)<br>\
</span><span class = "myGray">\
Blood Guard\'s Dreadweave Walkers<br>\
Blood Guard\'s Dreadweave Handwraps<br>\
Legionnaire\'s Dreadweave Tunic<br>\
Legionnaire\'s Dreadweave Legguards<br>\
Champion\'s Dreadweave Cowl<br>\
Champion\'s Dreadweave Spaulders<br>\
</span>'+ threadsBlue];
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Dreadweave Cowl', '<span class = "myBlue">\
Champion\'s Dreadweave Cowl'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Head\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
81 Armor<br>\
+21 Stamina<br>\
+18 Intellect<br>\
Classes: Warlock<br>\
Durability 50/50<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 21.<br>\
Equip: Improves your chance to get a critical strike with spells by 1%.\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Dreadweave Spaulders', '<span class = "myBlue">\
Champion\'s Dreadweave Spaulders'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Shoulders\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
75 Armor<br>\
+17 Stamina<br>\
+13 Intellect<br>\
Classes: Warlock<br>\
Durability 50/50<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 12.<br>\
Equip: Improves your chance to get a critical strike with spells by 1%.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Dreadweave Tunic', '<span class = "myBlue">\
Legionnaire\'s Dreadweave Tunic'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Chest\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
96 Armor<br>\
+20 Stamina<br>\
+20 Intellect<br>\
Classes: Warlock<br>\
Durability 80/80<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 25.\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Dreadweave Handwraps', '<span class = "myBlue">\
Blood Guard\'s Dreadweave Handwraps'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Hands\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
58 Armor<br>\
+14 Stamina<br>\
+4 Intellect<br>\
Classes: Warlock<br>\
Durability 30/30<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Increases the damage dealt and health regained by your Death Coil spell by 8%.<br>\
Equip: Increases damage and healing done by magical spells and effects by up to 21.</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Dreadweave Legguards', '<span class = "myBlue">\
Legionnaire\'s Dreadweave Legguards'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Legs\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
84 Armor<br>\
+21 Stamina<br>\
+13 Intellect<br>\
Classes: Warlock<br>\
Durability 65/65<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 28.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Dreadweave Walkers', '<span class = "myBlue">\
Blood Guard\'s Dreadweave Walkers'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Feet\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
64 Armor<br>\
+17 Stamina<br>\
+13 Intellect<br>\
Classes: Warlock<br>\
Durability 40/40<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 18.</span>\
<p>';
//Warlock end
classCounter++;
//warrior begin
var battlegearBlue = '<span class = "myGreen">\
(2) Set: +40 Attack Power.<br>\
(4) Set: Reduces the cooldown of your Intercept ability by 5 sec.<br>\
(6) Set: +20 Stamina.\
</span>';
armorSetPvPSuperior.setNameArray[classCounter] = ['<span class = "myYellow">\
Lieutenant Commander\'s Battlearmor (0/6)<br>\
</span><span class = "myGray">\
Lieutenant Commander\'s Plate Shoulders<br>\
Lieutenant Commander\'s Plate Helm<br>\
Knight-Captain\'s Plate Leggings<br>\
Knight-Captain\'s Plate Hauberk<br>\
Knight-Lieutenant\'s Plate Greaves<br>\
Knight-Lieutenant\'s Plate Gauntlets<br>\
</span>'+ battlegearBlue, '<span class = "myYellow">\
Champion\'s Battlearmor (0/6)<br>\
</span><span class = "myGray">\
Blood Guard\'s Plate Greaves<br>\
Blood Guard\'s Plate Gauntlets<br>\
Legionnaire\'s Plate Hauberk<br>\
Legionnaire\'s Plate Leggings<br>\
Champion\'s Plate Helm<br>\
Champion\'s Plate Shoulders<br>\
</span>'+ battlegearBlue];
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Plate Helm', '<span class = "myBlue">\
Champion\'s Plate Helm'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Head\
</span></td><td align = "right"><span class = "myTable">\
Plate\
</span></td></tr></table>\
598 Armor<br>\
+21 Strength<br>\
+24 Stamina<br>\
Classes: Warrior<br>\
Durability 80/80<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 1%.<br>\
Equip: Improves your chance to hit by 1%.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Plate Shoulders', '<span class = "myBlue">\
Champion\'s Plate Shoulders'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Shoulders\
</span></td><td align = "right"><span class = "myTable">\
Plate\
</span></td></tr></table>\
552 Armor<br>\
+17 Strength<br>\
+18 Stamina<br>\
Classes: Warrior<br>\
Durability 80/80<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 1%.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Plate Hauberk', '<span class = "myBlue">\
Legionnaire\'s Plate Hauberk'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Chest\
</span></td><td align = "right"><span class = "myTable">\
Plate\
</span></td></tr></table>\
706 Armor<br>\
+21 Strength<br>\
+23 Stamina<br>\
Classes: Warrior<br>\
Durability 135/135<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 1%.\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Plate Gauntlets', '<span class = "myBlue">\
Blood Guard\'s Plate Gauntlets'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Hands\
</span></td><td align = "right"><span class = "myTable">\
Plate\
</span></td></tr></table>\
429 Armor<br>\
+17 Strength<br>\
+17 Stamina<br>\
Classes: Warrior<br>\
Durability 45/45<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Hamstring Rage cost reduced by 3.</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Plate Leggings', '<span class = "myBlue">\
Legionnaire\'s Plate Leggings'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Legs\
</span></td><td align = "right"><span class = "myTable">\
Plate\
</span></td></tr></table>\
618 Armor<br>\
+12 Strength<br>\
+17 Stamina<br>\
Classes: Warrior<br>\
Durability 100/100<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 2%.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant Plate Greaves', '<span class = "myBlue">\
Blood Guard\'s Plate Greaves'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Feet\
</span></td><td align = "right"><span class = "myTable">\
Plate\
</span></td></tr></table>\
472 Armor<br>\
+10 Strength<br>\
+9 Agility<br>\
+23 Stamina<br>\
Classes: Warrior<br>\
Durability 65/65<br>\
Requires Level 60<br>\
Requires Rank 7\
<span class = "myGreen">\
</span>\
<p>';
//Warrior end
armorSetsArray[theArmorSetCounter] = armorSetPvPSuperior;
armorSetsValues[theArmorSetCounter] = "pvpsuperior";
theArmorSetCounter++;
| borgotech/Infinity_MaNGOS | sql/Tools & Optional/Websites/I_CSwowd/pvpmini/shared/wow-com/includes-client/armorsets/en/pvpsuperior.js | JavaScript | gpl-2.0 | 49,796 |
<?php
/**
* The Footer widget areas.
*
* @package Pilcrow
* @since Pilcrow 1.0
*/
?>
<?php
/* The footer widget area is triggered if any of the areas
* have widgets. So let's check that first.
*
* If none of the sidebars have widgets, then let's bail early.
*/
if ( ! is_active_sidebar( 'sidebar-4' )
&& ! is_active_sidebar( 'sidebar-5' )
)
return;
// If we get this far, we have widgets. Let's do this.
?>
<div id="footer-widget-area" role="complementary">
<?php if ( is_active_sidebar( 'sidebar-4' ) ) : ?>
<div id="first" class="widget-area">
<ul class="xoxo sidebar-list">
<?php dynamic_sidebar( 'sidebar-4' ); ?>
</ul>
</div><!-- #first .widget-area -->
<?php endif; ?>
<?php if ( is_active_sidebar( 'sidebar-5' ) ) : ?>
<div id="second" class="widget-area">
<ul class="xoxo sidebar-list">
<?php dynamic_sidebar( 'sidebar-5' ); ?>
</ul>
</div><!-- #second .widget-area -->
<?php endif; ?>
</div><!-- #footer-widget-area -->
| mearleycf/boltgun2 | wp-content/themes/pilcrow/sidebar-footer.php | PHP | gpl-2.0 | 1,009 |
/*
Copyright (C) 2009 Roy R. Rankin
This file is part of the libgpsim library of gpsim
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, see
<http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
//
// p12f6xx
//
// This file supports:
// PIC12F629
// PIC12F675
// PIC12F683
//
//Note: unlike most other 12F processors these have 14bit instructions
#include <stdio.h>
#include <iostream>
#include <string>
#include "../config.h"
#include "symbol.h"
#include "stimuli.h"
#include "eeprom.h"
#include "p12f6xx.h"
#include "pic-ioports.h"
#include "packages.h"
//#define DEBUG
#if defined(DEBUG)
#include "../config.h"
#define Dprintf(arg) {printf("%s:%d ",__FILE__,__LINE__); printf arg; }
#else
#define Dprintf(arg) {}
#endif
//========================================================================
//
// Configuration Memory for the 12F6XX devices.
class Config12F6 : public ConfigWord
{
public:
Config12F6(P12F629 *pCpu)
: ConfigWord("CONFIG12F6", 0x3fff, "Configuration Word", pCpu, 0x2007)
{
Dprintf(("Config12F6::Config12F6 %p\n", m_pCpu));
if (m_pCpu)
{
m_pCpu->set_config_word(0x2007, 0x3fff);
}
}
};
// Does not match any of 3 versions in pir.h, pir.cc
// If required by any other porcessors should be moved there
//
class PIR1v12f : public PIR
{
public:
enum {
TMR1IF = 1 << 0,
TMR2IF = 1 << 1, //For 12F683
CMIF = 1 << 3,
ADIF = 1 << 6,
EEIF = 1 << 7
};
//------------------------------------------------------------------------
PIR1v12f(Processor *pCpu, const char *pName, const char *pDesc,INTCON *_intcon, PIE *_pie)
: PIR(pCpu,pName,pDesc,_intcon, _pie,0)
{
valid_bits = TMR1IF | CMIF | ADIF | EEIF;
writable_bits = TMR1IF | CMIF | ADIF | EEIF;
}
virtual void set_tmr1if()
{
put(get() | TMR1IF);
}
virtual void set_tmr2if()
{
put(get() | TMR2IF);
}
virtual void set_cmif()
{
trace.raw(write_trace.get() | value.get());
value.put(value.get() | CMIF);
if( value.get() & pie->value.get() )
setPeripheralInterrupt();
}
virtual void set_c1if()
{
set_cmif();
}
virtual void set_eeif()
{
trace.raw(write_trace.get() | value.get());
value.put(value.get() | EEIF);
if( value.get() & pie->value.get() )
setPeripheralInterrupt();
}
virtual void set_adif()
{
trace.raw(write_trace.get() | value.get());
value.put(value.get() | ADIF);
if( value.get() & pie->value.get() )
setPeripheralInterrupt();
}
};
//========================================================================
void P12F629::create_config_memory()
{
m_configMemory = new ConfigMemory(this,1);
m_configMemory->addConfigWord(0,new Config12F6(this));
};
class MCLRPinMonitor;
bool P12F629::set_config_word(unsigned int address,unsigned int cfg_word)
{
enum {
FOSC0 = 1<<0,
FOSC1 = 1<<1,
FOSC2 = 1<<2,
WDTEN = 1<<3,
PWRTEN = 1<<4,
MCLRE = 1<<5,
BOREN = 1<<6,
CP = 1<<7,
CPD = 1<<8,
BG0 = 1<<12,
BG1 = 1<<13
};
if(address == config_word_address())
{
if ((cfg_word & MCLRE) == MCLRE)
assignMCLRPin(4); // package pin 4
else
unassignMCLRPin();
wdt.initialize((cfg_word & WDTEN) == WDTEN);
if ((cfg_word & (FOSC2 | FOSC1 )) == 0x04) // internal RC OSC
osccal.set_freq(4e6);
return(_14bit_processor::set_config_word(address, cfg_word));
}
return false;
}
P12F629::P12F629(const char *_name, const char *desc)
: _14bit_processor(_name,desc),
intcon_reg(this,"intcon","Interrupt Control"),
comparator(this),
pie1(this,"PIE1", "Peripheral Interrupt Enable"),
t1con(this, "t1con", "TMR1 Control"),
tmr1l(this, "tmr1l", "TMR1 Low"),
tmr1h(this, "tmr1h", "TMR1 High"),
pcon(this, "pcon", "pcon"),
osccal(this, "osccal", "Oscillator Calibration Register", 0xfc)
{
m_ioc = new IOC(this, "ioc", "Interrupt-On-Change GPIO Register");
m_gpio = new PicPortGRegister(this,"gpio","", &intcon_reg, m_ioc,8,0x3f);
m_trisio = new PicTrisRegister(this,"trisio","", m_gpio, false);
m_wpu = new WPU(this, "wpu", "Weak Pull-up Register", m_gpio, 0x37);
pir1 = new PIR1v12f(this,"pir1","Peripheral Interrupt Register",&intcon_reg, &pie1);
tmr0.set_cpu(this, m_gpio, 4, option_reg);
tmr0.start(0);
if(config_modes)
config_modes->valid_bits = ConfigMode::CM_FOSC0 | ConfigMode::CM_FOSC1 |
ConfigMode::CM_FOSC1x | ConfigMode::CM_WDTE | ConfigMode::CM_PWRTE;
}
P12F629::~P12F629()
{
delete_file_registers(0x20, ram_top);
remove_sfr_register(&tmr0);
remove_sfr_register(&tmr1l);
remove_sfr_register(&tmr1h);
remove_sfr_register(&pcon);
remove_sfr_register(&t1con);
remove_sfr_register(&intcon_reg);
remove_sfr_register(&pie1);
remove_sfr_register(&comparator.cmcon);
remove_sfr_register(&comparator.vrcon);
remove_sfr_register(get_eeprom()->get_reg_eedata());
remove_sfr_register(get_eeprom()->get_reg_eeadr());
remove_sfr_register(get_eeprom()->get_reg_eecon1());
remove_sfr_register(get_eeprom()->get_reg_eecon2());
remove_sfr_register(&osccal);
delete_sfr_register(m_gpio);
delete_sfr_register(m_trisio);
delete_sfr_register(m_wpu);
delete_sfr_register(m_ioc);
delete_sfr_register(pir1);
delete e;
}
Processor * P12F629::construct(const char *name)
{
P12F629 *p = new P12F629(name);
p->create(0x5f, 128);
p->create_invalid_registers ();
p->create_symbols();
return p;
}
void P12F629::create_symbols()
{
pic_processor::create_symbols();
addSymbol(Wreg);
}
void P12F629::create_sfr_map()
{
pir_set_def.set_pir1(pir1);
add_sfr_register(indf, 0x00);
alias_file_registers(0x00,0x00,0x80);
add_sfr_register(&tmr0, 0x01, RegisterValue(0xff,0));
add_sfr_register(option_reg, 0x81, RegisterValue(0xff,0));
add_sfr_register(pcl, 0x02, RegisterValue(0,0));
add_sfr_register(status, 0x03, RegisterValue(0x18,0));
add_sfr_register(fsr, 0x04);
alias_file_registers(0x02,0x04,0x80);
add_sfr_register(&tmr1l, 0x0e, RegisterValue(0,0),"tmr1l");
add_sfr_register(&tmr1h, 0x0f, RegisterValue(0,0),"tmr1h");
add_sfr_register(&pcon, 0x8e, RegisterValue(0,0),"pcon");
add_sfr_register(&t1con, 0x10, RegisterValue(0,0));
add_sfr_register(m_gpio, 0x05);
add_sfr_register(m_trisio, 0x85, RegisterValue(0x3f,0));
add_sfr_register(pclath, 0x0a, RegisterValue(0,0));
add_sfr_register(&intcon_reg, 0x0b, RegisterValue(0,0));
alias_file_registers(0x0a,0x0b,0x80);
intcon = &intcon_reg;
intcon_reg.set_pir_set(get_pir_set());
add_sfr_register(pir1, 0x0c, RegisterValue(0,0),"pir1");
tmr1l.tmrh = &tmr1h;
tmr1l.t1con = &t1con;
tmr1l.setInterruptSource(new InterruptSource(pir1, PIR1v1::TMR1IF));
tmr1h.tmrl = &tmr1l;
t1con.tmrl = &tmr1l;
tmr1l.setIOpin(&(*m_gpio)[5]);
tmr1l.setGatepin(&(*m_gpio)[4]);
add_sfr_register(&pie1, 0x8c, RegisterValue(0,0));
if (pir1) {
pir1->set_intcon(&intcon_reg);
pir1->set_pie(&pie1);
}
pie1.setPir(pir1);
// Link the comparator and voltage ref to porta
comparator.initialize(get_pir_set(), NULL,
&(*m_gpio)[0], &(*m_gpio)[1],
NULL, NULL,
&(*m_gpio)[2], NULL);
comparator.cmcon.set_configuration(1, 0, AN0, AN1, AN0, AN1, ZERO);
comparator.cmcon.set_configuration(1, 1, AN0, AN1, AN0, AN1, OUT0);
comparator.cmcon.set_configuration(1, 2, AN0, AN1, AN0, AN1, NO_OUT);
comparator.cmcon.set_configuration(1, 3, AN1, VREF, AN1, VREF, OUT0);
comparator.cmcon.set_configuration(1, 4, AN1, VREF, AN1, VREF, NO_OUT);
comparator.cmcon.set_configuration(1, 5, AN1, VREF, AN0, VREF, OUT0);
comparator.cmcon.set_configuration(1, 6, AN1, VREF, AN0, VREF, NO_OUT);
comparator.cmcon.set_configuration(1, 7, NO_IN, NO_IN, NO_IN, NO_IN, ZERO);
comparator.cmcon.set_configuration(2, 0, NO_IN, NO_IN, NO_IN, NO_IN, ZERO);
comparator.cmcon.set_configuration(2, 1, NO_IN, NO_IN, NO_IN, NO_IN, ZERO);
comparator.cmcon.set_configuration(2, 2, NO_IN, NO_IN, NO_IN, NO_IN, ZERO);
comparator.cmcon.set_configuration(2, 3, NO_IN, NO_IN, NO_IN, NO_IN, ZERO);
comparator.cmcon.set_configuration(2, 4, NO_IN, NO_IN, NO_IN, NO_IN, ZERO);
comparator.cmcon.set_configuration(2, 5, NO_IN, NO_IN, NO_IN, NO_IN, ZERO);
comparator.cmcon.set_configuration(2, 6, NO_IN, NO_IN, NO_IN, NO_IN, ZERO);
comparator.cmcon.set_configuration(2, 7, NO_IN, NO_IN, NO_IN, NO_IN, ZERO);
add_sfr_register(&comparator.cmcon, 0x19, RegisterValue(0,0),"cmcon");
add_sfr_register(&comparator.vrcon, 0x99, RegisterValue(0,0),"cvrcon");
add_sfr_register(get_eeprom()->get_reg_eedata(), 0x9a);
add_sfr_register(get_eeprom()->get_reg_eeadr(), 0x9b);
add_sfr_register(get_eeprom()->get_reg_eecon1(), 0x9c, RegisterValue(0,0));
add_sfr_register(get_eeprom()->get_reg_eecon2(), 0x9d);
add_sfr_register(m_wpu, 0x95, RegisterValue(0x37,0),"wpu");
add_sfr_register(m_ioc, 0x96, RegisterValue(0,0),"ioc");
add_sfr_register(&osccal, 0x90, RegisterValue(0x80,0));
}
//-------------------------------------------------------------------
void P12F629::set_out_of_range_pm(unsigned int address, unsigned int value)
{
if( (address>= 0x2100) && (address < 0x2100 + get_eeprom()->get_rom_size()))
get_eeprom()->change_rom(address - 0x2100, value);
}
void P12F629::create_iopin_map()
{
package = new Package(8);
if(!package)
return;
// Now Create the package and place the I/O pins
package->assign_pin( 7, m_gpio->addPin(new IO_bi_directional_pu("gpio0"),0));
package->assign_pin( 6, m_gpio->addPin(new IO_bi_directional_pu("gpio1"),1));
package->assign_pin( 5, m_gpio->addPin(new IO_bi_directional_pu("gpio2"),2));
package->assign_pin( 4, m_gpio->addPin(new IOPIN("gpio3"),3));
package->assign_pin( 3, m_gpio->addPin(new IO_bi_directional_pu("gpio4"),4));
package->assign_pin( 2, m_gpio->addPin(new IO_bi_directional_pu("gpio5"),5));
package->assign_pin( 1, 0);
package->assign_pin( 8, 0);
}
void P12F629::create(int _ram_top, int eeprom_size)
{
ram_top = _ram_top;
create_iopin_map();
_14bit_processor::create();
e = new EEPROM_PIR(this, pir1);
e->initialize(eeprom_size);
e->set_intcon(&intcon_reg);
set_eeprom(e);
add_file_registers(0x20, ram_top, 0x80);
P12F629::create_sfr_map();
}
//-------------------------------------------------------------------
void P12F629::enter_sleep()
{
tmr1l.sleep();
_14bit_processor::enter_sleep();
}
//-------------------------------------------------------------------
void P12F629::exit_sleep()
{
tmr1l.wake();
_14bit_processor::exit_sleep();
}
//-------------------------------------------------------------------
void P12F629::option_new_bits_6_7(unsigned int bits)
{
Dprintf(("P12F629::option_new_bits_6_7 bits=%x\n", bits));
m_gpio->setIntEdge ( (bits & OPTION_REG::BIT6) == OPTION_REG::BIT6);
m_wpu->set_wpu_pu ( (bits & OPTION_REG::BIT7) != OPTION_REG::BIT7);
}
//========================================================================
//
// Pic 16F675
//
Processor * P12F675::construct(const char *name)
{
P12F675 *p = new P12F675(name);
p->create(0x5f, 128);
p->create_invalid_registers ();
p->create_symbols();
return p;
}
P12F675::P12F675(const char *_name, const char *desc)
: P12F629(_name,desc),
ansel(this,"ansel", "Analog Select"),
adcon0(this,"adcon0", "A2D Control 0"),
adcon1(this,"adcon1", "A2D Control 1"),
adresh(this,"adresh", "A2D Result High"),
adresl(this,"adresl", "A2D Result Low")
{
}
P12F675::~P12F675()
{
remove_sfr_register(&adresl);
remove_sfr_register(&adresh);
remove_sfr_register(&adcon0);
remove_sfr_register(&ansel);
}
void P12F675::create(int ram_top, int eeprom_size)
{
P12F629::create(ram_top, eeprom_size);
create_sfr_map();
}
void P12F675::create_sfr_map()
{
//
// adcon1 is not a register on the 12f675, but it is used internally
// to perform the ADC conversions
//
add_sfr_register(&adresl, 0x9e, RegisterValue(0,0));
add_sfr_register(&adresh, 0x1e, RegisterValue(0,0));
add_sfr_register(&adcon0, 0x1f, RegisterValue(0,0));
add_sfr_register(&ansel, 0x9f, RegisterValue(0x0f,0));
ansel.setAdcon1(&adcon1);
ansel.setAdcon0(&adcon0);
adcon0.setAdresLow(&adresl);
adcon0.setAdres(&adresh);
adcon0.setAdcon1(&adcon1);
adcon0.setIntcon(&intcon_reg);
adcon0.setA2DBits(10);
adcon0.setPir(pir1);
adcon0.setChannel_Mask(3);
adcon0.setChannel_shift(2);
adcon1.setNumberOfChannels(4);
adcon1.setIOPin(0, &(*m_gpio)[0]);
adcon1.setIOPin(1, &(*m_gpio)[1]);
adcon1.setIOPin(2, &(*m_gpio)[2]);
adcon1.setIOPin(3, &(*m_gpio)[4]);
adcon1.setVrefHiConfiguration(2, 1);
/* Channel Configuration done dynamiclly based on ansel */
adcon1.setValidCfgBits(ADCON1::VCFG0 | ADCON1::VCFG1 , 4);
}
//========================================================================
//
// Pic 16F683
//
Processor * P12F683::construct(const char *name)
{
P12F683 *p = new P12F683(name);
p->create(0x7f, 256);
p->create_invalid_registers ();
p->create_symbols();
return p;
}
P12F683::P12F683(const char *_name, const char *desc)
: P12F675(_name,desc),
t2con(this, "t2con", "TMR2 Control"),
pr2(this, "pr2", "TMR2 Period Register"),
tmr2(this, "tmr2", "TMR2 Register"),
ccp1con(this, "ccp1con", "Capture Compare Control"),
ccpr1l(this, "ccpr1l", "Capture Compare 1 Low"),
ccpr1h(this, "ccpr1h", "Capture Compare 1 High"),
wdtcon(this, "wdtcon", "WDT Control", 0x1f),
osccon(this, "osccon", "OSC Control"),
osctune(this, "osctune", "OSC Tune")
{
internal_osc = false;
pir1->valid_bits |= PIR1v12f::TMR2IF;
pir1->writable_bits |= PIR1v12f::TMR2IF;
}
P12F683::~P12F683()
{
delete_file_registers(0x20, 0x7f);
delete_file_registers(0xa0, 0xbf);
remove_sfr_register(&tmr2);
remove_sfr_register(&t2con);
remove_sfr_register(&pr2);
remove_sfr_register(&ccpr1l);
remove_sfr_register(&ccpr1h);
remove_sfr_register(&ccp1con);
remove_sfr_register(&wdtcon);
remove_sfr_register(&osccon);
remove_sfr_register(&osctune);
remove_sfr_register(&comparator.cmcon1);
}
void P12F683::create(int _ram_top, int eeprom_size)
{
P12F629::create(0, eeprom_size);
add_file_registers(0x20, 0x6f, 0);
add_file_registers(0xa0, 0xbf, 0);
add_file_registers(0x70, 0x7f, 0x80);
create_sfr_map();
}
void P12F683::create_sfr_map()
{
P12F675::create_sfr_map();
add_sfr_register(&tmr2, 0x11, RegisterValue(0,0));
add_sfr_register(&t2con, 0x12, RegisterValue(0,0));
add_sfr_register(&pr2, 0x92, RegisterValue(0xff,0));
add_sfr_register(&ccpr1l, 0x13, RegisterValue(0,0));
add_sfr_register(&ccpr1h, 0x14, RegisterValue(0,0));
add_sfr_register(&ccp1con, 0x15, RegisterValue(0,0));
add_sfr_register(&wdtcon, 0x18, RegisterValue(0x08,0),"wdtcon");
add_sfr_register(&osccon, 0x8f, RegisterValue(0,0),"osccon");
remove_sfr_register(&osccal);
add_sfr_register(&osctune, 0x90, RegisterValue(0,0),"osctune");
osccon.set_osctune(&osctune);
osctune.set_osccon(&osccon);
t2con.tmr2 = &tmr2;
tmr2.pir_set = get_pir_set();
tmr2.pr2 = &pr2;
tmr2.t2con = &t2con;
tmr2.add_ccp ( &ccp1con );
pr2.tmr2 = &tmr2;
ccp1con.setCrosslinks(&ccpr1l, pir1, PIR1v1::CCP1IF, &tmr2);
ccp1con.setIOpin(&((*m_gpio)[2]));
ccpr1l.ccprh = &ccpr1h;
ccpr1l.tmrl = &tmr1l;
ccpr1h.ccprl = &ccpr1l;
comparator.cmcon.new_name("cmcon0");
comparator.cmcon.set_tmrl(&tmr1l);
comparator.cmcon1.set_tmrl(&tmr1l);
add_sfr_register(&comparator.cmcon1, 0x1a, RegisterValue(2,0),"cmcon1");
wdt.set_timeout(1./31000.);
}
| WellDone/gpsim | src/src/p12f6xx.cc | C++ | gpl-2.0 | 16,139 |
<?php
/**
* @file quiz.api.php
* Hooks provided by Quiz module.
*
* These entity types provided by Quiz also have entity API hooks. There are a
* few additional Quiz specific hooks defined in this file.
*
* quiz (settings for quiz nodes)
* quiz_result (quiz attempt/result)
* quiz_result_answer (answer to a specific question in a quiz result)
* quiz_question (generic settings for question nodes)
* quiz_question_relationship (relationship from quiz to question)
*
* So for example
*
* hook_quiz_result_presave($quiz_result)
* - Runs before a result is saved to the DB.
* hook_quiz_question_relationship_insert($quiz_question_relationship)
* - Runs when a new question is added to a quiz.
*
* You can also use Rules to build conditional actions based off of these
* events.
*
* Enjoy :)
*/
/**
* Implements hook_quiz_begin().
*
* Fired when a new quiz result is created.
*
* @deprecated
*
* Use hook_quiz_result_insert().
*/
function hook_quiz_begin($quiz, $result_id) {
}
/**
* Implements hook_quiz_finished().
*
* Fired after the last question is submitted.
*
* @deprecated
*
* Use hook_quiz_result_update().
*/
function hook_quiz_finished($quiz, $score, $data) {
}
/**
* Implements hook_quiz_scored().
*
* Fired when a quiz is evaluated.
*
* @deprecated
*
* Use hook_quiz_result_update().
*/
function hook_quiz_scored($quiz, $score, $result_id) {
}
/**
* Implements hook_quiz_question_info().
*
* Define a new question type. The question provider must extend QuizQuestion,
* and the response provider must extend QuizQuestionResponse. See those classes
* for additional implementation details.
*/
function hook_quiz_question_info() {
return array(
'long_answer' => array(
'name' => t('Example question type'),
'description' => t('An example question type that does something.'),
'question provider' => 'ExampleAnswerQuestion',
'response provider' => 'ExampleAnswerResponse',
'module' => 'quiz_question',
),
);
}
/**
* Expose a feedback option to Quiz so that Quiz administrators can choose when
* to show it to Quiz takers.
*
* @return array
* An array of feedback options keyed by machine name.
*/
function hook_quiz_feedback_options() {
return array(
'percentile' => t('Percentile'),
);
}
/**
* Allow modules to alter the quiz feedback options.
*
* @param array $review_options
* An array of review options keyed by a machine name.
*/
function hook_quiz_feedback_options_alter(&$review_options) {
// Change label.
$review_options['quiz_feedback'] = t('General feedback from the Quiz.');
// Disable showing correct answer.
unset($review_options['solution']);
}
/**
* Allow modules to define feedback times.
*
* Feedback times are configurable by Rules.
*
* @return array
* An array of feedback times keyed by machine name.
*/
function hook_quiz_feedback_times() {
return array(
'2_weeks_later' => t('Two weeks after finishing'),
);
}
/**
* Allow modules to alter the feedback times.
*
* @param array $feedback_times
*/
function hook_quiz_feedback_times_alter(&$feedback_times) {
// Change label.
$feedback_times['end'] = t('At the end of a quiz');
// Do not allow question feedback.
unset($feedback_times['question']);
}
/**
* Allow modules to alter the feedback labels.
*
* These are the labels that are displayed to the user, so instead of
* "Answer feedback" you may want to display something more learner-friendly.
*
* @param $feedback_labels
* An array keyed by the feedback option. Default keys are the keys from
* quiz_get_feedback_options().
*/
function hook_quiz_feedback_labels_alter(&$feedback_labels) {
$feedback_labels['solution'] = t('The answer you should have chosen.');
}
/**
* Implements hook_quiz_access().
*
* Control access to Quizzes.
*
* @see quiz_quiz_access() for default access implementations.
*
* Modules may implement Quiz access control hooks to block access to a Quiz or
* display a non-blocking message. Blockers are keyed by a blocker name, and
* must be an array keyed by 'success' and 'message'.
*/
function hook_quiz_access($op, $quiz, $account) {
if ($op == 'take') {
$today = date('l');
if ($today == 'Monday') {
return array(
'monday' => array(
'success' => FALSE,
'message' => t('You cannot take quizzes on Monday.'),
),
);
}
else {
return array(
'not_monday' => array(
'success' => TRUE,
'message' => t('It is not Monday so you may take quizzes.'),
),
);
}
}
}
/**
* Implements hook_quiz_access_alter().
*
* Alter the access blockers for a Quiz.
*
*/
function hook_quiz_access_alter(&$hooks, $op, $quiz, $account) {
if ($op == 'take') {
unset($hooks['monday']);
}
}
| bondjimbond/bcelnapps | sites/all/modules/quiz/quiz.api.php | PHP | gpl-2.0 | 4,847 |
--TEST--
Bug #67215 (php-cgi work with opcache, may be segmentation fault happen)
--INI--
opcache.enable=1
opcache.enable_cli=1
opcache.file_update_protection=0
--SKIPIF--
<?php require_once('skipif.inc'); ?>
--FILE--
<?php
$file_c = __DIR__ . "/bug67215.c.php";
$file_p = __DIR__ . "/bug67215.p.php";
file_put_contents($file_c, "<?php require \"$file_p\"; class c extends p {} ?>");
file_put_contents($file_p, '<?php class p { protected $var = ""; } ?>');
require $file_c;
$a = new c();
require $file_c;
?>
--CLEAN--
<?php
$file_c = __DIR__ . "/bug67215.c.php";
$file_p = __DIR__ . "/bug67215.p.php";
unlink($file_c);
unlink($file_p);
?>
--EXPECTF--
Fatal error: Cannot redeclare class c in %sbug67215.c.php on line %d
| neonatura/crotalus | php/ext/opcache/tests/bug67215.phpt | PHP | gpl-2.0 | 721 |
<?php
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// REPORTE: Formato de salida de Solicitud de Pago
// ORGANISMO: MINISTERIO DEL PODER POPULAR PARA LA INFRAESTRUCTURA.
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
session_start();
header("Pragma: public");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
if(!array_key_exists("la_logusr",$_SESSION))
{
print "<script language=JavaScript>";
print "close();";
print "opener.document.form1.submit();";
print "</script>";
}
//-----------------------------------------------------------------------------------------------------------------------------------
function uf_insert_seguridad($as_titulo)
{
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: uf_insert_seguridad
// Access: private
// Arguments: as_titulo // Título del reporte
// Description: función que guarda la seguridad de quien generó el reporte
// Creado Por: Ing. Yesenia Moreno/ Ing. Luis Lang
// Fecha Creación: 11/03/2007
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
global $io_fun_cxp;
$ls_descripcion="Generó el Reporte ".$as_titulo;
$lb_valido=$io_fun_cxp->uf_load_seguridad_reporte("CXP","sigesp_cxp_p_solicitudpago.php",$ls_descripcion);
return $lb_valido;
}
//-----------------------------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------------------
function uf_print_encabezado_pagina($as_titulo,$as_numsol,$ad_fecregsol,&$io_pdf)
{
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: uf_print_encabezado_pagina
// Access: private
// Arguments: as_titulo // Título del Reporte
// as_numsol // numero de la solicitud
// ad_fecregsol // fecha de registro de la solicitud
// io_pdf // Instancia de objeto pdf
// Description: Función que imprime los encabezados por página
// Creado Por: Ing. Yesenia Moreno / Ing. Luis Lang
// Fecha Creación: 11/03/2007
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$io_encabezado=$io_pdf->openObject();
$io_pdf->saveState();
$io_pdf->setStrokeColor(0,0,0);
$io_pdf->line(20,40,590,40);
$io_pdf->line(480,655,480,700);
$io_pdf->line(480,677,590,677);
$io_pdf->Rectangle(105,655,485,45);
$io_pdf->addJpegFromFile('../../shared/imagebank/banner_minfra.jpg',20,708,570,50); // Agregar Banner.
$io_pdf->addJpegFromFile('../../shared/imagebank/'.$_SESSION["ls_logo"],20,655,$_SESSION["ls_width"],$_SESSION["ls_height"]); // Agregar Logo
$li_tm=$io_pdf->getTextWidth(11,$as_titulo);
$tm=285-($li_tm/2);
$io_pdf->addText($tm,673,12,$as_titulo); // Agregar el título
$io_pdf->addText(485,685,9,"<b>No.</b> ".$as_numsol); // Agregar el título
$io_pdf->addText(485,663,9,"<b>Fecha</b> ".$ad_fecregsol); // Agregar el título
$io_pdf->addText(540,770,7,date("d/m/Y")); // Agregar la Fecha
$io_pdf->addText(546,764,6,date("h:i a")); // Agregar la Hora
// cuadro inferior
$io_pdf->Rectangle(20,60,570,70);
$io_pdf->line(20,73,590,73);
$io_pdf->line(20,117,590,117);
$io_pdf->line(130,60,130,130);
$io_pdf->line(240,60,240,130);
$io_pdf->line(380,60,380,130);
$io_pdf->addText(40,122,7,"ELABORADO POR"); // Agregar el título
$io_pdf->addText(42,63,7,"FIRMA / SELLO"); // Agregar el título
$io_pdf->addText(157,122,7,"VERIFICADO POR"); // Agregar el título
$io_pdf->addText(145,63,7,"FIRMA / SELLO / FECHA"); // Agregar el título
$io_pdf->addText(275,122,7,"AUTORIZADO POR"); // Agregar el título
$io_pdf->addText(257,63,7,"ADMINISTRACIÓN Y FINANZAS"); // Agregar el título
$io_pdf->addText(440,122,7,"CONTRALORIA INTERNA"); // Agregar el título
$io_pdf->addText(445,63,7,"FIRMA / SELLO / FECHA"); // Agregar el título
$io_pdf->restoreState();
$io_pdf->closeObject();
$io_pdf->addObject($io_encabezado,'all');
}// end function uf_print_encabezado_pagina
//-----------------------------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------------------
function uf_print_cabecera($as_numsol,$as_codigo,$as_nombre,$as_denfuefin,$ad_fecemisol,$as_consol,$as_obssol,
$ai_monsol,$as_monto,&$io_pdf)
{
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: uf_print_cabecera
// Access: private
// Arguments: as_numsol // Numero de la Solicitud de Pago
// as_codigo // Codigo del Proveedor / Beneficiario
// as_nombre // Nombre del Proveedor / Beneficiario
// as_denfuefin // Denominacion de la fuente de financiamiento
// ad_fecemisol // Fecha de Emision de la Solicitud
// as_consol // Concepto de la Solicitud
// as_obssol // Observaciones de la Solicitud
// ai_monsol // Monto de la Solicitud
// as_monto // Monto de la Solicitud en letras
// io_pdf // Instancia de objeto pdf
// Description: función que imprime la cabecera
// Creado Por: Ing. Yesenia Moreno / Ing. Luis Lang
// Fecha Creación: 17/05/2007
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$la_data[1]=array('titulo'=>'<b>Beneficiario</b>');
$la_data[2]=array('titulo'=>" ".$as_nombre);
$la_columnas=array('titulo'=>'');
$la_config=array('showHeadings'=>0, // Mostrar encabezados
'fontSize' => 9, // Tamaño de Letras
'titleFontSize' => 12, // Tamaño de Letras de los títulos
'showLines'=>1, // Mostrar Líneas
'shaded'=>2, // Sombra entre líneas
'shadeCol'=>array((249/255),(249/255),(249/255)), // Color de la sombra
'shadeCol2'=>array((249/255),(249/255),(249/255)), // Color de la sombra
'width'=>540, // Ancho de la tabla
'maxWidth'=>540, // Ancho Máximo de la tabla
'xOrientation'=>'center', // Orientación de la tabla
'outerLineThickness'=>0.5,
'innerLineThickness' =>0.5,
'cols'=>array('titulo'=>array('justification'=>'left','width'=>570))); // Justificación y ancho de la columna
$io_pdf->ezTable($la_data,$la_columnas,'',$la_config);
unset($la_data);
unset($la_columnas);
unset($la_config);
$la_data[1]=array('titulo'=>'<b> Concepto: </b>'.$as_consol);
$la_columnas=array('titulo'=>'');
$la_config=array('showHeadings'=>0, // Mostrar encabezados
'fontSize' => 9, // Tamaño de Letras
'titleFontSize' => 12, // Tamaño de Letras de los títulos
'showLines'=>1, // Mostrar Líneas
'shaded'=>2, // Sombra entre líneas
'shadeCol'=>array((249/255),(249/255),(249/255)), // Color de la sombra
'shadeCol2'=>array((249/255),(249/255),(249/255)), // Color de la sombra
'width'=>540, // Ancho de la tabla
'maxWidth'=>540, // Ancho Máximo de la tabla
'xOrientation'=>'center', // Orientación de la tabla
'outerLineThickness'=>0.5,
'innerLineThickness' =>0.5,
'cols'=>array('titulo'=>array('justification'=>'left','width'=>570))); // Justificación y ancho de la columna
$io_pdf->ezTable($la_data,$la_columnas,'',$la_config);
unset($la_data);
unset($la_columnas);
unset($la_config);
$la_data[1]=array('titulo'=>'<b>Monto en Letras: </b>'.$as_monto,);
$la_columnas=array('titulo'=>'');
$la_config=array('showHeadings'=>0, // Mostrar encabezados
'fontSize' => 9, // Tamaño de Letras
'titleFontSize' => 12, // Tamaño de Letras de los títulos
'showLines'=>1, // Mostrar Líneas
'shaded'=>2, // Sombra entre líneas
'shadeCol'=>array((249/255),(249/255),(249/255)), // Color de la sombra
'shadeCol2'=>array((249/255),(249/255),(249/255)), // Color de la sombra
'width'=>540, // Ancho de la tabla
'maxWidth'=>540, // Ancho Máximo de la tabla
'xOrientation'=>'center', // Orientación de la tabla
'outerLineThickness'=>0.5,
'innerLineThickness' =>0.5,
'cols'=>array('titulo'=>array('justification'=>'left','width'=>570))); // Justificación y ancho de la columna
$io_pdf->ezTable($la_data,$la_columnas,'',$la_config);
unset($la_data);
unset($la_columnas);
unset($la_config);
global $ls_tiporeporte;
if($ls_tiporeporte==1)
{
$ls_titulo=" Bs.F.";
}
else
{
$ls_titulo=" Bs.";
}
$la_data[1]=array('titulo'=>'<b>'.$ls_titulo.'</b>','contenido'=>$ai_monsol,);
$la_columnas=array('titulo'=>'',
'contenido'=>'');
$la_config=array('showHeadings'=>0, // Mostrar encabezados
'fontSize' => 9, // Tamaño de Letras
'titleFontSize' => 12, // Tamaño de Letras de los títulos
'showLines'=>1, // Mostrar Líneas
'shaded'=>2, // Sombra entre líneas
'shadeCol'=>array((249/255),(249/255),(249/255)), // Color de la sombra
'shadeCol2'=>array((249/255),(249/255),(249/255)), // Color de la sombra
'width'=>540, // Ancho de la tabla
'maxWidth'=>540, // Ancho Máximo de la tabla
'xOrientation'=>'center', // Orientación de la tabla
'outerLineThickness'=>0.5,
'innerLineThickness' =>0.5,
'cols'=>array('titulo'=>array('justification'=>'right','width'=>400), // Justificación y ancho de la columna
'contenido'=>array('justification'=>'center','width'=>170))); // Justificación y ancho de la columna
$io_pdf->ezTable($la_data,$la_columnas,'',$la_config);
unset($la_data);
unset($la_columnas);
unset($la_config);
}// end function uf_print_cabecera
//-----------------------------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------------------
function uf_print_detalle_recepcion($la_data,$ai_totsubtot,$ai_tottot,$ai_totcar,$ai_totded,&$io_pdf)
{
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: uf_print_detalle
// Access: private
// Arguments: la_data // arreglo de información
// ai_totsubtot // acumulado del subtotal
// ai_tottot // acumulado del total
// ai_totcar // acumulado de los cargos
// ai_totded // acumulado de las deducciones
// io_pdf // Instancia de objeto pdf
// Description: función que imprime el detalle
// Creado Por: Ing. Yesenia Moreno / Ing. Luis Lang
// Fecha Creación: 20/05/2006
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
global $ls_tiporeporte;
if($ls_tiporeporte==1)
{
$ls_titulo=" Bs.F.";
}
else
{
$ls_titulo=" Bs.";
}
$io_pdf->ezSetDy(-2);
$la_datatit[1]=array('numrecdoc'=>'<b>Factura</b>','fecemisol'=>'<b>Fecha</b>','subtotdoc'=>'<b>Monto</b>',
'moncardoc'=>'<b>Cargos</b>','mondeddoc'=>'<b>Deducciones</b>','montotdoc'=>'<b>Total</b>');
$la_columnas=array('numrecdoc'=>'','fecemisol'=>'','subtotdoc'=>'','moncardoc'=>'','mondeddoc'=>'','montotdoc'=>'');
$la_config=array('showHeadings'=>0, // Mostrar encabezados
'fontSize'=>9, // Tamaño de Letras
'titleFontSize'=>9, // Tamaño de Letras de los títulos
'showLines'=>1, // Mostrar Líneas
'shaded'=>2, // Sombra entre líneas
'shadeCol2'=>array(0.9,0.9,0.9), // Color de la sombra
'width'=>540, // Ancho de la tabla
'maxWidth'=>540, // Ancho Máximo de la tabla
'xOrientation'=>'center', // Orientación de la tabla
'outerLineThickness'=>0.5,
'innerLineThickness' =>0.5,
'cols'=>array('numrecdoc'=>array('justification'=>'center','width'=>130), // Justificación y ancho de la columna
'fecemisol'=>array('justification'=>'center','width'=>70), // Justificación y ancho de la columna
'subtotdoc'=>array('justification'=>'center','width'=>92), // Justificación y ancho de la columna
'moncardoc'=>array('justification'=>'center','width'=>92), // Justificación y ancho de la columna
'mondeddoc'=>array('justification'=>'center','width'=>92), // Justificación y ancho de la columna
'montotdoc'=>array('justification'=>'center','width'=>92))); // Justificación y ancho de la columna
$io_pdf->ezTable($la_datatit,$la_columnas,'<b>RECEPCIONES DE DOCUMENTOS</b>',$la_config);
$la_columnas=array('numrecdoc'=>'','fecemisol'=>'','subtotdoc'=>'','moncardoc'=>'','mondeddoc'=>'','montotdoc'=>'');
$la_config=array('showHeadings'=>0, // Mostrar encabezados
'fontSize' => 9, // Tamaño de Letras
'titleFontSize' => 12, // Tamaño de Letras de los títulos
'showLines'=>1, // Mostrar Líneas
'shaded'=>0, // Sombra entre líneas
'width'=>540, // Ancho de la tabla
'maxWidth'=>540, // Ancho Máximo de la tabla
'xOrientation'=>'center', // Orientación de la tabla
'outerLineThickness'=>0.5,
'innerLineThickness' =>0.5,
'cols'=>array('numrecdoc'=>array('justification'=>'center','width'=>130), // Justificación y ancho de la columna
'fecemisol'=>array('justification'=>'left','width'=>70), // Justificación y ancho de la columna
'subtotdoc'=>array('justification'=>'right','width'=>92), // Justificación y ancho de la columna
'moncardoc'=>array('justification'=>'right','width'=>92), // Justificación y ancho de la columna
'mondeddoc'=>array('justification'=>'right','width'=>92), // Justificación y ancho de la columna
'montotdoc'=>array('justification'=>'right','width'=>92))); // Justificación y ancho de la columna
$io_pdf->ezTable($la_data,$la_columnas,'',$la_config);
$la_datatot[1]=array('numrecdoc'=>'<b>Totales '.$ls_titulo.'</b>','subtotdoc'=>$ai_totsubtot,
'moncardoc'=>$ai_totcar,'mondeddoc'=>$ai_totded,'montotdoc'=>$ai_tottot);
$la_columnas=array('numrecdoc'=>'','subtotdoc'=>'','moncardoc'=>'','mondeddoc'=>'','montotdoc'=>'');
$la_config=array('showHeadings'=>0, // Mostrar encabezados
'fontSize' => 9, // Tamaño de Letras
'titleFontSize' => 12, // Tamaño de Letras de los títulos
'showLines'=>1, // Mostrar Líneas
'shaded'=>0, // Sombra entre líneas
'width'=>540, // Ancho de la tabla
'maxWidth'=>540, // Ancho Máximo de la tabla
'xOrientation'=>'center', // Orientación de la tabla
'outerLineThickness'=>0.5,
'innerLineThickness' =>0.5,
'cols'=>array('numrecdoc'=>array('justification'=>'right','width'=>200), // Justificación y ancho de la columna
'subtotdoc'=>array('justification'=>'right','width'=>92), // Justificación y ancho de la columna
'moncardoc'=>array('justification'=>'right','width'=>92), // Justificación y ancho de la columna
'mondeddoc'=>array('justification'=>'right','width'=>92), // Justificación y ancho de la columna
'montotdoc'=>array('justification'=>'right','width'=>92))); // Justificación y ancho de la columna
$io_pdf->ezTable($la_datatot,$la_columnas,'',$la_config);
}// end function uf_print_detalle
//-----------------------------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------------------
function uf_print_detalle_spg($aa_data,$ai_totpre,&$io_pdf)
{
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: uf_print_detalle_cuentas
// Access: private
// Arguments: aa_data // arreglo de información
// ai_totpre // monto total de presupuesto
// io_pdf // Instancia de objeto pdf
// Description: función que imprime el detalle presupuestario
// Creado Por: Ing. Yesenia Moreno / Ing. Luis Lang
// Fecha Creación: 27/04/2006
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$io_pdf->ezSetDy(-5);
global $ls_estmodest;
global $ls_tiporeporte;
if($ls_estmodest==1)
{
$ls_titcuentas="Estructura Presupuestaria";
}
else
{
$ls_titcuentas="Estructura Programatica";
}
if($ls_tiporeporte==1)
{
$ls_titulo=" Bs.F.";
}
else
{
$ls_titulo=" Bs.";
}
$io_pdf->ezSetDy(-2);
$la_datasercon= array(array('estpro'=>"<b>".$ls_titcuentas."</b>",
'spg_cuenta'=>"<b>Cuenta</b>",
'denominacion'=>"<b>Denominación</b>",
'monto'=>"<b>Total ".$ls_titulo."</b>"));
$la_columna=array('estpro'=>'','spg_cuenta'=>'','denominacion'=>'','monto'=>'');
$la_config=array('showHeadings'=>0, // Mostrar encabezados
'fontSize'=>9, // Tamaño de Letras
'titleFontSize'=>9, // Tamaño de Letras de los titulos
'showLines'=>1, // Mostrar Lineas
'shaded'=>2, // Sombra entre lineas
'shadeCol2'=>array(0.9,0.9,0.9), // Sombra entre lineas
'width'=>570, // Ancho de la tabla
'maxWidth'=>570, // Ancho Minimo de la tabla
'xOrientation'=>'center', // Orientacion de la tabla
'outerLineThickness'=>0.5,
'innerLineThickness'=>0.5,
'cols'=>array('estpro'=>array('justification'=>'center','width'=>165),
'spg_cuenta'=>array('justification'=>'center','width'=>84),
'denominacion'=>array('justification'=>'center','width'=>236),
'monto'=>array('justification'=>'center','width'=>85))); // Justificacion y ancho de la columna
$io_pdf->ezTable($la_datasercon,$la_columna,'<b>DETALLE PRESUPUESTARIO</b>',$la_config);
unset($la_datasercon);
unset($la_columna);
unset($la_config);
$la_columnas=array('codestpro'=>'','spg_cuenta'=>'','denominacion'=>'','monto'=>'');
$la_config=array('showHeadings'=>0, // Mostrar encabezados
'fontSize'=>9, // Tamaño de Letras
'titleFontSize'=>9, // Tamaño de Letras de los títulos
'showLines'=>1, // Mostrar Líneas
'shaded'=>0, // Sombra entre líneas
'width'=>570, // Ancho de la tabla
'maxWidth'=>570, // Ancho Máximo de la tabla
'xOrientation'=>'center', // Orientación de la tabla
'outerLineThickness'=>0.5,
'innerLineThickness' =>0.5,
'cols'=>array('codestpro'=>array('justification'=>'center','width'=>165), // Justificación y ancho de la columna
'spg_cuenta'=>array('justification'=>'center','width'=>84), // Justificación y ancho de la columna
'denominacion'=>array('justification'=>'left','width'=>236), // Justificación y ancho de la columna
'monto'=>array('justification'=>'right','width'=>85))); // Justificación y ancho de la columna
$io_pdf->ezTable($aa_data,$la_columnas,'',$la_config);
$la_datatot[1]=array('titulo'=>'<b>Totales '.$ls_titulo.'</b>','totpre'=>$ai_totpre);
$la_columnas=array('titulo'=>'','totpre'=>'');
$la_config=array('showHeadings'=>0, // Mostrar encabezados
'fontSize'=>9, // Tamaño de Letras
'titleFontSize'=>9, // Tamaño de Letras de los títulos
'showLines'=>1, // Mostrar Líneas
'shaded'=>0, // Sombra entre líneas
'width'=>570, // Ancho de la tabla
'maxWidth'=>570, // Ancho Máximo de la tabla
'xOrientation'=>'center', // Orientación de la tabla
'outerLineThickness'=>0.5,
'innerLineThickness' =>0.5,
'cols'=>array('titulo'=>array('justification'=>'right','width'=>485), // Justificación y ancho de la columna
'totpre'=>array('justification'=>'right','width'=>85))); // Justificación y ancho de la columna
$io_pdf->ezTable($la_datatot,$la_columnas,'',$la_config);
}// end function uf_print_detalle
//-----------------------------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------------------
function uf_print_detalle_scg($aa_data,$ai_totdeb,$ai_tothab,&$io_pdf)
{
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: uf_print_detalle_cuentas
// Access: private
// Arguments: aa_data // arreglo de información
// si_totdeb // total monto debe
// si_tothab // total monto haber
// io_pdf // Instancia de objeto pdf
// Description: función que imprime el detalle contable
// Creado Por: Ing. Yesenia Moreno / Ing. Luis Lang
// Fecha Creación: 27/05/2007
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$io_pdf->ezSetDy(-5);
global $ls_tiporeporte;
if($ls_tiporeporte==1)
{
$ls_titulo=" Bs.F.";
}
else
{
$ls_titulo=" Bs.";
}
$io_pdf->ezSetDy(-2);
$la_data[1]=array('sc_cuenta'=>'<b>Cuenta</b>','denominacion'=>'<b>Denominacion</b>','mondeb'=>'<b>Debe</b>','monhab'=>'<b>Haber</b>');
$la_columnas=array('sc_cuenta'=>'','denominacion'=>'','mondeb'=>'','monhab'=>'');
$la_config=array('showHeadings'=>0, // Mostrar encabezados
'fontSize'=>9, // Tamaño de Letras
'titleFontSize'=>9, // Tamaño de Letras de los títulos
'showLines'=>1, // Mostrar Líneas
'shaded'=>2, // Sombra entre lineas
'shadeCol2'=>array(0.9,0.9,0.9), // Sombra entre lineas
'width'=>570, // Ancho de la tabla
'maxWidth'=>570, // Ancho Máximo de la tabla
'xOrientation'=>'center', // Orientación de la tabla
'outerLineThickness'=>0.5,
'innerLineThickness' =>0.5,
'cols'=>array('sc_cuenta'=>array('justification'=>'center','width'=>90), // Justificación y ancho de la columna
'denominacion'=>array('justification'=>'center','width'=>300), // Justificación y ancho de la columna
'mondeb'=>array('justification'=>'center','width'=>90), // Justificación y ancho de la columna
'monhab'=>array('justification'=>'center','width'=>90))); // Justificación y ancho de la columna
$io_pdf->ezTable($la_data,$la_columnas,'<b>DETALLE CONTABLE</b>',$la_config);
unset($la_datatit);
unset($la_columnas);
unset($la_config);
$la_columnas=array('sc_cuenta'=>'','denominacion'=>'','mondeb'=>'','monhab'=>'');
$la_config=array('showHeadings'=>0, // Mostrar encabezados
'fontSize' => 9, // Tamaño de Letras
'titleFontSize' => 12, // Tamaño de Letras de los títulos
'showLines'=>1, // Mostrar Líneas
'shaded'=>0, // Sombra entre lineas
'width'=>540, // Ancho de la tabla
'maxWidth'=>540, // Ancho Máximo de la tabla
'xOrientation'=>'center', // Orientación de la tabla
'outerLineThickness'=>0.5,
'innerLineThickness' =>0.5,
'cols'=>array('sc_cuenta'=>array('justification'=>'center','width'=>90), // Justificación y ancho de la columna
'denominacion'=>array('justification'=>'left','width'=>300), // Justificación y ancho de la columna
'mondeb'=>array('justification'=>'right','width'=>90), // Justificación y ancho de la columna
'monhab'=>array('justification'=>'right','width'=>90))); // Justificación y ancho de la columna
$io_pdf->ezTable($aa_data,$la_columnas,'',$la_config);
$la_datatot[1]=array('titulo'=>'<b>Totales '.$ls_titulo.'</b>','totdeb'=>$ai_totdeb,'tothab'=>$ai_tothab);
$la_columnas=array('titulo'=>'','totdeb'=>'','tothab'=>'');
$la_config=array('showHeadings'=>0, // Mostrar encabezados
'fontSize' => 9, // Tamaño de Letras
'titleFontSize' => 12, // Tamaño de Letras de los títulos
'showLines'=>1, // Mostrar Líneas
'shaded'=>0, // Sombra entre líneas
'width'=>540, // Ancho de la tabla
'maxWidth'=>540, // Ancho Máximo de la tabla
'xOrientation'=>'center', // Orientación de la tabla
'outerLineThickness'=>0.5,
'innerLineThickness' =>0.5,
'cols'=>array('titulo'=>array('justification'=>'right','width'=>390), // Justificación y ancho de la columna
'totdeb'=>array('justification'=>'right','width'=>90), // Justificación y ancho de la columna
'tothab'=>array('justification'=>'right','width'=>90))); // Justificación y ancho de la columna
$io_pdf->ezTable($la_datatot,$la_columnas,'',$la_config);
}// end function uf_print_detalle
//-----------------------------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------------------
function uf_print_total_bsf($ai_monsolaux,&$io_pdf)
{
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: uf_print_detalle_cuentas
// Access: private
// Arguments: ai_monsolaux // Monto Auxiliar en Bs.F.
// io_pdf // Instancia de objeto pdf
// Description: Funcion que imprime el monto total de la solicitud en Bs.F.
// Creado Por: Ing. Luis Anibal Lang
// Fecha Creación: 26/09/2007
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$io_pdf->ezSetDy(-5);
$la_datatot[1]=array('titulo'=>'<b>Total Bs.F.</b>','monto'=>$ai_monsolaux);
$la_columnas=array('titulo'=>'<b>Factura</b>',
'monto'=>'<b>Total</b>');
$la_config=array('showHeadings'=>0, // Mostrar encabezados
'fontSize' => 9, // Tamaño de Letras
'titleFontSize' => 12, // Tamaño de Letras de los títulos
'showLines'=>0, // Mostrar Líneas
'shaded'=>0, // Sombra entre líneas
'width'=>540, // Ancho de la tabla
'maxWidth'=>540, // Ancho Máximo de la tabla
'xOrientation'=>'center', // Orientación de la tabla
'outerLineThickness'=>0.5,
'innerLineThickness' =>0.5,
'cols'=>array('titulo'=>array('justification'=>'right','width'=>480), // Justificación y ancho de la columna
'monto'=>array('justification'=>'right','width'=>90))); // Justificación y ancho de la columna
$io_pdf->ezTable($la_datatot,$la_columnas,'',$la_config);
}// end function uf_print_total_bsf
//-----------------------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------- Instancia de las clases ------------------------------------------------
require_once("../../shared/ezpdf/class.ezpdf.php");
require_once("../../shared/class_folder/class_funciones.php");
$io_funciones=new class_funciones();
require_once("../class_folder/class_funciones_cxp.php");
$io_fun_cxp=new class_funciones_cxp();
$ls_estmodest=$_SESSION["la_empresa"]["estmodest"];
//Instancio a la clase de conversión de numeros a letras.
include("../../shared/class_folder/class_numero_a_letra.php");
$numalet= new class_numero_a_letra();
//imprime numero con los valore por defecto
//cambia a minusculas
$numalet->setMayusculas(1);
//cambia a femenino
$numalet->setGenero(1);
//cambia moneda
$numalet->setMoneda("Bolivares");
//cambia prefijo
$numalet->setPrefijo("***");
//cambia sufijo
$numalet->setSufijo("***");
if($ls_estmodest==1)
{
$ls_titcuentas="Estructura Presupuestaria";
}
else
{
$ls_titcuentas="Estructura Programatica";
}
//---------------------------------------------------- Parámetros del encabezado -----------------------------------------------
$ls_titulo="<b>SOLICITUD DE ORDEN DE PAGO</b>";
//-------------------------------------------------- Parámetros para Filtar el Reporte -----------------------------------------
$ls_numsol=$io_fun_cxp->uf_obtenervalor_get("numsol","");
$ls_tiporeporte=$io_fun_cxp->uf_obtenervalor_get("tiporeporte",0);
global $ls_tiporeporte;
require_once("../../shared/ezpdf/class.ezpdf.php");
if($ls_tiporeporte==1)
{
require_once("sigesp_cxp_class_reportbsf.php");
$io_report=new sigesp_cxp_class_reportbsf();
}
else
{
require_once("sigesp_cxp_class_report.php");
$io_report=new sigesp_cxp_class_report();
}
//--------------------------------------------------------------------------------------------------------------------------------
$lb_valido=uf_insert_seguridad($ls_titulo); // Seguridad de Reporte
if($lb_valido)
{
$lb_valido=$io_report->uf_select_solicitud($ls_numsol); // Cargar el DS con los datos del reporte
if($lb_valido==false) // Existe algún error ó no hay registros
{
print("<script language=JavaScript>");
print(" alert('No hay nada que Reportar');");
print(" close();");
print("</script>");
}
else // Imprimimos el reporte
{
error_reporting(E_ALL);
set_time_limit(1800);
$io_pdf=new Cezpdf('LETTER','portrait'); // Instancia de la clase PDF
$io_pdf->selectFont('../../shared/ezpdf/fonts/Helvetica.afm'); // Seleccionamos el tipo de letra
$io_pdf->ezSetCmMargins(5,5,3.3,3); // Configuración de los margenes en centímetros
$io_pdf->ezStartPageNumbers(570,47,8,'','',1); // Insertar el número de página
$li_totrow=$io_report->DS->getRowCount("numsol");
for($li_i=1;$li_i<=$li_totrow;$li_i++)
{
$ls_numsol=$io_report->DS->data["numsol"][$li_i];
$ls_codpro=$io_report->DS->data["cod_pro"][$li_i];
$ls_cedbene=$io_report->DS->data["ced_bene"][$li_i];
$ls_denfuefin=$io_report->DS->data["denfuefin"][$li_i];
$ls_nombre=$io_report->DS->data["nombre"][$li_i];
$ld_fecemisol=$io_report->DS->data["fecemisol"][$li_i];
$ls_consol=$io_report->DS->data["consol"][$li_i];
$ls_obssol=$io_report->DS->data["obssol"][$li_i];
$li_monsol=$io_report->DS->data["monsol"][$li_i];
$numalet->setNumero($li_monsol);
$ls_monto= $numalet->letra();
$li_monsol=number_format($li_monsol,2,",",".");
$ld_fecemisol=$io_funciones->uf_convertirfecmostrar($ld_fecemisol);
if($ls_codpro!="----------")
{
$ls_codigo=$ls_codpro;
}
else
{
$ls_codigo=$ls_cedbene;
}
/* if($ls_tiporeporte==0)
{
$li_monsolaux=$io_report->DS->data["monsolaux"][$li_i];
$li_monsolaux=number_format($li_monsolaux,2,",",".");
}
*/ uf_print_encabezado_pagina($ls_titulo,$ls_numsol,$ld_fecemisol,&$io_pdf);
uf_print_cabecera($ls_numsol,$ls_codigo,$ls_nombre,$ls_denfuefin,$ld_fecemisol,$ls_consol,$ls_obssol,$li_monsol,$ls_monto,&$io_pdf);
////////////////////////// GRID RECEPCIONES DE DOCUMENTOS //////////////////////////////////////
$io_report->ds_detalle->reset_ds();
$lb_valido=$io_report->uf_select_rec_doc_solicitud($ls_numsol); // Cargar el DS con los datos del reporte
if($lb_valido)
{
$li_totrowdet=$io_report->ds_detalle_rec->getRowCount("numrecdoc");
$la_data="";
$li_totsubtot=0;
$li_tottot=0;
$li_totcar=0;
$li_totded=0;
for($li_s=1;$li_s<=$li_totrowdet;$li_s++)
{
$ls_numrecdoc=trim($io_report->ds_detalle_rec->data["numrecdoc"][$li_s]);
$ld_fecemidoc=trim($io_report->ds_detalle_rec->data["fecemidoc"][$li_s]);
$ls_numdoccomspg=$io_report->ds_detalle_rec->data["numdoccomspg"][$li_s];
$li_mondeddoc=$io_report->ds_detalle_rec->data["mondeddoc"][$li_s];
$li_moncardoc=$io_report->ds_detalle_rec->data["moncardoc"][$li_s];
$li_montotdoc=$io_report->ds_detalle_rec->data["montotdoc"][$li_s];
$li_subtotdoc=($li_montotdoc-$li_moncardoc+$li_mondeddoc);
$li_totsubtot=$li_totsubtot + $li_subtotdoc;
$li_tottot=$li_tottot + $li_montotdoc;
$li_totcar=$li_totcar + $li_moncardoc;
$li_totded=$li_totded + $li_mondeddoc;
$ld_fecemidoc=$io_funciones->uf_convertirfecmostrar($ld_fecemidoc);
$li_mondeddoc=number_format($li_mondeddoc,2,",",".");
$li_moncardoc=number_format($li_moncardoc,2,",",".");
$li_montotdoc=number_format($li_montotdoc,2,",",".");
$li_subtotdoc=number_format($li_subtotdoc,2,",",".");
$la_data[$li_s]=array('numrecdoc'=>$ls_numrecdoc,'fecemisol'=>$ld_fecemidoc,'mondeddoc'=>$li_mondeddoc,
'moncardoc'=>$li_moncardoc,'montotdoc'=>$li_montotdoc,'subtotdoc'=>$li_subtotdoc);
}
$li_totsubtot=number_format($li_totsubtot,2,",",".");
$li_tottot=number_format($li_tottot,2,",",".");
$li_totcar=number_format($li_totcar,2,",",".");
$li_totded=number_format($li_totded,2,",",".");
uf_print_detalle_recepcion($la_data,$li_totsubtot,$li_tottot,$li_totcar,$li_totded,&$io_pdf);
unset($la_data);
////////////////////////// GRID RECEPCIONES DE DOCUMENTOS //////////////////////////////////////
////////////////////////// GRID DETALLE PRESUPUESTARIO //////////////////////////////////////
$lb_valido=$io_report->uf_select_detalle_spg($ls_numsol); // Cargar el DS con los datos del reporte
if($lb_valido)
{
$li_totrowspg=$io_report->ds_detalle_spg->getRowCount("codestpro");
$la_data="";
$li_totpre=0;
for($li_s=1;$li_s<=$li_totrowspg;$li_s++)
{
$ls_codestpro = trim($io_report->ds_detalle_spg->data["codestpro"][$li_s]);
$ls_spgcuenta = trim($io_report->ds_detalle_spg->data["spg_cuenta"][$li_s]);
$ls_denominacion = $io_report->ds_detalle_spg->data["denominacion"][$li_s];
$li_monto = $io_report->ds_detalle_spg->data["monto"][$li_s];
$li_totpre = $li_totpre+$li_monto;
$li_monto=number_format($li_monto,2,",",".");
$io_fun_cxp->uf_formatoprogramatica($ls_codestpro,&$ls_programatica);
$la_data[$li_s]=array('codestpro'=>$ls_programatica,'spg_cuenta'=>$ls_spgcuenta,
'denominacion'=>$ls_denominacion,'monto'=>$li_monto);
}
$li_totpre=number_format($li_totpre,2,",",".");
uf_print_detalle_spg($la_data,$li_totpre,&$io_pdf);
unset($la_data);
}
////////////////////////// GRID DETALLE PRESUPUESTARIO //////////////////////////////////////
////////////////////////// GRID DETALLE CONTABLE //////////////////////////////////////
$lb_valido=$io_report->uf_select_detalle_scg($ls_numsol); // Cargar el DS con los datos del reporte
if($lb_valido)
{
$li_totrowscg=$io_report->ds_detalle_scg->getRowCount("sc_cuenta");
$la_data="";
$li_totdeb=0;
$li_tothab=0;
for($li_s=1;$li_s<=$li_totrowscg;$li_s++)
{
$ls_sccuenta=trim($io_report->ds_detalle_scg->data["sc_cuenta"][$li_s]);
$ls_debhab=trim($io_report->ds_detalle_scg->data["debhab"][$li_s]);
$ls_denominacion=trim($io_report->ds_detalle_scg->data["denominacion"][$li_s]);
$li_monto=$io_report->ds_detalle_scg->data["monto"][$li_s];
if($ls_debhab=="D")
{
$li_montodebe=$li_monto;
$li_montohab="";
$li_totdeb=$li_totdeb+$li_montodebe;
$li_montodebe=number_format($li_montodebe,2,",",".");
}
else
{
$li_montodebe="";
$li_montohab=$li_monto;
$li_tothab=$li_tothab+$li_montohab;
$li_montohab=number_format($li_montohab,2,",",".");
}
$la_data[$li_s]=array('sc_cuenta'=>$ls_sccuenta,'denominacion'=>$ls_denominacion,
'mondeb'=>$li_montodebe,'monhab'=>$li_montohab);
}
$li_totdeb=number_format($li_totdeb,2,",",".");
$li_tothab=number_format($li_tothab,2,",",".");
uf_print_detalle_scg($la_data,$li_totdeb,$li_tothab,&$io_pdf);
unset($la_data);
}
}
}
}
/* if($ls_tiporeporte==0)
{
uf_print_total_bsf($li_monsolaux,&$io_pdf);
}
*/ if($lb_valido) // Si no ocurrio ningún error
{
$io_pdf->ezStopPageNumbers(1,1); // Detenemos la impresión de los números de página
$io_pdf->ezStream(); // Mostramos el reporte
}
else // Si hubo algún error
{
print("<script language=JavaScript>");
print(" alert('Ocurrio un error al generar el reporte. Intente de Nuevo');");
print(" close();");
print("</script>");
}
}
?>
| ArrozAlba/huayra | cxp/reportes/sigesp_cxp_rfs_solicitudes_minfra.php | PHP | gpl-2.0 | 37,861 |
// PR c++/39866
// { dg-options "-std=c++0x" }
struct A {
A& operator=(const A&) = delete; // { dg-bogus "" }
void operator=(int) {} // { dg-message "" }
void operator=(char) {} // { dg-message "" }
};
struct B {};
int main()
{
A a;
a = B(); // { dg-error "no match" }
a = 1.0; // { dg-error "ambiguous" }
}
| ccompiler4pic32/pic32-gcc | gcc/testsuite/g++.dg/cpp0x/defaulted14.C | C++ | gpl-2.0 | 326 |
<?php return array('dependencies' => array(), 'version' => 'a8dca9f7d5fd098db5af94613d2a8ec0'); | tstephen/srp-digital | wp-content/plugins/jetpack/_inc/build/shortcodes/js/recipes.min.asset.php | PHP | gpl-2.0 | 95 |
import sys
if __name__ == "__main__":
if len(sys.argv) < 2:
print "need input file"
sys.exit(1)
fin = open(sys.argv[1], "r")
lines = fin.readlines()
fin.close()
fout = open("bootloader.h", "w")
fout.write("/* File automatically generated by hex2header.py */\n\n")
fout.write("const unsigned int bootloader_data[] = {");
mem = {}
eAddr = 0
addr = 0
for line in lines:
line = line.strip()
if line[0] != ":":
continue
lType = int(line[7:9], 16)
lAddr = int(line[3:7], 16)
dLen = int(line[1:3], 16)
if lType == 2:
eAddr = int(line[9:13], 16) << 8;
continue
if lType == 4:
eAddr = int(line[9:13], 16) << 16;
continue
if lType == 1:
break
if lType == 0:
idx = 0
data = line[9:-2]
dataLen = len(data)
#print "data = ", data
for idx in range(dataLen / 4):
word = int(data[idx*4:(idx*4)+2], 16)
word |= int(data[(idx*4)+2:(idx*4)+4], 16) << 8;
addr = (lAddr + eAddr + idx*2) >> 1
#print hex(addr), "=", hex(word)
mem[addr] = word
output = []
for addr in range(0x800, 0xfff):
if mem.has_key(addr):
output.append(mem[addr])
else:
output.append(0xffff)
output.reverse()
idx = 0
for word in output:
if word != 0xffff:
break
output = output[1:]
output.reverse()
left = len(output) % 8
if left != 0:
output += [0xffff] * (8-left)
while (idx < len(output)):
fout.write("\n ")
for i in range(8):
fout.write("0x%04x, " % output[idx])
idx += 1
fout.write("\n};\n");
fout.close()
| diydrones/alceosd | firmware/bootloader_updater.X/hex2header.py | Python | gpl-2.0 | 1,513 |
/****************************************************************************
**
** Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information (qt-info@nokia.com)
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License versions 2.0 or 3.0 as published by the Free
** Software Foundation and appearing in the file LICENSE.GPL included in
** the packaging of this file. Please review the following information
** to ensure GNU General Public Licensing requirements will be met:
** http://www.fsf.org/licensing/licenses/info/GPLv2.html and
** http://www.gnu.org/copyleft/gpl.html. In addition, as a special
** exception, Nokia gives you certain additional rights. These rights
** are described in the Nokia Qt GPL Exception version 1.3, included in
** the file GPL_EXCEPTION.txt in this package.
**
** Qt for Windows(R) Licensees
** As a special exception, Nokia, as the sole copyright holder for Qt
** Designer, grants users of the Qt/Eclipse Integration plug-in the
** right for the Qt/Eclipse Integration to link to functionality
** provided by Qt Designer and its related libraries.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
**
****************************************************************************/
#include "qfontengine_p.h"
#include "qtextengine_p.h"
#include <qglobal.h>
#include "qt_windows.h"
#include <private/qapplication_p.h>
#include <qlibrary.h>
#include <qpaintdevice.h>
#include <qpainter.h>
#include <qlibrary.h>
#include <limits.h>
#include <qendian.h>
#include <qmath.h>
#include <qthreadstorage.h>
#include <private/qunicodetables_p.h>
#include <qbitmap.h>
#include <private/qpainter_p.h>
#include <private/qpdf_p.h>
#include "qpaintengine.h"
#include "qvarlengtharray.h"
#include <private/qpaintengine_raster_p.h>
#if defined(Q_OS_WINCE)
#include "qguifunctions_wince.h"
#endif
//### mingw needed define
#ifndef TT_PRIM_CSPLINE
#define TT_PRIM_CSPLINE 3
#endif
#ifdef MAKE_TAG
#undef MAKE_TAG
#endif
// GetFontData expects the tags in little endian ;(
#define MAKE_TAG(ch1, ch2, ch3, ch4) (\
(((quint32)(ch4)) << 24) | \
(((quint32)(ch3)) << 16) | \
(((quint32)(ch2)) << 8) | \
((quint32)(ch1)) \
)
typedef BOOL (WINAPI *PtrGetCharWidthI)(HDC, UINT, UINT, LPWORD, LPINT);
// common DC for all fonts
QT_BEGIN_NAMESPACE
class QtHDC
{
HDC _hdc;
public:
QtHDC()
{
HDC displayDC = GetDC(0);
_hdc = CreateCompatibleDC(displayDC);
ReleaseDC(0, displayDC);
}
~QtHDC()
{
if (_hdc)
DeleteDC(_hdc);
}
HDC hdc() const
{
return _hdc;
}
};
#ifndef QT_NO_THREAD
Q_GLOBAL_STATIC(QThreadStorage<QtHDC *>, local_shared_dc)
HDC shared_dc()
{
QtHDC *&hdc = local_shared_dc()->localData();
if (!hdc)
hdc = new QtHDC;
return hdc->hdc();
}
#else
HDC shared_dc()
{
return 0;
}
#endif
static HFONT stock_sysfont = 0;
static PtrGetCharWidthI ptrGetCharWidthI = 0;
static bool resolvedGetCharWidthI = false;
static void resolveGetCharWidthI()
{
if (resolvedGetCharWidthI)
return;
resolvedGetCharWidthI = true;
ptrGetCharWidthI = (PtrGetCharWidthI)QLibrary::resolve(QLatin1String("gdi32"), "GetCharWidthI");
}
// Copy a LOGFONTW struct into a LOGFONTA by converting the face name to an 8 bit value.
// This is needed when calling CreateFontIndirect on non-unicode windowses.
inline static void wa_copy_logfont(LOGFONTW *lfw, LOGFONTA *lfa)
{
lfa->lfHeight = lfw->lfHeight;
lfa->lfWidth = lfw->lfWidth;
lfa->lfEscapement = lfw->lfEscapement;
lfa->lfOrientation = lfw->lfOrientation;
lfa->lfWeight = lfw->lfWeight;
lfa->lfItalic = lfw->lfItalic;
lfa->lfUnderline = lfw->lfUnderline;
lfa->lfCharSet = lfw->lfCharSet;
lfa->lfOutPrecision = lfw->lfOutPrecision;
lfa->lfClipPrecision = lfw->lfClipPrecision;
lfa->lfQuality = lfw->lfQuality;
lfa->lfPitchAndFamily = lfw->lfPitchAndFamily;
QString fam = QString::fromUtf16((const ushort*)lfw->lfFaceName);
memcpy(lfa->lfFaceName, fam.toLocal8Bit().constData(), fam.length() + 1);
}
// defined in qtextengine_win.cpp
typedef void *SCRIPT_CACHE;
typedef HRESULT (WINAPI *fScriptFreeCache)(SCRIPT_CACHE *);
extern fScriptFreeCache ScriptFreeCache;
static inline quint32 getUInt(unsigned char *p)
{
quint32 val;
val = *p++ << 24;
val |= *p++ << 16;
val |= *p++ << 8;
val |= *p;
return val;
}
static inline quint16 getUShort(unsigned char *p)
{
quint16 val;
val = *p++ << 8;
val |= *p;
return val;
}
static inline HFONT systemFont()
{
if (stock_sysfont == 0)
stock_sysfont = (HFONT)GetStockObject(SYSTEM_FONT);
return stock_sysfont;
}
// general font engine
QFixed QFontEngineWin::lineThickness() const
{
if(lineWidth > 0)
return lineWidth;
return QFontEngine::lineThickness();
}
#if defined(Q_OS_WINCE)
static OUTLINETEXTMETRICW *getOutlineTextMetric(HDC hdc)
{
int size;
size = GetOutlineTextMetricsW(hdc, 0, 0);
OUTLINETEXTMETRICW *otm = (OUTLINETEXTMETRICW *)malloc(size);
GetOutlineTextMetricsW(hdc, size, otm);
return otm;
}
#else
static OUTLINETEXTMETRICA *getOutlineTextMetric(HDC hdc)
{
int size;
size = GetOutlineTextMetricsA(hdc, 0, 0);
OUTLINETEXTMETRICA *otm = (OUTLINETEXTMETRICA *)malloc(size);
GetOutlineTextMetricsA(hdc, size, otm);
return otm;
}
#endif
void QFontEngineWin::getCMap()
{
QT_WA({
ttf = (bool)(tm.w.tmPitchAndFamily & TMPF_TRUETYPE);
} , {
ttf = (bool)(tm.a.tmPitchAndFamily & TMPF_TRUETYPE);
});
HDC hdc = shared_dc();
SelectObject(hdc, hfont);
bool symb = false;
if (ttf) {
cmapTable = getSfntTable(qbswap<quint32>(MAKE_TAG('c', 'm', 'a', 'p')));
int size = 0;
cmap = QFontEngine::getCMap(reinterpret_cast<const uchar *>(cmapTable.constData()),
cmapTable.size(), &symb, &size);
}
if (!cmap) {
ttf = false;
symb = false;
}
symbol = symb;
designToDevice = 1;
_faceId.index = 0;
if(cmap) {
#if defined(Q_OS_WINCE)
OUTLINETEXTMETRICW *otm = getOutlineTextMetric(hdc);
#else
OUTLINETEXTMETRICA *otm = getOutlineTextMetric(hdc);
#endif
designToDevice = QFixed((int)otm->otmEMSquare)/int(otm->otmTextMetrics.tmHeight);
unitsPerEm = otm->otmEMSquare;
x_height = (int)otm->otmsXHeight;
loadKerningPairs(designToDevice);
_faceId.filename = (char *)otm + (int)otm->otmpFullName;
lineWidth = otm->otmsUnderscoreSize;
fsType = otm->otmfsType;
free(otm);
} else {
unitsPerEm = tm.w.tmHeight;
}
}
inline unsigned int getChar(const QChar *str, int &i, const int len)
{
unsigned int uc = str[i].unicode();
if (uc >= 0xd800 && uc < 0xdc00 && i < len-1) {
uint low = str[i+1].unicode();
if (low >= 0xdc00 && low < 0xe000) {
uc = (uc - 0xd800)*0x400 + (low - 0xdc00) + 0x10000;
++i;
}
}
return uc;
}
int QFontEngineWin::getGlyphIndexes(const QChar *str, int numChars, QGlyphLayout *glyphs, bool mirrored) const
{
QGlyphLayout *g = glyphs;
if (mirrored) {
if (symbol) {
for (int i = 0; i < numChars; ++i) {
unsigned int uc = getChar(str, i, numChars);
glyphs->glyph = getTrueTypeGlyphIndex(cmap, uc);
if(!glyphs->glyph && uc < 0x100)
glyphs->glyph = getTrueTypeGlyphIndex(cmap, uc + 0xf000);
glyphs++;
}
} else if (ttf) {
for (int i = 0; i < numChars; ++i) {
unsigned int uc = getChar(str, i, numChars);
glyphs->glyph = getTrueTypeGlyphIndex(cmap, QChar::mirroredChar(uc));
glyphs++;
}
} else {
ushort first, last;
QT_WA({
first = tm.w.tmFirstChar;
last = tm.w.tmLastChar;
}, {
first = tm.a.tmFirstChar;
last = tm.a.tmLastChar;
});
for (int i = 0; i < numChars; ++i) {
uint ucs = QChar::mirroredChar(getChar(str, i, numChars));
if (ucs >= first && ucs <= last)
glyphs->glyph = ucs;
else
glyphs->glyph = 0;
glyphs++;
}
}
} else {
if (symbol) {
for (int i = 0; i < numChars; ++i) {
unsigned int uc = getChar(str, i, numChars);
glyphs->glyph = getTrueTypeGlyphIndex(cmap, uc);
if(!glyphs->glyph && uc < 0x100)
glyphs->glyph = getTrueTypeGlyphIndex(cmap, uc + 0xf000);
glyphs++;
}
} else if (ttf) {
for (int i = 0; i < numChars; ++i) {
unsigned int uc = getChar(str, i, numChars);
glyphs->glyph = getTrueTypeGlyphIndex(cmap, uc);
glyphs++;
}
} else {
ushort first, last;
QT_WA({
first = tm.w.tmFirstChar;
last = tm.w.tmLastChar;
}, {
first = tm.a.tmFirstChar;
last = tm.a.tmLastChar;
});
for (int i = 0; i < numChars; ++i) {
uint uc = getChar(str, i, numChars);
if (uc >= first && uc <= last)
glyphs->glyph = uc;
else
glyphs->glyph = 0;
glyphs++;
}
}
}
return glyphs - g;
}
QFontEngineWin::QFontEngineWin(const QString &name, HFONT _hfont, bool stockFont, LOGFONT lf)
{
//qDebug("regular windows font engine created: font='%s', size=%d", name, lf.lfHeight);
_name = name;
cmap = 0;
hfont = _hfont;
logfont = lf;
HDC hdc = shared_dc();
SelectObject(hdc, hfont);
this->stockFont = stockFont;
fontDef.pixelSize = -lf.lfHeight;
lbearing = SHRT_MIN;
rbearing = SHRT_MIN;
synthesized_flags = -1;
lineWidth = -1;
x_height = -1;
BOOL res;
QT_WA({
res = GetTextMetricsW(hdc, &tm.w);
} , {
res = GetTextMetricsA(hdc, &tm.a);
});
fontDef.fixedPitch = !(tm.w.tmPitchAndFamily & TMPF_FIXED_PITCH);
if (!res)
qErrnoWarning("QFontEngineWin: GetTextMetrics failed");
cache_cost = tm.w.tmHeight * tm.w.tmAveCharWidth * 2000;
getCMap();
useTextOutA = false;
#ifndef Q_OS_WINCE
// TextOutW doesn't work for symbol fonts on Windows 95!
// since we're using glyph indices we don't care for ttfs about this!
if (QSysInfo::WindowsVersion == QSysInfo::WV_95 && !ttf &&
(_name == QLatin1String("Marlett") || _name == QLatin1String("Symbol") ||
_name == QLatin1String("Webdings") || _name == QLatin1String("Wingdings")))
useTextOutA = true;
#endif
widthCache = 0;
widthCacheSize = 0;
designAdvances = 0;
designAdvancesSize = 0;
if (!resolvedGetCharWidthI)
resolveGetCharWidthI();
}
QFontEngineWin::~QFontEngineWin()
{
if (designAdvances)
free(designAdvances);
if (widthCache)
free(widthCache);
// make sure we aren't by accident still selected
SelectObject(shared_dc(), systemFont());
if (!stockFont) {
if (!DeleteObject(hfont))
qErrnoWarning("QFontEngineWin: failed to delete non-stock font...");
}
}
HGDIOBJ QFontEngineWin::selectDesignFont(QFixed *overhang) const
{
LOGFONT f = logfont;
f.lfHeight = unitsPerEm;
HFONT designFont;
QT_WA({
designFont = CreateFontIndirectW(&f);
}, {
LOGFONTA fa;
wa_copy_logfont(&f, &fa);
designFont = CreateFontIndirectA(&fa);
});
HGDIOBJ oldFont = SelectObject(shared_dc(), designFont);
if (QSysInfo::WindowsVersion & QSysInfo::WV_DOS_based) {
BOOL res;
QT_WA({
TEXTMETRICW tm;
res = GetTextMetricsW(shared_dc(), &tm);
if (!res)
qErrnoWarning("QFontEngineWin: GetTextMetrics failed");
*overhang = QFixed((int)tm.tmOverhang) / designToDevice;
} , {
TEXTMETRICA tm;
res = GetTextMetricsA(shared_dc(), &tm);
if (!res)
qErrnoWarning("QFontEngineWin: GetTextMetrics failed");
*overhang = QFixed((int)tm.tmOverhang) / designToDevice;
});
} else {
*overhang = 0;
}
return oldFont;
}
bool QFontEngineWin::stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs, QTextEngine::ShaperFlags flags) const
{
if (*nglyphs < len) {
*nglyphs = len;
return false;
}
*nglyphs = getGlyphIndexes(str, len, glyphs, flags & QTextEngine::RightToLeft);
if (flags & QTextEngine::GlyphIndicesOnly)
return true;
#if defined(Q_OS_WINCE)
HDC hdc = shared_dc();
if (flags & QTextEngine::DesignMetrics) {
HGDIOBJ oldFont = 0;
QFixed overhang = 0;
int glyph_pos = 0;
for(register int i = 0; i < len; i++) {
bool surrogate = (str[i].unicode() >= 0xd800 && str[i].unicode() < 0xdc00 && i < len-1
&& str[i+1].unicode() >= 0xdc00 && str[i+1].unicode() < 0xe000);
unsigned int glyph = glyphs[glyph_pos].glyph;
if(int(glyph) >= designAdvancesSize) {
int newSize = (glyph + 256) >> 8 << 8;
designAdvances = (QFixed *)realloc(designAdvances, newSize*sizeof(QFixed));
for(int i = designAdvancesSize; i < newSize; ++i)
designAdvances[i] = -1000000;
designAdvancesSize = newSize;
}
if(designAdvances[glyph] < -999999) {
if(!oldFont)
oldFont = selectDesignFont(&overhang);
SIZE size = {0, 0};
GetTextExtentPoint32W(hdc, (wchar_t *)(str+i), surrogate ? 2 : 1, &size);
designAdvances[glyph] = QFixed((int)size.cx)/designToDevice;
}
glyphs[glyph_pos].advance.x = designAdvances[glyph];
glyphs[glyph_pos].advance.y = 0;
if (surrogate)
++i;
++glyph_pos;
}
if(oldFont)
DeleteObject(SelectObject(hdc, oldFont));
} else {
int overhang = (QSysInfo::WindowsVersion & QSysInfo::WV_DOS_based) ? tm.a.tmOverhang : 0;
int glyph_pos = 0;
HGDIOBJ oldFont = 0;
for(register int i = 0; i < len; i++) {
bool surrogate = (str[i].unicode() >= 0xd800 && str[i].unicode() < 0xdc00 && i < len-1
&& str[i+1].unicode() >= 0xdc00 && str[i+1].unicode() < 0xe000);
unsigned int glyph = glyphs[glyph_pos].glyph;
glyphs[glyph_pos].advance.y = 0;
if (glyph >= widthCacheSize) {
int newSize = (glyph + 256) >> 8 << 8;
widthCache = (unsigned char *)realloc(widthCache, newSize*sizeof(QFixed));
memset(widthCache + widthCacheSize, 0, newSize - widthCacheSize);
widthCacheSize = newSize;
}
glyphs[glyph_pos].advance.x = widthCache[glyph];
// font-width cache failed
if (glyphs[glyph_pos].advance.x == 0) {
SIZE size = {0, 0};
if (!oldFont)
oldFont = SelectObject(hdc, hfont);
GetTextExtentPoint32W(hdc, (wchar_t *)str + i, surrogate ? 2 : 1, &size);
size.cx -= overhang;
glyphs[glyph_pos].advance.x = size.cx;
// if glyph's within cache range, store it for later
if (size.cx > 0 && size.cx < 0x100)
widthCache[glyph] = size.cx;
}
if (surrogate)
++i;
++glyph_pos;
}
if (oldFont)
SelectObject(hdc, oldFont);
}
#else
recalcAdvances(*nglyphs, glyphs, flags);
#endif
return true;
}
void QFontEngineWin::recalcAdvances(int len, QGlyphLayout *glyphs, QTextEngine::ShaperFlags flags) const
{
HGDIOBJ oldFont = 0;
HDC hdc = shared_dc();
if (ttf && (flags & QTextEngine::DesignMetrics)) {
QFixed overhang = 0;
for(int i = 0; i < len; i++) {
unsigned int glyph = glyphs[i].glyph;
if(int(glyph) >= designAdvancesSize) {
int newSize = (glyph + 256) >> 8 << 8;
designAdvances = (QFixed *)realloc(designAdvances, newSize*sizeof(QFixed));
for(int i = designAdvancesSize; i < newSize; ++i)
designAdvances[i] = -1000000;
designAdvancesSize = newSize;
}
if(designAdvances[glyph] < -999999) {
if(!oldFont)
oldFont = selectDesignFont(&overhang);
if (ptrGetCharWidthI) {
int width = 0;
ptrGetCharWidthI(hdc, glyph, 1, 0, &width);
designAdvances[glyph] = QFixed(width) / designToDevice;
} else {
#ifndef Q_OS_WINCE
GLYPHMETRICS gm;
DWORD res = GDI_ERROR;
MAT2 mat;
mat.eM11.value = mat.eM22.value = 1;
mat.eM11.fract = mat.eM22.fract = 0;
mat.eM21.value = mat.eM12.value = 0;
mat.eM21.fract = mat.eM12.fract = 0;
QT_WA({
res = GetGlyphOutlineW(hdc, glyph, GGO_METRICS|GGO_GLYPH_INDEX|GGO_NATIVE, &gm, 0, 0, &mat);
} , {
res = GetGlyphOutlineA(hdc, glyph, GGO_METRICS|GGO_GLYPH_INDEX|GGO_NATIVE, &gm, 0, 0, &mat);
});
if (res != GDI_ERROR) {
designAdvances[glyph] = QFixed(gm.gmCellIncX) / designToDevice;
}
#endif
}
}
glyphs[i].advance.x = designAdvances[glyph];
glyphs[i].advance.y = 0;
}
if(oldFont)
DeleteObject(SelectObject(hdc, oldFont));
} else {
int overhang = (QSysInfo::WindowsVersion & QSysInfo::WV_DOS_based) ? tm.a.tmOverhang : 0;
for(int i = 0; i < len; i++) {
unsigned int glyph = glyphs[i].glyph;
glyphs[i].advance.y = 0;
if (glyph >= widthCacheSize) {
int newSize = (glyph + 256) >> 8 << 8;
widthCache = (unsigned char *)realloc(widthCache, newSize*sizeof(QFixed));
memset(widthCache + widthCacheSize, 0, newSize - widthCacheSize);
widthCacheSize = newSize;
}
glyphs[i].advance.x = widthCache[glyph];
// font-width cache failed
if (glyphs[i].advance.x == 0) {
int width = 0;
if (!oldFont)
oldFont = SelectObject(hdc, hfont);
if (!ttf) {
QChar ch[2] = { ushort(glyph), 0 };
int chrLen = 1;
if (glyph > 0xffff) {
ch[0] = QChar::highSurrogate(glyph);
ch[1] = QChar::lowSurrogate(glyph);
++chrLen;
}
SIZE size = {0, 0};
GetTextExtentPoint32W(hdc, (wchar_t *)ch, chrLen, &size);
width = size.cx;
} else if (ptrGetCharWidthI) {
ptrGetCharWidthI(hdc, glyph, 1, 0, &width);
width -= overhang;
} else {
#ifndef Q_OS_WINCE
GLYPHMETRICS gm;
DWORD res = GDI_ERROR;
MAT2 mat;
mat.eM11.value = mat.eM22.value = 1;
mat.eM11.fract = mat.eM22.fract = 0;
mat.eM21.value = mat.eM12.value = 0;
mat.eM21.fract = mat.eM12.fract = 0;
QT_WA({
res = GetGlyphOutlineW(hdc, glyph, GGO_METRICS|GGO_GLYPH_INDEX, &gm, 0, 0, &mat);
} , {
res = GetGlyphOutlineA(hdc, glyph, GGO_METRICS|GGO_GLYPH_INDEX, &gm, 0, 0, &mat);
});
if (res != GDI_ERROR) {
width = gm.gmCellIncX;
}
#endif
}
glyphs[i].advance.x = width;
// if glyph's within cache range, store it for later
if (width > 0 && width < 0x100)
widthCache[glyph] = width;
}
}
if (oldFont)
SelectObject(hdc, oldFont);
}
}
glyph_metrics_t QFontEngineWin::boundingBox(const QGlyphLayout *glyphs, int numGlyphs)
{
if (numGlyphs == 0)
return glyph_metrics_t();
QFixed w = 0;
const QGlyphLayout *end = glyphs + numGlyphs;
while(end > glyphs) {
--end;
w += end->effectiveAdvance();
}
return glyph_metrics_t(0, -tm.w.tmAscent, w, tm.w.tmHeight, w, 0);
}
#ifndef Q_OS_WINCE
typedef HRESULT (WINAPI *pGetCharABCWidthsFloat)(HDC, UINT, UINT, LPABCFLOAT);
static pGetCharABCWidthsFloat qt_GetCharABCWidthsFloat = 0;
#endif
glyph_metrics_t QFontEngineWin::boundingBox(glyph_t glyph)
{
#ifndef Q_OS_WINCE
GLYPHMETRICS gm;
HDC hdc = shared_dc();
SelectObject(hdc, hfont);
if(!ttf) {
SIZE s = {0, 0};
WCHAR ch = glyph;
int width;
int overhang = 0;
static bool resolved = false;
if (!resolved) {
QLibrary lib(QLatin1String("gdi32"));
qt_GetCharABCWidthsFloat = (pGetCharABCWidthsFloat) lib.resolve("GetCharABCWidthsFloatW");
resolved = true;
}
if (QT_WA_INLINE(true, false) && qt_GetCharABCWidthsFloat) {
ABCFLOAT abc;
qt_GetCharABCWidthsFloat(hdc, ch, ch, &abc);
width = qRound(abc.abcfB);
} else {
GetTextExtentPoint32W(hdc, &ch, 1, &s);
overhang = (QSysInfo::WindowsVersion & QSysInfo::WV_DOS_based) ? tm.a.tmOverhang : 0;
width = s.cx;
}
return glyph_metrics_t(0, -tm.a.tmAscent, width, tm.a.tmHeight, width-overhang, 0);
} else {
DWORD res = 0;
MAT2 mat;
mat.eM11.value = mat.eM22.value = 1;
mat.eM11.fract = mat.eM22.fract = 0;
mat.eM21.value = mat.eM12.value = 0;
mat.eM21.fract = mat.eM12.fract = 0;
QT_WA({
res = GetGlyphOutlineW(hdc, glyph, GGO_METRICS|GGO_GLYPH_INDEX, &gm, 0, 0, &mat);
} , {
res = GetGlyphOutlineA(hdc, glyph, GGO_METRICS|GGO_GLYPH_INDEX, &gm, 0, 0, &mat);
});
if (res != GDI_ERROR)
return glyph_metrics_t(gm.gmptGlyphOrigin.x, -gm.gmptGlyphOrigin.y,
(int)gm.gmBlackBoxX, (int)gm.gmBlackBoxY, gm.gmCellIncX, gm.gmCellIncY);
}
return glyph_metrics_t();
#else
SIZE s = {0, 0};
WCHAR ch = glyph;
HDC hdc = shared_dc();
BOOL res = GetTextExtentPoint32W(hdc, &ch, 1, &s);
Q_UNUSED(res);
return glyph_metrics_t(0, -tm.a.tmAscent, s.cx, tm.a.tmHeight, s.cx, 0);
#endif
}
QFixed QFontEngineWin::ascent() const
{
return tm.w.tmAscent;
}
QFixed QFontEngineWin::descent() const
{
return tm.w.tmDescent;
}
QFixed QFontEngineWin::leading() const
{
return tm.w.tmExternalLeading;
}
QFixed QFontEngineWin::xHeight() const
{
if(x_height >= 0)
return x_height;
return QFontEngine::xHeight();
}
QFixed QFontEngineWin::averageCharWidth() const
{
return tm.w.tmAveCharWidth;
}
qreal QFontEngineWin::maxCharWidth() const
{
return tm.w.tmMaxCharWidth;
}
enum { max_font_count = 256 };
static const ushort char_table[] = {
40,
67,
70,
75,
86,
88,
89,
91,
102,
114,
124,
127,
205,
645,
884,
922,
1070,
12386,
0
};
static const int char_table_entries = sizeof(char_table)/sizeof(ushort);
qreal QFontEngineWin::minLeftBearing() const
{
if (lbearing == SHRT_MIN)
minRightBearing(); // calculates both
return lbearing;
}
qreal QFontEngineWin::minRightBearing() const
{
#ifdef Q_OS_WINCE
if (rbearing == SHRT_MIN) {
int ml = 0;
int mr = 0;
HDC hdc = shared_dc();
SelectObject(hdc, hfont);
if (ttf) {
ABC *abc = 0;
int n = QT_WA_INLINE(tm.w.tmLastChar - tm.w.tmFirstChar, tm.a.tmLastChar - tm.a.tmFirstChar);
if (n <= max_font_count) {
abc = new ABC[n+1];
GetCharABCWidths(hdc, tm.w.tmFirstChar, tm.w.tmLastChar, abc);
} else {
abc = new ABC[char_table_entries+1];
for(int i = 0; i < char_table_entries; i++)
GetCharABCWidths(hdc, char_table[i], char_table[i], abc+i);
n = char_table_entries;
}
ml = abc[0].abcA;
mr = abc[0].abcC;
for (int i = 1; i < n; i++) {
if (abc[i].abcA + abc[i].abcB + abc[i].abcC != 0) {
ml = qMin(ml,abc[i].abcA);
mr = qMin(mr,abc[i].abcC);
}
}
delete [] abc;
} else {
ml = 0;
mr = -tm.a.tmOverhang;
}
lbearing = ml;
rbearing = mr;
}
return rbearing;
#else
if (rbearing == SHRT_MIN) {
int ml = 0;
int mr = 0;
HDC hdc = shared_dc();
SelectObject(hdc, hfont);
if (ttf) {
ABC *abc = 0;
int n = QT_WA_INLINE(tm.w.tmLastChar - tm.w.tmFirstChar, tm.a.tmLastChar - tm.a.tmFirstChar);
if (n <= max_font_count) {
abc = new ABC[n+1];
QT_WA({
GetCharABCWidths(hdc, tm.w.tmFirstChar, tm.w.tmLastChar, abc);
}, {
GetCharABCWidthsA(hdc,tm.a.tmFirstChar,tm.a.tmLastChar,abc);
});
} else {
abc = new ABC[char_table_entries+1];
QT_WA({
for(int i = 0; i < char_table_entries; i++)
GetCharABCWidths(hdc, char_table[i], char_table[i], abc+i);
}, {
for(int i = 0; i < char_table_entries; i++) {
QByteArray w = QString(QChar(char_table[i])).toLocal8Bit();
if (w.length() == 1) {
uint ch8 = (uchar)w[0];
GetCharABCWidthsA(hdc, ch8, ch8, abc+i);
}
}
});
n = char_table_entries;
}
ml = abc[0].abcA;
mr = abc[0].abcC;
for (int i = 1; i < n; i++) {
if (abc[i].abcA + abc[i].abcB + abc[i].abcC != 0) {
ml = qMin(ml,abc[i].abcA);
mr = qMin(mr,abc[i].abcC);
}
}
delete [] abc;
} else {
QT_WA({
ABCFLOAT *abc = 0;
int n = tm.w.tmLastChar - tm.w.tmFirstChar+1;
if (n <= max_font_count) {
abc = new ABCFLOAT[n];
GetCharABCWidthsFloat(hdc, tm.w.tmFirstChar, tm.w.tmLastChar, abc);
} else {
abc = new ABCFLOAT[char_table_entries];
for(int i = 0; i < char_table_entries; i++)
GetCharABCWidthsFloat(hdc, char_table[i], char_table[i], abc+i);
n = char_table_entries;
}
float fml = abc[0].abcfA;
float fmr = abc[0].abcfC;
for (int i=1; i<n; i++) {
if (abc[i].abcfA + abc[i].abcfB + abc[i].abcfC != 0) {
fml = qMin(fml,abc[i].abcfA);
fmr = qMin(fmr,abc[i].abcfC);
}
}
ml = int(fml-0.9999);
mr = int(fmr-0.9999);
delete [] abc;
} , {
ml = 0;
mr = -tm.a.tmOverhang;
});
}
lbearing = ml;
rbearing = mr;
}
return rbearing;
#endif
}
const char *QFontEngineWin::name() const
{
return 0;
}
bool QFontEngineWin::canRender(const QChar *string, int len)
{
if (symbol) {
for (int i = 0; i < len; ++i) {
unsigned int uc = getChar(string, i, len);
if (getTrueTypeGlyphIndex(cmap, uc) == 0) {
if (uc < 0x100) {
if (getTrueTypeGlyphIndex(cmap, uc + 0xf000) == 0)
return false;
} else {
return false;
}
}
}
} else if (ttf) {
for (int i = 0; i < len; ++i) {
unsigned int uc = getChar(string, i, len);
if (getTrueTypeGlyphIndex(cmap, uc) == 0)
return false;
}
} else {
QT_WA({
while(len--) {
if (tm.w.tmFirstChar > string->unicode() || tm.w.tmLastChar < string->unicode())
return false;
}
}, {
while(len--) {
if (tm.a.tmFirstChar > string->unicode() || tm.a.tmLastChar < string->unicode())
return false;
}
});
}
return true;
}
QFontEngine::Type QFontEngineWin::type() const
{
return QFontEngine::Win;
}
static inline double qt_fixed_to_double(const FIXED &p) {
return ((p.value << 16) + p.fract) / 65536.0;
}
static inline QPointF qt_to_qpointf(const POINTFX &pt, qreal scale) {
return QPointF(qt_fixed_to_double(pt.x) * scale, -qt_fixed_to_double(pt.y) * scale);
}
#ifndef GGO_UNHINTED
#define GGO_UNHINTED 0x0100
#endif
static void addGlyphToPath(glyph_t glyph, const QFixedPoint &position, HDC hdc,
QPainterPath *path, bool ttf, glyph_metrics_t *metric = 0, qreal scale = 1)
{
#if defined(Q_OS_WINCE)
Q_UNUSED(glyph);
Q_UNUSED(hdc);
#endif
MAT2 mat;
mat.eM11.value = mat.eM22.value = 1;
mat.eM11.fract = mat.eM22.fract = 0;
mat.eM21.value = mat.eM12.value = 0;
mat.eM21.fract = mat.eM12.fract = 0;
uint glyphFormat = GGO_NATIVE;
if (ttf)
glyphFormat |= GGO_GLYPH_INDEX;
GLYPHMETRICS gMetric;
memset(&gMetric, 0, sizeof(GLYPHMETRICS));
int bufferSize = GDI_ERROR;
#if !defined(Q_OS_WINCE)
QT_WA( {
bufferSize = GetGlyphOutlineW(hdc, glyph, glyphFormat, &gMetric, 0, 0, &mat);
}, {
bufferSize = GetGlyphOutlineA(hdc, glyph, glyphFormat, &gMetric, 0, 0, &mat);
});
#endif
if ((DWORD)bufferSize == GDI_ERROR) {
qErrnoWarning("QFontEngineWin::addOutlineToPath: GetGlyphOutline(1) failed");
return;
}
void *dataBuffer = new char[bufferSize];
DWORD ret = GDI_ERROR;
#if !defined(Q_OS_WINCE)
QT_WA( {
ret = GetGlyphOutlineW(hdc, glyph, glyphFormat, &gMetric, bufferSize,
dataBuffer, &mat);
}, {
ret = GetGlyphOutlineA(hdc, glyph, glyphFormat, &gMetric, bufferSize,
dataBuffer, &mat);
} );
#endif
if (ret == GDI_ERROR) {
qErrnoWarning("QFontEngineWin::addOutlineToPath: GetGlyphOutline(2) failed");
delete [](char *)dataBuffer;
return;
}
if(metric) {
// #### obey scale
*metric = glyph_metrics_t(gMetric.gmptGlyphOrigin.x, -gMetric.gmptGlyphOrigin.y,
(int)gMetric.gmBlackBoxX, (int)gMetric.gmBlackBoxY,
gMetric.gmCellIncX, gMetric.gmCellIncY);
}
int offset = 0;
int headerOffset = 0;
TTPOLYGONHEADER *ttph = 0;
QPointF oset = position.toPointF();
while (headerOffset < bufferSize) {
ttph = (TTPOLYGONHEADER*)((char *)dataBuffer + headerOffset);
QPointF lastPoint(qt_to_qpointf(ttph->pfxStart, scale));
path->moveTo(lastPoint + oset);
offset += sizeof(TTPOLYGONHEADER);
TTPOLYCURVE *curve;
while (offset<int(headerOffset + ttph->cb)) {
curve = (TTPOLYCURVE*)((char*)(dataBuffer) + offset);
switch (curve->wType) {
case TT_PRIM_LINE: {
for (int i=0; i<curve->cpfx; ++i) {
QPointF p = qt_to_qpointf(curve->apfx[i], scale) + oset;
path->lineTo(p);
}
break;
}
case TT_PRIM_QSPLINE: {
const QPainterPath::Element &elm = path->elementAt(path->elementCount()-1);
QPointF prev(elm.x, elm.y);
QPointF endPoint;
for (int i=0; i<curve->cpfx - 1; ++i) {
QPointF p1 = qt_to_qpointf(curve->apfx[i], scale) + oset;
QPointF p2 = qt_to_qpointf(curve->apfx[i+1], scale) + oset;
if (i < curve->cpfx - 2) {
endPoint = QPointF((p1.x() + p2.x()) / 2, (p1.y() + p2.y()) / 2);
} else {
endPoint = p2;
}
path->quadTo(p1, endPoint);
prev = endPoint;
}
break;
}
case TT_PRIM_CSPLINE: {
for (int i=0; i<curve->cpfx; ) {
QPointF p2 = qt_to_qpointf(curve->apfx[i++], scale) + oset;
QPointF p3 = qt_to_qpointf(curve->apfx[i++], scale) + oset;
QPointF p4 = qt_to_qpointf(curve->apfx[i++], scale) + oset;
path->cubicTo(p2, p3, p4);
}
break;
}
default:
qWarning("QFontEngineWin::addOutlineToPath, unhandled switch case");
}
offset += sizeof(TTPOLYCURVE) + (curve->cpfx-1) * sizeof(POINTFX);
}
path->closeSubpath();
headerOffset += ttph->cb;
}
delete [] (char*)dataBuffer;
}
void QFontEngineWin::addGlyphsToPath(glyph_t *glyphs, QFixedPoint *positions, int nglyphs,
QPainterPath *path, QTextItem::RenderFlags)
{
LOGFONT lf = logfont;
// The sign must be negative here to make sure we match against character height instead of
// hinted cell height. This ensures that we get linear matching, and we need this for
// paths since we later on apply a scaling transform to the glyph outline to get the
// font at the correct pixel size.
lf.lfHeight = -unitsPerEm;
lf.lfWidth = 0;
HFONT hf;
QT_WA({
hf = CreateFontIndirectW(&lf);
}, {
LOGFONTA lfa;
wa_copy_logfont(&lf, &lfa);
hf = CreateFontIndirectA(&lfa);
});
HDC hdc = shared_dc();
HGDIOBJ oldfont = SelectObject(hdc, hf);
for(int i = 0; i < nglyphs; ++i)
addGlyphToPath(glyphs[i], positions[i], hdc, path, ttf, /*metric*/0, qreal(fontDef.pixelSize) / unitsPerEm);
DeleteObject(SelectObject(hdc, oldfont));
}
void QFontEngineWin::addOutlineToPath(qreal x, qreal y, const QGlyphLayout *glyphs, int numGlyphs,
QPainterPath *path, QTextItem::RenderFlags flags)
{
#if !defined(Q_OS_WINCE)
if(tm.w.tmPitchAndFamily & (TMPF_TRUETYPE)) {
QFontEngine::addOutlineToPath(x, y, glyphs, numGlyphs, path, flags);
return;
}
#endif
QFontEngine::addBitmapFontToPath(x, y, glyphs, numGlyphs, path, flags);
}
QFontEngine::FaceId QFontEngineWin::faceId() const
{
return _faceId;
}
QT_BEGIN_INCLUDE_NAMESPACE
#include <qdebug.h>
QT_END_INCLUDE_NAMESPACE
int QFontEngineWin::synthesized() const
{
if(synthesized_flags == -1) {
synthesized_flags = 0;
if(ttf) {
const DWORD HEAD = MAKE_TAG('h', 'e', 'a', 'd');
HDC hdc = shared_dc();
SelectObject(hdc, hfont);
uchar data[4];
GetFontData(hdc, HEAD, 44, &data, 4);
USHORT macStyle = getUShort(data);
if (tm.w.tmItalic && !(macStyle & 2))
synthesized_flags = SynthesizedItalic;
if (fontDef.stretch != 100 && ttf)
synthesized_flags |= SynthesizedStretch;
if (tm.w.tmWeight >= 500 && !(macStyle & 1))
synthesized_flags |= SynthesizedBold;
//qDebug() << "font is" << _name <<
// "it=" << (macStyle & 2) << fontDef.style << "flags=" << synthesized_flags;
}
}
return synthesized_flags;
}
QFixed QFontEngineWin::emSquareSize() const
{
return unitsPerEm;
}
QFontEngine::Properties QFontEngineWin::properties() const
{
LOGFONT lf = logfont;
lf.lfHeight = unitsPerEm;
HFONT hf;
QT_WA({
hf = CreateFontIndirectW(&lf);
}, {
LOGFONTA lfa;
wa_copy_logfont(&lf, &lfa);
hf = CreateFontIndirectA(&lfa);
});
HDC hdc = shared_dc();
HGDIOBJ oldfont = SelectObject(hdc, hf);
#if defined(Q_OS_WINCE)
OUTLINETEXTMETRICW *otm = getOutlineTextMetric(hdc);
#else
OUTLINETEXTMETRICA *otm = getOutlineTextMetric(hdc);
#endif
Properties p;
p.emSquare = unitsPerEm;
p.italicAngle = otm->otmItalicAngle;
p.postscriptName = (char *)otm + (int)otm->otmpFamilyName;
p.postscriptName += (char *)otm + (int)otm->otmpStyleName;
#ifndef QT_NO_PRINTER
p.postscriptName = QPdf::stripSpecialCharacters(p.postscriptName);
#endif
p.boundingBox = QRectF(otm->otmrcFontBox.left, -otm->otmrcFontBox.top,
otm->otmrcFontBox.right - otm->otmrcFontBox.left,
otm->otmrcFontBox.top - otm->otmrcFontBox.bottom);
p.ascent = otm->otmAscent;
p.descent = -otm->otmDescent;
p.leading = (int)otm->otmLineGap;
p.capHeight = 0;
p.lineWidth = otm->otmsUnderscoreSize;
free(otm);
DeleteObject(SelectObject(hdc, oldfont));
return p;
}
void QFontEngineWin::getUnscaledGlyph(glyph_t glyph, QPainterPath *path, glyph_metrics_t *metrics)
{
LOGFONT lf = logfont;
lf.lfHeight = unitsPerEm;
int flags = synthesized();
if(flags & SynthesizedItalic)
lf.lfItalic = false;
lf.lfWidth = 0;
HFONT hf;
QT_WA({
hf = CreateFontIndirectW(&lf);
}, {
LOGFONTA lfa;
wa_copy_logfont(&lf, &lfa);
hf = CreateFontIndirectA(&lfa);
});
HDC hdc = shared_dc();
HGDIOBJ oldfont = SelectObject(hdc, hf);
QFixedPoint p;
p.x = 0;
p.y = 0;
addGlyphToPath(glyph, p, hdc, path, ttf, metrics);
DeleteObject(SelectObject(hdc, oldfont));
}
bool QFontEngineWin::getSfntTableData(uint tag, uchar *buffer, uint *length) const
{
if (!ttf)
return false;
HDC hdc = shared_dc();
SelectObject(hdc, hfont);
DWORD t = qbswap<quint32>(tag);
*length = GetFontData(hdc, t, 0, buffer, *length);
return *length != GDI_ERROR;
}
#if !defined(CLEARTYPE_QUALITY)
# define CLEARTYPE_QUALITY 5
#endif
QImage QFontEngineWin::alphaMapForGlyph(glyph_t glyph)
{
glyph_metrics_t gm = boundingBox(glyph);
int glyph_x = qFloor(gm.x.toReal());
int glyph_y = qFloor(gm.y.toReal());
int glyph_width = qCeil((gm.x + gm.width).toReal()) - glyph_x;
int glyph_height = qCeil((gm.y + gm.height).toReal()) - glyph_y;
if (glyph_width + glyph_x <= 0 || glyph_height <= 0)
return QImage();
QImage im(glyph_width, glyph_height, QImage::Format_ARGB32_Premultiplied);
im.fill(0);
QPainter p(&im);
HFONT oldHFont = hfont;
if (QSysInfo::WindowsVersion >= QSysInfo::WV_XP) {
// try hard to disable cleartype rendering
static_cast<QRasterPaintEngine *>(p.paintEngine())->disableClearType();
LOGFONT nonCleartypeFont = logfont;
nonCleartypeFont.lfQuality = ANTIALIASED_QUALITY;
hfont = CreateFontIndirect(&nonCleartypeFont);
}
p.setPen(Qt::black);
p.setBrush(Qt::NoBrush);
QTextItemInt ti;
ti.ascent = ascent();
ti.descent = descent();
ti.width = glyph_width;
ti.fontEngine = this;
ti.num_glyphs = 1;
QGlyphLayout glyphLayout;
ti.glyphs = &glyphLayout;
glyphLayout.glyph = glyph;
memset(&glyphLayout.attributes, 0, sizeof(glyphLayout.attributes));
glyphLayout.advance.x = glyph_width;
p.drawTextItem(QPointF(-glyph_x, -glyph_y), ti);
if (QSysInfo::WindowsVersion >= QSysInfo::WV_XP) {
DeleteObject(hfont);
hfont = oldHFont;
}
p.end();
QImage indexed(im.width(), im.height(), QImage::Format_Indexed8);
QVector<QRgb> colors(256);
for (int i=0; i<256; ++i)
colors[i] = qRgba(0, 0, 0, i);
indexed.setColorTable(colors);
for (int y=0; y<im.height(); ++y) {
uchar *dst = (uchar *) indexed.scanLine(y);
uint *src = (uint *) im.scanLine(y);
for (int x=0; x<im.width(); ++x)
dst[x] = qAlpha(src[x]);
}
return indexed;
}
// -------------------------------------- Multi font engine
QFontEngineMultiWin::QFontEngineMultiWin(QFontEngineWin *first, const QStringList &fallbacks)
: QFontEngineMulti(fallbacks.size()+1),
fallbacks(fallbacks)
{
engines[0] = first;
first->ref.ref();
fontDef = engines[0]->fontDef;
}
void QFontEngineMultiWin::loadEngine(int at)
{
Q_ASSERT(at < engines.size());
Q_ASSERT(engines.at(at) == 0);
QString fam = fallbacks.at(at-1);
LOGFONT lf = static_cast<QFontEngineWin *>(engines.at(0))->logfont;
HFONT hfont;
QT_WA({
memcpy(lf.lfFaceName, fam.utf16(), sizeof(TCHAR)*qMin(fam.length()+1,32)); // 32 = Windows hard-coded
hfont = CreateFontIndirectW(&lf);
} , {
// LOGFONTA and LOGFONTW are binary compatible
QByteArray lname = fam.toLocal8Bit();
memcpy(lf.lfFaceName,lname.data(),
qMin(lname.length()+1,32)); // 32 = Windows hard-coded
hfont = CreateFontIndirectA((LOGFONTA*)&lf);
});
bool stockFont = false;
if (hfont == 0) {
hfont = (HFONT)GetStockObject(ANSI_VAR_FONT);
stockFont = true;
}
engines[at] = new QFontEngineWin(fam, hfont, stockFont, lf);
engines[at]->ref.ref();
engines[at]->fontDef = fontDef;
}
QT_END_NAMESPACE
| liuyanghejerry/qtextended | qtopiacore/qt/src/gui/text/qfontengine_win.cpp | C++ | gpl-2.0 | 43,049 |
<?php
/**
* The markup for the frontend of the Latest Comments widget
*
* @package Muut
* @copyright 2014 Muut Inc
*/
/**
* This file assumes that we are within the widget() method of the Muut_Widget_Latest_Comments class (which extends WP_Widget).
* Knowing that, `$this` represents that widget instance.
*/
?>
<div id="muut-widget-latest-comments-wrapper" class="muut_widget_wrapper muut_widget_latest_comments_wrapper">
<ul id="muut-recentcomments">
<?php
foreach ( $latest_comments_data as $comment ) {
if ( is_string( $comment['user'] ) ) {
$user_obj->displayname = $comment['user'];
$user_obj->img = '';
$user_obj->path = $comment['user'];
} else {
$user_obj = $comment['user'];
}
echo $this->getRowMarkup( $comment['post_id'], $comment['timestamp'], $comment['user'] );
}
?>
</ul>
</div>
| AnduZhang/resource-center | wp-content/plugins/muut/views/widgets/widget-latest-comments.php | PHP | gpl-2.0 | 846 |
#!/usr/bin/python2.4
# Copyright 2008 Google Inc.
# Author : Anoop Chandran <anoopj@google.com>
#
# openduckbill is a simple backup application. It offers support for
# transferring data to a local backup directory, NFS. It also provides
# file system monitoring of directories marked for backup. Please read
# the README file for more details.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
"""Helper class, does command execution and returns value.
This class has the method RunCommandPopen which executes commands passed to
it and returns the status.
"""
import os
import subprocess
import sys
class CommandHelper:
"""Run command and return status, either using Popen or call
"""
def __init__(self, log_handle=''):
"""Initialise logging state
Logging enabled in debug mode.
Args:
log_handle: Object - a handle to the logging subsystem.
"""
self.logmsg = log_handle
if self.logmsg.debug:
self.stdout_debug = None
self.stderr_debug = None
else:
self.stdout_debug = 1
self.stderr_debug = 1
def RunCommandPopen(self, runcmd):
"""Uses subprocess.Popen to run the command.
Also prints the command output if being run in debug mode.
Args:
runcmd: List - path to executable and its arguments.
Retuns:
runretval: Integer - exit value of the command, after execution.
"""
stdout_val=self.stdout_debug
stderr_val=self.stderr_debug
if stdout_val:
stdout_l = file(os.devnull, 'w')
else:
stdout_l=subprocess.PIPE
if stderr_val:
stderr_l = file(os.devnull, 'w')
else:
stderr_l=subprocess.STDOUT
try:
run_proc = subprocess.Popen(runcmd, bufsize=0,
executable=None, stdin=None,
stdout=stdout_l, stderr=stderr_l)
if self.logmsg.debug:
output = run_proc.stdout
while 1:
line = output.readline()
if not line:
break
line = line.rstrip()
self.logmsg.logger.debug("Command output: %s" % line)
run_proc.wait()
runretval = run_proc.returncode
except OSError, e:
self.logmsg.logger.error('%s', e)
runretval = 1
except KeyboardInterrupt, e:
self.logmsg.logger.error('User interrupt')
sys.exit(1)
if stdout_l:
pass
#stderr_l.close()
if stderr_l:
pass
#stderr_l.close()
return runretval
| xtao/openduckbill | src/helper.py | Python | gpl-2.0 | 3,110 |
<?php
/**
* -----------------------------------------------------------------------------
*
* Functions for TwitterZoid PHP Script
* Copyright (c) 2008 Philip Newborough <mail@philipnewborough.co.uk>
*
* http://crunchbang.org/archives/2008/02/20/twitterzoid-php-script/
*
* LICENSE: This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* http://www.gnu.org/licenses/
*
* -----------------------------------------------------------------------------
*/
// no direct access
defined( '_JEXEC' ) or die( 'Restricted Access' );
function timesince($i,$date){
if($i >= time()){
$timeago = JText::_('JM_0_SECONDS_AGO');
return $timeago;
}
$seconds = time()-$i;
$units = array('JM_SECOND' => 1,'JM_MINUTE' => 60,'JM_HOUR' => 3600,'JM_DAY' => 86400,'JM_MONTH' => 2629743,'JM_YEAR' => 31556926);
foreach($units as $key => $val){
if($seconds >= $val){
$results = floor($seconds/$val);
if($key == 'JM_DAY' | $key == 'JM_MONTH' | $key == 'JM_YEAR'){
$timeago = $date;
}else{
$timeago = ($results >= 2) ? JText::_('JM_ABOUT').' ' . $results . ' ' . JText::_($key) . JText::_('JM_S_AGO') : JText::_('JM_ABOUT').' '. $results . ' ' . JText::_($key) .' '. JText::_('JM_AGO');
}
}
}
return $timeago;
}
function twitterit(&$text, $twitter_username, $target='_blank', $nofollow=true){
$urls = _autolink_find_URLS( $text );
if(!empty($urls)){
array_walk( $urls, '_autolink_create_html_tags', array('target'=>$target, 'nofollow'=>$nofollow) );
$text = strtr( $text, $urls );
}
$text = preg_replace("/(\s@|^@)([a-zA-Z0-9]{1,15})/","$1<a href=\"http://twitter.com/$2\" target=\"_blank\" rel=\"nofollow\">$2</a>",$text);
$text = preg_replace("/(\s#|^#)([a-zA-Z0-9]{1,15})/","$1<a href=\"http://twitter.com/#!/search?q=$2\" target=\"_blank\" rel=\"nofollow\">$2</a>",$text);
$text = str_replace($twitter_username.": ", "",$text);
return $text;
}
function _autolink_find_URLS($text){
$scheme = '(http:\/\/|https:\/\/)';
$www = 'www\.';
$ip = '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}';
$subdomain = '[-a-z0-9_]+\.';
$name = '[a-z][-a-z0-9]+\.';
$tld = '[a-z]+(\.[a-z]{2,2})?';
$the_rest = '\/?[a-z0-9._\/~#&=;%+?-]+[a-z0-9\/#=?]{1,1}';
$pattern = "$scheme?(?(1)($ip|($subdomain)?$name$tld)|($www$name$tld))$the_rest";
$pattern = '/'.$pattern.'/is';
$c = preg_match_all($pattern, $text, $m);
unset($text, $scheme, $www, $ip, $subdomain, $name, $tld, $the_rest, $pattern);
if($c){
return(array_flip($m[0]));
}
return(array());
}
function _autolink_create_html_tags(&$value, $key, $other=null){
$target = $nofollow = null;
if(is_array($other)){
$target = ($other['target'] ? " target=\"$other[target]\"":null);
$nofollow = ($other['nofollow'] ? ' rel="nofollow"':null);
}
$value = "<a href=\"$key\"$target$nofollow>$key</a>";
}
?>
| cifren/opussalon | administrator/components/com_joomailermailchimpintegration/libraries/TwitterZoid.php | PHP | gpl-2.0 | 3,467 |
<?php
echo '<h2 class="paddingtop">' . $words->get('members') . '</h2>';
$User = new APP_User;
$words = new MOD_words();
$layoutbits = new MOD_layoutbits;
$url = '/places/' . htmlspecialchars($this->countryName) . '/' . $this->countryCode . '/';
if ($this->regionCode) {
$url .= htmlspecialchars($this->regionName) . '/' . $this->regionCode . '/';
}
if ($this->cityCode) {
$url .= htmlspecialchars($this->cityName) . '/' . $this->cityCode . '/';
}
$loginUrlOpen = '<a href="login' . $url . '#login-widget">';
$loginUrlClose = '</a>';
if (!$this->members) {
if ($this->totalMemberCount) {
echo $words->get('PlacesMoreMembers', $words->getSilent('PlacesMoreLogin'), $loginUrlOpen, $loginUrlClose) . $words->flushBuffer();
} else {
echo $words->get('PlacesNoMembersFound', htmlspecialchars($this->placeName));
}
} else {
if ($this->totalMemberCount != $this->memberCount) {
echo $words->get('PlacesMoreMembers', $words->getSilent('PlacesMoreLogin'), $loginUrlOpen, $loginUrlClose) . $words->flushBuffer();
}
// divide members into pages of Places::MEMBERS_PER_PAGE (20)
$params = new StdClass;
$params->strategy = new HalfPagePager('right');
$params->page_url = $url;
$params->page_url_marker = 'page';
$params->page_method = 'url';
$params->items = $this->memberCount;
$params->active_page = $this->pageNumber;
$params->items_per_page = Places::MEMBERS_PER_PAGE;
$pager = new PagerWidget($params);
// show members if there are any to show
echo '<ul class="clearfix">';
foreach ($this->members as $member) {
$image = new MOD_images_Image('',$member->username);
if ($member->HideBirthDate=="No") {
$member->age = floor($layoutbits->fage_value($member->BirthDate));
} else {
$member->age = $words->get("Hidden");
}
echo '<li class="userpicbox float_left">';
echo MOD_layoutbits::PIC_50_50($member->username,'',$style='framed float_left');
echo '<div class="userinfo">';
echo ' <a class="username" href="members/'.$member->username.'">'.
$member->username.'</a><br />';
echo ' <span class="small">'.$words->get("yearsold",$member->age).
'<br />'.$member->city.'</span>';
echo '</div>';
echo '</li>';
}
echo '</ul>';
$pager->render();
}
?>
| thisismeonmounteverest/rox | build/places/templates/memberlist.php | PHP | gpl-2.0 | 2,396 |
<?php
class sigesp_snorh_c_diaferiado
{
var $io_sql;
var $io_mensajes;
var $io_funciones;
var $io_seguridad;
var $io_sno;
var $ls_codemp;
//-----------------------------------------------------------------------------------------------------------------------------------
function sigesp_snorh_c_diaferiado()
{
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: sigesp_snorh_c_diaferiado
// Access: public (sigesp_snorh_d_diaferiado)
// Description: Constructor de la Clase
// Creado Por: Ing. Yesenia Moreno
// Fecha Creación: 01/01/2006 Fecha Última Modificación :
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
require_once("../shared/class_folder/sigesp_include.php");
$io_include=new sigesp_include();
$io_conexion=$io_include->uf_conectar();
require_once("../shared/class_folder/class_sql.php");
$this->io_sql=new class_sql($io_conexion);
require_once("../shared/class_folder/class_mensajes.php");
$this->io_mensajes=new class_mensajes();
require_once("../shared/class_folder/class_funciones.php");
$this->io_funciones=new class_funciones();
require_once("../shared/class_folder/sigesp_c_seguridad.php");
$this->io_seguridad=new sigesp_c_seguridad();
require_once("sigesp_sno.php");
$this->io_sno=new sigesp_sno();
$this->ls_codemp=$_SESSION["la_empresa"]["codemp"];
}// end function sigesp_snorh_c_diaferiado
//-----------------------------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------------------
function uf_destructor()
{
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: uf_destructor
// Access: public (sigesp_snorh_d_diaferiado)
// Description: Destructor de la Clase
// Creado Por: Ing. Yesenia Moreno
// Fecha Creación: 01/01/2006 Fecha Última Modificación :
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
unset($io_include);
unset($io_conexion);
unset($this->io_sql);
unset($this->io_mensajes);
unset($this->io_funciones);
unset($this->io_seguridad);
unset($this->ls_codemp);
}// end function uf_destructor
//-----------------------------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------------------
function uf_select_diaferiado($as_campo,$as_valor)
{
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: uf_select_diaferiado
// Access: private
// Arguments: as_campo // Campo por el que se quiere filtrar
// as_valor // Valor del campo
// Returns: lb_existe True si existe ó False si no existe
// Description: Funcion que verifica si el día feriado está registrado
// Creado Por: Ing. Yesenia Moreno
// Fecha Creación: 01/01/2006 Fecha Última Modificación :
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$lb_existe=true;
$ls_sql="SELECT ".$as_campo." ".
" FROM sno_diaferiado ".
" WHERE codemp='".$this->ls_codemp."'".
" AND ".$as_campo."='".$as_valor."'";
$rs_data=$this->io_sql->select($ls_sql);
if($rs_data===false)
{
$this->io_mensajes->message("CLASE->Dia Feriado MÉTODO->uf_select_diaferiado ERROR->".$this->io_funciones->uf_convertirmsg($this->io_sql->message));
$lb_existe=false;
}
else
{
if(!$row=$this->io_sql->fetch_row($rs_data))
{
$lb_existe=false;
}
$this->io_sql->free_result($rs_data);
}
return $lb_existe;
}// end function uf_select_diaferiado
//-----------------------------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------------------
function uf_insert_diaferiado($ad_fecfer,$as_nomfer,$aa_seguridad)
{
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: uf_insert_diaferiado
// Access: private
// Arguments: ad_fecfer // Fecha del Feriado
// as_nomfer // Descripción del Feriado
// aa_seguridad // arreglo de las variables de seguridad
// Returns: lb_valido True si se ejecuto el insert ó False si hubo error en el insert
// Description: Funcion que inserta en la tabla sno_diaferiado
// Creado Por: Ing. Yesenia Moreno
// Fecha Creación: 01/01/2006 Fecha Última Modificación :
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$lb_valido=true;
$ls_sql="INSERT INTO sno_diaferiado".
"(codemp,fecfer,nomfer)VALUES('".$this->ls_codemp."','".$ad_fecfer."','".$as_nomfer."')";
$this->io_sql->begin_transaction() ;
$li_row=$this->io_sql->execute($ls_sql);
if($li_row===false)
{
$lb_valido=false;
$this->io_mensajes->message("CLASE->Dia Feriado MÉTODO->uf_insert_diaferiado ERROR->".$this->io_funciones->uf_convertirmsg($this->io_sql->message));
$this->io_sql->rollback();
}
else
{
///////////////////////////////// SEGURIDAD /////////////////////////////
$ls_evento="INSERT";
$ls_descripcion ="Insertó el Día Feriado ".$ad_fecfer;
$lb_valido= $this->io_seguridad->uf_sss_insert_eventos_ventana($aa_seguridad["empresa"],
$aa_seguridad["sistema"],$ls_evento,$aa_seguridad["logusr"],
$aa_seguridad["ventanas"],$ls_descripcion);
///////////////////////////////// SEGURIDAD /////////////////////////////
if($lb_valido)
{
$this->io_mensajes->message("El Dia Feriado fue registrado.");
$this->io_sql->commit();
}
else
{
$lb_valido=false;
$this->io_mensajes->message("CLASE->Dia Feriado MÉTODO->uf_insert_diaferiado ERROR->".$this->io_funciones->uf_convertirmsg($this->io_sql->message));
$this->io_sql->rollback();
}
}
return $lb_valido;
}// end function uf_insert_diaferiado
//-----------------------------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------------------
function uf_update_diaferiado($ad_fecfer,$as_nomfer,$aa_seguridad)
{
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: uf_update_diaferiado
// Access: private
// Arguments: ad_fecfer // Fecha del Feriado
// as_nomfer // Descripción del Feriado
// aa_seguridad // arreglo de las variables de seguridad
// Returns: lb_valido True si se ejecuto el update ó False si hubo error en el update
// Description: Funcion que actualiza en la tabla sno_diaferiado
// Creado Por: Ing. Yesenia Moreno
// Fecha Creación: 01/01/2006 Fecha Última Modificación :
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$lb_valido=true;
$ls_sql="UPDATE sno_diaferiado ".
" SET nomfer='".$as_nomfer."' ".
" WHERE codemp='".$this->ls_codemp."'".
" AND fecfer='".$ad_fecfer."'";
$this->io_sql->begin_transaction();
$li_row=$this->io_sql->execute($ls_sql);
if($li_row===false)
{
$lb_valido=false;
$this->io_mensajes->message("CLASE->Dia Feriado MÉTODO->uf_update_diaferiado ERROR->".$this->io_funciones->uf_convertirmsg($this->io_sql->message));
$this->io_sql->rollback();
}
else
{
///////////////////////////////// SEGURIDAD /////////////////////////////
$ls_evento="UPDATE";
$ls_descripcion ="Actualizó el Día Feriado ".$ad_fecfer;
$lb_valido= $this->io_seguridad->uf_sss_insert_eventos_ventana($aa_seguridad["empresa"],
$aa_seguridad["sistema"],$ls_evento,$aa_seguridad["logusr"],
$aa_seguridad["ventanas"],$ls_descripcion);
///////////////////////////////// SEGURIDAD /////////////////////////////
if($lb_valido)
{
$this->io_mensajes->message("El Día feriado fue Actualizado.");
$this->io_sql->commit();
}
else
{
$lb_valido=false;
$this->io_mensajes->message("CLASE->Dia Feriado MÉTODO->uf_update_diaferiado ERROR->".$this->io_funciones->uf_convertirmsg($this->io_sql->message));
$this->io_sql->rollback();
}
}
return $lb_valido;
}// end function uf_update_diaferiado
//-----------------------------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------------------
function uf_guardar($as_existe,$ad_fecfer,$as_nomfer,$aa_seguridad)
{
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: uf_guardar
// Access: public (sigesp_snorh_d_diaferiado)
// Arguments: ad_fecfer // Fecha del Feriado
// as_nomfer // Descripción del Feriado
// aa_seguridad // arreglo de las variables de seguridad
// Returns: lb_valido True si guardo ó False si hubo error al guardar
// Description: Funcion que almacena el día feriado
// Creado Por: Ing. Yesenia Moreno
// Fecha Creación: 01/01/2006 Fecha Última Modificación :
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$ad_fecfer=$this->io_funciones->uf_convertirdatetobd($ad_fecfer);
$lb_valido=false;
switch ($as_existe)
{
case "FALSE":
if($this->uf_select_diaferiado("fecfer",$ad_fecfer)===false)
{
$lb_valido=$this->uf_insert_diaferiado($ad_fecfer,$as_nomfer,$aa_seguridad);
}
else
{
$this->io_mensajes->message("El Dia Feriado ya existe, no lo puede incluir.");
}
break;
case "TRUE":
if(($this->uf_select_diaferiado("fecfer",$ad_fecfer)))
{
$lb_valido=$this->uf_update_diaferiado($ad_fecfer,$as_nomfer,$aa_seguridad);
}
else
{
$this->io_mensajes->message("El Dia Feriado no existe, no lo puede actualizar.");
}
break;
}
return $lb_valido;
}// end function uf_guardar
//-----------------------------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------------------
function uf_delete_diaferiado($ad_fecfer,$aa_seguridad)
{
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: uf_delete_diaferiado
// Access: public (sigesp_snorh_d_diaferiado)
// Arguments: ad_fecfer // Fecha del Feriado
// as_nomfer // Descripción del Feriado
// aa_seguridad // arreglo de las variables de seguridad
// Returns: lb_valido True si se ejecuto el delete ó False si hubo error en el delete
// Description: Funcion que elimina el día feriado
// Creado Por: Ing. Yesenia Moreno
// Fecha Creación: 01/01/2006 Fecha Última Modificación :
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$lb_valido=true;
$ad_fecfer=$this->io_funciones->uf_convertirdatetobd($ad_fecfer);
$ls_sql="DELETE ".
" FROM sno_diaferiado ".
" WHERE codemp='".$this->ls_codemp."'".
" AND fecfer='".$ad_fecfer."'";
$this->io_sql->begin_transaction();
$li_row=$this->io_sql->execute($ls_sql);
if($li_row===false)
{
$lb_valido=false;
$this->io_mensajes->message("CLASE->Dia Feriado MÉTODO->uf_delete_diaferiado ERROR->".$this->io_funciones->uf_convertirmsg($this->io_sql->message));
$this->io_sql->rollback();
}
else
{
///////////////////////////////// SEGURIDAD /////////////////////////////
$ls_evento="DELETE";
$ls_descripcion ="Eliminó el Día Feriado ".$ad_fecfer;
$lb_valido= $this->io_seguridad->uf_sss_insert_eventos_ventana($aa_seguridad["empresa"],
$aa_seguridad["sistema"],$ls_evento,$aa_seguridad["logusr"],
$aa_seguridad["ventanas"],$ls_descripcion);
///////////////////////////////// SEGURIDAD /////////////////////////////
if($lb_valido)
{
$this->io_mensajes->message("El Día feriado fue Eliminado.");
$this->io_sql->commit();
}
else
{
$lb_valido=false;
$this->io_mensajes->message("CLASE->Dia Feriado MÉTODO->uf_delete_diaferiado ERROR->".$this->io_funciones->uf_convertirmsg($this->io_sql->message));
$this->io_sql->rollback();
}
}// end function uf_delete_diaferiado
return $lb_valido;
}
//-----------------------------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------------------
function uf_select_feriados($ad_fecdes,$ad_fechas)
{
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: uf_select_feriados
// Access: private
// Arguments: ad_fecdes // Fecha desde
// ad_fechas // Fecha Hasta
// Returns: li_total Toal de días feriados
// Description: Funcion que cuenta la cantidad de días feriados dada una fecha
// Creado Por: Ing. Yesenia Moreno
// Fecha Creación: 07/09/2006 Fecha Última Modificación :
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$li_total=0;
$ls_sql="SELECT fecfer ".
" FROM sno_diaferiado ".
" WHERE codemp='".$this->ls_codemp."'".
" AND fecfer>='".$ad_fecdes."' ".
" AND fecfer<='".$ad_fechas."' ";
$rs_data=$this->io_sql->select($ls_sql);
if($rs_data===false)
{
$this->io_mensajes->message("CLASE->Dia Feriado MÉTODO->uf_select_feriados ERROR->".$this->io_funciones->uf_convertirmsg($this->io_sql->message));
}
else
{
while($row=$this->io_sql->fetch_row($rs_data))
{
$ld_fecfer=$row["fecfer"];
$ld_fecfer=$this->io_funciones->uf_convertirfecmostrar($ld_fecfer);
if($this->io_sno->uf_nro_sabydom($ld_fecfer,$ld_fecfer)==0)
{
$li_total=$li_total+1;
}
}
$this->io_sql->free_result($rs_data);
}
return $li_total;
}// end function uf_select_feriados
//-----------------------------------------------------------------------------------------------------------------------------------
}
?> | omerta/huayra | sno/sigesp_snorh_c_diaferiado.php | PHP | gpl-2.0 | 16,072 |
/* AbiWord
* Copyright (C) 2004 Luca Padovani <lpadovan@cs.unibo.it>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*/
#include "gr_Graphics.h"
#include "gr_Abi_CharArea.h"
#include "gr_Abi_RenderingContext.h"
GR_Abi_CharArea::GR_Abi_CharArea(GR_Graphics* graphics, GR_Font* f, const scaled& /*size*/, UT_UCS4Char c)
: m_pFont(f), m_ch(c)
{
#if 0
UT_ASSERT(graphics);
graphics->setFont(m_pFont);
m_box = BoundingBox(GR_Abi_RenderingContext::fromAbiLayoutUnits(graphics->measureUnRemappedChar(m_ch)),
GR_Abi_RenderingContext::fromAbiLayoutUnits(graphics->getFontAscent()),
GR_Abi_RenderingContext::fromAbiLayoutUnits(graphics->getFontDescent()));
#else
UT_ASSERT(f);
UT_Rect glyphRect;
graphics->setFont(m_pFont);
f->glyphBox(m_ch, glyphRect, graphics);
GR_Abi_RenderingContext Context(graphics);
#if 0
fprintf(stderr, "getting glyph %d\n glyphBox [left=%d,width=%d,top=%d,height=%d]\n measureUnremappedChar=%d\n measureUnremappedCharForCache=%d\n ftlu=%f\n tdu=%f\n tlu=%f\n size=%d\n", c,
glyphRect.left, glyphRect.width, glyphRect.top, glyphRect.height,
graphics->measureUnRemappedChar(m_ch),
f->measureUnremappedCharForCache(m_ch),
graphics->ftluD(1.0),
graphics->tduD(1.0),
graphics->tluD(1.0),
size.getValue());
#endif
m_box = BoundingBox(Context.fromAbiLayoutUnits(glyphRect.width + glyphRect.left),
Context.fromAbiLayoutUnits(glyphRect.top),
Context.fromAbiLayoutUnits(glyphRect.height - glyphRect.top));
#endif
}
GR_Abi_CharArea::~GR_Abi_CharArea()
{ }
BoundingBox
GR_Abi_CharArea::box() const
{
return m_box;
}
scaled
GR_Abi_CharArea::leftEdge() const
{
return 0;
}
scaled
GR_Abi_CharArea::rightEdge() const
{
return m_box.width;
}
void
GR_Abi_CharArea::render(RenderingContext& c, const scaled& x, const scaled& y) const
{
GR_Abi_RenderingContext& context = dynamic_cast<GR_Abi_RenderingContext&>(c);
context.drawChar(x, y, m_pFont, m_ch);
//context.drawBox(x, y, m_box);
}
| tanya-guza/abiword | plugins/mathview/xp/gr_Abi_CharArea.cpp | C++ | gpl-2.0 | 2,657 |
<?php
/**
* @file
* Default theme implementation to display a region.
*
* Available variables:
* - $regions: Renderable array of regions associated with this zone
* - $enabled: Flag to detect if the zone was enabled/disabled via theme settings
* - $wrapper: Flag set to display a full browser width wrapper around the
* container zone allowing items/backgrounds to be themed outside the
* 960pixel container size.
* - $zid: the zone id of the zone being rendered. This is a text value.
* - $container_width: the container width (12, 16, 24) of the zone
* - $attributes: a string containing the relevant class & id data for a container
*
* Helper Variables
* - $attributes_array: an array of attributes for the container zone
*
* @see template_preprocess()
* @see template_preprocess_zone()
* @see template_process()
* @see template_process_zone()
*/
?>
<?php if($enabled && $populated): ?>
<?php if($wrapper): ?><div id="<?php print $zid;?>-outer-wrapper" class="clearfix"><?php endif; ?>
<div <?php print $attributes; ?>>
<?php print render($regions); ?>
</div>
<?php if($wrapper): ?></div><?php endif; ?>
<?php endif; ?> | 404pnf/d7sites | sites/csc.fltrp.com/themes/standard/omega/omega/templates/zone.tpl.php | PHP | gpl-2.0 | 1,173 |
<?php global $woocommerce, $yith_wcwl; ?>
<?php
$instance = jaw_template_get_var('instance');
?>
<ul>
<?php if (isset($instance['login_show']) && $instance['login_show'] == '1') { ?>
<li class="top-bar-login-content" aria-haspopup="true">
<?php
$myaccount_page_id = get_option('woocommerce_myaccount_page_id');
$myaccount_page_url = '';
if ($myaccount_page_id) {
$myaccount_page_url = get_permalink($myaccount_page_id);
}
if (is_user_logged_in()) {
$text = __('My account', 'jawtemplates');
} else {
$text = __('Log in', 'jawtemplates');
}
?>
<a href="<?php echo $myaccount_page_url; ?>">
<span class="topbar-title-icon icon-user-icon2"></span>
<span class="topbar-title-text">
<?php echo $text; ?>
</span>
</a>
<?php
$class = '';
if (class_exists('WooCommerce') && is_user_logged_in()) {
$class = 'woo-menu';
}
?>
<div class="top-bar-login-form <?php echo $class; ?>">
<?php echo jaw_get_template_part('login', array('header', 'top_bar')); ?>
<?php if (get_option('users_can_register') && !is_user_logged_in()) : ?>
<p class="regiter-button">
<?php
if (class_exists('WooCommerce') && get_option('woocommerce_enable_myaccount_registration') == 'yes') {
$register_link = get_permalink($myaccount_page_id);
} else {
$register_link = esc_url(wp_registration_url());
}
?>
<?php echo apply_filters('register', sprintf('<a class="btnregiter" href="%s">%s</a>', $register_link, __('Register', 'jawtemplates'))); ?>
</p>
<?php endif; ?>
</div>
</li>
<?php } ?>
<?php if (is_plugin_active('yith-woocommerce-wishlist/init.php') && class_exists('WooCommerce')) { ?>
<?php if (isset($instance['wishlist_show']) && $instance['wishlist_show'] == '1') { ?>
<li class="wishlist-contents">
<a href="<?php echo $yith_wcwl->get_wishlist_url(); ?>">
<span class="topbar-title-icon icon-wishlist-icon"></span>
<span class="topbar-title-text">
<?php _e('Wishlist', 'jawtemplates'); ?>
</span>
</a>
</li>
<?php } ?>
<?php } ?>
<?php if (class_exists('WooCommerce')) { ?>
<?php if (isset($instance['cart_show']) && $instance['cart_show'] == '1') { ?>
<li class="woo-bar-woo-cart woocommerce-page " aria-haspopup="true">
<?php echo jaw_get_template_part('woo_cart', array('widgets', 'ecommerce_widget')); ?>
</li>
<?php } ?>
<?php } ?>
</ul>
| thanhtrantv/car-wp | wp-content/themes/goodstore/templates/widgets/jaw_ecommerce_widget.php | PHP | gpl-2.0 | 3,151 |