code
stringlengths
3
1.04M
repo_name
stringlengths
5
109
path
stringlengths
6
306
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
3
1.04M
/******************************************************************************* * Copyright (c) 2005-2010, G. Weirich and Elexis * 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: * G. Weirich - initial implementation * D. Lutz - adapted for importing data from other databases * *******************************************************************************/ package ch.elexis.core.ui.wizards; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.wizard.WizardPage; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.List; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.forms.widgets.Form; import org.eclipse.ui.forms.widgets.FormToolkit; import org.eclipse.ui.forms.widgets.TableWrapData; import org.eclipse.ui.forms.widgets.TableWrapLayout; import ch.elexis.core.ui.UiDesk; import ch.elexis.core.ui.icons.ImageSize; import ch.elexis.core.ui.icons.Images; import ch.rgw.tools.JdbcLink; import ch.rgw.tools.StringTool; public class DBImportFirstPage extends WizardPage { List dbTypes; Text server, dbName; String defaultUser, defaultPassword; JdbcLink j = null; static final String[] supportedDB = new String[] { "mySQl", "PostgreSQL", "H2", "ODBC" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ }; static final int MYSQL = 0; static final int POSTGRESQL = 1; static final int ODBC = 3; static final int H2 = 2; public DBImportFirstPage(String pageName){ super(Messages.DBImportFirstPage_connection, Messages.DBImportFirstPage_typeOfDB, Images.IMG_LOGO.getImageDescriptor(ImageSize._75x66_TitleDialogIconSize)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ setMessage(Messages.DBImportFirstPage_selectType + Messages.DBImportFirstPage_enterNameODBC); //$NON-NLS-1$ setDescription(Messages.DBImportFirstPage_theDesrciption); //$NON-NLS-1$ } public DBImportFirstPage(String pageName, String title, ImageDescriptor titleImage){ super(pageName, title, titleImage); // TODO Automatisch erstellter Konstruktoren-Stub } public void createControl(Composite parent){ DBImportWizard wiz = (DBImportWizard) getWizard(); FormToolkit tk = UiDesk.getToolkit(); Form form = tk.createForm(parent); form.setText(Messages.DBImportFirstPage_Connection); //$NON-NLS-1$ Composite body = form.getBody(); body.setLayout(new TableWrapLayout()); tk.createLabel(body, Messages.DBImportFirstPage_EnterType); //$NON-NLS-1$ dbTypes = new List(body, SWT.BORDER); dbTypes.setItems(supportedDB); dbTypes.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e){ int it = dbTypes.getSelectionIndex(); switch (it) { case MYSQL: case POSTGRESQL: server.setEnabled(true); dbName.setEnabled(true); defaultUser = ""; //$NON-NLS-1$ defaultPassword = ""; //$NON-NLS-1$ break; case H2: server.setEnabled(false); dbName.setEnabled(true); defaultUser = "sa"; defaultPassword = ""; break; case ODBC: server.setEnabled(false); dbName.setEnabled(true); defaultUser = "sa"; //$NON-NLS-1$ defaultPassword = ""; //$NON-NLS-1$ break; default: break; } DBImportSecondPage sec = (DBImportSecondPage) getNextPage(); sec.name.setText(defaultUser); sec.pwd.setText(defaultPassword); } }); tk.adapt(dbTypes, true, true); tk.createLabel(body, Messages.DBImportFirstPage_serverAddress); //$NON-NLS-1$ server = tk.createText(body, "", SWT.BORDER); //$NON-NLS-1$ TableWrapData twr = new TableWrapData(TableWrapData.FILL_GRAB); server.setLayoutData(twr); tk.createLabel(body, Messages.DBImportFirstPage_databaseName); //$NON-NLS-1$ dbName = tk.createText(body, "", SWT.BORDER); //$NON-NLS-1$ TableWrapData twr2 = new TableWrapData(TableWrapData.FILL_GRAB); dbName.setLayoutData(twr2); if (wiz.preset != null && wiz.preset.length > 1) { int idx = StringTool.getIndex(supportedDB, wiz.preset[0]); if (idx < dbTypes.getItemCount()) { dbTypes.select(idx); } server.setText(wiz.preset[1]); dbName.setText(wiz.preset[2]); } setControl(form); } }
sazgin/elexis-3-core
ch.elexis.core.ui/src/ch/elexis/core/ui/wizards/DBImportFirstPage.java
Java
epl-1.0
4,493
/******************************************************************************* * Copyright (c) 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.ws.install.internal; public class MavenRepository { private String name; private String repositoryUrl; private String userId; private String password; public MavenRepository(String name, String repositoryUrl, String userId, String password) { this.name = name; this.repositoryUrl = repositoryUrl; this.userId = userId; this.password = password; } public String getName(){ return name; } public String getRepositoryUrl() { return repositoryUrl; } public String getUserId() { return userId; } public String getPassword() { return password; } public String toString(){ return this.repositoryUrl; } }
OpenLiberty/open-liberty
dev/com.ibm.ws.install/src/com/ibm/ws/install/internal/MavenRepository.java
Java
epl-1.0
1,293
/******************************************************************************* * Copyright (c) 2011, 2016 Eurotech and/or its affiliates 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: * Eurotech - initial API and implementation * *******************************************************************************/ package org.eclipse.kapua.service.datastore.internal.model.query; import java.util.ArrayList; import org.eclipse.kapua.service.datastore.model.Storable; import org.eclipse.kapua.service.datastore.model.StorableListResult; @SuppressWarnings("serial") public class AbstractStorableListResult<E extends Storable> extends ArrayList<E> implements StorableListResult<E> { private Object nextKey; private Integer totalCount; public AbstractStorableListResult() { nextKey = null; totalCount = null; } public AbstractStorableListResult(Object nextKey) { this.nextKey = nextKey; this.totalCount = null; } public AbstractStorableListResult(Object nextKeyOffset, Integer totalCount) { this(nextKeyOffset); this.totalCount = totalCount; } public Object getNextKey() { return nextKey; } public Integer getTotalCount() { return totalCount; } }
muros-ct/kapua
service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/model/query/AbstractStorableListResult.java
Java
epl-1.0
1,524
/******************************************************************************* * Copyright (c) 2017, 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.ws.transaction.test; import org.junit.ClassRule; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; import com.ibm.ws.transaction.test.tests.EJBNewTxDBRoSTest; import com.ibm.ws.transaction.test.tests.EJBNewTxDBTest; import com.ibm.ws.transaction.test.tests.EJBNewTxRoSTest; import com.ibm.ws.transaction.test.tests.EJBNewTxTest; import componenttest.rules.repeater.FeatureReplacementAction; import componenttest.rules.repeater.JakartaEE9Action; import componenttest.rules.repeater.RepeatTests; @RunWith(Suite.class) @SuiteClasses({ EJBNewTxTest.class, EJBNewTxDBTest.class, EJBNewTxRoSTest.class, EJBNewTxDBRoSTest.class }) public class FATSuite { // Using the RepeatTests @ClassRule will cause all tests to be run twice. // First without any modifications, then again with all features upgraded to their EE8 equivalents. @ClassRule public static RepeatTests r = RepeatTests.withoutModification() .andWith(FeatureReplacementAction.EE8_FEATURES()) .andWith(new JakartaEE9Action()); }
OpenLiberty/open-liberty
dev/com.ibm.ws.transaction.core_fat.startMultiEJB/fat/src/com/ibm/ws/transaction/test/FATSuite.java
Java
epl-1.0
1,724
/** * Copyright (c) 2010-2021 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.loxone.internal.controls; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.openhab.core.library.types.StringType; /** * Test class for (@link LxControlTracker} * * @author Pawel Pieczul - initial contribution * */ public class LxControlTrackerTest extends LxControlTest { @BeforeEach public void setup() { setupControl("132aa43b-01d4-56ea-ffff403fb0c34b9e", "0b734138-037d-034e-ffff403fb0c34b9e", "0fe650c2-0004-d446-ffff504f9410790f", "Tracker Control"); } @Test public void testControlCreation() { testControlCreation(LxControlTracker.class, 1, 0, 1, 1, 1); } @Test public void testChannels() { testChannel("String", null, null, null, null, null, true, null); } @Test public void testLoxoneStateChanges() { for (int i = 0; i < 20; i++) { String s = new String(); for (int j = 0; j < i; j++) { for (char c = 'a'; c <= 'a' + j; c++) { s = s + c; } if (j != i - 1) { s = s + '|'; } } changeLoxoneState("entries", s); testChannelState(new StringType(s)); } } }
MikeJMajor/openhab2-addons-dlinksmarthome
bundles/org.openhab.binding.loxone/src/test/java/org/openhab/binding/loxone/internal/controls/LxControlTrackerTest.java
Java
epl-1.0
1,684
package moCreatures.items; import net.minecraft.src.EntityPlayer; import net.minecraft.src.Item; import net.minecraft.src.ItemStack; import net.minecraft.src.World; import moCreatures.entities.EntitySharkEgg; // Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) braces deadcode public class ItemSharkEgg extends Item { public ItemSharkEgg(int i) { super(i); maxStackSize = 16; } public ItemStack onItemRightClick(ItemStack itemstack, World world, EntityPlayer entityplayer) { itemstack.stackSize--; if(!world.singleplayerWorld) { EntitySharkEgg entitysharkegg = new EntitySharkEgg(world); entitysharkegg.setPosition(entityplayer.posX, entityplayer.posY, entityplayer.posZ); world.entityJoinedWorld(entitysharkegg); entitysharkegg.motionY += world.rand.nextFloat() * 0.05F; entitysharkegg.motionX += (world.rand.nextFloat() - world.rand.nextFloat()) * 0.3F; entitysharkegg.motionZ += (world.rand.nextFloat() - world.rand.nextFloat()) * 0.3F; } return itemstack; } }
sehrgut/minecraft-smp-mocreatures
moCreatures/server/debug/sources/moCreatures/items/ItemSharkEgg.java
Java
epl-1.0
1,137
/******************************************************************************* * Copyright (C) 2008, 2009 Robin Rosenberg <robin.rosenberg@dewire.com> * * 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.egit.ui.internal.decorators; import java.io.IOException; import java.util.Map; import java.util.WeakHashMap; import org.eclipse.core.resources.IResource; import org.eclipse.egit.core.GitProvider; import org.eclipse.egit.core.project.RepositoryMapping; import org.eclipse.egit.ui.Activator; import org.eclipse.egit.ui.UIText; import org.eclipse.egit.ui.internal.CompareUtils; import org.eclipse.egit.ui.internal.trace.GitTraceLocation; import org.eclipse.jface.text.Document; import org.eclipse.jgit.events.ListenerHandle; import org.eclipse.jgit.events.RefsChangedEvent; import org.eclipse.jgit.events.RefsChangedListener; import org.eclipse.jgit.lib.AnyObjectId; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.ObjectLoader; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.revwalk.RevTree; import org.eclipse.jgit.revwalk.RevWalk; import org.eclipse.jgit.treewalk.TreeWalk; import org.eclipse.osgi.util.NLS; import org.eclipse.team.core.RepositoryProvider; class GitDocument extends Document implements RefsChangedListener { private final IResource resource; private ObjectId lastCommit; private ObjectId lastTree; private ObjectId lastBlob; private ListenerHandle myRefsChangedHandle; static Map<GitDocument, Repository> doc2repo = new WeakHashMap<GitDocument, Repository>(); static GitDocument create(final IResource resource) throws IOException { if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation.getTrace().trace( GitTraceLocation.QUICKDIFF.getLocation(), "(GitDocument) create: " + resource); //$NON-NLS-1$ GitDocument ret = null; if (RepositoryProvider.getProvider(resource.getProject()) instanceof GitProvider) { ret = new GitDocument(resource); ret.populate(); final Repository repository = ret.getRepository(); if (repository != null) ret.myRefsChangedHandle = repository.getListenerList() .addRefsChangedListener(ret); } return ret; } private GitDocument(IResource resource) { this.resource = resource; GitDocument.doc2repo.put(this, getRepository()); } private void setResolved(final AnyObjectId commit, final AnyObjectId tree, final AnyObjectId blob, final String value) { lastCommit = commit != null ? commit.copy() : null; lastTree = tree != null ? tree.copy() : null; lastBlob = blob != null ? blob.copy() : null; set(value); if (blob != null) if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation .getTrace() .trace( GitTraceLocation.QUICKDIFF.getLocation(), "(GitDocument) resolved " + resource + " to " + lastBlob + " in " + lastCommit + "/" + lastTree); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ else if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation.getTrace().trace( GitTraceLocation.QUICKDIFF.getLocation(), "(GitDocument) unresolved " + resource); //$NON-NLS-1$ } void populate() throws IOException { if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation.getTrace().traceEntry( GitTraceLocation.QUICKDIFF.getLocation(), resource); TreeWalk tw = null; RevWalk rw = null; try { RepositoryMapping mapping = RepositoryMapping.getMapping(resource); if (mapping == null) { setResolved(null, null, null, ""); //$NON-NLS-1$ return; } final String gitPath = mapping.getRepoRelativePath(resource); final Repository repository = mapping.getRepository(); String baseline = GitQuickDiffProvider.baseline.get(repository); if (baseline == null) baseline = Constants.HEAD; ObjectId commitId = repository.resolve(baseline); if (commitId != null) { if (commitId.equals(lastCommit)) { if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation.getTrace().trace( GitTraceLocation.QUICKDIFF.getLocation(), "(GitDocument) already resolved"); //$NON-NLS-1$ return; } } else { String msg = NLS.bind(UIText.GitDocument_errorResolveQuickdiff, new Object[] { baseline, resource, repository }); Activator.logError(msg, new Throwable()); setResolved(null, null, null, ""); //$NON-NLS-1$ return; } rw = new RevWalk(repository); RevCommit baselineCommit; try { baselineCommit = rw.parseCommit(commitId); } catch (IOException err) { String msg = NLS .bind(UIText.GitDocument_errorLoadCommit, new Object[] { commitId, baseline, resource, repository }); Activator.logError(msg, err); setResolved(null, null, null, ""); //$NON-NLS-1$ return; } RevTree treeId = baselineCommit.getTree(); if (treeId.equals(lastTree)) { if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation.getTrace().trace( GitTraceLocation.QUICKDIFF.getLocation(), "(GitDocument) already resolved"); //$NON-NLS-1$ return; } tw = TreeWalk.forPath(repository, gitPath, treeId); if (tw == null) { if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation .getTrace() .trace( GitTraceLocation.QUICKDIFF.getLocation(), "(GitDocument) resource " + resource + " not found in " + treeId + " in " + repository + ", baseline=" + baseline); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ setResolved(null, null, null, ""); //$NON-NLS-1$ return; } ObjectId id = tw.getObjectId(0); if (id.equals(ObjectId.zeroId())) { setResolved(null, null, null, ""); //$NON-NLS-1$ String msg = NLS .bind(UIText.GitDocument_errorLoadTree, new Object[] { treeId.getName(), baseline, resource, repository }); Activator.logError(msg, new Throwable()); setResolved(null, null, null, ""); //$NON-NLS-1$ return; } if (!id.equals(lastBlob)) { if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation.getTrace().trace( GitTraceLocation.QUICKDIFF.getLocation(), "(GitDocument) compareTo: " + baseline); //$NON-NLS-1$ ObjectLoader loader = repository.open(id, Constants.OBJ_BLOB); byte[] bytes = loader.getBytes(); String charset; charset = CompareUtils.getResourceEncoding(resource); // Finally we could consider validating the content with respect // to the content. We don't do that here. String s = new String(bytes, charset); setResolved(commitId, treeId, id, s); if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation .getTrace() .trace(GitTraceLocation.QUICKDIFF.getLocation(), "(GitDocument) has reference doc, size=" + s.length() + " bytes"); //$NON-NLS-1$ //$NON-NLS-2$ } else { if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation.getTrace().trace( GitTraceLocation.QUICKDIFF.getLocation(), "(GitDocument) already resolved"); //$NON-NLS-1$ } } finally { if (tw != null) tw.release(); if (rw != null) rw.release(); if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation.getTrace().traceExit( GitTraceLocation.QUICKDIFF.getLocation()); } } void dispose() { if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation.getTrace().trace( GitTraceLocation.QUICKDIFF.getLocation(), "(GitDocument) dispose: " + resource); //$NON-NLS-1$ doc2repo.remove(this); if (myRefsChangedHandle != null) { myRefsChangedHandle.remove(); myRefsChangedHandle = null; } } public void onRefsChanged(final RefsChangedEvent e) { try { populate(); } catch (IOException e1) { Activator.logError(UIText.GitDocument_errorRefreshQuickdiff, e1); } } private Repository getRepository() { RepositoryMapping mapping = RepositoryMapping.getMapping(resource); return (mapping != null) ? mapping.getRepository() : null; } /** * A change occurred to a repository. Update any GitDocument instances * referring to such repositories. * * @param repository * Repository which changed * @throws IOException */ static void refreshRelevant(final Repository repository) throws IOException { for (Map.Entry<GitDocument, Repository> i : doc2repo.entrySet()) { if (i.getValue() == repository) { i.getKey().populate(); } } } }
jdcasey/EGit
org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/decorators/GitDocument.java
Java
epl-1.0
8,708
/******************************************************************************* * 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 *******************************************************************************/ // Generated from C:\SIB\Code\WASX.SIB\dd\SIB\ws\code\sib.mfp.impl\src\com\ibm\ws\sib\mfp\schema\JsHdrSchema.schema: do not edit directly package com.ibm.ws.sib.mfp.schema; import com.ibm.ws.sib.mfp.jmf.impl.JSchema; public final class JsHdrAccess { public final static JSchema schema = new JsHdrSchema(); public final static int DISCRIMINATOR = 0; public final static int ARRIVALTIMESTAMP = 1; public final static int SYSTEMMESSAGESOURCEUUID = 2; public final static int SYSTEMMESSAGEVALUE = 3; public final static int SECURITYUSERID = 4; public final static int SECURITYSENTBYSYSTEM = 5; public final static int MESSAGETYPE = 6; public final static int SUBTYPE = 7; public final static int HDR2 = 8; public final static int API = 10; public final static int IS_API_EMPTY = 0; public final static int IS_API_DATA = 1; public final static int API_DATA = 9; }
OpenLiberty/open-liberty
dev/com.ibm.ws.messaging.common/src/com/ibm/ws/sib/mfp/schema/JsHdrAccess.java
Java
epl-1.0
1,422
///******************************************************************************* // * Copyright (c) 2015, 2016 EfficiOS Inc., Alexandre Montplaisir // * // * 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.lttng.scope.lami.ui.viewers; // //import org.eclipse.jface.viewers.TableViewer; //import org.eclipse.swt.SWT; //import org.eclipse.swt.widgets.Composite; //import org.lttng.scope.lami.core.module.LamiChartModel; //import org.lttng.scope.lami.ui.views.LamiReportViewTabPage; // ///** // * Common interface for all Lami viewers. // * // * @author Alexandre Montplaisir // */ //public interface ILamiViewer { // // /** // * Dispose the viewer widget. // */ // void dispose(); // // /** // * Factory method to create a new Table viewer. // * // * @param parent // * The parent composite // * @param page // * The {@link LamiReportViewTabPage} parent page // * @return The new viewer // */ // static ILamiViewer createLamiTable(Composite parent, LamiReportViewTabPage page) { // TableViewer tableViewer = new TableViewer(parent, SWT.FULL_SELECTION | SWT.MULTI | SWT.VIRTUAL); // return new LamiTableViewer(tableViewer, page); // } // // /** // * Factory method to create a new chart viewer. The chart type is specified // * by the 'chartModel' parameter. // * // * @param parent // * The parent composite // * @param page // * The {@link LamiReportViewTabPage} parent page // * @param chartModel // * The information about the chart to display // * @return The new viewer // */ // static ILamiViewer createLamiChart(Composite parent, LamiReportViewTabPage page, LamiChartModel chartModel) { // switch (chartModel.getChartType()) { // case BAR_CHART: // return new LamiBarChartViewer(parent, page, chartModel); // case XY_SCATTER: // return new LamiScatterViewer(parent, page, chartModel); // case PIE_CHART: // default: // throw new UnsupportedOperationException("Unsupported chart type: " + chartModel.toString()); //$NON-NLS-1$ // } // } //}
alexmonthy/lttng-scope
lttng-scope/src/main/java/org/lttng/scope/lami/viewers/ILamiViewer.java
Java
epl-1.0
2,501
/******************************************************************************* * Copyright (c) 2017, 2021 Red Hat Inc and others * * This program and the accompanying materials are made * available under the terms of the Eclipse Public License 2.0 * which is available at https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * Red Hat Inc - initial API and implementation *******************************************************************************/ package org.eclipse.kapua.kura.simulator.app.deploy; import org.eclipse.kapua.kura.simulator.payload.Metric; import org.eclipse.kapua.kura.simulator.payload.Optional; public class DeploymentUninstallPackageRequest { @Metric("dp.name") private String name; @Metric("dp.version") private String version; @Metric("job.id") private long jobId; @Optional @Metric("dp.reboot") private Boolean reboot; @Optional @Metric("dp.reboot.delay") private Integer rebootDelay; public String getName() { return name; } public void setName(final String name) { this.name = name; } public String getVersion() { return version; } public void setVersion(final String version) { this.version = version; } public long getJobId() { return jobId; } public void setJobId(final long jobId) { this.jobId = jobId; } public Boolean getReboot() { return reboot; } public void setReboot(final Boolean reboot) { this.reboot = reboot; } public Integer getRebootDelay() { return rebootDelay; } public void setRebootDelay(final Integer rebootDelay) { this.rebootDelay = rebootDelay; } }
stzilli/kapua
simulator-kura/src/main/java/org/eclipse/kapua/kura/simulator/app/deploy/DeploymentUninstallPackageRequest.java
Java
epl-1.0
1,787
/** * Copyright (c) 2020 Bosch.IO GmbH 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 */ package org.eclipse.hawkbit.ui.common.tagdetails; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Optional; import java.util.Set; import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.ui.common.data.proxies.ProxyTag; import org.eclipse.hawkbit.ui.common.tagdetails.TagPanelLayout.TagAssignmentListener; import org.eclipse.hawkbit.ui.utils.UIComponentIdProvider; import org.eclipse.hawkbit.ui.utils.UIMessageIdProvider; import org.eclipse.hawkbit.ui.utils.VaadinMessageSource; import com.google.common.collect.Sets; import com.vaadin.ui.ComboBox; import com.vaadin.ui.HorizontalLayout; import com.vaadin.ui.themes.ValoTheme; /** * Combobox that lists all available Tags that can be assigned to a * {@link Target} or {@link DistributionSet}. */ public class TagAssignementComboBox extends HorizontalLayout { private static final long serialVersionUID = 1L; private final Collection<ProxyTag> allAssignableTags; private final transient Set<TagAssignmentListener> listeners = Sets.newConcurrentHashSet(); private final ComboBox<ProxyTag> assignableTagsComboBox; private final boolean readOnlyMode; /** * Constructor. * * @param i18n * the i18n * @param readOnlyMode * if true the combobox will be disabled so no assignment can be * done. */ TagAssignementComboBox(final VaadinMessageSource i18n, final boolean readOnlyMode) { this.readOnlyMode = readOnlyMode; setWidth("100%"); this.assignableTagsComboBox = getAssignableTagsComboBox( i18n.getMessage(UIMessageIdProvider.TOOLTIP_SELECT_TAG)); this.allAssignableTags = new HashSet<>(); this.assignableTagsComboBox.setItems(allAssignableTags); addComponent(assignableTagsComboBox); } private ComboBox<ProxyTag> getAssignableTagsComboBox(final String description) { final ComboBox<ProxyTag> tagsComboBox = new ComboBox<>(); tagsComboBox.setId(UIComponentIdProvider.TAG_SELECTION_ID); tagsComboBox.setDescription(description); tagsComboBox.addStyleName(ValoTheme.COMBOBOX_TINY); tagsComboBox.setEnabled(!readOnlyMode); tagsComboBox.setWidth("100%"); tagsComboBox.setEmptySelectionAllowed(true); tagsComboBox.setItemCaptionGenerator(ProxyTag::getName); tagsComboBox.addValueChangeListener(event -> assignTag(event.getValue())); return tagsComboBox; } private void assignTag(final ProxyTag tagData) { if (tagData == null || readOnlyMode) { return; } allAssignableTags.remove(tagData); assignableTagsComboBox.clear(); assignableTagsComboBox.getDataProvider().refreshAll(); notifyListenersTagAssigned(tagData); } /** * Initializes the Combobox with all assignable tags. * * @param assignableTags * assignable tags */ void initializeAssignableTags(final List<ProxyTag> assignableTags) { allAssignableTags.addAll(assignableTags); assignableTagsComboBox.getDataProvider().refreshAll(); } /** * Removes all Tags from Combobox. */ void removeAllTags() { allAssignableTags.clear(); assignableTagsComboBox.clear(); assignableTagsComboBox.getDataProvider().refreshAll(); } /** * Adds an assignable Tag to the combobox. * * @param tagData * the data of the Tag */ void addAssignableTag(final ProxyTag tagData) { if (tagData == null) { return; } allAssignableTags.add(tagData); assignableTagsComboBox.getDataProvider().refreshAll(); } /** * Updates an assignable Tag in the combobox. * * @param tagData * the data of the Tag */ void updateAssignableTag(final ProxyTag tagData) { if (tagData == null) { return; } findAssignableTagById(tagData.getId()).ifPresent(tagToUpdate -> updateAssignableTag(tagToUpdate, tagData)); } private Optional<ProxyTag> findAssignableTagById(final Long id) { return allAssignableTags.stream().filter(tag -> tag.getId().equals(id)).findAny(); } private void updateAssignableTag(final ProxyTag oldTag, final ProxyTag newTag) { allAssignableTags.remove(oldTag); allAssignableTags.add(newTag); assignableTagsComboBox.getDataProvider().refreshAll(); } /** * Removes an assignable tag from the combobox. * * @param tagId * the tag Id of the Tag that should be removed. */ void removeAssignableTag(final Long tagId) { findAssignableTagById(tagId).ifPresent(this::removeAssignableTag); } /** * Removes an assignable tag from the combobox. * * @param tagData * the {@link ProxyTag} of the Tag that should be removed. */ void removeAssignableTag(final ProxyTag tagData) { allAssignableTags.remove(tagData); assignableTagsComboBox.getDataProvider().refreshAll(); } /** * Registers an {@link TagAssignmentListener} on the combobox. * * @param listener * the listener to register */ void addTagAssignmentListener(final TagAssignmentListener listener) { listeners.add(listener); } /** * Removes a {@link TagAssignmentListener} from the combobox, * * @param listener * the listener that should be removed. */ void removeTagAssignmentListener(final TagAssignmentListener listener) { listeners.remove(listener); } private void notifyListenersTagAssigned(final ProxyTag tagData) { listeners.forEach(listener -> listener.assignTag(tagData)); } }
eclipse/hawkbit
hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/tagdetails/TagAssignementComboBox.java
Java
epl-1.0
6,274
/** * Copyright (c) 2010-2021 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.fronius.internal.api; import com.google.gson.annotations.SerializedName; /** * The {@link HeadRequestArguments} is responsible for storing * the "RequestArguments" node from the {@link Head} * * @author Thomas Rokohl - Initial contribution */ public class HeadRequestArguments { @SerializedName("DataCollection") private String dataCollection; @SerializedName("DeviceClass") private String deviceClass; @SerializedName("DeviceId") private String deviceId; @SerializedName("Scope") private String scope; public String getDataCollection() { if (null == dataCollection) { dataCollection = ""; } return dataCollection; } public void setDataCollection(String dataCollection) { this.dataCollection = dataCollection; } public String getDeviceClass() { if (null == deviceClass) { deviceClass = ""; } return deviceClass; } public void setDeviceClass(String deviceClass) { this.deviceClass = deviceClass; } public String getDeviceId() { if (null == deviceId) { deviceId = ""; } return deviceId; } public void setDeviceId(String deviceId) { this.deviceId = deviceId; } public String getScope() { if (null == scope) { scope = ""; } return scope; } public void setScope(String scope) { this.scope = scope; } }
paulianttila/openhab2
bundles/org.openhab.binding.fronius/src/main/java/org/openhab/binding/fronius/internal/api/HeadRequestArguments.java
Java
epl-1.0
1,893
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.vigicrues.internal.dto.vigicrues; import java.util.List; import com.google.gson.annotations.SerializedName; /** * The {@link TerEntVigiCru} is the Java class used to map the JSON * response to an vigicrue api endpoint request. * * @author Gaël L'hopital - Initial contribution */ public class TerEntVigiCru { public class VicTerEntVigiCru { @SerializedName("vic:aNMoinsUn") public List<VicANMoinsUn> vicANMoinsUn; /* * Currently unused, maybe interesting in the future * * @SerializedName("@id") * public String id; * * @SerializedName("vic:CdEntVigiCru") * public String vicCdEntVigiCru; * * @SerializedName("vic:TypEntVigiCru") * public String vicTypEntVigiCru; * * @SerializedName("vic:LbEntVigiCru") * public String vicLbEntVigiCru; * * @SerializedName("vic:DtHrCreatEntVigiCru") * public String vicDtHrCreatEntVigiCru; * * @SerializedName("vic:DtHrMajEntVigiCru") * public String vicDtHrMajEntVigiCru; * * @SerializedName("vic:StEntVigiCru") * public String vicStEntVigiCru; * public int count_aNMoinsUn; * * @SerializedName("LinkInfoCru") * public String linkInfoCru; */ } @SerializedName("vic:TerEntVigiCru") public VicTerEntVigiCru vicTerEntVigiCru; }
openhab/openhab2
bundles/org.openhab.binding.vigicrues/src/main/java/org/openhab/binding/vigicrues/internal/dto/vigicrues/TerEntVigiCru.java
Java
epl-1.0
1,863
/******************************************************************************* * Copyright (c) 2016, 2021 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.security.openidconnect.server.fat.jaxrs.config.OAuth; import java.util.ArrayList; import java.util.List; import org.junit.Assume; import org.junit.BeforeClass; import org.junit.runner.RunWith; import com.ibm.websphere.simplicity.log.Log; import com.ibm.ws.security.oauth_oidc.fat.commonTest.Constants; import com.ibm.ws.security.oauth_oidc.fat.commonTest.TestServer; import com.ibm.ws.security.oauth_oidc.fat.commonTest.TestSettings; import com.ibm.ws.security.openidconnect.server.fat.jaxrs.config.CommonTests.MapToUserRegistryWithRegMismatch2ServerTests; import componenttest.custom.junit.runner.FATRunner; import componenttest.custom.junit.runner.Mode; import componenttest.custom.junit.runner.Mode.TestMode; import componenttest.topology.impl.LibertyServerWrapper; import componenttest.topology.utils.LDAPUtils; // See test description in // com.ibm.ws.security.openidconnect.server-1.0_fat.jaxrs.config/fat/src/com/ibm/ws/security/openidconnect/server/fat/jaxrs/config/CommonTests/MapToUserRegistryWithRegMismatch2ServerTests.java @LibertyServerWrapper @Mode(TestMode.FULL) @RunWith(FATRunner.class) public class OAuthMapToUserRegistryWithRegMismatch2ServerTests extends MapToUserRegistryWithRegMismatch2ServerTests { private static final Class<?> thisClass = OAuthMapToUserRegistryWithRegMismatch2ServerTests.class; @BeforeClass public static void setupBeforeTest() throws Exception { /* * These tests have not been configured to run with the local LDAP server. */ Assume.assumeTrue(!LDAPUtils.USE_LOCAL_LDAP_SERVER); msgUtils.printClassName(thisClass.toString()); Log.info(thisClass, "setupBeforeTest", "Prep for test"); // add any additional messages that you want the "start" to wait for // we should wait for any providers that this test requires List<String> extraMsgs = new ArrayList<String>(); extraMsgs.add("CWWKS1631I.*"); List<String> extraApps = new ArrayList<String>(); TestServer.addTestApp(null, extraMsgs, Constants.OP_SAMPLE_APP, Constants.OAUTH_OP); TestServer.addTestApp(extraApps, null, Constants.OP_CLIENT_APP, Constants.OAUTH_OP); TestServer.addTestApp(extraApps, extraMsgs, Constants.OP_TAI_APP, Constants.OAUTH_OP); List<String> extraMsgs2 = new ArrayList<String>(); List<String> extraApps2 = new ArrayList<String>(); extraApps2.add(Constants.HELLOWORLD_SERVLET); testSettings = new TestSettings(); testOPServer = commonSetUp(OPServerName, "server_orig_maptest_ldap.xml", Constants.OAUTH_OP, extraApps, Constants.DO_NOT_USE_DERBY, extraApps); genericTestServer = commonSetUp(RSServerName, "server_orig_maptest_mismatchregistry.xml", Constants.GENERIC_SERVER, extraApps2, Constants.DO_NOT_USE_DERBY, extraMsgs2, null, Constants.OAUTH_OP); targetProvider = Constants.OAUTHCONFIGSAMPLE_APP; flowType = Constants.WEB_CLIENT_FLOW; goodActions = Constants.BASIC_PROTECTED_RESOURCE_RS_PROTECTED_RESOURCE_ACTIONS; // set RS protected resource to point to second server. testSettings.setRSProtectedResource(genericTestServer.getHttpsString() + "/helloworld/rest/helloworld"); // Initial user settings for default user. Individual tests override as needed. testSettings.setAdminUser("oidcu1"); testSettings.setAdminPswd("security"); testSettings.setGroupIds("RSGroup"); } }
OpenLiberty/open-liberty
dev/com.ibm.ws.security.oidc.server_fat.jaxrs.config/fat/src/com/ibm/ws/security/openidconnect/server/fat/jaxrs/config/OAuth/OAuthMapToUserRegistryWithRegMismatch2ServerTests.java
Java
epl-1.0
4,019
/******************************************************************************* * Copyright (c) 2016, 2021 Eurotech and/or its affiliates and others * * This program and the accompanying materials are made * available under the terms of the Eclipse Public License 2.0 * which is available at https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * Eurotech - initial API and implementation *******************************************************************************/ package org.eclipse.kapua; /** * KapuaIllegalNullArgumentException is thrown when <tt>null</tt> is passed to a method for an argument * or as a value for field in an object where <tt>null</tt> is not allowed.<br> * This should always be used instead of <tt>NullPointerException</tt> as the latter is too easily confused with programming bugs. * * @since 1.0 * */ public class KapuaIllegalNullArgumentException extends KapuaIllegalArgumentException { private static final long serialVersionUID = -8762712571192128282L; /** * Constructor * * @param argumentName */ public KapuaIllegalNullArgumentException(String argumentName) { super(KapuaErrorCodes.ILLEGAL_NULL_ARGUMENT, argumentName, null); } }
stzilli/kapua
service/api/src/main/java/org/eclipse/kapua/KapuaIllegalNullArgumentException.java
Java
epl-1.0
1,278
/* * Copyright (C) 2014 Michael Joyce <ubermichael@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 version 2. * * 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 ca.nines.ise.util; import java.util.ArrayDeque; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.UserDataHandler; import org.w3c.dom.events.Event; import org.w3c.dom.events.EventListener; import org.w3c.dom.events.EventTarget; import org.xml.sax.Attributes; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.helpers.XMLFilterImpl; import org.xml.sax.XMLReader; import org.xml.sax.helpers.LocatorImpl; /** * Annotates a DOM with location data during the construction process. * <p> * http://javacoalface.blogspot.ca/2011/04/line-and-column-numbers-in-xml-dom.html * <p> * @author Michael Joyce <ubermichael@gmail.com> */ public class LocationAnnotator extends XMLFilterImpl { /** * Locator returned by the construction process. */ private Locator locator; /** * The systemID of the XML. */ private final String source; /** * Stack to hold the locators which haven't been completed yet. */ private final ArrayDeque<Locator> locatorStack = new ArrayDeque<>(); /** * Stack holding incomplete elements. */ private final ArrayDeque<Element> elementStack = new ArrayDeque<>(); /** * A data handler to add the location data. */ private final UserDataHandler dataHandler = new LocationDataHandler(); /** * Construct a location annotator for an XMLReader and Document. The systemID * is determined automatically. * * @param xmlReader the reader to use the annotator * @param dom the DOM to annotate */ LocationAnnotator(XMLReader xmlReader, Document dom) { super(xmlReader); source = ""; EventListener modListener = new EventListener() { @Override public void handleEvent(Event e) { EventTarget target = e.getTarget(); elementStack.push((Element) target); } }; ((EventTarget) dom).addEventListener("DOMNodeInserted", modListener, true); } /** * Construct a location annotator for an XMLReader and Document. The systemID * is NOT determined automatically. * * @param source the systemID of the XML * @param xmlReader the reader to use the annotator * @param dom the DOM to annotate */ LocationAnnotator(String source, XMLReader xmlReader, Document dom) { super(xmlReader); this.source = source; EventListener modListener = new EventListener() { @Override public void handleEvent(Event e) { EventTarget target = e.getTarget(); elementStack.push((Element) target); } }; ((EventTarget) dom).addEventListener("DOMNodeInserted", modListener, true); } /** * Add the locator to the document during the parse. * * @param locator the locator to add */ @Override public void setDocumentLocator(Locator locator) { super.setDocumentLocator(locator); this.locator = locator; } /** * Handle the start tag of an element by adding locator data. * * @param uri The systemID of the XML. * @param localName the name of the tag. unused. * @param qName the FQDN of the tag. unused. * @param atts the attributes of the tag. unused. * @throws SAXException */ @Override public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { super.startElement(uri, localName, qName, atts); locatorStack.push(new LocatorImpl(locator)); } /** * Handle the end tag of an element by adding locator data. * * @param uri The systemID of the XML. * @param localName the name of the tag. unused. * @param qName the FQDN of the tag. unused. * @throws SAXException */ @Override public void endElement(String uri, String localName, String qName) throws SAXException { super.endElement(uri, localName, qName); if (locatorStack.size() > 0) { Locator startLocator = locatorStack.pop(); LocationData location = new LocationData( (startLocator.getSystemId() == null ? source : startLocator.getSystemId()), startLocator.getLineNumber(), startLocator.getColumnNumber(), locator.getLineNumber(), locator.getColumnNumber() ); Element e = elementStack.pop(); e.setUserData( LocationData.LOCATION_DATA_KEY, location, dataHandler); } } /** * UserDataHandler to insert location data into the XML DOM. */ private class LocationDataHandler implements UserDataHandler { /** * Handle an even during a parse. An even is a start/end/empty tag or some * data. * * @param operation unused. * @param key unused * @param data unused * @param src the source of the data * @param dst the destination of the data */ @Override public void handle(short operation, String key, Object data, Node src, Node dst) { if (src != null && dst != null) { LocationData locatonData = (LocationData) src.getUserData(LocationData.LOCATION_DATA_KEY); if (locatonData != null) { dst.setUserData(LocationData.LOCATION_DATA_KEY, locatonData, dataHandler); } } } } }
emmental/isetools
src/main/java/ca/nines/ise/util/LocationAnnotator.java
Java
gpl-2.0
5,912
package net.indrix.arara.servlets.pagination; import java.sql.SQLException; import java.util.List; import net.indrix.arara.dao.DatabaseDownException; public class SoundBySpeciePaginationController extends SoundPaginationController { /** * Creates a new PaginationController object, with the given number of elements per page, and * with the flag identification * * @param soundsPerPage The amount of sounds per page * @param identification The flag for identification */ public SoundBySpeciePaginationController(int soundsPerPage, boolean identification) { super(soundsPerPage, identification); } @Override protected List retrieveAllData() throws DatabaseDownException, SQLException { logger.debug("SoundBySpeciePaginationController.retrieveAllData : retrieving all sounds..."); List listOfSounds = null; if (id != -1){ listOfSounds = model.retrieveIDsForSpecie(getId()); } else { listOfSounds = model.retrieveIDsForSpecieName(getText()); } logger.debug("SoundBySpeciePaginationController.retrieveAllData : " + listOfSounds.size() + " sounds retrieved..."); return listOfSounds; } }
BackupTheBerlios/arara-svn
core/trunk/src/main/java/net/indrix/arara/servlets/pagination/SoundBySpeciePaginationController.java
Java
gpl-2.0
1,289
package dataservice.businessdataservice; import java.rmi.Remote; import java.rmi.RemoteException; import java.util.ArrayList; import po.BusinessPO; import po.DistributeReceiptPO; import po.DriverPO; import po.EnVehicleReceiptPO; import po.GatheringReceiptPO; import po.OrderAcceptReceiptPO; import po.OrganizationPO; import po.VehiclePO; /** * BusinessData */ public interface BusinessDataService extends Remote { // 根据营业厅ID(找到文件)和营业厅业务员ID(查找文件内容),ID为null就返回第一个 public BusinessPO getBusinessInfo(String organizationID, String ID) throws RemoteException; // 根据营业厅ID和车辆ID查询车辆PO public VehiclePO getVehicleInfo(String organizationID, String vehicleID) throws RemoteException; // 营业厅每日一个,每日早上8点发货一次 public boolean addReceipt(String organizationID, OrderAcceptReceiptPO po) throws RemoteException; // 获得某营业厅的全部车辆信息 public ArrayList<VehiclePO> getVehicleInfos(String organizationID) throws RemoteException; // 添加装车单到今日装车单文件中 public boolean addEnVehicleReceipt(String organizationID, ArrayList<EnVehicleReceiptPO> pos) throws RemoteException; // 增加一个车辆信息VehiclePO到VehiclePOList中 public boolean addVehicle(String organizationID, VehiclePO po) throws RemoteException; // 删除VehiclePOList中的一个车辆信息VehiclePO public boolean deleteVehicle(String organizationID, VehiclePO po) throws RemoteException; // 修改VehiclePOList中的一个车辆信息VehiclePO public boolean modifyVehicle(String organizationID, VehiclePO po) throws RemoteException; // 返回本营业厅司机信息列表 public ArrayList<DriverPO> getDriverInfos(String organizationID) throws RemoteException; // 增加一个GatheringReceipt到本营业厅今日的文件中,一天也就一个 public boolean addGatheringReceipt(String organizationID, GatheringReceiptPO grp) throws RemoteException; // 获得今日本营业厅OrderAcceptReceiptPO的个数 public int getNumOfOrderAcceptReceipt(String organizationID) throws RemoteException; // 返回规定日期的所有GatheringReceipt,time格式 2015-11-23 public ArrayList<GatheringReceiptPO> getGatheringReceipt(String time) throws RemoteException; public ArrayList<GatheringReceiptPO> getGatheringReceiptByHallID(String organization) throws RemoteException; public ArrayList<GatheringReceiptPO> getGatheringReceiptByBoth(String organization, String time) throws RemoteException; // 增加一个DistributeOrder到本营业厅今日的文件中,一天也就一个 public boolean addDistributeReceipt(String organizationID, DistributeReceiptPO po) throws RemoteException; // 查照死机 public DriverPO getDriverInfo(String organizationID, String ID) throws RemoteException; // 增加一个司机到本营业厅 public boolean addDriver(String organizationID, DriverPO po) throws RemoteException; // 删除一个司机到本营业厅 public boolean deleteDriver(String organizationID, DriverPO po) throws RemoteException; // 修改本营业厅该司机信息 public boolean modifyDriver(String organizationID, DriverPO po) throws RemoteException; /** * Lizi 收款单 */ public ArrayList<GatheringReceiptPO> getSubmittedGatheringReceiptInfo() throws RemoteException; /** * Lizi 派件单 */ public ArrayList<DistributeReceiptPO> getSubmittedDistributeReceiptInfo() throws RemoteException; /** * Lizi 装车 */ public ArrayList<EnVehicleReceiptPO> getSubmittedEnVehicleReceiptInfo() throws RemoteException; /** * Lizi 到达单 */ public ArrayList<OrderAcceptReceiptPO> getSubmittedOrderAcceptReceiptInfo() throws RemoteException; public void saveDistributeReceiptInfo(DistributeReceiptPO po) throws RemoteException; public void saveOrderAcceptReceiptInfo(OrderAcceptReceiptPO po) throws RemoteException; public void saveEnVehicleReceiptInfo(EnVehicleReceiptPO po) throws RemoteException; public void saveGatheringReceiptInfo(GatheringReceiptPO po) throws RemoteException; // public boolean addDriverTime(String organizationID, String driverID) throws RemoteException; public ArrayList<OrganizationPO> getOrganizationInfos() throws RemoteException; public int getNumOfVehicles(String organizationID) throws RemoteException; public int getNumOfDrivers(String organizationID) throws RemoteException; public int getNumOfEnVechileReceipt(String organizationID) throws RemoteException; public int getNumOfOrderReceipt(String organizationID) throws RemoteException; public int getNumOfOrderDistributeReceipt(String organizationID) throws RemoteException; // // /** // * 返回待转运的订单的列表 // */ // public ArrayList<OrderPO> getTransferOrders() throws RemoteException; // // /** // * 返回待派送的订单的列表 // */ // public ArrayList<VehiclePO> getFreeVehicles() throws RemoteException; // // /** // * 生成装车单 // */ // public boolean addEnVehicleReceiptPO(EnVehicleReceiptPO po) throws // RemoteException; // // /** // * 获取收款汇总单 // */ // public ArrayList<GatheringReceiptPO> getGatheringReceiptPOs() throws // RemoteException; // // /** // * 增加收货单 // */ // public boolean addReceipt(OrderAcceptReceiptPO po) throws // RemoteException; // // /** // * 增加收款汇总单 // */ // // public boolean addGatheringReceipt(GatheringReceiptPO po); }
Disguiser-w/SE2
ELS_SERVICE/src/main/java/dataservice/businessdataservice/BusinessDataService.java
Java
gpl-2.0
5,469
package org.xmlvm.ios; import java.util.*; import org.xmlvm.XMLVMSkeletonOnly; @XMLVMSkeletonOnly public class CFGregorianDate { /* * Variables */ public int year; public byte month; public byte day; public byte hour; public byte minute; public double second; /* * Constructors */ /** Default constructor */ CFGregorianDate() {} /* * Instance methods */ /** * Boolean CFGregorianDateIsValid(CFGregorianDate gdate, CFOptionFlags unitFlags); */ public byte isValid(long unitFlags){ throw new RuntimeException("Stub"); } /** * CFAbsoluteTime CFGregorianDateGetAbsoluteTime(CFGregorianDate gdate, CFTimeZoneRef tz); */ public double getAbsoluteTime(NSTimeZone tz){ throw new RuntimeException("Stub"); } }
skyHALud/codenameone
Ports/iOSPort/xmlvm/src/ios/org/xmlvm/ios/CFGregorianDate.java
Java
gpl-2.0
755
/** * OpenKM, Open Document Management System (http://www.openkm.com) * Copyright (c) 2006-2017 Paco Avila & Josep Llort * <p> * No bytes were intentionally harmed during the development of this application. * <p> * 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. * <p> * 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. * <p> * 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.openkm.frontend.client.bean; import com.google.gwt.user.client.rpc.IsSerializable; /** * @author jllort * */ public class GWTUserConfig implements IsSerializable { private String user = ""; private String homePath = ""; private String homeType = ""; private String homeNode = ""; /** * GWTUserConfig */ public GWTUserConfig() { } public String getUser() { return user; } public void setUser(String user) { this.user = user; } public String getHomePath() { return homePath; } public void setHomePath(String homePath) { this.homePath = homePath; } public String getHomeType() { return homeType; } public void setHomeType(String homeType) { this.homeType = homeType; } public String getHomeNode() { return homeNode; } public void setHomeNode(String homeNode) { this.homeNode = homeNode; } }
Beau-M/document-management-system
src/main/java/com/openkm/frontend/client/bean/GWTUserConfig.java
Java
gpl-2.0
1,807
package com.avrgaming.civcraft.endgame; import java.util.ArrayList; import com.avrgaming.civcraft.main.CivGlobal; import com.avrgaming.civcraft.main.CivMessage; import com.avrgaming.civcraft.object.Civilization; import com.avrgaming.civcraft.object.Town; import com.avrgaming.civcraft.sessiondb.SessionEntry; import com.avrgaming.civcraft.structure.wonders.Wonder; public class EndConditionScience extends EndGameCondition { String techname; @Override public void onLoad() { techname = this.getString("tech"); } @Override public boolean check(Civilization civ) { if (!civ.hasTechnology(techname)) { return false; } if (civ.isAdminCiv()) { return false; } boolean hasGreatLibrary = false; for (Town town : civ.getTowns()) { if (town.getMotherCiv() != null) { continue; } for (Wonder wonder :town.getWonders()) { if (wonder.isActive()) { if (wonder.getConfigId().equals("w_greatlibrary")) { hasGreatLibrary = true; break; } } } if (hasGreatLibrary) { break; } } if (!hasGreatLibrary) { return false; } return true; } @Override public boolean finalWinCheck(Civilization civ) { Civilization rival = getMostAccumulatedBeakers(); if (rival != civ) { CivMessage.global(civ.getName()+" doesn't have enough beakers for a scientific victory. The rival civilization of "+rival.getName()+" has more!"); return false; } return true; } public Civilization getMostAccumulatedBeakers() { double most = 0; Civilization mostCiv = null; for (Civilization civ : CivGlobal.getCivs()) { double beakers = getExtraBeakersInCiv(civ); if (beakers > most) { most = beakers; mostCiv = civ; } } return mostCiv; } @Override public String getSessionKey() { return "endgame:science"; } @Override protected void onWarDefeat(Civilization civ) { /* remove any extra beakers we might have. */ CivGlobal.getSessionDB().delete_all(getBeakerSessionKey(civ)); civ.removeTech(techname); CivMessage.sendCiv(civ, "We were defeated while trying to achieve a science victory! We've lost all of our accumulated beakers and our victory tech!"); civ.save(); this.onFailure(civ); } public static String getBeakerSessionKey(Civilization civ) { return "endgame:sciencebeakers:"+civ.getId(); } public double getExtraBeakersInCiv(Civilization civ) { ArrayList<SessionEntry> entries = CivGlobal.getSessionDB().lookup(getBeakerSessionKey(civ)); if (entries.size() == 0) { return 0; } return Double.valueOf(entries.get(0).value); } public void addExtraBeakersToCiv(Civilization civ, double beakers) { ArrayList<SessionEntry> entries = CivGlobal.getSessionDB().lookup(getBeakerSessionKey(civ)); double current = 0; if (entries.size() == 0) { CivGlobal.getSessionDB().add(getBeakerSessionKey(civ), ""+beakers, civ.getId(), 0, 0); current += beakers; } else { current = Double.valueOf(entries.get(0).value); current += beakers; CivGlobal.getSessionDB().update(entries.get(0).request_id, entries.get(0).key, ""+current); } //DecimalFormat df = new DecimalFormat("#.#"); //CivMessage.sendCiv(civ, "Added "+df.format(beakers)+" beakers to our scientific victory! We now have "+df.format(current)+" beakers saved up."); } public static Double getBeakersFor(Civilization civ) { ArrayList<SessionEntry> entries = CivGlobal.getSessionDB().lookup(getBeakerSessionKey(civ)); if (entries.size() == 0) { return 0.0; } else { return Double.valueOf(entries.get(0).value); } } }
netizen539/civcraft
civcraft/src/com/avrgaming/civcraft/endgame/EndConditionScience.java
Java
gpl-2.0
3,584
/* * Copyright 2010 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. */ package org.visage.jdi.request; import org.visage.jdi.VisageThreadReference; import org.visage.jdi.VisageVirtualMachine; import org.visage.jdi.VisageWrapper; import com.sun.jdi.ObjectReference; import com.sun.jdi.ReferenceType; import com.sun.jdi.request.StepRequest; /** * * @author sundar */ public class VisageStepRequest extends VisageEventRequest implements StepRequest { public VisageStepRequest(VisageVirtualMachine visagevm, StepRequest underlying) { super(visagevm, underlying); } public void addClassExclusionFilter(String arg0) { underlying().addClassExclusionFilter(arg0); } public void addClassFilter(ReferenceType arg0) { underlying().addClassFilter(VisageWrapper.unwrap(arg0)); } public void addClassFilter(String arg0) { underlying().addClassFilter(arg0); } public void addInstanceFilter(ObjectReference ref) { underlying().addInstanceFilter(VisageWrapper.unwrap(ref)); } public int depth() { return underlying().depth(); } public int size() { return underlying().size(); } public VisageThreadReference thread() { return VisageWrapper.wrap(virtualMachine(), underlying().thread()); } @Override protected StepRequest underlying() { return (StepRequest) super.underlying(); } }
pron/visage-compiler
visagejdi/src/org/visage/jdi/request/VisageStepRequest.java
Java
gpl-2.0
2,405
package gr.softaware.lib_1_3.data.convert.csv; import java.util.List; /** * * @author siggouroglou * @param <T> A class that implements the CsvGenerationModel interface. */ final public class CsvGenerator<T extends CsvGenerationModel> { private final List<CsvGenerationModel> modelList; public CsvGenerator(List<T> modelList) { this.modelList = (List<CsvGenerationModel>)modelList; } public StringBuilder getContent() { return getContent("\t", "\\t"); } public StringBuilder getContent(String separator, String separatorAsString) { StringBuilder builder = new StringBuilder(); // First line contains the separator. builder.append("sep=").append(separatorAsString).append("\n"); // Get the header. if(!modelList.isEmpty()) { builder.append(modelList.get(0).toCsvFormattedHeader(separator)).append("\n"); } // Get the data. modelList.stream().forEach((model) -> { builder.append(model.toCsvFormattedRow(separator)).append("\n"); }); return builder; } }
siggouroglou/innovathens
webnew/src/main/java/gr/softaware/lib_1_3/data/convert/csv/CsvGenerator.java
Java
gpl-2.0
1,153
/* * This file is part of KITCard Reader. * Ⓒ 2012 Philipp Kern <phil@philkern.de> * * KITCard Reader 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. * * KITCard Reader 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 KITCard Reader. If not, see <http://www.gnu.org/licenses/>. */ package de.Ox539.kitcard.reader; /** * ReadCardTask: Read an NFC tag using the Wallet class asynchronously. * * This class provides the glue calling the Wallet class and passing * the information back to the Android UI layer. Detailed error * information is not provided yet. * * @author Philipp Kern <pkern@debian.org> */ import de.Ox539.kitcard.reader.Wallet.ReadCardResult; import android.nfc.Tag; import android.nfc.tech.MifareClassic; import android.os.AsyncTask; import android.widget.Toast; public class ReadCardTask extends AsyncTask<Tag, Integer, Pair<ReadCardResult, Wallet>> { private ScanActivity mActivity; public ReadCardTask(ScanActivity activity) { super(); this.mActivity = activity; } protected Pair<ReadCardResult, Wallet> doInBackground(Tag... tags) { MifareClassic card = null; try { card = MifareClassic.get(tags[0]); } catch (NullPointerException e) { /* Error while reading card. This problem occurs on HTC devices from the ONE series with Android Lollipop (status of June 2015) * Try to repair the tag. */ card = MifareClassic.get(MifareUtils.repairTag(tags[0])); } if(card == null) return new Pair<ReadCardResult, Wallet>(null, null); final Wallet wallet = new Wallet(card); final ReadCardResult result = wallet.readCard(); return new Pair<ReadCardResult, Wallet>(result, wallet); } protected void onPostExecute(Pair<ReadCardResult, Wallet> data) { ReadCardResult result = data.getValue0(); if(result == ReadCardResult.FAILURE) { // read failed Toast.makeText(mActivity, mActivity.getResources().getString(R.string.kitcard_read_failed), Toast.LENGTH_LONG).show(); return; } else if(result == ReadCardResult.OLD_STYLE_WALLET) { // old-style wallet encountered Toast.makeText(mActivity, mActivity.getResources().getString(R.string.kitcard_needs_reencode), Toast.LENGTH_LONG).show(); return; } final Wallet wallet = data.getValue1(); mActivity.updateCardNumber(wallet.getCardNumber()); mActivity.updateBalance(wallet.getCurrentBalance()); mActivity.updateLastTransaction(wallet.getLastTransactionValue()); mActivity.updateCardIssuer(wallet.getCardIssuer()); mActivity.updateCardType(wallet.getCardType()); } }
simontb/kitcard-reader
src/de/Ox539/kitcard/reader/ReadCardTask.java
Java
gpl-2.0
3,022
package gitmad.bitter.ui; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import gitmad.bitter.R; import gitmad.bitter.model.Comment; import gitmad.bitter.model.User; import java.util.Map; /** * Created by prabh on 10/19/2015. */ public class CommentAdapter extends ArrayAdapter<Comment> { private Comment[] comments; private Map<Comment, User> commentAuthors; public CommentAdapter(Context context, Comment[] comments, Map<Comment, User> commentAuthors) { super(context, 0, comments); // TODO is the zero here correct? this.comments = comments; this.commentAuthors = commentAuthors; } public View getView(int position, View convertView, ViewGroup parent) { Comment comment = comments[position]; if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(R.layout .view_comment, parent, false); } TextView userText = (TextView) convertView.findViewById(R.id.user_text); TextView commentText = (TextView) convertView.findViewById(R.id .comment_text); userText.setText(commentAuthors.get(comment).getName()); commentText.setText(comment.getText()); return convertView; } }
nareddyt/Bitter
app/src/main/java/gitmad/bitter/ui/CommentAdapter.java
Java
gpl-2.0
1,425
/* * Created on 5 Sep 2007 * * Copyright (c) 2004-2007 Paul John Leonard * * http://www.frinika.com * * This file is part of Frinika. * * Frinika 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. * Frinika 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 Frinika; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package com.frinika.tootX.midi; import java.util.logging.Level; import java.util.logging.Logger; import javax.sound.midi.InvalidMidiDataException; import javax.sound.midi.ShortMessage; public class MidiHashUtil { static public long hashValue(ShortMessage mess) { byte data[] = mess.getMessage(); long cmd = mess.getCommand(); if (cmd == ShortMessage.PITCH_BEND) { return ((long) data[0] << 8); } else { return (((long) data[0] << 8) + data[1]); } } static public void hashDisp(long hash) { long cntrl = hash & 0xFF; long cmd = (hash >> 8) & 0xFF; long chn = (hash >> 16) & 0xFF; System.out.println(chn + " " + cmd + " " + cntrl); } static ShortMessage reconstructShortMessage(long hash, ShortMessage mess) { if (mess == null) mess=new ShortMessage(); int status = (int) ((hash >> 8) & 0xFF); int data1 = (int) (hash & 0xFF); try { mess.setMessage(status, data1, 0); } catch (InvalidMidiDataException ex) { Logger.getLogger(MidiHashUtil.class.getName()).log(Level.SEVERE, null, ex); } return mess; } }
petersalomonsen/frinika
src/com/frinika/tootX/midi/MidiHashUtil.java
Java
gpl-2.0
2,069
package org.compiere.dbPort; import java.util.Collections; import java.util.List; /** * Native PostgreSQL (pass-through) implementation of {@link Convert} * * @author tsa * */ public final class Convert_PostgreSQL_Native extends Convert { @Override protected final List<String> convertStatement(final String sqlStatement) { return Collections.singletonList(sqlStatement); } }
klst-com/metasfresh
de.metas.adempiere.adempiere/base/src/main/java-legacy/org/compiere/dbPort/Convert_PostgreSQL_Native.java
Java
gpl-2.0
393
package mpicbg.spim.segmentation; import fiji.tool.SliceListener; import fiji.tool.SliceObserver; import ij.IJ; import ij.ImageJ; import ij.ImagePlus; import ij.ImageStack; import ij.WindowManager; import ij.gui.OvalRoi; import ij.gui.Overlay; import ij.gui.Roi; import ij.io.Opener; import ij.plugin.PlugIn; import ij.process.ByteProcessor; import ij.process.FloatProcessor; import ij.process.ImageProcessor; import ij.process.ShortProcessor; import java.awt.Button; import java.awt.Checkbox; import java.awt.Color; import java.awt.Font; import java.awt.Frame; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.Label; import java.awt.Rectangle; import java.awt.Scrollbar; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.AdjustmentEvent; import java.awt.event.AdjustmentListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.ArrayList; import java.util.List; import mpicbg.imglib.algorithm.gauss.GaussianConvolutionReal; import mpicbg.imglib.algorithm.math.LocalizablePoint; import mpicbg.imglib.algorithm.scalespace.DifferenceOfGaussianPeak; import mpicbg.imglib.algorithm.scalespace.DifferenceOfGaussianReal1; import mpicbg.imglib.algorithm.scalespace.SubpixelLocalization; import mpicbg.imglib.container.array.ArrayContainerFactory; import mpicbg.imglib.cursor.LocalizableByDimCursor; import mpicbg.imglib.cursor.LocalizableCursor; import mpicbg.imglib.image.Image; import mpicbg.imglib.image.ImageFactory; import mpicbg.imglib.image.display.imagej.ImageJFunctions; import mpicbg.imglib.multithreading.SimpleMultiThreading; import mpicbg.imglib.outofbounds.OutOfBoundsStrategyMirrorFactory; import mpicbg.imglib.outofbounds.OutOfBoundsStrategyValueFactory; import mpicbg.imglib.type.numeric.real.FloatType; import mpicbg.imglib.util.Util; import mpicbg.spim.io.IOFunctions; import mpicbg.spim.registration.ViewStructure; import mpicbg.spim.registration.detection.DetectionSegmentation; import net.imglib2.RandomAccess; import net.imglib2.exception.ImgLibException; import net.imglib2.img.ImagePlusAdapter; import net.imglib2.img.imageplus.FloatImagePlus; import net.imglib2.view.Views; import spim.process.fusion.FusionHelper; /** * An interactive tool for determining the required sigma and peak threshold * * @author Stephan Preibisch */ public class InteractiveDoG implements PlugIn { final int extraSize = 40; final int scrollbarSize = 1000; float sigma = 0.5f; float sigma2 = 0.5f; float threshold = 0.0001f; // steps per octave public static int standardSenstivity = 4; int sensitivity = standardSenstivity; float imageSigma = 0.5f; float sigmaMin = 0.5f; float sigmaMax = 10f; int sigmaInit = 300; float thresholdMin = 0.0001f; float thresholdMax = 1f; int thresholdInit = 500; double minIntensityImage = Double.NaN; double maxIntensityImage = Double.NaN; SliceObserver sliceObserver; RoiListener roiListener; ImagePlus imp; int channel = 0; Rectangle rectangle; Image<FloatType> img; FloatImagePlus< net.imglib2.type.numeric.real.FloatType > source; ArrayList<DifferenceOfGaussianPeak<FloatType>> peaks; Color originalColor = new Color( 0.8f, 0.8f, 0.8f ); Color inactiveColor = new Color( 0.95f, 0.95f, 0.95f ); public Rectangle standardRectangle; boolean isComputing = false; boolean isStarted = false; boolean enableSigma2 = false; boolean sigma2IsAdjustable = true; boolean lookForMinima = false; boolean lookForMaxima = true; public static enum ValueChange { SIGMA, THRESHOLD, SLICE, ROI, MINMAX, ALL } boolean isFinished = false; boolean wasCanceled = false; public boolean isFinished() { return isFinished; } public boolean wasCanceled() { return wasCanceled; } public double getInitialSigma() { return sigma; } public void setInitialSigma( final float value ) { sigma = value; sigmaInit = computeScrollbarPositionFromValue( sigma, sigmaMin, sigmaMax, scrollbarSize ); } public double getSigma2() { return sigma2; } public double getThreshold() { return threshold; } public void setThreshold( final float value ) { threshold = value; final double log1001 = Math.log10( scrollbarSize + 1); thresholdInit = (int)Math.round( 1001-Math.pow(10, -(((threshold - thresholdMin)/(thresholdMax-thresholdMin))*log1001) + log1001 ) ); } public boolean getSigma2WasAdjusted() { return enableSigma2; } public boolean getLookForMaxima() { return lookForMaxima; } public boolean getLookForMinima() { return lookForMinima; } public void setLookForMaxima( final boolean lookForMaxima ) { this.lookForMaxima = lookForMaxima; } public void setLookForMinima( final boolean lookForMinima ) { this.lookForMinima = lookForMinima; } public void setSigmaMax( final float sigmaMax ) { this.sigmaMax = sigmaMax; } public void setSigma2isAdjustable( final boolean state ) { sigma2IsAdjustable = state; } // for the case that it is needed again, we can save one conversion public FloatImagePlus< net.imglib2.type.numeric.real.FloatType > getConvertedImage() { return source; } public InteractiveDoG( final ImagePlus imp, final int channel ) { this.imp = imp; this.channel = channel; } public InteractiveDoG( final ImagePlus imp ) { this.imp = imp; } public InteractiveDoG() {} public void setMinIntensityImage( final double min ) { this.minIntensityImage = min; } public void setMaxIntensityImage( final double max ) { this.maxIntensityImage = max; } @Override public void run( String arg ) { if ( imp == null ) imp = WindowManager.getCurrentImage(); standardRectangle = new Rectangle( imp.getWidth()/4, imp.getHeight()/4, imp.getWidth()/2, imp.getHeight()/2 ); if ( imp.getType() == ImagePlus.COLOR_RGB || imp.getType() == ImagePlus.COLOR_256 ) { IJ.log( "Color images are not supported, please convert to 8, 16 or 32-bit grayscale" ); return; } Roi roi = imp.getRoi(); if ( roi == null ) { //IJ.log( "A rectangular ROI is required to define the area..." ); imp.setRoi( standardRectangle ); roi = imp.getRoi(); } if ( roi.getType() != Roi.RECTANGLE ) { IJ.log( "Only rectangular rois are supported..." ); return; } // copy the ImagePlus into an ArrayImage<FloatType> for faster access source = convertToFloat( imp, channel, 0, minIntensityImage, maxIntensityImage ); // show the interactive kit displaySliders(); // add listener to the imageplus slice slider sliceObserver = new SliceObserver( imp, new ImagePlusListener() ); // compute first version updatePreview( ValueChange.ALL ); isStarted = true; // check whenever roi is modified to update accordingly roiListener = new RoiListener(); imp.getCanvas().addMouseListener( roiListener ); } /** * Updates the Preview with the current parameters (sigma, threshold, roi, slicenumber) * * @param change - what did change */ protected void updatePreview( final ValueChange change ) { // check if Roi changed boolean roiChanged = false; Roi roi = imp.getRoi(); if ( roi == null || roi.getType() != Roi.RECTANGLE ) { imp.setRoi( new Rectangle( standardRectangle ) ); roi = imp.getRoi(); roiChanged = true; } final Rectangle rect = roi.getBounds(); if ( roiChanged || img == null || change == ValueChange.SLICE || rect.getMinX() != rectangle.getMinX() || rect.getMaxX() != rectangle.getMaxX() || rect.getMinY() != rectangle.getMinY() || rect.getMaxY() != rectangle.getMaxY() ) { rectangle = rect; img = extractImage( source, rectangle, extraSize ); roiChanged = true; } // if we got some mouse click but the ROI did not change we can return if ( !roiChanged && change == ValueChange.ROI ) { isComputing = false; return; } // compute the Difference Of Gaussian if necessary if ( peaks == null || roiChanged || change == ValueChange.SIGMA || change == ValueChange.SLICE || change == ValueChange.ALL ) { // // Compute the Sigmas for the gaussian folding // final float k, K_MIN1_INV; final float[] sigma, sigmaDiff; if ( enableSigma2 ) { sigma = new float[ 2 ]; sigma[ 0 ] = this.sigma; sigma[ 1 ] = this.sigma2; k = sigma[ 1 ] / sigma[ 0 ]; K_MIN1_INV = DetectionSegmentation.computeKWeight( k ); sigmaDiff = DetectionSegmentation.computeSigmaDiff( sigma, imageSigma ); } else { k = (float)DetectionSegmentation.computeK( sensitivity ); K_MIN1_INV = DetectionSegmentation.computeKWeight( k ); sigma = DetectionSegmentation.computeSigma( k, this.sigma ); sigmaDiff = DetectionSegmentation.computeSigmaDiff( sigma, imageSigma ); } // the upper boundary this.sigma2 = sigma[ 1 ]; final DifferenceOfGaussianReal1<FloatType> dog = new DifferenceOfGaussianReal1<FloatType>( img, new OutOfBoundsStrategyValueFactory<FloatType>(), sigmaDiff[ 0 ], sigmaDiff[ 1 ], thresholdMin/4, K_MIN1_INV ); dog.setKeepDoGImage( true ); dog.process(); final SubpixelLocalization<FloatType> subpixel = new SubpixelLocalization<FloatType>( dog.getDoGImage(), dog.getPeaks() ); subpixel.process(); peaks = dog.getPeaks(); } // extract peaks to show Overlay o = imp.getOverlay(); if ( o == null ) { o = new Overlay(); imp.setOverlay( o ); } o.clear(); for ( final DifferenceOfGaussianPeak<FloatType> peak : peaks ) { if ( ( peak.isMax() && lookForMaxima ) || ( peak.isMin() && lookForMinima ) ) { final float x = peak.getPosition( 0 ); final float y = peak.getPosition( 1 ); if ( Math.abs( peak.getValue().get() ) > threshold && x >= extraSize/2 && y >= extraSize/2 && x < rect.width+extraSize/2 && y < rect.height+extraSize/2 ) { final OvalRoi or = new OvalRoi( Util.round( x - sigma ) + rect.x - extraSize/2, Util.round( y - sigma ) + rect.y - extraSize/2, Util.round( sigma+sigma2 ), Util.round( sigma+sigma2 ) ); if ( peak.isMax() ) or.setStrokeColor( Color.green ); else if ( peak.isMin() ) or.setStrokeColor( Color.red ); o.add( or ); } } } imp.updateAndDraw(); isComputing = false; } public static float computeSigma2( final float sigma1, final int sensitivity ) { final float k = (float)DetectionSegmentation.computeK( sensitivity ); final float[] sigma = DetectionSegmentation.computeSigma( k, sigma1 ); return sigma[ 1 ]; } /** * Extract the current 2d region of interest from the souce image * * @param source - the source image, a {@link Image} which is a copy of the {@link ImagePlus} * @param rectangle - the area of interest * @param extraSize - the extra size around so that detections at the border of the roi are not messed up * @return */ protected Image<FloatType> extractImage( final FloatImagePlus< net.imglib2.type.numeric.real.FloatType > source, final Rectangle rectangle, final int extraSize ) { final Image<FloatType> img = new ImageFactory<FloatType>( new FloatType(), new ArrayContainerFactory() ).createImage( new int[]{ rectangle.width+extraSize, rectangle.height+extraSize } ); final int offsetX = rectangle.x - extraSize/2; final int offsetY = rectangle.y - extraSize/2; final int[] location = new int[ source.numDimensions() ]; if ( location.length > 2 ) location[ 2 ] = (imp.getCurrentSlice()-1)/imp.getNChannels(); final LocalizableCursor<FloatType> cursor = img.createLocalizableCursor(); final RandomAccess<net.imglib2.type.numeric.real.FloatType> positionable; if ( offsetX >= 0 && offsetY >= 0 && offsetX + img.getDimension( 0 ) < source.dimension( 0 ) && offsetY + img.getDimension( 1 ) < source.dimension( 1 ) ) { // it is completely inside so we need no outofbounds for copying positionable = source.randomAccess(); } else { positionable = Views.extendMirrorSingle( source ).randomAccess(); } while ( cursor.hasNext() ) { cursor.fwd(); cursor.getPosition( location ); location[ 0 ] += offsetX; location[ 1 ] += offsetY; positionable.setPosition( location ); cursor.getType().set( positionable.get().get() ); } return img; } /** * Normalize and make a copy of the {@link ImagePlus} into an {@link Image}&gt;FloatType&lt; for faster access when copying the slices * * @param imp - the {@link ImagePlus} input image * @return - the normalized copy [0...1] */ public static FloatImagePlus< net.imglib2.type.numeric.real.FloatType > convertToFloat( final ImagePlus imp, int channel, int timepoint ) { return convertToFloat( imp, channel, timepoint, Double.NaN, Double.NaN ); } public static FloatImagePlus< net.imglib2.type.numeric.real.FloatType > convertToFloat( final ImagePlus imp, int channel, int timepoint, final double min, final double max ) { // stupid 1-offset of imagej channel++; timepoint++; final int h = imp.getHeight(); final int w = imp.getWidth(); final ArrayList< float[] > img = new ArrayList< float[] >(); if ( imp.getProcessor() instanceof FloatProcessor ) { for ( int z = 0; z < imp.getNSlices(); ++z ) img.add( ( (float[])imp.getStack().getProcessor( imp.getStackIndex( channel, z + 1, timepoint ) ).getPixels() ).clone() ); } else if ( imp.getProcessor() instanceof ByteProcessor ) { for ( int z = 0; z < imp.getNSlices(); ++z ) { final byte[] pixels = (byte[])imp.getStack().getProcessor( imp.getStackIndex( channel, z + 1, timepoint ) ).getPixels(); final float[] pixelsF = new float[ pixels.length ]; for ( int i = 0; i < pixels.length; ++i ) pixelsF[ i ] = pixels[ i ] & 0xff; img.add( pixelsF ); } } else if ( imp.getProcessor() instanceof ShortProcessor ) { for ( int z = 0; z < imp.getNSlices(); ++z ) { final short[] pixels = (short[])imp.getStack().getProcessor( imp.getStackIndex( channel, z + 1, timepoint ) ).getPixels(); final float[] pixelsF = new float[ pixels.length ]; for ( int i = 0; i < pixels.length; ++i ) pixelsF[ i ] = pixels[ i ] & 0xffff; img.add( pixelsF ); } } else // some color stuff or so { for ( int z = 0; z < imp.getNSlices(); ++z ) { final ImageProcessor ip = imp.getStack().getProcessor( imp.getStackIndex( channel, z + 1, timepoint ) ); final float[] pixelsF = new float[ w * h ]; int i = 0; for ( int y = 0; y < h; ++y ) for ( int x = 0; x < w; ++x ) pixelsF[ i++ ] = ip.getPixelValue( x, y ); img.add( pixelsF ); } } final FloatImagePlus< net.imglib2.type.numeric.real.FloatType > i = createImgLib2( img, w, h ); if ( Double.isNaN( min ) || Double.isNaN( max ) || Double.isInfinite( min ) || Double.isInfinite( max ) || min == max ) FusionHelper.normalizeImage( i ); else FusionHelper.normalizeImage( i, (float)min, (float)max ); return i; } public static FloatImagePlus< net.imglib2.type.numeric.real.FloatType > createImgLib2( final List< float[] > img, final int w, final int h ) { final ImagePlus imp; if ( img.size() > 1 ) { final ImageStack stack = new ImageStack( w, h ); for ( int z = 0; z < img.size(); ++z ) stack.addSlice( new FloatProcessor( w, h, img.get( z ) ) ); imp = new ImagePlus( "ImgLib2 FloatImagePlus (3d)", stack ); } else { imp = new ImagePlus( "ImgLib2 FloatImagePlus (2d)", new FloatProcessor( w, h, img.get( 0 ) ) ); } return ImagePlusAdapter.wrapFloat( imp ); } /** * Instantiates the panel for adjusting the paramters */ protected void displaySliders() { final Frame frame = new Frame("Adjust Difference-of-Gaussian Values"); frame.setSize( 400, 330 ); /* Instantiation */ final GridBagLayout layout = new GridBagLayout(); final GridBagConstraints c = new GridBagConstraints(); final Scrollbar sigma1 = new Scrollbar ( Scrollbar.HORIZONTAL, sigmaInit, 10, 0, 10 + scrollbarSize ); this.sigma = computeValueFromScrollbarPosition( sigmaInit, sigmaMin, sigmaMax, scrollbarSize); final Scrollbar threshold = new Scrollbar ( Scrollbar.HORIZONTAL, thresholdInit, 10, 0, 10 + scrollbarSize ); final float log1001 = (float)Math.log10( scrollbarSize + 1); this.threshold = thresholdMin + ( (log1001 - (float)Math.log10(1001-thresholdInit))/log1001 ) * (thresholdMax-thresholdMin); this.sigma2 = computeSigma2( this.sigma, this.sensitivity ); final int sigma2init = computeScrollbarPositionFromValue( this.sigma2, sigmaMin, sigmaMax, scrollbarSize ); final Scrollbar sigma2 = new Scrollbar ( Scrollbar.HORIZONTAL, sigma2init, 10, 0, 10 + scrollbarSize ); final Label sigmaText1 = new Label( "Sigma 1 = " + this.sigma, Label.CENTER ); final Label sigmaText2 = new Label( "Sigma 2 = " + this.sigma2, Label.CENTER ); final Label thresholdText = new Label( "Threshold = " + this.threshold, Label.CENTER ); final Button apply = new Button( "Apply to Stack (will take some time)" ); final Button button = new Button( "Done" ); final Button cancel = new Button( "Cancel" ); final Checkbox sigma2Enable = new Checkbox( "Enable Manual Adjustment of Sigma 2 ", enableSigma2 ); final Checkbox min = new Checkbox( "Look for Minima (red)", lookForMinima ); final Checkbox max = new Checkbox( "Look for Maxima (green)", lookForMaxima ); /* Location */ frame.setLayout( layout ); c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 0; c.gridy = 0; c.weightx = 1; frame.add ( sigma1, c ); ++c.gridy; frame.add( sigmaText1, c ); ++c.gridy; frame.add ( sigma2, c ); ++c.gridy; frame.add( sigmaText2, c ); ++c.gridy; c.insets = new Insets(0,65,0,65); frame.add( sigma2Enable, c ); ++c.gridy; c.insets = new Insets(10,0,0,0); frame.add ( threshold, c ); c.insets = new Insets(0,0,0,0); ++c.gridy; frame.add( thresholdText, c ); ++c.gridy; c.insets = new Insets(0,130,0,75); frame.add( min, c ); ++c.gridy; c.insets = new Insets(0,125,0,75); frame.add( max, c ); ++c.gridy; c.insets = new Insets(0,75,0,75); frame.add( apply, c ); ++c.gridy; c.insets = new Insets(10,150,0,150); frame.add( button, c ); ++c.gridy; c.insets = new Insets(10,150,0,150); frame.add( cancel, c ); /* Configuration */ sigma1.addAdjustmentListener( new SigmaListener( sigmaText1, sigmaMin, sigmaMax, scrollbarSize, sigma1, sigma2, sigmaText2 ) ); sigma2.addAdjustmentListener( new Sigma2Listener( sigmaMin, sigmaMax, scrollbarSize, sigma2, sigmaText2 ) ); threshold.addAdjustmentListener( new ThresholdListener( thresholdText, thresholdMin, thresholdMax ) ); button.addActionListener( new FinishedButtonListener( frame, false ) ); cancel.addActionListener( new FinishedButtonListener( frame, true ) ); apply.addActionListener( new ApplyButtonListener() ); min.addItemListener( new MinListener() ); max.addItemListener( new MaxListener() ); sigma2Enable.addItemListener( new EnableListener( sigma2, sigmaText2 ) ); if ( !sigma2IsAdjustable ) sigma2Enable.setEnabled( false ); frame.addWindowListener( new FrameListener( frame ) ); frame.setVisible( true ); originalColor = sigma2.getBackground(); sigma2.setBackground( inactiveColor ); sigmaText1.setFont( sigmaText1.getFont().deriveFont( Font.BOLD ) ); thresholdText.setFont( thresholdText.getFont().deriveFont( Font.BOLD ) ); } protected class EnableListener implements ItemListener { final Scrollbar sigma2; final Label sigmaText2; public EnableListener( final Scrollbar sigma2, final Label sigmaText2 ) { this.sigmaText2 = sigmaText2; this.sigma2 = sigma2; } @Override public void itemStateChanged( final ItemEvent arg0 ) { if ( arg0.getStateChange() == ItemEvent.DESELECTED ) { sigmaText2.setFont( sigmaText2.getFont().deriveFont( Font.PLAIN ) ); sigma2.setBackground( inactiveColor ); enableSigma2 = false; } else if ( arg0.getStateChange() == ItemEvent.SELECTED ) { sigmaText2.setFont( sigmaText2.getFont().deriveFont( Font.BOLD ) ); sigma2.setBackground( originalColor ); enableSigma2 = true; } } } protected class MinListener implements ItemListener { @Override public void itemStateChanged( final ItemEvent arg0 ) { boolean oldState = lookForMinima; if ( arg0.getStateChange() == ItemEvent.DESELECTED ) lookForMinima = false; else if ( arg0.getStateChange() == ItemEvent.SELECTED ) lookForMinima = true; if ( lookForMinima != oldState ) { while ( isComputing ) SimpleMultiThreading.threadWait( 10 ); updatePreview( ValueChange.MINMAX ); } } } protected class MaxListener implements ItemListener { @Override public void itemStateChanged( final ItemEvent arg0 ) { boolean oldState = lookForMaxima; if ( arg0.getStateChange() == ItemEvent.DESELECTED ) lookForMaxima = false; else if ( arg0.getStateChange() == ItemEvent.SELECTED ) lookForMaxima = true; if ( lookForMaxima != oldState ) { while ( isComputing ) SimpleMultiThreading.threadWait( 10 ); updatePreview( ValueChange.MINMAX ); } } } /** * Tests whether the ROI was changed and will recompute the preview * * @author Stephan Preibisch */ protected class RoiListener implements MouseListener { @Override public void mouseClicked(MouseEvent e) {} @Override public void mouseEntered(MouseEvent e) {} @Override public void mouseExited(MouseEvent e) {} @Override public void mousePressed(MouseEvent e) {} @Override public void mouseReleased( final MouseEvent e ) { // here the ROI might have been modified, let's test for that final Roi roi = imp.getRoi(); if ( roi == null || roi.getType() != Roi.RECTANGLE ) return; while ( isComputing ) SimpleMultiThreading.threadWait( 10 ); updatePreview( ValueChange.ROI ); } } protected class ApplyButtonListener implements ActionListener { @Override public void actionPerformed( final ActionEvent arg0 ) { ImagePlus imp; try { imp = source.getImagePlus(); } catch (ImgLibException e) { imp = null; e.printStackTrace(); } // convert ImgLib2 image to ImgLib1 image via the imageplus final Image< FloatType > source = ImageJFunctions.wrapFloat( imp ); IOFunctions.println( "Computing DoG ... " ); // test the parameters on the complete stack final ArrayList<DifferenceOfGaussianPeak<FloatType>> peaks = DetectionSegmentation.extractBeadsLaPlaceImgLib( source, new OutOfBoundsStrategyMirrorFactory<FloatType>(), imageSigma, sigma, sigma2, threshold, threshold/4, lookForMaxima, lookForMinima, ViewStructure.DEBUG_MAIN ); IOFunctions.println( "Drawing DoG result ... " ); // display as extra image Image<FloatType> detections = source.createNewImage(); final LocalizableByDimCursor<FloatType> c = detections.createLocalizableByDimCursor(); for ( final DifferenceOfGaussianPeak<FloatType> peak : peaks ) { final LocalizablePoint p = new LocalizablePoint( new float[]{ peak.getSubPixelPosition( 0 ), peak.getSubPixelPosition( 1 ), peak.getSubPixelPosition( 2 ) } ); c.setPosition( p ); c.getType().set( 1 ); } IOFunctions.println( "Convolving DoG result ... " ); final GaussianConvolutionReal<FloatType> gauss = new GaussianConvolutionReal<FloatType>( detections, new OutOfBoundsStrategyValueFactory<FloatType>(), 2 ); gauss.process(); detections = gauss.getResult(); IOFunctions.println( "Showing DoG result ... " ); ImageJFunctions.show( detections ); } } protected class FinishedButtonListener implements ActionListener { final Frame parent; final boolean cancel; public FinishedButtonListener( Frame parent, final boolean cancel ) { this.parent = parent; this.cancel = cancel; } @Override public void actionPerformed( final ActionEvent arg0 ) { wasCanceled = cancel; close( parent, sliceObserver, imp, roiListener ); } } protected class FrameListener extends WindowAdapter { final Frame parent; public FrameListener( Frame parent ) { super(); this.parent = parent; } @Override public void windowClosing (WindowEvent e) { close( parent, sliceObserver, imp, roiListener ); } } protected final void close( final Frame parent, final SliceObserver sliceObserver, final ImagePlus imp, final RoiListener roiListener ) { if ( parent != null ) parent.dispose(); if ( sliceObserver != null ) sliceObserver.unregister(); if ( imp != null ) { if ( roiListener != null ) imp.getCanvas().removeMouseListener( roiListener ); imp.getOverlay().clear(); imp.updateAndDraw(); } isFinished = true; } protected class Sigma2Listener implements AdjustmentListener { final float min, max; final int scrollbarSize; final Scrollbar sigmaScrollbar2; final Label sigma2Label; public Sigma2Listener( final float min, final float max, final int scrollbarSize, final Scrollbar sigmaScrollbar2, final Label sigma2Label ) { this.min = min; this.max = max; this.scrollbarSize = scrollbarSize; this.sigmaScrollbar2 = sigmaScrollbar2; this.sigma2Label = sigma2Label; } @Override public void adjustmentValueChanged( final AdjustmentEvent event ) { if ( enableSigma2 ) { sigma2 = computeValueFromScrollbarPosition( event.getValue(), min, max, scrollbarSize ); if ( sigma2 < sigma ) { sigma2 = sigma + 0.001f; sigmaScrollbar2.setValue( computeScrollbarPositionFromValue( sigma2, min, max, scrollbarSize ) ); } sigma2Label.setText( "Sigma 2 = " + sigma2 ); if ( !event.getValueIsAdjusting() ) { while ( isComputing ) { SimpleMultiThreading.threadWait( 10 ); } updatePreview( ValueChange.SIGMA ); } } else { // if no manual adjustment simply reset it sigmaScrollbar2.setValue( computeScrollbarPositionFromValue( sigma2, min, max, scrollbarSize ) ); } } } protected class SigmaListener implements AdjustmentListener { final Label label; final float min, max; final int scrollbarSize; final Scrollbar sigmaScrollbar1; final Scrollbar sigmaScrollbar2; final Label sigmaText2; public SigmaListener( final Label label, final float min, final float max, final int scrollbarSize, final Scrollbar sigmaScrollbar1, final Scrollbar sigmaScrollbar2, final Label sigmaText2 ) { this.label = label; this.min = min; this.max = max; this.scrollbarSize = scrollbarSize; this.sigmaScrollbar1 = sigmaScrollbar1; this.sigmaScrollbar2 = sigmaScrollbar2; this.sigmaText2 = sigmaText2; } @Override public void adjustmentValueChanged( final AdjustmentEvent event ) { sigma = computeValueFromScrollbarPosition( event.getValue(), min, max, scrollbarSize ); if ( !enableSigma2 ) { sigma2 = computeSigma2( sigma, sensitivity ); sigmaText2.setText( "Sigma 2 = " + sigma2 ); sigmaScrollbar2.setValue( computeScrollbarPositionFromValue( sigma2, min, max, scrollbarSize ) ); } else if ( sigma > sigma2 ) { sigma = sigma2 - 0.001f; sigmaScrollbar1.setValue( computeScrollbarPositionFromValue( sigma, min, max, scrollbarSize ) ); } label.setText( "Sigma 1 = " + sigma ); if ( !event.getValueIsAdjusting() ) { while ( isComputing ) { SimpleMultiThreading.threadWait( 10 ); } updatePreview( ValueChange.SIGMA ); } } } protected static float computeValueFromScrollbarPosition( final int scrollbarPosition, final float min, final float max, final int scrollbarSize ) { return min + (scrollbarPosition/(float)scrollbarSize) * (max-min); } protected static int computeScrollbarPositionFromValue( final float sigma, final float min, final float max, final int scrollbarSize ) { return Util.round( ((sigma - min)/(max-min)) * scrollbarSize ); } protected class ThresholdListener implements AdjustmentListener { final Label label; final float min, max; final float log1001 = (float)Math.log10(1001); public ThresholdListener( final Label label, final float min, final float max ) { this.label = label; this.min = min; this.max = max; } @Override public void adjustmentValueChanged( final AdjustmentEvent event ) { threshold = min + ( (log1001 - (float)Math.log10(1001-event.getValue()))/log1001 ) * (max-min); label.setText( "Threshold = " + threshold ); if ( !isComputing ) { updatePreview( ValueChange.THRESHOLD ); } else if ( !event.getValueIsAdjusting() ) { while ( isComputing ) { SimpleMultiThreading.threadWait( 10 ); } updatePreview( ValueChange.THRESHOLD ); } } } protected class ImagePlusListener implements SliceListener { @Override public void sliceChanged(ImagePlus arg0) { if ( isStarted ) { while ( isComputing ) { SimpleMultiThreading.threadWait( 10 ); } updatePreview( ValueChange.SLICE ); } } } public static void main( String[] args ) { new ImageJ(); ImagePlus imp = new Opener().openImage( "/home/preibisch/Documents/Microscopy/SPIM/Harvard/f11e6/exp3/img_Ch0_Angle0.tif.zip" ); //ImagePlus imp = new Opener().openImage( "D:/Documents and Settings/Stephan/My Documents/Downloads/1-315--0.08-isotropic-subvolume/1-315--0.08-isotropic-subvolume.tif" ); imp.show(); imp.setSlice( 27 ); imp.setRoi( imp.getWidth()/4, imp.getHeight()/4, imp.getWidth()/2, imp.getHeight()/2 ); new InteractiveDoG().run( null ); } }
psteinb/SPIM_Registration
src/main/java/mpicbg/spim/segmentation/InteractiveDoG.java
Java
gpl-2.0
30,536
/* * Copyright (c) 2003, 2015, 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. */ package test.auctionportal; import static com.sun.org.apache.xerces.internal.jaxp.JAXPConstants.JAXP_SCHEMA_LANGUAGE; import static com.sun.org.apache.xerces.internal.jaxp.JAXPConstants.JAXP_SCHEMA_SOURCE; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.math.BigInteger; import java.nio.file.Paths; import java.util.GregorianCalendar; import static javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI; import javax.xml.datatype.DatatypeConstants; import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.Duration; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import javax.xml.transform.dom.DOMResult; import javax.xml.transform.dom.DOMSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import javax.xml.validation.Validator; import jaxp.library.JAXPFileReadOnlyBaseTest; import static jaxp.library.JAXPTestUtilities.bomStream; import org.testng.annotations.Test; import org.w3c.dom.Attr; import org.w3c.dom.DOMConfiguration; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.w3c.dom.TypeInfo; import org.w3c.dom.bootstrap.DOMImplementationRegistry; import org.w3c.dom.ls.DOMImplementationLS; import org.w3c.dom.ls.LSSerializer; import static test.auctionportal.HiBidConstants.PORTAL_ACCOUNT_NS; import static test.auctionportal.HiBidConstants.XML_DIR; /** * This is the user controller class for the Auction portal HiBid.com. */ public class AuctionController extends JAXPFileReadOnlyBaseTest { /** * Check for DOMErrorHandler handling DOMError. Before fix of bug 4890927 * DOMConfiguration.setParameter("well-formed",true) throws an exception. * * @throws Exception If any errors occur. */ @Test(groups = {"readLocalFiles"}) public void testCreateNewItem2Sell() throws Exception { String xmlFile = XML_DIR + "novelsInvalid.xml"; Document document = DocumentBuilderFactory.newInstance() .newDocumentBuilder().parse(xmlFile); document.getDomConfig().setParameter("well-formed", true); DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance(); DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS"); MyDOMOutput domOutput = new MyDOMOutput(); domOutput.setByteStream(System.out); LSSerializer writer = impl.createLSSerializer(); writer.write(document, domOutput); } /** * Check for DOMErrorHandler handling DOMError. Before fix of bug 4896132 * test throws DOM Level 1 node error. * * @throws Exception If any errors occur. */ @Test(groups = {"readLocalFiles"}) public void testCreateNewItem2SellRetry() throws Exception { String xmlFile = XML_DIR + "accountInfo.xml"; DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); Document document = dbf.newDocumentBuilder().parse(xmlFile); DOMConfiguration domConfig = document.getDomConfig(); MyDOMErrorHandler errHandler = new MyDOMErrorHandler(); domConfig.setParameter("error-handler", errHandler); DOMImplementationLS impl = (DOMImplementationLS) DOMImplementationRegistry.newInstance() .getDOMImplementation("LS"); LSSerializer writer = impl.createLSSerializer(); MyDOMOutput domoutput = new MyDOMOutput(); domoutput.setByteStream(System.out); writer.write(document, domoutput); document.normalizeDocument(); writer.write(document, domoutput); assertFalse(errHandler.isError()); } /** * Check if setting the attribute to be of type ID works. This will affect * the Attr.isID method according to the spec. * * @throws Exception If any errors occur. */ @Test(groups = {"readLocalFiles"}) public void testCreateID() throws Exception { String xmlFile = XML_DIR + "accountInfo.xml"; DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); Document document = dbf.newDocumentBuilder().parse(xmlFile); Element account = (Element)document .getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "Account").item(0); account.setIdAttributeNS(PORTAL_ACCOUNT_NS, "accountID", true); Attr aID = account.getAttributeNodeNS(PORTAL_ACCOUNT_NS, "accountID"); assertTrue(aID.isId()); } /** * Check the user data on the node. * * @throws Exception If any errors occur. */ @Test(groups = {"readLocalFiles"}) public void testCheckingUserData() throws Exception { String xmlFile = XML_DIR + "accountInfo.xml"; DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder docBuilder = dbf.newDocumentBuilder(); Document document = docBuilder.parse(xmlFile); Element account = (Element)document.getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "Account").item(0); assertEquals(account.getNodeName(), "acc:Account"); Element firstName = (Element) document.getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "FirstName").item(0); assertEquals(firstName.getNodeName(), "FirstName"); Document doc1 = docBuilder.newDocument(); Element someName = doc1.createElement("newelem"); someName.setUserData("mykey", "dd", (operation, key, data, src, dst) -> { System.err.println("In UserDataHandler" + key); System.out.println("In UserDataHandler"); }); Element impAccount = (Element)document.importNode(someName, true); assertEquals(impAccount.getNodeName(), "newelem"); document.normalizeDocument(); String data = (someName.getUserData("mykey")).toString(); assertEquals(data, "dd"); } /** * Check the UTF-16 XMLEncoding xml file. * * @throws Exception If any errors occur. * @see <a href="content/movies.xml">movies.xml</a> */ @Test(groups = {"readLocalFiles"}) public void testCheckingEncoding() throws Exception { // Note since movies.xml is UTF-16 encoding. We're not using stanard XML // file suffix. String xmlFile = XML_DIR + "movies.xml.data"; try (InputStream source = bomStream("UTF-16", xmlFile)) { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); Document document = dbf.newDocumentBuilder().parse(source); assertEquals(document.getXmlEncoding(), "UTF-16"); assertEquals(document.getXmlStandalone(), true); } } /** * Check validation API features. A schema which is including in Bug 4909119 * used to be testing for the functionalities. * * @throws Exception If any errors occur. * @see <a href="content/userDetails.xsd">userDetails.xsd</a> */ @Test(groups = {"readLocalFiles"}) public void testGetOwnerInfo() throws Exception { String schemaFile = XML_DIR + "userDetails.xsd"; String xmlFile = XML_DIR + "userDetails.xml"; try(FileInputStream fis = new FileInputStream(xmlFile)) { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI); SchemaFactory schemaFactory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI); Schema schema = schemaFactory.newSchema(Paths.get(schemaFile).toFile()); Validator validator = schema.newValidator(); MyErrorHandler eh = new MyErrorHandler(); validator.setErrorHandler(eh); DocumentBuilder docBuilder = dbf.newDocumentBuilder(); docBuilder.setErrorHandler(eh); Document document = docBuilder.parse(fis); DOMResult dResult = new DOMResult(); DOMSource domSource = new DOMSource(document); validator.validate(domSource, dResult); assertFalse(eh.isAnyError()); } } /** * Check grammar caching with imported schemas. * * @throws Exception If any errors occur. * @see <a href="content/coins.xsd">coins.xsd</a> * @see <a href="content/coinsImportMe.xsd">coinsImportMe.xsd</a> */ @Test(groups = {"readLocalFiles"}) public void testGetOwnerItemList() throws Exception { String xsdFile = XML_DIR + "coins.xsd"; String xmlFile = XML_DIR + "coins.xml"; try(FileInputStream fis = new FileInputStream(xmlFile)) { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI); dbf.setValidating(false); SchemaFactory schemaFactory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI); Schema schema = schemaFactory.newSchema(new File(((xsdFile)))); MyErrorHandler eh = new MyErrorHandler(); Validator validator = schema.newValidator(); validator.setErrorHandler(eh); DocumentBuilder docBuilder = dbf.newDocumentBuilder(); Document document = docBuilder.parse(fis); validator.validate(new DOMSource(document), new DOMResult()); assertFalse(eh.isAnyError()); } } /** * Check for the same imported schemas but will use SAXParserFactory and try * parsing using the SAXParser. SCHEMA_SOURCE attribute is using for this * test. * * @throws Exception If any errors occur. * @see <a href="content/coins.xsd">coins.xsd</a> * @see <a href="content/coinsImportMe.xsd">coinsImportMe.xsd</a> */ @Test(groups = {"readLocalFiles"}) public void testGetOwnerItemList1() throws Exception { String xsdFile = XML_DIR + "coins.xsd"; String xmlFile = XML_DIR + "coins.xml"; SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setNamespaceAware(true); spf.setValidating(true); SAXParser sp = spf.newSAXParser(); sp.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI); sp.setProperty(JAXP_SCHEMA_SOURCE, xsdFile); MyErrorHandler eh = new MyErrorHandler(); sp.parse(new File(xmlFile), eh); assertFalse(eh.isAnyError()); } /** * Check usage of javax.xml.datatype.Duration class. * * @throws Exception If any errors occur. */ @Test(groups = {"readLocalFiles"}) public void testGetItemDuration() throws Exception { String xmlFile = XML_DIR + "itemsDuration.xml"; DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); Document document = dbf.newDocumentBuilder().parse(xmlFile); Element durationElement = (Element) document.getElementsByTagName("sellDuration").item(0); NodeList childList = durationElement.getChildNodes(); for (int i = 0; i < childList.getLength(); i++) { System.out.println("child " + i + childList.item(i)); } Duration duration = DatatypeFactory.newInstance().newDuration("P365D"); Duration sellDuration = DatatypeFactory.newInstance().newDuration(childList.item(0).getNodeValue()); assertFalse(sellDuration.isShorterThan(duration)); assertFalse(sellDuration.isLongerThan(duration)); assertEquals(sellDuration.getField(DatatypeConstants.DAYS), BigInteger.valueOf(365)); assertEquals(sellDuration.normalizeWith(new GregorianCalendar(1999, 2, 22)), duration); Duration myDuration = sellDuration.add(duration); assertEquals(myDuration.normalizeWith(new GregorianCalendar(2003, 2, 22)), DatatypeFactory.newInstance().newDuration("P730D")); } /** * Check usage of TypeInfo interface introduced in DOM L3. * * @throws Exception If any errors occur. */ @Test(groups = {"readLocalFiles"}) public void testGetTypeInfo() throws Exception { String xmlFile = XML_DIR + "accountInfo.xml"; DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setValidating(true); dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI); DocumentBuilder docBuilder = dbf.newDocumentBuilder(); docBuilder.setErrorHandler(new MyErrorHandler()); Document document = docBuilder.parse(xmlFile); Element userId = (Element)document.getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "UserID").item(0); TypeInfo typeInfo = userId.getSchemaTypeInfo(); assertTrue(typeInfo.getTypeName().equals("nonNegativeInteger")); assertTrue(typeInfo.getTypeNamespace().equals(W3C_XML_SCHEMA_NS_URI)); Element role = (Element)document.getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "Role").item(0); TypeInfo roletypeInfo = role.getSchemaTypeInfo(); assertTrue(roletypeInfo.getTypeName().equals("BuyOrSell")); assertTrue(roletypeInfo.getTypeNamespace().equals(PORTAL_ACCOUNT_NS)); } }
lostdj/Jaklin-OpenJDK-JAXP
test/javax/xml/jaxp/functional/test/auctionportal/AuctionController.java
Java
gpl-2.0
14,668
/* Adept MobileRobots Robotics Interface for Applications (ARIA) Copyright (C) 2004-2005 ActivMedia Robotics LLC Copyright (C) 2006-2010 MobileRobots Inc. Copyright (C) 2011-2014 Adept Technology 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 If you wish to redistribute ARIA under different terms, contact Adept MobileRobots for information about a commercial version of ARIA at robots@mobilerobots.com or Adept MobileRobots, 10 Columbia Drive, Amherst, NH 03031; +1-603-881-7960 */ /* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). * Version 1.3.40 * * Do not make changes to this file unless you know what you are doing--modify * the SWIG interface file instead. * ----------------------------------------------------------------------------- */ package com.mobilerobots.Aria; public class ArUrg extends ArLaser { /* (begin code from javabody_derived typemap) */ private long swigCPtr; /* for internal use by swig only */ public ArUrg(long cPtr, boolean cMemoryOwn) { super(AriaJavaJNI.SWIGArUrgUpcast(cPtr), cMemoryOwn); swigCPtr = cPtr; } /* for internal use by swig only */ public static long getCPtr(ArUrg obj) { return (obj == null) ? 0 : obj.swigCPtr; } /* (end code from javabody_derived typemap) */ protected void finalize() { delete(); } public synchronized void delete() { if (swigCPtr != 0) { if (swigCMemOwn) { swigCMemOwn = false; AriaJavaJNI.delete_ArUrg(swigCPtr); } swigCPtr = 0; } super.delete(); } public ArUrg(int laserNumber, String name) { this(AriaJavaJNI.new_ArUrg__SWIG_0(laserNumber, name), true); } public ArUrg(int laserNumber) { this(AriaJavaJNI.new_ArUrg__SWIG_1(laserNumber), true); } public boolean blockingConnect() { return AriaJavaJNI.ArUrg_blockingConnect(swigCPtr, this); } public boolean asyncConnect() { return AriaJavaJNI.ArUrg_asyncConnect(swigCPtr, this); } public boolean disconnect() { return AriaJavaJNI.ArUrg_disconnect(swigCPtr, this); } public boolean isConnected() { return AriaJavaJNI.ArUrg_isConnected(swigCPtr, this); } public boolean isTryingToConnect() { return AriaJavaJNI.ArUrg_isTryingToConnect(swigCPtr, this); } public void log() { AriaJavaJNI.ArUrg_log(swigCPtr, this); } }
sfe1012/Robot
java/com/mobilerobots/Aria/ArUrg.java
Java
gpl-2.0
3,101
/* * #%L * BSD implementations of Bio-Formats readers and writers * %% * Copyright (C) 2005 - 2016 Open Microscopy Environment: * - Board of Regents of the University of Wisconsin-Madison * - Glencoe Software, Inc. * - University of Dundee * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * #L% */ package loci.formats.codec; import java.io.IOException; import java.util.Vector; import loci.common.ByteArrayHandle; import loci.common.DataTools; import loci.common.RandomAccessInputStream; import loci.formats.FormatException; import loci.formats.UnsupportedCompressionException; /** * Decompresses lossless JPEG images. * * @author Melissa Linkert melissa at glencoesoftware.com */ public class LosslessJPEGCodec extends BaseCodec { // -- Constants -- // Start of Frame markers - non-differential, Huffman coding private static final int SOF0 = 0xffc0; // baseline DCT private static final int SOF1 = 0xffc1; // extended sequential DCT private static final int SOF2 = 0xffc2; // progressive DCT private static final int SOF3 = 0xffc3; // lossless (sequential) // Start of Frame markers - differential, Huffman coding private static final int SOF5 = 0xffc5; // differential sequential DCT private static final int SOF6 = 0xffc6; // differential progressive DCT private static final int SOF7 = 0xffc7; // differential lossless (sequential) // Start of Frame markers - non-differential, arithmetic coding private static final int JPG = 0xffc8; // reserved for JPEG extensions private static final int SOF9 = 0xffc9; // extended sequential DCT private static final int SOF10 = 0xffca; // progressive DCT private static final int SOF11 = 0xffcb; // lossless (sequential) // Start of Frame markers - differential, arithmetic coding private static final int SOF13 = 0xffcd; // differential sequential DCT private static final int SOF14 = 0xffce; // differential progressive DCT private static final int SOF15 = 0xffcf; // differential lossless (sequential) private static final int DHT = 0xffc4; // define Huffman table(s) private static final int DAC = 0xffcc; // define arithmetic coding conditions // Restart interval termination private static final int RST_0 = 0xffd0; private static final int RST_1 = 0xffd1; private static final int RST_2 = 0xffd2; private static final int RST_3 = 0xffd3; private static final int RST_4 = 0xffd4; private static final int RST_5 = 0xffd5; private static final int RST_6 = 0xffd6; private static final int RST_7 = 0xffd7; private static final int SOI = 0xffd8; // start of image private static final int EOI = 0xffd9; // end of image private static final int SOS = 0xffda; // start of scan private static final int DQT = 0xffdb; // define quantization table(s) private static final int DNL = 0xffdc; // define number of lines private static final int DRI = 0xffdd; // define restart interval private static final int DHP = 0xffde; // define hierarchical progression private static final int EXP = 0xffdf; // expand reference components private static final int COM = 0xfffe; // comment // -- Codec API methods -- /* @see Codec#compress(byte[], CodecOptions) */ @Override public byte[] compress(byte[] data, CodecOptions options) throws FormatException { throw new UnsupportedCompressionException( "Lossless JPEG compression not supported"); } /** * The CodecOptions parameter should have the following fields set: * {@link CodecOptions#interleaved interleaved} * {@link CodecOptions#littleEndian littleEndian} * * @see Codec#decompress(RandomAccessInputStream, CodecOptions) */ @Override public byte[] decompress(RandomAccessInputStream in, CodecOptions options) throws FormatException, IOException { if (in == null) throw new IllegalArgumentException("No data to decompress."); if (options == null) options = CodecOptions.getDefaultOptions(); byte[] buf = new byte[0]; int width = 0, height = 0; int bitsPerSample = 0, nComponents = 0, bytesPerSample = 0; int[] horizontalSampling = null, verticalSampling = null; int[] quantizationTable = null; short[][] huffmanTables = null; int startPredictor = 0, endPredictor = 0; int pointTransform = 0; int[] dcTable = null, acTable = null; while (in.getFilePointer() < in.length() - 1) { int code = in.readShort() & 0xffff; int length = in.readShort() & 0xffff; long fp = in.getFilePointer(); if (length > 0xff00) { length = 0; in.seek(fp - 2); } else if (code == SOS) { nComponents = in.read(); dcTable = new int[nComponents]; acTable = new int[nComponents]; for (int i=0; i<nComponents; i++) { int componentSelector = in.read(); int tableSelector = in.read(); dcTable[i] = (tableSelector & 0xf0) >> 4; acTable[i] = tableSelector & 0xf; } startPredictor = in.read(); endPredictor = in.read(); pointTransform = in.read() & 0xf; // read image data byte[] toDecode = new byte[(int) (in.length() - in.getFilePointer())]; in.read(toDecode); // scrub out byte stuffing ByteVector b = new ByteVector(); for (int i=0; i<toDecode.length; i++) { byte val = toDecode[i]; if (val == (byte) 0xff) { if (toDecode[i + 1] == 0) b.add(val); i++; } else { b.add(val); } } toDecode = b.toByteArray(); RandomAccessInputStream bb = new RandomAccessInputStream( new ByteArrayHandle(toDecode)); HuffmanCodec huffman = new HuffmanCodec(); HuffmanCodecOptions huffmanOptions = new HuffmanCodecOptions(); huffmanOptions.bitsPerSample = bitsPerSample; huffmanOptions.maxBytes = buf.length / nComponents; int nextSample = 0; while (nextSample < buf.length / nComponents) { for (int i=0; i<nComponents; i++) { huffmanOptions.table = huffmanTables[dcTable[i]]; int v = 0; if (huffmanTables != null) { v = huffman.getSample(bb, huffmanOptions); if (nextSample == 0) { v += (int) Math.pow(2, bitsPerSample - 1); } } else { throw new UnsupportedCompressionException( "Arithmetic coding not supported"); } // apply predictor to the sample int predictor = startPredictor; if (nextSample < width * bytesPerSample) predictor = 1; else if ((nextSample % (width * bytesPerSample)) == 0) { predictor = 2; } int componentOffset = i * (buf.length / nComponents); int indexA = nextSample - bytesPerSample + componentOffset; int indexB = nextSample - width * bytesPerSample + componentOffset; int indexC = nextSample - (width + 1) * bytesPerSample + componentOffset; int sampleA = indexA < 0 ? 0 : DataTools.bytesToInt(buf, indexA, bytesPerSample, false); int sampleB = indexB < 0 ? 0 : DataTools.bytesToInt(buf, indexB, bytesPerSample, false); int sampleC = indexC < 0 ? 0 : DataTools.bytesToInt(buf, indexC, bytesPerSample, false); if (nextSample > 0) { int pred = 0; switch (predictor) { case 1: pred = sampleA; break; case 2: pred = sampleB; break; case 3: pred = sampleC; break; case 4: pred = sampleA + sampleB + sampleC; break; case 5: pred = sampleA + ((sampleB - sampleC) / 2); break; case 6: pred = sampleB + ((sampleA - sampleC) / 2); break; case 7: pred = (sampleA + sampleB) / 2; break; } v += pred; } int offset = componentOffset + nextSample; DataTools.unpackBytes(v, buf, offset, bytesPerSample, false); } nextSample += bytesPerSample; } bb.close(); } else { length -= 2; // stored length includes length param if (length == 0) continue; if (code == EOI) { } else if (code == SOF3) { // lossless w/Huffman coding bitsPerSample = in.read(); height = in.readShort(); width = in.readShort(); nComponents = in.read(); horizontalSampling = new int[nComponents]; verticalSampling = new int[nComponents]; quantizationTable = new int[nComponents]; for (int i=0; i<nComponents; i++) { in.skipBytes(1); int s = in.read(); horizontalSampling[i] = (s & 0xf0) >> 4; verticalSampling[i] = s & 0x0f; quantizationTable[i] = in.read(); } bytesPerSample = bitsPerSample / 8; if ((bitsPerSample % 8) != 0) bytesPerSample++; buf = new byte[width * height * nComponents * bytesPerSample]; } else if (code == SOF11) { throw new UnsupportedCompressionException( "Arithmetic coding is not yet supported"); } else if (code == DHT) { if (huffmanTables == null) { huffmanTables = new short[4][]; } int bytesRead = 0; while (bytesRead < length) { int s = in.read(); byte tableClass = (byte) ((s & 0xf0) >> 4); byte destination = (byte) (s & 0xf); int[] nCodes = new int[16]; Vector table = new Vector(); for (int i=0; i<nCodes.length; i++) { nCodes[i] = in.read(); table.add(new Short((short) nCodes[i])); } for (int i=0; i<nCodes.length; i++) { for (int j=0; j<nCodes[i]; j++) { table.add(new Short((short) (in.read() & 0xff))); } } huffmanTables[destination] = new short[table.size()]; for (int i=0; i<huffmanTables[destination].length; i++) { huffmanTables[destination][i] = ((Short) table.get(i)).shortValue(); } bytesRead += table.size() + 1; } } in.seek(fp + length); } } if (options.interleaved && nComponents > 1) { // data is stored in planar (RRR...GGG...BBB...) order byte[] newBuf = new byte[buf.length]; for (int i=0; i<buf.length; i+=nComponents*bytesPerSample) { for (int c=0; c<nComponents; c++) { int src = c * (buf.length / nComponents) + (i / nComponents); int dst = i + c * bytesPerSample; System.arraycopy(buf, src, newBuf, dst, bytesPerSample); } } buf = newBuf; } if (options.littleEndian && bytesPerSample > 1) { // data is stored in big endian order // reverse the bytes in each sample byte[] newBuf = new byte[buf.length]; for (int i=0; i<buf.length; i+=bytesPerSample) { for (int q=0; q<bytesPerSample; q++) { newBuf[i + bytesPerSample - q - 1] = buf[i + q]; } } buf = newBuf; } return buf; } }
imunro/bioformats
components/formats-bsd/src/loci/formats/codec/LosslessJPEGCodec.java
Java
gpl-2.0
12,867
/* * Copyright (c) 2018, 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. */ import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.geom.AffineTransform; import java.awt.geom.Path2D; import java.awt.image.BufferedImage; import java.awt.image.Raster; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; /** * Scaled Line Clipping rendering test */ public class ScaleClipTest { static final boolean SAVE_IMAGE = false; static final int SIZE = 50; enum SCALE_MODE { ORTHO, NON_ORTHO, COMPLEX }; public static void main(String[] args) { // First display which renderer is tested: // JDK9 only: System.setProperty("sun.java2d.renderer.verbose", "true"); System.out.println("Testing renderer: "); // Other JDK: String renderer = "undefined"; try { renderer = sun.java2d.pipe.RenderingEngine.getInstance().getClass().getName(); System.out.println(renderer); } catch (Throwable th) { // may fail with JDK9 jigsaw (jake) if (false) { System.err.println("Unable to get RenderingEngine.getInstance()"); th.printStackTrace(); } } System.out.println("ScaleClipTest: size = " + SIZE); final BufferedImage image = new BufferedImage(SIZE, SIZE, BufferedImage.TYPE_INT_ARGB); boolean fail = false; // testNegativeScale: for (SCALE_MODE mode : SCALE_MODE.values()) { try { testNegativeScale(image, mode); } catch (IllegalStateException ise) { System.err.println("testNegativeScale[" + mode + "] failed:"); ise.printStackTrace(); fail = true; } } // testMarginScale: for (SCALE_MODE mode : SCALE_MODE.values()) { try { testMarginScale(image, mode); } catch (IllegalStateException ise) { System.err.println("testMarginScale[" + mode + "] failed:"); ise.printStackTrace(); fail = true; } } // Fail at the end: if (fail) { throw new RuntimeException("ScaleClipTest has failures."); } } private static void testNegativeScale(final BufferedImage image, final SCALE_MODE mode) { final Graphics2D g2d = (Graphics2D) image.getGraphics(); try { g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE); g2d.setBackground(Color.WHITE); g2d.clearRect(0, 0, SIZE, SIZE); g2d.setColor(Color.BLACK); // Bug in TransformingPathConsumer2D.adjustClipScale() // non ortho scale only final double scale = -1.0; final AffineTransform at; switch (mode) { default: case ORTHO: at = AffineTransform.getScaleInstance(scale, scale); break; case NON_ORTHO: at = AffineTransform.getScaleInstance(scale, scale + 1e-5); break; case COMPLEX: at = AffineTransform.getScaleInstance(scale, scale); at.concatenate(AffineTransform.getShearInstance(1e-4, 1e-4)); break; } g2d.setTransform(at); // Set cap/join to reduce clip margin: g2d.setStroke(new BasicStroke(2f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL)); final Path2D p = new Path2D.Double(); p.moveTo(scale * 10, scale * 10); p.lineTo(scale * (SIZE - 10), scale * (SIZE - 10)); g2d.draw(p); if (SAVE_IMAGE) { try { final File file = new File("ScaleClipTest-testNegativeScale-" + mode + ".png"); System.out.println("Writing file: " + file.getAbsolutePath()); ImageIO.write(image, "PNG", file); } catch (IOException ioe) { ioe.printStackTrace(); } } // Check image: // 25, 25 = black checkPixel(image.getData(), 25, 25, Color.BLACK.getRGB()); } finally { g2d.dispose(); } } private static void testMarginScale(final BufferedImage image, final SCALE_MODE mode) { final Graphics2D g2d = (Graphics2D) image.getGraphics(); try { g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE); g2d.setBackground(Color.WHITE); g2d.clearRect(0, 0, SIZE, SIZE); g2d.setColor(Color.BLACK); // Bug in Stroker.init() // ortho scale only: scale used twice ! final double scale = 1e-2; final AffineTransform at; switch (mode) { default: case ORTHO: at = AffineTransform.getScaleInstance(scale, scale); break; case NON_ORTHO: at = AffineTransform.getScaleInstance(scale, scale + 1e-5); break; case COMPLEX: at = AffineTransform.getScaleInstance(scale, scale); at.concatenate(AffineTransform.getShearInstance(1e-4, 1e-4)); break; } g2d.setTransform(at); final double invScale = 1.0 / scale; // Set cap/join to reduce clip margin: final float w = (float) (3.0 * invScale); g2d.setStroke(new BasicStroke(w, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL)); final Path2D p = new Path2D.Double(); p.moveTo(invScale * -0.5, invScale * 10); p.lineTo(invScale * -0.5, invScale * (SIZE - 10)); g2d.draw(p); if (SAVE_IMAGE) { try { final File file = new File("ScaleClipTest-testMarginScale-" + mode + ".png"); System.out.println("Writing file: " + file.getAbsolutePath()); ImageIO.write(image, "PNG", file); } catch (IOException ioe) { ioe.printStackTrace(); } } // Check image: // 0, 25 = black checkPixel(image.getData(), 0, 25, Color.BLACK.getRGB()); } finally { g2d.dispose(); } } private static void checkPixel(final Raster raster, final int x, final int y, final int expected) { final int[] rgb = (int[]) raster.getDataElements(x, y, null); if (rgb[0] != expected) { throw new IllegalStateException("bad pixel at (" + x + ", " + y + ") = " + rgb[0] + " expected: " + expected); } } }
JetBrains/jdk8u_jdk
test/sun/java2d/marlin/ScaleClipTest.java
Java
gpl-2.0
8,526
/** Copyright 2008, 2009 UFPE - Universidade Federal de Pernambuco Este arquivo é parte do programa Amadeus Sistema de Gestão de Aprendizagem, ou simplesmente Amadeus LMS O Amadeus LMS é um software livre; você pode redistribui-lo e/ou modifica-lo dentro dos termos da Licença Pública Geral GNU como publicada pela Fundação do Software Livre (FSF); na versão 2 da Licença. Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU para maiores detalhes. Você deve ter recebido uma cópia da Licença Pública Geral GNU, sob o título "LICENCA.txt", junto com este programa, se não, escreva para a Fundação do Software Livre (FSF) Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. **/ package br.ufpe.cin.amadeus.amadeus_mobile.util; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile; import br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Forum; import br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Game; import br.ufpe.cin.amadeus.amadeus_web.domain.content_management.LearningObject; import br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Poll; public class Conversor { /** * Method that converts AMADeUs Course object into Mobile Course object * @param curso - AMADeUs Course to be converted * @return - Converted Mobile Course object */ public static br.ufpe.cin.amadeus.amadeus_mobile.basics.CourseMobile converterCurso(br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Course curso){ br.ufpe.cin.amadeus.amadeus_mobile.basics.CourseMobile retorno = new br.ufpe.cin.amadeus.amadeus_mobile.basics.CourseMobile(); retorno.setId(curso.getId()); retorno.setName(curso.getName()); retorno.setContent(curso.getContent()); retorno.setObjectives(curso.getObjectives()); retorno.setModules(converterModulos(curso.getModules())); retorno.setKeywords(converterKeywords(curso.getKeywords())); ArrayList<String> nomes = new ArrayList<String>(); nomes.add(curso.getProfessor().getName()); retorno.setTeachers(nomes); retorno.setCount(0); retorno.setMaxAmountStudents(curso.getMaxAmountStudents()); retorno.setFinalCourseDate(curso.getFinalCourseDate()); retorno.setInitialCourseDate(curso.getInitialCourseDate()); return retorno; } /** * Method that converts a AMADeUs Course object list into Mobile Course object list * @param cursos - AMADeUs Course object list to be converted * @return - Converted Mobile Course object list */ public static List<br.ufpe.cin.amadeus.amadeus_mobile.basics.CourseMobile> converterCursos(List<br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Course> cursos){ ArrayList<br.ufpe.cin.amadeus.amadeus_mobile.basics.CourseMobile> retorno = new ArrayList<br.ufpe.cin.amadeus.amadeus_mobile.basics.CourseMobile>(); for (br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Course c : cursos){ retorno.add(Conversor.converterCurso(c)); } return retorno; } /** * Method that converts AMADeUs Module object into Mobile Module object * @param modulo - AMADeUs Module object to be converted * @return - Converted Mobile Module object */ public static br.ufpe.cin.amadeus.amadeus_mobile.basics.ModuleMobile converterModulo(br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Module modulo){ br.ufpe.cin.amadeus.amadeus_mobile.basics.ModuleMobile mod = new br.ufpe.cin.amadeus.amadeus_mobile.basics.ModuleMobile(modulo.getId(), modulo.getName()); List<HomeworkMobile> listHomeworks = new ArrayList<HomeworkMobile>(); for (Poll poll : modulo.getPolls()) { listHomeworks.add( Conversor.converterPollToHomework(poll) ); } for (Forum forum : modulo.getForums()) { listHomeworks.add( Conversor.converterForumToHomework(forum) ); } for(Game game : modulo.getGames()){ listHomeworks.add( Conversor.converterGameToHomework(game) ); } for(LearningObject learning : modulo.getLearningObjects()){ listHomeworks.add( Conversor.converterLearningObjectToHomework(learning) ); } mod.setHomeworks(listHomeworks); mod.setMaterials(converterMaterials(modulo.getMaterials())); return mod; } /** * Mothod that converts a AMADeUs Module object list into Mobile Module object list * @param modulos - AMADeUs Module object list to be converted * @return - Converted Mobile Module object list */ public static List<br.ufpe.cin.amadeus.amadeus_mobile.basics.ModuleMobile> converterModulos(List<br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Module> modulos){ ArrayList<br.ufpe.cin.amadeus.amadeus_mobile.basics.ModuleMobile> retorno = new ArrayList<br.ufpe.cin.amadeus.amadeus_mobile.basics.ModuleMobile>(); for (br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Module m : modulos){ retorno.add(Conversor.converterModulo(m)); } return retorno; } /** * Method that converts AMADeUs Homework object into Mobile Homework object * @param home - AMADeUs Homework object to be converted * @return - Converted Mobile Homework object */ public static br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile converterHomework(br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Homework home){ br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile retorno = new br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile(); retorno.setId(home.getId()); retorno.setName(home.getName()); retorno.setDescription(home.getDescription()); retorno.setInitDate(home.getInitDate()); retorno.setDeadline(home.getDeadline()); retorno.setAlowPostponing(home.getAllowPostponing()); retorno.setInfoExtra(""); retorno.setTypeActivity(HomeworkMobile.HOMEWORK); return retorno; } /** * Method that converts AMADeUs Game object into Mobile Homework object * @param game - AMADeUs Game object to be converted * @return - Converted Mobile Homework object */ public static br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile converterGameToHomework(br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Game game){ br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile retorno = new br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile(); retorno.setId(game.getId()); retorno.setName(game.getName()); retorno.setDescription(game.getDescription()); retorno.setInfoExtra(game.getUrl()); retorno.setTypeActivity(HomeworkMobile.GAME); return retorno; } /** * Method that converts AMADeUs Forum object into Mobile Homework object * @param forum - AMADeUs Forum object to be converted * @return - Converted Mobile Homework object */ public static br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile converterForumToHomework(br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Forum forum){ br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile retorno = new br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile(); retorno.setId(forum.getId()); retorno.setName(forum.getName()); retorno.setDescription(forum.getDescription()); retorno.setInitDate(forum.getCreationDate()); retorno.setInfoExtra(""); retorno.setTypeActivity(HomeworkMobile.FORUM); return retorno; } /** * Method that converts AMADeUs Poll object into Mobile Homework object * @param poll - AMADeUs Poll object to be converted * @return - Converted Mobile Homework object */ public static br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile converterPollToHomework(br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Poll poll){ br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile retorno = new br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile(); retorno.setId(poll.getId()); retorno.setName(poll.getName()); retorno.setDescription(poll.getQuestion()); retorno.setInitDate(poll.getCreationDate()); retorno.setDeadline(poll.getFinishDate()); retorno.setInfoExtra(""); retorno.setTypeActivity(HomeworkMobile.POLL); return retorno; } /** * Method that converts AMADeUs Multimedia object into Mobile Homework object * @param media - AMADeUs Multimedia object to be converted * @return - Converted Mobile Homework object */ public static br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile converterMultimediaToHomework(br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Multimedia media){ br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile retorno = new br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile(); retorno.setId(media.getId()); retorno.setName(media.getName()); retorno.setDescription(media.getDescription()); retorno.setInfoExtra(media.getUrl()); retorno.setTypeActivity(HomeworkMobile.MULTIMEDIA); return retorno; } /** * Method that converts AMADeUs Video object into Mobile Homework object * @param video - AMADeUs Video object to be converted * @return - Converted Mobile Homework object */ public static br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile converterVideoToHomework(br.ufpe.cin.amadeus.amadeus_sdmm.dao.Video video){ br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile retorno = new br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile(); retorno.setId(video.getId()); retorno.setName(video.getName()); retorno.setDescription(video.getDescription()); retorno.setInitDate(video.getDateinsertion()); retorno.setInfoExtra(video.getTags()); retorno.setTypeActivity(HomeworkMobile.VIDEO); return retorno; } public static br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile converterLearningObjectToHomework( br.ufpe.cin.amadeus.amadeus_web.domain.content_management.LearningObject learning) { br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile retorno = new br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile(); retorno.setId(learning.getId()); retorno.setName(learning.getName()); retorno.setUrl(learning.getUrl()); retorno.setDescription(learning.getDescription()); retorno.setDeadline(learning.getCreationDate()); retorno.setTypeActivity(HomeworkMobile.LEARNING_OBJECT); return retorno; } /** * Method that converts AMADeUs Homework object list into Mobile Homework object list * @param homes - AMADeUs Homework object list to be converted * @return - Converted Mobile Homework object list */ public static List<br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile> converterHomeworks(List<br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Homework> homes){ ArrayList<br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile> retorno = new ArrayList<br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile>(); for (br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Homework h : homes){ retorno.add(Conversor.converterHomework(h)); } return retorno; } /** * Method that converts AMADeUs Material object into Mobile Material object * @param mat - AMADeUs Material object to be converted * @return - Mobile Material object converted */ public static br.ufpe.cin.amadeus.amadeus_mobile.basics.MaterialMobile converterMaterial(br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Material mat){ br.ufpe.cin.amadeus.amadeus_mobile.basics.MaterialMobile retorno = new br.ufpe.cin.amadeus.amadeus_mobile.basics.MaterialMobile(); retorno.setId(mat.getId()); retorno.setName(mat.getArchiveName()); retorno.setAuthor(converterPerson(mat.getAuthor())); retorno.setPostDate(mat.getCreationDate()); return retorno; } /** * Method that converts AMADeUs Mobile Material object list into Mobile Material object list * @param mats - AMADeUs Material object list * @return - Mobile Material object list */ public static List<br.ufpe.cin.amadeus.amadeus_mobile.basics.MaterialMobile> converterMaterials(List<br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Material> mats){ ArrayList<br.ufpe.cin.amadeus.amadeus_mobile.basics.MaterialMobile> retorno = new ArrayList<br.ufpe.cin.amadeus.amadeus_mobile.basics.MaterialMobile>(); for (br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Material mat : mats){ retorno.add(Conversor.converterMaterial(mat)); } return retorno; } /** * Method that converts AMADeUs Keyword object into Mobile Keyword object * @param key - AMADeUs Keyword object to be converted * @return - Converted Keywork object */ public static br.ufpe.cin.amadeus.amadeus_mobile.basics.KeywordMobile converterKeyword(br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Keyword key){ br.ufpe.cin.amadeus.amadeus_mobile.basics.KeywordMobile retorno = new br.ufpe.cin.amadeus.amadeus_mobile.basics.KeywordMobile(); retorno.setId(key.getId()); retorno.setName(key.getName()); retorno.setPopularity(key.getPopularity()); return retorno; } /** * Method that converts AMADeUs Keyword object list into a Mobile Keyword HashSet object * @param keys - AMADeUs Keyword object list to be converted * @return - Mobile Keywork HashSet object list */ public static HashSet<br.ufpe.cin.amadeus.amadeus_mobile.basics.KeywordMobile> converterKeywords(Set<br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Keyword> keys){ HashSet<br.ufpe.cin.amadeus.amadeus_mobile.basics.KeywordMobile> retorno = new HashSet<br.ufpe.cin.amadeus.amadeus_mobile.basics.KeywordMobile>(); for (br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Keyword k : keys){ retorno.add(Conversor.converterKeyword(k)); } return retorno; } /** * Method that converts AMADeUs Choice object into Mobile Choice object * @param ch - AMADeUs Choice object to be converted * @return - Converted Mobile Choice object */ public static br.ufpe.cin.amadeus.amadeus_mobile.basics.ChoiceMobile converterChoice(br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Choice ch){ br.ufpe.cin.amadeus.amadeus_mobile.basics.ChoiceMobile retorno = new br.ufpe.cin.amadeus.amadeus_mobile.basics.ChoiceMobile(); retorno.setId(ch.getId()); retorno.setAlternative(ch.getAlternative()); retorno.setVotes(ch.getVotes()); retorno.setPercentage(ch.getPercentage()); return retorno; } /** * Method that converts AMADeUs Choice object list into Mobile Choice object list * @param chs - AMADeUs Choice object list to be converted * @return - Converted Mobile Choice object list */ public static List<br.ufpe.cin.amadeus.amadeus_mobile.basics.ChoiceMobile> converterChoices(List<br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Choice> chs){ List<br.ufpe.cin.amadeus.amadeus_mobile.basics.ChoiceMobile> retorno = new ArrayList<br.ufpe.cin.amadeus.amadeus_mobile.basics.ChoiceMobile>(); for (br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Choice c : chs){ retorno.add(Conversor.converterChoice(c)); } return retorno; } /** * Method that converts AMADeUs Poll object into Mobile Poll Object * @param p - AMADeUs Poll object to be converted * @return - Converted Mobile Poll object */ public static br.ufpe.cin.amadeus.amadeus_mobile.basics.PollMobile converterPool(br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Poll p){ br.ufpe.cin.amadeus.amadeus_mobile.basics.PollMobile retorno = new br.ufpe.cin.amadeus.amadeus_mobile.basics.PollMobile(); retorno.setId(p.getId()); retorno.setName(p.getName()); retorno.setQuestion(p.getQuestion()); retorno.setInitDate(p.getCreationDate()); retorno.setFinishDate(p.getFinishDate()); retorno.setAnswered(false); retorno.setChoices(converterChoices(p.getChoices())); retorno.setAnsewered(converterAnswers(p.getAnswers())); return retorno; } public static br.ufpe.cin.amadeus.amadeus_mobile.basics.LearningObjectMobile converterLearningObject (br.ufpe.cin.amadeus.amadeus_web.domain.content_management.LearningObject learning){ br.ufpe.cin.amadeus.amadeus_mobile.basics.LearningObjectMobile retorno = new br.ufpe.cin.amadeus.amadeus_mobile.basics.LearningObjectMobile(); retorno.setId(learning.getId()); retorno.setName(learning.getName()); retorno.setDescription(learning.getDescription()); retorno.setDatePublication(learning.getCreationDate()); retorno.setUrl(learning.getUrl()); return retorno; } /** * Method that converts AMADeUs Poll object list into Mobile Poll object list * @param pls - AMADeUs Poll object list * @return - Converted Mobile object list */ public static List<br.ufpe.cin.amadeus.amadeus_mobile.basics.PollMobile> converterPools(List<br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Poll> pls){ List<br.ufpe.cin.amadeus.amadeus_mobile.basics.PollMobile> retorno = new ArrayList<br.ufpe.cin.amadeus.amadeus_mobile.basics.PollMobile>(); for (br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Poll p : pls){ retorno.add(Conversor.converterPool(p)); } return retorno; } /** * Method that converts AMADeUs Answer object into Mobile Answer object * @param ans - AMADeUs Answer object to be converted * @return - Converted Mobile Answer object */ public static br.ufpe.cin.amadeus.amadeus_mobile.basics.AnswerMobile converterAnswer(br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Answer ans){ br.ufpe.cin.amadeus.amadeus_mobile.basics.AnswerMobile retorno = new br.ufpe.cin.amadeus.amadeus_mobile.basics.AnswerMobile(); retorno.setId(ans.getId()); retorno.setAnswerDate(ans.getAnswerDate()); retorno.setPerson(converterPerson(ans.getPerson())); return retorno; } /** * Method that converts AMADeUs Answer object list into Mobile Answer object list * @param anss - AMADeUs Answer object list * @return - Converted Mobile object list */ public static List<br.ufpe.cin.amadeus.amadeus_mobile.basics.AnswerMobile> converterAnswers(List<br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Answer> anss){ List<br.ufpe.cin.amadeus.amadeus_mobile.basics.AnswerMobile> retorno = new ArrayList<br.ufpe.cin.amadeus.amadeus_mobile.basics.AnswerMobile>(); for (br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Answer an : anss){ retorno.add(Conversor.converterAnswer(an)); } return retorno; } /** * Method that converts AMADeUs Person object into Mobile Person object * @param p - AMADeUs Person object to be converted * @return - Converted Mobile Person object */ public static br.ufpe.cin.amadeus.amadeus_mobile.basics.PersonMobile converterPerson(br.ufpe.cin.amadeus.amadeus_web.domain.register.Person p){ return new br.ufpe.cin.amadeus.amadeus_mobile.basics.PersonMobile(p.getId(), p.getAccessInfo().getLogin(), p.getPhoneNumber()); } /** * Method that converts AMADeUs Person object list into Mobile Person object list * @param persons - AMADeUs Person object list to be converted * @return - Converted Mobile Person object list */ public static List<br.ufpe.cin.amadeus.amadeus_mobile.basics.PersonMobile> converterPersons(List<br.ufpe.cin.amadeus.amadeus_web.domain.register.Person> persons){ List<br.ufpe.cin.amadeus.amadeus_mobile.basics.PersonMobile> retorno = new ArrayList<br.ufpe.cin.amadeus.amadeus_mobile.basics.PersonMobile>(); for (br.ufpe.cin.amadeus.amadeus_web.domain.register.Person p : persons){ retorno.add(Conversor.converterPerson(p)); } return retorno; } /** * Method that converts Mobile Poll object into AMADeUs Poll Object * @param p - Mobile Poll object to be converted * @return - Converted AMADeUs Poll object */ public static br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Poll converterPool(br.ufpe.cin.amadeus.amadeus_mobile.basics.PollMobile p){ br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Poll retorno = new br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Poll(); retorno.setId(p.getId()); retorno.setName(p.getName()); retorno.setQuestion(p.getQuestion()); retorno.setCreationDate(p.getInitDate()); retorno.setFinishDate(p.getFinishDate()); retorno.setChoices(converterChoices2(p.getChoices())); retorno.setAnswers(converterAnswers2(p.getAnsewered())); return retorno; } /** * Method that converts Mobile Choice object into AMADeUs Choice object * @param ch - Mobile Choice object to be converted * @return - Converted AMADeUs Choice object */ public static br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Choice converterChoice(br.ufpe.cin.amadeus.amadeus_mobile.basics.ChoiceMobile ch){ br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Choice retorno = new br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Choice(); retorno.setId(ch.getId()); retorno.setAlternative(ch.getAlternative()); retorno.setVotes(ch.getVotes()); retorno.setPercentage(ch.getPercentage()); return retorno; } /** * Method that converts Mobile Choiceobject list into AMADeUs Choice object list * @param chs - Mobile Choice object list to be converted * @return - Converted AMADeUs Choice object list */ public static List<br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Choice> converterChoices2(List<br.ufpe.cin.amadeus.amadeus_mobile.basics.ChoiceMobile> chs){ List<br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Choice> retorno = new ArrayList<br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Choice>(); for (br.ufpe.cin.amadeus.amadeus_mobile.basics.ChoiceMobile c : chs){ retorno.add(Conversor.converterChoice(c)); } return retorno; } /** * Method that converts Mobile Answer object into AMADeUs Answer object * @param ans - Mobile Answer object to be converted * @return - Converted AMADeUs Answer object */ public static br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Answer converterAnswer(br.ufpe.cin.amadeus.amadeus_mobile.basics.AnswerMobile ans){ br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Answer retorno = new br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Answer(); retorno.setId(ans.getId()); retorno.setAnswerDate(ans.getAnswerDate()); retorno.setPerson(converterPerson(ans.getPerson())); return retorno; } /** * Method that converts Mobile Answer object list into AMADeUs Answer object list * @param anss - Mobile Answer object list * @return - Converted AMADeUs Answer object list */ public static List<br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Answer> converterAnswers2(List<br.ufpe.cin.amadeus.amadeus_mobile.basics.AnswerMobile> anss){ List<br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Answer> retorno = new ArrayList<br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Answer>(); for (br.ufpe.cin.amadeus.amadeus_mobile.basics.AnswerMobile an : anss){ retorno.add(Conversor.converterAnswer(an)); } return retorno; } /** * Method that converts Mobile Person object into AMADeUs Person object * @param p - Mobile Person object to be converted * @return - Converted AMADeUs Person object */ public static br.ufpe.cin.amadeus.amadeus_web.domain.register.Person converterPerson(br.ufpe.cin.amadeus.amadeus_mobile.basics.PersonMobile p){ br.ufpe.cin.amadeus.amadeus_web.domain.register.Person p1 = new br.ufpe.cin.amadeus.amadeus_web.domain.register.Person(); p1.setId(p.getId()); p1.setName(p.getName()); p1.setPhoneNumber(p.getPhoneNumber()); return p1; } }
phcp/AmadeusLMS
src/br/ufpe/cin/amadeus/amadeus_mobile/util/Conversor.java
Java
gpl-2.0
24,368
package net.sf.memoranda.ui.htmleditor; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Frame; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Image; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JDialog; import javax.swing.JFileChooser; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.UIManager; import javax.swing.border.EmptyBorder; import javax.swing.border.EtchedBorder; import net.sf.memoranda.ui.htmleditor.util.Local; /** * <p>Title: </p> * <p>Description: </p> * <p>Copyright: Copyright (c) 2002</p> * <p>Company: </p> * @author unascribed * @version 1.0 */ public class ImageDialog extends JDialog implements WindowListener { /** * */ private static final long serialVersionUID = 5326851249529076804L; JPanel headerPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); JLabel header = new JLabel(); JPanel areaPanel = new JPanel(new GridBagLayout()); GridBagConstraints gbc; JLabel jLabel1 = new JLabel(); public JTextField fileField = new JTextField(); JButton browseB = new JButton(); JLabel jLabel2 = new JLabel(); public JTextField altField = new JTextField(); JLabel jLabel3 = new JLabel(); public JTextField widthField = new JTextField(); JLabel jLabel4 = new JLabel(); public JTextField heightField = new JTextField(); JLabel jLabel5 = new JLabel(); public JTextField hspaceField = new JTextField(); JLabel jLabel6 = new JLabel(); public JTextField vspaceField = new JTextField(); JLabel jLabel7 = new JLabel(); public JTextField borderField = new JTextField(); JLabel jLabel8 = new JLabel(); String[] aligns = {"left", "right", "top", "middle", "bottom", "absmiddle", "texttop", "baseline"}; // Note: align values are not localized because they are HTML keywords public JComboBox<String> alignCB = new JComboBox<String>(aligns); JLabel jLabel9 = new JLabel(); public JTextField urlField = new JTextField(); JPanel buttonsPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 10, 10)); JButton okB = new JButton(); JButton cancelB = new JButton(); public boolean CANCELLED = false; public ImageDialog(Frame frame) { super(frame, Local.getString("Image"), true); try { jbInit(); pack(); } catch (Exception ex) { ex.printStackTrace(); } super.addWindowListener(this); } public ImageDialog() { this(null); } void jbInit() throws Exception { this.setResizable(false); // three Panels, so used BorderLayout for this dialog. headerPanel.setBorder(new EmptyBorder(new Insets(0, 5, 0, 5))); headerPanel.setBackground(Color.WHITE); header.setFont(new java.awt.Font("Dialog", 0, 20)); header.setForeground(new Color(0, 0, 124)); header.setText(Local.getString("Image")); header.setIcon(new ImageIcon( net.sf.memoranda.ui.htmleditor.ImageDialog.class.getResource( "resources/icons/imgbig.png"))); headerPanel.add(header); this.getContentPane().add(headerPanel, BorderLayout.NORTH); areaPanel.setBorder(new EtchedBorder(Color.white, new Color(142, 142, 142))); jLabel1.setText(Local.getString("Image file")); gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 0; gbc.insets = new Insets(10, 10, 5, 5); gbc.anchor = GridBagConstraints.WEST; areaPanel.add(jLabel1, gbc); fileField.setMinimumSize(new Dimension(200, 25)); fileField.setPreferredSize(new Dimension(285, 25)); gbc = new GridBagConstraints(); gbc.gridx = 1; gbc.gridy = 0; gbc.gridwidth = 5; gbc.insets = new Insets(10, 5, 5, 5); gbc.anchor = GridBagConstraints.WEST; gbc.fill = GridBagConstraints.HORIZONTAL; areaPanel.add(fileField, gbc); browseB.setMinimumSize(new Dimension(25, 25)); browseB.setPreferredSize(new Dimension(25, 25)); browseB.setIcon(new ImageIcon( net.sf.memoranda.ui.htmleditor.ImageDialog.class.getResource( "resources/icons/fileopen16.png"))); browseB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { browseB_actionPerformed(e); } }); gbc = new GridBagConstraints(); gbc.gridx = 6; gbc.gridy = 0; gbc.insets = new Insets(10, 5, 5, 10); gbc.anchor = GridBagConstraints.WEST; areaPanel.add(browseB, gbc); jLabel2.setText(Local.getString("ALT text")); gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 1; gbc.insets = new Insets(5, 10, 5, 5); gbc.anchor = GridBagConstraints.WEST; areaPanel.add(jLabel2, gbc); altField.setPreferredSize(new Dimension(315, 25)); altField.setMinimumSize(new Dimension(200, 25)); gbc = new GridBagConstraints(); gbc.gridx = 1; gbc.gridy = 1; gbc.gridwidth = 6; gbc.insets = new Insets(5, 5, 5, 10); gbc.anchor = GridBagConstraints.WEST; gbc.fill = GridBagConstraints.HORIZONTAL; areaPanel.add(altField, gbc); jLabel3.setText(Local.getString("Width")); gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 2; gbc.insets = new Insets(5, 10, 5, 5); gbc.anchor = GridBagConstraints.WEST; areaPanel.add(jLabel3, gbc); widthField.setPreferredSize(new Dimension(30, 25)); widthField.setMinimumSize(new Dimension(30, 25)); gbc = new GridBagConstraints(); gbc.gridx = 1; gbc.gridy = 2; gbc.insets = new Insets(5, 5, 5, 5); gbc.anchor = GridBagConstraints.WEST; areaPanel.add(widthField, gbc); jLabel4.setText(Local.getString("Height")); gbc = new GridBagConstraints(); gbc.gridx = 2; gbc.gridy = 2; gbc.insets = new Insets(5, 50, 5, 5); gbc.anchor = GridBagConstraints.WEST; areaPanel.add(jLabel4, gbc); heightField.setMinimumSize(new Dimension(30, 25)); heightField.setPreferredSize(new Dimension(30, 25)); gbc = new GridBagConstraints(); gbc.gridx = 3; gbc.gridy = 2; gbc.insets = new Insets(5, 5, 5, 5); gbc.anchor = GridBagConstraints.WEST; areaPanel.add(heightField, gbc); jLabel5.setText(Local.getString("H. space")); gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 3; gbc.insets = new Insets(5, 10, 5, 5); gbc.anchor = GridBagConstraints.WEST; areaPanel.add(jLabel5, gbc); hspaceField.setMinimumSize(new Dimension(30, 25)); hspaceField.setPreferredSize(new Dimension(30, 25)); hspaceField.setText("0"); gbc = new GridBagConstraints(); gbc.gridx = 1; gbc.gridy = 3; gbc.insets = new Insets(5, 5, 5, 5); gbc.anchor = GridBagConstraints.WEST; areaPanel.add(hspaceField, gbc); jLabel6.setText(Local.getString("V. space")); gbc = new GridBagConstraints(); gbc.gridx = 2; gbc.gridy = 3; gbc.insets = new Insets(5, 50, 5, 5); gbc.anchor = GridBagConstraints.WEST; areaPanel.add(jLabel6, gbc); vspaceField.setMinimumSize(new Dimension(30, 25)); vspaceField.setPreferredSize(new Dimension(30, 25)); vspaceField.setText("0"); gbc = new GridBagConstraints(); gbc.gridx = 3; gbc.gridy = 3; gbc.insets = new Insets(5, 5, 5, 5); gbc.anchor = GridBagConstraints.WEST; areaPanel.add(vspaceField, gbc); jLabel7.setText(Local.getString("Border")); gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 4; gbc.insets = new Insets(5, 10, 5, 5); gbc.anchor = GridBagConstraints.WEST; areaPanel.add(jLabel7, gbc); borderField.setMinimumSize(new Dimension(30, 25)); borderField.setPreferredSize(new Dimension(30, 25)); borderField.setText("0"); gbc = new GridBagConstraints(); gbc.gridx = 1; gbc.gridy = 4; gbc.insets = new Insets(5, 5, 5, 5); gbc.anchor = GridBagConstraints.WEST; areaPanel.add(borderField, gbc); jLabel8.setText(Local.getString("Align")); gbc = new GridBagConstraints(); gbc.gridx = 2; gbc.gridy = 4; gbc.insets = new Insets(5, 50, 5, 5); gbc.anchor = GridBagConstraints.WEST; areaPanel.add(jLabel8, gbc); alignCB.setBackground(new Color(230, 230, 230)); alignCB.setFont(new java.awt.Font("Dialog", 1, 10)); alignCB.setPreferredSize(new Dimension(100, 25)); alignCB.setSelectedIndex(0); gbc = new GridBagConstraints(); gbc.gridx = 3; gbc.gridy = 4; gbc.gridwidth = 2; gbc.insets = new Insets(5, 5, 5, 5); gbc.anchor = GridBagConstraints.WEST; areaPanel.add(alignCB, gbc); jLabel9.setText(Local.getString("Hyperlink")); gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 5; gbc.insets = new Insets(5, 10, 10, 5); gbc.anchor = GridBagConstraints.WEST; areaPanel.add(jLabel9, gbc); urlField.setPreferredSize(new Dimension(315, 25)); urlField.setMinimumSize(new Dimension(200, 25)); gbc = new GridBagConstraints(); gbc.gridx = 1; gbc.gridy = 5; gbc.gridwidth = 6; gbc.insets = new Insets(5, 5, 10, 10); gbc.fill = GridBagConstraints.HORIZONTAL; gbc.anchor = GridBagConstraints.WEST; areaPanel.add(urlField, gbc); this.getContentPane().add(areaPanel, BorderLayout.CENTER); okB.setMaximumSize(new Dimension(100, 26)); okB.setMinimumSize(new Dimension(100, 26)); okB.setPreferredSize(new Dimension(100, 26)); okB.setText(Local.getString("Ok")); okB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { okB_actionPerformed(e); } }); this.getRootPane().setDefaultButton(okB); cancelB.setMaximumSize(new Dimension(100, 26)); cancelB.setMinimumSize(new Dimension(100, 26)); cancelB.setPreferredSize(new Dimension(100, 26)); cancelB.setText(Local.getString("Cancel")); cancelB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { cancelB_actionPerformed(e); } }); buttonsPanel.add(okB, null); buttonsPanel.add(cancelB, null); this.getContentPane().add(buttonsPanel, BorderLayout.SOUTH); } void okB_actionPerformed(ActionEvent e) { this.dispose(); } void cancelB_actionPerformed(ActionEvent e) { CANCELLED = true; this.dispose(); } private ImageIcon getPreviewIcon(java.io.File file) { ImageIcon tmpIcon = new ImageIcon(file.getPath()); ImageIcon thmb = null; if (tmpIcon.getIconHeight() > 48) { thmb = new ImageIcon(tmpIcon.getImage() .getScaledInstance( -1, 48, Image.SCALE_DEFAULT)); } else { thmb = tmpIcon; } if (thmb.getIconWidth() > 350) { return new ImageIcon(thmb.getImage() .getScaledInstance(350, -1, Image.SCALE_DEFAULT)); } else { return thmb; } } public void updatePreview() { try { if (!(new java.net.URL(fileField.getText()).getPath()).equals("")) header.setIcon(getPreviewIcon(new java.io.File( new java.net.URL(fileField.getText()).getPath()))); } catch (Exception ex) { ex.printStackTrace(); } } public void windowOpened(WindowEvent e) { } public void windowClosing(WindowEvent e) { CANCELLED = true; this.dispose(); } public void windowClosed(WindowEvent e) { } public void windowIconified(WindowEvent e) { } public void windowDeiconified(WindowEvent e) { } public void windowActivated(WindowEvent e) { } public void windowDeactivated(WindowEvent e) { } void browseB_actionPerformed(ActionEvent e) { // Fix until Sun's JVM supports more locales... UIManager.put("FileChooser.lookInLabelText", Local .getString("Look in:")); UIManager.put("FileChooser.upFolderToolTipText", Local.getString( "Up One Level")); UIManager.put("FileChooser.newFolderToolTipText", Local.getString( "Create New Folder")); UIManager.put("FileChooser.listViewButtonToolTipText", Local .getString("List")); UIManager.put("FileChooser.detailsViewButtonToolTipText", Local .getString("Details")); UIManager.put("FileChooser.fileNameLabelText", Local.getString( "File Name:")); UIManager.put("FileChooser.filesOfTypeLabelText", Local.getString( "Files of Type:")); UIManager.put("FileChooser.openButtonText", Local.getString("Open")); UIManager.put("FileChooser.openButtonToolTipText", Local.getString( "Open selected file")); UIManager .put("FileChooser.cancelButtonText", Local.getString("Cancel")); UIManager.put("FileChooser.cancelButtonToolTipText", Local.getString( "Cancel")); JFileChooser chooser = new JFileChooser(); chooser.setFileHidingEnabled(false); chooser.setDialogTitle(Local.getString("Choose an image file")); chooser.setAcceptAllFileFilterUsed(false); chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); chooser.addChoosableFileFilter( new net.sf.memoranda.ui.htmleditor.filechooser.ImageFilter()); chooser.setAccessory( new net.sf.memoranda.ui.htmleditor.filechooser.ImagePreview( chooser)); chooser.setPreferredSize(new Dimension(550, 375)); java.io.File lastSel = (java.io.File) Context.get( "LAST_SELECTED_IMG_FILE"); if (lastSel != null) chooser.setCurrentDirectory(lastSel); if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { try { fileField.setText(chooser.getSelectedFile().toURI().toURL().toString()); header.setIcon(getPreviewIcon(chooser.getSelectedFile())); Context .put("LAST_SELECTED_IMG_FILE", chooser .getSelectedFile()); } catch (Exception ex) { fileField.setText(chooser.getSelectedFile().getPath()); } try { ImageIcon img = new ImageIcon(chooser.getSelectedFile() .getPath()); widthField.setText(new Integer(img.getIconWidth()).toString()); heightField .setText(new Integer(img.getIconHeight()).toString()); } catch (Exception ex) { ex.printStackTrace(); } } } }
jzalden/SER316-Karlsruhe
src/net/sf/memoranda/ui/htmleditor/ImageDialog.java
Java
gpl-2.0
13,558
/*************************************************************************** * (C) Copyright 2003-2015 - Stendhal * *************************************************************************** *************************************************************************** * * * 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. * * * ***************************************************************************/ package games.stendhal.server.actions.chat; import static org.junit.Assert.assertEquals; import games.stendhal.server.entity.player.Player; import marauroa.common.game.RPAction; import org.junit.Test; import utilities.PlayerTestHelper; public class AwayActionTest { /** * Tests for playerIsNull. */ @Test(expected = NullPointerException.class) public void testPlayerIsNull() { final RPAction action = new RPAction(); action.put("type", "away"); final AwayAction aa = new AwayAction(); aa.onAction(null, action); } /** * Tests for onAction. */ @Test public void testOnAction() { final Player bob = PlayerTestHelper.createPlayer("bob"); final RPAction action = new RPAction(); action.put("type", "away"); final AwayAction aa = new AwayAction(); aa.onAction(bob, action); assertEquals(null, bob.getAwayMessage()); action.put("message", "bla"); aa.onAction(bob, action); assertEquals("\"bla\"", bob.getAwayMessage()); } /** * Tests for onInvalidAction. */ @Test public void testOnInvalidAction() { final Player bob = PlayerTestHelper.createPlayer("bob"); bob.clearEvents(); final RPAction action = new RPAction(); action.put("type", "bla"); action.put("message", "bla"); final AwayAction aa = new AwayAction(); aa.onAction(bob, action); assertEquals(null, bob.getAwayMessage()); } }
acsid/stendhal
tests/games/stendhal/server/actions/chat/AwayActionTest.java
Java
gpl-2.0
2,201
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.harmony.unpack200.bytecode.forms; import org.apache.harmony.unpack200.SegmentConstantPool; import org.apache.harmony.unpack200.bytecode.ByteCode; import org.apache.harmony.unpack200.bytecode.CPInterfaceMethodRef; import org.apache.harmony.unpack200.bytecode.OperandManager; /** * This class implements the byte code form for those bytecodes which have * IMethod references (and only IMethod references). */ public class IMethodRefForm extends ReferenceForm { public IMethodRefForm(int opcode, String name, int[] rewrite) { super(opcode, name, rewrite); } protected int getOffset(OperandManager operandManager) { return operandManager.nextIMethodRef(); } protected int getPoolID() { return SegmentConstantPool.CP_IMETHOD; } /* * (non-Javadoc) * * @see org.apache.harmony.unpack200.bytecode.forms.ByteCodeForm#setByteCodeOperands(org.apache.harmony.unpack200.bytecode.ByteCode, * org.apache.harmony.unpack200.bytecode.OperandTable, * org.apache.harmony.unpack200.Segment) */ public void setByteCodeOperands(ByteCode byteCode, OperandManager operandManager, int codeLength) { super.setByteCodeOperands(byteCode, operandManager, codeLength); final int count = ((CPInterfaceMethodRef) byteCode .getNestedClassFileEntries()[0]).invokeInterfaceCount(); byteCode.getRewrite()[3] = count; } }
skyHALud/codenameone
Ports/iOSPort/xmlvm/apache-harmony-6.0-src-r991881/classlib/modules/pack200/src/main/java/org/apache/harmony/unpack200/bytecode/forms/IMethodRefForm.java
Java
gpl-2.0
2,333
/* * This is the source code of Telegram for Android v. 3.x.x. * It is licensed under GNU GPL v. 2 or later. * You should have received a copy of the license in this archive (see LICENSE). * * Copyright Nikolai Kudashov, 2013-2016. */ package org.pouyadr.ui; import android.animation.ObjectAnimator; import android.animation.StateListAnimator; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.res.Configuration; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Outline; import android.graphics.Typeface; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.support.annotation.NonNull; import android.text.Html; import android.text.InputType; import android.text.Spannable; import android.text.TextUtils; import android.text.method.LinkMovementMethod; import android.util.Base64; import android.util.Log; import android.util.TypedValue; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.ViewOutlineProvider; import android.view.ViewTreeObserver; import android.view.animation.AccelerateInterpolator; import android.view.animation.DecelerateInterpolator; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import org.pouyadr.PhoneFormat.PhoneFormat; import org.pouyadr.Pouya.Helper.GhostPorotocol; import org.pouyadr.Pouya.Helper.ThemeChanger; import org.pouyadr.Pouya.Setting.Setting; import org.pouyadr.finalsoft.FontActivity; import org.pouyadr.finalsoft.Fonts; import org.pouyadr.messenger.AndroidUtilities; import org.pouyadr.messenger.AnimationCompat.AnimatorListenerAdapterProxy; import org.pouyadr.messenger.AnimationCompat.AnimatorSetProxy; import org.pouyadr.messenger.AnimationCompat.ObjectAnimatorProxy; import org.pouyadr.messenger.AnimationCompat.ViewProxy; import org.pouyadr.messenger.ApplicationLoader; import org.pouyadr.messenger.BuildVars; import org.pouyadr.messenger.FileLoader; import org.pouyadr.messenger.FileLog; import org.pouyadr.messenger.LocaleController; import org.pouyadr.messenger.MediaController; import org.pouyadr.messenger.MessageObject; import org.pouyadr.messenger.MessagesController; import org.pouyadr.messenger.MessagesStorage; import org.pouyadr.messenger.NotificationCenter; import org.pouyadr.messenger.R; import org.pouyadr.messenger.UserConfig; import org.pouyadr.messenger.UserObject; import org.pouyadr.messenger.browser.Browser; import org.pouyadr.tgnet.ConnectionsManager; import org.pouyadr.tgnet.RequestDelegate; import org.pouyadr.tgnet.SerializedData; import org.pouyadr.tgnet.TLObject; import org.pouyadr.tgnet.TLRPC; import org.pouyadr.ui.ActionBar.ActionBar; import org.pouyadr.ui.ActionBar.ActionBarMenu; import org.pouyadr.ui.ActionBar.ActionBarMenuItem; import org.pouyadr.ui.ActionBar.BaseFragment; import org.pouyadr.ui.ActionBar.BottomSheet; import org.pouyadr.ui.ActionBar.Theme; import org.pouyadr.ui.Adapters.BaseFragmentAdapter; import org.pouyadr.ui.Cells.CheckBoxCell; import org.pouyadr.ui.Cells.EmptyCell; import org.pouyadr.ui.Cells.HeaderCell; import org.pouyadr.ui.Cells.ShadowSectionCell; import org.pouyadr.ui.Cells.TextCheckCell; import org.pouyadr.ui.Cells.TextDetailSettingsCell; import org.pouyadr.ui.Cells.TextInfoCell; import org.pouyadr.ui.Cells.TextSettingsCell; import org.pouyadr.ui.Components.AvatarDrawable; import org.pouyadr.ui.Components.AvatarUpdater; import org.pouyadr.ui.Components.BackupImageView; import org.pouyadr.ui.Components.LayoutHelper; import org.pouyadr.ui.Components.NumberPicker; import java.io.File; import java.util.ArrayList; import java.util.Locale; public class SettingsActivity extends BaseFragment implements NotificationCenter.NotificationCenterDelegate, PhotoViewer.PhotoViewerProvider { private ListView listView; private ListAdapter listAdapter; private BackupImageView avatarImage; private TextView nameTextView; private TextView onlineTextView; private ImageView writeButton; private AnimatorSetProxy writeButtonAnimation; private AvatarUpdater avatarUpdater = new AvatarUpdater(); private View extraHeightView; private View shadowView; private int extraHeight; private int overscrollRow; private int emptyRow; private int numberSectionRow; private int newgeramsectionrow; private int newgeramsectionrow2; private int ghostactivate; private int showdateshamsi; private int sendtyping; private int showtimeago; private int numberRow; private int usernameRow; private int settingsSectionRow; private int settingsSectionRow2; private int enableAnimationsRow; private int notificationRow; private int backgroundRow; private int languageRow; private int privacyRow; private int mediaDownloadSection; private int mediaDownloadSection2; private int mobileDownloadRow; private int wifiDownloadRow; private int roamingDownloadRow; private int saveToGalleryRow; private int messagesSectionRow; private int messagesSectionRow2; private int customTabsRow; private int directShareRow; private int textSizeRow; private int fontType; private int stickersRow; private int cacheRow; private int raiseToSpeakRow; private int sendByEnterRow; private int supportSectionRow; private int supportSectionRow2; private int askQuestionRow; private int telegramFaqRow; private int privacyPolicyRow; private int sendLogsRow; private int clearLogsRow; private int switchBackendButtonRow; private int versionRow; private int contactsSectionRow; private int contactsReimportRow; private int contactsSortRow; private int autoplayGifsRow; private int rowCount; private final static int edit_name = 1; private final static int logout = 2; private int answeringmachinerow2; private int answeringmachinerow; private int tabletforceoverride; private int anweringmachinactive; private int answermachinetext; private static class LinkMovementMethodMy extends LinkMovementMethod { @Override public boolean onTouchEvent(@NonNull TextView widget, @NonNull Spannable buffer, @NonNull MotionEvent event) { try { return super.onTouchEvent(widget, buffer, event); } catch (Exception e) { FileLog.e("tmessages", e); } return false; } } @Override public boolean onFragmentCreate() { super.onFragmentCreate(); avatarUpdater.parentFragment = this; avatarUpdater.delegate = new AvatarUpdater.AvatarUpdaterDelegate() { @Override public void didUploadedPhoto(TLRPC.InputFile file, TLRPC.PhotoSize small, TLRPC.PhotoSize big) { TLRPC.TL_photos_uploadProfilePhoto req = new TLRPC.TL_photos_uploadProfilePhoto(); req.caption = ""; req.crop = new TLRPC.TL_inputPhotoCropAuto(); req.file = file; req.geo_point = new TLRPC.TL_inputGeoPointEmpty(); ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { @Override public void run(TLObject response, TLRPC.TL_error error) { if (error == null) { TLRPC.User user = MessagesController.getInstance().getUser(UserConfig.getClientUserId()); if (user == null) { user = UserConfig.getCurrentUser(); if (user == null) { return; } MessagesController.getInstance().putUser(user, false); } else { UserConfig.setCurrentUser(user); } TLRPC.TL_photos_photo photo = (TLRPC.TL_photos_photo) response; ArrayList<TLRPC.PhotoSize> sizes = photo.photo.sizes; TLRPC.PhotoSize smallSize = FileLoader.getClosestPhotoSizeWithSize(sizes, 100); TLRPC.PhotoSize bigSize = FileLoader.getClosestPhotoSizeWithSize(sizes, 1000); user.photo = new TLRPC.TL_userProfilePhoto(); user.photo.photo_id = photo.photo.id; if (smallSize != null) { user.photo.photo_small = smallSize.location; } if (bigSize != null) { user.photo.photo_big = bigSize.location; } else if (smallSize != null) { user.photo.photo_small = smallSize.location; } MessagesStorage.getInstance().clearUserPhotos(user.id); ArrayList<TLRPC.User> users = new ArrayList<>(); users.add(user); MessagesStorage.getInstance().putUsersAndChats(users, null, false, true); AndroidUtilities.runOnUIThread(new Runnable() { @Override public void run() { NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, MessagesController.UPDATE_MASK_ALL); NotificationCenter.getInstance().postNotificationName(NotificationCenter.mainUserInfoChanged); UserConfig.saveConfig(true); } }); } } }); } }; NotificationCenter.getInstance().addObserver(this, NotificationCenter.updateInterfaces); rowCount = 0; overscrollRow = rowCount++; emptyRow = rowCount++; numberSectionRow = rowCount++; numberRow = rowCount++; usernameRow = rowCount++; newgeramsectionrow = rowCount++; newgeramsectionrow2 = rowCount++; ghostactivate = rowCount++; sendtyping = rowCount++; showtimeago = rowCount++; showdateshamsi = rowCount++; tabletforceoverride = rowCount++; answeringmachinerow = rowCount++; answeringmachinerow2 = rowCount++; anweringmachinactive = rowCount++; answermachinetext = rowCount++; settingsSectionRow = rowCount++; settingsSectionRow2 = rowCount++; notificationRow = rowCount++; privacyRow = rowCount++; backgroundRow = rowCount++; languageRow = rowCount++; enableAnimationsRow = rowCount++; mediaDownloadSection = rowCount++; mediaDownloadSection2 = rowCount++; mobileDownloadRow = rowCount++; wifiDownloadRow = rowCount++; roamingDownloadRow = rowCount++; if (Build.VERSION.SDK_INT >= 11) { autoplayGifsRow = rowCount++; } saveToGalleryRow = rowCount++; messagesSectionRow = rowCount++; messagesSectionRow2 = rowCount++; customTabsRow = rowCount++; if (Build.VERSION.SDK_INT >= 23) { directShareRow = rowCount++; } textSizeRow = rowCount++; fontType = rowCount++; stickersRow = rowCount++; cacheRow = rowCount++; raiseToSpeakRow = rowCount++; sendByEnterRow = rowCount++; supportSectionRow = rowCount++; supportSectionRow2 = rowCount++; askQuestionRow = rowCount++; telegramFaqRow = rowCount++; privacyPolicyRow = rowCount++; if (BuildVars.DEBUG_VERSION) { sendLogsRow = rowCount++; clearLogsRow = rowCount++; switchBackendButtonRow = rowCount++; } versionRow = rowCount++; //contactsSectionRow = rowCount++; //contactsReimportRow = rowCount++; //contactsSortRow = rowCount++; MessagesController.getInstance().loadFullUser(UserConfig.getCurrentUser(), classGuid, true); return true; } @Override public void onFragmentDestroy() { super.onFragmentDestroy(); if (avatarImage != null) { avatarImage.setImageDrawable(null); } MessagesController.getInstance().cancelLoadFullUser(UserConfig.getClientUserId()); NotificationCenter.getInstance().removeObserver(this, NotificationCenter.updateInterfaces); avatarUpdater.clear(); } @Override public View createView(final Context context) { actionBar.setBackgroundColor(ThemeChanger.getcurrent().getActionbarcolor()); actionBar.setItemsBackgroundColor(ThemeChanger.getcurrent().getActionbarcolor()); actionBar.setBackButtonImage(R.drawable.ic_ab_back); actionBar.setAddToContainer(false); extraHeight = 88; if (AndroidUtilities.isTablet()) { actionBar.setOccupyStatusBar(false); } actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { @Override public void onItemClick(int id) { if (id == -1) { finishFragment(); } else if (id == edit_name) { presentFragment(new ChangeNameActivity()); } else if (id == logout) { if (getParentActivity() == null) { return; } AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); builder.setMessage(LocaleController.getString("AreYouSureLogout", R.string.AreYouSureLogout)); builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { MessagesController.getInstance().performLogout(true); } }); builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); showDialog(builder.create()); } } }); ActionBarMenu menu = actionBar.createMenu(); ActionBarMenuItem item = menu.addItem(0, R.drawable.ic_ab_other); item.addSubItem(edit_name, LocaleController.getString("EditName", R.string.EditName), 0); item.addSubItem(logout, LocaleController.getString("LogOut", R.string.LogOut), 0); listAdapter = new ListAdapter(context); fragmentView = new FrameLayout(context) { @Override protected boolean drawChild(@NonNull Canvas canvas, @NonNull View child, long drawingTime) { if (child == listView) { boolean result = super.drawChild(canvas, child, drawingTime); if (parentLayout != null) { int actionBarHeight = 0; int childCount = getChildCount(); for (int a = 0; a < childCount; a++) { View view = getChildAt(a); if (view == child) { continue; } if (view instanceof ActionBar && view.getVisibility() == VISIBLE) { if (((ActionBar) view).getCastShadows()) { actionBarHeight = view.getMeasuredHeight(); } break; } } parentLayout.drawHeaderShadow(canvas, actionBarHeight); } return result; } else { return super.drawChild(canvas, child, drawingTime); } } }; FrameLayout frameLayout = (FrameLayout) fragmentView; listView = new ListView(context); listView.setDivider(null); listView.setDividerHeight(0); listView.setVerticalScrollBarEnabled(false); AndroidUtilities.setListViewEdgeEffectColor(listView, AvatarDrawable.getProfileBackColorForId(5)); frameLayout.addView(listView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT)); listView.setAdapter(listAdapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, final int i, long l) { if (i == textSizeRow) { if (getParentActivity() == null) { return; } AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); builder.setTitle(LocaleController.getString("TextSize", R.string.TextSize)); final NumberPicker numberPicker = new NumberPicker(getParentActivity()); numberPicker.setMinValue(12); numberPicker.setMaxValue(30); numberPicker.setValue(MessagesController.getInstance().fontSize); builder.setView(numberPicker); builder.setNegativeButton(LocaleController.getString("Done", R.string.Done), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); editor.putInt("fons_size", numberPicker.getValue()); MessagesController.getInstance().fontSize = numberPicker.getValue(); editor.commit(); if (listView != null) { listView.invalidateViews(); } } }); showDialog(builder.create()); } else if (i == fontType) { // Toast.makeText(context, "ssssssssssss", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(context, FontActivity.class); context.startActivity(intent); } else if (i == enableAnimationsRow) { SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); boolean animations = preferences.getBoolean("view_animations", true); SharedPreferences.Editor editor = preferences.edit(); editor.putBoolean("view_animations", !animations); editor.commit(); if (view instanceof TextCheckCell) { ((TextCheckCell) view).setChecked(!animations); } } else if (i == notificationRow) { presentFragment(new NotificationsSettingsActivity()); } else if (i == answermachinetext) { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle(LocaleController.getString("Answeringmachinetext", R.string.Answeringmachinetext)); final EditText input = new EditText(context); input.setText(Setting.getAnsweringmachineText()); input.setInputType(InputType.TYPE_CLASS_TEXT); builder.setView(input); builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Setting.setAnsweringmachineText(input.getText().toString()); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); builder.show(); } else if (i == backgroundRow) { presentFragment(new WallpapersActivity()); } else if (i == askQuestionRow) { if (getParentActivity() == null) { return; } final TextView message = new TextView(getParentActivity()); message.setText(Html.fromHtml(LocaleController.getString("AskAQuestionInfo", R.string.AskAQuestionInfo))); message.setTextSize(18); message.setLinkTextColor(Theme.MSG_LINK_TEXT_COLOR); // message.setTypeface(AndroidUtilities.getTypeface(org.pouyadr.finalsoft.Fonts.CurrentFont())); message.setPadding(AndroidUtilities.dp(8), AndroidUtilities.dp(5), AndroidUtilities.dp(8), AndroidUtilities.dp(6)); message.setMovementMethod(new LinkMovementMethodMy()); AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); builder.setView(message); builder.setPositiveButton(LocaleController.getString("AskButton", R.string.AskButton), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { performAskAQuestion(); } }); builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); showDialog(builder.create()); } else if (i == sendLogsRow) { sendLogs(); } else if (i == clearLogsRow) { FileLog.cleanupLogs(); } else if (i == sendByEnterRow) { SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); boolean send = preferences.getBoolean("send_by_enter", false); SharedPreferences.Editor editor = preferences.edit(); editor.putBoolean("send_by_enter", !send); editor.commit(); if (view instanceof TextCheckCell) { ((TextCheckCell) view).setChecked(!send); } } else if (i == ghostactivate) { boolean send = Setting.getGhostMode(); GhostPorotocol.toggleGhostPortocol(); if (view instanceof TextCheckCell) { ((TextCheckCell) view).setChecked(!send); } } else if (i == sendtyping) { boolean send = Setting.getSendTyping(); Setting.setSendTyping(!send); if (view instanceof TextCheckCell) { ((TextCheckCell) view).setChecked(!send); } } else if (i == anweringmachinactive) { boolean send = Setting.getAnsweringMachine(); Setting.setAnsweringMachine(!send); if (view instanceof TextCheckCell) { ((TextCheckCell) view).setChecked(!send); } } else if (i == showtimeago) { boolean send = Setting.getShowTimeAgo(); Setting.setShowTimeAgo(!send); if (view instanceof TextCheckCell) { ((TextCheckCell) view).setChecked(!send); } } else if (i == showdateshamsi) { boolean send = Setting.getDatePersian(); Setting.setDatePersian(!send); if (view instanceof TextCheckCell) { ((TextCheckCell) view).setChecked(!send); } } else if (i == tabletforceoverride) { boolean send = Setting.getTabletMode(); Setting.setTabletMode(!send); if (view instanceof TextCheckCell) { ((TextCheckCell) view).setChecked(!send); } } else if (i == raiseToSpeakRow) { MediaController.getInstance().toogleRaiseToSpeak(); if (view instanceof TextCheckCell) { ((TextCheckCell) view).setChecked(MediaController.getInstance().canRaiseToSpeak()); } } else if (i == autoplayGifsRow) { MediaController.getInstance().toggleAutoplayGifs(); if (view instanceof TextCheckCell) { ((TextCheckCell) view).setChecked(MediaController.getInstance().canAutoplayGifs()); } } else if (i == saveToGalleryRow) { MediaController.getInstance().toggleSaveToGallery(); if (view instanceof TextCheckCell) { ((TextCheckCell) view).setChecked(MediaController.getInstance().canSaveToGallery()); } } else if (i == customTabsRow) { MediaController.getInstance().toggleCustomTabs(); if (view instanceof TextCheckCell) { ((TextCheckCell) view).setChecked(MediaController.getInstance().canCustomTabs()); } } else if (i == directShareRow) { MediaController.getInstance().toggleDirectShare(); if (view instanceof TextCheckCell) { ((TextCheckCell) view).setChecked(MediaController.getInstance().canDirectShare()); } } else if (i == privacyRow) { presentFragment(new PrivacySettingsActivity()); } else if (i == languageRow) { presentFragment(new LanguageSelectActivity()); } else if (i == switchBackendButtonRow) { if (getParentActivity() == null) { return; } AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); builder.setMessage(LocaleController.getString("AreYouSure", R.string.AreYouSure)); builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { ConnectionsManager.getInstance().switchBackend(); } }); builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); showDialog(builder.create()); } else if (i == telegramFaqRow) { Browser.openUrl(getParentActivity(), LocaleController.getString("TelegramFaqUrl", R.string.TelegramFaqUrl)); } else if (i == privacyPolicyRow) { Browser.openUrl(getParentActivity(), LocaleController.getString("PrivacyPolicyUrl", R.string.PrivacyPolicyUrl)); } else if (i == contactsReimportRow) { //not implemented } else if (i == contactsSortRow) { if (getParentActivity() == null) { return; } AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); builder.setTitle(LocaleController.getString("SortBy", R.string.SortBy)); builder.setItems(new CharSequence[]{ LocaleController.getString("Default", R.string.Default), LocaleController.getString("SortFirstName", R.string.SortFirstName), LocaleController.getString("SortLastName", R.string.SortLastName) }, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); editor.putInt("sortContactsBy", which); editor.commit(); if (listView != null) { listView.invalidateViews(); } } }); builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); showDialog(builder.create()); } else if (i == wifiDownloadRow || i == mobileDownloadRow || i == roamingDownloadRow) { if (getParentActivity() == null) { return; } final boolean maskValues[] = new boolean[6]; BottomSheet.Builder builder = new BottomSheet.Builder(getParentActivity()); int mask = 0; if (i == mobileDownloadRow) { mask = MediaController.getInstance().mobileDataDownloadMask; } else if (i == wifiDownloadRow) { mask = MediaController.getInstance().wifiDownloadMask; } else if (i == roamingDownloadRow) { mask = MediaController.getInstance().roamingDownloadMask; } builder.setApplyTopPadding(false); builder.setApplyBottomPadding(false); LinearLayout linearLayout = new LinearLayout(getParentActivity()); linearLayout.setOrientation(LinearLayout.VERTICAL); for (int a = 0; a < 6; a++) { String name = null; if (a == 0) { maskValues[a] = (mask & MediaController.AUTODOWNLOAD_MASK_PHOTO) != 0; name = LocaleController.getString("AttachPhoto", R.string.AttachPhoto); } else if (a == 1) { maskValues[a] = (mask & MediaController.AUTODOWNLOAD_MASK_AUDIO) != 0; name = LocaleController.getString("AttachAudio", R.string.AttachAudio); } else if (a == 2) { maskValues[a] = (mask & MediaController.AUTODOWNLOAD_MASK_VIDEO) != 0; name = LocaleController.getString("AttachVideo", R.string.AttachVideo); } else if (a == 3) { maskValues[a] = (mask & MediaController.AUTODOWNLOAD_MASK_DOCUMENT) != 0; name = LocaleController.getString("AttachDocument", R.string.AttachDocument); } else if (a == 4) { maskValues[a] = (mask & MediaController.AUTODOWNLOAD_MASK_MUSIC) != 0; name = LocaleController.getString("AttachMusic", R.string.AttachMusic); } else if (a == 5) { if (Build.VERSION.SDK_INT >= 11) { maskValues[a] = (mask & MediaController.AUTODOWNLOAD_MASK_GIF) != 0; name = LocaleController.getString("AttachGif", R.string.AttachGif); } else { continue; } } CheckBoxCell checkBoxCell = new CheckBoxCell(getParentActivity()); checkBoxCell.setTag(a); checkBoxCell.setBackgroundResource(R.drawable.list_selector); linearLayout.addView(checkBoxCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 48)); checkBoxCell.setText(name, "", maskValues[a], true); checkBoxCell.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { CheckBoxCell cell = (CheckBoxCell) v; int num = (Integer) cell.getTag(); maskValues[num] = !maskValues[num]; cell.setChecked(maskValues[num], true); } }); } BottomSheet.BottomSheetCell cell = new BottomSheet.BottomSheetCell(getParentActivity(), 1); cell.setBackgroundResource(R.drawable.list_selector); cell.setTextAndIcon(LocaleController.getString("Save", R.string.Save).toUpperCase(), 0); cell.setTextColor(Theme.AUTODOWNLOAD_SHEET_SAVE_TEXT_COLOR); cell.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { if (visibleDialog != null) { visibleDialog.dismiss(); } } catch (Exception e) { FileLog.e("tmessages", e); } int newMask = 0; for (int a = 0; a < 6; a++) { if (maskValues[a]) { if (a == 0) { newMask |= MediaController.AUTODOWNLOAD_MASK_PHOTO; } else if (a == 1) { newMask |= MediaController.AUTODOWNLOAD_MASK_AUDIO; } else if (a == 2) { newMask |= MediaController.AUTODOWNLOAD_MASK_VIDEO; } else if (a == 3) { newMask |= MediaController.AUTODOWNLOAD_MASK_DOCUMENT; } else if (a == 4) { newMask |= MediaController.AUTODOWNLOAD_MASK_MUSIC; } else if (a == 5) { newMask |= MediaController.AUTODOWNLOAD_MASK_GIF; } } } SharedPreferences.Editor editor = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE).edit(); if (i == mobileDownloadRow) { editor.putInt("mobileDataDownloadMask", newMask); MediaController.getInstance().mobileDataDownloadMask = newMask; } else if (i == wifiDownloadRow) { editor.putInt("wifiDownloadMask", newMask); MediaController.getInstance().wifiDownloadMask = newMask; } else if (i == roamingDownloadRow) { editor.putInt("roamingDownloadMask", newMask); MediaController.getInstance().roamingDownloadMask = newMask; } editor.commit(); if (listView != null) { listView.invalidateViews(); } } }); linearLayout.addView(cell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 48)); builder.setCustomView(linearLayout); showDialog(builder.create()); } else if (i == usernameRow) { presentFragment(new ChangeUsernameActivity()); } else if (i == numberRow) { presentFragment(new ChangePhoneHelpActivity()); } else if (i == stickersRow) { presentFragment(new StickersActivity()); } else if (i == cacheRow) { presentFragment(new CacheControlActivity()); } } }); frameLayout.addView(actionBar); extraHeightView = new View(context); ViewProxy.setPivotY(extraHeightView, 0); extraHeightView.setBackgroundColor(ThemeChanger.getcurrent().getActionbarcolor()); frameLayout.addView(extraHeightView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 88)); shadowView = new View(context); shadowView.setBackgroundResource(R.drawable.header_shadow); frameLayout.addView(shadowView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 3)); avatarImage = new BackupImageView(context); avatarImage.setRoundRadius(AndroidUtilities.dp(21)); ViewProxy.setPivotX(avatarImage, 0); ViewProxy.setPivotY(avatarImage, 0); frameLayout.addView(avatarImage, LayoutHelper.createFrame(42, 42, Gravity.TOP | Gravity.LEFT, 64, 0, 0, 0)); avatarImage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { TLRPC.User user = MessagesController.getInstance().getUser(UserConfig.getClientUserId()); if (user != null && user.photo != null && user.photo.photo_big != null) { PhotoViewer.getInstance().setParentActivity(getParentActivity()); PhotoViewer.getInstance().openPhoto(user.photo.photo_big, SettingsActivity.this); } } }); nameTextView = new TextView(context); nameTextView.setTextColor(0xffffffff); nameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18); nameTextView.setLines(1); nameTextView.setMaxLines(1); nameTextView.setSingleLine(true); nameTextView.setEllipsize(TextUtils.TruncateAt.END); nameTextView.setGravity(Gravity.LEFT); nameTextView.setTypeface(AndroidUtilities.getTypeface(org.pouyadr.finalsoft.Fonts.CurrentFont())); ViewProxy.setPivotX(nameTextView, 0); ViewProxy.setPivotY(nameTextView, 0); frameLayout.addView(nameTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, 118, 0, 48, 0)); onlineTextView = new TextView(context); onlineTextView.setTextColor(AvatarDrawable.getProfileTextColorForId(5)); onlineTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); onlineTextView.setLines(1); onlineTextView.setMaxLines(1); onlineTextView.setSingleLine(true); onlineTextView.setEllipsize(TextUtils.TruncateAt.END); onlineTextView.setGravity(Gravity.LEFT); frameLayout.addView(onlineTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, 118, 0, 48, 0)); writeButton = new ImageView(context); writeButton.setBackgroundResource(R.drawable.floating_user_states); writeButton.setImageResource(R.drawable.floating_camera); writeButton.setScaleType(ImageView.ScaleType.CENTER); if (Build.VERSION.SDK_INT >= 21) { StateListAnimator animator = new StateListAnimator(); animator.addState(new int[]{android.R.attr.state_pressed}, ObjectAnimator.ofFloat(writeButton, "translationZ", AndroidUtilities.dp(2), AndroidUtilities.dp(4)).setDuration(200)); animator.addState(new int[]{}, ObjectAnimator.ofFloat(writeButton, "translationZ", AndroidUtilities.dp(4), AndroidUtilities.dp(2)).setDuration(200)); writeButton.setStateListAnimator(animator); writeButton.setOutlineProvider(new ViewOutlineProvider() { @SuppressLint("NewApi") @Override public void getOutline(View view, Outline outline) { outline.setOval(0, 0, AndroidUtilities.dp(56), AndroidUtilities.dp(56)); } }); } frameLayout.addView(writeButton, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.RIGHT | Gravity.TOP, 0, 0, 16, 0)); writeButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (getParentActivity() == null) { return; } AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); CharSequence[] items; TLRPC.User user = MessagesController.getInstance().getUser(UserConfig.getClientUserId()); if (user == null) { user = UserConfig.getCurrentUser(); } if (user == null) { return; } boolean fullMenu = false; if (user.photo != null && user.photo.photo_big != null && !(user.photo instanceof TLRPC.TL_userProfilePhotoEmpty)) { items = new CharSequence[]{LocaleController.getString("FromCamera", R.string.FromCamera), LocaleController.getString("FromGalley", R.string.FromGalley), LocaleController.getString("DeletePhoto", R.string.DeletePhoto)}; fullMenu = true; } else { items = new CharSequence[]{LocaleController.getString("FromCamera", R.string.FromCamera), LocaleController.getString("FromGalley", R.string.FromGalley)}; } final boolean full = fullMenu; builder.setItems(items, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { if (i == 0) { avatarUpdater.openCamera(); } else if (i == 1) { avatarUpdater.openGallery(); } else if (i == 2) { MessagesController.getInstance().deleteUserPhoto(null); } } }); showDialog(builder.create()); } }); needLayout(); listView.setOnScrollListener(new AbsListView.OnScrollListener() { @Override public void onScrollStateChanged(AbsListView view, int scrollState) { } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { if (totalItemCount == 0) { return; } int height = 0; View child = view.getChildAt(0); if (child != null) { if (firstVisibleItem == 0) { height = AndroidUtilities.dp(88) + (child.getTop() < 0 ? child.getTop() : 0); } if (extraHeight != height) { extraHeight = height; needLayout(); } } } }); return fragmentView; } @Override protected void onDialogDismiss(Dialog dialog) { MediaController.getInstance().checkAutodownloadSettings(); } @Override public void updatePhotoAtIndex(int index) { } @Override public PhotoViewer.PlaceProviderObject getPlaceForPhoto(MessageObject messageObject, TLRPC.FileLocation fileLocation, int index) { if (fileLocation == null) { return null; } TLRPC.User user = MessagesController.getInstance().getUser(UserConfig.getClientUserId()); if (user != null && user.photo != null && user.photo.photo_big != null) { TLRPC.FileLocation photoBig = user.photo.photo_big; if (photoBig.local_id == fileLocation.local_id && photoBig.volume_id == fileLocation.volume_id && photoBig.dc_id == fileLocation.dc_id) { int coords[] = new int[2]; avatarImage.getLocationInWindow(coords); PhotoViewer.PlaceProviderObject object = new PhotoViewer.PlaceProviderObject(); object.viewX = coords[0]; object.viewY = coords[1] - AndroidUtilities.statusBarHeight; object.parentView = avatarImage; object.imageReceiver = avatarImage.getImageReceiver(); object.user_id = UserConfig.getClientUserId(); object.thumb = object.imageReceiver.getBitmap(); object.size = -1; object.radius = avatarImage.getImageReceiver().getRoundRadius(); object.scale = ViewProxy.getScaleX(avatarImage); return object; } } return null; } @Override public Bitmap getThumbForPhoto(MessageObject messageObject, TLRPC.FileLocation fileLocation, int index) { return null; } @Override public void willSwitchFromPhoto(MessageObject messageObject, TLRPC.FileLocation fileLocation, int index) { } @Override public void willHidePhotoViewer() { avatarImage.getImageReceiver().setVisible(true, true); } @Override public boolean isPhotoChecked(int index) { return false; } @Override public void setPhotoChecked(int index) { } @Override public boolean cancelButtonPressed() { return true; } @Override public void sendButtonPressed(int index) { } @Override public int getSelectedCount() { return 0; } public void performAskAQuestion() { final SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); int uid = preferences.getInt("support_id", 0); TLRPC.User supportUser = null; if (uid != 0) { supportUser = MessagesController.getInstance().getUser(uid); if (supportUser == null) { String userString = preferences.getString("support_user", null); if (userString != null) { try { byte[] datacentersBytes = Base64.decode(userString, Base64.DEFAULT); if (datacentersBytes != null) { SerializedData data = new SerializedData(datacentersBytes); supportUser = TLRPC.User.TLdeserialize(data, data.readInt32(false), false); if (supportUser != null && supportUser.id == 333000) { supportUser = null; } data.cleanup(); } } catch (Exception e) { FileLog.e("tmessages", e); supportUser = null; } } } } if (supportUser == null) { final ProgressDialog progressDialog = new ProgressDialog(getParentActivity()); progressDialog.setMessage(LocaleController.getString("Loading", R.string.Loading)); progressDialog.setCanceledOnTouchOutside(false); progressDialog.setCancelable(false); progressDialog.show(); TLRPC.TL_help_getSupport req = new TLRPC.TL_help_getSupport(); ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { @Override public void run(TLObject response, TLRPC.TL_error error) { if (error == null) { final TLRPC.TL_help_support res = (TLRPC.TL_help_support) response; AndroidUtilities.runOnUIThread(new Runnable() { @Override public void run() { SharedPreferences.Editor editor = preferences.edit(); editor.putInt("support_id", res.user.id); SerializedData data = new SerializedData(); res.user.serializeToStream(data); editor.putString("support_user", Base64.encodeToString(data.toByteArray(), Base64.DEFAULT)); editor.commit(); data.cleanup(); try { progressDialog.dismiss(); } catch (Exception e) { FileLog.e("tmessages", e); } ArrayList<TLRPC.User> users = new ArrayList<>(); users.add(res.user); MessagesStorage.getInstance().putUsersAndChats(users, null, true, true); MessagesController.getInstance().putUser(res.user, false); Bundle args = new Bundle(); args.putInt("user_id", res.user.id); presentFragment(new ChatActivity(args)); } }); } else { AndroidUtilities.runOnUIThread(new Runnable() { @Override public void run() { try { progressDialog.dismiss(); } catch (Exception e) { FileLog.e("tmessages", e); } } }); } } }); } else { MessagesController.getInstance().putUser(supportUser, true); Bundle args = new Bundle(); args.putInt("user_id", supportUser.id); presentFragment(new ChatActivity(args)); } } @Override public void onActivityResultFragment(int requestCode, int resultCode, Intent data) { avatarUpdater.onActivityResult(requestCode, resultCode, data); } @Override public void saveSelfArgs(Bundle args) { if (avatarUpdater != null && avatarUpdater.currentPicturePath != null) { args.putString("path", avatarUpdater.currentPicturePath); } } @Override public void restoreSelfArgs(Bundle args) { if (avatarUpdater != null) { avatarUpdater.currentPicturePath = args.getString("path"); } } @Override public void didReceivedNotification(int id, Object... args) { if (id == NotificationCenter.updateInterfaces) { int mask = (Integer) args[0]; if ((mask & MessagesController.UPDATE_MASK_AVATAR) != 0 || (mask & MessagesController.UPDATE_MASK_NAME) != 0) { updateUserData(); } } } @Override public void onResume() { super.onResume(); if (listAdapter != null) { listAdapter.notifyDataSetChanged(); } updateUserData(); fixLayout(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); fixLayout(); } private void needLayout() { FrameLayout.LayoutParams layoutParams; int newTop = (actionBar.getOccupyStatusBar() ? AndroidUtilities.statusBarHeight : 0) + ActionBar.getCurrentActionBarHeight(); if (listView != null) { layoutParams = (FrameLayout.LayoutParams) listView.getLayoutParams(); if (layoutParams.topMargin != newTop) { layoutParams.topMargin = newTop; listView.setLayoutParams(layoutParams); ViewProxy.setTranslationY(extraHeightView, newTop); } } if (avatarImage != null) { float diff = extraHeight / (float) AndroidUtilities.dp(88); ViewProxy.setScaleY(extraHeightView, diff); ViewProxy.setTranslationY(shadowView, newTop + extraHeight); if (Build.VERSION.SDK_INT < 11) { layoutParams = (FrameLayout.LayoutParams) writeButton.getLayoutParams(); layoutParams.topMargin = (actionBar.getOccupyStatusBar() ? AndroidUtilities.statusBarHeight : 0) + ActionBar.getCurrentActionBarHeight() + extraHeight - AndroidUtilities.dp(29.5f); writeButton.setLayoutParams(layoutParams); } else { ViewProxy.setTranslationY(writeButton, (actionBar.getOccupyStatusBar() ? AndroidUtilities.statusBarHeight : 0) + ActionBar.getCurrentActionBarHeight() + extraHeight - AndroidUtilities.dp(29.5f)); } final boolean setVisible = diff > 0.2f; boolean currentVisible = writeButton.getTag() == null; if (setVisible != currentVisible) { if (setVisible) { writeButton.setTag(null); writeButton.setVisibility(View.VISIBLE); } else { writeButton.setTag(0); } if (writeButtonAnimation != null) { AnimatorSetProxy old = writeButtonAnimation; writeButtonAnimation = null; old.cancel(); } writeButtonAnimation = new AnimatorSetProxy(); if (setVisible) { writeButtonAnimation.setInterpolator(new DecelerateInterpolator()); writeButtonAnimation.playTogether( ObjectAnimatorProxy.ofFloat(writeButton, "scaleX", 1.0f), ObjectAnimatorProxy.ofFloat(writeButton, "scaleY", 1.0f), ObjectAnimatorProxy.ofFloat(writeButton, "alpha", 1.0f) ); } else { writeButtonAnimation.setInterpolator(new AccelerateInterpolator()); writeButtonAnimation.playTogether( ObjectAnimatorProxy.ofFloat(writeButton, "scaleX", 0.2f), ObjectAnimatorProxy.ofFloat(writeButton, "scaleY", 0.2f), ObjectAnimatorProxy.ofFloat(writeButton, "alpha", 0.0f) ); } writeButtonAnimation.setDuration(150); writeButtonAnimation.addListener(new AnimatorListenerAdapterProxy() { @Override public void onAnimationEnd(Object animation) { if (writeButtonAnimation != null && writeButtonAnimation.equals(animation)) { writeButton.clearAnimation(); writeButton.setVisibility(setVisible ? View.VISIBLE : View.GONE); writeButtonAnimation = null; } } }); writeButtonAnimation.start(); } ViewProxy.setScaleX(avatarImage, (42 + 18 * diff) / 42.0f); ViewProxy.setScaleY(avatarImage, (42 + 18 * diff) / 42.0f); float avatarY = (actionBar.getOccupyStatusBar() ? AndroidUtilities.statusBarHeight : 0) + ActionBar.getCurrentActionBarHeight() / 2.0f * (1.0f + diff) - 21 * AndroidUtilities.density + 27 * AndroidUtilities.density * diff; ViewProxy.setTranslationX(avatarImage, -AndroidUtilities.dp(47) * diff); ViewProxy.setTranslationY(avatarImage, (float) Math.ceil(avatarY)); ViewProxy.setTranslationX(nameTextView, -21 * AndroidUtilities.density * diff); ViewProxy.setTranslationY(nameTextView, (float) Math.floor(avatarY) - (float) Math.ceil(AndroidUtilities.density) + (float) Math.floor(7 * AndroidUtilities.density * diff)); ViewProxy.setTranslationX(onlineTextView, -21 * AndroidUtilities.density * diff); ViewProxy.setTranslationY(onlineTextView, (float) Math.floor(avatarY) + AndroidUtilities.dp(22) + (float) Math.floor(11 * AndroidUtilities.density) * diff); ViewProxy.setScaleX(nameTextView, 1.0f + 0.12f * diff); ViewProxy.setScaleY(nameTextView, 1.0f + 0.12f * diff); } } private void fixLayout() { if (fragmentView == null) { return; } fragmentView.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { @Override public boolean onPreDraw() { if (fragmentView != null) { needLayout(); fragmentView.getViewTreeObserver().removeOnPreDrawListener(this); } return true; } }); } private void updateUserData() { TLRPC.User user = MessagesController.getInstance().getUser(UserConfig.getClientUserId()); TLRPC.FileLocation photo = null; TLRPC.FileLocation photoBig = null; if (user.photo != null) { photo = user.photo.photo_small; photoBig = user.photo.photo_big; } AvatarDrawable avatarDrawable = new AvatarDrawable(user, true); avatarDrawable.setColor(Theme.ACTION_BAR_MAIN_AVATAR_COLOR); if (avatarImage != null) { avatarImage.setImage(photo, "50_50", avatarDrawable); avatarImage.getImageReceiver().setVisible(!PhotoViewer.getInstance().isShowingImage(photoBig), false); nameTextView.setText(UserObject.getUserName(user)); onlineTextView.setText(LocaleController.getString("Online", R.string.Online)); avatarImage.getImageReceiver().setVisible(!PhotoViewer.getInstance().isShowingImage(photoBig), false); } } private void sendLogs() { try { ArrayList<Uri> uris = new ArrayList<>(); File sdCard = ApplicationLoader.applicationContext.getExternalFilesDir(null); File dir = new File(sdCard.getAbsolutePath() + "/logs"); File[] files = dir.listFiles(); for (File file : files) { uris.add(Uri.fromFile(file)); } if (uris.isEmpty()) { return; } Intent i = new Intent(Intent.ACTION_SEND_MULTIPLE); i.setType("message/rfc822"); i.putExtra(Intent.EXTRA_EMAIL, new String[]{BuildVars.SEND_LOGS_EMAIL}); i.putExtra(Intent.EXTRA_SUBJECT, "last logs"); i.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris); getParentActivity().startActivityForResult(Intent.createChooser(i, "Select email application."), 500); } catch (Exception e) { e.printStackTrace(); } } private class ListAdapter extends BaseFragmentAdapter { private Context mContext; public ListAdapter(Context context) { mContext = context; } @Override public boolean areAllItemsEnabled() { return false; } @Override public boolean isEnabled(int i) { return i == textSizeRow || i == fontType || i == tabletforceoverride || i == anweringmachinactive || i == answermachinetext || i == sendtyping || i == showdateshamsi || i == showtimeago || i == ghostactivate || i == enableAnimationsRow || i == notificationRow || i == backgroundRow || i == numberRow || i == askQuestionRow || i == sendLogsRow || i == sendByEnterRow || i == autoplayGifsRow || i == privacyRow || i == wifiDownloadRow || i == mobileDownloadRow || i == clearLogsRow || i == roamingDownloadRow || i == languageRow || i == usernameRow || i == switchBackendButtonRow || i == telegramFaqRow || i == contactsSortRow || i == contactsReimportRow || i == saveToGalleryRow || i == stickersRow || i == cacheRow || i == raiseToSpeakRow || i == privacyPolicyRow || i == customTabsRow || i == directShareRow; } @Override public int getCount() { return rowCount; } @Override public Object getItem(int i) { return null; } @Override public long getItemId(int i) { return i; } @Override public boolean hasStableIds() { return false; } @Override public View getView(int i, View view, ViewGroup viewGroup) { int type = getItemViewType(i); if (type == 0) { if (view == null) { view = new EmptyCell(mContext); } if (i == overscrollRow) { ((EmptyCell) view).setHeight(AndroidUtilities.dp(88)); } else { ((EmptyCell) view).setHeight(AndroidUtilities.dp(16)); } } else if (type == 1) { if (view == null) { view = new ShadowSectionCell(mContext); } } else if (type == 2) { if (view == null) { view = new TextSettingsCell(mContext); } TextSettingsCell textCell = (TextSettingsCell) view; if (i == textSizeRow) { SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); int size = preferences.getInt("fons_size", AndroidUtilities.isTablet() ? 18 : 16); textCell.setTextAndValue(LocaleController.getString("TextSize", R.string.TextSize), String.format("%d", size), true); } else if (i == fontType) { textCell.setTextAndValue( "نوع خط نوشتاری", Fonts.CurrentFont().replace("fonts/","").replace(".ttf",""), true); } else if (i == languageRow) { textCell.setTextAndValue(LocaleController.getString("Language", R.string.Language), LocaleController.getCurrentLanguageName(), true); } else if (i == contactsSortRow) { String value; SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); int sort = preferences.getInt("sortContactsBy", 0); if (sort == 0) { value = LocaleController.getString("Default", R.string.Default); } else if (sort == 1) { value = LocaleController.getString("FirstName", R.string.SortFirstName); } else { value = LocaleController.getString("LastName", R.string.SortLastName); } textCell.setTextAndValue(LocaleController.getString("SortBy", R.string.SortBy), value, true); } else if (i == notificationRow) { textCell.setText(LocaleController.getString("NotificationsAndSounds", R.string.NotificationsAndSounds), true); } else if (i == backgroundRow) { textCell.setText(LocaleController.getString("ChatBackground", R.string.ChatBackground), true); } else if (i == answermachinetext) { textCell.setTextAndValue(LocaleController.getString("Answeringmachinetext", R.string.Answeringmachinetext), Setting.getAnsweringmachineText(), true); } else if (i == sendLogsRow) { textCell.setText("Send Logs", true); } else if (i == clearLogsRow) { textCell.setText("Clear Logs", true); } else if (i == askQuestionRow) { textCell.setText(LocaleController.getString("AskAQuestion", R.string.AskAQuestion), true); } else if (i == privacyRow) { textCell.setText(LocaleController.getString("PrivacySettings", R.string.PrivacySettings), true); } else if (i == switchBackendButtonRow) { textCell.setText("Switch Backend", true); } else if (i == telegramFaqRow) { textCell.setText(LocaleController.getString("TelegramFAQ", R.string.TelegramFaq), true); } else if (i == contactsReimportRow) { textCell.setText(LocaleController.getString("ImportContacts", R.string.ImportContacts), true); } else if (i == stickersRow) { textCell.setText(LocaleController.getString("Stickers", R.string.Stickers), true); } else if (i == cacheRow) { textCell.setText(LocaleController.getString("CacheSettings", R.string.CacheSettings), true); } else if (i == privacyPolicyRow) { textCell.setText(LocaleController.getString("PrivacyPolicy", R.string.PrivacyPolicy), true); } } else if (type == 3) { if (view == null) { view = new TextCheckCell(mContext); } TextCheckCell textCell = (TextCheckCell) view; SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); if (i == enableAnimationsRow) { textCell.setTextAndCheck(LocaleController.getString("EnableAnimations", R.string.EnableAnimations), preferences.getBoolean("view_animations", true), false); } else if (i == sendByEnterRow) { textCell.setTextAndCheck(LocaleController.getString("SendByEnter", R.string.SendByEnter), preferences.getBoolean("send_by_enter", false), false); } else if (i == ghostactivate) { textCell.setTextAndValueAndCheck(LocaleController.getString("GhostMode", R.string.GhostMode), LocaleController.getString("GhostModeInfo", R.string.GhostModeInfo), Setting.getGhostMode(), true, true); } else if (i == sendtyping) { textCell.setTextAndValueAndCheck(LocaleController.getString("HideTypingState", R.string.HideTypingState), LocaleController.getString("HideTypingStateinfo", R.string.HideTypingStateinfo), Setting.getSendTyping(), true, true); } else if (i == anweringmachinactive) { textCell.setTextAndValueAndCheck(LocaleController.getString("Answeringmachineenable", R.string.Answeringmachineenable), LocaleController.getString("Answeringmachineenableinfo", R.string.Answeringmachineenableinfo), Setting.getAnsweringMachine(), true, true); } else if (i == showtimeago) { textCell.setTextAndValueAndCheck(LocaleController.getString("showtimeago", R.string.showtimeago), LocaleController.getString("showtimeagoinfo", R.string.showtimeagoinfo), Setting.getShowTimeAgo(), true, true); } else if (i == showdateshamsi) { textCell.setTextAndValueAndCheck(LocaleController.getString("showshamsidate", R.string.Showshamsidate), LocaleController.getString("showshamsidateinfo", R.string.showshamsidateinfo), Setting.getDatePersian(), true, true); } else if (i == tabletforceoverride) { textCell.setTextAndValueAndCheck(LocaleController.getString("TabletMode", R.string.TabletMode), LocaleController.getString("tabletmodeinfo", R.string.tabletmodeinfo), Setting.getTabletMode(), true, true); } else if (i == saveToGalleryRow) { textCell.setTextAndCheck(LocaleController.getString("SaveToGallerySettings", R.string.SaveToGallerySettings), MediaController.getInstance().canSaveToGallery(), false); } else if (i == autoplayGifsRow) { textCell.setTextAndCheck(LocaleController.getString("AutoplayGifs", R.string.AutoplayGifs), MediaController.getInstance().canAutoplayGifs(), true); } else if (i == raiseToSpeakRow) { textCell.setTextAndCheck(LocaleController.getString("RaiseToSpeak", R.string.RaiseToSpeak), MediaController.getInstance().canRaiseToSpeak(), true); } else if (i == customTabsRow) { textCell.setTextAndValueAndCheck(LocaleController.getString("ChromeCustomTabs", R.string.ChromeCustomTabs), LocaleController.getString("ChromeCustomTabsInfo", R.string.ChromeCustomTabsInfo), MediaController.getInstance().canCustomTabs(), false, true); } else if (i == directShareRow) { textCell.setTextAndValueAndCheck(LocaleController.getString("DirectShare", R.string.DirectShare), LocaleController.getString("DirectShareInfo", R.string.DirectShareInfo), MediaController.getInstance().canDirectShare(), false, true); } } else if (type == 4) { if (view == null) { view = new HeaderCell(mContext); } if (i == answeringmachinerow2) { ((HeaderCell) view).setText(LocaleController.getString("AnsweringMachin", R.string.answeringmachine)); } else if (i == settingsSectionRow2) { ((HeaderCell) view).setText(LocaleController.getString("SETTINGS", R.string.SETTINGS)); } else if (i == supportSectionRow2) { ((HeaderCell) view).setText(LocaleController.getString("Support", R.string.Support)); } else if (i == messagesSectionRow2) { ((HeaderCell) view).setText(LocaleController.getString("MessagesSettings", R.string.MessagesSettings)); } else if (i == mediaDownloadSection2) { ((HeaderCell) view).setText(LocaleController.getString("AutomaticMediaDownload", R.string.AutomaticMediaDownload)); } else if (i == numberSectionRow) { ((HeaderCell) view).setText(LocaleController.getString("Info", R.string.Info)); } else if (i == newgeramsectionrow2) { ((HeaderCell) view).setText(LocaleController.getString("NewGramSettings", R.string.newgeramsettings)); } } else if (type == 5) { if (view == null) { view = new TextInfoCell(mContext); try { PackageInfo pInfo = ApplicationLoader.applicationContext.getPackageManager().getPackageInfo(ApplicationLoader.applicationContext.getPackageName(), 0); int code = pInfo.versionCode / 10; String abi = ""; switch (pInfo.versionCode % 10) { case 0: abi = "arm"; break; case 1: abi = "arm-v7a"; break; case 2: abi = "x86"; break; case 3: abi = "universal"; break; } ((TextInfoCell) view).setText(String.format(Locale.US, "AriaGram for Android v%s (%d) %s", pInfo.versionName, code, abi)); } catch (Exception e) { FileLog.e("tmessages", e); } } } else if (type == 6) { if (view == null) { view = new TextDetailSettingsCell(mContext); } TextDetailSettingsCell textCell = (TextDetailSettingsCell) view; if (i == mobileDownloadRow || i == wifiDownloadRow || i == roamingDownloadRow) { int mask; String value; SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); if (i == mobileDownloadRow) { value = LocaleController.getString("WhenUsingMobileData", R.string.WhenUsingMobileData); mask = MediaController.getInstance().mobileDataDownloadMask; } else if (i == wifiDownloadRow) { value = LocaleController.getString("WhenConnectedOnWiFi", R.string.WhenConnectedOnWiFi); mask = MediaController.getInstance().wifiDownloadMask; } else { value = LocaleController.getString("WhenRoaming", R.string.WhenRoaming); mask = MediaController.getInstance().roamingDownloadMask; } String text = ""; if ((mask & MediaController.AUTODOWNLOAD_MASK_PHOTO) != 0) { text += LocaleController.getString("AttachPhoto", R.string.AttachPhoto); } if ((mask & MediaController.AUTODOWNLOAD_MASK_AUDIO) != 0) { if (text.length() != 0) { text += ", "; } text += LocaleController.getString("AttachAudio", R.string.AttachAudio); } if ((mask & MediaController.AUTODOWNLOAD_MASK_VIDEO) != 0) { if (text.length() != 0) { text += ", "; } text += LocaleController.getString("AttachVideo", R.string.AttachVideo); } if ((mask & MediaController.AUTODOWNLOAD_MASK_DOCUMENT) != 0) { if (text.length() != 0) { text += ", "; } text += LocaleController.getString("AttachDocument", R.string.AttachDocument); } if ((mask & MediaController.AUTODOWNLOAD_MASK_MUSIC) != 0) { if (text.length() != 0) { text += ", "; } text += LocaleController.getString("AttachMusic", R.string.AttachMusic); } if (Build.VERSION.SDK_INT >= 11) { if ((mask & MediaController.AUTODOWNLOAD_MASK_GIF) != 0) { if (text.length() != 0) { text += ", "; } text += LocaleController.getString("AttachGif", R.string.AttachGif); } } if (text.length() == 0) { text = LocaleController.getString("NoMediaAutoDownload", R.string.NoMediaAutoDownload); } textCell.setTextAndValue(value, text, true); } else if (i == numberRow) { TLRPC.User user = UserConfig.getCurrentUser(); String value; if (user != null && user.phone != null && user.phone.length() != 0) { value = PhoneFormat.getInstance().format("+" + user.phone); } else { value = LocaleController.getString("NumberUnknown", R.string.NumberUnknown); } textCell.setTextAndValue(value, LocaleController.getString("Phone", R.string.Phone), true); } else if (i == usernameRow) { TLRPC.User user = UserConfig.getCurrentUser(); String value; if (user != null && user.username != null && user.username.length() != 0) { value = "@" + user.username; } else { value = LocaleController.getString("UsernameEmpty", R.string.UsernameEmpty); } // Log.i("username",""+ user.username); textCell.setTextAndValue(value, LocaleController.getString("Username", R.string.Username), false); } } return view; } @Override public int getItemViewType(int i) { if (i == emptyRow || i == overscrollRow) { return 0; } if (i == answeringmachinerow || i == settingsSectionRow || i == newgeramsectionrow || i == supportSectionRow || i == messagesSectionRow || i == mediaDownloadSection || i == contactsSectionRow) { return 1; } else if (i == enableAnimationsRow || i == tabletforceoverride || i == showdateshamsi || i == showtimeago || i == anweringmachinactive || i == sendtyping || i == ghostactivate || i == sendByEnterRow || i == saveToGalleryRow || i == autoplayGifsRow || i == raiseToSpeakRow || i == customTabsRow || i == directShareRow) { return 3; } else if (i == notificationRow || i == answermachinetext || i == backgroundRow || i == askQuestionRow || i == sendLogsRow || i == privacyRow || i == clearLogsRow || i == switchBackendButtonRow || i == telegramFaqRow || i == contactsReimportRow || i == textSizeRow || i == fontType || i == languageRow || i == contactsSortRow || i == stickersRow || i == cacheRow || i == privacyPolicyRow) { return 2; } else if (i == versionRow) { return 5; } else if (i == wifiDownloadRow || i == mobileDownloadRow || i == roamingDownloadRow || i == numberRow || i == usernameRow) { return 6; } else if (i == settingsSectionRow2 || i == answeringmachinerow2 || i == newgeramsectionrow2 || i == messagesSectionRow2 || i == supportSectionRow2 || i == numberSectionRow || i == mediaDownloadSection2) { return 4; } else { return 2; } } @Override public int getViewTypeCount() { return 7; } @Override public boolean isEmpty() { return false; } } }
Fakkar/TeligramFars
TMessagesProj/src/main/java/com/teligramfars/ui/SettingsActivity.java
Java
gpl-2.0
80,162
/* * RapidMiner * * Copyright (C) 2001-2008 by Rapid-I and the contributors * * Complete list of developers available at our web site: * * http://rapid-i.com * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see http://www.gnu.org/licenses/. */ package com.rapidminer.operator.similarity; import java.util.Iterator; import com.rapidminer.example.Attribute; import com.rapidminer.example.Attributes; import com.rapidminer.example.Example; import com.rapidminer.example.ExampleSet; import com.rapidminer.example.SimpleAttributes; import com.rapidminer.example.set.AbstractExampleReader; import com.rapidminer.example.set.AbstractExampleSet; import com.rapidminer.example.set.MappedExampleSet; import com.rapidminer.example.table.AttributeFactory; import com.rapidminer.example.table.DoubleArrayDataRow; import com.rapidminer.example.table.ExampleTable; import com.rapidminer.example.table.NominalMapping; import com.rapidminer.tools.Ontology; import com.rapidminer.tools.math.similarity.DistanceMeasure; /** * This similarity based example set is used for the operator * {@link ExampleSet2SimilarityExampleSet}. * * @author Ingo Mierswa * @version $Id: SimilarityExampleSet.java,v 1.1 2008/09/08 18:53:49 ingomierswa Exp $ */ public class SimilarityExampleSet extends AbstractExampleSet { private static final long serialVersionUID = 4757975818441794105L; private static class IndexExampleReader extends AbstractExampleReader { private int index = 0; private ExampleSet exampleSet; public IndexExampleReader(ExampleSet exampleSet) { this.exampleSet = exampleSet; } public boolean hasNext() { return index < exampleSet.size() - 1; } public Example next() { Example example = exampleSet.getExample(index); index++; return example; } } private ExampleSet parent; private Attribute parentIdAttribute; private Attributes attributes; private DistanceMeasure measure; public SimilarityExampleSet(ExampleSet parent, DistanceMeasure measure) { this.parent = parent; this.parentIdAttribute = parent.getAttributes().getId(); this.attributes = new SimpleAttributes(); Attribute firstIdAttribute = null; Attribute secondIdAttribute = null; if (parentIdAttribute.isNominal()) { firstIdAttribute = AttributeFactory.createAttribute("FIRST_ID", Ontology.NOMINAL); secondIdAttribute = AttributeFactory.createAttribute("SECOND_ID", Ontology.NOMINAL); } else { firstIdAttribute = AttributeFactory.createAttribute("FIRST_ID", Ontology.NUMERICAL); secondIdAttribute = AttributeFactory.createAttribute("SECOND_ID", Ontology.NUMERICAL); } this.attributes.addRegular(firstIdAttribute); this.attributes.addRegular(secondIdAttribute); firstIdAttribute.setTableIndex(0); secondIdAttribute.setTableIndex(1); // copying mapping of original id attribute if (parentIdAttribute.isNominal()) { NominalMapping mapping = parentIdAttribute.getMapping(); firstIdAttribute.setMapping(mapping); secondIdAttribute.setMapping(mapping); } String name = "SIMILARITY"; if (measure.isDistance()) { name = "DISTANCE"; } Attribute similarityAttribute = AttributeFactory.createAttribute(name, Ontology.REAL); this.attributes.addRegular(similarityAttribute); similarityAttribute.setTableIndex(2); this.measure = measure; } public boolean equals(Object o) { if (!super.equals(o)) return false; if (!(o instanceof MappedExampleSet)) return false; SimilarityExampleSet other = (SimilarityExampleSet)o; if (!this.measure.getClass().equals(other.measure.getClass())) return false; return true; } public int hashCode() { return super.hashCode() ^ this.measure.getClass().hashCode(); } public Attributes getAttributes() { return this.attributes; } public Example getExample(int index) { int firstIndex = index / this.parent.size(); int secondIndex = index % this.parent.size(); Example firstExample = this.parent.getExample(firstIndex); Example secondExample = this.parent.getExample(secondIndex); double[] data = new double[3]; data[0] = firstExample.getValue(parentIdAttribute); data[1] = secondExample.getValue(parentIdAttribute); if (measure.isDistance()) data[2] = measure.calculateDistance(firstExample, secondExample); else data[2] = measure.calculateSimilarity(firstExample, secondExample); return new Example(new DoubleArrayDataRow(data), this); } public Iterator<Example> iterator() { return new IndexExampleReader(this); } public ExampleTable getExampleTable() { return null;//this.parent.getExampleTable(); } public int size() { return this.parent.size() * this.parent.size(); } }
ntj/ComplexRapidMiner
src/com/rapidminer/operator/similarity/SimilarityExampleSet.java
Java
gpl-2.0
5,564
/** * yamsLog is a program for real time multi sensor logging and * supervision * Copyright (C) 2014 * * 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. */ import Database.Messages.ProjectMetaData; import Database.Sensors.Sensor; import Errors.BackendError; import FrontendConnection.Backend; import FrontendConnection.Listeners.ProjectCreationStatusListener; import protobuf.Protocol; import java.util.ArrayList; import java.util.List; import java.util.Random; /** * Created with IntelliJ IDEA. * User: Aitesh * Date: 2014-04-10 * Time: 09:34 * To change this template use File | Settings | File Templates. */ public class NewDebugger implements ProjectCreationStatusListener { private boolean projectListChanged; public NewDebugger(){ try{ Backend.createInstance(null); //args[0],Integer.parseInt(args[1]), Backend.getInstance().addProjectCreationStatusListener(this); Backend.getInstance().connectToServer("130.236.63.46",2001); } catch (BackendError b){ b.printStackTrace(); } projectListChanged = false; } private synchronized boolean readWriteBoolean(Boolean b){ if(b!=null) projectListChanged=b; return projectListChanged; } public void runPlayback() { try{ Thread.sleep(1000); //Backend.getInstance().sendSettingsRequestMessageALlSensors(0); readWriteBoolean(false); Random r = new Random(); String[] strings = new String[]{"Name","Code","File","Today","Monday","Tuesday","Wednesday","Thursday","Friday","Gotta","Get","Out","It","S","Friday"}; String project = "projectName" +r.nextInt()%10000; String playbackProject = "realCollection"; Thread.sleep(1000); System.out.println("Setting active project to : " + playbackProject); Backend.getInstance().setActiveProject(playbackProject); ProjectMetaData d = new ProjectMetaData(); d.setTest_leader("ffu"); d.setDate(1l); List<String> s = new ArrayList<String>(); s.add("memer1"); d.setMember_names(s); d.setTags(s); d.setDescription("desc"); List l = d.getMember_names(); l.add(r.nextInt()+". name"); d.setMember_names(l); Backend.getInstance().sendProjectMetaData(d); System.out.println("starting data collection"); Thread.sleep(100); String experimentName = "smallrun"; //Backend.getInstance().setActiveProject(playbackProject); // projektnamn: Thread.sleep(3000); // Backend.getInstance().getSensorConfigurationForPlayback().getSensorId(); List<Protocol.SensorConfiguration> playbackConfig; playbackConfig = Backend.getInstance().getSensorConfigurationForPlayback(); List<Integer> listOfIds = new ArrayList<Integer>(); /* for (Protocol.SensorConfiguration aPlaybackConfig : playbackConfig) { listOfIds.add(aPlaybackConfig.getSensorId()); }*/ System.out.println("LIST OF IDS SENT TO SERVER-------------------------------------------"); System.out.println(listOfIds); System.out.println("LIST OF IDS END -----------------------------------------------------"); System.out.println("LIST OF IDS CURRENTLY IN DATABASE -----------------------------------"); System.out.println(Backend.getInstance().getSensors()); System.out.println("LIST IN DATABASE END ------------------------------------------------"); Backend.getInstance().sendExperimentPlaybackRequest(experimentName, listOfIds); //Thread.sleep(3000); //Backend.getInstance().stopConnection(); } catch (BackendError b){ b.printStackTrace(); } catch (InterruptedException ignore){ } } public void run(){ try{ Thread.sleep(1000); Backend.getInstance().sendSettingsRequestMessageALlSensors(0); readWriteBoolean(false); Random r = new Random(); String[] strings = new String[]{"Name","Code","File","Today","Monday","Tuesday","Wednesday","Thursday","Friday","Gotta","Get","Out","It","S","Friday"}; String project = "projectName" +r.nextInt()%10000; String playbackProject = "realCollection"; for(int i = 0; i < 1000; i++){ // project+=strings[r.nextInt(strings.length)]; } //System.out.println(project); //if(r.nextInt()>0) return; Thread.sleep(1000); Backend.getInstance().createNewProjectRequest(project);//"projectName"+ System.currentTimeMillis()); if(!readWriteBoolean(null)){ System.out.println("Waiting on projectListAgain"); while (!readWriteBoolean(null)); System.out.println("finished waiting"); } // = Backend.getInstance().getProjectFilesFromServer().get()); System.out.println("Setting active project to : " + project); Backend.getInstance().setActiveProject(project); ProjectMetaData d = new ProjectMetaData(); //d.setEmail("NotMyEmail@gmail.com"); d.setTest_leader("ffu"); d.setDate(1l); List<String> s = new ArrayList<String>(); s.add("memer1"); d.setMember_names(s); d.setTags(s); d.setDescription("desc"); List l = d.getMember_names(); l.add(r.nextInt() + ". name"); d.setMember_names(l); Backend.getInstance().sendProjectMetaData(d); /* while(!readWriteBoolean(null) && readWriteBoolean(null)){ Backend.getInstance().sendProjectMetaData(d); List<String> f =d.getTags(); f.add(String.valueOf(System.currentTimeMillis())); d.setTags(f); } **/ System.out.println("starting data collection"); Thread.sleep(100); String experimentName = "experimentNam5"+System.currentTimeMillis(); //String experimentName = "smallrun"; // projektnamn: Backend.getInstance().startDataCollection(experimentName); Thread.sleep(3000); Backend.getInstance().stopDataCollection(); Thread.sleep(1); } catch (BackendError b){ b.printStackTrace(); } catch (InterruptedException ignore){ } System.out.println("Exiting"); } public void runTest(){ // try{ // Thread.sleep(1000); Backend.getInstance().sendSettingsRequestMessageALlSensors(0); // Thread.sleep(1000); Backend.getInstance().createNewProjectRequest("projectName"+ System.currentTimeMillis()); // // //Backend.getInstance().startDataCollection("test1234"); // // //Thread.sleep(5000); Backend.getInstance().stopDataCollection(); // Backend localInstance = Backend.getInstance(); // // Sensor sensor = localInstance.getSensors().get(0); // for(int i = 0; i<sensor.getAttributeList(0).size();i++){ // System.out.print(String.format("%f", sensor.getAttributeList(0).get(i).floatValue()).replace(',', '.') + ","); // // System.out.print(sensor.getId() + ","); // for (int j = 1; j < sensor.getAttributesName().length;j++){ // // System.out.print(sensor.getAttributeList(j).get(i).floatValue() + " ,"); // } // System.out.println(); // } // // } catch (BackendError b){ // b.printStackTrace(); // } catch (InterruptedException ignore){} } @Override public void projectCreationStatusChanged(Protocol.CreateNewProjectResponseMsg.ResponseType responseType) { readWriteBoolean(true); } }
droberg/yamsLog
client-backend/src/NewDebugger.java
Java
gpl-2.0
8,996
/** Copyright (C) SYSTAP, LLC 2006-2012. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.bigdata.rdf.graph.analytics; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import org.openrdf.model.Value; import org.openrdf.sail.SailConnection; import com.bigdata.rdf.graph.IGASContext; import com.bigdata.rdf.graph.IGASEngine; import com.bigdata.rdf.graph.IGASState; import com.bigdata.rdf.graph.IGASStats; import com.bigdata.rdf.graph.IGraphAccessor; import com.bigdata.rdf.graph.analytics.CC.VS; import com.bigdata.rdf.graph.impl.sail.AbstractSailGraphTestCase; /** * Test class for Breadth First Search (BFS) traversal. * * @see BFS * * @author <a href="mailto:thompsonbry@users.sourceforge.net">Bryan Thompson</a> */ public class TestCC extends AbstractSailGraphTestCase { public TestCC() { } public TestCC(String name) { super(name); } public void testCC() throws Exception { /* * Load two graphs. These graphs are not connected with one another (no * shared vertices). This means that each graph will be its own * connected component (all vertices in each source graph are * connected within that source graph). */ final SmallGraphProblem p1 = setupSmallGraphProblem(); final SSSPGraphProblem p2 = setupSSSPGraphProblem(); final IGASEngine gasEngine = getGraphFixture() .newGASEngine(1/* nthreads */); try { final SailConnection cxn = getGraphFixture().getSail() .getConnection(); try { final IGraphAccessor graphAccessor = getGraphFixture() .newGraphAccessor(cxn); final CC gasProgram = new CC(); final IGASContext<CC.VS, CC.ES, Value> gasContext = gasEngine .newGASContext(graphAccessor, gasProgram); final IGASState<CC.VS, CC.ES, Value> gasState = gasContext .getGASState(); // Converge. final IGASStats stats = gasContext.call(); if(log.isInfoEnabled()) log.info(stats); /* * Check the #of connected components that are self-reported and * the #of vertices in each connected component. This helps to * detect vertices that should have been visited but were not * due to the initial frontier. E.g., "DC" will not be reported * as a connected component of size (1) unless it gets into the * initial frontier (it has no edges, only an attribute). */ final Map<Value, AtomicInteger> labels = gasProgram .getConnectedComponents(gasState); // the size of the connected component for this vertex. { final VS valueState = gasState.getState(p1.getFoafPerson()); final Value label = valueState != null?valueState.getLabel():null; assertEquals(4, labels.get(label).get()); } // the size of the connected component for this vertex. { final VS valueState = gasState.getState(p2.get_v1()); final Value label = valueState != null?valueState.getLabel():null; final AtomicInteger ai = labels.get(label); final int count = ai!=null?ai.get():-1; assertEquals(5, count); } if (false) { /* * The size of the connected component for this vertex. * * Note: The vertex sampling code ignores self-loops and * ignores vertices that do not have ANY edges. Thus "DC" is * not put into the frontier and is not visited. */ final Value label = gasState.getState(p1.getDC()) .getLabel(); assertNotNull(label); /* * If DC was not put into the initial frontier, then it will * be missing here. */ assertNotNull(labels.get(label)); assertEquals(1, labels.get(label).get()); } // the #of connected components. assertEquals(2, labels.size()); /* * Most vertices in problem1 have the same label (the exception * is DC, which is it its own connected component). */ Value label1 = null; for (Value v : p1.getVertices()) { final CC.VS vs = gasState.getState(v); if (log.isInfoEnabled()) log.info("v=" + v + ", label=" + vs.getLabel()); if(v.equals(p1.getDC())) { /* * This vertex is in its own connected component and is * therefore labeled by itself. */ assertEquals("vertex=" + v, v, vs.getLabel()); continue; } if (label1 == null) { label1 = vs.getLabel(); assertNotNull(label1); } assertEquals("vertex=" + v, label1, vs.getLabel()); } // All vertices in problem2 have the same label. Value label2 = null; for (Value v : p2.getVertices()) { final CC.VS vs = gasState.getState(v); if (log.isInfoEnabled()) log.info("v=" + v + ", label=" + vs.getLabel()); if (label2 == null) { label2 = vs.getLabel(); assertNotNull(label2); } assertEquals("vertex=" + v, label2, vs.getLabel()); } // The labels for the two connected components are distinct. assertNotSame(label1, label2); } finally { try { cxn.rollback(); } finally { cxn.close(); } } } finally { gasEngine.shutdownNow(); } } }
blazegraph/database
bigdata-gas/src/test/java/com/bigdata/rdf/graph/analytics/TestCC.java
Java
gpl-2.0
7,408
/* * Copyright (C) 2016 robert * * 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 3 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/>. */ package pl.rcebula.code_generation.final_steps; import java.util.ArrayList; import java.util.List; import pl.rcebula.code_generation.intermediate.intermediate_code_structure.IField; import pl.rcebula.code_generation.intermediate.intermediate_code_structure.IntermediateCode; import pl.rcebula.code_generation.intermediate.intermediate_code_structure.Line; import pl.rcebula.code_generation.intermediate.intermediate_code_structure.StringField; /** * * @author robert */ public class AddInformationsAboutModules { private final IntermediateCode ic; private final List<String> modulesName; public AddInformationsAboutModules(IntermediateCode ic, List<String> modulesName) { this.ic = ic; this.modulesName = modulesName; analyse(); } private void analyse() { // tworzymy pola List<IField> fields = new ArrayList<>(); for (String m : modulesName) { IField f = new StringField(m); fields.add(f); } // wstawiamy pustą linię na początek ic.insertLine(Line.generateEmptyStringLine(), 0); // tworzymy linię i wstawiamy na początek Line line = new Line(fields); ic.insertLine(line, 0); } }
bercik/BIO
impl/bioc/src/pl/rcebula/code_generation/final_steps/AddInformationsAboutModules.java
Java
gpl-2.0
1,977
/* -*- compile-command: "cd ../../../../../; ant debug install"; -*- */ /* * Copyright 2010 by Eric House (xwords@eehouse.org). 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; 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 com.oliversride.wordryo; import junit.framework.Assert; import android.app.Activity; import android.app.Dialog; import android.os.Bundle; public class XWActivity extends Activity implements DlgDelegate.DlgClickNotify, MultiService.MultiEventListener { private final static String TAG = "XWActivity"; private DlgDelegate m_delegate; @Override protected void onCreate( Bundle savedInstanceState ) { DbgUtils.logf( "%s.onCreate(this=%H)", getClass().getName(), this ); super.onCreate( savedInstanceState ); m_delegate = new DlgDelegate( this, this, savedInstanceState ); } @Override protected void onStart() { DbgUtils.logf( "%s.onStart(this=%H)", getClass().getName(), this ); super.onStart(); } @Override protected void onResume() { DbgUtils.logf( "%s.onResume(this=%H)", getClass().getName(), this ); BTService.setListener( this ); SMSService.setListener( this ); super.onResume(); } @Override protected void onPause() { DbgUtils.logf( "%s.onPause(this=%H)", getClass().getName(), this ); BTService.setListener( null ); SMSService.setListener( null ); super.onPause(); } @Override protected void onStop() { DbgUtils.logf( "%s.onStop(this=%H)", getClass().getName(), this ); super.onStop(); } @Override protected void onDestroy() { DbgUtils.logf( "%s.onDestroy(this=%H); isFinishing=%b", getClass().getName(), this, isFinishing() ); super.onDestroy(); } @Override protected void onSaveInstanceState( Bundle outState ) { super.onSaveInstanceState( outState ); m_delegate.onSaveInstanceState( outState ); } @Override protected Dialog onCreateDialog( int id ) { Dialog dialog = super.onCreateDialog( id ); if ( null == dialog ) { DbgUtils.logf( "%s.onCreateDialog() called", getClass().getName() ); dialog = m_delegate.onCreateDialog( id ); } return dialog; } // these are duplicated in XWListActivity -- sometimes multiple // inheritance would be nice to have... protected void showAboutDialog() { m_delegate.showAboutDialog(); } protected void showNotAgainDlgThen( int msgID, int prefsKey, int action ) { m_delegate.showNotAgainDlgThen( msgID, prefsKey, action ); } protected void showNotAgainDlgThen( int msgID, int prefsKey ) { m_delegate.showNotAgainDlgThen( msgID, prefsKey ); } protected void showOKOnlyDialog( int msgID ) { m_delegate.showOKOnlyDialog( msgID ); } protected void showOKOnlyDialog( String msg ) { m_delegate.showOKOnlyDialog( msg ); } protected void showDictGoneFinish() { m_delegate.showDictGoneFinish(); } protected void showConfirmThen( int msgID, int action ) { m_delegate.showConfirmThen( getString(msgID), action ); } protected void showConfirmThen( String msg, int action ) { m_delegate.showConfirmThen( msg, action ); } protected void showConfirmThen( int msg, int posButton, int action ) { m_delegate.showConfirmThen( getString(msg), posButton, action ); } public void showEmailOrSMSThen( int action ) { m_delegate.showEmailOrSMSThen( action ); } protected void doSyncMenuitem() { m_delegate.doSyncMenuitem(); } protected void launchLookup( String[] words, int lang ) { m_delegate.launchLookup( words, lang, false ); } protected void startProgress( int id ) { m_delegate.startProgress( id ); } protected void stopProgress() { m_delegate.stopProgress(); } protected boolean post( Runnable runnable ) { return m_delegate.post( runnable ); } // DlgDelegate.DlgClickNotify interface public void dlgButtonClicked( int id, int which ) { Assert.fail(); } // BTService.MultiEventListener interface public void eventOccurred( MultiService.MultiEvent event, final Object ... args ) { m_delegate.eventOccurred( event, args ); } }
oliversride/Wordryo
src/main/java/com/oliversride/wordryo/XWActivity.java
Java
gpl-2.0
5,258
package kc.spark.pixels.android.ui.assets; import static org.solemnsilence.util.Py.map; import java.util.Map; import android.content.Context; import android.graphics.Typeface; public class Typefaces { // NOTE: this is tightly coupled to the filenames in assets/fonts public static enum Style { BOLD("Arial.ttf"), BOLD_ITALIC("Arial.ttf"), BOOK("Arial.ttf"), BOOK_ITALIC("Arial.ttf"), LIGHT("Arial.ttf"), LIGHT_ITALIC("Arial.ttf"), MEDIUM("Arial.ttf"), MEDIUM_ITALIC("Arial.ttf"); // BOLD("gotham_bold.otf"), // BOLD_ITALIC("gotham_bold_ita.otf"), // BOOK("gotham_book.otf"), // BOOK_ITALIC("gotham_book_ita.otf"), // LIGHT("gotham_light.otf"), // LIGHT_ITALIC("gotham_light_ita.otf"), // MEDIUM("gotham_medium.otf"), // MEDIUM_ITALIC("gotham_medium_ita.otf"); public final String fileName; private Style(String name) { fileName = name; } } private static final Map<Style, Typeface> typefaces = map(); public static Typeface getTypeface(Context ctx, Style style) { Typeface face = typefaces.get(style); if (face == null) { face = Typeface.createFromAsset(ctx.getAssets(), "fonts/" + style.fileName); typefaces.put(style, face); } return face; } }
sparcules/Spark_Pixels
AndroidApp/SparkPixels/src/kc/spark/pixels/android/ui/assets/Typefaces.java
Java
gpl-2.0
1,212
/* * Copyright (c) 2003, 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. */ /* @test @bug 4922813 @summary Check the new impl of encodePath will not cause regression @key randomness */ import java.util.BitSet; import java.io.File; import java.util.Random; import sun.net.www.ParseUtil; public class ParseUtil_4922813 { public static void main(String[] argv) throws Exception { int num = 400; while (num-- >= 0) { String source = getTestSource(); String ec = sun.net.www.ParseUtil.encodePath(source); String v117 = ParseUtil_V117.encodePath(source); if (!ec.equals(v117)) { throw new RuntimeException("Test Failed for : \n" + " source =<" + getUnicodeString(source) + ">"); } } } static int maxCharCount = 200; static int maxCodePoint = 0x10ffff; static Random random; static String getTestSource() { if (random == null) { long seed = System.currentTimeMillis(); random = new Random(seed); } String source = ""; int i = 0; int count = random.nextInt(maxCharCount) + 1; while (i < count) { int codepoint = random.nextInt(127); source = source + String.valueOf((char)codepoint); codepoint = random.nextInt(0x7ff); source = source + String.valueOf((char)codepoint); codepoint = random.nextInt(maxCodePoint); source = source + new String(Character.toChars(codepoint)); i += 3; } return source; } static String getUnicodeString(String s){ String unicodeString = ""; for(int j=0; j< s.length(); j++){ unicodeString += "0x"+ Integer.toString(s.charAt(j), 16); } return unicodeString; } } class ParseUtil_V117 { static BitSet encodedInPath; static { encodedInPath = new BitSet(256); // Set the bits corresponding to characters that are encoded in the // path component of a URI. // These characters are reserved in the path segment as described in // RFC2396 section 3.3. encodedInPath.set('='); encodedInPath.set(';'); encodedInPath.set('?'); encodedInPath.set('/'); // These characters are defined as excluded in RFC2396 section 2.4.3 // and must be escaped if they occur in the data part of a URI. encodedInPath.set('#'); encodedInPath.set(' '); encodedInPath.set('<'); encodedInPath.set('>'); encodedInPath.set('%'); encodedInPath.set('"'); encodedInPath.set('{'); encodedInPath.set('}'); encodedInPath.set('|'); encodedInPath.set('\\'); encodedInPath.set('^'); encodedInPath.set('['); encodedInPath.set(']'); encodedInPath.set('`'); // US ASCII control characters 00-1F and 7F. for (int i=0; i<32; i++) encodedInPath.set(i); encodedInPath.set(127); } /** * Constructs an encoded version of the specified path string suitable * for use in the construction of a URL. * * A path separator is replaced by a forward slash. The string is UTF8 * encoded. The % escape sequence is used for characters that are above * 0x7F or those defined in RFC2396 as reserved or excluded in the path * component of a URL. */ public static String encodePath(String path) { StringBuffer sb = new StringBuffer(); int n = path.length(); for (int i=0; i<n; i++) { char c = path.charAt(i); if (c == File.separatorChar) sb.append('/'); else { if (c <= 0x007F) { if (encodedInPath.get(c)) escape(sb, c); else sb.append(c); } else if (c > 0x07FF) { escape(sb, (char)(0xE0 | ((c >> 12) & 0x0F))); escape(sb, (char)(0x80 | ((c >> 6) & 0x3F))); escape(sb, (char)(0x80 | ((c >> 0) & 0x3F))); } else { escape(sb, (char)(0xC0 | ((c >> 6) & 0x1F))); escape(sb, (char)(0x80 | ((c >> 0) & 0x3F))); } } } return sb.toString(); } /** * Appends the URL escape sequence for the specified char to the * specified StringBuffer. */ private static void escape(StringBuffer s, char c) { s.append('%'); s.append(Character.forDigit((c >> 4) & 0xF, 16)); s.append(Character.forDigit(c & 0xF, 16)); } }
openjdk/jdk8u
jdk/test/sun/net/www/ParseUtil_4922813.java
Java
gpl-2.0
5,843
/* * jMemorize - Learning made easy (and fun) - A Leitner flashcards tool * Copyright(C) 2004-2006 Riad Djemili * * 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 1, 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. */ package jmemorize.core.test; import java.io.File; import java.io.IOException; import java.util.List; import jmemorize.core.Card; import jmemorize.core.Lesson; import jmemorize.core.LessonObserver; import jmemorize.core.LessonProvider; import jmemorize.core.Main; import junit.framework.TestCase; public class LessonProviderTest extends TestCase implements LessonObserver { private LessonProvider m_lessonProvider; private StringBuffer m_log; protected void setUp() throws Exception { m_lessonProvider = new Main(); m_lessonProvider.addLessonObserver(this); m_log = new StringBuffer(); } public void testLessonNewEvent() { m_lessonProvider.createNewLesson(); assertEquals("loaded ", m_log.toString()); } public void testLessonLoadedEvent() throws IOException { m_lessonProvider.loadLesson(new File("test/fixtures/simple_de.jml")); assertEquals("loaded ", m_log.toString()); } public void testLessonLoadedCardsAlwaysHaveExpiration() throws IOException { m_lessonProvider.loadLesson(new File("test/fixtures/no_expiration.jml")); Lesson lesson = m_lessonProvider.getLesson(); List<Card> cards = lesson.getRootCategory().getCards(); for (Card card : cards) { if (card.getLevel() > 0) assertNotNull(card.getDateExpired()); else assertNull(card.getDateExpired()); } } public void testLessonLoadedClosedNewEvents() throws IOException { m_lessonProvider.loadLesson(new File("test/fixtures/simple_de.jml")); m_lessonProvider.createNewLesson(); assertEquals("loaded closed loaded ", m_log.toString()); // TODO also check lesson param } public void testLessonLoadedClosedLoadEvents() throws IOException { m_lessonProvider.loadLesson(new File("test/fixtures/simple_de.jml")); m_lessonProvider.loadLesson(new File("test/fixtures/test.jml")); assertEquals("loaded closed loaded ", m_log.toString()); // TODO also check lesson param } public void testLessonSavedEvent() throws Exception { m_lessonProvider.loadLesson( new File("test/fixtures/simple_de.jml")); Lesson lesson = m_lessonProvider.getLesson(); m_lessonProvider.saveLesson(lesson, new File("./test.jml")); assertEquals("loaded saved ", m_log.toString()); } public void testLessonModifiedEvent() throws Exception { m_lessonProvider.loadLesson( new File("test/fixtures/simple_de.jml")); Lesson lesson = m_lessonProvider.getLesson(); lesson.getRootCategory().addCard(new Card("front", "flip")); assertEquals("loaded modified ", m_log.toString()); } /* (non-Javadoc) * @see jmemorize.core.LessonObserver */ public void lessonLoaded(Lesson lesson) { m_log.append("loaded "); } /* (non-Javadoc) * @see jmemorize.core.LessonObserver */ public void lessonModified(Lesson lesson) { m_log.append("modified "); } /* (non-Javadoc) * @see jmemorize.core.LessonObserver */ public void lessonSaved(Lesson lesson) { m_log.append("saved "); } /* (non-Javadoc) * @see jmemorize.core.LessonObserver */ public void lessonClosed(Lesson lesson) { m_log.append("closed "); } }
riadd/jMemorize
src/jmemorize/core/test/LessonProviderTest.java
Java
gpl-2.0
4,360
/* * ************************************************************************************* * Copyright (C) 2008 EsperTech, Inc. All rights reserved. * * http://esper.codehaus.org * * http://www.espertech.com * * ---------------------------------------------------------------------------------- * * The software in this package is published under the terms of the GPL license * * a copy of which has been included with this distribution in the license.txt file. * * ************************************************************************************* */ package com.espertech.esper.multithread; import junit.framework.TestCase; import com.espertech.esper.client.EPServiceProvider; import com.espertech.esper.client.EPServiceProviderManager; import com.espertech.esper.client.EPStatement; import com.espertech.esper.client.Configuration; import com.espertech.esper.support.bean.SupportTradeEvent; import com.espertech.esper.multithread.TwoPatternRunnable; /** * Test for multithread-safety for case of 2 patterns: * 1. Thread 1 starts pattern "every event1=SupportEvent(userID in ('100','101'), amount>=1000)" * 2. Thread 1 repeats sending 100 events and tests 5% received * 3. Main thread starts pattern: * ( every event1=SupportEvent(userID in ('100','101')) -> (SupportEvent(userID in ('100','101'), direction = event1.direction ) -> SupportEvent(userID in ('100','101'), direction = event1.direction ) ) where timer:within(8 hours) and not eventNC=SupportEvent(userID in ('100','101'), direction!= event1.direction ) ) -> eventFinal=SupportEvent(userID in ('100','101'), direction != event1.direction ) where timer:within(1 hour) * 4. Main thread waits for 2 seconds and stops all threads */ public class TestMTStmtTwoPatternsStartStop extends TestCase { private EPServiceProvider engine; public void setUp() { Configuration config = new Configuration(); config.addEventType("SupportEvent", SupportTradeEvent.class); engine = EPServiceProviderManager.getDefaultProvider(config); engine.initialize(); } public void tearDown() { engine.initialize(); } public void test2Patterns() throws Exception { String statementTwo = "( every event1=SupportEvent(userId in ('100','101')) ->\n" + " (SupportEvent(userId in ('100','101'), direction = event1.direction ) ->\n" + " SupportEvent(userId in ('100','101'), direction = event1.direction )\n" + " ) where timer:within(8 hours)\n" + " and not eventNC=SupportEvent(userId in ('100','101'), direction!= event1.direction )\n" + " ) -> eventFinal=SupportEvent(userId in ('100','101'), direction != event1.direction ) where timer:within(1 hour)"; TwoPatternRunnable runnable = new TwoPatternRunnable(engine); Thread t = new Thread(runnable); t.start(); Thread.sleep(200); // Create a second pattern, wait 200 msec, destroy second pattern in a loop for (int i = 0; i < 10; i++) { EPStatement statement = engine.getEPAdministrator().createPattern(statementTwo); Thread.sleep(200); statement.destroy(); } runnable.setShutdown(true); Thread.sleep(1000); assertFalse(t.isAlive()); } }
intelie/esper
esper/src/test/java/com/espertech/esper/multithread/TestMTStmtTwoPatternsStartStop.java
Java
gpl-2.0
3,675
package org.webbuilder.web.service.script; import org.springframework.stereotype.Service; import org.webbuilder.utils.script.engine.DynamicScriptEngine; import org.webbuilder.utils.script.engine.DynamicScriptEngineFactory; import org.webbuilder.utils.script.engine.ExecuteResult; import org.webbuilder.web.po.script.DynamicScript; import javax.annotation.Resource; import java.util.Map; /** * Created by 浩 on 2015-10-29 0029. */ @Service public class DynamicScriptExecutor { @Resource private DynamicScriptService dynamicScriptService; public ExecuteResult exec(String id, Map<String, Object> param) throws Exception { DynamicScript data = dynamicScriptService.selectByPk(id); if (data == null) { ExecuteResult result = new ExecuteResult(); result.setResult(String.format("script %s not found!", id)); result.setSuccess(false); return result; } DynamicScriptEngine engine = DynamicScriptEngineFactory.getEngine(data.getType()); return engine.execute(id, param); } }
wb-goup/webbuilder
wb-core/src/main/java/org/webbuilder/web/service/script/DynamicScriptExecutor.java
Java
gpl-2.0
1,079
/* * Copyright (C) 2013-2016 52°North Initiative for Geospatial Open Source * Software GmbH * * 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. * * If the program is linked with libraries which are licensed under one of * the following licenses, the combination of the program with the linked * library is not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed * under the aforementioned licenses, is permitted by the copyright holders * if the distribution is compliant with both the GNU General Public License * version 2 and the aforementioned licenses. * * 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. */ package org.n52.io.measurement.img; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import java.util.Date; import org.joda.time.DateTime; import org.joda.time.format.ISODateTimeFormat; import org.junit.Before; import org.junit.Test; import org.n52.io.IoStyleContext; import org.n52.io.MimeType; import org.n52.io.request.RequestSimpleParameterSet; import org.n52.io.response.dataset.DataCollection; import org.n52.io.response.dataset.measurement.MeasurementData; public class ChartRendererTest { private static final String VALID_ISO8601_RELATIVE_START = "PT6H/2013-08-13TZ"; private static final String VALID_ISO8601_ABSOLUTE_START = "2013-07-13TZ/2013-08-13TZ"; private static final String VALID_ISO8601_DAYLIGHT_SAVING_SWITCH = "2013-10-28T02:00:00+02:00/2013-10-28T02:00:00+01:00"; private MyChartRenderer chartRenderer; @Before public void setUp() { this.chartRenderer = new MyChartRenderer(IoStyleContext.createEmpty()); } @Test public void shouldParseBeginFromIso8601PeriodWithRelativeStart() { Date start = chartRenderer.getStartTime(VALID_ISO8601_RELATIVE_START); assertThat(start, is(DateTime.parse("2013-08-13TZ").minusHours(6).toDate())); } @Test public void shouldParseBeginFromIso8601PeriodWithAbsoluteStart() { Date start = chartRenderer.getStartTime(VALID_ISO8601_ABSOLUTE_START); assertThat(start, is(DateTime.parse("2013-08-13TZ").minusMonths(1).toDate())); } @Test public void shouldParseBeginAndEndFromIso8601PeriodContainingDaylightSavingTimezoneSwith() { Date start = chartRenderer.getStartTime(VALID_ISO8601_DAYLIGHT_SAVING_SWITCH); Date end = chartRenderer.getEndTime(VALID_ISO8601_DAYLIGHT_SAVING_SWITCH); assertThat(start, is(DateTime.parse("2013-10-28T00:00:00Z").toDate())); assertThat(end, is(DateTime.parse("2013-10-28T01:00:00Z").toDate())); } @Test public void shouldHaveCETTimezoneIncludedInDomainAxisLabel() { IoStyleContext context = IoStyleContext.createEmpty(); context.getChartStyleDefinitions().setTimespan(VALID_ISO8601_DAYLIGHT_SAVING_SWITCH); this.chartRenderer = new MyChartRenderer(context); String label = chartRenderer.getXYPlot().getDomainAxis().getLabel(); assertThat(label, is("Time (+01:00)")); } @Test public void shouldHandleEmptyTimespanWhenIncludingTimezoneInDomainAxisLabel() { IoStyleContext context = IoStyleContext.createEmpty(); context.getChartStyleDefinitions().setTimespan(null); this.chartRenderer = new MyChartRenderer(context); String label = chartRenderer.getXYPlot().getDomainAxis().getLabel(); //assertThat(label, is("Time (+01:00)")); } @Test public void shouldHaveUTCTimezoneIncludedInDomainAxisLabel() { IoStyleContext context = IoStyleContext.createEmpty(); context.getChartStyleDefinitions().setTimespan(VALID_ISO8601_ABSOLUTE_START); this.chartRenderer = new MyChartRenderer(context); String label = chartRenderer.getXYPlot().getDomainAxis().getLabel(); ISODateTimeFormat.dateTimeParser().withOffsetParsed().parseDateTime(VALID_ISO8601_ABSOLUTE_START.split("/")[1]); assertThat(label, is("Time (UTC)")); } static class MyChartRenderer extends ChartIoHandler { public MyChartRenderer(IoStyleContext context) { super(new RequestSimpleParameterSet(), null, context); } public MyChartRenderer() { super(new RequestSimpleParameterSet(), null, null); } @Override public void setMimeType(MimeType mimetype) { throw new UnsupportedOperationException(); } @Override public void writeDataToChart(DataCollection<MeasurementData> data) { throw new UnsupportedOperationException(); } } }
ridoo/timeseries-api
io/src/test/java/org/n52/io/measurement/img/ChartRendererTest.java
Java
gpl-2.0
5,333
/* * 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.xml.internal.bind.v2.util; import java.util.AbstractList; import java.util.Arrays; import java.util.List; import java.util.Stack; /** * {@link Stack}-like data structure that allows the following efficient operations: * * <ol> * <li>Push/pop operation. * <li>Duplicate check. When an object that's already in the stack is pushed, * this class will tell you so. * </ol> * * <p> * Object equality is their identity equality. * * <p> * This class implements {@link List} for accessing items in the stack, * but {@link List} methods that alter the stack is not supported. * * @author Kohsuke Kawaguchi */ public final class CollisionCheckStack<E> extends AbstractList<E> { private Object[] data; private int[] next; private int size = 0; /** * True if the check shall be done by using the object identity. * False if the check shall be done with the equals method. */ private boolean useIdentity = true; // for our purpose, there isn't much point in resizing this as we don't expect // the stack to grow that much. private final int[] initialHash; public CollisionCheckStack() { initialHash = new int[17]; data = new Object[16]; next = new int[16]; } /** * Set to false to use {@link Object#equals(Object)} to detect cycles. * This method can be only used when the stack is empty. */ public void setUseIdentity(boolean useIdentity) { this.useIdentity = useIdentity; } public boolean getUseIdentity() { return useIdentity; } /** * Pushes a new object to the stack. * * @return * true if this object has already been pushed */ public boolean push(E o) { if(data.length==size) expandCapacity(); data[size] = o; int hash = hash(o); boolean r = findDuplicate(o, hash); next[size] = initialHash[hash]; initialHash[hash] = size+1; size++; return r; } /** * Pushes a new object to the stack without making it participate * with the collision check. */ public void pushNocheck(E o) { if(data.length==size) expandCapacity(); data[size] = o; next[size] = -1; size++; } @Override public E get(int index) { return (E)data[index]; } @Override public int size() { return size; } private int hash(Object o) { return ((useIdentity?System.identityHashCode(o):o.hashCode())&0x7FFFFFFF) % initialHash.length; } /** * Pops an object from the stack */ public E pop() { size--; Object o = data[size]; data[size] = null; // keeping references too long == memory leak int n = next[size]; if(n<0) { // pushed by nocheck. no need to update hash } else { int hash = hash(o); assert initialHash[hash]==size+1; initialHash[hash] = n; } return (E)o; } /** * Returns the top of the stack. */ public E peek() { return (E)data[size-1]; } private boolean findDuplicate(E o, int hash) { int p = initialHash[hash]; while(p!=0) { p--; Object existing = data[p]; if (useIdentity) { if(existing==o) return true; } else { if (o.equals(existing)) return true; } p = next[p]; } return false; } private void expandCapacity() { int oldSize = data.length; int newSize = oldSize * 2; Object[] d = new Object[newSize]; int[] n = new int[newSize]; System.arraycopy(data,0,d,0,oldSize); System.arraycopy(next,0,n,0,oldSize); data = d; next = n; } /** * Clears all the contents in the stack. */ public void reset() { if(size>0) { size = 0; Arrays.fill(initialHash,0); } } /** * String that represents the cycle. */ public String getCycleString() { StringBuilder sb = new StringBuilder(); int i=size()-1; E obj = get(i); sb.append(obj); Object x; do { sb.append(" -> "); x = get(--i); sb.append(x); } while(obj!=x); return sb.toString(); } }
samskivert/ikvm-openjdk
build/linux-amd64/impsrc/com/sun/xml/internal/bind/v2/util/CollisionCheckStack.java
Java
gpl-2.0
5,703
/* * #%L * OME SCIFIO package for reading and converting scientific file formats. * %% * Copyright (C) 2005 - 2012 Open Microscopy Environment: * - Board of Regents of the University of Wisconsin-Madison * - Glencoe Software, Inc. * - University of Dundee * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are * those of the authors and should not be interpreted as representing official * policies, either expressed or implied, of any organization. * #L% */ package loci.common; import java.io.IOException; /** * A legacy delegator class for ome.scifio.common.IniWriter. * * <dl><dt><b>Source code:</b></dt> * <dd><a href="http://trac.openmicroscopy.org.uk/ome/browser/bioformats.git/components/common/src/loci/common/IniWriter.java">Trac</a>, * <a href="http://git.openmicroscopy.org/?p=bioformats.git;a=blob;f=components/common/src/loci/common/IniWriter.java;hb=HEAD">Gitweb</a></dd></dl> * * @author Melissa Linkert melissa at glencoesoftware.com */ public class IniWriter { // -- Fields -- private ome.scifio.common.IniWriter writer; // -- Constructor -- public IniWriter() { writer = new ome.scifio.common.IniWriter(); } // -- IniWriter API methods -- /** * Saves the given IniList to the given file. * If the given file already exists, then the IniList will be appended. */ public void saveINI(IniList ini, String path) throws IOException { writer.saveINI(ini.list, path); } /** Saves the given IniList to the given file. */ public void saveINI(IniList ini, String path, boolean append) throws IOException { writer.saveINI(ini.list, path, append); } // -- Object delegators -- @Override public boolean equals(Object obj) { return writer.equals(obj); } @Override public int hashCode() { return writer.hashCode(); } @Override public String toString() { return writer.toString(); } }
ximenesuk/bioformats
components/loci-legacy/src/loci/common/IniWriter.java
Java
gpl-2.0
3,258
package dataset; public class UndefinedSampleLengthException extends Exception { private static final long serialVersionUID = 1L; }
ric2b/POO
java/src/dataset/UndefinedSampleLengthException.java
Java
gpl-2.0
135
/* * 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 Evgeniya G. Maenkova */ package org.apache.harmony.awt.text; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.security.AccessController; import java.security.PrivilegedAction; import javax.swing.text.Element; import javax.swing.text.View; public abstract class TextFactory { private static final String FACTORY_IMPL_CLS_NAME = "javax.swing.text.TextFactoryImpl"; //$NON-NLS-1$ private static final TextFactory viewFactory = createTextFactory(); public static TextFactory getTextFactory() { return viewFactory; } private static TextFactory createTextFactory() { PrivilegedAction<TextFactory> createAction = new PrivilegedAction<TextFactory>() { public TextFactory run() { try { Class<?> factoryImplClass = Class .forName(FACTORY_IMPL_CLS_NAME); Constructor<?> defConstr = factoryImplClass.getDeclaredConstructor(new Class[0]); defConstr.setAccessible(true); return (TextFactory)defConstr.newInstance(new Object[0]); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return null; } }; return AccessController.doPrivileged(createAction); } public abstract RootViewContext createRootView(final Element element); public abstract View createPlainView(final Element e); public abstract View createWrappedPlainView(final Element e); public abstract View createFieldView(final Element e); public abstract View createPasswordView(Element e); public abstract TextCaret createCaret(); }
skyHALud/codenameone
Ports/iOSPort/xmlvm/apache-harmony-6.0-src-r991881/classlib/modules/awt/src/main/java/common/org/apache/harmony/awt/text/TextFactory.java
Java
gpl-2.0
3,164
/* OtherwiseNode.java -- Copyright (C) 2004 Free Software Foundation, Inc. This file is part of GNU Classpath. GNU Classpath 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. GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to link this library 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 your choice, provided that you 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 or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ package gnu.xml.transform; import javax.xml.namespace.QName; import javax.xml.transform.TransformerException; import org.w3c.dom.Node; /** * A template node representing an XSL <code>otherwise</code> instruction. * * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a> */ final class OtherwiseNode extends TemplateNode { OtherwiseNode(TemplateNode children, TemplateNode next) { super(children, next); } TemplateNode clone(Stylesheet stylesheet) { return new OtherwiseNode((children == null) ? null : children.clone(stylesheet), (next == null) ? null : next.clone(stylesheet)); } void doApply(Stylesheet stylesheet, QName mode, Node context, int pos, int len, Node parent, Node nextSibling) throws TransformerException { if (children != null) { children.apply(stylesheet, mode, context, pos, len, parent, nextSibling); } if (next != null) { next.apply(stylesheet, mode, context, pos, len, parent, nextSibling); } } public String toString() { StringBuffer buf = new StringBuffer(getClass().getName()); buf.append('['); buf.append(']'); return buf.toString(); } }
unofficial-opensource-apple/gcc_40
libjava/gnu/xml/transform/OtherwiseNode.java
Java
gpl-2.0
3,110
// StanfordLexicalizedParser -- a probabilistic lexicalized NL CFG parser // Copyright (c) 2002, 2003, 2004, 2005 The Board of Trustees of // The Leland Stanford Junior University. 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; 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. // // For more information, bug reports, fixes, contact: // Christopher Manning // Dept of Computer Science, Gates 1A // Stanford CA 94305-9010 // USA // parser-support@lists.stanford.edu // http://nlp.stanford.edu/downloads/lex-parser.shtml package edu.stanford.nlp.parser.lexparser; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import edu.stanford.nlp.io.NumberRangeFileFilter; import edu.stanford.nlp.ling.HasWord; import edu.stanford.nlp.ling.TaggedWord; import edu.stanford.nlp.ling.Word; import edu.stanford.nlp.parser.metrics.AbstractEval; import edu.stanford.nlp.parser.metrics.UnlabeledAttachmentEval; import edu.stanford.nlp.parser.metrics.Evalb; import edu.stanford.nlp.parser.metrics.TaggingEval; import edu.stanford.nlp.trees.LeftHeadFinder; import edu.stanford.nlp.trees.MemoryTreebank; import edu.stanford.nlp.trees.Tree; import edu.stanford.nlp.trees.TreeLengthComparator; import edu.stanford.nlp.trees.TreeTransformer; import edu.stanford.nlp.trees.Treebank; import edu.stanford.nlp.trees.TreebankLanguagePack; import java.util.function.Function; import edu.stanford.nlp.util.Generics; import edu.stanford.nlp.util.HashIndex; import edu.stanford.nlp.util.Index; import edu.stanford.nlp.util.Pair; import edu.stanford.nlp.util.Timing; import edu.stanford.nlp.util.StringUtils; /** * @author Dan Klein (original version) * @author Christopher Manning (better features, ParserParams, serialization) * @author Roger Levy (internationalization) * @author Teg Grenager (grammar compaction, etc., tokenization, etc.) * @author Galen Andrew (lattice parsing) * @author Philip Resnik and Dan Zeman (n good parses) */ public class FactoredParser { /* some documentation for Roger's convenience * {pcfg,dep,combo}{PE,DE,TE} are precision/dep/tagging evals for the models * parser is the PCFG parser * dparser is the dependency parser * bparser is the combining parser * during testing: * tree is the test tree (gold tree) * binaryTree is the gold tree binarized * tree2b is the best PCFG paser, binarized * tree2 is the best PCFG parse (debinarized) * tree3 is the dependency parse, binarized * tree3db is the dependency parser, debinarized * tree4 is the best combo parse, binarized and then debinarized * tree4b is the best combo parse, binarized */ public static void main(String[] args) { Options op = new Options(new EnglishTreebankParserParams()); // op.tlpParams may be changed to something else later, so don't use it till // after options are parsed. System.out.println(StringUtils.toInvocationString("FactoredParser", args)); String path = "/u/nlp/stuff/corpora/Treebank3/parsed/mrg/wsj"; int trainLow = 200, trainHigh = 2199, testLow = 2200, testHigh = 2219; String serializeFile = null; int i = 0; while (i < args.length && args[i].startsWith("-")) { if (args[i].equalsIgnoreCase("-path") && (i + 1 < args.length)) { path = args[i + 1]; i += 2; } else if (args[i].equalsIgnoreCase("-train") && (i + 2 < args.length)) { trainLow = Integer.parseInt(args[i + 1]); trainHigh = Integer.parseInt(args[i + 2]); i += 3; } else if (args[i].equalsIgnoreCase("-test") && (i + 2 < args.length)) { testLow = Integer.parseInt(args[i + 1]); testHigh = Integer.parseInt(args[i + 2]); i += 3; } else if (args[i].equalsIgnoreCase("-serialize") && (i + 1 < args.length)) { serializeFile = args[i + 1]; i += 2; } else if (args[i].equalsIgnoreCase("-tLPP") && (i + 1 < args.length)) { try { op.tlpParams = (TreebankLangParserParams) Class.forName(args[i + 1]).newInstance(); } catch (ClassNotFoundException e) { System.err.println("Class not found: " + args[i + 1]); throw new RuntimeException(e); } catch (InstantiationException e) { System.err.println("Couldn't instantiate: " + args[i + 1] + ": " + e.toString()); throw new RuntimeException(e); } catch (IllegalAccessException e) { System.err.println("illegal access" + e); throw new RuntimeException(e); } i += 2; } else if (args[i].equals("-encoding")) { // sets encoding for TreebankLangParserParams op.tlpParams.setInputEncoding(args[i + 1]); op.tlpParams.setOutputEncoding(args[i + 1]); i += 2; } else { i = op.setOptionOrWarn(args, i); } } // System.out.println(tlpParams.getClass()); TreebankLanguagePack tlp = op.tlpParams.treebankLanguagePack(); op.trainOptions.sisterSplitters = Generics.newHashSet(Arrays.asList(op.tlpParams.sisterSplitters())); // BinarizerFactory.TreeAnnotator.setTreebankLang(tlpParams); PrintWriter pw = op.tlpParams.pw(); op.testOptions.display(); op.trainOptions.display(); op.display(); op.tlpParams.display(); // setup tree transforms Treebank trainTreebank = op.tlpParams.memoryTreebank(); MemoryTreebank testTreebank = op.tlpParams.testMemoryTreebank(); // Treebank blippTreebank = ((EnglishTreebankParserParams) tlpParams).diskTreebank(); // String blippPath = "/afs/ir.stanford.edu/data/linguistic-data/BLLIP-WSJ/"; // blippTreebank.loadPath(blippPath, "", true); Timing.startTime(); System.err.print("Reading trees..."); testTreebank.loadPath(path, new NumberRangeFileFilter(testLow, testHigh, true)); if (op.testOptions.increasingLength) { Collections.sort(testTreebank, new TreeLengthComparator()); } trainTreebank.loadPath(path, new NumberRangeFileFilter(trainLow, trainHigh, true)); Timing.tick("done."); System.err.print("Binarizing trees..."); TreeAnnotatorAndBinarizer binarizer; if (!op.trainOptions.leftToRight) { binarizer = new TreeAnnotatorAndBinarizer(op.tlpParams, op.forceCNF, !op.trainOptions.outsideFactor(), true, op); } else { binarizer = new TreeAnnotatorAndBinarizer(op.tlpParams.headFinder(), new LeftHeadFinder(), op.tlpParams, op.forceCNF, !op.trainOptions.outsideFactor(), true, op); } CollinsPuncTransformer collinsPuncTransformer = null; if (op.trainOptions.collinsPunc) { collinsPuncTransformer = new CollinsPuncTransformer(tlp); } TreeTransformer debinarizer = new Debinarizer(op.forceCNF); List<Tree> binaryTrainTrees = new ArrayList<>(); if (op.trainOptions.selectiveSplit) { op.trainOptions.splitters = ParentAnnotationStats.getSplitCategories(trainTreebank, op.trainOptions.tagSelectiveSplit, 0, op.trainOptions.selectiveSplitCutOff, op.trainOptions.tagSelectiveSplitCutOff, op.tlpParams.treebankLanguagePack()); if (op.trainOptions.deleteSplitters != null) { List<String> deleted = new ArrayList<>(); for (String del : op.trainOptions.deleteSplitters) { String baseDel = tlp.basicCategory(del); boolean checkBasic = del.equals(baseDel); for (Iterator<String> it = op.trainOptions.splitters.iterator(); it.hasNext(); ) { String elem = it.next(); String baseElem = tlp.basicCategory(elem); boolean delStr = checkBasic && baseElem.equals(baseDel) || elem.equals(del); if (delStr) { it.remove(); deleted.add(elem); } } } System.err.println("Removed from vertical splitters: " + deleted); } } if (op.trainOptions.selectivePostSplit) { TreeTransformer myTransformer = new TreeAnnotator(op.tlpParams.headFinder(), op.tlpParams, op); Treebank annotatedTB = trainTreebank.transform(myTransformer); op.trainOptions.postSplitters = ParentAnnotationStats.getSplitCategories(annotatedTB, true, 0, op.trainOptions.selectivePostSplitCutOff, op.trainOptions.tagSelectivePostSplitCutOff, op.tlpParams.treebankLanguagePack()); } if (op.trainOptions.hSelSplit) { binarizer.setDoSelectiveSplit(false); for (Tree tree : trainTreebank) { if (op.trainOptions.collinsPunc) { tree = collinsPuncTransformer.transformTree(tree); } //tree.pennPrint(tlpParams.pw()); tree = binarizer.transformTree(tree); //binaryTrainTrees.add(tree); } binarizer.setDoSelectiveSplit(true); } for (Tree tree : trainTreebank) { if (op.trainOptions.collinsPunc) { tree = collinsPuncTransformer.transformTree(tree); } tree = binarizer.transformTree(tree); binaryTrainTrees.add(tree); } if (op.testOptions.verbose) { binarizer.dumpStats(); } List<Tree> binaryTestTrees = new ArrayList<>(); for (Tree tree : testTreebank) { if (op.trainOptions.collinsPunc) { tree = collinsPuncTransformer.transformTree(tree); } tree = binarizer.transformTree(tree); binaryTestTrees.add(tree); } Timing.tick("done."); // binarization BinaryGrammar bg = null; UnaryGrammar ug = null; DependencyGrammar dg = null; // DependencyGrammar dgBLIPP = null; Lexicon lex = null; Index<String> stateIndex = new HashIndex<>(); // extract grammars Extractor<Pair<UnaryGrammar,BinaryGrammar>> bgExtractor = new BinaryGrammarExtractor(op, stateIndex); //Extractor bgExtractor = new SmoothedBinaryGrammarExtractor();//new BinaryGrammarExtractor(); // Extractor lexExtractor = new LexiconExtractor(); //Extractor dgExtractor = new DependencyMemGrammarExtractor(); if (op.doPCFG) { System.err.print("Extracting PCFG..."); Pair<UnaryGrammar, BinaryGrammar> bgug = null; if (op.trainOptions.cheatPCFG) { List<Tree> allTrees = new ArrayList<>(binaryTrainTrees); allTrees.addAll(binaryTestTrees); bgug = bgExtractor.extract(allTrees); } else { bgug = bgExtractor.extract(binaryTrainTrees); } bg = bgug.second; bg.splitRules(); ug = bgug.first; ug.purgeRules(); Timing.tick("done."); } System.err.print("Extracting Lexicon..."); Index<String> wordIndex = new HashIndex<>(); Index<String> tagIndex = new HashIndex<>(); lex = op.tlpParams.lex(op, wordIndex, tagIndex); lex.initializeTraining(binaryTrainTrees.size()); lex.train(binaryTrainTrees); lex.finishTraining(); Timing.tick("done."); if (op.doDep) { System.err.print("Extracting Dependencies..."); binaryTrainTrees.clear(); Extractor<DependencyGrammar> dgExtractor = new MLEDependencyGrammarExtractor(op, wordIndex, tagIndex); // dgBLIPP = (DependencyGrammar) dgExtractor.extract(new ConcatenationIterator(trainTreebank.iterator(),blippTreebank.iterator()),new TransformTreeDependency(tlpParams,true)); // DependencyGrammar dg1 = dgExtractor.extract(trainTreebank.iterator(), new TransformTreeDependency(op.tlpParams, true)); //dgBLIPP=(DependencyGrammar)dgExtractor.extract(blippTreebank.iterator(),new TransformTreeDependency(tlpParams)); //dg = (DependencyGrammar) dgExtractor.extract(new ConcatenationIterator(trainTreebank.iterator(),blippTreebank.iterator()),new TransformTreeDependency(tlpParams)); // dg=new DependencyGrammarCombination(dg1,dgBLIPP,2); dg = dgExtractor.extract(binaryTrainTrees); //uses information whether the words are known or not, discards unknown words Timing.tick("done."); //System.out.print("Extracting Unknown Word Model..."); //UnknownWordModel uwm = (UnknownWordModel)uwmExtractor.extract(binaryTrainTrees); //Timing.tick("done."); System.out.print("Tuning Dependency Model..."); dg.tune(binaryTestTrees); //System.out.println("TUNE DEPS: "+tuneDeps); Timing.tick("done."); } BinaryGrammar boundBG = bg; UnaryGrammar boundUG = ug; GrammarProjection gp = new NullGrammarProjection(bg, ug); // serialization if (serializeFile != null) { System.err.print("Serializing parser..."); LexicalizedParser parser = new LexicalizedParser(lex, bg, ug, dg, stateIndex, wordIndex, tagIndex, op); parser.saveParserToSerialized(serializeFile); Timing.tick("done."); } // test: pcfg-parse and output ExhaustivePCFGParser parser = null; if (op.doPCFG) { parser = new ExhaustivePCFGParser(boundBG, boundUG, lex, op, stateIndex, wordIndex, tagIndex); } ExhaustiveDependencyParser dparser = ((op.doDep && ! op.testOptions.useFastFactored) ? new ExhaustiveDependencyParser(dg, lex, op, wordIndex, tagIndex) : null); Scorer scorer = (op.doPCFG ? new TwinScorer(new ProjectionScorer(parser, gp, op), dparser) : null); //Scorer scorer = parser; BiLexPCFGParser bparser = null; if (op.doPCFG && op.doDep) { bparser = (op.testOptions.useN5) ? new BiLexPCFGParser.N5BiLexPCFGParser(scorer, parser, dparser, bg, ug, dg, lex, op, gp, stateIndex, wordIndex, tagIndex) : new BiLexPCFGParser(scorer, parser, dparser, bg, ug, dg, lex, op, gp, stateIndex, wordIndex, tagIndex); } Evalb pcfgPE = new Evalb("pcfg PE", true); Evalb comboPE = new Evalb("combo PE", true); AbstractEval pcfgCB = new Evalb.CBEval("pcfg CB", true); AbstractEval pcfgTE = new TaggingEval("pcfg TE"); AbstractEval comboTE = new TaggingEval("combo TE"); AbstractEval pcfgTEnoPunct = new TaggingEval("pcfg nopunct TE"); AbstractEval comboTEnoPunct = new TaggingEval("combo nopunct TE"); AbstractEval depTE = new TaggingEval("depnd TE"); AbstractEval depDE = new UnlabeledAttachmentEval("depnd DE", true, null, tlp.punctuationWordRejectFilter()); AbstractEval comboDE = new UnlabeledAttachmentEval("combo DE", true, null, tlp.punctuationWordRejectFilter()); if (op.testOptions.evalb) { EvalbFormatWriter.initEVALBfiles(op.tlpParams); } // int[] countByLength = new int[op.testOptions.maxLength+1]; // Use a reflection ruse, so one can run this without needing the // tagger. Using a function rather than a MaxentTagger means we // can distribute a version of the parser that doesn't include the // entire tagger. Function<List<? extends HasWord>,ArrayList<TaggedWord>> tagger = null; if (op.testOptions.preTag) { try { Class[] argsClass = { String.class }; Object[] arguments = new Object[]{op.testOptions.taggerSerializedFile}; tagger = (Function<List<? extends HasWord>,ArrayList<TaggedWord>>) Class.forName("edu.stanford.nlp.tagger.maxent.MaxentTagger").getConstructor(argsClass).newInstance(arguments); } catch (Exception e) { System.err.println(e); System.err.println("Warning: No pretagging of sentences will be done."); } } for (int tNum = 0, ttSize = testTreebank.size(); tNum < ttSize; tNum++) { Tree tree = testTreebank.get(tNum); int testTreeLen = tree.yield().size(); if (testTreeLen > op.testOptions.maxLength) { continue; } Tree binaryTree = binaryTestTrees.get(tNum); // countByLength[testTreeLen]++; System.out.println("-------------------------------------"); System.out.println("Number: " + (tNum + 1)); System.out.println("Length: " + testTreeLen); //tree.pennPrint(pw); // System.out.println("XXXX The binary tree is"); // binaryTree.pennPrint(pw); //System.out.println("Here are the tags in the lexicon:"); //System.out.println(lex.showTags()); //System.out.println("Here's the tagnumberer:"); //System.out.println(Numberer.getGlobalNumberer("tags").toString()); long timeMil1 = System.currentTimeMillis(); Timing.tick("Starting parse."); if (op.doPCFG) { //System.err.println(op.testOptions.forceTags); if (op.testOptions.forceTags) { if (tagger != null) { //System.out.println("Using a tagger to set tags"); //System.out.println("Tagged sentence as: " + tagger.processSentence(cutLast(wordify(binaryTree.yield()))).toString(false)); parser.parse(addLast(tagger.apply(cutLast(wordify(binaryTree.yield()))))); } else { //System.out.println("Forcing tags to match input."); parser.parse(cleanTags(binaryTree.taggedYield(), tlp)); } } else { // System.out.println("XXXX Parsing " + binaryTree.yield()); parser.parse(binaryTree.yieldHasWord()); } //Timing.tick("Done with pcfg phase."); } if (op.doDep) { dparser.parse(binaryTree.yieldHasWord()); //Timing.tick("Done with dependency phase."); } boolean bothPassed = false; if (op.doPCFG && op.doDep) { bothPassed = bparser.parse(binaryTree.yieldHasWord()); //Timing.tick("Done with combination phase."); } long timeMil2 = System.currentTimeMillis(); long elapsed = timeMil2 - timeMil1; System.err.println("Time: " + ((int) (elapsed / 100)) / 10.00 + " sec."); //System.out.println("PCFG Best Parse:"); Tree tree2b = null; Tree tree2 = null; //System.out.println("Got full best parse..."); if (op.doPCFG) { tree2b = parser.getBestParse(); tree2 = debinarizer.transformTree(tree2b); } //System.out.println("Debinarized parse..."); //tree2.pennPrint(); //System.out.println("DepG Best Parse:"); Tree tree3 = null; Tree tree3db = null; if (op.doDep) { tree3 = dparser.getBestParse(); // was: but wrong Tree tree3db = debinarizer.transformTree(tree2); tree3db = debinarizer.transformTree(tree3); tree3.pennPrint(pw); } //tree.pennPrint(); //((Tree)binaryTrainTrees.get(tNum)).pennPrint(); //System.out.println("Combo Best Parse:"); Tree tree4 = null; if (op.doPCFG && op.doDep) { try { tree4 = bparser.getBestParse(); if (tree4 == null) { tree4 = tree2b; } } catch (NullPointerException e) { System.err.println("Blocked, using PCFG parse!"); tree4 = tree2b; } } if (op.doPCFG && !bothPassed) { tree4 = tree2b; } //tree4.pennPrint(); if (op.doDep) { depDE.evaluate(tree3, binaryTree, pw); depTE.evaluate(tree3db, tree, pw); } TreeTransformer tc = op.tlpParams.collinizer(); TreeTransformer tcEvalb = op.tlpParams.collinizerEvalb(); if (op.doPCFG) { // System.out.println("XXXX Best PCFG was: "); // tree2.pennPrint(); // System.out.println("XXXX Transformed best PCFG is: "); // tc.transformTree(tree2).pennPrint(); //System.out.println("True Best Parse:"); //tree.pennPrint(); //tc.transformTree(tree).pennPrint(); pcfgPE.evaluate(tc.transformTree(tree2), tc.transformTree(tree), pw); pcfgCB.evaluate(tc.transformTree(tree2), tc.transformTree(tree), pw); Tree tree4b = null; if (op.doDep) { comboDE.evaluate((bothPassed ? tree4 : tree3), binaryTree, pw); tree4b = tree4; tree4 = debinarizer.transformTree(tree4); if (op.nodePrune) { NodePruner np = new NodePruner(parser, debinarizer); tree4 = np.prune(tree4); } //tree4.pennPrint(); comboPE.evaluate(tc.transformTree(tree4), tc.transformTree(tree), pw); } //pcfgTE.evaluate(tree2, tree); pcfgTE.evaluate(tcEvalb.transformTree(tree2), tcEvalb.transformTree(tree), pw); pcfgTEnoPunct.evaluate(tc.transformTree(tree2), tc.transformTree(tree), pw); if (op.doDep) { comboTE.evaluate(tcEvalb.transformTree(tree4), tcEvalb.transformTree(tree), pw); comboTEnoPunct.evaluate(tc.transformTree(tree4), tc.transformTree(tree), pw); } System.out.println("PCFG only: " + parser.scoreBinarizedTree(tree2b, 0)); //tc.transformTree(tree2).pennPrint(); tree2.pennPrint(pw); if (op.doDep) { System.out.println("Combo: " + parser.scoreBinarizedTree(tree4b, 0)); // tc.transformTree(tree4).pennPrint(pw); tree4.pennPrint(pw); } System.out.println("Correct:" + parser.scoreBinarizedTree(binaryTree, 0)); /* if (parser.scoreBinarizedTree(tree2b,true) < parser.scoreBinarizedTree(binaryTree,true)) { System.out.println("SCORE INVERSION"); parser.validateBinarizedTree(binaryTree,0); } */ tree.pennPrint(pw); } // end if doPCFG if (op.testOptions.evalb) { if (op.doPCFG && op.doDep) { EvalbFormatWriter.writeEVALBline(tcEvalb.transformTree(tree), tcEvalb.transformTree(tree4)); } else if (op.doPCFG) { EvalbFormatWriter.writeEVALBline(tcEvalb.transformTree(tree), tcEvalb.transformTree(tree2)); } else if (op.doDep) { EvalbFormatWriter.writeEVALBline(tcEvalb.transformTree(tree), tcEvalb.transformTree(tree3db)); } } } // end for each tree in test treebank if (op.testOptions.evalb) { EvalbFormatWriter.closeEVALBfiles(); } // op.testOptions.display(); if (op.doPCFG) { pcfgPE.display(false, pw); System.out.println("Grammar size: " + stateIndex.size()); pcfgCB.display(false, pw); if (op.doDep) { comboPE.display(false, pw); } pcfgTE.display(false, pw); pcfgTEnoPunct.display(false, pw); if (op.doDep) { comboTE.display(false, pw); comboTEnoPunct.display(false, pw); } } if (op.doDep) { depTE.display(false, pw); depDE.display(false, pw); } if (op.doPCFG && op.doDep) { comboDE.display(false, pw); } // pcfgPE.printGoodBad(); } private static List<TaggedWord> cleanTags(List<TaggedWord> twList, TreebankLanguagePack tlp) { int sz = twList.size(); List<TaggedWord> l = new ArrayList<>(sz); for (TaggedWord tw : twList) { TaggedWord tw2 = new TaggedWord(tw.word(), tlp.basicCategory(tw.tag())); l.add(tw2); } return l; } private static ArrayList<Word> wordify(List wList) { ArrayList<Word> s = new ArrayList<>(); for (Object obj : wList) { s.add(new Word(obj.toString())); } return s; } private static ArrayList<Word> cutLast(ArrayList<Word> s) { return new ArrayList<>(s.subList(0, s.size() - 1)); } private static ArrayList<Word> addLast(ArrayList<? extends Word> s) { ArrayList<Word> s2 = new ArrayList<>(s); //s2.add(new StringLabel(Lexicon.BOUNDARY)); s2.add(new Word(Lexicon.BOUNDARY)); return s2; } /** * Not an instantiable class */ private FactoredParser() { } }
hbbpb/stanford-corenlp-gv
src/edu/stanford/nlp/parser/lexparser/FactoredParser.java
Java
gpl-2.0
23,782
package com.oinux.lanmitm.service; import com.oinux.lanmitm.R; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.os.IBinder; public class BaseService extends Service { public static final int HTTP_SERVER_NOTICE = 1; public static final int HIJACK_NOTICE = 2; public static final int SNIFFER_NOTICE = 3; public static final int INJECT_NOTICE = 4; public static final int ARPSPOOF_NOTICE = 0; @Override public IBinder onBind(Intent intent) { return null; } @SuppressWarnings("deprecation") protected void notice(String tickerText, int id, Class<?> cls) { NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); Notification n = new Notification(R.drawable.ic_launch_notice, getString(R.string.app_name), System.currentTimeMillis()); n.flags = Notification.FLAG_NO_CLEAR; Intent intent = new Intent(this, cls); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); PendingIntent contentIntent = PendingIntent.getActivity(this, R.string.app_name, intent, PendingIntent.FLAG_UPDATE_CURRENT); n.setLatestEventInfo(this, this.getString(R.string.app_name), tickerText, contentIntent); nm.notify(id, n); } }
vaginessa/Lanmitm
src/com/oinux/lanmitm/service/BaseService.java
Java
gpl-2.0
1,380
/* ==================================================================== * 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.apache.jcc; public class PythonVM { static protected PythonVM vm; static { System.loadLibrary("jcc"); } static public PythonVM start(String programName, String[] args) { if (vm == null) { vm = new PythonVM(); vm.init(programName, args); } return vm; } static public PythonVM start(String programName) { return start(programName, null); } static public PythonVM get() { return vm; } protected PythonVM() { } protected native void init(String programName, String[] args); public native Object instantiate(String moduleName, String className) throws PythonException; }
adamdoupe/enemy-of-the-state
jcc/java/org/apache/jcc/PythonVM.java
Java
gpl-2.0
1,466
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.math.analysis.interpolation; import org.apache.commons.math.MathException; import org.apache.commons.math.exception.NonMonotonousSequenceException; import org.apache.commons.math.exception.DimensionMismatchException; import org.apache.commons.math.exception.NumberIsTooSmallException; import org.apache.commons.math.TestUtils; import org.apache.commons.math.analysis.UnivariateRealFunction; import org.apache.commons.math.analysis.polynomials.PolynomialFunction; import org.apache.commons.math.analysis.polynomials.PolynomialSplineFunction; import org.junit.Assert; import org.junit.Test; /** * Test the LinearInterpolator. */ public class LinearInterpolatorTest { /** error tolerance for spline interpolator value at knot points */ protected double knotTolerance = 1E-12; /** error tolerance for interpolating polynomial coefficients */ protected double coefficientTolerance = 1E-6; /** error tolerance for interpolated values */ protected double interpolationTolerance = 1E-12; @Test public void testInterpolateLinearDegenerateTwoSegment() throws Exception { double x[] = { 0.0, 0.5, 1.0 }; double y[] = { 0.0, 0.5, 1.0 }; UnivariateRealInterpolator i = new LinearInterpolator(); UnivariateRealFunction f = i.interpolate(x, y); verifyInterpolation(f, x, y); // Verify coefficients using analytical values PolynomialFunction polynomials[] = ((PolynomialSplineFunction) f).getPolynomials(); double target[] = {y[0], 1d}; TestUtils.assertEquals(polynomials[0].getCoefficients(), target, coefficientTolerance); target = new double[]{y[1], 1d}; TestUtils.assertEquals(polynomials[1].getCoefficients(), target, coefficientTolerance); // Check interpolation Assert.assertEquals(0.0,f.value(0.0), interpolationTolerance); Assert.assertEquals(0.4,f.value(0.4), interpolationTolerance); Assert.assertEquals(1.0,f.value(1.0), interpolationTolerance); } @Test public void testInterpolateLinearDegenerateThreeSegment() throws Exception { double x[] = { 0.0, 0.5, 1.0, 1.5 }; double y[] = { 0.0, 0.5, 1.0, 1.5 }; UnivariateRealInterpolator i = new LinearInterpolator(); UnivariateRealFunction f = i.interpolate(x, y); verifyInterpolation(f, x, y); // Verify coefficients using analytical values PolynomialFunction polynomials[] = ((PolynomialSplineFunction) f).getPolynomials(); double target[] = {y[0], 1d}; TestUtils.assertEquals(polynomials[0].getCoefficients(), target, coefficientTolerance); target = new double[]{y[1], 1d}; TestUtils.assertEquals(polynomials[1].getCoefficients(), target, coefficientTolerance); target = new double[]{y[2], 1d}; TestUtils.assertEquals(polynomials[2].getCoefficients(), target, coefficientTolerance); // Check interpolation Assert.assertEquals(0,f.value(0), interpolationTolerance); Assert.assertEquals(1.4,f.value(1.4), interpolationTolerance); Assert.assertEquals(1.5,f.value(1.5), interpolationTolerance); } @Test public void testInterpolateLinear() throws Exception { double x[] = { 0.0, 0.5, 1.0 }; double y[] = { 0.0, 0.5, 0.0 }; UnivariateRealInterpolator i = new LinearInterpolator(); UnivariateRealFunction f = i.interpolate(x, y); verifyInterpolation(f, x, y); // Verify coefficients using analytical values PolynomialFunction polynomials[] = ((PolynomialSplineFunction) f).getPolynomials(); double target[] = {y[0], 1d}; TestUtils.assertEquals(polynomials[0].getCoefficients(), target, coefficientTolerance); target = new double[]{y[1], -1d}; TestUtils.assertEquals(polynomials[1].getCoefficients(), target, coefficientTolerance); } @Test public void testIllegalArguments() throws MathException { // Data set arrays of different size. UnivariateRealInterpolator i = new LinearInterpolator(); try { double xval[] = { 0.0, 1.0 }; double yval[] = { 0.0, 1.0, 2.0 }; i.interpolate(xval, yval); Assert.fail("Failed to detect data set array with different sizes."); } catch (DimensionMismatchException iae) { // Expected. } // X values not sorted. try { double xval[] = { 0.0, 1.0, 0.5 }; double yval[] = { 0.0, 1.0, 2.0 }; i.interpolate(xval, yval); Assert.fail("Failed to detect unsorted arguments."); } catch (NonMonotonousSequenceException iae) { // Expected. } // Not enough data to interpolate. try { double xval[] = { 0.0 }; double yval[] = { 0.0 }; i.interpolate(xval, yval); Assert.fail("Failed to detect unsorted arguments."); } catch (NumberIsTooSmallException iae) { // Expected. } } /** * verifies that f(x[i]) = y[i] for i = 0..n-1 where n is common length. */ protected void verifyInterpolation(UnivariateRealFunction f, double x[], double y[]) throws Exception{ for (int i = 0; i < x.length; i++) { Assert.assertEquals(f.value(x[i]), y[i], knotTolerance); } } }
SpoonLabs/astor
examples/math_63/src/test/java/org/apache/commons/math/analysis/interpolation/LinearInterpolatorTest.java
Java
gpl-2.0
6,231
package com.avrgaming.civcraft.structure; import java.sql.ResultSet; import java.sql.SQLException; import java.util.concurrent.locks.ReentrantLock; import org.bukkit.Location; import com.avrgaming.civcraft.config.CivSettings; import com.avrgaming.civcraft.exception.CivException; import com.avrgaming.civcraft.exception.InvalidConfiguration; import com.avrgaming.civcraft.object.Buff; import com.avrgaming.civcraft.object.Town; public class MobGrinder extends Structure { private static final double T1_CHANCE = CivSettings.getDoubleStructure("mobGrinder.t1_chance"); //1% private static final double T2_CHANCE = CivSettings.getDoubleStructure("mobGrinder.t2_chance"); //2% private static final double T3_CHANCE = CivSettings.getDoubleStructure("mobGrinder.t3_chance"); //1% private static final double T4_CHANCE = CivSettings.getDoubleStructure("mobGrinder.t4_chance"); //0.25% private static final double PACK_CHANCE = CivSettings.getDoubleStructure("mobGrinder.pack_chance"); //0.10% private static final double BIGPACK_CHANCE = CivSettings.getDoubleStructure("mobGrinder.bigpack_chance"); private static final double HUGEPACK_CHANCE = CivSettings.getDoubleStructure("mobGrinder.hugepack_chance"); public int skippedCounter = 0; public ReentrantLock lock = new ReentrantLock(); public enum Crystal { T1, T2, T3, T4, PACK, BIGPACK, HUGEPACK } protected MobGrinder(Location center, String id, Town town) throws CivException { super(center, id, town); } public MobGrinder(ResultSet rs) throws SQLException, CivException { super(rs); } @Override public String getDynmapDescription() { return null; } @Override public String getMarkerIconName() { return "minecart"; } public double getMineralChance(Crystal crystal) { double chance = 0; switch (crystal) { case T1: chance = T1_CHANCE; break; case T2: chance = T2_CHANCE; break; case T3: chance = T3_CHANCE; break; case T4: chance = T4_CHANCE; break; case PACK: chance = PACK_CHANCE; break; case BIGPACK: chance = BIGPACK_CHANCE; break; case HUGEPACK: chance = HUGEPACK_CHANCE; } double increase = chance*this.getTown().getBuffManager().getEffectiveDouble(Buff.EXTRACTION); chance += increase; try { if (this.getTown().getGovernment().id.equals("gov_tribalism")) { chance *= CivSettings.getDouble(CivSettings.structureConfig, "mobGrinder.tribalism_rate"); } else { chance *= CivSettings.getDouble(CivSettings.structureConfig, "mobGrinder.penalty_rate"); } } catch (InvalidConfiguration e) { e.printStackTrace(); } return chance; } }
ataranlen/civcraft
civcraft/src/com/avrgaming/civcraft/structure/MobGrinder.java
Java
gpl-2.0
2,644
/* * $Id$ * * Copyright 2006 University of Dundee. All rights reserved. * Use is subject to license terms supplied in LICENSE.txt */ package ome.server.itests.hibernate; import java.util.Arrays; import java.util.Set; import ome.model.IAnnotated; import ome.model.ILink; import ome.model.IObject; import ome.model.annotations.Annotation; import ome.model.annotations.BasicAnnotation; import ome.model.annotations.LongAnnotation; import ome.model.containers.Dataset; import ome.model.containers.DatasetImageLink; import ome.model.containers.Project; import ome.model.containers.ProjectDatasetLink; import ome.model.core.Image; import ome.model.core.Pixels; import ome.model.display.RenderingDef; import ome.model.meta.Experimenter; import ome.server.itests.AbstractManagedContextTest; import ome.testing.ObjectFactory; import ome.tools.hibernate.ExtendedMetadata; import org.hibernate.SessionFactory; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class ExtendedMetadataTest extends AbstractManagedContextTest { ExtendedMetadata.Impl metadata; @BeforeClass public void init() throws Exception { setUp(); metadata = new ExtendedMetadata.Impl(); metadata.setSessionFactory((SessionFactory)applicationContext.getBean("sessionFactory")); tearDown(); } @Test public void testAnnotatedAreFound() throws Exception { Set<Class<IAnnotated>> anns = metadata.getAnnotatableTypes(); assertTrue(anns.contains(Image.class)); assertTrue(anns.contains(Project.class)); // And several others } @Test public void testAnnotationsAreFound() throws Exception { Set<Class<Annotation>> anns = metadata.getAnnotationTypes(); assertTrue(anns.toString(), anns.contains(Annotation.class)); assertTrue(anns.toString(), anns.contains(BasicAnnotation.class)); assertTrue(anns.toString(), anns.contains(LongAnnotation.class)); // And several others } /** * Where a superclass has a relationship to a class (Annotation to some link type), * it is also necessary to be able to find the same relationship from a subclass * (e.g. FileAnnotation). */ @Test public void testLinkFromSubclassToSuperClassRel() { assertNotNull( metadata.getRelationship("ImageAnnotationLink", "FileAnnotation")); } /** * For simplicity, the relationship map currently holds only the short * class names. Here we are adding a test which checks for the full ones * under "broken" to remember to re-evaluate. */ @Test(groups = {"broken","fixme"}) public void testAnnotatedAreFoundByFQN() throws Exception { Set<Class<IAnnotated>> anns = metadata.getAnnotatableTypes(); assertTrue(anns.contains(Image.class)); assertTrue(anns.contains(Project.class)); // And several others } // ~ Locking // ========================================================================= @Test public void testProjectLocksDataset() throws Exception { Project p = new Project(); Dataset d = new Dataset(); p.linkDataset(d); ILink l = (ILink) p.collectDatasetLinks(null).iterator().next(); assertDoesntContain(metadata.getLockCandidates(p), d); assertContains(metadata.getLockCandidates(l), d); } @Test // Because Pixels does not have a reference to RenderingDef public void testRenderingDefLocksPixels() throws Exception { Pixels p = ObjectFactory.createPixelGraph(null); RenderingDef r = ObjectFactory.createRenderingDef(); r.setPixels(p); assertContains(metadata.getLockCandidates(r), p); } @Test(groups = "ticket:357") // quirky because of defaultTag // see https://trac.openmicroscopy.org/ome/ticket/357 public void testPixelsLocksImage() throws Exception { Pixels p = ObjectFactory.createPixelGraph(null); Image i = new Image(); i.setName("locking"); i.addPixels(p); assertContains(metadata.getLockCandidates(p), i); } @Test // omit locks for system types (TODO they shouldn't have permissions anyway) public void testExperimenterDoesntGetLocked() throws Exception { Experimenter e = new Experimenter(); Project p = new Project(); p.getDetails().setOwner(e); assertDoesntContain(metadata.getLockCandidates(p), e); } @Test public void testNoNulls() throws Exception { Project p = new Project(); ProjectDatasetLink pdl = new ProjectDatasetLink(); pdl.link(p, null); assertDoesntContain(metadata.getLockCandidates(pdl), null); } // ~ Unlocking // ========================================================================= @Test public void testProjectCanBeUnlockedFromDataset() throws Exception { assertContains(metadata.getLockChecks(Project.class), ProjectDatasetLink.class.getName(), "parent"); } @Test // Because Pixels does not have a reference to RenderingDef public void testPixelsCanBeUnlockedFromRenderingDef() throws Exception { assertContains(metadata.getLockChecks(Pixels.class), RenderingDef.class .getName(), "pixels"); } @Test(groups = "ticket:357") // quirky because of defaultTag // see https://trac.openmicroscopy.org/ome/ticket/357 public void testImageCanBeUnlockedFromPixels() throws Exception { assertContains(metadata.getLockChecks(Image.class), Pixels.class .getName(), "image"); } // ~ Updating // ========================================================================= @Test(groups = { "ticket:346", "broken" }) public void testCreateEventImmutable() throws Exception { assertContains(metadata.getImmutableFields(Image.class), "details.creationEvent"); } // ~ Counting // ========================================================================= @Test(groups = { "ticket:657" }) public void testCountQueriesAreCorrect() throws Exception { assertEquals(metadata.getCountQuery(DatasetImageLink.CHILD), metadata .getCountQuery(DatasetImageLink.CHILD), "select target.child.id, count(target) " + "from ome.model.containers.DatasetImageLink target " + "group by target.child.id"); assertEquals(metadata.getCountQuery(Pixels.IMAGE), metadata .getCountQuery(Pixels.IMAGE), "select target.image.id, count(target) " + "from ome.model.core.Pixels target " + "group by target.image.id"); } @Test(groups = { "ticket:657" }) public void testTargetTypes() throws Exception { assertEquals(metadata.getTargetType(Pixels.IMAGE), Image.class); assertEquals(metadata.getTargetType(DatasetImageLink.CHILD), Image.class); } // ~ Relationships // ========================================================================= @Test(groups = "ticket:2665") public void testRelationships() { String rel; rel = metadata.getRelationship(Pixels.class.getSimpleName(), Image.class.getSimpleName()); assertEquals("image", rel); rel = metadata.getRelationship(Image.class.getSimpleName(), Pixels.class.getSimpleName()); assertEquals("pixels", rel); } // ~ Helpers // ========================================================================= private void assertContains(Object[] array, Object i) { if (!contained(array, i)) { fail(i + " not contained in " + Arrays.toString(array)); } } private void assertDoesntContain(IObject[] array, IObject i) { if (contained(array, i)) { fail(i + " contained in " + Arrays.toString(array)); } } private void assertContains(String[][] array, String t1, String t2) { boolean contained = false; for (int i = 0; i < array.length; i++) { String[] test = array[i]; if (test[0].equals(t1) && test[1].equals(t2)) { contained |= true; } } assertTrue(contained); } private boolean contained(Object[] array, Object i) { boolean contained = false; for (Object object : array) { if (i == null) { if (object == null) { contained = true; } } else { if (i.equals(object)) { contained = true; } } } return contained; } }
knabar/openmicroscopy
components/server/test/ome/server/itests/hibernate/ExtendedMetadataTest.java
Java
gpl-2.0
8,808
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package bc; import be.ReporteFumigacion; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; /** * * @author argos */ @Stateless public class ReporteFumigacionFacade extends AbstractFacade<ReporteFumigacion> implements ReporteFumigacionFacadeLocal { @PersistenceContext(unitName = "sistema-ejbPU") private EntityManager em; protected EntityManager getEntityManager() { return em; } public ReporteFumigacionFacade() { super(ReporteFumigacion.class); } }
jchalco/Ate
sistema/sistema-ejb/src/java/bc/ReporteFumigacionFacade.java
Java
gpl-2.0
663
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.math3.stat.clustering; import java.io.Serializable; import java.util.Collection; import java.util.Arrays; import org.apache.commons.math3.util.MathArrays; /** * A simple implementation of {@link Clusterable} for points with double coordinates. * @version $Id$ * @since 3.1 */ public class EuclideanDoublePoint implements Clusterable<EuclideanDoublePoint>, Serializable { /** Serializable version identifier. */ private static final long serialVersionUID = 8026472786091227632L; /** Point coordinates. */ private final double[] point; /** * Build an instance wrapping an integer array. * <p> * The wrapped array is referenced, it is <em>not</em> copied. * * @param point the n-dimensional point in integer space */ public EuclideanDoublePoint(final double[] point) { this.point = point; } /** {@inheritDoc} */ public EuclideanDoublePoint centroidOf(final Collection<EuclideanDoublePoint> points) { final double[] centroid = new double[getPoint().length]; for (final EuclideanDoublePoint p : points) { for (int i = 0; i < centroid.length; i++) { centroid[i] += p.getPoint()[i]; } } for (int i = 0; i < centroid.length; i++) { centroid[i] /= points.size(); } return new EuclideanDoublePoint(centroid); } /** {@inheritDoc} */ public double distanceFrom(final EuclideanDoublePoint p) { return MathArrays.distance(point, p.getPoint()); } /** {@inheritDoc} */ @Override public boolean equals(final Object other) { if (!(other instanceof EuclideanDoublePoint)) { return false; } return Arrays.equals(point, ((EuclideanDoublePoint) other).point); } /** * Get the n-dimensional point in integer space. * * @return a reference (not a copy!) to the wrapped array */ public double[] getPoint() { return point; } /** {@inheritDoc} */ @Override public int hashCode() { return Arrays.hashCode(point); } /** {@inheritDoc} */ @Override public String toString() { return Arrays.toString(point); } }
SpoonLabs/astor
examples/math_5/src/main/java/org/apache/commons/math3/stat/clustering/EuclideanDoublePoint.java
Java
gpl-2.0
3,065
/* * Copyright (c) 2014, 2015, 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. */ import com.oracle.java.testlibrary.Asserts; import java.lang.management.MemoryType; import sun.hotspot.code.BlobType; /** * @test BeanTypeTest * @library /testlibrary /../../test/lib * @modules java.management * @build BeanTypeTest * @run main ClassFileInstaller sun.hotspot.WhiteBox * sun.hotspot.WhiteBox$WhiteBoxPermission * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions * -XX:+WhiteBoxAPI -XX:+SegmentedCodeCache BeanTypeTest * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions * -XX:+WhiteBoxAPI -XX:-SegmentedCodeCache BeanTypeTest * @summary verify types of code cache memory pool bean */ public class BeanTypeTest { public static void main(String args[]) { for (BlobType bt : BlobType.getAvailable()) { Asserts.assertEQ(MemoryType.NON_HEAP, bt.getMemoryPool().getType()); } } }
netroby/hotspot9
test/compiler/codecache/jmx/BeanTypeTest.java
Java
gpl-2.0
1,948
/* * Copyright 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cache.interceptor; import java.io.Serializable; import java.lang.reflect.Method; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; /** * AOP Alliance MethodInterceptor for declarative cache * management using the common Spring caching infrastructure * ({@link org.springframework.cache.Cache}). * * <p>Derives from the {@link CacheAspectSupport} class which * contains the integration with Spring's underlying caching API. * CacheInterceptor simply calls the relevant superclass methods * in the correct order. * * <p>CacheInterceptors are thread-safe. * * @author Costin Leau * @author Juergen Hoeller * @since 3.1 */ @SuppressWarnings("serial") public class CacheInterceptor extends CacheAspectSupport implements MethodInterceptor, Serializable { private static class ThrowableWrapper extends RuntimeException { private final Throwable original; ThrowableWrapper(Throwable original) { this.original = original; } } public Object invoke(final MethodInvocation invocation) throws Throwable { Method method = invocation.getMethod(); Invoker aopAllianceInvoker = new Invoker() { public Object invoke() { try { return invocation.proceed(); } catch (Throwable ex) { throw new ThrowableWrapper(ex); } } }; try { return execute(aopAllianceInvoker, invocation.getThis(), method, invocation.getArguments()); } catch (ThrowableWrapper th) { throw th.original; } } }
deathspeeder/class-guard
spring-framework-3.2.x/spring-context/src/main/java/org/springframework/cache/interceptor/CacheInterceptor.java
Java
gpl-2.0
2,142
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2006-2011 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2011 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) 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. * * OpenNMS(R) 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 OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <license@opennms.org> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ package org.opennms.protocols.jmx.connectors; import javax.management.MBeanServerConnection; /* * This interface defines the ability to handle a live connection and the ability to * close it. * * @author <A HREF="mailto:mike@opennms.org">Mike Jamison </A> * @author <A HREF="http://www.opennms.org/">OpenNMS </A> */ /** * <p>ConnectionWrapper interface.</p> * * @author ranger * @version $Id: $ */ public interface ConnectionWrapper { /** * <p>getMBeanServer</p> * * @return a {@link javax.management.MBeanServerConnection} object. */ public MBeanServerConnection getMBeanServer(); /** * <p>close</p> */ public void close(); }
tharindum/opennms_dashboard
opennms-services/src/main/java/org/opennms/protocols/jmx/connectors/ConnectionWrapper.java
Java
gpl-2.0
1,879
/** * 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 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("/BenchmarkTest01168") public class BenchmarkTest01168 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 = ""; boolean flag = true; java.util.Enumeration<String> names = request.getHeaderNames(); while (names.hasMoreElements() && flag) { String name = (String) names.nextElement(); java.util.Enumeration<String> values = request.getHeaders(name); if (values != null) { while (values.hasMoreElements() && flag) { String value = (String) values.nextElement(); if (value.equals("vector")) { param = name; flag = false; } } } } String bar = new Test().doSomething(param); try { java.util.Random numGen = java.security.SecureRandom.getInstance("SHA1PRNG"); double rand = getNextNumber(numGen); String rememberMeKey = Double.toString(rand).substring(2); // Trim off the 0. at the front. String user = "SafeDonatella"; String fullClassName = this.getClass().getName(); String testCaseNumber = fullClassName.substring(fullClassName.lastIndexOf('.')+1+"BenchmarkTest".length()); user+= testCaseNumber; String cookieName = "rememberMe" + testCaseNumber; boolean foundUser = false; javax.servlet.http.Cookie[] cookies = request.getCookies(); for (int i = 0; cookies != null && ++i < cookies.length && !foundUser;) { javax.servlet.http.Cookie cookie = cookies[i]; if (cookieName.equals(cookie.getName())) { if (cookie.getValue().equals(request.getSession().getAttribute(cookieName))) { foundUser = true; } } } if (foundUser) { response.getWriter().println("Welcome back: " + user + "<br/>"); } else { javax.servlet.http.Cookie rememberMe = new javax.servlet.http.Cookie(cookieName, rememberMeKey); rememberMe.setSecure(true); request.getSession().setAttribute(cookieName, rememberMeKey); response.addCookie(rememberMe); response.getWriter().println(user + " has been remembered with cookie: " + rememberMe.getName() + " whose value is: " + rememberMe.getValue() + "<br/>"); } } catch (java.security.NoSuchAlgorithmException e) { System.out.println("Problem executing SecureRandom.nextDouble() - TestCase"); throw new ServletException(e); } response.getWriter().println("Weak Randomness Test java.security.SecureRandom.nextDouble() executed"); } double getNextNumber(java.util.Random generator) { return generator.nextDouble(); } // end doPost private class Test { public String doSomething(String param) throws ServletException, IOException { 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; return bar; } } // end innerclass Test } // end DataflowThruInnerClass
marylinh/Benchmark
src/main/java/org/owasp/benchmark/testcode/BenchmarkTest01168.java
Java
gpl-2.0
4,339
/* Copyright (C) SYSTAP, LLC 2006-2015. All rights reserved. Contact: SYSTAP, LLC 2501 Calvert ST NW #106 Washington, DC 20008 licenses@systap.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; 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 */ /* * Created on Apr 18, 2009 */ package com.bigdata.relation.accesspath; import junit.framework.TestCase2; import com.bigdata.striterator.IChunkedIterator; /** * @author <a href="mailto:thompsonbry@users.sourceforge.net">Bryan Thompson</a> * @version $Id$ */ public class TestUnsynchronizedUnboundedChunkBuffer extends TestCase2 { /** * */ public TestUnsynchronizedUnboundedChunkBuffer() { } /** * @param arg0 */ public TestUnsynchronizedUnboundedChunkBuffer(String arg0) { super(arg0); } /** * Test empty iterator. */ public void test_emptyIterator() { final UnsynchronizedUnboundedChunkBuffer<String> buffer = new UnsynchronizedUnboundedChunkBuffer<String>( 3/* chunkCapacity */, String.class); // the iterator is initially empty. assertFalse(buffer.iterator().hasNext()); } /** * Verify that elements are flushed when an iterator is requested so * that they will be visited by the iterator. */ public void test_bufferFlushedByIterator() { final UnsynchronizedUnboundedChunkBuffer<String> buffer = new UnsynchronizedUnboundedChunkBuffer<String>( 3/* chunkCapacity */, String.class); buffer.add("a"); assertSameIterator(new String[] { "a" }, buffer.iterator()); } /** * Verify that the iterator has snapshot semantics. */ public void test_snapshotIterator() { final UnsynchronizedUnboundedChunkBuffer<String> buffer = new UnsynchronizedUnboundedChunkBuffer<String>( 3/* chunkCapacity */, String.class); buffer.add("a"); buffer.add("b"); buffer.add("c"); // visit once. assertSameIterator(new String[] { "a", "b", "c" }, buffer.iterator()); // will visit again. assertSameIterator(new String[] { "a", "b", "c" }, buffer.iterator()); } /** * Verify iterator visits chunks as placed onto the queue. */ public void test_chunkedIterator() { final UnsynchronizedUnboundedChunkBuffer<String> buffer = new UnsynchronizedUnboundedChunkBuffer<String>( 3/* chunkCapacity */, String.class); buffer.add("a"); buffer.flush(); buffer.add("b"); buffer.add("c"); // visit once. assertSameChunkedIterator(new String[][] { new String[] { "a" }, new String[] { "b", "c" } }, buffer.iterator()); } /** * Test class of chunks created by the iterator (the array class should be * taken from the first visited chunk's class). */ // @SuppressWarnings("unchecked") public void test_chunkClass() { final UnsynchronizedUnboundedChunkBuffer<String> buffer = new UnsynchronizedUnboundedChunkBuffer<String>( 3/* chunkCapacity */, String.class); buffer.add("a"); buffer.flush(); buffer.add("b"); buffer.add("c"); // visit once. assertSameChunkedIterator(new String[][] { new String[] { "a" }, new String[] { "b", "c" } }, buffer.iterator()); } /** * Verify that the iterator visits the expected chunks in the expected * order. * * @param <E> * @param chunks * @param itr */ protected <E> void assertSameChunkedIterator(final E[][] chunks, final IChunkedIterator<E> itr) { for(E[] chunk : chunks) { assertTrue(itr.hasNext()); final E[] actual = itr.nextChunk(); assertSameArray(chunk, actual); } assertFalse(itr.hasNext()); } }
smalyshev/blazegraph
bigdata/src/test/com/bigdata/relation/accesspath/TestUnsynchronizedUnboundedChunkBuffer.java
Java
gpl-2.0
4,863
/******************************************************************************* * Copyright (C) 2011 - 2015 Yoav Artzi, All rights reserved. * <p> * 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 any later version. * <p> * 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. * <p> * 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 edu.cornell.cs.nlp.spf.parser.ccg.rules.coordination; import edu.cornell.cs.nlp.spf.ccg.categories.Category; import edu.cornell.cs.nlp.spf.ccg.categories.syntax.ComplexSyntax; import edu.cornell.cs.nlp.spf.ccg.categories.syntax.Slash; import edu.cornell.cs.nlp.spf.ccg.categories.syntax.Syntax; import edu.cornell.cs.nlp.spf.parser.ccg.rules.IBinaryParseRule; import edu.cornell.cs.nlp.spf.parser.ccg.rules.ParseRuleResult; import edu.cornell.cs.nlp.spf.parser.ccg.rules.RuleName; import edu.cornell.cs.nlp.spf.parser.ccg.rules.SentenceSpan; import edu.cornell.cs.nlp.spf.parser.ccg.rules.RuleName.Direction; class C2Rule<MR> implements IBinaryParseRule<MR> { private static final RuleName RULE_NAME = RuleName .create("c2", Direction.FORWARD); private static final long serialVersionUID = 1876084168220307197L; private final ICoordinationServices<MR> services; public C2Rule(ICoordinationServices<MR> services) { this.services = services; } @Override public ParseRuleResult<MR> apply(Category<MR> left, Category<MR> right, SentenceSpan span) { if (left.getSyntax().equals(Syntax.C) && SyntaxCoordinationServices.isCoordinationOfType( right.getSyntax(), null)) { final MR semantics = services.expandCoordination(right .getSemantics()); if (semantics != null) { return new ParseRuleResult<MR>(RULE_NAME, Category.create( new ComplexSyntax(right.getSyntax(), SyntaxCoordinationServices .getCoordinationType(right .getSyntax()), Slash.BACKWARD), semantics)); } } return null; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } @SuppressWarnings("rawtypes") final C2Rule other = (C2Rule) obj; if (services == null) { if (other.services != null) { return false; } } else if (!services.equals(other.services)) { return false; } return true; } @Override public RuleName getName() { return RULE_NAME; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (RULE_NAME == null ? 0 : RULE_NAME.hashCode()); result = prime * result + (services == null ? 0 : services.hashCode()); return result; } }
ayuzhanin/cornell-spf-scala
src/main/java/edu/cornell/cs/nlp/spf/parser/ccg/rules/coordination/C2Rule.java
Java
gpl-2.0
3,328
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package java.sql; public class SQLTransactionRollbackException extends SQLTransientException { private static final long serialVersionUID = 5246680841170837229L; /** * Creates an SQLTransactionRollbackException object. The Reason string is * set to null, the SQLState string is set to null and the Error Code is set * to 0. */ public SQLTransactionRollbackException() { super(); } /** * Creates an SQLTransactionRollbackException object. The Reason string is * set to the given reason string, the SQLState string is set to null and * the Error Code is set to 0. * * @param reason * the string to use as the Reason string */ public SQLTransactionRollbackException(String reason) { super(reason, null, 0); } /** * Creates an SQLTransactionRollbackException object. The Reason string is * set to the given reason string, the SQLState string is set to the given * SQLState string and the Error Code is set to 0. * * @param reason * the string to use as the Reason string * @param sqlState * the string to use as the SQLState string */ public SQLTransactionRollbackException(String reason, String sqlState) { super(reason, sqlState, 0); } /** * Creates an SQLTransactionRollbackException object. The Reason string is * set to the given reason string, the SQLState string is set to the given * SQLState string and the Error Code is set to the given error code value. * * @param reason * the string to use as the Reason string * @param sqlState * the string to use as the SQLState string * @param vendorCode * the integer value for the error code */ public SQLTransactionRollbackException(String reason, String sqlState, int vendorCode) { super(reason, sqlState, vendorCode); } /** * Creates an SQLTransactionRollbackException object. The Reason string is * set to the null if cause == null or cause.toString() if cause!=null,and * the cause Throwable object is set to the given cause Throwable object. * * @param cause * the Throwable object for the underlying reason this * SQLException */ public SQLTransactionRollbackException(Throwable cause) { super(cause); } /** * Creates an SQLTransactionRollbackException object. The Reason string is * set to the given and the cause Throwable object is set to the given cause * Throwable object. * * @param reason * the string to use as the Reason string * @param cause * the Throwable object for the underlying reason this * SQLException */ public SQLTransactionRollbackException(String reason, Throwable cause) { super(reason, cause); } /** * Creates an SQLTransactionRollbackException object. The Reason string is * set to the given reason string, the SQLState string is set to the given * SQLState string and the cause Throwable object is set to the given cause * Throwable object. * * @param reason * the string to use as the Reason string * @param sqlState * the string to use as the SQLState string * @param cause * the Throwable object for the underlying reason this * SQLException */ public SQLTransactionRollbackException(String reason, String sqlState, Throwable cause) { super(reason, sqlState, cause); } /** * Creates an SQLTransactionRollbackException object. The Reason string is * set to the given reason string, the SQLState string is set to the given * SQLState string , the Error Code is set to the given error code value, * and the cause Throwable object is set to the given cause Throwable * object. * * @param reason * the string to use as the Reason string * @param sqlState * the string to use as the SQLState string * @param vendorCode * the integer value for the error code * @param cause * the Throwable object for the underlying reason this * SQLException */ public SQLTransactionRollbackException(String reason, String sqlState, int vendorCode, Throwable cause) { super(reason, sqlState, vendorCode, cause); } }
skyHALud/codenameone
Ports/iOSPort/xmlvm/apache-harmony-6.0-src-r991881/classlib/modules/sql/src/main/java/java/sql/SQLTransactionRollbackException.java
Java
gpl-2.0
5,553
/* * Copyright (c) 1998-2012 Caucho Technology -- all rights reserved * * This file is part of Resin(R) Open Source * * Each copy or derived work must preserve the copyright notice and this * notice unmodified. * * Resin Open Source 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. * * Resin Open Source 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, or any warranty * of NON-INFRINGEMENT. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with Resin Open Source; if not, write to the * * Free Software Foundation, Inc. * 59 Temple Place, Suite 330 * Boston, MA 02111-1307 USA * * @author Scott Ferguson */ package com.caucho.quercus.expr; import java.io.IOException; import java.util.ArrayList; import com.caucho.quercus.Location; import com.caucho.quercus.env.Env; import com.caucho.quercus.env.MethodIntern; import com.caucho.quercus.env.NullValue; import com.caucho.quercus.env.StringValue; import com.caucho.quercus.env.QuercusClass; import com.caucho.quercus.env.Value; import com.caucho.quercus.env.Var; import com.caucho.quercus.parser.QuercusParser; import com.caucho.util.L10N; /** * Represents a PHP static field reference. */ public class ClassVirtualFieldExpr extends AbstractVarExpr { private static final L10N L = new L10N(ClassVirtualFieldExpr.class); protected final StringValue _varName; public ClassVirtualFieldExpr(String varName) { _varName = MethodIntern.intern(varName); } // // function call creation // /** * Creates a function call expression */ @Override public Expr createCall(QuercusParser parser, Location location, ArrayList<Expr> args) throws IOException { ExprFactory factory = parser.getExprFactory(); Expr var = parser.createVar(_varName.toString()); return factory.createClassVirtualMethodCall(location, var, args); } /** * Evaluates the expression. * * @param env the calling environment. * * @return the expression value. */ @Override public Value eval(Env env) { Value qThis = env.getThis(); QuercusClass qClass = qThis != null ? qThis.getQuercusClass() : null; if (qClass == null) { env.error(L.l("No calling class found for '{0}'", this)); return NullValue.NULL; } return qClass.getStaticFieldValue(env, _varName); } /** * Evaluates the expression. * * @param env the calling environment. * * @return the expression value. */ @Override public Var evalVar(Env env) { Value qThis = env.getThis(); QuercusClass qClass = qThis != null ? qThis.getQuercusClass() : null; if (qClass == null) { env.error(L.l("No calling class found for '{0}'", this)); return NullValue.NULL.toVar(); } return qClass.getStaticFieldVar(env, _varName); } /** * Evaluates the expression. * * @param env the calling environment. * * @return the expression value. */ @Override public Value evalAssignRef(Env env, Value value) { Value qThis = env.getThis(); QuercusClass qClass = qThis != null ? qThis.getQuercusClass() : null; if (qClass == null) { env.error(L.l("No calling class found for '{0}'", this)); return NullValue.NULL.toVar(); } return qClass.setStaticFieldRef(env, _varName, value); } /** * Evaluates the expression. * * @param env the calling environment. * * @return the expression value. */ public void evalUnset(Env env) { env.error(getLocation(), L.l("{0}::${1}: Cannot unset static variables.", env.getCallingClass().getName(), _varName)); } public String toString() { return "static::$" + _varName; } }
dwango/quercus
src/main/java/com/caucho/quercus/expr/ClassVirtualFieldExpr.java
Java
gpl-2.0
4,206
package com.amaze.filemanager.filesystem; import android.content.Context; import android.os.AsyncTask; import android.os.Build; import android.support.annotation.NonNull; import android.support.v4.provider.DocumentFile; import com.amaze.filemanager.exceptions.RootNotPermittedException; import com.amaze.filemanager.utils.DataUtils; import com.amaze.filemanager.utils.cloud.CloudUtil; import com.amaze.filemanager.utils.Logger; import com.amaze.filemanager.utils.MainActivityHelper; import com.amaze.filemanager.utils.OTGUtil; import com.amaze.filemanager.utils.OpenMode; import com.amaze.filemanager.utils.RootUtils; import com.cloudrail.si.interfaces.CloudStorage; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.net.MalformedURLException; import jcifs.smb.SmbException; import jcifs.smb.SmbFile; /** * Created by arpitkh996 on 13-01-2016, modified by Emmanuel Messulam<emmanuelbendavid@gmail.com> */ public class Operations { // reserved characters by OS, shall not be allowed in file names private static final String FOREWARD_SLASH = "/"; private static final String BACKWARD_SLASH = "\\"; private static final String COLON = ":"; private static final String ASTERISK = "*"; private static final String QUESTION_MARK = "?"; private static final String QUOTE = "\""; private static final String GREATER_THAN = ">"; private static final String LESS_THAN = "<"; private static final String FAT = "FAT"; private DataUtils dataUtils = DataUtils.getInstance(); public interface ErrorCallBack { /** * Callback fired when file being created in process already exists * * @param file */ void exists(HFile file); /** * Callback fired when creating new file/directory and required storage access framework permission * to access SD Card is not available * * @param file */ void launchSAF(HFile file); /** * Callback fired when renaming file and required storage access framework permission to access * SD Card is not available * * @param file * @param file1 */ void launchSAF(HFile file, HFile file1); /** * Callback fired when we're done processing the operation * * @param hFile * @param b defines whether operation was successful */ void done(HFile hFile, boolean b); /** * Callback fired when an invalid file name is found. * * @param file */ void invalidName(HFile file); } public static void mkdir(@NonNull final HFile file, final Context context, final boolean rootMode, @NonNull final ErrorCallBack errorCallBack) { new AsyncTask<Void, Void, Void>() { private DataUtils dataUtils = DataUtils.getInstance(); @Override protected Void doInBackground(Void... params) { // checking whether filename is valid or a recursive call possible if (MainActivityHelper.isNewDirectoryRecursive(file) || !Operations.isFileNameValid(file.getName(context))) { errorCallBack.invalidName(file); return null; } if (file.exists()) { errorCallBack.exists(file); return null; } if (file.isSmb()) { try { file.getSmbFile(2000).mkdirs(); } catch (SmbException e) { Logger.log(e, file.getPath(), context); errorCallBack.done(file, false); return null; } errorCallBack.done(file, file.exists()); return null; } else if (file.isOtgFile()) { // first check whether new directory already exists DocumentFile directoryToCreate = OTGUtil.getDocumentFile(file.getPath(), context, false); if (directoryToCreate != null) errorCallBack.exists(file); DocumentFile parentDirectory = OTGUtil.getDocumentFile(file.getParent(), context, false); if (parentDirectory.isDirectory()) { parentDirectory.createDirectory(file.getName(context)); errorCallBack.done(file, true); } else errorCallBack.done(file, false); return null; } else if (file.isDropBoxFile()) { CloudStorage cloudStorageDropbox = dataUtils.getAccount(OpenMode.DROPBOX); try { cloudStorageDropbox.createFolder(CloudUtil.stripPath(OpenMode.DROPBOX, file.getPath())); errorCallBack.done(file, true); } catch (Exception e) { e.printStackTrace(); errorCallBack.done(file, false); } } else if (file.isBoxFile()) { CloudStorage cloudStorageBox = dataUtils.getAccount(OpenMode.BOX); try { cloudStorageBox.createFolder(CloudUtil.stripPath(OpenMode.BOX, file.getPath())); errorCallBack.done(file, true); } catch (Exception e) { e.printStackTrace(); errorCallBack.done(file, false); } } else if (file.isOneDriveFile()) { CloudStorage cloudStorageOneDrive = dataUtils.getAccount(OpenMode.ONEDRIVE); try { cloudStorageOneDrive.createFolder(CloudUtil.stripPath(OpenMode.ONEDRIVE, file.getPath())); errorCallBack.done(file, true); } catch (Exception e) { e.printStackTrace(); errorCallBack.done(file, false); } } else if (file.isGoogleDriveFile()) { CloudStorage cloudStorageGdrive = dataUtils.getAccount(OpenMode.GDRIVE); try { cloudStorageGdrive.createFolder(CloudUtil.stripPath(OpenMode.GDRIVE, file.getPath())); errorCallBack.done(file, true); } catch (Exception e) { e.printStackTrace(); errorCallBack.done(file, false); } } else { if (file.isLocal() || file.isRoot()) { int mode = checkFolder(new File(file.getParent()), context); if (mode == 2) { errorCallBack.launchSAF(file); return null; } if (mode == 1 || mode == 0) FileUtil.mkdir(file.getFile(), context); if (!file.exists() && rootMode) { file.setMode(OpenMode.ROOT); if (file.exists()) errorCallBack.exists(file); try { RootUtils.mkDir(file.getParent(context), file.getName(context)); } catch (RootNotPermittedException e) { Logger.log(e, file.getPath(), context); } errorCallBack.done(file, file.exists()); return null; } errorCallBack.done(file, file.exists()); return null; } errorCallBack.done(file, file.exists()); } return null; } }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } public static void mkfile(@NonNull final HFile file, final Context context, final boolean rootMode, @NonNull final ErrorCallBack errorCallBack) { new AsyncTask<Void, Void, Void>() { private DataUtils dataUtils = DataUtils.getInstance(); @Override protected Void doInBackground(Void... params) { // check whether filename is valid or not if (!Operations.isFileNameValid(file.getName(context))) { errorCallBack.invalidName(file); return null; } if (file.exists()) { errorCallBack.exists(file); return null; } if (file.isSmb()) { try { file.getSmbFile(2000).createNewFile(); } catch (SmbException e) { Logger.log(e, file.getPath(), context); errorCallBack.done(file, false); return null; } errorCallBack.done(file, file.exists()); return null; } else if (file.isDropBoxFile()) { CloudStorage cloudStorageDropbox = dataUtils.getAccount(OpenMode.DROPBOX); try { byte[] tempBytes = new byte[0]; ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(tempBytes); cloudStorageDropbox.upload(CloudUtil.stripPath(OpenMode.DROPBOX, file.getPath()), byteArrayInputStream, 0l, true); errorCallBack.done(file, true); } catch (Exception e) { e.printStackTrace(); errorCallBack.done(file, false); } } else if (file.isBoxFile()) { CloudStorage cloudStorageBox = dataUtils.getAccount(OpenMode.BOX); try { byte[] tempBytes = new byte[0]; ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(tempBytes); cloudStorageBox.upload(CloudUtil.stripPath(OpenMode.BOX, file.getPath()), byteArrayInputStream, 0l, true); errorCallBack.done(file, true); } catch (Exception e) { e.printStackTrace(); errorCallBack.done(file, false); } } else if (file.isOneDriveFile()) { CloudStorage cloudStorageOneDrive = dataUtils.getAccount(OpenMode.ONEDRIVE); try { byte[] tempBytes = new byte[0]; ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(tempBytes); cloudStorageOneDrive.upload(CloudUtil.stripPath(OpenMode.ONEDRIVE, file.getPath()), byteArrayInputStream, 0l, true); errorCallBack.done(file, true); } catch (Exception e) { e.printStackTrace(); errorCallBack.done(file, false); } } else if (file.isGoogleDriveFile()) { CloudStorage cloudStorageGdrive = dataUtils.getAccount(OpenMode.GDRIVE); try { byte[] tempBytes = new byte[0]; ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(tempBytes); cloudStorageGdrive.upload(CloudUtil.stripPath(OpenMode.GDRIVE, file.getPath()), byteArrayInputStream, 0l, true); errorCallBack.done(file, true); } catch (Exception e) { e.printStackTrace(); errorCallBack.done(file, false); } } else if (file.isOtgFile()) { // first check whether new file already exists DocumentFile fileToCreate = OTGUtil.getDocumentFile(file.getPath(), context, false); if (fileToCreate != null) errorCallBack.exists(file); DocumentFile parentDirectory = OTGUtil.getDocumentFile(file.getParent(), context, false); if (parentDirectory.isDirectory()) { parentDirectory.createFile(file.getName(context).substring(file.getName().lastIndexOf(".")), file.getName(context)); errorCallBack.done(file, true); } else errorCallBack.done(file, false); return null; } else { if (file.isLocal() || file.isRoot()) { int mode = checkFolder(new File(file.getParent()), context); if (mode == 2) { errorCallBack.launchSAF(file); return null; } if (mode == 1 || mode == 0) try { FileUtil.mkfile(file.getFile(), context); } catch (IOException e) { } if (!file.exists() && rootMode) { file.setMode(OpenMode.ROOT); if (file.exists()) errorCallBack.exists(file); try { RootUtils.mkFile(file.getPath()); } catch (RootNotPermittedException e) { Logger.log(e, file.getPath(), context); } errorCallBack.done(file, file.exists()); return null; } errorCallBack.done(file, file.exists()); return null; } errorCallBack.done(file, file.exists()); } return null; } }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } public static void rename(final HFile oldFile, final HFile newFile, final boolean rootMode, final Context context, final ErrorCallBack errorCallBack) { new AsyncTask<Void, Void, Void>() { private DataUtils dataUtils = DataUtils.getInstance(); @Override protected Void doInBackground(Void... params) { // check whether file names for new file are valid or recursion occurs if (MainActivityHelper.isNewDirectoryRecursive(newFile) || !Operations.isFileNameValid(newFile.getName(context))) { errorCallBack.invalidName(newFile); return null; } if (newFile.exists()) { errorCallBack.exists(newFile); return null; } if (oldFile.isSmb()) { try { SmbFile smbFile = new SmbFile(oldFile.getPath()); SmbFile smbFile1 = new SmbFile(newFile.getPath()); if (smbFile1.exists()) { errorCallBack.exists(newFile); return null; } smbFile.renameTo(smbFile1); if (!smbFile.exists() && smbFile1.exists()) errorCallBack.done(newFile, true); } catch (MalformedURLException e) { e.printStackTrace(); } catch (SmbException e) { e.printStackTrace(); } return null; } else if (oldFile.isDropBoxFile()) { CloudStorage cloudStorageDropbox = dataUtils.getAccount(OpenMode.DROPBOX); try { cloudStorageDropbox.move(CloudUtil.stripPath(OpenMode.DROPBOX, oldFile.getPath()), CloudUtil.stripPath(OpenMode.DROPBOX, newFile.getPath())); errorCallBack.done(newFile, true); } catch (Exception e) { e.printStackTrace(); errorCallBack.done(newFile, false); } } else if (oldFile.isBoxFile()) { CloudStorage cloudStorageBox = dataUtils.getAccount(OpenMode.BOX); try { cloudStorageBox.move(CloudUtil.stripPath(OpenMode.BOX, oldFile.getPath()), CloudUtil.stripPath(OpenMode.BOX, newFile.getPath())); errorCallBack.done(newFile, true); } catch (Exception e) { e.printStackTrace(); errorCallBack.done(newFile, false); } } else if (oldFile.isOneDriveFile()) { CloudStorage cloudStorageOneDrive = dataUtils.getAccount(OpenMode.ONEDRIVE); try { cloudStorageOneDrive.move(CloudUtil.stripPath(OpenMode.ONEDRIVE, oldFile.getPath()), CloudUtil.stripPath(OpenMode.ONEDRIVE, newFile.getPath())); errorCallBack.done(newFile, true); } catch (Exception e) { e.printStackTrace(); errorCallBack.done(newFile, false); } } else if (oldFile.isGoogleDriveFile()) { CloudStorage cloudStorageGdrive = dataUtils.getAccount(OpenMode.GDRIVE); try { cloudStorageGdrive.move(CloudUtil.stripPath(OpenMode.GDRIVE, oldFile.getPath()), CloudUtil.stripPath(OpenMode.GDRIVE, newFile.getPath())); errorCallBack.done(newFile, true); } catch (Exception e) { e.printStackTrace(); errorCallBack.done(newFile, false); } } else if (oldFile.isOtgFile()) { DocumentFile oldDocumentFile = OTGUtil.getDocumentFile(oldFile.getPath(), context, false); DocumentFile newDocumentFile = OTGUtil.getDocumentFile(newFile.getPath(), context, false); if (newDocumentFile != null) { errorCallBack.exists(newFile); return null; } errorCallBack.done(newFile, oldDocumentFile.renameTo(newFile.getName(context))); return null; } else { File file = new File(oldFile.getPath()); File file1 = new File(newFile.getPath()); switch (oldFile.getMode()) { case FILE: int mode = checkFolder(file.getParentFile(), context); if (mode == 2) { errorCallBack.launchSAF(oldFile, newFile); } else if (mode == 1 || mode == 0) { try { FileUtil.renameFolder(file, file1, context); } catch (RootNotPermittedException e) { e.printStackTrace(); } boolean a = !file.exists() && file1.exists(); if (!a && rootMode) { try { RootUtils.rename(file.getPath(), file1.getPath()); } catch (Exception e) { Logger.log(e, oldFile.getPath() + "\n" + newFile.getPath(), context); } oldFile.setMode(OpenMode.ROOT); newFile.setMode(OpenMode.ROOT); a = !file.exists() && file1.exists(); } errorCallBack.done(newFile, a); return null; } break; case ROOT: try { RootUtils.rename(file.getPath(), file1.getPath()); } catch (Exception e) { Logger.log(e, oldFile.getPath() + "\n" + newFile.getPath(), context); } newFile.setMode(OpenMode.ROOT); errorCallBack.done(newFile, true); break; } } return null; } }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } private static int checkFolder(final File folder, Context context) { boolean lol = Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP; if (lol) { boolean ext = FileUtil.isOnExtSdCard(folder, context); if (ext) { if (!folder.exists() || !folder.isDirectory()) { return 0; } // On Android 5, trigger storage access framework. if (!FileUtil.isWritableNormalOrSaf(folder, context)) { return 2; } return 1; } } else if (Build.VERSION.SDK_INT == 19) { // Assume that Kitkat workaround works if (FileUtil.isOnExtSdCard(folder, context)) return 1; } // file not on external sd card if (FileUtil.isWritable(new File(folder, "DummyFile"))) { return 1; } else { return 0; } } /** * Well, we wouldn't want to copy when the target is inside the source * otherwise it'll end into a loop * * @param sourceFile * @param targetFile * @return true when copy loop is possible */ public static boolean isCopyLoopPossible(BaseFile sourceFile, HFile targetFile) { return targetFile.getPath().contains(sourceFile.getPath()); } /** * Validates file name * special reserved characters shall not be allowed in the file names on FAT filesystems * * @param fileName the filename, not the full path! * @return boolean if the file name is valid or invalid */ public static boolean isFileNameValid(String fileName) { //String fileName = builder.substring(builder.lastIndexOf("/")+1, builder.length()); // TODO: check file name validation only for FAT filesystems return !(fileName.contains(ASTERISK) || fileName.contains(BACKWARD_SLASH) || fileName.contains(COLON) || fileName.contains(FOREWARD_SLASH) || fileName.contains(GREATER_THAN) || fileName.contains(LESS_THAN) || fileName.contains(QUESTION_MARK) || fileName.contains(QUOTE)); } private static boolean isFileSystemFAT(String mountPoint) { String[] args = new String[]{"/bin/bash", "-c", "df -DO_NOT_REPLACE | awk '{print $1,$2,$NF}' | grep \"^" + mountPoint + "\""}; try { Process proc = new ProcessBuilder(args).start(); OutputStream outputStream = proc.getOutputStream(); String buffer = null; outputStream.write(buffer.getBytes()); return buffer != null && buffer.contains(FAT); } catch (IOException e) { e.printStackTrace(); // process interrupted, returning true, as a word of cation return true; } } }
martincz/AmazeFileManager
src/main/java/com/amaze/filemanager/filesystem/Operations.java
Java
gpl-3.0
24,347
package org.ovirt.engine.core.bll.scheduling.commands; import java.util.HashMap; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.ovirt.engine.core.common.config.ConfigValues; import org.ovirt.engine.core.common.scheduling.ClusterPolicy; import org.ovirt.engine.core.common.scheduling.parameters.ClusterPolicyCRUDParameters; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.core.utils.MockConfigRule; public class ClusterPolicyCRUDCommandTest { @Rule public MockConfigRule mockConfigRule = new MockConfigRule((MockConfigRule.mockConfig(ConfigValues.EnableVdsLoadBalancing, false)), (MockConfigRule.mockConfig(ConfigValues.EnableVdsHaReservation, false))); @Test public void testCheckAddEditValidations() { Guid clusterPolicyId = new Guid("e754440b-76a6-4099-8235-4565ab4b5521"); ClusterPolicy clusterPolicy = new ClusterPolicy(); clusterPolicy.setId(clusterPolicyId); ClusterPolicyCRUDCommand command = new ClusterPolicyCRUDCommand(new ClusterPolicyCRUDParameters(clusterPolicyId, clusterPolicy)) { @Override protected void executeCommand() { } }; Assert.assertTrue(command.checkAddEditValidations()); } @Test public void testCheckAddEditValidationsFailOnParameters() { Guid clusterPolicyId = new Guid("e754440b-76a6-4099-8235-4565ab4b5521"); ClusterPolicy clusterPolicy = new ClusterPolicy(); clusterPolicy.setId(clusterPolicyId); HashMap<String, String> parameterMap = new HashMap<String, String>(); parameterMap.put("fail?", "sure, fail!"); clusterPolicy.setParameterMap(parameterMap); ClusterPolicyCRUDCommand command = new ClusterPolicyCRUDCommand(new ClusterPolicyCRUDParameters(clusterPolicyId, clusterPolicy)) { @Override protected void executeCommand() { } }; Assert.assertFalse(command.checkAddEditValidations()); } }
jtux270/translate
ovirt/backend/manager/modules/bll/src/test/java/org/ovirt/engine/core/bll/scheduling/commands/ClusterPolicyCRUDCommandTest.java
Java
gpl-3.0
2,187
package com.xxl.job.admin.core.route.strategy; import com.xxl.job.admin.core.route.ExecutorRouter; import com.xxl.job.core.biz.model.ReturnT; import com.xxl.job.core.biz.model.TriggerParam; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; /** * 单个JOB对应的每个执行器,使用频率最低的优先被选举 * a(*)、LFU(Least Frequently Used):最不经常使用,频率/次数 * b、LRU(Least Recently Used):最近最久未使用,时间 * * Created by xuxueli on 17/3/10. */ public class ExecutorRouteLFU extends ExecutorRouter { private static ConcurrentMap<Integer, HashMap<String, Integer>> jobLfuMap = new ConcurrentHashMap<Integer, HashMap<String, Integer>>(); private static long CACHE_VALID_TIME = 0; public String route(int jobId, List<String> addressList) { // cache clear if (System.currentTimeMillis() > CACHE_VALID_TIME) { jobLfuMap.clear(); CACHE_VALID_TIME = System.currentTimeMillis() + 1000*60*60*24; } // lfu item init HashMap<String, Integer> lfuItemMap = jobLfuMap.get(jobId); // Key排序可以用TreeMap+构造入参Compare;Value排序暂时只能通过ArrayList; if (lfuItemMap == null) { lfuItemMap = new HashMap<String, Integer>(); jobLfuMap.putIfAbsent(jobId, lfuItemMap); // 避免重复覆盖 } // put new for (String address: addressList) { if (!lfuItemMap.containsKey(address) || lfuItemMap.get(address) >1000000 ) { lfuItemMap.put(address, new Random().nextInt(addressList.size())); // 初始化时主动Random一次,缓解首次压力 } } // remove old List<String> delKeys = new ArrayList<>(); for (String existKey: lfuItemMap.keySet()) { if (!addressList.contains(existKey)) { delKeys.add(existKey); } } if (delKeys.size() > 0) { for (String delKey: delKeys) { lfuItemMap.remove(delKey); } } // load least userd count address List<Map.Entry<String, Integer>> lfuItemList = new ArrayList<Map.Entry<String, Integer>>(lfuItemMap.entrySet()); Collections.sort(lfuItemList, new Comparator<Map.Entry<String, Integer>>() { @Override public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) { return o1.getValue().compareTo(o2.getValue()); } }); Map.Entry<String, Integer> addressItem = lfuItemList.get(0); String minAddress = addressItem.getKey(); addressItem.setValue(addressItem.getValue() + 1); return addressItem.getKey(); } @Override public ReturnT<String> route(TriggerParam triggerParam, List<String> addressList) { String address = route(triggerParam.getJobId(), addressList); return new ReturnT<String>(address); } }
xuxueli/xxl-job
xxl-job-admin/src/main/java/com/xxl/job/admin/core/route/strategy/ExecutorRouteLFU.java
Java
gpl-3.0
3,053
package com.bioxx.tfc2.gui; import java.awt.Rectangle; import java.util.Collection; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.inventory.GuiContainerCreative; import net.minecraft.client.gui.inventory.GuiInventory; import net.minecraft.client.renderer.InventoryEffectRenderer; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.Slot; import net.minecraft.stats.AchievementList; import net.minecraft.util.ResourceLocation; import org.lwjgl.opengl.GL11; import com.bioxx.tfc2.Core; import com.bioxx.tfc2.Reference; import com.bioxx.tfc2.core.PlayerInventory; public class GuiInventoryTFC extends InventoryEffectRenderer { private float xSizeLow; private float ySizeLow; private boolean hasEffect; protected static final ResourceLocation UPPER_TEXTURE = new ResourceLocation(Reference.ModID+":textures/gui/inventory.png"); protected static final ResourceLocation UPPER_TEXTURE_2X2 = new ResourceLocation(Reference.ModID+":textures/gui/gui_inventory2x2.png"); protected static final ResourceLocation EFFECTS_TEXTURE = new ResourceLocation(Reference.ModID+":textures/gui/inv_effects.png"); protected EntityPlayer player; protected Slot activeSlot; public GuiInventoryTFC(EntityPlayer player) { super(player.inventoryContainer); this.allowUserInput = true; player.addStat(AchievementList.OPEN_INVENTORY, 1); xSize = 176; ySize = 102 + PlayerInventory.invYSize; this.player = player; } @Override protected void drawGuiContainerBackgroundLayer(float par1, int par2, int par3) { GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); if(player.getEntityData().hasKey("craftingTable")) Core.bindTexture(UPPER_TEXTURE); else Core.bindTexture(UPPER_TEXTURE_2X2); int k = this.guiLeft; int l = this.guiTop; this.drawTexturedModalRect(k, l, 0, 0, this.xSize, 102); //Draw the player avatar GuiInventory.drawEntityOnScreen(k + 51, l + 75, 30, k + 51 - this.xSizeLow, l + 75 - 50 - this.ySizeLow, this.mc.player); PlayerInventory.drawInventory(this, width, height, ySize - PlayerInventory.invYSize); GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); } @Override protected void drawGuiContainerForegroundLayer(int par1, int par2) { //this.fontRenderer.drawString(I18n.format("container.crafting", new Object[0]), 86, 7, 4210752); } @Override /** * Called from the main game loop to update the screen. */ public void updateScreen() { if (this.mc.playerController.isInCreativeMode()) this.mc.displayGuiScreen(new GuiContainerCreative(player)); } @Override public void initGui() { super.buttonList.clear(); if (this.mc.playerController.isInCreativeMode()) { this.mc.displayGuiScreen(new GuiContainerCreative(this.mc.player)); } else super.initGui(); if (!this.mc.player.getActivePotionEffects().isEmpty()) { //this.guiLeft = 160 + (this.width - this.xSize - 200) / 2; this.guiLeft = (this.width - this.xSize) / 2; this.hasEffect = true; } buttonList.clear(); buttonList.add(new GuiInventoryButton(0, new Rectangle(guiLeft+176, guiTop + 3, 25, 20), new Rectangle(0, 103, 25, 20), Core.translate("gui.Inventory.Inventory"), new Rectangle(1,223,32,32))); buttonList.add(new GuiInventoryButton(1, new Rectangle(guiLeft+176, guiTop + 22, 25, 20), new Rectangle(0, 103, 25, 20), Core.translate("gui.Inventory.Skills"), new Rectangle(100,223,32,32))); buttonList.add(new GuiInventoryButton(2, new Rectangle(guiLeft+176, guiTop + 41, 25, 20), new Rectangle(0, 103, 25, 20), Core.translate("gui.Calendar.Calendar"), new Rectangle(34,223,32,32))); buttonList.add(new GuiInventoryButton(3, new Rectangle(guiLeft+176, guiTop + 60, 25, 20), new Rectangle(0, 103, 25, 20), Core.translate("gui.Inventory.Health"), new Rectangle(67,223,32,32))); } @Override protected void actionPerformed(GuiButton guibutton) { //Removed during port if (guibutton.id == 1) Minecraft.getMinecraft().displayGuiScreen(new GuiSkills(player)); /*else if (guibutton.id == 2) Minecraft.getMinecraft().displayGuiScreen(new GuiCalendar(player));*/ else if (guibutton.id == 3) Minecraft.getMinecraft().displayGuiScreen(new GuiHealth(player)); } @Override public void drawScreen(int par1, int par2, float par3) { GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); super.drawScreen(par1, par2, par3); this.xSizeLow = par1; this.ySizeLow = par2; if(hasEffect) displayDebuffEffects(); //removed during port /*for (int j1 = 0; j1 < this.inventorySlots.inventorySlots.size(); ++j1) { Slot slot = (Slot)this.inventorySlots.inventorySlots.get(j1); if (this.isMouseOverSlot(slot, par1, par2) && slot.func_111238_b()) this.activeSlot = slot; }*/ } protected boolean isMouseOverSlot(Slot par1Slot, int par2, int par3) { return this.isPointInRegion(par1Slot.xPos, par1Slot.yPos, 16, 16, par2, par3); } /** * Displays debuff/potion effects that are currently being applied to the player */ private void displayDebuffEffects() { int var1 = this.guiLeft - 124; int var2 = this.guiTop; Collection var4 = this.mc.player.getActivePotionEffects(); //Remvoed during port /*if (!var4.isEmpty()) { GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); GL11.glDisable(GL11.GL_LIGHTING); int var6 = 33; if (var4.size() > 5) var6 = 132 / (var4.size() - 1); for (Iterator var7 = this.mc.player.getActivePotionEffects().iterator(); var7.hasNext(); var2 += var6) { PotionEffect var8 = (PotionEffect)var7.next(); Potion var9 = Potion.potionTypes[var8.getPotionID()] instanceof TFCPotion ? ((TFCPotion) Potion.potionTypes[var8.getPotionID()]) : Potion.potionTypes[var8.getPotionID()]; GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); TFC_Core.bindTexture(EFFECTS_TEXTURE); this.drawTexturedModalRect(var1, var2, 0, 166, 140, 32); if (var9.hasStatusIcon()) { int var10 = var9.getStatusIconIndex(); this.drawTexturedModalRect(var1 + 6, var2 + 7, 0 + var10 % 8 * 18, 198 + var10 / 8 * 18, 18, 18); } String var12 = Core.translate(var9.getName()); if (var8.getAmplifier() == 1) var12 = var12 + " II"; else if (var8.getAmplifier() == 2) var12 = var12 + " III"; else if (var8.getAmplifier() == 3) var12 = var12 + " IV"; this.fontRenderer.drawStringWithShadow(var12, var1 + 10 + 18, var2 + 6, 16777215); String var11 = Potion.getDurationString(var8); this.fontRenderer.drawStringWithShadow(var11, var1 + 10 + 18, var2 + 6 + 10, 8355711); } }*/ } private long spamTimer; @Override protected boolean checkHotbarKeys(int keycode) { /*if(this.activeSlot != null && this.activeSlot.slotNumber == 0 && this.activeSlot.getHasStack() && this.activeSlot.getStack().getItem() instanceof IFood) return false;*/ return super.checkHotbarKeys(keycode); } private int getEmptyCraftSlot() { if(this.inventorySlots.getSlot(4).getStack() == null) return 4; if(this.inventorySlots.getSlot(1).getStack() == null) return 1; if(this.inventorySlots.getSlot(2).getStack() == null) return 2; if(this.inventorySlots.getSlot(3).getStack() == null) return 3; if(player.getEntityData().hasKey("craftingTable")) { if(this.inventorySlots.getSlot(45).getStack() == null) return 45; if(this.inventorySlots.getSlot(46).getStack() == null) return 46; if(this.inventorySlots.getSlot(47).getStack() == null) return 47; if(this.inventorySlots.getSlot(48).getStack() == null) return 48; if(this.inventorySlots.getSlot(49).getStack() == null) return 49; } return -1; } }
CHeuberger/TFC2
src/Common/com/bioxx/tfc2/gui/GuiInventoryTFC.java
Java
gpl-3.0
7,667
/* * GPXParser.java * * Copyright (c) 2012, AlternativeVision. All rights reserved. * * 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 */ package org.alternativevision.gpx; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.alternativevision.gpx.beans.GPX; import org.alternativevision.gpx.beans.Route; import org.alternativevision.gpx.beans.Track; import org.alternativevision.gpx.beans.Waypoint; import org.alternativevision.gpx.extensions.IExtensionParser; import org.alternativevision.gpx.types.FixType; import org.apache.commons.io.FileUtils; import org.apache.log4j.Logger; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * <p>This class defines methods for parsing and writing gpx files.</p> * <br> * Usage for parsing a gpx file into a {@link GPX} object:<br> * <code> * GPXParser p = new GPXParser();<br> * FileInputStream in = new FileInputStream("inFile.gpx");<br> * GPX gpx = p.parseGPX(in);<br> * </code> * <br> * Usage for writing a {@link GPX} object to a file:<br> * <code> * GPXParser p = new GPXParser();<br> * FileOutputStream out = new FileOutputStream("outFile.gpx");<br> * p.writeGPX(gpx, out);<br> * out.close();<br> * </code> */ public class GPXParser { private ArrayList<IExtensionParser> extensionParsers = new ArrayList<IExtensionParser>(); private Logger logger = Logger.getLogger(this.getClass().getName()); private DocumentBuilderFactory docFactory= DocumentBuilderFactory.newInstance(); private TransformerFactory tFactory = TransformerFactory.newInstance(); private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'kk:mm:ss"); private SimpleDateFormat sdfZ = new SimpleDateFormat("yyyy-MM-dd'T'kk:mm:ss'Z'"); /** * Adds a new extension parser to be used when parsing a gpx steam * * @param parser an instance of a {@link IExtensionParser} implementation */ public void addExtensionParser(IExtensionParser parser) { extensionParsers.add(parser); } /** * Removes an extension parser previously added * * @param parser an instance of a {@link IExtensionParser} implementation */ public void removeExtensionParser(IExtensionParser parser) { extensionParsers.remove(parser); } public GPX parseGPX(File gpxFile) throws IOException, ParserConfigurationException, SAXException, IOException { InputStream in = FileUtils.openInputStream(gpxFile); GPX gpx = parseGPX(in); in.close(); return gpx; } /** * Parses a stream containing GPX data * * @param in the input stream * @return {@link GPX} object containing parsed data, or null if no gpx data was found in the seream * @throws ParserConfigurationException * @throws SAXException * @throws IOException */ public GPX parseGPX(InputStream in) throws ParserConfigurationException, SAXException, IOException { DocumentBuilder builder = docFactory.newDocumentBuilder(); Document doc = builder.parse(in); Node firstChild = doc.getFirstChild(); if( firstChild != null && GPXConstants.GPX_NODE.equals(firstChild.getNodeName())) { GPX gpx = new GPX(); NamedNodeMap attrs = firstChild.getAttributes(); for(int idx = 0; idx < attrs.getLength(); idx++) { Node attr = attrs.item(idx); if(GPXConstants.VERSION_ATTR.equals(attr.getNodeName())) { gpx.setVersion(attr.getNodeValue()); } else if(GPXConstants.CREATOR_ATTR.equals(attr.getNodeName())) { gpx.setCreator(attr.getNodeValue()); } } NodeList nodes = firstChild.getChildNodes(); if(logger.isDebugEnabled())logger.debug("Found " +nodes.getLength()+ " child nodes. Start parsing ..."); for(int idx = 0; idx < nodes.getLength(); idx++) { Node currentNode = nodes.item(idx); if(GPXConstants.WPT_NODE.equals(currentNode.getNodeName())) { if(logger.isDebugEnabled())logger.debug("Found waypoint node. Start parsing..."); Waypoint w = parseWaypoint(currentNode); if(w!= null) { logger.info("Add waypoint to gpx data. [waypointName="+ w.getName() + "]"); gpx.addWaypoint(w); } } else if(GPXConstants.TRK_NODE.equals(currentNode.getNodeName())) { if(logger.isDebugEnabled())logger.debug("Found track node. Start parsing..."); Track trk = parseTrack(currentNode); if(trk!= null) { logger.info("Add track to gpx data. [trackName="+ trk.getName() + "]"); gpx.addTrack(trk); } } else if(GPXConstants.EXTENSIONS_NODE.equals(currentNode.getNodeName())) { if(logger.isDebugEnabled())logger.debug("Found extensions node. Start parsing..."); Iterator<IExtensionParser> it = extensionParsers.iterator(); while(it.hasNext()) { IExtensionParser parser = it.next(); Object data = parser.parseGPXExtension(currentNode); gpx.addExtensionData(parser.getId(), data); } } else if(GPXConstants.RTE_NODE.equals(currentNode.getNodeName())) { if(logger.isDebugEnabled())logger.debug("Found route node. Start parsing..."); Route rte = parseRoute(currentNode); if(rte!= null) { logger.info("Add route to gpx data. [routeName="+ rte.getName() + "]"); gpx.addRoute(rte); } } } //TODO: parse route node return gpx; } else { logger.error("FATAL!! - Root node is not gpx."); } return null; } /** * Parses a wpt node into a Waypoint object * * @param node * @return Waypoint object with info from the received node */ private Waypoint parseWaypoint(Node node) { if(node == null) { logger.error("null node received"); return null; } Waypoint w = new Waypoint(); NamedNodeMap attrs = node.getAttributes(); //check for lat attribute Node latNode = attrs.getNamedItem(GPXConstants.LAT_ATTR); if(latNode != null) { Double latVal = null; try { latVal = Double.parseDouble(latNode.getNodeValue()); } catch(NumberFormatException ex) { logger.error("bad lat value in waypoint data: " + latNode.getNodeValue()); } w.setLatitude(latVal); } else { logger.warn("no lat value in waypoint data."); } //check for lon attribute Node lonNode = attrs.getNamedItem(GPXConstants.LON_ATTR); if(lonNode != null) { Double lonVal = null; try { lonVal = Double.parseDouble(lonNode.getNodeValue()); } catch(NumberFormatException ex) { logger.error("bad lon value in waypoint data: " + lonNode.getNodeValue()); } w.setLongitude(lonVal); } else { logger.warn("no lon value in waypoint data."); } NodeList childNodes = node.getChildNodes(); if(childNodes != null) { for(int idx = 0; idx < childNodes.getLength(); idx++) { Node currentNode = childNodes.item(idx); if(GPXConstants.ELE_NODE.equals(currentNode.getNodeName())) { if(logger.isDebugEnabled())logger.debug("found ele node in waypoint data"); w.setElevation(getNodeValueAsDouble(currentNode)); } else if(GPXConstants.TIME_NODE.equals(currentNode.getNodeName())) { if(logger.isDebugEnabled())logger.debug("found time node in waypoint data"); w.setTime(getNodeValueAsDate(currentNode)); } else if(GPXConstants.NAME_NODE.equals(currentNode.getNodeName())) { if(logger.isDebugEnabled())logger.debug("found name node in waypoint data"); w.setName(getNodeValueAsString(currentNode)); } else if(GPXConstants.CMT_NODE.equals(currentNode.getNodeName())) { if(logger.isDebugEnabled())logger.debug("found cmt node in waypoint data"); w.setComment(getNodeValueAsString(currentNode)); } else if(GPXConstants.DESC_NODE.equals(currentNode.getNodeName())) { if(logger.isDebugEnabled())logger.debug("found desc node in waypoint data"); w.setDescription(getNodeValueAsString(currentNode)); } else if(GPXConstants.SRC_NODE.equals(currentNode.getNodeName())) { if(logger.isDebugEnabled())logger.debug("found src node in waypoint data"); w.setSrc(getNodeValueAsString(currentNode)); } else if(GPXConstants.MAGVAR_NODE.equals(currentNode.getNodeName())) { if(logger.isDebugEnabled())logger.debug("found magvar node in waypoint data"); w.setMagneticDeclination(getNodeValueAsDouble(currentNode)); } else if(GPXConstants.GEOIDHEIGHT_NODE.equals(currentNode.getNodeName())) { if(logger.isDebugEnabled())logger.debug("found geoidheight node in waypoint data"); w.setGeoidHeight(getNodeValueAsDouble(currentNode)); } else if(GPXConstants.LINK_NODE.equals(currentNode.getNodeName())) { if(logger.isDebugEnabled())logger.debug("found link node in waypoint data"); //TODO: parse link //w.setGeoidHeight(getNodeValueAsDouble(currentNode)); } else if(GPXConstants.SYM_NODE.equals(currentNode.getNodeName())) { if(logger.isDebugEnabled())logger.debug("found sym node in waypoint data"); w.setSym(getNodeValueAsString(currentNode)); } else if(GPXConstants.FIX_NODE.equals(currentNode.getNodeName())) { if(logger.isDebugEnabled())logger.debug("found fix node in waypoint data"); w.setFix(getNodeValueAsFixType(currentNode)); } else if(GPXConstants.TYPE_NODE.equals(currentNode.getNodeName())) { if(logger.isDebugEnabled())logger.debug("found type node in waypoint data"); w.setType(getNodeValueAsString(currentNode)); } else if(GPXConstants.SAT_NODE.equals(currentNode.getNodeName())) { if(logger.isDebugEnabled())logger.debug("found sat node in waypoint data"); w.setSat(getNodeValueAsInteger(currentNode)); } else if(GPXConstants.HDOP_NODE.equals(currentNode.getNodeName())) { if(logger.isDebugEnabled())logger.debug("found hdop node in waypoint data"); w.setHdop(getNodeValueAsDouble(currentNode)); } else if(GPXConstants.VDOP_NODE.equals(currentNode.getNodeName())) { if(logger.isDebugEnabled())logger.debug("found vdop node in waypoint data"); w.setVdop(getNodeValueAsDouble(currentNode)); } else if(GPXConstants.PDOP_NODE.equals(currentNode.getNodeName())) { if(logger.isDebugEnabled())logger.debug("found pdop node in waypoint data"); w.setPdop(getNodeValueAsDouble(currentNode)); } else if(GPXConstants.AGEOFGPSDATA_NODE.equals(currentNode.getNodeName())) { if(logger.isDebugEnabled())logger.debug("found ageofgpsdata node in waypoint data"); w.setAgeOfGPSData(getNodeValueAsDouble(currentNode)); } else if(GPXConstants.DGPSID_NODE.equals(currentNode.getNodeName())) { if(logger.isDebugEnabled())logger.debug("found dgpsid node in waypoint data"); w.setDgpsid(getNodeValueAsInteger(currentNode)); } else if(GPXConstants.EXTENSIONS_NODE.equals(currentNode.getNodeName())) { if(logger.isDebugEnabled())logger.debug("found extensions node in waypoint data"); Iterator<IExtensionParser> it = extensionParsers.iterator(); while(it.hasNext()) { IExtensionParser parser = it.next(); Object data = parser.parseWaypointExtension(currentNode); w.addExtensionData(parser.getId(), data); } } } } else { if(logger.isDebugEnabled())logger.debug("no child nodes found in waypoint"); } return w; } private Track parseTrack(Node node) { if(node == null) { logger.error("null node received"); return null; } Track trk = new Track(); NodeList nodes = node.getChildNodes(); if(nodes != null) { for(int idx = 0; idx < nodes.getLength(); idx++) { Node currentNode = nodes.item(idx); if(GPXConstants.NAME_NODE.equals(currentNode.getNodeName())) { if(logger.isDebugEnabled())logger.debug("node name found"); trk.setName(getNodeValueAsString(currentNode)); } else if(GPXConstants.CMT_NODE.equals(currentNode.getNodeName())) { if(logger.isDebugEnabled())logger.debug("node cmt found"); trk.setComment(getNodeValueAsString(currentNode)); } else if(GPXConstants.DESC_NODE.equals(currentNode.getNodeName())) { if(logger.isDebugEnabled())logger.debug("node desc found"); trk.setDescription(getNodeValueAsString(currentNode)); } else if(GPXConstants.SRC_NODE.equals(currentNode.getNodeName())) { if(logger.isDebugEnabled())logger.debug("node src found"); trk.setSrc(getNodeValueAsString(currentNode)); } else if(GPXConstants.LINK_NODE.equals(currentNode.getNodeName())) { if(logger.isDebugEnabled())logger.debug("node link found"); //TODO: parse link //trk.setLink(getNodeValueAsLink(currentNode)); } else if(GPXConstants.NUMBER_NODE.equals(currentNode.getNodeName())) { if(logger.isDebugEnabled())logger.debug("node number found"); trk.setNumber(getNodeValueAsInteger(currentNode)); } else if(GPXConstants.TYPE_NODE.equals(currentNode.getNodeName())) { if(logger.isDebugEnabled())logger.debug("node type found"); trk.setType(getNodeValueAsString(currentNode)); } else if(GPXConstants.TRKSEG_NODE.equals(currentNode.getNodeName())) { if(logger.isDebugEnabled())logger.debug("node trkseg found"); trk.setTrackPoints(parseTrackSeg(currentNode)); } else if(GPXConstants.EXTENSIONS_NODE.equals(currentNode.getNodeName())) { Iterator<IExtensionParser> it = extensionParsers.iterator(); while(it.hasNext()) { if(logger.isDebugEnabled())logger.debug("node extensions found"); while(it.hasNext()) { IExtensionParser parser = it.next(); Object data = parser.parseTrackExtension(currentNode); trk.addExtensionData(parser.getId(), data); } } } } } return trk; } private Route parseRoute(Node node) { if(node == null) { logger.error("null node received"); return null; } Route rte = new Route(); NodeList nodes = node.getChildNodes(); if(nodes != null) { for(int idx = 0; idx < nodes.getLength(); idx++) { Node currentNode = nodes.item(idx); if(GPXConstants.NAME_NODE.equals(currentNode.getNodeName())) { if(logger.isDebugEnabled())logger.debug("node name found"); rte.setName(getNodeValueAsString(currentNode)); } else if(GPXConstants.CMT_NODE.equals(currentNode.getNodeName())) { if(logger.isDebugEnabled())logger.debug("node cmt found"); rte.setComment(getNodeValueAsString(currentNode)); } else if(GPXConstants.DESC_NODE.equals(currentNode.getNodeName())) { if(logger.isDebugEnabled())logger.debug("node desc found"); rte.setDescription(getNodeValueAsString(currentNode)); } else if(GPXConstants.SRC_NODE.equals(currentNode.getNodeName())) { if(logger.isDebugEnabled())logger.debug("node src found"); rte.setSrc(getNodeValueAsString(currentNode)); } else if(GPXConstants.LINK_NODE.equals(currentNode.getNodeName())) { if(logger.isDebugEnabled())logger.debug("node link found"); //TODO: parse link //rte.setLink(getNodeValueAsLink(currentNode)); } else if(GPXConstants.NUMBER_NODE.equals(currentNode.getNodeName())) { if(logger.isDebugEnabled())logger.debug("node number found"); rte.setNumber(getNodeValueAsInteger(currentNode)); } else if(GPXConstants.TYPE_NODE.equals(currentNode.getNodeName())) { if(logger.isDebugEnabled())logger.debug("node type found"); rte.setType(getNodeValueAsString(currentNode)); } else if(GPXConstants.RTEPT_NODE.equals(currentNode.getNodeName())) { if(logger.isDebugEnabled())logger.debug("node rtept found"); Waypoint wp = parseWaypoint(currentNode); if(wp!=null) { rte.addRoutePoint(wp); } } else if(GPXConstants.EXTENSIONS_NODE.equals(currentNode.getNodeName())) { Iterator<IExtensionParser> it = extensionParsers.iterator(); while(it.hasNext()) { if(logger.isDebugEnabled())logger.debug("node extensions found"); while(it.hasNext()) { IExtensionParser parser = it.next(); Object data = parser.parseRouteExtension(currentNode); rte.addExtensionData(parser.getId(), data); } } } } } return rte; } private ArrayList<Waypoint> parseTrackSeg(Node node) { if(node == null) { logger.error("null node received"); return null; } ArrayList<Waypoint> trkpts = new ArrayList<Waypoint>(); NodeList nodes = node.getChildNodes(); if(nodes != null) { for(int idx = 0; idx < nodes.getLength(); idx++) { Node currentNode = nodes.item(idx); if(GPXConstants.TRKPT_NODE.equals(currentNode.getNodeName())) { if(logger.isDebugEnabled())logger.debug("node name found"); Waypoint wp = parseWaypoint(currentNode); if(wp!=null) { trkpts.add(wp); } } else if(GPXConstants.EXTENSIONS_NODE.equals(currentNode.getNodeName())) { if(logger.isDebugEnabled())logger.debug("node extensions found"); /* Iterator<IExtensionParser> it = extensionParsers.iterator(); while(it.hasNext()) { IExtensionParser parser = it.next(); Object data = parser.parseWaypointExtension(currentNode); //.addExtensionData(parser.getId(), data); } */ } } } return trkpts; } private Double getNodeValueAsDouble(Node node) { Double val = null; try { val = Double.parseDouble(node.getFirstChild().getNodeValue()); } catch (Exception ex) { logger.error("error parsing Double value form node. val=" + node.getNodeValue(), ex); } return val; } private Date getNodeValueAsDate(Node node) { //2012-02-25T09:28:45Z Date val = null; try { val = sdf.parse(node.getFirstChild().getNodeValue()); } catch (Exception ex) { logger.error("error parsing Date value form node. val=" + node.getNodeName(), ex); } return val; } private String getNodeValueAsString(Node node) { String val = null; try { val = node.getFirstChild().getNodeValue(); } catch (Exception ex) { logger.error("error getting String value form node. val=" + node.getNodeName(), ex); } return val; } private FixType getNodeValueAsFixType(Node node) { FixType val = null; try { val = FixType.returnType(node.getFirstChild().getNodeValue()); } catch (Exception ex) { logger.error("error getting FixType value form node. val=" + node.getNodeName(), ex); } return val; } private Integer getNodeValueAsInteger(Node node) { Integer val = null; try { val = Integer.parseInt(node.getFirstChild().getNodeValue()); } catch (Exception ex) { logger.error("error parsing Integer value form node. val=" + node.getNodeValue(), ex); } return val; } public void writeGPX(GPX gpx, File gpxFile) throws IOException, ParserConfigurationException, TransformerException { OutputStream out = FileUtils.openOutputStream(gpxFile); writeGPX(gpx,out); out.flush(); out.close(); } public void writeGPX(GPX gpx, OutputStream out) throws ParserConfigurationException, TransformerException { DocumentBuilder builder = docFactory.newDocumentBuilder(); Document doc = builder.newDocument(); Node gpxNode = doc.createElement(GPXConstants.GPX_NODE); addBasicGPXInfoToNode(gpx, gpxNode, doc); if(gpx.getWaypoints() != null) { Iterator<Waypoint> itW = gpx.getWaypoints().iterator(); while(itW.hasNext()) { addWaypointToGPXNode(itW.next(), gpxNode, doc); } Iterator<Track> itT = gpx.getTracks().iterator(); while(itT.hasNext()) { addTrackToGPXNode(itT.next(), gpxNode, doc); } Iterator<Route> itR = gpx.getRoutes().iterator(); while(itR.hasNext()) { addRouteToGPXNode(itR.next(), gpxNode, doc); } } doc.appendChild(gpxNode); // Use a Transformer for output Transformer transformer = tFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(out); transformer.transform(source, result); } private void addWaypointToGPXNode(Waypoint wpt, Node gpxNode, Document doc) { addGenericWaypointToGPXNode(GPXConstants.WPT_NODE, wpt, gpxNode, doc); } private void addGenericWaypointToGPXNode(String tagName,Waypoint wpt, Node gpxNode, Document doc) { Node wptNode = doc.createElement(tagName); NamedNodeMap attrs = wptNode.getAttributes(); if(wpt.getLatitude() != null) { Node latNode = doc.createAttribute(GPXConstants.LAT_ATTR); latNode.setNodeValue(wpt.getLatitude().toString()); attrs.setNamedItem(latNode); } if(wpt.getLongitude() != null) { Node longNode = doc.createAttribute(GPXConstants.LON_ATTR); longNode.setNodeValue(wpt.getLongitude().toString()); attrs.setNamedItem(longNode); } if(wpt.getElevation() != null) { Node node = doc.createElement(GPXConstants.ELE_NODE); node.appendChild(doc.createTextNode(wpt.getElevation().toString())); wptNode.appendChild(node); } if(wpt.getTime() != null) { Node node = doc.createElement(GPXConstants.TIME_NODE); node.appendChild(doc.createTextNode(sdfZ.format(wpt.getTime()))); wptNode.appendChild(node); } if(wpt.getMagneticDeclination() != null) { Node node = doc.createElement(GPXConstants.MAGVAR_NODE); node.appendChild(doc.createTextNode(wpt.getMagneticDeclination().toString())); wptNode.appendChild(node); } if(wpt.getGeoidHeight() != null) { Node node = doc.createElement(GPXConstants.GEOIDHEIGHT_NODE); node.appendChild(doc.createTextNode(wpt.getGeoidHeight().toString())); wptNode.appendChild(node); } if(wpt.getName() != null) { Node node = doc.createElement(GPXConstants.NAME_NODE); node.appendChild(doc.createTextNode(wpt.getName())); wptNode.appendChild(node); } if(wpt.getComment() != null) { Node node = doc.createElement(GPXConstants.CMT_NODE); node.appendChild(doc.createTextNode(wpt.getComment())); wptNode.appendChild(node); } if(wpt.getDescription() != null) { Node node = doc.createElement(GPXConstants.DESC_NODE); node.appendChild(doc.createTextNode(wpt.getDescription())); wptNode.appendChild(node); } if(wpt.getSrc() != null) { Node node = doc.createElement(GPXConstants.SRC_NODE); node.appendChild(doc.createTextNode(wpt.getSrc())); wptNode.appendChild(node); } //TODO: write link node if(wpt.getSym() != null) { Node node = doc.createElement(GPXConstants.SYM_NODE); node.appendChild(doc.createTextNode(wpt.getSym())); wptNode.appendChild(node); } if(wpt.getType() != null) { Node node = doc.createElement(GPXConstants.TYPE_NODE); node.appendChild(doc.createTextNode(wpt.getType())); wptNode.appendChild(node); } if(wpt.getFix() != null) { Node node = doc.createElement(GPXConstants.FIX_NODE); node.appendChild(doc.createTextNode(wpt.getFix().toString())); wptNode.appendChild(node); } if(wpt.getSat() != null) { Node node = doc.createElement(GPXConstants.SAT_NODE); node.appendChild(doc.createTextNode(wpt.getSat().toString())); wptNode.appendChild(node); } if(wpt.getHdop() != null) { Node node = doc.createElement(GPXConstants.HDOP_NODE); node.appendChild(doc.createTextNode(wpt.getHdop().toString())); wptNode.appendChild(node); } if(wpt.getVdop() != null) { Node node = doc.createElement(GPXConstants.VDOP_NODE); node.appendChild(doc.createTextNode(wpt.getVdop().toString())); wptNode.appendChild(node); } if(wpt.getPdop() != null) { Node node = doc.createElement(GPXConstants.PDOP_NODE); node.appendChild(doc.createTextNode(wpt.getPdop().toString())); wptNode.appendChild(node); } if(wpt.getAgeOfGPSData() != null) { Node node = doc.createElement(GPXConstants.AGEOFGPSDATA_NODE); node.appendChild(doc.createTextNode(wpt.getAgeOfGPSData().toString())); wptNode.appendChild(node); } if(wpt.getDgpsid() != null) { Node node = doc.createElement(GPXConstants.DGPSID_NODE); node.appendChild(doc.createTextNode(wpt.getDgpsid().toString())); wptNode.appendChild(node); } if(wpt.getExtensionsParsed() > 0) { Node node = doc.createElement(GPXConstants.EXTENSIONS_NODE); Iterator<IExtensionParser> it = extensionParsers.iterator(); while(it.hasNext()) { it.next().writeWaypointExtensionData(node, wpt, doc); } wptNode.appendChild(node); } gpxNode.appendChild(wptNode); } private void addTrackToGPXNode(Track trk, Node gpxNode, Document doc) { Node trkNode = doc.createElement(GPXConstants.TRK_NODE); if(trk.getName() != null) { Node node = doc.createElement(GPXConstants.NAME_NODE); node.appendChild(doc.createTextNode(trk.getName())); trkNode.appendChild(node); } if(trk.getComment() != null) { Node node = doc.createElement(GPXConstants.CMT_NODE); node.appendChild(doc.createTextNode(trk.getComment())); trkNode.appendChild(node); } if(trk.getDescription() != null) { Node node = doc.createElement(GPXConstants.DESC_NODE); node.appendChild(doc.createTextNode(trk.getDescription())); trkNode.appendChild(node); } if(trk.getSrc() != null) { Node node = doc.createElement(GPXConstants.SRC_NODE); node.appendChild(doc.createTextNode(trk.getSrc())); trkNode.appendChild(node); } //TODO: write link if(trk.getNumber() != null) { Node node = doc.createElement(GPXConstants.NUMBER_NODE); node.appendChild(doc.createTextNode(trk.getNumber().toString())); trkNode.appendChild(node); } if(trk.getType() != null) { Node node = doc.createElement(GPXConstants.TYPE_NODE); node.appendChild(doc.createTextNode(trk.getType())); trkNode.appendChild(node); } if(trk.getExtensionsParsed() > 0) { Node node = doc.createElement(GPXConstants.EXTENSIONS_NODE); Iterator<IExtensionParser> it = extensionParsers.iterator(); while(it.hasNext()) { it.next().writeTrackExtensionData(node, trk, doc); } trkNode.appendChild(node); } if(trk.getTrackPoints() != null) { Node trksegNode = doc.createElement(GPXConstants.TRKSEG_NODE); Iterator<Waypoint> it = trk.getTrackPoints().iterator(); while(it.hasNext()) { addGenericWaypointToGPXNode(GPXConstants.TRKPT_NODE, it.next(), trksegNode, doc); } trkNode.appendChild(trksegNode); } gpxNode.appendChild(trkNode); } private void addRouteToGPXNode(Route rte, Node gpxNode, Document doc) { Node trkNode = doc.createElement(GPXConstants.TRK_NODE); if(rte.getName() != null) { Node node = doc.createElement(GPXConstants.NAME_NODE); node.appendChild(doc.createTextNode(rte.getName())); trkNode.appendChild(node); } if(rte.getComment() != null) { Node node = doc.createElement(GPXConstants.CMT_NODE); node.appendChild(doc.createTextNode(rte.getComment())); trkNode.appendChild(node); } if(rte.getDescription() != null) { Node node = doc.createElement(GPXConstants.DESC_NODE); node.appendChild(doc.createTextNode(rte.getDescription())); trkNode.appendChild(node); } if(rte.getSrc() != null) { Node node = doc.createElement(GPXConstants.SRC_NODE); node.appendChild(doc.createTextNode(rte.getSrc())); trkNode.appendChild(node); } //TODO: write link if(rte.getNumber() != null) { Node node = doc.createElement(GPXConstants.NUMBER_NODE); node.appendChild(doc.createTextNode(rte.getNumber().toString())); trkNode.appendChild(node); } if(rte.getType() != null) { Node node = doc.createElement(GPXConstants.TYPE_NODE); node.appendChild(doc.createTextNode(rte.getType())); trkNode.appendChild(node); } if(rte.getExtensionsParsed() > 0) { Node node = doc.createElement(GPXConstants.EXTENSIONS_NODE); Iterator<IExtensionParser> it = extensionParsers.iterator(); while(it.hasNext()) { it.next().writeRouteExtensionData(node, rte, doc); } trkNode.appendChild(node); } if(rte.getRoutePoints() != null) { Iterator<Waypoint> it = rte.getRoutePoints().iterator(); while(it.hasNext()) { addGenericWaypointToGPXNode(GPXConstants.RTEPT_NODE, it.next(), trkNode, doc); } } gpxNode.appendChild(trkNode); } private void addBasicGPXInfoToNode(GPX gpx, Node gpxNode, Document doc) { NamedNodeMap attrs = gpxNode.getAttributes(); if(gpx.getVersion() != null) { Node verNode = doc.createAttribute(GPXConstants.VERSION_ATTR); verNode.setNodeValue(gpx.getVersion()); attrs.setNamedItem(verNode); } if(gpx.getCreator() != null) { Node creatorNode = doc.createAttribute(GPXConstants.CREATOR_ATTR); creatorNode.setNodeValue(gpx.getCreator()); attrs.setNamedItem(creatorNode); } if(gpx.getExtensionsParsed() > 0) { Node node = doc.createElement(GPXConstants.EXTENSIONS_NODE); Iterator<IExtensionParser> it = extensionParsers.iterator(); while(it.hasNext()) { it.next().writeGPXExtensionData(node, gpx, doc); } gpxNode.appendChild(node); } } }
RBerliner/freeboard-server
src/main/java/org/alternativevision/gpx/GPXParser.java
Java
gpl-3.0
30,515
package it.ninjatech.kvo.async.job; import it.ninjatech.kvo.model.ImageProvider; import it.ninjatech.kvo.util.Logger; import java.awt.Dimension; import java.awt.Image; import java.util.EnumSet; public class CacheRemoteImageAsyncJob extends AbstractImageLoaderAsyncJob { private static final long serialVersionUID = -8459315395025635686L; private final String path; private final String type; private final Dimension size; private Image image; public CacheRemoteImageAsyncJob(String id, ImageProvider provider, String path, Dimension size, String type) { super(id, EnumSet.of(LoadType.Cache, LoadType.Remote), provider); this.path = path; this.size = size; this.type = type; } @Override protected void execute() { try { Logger.log("-> executing cache-remote image %s\n", this.id); this.image = getImage(null, null, this.id, this.path, this.size, this.type); } catch (Exception e) { this.exception = e; } } public Image getImage() { return this.image; } }
vincenzomazzeo/kodi-video-organizer
src/main/java/it/ninjatech/kvo/async/job/CacheRemoteImageAsyncJob.java
Java
gpl-3.0
1,058
/** * The MIT License * Copyright (c) 2012 Graylog, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.graylog2.plugin; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import org.graylog2.plugin.streams.Stream; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.runners.MockitoJUnitRunner; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class MessageTest { private Message message; private DateTime originalTimestamp; @Before public void setUp() { originalTimestamp = Tools.iso8601(); message = new Message("foo", "bar", originalTimestamp); } @Test public void testAddFieldDoesOnlyAcceptAlphanumericKeys() throws Exception { Message m = new Message("foo", "bar", Tools.iso8601()); m.addField("some_thing", "bar"); assertEquals("bar", m.getField("some_thing")); m = new Message("foo", "bar", Tools.iso8601()); m.addField("some-thing", "bar"); assertEquals("bar", m.getField("some-thing")); m = new Message("foo", "bar", Tools.iso8601()); m.addField("somethin$g", "bar"); assertNull(m.getField("somethin$g")); m = new Message("foo", "bar", Tools.iso8601()); m.addField("someäthing", "bar"); assertNull(m.getField("someäthing")); } @Test public void testAddFieldTrimsValue() throws Exception { Message m = new Message("foo", "bar", Tools.iso8601()); m.addField("something", " bar "); assertEquals("bar", m.getField("something")); m.addField("something2", " bar"); assertEquals("bar", m.getField("something2")); m.addField("something3", "bar "); assertEquals("bar", m.getField("something3")); } @Test public void testAddFieldWorksWithIntegers() throws Exception { Message m = new Message("foo", "bar", Tools.iso8601()); m.addField("something", 3); assertEquals(3, m.getField("something")); } @Test public void testAddFields() throws Exception { final Map<String, Object> map = Maps.newHashMap(); map.put("field1", "Foo"); map.put("field2", 1); message.addFields(map); assertEquals("Foo", message.getField("field1")); assertEquals(1, message.getField("field2")); } @Test public void testAddStringFields() throws Exception { final Map<String, String> map = Maps.newHashMap(); map.put("field1", "Foo"); map.put("field2", "Bar"); message.addStringFields(map); assertEquals("Foo", message.getField("field1")); assertEquals("Bar", message.getField("field2")); } @Test public void testAddLongFields() throws Exception { final Map<String, Long> map = Maps.newHashMap(); map.put("field1", 10L); map.put("field2", 230L); message.addLongFields(map); assertEquals(10L, message.getField("field1")); assertEquals(230L, message.getField("field2")); } @Test public void testAddDoubleFields() throws Exception { final Map<String, Double> map = Maps.newHashMap(); map.put("field1", 10.0d); map.put("field2", 230.2d); message.addDoubleFields(map); assertEquals(10.0d, message.getField("field1")); assertEquals(230.2d, message.getField("field2")); } @Test public void testRemoveField() throws Exception { message.addField("foo", "bar"); message.removeField("foo"); assertNull(message.getField("foo")); } @Test public void testRemoveFieldNotDeletingReservedFields() throws Exception { message.removeField("message"); message.removeField("source"); message.removeField("timestamp"); assertNotNull(message.getField("message")); assertNotNull(message.getField("source")); assertNotNull(message.getField("timestamp")); } @Test public void testGetFieldAs() throws Exception { message.addField("fields", Lists.newArrayList("hello")); assertEquals(Lists.newArrayList("hello"), message.getFieldAs(List.class, "fields")); } @Test(expected = ClassCastException.class) public void testGetFieldAsWithIncompatibleCast() throws Exception { message.addField("fields", Lists.newArrayList("hello")); message.getFieldAs(Map.class, "fields"); } @Test public void testSetAndGetStreams() throws Exception { final Stream stream1 = mock(Stream.class); final Stream stream2 = mock(Stream.class); message.setStreams(Lists.newArrayList(stream1, stream2)); assertEquals(Lists.newArrayList(stream1, stream2), message.getStreams()); } @Test public void testGetStreamIds() throws Exception { message.addField("streams", Lists.newArrayList("stream-id")); assertEquals(Lists.newArrayList("stream-id"), message.getStreamIds()); } @Test public void testGetAndSetFilterOut() throws Exception { assertFalse(message.getFilterOut()); message.setFilterOut(true); assertTrue(message.getFilterOut()); message.setFilterOut(false); assertFalse(message.getFilterOut()); } @Test public void testGetId() throws Exception { final Pattern pattern = Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"); assertTrue(pattern.matcher(message.getId()).matches()); } @Test public void testGetTimestamp() { try { final DateTime timestamp = message.getTimestamp(); assertNotNull(timestamp); assertEquals(originalTimestamp.getZone(), timestamp.getZone()); } catch (ClassCastException e) { fail("timestamp wasn't a DateTime " + e.getMessage()); } } @Test public void testTimestampAsDate() { final DateTime dateTime = new DateTime(2015, 9, 8, 0, 0, DateTimeZone.UTC); message.addField(Message.FIELD_TIMESTAMP, dateTime.toDate()); final Map<String, Object> elasticSearchObject = message.toElasticSearchObject(); final Object esTimestampFormatted = elasticSearchObject.get(Message.FIELD_TIMESTAMP); assertEquals("Setting message timestamp as java.util.Date results in correct format for elasticsearch", Tools.buildElasticSearchTimeFormat(dateTime), esTimestampFormatted); } @Test public void testGetMessage() throws Exception { assertEquals("foo", message.getMessage()); } @Test public void testGetSource() throws Exception { assertEquals("bar", message.getSource()); } @Test public void testValidKeys() throws Exception { assertTrue(Message.validKey("foo123")); assertTrue(Message.validKey("foo-bar123")); assertTrue(Message.validKey("foo_bar123")); assertTrue(Message.validKey("foo.bar123")); assertTrue(Message.validKey("123")); assertTrue(Message.validKey("")); assertFalse(Message.validKey("foo bar")); assertFalse(Message.validKey("foo+bar")); assertFalse(Message.validKey("foo$bar")); assertFalse(Message.validKey(" ")); } @Test public void testToElasticSearchObject() throws Exception { message.addField("field1", "wat"); message.addField("field2", "that"); final Map<String, Object> object = message.toElasticSearchObject(); assertEquals("foo", object.get("message")); assertEquals("bar", object.get("source")); assertEquals("wat", object.get("field1")); assertEquals("that", object.get("field2")); assertEquals(Tools.buildElasticSearchTimeFormat((DateTime) message.getField("timestamp")), object.get("timestamp")); assertEquals(Collections.EMPTY_LIST, object.get("streams")); } @Test public void testToElasticSearchObjectWithoutDateTimeTimestamp() throws Exception { message.addField("timestamp", "time!"); final Map<String, Object> object = message.toElasticSearchObject(); assertEquals("time!", object.get("timestamp")); } @Test public void testToElasticSearchObjectWithStreams() throws Exception { final Stream stream = mock(Stream.class); when(stream.getId()).thenReturn("stream-id"); message.setStreams(Lists.newArrayList(stream)); final Map<String, Object> object = message.toElasticSearchObject(); assertEquals(Lists.newArrayList("stream-id"), object.get("streams")); } @Test public void testIsComplete() throws Exception { Message message = new Message("message", "source", Tools.iso8601()); assertTrue(message.isComplete()); message = new Message("message", "", Tools.iso8601()); assertTrue(message.isComplete()); message = new Message("message", null, Tools.iso8601()); assertTrue(message.isComplete()); message = new Message("", "source", Tools.iso8601()); assertFalse(message.isComplete()); message = new Message(null, "source", Tools.iso8601()); assertFalse(message.isComplete()); } @Test public void testGetValidationErrorsWithEmptyMessage() throws Exception { final Message message = new Message("", "source", Tools.iso8601()); assertEquals("message is empty, ", message.getValidationErrors()); } @Test public void testGetValidationErrorsWithNullMessage() throws Exception { final Message message = new Message(null, "source", Tools.iso8601()); assertEquals("message is missing, ", message.getValidationErrors()); } @Test public void testGetFields() throws Exception { final Map<String, Object> fields = message.getFields(); assertEquals(message.getId(), fields.get("_id")); assertEquals(message.getMessage(), fields.get("message")); assertEquals(message.getSource(), fields.get("source")); assertEquals(message.getField("timestamp"), fields.get("timestamp")); } @Test(expected = UnsupportedOperationException.class) public void testGetFieldsReturnsImmutableMap() throws Exception { final Map<String, Object> fields = message.getFields(); fields.put("foo", "bar"); } @Test public void testGetFieldNames() throws Exception { assertTrue("Missing fields in set!", Sets.symmetricDifference(message.getFieldNames(), Sets.newHashSet("_id", "timestamp", "source", "message")).isEmpty()); message.addField("testfield", "testvalue"); assertTrue("Missing fields in set!", Sets.symmetricDifference(message.getFieldNames(), Sets.newHashSet("_id", "timestamp", "source", "message", "testfield")).isEmpty()); } @Test(expected = UnsupportedOperationException.class) public void testGetFieldNamesReturnsUnmodifiableSet() throws Exception { final Set<String> fieldNames = message.getFieldNames(); fieldNames.remove("_id"); } @Test public void testHasField() throws Exception { assertFalse(message.hasField("__foo__")); message.addField("__foo__", "bar"); assertTrue(message.hasField("__foo__")); } }
berkeleydave/graylog2-server
graylog2-plugin-interfaces/src/test/java/org/graylog2/plugin/MessageTest.java
Java
gpl-3.0
12,940
package org.obiba.mica.search.aggregations; import org.obiba.mica.micaConfig.service.helper.AggregationMetaDataProvider; import org.obiba.mica.micaConfig.service.helper.PopulationIdAggregationMetaDataHelper; import org.springframework.stereotype.Component; import javax.inject.Inject; import java.util.Map; @Component public class PopulationAggregationMetaDataProvider implements AggregationMetaDataProvider { private static final String AGGREGATION_NAME = "populationId"; private final PopulationIdAggregationMetaDataHelper helper; @Inject public PopulationAggregationMetaDataProvider(PopulationIdAggregationMetaDataHelper helper) { this.helper = helper; } @Override public MetaData getMetadata(String aggregation, String termKey, String locale) { Map<String, LocalizedMetaData> dataMap = helper.getPopulations(); return AGGREGATION_NAME.equals(aggregation) && dataMap.containsKey(termKey) ? MetaData.newBuilder() .title(dataMap.get(termKey).getTitle().get(locale)) .description(dataMap.get(termKey).getDescription().get(locale)) .className(dataMap.get(termKey).getClassName()) .build() : null; } @Override public boolean containsAggregation(String aggregation) { return AGGREGATION_NAME.equals(aggregation); } @Override public void refresh() { } }
obiba/mica2
mica-search/src/main/java/org/obiba/mica/search/aggregations/PopulationAggregationMetaDataProvider.java
Java
gpl-3.0
1,342
/** * This file is part of d:swarm graph extension. * * d:swarm graph extension 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. * * d:swarm graph extension 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 d:swarm graph extension. If not, see <http://www.gnu.org/licenses/>. */ package org.dswarm.graph.delta.match.model.util; import java.util.Collection; import java.util.HashSet; import java.util.Optional; import java.util.Set; import org.dswarm.graph.delta.match.model.CSEntity; import org.dswarm.graph.delta.match.model.ValueEntity; /** * @author tgaengler */ public final class CSEntityUtil { public static Optional<? extends Collection<ValueEntity>> getValueEntities(final Optional<? extends Collection<CSEntity>> csEntities) { if (!csEntities.isPresent() || csEntities.get().isEmpty()) { return Optional.empty(); } final Set<ValueEntity> valueEntities = new HashSet<>(); for (final CSEntity csEntity : csEntities.get()) { valueEntities.addAll(csEntity.getValueEntities()); } return Optional.of(valueEntities); } }
zazi/dswarm-graph-neo4j
src/main/java/org/dswarm/graph/delta/match/model/util/CSEntityUtil.java
Java
gpl-3.0
1,515
/* Copyright 2014 Red Hat, Inc. and/or its affiliates. This file is part of lightblue. 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 3 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/>. */ package com.redhat.lightblue.hystrix.ldap; import com.netflix.hystrix.HystrixCommand; import com.netflix.hystrix.HystrixCommandGroupKey; import com.netflix.hystrix.HystrixCommandKey; import com.unboundid.ldap.sdk.LDAPConnection; public abstract class AbstractLdapHystrixCommand<T> extends HystrixCommand<T>{ public static final String GROUPKEY = "ldap"; private final LDAPConnection connection; public LDAPConnection getConnection(){ return connection; } public AbstractLdapHystrixCommand(LDAPConnection connection, String commandKey){ super(HystrixCommand.Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey(GROUPKEY)). andCommandKey(HystrixCommandKey.Factory.asKey(GROUPKEY + ":" + commandKey))); this.connection = connection; } }
dcrissman/lightblue-ldap
lightblue-ldap-hystrix/src/main/java/com/redhat/lightblue/hystrix/ldap/AbstractLdapHystrixCommand.java
Java
gpl-3.0
1,527
/* * Syncany, www.syncany.org * Copyright (C) 2011 Philipp C. Heckel <philipp.heckel@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 3 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/>. */ package com.stacksync.desktop.watch.local; import java.io.File; import org.apache.log4j.Logger; import com.stacksync.desktop.Environment; import com.stacksync.desktop.Environment.OperatingSystem; import com.stacksync.desktop.config.Config; import com.stacksync.desktop.config.Folder; import com.stacksync.desktop.config.profile.Profile; import com.stacksync.desktop.index.Indexer; import com.stacksync.desktop.util.FileUtil; /** * * @author oubou68, pheckel */ public abstract class LocalWatcher { protected final Logger logger = Logger.getLogger(LocalWatcher.class.getName()); protected static final Environment env = Environment.getInstance(); protected static LocalWatcher instance; protected Config config; protected Indexer indexer; public LocalWatcher() { initDependencies(); logger.info("Creating watcher ..."); } private void initDependencies() { config = Config.getInstance(); indexer = Indexer.getInstance(); } public void queueCheckFile(Folder root, File file) { // Exclude ".ignore*" files from everything if (FileUtil.checkIgnoreFile(root, file)) { logger.debug("Watcher: Ignoring file "+file.getAbsolutePath()); return; } // File vanished! if (!file.exists()) { logger.warn("Watcher: File "+file+" vanished. IGNORING."); return; } // Add to queue logger.info("Watcher: Checking new/modified file "+file); indexer.queueChecked(root, file); } public void queueMoveFile(Folder fromRoot, File fromFile, Folder toRoot, File toFile) { // Exclude ".ignore*" files from everything if (FileUtil.checkIgnoreFile(fromRoot, fromFile) || FileUtil.checkIgnoreFile(toRoot, toFile)) { logger.info("Watcher: Ignoring file "+fromFile.getAbsolutePath()); return; } // File vanished! if (!toFile.exists()) { logger.warn("Watcher: File "+toFile+" vanished. IGNORING."); return; } // Add to queue logger.info("Watcher: Moving file "+fromFile+" TO "+toFile+""); indexer.queueMoved(fromRoot, fromFile, toRoot, toFile); } public void queueDeleteFile(Folder root, File file) { // Exclude ".ignore*" files from everything if (FileUtil.checkIgnoreFile(root, file)) { logger.info("Watcher: Ignoring file "+file.getAbsolutePath()); return; } // Add to queue logger.info("Watcher: Deleted file "+file+""); indexer.queueDeleted(root, file); } public static synchronized LocalWatcher getInstance() { if (instance != null) { return instance; } if (env.getOperatingSystem() == OperatingSystem.Linux || env.getOperatingSystem() == OperatingSystem.Windows || env.getOperatingSystem() == OperatingSystem.Mac) { instance = new CommonLocalWatcher(); return instance; } throw new RuntimeException("Your operating system is currently not supported: " + System.getProperty("os.name")); } public abstract void start(); public abstract void stop(); public abstract void watch(Profile profile); public abstract void unwatch(Profile profile); }
pviotti/stacksync-desktop
src/com/stacksync/desktop/watch/local/LocalWatcher.java
Java
gpl-3.0
4,196
package org.gnubridge.presentation.gui; import java.awt.Point; import org.gnubridge.core.Card; import org.gnubridge.core.Direction; import org.gnubridge.core.East; import org.gnubridge.core.Deal; import org.gnubridge.core.Hand; import org.gnubridge.core.North; import org.gnubridge.core.South; import org.gnubridge.core.West; import org.gnubridge.core.deck.Suit; public class OneColumnPerColor extends HandDisplay { public OneColumnPerColor(Direction human, Direction player, Deal game, CardPanelHost owner) { super(human, player, game, owner); } final static int CARD_OFFSET = 30; @Override public void display() { dispose(cards); Hand hand = new Hand(game.getPlayer(player).getHand()); Point upperLeft = calculateUpperLeft(human, player); for (Suit color : Suit.list) { int j = 0; for (Card card : hand.getSuitHi2Low(color)) { CardPanel cardPanel = new CardPanel(card); cards.add(cardPanel); if (human.equals(South.i())) { cardPanel.setPlayable(true); } owner.addCard(cardPanel); cardPanel.setLocation((int) upperLeft.getX(), (int) upperLeft.getY() + CARD_OFFSET * j); j++; } upperLeft.setLocation(upperLeft.getX() + CardPanel.IMAGE_WIDTH + 2, upperLeft.getY()); } } private Point calculateUpperLeft(Direction human, Direction player) { Direction slot = new HumanAlwaysOnBottom(human).mapRelativeTo(player); if (North.i().equals(slot)) { return new Point(235, 5); } else if (West.i().equals(slot)) { return new Point(3, owner.getTotalHeight() - 500); } else if (East.i().equals(slot)) { return new Point(512, owner.getTotalHeight() - 500); } else if (South.i().equals(slot)) { return new Point(235, owner.getTableBottom() + 1); } throw new RuntimeException("unknown direction"); } }
pslusarz/gnubridge
src/main/java/org/gnubridge/presentation/gui/OneColumnPerColor.java
Java
gpl-3.0
1,786
/* * Copyright (C) 2013 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.inputmethod.latin; import android.content.Context; import com.android.inputmethod.keyboard.ProximityInfo; import com.android.inputmethod.latin.SuggestedWords.SuggestedWordInfo; import com.android.inputmethod.latin.makedict.DictEncoder; import com.android.inputmethod.latin.makedict.FormatSpec; import com.android.inputmethod.latin.makedict.FusionDictionary; import com.android.inputmethod.latin.makedict.FusionDictionary.PtNodeArray; import com.android.inputmethod.latin.makedict.FusionDictionary.WeightedString; import com.android.inputmethod.latin.makedict.UnsupportedFormatException; import com.android.inputmethod.latin.utils.CollectionUtils; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; /** * An in memory dictionary for memorizing entries and writing a binary dictionary. */ public class DictionaryWriter extends AbstractDictionaryWriter { private static final int BINARY_DICT_VERSION = 3; private static final FormatSpec.FormatOptions FORMAT_OPTIONS = new FormatSpec.FormatOptions(BINARY_DICT_VERSION, true /* supportsDynamicUpdate */); private FusionDictionary mFusionDictionary; public DictionaryWriter(final Context context, final String dictType) { super(context, dictType); clear(); } @Override public void clear() { final HashMap<String, String> attributes = CollectionUtils.newHashMap(); mFusionDictionary = new FusionDictionary(new PtNodeArray(), new FusionDictionary.DictionaryOptions(attributes, false, false)); } /** * Adds a word unigram to the fusion dictionary. */ // TODO: Create "cache dictionary" to cache fresh words for frequently updated dictionaries, // considering performance regression. @Override public void addUnigramWord(final String word, final String shortcutTarget, final int frequency, final int shortcutFreq, final boolean isNotAWord) { if (shortcutTarget == null) { mFusionDictionary.add(word, frequency, null, isNotAWord); } else { // TODO: Do this in the subclass, with this class taking an arraylist. final ArrayList<WeightedString> shortcutTargets = CollectionUtils.newArrayList(); shortcutTargets.add(new WeightedString(shortcutTarget, shortcutFreq)); mFusionDictionary.add(word, frequency, shortcutTargets, isNotAWord); } } @Override public void addBigramWords(final String word0, final String word1, final int frequency, final boolean isValid, final long lastModifiedTime) { mFusionDictionary.setBigram(word0, word1, frequency); } @Override public void removeBigramWords(final String word0, final String word1) { // This class don't support removing bigram words. } @Override protected void writeDictionary(final DictEncoder dictEncoder, final Map<String, String> attributeMap) throws IOException, UnsupportedFormatException { for (final Map.Entry<String, String> entry : attributeMap.entrySet()) { mFusionDictionary.addOptionAttribute(entry.getKey(), entry.getValue()); } dictEncoder.writeDictionary(mFusionDictionary, FORMAT_OPTIONS); } @Override public ArrayList<SuggestedWordInfo> getSuggestions(final WordComposer composer, final String prevWord, final ProximityInfo proximityInfo, boolean blockOffensiveWords, final int[] additionalFeaturesOptions) { // This class doesn't support suggestion. return null; } @Override public boolean isValidWord(String word) { // This class doesn't support dictionary retrieval. return false; } }
s20121035/rk3288_android5.1_repo
packages/inputmethods/LatinIME/java/src/com/android/inputmethod/latin/DictionaryWriter.java
Java
gpl-3.0
4,412
package com.example.mathsolver; import android.annotation.TargetApi; import android.app.Fragment; import android.os.Build; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @TargetApi(Build.VERSION_CODES.HONEYCOMB) public class AreaFragmentRight extends Fragment { public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO Auto-generated method stub return inflater.inflate(R.layout.area_right, container, false); } }
RahulDadoriya/MathSolverApp
src/com/example/mathsolver/AreaFragmentRight.java
Java
gpl-3.0
580
/* * ============================================================================ * GNU General Public License * ============================================================================ * * Copyright (C) 2015 Infinite Automation Software. 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, either version 3 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/>. * * When signing a commercial license with Infinite Automation Software, * the following extension to GPL is made. A special exception to the GPL is * included to allow you to distribute a combined work that includes BAcnet4J * without being obliged to provide the source code for any proprietary components. * * See www.infiniteautomation.com for commercial license options. * * @author Matthew Lohbihler */ package com.serotonin.bacnet4j.type.notificationParameters; import com.serotonin.bacnet4j.exception.BACnetException; import com.serotonin.bacnet4j.type.AmbiguousValue; import com.serotonin.bacnet4j.type.Encodable; import com.serotonin.bacnet4j.type.constructed.StatusFlags; import com.serotonin.bacnet4j.util.sero.ByteQueue; public class CommandFailure extends NotificationParameters { private static final long serialVersionUID = 5727410398456093753L; public static final byte TYPE_ID = 3; private final Encodable commandValue; private final StatusFlags statusFlags; private final Encodable feedbackValue; public CommandFailure(Encodable commandValue, StatusFlags statusFlags, Encodable feedbackValue) { this.commandValue = commandValue; this.statusFlags = statusFlags; this.feedbackValue = feedbackValue; } @Override protected void writeImpl(ByteQueue queue) { writeEncodable(queue, commandValue, 0); write(queue, statusFlags, 1); writeEncodable(queue, feedbackValue, 2); } public CommandFailure(ByteQueue queue) throws BACnetException { commandValue = new AmbiguousValue(queue, 0); statusFlags = read(queue, StatusFlags.class, 1); feedbackValue = new AmbiguousValue(queue, 2); } @Override protected int getTypeId() { return TYPE_ID; } public Encodable getCommandValue() { return commandValue; } public StatusFlags getStatusFlags() { return statusFlags; } public Encodable getFeedbackValue() { return feedbackValue; } @Override public int hashCode() { final int PRIME = 31; int result = 1; result = PRIME * result + ((commandValue == null) ? 0 : commandValue.hashCode()); result = PRIME * result + ((feedbackValue == null) ? 0 : feedbackValue.hashCode()); result = PRIME * result + ((statusFlags == null) ? 0 : statusFlags.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final CommandFailure other = (CommandFailure) obj; if (commandValue == null) { if (other.commandValue != null) return false; } else if (!commandValue.equals(other.commandValue)) return false; if (feedbackValue == null) { if (other.feedbackValue != null) return false; } else if (!feedbackValue.equals(other.feedbackValue)) return false; if (statusFlags == null) { if (other.statusFlags != null) return false; } else if (!statusFlags.equals(other.statusFlags)) return false; return true; } }
mlohbihler/BACnet4J
src/main/java/com/serotonin/bacnet4j/type/notificationParameters/CommandFailure.java
Java
gpl-3.0
4,277
/* * Copyright (C) 2012 Krawler Information Systems Pvt Ltd * 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; 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.krawler.portal.util; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.TreeSet; /** * <a href="ListUtil.java.html"><b><i>View Source</i></b></a> * * @author Brian Wing Shun Chan * */ public class ListUtil { public static List copy(List master) { if (master == null) { return null; } return new ArrayList(master); } public static void copy(List master, List copy) { if ((master == null) || (copy == null)) { return; } copy.clear(); Iterator itr = master.iterator(); while (itr.hasNext()) { Object obj = itr.next(); copy.add(obj); } } public static void distinct(List list) { distinct(list, null); } public static void distinct(List list, Comparator comparator) { if ((list == null) || (list.size() == 0)) { return; } Set<Object> set = null; if (comparator == null) { set = new TreeSet<Object>(); } else { set = new TreeSet<Object>(comparator); } Iterator<Object> itr = list.iterator(); while (itr.hasNext()) { Object obj = itr.next(); if (set.contains(obj)) { itr.remove(); } else { set.add(obj); } } } public static List fromArray(Object[] array) { if ((array == null) || (array.length == 0)) { return new ArrayList(); } List list = new ArrayList(array.length); for (int i = 0; i < array.length; i++) { list.add(array[i]); } return list; } public static List fromCollection(Collection c) { if ((c != null) && (c instanceof List)) { return (List)c; } if ((c == null) || (c.size() == 0)) { return new ArrayList(); } List list = new ArrayList(c.size()); Iterator itr = c.iterator(); while (itr.hasNext()) { list.add(itr.next()); } return list; } public static List fromEnumeration(Enumeration enu) { List list = new ArrayList(); while (enu.hasMoreElements()) { Object obj = enu.nextElement(); list.add(obj); } return list; } public static List fromFile(String fileName) throws IOException { return fromFile(new File(fileName)); } public static List fromFile(File file) throws IOException { List list = new ArrayList(); BufferedReader br = new BufferedReader(new FileReader(file)); String s = StringPool.BLANK; while ((s = br.readLine()) != null) { list.add(s); } br.close(); return list; } public static List fromString(String s) { return fromArray(StringUtil.split(s, StringPool.NEW_LINE)); } public static List sort(List list) { return sort(list, null); } public static List sort(List list, Comparator comparator) { // if (list instanceof UnmodifiableList) { // list = copy(list); // } // // Collections.sort(list, comparator); return list; } public static List subList(List list, int start, int end) { List newList = new ArrayList(); int normalizedSize = list.size() - 1; if ((start < 0) || (start > normalizedSize) || (end < 0) || (start > end)) { return newList; } for (int i = start; i < end && i <= normalizedSize; i++) { newList.add(list.get(i)); } return newList; } public static List<Boolean> toList(boolean[] array) { if ((array == null) || (array.length == 0)) { return Collections.EMPTY_LIST; } List<Boolean> list = new ArrayList<Boolean>(array.length); for (boolean value : array) { list.add(value); } return list; } public static List<Double> toList(double[] array) { if ((array == null) || (array.length == 0)) { return Collections.EMPTY_LIST; } List<Double> list = new ArrayList<Double>(array.length); for (double value : array) { list.add(value); } return list; } public static List<Float> toList(float[] array) { if ((array == null) || (array.length == 0)) { return Collections.EMPTY_LIST; } List<Float> list = new ArrayList<Float>(array.length); for (float value : array) { list.add(value); } return list; } public static List<Integer> toList(int[] array) { if ((array == null) || (array.length == 0)) { return Collections.EMPTY_LIST; } List<Integer> list = new ArrayList<Integer>(array.length); for (int value : array) { list.add(value); } return list; } public static List<Long> toList(long[] array) { if ((array == null) || (array.length == 0)) { return Collections.EMPTY_LIST; } List<Long> list = new ArrayList<Long>(array.length); for (long value : array) { list.add(value); } return list; } public static List<Short> toList(short[] array) { if ((array == null) || (array.length == 0)) { return Collections.EMPTY_LIST; } List<Short> list = new ArrayList<Short>(array.length); for (short value : array) { list.add(value); } return list; } public static List<Boolean> toList(Boolean[] array) { if ((array == null) || (array.length == 0)) { return Collections.EMPTY_LIST; } List<Boolean> list = new ArrayList<Boolean>(array.length); for (Boolean value : array) { list.add(value); } return list; } public static List<Double> toList(Double[] array) { if ((array == null) || (array.length == 0)) { return Collections.EMPTY_LIST; } List<Double> list = new ArrayList<Double>(array.length); for (Double value : array) { list.add(value); } return list; } public static List<Float> toList(Float[] array) { if ((array == null) || (array.length == 0)) { return Collections.EMPTY_LIST; } List<Float> list = new ArrayList<Float>(array.length); for (Float value : array) { list.add(value); } return list; } public static List<Integer> toList(Integer[] array) { if ((array == null) || (array.length == 0)) { return Collections.EMPTY_LIST; } List<Integer> list = new ArrayList<Integer>(array.length); for (Integer value : array) { list.add(value); } return list; } public static List<Long> toList(Long[] array) { if ((array == null) || (array.length == 0)) { return Collections.EMPTY_LIST; } List<Long> list = new ArrayList<Long>(array.length); for (Long value : array) { list.add(value); } return list; } public static List<Short> toList(Short[] array) { if ((array == null) || (array.length == 0)) { return Collections.EMPTY_LIST; } List<Short> list = new ArrayList<Short>(array.length); for (Short value : array) { list.add(value); } return list; } public static List<String> toList(String[] array) { if ((array == null) || (array.length == 0)) { return Collections.EMPTY_LIST; } List<String> list = new ArrayList<String>(array.length); for (String value : array) { list.add(value); } return list; } public static String toString(List list, String param) { return toString(list, param, StringPool.COMMA); } public static String toString(List list, String param, String delimiter) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < list.size(); i++) { Object bean = list.get(i); // Object value = BeanPropertiesUtil.getObject(bean, param); // // if (value == null) { // value = StringPool.BLANK; // } // // sb.append(value.toString()); if ((i + 1) != list.size()) { sb.append(delimiter); } } return sb.toString(); } }
ufoe/Deskera-CRM
bpm-app/modulebuilder/src/main/java/com/krawler/portal/util/ListUtil.java
Java
gpl-3.0
8,286
/** * Copyright (c) 2012, Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.mail.compose; import android.content.Context; import android.text.TextUtils; import android.util.AttributeSet; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.Spinner; import com.android.mail.providers.Account; import com.android.mail.providers.Message; import com.android.mail.providers.ReplyFromAccount; import com.android.mail.utils.AccountUtils; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import java.util.List; public class FromAddressSpinner extends Spinner implements OnItemSelectedListener { private List<Account> mAccounts; private ReplyFromAccount mAccount; private final List<ReplyFromAccount> mReplyFromAccounts = Lists.newArrayList(); private OnAccountChangedListener mAccountChangedListener; public FromAddressSpinner(Context context) { this(context, null); } public FromAddressSpinner(Context context, AttributeSet set) { super(context, set); } public void setCurrentAccount(ReplyFromAccount account) { mAccount = account; selectCurrentAccount(); } private void selectCurrentAccount() { if (mAccount == null) { return; } int currentIndex = 0; for (ReplyFromAccount acct : mReplyFromAccounts) { if (TextUtils.equals(mAccount.name, acct.name) && TextUtils.equals(mAccount.address, acct.address)) { setSelection(currentIndex, true); break; } currentIndex++; } } public ReplyFromAccount getMatchingReplyFromAccount(String accountString) { if (!TextUtils.isEmpty(accountString)) { for (ReplyFromAccount acct : mReplyFromAccounts) { if (accountString.equals(acct.address)) { return acct; } } } return null; } public ReplyFromAccount getCurrentAccount() { return mAccount; } /** * @param action Action being performed; if this is COMPOSE, show all * accounts. Otherwise, show just the account this was launched * with. * @param currentAccount Account used to launch activity. * @param syncingAccounts */ public void initialize(int action, Account currentAccount, Account[] syncingAccounts, Message refMessage) { final List<Account> accounts = AccountUtils.mergeAccountLists(mAccounts, syncingAccounts, true /* prioritizeAccountList */); if (action == ComposeActivity.COMPOSE) { mAccounts = accounts; } else { // First assume that we are going to use the current account as the reply account Account replyAccount = currentAccount; if (refMessage != null && refMessage.accountUri != null) { // This is a reply or forward of a message access through the "combined" account. // We want to make sure that the real account is in the spinner for (Account account : accounts) { if (account.uri.equals(refMessage.accountUri)) { replyAccount = account; break; } } } mAccounts = ImmutableList.of(replyAccount); } initFromSpinner(); } @VisibleForTesting protected void initFromSpinner() { // If there are not yet any accounts in the cached synced accounts // because this is the first time mail was opened, and it was opened // directly to the compose activity, don't bother populating the reply // from spinner yet. if (mAccounts == null || mAccounts.size() == 0) { return; } FromAddressSpinnerAdapter adapter = new FromAddressSpinnerAdapter(getContext()); mReplyFromAccounts.clear(); for (Account account : mAccounts) { mReplyFromAccounts.addAll(account.getReplyFroms()); } adapter.addAccounts(mReplyFromAccounts); setAdapter(adapter); selectCurrentAccount(); setOnItemSelectedListener(this); } public List<ReplyFromAccount> getReplyFromAccounts() { return mReplyFromAccounts; } public void setOnAccountChangedListener(OnAccountChangedListener listener) { mAccountChangedListener = listener; } @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { ReplyFromAccount selection = (ReplyFromAccount) getItemAtPosition(position); if (!selection.address.equals(mAccount.address)) { mAccount = selection; mAccountChangedListener.onAccountChanged(); } } @Override public void onNothingSelected(AdapterView<?> parent) { // Do nothing. } /** * Classes that want to know when a different account in the * FromAddressSpinner has been selected should implement this interface. * Note: if the user chooses the same account as the one that has already * been selected, this method will not be called. */ public static interface OnAccountChangedListener { public void onAccountChanged(); } }
s20121035/rk3288_android5.1_repo
packages/apps/UnifiedEmail/src/com/android/mail/compose/FromAddressSpinner.java
Java
gpl-3.0
6,076
/* * CPAchecker is a tool for configurable software verification. * This file is part of CPAchecker. * * Copyright (C) 2007-2014 Dirk Beyer * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * * CPAchecker web page: * http://cpachecker.sosy-lab.org */ package org.sosy_lab.cpachecker.cfa.model; import org.sosy_lab.cpachecker.cfa.ast.FileLocation; import org.sosy_lab.cpachecker.cfa.ast.ADeclaration; import com.google.common.base.Optional; public class ADeclarationEdge extends AbstractCFAEdge { protected final ADeclaration declaration; protected ADeclarationEdge(final String pRawSignature, final FileLocation pFileLocation, final CFANode pPredecessor, final CFANode pSuccessor, final ADeclaration pDeclaration) { super(pRawSignature, pFileLocation, pPredecessor, pSuccessor); declaration = pDeclaration; } @Override public CFAEdgeType getEdgeType() { return CFAEdgeType.DeclarationEdge; } public ADeclaration getDeclaration() { return declaration; } @Override public Optional<? extends ADeclaration> getRawAST() { return Optional.of(declaration); } @Override public String getCode() { return declaration.toASTString(); } }
nishanttotla/predator
cpachecker/src/org/sosy_lab/cpachecker/cfa/model/ADeclarationEdge.java
Java
gpl-3.0
1,757
/** * Copyright (C) 2015 Envidatec GmbH <info@envidatec.com> * * This file is part of JECommons. * * JECommons 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 in version 3. * * JECommons 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 * JECommons. If not, see <http://www.gnu.org/licenses/>. * * JECommons is part of the OpenJEVis project, further project information are * published at <http://www.OpenJEVis.org/>. */ package org.jevis.commons.dataprocessing.v2; import java.util.List; /** * * @author Florian Simon */ public interface Task { void setDataProcessor(Function dp); Function getDataProcessor(); void setDependency(List<Task> dps); List<Task> getDependency(); Result getResult(); }
AIT-JEVis/JECommons
src/main/java/org/jevis/commons/dataprocessing/v2/Task.java
Java
gpl-3.0
1,111
package org.ovirt.engine.core.bll.transport; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.ovirt.engine.core.bll.Backend; import org.ovirt.engine.core.common.businessentities.VDS; import org.ovirt.engine.core.common.businessentities.VdsProtocol; import org.ovirt.engine.core.common.businessentities.VdsStatic; import org.ovirt.engine.core.common.config.Config; import org.ovirt.engine.core.common.config.ConfigValues; import org.ovirt.engine.core.common.interfaces.FutureVDSCall; import org.ovirt.engine.core.common.vdscommands.FutureVDSCommandType; import org.ovirt.engine.core.common.vdscommands.TimeBoundPollVDSCommandParameters; import org.ovirt.engine.core.common.vdscommands.VDSReturnValue; import org.ovirt.engine.core.dal.dbbroker.DbFacade; import org.ovirt.engine.core.utils.transaction.TransactionMethod; import org.ovirt.engine.core.utils.transaction.TransactionSupport; import org.ovirt.engine.core.vdsbroker.ResourceManager; /** * We need to detect whether vdsm supports jsonrpc or only xmlrpc. It is confusing to users * when they have cluster 3.5+ and connect to vdsm <3.5 which supports only xmlrpc. * In order to present version information in such situation we need fallback to xmlrpc. * */ public class ProtocolDetector { private Integer connectionTimeout = null; private Integer retryAttempts = null; private VDS vds; public ProtocolDetector(VDS vds) { this.vds = vds; this.retryAttempts = Config.<Integer> getValue(ConfigValues.ProtocolFallbackRetries); this.connectionTimeout = Config.<Integer> getValue(ConfigValues.ProtocolFallbackTimeoutInMilliSeconds); } /** * Attempts to connect to vdsm using a proxy from {@code VdsManager} for a host. * There are 3 attempts to connect. * * @return <code>true</code> if connected or <code>false</code> if connection failed. */ public boolean attemptConnection() { boolean connected = false; try { for (int i = 0; i < this.retryAttempts; i++) { long timeout = Config.<Integer> getValue(ConfigValues.SetupNetworksPollingTimeout); FutureVDSCall<VDSReturnValue> task = Backend.getInstance().getResourceManager().runFutureVdsCommand(FutureVDSCommandType.TimeBoundPoll, new TimeBoundPollVDSCommandParameters(vds.getId(), timeout, TimeUnit.SECONDS)); VDSReturnValue returnValue = task.get(timeout, TimeUnit.SECONDS); connected = returnValue.getSucceeded(); if (connected) { break; } Thread.sleep(this.connectionTimeout); } } catch (TimeoutException | InterruptedException ignored) { } return connected; } /** * Stops {@code VdsManager} for a host. */ public void stopConnection() { ResourceManager.getInstance().RemoveVds(this.vds.getId()); } /** * Fall back the protocol and attempts the connection {@link ProtocolDetector#attemptConnection()}. * * @return <code>true</code> if connected or <code>false</code> if connection failed. */ public boolean attemptFallbackProtocol() { vds.setProtocol(VdsProtocol.XML); ResourceManager.getInstance().AddVds(vds, false); return attemptConnection(); } /** * Updates DB with fall back protocol (xmlrpc). */ public void setFallbackProtocol() { final VdsStatic vdsStatic = this.vds.getStaticData(); vdsStatic.setProtocol(VdsProtocol.XML); TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { DbFacade.getInstance().getVdsStaticDao().update(vdsStatic); return null; } }); } }
jtux270/translate
ovirt/backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/transport/ProtocolDetector.java
Java
gpl-3.0
3,963
/* * This file is part of eduVPN. * * eduVPN 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. * * eduVPN 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 eduVPN. If not, see <http://www.gnu.org/licenses/>. */ package nl.eduvpn.app.adapter; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import nl.eduvpn.app.R; import nl.eduvpn.app.adapter.viewholder.MessageViewHolder; import nl.eduvpn.app.entity.message.Maintenance; import nl.eduvpn.app.entity.message.Message; import nl.eduvpn.app.entity.message.Notification; import nl.eduvpn.app.utils.FormattingUtils; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Adapter for serving the message views inside a list. * Created by Daniel Zolnai on 2016-10-19. */ public class MessagesAdapter extends RecyclerView.Adapter<MessageViewHolder> { private List<Message> _userMessages; private List<Message> _systemMessages; private List<Message> _mergedList = new ArrayList<>(); private LayoutInflater _layoutInflater; public void setUserMessages(List<Message> userMessages) { _userMessages = userMessages; _regenerateList(); } public void setSystemMessages(List<Message> systemMessages) { _systemMessages = systemMessages; _regenerateList(); } private void _regenerateList() { _mergedList.clear(); if (_userMessages != null) { _mergedList.addAll(_userMessages); } if (_systemMessages != null) { _mergedList.addAll(_systemMessages); } Collections.sort(_mergedList); notifyDataSetChanged(); } @Override public MessageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { if (_layoutInflater == null) { _layoutInflater = LayoutInflater.from(parent.getContext()); } return new MessageViewHolder(_layoutInflater.inflate(R.layout.list_item_message, parent, false)); } @Override public void onBindViewHolder(MessageViewHolder holder, int position) { Message message = _mergedList.get(position); if (message instanceof Maintenance) { holder.messageIcon.setVisibility(View.VISIBLE); Context context = holder.messageText.getContext(); String maintenanceText = FormattingUtils.getMaintenanceText(context, (Maintenance)message); holder.messageText.setText(maintenanceText); } else if (message instanceof Notification) { holder.messageIcon.setVisibility(View.GONE); holder.messageText.setText(((Notification)message).getContent()); } else { throw new RuntimeException("Unexpected message type!"); } } @Override public int getItemCount() { return _mergedList.size(); } }
dzolnai/android
app/src/main/java/nl/eduvpn/app/adapter/MessagesAdapter.java
Java
gpl-3.0
3,444
/* * Copyright (c) 2013 The Interedition Development Group. * * This file is part of CollateX. * * CollateX 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. * * CollateX 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 CollateX. If not, see <http://www.gnu.org/licenses/>. */ package eu.interedition.text.xml; import com.google.common.base.Objects; import javax.xml.XMLConstants; import javax.xml.stream.XMLStreamReader; import java.util.Stack; /** * @author <a href="http://gregor.middell.net/" title="Homepage">Gregor Middell</a> */ public class WhitespaceCompressor extends ConversionFilter { private final Stack<Boolean> spacePreservationContext = new Stack<Boolean>(); private final WhitespaceStrippingContext whitespaceStrippingContext; private char lastChar = ' '; public WhitespaceCompressor(WhitespaceStrippingContext whitespaceStrippingContext) { this.whitespaceStrippingContext = whitespaceStrippingContext; } @Override public void start() { spacePreservationContext.clear(); whitespaceStrippingContext.reset(); lastChar = ' '; } @Override protected void onXMLEvent(XMLStreamReader reader) { whitespaceStrippingContext.onXMLEvent(reader); if (reader.isStartElement()) { spacePreservationContext.push(spacePreservationContext.isEmpty() ? false : spacePreservationContext.peek()); final Object xmlSpace = reader.getAttributeValue(XMLConstants.XML_NS_URI, "space"); if (xmlSpace != null) { spacePreservationContext.pop(); spacePreservationContext.push("preserve".equalsIgnoreCase(xmlSpace.toString())); } } else if (reader.isEndElement()) { spacePreservationContext.pop(); } } String compress(String text) { final StringBuilder compressed = new StringBuilder(); final boolean preserveSpace = Objects.firstNonNull(spacePreservationContext.peek(), false); for (int cc = 0, length = text.length(); cc < length; cc++) { char currentChar = text.charAt(cc); if (!preserveSpace && Character.isWhitespace(currentChar) && (Character.isWhitespace(lastChar) || whitespaceStrippingContext.isInContainerElement())) { continue; } if (currentChar == '\n' || currentChar == '\r') { currentChar = ' '; } compressed.append(lastChar = currentChar); } return compressed.toString(); } }
faustedition/text
text-core/src/main/java/eu/interedition/text/xml/WhitespaceCompressor.java
Java
gpl-3.0
3,002
/* * Copyright (C) 2016-2021 David Rubio Escares / Kodehawa * * Mantaro 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. * Mantaro 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 Mantaro. If not, see http://www.gnu.org/licenses/ */ package net.kodehawa.mantarobot.commands.currency.profile; import javax.imageio.ImageIO; import java.awt.Color; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.awt.image.WritableRaster; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; public class BadgeUtils { public static byte[] applyBadge(byte[] avatarBytes, byte[] badgeBytes, int startX, int startY, boolean allWhite) { BufferedImage avatar; BufferedImage badge; try { avatar = ImageIO.read(new ByteArrayInputStream(avatarBytes)); badge = ImageIO.read(new ByteArrayInputStream(badgeBytes)); } catch (IOException impossible) { throw new AssertionError(impossible); } WritableRaster raster = badge.getRaster(); if (allWhite) { for (int xx = 0, width = badge.getWidth(); xx < width; xx++) { for (int yy = 0, height = badge.getHeight(); yy < height; yy++) { int[] pixels = raster.getPixel(xx, yy, (int[]) null); pixels[0] = 255; pixels[1] = 255; pixels[2] = 255; pixels[3] = pixels[3] == 255 ? 165 : 0; raster.setPixel(xx, yy, pixels); } } } BufferedImage res = new BufferedImage(128, 128, BufferedImage.TYPE_INT_ARGB); int circleCenterX = 88, circleCenterY = 88; int width = 32, height = 32; int circleRadius = 40; Graphics2D g2d = res.createGraphics(); g2d.drawImage(avatar, 0, 0, 128, 128, null); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.setColor(new Color(0, 0, 165, 165)); g2d.fillOval(circleCenterX, circleCenterY, circleRadius, circleRadius); g2d.drawImage(badge, startX, startY, width, height, null); g2d.dispose(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { ImageIO.write(res, "png", baos); } catch (IOException e) { throw new AssertionError(e); } return baos.toByteArray(); } }
Mantaro/MantaroBot
src/main/java/net/kodehawa/mantarobot/commands/currency/profile/BadgeUtils.java
Java
gpl-3.0
2,976
package monitor; public interface RunnableWithResult<T> { public T run() ; }
erseco/ugr_sistemas_concurrentes_distribuidos
Practica_02_monitores/monitor/RunnableWithResult.java
Java
gpl-3.0
84
package cern.colt.matrix.tlong.impl; public class SparseRCMLongMatrix2DViewTest extends SparseRCMLongMatrix2DTest { public SparseRCMLongMatrix2DViewTest(String arg0) { super(arg0); } protected void createMatrices() throws Exception { A = new SparseRCMLongMatrix2D(NCOLUMNS, NROWS).viewDice(); B = new SparseRCMLongMatrix2D(NCOLUMNS, NROWS).viewDice(); Bt = new SparseRCMLongMatrix2D(NROWS, NCOLUMNS).viewDice(); } }
Shappiro/GEOFRAME
PROJECTS/oms3.proj.richards1d/src/JAVA/parallelcolt-code/test/cern/colt/matrix/tlong/impl/SparseRCMLongMatrix2DViewTest.java
Java
gpl-3.0
483
package handling.handlers; import java.awt.Point; import client.MapleClient; import handling.PacketHandler; import handling.RecvPacketOpcode; import server.MaplePortal; import tools.data.LittleEndianAccessor; public class UseInnerPortalHandler { @PacketHandler(opcode = RecvPacketOpcode.USE_INNER_PORTAL) public static void handle(MapleClient c, LittleEndianAccessor lea) { lea.skip(1); if (c.getPlayer() == null || c.getPlayer().getMap() == null) { return; } String portalName = lea.readMapleAsciiString(); MaplePortal portal = c.getPlayer().getMap().getPortal(portalName); if (portal == null) { return; } //That "22500" should not be hard coded in this manner if (portal.getPosition().distanceSq(c.getPlayer().getTruePosition()) > 22500.0D && !c.getPlayer().isGM()) { return; } int toX = lea.readShort(); int toY = lea.readShort(); //Are there not suppose to be checks here? Can players not just PE any x and y value they want? c.getPlayer().getMap().movePlayer(c.getPlayer(), new Point(toX, toY)); c.getPlayer().checkFollow(); } }
Maxcloud/Mushy
src/handling/handlers/UseInnerPortalHandler.java
Java
gpl-3.0
1,090
package net.minecraft.inventory; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemArmor; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.CraftingManager; import net.minecraft.util.IIcon; // CraftBukkit start import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.network.play.server.S2FPacketSetSlot; import org.bukkit.craftbukkit.inventory.CraftInventoryCrafting; import org.bukkit.craftbukkit.inventory.CraftInventoryView; // CraftBukkit end public class ContainerPlayer extends Container { public InventoryCrafting craftMatrix = new InventoryCrafting(this, 2, 2); public IInventory craftResult = new InventoryCraftResult(); public boolean isLocalWorld; private final EntityPlayer thePlayer; // CraftBukkit start private CraftInventoryView bukkitEntity = null; private InventoryPlayer player; // CraftBukkit end private static final String __OBFID = "CL_00001754"; public ContainerPlayer(final InventoryPlayer p_i1819_1_, boolean p_i1819_2_, EntityPlayer p_i1819_3_) { this.isLocalWorld = p_i1819_2_; this.thePlayer = p_i1819_3_; this.craftResult = new InventoryCraftResult(); // CraftBukkit - moved to before InventoryCrafting construction this.craftMatrix = new InventoryCrafting(this, 2, 2, p_i1819_1_.player); // CraftBukkit - pass player this.craftMatrix.resultInventory = this.craftResult; // CraftBukkit - let InventoryCrafting know about its result slot this.player = p_i1819_1_; // CraftBukkit - save player this.addSlotToContainer(new SlotCrafting(p_i1819_1_.player, this.craftMatrix, this.craftResult, 0, 144, 36)); int i; int j; for (i = 0; i < 2; ++i) { for (j = 0; j < 2; ++j) { this.addSlotToContainer(new Slot(this.craftMatrix, j + i * 2, 88 + j * 18, 26 + i * 18)); } } for (i = 0; i < 4; ++i) { final int k = i; this.addSlotToContainer(new Slot(p_i1819_1_, p_i1819_1_.getSizeInventory() - 1 - i, 8, 8 + i * 18) { private static final String __OBFID = "CL_00001755"; public int getSlotStackLimit() { return 1; } public boolean isItemValid(ItemStack p_75214_1_) { if (p_75214_1_ == null) return false; return p_75214_1_.getItem().isValidArmor(p_75214_1_, k, thePlayer); } @SideOnly(Side.CLIENT) public IIcon getBackgroundIconIndex() { return ItemArmor.func_94602_b(k); } }); } for (i = 0; i < 3; ++i) { for (j = 0; j < 9; ++j) { this.addSlotToContainer(new Slot(p_i1819_1_, j + (i + 1) * 9, 8 + j * 18, 84 + i * 18)); } } for (i = 0; i < 9; ++i) { this.addSlotToContainer(new Slot(p_i1819_1_, i, 8 + i * 18, 142)); } // this.onCraftMatrixChanged(this.craftMatrix); // CraftBukkit - unneeded since it just sets result slot to empty } public void onCraftMatrixChanged(IInventory p_75130_1_) { // CraftBukkit start (Note: the following line would cause an error if called during construction) CraftingManager.getInstance().lastCraftView = getBukkitView(); ItemStack craftResult = CraftingManager.getInstance().findMatchingRecipe(this.craftMatrix, this.thePlayer.worldObj); this.craftResult.setInventorySlotContents(0, craftResult); if (super.crafters.size() < 1) { return; } EntityPlayerMP player = (EntityPlayerMP) super.crafters.get(0); // TODO: Is this _always_ correct? Seems like it. player.playerNetServerHandler.sendPacket(new S2FPacketSetSlot(player.openContainer.windowId, 0, craftResult)); // CraftBukkit end } public void onContainerClosed(EntityPlayer p_75134_1_) { super.onContainerClosed(p_75134_1_); for (int i = 0; i < 4; ++i) { ItemStack itemstack = this.craftMatrix.getStackInSlotOnClosing(i); if (itemstack != null) { p_75134_1_.dropPlayerItemWithRandomChoice(itemstack, false); } } this.craftResult.setInventorySlotContents(0, (ItemStack)null); } public boolean canInteractWith(EntityPlayer p_75145_1_) { return true; } public ItemStack transferStackInSlot(EntityPlayer p_82846_1_, int p_82846_2_) { ItemStack itemstack = null; Slot slot = (Slot)this.inventorySlots.get(p_82846_2_); if (slot != null && slot.getHasStack()) { ItemStack itemstack1 = slot.getStack(); itemstack = itemstack1.copy(); if (p_82846_2_ == 0) { if (!this.mergeItemStack(itemstack1, 9, 45, true)) { return null; } slot.onSlotChange(itemstack1, itemstack); } else if (p_82846_2_ >= 1 && p_82846_2_ < 5) { if (!this.mergeItemStack(itemstack1, 9, 45, false)) { return null; } } else if (p_82846_2_ >= 5 && p_82846_2_ < 9) { if (!this.mergeItemStack(itemstack1, 9, 45, false)) { return null; } } else if (itemstack.getItem() instanceof ItemArmor && !((Slot)this.inventorySlots.get(5 + ((ItemArmor)itemstack.getItem()).armorType)).getHasStack()) { int j = 5 + ((ItemArmor)itemstack.getItem()).armorType; if (!this.mergeItemStack(itemstack1, j, j + 1, false)) { return null; } } else if (p_82846_2_ >= 9 && p_82846_2_ < 36) { if (!this.mergeItemStack(itemstack1, 36, 45, false)) { return null; } } else if (p_82846_2_ >= 36 && p_82846_2_ < 45) { if (!this.mergeItemStack(itemstack1, 9, 36, false)) { return null; } } else if (!this.mergeItemStack(itemstack1, 9, 45, false)) { return null; } if (itemstack1.stackSize == 0) { slot.putStack((ItemStack)null); } else { slot.onSlotChanged(); } if (itemstack1.stackSize == itemstack.stackSize) { return null; } slot.onPickupFromSlot(p_82846_1_, itemstack1); } return itemstack; } public boolean func_94530_a(ItemStack p_94530_1_, Slot p_94530_2_) { return p_94530_2_.inventory != this.craftResult && super.func_94530_a(p_94530_1_, p_94530_2_); } // CraftBukkit start public CraftInventoryView getBukkitView() { if (bukkitEntity != null) { return bukkitEntity; } CraftInventoryCrafting inventory = new CraftInventoryCrafting(this.craftMatrix, this.craftResult); bukkitEntity = new CraftInventoryView(this.player.player.getBukkitEntity(), inventory, this); return bukkitEntity; } // CraftBukkit end }
Scrik/Cauldron-1
eclipse/cauldron/src/main/java/net/minecraft/inventory/ContainerPlayer.java
Java
gpl-3.0
7,916
package com.app.server.repository; import com.athena.server.repository.SearchInterface; import com.athena.annotation.Complexity; import com.athena.annotation.SourceCodeAuthorClass; import com.athena.framework.server.exception.repository.SpartanPersistenceException; import java.util.List; import com.athena.framework.server.exception.biz.SpartanConstraintViolationException; @SourceCodeAuthorClass(createdBy = "john.doe", updatedBy = "", versionNumber = "1", comments = "Repository for Title Master table Entity", complexity = Complexity.LOW) public interface TitleRepository<T> extends SearchInterface { public List<T> findAll() throws SpartanPersistenceException; public T save(T entity) throws SpartanPersistenceException; public List<T> save(List<T> entity) throws SpartanPersistenceException; public void delete(String id) throws SpartanPersistenceException; public void update(T entity) throws SpartanConstraintViolationException, SpartanPersistenceException; public void update(List<T> entity) throws SpartanPersistenceException; public T findById(String titleId) throws Exception, SpartanPersistenceException; }
applifireAlgo/appDemoApps201115
bloodbank/src/main/java/com/app/server/repository/TitleRepository.java
Java
gpl-3.0
1,156
package cn.nukkit.math; /** * author: MagicDroidX * Nukkit Project */ public class Vector3 implements Cloneable { public double x; public double y; public double z; public Vector3() { this(0, 0, 0); } public Vector3(double x) { this(x, 0, 0); } public Vector3(double x, double y) { this(x, y, 0); } public Vector3(double x, double y, double z) { this.x = x; this.y = y; this.z = z; } public double getX() { return this.x; } public double getY() { return this.y; } public double getZ() { return this.z; } public int getFloorX() { return (int) Math.floor(this.x); } public int getFloorY() { return (int) Math.floor(this.y); } public int getFloorZ() { return (int) Math.floor(this.z); } public double getRight() { return this.x; } public double getUp() { return this.y; } public double getForward() { return this.z; } public double getSouth() { return this.x; } public double getWest() { return this.z; } public Vector3 add(double x) { return this.add(x, 0, 0); } public Vector3 add(double x, double y) { return this.add(x, y, 0); } public Vector3 add(double x, double y, double z) { return new Vector3(this.x + x, this.y + y, this.z + z); } public Vector3 add(Vector3 x) { return new Vector3(this.x + x.getX(), this.y + x.getY(), this.z + x.getZ()); } public Vector3 subtract() { return this.subtract(0, 0, 0); } public Vector3 subtract(double x) { return this.subtract(x, 0, 0); } public Vector3 subtract(double x, double y) { return this.subtract(x, y, 0); } public Vector3 subtract(double x, double y, double z) { return this.add(-x, -y, -z); } public Vector3 subtract(Vector3 x) { return this.add(-x.getX(), -x.getY(), -x.getZ()); } public Vector3 multiply(double number) { return new Vector3(this.x * number, this.y * number, this.z * number); } public Vector3 divide(double number) { return new Vector3(this.x / number, this.y / number, this.z / number); } public Vector3 ceil() { return new Vector3((int) Math.ceil(this.x), (int) Math.ceil(this.y), (int) Math.ceil(this.z)); } public Vector3 floor() { return new Vector3(this.getFloorX(), this.getFloorY(), this.getFloorZ()); } public Vector3 round() { return new Vector3(Math.round(this.x), Math.round(this.y), Math.round(this.z)); } public Vector3 abs() { return new Vector3((int) Math.abs(this.x), (int) Math.abs(this.y), (int) Math.abs(this.z)); } public Vector3 getSide(BlockFace face) { return this.getSide(face, 1); } public Vector3 getSide(BlockFace face, int step) { return new Vector3(this.getX() + face.getXOffset() * step, this.getY() + face.getYOffset() * step, this.getZ() + face.getZOffset() * step); } public Vector3 up() { return up(1); } public Vector3 up(int step) { return getSide(BlockFace.UP, step); } public Vector3 down() { return down(1); } public Vector3 down(int step) { return getSide(BlockFace.DOWN, step); } public Vector3 north() { return north(1); } public Vector3 north(int step) { return getSide(BlockFace.NORTH, step); } public Vector3 south() { return south(1); } public Vector3 south(int step) { return getSide(BlockFace.SOUTH, step); } public Vector3 east() { return east(1); } public Vector3 east(int step) { return getSide(BlockFace.EAST, step); } public Vector3 west() { return west(1); } public Vector3 west(int step) { return getSide(BlockFace.WEST, step); } public double distance(Vector3 pos) { return Math.sqrt(this.distanceSquared(pos)); } public double distanceSquared(Vector3 pos) { return Math.pow(this.x - pos.x, 2) + Math.pow(this.y - pos.y, 2) + Math.pow(this.z - pos.z, 2); } public double maxPlainDistance() { return this.maxPlainDistance(0, 0); } public double maxPlainDistance(double x) { return this.maxPlainDistance(x, 0); } public double maxPlainDistance(double x, double z) { return Math.max(Math.abs(this.x - x), Math.abs(this.z - z)); } public double maxPlainDistance(Vector2 vector) { return this.maxPlainDistance(vector.x, vector.y); } public double maxPlainDistance(Vector3 x) { return this.maxPlainDistance(x.x, x.z); } public double length() { return Math.sqrt(this.lengthSquared()); } public double lengthSquared() { return this.x * this.x + this.y * this.y + this.z * this.z; } public Vector3 normalize() { double len = this.lengthSquared(); if (len > 0) { return this.divide(Math.sqrt(len)); } return new Vector3(0, 0, 0); } public double dot(Vector3 v) { return this.x * v.x + this.y * v.y + this.z * v.z; } public Vector3 cross(Vector3 v) { return new Vector3( this.y * v.z - this.z * v.y, this.z * v.x - this.x * v.z, this.x * v.y - this.y * v.x ); } /** * Returns a new vector with x value equal to the second parameter, along the line between this vector and the * passed in vector, or null if not possible. */ public Vector3 getIntermediateWithXValue(Vector3 v, double x) { double xDiff = v.x - this.x; double yDiff = v.y - this.y; double zDiff = v.z - this.z; if (xDiff * xDiff < 0.0000001) { return null; } double f = (x - this.x) / xDiff; if (f < 0 || f > 1) { return null; } else { return new Vector3(this.x + xDiff * f, this.y + yDiff * f, this.z + zDiff * f); } } /** * Returns a new vector with y value equal to the second parameter, along the line between this vector and the * passed in vector, or null if not possible. */ public Vector3 getIntermediateWithYValue(Vector3 v, double y) { double xDiff = v.x - this.x; double yDiff = v.y - this.y; double zDiff = v.z - this.z; if (yDiff * yDiff < 0.0000001) { return null; } double f = (y - this.y) / yDiff; if (f < 0 || f > 1) { return null; } else { return new Vector3(this.x + xDiff * f, this.y + yDiff * f, this.z + zDiff * f); } } /** * Returns a new vector with z value equal to the second parameter, along the line between this vector and the * passed in vector, or null if not possible. */ public Vector3 getIntermediateWithZValue(Vector3 v, double z) { double xDiff = v.x - this.x; double yDiff = v.y - this.y; double zDiff = v.z - this.z; if (zDiff * zDiff < 0.0000001) { return null; } double f = (z - this.z) / zDiff; if (f < 0 || f > 1) { return null; } else { return new Vector3(this.x + xDiff * f, this.y + yDiff * f, this.z + zDiff * f); } } public Vector3 setComponents(double x, double y, double z) { this.x = x; this.y = y; this.z = z; return this; } @Override public String toString() { return "Vector3(x=" + this.x + ",y=" + this.y + ",z=" + this.z + ")"; } @Override public boolean equals(Object obj) { if (!(obj instanceof Vector3)) { return false; } Vector3 other = (Vector3) obj; return this.x == other.x && this.y == other.y && this.z == other.z; } @Override public int hashCode() { int hash = 7; hash = 79 * hash + (int) (Double.doubleToLongBits(this.x) ^ Double.doubleToLongBits(this.x) >>> 32); hash = 79 * hash + (int) (Double.doubleToLongBits(this.y) ^ Double.doubleToLongBits(this.y) >>> 32); hash = 79 * hash + (int) (Double.doubleToLongBits(this.z) ^ Double.doubleToLongBits(this.z) >>> 32); return hash; } public int rawHashCode() { return super.hashCode(); } @Override public Vector3 clone() { try { return (Vector3) super.clone(); } catch (CloneNotSupportedException e) { return null; } } public Vector3f asVector3f() { return new Vector3f((float) this.x, (float) this.y, (float) this.z); } public BlockVector3 asBlockVector3() { return new BlockVector3(this.getFloorX(), this.getFloorY(), this.getFloorZ()); } }
JupiterDevelopmentTeam/JupiterDevelopmentTeam
src/main/java/cn/nukkit/math/Vector3.java
Java
gpl-3.0
9,009
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package VerilogCompiler.SyntacticTree; import VerilogCompiler.SemanticCheck.ErrorHandler; import VerilogCompiler.SemanticCheck.ExpressionType; import VerilogCompiler.SyntacticTree.Expressions.Expression; /** * * @author Néstor A. Bermúdez < nestor.bermudezs@gmail.com > */ public class Range extends VNode { Expression minValue; Expression maxValue; public Range(Expression minValue, Expression maxValue, int line, int column) { super(line, column); this.minValue = minValue; this.maxValue = maxValue; } public Expression getMinValue() { return minValue; } public void setMinValue(Expression minValue) { this.minValue = minValue; } public Expression getMaxValue() { return maxValue; } public void setMaxValue(Expression maxValue) { this.maxValue = maxValue; } @Override public String toString() { return String.format("[%s:%s]", this.minValue, this.maxValue); } @Override public ExpressionType validateSemantics() { ExpressionType minReturnType = minValue.validateSemantics(); ExpressionType maxReturnType = maxValue.validateSemantics(); if (minReturnType != ExpressionType.INTEGER || maxReturnType != ExpressionType.INTEGER) { ErrorHandler.getInstance().handleError(line, column, "range min and max value must be integer"); } return null; } @Override public VNode getCopy() { return new Range((Expression)minValue.getCopy(), (Expression)maxValue.getCopy(), line, column); } }
CastellarFrank/ArchSim
src/VerilogCompiler/SyntacticTree/Range.java
Java
gpl-3.0
1,723
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Don't edit this file! It is auto-generated by frameworks/rs/api/gen_runtime. package android.renderscript.cts; import android.renderscript.Allocation; import android.renderscript.RSRuntimeException; import android.renderscript.Element; public class TestAsin extends RSBaseCompute { private ScriptC_TestAsin script; private ScriptC_TestAsinRelaxed scriptRelaxed; @Override protected void setUp() throws Exception { super.setUp(); script = new ScriptC_TestAsin(mRS); scriptRelaxed = new ScriptC_TestAsinRelaxed(mRS); } public class ArgumentsFloatFloat { public float inV; public Target.Floaty out; } private void checkAsinFloatFloat() { Allocation inV = createRandomFloatAllocation(mRS, Element.DataType.FLOAT_32, 1, 0x80b5674ff98b5a12l, -1, 1); try { Allocation out = Allocation.createSized(mRS, getElement(mRS, Element.DataType.FLOAT_32, 1), INPUTSIZE); script.forEach_testAsinFloatFloat(inV, out); verifyResultsAsinFloatFloat(inV, out, false); } catch (Exception e) { throw new RSRuntimeException("RenderScript. Can't invoke forEach_testAsinFloatFloat: " + e.toString()); } try { Allocation out = Allocation.createSized(mRS, getElement(mRS, Element.DataType.FLOAT_32, 1), INPUTSIZE); scriptRelaxed.forEach_testAsinFloatFloat(inV, out); verifyResultsAsinFloatFloat(inV, out, true); } catch (Exception e) { throw new RSRuntimeException("RenderScript. Can't invoke forEach_testAsinFloatFloat: " + e.toString()); } } private void verifyResultsAsinFloatFloat(Allocation inV, Allocation out, boolean relaxed) { float[] arrayInV = new float[INPUTSIZE * 1]; inV.copyTo(arrayInV); float[] arrayOut = new float[INPUTSIZE * 1]; out.copyTo(arrayOut); for (int i = 0; i < INPUTSIZE; i++) { for (int j = 0; j < 1 ; j++) { // Extract the inputs. ArgumentsFloatFloat args = new ArgumentsFloatFloat(); args.inV = arrayInV[i]; // Figure out what the outputs should have been. Target target = new Target(relaxed); CoreMathVerifier.computeAsin(args, target); // Validate the outputs. boolean valid = true; if (!args.out.couldBe(arrayOut[i * 1 + j])) { valid = false; } if (!valid) { StringBuilder message = new StringBuilder(); message.append("Input inV: "); message.append(String.format("%14.8g {%8x} %15a", args.inV, Float.floatToRawIntBits(args.inV), args.inV)); message.append("\n"); message.append("Expected output out: "); message.append(args.out.toString()); message.append("\n"); message.append("Actual output out: "); message.append(String.format("%14.8g {%8x} %15a", arrayOut[i * 1 + j], Float.floatToRawIntBits(arrayOut[i * 1 + j]), arrayOut[i * 1 + j])); if (!args.out.couldBe(arrayOut[i * 1 + j])) { message.append(" FAIL"); } message.append("\n"); assertTrue("Incorrect output for checkAsinFloatFloat" + (relaxed ? "_relaxed" : "") + ":\n" + message.toString(), valid); } } } } private void checkAsinFloat2Float2() { Allocation inV = createRandomFloatAllocation(mRS, Element.DataType.FLOAT_32, 2, 0x9e11e5e823f7cce6l, -1, 1); try { Allocation out = Allocation.createSized(mRS, getElement(mRS, Element.DataType.FLOAT_32, 2), INPUTSIZE); script.forEach_testAsinFloat2Float2(inV, out); verifyResultsAsinFloat2Float2(inV, out, false); } catch (Exception e) { throw new RSRuntimeException("RenderScript. Can't invoke forEach_testAsinFloat2Float2: " + e.toString()); } try { Allocation out = Allocation.createSized(mRS, getElement(mRS, Element.DataType.FLOAT_32, 2), INPUTSIZE); scriptRelaxed.forEach_testAsinFloat2Float2(inV, out); verifyResultsAsinFloat2Float2(inV, out, true); } catch (Exception e) { throw new RSRuntimeException("RenderScript. Can't invoke forEach_testAsinFloat2Float2: " + e.toString()); } } private void verifyResultsAsinFloat2Float2(Allocation inV, Allocation out, boolean relaxed) { float[] arrayInV = new float[INPUTSIZE * 2]; inV.copyTo(arrayInV); float[] arrayOut = new float[INPUTSIZE * 2]; out.copyTo(arrayOut); for (int i = 0; i < INPUTSIZE; i++) { for (int j = 0; j < 2 ; j++) { // Extract the inputs. ArgumentsFloatFloat args = new ArgumentsFloatFloat(); args.inV = arrayInV[i * 2 + j]; // Figure out what the outputs should have been. Target target = new Target(relaxed); CoreMathVerifier.computeAsin(args, target); // Validate the outputs. boolean valid = true; if (!args.out.couldBe(arrayOut[i * 2 + j])) { valid = false; } if (!valid) { StringBuilder message = new StringBuilder(); message.append("Input inV: "); message.append(String.format("%14.8g {%8x} %15a", args.inV, Float.floatToRawIntBits(args.inV), args.inV)); message.append("\n"); message.append("Expected output out: "); message.append(args.out.toString()); message.append("\n"); message.append("Actual output out: "); message.append(String.format("%14.8g {%8x} %15a", arrayOut[i * 2 + j], Float.floatToRawIntBits(arrayOut[i * 2 + j]), arrayOut[i * 2 + j])); if (!args.out.couldBe(arrayOut[i * 2 + j])) { message.append(" FAIL"); } message.append("\n"); assertTrue("Incorrect output for checkAsinFloat2Float2" + (relaxed ? "_relaxed" : "") + ":\n" + message.toString(), valid); } } } } private void checkAsinFloat3Float3() { Allocation inV = createRandomFloatAllocation(mRS, Element.DataType.FLOAT_32, 3, 0x9e13af031a12edc4l, -1, 1); try { Allocation out = Allocation.createSized(mRS, getElement(mRS, Element.DataType.FLOAT_32, 3), INPUTSIZE); script.forEach_testAsinFloat3Float3(inV, out); verifyResultsAsinFloat3Float3(inV, out, false); } catch (Exception e) { throw new RSRuntimeException("RenderScript. Can't invoke forEach_testAsinFloat3Float3: " + e.toString()); } try { Allocation out = Allocation.createSized(mRS, getElement(mRS, Element.DataType.FLOAT_32, 3), INPUTSIZE); scriptRelaxed.forEach_testAsinFloat3Float3(inV, out); verifyResultsAsinFloat3Float3(inV, out, true); } catch (Exception e) { throw new RSRuntimeException("RenderScript. Can't invoke forEach_testAsinFloat3Float3: " + e.toString()); } } private void verifyResultsAsinFloat3Float3(Allocation inV, Allocation out, boolean relaxed) { float[] arrayInV = new float[INPUTSIZE * 4]; inV.copyTo(arrayInV); float[] arrayOut = new float[INPUTSIZE * 4]; out.copyTo(arrayOut); for (int i = 0; i < INPUTSIZE; i++) { for (int j = 0; j < 3 ; j++) { // Extract the inputs. ArgumentsFloatFloat args = new ArgumentsFloatFloat(); args.inV = arrayInV[i * 4 + j]; // Figure out what the outputs should have been. Target target = new Target(relaxed); CoreMathVerifier.computeAsin(args, target); // Validate the outputs. boolean valid = true; if (!args.out.couldBe(arrayOut[i * 4 + j])) { valid = false; } if (!valid) { StringBuilder message = new StringBuilder(); message.append("Input inV: "); message.append(String.format("%14.8g {%8x} %15a", args.inV, Float.floatToRawIntBits(args.inV), args.inV)); message.append("\n"); message.append("Expected output out: "); message.append(args.out.toString()); message.append("\n"); message.append("Actual output out: "); message.append(String.format("%14.8g {%8x} %15a", arrayOut[i * 4 + j], Float.floatToRawIntBits(arrayOut[i * 4 + j]), arrayOut[i * 4 + j])); if (!args.out.couldBe(arrayOut[i * 4 + j])) { message.append(" FAIL"); } message.append("\n"); assertTrue("Incorrect output for checkAsinFloat3Float3" + (relaxed ? "_relaxed" : "") + ":\n" + message.toString(), valid); } } } } private void checkAsinFloat4Float4() { Allocation inV = createRandomFloatAllocation(mRS, Element.DataType.FLOAT_32, 4, 0x9e15781e102e0ea2l, -1, 1); try { Allocation out = Allocation.createSized(mRS, getElement(mRS, Element.DataType.FLOAT_32, 4), INPUTSIZE); script.forEach_testAsinFloat4Float4(inV, out); verifyResultsAsinFloat4Float4(inV, out, false); } catch (Exception e) { throw new RSRuntimeException("RenderScript. Can't invoke forEach_testAsinFloat4Float4: " + e.toString()); } try { Allocation out = Allocation.createSized(mRS, getElement(mRS, Element.DataType.FLOAT_32, 4), INPUTSIZE); scriptRelaxed.forEach_testAsinFloat4Float4(inV, out); verifyResultsAsinFloat4Float4(inV, out, true); } catch (Exception e) { throw new RSRuntimeException("RenderScript. Can't invoke forEach_testAsinFloat4Float4: " + e.toString()); } } private void verifyResultsAsinFloat4Float4(Allocation inV, Allocation out, boolean relaxed) { float[] arrayInV = new float[INPUTSIZE * 4]; inV.copyTo(arrayInV); float[] arrayOut = new float[INPUTSIZE * 4]; out.copyTo(arrayOut); for (int i = 0; i < INPUTSIZE; i++) { for (int j = 0; j < 4 ; j++) { // Extract the inputs. ArgumentsFloatFloat args = new ArgumentsFloatFloat(); args.inV = arrayInV[i * 4 + j]; // Figure out what the outputs should have been. Target target = new Target(relaxed); CoreMathVerifier.computeAsin(args, target); // Validate the outputs. boolean valid = true; if (!args.out.couldBe(arrayOut[i * 4 + j])) { valid = false; } if (!valid) { StringBuilder message = new StringBuilder(); message.append("Input inV: "); message.append(String.format("%14.8g {%8x} %15a", args.inV, Float.floatToRawIntBits(args.inV), args.inV)); message.append("\n"); message.append("Expected output out: "); message.append(args.out.toString()); message.append("\n"); message.append("Actual output out: "); message.append(String.format("%14.8g {%8x} %15a", arrayOut[i * 4 + j], Float.floatToRawIntBits(arrayOut[i * 4 + j]), arrayOut[i * 4 + j])); if (!args.out.couldBe(arrayOut[i * 4 + j])) { message.append(" FAIL"); } message.append("\n"); assertTrue("Incorrect output for checkAsinFloat4Float4" + (relaxed ? "_relaxed" : "") + ":\n" + message.toString(), valid); } } } } public void testAsin() { checkAsinFloatFloat(); checkAsinFloat2Float2(); checkAsinFloat3Float3(); checkAsinFloat4Float4(); } }
s20121035/rk3288_android5.1_repo
cts/tests/tests/renderscript/src/android/renderscript/cts/TestAsin.java
Java
gpl-3.0
13,539