repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
kgibm/open-liberty
dev/com.ibm.ws.jbatch.fat.common/test-applications/BonusPayout.war/src/com/ibm/websphere/samples/batch/artifacts/BonusCreditProcessor.java
1574
/******************************************************************************* * Copyright (c) 2014, 2020 IBM Corporation and others. * 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: * IBM Corporation - initial API and implementation *******************************************************************************/ package com.ibm.websphere.samples.batch.artifacts; import javax.batch.api.BatchProperty; import javax.batch.api.chunk.ItemProcessor; import javax.inject.Inject; import com.ibm.websphere.samples.batch.beans.AccountDataObject; import com.ibm.websphere.samples.batch.util.BonusPayoutConstants; import javax.inject.Named; /** * Add a 'bonusAmount' to each balance. */ @Named("BonusCreditProcessor") public class BonusCreditProcessor implements ItemProcessor, BonusPayoutConstants { @Inject @BatchProperty(name = "bonusAmount") String bonusAmountStr; Integer bonusAmount = null; @Override public Object processItem(Object item) throws Exception { AccountDataObject ado = (AccountDataObject) item; int newBalance = ado.getBalance(); ado.setBalance(newBalance + getBonusAmount()); return ado; } private int getBonusAmount() { if (bonusAmount == null) { bonusAmount = Integer.parseInt(bonusAmountStr); } return bonusAmount; } }
epl-1.0
S0urceror/smarthome
extensions/binding/org.eclipse.smarthome.binding.tradfri.test/src/test/java/org/eclipse/smarthome/binding/tradfri/discovery/TradfriDiscoveryParticipantOSGITest.java
4099
/** * Copyright (c) 2014-2017 by the respective copyright holders. * 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 */ package org.eclipse.smarthome.binding.tradfri.discovery; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; import javax.jmdns.ServiceInfo; import org.eclipse.smarthome.binding.tradfri.GatewayConfig; import org.eclipse.smarthome.binding.tradfri.TradfriBindingConstants; import org.eclipse.smarthome.binding.tradfri.internal.discovery.TradfriDiscoveryParticipant; import org.eclipse.smarthome.config.discovery.DiscoveryResult; import org.eclipse.smarthome.config.discovery.DiscoveryResultFlag; import org.eclipse.smarthome.core.thing.ThingUID; import org.eclipse.smarthome.io.transport.mdns.discovery.MDNSDiscoveryParticipant; import org.eclipse.smarthome.test.java.JavaOSGiTest; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; /** * Tests for {@link TradfriDiscoveryParticipant}. * * @author Kai Kreuzer - Initial contribution */ public class TradfriDiscoveryParticipantOSGITest extends JavaOSGiTest { private MDNSDiscoveryParticipant discoveryParticipant; @Mock private ServiceInfo tradfriGateway; @Mock private ServiceInfo otherDevice; @Before public void setUp() { initMocks(this); discoveryParticipant = getService(MDNSDiscoveryParticipant.class, TradfriDiscoveryParticipant.class); when(tradfriGateway.getType()).thenReturn("_coap._udp.local."); when(tradfriGateway.getName()).thenReturn("gw:12-34-56-78-90-ab"); when(tradfriGateway.getHostAddresses()).thenReturn(new String[] { "192.168.0.5" }); when(tradfriGateway.getPort()).thenReturn(1234); when(tradfriGateway.getPropertyString("version")).thenReturn("1.1"); when(otherDevice.getType()).thenReturn("_coap._udp.local."); when(otherDevice.getName()).thenReturn("something"); when(otherDevice.getHostAddresses()).thenReturn(new String[] { "192.168.0.5" }); when(otherDevice.getPort()).thenReturn(1234); when(otherDevice.getPropertyString("version")).thenReturn("1.1"); } @Test public void correctSupportedTypes() { assertThat(discoveryParticipant.getSupportedThingTypeUIDs().size(), is(1)); assertThat(discoveryParticipant.getSupportedThingTypeUIDs().iterator().next(), is(TradfriBindingConstants.GATEWAY_TYPE_UID)); } @Test public void correctThingUID() { assertThat(discoveryParticipant.getThingUID(tradfriGateway), is(new ThingUID("tradfri:gateway:gw1234567890ab"))); } @Test public void validDiscoveryResult() { DiscoveryResult result = discoveryParticipant.createResult(tradfriGateway); assertNotNull(result); assertThat(result.getProperties().get("firmware"), is("1.1")); assertThat(result.getFlag(), is(DiscoveryResultFlag.NEW)); assertThat(result.getThingUID(), is(new ThingUID("tradfri:gateway:gw1234567890ab"))); assertThat(result.getThingTypeUID(), is(TradfriBindingConstants.GATEWAY_TYPE_UID)); assertThat(result.getBridgeUID(), is(nullValue())); assertThat(result.getProperties().get("vendor"), is("IKEA")); assertThat(result.getProperties().get(GatewayConfig.HOST), is("192.168.0.5")); assertThat(result.getProperties().get(GatewayConfig.PORT), is(1234)); assertThat(result.getRepresentationProperty(), is(GatewayConfig.HOST)); } @Test public void noThingUIDForUnknownDevice() { assertThat(discoveryParticipant.getThingUID(otherDevice), is(nullValue())); } @Test public void noDiscoveryResultForUnknownDevice() { assertThat(discoveryParticipant.createResult(otherDevice), is(nullValue())); } }
epl-1.0
kevinmcgoldrick/Tank
tank_vmManager/src/test/java/com/intuit/tank/vmManager/environment/amazon/KeyValuePairTest.java
1904
package com.intuit.tank.vmManager.environment.amazon; /* * #%L * VmManager * %% * Copyright (C) 2011 - 2015 Intuit Inc. * %% * 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 * #L% */ import org.junit.*; import com.intuit.tank.vmManager.environment.amazon.KeyValuePair; import static org.junit.Assert.*; /** * The class <code>KeyValuePairTest</code> contains tests for the class <code>{@link KeyValuePair}</code>. * * @generatedBy CodePro at 12/16/14 6:30 PM */ public class KeyValuePairTest { /** * Run the KeyValuePair(String,String) constructor test. * * @throws Exception * * @generatedBy CodePro at 12/16/14 6:30 PM */ @Test public void testKeyValuePair_1() throws Exception { String key = ""; String value = ""; KeyValuePair result = new KeyValuePair(key, value); assertNotNull(result); assertEquals("", result.getValue()); assertEquals("", result.getKey()); } /** * Run the String getKey() method test. * * @throws Exception * * @generatedBy CodePro at 12/16/14 6:30 PM */ @Test public void testGetKey_1() throws Exception { KeyValuePair fixture = new KeyValuePair("", ""); String result = fixture.getKey(); assertEquals("", result); } /** * Run the String getValue() method test. * * @throws Exception * * @generatedBy CodePro at 12/16/14 6:30 PM */ @Test public void testGetValue_1() throws Exception { KeyValuePair fixture = new KeyValuePair("", ""); String result = fixture.getValue(); assertEquals("", result); } }
epl-1.0
OpenLiberty/open-liberty
dev/com.ibm.ws.microprofile.config.1.1/test/src/com/ibm/ws/microprofile/config/converter/test/StringConverter101.java
913
/******************************************************************************* * Copyright (c) 2017 IBM Corporation and others. * 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: * IBM Corporation - initial API and implementation *******************************************************************************/ package com.ibm.ws.microprofile.config.converter.test; import javax.annotation.Priority; import org.eclipse.microprofile.config.spi.Converter; @Priority(101) public class StringConverter101 implements Converter<String> { /** {@inheritDoc} */ @Override public String convert(String value) throws IllegalArgumentException { return "101=" + value; } }
epl-1.0
sudaraka94/che
plugins/plugin-docker/che-plugin-docker-machine/src/test/java/org/eclipse/che/plugin/docker/machine/MachineProviderImplTest.java
75215
/* * Copyright (c) 2012-2017 Red Hat, Inc. * 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: * Red Hat, Inc. - initial API and implementation */ package org.eclipse.che.plugin.docker.machine; import static java.util.Arrays.asList; import static java.util.Collections.emptyMap; import static java.util.Collections.emptySet; import static java.util.Collections.singleton; import static java.util.Collections.singletonMap; import static java.util.stream.Collectors.toMap; import static org.eclipse.che.plugin.docker.machine.DockerInstanceProvider.DOCKER_FILE_TYPE; import static org.eclipse.che.plugin.docker.machine.DockerInstanceProvider.MACHINE_SNAPSHOT_PREFIX; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertEqualsNoOrder; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; import org.eclipse.che.api.core.ServerException; import org.eclipse.che.api.core.jsonrpc.commons.RequestTransmitter; import org.eclipse.che.api.core.model.machine.Machine; import org.eclipse.che.api.core.model.machine.MachineConfig; import org.eclipse.che.api.core.model.machine.ServerConf; import org.eclipse.che.api.core.util.JsonRpcEndpointToMachineNameHolder; import org.eclipse.che.api.core.util.LineConsumer; import org.eclipse.che.api.environment.server.model.CheServiceImpl; import org.eclipse.che.api.machine.server.model.impl.ServerConfImpl; import org.eclipse.che.api.machine.server.recipe.RecipeImpl; import org.eclipse.che.api.machine.server.util.RecipeRetriever; import org.eclipse.che.commons.env.EnvironmentContext; import org.eclipse.che.commons.lang.os.WindowsPathEscaper; import org.eclipse.che.commons.subject.SubjectImpl; import org.eclipse.che.plugin.docker.client.DockerConnector; import org.eclipse.che.plugin.docker.client.DockerConnectorConfiguration; import org.eclipse.che.plugin.docker.client.DockerConnectorProvider; import org.eclipse.che.plugin.docker.client.ProgressMonitor; import org.eclipse.che.plugin.docker.client.UserSpecificDockerRegistryCredentialsProvider; import org.eclipse.che.plugin.docker.client.json.ContainerConfig; import org.eclipse.che.plugin.docker.client.json.ContainerCreated; import org.eclipse.che.plugin.docker.client.json.ContainerInfo; import org.eclipse.che.plugin.docker.client.json.ContainerState; import org.eclipse.che.plugin.docker.client.json.ImageConfig; import org.eclipse.che.plugin.docker.client.json.ImageInfo; import org.eclipse.che.plugin.docker.client.json.Volume; import org.eclipse.che.plugin.docker.client.params.CreateContainerParams; import org.eclipse.che.plugin.docker.client.params.InspectContainerParams; import org.eclipse.che.plugin.docker.client.params.PullParams; import org.eclipse.che.plugin.docker.client.params.RemoveContainerParams; import org.eclipse.che.plugin.docker.client.params.RemoveImageParams; import org.eclipse.che.plugin.docker.client.params.StartContainerParams; import org.eclipse.che.plugin.docker.client.params.TagParams; import org.eclipse.che.plugin.docker.machine.node.DockerNode; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.testng.MockitoTestNGListener; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Listeners; import org.testng.annotations.Test; @Listeners(MockitoTestNGListener.class) public class MachineProviderImplTest { private static final String CONTAINER_ID = "containerId"; private static final String WORKSPACE_ID = "wsId"; private static final String MACHINE_NAME = "machineName"; private static final String USER_TOKEN = "userToken"; private static final String USER_NAME = "user"; private static final boolean SNAPSHOT_USE_REGISTRY = true; private static final int MEMORY_SWAP_MULTIPLIER = 0; private static final String ENV_NAME = "env"; private static final String NETWORK_NAME = "networkName"; private static final String[] DEFAULT_CMD = new String[] {"some", "command"}; private static final String[] DEFAULT_ENTRYPOINT = new String[] {"entry", "point"}; @Mock private DockerConnector dockerConnector; @Mock private DockerConnectorConfiguration dockerConnectorConfiguration; @Mock private DockerMachineFactory dockerMachineFactory; @Mock private DockerInstanceStopDetector dockerInstanceStopDetector; @Mock private RequestTransmitter transmitter; @Mock private JsonRpcEndpointToMachineNameHolder jsonRpcEndpointToMachineNameHolder; @Mock private DockerNode dockerNode; @Mock private UserSpecificDockerRegistryCredentialsProvider credentialsReader; @Mock private ContainerInfo containerInfo; @Mock private ContainerState containerState; @Mock private ImageInfo imageInfo; @Mock private ImageConfig imageConfig; @Mock private RecipeRetriever recipeRetriever; @Mock private WindowsPathEscaper pathEscaper; private MachineProviderImpl provider; private class MockConnectorProvider extends DockerConnectorProvider { public MockConnectorProvider() { super(Collections.emptyMap(), "default"); } @Override public DockerConnector get() { return dockerConnector; } } @BeforeMethod public void setUp() throws Exception { when(dockerConnectorConfiguration.getDockerHostIp()).thenReturn("123.123.123.123"); provider = new MachineProviderBuilder().build(); EnvironmentContext envCont = new EnvironmentContext(); envCont.setSubject(new SubjectImpl(USER_NAME, "userId", USER_TOKEN, false)); EnvironmentContext.setCurrent(envCont); when(recipeRetriever.getRecipe(any(MachineConfig.class))) .thenReturn(new RecipeImpl().withType(DOCKER_FILE_TYPE).withScript("FROM codenvy")); when(dockerMachineFactory.createNode(anyString(), anyString())).thenReturn(dockerNode); when(dockerConnector.createContainer(any(CreateContainerParams.class))) .thenReturn(new ContainerCreated(CONTAINER_ID, new String[0])); when(dockerConnector.inspectContainer(any(InspectContainerParams.class))) .thenReturn(containerInfo); when(dockerConnector.inspectContainer(anyString())).thenReturn(containerInfo); when(containerInfo.getState()).thenReturn(containerState); when(containerState.getStatus()).thenReturn("running"); when(dockerConnector.inspectImage(anyString())).thenReturn(imageInfo); when(imageInfo.getConfig()).thenReturn(imageConfig); when(imageConfig.getCmd()).thenReturn(new String[] {"tail", "-f", "/dev/null"}); } @AfterMethod public void tearDown() throws Exception { EnvironmentContext.reset(); } @Test public void shouldPullDockerImageOnInstanceCreationFromSnapshotFromRegistry() throws Exception { String repo = MACHINE_SNAPSHOT_PREFIX + "repo"; String tag = "latest"; String registry = "localhost:1234"; createInstanceFromSnapshot(repo, tag, registry); PullParams pullParams = PullParams.create(repo).withRegistry(registry).withTag(tag); verify(dockerConnector).pull(eq(pullParams), any(ProgressMonitor.class)); } @Test public void shouldNotPullDockerImageOnInstanceCreationFromLocalSnapshot() throws Exception { String repo = MACHINE_SNAPSHOT_PREFIX + "repo"; String tag = "latest"; String registry = "localhost:1234"; provider = new MachineProviderBuilder().setSnapshotUseRegistry(false).build(); createInstanceFromSnapshot(repo, tag, registry); verify(dockerConnector, never()) .pull(eq(PullParams.create(repo).withTag(tag)), any(ProgressMonitor.class)); } @Test public void shouldPullDockerImageIfAlwaysPullIsTrueEvenIfImageExistsLocally() throws Exception { provider = new MachineProviderBuilder().setDoForcePullImage(true).build(); doReturn(true).when(provider).isDockerImageExistLocally(anyString()); createInstanceFromRecipe(); verify(dockerConnector).pull(any(PullParams.class), any(ProgressMonitor.class)); } @Test public void shouldPullDockerImageIfAlwaysPullIsFalseButImageDoesNotExist() throws Exception { provider = new MachineProviderBuilder().setDoForcePullImage(false).build(); doReturn(false).when(provider).isDockerImageExistLocally(anyString()); createInstanceFromRecipe(); verify(dockerConnector).pull(any(PullParams.class), any(ProgressMonitor.class)); } @Test public void shouldNotPullDockerImageIfAlwaysPullIsFalseAndTheImageExistLocally() throws Exception { provider = new MachineProviderBuilder().setDoForcePullImage(false).build(); doReturn(true).when(provider).isDockerImageExistLocally(anyString()); createInstanceFromRecipe(); verify(dockerConnector, never()).pull(any(PullParams.class), any(ProgressMonitor.class)); } @Test public void shouldUseLocalImageOnInstanceCreationFromSnapshot() throws Exception { final String repo = MACHINE_SNAPSHOT_PREFIX + "repo"; final String tag = "latest"; provider = new MachineProviderBuilder().setSnapshotUseRegistry(false).build(); CheServiceImpl machine = createService(); machine.setImage(repo + ":" + tag); machine.setBuild(null); provider.startService( USER_NAME, WORKSPACE_ID, ENV_NAME, MACHINE_NAME, false, NETWORK_NAME, machine, LineConsumer.DEV_NULL); verify(dockerConnector, never()).pull(any(PullParams.class), any(ProgressMonitor.class)); } @Test public void shouldNotRemoveImageAfterRestoreFromLocalSnapshot() throws Exception { String repo = MACHINE_SNAPSHOT_PREFIX + "repo"; String tag = "latest"; provider = new MachineProviderBuilder().setSnapshotUseRegistry(false).build(); createInstanceFromSnapshot(repo, tag, null); verify(dockerConnector, never()).removeImage(any(RemoveImageParams.class)); } @Test public void shouldNotRemoveImageWhenCreatingInstanceFromLocalImage() throws Exception { String repo = "repo1"; String tag = "latest"; MachineProviderImpl provider = new MachineProviderBuilder().setSnapshotUseRegistry(false).build(); CheServiceImpl machine = createService(); machine.setBuild(null); machine.setImage(repo + ":" + tag + "@digest"); provider.startService( USER_NAME, WORKSPACE_ID, ENV_NAME, MACHINE_NAME, false, NETWORK_NAME, machine, LineConsumer.DEV_NULL); verify(dockerConnector, never()).removeImage(any(RemoveImageParams.class)); } @Test public void shouldReTagBuiltImageWithPredictableOnInstanceCreationFromRecipe() throws Exception { // given String repo = MACHINE_SNAPSHOT_PREFIX + "repo1"; String tag = "tag1"; String registry = "registry1"; // when CheServiceImpl machine = createInstanceFromSnapshot(repo, tag, registry); // then TagParams tagParams = TagParams.create( registry + "/" + repo + ":" + tag, "eclipse-che/" + machine.getContainerName()); verify(dockerConnector).tag(eq(tagParams)); ArgumentCaptor<RemoveImageParams> argumentCaptor = ArgumentCaptor.forClass(RemoveImageParams.class); verify(dockerConnector).removeImage(argumentCaptor.capture()); RemoveImageParams imageParams = argumentCaptor.getValue(); assertEquals(imageParams.getImage(), registry + "/" + repo + ":" + tag); assertFalse(imageParams.isForce()); } @Test public void shouldCreateContainerOnInstanceCreationFromRecipe() throws Exception { // when CheServiceImpl machine = createInstanceFromRecipe(); // then ArgumentCaptor<CreateContainerParams> argumentCaptor = ArgumentCaptor.forClass(CreateContainerParams.class); verify(dockerConnector).createContainer(argumentCaptor.capture()); assertEquals( argumentCaptor.getValue().getContainerConfig().getImage(), "eclipse-che/" + machine.getContainerName()); } @Test public void shouldPublishAllExposedPortsOnCreateContainerOnInstanceCreationFromRecipe() throws Exception { // when createInstanceFromRecipe(); // then ArgumentCaptor<CreateContainerParams> argumentCaptor = ArgumentCaptor.forClass(CreateContainerParams.class); verify(dockerConnector).createContainer(argumentCaptor.capture()); assertTrue(argumentCaptor.getValue().getContainerConfig().getHostConfig().isPublishAllPorts()); } @Test public void shouldStartContainerOnCreateInstanceFromRecipe() throws Exception { createInstanceFromRecipe(); ArgumentCaptor<StartContainerParams> argumentCaptor = ArgumentCaptor.forClass(StartContainerParams.class); verify(dockerConnector).startContainer(argumentCaptor.capture()); assertEquals(argumentCaptor.getValue().getContainer(), CONTAINER_ID); } @Test public void shouldCreateContainerOnInstanceCreationFromSnapshot() throws Exception { // when CheServiceImpl machine = createInstanceFromSnapshot(); // then ArgumentCaptor<CreateContainerParams> argumentCaptor = ArgumentCaptor.forClass(CreateContainerParams.class); verify(dockerConnector).createContainer(argumentCaptor.capture()); assertEquals( argumentCaptor.getValue().getContainerConfig().getImage(), "eclipse-che/" + machine.getContainerName()); } @Test public void shouldPublishAllExposedPortsOnCreateContainerOnInstanceCreationFromSnapshot() throws Exception { // when createInstanceFromSnapshot(); // then ArgumentCaptor<CreateContainerParams> argumentCaptor = ArgumentCaptor.forClass(CreateContainerParams.class); verify(dockerConnector).createContainer(argumentCaptor.capture()); assertTrue(argumentCaptor.getValue().getContainerConfig().getHostConfig().isPublishAllPorts()); } @Test public void shouldBeAbleToCreateContainerWithPrivilegeMode() throws Exception { provider = new MachineProviderBuilder().setPrivilegedMode(true).build(); createInstanceFromRecipe(); ArgumentCaptor<CreateContainerParams> argumentCaptor = ArgumentCaptor.forClass(CreateContainerParams.class); verify(dockerConnector).createContainer(argumentCaptor.capture()); assertTrue(argumentCaptor.getValue().getContainerConfig().getHostConfig().isPrivileged()); } @Test public void shouldBeAbleToCreateContainerWithCpuSet() throws Exception { provider = new MachineProviderBuilder().setCpuSet("0-3").build(); createInstanceFromRecipe(); ArgumentCaptor<CreateContainerParams> argumentCaptor = ArgumentCaptor.forClass(CreateContainerParams.class); verify(dockerConnector).createContainer(argumentCaptor.capture()); assertEquals( argumentCaptor.getValue().getContainerConfig().getHostConfig().getCpusetCpus(), "0-3"); } @Test public void shouldBeAbleToCreateContainerWithCpuPeriod() throws Exception { provider = new MachineProviderBuilder().setCpuPeriod(200).build(); createInstanceFromRecipe(); ArgumentCaptor<CreateContainerParams> argumentCaptor = ArgumentCaptor.forClass(CreateContainerParams.class); verify(dockerConnector).createContainer(argumentCaptor.capture()); assertEquals( ((long) argumentCaptor.getValue().getContainerConfig().getHostConfig().getCpuPeriod()), 200); } @Test(dataProvider = "dnsResolverTestProvider") public void shouldSetDnsResolversOnContainerCreation(String[] dnsResolvers) throws Exception { provider = new MachineProviderBuilder().setDnsResolvers(dnsResolvers).build(); createInstanceFromRecipe(); ArgumentCaptor<CreateContainerParams> argumentCaptor = ArgumentCaptor.forClass(CreateContainerParams.class); verify(dockerConnector).createContainer(argumentCaptor.capture()); assertEqualsNoOrder( argumentCaptor.getValue().getContainerConfig().getHostConfig().getDns(), dnsResolvers); } @DataProvider(name = "dnsResolverTestProvider") public static Object[][] dnsResolverTestProvider() { return new Object[][] { {new String[] {}}, {new String[] {"8.8.8.8", "7.7.7.7", "9.9.9.9"}}, {new String[] {"9.9.9.9"}}, {null}, }; } @Test public void shouldSetNullDnsResolversOnContainerCreationByDefault() throws Exception { provider = new MachineProviderBuilder().build(); createInstanceFromRecipe(); ArgumentCaptor<CreateContainerParams> argumentCaptor = ArgumentCaptor.forClass(CreateContainerParams.class); verify(dockerConnector).createContainer(argumentCaptor.capture()); assertEqualsNoOrder( argumentCaptor.getValue().getContainerConfig().getHostConfig().getDns(), null); } @Test public void shouldBeAbleToCreateContainerWithCgroupParent() throws Exception { provider = new MachineProviderBuilder().setParentCgroup("some_parent").build(); createInstanceFromRecipe(); ArgumentCaptor<CreateContainerParams> argumentCaptor = ArgumentCaptor.forClass(CreateContainerParams.class); verify(dockerConnector).createContainer(argumentCaptor.capture()); assertEquals( argumentCaptor.getValue().getContainerConfig().getHostConfig().getCgroupParent(), "some_parent"); } @Test public void shouldCreateContainerWithPidsLimit() throws Exception { provider = new MachineProviderBuilder().setPidsLimit(512).build(); createInstanceFromRecipe(); ArgumentCaptor<CreateContainerParams> argumentCaptor = ArgumentCaptor.forClass(CreateContainerParams.class); verify(dockerConnector).createContainer(argumentCaptor.capture()); assertEquals( argumentCaptor.getValue().getContainerConfig().getHostConfig().getPidsLimit(), 512); } @Test(expectedExceptions = ServerException.class) public void shouldRemoveContainerInCaseFailedStartContainer() throws Exception { doThrow(IOException.class) .when(dockerConnector) .startContainer(StartContainerParams.create(CONTAINER_ID)); createInstanceFromRecipe(false, WORKSPACE_ID); verify(dockerConnector) .removeContainer( RemoveContainerParams.create(CONTAINER_ID).withRemoveVolumes(true).withForce(true)); } @Test(expectedExceptions = ServerException.class) public void shouldRemoveContainerInCaseFailedGetCreateNode() throws Exception { doThrow(IOException.class).when(dockerMachineFactory).createNode(any(), any()); createInstanceFromRecipe(false, WORKSPACE_ID); verify(dockerConnector) .removeContainer( RemoveContainerParams.create(CONTAINER_ID).withRemoveVolumes(true).withForce(true)); } @Test(expectedExceptions = ServerException.class) public void shouldRemoveContainerInCaseFailedCreateInstanceOnTheDockerMachineFactory() throws Exception { doThrow(IOException.class) .when(dockerMachineFactory) .createInstance(any(), any(), any(), any(), any()); createInstanceFromRecipe(false, WORKSPACE_ID); verify(dockerConnector) .removeContainer( RemoveContainerParams.create(CONTAINER_ID).withRemoveVolumes(true).withForce(true)); } @Test public void shouldStartContainerOnCreateInstanceFromSnapshot() throws Exception { createInstanceFromSnapshot(); ArgumentCaptor<StartContainerParams> argumentCaptor = ArgumentCaptor.forClass(StartContainerParams.class); verify(dockerConnector).startContainer(argumentCaptor.capture()); assertEquals(argumentCaptor.getValue().getContainer(), CONTAINER_ID); } @Test public void shouldCallCreationDockerInstanceWithFactoryOnCreateInstanceFromRecipe() throws Exception { CheServiceImpl service = createService(); createInstanceFromRecipe(service); verify(dockerMachineFactory) .createInstance( any(Machine.class), eq(CONTAINER_ID), eq("eclipse-che/" + service.getContainerName()), eq(dockerNode), any(LineConsumer.class)); } @Test public void shouldSetMemorySizeInContainersOnInstanceCreationFromRecipe() throws Exception { int memorySizeMB = 234; createInstanceFromRecipe(memorySizeMB); ArgumentCaptor<CreateContainerParams> argumentCaptor = ArgumentCaptor.forClass(CreateContainerParams.class); verify(dockerConnector).createContainer(argumentCaptor.capture()); verify(dockerConnector).startContainer(any(StartContainerParams.class)); // docker accepts memory size in bytes assertEquals( argumentCaptor.getValue().getContainerConfig().getHostConfig().getMemory(), memorySizeMB * 1024 * 1024); } @Test public void shouldSetMemorySizeInContainersOnInstanceCreationFromSnapshot() throws Exception { int memorySizeMB = 234; createInstanceFromSnapshot(memorySizeMB); ArgumentCaptor<CreateContainerParams> argumentCaptor = ArgumentCaptor.forClass(CreateContainerParams.class); verify(dockerConnector).createContainer(argumentCaptor.capture()); verify(dockerConnector).startContainer(any(StartContainerParams.class)); // docker accepts memory size in bytes assertEquals( argumentCaptor.getValue().getContainerConfig().getHostConfig().getMemory(), memorySizeMB * 1024 * 1024); } @Test(dataProvider = "swapTestProvider") public void shouldBeAbleToSetCorrectSwapSize( double swapMultiplier, int memoryMB, long expectedSwapSize) throws Exception { // given provider = new MachineProviderBuilder().setMemorySwapMultiplier(swapMultiplier).build(); // when createInstanceFromRecipe(memoryMB); // then ArgumentCaptor<CreateContainerParams> argumentCaptor = ArgumentCaptor.forClass(CreateContainerParams.class); verify(dockerConnector).createContainer(argumentCaptor.capture()); assertEquals( argumentCaptor.getValue().getContainerConfig().getHostConfig().getMemorySwap(), expectedSwapSize); } @DataProvider(name = "swapTestProvider") public static Object[][] swapTestProvider() { return new Object[][] { {-1, 1000, -1}, {0, 1000, 1000L * 1024 * 1024}, {0.7, 1000, (long) (1.7 * 1000 * 1024 * 1024)}, {1, 1000, 2L * 1000 * 1024 * 1024}, {2, 1000, 3L * 1000 * 1024 * 1024}, {2.5, 1000, (long) (3.5 * 1000 * 1024 * 1024)} }; } @Test public void shouldExposeCommonAndDevPortsToContainerOnDevInstanceCreationFromRecipe() throws Exception { List<String> expectedExposedPorts = new ArrayList<>(); final Set<ServerConf> commonServers = new HashSet<>( asList( new ServerConfImpl("reference1", "8080", "http", null), new ServerConfImpl("reference2", "8081", "ftp", null))); expectedExposedPorts.addAll( commonServers.stream().map(ServerConf::getPort).collect(Collectors.toList())); final Set<ServerConf> devServers = new HashSet<>( asList( new ServerConfImpl("reference3", "8082", "https", null), new ServerConfImpl("reference4", "8083", "sftp", null))); expectedExposedPorts.addAll( devServers.stream().map(ServerConf::getPort).collect(Collectors.toList())); provider = new MachineProviderBuilder() .setDevMachineServers(devServers) .setAllMachineServers(commonServers) .build(); final boolean isDev = true; createInstanceFromRecipe(isDev); ArgumentCaptor<CreateContainerParams> argumentCaptor = ArgumentCaptor.forClass(CreateContainerParams.class); verify(dockerConnector).createContainer(argumentCaptor.capture()); assertTrue( new ArrayList<>(argumentCaptor.getValue().getContainerConfig().getExposedPorts().keySet()) .containsAll(expectedExposedPorts)); } @Test public void shouldExposeOnlyCommonPortsToContainerOnNonDevInstanceCreationFromRecipe() throws Exception { List<String> expectedExposedPorts = new ArrayList<>(); final Set<ServerConf> commonServers = new HashSet<>( asList( new ServerConfImpl("reference1", "8080", "http", null), new ServerConfImpl("reference2", "8081", "ftp", null))); expectedExposedPorts.addAll( commonServers.stream().map(ServerConf::getPort).collect(Collectors.toList())); provider = new MachineProviderBuilder().setAllMachineServers(commonServers).build(); final boolean isDev = false; createInstanceFromRecipe(isDev); ArgumentCaptor<CreateContainerParams> argumentCaptor = ArgumentCaptor.forClass(CreateContainerParams.class); verify(dockerConnector).createContainer(argumentCaptor.capture()); assertTrue( new ArrayList<>(argumentCaptor.getValue().getContainerConfig().getExposedPorts().keySet()) .containsAll(expectedExposedPorts)); } @Test public void shouldExposeCommonAndDevPortsToContainerOnDevInstanceCreationFromSnapshot() throws Exception { List<String> expectedExposedPorts = new ArrayList<>(); final Set<ServerConf> commonServers = new HashSet<>( asList( new ServerConfImpl("reference1", "8080", "http", null), new ServerConfImpl("reference2", "8081", "ftp", null))); expectedExposedPorts.addAll( commonServers.stream().map(ServerConf::getPort).collect(Collectors.toList())); final Set<ServerConf> devServers = new HashSet<>( asList( new ServerConfImpl("reference3", "8082", "https", null), new ServerConfImpl("reference4", "8083", "sftp", null))); expectedExposedPorts.addAll( devServers.stream().map(ServerConf::getPort).collect(Collectors.toList())); provider = new MachineProviderBuilder() .setDevMachineServers(devServers) .setAllMachineServers(commonServers) .build(); final boolean isDev = true; createInstanceFromSnapshot(isDev); ArgumentCaptor<CreateContainerParams> argumentCaptor = ArgumentCaptor.forClass(CreateContainerParams.class); verify(dockerConnector).createContainer(argumentCaptor.capture()); assertTrue( new ArrayList<>(argumentCaptor.getValue().getContainerConfig().getExposedPorts().keySet()) .containsAll(expectedExposedPorts)); } @Test public void shouldExposeOnlyCommonPortsToContainerOnNonDevInstanceCreationFromSnapshot() throws Exception { List<String> expectedExposedPorts = new ArrayList<>(); final Set<ServerConf> commonServers = new HashSet<>( asList( new ServerConfImpl("reference1", "8080", "http", null), new ServerConfImpl("reference2", "8081", "ftp", null))); expectedExposedPorts.addAll( commonServers.stream().map(ServerConf::getPort).collect(Collectors.toList())); provider = new MachineProviderBuilder().setAllMachineServers(commonServers).build(); final boolean isDev = false; createInstanceFromSnapshot(isDev); ArgumentCaptor<CreateContainerParams> argumentCaptor = ArgumentCaptor.forClass(CreateContainerParams.class); verify(dockerConnector).createContainer(argumentCaptor.capture()); assertTrue( new ArrayList<>(argumentCaptor.getValue().getContainerConfig().getExposedPorts().keySet()) .containsAll(expectedExposedPorts)); } @Test public void shouldAddServersConfsPortsFromMachineConfigToExposedPortsOnNonDevInstanceCreationFromRecipe() throws Exception { // given final boolean isDev = false; CheServiceImpl machine = createService(); machine.setExpose(asList("9090", "8080")); List<String> expectedExposedPorts = asList("9090", "8080"); // when createInstanceFromRecipe(machine, isDev); // then ArgumentCaptor<CreateContainerParams> argumentCaptor = ArgumentCaptor.forClass(CreateContainerParams.class); verify(dockerConnector).createContainer(argumentCaptor.capture()); assertTrue( new ArrayList<>(argumentCaptor.getValue().getContainerConfig().getExposedPorts().keySet()) .containsAll(expectedExposedPorts)); } @Test public void shouldAddServersConfigsPortsFromMachineConfigToExposedPortsOnDevInstanceCreationFromRecipe() throws Exception { // given final boolean isDev = true; CheServiceImpl machine = createService(); machine.setExpose(asList("9090", "8080")); // when createInstanceFromRecipe(machine, isDev); // then ArgumentCaptor<CreateContainerParams> argumentCaptor = ArgumentCaptor.forClass(CreateContainerParams.class); verify(dockerConnector).createContainer(argumentCaptor.capture()); assertTrue( new ArrayList<>(argumentCaptor.getValue().getContainerConfig().getExposedPorts().keySet()) .containsAll(asList("9090", "8080"))); } @Test public void shouldAddBindMountAndRegularVolumesOnInstanceCreationFromRecipe() throws Exception { String[] bindMountVolumesFromMachine = new String[] { "/my/bind/mount1:/from/host1", "/my/bind/mount2:/from/host2:ro", "/my/bind/mount3:/from/host3:ro,Z" }; String[] volumesFromMachine = new String[] {"/projects", "/something", "/something/else"}; String[] expectedBindMountVolumes = new String[] { "/my/bind/mount1:/from/host1", "/my/bind/mount2:/from/host2:ro", "/my/bind/mount3:/from/host3:ro,Z" }; Map<String, Volume> expectedVolumes = Stream.of("/projects", "/something", "/something/else") .collect(toMap(Function.identity(), v -> new Volume())); provider = new MachineProviderBuilder() .setDevMachineVolumes(emptySet()) .setAllMachineVolumes(emptySet()) .build(); CheServiceImpl service = createService(); service.setVolumes( Stream.concat(Stream.of(bindMountVolumesFromMachine), Stream.of(volumesFromMachine)) .collect(Collectors.toList())); createInstanceFromRecipe(service, true); ArgumentCaptor<CreateContainerParams> argumentCaptor = ArgumentCaptor.forClass(CreateContainerParams.class); verify(dockerConnector).createContainer(argumentCaptor.capture()); String[] actualBindMountVolumes = argumentCaptor.getValue().getContainerConfig().getHostConfig().getBinds(); Map<String, Volume> actualVolumes = argumentCaptor.getValue().getContainerConfig().getVolumes(); assertEquals(actualVolumes, expectedVolumes); assertEqualsNoOrder(actualBindMountVolumes, expectedBindMountVolumes); } @Test public void shouldAddBindMountAndRegularVolumesOnInstanceCreationFromSnapshot() throws Exception { String[] bindMountVolumesFromMachine = new String[] { "/my/bind/mount1:/from/host1", "/my/bind/mount2:/from/host2:ro", "/my/bind/mount3:/from/host3:ro,Z" }; String[] volumesFromMachine = new String[] {"/projects", "/something", "/something/else"}; String[] expectedBindMountVolumes = new String[] { "/my/bind/mount1:/from/host1", "/my/bind/mount2:/from/host2:ro", "/my/bind/mount3:/from/host3:ro,Z" }; Map<String, Volume> expectedVolumes = Stream.of("/projects", "/something", "/something/else") .collect(toMap(Function.identity(), v -> new Volume())); provider = new MachineProviderBuilder() .setDevMachineVolumes(emptySet()) .setAllMachineVolumes(emptySet()) .build(); CheServiceImpl service = createService(); service.setVolumes( Stream.concat(Stream.of(bindMountVolumesFromMachine), Stream.of(volumesFromMachine)) .collect(Collectors.toList())); createInstanceFromSnapshot(service, true); ArgumentCaptor<CreateContainerParams> argumentCaptor = ArgumentCaptor.forClass(CreateContainerParams.class); verify(dockerConnector).createContainer(argumentCaptor.capture()); String[] actualBindMountVolumes = argumentCaptor.getValue().getContainerConfig().getHostConfig().getBinds(); Map<String, Volume> actualVolumes = argumentCaptor.getValue().getContainerConfig().getVolumes(); assertEquals(actualVolumes, expectedVolumes); assertEqualsNoOrder(actualBindMountVolumes, expectedBindMountVolumes); } @Test public void shouldAddAllVolumesOnDevInstanceCreationFromRecipe() throws Exception { String[] bindMountVolumesFromMachine = new String[] { "/my/bind/mount1:/from/host1", "/my/bind/mount2:/from/host2:ro", "/my/bind/mount3:/from/host3:ro,Z" }; String[] volumesFromMachine = new String[] {"/projects", "/something", "/something/else"}; String[] allMachinesSystemVolumes = new String[] { "/some/thing/else:/home/some/thing/else", "/other/path:/home/other/path", "/home/other/path2" }; String[] devMachinesSystemVolumes = new String[] { "/etc:/tmp/etc:ro", "/some/thing:/home/some/thing", "/some/thing2:/home/some/thing2:ro,z", "/home/some/thing3" }; String[] expectedBindMountVolumes = new String[] { "/my/bind/mount1:/from/host1", "/my/bind/mount2:/from/host2:ro", "/my/bind/mount3:/from/host3:ro,Z", "/some/thing/else:/home/some/thing/else", "/other/path:/home/other/path", "/etc:/tmp/etc:ro", "/some/thing:/home/some/thing", "/some/thing2:/home/some/thing2:ro,z" }; Map<String, Volume> expectedVolumes = Stream.of( "/projects", "/something", "/something/else", "/home/other/path2", "/home/some/thing3") .collect(toMap(Function.identity(), v -> new Volume())); provider = new MachineProviderBuilder() .setDevMachineVolumes(new HashSet<>(asList(devMachinesSystemVolumes))) .setAllMachineVolumes(new HashSet<>(asList(allMachinesSystemVolumes))) .build(); CheServiceImpl service = createService(); service.setVolumes( Stream.concat(Stream.of(bindMountVolumesFromMachine), Stream.of(volumesFromMachine)) .collect(Collectors.toList())); createInstanceFromRecipe(service, true); ArgumentCaptor<CreateContainerParams> argumentCaptor = ArgumentCaptor.forClass(CreateContainerParams.class); verify(dockerConnector).createContainer(argumentCaptor.capture()); String[] actualBindMountVolumes = argumentCaptor.getValue().getContainerConfig().getHostConfig().getBinds(); Map<String, Volume> actualVolumes = argumentCaptor.getValue().getContainerConfig().getVolumes(); assertEquals(actualVolumes, expectedVolumes); assertEqualsNoOrder(actualBindMountVolumes, expectedBindMountVolumes); } @Test public void shouldAddAllVolumesOnDevInstanceCreationFromSnapshot() throws Exception { String[] bindMountVolumesFromMachine = new String[] { "/my/bind/mount1:/from/host1", "/my/bind/mount2:/from/host2:ro", "/my/bind/mount3:/from/host3:ro,Z" }; String[] volumesFromMachine = new String[] {"/projects", "/something", "/something/else"}; String[] allMachinesSystemVolumes = new String[] { "/some/thing/else:/home/some/thing/else", "/other/path:/home/other/path", "/home/other/path2" }; String[] devMachinesSystemVolumes = new String[] { "/etc:/tmp/etc:ro", "/some/thing:/home/some/thing", "/some/thing2:/home/some/thing2:ro,z", "/home/some/thing3" }; String[] expectedBindMountVolumes = new String[] { "/my/bind/mount1:/from/host1", "/my/bind/mount2:/from/host2:ro", "/my/bind/mount3:/from/host3:ro,Z", "/some/thing/else:/home/some/thing/else", "/other/path:/home/other/path", "/etc:/tmp/etc:ro", "/some/thing:/home/some/thing", "/some/thing2:/home/some/thing2:ro,z" }; Map<String, Volume> expectedVolumes = Stream.of( "/projects", "/something", "/something/else", "/home/other/path2", "/home/some/thing3") .collect(toMap(Function.identity(), v -> new Volume())); provider = new MachineProviderBuilder() .setDevMachineVolumes(new HashSet<>(asList(devMachinesSystemVolumes))) .setAllMachineVolumes(new HashSet<>(asList(allMachinesSystemVolumes))) .build(); CheServiceImpl service = createService(); service.setVolumes( Stream.concat(Stream.of(bindMountVolumesFromMachine), Stream.of(volumesFromMachine)) .collect(Collectors.toList())); createInstanceFromSnapshot(service, true); ArgumentCaptor<CreateContainerParams> argumentCaptor = ArgumentCaptor.forClass(CreateContainerParams.class); verify(dockerConnector).createContainer(argumentCaptor.capture()); String[] actualBindMountVolumes = argumentCaptor.getValue().getContainerConfig().getHostConfig().getBinds(); Map<String, Volume> actualVolumes = argumentCaptor.getValue().getContainerConfig().getVolumes(); assertEquals(actualVolumes, expectedVolumes); assertEqualsNoOrder(actualBindMountVolumes, expectedBindMountVolumes); } @Test public void shouldAddCommonsSystemVolumesOnlyOnNonDevInstanceCreationFromRecipe() throws Exception { String[] bindMountVolumesFromMachine = new String[] { "/my/bind/mount1:/from/host1", "/my/bind/mount2:/from/host2:ro", "/my/bind/mount3:/from/host3:ro,Z" }; String[] volumesFromMachine = new String[] {"/projects", "/something", "/something/else"}; String[] allMachinesSystemVolumes = new String[] { "/some/thing/else:/home/some/thing/else", "/other/path:/home/other/path", "/home/other/path2" }; String[] devMachinesSystemVolumes = new String[] { "/etc:/tmp/etc:ro", "/some/thing:/home/some/thing", "/some/thing2:/home/some/thing2:ro,z", "/home/some/thing3" }; String[] expectedBindMountVolumes = new String[] { "/my/bind/mount1:/from/host1", "/my/bind/mount2:/from/host2:ro", "/my/bind/mount3:/from/host3:ro,Z", "/some/thing/else:/home/some/thing/else", "/other/path:/home/other/path" }; Map<String, Volume> expectedVolumes = Stream.of("/projects", "/something", "/something/else", "/home/other/path2") .collect(toMap(Function.identity(), v -> new Volume())); provider = new MachineProviderBuilder() .setDevMachineVolumes(new HashSet<>(asList(devMachinesSystemVolumes))) .setAllMachineVolumes(new HashSet<>(asList(allMachinesSystemVolumes))) .build(); CheServiceImpl service = createService(); service.setVolumes( Stream.concat(Stream.of(bindMountVolumesFromMachine), Stream.of(volumesFromMachine)) .collect(Collectors.toList())); createInstanceFromRecipe(service, false); ArgumentCaptor<CreateContainerParams> argumentCaptor = ArgumentCaptor.forClass(CreateContainerParams.class); verify(dockerConnector).createContainer(argumentCaptor.capture()); String[] actualBindMountVolumes = argumentCaptor.getValue().getContainerConfig().getHostConfig().getBinds(); Map<String, Volume> actualVolumes = argumentCaptor.getValue().getContainerConfig().getVolumes(); assertEquals(actualVolumes, expectedVolumes); assertEqualsNoOrder(actualBindMountVolumes, expectedBindMountVolumes); } @Test public void shouldAddCommonsSystemVolumesOnlyOnNonDevInstanceCreationFromSnapshot() throws Exception { String[] bindMountVolumesFromMachine = new String[] { "/my/bind/mount1:/from/host1", "/my/bind/mount2:/from/host2:ro", "/my/bind/mount3:/from/host3:ro,Z" }; String[] volumesFromMachine = new String[] {"/projects", "/something", "/something/else"}; String[] allMachinesSystemVolumes = new String[] { "/some/thing/else:/home/some/thing/else", "/other/path:/home/other/path", "/home/other/path2" }; String[] devMachinesSystemVolumes = new String[] { "/etc:/tmp/etc:ro", "/some/thing:/home/some/thing", "/some/thing2:/home/some/thing2:ro,z", "/home/some/thing3" }; String[] expectedBindMountVolumes = new String[] { "/my/bind/mount1:/from/host1", "/my/bind/mount2:/from/host2:ro", "/my/bind/mount3:/from/host3:ro,Z", "/some/thing/else:/home/some/thing/else", "/other/path:/home/other/path" }; Map<String, Volume> expectedVolumes = Stream.of("/projects", "/something", "/something/else", "/home/other/path2") .collect(toMap(Function.identity(), v -> new Volume())); provider = new MachineProviderBuilder() .setDevMachineVolumes(new HashSet<>(asList(devMachinesSystemVolumes))) .setAllMachineVolumes(new HashSet<>(asList(allMachinesSystemVolumes))) .build(); CheServiceImpl service = createService(); service.setVolumes( Stream.concat(Stream.of(bindMountVolumesFromMachine), Stream.of(volumesFromMachine)) .collect(Collectors.toList())); createInstanceFromSnapshot(service, false); ArgumentCaptor<CreateContainerParams> argumentCaptor = ArgumentCaptor.forClass(CreateContainerParams.class); verify(dockerConnector).createContainer(argumentCaptor.capture()); String[] actualBindMountVolumes = argumentCaptor.getValue().getContainerConfig().getHostConfig().getBinds(); Map<String, Volume> actualVolumes = argumentCaptor.getValue().getContainerConfig().getVolumes(); assertEquals(actualVolumes, expectedVolumes); assertEqualsNoOrder(actualBindMountVolumes, expectedBindMountVolumes); } @Test public void shouldAddExtraHostOnDevInstanceCreationFromRecipe() throws Exception { //given provider = new MachineProviderBuilder().setExtraHosts("dev.box.com:192.168.0.1").build(); final boolean isDev = true; //when createInstanceFromRecipe(isDev); //then ArgumentCaptor<CreateContainerParams> argumentCaptor = ArgumentCaptor.forClass(CreateContainerParams.class); verify(dockerConnector).createContainer(argumentCaptor.capture()); verify(dockerConnector).startContainer(any(StartContainerParams.class)); final String[] extraHosts = argumentCaptor.getValue().getContainerConfig().getHostConfig().getExtraHosts(); assertEquals(extraHosts.length, 1); assertEquals(extraHosts[0], "dev.box.com:192.168.0.1"); } @Test public void shouldAddExtraHostOnDevInstanceCreationFromSnapshot() throws Exception { //given provider = new MachineProviderBuilder() .setExtraHosts("dev.box.com:192.168.0.1", "codenvy.com.com:185") .build(); final boolean isDev = true; //when createInstanceFromSnapshot(isDev); //then ArgumentCaptor<CreateContainerParams> argumentCaptor = ArgumentCaptor.forClass(CreateContainerParams.class); verify(dockerConnector).createContainer(argumentCaptor.capture()); verify(dockerConnector).startContainer(any(StartContainerParams.class)); final String[] extraHosts = argumentCaptor.getValue().getContainerConfig().getHostConfig().getExtraHosts(); assertEquals(extraHosts.length, 2); assertEquals(extraHosts[0], "dev.box.com:192.168.0.1"); assertEquals(extraHosts[1], "codenvy.com.com:185"); } @Test public void shouldAddExtraHostOnNonDevInstanceCreationFromRecipe() throws Exception { //given provider = new MachineProviderBuilder().setExtraHosts("dev.box.com:192.168.0.1").build(); final boolean isDev = false; //when createInstanceFromRecipe(isDev); //then ArgumentCaptor<CreateContainerParams> argumentCaptor = ArgumentCaptor.forClass(CreateContainerParams.class); verify(dockerConnector).createContainer(argumentCaptor.capture()); verify(dockerConnector).startContainer(any(StartContainerParams.class)); final String[] extraHosts = argumentCaptor.getValue().getContainerConfig().getHostConfig().getExtraHosts(); assertEquals(extraHosts.length, 1); assertEquals(extraHosts[0], "dev.box.com:192.168.0.1"); } @Test public void shouldAddExtraHostOnNonDevInstanceCreationFromSnapshot() throws Exception { //given provider = new MachineProviderBuilder() .setExtraHosts("dev.box.com:192.168.0.1", "codenvy.com.com:185") .build(); final boolean isDev = false; //when createInstanceFromSnapshot(isDev); //then ArgumentCaptor<CreateContainerParams> argumentCaptor = ArgumentCaptor.forClass(CreateContainerParams.class); verify(dockerConnector).createContainer(argumentCaptor.capture()); verify(dockerConnector).startContainer(any(StartContainerParams.class)); final String[] extraHosts = argumentCaptor.getValue().getContainerConfig().getHostConfig().getExtraHosts(); assertEquals(extraHosts.length, 2); assertEquals(extraHosts[0], "dev.box.com:192.168.0.1"); assertEquals(extraHosts[1], "codenvy.com.com:185"); } @Test public void shouldAddWorkspaceIdEnvVariableOnDevInstanceCreationFromRecipe() throws Exception { String wsId = "myWs"; createInstanceFromRecipe(true, wsId); ArgumentCaptor<CreateContainerParams> argumentCaptor = ArgumentCaptor.forClass(CreateContainerParams.class); verify(dockerConnector).createContainer(argumentCaptor.capture()); assertTrue( asList(argumentCaptor.getValue().getContainerConfig().getEnv()) .contains(DockerInstanceRuntimeInfo.CHE_WORKSPACE_ID + "=" + wsId), "Workspace Id variable is missing. Required " + DockerInstanceRuntimeInfo.CHE_WORKSPACE_ID + "=" + wsId + ". Found " + Arrays.toString(argumentCaptor.getValue().getContainerConfig().getEnv())); } @Test public void shouldAddMachineNameEnvVariableOnDevInstanceCreationFromRecipe() throws Exception { String wsId = "myWs"; createInstanceFromRecipe(true, wsId); ArgumentCaptor<CreateContainerParams> argumentCaptor = ArgumentCaptor.forClass(CreateContainerParams.class); verify(dockerConnector).createContainer(argumentCaptor.capture()); assertTrue( asList(argumentCaptor.getValue().getContainerConfig().getEnv()) .contains(DockerInstanceRuntimeInfo.CHE_MACHINE_NAME + "=" + MACHINE_NAME), "Machine Name variable is missing. Required " + DockerInstanceRuntimeInfo.CHE_MACHINE_NAME + "=" + MACHINE_NAME + ". Found " + Arrays.toString(argumentCaptor.getValue().getContainerConfig().getEnv())); } @Test public void shouldAddMachineNameEnvVariableOnNonDevInstanceCreationFromRecipe() throws Exception { String wsId = "myWs"; createInstanceFromRecipe(false, wsId); ArgumentCaptor<CreateContainerParams> argumentCaptor = ArgumentCaptor.forClass(CreateContainerParams.class); verify(dockerConnector).createContainer(argumentCaptor.capture()); assertTrue( asList(argumentCaptor.getValue().getContainerConfig().getEnv()) .contains(DockerInstanceRuntimeInfo.CHE_MACHINE_NAME + "=" + MACHINE_NAME), "Machine Name variable is missing. Required " + DockerInstanceRuntimeInfo.CHE_MACHINE_NAME + "=" + MACHINE_NAME + ". Found " + Arrays.toString(argumentCaptor.getValue().getContainerConfig().getEnv())); } @Test public void shouldAddWorkspaceIdEnvVariableOnDevInstanceCreationFromSnapshot() throws Exception { String wsId = "myWs"; createInstanceFromSnapshot(true, wsId); ArgumentCaptor<CreateContainerParams> argumentCaptor = ArgumentCaptor.forClass(CreateContainerParams.class); verify(dockerConnector).createContainer(argumentCaptor.capture()); assertTrue( asList(argumentCaptor.getValue().getContainerConfig().getEnv()) .contains(DockerInstanceRuntimeInfo.CHE_WORKSPACE_ID + "=" + wsId), "Workspace Id variable is missing. Required " + DockerInstanceRuntimeInfo.CHE_WORKSPACE_ID + "=" + wsId + ". Found " + Arrays.toString(argumentCaptor.getValue().getContainerConfig().getEnv())); } @Test public void shouldAddWorkspaceIdEnvVariableOnNonDevInstanceCreationFromRecipe() throws Exception { String wsId = "myWs"; createInstanceFromRecipe(false, wsId); ArgumentCaptor<CreateContainerParams> argumentCaptor = ArgumentCaptor.forClass(CreateContainerParams.class); verify(dockerConnector).createContainer(argumentCaptor.capture()); assertTrue( asList(argumentCaptor.getValue().getContainerConfig().getEnv()) .contains(DockerInstanceRuntimeInfo.CHE_WORKSPACE_ID + "=" + wsId), "Non dev machine should contains " + DockerInstanceRuntimeInfo.CHE_WORKSPACE_ID); } @Test public void shouldAddCommonAndDevEnvVariablesToContainerOnDevInstanceCreationFromRecipe() throws Exception { Set<String> commonEnv = new HashSet<>(asList("ENV_VAR1=123", "ENV_VAR2=234")); Set<String> devEnv = new HashSet<>(asList("DEV_ENV_VAR1=345", "DEV_ENV_VAR2=456", "DEV_ENV_VAR3=567")); Set<String> expectedEnv = new HashSet<>(); expectedEnv.addAll(commonEnv); expectedEnv.addAll(devEnv); expectedEnv.add(DockerInstanceRuntimeInfo.USER_TOKEN + "=" + USER_TOKEN); expectedEnv.add(DockerInstanceRuntimeInfo.CHE_WORKSPACE_ID + "=" + WORKSPACE_ID); provider = new MachineProviderBuilder() .setDevMachineEnvVars(devEnv) .setAllMachineEnvVars(commonEnv) .build(); final boolean isDev = true; createInstanceFromRecipe(isDev); ArgumentCaptor<CreateContainerParams> argumentCaptor = ArgumentCaptor.forClass(CreateContainerParams.class); verify(dockerConnector).createContainer(argumentCaptor.capture()); assertTrue( new HashSet<>(asList(argumentCaptor.getValue().getContainerConfig().getEnv())) .containsAll(expectedEnv)); } @Test public void shouldNotAddDevEnvToCommonEnvVariablesToContainerOnNonDevInstanceCreationFromRecipe() throws Exception { Set<String> commonEnv = new HashSet<>(asList("ENV_VAR1=123", "ENV_VAR2=234")); Set<String> devEnv = new HashSet<>(asList("DEV_ENV_VAR1=345", "DEV_ENV_VAR2=456", "DEV_ENV_VAR3=567")); provider = new MachineProviderBuilder() .setDevMachineEnvVars(devEnv) .setAllMachineEnvVars(commonEnv) .build(); final boolean isDev = false; createInstanceFromRecipe(isDev); ArgumentCaptor<CreateContainerParams> argumentCaptor = ArgumentCaptor.forClass(CreateContainerParams.class); verify(dockerConnector).createContainer(argumentCaptor.capture()); assertTrue( new HashSet<>(asList(argumentCaptor.getValue().getContainerConfig().getEnv())) .containsAll(commonEnv)); } @Test public void shouldAddCommonAndDevEnvVariablesToContainerOnDevInstanceCreationFromSnapshot() throws Exception { Set<String> commonEnv = new HashSet<>(asList("ENV_VAR1=123", "ENV_VAR2=234")); Set<String> devEnv = new HashSet<>(asList("DEV_ENV_VAR1=345", "DEV_ENV_VAR2=456", "DEV_ENV_VAR3=567")); Set<String> expectedEnv = new HashSet<>(); expectedEnv.addAll(commonEnv); expectedEnv.addAll(devEnv); expectedEnv.add(DockerInstanceRuntimeInfo.USER_TOKEN + "=" + USER_TOKEN); expectedEnv.add(DockerInstanceRuntimeInfo.CHE_WORKSPACE_ID + "=" + WORKSPACE_ID); provider = new MachineProviderBuilder() .setDevMachineEnvVars(devEnv) .setAllMachineEnvVars(commonEnv) .build(); final boolean isDev = true; createInstanceFromSnapshot(isDev); ArgumentCaptor<CreateContainerParams> argumentCaptor = ArgumentCaptor.forClass(CreateContainerParams.class); verify(dockerConnector).createContainer(argumentCaptor.capture()); assertTrue( new HashSet<>(asList(argumentCaptor.getValue().getContainerConfig().getEnv())) .containsAll(expectedEnv)); } @Test public void shouldNotAddDevEnvToCommonEnvVariablesToContainerOnNonDevInstanceCreationFromSnapshot() throws Exception { Set<String> commonEnv = new HashSet<>(asList("ENV_VAR1=123", "ENV_VAR2=234")); Set<String> devEnv = new HashSet<>(asList("DEV_ENV_VAR1=345", "DEV_ENV_VAR2=456", "DEV_ENV_VAR3=567")); provider = new MachineProviderBuilder() .setDevMachineEnvVars(devEnv) .setAllMachineEnvVars(commonEnv) .build(); final boolean isDev = false; createInstanceFromSnapshot(isDev); ArgumentCaptor<CreateContainerParams> argumentCaptor = ArgumentCaptor.forClass(CreateContainerParams.class); verify(dockerConnector).createContainer(argumentCaptor.capture()); assertTrue( new HashSet<>(asList(argumentCaptor.getValue().getContainerConfig().getEnv())) .containsAll(commonEnv)); } @Test public void shouldAddEnvVarsFromMachineConfigToContainerOnNonDevInstanceCreationFromSnapshot() throws Exception { // given Map<String, String> envVarsFromConfig = new HashMap<>(); envVarsFromConfig.put("ENV_VAR1", "123"); envVarsFromConfig.put("ENV_VAR2", "234"); final boolean isDev = false; CheServiceImpl machine = createService(); machine.setEnvironment(envVarsFromConfig); // when createInstanceFromSnapshot(machine, isDev); // then ArgumentCaptor<CreateContainerParams> argumentCaptor = ArgumentCaptor.forClass(CreateContainerParams.class); verify(dockerConnector).createContainer(argumentCaptor.capture()); assertTrue( asList(argumentCaptor.getValue().getContainerConfig().getEnv()) .containsAll( envVarsFromConfig .entrySet() .stream() .map(entry -> entry.getKey() + "=" + entry.getValue()) .collect(Collectors.toList()))); } @Test public void shouldAddEnvVarsFromMachineConfigToContainerOnDevInstanceCreationFromSnapshot() throws Exception { // given Map<String, String> envVarsFromConfig = new HashMap<>(); envVarsFromConfig.put("ENV_VAR1", "123"); envVarsFromConfig.put("ENV_VAR2", "234"); final boolean isDev = true; CheServiceImpl machine = createService(); machine.setEnvironment(envVarsFromConfig); // when createInstanceFromSnapshot(machine, isDev); // then ArgumentCaptor<CreateContainerParams> argumentCaptor = ArgumentCaptor.forClass(CreateContainerParams.class); verify(dockerConnector).createContainer(argumentCaptor.capture()); assertTrue( asList(argumentCaptor.getValue().getContainerConfig().getEnv()) .containsAll( envVarsFromConfig .entrySet() .stream() .map(entry -> entry.getKey() + "=" + entry.getValue()) .collect(Collectors.toList()))); } @Test public void shouldAddEnvVarsFromMachineConfigToContainerOnNonDevInstanceCreationFromRecipe() throws Exception { // given Map<String, String> envVarsFromConfig = new HashMap<>(); envVarsFromConfig.put("ENV_VAR1", "123"); envVarsFromConfig.put("ENV_VAR2", "234"); final boolean isDev = false; CheServiceImpl service = createService(); service.setEnvironment(envVarsFromConfig); // when createInstanceFromRecipe(service, isDev); // then ArgumentCaptor<CreateContainerParams> argumentCaptor = ArgumentCaptor.forClass(CreateContainerParams.class); verify(dockerConnector).createContainer(argumentCaptor.capture()); assertTrue( asList(argumentCaptor.getValue().getContainerConfig().getEnv()) .containsAll( envVarsFromConfig .entrySet() .stream() .map(entry -> entry.getKey() + "=" + entry.getValue()) .collect(Collectors.toList()))); } @Test public void shouldAddEnvVarsFromMachineConfigToContainerOnDevInstanceCreationFromRecipe() throws Exception { // given Map<String, String> envVarsFromConfig = new HashMap<>(); envVarsFromConfig.put("ENV_VAR1", "123"); envVarsFromConfig.put("ENV_VAR2", "234"); final boolean isDev = true; CheServiceImpl machine = createService(); machine.setEnvironment(envVarsFromConfig); // when createInstanceFromRecipe(machine, isDev); // then ArgumentCaptor<CreateContainerParams> argumentCaptor = ArgumentCaptor.forClass(CreateContainerParams.class); verify(dockerConnector).createContainer(argumentCaptor.capture()); assertTrue( asList(argumentCaptor.getValue().getContainerConfig().getEnv()) .containsAll( envVarsFromConfig .entrySet() .stream() .map(entry -> entry.getKey() + "=" + entry.getValue()) .collect(Collectors.toList()))); } @Test public void shouldAddLinksToContainerOnCreation() throws Exception { // given String links[] = new String[] {"container1", "container2:alias"}; CheServiceImpl service = createService(); service.setLinks(asList(links)); // when createInstanceFromRecipe(service, true); // then ArgumentCaptor<CreateContainerParams> argumentCaptor = ArgumentCaptor.forClass(CreateContainerParams.class); verify(dockerConnector).createContainer(argumentCaptor.capture()); ContainerConfig containerConfig = argumentCaptor.getValue().getContainerConfig(); assertEquals(containerConfig.getHostConfig().getLinks(), links); assertEquals( containerConfig.getNetworkingConfig().getEndpointsConfig().get(NETWORK_NAME).getLinks(), links); } @Test public void shouldBeAbleToCreateContainerWithCpuQuota() throws Exception { // given provider = new MachineProviderBuilder().setCpuQuota(200).build(); // when createInstanceFromRecipe(); // then ArgumentCaptor<CreateContainerParams> argumentCaptor = ArgumentCaptor.forClass(CreateContainerParams.class); verify(dockerConnector).createContainer(argumentCaptor.capture()); assertEquals( ((long) argumentCaptor.getValue().getContainerConfig().getHostConfig().getCpuQuota()), 200); } @Test(dataProvider = "terminatingContainerEntrypointCmd") public void shouldChangeEntrypointCmdToTailfDevNullIfTheyAreIdentifiedAsTerminating( String[] entrypoint, String[] cmd) throws Exception { // given when(imageConfig.getCmd()).thenReturn(cmd); when(imageConfig.getEntrypoint()).thenReturn(entrypoint); // when createInstanceFromRecipe(); // then ArgumentCaptor<CreateContainerParams> argumentCaptor = ArgumentCaptor.forClass(CreateContainerParams.class); verify(dockerConnector).createContainer(argumentCaptor.capture()); assertNull(argumentCaptor.getValue().getContainerConfig().getEntrypoint()); assertEquals( argumentCaptor.getValue().getContainerConfig().getCmd(), new String[] {"tail", "-f", "/dev/null"}); } @DataProvider(name = "terminatingContainerEntrypointCmd") public static Object[][] terminatingContainerEntrypointCmd() { return new Object[][] { // entrypoint and cmd are unset {null, null}, // entrypoint is unset {null, new String[] {"/bin/bash"}}, {null, new String[] {"/bin/sh"}}, {null, new String[] {"bash"}}, {null, new String[] {"sh"}}, {null, new String[] {"/bin/sh", "-c", "/bin/bash"}}, {null, new String[] {"/bin/sh", "-c", "/bin/sh"}}, {null, new String[] {"/bin/sh", "-c", "bash"}}, {null, new String[] {"/bin/sh", "-c", "sh"}}, // cmd is unset {new String[] {"/bin/sh", "-c"}, null}, {new String[] {"/bin/bash", "-c"}, null}, {new String[] {"bash", "-c"}, null}, {new String[] {"sh", "-c"}, null}, {new String[] {"/bin/bash"}, null}, {new String[] {"/bin/sh"}, null}, {new String[] {"bash"}, null}, {new String[] {"sh"}, null}, {new String[] {"/bin/sh", "-c", "/bin/bash"}, null}, {new String[] {"/bin/sh", "-c", "/bin/sh"}, null}, {new String[] {"/bin/sh", "-c", "bash"}, null}, {new String[] {"/bin/sh", "-c", "sh"}, null}, // entrypoint and cmd are set {new String[] {"/bin/sh", "-c"}, new String[] {"bash"}}, {new String[] {"/bin/bash", "-c"}, new String[] {"sh"}}, {new String[] {"bash", "-c"}, new String[] {"/bin/bash"}}, {new String[] {"sh", "-c"}, new String[] {"/bin/sh"}}, {new String[] {"/bin/bash"}, new String[] {"/bin/bash"}}, {new String[] {"/bin/sh"}, new String[] {"/bin/bash"}}, {new String[] {"bash"}, new String[] {"/bin/bash"}}, {new String[] {"sh"}, new String[] {"/bin/bash"}}, {new String[] {"/bin/sh", "-c", "/bin/bash"}, new String[] {"/bin/bash"}}, {new String[] {"/bin/sh", "-c", "/bin/sh"}, new String[] {"/bin/bash"}}, {new String[] {"/bin/sh", "-c", "bash"}, new String[] {"/bin/bash"}}, {new String[] {"/bin/sh", "-c", "sh"}, new String[] {"/bin/bash"}}, }; } @Test(dataProvider = "nonTerminatingContainerEntrypointCmd") public void shouldNotChangeEntrypointCmdIfTheyAreNotIdentified(String[] entrypoint, String[] cmd) throws Exception { // given when(imageConfig.getCmd()).thenReturn(cmd); when(imageConfig.getEntrypoint()).thenReturn(entrypoint); // when createInstanceFromRecipe(); // then ArgumentCaptor<CreateContainerParams> argumentCaptor = ArgumentCaptor.forClass(CreateContainerParams.class); verify(dockerConnector).createContainer(argumentCaptor.capture()); assertEqualsNoOrder( argumentCaptor.getValue().getContainerConfig().getEntrypoint(), DEFAULT_ENTRYPOINT); assertEqualsNoOrder(argumentCaptor.getValue().getContainerConfig().getCmd(), DEFAULT_CMD); } @DataProvider(name = "nonTerminatingContainerEntrypointCmd") public static Object[][] nonTerminatingContainerEntrypointCmd() { return new Object[][] { {new String[] {"/bin/sh", "-c"}, new String[] {"tail", "-f", "/dev/null"}}, {new String[] {"/bin/sh", "-c"}, new String[] {"tailf", "/dev/null"}}, {new String[] {"/bin/sh", "-c"}, new String[] {"./entrypoint.sh", "something"}}, {new String[] {"/bin/sh", "-c"}, new String[] {"./entrypoint.sh"}}, {new String[] {"/bin/sh", "-c"}, new String[] {"ping google.com"}}, {new String[] {"sh", "-c"}, new String[] {"./entrypoint.sh"}}, {new String[] {"bash", "-c"}, new String[] {"./entrypoint.sh"}}, {new String[] {"/bin/bash", "-c"}, new String[] {"./entrypoint.sh"}}, // terminating cmd but we don't recognize it since it is not used luckily and we should limit // list of handled variants {new String[] {"/bin/sh", "-c"}, new String[] {"echo", "something"}}, {new String[] {"/bin/sh", "-c"}, new String[] {"ls"}}, }; } @Test(dataProvider = "acceptableStartedContainerStatus") public void shouldNotThrowExceptionIfContainerStatusIsAcceptable(String status) throws Exception { // given when(containerState.getStatus()).thenReturn(status); // when createInstanceFromRecipe(); // then verify(dockerConnector).inspectContainer(CONTAINER_ID); verify(containerState).getStatus(); } @DataProvider(name = "acceptableStartedContainerStatus") public static Object[][] acceptableStartedContainerStatus() { return new Object[][] { // in case status is not returned for some reason, e.g. docker doesn't provide it {null}, // expected status {"running"}, // unknown status, pass for compatibility {"some thing"} }; } @Test( expectedExceptions = ServerException.class, expectedExceptionsMessageRegExp = MachineProviderImpl.CONTAINER_EXITED_ERROR ) public void shouldThrowExceptionIfContainerExitedRightAfterStart() throws Exception { // given when(containerState.getStatus()).thenReturn("exited"); // when createInstanceFromRecipe(); } private CheServiceImpl createInstanceFromRecipe() throws Exception { CheServiceImpl service = createService(); createInstanceFromRecipe(service); return service; } private void createInstanceFromRecipe(boolean isDev) throws Exception { createInstanceFromRecipe(createService(), isDev, WORKSPACE_ID); } private void createInstanceFromRecipe(boolean isDev, String workspaceId) throws Exception { createInstanceFromRecipe(createService(), isDev, workspaceId); } private void createInstanceFromRecipe(int memorySizeInMB) throws Exception { CheServiceImpl machine = createService(); machine.setMemLimit(memorySizeInMB * 1024L * 1024L); createInstanceFromRecipe(machine); } private CheServiceImpl createInstanceFromSnapshot(String repo, String tag, String registry) throws ServerException { CheServiceImpl machine = createService(); machine.setImage(registry + "/" + repo + ":" + tag); machine.setBuild(null); createInstanceFromSnapshot(machine); return machine; } private void createInstanceFromRecipe(CheServiceImpl service, boolean isDev) throws Exception { createInstanceFromRecipe(service, isDev, WORKSPACE_ID); } private void createInstanceFromRecipe(CheServiceImpl service) throws Exception { createInstanceFromRecipe(service, false, WORKSPACE_ID); } private void createInstanceFromRecipe(CheServiceImpl service, boolean isDev, String workspaceId) throws Exception { provider.startService( USER_NAME, workspaceId, ENV_NAME, MACHINE_NAME, isDev, NETWORK_NAME, service, LineConsumer.DEV_NULL); } private CheServiceImpl createInstanceFromSnapshot() throws ServerException { CheServiceImpl service = createService(); createInstanceFromSnapshot(service, false, WORKSPACE_ID); return service; } private void createInstanceFromSnapshot(CheServiceImpl service) throws ServerException { createInstanceFromSnapshot(service, false, WORKSPACE_ID); } private void createInstanceFromSnapshot(int memorySizeInMB) throws ServerException { CheServiceImpl machine = createService(); machine.setMemLimit(memorySizeInMB * 1024L * 1024L); createInstanceFromSnapshot(machine, false, WORKSPACE_ID); } private void createInstanceFromSnapshot(boolean isDev) throws ServerException { createInstanceFromSnapshot(createService(), isDev, WORKSPACE_ID); } private void createInstanceFromSnapshot(boolean isDev, String workspaceId) throws ServerException { createInstanceFromSnapshot(createService(), isDev, workspaceId); } private void createInstanceFromSnapshot(CheServiceImpl service, boolean isDev) throws ServerException { createInstanceFromSnapshot(service, isDev, WORKSPACE_ID); } private void createInstanceFromSnapshot(CheServiceImpl service, boolean isDev, String workspaceId) throws ServerException { provider.startService( USER_NAME, workspaceId, ENV_NAME, MACHINE_NAME, isDev, NETWORK_NAME, service, LineConsumer.DEV_NULL); } private CheServiceImpl createService() { CheServiceImpl service = new CheServiceImpl(); service.setId("testId"); service.setImage("image"); service.setCommand(asList(DEFAULT_CMD)); service.setContainerName("cont_name"); service.setDependsOn(asList("dep1", "dep2")); service.setEntrypoint(asList(DEFAULT_ENTRYPOINT)); service.setExpose(asList("1010", "1111")); service.setEnvironment(singletonMap("some", "var")); service.setLabels(singletonMap("some", "label")); service.setLinks(asList("link1", "link2:alias")); service.setMemLimit(1000000000L); service.setPorts(asList("port1", "port2")); service.setVolumes(asList("vol1", "vol2")); service.setVolumesFrom(asList("from1", "from2")); return service; } private class MachineProviderBuilder { private Set<ServerConf> devMachineServers; private Set<ServerConf> allMachineServers; private Set<String> devMachineVolumes; private Set<String> allMachineVolumes; private Set<Set<String>> extraHosts; private boolean doForcePullImage; private boolean privilegedMode; private int pidsLimit; private Set<String> devMachineEnvVars; private Set<String> allMachineEnvVars; private boolean snapshotUseRegistry; private Set<Set<String>> additionalNetworks; private double memorySwapMultiplier; private String networkDriver; private String parentCgroup; private String cpuSet; private long cpuPeriod; private long cpuQuota; private String[] dnsResolvers; public MachineProviderBuilder() { devMachineEnvVars = emptySet(); allMachineEnvVars = emptySet(); snapshotUseRegistry = SNAPSHOT_USE_REGISTRY; privilegedMode = false; doForcePullImage = false; additionalNetworks = emptySet(); devMachineServers = emptySet(); allMachineServers = emptySet(); devMachineVolumes = emptySet(); allMachineVolumes = emptySet(); extraHosts = emptySet(); memorySwapMultiplier = MEMORY_SWAP_MULTIPLIER; pidsLimit = -1; } public MachineProviderBuilder setDevMachineEnvVars(Set<String> devMachineEnvVars) { this.devMachineEnvVars = devMachineEnvVars; return this; } public MachineProviderBuilder setAllMachineEnvVars(Set<String> allMachineEnvVars) { this.allMachineEnvVars = allMachineEnvVars; return this; } public MachineProviderBuilder setSnapshotUseRegistry(boolean snapshotUseRegistry) { this.snapshotUseRegistry = snapshotUseRegistry; return this; } public MachineProviderBuilder setDoForcePullImage(boolean doForcePullImage) { this.doForcePullImage = doForcePullImage; return this; } public MachineProviderBuilder setPrivilegedMode(boolean privilegedMode) { this.privilegedMode = privilegedMode; return this; } public MachineProviderBuilder setPidsLimit(int pidsLimit) { this.pidsLimit = pidsLimit; return this; } public MachineProviderBuilder setMemorySwapMultiplier(double memorySwapMultiplier) { this.memorySwapMultiplier = memorySwapMultiplier; return this; } public MachineProviderBuilder setDevMachineServers(Set<ServerConf> devMachineServers) { this.devMachineServers = devMachineServers; return this; } public MachineProviderBuilder setAllMachineServers(Set<ServerConf> allMachineServers) { this.allMachineServers = allMachineServers; return this; } public MachineProviderBuilder setAllMachineVolumes(Set<String> allMachineVolumes) { this.allMachineVolumes = allMachineVolumes; return this; } public MachineProviderBuilder setDevMachineVolumes(Set<String> devMachineVolumes) { this.devMachineVolumes = devMachineVolumes; return this; } public MachineProviderBuilder setExtraHosts(String... extraHosts) { this.extraHosts = singleton(new HashSet<>(Arrays.asList(extraHosts))); return this; } public MachineProviderBuilder setNetworkDriver(String networkDriver) { this.networkDriver = networkDriver; return this; } public MachineProviderBuilder setParentCgroup(String parentCgroup) { this.parentCgroup = parentCgroup; return this; } public MachineProviderBuilder setCpuSet(String cpuSet) { this.cpuSet = cpuSet; return this; } public MachineProviderBuilder setCpuPeriod(long cpuPeriod) { this.cpuPeriod = cpuPeriod; return this; } public MachineProviderBuilder setCpuQuota(long cpuQuota) { this.cpuQuota = cpuQuota; return this; } public MachineProviderBuilder setDnsResolvers(String[] dnsResolvers) { this.dnsResolvers = dnsResolvers; return this; } MachineProviderImpl build() throws IOException { MachineProviderImpl provider = spy( new MachineProviderImpl( new MockConnectorProvider(), credentialsReader, dockerMachineFactory, dockerInstanceStopDetector, transmitter, jsonRpcEndpointToMachineNameHolder, devMachineServers, allMachineServers, devMachineVolumes, allMachineVolumes, doForcePullImage, privilegedMode, pidsLimit, devMachineEnvVars, allMachineEnvVars, snapshotUseRegistry, memorySwapMultiplier, additionalNetworks, networkDriver, parentCgroup, cpuSet, cpuPeriod, cpuQuota, pathEscaper, extraHosts, dnsResolvers, emptyMap())); doNothing() .when(provider) .readContainerLogsInSeparateThread( anyString(), anyString(), anyString(), any(LineConsumer.class)); return provider; } } }
epl-1.0
epsilonlabs/epsilon-static-analysis
org.eclipse.epsilon.haetae.eol.metamodel.visitor.printer/src/org/eclipse/epsilon/eol/visitor/printer/impl/MapExpressionPrinter.java
1030
package org.eclipse.epsilon.eol.visitor.printer.impl; import org.eclipse.epsilon.eol.visitor.printer.context.EOLPrinterContext; import org.eclipse.epsilon.eol.metamodel.MapExpression; import org.eclipse.epsilon.eol.metamodel.visitor.EolVisitorController; import org.eclipse.epsilon.eol.metamodel.visitor.MapExpressionVisitor; public class MapExpressionPrinter extends MapExpressionVisitor<EOLPrinterContext, Object>{ @Override public Object visit(MapExpression mapExpression, EOLPrinterContext context, EolVisitorController<EOLPrinterContext, Object> controller) { String result = "Map{"; if (mapExpression.getKeyValues() != null && mapExpression.getKeyValues().size() >0) { result += controller.visit(mapExpression.getKeyValues().get(0), context); for(int i = 1; i < mapExpression.getKeyValues().size(); i++) { result += "," + controller.visit(mapExpression.getKeyValues().get(i), context); } } if (mapExpression.isInBrackets()) { result = "(" + result + ")"; } return result; } }
epl-1.0
alastrina123/debrief
org.mwc.debrief.legacy/src/Debrief/Tools/Operations/DebriefWriteVRML.java
6133
/* * Debrief - the Open Source Maritime Analysis Application * http://debrief.info * * (C) 2000-2014, PlanetMayo Ltd * * This library is free software; you can redistribute it and/or * modify it under the terms of the Eclipse Public License v1.0 * (http://www.eclipse.org/legal/epl-v10.html) * * 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. */ // $RCSfile: DebriefWriteVRML.java,v $ // $Author: Ian.Mayo $ // $Log: DebriefWriteVRML.java,v $ // Revision 1.5 2005/12/13 09:04:45 Ian.Mayo // Tidying - as recommended by Eclipse // // Revision 1.4 2004/11/25 10:24:32 Ian.Mayo // Switch to Hi Res dates // // Revision 1.3 2004/11/22 13:41:03 Ian.Mayo // Replace old variable name used for stepping through enumeration, since it is now part of language (Jdk1.5) // // Revision 1.2 2004/09/09 10:23:07 Ian.Mayo // Reflect method name change in Layer interface // // Revision 1.1.1.2 2003/07/21 14:48:28 Ian.Mayo // Re-import Java files to keep correct line spacing // // Revision 1.3 2003-03-19 15:37:03+00 ian_mayo // improvements according to IntelliJ inspector // // Revision 1.2 2002-05-28 12:28:24+01 ian_mayo // after update // // Revision 1.1 2002-05-28 09:11:57+01 ian_mayo // Initial revision // // Revision 1.1 2002-04-23 12:28:55+01 ian_mayo // Initial revision // // Revision 1.0 2001-07-17 08:41:18+01 administrator // Initial revision // // Revision 1.2 2001-01-09 10:27:34+00 novatech // use WatchableList instead of TrackWrapper // // Revision 1.1 2001-01-03 13:40:30+00 novatech // Initial revision // // Revision 1.1.1.1 2000/12/12 20:48:16 ianmayo // initial import of files // // Revision 1.3 2000-11-02 16:45:48+00 ian_mayo // changing Layer into Interface, replaced by BaseLayer, also changed TrackWrapper so that it implements Layer, and as we read in files, we put them into track and add Track to Layers, not to Layer then Layers // // Revision 1.2 2000-09-28 12:09:39+01 ian_mayo // switch to GMT time zone // // Revision 1.1 2000-08-23 09:35:23+01 ian_mayo // Initial revision // package Debrief.Tools.Operations; import java.text.ParseException; import java.util.*; import MWC.GUI.Editable; import MWC.GUI.Layer; import MWC.GenericData.WorldLocation; import MWC.Utilities.TextFormatting.DebriefFormatDateTime; /** * Code to plot the debrief-specific components of the VRML file * * @author IAN MAYO */ final class DebriefWriteVRML extends MWC.GUI.Tools.Operations.WriteVRML { /** * Creates new DebriefWriteVRML * * @param theParent the parent application for the Action we are creating * @param theLabel the label for the plot button * @param theData the data we are going to plot */ public DebriefWriteVRML(final MWC.GUI.ToolParent theParent, final String theLabel, final MWC.GUI.Layers theData) { super(theParent, theLabel, theData); } /** * over-ridden method, where we write out our data * * @param theData the data to plot * @param out the stream to write to * @throws java.io.IOException file-related troubles */ protected final void plotData(final MWC.GUI.Layers theData, final java.io.BufferedWriter out) throws java.io.IOException { final java.text.DateFormat df = new java.text.SimpleDateFormat("ddHHmm"); df.setTimeZone(TimeZone.getTimeZone("GMT")); // work through the layers int num = _theData.size(); for (int i = 0; i < num; i++) { final Layer l = (Layer) _theData.elementAt(i); final Enumeration<Editable> iter = l.elements(); while (iter.hasMoreElements()) { final Object oj = iter.nextElement(); if (oj instanceof Debrief.Wrappers.FixWrapper) { final Debrief.Wrappers.FixWrapper fw = (Debrief.Wrappers.FixWrapper) oj; final WorldLocation pos = fw.getLocation(); if (fw.getSymbolShowing()) { final String lbl = fw.getName(); try { writeBox(out, pos.getLong(), pos.getLat(), pos.getDepth(), fw.getColor(), lbl); } catch (ParseException e) { MWC.Utilities.Errors.Trace.trace(e); } } if (fw.getLabelShowing()) { final String str = DebriefFormatDateTime.toStringHiRes(fw.getTime()); writeText(out, pos.getLong(), pos.getLat(), pos.getDepth(), str, fw.getColor()); } } } } // now draw the line connectors num = _theData.size(); for (int i = 0; i < num; i++) { final Layer l = (Layer) _theData.elementAt(i); final Enumeration<Editable> iter = l.elements(); int len = 0; while (iter.hasMoreElements()) { final Object oj = iter.nextElement(); if (oj instanceof MWC.GenericData.WatchableList) { // just check that we haven't got any dangling Fix lines // waiting to be finished if (len > 0) { // we have clearly written some fixes to the file, write the footer writeLineFooter(out, len); len = 0; } final MWC.GenericData.WatchableList tw = (MWC.GenericData.WatchableList) oj; final java.awt.Color col = tw.getColor(); writeLineHeader(out, col); } if (oj instanceof Debrief.Wrappers.FixWrapper) { len++; final Debrief.Wrappers.FixWrapper fw = (Debrief.Wrappers.FixWrapper) oj; final WorldLocation pos = fw.getLocation(); writeLineEntry(out, pos.getLong(), pos.getLat(), pos.getDepth()); } } if (len > 0) { // we have clearly written some fixes to the file, write the footer writeLineFooter(out, len); } } } }
epl-1.0
kgibm/open-liberty
dev/com.ibm.ws.javaee.dd/src/com/ibm/ws/javaee/dd/commonbnd/Interceptor.java
1033
/******************************************************************************* * Copyright (c) 2012, 2014 IBM Corporation and others. * 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: * IBM Corporation - initial API and implementation *******************************************************************************/ package com.ibm.ws.javaee.dd.commonbnd; import com.ibm.ws.javaee.ddmetadata.annotation.DDAttribute; import com.ibm.ws.javaee.ddmetadata.annotation.DDAttributeType; import com.ibm.ws.javaee.ddmetadata.annotation.DDIdAttribute; /** * Represents &lt;interceptor>. * * Used in ejb-jar and managed-bean bnd schemas. */ @DDIdAttribute public interface Interceptor extends RefBindingsGroup { @DDAttribute(name = "class", type = DDAttributeType.String) public String getClassName(); }
epl-1.0
kgibm/open-liberty
dev/com.ibm.ws.messaging.common/src/com/ibm/websphere/sib/exception/SIResourceException.java
2227
/******************************************************************************* * Copyright (c) 2012 IBM Corporation and others. * 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: * IBM Corporation - initial API and implementation *******************************************************************************/ package com.ibm.websphere.sib.exception; /** * SIResourceException thrown by the SIBus when an operation is unable to complete * due to a resource error, such as lose of connection to a database or system. * In many cases, if the operation is retried it may succeed. * <p> * The context and root cause of the problem are detailed in the chain of linked * Exceptions contained by the SIResourceException. * * @ibm-was-base * @ibm-api */ public class SIResourceException extends SIException { private static final long serialVersionUID = 7713697496638751309L; public SIResourceException() { super(); } /** * Constructor for when the Exception is to be thrown because another * Exception has been caught during the copy. * * @param cause The original Throwable which has caused this to be thrown. */ public SIResourceException(Throwable cause) { super(cause); } /** * Constructor for when the Exception is to be thrown for a reason other than * that an Exception has been caught during the copy. * * @param message A String giving information about the problem which caused this to be thrown. */ public SIResourceException(String message) { super(message); } /** * Constructor for when the Exception is to be thrown because another * Exception has been caught during the copy and additional information is * to be included. * * @param message A String giving information about the problem which caused this to be thrown. * @param cause The original Throwable which has caused this to be thrown. */ public SIResourceException(String message, Throwable cause) { super(message, cause); } }
epl-1.0
OneTimeUser/retailwire2
wp-content/plugins/adrotate-pro/templates/adrotate-summary.php
2637
<?php /* ------------------------------------------------------------------------------------ * COPYRIGHT AND TRADEMARK NOTICE * Copyright 2008-2015 Arnan de Gans. All Rights Reserved. * ADROTATE is a trademark of Arnan de Gans. * COPYRIGHT NOTICES AND ALL THE COMMENTS SHOULD REMAIN INTACT. * By using this code you agree to indemnify Arnan de Gans from any * liability that might arise from it's use. ------------------------------------------------------------------------------------ */ /** * Override this template by copying it to yourtheme/adrotate-summary.php * * @version 1.0 */ global $current_user; $adverts = adrotate_load_adverts($current_user->ID); // Summary stats $summary = adrotate_prepare_advertiser_report($current_user->ID, $adverts['active']); ?> <table class="widefat" style="margin-top: .5em"> <tbody> <tr> <td width="15%"><?php _e('General', 'adrotate'); ?></td> <td><?php echo $summary['ad_amount']; ?> <?php _e('ads, sharing a total of', 'adrotate'); ?> <?php echo $summary['total_impressions']; ?> <?php _e('impressions.', 'adrotate'); ?></td> </tr> <tr> <td><?php _e('Most clicks', 'adrotate'); ?></td> <td><?php if($summary['thebest']) {?>'<?php echo $summary['thebest']['title']; ?>' <?php _e('with', 'adrotate'); ?> <?php echo $summary['thebest']['clicks']; ?> <?php _e('clicks.', 'adrotate'); ?><?php } else { ?><?php _e('No ad stands out at this time.', 'adrotate'); ?><?php } ?></td> </tr> <tr> <td><?php _e('Least clicks', 'adrotate'); ?></td> <td><?php if($summary['theworst']) {?>'<?php echo $summary['theworst']['title']; ?>' <?php _e('with', 'adrotate'); ?> <?php echo $summary['theworst']['clicks']; ?> <?php _e('clicks.', 'adrotate'); ?><?php } else { ?><?php _e('No ad stands out at this time.', 'adrotate'); ?><?php } ?></td> </tr> <tr> <td><?php _e('Average on all ads', 'adrotate'); ?></td> <td><?php echo $summary['total_clicks']; ?> <?php _e('clicks.', 'adrotate'); ?></td> </tr> <tr> <td><?php _e('Click-Through-Rate', 'adrotate'); ?></td> <td><?php echo adrotate_ctr($summary['total_clicks'], $summary['total_impressions']); ?>%, <?php _e('based on', 'adrotate'); ?> <?php echo $summary['total_impressions']; ?> <?php _e('impressions and', 'adrotate'); ?> <?php echo $summary['total_clicks']; ?> <?php _e('clicks.', 'adrotate'); ?></td> </tr> </tbody> </table> <h3><?php _e('Monthly overview of clicks and impressions', 'adrotate'); ?></h3> <?php echo adrotate_stats_graph('advertiserfull', $current_user->ID, 100000, mktime(0, 0, 0, date("m")-2, 1, date("Y")), mktime(0, 0, 0, date("m")+1, 0, date("Y")), 200); ?>
gpl-2.0
shannah/cn1
Ports/iOSPort/xmlvm/apache-harmony-6.0-src-r991881/drlvm/vm/tests/kernel/java/lang/ClassTestToString.java
2127
/* * 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. */ /** * @author Evgueni V. Brevnov, Roman S. Bushmanov */ package java.lang; import java.io.Serializable; import java.security.Permission; import junit.framework.TestCase; /** * tested class: java.lang.Class * tested method: toString */ public class ClassTestToString extends TestCase { /** * only the class name should be returned in the case of primitive type. */ public void test1() { assertEquals(void.class.toString(), void.class.toString()); } /** * The string "interface" should be followed by the class name if this class * represents an interface. */ public void test2() { assertEquals("interface " + Cloneable.class.getName(), Cloneable.class .toString()); } /** * The string "class" should be followed by the class name * if this is a class. */ public void test3() { assertEquals("class " + Class.class.getName(), Class.class.toString()); } /** * The string "class" should be followed by the class name * if this is a class. */ public void test4() { Serializable[] c = new Permission[0]; assertEquals("class " + c.getClass().getName(), c.getClass().toString()); } }
gpl-2.0
igorette/nerdalert.de
lib/plugins/config/lang/sv/lang.php
13723
<?php /** * swedish language file * * @license GPL 2 (http://www.gnu.org/licenses/gpl.html) * @author Per Foreby <per@foreby.se> * @author Nicklas Henriksson <nicklas[at]nihe.se> * @author Håkan Sandell <hakan.sandell[at]mydata.se> * @author Dennis Karlsson * @author Tormod Otter Johansson <tormod@latast.se> * @author emil@sys.nu * @author Pontus Bergendahl <pontus.bergendahl@gmail.com> * @author Tormod Johansson tormod.otter.johansson@gmail.com * @author Emil Lind <emil@sys.nu> * @author Bogge Bogge <bogge@bogge.com> * @author Peter Åström <eaustreum@gmail.com> * @author Håkan Sandell <hakan.sandell@home.se> */ $lang['menu'] = 'Hantera inställningar'; $lang['error'] = 'Inställningarna uppdaterades inte på grund av ett felaktigt värde. Titta igenom dina ändringar och försök sedan spara igen. <br />Felaktiga värden är omgivna av en röd ram.'; $lang['updated'] = 'Inställningarna uppdaterade.'; $lang['nochoice'] = '(inga andra val tillgängliga)'; $lang['locked'] = 'Filen med inställningar kan inte uppdateras. Om det inte är meningen att det ska vara så, <br /> kontrollera att filen med lokala inställningar har rätt namn och filskydd.'; $lang['danger'] = 'Risk: Denna förändring kan göra wikin och inställningarna otillgängliga.'; $lang['warning'] = 'Varning: Denna förändring kan orsaka icke åsyftade resultat.'; $lang['security'] = 'Säkerhetsvarning: Denna förändring kan innebära en säkerhetsrisk.'; $lang['_configuration_manager'] = 'Hantera inställningar'; $lang['_header_dokuwiki'] = 'Inställningar för DokuWiki'; $lang['_header_plugin'] = 'Inställningar för insticksmoduler'; $lang['_header_template'] = 'Inställningar för mallar'; $lang['_header_undefined'] = 'Odefinierade inställningar'; $lang['_basic'] = 'Grundläggande inställningar'; $lang['_display'] = 'Inställningar för presentation'; $lang['_authentication'] = 'Inställningar för autentisering'; $lang['_anti_spam'] = 'Inställningar för anti-spam'; $lang['_editing'] = 'Inställningar för redigering'; $lang['_links'] = 'Inställningar för länkar'; $lang['_media'] = 'Inställningar för medier'; $lang['_advanced'] = 'Avancerade inställningar'; $lang['_network'] = 'Nätverksinställningar'; $lang['_plugin_sufix'] = '(inställningar för insticksmodul)'; $lang['_template_sufix'] = '(inställningar för mall)'; $lang['_msg_setting_undefined'] = 'Ingen inställningsmetadata.'; $lang['_msg_setting_no_class'] = 'Ingen inställningsklass.'; $lang['_msg_setting_no_default'] = 'Inget standardvärde.'; $lang['fmode'] = 'Filskydd för nya filer'; $lang['dmode'] = 'Filskydd för nya kataloger'; $lang['lang'] = 'Språk'; $lang['basedir'] = 'Grundkatalog'; $lang['baseurl'] = 'Grund-webbadress'; $lang['savedir'] = 'Katalog för att spara data'; $lang['start'] = 'Startsidans namn'; $lang['title'] = 'Wikins namn'; $lang['template'] = 'Mall'; $lang['license'] = 'Under vilken licens skall ditt innehåll publiceras?'; $lang['fullpath'] = 'Visa fullständig sökväg i sidfoten'; $lang['recent'] = 'Antal poster under "Nyligen ändrat"'; $lang['breadcrumbs'] = 'Antal spår'; $lang['youarehere'] = 'Hierarkiska spår'; $lang['typography'] = 'Aktivera typografiska ersättningar'; $lang['htmlok'] = 'Tillåt inbäddad HTML'; $lang['phpok'] = 'Tillåt inbäddad PHP'; $lang['dformat'] = 'Datumformat (se PHP:s <a href="http://www.php.net/strftime">strftime</a>-funktion)'; $lang['signature'] = 'Signatur'; $lang['toptoclevel'] = 'Toppnivå för innehållsförteckning'; $lang['tocminheads'] = 'Minimalt antal rubriker för att avgöra om innehållsförteckning byggs'; $lang['maxtoclevel'] = 'Maximal nivå för innehållsförteckning'; $lang['maxseclevel'] = 'Maximal nivå för redigering av rubriker'; $lang['camelcase'] = 'Använd CamelCase för länkar'; $lang['deaccent'] = 'Rena sidnamn'; $lang['useheading'] = 'Använda första rubriken som sidnamn'; $lang['refcheck'] = 'Kontrollera referenser till mediafiler'; $lang['refshow'] = 'Antal mediareferenser som ska visas'; $lang['allowdebug'] = 'Tillåt felsökning <b>stäng av om det inte behövs!</b>'; $lang['usewordblock'] = 'Blockera spam baserat på ordlista'; $lang['indexdelay'] = 'Tidsfördröjning före indexering (sek)'; $lang['relnofollow'] = 'Använd rel="nofollow" för externa länkar'; $lang['mailguard'] = 'Koda e-postadresser'; $lang['iexssprotect'] = 'Kontrollera om uppladdade filer innehåller eventuellt skadlig JavaScript eller HTML-kod'; $lang['showuseras'] = 'Vad som skall visas när man visar den användare som senast redigerade en sida'; $lang['useacl'] = 'Använd behörighetslista (ACL)'; $lang['autopasswd'] = 'Autogenerera lösenord'; $lang['authtype'] = 'System för autentisering'; $lang['passcrypt'] = 'Metod för kryptering av lösenord'; $lang['defaultgroup'] = 'Förvald grupp'; $lang['superuser'] = 'Huvudadministratör - en grupp eller en användare med full tillgång till alla sidor och funktioner, oavsett behörighetsinställningars'; $lang['manager'] = 'Administratör -- en grupp eller användare med tillgång till vissa administrativa funktioner.'; $lang['profileconfirm'] = 'Bekräfta ändringarna i profilen med lösenordet'; $lang['disableactions'] = 'Stäng av funktioner i DokuWiki'; $lang['disableactions_check'] = 'Kontroll'; $lang['disableactions_subscription'] = 'Prenumerera/Säg upp prenumeration'; $lang['disableactions_nssubscription'] = 'Namnrymd Prenumerera/Säg upp prenumeration'; $lang['disableactions_wikicode'] = 'Visa källkod/Exportera råtext'; $lang['disableactions_other'] = 'Andra funktioner (kommaseparerade)'; $lang['sneaky_index'] = 'Som standard visar DokuWiki alla namnrymder på indexsidan. Genom att aktivera det här valet döljer man namnrymder som användaren inte har behörighet att läsa. Det kan leda till att man döljer åtkomliga undernamnrymder, och gör indexet oanvändbart med vissa ACL-inställningar.'; $lang['auth_security_timeout'] = 'Autentisieringssäkerhets timeout (sekunder)'; $lang['securecookie'] = 'Skall cookies som sätts via HTTPS endast skickas via HTTPS från webbläsaren? Avaktivera detta alternativ endast om inloggningen till din wiki är säkrad med SSL men läsning av wikin är osäkrad.'; $lang['xmlrpc'] = 'Aktivera/avaktivera XML-RPC-gränssnitt'; $lang['xmlrpcuser'] = 'Begränsa XML-RPC tillträde till komma separerade grupper eller användare som ges här. Lämna tomt för att ge tillgång till alla.'; $lang['updatecheck'] = 'Kontrollera uppdateringar och säkerhetsvarningar? DokuWiki behöver kontakta splitbrain.org för den här funktionen.'; $lang['userewrite'] = 'Använd rena webbadresser'; $lang['useslash'] = 'Använd snedstreck för att separera namnrymder i webbadresser'; $lang['usedraft'] = 'Spara utkast automatiskt under redigering'; $lang['sepchar'] = 'Ersätt blanktecken i webbadresser med'; $lang['canonical'] = 'Använd fullständiga webbadresser'; $lang['autoplural'] = 'Leta efter pluralformer av länkar'; $lang['compression'] = 'Metod för komprimering av gamla versioner'; $lang['cachetime'] = 'Maximal livslängd för cache (sek)'; $lang['locktime'] = 'Maximal livslängd för fillåsning (sek)'; $lang['fetchsize'] = 'Maximal storlek (bytes) som fetch.php får ladda ned externt'; $lang['notify'] = 'Skicka meddelande om ändrade sidor till den här e-postadressen'; $lang['registernotify'] = 'Skicka meddelande om nyregistrerade användare till en här e-postadressen'; $lang['mailfrom'] = 'Avsändaradress i automatiska e-postmeddelanden'; $lang['gzip_output'] = 'Använd gzip Content-Encoding för xhtml'; $lang['gdlib'] = 'Version av GD-biblioteket'; $lang['im_convert'] = 'Sökväg till ImageMagicks konverteringsverktyg'; $lang['jpg_quality'] = 'Kvalitet för JPG-komprimering (0-100)'; $lang['subscribers'] = 'Aktivera stöd för prenumeration på ändringar'; $lang['compress'] = 'Komprimera CSS och javascript'; $lang['hidepages'] = 'Dölj matchande sidor (reguljära uttryck)'; $lang['send404'] = 'Skicka "HTTP 404/Page Not Found" för sidor som inte finns'; $lang['sitemap'] = 'Skapa Google sitemap (dagar)'; $lang['broken_iua'] = 'Är funktionen ignore_user_abort trasig på ditt system? Det kan i så fall leda till att indexering av sökningar inte fungerar. Detta är ett känt problem med IIS+PHP/CGI. Se <a href="http://bugs.splitbrain.org/?do=details&amp;task_id=852">Bug 852</a> för mer info.'; $lang['xsendfile'] = 'Använd X-Sendfile huvudet för att låta webservern leverera statiska filer? Din webserver behöver stöd för detta.'; $lang['renderer_xhtml'] = 'Generera för användning i huvudwikipresentation (xhtml)'; $lang['renderer__core'] = '%s (dokuwiki core)'; $lang['renderer__plugin'] = '%s (plugin)'; $lang['rememberme'] = 'Tillåt permanenta inloggningscookies (kom ihåg mig)'; $lang['rss_type'] = 'Typ av XML-flöde'; $lang['rss_linkto'] = 'XML-flöde pekar på'; $lang['rss_content'] = 'Vad ska visas för saker i XML-flödet?'; $lang['rss_update'] = 'Uppdateringsintervall för XML-flöde (sek)'; $lang['recent_days'] = 'Hur många ändringar som ska sparas (dagar)'; $lang['rss_show_summary'] = 'XML-flöde visar sammanfattning i rubriken'; $lang['target____wiki'] = 'Målfönster för interna länkar'; $lang['target____interwiki'] = 'Målfönster för interwiki-länkar'; $lang['target____extern'] = 'Målfönster för externa länkar'; $lang['target____media'] = 'Målfönster för medialänkar'; $lang['target____windows'] = 'Målfönster för windowslänkar'; $lang['proxy____host'] = 'Proxyserver'; $lang['proxy____port'] = 'Proxyport'; $lang['proxy____user'] = 'Användarnamn för proxy'; $lang['proxy____pass'] = 'Lösenord för proxy'; $lang['proxy____ssl'] = 'Använd ssl för anslutning till proxy'; $lang['safemodehack'] = 'Aktivera safemode hack'; $lang['ftp____host'] = 'FTP-server för safemode hack'; $lang['ftp____port'] = 'FTP-port för safemode hack'; $lang['ftp____user'] = 'FTP-användarnamn för safemode hack'; $lang['ftp____pass'] = 'FTP-lösenord för safemode hack'; $lang['ftp____root'] = 'FTP-rotkatalog för safemode hack'; $lang['license_o_'] = 'Ingen vald'; $lang['typography_o_0'] = 'Inga'; $lang['typography_o_1'] = 'enbart dubbla citattecken'; $lang['typography_o_2'] = 'både dubbla och enkla citattecken (fungerar inte alltid)'; $lang['userewrite_o_0'] = 'av'; $lang['userewrite_o_1'] = '.htaccess'; $lang['userewrite_o_2'] = 'DokuWiki internt'; $lang['deaccent_o_0'] = 'av'; $lang['deaccent_o_1'] = 'ta bort accenter'; $lang['deaccent_o_2'] = 'romanisera'; $lang['gdlib_o_0'] = 'GD-bibliotek inte tillgängligt'; $lang['gdlib_o_1'] = 'Version 1.x'; $lang['gdlib_o_2'] = 'Automatisk detektering'; $lang['rss_type_o_rss'] = 'RSS 0.91'; $lang['rss_type_o_rss1'] = 'RSS 1.0'; $lang['rss_type_o_rss2'] = 'RSS 2.0'; $lang['rss_type_o_atom'] = 'Atom 0.3'; $lang['rss_type_o_atom1'] = 'Atom 1.0'; $lang['rss_content_o_abstract'] = 'Abstrakt'; $lang['rss_content_o_diff'] = 'Unified Diff'; $lang['rss_content_o_htmldiff'] = 'HTML formaterad diff tabell'; $lang['rss_content_o_html'] = 'Sidans innehåll i full HTML'; $lang['rss_linkto_o_diff'] = 'lista på skillnader'; $lang['rss_linkto_o_page'] = 'den reviderade sidan'; $lang['rss_linkto_o_rev'] = 'lista över ändringar'; $lang['rss_linkto_o_current'] = 'den aktuella sidan'; $lang['compression_o_0'] = 'ingen'; $lang['compression_o_gz'] = 'gzip'; $lang['compression_o_bz2'] = 'bz2'; $lang['xsendfile_o_0'] = 'använd ej'; $lang['xsendfile_o_1'] = 'Proprietär lighttpd-header (före version 1.5)'; $lang['xsendfile_o_2'] = 'Standard X-Sendfile-huvud'; $lang['xsendfile_o_3'] = 'Proprietär Nginx X-Accel-Redirect header'; $lang['showuseras_o_loginname'] = 'Användarnamn'; $lang['showuseras_o_username'] = 'Namn'; $lang['showuseras_o_email'] = 'Användarens e-postadress (obfuskerad enligt inställningarna i mailguard)'; $lang['showuseras_o_email_link'] = 'Användarens e-postadress som mailto: länk'; $lang['useheading_o_0'] = 'Aldrig'; $lang['useheading_o_navigation'] = 'Endst navigering'; $lang['useheading_o_content'] = 'Endast innehåll i wiki'; $lang['useheading_o_1'] = 'Alltid';
gpl-2.0
petergeneric/j2ssh
src/main/java/com/sshtools/common/ui/OptionsAction.java
2036
/* * SSHTools - Java SSH2 API * * Copyright (C) 2002-2003 Lee David Painter and Contributors. * * Contributions made by: * * Brett Smith * Richard Pernavas * Erwin Bolwidt * * 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. */ package com.sshtools.common.ui; import javax.swing.Action; /** * * * @author $author$ * @version $Revision: 1.13 $ */ public class OptionsAction extends StandardAction { /** * Creates a new OptionsAction object. */ public OptionsAction() { putValue(Action.NAME, "Options"); putValue(Action.SMALL_ICON, getIcon("/com/sshtools/common/ui/options.png")); putValue(Action.SHORT_DESCRIPTION, "Application options"); putValue(Action.LONG_DESCRIPTION, "Edit the application options"); putValue(Action.MNEMONIC_KEY, new Integer('o')); putValue(Action.ACTION_COMMAND_KEY, "options-command"); putValue(StandardAction.ON_MENUBAR, new Boolean(true)); putValue(StandardAction.MENU_NAME, "Tools"); putValue(StandardAction.MENU_ITEM_GROUP, new Integer(90)); putValue(StandardAction.MENU_ITEM_WEIGHT, new Integer(99)); putValue(StandardAction.ON_TOOLBAR, new Boolean(true)); putValue(StandardAction.TOOLBAR_GROUP, new Integer(90)); putValue(StandardAction.TOOLBAR_WEIGHT, new Integer(0)); } }
gpl-2.0
vosgus/phpmyadmin
libraries/dbi/DBIDummy.php
39445
<?php /* vim: set expandtab sw=4 ts=4 sts=4: */ /** * Fake database driver for testing purposes * * It has hardcoded results for given queries what makes easy to use it * in testsuite. Feel free to include other queries which your test will * need. * * @package PhpMyAdmin-DBI * @subpackage Dummy */ namespace PMA\libraries\dbi; if (!defined('PHPMYADMIN')) { exit; } /** * Array of queries this "driver" supports */ $GLOBALS['dummy_queries'] = array( array('query' => 'SELECT 1', 'result' => array(array('1'))), array( 'query' => 'SELECT CURRENT_USER();', 'result' => array(array('pma_test@localhost')), ), array( 'query' => "SHOW VARIABLES LIKE 'lower_case_table_names'", 'result' => array(array('lower_case_table_names', '1')), ), array( 'query' => 'SELECT 1 FROM mysql.user LIMIT 1', 'result' => array(array('1')), ), array( 'query' => "SELECT 1 FROM `INFORMATION_SCHEMA`.`USER_PRIVILEGES`" . " WHERE `PRIVILEGE_TYPE` = 'CREATE USER'" . " AND '''pma_test''@''localhost''' LIKE `GRANTEE` LIMIT 1", 'result' => array(array('1')), ), array( 'query' => "SELECT 1 FROM (SELECT `GRANTEE`, `IS_GRANTABLE`" . " FROM `INFORMATION_SCHEMA`.`COLUMN_PRIVILEGES`" . " UNION SELECT `GRANTEE`, `IS_GRANTABLE`" . " FROM `INFORMATION_SCHEMA`.`TABLE_PRIVILEGES`" . " UNION SELECT `GRANTEE`, `IS_GRANTABLE`" . " FROM `INFORMATION_SCHEMA`.`SCHEMA_PRIVILEGES`" . " UNION SELECT `GRANTEE`, `IS_GRANTABLE`" . " FROM `INFORMATION_SCHEMA`.`USER_PRIVILEGES`) t" . " WHERE `IS_GRANTABLE` = 'YES'" . " AND '''pma_test''@''localhost''' LIKE `GRANTEE` LIMIT 1", 'result' => array(array('1')), ), array( 'query' => 'SHOW MASTER LOGS', 'result' => false, ), array( 'query' => 'SHOW STORAGE ENGINES', 'result' => array( array( 'Engine' => 'dummy', 'Support' => 'YES', 'Comment' => 'dummy comment', ), array( 'Engine' => 'dummy2', 'Support' => 'NO', 'Comment' => 'dummy2 comment', ), array( 'Engine' => 'FEDERATED', 'Support' => 'NO', 'Comment' => 'Federated MySQL storage engine', ), ), ), array( 'query' => 'SHOW STATUS WHERE Variable_name' . ' LIKE \'Innodb\\_buffer\\_pool\\_%\'' . ' OR Variable_name = \'Innodb_page_size\';', 'result' => array( array('Innodb_buffer_pool_pages_data', 0), array('Innodb_buffer_pool_pages_dirty', 0), array('Innodb_buffer_pool_pages_flushed', 0), array('Innodb_buffer_pool_pages_free', 0), array('Innodb_buffer_pool_pages_misc', 0), array('Innodb_buffer_pool_pages_total', 4096), array('Innodb_buffer_pool_read_ahead_rnd', 0), array('Innodb_buffer_pool_read_ahead', 0), array('Innodb_buffer_pool_read_ahead_evicted', 0), array('Innodb_buffer_pool_read_requests', 64), array('Innodb_buffer_pool_reads', 32), array('Innodb_buffer_pool_wait_free', 0), array('Innodb_buffer_pool_write_requests', 64), array('Innodb_page_size', 16384), ), ), array( 'query' => 'SHOW ENGINE INNODB STATUS;', 'result' => false, ), array( 'query' => 'SELECT @@innodb_version;', 'result' => array( array('1.1.8'), ), ), array( 'query' => 'SELECT @@disabled_storage_engines', 'result' => array( array(''), ), ), array( 'query' => 'SHOW GLOBAL VARIABLES LIKE \'innodb_file_per_table\';', 'result' => array( array('innodb_file_per_table', 'OFF'), ), ), array( 'query' => 'SHOW GLOBAL VARIABLES LIKE \'innodb_file_format\';', 'result' => array( array('innodb_file_format', 'Antelope'), ), ), array( 'query' => 'SELECT @@collation_server', 'result' => array( array('utf8_general_ci'), ), ), array( 'query' => 'SELECT @@lc_messages;', 'result' => array(), ), array( 'query' => 'SHOW SESSION VARIABLES LIKE \'FOREIGN_KEY_CHECKS\';', 'result' => array( array('foreign_key_checks', 'ON'), ), ), array( 'query' => 'SHOW TABLES FROM `pma_test`;', 'result' => array( array('table1'), array('table2'), ), ), array( 'query' => 'SHOW TABLES FROM `pmadb`', 'result' => array( array('column_info'), ), ), array( 'query' => 'SHOW COLUMNS FROM `pma_test`.`table1`', 'columns' => array( 'Field', 'Type', 'Null', 'Key', 'Default', 'Extra', ), 'result' => array( array('i', 'int(11)', 'NO', 'PRI', 'NULL', 'auto_increment'), array('o', 'int(11)', 'NO', 'MUL', 'NULL', ''), ), ), array( 'query' => 'SHOW INDEXES FROM `pma_test`.`table1` WHERE (Non_unique = 0)', 'result' => array(), ), array( 'query' => 'SHOW COLUMNS FROM `pma_test`.`table2`', 'columns' => array( 'Field', 'Type', 'Null', 'Key', 'Default', 'Extra', ), 'result' => array( array('i', 'int(11)', 'NO', 'PRI', 'NULL', 'auto_increment'), array('o', 'int(11)', 'NO', 'MUL', 'NULL', ''), ), ), array( 'query' => 'SHOW INDEXES FROM `pma_test`.`table1`', 'result' => array(), ), array( 'query' => 'SHOW INDEXES FROM `pma_test`.`table2`', 'result' => array(), ), array( 'query' => 'SHOW COLUMNS FROM `pma`.`table1`', 'columns' => array( 'Field', 'Type', 'Null', 'Key', 'Default', 'Extra', 'Privileges', 'Comment', ), 'result' => array( array( 'i', 'int(11)', 'NO', 'PRI', 'NULL', 'auto_increment', 'select,insert,update,references', '', ), array( 'o', 'varchar(100)', 'NO', 'MUL', 'NULL', '', 'select,insert,update,references', '', ), ), ), array( 'query' => 'SELECT * FROM information_schema.CHARACTER_SETS', 'columns' => array( 'CHARACTER_SET_NAME', 'DEFAULT_COLLATE_NAME', 'DESCRIPTION', 'MAXLEN', ), 'result' => array( array('utf8', 'utf8_general_ci', 'UTF-8 Unicode', 3), array('latin1', 'latin1_swedish_ci', 'cp1252 West European', 1), ), ), array( 'query' => 'SELECT * FROM information_schema.COLLATIONS', 'columns' => array( 'COLLATION_NAME', 'CHARACTER_SET_NAME', 'ID', 'IS_DEFAULT', 'IS_COMPILED', 'SORTLEN', ), 'result' => array( array('utf8_general_ci', 'utf8', 33, 'Yes', 'Yes', 1), array('utf8_bin', 'utf8', 83, '', 'Yes', 1), array('latin1_swedish_ci', 'latin1', 8, 'Yes', 'Yes', 1), ), ), array( 'query' => 'SELECT `TABLE_NAME` FROM `INFORMATION_SCHEMA`.`TABLES`' . ' WHERE `TABLE_SCHEMA`=\'pma_test\' AND `TABLE_TYPE`=\'BASE TABLE\'', 'result' => array(), ), array( 'query' => 'SELECT `column_name`, `mimetype`, `transformation`,' . ' `transformation_options`, `input_transformation`,' . ' `input_transformation_options`' . ' FROM `pmadb`.`column_info`' . ' WHERE `db_name` = \'pma_test\' AND `table_name` = \'table1\'' . ' AND ( `mimetype` != \'\' OR `transformation` != \'\'' . ' OR `transformation_options` != \'\'' . ' OR `input_transformation` != \'\'' . ' OR `input_transformation_options` != \'\')', 'columns' => array( 'column_name', 'mimetype', 'transformation', 'transformation_options', 'input_transformation', 'input_transformation_options', ), 'result' => array( array('o', 'text/plain', 'sql', '', 'regex', '/pma/i'), array('col', 't', 'o/p', '', 'i/p', ''), ), ), array( 'query' => 'SELECT TABLE_NAME FROM information_schema.VIEWS' . ' WHERE TABLE_SCHEMA = \'pma_test\' AND TABLE_NAME = \'table1\'', 'result' => array(), ), array( 'query' => 'SELECT *, `TABLE_SCHEMA` AS `Db`, `TABLE_NAME` AS `Name`,' . ' `TABLE_TYPE` AS `TABLE_TYPE`, `ENGINE` AS `Engine`,' . ' `ENGINE` AS `Type`, `VERSION` AS `Version`,' . ' `ROW_FORMAT` AS `Row_format`, `TABLE_ROWS` AS `Rows`,' . ' `AVG_ROW_LENGTH` AS `Avg_row_length`,' . ' `DATA_LENGTH` AS `Data_length`,' . ' `MAX_DATA_LENGTH` AS `Max_data_length`,' . ' `INDEX_LENGTH` AS `Index_length`, `DATA_FREE` AS `Data_free`,' . ' `AUTO_INCREMENT` AS `Auto_increment`,' . ' `CREATE_TIME` AS `Create_time`, `UPDATE_TIME` AS `Update_time`,' . ' `CHECK_TIME` AS `Check_time`, `TABLE_COLLATION` AS `Collation`,' . ' `CHECKSUM` AS `Checksum`, `CREATE_OPTIONS` AS `Create_options`,' . ' `TABLE_COMMENT` AS `Comment`' . ' FROM `information_schema`.`TABLES` t' . ' WHERE `TABLE_SCHEMA` IN (\'pma_test\')' . ' AND t.`TABLE_NAME` = \'table1\' ORDER BY Name ASC', 'columns' => array( 'TABLE_CATALOG', 'TABLE_SCHEMA', 'TABLE_NAME', 'TABLE_TYPE', 'ENGINE', 'VERSION', 'ROW_FORMAT', 'TABLE_ROWS', 'AVG_ROW_LENGTH', 'DATA_LENGTH', 'MAX_DATA_LENGTH', 'INDEX_LENGTH', 'DATA_FREE', 'AUTO_INCREMENT', 'CREATE_TIME', 'UPDATE_TIME', 'CHECK_TIME', 'TABLE_COLLATION', 'CHECKSUM', 'CREATE_OPTIONS', 'TABLE_COMMENT', 'Db', 'Name', 'TABLE_TYPE', 'Engine', 'Type', 'Version', 'Row_format', 'Rows', 'Avg_row_length', 'Data_length', 'Max_data_length', 'Index_length', 'Data_free', 'Auto_increment', 'Create_time', 'Update_time', 'Check_time', 'Collation', 'Checksum', 'Create_options', 'Comment', ), 'result' => array( array( 'def', 'smash', 'issues_issue', 'BASE TABLE', 'InnoDB', '10', 'Compact', '9136', '862', '7880704', '0', '1032192', '420478976', '155862', '2012-08-29 13:28:28', 'NULL', 'NULL', 'utf8_general_ci', 'NULL', '', '', 'smash', 'issues_issue', 'BASE TABLE', 'InnoDB', 'InnoDB', '10', 'Compact', '9136', '862', '7880704', '0', '1032192', '420478976', '155862', '2012-08-29 13:28:28', 'NULL', 'NULL', 'utf8_general_ci', 'NULL', ), ), ), array( 'query' => 'SELECT *, `TABLE_SCHEMA` AS `Db`, `TABLE_NAME` AS `Name`,' . ' `TABLE_TYPE` AS `TABLE_TYPE`, `ENGINE` AS `Engine`,' . ' `ENGINE` AS `Type`, `VERSION` AS `Version`,' . ' `ROW_FORMAT` AS `Row_format`, `TABLE_ROWS` AS `Rows`,' . ' `AVG_ROW_LENGTH` AS `Avg_row_length`,' . ' `DATA_LENGTH` AS `Data_length`,' . ' `MAX_DATA_LENGTH` AS `Max_data_length`,' . ' `INDEX_LENGTH` AS `Index_length`, `DATA_FREE` AS `Data_free`,' . ' `AUTO_INCREMENT` AS `Auto_increment`,' . ' `CREATE_TIME` AS `Create_time`, `UPDATE_TIME` AS `Update_time`,' . ' `CHECK_TIME` AS `Check_time`, `TABLE_COLLATION` AS `Collation`,' . ' `CHECKSUM` AS `Checksum`, `CREATE_OPTIONS` AS `Create_options`,' . ' `TABLE_COMMENT` AS `Comment`' . ' FROM `information_schema`.`TABLES` t' . ' WHERE `TABLE_SCHEMA` IN (\'pma_test\')' . ' AND t.`TABLE_NAME` = \'table1\' ORDER BY Name ASC', 'columns' => array( 'TABLE_CATALOG', 'TABLE_SCHEMA', 'TABLE_NAME', 'TABLE_TYPE', 'ENGINE', 'VERSION', 'ROW_FORMAT', 'TABLE_ROWS', 'AVG_ROW_LENGTH', 'DATA_LENGTH', 'MAX_DATA_LENGTH', 'INDEX_LENGTH', 'DATA_FREE', 'AUTO_INCREMENT', 'CREATE_TIME', 'UPDATE_TIME', 'CHECK_TIME', 'TABLE_COLLATION', 'CHECKSUM', 'CREATE_OPTIONS', 'TABLE_COMMENT', 'Db', 'Name', 'TABLE_TYPE', 'Engine', 'Type', 'Version', 'Row_format', 'Rows', 'Avg_row_length', 'Data_length', 'Max_data_length', 'Index_length', 'Data_free', 'Auto_increment', 'Create_time', 'Update_time', 'Check_time', 'Collation', 'Checksum', 'Create_options', 'Comment', ), 'result' => array( array( 'def', 'smash', 'issues_issue', 'BASE TABLE', 'InnoDB', '10', 'Compact', '9136', '862', '7880704', '0', '1032192', '420478976', '155862', '2012-08-29 13:28:28', 'NULL', 'NULL', 'utf8_general_ci', 'NULL', '', '', 'smash', 'issues_issue', 'BASE TABLE', 'InnoDB', 'InnoDB', '10', 'Compact', '9136', '862', '7880704', '0', '1032192', '420478976', '155862', '2012-08-29 13:28:28', 'NULL', 'NULL', 'utf8_general_ci', 'NULL', ), ), ), array( 'query' => 'SELECT COUNT(*) FROM `pma_test`.`table1`', 'result' => array(array(0)), ), array( 'query' => 'SELECT `PRIVILEGE_TYPE` FROM `INFORMATION_SCHEMA`.' . '`USER_PRIVILEGES`' . ' WHERE GRANTEE=\'\'\'pma_test\'\'@\'\'localhost\'\'\'' . ' AND PRIVILEGE_TYPE=\'TRIGGER\'', 'result' => array(), ), array( 'query' => 'SELECT `PRIVILEGE_TYPE` FROM `INFORMATION_SCHEMA`.' . '`SCHEMA_PRIVILEGES`' . ' WHERE GRANTEE=\'\'\'pma_test\'\'@\'\'localhost\'\'\'' . ' AND PRIVILEGE_TYPE=\'TRIGGER\' AND \'pma_test\'' . ' LIKE `TABLE_SCHEMA`', 'result' => array(), ), array( 'query' => 'SELECT `PRIVILEGE_TYPE` FROM `INFORMATION_SCHEMA`.' . '`TABLE_PRIVILEGES`' . ' WHERE GRANTEE=\'\'\'pma_test\'\'@\'\'localhost\'\'\'' . ' AND PRIVILEGE_TYPE=\'TRIGGER\' AND \'pma_test\'' . ' LIKE `TABLE_SCHEMA` AND TABLE_NAME=\'table1\'', 'result' => array(), ), array( 'query' => 'SELECT `PRIVILEGE_TYPE` FROM `INFORMATION_SCHEMA`.' . '`USER_PRIVILEGES`' . ' WHERE GRANTEE=\'\'\'pma_test\'\'@\'\'localhost\'\'\'' . ' AND PRIVILEGE_TYPE=\'EVENT\'', 'result' => array(), ), array( 'query' => 'SELECT `PRIVILEGE_TYPE` FROM `INFORMATION_SCHEMA`.' . '`SCHEMA_PRIVILEGES`' . ' WHERE GRANTEE=\'\'\'pma_test\'\'@\'\'localhost\'\'\'' . ' AND PRIVILEGE_TYPE=\'EVENT\' AND \'pma_test\'' . ' LIKE `TABLE_SCHEMA`', 'result' => array(), ), array( 'query' => 'SELECT `PRIVILEGE_TYPE` FROM `INFORMATION_SCHEMA`.' . '`TABLE_PRIVILEGES`' . ' WHERE GRANTEE=\'\'\'pma_test\'\'@\'\'localhost\'\'\'' . ' AND PRIVILEGE_TYPE=\'EVENT\'' . ' AND TABLE_SCHEMA=\'pma\\\\_test\' AND TABLE_NAME=\'table1\'', 'result' => array(), ), array( 'query' => 'RENAME TABLE `pma_test`.`table1` TO `pma_test`.`table3`;', 'result' => array(), ), array( 'query' => 'SELECT TRIGGER_SCHEMA, TRIGGER_NAME, EVENT_MANIPULATION,' . ' EVENT_OBJECT_TABLE, ACTION_TIMING, ACTION_STATEMENT, ' . 'EVENT_OBJECT_SCHEMA, EVENT_OBJECT_TABLE, DEFINER' . ' FROM information_schema.TRIGGERS' . ' WHERE EVENT_OBJECT_SCHEMA= \'pma_test\'' . ' AND EVENT_OBJECT_TABLE = \'table1\';', 'result' => array(), ), array( 'query' => 'SHOW TABLES FROM `pma`;', 'result' => array(), ), array( 'query' => "SELECT `PRIVILEGE_TYPE` FROM `INFORMATION_SCHEMA`." . "`SCHEMA_PRIVILEGES` WHERE GRANTEE='''pma_test''@''localhost'''" . " AND PRIVILEGE_TYPE='EVENT' AND TABLE_SCHEMA='pma'", 'result' => array(), ), array( 'query' => "SELECT `PRIVILEGE_TYPE` FROM `INFORMATION_SCHEMA`." . "`SCHEMA_PRIVILEGES` WHERE GRANTEE='''pma_test''@''localhost'''" . " AND PRIVILEGE_TYPE='TRIGGER' AND TABLE_SCHEMA='pma'", 'result' => array(), ), array( 'query' => 'SELECT DEFAULT_COLLATION_NAME FROM information_schema.SCHEMATA' . ' WHERE SCHEMA_NAME = \'pma_test\' LIMIT 1', 'columns' => array('DEFAULT_COLLATION_NAME'), 'result' => array( array('utf8_general_ci'), ), ), array( 'query' => 'SELECT @@collation_database', 'columns' => array('@@collation_database'), 'result' => array( array('bar'), ), ), array( 'query' => "SHOW TABLES FROM `phpmyadmin`", 'result' => array(), ), array( 'query' => "SELECT tracking_active FROM `pmadb`.`tracking`" . " WHERE db_name = 'pma_test_db'" . " AND table_name = 'pma_test_table'" . " ORDER BY version DESC LIMIT 1", 'columns' => array('tracking_active'), 'result' => array( array(1), ), ), array( 'query' => "SELECT tracking_active FROM `pmadb`.`tracking`" . " WHERE db_name = 'pma_test_db'" . " AND table_name = 'pma_test_table2'" . " ORDER BY version DESC LIMIT 1", 'result' => array(), ), array( 'query' => "SHOW SLAVE STATUS", 'result' => array( array( 'Slave_IO_State' => 'running', 'Master_Host' => 'locahost', 'Master_User' => 'Master_User', 'Master_Port' => '1002', 'Connect_Retry' => 'Connect_Retry', 'Master_Log_File' => 'Master_Log_File', 'Read_Master_Log_Pos' => 'Read_Master_Log_Pos', 'Relay_Log_File' => 'Relay_Log_File', 'Relay_Log_Pos' => 'Relay_Log_Pos', 'Relay_Master_Log_File' => 'Relay_Master_Log_File', 'Slave_IO_Running' => 'NO', 'Slave_SQL_Running' => 'NO', 'Replicate_Do_DB' => 'Replicate_Do_DB', 'Replicate_Ignore_DB' => 'Replicate_Ignore_DB', 'Replicate_Do_Table' => 'Replicate_Do_Table', 'Replicate_Ignore_Table' => 'Replicate_Ignore_Table', 'Replicate_Wild_Do_Table' => 'Replicate_Wild_Do_Table', 'Replicate_Wild_Ignore_Table' => 'Replicate_Wild_Ignore_Table', 'Last_Errno' => 'Last_Errno', 'Last_Error' => 'Last_Error', 'Skip_Counter' => 'Skip_Counter', 'Exec_Master_Log_Pos' => 'Exec_Master_Log_Pos', 'Relay_Log_Space' => 'Relay_Log_Space', 'Until_Condition' => 'Until_Condition', 'Until_Log_File' => 'Until_Log_File', 'Until_Log_Pos' => 'Until_Log_Pos', 'Master_SSL_Allowed' => 'Master_SSL_Allowed', 'Master_SSL_CA_File' => 'Master_SSL_CA_File', 'Master_SSL_CA_Path' => 'Master_SSL_CA_Path', 'Master_SSL_Cert' => 'Master_SSL_Cert', 'Master_SSL_Cipher' => 'Master_SSL_Cipher', 'Master_SSL_Key' => 'Master_SSL_Key', 'Seconds_Behind_Master' => 'Seconds_Behind_Master', ), ), ), array( 'query' => "SHOW MASTER STATUS", 'result' => array( array( "File" => "master-bin.000030", "Position" => "107", "Binlog_Do_DB" => "Binlog_Do_DB", "Binlog_Ignore_DB" => "Binlog_Ignore_DB", ), ), ), array( 'query' => "SHOW GRANTS", 'result' => array(), ), array( 'query' => "SELECT `SCHEMA_NAME` FROM `INFORMATION_SCHEMA`.`SCHEMATA`, " . "(SELECT DB_first_level FROM ( SELECT DISTINCT " . "SUBSTRING_INDEX(SCHEMA_NAME, '_', 1) DB_first_level " . "FROM INFORMATION_SCHEMA.SCHEMATA WHERE TRUE ) t ORDER BY " . "DB_first_level ASC LIMIT 0, 100) t2 WHERE TRUE AND 1 = LOCATE(" . "CONCAT(DB_first_level, '_'), CONCAT(SCHEMA_NAME, '_')) " . "ORDER BY SCHEMA_NAME ASC", 'result' => array( "test", ), ), array( 'query' => "SELECT COUNT(*) FROM ( SELECT DISTINCT SUBSTRING_INDEX(" . "SCHEMA_NAME, '_', 1) DB_first_level " . "FROM INFORMATION_SCHEMA.SCHEMATA WHERE TRUE ) t", 'result' => array( array(1), ), ), array( 'query' => "SELECT `PARTITION_METHOD` " . "FROM `information_schema`.`PARTITIONS` " . "WHERE `TABLE_SCHEMA` = 'db' AND `TABLE_NAME` = 'table' LIMIT 1", 'result' => array(), ), array( 'query' => "SHOW PLUGINS", 'result' => array( array('Name' => 'partition'), ), ), array( 'query' => "SHOW FULL TABLES FROM `default` WHERE `Table_type`='BASE TABLE'", 'result' => array( array("test1", "BASE TABLE"), array("test2", "BASE TABLE"), ), ), array( 'query' => "SHOW FULL TABLES FROM `default` " . "WHERE `Table_type`!='BASE TABLE'", 'result' => array(), ), array( 'query' => "SHOW FUNCTION STATUS WHERE `Db`='default'", 'result' => array(array("Name" => "testFunction")), ), array( 'query' => "SHOW PROCEDURE STATUS WHERE `Db`='default'", 'result' => array(), ), array( 'query' => "SHOW EVENTS FROM `default`", 'result' => array(), ), array( 'query' => "FLUSH PRIVILEGES", 'result' => array(), ), array( 'query' => "SELECT * FROM `mysql`.`db` LIMIT 1", 'result' => array(), ), array( 'query' => "SELECT * FROM `mysql`.`columns_priv` LIMIT 1", 'result' => array(), ), array( 'query' => "SELECT * FROM `mysql`.`tables_priv` LIMIT 1", 'result' => array(), ), array( 'query' => "SELECT * FROM `mysql`.`procs_priv` LIMIT 1", 'result' => array(), ), array( 'query' => 'DELETE FROM `mysql`.`db` WHERE `host` = "" ' . 'AND `Db` = "" AND `User` = ""', 'result' => true ), array( 'query' => 'DELETE FROM `mysql`.`columns_priv` WHERE ' . '`host` = "" AND `Db` = "" AND `User` = ""', 'result' => true ), array( 'query' => 'DELETE FROM `mysql`.`tables_priv` WHERE ' . '`host` = "" AND `Db` = "" AND `User` = "" AND Table_name = ""', 'result' => true ), array( 'query' => 'DELETE FROM `mysql`.`procs_priv` WHERE ' . '`host` = "" AND `Db` = "" AND `User` = "" AND `Routine_name` = "" ' . 'AND `Routine_type` = ""', 'result' => true ), array( 'query' => 'SELECT `plugin` FROM `mysql`.`user` WHERE ' . '`User` = "pma_username" AND `Host` = "pma_hostname" LIMIT 1', 'result' => array() ), array( 'query' => 'SELECT @@default_authentication_plugin', 'result' => array( array('@@default_authentication_plugin' => 'mysql_native_password'), ), ), array( 'query' => "SELECT TABLE_NAME FROM information_schema.VIEWS WHERE " . "TABLE_SCHEMA = 'db' AND TABLE_NAME = 'table'", 'result' => array(), ), array( 'query' => "SELECT *, `TABLE_SCHEMA` AS `Db`, " . "`TABLE_NAME` AS `Name`, `TABLE_TYPE` AS `TABLE_TYPE`, " . "`ENGINE` AS `Engine`, `ENGINE` AS `Type`, " . "`VERSION` AS `Version`, `ROW_FORMAT` AS `Row_format`, " . "`TABLE_ROWS` AS `Rows`, `AVG_ROW_LENGTH` AS `Avg_row_length`, " . "`DATA_LENGTH` AS `Data_length`, " . "`MAX_DATA_LENGTH` AS `Max_data_length`, " . "`INDEX_LENGTH` AS `Index_length`, `DATA_FREE` AS `Data_free`, " . "`AUTO_INCREMENT` AS `Auto_increment`, " . "`CREATE_TIME` AS `Create_time`, " . "`UPDATE_TIME` AS `Update_time`, `CHECK_TIME` AS `Check_time`, " . "`TABLE_COLLATION` AS `Collation`, `CHECKSUM` AS `Checksum`, " . "`CREATE_OPTIONS` AS `Create_options`, " . "`TABLE_COMMENT` AS `Comment` " . "FROM `information_schema`.`TABLES` t " . "WHERE `TABLE_SCHEMA` IN ('db') " . "AND t.`TABLE_NAME` = 'table' ORDER BY Name ASC", 'result' => array(), ), array( 'query' => "SHOW TABLE STATUS FROM `db` WHERE `Name` LIKE 'table%'", 'result' => array(), ), array( 'query' => "SELECT @@have_partitioning;", 'result' => array(), ), array( 'query' => "SELECT @@lower_case_table_names", 'result' => array(), ), array( 'query' => "SELECT `PLUGIN_NAME`, `PLUGIN_DESCRIPTION` " . "FROM `information_schema`.`PLUGINS` " . "WHERE `PLUGIN_TYPE` = 'AUTHENTICATION';", 'result' => array(), ), array( 'query' => "SHOW TABLES FROM `db`;", 'result' => array(), ), array( 'query' => "SELECT `PRIVILEGE_TYPE` FROM " . "`INFORMATION_SCHEMA`.`SCHEMA_PRIVILEGES` " . "WHERE GRANTEE='''pma_test''@''localhost''' " . "AND PRIVILEGE_TYPE='EVENT' AND 'db' LIKE `TABLE_SCHEMA`", 'result' => array(), ), array( 'query' => "SELECT `PRIVILEGE_TYPE` FROM " . "`INFORMATION_SCHEMA`.`SCHEMA_PRIVILEGES` " . "WHERE GRANTEE='''pma_test''@''localhost''' " . "AND PRIVILEGE_TYPE='TRIGGER' AND 'db' LIKE `TABLE_SCHEMA`", 'result' => array(), ), array( 'query' => "SELECT (COUNT(DB_first_level) DIV 100) * 100 from " . "( SELECT distinct SUBSTRING_INDEX(SCHEMA_NAME, '_', 1) " . "DB_first_level FROM INFORMATION_SCHEMA.SCHEMATA " . "WHERE `SCHEMA_NAME` < 'db' ) t", 'result' => array(), ), array( 'query' => "SELECT `SCHEMA_NAME` FROM " . "`INFORMATION_SCHEMA`.`SCHEMATA`, " . "(SELECT DB_first_level FROM ( SELECT DISTINCT " . "SUBSTRING_INDEX(SCHEMA_NAME, '_', 1) DB_first_level FROM " . "INFORMATION_SCHEMA.SCHEMATA WHERE TRUE ) t " . "ORDER BY DB_first_level ASC LIMIT , 100) t2 WHERE TRUE AND " . "1 = LOCATE(CONCAT(DB_first_level, '_'), " . "CONCAT(SCHEMA_NAME, '_')) ORDER BY SCHEMA_NAME ASC", 'result' => array(), ), array( 'query' => 'SELECT @@ndb_version_string', 'result' => array(array('ndb-7.4.10')), ), ); /** * Current database. */ $GLOBALS['dummy_db'] = ''; /* Some basic setup for dummy driver */ $GLOBALS['userlink'] = 1; $GLOBALS['controllink'] = 2; $GLOBALS['cfg']['DBG']['sql'] = false; if (!defined('PMA_MARIADB')) { define('PMA_MARIADB', 0); } /** * Fake database driver for testing purposes * * It has hardcoded results for given queries what makes easy to use it * in testsuite. Feel free to include other queries which your test will * need. * * @package PhpMyAdmin-DBI * @subpackage Dummy */ class DBIDummy implements DBIExtension { /** * connects to the database server * * @param string $user mysql user name * @param string $password mysql user password * @param array $server host/port/socket/persistent * * @return mixed false on error or a mysqli object on success */ public function connect( $user, $password, $server = null ) { return true; } /** * selects given database * * @param string $dbname name of db to select * @param resource $link mysql link resource * * @return bool */ public function selectDb($dbname, $link) { $GLOBALS['dummy_db'] = $dbname; return true; } /** * runs a query and returns the result * * @param string $query query to run * @param resource $link mysql link resource * @param int $options query options * * @return mixed */ public function realQuery($query, $link = null, $options = 0) { $query = trim(preg_replace('/ */', ' ', str_replace("\n", ' ', $query))); for ($i = 0, $nb = count($GLOBALS['dummy_queries']); $i < $nb; $i++) { if ($GLOBALS['dummy_queries'][$i]['query'] != $query) { continue; } $GLOBALS['dummy_queries'][$i]['pos'] = 0; if (!is_array($GLOBALS['dummy_queries'][$i]['result'])) { return false; } return $i; } echo "Not supported query: $query\n"; return false; } /** * Run the multi query and output the results * * @param resource $link connection object * @param string $query multi query statement to execute * * @return array|bool */ public function realMultiQuery($link, $query) { return false; } /** * returns result data from $result * * @param object $result MySQL result * * @return array */ public function fetchAny($result) { $query_data = $GLOBALS['dummy_queries'][$result]; if ($query_data['pos'] >= count($query_data['result'])) { return false; } $ret = $query_data['result'][$query_data['pos']]; $GLOBALS['dummy_queries'][$result]['pos'] += 1; return $ret; } /** * returns array of rows with associative and numeric keys from $result * * @param object $result result MySQL result * * @return array */ public function fetchArray($result) { $data = $this->fetchAny($result); if (!is_array($data) || !isset($GLOBALS['dummy_queries'][$result]['columns']) ) { return $data; } foreach ($data as $key => $val) { $data[$GLOBALS['dummy_queries'][$result]['columns'][$key]] = $val; } return $data; } /** * returns array of rows with associative keys from $result * * @param object $result MySQL result * * @return array */ public function fetchAssoc($result) { $data = $this->fetchAny($result); if (!is_array($data) || !isset($GLOBALS['dummy_queries'][$result]['columns']) ) { return $data; } $ret = array(); foreach ($data as $key => $val) { $ret[$GLOBALS['dummy_queries'][$result]['columns'][$key]] = $val; } return $ret; } /** * returns array of rows with numeric keys from $result * * @param object $result MySQL result * * @return array */ public function fetchRow($result) { $data = $this->fetchAny($result); return $data; } /** * Adjusts the result pointer to an arbitrary row in the result * * @param object $result database result * @param integer $offset offset to seek * * @return bool true on success, false on failure */ public function dataSeek($result, $offset) { if ($offset > count($GLOBALS['dummy_queries'][$result]['result'])) { return false; } $GLOBALS['dummy_queries'][$result]['pos'] = $offset; return true; } /** * Frees memory associated with the result * * @param object $result database result * * @return void */ public function freeResult($result) { return; } /** * Check if there are any more query results from a multi query * * @param resource $link the connection object * * @return bool false */ public function moreResults($link) { return false; } /** * Prepare next result from multi_query * * @param resource $link the connection object * * @return boolean false */ public function nextResult($link) { return false; } /** * Store the result returned from multi query * * @param resource $link the connection object * * @return mixed false when empty results / result set when not empty */ public function storeResult($link) { return false; } /** * Returns a string representing the type of connection used * * @param resource $link mysql link * * @return string type of connection used */ public function getHostInfo($link) { return ''; } /** * Returns the version of the MySQL protocol used * * @param resource $link mysql link * * @return integer version of the MySQL protocol used */ public function getProtoInfo($link) { return -1; } /** * returns a string that represents the client library version * * @return string MySQL client library version */ public function getClientInfo() { return ''; } /** * returns last error message or false if no errors occurred * * @param resource $link connection link * * @return string|bool $error or false */ public function getError($link) { return false; } /** * returns the number of rows returned by last query * * @param object $result MySQL result * * @return string|int */ public function numRows($result) { if (is_bool($result)) { return 0; } return count($GLOBALS['dummy_queries'][$result]['result']); } /** * returns the number of rows affected by last query * * @param resource $link the mysql object * @param bool $get_from_cache whether to retrieve from cache * * @return string|int */ public function affectedRows($link = null, $get_from_cache = true) { return 0; } /** * returns metainfo for fields in $result * * @param object $result result set identifier * * @return array meta info for fields in $result */ public function getFieldsMeta($result) { return array(); } /** * return number of fields in given $result * * @param object $result MySQL result * * @return int field count */ public function numFields($result) { if (!isset($GLOBALS['dummy_queries'][$result]['columns'])) { return 0; } return count($GLOBALS['dummy_queries'][$result]['columns']); } /** * returns the length of the given field $i in $result * * @param object $result result set identifier * @param int $i field * * @return int length of field */ public function fieldLen($result, $i) { return -1; } /** * returns name of $i. field in $result * * @param object $result result set identifier * @param int $i field * * @return string name of $i. field in $result */ public function fieldName($result, $i) { return ''; } /** * returns concatenated string of human readable field flags * * @param object $result result set identifier * @param int $i field * * @return string field flags */ public function fieldFlags($result, $i) { return ''; } /** * returns properly escaped string for use in MySQL queries * * @param mixed $link database link * @param string $str string to be escaped * * @return string a MySQL escaped string */ public function escapeString($link, $str) { return $str; } }
gpl-2.0
girirajsharma/wildfly-ssl-examples
SSL/user/helloworld-rs/src/main/java/org/jboss/as/quickstarts/rshelloworld/HelloWorldApplication.java
1249
/* * JBoss, Home of Professional Open Source * Copyright 2014, Red Hat, Inc. and/or its affiliates, and individual * contributors by the @authors tag. See the copyright.txt in the * distribution for a full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.as.quickstarts.rshelloworld; import javax.ws.rs.ApplicationPath; import javax.ws.rs.core.Application; /** * A class extending {@link javax.ws.rs.core.Application} is the portable way to define JAX-RS 2.0 resources, and the {@link javax.ws.rs.ApplicationPath} defines the root path shared by all these resources. * * @author Giriraj Sharma */ @ApplicationPath("rest") public class HelloWorldApplication extends Application { }
gpl-2.0
eauxnguyen/civicrm-starterkit-drops-7
profiles/civicrm_starterkit/modules/civicrm/packages/jquery/jquery-ui-1.9.0/development-bundle/ui/jquery.ui.effect-fold.js
1704
/*! * jQuery UI Effects Fold 1.9.0-rc.1 * http://jqueryui.com * * Copyright 2012 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://docs.jquery.com/UI/Effects/Fold * * Depends: * jquery.ui.effect.js */ (function( $, undefined ) { $.effects.effect.fold = function( o, done ) { // Create element var el = $( this ), props = [ "position", "top", "bottom", "left", "right", "height", "width" ], mode = $.effects.setMode( el, o.mode || "hide" ), show = mode === "show", hide = mode === "hide", size = o.size || 15, percent = /([0-9]+)%/.exec( size ), horizFirst = !!o.horizFirst, widthFirst = show !== horizFirst, ref = widthFirst ? [ "width", "height" ] : [ "height", "width" ], duration = o.duration / 2, wrapper, distance, animation1 = {}, animation2 = {}; $.effects.save( el, props ); el.show(); // Create Wrapper wrapper = $.effects.createWrapper( el ).css({ overflow: "hidden" }); distance = widthFirst ? [ wrapper.width(), wrapper.height() ] : [ wrapper.height(), wrapper.width() ]; if ( percent ) { size = parseInt( percent[ 1 ], 10 ) / 100 * distance[ hide ? 0 : 1 ]; } if ( show ) { wrapper.css( horizFirst ? { height: 0, width: size } : { height: size, width: 0 }); } // Animation animation1[ ref[ 0 ] ] = show ? distance[ 0 ] : size; animation2[ ref[ 1 ] ] = show ? distance[ 1 ] : 0; // Animate wrapper .animate( animation1, duration, o.easing ) .animate( animation2, duration, o.easing, function() { if ( hide ) { el.hide(); } $.effects.restore( el, props ); $.effects.removeWrapper( el ); done(); }); }; })(jQuery);
gpl-2.0
hcross/firemox
src/main/java/net/sf/firemox/clickable/ability/Optimization.java
6124
/* * Firemox is a turn based strategy simulator * Copyright (C) 2003-2007 Fabrice Daugan * * 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 */ package net.sf.firemox.clickable.ability; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.List; import net.sf.firemox.clickable.target.card.TriggeredCard; import net.sf.firemox.clickable.target.card.TriggeredCardChoice; import net.sf.firemox.event.context.ContextEventListener; import net.sf.firemox.stack.StackManager; import net.sf.firemox.tools.Log; /** * @author <a href="mailto:fabdouglas@users.sourceforge.net">Fabrice Daugan </a> * @since 0.91 */ public enum Optimization { /** * no optimization is done. */ none, /** * An ability is not added in the TBZ if the last ability is the same. Only * ability is compared, the context is ignored. */ follow, /** * The ability would not be added if it already exists in the TBZ. */ first, /** * The ability would replace any existing ability in the TBZ. */ last, /** * Same ability is added only once per action. This important for * LoopingAction. */ action, /** * Ability is added to the TBZ but during the resolution a prompt asks to * controller only one ability to be added to the stack. */ choice, /** * Same ability is added only once per ability triggering this event. */ event, /** * An ability is not added in the TBZ if the last ability is the same. Ability * and context are compared. */ context; /** * Add the specified ability to the TBZ. * * @param ability * the ability to add * @param context * the attached context * @param where * the list where the constructed triggered card would be added * @return true if the specified ability has been added */ public boolean addTo(Ability ability, ContextEventListener context, List<TriggeredCard> where) { // no optimization for this add switch (this) { case none: return where.add(ability.getTriggeredClone(context)); case follow: if (!where.isEmpty()) { final TriggeredCard triggeredCard = where.get(where.size() - 1); if (ability.equals(context, triggeredCard.triggeredAbility, triggeredCard.getAbilityContext())) { // the last ability is the one to add return false; } } return where.add(ability.getTriggeredClone(context)); case first: for (int i = where.size(); i-- > 0;) { final TriggeredCard triggeredCard = where.get(i); if (ability.equals(context, triggeredCard.triggeredAbility, triggeredCard.getAbilityContext())) { // this ability would not be added return false; } } return where.add(ability.getTriggeredClone(context)); case last: for (int i = where.size(); i-- > 0;) { final TriggeredCard triggeredCard = where.get(i); if (ability.equals(context, triggeredCard.triggeredAbility, triggeredCard.getAbilityContext())) { // this ability would replace the old one where.remove(i); where.add(ability.getTriggeredClone(context)); return false; } } return where.add(ability.getTriggeredClone(context)); case action: return where.add(ability.getTriggeredClone(context)); case choice: for (int i = where.size(); i-- > 0;) { final TriggeredCard triggeredCard = where.get(i); if (triggeredCard.abilityID == StackManager.abilityID && ability.equals(context, triggeredCard.triggeredAbility, triggeredCard.getAbilityContext())) { /* * Same ability as already generating one instance of this triggered * ability */ ((TriggeredCardChoice) where.get(i)).addChoice(ability, context); return false; } } return where.add(ability.getTriggeredCloneChoice(context)); case event: for (int i = where.size(); i-- > 0;) { if (where.get(i).abilityID == StackManager.abilityID && ability.equals(where.get(i).triggeredAbility)) { // Same ability as already generating one instance of this triggered // ability return false; } } return where.add(ability.getTriggeredClone(context)); case context: if (!where.isEmpty()) { final TriggeredCard triggeredCard = where.get(where.size() - 1); if (ability.equals(context, triggeredCard.triggeredAbility, triggeredCard.getAbilityContext()) && context.equals(triggeredCard.getAbilityContext())) { // the last ability is the one to add return false; } } return where.add(ability.getTriggeredClone(context)); default: Log.fatal("unmanaged optimization : " + this); return false; } } /** * Write this enumeration to the given output stream. * * @param out * the stream this enumeration would be written. * @throws IOException */ public void write(OutputStream out) throws IOException { out.write(ordinal()); } /** * Read and return the enumeration from the given input stream. * * @param input * the stream containing the enumeration to read. * @return the enumeration from the given input stream. * @throws IOException */ static Optimization valueOf(InputStream input) throws IOException { return values()[input.read()]; } }
gpl-2.0
Moujimouja/centreon
www/include/reporting/dashboard/csvExport/csv_ServiceLogs.php
7100
<?php /* * Copyright 2005-2016 Centreon * Centreon is developped by : Julien Mathis and Romain Le Merlus under * GPL Licence 2.0. * * 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. * * 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, see <http://www.gnu.org/licenses>. * * Linking this program statically or dynamically with other modules is making a * combined work based on this program. Thus, the terms and conditions of the GNU * General Public License cover the whole combination. * * As a special exception, the copyright holders of this program give Centreon * permission to link this program with independent modules to produce an executable, * regardless of the license terms of these independent modules, and to copy and * distribute the resulting executable under terms of Centreon choice, provided that * Centreon also meet, for each linked independent module, the terms and conditions * of the license of that module. An independent module is a module which is not * derived from this program. If you modify this program, you may extend this * exception to your version of the program, but you are not obliged to do so. If you * do not wish to do so, delete this exception statement from your version. * * For more information : contact@centreon.com * */ require_once realpath(dirname(__FILE__) . "/../../../../../config/centreon.config.php"); require_once _CENTREON_PATH_ . "www/class/centreonDB.class.php"; include_once _CENTREON_PATH_ . "www/include/common/common-Func.php"; include_once _CENTREON_PATH_ . "www/include/reporting/dashboard/common-Func.php"; require_once _CENTREON_PATH_ . "www/class/centreonUser.class.php"; require_once _CENTREON_PATH_ . "www/class/centreonSession.class.php"; require_once _CENTREON_PATH_ . "www/class/centreon.class.php"; require_once _CENTREON_PATH_ . "www/class/centreonDuration.class.php"; include_once _CENTREON_PATH_ . "www/include/reporting/dashboard/DB-Func.php"; session_start(); session_write_close(); /* * DB connexion */ $pearDB = new CentreonDB(); $pearDBO = new CentreonDB("centstorage"); $sid = session_id(); if (!empty($sid) && isset($_SESSION['centreon'])) { $oreon = $_SESSION['centreon']; $query = "SELECT user_id FROM session WHERE user_id = '".$pearDB->escape($oreon->user->user_id)."'"; $res = $pearDB->query($query); if (!$res->rowCount()) { get_error('bad session id'); } } else { get_error('need session id!'); } $centreon = $oreon; /* * getting host and service id */ isset($_GET["host"]) ? $host_id = htmlentities($_GET["host"], ENT_QUOTES, "UTF-8") : $host_id = "NULL"; isset($_POST["host"]) ? $host_id = htmlentities($_POST["host"], ENT_QUOTES, "UTF-8") : $host_id; isset($_GET["service"]) ? $service_id = htmlentities($_GET["service"], ENT_QUOTES, "UTF-8") : $service_id = "NULL"; isset($_POST["service"]) ? $service_id = htmlentities($_POST["service"], ENT_QUOTES, "UTF-8") : $service_id; /* * Getting time interval to report */ $dates = getPeriodToReport(); $start_date = htmlentities($_GET['start'], ENT_QUOTES, "UTF-8"); $end_date = htmlentities($_GET['end'], ENT_QUOTES, "UTF-8"); $host_name = getHostNameFromId($host_id); $service_description = getServiceDescriptionFromId($service_id); /* * file type setting */ header("Cache-Control: public"); header("Pragma: public"); header("Content-Type: application/octet-stream"); header("Content-disposition: attachment ; filename=".$host_name. "_" .$service_description.".csv"); echo _("Host").";"._("Service").";"._("Begin date")."; "._("End date")."; "._("Duration")."\n"; echo $host_name."; ".$service_description."; ".date(_("d/m/Y H:i:s"), $start_date)."; " . date(_("d/m/Y H:i:s"), $end_date)."; ".($end_date - $start_date)."s\n"; echo "\n"; echo _("Status").";"._("Time").";"._("Total Time").";"._("Mean Time")."; "._("Alert")."\n"; $reportingTimePeriod = getreportingTimePeriod(); $serviceStats = getLogInDbForOneSVC($host_id, $service_id, $start_date, $end_date, $reportingTimePeriod); echo "OK;".$serviceStats["OK_T"]."s;".$serviceStats["OK_TP"]."%;" . $serviceStats["OK_MP"]. "%;".$serviceStats["OK_A"].";\n"; echo "WARNING;".$serviceStats["WARNING_T"]."s;".$serviceStats["WARNING_TP"]."%;" . $serviceStats["WARNING_MP"]. "%;".$serviceStats["WARNING_A"].";\n"; echo "CRITICAL;".$serviceStats["CRITICAL_T"]."s;".$serviceStats["CRITICAL_TP"]."%;" . $serviceStats["CRITICAL_MP"]. "%;".$serviceStats["CRITICAL_A"].";\n"; echo "UNKNOWN;".$serviceStats["UNKNOWN_T"]."s;".$serviceStats["UNKNOWN_TP"]."%;" . $serviceStats["UNKNOWN_MP"]. "%;".$serviceStats["UNKNOWN_A"].";\n"; echo "UNDETERMINED;".$serviceStats["UNDETERMINED_T"]."s;" . $serviceStats["UNDETERMINED_TP"]."%;;;\n"; echo "\n"; echo "\n"; /* * Getting evolution of service stats in time */ echo _("Day").";"._("Duration").";" ._("OK")." "._("Time")."; "._("OK")."; "._("OK")." Alert;" ._("Warning")." "._("Time")."; "._("Warning").";"._("Warning")." Alert;" ._("Unknown")." "._("Time")."; "._("Unknown").";"._("Unknown")." Alert;" ._("Critical")." "._("Time")."; "._("Critical").";"._("Critical")." Alert;" ._("Day").";\n"; $request = "SELECT * FROM `log_archive_service` " . "WHERE `host_id` = '".$host_id."' " . "AND `service_id` = '".$service_id."' " . "AND `date_start` >= '".$start_date."' " . "AND `date_end` <= '".$end_date."' " . "ORDER BY `date_start` DESC"; $DBRESULT = $pearDBO->query($request); while ($row = $DBRESULT->fetchRow()) { $duration = $row["date_end"] - $row["date_start"]; /* Percentage by status */ $duration = $row["OKTimeScheduled"] + $row["WARNINGTimeScheduled"] + $row["UNKNOWNTimeScheduled"] + $row["CRITICALTimeScheduled"]; $row["OK_MP"] = round($row["OKTimeScheduled"] * 100 / $duration, 2); $row["WARNING_MP"] = round($row["WARNINGTimeScheduled"] * 100 / $duration, 2); $row["UNKNOWN_MP"] = round($row["UNKNOWNTimeScheduled"] * 100 / $duration, 2); $row["CRITICAL_MP"] = round($row["CRITICALTimeScheduled"] * 100 / $duration, 2); echo $row["date_start"].";".$duration.";" . $row["OKTimeScheduled"]."s;".$row["OK_MP"]."%;".$row["OKnbEvent"].";" . $row["WARNINGTimeScheduled"]."s;".$row["WARNING_MP"]."%;".$row["WARNINGnbEvent"].";" . $row["UNKNOWNTimeScheduled"]."s;".$row["UNKNOWN_MP"]."%;".$row["UNKNOWNnbEvent"].";" . $row["CRITICALTimeScheduled"]."s;".$row["CRITICAL_MP"]."%;".$row["CRITICALnbEvent"].";" . date("Y-m-d H:i:s", $row["date_start"]).";\n"; } $DBRESULT->closeCursor();
gpl-2.0
Attnam/ivan
Main/Source/dungeon.cpp
9878
/* * * Iter Vehemens ad Necem (IVAN) * Copyright (C) Timo Kiviluoto * Released under the GNU General * Public License * * See LICENSING which should be included * along with this file for more details * */ #include "audio.h" #include "bitmap.h" #include "database.h" #include "dbgmsgproj.h" #include "dungeon.h" #include "error.h" #include "lsquare.h" #include "femath.h" #include "game.h" #include "graphics.h" #include "level.h" #include "message.h" #include "save.h" #include "script.h" dungeon::dungeon(int Index) : Index(Index) { Initialize(); for(int c = 0; c < GetLevels(); ++c) Generated[c] = false; } dungeon::~dungeon() { for(int c = 0; c < GetLevels(); ++c) delete Level[c]; delete [] Level; delete [] Generated; } void dungeon::Initialize() { std::map<int, dungeonscript>::const_iterator DungeonIterator = game::GetGameScript()->GetDungeon().find(Index); if(DungeonIterator != game::GetGameScript()->GetDungeon().end()) DungeonScript = &DungeonIterator->second; else { ABORT("Unknown dungeon #%d requested!", Index); return; } Level = new level*[GetLevels()]; Generated = new truth[GetLevels()]; for(int c = 0; c < GetLevels(); ++c) Level[c] = 0; } const levelscript* dungeon::GetLevelScript(int I) { std::map<int, levelscript>::const_iterator LevelIterator = DungeonScript->GetLevel().find(I); const levelscript* LevelScript; if(LevelIterator != DungeonScript->GetLevel().end()) LevelScript = &LevelIterator->second; else LevelScript = DungeonScript->GetLevelDefault(); return LevelScript; } /* Returns whether the level has been visited before */ truth dungeon::PrepareLevel(int Index, truth Visual) { graphics::SetDenyStretchedBlit(); if(Generated[Index]) { level* NewLevel = LoadLevel(game::SaveName(), Index); game::SetCurrentArea(NewLevel); game::SetCurrentLevel(NewLevel); game::SetCurrentLSquareMap(NewLevel->GetMap()); return true; } else { festring fsGenLoopDL;{const char* pc = std::getenv("IVAN_DebugGenDungeonLevelLoopID");if(pc!=NULL)fsGenLoopDL<<pc;} int iGenLoopMax=250;{const char* pc = std::getenv("IVAN_DebugGenDungeonLevelLoopMax");if(pc!=NULL)iGenLoopMax=atoi(pc);} festring fsDL;fsDL<<GetIndex()<<Index; int iRetryMax = fsGenLoopDL==fsDL ? iGenLoopMax : 10; DBG3("GeneratingDungeonLevel",fsDL.CStr(),fsGenLoopDL.CStr()); level* NewLevel=NULL; cbitmap* EnterImage=NULL; for(int i=0;i<iRetryMax;i++){ try{ if(!genericException::ToggleGenNewLvl())ABORT("expecting gen lvl to become: true"); NewLevel = Level[Index] = new level; NewLevel->SetDungeon(this); NewLevel->SetIndex(Index); const levelscript* LevelScript = GetLevelScript(Index); NewLevel->SetLevelScript(LevelScript); DBG7("GeneratingDungeonLevel",NewLevel->GetDungeon()->GetIndex(),Index,fsDL.CStr(),fsGenLoopDL.CStr(),i,NewLevel->GetDungeon()->GetLevelDescription(Index, true).CStr()); if(Visual) { if(LevelScript->GetEnterImage()) { EnterImage = new bitmap(game::GetDataDir() + "Graphics/" + *LevelScript->GetEnterImage()); game::SetEnterImage(EnterImage); v2 Displacement = *LevelScript->GetEnterTextDisplacement(); game::SetEnterTextDisplacement(Displacement); game::TextScreen(CONST_S("Entering ") + GetLevelDescription(Index) + CONST_S("...\n\nThis may take some time, please wait."), Displacement, WHITE, false, true, &game::BusyAnimation); game::TextScreen(CONST_S("Entering ") + GetLevelDescription(Index) + CONST_S("...\n\nPress any key to continue."), Displacement, WHITE, game::GetAutoPlayMode()<2, false, &game::BusyAnimation); game::SetEnterImage(0); delete EnterImage; EnterImage=NULL; } else { game::SetEnterTextDisplacement(ZERO_V2); game::TextScreen(CONST_S("Entering ") + GetLevelDescription(Index) + CONST_S("...\n\nThis may take some time, please wait."), ZERO_V2, WHITE, false, true, &game::BusyAnimation); } } NewLevel->Generate(Index); game::SetCurrentLSquareMap(NewLevel->GetMap()); Generated[Index] = true; game::BusyAnimation(); if(*NewLevel->GetLevelScript()->GenerateMonsters()) NewLevel->GenerateNewMonsters(NewLevel->GetIdealPopulation(), false); if(genericException::ToggleGenNewLvl())ABORT("expecting gen lvl to become: false"); if(fsGenLoopDL!=fsDL) return false; // new level is ok }catch(const genericException& e){ // cleanup //TODO it is not working well, memory usage keeps increasing... if(NewLevel ){delete NewLevel ;NewLevel=NULL;} if(EnterImage){delete EnterImage;EnterImage=NULL;} //retry } } //for() if(fsGenLoopDL==fsDL)ABORT("Generating dungeon loop test completed."); ABORT("Generating new level failed after %d retries, aborting...",iRetryMax); } } void dungeon::PrepareMusic(int Index) { const levelscript* LevelScript = GetLevelScript(Index); bool hasCurrentTrack = false; festring CurrentTrack = audio::GetCurrentlyPlayedFile(); for( int i = 0; i < LevelScript->GetAudioPlayList()->Size; ++i ) { festring Music = LevelScript->GetAudioPlayList()->Data[i]; if( CurrentTrack == Music ) { hasCurrentTrack = true; break; } } if( hasCurrentTrack == true ) { audio::ClearMIDIPlaylist(CurrentTrack); for( int i = 0; i < LevelScript->GetAudioPlayList()->Size; ++i ) { festring Music = LevelScript->GetAudioPlayList()->Data[i]; if( CurrentTrack == Music ) { } else { audio::LoadMIDIFile(Music, 0, 100); } } } if( hasCurrentTrack == false ) { audio::SetPlaybackStatus(audio::STOPPED); audio::ClearMIDIPlaylist(); for( int i = 0; i < LevelScript->GetAudioPlayList()->Size; ++i ) { festring Music = LevelScript->GetAudioPlayList()->Data[i]; audio::LoadMIDIFile(Music, 0, 100); } audio::SetPlaybackStatus(audio::PLAYING); } } void dungeon::SaveLevel(cfestring& SaveName, int Number, truth DeleteAfterwards) { outputfile SaveFile(SaveName + '.' + Index + Number); SaveFile << Level[Number]; if(DeleteAfterwards) { delete Level[Number]; Level[Number] = 0; } } level* dungeon::LoadLevel(cfestring& SaveName, int Number) { inputfile SaveFile(SaveName + '.' + Index + Number); return LoadLevel(SaveFile, Number); } void dungeon::Save(outputfile& SaveFile) const { SaveFile << Index << WorldMapPos; for(int c = 0; c < GetLevels(); ++c) SaveFile << Generated[c]; } void dungeon::Load(inputfile& SaveFile) { SaveFile >> Index >> WorldMapPos; Initialize(); for(int c = 0; c < GetLevels(); ++c) SaveFile >> Generated[c]; } int dungeon::GetLevels() const { return *DungeonScript->GetLevels(); } festring dungeon::GetLevelDescription(int I,bool bPretty) { if(GetLevel(I)->GetLevelScript()->GetDescription()){ return *GetLevel(I)->GetLevelScript()->GetDescription(); }else{ festring fs = *DungeonScript->GetDescription(); int i = I+1; if(bPretty){ festring fsRoman; // roman numbers const char* X[] = {"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"}; fsRoman << X[(i%100)/10]; const char* I[] = {"","I","II","III","IV","V","VI","VII","VIII","IX"}; fsRoman << I[(i%10)]; return fs + " " + fsRoman; }else{ return fs + " level " + i; } } } festring dungeon::GetShortLevelDescription(int I) { if(GetLevel(I)->GetLevelScript()->GetShortDescription()) return *GetLevel(I)->GetLevelScript()->GetShortDescription(); else return *DungeonScript->GetShortDescription() + " lvl " + (I + 1); } outputfile& operator<<(outputfile& SaveFile, const dungeon* Dungeon) { if(Dungeon) { SaveFile.Put(1); Dungeon->Save(SaveFile); } else SaveFile.Put(0); return SaveFile; } inputfile& operator>>(inputfile& SaveFile, dungeon*& Dungeon) { if(SaveFile.Get()) { Dungeon = new dungeon; Dungeon->Load(SaveFile); } return SaveFile; } /** * The wrong luminance saved to a lsquare problem * may happen after craft/split eg.: a blue crystal stone, * then you save the game and re-load it and the luminance would be still there. * TODO this workaround will not be necessary when the problem is fixed on it's origin */ void WorkaroundFixLuminance(level* lvl) { for(int iY=0;iY<lvl->GetYSize();iY++){for(int iX=0;iX<lvl->GetXSize();iX++){ static lsquare* lsqr;lsqr=lvl->GetLSquare(iX,iY); lsqr->SignalEmitationDecrease(lsqr->GetEmitation()); lsqr->CalculateLuminance(); }} } level* dungeon::LoadLevel(inputfile& SaveFile, int Number) { SaveFile >> Level[Number]; Level[Number]->SetDungeon(this); Level[Number]->SetIndex(Number); Level[Number]->SetLevelScript(GetLevelScript(Number)); PrepareMusic(Number); WorkaroundFixLuminance(Level[Number]); return Level[Number]; } int dungeon::GetLevelTeleportDestination(int From) const { int To; if(Index == ELPURI_CAVE) { if(RAND_2) { To = From + RAND_2 + RAND_2 + RAND_2 + RAND_2 + 1; if(To > DARK_LEVEL) To = From; } else { To = From - RAND_2 - RAND_2 - RAND_2 - RAND_2 - 1; if(To < 0) To = 0; } return To; } if(Index == UNDER_WATER_TUNNEL) return RAND_N(3); return From; }
gpl-2.0
fb/XCSoar
src/GliderLink/GliderLinkId.hpp
1388
/* Copyright_License { XCSoar Glide Computer - http://www.xcsoar.org/ Copyright (C) 2000-2018 The XCSoar Project A detailed list of copyright holders can be found in the file "AUTHORS". 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. } */ #ifndef XCSOAR_GLIDER_LINK_ID_HPP #define XCSOAR_GLIDER_LINK_ID_HPP #include <cstdint> /** * The identification number of a GliderLink traffic. */ class GliderLinkId { uint32_t value; public: explicit constexpr GliderLinkId(uint32_t _value):value(_value) {} GliderLinkId() = default; constexpr bool operator==(GliderLinkId other) const { return value == other.value; } constexpr bool operator<(GliderLinkId other) const { return value < other.value; } }; #endif
gpl-2.0
drptbl/snort3
src/ips_options/ips_byte_jump.cc
13703
//-------------------------------------------------------------------------- // Copyright (C) 2014-2015 Cisco and/or its affiliates. All rights reserved. // Copyright (C) 2002-2013 Sourcefire, Inc. // // This program is free software; you can redistribute it and/or modify it // under the terms of the GNU General Public License Version 2 as published // by the Free Software Foundation. You may not use, modify or distribute // this program under any other version of the GNU General Public License. // // 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. //-------------------------------------------------------------------------- /* sp_byte_jump * Author: Martin Roesch * * Purpose: * Grab some number of bytes, convert them to their numeric * representation, jump the cursor up that many bytes (for * further pattern matching/byte_testing). * * * Arguments: * Required: * <bytes_to_grab>: number of bytes to pick up from the packet * <offset>: number of bytes into the payload to grab the bytes * Optional: * ["relative"]: offset relative to last pattern match * ["big"]: process data as big endian (default) * ["little"]: process data as little endian * ["string"]: converted bytes represented as a string needing conversion * ["hex"]: converted string data is represented in hexidecimal * ["dec"]: converted string data is represented in decimal * ["oct"]: converted string data is represented in octal * ["align"]: round the number of converted bytes up to the next * 32-bit boundry * ["post_offset"]: number of bytes to adjust after applying * * sample rules: * alert udp any any -> any 32770:34000 (content: "|00 01 86 B8|"; \ * content: "|00 00 00 01|"; distance: 4; within: 4; \ * byte_jump: 4, 12, relative, align; \ * byte_test: 4, >, 900, 20, relative; \ * msg: "statd format string buffer overflow";) * * Effect: * * Reads in the indicated bytes, converts them to an numeric * representation and then jumps the cursor up * that number of bytes. Returns 1 if the jump is in range (within the * packet) and 0 if it's not. * * Comments: * * Any comments? * */ #include <sys/types.h> #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <stdlib.h> #include <ctype.h> #include <errno.h> #include <string> #include "snort_types.h" #include "snort_bounds.h" #include "detection/treenodes.h" #include "protocols/packet.h" #include "parser.h" #include "snort_debug.h" #include "util.h" #include "extract.h" #include "ips_byte_extract.h" #include "sfhashfcn.h" #include "profiler.h" #include "sfhashfcn.h" #include "detection/detection_defines.h" #include "detection/detection_util.h" #include "framework/cursor.h" #include "framework/ips_option.h" #include "framework/parameter.h" #include "framework/module.h" static THREAD_LOCAL ProfileStats byteJumpPerfStats; #define s_name "byte_jump" using namespace std; typedef struct _ByteJumpData { uint32_t bytes_to_grab; int32_t offset; uint8_t relative_flag; uint8_t data_string_convert_flag; uint8_t from_beginning_flag; uint8_t align_flag; int8_t endianess; uint32_t base; uint32_t multiplier; int32_t post_offset; int8_t offset_var; } ByteJumpData; class ByteJumpOption : public IpsOption { public: ByteJumpOption(const ByteJumpData& c) : IpsOption(s_name) { config = c; } ~ByteJumpOption() { } uint32_t hash() const override; bool operator==(const IpsOption&) const override; CursorActionType get_cursor_type() const override { return CAT_ADJUST; } bool is_relative() override { return (config.relative_flag == 1); } int eval(Cursor&, Packet*) override; private: ByteJumpData config; }; //------------------------------------------------------------------------- // class methods //------------------------------------------------------------------------- uint32_t ByteJumpOption::hash() const { uint32_t a,b,c; const ByteJumpData* data = &config; a = data->bytes_to_grab; b = data->offset; c = data->base; mix(a,b,c); a += (data->relative_flag << 24 | data->data_string_convert_flag << 16 | data->from_beginning_flag << 8 | data->align_flag); b += data->endianess; c += data->multiplier; mix(a,b,c); a += data->post_offset; b += data->offset_var; mix(a,b,c); mix_str(a,b,c,get_name()); final(a,b,c); return c; } bool ByteJumpOption::operator==(const IpsOption& ips) const { if ( strcmp(s_name, ips.get_name()) ) return false; ByteJumpOption& rhs = (ByteJumpOption&)ips; ByteJumpData* left = (ByteJumpData*)&config; ByteJumpData* right = (ByteJumpData*)&rhs.config; if (( left->bytes_to_grab == right->bytes_to_grab) && ( left->offset == right->offset) && ( left->offset_var == right->offset_var) && ( left->relative_flag == right->relative_flag) && ( left->data_string_convert_flag == right->data_string_convert_flag) && ( left->from_beginning_flag == right->from_beginning_flag) && ( left->align_flag == right->align_flag) && ( left->endianess == right->endianess) && ( left->base == right->base) && ( left->multiplier == right->multiplier) && ( left->post_offset == right->post_offset)) { return true; } return false; } int ByteJumpOption::eval(Cursor& c, Packet*) { ByteJumpData* bjd = (ByteJumpData*)&config; int rval = DETECTION_OPTION_NO_MATCH; uint32_t jump = 0; uint32_t payload_bytes_grabbed = 0; int32_t offset; PROFILE_VARS; MODULE_PROFILE_START(byteJumpPerfStats); /* Get values from byte_extract variables, if present. */ if (bjd->offset_var >= 0 && bjd->offset_var < NUM_BYTE_EXTRACT_VARS) { uint32_t extract_offset; GetByteExtractValue(&extract_offset, bjd->offset_var); offset = (int32_t)extract_offset; } else { offset = bjd->offset; } const uint8_t* const start_ptr = c.buffer(); const int dsize = c.size(); const uint8_t* const end_ptr = start_ptr + dsize; const uint8_t* const base_ptr = offset + ((bjd->relative_flag) ? c.start() : start_ptr); /* Both of the extraction functions contain checks to ensure the data * is inbounds and will return no match if it isn't */ if ( !bjd->data_string_convert_flag ) { if ( byte_extract( bjd->endianess, bjd->bytes_to_grab, base_ptr, start_ptr, end_ptr, &jump) ) { MODULE_PROFILE_END(byteJumpPerfStats); return rval; } payload_bytes_grabbed = bjd->bytes_to_grab; } else { int32_t tmp = string_extract( bjd->bytes_to_grab, bjd->base, base_ptr, start_ptr, end_ptr, &jump); if (tmp < 0) { MODULE_PROFILE_END(byteJumpPerfStats); return rval; } payload_bytes_grabbed = tmp; } // Negative offsets that put us outside the buffer should have been caught // in the extraction routines assert(base_ptr >= c.buffer()); if (bjd->multiplier) jump *= bjd->multiplier; /* if we need to align on 32-bit boundries, round up to the next * 32-bit value */ if (bjd->align_flag) { if ((jump % 4) != 0) { jump += (4 - (jump % 4)); } } if ( !bjd->from_beginning_flag ) { jump += payload_bytes_grabbed; jump += c.get_pos(); } jump += offset; jump += bjd->post_offset; if ( !c.set_pos(jump) ) { MODULE_PROFILE_END(byteJumpPerfStats); return rval; } else { rval = DETECTION_OPTION_MATCH; } MODULE_PROFILE_END(byteJumpPerfStats); return rval; } //------------------------------------------------------------------------- // module //------------------------------------------------------------------------- static const Parameter s_params[] = { { "~count", Parameter::PT_INT, "1:10", nullptr, "number of bytes to pick up from the buffer" }, { "~offset", Parameter::PT_STRING, nullptr, nullptr, "variable name or number of bytes into the buffer to start processing" }, { "relative", Parameter::PT_IMPLIED, nullptr, nullptr, "offset from cursor instead of start of buffer" }, { "from_beginning", Parameter::PT_IMPLIED, nullptr, nullptr, "jump from start of buffer instead of cursor" }, { "multiplier", Parameter::PT_INT, "1:65535", "1", "scale extracted value by given amount" }, { "align", Parameter::PT_INT, "0:4", "0", "round the number of converted bytes up to the next 2- or 4-byte boundary" }, { "post_offset", Parameter::PT_INT, "-65535:65535", "0", "also skip forward or backwards (positive of negative value) this number of bytes" }, { "big", Parameter::PT_IMPLIED, nullptr, nullptr, "big endian" }, { "little", Parameter::PT_IMPLIED, nullptr, nullptr, "little endian" }, { "dce", Parameter::PT_IMPLIED, nullptr, nullptr, "dcerpc2 determines endianness" }, { "string", Parameter::PT_IMPLIED, nullptr, nullptr, "convert from string" }, { "hex", Parameter::PT_IMPLIED, nullptr, nullptr, "convert from hex string" }, { "oct", Parameter::PT_IMPLIED, nullptr, nullptr, "convert from octal string" }, { "dec", Parameter::PT_IMPLIED, nullptr, nullptr, "convert from decimal string" }, { nullptr, Parameter::PT_MAX, nullptr, nullptr, nullptr } }; #define s_help \ "rule option to move the detection cursor" class ByteJumpModule : public Module { public: ByteJumpModule() : Module(s_name, s_help, s_params) { } bool begin(const char*, int, SnortConfig*) override; bool end(const char*, int, SnortConfig*) override; bool set(const char*, Value&, SnortConfig*) override; ProfileStats* get_profile() const override { return &byteJumpPerfStats; } ByteJumpData data; string var; }; bool ByteJumpModule::begin(const char*, int, SnortConfig*) { memset(&data, 0, sizeof(data)); var.clear(); data.multiplier = 1; return true; } bool ByteJumpModule::end(const char*, int, SnortConfig*) { if ( var.empty() ) data.offset_var = BYTE_EXTRACT_NO_VAR; else { data.offset_var = GetVarByName(var.c_str()); if (data.offset_var == BYTE_EXTRACT_NO_VAR) { ParseError(BYTE_EXTRACT_INVALID_ERR_STR, "byte_jump", var.c_str()); return false; } } unsigned e1 = ffs(data.endianess); unsigned e2 = ffs(data.endianess >> e1); if ( e1 && e2 ) { ParseError("byte_jump has multiple arguments " "specifying the type of string conversion. Use only " "one of 'dec', 'hex', or 'oct'."); return false; } return true; } bool ByteJumpModule::set(const char*, Value& v, SnortConfig*) { if ( v.is("~count") ) data.bytes_to_grab = v.get_long(); else if ( v.is("~offset") ) { long n; if ( v.strtol(n) ) data.offset = n; else var = v.get_string(); } else if ( v.is("relative") ) data.relative_flag = 1; else if ( v.is("from_beginning") ) data.from_beginning_flag = 1; else if ( v.is("align") ) data.align_flag = 1; else if ( v.is("multiplier") ) data.multiplier = v.get_long(); else if ( v.is("post_offset") ) data.post_offset = v.get_long(); else if ( v.is("big") ) data.endianess |= ENDIAN_BIG; else if ( v.is("little") ) data.endianess |= ENDIAN_LITTLE; else if ( v.is("dce") ) data.endianess |= ENDIAN_FUNC; else if ( v.is("string") ) { data.data_string_convert_flag = 1; data.base = 10; } else if ( v.is("dec") ) data.base = 10; else if ( v.is("hex") ) data.base = 16; else if ( v.is("oct") ) data.base = 8; else return false; return true; } //------------------------------------------------------------------------- // api methods //------------------------------------------------------------------------- static Module* mod_ctor() { return new ByteJumpModule; } static void mod_dtor(Module* m) { delete m; } static IpsOption* byte_jump_ctor(Module* p, OptTreeNode*) { ByteJumpModule* m = (ByteJumpModule*)p; return new ByteJumpOption(m->data); } static void byte_jump_dtor(IpsOption* p) { delete p; } static const IpsApi byte_jump_api = { { PT_IPS_OPTION, sizeof(IpsApi), IPSAPI_VERSION, 0, API_RESERVED, API_OPTIONS, s_name, s_help, mod_ctor, mod_dtor }, OPT_TYPE_DETECTION, 0, 0, nullptr, nullptr, nullptr, nullptr, byte_jump_ctor, byte_jump_dtor, nullptr }; #ifdef BUILDING_SO SO_PUBLIC const BaseApi* snort_plugins[] = { &byte_jump_api.base, nullptr }; #else const BaseApi* ips_byte_jump = &byte_jump_api.base; #endif
gpl-2.0
mdzakir/HelloWorld
components/com_osproperty/helpers/cronhelper.php
16988
<?php /*------------------------------------------------------------------------ # cronhelper.php - Ossolution Property # ------------------------------------------------------------------------ # author Dang Thuc Dam # copyright Copyright (C) 2015 joomdonation.com. All Rights Reserved. # @license - http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL # Websites: http://www.joomdonation.com # Technical Support: Forum - http://www.joomdonation.com/forum.html */ // no direct access defined('_JEXEC') or die('Restricted access'); class OSPHelperCron{ /** * This function is used to check the property is suitable with the list * @param $property * @param $list */ static function checkProperty($property,$list){ $db = JFactory::getDbo(); $db->setQuery("Select * from #__osrs_user_list_details where list_id = '$list->id'"); $list_details = $db->loadObjectList(); for($i=0;$i<count($list_details);$i++) { $list_detail = $list_details[$i]; switch ($list_detail->field_id) { case "keyword": JRequest::setVar('keyword',$list_detail->search_param); break; case "add": JRequest::setVar('address', $list_detail->search_param); break; case "agent_type": JRequest::setVar('agent_type', $list_detail->search_param); break; case "catid": $temp_category_ids[] = $list_detail->search_param; break; case "type": //JRequest::setVar('property_type',$list_detail->search_param); $temp_type_ids[] = $list_detail->search_param; break; case "amenity": $temp_amen_ids[] = $list_detail->search_param; break; case "country": JRequest::setVar('country_id', $list_detail->search_param); break; case "state": JRequest::setVar('state_id', $list_detail->search_param); break; case "city": JRequest::setVar('city', $list_detail->search_param); break; case "nbath": JRequest::setVar('nbath', $list_detail->search_param); break; case "nbed": JRequest::setVar('nbed', $list_detail->search_param); break; case "price": JRequest::setVar('price', $list_detail->search_param); break; case "min_price": JRequest::setVar('min_price', $list_detail->search_param); break; case "max_price": JRequest::setVar('max_price', $list_detail->search_param); break; case "nroom": JRequest::setVar('nroom', $list_detail->search_param); break; case "nfloors": JRequest::setVar('nfloors', $list_detail->search_param); break; case "sqft_min": JRequest::setVar('sqft_min', $list_detail->search_param); break; case "sqft_max": JRequest::setVar('sqft_max', $list_detail->search_param); break; case "lotsize_min": JRequest::setVar('lotsize_min', $list_detail->search_param); break; case "lotsize_max": JRequest::setVar('lotsize_max', $list_detail->search_param); break; case "featured": JRequest::setVar('isFeatured', $list_detail->search_param); break; case "sold": JRequest::setVar('isSold', $list_detail->search_param); break; case "sortby": JRequest::setVar('sortby', $list_detail->search_param); break; case "orderby": JRequest::setVar('orderby', $list_detail->search_param); break; default: HelperOspropertyFields::setFieldValue($list_detail); break; } } if(count($temp_category_ids) > 0){ JRequest::setVar('category_ids',$temp_category_ids); } if(count($temp_type_ids) > 0){ JRequest::setVar('property_types',$temp_type_ids); } if(count($temp_amen_ids) > 0){ JRequest::setVar('amenities',$temp_amen_ids); } $category_ids = JRequest::getVar('category_ids');//array $agent_type = JRequest::getInt('agent_type',-1); $country_id = JRequest::getVar('country_id',HelperOspropertyCommon::getDefaultCountry()); $city = JRequest::getInt('city',0); $state_id = JRequest::getInt('state_id',0); $nbed = JRequest::getInt('nbed',0); $nbath = JRequest::getInt('nbath',0); $price = JRequest::getInt('price',0); $nroom = JRequest::getInt('nroom',0); $nfloors = JRequest::getInt('nfloors',0); $address = OSPHelper::getStringRequest('address','',''); $address = $db->escape($address); $keyword = OSPHelper::getStringRequest('keyword','',''); //JRequest::getVar('keyword','','','string'); $keyword = $db->escape($keyword); $isFeatured = JRequest::getInt('isFeatured',0); $isSold = JRequest::getInt('isSold',0); $sortby = JRequest::getVar('sortby',$configClass['adv_sortby']); $orderby = JRequest::getVar('orderby',$configClass['adv_orderby']); $min_price = JRequest::getInt('min_price',0); $max_price = JRequest::getInt('max_price',0); $sqft_min = JRequest::getInt('sqft_min',0); $sqft_max = JRequest::getInt('sqft_max',0); $lotsize_min = JRequest::getInt('lotsize_min',0); $lotsize_max = JRequest::getInt('lotsize_max',0); $amenities = Jrequest::getVar('amenities','','','array'); $property_types = JRequest::getVar('property_types',null);//array $category_ids = JRequest::getVar('category_ids');//array if(count($amenities) > 0){ $amenities_str = implode(",",$amenities); if($amenities_str != ""){ $amenities_sql = " AND a.id in (SELECT pro_id FROM #__osrs_property_amenities WHERE amen_id in ($amenities_str) group by pro_id having count(pro_id) = ".count($amenities).")"; $dosearch = 1; }else{ $amenities_sql = ""; } }else{ $amenities_sql = ""; } $access_sql = ""; $db->setQuery("Select * from #__osrs_fieldgroups where published = '1' $access_sql order by ordering"); $groups = $db->loadObjectList(); if(count($groups) > 0){ $extrafieldSql = array(); for($i=0;$i<count($groups);$i++){ $group = $groups[$i]; $extraSql = ""; if(count($types) > 0){ $extraSql = " and id in (Select fid from #__osrs_extra_field_types where type_id in (".implode(",",$types).")) "; }elseif($adv_type > 0){ $extraSql = " and id in (Select fid from #__osrs_extra_field_types where type_id = '$adv_type')"; } $db->setQuery("Select * from #__osrs_extra_fields where group_id = '$group->id' $extraSql and published = '1' and searchable = '1' $access_sql order by ordering"); //echo $db->getQuery(); $fields = $db->loadObjectList(); $group->fields = $fields; if(count($fields) > 0){ for($j=0;$j<count($fields);$j++){ $field = $fields[$j]; //check do search $check = HelperOspropertyFields::checkField($field); if($check){ $dosearch = 1; $sql = HelperOspropertyFields::buildQuery($field); if($sql != ""){ $extrafieldSql[] = $sql; $param[] = HelperOspropertyFields::getFieldParam($field); } } } } } } //$select = "SELECT distinct a.id, a.*, c.name as agent_name,c.photo as agent_photo, d.id as type_id,d.type_name$lang_suffix as type_name, e.country_name"; $count = "SELECT count(distinct a.id) "; $from = " FROM #__osrs_properties as a" ." INNER JOIN #__osrs_agents as c on c.id = a.agent_id" ." INNER JOIN #__osrs_types as d on d.id = a.pro_type" ." INNER JOIN #__osrs_states as g on g.id = a.state" ." LEFT JOIN #__osrs_cities as h on h.id = a.city" ." LEFT JOIN #__osrs_countries as e on e.id = a.country"; $where = " WHERE a.published = '1' AND a.approved = '1' "; //important point $where .= " AND a.id = '$property->id'"; if(intval($user->id) > 0){ $special = HelperOspropertyCommon::checkSpecial(); if($special){ $where .= " and a.`access` in (0,1,2) "; }else{ $where .= " and a.`access` in (0,1) "; } }else{ $where .= " and a.`access` = '0' "; } //if($sortby == "a.isFeatured"){ // $Order_by = " ORDER BY $sortby $orderby,a.created desc"; // }else{ // $Order_by = " ORDER BY $sortby $orderby"; //} if($isFeatured == 1){ $where .= " AND a.isFeatured = '1'"; } if($isSold == 1){ $where .= " AND a.isSold = '1'"; } if($address != ""){ $address = str_replace(";","",$address); if(strpos($address,",")){ $addressArr = explode(",",$address); if(count($addressArr) > 0){ $where .= " AND ("; foreach ($addressArr as $address_item){ $where .= " a.ref like '%$address_item%' OR"; $where .= " a.pro_name$lang_suffix like '%$address_item%' OR"; $where .= " a.address like '%$address_item%' OR"; $where .= " a.region like '%$address_item%' OR"; $where .= " a.postcode like '%$address_item%' OR"; $where .= " g.state_name$lang_suffix like '%$address_item%' OR"; $where .= " h.city$lang_suffix like '%$address_item%' OR"; } $where = substr($where,0,strlen($where)-2); $where .= " )"; } }else{ $where .= " AND ("; $where .= " a.ref like '%$address%' OR"; $where .= " a.pro_name$lang_suffix like '%$address%' OR"; $where .= " a.address like '%$address%' OR"; $where .= " a.region like '%$address%' OR"; $where .= " g.state_name$lang_suffix like '%$address%' OR"; $where .= " h.city$lang_suffix like '%$address%' OR"; $where .= " a.postcode like '%$address%'"; $where .= " )"; } $no_search = false; } if($keyword != ""){ $where .= " AND ("; $where .= " a.ref like '%$keyword%' OR"; $where .= " a.pro_name$lang_suffix like '%$keyword%' OR"; $where .= " a.pro_small_desc$lang_suffix like '%$keyword%' OR"; $where .= " a.pro_full_desc$lang_suffix like '%$keyword%' OR"; $where .= " a.note like '%$keyword%' OR"; $where .= " a.postcode like '%$keyword%' OR"; $where .= " g.state_name$lang_suffix like '%$keyword%' OR"; $where .= " h.city$lang_suffix like '%$keyword%' OR"; $where .= " a.ref like '%$keyword%'"; $where .= " )"; $no_search = false; } if (count($category_ids) > 0){ $categoryArr = array(); foreach ($category_ids as $category_id){ if($category_id > 0){ $categoryArr = HelperOspropertyCommon::getSubCategories($category_id,$categoryArr); $no_search = false; } } $catids = implode(",",$categoryArr); if($catids != ""){ $where .= " AND a.id in (Select pid from #__osrs_property_categories where category_id in ($catids)) "; } } if (count($property_types) > 0){ $no_search = false; //$type_ids = implode(",",$property_types); $tempArr = array(); foreach ($property_types as $type_id){ if($type_id > 0){ $tempArr[] = "$type_id"; } } if(count($tempArr) > 0){ $temp_sql = implode(",",$tempArr); $where .= " AND a.pro_type in (".$temp_sql.")"; } } //if ($property_type > 0) {$where .= " AND a.pro_type = '$property_type'"; $no_search = false;} if ($country_id > 0) {$where .= " AND a.country = '$country_id'"; $no_search = false;} if ($city > 0) {$where .= " AND a.city = '$city'"; $no_search = false;} if ($state_id >0) {$where .= " AND a.state = '$state_id'"; $no_search = false;} if ($nbed > 0) {$where .= " AND a.bed_room >= '$nbed'"; $no_search = false;} if ($nbath > 0) {$where .= " AND a.bath_room >= '$nbath'"; $no_search = false;} if ($nroom > 0) {$where .= " AND a.rooms >= '$nroom'"; $no_search = false;} if ($nfloors > 0) {$where .= " AND a.number_of_floors >= '$nfloors'"; $no_search = false;} if ($agent_type >= 0) {$where .= " AND c.agent_type = '$agent_type'"; $no_search = false;} if($price > 0){ $db->setQuery("Select * from #__osrs_pricegroups where id = '$price'"); $pricegroup = $db->loadObject(); $price_from = $pricegroup->price_from; $price_to = $pricegroup->price_to; if($price_from > 0){ $where .= " AND (a.price >= '$price_from')"; } if($price_to > 0){ $where .= " AND (a.price <= '$price_to')"; } $no_search = false; } if($min_price > 0){ $where .= " AND a.price >= '$min_price'"; } if($max_price > 0){ $where .= " AND a.price <= '$max_price'"; } if($sqft_min > 0){ $where .= " AND a.square_feet >= '$sqft_min'"; $lists['sqft_min'] = $sqft_min; } if($sqft_max > 0){ $where .= " AND a.square_feet <= '$sqft_max'"; $lists['sqft_max'] = $sqft_max; } if($lotsize_min > 0){ $where .= " AND a.lot_size >= '$lotsize_min'"; $lists['lotsize_min'] = $lotsize_min; } if($lotsize_max > 0){ $where .= " AND a.lot_size <= '$lotsize_max'"; $lists['lotsize_max'] = $lotsize_max; } if((isset($extrafieldSql)) AND (count($extrafieldSql)) > 0){ $extrafieldSql = implode(" AND ",$extrafieldSql); if(trim($extrafieldSql) != ""){ $where .= " AND ".$extrafieldSql; } } $where .= $amenities_sql; $where .= $rangeDateQuery; $db->setQuery($count.' '.$from.' '.$where.' '.$group_by); $total = $db->loadResult(); if(intval($total) > 0) { //insert into MySQL #__osrs_list_properties $db->setQuery("Select count(id) from #__osrs_list_properties where pid = '$property->id' and list_id = '$list->id'"); $count = $db->loadResult(); if ($count == 0) { $db->setQuery("Insert into #__osrs_list_properties (id,pid,list_id,sent_notify) values (NULL,'$property->id','$list->id',1)"); $db->query(); } else { $db->setQuery("Insert into #__osrs_list_properties (id,pid,list_id,sent_notify) values (NULL,'$property->id','$list->id','0')"); $db->query(); } }else{ $db->setQuery("Insert into #__osrs_list_properties (id,pid,list_id,sent_notify) values (NULL,'$property->id','$list->id','0')"); $db->query(); } } } ?>
gpl-2.0
mikegarite/hoppedla
wp-content/themes/hoppedla/content-single-product.php
1956
<?php /** * The template for displaying product content in the single-product.php template * * Override this template by copying it to yourtheme/woocommerce/content-single-product.php * * @author WooThemes * @package WooCommerce/Templates * @version 1.6.4 */ if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly ?> <?php /** * woocommerce_before_single_product hook * * @hooked wc_print_notices - 10 */ do_action( 'woocommerce_before_single_product' ); if ( post_password_required() ) { echo get_the_password_form(); return; } ?> <div itemscope itemtype="<?php echo woocommerce_get_product_schema(); ?>" id="product-<?php the_ID(); ?>" <?php post_class(); ?>> <?php /** * woocommerce_before_single_product_summary hook * * @hooked woocommerce_show_product_sale_flash - 10 * @hooked woocommerce_show_product_images - 20 */ do_action( 'woocommerce_before_single_product_summary' ); ?> <div class="summary entry-summary"> <?php /** * woocommerce_single_product_summary hook * * @hooked woocommerce_template_single_title - 5 * @hooked woocommerce_template_single_rating - 10 * @hooked woocommerce_template_single_price - 10 * @hooked woocommerce_template_single_excerpt - 20 * @hooked woocommerce_template_single_add_to_cart - 30 * @hooked woocommerce_template_single_meta - 40 * @hooked woocommerce_template_single_sharing - 50 */ do_action( 'woocommerce_single_product_summary' ); ?> </div><!-- .summary --> <?php /** * woocommerce_after_single_product_summary hook * * @hooked woocommerce_output_product_data_tabs - 10 * @hooked woocommerce_output_related_products - 20 */ do_action( 'woocommerce_after_single_product_summary' ); ?> <meta itemprop="url" content="<?php the_permalink(); ?>" /> </div><!-- #product-<?php the_ID(); ?> --> <?php do_action( 'woocommerce_after_single_product' ); ?>
gpl-2.0
ScottKinder/saw
saw.py
6541
# TODO: Find a better way to pass pillar data to cmd.run, if there is one from getpass import getpass import re import requests base_url = 'http://salt-master' class user_session: def __init__(self, user_name=None): ''' Initializer. Optionally takes user_name(str). ''' self.auth_token = None if not user_name: self.user_name = raw_input('Username: ') else: self.user_name = user_name def set_auth_token(self, user_pass=None, url=base_url): ''' sets instance variable for auth_token that allows x-auth-token header authentication with salt-api. Optionally takes user_pass(str). ''' url += '/login' data = {} data['username'] = self.user_name data['eauth'] = 'pam' if not user_pass: data['password'] = get_pw() else: data['password'] = user_pass r = requests.post(url, data=data, verify=False) try: self.auth_token = r.headers['x-auth-token'] self.auth_expiry = re.search( r'expires=(.*);', r.headers['set-cookie']).group(1) except: print('Auth error.') def get_pw(): ''' prompt for password as needed ''' return getpass('Enter password: ') def cmd_run(user, target, cmd, url=base_url, user_pass=None): ''' Runs cmd.run from cmd parameter. Takes user(str), target(str), cmd(str). Optionally takes user_pass(str). Returns dict of results per minion. ''' url = base_url + '/run' data = {} data['username'] = user data['tgt'] = target data['client'] = 'local' data['eauth'] = 'pam' data['password'] = None data['fun'] = 'cmd.run' data['arg'] = cmd if not user_pass: data['password'] = get_pw() else: data['password'] = user_pass r = requests.post(url, data=data, verify=False) if r.status_code != 200: return 'Status code ' + str(r.status_code) + ', something went wrong.\n' else: return r.json()['return'][0] def token_cmd_run(auth_token, target, cmd, url=base_url): ''' Runs cmd.run from state parameter. Takes user(str), target(str), cmd(str). Returns dict of results per minion. ''' headers = {'Accept': 'application/x-yaml', 'X-Auth-Token': auth_token} data = {'tgt': target, 'client': 'local', 'fun': 'cmd.run', 'arg': cmd} r = requests.post(url, headers=headers, data=data, verify=False) if r.status_code != 200: return 'Status code ' + str(r.status_code) + ', something went wrong.\n' else: return r.text def print_cmd_run(cmd): ''' prints returned dict from cmd_run function ''' if type(cmd) == str or type(cmd) == unicode: print(cmd) else: for minion in cmd: print('*** ' + minion + ' ***\n') print(cmd[minion] + '\n') print('-' * 10 + '\n') def get_minions(auth_token, url=base_url): ''' returns dict of minions that were connected when function was run, uses x-auth-token header value for authentication. ''' url += '/minions' headers = {'X-Auth-Token': auth_token} r = requests.get(url, headers=headers, verify=False) minions = r.json()['return'][0] return minions def print_minions(minions): ''' prints dict of minions from get_minions function. ''' print('Registered minions:\n') for minion in minions: print('* ' + minion) print(' Kernel release: %s\n') % minions[minion]['kernelrelease'] print('-' * 10 + '\n') def run_state(user, target, state, url=base_url, pillar=None, user_pass=None): ''' runs a state.sls where target is the path to the state. pillar can be a string in the form of pillar='pillar={"value1": "string"}'. returns dict with return information from the salt-api about the states run from the state file specified. ''' url += '/run' data = {} data['username'] = user data['tgt'] = target data['client'] = 'local' data['eauth'] = 'pam' data['password'] = None data['fun'] = 'cmd.run' data['arg'] = None if not user_pass: data['password'] = get_pw() else: data['password'] = user_pass if pillar: data['arg'] = [state, pillar] else: data['arg'] = [state] r = requests.post(url, data=data, verify=False) if r.status_code != 200: return 'Status code ' + str(r.status_code) + ', something went wrong.\n' else: results = r.json()['return'][0] return results def token_run_state(auth_token, target, state, url=base_url, pillar=None): ''' runs a state.sls where target is the path to the state. pillar can be a string in the form of pillar='pillar={"value1": "string"}'. returns dict with return information from the salt-api about the states run from the state file specified. ''' headers = {'Accept': 'application/x-yaml', 'X-Auth-Token': auth_token} data = {} data['tgt'] = target data['client'] = 'local' data['fun'] = 'state.sls' data['arg'] = None if pillar: data['arg'] = [state, pillar] else: data['arg'] = [state] r = requests.post(url, headers=headers, data=data, verify=False) if r.status_code != 200: return 'Status code ' + str(r.status_code) + ', something went wrong.\n' else: return r.text def print_run_state(state): ''' prints dict from run_state function ''' if type(state) == str or type(state) == unicode: print(state) else: for minion in state: print('*** ' + minion + ' ***\n') for item in state[minion]: try: comment = state[minion][item]['comment'] result = str(state[minion][item]['result']) print('State: ' + item) print('Comment: ' + comment) print('Result: ' + result + '\n') except: print(state[minion][0] + '\n') def test_target(auth_token, target, url=base_url): ''' tests which minions will match a target expression ''' headers = {'Accept': 'application/x-yaml', 'X-Auth-Token': auth_token} data = {'client': 'local', 'tgt': target, 'fun': 'test.ping'} r = requests.post(url, headers=headers, data=data, verify=False) return r.text
gpl-2.0
SciresM/FEAT
FEAT/DSDecmp/Formats/Nitro/NitroCFormat.cs
3366
using System; using System.Collections.Generic; using System.Text; namespace DSDecmp.Formats.Nitro { /// <summary> /// Base class for Nitro-based decompressors. Uses the 1-byte magic and 3-byte decompression /// size format. /// </summary> public abstract class NitroCFormat : CompressionFormat { /// <summary> /// If true, Nitro Decompressors will not decompress files that have a decompressed /// size (plaintext size) larger than MaxPlaintextSize. /// </summary> public static bool SkipLargePlaintexts = true; /// <summary> /// The maximum allowed size of the decompressed file (plaintext size) allowed for Nitro /// Decompressors. Only used when SkipLargePlaintexts = true. /// If the expected plaintext size is larger that this, the 'Supports' method will partially /// decompress the data to check if the file is OK. /// </summary> public static int MaxPlaintextSize = 0x180000; /// <summary> /// The first byte of every file compressed with the format for this particular /// Nitro Dcompressor instance. /// </summary> protected byte magicByte; /// <summary> /// Creates a new instance of the Nitro Compression Format base class. /// </summary> /// <param name="magicByte">The expected first byte of the file for this format.</param> protected NitroCFormat(byte magicByte) { this.magicByte = magicByte; } /// <summary> /// Checks if the first four (or eight) bytes match the format used in nitro compression formats. /// </summary> public override bool Supports(System.IO.Stream stream, long inLength) { long startPosition = stream.Position; try { int firstByte = stream.ReadByte(); if (firstByte != this.magicByte) return false; // no need to read the size info as well if it's used anyway. if (!SkipLargePlaintexts) return true; byte[] sizeBytes = new byte[3]; stream.Read(sizeBytes, 0, 3); int outSize = IOUtils.ToNDSu24(sizeBytes, 0); if (outSize == 0) { sizeBytes = new byte[4]; stream.Read(sizeBytes, 0, 4); outSize = (int)IOUtils.ToNDSu32(sizeBytes, 0); } if (outSize <= MaxPlaintextSize) return true; try { stream.Position = startPosition; this.Decompress(stream, Math.Min(Math.Min(inLength, 0x80000), MaxPlaintextSize), new System.IO.MemoryStream()); // we expect a NotEnoughDataException, since we're giving the decompressor only part of the file. return false; } catch (NotEnoughDataException) { return true; } catch (Exception) { return false; } } finally { stream.Position = startPosition; } } } }
gpl-2.0
DynamicDevices/dta
Test.Ssh/Scripting/EnumUICommandSubType.cs
152
namespace DeviceTestApplication.Scripting { public enum EnumUICommandSubType { Unknown, Info, Yesno } }
gpl-2.0
bloomberg/ocamlscript
jscomp/test/gpr_2413_test.js
626
'use strict'; function f(param) { switch (param.TAG | 0) { case /* A */0 : var a = param._0; if (a.TAG === /* P */0) { var a$1 = a._0; return a$1 + a$1 | 0; } var a$2 = a._0; return a$2 - a$2 | 0; case /* B */1 : case /* C */2 : break; } var a$3 = param._0._0; return Math.imul(a$3, a$3); } function ff(c) { c.contents = c.contents + 1 | 0; var match = (1 + c.contents | 0) + 1 | 0; if (match > 3 || match < 0) { return 0; } else { return match + 1 | 0; } } exports.f = f; exports.ff = ff; /* No side effect */
gpl-2.0
grlf/eyedock
amember/application/default/views/public/js/ckeditor/plugins/placeholder/lang/pl.js
406
/** * @license Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'placeholder', 'pl', { title: 'Właściwości wypełniacza', toolbar: 'Utwórz wypełniacz', text: 'Tekst wypełnienia', edit: 'Edytuj wypełnienie', textMissing: 'Wypełnienie musi posiadać jakiś tekst.' });
gpl-2.0
DanielAeolusLaude/ardour
gtk2_ardour/region_editor.cc
13726
/* Copyright (C) 2001 Paul Davis 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., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <cmath> #include <gtkmm/listviewtext.h> #include "pbd/memento_command.h" #include "pbd/stateful_diff_command.h" #include "ardour/region.h" #include "ardour/session.h" #include "ardour/source.h" #include "ardour_ui.h" #include "clock_group.h" #include "main_clock.h" #include "gui_thread.h" #include "region_editor.h" #include "public_editor.h" #include "i18n.h" using namespace ARDOUR; using namespace PBD; using namespace std; using namespace Gtkmm2ext; RegionEditor::RegionEditor (Session* s, boost::shared_ptr<Region> r) : ArdourDialog (_("Region")) , _table (9, 2) , _table_row (0) , _region (r) , name_label (_("Name:")) , audition_button (_("Audition")) , _clock_group (new ClockGroup) , position_clock (X_("regionposition"), true, "", true, false) , end_clock (X_("regionend"), true, "", true, false) , length_clock (X_("regionlength"), true, "", true, false, true) , sync_offset_relative_clock (X_("regionsyncoffsetrelative"), true, "", true, false) , sync_offset_absolute_clock (X_("regionsyncoffsetabsolute"), true, "", true, false) /* XXX cannot file start yet */ , start_clock (X_("regionstart"), true, "", false, false) , _sources (1) { set_session (s); _clock_group->set_clock_mode (ARDOUR_UI::instance()->secondary_clock->mode()); _clock_group->add (position_clock); _clock_group->add (end_clock); _clock_group->add (length_clock); _clock_group->add (sync_offset_relative_clock); _clock_group->add (sync_offset_absolute_clock); _clock_group->add (start_clock); position_clock.set_session (_session); end_clock.set_session (_session); length_clock.set_session (_session); sync_offset_relative_clock.set_session (_session); sync_offset_absolute_clock.set_session (_session); start_clock.set_session (_session); ARDOUR_UI::instance()->set_tip (audition_button, _("audition this region")); audition_button.unset_flags (Gtk::CAN_FOCUS); audition_button.set_events (audition_button.get_events() & ~(Gdk::ENTER_NOTIFY_MASK|Gdk::LEAVE_NOTIFY_MASK)); name_entry.set_name ("RegionEditorEntry"); name_label.set_name ("RegionEditorLabel"); position_label.set_name ("RegionEditorLabel"); position_label.set_text (_("Position:")); end_label.set_name ("RegionEditorLabel"); end_label.set_text (_("End:")); length_label.set_name ("RegionEditorLabel"); length_label.set_text (_("Length:")); sync_relative_label.set_name ("RegionEditorLabel"); sync_relative_label.set_text (_("Sync point (relative to region):")); sync_absolute_label.set_name ("RegionEditorLabel"); sync_absolute_label.set_text (_("Sync point (absolute):")); start_label.set_name ("RegionEditorLabel"); start_label.set_text (_("File start:")); _sources_label.set_name ("RegionEditorLabel"); if (_region->n_channels() > 1) { _sources_label.set_text (_("Sources:")); } else { _sources_label.set_text (_("Source:")); } _table.set_col_spacings (12); _table.set_row_spacings (6); _table.set_border_width (12); name_label.set_alignment (1, 0.5); position_label.set_alignment (1, 0.5); end_label.set_alignment (1, 0.5); length_label.set_alignment (1, 0.5); sync_relative_label.set_alignment (1, 0.5); sync_absolute_label.set_alignment (1, 0.5); start_label.set_alignment (1, 0.5); _sources_label.set_alignment (1, 0.5); Gtk::HBox* nb = Gtk::manage (new Gtk::HBox); nb->set_spacing (6); nb->pack_start (name_entry); nb->pack_start (audition_button, false, false); _table.attach (name_label, 0, 1, _table_row, _table_row + 1, Gtk::FILL, Gtk::FILL); _table.attach (*nb, 1, 2, _table_row, _table_row + 1, Gtk::FILL | Gtk::EXPAND, Gtk::FILL); ++_table_row; _table.attach (position_label, 0, 1, _table_row, _table_row + 1, Gtk::FILL, Gtk::FILL); _table.attach (position_clock, 1, 2, _table_row, _table_row + 1, Gtk::FILL | Gtk::EXPAND, Gtk::FILL); ++_table_row; _table.attach (end_label, 0, 1, _table_row, _table_row + 1, Gtk::FILL, Gtk::FILL); _table.attach (end_clock, 1, 2, _table_row, _table_row + 1, Gtk::FILL | Gtk::EXPAND, Gtk::FILL); ++_table_row; _table.attach (length_label, 0, 1, _table_row, _table_row + 1, Gtk::FILL, Gtk::FILL); _table.attach (length_clock, 1, 2, _table_row, _table_row + 1, Gtk::FILL | Gtk::EXPAND, Gtk::FILL); ++_table_row; _table.attach (sync_relative_label, 0, 1, _table_row, _table_row + 1, Gtk::FILL, Gtk::FILL); _table.attach (sync_offset_relative_clock, 1, 2, _table_row, _table_row + 1, Gtk::FILL | Gtk::EXPAND, Gtk::FILL); ++_table_row; _table.attach (sync_absolute_label, 0, 1, _table_row, _table_row + 1, Gtk::FILL, Gtk::FILL); _table.attach (sync_offset_absolute_clock, 1, 2, _table_row, _table_row + 1, Gtk::FILL | Gtk::EXPAND, Gtk::FILL); ++_table_row; _table.attach (start_label, 0, 1, _table_row, _table_row + 1, Gtk::FILL, Gtk::FILL); _table.attach (start_clock, 1, 2, _table_row, _table_row + 1, Gtk::FILL | Gtk::EXPAND, Gtk::FILL); ++_table_row; _table.attach (_sources_label, 0, 1, _table_row, _table_row + 1, Gtk::FILL, Gtk::FILL); _table.attach (_sources, 1, 2, _table_row, _table_row + 1, Gtk::FILL | Gtk::EXPAND, Gtk::FILL); ++_table_row; get_vbox()->pack_start (_table, true, true); add_button (Gtk::Stock::CLOSE, Gtk::RESPONSE_ACCEPT); set_name ("RegionEditorWindow"); add_events (Gdk::KEY_PRESS_MASK|Gdk::KEY_RELEASE_MASK); signal_response().connect (sigc::mem_fun (*this, &RegionEditor::handle_response)); set_title (string_compose (_("Region '%1'"), _region->name())); for (uint32_t i = 0; i < _region->n_channels(); ++i) { _sources.append_text (_region->source(i)->name()); } _sources.set_headers_visible (false); Gtk::CellRendererText* t = dynamic_cast<Gtk::CellRendererText*> (_sources.get_column_cell_renderer(0)); assert (t); t->property_ellipsize() = Pango::ELLIPSIZE_END; show_all(); name_changed (); PropertyChange change; change.add (ARDOUR::Properties::start); change.add (ARDOUR::Properties::length); change.add (ARDOUR::Properties::position); change.add (ARDOUR::Properties::sync_position); bounds_changed (change); _region->PropertyChanged.connect (state_connection, invalidator (*this), boost::bind (&RegionEditor::region_changed, this, _1), gui_context()); spin_arrow_grab = false; connect_editor_events (); } RegionEditor::~RegionEditor () { delete _clock_group; } void RegionEditor::region_changed (const PBD::PropertyChange& what_changed) { if (what_changed.contains (ARDOUR::Properties::name)) { name_changed (); } PropertyChange interesting_stuff; interesting_stuff.add (ARDOUR::Properties::position); interesting_stuff.add (ARDOUR::Properties::length); interesting_stuff.add (ARDOUR::Properties::start); interesting_stuff.add (ARDOUR::Properties::sync_position); if (what_changed.contains (interesting_stuff)) { bounds_changed (what_changed); } } gint RegionEditor::bpressed (GdkEventButton* ev, Gtk::SpinButton* /*but*/, void (RegionEditor::*/*pmf*/)()) { switch (ev->button) { case 1: case 2: case 3: if (ev->type == GDK_BUTTON_PRESS) { /* no double clicks here */ if (!spin_arrow_grab) { // GTK2FIX probably nuke the region editor // if ((ev->window == but->gobj()->panel)) { // spin_arrow_grab = true; // (this->*pmf)(); // } } } break; default: break; } return FALSE; } gint RegionEditor::breleased (GdkEventButton* /*ev*/, Gtk::SpinButton* /*but*/, void (RegionEditor::*pmf)()) { if (spin_arrow_grab) { (this->*pmf)(); spin_arrow_grab = false; } return FALSE; } void RegionEditor::connect_editor_events () { name_entry.signal_changed().connect (sigc::mem_fun(*this, &RegionEditor::name_entry_changed)); position_clock.ValueChanged.connect (sigc::mem_fun(*this, &RegionEditor::position_clock_changed)); end_clock.ValueChanged.connect (sigc::mem_fun(*this, &RegionEditor::end_clock_changed)); length_clock.ValueChanged.connect (sigc::mem_fun(*this, &RegionEditor::length_clock_changed)); sync_offset_absolute_clock.ValueChanged.connect (sigc::mem_fun (*this, &RegionEditor::sync_offset_absolute_clock_changed)); sync_offset_relative_clock.ValueChanged.connect (sigc::mem_fun (*this, &RegionEditor::sync_offset_relative_clock_changed)); audition_button.signal_toggled().connect (sigc::mem_fun(*this, &RegionEditor::audition_button_toggled)); _session->AuditionActive.connect (audition_connection, invalidator (*this), boost::bind (&RegionEditor::audition_state_changed, this, _1), gui_context()); } void RegionEditor::position_clock_changed () { PublicEditor::instance().begin_reversible_command (_("change region start position")); boost::shared_ptr<Playlist> pl = _region->playlist(); if (pl) { _region->clear_changes (); _region->set_position (position_clock.current_time()); _session->add_command(new StatefulDiffCommand (_region)); } PublicEditor::instance().commit_reversible_command (); } void RegionEditor::end_clock_changed () { PublicEditor::instance().begin_reversible_command (_("change region end position")); boost::shared_ptr<Playlist> pl = _region->playlist(); if (pl) { _region->clear_changes (); _region->trim_end (end_clock.current_time()); _session->add_command(new StatefulDiffCommand (_region)); } PublicEditor::instance().commit_reversible_command (); end_clock.set (_region->position() + _region->length() - 1, true); } void RegionEditor::length_clock_changed () { framecnt_t frames = length_clock.current_time(); PublicEditor::instance().begin_reversible_command (_("change region length")); boost::shared_ptr<Playlist> pl = _region->playlist(); if (pl) { _region->clear_changes (); _region->trim_end (_region->position() + frames - 1); _session->add_command(new StatefulDiffCommand (_region)); } PublicEditor::instance().commit_reversible_command (); length_clock.set (_region->length()); } void RegionEditor::audition_button_toggled () { if (audition_button.get_active()) { _session->audition_region (_region); } else { _session->cancel_audition (); } } void RegionEditor::name_changed () { if (name_entry.get_text() != _region->name()) { name_entry.set_text (_region->name()); } } void RegionEditor::bounds_changed (const PropertyChange& what_changed) { if (what_changed.contains (ARDOUR::Properties::position) && what_changed.contains (ARDOUR::Properties::length)) { position_clock.set (_region->position(), true); end_clock.set (_region->position() + _region->length() - 1, true); length_clock.set (_region->length(), true); } else if (what_changed.contains (ARDOUR::Properties::position)) { position_clock.set (_region->position(), true); end_clock.set (_region->position() + _region->length() - 1, true); } else if (what_changed.contains (ARDOUR::Properties::length)) { end_clock.set (_region->position() + _region->length() - 1, true); length_clock.set (_region->length(), true); } if (what_changed.contains (ARDOUR::Properties::sync_position) || what_changed.contains (ARDOUR::Properties::position)) { int dir; frameoffset_t off = _region->sync_offset (dir); if (dir == -1) { off = -off; } if (what_changed.contains (ARDOUR::Properties::sync_position)) { sync_offset_relative_clock.set (off, true); } sync_offset_absolute_clock.set (off + _region->position (), true); } if (what_changed.contains (ARDOUR::Properties::start)) { start_clock.set (_region->start(), true); } } void RegionEditor::activation () { } void RegionEditor::name_entry_changed () { if (name_entry.get_text() != _region->name()) { _region->set_name (name_entry.get_text()); } } void RegionEditor::audition_state_changed (bool yn) { ENSURE_GUI_THREAD (*this, &RegionEditor::audition_state_changed, yn) if (!yn) { audition_button.set_active (false); } } void RegionEditor::sync_offset_absolute_clock_changed () { PublicEditor::instance().begin_reversible_command (_("change region sync point")); _region->clear_changes (); _region->set_sync_position (sync_offset_absolute_clock.current_time()); _session->add_command (new StatefulDiffCommand (_region)); PublicEditor::instance().commit_reversible_command (); } void RegionEditor::sync_offset_relative_clock_changed () { PublicEditor::instance().begin_reversible_command (_("change region sync point")); _region->clear_changes (); _region->set_sync_position (sync_offset_relative_clock.current_time() + _region->position ()); _session->add_command (new StatefulDiffCommand (_region)); PublicEditor::instance().commit_reversible_command (); } bool RegionEditor::on_delete_event (GdkEventAny*) { PropertyChange change; change.add (ARDOUR::Properties::start); change.add (ARDOUR::Properties::length); change.add (ARDOUR::Properties::position); change.add (ARDOUR::Properties::sync_position); bounds_changed (change); return true; } void RegionEditor::handle_response (int) { hide (); }
gpl-2.0
sangwook236/general-development-and-testing
hw_dev/processor/avr/ext/test/procyon_avrlib_test/i2c/i2c_main.cpp
246
#include <avr/sleep.h> #include <avr/interrupt.h> #include <util/delay.h> namespace { namespace local { } // namespace local } // unnamed namespace namespace my_i2c { } // namespace my_i2c int i2c_main() { return 0; }
gpl-2.0
skyHALud/codenameone
Ports/iOSPort/xmlvm/src/xmlvm2js/org/eclipse/swt/events/TypedEvent.js
1083
/* Copyright (c) 2002-2011 by XMLVM.org * * Project Info: http://www.xmlvm.org * * This program 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, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. */ qx.Class.define("org_eclipse_swt_events_TypedEvent",{ extend: org_eclipse_swt_internal_SWTEventObject, construct: function(){ }, members: { $$init____org_eclipse_swt_widgets_Event: function(e){ } } });
gpl-2.0
tumi8/vermont
src/modules/packet/PSAMPExporterCfg.cpp
4804
/* * Vermont Configuration Subsystem * Copyright (C) 2009 Vermont Project * * 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. * */ #include "modules/packet/PacketReportingCfg.h" #include "modules/packet/PSAMPExporterCfg.h" #include "modules/packet/PSAMPExporterModule.h" #include "common/defs.h" #include <cassert> PSAMPExporterCfg::PSAMPExporterCfg(XMLElement* elem) : CfgHelper<PSAMPExporterModule, PSAMPExporterCfg>(elem, "psampExporter"), templateRefreshTime(0), /* templateRefreshRate(0), */ maxPacketSize(0), exportDelay(0), reporting(NULL) { if (!elem) return; observationDomainId = getInt("observationDomainId", 0); // determine captureLen // FIXME: undocumented parameter, this value should come from observer int captureLen = getInt("captureLen", PCAP_DEFAULT_CAPTURE_LENGTH); XMLNode::XMLSet<XMLElement*> set = elem->getElementChildren(); for (XMLNode::XMLSet<XMLElement*>::iterator it = set.begin(); it != set.end(); it++) { XMLElement* e = *it; if (e->matches("ipfixPacketRestrictions")) { maxPacketSize = (uint16_t)getInt("maxPacketSize", 0, e); exportDelay = getTimeInUnit("maxExportDelay", mSEC, 0, e); } else if (e->matches("udpTemplateManagement")) { // use 0 as default values for both if the config entry isn't found templateRefreshTime = getTimeInUnit("templateRefreshTimeout", SEC, IS_DEFAULT_TEMPLATE_TIMEINTERVAL, e); /* templateRefreshRate = getInt("templateRefreshRate", IS_DEFAULT_TEMPLATE_RECORDINTERVAL, e); */ /* TODO */ } else if (e->matches("collector")) { collectors.push_back(new CollectorCfg(e, this->getID())); } else if (e->matches("packetReporting")) { reporting = new PacketReportingCfg(e); } else if (e->matches("captureLen") || e->matches("observationDomainId")) { // ignore it, already handled } else { THROWEXCEPTION("Illegal PSAMPExporter config entry \"%s\"found", e->getName().c_str()); } } if (reporting == NULL) THROWEXCEPTION("No packetReporting found in psampExporter config"); // rough estimation of the maximum record length including variable length fields recordLength = reporting->getRecordLength() + reporting->getRecordsVariableLen() * captureLen; } PSAMPExporterCfg* PSAMPExporterCfg::create(XMLElement* elem) { assert(elem); assert(elem->getName() == getName()); return new PSAMPExporterCfg(elem); } PSAMPExporterCfg::~PSAMPExporterCfg() { for (size_t i = 0; i < collectors.size(); i++) delete collectors[i]; delete reporting; } PSAMPExporterModule* PSAMPExporterCfg::createInstance() { instance = new PSAMPExporterModule(reporting->getTemplate(), observationDomainId); if (recordLength || maxPacketSize) { int recordsPerPacket = 1; if (recordLength) { // IPFIX packet header: 16 bytes, set header: 4 bytes recordsPerPacket = (maxPacketSize - 16 - 4) / recordLength; if(recordsPerPacket <= 0) recordsPerPacket = 1; } msg(LOG_NOTICE, "Set maximum records per packet to %d", recordsPerPacket); instance->setMaxRecords(recordsPerPacket); } if (exportDelay) { msg(LOG_NOTICE, "Set maximum export timeout to %d", exportDelay); instance->setExportTimeout(exportDelay); } if (templateRefreshTime /* || templateRefreshRate */) { msg(LOG_WARNING, "Exporter: Configuration of templateRefreshRate/Time not yet supported."); } for (unsigned i = 0; i != collectors.size(); ++i) { char vrf_log[VRF_LOG_LEN] = ""; if (!collectors[i]->getVrfName().empty()) { snprintf(vrf_log, VRF_LOG_LEN, "[%.*s] ", IFNAMSIZ, collectors[i]->getVrfName().c_str()); } msg(LOG_INFO, "%sPsampExporter: adding collector %s://%s:%d on VRF %s", vrf_log, collectors[i]->getProtocol()==ipfix_transport_protocol::SCTP?"SCTP":"UDP", collectors[i]->getIpAddress().c_str(), collectors[i]->getPort(), collectors[i]->getVrfName().c_str()); instance->addCollector(collectors[i]->getIpAddress().c_str(), collectors[i]->getPort(), collectors[i]->getProtocol(), collectors[i]->getVrfName().c_str()); } return instance; } bool PSAMPExporterCfg::deriveFrom(PSAMPExporterCfg* old) { return false; // FIXME: implement }
gpl-2.0
hfiguiere/abiword
src/wp/ap/win/ap_Win32Dialog_Border_Shading.cpp
21412
/* AbiWord * Copyright (C) 2002-3 Jordi Mas i Hernàndez <jmas@softcatala.org> * Copyright (C) 2010-11 Maleesh Prasan <maleesh.prasan@gmail.com> * * 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. */ #include <stdlib.h> #include "ut_string.h" #include "ut_assert.h" #include "ut_debugmsg.h" #include "xap_App.h" #include "xap_Win32App.h" #include "xap_Win32FrameImpl.h" #include "ap_Strings.h" #include "ap_Dialog_Id.h" #include "ap_Win32Dialog_Border_Shading.h" #include "ap_Win32Resources.rc2" #include "xap_Win32DialogHelper.h" #include "xap_Win32Toolbar_Icons.h" #define BITMAP_WITDH 15 #define BITMAP_HEIGHT 15 #define BORDER_STYLE_BITMAP_WIDTH 180 #define BORDER_STYLE_BITMAP_HEIGHT 30 #define BORDER_STYLE_COMBO_POSITION_X 60 #define BORDER_STYLE_COMBO_POSITION_Y 125 const char * sThicknessTable_Border_Shading[BORDER_SHADING_NUMTHICKNESS] = {"0.25pt","0.5pt", "0.75pt","1.0pt", "1.5pt","2.25pt","3pt", "4.5pt","6.0pt"}; const char * sOffsetTable_Border_Shading[BORDER_SHADING_NUMOFFSETS] = {"0.25pt","0.5pt", "0.75pt","1.0pt", "1.5pt","2.25pt","3pt", "4.5pt","6.0pt"}; const char * sBorderStyle_Border_Shading[BORDER_SHADING_NUMOFSTYLES] = { "0", //No line "1", //Solid line "2", //Dashed line "3"}; //Dotted line XAP_Dialog * AP_Win32Dialog_Border_Shading::static_constructor(XAP_DialogFactory * pFactory, XAP_Dialog_Id id) { AP_Win32Dialog_Border_Shading * p = new AP_Win32Dialog_Border_Shading(pFactory,id); return p; } AP_Win32Dialog_Border_Shading::AP_Win32Dialog_Border_Shading(XAP_DialogFactory * pDlgFactory, XAP_Dialog_Id id) : AP_Dialog_Border_Shading(pDlgFactory,id), m_hBitmapBottom(NULL), m_hBitmapTop(NULL), m_hBitmapRight(NULL), m_hBitmapLeft(NULL), m_pPreviewWidget(NULL), m_hwndComboEx(NULL) { } AP_Win32Dialog_Border_Shading::~AP_Win32Dialog_Border_Shading(void) { if (m_pPreviewWidget) delete m_pPreviewWidget; if (m_hBitmapBottom) DeleteObject(m_hBitmapBottom); if (m_hBitmapTop) DeleteObject(m_hBitmapTop); if (m_hBitmapRight) DeleteObject(m_hBitmapRight); if (m_hBitmapLeft) DeleteObject(m_hBitmapLeft); } void AP_Win32Dialog_Border_Shading::runModeless(XAP_Frame * pFrame) { UT_return_if_fail (pFrame); UT_return_if_fail (m_id == AP_DIALOG_ID_BORDER_SHADING); createModeless(pFrame, MAKEINTRESOURCEW(AP_RID_DIALOG_BORDER_SHADING)); // Save dialog the ID number and pointer to the widget UT_sint32 sid =(UT_sint32) getDialogId(); m_pApp->rememberModelessId( sid, (XAP_Dialog_Modeless *) m_pDialog); } BOOL AP_Win32Dialog_Border_Shading::_onDlgMessage(HWND /*hWnd*/, UINT msg, WPARAM /*wParam*/, LPARAM lParam) { if (msg == WM_DRAWITEM) { DRAWITEMSTRUCT* dis = (DRAWITEMSTRUCT*)lParam; if (dis->CtlID == AP_RID_DIALOG_BORDERSHADING_BTN_SHADING_COLOR) m_shadingButton.draw(dis); if (dis->CtlID == AP_RID_DIALOG_BORDERSHADING_BTN_BORDER_COLOR) m_borderButton.draw(dis); return TRUE; } else if (msg == WM_DESTROY) { finalize(); return FALSE; } return FALSE; } HWND AP_Win32Dialog_Border_Shading::_createComboboxEx( const HWND hParent, const HINSTANCE hInst, DWORD dwStyle, const RECT& rc,const int id) { dwStyle|=WS_CHILD|WS_VISIBLE; return CreateWindowExW(0, WC_COMBOBOXEXW, 0, dwStyle, rc.left, rc.top, rc.right, rc.bottom, hParent, reinterpret_cast<HMENU>(static_cast<INT_PTR>(id)), hInst, 0); } // 8/7/2010 Maleesh - Convenience constant const UINT CBX_ITEM_MASK = CBEIF_IMAGE | CBEIF_TEXT | CBEIF_SELECTEDIMAGE; int AP_Win32Dialog_Border_Shading::_insertItemToComboboxEx( HWND hCbx, const char* txt, int imgIndex, int selectedImgIndex, INT_PTR index = -1, UINT mask = CBX_ITEM_MASK) { COMBOBOXEXITEMW cbei; memset(&cbei, 0, sizeof(cbei)); cbei.mask = mask; cbei.iItem = index; cbei.pszText = (LPWSTR)txt; cbei.iImage = imgIndex; cbei.iSelectedImage = selectedImgIndex; return static_cast<int>(SendMessageW(hCbx, CBEM_INSERTITEMW, 0, reinterpret_cast<LPARAM>(&cbei))); } #define _DS(c,s) setDlgItemText(AP_RID_DIALOG_##c,pSS->getValue(AP_STRING_ID_##s)) #define _DSX(c,s) setDlgItemText(AP_RID_DIALOG_##c,pSS->getValue(XAP_STRING_ID_##s)) // This handles the WM_INITDIALOG message for the top-level dialog. BOOL AP_Win32Dialog_Border_Shading::_onInitDialog(HWND hWnd, WPARAM /*wParam*/, LPARAM /*lParam*/) { UT_uint32 w,h, i; const XAP_StringSet * pSS = m_pApp->getStringSet(); DWORD dwColor = GetSysColor(COLOR_BTNFACE); UT_RGBColor Color(GetRValue(dwColor),GetGValue(dwColor),GetBValue(dwColor)); /* Localise controls*/ _DSX(BORDERSHADING_BTN_CANCEL, DLG_Close); _DSX(BORDERSHADING_BTN_APPLY, DLG_Apply); _DS(BORDERSHADING_TEXT_BORDER_COLOR, DLG_BorderShading_Color); _DS(BORDERSHADING_TEXT_SHADING_COLOR, DLG_BorderShading_Color); _DS(BORDERSHADING_TEXT_PREVIEW, DLG_BorderShading_Preview); _DS(BORDERSHADING_TEXT_BORDER, DLG_BorderShading_Borders); _DS(BORDERSHADING_TEXT_SHADING, DLG_BorderShading_Shading); _DS(BORDERSHADING_BTN_SHADING_ENABLE, DLG_BorderShading_Use_Shading); _DS(BORDERSHADING_TEXT_BORDER_STYLE, DLG_BorderShading_Border_Style); _DS(BORDERSHADING_TEXT_BORDER_THICKNESS, DLG_BorderShading_Thickness); _DS(BORDERSHADING_TEXT_SHADING_OFFSET, DLG_BorderShading_Offset); setDialogTitle(pSS->getValue(AP_STRING_ID_DLG_BorderShading_Title)); /* Load the bitmaps into the dialog box */ m_hBitmapBottom = XAP_Win32DialogHelper::s_loadBitmap(hWnd,AP_RID_DIALOG_BORDERSHADING_BMP_BOTTOM, "FT_LINEBOTTOM", BITMAP_WITDH, BITMAP_HEIGHT, Color); m_hBitmapTop = XAP_Win32DialogHelper::s_loadBitmap(hWnd,AP_RID_DIALOG_BORDERSHADING_BMP_TOP, "FT_LINETOP", BITMAP_WITDH, BITMAP_HEIGHT, Color); m_hBitmapRight = XAP_Win32DialogHelper::s_loadBitmap(hWnd,AP_RID_DIALOG_BORDERSHADING_BMP_RIGHT, "FT_LINERIGHT", BITMAP_WITDH, BITMAP_HEIGHT, Color); m_hBitmapLeft = XAP_Win32DialogHelper::s_loadBitmap(hWnd,AP_RID_DIALOG_BORDERSHADING_BMP_LEFT, "FT_LINELEFT", BITMAP_WITDH, BITMAP_HEIGHT, Color); /* Preview*/ HWND hwndChild = GetDlgItem(hWnd, AP_RID_DIALOG_BORDERSHADING_STATIC_PREVIEW); UT_return_val_if_fail (hwndChild,0); delete m_pPreviewWidget; m_pPreviewWidget = new XAP_Win32PreviewWidget(static_cast<XAP_Win32App *>(m_pApp), hwndChild, 0); m_pPreviewWidget->getGraphics()->init3dColors(); m_pPreviewWidget->getWindowSize(&w,&h); _createPreviewFromGC(m_pPreviewWidget->getGraphics(), w, h); m_pPreviewWidget->setPreview(m_pBorderShadingPreview); startUpdater(); setAllSensitivities(); /* Default status for the push bottons*/ CheckDlgButton(m_hDlg, AP_RID_DIALOG_BORDERSHADING_BMP_TOP, getTopToggled() ? BST_CHECKED: BST_UNCHECKED); CheckDlgButton(m_hDlg, AP_RID_DIALOG_BORDERSHADING_BMP_BOTTOM, getBottomToggled() ? BST_CHECKED: BST_UNCHECKED); CheckDlgButton(m_hDlg, AP_RID_DIALOG_BORDERSHADING_BMP_RIGHT, getRightToggled() ? BST_CHECKED: BST_UNCHECKED); CheckDlgButton(m_hDlg, AP_RID_DIALOG_BORDERSHADING_BMP_LEFT, getLeftToggled() ? BST_CHECKED: BST_UNCHECKED); /* Combo Values for Thickness */ for(i=0; i < BORDER_SHADING_NUMTHICKNESS ;i++) addItemToCombo (AP_RID_DIALOG_BORDERSHADING_COMBO_BORDER_THICKNESS, sThicknessTable_Border_Shading[i]); selectComboItem (AP_RID_DIALOG_BORDERSHADING_COMBO_BORDER_THICKNESS, 0); /* Combo Values for Offset */ for(i=0; i < BORDER_SHADING_NUMOFFSETS ;i++) addItemToCombo (AP_RID_DIALOG_BORDERSHADING_COMBO_SHADING_OFFSET, sOffsetTable_Border_Shading[i]); selectComboItem (AP_RID_DIALOG_BORDERSHADING_COMBO_SHADING_OFFSET, 0); RECT combo_rect = { BORDER_STYLE_COMBO_POSITION_X, BORDER_STYLE_COMBO_POSITION_Y, BORDER_STYLE_BITMAP_WIDTH, BORDER_STYLE_BITMAP_HEIGHT * (BORDER_SHADING_NUMOFSTYLES * 2)}; // StartCommonControls(ICC_USEREX_CLASSES); XAP_App* pApp = XAP_App::getApp(); UT_ASSERT(pApp); XAP_Win32App* pWin32App = static_cast<XAP_Win32App*>(pApp); m_hwndComboEx = _createComboboxEx( m_hDlg, pWin32App->getInstance(), CBS_DROPDOWNLIST, combo_rect, AP_RID_DIALOG_BORDERSHADING_COMBO_BORDER_STYLE); HIMAGELIST hImageList = ImageList_Create( BORDER_STYLE_BITMAP_WIDTH, BORDER_STYLE_BITMAP_HEIGHT, ILC_MASK|ILC_COLOR32, BORDER_SHADING_NUMOFSTYLES, 0); // Follow the PP_PropertyMap::TypeLineStyle order. HBITMAP tmp_bmp0 = XAP_Win32DialogHelper::s_loadBitmap(hWnd, 0, "BORDER_STYLE_NONE", BORDER_STYLE_BITMAP_WIDTH, BORDER_STYLE_BITMAP_HEIGHT, Color); HBITMAP tmp_bmp1 = XAP_Win32DialogHelper::s_loadBitmap(hWnd, 0, "BORDER_STYLE_SOLID", BORDER_STYLE_BITMAP_WIDTH, BORDER_STYLE_BITMAP_HEIGHT, Color); HBITMAP tmp_bmp2 = XAP_Win32DialogHelper::s_loadBitmap(hWnd, 0, "BORDER_STYLE_DOTTED", BORDER_STYLE_BITMAP_WIDTH, BORDER_STYLE_BITMAP_HEIGHT, Color); HBITMAP tmp_bmp3 = XAP_Win32DialogHelper::s_loadBitmap(hWnd, 0, "BORDER_STYLE_DASHED", BORDER_STYLE_BITMAP_WIDTH, BORDER_STYLE_BITMAP_HEIGHT, Color); ImageList_Add(hImageList, tmp_bmp0, NULL); ImageList_Add(hImageList, tmp_bmp1, NULL); ImageList_Add(hImageList, tmp_bmp2, NULL); ImageList_Add(hImageList, tmp_bmp3, NULL); SendMessage(m_hwndComboEx, CBEM_SETIMAGELIST, 0, reinterpret_cast<LPARAM>(hImageList)); _insertItemToComboboxEx(m_hwndComboEx, NULL, 0, 0); _insertItemToComboboxEx(m_hwndComboEx, NULL, 1, 1); _insertItemToComboboxEx(m_hwndComboEx, NULL, 2, 2); _insertItemToComboboxEx(m_hwndComboEx, NULL, 3, 3); centerDialog(); return 1; } BOOL AP_Win32Dialog_Border_Shading::_onCommand(HWND hWnd, WPARAM wParam, LPARAM /*lParam*/) { WORD wNotifyCode = HIWORD(wParam); WORD wId = LOWORD(wParam); // HWND hWndCtrl = (HWND)lParam; switch (wId) { case AP_RID_DIALOG_BORDERSHADING_BMP_BOTTOM: { bool bChecked; bChecked = (bool)(IsDlgButtonChecked(m_hDlg, AP_RID_DIALOG_BORDERSHADING_BMP_BOTTOM)==BST_CHECKED); toggleLineType(AP_Dialog_Border_Shading::toggle_bottom, bChecked); event_previewExposed(); return 1; } case AP_RID_DIALOG_BORDERSHADING_BMP_TOP: { bool bChecked; bChecked = (bool)(IsDlgButtonChecked(m_hDlg, AP_RID_DIALOG_BORDERSHADING_BMP_TOP)==BST_CHECKED); toggleLineType(AP_Dialog_Border_Shading::toggle_top, bChecked); event_previewExposed(); return 1; } case AP_RID_DIALOG_BORDERSHADING_BMP_RIGHT: { bool bChecked; bChecked = (bool)(IsDlgButtonChecked(m_hDlg, AP_RID_DIALOG_BORDERSHADING_BMP_RIGHT)==BST_CHECKED); toggleLineType(AP_Dialog_Border_Shading::toggle_right, bChecked); event_previewExposed(); return 1; } case AP_RID_DIALOG_BORDERSHADING_BMP_LEFT: { bool bChecked; bChecked = (bool)(IsDlgButtonChecked(m_hDlg, AP_RID_DIALOG_BORDERSHADING_BMP_LEFT)==BST_CHECKED); toggleLineType(AP_Dialog_Border_Shading::toggle_left, bChecked); event_previewExposed(); return 1; } case AP_RID_DIALOG_BORDERSHADING_BTN_BORDER_COLOR: { CHOOSECOLORW cc; static COLORREF acrCustClr[16]; /* Initialize CHOOSECOLOR */ ZeroMemory(&cc, sizeof(CHOOSECOLORW)); cc.lStructSize = sizeof(CHOOSECOLORW); cc.hwndOwner = m_hDlg; cc.lpCustColors = (LPDWORD) acrCustClr; cc.rgbResult = 0; cc.Flags = CC_FULLOPEN | CC_RGBINIT; if(ChooseColorW(&cc)) { setBorderColor(UT_RGBColor(GetRValue( cc.rgbResult), GetGValue(cc.rgbResult), GetBValue(cc.rgbResult))); m_borderButton.setColour(cc.rgbResult); /*Force redraw*/ InvalidateRect(GetDlgItem(hWnd, AP_RID_DIALOG_BORDERSHADING_BTN_BORDER_COLOR), NULL, FALSE); event_previewExposed(); } return 1; } case AP_RID_DIALOG_BORDERSHADING_COMBO_BORDER_THICKNESS: { if (wNotifyCode == CBN_SELCHANGE) { int nSelected = getComboSelectedIndex (AP_RID_DIALOG_BORDERSHADING_COMBO_BORDER_THICKNESS); if (nSelected != CB_ERR) { UT_Win32LocaleString thickness; getComboTextItem(AP_RID_DIALOG_BORDERSHADING_COMBO_BORDER_THICKNESS, nSelected, thickness); setBorderThickness(thickness.utf8_str().utf8_str()); /*Force redraw*/ InvalidateRect(GetDlgItem(hWnd, AP_RID_DIALOG_BORDERSHADING_BTN_BORDER_COLOR), NULL, FALSE); event_previewExposed(); } } return 1; } case AP_RID_DIALOG_BORDERSHADING_COMBO_BORDER_STYLE: { if (wNotifyCode == CBN_SELCHANGE) { int nSelected = getComboSelectedIndex (AP_RID_DIALOG_BORDERSHADING_COMBO_BORDER_STYLE); if (nSelected != CB_ERR && nSelected >= 0 && nSelected <= BORDER_SHADING_NUMOFSTYLES) { // Kill the focus of the combobox. Because selected // images of a combobox-ex doesn't look clear/good. setBorderStyle(sBorderStyle_Border_Shading[nSelected]); SetFocus(m_hDlg); event_previewExposed(); } } return 1; } case AP_RID_DIALOG_BORDERSHADING_BTN_SHADING_COLOR: { CHOOSECOLORW cc; static COLORREF acrCustClr2[16]; /* Initialize CHOOSECOLOR */ ZeroMemory(&cc, sizeof(CHOOSECOLORW)); cc.lStructSize = sizeof(CHOOSECOLORW); cc.hwndOwner = m_hDlg; cc.lpCustColors = (LPDWORD) acrCustClr2; cc.rgbResult = 0; cc.Flags = CC_FULLOPEN | CC_RGBINIT; if(ChooseColorW(&cc)) { setShadingColor(UT_RGBColor(GetRValue( cc.rgbResult), GetGValue(cc.rgbResult), GetBValue(cc.rgbResult))); m_shadingButton.setColour(cc.rgbResult); /*Force redraw*/ InvalidateRect(GetDlgItem(hWnd, AP_RID_DIALOG_BORDERSHADING_BTN_SHADING_COLOR), NULL, FALSE); event_previewExposed(); } return 1; } case AP_RID_DIALOG_BORDERSHADING_BTN_SHADING_ENABLE: { bool bChecked; bChecked = (bool)(IsDlgButtonChecked(m_hDlg, AP_RID_DIALOG_BORDERSHADING_BTN_SHADING_ENABLE)==BST_CHECKED); // TODO: Change this, when there are more shading patterns. setShadingPattern(bChecked ? BORDER_SHADING_SHADING_ENABLE : BORDER_SHADING_SHADING_DISABLE); setShadingEnable(bChecked); return 1; } case AP_RID_DIALOG_BORDERSHADING_COMBO_SHADING_OFFSET: { if (wNotifyCode == CBN_SELCHANGE) { int nSelected = getComboSelectedIndex (AP_RID_DIALOG_BORDERSHADING_COMBO_SHADING_OFFSET); if (nSelected != CB_ERR) { UT_Win32LocaleString offset; getComboTextItem(AP_RID_DIALOG_BORDERSHADING_COMBO_SHADING_OFFSET, nSelected, offset); setShadingOffset(offset.utf8_str().utf8_str()); /*Force redraw*/ InvalidateRect(GetDlgItem(hWnd, AP_RID_DIALOG_BORDERSHADING_BTN_SHADING_COLOR), NULL, FALSE); event_previewExposed(); } } return 1; } case AP_RID_DIALOG_BORDERSHADING_BTN_CANCEL: m_answer = AP_Dialog_Border_Shading::a_CLOSE; destroy(); EndDialog(hWnd,0); return 1; case AP_RID_DIALOG_BORDERSHADING_BTN_APPLY: { m_answer = AP_Dialog_Border_Shading::a_OK; applyChanges(); return 1; } default: // we did not handle this notification UT_DEBUGMSG(("WM_Command for id %ld\n",wId)); return 0; // return zero to let windows take care of it. } } void AP_Win32Dialog_Border_Shading::event_previewExposed(void) { if(m_pBorderShadingPreview) m_pBorderShadingPreview->draw(); } void AP_Win32Dialog_Border_Shading::setShadingColorInGUI(const UT_RGBColor & clr) { UT_DEBUGMSG(("Maleesh =============== Setup the shading color in the GUI: %d|%d|%d \n", clr.m_red, clr.m_grn, clr.m_blu)); m_shadingButton.setColour(RGB(clr.m_red,clr.m_grn,clr.m_blu)); /* force redraw */ InvalidateRect(GetDlgItem(m_hDlg, AP_RID_DIALOG_BORDERSHADING_BTN_SHADING_COLOR), NULL, FALSE); } void AP_Win32Dialog_Border_Shading::setShadingPatternInGUI(const std::string & sPattern) { xxx_UT_DEBUGMSG(("Maleesh =============== Setup the shading pattern in the GUI: %s \n", sPattern.c_str())); // TODO: Change this, when there are more shading patterns. bool shading_enabled = (sPattern != BORDER_SHADING_SHADING_DISABLE); setShadingEnable(shading_enabled); } void AP_Win32Dialog_Border_Shading::setShadingOffsetInGUI(const std::string & sOffset) { xxx_UT_DEBUGMSG(("Maleesh =============== Setup the shading offset in the GUI: %s \n", sOffset.c_str())); guint closest = _findClosestOffset(sOffset.c_str()); SendMessageA(GetDlgItem(m_hDlg, AP_RID_DIALOG_BORDERSHADING_COMBO_SHADING_OFFSET), CB_SETCURSEL, WPARAM(closest), 0); } void AP_Win32Dialog_Border_Shading::setBorderColorInGUI(const UT_RGBColor & clr) { xxx_UT_DEBUGMSG(("Maleesh =============== Setup the border color in the GUI: %d|%d|%d \n", clr.m_red, clr.m_grn, clr.m_blu)); m_borderButton.setColour(RGB(clr.m_red,clr.m_grn,clr.m_blu)); /* force redraw */ InvalidateRect(GetDlgItem(m_hDlg, AP_RID_DIALOG_BORDERSHADING_BTN_BORDER_COLOR), NULL, FALSE); } void AP_Win32Dialog_Border_Shading::setBorderThicknessInGUI(const std::string & sThick) { xxx_UT_DEBUGMSG(("Maleesh =============== Setup the border thickness in the GUI: %s \n", sThick.c_str())); guint closest = _findClosestThickness(sThick.c_str()); SendMessageA(GetDlgItem(m_hDlg, AP_RID_DIALOG_BORDERSHADING_COMBO_BORDER_THICKNESS), CB_SETCURSEL, WPARAM(closest), 0); } void AP_Win32Dialog_Border_Shading::setBorderStyleInGUI(const std::string & sStyle) { xxx_UT_DEBUGMSG(("Maleesh =============== Setup the border style in the GUI: %s \n", sStyle.c_str())); PP_PropertyMap::TypeLineStyle style = PP_PropertyMap::linestyle_type(sStyle.c_str()); gint index = (guint)style - 1; if (index >= 0) SendMessageA(GetDlgItem(m_hDlg, AP_RID_DIALOG_BORDERSHADING_COMBO_BORDER_STYLE), CB_SETCURSEL, WPARAM(index), 0); } void AP_Win32Dialog_Border_Shading::setShadingEnable(bool enable) { CheckDlgButton(m_hDlg, AP_RID_DIALOG_BORDERSHADING_BTN_SHADING_ENABLE, (enable ? BST_CHECKED : BST_UNCHECKED)); m_shadingButton.setEnable(enable); EnableWindow(GetDlgItem(m_hDlg, AP_RID_DIALOG_BORDERSHADING_COMBO_SHADING_OFFSET), enable); EnableWindow(GetDlgItem(m_hDlg, AP_RID_DIALOG_BORDERSHADING_BTN_SHADING_COLOR), enable); EnableWindow(GetDlgItem(m_hDlg, AP_RID_DIALOG_BORDERSHADING_TEXT_SHADING_COLOR), enable); EnableWindow(GetDlgItem(m_hDlg, AP_RID_DIALOG_BORDERSHADING_TEXT_SHADING_OFFSET), enable); /* force redraw */ InvalidateRect(GetDlgItem(m_hDlg, AP_RID_DIALOG_BORDERSHADING_BTN_SHADING_COLOR), NULL, FALSE); event_previewExposed(); } void AP_Win32Dialog_Border_Shading::setSensitivity(bool /*bSens*/) { CheckDlgButton(m_hDlg, AP_RID_DIALOG_BORDERSHADING_BMP_TOP, getTopToggled() ? BST_CHECKED: BST_UNCHECKED); CheckDlgButton(m_hDlg, AP_RID_DIALOG_BORDERSHADING_BMP_BOTTOM, getBottomToggled() ? BST_CHECKED: BST_UNCHECKED); CheckDlgButton(m_hDlg, AP_RID_DIALOG_BORDERSHADING_BMP_RIGHT, getRightToggled() ? BST_CHECKED: BST_UNCHECKED); CheckDlgButton(m_hDlg, AP_RID_DIALOG_BORDERSHADING_BMP_LEFT, getLeftToggled() ? BST_CHECKED: BST_UNCHECKED); } void AP_Win32Dialog_Border_Shading::destroy(void) { finalize(); DestroyWindow(m_hDlg); } void AP_Win32Dialog_Border_Shading::activate(void) { ConstructWindowName(); setAllSensitivities(); showWindow(SW_SHOW); bringWindowToTop(); } void AP_Win32Dialog_Border_Shading::notifyActiveFrame(XAP_Frame *pFrame) { setAllSensitivities(); if((HWND)GetWindowLongPtrW(m_hDlg, GWLP_HWNDPARENT) != static_cast<XAP_Win32FrameImpl*>(pFrame->getFrameImpl())->getTopLevelWindow()) { // Update the caption ConstructWindowName(); setDialogTitle(m_WindowName); SetWindowLongPtrW(m_hDlg, GWLP_HWNDPARENT, (LONG_PTR)static_cast<XAP_Win32FrameImpl*>(pFrame->getFrameImpl())->getTopLevelWindow()); SetWindowPos(m_hDlg, NULL, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED); } } void AP_Win32Dialog_Border_Shading::event_Close(void) { m_answer = AP_Dialog_Border_Shading::a_CLOSE; destroy(); }
gpl-2.0
mohammadhamad/mge
repos/gems/src/server/wm/main.cc
3470
/* * \brief Window manager * \author Norman Feske * \date 2014-01-06 */ /* * Copyright (C) 2014 Genode Labs GmbH * * This file is part of the Genode OS framework, which is distributed * under the terms of the GNU General Public License version 2. */ /* Genode includes */ #include <os/server.h> #include <nitpicker_session/client.h> #include <framebuffer_session/client.h> #include <cap_session/connection.h> #include <os/attached_rom_dataspace.h> #include <util/volatile_object.h> #include <util/xml_node.h> /* local includes */ #include <nitpicker.h> namespace Wm { class Main; using Genode::size_t; using Genode::env; using Genode::Rom_session_client; using Genode::Rom_connection; using Genode::Xml_node; using Genode::Attached_rom_dataspace; } struct Wm::Main { Server::Entrypoint ep; Genode::Cap_connection cap; /* currently focused window, reported by the layouter */ Attached_rom_dataspace focus_rom { "focus" }; /* resize requests, issued by the layouter */ Attached_rom_dataspace resize_request_rom { "resize_request" }; /* pointer position to be consumed by the layouter */ Reporter pointer_reporter = { "pointer" }; /* list of present windows, to be consumed by the layouter */ Reporter window_list_reporter = { "window_list" }; Window_registry window_registry { *env()->heap(), window_list_reporter }; Nitpicker::Root nitpicker_root { ep, window_registry, *env()->heap(), env()->ram_session_cap(), pointer_reporter }; Nitpicker::Connection focus_nitpicker_session; void handle_focus_update(unsigned) { try { focus_rom.update(); unsigned long win_id = 0; Xml_node(focus_rom.local_addr<char>()).sub_node("window") .attribute("id").value(&win_id); if (win_id) { Nitpicker::Session_capability session_cap = nitpicker_root.lookup_nitpicker_session(win_id); focus_nitpicker_session.focus(session_cap); } } catch (...) { PWRN("no focus model available"); } } Genode::Signal_rpc_member<Main> focus_dispatcher = { ep, *this, &Main::handle_focus_update }; void handle_resize_request_update(unsigned) { try { resize_request_rom.update(); char const * const node_type = "window"; Xml_node window = Xml_node(resize_request_rom.local_addr<char>()).sub_node(node_type); for (;;) { unsigned long win_id = 0, width = 0, height = 0; window.attribute("id") .value(&win_id); window.attribute("width") .value(&width); window.attribute("height").value(&height); nitpicker_root.request_resize(win_id, Area(width, height)); if (window.is_last(node_type)) break; window = window.next(node_type); } } catch (...) { /* no resize-request model available */ } } Genode::Signal_rpc_member<Main> resize_request_dispatcher = { ep, *this, &Main::handle_resize_request_update }; Main(Server::Entrypoint &ep) : ep(ep) { pointer_reporter.enabled(true); /* initially report an empty window list */ window_list_reporter.enabled(true); Genode::Reporter::Xml_generator xml(window_list_reporter, [&] () { }); focus_rom.sigh(focus_dispatcher); resize_request_rom.sigh(resize_request_dispatcher); } }; /************ ** Server ** ************/ namespace Server { char const *name() { return "desktop_ep"; } size_t stack_size() { return 4*1024*sizeof(long); } void construct(Entrypoint &ep) { static Wm::Main desktop(ep); } }
gpl-2.0
nacc/autotest
client/tests/bonnie/bonnie.py
2749
import os, re from autotest.client import test, os_dep, utils def convert_size(values): values = values.split(':') size = values[0] if len(values) > 1: chunk = values[1] else: chunk = 0 if size.endswith('G') or size.endswith('g'): size = int(size[:-1]) * 2**30 else: if size.endswith('M') or size.endswith('m'): size = int(size[:-1]) size = int(size) * 2**20 if chunk: if chunk.endswith('K') or chunk.endswith('k'): chunk = int(chunk[:-1]) * 2**10 else: chunk = int(chunk) return [size, chunk] class bonnie(test.test): version = 1 def initialize(self): self.job.require_gcc() self.results = [] # http://www.coker.com.au/bonnie++/bonnie++-1.03a.tgz def setup(self, tarball = 'bonnie++-1.03a.tgz'): tarball = utils.unmap_url(self.bindir, tarball, self.tmpdir) utils.extract_tarball_to_dir(tarball, self.srcdir) os.chdir(self.srcdir) os_dep.command('g++') utils.system('patch -p1 < ../bonnie++-1.03a-gcc43.patch') utils.configure() utils.make() def run_once(self, dir=None, extra_args='', user='root'): if not dir: dir = self.tmpdir # if the user specified a -n we will use that if '-n' not in extra_args: extra_args += ' -n 2048' args = '-d ' + dir + ' -u ' + user + ' ' + extra_args cmd = self.srcdir + '/bonnie++ ' + args self.results.append(utils.system_output(cmd, retain_output=True)) def postprocess(self): strip_plus = lambda s: re.sub(r"^\++$", "0", s) keys = ('size', 'chnk', 'seqout_perchr_ksec', 'seqout_perchr_pctcp', 'seqout_perblk_ksec', 'seqout_perblk_pctcp', 'seqout_rewrite_ksec', 'seqout_rewrite_pctcp', 'seqin_perchr_ksec', 'seqin_perchr_pctcp', 'seqin_perblk_ksec', 'seqin_perblk_pctcp', 'rand_ksec', 'rand_pctcp', 'files', 'seqcreate_create_ksec', 'seqcreate_create_pctcp', 'seqcreate_read_ksec', 'seqcreate_read_pctcp', 'seqcreate_delete_ksec', 'seqcreate_delete_pctcp', 'randreate_create_ksec', 'randcreate_create_pctcp', 'randcreate_read_ksec', 'randcreate_read_pctcp', 'randcreate_delete_ksec', 'randcreate_delete_pctcp') for line in self.results: if line.count(',') != 26: continue fields = line.split(',') fields = [strip_plus(f) for f in fields] fields = convert_size(fields[1]) + fields[2:] self.write_perf_keyval(dict(zip(keys,fields)))
gpl-2.0
ganncamp/Benchmark
src/main/java/org/owasp/benchmark/testcode/BenchmarkTest00329.java
2580
/** * OWASP Benchmark Project v1.2beta * * This file is part of the Open Web Application Security Project (OWASP) * Benchmark Project. For details, please see * <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>. * * The OWASP Benchmark 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, version 2. * * The OWASP Benchmark 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. * * @author Nick Sanidas <a href="https://www.aspectsecurity.com">Aspect Security</a> * @created 2015 */ package org.owasp.benchmark.testcode; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/BenchmarkTest00329") public class BenchmarkTest00329 extends HttpServlet { private static final long serialVersionUID = 1L; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); String param = ""; java.util.Enumeration<String> headers = request.getHeaders("vector"); if (headers.hasMoreElements()) { param = headers.nextElement(); // just grab first element } String bar; // Simple if statement that assigns constant to bar on true condition int num = 86; if ( (7*42) - num > 200 ) bar = "This_should_always_happen"; else bar = param; String sql = "{call " + bar + "}"; try { java.sql.Connection connection = org.owasp.benchmark.helpers.DatabaseHelper.getSqlConnection(); java.sql.CallableStatement statement = connection.prepareCall( sql ); java.sql.ResultSet rs = statement.executeQuery(); org.owasp.benchmark.helpers.DatabaseHelper.printResults(rs, sql, response); } catch (java.sql.SQLException e) { if (org.owasp.benchmark.helpers.DatabaseHelper.hideSQLErrors) { response.getWriter().println("Error processing request."); return; } else throw new ServletException(e); } } }
gpl-2.0
cwaclawik/moodle
admin/xmldb/actions/delete_table/delete_table.class.php
5115
<?php // $Id$ /////////////////////////////////////////////////////////////////////////// // // // NOTICE OF COPYRIGHT // // // // Moodle - Modular Object-Oriented Dynamic Learning Environment // // http://moodle.com // // // // Copyright (C) 1999 onwards Martin Dougiamas http://dougiamas.com // // (C) 2001-3001 Eloy Lafuente (stronk7) http://contiento.com // // // // 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/copyleft/gpl.html // // // /////////////////////////////////////////////////////////////////////////// /// This class will delete completely one table class delete_table extends XMLDBAction { /** * Init method, every subclass will have its own */ function init() { parent::init(); /// Set own custom attributes /// Get needed strings $this->loadStrings(array( 'confirmdeletetable' => 'xmldb', 'yes' => '', 'no' => '' )); } /** * Invoke method, every class will have its own * returns true/false on completion, setting both * errormsg and output as necessary */ function invoke() { parent::invoke(); $result = true; /// Set own core attributes $this->does_generate = ACTION_GENERATE_HTML; /// These are always here global $CFG, $XMLDB; /// Do the job, setting result as needed /// Get the dir containing the file $dirpath = required_param('dir', PARAM_PATH); $dirpath = $CFG->dirroot . $dirpath; $tableparam = required_param('table', PARAM_CLEAN); $confirmed = optional_param('confirmed', false, PARAM_BOOL); /// If not confirmed, show confirmation box if (!$confirmed) { $o = '<table width="60" class="generalbox" border="0" cellpadding="5" cellspacing="0" id="notice">'; $o.= ' <tr><td class="generalboxcontent">'; $o.= ' <p class="centerpara">' . $this->str['confirmdeletetable'] . '<br /><br />' . $tableparam . '</p>'; $o.= ' <table class="boxaligncenter" cellpadding="20"><tr><td>'; $o.= ' <div class="singlebutton">'; $o.= ' <form action="index.php?action=delete_table&amp;confirmed=yes&amp;postaction=edit_xml_file&amp;table=' . $tableparam . '&amp;dir=' . urlencode(str_replace($CFG->dirroot, '', $dirpath)) . '" method="post"><fieldset class="invisiblefieldset">'; $o.= ' <input type="submit" value="'. $this->str['yes'] .'" /></fieldset></form></div>'; $o.= ' </td><td>'; $o.= ' <div class="singlebutton">'; $o.= ' <form action="index.php?action=edit_xml_file&amp;dir=' . urlencode(str_replace($CFG->dirroot, '', $dirpath)) . '" method="post"><fieldset class="invisiblefieldset">'; $o.= ' <input type="submit" value="'. $this->str['no'] .'" /></fieldset></form></div>'; $o.= ' </td></tr>'; $o.= ' </table>'; $o.= ' </td></tr>'; $o.= '</table>'; $this->output = $o; } else { /// Get the edited dir if (!empty($XMLDB->editeddirs)) { if (isset($XMLDB->editeddirs[$dirpath])) { $dbdir =& $XMLDB->dbdirs[$dirpath]; $editeddir =& $XMLDB->editeddirs[$dirpath]; if ($editeddir) { $structure =& $editeddir->xml_file->getStructure(); /// Remove the table $structure->deleteTable($tableparam); } } } } /// Launch postaction if exists (leave this here!) if ($this->getPostAction() && $result) { return $this->launch($this->getPostAction()); } /// Return ok if arrived here return $result; } } ?>
gpl-2.0
cidesa/roraima
web/reportes/reportes/ingresos/inrtiping.php
8143
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <title>SIGA Reportes</title> <link href="../../lib/css/siga.css" rel="stylesheet" type="text/css"> <link href="../../lib/css/datepickercontrol.css" rel="stylesheet" type="text/css"> <script language="JavaScript" src="../../lib/general/datepickercontrol.js"></script> <script language="JavaScript" src="../../lib/general/fecha.js"></script> <style type="text/css"> <!-- .style1 {color: #0000CC} --> </style> </head> <body> <? require_once("../../lib/bd/basedatosAdo.php"); $bd=new basedatosAdo(); function LlenarTextoSql($sql,$campo1,$con) { $tb=$con->select($sql); if (!$tb->EOF) { print $tb->fields[$campo1]; } else { print ""; } } ?> <form name="form1" method="post" action=""> <table width="760" height="40" border="0" align="center" cellpadding="0" cellspacing="0" bgcolor="#EEEEEE"> <tr> <td width="190" rowspan="2" bgcolor="#003399" class="cell_left_line02"><img src="../../img/tl_logo_01.gif" width="190" height="40" border="0"></a></td> <td colspan="2" class="cell_date" align="right"> <? $dias = array("Domingo","Lunes","Martes","Miercoles","Jueves","Viernes","S&aacute;bado"); $mes = array("","Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre"); $me=$mes[date('n')]; echo $dias[date('w')].strftime(", %d de $me del %Y")."<br>"; ?> </td> </tr> <tr> <td width="313">&nbsp; </td> <td width="257" align="right" valign="middle" class="cell_logout">&nbsp;</td> </tr> </table> <table width="760" border="0" align="center" cellpadding="0" cellspacing="0" bgcolor="#FFFFFF"> <tr> <td width="6" align="left" valign="top" class="cell_left_line02"><img src="../../img/center02_tl.gif" width="6" height="6"></td> <td rowspan="2" valign="top" class="cell_padding_01"> <p class="breadcrumb">Reportes </p> <fieldset> <div align="left">&nbsp; <table width="612" align="center" cellspacing="0" bordercolor="#6699CC" class="grid_line01_tl"> <tr bordercolor="#FFFFFF"> <td colspan="3" class="form_label_01"> <div align="center"> <font color="#000066" size="4"><strong>Listado de Tipos de Ingresos <input name="titulo" type="hidden" id="titulo"> </strong></font></div></td> </tr> <tr bordercolor="#FFFFFF"> <td class="form_label_01">&nbsp;</td> <td>&nbsp;</td> <td><font color="#00FFCC">&nbsp; </font></td> </tr> <tr bordercolor="#6699CC"> <td width="186" class="form_label_01"><strong>Tama&ntilde;o Hoja:</strong></td> <td width="174"> <input name="tamano" type="text" class="breadcrumb" id="tamano" readonly="true"></td> <td width="238">&nbsp;</td> </tr> <tr bordercolor="#6699CC"> <td height="24" class="form_label_01"><strong>Orientaci&oacute;n:</strong></td> <td> <input name="orientacion" type="text" class="breadcrumb" id="orientacion" readonly="true"></td> <td> <div align="right"> </div></td> </tr> <tr bordercolor="#6699CC"> <td class="form_label_01"> <div align="left"><strong>Salida del Reporte:</strong></div></td> <td> <div align="left"> </div> <div align="left"> <strong> <input name="radiobutton" type="radio" class="breadcrumb" value="radiobutton" checked> PANTALLA</strong></div></td> <td> <strong> <input name="radiobutton" type="radio" class="breadcrumb" value="radiobutton"> IMPRESORA</strong></td> </tr> <tr bordercolor="#FFFFFF"> <td class="form_label_01">&nbsp;</td> <td colspan="2">&nbsp;</td> </tr> <tr bordercolor="#FFFFFF"> <td colspan="3" class="form_label_01"> <div align="center"><font color="#000066" size="3"><strong><em>Criterios de Selecci&oacute;n</em></strong></font></div></td> </tr> <tr bordercolor="#6699CC"> <td bordercolor="#FFFFFF" class="form_label_01">&nbsp;</td> <td><strong>DESDE</strong></td> <td><strong>HASTA</strong></td> </tr> <tr bordercolor="#6699CC"> <td class="form_label_01"> <div align="left"><strong>Tipo de Ingreso:</strong></div></td> <td> <div align="left"> <input name="tiping1" type="text" value="<? $sql="select min(codtip) as codtip from citiping"; LlenarTextoSql($sql,"codtip",$bd); ?>" class="breadcrumb" id="tiping1" size="15" maxlength="50"> <input type="button" name="Button1" value="..." onClick="catalogo('tiping1','1');"> </div></td> <td> <div align="left"> <input name="tiping2" type="text" value="<? $sql="select max(codtip) as codtip from citiping"; LlenarTextoSql($sql,"codtip",$bd); ?>" class="breadcrumb" id="tiping2" size="15" maxlength="50"> <input type="button" name="Button2" value="..." onClick="catalogo('tiping2');"> </div></td> </tr> <tr bordercolor="#FFFFFF"> <td class="form_label_01">&nbsp;</td> <td colspan="2">&nbsp;</td> </tr> <tr bordercolor="#FFFFFF"> <td class="form_label_01">&nbsp;</td> <td colspan="2">&nbsp;</td> </tr> <tr bordercolor="#6699CC"> <td colspan="3" class="form_label_01">&nbsp;</td> </tr> </table> </div> <div align="left">&nbsp; </div> </fieldset> <table width="356" border="0" align="center" cellpadding="0" cellspacing="0" bgcolor="#EEEEEE"> <tr> <td width="38" rowspan="3" bgcolor="#FFFFFF">&nbsp;</td> <td width="258"><img src="../../img/box01_tl.gif" width="6" height="6"></td> <td width="60" align="right"><img src="../../img/box01_tr.gif" width="6" height="6"></td> </tr> <tr> <td colspan="2" align="center"><input name="Button" type="button" class="form_button01" value="Generar" onClick="enviar()"> <input name="Button" type="button" class="form_button01" value=" Salir " onClick="cerrar()"> </td> </tr> <tr> <td><img src="../../img/box01_bl.gif" width="6" height="6"></td> <td align="right"><img src="../../img/box01_br.gif" width="6" height="6"></td> </tr> </table></td> <td width="6" align="right" valign="top"><img src="../../img/center01_tr.gif" width="6" height="6"></td> <td width="40" rowspan="2" align="center" bgcolor="#EEEEEE">&nbsp;</td> </tr> <tr> <td align="left" valign="bottom" class="cell_left_line02"><img src="../../img/center02_bl.gif" width="6" height="6"></td> <td align="right" valign="bottom"><img src="../../img/center01_br.gif" width="6" height="6"></td> </tr> </table> </form> </body> <script language="javascript"> function enviar() { f=document.form1; f.titulo.value="Listado de Tipos de Ingresos"; f.action="rinrtiping.php"; f.submit(); } function cerrar() { window.close(); } function catalogo(campo,valor) { if (valor=='1') { mysql='select codtip as Codigo, destip as Descripcion from citiping order by codtip'; } else { mysql='select codtip as Codigo, destip as Descripcion from citiping order by codtip desc'; } pagina="../../lib/general/catalogoobj.php?sql="+mysql+"&campo="+campo; window.open(pagina,"catalogo","menubar=no,toolbar=no,scrollbars=yes,width=500,height=400,resizable=yes,left=50,top=50"); } </script> </html>
gpl-2.0
Hannah93/BuddyForms
includes/admin/form-builder/meta-boxes/metabox-select-form.php
3326
<?php /** * Adds a box to the main column on the Post and Page edit screens. */ function buddyforms_add_custom_box() { global $buddyforms; if ( ! $buddyforms ) { return; } $screens = Array(); foreach ( $buddyforms as $key => $buddyform ) { if ( isset( $buddyform['post_type'] ) ) { array_push( $screens, $buddyform['post_type'] ); } } foreach ( $screens as $screen ) { add_meta_box( 'bf_sectionid', __( 'Attach a BuddyForm', 'buddyforms' ), 'buddyforms_inner_custom_box', $screen, 'side', 'high' ); } } add_action( 'add_meta_boxes', 'buddyforms_add_custom_box' ); /** * Prints the box content. * * @param WP_Post $post The object for the current post/page. */ function buddyforms_inner_custom_box( $post ) { global $buddyforms; // Add an nonce field so we can check for it later. wp_nonce_field( 'buddyforms_inner_custom_box', 'buddyforms_inner_custom_box_nonce' ); /* * Use get_post_meta() to retrieve an existing value * from the database and use the value for the form. */ $value = get_post_meta( $post->ID, '_bf_form_slug', true ); $buddyforms_posttypes_default = get_option( 'buddyforms_posttypes_default' ); if ( ! $value && isset( $buddyforms_posttypes_default[ $post->post_type ] ) ) { $value = $buddyforms_posttypes_default[ $post->post_type ]; } echo '<label for="_bf_form_slug">'; _e( "Select the form", 'buddyforms' ); echo '</label> '; //echo '<input type="text" id="_bf_form_slug" name="_bf_form_slug" value="' . esc_attr( $value ) . '" size="25" />'; echo ' <p><select name="_bf_form_slug" id="_bf_form_slug">'; echo ' <option value="none">' . __( 'None', 'buddyforms' ) . '</option>'; foreach ( $buddyforms as $key => $buddyform ) { $selected = ''; if ( $buddyform['slug'] == $value ) { $selected = ' selected'; } if ( $buddyform['post_type'] == get_post_type( $post ) ) { echo ' <option value="' . $buddyform['slug'] . '"' . $selected . '>' . $buddyform['name'] . '</option>'; } } echo '</select></p>'; do_action( 'buddyforms_post_edit_meta_box_select_form', $post ); } /** * When the post is saved, saves our custom data. * * @param int $post_id The ID of the post being saved. * * @return int */ function buddyforms_save_postdata( $post_id ) { if ( ! is_admin() ) { return $post_id; } if ( ! isset( $_POST['buddyforms_inner_custom_box_nonce'] ) ) { return $post_id; } $nonce = $_POST['buddyforms_inner_custom_box_nonce']; // Verify that the nonce is valid. if ( ! wp_verify_nonce( $nonce, 'buddyforms_inner_custom_box' ) ) { return $post_id; } // If this is an autosave, our form has not been submitted, so we don't want to do anything. if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) { return $post_id; } // Check the user's permissions. if ( 'page' == $_POST['post_type'] ) { if ( ! current_user_can( 'edit_page', $post_id ) ) { return $post_id; } } else { if ( ! current_user_can( 'edit_post', $post_id ) ) { return $post_id; } } /* OK, its safe for us to save the data now. */ // Sanitize user input. $form_slug = sanitize_text_field( $_POST['_bf_form_slug'] ); // Update the form slug for this post update_post_meta( $post_id, '_bf_form_slug', $form_slug ); return $post_id; } add_action( 'save_post', 'buddyforms_save_postdata' );
gpl-2.0
regneq/TrinityCore
src/server/scripts/Northrend/Ulduar/Ulduar/boss_ignis.cpp
17542
/* * This file is part of the TrinityCore Project. See AUTHORS file for Copyright information * * 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, see <http://www.gnu.org/licenses/>. */ #include "ScriptMgr.h" #include "GameTime.h" #include "InstanceScript.h" #include "ObjectAccessor.h" #include "ScriptedCreature.h" #include "SpellAuras.h" #include "SpellScript.h" #include "ulduar.h" #include "Vehicle.h" enum Yells { SAY_AGGRO = 0, SAY_SUMMON = 1, SAY_SLAG_POT = 2, SAY_SCORCH = 3, SAY_SLAY = 4, SAY_BERSERK = 5, SAY_DEATH = 6, EMOTE_JETS = 7 }; enum Spells { SPELL_FLAME_JETS = 62680, SPELL_SCORCH = 62546, SPELL_SLAG_POT = 62717, SPELL_SLAG_POT_DAMAGE = 65722, SPELL_SLAG_IMBUED = 62836, SPELL_ACTIVATE_CONSTRUCT = 62488, SPELL_STRENGHT = 64473, SPELL_GRAB = 62707, SPELL_BERSERK = 47008, // Iron Construct SPELL_HEAT = 65667, SPELL_MOLTEN = 62373, SPELL_BRITTLE = 62382, SPELL_BRITTLE_25 = 67114, SPELL_SHATTER = 62383, SPELL_GROUND = 62548, }; enum Events { EVENT_JET = 1, EVENT_SCORCH = 2, EVENT_SLAG_POT = 3, EVENT_GRAB_POT = 4, EVENT_CHANGE_POT = 5, EVENT_END_POT = 6, EVENT_CONSTRUCT = 7, EVENT_BERSERK = 8, }; enum Actions { ACTION_REMOVE_BUFF = 20, }; enum Creatures { NPC_IRON_CONSTRUCT = 33121, NPC_GROUND_SCORCH = 33221, }; enum AchievementData { DATA_SHATTERED = 29252926, ACHIEVEMENT_IGNIS_START_EVENT = 20951, }; #define CONSTRUCT_SPAWN_POINTS 20 Position const ConstructSpawnPosition[CONSTRUCT_SPAWN_POINTS] = { {630.366f, 216.772f, 360.891f, 3.001970f}, {630.594f, 231.846f, 360.891f, 3.124140f}, {630.435f, 337.246f, 360.886f, 3.211410f}, {630.493f, 313.349f, 360.886f, 3.054330f}, {630.444f, 321.406f, 360.886f, 3.124140f}, {630.366f, 247.307f, 360.888f, 3.211410f}, {630.698f, 305.311f, 360.886f, 3.001970f}, {630.500f, 224.559f, 360.891f, 3.054330f}, {630.668f, 239.840f, 360.890f, 3.159050f}, {630.384f, 329.585f, 360.886f, 3.159050f}, {543.220f, 313.451f, 360.886f, 0.104720f}, {543.356f, 329.408f, 360.886f, 6.248280f}, {543.076f, 247.458f, 360.888f, 6.213370f}, {543.117f, 232.082f, 360.891f, 0.069813f}, {543.161f, 305.956f, 360.886f, 0.157080f}, {543.277f, 321.482f, 360.886f, 0.052360f}, {543.316f, 337.468f, 360.886f, 6.195920f}, {543.280f, 239.674f, 360.890f, 6.265730f}, {543.265f, 217.147f, 360.891f, 0.174533f}, {543.256f, 224.831f, 360.891f, 0.122173f}, }; class boss_ignis : public CreatureScript { public: boss_ignis() : CreatureScript("boss_ignis") { } struct boss_ignis_AI : public BossAI { boss_ignis_AI(Creature* creature) : BossAI(creature, BOSS_IGNIS) { Initialize(); } void Initialize() { _slagPotGUID.Clear(); _shattered = false; _firstConstructKill = 0; } void Reset() override { _Reset(); if (Vehicle* _vehicle = me->GetVehicleKit()) _vehicle->RemoveAllPassengers(); instance->DoStopTimedAchievement(ACHIEVEMENT_TIMED_TYPE_EVENT, ACHIEVEMENT_IGNIS_START_EVENT); } void JustEngagedWith(Unit* who) override { BossAI::JustEngagedWith(who); Talk(SAY_AGGRO); events.ScheduleEvent(EVENT_JET, 30s); events.ScheduleEvent(EVENT_SCORCH, 25000); events.ScheduleEvent(EVENT_SLAG_POT, 35000); events.ScheduleEvent(EVENT_CONSTRUCT, 15000); events.ScheduleEvent(EVENT_END_POT, 40s); events.ScheduleEvent(EVENT_BERSERK, 480000); Initialize(); instance->DoStartTimedAchievement(ACHIEVEMENT_TIMED_TYPE_EVENT, ACHIEVEMENT_IGNIS_START_EVENT); } void JustDied(Unit* /*killer*/) override { _JustDied(); Talk(SAY_DEATH); } uint32 GetData(uint32 type) const override { if (type == DATA_SHATTERED) return _shattered ? 1 : 0; return 0; } void KilledUnit(Unit* who) override { if (who->GetTypeId() == TYPEID_PLAYER) Talk(SAY_SLAY); } void JustSummoned(Creature* summon) override { if (summon->GetEntry() == NPC_IRON_CONSTRUCT) { summon->SetFaction(FACTION_MONSTER_2); summon->SetReactState(REACT_AGGRESSIVE); summon->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_PACIFIED | UNIT_FLAG_STUNNED); summon->SetImmuneToPC(false); summon->SetControlled(false, UNIT_STATE_ROOT); } summon->AI()->AttackStart(me->GetVictim()); summon->AI()->DoZoneInCombat(); summons.Summon(summon); } void DoAction(int32 action) override { if (action != ACTION_REMOVE_BUFF) return; me->RemoveAuraFromStack(SPELL_STRENGHT); // Shattered Achievement time_t secondKill = GameTime::GetGameTime(); if ((secondKill - _firstConstructKill) < 5) _shattered = true; _firstConstructKill = secondKill; } void UpdateAI(uint32 diff) override { if (!UpdateVictim()) return; events.Update(diff); if (me->HasUnitState(UNIT_STATE_CASTING)) return; while (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_JET: Talk(EMOTE_JETS); DoCast(me, SPELL_FLAME_JETS); events.ScheduleEvent(EVENT_JET, 35s, 40s); break; case EVENT_SLAG_POT: if (Unit* target = SelectTarget(SelectTargetMethod::Random, 1, 100, true)) { Talk(SAY_SLAG_POT); _slagPotGUID = target->GetGUID(); DoCast(target, SPELL_GRAB); events.DelayEvents(3000); events.ScheduleEvent(EVENT_GRAB_POT, 500ms); } events.ScheduleEvent(EVENT_SLAG_POT, RAID_MODE(30000, 15000)); break; case EVENT_GRAB_POT: if (Unit* slagPotTarget = ObjectAccessor::GetUnit(*me, _slagPotGUID)) { slagPotTarget->EnterVehicle(me, 0); events.CancelEvent(EVENT_GRAB_POT); events.ScheduleEvent(EVENT_CHANGE_POT, 1s); } break; case EVENT_CHANGE_POT: if (Unit* slagPotTarget = ObjectAccessor::GetUnit(*me, _slagPotGUID)) { DoCast(slagPotTarget, SPELL_SLAG_POT, true); slagPotTarget->EnterVehicle(me, 1); events.CancelEvent(EVENT_CHANGE_POT); events.ScheduleEvent(EVENT_END_POT, 10s); } break; case EVENT_END_POT: if (Unit* slagPotTarget = ObjectAccessor::GetUnit(*me, _slagPotGUID)) { slagPotTarget->ExitVehicle(); slagPotTarget = nullptr; _slagPotGUID.Clear(); events.CancelEvent(EVENT_END_POT); } break; case EVENT_SCORCH: Talk(SAY_SCORCH); if (Unit* target = me->GetVictim()) me->SummonCreature(NPC_GROUND_SCORCH, target->GetPositionX(), target->GetPositionY(), target->GetPositionZ(), 0, TEMPSUMMON_TIMED_DESPAWN, 45000); DoCast(SPELL_SCORCH); events.ScheduleEvent(EVENT_SCORCH, 25000); break; case EVENT_CONSTRUCT: Talk(SAY_SUMMON); DoSummon(NPC_IRON_CONSTRUCT, ConstructSpawnPosition[urand(0, CONSTRUCT_SPAWN_POINTS - 1)], 30000, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT); DoCast(SPELL_STRENGHT); DoCast(me, SPELL_ACTIVATE_CONSTRUCT); events.ScheduleEvent(EVENT_CONSTRUCT, RAID_MODE(40000, 30000)); break; case EVENT_BERSERK: DoCast(me, SPELL_BERSERK, true); Talk(SAY_BERSERK); break; } if (me->HasUnitState(UNIT_STATE_CASTING)) return; } DoMeleeAttackIfReady(); } private: ObjectGuid _slagPotGUID; time_t _firstConstructKill; bool _shattered; }; CreatureAI* GetAI(Creature* creature) const override { return GetUlduarAI<boss_ignis_AI>(creature); } }; class npc_iron_construct : public CreatureScript { public: npc_iron_construct() : CreatureScript("npc_iron_construct") { } struct npc_iron_constructAI : public ScriptedAI { npc_iron_constructAI(Creature* creature) : ScriptedAI(creature), _instance(creature->GetInstanceScript()) { Initialize(); creature->SetReactState(REACT_PASSIVE); } void Initialize() { _brittled = false; } void Reset() override { Initialize(); } void DamageTaken(Unit* /*attacker*/, uint32& damage) override { if (me->HasAura(RAID_MODE(SPELL_BRITTLE, SPELL_BRITTLE_25)) && damage >= 5000) { DoCast(SPELL_SHATTER); if (Creature* ignis = _instance->GetCreature(BOSS_IGNIS)) if (ignis->AI()) ignis->AI()->DoAction(ACTION_REMOVE_BUFF); me->DespawnOrUnsummon(1000); } } void UpdateAI(uint32 /*uiDiff*/) override { if (!UpdateVictim()) return; if (Aura* aur = me->GetAura(SPELL_HEAT)) { if (aur->GetStackAmount() >= 10) { me->RemoveAura(SPELL_HEAT); DoCast(SPELL_MOLTEN); _brittled = false; } } // Water pools if (me->IsInWater() && !_brittled && me->HasAura(SPELL_MOLTEN)) { DoCast(SPELL_BRITTLE); me->RemoveAura(SPELL_MOLTEN); _brittled = true; } DoMeleeAttackIfReady(); } private: InstanceScript* _instance; bool _brittled; }; CreatureAI* GetAI(Creature* creature) const override { return GetUlduarAI<npc_iron_constructAI>(creature); } }; class npc_scorch_ground : public CreatureScript { public: npc_scorch_ground() : CreatureScript("npc_scorch_ground") { } struct npc_scorch_groundAI : public ScriptedAI { npc_scorch_groundAI(Creature* creature) : ScriptedAI(creature) { Initialize(); me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_PACIFIED); me->SetControlled(true, UNIT_STATE_ROOT); creature->SetDisplayId(16925); //model 2 in db cannot overwrite wdb fields } void Initialize() { _heat = false; _constructGUID.Clear(); _heatTimer = 0; } void MoveInLineOfSight(Unit* who) override { if (!_heat) { if (who->GetEntry() == NPC_IRON_CONSTRUCT) { if (!who->HasAura(SPELL_HEAT) || !who->HasAura(SPELL_MOLTEN)) { _constructGUID = who->GetGUID(); _heat = true; } } } } void Reset() override { Initialize(); DoCast(me, SPELL_GROUND); } void UpdateAI(uint32 uiDiff) override { if (_heat) { if (_heatTimer <= uiDiff) { Creature* construct = ObjectAccessor::GetCreature(*me, _constructGUID); if (construct && !construct->HasAura(SPELL_MOLTEN)) { me->AddAura(SPELL_HEAT, construct); _heatTimer = 1000; } } else _heatTimer -= uiDiff; } } private: ObjectGuid _constructGUID; uint32 _heatTimer; bool _heat; }; CreatureAI* GetAI(Creature* creature) const override { return GetUlduarAI<npc_scorch_groundAI>(creature); } }; class spell_ignis_slag_pot : public SpellScriptLoader { public: spell_ignis_slag_pot() : SpellScriptLoader("spell_ignis_slag_pot") { } class spell_ignis_slag_pot_AuraScript : public AuraScript { PrepareAuraScript(spell_ignis_slag_pot_AuraScript); bool Validate(SpellInfo const* /*spellInfo*/) override { return ValidateSpellInfo({ SPELL_SLAG_POT_DAMAGE, SPELL_SLAG_IMBUED }); } void HandleEffectPeriodic(AuraEffect const* /*aurEff*/) { if (Unit* caster = GetCaster()) { Unit* target = GetTarget(); caster->CastSpell(target, SPELL_SLAG_POT_DAMAGE, true); } } void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) { if (GetTarget()->IsAlive()) GetTarget()->CastSpell(GetTarget(), SPELL_SLAG_IMBUED, true); } void Register() override { OnEffectPeriodic += AuraEffectPeriodicFn(spell_ignis_slag_pot_AuraScript::HandleEffectPeriodic, EFFECT_0, SPELL_AURA_PERIODIC_DUMMY); AfterEffectRemove += AuraEffectRemoveFn(spell_ignis_slag_pot_AuraScript::OnRemove, EFFECT_0, SPELL_AURA_PERIODIC_DUMMY, AURA_EFFECT_HANDLE_REAL); } }; AuraScript* GetAuraScript() const override { return new spell_ignis_slag_pot_AuraScript(); } }; class achievement_ignis_shattered : public AchievementCriteriaScript { public: achievement_ignis_shattered() : AchievementCriteriaScript("achievement_ignis_shattered") { } bool OnCheck(Player* /*source*/, Unit* target) override { if (UnitAI* ai = target ? target->GetAI() : nullptr) return ai->GetData(DATA_SHATTERED) != 0; return false; } }; void AddSC_boss_ignis() { new boss_ignis(); new npc_iron_construct(); new npc_scorch_ground(); new spell_ignis_slag_pot(); new achievement_ignis_shattered(); }
gpl-2.0
KKBOX/FireApp
src/compiler/base_compiler.rb
3533
class BaseCompiler def self.compile(src_file_path, dst_file_path, options = {}) # _compile(src_file_path, dst_file_path, options) do ... end raise "You should implement this method: #{__method__}" end def self.src_file_ext # "coffee" raise "You should implement this method: #{__method__}" end def self.dst_file_ext # "js" raise "You should implement this method: #{__method__}" end def self.cache_folder_name # ".coffeescript-cache" raise "You should implement this method: #{__method__}" end def self.compile_folder(src_dir, dst_dir, options = {}) src_dir = File.expand_path(src_dir) dst_dir = File.expand_path(dst_dir) src_files = File.join(src_dir, "**", "*.#{self.src_file_ext}") Dir.glob( src_files ) do |path| #new_js_path = dst_file_path(src_dir, path, dst_dir) # CoffeeCompiler.new(full_path, new_js_path, get_cache_dir(coffeescripts_dir), options ).compile compile( path, get_dst_file_path(src_dir, path, dst_dir), options ) end end def self.clean_folder(src_dir, dst_dir) src_dir = File.expand_path(src_dir) dst_dir = File.expand_path(dst_dir) cache = CompilationCache.new(cache_folder_name) cache.cached_file_list.each do |path| dst_file = get_dst_file_path(src_dir, path, dst_dir) if File.exists?(dst_file) log( :remove, dst_file) FileUtils.rm_rf(dst_file) end end Dir.glob( File.join(src_dir, "**", "*.#{self.src_file_ext}")) do |path| dst_file = get_dst_file_path(src_dir, path, dst_dir) if File.exists?(dst_file) log( :remove, dst_file) FileUtils.rm_rf(dst_file) end end cache.clear log( :remove, "#{cache.cache_dir}/") end private def self.log(type, msg) msg = msg.sub(File.expand_path(Compass.configuration.project_path), '')[1..-1] if defined?(Tray) if defined?(Tray) && Tray.instance.logger Tray.instance.logger.record type, msg else puts " #{type} #{msg}" end end def self.get_dst_file_path(src_dir, src_file_path, dst_dir) src_file_path = File.expand_path(src_file_path) new_dir = File.dirname(src_file_path.to_s.sub(src_dir, "")) new_file = File.basename(src_file_path) .gsub(/\.#{self.src_file_ext}$/,".#{self.dst_file_ext}") .gsub(/\.#{self.dst_file_ext}\.#{self.dst_file_ext}$/,".#{self.dst_file_ext}") return File.join(dst_dir, new_dir, new_file) end def self.write_dst_file(dst_file_path, content) dst_file_path.parent.mkdir unless dst_file_path.parent.exist? if dst_file_path.exist? log( :overwrite, dst_file_path.to_s) else log( :create, dst_file_path.to_s) end dst_file_path.open("w") do |f| f.write(content) end end def self._compile(src_file_path, dst_file_path, options) src_file_path = Pathname.new(src_file_path) dst_file_path = Pathname.new(dst_file_path) cache = CompilationCache.new(cache_folder_name) begin content = cache.get(src_file_path) if content.nil? content = yield cache.update(src_file_path, content) end write_dst_file(dst_file_path, content) content rescue Exception => e error_msg = "#{src_file_path}: #{e.message}" log(:error, error_msg) "document.write("+ error_msg.to_json + ")" end end end
gpl-2.0
flegastelois/glpi
front/item_devicegeneric.form.php
1298
<?php /** * --------------------------------------------------------------------- * GLPI - Gestionnaire Libre de Parc Informatique * Copyright (C) 2015-2021 Teclib' and contributors. * * http://glpi-project.org * * based on GLPI - Gestionnaire Libre de Parc Informatique * Copyright (C) 2003-2014 by the INDEPNET Development Team. * * --------------------------------------------------------------------- * * LICENSE * * This file is part of GLPI. * * GLPI 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. * * GLPI 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 GLPI. If not, see <http://www.gnu.org/licenses/>. * --------------------------------------------------------------------- */ include('../inc/includes.php'); $item_device = new Item_DeviceGeneric(); include(GLPI_ROOT . "/front/item_device.common.form.php");
gpl-2.0
evolutivo/asf
modules/mod_lofarticlesslideshow/mod_lofarticlesslideshow.php
3243
<?php /** * $ModDesc * * @version $Id: $file.php $Revision * @package modules * @subpackage $Subpackage. * @copyright Copyright (C) November 2010 LandOfCoder.com <@emai:landofcoder@gmail.com>.All rights reserved. * @license GNU General Public License version 2 */ // no direct access defined('_JEXEC') or die; // Include the syndicate functions only once require_once dirname(__FILE__).DS.'helper.php'; $list = modLofArticlesSlideShowHelper::getList( $params ); $tmp = $params->get( 'module_height', 'auto' ); $moduleHeight = ( $tmp=='auto' ) ? 'auto' : (int)$tmp.'px'; $tmp = $params->get( 'module_width', 'auto' ); $moduleWidth = ( $tmp=='auto') ? 'auto': (int)$tmp.'px'; $themeClass = $params->get( 'theme' , ''); $openTarget = $params->get( 'open_target', 'parent' ); $class = $params->get( 'navigator_pos', 'right' ) == "0" ? '':'lof-sn'.$params->get( 'navigator_pos', 'right' ); $css3 = $params->get('enable_css3','1')? " lof-css3":""; $isIntrotext = $params->get('slider_information', 'description') == 'description'?0:1; $enableBlockdescription = $params->get( 'enable_blockdescription' , 1 ); $enableImageLink = $params->get( 'enable_image_link' , 0); // navigator setting $navEnableThumbnail = $params->get( 'enable_thumbnail', 1 ); $navEnableTitle = $params->get( 'enable_navtitle', 1 ); $navEnableDate = $params->get( 'enable_navdate', 1 ); $navEnableCate = $params->get( 'enable_navcate', 1 ); $customSliderClass = $params->get('custom_slider_class',''); $customSliderClass = is_array($customSliderClass)?$customSliderClass:array($customSliderClass); modLofArticlesSlideShowHelper::loadMediaFiles( $params, $module ); require( JModuleHelper::getLayoutPath($module->module) ); ?> <script type="text/javascript"> var _lofmain = $('lofass<?php echo $module->id; ?>'); var object = new LofArticleSlideshow( _lofmain, { fxObject:{ transition:<?php echo $params->get( 'effect', 'Sine.easeInOut' );?>, duration:<?php echo (int)$params->get('duration', '700')?> }, startItem:<?php echo (int)$params->get('start_item',0);?>, interval:<?php echo (int)$params->get('interval', '3000'); ?>, direction :'<?php echo $params->get('layout_style','opacity');?>', navItemHeight:<?php echo $params->get('navitem_height', 100) ?>, navItemWidth:<?php echo $params->get('navitem_width', 290) ?>, navItemsDisplay:<?php echo $params->get('max_items_display', 3) ?>, navPos:'<?php echo $params->get( 'navigator_pos', 0 ); ?>', autoStart:<?php echo (int)$params->get('auto_start',1)?>, descOpacity:<?php echo (float)$params->get('desc_opacity',1); ?> } ); <?php if( $params->get('display_button', '') ): ?> object.registerButtonsControl( 'click', {next:_lofmain.getElement('.lof-next'), previous:_lofmain.getElement('.lof-previous')} ); <?php endif; ?> </script>
gpl-2.0
iut-ibk/DynaMind-UrbanSim
3rdparty/opus/src/urbansim/gridcell/number_of_developed_with_buildings_within_walking_distance.py
506
# Opus/UrbanSim urban simulation software. # Copyright (C) 2005-2009 University of Washington # See opus_core/LICENSE from abstract_within_walking_distance import abstract_within_walking_distance class number_of_developed_with_buildings_within_walking_distance(abstract_within_walking_distance): """Total number of developed locations (computed from buildings) within walking distance of a given gridcell""" _return_type = "int32" dependent_variable = "is_developed_with_buildings"
gpl-2.0
dmarteau/QGIS
src/core/geometry/qgsabstractgeometry.cpp
13585
/*************************************************************************** qgsabstractgeometry.cpp ------------------------------------------------------------------- Date : 04 Sept 2014 Copyright : (C) 2014 by Marco Hugentobler email : marco.hugentobler at sourcepole dot com *************************************************************************** * * * 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. * * * ***************************************************************************/ #include "qgsapplication.h" #include "qgsabstractgeometry.h" #include "qgswkbptr.h" #include "qgsgeos.h" #include "qgsmaptopixel.h" #include "qgspoint.h" #include "qgsgeometrycollection.h" #include <nlohmann/json.hpp> #include <limits> #include <QTransform> QgsAbstractGeometry::QgsAbstractGeometry( const QgsAbstractGeometry &geom ) { mWkbType = geom.mWkbType; } QgsAbstractGeometry &QgsAbstractGeometry::operator=( const QgsAbstractGeometry &geom ) { if ( &geom != this ) { clear(); mWkbType = geom.mWkbType; } return *this; } void QgsAbstractGeometry::setZMTypeFromSubGeometry( const QgsAbstractGeometry *subgeom, QgsWkbTypes::Type baseGeomType ) { if ( !subgeom ) { return; } //special handling for 25d types: if ( baseGeomType == QgsWkbTypes::LineString && ( subgeom->wkbType() == QgsWkbTypes::Point25D || subgeom->wkbType() == QgsWkbTypes::LineString25D ) ) { mWkbType = QgsWkbTypes::LineString25D; return; } else if ( baseGeomType == QgsWkbTypes::Polygon && ( subgeom->wkbType() == QgsWkbTypes::Point25D || subgeom->wkbType() == QgsWkbTypes::LineString25D ) ) { mWkbType = QgsWkbTypes::Polygon25D; return; } bool hasZ = subgeom->is3D(); bool hasM = subgeom->isMeasure(); if ( hasZ && hasM ) { mWkbType = QgsWkbTypes::addM( QgsWkbTypes::addZ( baseGeomType ) ); } else if ( hasZ ) { mWkbType = QgsWkbTypes::addZ( baseGeomType ); } else if ( hasM ) { mWkbType = QgsWkbTypes::addM( baseGeomType ); } else { mWkbType = baseGeomType; } } QgsRectangle QgsAbstractGeometry::calculateBoundingBox() const { double xmin = std::numeric_limits<double>::max(); double ymin = std::numeric_limits<double>::max(); double xmax = -std::numeric_limits<double>::max(); double ymax = -std::numeric_limits<double>::max(); QgsVertexId id; QgsPoint vertex; double x, y; while ( nextVertex( id, vertex ) ) { x = vertex.x(); y = vertex.y(); if ( x < xmin ) xmin = x; if ( x > xmax ) xmax = x; if ( y < ymin ) ymin = y; if ( y > ymax ) ymax = y; } return QgsRectangle( xmin, ymin, xmax, ymax ); } void QgsAbstractGeometry::clearCache() const { } int QgsAbstractGeometry::nCoordinates() const { int nCoords = 0; const QgsCoordinateSequence seq = coordinateSequence(); for ( const QgsRingSequence &r : seq ) { for ( const QgsPointSequence &p : r ) { nCoords += p.size(); } } return nCoords; } double QgsAbstractGeometry::length() const { return 0.0; } double QgsAbstractGeometry::perimeter() const { return 0.0; } double QgsAbstractGeometry::area() const { return 0.0; } QString QgsAbstractGeometry::wktTypeStr() const { QString wkt = geometryType(); if ( is3D() ) wkt += 'Z'; if ( isMeasure() ) wkt += 'M'; return wkt; } QString QgsAbstractGeometry::asJson( int precision ) { return QString::fromStdString( asJsonObject( precision ).dump() ); } json QgsAbstractGeometry::asJsonObject( int precision ) const { Q_UNUSED( precision ) return nullptr; } QgsPoint QgsAbstractGeometry::centroid() const { // http://en.wikipedia.org/wiki/Centroid#Centroid_of_polygon // Pick the first ring of first part for the moment int n = vertexCount( 0, 0 ); if ( n == 1 ) { return vertexAt( QgsVertexId( 0, 0, 0 ) ); } double A = 0.; double Cx = 0.; double Cy = 0.; QgsPoint v0 = vertexAt( QgsVertexId( 0, 0, 0 ) ); int i = 0, j = 1; if ( vertexAt( QgsVertexId( 0, 0, 0 ) ) != vertexAt( QgsVertexId( 0, 0, n - 1 ) ) ) { i = n - 1; j = 0; } for ( ; j < n; i = j++ ) { QgsPoint vi = vertexAt( QgsVertexId( 0, 0, i ) ); QgsPoint vj = vertexAt( QgsVertexId( 0, 0, j ) ); vi.rx() -= v0.x(); vi.ry() -= v0.y(); vj.rx() -= v0.x(); vj.ry() -= v0.y(); double d = vi.x() * vj.y() - vj.x() * vi.y(); A += d; Cx += ( vi.x() + vj.x() ) * d; Cy += ( vi.y() + vj.y() ) * d; } if ( A < 1E-12 ) { Cx = Cy = 0.; for ( int i = 0; i < n - 1; ++i ) { QgsPoint vi = vertexAt( QgsVertexId( 0, 0, i ) ); Cx += vi.x(); Cy += vi.y(); } return QgsPoint( Cx / ( n - 1 ), Cy / ( n - 1 ) ); } else { return QgsPoint( v0.x() + Cx / ( 3. * A ), v0.y() + Cy / ( 3. * A ) ); } } bool QgsAbstractGeometry::convertTo( QgsWkbTypes::Type type ) { if ( type == mWkbType ) return true; if ( QgsWkbTypes::flatType( type ) != QgsWkbTypes::flatType( mWkbType ) ) return false; bool needZ = QgsWkbTypes::hasZ( type ); bool needM = QgsWkbTypes::hasM( type ); if ( !needZ ) { dropZValue(); } else if ( !is3D() ) { addZValue( std::numeric_limits<double>::quiet_NaN() ); } if ( !needM ) { dropMValue(); } else if ( !isMeasure() ) { addMValue( std::numeric_limits<double>::quiet_NaN() ); } return true; } void QgsAbstractGeometry::filterVertices( const std::function<bool ( const QgsPoint & )> & ) { // Ideally this would be pure virtual, but SIP has issues with that } void QgsAbstractGeometry::transformVertices( const std::function<QgsPoint( const QgsPoint & )> & ) { // Ideally this would be pure virtual, but SIP has issues with that } QgsAbstractGeometry::part_iterator QgsAbstractGeometry::parts_end() { const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( this ); return part_iterator( this, collection ? collection->partCount() : 1 ); } QgsGeometryPartIterator QgsAbstractGeometry::parts() { return QgsGeometryPartIterator( this ); } QgsGeometryConstPartIterator QgsAbstractGeometry::parts() const { return QgsGeometryConstPartIterator( this ); } QgsAbstractGeometry::const_part_iterator QgsAbstractGeometry::const_parts_end() const { const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( this ); return const_part_iterator( this, collection ? collection->partCount() : 1 ); } QgsVertexIterator QgsAbstractGeometry::vertices() const { return QgsVertexIterator( this ); } bool QgsAbstractGeometry::hasChildGeometries() const { return QgsWkbTypes::isMultiType( wkbType() ) || dimension() == 2; } QgsPoint QgsAbstractGeometry::childPoint( int index ) const { Q_UNUSED( index ) return QgsPoint(); } bool QgsAbstractGeometry::isEmpty() const { QgsVertexId vId; QgsPoint vertex; return !nextVertex( vId, vertex ); } bool QgsAbstractGeometry::hasCurvedSegments() const { return false; } bool QgsAbstractGeometry::boundingBoxIntersects( const QgsRectangle &rectangle ) const { return boundingBox().intersects( rectangle ); } QgsAbstractGeometry *QgsAbstractGeometry::segmentize( double tolerance, SegmentationToleranceType toleranceType ) const { Q_UNUSED( tolerance ) Q_UNUSED( toleranceType ) return clone(); } QgsAbstractGeometry::vertex_iterator::vertex_iterator( const QgsAbstractGeometry *g, int index ) : depth( 0 ) { levels.fill( Level() ); levels[0].g = g; levels[0].index = index; digDown(); // go to the leaf level of the first vertex } QgsAbstractGeometry::vertex_iterator &QgsAbstractGeometry::vertex_iterator::operator++() { if ( depth == 0 && levels[0].index >= levels[0].g->childCount() ) return *this; // end of geometry - nowhere else to go Q_ASSERT( !levels[depth].g->hasChildGeometries() ); // we should be at a leaf level ++levels[depth].index; // traverse up if we are at the end in the current level while ( depth > 0 && levels[depth].index >= levels[depth].g->childCount() ) { --depth; ++levels[depth].index; } digDown(); // go to the leaf level again return *this; } QgsAbstractGeometry::vertex_iterator QgsAbstractGeometry::vertex_iterator::operator++( int ) { vertex_iterator it( *this ); ++*this; return it; } QgsPoint QgsAbstractGeometry::vertex_iterator::operator*() const { Q_ASSERT( !levels[depth].g->hasChildGeometries() ); return levels[depth].g->childPoint( levels[depth].index ); } QgsVertexId QgsAbstractGeometry::vertex_iterator::vertexId() const { int part = 0, ring = 0, vertex = levels[depth].index; if ( depth == 0 ) { // nothing else to do } else if ( depth == 1 ) { if ( QgsWkbTypes::isMultiType( levels[0].g->wkbType() ) ) part = levels[0].index; else ring = levels[0].index; } else if ( depth == 2 ) { part = levels[0].index; ring = levels[1].index; } else { Q_ASSERT( false ); return QgsVertexId(); } // get the vertex type: find out from the leaf geometry QgsVertexId::VertexType vertexType = QgsVertexId::SegmentVertex; if ( const QgsCurve *curve = dynamic_cast<const QgsCurve *>( levels[depth].g ) ) { QgsPoint p; curve->pointAt( vertex, p, vertexType ); } return QgsVertexId( part, ring, vertex, vertexType ); } bool QgsAbstractGeometry::vertex_iterator::operator==( const QgsAbstractGeometry::vertex_iterator &other ) const { if ( depth != other.depth ) return false; return std::equal( std::begin( levels ), std::begin( levels ) + depth + 1, std::begin( other.levels ) ); } void QgsAbstractGeometry::vertex_iterator::digDown() { if ( levels[depth].g->hasChildGeometries() && levels[depth].index >= levels[depth].g->childCount() ) return; // first check we are not already at the end // while not "final" depth for the geom: go one level down. while ( levels[depth].g->hasChildGeometries() ) { ++depth; Q_ASSERT( depth < 3 ); // that's capacity of the levels array levels[depth].index = 0; levels[depth].g = levels[depth - 1].g->childGeometry( levels[depth - 1].index ); } } QgsPoint QgsVertexIterator::next() { n = i++; return *n; } QgsAbstractGeometry::part_iterator::part_iterator( QgsAbstractGeometry *g, int index ) : mIndex( index ) , mGeometry( g ) { } QgsAbstractGeometry::part_iterator &QgsAbstractGeometry::part_iterator::operator++() { const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( mGeometry ); if ( !collection ) { mIndex = 1; return *this; // end of geometry -- nowhere else to go } if ( mIndex >= collection->partCount() ) return *this; // end of geometry - nowhere else to go mIndex++; return *this; } QgsAbstractGeometry::part_iterator QgsAbstractGeometry::part_iterator::operator++( int ) { part_iterator it( *this ); ++*this; return it; } QgsAbstractGeometry *QgsAbstractGeometry::part_iterator::operator*() const { QgsGeometryCollection *collection = qgsgeometry_cast< QgsGeometryCollection * >( mGeometry ); if ( !collection ) { return mGeometry; } return collection->geometryN( mIndex ); } int QgsAbstractGeometry::part_iterator::partNumber() const { return mIndex; } bool QgsAbstractGeometry::part_iterator::operator==( QgsAbstractGeometry::part_iterator other ) const { return mGeometry == other.mGeometry && mIndex == other.mIndex; } QgsAbstractGeometry *QgsGeometryPartIterator::next() { n = i++; return *n; } QgsAbstractGeometry::const_part_iterator::const_part_iterator( const QgsAbstractGeometry *g, int index ) : mIndex( index ) , mGeometry( g ) { } QgsAbstractGeometry::const_part_iterator &QgsAbstractGeometry::const_part_iterator::operator++() { const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( mGeometry ); if ( !collection ) { mIndex = 1; return *this; // end of geometry -- nowhere else to go } if ( mIndex >= collection->partCount() ) return *this; // end of geometry - nowhere else to go mIndex++; return *this; } QgsAbstractGeometry::const_part_iterator QgsAbstractGeometry::const_part_iterator::operator++( int ) { const_part_iterator it( *this ); ++*this; return it; } const QgsAbstractGeometry *QgsAbstractGeometry::const_part_iterator::operator*() const { const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( mGeometry ); if ( !collection ) { return mGeometry; } return collection->geometryN( mIndex ); } int QgsAbstractGeometry::const_part_iterator::partNumber() const { return mIndex; } bool QgsAbstractGeometry::const_part_iterator::operator==( QgsAbstractGeometry::const_part_iterator other ) const { return mGeometry == other.mGeometry && mIndex == other.mIndex; } const QgsAbstractGeometry *QgsGeometryConstPartIterator::next() { n = i++; return *n; } bool QgsAbstractGeometry::vertex_iterator::Level::operator==( const QgsAbstractGeometry::vertex_iterator::Level &other ) const { return g == other.g && index == other.index; }
gpl-2.0
fb/XCSoar
src/Math/ZeroFinder.hpp
3219
/* Copyright_License { XCSoar Glide Computer - http://www.xcsoar.org/ Copyright (C) 2000-2016 The XCSoar Project A detailed list of copyright holders can be found in the file "AUTHORS". 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. } */ #ifndef ZERO_FINDER_HPP #define ZERO_FINDER_HPP #include "Util/Compiler.h" #include <cassert> /** * Zero finding and minimisation search algorithm * * Can be given initial value as hint of solution. * */ class ZeroFinder { protected: /** min value of search range */ const double xmin; /** max value of search range */ const double xmax; /** search tolerance in x */ const double tolerance; public: /** * Constructor of zero finder search algorithm * * @param _xmin Minimum allowable value of x * @param _xmax Maximum allowable value of x * @param _tolerance Absolute tolerance of solution (in x) */ ZeroFinder(const double _xmin, const double _xmax, const double _tolerance) :xmin(_xmin), xmax(_xmax), tolerance(_tolerance) { assert(xmin < xmax); } /** * Abstract method for function to be minimised or root-solved * * @param x Value of x * * @return f(x) */ virtual double f(const double x) = 0; /** * Find closest value of x that produces f(x)=0 * Method used is a variant of a bisector search. * To enforce search, set xstart outside range * * @param xstart Initial guess of x * * @return x value of best solution */ gcc_pure double find_zero(const double xstart); /** * Find value of x that minimises f(x) * Method used is a variant of a bisector search. * To enforce search, set xstart outside range * * @param xstart Initial guess of x * * @return x value of best solution */ gcc_pure double find_min(const double xstart); private: gcc_pure double find_zero_actual(const double xstart); gcc_pure double find_min_actual(const double xstart); /** * Tolerance in f of minimisation routine at x */ gcc_pure double tolerance_actual_min(const double x) const; /** * Tolerance in f of zero finding routine at x */ gcc_pure double tolerance_actual_zero(const double x) const; /** * Test whether solution is within tolerance * * @param xstart Initial value of x * @param tol_act Actual tolerance of routine evaluated at xstart * * @return true if no search required (xstart is good) */ gcc_pure bool solution_within_tolerance(const double xstart, const double tol_act); }; #endif
gpl-2.0
SLAC-OCIO/slac-www
sites/all/themes/slac_www/templates/field--field-header-image.tpl.php
3611
<?php /** * @file field.tpl.php * Default template implementation to display the value of a field. * * This file is not used by Drupal core, which uses theme functions instead for * performance reasons. The markup is the same, though, so if you want to use * template files rather than functions to extend field theming, copy this to * your custom theme. See theme_field() for a discussion of performance. * * Available variables: * - $items: An array of field values. Use render() to output them. * - $label: The item label. * - $label_hidden: Whether the label display is set to 'hidden'. * - $classes: String of classes that can be used to style contextually through * CSS. It can be manipulated through the variable $classes_array from * preprocess functions. The default values can be one or more of the * following: * - field: The current template type, i.e., "theming hook". * - field-name-[field_name]: The current field name. For example, if the * field name is "field_description" it would result in * "field-name-field-description". * - field-type-[field_type]: The current field type. For example, if the * field type is "text" it would result in "field-type-text". * - field-label-[label_display]: The current label position. For example, if * the label position is "above" it would result in "field-label-above". * * Other variables: * - $element['#object']: The entity to which the field is attached. * - $element['#view_mode']: View mode, e.g. 'full', 'teaser'... * - $element['#field_name']: The field name. * - $element['#field_type']: The field type. * - $element['#field_language']: The field language. * - $element['#field_translatable']: Whether the field is translatable or not. * - $element['#label_display']: Position of label display, inline, above, or * hidden. * - $field_name_css: The css-compatible field name. * - $field_type_css: The css-compatible field type. * - $classes_array: Array of html class attribute values. It is flattened * into a string within the variable $classes. * * @see template_preprocess_field() * @see theme_field() * * @ingroup themeable */ $image_url = file_create_url($items['0']['file']['#path']); ?> <!-- This file is not used by Drupal core, which uses theme functions instead. See http://api.drupal.org/api/function/theme_field/7 for details. After copying this file to your theme's folder and customizing it, remove this HTML comment. --> <?php if ($element['#object']->field_do_not_display_hero_image['und']['0']['value'] != 1): ?> <?php if ($element['#object']->field_do_not_limit_header_image_['und']['0']['value'] != 1): ?> <div class="header-image-as-background" style="background-image:url('<?php print $image_url; ?>');"> <?php if ( !empty( $items['0']['field_description']['#items']['0']['value'])) :?> <div class="header-image-bg-caption"><?php print $items['0']['field_description']['#items']['0']['value'] ?></div> <?php endif; ?> </div> <?php else: ?> <div class="<?php print $classes; ?>"<?php print $attributes; ?>> <?php if (!$label_hidden): ?> <div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>:&nbsp;</div> <?php endif; ?> <div class="field-items"<?php print $content_attributes; ?>> <?php foreach ($items as $delta => $item): ?> <div class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>><?php print render($item); ?></div> <?php endforeach; ?> </div> </div> <?php endif; ?> <?php endif; ?>
gpl-2.0
mgravina1/editohtml5
js/has_a_note.js
731
$(document).ready(function(){ var localStorageNameShapes = "CloudmedJsonImgHtml5" var localStorageNamePencil = "CloudmedJsonImgHtml5-pencil" $("#preview_elements").find('a').each(function(k,v){ var href = []; href=$(this).attr('href').split('\\'); href = href[href.length-1]; if(((localStorage.getItem(localStorageNameShapes+href))&& (($.parseJSON(localStorage.getItem(localStorageNameShapes+href)).areas.length) > 0))|| ((localStorage.getItem(localStorageNamePencil+href)) && ($.parseJSON(localStorage.getItem(localStorageNamePencil+href)).areas.length) > 0)) { $(this).find('img').addClass('has_note'); }else { $(this).find('img').removeClass('has_note'); } }) })
gpl-2.0
loveyoupeng/rt
modules/builders/src/main/java/javafx/scene/effect/LightBuilder.java
2147
/* * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javafx.scene.effect; /** Builder class for javafx.scene.effect.Light @see javafx.scene.effect.Light @deprecated This class is deprecated and will be removed in the next version * @since JavaFX 2.0 */ @javax.annotation.Generated("Generated by javafx.builder.processor.BuilderProcessor") @Deprecated public abstract class LightBuilder<B extends javafx.scene.effect.LightBuilder<B>> { protected LightBuilder() { } private boolean __set; public void applyTo(javafx.scene.effect.Light x) { if (__set) x.setColor(this.color); } private javafx.scene.paint.Color color; /** Set the value of the {@link javafx.scene.effect.Light#getColor() color} property for the instance constructed by this builder. */ @SuppressWarnings("unchecked") public B color(javafx.scene.paint.Color x) { this.color = x; __set = true; return (B) this; } }
gpl-2.0
subhadip-sahoo/burswood
wp-content/themes/burswood/template-step24.php
16762
<?php /* Template Name: step4 */ session_start(); if (!isset($_SESSION['api']['CategoryTypeID'])) $_SESSION['api']["CategoryTypeID"] = ""; if (!isset($_SESSION['api']['PickupLocationID'])) $_SESSION['api']["PickupLocationID"] = ""; if (!isset($_SESSION['api']['DropOffLocationID'])) $_SESSION['api']["DropOffLocationID"] = ""; if (!isset($_SESSION['api']['PickupDate'])) $_SESSION['api']["PickupDate"] = ""; if (!isset($_SESSION['api']['PickupTime'])) $_SESSION['api']["PickupTime"] = ""; if (!isset($_SESSION['api']['ReturnDate'])) $_SESSION['api']["ReturnDate"] = ""; if (!isset($_SESSION['api']['ReturnTime'])) $_SESSION['api']["ReturnTime"] = ""; if (!isset($_SESSION['api']['Age'])) $_SESSION['api']["Age"] = ""; if (!isset($_SESSION['api']['PromoCode'])) $_SESSION['api']["PromoCode"] = ""; if (!isset($_SESSION['api']['refid'])) $_SESSION['api']["refid"] = ""; if (!isset($_SESSION['api']['RateID'])) $_SESSION['api']["RateID"] = ""; if (!isset($_SESSION['api']['CarSizeID'])) $_SESSION['api']["CarSizeID"] = ""; if (!isset($_SESSION['api']['firstname'])) $_SESSION['api']["firstname"] = ""; if (!isset($_SESSION['api']['lastname'])) $_SESSION['api']["lastname"] = ""; if (!isset($_SESSION['api']['email'])) $_SESSION['api']["email"] = ""; if (!isset($_SESSION['api']['phone'])) $_SESSION['api']["phone"] = ""; if (!isset($_SESSION['api']['dob'])) $_SESSION['api']["dob"] = ""; if (!isset($_SESSION['api']['license'])) $_SESSION['api']["license"] = ""; if (!isset($_SESSION['api']['expire'])) $_SESSION['api']["expire"] = ""; if (!isset($_SESSION['api']['address'])) $_SESSION['api']["address"] = ""; if (!isset($_SESSION['api']['city'])) $_SESSION['api']["city"] = ""; if (!isset($_SESSION['api']['postcode'])) $_SESSION['api']["postcode"] = ""; if (!isset($_SESSION['api']['valoldcustomer'])) $_SESSION['api']["valoldcustomer"] = ""; if (!isset($_SESSION['api']['valquote'])) $_SESSION['api']["valquote"] = ""; if (!isset($_SESSION['api']['valbooking'])) $_SESSION['api']["valbooking"] = ""; if (!isset($_SESSION['api']['selOptions'])) $_SESSION['api']["selOptions"] = ""; if (!isset($_SESSION['api']['CustomerData'])) $_SESSION['api']["CustomerData"] = ""; if (!isset($_SESSION['api']['ReservationRef'])) $_SESSION['api']["ReservationRef"] = ""; if (!isset($_SESSION['api']['ReservationNo'])) $_SESSION['api']["ReservationNo"] = ""; if (!isset($_SESSION['api']['BookingType'])) $_SESSION['api']["BookingType"] = ""; if (isset($_POST["CategoryTypeID"])) $_SESSION['api']["CategoryTypeID"] = $_POST["CategoryTypeID"]; if (isset($_POST["PickupLocationID"])) $_SESSION['api']["PickupLocationID"] = $_POST["PickupLocationID"]; if (isset($_POST["DropOffLocationID"])) $_SESSION['api']["DropOffLocationID"] = $_POST["DropOffLocationID"]; if (isset($_POST["PickupDate"])) $_SESSION['api']["PickupDate"] = $_POST["PickupDate"]; if (isset($_POST["PickupTime"])) $_SESSION['api']["PickupTime"] = $_POST["PickupTime"]; if (isset($_POST["ReturnDate"])) $_SESSION['api']["ReturnDate"] = $_POST["ReturnDate"]; if (isset($_POST["ReturnTime"])) $_SESSION['api']["ReturnTime"] = $_POST["ReturnTime"]; if (isset($_POST["Age"])) $_SESSION['api']["Age"] = $_POST["Age"]; if (isset($_POST["PromoCode"])) $_SESSION['api']["PromoCode"] = $_POST["PromoCode"]; if (isset($_POST["refid"])) $_SESSION['api']["refid"] = $_POST["refid"]; if (isset($_POST["RateID"])) $_SESSION['api']["RateID"] = $_POST["RateID"]; if (isset($_POST["CarSizeID"])) $_SESSION['api']["CarSizeID"] = $_POST["CarSizeID"]; if (isset($_POST["firstname"])) $_SESSION['api']["firstname"] = $_POST["firstname"]; if (isset($_POST["lastname"])) $_SESSION['api']["lastname"] = $_POST["lastname"]; if (isset($_POST["email"])) $_SESSION['api']["email"] = $_POST["email"]; if (isset($_POST["phone"])) $_SESSION['api']["phone"] = $_POST["phone"]; if (isset($_POST["dob"])) $_SESSION['api']["dob"] = $_POST["dob"]; if (isset($_POST["license"])) $_SESSION['api']["license"] = $_POST["license"]; if (isset($_POST["expire"])) $_SESSION['api']["expire"] = $_POST["expire"]; if (isset($_POST["address"])) $_SESSION['api']["address"] = $_POST["address"]; if (isset($_POST["city"])) $_SESSION['api']["city"] = $_POST["city"]; if (isset($_POST["postcode"])) $_SESSION['api']["postcode"] = $_POST["postcode"]; if (isset($_POST["valoldcustomer"])) $_SESSION['api']["valoldcustomer"] = $_POST["valoldcustomer"]; if (isset($_POST["valquote"])) $_SESSION['api']["valquote"] = $_POST["valquote"]; if (isset($_POST["valbooking"])) $_SESSION['api']["valbooking"] = $_POST["valbooking"]; if (isset($_POST["selOptions"])) $_SESSION['api']["selOptions"] = $_POST["selOptions"]; if (isset($_POST["CustomerData"])) $_SESSION['api']["CustomerData"] = $_POST["CustomerData"]; if (isset($_POST["ReservationRef"])) $_SESSION['api']["ReservationRef"] = $_POST["ReservationRef"]; if (isset($_POST["ReservationNo"])) $_SESSION['api']["ReservationNo"] = $_POST["ReservationNo"]; if (isset($_POST["BookingType"])) $_SESSION['api']["BookingType"] = $_POST["BookingType"]; get_header(); ?> <script type="text/javascript" language="javascript"> //paste this code under head tag or in a seperate js file. // Wait for window load $(window).load(function () { // Animate loader off screen $(".se-pre-con").fadeOut("slow"); }); </script> <script type="text/javascript"> var frmvalidator; var getDetails = 0; var subtotal = 0.0; var basetotal = 0.0; var stamptotal = 0.0; var LocID = 0; var Age = 0; var SizeID = 0; var idleTime = 0; var idleInterval; var oAPI = new rcmAPI(); $(document).ready(function () { document.getElementById("lblResNo").innerHTML = "Booking Reference Number:<strong>" + document.getElementById("ReservationNo").value + "</strong>"; var ifrm = document.getElementById("frmAuric"); ifrm.contentWindow.document.write("<center><img src='<?php echo get_template_directory_uri(); ?>/images/Loading_White.gif' alt='Loading....'><br/>Loading...</center>"); ifrm.contentWindow.document.close(); oAPI.GetURL(document.getElementById("ReservationRef").value, 'frmAuric'); // Lock Payment screen after 1 minute being idle //Increment the idle time counter every second. idleInterval = setInterval(timerIncrement, 1000); // 1 minute //Zero the idle timer on mouse movement. $(this).mousemove(function (e) { idleTime = 0; }); $(this).keypress(function (e) { idleTime = 0; }); }); function timerIncrement() { idleTime = idleTime + 1; document.getElementById("lblMessage").innerHTML = "Auto lock in: " + (60 - idleTime) + " seconds."; if (idleTime >= 60) { LockPayment(); } } function LockPayment() { clearInterval(idleInterval); var ifrm = document.getElementById("frmAuric"); ifrm.src = "<?php echo get_template_directory_uri() ?>/lock.htm"; } function gotoConfirmation() { document.getElementById("frmStep4").submit(); } var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent"; var eventer = window[eventMethod]; var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message"; // Listen to message from child window needed for vault page eventer(messageEvent, function (e) { var key = e.message ? "message" : "data"; var data = e[key]; //run function// document.getElementById('frmAuric').src = "about:blank"; oAPI.OnPaymentDone(gotoConfirmation); oAPI.MakePayment( document.getElementById("ReservationRef").value, data ); }, false); </script> <div class="top-content"> <div class="inner-bg"> <div class="container"> <div class="row"> <div class="col-sm-12" id="rent-details"> <article> <ol> <li>Booking Dates</li> <li>SELECT CAR</li> <li class="act">SELECT OPTIONS</li> <li>REVIEW &amp; BOOK</li> </ol> </article> </div> </div> <div class="row"> <div class="col-sm-12"> <div id="progress-bar"> <div id="progress-bar-steps"> <div class="progress-bar-step done"> <a href="<?php echo home_url(); ?>"> <div class="step_number">1</div> <div class="step_name">Request</div> </a> </div> <div class="progress-bar-step done"> <a href="<?php echo site_url(); ?>/step2"> <div class="step_number">2</div> <div class="step_name">Select</div> </a> </div> <div class="progress-bar-step done"> <div class="step_number">3</div> <div class="step_name">Extras</div> </div> <div class="progress-bar-step current"> <div class="step_number">4</div> <div class="step_name">Payment</div> </div> <div class="progress-bar-step last"> <div class="step_number">5</div> <div class="step_name">Summary</div> </div> </div> <div class="clear"></div> </div> </div> </div> <div class="row" style="margin-top:5px;"> <div class="col-sm-12 form-box"> <div class="col-sm-12" style="background-color: white; border-radius: 5px; padding-top: 5px; padding-bottom: 5px;"> <div class="row"> <div class="form-group col-md-12"> <div id="displHeader"><span id="lblResNo">###</span></div> <div id="displBooking"> <table align="center" class="padlock"> <tr> <td style="padding-right: 5px; width: 8%; text-align: left;" id="td_Padlock"> <img src="<?php echo get_template_directory_uri(); ?>/images/padlock.png" width="32" height="32" /> </td> <td style="width: 80%; text-align: center" nowrap="nowrap"> <span id="lblHeaderTxt">Secure Credit Card Payment</span> </td> <td style="padding-left: 5px; text-align: right;" id="td_Card"> <img src="<?php echo get_template_directory_uri(); ?>/images/visa_mastercard.jpg" width="100" height="32" /> </td> </tr> </table> <div id="divCard" style="padding-top: 5px;"> <div id="pnlCardView" class="tdbackCard"> <center> <iframe id="frmAuric" name="frmAuric" class="frame" src="about:blank"></iframe> </center> </div> </div> <div id="DivErrorMSG" class="DivFrmMSG" style="display: none;"> <center> <div id="imgloading"> <img src="<?php echo get_template_directory_uri(); ?>/images/Loading_White.gif" alt="Confirming" /> </div> <table border="0" cellspacing="5" cellpadding="0" id="showcardMSG"> <tbody> <tr> <td align="center"> <textarea rows="7" cols="120" id="ltrlError" readonly="readonly" class="TextBoxAsLabel"> </textarea><br /> <input type="button" value="Add" id="btnAdd" name="btnAdd" onclick="window.location.reload();" style="text-align: center; display: none;" /> </td> </tr> </tbody> </table> </center> </div> <table align="center" border="0" style="margin-top: -15px; position: absolute"> <tr> <td colspan="2" class="NoteFooter"> Note : Your card will NOT be charged until vehicle availability is confirmed </td> </tr> </table> <table align="center" class="padlockFooter"> <tr> <td colspan="2"> <span id="lblMessage"></span> </td> </tr> <tr> <td align="left" style="width: 90%;" class="fontsmall"> <img src='<?php echo get_template_directory_uri(); ?>/images/Auric.png' /><br /> Secured by www.auricsystems.com<br /> Auric Systems is a Level 1 PCI DSS Validated Service Provider. </td> <td style="padding-left: 5px; vertical-align: bottom; text-align: right;"> <img src="<?php echo get_template_directory_uri(); ?>/images/pci_dss.png" /> </td> </tr> </table> </div> </div> </div> </div> </div> <div class="row"><div class="col-sm-12">&nbsp;</div></div> <form id="frmStep4" name="frmStep4" action="<?php echo site_url(); ?>/step4" method="post"> <input type='hidden' name='CategoryTypeID' id='CategoryTypeID' value='<?php echo $_SESSION['api']["CategoryTypeID"]; ?>'> <input type='hidden' name='PickupLocationID' id='PickupLocationID' value='<?php echo $_SESSION['api']["PickupLocationID"]; ?>'> <input type='hidden' name='DropOffLocationID' id='DropOffLocationID' value='<?php echo $_SESSION['api']["DropOffLocationID"]; ?>'> <input type='hidden' name='PickupDate' id='PickupDate' value='<?php echo $_SESSION['api']["PickupDate"]; ?>'> <input type='hidden' name='PickupTime' id='PickupTime' value='<?php echo $_SESSION['api']["PickupTime"]; ?>'> <input type='hidden' name='ReturnDate' id='ReturnDate' value='<?php echo $_SESSION['api']["ReturnDate"]; ?>'> <input type='hidden' name='ReturnTime' id='ReturnTime' value='<?php echo $_SESSION['api']["ReturnTime"]; ?>'> <input type='hidden' name='Age' id='Age' value='<?php echo $_SESSION['api']["Age"]; ?>'> <input type='hidden' name='RateID' id='RateID' value='<?php echo $_SESSION['api']["RateID"]; ?>'> <input type='hidden' name='CarSizeID' id='CarSizeID' value='<?php echo $_SESSION['api']["CarSizeID"]; ?>'> <input type='hidden' name='choosetext' id='choosetext' value='Check the following entries:'> <input type='hidden' name='valoldcustomer' id='valoldcustomer' value='<?php echo $_SESSION['api']["valoldcustomer"]; ?>'> <input type='hidden' name='valquote' id='valquote' value='<?php echo $_SESSION['api']["valquote"]; ?>'> <input type='hidden' name='valbooking' id='valbooking' value='<?php echo $_SESSION['api']["valbooking"]; ?>'> <input type='hidden' name='selOptions' id='selOptions' value='<?php echo $_SESSION['api']["selOptions"]; ?>'> <input type='hidden' name='CustomerData' id='CustomerData' value='<?php echo $_SESSION['api']["CustomerData"]; ?>'> <input type='hidden' name='Insurance' id='Insurance' value='<?php echo $_SESSION['api']["Insurance"]; ?>'> <input type='hidden' name='ExtraKmOut' id='ExtraKmOut' value='<?php echo $_SESSION['api']["ExtraKmOut"]; ?>'> <input type='hidden' name='ReservationRef' id='ReservationRef' value='<?php echo $_SESSION['api']["ReservationRef"]; ?>'> <input type='hidden' name='ReservationNo' id='ReservationNo' value='<?php echo $_SESSION['api']["ReservationNo"]; ?>'> <input type='hidden' name='BookingType' id='BookingType' value='<?php echo $_SESSION['api']["BookingType"]; ?>'> <input type='hidden' name='refid' id='refid' value='<?php echo $_SESSION['api']["refid"]; ?>'> </form> </div> </div> </div> </div> <?php get_footer(); ?>
gpl-2.0
SpoonLabs/astor
examples/chart_11/tests/org/jfree/chart/plot/dial/junit/StandardDialRangeTests.java
5402
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2007, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * 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, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------- * SimpleDialRangeTests.java * ------------------------- * (C) Copyright 2006-2007, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 03-Nov-2006 : Version 1 (DG); * */ package org.jfree.chart.plot.dial.junit; import java.awt.Color; import java.awt.GradientPaint; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.chart.plot.dial.StandardDialRange; /** * Tests for the {@link StandardDialRange} class. */ public class StandardDialRangeTests extends TestCase { /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(StandardDialRangeTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public StandardDialRangeTests(String name) { super(name); } /** * Confirm that the equals method can distinguish all the required fields. */ public void testEquals() { StandardDialRange r1 = new StandardDialRange(); StandardDialRange r2 = new StandardDialRange(); assertTrue(r1.equals(r2)); // lowerBound r1.setLowerBound(1.1); assertFalse(r1.equals(r2)); r2.setLowerBound(1.1); assertTrue(r1.equals(r2)); // upperBound r1.setUpperBound(11.1); assertFalse(r1.equals(r2)); r2.setUpperBound(11.1); assertTrue(r1.equals(r2)); // paint r1.setPaint(new GradientPaint(1.0f, 2.0f, Color.red, 3.0f, 4.0f, Color.blue)); assertFalse(r1.equals(r2)); r2.setPaint(new GradientPaint(1.0f, 2.0f, Color.red, 3.0f, 4.0f, Color.blue)); assertTrue(r1.equals(r2)); // check an inherited attribute r1.setVisible(false); assertFalse(r1.equals(r2)); r2.setVisible(false); assertTrue(r1.equals(r2)); } /** * Two objects that are equal are required to return the same hashCode. */ public void testHashCode() { StandardDialRange r1 = new StandardDialRange(); StandardDialRange r2 = new StandardDialRange(); assertTrue(r1.equals(r2)); int h1 = r1.hashCode(); int h2 = r2.hashCode(); assertEquals(h1, h2); } /** * Confirm that cloning works. */ public void testCloning() { StandardDialRange r1 = new StandardDialRange(); StandardDialRange r2 = null; try { r2 = (StandardDialRange) r1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } assertTrue(r1 != r2); assertTrue(r1.getClass() == r2.getClass()); assertTrue(r1.equals(r2)); // check that the listener lists are independent MyDialLayerChangeListener l1 = new MyDialLayerChangeListener(); r1.addChangeListener(l1); assertTrue(r1.hasListener(l1)); assertFalse(r2.hasListener(l1)); } /** * Serialize an instance, restore it, and check for equality. */ public void testSerialization() { StandardDialRange r1 = new StandardDialRange(); StandardDialRange r2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(r1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray())); r2 = (StandardDialRange) in.readObject(); in.close(); } catch (Exception e) { e.printStackTrace(); } assertEquals(r1, r2); } }
gpl-2.0
wangwen1220/ruigui-electronic.com
wp-content/themes/e-mall/archive.php
3124
<?php /** * The template for displaying Archive pages. * * Learn more: http://codex.wordpress.org/Template_Hierarchy * * @package _s */ get_header(); ?> <div class="pagebox mb15"> <div class="pagebox_hd"></div> <div class="pagebox_bd"> <div class="place"><?php if (function_exists('wp_bac_breadcrumb')) {wp_bac_breadcrumb();}?></div> <div class="arc_tags"><em>标签:</em> <?php $limit = get_option('posts_per_page'); $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; query_posts('cat='.$cat.'&paged=' . $paged); if (have_posts()) : while (have_posts()) : the_post(); $posttags = get_the_tags(); if ($posttags) { foreach($posttags as $tag) { $all_tags[] = $tag->term_id; } } endwhile; endif; wp_reset_query(); if($all_tags){ $tags_arr = array_unique($all_tags); $tags_str = implode(",", $tags_arr); $args = array( 'smallest' => 12, 'largest' => 12, 'unit' => 'px', 'number' => 15, 'orderby' => '', 'order' => DESC, 'format' => 'flat', 'include' => $tags_str ); wp_tag_cloud($args); }else{ echo '该分类下暂无标签'; } ?> </div> </div> <div class="pagebox_ft"></div> </div> <div class="w960" style="width:980px;"> <div class="list_content clearfix" id="list_content"> <?php if( have_posts() ){ while( have_posts() ) : the_post();?> <div class="item"> <div class="list_item"> <ul class="pic"> <li><a style="width:200px;" href="<?php the_permalink() ?>" target="_blank"> <?php $picurl = get_post_meta($post->ID,'haikuo_pic_url',true); if( has_post_thumbnail() ){ $img_id = get_post_thumbnail_id(); $img_url = wp_get_attachment_image_src($img_id); $img_url = $img_url[0]; $img_url_full = $img_url.'_full.jpg'; $array1 = get_headers($img_url_full); if ($array1[0] == 'HTTP/1.1 200 OK') { }else{ $img_url = get_bloginfo("template_url").'/timthumb.php?src='.$img_url.'&amp;q=90&amp;w=200'; } }elseif(!empty($picurl)){ $img_url = get_bloginfo("template_url").'/timthumb.php?src='.$picurl.'&amp;q=90&amp;w=200'; }else{ $img_url = get_post_img( '', 200, '' ); } echo '<img src="'.$img_url.'" alt="'.$post->post_title.'" width="200" />' ?> </a> <?php $price = get_post_meta($post->ID, "haikuo_tb_price", true); if(empty($price)){}else{?> <p>¥<?php echo $price; ?></p> <?php }?> </li> </ul> <div class="t_l"> <div class="tl"> <a href="<?php the_permalink() ?>#combook" class="cmt ed">评论(<span class="SHARE_CMT_COUNT"><?php $id=$post->ID; echo get_post($id)->comment_count;?></span>)</a> </div> </div> <div class="title"><a href="<?php the_permalink() ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></div> <?php global $withcomments; $withcomments = true; comments_template("/inline-comments.php"); ?> </div> </div> <?php endwhile; }else{echo '<div style="padding:20px;color:#777;">本分类暂无内容!</div>';}?> </div> <div class="page"> <?php pagenavi();?> </div> </div> <script> window.onload = function() { var wall = new Masonry( document.getElementById('list_content') ); }; </script> <?php get_footer(); ?>
gpl-2.0
md-5/jdk10
src/hotspot/share/gc/g1/heapRegionSet.hpp
8382
/* * Copyright (c) 2011, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ #ifndef SHARE_GC_G1_HEAPREGIONSET_HPP #define SHARE_GC_G1_HEAPREGIONSET_HPP #include "gc/g1/heapRegion.hpp" #include "utilities/macros.hpp" #define assert_heap_region_set(p, message) \ do { \ assert((p), "[%s] %s ln: %u", \ name(), message, length()); \ } while (0) #define guarantee_heap_region_set(p, message) \ do { \ guarantee((p), "[%s] %s ln: %u", \ name(), message, length()); \ } while (0) #define assert_free_region_list(p, message) \ do { \ assert((p), "[%s] %s ln: %u hd: " PTR_FORMAT " tl: " PTR_FORMAT, \ name(), message, length(), p2i(_head), p2i(_tail)); \ } while (0) // Interface collecting various instance specific verification methods of // HeapRegionSets. class HeapRegionSetChecker : public CHeapObj<mtGC> { public: // Verify MT safety for this HeapRegionSet. virtual void check_mt_safety() = 0; // Returns true if the given HeapRegion is of the correct type for this HeapRegionSet. virtual bool is_correct_type(HeapRegion* hr) = 0; // Return a description of the type of regions this HeapRegionSet contains. virtual const char* get_description() = 0; }; // Base class for all the classes that represent heap region sets. It // contains the basic attributes that each set needs to maintain // (e.g., length, region num, used bytes sum) plus any shared // functionality (e.g., verification). class HeapRegionSetBase { friend class VMStructs; HeapRegionSetChecker* _checker; protected: // The number of regions in to the set. uint _length; const char* _name; bool _verify_in_progress; // verify_region() is used to ensure that the contents of a region // added to / removed from a set are consistent. void verify_region(HeapRegion* hr) PRODUCT_RETURN; void check_mt_safety() { if (_checker != NULL) { _checker->check_mt_safety(); } } HeapRegionSetBase(const char* name, HeapRegionSetChecker* verifier); public: const char* name() { return _name; } uint length() const { return _length; } bool is_empty() { return _length == 0; } // It updates the fields of the set to reflect hr being added to // the set and tags the region appropriately. inline void add(HeapRegion* hr); // It updates the fields of the set to reflect hr being removed // from the set and tags the region appropriately. inline void remove(HeapRegion* hr); virtual void verify(); void verify_start(); void verify_next_region(HeapRegion* hr); void verify_end(); void verify_optional() { DEBUG_ONLY(verify();) } virtual void print_on(outputStream* out, bool print_contents = false); }; // This class represents heap region sets whose members are not // explicitly tracked. It's helpful to group regions using such sets // so that we can reason about all the region groups in the heap using // the same interface (namely, the HeapRegionSetBase API). class HeapRegionSet : public HeapRegionSetBase { public: HeapRegionSet(const char* name, HeapRegionSetChecker* checker): HeapRegionSetBase(name, checker) { } void bulk_remove(const uint removed) { _length -= removed; } }; // A set that links all the regions added to it in a doubly-linked // sorted list. We should try to avoid doing operations that iterate over // such lists in performance critical paths. Typically we should // add / remove one region at a time or concatenate two lists. class FreeRegionListIterator; class G1NUMA; class FreeRegionList : public HeapRegionSetBase { friend class FreeRegionListIterator; private: // This class is only initialized if there are multiple active nodes. class NodeInfo : public CHeapObj<mtGC> { G1NUMA* _numa; uint* _length_of_node; uint _num_nodes; public: NodeInfo(); ~NodeInfo(); inline void increase_length(uint node_index); inline void decrease_length(uint node_index); inline uint length(uint index) const; void clear(); void add(NodeInfo* info); }; HeapRegion* _head; HeapRegion* _tail; // _last is used to keep track of where we added an element the last // time. It helps to improve performance when adding several ordered items in a row. HeapRegion* _last; NodeInfo* _node_info; static uint _unrealistically_long_length; inline HeapRegion* remove_from_head_impl(); inline HeapRegion* remove_from_tail_impl(); inline void increase_length(uint node_index); inline void decrease_length(uint node_index); // Common checks for adding a list. void add_list_common_start(FreeRegionList* from_list); void add_list_common_end(FreeRegionList* from_list); protected: // See the comment for HeapRegionSetBase::clear() virtual void clear(); public: FreeRegionList(const char* name, HeapRegionSetChecker* checker = NULL); ~FreeRegionList(); void verify_list(); #ifdef ASSERT bool contains(HeapRegion* hr) const { return hr->containing_set() == this; } #endif static void set_unrealistically_long_length(uint len); // Add hr to the list. The region should not be a member of another set. // Assumes that the list is ordered and will preserve that order. The order // is determined by hrm_index. inline void add_ordered(HeapRegion* hr); // Same restrictions as above, but adds the region last in the list. inline void add_to_tail(HeapRegion* region_to_add); // Removes from head or tail based on the given argument. HeapRegion* remove_region(bool from_head); HeapRegion* remove_region_with_node_index(bool from_head, uint requested_node_index); // Merge two ordered lists. The result is also ordered. The order is // determined by hrm_index. void add_ordered(FreeRegionList* from_list); void append_ordered(FreeRegionList* from_list); // It empties the list by removing all regions from it. void remove_all(); // Abandon current free list. Requires that all regions in the current list // are taken care of separately, to allow a rebuild. void abandon(); // Remove all (contiguous) regions from first to first + num_regions -1 from // this list. // Num_regions must be > 1. void remove_starting_at(HeapRegion* first, uint num_regions); virtual void verify(); uint num_of_regions_in_range(uint start, uint end) const; using HeapRegionSetBase::length; uint length(uint node_index) const; }; // Iterator class that provides a convenient way to iterate over the // regions of a FreeRegionList. class FreeRegionListIterator : public StackObj { private: FreeRegionList* _list; HeapRegion* _curr; public: bool more_available() { return _curr != NULL; } HeapRegion* get_next() { assert(more_available(), "get_next() should be called when more regions are available"); // If we are going to introduce a count in the iterator we should // do the "cycle" check. HeapRegion* hr = _curr; _list->verify_region(hr); _curr = hr->next(); return hr; } FreeRegionListIterator(FreeRegionList* list) : _list(list), _curr(list->_head) { } }; #endif // SHARE_GC_G1_HEAPREGIONSET_HPP
gpl-2.0
samskivert/ikvm-openjdk
build/linux-amd64/impsrc/com/sun/tools/internal/ws/resources/UtilMessages.java
3053
/* * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tools.internal.ws.resources; import com.sun.xml.internal.ws.util.localization.Localizable; import com.sun.xml.internal.ws.util.localization.LocalizableMessageFactory; import com.sun.xml.internal.ws.util.localization.Localizer; /** * Defines string formatting method for each constant in the resource file * */ public final class UtilMessages { private final static LocalizableMessageFactory messageFactory = new LocalizableMessageFactory("com.sun.tools.internal.ws.resources.util"); private final static Localizer localizer = new Localizer(); public static Localizable localizableSAX_2_DOM_NOTSUPPORTED_CREATEELEMENT(Object arg0) { return messageFactory.getMessage("sax2dom.notsupported.createelement", arg0); } /** * SAX2DOMEx.DomImplDoesntSupportCreateElementNs: {0} * */ public static String SAX_2_DOM_NOTSUPPORTED_CREATEELEMENT(Object arg0) { return localizer.localize(localizableSAX_2_DOM_NOTSUPPORTED_CREATEELEMENT(arg0)); } public static Localizable localizableNULL_NAMESPACE_FOUND(Object arg0) { return messageFactory.getMessage("null.namespace.found", arg0); } /** * Encountered error in wsdl. Check namespace of element <{0}> * */ public static String NULL_NAMESPACE_FOUND(Object arg0) { return localizer.localize(localizableNULL_NAMESPACE_FOUND(arg0)); } public static Localizable localizableHOLDER_VALUEFIELD_NOT_FOUND(Object arg0) { return messageFactory.getMessage("holder.valuefield.not.found", arg0); } /** * Could not find the field in the Holder that contains the Holder''s value: {0} * */ public static String HOLDER_VALUEFIELD_NOT_FOUND(Object arg0) { return localizer.localize(localizableHOLDER_VALUEFIELD_NOT_FOUND(arg0)); } }
gpl-2.0
iammyr/Benchmark
src/main/java/org/owasp/benchmark/testcode/BenchmarkTest11495.java
2423
/** * OWASP Benchmark Project v1.1 * * This file is part of the Open Web Application Security Project (OWASP) * Benchmark Project. For details, please see * <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>. * * The Benchmark 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, version 2. * * The Benchmark 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 * * @author Dave Wichers <a href="https://www.aspectsecurity.com">Aspect Security</a> * @created 2015 */ package org.owasp.benchmark.testcode; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/BenchmarkTest11495") public class BenchmarkTest11495 extends HttpServlet { private static final long serialVersionUID = 1L; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String param = ""; java.util.Enumeration<String> names = request.getParameterNames(); if (names.hasMoreElements()) { param = names.nextElement(); // just grab first element } String bar = new Test().doSomething(param); String sql = "{call verifyUserPassword('foo','"+bar+"')}"; try { java.sql.Connection connection = org.owasp.benchmark.helpers.DatabaseHelper.getSqlConnection(); java.sql.CallableStatement statement = connection.prepareCall( sql, java.sql.ResultSet.TYPE_FORWARD_ONLY, java.sql.ResultSet.CONCUR_READ_ONLY ); statement.execute(); } catch (java.sql.SQLException e) { throw new ServletException(e); } } // end doPost private class Test { public String doSomething(String param) throws ServletException, IOException { String bar = param; return bar; } } // end innerclass Test } // end DataflowThruInnerClass
gpl-2.0
flegastelois/glpi
src/Application/View/Extension/FrontEndAssetsExtension.php
6096
<?php /** * --------------------------------------------------------------------- * GLPI - Gestionnaire Libre de Parc Informatique * Copyright (C) 2015-2021 Teclib' and contributors. * * http://glpi-project.org * * based on GLPI - Gestionnaire Libre de Parc Informatique * Copyright (C) 2003-2014 by the INDEPNET Development Team. * * --------------------------------------------------------------------- * * LICENSE * * This file is part of GLPI. * * GLPI 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. * * GLPI 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 GLPI. If not, see <http://www.gnu.org/licenses/>. * --------------------------------------------------------------------- */ namespace Glpi\Application\View\Extension; use DBmysql; use Entity; use Html; use Plugin; use Session; use Twig\Extension\AbstractExtension; use Twig\TwigFunction; /** * @since 10.0.0 */ class FrontEndAssetsExtension extends AbstractExtension { public function getFunctions(): array { return [ new TwigFunction('asset_path', [$this, 'assetPath']), new TwigFunction('css_path', [$this, 'cssPath']), new TwigFunction('js_path', [$this, 'jsPath']), new TwigFunction('custom_css', [$this, 'customCss'], ['is_safe' => ['html']]), new TwigFunction('locales_js', [$this, 'localesJs'], ['is_safe' => ['html']]), ]; } /** * Return domain-relative path of an asset. * * @param string $path * * @return string */ public function assetPath(string $path): string { return Html::getPrefixedUrl($path); } /** * Return domain-relative path of a CSS file. * * @param string $path * * @return string */ public function cssPath(string $path): string { $is_debug = isset($_SESSION['glpi_use_mode']) && $_SESSION['glpi_use_mode'] === Session::DEBUG_MODE; if (preg_match('/\.scss$/', $path)) { $compiled_file = Html::getScssCompilePath($path); if (!$is_debug && file_exists($compiled_file)) { $path = str_replace(GLPI_ROOT, '', $compiled_file); } else { $path = '/front/css.php?file=' . $path . ($is_debug ? '&debug=1' : ''); } } else { $minified_path = str_replace('.css', '.min.css', $path); if (!$is_debug && file_exists(GLPI_ROOT . '/' . $minified_path)) { $path = $minified_path; } } $path = Html::getPrefixedUrl($path); $path = $this->getVersionnedPath($path); return $path; } /** * Return domain-relative path of a JS file. * * @param string $path * * @return string */ public function jsPath(string $path): string { $is_debug = isset($_SESSION['glpi_use_mode']) && $_SESSION['glpi_use_mode'] === Session::DEBUG_MODE; $minified_path = str_replace('.js', '.min.js', $path); if (!$is_debug && file_exists(GLPI_ROOT . '/' . $minified_path)) { $path = $minified_path; } $path = Html::getPrefixedUrl($path); $path = $this->getVersionnedPath($path); return $path; } /** * Get path suffixed with asset version. * * @param string $path * * @return string */ private function getVersionnedPath(string $path): string { // @TODO Adapt version to plugin version if path is related to a specific plugin $version = GLPI_VERSION; $path .= (strpos($path, '?') !== false ? '&' : '?') . 'v=' . $version; return $path; } /** * Return custom CSS for active entity. * * @return string */ public function customCss(): string { global $DB; $css = ''; if ($DB instanceof DBmysql && $DB->connected) { $entity = new Entity(); if (isset($_SESSION['glpiactive_entity'])) { // Apply active entity styles $entity->getFromDB($_SESSION['glpiactive_entity']); } else { // Apply root entity styles $entity->getFromDB('0'); } $css = $entity->getCustomCssTag(); } return $css; } /** * Return locales JS code. * * @return string */ public function localesJs(): string { if (!isset($_SESSION['glpilanguage'])) { return ''; } // Compute available translation domains $locales_domains = ['glpi' => GLPI_VERSION]; $plugins = Plugin::getPlugins(); foreach ($plugins as $plugin) { $locales_domains[$plugin] = Plugin::getInfo($plugin, 'version'); } $script = <<<JAVASCRIPT $(function() { i18n.setLocale('{$_SESSION['glpilanguage']}'); }); JAVASCRIPT; foreach ($locales_domains as $locale_domain => $locale_version) { $locales_path = Html::getPrefixedUrl( '/front/locale.php' . '?domain=' . $locale_domain . '&version=' . $locale_version . ($_SESSION['glpi_use_mode'] == Session::DEBUG_MODE ? '&debug' : '') ); $script .= <<<JAVASCRIPT $(function() { $.ajax({ type: 'GET', url: '{$locales_path}', success: function(json) { i18n.loadJSON(json, '{$locale_domain}'); } }); }); JAVASCRIPT; } return Html::scriptBlock($script); } }
gpl-2.0
plesager/barakuda
python/exec/test_zoom_basin.py
516
#!/usr/bin/env python # B a r a K u d a # # L. Brodeau, 2017] import sys import numpy as nmp from netCDF4 import Dataset import barakuda_orca as bo narg = len(sys.argv) if narg != 3: print 'Usage: '+sys.argv[0]+' <basin_mask> <basin_name>'; sys.exit(0) cf_bm = sys.argv[1] cname = sys.argv[2] # Opening basin_mask: f_bm = Dataset(cf_bm) mask = f_bm.variables['tmask'+cname][:,:] f_bm.close() (i1,j1,i2,j2) = bo.shrink_domain(mask) print ' i1, i2 =>', i1, i2 print ' j1, j2 =>', j1, j2
gpl-2.0
napalm255/makeachangewithmarie.com
wp-content/themes/goodday/framework/postType/blog/post/sidebar/standard.php
2440
<?php /** * @package WordPress * @subpackage GoodDay * @version 1.0.0 * * Blog Post with Sidebar Standard Post Format Template * Created by CMSMasters * */ $cmsms_option = cmsms_get_global_options(); $cmsms_post_title = get_post_meta(get_the_ID(), 'cmsms_post_title', true); ?> <!--_________________________ Start Standard Article _________________________ --> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <?php if ($cmsms_post_title == 'true') { echo '<header class="cmsms_post_header entry-header">' . '<span class="cmsms_post_format_img cmsms-icon-desktop-3"></span>'; cmsms_post_title_nolink(get_the_ID(), 'h1'); echo '</header>'; } echo '<div class="cmsms_post_content entry-content">'; the_content(); wp_link_pages(array( 'before' => '<div class="subpage_nav" role="navigation">' . '<strong>' . __('Pages', 'cmsmasters') . ':</strong>', 'after' => '</div>', 'link_before' => ' [ ', 'link_after' => ' ] ' )); echo '<div class="cl"></div>' . '</div>'; if ( $cmsms_option[CMSMS_SHORTNAME . '_blog_post_date'] || $cmsms_option[CMSMS_SHORTNAME . '_blog_post_like'] || $cmsms_option[CMSMS_SHORTNAME . '_blog_post_comment'] || $cmsms_option[CMSMS_SHORTNAME . '_blog_post_author'] || $cmsms_option[CMSMS_SHORTNAME . '_blog_post_cat'] || $cmsms_option[CMSMS_SHORTNAME . '_blog_post_tag'] ) { echo '<footer class="cmsms_post_footer entry-meta">'; if ( $cmsms_option[CMSMS_SHORTNAME . '_blog_post_date'] || $cmsms_option[CMSMS_SHORTNAME . '_blog_post_like'] || $cmsms_option[CMSMS_SHORTNAME . '_blog_post_comment'] ) { echo '<div class="cmsms_post_meta_info">'; cmsms_post_date('post'); cmsms_post_like('post'); cmsms_post_comments('post'); echo '</div>'; } if ( $cmsms_option[CMSMS_SHORTNAME . '_blog_post_author'] || $cmsms_option[CMSMS_SHORTNAME . '_blog_post_cat'] || $cmsms_option[CMSMS_SHORTNAME . '_blog_post_tag'] ) { echo '<div class="cmsms_post_cont_info">'; cmsms_post_author('post'); cmsms_post_category('post'); cmsms_post_tags('post'); echo '</div>'; } echo '</footer>'; } ?> </article> <!--_________________________ Finish Standard Article _________________________ -->
gpl-2.0
wassemgtk/OpenX-using-S3-and-CloudFront
www/admin/userlog-audit-detailed.php
3572
<?php /* +---------------------------------------------------------------------------+ | OpenX v2.8 | | ========== | | | | Copyright (c) 2003-2009 OpenX Limited | | For contact details, see: http://www.openx.org/ | | | | 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 | +---------------------------------------------------------------------------+ $Id: userlog-audit-detailed.php 62345 2010-09-14 21:16:38Z chris.nutting $ */ // Require the initialisation file require_once '../../init.php'; // Required files require_once MAX_PATH . '/lib/OA/Dal.php'; require_once MAX_PATH . '/lib/OA/Dll/Audit.php'; require_once MAX_PATH . '/lib/OA/Admin/Template.php'; require_once MAX_PATH . '/www/admin/config.php'; // Register input variables $auditId = MAX_getStoredValue('auditId', 0); // Security check OA_Permission::enforceAccount(OA_ACCOUNT_ADMIN, OA_ACCOUNT_MANAGER, OA_ACCOUNT_ADVERTISER, OA_ACCOUNT_TRAFFICKER); OA_Permission::enforceAccountPermission(OA_ACCOUNT_ADVERTISER, OA_PERM_USER_LOG_ACCESS); OA_Permission::enforceAccountPermission(OA_ACCOUNT_TRAFFICKER, OA_PERM_USER_LOG_ACCESS); OA_Permission::enforceAccessToObject('audit', $auditId); /*-------------------------------------------------------*/ /* HTML framework */ /*-------------------------------------------------------*/ phpAds_PageHeader('userlog-index'); if (OA_Permission::isAccount(OA_ACCOUNT_ADMIN)) { // Show all "My Account" sections phpAds_ShowSections(array("5.1", "5.2", "5.3", "5.5", "5.6", "5.4")); phpAds_UserlogSelection("index"); } else if (OA_Permission::isAccount(OA_ACCOUNT_MANAGER)) { // Show the "Preferences", "User Log" and "Channel Management" sections of the "My Account" sections phpAds_ShowSections(array("5.1", "5.2", "5.4", "5.7")); } else if (OA_Permission::isAccount(OA_ACCOUNT_TRAFFICKER) || OA_Permission::isAccount(OA_ACCOUNT_ADVERTISER)) { phpAds_ShowSections(array("5.1", "5.2", "5.4")); } // initialize parameters $pageName = basename($_SERVER['SCRIPT_NAME']); $oTpl = new OA_Admin_Template('userlog-audit-detailed.html'); $oAudit = new OA_Dll_Audit(); $aAuditDetail = $oAudit->getAuditDetail($auditId); $oTpl->assign('aAuditDetail', $aAuditDetail); $oTpl->display(); phpAds_PageFooter(); ?>
gpl-2.0
Entkenntnis/Wyrmgus
src/sound/mikmod.cpp
6351
// _________ __ __ // / _____// |_____________ _/ |______ ____ __ __ ______ // \_____ \\ __\_ __ \__ \\ __\__ \ / ___\| | \/ ___/ // / \| | | | \// __ \| | / __ \_/ /_/ > | /\___ | // /_______ /|__| |__| (____ /__| (____ /\___ /|____//____ > // \/ \/ \//_____/ \/ // ______________________ ______________________ // T H E W A R B E G I N S // Stratagus - A free fantasy real time strategy game engine // /**@name mikmod.cpp - MikMod support */ // // (c) Copyright 2004-2005 by Nehal Mistry // // 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; only version 2 of the License. // // 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. // //@{ /*---------------------------------------------------------------------------- -- Includes ----------------------------------------------------------------------------*/ #include "stratagus.h" #ifdef USE_MIKMOD // { #include "sound.h" #include "sound_server.h" #include "iolib.h" #include <mikmod.h> /*---------------------------------------------------------------------------- -- Declarations ----------------------------------------------------------------------------*/ struct MikModData { MODULE *MikModModule; CFile *MikModFile; }; static CFile *CurrentFile; class CSampleMikMod : public CSample { public: ~CSampleMikMod(); int Read(void *buf, int len); MikModData Data; }; class CSampleMikModStream : public CSample { public: ~CSampleMikModStream(); int Read(void *buf, int len); MikModData Data; }; /*---------------------------------------------------------------------------- -- Functions ----------------------------------------------------------------------------*/ static BOOL Seek(struct MREADER *, long off, int whence) { return CurrentFile->seek(off, whence); } static long Tell(struct MREADER *) { return CurrentFile->tell(); } static BOOL Read(struct MREADER *, void *buf, size_t len) { return CurrentFile->read(buf, len); } static int Get(struct MREADER *) { char c; CurrentFile->read(&c, 1); return c; } static BOOL Eof(struct MREADER *) { return 0; } static MREADER MReader = { Seek, Tell, Read, Get, Eof }; /** ** Type member function to read from the module ** ** @param buf Buffer to write data to ** @param len Length of the buffer ** ** @return Number of bytes read */ int CSampleMikModStream::Read(void *buf, int len) { int read; // fill up the buffer read = 0; while (this->Len < SOUND_BUFFER_SIZE / 2 && Player_Active()) { memcpy(this->Buffer, this->Buffer + this->Pos, this->Len); this->Pos = 0; CurrentFile = this->Data.MikModFile; read = VC_WriteBytes((SBYTE *)this->Buffer + this->Pos, SOUND_BUFFER_SIZE - (this->Pos + this->Len)); this->Len += read; } if (this->Len < len) { // EOF len = this->Len; } memcpy(buf, this->Buffer + this->Pos, len); this->Len -= len; this->Pos += len; return len; } /** ** Type member function to free sample */ CSampleMikModStream::~CSampleMikModStream() { CurrentFile = this->Data.MikModFile; Player_Stop(); Player_Free(this->Data.MikModModule); MikMod_Exit(); this->Data.MikModFile->close(); delete this->Data.MikModFile; delete[] this->Buffer; } /** ** Type member function to read from the module ** ** @param buf Buffer to write data to ** @param len Length of the buffer ** ** @return Number of bytes read */ int CSampleMikMod::Read(void *buf, int len) { if (this->Len < len) { len = this->Len; } memcpy(buf, this->Buffer + this->Pos, len); this->Pos += len; this->Len -= len; return len; } /** ** Type member function to free sample */ CSampleMikMod::~CSampleMikMod() { delete[] this->Buffer; } /** ** Load MikMod. ** ** @param name Filename of the module. ** @param flags Unused. ** ** @return Returns the loaded sample. */ CSample *LoadMikMod(const char *name, int flags) { CSample *sample; MikModData *data; MODULE *module; CFile *f; char s[256]; static int registered = 0; md_mode |= DMODE_STEREO | DMODE_INTERP | DMODE_SURROUND | DMODE_HQMIXER; MikMod_RegisterDriver(&drv_nos); if (!registered) { MikMod_RegisterAllLoaders(); registered = 1; } strcpy_s(s, sizeof(s), name); f = new CFile; if (f->open(name, CL_OPEN_READ) == -1) { delete f; return NULL; } CurrentFile = f; MikMod_Init((char *)""); module = Player_LoadGeneric(&MReader, 64, 0); if (!module) { MikMod_Exit(); f->close(); delete f; return NULL; } if (flags & PlayAudioStream) { CSampleMikModStream *sampleMikModStream = new CSampleMikModStream; sample = sampleMikModStream; data = &sampleMikModStream->Data; } else { CSampleMikMod *sampleMikMod = new CSampleMikMod; sample = sampleMikMod; data = &sampleMikMod->Data; } data->MikModFile = f; data->MikModModule = module; sample->Channels = 2; sample->SampleSize = 16; sample->Frequency = 44100; sample->Pos = 0; //Wyrmgus start sample->File = name; //Wyrmgus end if (flags & PlayAudioStream) { sample->Len = 0; sample->Buffer = new unsigned char[SOUND_BUFFER_SIZE]; Player_Start(data->MikModModule); } else { int read; int pos; // FIXME: need to find the correct length sample->Len = 55000000; sample->Buffer = new unsigned char[sample->Len]; pos = 0; Player_Start(data->MikModModule); while (Player_Active()) { read = VC_WriteBytes((SBYTE *)sample->Buffer + pos, sample->Len - pos); pos += read; } Player_Stop(); Player_Free(data->MikModModule); MikMod_Exit(); data->MikModFile->close(); delete data->MikModFile; } return sample; } #endif // } USE_MIKMOD //@}
gpl-2.0
guanxiaohua/TransGC
src/share/vm/classfile/verificationType.cpp
5525
/* * Copyright 2003-2006 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. * */ # include "incls/_precompiled.incl" # include "incls/_verificationType.cpp.incl" VerificationType VerificationType::from_tag(u1 tag) { switch (tag) { case ITEM_Top: return bogus_type(); case ITEM_Integer: return integer_type(); case ITEM_Float: return float_type(); case ITEM_Double: return double_type(); case ITEM_Long: return long_type(); case ITEM_Null: return null_type(); default: ShouldNotReachHere(); return bogus_type(); } } bool VerificationType::is_reference_assignable_from( const VerificationType& from, instanceKlassHandle context, TRAPS) const { if (from.is_null()) { // null is assignable to any reference return true; } else if (is_null()) { return false; } else if (name() == from.name()) { return true; } else if (is_object()) { // We need check the class hierarchy to check assignability if (name() == vmSymbols::java_lang_Object()) { // any object or array is assignable to java.lang.Object return true; } klassOop this_class = SystemDictionary::resolve_or_fail( name_handle(), Handle(THREAD, context->class_loader()), Handle(THREAD, context->protection_domain()), true, CHECK_false); if (this_class->klass_part()->is_interface()) { // We treat interfaces as java.lang.Object, including // java.lang.Cloneable and java.io.Serializable return true; } else if (from.is_object()) { klassOop from_class = SystemDictionary::resolve_or_fail( from.name_handle(), Handle(THREAD, context->class_loader()), Handle(THREAD, context->protection_domain()), true, CHECK_false); return instanceKlass::cast(from_class)->is_subclass_of(this_class); } } else if (is_array() && from.is_array()) { VerificationType comp_this = get_component(CHECK_false); VerificationType comp_from = from.get_component(CHECK_false); return comp_this.is_assignable_from(comp_from, context, CHECK_false); } return false; } VerificationType VerificationType::get_component(TRAPS) const { assert(is_array() && name()->utf8_length() >= 2, "Must be a valid array"); symbolOop component; switch (name()->byte_at(1)) { case 'Z': return VerificationType(Boolean); case 'B': return VerificationType(Byte); case 'C': return VerificationType(Char); case 'S': return VerificationType(Short); case 'I': return VerificationType(Integer); case 'J': return VerificationType(Long); case 'F': return VerificationType(Float); case 'D': return VerificationType(Double); case '[': component = SymbolTable::lookup( name(), 1, name()->utf8_length(), CHECK_(VerificationType::bogus_type())); return VerificationType::reference_type(component); case 'L': component = SymbolTable::lookup( name(), 2, name()->utf8_length() - 1, CHECK_(VerificationType::bogus_type())); return VerificationType::reference_type(component); default: ShouldNotReachHere(); return VerificationType::bogus_type(); } } #ifndef PRODUCT void VerificationType::print_on(outputStream* st) const { switch (_u._data) { case Bogus: st->print(" bogus "); break; case Category1: st->print(" category1 "); break; case Category2: st->print(" category2 "); break; case Category2_2nd: st->print(" category2_2nd "); break; case Boolean: st->print(" boolean "); break; case Byte: st->print(" byte "); break; case Short: st->print(" short "); break; case Char: st->print(" char "); break; case Integer: st->print(" integer "); break; case Float: st->print(" float "); break; case Long: st->print(" long "); break; case Double: st->print(" double "); break; case Long_2nd: st->print(" long_2nd "); break; case Double_2nd: st->print(" double_2nd "); break; case Null: st->print(" null "); break; default: if (is_uninitialized_this()) { st->print(" uninitializedThis "); } else if (is_uninitialized()) { st->print(" uninitialized %d ", bci()); } else { st->print(" class %s ", name()->as_klass_external_name()); } } } #endif
gpl-2.0
jbachorik/btrace
btrace-dtrace/src/mock/java/org/opensolaris/os/dtrace/Program.java
60
package org.opensolaris.os.dtrace; public class Program {}
gpl-2.0
matijaskala/partitionmanager
src/jobs/setpartgeometryjob.cpp
3554
/*************************************************************************** * Copyright (C) 2008 by Volker Lanz <vl@fidra.de> * * * * 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 * ***************************************************************************/ #include "jobs/setpartgeometryjob.h" #include "backend/corebackend.h" #include "backend/corebackendmanager.h" #include "backend/corebackenddevice.h" #include "backend/corebackendpartitiontable.h" #include "core/partition.h" #include "core/device.h" #include "util/report.h" #include <kdebug.h> #include <klocale.h> /** Creates a new SetPartGeometryJob @param d the Device the Partition whose geometry is to be set is on @param p the Partition whose geometry is to be set @param newstart the new start sector for the Partition @param newlength the new length for the Partition @todo Wouldn't it be better to have newfirst (new first sector) and newlast (new last sector) as args instead? Having a length here doesn't seem to be very consistent with the rest of the app, right? */ SetPartGeometryJob::SetPartGeometryJob(Device& d, Partition& p, qint64 newstart, qint64 newlength) : Job(), m_Device(d), m_Partition(p), m_NewStart(newstart), m_NewLength(newlength) { } bool SetPartGeometryJob::run(Report& parent) { bool rval = false; Report* report = jobStarted(parent); CoreBackendDevice* backendDevice = CoreBackendManager::self()->backend()->openDevice(device().deviceNode()); if (backendDevice) { CoreBackendPartitionTable* backendPartitionTable = backendDevice->openPartitionTable(); if (backendPartitionTable) { rval = backendPartitionTable->updateGeometry(*report, partition(), newStart(), newStart() + newLength() - 1); if (rval) { partition().setFirstSector(newStart()); partition().setLastSector(newStart() + newLength() - 1); backendPartitionTable->commit(); } delete backendPartitionTable; } delete backendDevice; } else report->line() << i18nc("@info/plain", "Could not open device <filename>%1</filename> while trying to resize/move partition <filename>%2</filename>.", device().deviceNode(), partition().deviceNode()); jobFinished(*report, rval); return rval; } QString SetPartGeometryJob::description() const { return i18nc("@info/plain", "Set geometry of partition <filename>%1</filename>: Start sector: %2, length: %3", partition().deviceNode(), newStart(), newLength()); }
gpl-2.0
AndyPeterman/mrmc
xbmc/cores/dvdplayer/DVDStreamInfo.cpp
7082
/* * Copyright (C) 2005-2013 Team XBMC * http://xbmc.org * * 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, 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 XBMC; see the file COPYING. If not, see * <http://www.gnu.org/licenses/>. * */ #include "DVDStreamInfo.h" #include "DVDDemuxers/DVDDemux.h" CDVDStreamInfo::CDVDStreamInfo() { extradata = NULL; Clear(); } CDVDStreamInfo::CDVDStreamInfo(const CDVDStreamInfo &right, bool withextradata ) { extradata = NULL; Clear(); Assign(right, withextradata); } CDVDStreamInfo::CDVDStreamInfo(const CDemuxStream &right, bool withextradata ) { extradata = NULL; Clear(); Assign(right, withextradata); } CDVDStreamInfo::~CDVDStreamInfo() { if( extradata && extrasize ) free(extradata); extradata = NULL; extrasize = 0; } void CDVDStreamInfo::Clear() { codec = AV_CODEC_ID_NONE; type = STREAM_NONE; realtime = false; software = false; codec_tag = 0; flags = 0; filename.clear(); dvd = false; if( extradata && extrasize ) free(extradata); extradata = NULL; extrasize = 0; fpsscale = 0; fpsrate = 0; rfpsscale= 0; rfpsrate = 0; height = 0; width = 0; aspect = 0.0; vfr = false; stills = false; level = 0; profile = 0; ptsinvalid = false; forced_aspect = false; bitsperpixel = 0; colorspace = 0; colorrange = 0; colortransfer = 0; colorprimaries = 0; pid = 0; stereo_mode.clear(); maybe_interlaced = -1; channels = 0; samplerate = 0; blockalign = 0; bitrate = 0; bitspersample = 0; channellayout = 0; orientation = 0; } bool CDVDStreamInfo::Equal(const CDVDStreamInfo& right, bool withextradata) { if( codec != right.codec || type != right.type || realtime != right.realtime || codec_tag != right.codec_tag || flags != right.flags) return false; if( withextradata ) { if( extrasize != right.extrasize ) return false; if( extrasize ) { if( memcmp(extradata, right.extradata, extrasize) != 0 ) return false; } } // VIDEO if( fpsscale != right.fpsscale || fpsrate != right.fpsrate || rfpsscale!= right.rfpsscale || rfpsrate != right.rfpsrate || height != right.height || width != right.width || stills != right.stills || level != right.level || profile != right.profile || ptsinvalid != right.ptsinvalid || forced_aspect != right.forced_aspect || bitsperpixel != right.bitsperpixel || colorspace != right.colorspace || colorrange != right.colorrange || colortransfer != right.colortransfer || colorprimaries != right.colorprimaries || pid != right.pid || vfr != right.vfr || maybe_interlaced != right.maybe_interlaced || stereo_mode != right.stereo_mode ) return false; // AUDIO if( channels != right.channels || samplerate != right.samplerate || blockalign != right.blockalign || bitrate != right.bitrate || bitspersample != right.bitspersample || channellayout != right.channellayout) return false; // SUBTITLE return true; } bool CDVDStreamInfo::Equal(const CDemuxStream& right, bool withextradata) { CDVDStreamInfo info; info.Assign(right, withextradata); return Equal(info, withextradata); } // ASSIGNMENT void CDVDStreamInfo::Assign(const CDVDStreamInfo& right, bool withextradata) { codec = right.codec; type = right.type; realtime = right.realtime; codec_tag = right.codec_tag; flags = right.flags; filename = right.filename; dvd = right.dvd; if( extradata && extrasize ) free(extradata); if( withextradata && right.extrasize ) { extrasize = right.extrasize; extradata = malloc(extrasize); if (!extradata) return; memcpy(extradata, right.extradata, extrasize); } else { extrasize = 0; extradata = 0; } // VIDEO fpsscale = right.fpsscale; fpsrate = right.fpsrate; rfpsscale= right.rfpsscale; rfpsrate = right.rfpsrate; height = right.height; width = right.width; aspect = right.aspect; stills = right.stills; level = right.level; profile = right.profile; ptsinvalid = right.ptsinvalid; forced_aspect = right.forced_aspect; orientation = right.orientation; bitsperpixel = right.bitsperpixel; colorspace = right.colorspace; colorrange = right.colorrange; colortransfer = right.colortransfer; colorprimaries = right.colorprimaries; pid = right.pid; vfr = right.vfr; software = right.software; stereo_mode = right.stereo_mode; // AUDIO channels = right.channels; samplerate = right.samplerate; blockalign = right.blockalign; bitrate = right.bitrate; bitspersample = right.bitspersample; channellayout = right.channellayout; // SUBTITLE } void CDVDStreamInfo::Assign(const CDemuxStream& right, bool withextradata) { Clear(); codec = right.codec; type = right.type; realtime = right.realtime; codec_tag = right.codec_fourcc; profile = right.profile; level = right.level; flags = right.flags; if( withextradata && right.ExtraSize ) { extrasize = right.ExtraSize; extradata = malloc(extrasize); if (!extradata) return; memcpy(extradata, right.ExtraData, extrasize); } if( right.type == STREAM_AUDIO ) { const CDemuxStreamAudio *stream = static_cast<const CDemuxStreamAudio*>(&right); channels = stream->iChannels; samplerate = stream->iSampleRate; blockalign = stream->iBlockAlign; bitrate = stream->iBitRate; bitspersample = stream->iBitsPerSample; channellayout = stream->iChannelLayout; } else if( right.type == STREAM_VIDEO ) { const CDemuxStreamVideo *stream = static_cast<const CDemuxStreamVideo*>(&right); fpsscale = stream->iFpsScale; fpsrate = stream->iFpsRate; rfpsscale = stream->irFpsScale; rfpsrate = stream->irFpsRate; height = stream->iHeight; width = stream->iWidth; aspect = stream->fAspect; vfr = stream->bVFR; ptsinvalid = stream->bPTSInvalid; forced_aspect = stream->bForcedAspect; orientation = stream->iOrientation; bitsperpixel = stream->iBitsPerPixel; colorspace = stream->iColorSpace; colorrange = stream->iColorRange; colortransfer = stream->iColorTransfer; colorprimaries = stream->iColorPrimaries; pid = stream->iPhysicalId; stereo_mode = stream->stereo_mode; maybe_interlaced = stream->bMaybeInterlaced > 0? 1:0; } else if( right.type == STREAM_SUBTITLE ) { } }
gpl-2.0
rxu/pages
tests/operators/page_operator_get_page_routes_test.php
1089
<?php /** * * Pages extension for the phpBB Forum Software package. * * @copyright (c) 2014 phpBB Limited <https://www.phpbb.com> * @license GNU General Public License, version 2 (GPL-2.0) * */ namespace phpbb\pages\tests\operators; class page_operator_get_page_routes_test extends page_operator_base { /** * Test data for the test_get_routes() function * * @return array Array of test routes */ public function get_routes_test_data() { return array( array( array( 1 => array('route' => 'page_1', 'title' => 'title_1'), 2 => array('route' => 'page_2', 'title' => 'title_2'), 3 => array('route' => 'page_3', 'title' => 'title_3'), 4 => array('route' => 'page_4', 'title' => 'title_4'), ), ), ); } /** * Test getting page routes from the database * * @dataProvider get_routes_test_data */ public function test_get_routes($expected) { // Setup the operator class $operator = $this->get_page_operator(); // Grab the route data as an array $routes = $operator->get_page_routes(); $this->assertEquals($expected, $routes); } }
gpl-2.0
robalo/mods
asr_ai3/addons/incognito/script_component.hpp
132
#define COMPONENT incognito #include "\x\asr_ai3\addons\main\script_mod.hpp" #include "\x\asr_ai3\addons\main\script_macros.hpp"
gpl-2.0
seret/oxtebafu1org
ow_plugins/gphotoviewer/init.php
2604
<?php OW::getRouter()->addRoute(new OW_Route('gphotoviewer.photos_content', 'gphotoviewer/ajax/get-photos/', 'GPHOTOVIEWER_CTRL_Index', 'getPhotosContent')); OW::getRouter()->addRoute(new OW_Route('gphotoviewer.photos_comment', 'gphotoviewer/ajax/get-photo_comment/', 'GPHOTOVIEWER_CTRL_Index', 'getPhotosComment')); OW::getRouter()->addRoute(new OW_Route('gphotoviewer.photo_download', 'gphotoviewer/photo/download/:id/', 'GPHOTOVIEWER_CTRL_Index', 'download')); OW::getRouter()->addRoute(new OW_Route('gphotoviewer.admin_config', 'admin/gphotoviewer', 'GPHOTOVIEWER_CTRL_Admin', 'index')); $plugin = OW::getPluginManager()->getPlugin('gphotoviewer'); function photoviewer_script_render($event){ $configs = OW::getConfig()->getValues('gphotoviewer'); if(!$configs['enable_photo_viewer']) return; OW::getDocument()->addStyleSheet(OW::getPluginManager()->getPlugin('gphotoviewer')->getStaticCssUrl() . 'PhotoViewer.min.css'); OW::getDocument()->addStyleSheet(OW::getPluginManager()->getPlugin('gphotoviewer')->getStaticCssUrl() . 'font-awesome.css'); OW::getDocument()->addScript(OW::getPluginManager()->getPlugin('gphotoviewer')->getStaticJsUrl() . 'PhotoViewer.min.js'); OW::getLanguage()->addKeyForJs('gphotoviewer', 'from'); OW::getLanguage()->addKeyForJs('gphotoviewer', 'repeat'); OW::getLanguage()->addKeyForJs('gphotoviewer', 'pause'); OW::getLanguage()->addKeyForJs('gphotoviewer', 'play'); OW::getLanguage()->addKeyForJs('gphotoviewer', 'slideshow'); OW::getLanguage()->addKeyForJs('gphotoviewer', 'all_photos'); OW::getLanguage()->addKeyForJs('gphotoviewer', 'loading'); $slideshow_time = $configs['slideshow_time_per_a_photo']; if ($slideshow_time < 1 || $slideshow_time > 10){ // between 1 and 10 sec $slideshow_time = 3; } $slideshow_time = $slideshow_time * 1000; $urlPhoto = OW::getRouter()->urlForRoute('gphotoviewer.photos_content'); $urlComment = OW::getRouter()->urlForRoute('gphotoviewer.photos_comment'); $ajaxResponder = OW::getRouter()->urlFor('PHOTO_CTRL_Photo', 'ajaxResponder'); $content = <<<CONTENT $(window).ready(function (){ PhotoViewer.options.slideshow_time = {$slideshow_time}; PhotoViewer.options.urlPhoto = '{$urlPhoto}'; PhotoViewer.options.urlComment = '{$urlComment}'; PhotoViewer.options.ajaxResponder = '{$ajaxResponder}'; PhotoViewer.bindPhotoViewer(); window.wpViewerTimer = setInterval(function (){ PhotoViewer.bindPhotoViewer(); }, 3000); }); CONTENT; OW::getDocument()->addOnloadScript($content); } OW::getEventManager()->bind(OW_EventManager::ON_FINALIZE, 'photoviewer_script_render'); ?>
gpl-2.0
careshub/cc-salud-america
public/views/report-card.php
48798
<?php /** * Template tag for outputting the SA Leader Report. * * Community Commons Salud America * * @package Community_Commons_Salud_America * @author Yan Barnett * @license GPL-2.0+ * @link http://www.communitycommons.org * @copyright 2013 Community Commons */ /** * Generate Leader Report within the group. * * Output is accomplished via a template tag, for easy insertion in group pages. * * @since 1.8.0 * * @return string The html for the leader report */ function sa_report_card() { /* * Is there a geoid set? We determine whether to show the report or the county * selector based on this variable. */ $geoid = isset( $_GET['geoid'] ) ? $_GET['geoid'] : ''; if (strlen($geoid) != 12 || preg_match('/^05000US\d{5}/i', $geoid) == 0) $geoid = ''; $image_url = plugins_url('images/report-card/', dirname(__FILE__)); ?> <div class="content-row clear"> <?php if (! $geoid): ?> <h2 class="screamer sablue no-top-margin">See How Your Area Stacks Up in Obesity, Food Access, Physical Activity &amp; Equity</h2> <div style="float: right; font-size: 12px; font-style: italic; margin-left: 10px;"> <a href="?geoid=05000US08031" class="salud-report-card-link" title="See a sample Report Card"> <img src="<?php echo $image_url?>sample-report.png" height="100" /><br /> See a sample Report Card!</a> </div> <p > The <em>Salud America!</em> Salud Report Card highlights health issues in your county (vs. state + nation) with data, policy solutions, research, and stories so you can start and support healthy changes for Latino kids. </p> <div style="clear:both"></div> <div id="sa-report-selection" class="report-control-header clear"> <h3 class="screamer sagreen">Create a report for your area</h3> <div class="inset-contents"> <div id="select-county">Select your state and county to see your own report card:</div> <select id="state-list"> <option value="" selected>--- Select a State ---</option> </select> <select id="county-list"> <option value="" selected>--- Select a County ---</option> </select> <span id="report-wait-message">Preparing your report card, please wait...</span> </div> </div> <p><strong>How can you use it?</strong></p> <p>Let people know what health issues are important to you!</p> Email the link to: <ul> <li>Your local and state PTA</li> <li>Your county and city health department</li> <li>Your friends, family, teachers</li> </ul> Print the report and hand it to: <ul> <li>Your city and school leaders</li> </ul> Share the report: <ul> <li>On social media</li> <li>With your neighborhood association, town halls, public health departments</li> </ul> <p><strong>You know the issues...now start a change!</strong></p> <p>Want to solve one of these health issues?</p> <p> <a href="<?php echo sa_get_group_permalink(); ?>">Log in to our website</a> and use our research, which suggests lots of achievable healthy changes, or our many posts about policy changes happening now. Or follow the footsteps of Salud Heroes and how they made change, like opening locked playgrounds after school hours! </p> <p><strong>Get help</strong></p> <p> Email our Salud America! digital curators, Eric, Lisa, and Amanda at <a href="mailto:saludamerica@uthscsa.edua">saludamerica@uthscsa.edu</a>. They can answer questions and help you access information and data/maps on many other topics. </p> <?php else: // Generate the report. $group_url = bp_get_group_permalink(); $plugin_base_url = sa_get_plugin_base_uri(); // Fetch big bet terms. $big_bets_base_url = sa_get_section_permalink( 'big_bets' ); $big_bets = get_terms( 'sa_advocacy_targets', array( 'hide_empty' => 0, 'exclude' => array( 74550, 74551, 74552 ), ) ); // get county FIPS code $fips = preg_replace("/[^',]*US/i", '', $geoid); // get data for cover page $cover_page = sa_report_cover_page($fips); $report_area = $cover_page->county_name . ', ' . $cover_page->state_name; // in case of District of Columbia if ($cover_page->county_name === $cover_page->state_name) $report_area = $cover_page->county_name; // get data for obesity page $obesity_page = sa_report_obesity_page($fips); // get data for fast food page $fast_food_page = sa_report_food_access_page($fips); // get data for physical activity page $physical_activity_page = sa_report_physical_activity_page($fips); // get data for health equity page $health_equity_page = sa_report_health_equity_page($fips); // get data for vulnerable population page $vulnerable_population_page = sa_report_vulnerable_population_page($geoid); // add share and mailto links $share_title_twitter = 'Check out this @SaludToday Report Card on Latino health for ' . $report_area; $share_title = 'Check out this Salud Report Card on Latino health for ' . $report_area; $share_url = ( is_ssl() ? 'https://' : 'http://' ) . $_SERVER["HTTP_HOST"] . $_SERVER['REQUEST_URI']; $mail_to = '?subject=Check Out Latino Health in ' . $report_area . '&body=' . $share_title . ': ' . $share_url; ?> <style> /* only apply to screen, not PDF */ @media screen and (max-width: 800px) { #sa-report-content #sa-vulnerable-map{ margin-bottom: 20px; } #sa-report-content #sa-vulnerable-sidebar { clear: left; padding: 0; margin: 0 auto; } } @media only screen { #sa-report-content .page-break { margin-top: 40px; } } </style> <div id="sa-report-action-top" class="sa-report-action"> <input type="button" class="button salud-report-card-link" value="Email Report" onclick="document.location='mailto:<?php echo $mail_to ?>';" title="Email it"/> <input type="button" class="button sa-report-export" id="sa-report-export-top" value="Export Report to PDF" /> <?php if ( current_user_can( 'bp_docs_associate_with_group', sa_get_group_id() ) ) : ?> <input type="button" class="button sa-report-save" id="sa-report-save-top" value="Save Report to My Library" /> <?php endif; ?> <div id="report-save-message-top" class="report-save-message">Saving your report card, please wait...</div> </div> <hr /> <div id="sa-report-content"> <div id="cover-page"> <table class="sa-report-cols"><tr> <td class="col3"><img src="<?php echo $image_url?>logo-salud.png" width="70" /></td> <td class="col3 center-align"><?php echo date("F, Y") ?></td> <td class="col3 right-align"><img src="<?php echo $image_url?>logo-rwjf.png" width="120" /></td> </tr></table> <div class="sa-report-title sa-report-font-2"> <p>your very own <b>Salud Report Card</b> for</p> <p class="sa-report-font-large"><?php echo $report_area ?></p> </div> <p class="center-align sa-report-font-2">1 of 3 U.S. public school students will be <span class="sa-text-orange">Latino</span> by 2024. <sup>1</sup></p> <div class="center-align"><img src="<?php echo $image_url?>three-figures.png" width="120" /></div> <div class="sa-report-spacing1"></div> <div class="center-align sa-report-font-3"><img src="<?php echo $image_url?>check.png" width="50" /> In <?php echo $cover_page->county_name ?> today,</div> <div class="center-align sa-text-orange sa-report-font-3"><?php echo $cover_page->frac_latino_adults ?> adults (<?php echo $cover_page->pct_latino_adults ?>) and</div> <div class="center-align sa-text-orange sa-report-font-3"><?php echo $cover_page->frac_latino_kids ?> kids (<?php echo $cover_page->pct_latino_kids ?>) are Latino<sup>2</sup></div> <div class="center-align sa-report-font-3">...and it ranks <?php echo $cover_page->health_ranking ?><sup><?php echo $cover_page->health_ranking_suffix ?></sup> of <?php echo $cover_page->health_ranking_total ?> counties</div> <div class="center-align sa-report-font-3">in health outcomes.<sup>3</sup></div> <div class="sa-report-spacing2"></div> <div class="center-align sa-text-green sa-report-font-3">This <i>Salud America!</i> Salud Report Card</div> <div class="center-align sa-report-font-2">highlights health issues in your county (vs. state + nation) with</div> <div class="center-align sa-report-font-2 sa-report-icons"> <span><img src="<?php echo $image_url?>icon-data.png" />DATA</span> <span><img src="<?php echo $image_url?>icon-policy.png" />POLICY SOLUTIONS</span> <span><img src="<?php echo $image_url?>icon-research.png" />RESEARCH</span> <span><img src="<?php echo $image_url?>icon-stories.png" />STORIES</span> </div> <div class="center-align sa-report-font-2">so you can start and support healthy changes in these areas:</div> <div class="center-align sa-report-changes"> <?php foreach ( $big_bets as $term ) { ?> <a href="<?php echo $big_bets_base_url . $term->slug; ?>" class="big-bet-icon-link" title="Link to Big Bet archive: <?php echo $term->name; ?>"><img src="<?php echo $plugin_base_url . 'public/images/big_bets/icons-with-titles/' . $term->slug . '-112x150.png' ?>" alt="Icon for Big Bet: <?php echo $term->name; ?>" class="big-bet-icon" /></a> <?php } ?> </div> <div class="page-break"></div> </div> <div id="obesity-page"> <table class="sa-report-page-header sa-background-darkgray"><tr> <td class="sa-img"> <a href="<?php echo sa_get_section_permalink( 'big-bets' ); ?>sa-healthy-weight" class="salud-report-card-link" title="Link to Big Bet archive: Healthy Weight"> <img src="<?php echo $plugin_base_url . 'public/images/big_bets/icons-with-titles/sa-healthy-weight-112x150.png' ?>" alt="Icon for Big Bet: Healthier Weight" class="big-bet-icon" /></a> </td> <td class="sa-page-title"> <div class="sa-report-font-4">Obesity</div> <p>More U.S. Latino kids are obese by age 5 than whites, due to maternal obesity, less breastfeeding, and workplace/childcare issues.</p> <a href="<?php echo sa_get_section_permalink( 'big-bets' ); ?>sa-healthy-weight/" target="_blank" class="learn-more-link" title="Learn more about obesity"> Learn More</a> </td> </tr> </table> <p>In <span class="sa-text-orange sa-text-capital">THE UNITED STATES OVERALL</span>, nearly 40% of U.S. Latino youths ages 2-19 are overweight or obese, compared with only 28.5% of non-Latino white youths.</p> <p>In <span class="sa-text-capital sa-text-pink"><?php echo $cover_page->state_name ?> OVERALL</span>, <?php echo $obesity_page->pct_latino_obese ?> of Latino children ages 10-17 are overweight or obese, compared with <?php echo $obesity_page->pct_white_obese ?> of non-Latino white children.<sup>4</sup></p> <p>In <span class="sa-text-capital sa-text-green"><?php echo $cover_page->county_name ?> OVERALL</span>, <?php echo $obesity_page->pct_obese ?> of all adults aged 20 and older self-report that they have a Body Mass Index (BMI; a measure of body fat based on height and weight) greater than 30.0 (obese).<sup>5</sup> <?php if ($obesity_page->pct_overweight != -1): ?> <?php echo $obesity_page->pct_overweight ?> of all adults aged 18 and older self-report that they have a Body Mass Index (BMI) between 25.0 and 30.0 (overweight). <?php else: ?> The overweight indicator measures percent of all adults aged 18 and older who self-report that they have a Body Mass Index (BMI) between 25.0 and 30.0 (overweight). Due to small number of survey respondents, county-level results are not available. <?php endif ?> <sup>5</sup> </p> <div class="sa-report-spacing1"></div> <div class="w3-row"> <div class="w3-half"> <?php echo $obesity_page->dial_obese ?> </div> <div class="w3-half"> <?php echo $obesity_page->dial_overweight ?> </div> </div> <div class="sa-report-spacing2"></div> <div class="w3-row"> <div class="w3-third sa-col-end sa-col-media center-align"> <a href="https://youtu.be/3yFOgZ2ku6k" target="_blank" class="center-align salud-report-card-link" title="Policy solutions: obesity"> <img src="<?php echo $image_url?>icon-policy.png" height="52" /><br /> <p class="sa-report-font-2">Policy<br />Solutions</p> <p><img src="<?php echo $image_url?>obesity-policy.jpg" /></p> </a> </div> <div class="w3-third sa-col-middle sa-col-media center-align"> <a href="<?php echo sa_get_section_permalink( 'big-bets' ); ?>sa-healthy-weight/" target="_blank" class="center-align salud-report-card-link" title="Research and infographics: obesity"> <img src="<?php echo $image_url?>icon-research.png" height="52" /><br /> <p class="sa-report-font-2">Research <br />and Infographics</p> <p><img src="<?php echo $image_url?>obesity-research.jpg" /></p> </a> </div> <div class="w3-third sa-col-end sa-col-media center-align"> <a href="<?php echo sa_get_section_permalink( 'heroes' ); ?>baby-cafe-opens-to-bring-breastfeeding-peer-counselors-to-san-antonio-mothers/" target="_blank" class="center-align salud-report-card-link" title="Salud heroes: obesity"> <img src="<?php echo $image_url?>icon-stories.png" height="52" /><br /> <p class="sa-report-font-2">Salud Heroes: How to Start a Baby Cafe</p> <p><img src="<?php echo $image_url?>obesity-stories.jpg" /></p> </a> </div> </div> <div class="page-break"></div> </div> <div id="food-access-page"> <table class="sa-report-page-header sa-background-darkgray"><tr> <td class="sa-img"> <a href="<?php echo sa_get_section_permalink( 'big-bets' ); ?>sa-better-food-in-neighborhoods" class="salud-report-card-link" title="Link to Big Bet archive: Better Food in Neighborhoods"> <img src="<?php echo $plugin_base_url . 'public/images/big_bets/icons-with-titles/sa-better-food-in-neighborhoods-112x150.png' ?>" alt="Icon for Big Bet: Better Food in the Neighborhood" class="big-bet-icon" /></a> <a href="<?php echo sa_get_section_permalink( 'big-bets' ); ?>sa-sugary-drinks" class="salud-report-card-link" title="Link to Big Bet archive: Sugary Drinks"> <img src="<?php echo $plugin_base_url . 'public/images/big_bets/icons-with-titles/sa-sugary-drinks-112x150.png' ?>" alt="Icon for Big Bet: Sugary Drinks" class="big-bet-icon" /></a> </td> <td class="sa-page-title"> <div class="sa-report-font-4">Food Access</div> <p>U.S. Latino kids face unhealthy neighborhood food environments with fewer grocery stores and more fast food.</p> <a href="<?php echo sa_get_section_permalink( 'big-bets' ); ?>sa-better-food-in-neighborhoods/" target="_blank" class="learn-more-link" title="Learn more about food access"> Learn More</a> </td> </tr> </table> <div class="w3-row"> <div class="w3-third sa-col-1"> <div class="sa-report-indicator-food"> <p><span class="sa-report-indicator-title">Fast Food Restaurant Access</span> <sup>6</sup></p> <p>This indicator reports the number of fast food restaurants per 100,000 people in <span class="sa-text-green sa-text-capital"><?php echo $cover_page->county_name ?> OVERALL</span>. This indicator is relevant because it measures environmental influences on dietary behaviors.</p> </div> <?php echo $fast_food_page->dial_fast_food ?> </div> <div class="w3-third sa-col-2"> <div class="sa-report-indicator-food"> <p><span class="sa-report-indicator-title">Grocery Store Access</span> <sup>6</sup></p> <p>This indicator reports the number of grocery stores per 100,000 people in <span class="sa-text-green sa-text-capital"><?php echo $cover_page->county_name ?> OVERALL</span>. This indicator is relevant because it provides a measure of healthy food access in a community.</p> </div> <?php echo $fast_food_page->dial_grocery ?> </div> <div class="w3-third sa-col-3"> <div class="sa-report-indicator-food"> <p><span class="sa-report-indicator-title">Fruit/Veggie Consumption</span> <sup>7</sup></p> <p> <?php if ($fast_food_page->total_fruit != -1): ?> In <span class="sa-text-green sa-text-capital"><?php echo $cover_page->county_name ?> OVERALL</span>, <?php echo $fast_food_page->total_fruit ?>, or <?php echo $fast_food_page->pct_fruit ?> of adults over the age of 18 are consuming less than 5 servings of fruits and vegetables each day. <?php else: ?> This indicator reports the percent of adults over the age of 18 who are consuming less than 5 servings of fruits and vegetables each day. Due to small number of survey respondents, results in <span class="sa-text-green sa-text-capital"><?php echo $cover_page->county_name ?> OVERALL</span> are not available. <?php endif; ?> This indicator is relevant because unhealthy eating may cause health issues.</p> </div> <?php echo $fast_food_page->dial_fruit ?> </div> </div> <div class="sa-report-spacing2"></div> <div class="w3-row"> <div class="w3-third sa-col-end sa-col-media center-align"> <a href="https://youtu.be/WLoZrkIAZT8" target="_blank" class="salud-report-card-link" title="Policy solutions: food access"> <img src="<?php echo $image_url?>icon-policy.png" height="52" /><br /> <p class="sa-report-font-2">Policy<br />Solutions</p> <p><img src="<?php echo $image_url?>food-policy.jpg" /></p> </a> </div> <div class="w3-third sa-col-middle sa-col-media center-align"> <a href="<?php echo sa_get_section_permalink( 'big-bets' ); ?>sa-better-food-in-neighborhoods/" target="_blank" class="salud-report-card-link" title="Research and infographics: food access"> <img src="<?php echo $image_url?>icon-research.png" height="52" /><br /> <p class="sa-report-font-2">Research <br />and Infographics</p> <p><img src="<?php echo $image_url?>food-research.jpg" /></p> </a> </div> <div class="w3-third sa-col-end sa-col-media center-align"> <a href="<?php echo sa_get_section_permalink( 'heroes' ); ?>dignowity-hill-farmers-market/" target="_blank" class="salud-report-card-link" title="Salud heroes: food access"> <img src="<?php echo $image_url?>icon-stories.png" height="52" /><br /> <p class="sa-report-font-2">Salud Heroes: How to Start a Farmers Market</p> <p><img src="<?php echo $image_url?>food-stories.jpg" /></p> </a> </div> </div> <div class="page-break"></div> </div> <div id="physical-activity-issues-page"> <table class="sa-report-page-header sa-background-darkgray"><tr> <td class="sa-img"> <a href="<?php echo sa_get_section_permalink( 'big-bets' ); ?>sa-active-spaces" class="salud-report-card-link" title="Link to Big Bet archive: Active Spaces"> <img src="<?php echo $plugin_base_url . 'public/images/big_bets/icons-with-titles/sa-active-spaces-112x150.png' ?>" alt="Icon for Big Bet: Active Spaces" class="big-bet-icon" /></a> </td> <td class="sa-page-title"> <div class="sa-report-font-4">Physical Activity Issues</div> <p>Latino children and adults face less access to recreational facilities and lower activity rates. </p> <a href="<?php echo sa_get_section_permalink( 'big-bets' ); ?>sa-active-spaces/" target="_blank" class="learn-more-link" title="Learn more about physical activity issues">Learn More</a> </td> </tr> </table> <div class="w3-row"> <div class="w3-third sa-col-1"> <div class="sa-report-indicator-physical"> <p><span class="sa-report-indicator-title">Recreation and Fitness Facility Access</span> <sup>8</sup></p> <p>This indicator reports the number per 100,000 population of recreation facilities in <span class="sa-text-green sa-text-capital"><?php echo $cover_page->county_name ?> OVERALL</span>. This indicator is relevant because access to recreation facilities encourages physical activity and healthy behaviors.</p> </div> <?php echo $physical_activity_page->dial_recreation ?> </div> <div class="w3-third sa-col-1"> <div class="sa-report-indicator-physical"> <p><span class="sa-report-indicator-title">Physical Inactivity</span> <sup>6</sup></p> <p>In <span class="sa-text-green sa-text-capital"><?php echo $cover_page->county_name ?> OVERALL</span>, <?php echo $physical_activity_page->total_physical?> or <?php echo $physical_activity_page->pct_physical?> of adults aged 20+ self-report no leisure time for activity, based on the question: "During the past month, other than your regular job, did you participate in any physical activities or exercises such as running, calisthenics, golf, gardening, or walking for exercise?"</p> </div> <?php echo $physical_activity_page->dial_physical ?> </div> <div class="w3-third sa-col-1"> <div class="sa-report-indicator-physical"> <p><span class="sa-report-indicator-title">Pedestrian-Motor Vehicle Accidents</span> <sup>7</sup></p> <p><span class="sa-text-green sa-text-capital"><?php echo $cover_page->county_name ?> OVERALL</span> had 50 pedestrian deaths from 2011-13. This indicator shows the pedestrian deaths by motor vehicles per 100,000 people. These preventable deaths may be associated with a lack of safe routes (sidewalks, crosswalks, walkable spaces) and narrow traffic lanes/roads. </p> </div> <?php echo $physical_activity_page->dial_pedestrian ?> </div> </div> <div class="sa-report-spacing2"></div> <div class="w3-row"> <div class="w3-third sa-col-end sa-col-media center-align"> <a href="https://youtu.be/CJfaMmsCzNo" target="_blank" class="salud-report-card-link" title="Policy solutions: physical activity issues"> <img src="<?php echo $image_url?>icon-policy.png" height="52" /><br /> <p class="sa-report-font-2">Policy<br />Solutions</p> <p><img src="<?php echo $image_url?>physical-policy.jpg" /></p> </a> </div> <div class="w3-third sa-col-middle sa-col-media center-align"> <a href="<?php echo sa_get_section_permalink( 'big-bets' ); ?>sa-active-spaces/" target="_blank" class="salud-report-card-link" title="Research and infographics: physical activity issues"> <img src="<?php echo $image_url?>icon-research.png" height="52" /><br /> <p class="sa-report-font-2">Research <br />and Infographics</p> <p><img src="<?php echo $image_url?>physical-research.jpg" /></p> </a> </div> <div class="w3-third sa-col-end sa-col-media center-align"> <a href="<?php echo sa_get_section_permalink( 'heroes' ); ?>move-el-paso-walking-trails-encourage-local-residents-to-get-up-get-walking/" target="_blank" class="salud-report-card-link" title="Salud heroes: physical activity issues"> <img src="<?php echo $image_url?>icon-stories.png" height="52" /><br /> <p class="sa-report-font-2">Salud Heroes: How to Start Local Trails</p> <p><img src="<?php echo $image_url?>physical-stories.jpg" /></p> </a> </div> </div> <div class="page-break"></div> </div> <div id="health-equity-page"> <table class="sa-report-page-header sa-background-darkgray"><tr> <td class="sa-img"> <a href="<?php echo sa_get_section_permalink( 'big-bets' ); ?>sa-health-equity" class="salud-report-card-link" title="Link to Big Bet archive: Health Equity"> <img src="<?php echo $plugin_base_url . 'public/images/big_bets/icons-with-titles/sa-health-equity-112x150.png' ?>" alt="Icon for Big Bet: Health Equity" class="big-bet-icon" /></a> </td> <td class="sa-page-title"> <div class="sa-report-font-4">Health Equity</div> <p>Latino families face inequities in educational attainment, income, residential segregation, access to care, and more.</p> <a href="<?php echo sa_get_section_permalink( 'big-bets' ); ?>sa-health-equity/" target="_blank" class="learn-more-link" title="Learn more about health equity">Learn More</a> </td> </tr> </table> <div class="w3-row"> <div class="w3-third sa-col-1"> <div class="sa-report-indicator-health"> <p><span class="sa-report-indicator-title">Children in Poverty</span> <sup>2</sup></p> <p>In <span class="sa-text-green sa-text-capital"><?php echo $cover_page->county_name ?> OVERALL</span>, <?php echo $health_equity_page->pct_poverty ?> or <?php echo $health_equity_page->total_poverty ?> children 0-17 live in households with income below the Federal Poverty Level (FPL). Poverty creates barriers to access of health services, healthy food, and other necessities that contribute to poor health status.</p> </div> <?php echo $health_equity_page->dial_poverty ?> </div> <div class="w3-third sa-col-1"> <div class="sa-report-indicator-health"> <p><span class="sa-report-indicator-title">Access to Primary Care</span> <sup>11</sup></p> <p>This indicator reports the number of primary care physicians per 100,000 population in <span class="sa-text-green sa-text-capital"><?php echo $cover_page->county_name ?> OVERALL</span>. Having a usual primary care provider is linked to a higher likelihood of appropriate care (and thus better health outcomes). </p> </div> <?php echo $health_equity_page->dial_primary_care ?> </div> <div class="w3-third sa-col-1"> <div class="sa-report-indicator-health"> <p><span class="sa-report-indicator-title">% with No Health Insurance</span> <sup>2</sup></p> <p>This indicator reports the percentage of the total civilian non-institutionalized population without health insurance coverage in <span class="sa-text-green sa-text-capital"><?php echo $cover_page->county_name ?> OVERALL</span>. Lack of health insurance is considered a key driver of health status.</p> </div> <?php echo $health_equity_page->dial_insurance ?> </div> </div> <div class="sa-report-spacing2"></div> <div class="center-align sa-report-font-2"><u>Socio-economic Barriers for <span class="sa-text-capital sa-text-green"><?php echo $cover_page->county_name ?></span> <span class="sa-text-orange">Latinos</span></u> <sup>2</sup> </div> <table class="sa-report-sociobarriers"> <tr> <td></td> <td>% among <span class="sa-text-orange">Latino</span> Population</td> <td>% among Non-Latino Population</td> </tr> <tr class="sa-background-gray"><td colspan="3"><b>No High School Diploma</b></td></tr> <tr> <td class="sa-report-sociobarriers-area"><?php echo $cover_page->county_name ?></td> <td class="sa-text-orange sa-text-bold"><?php echo $health_equity_page->pct_latino_hs1 ?></td> <td class="sa-text-bold"><?php echo $health_equity_page->pct_nonlatino_hs1 ?></td> </tr> <tr class="sa-background-gray"> <td class="sa-report-sociobarriers-area"><?php echo $cover_page->state_name ?></td> <td class="sa-text-orange sa-text-bold"><?php echo $health_equity_page->pct_latino_hs2 ?></td> <td class="sa-text-bold"><?php echo $health_equity_page->pct_nonlatino_hs2 ?></td> </tr> <tr> <td class="sa-report-sociobarriers-area">United States</td> <td class="sa-text-orange sa-text-bold"><?php echo $health_equity_page->pct_latino_hs3 ?></td> <td class="sa-text-bold"><?php echo $health_equity_page->pct_nonlatino_hs3 ?></td> </tr> <tr class="sa-background-gray"><td colspan="3"><b>Children in Poverty</b></td></tr> <tr> <td class="sa-report-sociobarriers-area"><?php echo $cover_page->county_name ?></td> <td class="sa-text-orange sa-text-bold"><?php echo $health_equity_page->pct_latino_pov1 ?></td> <td class="sa-text-bold"><?php echo $health_equity_page->pct_nonlatino_pov1 ?></td> </tr> <tr class="sa-background-gray"> <td class="sa-report-sociobarriers-area"><?php echo $cover_page->state_name ?></td> <td class="sa-text-orange sa-text-bold"><?php echo $health_equity_page->pct_latino_pov2 ?></td> <td class="sa-text-bold"><?php echo $health_equity_page->pct_nonlatino_pov2 ?></td> </tr> <tr> <td class="sa-report-sociobarriers-area">United States</td> <td class="sa-text-orange sa-text-bold"><?php echo $health_equity_page->pct_latino_pov3 ?></td> <td class="sa-text-bold"><?php echo $health_equity_page->pct_nonlatino_pov3 ?></td> </tr> <tr class="sa-background-gray"><td colspan="3"><b>Uninsured</b></td></tr> <tr> <td class="sa-report-sociobarriers-area"><?php echo $cover_page->county_name ?></td> <td class="sa-text-orange sa-text-bold"><?php echo $health_equity_page->pct_latino_ins1 ?></td> <td class="sa-text-bold"><?php echo $health_equity_page->pct_nonlatino_ins1 ?></td> </tr> <tr class="sa-background-gray"> <td class="sa-report-sociobarriers-area"><?php echo $cover_page->state_name ?></td> <td class="sa-text-orange sa-text-bold"><?php echo $health_equity_page->pct_latino_ins2 ?></td> <td class="sa-text-bold"><?php echo $health_equity_page->pct_nonlatino_ins2 ?></td> </tr> <tr> <td class="sa-report-sociobarriers-area">United States</td> <td class="sa-text-orange sa-text-bold"><?php echo $health_equity_page->pct_latino_ins3 ?></td> <td class="sa-text-bold"><?php echo $health_equity_page->pct_nonlatino_ins3 ?></td> </tr> </table> <div class="page-break"></div> </div> <?php if ($vulnerable_population_page->pct_white != -1) :?> <div id="vulnerable-population-page"> <div class="sa-report-page-header"> <div class="float-left"> <img src="<?php echo $image_url?>vulnerable-population.jpg" width="210" /> </div> <div class="sa-vulnerable-header sa-page-title"> <div class="sa-report-font-4">Vulnerable Populations</div> <p>"Vulnerable populations" are those with over 20% of the population living below the poverty level AND over 25% of the population with less than high school education-two indicators that are primary social determinants of population health. </p> </div> </div> <p>In <span class="sa-text-green sa-text-capital"><?php echo $cover_page->county_name ?> OVERALL</span>, Latinos comprise <?php echo $vulnerable_population_page->pct_latino ?> of the entire vulnerable population (who are in both poverty and have less than a high school educational attainment), compared to non-Latino whites who comprise <?php echo $vulnerable_population_page->pct_white ?> of the entire vulnerable population.<sup>2</sup> The map below shows the vulnerable population in red. </p> <div class="w3-row"> <div id="sa-vulnerable-map" class="w3-threequarter"><?php echo $vulnerable_population_page->map ?></div> <div id="sa-vulnerable-sidebar" class="w3-rest"> <div id="sa-vulnerable-maplegend"> <p><b>Vulnerable Populations Footprint</b> <sup>2</sup></p> <div class="sa-vulnerable-map-legend"><span style="background: #A32A00; border: 1px solid #7F0400"></span>Above all thresholds (Footprint)</div> <div class="sa-vulnerable-map-legend"><span style="background: #F09432; border: 1px solid #D17615"></span>Population living below poverty: >= 20%</div> <div class="sa-vulnerable-map-legend"><span style="background: #9D6EBA; border: 1px solid #80509C"></span>Populaton with below high school attainment: >= 25%</div> </div> <div id="sa-vulnerable-contact"> <p style="color: #f00">Like maps?</p> <p>Want to know where the parks are in your county? The farmer's markets? The hospitals? </p> <p><a href="mailto:saludamerica@uthscsa.edu?Subject=Creating Maps">Email us</a> and we can help you create a map of almost anything in your area, for you to show to decision-makers!</p> </div> </div> </div> <div class="page-break"></div> </div> <?php endif ?> <div id="reference-page"> <div class="sa-report-page-header"></div> <div class="center-align sa-report-font-3"><p>You know the issues. Now what?</p></div> <div class="center-align sa-report-font-large sa-text-orange"> <div><img src="<?php echo $image_url?>icon-share.png" width="35" /> Share This Report!</div> </div> <div class="sa-report-font-2"> <a href="mailto:<?php echo $mail_to ?>" class="salud-report-card-link" title="Email it">Email this report to colleagues</a>; share it to start discussions on <a href="http://www.facebook.com/sharer.php?t=<?php echo $share_title ?>&u=<?php echo $share_url ?>" class="salud-report-card-link" title="Share on Facebook" target="_blank">Facebook</a> and <a href="http://twitter.com/share?text=<?php echo $share_title_twitter ?>&url=<?php echo $share_url ?>" class="salud-report-card-link" title="Share on Twitter" target="_blank">Twitter</a>, or at the PTA, etc.; and bring it to city/school leaders to spur change.</div> <div class="sa-report-spacing1"></div> <div class="center-align sa-report-font-large sa-text-orange"><p>Start (or Support) a Change!</p></div> <div class="sa-list"> <p class="sa-report-font-2">1. <a href="<?php echo $group_url; ?>report-card/share-your-story/" class="salud-report-card-link" title="Share your story" target="_blank">Start a change and share it with us</a>. We might write it up, film it, promote it nationally, and move you from Leader to Hero!</p> <p class="sa-report-font-2">2. <a href="http://maps.communitycommons.org/policymap/?bbox=<?php echo $vulnerable_population_page->bbox ?>" class="salud-report-card-link" title="Use policy map" target="_blank"> Use our map</a> to connect with Salud Leaders who you can ask to support your change, or find changes you can support!</p> <p class="sa-report-font-2">3. Gather support from others by <a href="<?php echo $group_url ?>forum/" class="salud-report-card-link" title="Start a forum" target="_blank">starting your own forum for discussion on the SA! Hub</a>.</p> </div> <p></p> <div class="center-align sa-report-font-3"><p>Need more data first?</p></div> <p>Email our <i>Salud America!</i> digital curators, <a href="<?php echo bp_core_get_userlink( bp_core_get_userid( 'amfitness' ), false, true ); ?>" target="_blank">Amanda</a>, <a href="<?php echo bp_core_get_userlink( bp_core_get_userid( 'lveraza' ), false, true ); ?>" target="_blank">Lisa</a> and <a href="<?php echo bp_core_get_userlink( bp_core_get_userid( 'ericmoreno77' ), false, true ); ?>" target="_blank">Eric</a>, who can answer questions and help you access information, data and maps on many other topics. </p> <div id="sa-reference"> <p><b>References</b></p> <p>Note: Data in this Salud Report Card was selected by <i>Salud America!</i> curators from several data and mapping tools available on the Community Commons website, including the <a href="<?php echo get_site_url( null, 'chna' ); ?>" target="_blank">Community Health Needs Assessment</a> and the <a href="http://assessment.communitycommons.org/Footprint/" target="_blank">Vulnerable Populations Footprint</a> tools. Contact our curator team at <a href="mailto:saludamerica@uthscsa.edu">saludamerica@uthscsa.edu</a> for a full report or more tailored data. </p> <div class="sa-list"> <p>1. National Center for Education Statistics. <a href="http://nces.ed.gov/programs/coe/indicator_cge.asp" target="_blank">http://nces.ed.gov/programs/coe/indicator_cge.asp</a>. </p> <p>2. U.S. Census Bureau. American Community Survey (<a href="http://www.census.gov/programs-surveys/acs/" target="_blank">ACS</a>). 2011-2015. U.S. Department of Commerce, Washington, DC. Available.</p> <p>3. County Health Rankings (2016). <a href="http://www.countyhealthrankings.org/" target="_blank">http://www.countyhealthrankings.org/</a>.</p> <p>4. National Survey of Children's Health 2011-12. Data Resource Center for Child and Adolescent Health.</p> <p>5. Overweight and Obesity: Centers for Disease Control and Prevention (CDC), Behavioral Risk Factor Surveillance System (BRFSS). 2011-12. Atlanta, GA..<sup>1</sup></p> <p>6. Fast food restaurant access and grocery store access: U.S. Census Bureau. (2012). County Business Patterns. 2013. U.S. Department of Commerce.<sup>1</sup></p> <p>7. CDC, Behavioral Risk Factor Surveillance System (<a href="http://www.cdc.gov/brfss/" target="_blank">BRFSS</a>). 2005-09. Atlanta, GA. Available.<sup>1</sup></p> <p>8. U.S. Census Bureau. County Business Patterns. (<a href="http://www.census.gov/programs-surveys/cbp.html" target="_blank">CBP</a>). 2013. U.S. Department of Commerce, Washington, DC. Available.<sup>1</sup></p> <p>9. CDC, National Center for Chronic Disease Prevention and Health Promotion (<a href="http://www.cdc.gov/nccdphp/dnpao/index.html" target="_blank">NCCDPHP</a>). 2012. Atlanta, GA. Available.<sup>1</sup></p> <p>10. U.S. Department of Transportation, National Highway Traffic Safety Administration, <a href="http://www.nhtsa.gov/FARS" target="_blank">Fatality Analysis Reporting System</a>. 2011-13 (county data).</p> <p>11. U.S. Department of Health and Human Services, HRSA, Area Health Resource File (<a href="http://ahrf.hrsa.gov/" target="_blank">AHRF</a>). 2012. Washington, DC. Available.<sup>1</sup></p> </div> <div id="footer"></div> <sup>1</sup> Additional estimation and analysis done by <a href="http://cares.missouri.edu" target="_blank">CARES</a>. </div> </div> </div> <hr /> <div id="sa-report-action" class="sa-report-action"> <input type="button" class="button salud-report-card-link" value="Email Report" onclick="document.location='mailto:<?php echo $mail_to ?>';" title="Email it"/> <input type="button" class="button sa-report-export" id="sa-report-export" value="Export Report to PDF" /> <?php if ( current_user_can( 'bp_docs_associate_with_group', sa_get_group_id() ) ) : ?> <input type="button" class="button sa-report-save" id="sa-report-save" value="Save Report to My Library" /> <?php endif; ?> <div id="report-save-message" class="report-save-message">Saving your report card, please wait...</div> <input type="hidden" id="report-card-geoid" value="<?php echo $geoid ?>" /> <input type="hidden" id="report-card-county" value="<?php echo $cover_page->county_name ?>" /> <input type="hidden" id="report-card-state" value="<?php echo $cover_page->state_name ?>" /> <input type="hidden" id="report-card-wpnonce" value="<?php echo wp_create_nonce( 'save-leader-report-' . bp_loggedin_user_id() ) ?>" /> </div> <hr /> <?php endif; ?> </div><!-- end .content-row --> <?php } function console_log( $data ){ echo '<script>'; echo 'console.log(1, '. json_encode( $data ) .')'; echo '</script>'; } // get json object from API service function sa_report_get_json($fips, $id='', $param = '', $api_name ='indicator'){ $api_url = 'https://services.communitycommons.org/api-report/v1/' . $api_name . '/Salud/'; $api_url .= $id . '?area_type=county&area_ids=' . $fips . $param; $result = file_get_contents($api_url); return json_decode($result); } // get indicator dial function sa_report_get_dial($json){ return "<div class='center-align'><p><b>". $json->data->gauge_label . "</b></p><div class='sa-report-dial'>" . $json->gauge . "</div></div>"; } // get indicator value as double function sa_report_get_double($value){ if ($value == "no data" || $value == "suppressed"){ return 0; }else{ $value = preg_replace("/[^.0-9]/", '', $value); return floatval($value); } return 0; } // write the percentage in single digit format function sa_report_get_single_digit_pct($value){ if ($value == 0) { return "0%"; }else{ return number_format($value, 1) . "%"; } } // get fraction expression for latino adults & kids, called from sa_report_cover_page() function sa_report_set_fraction_value($value){ if ($value > 0){ $fraction = round(100 / $value); // in case we have "1 in 1", we change to common fractors if ($fraction == 1){ $fraction = round($value / 10); return "$fraction in 10"; }else{ return "1 in $fraction"; } }else{ return "0 in all"; } } // get all data for the cover page function sa_report_cover_page($fips){ $data = (object) array( 'frac_latino_adult' =>'1 in all', 'pct_latino_adults' =>0, 'frac_latino_kids' =>'1 in all', 'pct_latino_kids' =>0, ); try{ // Latino adults - percentage and fraction $json_value = sa_report_get_json($fips, '7080', '&breakout_id=8269'); // age 18+ $data->county_name = substr($json_value->area_name, 0, strrpos($json_value->area_name, ',')); $data->state_name = $json_value->data->state_list[0]->values[0]; $value_double = sa_report_get_double($json_value->data->summary->values[3]); $data->pct_latino_adults = sa_report_get_single_digit_pct($value_double); $data->frac_latino_adults = sa_report_set_fraction_value($value_double); // Latino kids - percentage and fraction $json_value = sa_report_get_json($fips, '706', '&breakout_id=8590'); $value_double = sa_report_get_double($json_value->data->summary->values[3]); $data->pct_latino_kids = sa_report_get_single_digit_pct($value_double); $data->frac_latino_kids = sa_report_set_fraction_value($value_double); // health outcoome ranking $json_value = sa_report_get_json($fips, '8040'); $data->health_ranking_total = $json_value->data->summary->values[1]; $data->health_ranking = $json_value->data->summary->values[4]; switch(substr($data->health_ranking, -1)){ case '1': $data->health_ranking_suffix = 'st'; break; case '2': $data->health_ranking_suffix = 'nd'; break; case '3': $data->health_ranking_suffix = 'rd'; break; default: $data->health_ranking_suffix = 'th'; break; } } catch (Exception $e){ console_log($e->getMessage()); } return $data; } // get all data for the obesity page function sa_report_obesity_page($fips){ $data = (object) array( 'pct_overweight'=>-1 ); try{ // state overall percentage overweight or obese $json_value = sa_report_get_json($fips, '8018', '&breakout_id=3'); $value_double = sa_report_get_double($json_value->data->state_list[0]->values[1]); $data->pct_latino_obese = sa_report_get_single_digit_pct($value_double); $value_double = sa_report_get_double($json_value->data->state_list[0]->values[2]); $data->pct_white_obese = sa_report_get_single_digit_pct($value_double); // obese percentage and dial - should always have data for counties except PR $json_value = sa_report_get_json($fips, '603', "&output_gauge=true"); $data->dial_obese = sa_report_get_dial($json_value); $value_double = sa_report_get_double($json_value->data->summary->values[3]); $data->pct_obese = sa_report_get_single_digit_pct($value_double); // overweight percentage and dial - may not have data for the county $json_value = sa_report_get_json($fips, '604', "&output_gauge=true"); $data->dial_overweight = sa_report_get_dial($json_value); $value_double = sa_report_get_double($json_value->data->summary->values[3]); if ($value_double !== 0){ $data->pct_overweight = sa_report_get_single_digit_pct($value_double); } }catch(Exception $e){ console_log($e->getMessage()); } return $data; } // get data for food access page function sa_report_food_access_page($fips){ $data = (object) array( 'total_fruit'=>-1 ); try{ // fast food dial $json_value = sa_report_get_json($fips, '401', "&output_gauge=true"); $data->dial_fast_food = sa_report_get_dial($json_value); // grovery store $json_value = sa_report_get_json($fips, '402', "&output_gauge=true"); $data->dial_grocery = sa_report_get_dial($json_value); // fruit/veggis - may not have value $json_value = sa_report_get_json($fips, '301', "&output_gauge=true"); $data->dial_fruit = sa_report_get_dial($json_value); $value_double = sa_report_get_double($json_value->data->summary->values[3]); if ($value_double !== 0){ $data->total_fruit = $json_value->data->summary->values[2]; $data->pct_fruit = sa_report_get_single_digit_pct($value_double); } }catch(Exception $e){ console_log($e->getMessage()); } return $data; } function sa_report_physical_activity_page($fips){ $data = (object) array(); try{ // recreation $json_value = sa_report_get_json($fips, '408', "&output_gauge=true"); $data->dial_recreation = sa_report_get_dial($json_value); // physical inactivity $json_value = sa_report_get_json($fips, '306', "&output_gauge=true"); $data->dial_physical = sa_report_get_dial($json_value); $data->total_physical = $json_value->data->summary->values[2]; $value_double = sa_report_get_double($json_value->data->summary->values[3]); $data->pct_physical = sa_report_get_single_digit_pct($value_double); // pedestrian $json_value = sa_report_get_json($fips, '627', "&output_gauge=true"); $data->dial_pedestrian = sa_report_get_dial($json_value); }catch(Exception $e){ console_log($e->getMessage()); } return $data; } function sa_report_health_equity_page($fips){ $data = (object) array(); try{ // children in poverty $json_value = sa_report_get_json($fips, '781', "&output_gauge=true"); $data->dial_poverty = sa_report_get_dial($json_value); $data->total_poverty = $json_value->data->summary->values[3]; $value_double = sa_report_get_double($json_value->data->summary->values[4]); $data->pct_poverty = sa_report_get_single_digit_pct($value_double); // access to primary care $json_value = sa_report_get_json($fips, '505', "&output_gauge=true"); $data->dial_primary_care = sa_report_get_dial($json_value); // no insurance $json_value = sa_report_get_json($fips, '202', "&output_gauge=true"); $data->dial_insurance = sa_report_get_dial($json_value); // socio-economic - high school graduation $json_value = sa_report_get_json($fips, '760', "&breakout_id=465"); $data->pct_latino_hs1 = $json_value->data->summary->values[3]; $data->pct_nonlatino_hs1 = $json_value->data->summary->values[4]; $data->pct_latino_hs2 = $json_value->data->state_list[0]->values[3]; $data->pct_nonlatino_hs2 = $json_value->data->state_list[0]->values[4]; $data->pct_latino_hs3 = $json_value->data->usa_summary->values[3]; $data->pct_nonlatino_hs3 = $json_value->data->usa_summary->values[4]; // socio-economic - poverty $json_value = sa_report_get_json($fips, '781', "&breakout_id=925"); $data->pct_latino_pov1 = $json_value->data->summary->values[3]; $data->pct_nonlatino_pov1 = $json_value->data->summary->values[4]; $data->pct_latino_pov2 = $json_value->data->state_list[0]->values[3]; $data->pct_nonlatino_pov2 = $json_value->data->state_list[0]->values[4]; $data->pct_latino_pov3 = $json_value->data->usa_summary->values[3]; $data->pct_nonlatino_pov3 = $json_value->data->usa_summary->values[4]; // socio-economic - insurance $json_value = sa_report_get_json($fips, '202', "&breakout_id=917"); $data->pct_latino_ins1 = $json_value->data->summary->values[3]; $data->pct_nonlatino_ins1 = $json_value->data->summary->values[4]; $data->pct_latino_ins2 = $json_value->data->state_list[0]->values[3]; $data->pct_nonlatino_ins2 = $json_value->data->state_list[0]->values[4]; $data->pct_latino_ins3 = $json_value->data->usa_summary->values[3]; $data->pct_nonlatino_ins3 = $json_value->data->usa_summary->values[4]; } catch(Exception $e){ console_log($e->getMessage()); } return $data; } function sa_report_vulnerable_population_page($geoid){ $data = (object) array( 'pct_white'=>-1 ); try{ // get data and map for vulnerable population $json_value = sa_report_get_json('', $geoid, '&map_width=600&map_height=615', 'vpf'); if ($json_value->values != null){ $data->pct_white = sa_report_get_single_digit_pct($json_value->values[0]->value); $data->pct_latino = sa_report_get_single_digit_pct($json_value->values[1]->value); $data->map = htmlspecialchars_decode($json_value->map); } $data->bbox = join(',', $json_value->bbox); } catch(Exception $e){ console_log($e->getMessage()); } return $data; }
gpl-2.0
mixaceh/openyu-commons.j
openyu-commons-core/src/main/java/org/openyu/commons/bao/hbase/supporter/HzBaoSupporter.java
8093
package org.openyu.commons.bao.hbase.supporter; import java.util.List; import java.util.Map; import org.apache.hadoop.hbase.HTableDescriptor; import org.apache.hadoop.hbase.client.Delete; import org.apache.hadoop.hbase.client.Get; import org.apache.hadoop.hbase.client.HTableInterface; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.client.ResultScanner; import org.apache.hadoop.hbase.client.Row; import org.apache.hadoop.hbase.client.RowMutations; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.client.coprocessor.Batch.Call; import org.apache.hadoop.hbase.client.coprocessor.Batch.Callback; import org.apache.hadoop.hbase.ipc.CoprocessorProtocol; import org.openyu.commons.bao.hbase.HzBao; import org.openyu.commons.bao.hbase.HzTemplate; import org.openyu.commons.bao.hbase.ex.HzBaoException; import org.openyu.commons.bao.hbase.impl.HzTemplateImpl; import org.openyu.commons.bao.supporter.BaseBaoSupporter; import org.openyu.commons.hbase.HzSession; import org.openyu.commons.hbase.HzSessionFactory; import org.openyu.commons.util.AssertHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class HzBaoSupporter extends BaseBaoSupporter implements HzBao { private static final long serialVersionUID = 1099108265636854567L; private static transient final Logger LOGGER = LoggerFactory.getLogger(HzBaoSupporter.class); private HzTemplate hzTemplate; public HzBaoSupporter() { } /** * 檢查設置 * * @throws Exception */ protected final void checkConfig() throws Exception { AssertHelper.notNull(hzTemplate, "The HzTemplate is required"); AssertHelper.notNull(this.hzTemplate.getHzSessionFactory(), "The HzSessionFactory is required"); } public final HzSessionFactory getHzSessionFactory() { return ((this.hzTemplate != null ? this.hzTemplate.getHzSessionFactory() : null)); } public final void setHzSessionFactory(HzSessionFactory hzSessionFactory) { if ((this.hzTemplate == null) || (hzSessionFactory != this.hzTemplate.getHzSessionFactory())) this.hzTemplate = createHzTemplate(hzSessionFactory); } protected HzTemplate createHzTemplate(HzSessionFactory hzSessionFactory) { return new HzTemplateImpl(hzSessionFactory); } public final HzTemplate getHzTemplate() { return hzTemplate; } public final void setHzTemplate(HzTemplate hzTemplate) { this.hzTemplate = hzTemplate; } protected final HzSession getSession() { return hzTemplate.getSession(); } protected final void closeSession() { hzTemplate.closeSession(); } // -------------------------------------------------- public boolean tableExists(String tableName) { try { return hzTemplate.tableExists(tableName); } catch (Exception ex) { throw new HzBaoException(ex); } } public boolean tableExists(byte[] tableName) { try { return hzTemplate.tableExists(tableName); } catch (Exception ex) { throw new HzBaoException(ex); } } public HTableDescriptor[] listTables() { try { return hzTemplate.listTables(); } catch (Exception ex) { throw new HzBaoException(ex); } } protected final HTableInterface getTable(String tableName) { try { return hzTemplate.getTable(tableName); } catch (Exception ex) { throw new HzBaoException(ex); } } protected final void closeTable(String tableName) { try { hzTemplate.closeTable(tableName); } catch (Exception ex) { throw new HzBaoException(ex); } } protected final void closeTable(HTableInterface table) { try { hzTemplate.closeTable(table); } catch (Exception ex) { throw new HzBaoException(ex); } } public boolean exists(String tableName, Get paramGet) { try { return hzTemplate.exists(tableName, paramGet); } catch (Exception ex) { throw new HzBaoException(ex); } } public void batch(String tableName, List<? extends Row> paramList, Object[] paramArrayOfObject) { try { hzTemplate.batch(tableName, paramList, paramArrayOfObject); } catch (Exception ex) { throw new HzBaoException(ex); } } public Object[] batch(String tableName, List<? extends Row> paramList) { try { return hzTemplate.batch(tableName, paramList); } catch (Exception ex) { throw new HzBaoException(ex); } } public Result get(String tableName, Get paramGet) { try { return hzTemplate.get(tableName, paramGet); } catch (Exception ex) { throw new HzBaoException(ex); } } public Result[] get(String tableName, List<Get> paramList) { try { return hzTemplate.get(tableName, paramList); } catch (Exception ex) { throw new HzBaoException(ex); } } public ResultScanner getScanner(String tableName, Scan paramScan) { try { return hzTemplate.getScanner(tableName, paramScan); } catch (Exception ex) { throw new HzBaoException(ex); } } public ResultScanner getScanner(String tableName, byte[] paramArrayOfByte) { try { return hzTemplate.getScanner(tableName, paramArrayOfByte); } catch (Exception ex) { throw new HzBaoException(ex); } } public ResultScanner getScanner(String tableName, byte[] paramArrayOfByte1, byte[] paramArrayOfByte2) { try { return hzTemplate.getScanner(tableName, paramArrayOfByte1, paramArrayOfByte2); } catch (Exception ex) { throw new HzBaoException(ex); } } public void put(String tableName, Put paramPut) { try { hzTemplate.put(tableName, paramPut); } catch (Exception ex) { throw new HzBaoException(ex); } } public void put(String tableName, List<Put> paramList) { try { hzTemplate.put(tableName, paramList); } catch (Exception ex) { throw new HzBaoException(ex); } } public boolean checkAndPut(String tableName, byte[] paramArrayOfByte1, byte[] paramArrayOfByte2, byte[] paramArrayOfByte3, byte[] paramArrayOfByte4, Put paramPut) { try { return hzTemplate.checkAndPut(tableName, paramArrayOfByte1, paramArrayOfByte2, paramArrayOfByte3, paramArrayOfByte4, paramPut); } catch (Exception ex) { throw new HzBaoException(ex); } } public void delete(String tableName, Delete paramDelete) { try { hzTemplate.delete(tableName, paramDelete); } catch (Exception ex) { throw new HzBaoException(ex); } } public void delete(String tableName, List<Delete> paramList) { try { hzTemplate.delete(tableName, paramList); } catch (Exception ex) { throw new HzBaoException(ex); } } public boolean checkAndDelete(String tableName, byte[] paramArrayOfByte1, byte[] paramArrayOfByte2, byte[] paramArrayOfByte3, byte[] paramArrayOfByte4, Delete paramDelete) { try { return hzTemplate.checkAndDelete(tableName, paramArrayOfByte1, paramArrayOfByte2, paramArrayOfByte3, paramArrayOfByte4, paramDelete); } catch (Exception ex) { throw new HzBaoException(ex); } } public void mutateRow(String tableName, RowMutations paramRowMutations) { try { hzTemplate.mutateRow(tableName, paramRowMutations); } catch (Exception ex) { throw new HzBaoException(ex); } } public <T extends CoprocessorProtocol> T coprocessorProxy(String tableName, Class<T> paramClass, byte[] paramArrayOfByte) { try { return hzTemplate.coprocessorProxy(tableName, paramClass, paramArrayOfByte); } catch (Exception ex) { throw new HzBaoException(ex); } } public <T extends CoprocessorProtocol, R> Map<byte[], R> coprocessorExec(String tableName, Class<T> paramClass, byte[] paramArrayOfByte1, byte[] paramArrayOfByte2, Call<T, R> paramCall) { try { return hzTemplate.coprocessorExec(tableName, paramClass, paramArrayOfByte1, paramArrayOfByte2, paramCall); } catch (Throwable ex) { throw new HzBaoException(ex); } } public <T extends CoprocessorProtocol, R> void coprocessorExec(String tableName, Class<T> paramClass, byte[] paramArrayOfByte1, byte[] paramArrayOfByte2, Call<T, R> paramCall, Callback<R> paramCallback) { try { hzTemplate.coprocessorExec(tableName, paramClass, paramArrayOfByte1, paramArrayOfByte2, paramCall, paramCallback); } catch (Throwable ex) { throw new HzBaoException(ex); } } }
gpl-2.0
gladk/LIGGGHTS-PUBLIC
src/cfd_datacoupling_file.cpp
13056
/* ---------------------------------------------------------------------- LIGGGHTS - LAMMPS Improved for General Granular and Granular Heat Transfer Simulations LIGGGHTS is part of the CFDEMproject www.liggghts.com | www.cfdem.com Christoph Kloss, christoph.kloss@cfdem.com Copyright 2009-2012 JKU Linz Copyright 2012- DCS Computing GmbH, Linz LIGGGHTS is based on LAMMPS LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator http://lammps.sandia.gov, Sandia National Laboratories Steve Plimpton, sjplimp@sandia.gov This software is distributed under the GNU General Public License. See the README file in the top-level directory. ------------------------------------------------------------------------- */ #include "sys/stat.h" #include "string.h" #include "stdlib.h" #include "atom.h" #include "comm.h" #include "update.h" #include "respa.h" #include "error.h" #include "memory.h" #include "modify.h" #include "math.h" #include "vector_liggghts.h" #include "fix_property_atom.h" #include "fix_property_global.h" #include "fix_cfd_coupling.h" #include "cfd_datacoupling_file.h" #include <iostream> #include <fstream> #include <unistd.h> #if defined(_WIN32) || defined(_WIN64) #include <windows.h> #define sleep Sleep #endif using namespace LAMMPS_NS; using namespace std; /* ---------------------------------------------------------------------- */ CfdDatacouplingFile::CfdDatacouplingFile(LAMMPS *lmp, int iarg,int narg, char **arg,FixCfdCoupling *fc) : CfdDatacoupling(lmp, iarg, narg, arg,fc) { iarg_ = iarg; int n_arg = narg - iarg_; if(n_arg < 1) error->all(FLERR,"Cfd file coupling: wrong # arguments"); liggghts_is_active = true; firstexec = true; this->fc_ = fc; is_parallel = false; filepath = new char[strlen(arg[iarg_])+2]; strcpy(filepath,arg[iarg_]); t0 = -1; iarg_++; append = 1; } /* ---------------------------------------------------------------------- */ CfdDatacouplingFile::~CfdDatacouplingFile() { delete []filepath; } /* ---------------------------------------------------------------------- */ void CfdDatacouplingFile::post_create() { if(!is_parallel && comm->nprocs > 1) error->all(FLERR,"Fix couple/cfd with file coupling is for serial computation only"); } /* ---------------------------------------------------------------------- */ void CfdDatacouplingFile::exchange() { void *dummy = NULL; // write to file for(int i = 0; i < npush_; i++) { push(pushnames_[i],pushtypes_[i],dummy,""); } // read from files for(int i = 0; i < npull_; i++) { pull(pullnames_[i],pulltypes_[i],dummy,""); } } /* ---------------------------------------------------------------------- */ void CfdDatacouplingFile::pull(char *name,char *type,void *&from,char *datatype) { CfdDatacoupling::pull(name,type,from,datatype); int len1 = -1, len2 = -1; void * to = find_pull_property(name,type,len1,len2); if(to && strcmp(type,"scalar-atom") == 0) { readScalarData(name,(double*)to); } else if(to && strcmp(type,"vector-atom") == 0) { readVectorData(name,(double**)to); } else if(to && strcmp(type,"vector-global") == 0) { readGlobalVectorData(name,(double*)from,len1); } else if(to && strcmp(type,"array-global") == 0) { readGlobalArrayData(name,(double**)from,len1,len2); } else { if(screen) fprintf(screen,"LIGGGHTS could not find property %s to write data from calling program to.\n",name); lmp->error->all(FLERR,"This error is fatal"); } } /* ---------------------------------------------------------------------- */ void CfdDatacouplingFile::push(char *name,char *type,void *&to,char *datatype) { CfdDatacoupling::push(name,type,to,datatype); int len1 = -1, len2 = -1; if(t0 == -1) t0 = update->ntimestep; if(update->ntimestep > t0) firstexec = false; void * from = find_push_property(name,type,len1,len2); if(from && strcmp(type,"scalar-atom") == 0) { writeScalarData(name,(double*)from); } else if(from && strcmp(type,"vector-atom") == 0) { writeVectorData(name,(double**)from); } else if(from && strcmp(type,"vector-global") == 0) { writeGlobalVectorData(name,(double*)from,len1); } else if(from && strcmp(type,"array-global") == 0) { writeGlobalArrayData(name,(double**)from,len1,len2); } else { if(screen) fprintf(screen,"LIGGGHTS could not find property %s to write to calling program.\n",name); lmp->error->all(FLERR,"This error is fatal"); } } /* ---------------------------------------------------------------------- */ /* ---------------------------------------------------------------------- */ char * CfdDatacouplingFile::getFilePath(char *name,bool flag) { if(!append) return name; char *file = new char[strlen(filepath)+strlen(name)+3]; strcpy(file,filepath); strcat(file,name); if(flag) strcat(file,"0"); else strcat(file,"1"); struct stat st; return file; } /* ---------------------------------------------------------------------- */ void CfdDatacouplingFile::op_complete(char *name) { if(!append) return; char *oldfile = getFilePath(name,true); char *newfile = getFilePath(name,false); rename(oldfile,newfile); delete []oldfile; delete []newfile; } /* ---------------------------------------------------------------------- */ void CfdDatacouplingFile::readVectorData(char *name, double ** field) { // get output path char *file = getFilePath(name,true); fprintf(screen,"Fix couple/cfd/file: waiting for file: %s\n",file); struct stat st; while (stat(file,&st)) sleep(0.03); // set file pointer ifstream inputPtr(file); // skip lines starting with # while(inputPtr.peek() == '#') inputPtr.ignore(1000,'\n'); // write data to variable int numberOfParticles; inputPtr >> numberOfParticles; if(atom->nlocal!=numberOfParticles) error->all(FLERR,"Fix couple/cfd/file: Data corruption: # particles in file does not match # particles in LIGGGHTS.\n" "Note that file-based coupling currently does not support inserting or deleting particles during a coupled run."); for(int index = 0;index < numberOfParticles; ++index) { for(int i=0;i<3;i++) inputPtr >> field[index][i]; } // clean up inputStream delete []file; op_complete(name); } /* ---------------------------------------------------------------------- */ void CfdDatacouplingFile::readScalarData(char* name, double *field) { // get output path char *file = getFilePath(name,true); fprintf(screen,"Fix couple/cfd/file: waiting for file: %s\n",file); struct stat st; while (stat(file,&st)) sleep(0.03); // set file pointer ifstream inputPtr(file); // skip lines starting with # while(inputPtr.peek() == '#') inputPtr.ignore(1000,'\n'); // write data to variable int numberOfParticles; inputPtr >> numberOfParticles; if(atom->nlocal!=numberOfParticles) error->all(FLERR,"Fix couple/cfd/file: Data corruption: # particles in file does not match # particles in LIGGGHTS.\n" "Note that file-based coupling currently does not support inserting or deleting particles during a coupled run."); // write data to variable for(int index = 0;index < numberOfParticles; ++index) { inputPtr >> field[index]; } // clean up inputStream delete []file; op_complete(name); } /* ---------------------------------------------------------------------- */ void CfdDatacouplingFile::readGlobalArrayData(char *name, double ** field, int &len1, int &len2) { // get output path char *file = getFilePath(name,true); fprintf(screen,"Fix couple/cfd/file: waiting for file: %s\n",file); struct stat st; while (stat(file,&st)) sleep(0.03); // set file pointerfrom ifstream inputPtr(file); // skip lines starting with # while(inputPtr.peek() == '#') inputPtr.ignore(1000,'\n'); // write data to variable int l1,l2; inputPtr >> l1; inputPtr >> l2; if(l1 != len1 || l2 != len2) error->one(FLERR,"Global array received has different length than the corresponding global array in LIGGGHTS"); for(int index = 0; index < len1; ++index) { for(int i = 0; i < len2; i++) { if(inputPtr.eof()) error->one(FLERR,"Global array received has different length than the corresponding global array in LIGGGHTS"); inputPtr >> field[index][i]; } } // clean up inputStream delete []file; op_complete(name); } /* ---------------------------------------------------------------------- */ void CfdDatacouplingFile::readGlobalVectorData(char* name, double *field, int &len) { // get output path char *file = getFilePath(name,true); fprintf(screen,"Fix couple/cfd/file: waiting for file: %s\n",file); struct stat st; while (stat(file,&st)) sleep(0.03); // set file pointer int l1; ifstream inputPtr(file); // skip lines starting with # while(inputPtr.peek() == '#') inputPtr.ignore(1000,'\n'); inputPtr >> l1; if(l1 != len) error->all(FLERR,"Global vector received has different length than the corresponding global array in LIGGGHTS"); // write data to variable for(int index = 0;index < len; ++index) { inputPtr >> field[index]; } // clean up inputStream delete []file; op_complete(name); } /* ---------------------------------------------------------------------- */ void CfdDatacouplingFile::writeVectorData(char *name, double ** field) { // get output path char *file = getFilePath(name,true); if(!firstexec) { fprintf(screen,"Fix couple/cfd/file: waiting for file: %s\n",file); struct stat st; while (stat(file,&st)) sleep(0.03); } // set file pointer ofstream outputPtr(file); // write data to file int numberOfParticles = atom->nlocal; outputPtr << numberOfParticles << endl; for(int index = 0;index < numberOfParticles; ++index) { for(int i=0;i<3;i++) outputPtr << field[index][i] << " "; outputPtr << endl; } // clean up outputStream and rename file delete []file; op_complete(name); } /* ---------------------------------------------------------------------- */ void CfdDatacouplingFile::writeScalarData(char* name, double * field) { // get output path char *file = getFilePath(name,true); if(!firstexec) { fprintf(screen,"Fix couple/cfd/file: waiting for file: %s\n",file); struct stat st; while (stat(file,&st)) sleep(0.03); } // set file pointer ofstream outputPtr(file); // write data to file int numberOfParticles = atom->nlocal; outputPtr << numberOfParticles << endl; for(int index = 0;index < numberOfParticles; ++index) { outputPtr << field[index] << endl; } // clean up outputStream and rename file delete []file; op_complete(name); } /* ---------------------------------------------------------------------- */ void CfdDatacouplingFile::writeGlobalVectorData(char *name, double *field,int len) { if(len < 0) error->all(FLERR,"Internal error in CfdDatacouplingFile"); // get output path char *file = getFilePath(name,true); if(!firstexec) { fprintf(screen,"Fix couple/cfd/file: waiting for file: %s\n",file); struct stat st; while (stat(file,&st)) sleep(0.03); } // set file pointer ofstream outputPtr(file); // write data to file outputPtr << len << endl; for(int index = 0;index < len; ++index) { outputPtr << field[index]; outputPtr << endl; } // clean up outputStream and rename file delete []file; op_complete(name); } /* ---------------------------------------------------------------------- */ void CfdDatacouplingFile::writeGlobalArrayData(char* name, double **field,int len1,int len2) { if(len1 < 0 || len2 < 0) error->all(FLERR,"Internal error in CfdDatacouplingFile"); // get output path char *file = getFilePath(name,true); if(!firstexec) { fprintf(screen,"Fix couple/cfd/file: waiting for file: %s\n",file); struct stat st; while (stat(file,&st)) sleep(0.03); } // set file pointer ofstream outputPtr(file); // write data to file outputPtr << len1 << endl; outputPtr << len2 << endl; for(int index = 0;index < len1; ++index) { for(int i=0;i<len2;i++) outputPtr << field[index][i] << " "; outputPtr << endl; } // clean up outputStream and rename file delete []file; op_complete(name); }
gpl-2.0
Ziqi-Li/bknqgis
bokeh/bokeh/models/glyphs.py
27774
# -*- coding: utf-8 -*- ''' Display a variety of visual shapes whose attributes can be associated with data columns from ``ColumnDataSources``. The full list of glyphs built into Bokeh is given below: * :class:`~bokeh.models.glyphs.AnnularWedge` * :class:`~bokeh.models.glyphs.Annulus` * :class:`~bokeh.models.glyphs.Arc` * :class:`~bokeh.models.glyphs.Bezier` * :class:`~bokeh.models.glyphs.Ellipse` * :class:`~bokeh.models.glyphs.HBar` * :class:`~bokeh.models.glyphs.Image` * :class:`~bokeh.models.glyphs.ImageRGBA` * :class:`~bokeh.models.glyphs.ImageURL` * :class:`~bokeh.models.glyphs.Line` * :class:`~bokeh.models.glyphs.MultiLine` * :class:`~bokeh.models.glyphs.Oval` * :class:`~bokeh.models.glyphs.Patch` * :class:`~bokeh.models.glyphs.Patches` * :class:`~bokeh.models.glyphs.Quad` * :class:`~bokeh.models.glyphs.Quadratic` * :class:`~bokeh.models.glyphs.Ray` * :class:`~bokeh.models.glyphs.Rect` * :class:`~bokeh.models.glyphs.Segment` * :class:`~bokeh.models.glyphs.Text` * :class:`~bokeh.models.glyphs.VBar` * :class:`~bokeh.models.glyphs.Wedge` All these glyphs share a minimal common interface through their base class ``Glyph``: .. autoclass:: Glyph :members: ''' from __future__ import absolute_import from ..core.enums import Anchor, Direction from ..core.has_props import abstract from ..core.properties import (AngleSpec, Bool, DistanceSpec, Enum, Float, Include, Instance, Int, NumberSpec, StringSpec) from ..core.property_mixins import FillProps, LineProps, TextProps from ..model import Model from .mappers import ColorMapper, LinearColorMapper @abstract class Glyph(Model): ''' Base class for all glyph models. ''' @abstract class XYGlyph(Glyph): ''' Base class of glyphs with `x` and `y` coordinate attributes. ''' class AnnularWedge(XYGlyph): ''' Render annular wedges. ''' __example__ = "examples/reference/models/AnnularWedge.py" # a canonical order for positional args that can be used for any # functions derived from this class _args = ('x', 'y', 'inner_radius', 'outer_radius', 'start_angle', 'end_angle', 'direction') x = NumberSpec(help=""" The x-coordinates of the center of the annular wedges. """) y = NumberSpec(help=""" The y-coordinates of the center of the annular wedges. """) inner_radius = DistanceSpec(help=""" The inner radii of the annular wedges. """) outer_radius = DistanceSpec(help=""" The outer radii of the annular wedges. """) start_angle = AngleSpec(help=""" The angles to start the annular wedges, as measured from the horizontal. """) end_angle = AngleSpec(help=""" The angles to end the annular wedges, as measured from the horizontal. """) direction = Enum(Direction, default=Direction.anticlock, help=""" Which direction to stroke between the start and end angles. """) line_props = Include(LineProps, use_prefix=False, help=""" The %s values for the annular wedges. """) fill_props = Include(FillProps, use_prefix=False, help=""" The %s values for the annular wedges. """) class Annulus(XYGlyph): ''' Render annuli. ''' __example__ = "examples/reference/models/Annulus.py" # a canonical order for positional args that can be used for any # functions derived from this class _args = ('x', 'y', 'inner_radius', 'outer_radius') x = NumberSpec(help=""" The x-coordinates of the center of the annuli. """) y = NumberSpec(help=""" The y-coordinates of the center of the annuli. """) inner_radius = DistanceSpec(help=""" The inner radii of the annuli. """) outer_radius = DistanceSpec(help=""" The outer radii of the annuli. """) line_props = Include(LineProps, use_prefix=False, help=""" The %s values for the annuli. """) fill_props = Include(FillProps, use_prefix=False, help=""" The %s values for the annuli. """) class Arc(XYGlyph): ''' Render arcs. ''' __example__ = "examples/reference/models/Arc.py" # a canonical order for positional args that can be used for any # functions derived from this class _args = ('x', 'y', 'radius', 'start_angle', 'end_angle', 'direction') x = NumberSpec(help=""" The x-coordinates of the center of the arcs. """) y = NumberSpec(help=""" The y-coordinates of the center of the arcs. """) radius = DistanceSpec(help=""" Radius of the arc. """) start_angle = AngleSpec(help=""" The angles to start the arcs, as measured from the horizontal. """) end_angle = AngleSpec(help=""" The angles to end the arcs, as measured from the horizontal. """) direction = Enum(Direction, default='anticlock', help=""" Which direction to stroke between the start and end angles. """) line_props = Include(LineProps, use_prefix=False, help=""" The %s values for the arcs. """) class Bezier(Glyph): u''' Render Bézier curves. For more information consult the `Wikipedia article for Bézier curve`_. .. _Wikipedia article for Bézier curve: http://en.wikipedia.org/wiki/Bézier_curve ''' __example__ = "examples/reference/models/Bezier.py" # a canonical order for positional args that can be used for any # functions derived from this class _args = ('x0', 'y0', 'x1', 'y1', 'cx0', 'cy0', 'cx1', 'cy1') x0 = NumberSpec(help=""" The x-coordinates of the starting points. """) y0 = NumberSpec(help=""" The y-coordinates of the starting points. """) x1 = NumberSpec(help=""" The x-coordinates of the ending points. """) y1 = NumberSpec(help=""" The y-coordinates of the ending points. """) cx0 = NumberSpec(help=""" The x-coordinates of first control points. """) cy0 = NumberSpec(help=""" The y-coordinates of first control points. """) cx1 = NumberSpec(help=""" The x-coordinates of second control points. """) cy1 = NumberSpec(help=""" The y-coordinates of second control points. """) line_props = Include(LineProps, use_prefix=False, help=u""" The %s values for the Bézier curves. """) class Ellipse(XYGlyph): u''' Render ellipses. ''' __example__ = "examples/reference/models/Ellipse.py" # a canonical order for positional args that can be used for any # functions derived from this class _args = ('x', 'y', 'width', 'height', 'angle') x = NumberSpec(help=""" The x-coordinates of the centers of the ellipses. """) y = NumberSpec(help=""" The y-coordinates of the centers of the ellipses. """) width = DistanceSpec(help=""" The widths of each ellipse. """) height = DistanceSpec(help=""" The heights of each ellipse. """) angle = AngleSpec(default=0.0, help=""" The angle the ellipses are rotated from horizontal. [rad] """) line_props = Include(LineProps, use_prefix=False, help=""" The %s values for the ovals. """) fill_props = Include(FillProps, use_prefix=False, help=""" The %s values for the ovals. """) class HBar(Glyph): ''' Render horizontal bars, given a center coordinate, ``height`` and (``left``, ``right``) coordinates. ''' __example__ = "examples/reference/models/HBar.py" # a canonical order for positional args that can be used for any # functions derived from this class _args = ('y', 'height', 'right', 'left') y = NumberSpec(help=""" The y-coordinates of the centers of the horizontal bars. """) height = NumberSpec(help=""" The heights of the vertical bars. """) left = NumberSpec(default=0, help=""" The x-coordinates of the left edges. """) right = NumberSpec(help=""" The x-coordinates of the right edges. """) line_props = Include(LineProps, use_prefix=False, help=""" The %s values for the horizontal bars. """) fill_props = Include(FillProps, use_prefix=False, help=""" The %s values for the horizontal bars. """) class Image(XYGlyph): ''' Render images given as scalar data together with a color mapper. In addition to the defined model properties, ``Image`` also can accept a keyword argument ``palette`` in place of an explicit ``color_mapper``. The value should be a list of colors, or the name of one of the built-in palettes in ``bokeh.palettes``. This palette will be used to automatically construct a ``ColorMapper`` model for the ``color_mapper`` property. If both ``palette`` and ``color_mapper`` are passed, a ``ValueError`` exception will be raised. If neither is passed, then the ``Greys9`` palette will be used as a default. ''' def __init__(self, **kwargs): if 'palette' in kwargs and 'color_mapper' in kwargs: raise ValueError("only one of 'palette' and 'color_mapper' may be specified") elif 'color_mapper' not in kwargs: # Use a palette (given or default) palette = kwargs.pop('palette', 'Greys9') mapper = LinearColorMapper(palette) kwargs['color_mapper'] = mapper super(Image, self).__init__(**kwargs) # a canonical order for positional args that can be used for any # functions derived from this class _args = ('image', 'x', 'y', 'dw', 'dh', 'dilate') # a hook to specify any additional kwargs handled by an initializer _extra_kws = { 'palette': ( 'str or list[color value]', 'a palette to construct a value for the color mapper property from' ) } image = NumberSpec(help=""" The arrays of scalar data for the images to be colormapped. """) x = NumberSpec(help=""" The x-coordinates to locate the image anchors. """) y = NumberSpec(help=""" The y-coordinates to locate the image anchors. """) dw = DistanceSpec(help=""" The widths of the plot regions that the images will occupy. .. note:: This is not the number of pixels that an image is wide. That number is fixed by the image itself. """) dh = DistanceSpec(help=""" The height of the plot region that the image will occupy. .. note:: This is not the number of pixels that an image is tall. That number is fixed by the image itself. """) dilate = Bool(False, help=""" Whether to always round fractional pixel locations in such a way as to make the images bigger. This setting may be useful if pixel rounding errors are causing images to have a gap between them, when they should appear flush. """) color_mapper = Instance(ColorMapper, help=""" A ``ColorMapper`` to use to map the scalar data from ``image`` into RGBA values for display. .. note:: The color mapping step happens on the client. """) # TODO: (bev) support anchor property for Image # ref: https://github.com/bokeh/bokeh/issues/1763 class ImageRGBA(XYGlyph): ''' Render images given as RGBA data. ''' # a canonical order for positional args that can be used for any # functions derived from this class _args = ('image', 'x', 'y', 'dw', 'dh', 'dilate') image = NumberSpec(help=""" The arrays of RGBA data for the images. """) x = NumberSpec(help=""" The x-coordinates to locate the image anchors. """) y = NumberSpec(help=""" The y-coordinates to locate the image anchors. """) dw = DistanceSpec(help=""" The widths of the plot regions that the images will occupy. .. note:: This is not the number of pixels that an image is wide. That number is fixed by the image itself. """) dh = DistanceSpec(help=""" The height of the plot region that the image will occupy. .. note:: This is not the number of pixels that an image is tall. That number is fixed by the image itself. """) dilate = Bool(False, help=""" Whether to always round fractional pixel locations in such a way as to make the images bigger. This setting may be useful if pixel rounding errors are causing images to have a gap between them, when they should appear flush. """) # TODO: (bev) support anchor property for ImageRGBA # ref: https://github.com/bokeh/bokeh/issues/1763 class ImageURL(XYGlyph): ''' Render images loaded from given URLs. ''' __example__ = "examples/reference/models/ImageURL.py" # a canonical order for positional args that can be used for any # functions derived from this class _args = ('url', 'x', 'y', 'w', 'h', 'angle', 'global_alpha', 'dilate') # TODO (bev) Why is this a NumberSpec?? url = NumberSpec(accept_datetime=False, help=""" The URLs to retrieve images from. .. note:: The actual retrieving and loading of the images happens on the client. """) x = NumberSpec(help=""" The x-coordinates to locate the image anchors. """) y = NumberSpec(help=""" The y-coordinates to locate the image anchors. """) w = DistanceSpec(default=None, help=""" The height of the plot region that the image will occupy in data space. The default value is ``None``, in which case the image will be displayed at its actual image size (regardless of the units specified here). """) h = DistanceSpec(default=None, help=""" The height of the plot region that the image will occupy in data space. The default value is ``None``, in which case the image will be displayed at its actual image size (regardless of the units specified here). """) angle = AngleSpec(default=0, help=""" The angles to rotate the images, as measured from the horizontal. """) global_alpha = Float(1.0, help=""" An overall opacity that each image is rendered with (in addition to any inherent alpha values in the image itself). """) dilate = Bool(False, help=""" Whether to always round fractional pixel locations in such a way as to make the images bigger. This setting may be useful if pixel rounding errors are causing images to have a gap between them, when they should appear flush. """) anchor = Enum(Anchor, help=""" What position of the image should be anchored at the `x`, `y` coordinates. """) retry_attempts = Int(0, help=""" Number of attempts to retry loading the images from the specified URL. Default is zero. """) retry_timeout = Int(0, help=""" Timeout (in ms) between retry attempts to load the image from the specified URL. Default is zero ms. """) class Line(XYGlyph): ''' Render a single line. The ``Line`` glyph is different from most other glyphs in that the vector of values only produces one glyph on the Plot. ''' # a canonical order for positional args that can be used for any # functions derived from this class _args = ('x', 'y') __example__ = "examples/reference/models/Line.py" x = NumberSpec(help=""" The x-coordinates for the points of the line. """) y = NumberSpec(help=""" The y-coordinates for the points of the line. """) line_props = Include(LineProps, use_prefix=False, help=""" The %s values for the line. """) class MultiLine(Glyph): ''' Render several lines. The data for the ``MultiLine`` glyph is different in that the vector of values is not a vector of scalars. Rather, it is a "list of lists". ''' __example__ = "examples/reference/models/MultiLine.py" # a canonical order for positional args that can be used for any # functions derived from this class _args = ('xs', 'ys') xs = NumberSpec(help=""" The x-coordinates for all the lines, given as a "list of lists". """) ys = NumberSpec(help=""" The y-coordinates for all the lines, given as a "list of lists". """) line_props = Include(LineProps, use_prefix=False, help=""" The %s values for the lines. """) class Oval(XYGlyph): u''' Render ovals. This glyph renders ovals using Bézier curves, which are similar, but not identical to ellipses. In particular, widths equal to heights will not render circles. Use the ``Ellipse`` glyph for that. ''' __example__ = "examples/reference/models/Oval.py" # a canonical order for positional args that can be used for any # functions derived from this class _args = ('x', 'y', 'width', 'height', 'angle') x = NumberSpec(help=""" The x-coordinates of the centers of the ovals. """) y = NumberSpec(help=""" The y-coordinates of the centers of the ovals. """) width = DistanceSpec(help=""" The overall widths of each oval. """) height = DistanceSpec(help=""" The overall height of each oval. """) angle = AngleSpec(default=0.0, help=""" The angle the ovals are rotated from horizontal. [rad] """) line_props = Include(LineProps, use_prefix=False, help=""" The %s values for the ovals. """) fill_props = Include(FillProps, use_prefix=False, help=""" The %s values for the ovals. """) class Patch(XYGlyph): ''' Render a single patch. The ``Patch`` glyph is different from most other glyphs in that the vector of values only produces one glyph on the Plot. ''' __example__ = "examples/reference/models/Patch.py" # a canonical order for positional args that can be used for any # functions derived from this class _args = ('x', 'y') x = NumberSpec(help=""" The x-coordinates for the points of the patch. .. note:: A patch may comprise multiple polygons. In this case the x-coordinates for each polygon should be separated by NaN values in the sequence. """) y = NumberSpec(help=""" The y-coordinates for the points of the patch. .. note:: A patch may comprise multiple polygons. In this case the y-coordinates for each polygon should be separated by NaN values in the sequence. """) line_props = Include(LineProps, use_prefix=False, help=""" The %s values for the patch. """) fill_props = Include(FillProps, use_prefix=False, help=""" The %s values for the patch. """) class Patches(Glyph): ''' Render several patches. The data for the ``Patches`` glyph is different in that the vector of values is not a vector of scalars. Rather, it is a "list of lists". ''' __example__ = "examples/reference/models/Patches.py" # a canonical order for positional args that can be used for any # functions derived from this class _args = ('xs', 'ys') xs = NumberSpec(help=""" The x-coordinates for all the patches, given as a "list of lists". .. note:: Individual patches may comprise multiple polygons. In this case the x-coordinates for each polygon should be separated by NaN values in the sublists. """) ys = NumberSpec(help=""" The y-coordinates for all the patches, given as a "list of lists". .. note:: Individual patches may comprise multiple polygons. In this case the y-coordinates for each polygon should be separated by NaN values in the sublists. """) line_props = Include(LineProps, use_prefix=False, help=""" The %s values for the patches. """) fill_props = Include(FillProps, use_prefix=False, help=""" The %s values for the patches. """) class Quad(Glyph): ''' Render axis-aligned quads. ''' __example__ = "examples/reference/models/Quad.py" # a canonical order for positional args that can be used for any # functions derived from this class _args = ('left', 'right', 'top', 'bottom') left = NumberSpec(help=""" The x-coordinates of the left edges. """) right = NumberSpec(help=""" The x-coordinates of the right edges. """) bottom = NumberSpec(help=""" The y-coordinates of the bottom edges. """) top = NumberSpec(help=""" The y-coordinates of the top edges. """) line_props = Include(LineProps, use_prefix=False, help=""" The %s values for the quads. """) fill_props = Include(FillProps, use_prefix=False, help=""" The %s values for the quads. """) class Quadratic(Glyph): ''' Render parabolas. ''' __example__ = "examples/reference/models/Quadratic.py" # a canonical order for positional args that can be used for any # functions derived from this class _args = ('x0', 'y0', 'x1', 'y1', 'cx', 'cy') x0 = NumberSpec(help=""" The x-coordinates of the starting points. """) y0 = NumberSpec(help=""" The y-coordinates of the starting points. """) x1 = NumberSpec(help=""" The x-coordinates of the ending points. """) y1 = NumberSpec(help=""" The y-coordinates of the ending points. """) cx = NumberSpec(help=""" The x-coordinates of the control points. """) cy = NumberSpec(help=""" The y-coordinates of the control points. """) line_props = Include(LineProps, use_prefix=False, help=""" The %s values for the parabolas. """) class Ray(XYGlyph): ''' Render rays. ''' __example__ = "examples/reference/models/Ray.py" # a canonical order for positional args that can be used for any # functions derived from this class _args = ('x', 'y', 'length', 'angle') x = NumberSpec(help=""" The x-coordinates to start the rays. """) y = NumberSpec(help=""" The y-coordinates to start the rays. """) angle = AngleSpec(help=""" The angles in radians to extend the rays, as measured from the horizontal. """) length = DistanceSpec(help=""" The length to extend the ray. Note that this ``length`` defaults to screen units. """) line_props = Include(LineProps, use_prefix=False, help=""" The %s values for the rays. """) class Rect(XYGlyph): ''' Render rectangles. ''' __example__ = "examples/reference/models/Rect.py" # a canonical order for positional args that can be used for any # functions derived from this class _args = ('x', 'y', 'width', 'height', 'angle', 'dilate') x = NumberSpec(help=""" The x-coordinates of the centers of the rectangles. """) y = NumberSpec(help=""" The y-coordinates of the centers of the rectangles. """) width = DistanceSpec(help=""" The overall widths of the rectangles. """) height = DistanceSpec(help=""" The overall heights of the rectangles. """) angle = AngleSpec(default=0.0, help=""" The angles to rotate the rectangles, as measured from the horizontal. """) dilate = Bool(False, help=""" Whether to always round fractional pixel locations in such a way as to make the rectangles bigger. This setting may be useful if pixel rounding errors are causing rectangles to have a gap between them, when they should appear flush. """) line_props = Include(LineProps, use_prefix=False, help=""" The %s values for the rectangles. """) fill_props = Include(FillProps, use_prefix=False, help=""" The %s values for the rectangles. """) class Segment(Glyph): ''' Render segments. ''' __example__ = "examples/reference/models/Segment.py" # a canonical order for positional args that can be used for any # functions derived from this class _args = ('x0', 'y0', 'x1', 'y1') x0 = NumberSpec(help=""" The x-coordinates of the starting points. """) y0 = NumberSpec(help=""" The y-coordinates of the starting points. """) x1 = NumberSpec(help=""" The x-coordinates of the ending points. """) y1 = NumberSpec(help=""" The y-coordinates of the ending points. """) line_props = Include(LineProps, use_prefix=False, help=""" The %s values for the segments. """) class Text(XYGlyph): ''' Render text. ''' __example__ = "examples/reference/models/Text.py" # a canonical order for positional args that can be used for any # functions derived from this class _args = ('x', 'y', 'text', 'angle', 'x_offset', 'y_offset') x = NumberSpec(help=""" The x-coordinates to locate the text anchors. """) y = NumberSpec(help=""" The y-coordinates to locate the text anchors. """) text = StringSpec("text", help=""" The text values to render. """) angle = AngleSpec(default=0, help=""" The angles to rotate the text, as measured from the horizontal. """) x_offset = NumberSpec(default=0, help=""" Offset values to apply to the x-coordinates. This is useful, for instance, if it is desired to "float" text a fixed distance in screen units from a given data position. """) y_offset = NumberSpec(default=0, help=""" Offset values to apply to the y-coordinates. This is useful, for instance, if it is desired to "float" text a fixed distance in screen units from a given data position. """) text_props = Include(TextProps, use_prefix=False, help=""" The %s values for the text. """) class VBar(Glyph): ''' Render vertical bars, given a center coordinate, width and (top, bottom) coordinates. ''' __example__ = "examples/reference/models/VBar.py" # a canonical order for positional args that can be used for any # functions derived from this class _args = ('x', 'width', 'top', 'bottom') x = NumberSpec(help=""" The x-coordinates of the centers of the vertical bars. """) width = NumberSpec(help=""" The widths of the vertical bars. """) bottom = NumberSpec(default=0, help=""" The y-coordinates of the bottom edges. """) top = NumberSpec(help=""" The y-coordinates of the top edges. """) line_props = Include(LineProps, use_prefix=False, help=""" The %s values for the vertical bars. """) fill_props = Include(FillProps, use_prefix=False, help=""" The %s values for the vertical bars. """) class Wedge(XYGlyph): ''' Render wedges. ''' __example__ = "examples/reference/models/Wedge.py" # a canonical order for positional args that can be used for any # functions derived from this class _args = ('x', 'y', 'radius', 'start_angle', 'end_angle', 'direction') x = NumberSpec(help=""" The x-coordinates of the points of the wedges. """) y = NumberSpec(help=""" The y-coordinates of the points of the wedges. """) radius = DistanceSpec(help=""" Radii of the wedges. """) start_angle = AngleSpec(help=""" The angles to start the wedges, as measured from the horizontal. """) end_angle = AngleSpec(help=""" The angles to end the wedges, as measured from the horizontal. """) direction = Enum(Direction, default='anticlock', help=""" Which direction to stroke between the start and end angles. """) line_props = Include(LineProps, use_prefix=False, help=""" The %s values for the wedges. """) fill_props = Include(FillProps, use_prefix=False, help=""" The %s values for the wedges. """) # XXX: allow `from bokeh.models.glyphs import *` from .markers import (Asterisk, Circle, CircleCross, CircleX, Cross, Diamond, DiamondCross, InvertedTriangle, Marker, Square, SquareCross, SquareX, Triangle, X) # Fool pyflakes (Asterisk, Circle, CircleCross, CircleX, Cross, Diamond, DiamondCross, InvertedTriangle, Marker, Square, SquareCross, SquareX, Triangle, X)
gpl-2.0
kusum18/opensis
modules/Students/AdvancedReport.php
4420
<?php #************************************************************************** # openSIS is a free student information system for public and non-public # schools from Open Solutions for Education, Inc. It is web-based, # open source, and comes packed with features that include student # demographic info, scheduling, grade book, attendance, # report cards, eligibility, transcripts, parent portal, # student portal and more. # # Visit the openSIS web site at http://www.opensis.com to learn more. # If you have question regarding this system or the license, please send # an email to info@os4ed.com. # # Copyright (C) 2007-2008, Open Solutions for Education, Inc. # #************************************************************************* # 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, version 2 of the License. See license.txt. # # 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, see <http://www.gnu.org/licenses/>. #************************************************************************** if($_REQUEST['modfunc']=='save') { if(count($_REQUEST['st_arr'])) { $st_list = '\''.implode('\',\'',$_REQUEST['st_arr']).'\''; $extra['WHERE'] = " AND s.STUDENT_ID IN ($st_list)"; if($_REQUEST['ADDRESS_ID']) { $extra['singular'] = 'Family'; $extra['plural'] = 'Families'; $extra['group'] = $extra['LO_group'] = array('ADDRESS_ID'); } echo "<table width=100% style=\" font-family:Arial; font-size:12px;\" >"; echo "<tr><td style=\"font-size:15px; font-weight:bold; padding-top:20px;\">". GetSchool(UserSchool())."<div style=\"font-size:12px;\">Student Advanced Report</div></td><td align=right style=\"padding-top:20px;\">". ProperDate(DBDate()) ."<br />Powered by openSIS</td></tr><tr><td colspan=2 style=\"border-top:1px solid #333;\">&nbsp;</td></tr></table>"; echo "<table >"; include('modules/misc/Export.php'); } } if(!$_REQUEST['modfunc']) { DrawBC("Students > ".ProgramTitle()); if($_REQUEST['search_modfunc']=='list' || $_REQUEST['search_modfunc']=='select') { $_REQUEST['search_modfunc'] = 'select'; $extra['extra_header_left'] .= '<TABLE><TR><TD><INPUT type=checkbox name=ADDRESS_ID value=Y'.($_REQUEST['address_group']?' checked':'').'>Group by Family</TD></TR></TABLE>'; $extra['link'] = array('FULL_NAME'=>false); $extra['SELECT'] = ",CONCAT('<INPUT type=checkbox name=st_arr[] value=',s.STUDENT_ID,' checked>') AS CHECKBOX"; $extra['columns_before'] = array('CHECKBOX'=>'</A><INPUT type=checkbox value=Y name=controller checked onclick="checkAll(this.form,this.form.controller.checked,\'st_arr\');"><A>'); $extra['options']['search'] = false; echo "<FORM action=for_export.php?modname=$_REQUEST[modname]&modfunc=save&search_modfunc=list&_CENTRE_PDF=true&include_inactive=$_REQUEST[include_inactive]&_search_all_schools=$_REQUEST[_search_all_schools] onsubmit=document.forms[0].relation.value=document.getElementById(\"relation\").value; method=POST target=_blank>"; echo '<DIV id=fields_div></DIV>'; echo '<INPUT type=hidden name=relation>'; Widgets('course'); Widgets('request'); Widgets('activity'); Widgets('absences'); Widgets('gpa'); Widgets('class_rank'); Widgets('letter_grade'); Widgets('eligibility'); $extra['search'] .= '<TR><TD align=right width=120>Include courses active as of </TD><TD>'.PrepareDate('','_include_active_date').'</TD></TR>'; $extra['new'] = true; include('modules/misc/Export.php'); echo '<BR><CENTER><INPUT type=submit value=\'Create Report for Selected Students\' class=btn_xxlarge></CENTER>'; echo "</FORM>"; } else { Widgets('course'); Widgets('request'); Widgets('activity'); Widgets('absences'); Widgets('gpa'); Widgets('class_rank'); Widgets('letter_grade'); Widgets('eligibility'); $extra['search'] .= '<TR><TD align=right width=120>Include courses active as of </TD><TD>'.PrepareDate('','_include_active_date').'</TD></TR>'; $extra['new'] = true; Search('student_id',$extra); } } ?>
gpl-2.0
baxri/presents
administrator/templates/jisrael/html/modules.php
1999
<?php /** * @package JIsrael Template package * @subpackage Templates.jisrael * @copyright Copyright (C) 2005 - 2013 J-Guru.com, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt * @since 3.0 */ /** * @package Joomla.Administrator * @subpackage Templates.isis * * @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ defined('_JEXEC') or die; /** * This is a file to add template specific chrome to module rendering. To use it you would * set the style attribute for the given module(s) include in your template to use the style * for each given modChrome function. * * eg. To render a module mod_test in the submenu style, you would use the following include: * <jdoc:include type="module" name="test" style="submenu" /> * * This gives template designers ultimate control over how modules are rendered. * * NOTICE: All chrome wrapping methods should be named: modChrome_{STYLE} and take the same * two arguments. */ /* * Module chrome for rendering the module in a submenu */ function modChrome_title($module, &$params, &$attribs) { if ($module->content) { echo "<div class=\"module-title\"><h6>".$module->title."</h6></div>"; echo $module->content; } } function modChrome_no($module, &$params, &$attribs) { if ($module->content) { echo $module->content; } } function modChrome_well($module, &$params, &$attribs) { if ($module->content) { $bootstrapSize = $params->get('bootstrap_size'); $moduleClass = !empty($bootstrapSize) ? ' span' . (int) $bootstrapSize . '' : ''; if ( $moduleClass ) { echo '<div class="' . $moduleClass . '">'; } echo '<div class="well well-small">'; echo '<h2 class="module-title nav-header">' . $module->title .'</h2>'; echo $module->content; echo '</div>'; if ( $moduleClass ) { echo '</div>'; } } }
gpl-2.0
T-R0D/JustForFun
GA-Noodle/bin/__init__.py
658
# This file is part of GANoodle. # # GANoodle 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 3 of the License, or # (at your option) any later version. # # GANoodle 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 Foobar. If not, see <http://www.gnu.org/licenses/>.
gpl-2.0
myblockchain/myblockchain
storage/perfschema/pfs_program.cc
8538
/* Copyright (c) 2013, 2015, Oracle and/or its affiliates. All rights reserved. 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; version 2 of the License. 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, 51 Franklin Street, Suite 500, Boston, MA 02110-1335 USA */ /** @file storage/perfschema/pfs_program.cc Statement Digest data structures (implementation). */ /* This code needs extra visibility in the lexer structures */ #include "my_global.h" #include "my_sys.h" #include "pfs_instr.h" #include "pfs_program.h" #include "pfs_global.h" #include "sql_string.h" #include "pfs_setup_object.h" #include "pfs_buffer_container.h" #include "myblockchaind.h" //system_charset_info #include <string.h> LF_HASH program_hash; static bool program_hash_inited= false; /** Initialize table EVENTS_STATEMENTS_SUMMARY_BY_PROGRAM. @param param performance schema sizing */ int init_program(const PFS_global_param *param) { if (global_program_container.init(param->m_program_sizing)) return 1; reset_esms_by_program(); return 0; } /** Cleanup table EVENTS_STATEMENTS_SUMMARY_BY_PROGRAM. */ void cleanup_program(void) { global_program_container.cleanup(); } C_MODE_START static uchar *program_hash_get_key(const uchar *entry, size_t *length, my_bool) { const PFS_program * const *typed_entry; const PFS_program *program; const void *result; typed_entry= reinterpret_cast<const PFS_program* const *> (entry); DBUG_ASSERT(typed_entry != NULL); program= *typed_entry; DBUG_ASSERT(program != NULL); *length= program->m_key.m_key_length; result= program->m_key.m_hash_key; return const_cast<uchar*> (reinterpret_cast<const uchar*> (result)); } C_MODE_END /** Initialize the program hash. @return 0 on success */ int init_program_hash(const PFS_global_param *param) { if ((! program_hash_inited) && (param->m_program_sizing != 0)) { lf_hash_init(&program_hash, sizeof(PFS_program*), LF_HASH_UNIQUE, 0, 0, program_hash_get_key, &my_charset_bin); program_hash_inited= true; } return 0; } /** Cleanup the program hash. */ void cleanup_program_hash(void) { if (program_hash_inited) { lf_hash_destroy(&program_hash); program_hash_inited= false; } } static void set_program_key(PFS_program_key *key, enum_object_type object_type, const char *object_name, uint object_name_length, const char *schema_name, uint schema_name_length) { DBUG_ASSERT(object_name_length <= COL_OBJECT_NAME_SIZE); DBUG_ASSERT(schema_name_length <= COL_OBJECT_SCHEMA_SIZE); /* To make sure generated key is case insensitive, convert object_name/schema_name to lowercase. */ char *ptr= &key->m_hash_key[0]; ptr[0]= object_type; ptr++; if (object_name_length > 0) { char tmp_object_name[COL_OBJECT_NAME_SIZE + 1]; memcpy(tmp_object_name, object_name, object_name_length); tmp_object_name[object_name_length]= '\0'; my_casedn_str(system_charset_info, tmp_object_name); memcpy(ptr, tmp_object_name, object_name_length); ptr+= object_name_length; } ptr[0]= 0; ptr++; if (schema_name_length > 0) { char tmp_schema_name[COL_OBJECT_SCHEMA_SIZE + 1]; memcpy(tmp_schema_name, schema_name, schema_name_length); tmp_schema_name[schema_name_length]='\0'; my_casedn_str(system_charset_info, tmp_schema_name); memcpy(ptr, tmp_schema_name, schema_name_length); ptr+= schema_name_length; } ptr[0]= 0; ptr++; key->m_key_length= ptr - &key->m_hash_key[0]; } void PFS_program::reset_data() { m_sp_stat.reset(); m_stmt_stat.reset(); } static void fct_reset_esms_by_program(PFS_program *pfs) { pfs->reset_data(); } void reset_esms_by_program() { global_program_container.apply_all(fct_reset_esms_by_program); } static LF_PINS* get_program_hash_pins(PFS_thread *thread) { if (unlikely(thread->m_program_hash_pins == NULL)) { if (! program_hash_inited) return NULL; thread->m_program_hash_pins= lf_hash_get_pins(&program_hash); } return thread->m_program_hash_pins; } PFS_program* find_or_create_program(PFS_thread *thread, enum_object_type object_type, const char *object_name, uint object_name_length, const char *schema_name, uint schema_name_length) { bool is_enabled, is_timed; LF_PINS *pins= get_program_hash_pins(thread); if (unlikely(pins == NULL)) { global_program_container.m_lost++; return NULL; } /* Prepare program key */ PFS_program_key key; set_program_key(&key, object_type, object_name, object_name_length, schema_name, schema_name_length); PFS_program **entry; PFS_program *pfs= NULL; uint retry_count= 0; const uint retry_max= 3; pfs_dirty_state dirty_state; search: entry= reinterpret_cast<PFS_program**> (lf_hash_search(&program_hash, pins, key.m_hash_key, key.m_key_length)); if (entry && (entry != MY_ERRPTR)) { /* If record already exists then return its pointer. */ pfs= *entry; lf_hash_search_unpin(pins); return pfs; } lf_hash_search_unpin(pins); /* First time while inserting this record to program array we need to find out if it is enabled and timed. */ lookup_setup_object(thread, object_type, schema_name, schema_name_length, object_name, object_name_length, &is_enabled, &is_timed); /* Else create a new record in program stat array. */ pfs= global_program_container.allocate(& dirty_state); if (pfs != NULL) { /* Do the assignments. */ memcpy(pfs->m_key.m_hash_key, key.m_hash_key, key.m_key_length); pfs->m_key.m_key_length= key.m_key_length; pfs->m_type= object_type; pfs->m_object_name= pfs->m_key.m_hash_key + 1; pfs->m_object_name_length= object_name_length; pfs->m_schema_name= pfs->m_object_name + object_name_length + 1; pfs->m_schema_name_length= schema_name_length; pfs->m_enabled= is_enabled; pfs->m_timed= is_timed; /* Insert this record. */ pfs->m_lock.dirty_to_allocated(& dirty_state); int res= lf_hash_insert(&program_hash, pins, &pfs); if (likely(res == 0)) { return pfs; } global_program_container.deallocate(pfs); if (res > 0) { /* Duplicate insert by another thread */ if (++retry_count > retry_max) { /* Avoid infinite loops */ global_program_container.m_lost++; return NULL; } goto search; } /* OOM in lf_hash_insert */ global_program_container.m_lost++; return NULL; } return NULL; } void drop_program(PFS_thread *thread, enum_object_type object_type, const char *object_name, uint object_name_length, const char *schema_name, uint schema_name_length) { LF_PINS *pins= get_program_hash_pins(thread); if (unlikely(pins == NULL)) return; /* Prepare program key */ PFS_program_key key; set_program_key(&key, object_type, object_name, object_name_length, schema_name, schema_name_length); PFS_program **entry; entry= reinterpret_cast<PFS_program**> (lf_hash_search(&program_hash, pins, key.m_hash_key, key.m_key_length)); if (entry && (entry != MY_ERRPTR)) { PFS_program *pfs= NULL; pfs= *entry; lf_hash_delete(&program_hash, pins, key.m_hash_key, key.m_key_length); global_program_container.deallocate(pfs); } lf_hash_search_unpin(pins); return; } void PFS_program::refresh_setup_object_flags(PFS_thread *thread) { lookup_setup_object(thread, m_type, m_schema_name, m_schema_name_length, m_object_name, m_object_name_length, &m_enabled, &m_timed); }
gpl-2.0
jlahm/Belize-openSIS
functions/CustomFields.fnc.php
6567
<?php /* Call in an SQL statement to select students based on custom fields Use in the where section of the query by CustomFIelds('where') */ function CustomFields($location,$table_arr='') { global $_openSIS; if(count($_REQUEST['month_cust_begin'])) { foreach($_REQUEST['month_cust_begin'] as $field_name=>$month) { $_REQUEST['cust_begin'][$field_name] = $_REQUEST['day_cust_begin'][$field_name].'-'.$_REQUEST['month_cust_begin'][$field_name].'-'.$_REQUEST['year_cust_begin'][$field_name]; $_REQUEST['cust_end'][$field_name] = $_REQUEST['day_cust_end'][$field_name].'-'.$_REQUEST['month_cust_end'][$field_name].'-'.$_REQUEST['year_cust_end'][$field_name]; if(!VerifyDate($_REQUEST['cust_begin'][$field_name]) || !VerifyDate($_REQUEST['cust_end'][$field_name])) { unset($_REQUEST['cust_begin'][$field_name]); unset($_REQUEST['cust_end'][$field_name]); } } unset($_REQUEST['month_cust_begin']);unset($_REQUEST['year_cust_begin']);unset($_REQUEST['day_cust_begin']); unset($_REQUEST['month_cust_end']);unset($_REQUEST['year_cust_end']);unset($_REQUEST['day_cust_end']); } if(count($_REQUEST['cust'])) { foreach($_REQUEST['cust'] as $key=>$value) { if($value=='') unset($_REQUEST['cust'][$key]); } } switch($location) { case 'from': break; case 'where': if(count($_REQUEST['cust']) || count($_REQUEST['cust_begin'])) $fields = DBGet(DBQuery("SELECT TITLE,ID,TYPE,SYSTEM_FIELD FROM CUSTOM_FIELDS"),array(),array('ID')); if(count($_REQUEST['cust'])) { foreach($_REQUEST['cust'] as $id => $value) { $field_name = $id; $id = substr($id,7); if($fields[$id][1]['SYSTEM_FIELD'] == 'Y') $field_name = strtoupper(str_replace(' ','_',$fields[$id][1]['TITLE'])); if($value!='') { switch($fields[$id][1]['TYPE']) { case 'radio': $_openSIS['SearchTerms'] .= '<font color=gray><b>'.$fields[$id][1]['TITLE'].': </b></font>'; if($value=='Y') { $string .= " and s.$field_name='$value' "; $_openSIS['SearchTerms'] .= 'Yes'; } elseif($value=='N') { $string .= " and (s.$field_name!='Y' OR s.$field_name IS NULL) "; $_openSIS['SearchTerms'] .= 'No'; } $_openSIS['SearchTerms'] .= '<BR>'; break; case 'codeds': $_openSIS['SearchTerms'] .= '<font color=gray><b>'.$fields[$id][1]['TITLE'].': </b></font>'; if($value=='!') { $string .= " and (s.$field_name='' OR s.$field_name IS NULL) "; $_openSIS['SearchTerms'] .= 'No Value'; } else { $string .= " and s.$field_name='$value' "; $_openSIS['SearchTerms'] .= $value; } $_openSIS['SearchTerms'] .= '<BR>'; break; case 'select': $_openSIS['SearchTerms'] .= '<font color=gray><b>'.$fields[$id][1]['TITLE'].': </b></font>'; if($value=='!') { $string .= " and (s.$field_name='' OR s.$field_name IS NULL) "; $_openSIS['SearchTerms'] .= 'No Value'; } else { $string .= " and s.$field_name='$value' "; $_openSIS['SearchTerms'] .= $value; } $_openSIS['SearchTerms'] .= '<BR>'; break; case 'autos': $_openSIS['SearchTerms'] .= '<font color=gray><b>'.$fields[$id][1]['TITLE'].': </b></font>'; if($value=='!') { $string .= " and (s.$field_name='' OR s.$field_name IS NULL) "; $_openSIS['SearchTerms'] .= 'No Value'; } else { $string .= " and s.$field_name='$value' "; $_openSIS['SearchTerms'] .= $value; } $_openSIS['SearchTerms'] .= '<BR>'; break; case 'edits': $_openSIS['SearchTerms'] .= '<font color=gray><b>'.$fields[$id][1]['TITLE'].': </b></font>'; if($value=='!') { $string .= " and (s.$field_name='' OR s.$field_name IS NULL) "; $_openSIS['SearchTerms'] .= 'No Value'; } elseif($value=='~') { $string .= " and position('\n'||s.$field_name||'\r' IN '\n'||(SELECT SELECT_OPTIONS FROM CUSTOM_FIELDS WHERE ID='".$id."')||'\r')=0 "; $_openSIS['SearchTerms'] .= 'Other'; } else { $string .= " and s.$field_name='$value' "; $_openSIS['SearchTerms'] .= $value; } $_openSIS['SearchTerms'] .= '<BR>'; break; case 'text': if(substr($value,0,2)=='\"' && substr($value,-2)=='\"') { $string .= " and s.$field_name='".substr($value,2,-2)."' "; $_openSIS['SearchTerms'] .= '<font color=gray><b>'.$fields[$id][1]['TITLE'].': </b></font>'.substr($value,2,-2).'<BR>'; } else { $string .= " and LOWER(s.$field_name) LIKE '".strtolower($value)."%' "; $_openSIS['SearchTerms'] .= '<font color=gray><b>'.$fields[$id][1]['TITLE'].' starts with: </b></font>'.$value.'<BR>'; } break; } } } } if(count($_REQUEST['cust_begin'])) { foreach($_REQUEST['cust_begin'] as $id => $value) { $field_name = $id; $id = substr($id,7); $column_name = $field_name; if($fields[$id][1]['SYSTEM_FIELD'] == 'Y') $column_name = strtoupper(str_replace(' ','_',$fields[$id][1]['TITLE'])); if($fields[$id][1]['TYPE']=='numeric') { $_REQUEST['cust_end'][$field_name] = ereg_replace('[^0-9.-]+','',$_REQUEST['cust_end'][$field_name]); $value = ereg_replace('[^0-9.-]+','',$value); } if($_REQUEST['cust_begin'][$field_name]!='' && $_REQUEST['cust_end'][$field_name]!='') { if($fields[$id][1]['TYPE']=='numeric' && $_REQUEST['cust_begin'][$field_name]>$_REQUEST['cust_end'][$field_name]) { $temp = $_REQUEST['cust_end'][$field_name]; $_REQUEST['cust_end'][$field_name] = $value; $value = $temp; } $string .= " and s.$column_name BETWEEN '$value' AND '".$_REQUEST['cust_end'][$field_name]."' "; if($fields[$id][1]['TYPE']=='date') $_openSIS['SearchTerms'] .= '<font color=gray><b>'.$fields[$id][1]['TITLE'].' between: </b></font>'.ProperDate($value).' &amp; '.ProperDate($_REQUEST['cust_end'][$field_name]).'<BR>'; else $_openSIS['SearchTerms'] .= '<font color=gray><b>'.$fields[$id][1]['TITLE'].' between: </b></font>'.$value.' &amp; '.$_REQUEST['cust_end'][$field_name].'<BR>'; } } } break; } return $string; } ?>
gpl-2.0
timroes/awesome
docs/06-appearance.md.lua
6204
#! /usr/bin/lua local args = {...} local gio = require("lgi").Gio local gobject = require("lgi").GObject local glib = require("lgi").GLib local name_attr = gio.FILE_ATTRIBUTE_STANDARD_NAME local type_attr = gio.FILE_ATTRIBUTE_STANDARD_TYPE -- Like pairs(), but iterate over keys in a sorted manner. Does not support -- modifying the table while iterating. local function sorted_pairs(t) -- Collect all keys local keys = {} for k in pairs(t) do table.insert(keys, k) end table.sort(keys) -- return iterator function local i = 0 return function() i = i + 1 if keys[i] then return keys[i], t[keys[i]] end end end -- Recursive file scanner local function get_all_files(path, ext, ret) ret = ret or {} local enumerator = gio.File.new_for_path(path):enumerate_children( table.concat({name_attr, type_attr}, ",") , 0, nil, nil ) for file in function() return enumerator:next_file() end do local file_name = file:get_attribute_as_string(name_attr) local file_type = file:get_file_type() if file_type == "REGULAR" and file_name:match(ext or "") then table.insert(ret, enumerator:get_child(file):get_path()) elseif file_type == "DIRECTORY" then get_all_files(enumerator:get_child(file):get_path(), ext, ret) end end return ret end local function path_to_module(path) for _, module in ipairs { "awful", "wibox", "gears", "naughty", "menubar", "beautiful" } do local match = path:match("/"..module.."/([^.]+).lua") if match then return module.."."..match:gsub("/",".") end end error("Cannot figure out module for " .. tostring(path)) end local function path_to_html(path) local mod = path_to_module(path):gsub(".init", "") local f = assert(io.open(path)) while true do local line = f:read() if not line then break end if line:match("@classmod") then f:close() return "../classes/".. mod ..".html" end if line:match("@module") or line:match("@submodule") then f:close() return "../libraries/".. mod ..".html" end end f:close() error("Cannot figure out if module or class: " .. tostring(path)) end local function get_link(file, element) return table.concat { "<a href='", path_to_html(file), "#", element, "'>", element:match("[. ](.+)"), "</a>" } end local all_files = get_all_files("./lib/", "lua") local beautiful_vars = {} -- Find all @beautiful doc entries for _,file in ipairs(all_files) do local f = io.open(file) local buffer = "" for line in f:lines() do local var = line:gmatch("--[ ]*@beautiful ([^ \n]*)")() -- There is no backward/forward pattern in lua if #line <= 1 then buffer = "" elseif #buffer and not var then buffer = buffer.."\n"..line elseif line:sub(1,3) == "---" then buffer = line end if var then -- Get the @param, @see and @usage local params = "" for line in f:lines() do if line:sub(1,2) ~= "--" then break else params = params.."\n"..line end end local name = var:gmatch("[ ]*beautiful.(.+)")() if not name then print("WARNING:", var, "seems to be misformatted. Use `beautiful.namespace_name`" ) else table.insert(beautiful_vars, { file = file, name = name, link = get_link(file, var), desc = buffer:gmatch("[- ]+([^\n.]*)")() or "", mod = path_to_module(file), }) end buffer = "" end end end local function create_table(entries, columns) local lines = {} for _, entry in ipairs(entries) do local line = " <tr>" for _, column in ipairs(columns) do line = line.."<td>"..entry[column].."</td>" end table.insert(lines, line.."</tr>\n") end return [[<br \><br \><table class='widget_list' border=1> <tr style='font-weight: bold;'> <th align='center'>Name</th> <th align='center'>Description</th> </tr>]] .. table.concat(lines) .. "</table>\n" end local override_cats = { ["border" ] = true, ["bg" ] = true, ["fg" ] = true, ["useless" ] = true, ["" ] = true, } local function categorize(entries) local ret = {} local cats = { ["Default variables"] = {} } for _, v in ipairs(entries) do local ns = v.name:match("([^_]+)_") or "" ns = override_cats[ns] and "Default variables" or ns cats[ns] = cats[ns] or {} table.insert(cats[ns], v) end return cats end local function create_sample(entries) local ret = { " local theme = {}" } for name, cat in sorted_pairs(categorize(entries)) do table.insert(ret, "\n -- "..name) for _, v in ipairs(cat) do table.insert(ret, " -- theme."..v.name.." = nil") end end table.insert(ret, [[ return theme -- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80]] ) return table.concat(ret, '\n') end -- Create the file local filename = args[1] local f = io.open(filename, "w") f:write[[ # Change Awesome appearance ## The beautiful themes Beautiful is where Awesome theme variables are stored. ]] f:write(create_table(beautiful_vars, {"link", "desc"})) f:write("\n\n## Sample theme file\n\n") f:write(create_sample(beautiful_vars, {"link", "desc"})) f:close() --TODO add some linting to direct undeclared beautiful variables --TODO re-generate all official themes --TODO generate a complete sample theme --TODO also parse C files. -- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
gpl-2.0
karlstroetmann/Formal-Languages
Java/Differentiate/Expr.java
111
public abstract class Expr { // var is the name of a variable public abstract Expr diff(String var); }
gpl-2.0
dyon/skcore
src/server/scripts/Northrend/Ulduar/Ulduar/boss_ignis.cpp
23010
/* * Copyright (C) 2008-2013 TrinityCore <http://www.trinitycore.org/> * * 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, see <http://www.gnu.org/licenses/>. */ #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "SpellScript.h" #include "SpellAuraEffects.h" #include "ulduar.h" #include "Vehicle.h" enum Yells { SAY_AGGRO = 0, SAY_SLAY = 1, SAY_DEATH = 2, SAY_SUMMON = 3, SAY_SLAG_POT = 4, SAY_SCORCH = 5, SAY_BERSERK = 6, EMOTE_JETS = 7 }; enum Spells { SPELL_FLAME_JETS = 62680, SPELL_SCORCH = 62546, SPELL_SLAG_POT = 62717, SPELL_SLAG_POT_DAMAGE = 65722, SPELL_SLAG_IMBUED = 62836, SPELL_ACTIVATE_CONSTRUCT = 62488, SPELL_STRENGTH = 64473, SPELL_GRAB = 62707, SPELL_BERSERK = 47008, SPELL_GRAB_ENTER_VEHICLE = 62711, // Iron Construct SPELL_HEAT = 65667, SPELL_MOLTEN = 62373, SPELL_BRITTLE_10 = 62382, SPELL_BRITTLE_25 = 67114, SPELL_SHATTER = 62383, SPELL_GROUND = 62548, SPELL_FREEZE_ANIM = 63354 }; #define SPELL_BRITTLE RAID_MODE(SPELL_BRITTLE_10, SPELL_BRITTLE_25) enum Events { EVENT_JET = 1, EVENT_SCORCH = 2, EVENT_SLAG_POT = 3, EVENT_GRAB_POT = 4, EVENT_CHANGE_POT = 5, EVENT_END_POT = 6, EVENT_CONSTRUCT = 7, EVENT_BERSERK = 8 }; enum Actions { ACTION_REMOVE_BUFF = 20 }; enum Creatures { NPC_IRON_CONSTRUCT = 33121, NPC_GROUND_SCORCH = 33221 }; enum AchievementData { DATA_SHATTERED = 29252926, ACHIEVEMENT_IGNIS_START_EVENT = 20951, ACHIEVEMENT_SHATTERED_TIME_LIMIT = 5*IN_MILLISECONDS }; #define CONSTRUCT_SPAWN_POINTS 20 Position const ConstructSpawnPosition[CONSTRUCT_SPAWN_POINTS] = { {630.366f, 216.772f, 360.891f, 3.001970f}, {630.594f, 231.846f, 360.891f, 3.124140f}, {630.435f, 337.246f, 360.886f, 3.211410f}, {630.493f, 313.349f, 360.886f, 3.054330f}, {630.444f, 321.406f, 360.886f, 3.124140f}, {630.366f, 247.307f, 360.888f, 3.211410f}, {630.698f, 305.311f, 360.886f, 3.001970f}, {630.500f, 224.559f, 360.891f, 3.054330f}, {630.668f, 239.840f, 360.890f, 3.159050f}, {630.384f, 329.585f, 360.886f, 3.159050f}, {543.220f, 313.451f, 360.886f, 0.104720f}, {543.356f, 329.408f, 360.886f, 6.248280f}, {543.076f, 247.458f, 360.888f, 6.213370f}, {543.117f, 232.082f, 360.891f, 0.069813f}, {543.161f, 305.956f, 360.886f, 0.157080f}, {543.277f, 321.482f, 360.886f, 0.052360f}, {543.316f, 337.468f, 360.886f, 6.195920f}, {543.280f, 239.674f, 360.890f, 6.265730f}, {543.265f, 217.147f, 360.891f, 0.174533f}, {543.256f, 224.831f, 360.891f, 0.122173f} }; /* TODO: - Shatter Achievement (2925/2926) */ class AchievShatterHelper { public: explicit AchievShatterHelper(const uint64 timeLimit) : gotInformed(false), achievFulfilled(false), timer(0), limit(timeLimit) {} // Called when an Iron Construct got Shattered void Inform() { if (achievFulfilled) return; // Nothing to be done if (gotInformed) // Check if timer is ok { if (timer <= limit) achievFulfilled = true; } else // First information, start tracking { gotInformed = true; timer = 0; } } void Reset() { gotInformed = achievFulfilled = false; timer = 0; } // Updated by boss script void Update(uint32 diff) { if (achievFulfilled || !gotInformed) // Nothing to be done if achievement got already fulfilled, or tracking was not started yet. return; timer += diff; if (timer > limit) // Check timeout { gotInformed = false; timer = 0; } } bool GotAchievFulfilled() const { return achievFulfilled; } private: bool gotInformed; // Starts time-tracking bool achievFulfilled; // Set if achievement was completed successfully const uint64 limit; // Time-limit, set on construction uint64 timer; // Current timer }; class boss_ignis : public CreatureScript { public: boss_ignis() : CreatureScript("boss_ignis") { } struct boss_ignis_AI : public BossAI { boss_ignis_AI(Creature* creature) : BossAI(creature, BOSS_IGNIS), vehicle(me->GetVehicleKit()), shatteredHelper(ACHIEVEMENT_SHATTERED_TIME_LIMIT) { ASSERT(vehicle); } void Reset() { _Reset(); if (vehicle) vehicle->RemoveAllPassengers(); summons.DespawnAll(); shatteredHelper.Reset(); for (uint8 i = 0; i < CONSTRUCT_SPAWN_POINTS; i++) if (Creature* construct = me->SummonCreature(NPC_IRON_CONSTRUCT, ConstructSpawnPosition[i])) summons.Summon(construct); instance->DoStopTimedAchievement(ACHIEVEMENT_TIMED_TYPE_EVENT, ACHIEVEMENT_IGNIS_START_EVENT); } void EnterCombat(Unit* /*who*/) { _EnterCombat(); Talk(SAY_AGGRO); events.ScheduleEvent(EVENT_JET, 30*IN_MILLISECONDS); events.ScheduleEvent(EVENT_SCORCH, 25*IN_MILLISECONDS); events.ScheduleEvent(EVENT_SLAG_POT, 35*IN_MILLISECONDS); events.ScheduleEvent(EVENT_CONSTRUCT, 15*IN_MILLISECONDS); events.ScheduleEvent(EVENT_END_POT, 40*IN_MILLISECONDS); events.ScheduleEvent(EVENT_BERSERK, 8*MINUTE*IN_MILLISECONDS); slagPotGUID = 0; instance->DoStartTimedAchievement(ACHIEVEMENT_TIMED_TYPE_EVENT, ACHIEVEMENT_IGNIS_START_EVENT); } void JustDied(Unit* /*victim*/) { _JustDied(); Talk(SAY_DEATH); if (shatteredHelper.GotAchievFulfilled()) { instance->DoCompleteAchievement(RAID_MODE(2925,2926)); } } void SummonedCreatureDespawn(Creature* summon) // Gets called then an Iron Construct despawns through its own script { if (summon->GetEntry() == NPC_IRON_CONSTRUCT) summons.Despawn(summon); } void SummonedCreatureDies(Creature* summon, Unit* /*killer*/) { if (summon->GetEntry() == NPC_IRON_CONSTRUCT) summons.Despawn(summon); } uint32 GetData(uint32 type) const { if (type == DATA_SHATTERED) return shatteredHelper.GotAchievFulfilled() ? 1 : 0; return 0; } void KilledUnit(Unit* /*victim*/) { if (!urand(0,5)) Talk(SAY_SLAY); } void DoAction(int32 action) { switch (action) { case ACTION_REMOVE_BUFF: // Action is called every time a construct is shattered. me->RemoveAuraFromStack(SPELL_STRENGTH); // Shattered Achievement - testing stage shatteredHelper.Inform(); break; default: break; } } void UpdateAI(uint32 diff) { if (!UpdateVictim()) return; shatteredHelper.Update(diff); events.Update(diff); if (me->HasUnitState(UNIT_STATE_CASTING)) return; while (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_JET: Talk(EMOTE_JETS); DoCast(me, SPELL_FLAME_JETS); events.DelayEvents(5*IN_MILLISECONDS); // Cast time events.ScheduleEvent(EVENT_JET, urand(35*IN_MILLISECONDS, 40*IN_MILLISECONDS)); return; case EVENT_SLAG_POT: if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 1, 0.0f, true)) { Talk(SAY_SLAG_POT); slagPotGUID = target->GetGUID(); DoCast(target, SPELL_GRAB); events.DelayEvents(3*IN_MILLISECONDS); events.ScheduleEvent(EVENT_GRAB_POT, 0.5*IN_MILLISECONDS); } events.ScheduleEvent(EVENT_SLAG_POT, RAID_MODE(30*IN_MILLISECONDS, 15*IN_MILLISECONDS)); return; case EVENT_GRAB_POT: if (Unit* slagPotTarget = ObjectAccessor::GetUnit(*me, slagPotGUID)) { slagPotTarget->EnterVehicle(me, 1); events.ScheduleEvent(EVENT_CHANGE_POT, 1*IN_MILLISECONDS); } return; case EVENT_CHANGE_POT: if (Unit* slagPotTarget = ObjectAccessor::GetUnit(*me, slagPotGUID)) { slagPotTarget->EnterVehicle(me, 1); slagPotTarget->ClearUnitState(UNIT_STATE_ONVEHICLE); DoCast(slagPotTarget, SPELL_SLAG_POT); events.ScheduleEvent(EVENT_END_POT, 10*IN_MILLISECONDS); } return; case EVENT_END_POT: if (Unit* slagPotTarget = ObjectAccessor::GetUnit(*me, slagPotGUID)) { slagPotTarget->ExitVehicle(); slagPotGUID = 0; } return; case EVENT_SCORCH: Talk(SAY_SCORCH); if (Unit* target = me->getVictim()) me->SummonCreature(NPC_GROUND_SCORCH, target->GetPositionX(), target->GetPositionY(), target->GetPositionZ(), 0, TEMPSUMMON_TIMED_DESPAWN, 45*IN_MILLISECONDS); DoCast(SPELL_SCORCH); events.ScheduleEvent(EVENT_SCORCH, 25*IN_MILLISECONDS); return; case EVENT_CONSTRUCT: if (!summons.empty()) { Talk(SAY_SUMMON); DoCast(me, SPELL_ACTIVATE_CONSTRUCT); events.ScheduleEvent(EVENT_CONSTRUCT, RAID_MODE(40*IN_MILLISECONDS, 30*IN_MILLISECONDS)); } return; case EVENT_BERSERK: DoCast(me, SPELL_BERSERK, true); Talk(SAY_BERSERK); return; default: return; } } DoMeleeAttackIfReady(); EnterEvadeIfOutOfCombatArea(diff); } private: AchievShatterHelper shatteredHelper; uint64 slagPotGUID; Vehicle* vehicle; }; CreatureAI* GetAI(Creature* creature) const { return GetUlduarAI<boss_ignis_AI>(creature); } }; class npc_iron_construct : public CreatureScript { public: npc_iron_construct() : CreatureScript("npc_iron_construct") { } struct npc_iron_constructAI : public ScriptedAI { npc_iron_constructAI(Creature* creature) : ScriptedAI(creature), instance(creature->GetInstanceScript()) { creature->setActive(true); creature->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_STUNNED | UNIT_FLAG_DISABLE_MOVE); DoCast(me, SPELL_FREEZE_ANIM, true); } void Reset() { me->SetReactState(REACT_PASSIVE); brittled = false; } void JustReachedHome() { me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_STUNNED | UNIT_FLAG_DISABLE_MOVE); DoCast(me, SPELL_FREEZE_ANIM, true); } void DamageTaken(Unit* /*attacker*/, uint32& damage) { if (me->HasAura(SPELL_BRITTLE) && damage >= 5*IN_MILLISECONDS) { DoCast(SPELL_SHATTER); if (Creature* ignis = ObjectAccessor::GetCreature(*me, instance->GetData64(BOSS_IGNIS))) if (ignis->AI()) ignis->AI()->DoAction(ACTION_REMOVE_BUFF); me->DespawnOrUnsummon(1*IN_MILLISECONDS); } } void SpellHit(Unit* /*caster*/, SpellInfo const* spell) { if (spell->Id == SPELL_ACTIVATE_CONSTRUCT) { me->RemoveAurasDueToSpell(SPELL_FREEZE_ANIM); me->SetReactState(REACT_AGGRESSIVE); me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_STUNNED | UNIT_FLAG_DISABLE_MOVE); me->AI()->DoZoneInCombat(); if (Creature* ignis = ObjectAccessor::GetCreature(*me, instance->GetData64(BOSS_IGNIS))) { me->AI()->AttackStart(ignis->getVictim()); ignis->CastSpell(ignis, SPELL_STRENGTH, true); } } } void UpdateAI(uint32 /*uiDiff*/) { if (!UpdateVictim()) return; if (Aura* aur = me->GetAura(SPELL_HEAT)) { if (aur->GetStackAmount() >= 10) { me->RemoveAura(SPELL_HEAT); DoCast(SPELL_MOLTEN); brittled = false; } } // Water pools if (me->IsInWater() && !brittled && me->HasAura(SPELL_MOLTEN)) { DoCast(SPELL_BRITTLE); me->RemoveAura(SPELL_MOLTEN); brittled = true; } DoMeleeAttackIfReady(); } private: InstanceScript* instance; bool brittled; }; CreatureAI* GetAI(Creature* creature) const { return GetUlduarAI<npc_iron_constructAI>(creature); } }; class npc_scorch_ground : public CreatureScript { public: npc_scorch_ground() : CreatureScript("npc_scorch_ground") { } struct npc_scorch_groundAI : public ScriptedAI { npc_scorch_groundAI(Creature* creature) : ScriptedAI(creature) { me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE |UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_PACIFIED); creature->SetDisplayId(16925); //model 2 in db cannot overwrite wdb fields } void MoveInLineOfSight(Unit* unit) { if (!heat) { if (unit->GetEntry() == NPC_IRON_CONSTRUCT) { if (!unit->HasAura(SPELL_HEAT) || !unit->HasAura(SPELL_MOLTEN)) { constructGUID = unit->GetGUID(); heat = true; } } } } void Reset() { heat = false; DoCast(me, SPELL_GROUND); constructGUID = 0; heatTimer = 0; } void UpdateAI(uint32 uiDiff) { if (heat) { if (heatTimer <= uiDiff) { Creature* construct = me->GetCreature(*me, constructGUID); if (construct && !construct->HasAura(SPELL_MOLTEN)) { me->AddAura(SPELL_HEAT, construct); heatTimer = 1*IN_MILLISECONDS; } } else heatTimer -= uiDiff; } } private: uint64 constructGUID; uint32 heatTimer; bool heat; }; CreatureAI* GetAI(Creature* creature) const { return GetUlduarAI<npc_scorch_groundAI>(creature); } }; class spell_ignis_slag_pot : public SpellScriptLoader { public: spell_ignis_slag_pot() : SpellScriptLoader("spell_ignis_slag_pot") { } class spell_ignis_slag_pot_AuraScript : public AuraScript { PrepareAuraScript(spell_ignis_slag_pot_AuraScript); bool Validate(SpellInfo const* /*spellEntry*/) { if (!sSpellMgr->GetSpellInfo(SPELL_SLAG_POT_DAMAGE)) return false; if (!sSpellMgr->GetSpellInfo(SPELL_SLAG_IMBUED)) return false; return true; } void HandleEffectPeriodic(AuraEffect const* aurEff) { Unit* aurEffCaster = aurEff->GetCaster(); if (!aurEffCaster) return; Unit* target = GetTarget(); aurEffCaster->CastSpell(target, SPELL_SLAG_POT_DAMAGE, true); } void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) { if (GetTarget()->isAlive()) GetTarget()->CastSpell(GetTarget(), SPELL_SLAG_IMBUED, true); } void Register() { OnEffectPeriodic += AuraEffectPeriodicFn(spell_ignis_slag_pot_AuraScript::HandleEffectPeriodic, EFFECT_0, SPELL_AURA_PERIODIC_DUMMY); AfterEffectRemove += AuraEffectRemoveFn(spell_ignis_slag_pot_AuraScript::OnRemove, EFFECT_0, SPELL_AURA_PERIODIC_DUMMY, AURA_EFFECT_HANDLE_REAL); } }; AuraScript* GetAuraScript() const { return new spell_ignis_slag_pot_AuraScript(); } }; // Selector removes targets that are neither player not pets class spell_ignis_flame_jets : public SpellScriptLoader { public: spell_ignis_flame_jets() : SpellScriptLoader("spell_ignis_flame_jets") { } class spell_ignis_flame_jets_SpellScript : public SpellScript { PrepareSpellScript(spell_ignis_flame_jets_SpellScript); void FilterTargets(std::list<WorldObject*>& targets) { targets.remove_if(PlayerOrPetCheck()); } void Register() { OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_ignis_flame_jets_SpellScript::FilterTargets, EFFECT_0, TARGET_UNIT_SRC_AREA_ENEMY); OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_ignis_flame_jets_SpellScript::FilterTargets, EFFECT_1, TARGET_UNIT_SRC_AREA_ENEMY); OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_ignis_flame_jets_SpellScript::FilterTargets, EFFECT_2, TARGET_UNIT_SRC_AREA_ENEMY); } }; SpellScript* GetSpellScript() const { return new spell_ignis_flame_jets_SpellScript(); } }; class spell_ignis_activate_construct : public SpellScriptLoader { public: spell_ignis_activate_construct() : SpellScriptLoader("spell_ignis_activate_construct") {} class spell_ignis_activate_construct_SpellScript : public SpellScript { PrepareSpellScript(spell_ignis_activate_construct_SpellScript); void FilterTargets(std::list<WorldObject*>& targets) { if (WorldObject* _target = Trinity::Containers::SelectRandomContainerElement(targets)) { targets.clear(); targets.push_back(_target); } } void Register() { OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_ignis_activate_construct_SpellScript::FilterTargets, EFFECT_0, TARGET_UNIT_SRC_AREA_ENTRY); } }; SpellScript* GetSpellScript() const { return new spell_ignis_activate_construct_SpellScript(); } }; class achievement_ignis_shattered : public AchievementCriteriaScript { public: achievement_ignis_shattered() : AchievementCriteriaScript("achievement_ignis_shattered") { } bool OnCheck(Player* /*source*/, Unit* target) { if (target && target->IsAIEnabled) return target->GetAI()->GetData(DATA_SHATTERED); return false; } }; void AddSC_boss_ignis() { new boss_ignis(); new npc_iron_construct(); new npc_scorch_ground(); new spell_ignis_slag_pot(); new spell_ignis_flame_jets(); new achievement_ignis_shattered(); new spell_ignis_activate_construct(); } #undef SPELL_BRITTLE
gpl-2.0
md-5/jdk10
src/hotspot/share/runtime/globals.hpp
193758
/* * Copyright (c) 1997, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ #ifndef SHARE_RUNTIME_GLOBALS_HPP #define SHARE_RUNTIME_GLOBALS_HPP #include "compiler/compiler_globals.hpp" #include "gc/shared/gc_globals.hpp" #include "runtime/globals_shared.hpp" #include "utilities/align.hpp" #include "utilities/globalDefinitions.hpp" #include "utilities/macros.hpp" #include CPU_HEADER(globals) #include OS_HEADER(globals) #include OS_CPU_HEADER(globals) // develop flags are settable / visible only during development and are constant in the PRODUCT version // product flags are always settable / visible // notproduct flags are settable / visible only during development and are not declared in the PRODUCT version // A flag must be declared with one of the following types: // bool, int, uint, intx, uintx, size_t, ccstr, ccstrlist, double, or uint64_t. // The type "ccstr" and "ccstrlist" are an alias for "const char*" and is used // only in this file, because the macrology requires single-token type names. // Note: Diagnostic options not meant for VM tuning or for product modes. // They are to be used for VM quality assurance or field diagnosis // of VM bugs. They are hidden so that users will not be encouraged to // try them as if they were VM ordinary execution options. However, they // are available in the product version of the VM. Under instruction // from support engineers, VM customers can turn them on to collect // diagnostic information about VM problems. To use a VM diagnostic // option, you must first specify +UnlockDiagnosticVMOptions. // (This master switch also affects the behavior of -Xprintflags.) // // experimental flags are in support of features that are not // part of the officially supported product, but are available // for experimenting with. They could, for example, be performance // features that may not have undergone full or rigorous QA, but which may // help performance in some cases and released for experimentation // by the community of users and developers. This flag also allows one to // be able to build a fully supported product that nonetheless also // ships with some unsupported, lightly tested, experimental features. // Like the UnlockDiagnosticVMOptions flag above, there is a corresponding // UnlockExperimentalVMOptions flag, which allows the control and // modification of the experimental flags. // // Nota bene: neither diagnostic nor experimental options should be used casually, // and they are not supported on production loads, except under explicit // direction from support engineers. // // manageable flags are writeable external product flags. // They are dynamically writeable through the JDK management interface // (com.sun.management.HotSpotDiagnosticMXBean API) and also through JConsole. // These flags are external exported interface (see CCC). The list of // manageable flags can be queried programmatically through the management // interface. // // A flag can be made as "manageable" only if // - the flag is defined in a CCC as an external exported interface. // - the VM implementation supports dynamic setting of the flag. // This implies that the VM must *always* query the flag variable // and not reuse state related to the flag state at any given time. // - you want the flag to be queried programmatically by the customers. // // product_rw flags are writeable internal product flags. // They are like "manageable" flags but for internal/private use. // The list of product_rw flags are internal/private flags which // may be changed/removed in a future release. It can be set // through the management interface to get/set value // when the name of flag is supplied. // // A flag can be made as "product_rw" only if // - the VM implementation supports dynamic setting of the flag. // This implies that the VM must *always* query the flag variable // and not reuse state related to the flag state at any given time. // // Note that when there is a need to support develop flags to be writeable, // it can be done in the same way as product_rw. // // range is a macro that will expand to min and max arguments for range // checking code if provided - see jvmFlagRangeList.hpp // // constraint is a macro that will expand to custom function call // for constraint checking if provided - see jvmFlagConstraintList.hpp // // writeable is a macro that controls if and how the value can change during the runtime // // writeable(Always) is optional and allows the flag to have its value changed // without any limitations at any time // // writeable(Once) flag value's can be only set once during the lifetime of VM // // writeable(CommandLineOnly) flag value's can be only set from command line // (multiple times allowed) // // Default and minimum StringTable and SymbolTable size values // Must be powers of 2 const size_t defaultStringTableSize = NOT_LP64(1024) LP64_ONLY(65536); const size_t minimumStringTableSize = 128; const size_t defaultSymbolTableSize = 32768; // 2^15 const size_t minimumSymbolTableSize = 1024; #define RUNTIME_FLAGS(develop, \ develop_pd, \ product, \ product_pd, \ diagnostic, \ diagnostic_pd, \ experimental, \ notproduct, \ manageable, \ product_rw, \ lp64_product, \ range, \ constraint, \ writeable) \ \ lp64_product(bool, UseCompressedOops, false, \ "Use 32-bit object references in 64-bit VM. " \ "lp64_product means flag is always constant in 32 bit VM") \ \ lp64_product(bool, UseCompressedClassPointers, false, \ "Use 32-bit class pointers in 64-bit VM. " \ "lp64_product means flag is always constant in 32 bit VM") \ \ notproduct(bool, CheckCompressedOops, true, \ "Generate checks in encoding/decoding code in debug VM") \ \ product(uintx, HeapSearchSteps, 3 PPC64_ONLY(+17), \ "Heap allocation steps through preferred address regions to find" \ " where it can allocate the heap. Number of steps to take per " \ "region.") \ range(1, max_uintx) \ \ lp64_product(intx, ObjectAlignmentInBytes, 8, \ "Default object alignment in bytes, 8 is minimum") \ range(8, 256) \ constraint(ObjectAlignmentInBytesConstraintFunc,AtParse) \ \ develop(bool, CleanChunkPoolAsync, true, \ "Clean the chunk pool asynchronously") \ \ diagnostic(uint, HandshakeTimeout, 0, \ "If nonzero set a timeout in milliseconds for handshakes") \ \ experimental(bool, AlwaysSafeConstructors, false, \ "Force safe construction, as if all fields are final.") \ \ diagnostic(bool, UnlockDiagnosticVMOptions, trueInDebug, \ "Enable normal processing of flags relating to field diagnostics")\ \ experimental(bool, UnlockExperimentalVMOptions, false, \ "Enable normal processing of flags relating to experimental " \ "features") \ \ product(bool, JavaMonitorsInStackTrace, true, \ "Print information about Java monitor locks when the stacks are" \ "dumped") \ \ product_pd(bool, UseLargePages, \ "Use large page memory") \ \ product_pd(bool, UseLargePagesIndividualAllocation, \ "Allocate large pages individually for better affinity") \ \ develop(bool, LargePagesIndividualAllocationInjectError, false, \ "Fail large pages individual allocation") \ \ product(bool, UseLargePagesInMetaspace, false, \ "Use large page memory in metaspace. " \ "Only used if UseLargePages is enabled.") \ \ product(bool, UseNUMA, false, \ "Use NUMA if available") \ \ product(bool, UseNUMAInterleaving, false, \ "Interleave memory across NUMA nodes if available") \ \ product(size_t, NUMAInterleaveGranularity, 2*M, \ "Granularity to use for NUMA interleaving on Windows OS") \ range(os::vm_allocation_granularity(), NOT_LP64(2*G) LP64_ONLY(8192*G)) \ \ product(bool, ForceNUMA, false, \ "Force NUMA optimizations on single-node/UMA systems") \ \ product(uintx, NUMAChunkResizeWeight, 20, \ "Percentage (0-100) used to weight the current sample when " \ "computing exponentially decaying average for " \ "AdaptiveNUMAChunkSizing") \ range(0, 100) \ \ product(size_t, NUMASpaceResizeRate, 1*G, \ "Do not reallocate more than this amount per collection") \ range(0, max_uintx) \ \ product(bool, UseAdaptiveNUMAChunkSizing, true, \ "Enable adaptive chunk sizing for NUMA") \ \ product(bool, NUMAStats, false, \ "Print NUMA stats in detailed heap information") \ \ product(uintx, NUMAPageScanRate, 256, \ "Maximum number of pages to include in the page scan procedure") \ range(0, max_uintx) \ \ product(intx, UseSSE, 99, \ "Highest supported SSE instructions set on x86/x64") \ range(0, 99) \ \ product(bool, UseAES, false, \ "Control whether AES instructions are used when available") \ \ product(bool, UseFMA, false, \ "Control whether FMA instructions are used when available") \ \ product(bool, UseSHA, false, \ "Control whether SHA instructions are used when available") \ \ diagnostic(bool, UseGHASHIntrinsics, false, \ "Use intrinsics for GHASH versions of crypto") \ \ product(bool, UseBASE64Intrinsics, false, \ "Use intrinsics for java.util.Base64") \ \ product(size_t, LargePageSizeInBytes, 0, \ "Large page size (0 to let VM choose the page size)") \ range(0, max_uintx) \ \ product(size_t, LargePageHeapSizeThreshold, 128*M, \ "Use large pages if maximum heap is at least this big") \ range(0, max_uintx) \ \ product(bool, ForceTimeHighResolution, false, \ "Using high time resolution (for Win32 only)") \ \ develop(bool, TracePcPatching, false, \ "Trace usage of frame::patch_pc") \ \ develop(bool, TraceRelocator, false, \ "Trace the bytecode relocator") \ \ develop(bool, TraceLongCompiles, false, \ "Print out every time compilation is longer than " \ "a given threshold") \ \ diagnostic(bool, SafepointALot, false, \ "Generate a lot of safepoints. This works with " \ "GuaranteedSafepointInterval") \ \ diagnostic(bool, HandshakeALot, false, \ "Generate a lot of handshakes. This works with " \ "GuaranteedSafepointInterval") \ \ product_pd(bool, BackgroundCompilation, \ "A thread requesting compilation is not blocked during " \ "compilation") \ \ product(bool, PrintVMQWaitTime, false, \ "Print out the waiting time in VM operation queue") \ \ product(bool, MethodFlushing, true, \ "Reclamation of zombie and not-entrant methods") \ \ develop(bool, VerifyStack, false, \ "Verify stack of each thread when it is entering a runtime call") \ \ diagnostic(bool, ForceUnreachable, false, \ "Make all non code cache addresses to be unreachable by " \ "forcing use of 64bit literal fixups") \ \ notproduct(bool, StressDerivedPointers, false, \ "Force scavenge when a derived pointer is detected on stack " \ "after rtm call") \ \ develop(bool, TraceDerivedPointers, false, \ "Trace traversal of derived pointers on stack") \ \ notproduct(bool, TraceCodeBlobStacks, false, \ "Trace stack-walk of codeblobs") \ \ notproduct(bool, PrintRewrites, false, \ "Print methods that are being rewritten") \ \ product(bool, UseInlineCaches, true, \ "Use Inline Caches for virtual calls ") \ \ diagnostic(bool, InlineArrayCopy, true, \ "Inline arraycopy native that is known to be part of " \ "base library DLL") \ \ diagnostic(bool, InlineObjectHash, true, \ "Inline Object::hashCode() native that is known to be part " \ "of base library DLL") \ \ diagnostic(bool, InlineNatives, true, \ "Inline natives that are known to be part of base library DLL") \ \ diagnostic(bool, InlineMathNatives, true, \ "Inline SinD, CosD, etc.") \ \ diagnostic(bool, InlineClassNatives, true, \ "Inline Class.isInstance, etc") \ \ diagnostic(bool, InlineThreadNatives, true, \ "Inline Thread.currentThread, etc") \ \ diagnostic(bool, InlineUnsafeOps, true, \ "Inline memory ops (native methods) from Unsafe") \ \ product(bool, CriticalJNINatives, true, \ "Check for critical JNI entry points") \ \ notproduct(bool, StressCriticalJNINatives, false, \ "Exercise register saving code in critical natives") \ \ diagnostic(bool, UseAESIntrinsics, false, \ "Use intrinsics for AES versions of crypto") \ \ diagnostic(bool, UseAESCTRIntrinsics, false, \ "Use intrinsics for the paralleled version of AES/CTR crypto") \ \ diagnostic(bool, UseSHA1Intrinsics, false, \ "Use intrinsics for SHA-1 crypto hash function. " \ "Requires that UseSHA is enabled.") \ \ diagnostic(bool, UseSHA256Intrinsics, false, \ "Use intrinsics for SHA-224 and SHA-256 crypto hash functions. " \ "Requires that UseSHA is enabled.") \ \ diagnostic(bool, UseSHA512Intrinsics, false, \ "Use intrinsics for SHA-384 and SHA-512 crypto hash functions. " \ "Requires that UseSHA is enabled.") \ \ diagnostic(bool, UseCRC32Intrinsics, false, \ "use intrinsics for java.util.zip.CRC32") \ \ diagnostic(bool, UseCRC32CIntrinsics, false, \ "use intrinsics for java.util.zip.CRC32C") \ \ diagnostic(bool, UseAdler32Intrinsics, false, \ "use intrinsics for java.util.zip.Adler32") \ \ diagnostic(bool, UseVectorizedMismatchIntrinsic, false, \ "Enables intrinsification of ArraysSupport.vectorizedMismatch()") \ \ diagnostic(ccstrlist, DisableIntrinsic, "", \ "do not expand intrinsics whose (internal) names appear here") \ \ develop(bool, TraceCallFixup, false, \ "Trace all call fixups") \ \ develop(bool, DeoptimizeALot, false, \ "Deoptimize at every exit from the runtime system") \ \ notproduct(ccstrlist, DeoptimizeOnlyAt, "", \ "A comma separated list of bcis to deoptimize at") \ \ develop(bool, DeoptimizeRandom, false, \ "Deoptimize random frames on random exit from the runtime system")\ \ notproduct(bool, ZombieALot, false, \ "Create zombies (non-entrant) at exit from the runtime system") \ \ notproduct(bool, WalkStackALot, false, \ "Trace stack (no print) at every exit from the runtime system") \ \ product(bool, Debugging, false, \ "Set when executing debug methods in debug.cpp " \ "(to prevent triggering assertions)") \ \ notproduct(bool, VerifyLastFrame, false, \ "Verify oops on last frame on entry to VM") \ \ product(bool, SafepointTimeout, false, \ "Time out and warn or fail after SafepointTimeoutDelay " \ "milliseconds if failed to reach safepoint") \ \ diagnostic(bool, AbortVMOnSafepointTimeout, false, \ "Abort upon failure to reach safepoint (see SafepointTimeout)") \ \ diagnostic(bool, AbortVMOnVMOperationTimeout, false, \ "Abort upon failure to complete VM operation promptly") \ \ diagnostic(intx, AbortVMOnVMOperationTimeoutDelay, 1000, \ "Delay in milliseconds for option AbortVMOnVMOperationTimeout") \ range(0, max_intx) \ \ /* 50 retries * (5 * current_retry_count) millis = ~6.375 seconds */ \ /* typically, at most a few retries are needed */ \ product(intx, SuspendRetryCount, 50, \ "Maximum retry count for an external suspend request") \ range(0, max_intx) \ \ product(intx, SuspendRetryDelay, 5, \ "Milliseconds to delay per retry (* current_retry_count)") \ range(0, max_intx) \ \ product(bool, AssertOnSuspendWaitFailure, false, \ "Assert/Guarantee on external suspend wait failure") \ \ product(bool, TraceSuspendWaitFailures, false, \ "Trace external suspend wait failures") \ \ product(bool, MaxFDLimit, true, \ "Bump the number of file descriptors to maximum in Solaris") \ \ diagnostic(bool, LogEvents, true, \ "Enable the various ring buffer event logs") \ \ diagnostic(uintx, LogEventsBufferEntries, 20, \ "Number of ring buffer event logs") \ range(1, NOT_LP64(1*K) LP64_ONLY(1*M)) \ \ diagnostic(bool, BytecodeVerificationRemote, true, \ "Enable the Java bytecode verifier for remote classes") \ \ diagnostic(bool, BytecodeVerificationLocal, false, \ "Enable the Java bytecode verifier for local classes") \ \ develop(bool, ForceFloatExceptions, trueInDebug, \ "Force exceptions on FP stack under/overflow") \ \ develop(bool, VerifyStackAtCalls, false, \ "Verify that the stack pointer is unchanged after calls") \ \ develop(bool, TraceJavaAssertions, false, \ "Trace java language assertions") \ \ notproduct(bool, VerifyCodeCache, false, \ "Verify code cache on memory allocation/deallocation") \ \ develop(bool, UseMallocOnly, false, \ "Use only malloc/free for allocation (no resource area/arena)") \ \ develop(bool, ZapResourceArea, trueInDebug, \ "Zap freed resource/arena space with 0xABABABAB") \ \ notproduct(bool, ZapVMHandleArea, trueInDebug, \ "Zap freed VM handle space with 0xBCBCBCBC") \ \ notproduct(bool, ZapStackSegments, trueInDebug, \ "Zap allocated/freed stack segments with 0xFADFADED") \ \ develop(bool, ZapUnusedHeapArea, trueInDebug, \ "Zap unused heap space with 0xBAADBABE") \ \ develop(bool, CheckZapUnusedHeapArea, false, \ "Check zapping of unused heap space") \ \ develop(bool, ZapFillerObjects, trueInDebug, \ "Zap filler objects with 0xDEAFBABE") \ \ develop(bool, PrintVMMessages, true, \ "Print VM messages on console") \ \ notproduct(uintx, ErrorHandlerTest, 0, \ "If > 0, provokes an error after VM initialization; the value " \ "determines which error to provoke. See test_error_handler() " \ "in vmError.cpp.") \ \ notproduct(uintx, TestCrashInErrorHandler, 0, \ "If > 0, provokes an error inside VM error handler (a secondary " \ "crash). see test_error_handler() in vmError.cpp") \ \ notproduct(bool, TestSafeFetchInErrorHandler, false, \ "If true, tests SafeFetch inside error handler.") \ \ notproduct(bool, TestUnresponsiveErrorHandler, false, \ "If true, simulates an unresponsive error handler.") \ \ develop(bool, Verbose, false, \ "Print additional debugging information from other modes") \ \ develop(bool, PrintMiscellaneous, false, \ "Print uncategorized debugging information (requires +Verbose)") \ \ develop(bool, WizardMode, false, \ "Print much more debugging information") \ \ product(bool, ShowMessageBoxOnError, false, \ "Keep process alive on VM fatal error") \ \ product(bool, CreateCoredumpOnCrash, true, \ "Create core/mini dump on VM fatal error") \ \ product(uint64_t, ErrorLogTimeout, 2 * 60, \ "Timeout, in seconds, to limit the time spent on writing an " \ "error log in case of a crash.") \ range(0, (uint64_t)max_jlong/1000) \ \ product_pd(bool, UseOSErrorReporting, \ "Let VM fatal error propagate to the OS (ie. WER on Windows)") \ \ product(bool, SuppressFatalErrorMessage, false, \ "Report NO fatal error message (avoid deadlock)") \ \ product(ccstrlist, OnError, "", \ "Run user-defined commands on fatal error; see VMError.cpp " \ "for examples") \ \ product(ccstrlist, OnOutOfMemoryError, "", \ "Run user-defined commands on first java.lang.OutOfMemoryError") \ \ manageable(bool, HeapDumpBeforeFullGC, false, \ "Dump heap to file before any major stop-the-world GC") \ \ manageable(bool, HeapDumpAfterFullGC, false, \ "Dump heap to file after any major stop-the-world GC") \ \ manageable(bool, HeapDumpOnOutOfMemoryError, false, \ "Dump heap to file when java.lang.OutOfMemoryError is thrown") \ \ manageable(ccstr, HeapDumpPath, NULL, \ "When HeapDumpOnOutOfMemoryError is on, the path (filename or " \ "directory) of the dump file (defaults to java_pid<pid>.hprof " \ "in the working directory)") \ \ develop(bool, BreakAtWarning, false, \ "Execute breakpoint upon encountering VM warning") \ \ product(ccstr, NativeMemoryTracking, "off", \ "Native memory tracking options") \ \ diagnostic(bool, PrintNMTStatistics, false, \ "Print native memory tracking summary data if it is on") \ \ diagnostic(bool, LogCompilation, false, \ "Log compilation activity in detail to LogFile") \ \ product(bool, PrintCompilation, false, \ "Print compilations") \ \ product(bool, PrintExtendedThreadInfo, false, \ "Print more information in thread dump") \ \ diagnostic(intx, ScavengeRootsInCode, 2, \ "0: do not allow scavengable oops in the code cache; " \ "1: allow scavenging from the code cache; " \ "2: emit as many constants as the compiler can see") \ range(0, 2) \ \ product(bool, AlwaysRestoreFPU, false, \ "Restore the FPU control word after every JNI call (expensive)") \ \ diagnostic(bool, PrintCompilation2, false, \ "Print additional statistics per compilation") \ \ diagnostic(bool, PrintAdapterHandlers, false, \ "Print code generated for i2c/c2i adapters") \ \ diagnostic(bool, VerifyAdapterCalls, trueInDebug, \ "Verify that i2c/c2i adapters are called properly") \ \ develop(bool, VerifyAdapterSharing, false, \ "Verify that the code for shared adapters is the equivalent") \ \ diagnostic(bool, PrintAssembly, false, \ "Print assembly code (using external disassembler.so)") \ \ diagnostic(ccstr, PrintAssemblyOptions, NULL, \ "Print options string passed to disassembler.so") \ \ notproduct(bool, PrintNMethodStatistics, false, \ "Print a summary statistic for the generated nmethods") \ \ diagnostic(bool, PrintNMethods, false, \ "Print assembly code for nmethods when generated") \ \ diagnostic(bool, PrintNativeNMethods, false, \ "Print assembly code for native nmethods when generated") \ \ develop(bool, PrintDebugInfo, false, \ "Print debug information for all nmethods when generated") \ \ develop(bool, PrintRelocations, false, \ "Print relocation information for all nmethods when generated") \ \ develop(bool, PrintDependencies, false, \ "Print dependency information for all nmethods when generated") \ \ develop(bool, PrintExceptionHandlers, false, \ "Print exception handler tables for all nmethods when generated") \ \ develop(bool, StressCompiledExceptionHandlers, false, \ "Exercise compiled exception handlers") \ \ develop(bool, InterceptOSException, false, \ "Start debugger when an implicit OS (e.g. NULL) " \ "exception happens") \ \ product(bool, PrintCodeCache, false, \ "Print the code cache memory usage when exiting") \ \ develop(bool, PrintCodeCache2, false, \ "Print detailed usage information on the code cache when exiting")\ \ product(bool, PrintCodeCacheOnCompilation, false, \ "Print the code cache memory usage each time a method is " \ "compiled") \ \ diagnostic(bool, PrintCodeHeapAnalytics, false, \ "Print code heap usage statistics on exit and on full condition") \ \ diagnostic(bool, PrintStubCode, false, \ "Print generated stub code") \ \ product(bool, StackTraceInThrowable, true, \ "Collect backtrace in throwable when exception happens") \ \ product(bool, OmitStackTraceInFastThrow, true, \ "Omit backtraces for some 'hot' exceptions in optimized code") \ \ manageable(bool, ShowCodeDetailsInExceptionMessages, false, \ "Show exception messages from RuntimeExceptions that contain " \ "snippets of the failing code. Disable this to improve privacy.") \ \ product(bool, PrintWarnings, true, \ "Print JVM warnings to output stream") \ \ notproduct(uintx, WarnOnStalledSpinLock, 0, \ "Print warnings for stalled SpinLocks") \ \ product(bool, RegisterFinalizersAtInit, true, \ "Register finalizable objects at end of Object.<init> or " \ "after allocation") \ \ develop(bool, RegisterReferences, true, \ "Tell whether the VM should register soft/weak/final/phantom " \ "references") \ \ develop(bool, IgnoreRewrites, false, \ "Suppress rewrites of bytecodes in the oopmap generator. " \ "This is unsafe!") \ \ develop(bool, PrintCodeCacheExtension, false, \ "Print extension of code cache") \ \ develop(bool, UsePrivilegedStack, true, \ "Enable the security JVM functions") \ \ develop(bool, ProtectionDomainVerification, true, \ "Verify protection domain before resolution in system dictionary")\ \ product(bool, ClassUnloading, true, \ "Do unloading of classes") \ \ product(bool, ClassUnloadingWithConcurrentMark, true, \ "Do unloading of classes with a concurrent marking cycle") \ \ develop(bool, DisableStartThread, false, \ "Disable starting of additional Java threads " \ "(for debugging only)") \ \ develop(bool, MemProfiling, false, \ "Write memory usage profiling to log file") \ \ notproduct(bool, PrintSystemDictionaryAtExit, false, \ "Print the system dictionary at exit") \ \ diagnostic(bool, DynamicallyResizeSystemDictionaries, true, \ "Dynamically resize system dictionaries as needed") \ \ product(bool, AlwaysLockClassLoader, false, \ "Require the VM to acquire the class loader lock before calling " \ "loadClass() even for class loaders registering " \ "as parallel capable") \ \ product(bool, AllowParallelDefineClass, false, \ "Allow parallel defineClass requests for class loaders " \ "registering as parallel capable") \ \ product_pd(bool, DontYieldALot, \ "Throw away obvious excess yield calls") \ \ develop(bool, UseDetachedThreads, true, \ "Use detached threads that are recycled upon termination " \ "(for Solaris only)") \ \ experimental(bool, DisablePrimordialThreadGuardPages, false, \ "Disable the use of stack guard pages if the JVM is loaded " \ "on the primordial process thread") \ \ product(bool, UseLWPSynchronization, true, \ "Use LWP-based instead of libthread-based synchronization " \ "(SPARC only)") \ \ product(intx, MonitorBound, 0, "(Deprecated) Bound Monitor population") \ range(0, max_jint) \ \ experimental(intx, MonitorUsedDeflationThreshold, 90, \ "Percentage of used monitors before triggering cleanup " \ "safepoint which deflates monitors (0 is off). " \ "The check is performed on GuaranteedSafepointInterval.") \ range(0, 100) \ \ experimental(intx, hashCode, 5, \ "(Unstable) select hashCode generation algorithm") \ \ product(bool, FilterSpuriousWakeups, true, \ "When true prevents OS-level spurious, or premature, wakeups " \ "from Object.wait (Ignored for Windows)") \ \ develop(bool, UsePthreads, false, \ "Use pthread-based instead of libthread-based synchronization " \ "(SPARC only)") \ \ product(bool, ReduceSignalUsage, false, \ "Reduce the use of OS signals in Java and/or the VM") \ \ develop(bool, LoadLineNumberTables, true, \ "Tell whether the class file parser loads line number tables") \ \ develop(bool, LoadLocalVariableTables, true, \ "Tell whether the class file parser loads local variable tables") \ \ develop(bool, LoadLocalVariableTypeTables, true, \ "Tell whether the class file parser loads local variable type" \ "tables") \ \ product(bool, AllowUserSignalHandlers, false, \ "Do not complain if the application installs signal handlers " \ "(Solaris & Linux only)") \ \ product(bool, UseSignalChaining, true, \ "Use signal-chaining to invoke signal handlers installed " \ "by the application (Solaris & Linux only)") \ \ product(bool, RestoreMXCSROnJNICalls, false, \ "Restore MXCSR when returning from JNI calls") \ \ product(bool, CheckJNICalls, false, \ "Verify all arguments to JNI calls") \ \ product(bool, UseFastJNIAccessors, true, \ "Use optimized versions of Get<Primitive>Field") \ \ product(intx, MaxJNILocalCapacity, 65536, \ "Maximum allowable local JNI handle capacity to " \ "EnsureLocalCapacity() and PushLocalFrame(), " \ "where <= 0 is unlimited, default: 65536") \ range(min_intx, max_intx) \ \ product(bool, EagerXrunInit, false, \ "Eagerly initialize -Xrun libraries; allows startup profiling, " \ "but not all -Xrun libraries may support the state of the VM " \ "at this time") \ \ product(bool, PreserveAllAnnotations, false, \ "Preserve RuntimeInvisibleAnnotations as well " \ "as RuntimeVisibleAnnotations") \ \ develop(uintx, PreallocatedOutOfMemoryErrorCount, 4, \ "Number of OutOfMemoryErrors preallocated with backtrace") \ \ product(bool, UseXMMForArrayCopy, false, \ "Use SSE2 MOVQ instruction for Arraycopy") \ \ product(intx, FieldsAllocationStyle, 1, \ "(Deprecated) 0 - type based with oops first, " \ "1 - with oops last, " \ "2 - oops in super and sub classes are together") \ range(0, 2) \ \ product(bool, CompactFields, true, \ "(Deprecated) Allocate nonstatic fields in gaps " \ "between previous fields") \ \ notproduct(bool, PrintFieldLayout, false, \ "Print field layout for each class") \ \ /* Need to limit the extent of the padding to reasonable size. */\ /* 8K is well beyond the reasonable HW cache line size, even with */\ /* aggressive prefetching, while still leaving the room for segregating */\ /* among the distinct pages. */\ product(intx, ContendedPaddingWidth, 128, \ "How many bytes to pad the fields/classes marked @Contended with")\ range(0, 8192) \ constraint(ContendedPaddingWidthConstraintFunc,AfterErgo) \ \ product(bool, EnableContended, true, \ "Enable @Contended annotation support") \ \ product(bool, RestrictContended, true, \ "Restrict @Contended to trusted classes") \ \ product(bool, UseBiasedLocking, true, \ "Enable biased locking in JVM") \ \ product(intx, BiasedLockingStartupDelay, 0, \ "Number of milliseconds to wait before enabling biased locking") \ range(0, (intx)(max_jint-(max_jint%PeriodicTask::interval_gran))) \ constraint(BiasedLockingStartupDelayFunc,AfterErgo) \ \ diagnostic(bool, PrintBiasedLockingStatistics, false, \ "Print statistics of biased locking in JVM") \ \ product(intx, BiasedLockingBulkRebiasThreshold, 20, \ "Threshold of number of revocations per type to try to " \ "rebias all objects in the heap of that type") \ range(0, max_intx) \ constraint(BiasedLockingBulkRebiasThresholdFunc,AfterErgo) \ \ product(intx, BiasedLockingBulkRevokeThreshold, 40, \ "Threshold of number of revocations per type to permanently " \ "revoke biases of all objects in the heap of that type") \ range(0, max_intx) \ constraint(BiasedLockingBulkRevokeThresholdFunc,AfterErgo) \ \ product(intx, BiasedLockingDecayTime, 25000, \ "Decay time (in milliseconds) to re-enable bulk rebiasing of a " \ "type after previous bulk rebias") \ range(500, max_intx) \ constraint(BiasedLockingDecayTimeFunc,AfterErgo) \ \ product(bool, ExitOnOutOfMemoryError, false, \ "JVM exits on the first occurrence of an out-of-memory error") \ \ product(bool, CrashOnOutOfMemoryError, false, \ "JVM aborts, producing an error log and core/mini dump, on the " \ "first occurrence of an out-of-memory error") \ \ /* tracing */ \ \ develop(bool, StressRewriter, false, \ "Stress linktime bytecode rewriting") \ \ product(ccstr, TraceJVMTI, NULL, \ "Trace flags for JVMTI functions and events") \ \ /* This option can change an EMCP method into an obsolete method. */ \ /* This can affect tests that except specific methods to be EMCP. */ \ /* This option should be used with caution. */ \ product(bool, StressLdcRewrite, false, \ "Force ldc -> ldc_w rewrite during RedefineClasses") \ \ /* change to false by default sometime after Mustang */ \ product(bool, VerifyMergedCPBytecodes, true, \ "Verify bytecodes after RedefineClasses constant pool merging") \ \ product(bool, AllowRedefinitionToAddDeleteMethods, false, \ "(Deprecated) Allow redefinition to add and delete private " \ "static or final methods for compatibility with old releases") \ \ develop(bool, TraceBytecodes, false, \ "Trace bytecode execution") \ \ develop(bool, TraceICs, false, \ "Trace inline cache changes") \ \ notproduct(bool, TraceInvocationCounterOverflow, false, \ "Trace method invocation counter overflow") \ \ develop(bool, TraceInlineCacheClearing, false, \ "Trace clearing of inline caches in nmethods") \ \ develop(bool, TraceDependencies, false, \ "Trace dependencies") \ \ develop(bool, VerifyDependencies, trueInDebug, \ "Exercise and verify the compilation dependency mechanism") \ \ develop(bool, TraceNewOopMapGeneration, false, \ "Trace OopMapGeneration") \ \ develop(bool, TraceNewOopMapGenerationDetailed, false, \ "Trace OopMapGeneration: print detailed cell states") \ \ develop(bool, TimeOopMap, false, \ "Time calls to GenerateOopMap::compute_map() in sum") \ \ develop(bool, TimeOopMap2, false, \ "Time calls to GenerateOopMap::compute_map() individually") \ \ develop(bool, TraceOopMapRewrites, false, \ "Trace rewriting of method oops during oop map generation") \ \ develop(bool, TraceICBuffer, false, \ "Trace usage of IC buffer") \ \ develop(bool, TraceCompiledIC, false, \ "Trace changes of compiled IC") \ \ develop(bool, FLSVerifyDictionary, false, \ "Do lots of (expensive) FLS dictionary verification") \ \ \ notproduct(bool, CheckMemoryInitialization, false, \ "Check memory initialization") \ \ product(uintx, ProcessDistributionStride, 4, \ "Stride through processors when distributing processes") \ range(0, max_juint) \ \ develop(bool, TraceFinalizerRegistration, false, \ "Trace registration of final references") \ \ product(bool, IgnoreEmptyClassPaths, false, \ "Ignore empty path elements in -classpath") \ \ product(size_t, InitialBootClassLoaderMetaspaceSize, \ NOT_LP64(2200*K) LP64_ONLY(4*M), \ "Initial size of the boot class loader data metaspace") \ range(30*K, max_uintx/BytesPerWord) \ constraint(InitialBootClassLoaderMetaspaceSizeConstraintFunc, AfterErgo)\ \ product(bool, PrintHeapAtSIGBREAK, true, \ "Print heap layout in response to SIGBREAK") \ \ manageable(bool, PrintClassHistogram, false, \ "Print a histogram of class instances") \ \ experimental(double, ObjectCountCutOffPercent, 0.5, \ "The percentage of the used heap that the instances of a class " \ "must occupy for the class to generate a trace event") \ range(0.0, 100.0) \ \ /* JVMTI heap profiling */ \ \ diagnostic(bool, TraceJVMTIObjectTagging, false, \ "Trace JVMTI object tagging calls") \ \ diagnostic(bool, VerifyBeforeIteration, false, \ "Verify memory system before JVMTI iteration") \ \ /* compiler interface */ \ \ develop(bool, CIPrintCompilerName, false, \ "when CIPrint is active, print the name of the active compiler") \ \ diagnostic(bool, CIPrintCompileQueue, false, \ "display the contents of the compile queue whenever a " \ "compilation is enqueued") \ \ develop(bool, CIPrintRequests, false, \ "display every request for compilation") \ \ product(bool, CITime, false, \ "collect timing information for compilation") \ \ develop(bool, CITimeVerbose, false, \ "be more verbose in compilation timings") \ \ develop(bool, CITimeEach, false, \ "display timing information after each successful compilation") \ \ develop(bool, CICountOSR, false, \ "use a separate counter when assigning ids to osr compilations") \ \ develop(bool, CICompileNatives, true, \ "compile native methods if supported by the compiler") \ \ develop_pd(bool, CICompileOSR, \ "compile on stack replacement methods if supported by the " \ "compiler") \ \ develop(bool, CIPrintMethodCodes, false, \ "print method bytecodes of the compiled code") \ \ develop(bool, CIPrintTypeFlow, false, \ "print the results of ciTypeFlow analysis") \ \ develop(bool, CITraceTypeFlow, false, \ "detailed per-bytecode tracing of ciTypeFlow analysis") \ \ develop(intx, OSROnlyBCI, -1, \ "OSR only at this bci. Negative values mean exclude that bci") \ \ /* compiler */ \ \ /* notice: the max range value here is max_jint, not max_intx */ \ /* because of overflow issue */ \ product(intx, CICompilerCount, CI_COMPILER_COUNT, \ "Number of compiler threads to run") \ range(0, max_jint) \ constraint(CICompilerCountConstraintFunc, AfterErgo) \ \ product(bool, UseDynamicNumberOfCompilerThreads, true, \ "Dynamically choose the number of parallel compiler threads") \ \ diagnostic(bool, ReduceNumberOfCompilerThreads, true, \ "Reduce the number of parallel compiler threads when they " \ "are not used") \ \ diagnostic(bool, TraceCompilerThreads, false, \ "Trace creation and removal of compiler threads") \ \ develop(bool, InjectCompilerCreationFailure, false, \ "Inject thread creation failures for " \ "UseDynamicNumberOfCompilerThreads") \ \ develop(bool, UseStackBanging, true, \ "use stack banging for stack overflow checks (required for " \ "proper StackOverflow handling; disable only to measure cost " \ "of stackbanging)") \ \ develop(bool, UseStrictFP, true, \ "use strict fp if modifier strictfp is set") \ \ develop(bool, GenerateSynchronizationCode, true, \ "generate locking/unlocking code for synchronized methods and " \ "monitors") \ \ develop(bool, GenerateRangeChecks, true, \ "Generate range checks for array accesses") \ \ diagnostic_pd(bool, ImplicitNullChecks, \ "Generate code for implicit null checks") \ \ product_pd(bool, TrapBasedNullChecks, \ "Generate code for null checks that uses a cmp and trap " \ "instruction raising SIGTRAP. This is only used if an access to" \ "null (+offset) will not raise a SIGSEGV, i.e.," \ "ImplicitNullChecks don't work (PPC64).") \ \ diagnostic(bool, EnableThreadSMRExtraValidityChecks, true, \ "Enable Thread SMR extra validity checks") \ \ diagnostic(bool, EnableThreadSMRStatistics, trueInDebug, \ "Enable Thread SMR Statistics") \ \ product(bool, UseNotificationThread, true, \ "Use Notification Thread") \ \ product(bool, Inline, true, \ "Enable inlining") \ \ product(bool, ClipInlining, true, \ "Clip inlining if aggregate method exceeds DesiredMethodLimit") \ \ develop(bool, UseCHA, true, \ "Enable CHA") \ \ product(bool, UseTypeProfile, true, \ "Check interpreter profile for historically monomorphic calls") \ \ diagnostic(bool, PrintInlining, false, \ "Print inlining optimizations") \ \ product(bool, UsePopCountInstruction, false, \ "Use population count instruction") \ \ develop(bool, EagerInitialization, false, \ "Eagerly initialize classes if possible") \ \ diagnostic(bool, LogTouchedMethods, false, \ "Log methods which have been ever touched in runtime") \ \ diagnostic(bool, PrintTouchedMethodsAtExit, false, \ "Print all methods that have been ever touched in runtime") \ \ develop(bool, TraceMethodReplacement, false, \ "Print when methods are replaced do to recompilation") \ \ develop(bool, PrintMethodFlushing, false, \ "Print the nmethods being flushed") \ \ diagnostic(bool, PrintMethodFlushingStatistics, false, \ "print statistics about method flushing") \ \ diagnostic(intx, HotMethodDetectionLimit, 100000, \ "Number of compiled code invocations after which " \ "the method is considered as hot by the flusher") \ range(1, max_jint) \ \ diagnostic(intx, MinPassesBeforeFlush, 10, \ "Minimum number of sweeper passes before an nmethod " \ "can be flushed") \ range(0, max_intx) \ \ product(bool, UseCodeAging, true, \ "Insert counter to detect warm methods") \ \ diagnostic(bool, StressCodeAging, false, \ "Start with counters compiled in") \ \ develop(bool, StressCodeBuffers, false, \ "Exercise code buffer expansion and other rare state changes") \ \ diagnostic(bool, DebugNonSafepoints, trueInDebug, \ "Generate extra debugging information for non-safepoints in " \ "nmethods") \ \ product(bool, PrintVMOptions, false, \ "Print flags that appeared on the command line") \ \ product(bool, IgnoreUnrecognizedVMOptions, false, \ "Ignore unrecognized VM options") \ \ product(bool, PrintCommandLineFlags, false, \ "Print flags specified on command line or set by ergonomics") \ \ product(bool, PrintFlagsInitial, false, \ "Print all VM flags before argument processing and exit VM") \ \ product(bool, PrintFlagsFinal, false, \ "Print all VM flags after argument and ergonomic processing") \ \ notproduct(bool, PrintFlagsWithComments, false, \ "Print all VM flags with default values and descriptions and " \ "exit") \ \ product(bool, PrintFlagsRanges, false, \ "Print VM flags and their ranges") \ \ diagnostic(bool, SerializeVMOutput, true, \ "Use a mutex to serialize output to tty and LogFile") \ \ diagnostic(bool, DisplayVMOutput, true, \ "Display all VM output on the tty, independently of LogVMOutput") \ \ diagnostic(bool, LogVMOutput, false, \ "Save VM output to LogFile") \ \ diagnostic(ccstr, LogFile, NULL, \ "If LogVMOutput or LogCompilation is on, save VM output to " \ "this file [default: ./hotspot_pid%p.log] (%p replaced with pid)")\ \ product(ccstr, ErrorFile, NULL, \ "If an error occurs, save the error data to this file " \ "[default: ./hs_err_pid%p.log] (%p replaced with pid)") \ \ product(bool, ExtensiveErrorReports, \ PRODUCT_ONLY(false) NOT_PRODUCT(true), \ "Error reports are more extensive.") \ \ product(bool, DisplayVMOutputToStderr, false, \ "If DisplayVMOutput is true, display all VM output to stderr") \ \ product(bool, DisplayVMOutputToStdout, false, \ "If DisplayVMOutput is true, display all VM output to stdout") \ \ product(bool, ErrorFileToStderr, false, \ "If true, error data is printed to stderr instead of a file") \ \ product(bool, ErrorFileToStdout, false, \ "If true, error data is printed to stdout instead of a file") \ \ product(bool, UseHeavyMonitors, false, \ "use heavyweight instead of lightweight Java monitors") \ \ product(bool, PrintStringTableStatistics, false, \ "print statistics about the StringTable and SymbolTable") \ \ diagnostic(bool, VerifyStringTableAtExit, false, \ "verify StringTable contents at exit") \ \ notproduct(bool, PrintSymbolTableSizeHistogram, false, \ "print histogram of the symbol table") \ \ notproduct(bool, ExitVMOnVerifyError, false, \ "standard exit from VM if bytecode verify error " \ "(only in debug mode)") \ \ diagnostic(ccstr, AbortVMOnException, NULL, \ "Call fatal if this exception is thrown. Example: " \ "java -XX:AbortVMOnException=java.lang.NullPointerException Foo") \ \ diagnostic(ccstr, AbortVMOnExceptionMessage, NULL, \ "Call fatal if the exception pointed by AbortVMOnException " \ "has this message") \ \ develop(bool, DebugVtables, false, \ "add debugging code to vtable dispatch") \ \ notproduct(bool, PrintVtableStats, false, \ "print vtables stats at end of run") \ \ develop(bool, TraceCreateZombies, false, \ "trace creation of zombie nmethods") \ \ product(bool, RangeCheckElimination, true, \ "Eliminate range checks") \ \ develop_pd(bool, UncommonNullCast, \ "track occurrences of null in casts; adjust compiler tactics") \ \ develop(bool, TypeProfileCasts, true, \ "treat casts like calls for purposes of type profiling") \ \ develop(bool, TraceLivenessGen, false, \ "Trace the generation of liveness analysis information") \ \ notproduct(bool, TraceLivenessQuery, false, \ "Trace queries of liveness analysis information") \ \ notproduct(bool, CollectIndexSetStatistics, false, \ "Collect information about IndexSets") \ \ develop(bool, UseLoopSafepoints, true, \ "Generate Safepoint nodes in every loop") \ \ develop(intx, FastAllocateSizeLimit, 128*K, \ /* Note: This value is zero mod 1<<13 for a cheap sparc set. */ \ "Inline allocations larger than this in doublewords must go slow")\ \ product_pd(bool, CompactStrings, \ "Enable Strings to use single byte chars in backing store") \ \ product_pd(uintx, TypeProfileLevel, \ "=XYZ, with Z: Type profiling of arguments at call; " \ "Y: Type profiling of return value at call; " \ "X: Type profiling of parameters to methods; " \ "X, Y and Z in 0=off ; 1=jsr292 only; 2=all methods") \ constraint(TypeProfileLevelConstraintFunc, AfterErgo) \ \ product(intx, TypeProfileArgsLimit, 2, \ "max number of call arguments to consider for type profiling") \ range(0, 16) \ \ product(intx, TypeProfileParmsLimit, 2, \ "max number of incoming parameters to consider for type profiling"\ ", -1 for all") \ range(-1, 64) \ \ /* statistics */ \ develop(bool, CountCompiledCalls, false, \ "Count method invocations") \ \ notproduct(bool, CountRuntimeCalls, false, \ "Count VM runtime calls") \ \ develop(bool, CountJNICalls, false, \ "Count jni method invocations") \ \ notproduct(bool, CountJVMCalls, false, \ "Count jvm method invocations") \ \ notproduct(bool, CountRemovableExceptions, false, \ "Count exceptions that could be replaced by branches due to " \ "inlining") \ \ notproduct(bool, ICMissHistogram, false, \ "Produce histogram of IC misses") \ \ /* interpreter */ \ product_pd(bool, RewriteBytecodes, \ "Allow rewriting of bytecodes (bytecodes are not immutable)") \ \ product_pd(bool, RewriteFrequentPairs, \ "Rewrite frequently used bytecode pairs into a single bytecode") \ \ diagnostic(bool, PrintInterpreter, false, \ "Print the generated interpreter code") \ \ product(bool, UseInterpreter, true, \ "Use interpreter for non-compiled methods") \ \ develop(bool, UseFastSignatureHandlers, true, \ "Use fast signature handlers for native calls") \ \ product(bool, UseLoopCounter, true, \ "Increment invocation counter on backward branch") \ \ product_pd(bool, UseOnStackReplacement, \ "Use on stack replacement, calls runtime if invoc. counter " \ "overflows in loop") \ \ notproduct(bool, TraceOnStackReplacement, false, \ "Trace on stack replacement") \ \ product_pd(bool, PreferInterpreterNativeStubs, \ "Use always interpreter stubs for native methods invoked via " \ "interpreter") \ \ develop(bool, CountBytecodes, false, \ "Count number of bytecodes executed") \ \ develop(bool, PrintBytecodeHistogram, false, \ "Print histogram of the executed bytecodes") \ \ develop(bool, PrintBytecodePairHistogram, false, \ "Print histogram of the executed bytecode pairs") \ \ diagnostic(bool, PrintSignatureHandlers, false, \ "Print code generated for native method signature handlers") \ \ develop(bool, VerifyOops, false, \ "Do plausibility checks for oops") \ \ develop(bool, CheckUnhandledOops, false, \ "Check for unhandled oops in VM code") \ \ develop(bool, VerifyJNIFields, trueInDebug, \ "Verify jfieldIDs for instance fields") \ \ notproduct(bool, VerifyJNIEnvThread, false, \ "Verify JNIEnv.thread == Thread::current() when entering VM " \ "from JNI") \ \ develop(bool, VerifyFPU, false, \ "Verify FPU state (check for NaN's, etc.)") \ \ develop(bool, VerifyThread, false, \ "Watch the thread register for corruption (SPARC only)") \ \ develop(bool, VerifyActivationFrameSize, false, \ "Verify that activation frame didn't become smaller than its " \ "minimal size") \ \ develop(bool, TraceFrequencyInlining, false, \ "Trace frequency based inlining") \ \ develop_pd(bool, InlineIntrinsics, \ "Inline intrinsics that can be statically resolved") \ \ product_pd(bool, ProfileInterpreter, \ "Profile at the bytecode level during interpretation") \ \ develop(bool, TraceProfileInterpreter, false, \ "Trace profiling at the bytecode level during interpretation. " \ "This outputs the profiling information collected to improve " \ "jit compilation.") \ \ develop_pd(bool, ProfileTraps, \ "Profile deoptimization traps at the bytecode level") \ \ product(intx, ProfileMaturityPercentage, 20, \ "number of method invocations/branches (expressed as % of " \ "CompileThreshold) before using the method's profile") \ range(0, 100) \ \ diagnostic(bool, PrintMethodData, false, \ "Print the results of +ProfileInterpreter at end of run") \ \ develop(bool, VerifyDataPointer, trueInDebug, \ "Verify the method data pointer during interpreter profiling") \ \ develop(bool, VerifyCompiledCode, false, \ "Include miscellaneous runtime verifications in nmethod code; " \ "default off because it disturbs nmethod size heuristics") \ \ notproduct(bool, CrashGCForDumpingJavaThread, false, \ "Manually make GC thread crash then dump java stack trace; " \ "Test only") \ \ /* compilation */ \ product(bool, UseCompiler, true, \ "Use Just-In-Time compilation") \ \ product(bool, UseCounterDecay, true, \ "Adjust recompilation counters") \ \ develop(intx, CounterHalfLifeTime, 30, \ "Half-life time of invocation counters (in seconds)") \ \ develop(intx, CounterDecayMinIntervalLength, 500, \ "The minimum interval (in milliseconds) between invocation of " \ "CounterDecay") \ \ product(bool, AlwaysCompileLoopMethods, false, \ "When using recompilation, never interpret methods " \ "containing loops") \ \ product(bool, DontCompileHugeMethods, true, \ "Do not compile methods > HugeMethodLimit") \ \ /* Bytecode escape analysis estimation. */ \ product(bool, EstimateArgEscape, true, \ "Analyze bytecodes to estimate escape state of arguments") \ \ product(intx, BCEATraceLevel, 0, \ "How much tracing to do of bytecode escape analysis estimates " \ "(0-3)") \ range(0, 3) \ \ product(intx, MaxBCEAEstimateLevel, 5, \ "Maximum number of nested calls that are analyzed by BC EA") \ range(0, max_jint) \ \ product(intx, MaxBCEAEstimateSize, 150, \ "Maximum bytecode size of a method to be analyzed by BC EA") \ range(0, max_jint) \ \ product(intx, AllocatePrefetchStyle, 1, \ "0 = no prefetch, " \ "1 = generate prefetch instructions for each allocation, " \ "2 = use TLAB watermark to gate allocation prefetch, " \ "3 = generate one prefetch instruction per cache line") \ range(0, 3) \ \ product(intx, AllocatePrefetchDistance, -1, \ "Distance to prefetch ahead of allocation pointer. " \ "-1: use system-specific value (automatically determined") \ constraint(AllocatePrefetchDistanceConstraintFunc,AfterMemoryInit)\ \ product(intx, AllocatePrefetchLines, 3, \ "Number of lines to prefetch ahead of array allocation pointer") \ range(1, 64) \ \ product(intx, AllocateInstancePrefetchLines, 1, \ "Number of lines to prefetch ahead of instance allocation " \ "pointer") \ range(1, 64) \ \ product(intx, AllocatePrefetchStepSize, 16, \ "Step size in bytes of sequential prefetch instructions") \ range(1, 512) \ constraint(AllocatePrefetchStepSizeConstraintFunc,AfterMemoryInit)\ \ product(intx, AllocatePrefetchInstr, 0, \ "Select instruction to prefetch ahead of allocation pointer") \ constraint(AllocatePrefetchInstrConstraintFunc, AfterMemoryInit) \ \ /* deoptimization */ \ develop(bool, TraceDeoptimization, false, \ "Trace deoptimization") \ \ develop(bool, PrintDeoptimizationDetails, false, \ "Print more information about deoptimization") \ \ develop(bool, DebugDeoptimization, false, \ "Tracing various information while debugging deoptimization") \ \ product(intx, SelfDestructTimer, 0, \ "Will cause VM to terminate after a given time (in minutes) " \ "(0 means off)") \ range(0, max_intx) \ \ product(intx, MaxJavaStackTraceDepth, 1024, \ "The maximum number of lines in the stack trace for Java " \ "exceptions (0 means all)") \ range(0, max_jint/2) \ \ /* notice: the max range value here is max_jint, not max_intx */ \ /* because of overflow issue */ \ diagnostic(intx, GuaranteedSafepointInterval, 1000, \ "Guarantee a safepoint (at least) every so many milliseconds " \ "(0 means none)") \ range(0, max_jint) \ \ product(intx, SafepointTimeoutDelay, 10000, \ "Delay in milliseconds for option SafepointTimeout") \ LP64_ONLY(range(0, max_intx/MICROUNITS)) \ NOT_LP64(range(0, max_intx)) \ \ product(intx, NmethodSweepActivity, 10, \ "Removes cold nmethods from code cache if > 0. Higher values " \ "result in more aggressive sweeping") \ range(0, 2000) \ \ notproduct(bool, LogSweeper, false, \ "Keep a ring buffer of sweeper activity") \ \ notproduct(intx, SweeperLogEntries, 1024, \ "Number of records in the ring buffer of sweeper activity") \ \ notproduct(intx, MemProfilingInterval, 500, \ "Time between each invocation of the MemProfiler") \ \ develop(intx, MallocCatchPtr, -1, \ "Hit breakpoint when mallocing/freeing this pointer") \ \ notproduct(ccstrlist, SuppressErrorAt, "", \ "List of assertions (file:line) to muzzle") \ \ develop(intx, StackPrintLimit, 100, \ "number of stack frames to print in VM-level stack dump") \ \ notproduct(intx, MaxElementPrintSize, 256, \ "maximum number of elements to print") \ \ notproduct(intx, MaxSubklassPrintSize, 4, \ "maximum number of subklasses to print when printing klass") \ \ product(intx, MaxInlineLevel, 15, \ "maximum number of nested calls that are inlined") \ range(0, max_jint) \ \ product(intx, MaxRecursiveInlineLevel, 1, \ "maximum number of nested recursive calls that are inlined") \ range(0, max_jint) \ \ develop(intx, MaxForceInlineLevel, 100, \ "maximum number of nested calls that are forced for inlining " \ "(using CompileCommand or marked w/ @ForceInline)") \ range(0, max_jint) \ \ product_pd(intx, InlineSmallCode, \ "Only inline already compiled methods if their code size is " \ "less than this") \ range(0, max_jint) \ \ product(intx, MaxInlineSize, 35, \ "The maximum bytecode size of a method to be inlined") \ range(0, max_jint) \ \ product_pd(intx, FreqInlineSize, \ "The maximum bytecode size of a frequent method to be inlined") \ range(0, max_jint) \ \ product(intx, MaxTrivialSize, 6, \ "The maximum bytecode size of a trivial method to be inlined") \ range(0, max_jint) \ \ product(intx, MinInliningThreshold, 250, \ "The minimum invocation count a method needs to have to be " \ "inlined") \ range(0, max_jint) \ \ develop(intx, MethodHistogramCutoff, 100, \ "The cutoff value for method invocation histogram (+CountCalls)") \ \ develop(intx, DontYieldALotInterval, 10, \ "Interval between which yields will be dropped (milliseconds)") \ \ notproduct(intx, DeoptimizeALotInterval, 5, \ "Number of exits until DeoptimizeALot kicks in") \ \ notproduct(intx, ZombieALotInterval, 5, \ "Number of exits until ZombieALot kicks in") \ \ diagnostic(uintx, MallocMaxTestWords, 0, \ "If non-zero, maximum number of words that malloc/realloc can " \ "allocate (for testing only)") \ range(0, max_uintx) \ \ product(intx, TypeProfileWidth, 2, \ "Number of receiver types to record in call/cast profile") \ range(0, 8) \ \ develop(intx, BciProfileWidth, 2, \ "Number of return bci's to record in ret profile") \ \ product(intx, PerMethodRecompilationCutoff, 400, \ "After recompiling N times, stay in the interpreter (-1=>'Inf')") \ range(-1, max_intx) \ \ product(intx, PerBytecodeRecompilationCutoff, 200, \ "Per-BCI limit on repeated recompilation (-1=>'Inf')") \ range(-1, max_intx) \ \ product(intx, PerMethodTrapLimit, 100, \ "Limit on traps (of one kind) in a method (includes inlines)") \ range(0, max_jint) \ \ experimental(intx, PerMethodSpecTrapLimit, 5000, \ "Limit on speculative traps (of one kind) in a method " \ "(includes inlines)") \ range(0, max_jint) \ \ product(intx, PerBytecodeTrapLimit, 4, \ "Limit on traps (of one kind) at a particular BCI") \ range(0, max_jint) \ \ experimental(intx, SpecTrapLimitExtraEntries, 3, \ "Extra method data trap entries for speculation") \ \ develop(intx, InlineFrequencyRatio, 20, \ "Ratio of call site execution to caller method invocation") \ range(0, max_jint) \ \ diagnostic_pd(intx, InlineFrequencyCount, \ "Count of call site execution necessary to trigger frequent " \ "inlining") \ range(0, max_jint) \ \ develop(intx, InlineThrowCount, 50, \ "Force inlining of interpreted methods that throw this often") \ range(0, max_jint) \ \ develop(intx, InlineThrowMaxSize, 200, \ "Force inlining of throwing methods smaller than this") \ range(0, max_jint) \ \ develop(intx, ProfilerNodeSize, 1024, \ "Size in K to allocate for the Profile Nodes of each thread") \ range(0, 1024) \ \ product_pd(size_t, MetaspaceSize, \ "Initial threshold (in bytes) at which a garbage collection " \ "is done to reduce Metaspace usage") \ constraint(MetaspaceSizeConstraintFunc,AfterErgo) \ \ product(size_t, MaxMetaspaceSize, max_uintx, \ "Maximum size of Metaspaces (in bytes)") \ constraint(MaxMetaspaceSizeConstraintFunc,AfterErgo) \ \ product(size_t, CompressedClassSpaceSize, 1*G, \ "Maximum size of class area in Metaspace when compressed " \ "class pointers are used") \ range(1*M, 3*G) \ \ manageable(uintx, MinHeapFreeRatio, 40, \ "The minimum percentage of heap free after GC to avoid expansion."\ " For most GCs this applies to the old generation. In G1 and" \ " ParallelGC it applies to the whole heap.") \ range(0, 100) \ constraint(MinHeapFreeRatioConstraintFunc,AfterErgo) \ \ manageable(uintx, MaxHeapFreeRatio, 70, \ "The maximum percentage of heap free after GC to avoid shrinking."\ " For most GCs this applies to the old generation. In G1 and" \ " ParallelGC it applies to the whole heap.") \ range(0, 100) \ constraint(MaxHeapFreeRatioConstraintFunc,AfterErgo) \ \ product(bool, ShrinkHeapInSteps, true, \ "When disabled, informs the GC to shrink the java heap directly" \ " to the target size at the next full GC rather than requiring" \ " smaller steps during multiple full GCs.") \ \ product(intx, SoftRefLRUPolicyMSPerMB, 1000, \ "Number of milliseconds per MB of free space in the heap") \ range(0, max_intx) \ constraint(SoftRefLRUPolicyMSPerMBConstraintFunc,AfterMemoryInit) \ \ product(size_t, MinHeapDeltaBytes, ScaleForWordSize(128*K), \ "The minimum change in heap space due to GC (in bytes)") \ range(0, max_uintx) \ \ product(size_t, MinMetaspaceExpansion, ScaleForWordSize(256*K), \ "The minimum expansion of Metaspace (in bytes)") \ range(0, max_uintx) \ \ product(uintx, MaxMetaspaceFreeRatio, 70, \ "The maximum percentage of Metaspace free after GC to avoid " \ "shrinking") \ range(0, 100) \ constraint(MaxMetaspaceFreeRatioConstraintFunc,AfterErgo) \ \ product(uintx, MinMetaspaceFreeRatio, 40, \ "The minimum percentage of Metaspace free after GC to avoid " \ "expansion") \ range(0, 99) \ constraint(MinMetaspaceFreeRatioConstraintFunc,AfterErgo) \ \ product(size_t, MaxMetaspaceExpansion, ScaleForWordSize(4*M), \ "The maximum expansion of Metaspace without full GC (in bytes)") \ range(0, max_uintx) \ \ /* stack parameters */ \ product_pd(intx, StackYellowPages, \ "Number of yellow zone (recoverable overflows) pages of size " \ "4KB. If pages are bigger yellow zone is aligned up.") \ range(MIN_STACK_YELLOW_PAGES, (DEFAULT_STACK_YELLOW_PAGES+5)) \ \ product_pd(intx, StackRedPages, \ "Number of red zone (unrecoverable overflows) pages of size " \ "4KB. If pages are bigger red zone is aligned up.") \ range(MIN_STACK_RED_PAGES, (DEFAULT_STACK_RED_PAGES+2)) \ \ product_pd(intx, StackReservedPages, \ "Number of reserved zone (reserved to annotated methods) pages" \ " of size 4KB. If pages are bigger reserved zone is aligned up.") \ range(MIN_STACK_RESERVED_PAGES, (DEFAULT_STACK_RESERVED_PAGES+10))\ \ product(bool, RestrictReservedStack, true, \ "Restrict @ReservedStackAccess to trusted classes") \ \ /* greater stack shadow pages can't generate instruction to bang stack */ \ product_pd(intx, StackShadowPages, \ "Number of shadow zone (for overflow checking) pages of size " \ "4KB. If pages are bigger shadow zone is aligned up. " \ "This should exceed the depth of the VM and native call stack.") \ range(MIN_STACK_SHADOW_PAGES, (DEFAULT_STACK_SHADOW_PAGES+30)) \ \ product_pd(intx, ThreadStackSize, \ "Thread Stack Size (in Kbytes)") \ range(0, 1 * M) \ \ product_pd(intx, VMThreadStackSize, \ "Non-Java Thread Stack Size (in Kbytes)") \ range(0, max_intx/(1 * K)) \ \ product_pd(intx, CompilerThreadStackSize, \ "Compiler Thread Stack Size (in Kbytes)") \ range(0, max_intx/(1 * K)) \ \ develop_pd(size_t, JVMInvokeMethodSlack, \ "Stack space (bytes) required for JVM_InvokeMethod to complete") \ \ /* code cache parameters */ \ develop_pd(uintx, CodeCacheSegmentSize, \ "Code cache segment size (in bytes) - smallest unit of " \ "allocation") \ range(1, 1024) \ constraint(CodeCacheSegmentSizeConstraintFunc, AfterErgo) \ \ develop_pd(intx, CodeEntryAlignment, \ "Code entry alignment for generated code (in bytes)") \ constraint(CodeEntryAlignmentConstraintFunc, AfterErgo) \ \ product_pd(intx, OptoLoopAlignment, \ "Align inner loops to zero relative to this modulus") \ range(1, 16) \ constraint(OptoLoopAlignmentConstraintFunc, AfterErgo) \ \ product_pd(uintx, InitialCodeCacheSize, \ "Initial code cache size (in bytes)") \ range(os::vm_page_size(), max_uintx) \ \ develop_pd(uintx, CodeCacheMinimumUseSpace, \ "Minimum code cache size (in bytes) required to start VM.") \ range(0, max_uintx) \ \ product(bool, SegmentedCodeCache, false, \ "Use a segmented code cache") \ \ product_pd(uintx, ReservedCodeCacheSize, \ "Reserved code cache size (in bytes) - maximum code cache size") \ range(os::vm_page_size(), max_uintx) \ \ product_pd(uintx, NonProfiledCodeHeapSize, \ "Size of code heap with non-profiled methods (in bytes)") \ range(0, max_uintx) \ \ product_pd(uintx, ProfiledCodeHeapSize, \ "Size of code heap with profiled methods (in bytes)") \ range(0, max_uintx) \ \ product_pd(uintx, NonNMethodCodeHeapSize, \ "Size of code heap with non-nmethods (in bytes)") \ range(os::vm_page_size(), max_uintx) \ \ product_pd(uintx, CodeCacheExpansionSize, \ "Code cache expansion size (in bytes)") \ range(32*K, max_uintx) \ \ diagnostic_pd(uintx, CodeCacheMinBlockLength, \ "Minimum number of segments in a code cache block") \ range(1, 100) \ \ notproduct(bool, ExitOnFullCodeCache, false, \ "Exit the VM if we fill the code cache") \ \ product(bool, UseCodeCacheFlushing, true, \ "Remove cold/old nmethods from the code cache") \ \ product(uintx, StartAggressiveSweepingAt, 10, \ "Start aggressive sweeping if X[%] of the code cache is free." \ "Segmented code cache: X[%] of the non-profiled heap." \ "Non-segmented code cache: X[%] of the total code cache") \ range(0, 100) \ \ /* AOT parameters */ \ experimental(bool, UseAOT, false, \ "Use AOT compiled files") \ \ experimental(ccstrlist, AOTLibrary, NULL, \ "AOT library") \ \ experimental(bool, PrintAOT, false, \ "Print used AOT klasses and methods") \ \ notproduct(bool, PrintAOTStatistics, false, \ "Print AOT statistics") \ \ diagnostic(bool, UseAOTStrictLoading, false, \ "Exit the VM if any of the AOT libraries has invalid config") \ \ product(bool, CalculateClassFingerprint, false, \ "Calculate class fingerprint") \ \ /* interpreter debugging */ \ develop(intx, BinarySwitchThreshold, 5, \ "Minimal number of lookupswitch entries for rewriting to binary " \ "switch") \ \ develop(intx, StopInterpreterAt, 0, \ "Stop interpreter execution at specified bytecode number") \ \ develop(intx, TraceBytecodesAt, 0, \ "Trace bytecodes starting with specified bytecode number") \ \ /* compiler interface */ \ develop(intx, CIStart, 0, \ "The id of the first compilation to permit") \ \ develop(intx, CIStop, max_jint, \ "The id of the last compilation to permit") \ \ develop(intx, CIStartOSR, 0, \ "The id of the first osr compilation to permit " \ "(CICountOSR must be on)") \ \ develop(intx, CIStopOSR, max_jint, \ "The id of the last osr compilation to permit " \ "(CICountOSR must be on)") \ \ develop(intx, CIBreakAtOSR, -1, \ "The id of osr compilation to break at") \ \ develop(intx, CIBreakAt, -1, \ "The id of compilation to break at") \ \ product(ccstrlist, CompileOnly, "", \ "List of methods (pkg/class.name) to restrict compilation to") \ \ product(ccstr, CompileCommandFile, NULL, \ "Read compiler commands from this file [.hotspot_compiler]") \ \ diagnostic(ccstr, CompilerDirectivesFile, NULL, \ "Read compiler directives from this file") \ \ product(ccstrlist, CompileCommand, "", \ "Prepend to .hotspot_compiler; e.g. log,java/lang/String.<init>") \ \ develop(bool, ReplayCompiles, false, \ "Enable replay of compilations from ReplayDataFile") \ \ product(ccstr, ReplayDataFile, NULL, \ "File containing compilation replay information" \ "[default: ./replay_pid%p.log] (%p replaced with pid)") \ \ product(ccstr, InlineDataFile, NULL, \ "File containing inlining replay information" \ "[default: ./inline_pid%p.log] (%p replaced with pid)") \ \ develop(intx, ReplaySuppressInitializers, 2, \ "Control handling of class initialization during replay: " \ "0 - don't do anything special; " \ "1 - treat all class initializers as empty; " \ "2 - treat class initializers for application classes as empty; " \ "3 - allow all class initializers to run during bootstrap but " \ " pretend they are empty after starting replay") \ range(0, 3) \ \ develop(bool, ReplayIgnoreInitErrors, false, \ "Ignore exceptions thrown during initialization for replay") \ \ product(bool, DumpReplayDataOnError, true, \ "Record replay data for crashing compiler threads") \ \ product(bool, CICompilerCountPerCPU, false, \ "1 compiler thread for log(N CPUs)") \ \ notproduct(intx, CICrashAt, -1, \ "id of compilation to trigger assert in compiler thread for " \ "the purpose of testing, e.g. generation of replay data") \ notproduct(bool, CIObjectFactoryVerify, false, \ "enable potentially expensive verification in ciObjectFactory") \ \ diagnostic(bool, AbortVMOnCompilationFailure, false, \ "Abort VM when method had failed to compile.") \ \ /* Priorities */ \ product_pd(bool, UseThreadPriorities, "Use native thread priorities") \ \ product(intx, ThreadPriorityPolicy, 0, \ "0 : Normal. "\ " VM chooses priorities that are appropriate for normal "\ " applications. On Solaris NORM_PRIORITY and above are mapped "\ " to normal native priority. Java priorities below " \ " NORM_PRIORITY map to lower native priority values. On "\ " Windows applications are allowed to use higher native "\ " priorities. However, with ThreadPriorityPolicy=0, VM will "\ " not use the highest possible native priority, "\ " THREAD_PRIORITY_TIME_CRITICAL, as it may interfere with "\ " system threads. On Linux thread priorities are ignored "\ " because the OS does not support static priority in "\ " SCHED_OTHER scheduling class which is the only choice for "\ " non-root, non-realtime applications. "\ "1 : Aggressive. "\ " Java thread priorities map over to the entire range of "\ " native thread priorities. Higher Java thread priorities map "\ " to higher native thread priorities. This policy should be "\ " used with care, as sometimes it can cause performance "\ " degradation in the application and/or the entire system. On "\ " Linux/BSD/macOS this policy requires root privilege or an "\ " extended capability.") \ range(0, 1) \ \ product(bool, ThreadPriorityVerbose, false, \ "Print priority changes") \ \ product(intx, CompilerThreadPriority, -1, \ "The native priority at which compiler threads should run " \ "(-1 means no change)") \ range(min_jint, max_jint) \ constraint(CompilerThreadPriorityConstraintFunc, AfterErgo) \ \ product(intx, VMThreadPriority, -1, \ "The native priority at which the VM thread should run " \ "(-1 means no change)") \ range(-1, 127) \ \ product(intx, JavaPriority1_To_OSPriority, -1, \ "Map Java priorities to OS priorities") \ range(-1, 127) \ \ product(intx, JavaPriority2_To_OSPriority, -1, \ "Map Java priorities to OS priorities") \ range(-1, 127) \ \ product(intx, JavaPriority3_To_OSPriority, -1, \ "Map Java priorities to OS priorities") \ range(-1, 127) \ \ product(intx, JavaPriority4_To_OSPriority, -1, \ "Map Java priorities to OS priorities") \ range(-1, 127) \ \ product(intx, JavaPriority5_To_OSPriority, -1, \ "Map Java priorities to OS priorities") \ range(-1, 127) \ \ product(intx, JavaPriority6_To_OSPriority, -1, \ "Map Java priorities to OS priorities") \ range(-1, 127) \ \ product(intx, JavaPriority7_To_OSPriority, -1, \ "Map Java priorities to OS priorities") \ range(-1, 127) \ \ product(intx, JavaPriority8_To_OSPriority, -1, \ "Map Java priorities to OS priorities") \ range(-1, 127) \ \ product(intx, JavaPriority9_To_OSPriority, -1, \ "Map Java priorities to OS priorities") \ range(-1, 127) \ \ product(intx, JavaPriority10_To_OSPriority,-1, \ "Map Java priorities to OS priorities") \ range(-1, 127) \ \ experimental(bool, UseCriticalJavaThreadPriority, false, \ "Java thread priority 10 maps to critical scheduling priority") \ \ experimental(bool, UseCriticalCompilerThreadPriority, false, \ "Compiler thread(s) run at critical scheduling priority") \ \ develop(intx, NewCodeParameter, 0, \ "Testing Only: Create a dedicated integer parameter before " \ "putback") \ \ /* new oopmap storage allocation */ \ develop(intx, MinOopMapAllocation, 8, \ "Minimum number of OopMap entries in an OopMapSet") \ \ /* Background Compilation */ \ develop(intx, LongCompileThreshold, 50, \ "Used with +TraceLongCompiles") \ \ /* recompilation */ \ product_pd(intx, CompileThreshold, \ "number of interpreted method invocations before (re-)compiling") \ constraint(CompileThresholdConstraintFunc, AfterErgo) \ \ product(double, CompileThresholdScaling, 1.0, \ "Factor to control when first compilation happens " \ "(both with and without tiered compilation): " \ "values greater than 1.0 delay counter overflow, " \ "values between 0 and 1.0 rush counter overflow, " \ "value of 1.0 leaves compilation thresholds unchanged " \ "value of 0.0 is equivalent to -Xint. " \ "" \ "Flag can be set as per-method option. " \ "If a value is specified for a method, compilation thresholds " \ "for that method are scaled by both the value of the global flag "\ "and the value of the per-method flag.") \ range(0.0, DBL_MAX) \ \ product(intx, Tier0InvokeNotifyFreqLog, 7, \ "Interpreter (tier 0) invocation notification frequency") \ range(0, 30) \ \ product(intx, Tier2InvokeNotifyFreqLog, 11, \ "C1 without MDO (tier 2) invocation notification frequency") \ range(0, 30) \ \ product(intx, Tier3InvokeNotifyFreqLog, 10, \ "C1 with MDO profiling (tier 3) invocation notification " \ "frequency") \ range(0, 30) \ \ product(intx, Tier23InlineeNotifyFreqLog, 20, \ "Inlinee invocation (tiers 2 and 3) notification frequency") \ range(0, 30) \ \ product(intx, Tier0BackedgeNotifyFreqLog, 10, \ "Interpreter (tier 0) invocation notification frequency") \ range(0, 30) \ \ product(intx, Tier2BackedgeNotifyFreqLog, 14, \ "C1 without MDO (tier 2) invocation notification frequency") \ range(0, 30) \ \ product(intx, Tier3BackedgeNotifyFreqLog, 13, \ "C1 with MDO profiling (tier 3) invocation notification " \ "frequency") \ range(0, 30) \ \ product(intx, Tier2CompileThreshold, 0, \ "threshold at which tier 2 compilation is invoked") \ range(0, max_jint) \ \ product(intx, Tier2BackEdgeThreshold, 0, \ "Back edge threshold at which tier 2 compilation is invoked") \ range(0, max_jint) \ \ product(intx, Tier3InvocationThreshold, 200, \ "Compile if number of method invocations crosses this " \ "threshold") \ range(0, max_jint) \ \ product(intx, Tier3MinInvocationThreshold, 100, \ "Minimum invocation to compile at tier 3") \ range(0, max_jint) \ \ product(intx, Tier3CompileThreshold, 2000, \ "Threshold at which tier 3 compilation is invoked (invocation " \ "minimum must be satisfied)") \ range(0, max_jint) \ \ product(intx, Tier3BackEdgeThreshold, 60000, \ "Back edge threshold at which tier 3 OSR compilation is invoked") \ range(0, max_jint) \ \ product(intx, Tier3AOTInvocationThreshold, 10000, \ "Compile if number of method invocations crosses this " \ "threshold if coming from AOT") \ range(0, max_jint) \ \ product(intx, Tier3AOTMinInvocationThreshold, 1000, \ "Minimum invocation to compile at tier 3 if coming from AOT") \ range(0, max_jint) \ \ product(intx, Tier3AOTCompileThreshold, 15000, \ "Threshold at which tier 3 compilation is invoked (invocation " \ "minimum must be satisfied) if coming from AOT") \ range(0, max_jint) \ \ product(intx, Tier3AOTBackEdgeThreshold, 120000, \ "Back edge threshold at which tier 3 OSR compilation is invoked " \ "if coming from AOT") \ range(0, max_jint) \ \ diagnostic(intx, Tier0AOTInvocationThreshold, 200, \ "Switch to interpreter to profile if the number of method " \ "invocations crosses this threshold if coming from AOT " \ "(applicable only with " \ "CompilationMode=high-only|high-only-quick-internal)") \ range(0, max_jint) \ \ diagnostic(intx, Tier0AOTMinInvocationThreshold, 100, \ "Minimum number of invocations to switch to interpreter " \ "to profile if coming from AOT " \ "(applicable only with " \ "CompilationMode=high-only|high-only-quick-internal)") \ range(0, max_jint) \ \ diagnostic(intx, Tier0AOTCompileThreshold, 2000, \ "Threshold at which to switch to interpreter to profile " \ "if coming from AOT " \ "(invocation minimum must be satisfied, " \ "applicable only with " \ "CompilationMode=high-only|high-only-quick-internal)") \ range(0, max_jint) \ \ diagnostic(intx, Tier0AOTBackEdgeThreshold, 60000, \ "Back edge threshold at which to switch to interpreter " \ "to profile if coming from AOT " \ "(applicable only with " \ "CompilationMode=high-only|high-only-quick-internal)") \ range(0, max_jint) \ \ product(intx, Tier4InvocationThreshold, 5000, \ "Compile if number of method invocations crosses this " \ "threshold") \ range(0, max_jint) \ \ product(intx, Tier4MinInvocationThreshold, 600, \ "Minimum invocation to compile at tier 4") \ range(0, max_jint) \ \ product(intx, Tier4CompileThreshold, 15000, \ "Threshold at which tier 4 compilation is invoked (invocation " \ "minimum must be satisfied)") \ range(0, max_jint) \ \ product(intx, Tier4BackEdgeThreshold, 40000, \ "Back edge threshold at which tier 4 OSR compilation is invoked") \ range(0, max_jint) \ \ diagnostic(intx, Tier40InvocationThreshold, 5000, \ "Compile if number of method invocations crosses this " \ "threshold (applicable only with " \ "CompilationMode=high-only|high-only-quick-internal)") \ range(0, max_jint) \ \ diagnostic(intx, Tier40MinInvocationThreshold, 600, \ "Minimum number of invocations to compile at tier 4 " \ "(applicable only with " \ "CompilationMode=high-only|high-only-quick-internal)") \ range(0, max_jint) \ \ diagnostic(intx, Tier40CompileThreshold, 10000, \ "Threshold at which tier 4 compilation is invoked (invocation " \ "minimum must be satisfied, applicable only with " \ "CompilationMode=high-only|high-only-quick-internal)") \ range(0, max_jint) \ \ diagnostic(intx, Tier40BackEdgeThreshold, 15000, \ "Back edge threshold at which tier 4 OSR compilation is invoked " \ "(applicable only with " \ "CompilationMode=high-only|high-only-quick-internal)") \ range(0, max_jint) \ \ diagnostic(intx, Tier0Delay, 5, \ "If C2 queue size grows over this amount per compiler thread " \ "do not start profiling in the interpreter " \ "(applicable only with " \ "CompilationMode=high-only|high-only-quick-internal)") \ range(0, max_jint) \ \ product(intx, Tier3DelayOn, 5, \ "If C2 queue size grows over this amount per compiler thread " \ "stop compiling at tier 3 and start compiling at tier 2") \ range(0, max_jint) \ \ product(intx, Tier3DelayOff, 2, \ "If C2 queue size is less than this amount per compiler thread " \ "allow methods compiled at tier 2 transition to tier 3") \ range(0, max_jint) \ \ product(intx, Tier3LoadFeedback, 5, \ "Tier 3 thresholds will increase twofold when C1 queue size " \ "reaches this amount per compiler thread") \ range(0, max_jint) \ \ product(intx, Tier4LoadFeedback, 3, \ "Tier 4 thresholds will increase twofold when C2 queue size " \ "reaches this amount per compiler thread") \ range(0, max_jint) \ \ product(intx, TieredCompileTaskTimeout, 50, \ "Kill compile task if method was not used within " \ "given timeout in milliseconds") \ range(0, max_intx) \ \ product(intx, TieredStopAtLevel, 4, \ "Stop at given compilation level") \ range(0, 4) \ \ product(intx, Tier0ProfilingStartPercentage, 200, \ "Start profiling in interpreter if the counters exceed tier 3 " \ "thresholds (tier 4 thresholds with " \ "CompilationMode=high-only|high-only-quick-internal)" \ "by the specified percentage") \ range(0, max_jint) \ \ product(uintx, IncreaseFirstTierCompileThresholdAt, 50, \ "Increase the compile threshold for C1 compilation if the code " \ "cache is filled by the specified percentage") \ range(0, 99) \ \ product(intx, TieredRateUpdateMinTime, 1, \ "Minimum rate sampling interval (in milliseconds)") \ range(0, max_intx) \ \ product(intx, TieredRateUpdateMaxTime, 25, \ "Maximum rate sampling interval (in milliseconds)") \ range(0, max_intx) \ \ product(ccstr, CompilationMode, "default", \ "Compilation modes: " \ "default: normal tiered compilation; " \ "quick-only: C1-only mode; " \ "high-only: C2/JVMCI-only mode; " \ "high-only-quick-internal: C2/JVMCI-only mode, " \ "with JVMCI compiler compiled with C1.") \ \ product_pd(bool, TieredCompilation, \ "Enable tiered compilation") \ \ product(bool, PrintTieredEvents, false, \ "Print tiered events notifications") \ \ product_pd(intx, OnStackReplacePercentage, \ "NON_TIERED number of method invocations/branches (expressed as " \ "% of CompileThreshold) before (re-)compiling OSR code") \ constraint(OnStackReplacePercentageConstraintFunc, AfterErgo) \ \ product(intx, InterpreterProfilePercentage, 33, \ "NON_TIERED number of method invocations/branches (expressed as " \ "% of CompileThreshold) before profiling in the interpreter") \ range(0, 100) \ \ develop(intx, DesiredMethodLimit, 8000, \ "The desired maximum method size (in bytecodes) after inlining") \ \ develop(intx, HugeMethodLimit, 8000, \ "Don't compile methods larger than this if " \ "+DontCompileHugeMethods") \ \ /* Properties for Java libraries */ \ \ product(uint64_t, MaxDirectMemorySize, 0, \ "Maximum total size of NIO direct-buffer allocations") \ range(0, max_jlong) \ \ /* Flags used for temporary code during development */ \ \ diagnostic(bool, UseNewCode, false, \ "Testing Only: Use the new version while testing") \ \ diagnostic(bool, UseNewCode2, false, \ "Testing Only: Use the new version while testing") \ \ diagnostic(bool, UseNewCode3, false, \ "Testing Only: Use the new version while testing") \ \ /* flags for performance data collection */ \ \ product(bool, UsePerfData, true, \ "Flag to disable jvmstat instrumentation for performance testing "\ "and problem isolation purposes") \ \ product(bool, PerfDataSaveToFile, false, \ "Save PerfData memory to hsperfdata_<pid> file on exit") \ \ product(ccstr, PerfDataSaveFile, NULL, \ "Save PerfData memory to the specified absolute pathname. " \ "The string %p in the file name (if present) " \ "will be replaced by pid") \ \ product(intx, PerfDataSamplingInterval, 50, \ "Data sampling interval (in milliseconds)") \ range(PeriodicTask::min_interval, max_jint) \ constraint(PerfDataSamplingIntervalFunc, AfterErgo) \ \ product(bool, PerfDisableSharedMem, false, \ "Store performance data in standard memory") \ \ product(intx, PerfDataMemorySize, 32*K, \ "Size of performance data memory region. Will be rounded " \ "up to a multiple of the native os page size.") \ range(128, 32*64*K) \ \ product(intx, PerfMaxStringConstLength, 1024, \ "Maximum PerfStringConstant string length before truncation") \ range(32, 32*K) \ \ product(bool, PerfAllowAtExitRegistration, false, \ "Allow registration of atexit() methods") \ \ product(bool, PerfBypassFileSystemCheck, false, \ "Bypass Win32 file system criteria checks (Windows Only)") \ \ product(intx, UnguardOnExecutionViolation, 0, \ "Unguard page and retry on no-execute fault (Win32 only) " \ "0=off, 1=conservative, 2=aggressive") \ range(0, 2) \ \ /* Serviceability Support */ \ \ product(bool, ManagementServer, false, \ "Create JMX Management Server") \ \ product(bool, DisableAttachMechanism, false, \ "Disable mechanism that allows tools to attach to this VM") \ \ product(bool, StartAttachListener, false, \ "Always start Attach Listener at VM startup") \ \ product(bool, EnableDynamicAgentLoading, true, \ "Allow tools to load agents with the attach mechanism") \ \ manageable(bool, PrintConcurrentLocks, false, \ "Print java.util.concurrent locks in thread dump") \ \ /* Shared spaces */ \ \ product(bool, UseSharedSpaces, true, \ "Use shared spaces for metadata") \ \ product(bool, VerifySharedSpaces, false, \ "Verify integrity of shared spaces") \ \ product(bool, RequireSharedSpaces, false, \ "Require shared spaces for metadata") \ \ product(bool, DumpSharedSpaces, false, \ "Special mode: JVM reads a class list, loads classes, builds " \ "shared spaces, and dumps the shared spaces to a file to be " \ "used in future JVM runs") \ \ product(bool, DynamicDumpSharedSpaces, false, \ "Dynamic archive") \ \ product(bool, PrintSharedArchiveAndExit, false, \ "Print shared archive file contents") \ \ product(bool, PrintSharedDictionary, false, \ "If PrintSharedArchiveAndExit is true, also print the shared " \ "dictionary") \ \ product(size_t, SharedBaseAddress, LP64_ONLY(32*G) \ NOT_LP64(LINUX_ONLY(2*G) NOT_LINUX(0)), \ "Address to allocate shared memory region for class data") \ range(0, SIZE_MAX) \ \ product(ccstr, SharedArchiveConfigFile, NULL, \ "Data to add to the CDS archive file") \ \ product(uintx, SharedSymbolTableBucketSize, 4, \ "Average number of symbols per bucket in shared table") \ range(2, 246) \ \ diagnostic(bool, AllowArchivingWithJavaAgent, false, \ "Allow Java agent to be run with CDS dumping") \ \ diagnostic(bool, PrintMethodHandleStubs, false, \ "Print generated stub code for method handles") \ \ develop(bool, TraceMethodHandles, false, \ "trace internal method handle operations") \ \ diagnostic(bool, VerifyMethodHandles, trueInDebug, \ "perform extra checks when constructing method handles") \ \ diagnostic(bool, ShowHiddenFrames, false, \ "show method handle implementation frames (usually hidden)") \ \ experimental(bool, TrustFinalNonStaticFields, false, \ "trust final non-static declarations for constant folding") \ \ diagnostic(bool, FoldStableValues, true, \ "Optimize loads from stable fields (marked w/ @Stable)") \ \ develop(bool, TraceInvokeDynamic, false, \ "trace internal invoke dynamic operations") \ \ diagnostic(int, UseBootstrapCallInfo, 1, \ "0: when resolving InDy or ConDy, force all BSM arguments to be " \ "resolved before the bootstrap method is called; 1: when a BSM " \ "that may accept a BootstrapCallInfo is detected, use that API " \ "to pass BSM arguments, which allows the BSM to delay their " \ "resolution; 2+: stress test the BCI API by calling more BSMs " \ "via that API, instead of with the eagerly-resolved array.") \ \ diagnostic(bool, PauseAtStartup, false, \ "Causes the VM to pause at startup time and wait for the pause " \ "file to be removed (default: ./vm.paused.<pid>)") \ \ diagnostic(ccstr, PauseAtStartupFile, NULL, \ "The file to create and for whose removal to await when pausing " \ "at startup. (default: ./vm.paused.<pid>)") \ \ diagnostic(bool, PauseAtExit, false, \ "Pause and wait for keypress on exit if a debugger is attached") \ \ product(bool, ExtendedDTraceProbes, false, \ "Enable performance-impacting dtrace probes") \ \ product(bool, DTraceMethodProbes, false, \ "Enable dtrace probes for method-entry and method-exit") \ \ product(bool, DTraceAllocProbes, false, \ "Enable dtrace probes for object allocation") \ \ product(bool, DTraceMonitorProbes, false, \ "Enable dtrace probes for monitor events") \ \ product(bool, RelaxAccessControlCheck, false, \ "Relax the access control checks in the verifier") \ \ product(uintx, StringTableSize, defaultStringTableSize, \ "Number of buckets in the interned String table " \ "(will be rounded to nearest higher power of 2)") \ range(minimumStringTableSize, 16777216ul /* 2^24 */) \ \ experimental(uintx, SymbolTableSize, defaultSymbolTableSize, \ "Number of buckets in the JVM internal Symbol table") \ range(minimumSymbolTableSize, 16777216ul /* 2^24 */) \ \ product(bool, UseStringDeduplication, false, \ "Use string deduplication") \ \ product(uintx, StringDeduplicationAgeThreshold, 3, \ "A string must reach this age (or be promoted to an old region) " \ "to be considered for deduplication") \ range(1, markWord::max_age) \ \ diagnostic(bool, StringDeduplicationResizeALot, false, \ "Force table resize every time the table is scanned") \ \ diagnostic(bool, StringDeduplicationRehashALot, false, \ "Force table rehash every time the table is scanned") \ \ diagnostic(bool, WhiteBoxAPI, false, \ "Enable internal testing APIs") \ \ experimental(intx, SurvivorAlignmentInBytes, 0, \ "Default survivor space alignment in bytes") \ range(8, 256) \ constraint(SurvivorAlignmentInBytesConstraintFunc,AfterErgo) \ \ product(ccstr, DumpLoadedClassList, NULL, \ "Dump the names all loaded classes, that could be stored into " \ "the CDS archive, in the specified file") \ \ product(ccstr, SharedClassListFile, NULL, \ "Override the default CDS class list") \ \ product(ccstr, SharedArchiveFile, NULL, \ "Override the default location of the CDS archive file") \ \ product(ccstr, ArchiveClassesAtExit, NULL, \ "The path and name of the dynamic archive file") \ \ product(ccstr, ExtraSharedClassListFile, NULL, \ "Extra classlist for building the CDS archive file") \ \ diagnostic(intx, ArchiveRelocationMode, 0, \ "(0) first map at preferred address, and if " \ "unsuccessful, map at alternative address (default); " \ "(1) always map at alternative address; " \ "(2) always map at preferred address, and if unsuccessful, " \ "do not map the archive") \ range(0, 2) \ \ experimental(size_t, ArrayAllocatorMallocLimit, \ SOLARIS_ONLY(64*K) NOT_SOLARIS((size_t)-1), \ "Allocation less than this value will be allocated " \ "using malloc. Larger allocations will use mmap.") \ \ experimental(bool, AlwaysAtomicAccesses, false, \ "Accesses to all variables should always be atomic") \ \ diagnostic(bool, UseUnalignedAccesses, false, \ "Use unaligned memory accesses in Unsafe") \ \ product_pd(bool, PreserveFramePointer, \ "Use the FP register for holding the frame pointer " \ "and not as a general purpose register.") \ \ diagnostic(bool, CheckIntrinsics, true, \ "When a class C is loaded, check that " \ "(1) all intrinsics defined by the VM for class C are present "\ "in the loaded class file and are marked with the " \ "@HotSpotIntrinsicCandidate annotation, that " \ "(2) there is an intrinsic registered for all loaded methods " \ "that are annotated with the @HotSpotIntrinsicCandidate " \ "annotation, and that " \ "(3) no orphan methods exist for class C (i.e., methods for " \ "which the VM declares an intrinsic but that are not declared "\ "in the loaded class C. " \ "Check (3) is available only in debug builds.") \ \ diagnostic_pd(intx, InitArrayShortSize, \ "Threshold small size (in bytes) for clearing arrays. " \ "Anything this size or smaller may get converted to discrete " \ "scalar stores.") \ range(0, max_intx) \ constraint(InitArrayShortSizeConstraintFunc, AfterErgo) \ \ diagnostic(bool, CompilerDirectivesIgnoreCompileCommands, false, \ "Disable backwards compatibility for compile commands.") \ \ diagnostic(bool, CompilerDirectivesPrint, false, \ "Print compiler directives on installation.") \ diagnostic(int, CompilerDirectivesLimit, 50, \ "Limit on number of compiler directives.") \ \ product(ccstr, AllocateHeapAt, NULL, \ "Path to the directoy where a temporary file will be created " \ "to use as the backing store for Java Heap.") \ \ experimental(ccstr, AllocateOldGenAt, NULL, \ "Path to the directoy where a temporary file will be " \ "created to use as the backing store for old generation." \ "File of size Xmx is pre-allocated for performance reason, so" \ "we need that much space available") \ \ develop(int, VerifyMetaspaceInterval, DEBUG_ONLY(500) NOT_DEBUG(0), \ "Run periodic metaspace verifications (0 - none, " \ "1 - always, >1 every nth interval)") \ \ diagnostic(bool, ShowRegistersOnAssert, true, \ "On internal errors, include registers in error report.") \ \ diagnostic(bool, UseSwitchProfiling, true, \ "leverage profiling for table/lookup switch") \ \ develop(bool, TraceMemoryWriteback, false, \ "Trace memory writeback operations") \ \ JFR_ONLY(product(bool, FlightRecorder, false, \ "(Deprecated) Enable Flight Recorder")) \ \ JFR_ONLY(product(ccstr, FlightRecorderOptions, NULL, \ "Flight Recorder options")) \ \ JFR_ONLY(product(ccstr, StartFlightRecording, NULL, \ "Start flight recording with options")) \ \ experimental(bool, UseFastUnorderedTimeStamps, false, \ "Use platform unstable time where supported for timestamps only") // Interface macros #define DECLARE_PRODUCT_FLAG(type, name, value, doc) extern "C" type name; #define DECLARE_PD_PRODUCT_FLAG(type, name, doc) extern "C" type name; #define DECLARE_DIAGNOSTIC_FLAG(type, name, value, doc) extern "C" type name; #define DECLARE_PD_DIAGNOSTIC_FLAG(type, name, doc) extern "C" type name; #define DECLARE_EXPERIMENTAL_FLAG(type, name, value, doc) extern "C" type name; #define DECLARE_MANAGEABLE_FLAG(type, name, value, doc) extern "C" type name; #define DECLARE_PRODUCT_RW_FLAG(type, name, value, doc) extern "C" type name; #ifdef PRODUCT #define DECLARE_DEVELOPER_FLAG(type, name, value, doc) const type name = value; #define DECLARE_PD_DEVELOPER_FLAG(type, name, doc) const type name = pd_##name; #define DECLARE_NOTPRODUCT_FLAG(type, name, value, doc) const type name = value; #else #define DECLARE_DEVELOPER_FLAG(type, name, value, doc) extern "C" type name; #define DECLARE_PD_DEVELOPER_FLAG(type, name, doc) extern "C" type name; #define DECLARE_NOTPRODUCT_FLAG(type, name, value, doc) extern "C" type name; #endif // PRODUCT // Special LP64 flags, product only needed for now. #ifdef _LP64 #define DECLARE_LP64_PRODUCT_FLAG(type, name, value, doc) extern "C" type name; #else #define DECLARE_LP64_PRODUCT_FLAG(type, name, value, doc) const type name = value; #endif // _LP64 ALL_FLAGS(DECLARE_DEVELOPER_FLAG, \ DECLARE_PD_DEVELOPER_FLAG, \ DECLARE_PRODUCT_FLAG, \ DECLARE_PD_PRODUCT_FLAG, \ DECLARE_DIAGNOSTIC_FLAG, \ DECLARE_PD_DIAGNOSTIC_FLAG, \ DECLARE_EXPERIMENTAL_FLAG, \ DECLARE_NOTPRODUCT_FLAG, \ DECLARE_MANAGEABLE_FLAG, \ DECLARE_PRODUCT_RW_FLAG, \ DECLARE_LP64_PRODUCT_FLAG, \ IGNORE_RANGE, \ IGNORE_CONSTRAINT, \ IGNORE_WRITEABLE) #endif // SHARE_RUNTIME_GLOBALS_HPP
gpl-2.0
kibbi10/myElog
scripts/ckeditor/plugins/image2/lang/sv.js
665
/* Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'image2', 'sv', { alt: 'Alternativ text', btnUpload: 'Skicka till server', captioned: 'Rubricerad bild', captionPlaceholder: 'Bildtext', infoTab: 'Bildinformation', lockRatio: 'Lås höjd/bredd förhållanden', menu: 'Bildegenskaper', pathName: 'bild', pathNameCaption: 'rubrik', resetSize: 'Återställ storlek', resizer: 'Klicka och drag för att ändra storlek', title: 'Bildegenskaper', uploadTab: 'Ladda upp', urlMissing: 'Bildkällans URL saknas.' } );
gpl-2.0
ankaOnyschenko/homework_7
wp-content/plugins/easy-custom-sidebars/views/admin-page/manage-control-form.php
1601
<?php /** * Manage Control Form * * A form to allow the user to quickly select another * sidebar to edit. * * @package Easy_Custom_Sidebars * @author Sunny Johal - Titanium Themes <support@titaniumthemes.com> * @license GPL-2.0+ * @copyright Copyright (c) 2014, Titanium Themes * @version 1.0 * */ ?> <div class="manage-sidebars manage-menus"> <form autocomplete="off" id="" action="" method="get" enctype="multipart/form-data"> <?php if ( $this->is_edit_screen() ) : ?> <input type="hidden" name="page" value="<?php echo $this->plugin_slug; ?>"> <input name="action" type="hidden" value="edit"> <label class="selected-menu" for="sidebar"><?php _e( 'Select a sidebar to edit:', 'easy-custom-sidebars' ); ?></label> <select autocomplete="off" name="sidebar" id="sidebar"> <?php foreach ( $this->custom_sidebars as $custom_sidebar_id => $custom_sidebar_name ) : ?> <option value="<?php echo $custom_sidebar_id; ?>" <?php if ( $custom_sidebar_id == $this->sidebar_selected_id ) : ?>selected<?php endif; ?>><?php echo $custom_sidebar_name; ?></option> <?php endforeach; ?> <?php submit_button( __( 'Select', 'easy-custom-sidebars' ), 'secondary', '', false ); ?> </select> <span class="add-new-menu-action"> or <a href="<?php echo $this->create_url; ?>"><?php _e( 'create a new sidebar', 'easy-custom-sidebars' ); ?></a> </span> <?php elseif ( $this->is_create_screen() ) : ?> <label><?php _e( 'Create a new Sidebar.', 'easy-custom-sidebars' ); ?></label> <?php endif ?> </form> </div><!-- END .manage-controls -->
gpl-2.0
jasonmunro/hm3
modules/account/modules.php
9045
<?php /** * Account modules * @package modules * @subpackage account */ if (!defined('DEBUG_MODE')) { die(); } /** * @subpackage account/handler */ class Hm_Handler_process_change_password extends Hm_Handler_Module { public function process() { if (!$this->session->internal_users) { return; } list($success, $form) = $this->process_form(array('new_pass1', 'new_pass2', 'old_pass', 'change_password')); if (!$success) { return; } if ($form['new_pass1'] !== $form['new_pass2']) { Hm_Msgs::add("ERRNew passwords don't not match"); return; } $user = $this->session->get('username', false); if (!$this->session->auth($user, $form['old_pass'])) { Hm_Msgs::add("ERRCurrent password is incorrect"); return; } $user_config = load_user_config_object($this->config); if ($this->session->change_pass($user, $form['new_pass1'])) { Hm_Msgs::add("Password changed"); $user_config->load($user, $form['old_pass']); $user_config->save($user, $form['new_pass1']); return; } Hm_Msgs::add("ERRAn error Occurred"); } } /** * @subpackage account/handler */ class Hm_Handler_process_delete_account extends Hm_Handler_Module { public function process() { if (!$this->session->is_admin()) { return; } if (!$this->session->internal_users) { return; } list($success, $form) = $this->process_form(array('delete_username')); if (!$success) { return; } $dbh = Hm_DB::connect($this->config); if (Hm_DB::execute($dbh, 'delete from hm_user where username=?', array($form['delete_username']))) { Hm_Msgs::add('User account deleted'); } else { Hm_Msgs::add('ERRAn error occurred deleting the account'); } } } /** * @subpackage account/handler */ class Hm_Handler_account_list extends Hm_Handler_Module { public function process() { if (!$this->session->is_admin()) { return; } if (!$this->session->internal_users) { return; } $dbh = Hm_DB::connect($this->config); $this->out('user_list', Hm_DB::execute($dbh, 'select username from hm_user', array(), false, true)); } } /** * @subpackage account/handler */ class Hm_Handler_process_create_account extends Hm_Handler_Module { public function process() { if (!$this->session->is_admin()) { return; } if (!$this->session->internal_users) { return; } list($success, $form) = $this->process_form(array('create_username', 'create_password', 'create_password_again')); if (!$success) { return; } if ($form['create_password'] != $form['create_password_again']) { Hm_Msgs::add('ERRPasswords did not match'); return; } $res = $this->session->create($form['create_username'], $form['create_password']); if ($res === 1) { Hm_Msgs::add("ERRThat username is already in use"); } elseif ($res === 2) { Hm_Msgs::add("Account Created"); } } } /** * @subpackage account/handler */ class Hm_Handler_check_internal_users extends Hm_Handler_Module { public function process() { $this->out('is_admin', $this->session->is_admin()); $this->out('internal_users', $this->session->internal_users); } } /** * @subpackage account/output */ class Hm_Output_create_account_link extends Hm_Output_Module { protected function output() { if (!$this->get('is_admin', false)) { $res = ''; } else { $res = '<li class="menu_create_account"><a class="unread_link" href="?page=accounts">'; if (!$this->get('hide_folder_icons')) { $res .= '<img class="account_icon" src="'.$this->html_safe(Hm_Image_Sources::$globe).'" alt="" '.'width="16" height="16" /> '; } $res .= $this->trans('Accounts').'</a></li>'; } if ($this->format == 'HTML5') { return $res; } $this->concat('formatted_folder_list', $res); } } /** * @subpackage account/output */ class Hm_Output_create_form extends Hm_Output_Module { protected function output() { if (!$this->get('internal_users') || !$this->get('is_admin', false)) { Hm_Dispatch::page_redirect('?page=home'); } return '<div class="content_title">'.$this->trans('Accounts').'</div>'. '<div class="settings_subtitle">'.$this->trans('Create Account').'</div>'. '<div class="create_user">'. '<form method="POST" autocomplete="off" >'. '<input type="hidden" name="hm_page_key" value="'.Hm_Request_Key::generate().'" />'. '<input style="display:none" type="text" name="fake_username" />'. '<input style="display:none" type="password" name="fake_password" />'. ' <input required type="text" placeholder="'.$this->trans('Username').'" name="create_username" value="">'. ' <input type="password" required placeholder="'.$this->trans('Password').'" name="create_password">'. ' <input type="password" required placeholder="'.$this->trans('Password Again').'" name="create_password_again">'. ' <input type="submit" name="create_hm_user" value="'.$this->trans('Create').'" />'. '</form></div>'; } } class Hm_Output_user_list extends Hm_Output_Module { protected function output() { $res = '<br /><div class="settings_subtitle">'.$this->trans('Existing Accounts').'</div>'; $res .= '<table class="user_list"><thead></thead><tbody>'; if ($this->get('is_mobile')) { $width = 2; } else { $width = 6; } $count = 0; foreach ($this->get('user_list', array()) as $user) { if ($count == 0) { $res .= '<tr>'; } $res .= '<td><form class="delete_user_form" action="?page=accounts" method="POST">'. '<input type="hidden" name="hm_page_key" value="'.Hm_Request_Key::generate().'" />'. '<input name="delete_username" type="hidden" value="'. $this->html_safe($user['username']).'" /><input class="user_delete" type="submit" '. 'value=" X " /></form>'; $res .= ' '.$this->html_safe($user['username']).'</td>'; $count++; if ($count == $width) { $res .= '</tr>'; $count = 0; } } if ($count != $width) { $res .= '</tr>'; } $res .= '</table>'; return $res; } } /** * Adds a link to the change password page to the folder list * @subpackage account/output */ class Hm_Output_change_password_link extends Hm_Output_Module { protected function output() { if ($this->get('internal_users')) { $res = '<li class="menu_change_password"><a class="unread_link" href="?page=change_password">'; if (!$this->get('hide_folder_icons')) { $res .= '<img class="account_icon" src="'.$this->html_safe(Hm_Image_Sources::$key).'" alt="" width="16" height="16" /> '; } $res .= $this->trans('Password').'</a></li>'; $this->concat('formatted_folder_list', $res); } } } /** * @subpackage account/output */ class Hm_Output_change_password extends Hm_Output_Module { protected function output() { $res = ''; if ($this->get('internal_users')) { $res .= '<div class="chg_pass_page"><div class="content_title">'.$this->trans('Change Password').'</div>'. '<div class="change_pass"><form method="POST">'. '<input type="hidden" name="hm_page_key" value="'.Hm_Request_Key::generate().'" />'. '<label class="screen_reader" for="old_pass">'.$this->trans('Current password').'</label>'. '<input required type="password" id="old_pass" name="old_pass" placeholder="'.$this->trans('Current password').'" /><br />'. '<label class="screen_reader" for="new_pass1">'.$this->trans('New password').'</label>'. '<input required type="password" id="new_pass1" name="new_pass1" placeholder="'.$this->trans('New password').'" /><br />'. '<label class="screen_reader" for="new_pass2">'.$this->trans('New password again').'</label>'. '<input required type="password" id="new_pass2" name="new_pass2" placeholder="'.$this->trans('New password again').'" /><br />'. '<input type="submit" name="change_password" value="'.$this->trans('Update').'" />'; $res .= '</form></div></div>'; } return $res; } }
gpl-2.0
ROLE/widget-store
src/main/drupal/sites/all/libraries/shindig2.5beta/src/apache/shindig/social/service/RestRequestItem.php
7483
<?php namespace apache\shindig\social\service; use apache\shindig\common\IllegalArgumentException; use apache\shindig\common\Config; use apache\shindig\common\SecurityToken; /* * 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. */ /** * Represents the request items that come from the restful request. */ class RestRequestItem extends RequestItem { /** * * @var string */ private $url; /** * * @var array */ private $params; /** * @var string */ private $inputConverterMethod; /** * @var OutputConverter */ private $outputConverter; /** * * @var string */ private $postData; /** * * @param object $service * @param string $method * @param SecurityToken $token * @param string $inputConverterMethod * @param OutputConverter $outputConverter */ public function __construct($service, $method, SecurityToken $token, $inputConverterMethod, $outputConverter) { parent::__construct($service, $method, $token); $this->inputConverterMethod = $inputConverterMethod; $this->outputConverter = $outputConverter; } /** * @param $servletRequest * @param SecurityToken $token * @param string $inputConverterMethod * @param OutputConverter $outputConverter * @return RestRequestItem */ public static function createWithRequest($servletRequest, $token, $inputConverterMethod, $outputConverter) { $restfulRequestItem = new RestRequestItem(self::getServiceFromPath($servletRequest['url']), self::getMethod(), $token, $inputConverterMethod, $outputConverter); $restfulRequestItem->setUrl($servletRequest['url']); if (isset($servletRequest['params'])) { $restfulRequestItem->setParams($servletRequest['params']); } else { $paramPieces = parse_url($restfulRequestItem->url); if (isset($paramPieces['query'])) { $params = array(); parse_str($paramPieces['query'], $params); $restfulRequestItem->setParams($params); } } if (isset($servletRequest['postData'])) { $restfulRequestItem->setPostData($servletRequest['postData']); } return $restfulRequestItem; } /** * * @param string $url */ public function setUrl($url) { $this->url = $url; } /** * * @param array $params */ public function setParams($params) { $this->params = $params; } /** * * @param string $postData */ public function setPostData($postData) { $this->postData = $postData; $service = $this->getServiceFromPath($this->url); $inputConverterConfig = Config::get('service_input_converter'); if (isset($inputConverterConfig[$service])) { $class = $inputConverterConfig[$service]['class']; $inputConverter = new $class(); $data = $inputConverter->{$this->inputConverterMethod}($this->postData); $targetField = $inputConverterConfig[$service]['targetField']; if ($targetField !== false && isset($data)) { if ($targetField !== null) { $this->params[$targetField] = $data; } else { $this->params = $data; } } } else { throw new \Exception("Invalid or unknown service endpoint: $service"); } } /** * '/people/@me/@self' => 'people' * '/invalidate?invalidationKey=1' => 'invalidate' * * @param string $pathInfo * @return $pathInfo */ static function getServiceFromPath($pathInfo) { $pathInfo = substr($pathInfo, 1); $indexOfNextPathSeparator = strpos($pathInfo, '/'); $indexOfNextQuestionMark = strpos($pathInfo, '?'); if ($indexOfNextPathSeparator !== false && $indexOfNextQuestionMark !== false) { return substr($pathInfo, 0, min($indexOfNextPathSeparator, $indexOfNextQuestionMark)); } if ($indexOfNextPathSeparator !== false) { return substr($pathInfo, 0, $indexOfNextPathSeparator); } if ($indexOfNextQuestionMark !== false) { return substr($pathInfo, 0, $indexOfNextQuestionMark); } return $pathInfo; } /** * * @return string */ static function getMethod() { if (isset($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'])) { return $_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE']; } else { return $_SERVER['REQUEST_METHOD']; } } /** * This could definitely be cleaner.. * TODO: Come up with a cleaner way to handle all of this code. * * @param urlTemplate The template the url follows */ public function applyUrlTemplate($urlTemplate) { $paramPieces = @parse_url($this->url); $actualUrl = explode("/", $paramPieces['path']); $expectedUrl = explode("/", $urlTemplate); for ($i = 1; $i < count($actualUrl); $i ++) { $actualPart = isset($actualUrl[$i]) ? $actualUrl[$i] : null; $expectedPart = isset($expectedUrl[$i]) ? $expectedUrl[$i] : null; if (strpos($expectedPart, "{") !== false) { $this->params[preg_replace('/\{|\}/', '', $expectedPart)] = explode(',', $actualPart); } elseif (strpos($actualPart, ',') !== false) { throw new IllegalArgumentException("Cannot expect plural value " + $actualPart + " for singular field " + $expectedPart + " in " + $this->url); } else { $this->params[$expectedPart] = $actualPart; } } } /** * * @return aray */ public function getParameters() { return $this->params; } /** * * @param string $paramName * @param string $paramValue */ public function setParameter($paramName, $paramValue) { // Ignore nulls if ($paramValue == null) { return; } $this->params[$paramName] = $paramValue; } /** * Return a single param value * * @param string $paramName * @param string $defaultValue * @return string */ public function getParameter($paramName, $defaultValue = null) { $paramValue = isset($this->params[$paramName]) ? $this->params[$paramName] : null; if ($paramValue != null && ! empty($paramValue)) { return $paramValue; } return $defaultValue; } /** * Return a list param value * * @param string $paramName * @return array */ public function getListParameter($paramName) { $stringList = isset($this->params[$paramName]) ? $this->params[$paramName] : null; if ($stringList == null) { return array(); } elseif (is_array($stringList)) { // already converted to array, return straight away return $stringList; } if (strpos($stringList, ',') !== false) { $stringList = explode(',', $stringList); } else { // Allow up-conversion of non-array to array params. $stringList = array($stringList); } $this->params[$paramName] = $stringList; return $stringList; } }
gpl-2.0
easyw/kicad-3d-models-in-freecad
cadquery/FCAD_script_generator/CP_Tantalum_THT/main_generator.py
14397
# -*- coding: utf8 -*- #!/usr/bin/python # # This is derived from a cadquery script for generating QFP models in X3D format. # # from https://bitbucket.org/hyOzd/freecad-macros # author hyOzd # # Dimensions are from Jedec MS-026D document. ## requirements ## cadquery FreeCAD plugin ## https://github.com/jmwright/cadquery-freecad-module ## to run the script just do: freecad main_generator.py modelName ## e.g. c:\freecad\bin\freecad main_generator.py L35_D12.5_p05 ## the script will generate STEP and VRML parametric models ## to be used with kicad StepUp script #* These are a FreeCAD & cadquery tools * #* to export generated models in STEP & VRML format. * #* * #* cadquery script for generating QFP/SOIC/SSOP/TSSOP models in STEP AP214 * #* Copyright (c) 2015 * #* Maurice https://launchpad.net/~easyw * #* All trademarks within this guide belong to their legitimate owners. * #* * #* This program is free software; you can redistribute it and/or modify * #* it under the terms of the GNU Lesser General Public License (LGPL) * #* as published by the Free Software Foundation; either version 2 of * #* the License, or (at your option) any later version. * #* for detail see the LICENCE text file. * #* * #* 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 Library General Public License for more details. * #* * #* You should have received a copy of the GNU Library 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 * #* * #**************************************************************************** __title__ = "make Radial Caps 3D models" __author__ = "maurice and hyOzd and Frank" __Comment__ = 'make C axial Caps 3D models exported to STEP and VRML for Kicad StepUP script' ___ver___ = "1.3.2 10/02/2017" # maui import cadquery as cq # maui from Helpers import show from math import tan, radians, sqrt, sin, degrees from collections import namedtuple global save_memory save_memory = False #reducing memory consuming for all generation params check_Model = True stop_on_first_error = True check_log_file = 'check-log.md' import sys, os import datetime from datetime import datetime sys.path.append("../_tools") import exportPartToVRML as expVRML import shaderColors body_color_key = "orange body" body_color = shaderColors.named_colors[body_color_key].getDiffuseFloat() pins_color_key = "metal grey pins" pins_color = shaderColors.named_colors[pins_color_key].getDiffuseFloat() marking_color_key = "light brown body" marking_color = shaderColors.named_colors[marking_color_key].getDiffuseFloat() # maui start import FreeCAD, Draft, FreeCADGui import ImportGui import FreeCADGui as Gui #from Gui.Command import * cd_new_notfound=False cd_notfound=False try: from CadQuery.Gui.Command import * except: cd_new_notfound=True try: from Gui.Command import * except: cd_notfound=True if cd_new_notfound and cd_notfound: msg="missing CadQuery 0.3.0 or later Module!\r\n\r\n" msg+="https://github.com/jmwright/cadquery-freecad-module/wiki\n" reply = QtGui.QMessageBox.information(None,"Info ...",msg) outdir=os.path.dirname(os.path.realpath(__file__)+"/../_3Dmodels") scriptdir=os.path.dirname(os.path.realpath(__file__)) sys.path.append(outdir) sys.path.append(scriptdir) if FreeCAD.GuiUp: from PySide import QtCore, QtGui # Licence information of the generated models. ################################################################################################# STR_licAuthor = "kicad StepUp" STR_licEmail = "ksu" STR_licOrgSys = "kicad StepUp" STR_licPreProc = "OCC" STR_licOrg = "FreeCAD" LIST_license = ["",] ################################################################################################# try: # Gui.SendMsgToActiveView("Run") # cq Gui #from Gui.Command import * Gui.activateWorkbench("CadQueryWorkbench") import cadquery as cq from Helpers import show # CadQuery Gui except Exception as e: # catch *all* exceptions print(e) msg="missing CadQuery 0.3.0 or later Module!\r\n\r\n" msg+="https://github.com/jmwright/cadquery-freecad-module/wiki\n" reply = QtGui.QMessageBox.information(None,"Info ...",msg) # maui end # Import cad_tools from cqToolsExceptions import * import cq_cad_tools # Reload tools reload(cq_cad_tools) # Explicitly load all needed functions from cq_cad_tools import FuseObjs_wColors, GetListOfObjects, restore_Main_Tools, \ exportSTEP, close_CQ_Example, exportVRML, saveFCdoc, z_RotateObject, Color_Objects, \ CutObjs_wColors, checkRequirements, runGeometryCheck #checking requirements checkRequirements(cq) try: close_CQ_Example(App, Gui) except: # catch *all* exceptions print "CQ 030 doesn't open example file" import cq_parameters # modules parameters from cq_parameters import * #all_params = all_params_c_axial_th_cap all_params = kicad_naming_params_c_axial_th_cap def make_tantalum_th(params): L = params.L # body length W = params.W # body width d = params.d # lead diameter F = params.F # lead separation (center to center) ll = params.ll # lead length bs = params.bs # board separation rot = params.rotation dest_dir_pref = params.dest_dir_prefix bend_offset_y = (sin(radians(60.0))*d)/sin(radians(90.0)) bend_offset_z = (sin(radians(30.0))*d)/sin(radians(90.0)) # draw the leads lead1 = cq.Workplane("XY").workplane(offset=-ll).center(-F/2,0).circle(d/2).extrude(ll+L/4-d+bs) lead1 = lead1.union(cq.Workplane("XY").workplane(offset=L/4-d+bs).center(-F/2,0).circle(d/2).center(-F/2+d/2,0).revolve(30,(-F/2+d/2+d,d)).transformed((-30,0,0),(-(-F/2+d/2),d-bend_offset_y,bend_offset_z)).circle(d/2).extrude(L/2)) lead1 = lead1.rotate((-F/2,0,0), (0,0,1), -90) lead2 = lead1.rotate((-F/2,0,0), (0,0,1), 180).translate((F,0,0)) leads = lead1.union(lead2) oval_base_w = 2*d oval_base_L = L*0.7 body = cq.Workplane("XY").workplane(offset=bs).moveTo(-(oval_base_L/2-d), -oval_base_w/2).threePointArc((-oval_base_L/2, 0),(-(oval_base_L/2-d),oval_base_w/2)).line(oval_base_L-d*2,0).\ threePointArc((oval_base_L/2, 0),(oval_base_L/2-d,-oval_base_w/2)).close().extrude(d).edges("<Z").fillet(d/4) body = body.union(cq.Workplane("XY").workplane(offset=bs+d).moveTo(-(oval_base_L/2-d), -oval_base_w/2).threePointArc((-oval_base_L/2, 0),(-(oval_base_L/2-d),oval_base_w/2)).line(oval_base_L-d*2,0).\ threePointArc((oval_base_L/2, 0),(oval_base_L/2-d,-oval_base_w/2)).close().workplane(offset=L).circle(L/2).loft(combine=True)) middlepoint = (sin(radians(45.0))*L/2)/sin(radians(90.0)) body = body.union(cq.Workplane("YZ").moveTo(0,bs+d+L).vLine(L/2,forConstruction=False).threePointArc((middlepoint, bs+d+L+middlepoint),(L/2, bs+d+L),forConstruction=False).close().revolve()) plussize = L/3 plusthickness = plussize/3 pinmark = cq.Workplane("XZ").workplane(offset=-L/2-1).moveTo(-plusthickness/2-L/4,bs+d+L+plusthickness/2).line(0,plusthickness).line(plusthickness,0).line(0,-plusthickness).line(plusthickness,0).\ line(0,-plusthickness).line(-plusthickness,0).line(0,-plusthickness).line(-plusthickness,0).line(0,plusthickness).line(-plusthickness,0).line(0,plusthickness).close().extrude(L+2).\ edges(">X").edges("|Y").fillet(plusthickness/2.5).\ edges("<X").edges("|Y").fillet(plusthickness/2.5).\ edges(">Z").edges("|Y").fillet(plusthickness/2.5).\ edges("<Z").edges("|Y").fillet(plusthickness/2.5) subtract_part = pinmark.translate((0, 0.01, 0)).cut(body) subtract_part = subtract_part.translate((0, -0.02, 0)).cut(body).translate((0, 0.01, 0)) pinmark = pinmark.cut(subtract_part) #draw the body leads = leads.cut(body) #show(leads) return (body, leads, pinmark) #body, pins #import step_license as L import add_license as Lic def generateOneModel(params, log): ModelName = params.modelName FreeCAD.Console.PrintMessage( '\n\n############## ' + part_params['code_metric'] + ' ###############\n') CheckedModelName = ModelName.replace('.', '').replace('-', '_').replace('(', '').replace(')', '') Newdoc = App.newDocument(CheckedModelName) App.setActiveDocument(CheckedModelName) Gui.ActiveDocument=Gui.getDocument(CheckedModelName) #body, base, mark, pins = make_tantalum_th(params) body, pins, pinmark= make_tantalum_th(params) #body, base, mark, pins, top show(body) show(pins) show(pinmark) doc = FreeCAD.ActiveDocument print(GetListOfObjects(FreeCAD, doc)) objs = GetListOfObjects(FreeCAD, doc) Color_Objects(Gui,objs[0],body_color) Color_Objects(Gui,objs[1],pins_color) Color_Objects(Gui,objs[2],marking_color) col_body=Gui.ActiveDocument.getObject(objs[0].Name).DiffuseColor[0] col_pin=Gui.ActiveDocument.getObject(objs[1].Name).DiffuseColor[0] col_mark=Gui.ActiveDocument.getObject(objs[2].Name).DiffuseColor[0] material_substitutions={ col_body[:-1]:body_color_key, col_pin[:-1]:pins_color_key, col_mark[:-1]:marking_color_key } expVRML.say(material_substitutions) del objs objs=GetListOfObjects(FreeCAD, doc) FuseObjs_wColors(FreeCAD, FreeCADGui, doc.Name, objs[0].Name, objs[1].Name) objs=GetListOfObjects(FreeCAD, doc) FuseObjs_wColors(FreeCAD, FreeCADGui, doc.Name, objs[0].Name, objs[1].Name) #stop doc.Label = CheckedModelName objs=GetListOfObjects(FreeCAD, doc) objs[0].Label = CheckedModelName restore_Main_Tools() #rotate if required objs=GetListOfObjects(FreeCAD, doc) FreeCAD.getDocument(doc.Name).getObject(objs[0].Name).Placement = FreeCAD.Placement(FreeCAD.Vector(params.F/2,0,0), FreeCAD.Rotation(FreeCAD.Vector(0,0,1),params.rotation)) #out_dir=destination_dir+params.dest_dir_prefix+'/' script_dir=os.path.dirname(os.path.realpath(__file__)) expVRML.say(script_dir) #out_dir=script_dir+os.sep+destination_dir+os.sep+params.dest_dir_prefix out_dir=models_dir+destination_dir if not os.path.exists(out_dir): os.makedirs(out_dir) #out_dir="./generated_qfp/" # export STEP model exportSTEP(doc, ModelName, out_dir) if LIST_license[0]=="": LIST_license=Lic.LIST_int_license LIST_license.append("") Lic.addLicenseToStep(out_dir+'/', ModelName+".step", LIST_license,\ STR_licAuthor, STR_licEmail, STR_licOrgSys, STR_licOrg, STR_licPreProc) # scale and export Vrml model scale=1/2.54 #exportVRML(doc,ModelName,scale,out_dir) objs=GetListOfObjects(FreeCAD, doc) expVRML.say("######################################################################") expVRML.say(objs) expVRML.say("######################################################################") export_objects, used_color_keys = expVRML.determineColors(Gui, objs, material_substitutions) export_file_name=out_dir+os.sep+ModelName+'.wrl' colored_meshes = expVRML.getColoredMesh(Gui, export_objects , scale) expVRML.writeVRMLFile(colored_meshes, export_file_name, used_color_keys, LIST_license) if save_memory == False: Gui.SendMsgToActiveView("ViewFit") Gui.activeDocument().activeView().viewAxometric() # Save the doc in Native FC format saveFCdoc(App, Gui, doc, ModelName,out_dir) if save_memory == True: doc=FreeCAD.ActiveDocument FreeCAD.closeDocument(doc.Name) # when run from command line if __name__ == "__main__" or __name__ == "main_generator": expVRML.say(expVRML.__file__) FreeCAD.Console.PrintMessage('\r\nRunning...\r\n') full_path=os.path.realpath(__file__) expVRML.say(full_path) scriptdir=os.path.dirname(os.path.realpath(__file__)) expVRML.say(scriptdir) sub_path = full_path.split(scriptdir) expVRML.say(sub_path) sub_dir_name =full_path.split(os.sep)[-2] expVRML.say(sub_dir_name) sub_path = full_path.split(sub_dir_name)[0] expVRML.say(sub_path) models_dir=sub_path+"_3Dmodels" #expVRML.say(models_dir) #stop color_pin_mark=True if len(sys.argv) < 3: FreeCAD.Console.PrintMessage('No variant name is given! building C_Disc_D12.0mm_W4.4mm_P7.75mm') model_to_build='C_Disc_D12.0mm_W4.4mm_P7.75mm' else: model_to_build=sys.argv[2] if len(sys.argv)==4: FreeCAD.Console.PrintMessage(sys.argv[3]+'\r\n') if (sys.argv[3].find('no-pinmark-color')!=-1): color_pin_mark=False else: color_pin_mark=True if model_to_build == "all": variants = all_params.keys() save_memory = True else: variants = [model_to_build] with open(check_log_file, 'w') as log: for variant in variants: FreeCAD.Console.PrintMessage('\r\n'+variant) if not variant in all_params: print("Parameters for %s doesn't exist in 'all_params', skipping." % variant) continue params = all_params[variant] try: generateOneModel(params, log) except GeometryError as e: e.print_errors(stop_on_first_error) if stop_on_first_error: break except FreeCADVersionError as e: FreeCAD.Console.PrintError(e) break else: traceback.print_exc() raise
gpl-2.0
hariomkumarmth/champaranexpress
wp-content/plugins/dojo/dojox/drawing/manager/keys.js
3037
//>>built define("dojox/drawing/manager/keys",["dojo","../util/common"],function(_1,_2){ var _3=false; var _4=true; var _5="abcdefghijklmnopqrstuvwxyz"; var _6={arrowIncrement:1,arrowShiftIncrement:10,shift:false,ctrl:false,alt:false,cmmd:false,meta:false,onDelete:function(_7){ },onEsc:function(_8){ },onEnter:function(_9){ },onArrow:function(_a){ },onKeyDown:function(_b){ },onKeyUp:function(_c){ },listeners:[],register:function(_d){ var _e=_2.uid("listener"); this.listeners.push({handle:_e,scope:_d.scope||window,callback:_d.callback,keyCode:_d.keyCode}); },_getLetter:function(_f){ if(!_f.meta&&_f.keyCode>=65&&_f.keyCode<=90){ return _5.charAt(_f.keyCode-65); } return null; },_mixin:function(evt){ evt.meta=this.meta; evt.shift=this.shift; evt.alt=this.alt; evt.cmmd=this.cmmd; evt.ctrl=this.ctrl; evt.letter=this._getLetter(evt); return evt; },editMode:function(_10){ _3=_10; },enable:function(_11){ _4=_11; },scanForFields:function(){ if(this._fieldCons){ _1.forEach(this._fieldCons,_1.disconnect,_1); } this._fieldCons=[]; _1.query("input").forEach(function(n){ var a=_1.connect(n,"focus",this,function(evt){ this.enable(false); }); var b=_1.connect(n,"blur",this,function(evt){ this.enable(true); }); this._fieldCons.push(a); this._fieldCons.push(b); },this); },init:function(){ setTimeout(_1.hitch(this,"scanForFields"),500); _1.connect(document,"blur",this,function(evt){ this.meta=this.shift=this.ctrl=this.cmmd=this.alt=false; }); _1.connect(document,"keydown",this,function(evt){ if(!_4){ return; } if(evt.keyCode==16){ this.shift=true; } if(evt.keyCode==17){ this.ctrl=true; } if(evt.keyCode==18){ this.alt=true; } if(evt.keyCode==224){ this.cmmd=true; } this.meta=this.shift||this.ctrl||this.cmmd||this.alt; if(!_3){ this.onKeyDown(this._mixin(evt)); if(evt.keyCode==8||evt.keyCode==46){ _1.stopEvent(evt); } } }); _1.connect(document,"keyup",this,function(evt){ if(!_4){ return; } var _12=false; if(evt.keyCode==16){ this.shift=false; } if(evt.keyCode==17){ this.ctrl=false; } if(evt.keyCode==18){ this.alt=false; } if(evt.keyCode==224){ this.cmmd=false; } this.meta=this.shift||this.ctrl||this.cmmd||this.alt; !_3&&this.onKeyUp(this._mixin(evt)); if(evt.keyCode==13){ console.warn("KEY ENTER"); this.onEnter(evt); _12=true; } if(evt.keyCode==27){ this.onEsc(evt); _12=true; } if(evt.keyCode==8||evt.keyCode==46){ this.onDelete(evt); _12=true; } if(_12&&!_3){ _1.stopEvent(evt); } }); _1.connect(document,"keypress",this,function(evt){ if(!_4){ return; } var inc=this.shift?this.arrowIncrement*this.arrowShiftIncrement:this.arrowIncrement; var x=0,y=0; if(evt.keyCode==32&&!_3){ _1.stopEvent(evt); } if(evt.keyCode==37){ x=-inc; } if(evt.keyCode==38){ y=-inc; } if(evt.keyCode==39){ x=inc; } if(evt.keyCode==40){ y=inc; } if(x||y){ evt.x=x; evt.y=y; evt.shift=this.shift; if(!_3){ this.onArrow(evt); _1.stopEvent(evt); } } }); }}; _1.addOnLoad(_6,"init"); return _6; });
gpl-2.0
bbDKP/bbDKP
migrations/release_2_0_0_m01_schema.php
16243
<?php /** * bbDKP database installer * * @package bbguild v2.0 * @copyright 2018 avathar.be * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License v2 */ namespace avathar\bbguild\migrations; use phpbb\db\migration\migration; /** * Migration stage 1: Initial schema */ class release_2_0_0_m01_schema extends migration { protected $table_prefix; protected $bbgames_table; protected $news_table; protected $bblogs_table; protected $player_ranks_table; protected $player_list_table; protected $class_table; protected $race_table; protected $faction_table; protected $guild_table; protected $bb_language; protected $motd_table; protected $bbrecruit_table; protected $bb_gamerole_table; protected $plugins_table; protected $achievement_table; protected $achievement_track_table; protected $achievement_criteria_table; protected $achievement_rewards_table; protected $bb_relations_table; protected $criteria_track_table; static public function depends_on() { return array('\phpbb\db\migration\data\v310\gold'); } /** * Add the bbguild table schema to the database: * * @return array Array of table schema */ public function update_schema() { $this->GetTablenames(); return array( 'add_tables' => array( /*1*/ $this->news_table => array( 'COLUMNS' => array( 'news_id' => array('UINT', null, 'auto_increment'), 'news_headline' => array('VCHAR_UNI', ''), 'news_message' => array('TEXT_UNI', ''), 'news_date' => array('TIMESTAMP', 0), 'user_id' => array('UINT', 0), 'bbcode_bitfield' => array('VCHAR:20', ''), 'bbcode_uid' => array('VCHAR:8', ''), 'bbcode_options' => array('VCHAR:8', '') ), 'PRIMARY_KEY' => 'news_id', ), /*2*/ $this->bb_language => array( 'COLUMNS' => array( 'id' => array('UINT', null, 'auto_increment'), 'game_id' => array('VCHAR:10', ''), 'attribute_id' => array('UINT', 0), 'language' => array('CHAR:2', ''), 'attribute' => array('VCHAR:30', ''), 'name' => array('VCHAR_UNI:255', ''), 'name_short' => array('VCHAR_UNI:255', ''), ), 'PRIMARY_KEY' => array('id'), 'KEYS' => array('UQ01' => array('UNIQUE', array('game_id', 'attribute_id', 'language', 'attribute')), )), /*3*/ $this->faction_table => array( 'COLUMNS' => array( 'game_id' => array('VCHAR:10', ''), 'f_index' => array('USINT', null, 'auto_increment'), 'faction_id' => array('USINT', 0), 'faction_name' => array('VCHAR_UNI', ''), 'faction_hide' => array('BOOL', 0), ), 'PRIMARY_KEY' => 'f_index', 'KEYS' => array('UQ02' => array('UNIQUE', array('game_id', 'faction_id'))), ), /*4*/ $this->class_table => array( 'COLUMNS' => array( 'c_index' => array('USINT', null, 'auto_increment'), 'game_id' => array('VCHAR:10', ''), 'class_id' => array('USINT', 0), 'class_faction_id' => array('USINT', 0), 'class_min_level' => array('USINT', 0), 'class_max_level' => array('USINT', 0), 'class_armor_type' => array('VCHAR_UNI', ''), 'class_hide' => array('BOOL', 0), 'imagename' => array('VCHAR:255', ''), 'colorcode' => array('VCHAR:10', ''), ), 'PRIMARY_KEY' => 'c_index', 'KEYS' => array('UQ01' => array('UNIQUE', array('game_id', 'class_id'))), ), /*5*/ $this->race_table => array( 'COLUMNS' => array( 'game_id' => array('VCHAR:10', ''), 'race_id' => array('USINT', 0), 'race_faction_id' => array('USINT', 0), 'race_hide' => array('BOOL', 0), 'image_female' => array('VCHAR:255', ''), 'image_male' => array('VCHAR:255', ''), ), 'PRIMARY_KEY' => array('game_id', 'race_id') , ), /*6*/ $this->guild_table => array( 'COLUMNS' => array( 'id' => array('USINT', 0), 'name' => array('VCHAR_UNI:255', ''), 'realm' => array('VCHAR_UNI:255', ''), 'region' => array('VCHAR:3', ''), 'battlegroup' => array('VCHAR:255', ''), 'roster' => array('BOOL', 0), 'aion_legion_id' => array('USINT', 0), 'aion_server_id' => array('USINT', 0), 'level' => array('UINT', 0), 'players' => array('UINT', 0), 'achievementpoints' => array('UINT', 0), 'guildarmoryurl' => array('VCHAR:255', ''), 'emblemurl' => array('VCHAR:255', ''), 'game_id' => array('VCHAR:10', ''), 'min_armory' => array('UINT', 90), 'rec_status' => array('BOOL', 0), 'guilddefault' => array('BOOL', 0), 'armory_enabled' => array('BOOL', 0), 'armoryresult' => array('VCHAR_UNI:255', ''), 'recruitforum' => array('UINT', 0), 'faction' => array('UINT', 0), ), 'PRIMARY_KEY' => array('id'), 'KEYS' => array('UQ01' => array('UNIQUE', array('name', 'id') )), ), /*7*/ $this->player_ranks_table => array( 'COLUMNS' => array( //rank_id is not auto-increment 'guild_id' => array('USINT', 0), 'rank_id' => array('USINT', 0), 'rank_name' => array('VCHAR_UNI:50', ''), 'rank_hide' => array('BOOL', 0), 'rank_prefix' => array('VCHAR:75', ''), 'rank_suffix' => array('VCHAR:75', ''), ), 'PRIMARY_KEY' => array('rank_id', 'guild_id'), ), /*8*/ $this->player_list_table => array( 'COLUMNS' => array( 'player_id' => array('UINT', null, 'auto_increment'), 'game_id' => array('VCHAR:10', ''), 'player_name' => array('VCHAR_UNI:100', ''), 'player_region' => array('VCHAR', ''), 'player_realm' => array('VCHAR:30', ''), 'player_title' => array('VCHAR_UNI:100', ''), 'player_level' => array('USINT', 0), 'player_race_id' => array('USINT', 0), 'player_class_id' => array('USINT', 0), 'player_rank_id' => array('USINT', 0), 'player_role' => array('VCHAR:20', ''), 'player_comment' => array( 'TEXT_UNI' , ''), 'player_joindate' => array('TIMESTAMP', 0), 'player_outdate' => array('TIMESTAMP', 0), 'player_guild_id' => array('USINT', 0), 'player_gender_id' => array('USINT', 0), 'player_achiev' => array('UINT', 0), 'player_armory_url' => array('VCHAR:255', ''), 'player_portrait_url' => array('VCHAR', ''), 'phpbb_user_id' => array('UINT', 0), 'player_status' => array('BOOL', 0) , 'deactivate_reason' => array('VCHAR_UNI:255', ''), 'last_update' => array('TIMESTAMP', 0) ), 'PRIMARY_KEY' => 'player_id', 'KEYS' => array('UQ01' => array('UNIQUE', array('player_guild_id', 'player_name', 'player_realm'))), ), /*9*/ $this->motd_table => array( 'COLUMNS' => array( 'motd_id' => array('INT:8', null, 'auto_increment'), 'motd_title' => array('VCHAR_UNI', ''), 'motd_msg' => array('TEXT_UNI', ''), 'motd_timestamp' => array('TIMESTAMP', 0), 'bbcode_bitfield' => array('VCHAR:255', ''), 'bbcode_uid' => array('VCHAR:8', ''), 'user_id' => array('INT:8', 0), 'bbcode_options' => array('UINT', 7), ), 'PRIMARY_KEY' => 'motd_id' ), /*10*/ $this->bbgames_table => array( 'COLUMNS' => array( 'id' => array('UINT', null, 'auto_increment'), 'game_id' => array('VCHAR:10', ''), 'game_name' => array('VCHAR_UNI:255', ''), 'region' => array('VCHAR:3', ''), 'status' => array('VCHAR:30', ''), 'imagename' => array('VCHAR:20', ''), 'armory_enabled' => array('UINT', 0), 'bossbaseurl' => array('VCHAR:255', ''), 'zonebaseurl' => array('VCHAR:255', ''), 'apikey' => array('VCHAR:255', ''), 'apilocale' => array('VCHAR:5', ''), 'privkey' => array('VCHAR:255', '') ), 'PRIMARY_KEY' => array('id'), 'KEYS' => array('UQ01' => array('UNIQUE', array('game_id'))) ), /*11*/ $this->bb_gamerole_table => array( 'COLUMNS' => array( 'role_pkid' => array('INT:8', null, 'auto_increment'), 'game_id' => array('VCHAR:10', ''), 'role_id' => array('INT:8', 0), 'role_color' => array('VCHAR', ''), 'role_icon' => array('VCHAR', ''), 'role_cat_icon' => array('VCHAR', ''), ), 'PRIMARY_KEY' => 'role_pkid', 'KEYS' => array('UQ01' => array('UNIQUE', array('game_id', 'role_id'))) ), /*12*/ $this->bbrecruit_table => array( 'COLUMNS' => array( 'id' => array('INT:8', null, 'auto_increment'), 'guild_id' => array('USINT', 0), 'role_id' => array('INT:8', 0), 'class_id' => array('UINT', 0), 'level' => array('UINT', 0), 'positions' => array('USINT', 0), 'applicants' => array('USINT', 0), 'status' => array('USINT', 0), 'applytemplate_id' => array('UINT', 0), 'last_update' => array('TIMESTAMP', 0), 'note' => array('TEXT_UNI', ''), ), 'PRIMARY_KEY' => 'id', ), /*13*/ $this->bblogs_table => array( 'COLUMNS' => array( 'log_id' => array('UINT', null, 'auto_increment'), 'log_date' => array('TIMESTAMP', 0), 'log_type' => array('VCHAR_UNI:255', ''), 'log_action' => array('TEXT_UNI', ''), 'log_ipaddress' => array('VCHAR:45', ''), // ipv6 is 45 char 'log_sid' => array('VCHAR:32', ''), 'log_result' => array('VCHAR', ''), 'log_userid' => array('UINT', 0), ), 'PRIMARY_KEY' => 'log_id', 'KEYS' => array( 'I01' => array('INDEX', 'log_userid'), 'I02' => array('INDEX', 'log_type'), 'I03' => array('INDEX', 'log_ipaddress')), ), /* entity achievements */ /*14*/ $this->achievement_table => array( 'COLUMNS' => array( 'id' => array('UINT', 0), 'game_id' => array('VCHAR:10', ''), 'title' => array('VCHAR_UNI:255', ''), 'points' => array('UINT', 0), 'description' => array('VCHAR_UNI:255', ''), 'icon' => array('VCHAR_UNI:255', ''), 'factionid' => array('BOOL', 0), 'reward' => array('VCHAR_UNI:255', ''), ), 'PRIMARY_KEY' => 'id', ), /*15 entity achievements criteria */ $this->achievement_criteria_table => array( 'COLUMNS' => array( 'criteria_id' => array('UINT', 0), 'description' => array('VCHAR_UNI:255', ''), 'orderIndex' => array('UINT', 0), 'max' => array('TIMESTAMP', 0) ), 'PRIMARY_KEY' => 'criteria_id', ), /*16 entity achievements rewards */ $this->achievement_rewards_table => array( 'COLUMNS' => array( 'rewards_item_id' => array('UINT', 0), 'description' => array('VCHAR_UNI:255', ''), 'itemlevel' => array('UINT', 0), 'quality' => array('UINT', 0), 'icon' => array('VCHAR:255', 0), ), 'PRIMARY_KEY' => 'rewards_item_id', ), /*17 is the relation table between achievement and criterium/rewards */ $this->bb_relations_table => array( 'COLUMNS' => array( 'id' => array('UINT', null, 'auto_increment'), 'attribute_id' => array('VCHAR:3', ''), 'rel_attr_id' => array('VCHAR:3', ''), 'att_value' => array('UINT', 0), 'rel_value' => array('UINT', 0), ), 'PRIMARY_KEY' => 'id', 'KEYS' => array('UQ01' => array('UNIQUE', array('attribute_id', 'rel_attr_id', 'att_value', 'rel_value'))), ), /*18 time achievement reached */ $this->achievement_track_table => array( 'COLUMNS' => array( 'guild_id' => array('USINT', 0), 'player_id' => array('UINT', 0), 'achievement_id' => array('UINT', 0), 'achievements_completed' => array('BINT', 0), ), 'PRIMARY_KEY' => array('guild_id', 'player_id', 'achievement_id'), ), /*19 time criterium was achieved */ $this->criteria_track_table => array( 'COLUMNS' => array( 'guild_id' => array('USINT', 0), 'player_id' => array('UINT', 0), 'criteria_id' => array('UINT', 0), 'criteria_quantity' => array('BINT', 0), 'criteria_created' => array('BINT', 0), 'criteria_timestamp' => array('BINT', 0), ), 'PRIMARY_KEY' => array('guild_id', 'player_id', 'criteria_id'), ), /*20 extension plugins - nothing at this time */ $this->plugins_table => array( 'COLUMNS' => array( 'name' => array('VCHAR_UNI:255', ''), 'value' => array('BOOL', 0), 'version' => array('VCHAR:50', ''), 'installdate' => array('BINT', 0), 'orginal_copyright' => array('VCHAR_UNI:150', ''), 'bbdkp_copyright' => array('VCHAR_UNI:150', ''), ), 'PRIMARY_KEY' => array('name'), ), ), ); } /** * Drop the bbguild table schema from the database * * @return array Array of table schema * @access public */ public function revert_schema() { $this->GetTablenames(); return array( 'drop_tables' => array( $this->news_table, $this->bb_language, $this->faction_table, $this->class_table, $this->race_table, $this->guild_table, $this->player_ranks_table, $this->player_list_table, $this->motd_table, $this->bbgames_table, $this->bb_gamerole_table, $this->bbrecruit_table, $this->bblogs_table, $this->plugins_table, $this->achievement_table, $this->achievement_track_table, $this->achievement_criteria_table, $this->achievement_rewards_table, $this->bb_relations_table, $this->criteria_track_table ), ); } /** * populate table names */ public function GetTablenames() { $this->bbgames_table = $this->table_prefix . 'bb_games'; $this->news_table = $this->table_prefix . 'bb_news'; $this->bblogs_table = $this->table_prefix . 'bb_logs'; $this->player_ranks_table = $this->table_prefix . 'bb_ranks'; $this->player_list_table = $this->table_prefix . 'bb_players'; $this->class_table = $this->table_prefix . 'bb_classes'; $this->race_table = $this->table_prefix . 'bb_races'; $this->faction_table = $this->table_prefix . 'bb_factions'; $this->guild_table = $this->table_prefix . 'bb_guild'; $this->bb_language = $this->table_prefix . 'bb_language'; $this->motd_table = $this->table_prefix . 'bb_motd'; $this->bbrecruit_table = $this->table_prefix . 'bb_recruit'; $this->bb_gamerole_table = $this->table_prefix . 'bb_gameroles'; $this->plugins_table = $this->table_prefix . 'bb_plugins'; $this->achievement_table = $this->table_prefix . 'bb_achievement'; $this->achievement_track_table = $this->table_prefix . 'bb_achievement_track'; $this->achievement_criteria_table = $this->table_prefix . 'bb_achievement_criteria'; $this->achievement_rewards_table = $this->table_prefix . 'bb_achievement_rewards'; $this->bb_relations_table = $this->table_prefix . 'bb_relations_table'; $this->criteria_track_table = $this->table_prefix . 'bb_criteria_track'; } }
gpl-2.0
ColFusion/ColfusionWeb
downloads/spoon/spoon/plugins/spoon/agile-bi/platform/pentaho-solutions/system/analyzer/scripts/dojo/src/widget/ResizableTextarea.js
2344
/* Copyright (c) 2004-2006, The Dojo Foundation All Rights Reserved. Licensed under the Academic Free License version 2.1 or above OR the modified BSD license. For more information on Dojo licensing, see: http://dojotoolkit.org/community/licensing.shtml */ dojo.provide("dojo.widget.ResizableTextarea"); dojo.require("dojo.widget.*"); dojo.require("dojo.widget.LayoutContainer"); dojo.require("dojo.widget.ResizeHandle"); dojo.widget.defineWidget( "dojo.widget.ResizableTextarea", dojo.widget.HtmlWidget, { // summary // A resizable textarea. // Takes all the parameters (name, value, etc.) that a vanilla textarea takes. // usage // <textarea dojoType="ResizableTextArea">...</textarea> templatePath: dojo.uri.dojoUri("src/widget/templates/ResizableTextarea.html"), templateCssPath: dojo.uri.dojoUri("src/widget/templates/ResizableTextarea.css"), fillInTemplate: function(args, frag){ this.textAreaNode = this.getFragNodeRef(frag).cloneNode(true); // FIXME: Safari apparently needs this! dojo.body().appendChild(this.domNode); this.rootLayout = dojo.widget.createWidget( "LayoutContainer", { minHeight: 50, minWidth: 100 }, this.rootLayoutNode ); // TODO: all this code should be replaced with a template // (especially now that templates can contain subwidgets) this.textAreaContainer = dojo.widget.createWidget( "LayoutContainer", { layoutAlign: "client" }, this.textAreaContainerNode ); this.rootLayout.addChild(this.textAreaContainer); this.textAreaContainer.domNode.appendChild(this.textAreaNode); with(this.textAreaNode.style){ width="100%"; height="100%"; } this.statusBar = dojo.widget.createWidget( "LayoutContainer", { layoutAlign: "bottom", minHeight: 28 }, this.statusBarContainerNode ); this.rootLayout.addChild(this.statusBar); this.statusLabel = dojo.widget.createWidget( "LayoutContainer", { layoutAlign: "client", minWidth: 50 }, this.statusLabelNode ); this.statusBar.addChild(this.statusLabel); this.resizeHandle = dojo.widget.createWidget( "ResizeHandle", { targetElmId: this.rootLayout.widgetId }, this.resizeHandleNode ); this.statusBar.addChild(this.resizeHandle); } });
gpl-2.0
JozefAB/neoacu
administrator/components/com_guru/views/guruquizcountdown/tmpl/default_.php
29567
<?php /*------------------------------------------------------------------------ # com_guru # ------------------------------------------------------------------------ # author iJoomla # copyright Copyright (C) 2013 ijoomla.com. All Rights Reserved. # @license - http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL # Websites: http://www.ijoomla.com # Technical Support: Forum - http://www.ijoomla.com/forum/index/ -------------------------------------------------------------------------*/ defined( '_JEXEC' ) or die( 'Restricted access' ); JHtml::_('behavior.framework'); JHTML::_('behavior.tooltip'); $lists = $this->lists; ?> <script language="JavaScript" type="text/javascript" src="<?php echo JURI::base(); ?>components/com_guru/js/freecourse.js"></script> <script language="JavaScript" type="text/javascript" src="<?php echo JURI::base(); ?>components/com_guru/js/colorpicker.js"></script> <script type="text/javascript" language="javascript"> function isFloat(nr){ return parseFloat(nr.match(/^-?\d*(\.\d+)?$/)) > 0; } function validateColor(color){ if(color == ''){ return true } if(/^[0-9A-F]{6}$/i.test(color)){ return true; } return false; } Joomla.submitbutton = function(pressbutton){ if(pressbutton == 'save' || pressbutton == 'apply'){ st_width = document.getElementById("st_width").value; st_height = document.getElementById("st_height").value; border_color = document.getElementById("pick_donecolorfield").value; minandsec_color = document.getElementById("pick_notdonecolorfield").value; title_color = document.getElementById("pick_txtcolorfield").value; background_color = document.getElementById("pick_xdonecolorfield").value; if(!isFloat(st_width) || st_width <= 0){ alert("<?php echo JText::_("GURU_ALERT_INVALID_WIDTH"); ?>"); return false; } else if(!isFloat(st_height) || st_height <= 0){ alert("<?php echo JText::_("GURU_ALERT_INVALID_HEIGHT"); ?>"); return false; } else if(!validateColor(border_color)){ alert("<?php echo JText::_("GURU_ALERT_INVALID_COLOR"); ?>"); return false; } else if(!validateColor(minandsec_color)){ alert("<?php echo JText::_("GURU_ALERT_INVALID_COLOR"); ?>"); return false; } else if(!validateColor(title_color)){ alert("<?php echo JText::_("GURU_ALERT_INVALID_COLOR"); ?>"); return false; } else if(!validateColor(background_color)){ alert("<?php echo JText::_("GURU_ALERT_INVALID_COLOR"); ?>"); return false; } } submitform( pressbutton ); } </script> <style> input, textarea { width: 135px!important; } select { width: 150px!important; } </style> <div id="g_countdown"> <form action="index.php" method="post" name="adminForm" id="adminForm" class="form-horizontal"> <div class="well well-minimized"> <?php echo JText::_("GURU_QUIZC_SETTINGS_DESCRIPTION"); ?> </div> <?php $db = JFactory::getDBO(); $sql = "SELECT qct_alignment, qct_border_color, qct_minsec, qct_title_color, qct_bg_color, qct_font , qct_width, qct_height, qct_font_nb, qct_font_words FROM #__guru_config WHERE id=1"; $db->setQuery($sql); $db->query(); $result=$db->loadObjectList(); ?> <div class="adminform span9"> <div class="row-fluid"> <div class="span12"> <div class="row-fluid"> <div class="span8"> <div class="row-fluid"> <div class="control-group"> <label class="control-label" for="layout"><?php echo JText::_('GURU_ALIGN');?> </label> <div class="controls"> <div class="pull-left"> <select id="timer_alignement" name="timer_alignement"> <option value="1" <?php if($result[0]->qct_alignment == "1"){echo 'selected="selected"'; }?> ><?php echo JText::_("GURU_LEFT"); ?></option> <option value="2" <?php if($result[0]->qct_alignment == "2"){echo 'selected="selected"'; }?> ><?php echo JText::_("GURU_RIGHT"); ?></option> <option value="3" <?php if($result[0]->qct_alignment == "3"){echo 'selected="selected"'; }?> ><?php echo JText::_("GURU_CENTER"); ?></option> </select> <span class="editlinktip hasTip" title="<?php echo JText::_("GURU_CT_ALIGNEMENT"); ?>" > <img border="0" src="components/com_guru/images/icons/tooltip.png"> </span> </div> </div> </div> </div> </div> </div> </div> </div> <div class="row-fluid"> <div class="span12"> <div class="row-fluid"> <div class="span8"> <div class="row-fluid"> <div class="control-group"> <label class="control-label" for="layout"><?php echo JText::_('GURU_BORDER_COLOR');?> </label> <?php $st_donecolor = "#".$result[0]->qct_border_color;?> <div class="controls"> <div> <div style="float:left;"> <input type="text" size="7" name="st_donecolor" ID="pick_donecolorfield" value="<?php echo substr($st_donecolor, 1, strlen($st_donecolor));?>" onChange="if (this.value.length == 6 || this.value.length == 0) {relateColor('pick_donecolor', this.value);}" size="6" maxlength="6" onkeyup="if (this.value.length == 6 || this.value.length == 0) {relateColor('pick_donecolor', this.value);}" /> &nbsp; <a href="javascript:pickColor('pick_donecolor');" onClick="document.getElementById('show_hide_box').style.display='none';" id="pick_donecolor" style="border: 1px solid #000000; font-family:Verdana; font-size:10px; text-decoration: none;"> &nbsp;&nbsp;&nbsp; </a> <SCRIPT LANGUAGE="javascript">relateColor('pick_donecolor', getObj('pick_donecolorfield').value);</script> &nbsp;&nbsp;&nbsp; </div> <div style="float:left;"> <span class="editlinktip hasTip" title="<?php echo JText::_("GURU_CT_BORDERCOLOR"); ?>" > <img border="0" src="components/com_guru/images/icons/tooltip.png"> </span> </div> </div> </div> </div> </div> </div> </div> </div> </div> <div class="row-fluid"> <div class="span12"> <div class="row-fluid"> <div class="span8"> <div class="row-fluid"> <div class="control-group"> <label class="control-label" for="layout"><?php echo JText::_('GURU_MIN_SEC_COLOR');?> </label> <?php $st_notdonecolor = "#".$result[0]->qct_minsec;?> <div class="controls"> <div> <div style="float:left;"> <input type="text" size="7" name="st_notdonecolor" ID="pick_notdonecolorfield" value="<?php echo substr($st_notdonecolor, 1, strlen($st_notdonecolor));?>" onchange="changeBcolor(); relateColor('pick_notdonecolor', this.value);" size="6" maxlength="6" onkeyup="if (this.value.length == 6 || this.value.length == 0) {relateColor('pick_notdonecolor', this.value); changeBcolor();}" /> &nbsp; <a href="javascript:pickColor('pick_notdonecolor');" onClick="document.getElementById('show_hide_box').style.display='none';" id="pick_notdonecolor" style="border: 1px solid #000000; font-family:Verdana; font-size:10px; text-decoration: none;"> &nbsp;&nbsp;&nbsp; </a> <SCRIPT LANGUAGE="javascript">relateColor('pick_notdonecolor', getObj('pick_notdonecolorfield').value);</script> <span id='show_hide_box'></span> &nbsp;&nbsp;&nbsp; </div> <div style="float:left;"> <span class="editlinktip hasTip" title="<?php echo JText::_("GURU_MINSEC_COLOR"); ?>" > <img border="0" src="components/com_guru/images/icons/tooltip.png"> </span> </div> </div> </div> </div> </div> </div> </div> </div> <div class="row-fluid"> <div class="span12"> <div class="row-fluid"> <div class="span8"> <div class="row-fluid"> <div class="control-group"> <label class="control-label" for="layout"><?php echo JText::_('GURU_TILTE_COLOR');?> </label> <?php $st_txtcolor = "#".$result[0]->qct_title_color;?> <div class="controls"> <div> <div style="float:left;"> <input type="text" size="7" name="st_txtcolor" ID="pick_txtcolorfield" value="<?php echo substr($st_txtcolor, 1, strlen($st_txtcolor));?>" onChange="if (this.value.length == 6 || this.value.length == 0) {relateColor('pick_txtcolor', this.value);}" SIZE="6" MAXLENGTH="6" onkeyup="if (this.value.length == 6 || this.value.length == 0) {relateColor('pick_txtcolor', this.value);}" /> &nbsp; <a href="javascript:pickColor('pick_txtcolor');" onClick="document.getElementById('show_hide_box').style.display='none';" id="pick_txtcolor" style="border: 1px solid #000000; font-family:Verdana; font-size:10px; text-decoration: none;"> &nbsp;&nbsp;&nbsp; </a> <SCRIPT LANGUAGE="javascript">relateColor('pick_txtcolor', getObj('pick_txtcolorfield').value);</script> <span id='show_hide_box'></span> &nbsp;&nbsp;&nbsp; </div> <div style="float:left;"> <span class="editlinktip hasTip" title="<?php echo JText::_("GURU_CT_TITLE_COLOR"); ?>" > <img border="0" src="components/com_guru/images/icons/tooltip.png"> </span> </div> </div> </div> </div> </div> </div> </div> </div> </div> <div class="row-fluid"> <div class="span12"> <div class="row-fluid"> <div class="span8"> <div class="row-fluid"> <div class="control-group"> <label class="control-label" for="layout"><?php echo JText::_('GURU_BACKGROUND_COLOR');?> </label> <?php $st_xdonecolor = "#".$result[0]->qct_bg_color;?> <div class="controls"> <div> <div style="float:left;"> <input type="text" size="7" name="st_xdonecolor" ID="pick_xdonecolorfield" value="<?php echo substr($st_xdonecolor, 1, strlen($st_xdonecolor));?>" onChange="if (this.value.length == 6 || this.value.length == 0) {relateColor('pick_xdonecolor', this.value);}" size="6" maxlength="6" onkeyup="if (this.value.length == 6 || this.value.length == 0) {relateColor('pick_xdonecolor', this.value);}" /> &nbsp; <a href="javascript:pickColor('pick_xdonecolor');" onClick="document.getElementById('show_hide_box').style.display='none';" id="pick_xdonecolor" style="border: 1px solid #000000; font-family:Verdana; font-size:10px; text-decoration: none;"> &nbsp;&nbsp;&nbsp; </a> <SCRIPT LANGUAGE="javascript">relateColor('pick_xdonecolor', getObj('pick_xdonecolorfield').value);</script> <span id='show_hide_box'></span> &nbsp;&nbsp;&nbsp; </div> <div style="float:left;"> <span class="editlinktip hasTip" title="<?php echo JText::_("GURU_BG_COLOR"); ?>" > <img border="0" src="components/com_guru/images/icons/tooltip.png"> </span> </div> </div> </div> </div> </div> </div> </div> </div> </div> <div class="row-fluid"> <div class="span12"> <div class="row-fluid"> <div class="span8"> <div class="row-fluid"> <div class="control-group"> <label class="control-label" for="layout"><?php echo JText::_('GURU_FONT');?> </label> <div class="controls"> <select id="font" name="font" id="font" onchange="javascript:guruchangeFont(value)"> <option value="Arial" <?php if($result[0]->qct_font == "Arial"){echo 'selected="selected"'; } ?>>Arial</option> <option value="Helvetica" <?php if($result[0]->qct_font == "Helvetica"){echo 'selected="selected"'; } ?>>Helvetica</option> <option value="Garamond" <?php if($result[0]->qct_font == "Garamond"){echo 'selected="selected"'; } ?>>Garamond</option> <option value="sans-serif" <?php if($result[0]->qct_font == "sans-serif"){echo 'selected="selected"'; } ?>>Sans Serif</option> <option value="Verdana" <?php if($result[0]->qct_font == "Verdana"){echo 'selected="selected"'; } ?>>Verdana</option> </select> <span class="editlinktip hasTip" title="<?php echo JText::_("GURU_FONT_TOOLTIP"); ?>" > <img border="0" src="components/com_guru/images/icons/tooltip.png"> </span> </div> </div> </div> </div> </div> </div> </div> <div class="row-fluid"> <div class="span12"> <div class="row-fluid"> <div class="span8"> <div class="row-fluid"> <div class="control-group"> <label class="control-label" for="layout"><?php echo JText::_('GURU_WIDTH');?> </label> <?php if($result[0]->qct_width == ""){ $qct_width = 200; } else{ $qct_width = $result[0]->qct_width; } ?> <div class="controls"> <div> <div style="float:left;"> <input type="text" size="7" name="st_width" id="st_width" value="<?php echo $qct_width; ?>" onchange="javascript:guruchangeSizeW(value)" /> </div> <div style="float:left;"> px &nbsp; </div> <div style="float:left;"> <span class="editlinktip hasTip" title="<?php echo JText::_("GURU_WIDTH")."::".JText::_("GURU_CT_WIDTH"); ?>" > <img border="0" src="components/com_guru/images/icons/tooltip.png"> </span> </div> </div> </div> </div> </div> </div> </div> </div> </div> <div class="row-fluid"> <div class="span12"> <div class="row-fluid"> <div class="span8"> <div class="row-fluid"> <div class="control-group"> <label class="control-label" for="layout"><?php echo JText::_('GURU_HEIGHT');?> </label> <?php if($result[0]->qct_height == ""){ $qct_height = 80; } else{ $qct_height= $result[0]->qct_height; } ?> <div class="controls"> <div> <div style="float:left;"> <input type="text" size="7" name="st_height" id="st_height" value="<?php echo $qct_height; ?>" onchange="javascript:guruchangeSizeH(value)" /> </div> <div style="float:left;"> px &nbsp; </div> <div style="float:left;"> <span class="editlinktip hasTip" title="<?php echo JText::_("GURU_HEIGHT")."::".JText::_("GURU_CT_HEIGHT"); ?>" > <img border="0" src="components/com_guru/images/icons/tooltip.png"> </span> </div> </div> </div> </div> </div> </div> </div> </div> </div> <div class="row-fluid"> <div class="span12"> <div class="row-fluid"> <div class="span8"> <div class="row-fluid"> <div class="control-group"> <label class="control-label" for="layout"><?php echo JText::_('GURU_FONT_SIZE_NUMB');?> </label> <div class="controls"> <div> <div style="float:left;"> <select id="fontnb" name="fontnb" style="float:none !important;" onchange="javascript:guruchangeSizeFN(value)"> <?php for( $i=10; $i<=50; $i++){?> <option value="<?php echo $i;?>" <?php if($result[0]->qct_font_nb == $i){echo 'selected="selected"'; }?> ><?php echo $i;?></option> <?php }?> </select> </div> <div style="float:left;"> px &nbsp; </div> <div style="float:left;"> <span class="editlinktip hasTip" title="<?php echo JText::_("GURU_NB_FONT_SIZE"); ?>" > <img border="0" src="components/com_guru/images/icons/tooltip.png"> </span> </div> </div> </div> </div> </div> </div> </div> </div> </div> <div class="row-fluid"> <div class="span12"> <div class="row-fluid"> <div class="span8"> <div class="row-fluid"> <div class="control-group"> <label class="control-label" for="layout"><?php echo JText::_('GURU_FONT_SIZE_WORDS');?> </label> <div class="controls"> <div> <div style="float:left;"> <select id="fontwords" name="fontwords" style="float:none !important;" onchange="javascript:guruchangeSizeFM(value)"> <?php for( $i=10; $i<=50; $i++){?> <option value="<?php echo $i;?>" <?php if($result[0]->qct_font_words == $i){echo 'selected="selected"'; }?> ><?php echo $i;?></option> <?php }?> </select> </div> <div style="float:left;"> px &nbsp; </div> <div style="float:left;"> <span class="editlinktip hasTip" title="<?php echo JText::_("GURU_NB_FONT_SIZE"); ?>" > <img border="0" src="components/com_guru/images/icons/tooltip.png"> </span> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> <div class="pull-right span3"> <div style="padding-bottom:10px;"><?php echo JText::_("GURU_PREVIEW") ?></div> <div id = "divtotal" style="width:<?php echo $qct_width;?>px; height:<?php echo $qct_height;?>px; border: 1px solid; border-color:<?php echo $st_donecolor;?>; font-family:<?php echo $result[0]->qct_font;?>; background-color:<?php echo $st_xdonecolor;?>;"> <div id="timeleft" align="center" style="border-bottom:1px <?php echo $st_donecolor;?> solid; font-size:<?php echo $result[0]->qct_font_words;?>px; color:<?php echo $st_txtcolor;?>; background-color:<?php echo $st_donecolor;?>;"><?php echo JText::_("GURU_TIMEPROMO");?></div> <div id="totalbg" style="background-color:<?php echo $st_xdonecolor;?>;"> <div id="timetest" align="center" style="font-size:<?php echo $result[0]->qct_font_nb ;?>px; color:<?php echo $st_notdonecolor;?>;">04 &nbsp; 26</div> <div id="minsec" align="center" style="font-size:<?php echo $result[0]->qct_font_words;?>px;"><?php echo JText::_("GURU_PROGRAM_DETAILS_MINUTES")." ".JText::_("GURU_PROGRAM_DETAILS_SECONDS") ;?></div> </div> </div> </div> </div> <input type="hidden" name="option" value="com_guru" /> <input type="hidden" name="task" value="" /> <input type="hidden" name="controller" value="guruQuizCountdown" /> <input type="hidden" name="id" value="0" /> </form> </div>
gpl-2.0
olta/beam
src-bmMailKit/BmSmtpAccount.cpp
12904
/* * Copyright 2002-2006, project beam (http://sourceforge.net/projects/beam). * All rights reserved. Distributed under the terms of the GNU GPL v2. * * Authors: * Oliver Tappe <beam@hirschkaefer.de> */ #include <ByteOrder.h> #include <File.h> #include <Message.h> #include "BmBasics.h" #include "BmLogHandler.h" #include "BmMailQuery.h" #include "BmSmtpAccount.h" #include "BmRosterBase.h" #include "BmUtil.h" /********************************************************************************\ BmSmtpAccount \********************************************************************************/ const char* const BmSmtpAccount::MSG_NAME = "bm:name"; const char* const BmSmtpAccount::MSG_USERNAME = "bm:username"; const char* const BmSmtpAccount::MSG_PASSWORD = "bm:password"; const char* const BmSmtpAccount::MSG_SMTP_SERVER = "bm:smtpserver"; const char* const BmSmtpAccount::MSG_DOMAIN = "bm:domain"; const char* const BmSmtpAccount::MSG_ENCRYPTION_TYPE = "bm:encryptionType"; const char* const BmSmtpAccount::MSG_AUTH_METHOD = "bm:authmethod"; const char* const BmSmtpAccount::MSG_PORT_NR = "bm:portnr"; const char* const BmSmtpAccount::MSG_ACC_FOR_SAP = "bm:accForSmtpAfterPop"; const char* const BmSmtpAccount::MSG_STORE_PWD = "bm:storepwd"; const char* const BmSmtpAccount::MSG_CLIENT_CERT = "bm:clientcert"; const char* const BmSmtpAccount::MSG_ACCEPTED_CERT = "bm:acccert"; const int16 BmSmtpAccount::nArchiveVersion = 8; const char* const BmSmtpAccount::ENCR_AUTO = "<auto>"; const char* const BmSmtpAccount::ENCR_STARTTLS = "STARTTLS"; const char* const BmSmtpAccount::ENCR_TLS = "TLS"; const char* const BmSmtpAccount::ENCR_SSL = "SSL"; const char* const BmSmtpAccount::AUTH_AUTO = "<auto>"; const char* const BmSmtpAccount::AUTH_SMTP_AFTER_POP= "SMTP-AFTER-POP"; const char* const BmSmtpAccount::AUTH_PLAIN = "PLAIN"; const char* const BmSmtpAccount::AUTH_LOGIN = "LOGIN"; const char* const BmSmtpAccount::AUTH_CRAM_MD5 = "CRAM-MD5"; const char* const BmSmtpAccount::AUTH_DIGEST_MD5 = "DIGEST-MD5"; const char* const BmSmtpAccount::AUTH_NONE = "<none>"; const char* const BmSmtpAccount::MSG_REF = "ref"; /*------------------------------------------------------------------------------*\ BmSmtpAccount() - c'tor \*------------------------------------------------------------------------------*/ BmSmtpAccount::BmSmtpAccount( const char* name, BmSmtpAccountList* model) : inherited( name, model, (BmListModelItem*)NULL) , mPortNr( 25) , mPortNrString( "25") , mPwdStoredOnDisk( false) , mEncryptionType( ENCR_AUTO) , mAuthMethod( AUTH_AUTO) { } /*------------------------------------------------------------------------------*\ BmSmtpAccount( archive) - c'tor - constructs a BmSmtpAccount from a BMessage \*------------------------------------------------------------------------------*/ BmSmtpAccount::BmSmtpAccount( BMessage* archive, BmSmtpAccountList* model) : inherited( FindMsgString( archive, MSG_NAME), model, (BmListModelItem*)NULL) { int16 version = FindMsgInt16( archive, MSG_VERSION); mUsername = FindMsgString( archive, MSG_USERNAME); mPassword = FindMsgString( archive, MSG_PASSWORD); mSMTPServer = FindMsgString( archive, MSG_SMTP_SERVER); mDomainToAnnounce = FindMsgString( archive, MSG_DOMAIN); mAuthMethod = FindMsgString( archive, MSG_AUTH_METHOD); if (!mAuthMethod.Length()) mAuthMethod = AUTH_NONE; mPortNr = FindMsgInt16( archive, MSG_PORT_NR); mPortNrString << (uint32)mPortNr; mPwdStoredOnDisk = FindMsgBool( archive, MSG_STORE_PWD); mClientCertificate = archive->FindString( MSG_CLIENT_CERT); mAcceptedCertID = archive->FindString( MSG_ACCEPTED_CERT); if (version > 1) { mAccForSmtpAfterPop = FindMsgString( archive, MSG_ACC_FOR_SAP); } if (version <= 4) { if (mAuthMethod.Length() && mAuthMethod[0] != '<') mAuthMethod.ToUpper( ); } if (version <= 5) { // with version 6 we introduce auto-detection of best authentication // method. This is now the default: mAuthMethod = AUTH_AUTO; } if (version <= 6) { // with version 7 we introduce auto-detection of encryption // availability. This is now the default: mEncryptionType = ENCR_AUTO; } else { mEncryptionType = FindMsgString( archive, MSG_ENCRYPTION_TYPE); } } /*------------------------------------------------------------------------------*\ ~BmSmtpAccount() - standard d'tor \*------------------------------------------------------------------------------*/ BmSmtpAccount::~BmSmtpAccount() { } /*------------------------------------------------------------------------------*\ Archive( archive, deep) - writes BmSmtpAccount into archive - parameter deep makes no difference... \*------------------------------------------------------------------------------*/ status_t BmSmtpAccount::Archive( BMessage* archive, bool deep) const { status_t ret = inherited::Archive( archive, deep) || archive->AddString( MSG_NAME, Key().String()) || archive->AddString( MSG_USERNAME, mUsername.String()) || archive->AddString( MSG_PASSWORD, mPassword.String()) || archive->AddString( MSG_SMTP_SERVER, mSMTPServer.String()) || archive->AddString( MSG_DOMAIN, mDomainToAnnounce.String()) || archive->AddString( MSG_ENCRYPTION_TYPE, mEncryptionType.String()) || archive->AddString( MSG_AUTH_METHOD, mAuthMethod.String()) || archive->AddInt16( MSG_PORT_NR, mPortNr) || archive->AddBool( MSG_STORE_PWD, mPwdStoredOnDisk) || archive->AddString( MSG_ACC_FOR_SAP, mAccForSmtpAfterPop.String()) || archive->AddString( MSG_CLIENT_CERT, mClientCertificate.String()) || archive->AddString( MSG_ACCEPTED_CERT, mAcceptedCertID.String()); return ret; } /*------------------------------------------------------------------------------*\ NeedsAuthViaPopServer() - determines if this SMTP-account requires authentication through a corresponding POP-server \*------------------------------------------------------------------------------*/ bool BmSmtpAccount::NeedsAuthViaPopServer() { return mAuthMethod.ICompare(AUTH_SMTP_AFTER_POP) == 0; } /*------------------------------------------------------------------------------*\ SanityCheck() - checks if the current values make sense and returns error-info through given out-params - returns true if values are ok, false (and error-info) if not \*------------------------------------------------------------------------------*/ bool BmSmtpAccount::SanityCheck( BmString& complaint, BmString& fieldName) const { if (!mSMTPServer.Length()) { complaint = "Please enter the address of this account's SMTP-Server."; fieldName = "smtpserver"; return false; } if ((mAuthMethod != AUTH_NONE && mAuthMethod != AUTH_SMTP_AFTER_POP) && !mUsername.Length()) { complaint = "Please enter a username to use during authentication."; fieldName = "username"; return false; } if (mAuthMethod==AUTH_SMTP_AFTER_POP && !mAccForSmtpAfterPop.Length()) { complaint = "Please select a pop-account to be used for authentication."; fieldName = "pop-account"; return false; } if (mPortNr<=0) { complaint = "Please enter a valid port-nr (1-65535) for this account."; fieldName = "portnr"; return false; } return true; } /*------------------------------------------------------------------------------*\ SendMail() - sends the passed mail through this account \*------------------------------------------------------------------------------*/ void BmSmtpAccount::SendMail( const entry_ref& eref) { BMessage archive(BM_JOBWIN_SMTP); archive.AddString( BmJobModel::MSG_JOB_NAME, Key().String()); archive.AddRef( MSG_REF, &eref); BLooper* controller = BeamGuiRoster->JobMetaController(); if (controller) controller->PostMessage( &archive); } /*------------------------------------------------------------------------------*\ SendPendingMails() - sends all pending mails for this account (if any) \*------------------------------------------------------------------------------*/ void BmSmtpAccount::SendPendingMails() { BmMailQuery pendingQuery; BmString pred = "(MAIL:status = 'Pending') && (MAIL:account = '"; pred << Key() << "')"; pendingQuery.SetPredicate(pred); pendingQuery.Execute(); // only start job if there's actually something to do: uint32 count = pendingQuery.mRefVect.size(); if (count > 0) { BMessage archive(BM_JOBWIN_SMTP); archive.AddString( BmJobModel::MSG_JOB_NAME, Key().String()); for( uint32 i=0; i<count; ++i) archive.AddRef( MSG_REF, &pendingQuery.mRefVect[i]); BLooper* controller = BeamGuiRoster->JobMetaController(); if (controller) controller->PostMessage( &archive); } } /*------------------------------------------------------------------------------*\ GetSupportedAuthTypes() - \*------------------------------------------------------------------------------*/ void BmSmtpAccount::GetSupportedAuthTypes(vector<BmString>& outList) const { outList.push_back(AUTH_AUTO); outList.push_back(AUTH_CRAM_MD5); outList.push_back(AUTH_DIGEST_MD5); outList.push_back(AUTH_SMTP_AFTER_POP); outList.push_back(AUTH_PLAIN); outList.push_back(AUTH_LOGIN); outList.push_back(AUTH_NONE); } /********************************************************************************\ BmSmtpAccountList \********************************************************************************/ BmRef< BmSmtpAccountList> BmSmtpAccountList::theInstance( NULL); const int16 BmSmtpAccountList::nArchiveVersion = 1; /*------------------------------------------------------------------------------*\ CreateInstance() - initialiazes object by reading info from settings file (if any) \*------------------------------------------------------------------------------*/ BmSmtpAccountList* BmSmtpAccountList::CreateInstance() { if (!theInstance) { theInstance = new BmSmtpAccountList(); } return theInstance.Get(); } /*------------------------------------------------------------------------------*\ BmSmtpAccountList() - default constructor, creates empty list \*------------------------------------------------------------------------------*/ BmSmtpAccountList::BmSmtpAccountList() : inherited( "SmtpAccountList", BM_LogMailTracking) { NeedControllersToContinue( false); } /*------------------------------------------------------------------------------*\ ~BmSmtpAccountList() - standard destructor \*------------------------------------------------------------------------------*/ BmSmtpAccountList::~BmSmtpAccountList() { theInstance = NULL; } /*------------------------------------------------------------------------------*\ SettingsFileName() - returns name of settings-file for list of SMTP-accounts \*------------------------------------------------------------------------------*/ const BmString BmSmtpAccountList::SettingsFileName() { BmString name = BmString( BeamRoster->SettingsPath()) << "/" << "Sending Accounts"; // this file used to be called "Smtp Accounts", so we automatically // rename, if only the old name exists: BEntry entry( name.String()); if (!entry.Exists()) { BmString oldName = BmString( BeamRoster->SettingsPath()) << "/" << "Smtp Accounts"; BEntry oldEntry( oldName.String()); oldEntry.Rename( name.String()); } return name; } /*------------------------------------------------------------------------------*\ InstantiateItem( archive) - instantiates one SMTP-account from given message-archive \*------------------------------------------------------------------------------*/ void BmSmtpAccountList::InstantiateItem( BMessage* archive) { BmSmtpAccount* newAcc = new BmSmtpAccount( archive, this); BM_LOG3( BM_LogMailTracking, BmString("SmtpAccount <") << newAcc->Name() << "," << newAcc->Key() << "> read"); AddItemToList( newAcc); } /*------------------------------------------------------------------------------*\ SendPendingMails() - sends pending mails for all accounts \*------------------------------------------------------------------------------*/ void BmSmtpAccountList::SendPendingMails() { BmAutolockCheckGlobal lock( mModelLocker); if (!lock.IsLocked()) BM_THROW_RUNTIME( ModelNameNC() << ": Unable to get lock"); BmModelItemMap::const_iterator iter; for( iter = begin(); iter != end(); ++iter) { BmSmtpAccount* smtpAcc = dynamic_cast<BmSmtpAccount*>( iter->second.Get()); if (smtpAcc) smtpAcc->SendPendingMails(); } } /*------------------------------------------------------------------------------*\ SendPendingMailsFor( accName) - sends all pending mails for the account specified by accName \*------------------------------------------------------------------------------*/ void BmSmtpAccountList::SendPendingMailsFor( const BmString accName) { BmRef<BmListModelItem> itemRef = FindItemByKey( accName); BmSmtpAccount* smtpAcc = dynamic_cast<BmSmtpAccount*>( itemRef.Get()); if (smtpAcc) smtpAcc->SendPendingMails(); }
gpl-2.0
sammyboy45467/oak-star
wp-content/plugins/google-maps-builder/admin/views/logo-svg-small.php
3156
<?php /** * LOGO SVG * * @package Google_Maps_Builder * @author Devin Walker <devin@wordimpress.com> * @license GPL-2.0+ * @link http://wordimpress.com * @copyright 2014 WordImpress, Devin Walker */ ?> <svg height="35px" id="Layer_1" style="enable-background:new 0 0 512 512;" version="1.1" viewBox="0 0 512 512" width="35px" xml:space="preserve" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><g id="flat_x5F_8"> <g> <path d="M424.574,447.998l-25.471-6.039l77.041-316.293c-11.028-18.652-24.314-35.824-39.56-51.053 l-19.13,78.383L202.053,101.92L226.582,1.405c-19.051,2.152-37.457,6.407-55.006,12.514L152.948,90.28L77.144,72.303 c-13.296,12.945-25.186,27.313-35.437,42.88l99.446,23.58L85.485,367.595l-67.161-15.896c8.636,21.324,20.039,41.22,33.805,59.239 l21.566,5.14l-3.812,15.668c12.955,13.675,27.366,25.967,43.053,36.515l9.862-40.541l245.086,58.11 C388.496,475.764,407.523,462.987,424.574,447.998z M190.26,150.403l215.405,51.075l-55.666,228.84l-215.405-51.081 L190.26,150.403z" style="fill:#FFF8A3;" /> <path d="M417.456,152.996l-40.345-9.564l-41.879,41.348l70.433,16.699l-55.666,228.84l-212.431-50.377 l-60.126,59.369c10.944,10.652,22.775,20.396,35.497,28.951l9.862-40.541l245.086,58.111 c20.608-10.068,39.637-22.846,56.688-37.834l-25.471-6.039l77.041-316.293c-9.802-16.58-21.396-31.982-34.558-45.895l-8.246,8.143 L417.456,152.996z" style="fill:#E1D78F;" /> <g> <path d="M69.887,431.748l3.812-15.668l-21.566-5.141C57.67,418.198,63.612,425.135,69.887,431.748z" style="fill:#AAC26F;" /> <path d="M-0.344,255.718c0,33.956,6.664,66.331,18.67,95.981l67.161,15.896l55.668-228.832l-99.446-23.58 C15.153,155.528-0.344,203.8-0.344,255.718z" style="fill:#AAC26F;" /> <path d="M255.657-0.283c-9.836,0-19.527,0.611-29.074,1.688L202.054,101.92l215.402,51.075l19.13-78.382 C390.268,28.338,326.307-0.283,255.657-0.283z" style="fill:#AAC26F;" /> <path d="M152.949,90.28l18.628-76.361c-35.746,12.424-67.882,32.539-94.432,58.386L152.949,90.28z" style="fill:#AAC26F;" /> </g> <polygon points="134.594,379.237 349.999,430.318 405.665,201.479 190.26,150.403 " style="fill:#6AAFDA;" /> <g> <path d="M112.939,468.262c40.778,27.436,89.875,43.455,142.718,43.455 c40.263,0,78.341-9.322,112.229-25.885l-245.085-58.111L112.939,468.262z" style="fill:#5E9CC1;" /> <polygon points="405.665,201.479 335.232,184.779 137.568,379.941 349.999,430.318 " style="fill:#5E9CC1;" /> </g> <path d="M511.656,255.718c0-47.491-12.975-91.925-35.512-130.052l-77.041,316.293l25.471,6.039 C477.936,401.082,511.656,332.359,511.656,255.718z" style="fill:#C6A963;" /> <path d="M497.996,113.431c0,48.554-67.83,190.112-89.042,190.112c-20.666,0-89.044-141.56-89.044-190.112 c0-48.554,39.865-87.915,89.044-87.915C458.131,25.516,497.996,64.877,497.996,113.431z" style="fill:#F05D4A;" /> <path d="M454.284,115.528c0-24.716-20.296-44.749-45.33-44.749c-25.033,0-45.33,20.033-45.33,44.749 c0,24.719,20.297,44.758,45.33,44.758C433.988,160.284,454.284,140.246,454.284,115.528z" style="fill:#BD4231;" /> </g> </g> <g id="Layer_1_1_" /></svg>
gpl-2.0
pombreda/paludis
paludis/args/man.cc
10979
/* vim: set sw=4 sts=4 et foldmethod=syntax : */ /* * Copyright (c) 2006, 2007, 2008, 2009, 2010, 2011 Ciaran McCreesh * Copyright (c) 2011 Ingmar Vanhassel * * This file is part of the Paludis package manager. Paludis is free software; * you can redistribute it and/or modify it under the terms of the GNU General * Public License version 2, as published by the Free Software Foundation. * * Paludis 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 "man.hh" #include <paludis/util/upper_lower.hh> #include <paludis/util/visitor_cast.hh> #include <paludis/util/wrapped_forward_iterator-impl.hh> #include <functional> #include <ostream> #include <sstream> #include <algorithm> using namespace paludis; using namespace paludis::args; using std::endl; namespace { struct ExtraText { DocWriter & _dw; ExtraText(DocWriter & dw) : _dw(dw) { } void visit(const StringArg &) { } void visit(const AliasArg &) { } void visit(const SwitchArg &) { } void visit(const IntegerArg &) { } void visit(const EnumArg & e) { if (e.begin_allowed_args() == e.end_allowed_args()) return; _dw.start_extra_arg(); for (EnumArg::AllowedArgConstIterator a(e.begin_allowed_args()), a_end(e.end_allowed_args()) ; a != a_end ; ++a) _dw.extra_arg_enum(*a, e.default_arg()); _dw.end_extra_arg(); } void visit(const StringSetArg & e) { if (e.begin_allowed_args() == e.end_allowed_args()) return; _dw.start_extra_arg(); for (StringSetArg::AllowedArgConstIterator a(e.begin_allowed_args()), a_end(e.end_allowed_args()) ; a != a_end ; ++a) _dw.extra_arg_string_set(a->first, a->second); _dw.end_extra_arg(); } void visit(const StringSequenceArg &) { } }; } void paludis::args::generate_doc(DocWriter & dw, const ArgsHandler * const h) { using namespace std::placeholders; dw.heading(h->app_name(), h->man_section(), h->app_synopsis()); for (ArgsHandler::UsageLineConstIterator u(h->begin_usage_lines()), u_end(h->end_usage_lines()) ; u != u_end ; ++u) { if (u == h->begin_usage_lines()) dw.start_usage_lines(); dw.usage_line(h->app_name(), *u); } dw.start_description(h->app_description()); for (ArgsHandler::DescriptionLineConstIterator u(h->begin_description_lines()), u_end(h->end_description_lines()) ; u != u_end ; ++u) dw.extra_description(*u); dw.end_description(); for (ArgsHandler::ArgsSectionsConstIterator s(h->begin_args_sections()), s_end(h->end_args_sections()) ; s != s_end ; ++s) { dw.start_options(s->name()); for (ArgsSection::GroupsConstIterator a(s->begin()), a_end(s->end()) ; a != a_end ; ++a) { dw.start_arg_group(a->name(), a->description()); for (paludis::args::ArgsGroup::ConstIterator b(a->begin()), b_end(a->end()) ; b != b_end ; ++b) { if (visitor_cast<const paludis::args::AliasArg>(**b) && visitor_cast<const paludis::args::AliasArg>(**b)->hidden()) continue; dw.arg_group_item((*b)->short_name(), (*b)->long_name(), (*b)->can_be_negated() ? "no-" + (*b)->long_name() : "", (*b)->description()); ExtraText t(dw); (*b)->accept(t); } dw.end_arg_group(); } } dw.end_options(); if (h->begin_environment_lines() != h->end_environment_lines()) { dw.start_environment(); for (ArgsHandler::EnvironmentLineConstIterator a(h->begin_environment_lines()), a_end(h->end_environment_lines()) ; a != a_end ; ++a) { dw.environment_line(a->first, a->second); } dw.end_environment(); } if (h->begin_notes() != h->end_notes()) { dw.start_notes(); std::for_each(h->begin_notes(), h->end_notes(), std::bind(&DocWriter::note, &dw, _1)); dw.end_notes(); } if (h->begin_examples() != h->end_examples()) { dw.start_examples(); for (ArgsHandler::ExamplesConstIterator a(h->begin_examples()), a_end(h->end_examples()) ; a != a_end ; ++a) dw.example(a->first, a->second); dw.end_examples(); } if (h->begin_see_alsos() != h->end_see_alsos()) { dw.start_see_alsos(); for (ArgsHandler::SeeAlsoConstIterator u(h->begin_see_alsos()), u_end(h->end_see_alsos()) ; u != u_end ; ++u) dw.see_also(u->first, u->second, u == h->begin_see_alsos()); dw.end_see_alsos(); } } DocWriter::~DocWriter() { } namespace { void escape_asciidoc(std::ostream & stream, const std::string & s) { char previous('\0'); for (auto t(s.begin()), t_end(s.end()) ; t != t_end ; ++t) { switch (previous) { case '\0': case ' ': case '\n': case '\t': case '\'': if ('*' == *t) stream << '\\'; break; // Escape '*/*' -> '\*/*' } stream << *t; previous = *t; } } } AsciidocWriter::AsciidocWriter(std::ostream & os) : _os(os) { } AsciidocWriter::~AsciidocWriter() { } void AsciidocWriter::heading(const std::string & name, const std::string & section_, const std::string & synopsis) { std::string name_no_spaces(name); std::replace(name_no_spaces.begin(), name_no_spaces.end(), ' ', '-'); _os << name_no_spaces << "(" << section_ << ")" << endl; _os << std::string(name_no_spaces.size() + 3, '=') << endl << endl << endl; _os << "NAME" << endl; _os << "----" << endl << endl; _os << name_no_spaces << " - " << synopsis << endl << endl; } void AsciidocWriter::start_usage_lines() { _os << "SYNOPSIS" << endl; _os << "--------" << endl << endl; } void AsciidocWriter::usage_line(const std::string & name, const std::string & line) { _os << "*" << name; if (! line.empty()) { _os << " "; escape_asciidoc(_os, line); } _os << "*" << endl << endl; } void AsciidocWriter::start_description(const std::string & description) { _os << "DESCRIPTION" << endl; _os << "-----------" << endl; escape_asciidoc(_os, description); _os << endl; } void AsciidocWriter::extra_description(const std::string & description) { _os << endl; escape_asciidoc(_os, description); _os << endl << endl; } void AsciidocWriter::end_description() { _os << endl; } void AsciidocWriter::start_options(const std::string & s) { _os << toupper(s) << endl; _os << std::string(s.size(), char('-')) << endl; } void AsciidocWriter::start_arg_group(const std::string & name, const std::string & description) { _os << name << endl; _os << std::string(name.size(), char('~')) << endl; escape_asciidoc(_os, description); _os << endl << endl; } void AsciidocWriter::arg_group_item(const char & short_name, const std::string & long_name, const std::string & negated_long_name, const std::string & description) { _os << "*"; if (short_name) _os << "-" << short_name << " , "; _os << "--" << long_name; if (! negated_long_name.empty()) { _os << " ("; if (short_name) _os << "+" << short_name << " , "; _os << "--" << negated_long_name << ")"; } _os << "*::" << endl; _os << " "; escape_asciidoc(_os, description); _os << endl << endl; } void AsciidocWriter::start_extra_arg() { } void AsciidocWriter::extra_arg_enum(const AllowedEnumArg & e, const std::string & default_arg) { std::string default_string; if (e.long_name() == default_arg) default_string = " (default)"; _os << " *" << e.long_name(); if (e.short_name()) _os << " (" << std::string(1, e.short_name()) << ")"; _os << "*;;" << endl; _os << " "; escape_asciidoc(_os, e.description()); _os << default_string << endl << endl; } void AsciidocWriter::extra_arg_string_set(const std::string & first, const std::string & second) { _os << "*" << first << "*:::" << endl; _os << " "; escape_asciidoc(_os, second); _os << endl; } void AsciidocWriter::end_extra_arg() { _os << endl; } void AsciidocWriter::end_arg_group() { _os << endl; } void AsciidocWriter::end_options() { _os << endl; } void AsciidocWriter::start_environment() { _os << "ENVIRONMENT" << endl; _os << "-----------" << endl; } void AsciidocWriter::environment_line(const std::string & first, const std::string & second) { _os << first << "::" << endl; escape_asciidoc(_os, second); _os << endl; } void AsciidocWriter::end_environment() { _os << endl; } void AsciidocWriter::start_examples() { _os << "EXAMPLES" << endl; _os << "--------" << endl; } void AsciidocWriter::example(const std::string & first, const std::string & second) { _os << first << "::" << endl; escape_asciidoc(_os, second); _os << endl; } void AsciidocWriter::end_examples() { _os << endl; } void AsciidocWriter::start_notes() { _os << "NOTES" << endl; _os << "-----" << endl; } void AsciidocWriter::note(const std::string & s) { _os << "* "; escape_asciidoc(_os, s); _os << endl; } void AsciidocWriter::end_notes() { _os << endl; } void AsciidocWriter::section(const std::string & title) { _os << title << endl; _os << std::string(title.size(), '-') << endl; } void AsciidocWriter::subsection(const std::string & title) { _os << title << endl; _os << std::string(title.size(), '~') << endl; } void AsciidocWriter::paragraph(const std::string & text) { escape_asciidoc(_os, text); _os << endl; } void AsciidocWriter::start_see_alsos() { _os << "SEE ALSO" << endl; _os << "--------" << endl; } void AsciidocWriter::see_also(const std::string & page, const int s, const bool) { _os << "*" << page << "*(" << s << ")" << endl; } void AsciidocWriter::end_see_alsos() { _os << endl; }
gpl-2.0
Creativetech-Solutions/joomla-easysocial-network
administrator/components/com_rsform/controllers/conditions.php
1862
<?php /** * @package RSForm! Pro * @copyright (C) 2007-2014 www.rsjoomla.com * @license GPL, http://www.gnu.org/copyleft/gpl.html */ defined('_JEXEC') or die('Restricted access'); jimport('joomla.application.component.controller'); class RSFormControllerConditions extends RSFormController { function __construct() { parent::__construct(); $this->registerTask('apply', 'save'); } function save() { // Check for request forgeries JSession::checkToken() or jexit('Invalid Token'); $model = $this->getModel('conditions'); $task = $this->getTask(); $formId = $model->getFormId(); // Save $cid = $model->save(); $link = $cid ? 'index.php?option=com_rsform&view=conditions&layout=edit&cid='.$cid.'&formId='.$formId.'&tmpl=component' : 'index.php?option=com_rsform&view=conditions&layout=edit&formId='.$formId.'&tmpl=component'; $msg = $cid ? JText::_('RSFP_CONDITION_SAVED') : JText::_('RSFP_CONDITION_ERROR'); if ($task == 'save') $link .= '&close=1'; $this->setRedirect($link, $msg); } function remove() { $model = $this->getModel('conditions'); $formId = $model->getFormId(); $model->remove(); JFactory::getApplication()->input->set('view', 'forms'); JFactory::getApplication()->input->set('layout', 'edit_conditions'); JFactory::getApplication()->input->set('tmpl', 'component'); JFactory::getApplication()->input->set('formId', $formId); parent::display(); jexit(); } function showConditions() { $model = $this->getModel('conditions'); $formId = $model->getFormId(); JFactory::getApplication()->input->set('view', 'forms'); JFactory::getApplication()->input->set('layout', 'edit_conditions'); JFactory::getApplication()->input->set('tmpl', 'component'); JFactory::getApplication()->input->set('formId', $formId); parent::display(); exit(); } }
gpl-2.0
arthurmelo88/palmetalADP
adempiereTrunk/base/src/org/compiere/model/I_AD_Process.java
11209
/****************************************************************************** * Product: Adempiere ERP & CRM Smart Business Solution * * Copyright (C) 1999-2007 ComPiere, Inc. All Rights Reserved. * * This program is free software, you can redistribute it and/or modify it * * under the terms version 2 of the GNU General Public License as published * * by the Free Software Foundation. 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. * * For the text or an alternative of this public license, you may reach us * * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * * or via info@compiere.org or http://www.compiere.org/license.html * *****************************************************************************/ package org.compiere.model; import java.math.BigDecimal; import java.sql.Timestamp; import org.compiere.util.KeyNamePair; /** Generated Interface for AD_Process * @author Adempiere (generated) * @version Release 3.6.0LTS */ public interface I_AD_Process { /** TableName=AD_Process */ public static final String Table_Name = "AD_Process"; /** AD_Table_ID=284 */ public static final int Table_ID = MTable.getTable_ID(Table_Name); KeyNamePair Model = new KeyNamePair(Table_ID, Table_Name); /** AccessLevel = 4 - System */ BigDecimal accessLevel = BigDecimal.valueOf(4); /** Load Meta Data */ /** Column name AccessLevel */ public static final String COLUMNNAME_AccessLevel = "AccessLevel"; /** Set Data Access Level. * Access Level required */ public void setAccessLevel (String AccessLevel); /** Get Data Access Level. * Access Level required */ public String getAccessLevel(); /** Column name AD_Client_ID */ public static final String COLUMNNAME_AD_Client_ID = "AD_Client_ID"; /** Get Client. * Client/Tenant for this installation. */ public int getAD_Client_ID(); /** Column name AD_Form_ID */ public static final String COLUMNNAME_AD_Form_ID = "AD_Form_ID"; /** Set Special Form. * Special Form */ public void setAD_Form_ID (int AD_Form_ID); /** Get Special Form. * Special Form */ public int getAD_Form_ID(); public I_AD_Form getAD_Form() throws RuntimeException; /** Column name AD_Org_ID */ public static final String COLUMNNAME_AD_Org_ID = "AD_Org_ID"; /** Set Organization. * Organizational entity within client */ public void setAD_Org_ID (int AD_Org_ID); /** Get Organization. * Organizational entity within client */ public int getAD_Org_ID(); /** Column name AD_PrintFormat_ID */ public static final String COLUMNNAME_AD_PrintFormat_ID = "AD_PrintFormat_ID"; /** Set Print Format. * Data Print Format */ public void setAD_PrintFormat_ID (int AD_PrintFormat_ID); /** Get Print Format. * Data Print Format */ public int getAD_PrintFormat_ID(); public I_AD_PrintFormat getAD_PrintFormat() throws RuntimeException; /** Column name AD_Process_ID */ public static final String COLUMNNAME_AD_Process_ID = "AD_Process_ID"; /** Set Process. * Process or Report */ public void setAD_Process_ID (int AD_Process_ID); /** Get Process. * Process or Report */ public int getAD_Process_ID(); /** Column name AD_ReportView_ID */ public static final String COLUMNNAME_AD_ReportView_ID = "AD_ReportView_ID"; /** Set Report View. * View used to generate this report */ public void setAD_ReportView_ID (int AD_ReportView_ID); /** Get Report View. * View used to generate this report */ public int getAD_ReportView_ID(); public I_AD_ReportView getAD_ReportView() throws RuntimeException; /** Column name AD_Workflow_ID */ public static final String COLUMNNAME_AD_Workflow_ID = "AD_Workflow_ID"; /** Set Workflow. * Workflow or combination of tasks */ public void setAD_Workflow_ID (int AD_Workflow_ID); /** Get Workflow. * Workflow or combination of tasks */ public int getAD_Workflow_ID(); public I_AD_Workflow getAD_Workflow() throws RuntimeException; /** Column name Classname */ public static final String COLUMNNAME_Classname = "Classname"; /** Set Classname. * Java Classname */ public void setClassname (String Classname); /** Get Classname. * Java Classname */ public String getClassname(); /** Column name CopyFromProcess */ public static final String COLUMNNAME_CopyFromProcess = "CopyFromProcess"; /** Set Copy From Report and Process. * Copy settings from one report and process to another. */ public void setCopyFromProcess (String CopyFromProcess); /** Get Copy From Report and Process. * Copy settings from one report and process to another. */ public String getCopyFromProcess(); /** Column name Created */ public static final String COLUMNNAME_Created = "Created"; /** Get Created. * Date this record was created */ public Timestamp getCreated(); /** Column name CreatedBy */ public static final String COLUMNNAME_CreatedBy = "CreatedBy"; /** Get Created By. * User who created this records */ public int getCreatedBy(); /** Column name Description */ public static final String COLUMNNAME_Description = "Description"; /** Set Description. * Optional short description of the record */ public void setDescription (String Description); /** Get Description. * Optional short description of the record */ public String getDescription(); /** Column name EntityType */ public static final String COLUMNNAME_EntityType = "EntityType"; /** Set Entity Type. * Dictionary Entity Type; Determines ownership and synchronization */ public void setEntityType (String EntityType); /** Get Entity Type. * Dictionary Entity Type; Determines ownership and synchronization */ public String getEntityType(); /** Column name Help */ public static final String COLUMNNAME_Help = "Help"; /** Set Comment/Help. * Comment or Hint */ public void setHelp (String Help); /** Get Comment/Help. * Comment or Hint */ public String getHelp(); /** Column name IsActive */ public static final String COLUMNNAME_IsActive = "IsActive"; /** Set Active. * The record is active in the system */ public void setIsActive (boolean IsActive); /** Get Active. * The record is active in the system */ public boolean isActive(); /** Column name IsBetaFunctionality */ public static final String COLUMNNAME_IsBetaFunctionality = "IsBetaFunctionality"; /** Set Beta Functionality. * This functionality is considered Beta */ public void setIsBetaFunctionality (boolean IsBetaFunctionality); /** Get Beta Functionality. * This functionality is considered Beta */ public boolean isBetaFunctionality(); /** Column name IsDirectPrint */ public static final String COLUMNNAME_IsDirectPrint = "IsDirectPrint"; /** Set Direct print. * Print without dialog */ public void setIsDirectPrint (boolean IsDirectPrint); /** Get Direct print. * Print without dialog */ public boolean isDirectPrint(); /** Column name IsReport */ public static final String COLUMNNAME_IsReport = "IsReport"; /** Set Report. * Indicates a Report record */ public void setIsReport (boolean IsReport); /** Get Report. * Indicates a Report record */ public boolean isReport(); /** Column name IsServerProcess */ public static final String COLUMNNAME_IsServerProcess = "IsServerProcess"; /** Set Server Process. * Run this Process on Server only */ public void setIsServerProcess (boolean IsServerProcess); /** Get Server Process. * Run this Process on Server only */ public boolean isServerProcess(); /** Column name JasperReport */ public static final String COLUMNNAME_JasperReport = "JasperReport"; /** Set Jasper Report */ public void setJasperReport (String JasperReport); /** Get Jasper Report */ public String getJasperReport(); /** Column name Name */ public static final String COLUMNNAME_Name = "Name"; /** Set Name. * Alphanumeric identifier of the entity */ public void setName (String Name); /** Get Name. * Alphanumeric identifier of the entity */ public String getName(); /** Column name ProcedureName */ public static final String COLUMNNAME_ProcedureName = "ProcedureName"; /** Set Procedure. * Name of the Database Procedure */ public void setProcedureName (String ProcedureName); /** Get Procedure. * Name of the Database Procedure */ public String getProcedureName(); /** Column name ShowHelp */ public static final String COLUMNNAME_ShowHelp = "ShowHelp"; /** Set Show Help */ public void setShowHelp (String ShowHelp); /** Get Show Help */ public String getShowHelp(); /** Column name Statistic_Count */ public static final String COLUMNNAME_Statistic_Count = "Statistic_Count"; /** Set Statistic Count. * Internal statistics how often the entity was used */ public void setStatistic_Count (int Statistic_Count); /** Get Statistic Count. * Internal statistics how often the entity was used */ public int getStatistic_Count(); /** Column name Statistic_Seconds */ public static final String COLUMNNAME_Statistic_Seconds = "Statistic_Seconds"; /** Set Statistic Seconds. * Internal statistics how many seconds a process took */ public void setStatistic_Seconds (int Statistic_Seconds); /** Get Statistic Seconds. * Internal statistics how many seconds a process took */ public int getStatistic_Seconds(); /** Column name Updated */ public static final String COLUMNNAME_Updated = "Updated"; /** Get Updated. * Date this record was updated */ public Timestamp getUpdated(); /** Column name UpdatedBy */ public static final String COLUMNNAME_UpdatedBy = "UpdatedBy"; /** Get Updated By. * User who updated this records */ public int getUpdatedBy(); /** Column name Value */ public static final String COLUMNNAME_Value = "Value"; /** Set Search Key. * Search key for the record in the format required - must be unique */ public void setValue (String Value); /** Get Search Key. * Search key for the record in the format required - must be unique */ public String getValue(); /** Column name WorkflowValue */ public static final String COLUMNNAME_WorkflowValue = "WorkflowValue"; /** Set Workflow Key. * Key of the Workflow to start */ public void setWorkflowValue (String WorkflowValue); /** Get Workflow Key. * Key of the Workflow to start */ public String getWorkflowValue(); }
gpl-2.0
bohemio-rulo/lunanegra
wp-content/plugins/newsletter-sign-up/includes/views/parts/rows-aweber.php
303
<tr valign="top"> <th scope="row"><label for="aweber_list_name" Aweber list name</th> <td><input id="aweber_list_name" class="widefat" type="text" name="nsu_mailinglist[aweber_list_name]" value="<?php if (isset($opts['aweber_list_name'])) echo esc_attr($opts['aweber_list_name']); ?>" /></td> </tr>
gpl-2.0
scoophealth/oscar
src/main/java/org/oscarehr/common/model/DrugDispensing.java
3585
/** * Copyright (c) 2001-2002. Department of Family Medicine, McMaster University. All Rights Reserved. * This software is published under the GPL GNU General Public 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. * * 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. * * This software was written for the * Department of Family Medicine * McMaster University * Hamilton * Ontario, Canada */ package org.oscarehr.common.model; import java.util.Date; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Temporal; import javax.persistence.TemporalType; import org.apache.commons.lang.time.DateFormatUtils; @Entity public class DrugDispensing extends AbstractModel<Integer> { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id = null; private int drugId; @Temporal(TemporalType.TIMESTAMP) private Date dateCreated; private int productId; private int quantity; private String unit; private String dispensingProviderNo; private String providerNo; private boolean paidFor; private String notes; private int programNo; private boolean archived = false; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public int getDrugId() { return drugId; } public void setDrugId(int drugId) { this.drugId = drugId; } public Date getDateCreated() { return dateCreated; } public void setDateCreated(Date dateCreated) { this.dateCreated = dateCreated; } public int getProductId() { return productId; } public void setProductId(int productId) { this.productId = productId; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } public String getUnit() { return unit; } public void setUnit(String unit) { this.unit = unit; } public String getDispensingProviderNo() { return dispensingProviderNo; } public void setDispensingProviderNo(String dispensingProviderNo) { this.dispensingProviderNo = dispensingProviderNo; } public String getProviderNo() { return providerNo; } public void setProviderNo(String providerNo) { this.providerNo = providerNo; } public boolean isPaidFor() { return paidFor; } public void setPaidFor(boolean paidFor) { this.paidFor = paidFor; } public String getNotes() { return notes; } public void setNotes(String notes) { this.notes = notes; } public String getDateCreatedAsString() { if(getDateCreated() != null) return DateFormatUtils.ISO_DATE_FORMAT.format(getDateCreated()); return null; } public int getProgramNo() { return programNo; } public void setProgramNo(int programNo) { this.programNo = programNo; } public boolean isArchived() { return archived; } public void setArchived(boolean archived) { this.archived = archived; } }
gpl-2.0
ShaneRich5/hello-jenkins
app/models/tenant/AuthCrewUser.scala
1598
package models.tenant import java.time.LocalDate import java.util.UUID import com.mohiva.play.silhouette.api.{Identity, LoginInfo} import models.Role import models.helpers.BelongsToTenant /** * The crew (user) object. * * @param userID The unique ID of the user. * @param loginInfo The linked login info. * @param firstName Maybe the first name of the authenticated user. * @param lastName Maybe the last name of the authenticated user. * @param fullName Maybe the full name of the authenticated user. * @param email Maybe the email of the authenticated provider. * @param avatarURL Maybe the avatar URL of the authenticated provider. */ case class AuthCrewUser( userID: UUID, loginInfo: LoginInfo, firstName: Option[String], lastName: Option[String], fullName: Option[String], email: Option[String], avatarURL: Option[String], roles: Set[Role] ) extends Identity case class Crew( id: Option[UUID], loginInfo: LoginInfo, firstName: Option[String], lastName: Option[String], fullName: Option[String], email: Option[String], avatarURL: Option[String], birthDate: Option[LocalDate], address: Option[Address], tenantId: UUID ) extends Identity with BelongsToTenant
gpl-2.0
CharlesZ-Chen/checker-framework
checker/src/org/checkerframework/checker/nullness/qual/EnsuresNonNull.java
1247
package org.checkerframework.checker.nullness.qual; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.checkerframework.framework.qual.InheritedAnnotation; import org.checkerframework.framework.qual.PostconditionAnnotation; /** * Indicates that the value expressions are non-null, if the method terminates successfully. * * <p>This postcondition annotation is useful for methods that initialize a field. It can also be * used for a method that fails if a given expression is null. * * @see NonNull * @see org.checkerframework.checker.nullness.NullnessChecker * @checker_framework.manual #nullness-checker Nullness Checker */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD, ElementType.CONSTRUCTOR}) @PostconditionAnnotation(qualifier = NonNull.class) @InheritedAnnotation public @interface EnsuresNonNull { /** * The Java expressions that are ensured to be {@link NonNull} on successful method termination. * * @checker_framework.manual #java-expressions-as-arguments Syntax of Java expressions */ String[] value(); }
gpl-2.0
faysalmbt/digigo
wp-content/plugins/event-espresso-core-reg/core/third_party_libs/pue/pue-client.php
58972
<?php /** * This file should be bundled with the main plugin. Any addons to your main plugin can include this file from the main plugin folder. This contains the library for * handling all the automatic upgrade stuff on the clients end. * * You also have to make sure you call this class in any addons/plugins you want to be added to the update checker. Here's what you do: * if ( file_exists(WP_PLUGIN_DIR . '/location_of_file/pue-client.php') ) { //include the file * require( WP_PLUGIN_DIR . '/location_of_file/pue-client.php' ); * $host_server_url = 'http://updateserver.com'; //this needs to be the host server where plugin update engine is installed. note: if you leave this blank then it is assumed wordpress.org is going to be checked and we will just gracefully exit this class. * $plugin_slug = 'plugin-slug'; //this needs to be the slug of the plugin/addon that you want updated (and that pue-client.php is included with). This slug should match what you've set as the value for plugin-slug when adding the plugin to the plugin list via plugin-update-engine on your server. Note: IF this is a string then it is assumed the plugin slug will be for a premium version (requiring a license key). If it is an array, then PUE will look for the "free" and "premium" indexes and then depending on whether there is a valid key or not what version we download for upgrade. * //$options needs to be an array with the included keys as listed. * $options = array( * 'optionName' => '', //(optional) - used as the reference for saving update information in the clients options table. Will be automatically set if left blank. * 'apikey' => $api_key, //(required), you will need to obtain the apikey that the client gets from your site and then saves in their sites options table (see 'getting an api-key' below) * 'lang_domain' => '', //(optional) - put here whatever reference you are using for the localization of your plugin (if it's localized). That way strings in this file will be included in the translation for your plugin. * 'checkPeriod' => '', //(optional) - use this parameter to indicate how often you want the client's install to ping your server for update checks. The integer indicates hours. If you don't include this parameter it will default to 12 hours. * 'version_params' => array( 'free' => 'something', 'premium' => 'something' ) //(required if $slug is an array). IF $plugin_slug is an array then you must set in this option what the params are for each version as that allows PUE to know whether the installed version is your free plugin or the premium upgrade. * ); * $check_for_updates = new PluginUpdateEngineChecker($host_server_url, $plugin_slug, $options); //initiate the class and start the plugin update engine! * } */ /** * getting an api-key * */ //You'll need to put something like this here before initiating the PluginUpdateEngineChecker class to obtain the api-key the client has set for your plugin. Of course this means you will need to include a field in your plugin option page for the client to enter this key. (modify to match your setup): /* $settings = get_site_option('plugin_options'); //'plugin_options' should be replaced by whatever holds your plugin options and the api_key $api_key = $settings['plugin_api_key']; */ if ( !class_exists('PluginUpdateEngineChecker') ): /** * A custom plugin update checker. * * @original author (c) Janis Elsts * @heavily modified by Darren Ethier * @license GPL2 or greater. * @version 1.1 * @access public */ class PluginUpdateEngineChecker { public $metadataUrl = ''; //The URL of the plugin's metadata file. public $pluginFile = ''; //plugin_basename (used internally by WP updates). public $pluginName = ''; //variable used to hold the pluginName as set by the constructor. public $checkPeriod = 12; //How often to check for updates (in hours). public $optionName = ''; //Where to store the update info. public $option_key = ''; //this is what is used to reference the api_key in your plugin options. PUE uses this to trigger updating your information message whenever this option_key is modified. public $options_page_slug = ''; //this is the slug of the options page for your plugin where the site-licence(api) key is set by your user. This is required in order to do an update check immediately when the options page is set so api messages update immediately. public $json_error = ''; //for storing any json_error data that get's returned so we can display an admin notice. public $api_secret_key = ''; //used to hold the user API. If not set then nothing will work! public $install_key = ''; //used to hold the install_key if set (included here for addons that will extend PUE to use install key checks) public $install_key_arr = array(); //holds the install key array from the database. public $download_query = array(); //used to hold the query variables for download checks; public $lang_domain = ''; //used to hold the localization domain for translations . public $dismiss_upgrade; //for setting the dismiss upgrade option (per plugin). public $pue_install_key; //we'll customize this later so each plugin can have it's own install key! public $slug; //will hold the slug that is being used to check for updates. public $current_domain; //holds what the current domain is that is pinging for updates public $extra_stats; //used to contain an array of key/value pairs that will be sent as extra stats. public $turn_on_notice_saves = false; //used to flag that renewal notices/critical notices are attached to version updates of this plugin. private $_installed_version = ''; //this will just hold what installed version we have of the plugin right now. private $_is_premium = FALSE; //this is a flag used for setting whether the premium version is installed or not. private $_is_prerelease = FALSE; //optional, this flag is used to indicate whether this is a pre-release version or not. private $_is_freerelease = FALSE; //this is used to indicate whether this is a free release or not. private $_plugin_basename = ''; private $_use_wp_update = FALSE; //flag for indicating if free downloads are updated from wp or not. private $_incoming_slug = ''; private $_force_premium_upgrade = FALSE; //flag for indicating if we want to give the user the option to upgrade to premium from a free version immediately. /** * This is just a container for any pue errors that get generated (and possibly used to display via an admin notice) * @var array */ private $_pue_errors = array(); private $_error_msg = ''; /** * Class constructor. * * @param string $metadataUrl The URL of the plugin's metadata file. * @param string $pluginFile Fully qualified path to the main plugin file. * @param string $slug The plugin's 'slug'. * @param array $options: Will contain any options that need to be set in the class initialization for construct. These are the keys: * @key integer $checkPeriod How often to check for updates (in hours). Defaults to checking every 12 hours. Set to 0 to disable automatic update checks. * @key string $optionName Where to store book-keeping info about update checks. Defaults to 'external_updates-$slug'. * @key string $apikey used to authorize download updates from developer server * @key string $lang_domain If the plugin file pue-client.php is included with is localized you can put the domain reference string here so any strings in this file get included in the localization. * @return void */ function __construct( $metadataUrl = NULL, $slug = NULL, $options = array() ){ $this->metadataUrl = $metadataUrl; if ( empty($this->metadataUrl) ) return FALSE; $this->_incoming_slug = $slug; $options_verified = $this->_verify_options( $options ); if ( !$options_verified ) return; //get out because we don't have verified options (and the admin_notice should display); $verify_slug = $this->_set_slug_and_slug_props($slug, $options_verified); if ( !$verify_slug ) return; //get out because the slug isn't valid. An admin notice should show. $this->current_domain = str_replace('http://','',site_url()); $this->current_domain = urlencode(str_replace('https://','',$this->current_domain)); $this->optionName = 'external_updates-' . $this->slug; $this->checkPeriod = (int) $options_verified['checkPeriod']; $this->api_secret_key = trim( $options_verified['apikey'] ); $this->option_key = $options_verified['option_key']; $this->options_page_slug = $options_verified['options_page_slug']; $this->_use_wp_update = $this->_is_premium || $this->_is_prerelease ? FALSE : $options_verified['use_wp_update']; $this->extra_stats = $options_verified['extra_stats']; $this->turn_on_notice_saves = isset( $options_verified['turn_on_notices_saved'] ) ? $options_verified['turn_on_notices_saved'] : false; //set hooks $this->_check_for_forced_upgrade(); $this->installHooks(); } /** * This checks to see if there is a forced upgrade option saved from a previous saved options page trigger. If there is then we change the slug accordingly and setup for premium update * This function will also take care of deleting any previous force_update options IF our current installed plugin IS premium * * @access private * @return void */ private function _check_for_forced_upgrade() { /** * We ONLY execute this check if the incoming plugin being checked has a free option. * If there is no free option, then no forced upgrade will be happening. */ if ( ! isset( $this->_incoming_slug['free'] ) ) { return; } //is this premium? let's delete any saved options for free if ( $this->_is_premium ) { delete_site_option( 'pue_force_upgrade_' . $this->_incoming_slug['free'][key($this->_incoming_slug['free'])]); } else { $force_upgrade = get_site_option( 'pue_force_upgrade_' . $this->slug ); $this->_force_premium_upgrade = !empty($force_upgrade) ? TRUE : FALSE; $this->_is_premium = !empty( $force_upgrade ) ? TRUE : FALSE; $this->slug = !empty( $force_upgrade ) ? $force_upgrade : $this->slug; $this->pue_install_key = 'pue_install_key_'.$this->slug; $this->optionName = 'external_updates-' . $this->slug; $this->_use_wp_update = !empty( $force_upgrade ) ? FALSE : $this->_use_wp_update; } } /** * This simply goes through the sent options array and make sure it has all the REQUIRED info. If it doesn't then we'll set an admin notice with an error message for the user. * * @access private * @return void */ private function _verify_options( $options ) { $this->lang_domain = isset( $options['lang_domain'] ) ? $options['lang_domain'] : ''; $required = array( 'options_page_slug', 'plugin_basename' ); $defaults = array( 'apikey' => NULL, 'checkPeriod' => 12, 'option_key' => 'pue_site_license_key', 'use_wp_download' => FALSE, 'extra_stats' => array() //this is an array of key value pairs for extra stats being tracked. ); //let's first make sure requireds are present foreach ( $required as $key ) { if ( !isset( $options[$key] ) ) $this->_pue_errors[] = $key; } if ( empty( $this->_pue_errors ) ) { $options = array_merge( $defaults, $options ); return $options; } else { $this->_display_errors( 'options' ); return FALSE; } } /** * All this does is verify that if $slug is an array that we have a key in the $options field for 'version_params' that help us determine whether the plugin installed is the premium or freemium version. * Then we set the _installed_version property and the _is_premium property * * @access private * @param array $options already verified options * @param mixed(array|string) $slug if array then we have premium and free options for this plugin * @return bool (false for fail, true for success) */ private function _verify_and_set_installed_version( $slug ) { if ( is_array( $slug ) ) { //We require at LEAST 'premium' index to be present if this is an array if ( !isset( $slug['premium'] ) ) { $this->_display_errors('slug_array_invalid'); return FALSE; } } else { $this->_display_errors('slug_not_array'); return FALSE; } $this->_installed_version = $this->getInstalledVersion(); if ( !$this->_installed_version ) { $this->_display_errors('no_version_present'); return FALSE; } return TRUE; } private function _display_errors( $type ) { $msg = ''; if ( defined('WP_DEBUG') && WP_DEBUG ) { switch ( $type ) { case 'options' : $msg .= sprintf( __('Plugin Update Engine is unable to setup correctly for the plugin with the slug "%s" because there are the following keys missing from the options array sent to the PluginUpdateEngineChecker class when it is instantiated:', $this->lang_domain), print_r( $this->_incoming_slug, true) ) . '</p><p>'; $msg .= '<ul>'; foreach ( $this->_pue_errors as $error ) { $msg .= '<li>' . $error . '</li>'; } $msg .= '</ul>'; break; case 'slug_array_invalid' : $msg .= __('An array was sent to the PluginUpdateEngineChecker class as the value for the $plugin_slug property, however the array is missing the "premium" index.', $this->lang_domain); break; case 'slug_string_invalid' : $msg .= __('A string was sent to the PluginUpdateEngineChecker class as the value for the $plugin_slug property, however the string is empty', $this->lang_domain); break; case 'no_version_present' : $msg .= __('For some reason PUE is unable to determine the current version of the plugin. It is possible that the incorrect value was sent for the "plugin_basename" key in the <strong>$options</strong> array.', $this->lang_domain); break; case 'slug_not_array' : //Old method for plugin name is just to use the slug and manipulate $pluginname = ucwords(str_replace('-', ' ', $this->_incoming_slug) ); $msg .= sprintf( __('The following plugin needs to be updated in order to work with this version of our plugin update script: <strong>%s</strong></p><p>You will have to update this manually. Contact support for further instructions', $this->lang_domain), $pluginname); break; } } else { $slug = $this->slug; if ( empty( $this->slug ) ) { $msg .= sprintf( 'Automatic updates cannot be setup for an EE addon because of an error in the file. Please contact support, and include a list of EE addons recently installed/updated.', $this->lang_domain ) . '</p><p>'; } else { $msg .= sprintf( __('Unable to setup automatic updates for the plugin with the slug "%s" because of an error with the code. Please contact EE support and give them this error message.', $this->lang_domain), $slug ) . '</p><p>'; } } $this->_error_msg = apply_filters('PUE__display_errors', '<p>' . $msg . '</p>', $type, $this->_pue_errors, $this->_incoming_slug); add_action( 'admin_notices', array( $this, 'show_pue_client_errors'), 10 ); } /** * display any pue_client errors * * @access public * @return string html string echoed. */ public function show_pue_client_errors() { ?> <div class="error" style="padding:15px; position:relative;" id="pue_option_error"> <?php echo $this->_error_msg; ?> </div> <?php } /** * Takes care of setting the slug property and the related other properties dependent on the incoming slug var. * * If $slug is an array then we are expecting the array in the following format: * array( * 'free' => 'slug_for_free' //what is sent in the update package to check on the PUE server for the free product * 'premium' => 'slug_for_premium' //what is send in the update package to check on the PUE server for the premium product * ) * * @param mixed (array|string) $slug either an array containing free product slugs or premium product */ private function _set_slug_and_slug_props( $slug, $options ) { $this->pluginFile = $options['plugin_basename']; $this->lang_domain = isset( $options['lang_domain'] ) && !empty($options['lang_domain']) ? $options['lang_domain'] : NULL; //we need to set installed version and set flags for version $verify_version = $this->_verify_and_set_installed_version( $slug ); if ( !$verify_version ) return FALSE; //set other properties related to version //is_premium? $premium_search_ref = is_array($slug) ? key($slug['premium']) : NULL; //case insensitive search in version $this->_is_premium = !empty( $premium_search_ref ) && preg_match( "/$premium_search_ref/i", $this->_installed_version ) ? TRUE : FALSE; //wait... if slug is_string() then we'll assume this is a premium install by default $this->_is_premium = !$this->_is_premium && !is_array( $slug ) ? TRUE : $this->_is_premium; //set pre-release flag $pr_search_ref = is_array($slug) && isset( $slug['prerelease'] ) ? key( $slug['prerelease'] ) : NULL; $this->_is_prerelease = !empty( $pr_search_ref ) && preg_match("/$pr_search_ref/i", $this->_installed_version ) ? TRUE : FALSE; //free_release? $fr_search_ref = is_array($slug) && isset( $slug['free'] ) ? key( $slug['free'] ) : NULL; $this->_is_freerelease = !empty( $fr_search_ref ) && preg_match("/$fr_search_ref/", $this->_installed_version ) ? TRUE : FALSE; //set slug we use $this->slug = $this->_is_premium && is_array( $slug ) ? $slug['premium'][key($slug['premium'])] : NULL; //we handle differently depending on whether the slug is an array or not. if ( is_array( $slug ) ) { //let's go through the conditions on what we use for the slug $set_slug = $this->_is_premium ? $slug['premium'][key($slug['premium'])] : NULL; $set_slug = empty( $set_slug ) && $this->_is_prerelease ? $slug['prerelease'][key($slug['prerelease'])] : $set_slug; $set_slug = empty( $set_slug ) && isset( $slug['free'] ) ? $slug['free'][key($slug['free'])] : $set_slug; } else { //first verify that $slug is not empty! if ( empty($slug ) ) { $this->_display_errors['slug_string_invalid']; return FALSE; } $set_slug = $slug; } $this->slug = $set_slug; //now we've got the slug for the package to get set. //now let's setup other properties based on the slug OR the 'plugin_basename' option. $this->dismiss_upgrade = 'pu_dismissed_upgrade_'.$this->slug; $this->pue_install_key = 'pue_install_key_'.$this->slug; return TRUE; } /** * gets the api from the options table if present **/ function set_api($new_api = '') { //download query flag $this->download_query['pu_get_download'] = 1; //include current version $this->download_query['pue_active_version'] = $this->_installed_version; $this->download_query['site_domain'] = $this->current_domain; //the following is for install key inclusion (will apply later with PUE addons.) $this->install_key_arr = get_site_option($this->pue_install_key); if ( isset($this->install_key_arr['key'] ) ) { $this->install_key = $this->install_key_arr['key']; $this->download_query['pue_install_key'] = $this->install_key; } else { $this->download_query['pue_install_key'] = ''; } if ( !empty($new_api) ) { $this->api_secret_key = $new_api; $this->download_query['pu_plugin_api'] = $this->api_secret_key; return; } if ( empty($new_api) ) { $this->download_query['pu_plugin_api'] = $this->api_secret_key; return; } } /** * Install the hooks required to run periodic update checks and inject update info * into WP data structures. * Also other hooks related to the automatic updates (such as checking agains API and what not (@from Darren) * @return void */ function installHooks(){ //Set up the periodic update checks $cronHook = 'check_plugin_updates-' . $this->slug; if ( $this->checkPeriod > 0 ){ //Trigger the check via Cron if ( !wp_next_scheduled($cronHook) && !defined('WP_INSTALLING') ) { wp_schedule_event(time(), 'daily', $cronHook); } add_action($cronHook, array($this, 'checkForUpdates')); //In case Cron is disabled or unreliable, we also manually trigger //the periodic checks while the user is browsing the Dashboard. add_action( 'init', array($this, 'hook_into_wp_update_api'), 0 ); } else { //Periodic checks are disabled. wp_clear_scheduled_hook($cronHook); } //dashboard message "dismiss upgrade" link add_action( "wp_ajax_".$this->dismiss_upgrade, array($this, 'dashboard_dismiss_upgrade')); if ( ! has_action( "wp_ajax_pue_dismiss_persistent_notice" ) ) { add_action( "wp_ajax_pue_dismiss_persistent_notice", array( $this, 'dismiss_persistent_notice' ) ); } if ( !$this->_use_wp_update ) { add_filter( 'upgrader_pre_install', array( $this, 'pre_upgrade_setup'), 10, 2 ); add_filter( 'upgrader_post_install', array( $this, 'tidy_up_after_upgrade'), 10, 3 ); } } /** * This is where we'll hook in to set filters for handling bulk and regular updates (i.e. making sure directory names are setup properly etc.) * @param boolean $continue return true or WP aborts current upgrade process. * @param array $hook_extra This will contain the plugin basename in a 'plugin' key * @return boolean We always make sure to return true otherwise wp aborts. */ function pre_upgrade_setup( $continue, $hook_extra ) { if ( !empty( $hook_extra['plugin'] ) && $hook_extra['plugin'] == $this->pluginFile ) { //we need to make sure that the new directory is named correctly add_filter('upgrader_source_selection', array( $this, 'fixDirName'), 10, 3 ); } return TRUE; } /** * Tidy's up our plugin upgrade stuff after update is complete so other plugins aren't affected. * * @uses * @param boolean $continue return true so wp doesn't abort. * @param array $hook_extra contains the plugin_basename with the 'plugin' * index which we can use to indicate if this is * where we want our stuff run * @param array $install_result WP sends off all the things that have been done in * an array (post install) * @return boolean if wp_error object is returned then wp aborts. */ function tidy_up_after_upgrade( $continue, $hook_extra, $install_result ) { if ( !empty( $hook_extra['plugin'] ) && $hook_extra['plugin'] == $this->pluginFile ) { //gotta make sure bulk updates for other files don't get messed up!! remove_filter('upgrader_source_selection', array( $this, 'fixDirName'), 10); //maybe clean up any leftover files from upgrades $this->maybe_cleanup_upgrade(); } return true; } /** * This basically is set to fix the directories for our plugins. * * Take incoming remote_source file and rename it to match what it should be. * * @param string $source This is usually the same as $remote_source but *may* be something else if this has already been filtered * @param string $remote_source What WP has set as the source (ee plugins coming from beta.eventespresso.com will be beta.tmp) * @param WPPluginUpgrader $wppu * @return string renamed file and path */ function fixDirName( $source, $remote_source, $wppu ) { global $wp_filesystem; //get out early if this doesn't have a plugin updgrader object. if ( !$wppu instanceof Plugin_Upgrader ) return $source; //if this is a bulk update then we need an alternate method to verify this is an update we need to modify. if ( $wppu->bulk ) { $url_to_check = $wppu->skin->options['url']; $is_good = strpos( $url_to_check, urlencode($this->pluginFile) ) === FALSE ? FALSE : TRUE; } else { $is_good = isset( $wppu->skin->plugin ) && $wppu->skin->plugin == $this->pluginFile ? TRUE : FALSE; } if ( $is_good ) { $new_dir = $wp_filesystem->wp_content_dir() . 'upgrade/' . $this->slug . '/'; //make new directory if needed. if ( $wp_filesystem->exists( $new_dir ) ) { //delete the existing dir first because we want to make sure clean install $wp_filesystem->delete($new_dir, FALSE, 'd'); } //now make sure that we DON'T have the directory and we'll create a new one for this. if ( ! $wp_filesystem->exists( $new_dir ) ) { if ( !$wp_filesystem->mkdir( $new_dir, FS_CHMOD_DIR ) ) return new WP_Error( 'mkdir_failed_destination', $wppu->strings['mkdir_failed'], $new_dir ); } //copy original $source into new source $result = copy_dir( $source, $new_dir ); if ( is_wp_error($result ) ) { //something went wrong let's just return the original $source as a fallback. return $source; } //everything went okay... new source = new dir $source = $new_dir; } return $source; } function hook_into_wp_update_api() { $this->set_api(); $this->maybeCheckForUpdates(); $ver_option_key = 'puvererr_' . basename( $this->pluginFile ); //possible update checks on an option page save that is setting the license key. Note we're not actually using the response yet for this triggered update check but we might at some later date. $triggered = $this->trigger_update_check(); //if we've got a forced premium upgrade then let's add an admin notice for this with a nice button to do the upgrade right away. We'll also handle the display of any json errors in this admin_notice. if ( $this->_force_premium_upgrade ) { add_action('admin_notices', array($this, 'show_premium_upgrade') ); } //this injects info into the returned Plugin info popup but we ONLY inject if we're not doing wp_updates $this->json_error = $this->get_json_error_string(); if ( ! $this->_use_wp_update ) { add_filter('plugins_api', array( $this, 'injectInfo' ), 10, 3); //Insert our update info into the update array maintained by WP add_filter('site_transient_update_plugins', array( $this,'injectUpdate' )); } add_action( 'admin_notices', array( $this, 'maybe_display_extra_notices' ) ); if ( ! $this->_use_wp_update ) { if ( !empty($this->json_error) && !$this->_force_premium_upgrade ) { add_action('admin_notices', array($this, 'display_json_error'), 10, 3); } else if ( empty( $this->json_error ) ) { //no errors so let's get rid of any error option if present BUT ONLY if there are no json_errors! delete_site_option( $ver_option_key ); } } } function get_json_error_string() { $option_name = substr( 'pue_json_error_' . $this->pluginFile, 0, 40 ); return get_site_option( $option_name ); } function set_json_error_string( $error_message ) { $option_name = substr( 'pue_json_error_' . $this->pluginFile, 0, 40 ); update_site_option( $option_name, $error_message ); } function delete_json_error_string() { $option_name = substr( 'pue_json_error_' . $this->pluginFile, 0, 40 ); delete_site_option( $option_name ); } function maybe_cleanup_upgrade() { global $wp_filesystem; $chk_file = WP_CONTENT_DIR . '/upgrade/' . $this->slug . '/'; if ( is_readable($chk_file ) ) { if ( !is_object( $wp_filesystem ) ) { require_once( ABSPATH . '/wp-admin/includes/file.php'); WP_Filesystem(); } $wp_filesystem->delete($chk_file, FALSE, 'd'); } } function trigger_update_check() { //we're just using this to trigger a PUE ping whenever an option matching the given $this->option_key is saved.. $has_triggered = FALSE; if ( !empty($_POST) && !empty( $this->option_key ) ) { foreach ( $_POST as $key => $value ) { $triggered = $this->maybe_trigger_update($value, $key, $this->option_key); $has_triggered = $triggered && !$has_triggered ? TRUE : $has_triggered; } } return $has_triggered; } function maybe_trigger_update($value, $key, $site_key_search_string) { if ( $key == $site_key_search_string || (is_array($value) && isset($value[$site_key_search_string]) ) ) { //if $site_key_search_string exists but the actual key field is empty...let's reset the install key as well. if ( $value == '' || ( is_array($value) && empty($value[$site_key_search_string] ) ) || $value != $this->api_secret_key || ( is_array($value) && $value[$site_key_search_string] != $this->api_secret_key ) ) delete_site_option($this->pue_install_key); $this->api_secret_key = $value; $this->set_api($this->api_secret_key); //reset force_upgrade flag (but only if there's a free slug key) if ( !empty( $this->_incoming_slug['free'] ) ) delete_site_option( 'pue_force_upgrade_' . $this->_incoming_slug['free'][key($this->_incoming_slug['free'])]); //now let's reset some flags if necessary? in other words IF the user has entered a premium key and the CURRENT version is a free version (NOT a prerelease version) then we need to make sure that we ping for the right version $free_key_match = '/FREE/i'; //if this condition matches then that means we've got a free active key in place (or a free version from wp WITHOUT an active key) and the user has entered a NON free API key which means they intend to check for premium access. if ( !preg_match( $free_key_match, $this->api_secret_key ) && !empty($this->api_secret_key) && !$this->_is_premium && !$this->_is_prerelease && $this->_is_freerelease ) { $this->_use_wp_update = FALSE; $this->slug = $this->_incoming_slug['premium'][key($this->_incoming_slug['premium'])]; $this->_is_premium = TRUE; $this->_force_premium_upgrade = TRUE; $this->pue_install_key = 'pue_install_key_'.$this->slug; $this->optionName = 'external_updates-' . $this->slug; if ( isset( $this->_incoming_slug['free'] ) ) update_site_option( 'pue_force_upgrade_' . $this->_incoming_slug['free'][key($this->_incoming_slug['free'])], $this->slug ); } $this->checkForUpdates(); return true; } return false; } /** * Retrieve plugin info from the configured API endpoint. * * @uses wp_remote_get() * * @param array $queryArgs Additional query arguments to append to the request. Optional. * @return $pluginInfo */ function requestInfo($queryArgs = array()){ //Query args to append to the URL. Plugins can add their own by using a filter callback (see addQueryArgFilter()). $queryArgs['pu_request_plugin'] = $this->slug; if ( !empty($this->api_secret_key) ) $queryArgs['pu_plugin_api'] = $this->api_secret_key; if ( ! empty($this->install_key) && $this->_is_premium ) $queryArgs['pue_install_key'] = $this->install_key; //todo: this can be removed in a later version of PUE when majority of EE users are using more recent versions. $queryArgs['new_pue_chk'] = 1; //include version info $queryArgs['pue_active_version'] = $this->_installed_version; //include domain info $queryArgs['site_domain'] = $this->current_domain; $queryArgs = apply_filters('puc_request_info_query_args-'.$this->slug, $queryArgs); //Various options for the wp_remote_get() call. Plugins can filter these, too. $options = array( 'timeout' => 10, //seconds 'headers' => array( 'Accept' => 'application/json' ), ); $options = apply_filters('puc_request_info_options-'.$this->slug, $options); $url = $this->metadataUrl; if ( !empty($queryArgs) ){ $url = add_query_arg($queryArgs, $url); } $result = wp_remote_get( $url, $options ); $this->_send_extra_stats(); //we'll trigger an extra stats update here. //Try to parse the response $pluginInfo = null; //any special notices in the return package? if ( ! is_wp_error( $result ) && isset( $result['body'] ) ) { $response = json_decode( $result['body'] ); if ( isset( $response->extra_notices ) ) { $this->add_persistent_notice( $response->extra_notices ); } } if ( !is_wp_error($result) && isset($result['response']['code']) && ($result['response']['code'] == 200) && !empty($result['body']) ){ $pluginInfo = PU_PluginInfo::fromJson($result['body']); } $pluginInfo = apply_filters('puc_request_info_result-'.$this->slug, $pluginInfo, $result); return $pluginInfo; } /** * Utility method for adding a persistent notice to users admin. * * @param array $message Expect an array of ['error'], ['attention'], ['success'] notices to add to the persistent * array. * @param bool $overwrite Whether to force overwriting existing notices or just append to any existing notices * (default). */ protected function add_persistent_notice( $message, $overwrite = false ) { //renewal notices are only saved ONCE per version update and we only do this for plugins that have "turned on" // notice saves (typically the main plugin). if ( ! $this->turn_on_notice_saves ) { return; } //get existing notices $notice_prefix = 'pue_special_notices_'; $notice_ref = $notice_prefix . $this->_installed_version; $existing_notices = get_option( $notice_ref, array() ); //if we don't have existing notices for the current plugin version then let's just make sure all older notices //are removed from the db. if ( empty( $existing_notices ) ) { global $wpdb; $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->options WHERE option_name LIKE '%s'", '%' . $notice_prefix . '%' ) ); } //k make sure there are no existing notices matching the incoming notices and only append new notices (unless overwrite is set to true). foreach ( (array) $message as $notice_type => $notices ) { if ( isset( $existing_notices[$notice_type] ) && ! $overwrite ) { foreach ( (array) $notices as $notice_id => $notice ) { if ( empty( $notice ) || ( isset( $existing_notices[$notice_type][$notice_id] ) && ! $existing_notices[$notice_type][$notice_id]['active'] ) ) { //first let's check the message (if not empty) and if it matches what's already present then we continue, otherwise we replace and make active. if ( ! empty( $notice ) && $existing_notices[$notice_type][$notice_id]['msg'] && $existing_notices[$notice_type][$notice_id]['msg'] != $notice ) { $existing_notices[$notice_type][$notice_id]['msg'] = $notice; $existing_notices[$notice_type][$notice_id]['active'] = 1; } continue; } else { $existing_notices[$notice_type][$notice_id]['msg'] = $notice; $existing_notices[$notice_type][$notice_id]['active'] = 1; } } } else { foreach ( (array) $notices as $notice_id => $notice ) { if ( ! empty( $notice ) ) { $existing_notices[$notice_type][$notice_id]['msg'] = $notice; $existing_notices[ $notice_type ][ $notice_id ]['active'] = 1; } } } } //update notices option update_option( $notice_ref, $existing_notices ); } /** * This basically dismisses all persistent notices of a given type (note this only dismisses the notice for the * duration of the current plugins version * */ public function dismiss_persistent_notice() { //if no $type in the request then exit $type = isset( $_REQUEST['type'] ) ? $_REQUEST['type'] : null; if ( empty( $type ) ) { return; } $notice_ref = 'pue_special_notices_' . $this->_installed_version; $existing_notices = get_option( $notice_ref, array() ); if ( isset( $existing_notices[$type] ) ) { foreach ( $existing_notices[$type] as $notice_id => $details ) { $existing_notices[$type][$notice_id]['active'] = 0; } } update_option( $notice_ref, $existing_notices ); } /** * This method determines whether or not to display extra notices that might have come back from the request. */ public function maybe_display_extra_notices() { //nothing should happen if this plugin doesn't save extra notices if ( ! $this->turn_on_notice_saves || ! is_main_site() ) { return; } //okay let's get any extra notices $notices = get_option( 'pue_special_notices_' . $this->_installed_version, array() ); //setup the message content for each notice; $errors = $attentions = $successes = ''; foreach ( $notices as $type => $notes ) { switch( $type ) { case 'error' : foreach ( (array) $notes as $noteref ) { if ( ! $noteref['active'] || empty( $noteref['msg'] ) ) { continue; } $errors .= '<p>' . trim( stripslashes( $noteref['msg'] ) ) . '</p>'; } break; case 'attention' : foreach ( (array) $notes as $noteref ) { if ( ! $noteref['active'] || empty( $noteref['msg'] ) ) { continue; } $attentions .= '<p>' . trim( stripslashes( $noteref['msg'] ) ) . '</p>'; } break; case 'success' : foreach ( (array) $notes as $noteref ) { if ( ! $noteref['active'] || empty( $noteref['msg'] ) ) { continue; } $successes .= '<p>' . trim( stripslashes( $noteref['msg'] ) ) . '</p>'; } break; } } //now let's setup the containers but only if we HAVE message to use :) if ( empty( $errors ) && empty( $attentions ) && empty( $successes ) ) { return ''; } $content = ''; if ( !empty( $errors ) ) { ob_start(); ?> <div class="error" id="pue_error_notices"> <?php echo $this->_sanitize_notices( $errors ); ?> <a class="button-secondary" href="javascript:void(0);" onclick="PUEDismissNotice( 'error' );" style="float:right; margin-bottom: 10px;"> <?php _e("Dismiss"); ?> </a> <div style="clear:both"></div> </div> <?php $content .= ob_get_contents(); ob_end_clean(); } if ( !empty( $attentions ) ) { ob_start(); ?> <div class="notice notice-info" id="pue_attention_notices"> <?php echo $this->_sanitize_notices( $attentions ); ?> <a class="button-secondary" href="javascript:void(0);" onclick="PUEDismissNotice( 'attention' );" style="float:right; margin-bottom: 10px;"> <?php _e("Dismiss"); ?> </a> <div style="clear:both"></div> </div> <?php $content .= ob_get_contents(); ob_end_clean(); } if ( !empty( $successes ) ) { ob_start(); ?> <div class="success" id="pue_success_notices"> <?php echo $this->_sanitize_notices( $successes ); ?> <a class="button-secondary" href="javascript:void(0);" onclick="PUEDismissNotice( 'success' );" style="float:right; margin-bottom: 10px;"> <?php _e("Dismiss"); ?> </a> <div style="clear:both"></div> </div> <?php $content .= ob_get_contents(); ob_end_clean(); } //add inline script for dismissing notice ob_start(); ?> <script type="text/javascript"> function PUEDismissNotice( type ){ jQuery("#pue_" + type + "_notices").slideUp(); jQuery.post(ajaxurl, {action:"pue_dismiss_persistent_notice", type:type, cookie: encodeURIComponent(document.cookie)}); } </script> <?php $content .= ob_get_contents(); ob_end_clean(); echo $content; } private function _send_extra_stats() { //first if we don't have a stats array then lets just get out. if ( empty( $this->extra_stats) ) return; //set up args sent in body $body = array( 'extra_stats' => $this->extra_stats, 'user_api_key' => $this->api_secret_key, 'pue_stats_request' => 1, 'domain' => $this->current_domain, 'pue_plugin_slug' => $this->slug, 'pue_plugin_version' => $this->getInstalledVersion() ); //setup up post args $args = array( 'timeout' => 10, 'blocking' => TRUE, 'user-agent' => 'PUE-stats-carrier', 'body' => $body, 'sslverify' => FALSE ); wp_remote_post($this->metadataUrl, $args); } /** * Retrieve the latest update (if any) from the configured API endpoint. * * @uses PluginUpdateEngineChecker::requestInfo() * * @return PluginUpdateUtility An instance of PluginUpdateUtility, or NULL when no updates are available. */ function requestUpdate(){ //For the sake of simplicity, this function just calls requestInfo() //and transforms the result accordingly. $pluginInfo = $this->requestInfo(array('pu_checking_for_updates' => '1')); $this->delete_json_error_string(); if ( $pluginInfo == null ){ return null; } //admin display for if the update check reveals that there is a new version but the API key isn't valid. if ( isset($pluginInfo->api_invalid) ) { //we have json_error returned let's display a message $this->json_error = $pluginInfo; $this->set_json_error_string( $this->json_error ); return $this->json_error; } if ( isset($pluginInfo->new_install_key) ) { $this->install_key_arr['key'] = $pluginInfo->new_install_key; update_site_option($this->pue_install_key, $this->install_key_arr); } //need to correct the download url so it contains the custom user data (i.e. api and any other paramaters) //oh let's generate the download_url otherwise it will be old news... if ( !empty($this->download_query) ) { $d_install_key = $this->install_key_arr['key']; $this->download_query['pue_install_key'] = $d_install_key; $this->download_query['new_pue_check'] = 1; $pluginInfo->download_url = add_query_arg($this->download_query, $pluginInfo->download_url); } return PluginUpdateUtility::fromPluginInfo($pluginInfo); } function in_plugin_update_message($plugin_data) { $plugininfo = $this->json_error; //only display messages if there is a new version of the plugin. if ( is_object($plugininfo) ) { if ( version_compare($plugininfo->version, $this->_installed_version, '>') ) { if ( $plugininfo->api_invalid ) { $msg = str_replace('%plugin_name%', $this->pluginName, $plugininfo->api_inline_invalid_message); $msg = str_replace('%version%', $plugininfo->version, $msg); $msg = str_replace('%changelog%', '<a class="thickbox" title="'.$this->pluginName.'" href="plugin-install.php?tab=plugin-information&plugin='.$this->slug.'&TB_iframe=true&width=640&height=808">What\'s New</a>', $msg); echo '</tr><tr class="plugin-update-tr"><td colspan="3" class="plugin-update"><div class="update-message">' . $this->_sanitize_notices( $msg ) . '</div></td>'; } } } } function display_changelog() { //todo (at some point in the future!) contents of changelog display page when api-key is invalid or missing. It will ONLY show the changelog (hook into existing thickbox?) } function display_json_error($echo = TRUE, $ignore_version_check = FALSE, $alt_content = '') { $pluginInfo = $this->json_error; $update_dismissed = get_site_option($this->dismiss_upgrade); $ver_option_key = 'puvererr_' . basename( $this->pluginFile ); $msg = ''; $is_dismissed = !empty($update_dismissed) && in_array($pluginInfo->version, $update_dismissed) ? true : false; //add in pue_verification_error option for when the api_key is blank if ( empty( $this->api_secret_key ) ) { update_site_option( $ver_option_key, __('No API key is present', $this->lang_domain) ); } if ( $pluginInfo->api_invalid ) { $msg = str_replace('%plugin_name%', $this->pluginName, $pluginInfo->api_invalid_message); $msg = str_replace('%version%', $pluginInfo->version, $msg); } //let's add an option for plugin developers to display some sort of verification message on their options page. update_site_option( $ver_option_key, $msg ); if ($is_dismissed) return; //only display messages if there is a new version of the plugin. if ( version_compare($pluginInfo->version, $this->_installed_version, '>') || $ignore_version_check ) { //Dismiss code idea below is obtained from the Gravity Forms Plugin by rocketgenius.com ob_start(); ?> <div class="updated" style="padding:15px; position:relative;" id="pu_dashboard_message"><?php echo $this->_sanitize_notices( $msg ); ?> <a class="button-secondary" href="javascript:void(0);" onclick="PUDismissUpgrade();" style='float:right;'><?php _e("Dismiss") ?></a> <div style="clear:both;"></div> </div> <script type="text/javascript"> function PUDismissUpgrade(){ jQuery("#pu_dashboard_message").slideUp(); jQuery.post(ajaxurl, {action:"<?php echo $this->dismiss_upgrade; ?>", version:"<?php echo $pluginInfo->version; ?>", cookie: encodeURIComponent(document.cookie)}); } </script> <?php $content = ob_get_contents(); ob_end_clean(); if ( $echo !== FALSE ) echo $content; else return $content; } } /** * This just receives a content string and uses wp_kses to sanitize the incoming string so it only allows a small * subset of tags. * * @param string $content Content to sanitize * @return string */ protected function _sanitize_notices( $content ) { $allowed_tags = array( 'a' => array( 'href' => array(), 'title' => array() ), 'br' => array(), 'em' => array(), 'strong' => array(), 'abbr' => array(), 'acronym' => array(), 'b' => array(), 'blockquote' => array(), 'cite' => array(), 'code' => array(), 'strike' => array(), 'ol' => array(), 'ul' => array(), 'li' => array(), 'p' => array() ); return wp_kses( $content, $allowed_tags ); } /** * This admin_notice shows a message immediately to users who have successfully entered a valid api_key and allows them to click a button to get the premium version. * Note: we'll alternatively display any json errors that may be present from the returned package. * * @access public * @return string html */ public function show_premium_upgrade() { global $current_screen; $ver_option_key = 'puvererr_' . basename( $this->pluginFile ); if ( empty( $current_screen ) ) set_current_screen(); //check if we're on the wp update page. If so get out if ( $current_screen->id == 'update' ) return; $update_dismissed = get_site_option($this->dismiss_upgrade); $is_dismissed = !empty($update_dismissed) && !empty( $this->json_error ) && in_array( $this->json_error->version, $update_dismissed ) ? true : false; //first any json errors? if ( !empty( $this->json_error ) && isset($this->json_error->api_invalid) ) { if ( $is_dismissed ) return; $msg = str_replace('%plugin_name%', $this->pluginName, $this->json_error->api_invalid_message); $msg = str_replace('%version%', $this->json_error->version, $msg); $msg = sprintf( __('It appears you\'ve tried entering an api key to upgrade to the premium version of %s, however, the key does not appear to be valid. This is the message received back from the server:', $this->lang_domain ), $this->pluginName ) . '</p><p>' . $msg; //let's add an option for plugin developers to display some sort of verification message on their options page. update_site_option( $ver_option_key, $msg ); } else { $msg = sprintf( __('Congratulations! You have entered in a valid api key for the premium version of %s. You can click the button below to upgrade to this version immediately.', $this->lang_domain), $this->pluginName ); delete_site_option( $ver_option_key ); } //todo add in upgrade button in here. $button_link = wp_nonce_url( self_admin_url('update.php?action=upgrade-plugin&plugin=') . $this->pluginFile, 'upgrade-plugin_' . $this->pluginFile ); $button = '<a href="' . $button_link . '" class="button-secondary pue-upgrade-now-button" value="no">' . __('Upgrade Now', $this->lang_domain) . '</a>'; $content = '<div class="updated" style="padding:15px; position:relative;" id="pue_update_now_container"><p>' . $msg . '</p>'; $content .= empty($this->json_error) ? $button : ''; $content .= '<a class="button-secondary" href="javascript:void(0);" onclick="PUDismissUpgrade();" style="float:right;">' . __("Dismiss") . '</a>'; $content .= '<div style="clear:both;"></div></div>'; $content .= '<script type="text/javascript"> function PUDismissUpgrade(){ jQuery("#pue_update_now_container").slideUp(); jQuery.post( ajaxurl, {action:"' . $this->dismiss_upgrade .'", version:"' . $this->json_error->version . '", cookie: encodeURIComponent(document.cookie)}); } </script>'; echo $content; } function dashboard_dismiss_upgrade() { $os_ary = get_site_option($this->dismiss_upgrade); if (!is_array($os_ary)) $os_ary = array(); $os_ary[] = $_POST['version']; update_site_option($this->dismiss_upgrade, $os_ary); } /** * Get the currently installed version of the plugin. * * @return string Version number. */ function getInstalledVersion(){ if ( function_exists('get_plugin_data') ) { $plugin_data = get_plugin_data( WP_PLUGIN_DIR . DIRECTORY_SEPARATOR . $this->pluginFile); } else { require_once(ABSPATH.'wp-admin/includes/plugin.php'); $plugin_data = get_plugin_data( WP_PLUGIN_DIR . DIRECTORY_SEPARATOR . $this->pluginFile); } if ( !empty($plugin_data) ) { $this->pluginName = $plugin_data['Name']; $this->lang_domain = empty( $this->lang_domain ) && !empty($plugin_data['TextDomain']) ? $plugin_data['TextDomain'] : $this->lang_domain; return $plugin_data['Version']; } return FALSE; //this should never happen } /** * Check for plugin updates. * The results are stored in the DB option specified in $optionName. * * @return void */ function checkForUpdates(){ $state = get_site_option($this->optionName); if ( empty($state) ){ $state = new StdClass; $state->lastCheck = 0; $state->checkedVersion = ''; $state->update = null; } $state->lastCheck = time(); $state->checkedVersion = $this->_installed_version; update_site_option($this->optionName, $state); //Save before checking in case something goes wrong $state->update = $this->requestUpdate(); update_site_option($this->optionName, $state); } /** * Check for updates only if the configured check interval has already elapsed. * * @return void */ function maybeCheckForUpdates(){ if ( !is_admin() ) return; if ( empty($this->checkPeriod) ){ return; } $state = get_site_option($this->optionName); $shouldCheck = empty($state) || !isset($state->lastCheck) || ( (time() - $state->lastCheck) >= $this->checkPeriod*3600 ); //$shouldCheck = true; if ( $shouldCheck ){ $this->checkForUpdates(); } } /** * Intercept plugins_api() calls that request information about our plugin and * use the configured API endpoint to satisfy them. * * @see plugins_api() * * @param mixed $result * @param string $action * @param array|object $args * @return mixed */ function injectInfo($result, $action = null, $args = null){ $updates = FALSE; $relevant = ($action == 'plugin_information') && isset($args->slug) && ($args->slug == $this->slug); if ( !$relevant ){ return $result; } $state = get_site_option($this->optionName); if( !empty($state) && isset($state->update) ) { $state->update->name = $this->pluginName; $result = PU_PluginInfo::fromJson($state->update,true);; $updates = $result->toWpFormat(); } if ( $updates ) return $updates; else return $result; } /** * Insert the latest update (if any) into the update list maintained by WP. * We do two things in here: * 1. insert OUR update if there is an update available (and replace any existing WP one) * 2. remove the existing WP one if it exists even if we dont' have an update. This covers the cases where there may be a ping from WP before EE and we've got a premium plugin installed that MATCHES one in the WP db. * * @param array $updates Update list created by WordPress. * @return array Modified update list. */ function injectUpdate( $updates ){ $state = get_site_option($this->optionName); //first remove any existing WP update message that might have snuck in before we have any return from our plugin server. if ( isset( $updates->response[$this->pluginFile] ) ) unset( $updates->response[$this->pluginFile] ); //Is there an update to insert? if ( !empty($state) && isset($state->update) && !empty($state->update) ){ //Only insert updates that are actually newer than the currently installed version. if ( version_compare($state->update->version, $this->_installed_version, '>') ){ $updated = $state->update->toWPFormat(); $updated->plugin = $this->pluginFile; $updates->response[$this->pluginFile] = $updated; } } add_action('after_plugin_row_'.$this->pluginFile, array($this, 'in_plugin_update_message')); if ( $this->json_error ) remove_action('after_plugin_row_'.$this->pluginFile, 'wp_plugin_update_row', 10, 2); return $updates; } /** * Register a callback for filtering query arguments. * * The callback function should take one argument - an associative array of query arguments. * It should return a modified array of query arguments. * * @uses add_filter() This method is a convenience wrapper for add_filter(). * * @param callback $callback * @return void */ function addQueryArgFilter($callback){ add_filter('puc_request_info_query_args-'.$this->slug, $callback); } /** * Register a callback for filtering arguments passed to wp_remote_get(). * * The callback function should take one argument - an associative array of arguments - * and return a modified array or arguments. See the WP documentation on wp_remote_get() * for details on what arguments are available and how they work. * * @uses add_filter() This method is a convenience wrapper for add_filter(). * * @param callback $callback * @return void */ function addHttpRequestArgFilter($callback){ add_filter('puc_request_info_options-'.$this->slug, $callback); } /** * Register a callback for filtering the plugin info retrieved from the external API. * * The callback function should take two arguments. If the plugin info was retrieved * successfully, the first argument passed will be an instance of PU_PluginInfo. Otherwise, * it will be NULL. The second argument will be the corresponding return value of * wp_remote_get (see WP docs for details). * * The callback function should return a new or modified instance of PU_PluginInfo or NULL. * * @uses add_filter() This method is a convenience wrapper for add_filter(). * * @param callback $callback * @return void */ function addResultFilter($callback){ add_filter('puc_request_info_result-'.$this->slug, $callback, 10, 2); } } endif; if ( !class_exists('PU_PluginInfo') ): /** * A container class for holding and transforming various plugin metadata. * @version 1.1 * @access public */ class PU_PluginInfo { //Most fields map directly to the contents of the plugin's info.json file. public $name; public $slug; public $version; public $homepage; public $sections; public $download_url; public $author; public $author_homepage; public $requires; public $tested; public $upgrade_notice; public $rating; public $num_ratings; public $downloaded; public $last_updated; public $render_pass; public $id = 0; //The native WP.org API returns numeric plugin IDs, but they're not used for anything. /** * Create a new instance of PU_PluginInfo from JSON-encoded plugin info * returned by an external update API. * * @param string $json Valid JSON string representing plugin info. * @return PU_PluginInfo New instance of PU_PluginInfo, or NULL on error. */ public static function fromJson($json, $object = false){ $apiResponse = (!$object) ? json_decode($json) : $json; if ( empty($apiResponse) || !is_object($apiResponse) ){ return null; } //Very, very basic validation. $valid = (isset($apiResponse->name) && !empty($apiResponse->name) && isset($apiResponse->version) && !empty($apiResponse->version)) || (isset($apiResponse->api_invalid) || isset($apiResponse->no_api)); if ( !$valid ){ return null; } $info = new PU_PluginInfo(); foreach(get_object_vars($apiResponse) as $key => $value){ $key = str_replace('plugin_', '', $key); //let's strip out the "plugin_" prefix we've added in plugin-updater-classes. $info->$key = $value; } return $info; } /** * Transform plugin info into the format used by the native WordPress.org API * * @return object */ public function toWpFormat(){ $info = new StdClass; //The custom update API is built so that many fields have the same name and format //as those returned by the native WordPress.org API. These can be assigned directly. $sameFormat = array( 'name', 'slug', 'version', 'requires', 'tested', 'rating', 'upgrade_notice', 'num_ratings', 'downloaded', 'homepage', 'last_updated', ); foreach($sameFormat as $field){ if ( isset($this->$field) ) { $info->$field = $this->$field; } } //Other fields need to be renamed and/or transformed. $info->download_link = $this->download_url; if ( !empty($this->author_homepage) ){ $info->author = sprintf('<a href="%s">%s</a>', $this->author_homepage, $this->author); } else { $info->author = $this->author; } if ( is_object($this->sections) ){ $info->sections = get_object_vars($this->sections); } elseif ( is_array($this->sections) ) { $info->sections = $this->sections; } else { $info->sections = array('description' => ''); } $this->slug = ! empty( $this->slug ) ? $this->slug : ''; return $info; } } endif; if ( !class_exists('PluginUpdateUtility') ): /** * A simple container class for holding information about an available update. * * @version 1.1 * @access public */ class PluginUpdateUtility { public $id = 0; public $slug; public $version; public $homepage; public $download_url; public $sections = array(); public $upgrade_notice; /** * Create a new instance of PluginUpdateUtility from its JSON-encoded representation. * * @param string $json * @return PluginUpdateUtility */ public static function fromJson($json){ //Since update-related information is simply a subset of the full plugin info, //we can parse the update JSON as if it was a plugin info string, then copy over //the parts that we care about. $pluginInfo = PU_PluginInfo::fromJson($json); if ( $pluginInfo != null ) { return PluginUpdateUtility::fromPluginInfo($pluginInfo); } else { return null; } } /** * Create a new instance of PluginUpdateUtility based on an instance of PU_PluginInfo. * Basically, this just copies a subset of fields from one object to another. * * @param PU_PluginInfo $info * @return PluginUpdateUtility */ public static function fromPluginInfo($info){ $update = new PluginUpdateUtility(); $copyFields = array('id', 'slug', 'version', 'homepage', 'download_url', 'upgrade_notice', 'sections'); foreach($copyFields as $field){ $update->$field = $info->$field; } return $update; } /** * Transform the update into the format used by WordPress native plugin API. * * @return object */ public function toWpFormat(){ $update = new StdClass; $update->id = $this->id; $update->slug = $this->slug; $update->new_version = $this->version; $update->url = $this->homepage; $update->package = $this->download_url; if ( !empty($this->upgrade_notice) ){ $update->upgrade_notice = $this->upgrade_notice; } return $update; } } endif;
gpl-2.0
mgratch/metroinvestments
wp-content/plugins/facetwp/templates/page-settings.php
19207
<?php global $wpdb; // Translations $i18n = array( 'All post types' => __( 'All post types', 'fwp' ), 'Indexing complete' => __( 'Indexing complete', 'fwp' ), 'Indexing' => __( 'Indexing', 'fwp' ), 'Saving' => __( 'Saving', 'fwp' ), 'Loading' => __( 'Loading', 'fwp' ), 'Importing' => __( 'Importing', 'fwp' ), 'Activating' => __( 'Activating', 'fwp' ), 'Are you sure?' => __( 'Are you sure?', 'fwp' ), 'Select some items' => __( 'Select some items', 'fwp' ), ); // An array of facet type objects $facet_types = FWP()->helper->facet_types; // Get taxonomy list $taxonomies = get_taxonomies( array(), 'object' ); // Get post types & taxonomies for the Query Builder $builder_taxonomies = array(); foreach ( $taxonomies as $tax ) { $builder_taxonomies[ $tax->name ] = $tax->labels->singular_name; } $builder_post_types = array(); $post_types = get_post_types( array( 'public' => true ), 'objects' ); foreach ( $post_types as $type ) { $builder_post_types[ $type->name ] = $type->labels->name; } // Clone facet settings HTML $facet_clone = array(); foreach ( $facet_types as $name => $class ) { $facet_clone[ $name ] = __( 'This facet type has no additional settings.', 'fwp' ); if ( method_exists( $class, 'settings_html' ) ) { ob_start(); $class->settings_html(); $facet_clone[ $name ] = ob_get_clean(); } } // Activation status $message = __( 'Not yet activated', 'fwp' ); $activation = get_option( 'facetwp_activation' ); if ( ! empty( $activation ) ) { $activation = json_decode( $activation ); if ( 'success' == $activation->status ) { $message = __( 'License active', 'fwp' ); $message .= ' (' . __( 'expires', 'fwp' ) . ' ' . date( 'M j, Y', strtotime( $activation->expiration ) ) . ')'; } else { $message = $activation->message; } } // Settings $settings = FWP()->helper->settings; // Export feature $export = array(); foreach ( $settings['facets'] as $facet ) { $export['facet-' . $facet['name']] = 'Facet - ' . $facet['label']; } foreach ( $settings['templates'] as $template ) { $export['template-' . $template['name']] = 'Template - '. $template['label']; } // Data sources $sources = FWP()->helper->get_data_sources(); ?> <script src="<?php echo FACETWP_URL; ?>/assets/js/src/event-manager.js?ver=<?php echo FACETWP_VERSION; ?>"></script> <script src="<?php echo FACETWP_URL; ?>/assets/js/src/query-builder.js?ver=<?php echo FACETWP_VERSION; ?>"></script> <script src="<?php echo FACETWP_URL; ?>/assets/js/fSelect/fSelect.js?ver=<?php echo FACETWP_VERSION; ?>"></script> <?php foreach ( $facet_types as $class ) { $class->admin_scripts(); } ?> <script src="<?php echo FACETWP_URL; ?>/assets/js/admin.js?ver=<?php echo FACETWP_VERSION; ?>"></script> <script> FWP.i18n = <?php echo json_encode( $i18n ); ?>; FWP.nonce = '<?php echo wp_create_nonce( 'fwp_admin_nonce' ); ?>'; FWP.settings = <?php echo json_encode( $settings ); ?>; FWP.clone = <?php echo json_encode( $facet_clone ); ?>; FWP.builder = { post_types: <?php echo json_encode( $builder_post_types ); ?>, taxonomies: <?php echo json_encode( $builder_taxonomies ); ?> }; </script> <link href="<?php echo FACETWP_URL; ?>/assets/css/admin.css?ver=<?php echo FACETWP_VERSION; ?>" rel="stylesheet"> <link href="<?php echo FACETWP_URL; ?>/assets/js/fSelect/fSelect.css?ver=<?php echo FACETWP_VERSION; ?>" rel="stylesheet"> <div class="facetwp-header"> <span class="facetwp-logo" title="FacetWP">&nbsp;</span> <span class="facetwp-header-nav"> <a class="facetwp-tab" rel="welcome"><?php _e( 'Welcome', 'fwp' ); ?></a> <a class="facetwp-tab" rel="facets"><?php _e( 'Facets', 'fwp' ); ?></a> <a class="facetwp-tab" rel="templates"><?php _e( 'Templates', 'fwp' ); ?></a> <a class="facetwp-tab" rel="settings"><?php _e( 'Settings', 'fwp' ); ?></a> <a class="facetwp-tab" rel="support"><?php _e( 'Support', 'fwp' ); ?></a> </span> </div> <div class="wrap"> <div class="facetwp-response"></div> <div class="facetwp-loading"></div> <!-- Welcome tab --> <div class="facetwp-region facetwp-region-welcome about-wrap"> <h1><?php _e( 'Welcome to FacetWP', 'fwp' ); ?> <span class="version"><?php echo FACETWP_VERSION; ?></span></h1> <div class="about-text">Thank you for choosing FacetWP. Check out our intro video.</div> <a href="https://facetwp.com/documentation/getting-started/" target="_blank"> <img src="https://i.imgur.com/U4ko9Eh.png" width="575" height="323" /> </a> </div> <!-- Facets tab --> <div class="facetwp-region facetwp-region-facets"> <div class="flexbox"> <div class="left-side"> <span class="btn-wrap"> <a class="button facetwp-add"><?php _e( 'Add New', 'fwp' ); ?></a> </span> <span class="btn-wrap hidden"> <a class="button facetwp-back"><?php _e( 'Back', 'fwp' ); ?></a> </span> </div> <div class="right-side"> <a class="button facetwp-rebuild"><?php _e( 'Re-index', 'fwp' ); ?></a> <a class="button-primary facetwp-save"><?php _e( 'Save Changes', 'fwp' ); ?></a> </div> </div> <div class="facetwp-content-wrap"> <ul class="facetwp-cards"></ul> <div class="facetwp-content"></div> </div> </div> <!-- Templates tab --> <div class="facetwp-region facetwp-region-templates"> <div class="flexbox"> <div class="left-side"> <span class="btn-wrap"> <a class="button facetwp-add"><?php _e( 'Add New', 'fwp' ); ?></a> </span> <span class="btn-wrap hidden"> <a class="button facetwp-back"><?php _e( 'Back', 'fwp' ); ?></a> </span> </div> <div class="right-side"> <a class="button-primary facetwp-save"><?php _e( 'Save Changes', 'fwp' ); ?></a> </div> </div> <div class="facetwp-content-wrap"> <div class="facetwp-alert"> Did you know there's <a href="https://facetwp.com/documentation/template-configuration/" target="_blank">another way</a> to setup templates? </div> <ul class="facetwp-cards"></ul> <div class="facetwp-content"></div> </div> </div> <!-- Settings tab --> <div class="facetwp-region facetwp-region-settings"> <div class="flexbox"> <div class="left-side"> <div class="facetwp-settings-nav"> <a data-tab="general">General</a> <?php if ( is_plugin_active( 'woocommerce/woocommerce.php' ) ) : ?> <a data-tab="woocommerce">WooCommerce</a> <?php endif; ?> <a data-tab="backup">Backup</a> </div> </div> <div class="right-side"> <a class="button-primary facetwp-save"><?php _e( 'Save Changes', 'fwp' ); ?></a> </div> </div> <div class="facetwp-content-wrap"> <!-- General settings --> <div class="facetwp-settings-section" data-tab="general"> <table> <tr> <td><?php _e( 'License Key', 'fwp' ); ?></td> <td> <input type="text" class="facetwp-license" style="width:300px" value="<?php echo get_option( 'facetwp_license' ); ?>" /> <input type="button" class="button button-small facetwp-activate" value="<?php _e( 'Activate', 'fwp' ); ?>" /> <div class="facetwp-activation-status field-notes"><?php echo $message; ?></div> </td> </tr> </table> <table> <tr> <td> <?php _e( 'Google Maps API Key', 'fwp' ); ?> <div class="facetwp-tooltip"> <span class="icon-question">?</span> <div class="facetwp-tooltip-content"> An API key is required for Proximity facets </div> </div> </td> <td> <input type="text" class="facetwp-setting" data-name="gmaps_api_key" style="width:300px" /> <a href="https://developers.google.com/maps/documentation/javascript/get-api-key#step-1-get-an-api-key-from-the-google-api-console" target="_blank">Get an API key</a> </td> </tr> <tr> <td> <?php _e( 'Separators', 'fwp' ); ?> </td> <td> 34 <input type="text" style="width:20px" class="facetwp-setting" data-name="thousands_separator" /> 567 <input type="text" style="width:20px" class="facetwp-setting" data-name="decimal_separator" /> 89 </td> </tr> <tr> <td> <?php _e( 'Loading Animation', 'fwp' ); ?> </td> <td> <select class="facetwp-setting slim" data-name="loading_animation"> <option value=""><?php _e( 'Spin', 'fwp' ); ?></option> <option value="fade"><?php _e( 'Fade', 'fwp' ); ?></option> <option value="none"><?php _e( 'None', 'fwp' ); ?></option> </select> </td> </tr> <tr> <td> <?php _e( 'Debug Mode', 'fwp' ); ?> </td> <td> <select class="facetwp-setting slim" data-name="debug_mode"> <option value="off"><?php _e( 'Off', 'fwp' ); ?></option> <option value="on"><?php _e( 'On', 'fwp' ); ?></option> </select> </td> </tr> </table> </div> <!-- WooCommerce settings --> <div class="facetwp-settings-section" data-tab="woocommerce"> <table> <tr> <td style="width:240px"> <?php _e( 'Support product variations?', 'fwp' ); ?> <div class="facetwp-tooltip"> <span class="icon-question">?</span> <div class="facetwp-tooltip-content"> Enable if your store uses variable products. </div> </div> </td> <td> <select class="facetwp-setting slim" data-name="wc_enable_variations"> <option value="no"><?php _e( 'No', 'fwp' ); ?></option> <option value="yes"><?php _e( 'Yes', 'fwp' ); ?></option> </select> </td> </tr> <tr> <td style="width:240px"> <?php _e( 'Include all products?', 'fwp' ); ?> <div class="facetwp-tooltip"> <span class="icon-question">?</span> <div class="facetwp-tooltip-content"> Show facet choices for out-of-stock products? </div> </div> </td> <td> <select class="facetwp-setting slim" data-name="wc_index_all"> <option value="no"><?php _e( 'No', 'fwp' ); ?></option> <option value="yes"><?php _e( 'Yes', 'fwp' ); ?></option> </select> </td> </tr> </table> </div> <!-- Backup settings --> <div class="facetwp-settings-section" data-tab="backup"> <table> <tr> <td> <?php _e( 'Export', 'fwp' ); ?> </td> <td valign="top"> <select class="export-items" multiple="multiple" style="width:250px; height:100px"> <?php foreach ( $export as $val => $label ) : ?> <option value="<?php echo $val; ?>"><?php echo $label; ?></option> <?php endforeach; ?> </select> <a class="button export-submit"><?php _e( 'Export', 'fwp' ); ?></a> </td> </tr> </table> <table> <tr> <td> <?php _e( 'Import', 'fwp' ); ?> </td> <td> <div><textarea class="import-code" placeholder="<?php _e( 'Paste the import code here', 'fwp' ); ?>"></textarea></div> <div><input type="checkbox" class="import-overwrite" /> <?php _e( 'Overwrite existing items?', 'fwp' ); ?></div> <div style="margin-top:5px"><a class="button import-submit"><?php _e( 'Import', 'fwp' ); ?></a></div> </td> </tr> </table> </div> </div> </div> <!-- Support tab --> <div class="facetwp-region facetwp-region-support"> <div class="facetwp-content-wrap"> <?php include( FACETWP_DIR . '/templates/page-support.php' ); ?> </div> </div> <!-- Hidden: clone settings --> <div class="hidden clone-facet"> <div class="facetwp-row"> <div class="table-row code-unlock"> This facet is locked to prevent changes. <button class="unlock">Unlock now</button> </div> <table> <tr> <td><?php _e( 'Label', 'fwp' ); ?>:</td> <td> <input type="text" class="facet-label" value="New facet" /> &nbsp; &nbsp; <?php _e( 'Name', 'fwp' ); ?>: <span class="facet-name" contentEditable="true">new_facet</span> </td> </tr> <tr> <td><?php _e( 'Facet type', 'fwp' ); ?>:</td> <td> <select class="facet-type"> <?php foreach ( $facet_types as $name => $class ) : ?> <option value="<?php echo $name; ?>"><?php echo $class->label; ?></option> <?php endforeach; ?> </select> </td> </tr> <tr class="facetwp-show name-source"> <td> <?php _e( 'Data source', 'fwp' ); ?>: </td> <td> <select class="facet-source"> <?php foreach ( $sources as $group ) : ?> <optgroup label="<?php echo $group['label']; ?>"> <?php foreach ( $group['choices'] as $val => $label ) : ?> <option value="<?php echo esc_attr( $val ); ?>"><?php echo esc_html( $label ); ?></option> <?php endforeach; ?> </optgroup> <?php endforeach; ?> </select> </td> </tr> </table> <hr /> <table class="facet-fields"></table> </div> </div> <div class="hidden clone-template"> <div class="facetwp-row"> <div class="table-row code-unlock"> This template is locked to prevent changes. <button class="unlock">Unlock now</button> </div> <div class="table-row"> <input type="text" class="template-label" value="New template" /> &nbsp; &nbsp; <?php _e( 'Name', 'fwp' ); ?>: <span class="template-name" contentEditable="true">new_template</span> </div> <div class="table-row"> <div class="side-link open-builder"><?php _e( 'Open query builder', 'fwp' ); ?></div> <div class="row-label"><?php _e( 'Query Arguments', 'fwp' ); ?></div> <textarea class="template-query"></textarea> </div> <div class="table-row"> <div class="side-link"><a href="https://facetwp.com/documentation/template-configuration/#display-code" target="_blank"><?php _e( 'What goes here?', 'fwp' ); ?></a></div> <div class="row-label"><?php _e( 'Display Code', 'fwp' ); ?></div> <textarea class="template-template"></textarea> </div> </div> </div> </div> <!-- Modal window --> <div class="media-modal"> <button class="button-link media-modal-close"><span class="media-modal-icon"></span></button> <div class="media-modal-content"> <div class="media-frame"> <div class="media-frame-title"> <h1><?php _e( 'Query Builder', 'fwp' ); ?></h1> </div> <div class="media-frame-router"> <div class="media-router"> <?php _e( 'Which posts would you like to use for the content listing?', 'fwp' ); ?> </div> </div> <div class="media-frame-content"> <div class="modal-content-wrap"> <div class="flexbox"> <div class="qb-area"></div> <div class="qb-area-results"> <textarea class="qb-results" readonly></textarea> <button class="button qb-send"><?php _e( 'Send to editor', 'fwp' ); ?></button> </div> </div> </div> </div> </div> </div> </div> <div class="media-modal-backdrop"></div>
gpl-2.0