code
stringlengths 5
1.04M
| repo_name
stringlengths 7
108
| path
stringlengths 6
299
| language
stringclasses 1
value | license
stringclasses 15
values | size
int64 5
1.04M
|
---|---|---|---|---|---|
/*
* 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 libcore.java.lang;
import junit.framework.TestCase;
public class ClassTest extends TestCase {
interface Foo {
public void foo();
}
interface ParameterizedFoo<T> {
public void foo(T param);
}
interface ParameterizedBar<T> extends ParameterizedFoo<T> {
public void bar(T param);
}
interface ParameterizedBaz extends ParameterizedFoo<String> {
}
public void test_getGenericSuperclass_nullReturnCases() {
// Should always return null for interfaces.
assertNull(Foo.class.getGenericSuperclass());
assertNull(ParameterizedFoo.class.getGenericSuperclass());
assertNull(ParameterizedBar.class.getGenericSuperclass());
assertNull(ParameterizedBaz.class.getGenericSuperclass());
assertNull(Object.class.getGenericSuperclass());
assertNull(void.class.getGenericSuperclass());
assertNull(int.class.getGenericSuperclass());
}
public void test_getGenericSuperclass_returnsObjectForArrays() {
assertSame(Object.class, (new Integer[0]).getClass().getGenericSuperclass());
}
interface A {
public static String name = "A";
}
interface B {
public static String name = "B";
}
class X implements A { }
class Y extends X implements B { }
public void test_getField() {
try {
assertEquals(A.class.getField("name"), X.class.getField("name"));
} catch (NoSuchFieldException e) {
fail("Got exception");
}
try {
assertEquals(B.class.getField("name"), Y.class.getField("name"));
} catch (NoSuchFieldException e) {
fail("Got exception");
}
}
}
| AdmireTheDistance/android_libcore | luni/src/test/java/libcore/java/lang/ClassTest.java | Java | gpl-2.0 | 2,341 |
package org.swingBean.gui.custom.checkboxlist;
import java.awt.Component;
import javax.swing.JCheckBox;
import javax.swing.JList;
import javax.swing.ListCellRenderer;
import javax.swing.UIManager;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
public class CheckListCellRenderer extends JCheckBox implements ListCellRenderer {
protected static Border m_noFocusBorder = new EmptyBorder(1, 1, 1, 1);
public CheckListCellRenderer() {
super();
setOpaque(true);
setBorder(m_noFocusBorder);
}
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
setText(value.toString());
setBackground(isSelected ? list.getSelectionBackground() : list
.getBackground());
setForeground(isSelected ? list.getSelectionForeground() : list
.getForeground());
RowData data = (RowData) value;
setSelected(data.isSelected());
setFont(list.getFont());
setBorder((cellHasFocus) ? UIManager
.getBorder("List.focusCellHighlightBorder") : m_noFocusBorder);
return this;
}
}
| luizbag/swingbean | src/org/swingBean/gui/custom/checkboxlist/CheckListCellRenderer.java | Java | gpl-2.0 | 1,087 |
package ie.headway.app.htdi__companion.camera;
import java.io.IOException;
public interface CameraViewControls extends CameraControls {
void refreshCameraView() throws IOException;
void startPreview() throws IOException;
void stopPreview();
}
| HeadwayApp/HTDI-Companion | app/src/main/java/ie/headway/app/htdi__companion/camera/CameraViewControls.java | Java | gpl-2.0 | 255 |
/*
* jMemorize - Learning made easy (and fun) - A Leitner flashcards tool
* Copyright(C) 2004-2008 Riad Djemili and contributors
*
* 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.util.Calendar;
import java.util.Date;
import java.util.List;
import jmemorize.core.learn.LearnHistory;
import jmemorize.core.learn.LearnHistory.SessionSummary;
import junit.framework.TestCase;
public class LearnHistoryTest extends TestCase
{
private static long MINUTE = 1000*60;
private LearnHistory m_history;
private Date m_date0 = createDate(14, 30);
private Date m_date1 = createDate(14, 50);
private Date m_date2 = createDate(14, 55);
private Date m_date3 = createDate(15, 00);
/* (non-Javadoc)
* @see junit.framework.TestCase#setUp()
*/
protected void setUp() throws Exception
{
m_history = new LearnHistory(null);
}
public void testGetLastSummaryValues()
{
m_history.addSummary(m_date0, m_date1, 2, 0, 1, 1);
SessionSummary summary = m_history.getLastSummary();
assertEquals(2, (int)summary.getPassed());
assertEquals(0, (int)summary.getFailed());
assertEquals(1, (int)summary.getSkipped());
assertEquals(1, (int)summary.getRelearned());
}
public void testGetLastSummaryDates()
{
m_history.addSummary(m_date0, m_date1, 2, 0, 1, 1);
SessionSummary summary = m_history.getLastSummary();
assertEquals(m_date0, summary.getStart());
assertEquals(m_date1, summary.getEnd());
}
public void testAllSummariesDuration()
{
m_history.addSummary(m_date0, m_date1, 2, 0, 1, 1);
m_history.addSummary(m_date1, m_date2, 4, 3, 0, 1);
SessionSummary sessions = m_history.getSessionsSummary();
assertEquals(25, sessions.getDuration());
}
public void testAllsingleSummaryDuration()
{
m_history.addSummary(m_date0, m_date1, 2, 0, 1, 1);
SessionSummary session = m_history.getLastSummary();
assertEquals(20, session.getDuration());
}
public void testGetSummariesLimit()
{
m_history.addSummary(m_date0, m_date1, 2, 0, 1, 1);
m_history.addSummary(m_date1, m_date2, 4, 3, 0, 1);
m_history.addSummary(m_date2, m_date3, 1, 3, 0, 1);
List<SessionSummary> summaries = m_history.getSummaries(2);
assertEquals(4, (int)(summaries.get(0)).getPassed());
assertEquals(1, (int)(summaries.get(1)).getPassed());
assertEquals(2, summaries.size());
}
public void testGetSingleDailySummaries()
{
m_history.addSummary(m_date0, m_date1, 2, 0, 1, 1);
m_history.addSummary(m_date1, m_date2, 4, 3, 0, 1);
m_history.addSummary(m_date2, m_date3, 1, 3, 0, 1);
List<SessionSummary> summaries = m_history.getSummaries(LearnHistory.DATE_COMP);
SessionSummary summary = summaries.get(0);
assertSession(7, 6, 1, 3, summary);
assertEquals(1, summaries.size());
}
public void testGetSingleDailySummariesDates()
{
m_history.addSummary(m_date0, m_date1, 2, 0, 1, 1);
m_history.addSummary(m_date1, m_date2, 4, 3, 0, 1);
m_history.addSummary(m_date2, m_date3, 1, 3, 0, 1);
List<SessionSummary> summaries = m_history.getSummaries(LearnHistory.DATE_COMP);
SessionSummary summary = summaries.get(0);
assertEquals(m_date0, summary.getStart());
assertEquals(m_date3, summary.getEnd());
assertEquals(1, summaries.size());
}
public void testGetTwoDailySummaries()
{
Date today0 = new Date(System.currentTimeMillis() - MINUTE * 10);
Date today1 = new Date(System.currentTimeMillis() - MINUTE * 5);
m_history.addSummary(today0, today1, 2, 0, 1, 1);
m_history.addSummary(m_date0, m_date1, 4, 3, 0, 1);
m_history.addSummary(m_date1, m_date2, 1, 1, 0, 1);
List<SessionSummary> summaries = m_history.getSummaries(LearnHistory.DATE_COMP);
assertSession(2, 0, 1, 1, summaries.get(0));
assertSession(5, 4, 0, 2, summaries.get(1));
assertEquals(2, summaries.size());
}
public void testGetSummariesInOrder()
{
m_history.addSummary(m_date0, m_date1, 2, 0, 1, 1);
m_history.addSummary(m_date1, m_date2, 4, 3, 0, 1);
List<SessionSummary> summaries = m_history.getSummaries();
assertEquals(2, (int)(summaries.get(0)).getPassed());
assertEquals(4, (int)(summaries.get(1)).getPassed());
}
public void testGetAverageValues()
{
m_history.addSummary(m_date0, m_date1, 2, 0, 1, 1);
m_history.addSummary(m_date1, m_date2, 4, 3, 0, 1);
SessionSummary average = m_history.getAverage();
assertEquals(3.0, average.getPassed(), 0.1f);
assertEquals(1.5, average.getFailed(), 0.1f);
assertEquals(0.5, average.getSkipped(), 0.1f);
assertEquals(1.0, average.getRelearned(), 0.1f);
}
public void testGetAverageDates()
{
m_history.addSummary(m_date0, m_date1, 2, 0, 1, 1);
m_history.addSummary(m_date1, m_date2, 4, 3, 0, 1);
SessionSummary average = m_history.getAverage();
assertEquals(m_date0, average.getStart());
assertEquals(m_date2, average.getEnd());
}
public void testGetSessionsSummaryValues()
{
m_history.addSummary(m_date0, m_date1, 2, 0, 1, 1);
m_history.addSummary(m_date1, m_date2, 4, 3, 0, 1);
SessionSummary summary = m_history.getSessionsSummary();
assertSession(6, 3, 1, 2, summary);
}
public void testGetSessionsSummaryDates()
{
m_history.addSummary(m_date0, m_date1, 2, 0, 1, 1);
m_history.addSummary(m_date1, m_date2, 4, 3, 0, 1);
SessionSummary all = m_history.getSessionsSummary();
assertEquals(m_date0, all.getStart());
assertEquals(m_date2, all.getEnd());
}
public void testSaveLoadRoundtrip() throws Exception
{
m_history.addSummary(m_date0, m_date1, 2, 0, 1, 1);
m_history.addSummary(m_date1, m_date2, 4, 3, 0, 1);
File file = new File("test_stats.xml");
m_history.save(file);
LearnHistory stats = new LearnHistory(file);
assertEquals(m_history, stats);
}
public void testGetSessionSummaryByDate()
{
m_history.addSummary(m_date0, m_date1, 2, 0, 1, 1);
m_history.addSummary(m_date1, m_date2, 4, 3, 0, 1);
SessionSummary summary = m_history.getSummary(m_date0, LearnHistory.DATE_COMP);
assertSession(6, 3, 1, 2, summary);
}
private void assertSession(int passed, int failed, int skipped,
int relearned, SessionSummary summary)
{
assertEquals(passed, (int)summary.getPassed());
assertEquals(failed, (int)summary.getFailed());
assertEquals(skipped, (int)summary.getSkipped());
assertEquals(relearned, (int)summary.getRelearned());
}
private Date createDate(int hour, int minute)
{
Calendar calendar = Calendar.getInstance();
calendar.set(2007, 1, 1, hour, minute);
return calendar.getTime();
}
}
| mabdi/jMemorize-Plus-1 | src/jmemorize/core/test/LearnHistoryTest.java | Java | gpl-2.0 | 8,376 |
package edu.sc.seis.sod.example;
import edu.iris.Fissures.network.ChannelImpl;
import edu.sc.seis.fissuresUtil.cache.CacheEvent;
import edu.sc.seis.sod.CookieJar;
import edu.sc.seis.sod.status.Pass;
import edu.sc.seis.sod.status.StringTree;
import edu.sc.seis.sod.subsetter.eventChannel.EventChannelSubsetter;
public class EventChannelSubsetterExample implements EventChannelSubsetter {
public StringTree accept(CacheEvent event,
ChannelImpl channel,
CookieJar cookieJar) throws Exception {
return new Pass(this);
}
}
| crotwell/sod | externalExample/src/edu/sc/seis/sod/example/EventChannelSubsetterExample.java | Java | gpl-2.0 | 596 |
package org.aptivate.bmotools.pmgraph;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.AccessControlException;
import java.util.HashMap;
import java.util.Map;
import libAPI.ApiConn;
import org.apache.log4j.Logger;
import org.aptivate.bmotools.pmgraph.Resolver.FakeResolver;
import org.talamonso.OMAPI.Connection;
import org.talamonso.OMAPI.ErrorCode;
import org.talamonso.OMAPI.Message;
import org.talamonso.OMAPI.Exceptions.OmapiCallException;
import org.talamonso.OMAPI.Exceptions.OmapiConnectionException;
import org.talamonso.OMAPI.Exceptions.OmapiException;
import org.talamonso.OMAPI.Exceptions.OmapiInitException;
import org.talamonso.OMAPI.Objects.Host;
import org.talamonso.OMAPI.Objects.Lease;
import org.xbill.DNS.Address;
/**
* @author Noe Andres Rodriguez Gonzalez.
*
* A class containing the host resolver method. The DNS server is used to obtain
* the hostname, if this fails the DHCP server is used.
*
*/
public class DefaultResolver extends FakeResolver
{
public static interface Interface
{
public String getHostname(String IpAddress);
}
private static Logger m_logger = Logger.getLogger(DefaultResolver.class);
private Connection m_OmapiConnection;
private ApiConn m_MikrotikApi;
private final int HOSTNAME_LENGTH_LIMIT = 40;
private Map<String, String> m_MikrotikDhcpCache;
public DefaultResolver() throws IOException
{
this.m_OmapiConnection = null;
try
{
if (! Configuration.getDHCPAddress().isEmpty())
{
this.m_OmapiConnection = new Connection(Configuration
.getDHCPAddress(), Configuration.getDHCPPort());
this.m_OmapiConnection.setAuth(Configuration.getDHCPName(),
Configuration.getDHCPPass());
}
else
{
m_logger.info("DHCP name resolution disabled");
}
}
catch (OmapiInitException e)
{
m_logger.info("Unable to get a connection to DHCP server: "
+ "possibly wrong IP address? DHCP name resolution disabled.",
e);
}
catch (OmapiConnectionException e)
{
m_logger.info("Unable to connect to DHCP server: possibly "
+ "wrong key or server disabled? DHCP name resolution "
+ "disabled", e);
}
this.m_MikrotikApi = null;
try
{
if (! Configuration.getMikrotikAddress().isEmpty())
{
m_MikrotikApi = new ApiConn(Configuration.getMikrotikAddress(),
Configuration.getMikrotikApiPort());
if (!m_MikrotikApi.isConnected())
{
m_MikrotikApi.start();
m_MikrotikApi.join();
}
if (!m_MikrotikApi.isConnected())
{
Exception e = m_MikrotikApi.getStoredException();
if (e != null)
{
throw new Exception("Connection to Mikrotik failed", e);
}
else
{
throw new Exception("Connection to Mikrotik " +
"failed (generic)");
}
}
m_MikrotikApi.login(Configuration.getMikrotikUser(),
Configuration.getMikrotikPass().toCharArray());
/*
m_MikrotikApi.sendCommand("/ip/address/print");
String result = m_MikrotikApi.getData();
m_logger.info("Connected to Mikrotik: " + result);
*/
m_MikrotikDhcpCache = new HashMap<String, String>();
m_MikrotikApi.sendCommand("/ip/dhcp-server/lease/print");
while (true)
{
String result = m_MikrotikApi.getData();
m_logger.debug("Microtik API returned: " + result);
/*
* Results look like this:
*
* <pre>
!re
=.id=*1D
=address=192.168.88.237
=mac-address=00:D0:4B:91:13:A0
=server=default
=status=bound
=expires-after=1d22:36:21
=last-seen=1d1h23m39s
=active-address=192.168.88.237
=active-mac-address=00:D0:4B:91:13:A0
=active-server=default
=host-name=Lacie
=radius=false
=dynamic=true
=blocked=false
=disabled=false
=comment=</pre>
*/
if (!result.startsWith("\n!"))
{
m_logger.warn("Mikrotik API returned unknown string: " + result);
break;
}
String [] lines = result.split("\n");
String resultVerb = lines[1];
if (resultVerb.equals("!re"))
{
String address = null, hostName = null;
for (int i = 2; i < lines.length; i++)
{
String line = lines[i];
if (line.startsWith("="))
{
String [] parts = line.substring(1).split("=", 2);
if (parts[0].equals("address"))
{
address = parts[1];
}
else if (parts[0].equals("host-name"))
{
hostName = parts[1];
}
}
else
{
m_logger.info("Ignoring unknown line " +
"in result: " + line);
}
}
if (address != null && hostName != null)
{
m_MikrotikDhcpCache.put(address, hostName);
}
}
else if (resultVerb.equals("!trap"))
{
m_logger.warn("Mikrotik API returned error: " + result);
break;
}
else if (resultVerb.equals("!done"))
{
break;
}
else
{
m_logger.warn("Mikrotik API returned unexpected " +
"result: " + result);
}
}
}
else
{
m_logger.info("Mikrotik DHCP name resolution disabled");
}
}
catch (Exception e)
{
m_logger.info("Unable to get a connection to Mikrotik router: "
+ "possible wrong address. DHCP name resolution disabled",
e);
}
}
private String limitString (String text) {
if (text.length() > HOSTNAME_LENGTH_LIMIT)
{
return text.substring(0, HOSTNAME_LENGTH_LIMIT) + "...";
}
return text;
}
public class ResolvedHost
{
private String hostName;
private String method;
public ResolvedHost(String hostName, String method)
{
this.hostName = hostName;
this.method = method;
}
public String hostName()
{
return this.hostName;
}
public String method()
{
return this.method;
}
};
/**
* The DNS server is used to obtain the hostname of a IP, if this
* fails the DHCP server is used. The DHCP server has to be configured in
* the config file of the application
*
* @param IpAddress
* String representation of the IP
*
* @return An String containing the hostName for the provided IP. If the
* lookup for the Hostname is unsuccessful return the string
* "Unknown Host"
*/
public String getHostname(String IpAddress)
{
ResolvedHost rh = tryGetHostname(IpAddress);
if (rh == null)
{
m_logger.info("Failed to resolve hostname using any " +
"available method: " + IpAddress);
return super.getHostname(IpAddress);
}
else
{
m_logger.info("Resolved hostname for " + IpAddress + " to " +
rh.hostName() + " using " + rh.method());
return limitString(rh.hostName());
}
}
public ResolvedHost tryGetHostname(String IpAddress)
{
try
{
InetAddress inetadress = Address.getByAddress(IpAddress);
return new ResolvedHost(Address.getHostName(inetadress), "DNS");
}
catch (Exception e)
{
if (e instanceof AccessControlException)
m_logger.error(ErrorMessages.DNS_ERROR_JAVA_SECURITY, e);
if (e instanceof UnknownHostException)
{
m_logger.debug("Failed to resolve " + IpAddress +
" to hostname using DNS: unknown host");
}
else
{
m_logger.warn("Failed to resolve hostname using DNS", e);
}
}
/*
* If the DHCP server is available and OMAPI is configured,
* try looking up Host and Lease entries for the IP address.
*/
if (this.m_OmapiConnection != null)
{
try
{
Lease remote = new Lease(m_OmapiConnection);
remote.setIPAddress(IpAddress);
remote = remote.send(Message.OPEN);
if (remote.getClientHostname() != null &&
!remote.getClientHostname().equals(""))
{
return new ResolvedHost(remote.getClientHostname(),
"DHCP OMAPI Lease");
}
}
catch (OmapiException e1)
{
if (e1 instanceof OmapiCallException &&
((OmapiCallException) e1).getErrorCode() == ErrorCode.NOT_FOUND)
{
// short version, without stack trace
m_logger.info("Failed to resolve hostname from DHCP " +
"server using OMAPI leases: not found");
}
else
{
m_logger.info("Failed to resolve hostname from DHCP " +
"server using OMAPI leases", e1);
}
}
}
else
{
m_logger.debug("Failed to resolve " + IpAddress + " using " +
"DHCP OMAPI: not configured");
}
if (m_MikrotikApi != null)
{
String hostName = m_MikrotikDhcpCache.get(IpAddress);
if (hostName == null)
{
m_logger.debug("Failed to resolve hostname using Mikrotik API: " +
"entry not found for " + IpAddress);
}
else
{
return new ResolvedHost(hostName, "Mikrotik API");
}
}
else
{
m_logger.debug("Failed to resolve hostname using Mikrotik API: " +
"not configured");
}
return null;
}
protected void finalize()
{
if (m_OmapiConnection != null)
{
m_OmapiConnection.close();
}
if (m_MikrotikApi != null)
{
try
{
m_MikrotikApi.disconnect();
}
catch (IOException e)
{
m_logger.info("Failed to disconnect from Mikrotik", e);
}
}
}
}
| aptivate/pmgraph | web/WEB-INF/src/org/aptivate/bmotools/pmgraph/DefaultResolver.java | Java | gpl-2.0 | 9,668 |
/*
* Copyright (C) 2012-2022 52°North Spatial Information Research 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.sos.exception.ows.concrete;
import org.n52.shetland.ogc.ows.exception.InvalidParameterValueException;
import org.n52.shetland.ogc.sos.Sos2Constants;
/**
* @author <a href="mailto:[email protected]">Christian Autermann</a>
*
* @since 4.0.0
*/
public class InvalidProcedureDescriptionFormatException extends InvalidParameterValueException {
private static final long serialVersionUID = -6138488504467961928L;
public InvalidProcedureDescriptionFormatException(String value) {
super(Sos2Constants.DescribeSensorParams.procedureDescriptionFormat, value);
}
}
| 52North/SOS | core/api/src/main/java/org/n52/sos/exception/ows/concrete/InvalidProcedureDescriptionFormatException.java | Java | gpl-2.0 | 1,886 |
package Examples;
//Sql.java -- sample program to read a database
//Configure the database for ODBC access using Start->Settings->Control Panel->ODBC32
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import com.sidacoja.utils.Cell;
import com.sidacoja.utils.Row;
import com.sidacoja.utils.RowCache;
import com.sidacoja.utils.Sidacoja;
import rptGenerator.Generator;
//import rptGenerator.CellX;
//import rptGenerator.Generator;
//import rptGenerator.RowX;
//import rptGenerator.RowCacheX;
public class SQLReportExample {
static final String JDBC_DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
static final String DB_URL = "jdbc:sqlserver://CHUCK-PC\\SQLSERVERADVSP2;database=chuckDB;integratedSecurity=true;";
// Database credentials
static final String USER = "Chuck-PC\\Chuck"; //DriverManager.getConnection(connectionUrl,"Chuck-PC\\Chuck","");
static final String PASS = "";
public static void main(String[] args)
{
// attempt to connect to the ODBC database
//String db = "myDatabase"; // ODBC database name
//System.out.println("Attempting to open database ...");
Connection conn = null;
Statement stmt = null;
try
{
Class.forName(JDBC_DRIVER);
//STEP 3: Open a connection
//System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
stmt = conn.createStatement();
}
catch (Exception ex)
{
System.out.println(ex.getMessage());
// if not successful, quit
System.out.println("Cannot open database -- make sure connection is configured properly.");
System.exit(1);
}
/* create a table
String cr8 = "create table courses (desig varchar(12),term varchar(12),units integer,grade varchar(1))";
System.out.println("Executing " + cr8);
try
{
stmt.executeUpdate(cr8);
}
catch (Exception ex)
{
// error executing SQL statement
System.out.println("Error: " + ex);
}
*/
// create an INSERT statement
String sql = "INSERT INTO courses (desig, term, units, grade) VALUES ('COMSC-265', 'FA2001', 4, 'A')";
//System.out.println("Executing " + sql);
//try
//{
// stmt.executeUpdate(sql);
//}
//catch (Exception ex)
//{
// // error executing SQL statement
// System.out.println("Error: " + ex);
//}
// create another SQL statement
sql = "SELECT desig,term,units,grade FROM courses order by desig, term";
ResultSet rs = null;
try
{
rs = stmt.executeQuery(sql);
}
catch (Exception ex)
{
// error executing SQL statement
System.out.println("Error: " + ex);
}
final String STRING = "String";
final String INTEGER = "Integer";
final String DESIG = "Desig";
final String TERM = "Term";
final String UNITS = "Units";
final String GRADE = "Grade";
RowCache cache = new RowCache();
List<Row> rowList = new ArrayList<Row>();
// show records (skip for INSERT, DELETE, or UPDATE)
try {
while (rs.next()) {
Row row = new Row();
List<Cell> cellList = new ArrayList<Cell>();
String desig = rs.getString(1); // read 1st column as text
Cell cell0 = loadCell(STRING,DESIG,0,desig);
cellList.add(cell0);
String term = rs.getString(2); // read 2nd column as text
Cell cell1 = loadCell(STRING,TERM,1,term);
cellList.add(cell1);
int units = rs.getInt(3); // read 3rd column as int
Cell cell2 = loadCell(INTEGER,UNITS,2,Integer.toString(units));
cellList.add(cell2);
String grade = rs.getString(4); // read 4th column as text
Cell cell3 = loadCell(STRING,GRADE,3,grade);
cell3.setLabel(GRADE);
cellList.add(cell3);
row.setList(cellList);
rowList.add(row);
}
cache.setList(rowList);
}
catch (Exception ex)
{
// error executing SQL statement
System.out.println("Error: " + ex);
}
// close database
try
{
conn.close();
}
catch (Exception ex){}
try {
Generator generator = new Generator(4,16,132); //nbr cols, data length, linelength
generator.setHeading1(sql);
Calendar cal = Calendar.getInstance();
String dfString = DateFormat.getDateInstance().format(cal.getTime());
generator.setHeading2(dfString);
generator.setHeading3(" ");
generator.setControlBreak1(DESIG);
generator.setControlBreak2(TERM);
generator.setControlBreak3(null);
generator.setFooting1("*");
generator.setFooting2("**");
generator.setFooting3("End of Report");
generator.execRpt(cache);
} catch(Exception rex) {
System.out.println(rex.getMessage());
rex.printStackTrace();
}
}
/*
* loadCell is a utility method to create and load a standard cell object
*/
static public Cell loadCell(String dataType, String label, int number, String value) {
Cell cell = null; //new Cell();
cell.setDataType(dataType);
cell.setLabel(label);
cell.setNumber(number);
cell.setValue(value);
return cell;
}
}
| chuckrunge/siregeja | src/Examples/SQLReportExample.java | Java | gpl-2.0 | 4,976 |
package com.sfsctech.support.saml.secret;
import com.sfsctech.core.base.ex.BizException;
import com.sfsctech.support.common.security.CredentialTool;
import com.sfsctech.support.common.util.ThrowableUtil;
import org.opensaml.security.credential.Credential;
import org.opensaml.security.credential.CredentialSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Class IDPCerdentials
*
* @author 张麒 2019-12-27.
* @version Description:
*/
public class IDPCerdentials {
private static Logger logger = LoggerFactory.getLogger(IDPCerdentials.class);
private Credential credential;
public IDPCerdentials(String keyStore, String keyPass) {
try {
CredentialTool credentialTool = new CredentialTool(keyStore, keyPass);
credential = CredentialSupport.getSimpleCredential(credentialTool.getPublicKey(), credentialTool.getPrivateKey());
} catch (Exception e) {
throw new BizException(ThrowableUtil.getRootMessage(e), e);
}
}
public Credential getCredential() {
return credential;
}
}
| tkdiooo/sfsctech | common-parent/common-support/common-support-saml/src/main/java/com/sfsctech/support/saml/secret/IDPCerdentials.java | Java | gpl-2.0 | 1,096 |
package com.jeecms.cms.entity.assist;
import java.sql.Timestamp;
import com.jeecms.cms.entity.assist.base.BaseCmsComment;
import com.jeecms.common.util.StrUtils;
public class CmsComment extends BaseCmsComment {
private static final long serialVersionUID = 1L;
public String getText() {
return getCommentExt().getText();
}
public String getTextHtml() {
return StrUtils.txt2htm(getText());
}
public String getReply() {
return getCommentExt().getReply();
}
public String getReplayHtml() {
return StrUtils.txt2htm(getReply());
}
public String getIp() {
return getCommentExt().getIp();
}
public void init() {
short zero = 0;
if (getDowns() == null) {
setDowns(zero);
}
if (getUps() == null) {
setUps(zero);
}
if (getChecked() == null) {
setChecked(false);
}
if (getRecommend() == null) {
setRecommend(false);
}
if (getCreateTime() == null) {
setCreateTime(new Timestamp(System.currentTimeMillis()));
}
}
/* [CONSTRUCTOR MARKER BEGIN] */
public CmsComment () {
super();
}
/**
* Constructor for primary key
*/
public CmsComment (java.lang.Integer id) {
super(id);
}
/**
* Constructor for required fields
*/
public CmsComment (
java.lang.Integer id,
com.jeecms.cms.entity.main.Content content,
com.jeecms.cms.entity.main.CmsSite site,
java.util.Date createTime,
java.lang.Short ups,
java.lang.Short downs,
java.lang.Boolean recommend,
java.lang.Boolean checked) {
super (
id,
content,
site,
createTime,
ups,
downs,
recommend,
checked);
}
/* [CONSTRUCTOR MARKER END] */
} | caipiao/Lottery | src/com/jeecms/cms/entity/assist/CmsComment.java | Java | gpl-2.0 | 1,687 |
package wyvern.tools.typedAST.interfaces;
import wyvern.tools.typedAST.typedastvisitor.TypedASTVisitor;
public interface TypedASTNode {
<S, T> T acceptVisitor(TypedASTVisitor<S, T> visitor, S state);
}
| wyvernlang/wyvern | tools/src/wyvern/tools/typedAST/interfaces/TypedASTNode.java | Java | gpl-2.0 | 208 |
/*
* Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Sun Microsystems nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.retest.swingset3.demos.gridbaglayout;
import java.awt.*;
import java.awt.event.*;
import java.util.HashMap;
import java.util.Map;
import javax.swing.*;
/**
* Calculator
*
* @author Pavel Porvatov
*/
public class Calculator extends JComponent {
private static final String ZERO = "0";
private static final char DECIMAL_SEPARATOR = ',';
private final JTextField tfScreen = new JTextField();
private enum State {
INPUT_X,
INPUT_X_FINISHED,
INPUT_Y,
INPUT_Y_FINISHED
}
private enum Operator {
ADDITION,
SUBTRACTION,
MULTIPLICATION,
DIVISION,
SQRT,
INVERSE,
EQUALS
}
private final Map<Character, Operator> keyMapping = new HashMap<Character, Operator>();
private String operand_x;
private Operator operator;
private State state;
public Calculator() {
keyMapping.put( '/', Operator.DIVISION );
keyMapping.put( '*', Operator.MULTIPLICATION );
keyMapping.put( '+', Operator.ADDITION );
keyMapping.put( '-', Operator.SUBTRACTION );
keyMapping.put( '\n', Operator.EQUALS );
initUI();
addKeyListener( new KeyAdapter() {
public void keyTyped( KeyEvent e ) {
char c = e.getKeyChar();
if ( Character.isDigit( c ) ) {
doProcessChar( c );
} else if ( c == '.' || c == ',' ) {
doProcessChar( DECIMAL_SEPARATOR );
} else {
Operator operator = keyMapping.get( c );
if ( operator != null ) {
doProcessOperator( operator );
}
}
}
public void keyPressed( KeyEvent e ) {
switch ( e.getKeyCode() ) {
case KeyEvent.VK_BACK_SPACE:
doProcessBackspace();
break;
case KeyEvent.VK_DELETE:
doReset();
}
}
} );
doReset();
}
private void initUI() {
tfScreen.setHorizontalAlignment( JTextField.RIGHT );
JButton btnBackspace = new JButton( "Backspace" );
btnBackspace.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent e ) {
doProcessBackspace();
}
} );
JButton btnReset = new JButton( "C" );
btnReset.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent e ) {
doReset();
}
} );
JPanel pnGridPanel = new JPanel( new GridLayout( 1, 2, 8, 8 ) );
pnGridPanel.add( btnBackspace );
pnGridPanel.add( btnReset );
setLayout( new GridBagLayout() );
JButton btnSwapSign = new SquareButton( "+/-" );
btnSwapSign.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent e ) {
doSwapSign();
}
} );
addComp( tfScreen, 0, 0, 5, 1 );
addComp( pnGridPanel, 0, 1, 5, 1 );
addComp( new CharButton( '7' ), 0, 2, 1, 1 );
addComp( new CharButton( '8' ), 1, 2, 1, 1 );
addComp( new CharButton( '9' ), 2, 2, 1, 1 );
addComp( new OperatorButton( Operator.DIVISION, "/" ), 3, 2, 1, 1 );
addComp( new OperatorButton( Operator.INVERSE, "1/x" ), 4, 2, 1, 1 );
addComp( new CharButton( '4' ), 0, 3, 1, 1 );
addComp( new CharButton( '5' ), 1, 3, 1, 1 );
addComp( new CharButton( '6' ), 2, 3, 1, 1 );
addComp( new OperatorButton( Operator.MULTIPLICATION, "*" ), 3, 3, 1, 1 );
addComp( new OperatorButton( Operator.SQRT, "sqrt" ), 4, 3, 1, 1 );
addComp( new CharButton( '1' ), 0, 4, 1, 1 );
addComp( new CharButton( '2' ), 1, 4, 1, 1 );
addComp( new CharButton( '3' ), 2, 4, 1, 1 );
addComp( new OperatorButton( Operator.SUBTRACTION, "-" ), 3, 4, 1, 1 );
addComp( new CharButton( '0' ), 0, 5, 1, 1 );
addComp( btnSwapSign, 1, 5, 1, 1 );
addComp( new CharButton( DECIMAL_SEPARATOR ), 2, 5, 1, 1 );
addComp( new OperatorButton( Operator.ADDITION, "+" ), 3, 5, 1, 1 );
addComp( new OperatorButton( Operator.EQUALS, "=" ), 4, 5, 1, 1 );
// Set focusable false
resetFocusable( this );
setFocusable( true );
}
private static void resetFocusable( Component component ) {
component.setFocusable( false );
if ( component instanceof Container ) {
for ( Component c : ((Container) component).getComponents() ) {
resetFocusable( c );
}
}
}
private void doReset() {
operand_x = null;
operator = null;
state = State.INPUT_X;
tfScreen.setText( ZERO );
}
private void doProcessChar( char c ) {
String text = tfScreen.getText();
String newValue;
if ( state == State.INPUT_X || state == State.INPUT_Y ) {
newValue = attachChar( text, c );
if ( stringToValue( newValue ) == null ) {
return;
}
} else {
newValue = attachChar( "0", c );
if ( stringToValue( newValue ) == null ) {
return;
}
if ( operator == null ) {
operand_x = null;
state = State.INPUT_X;
} else {
operand_x = text;
state = State.INPUT_Y;
}
}
tfScreen.setText( newValue );
}
private static String attachChar( String s, char c ) {
if ( Character.isDigit( c ) ) {
if ( s.equals( ZERO ) ) {
return Character.toString( c );
}
if ( s.equals( "-" + ZERO ) ) {
return "-" + Character.toString( c );
}
return s + Character.toString( c );
} else {
return s + Character.toString( c );
}
}
private void doSwapSign() {
String text = tfScreen.getText();
tfScreen.setText( text.startsWith( "-" ) ? text.substring( 1 ) : "-" + text );
}
private void doProcessBackspace() {
String text = tfScreen.getText();
if ( text.length() > 0 ) {
text = text.substring( 0, text.length() - 1 );
}
if ( text.length() == 0 || text.equals( "-" ) ) {
text = ZERO;
}
if ( stringToValue( text ) != null ) {
tfScreen.setText( text );
}
}
private void doProcessOperator( Operator operator ) {
double y = stringToValue( tfScreen.getText() );
// Process unary operators
boolean isUnary;
switch ( operator ) {
case SQRT:
tfScreen.setText( valueToString( Math.sqrt( y ) ) );
isUnary = true;
break;
case INVERSE:
tfScreen.setText( valueToString( 1 / y ) );
isUnary = true;
break;
default:
isUnary = false;
}
if ( isUnary ) {
if ( state == State.INPUT_X ) {
state = State.INPUT_X_FINISHED;
}
if ( state == State.INPUT_Y ) {
state = State.INPUT_Y_FINISHED;
}
return;
}
// Process binary operators
if ( state == State.INPUT_Y || state == State.INPUT_Y_FINISHED ) {
double x = stringToValue( operand_x );
double result;
switch ( this.operator ) {
case ADDITION:
result = x + y;
break;
case SUBTRACTION:
result = x - y;
break;
case MULTIPLICATION:
result = x * y;
break;
case DIVISION:
result = x / y;
break;
default:
throw new IllegalStateException( "Unsupported operation " + operator );
}
tfScreen.setText( valueToString( result ) );
}
this.operator = operator == Operator.EQUALS ? null : operator;
operand_x = null;
state = State.INPUT_X_FINISHED;
}
private static Double stringToValue( String value ) {
try {
return new Double( value.replace( DECIMAL_SEPARATOR, '.' ) );
} catch ( NumberFormatException e ) {
// Continue convertion
}
if ( value.endsWith( String.valueOf( DECIMAL_SEPARATOR ) ) ) {
try {
// Try convert uncompleted value
return new Double( value.substring( 0, value.length() - 1 ) );
} catch ( NumberFormatException e ) {
// Continue convertion
}
}
return null;
}
private static String valueToString( Double value ) {
if ( value == null ) {
return ZERO;
} else {
String result = value.toString();
if ( result.endsWith( ".0" ) ) {
result = result.substring( 0, result.length() - 2 );
}
if ( result.equals( "-0" ) ) {
result = ZERO;
}
return result;
}
}
private void addComp( Component comp, int gridx, int gridy, int gridwidth, int gridheight ) {
add( comp, new GridBagConstraints( gridx, gridy, gridwidth, gridheight, 1, 1, GridBagConstraints.CENTER,
GridBagConstraints.BOTH, new Insets( 4, 4, 4, 4 ), 0, 0 ) );
}
private static class SquareButton extends JButton {
private SquareButton( String text ) {
super( text );
setMargin( new Insets( 2, 0, 2, 0 ) );
}
public Dimension getMinimumSize() {
Dimension result = super.getMinimumSize();
if ( result.width < result.height ) {
result.width = result.height;
}
return result;
}
public Dimension getPreferredSize() {
return getMinimumSize();
}
}
private class CharButton extends SquareButton {
private CharButton( final char c ) {
super( String.valueOf( c ) );
addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent e ) {
doProcessChar( c );
}
} );
}
}
private class OperatorButton extends SquareButton {
private OperatorButton( final Operator operator, String text ) {
super( text );
addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent e ) {
doProcessOperator( operator );
}
} );
}
}
}
| retest/swingset3 | src/org/retest/swingset3/demos/gridbaglayout/Calculator.java | Java | gpl-2.0 | 10,417 |
/**
* OpenKM, Open Document Management System (http://www.openkm.com)
* Copyright (c) 2006-2015 Paco Avila & Josep Llort
*
* No bytes were intentionally harmed during the development of this application.
*
* 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.openkm.extension.servlet;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.openkm.api.OKMAuth;
import com.openkm.api.OKMDocument;
import com.openkm.api.OKMFolder;
import com.openkm.api.OKMMail;
import com.openkm.api.OKMRepository;
import com.openkm.automation.AutomationException;
import com.openkm.bean.Document;
import com.openkm.bean.Folder;
import com.openkm.bean.Mail;
import com.openkm.bean.Permission;
import com.openkm.core.AccessDeniedException;
import com.openkm.core.DatabaseException;
import com.openkm.core.ItemExistsException;
import com.openkm.core.LockException;
import com.openkm.core.PathNotFoundException;
import com.openkm.core.RepositoryException;
import com.openkm.dao.ConfigDAO;
import com.openkm.extension.core.ExtensionException;
import com.openkm.extension.frontend.client.bean.GWTMacros;
import com.openkm.extension.frontend.client.service.OKMMacrosService;
import com.openkm.frontend.client.OKMException;
import com.openkm.frontend.client.constants.service.ErrorCode;
import com.openkm.servlet.frontend.OKMRemoteServiceServlet;
/**
* MacrosServlet
*
* @author jllort
*
*/
public class MacrosServlet extends OKMRemoteServiceServlet implements OKMMacrosService {
private static final long serialVersionUID = 1L;
private static Logger log = LoggerFactory.getLogger(MacrosServlet.class);
@Override
public List<GWTMacros> getActions() throws OKMException {
updateSessionManager();
List<GWTMacros> actionList = new ArrayList<GWTMacros>();
try {
String actions[] = ConfigDAO.getText("macros.actions", "").split("\r\n");
for (String action : actions) {
String act[] = action.split(",");
if (act.length > 1) {
// Path fix: all paths must finish with "/" for comparison
if (!act[0].endsWith("/")) {
act[0] += "/";
}
if (!act[1].endsWith("/")) {
act[1] += "/";
}
GWTMacros fastAction = new GWTMacros();
fastAction.setPathOrigin(act[0]);
fastAction.setPathDestination(act[1]);
actionList.add(fastAction);
}
}
} catch (DatabaseException e) {
log.error(e.getMessage(), e);
throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMFastActionService, ErrorCode.CAUSE_Database), e.getMessage());
}
return actionList;
}
@Override
public void executeAction(GWTMacros action, String path) throws OKMException {
updateSessionManager();
String orgPath = action.getPathOrigin(); // Origin path
String dstPath = action.getPathDestination(); // Destination path
// All paths should not finish with / althought must use for comparasion
if (orgPath.endsWith("/")) {
orgPath = orgPath.substring(0, orgPath.length() - 1);
}
if (dstPath.endsWith("/")) {
dstPath = dstPath.substring(0, dstPath.length() - 1);
}
try {
// Case when on destination should create folders to store documents
String rightPath = path.substring(orgPath.length() + 1); // Right path
if (rightPath.indexOf("/") >= 0) {
String extraFldPath = rightPath.substring(0, rightPath.lastIndexOf("/"));
String destFoldersToCreate[] = extraFldPath.split("/");
for (int i = 0; i < destFoldersToCreate.length; i++) { // Put all destination files path
if (i == 0) {
destFoldersToCreate[i] = dstPath + "/" + destFoldersToCreate[i];
} else {
destFoldersToCreate[i] = destFoldersToCreate[i - 1] + "/" + destFoldersToCreate[i];
}
}
createFolders(orgPath, dstPath, destFoldersToCreate);
}
// Move to destination
String dstPathToMove = dstPath + "/" + rightPath;
String dstParentFolder = dstPathToMove.substring(0, dstPathToMove.lastIndexOf("/"));
if (OKMDocument.getInstance().isValid(null, path)) {
OKMDocument.getInstance().move(null, path, dstParentFolder);
} else if (OKMMail.getInstance().isValid(null, path)) {
OKMMail.getInstance().move(null, path, dstParentFolder);
} else if (OKMFolder.getInstance().isValid(null, path)) {
// Control case if folder exists
if (!OKMRepository.getInstance().hasNode(null, dstPathToMove)) {
OKMFolder.getInstance().move(null, path, dstParentFolder);
} else {
moveFolderContents(path, dstPathToMove);
OKMFolder.getInstance().delete(null, path); // delete folder ( yet exists and contents has been yet
// moved )
}
}
} catch (PathNotFoundException e) {
log.error(e.getMessage(), e);
throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMFastActionService, ErrorCode.CAUSE_PathNotFound), e.getMessage());
} catch (AccessDeniedException e) {
log.error(e.getMessage(), e);
throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMFastActionService, ErrorCode.CAUSE_AccessDenied), e.getMessage());
} catch (RepositoryException e) {
log.error(e.getMessage(), e);
throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMFastActionService, ErrorCode.CAUSE_Repository), e.getMessage());
} catch (DatabaseException e) {
log.error(e.getMessage(), e);
throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMFastActionService, ErrorCode.CAUSE_Database), e.getMessage());
} catch (ItemExistsException e) {
log.error(e.getMessage(), e);
throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMFastActionService, ErrorCode.CAUSE_ItemExists), e.getMessage());
} catch (ExtensionException e) {
log.error(e.getMessage(), e);
throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMFastActionService, ErrorCode.CAUSE_Extension), e.getMessage());
} catch (AutomationException e) {
log.error(e.getMessage(), e);
throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMFastActionService, ErrorCode.CAUSE_Automation), e.getMessage());
} catch (LockException e) {
log.error(e.getMessage(), e);
throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMFastActionService, ErrorCode.CAUSE_Lock), e.getMessage());
}
}
/**
* moveFolderContents
*/
private void moveFolderContents(String fldPath, String dstPathToMove) throws PathNotFoundException, RepositoryException,
DatabaseException, ItemExistsException, AccessDeniedException, LockException, ExtensionException, AutomationException {
// Move documents
for (Document doc : OKMDocument.getInstance().getChildren(null, fldPath)) {
OKMDocument.getInstance().move(null, doc.getPath(), dstPathToMove);
}
// Move Mails
for (Mail mail : OKMMail.getInstance().getChildren(null, fldPath)) {
OKMMail.getInstance().move(null, mail.getPath(), dstPathToMove);
}
// Move subfolders
for (Folder fld : OKMFolder.getInstance().getChildren(null, fldPath)) {
String fldToMove = dstPathToMove + "/" + fld.getPath().substring(fld.getPath().lastIndexOf("/") + 1);
// Control case if folder exists
if (!OKMRepository.getInstance().hasNode(null, fldToMove)) {
OKMFolder.getInstance().move(null, fld.getPath(), dstPathToMove);
} else {
moveFolderContents(fld.getPath(), fldToMove);
OKMFolder.getInstance().delete(null, fld.getPath()); // delete folder ( yet exists and contents has been
// yet moved )
}
}
}
/**
* createFolders
*/
private void createFolders(String orgPath, String dstPath, String folders[]) throws OKMException, RepositoryException,
DatabaseException, PathNotFoundException, ItemExistsException, AccessDeniedException, ExtensionException, AutomationException {
for (String folder : folders) {
if (!OKMRepository.getInstance().hasNode(null, folder)) {
Folder fld = new Folder();
fld.setPath(folder);
OKMFolder.getInstance().create(null, fld);
// Change security
String originPath = folder.replaceFirst(dstPath, orgPath);
Map<String, Integer> dstRolesMap = OKMAuth.getInstance().getGrantedRoles(null, folder);
Map<String, Integer> dstUsersMap = OKMAuth.getInstance().getGrantedUsers(null, folder);
Map<String, Integer> orgRolesMap = OKMAuth.getInstance().getGrantedRoles(null, originPath);
Map<String, Integer> orgUsersMap = OKMAuth.getInstance().getGrantedUsers(null, originPath);
// Add full grants to actual remote user
String remoteUser = getThreadLocalRequest().getRemoteUser();
int allGrants = Permission.ALL_GRANTS;
OKMAuth.getInstance().grantUser(null, folder, remoteUser, allGrants, false);
// Remove all grants except remote user
for (String role : dstRolesMap.keySet()) {
OKMAuth.getInstance().revokeRole(null, folder, role, allGrants, false);
}
for (String user : dstUsersMap.keySet()) {
if (!remoteUser.equals(user)) {
OKMAuth.getInstance().revokeUser(null, folder, user, allGrants, false);
}
}
// Setting privileges except remote user
for (String role : orgRolesMap.keySet()) {
OKMAuth.getInstance().grantRole(null, folder, role, orgRolesMap.get(role).intValue(), false);
}
for (String user : orgUsersMap.keySet()) {
if (!remoteUser.equals(user)) {
OKMAuth.getInstance().grantUser(null, folder, user, orgUsersMap.get(user).intValue(), false);
}
}
// Setting user privileges if exists, otherside revokes all
if (orgUsersMap.containsKey(remoteUser)) {
int permission = orgUsersMap.get(remoteUser).intValue();
if ((permission & Permission.READ) != Permission.READ) {
OKMAuth.getInstance().revokeUser(null, folder, remoteUser, Permission.READ, false);
}
if ((permission & Permission.DELETE) != Permission.DELETE) {
OKMAuth.getInstance().revokeUser(null, folder, remoteUser, Permission.DELETE, false);
}
if ((permission & Permission.WRITE) != Permission.WRITE) {
OKMAuth.getInstance().revokeUser(null, folder, remoteUser, Permission.WRITE, false);
}
if ((permission & Permission.SECURITY) != Permission.SECURITY) {
OKMAuth.getInstance().revokeUser(null, folder, remoteUser, Permission.SECURITY, false);
}
} else {
OKMAuth.getInstance().revokeUser(null, folder, remoteUser, allGrants, false);
}
}
}
}
} | codelibs/n2dms | src/main/java/com/openkm/extension/servlet/MacrosServlet.java | Java | gpl-2.0 | 12,894 |
package com.kodeiinia;
import com.kodeiinia.admin.AdminController;
import com.mongodb.MongoClient;
import com.mongodb.DB;
public class Main {
public static DB evoluutioDb = setDb();
public static void main(String[] args) {
EvolutionController baseRoutes = new EvolutionController(evoluutioDb);
AdminController adminRoutes = new AdminController(evoluutioDb);
}
static DB setDb() {
try {
// Connect to MongoDB using the default port on your local machine
MongoClient mongoClient = new MongoClient("localhost");
DB db = mongoClient.getDB("evolutiondb");
System.out.println("Connecting to MongoDB@" + mongoClient.getAllAddress());
return db;
} catch (Exception e) {
System.out.println(e.getMessage());
return null;
}
}
}
| kodeiinikooprat/evoluutio | src/main/java/com/kodeiinia/Main.java | Java | gpl-2.0 | 871 |
/*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2018 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2018 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 Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <[email protected]>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.netmgt.telemetry.protocols.sflow.parser.proto.flows;
import org.bson.BsonWriter;
import org.opennms.netmgt.telemetry.listeners.utils.BufferUtils;
import org.opennms.netmgt.telemetry.protocols.sflow.parser.SampleDatagramEnrichment;
import org.opennms.netmgt.telemetry.protocols.sflow.parser.InvalidPacketException;
import com.google.common.base.MoreObjects;
import com.google.common.primitives.UnsignedLong;
import io.netty.buffer.ByteBuf;
// struct of_port {
// unsigned hyper datapath_id;
// unsigned int port_no;
// };
public class OfPort implements CounterData {
public final UnsignedLong datapath_id;
public final long port_no;
public OfPort(final ByteBuf buffer) throws InvalidPacketException {
this.datapath_id = BufferUtils.uint64(buffer);
this.port_no = BufferUtils.uint32(buffer);
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("datapath_id", this.datapath_id)
.add("port_no", this.port_no)
.toString();
}
@Override
public void writeBson(final BsonWriter bsonWriter, final SampleDatagramEnrichment enr) {
bsonWriter.writeStartDocument();
bsonWriter.writeInt64("datapath_id", this.datapath_id.longValue());
bsonWriter.writeInt64("port_no", this.port_no);
bsonWriter.writeEndDocument();
}
}
| jeffgdotorg/opennms | features/telemetry/protocols/sflow/parser/src/main/java/org/opennms/netmgt/telemetry/protocols/sflow/parser/proto/flows/OfPort.java | Java | gpl-2.0 | 2,613 |
package org.paradise.etrc.dialog;
import static org.paradise.etrc.ETRC.__;
import static org.paradise.etrc.ETRCUtil.DEBUG;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.time.Instant;
import java.util.List;
import java.util.Vector;
import java.util.stream.Collectors;
import javax.swing.BorderFactory;
import javax.swing.BoundedRangeModel;
import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.Timer;
import javax.swing.border.EmptyBorder;
import org.paradise.etrc.MainFrame;
import org.paradise.etrc.data.Train;
import org.paradise.etrc.data.skb.ETRCSKB;
/**
* @author [email protected]
* @version 1.0
*/
public class FindTrainsDialog extends JDialog {
private static final long serialVersionUID = -609136239072858202L;
private ProgressPanel progressPanel = new ProgressPanel();
private JLabel msgLabel;
private MainFrame mainFrame;
public FindTrainsDialog(MainFrame parent) {
super(parent);
mainFrame = parent;
try {
jbInit();
} catch (Exception e) {
e.printStackTrace();
}
}
private void jbInit() throws Exception {
this.setTitle(__("Finding Train Information"));
ImageIcon image = new ImageIcon(org.paradise.etrc.MainFrame.class.getResource("/pic/msg.png"));
JLabel imageLabel = new JLabel();
imageLabel.setIcon(image);
msgLabel = new JLabel(__("Removing existing train data, please wait..."));
msgLabel.setFont(new java.awt.Font("Dialog", 0, 12));
JPanel messagePanel = new JPanel();
messagePanel.setLayout(new BorderLayout());
messagePanel.setBorder(new EmptyBorder(4,4,4,4));
messagePanel.add(imageLabel, BorderLayout.WEST);
messagePanel.add(msgLabel, BorderLayout.CENTER);
JPanel rootPanel = new JPanel();
rootPanel.setLayout(new BorderLayout());
rootPanel.setBorder(BorderFactory.createRaisedBevelBorder());
rootPanel.add(progressPanel, BorderLayout.SOUTH);
rootPanel.add(messagePanel, BorderLayout.CENTER);
this.getContentPane().add(rootPanel, BorderLayout.CENTER);
int w = imageLabel.getPreferredSize().width
+ msgLabel.getPreferredSize().width + 40;
int h = messagePanel.getPreferredSize().height
+ progressPanel.getPreferredSize().height + 20;
this.setSize(w, h);
setResizable(false);
}
public void findTrains() {
Dimension dlgSize = this.getPreferredSize();
Dimension frmSize = mainFrame.getSize();
Point loc = mainFrame.getLocation();
this.setLocation((frmSize.width - dlgSize.width) / 2 + loc.x,
(frmSize.height - dlgSize.height) / 2 + loc.y);
this.setModal(true);
this.pack();
new Thread(new LoadingThread()).start();
setVisible(true);
}
class LoadingThread implements Runnable {
public void run() {
hold(500);
mainFrame.chart.clearTrains();
mainFrame.chartView.repaint();
msgLabel.setText(__("Please wait while imporing train information..."));
ETRCSKB skb = mainFrame.getSKB();
List<Train> trains = skb.findTrains(mainFrame.chart.allCircuits.stream()); //skb.findTrains(mainFrame.chart.trunkCircuit);
Instant instant1 = null, instant2 = null;
if (DEBUG())
instant1= Instant.now();
trains.stream().parallel()
.filter(train-> (train.isDownTrain(mainFrame.chart.railroadLine) > 0))
.forEach(train-> {
mainFrame.chart.addTrain(train);
msgLabel.setText(String.format(__("Importing train information %s"), train.getTrainName()));
});
if (DEBUG())
instant2= Instant.now();
DEBUG("Benchmark: [import circuit]: %d", instant2.toEpochMilli() - instant1.toEpochMilli());
// for(int i=0; i<trains.size(); i++) {
// Train loadingTrain = (Train) (trains.get(i));
//
// if(loadingTrain.isDownTrain(mainFrame.chart.trunkCircuit, false) > 0) {
// mainFrame.chart.addTrain(loadingTrain);
//
// msgLabel.setText(String.format(__("Importing train information %s"), loadingTrain.getTrainName()));
// hold(50);
// }
// }
mainFrame.chartView.repaint();
mainFrame.sheetView.updateData();
mainFrame.runView.refresh();
progressPanel.gotoEnd();
hold(200);
dispose();
}
private void hold(long time) {
try {
Thread.sleep(time);
} catch (InterruptedException e) {
}
}
}
class ProgressPanel extends JPanel
{
private static final long serialVersionUID = -2195298227589227704L;
private JProgressBar pb;
public ProgressPanel() {
pb = new JProgressBar();
pb.setPreferredSize(new Dimension(200,20));
// 设置定时器,用来控制进度条的处理
Timer time = new Timer(1,new ActionListener() {
int counter = 0;
public void actionPerformed(ActionEvent e) {
counter++;
pb.setValue(counter);
Timer t = (Timer)e.getSource();
// 如果进度条达到最大值重新开发计数
if (counter == pb.getMaximum())
{
t.stop();
counter =0;
t.start();
}
}
});
time.start();
//pb.setStringPainted(true);
pb.setMinimum(0);
pb.setMaximum(300);
pb.setBackground(Color.white);
pb.setForeground(Color.red);
this.add(pb);
}
/**
* 设置进度条的数据模型
*/
public void setProcessBar(BoundedRangeModel rangeModel) {
pb.setModel(rangeModel);
}
public void gotoEnd() {
pb.setValue(pb.getMaximum());
}
}
}
| zearon/train-graph | ETRC/src/org/paradise/etrc/dialog/FindTrainsDialog.java | Java | gpl-2.0 | 6,195 |
/*
* Copyright (c) 2007 Pentaho Corporation. All rights reserved.
* This software was developed by Pentaho Corporation and is provided under the terms
* of the GNU Lesser General Public License, Version 2.1. You may not use
* this file except in compliance with the license. If you need a copy of the license,
* please go to http://www.gnu.org/licenses/lgpl-2.1.txt. The Original Code is Pentaho
* Data Integration. The Initial Developer is Pentaho Corporation.
*
* Software distributed under the GNU Lesser Public License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to
* the license for the specific language governing your rights and limitations.
*/
package com.panet.imeta.job.entries.sql;
import com.panet.imeta.i18n.BaseMessages;
public class Messages
{
public static final String packageName = Messages.class.getPackage().getName();
public static String getString(String key)
{
return BaseMessages.getString(packageName, key);
}
public static String getString(String key, String param1)
{
return BaseMessages.getString(packageName, key, param1);
}
public static String getString(String key, String param1, String param2)
{
return BaseMessages.getString(packageName, key, param1, param2);
}
public static String getString(String key, String param1, String param2, String param3)
{
return BaseMessages.getString(packageName, key, param1, param2, param3);
}
public static String getString(String key, String param1, String param2, String param3,
String param4)
{
return BaseMessages.getString(packageName, key, param1, param2, param3, param4);
}
public static String getString(String key, String param1, String param2, String param3,
String param4, String param5)
{
return BaseMessages.getString(packageName, key, param1, param2, param3, param4, param5);
}
public static String getString(String key, String param1, String param2, String param3,
String param4, String param5, String param6)
{
return BaseMessages.getString(packageName, key, param1, param2, param3, param4, param5,
param6);
}
}
| panbasten/imeta | imeta2.x/imeta-src/imeta/src/main/java/com/panet/imeta/job/entries/sql/Messages.java | Java | gpl-2.0 | 2,269 |
/* ========================================================================
* PlantUML : a free UML diagram generator
* ========================================================================
*
* (C) Copyright 2009-2014, Arnaud Roques
*
* Project Info: http://plantuml.sourceforge.net
*
* This file is part of PlantUML.
*
* PlantUML 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.
*
* PlantUML 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 library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Java is a trademark or registered trademark of Sun Microsystems, Inc.
* in the United States and other countries.]
*
* Original Author: Arnaud Roques
*
* Revision $Revision: 4236 $
*
*/
package net.sourceforge.plantuml.svek.extremity;
import java.awt.geom.Point2D;
import net.sourceforge.plantuml.ugraphic.UChangeBackColor;
import net.sourceforge.plantuml.ugraphic.UGraphic;
import net.sourceforge.plantuml.ugraphic.UPolygon;
class ExtremityTriangle extends Extremity {
private UPolygon polygon = new UPolygon();
private final boolean fill;
public ExtremityTriangle(Point2D p1, double angle, boolean fill) {
this.fill = fill;
angle = manageround(angle);
polygon.addPoint(0, 0);
final int xAile = 8;
final int yOuverture = 3;
polygon.addPoint(-xAile, -yOuverture);
polygon.addPoint(-xAile, yOuverture);
polygon.addPoint(0, 0);
polygon.rotate(angle + Math.PI / 2);
polygon = polygon.translate(p1.getX(), p1.getY());
}
public void drawU(UGraphic ug) {
if (fill) {
ug = ug.apply(new UChangeBackColor(ug.getParam().getColor()));
}
ug.draw(polygon);
}
}
| jensnerche/plantuml | src/net/sourceforge/plantuml/svek/extremity/ExtremityTriangle.java | Java | gpl-2.0 | 2,217 |
package com.fangbinbin.dao;
import java.util.List;
import com.fangbinbin.model.Contact;
public interface ContactDAO {
public void addContact(Contact contact);
public List<Contact> listContact();
public void removeContact(Integer id);
} | fangbinbin/RestService | src/main/java/com/fangbinbin/dao/ContactDAO.java | Java | gpl-2.0 | 243 |
package org.fao.fenix.maps.util;
import org.apache.axis2.AxisFault;
import org.apache.log4j.Logger;
import org.fao.fenix.maps.bean.map.BBox;
import org.fao.fenix.maps.bean.map.join.JoinInfo;
import org.fao.fenix.wds.core.bean.DBBean;
import org.fao.fenix.wds.core.bean.FWDSBean;
import org.fao.fenix.wds.core.bean.OrderByBean;
import org.fao.fenix.wds.core.bean.SQLBean;
import org.fao.fenix.wds.core.constant.DATASOURCE;
import org.fao.fenix.wds.core.constant.SQL;
import org.fao.fenix.wds.core.exception.WDSException;
import org.fao.fenix.wds.core.sql.Bean2SQL;
import org.fao.fenix.wds.tools.client.WDSClient;
import org.json.simple.JSONArray;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;
public class DataServiceUtils {
private String wdsURL;
private String wdsIP;
private String wdsPORT;
private final static Logger LOGGER = Logger.getLogger(DataServiceUtils.class);
public Map<String, JoinInfo> getPointData(String tablename, String codeColumn, Map<String, Double> map, String language) throws AxisFault {
Map<String, JoinInfo> joinInfo = new HashMap<String, JoinInfo>();
List<JoinInfo> values = getPointDataList(tablename, codeColumn, map, language);
for(JoinInfo value : values)
joinInfo.put(value.getCode(), value);
return joinInfo;
}
public BBox getBBox(String tablename, String codeColumn, String code, String srs) throws AxisFault {
BBox bbox = null;
String urlParameters = "out=json&db="+ DATASOURCE.FENIX +"&select=minx,miny,maxx,maxy&from=geo_conversion_table&where="+ codeColumn +"('"+ code +"')";
URL url;
try {
url = new URL(wdsURL + "/api");
URLConnection conn;
conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(urlParameters);
writer.flush();
String line;
String result = "";
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
result = line;
}
JSONParser parser = new JSONParser();
Object obj = parser.parse(result);
JSONArray inputArray = (JSONArray) obj;
for(int i=1; i < inputArray.size(); i++) {
JSONArray row = (JSONArray) inputArray.get(i);
bbox = new BBox(srs, Double.valueOf(row.get(0).toString()), Double.valueOf(row.get(1).toString()), Double.valueOf(row.get(2).toString()),Double.valueOf(row.get(3).toString()));
}
writer.close();
reader.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
catch (ParseException e) {
e.printStackTrace();
}
return bbox;
}
public Map<String, Double> getAreas(String tablename, String codeColumn, String areaColumn, Map<String, Double> map) throws AxisFault {
// http://fenix.fao.org/wds/api?out=json&db=fenix&select=faost_code,area_dd&from=geo_conversion_table&where=faost_code('35':'130')
Map<String, Double> values = new HashMap<String, Double>();
String codes = getCodesString(map);
String urlParameters = "out=json&db="+ DATASOURCE.FENIX +"&select=" + codeColumn + ",area_dd&from=geo_conversion_table&where="+ codeColumn +"("+ codes +")";
URL url;
try {
url = new URL(wdsURL + "/api");
URLConnection conn;
conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(urlParameters);
writer.flush();
String line;
String result = "";
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
result = line;
}
JSONParser parser = new JSONParser();
Object obj = parser.parse(result);
JSONArray inputArray = (JSONArray) obj;
for(int i=1; i < inputArray.size(); i++) {
JSONArray v = (JSONArray) inputArray.get(i);
values.put(v.get(0).toString(), Double.valueOf(v.get(1).toString()));
}
writer.close();
reader.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
catch (ParseException e) {
e.printStackTrace();
}
return values;
}
public String getPointFromBBox(String tablename, String xmin, String ymin, String xmax, String ymax) throws AxisFault {
WDSClient c = new WDSClient(wdsIP, wdsPORT);
DBBean db = new DBBean(DATASOURCE.FENIX);
SQLBean sql = getPointsFromBBox(tablename, xmin, ymin, xmax, ymax);
FWDSBean b = new FWDSBean(sql, db);
LOGGER.info(Bean2SQL.convert(sql));
List<List<String>> table = new ArrayList<List<String>>();
try {
table = c.querySynch(b);
} catch (WDSException e) {
e.printStackTrace();
}
System.out.println(table);
String s = "({ \"type\":\"FeatureCollection\",\"features\":[";
int i = 0;
for (List<String> row : table) {
try {
s += "{\"type\":\"Feature\",\"properties\":{\"name\":\"Countrys\",\"iconurl\":\"http://localhost:8080/maps/libs/images/black_marker.png\",\"popupContent\":\"and the country is?<br> <b>"+ row.get(0) +"</b> ("+ row.get(1) +")\"},\"geometry\":{\"type\":\"Point\",\"coordinates\":["
+ row.get(2) + "," + row.get(3) + "]}}";
if (i < table.size() - 1) {
s += ",";
}
}catch (Exception e) {
}
i++;
}
s += "]})";
return s;
}
public String getCrowdPricesData(String tablename, String commodityCode, String date) throws AxisFault {
WDSClient c = new WDSClient(wdsIP, wdsPORT);
DBBean db = new DBBean(DATASOURCE.STAGINGAREA);
SQLBean sql = getCrowdPricesPoints(tablename, commodityCode, date);
FWDSBean b = new FWDSBean(sql, db);
// LOGGER.info(Bean2SQL.convert(sql));
List<List<String>> table = new ArrayList<List<String>>();
try {
table = c.querySynch(b);
} catch (WDSException e) {
e.printStackTrace();
}
System.out.println(table);
String s = "({ \"type\":\"FeatureCollection\",\"features\":[";
int i = 0;
LinkedHashMap<String, List<List<String>>> markets = getCrowdPricesPoints(table);
for(String marketname : markets.keySet()) {
String popupcontent = "<b>" + marketname + "</b><br>";
String lat ="";
String lon = "";
for(List<String> row : markets.get(marketname)) {
popupcontent += row.get(1).replace("_", " ") +" - "+ row.get(2) +" ("+ row.get(3).replace("_", " ") +") <br>";
lon = row.get(4);
lat = row.get(5);
}
System.out.println("popup: " + popupcontent);
s += "{\"type\":\"Feature\",\"properties\":{\"name\":\"Countrys\",\"iconurl\":\"http://localhost:8080/maps/libs/images/black_down_circular.png\"," +
"\"popupContent\":\""+ popupcontent+" \"},\"geometry\":{\"type\":\"Point\",\"coordinates\":["
+ lon + "," + lat + "]}}";
if (i < table.size() - 1) {
s += ",";
}
i++;
}
s += "]})";
return s;
}
private LinkedHashMap<String, List<List<String>>> getCrowdPricesPoints(List<List<String>> table) {
LinkedHashMap<String, List<List<String>>> markets = new LinkedHashMap<String, List<List<String>>>();
for (List<String> row : table) {
String marketname = row.get(0);
List<List<String>> rows = new ArrayList<List<String>>();
if ( markets.containsKey(marketname)) {
rows = markets.get(marketname);
}
rows.add(row);
markets.put(marketname, rows);
}
System.out.println(markets);
return markets;
}
private List<JoinInfo> getPointDataList(String tablename, String codeColumn, Map<String, Double> map, String language) throws AxisFault {
List<JoinInfo> values = new ArrayList<JoinInfo>();
// http://fenix.fao.org/wds/api?out=json&db=fenix&select=faost_code,area_dd&from=geo_conversion_table&where=faost_code('35':'130')
String codes = getCodesString(map);
String urlParameters =
"out=json" +
"&db="+ DATASOURCE.FENIX +"" +
"&select="+ codeColumn +"," +
"label"+ language+",lat,lon" +
"&from=geo_conversion_table" +
"&where="+ codeColumn +"("+ codes +")";
URL url;
try {
LOGGER.info("wdsURL: " + wdsURL);
LOGGER.info("urlParameters: " + urlParameters);
url = new URL(wdsURL + "/api");
URLConnection conn;
conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(urlParameters);
writer.flush();
String line;
String result = "";
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
result = line;
}
LOGGER.info("getPointDataList: " + result);
JSONParser parser = new JSONParser();
Object obj = parser.parse(result);
JSONArray inputArray = (JSONArray) obj;
for(int i=1; i < inputArray.size(); i++) {
JSONArray row = (JSONArray) inputArray.get(i);
String label = row.get(1).toString().replace("'", " ");
values.add(new JoinInfo(row.get(0).toString(), label, Double.valueOf(row.get(2).toString()), Double.valueOf(row.get(3).toString())));
}
writer.close();
reader.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
catch (ParseException e) {
e.printStackTrace();
}
return values;
}
private SQLBean getPointData(String tablename, String codeColumn, String[] codes, String language) {
SQLBean sql = new SQLBean();
sql.select(null, "D."+codeColumn , "code");
sql.select(null, "D.label"+ language, "label");
sql.select(null, "D.lat", "label");
sql.select(null, "D.lon", "label");
sql.from(tablename, "D");
sql.where(SQL.TEXT.name(), codeColumn, "IN", null, codes);
return sql;
}
private SQLBean getAreasData(String tablename, String codeColumn, String areaColumn, String[] codes) {
SQLBean sql = new SQLBean();
sql.select(null, "D."+codeColumn , "code");
sql.select(null, "D."+ areaColumn, "area");
sql.from(tablename, "D");
sql.where(SQL.TEXT.name(), codeColumn, "IN", null, codes);
return sql;
}
private SQLBean getPointsFromBBox(String tablename, String xmin, String ymin, String xmax, String ymax) {
SQLBean sql = new SQLBean();
sql.select(null, "D.labele", "label");
sql.select(null, "D.capitale", "label");
sql.select(null, "D.lon", "lon");
sql.select(null, "D.lat", "lat");
sql.from(tablename, "D");
sql.where(SQL.DATE.name(), "D.lon", ">", xmin, null);
sql.where(SQL.DATE.name(), "D.lon", "<", xmax, null);
sql.where(SQL.DATE.name(), "D.lat", ">", ymin, null);
sql.where(SQL.DATE.name(), "D.lat", "<", ymax, null);
return sql;
}
private SQLBean getCrowdPricesPoints(String tablename, String commodityCode, String date) {
SQLBean sql = new SQLBean();
sql.select(null, "M.marketnamee", "b");
sql.select(null, "D.commoditycode", "b");
sql.select(null, "D.value", "a");
sql.select(null, "D.unitcode", "b");
// TODO: lat e lon is wrong on the DB
sql.select(null, "M.lon", "lon");
sql.select(null, "M.lat", "lat");
sql.from(tablename, "D");
sql.from("crowdprices_market","M");
sql.where(SQL.DATE.name(), "D.marketcode", "=", "M.marketcode", null);
sql.where(SQL.DATE.name(), "D.commoditycode", "=", "'" +commodityCode +"'", null);
sql.where(SQL.DATE.name(), "D.date", "=", "'" +date + "'", null);
sql.orderBy(new OrderByBean("M.marketcode", "ASC"));
return sql;
}
private SQLBean getBBox(String tablename, String codeColumn, String[] codes) {
SQLBean sql = new SQLBean();
sql.select(null, "D.minx", "minlon");
sql.select(null, "D.miny", "minlat");
sql.select(null, "D.maxx", "maxlon");
sql.select(null, "D.maxy", "maxlat");
sql.from(tablename, "D");
sql.where(SQL.TEXT.name(), codeColumn, "IN", null, codes);
return sql;
}
private String[] getCodes(Map<String, Double> map) {
String[] values = new String[map.size()];
int i = 0;
for(String key : map.keySet()) {
values[i] = "'" + key + "'";
i++;
}
return values;
}
private String getCodesString(Map<String, Double> map) {
String values = "";
for(String key : map.keySet()) {
values += "'" + key + "':";
}
if ( !values.equals(""))
values.substring(0, map.size() -1);
return values;
}
public void setWdsIP(String wdsIP) {
this.wdsIP = wdsIP;
}
public void setWdsPORT(String wdsPORT) {
this.wdsPORT = wdsPORT;
}
public void setWdsURL(String wdsURL) {
this.wdsURL = wdsURL;
}
}
| FENIX-Platform/MAPS | maps-core/src/main/java/org/fao/fenix/maps/util/DataServiceUtils.java | Java | gpl-2.0 | 12,772 |
/*
* CalculatorForm.java
*
* Created on Feb 21, 2009, 7:11:13 PM
*
* Copyright (C) 2009 XXX All Rights Reserved.
* This software is the proprietary information of XXX
*
*/
package shell.ext;
// Java library
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Canvas;
// MatuX library
import com.mxme.shell.Element;
import com.mxme.shell.Shell;
import com.mxme.shell.core.Button;
// Internal
import app.MainCanvas;
import shell.AppShell;
import shell.StandardLayout;
import calculator.Calculator;
import util.Text;
import util.Font;
import util.Gfx;
/**
* Author: MatuX
* Date: Feb 21, 2009
* Current revision: 0
* Last modified: Feb 21, 2009
* By: MatuX
* Reviewers:
*
*/
public class PaintCountForm extends Element
{
// Form components
private TextBox boxWallAmount;
private Button buttonContinue;
private Viewer viewerMiniHelp;
// Form behavior
private boolean msgAboveMaxWalls, msgWriteSomething;
// Cursor
private Element currentSelection = null;
private boolean alreadyChanged = false;
// Screen
private final int startX = (Shell.m_nScreenWidthHalf >> 2) - (Shell.m_nMarginY >> 1);
/**
* Constructor
*
*/
public PaintCountForm()
{
m_nTitle = Text.str_CALCULATOR_TYPE_PINTURA;
}
/****
* Initialize this element
*
* @param none
*
*/
public void initialize()
{
Gfx.loadPackage(Gfx.pkgDemoForm);
setSoftButtons(Shell.m_nIDOk, Shell.m_nIDMenu);
// Init text boxes
boxWallAmount = new TextBox("", Font.VERDANA_MEDIUM_NUMBERS, Gfx.imgCalculatorTextBox.image);
boxWallAmount.initialize();
boxWallAmount.onlyNumbers(true);
boxWallAmount.maxChars = 2;
boxWallAmount.setDefaultSoftButtons(Shell.m_nIDMenu, Shell.m_nIDClear);
currentSelection = boxWallAmount;
// Init button
buttonContinue = new Button(Gfx.imgCalculatorButton.image, null, Gfx.imgCalculatorButtonText.image, Gfx.imgCalculatorButtonSel.image);
buttonContinue.initialize();
buttonContinue.x = startX + Gfx.imgCalculatorTextBox.image.getWidth() + (Gfx.imgCalculatorButton.image.getWidth() >> 1) + Shell.m_nMarginX;
//buttonContinue.setDefaultSoftButtons(Shell.m_nIDOk, Shell.m_nIDBack);
if( Shell.m_nScreenHeight <= 128 )
buttonContinue.x -= Shell.m_nMarginX * 3;
alreadyChanged = false;
// set messages
msgAboveMaxWalls = false;
// enable default element
enableElement(boxWallAmount);
// Create viewer
viewerMiniHelp = new Viewer(Text.str_TERMS, Text.str_CANTPAREDESHELP_MINI, Viewer.TYPE_SCROLL);
viewerMiniHelp.initialize();
}
/****
* Deinitialize this element
*
* @param none
*
*/
public void deinitialize()
{
Gfx.unloadPackage(Gfx.pkgDemoForm);
boxWallAmount = null;
buttonContinue = null;
currentSelection = null;
alreadyChanged = false;
}
/**
* Paint the element
*
* @param g, Graphics object
*
*/
public void paint(Graphics g)
{
// Set soft buttons
//setSoftButtons(Shell.m_nIDMenu, currentSelection.m_nRightSoftButton);
setSoftButtons(currentSelection.m_nLeftSoftButton, currentSelection.m_nRightSoftButton);
// get standard layout
//#if GFX_RES_ULTRALOW == "true"
//# g.drawImage(Gfx.imgProfileBack.image, 0, Shell.m_nScreenHeight - 1, Graphics.BOTTOM|Graphics.LEFT);
//# ((StandardLayout)m_standardLayout).drawTerms(g, this);
//# m_standardLayout.draw_title(g, this);
//# m_standardLayout.draw_command_buttons(g, this);
//#else
m_standardLayout.draw_standard_layout(g, this);
//#endif
// Draw subtitle
int y = Gfx.imgStdTitle.image.getHeight();
g.drawImage(Gfx.imgCalculatorSubtitle.image, 0, y, Graphics.TOP|Graphics.LEFT);
y += Gfx.imgCalculatorSubtitle.image.getHeight() + (Shell.m_nMarginY << 2);
// Textbox and Button
boxWallAmount.x = startX;
if( Shell.m_nScreenHeight <= 128 )
boxWallAmount.x -= Shell.m_nMarginX * 3;
boxWallAmount.y = y;
boxWallAmount.paint(g);
buttonContinue.y = y;
buttonContinue.paint(g);
int buttonH = Gfx.imgCalculatorButton.image.getHeight();
y += buttonH << 1;// + Shell.m_nMarginY;
// Some general settings
Font.set(Font.VERDANA_MEDIUM_BOLD_GRAY);
int x = startX;
int w = Shell.m_nScreenWidth - (x << 1);
int lowerBoxH = AppShell.usableMenuHeight() - buttonH - (Shell.m_nMarginY << 1);
//#if GFX_RES_ULTRALOW == "true"
//# lowerBoxH += Font.getHeight();
//#endif
// Message boxes
int intMarginX = Shell.m_nMarginX << 1;
int boxH = lowerBoxH;
Font.set(Font.VERDANA_MEDIUM_BOLD_RED);
int align = Font.FONT_ALIGN_CENTER|Font.FONT_ALIGN_VCENTER;
int textW = w - intMarginX;
int textH = boxH;
int textX = startX;
int textY = y;
int boxX = textX;
// Super ultra hack
if( Shell.m_nScreenHeight <= 160 )
{
textX -= intMarginX * 2;
textW += intMarginX * 5;
w = textW;
boxX = textX;
textX -= intMarginX * 2;
textW += intMarginX * 2;
textH += intMarginX;
}
if( msgAboveMaxWalls || msgWriteSomething )
{
String s = msgWriteSomething? Text.get(Text.str_WRITE_SOMETHING) : Text.get(Text.str_ABOVE_MAX_WALLS);
//g.setColor(0xefc108);
//g.fillRect(boxX, textY, w, boxH);
Font.drawMultiline(g, s, textX, textY - Font.getHeight(), textW, textH, align);
}
else
{
// Load code text
viewerMiniHelp.paintText(g, x, y, w, lowerBoxH);
y += (Font.getHeight() << 1) + Shell.m_nMarginY;
}
// change control
if( boxWallAmount.isEnabled && boxWallAmount.getCurPos() >= boxWallAmount.maxChars && !alreadyChanged )
{
keyPressed(-1, Canvas.FIRE);
alreadyChanged = true;
}
}
/**
* Process the element
*
* @param none
*
*/
public boolean keyPressed(int p_nAction, int keyCode)
{
boolean handled = false;
handled = currentSelection.keyPressed(p_nAction, keyCode);
if( !handled )
{
if( (keyCode == Canvas.FIRE || p_nAction == Shell.m_nIDOk) )
{
if( currentSelection == boxWallAmount )
{
enableElement(buttonContinue);
handled = true;
}
else if( currentSelection == buttonContinue )
{
if( boxWallAmount.getString().equals("") )
{
msgWriteSomething = true;
msgAboveMaxWalls = false;
boxWallAmount.clear();
enableElement(boxWallAmount);
handled = true;
}
else
{
int wallCount = Integer.parseInt(boxWallAmount.getString());
if( wallCount > 10 || wallCount <= 0 )
{
msgAboveMaxWalls = true;
msgWriteSomething = false;
boxWallAmount.clear();
enableElement(boxWallAmount);
handled = true;
}
else
// Set up our paintCalculator
Calculator.paintCalculator.resetWalls(wallCount);
// We don't set the handle so the Shell loads the next screen
}
}
}
else if( /*p_nAction == Canvas.DOWN ||*/ p_nAction == Canvas.RIGHT )
{
if( currentSelection == boxWallAmount )
enableElement(buttonContinue);
else if( currentSelection == buttonContinue )
enableElement(boxWallAmount);
handled = true;
}
else if( /*p_nAction == Canvas.UP ||*/ p_nAction == Canvas.LEFT )
{
if( currentSelection == boxWallAmount )
enableElement(buttonContinue);
else if( currentSelection == buttonContinue )
enableElement(boxWallAmount);
handled = true;
}
}
if( !handled )
handled = viewerMiniHelp.keyPressed(p_nAction, keyCode);
return handled;
}
public boolean keyReleased(int p_nAction, int keyCode)
{
boolean handled = false;
handled = viewerMiniHelp.keyReleased(p_nAction, keyCode);
return handled;
}
/**
* enableElement
*
* @param e
*
*/
private void enableElement(Element e)
{
if( e.equals(boxWallAmount) )
{
// enable this element
boxWallAmount.enable();
// disable this element
disableElement(buttonContinue);
}
else if( e.equals(buttonContinue) )
{
// enable this element
buttonContinue.enable();
// disable this element
disableElement(boxWallAmount);
}
currentSelection = e;
}
/**
* disableElement
*
* @param e
*
*/
private void disableElement(Element e)
{
if( e.equals(boxWallAmount) )
{
boxWallAmount.disable();
boxWallAmount.showDefaultText = false;
}
else if( e.equals(buttonContinue) )
{
buttonContinue.disable();
}
}
}
| matias-pequeno/ikea-calc-j2me-java | src/shell/ext/PaintCountForm.java | Java | gpl-2.0 | 10,057 |
package net.seninp.jmotif.sax.registry;
/**
* Implements a magic array which keeps track of windows that were processed.
*
* @author psenin
*
*/
public interface SlidingWindowMarkerAlgorithm {
/**
* Marks visited locations (of the magic array).
*
* @param registry The magic array instance.
* @param startPosition The position to start labeling from.
* @param intervalLength The length of the interval to be labeled.
*/
void markVisited(VisitRegistry registry, int startPosition, int intervalLength);
}
| jMotif/SAX | src/main/java/net/seninp/jmotif/sax/registry/SlidingWindowMarkerAlgorithm.java | Java | gpl-2.0 | 536 |
package techplex.core.registry;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fml.common.registry.GameRegistry;
public class RecipeRegistry {
public static void register() {
GameRegistry.addShapelessRecipe(new ItemStack(TPItems.bronzeDust, 4), TPItems.tinDust, TPItems.copperDust, TPItems.copperDust, TPItems.copperDust);
GameRegistry.addRecipe(new ItemStack(TPItems.ironCogwheel, 1), " i ", "iii", " i ", 'i', Items.iron_ingot);
GameRegistry.addRecipe(new ItemStack(TPItems.bronzeCogwheel, 1), " b ", "bbb", " b ", 'b', TPItems.bronzeIngot);
GameRegistry.addRecipe(new ItemStack(TPItems.diamondCogwheel, 1), " d ", "ddd", " d ", 'd', Items.diamond);
GameRegistry.addRecipe(new ItemStack(TPItems.rubber, 1), "rr", "rr", 'r', TPItems.rubberScrap);
GameRegistry.addRecipe(new ItemStack(TPItems.plasticBoard, 1), "ppp", "pgp", "ppp", 'p', TPItems.plastic, 'g', new ItemStack(Items.dye, 1, 2));
GameRegistry.addShapelessRecipe(new ItemStack(TPItems.circuitPaste, 1), TPItems.resin, Items.redstone, Items.water_bucket );
GameRegistry.addShapelessRecipe(new ItemStack(TPItems.circuitGlue, 1), Items.redstone, Items.slime_ball );
GameRegistry.addRecipe(new ItemStack(TPItems.circuitBoard, 1), " p ", " c ", "ggg", 'p', TPItems.plasticBoard, 'c', TPItems.circuitPaste, 'g', TPItems.goldDust);
GameRegistry.addRecipe(new ItemStack(TPBlocks.copperCable, 6), "rrr", "ccc", "rrr", 'c', TPItems.copperIngot, 'r', TPItems.rubber);
GameRegistry.addRecipe(new ItemStack(TPBlocks.tinCable, 6), "rrr", "ttt", "rrr", 't', TPItems.tinIngot, 'r', TPItems.rubber);
//GameRegistry.addShapelessRecipe(new ItemStack(TPBlocks.techplex_log, 1, 0), new Object[] {TPBlocks.techplex_log});
GameRegistry.addSmelting(TPBlocks.copperOre,
new ItemStack(TPItems.copperIngot,1), 0.7f);
GameRegistry.addSmelting(TPBlocks.tinOre,
new ItemStack(TPItems.tinIngot,1), 0.7f);
GameRegistry.addSmelting(TPItems.ironDust,
new ItemStack(Items.iron_ingot,1), 0.35f);
GameRegistry.addSmelting(TPItems.goldDust,
new ItemStack(Items.gold_ingot,1), 0.35f);
GameRegistry.addSmelting(TPItems.copperDust,
new ItemStack(TPItems.copperIngot,1), 0.35f);
GameRegistry.addSmelting(TPItems.tinDust,
new ItemStack(TPItems.tinIngot,1), 0.35f);
GameRegistry.addSmelting(TPItems.bronzeDust,
new ItemStack(TPItems.bronzeIngot,1), 0.35f);
GameRegistry.addSmelting(TPItems.resin,
new ItemStack(TPItems.rubberScrap,1), 0.1f);
GameRegistry.addSmelting(TPItems.rubber,
new ItemStack(TPItems.plastic,1), 0.1f);
}
}
| Auropen/TechPlex | src/main/java/techplex/core/registry/RecipeRegistry.java | Java | gpl-2.0 | 2,586 |
package com.toggle.notifica;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* To work on unit tests, switch the Test Artifact in the Build Variants view.
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | coders-circle/Notifica | android/app/src/test/java/com/notifica/notifica/ExampleUnitTest.java | Java | gpl-2.0 | 312 |
/*
* rtl_tcp_andro is a library that uses libusb and librtlsdr to
* turn your Realtek RTL2832 based DVB dongle into a SDR receiver.
* It independently implements the rtl-tcp API protocol for native Android usage.
* Copyright (C) 2016 by Martin Marinov <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sdrtouch.tools;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import com.sdrtouch.core.devices.SdrDevice;
import java.util.List;
import uts.SpectrumRecorder.R;
public class DeviceDialog extends DialogFragment {
private final static String SDR_DEVICE = "sdrDevice_%d";
private final static String SDR_DEVICES_COUNT = "sdrDevices_count";
public static DialogFragment invokeDialog(List<SdrDevice> devices) {
final Bundle b = new Bundle();
synchronized (devices) {
b.putInt(SDR_DEVICES_COUNT, devices.size());
for (int id = 0; id < devices.size(); id++) {
b.putSerializable(String.format(SDR_DEVICE, id), Check.isNotNull(devices.get(id)));
}
}
final DeviceDialog dmg = new DeviceDialog();
dmg.setArguments(b);
return dmg;
}
@Override @NonNull
public Dialog onCreateDialog(Bundle savedInstanceState) {
final OnDeviceDialog callback = (OnDeviceDialog) getActivity();
final Bundle b = getArguments();
final int devicesCount = b.getInt(SDR_DEVICES_COUNT);
final SdrDevice[] devices = new SdrDevice[devicesCount];
final String[] options = new String[devicesCount];
for (int id = 0; id < devicesCount; id++) {
SdrDevice sdrDevice = (SdrDevice) Check.isNotNull(b.getSerializable(String.format(SDR_DEVICE, id)));
devices[id] = sdrDevice;
options[id] = sdrDevice.getName();
}
return new AlertDialog.Builder(getActivity())
.setItems(options, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
final SdrDevice selected = devices[which];
callback.onDeviceDialogDeviceChosen(selected);
}
})
.setTitle(R.string.choose_device)
.create();
}
@Override
public void onCancel(DialogInterface dialog) {
super.onCancel(dialog);
final OnDeviceDialog callback = (OnDeviceDialog) getActivity();
callback.onDeviceDialogCanceled();
}
public interface OnDeviceDialog {
void onDeviceDialogDeviceChosen(SdrDevice selected);
void onDeviceDialogCanceled();
}
}
| AnthonyQuan/AndroidRTLPower | app/src/main/java/com/sdrtouch/tools/DeviceDialog.java | Java | gpl-2.0 | 3,134 |
package utem_horario;
import java.io.IOException;
import org.jsoup.Connection;
import org.jsoup.Connection.Method;
import org.jsoup.Connection.Response;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.parser.Parser;
public class Dirdoc {
private String horario_url = "http://postulacion.utem.cl/alumnos/horario.php";
private String alumnos_url = "http://postulacion.utem.cl/alumnos";
private String valida = "http://postulacion.utem.cl/valida.php";
private String user;
private String pass;
public Document dirdoc = null;
public Document index = null;
public Dirdoc(String user, String pass) {
// TODO Auto-generated constructor stub
this.pass = pass;
this.user = user;
// establecer una sesion de alumno de dirdoc (Log in)
Response res = null;
try {
res = Jsoup.connect(this.valida).data("rut", this.user)
.data("password", this.pass).data("tipo", "0")
.method(Method.POST).execute();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// parsear las paginas necesarias
try {
index = Jsoup
.connect("http://postulacion.utem.cl/alumnos/index.php")
.cookies(res.cookies()).get();
} catch (Exception e) {
System.out.println("nos fuimos a la B " + e);
}
}
}
| fcanalesS/pdaw | java_wrapper/src/utem_horario/Dirdoc.java | Java | gpl-2.0 | 1,295 |
/* ==================================================================
* 版权: kcit 版权所有 (c) 2013
* 文件: person.service.SgZhengshuService.java
* 创建日期: 2014-04-27 下午 01:22:52
* 功能: 接口:人员证书信息
* 所含类: {包含的类}
* 修改记录:
* 日期 作者 内容
* ==================================================================
* 2014-04-27 下午 01:22:52 蒋根亮 创建文件,实现基本功能
*
* ==================================================================
*/
package com.ccthanking.business.person.service.impl;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import com.ccthanking.common.BusinessUtil;
import com.ccthanking.common.EventManager;
import com.ccthanking.common.YwlxManager;
import com.ccthanking.common.vo.EventVO;
import com.ccthanking.framework.Globals;
import com.ccthanking.framework.common.User;
import com.ccthanking.framework.handle.ActionContext;
import com.ccthanking.framework.log.LogManager;
import com.ccthanking.business.person.vo.SgZhengshuVO;
import com.ccthanking.business.person.dao.SgPersonZhengshuDao;
import com.ccthanking.business.person.dao.SgZhengshuDao;
import com.ccthanking.business.person.service.SgZhengshuService;
import com.ccthanking.framework.service.impl.Base1ServiceImpl;
import com.copj.modules.utils.exception.DaoException;
import com.copj.modules.utils.exception.SystemException;
/**
* <p> SgZhengshuService.java </p>
* <p> 功能:人员证书信息 </p>
*
* <p><a href="SgZhengshuService.java.html"><i>查看源代码</i></a></p>
*
* @author <a href="mailto:[email protected]">蒋根亮</a>
* @version 0.1
* @since 2014-04-27
*
*/
@Service
public class SgZhengshuServiceImpl extends Base1ServiceImpl<SgZhengshuVO, String> implements SgZhengshuService {
private static Logger logger = LoggerFactory.getLogger(SgZhengshuServiceImpl.class);
private SgZhengshuDao sgZhengshuDao;
@Autowired
@Qualifier("sgZhengshuDaoImpl")
public void setSgZhengshuDao(SgZhengshuDao sgZhengshuDao) {
this.sgZhengshuDao = sgZhengshuDao;
}
// @Override
public String queryCondition(String json) throws Exception {
String domresult=sgZhengshuDao.queryCondition(json);
return domresult;
}
public String insert(String json) throws Exception {
String domresult=sgZhengshuDao.insert(json);
return domresult;
}
public String update(String json) throws Exception {
String domresult=sgZhengshuDao.update(json);
return domresult;
}
public String delete(String json) throws Exception {
String domresult=sgZhengshuDao.delete(json);
return domresult;
}
public String queryAllZhengshu() throws Exception {
String domresult=sgZhengshuDao.queryAllZhengshu();
return domresult;
}
public String queryZsByGw(String personUid, String gwUid) throws Exception {
String domresult=sgZhengshuDao.queryZsByGw(personUid, gwUid);
return domresult;
}
public String queryZs(String personUid,String zhengshu_type) throws Exception {
String domresult=sgZhengshuDao.queryZs(personUid, zhengshu_type);
return domresult;
}
}
| tigerisadandan/tianyu | wndjsbg-1.1/src/main/java/com/ccthanking/business/person/service/impl/SgZhengshuServiceImpl.java | Java | gpl-2.0 | 3,605 |
package org.minicastle.crypto.digests;
/**
* implementation of MD5 as outlined in "Handbook of Applied Cryptography", pages 346 - 347.
*/
public class MD5Digest
extends GeneralDigest
{
private static final int DIGEST_LENGTH = 16;
private int H1, H2, H3, H4; // IV's
private int[] X = new int[16];
private int xOff;
/**
* Standard constructor
*/
public MD5Digest()
{
reset();
}
/**
* Copy constructor. This will copy the state of the provided
* message digest.
*/
public MD5Digest(MD5Digest t)
{
super(t);
H1 = t.H1;
H2 = t.H2;
H3 = t.H3;
H4 = t.H4;
System.arraycopy(t.X, 0, X, 0, t.X.length);
xOff = t.xOff;
}
public String getAlgorithmName()
{
return "MD5";
}
public int getDigestSize()
{
return DIGEST_LENGTH;
}
protected void processWord(
byte[] in,
int inOff)
{
X[xOff++] = (in[inOff] & 0xff) | ((in[inOff + 1] & 0xff) << 8)
| ((in[inOff + 2] & 0xff) << 16) | ((in[inOff + 3] & 0xff) << 24);
if (xOff == 16)
{
processBlock();
}
}
protected void processLength(
long bitLength)
{
if (xOff > 14)
{
processBlock();
}
X[14] = (int)(bitLength & 0xffffffff);
X[15] = (int)(bitLength >>> 32);
}
private void unpackWord(
int word,
byte[] out,
int outOff)
{
out[outOff] = (byte)word;
out[outOff + 1] = (byte)(word >>> 8);
out[outOff + 2] = (byte)(word >>> 16);
out[outOff + 3] = (byte)(word >>> 24);
}
public int doFinal(
byte[] out,
int outOff)
{
finish();
unpackWord(H1, out, outOff);
unpackWord(H2, out, outOff + 4);
unpackWord(H3, out, outOff + 8);
unpackWord(H4, out, outOff + 12);
reset();
return DIGEST_LENGTH;
}
/**
* reset the chaining variables to the IV values.
*/
public void reset()
{
super.reset();
H1 = 0x67452301;
H2 = 0xefcdab89;
H3 = 0x98badcfe;
H4 = 0x10325476;
xOff = 0;
for (int i = 0; i != X.length; i++)
{
X[i] = 0;
}
}
//
// round 1 left rotates
//
private static final int S11 = 7;
private static final int S12 = 12;
private static final int S13 = 17;
private static final int S14 = 22;
//
// round 2 left rotates
//
private static final int S21 = 5;
private static final int S22 = 9;
private static final int S23 = 14;
private static final int S24 = 20;
//
// round 3 left rotates
//
private static final int S31 = 4;
private static final int S32 = 11;
private static final int S33 = 16;
private static final int S34 = 23;
//
// round 4 left rotates
//
private static final int S41 = 6;
private static final int S42 = 10;
private static final int S43 = 15;
private static final int S44 = 21;
/*
* rotate int x left n bits.
*/
private int rotateLeft(
int x,
int n)
{
return (x << n) | (x >>> (32 - n));
}
/*
* F, G, H and I are the basic MD5 functions.
*/
private int F(
int u,
int v,
int w)
{
return (u & v) | (~u & w);
}
private int G(
int u,
int v,
int w)
{
return (u & w) | (v & ~w);
}
private int H(
int u,
int v,
int w)
{
return u ^ v ^ w;
}
private int K(
int u,
int v,
int w)
{
return v ^ (u | ~w);
}
protected void processBlock()
{
int a = H1;
int b = H2;
int c = H3;
int d = H4;
//
// Round 1 - F cycle, 16 times.
//
a = rotateLeft((a + F(b, c, d) + X[ 0] + 0xd76aa478), S11) + b;
d = rotateLeft((d + F(a, b, c) + X[ 1] + 0xe8c7b756), S12) + a;
c = rotateLeft((c + F(d, a, b) + X[ 2] + 0x242070db), S13) + d;
b = rotateLeft((b + F(c, d, a) + X[ 3] + 0xc1bdceee), S14) + c;
a = rotateLeft((a + F(b, c, d) + X[ 4] + 0xf57c0faf), S11) + b;
d = rotateLeft((d + F(a, b, c) + X[ 5] + 0x4787c62a), S12) + a;
c = rotateLeft((c + F(d, a, b) + X[ 6] + 0xa8304613), S13) + d;
b = rotateLeft((b + F(c, d, a) + X[ 7] + 0xfd469501), S14) + c;
a = rotateLeft((a + F(b, c, d) + X[ 8] + 0x698098d8), S11) + b;
d = rotateLeft((d + F(a, b, c) + X[ 9] + 0x8b44f7af), S12) + a;
c = rotateLeft((c + F(d, a, b) + X[10] + 0xffff5bb1), S13) + d;
b = rotateLeft((b + F(c, d, a) + X[11] + 0x895cd7be), S14) + c;
a = rotateLeft((a + F(b, c, d) + X[12] + 0x6b901122), S11) + b;
d = rotateLeft((d + F(a, b, c) + X[13] + 0xfd987193), S12) + a;
c = rotateLeft((c + F(d, a, b) + X[14] + 0xa679438e), S13) + d;
b = rotateLeft((b + F(c, d, a) + X[15] + 0x49b40821), S14) + c;
//
// Round 2 - G cycle, 16 times.
//
a = rotateLeft((a + G(b, c, d) + X[ 1] + 0xf61e2562), S21) + b;
d = rotateLeft((d + G(a, b, c) + X[ 6] + 0xc040b340), S22) + a;
c = rotateLeft((c + G(d, a, b) + X[11] + 0x265e5a51), S23) + d;
b = rotateLeft((b + G(c, d, a) + X[ 0] + 0xe9b6c7aa), S24) + c;
a = rotateLeft((a + G(b, c, d) + X[ 5] + 0xd62f105d), S21) + b;
d = rotateLeft((d + G(a, b, c) + X[10] + 0x02441453), S22) + a;
c = rotateLeft((c + G(d, a, b) + X[15] + 0xd8a1e681), S23) + d;
b = rotateLeft((b + G(c, d, a) + X[ 4] + 0xe7d3fbc8), S24) + c;
a = rotateLeft((a + G(b, c, d) + X[ 9] + 0x21e1cde6), S21) + b;
d = rotateLeft((d + G(a, b, c) + X[14] + 0xc33707d6), S22) + a;
c = rotateLeft((c + G(d, a, b) + X[ 3] + 0xf4d50d87), S23) + d;
b = rotateLeft((b + G(c, d, a) + X[ 8] + 0x455a14ed), S24) + c;
a = rotateLeft((a + G(b, c, d) + X[13] + 0xa9e3e905), S21) + b;
d = rotateLeft((d + G(a, b, c) + X[ 2] + 0xfcefa3f8), S22) + a;
c = rotateLeft((c + G(d, a, b) + X[ 7] + 0x676f02d9), S23) + d;
b = rotateLeft((b + G(c, d, a) + X[12] + 0x8d2a4c8a), S24) + c;
//
// Round 3 - H cycle, 16 times.
//
a = rotateLeft((a + H(b, c, d) + X[ 5] + 0xfffa3942), S31) + b;
d = rotateLeft((d + H(a, b, c) + X[ 8] + 0x8771f681), S32) + a;
c = rotateLeft((c + H(d, a, b) + X[11] + 0x6d9d6122), S33) + d;
b = rotateLeft((b + H(c, d, a) + X[14] + 0xfde5380c), S34) + c;
a = rotateLeft((a + H(b, c, d) + X[ 1] + 0xa4beea44), S31) + b;
d = rotateLeft((d + H(a, b, c) + X[ 4] + 0x4bdecfa9), S32) + a;
c = rotateLeft((c + H(d, a, b) + X[ 7] + 0xf6bb4b60), S33) + d;
b = rotateLeft((b + H(c, d, a) + X[10] + 0xbebfbc70), S34) + c;
a = rotateLeft((a + H(b, c, d) + X[13] + 0x289b7ec6), S31) + b;
d = rotateLeft((d + H(a, b, c) + X[ 0] + 0xeaa127fa), S32) + a;
c = rotateLeft((c + H(d, a, b) + X[ 3] + 0xd4ef3085), S33) + d;
b = rotateLeft((b + H(c, d, a) + X[ 6] + 0x04881d05), S34) + c;
a = rotateLeft((a + H(b, c, d) + X[ 9] + 0xd9d4d039), S31) + b;
d = rotateLeft((d + H(a, b, c) + X[12] + 0xe6db99e5), S32) + a;
c = rotateLeft((c + H(d, a, b) + X[15] + 0x1fa27cf8), S33) + d;
b = rotateLeft((b + H(c, d, a) + X[ 2] + 0xc4ac5665), S34) + c;
//
// Round 4 - K cycle, 16 times.
//
a = rotateLeft((a + K(b, c, d) + X[ 0] + 0xf4292244), S41) + b;
d = rotateLeft((d + K(a, b, c) + X[ 7] + 0x432aff97), S42) + a;
c = rotateLeft((c + K(d, a, b) + X[14] + 0xab9423a7), S43) + d;
b = rotateLeft((b + K(c, d, a) + X[ 5] + 0xfc93a039), S44) + c;
a = rotateLeft((a + K(b, c, d) + X[12] + 0x655b59c3), S41) + b;
d = rotateLeft((d + K(a, b, c) + X[ 3] + 0x8f0ccc92), S42) + a;
c = rotateLeft((c + K(d, a, b) + X[10] + 0xffeff47d), S43) + d;
b = rotateLeft((b + K(c, d, a) + X[ 1] + 0x85845dd1), S44) + c;
a = rotateLeft((a + K(b, c, d) + X[ 8] + 0x6fa87e4f), S41) + b;
d = rotateLeft((d + K(a, b, c) + X[15] + 0xfe2ce6e0), S42) + a;
c = rotateLeft((c + K(d, a, b) + X[ 6] + 0xa3014314), S43) + d;
b = rotateLeft((b + K(c, d, a) + X[13] + 0x4e0811a1), S44) + c;
a = rotateLeft((a + K(b, c, d) + X[ 4] + 0xf7537e82), S41) + b;
d = rotateLeft((d + K(a, b, c) + X[11] + 0xbd3af235), S42) + a;
c = rotateLeft((c + K(d, a, b) + X[ 2] + 0x2ad7d2bb), S43) + d;
b = rotateLeft((b + K(c, d, a) + X[ 9] + 0xeb86d391), S44) + c;
H1 += a;
H2 += b;
H3 += c;
H4 += d;
//
// reset the offset and clean out the word buffer.
//
xOff = 0;
for (int i = 0; i != X.length; i++)
{
X[i] = 0;
}
}
}
| AcademicTorrents/AcademicTorrents-Downloader | frostwire-merge/org/minicastle/crypto/digests/MD5Digest.java | Java | gpl-2.0 | 9,034 |
package ro.swl.engine.grammar;
/**
* A grammar is a set of structural entities and rules that governs the
* generation and behavior of a language.
*
* A subclass will return the particular representation of the 'conceptual'
* entity. For example in a plain HTML
* grammar a representation of an input() component will be an '<input>
* tag'.
*
* In a JSF grammar context an input() will be an '<h:inputText>'.
*
* @author VictorBucutea
*
*/
public interface Grammar {
public String inputText();
public String inputTextType();
public String label();
public String labelForAttribute(String id);
public String inputArea();
public String inputAreaType();
public String inputFile();
public String inputFileType();
public String selectbox();
public String selectoption();
public String checkbox();
public String checkboxType();
public String checkboxClass();
public String radio();
public String radioType();
public String radioClass();
public String horizontalLayout();
public String horizontalLayoutClass();
public String horizontalFormClass();
public String horizontalFormControlClass();
public String horizontalFormGroupClass();
public String horizontalFormLabelClass();
public String horizontalLayoutColumn();
public String horizontalLayoutColumnClass(int span);
public String verticalLayout();
public String section();
public String sectionTitle();
public String inlineStyleAttribute(String value);
public String styleClassAttribute(String value);
public String idAttribute(String id);
public String span();
public String button();
public String img();
public String imgModelValueBinding(String modelBinding);
public String radioName(String groupName);
public String imgSrc(String image);
public String verticalLayoutRow();
public String text();
public String verticalLayoutRowClass();
public String buttonClassAttribute();
}
| victorbucutea/swl | engine/parser/src/main/java/ro/swl/engine/grammar/Grammar.java | Java | gpl-2.0 | 1,976 |
package vality;
import vality.expression.OperatorExpression;
import vality.expression.LiteralExpression;
import vality.expression.FieldExpression;
import vality.expression.Expressable;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import junit.framework.TestCase;
import static junit.framework.TestCase.assertEquals;
import static junit.framework.TestCase.assertTrue;
import vality.operator.OperatorException;
import vality.operator.binary.DivOperator;
import vality.operator.binary.MinusOperator;
import vality.operator.binary.MultOperator;
import vality.operator.binary.PlusOperator;
import vality.operator.relational.EqOperator;
import vality.type.IntegerType;
public class ExpressionTest extends TestCase {
public void testExpression1() throws OperatorException {
// 1 + 2 + 3
OperatorExpression e1 = new OperatorExpression(new PlusOperator());
e1.addSubExpression(new LiteralExpression("1", new IntegerType()));
e1.addSubExpression(new LiteralExpression("2", new IntegerType()));
OperatorExpression e2 = new OperatorExpression(new PlusOperator());
e2.addSubExpression(e1);
e2.addSubExpression(new LiteralExpression("3", new IntegerType()));
System.out.println(e2);
assertEquals(e2.toString(), "(+ (+ 1 2) 3)");
}
public void testSimplify1() throws OperatorException {
// 1 + 2 + 3 => 6
OperatorExpression e1 = new OperatorExpression(new PlusOperator());
e1.addSubExpression(new LiteralExpression("1", new IntegerType()));
e1.addSubExpression(new LiteralExpression("2", new IntegerType()));
OperatorExpression e2 = new OperatorExpression(new PlusOperator());
e2.addSubExpression(e1);
e2.addSubExpression(new LiteralExpression("3", new IntegerType()));
System.out.println(e2);
assertEquals(e2.toString(), "(+ (+ 1 2) 3)");
}
public void testEvalSimple() {
LiteralExpression e = new LiteralExpression("2", new IntegerType());
Expressable res = e.reduceToInteger();
assertEquals("2", res.toString());
System.out.println(e + " => " + res);
}
public void testEvalPlus() {
try {
OperatorExpression e1 = new OperatorExpression(new PlusOperator());
e1.addSubExpression(new LiteralExpression("1", new IntegerType()));
e1.addSubExpression(new LiteralExpression("2", new IntegerType()));
Expressable res = e1.reduceToInteger();
assertEquals("3", res.toString());
System.out.println(e1 + " => " + res);
} catch (OperatorException ex) {
Logger.getLogger(ExpressionTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void testEvalDiv() {
try {
OperatorExpression e1 = new OperatorExpression(new DivOperator());
e1.addSubExpression(new LiteralExpression("4", new IntegerType()));
e1.addSubExpression(new LiteralExpression("2", new IntegerType()));
assertTrue(e1.canReduceToInteger());
Expressable res = e1.reduceToInteger();
assertEquals("2", res.toString());
System.out.println(e1 + " => " + res);
} catch (OperatorException ex) {
Logger.getLogger(ExpressionTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void testEvalDivImp() {
try {
OperatorExpression e1 = new OperatorExpression(new DivOperator());
e1.addSubExpression(new LiteralExpression("4", new IntegerType()));
e1.addSubExpression(new LiteralExpression("3", new IntegerType()));
assertFalse(e1.canReduceToInteger());
Expressable res = e1.reduceToInteger();
System.out.println(e1 + " => " + res);
} catch (OperatorException ex) {
Logger.getLogger(ExpressionTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void testEvalComplex() {
try {
// 1 + 2 * 3
OperatorExpression e1 = new OperatorExpression(new PlusOperator());
e1.addSubExpression(new LiteralExpression("1", new IntegerType()));
OperatorExpression e2 = new OperatorExpression(new MultOperator());
e1.addSubExpression(e2);
e2.addSubExpression(new LiteralExpression("2", new IntegerType()));
e2.addSubExpression(new LiteralExpression("3", new IntegerType()));
Expressable res= e1.reduceToInteger();
assertEquals("7", res.toString());
System.out.println(e1 + " => " + res);
} catch (OperatorException ex) {
Logger.getLogger(ExpressionTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void testFindCoefficients1() {
try {
// 2a + 3
OperatorExpression e1 = new OperatorExpression(new PlusOperator());
OperatorExpression e11 = new OperatorExpression(new MultOperator());
e11.addSubExpression(new LiteralExpression("2", new IntegerType()));
e11.addSubExpression(new FieldExpression(new Field(new IntegerType(), "a")));
e1.addSubExpression(e11);
LiteralExpression e2 = new LiteralExpression("3", new IntegerType());
e1.addSubExpression(e2);
Expressable re = e1.reduceCoefficients();
List<Expressable> coefficients = re.collectCoefficients();
System.out.println(e1 + " => coefficients: " + coefficients);
} catch (OperatorException ex) {
Logger.getLogger(ExpressionTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void testFindCoefficients2() {
try {
// 2a + 3b - 4c
OperatorExpression e1 = new OperatorExpression(new MinusOperator());
OperatorExpression e11 = new OperatorExpression(new PlusOperator());
OperatorExpression e111 = new OperatorExpression(new MultOperator());
e111.addSubExpression(new LiteralExpression("2", new IntegerType()));
e111.addSubExpression(new FieldExpression(new Field(new IntegerType(), "a")));
OperatorExpression e112 = new OperatorExpression(new MultOperator());
e112.addSubExpression(new LiteralExpression("3", new IntegerType()));
e112.addSubExpression(new FieldExpression(new Field(new IntegerType(), "b")));
e11.addSubExpression(e111);
e11.addSubExpression(e112);
OperatorExpression e12 = new OperatorExpression(new MultOperator());
e12.addSubExpression(new LiteralExpression("4", new IntegerType()));
e12.addSubExpression(new FieldExpression(new Field(new IntegerType(), "c")));
e1.addSubExpression(e11);
e1.addSubExpression(e12);
Expressable re = e1.reduceMinusesToPluses().reduceCoefficients();
List<Expressable> coefficients = re.collectCoefficients();
System.out.println(e1 + " => re "+ re + " => coefficients: " + coefficients);
} catch (OperatorException ex) {
Logger.getLogger(ExpressionTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void testMultiplyOut() {
try {
// (2 + 3) * 4
LiteralExpression two = new LiteralExpression(2, new IntegerType());
LiteralExpression three = new LiteralExpression(3, new IntegerType());
LiteralExpression four = new LiteralExpression(4, new IntegerType());
OperatorExpression plus = new OperatorExpression(new PlusOperator(), two, three);
OperatorExpression mult = new OperatorExpression(new MultOperator(), four, plus);
System.out.println(mult);
System.out.println(mult.multiplyOut());
} catch (OperatorException ex) {
Logger.getLogger(ExpressionTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void testFactorizeBySimpleExpr() {
try {
// (2 * 3) + (2 * 5) -> 2 * (3 + 5)
// (+ (* 2 3) (* 2 5)) -> (* 2 (+ 3 5))
LiteralExpression two1 = new LiteralExpression(2, new IntegerType());
LiteralExpression three = new LiteralExpression(3, new IntegerType());
LiteralExpression two2 = new LiteralExpression(2, new IntegerType());
LiteralExpression five = new LiteralExpression(5, new IntegerType());
OperatorExpression mult1 = new OperatorExpression(new MultOperator(), two1, three);
OperatorExpression mult2 = new OperatorExpression(new MultOperator(), two2, five);
OperatorExpression plus = new OperatorExpression(new PlusOperator(), mult1, mult2);
assertTrue(plus.canFactorOutSubexpression());
System.out.println(plus.factorOutSubexpression());
assertEquals("(* 2 (+ 3 5))", plus.factorOutSubexpression().toString());
} catch (OperatorException ex) {
Logger.getLogger(ExpressionTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void testCannotFactorizeBySimpleExpr() {
try {
// (2 * 3) + (2 * 5) -> 2 * (3 + 5)
// (+ (* 2 3) (* 2 5)) -> (* 2 (+ 3 5))
LiteralExpression eight = new LiteralExpression(8, new IntegerType());
LiteralExpression three = new LiteralExpression(3, new IntegerType());
LiteralExpression two2 = new LiteralExpression(2, new IntegerType());
LiteralExpression five = new LiteralExpression(5, new IntegerType());
OperatorExpression mult1 = new OperatorExpression(new MultOperator(), eight, three);
OperatorExpression mult2 = new OperatorExpression(new MultOperator(), two2, five);
OperatorExpression plus = new OperatorExpression(new PlusOperator(), mult1, mult2);
assertFalse(plus.canFactorOutSubexpression());
} catch (OperatorException ex) {
Logger.getLogger(ExpressionTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void testFactorizeByComplexExpr() {
try {
// (+ (* (- x 2) 3) (* (- x 2) 5)) -> (* (- x 2) (+ 3 5))
Field x = new Field(new IntegerType(), "x");
FieldExpression x1 = new FieldExpression(x);
LiteralExpression two1 = new LiteralExpression(2, new IntegerType());
OperatorExpression xminus2_1 = new OperatorExpression(new MinusOperator(), x1, two1);
LiteralExpression three = new LiteralExpression(3, new IntegerType());
FieldExpression x2 = new FieldExpression(x);
LiteralExpression two2 = new LiteralExpression(2, new IntegerType());
OperatorExpression xminus2_2 = new OperatorExpression(new MinusOperator(), x2, two2);
LiteralExpression five = new LiteralExpression(5, new IntegerType());
OperatorExpression mult1 = new OperatorExpression(new MultOperator(), xminus2_1, three);
OperatorExpression mult2 = new OperatorExpression(new MultOperator(), xminus2_2, five);
OperatorExpression plus = new OperatorExpression(new PlusOperator(), mult1, mult2);
assertTrue(plus.canFactorOutSubexpression());
System.out.println(plus.factorOutSubexpression());
assertEquals("(* (- x 2) (+ 3 5))", plus.factorOutSubexpression().toString());
} catch (OperatorException ex) {
Logger.getLogger(ExpressionTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void testMoveToOtherSide() {
try {
// (2 + 3) = (4 + 5) -> 2 = (4 + 5) - 3
LiteralExpression two = new LiteralExpression(2, new IntegerType());
LiteralExpression three = new LiteralExpression(3, new IntegerType());
LiteralExpression four = new LiteralExpression(4, new IntegerType());
LiteralExpression five = new LiteralExpression(5, new IntegerType());
OperatorExpression plus1 = new OperatorExpression(new PlusOperator(), two, three);
OperatorExpression plus2 = new OperatorExpression(new PlusOperator(), four, five);
OperatorExpression eq = new OperatorExpression(new EqOperator(), plus1, plus2);
assertTrue(eq.canMoveToOtherSide());
assertEquals("(= 2 (- (+ 4 5) 3))", eq.moveToOtherSide().toString());
} catch (OperatorException ex) {
Logger.getLogger(ExpressionTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
} | christianfriedl/Vality | test/vality/ExpressionTest.java | Java | gpl-2.0 | 12,850 |
package com.kriskrause.learning;
import android.os.AsyncTask;
public abstract class CharTask extends AsyncTask<DataItem, Void, DataItem> {
private ICallbackListener _listener;
abstract DataItem getNext(DataItem... params);
public void setCallback(ICallbackListener listener) {
_listener = listener;
}
@Override
protected DataItem doInBackground(DataItem... params) {
return getNext(params);
}
@Override
protected void onPostExecute(DataItem result) {
_listener.callbackTextChanged(result);
}
@Override
protected void onPreExecute() {
}
@Override
protected void onProgressUpdate(Void... values) {
}
} | dragthor/learning | app/src/main/java/com/kriskrause/learning/CharTask.java | Java | gpl-2.0 | 787 |
package pri.h.uitool;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.graphics.*;
import android.graphics.drawable.Drawable;
import android.view.*;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.AnimationSet;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.RotateAnimation;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
//import android.widget.Toast;
import android.widget.LinearLayout;
public class RadialMenuWidget extends View {
// Defines the interface
public interface RadialMenuEntry {
public String getName();
public String getLabel();
public int getIcon();
public List<RadialMenuEntry> getChildren();
public void menuActiviated();
}
private List<RadialMenuEntry> menuEntries = new ArrayList<RadialMenuEntry>();
private RadialMenuEntry centerCircle = null;
private float screen_density = getContext().getResources()
.getDisplayMetrics().density;
private int defaultColor = Color.rgb(34, 96, 120); // default color of wedge
// pieces
private int defaultAlpha = 180; // transparency of the colors, 255=Opague,
// 0=Transparent
private int wedge2Color = Color.rgb(50, 50, 50); // default color of wedge
// pieces
private int wedge2Alpha = 210;
private int outlineColor = Color.rgb(150, 150, 150); // color of outline
private int outlineAlpha = 255; // transparency of outline
private int selectedColor = Color.rgb(70, 130, 180); // color to fill when
// something is
// selected
private int selectedAlpha = 210; // transparency of fill when something is
// selected
private int disabledColor = Color.rgb(34, 96, 120); // color to fill when
// something is selected
private int disabledAlpha = 100; // transparency of fill when something is
// selected
private int pictureAlpha = 255; // transparency of images
private int textColor = Color.rgb(255, 255, 255); // color to fill when
// something is selected
private int textAlpha = 255; // transparency of fill when something is
// selected
private int headerTextColor = Color.rgb(255, 255, 255); // color of header
// text
private int headerTextAlpha = 255; // transparency of header text
private int headerBackgroundColor = Color.rgb(0, 0, 0); // color of header
// background
private int headerBackgroundAlpha = 180; // transparency of header
// background
private int wedgeQty = 1; // Number of wedges
private Wedge[] Wedges = new Wedge[wedgeQty];
private Wedge selected = null; // Keeps track of which wedge is selected
private Wedge enabled = null; // Keeps track of which wedge is enabled for
// outer ring
private Rect[] iconRect = new Rect[wedgeQty];
private int wedgeQty2 = 1; // Number of wedges
private Wedge[] Wedges2 = new Wedge[wedgeQty2];
private Wedge selected2 = null; // Keeps track of which wedge is selected
private Rect[] iconRect2 = new Rect[wedgeQty2];
private RadialMenuEntry wedge2Data = null; // Keeps track off which menuItem
// data is being used for the
// outer ring
private int MinSize = scalePX(35); // Radius of inner ring size
private int MaxSize = scalePX(90); // Radius of outer ring size
private int r2MinSize = MaxSize + scalePX(5); // Radius of inner second ring
// size
private int r2MaxSize = r2MinSize + scalePX(45); // Radius of outer second
// ring size
private int MinIconSize = scalePX(15); // Min Size of Image in Wedge
private int MaxIconSize = scalePX(35); // Max Size of Image in Wedge
// private int BitmapSize = scalePX(40); //Size of Image in Wedge
private int cRadius = MinSize - scalePX(7); // Inner Circle Radius
private int textSize = scalePX(15); // TextSize
private int animateTextSize = textSize;
private int xPosition = scalePX(120); // Center X location of Radial Menu
private int yPosition = scalePX(120); // Center Y location of Radial Menu
private int xSource = 0; // Source X of clicked location
private int ySource = 0; // Center Y of clicked location
private boolean showSource = false; // Display icon where at source location
private boolean inWedge = false; // Identifies touch event was in first
// wedge
private boolean inWedge2 = false; // Identifies touch event was in second
// wedge
private boolean inCircle = false; // Identifies touch event was in middle
// circle
private boolean Wedge2Shown = false; // Identifies 2nd wedge is drawn
private boolean HeaderBoxBounded = false; // Identifies if header box is
// drawn
private String headerString = null;
private int headerTextSize = textSize; // TextSize
private int headerBuffer = scalePX(8);
private Rect textRect = new Rect();
private RectF textBoxRect = new RectF();
private int headerTextLeft;
private int headerTextBottom;
private ScaleAnimation scale;
private TranslateAnimation move;
private AnimationSet spriteAnimation;
private long animationSpeed = 400L;
private static final int ANIMATE_IN = 1;
private static final int ANIMATE_OUT = 2;
private int animateSections = 4;
private int r2VariableSize;
private boolean animateOuterIn = false;
private boolean animateOuterOut = false;
public RadialMenuWidget(Context context) {
super(context);
// Gets screen specs and defaults to center of screen
this.xPosition = (getResources().getDisplayMetrics().widthPixels) / 2;
this.yPosition = (getResources().getDisplayMetrics().heightPixels) / 2;
determineWedges();
onOpenAnimation();
}
@Override
public boolean onTouchEvent(MotionEvent e) {
int state = e.getAction();
int eventX = (int) e.getX();
int eventY = (int) e.getY();
if (state == MotionEvent.ACTION_DOWN) {
// selected = null;
// selected2 = null;
inWedge = false;
inWedge2 = false;
inCircle = false;
// Checks if a pie slice is selected in first Wedge
for (int i = 0; i < Wedges.length; i++) {
Wedge f = Wedges[i];
double slice = (2 * Math.PI) / wedgeQty;
double start = (2 * Math.PI) * (0.75) - (slice / 2);
// this is done so top slice is the centered on top of the circle
inWedge = pntInWedge(eventX, eventY, xPosition, yPosition,
MinSize, MaxSize, (i * slice) + start, slice);
if (inWedge == true) {
selected = f;
break;
}
}
// Checks if a pie slice is selected in second Wedge
if (Wedge2Shown == true) {
for (int i = 0; i < Wedges2.length; i++) {
Wedge f = Wedges2[i];
double slice = (2 * Math.PI) / wedgeQty2;
double start = (2 * Math.PI) * (0.75) - (slice / 2); // this is done so top slice is the centered on top of the circle
inWedge2 = pntInWedge(eventX, eventY, xPosition, yPosition,
r2MinSize, r2MaxSize, (i * slice) + start, slice);
if (inWedge2 == true) {
selected2 = f;
break;
}
}
}
// Checks if center circle is selected
inCircle = pntInCircle(eventX, eventY, xPosition, yPosition,
cRadius);
} else if (state == MotionEvent.ACTION_UP) {
// execute commands...
// put in stuff here to "return" the button that was pressed.
if (inCircle == true) {
if (Wedge2Shown == true) {
enabled = null;
animateOuterIn = true; // sets Wedge2Shown = false;
}
selected = null;
//呵呵
// Toast.makeText(getContext(),
// centerCircle.getName() + " pressed.",
// Toast.LENGTH_SHORT).show();
// 这里调用事件回调
centerCircle.menuActiviated();
} else if (selected != null) {
for (int i = 0; i < Wedges.length; i++) {
Wedge f = Wedges[i];
if (f == selected) {
// Checks if a inner ring is enabled if so closes the
// outer ring an
if (enabled != null) {
//呵呵
// Toast.makeText(getContext(), "Closing outer ring",
// Toast.LENGTH_SHORT).show();
enabled = null;
animateOuterIn = true; // sets Wedge2Shown = false;
// If outer ring is not enabled, then executes event
} else {
//呵呵
// Toast.makeText(getContext(),
// menuEntries.get(i).getName() + " pressed.@@@@@@@@",
// Toast.LENGTH_SHORT).show();
menuEntries.get(i).menuActiviated();
// Figures out how many outer rings
if (menuEntries.get(i).getChildren() != null) {
determineOuterWedges(menuEntries.get(i));
enabled = f;
animateOuterOut = true; // sets Wedge2Shown =
// true;
} else {
Wedge2Shown = false;
}
}
selected = null;
}
}
} else if (selected2 != null) {
for (int i = 0; i < Wedges2.length; i++) {
Wedge f = Wedges2[i];
if (f == selected2) {
//之前少这句
wedge2Data.getChildren().get(i).menuActiviated();
//在点击事件发生后关闭wedge!
animateOuterIn = true; // sets Wedge2Shown = false;
enabled = null;
selected = null;
}
}
} else {
// This is when something outside the circle or any of the rings
// is selected
//呵呵
// Toast.makeText(getContext(), "Area outside rings pressed.",
// Toast.LENGTH_SHORT).show();
pri.h.semap.myMap.outsideCircleClick();
// selected = null;
// enabled = null;
}
// selected = null;
selected2 = null;
inCircle = false;
}
invalidate();
return true;
}
@Override
protected void onDraw(Canvas c) {
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setStrokeWidth(3);
// draws a dot at the source of the press
if (showSource == true) {
paint.setColor(outlineColor);
paint.setAlpha(outlineAlpha);
paint.setStyle(Paint.Style.STROKE);
c.drawCircle(xSource, ySource, cRadius / 10, paint);
paint.setColor(selectedColor);
paint.setAlpha(selectedAlpha);
paint.setStyle(Paint.Style.FILL);
c.drawCircle(xSource, ySource, cRadius / 10, paint);
}
for (int i = 0; i < Wedges.length; i++) {
Wedge f = Wedges[i];
paint.setColor(outlineColor);
paint.setAlpha(outlineAlpha);
paint.setStyle(Paint.Style.STROKE);
c.drawPath(f, paint);
if (f == enabled && Wedge2Shown == true) {
paint.setColor(wedge2Color);
paint.setAlpha(wedge2Alpha);
paint.setStyle(Paint.Style.FILL);
c.drawPath(f, paint);
} else if (f != enabled && Wedge2Shown == true) {
paint.setColor(disabledColor);
paint.setAlpha(disabledAlpha);
paint.setStyle(Paint.Style.FILL);
c.drawPath(f, paint);
} else if (f == enabled && Wedge2Shown == false) {
paint.setColor(wedge2Color);
paint.setAlpha(wedge2Alpha);
paint.setStyle(Paint.Style.FILL);
c.drawPath(f, paint);
} else if (f == selected) {
paint.setColor(wedge2Color);
paint.setAlpha(wedge2Alpha);
paint.setStyle(Paint.Style.FILL);
c.drawPath(f, paint);
} else {
paint.setColor(defaultColor);
paint.setAlpha(defaultAlpha);
paint.setStyle(Paint.Style.FILL);
c.drawPath(f, paint);
}
Rect rf = iconRect[i];
if ((menuEntries.get(i).getIcon() != 0)
&& (menuEntries.get(i).getLabel() != null)) {
// This will look for a "new line" and split into multiple lines
String menuItemName = menuEntries.get(i).getLabel();
String[] stringArray = menuItemName.split("\n");
paint.setColor(textColor);
if (f != enabled && Wedge2Shown == true) {
paint.setAlpha(disabledAlpha);
} else {
paint.setAlpha(textAlpha);
}
paint.setStyle(Paint.Style.FILL);
paint.setTextSize(textSize);
Rect rect = new Rect();
float textHeight = 0;
for (int j = 0; j < stringArray.length; j++) {
paint.getTextBounds(stringArray[j], 0,
stringArray[j].length(), rect);
textHeight = textHeight + (rect.height() + 3);
}
Rect rf2 = new Rect();
rf2.set(rf.left, rf.top - ((int) textHeight / 2), rf.right,
rf.bottom - ((int) textHeight / 2));
float textBottom = rf2.bottom;
for (int j = 0; j < stringArray.length; j++) {
paint.getTextBounds(stringArray[j], 0,
stringArray[j].length(), rect);
float textLeft = rf.centerX() - rect.width() / 2;
textBottom = textBottom + (rect.height() + 3);
c.drawText(stringArray[j], textLeft - rect.left, textBottom
- rect.bottom, paint);
}
// Puts in the Icon
Drawable drawable = getResources().getDrawable(
menuEntries.get(i).getIcon());
drawable.setBounds(rf2);
if (f != enabled && Wedge2Shown == true) {
drawable.setAlpha(disabledAlpha);
} else {
drawable.setAlpha(pictureAlpha);
}
drawable.draw(c);
// Icon Only
} else if (menuEntries.get(i).getIcon() != 0) {
// Puts in the Icon
Drawable drawable = getResources().getDrawable(
menuEntries.get(i).getIcon());
drawable.setBounds(rf);
if (f != enabled && Wedge2Shown == true) {
drawable.setAlpha(disabledAlpha);
} else {
drawable.setAlpha(pictureAlpha);
}
drawable.draw(c);
// Text Only
} else {
// Puts in the Text if no Icon
paint.setColor(textColor);
if (f != enabled && Wedge2Shown == true) {
paint.setAlpha(disabledAlpha);
} else {
paint.setAlpha(textAlpha);
}
paint.setStyle(Paint.Style.FILL);
paint.setTextSize(textSize);
// This will look for a "new line" and split into multiple lines
String menuItemName = menuEntries.get(i).getLabel();
String[] stringArray = menuItemName.split("\n");
// gets total height
Rect rect = new Rect();
float textHeight = 0;
for (int j = 0; j < stringArray.length; j++) {
paint.getTextBounds(stringArray[j], 0,
stringArray[j].length(), rect);
textHeight = textHeight + (rect.height() + 3);
}
float textBottom = rf.centerY() - (textHeight / 2);
for (int j = 0; j < stringArray.length; j++) {
paint.getTextBounds(stringArray[j], 0,
stringArray[j].length(), rect);
float textLeft = rf.centerX() - rect.width() / 2;
textBottom = textBottom + (rect.height() + 3);
c.drawText(stringArray[j], textLeft - rect.left, textBottom
- rect.bottom, paint);
}
}
}
// Animate the outer ring in/out
if (animateOuterIn == true) {
animateOuterWedges(ANIMATE_IN);
} else if (animateOuterOut == true) {
animateOuterWedges(ANIMATE_OUT);
}
if (Wedge2Shown == true) {
for (int i = 0; i < Wedges2.length; i++) {
Wedge f = Wedges2[i];
paint.setColor(outlineColor);
paint.setAlpha(outlineAlpha);
paint.setStyle(Paint.Style.STROKE);
c.drawPath(f, paint);
if (f == selected2) {
paint.setColor(selectedColor);
paint.setAlpha(selectedAlpha);
paint.setStyle(Paint.Style.FILL);
c.drawPath(f, paint);
} else {
paint.setColor(wedge2Color);
paint.setAlpha(wedge2Alpha);
paint.setStyle(Paint.Style.FILL);
c.drawPath(f, paint);
}
Rect rf = iconRect2[i];
if ((wedge2Data.getChildren().get(i).getIcon() != 0)
&& (wedge2Data.getChildren().get(i).getLabel() != null)) {
// This will look for a "new line" and split into multiple
// lines
String menuItemName = wedge2Data.getChildren().get(i)
.getLabel();
String[] stringArray = menuItemName.split("\n");
paint.setColor(textColor);
paint.setAlpha(textAlpha);
paint.setStyle(Paint.Style.FILL);
paint.setTextSize(animateTextSize);
Rect rect = new Rect();
float textHeight = 0;
for (int j = 0; j < stringArray.length; j++) {
paint.getTextBounds(stringArray[j], 0,
stringArray[j].length(), rect);
textHeight = textHeight + (rect.height() + 3);
}
Rect rf2 = new Rect();
rf2.set(rf.left, rf.top - ((int) textHeight / 2), rf.right,
rf.bottom - ((int) textHeight / 2));
float textBottom = rf2.bottom;
for (int j = 0; j < stringArray.length; j++) {
paint.getTextBounds(stringArray[j], 0,
stringArray[j].length(), rect);
float textLeft = rf.centerX() - rect.width() / 2;
textBottom = textBottom + (rect.height() + 3);
c.drawText(stringArray[j], textLeft - rect.left,
textBottom - rect.bottom, paint);
}
// Puts in the Icon
Drawable drawable = getResources().getDrawable(
wedge2Data.getChildren().get(i).getIcon());
drawable.setBounds(rf2);
drawable.setAlpha(pictureAlpha);
drawable.draw(c);
// Icon Only
} else if (wedge2Data.getChildren().get(i).getIcon() != 0) {
// Puts in the Icon
Drawable drawable = getResources().getDrawable(
wedge2Data.getChildren().get(i).getIcon());
drawable.setBounds(rf);
drawable.setAlpha(pictureAlpha);
drawable.draw(c);
// Text Only
} else {
// Puts in the Text if no Icon
paint.setColor(textColor);
paint.setAlpha(textAlpha);
paint.setStyle(Paint.Style.FILL);
paint.setTextSize(animateTextSize);
// This will look for a "new line" and split into multiple
// lines
String menuItemName = wedge2Data.getChildren().get(i)
.getLabel();
String[] stringArray = menuItemName.split("\n");
// gets total height
Rect rect = new Rect();
float textHeight = 0;
for (int j = 0; j < stringArray.length; j++) {
paint.getTextBounds(stringArray[j], 0,
stringArray[j].length(), rect);
textHeight = textHeight + (rect.height() + 3);
}
float textBottom = rf.centerY() - (textHeight / 2);
for (int j = 0; j < stringArray.length; j++) {
paint.getTextBounds(stringArray[j], 0,
stringArray[j].length(), rect);
float textLeft = rf.centerX() - rect.width() / 2;
textBottom = textBottom + (rect.height() + 3);
c.drawText(stringArray[j], textLeft - rect.left,
textBottom - rect.bottom, paint);
}
}
}
}
// Draws the Middle Circle
paint.setColor(outlineColor);
paint.setAlpha(outlineAlpha);
paint.setStyle(Paint.Style.STROKE);
c.drawCircle(xPosition, yPosition, cRadius, paint);
if (inCircle == true) {
paint.setColor(selectedColor);
paint.setAlpha(selectedAlpha);
paint.setStyle(Paint.Style.FILL);
c.drawCircle(xPosition, yPosition, cRadius, paint);
onCloseAnimation();
} else {
paint.setColor(defaultColor);
paint.setAlpha(defaultAlpha);
paint.setStyle(Paint.Style.FILL);
c.drawCircle(xPosition, yPosition, cRadius, paint);
}
// Draw the circle picture
if ((centerCircle.getIcon() != 0) && (centerCircle.getLabel() != null)) {
// This will look for a "new line" and split into multiple lines
String menuItemName = centerCircle.getLabel();
String[] stringArray = menuItemName.split("\n");
paint.setColor(textColor);
paint.setAlpha(textAlpha);
paint.setStyle(Paint.Style.FILL);
paint.setTextSize(textSize);
Rect rectText = new Rect();
Rect rectIcon = new Rect();
Drawable drawable = getResources().getDrawable(
centerCircle.getIcon());
int h = getIconSize(drawable.getIntrinsicHeight(), MinIconSize,
MaxIconSize);
int w = getIconSize(drawable.getIntrinsicWidth(), MinIconSize,
MaxIconSize);
rectIcon.set(xPosition - w / 2, yPosition - h / 2, xPosition + w
/ 2, yPosition + h / 2);
float textHeight = 0;
for (int j = 0; j < stringArray.length; j++) {
paint.getTextBounds(stringArray[j], 0, stringArray[j].length(),
rectText);
textHeight = textHeight + (rectText.height() + 3);
}
rectIcon.set(rectIcon.left, rectIcon.top - ((int) textHeight / 2),
rectIcon.right, rectIcon.bottom - ((int) textHeight / 2));
float textBottom = rectIcon.bottom;
for (int j = 0; j < stringArray.length; j++) {
paint.getTextBounds(stringArray[j], 0, stringArray[j].length(),
rectText);
float textLeft = xPosition - rectText.width() / 2;
textBottom = textBottom + (rectText.height() + 3);
c.drawText(stringArray[j], textLeft - rectText.left, textBottom
- rectText.bottom, paint);
}
// Puts in the Icon
drawable.setBounds(rectIcon);
drawable.setAlpha(pictureAlpha);
drawable.draw(c);
// Icon Only
} else if (centerCircle.getIcon() != 0) {
Rect rect = new Rect();
Drawable drawable = getResources().getDrawable(
centerCircle.getIcon());
int h = getIconSize(drawable.getIntrinsicHeight(), MinIconSize,
MaxIconSize);
int w = getIconSize(drawable.getIntrinsicWidth(), MinIconSize,
MaxIconSize);
rect.set(xPosition - w / 2, yPosition - h / 2, xPosition + w / 2,
yPosition + h / 2);
drawable.setBounds(rect);
drawable.setAlpha(pictureAlpha);
drawable.draw(c);
// Text Only
} else {
// Puts in the Text if no Icon
paint.setColor(textColor);
paint.setAlpha(textAlpha);
paint.setStyle(Paint.Style.FILL);
paint.setTextSize(textSize);
// This will look for a "new line" and split into multiple lines
String menuItemName = centerCircle.getLabel();
String[] stringArray = menuItemName.split("\n");
// gets total height
Rect rect = new Rect();
float textHeight = 0;
for (int j = 0; j < stringArray.length; j++) {
paint.getTextBounds(stringArray[j], 0, stringArray[j].length(),
rect);
textHeight = textHeight + (rect.height() + 3);
}
float textBottom = yPosition - (textHeight / 2);
for (int j = 0; j < stringArray.length; j++) {
paint.getTextBounds(stringArray[j], 0, stringArray[j].length(),
rect);
float textLeft = xPosition - rect.width() / 2;
textBottom = textBottom + (rect.height() + 3);
c.drawText(stringArray[j], textLeft - rect.left, textBottom
- rect.bottom, paint);
}
}
// Draws Text in TextBox
if (headerString != null) {
paint.setTextSize(headerTextSize);
paint.getTextBounds(headerString, 0, headerString.length(),
this.textRect);
if (HeaderBoxBounded == false) {
determineHeaderBox();
HeaderBoxBounded = true;
}
paint.setColor(outlineColor);
paint.setAlpha(outlineAlpha);
paint.setStyle(Paint.Style.STROKE);
c.drawRoundRect(this.textBoxRect, scalePX(5), scalePX(5), paint);
paint.setColor(headerBackgroundColor);
paint.setAlpha(headerBackgroundAlpha);
paint.setStyle(Paint.Style.FILL);
c.drawRoundRect(this.textBoxRect, scalePX(5), scalePX(5), paint);
paint.setColor(headerTextColor);
paint.setAlpha(headerTextAlpha);
paint.setStyle(Paint.Style.FILL);
paint.setTextSize(headerTextSize);
c.drawText(headerString, headerTextLeft, headerTextBottom, paint);
}
}
private int getIconSize(int iconSize, int minSize, int maxSize) {
if (iconSize > minSize) {
if (iconSize > maxSize) {
return maxSize;
} else { // iconSize < maxSize
return iconSize;
}
} else { // iconSize < minSize
return minSize;
}
}
private void onOpenAnimation() {
new RotateAnimation(0, 360, xPosition, yPosition);
// rotate.setRepeatMode(Animation.REVERSE);
// rotate.setRepeatCount(Animation.INFINITE);
scale = new ScaleAnimation(0, 1, 0, 1, xPosition, yPosition);
// scale.setRepeatMode(Animation.REVERSE);
// scale.setRepeatCount(Animation.INFINITE);
scale.setInterpolator(new DecelerateInterpolator());
move = new TranslateAnimation(xSource - xPosition, 0, ySource
- yPosition, 0);
spriteAnimation = new AnimationSet(true);
// spriteAnimation.addAnimation(rotate);
spriteAnimation.addAnimation(scale);
spriteAnimation.addAnimation(move);
spriteAnimation.setDuration(animationSpeed);
startAnimation(spriteAnimation);
}
private void onCloseAnimation() {
new RotateAnimation(360, 0, xPosition, yPosition);
scale = new ScaleAnimation(1, 0, 1, 0, xPosition, yPosition);
scale.setInterpolator(new AccelerateInterpolator());
move = new TranslateAnimation(0, xSource - xPosition, 0, ySource
- yPosition);
spriteAnimation = new AnimationSet(true);
// spriteAnimation.addAnimation(rotate);
spriteAnimation.addAnimation(scale);
spriteAnimation.addAnimation(move);
spriteAnimation.setDuration(animationSpeed);
startAnimation(spriteAnimation);
}
private boolean pntInCircle(double px, double py, double x1, double y1,
double radius) {
double diffX = x1 - px;
double diffY = y1 - py;
double dist = diffX * diffX + diffY * diffY;
if (dist < radius * radius) {
return true;
} else {
return false;
}
}
private boolean pntInWedge(double px, double py, float xRadiusCenter,
float yRadiusCenter, int innerRadius, int outerRadius,
double startAngle, double sweepAngle) {
double diffX = px - xRadiusCenter;
double diffY = py - yRadiusCenter;
double angle = Math.atan2(diffY, diffX);
if (angle < 0)
angle += (2 * Math.PI);
if (startAngle >= (2 * Math.PI)) {
startAngle = startAngle - (2 * Math.PI);
}
// checks if point falls between the start and end of the wedge
if ((angle >= startAngle && angle <= startAngle + sweepAngle)
|| (angle + (2 * Math.PI) >= startAngle && (angle + (2 * Math.PI)) <= startAngle
+ sweepAngle)) {
// checks if point falls inside the radius of the wedge
double dist = diffX * diffX + diffY * diffY;
if (dist < outerRadius * outerRadius
&& dist > innerRadius * innerRadius) {
return true;
}
}
return false;
}
public boolean addMenuEntry(RadialMenuEntry entry) {
menuEntries.add(entry);
determineWedges();
return true;
}
public boolean setCenterCircle(RadialMenuEntry entry) {
centerCircle = entry;
return true;
}
public void setInnerRingRadius(int InnerRadius, int OuterRadius) {
this.MinSize = scalePX(InnerRadius);
this.MaxSize = scalePX(OuterRadius);
determineWedges();
}
public void setOuterRingRadius(int InnerRadius, int OuterRadius) {
this.r2MinSize = scalePX(InnerRadius);
this.r2MaxSize = scalePX(OuterRadius);
determineWedges();
}
public void setCenterCircleRadius(int centerRadius) {
this.cRadius = scalePX(centerRadius);
determineWedges();
}
public void setTextSize(int TextSize) {
this.textSize = scalePX(TextSize);
this.animateTextSize = this.textSize;
}
public void setIconSize(int minIconSize, int maxIconSize) {
this.MinIconSize = scalePX(minIconSize);
this.MaxIconSize = scalePX(maxIconSize);
determineWedges();
}
public void setCenterLocation(int x, int y) {
this.xPosition = x;
this.yPosition = y;
determineWedges();
onOpenAnimation();
}
public void setSourceLocation(int x, int y) {
this.xSource = x;
this.ySource = y;
onOpenAnimation();
}
public void setShowSourceLocation(boolean showSourceLocation) {
this.showSource = showSourceLocation;
onOpenAnimation();
}
public void setAnimationSpeed(long millis) {
this.animationSpeed = millis;
onOpenAnimation();
}
public void setInnerRingColor(int color, int alpha) {
this.defaultColor = color;
this.defaultAlpha = alpha;
}
public void setOuterRingColor(int color, int alpha) {
this.wedge2Color = color;
this.wedge2Alpha = alpha;
}
public void setOutlineColor(int color, int alpha) {
this.outlineColor = color;
this.outlineAlpha = alpha;
}
public void setSelectedColor(int color, int alpha) {
this.selectedColor = color;
this.selectedAlpha = alpha;
}
public void setDisabledColor(int color, int alpha) {
this.disabledColor = color;
this.disabledAlpha = alpha;
}
public void setTextColor(int color, int alpha) {
this.textColor = color;
this.textAlpha = alpha;
}
public void setHeader(String header, int TextSize) {
this.headerString = header;
this.headerTextSize = scalePX(TextSize);
HeaderBoxBounded = false;
// 这里需要刷新
invalidate();
}
public void setHeaderColors(int TextColor, int TextAlpha, int BgColor,
int BgAlpha) {
this.headerTextColor = TextColor;
this.headerTextAlpha = TextAlpha;
this.headerBackgroundColor = BgColor;
this.headerBackgroundAlpha = BgAlpha;
}
private int scalePX(int dp_size) {
int px_size = (int) (dp_size * screen_density + 0.5f);
return px_size;
}
private void animateOuterWedges(int animation_direction) {
boolean animationComplete = false;
// Wedge 2
float slice2 = 360 / wedgeQty2;
float start_slice2 = 270 - (slice2 / 2);
// calculates where to put the images
double rSlice2 = (2 * Math.PI) / wedgeQty2;
double rStart2 = (2 * Math.PI) * (0.75) - (rSlice2 / 2);
this.Wedges2 = new Wedge[wedgeQty2];
this.iconRect2 = new Rect[wedgeQty2];
Wedge2Shown = true;
int wedgeSizeChange = (r2MaxSize - r2MinSize) / animateSections;
if (animation_direction == ANIMATE_OUT) {
if (r2MinSize + r2VariableSize + wedgeSizeChange < r2MaxSize) {
r2VariableSize += wedgeSizeChange;
} else {
animateOuterOut = false;
r2VariableSize = r2MaxSize - r2MinSize;
animationComplete = true;
}
// animates text size change
this.animateTextSize = (textSize / animateSections)
* (r2VariableSize / wedgeSizeChange);
// calculates new wedge sizes
for (int i = 0; i < Wedges2.length; i++) {
this.Wedges2[i] = new Wedge(xPosition, yPosition, r2MinSize,
r2MinSize + r2VariableSize,
(i * slice2) + start_slice2, slice2);
float xCenter = (float) (Math
.cos(((rSlice2 * i) + (rSlice2 * 0.5)) + rStart2)
* (r2MinSize + r2VariableSize + r2MinSize) / 2)
+ xPosition;
float yCenter = (float) (Math
.sin(((rSlice2 * i) + (rSlice2 * 0.5)) + rStart2)
* (r2MinSize + r2VariableSize + r2MinSize) / 2)
+ yPosition;
int h = MaxIconSize;
int w = MaxIconSize;
if (wedge2Data.getChildren().get(i).getIcon() != 0) {
Drawable drawable = getResources().getDrawable(
wedge2Data.getChildren().get(i).getIcon());
h = getIconSize(drawable.getIntrinsicHeight(), MinIconSize,
MaxIconSize);
w = getIconSize(drawable.getIntrinsicWidth(), MinIconSize,
MaxIconSize);
}
if (r2VariableSize < h) {
h = r2VariableSize;
}
if (r2VariableSize < w) {
w = r2VariableSize;
}
this.iconRect2[i] = new Rect((int) xCenter - w / 2,
(int) yCenter - h / 2, (int) xCenter + w / 2,
(int) yCenter + h / 2);
int widthOffset = MaxSize;
if (widthOffset < this.textRect.width() / 2) {
widthOffset = this.textRect.width() / 2 + scalePX(3);
}
this.textBoxRect
.set((xPosition - (widthOffset)), (int) (yPosition
- (r2MinSize + r2VariableSize) - headerBuffer
- this.textRect.height() - scalePX(3)),
(xPosition + (widthOffset)), (yPosition
- (r2MinSize + r2VariableSize)
- headerBuffer + scalePX(3)));
this.headerTextBottom = yPosition
- (r2MinSize + r2VariableSize) - headerBuffer
- this.textRect.bottom;
}
} else if (animation_direction == ANIMATE_IN) {
if (r2MinSize < r2MaxSize - r2VariableSize - wedgeSizeChange) {
r2VariableSize += wedgeSizeChange;
} else {
animateOuterIn = false;
r2VariableSize = r2MaxSize;
animationComplete = true;
}
// animates text size change
this.animateTextSize = textSize
- ((textSize / animateSections) * (r2VariableSize / wedgeSizeChange));
for (int i = 0; i < Wedges2.length; i++) {
this.Wedges2[i] = new Wedge(xPosition, yPosition, r2MinSize,
r2MaxSize - r2VariableSize,
(i * slice2) + start_slice2, slice2);
float xCenter = (float) (Math
.cos(((rSlice2 * i) + (rSlice2 * 0.5)) + rStart2)
* (r2MaxSize - r2VariableSize + r2MinSize) / 2)
+ xPosition;
float yCenter = (float) (Math
.sin(((rSlice2 * i) + (rSlice2 * 0.5)) + rStart2)
* (r2MaxSize - r2VariableSize + r2MinSize) / 2)
+ yPosition;
int h = MaxIconSize;
int w = MaxIconSize;
if (wedge2Data.getChildren().get(i).getIcon() != 0) {
Drawable drawable = getResources().getDrawable(
wedge2Data.getChildren().get(i).getIcon());
h = getIconSize(drawable.getIntrinsicHeight(), MinIconSize,
MaxIconSize);
w = getIconSize(drawable.getIntrinsicWidth(), MinIconSize,
MaxIconSize);
}
if (r2MaxSize - r2MinSize - r2VariableSize < h) {
h = r2MaxSize - r2MinSize - r2VariableSize;
}
if (r2MaxSize - r2MinSize - r2VariableSize < w) {
w = r2MaxSize - r2MinSize - r2VariableSize;
}
this.iconRect2[i] = new Rect((int) xCenter - w / 2,
(int) yCenter - h / 2, (int) xCenter + w / 2,
(int) yCenter + h / 2);
// computes header text box
int heightOffset = r2MaxSize - r2VariableSize;
int widthOffset = MaxSize;
if (MaxSize > r2MaxSize - r2VariableSize) {
heightOffset = MaxSize;
}
if (widthOffset < this.textRect.width() / 2) {
widthOffset = this.textRect.width() / 2 + scalePX(3);
}
this.textBoxRect.set((xPosition - (widthOffset)),
(int) (yPosition - (heightOffset) - headerBuffer
- this.textRect.height() - scalePX(3)),
(xPosition + (widthOffset)), (yPosition
- (heightOffset) - headerBuffer + scalePX(3)));
this.headerTextBottom = yPosition - (heightOffset)
- headerBuffer - this.textRect.bottom;
}
}
if (animationComplete == true) {
r2VariableSize = 0;
this.animateTextSize = textSize;
if (animation_direction == ANIMATE_IN) {
Wedge2Shown = false;
}
}
invalidate(); // re-draws the picture
}
private void determineWedges() {
int entriesQty = menuEntries.size();
if (entriesQty > 0) {
wedgeQty = entriesQty;
float degSlice = 360 / wedgeQty;
float start_degSlice = 270 - (degSlice / 2);
// calculates where to put the images
double rSlice = (2 * Math.PI) / wedgeQty;
double rStart = (2 * Math.PI) * (0.75) - (rSlice / 2);
this.Wedges = new Wedge[wedgeQty];
this.iconRect = new Rect[wedgeQty];
for (int i = 0; i < Wedges.length; i++) {
this.Wedges[i] = new Wedge(xPosition, yPosition, MinSize,
MaxSize, (i * degSlice) + start_degSlice, degSlice);
float xCenter = (float) (Math
.cos(((rSlice * i) + (rSlice * 0.5)) + rStart)
* (MaxSize + MinSize) / 2) + xPosition;
float yCenter = (float) (Math
.sin(((rSlice * i) + (rSlice * 0.5)) + rStart)
* (MaxSize + MinSize) / 2) + yPosition;
int h = MaxIconSize;
int w = MaxIconSize;
if (menuEntries.get(i).getIcon() != 0) {
Drawable drawable = getResources().getDrawable(
menuEntries.get(i).getIcon());
h = getIconSize(drawable.getIntrinsicHeight(), MinIconSize,
MaxIconSize);
w = getIconSize(drawable.getIntrinsicWidth(), MinIconSize,
MaxIconSize);
}
this.iconRect[i] = new Rect((int) xCenter - w / 2,
(int) yCenter - h / 2, (int) xCenter + w / 2,
(int) yCenter + h / 2);
}
invalidate(); // re-draws the picture
}
}
private void determineOuterWedges(RadialMenuEntry entry) {
int entriesQty = entry.getChildren().size();
wedgeQty2 = entriesQty;
// Wedge 2
float degSlice2 = 360 / wedgeQty2;
float start_degSlice2 = 270 - (degSlice2 / 2);
// calculates where to put the images
double rSlice2 = (2 * Math.PI) / wedgeQty2;
double rStart2 = (2 * Math.PI) * (0.75) - (rSlice2 / 2);
this.Wedges2 = new Wedge[wedgeQty2];
this.iconRect2 = new Rect[wedgeQty2];
for (int i = 0; i < Wedges2.length; i++) {
this.Wedges2[i] = new Wedge(xPosition, yPosition, r2MinSize,
r2MaxSize, (i * degSlice2) + start_degSlice2, degSlice2);
float xCenter = (float) (Math.cos(((rSlice2 * i) + (rSlice2 * 0.5))
+ rStart2)
* (r2MaxSize + r2MinSize) / 2)
+ xPosition;
float yCenter = (float) (Math.sin(((rSlice2 * i) + (rSlice2 * 0.5))
+ rStart2)
* (r2MaxSize + r2MinSize) / 2)
+ yPosition;
int h = MaxIconSize;
int w = MaxIconSize;
if (entry.getChildren().get(i).getIcon() != 0) {
Drawable drawable = getResources().getDrawable(
entry.getChildren().get(i).getIcon());
h = getIconSize(drawable.getIntrinsicHeight(), MinIconSize,
MaxIconSize);
w = getIconSize(drawable.getIntrinsicWidth(), MinIconSize,
MaxIconSize);
}
this.iconRect2[i] = new Rect((int) xCenter - w / 2, (int) yCenter
- h / 2, (int) xCenter + w / 2, (int) yCenter + h / 2);
}
this.wedge2Data = entry;
invalidate(); // re-draws the picture
}
private void determineHeaderBox() {
this.headerTextLeft = xPosition - this.textRect.width() / 2;
this.headerTextBottom = yPosition - (MaxSize) - headerBuffer
- this.textRect.bottom;
int offset = MaxSize;
if (offset < this.textRect.width() / 2) {
offset = this.textRect.width() / 2 + scalePX(3);
}
this.textBoxRect.set(
(xPosition - (offset)),
(int) (yPosition - (MaxSize) - headerBuffer
- this.textRect.height() - scalePX(3)),
(xPosition + (offset)),
(yPosition - (MaxSize) - headerBuffer + scalePX(3)));
}
public class Wedge extends Path {
private int x, y;
private int InnerSize, OuterSize;
private float StartArc;
private float ArcWidth;
private Wedge(int x, int y, int InnerSize, int OuterSize,
float StartArc, float ArcWidth) {
super();
if (StartArc >= 360) {
StartArc = StartArc - 360;
}
this.x = x;
this.y = y;
this.InnerSize = InnerSize;
this.OuterSize = OuterSize;
this.StartArc = StartArc;
this.ArcWidth = ArcWidth;
this.buildPath();
}
private void buildPath() {
final RectF rect = new RectF();
final RectF rect2 = new RectF();
// Rectangles values
rect.set(this.x - this.InnerSize, this.y - this.InnerSize, this.x
+ this.InnerSize, this.y + this.InnerSize);
rect2.set(this.x - this.OuterSize, this.y - this.OuterSize, this.x
+ this.OuterSize, this.y + this.OuterSize);
this.reset();
// this.moveTo(100, 100);
this.arcTo(rect2, StartArc, ArcWidth);
this.arcTo(rect, StartArc + ArcWidth, -ArcWidth);
this.close();
}
}
}
| 282857484/LocationBaseServiceSocialNetworking | src/pri/h/uitool/RadialMenuWidget.java | Java | gpl-2.0 | 37,806 |
//public class Balle extends Projectil {
public class Balle extends Projectil2 {
public static int nbBalle=0;
private String toPrint;
public Balle(float x, float y, float a, boolean toTheRight, boolean leftPlayer ){
super(x,y,a,toTheRight,leftPlayer);
this.toPrint="\033[31mO\033[0m";
nbBalle ++;
}
public String getCaractere(){
return this.toPrint;
}
}
| Cyriled/Pong | Balle.java | Java | gpl-2.0 | 377 |
/*
* Copyright (C) 2007-2014 Geometer Plus <[email protected]>
*
* 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 org.geometerplus.zlibrary.text.view;
public class ZLTextFixedPosition extends ZLTextPosition {
public final int ParagraphIndex;
public final int ElementIndex;
public final int CharIndex;
public ZLTextFixedPosition(int paragraphIndex, int elementIndex, int charIndex) {
ParagraphIndex = paragraphIndex;
ElementIndex = elementIndex;
CharIndex = charIndex;
}
public ZLTextFixedPosition(ZLTextPosition position) {
ParagraphIndex = position.getParagraphIndex();
ElementIndex = position.getElementIndex();
CharIndex = position.getCharIndex();
}
public final int getParagraphIndex() {
return ParagraphIndex;
}
public final int getElementIndex() {
return ElementIndex;
}
public final int getCharIndex() {
return CharIndex;
}
public static class WithTimestamp extends ZLTextFixedPosition {
public final long Timestamp;
public WithTimestamp(int paragraphIndex, int elementIndex, int charIndex, Long stamp) {
super(paragraphIndex, elementIndex, charIndex);
Timestamp = stamp != null ? stamp : -1;
}
@Override
public String toString() {
return super.toString() + "; timestamp = " + Timestamp;
}
}
}
| xiaosea/easyreader | src/main/java/org/geometerplus/zlibrary/text/view/ZLTextFixedPosition.java | Java | gpl-2.0 | 1,958 |
import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.MenuItem;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.StringTokenizer;
import javax.swing.*;
import javax.swing.event.AncestorEvent;
import javax.swing.event.AncestorListener;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.plaf.synth.SynthOptionPaneUI;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
import org.omg.CORBA.IdentifierHelper;
public class seat712 extends JFrame implements ActionListener{
static ImageIcon icon;
static List<HashMap<String,String>> Data;
static List<JButton> BArr;
static List<JTextField> TArr1,TArr2;
static List<JPanel> PArr;
static String WeekDate[] = new String[18];
static Boolean hasData[] = new Boolean[18];
static char Seat[] = {'A','B','C','D','E','F','G'};
static Boolean Direction = true;
static String FileType = "null";//file,seat,new,null
static int ThisWeek = 0,NowWeek = 0;
static JMenuBar JMB = new JMenuBar();
static JMenu JM_file,JM_edit,JM_seat,JM_score,JM_week,JM_other;
static JLabel YEAR = new JLabel("OOO¾Ç¦~«×_²ÄO¾Ç´Á");
static JLabel TEACHER = new JLabel("XXX¦Ñ®v");
static JLabel WEEKDATE = new JLabel("00/00");
static JLabel CLASSNAME = new JLabel("½Òµ{¦WºÙ");
static JLabel WEEK = new JLabel("¥Ø«eÀ˵ø:00¶g ¥»¶g:00¶g");
static JLabel CLOCK = new JLabel();
static JTextArea STATUS = new JTextArea("Åwªï¨Ï¥Î712½Ò°ó»²§U¨t²Î,½Ð·s¼W©Î¶×¤J®y¦ìªí¥HÄ~Äò");
static JButton EDIT = new JButton("½s¿è§¹¦¨");
public static void main(String[] args) {
new seat712();
}
private seat712(){
setSize(900,685);
setLocationRelativeTo(this);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(null);
setResizable(false);
setTitle("¯u²z¤j¾Ç¸ê°T¤uµ{¾Ç¨t_712±Ð«Ç_½Ò°ó»²§U¨t²Î");
icon = new ImageIcon(this.getClass().getResource("/icon.png"));
setIconImage(icon.getImage());
YEAR.setBounds(10, 5, 135, 20);
add(YEAR);
TEACHER.setBounds(10, 25, 135, 20);
add(TEACHER);
CLASSNAME.setFont(new Font(null, Font.BOLD, 35));
CLASSNAME.setBounds(310, 5, 400, 40);
add(CLASSNAME);
WEEKDATE.setFont(new Font(null, Font.BOLD, 35));
WEEKDATE.setBounds(180, 5, 135, 40);
add(WEEKDATE);
WEEK.setBounds(705, 5, 180, 20);
WEEK.setFont(new Font(null, Font.BOLD, 14));
add(WEEK);
CLOCK.setBounds(705, 25, 180, 20);
CLOCK.setFont(new Font(null, Font.BOLD, 14));
CLOCK.setBackground(new Color(170,220,255));
CLOCK.setOpaque(true);
add(CLOCK);
new Thread(new Clock(CLOCK)).start();
STATUS.setFont(new Font(null, 0, 13));
STATUS.setEditable(false);
STATUS.setBackground(new Color(200,255,255));
JScrollPane JSP = new JScrollPane(STATUS);
JSP.setBounds(10, 607, 875, 25);
JSP.setAutoscrolls(true);
add(JSP);
EDIT.setBounds(150, 555, 135, 20);
EDIT.setVisible(false);
EDIT.setBackground(Color.CYAN);
EDIT.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JM_seat.getItem(1).setEnabled(true);
EDIT.setVisible(false);
DoneEdit();
}
});
add(EDIT);
GridLayout GL = new GridLayout(3,1);
GL.setVgap(5);
BArr = new ArrayList<JButton>();
TArr1 = new ArrayList<JTextField>();
TArr2 = new ArrayList<JTextField>();
PArr = new ArrayList<JPanel>();
for(int i=0;i<7;i++){
for(int j=0;j<12;j++){
JPanel JP = new JPanel();
JP.setLayout(GL);
JP.setBounds(j<4?(j*70)+10:j<8?(j*70)+30:(j*70)+50,(i*80)+50, 65, 75);
JButton JB = new JButton((String.valueOf(Seat[i])+(j+1)));
JTextField JT1 = new JTextField();
JTextField JT2 = new JTextField();
JB.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JButton B = (JButton)e.getSource();
if(B.getBackground() == Color.RED){
B.setForeground(Color.BLACK);
B.setBackground(Color.GREEN);
}else if(B.getBackground() == Color.BLUE){
B.setForeground(Color.WHITE);
B.setBackground(Color.RED);
}else if(B.getBackground() == Color.GREEN){
B.setForeground(Color.WHITE);
B.setBackground(Color.BLUE);
}
}
});
JB.setEnabled(false);
JT1.setHorizontalAlignment(JTextField.CENTER);
JT1.setEnabled(false);
JT1.setEditable(false);
JT2.setHorizontalAlignment(JTextField.CENTER);
JT2.setEnabled(false);
JT2.setEditable(false);
JP.add(JB);JP.add(JT1);JP.add(JT2);
BArr.add(JB);TArr1.add(JT1);TArr2.add(JT2);PArr.add(JP);
if(i==6 && j<4)
JP.setVisible(false);
add(JP);
}
}
JM_file = new JMenu("ÀÉ®×");
JM_file.add(new JMenuItem("Ū¨ú½Ò°ó¸ê®Æ")).addActionListener(this);
JM_file.add(new JMenuItem("Àx¦s½Ò°ó¸ê®Æ")).addActionListener(this);
JM_file.getItem(1).setEnabled(false);
JM_file.add(new JMenuItem("Â÷¶}")).addActionListener(this);
JM_edit = new JMenu("½s¿è");
JM_edit.add(new JMenuItem("¥»¶gµL½Òµ{¸ê®Æ")).addActionListener(this);
JM_edit.add(new JMenuItem("½s¿è¹L©¹¸ê®Æ")).addActionListener(this);
JM_edit.add(new JMenuItem("§ó§ï¥»¶g¤W½Ò¤é´Á")).addActionListener(this);
JM_edit.setEnabled(false);
JM_seat = new JMenu("®y¦ìªí");
JM_seat.add(new JMenuItem("·s¼W")).addActionListener(this);
JM_seat.add(new JMenuItem("×§ï")).addActionListener(this);
JM_seat.getItem(1).setEnabled(false);
JM_seat.add(new JMenuItem("¶×¤J")).addActionListener(this);
JM_seat.add(new JMenuItem("¶×¥X(¤£¥]§t½Òµ{¸ê®Æ)")).addActionListener(this);
JM_seat.getItem(3).setEnabled(false);
JM_score = new JMenu("½Ò°ó¤À¼Æ");
JM_score.add(new JMenuItem("½s¿è¥»¶g¦¨ÁZ")).addActionListener(this);
JM_score.setEnabled(false);
JM_week = new JMenu("¶g¦¸(0)");
ButtonGroup BG = new ButtonGroup();
JRadioButtonMenuItem JRB = null;
for(int i=0;i<19;i++){
JRB = new JRadioButtonMenuItem((i>0?"²Ä"+i+"¶g":"Á`Äý"));
JRB.addActionListener(this);
JRB.setName(String.valueOf(i));
BG.add(JRB);
JM_week.add(JRB);
}
JM_week.setEnabled(false);
JM_other = new JMenu("¨ä¥L");
JM_other.add(new JMenuItem("®y¦ì¤ÏÂà")).addActionListener(this);
JM_other.add(new JMenuItem("»¡©ú")).addActionListener(this);
JM_other.add(new JMenuItem("Ãö©ó")).addActionListener(this);
JMB.add(JM_file);
JMB.add(JM_edit);
JMB.add(JM_seat);
JMB.add(JM_score);
JMB.add(JM_week);
JMB.add(JM_other);
setJMenuBar(JMB);
setVisible(true);
JLabel JL = new JLabel(icon);
JTextArea JTA = new JTextArea("\n\n¦Ñ®v±z¦n\nÅwªï¨Ï¥Î712½Ò°ó»²§U¨t²Î\n"
+ "º¦¸¨Ï¥Î½Ð·s¼W©Î¶×¤J®y¦ìªí\n¨ä¥L¸Ô²Ó»¡©ú½ÐÂI¿ï -¨ä¥L-");
JTA.setEditable(false);
JTA.setBackground(new Color(240,240,240));
JPanel JP = new JPanel();
JP.setLayout(new GridLayout(1,2));
JP.add(JL);JP.add(JTA);
JOptionPane.showMessageDialog(this,JP,"Welcome",JOptionPane.PLAIN_MESSAGE);
}
private void ChangeDirection(){
if(!Direction){
for(int i=0;i<BArr.size();i++){
JButton JB = BArr.get(i);
JTextField JT1 = TArr1.get(i);
JTextField JT2 = TArr2.get(i);
JPanel JP = PArr.get(i);
JP.removeAll();
JP.setVisible(true);
JP.add(JB);JP.add(JT1);JP.add(JT2);
if(JB.getText().equals("G1") || JB.getText().equals("G2")
|| JB.getText().equals("G3") || JB.getText().equals("G4")){
JP.setVisible(false);
}
}
EDIT.setLocation(150, 555);
Direction = true;
}else{
for(int i=0;i<BArr.size();i++){
JButton JB = BArr.get(i);
JTextField JT1 = TArr1.get(i);
JTextField JT2 = TArr2.get(i);
JPanel JP = PArr.get(BArr.size()-1-i);
JP.removeAll();
JP.setVisible(true);
JP.add(JB);JP.add(JT1);JP.add(JT2);
if(JB.getText().equals("G1") || JB.getText().equals("G2")
|| JB.getText().equals("G3") || JB.getText().equals("G4")){
JP.setVisible(false);
}
}
EDIT.setLocation(610, 75);
Direction = false;
}
SetStatus(0,"Åܧó®y¦ì¤è¦V,¥Ø«e¬°"+(Direction?"¾Ç¥Í¨¤«×À˵ø":"±Ð®v¨¤«×À˵ø"));
}
private void UpdateInfo(String y,String t,String c) {
YEAR.setText(y);
TEACHER.setText(t);
CLASSNAME.setText(c);
}
private void UpdateAttend(){
for(HashMap<String,String> HM:Data){
for(JButton JB:BArr){
if(HM.get("seat").equals(JB.getText())){
if(JB.getBackground().equals(Color.GREEN)){
HM.put(NowWeek+"-attend","¥X®u");
}else if(JB.getBackground().equals(Color.BLUE)){
HM.put(NowWeek+"-attend","¿ð¨ì");
}else if(JB.getBackground().equals(Color.RED)){
HM.put(NowWeek+"-attend","Ãm½Ò");
}
}
}
}
}
private void UpdateSeat(){
WEEK.setText("¥Ø«eÀ˵ø:"+NowWeek+"¶g ¥»¶g:"+ThisWeek+"¶g");
JM_week.setText("¶g¦¸("+NowWeek+")");
JM_week.getItem(NowWeek).setSelected(true);
for(int i=0;i<19;i++){
if(i==0){
JM_week.getItem(i).setEnabled(true);
}else if(i<=ThisWeek && hasData[i-1]){
JM_week.getItem(i).setEnabled(true);
}else{
JM_week.getItem(i).setEnabled(false);
}
}
if(ThisWeek==1){
JM_edit.getItem(1).setEnabled(false);
}else{
JM_edit.getItem(1).setEnabled(true);
}
if(NowWeek == ThisWeek){
JM_edit.getItem(0).setEnabled(true);
JM_edit.getItem(2).setEnabled(true);
JM_seat.getItem(1).setEnabled(true);
JM_score.setEnabled(true);
}else{
JM_edit.getItem(0).setEnabled(false);
JM_edit.getItem(2).setEnabled(false);
JM_seat.getItem(1).setEnabled(false);
JM_score.setEnabled(false);
}
for(HashMap<String,String> HM:Data){
int index = 0;
for(JButton JB:BArr){
if(JB.getText().equals(HM.get("seat"))){
index = BArr.indexOf(JB);
break;
}
}
TArr1.get(index).setText(HM.get("id"));
TArr2.get(index).setText(HM.get("name"));
if(HM.get("id").length()==8){
if(HM.get(NowWeek+"-attend").equals("¥X®u")){
BArr.get(index).setBackground(Color.GREEN);
BArr.get(index).setForeground(Color.BLACK);
}else if(HM.get(NowWeek+"-attend").equals("¿ð¨ì")){
BArr.get(index).setBackground(Color.BLUE);
BArr.get(index).setForeground(Color.WHITE);
}else if(HM.get(NowWeek+"-attend").equals("Ãm½Ò")){
BArr.get(index).setBackground(Color.RED);
BArr.get(index).setForeground(Color.WHITE);
}
BArr.get(index).setEnabled(NowWeek == ThisWeek?true:false);
TArr1.get(index).setEnabled(true);
TArr2.get(index).setEnabled(true);
}else{
BArr.get(index).setBackground(Color.LIGHT_GRAY);
BArr.get(index).setForeground(Color.BLACK);
BArr.get(index).setEnabled(false);
TArr1.get(index).setEnabled(false);
TArr2.get(index).setEnabled(false);
}
}
WEEKDATE.setText(WeekDate[NowWeek-1]);
SetStatus(0, "¥Ø«eÅã¥Üªº¬O ²Ä"+NowWeek+"¶g ÂI¦W¬ö¿ý");
}
//after NewSeat or ReadSeat
private void InitialData(){
Data = new ArrayList<HashMap<String,String>>();
for(int i=0;i<7*12;i++){
HashMap<String,String> HM = new HashMap<String,String>();
HM.put("seat", BArr.get(i).getText());
HM.put("id", TArr1.get(i).getText());
HM.put("name", TArr2.get(i).getText());
for(int j=1;j<19;j++){
HM.put(j+"-attend","-");
HM.put(j+"-score","-");
}
Data.add(HM);
}
for(int i=0;i<18;i++)
hasData[i] = false;
JM_file.getItem(0).setEnabled(false);
JM_file.getItem(1).setEnabled(true);
JM_seat.getItem(0).setEnabled(false);
JM_seat.getItem(2).setEnabled(false);
JM_seat.getItem(3).setEnabled(true);
}
private void NewSeat(){
JTextField t[] = new JTextField[8];
t[0] = new JTextField("¾Ç¦~«×:(ex:102)");
t[0].setEditable(false);
t[1] = new JTextField();
t[2] = new JTextField("¾Ç´Á:(¤W or ¤U)");
t[2].setEditable(false);
t[3] = new JTextField();
t[4] = new JTextField("±Ð®v:");
t[4].setEditable(false);
t[5] = new JTextField();
t[6] = new JTextField("½Òµ{¦WºÙ:(³Ì¦h10¦r)");
t[6].setEditable(false);
t[7] = new JTextField();
String but[] = new String[] {"½T©w","¨ú®ø"};
do{
int result = JOptionPane.showOptionDialog(null, t, "¿é¤J½Òµ{¸ê°T",
JOptionPane.YES_NO_OPTION,
JOptionPane.INFORMATION_MESSAGE, null, but, but[0]);
t[1].setBackground(Color.WHITE);
t[3].setBackground(Color.WHITE);
t[5].setBackground(Color.WHITE);
t[7].setBackground(Color.WHITE);
if (result == 0) {
if(t[1].getText().length()==3){
if(t[3].getText().length()==1){
if(t[5].getText().length()>0){
if(t[7].getText().length()>0 && t[7].getText().length()<11){
UpdateInfo(t[1].getText()+"¾Ç¦~«×_"+t[3].getText()+"¾Ç´Á",
t[5].getText()+"¦Ñ®v",t[7].getText());
TArr1.get(0).setText("¾Ç¸¹");
TArr2.get(0).setText("©m¦W");
EDIT.setVisible(true);
FileType = "new";
ThisWeek = 1;
NowWeek = 1;
WeekDate[ThisWeek-1] = new SimpleDateFormat("MM/dd").format(new Date());
InitialData();
hasData[0] = true;
UpdateSeat();
StartEdit();
break;
}else{
t[7].setBackground(Color.YELLOW);
}
}else{
t[5].setBackground(Color.YELLOW);
}
}else{
t[3].setBackground(Color.YELLOW);
}
}else{
t[1].setBackground(Color.YELLOW);
}
}else{
SetStatus(1, "½Ð¶ñ¤J§¹¾ã½Òµ{¸ê°T¥H·s¼W®y¦ìªí!!!");
break;
}
}while(true);
}
private void StartEdit(){
for(int i=0;i<BArr.size();i++){
BArr.get(i).setEnabled(false);
BArr.get(i).setBackground(Color.LIGHT_GRAY);
TArr1.get(i).setEditable(true);
TArr1.get(i).setEnabled(true);
TArr2.get(i).setEditable(true);
TArr2.get(i).setEnabled(true);
}
JM_file.setEnabled(false);
JM_edit.setEnabled(false);
JM_seat.setEnabled(false);
JM_score.setEnabled(false);
JM_week.setEnabled(false);
EDIT.setVisible(true);
SetStatus(0, "®y¦ìªí×§ï§¹¦¨½ÐÂI¿ï-½s¿è§¹¦¨-");
}
private void DoneEdit(){
for(int i=0;i<BArr.size();i++){
TArr1.get(i).setEditable(false);
TArr2.get(i).setEditable(false);
for(HashMap<String,String> HM:Data){
if(HM.get("seat").equals(BArr.get(i).getText())){
if(TArr1.get(i).getText().length()==8){
HM.put("id",TArr1.get(i).getText());
HM.put("name",TArr2.get(i).getText());
HM.put(NowWeek+"-attend","¥X®u");
}else{
HM.put("id","-");
HM.put("name","-");
HM.put(NowWeek+"-attend","-");
}
break;
}
}
}
if(FileType.equals("new")){
SaveSeat();
FileType = "seat";
}
JM_file.setEnabled(true);
JM_edit.setEnabled(true);
JM_seat.setEnabled(true);
JM_seat.getItem(1).setEnabled(true);
JM_score.setEnabled(true);
JM_week.setEnabled(true);
UpdateSeat();
SetStatus(0, "×§ï®y¦ì¦¨¥\!!!");
}
private void ReadSeat() {
JFileChooser JFC = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("csv", "csv");
JFC.setFileFilter(filter);
int returnVal = JFC.showOpenDialog(this);
if(returnVal == JFileChooser.APPROVE_OPTION){
File F = JFC.getSelectedFile();
try {
BufferedReader BR = new BufferedReader(new InputStreamReader(new FileInputStream(F)));
String info = BR.readLine();
StringTokenizer STinfo = new StringTokenizer(info,",");
if(!info.substring(3,6).equals("¾Ç¦~«×")){
JOptionPane.showConfirmDialog(this, "Àɮ׮榡¿ù»~", "ĵ§i", JOptionPane.CLOSED_OPTION
,JOptionPane.ERROR_MESSAGE);
return;
}
UpdateInfo(STinfo.nextToken(),STinfo.nextToken(),STinfo.nextToken());
InitialData();
hasData[0] = true;
String S = "";
while((S = BR.readLine())!=null){
StringTokenizer ST = new StringTokenizer(S,", -");
String seat = ST.nextToken();
for(HashMap<String,String> HM:Data){
if(HM.get("seat").equals(seat)){
HM.put("1-attend",ST.hasMoreTokens()?"¥X®u":"-");
HM.put("id",ST.hasMoreTokens()?ST.nextToken():"-");
HM.put("name",ST.hasMoreTokens()?ST.nextToken():"-");
break;
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
JM_file.getItem(0).setEnabled(false);
JM_file.getItem(1).setEnabled(true);
JM_edit.setEnabled(true);
JM_seat.getItem(0).setEnabled(false);
JM_seat.getItem(1).setEnabled(true);
JM_seat.getItem(2).setEnabled(false);
JM_seat.getItem(3).setEnabled(true);
JM_score.setEnabled(true);
JM_week.setEnabled(true);
FileType = "seat";
ThisWeek = 1;
NowWeek = ThisWeek;
WeekDate[ThisWeek-1] = new SimpleDateFormat("MM/dd").format(new Date());
hasData[ThisWeek-1] = true;
UpdateSeat();
SetStatus(0, "®y¦ìªí¶×¤J¦¨¥\,±z¥i¥H¶}©lÂI¦W,ÂIÀ»®y¦ì«ö¶s§ó§ï¥X®uª¬ªp,ÂI¦W§¹¦¨½Ð¿ï¨ú-ÀÉ®×-Àx¦s½Ò°ó¸ê®Æ-");
}
}
private void SaveSeat(){
JFileChooser JFC =new JFileChooser();
JFC.setFileSelectionMode(JFileChooser.FILES_ONLY);
JFC.setApproveButtonText("Àx¦s");
JFC.setDialogTitle("Àx¦s¸ô®|¤ÎÀɦW");
JFC.setSelectedFile(new File(YEAR.getText()+"_"+CLASSNAME.getText()+"_®y¦ìªí.csv"));
do{
int returnVal = JFC.showOpenDialog(this);
if(returnVal == JFileChooser.APPROVE_OPTION){
String Path = JFC.getSelectedFile().getAbsolutePath();
File F = new File(Path+(Path.endsWith(".csv")?"":".csv"));
String S = YEAR.getText()+","+TEACHER.getText()+","+CLASSNAME.getText()+"\r\n";
for(int i=0;i<7;i++){
for(int j=0;j<12;j++){
S += BArr.get((i*12)+j).getText()+",";
S += TArr1.get((i*12)+j).getText()+",";
S += TArr2.get((i*12)+j).getText()+"\r\n";
}
}
try {
F.createNewFile();
BufferedWriter B = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(F)));
B.write(S);B.flush();
B.close();
} catch (IOException e) {
e.printStackTrace();
}
SetStatus(0, "®y¦ìªí¶×¥X¦¨¥\,¤U¦¸ÂI¦W¥iª½±µ¶×¤J®y¦ìªí");
break;
}else if(!FileType.equals("new")){
break;
}
}while(true);
}
private void ReadFile(){
JFileChooser JFC = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("csv", "csv");
JFC.setFileFilter(filter);
int returnVal = JFC.showOpenDialog(this);
if(returnVal == JFileChooser.APPROVE_OPTION){
File F = JFC.getSelectedFile();
try {
BufferedReader BR = new BufferedReader(new InputStreamReader(new FileInputStream(F)));
String info = BR.readLine();
StringTokenizer STinfo = new StringTokenizer(info,",");
if(!info.substring(3,6).equals("¾Ç¦~«×")){
JOptionPane.showConfirmDialog(this, "Àɮ׮榡¿ù»~", "ĵ§i", JOptionPane.CLOSED_OPTION
,JOptionPane.ERROR_MESSAGE);
return;
}
UpdateInfo(STinfo.nextToken(),STinfo.nextToken(),STinfo.nextToken());
ThisWeek = Integer.parseInt(STinfo.nextToken())+1;
InitialData();
info = BR.readLine();
StringTokenizer Winfo = new StringTokenizer(info,",");
Winfo.nextToken();Winfo.nextToken();Winfo.nextToken();
for(int i=0;i<18;i++){
WeekDate[i] = Winfo.nextToken();
hasData[i] = Winfo.nextToken().equals("true")?true:false;
}
String S = "";
while((S = BR.readLine())!=null){
StringTokenizer ST = new StringTokenizer(S,", ");
String seat = ST.nextToken();
for(HashMap<String,String> HM:Data){
if(HM.get("seat").equals(seat)){
HM.put("id",ST.nextToken());
HM.put("name",ST.nextToken());
for(int i=0;i<18;i++){
if(HM.get("id").equals("-")){
HM.put((i+1)+"-attend",ST.nextToken());
}else{
HM.put((i+1)+"-attend",(i+1)==ThisWeek?"¥X®u":ST.nextToken());
}
HM.put((i+1)+"-score",ST.nextToken());
}
break;
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
JM_file.getItem(0).setEnabled(false);
JM_edit.setEnabled(true);
JM_seat.getItem(0).setEnabled(false);
JM_seat.getItem(1).setEnabled(true);
JM_seat.getItem(2).setEnabled(false);
JM_score.setEnabled(true);
JM_week.setEnabled(true);
FileType = "file";
NowWeek = ThisWeek;
WeekDate[ThisWeek-1] = new SimpleDateFormat("MM/dd").format(new Date());
hasData[ThisWeek-1] = true;
UpdateSeat();
SetStatus(0, "½Òµ{¸ê®Æ¶×¤J¦¨¥\,±z¥i¥H¶}©lÂI¦W,ÂIÀ»®y¦ì«ö¶s§ó§ï¥X®uª¬ªp,ÂI¦W§¹¦¨½Ð¿ï¨ú-ÀÉ®×-Àx¦s½Ò°ó¸ê®Æ-");
}
}
private void SaveFile(){
UpdateAttend();
JFileChooser JFC = new JFileChooser();
JFC.setFileSelectionMode(JFileChooser.FILES_ONLY);
JFC.setApproveButtonText("Àx¦s");
JFC.setDialogTitle("Àx¦s¸ô®|¤ÎÀɦW");
JFC.setSelectedFile(new File(YEAR.getText()+"_"+CLASSNAME.getText()+"_½Òµ{¸ê®Æ.csv"));
int returnVal = JFC.showOpenDialog(this);
if(returnVal == JFileChooser.APPROVE_OPTION){
String Path = JFC.getSelectedFile().getAbsolutePath();
File F = new File(Path+(Path.endsWith(".csv")?"":".csv"));
String S = YEAR.getText()+","+TEACHER.getText()+","+CLASSNAME.getText()+","
+ThisWeek+",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,\r\n";
S += "®y¦ì,¾Ç¸¹,©m¦W";
for(int i=0;i<18;i++){
S += ","+WeekDate[i]+","+hasData[i];
}
S += "\r\n";
for(HashMap<String,String> HM:Data){
S += HM.get("seat")+","+HM.get("id")+","+HM.get("name");
for(int i=0;i<18;i++){
S += ","+HM.get((i+1)+"-attend")+","+HM.get((i+1)+"-score");
}
S += "\r\n";
}
try {
F.createNewFile();
BufferedWriter B = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(F)));
B.write(S);B.flush();
B.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void ViewInfo(){
String info = "¯u²z¤j¾Ç¸ê°T¤uµ{¾Ç¨t_712±Ð«Ç_½Ò°ó»²§U¨t²Î\n\n"+
"¡·º¦¸¨Ï¥Î½Ð·s¼W®y¦ìªí¶ñ¤J¾Ç¥Í¸ê®Æ\n¨Ã©ó½s¿è§¹²¦«áÀx¦s®y¦ìªí\n\n"+
"¡·²Ä¤@¶g¤W½Ò³z¹L¶×¤J®y¦ìªí¶}©l½s¿è½Ò°ó¸ê®Æ\n¥»¨t²Î¥i°O¿ý¨C¶g¤W½Ò¸ê°T(ÂI¦W¬ö¿ý,½Ò°ó¦¨ÁZ)\n\n"+
"¡·©¹«á¨C¶g¤W½Ò¥i§Q¥Î«e¦¸©ÒÀx¦s¤§½Òµ{¸ê®Æ¶i¦æ·s¤@¶gªº½Ò°ó";
JOptionPane.showMessageDialog(this,info);
}
private void ViewAbout(){
JLabel JL = new JLabel();
JL.addMouseListener(new MouseListener() {
@Override
public void mouseReleased(MouseEvent e) {}
@Override
public void mousePressed(MouseEvent e) {}
@Override
public void mouseExited(MouseEvent e) {}
@Override
public void mouseEntered(MouseEvent e) {}
@Override
public void mouseClicked(MouseEvent e) {
String cmd = "rundll32 "+"url.dll,FileProtocolHandler "
+"http://fb.com/yaohailong";
try {
Process p = Runtime.getRuntime().exec(cmd);
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
JL.setText("<html>¯u²z¤j¾Ç¸ê°T¤uµ{¾Ç¨t_712±Ð«Ç_½Ò°ó»²§U¨t²Î<br>"
+"Build: v 1.0-20140421<br>»s§@: ¯u²z¸ê¤u ¶ÀÄËåf<br><br>"
+"<a href=\"http://fb.com/yaohailong\">¯u²z¸ê¤u åf®üÀs</a></html>");
JOptionPane.showMessageDialog(this,JL,
"Ãö©ó",JOptionPane.CLOSED_OPTION,
new ImageIcon(this.getClass().getResource("/lute.png")));
}
private void ViewData(){
String c[] = new String[39];
c[0] = "®y¦ì";c[1] = "¾Ç¸¹";c[2] = "©m¦W";
for(int i=3;i<39;i+=2){
c[i] = ((i-1)/2)+"-¥X®u";
c[i+1] = ((i-1)/2)+"-¦¨ÁZ";
}
String t[][] = new String[84][39];
int i=0;
for(HashMap<String,String> HM:Data){
t[i][0] = HM.get("seat");
t[i][1] = HM.get("id");
t[i][2] = HM.get("name");
for(int j=3;j<39;j+=2){
t[i][j] = HM.get(((j-1)/2)+"-attend");
t[i][j+1] = HM.get(((j-1)/2)+"-score");
}
i++;
}
JTable JT = new JTable(t,c);
JT.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
JT.setShowHorizontalLines(false);
JT.setSelectionMode(0);
JT.setRowSorter(new TableRowSorter<TableModel>(JT.getModel()));
for(int x=0;x<JT.getColumnCount();x++){
int width = 0;
int Row = JT.getRowCount();
for (int ii=0;ii<Row;ii++) {
TableCellRenderer renderer = JT.getCellRenderer(ii, x);
Component comp = renderer.getTableCellRendererComponent(
JT, JT.getValueAt(ii, x),false, false, ii, x);
int thisWidth = comp.getPreferredSize().width;
if (thisWidth > width)
width = thisWidth;
}
if(x>2 && width<40)
width = 40;
JT.getColumnModel().getColumn(x).setPreferredWidth(width+10);
JT.getColumnModel().getColumn(x).setResizable(false);
}
JScrollPane JSP = new JScrollPane(JT);
JSP.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
JSP.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
JOptionPane.showMessageDialog(this,JSP,"ÂIÀ»Äæ¦ì¦WºÙ¥i¥H±Æ§Ç",JOptionPane.PLAIN_MESSAGE);
}
private void NoData(){
for(HashMap<String,String> HM:Data){
HM.put(NowWeek+"-attend","-");
}
for(JButton JB:BArr){
if(TArr1.get(BArr.indexOf(JB)).getText().length()==8){
JB.setBackground(Color.GREEN);
JB.setForeground(Color.BLACK);
}
}
hasData[NowWeek-1] = false;
hasData[NowWeek] = true;
ThisWeek++;
NowWeek = ThisWeek;
WeekDate[ThisWeek-1] = new SimpleDateFormat("MM/dd").format(new Date());
UpdateSeat();
}
private void EditScore(){
String c[] = {"®y¦ì","¾Ç¸¹","©m¦W","¥»¶g¦¨ÁZ"};
String t[][] = new String[84][4];
int i=0;
for(HashMap<String,String> HM:Data){
t[i][0] = HM.get("seat");
t[i][1] = HM.get("id");
t[i][2] = HM.get("name");
t[i][3] = HM.get(NowWeek+"-score");
i++;
}
JTable JT = new JTable(t,c);
JT.setShowHorizontalLines(false);
JT.setSelectionMode(0);
JT.setRowSorter(new TableRowSorter<TableModel>(JT.getModel()));
JT.putClientProperty("terminateEditOnFocusLost", true);
JScrollPane JSP = new JScrollPane(JT);
JSP.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
JSP.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
int cho = JOptionPane.showConfirmDialog(this,JSP,"ÂùÀ»¦¨ÁZÄæ¦ì¥H½s¿è",
JOptionPane.OK_CANCEL_OPTION,JOptionPane.PLAIN_MESSAGE);
if(cho==0){
for(i=0;i<84;i++){
for(HashMap<String,String> HM:Data){
if(HM.get("seat").equals(JT.getValueAt(i,0))){
HM.put(NowWeek+"-score",String.valueOf(JT.getValueAt(i,3)));
break;
}
}
}
SetStatus(0,"¦¨ÁZ½s¿è§¹¦¨,½Òµ{¸ê®Æ¤w§ó·s!!!");
}else{
SetStatus(1,"¨ú®ø½s¿è¦¨ÁZ!!!");
}
}
private void ChangeWeekDate(){
String d = JOptionPane.showInputDialog(this,"½Ð¿é¤J¤é´Á:(mm/dd)");
if(d.matches("[0-1][0-9]/[0-3][0-9]")){
WeekDate[NowWeek-1] = d;
UpdateSeat();
}else{
SetStatus(1, "¤é´Á®æ¦¡¿ù»~!!!");
}
}
private void SetStatus(int i,String S){
switch(i){
case 0:
STATUS.setForeground(Color.BLACK);
STATUS.setText(STATUS.getText()+"\n"+S);
break;
case 1:
STATUS.setForeground(Color.RED);
STATUS.setText(STATUS.getText()+"\n"+S);
break;
}
}
private class Clock implements Runnable{
JLabel CLOCK;
SimpleDateFormat fomat = new SimpleDateFormat("yyyy/MM/dd aaa hh:mm:ss");
public Clock(JLabel CLOCK) {
this.CLOCK = CLOCK;
}
@Override
public void run() {
while(true){
CLOCK.setText(fomat.format(new Date()));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
@Override
public void actionPerformed(ActionEvent e) {
JMenuItem M = (JMenuItem)e.getSource();
if(M.getText().equals("Ū¨ú½Ò°ó¸ê®Æ")){
ReadFile();
}else if(M.getText().equals("Àx¦s½Ò°ó¸ê®Æ")){
SaveFile();
}else if(M.getText().equals("Â÷¶}")){
System.exit(0);
}else if(M.getText().equals("¥»¶gµL½Òµ{¸ê®Æ")){
NoData();
}else if(M.getText().equals("½s¿è¹L©¹¸ê®Æ")){
JOptionPane.showMessageDialog(this,"¦¹¶µ¥\¯à¥¼¶}©ñ");
}else if(M.getText().equals("§ó§ï¥»¶g¤W½Ò¤é´Á")){
ChangeWeekDate();
}else if(M.getText().equals("·s¼W")){
NewSeat();
}else if(M.getText().equals("×§ï")){
if(JOptionPane.showConfirmDialog(this,"×§ï®y¦ì±N©ñ±óÂI¦W¬ö¿ý\n½T»{×§ï?","½T»{×§ï",
JOptionPane.OK_CANCEL_OPTION) == 0){
StartEdit();
}else{
SetStatus(0,"¨ú®ø×§ï!!!");
}
}else if(M.getText().equals("¶×¤J")){
ReadSeat();
}else if(M.getText().equals("¶×¥X(¤£¥]§t½Òµ{¸ê®Æ)")){
SaveSeat();
}else if(M.getText().equals("½s¿è¥»¶g¦¨ÁZ")){
EditScore();
}else if(M.getText().equals("®y¦ì¤ÏÂà")){
ChangeDirection();
}else if(M.getText().equals("»¡©ú")){
ViewInfo();
}else if(M.getText().equals("Ãö©ó")){
ViewAbout();
}else if(M.getText().equals("Á`Äý")){
UpdateAttend();
ViewData();
}else{
UpdateAttend();
NowWeek = Integer.parseInt(M.getName());
UpdateSeat();
}
}
} | a0tim/aucsie-712-class-assistant-system | assistant-system-712/src/seat712.java | Java | gpl-2.0 | 28,987 |
/*
* Copyright 1999 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. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun 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 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.
*/
/*
* COMPONENT_NAME: idl.parser
*
* ORIGINS: 27
*
* Licensed Materials - Property of IBM
* 5639-D57 (C) COPYRIGHT International Business Machines Corp. 1997, 1999
* RMI-IIOP v1.0
*
*/
package com.sun.tools.corba.se.idl.constExpr;
// NOTES:
import com.sun.tools.corba.se.idl.Util;
import java.math.BigInteger;
public class BooleanAnd extends BinaryExpr
{
protected BooleanAnd (Expression leftOperand, Expression rightOperand)
{
super ("&&", leftOperand, rightOperand);
} // ctor
public Object evaluate () throws EvaluationException
{
try
{
Object tmpL = left ().evaluate ();
Object tmpR = right ().evaluate ();
Boolean l;
Boolean r;
//daz if (tmpL instanceof Number)
// l = new Boolean (((Number)tmpL).longValue () != 0);
// else
// l = (Boolean)tmpL;
if (tmpL instanceof Number)
{
if (tmpL instanceof BigInteger)
l = new Boolean (((BigInteger)tmpL).compareTo (BigInteger.valueOf (0)) != 0);
else
l = new Boolean (((Number)tmpL).longValue () != 0);
}
else
l = (Boolean)tmpL;
//daz if (tmpR instanceof Number)
// r = new Boolean (((Number)tmpR).longValue () != 0);
// else
// r = (Boolean)tmpR;
if (tmpR instanceof Number)
{
if (tmpR instanceof BigInteger)
r = new Boolean (((BigInteger)tmpR).compareTo (zero) != 0);
else
r = new Boolean (((Number)tmpR).longValue () != 0);
}
else
r = (Boolean)tmpR;
value (new Boolean (l.booleanValue () && r.booleanValue ()));
}
catch (ClassCastException e)
{
String[] parameters = {Util.getMessage ("EvaluationException.booleanAnd"), left ().value ().getClass ().getName (), right ().value ().getClass ().getName ()};
throw new EvaluationException (Util.getMessage ("EvaluationException.1", parameters));
}
return value ();
} // evaluate
} // class BooleanAnd
| TheTypoMaster/Scaper | openjdk/corba/src/share/classes/com/sun/tools/corba/se/idl/constExpr/BooleanAnd.java | Java | gpl-2.0 | 3,223 |
package com.mnbryant.twinkies.ingredients;
import com.mnbryant.twinkies.Ingredient;
public class Salt extends Ingredient {
public Salt() {
super("Salt (Sodium Chloride)",
"Salt, also known as sodium chloride (NaCl), comes from rock salt or brine. Rock salt is mined from salt mines (no joke!) that can be anywhere from hundreds to thousands of feet below the surface. The salt is mined in a pattern that leaves solid columns to help support the mine roof. The general process involves undercutting, a process where a flat slot is cut about 10 feet deep into the salt to leave a smooth surface to pick up salt from. Small holes are drilled into the salt and loaded with explosives. After the work shift, the explosives are remotely detonated, releasing hundreds to thousands of tons of salt onto the mine floor. Equipment loads the salt and it is processed to be broken and crushed into various selling sizes.\r\n\r\n"
+ "Salt is harvested from brine through the processes of solar and vacuum evaporation. The basic idea of each is the same: evaporate the water and leave the salt behind. Solar evaporation uses massive shallow ponds of brine - anywhere from 40 to 200 acres - while vacuum evaporation uses massive vacuum pans, closed structures about three stories high that are under vacuum. They are found in groups of three to five, with each one under greater vacuum than the previous. Being under greater vacuum decreases the air pressure inside the container, which decreases the boiling point of the salt water inside. Hot steam is fed into the first vacuum pan, which sets the water inside boiling, then that steam is fed to the second pan, and so on. Having multiple pans in a row increases energy efficiency by producing more salt per pound of steam.",
"Salt may or may not be refined by having the impurities removed and possibly having other additives included as well. One common additive is iodine, creating iodized salt. As sodium chloride, it provides the body with electrolytes and helps relax muscles. Many cultures (such as the United States) consume dangerous levels of salt, however. This leads to high blood pressure, which can lead to stroke and heart disease.");
}
}
| Shadow53/Twinkies | src/com/mnbryant/twinkies/ingredients/Salt.java | Java | gpl-2.0 | 2,211 |
package hudsonmendes.lab.springDataRedis.model;
import java.io.Serializable;
import java.time.Instant;
public class EntryInfo implements Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
private String message;
private Instant createdAt;
public Integer getId() {
return id;
}
public void setId(final Integer id) {
this.id = id;
}
public String getMessage() {
return message;
}
public void setMessage(final String message) {
this.message = message;
}
public Instant getCreatedAt() {
return createdAt;
}
public void setCreatedAt(final Instant createdAt) {
this.createdAt = createdAt;
}
} | hudsonmendes/benchmark-spring-data-redis | src/main/java/hudsonmendes/lab/springDataRedis/model/EntryInfo.java | Java | gpl-2.0 | 656 |
package state;
public class PreState extends State {
public PreState(Machine machine) {
super(machine);
}
@Override
public String pay(double money) {
String ret = money + " paid, ";
machine.incMoney(money);
ret = ret + machine.getMoney() + " in total";
if (machine.enough()) {
ret = ret + ", enough";
try {
machine.setState("toConfirm");
} catch (Exception e) {
e.printStackTrace();
}
}
return ret;
}
@Override
public String cancel() {
return machine.rollback();
}
@Override
public String confirm() {
double left = machine.getLeft();
return "not enough money, need " + left + " more";
}
}
| momo9/design-pattern | state/src/state/PreState.java | Java | gpl-2.0 | 809 |
package com.crossarx.rest.api.hiv.tests;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.core.Response;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import com.crossarx.rest.api.hiv.Utils;
import com.crossarx.rest.api.hiv.entities.Chapter;
import com.crossmarx.rest.api.entities.Filter;
import com.crossmarx.rest.api.entities.FilterLeaf;
import com.crossmarx.rest.api.entities.FilterNode;
import com.crossmarx.rest.api.entities.Login;
import com.crossmarx.rest.api.entities.LoginResponse;
import com.crossmarx.rest.api.entities.Query;
import com.crossmarx.rest.api.entities.Spec;
import com.crossmarx.rest.api.exceptions.SecurityConfigurationException;
import com.crossmarx.rest.api.exceptions.SerializingException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
public class TestArchive {
private LoginResponse loginResponse;
private final Integer courseId = 18;
private final String language = "en";
private final Integer id = 162;
@Before
public void setUp() throws Exception {
loginResponse = getLoginResponse();
}
@Test
public void testArchiveOutput() {
try {
System.out.println(getArchive());
} catch (SecurityConfigurationException | JsonProcessingException e) {
fail(e.getMessage());
} catch (IOException e) {
fail(e.getMessage());
}
}
@Test
public void testGetArchive() {
try {
Assert.assertTrue(getArchive().getId() == this.id);
} catch (IOException | SecurityConfigurationException e) {
fail(e.getMessage());
}
}
@Test
public void testGetArchiveQueryOK() {
// /engine/api/VERSION/query?querydef={}&authhash=<hash>
try {
Query query = makeTestArchiveQueryOK();
String value = Utils.getMapper().writeValueAsString(query);
value = value.replace("className", "class");
value = URLEncoder.encode(value, "UTF-8");
String operation = "query?querydef=" + value + "&authhash=" + loginResponse.getAuthHash();
Response response = Utils.getClient().doGet(operation);
String result = response.readEntity(String.class);
System.out.println(result);
JsonNode rootNode = Utils.getMapper().readTree(result);
JsonNode recordNode = rootNode.path("record");
JsonNode dataNode = recordNode.path("data");
//System.out.println(dataNode);
String id = dataNode.path("Id").toString();
Assert.assertTrue(id.equals(id + ""));
} catch (SecurityConfigurationException | JsonProcessingException | UnsupportedEncodingException e) {
fail(e.getMessage());
} catch (IOException e) {
fail(e.getMessage());
}
}
/**
*
* @return
*/
private Query makeTestArchiveQueryOK() {
Query queryRequest = new Query();
List<Spec> sortSpecs = new ArrayList<>();
// Spec spec = new Spec();
// spec.setField("name");
// spec.setDirection("desc");
// sortSpecs.add(spec);
Spec spec2 = new Spec();
spec2.setField("Id");
spec2.setDirection("asc");
sortSpecs.add(spec2);
queryRequest.setSortSpecs(sortSpecs);
queryRequest.setClassName("Archive");
FilterNode filter = new FilterNode();
filter.setOperator("and");
List<Filter> children = new ArrayList<>();
FilterLeaf leaf1 = new FilterLeaf();
leaf1.setField("Courses");
leaf1.setOperator("equals");
leaf1.setValue(this.courseId);
children.add(leaf1);
filter.setChildren(children);
queryRequest.setFilter(filter);
List<String> resultFields = new ArrayList<>();
resultFields.add("Id");
resultFields.add("Name");
queryRequest.setResultFields(resultFields);
return queryRequest;
}
//@Test
public void testArchiveImageDownload() {
// URI: /engine/api/<version>/download/<class>/<id>/Image
String operation = "download/Archive/" + this.id + "/Image?authhash=" + loginResponse.getAuthHash();
try {
Response response = Utils.getClient().doGet(operation);
InputStream in = (InputStream) response.readEntity(InputStream.class);
//String path = getArchive(id).getImage();
String path = "";
Integer index = path.lastIndexOf("/");
String fileName = path.substring(index+1, path.length());
OutputStream outputStream = new FileOutputStream(new File("D:\\" + fileName));
int read = 0;
byte[] bytes = new byte[1024];
while ((read = in.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
outputStream.close();
System.out.println(bytes.length);
} catch (SecurityConfigurationException e) {
fail(e.getMessage());
} catch (IOException e) {
fail(e.getMessage());
}
}
private Chapter getArchive()
throws SecurityConfigurationException, JsonProcessingException, IOException {
// Operation:/record/<class>/<id>?authhash=<hash>
String operation = "record/Archive/" + this.id + "?authhash=" + loginResponse.getAuthHash();
Response response = Utils.getClient().doGet(operation);
String result = response.readEntity(String.class);
System.out.println(result);
JsonNode rootNode = Utils.getMapper().readTree(result);
JsonNode recordNode = rootNode.path("record");
JsonNode dataNode = recordNode.path("data");
return getArchiveFromJson(dataNode);
}
/**
*
* @param dataNode
* @return
*/
private Chapter getArchiveFromJson(JsonNode dataNode){
System.out.println(dataNode);
Chapter chapter = new Chapter();
// Iterator<JsonNode> it = dataNode.path("available_languages").iterator();
// List<String> languages = new ArrayList<>();
// while(it.hasNext()){
// String value = it.next().asText();
// languages.add(value);
// }
// course.setAvailable_languages(languages);
// course.setBezocht(Integer.valueOf(dataNode.path("bezocht").toString()));
// course.setCss_class(dataNode.path("css_class").toString());
// course.setDescription(dataNode.path("description").toString());
// course.setDownload_completed(Boolean.valueOf(dataNode.path("download_completed").toString()));
// course.setFree(Boolean.valueOf(dataNode.path("free").toString()));
// course.setId(Integer.valueOf(dataNode.path("id").toString()));
// course.setIntroduction(dataNode.path("introduction").toString());
// course.setName(dataNode.path("name").toString());
// course.setObjective(dataNode.path("objective").toString());
// course.setStatus(dataNode.path("status").toString());
// course.setWebdisplay(Boolean.valueOf(dataNode.path("webdisplay").toString()));
return chapter;
}
/**
*
* @return
* @throws SerializingException
* @throws SecurityConfigurationException
* @throws JsonProcessingException
*/
private LoginResponse getLoginResponse()
throws SerializingException, SecurityConfigurationException, JsonProcessingException {
String bodyRequest = getLoginRequest("ken", "123");
String operation = "login";
Response response = Utils.getClient().doPost(bodyRequest, operation);
return response.readEntity(LoginResponse.class);
}
/**
*
* @param loginname
* @param password
* @return
* @throws SerializingException
* @throws JsonProcessingException
*/
private String getLoginRequest(String loginname, String password)
throws SerializingException, JsonProcessingException {
Login login = new Login(loginname, password);
return Utils.getMapper().writeValueAsString(login);
}
}
| carlosgag/java | RestAPITest/src/test/java/com/crossarx/rest/api/hiv/tests/TestArchive.java | Java | gpl-2.0 | 7,461 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.ufrn.gui;
import java.net.MalformedURLException;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.util.Date;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import br.ufrn.controle.PacienteFachada;
import br.ufrn.controle.PacienteFachadaInterface;
import br.ufrn.controle.PacienteGUI;
import br.ufrn.excecoes.BDexception;
/**
*
* @author jorge
*/
public class paciente extends javax.swing.JFrame implements PacienteGUI {
private final PacienteFachadaInterface pacienteControle;
private int linhasTabela = 0;
private String paciente;
/**
* Creates new form paciente
*
* @throws NotBoundException
* @throws RemoteException
* @throws MalformedURLException
*/
public paciente() throws MalformedURLException, RemoteException, NotBoundException {
pacienteControle = new PacienteFachada(this);
inserirNomepaciente();
initComponents();
this.setTitle("Paciente " + paciente);
}
public void inserirNomepaciente() {
paciente = JOptionPane.showInputDialog("Digite o nome do paciente.");
try {
pacienteControle.inserirNomePaciente(paciente);
} catch (BDexception e) {
JOptionPane.showInternalMessageDialog(this, "Erro! \n" + e.getMessage());
this.dispose();
}
}
@Override
public void updateGUI(String medicamento, Date horario, Integer dosagem, String mensagem) {
DefaultTableModel model = (DefaultTableModel) jTmedicacao.getModel();
model.addRow(new String[]{null, null, null});
jTmedicacao.setValueAt(medicamento, linhasTabela, 0);
jTmedicacao.setValueAt(horario.toLocaleString(), linhasTabela, 1);
jTmedicacao.setValueAt(dosagem, linhasTabela, 2);
linhasTabela++;
JOptionPane.showMessageDialog(this, mensagem + "\nmedicacao: " + medicamento + " dosagem: " + dosagem,
"Sinais vitais fora dos limites", JOptionPane.WARNING_MESSAGE);
}
@Override
public String getNomePaciente() {
return paciente;
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated
// Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
jSpressao = new javax.swing.JSlider();
jSbatimentos = new javax.swing.JSlider();
jSglicose = new javax.swing.JSlider();
jPanel2 = new javax.swing.JPanel();
jScrollPane2 = new javax.swing.JScrollPane();
jTmedicacao = new javax.swing.JTable();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/ufrn/icons/paciente.gif"))); // NOI18N
jSpressao.setMajorTickSpacing(2);
jSpressao.setMaximum(20);
jSpressao.setMinorTickSpacing(1);
jSpressao.setPaintLabels(true);
jSpressao.setValue(10);
jSpressao.setBorder(javax.swing.BorderFactory.createTitledBorder("Pressão"));
jSpressao.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
jSpressao.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
jSpressaoMouseReleased(evt);
}
});
jSbatimentos.setMajorTickSpacing(20);
jSbatimentos.setMaximum(140);
jSbatimentos.setMinorTickSpacing(1);
jSbatimentos.setPaintLabels(true);
jSbatimentos.setValue(80);
jSbatimentos.setBorder(javax.swing.BorderFactory.createTitledBorder("Batimentos Cardíacos"));
jSbatimentos.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
jSbatimentosMouseReleased(evt);
}
});
jSglicose.setMajorTickSpacing(20);
jSglicose.setMaximum(200);
jSglicose.setMinimum(20);
jSglicose.setMinorTickSpacing(1);
jSglicose.setPaintLabels(true);
jSglicose.setValue(80);
jSglicose.setBorder(javax.swing.BorderFactory.createTitledBorder("Glicose"));
jSglicose.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
jSglicoseMouseReleased(evt);
}
});
jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder());
jTmedicacao.setModel(new javax.swing.table.DefaultTableModel(new Object[][] { },
new String[] { "Medicamento", "Horário", "Dosagem" }) {
boolean[] canEdit = new boolean[] { false, false, false };
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit[columnIndex];
}
});
jScrollPane2.setViewportView(jTmedicacao);
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup().addContainerGap()
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 574, Short.MAX_VALUE)
.addContainerGap()));
jPanel2Layout.setVerticalGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup().addComponent(jScrollPane2,
javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 9, Short.MAX_VALUE)));
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup().addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup().addComponent(jLabel2).addGap(18, 18, 18)
.addGroup(jPanel1Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jSbatimentos, javax.swing.GroupLayout.DEFAULT_SIZE, 360,
Short.MAX_VALUE)
.addComponent(jSpressao, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jSglicose, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addComponent(jPanel2, javax.swing.GroupLayout.Alignment.TRAILING,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE))
.addContainerGap()));
jPanel1Layout.setVerticalGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jSpressao, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSbatimentos, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jSglicose, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jLabel2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(20, 20, 20)));
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(
jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE));
layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup().addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));
pack();
}// </editor-fold>//GEN-END:initComponents
private void jSpressaoMouseReleased(java.awt.event.MouseEvent evt) {// GEN-FIRST:event_jSpressaoMouseReleased
pacienteControle.atualizarPressao(jSpressao.getValue());
}// GEN-LAST:event_jSpressaoMouseReleased
private void jSbatimentosMouseReleased(java.awt.event.MouseEvent evt) {// GEN-FIRST:event_jSbatimentosMouseReleased
pacienteControle.atualizarBatimentos(jSbatimentos.getValue());
}// GEN-LAST:event_jSbatimentosMouseReleased
private void jSglicoseMouseReleased(java.awt.event.MouseEvent evt) {// GEN-FIRST:event_jSglicoseMouseReleased
pacienteControle.atualizarGlicose(jSglicose.getValue());
}// GEN-LAST:event_jSglicoseMouseReleased
/**
* @param args
* the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
// <editor-fold defaultstate="collapsed" desc=" Look and feel setting
// code (optional) ">
/*
* If Nimbus (introduced in Java SE 6) is not available, stay with the
* default look and feel. For details see
* http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.
* html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(paciente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(paciente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(paciente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(paciente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
// </editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
try {
new paciente().setVisible(true);
} catch (MalformedURLException | RemoteException | NotBoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel jLabel2;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JSlider jSbatimentos;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JSlider jSglicose;
private javax.swing.JSlider jSpressao;
private javax.swing.JTable jTmedicacao;
// End of variables declaration//GEN-END:variables
}
| JorgePereiraUFRN/Monitoramento_Paciente | Paciente/src/br/ufrn/gui/paciente.java | Java | gpl-2.0 | 11,834 |
package puzzle;
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.border.TitledBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import algorithms.AStarSearch;
import algorithms.BreadthFirstSearch;
import algorithms.IterativeDeepeningSearch;
import algorithms.MemoizingDepthFirstSearch;
import algorithms.SearchAlgorithmCommons;
import datastructures.PuzzleState;
public class PanelSettings extends JPanel
{
private JPanel panelAlgorithmSettings = null;
private JPanel panelControlSettings = null;
private JButton buttonStart = null;
private JButton buttonPause = null;
private JButton buttonNext = null;
private JButton buttonStop = null;
private JSlider sliderRunningSpeed = null;
private JPanel panelMonteCarloSettings = null;
private JTextField textFieldMonteCarloSimCnt = null;
private JTextField textFieldTrueDistance = null;
private JButton buttonStartMonteCarloSimulation = null;
private JComboBox comboBoxMonteCarloPuzzleSize = null;
private JComboBox comboBoxAlgorithmSelection = null;
private PanelPuzzleView panelPuzzleView = null;
private PanelOutputWindow panelLogWindow = null;
private BreadthFirstSearch<PuzzleState> bfs = null;
private MemoizingDepthFirstSearch<PuzzleState> dfs = null;
private IterativeDeepeningSearch<PuzzleState> ids = null;
private AStarSearch<PuzzleState> ass = null;
private AlgoRunThread threadAlgoRun = null;
private int iTotalExpandedNode = 0;
private int iTotalMemoryStorage = 0;
public PanelSettings()
{
super(new BorderLayout(2, 2));
setBorder(new TitledBorder("Settings"));
add(getPanelAlgorithmSettings(), BorderLayout.WEST);
add(getPanelControlSettings(), BorderLayout.CENTER);
add(getPanelMonteCarloSettings(), BorderLayout.EAST);
}
private JSlider getSliderRunningSpeed()
{
if(sliderRunningSpeed == null)
{
sliderRunningSpeed = new JSlider(SwingConstants.HORIZONTAL);
sliderRunningSpeed.setBorder(new TitledBorder("Running Speed"));
sliderRunningSpeed.setValue(0);
sliderRunningSpeed.addChangeListener(new ChangeListener()
{
@Override
public void stateChanged(ChangeEvent arg0)
{
SearchAlgorithmCommons.iTimerDelayInMs = ((100 - sliderRunningSpeed.getValue()) * 10) + 1;
}
});
}
return sliderRunningSpeed;
}
private JPanel getPanelMonteCarloSettings()
{
if(panelMonteCarloSettings == null)
{
panelMonteCarloSettings = new JPanel(new GridBagLayout());
panelMonteCarloSettings.setBorder(new TitledBorder("Monte Carlo Simulations"));
GridBagConstraints gbc1 = new GridBagConstraints();
gbc1.gridx = 0;
gbc1.gridy = 0;
gbc1.fill = GridBagConstraints.HORIZONTAL;
gbc1.insets = new Insets(2,2,2,2);
panelMonteCarloSettings.add(new JLabel("Simulation Cnt(N):"), gbc1);
GridBagConstraints gbc2 = new GridBagConstraints();
gbc2.gridx = 1;
gbc2.gridy = 0;
gbc2.fill = GridBagConstraints.HORIZONTAL;
gbc2.insets = new Insets(2,2,2,2);
panelMonteCarloSettings.add(getTfMonteCarloSimulationCnt(), gbc2);
GridBagConstraints gbc3 = new GridBagConstraints();
gbc3.gridx = 0;
gbc3.gridy = 1;
gbc3.fill = GridBagConstraints.HORIZONTAL;
gbc3.insets = new Insets(2,2,2,2);
panelMonteCarloSettings.add(new JLabel("True Distance(M):"), gbc3);
GridBagConstraints gbc4 = new GridBagConstraints();
gbc4.gridx = 1;
gbc4.gridy = 1;
gbc4.fill = GridBagConstraints.HORIZONTAL;
gbc4.insets = new Insets(2,2,2,2);
panelMonteCarloSettings.add(getTfMonteCarloTrueDistance(), gbc4);
GridBagConstraints gbc5 = new GridBagConstraints();
gbc5.gridx = 0;
gbc5.gridy = 2;
gbc5.fill = GridBagConstraints.HORIZONTAL;
gbc5.insets = new Insets(2,2,2,2);
panelMonteCarloSettings.add(new JLabel("Puzzle Size:"), gbc5);
GridBagConstraints gbc6 = new GridBagConstraints();
gbc6.gridx = 1;
gbc6.gridy = 2;
gbc6.fill = GridBagConstraints.HORIZONTAL;
gbc6.insets = new Insets(2,2,2,2);
panelMonteCarloSettings.add(getCbMonteCarloPuzzleSize(), gbc6);
GridBagConstraints gbc7 = new GridBagConstraints();
gbc7.gridx = 0;
gbc7.gridy = 3;
gbc7.gridwidth = 2;
gbc7.fill = GridBagConstraints.HORIZONTAL;
gbc7.insets = new Insets(2,2,2,2);
panelMonteCarloSettings.add(getButtonStartMonteCarloSimulation(), gbc7);
}
return panelMonteCarloSettings;
}
private JButton getButtonStartMonteCarloSimulation()
{
if(buttonStartMonteCarloSimulation == null)
{
buttonStartMonteCarloSimulation = new JButton("Start");
buttonStartMonteCarloSimulation.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent arg0)
{
int iSimCnt = Integer.parseInt(getTfMonteCarloSimulationCnt().getText());
int iTrueDistance = Integer.parseInt(getTfMonteCarloTrueDistance().getText());
int iPuzzleSize = (getCbMonteCarloPuzzleSize().getSelectedIndex() * 2) + 3;
Vector<PuzzleState> vecVisited = new Vector<PuzzleState>();
PuzzleState goalState = new PuzzleState(getGoalStateIntArray(iPuzzleSize));
PuzzleState startState = null;
Vector<PuzzleState> vecSuccStates = null;
Random randNum = new Random();
int iRandomIndex = 0;
for (int i = 0; i < iSimCnt; i++)
{
startState = goalState;
vecVisited.removeAllElements();
vecVisited.add(startState);
for (int j = 0; j < iTrueDistance; j++)
{
vecSuccStates = startState.getSuccessorStates();
do
{
iRandomIndex = randNum.nextInt(vecSuccStates.size());
}while(vecSuccStates.get(iRandomIndex).isAlreadyContainedInVec(vecVisited));
startState = vecSuccStates.get(iRandomIndex);
}
getPuzzleView().setPuzzleState(startState);
threadAlgoRun = new AlgoRunThread();
threadAlgoRun.start();
while(threadAlgoRun.isAlive());
}
getLogWindow().insertToLogWindow("************");
getLogWindow().insertToLogWindow("Avg Expanded Node Cnt: " + ((double)iTotalExpandedNode) / iSimCnt);
getLogWindow().insertToLogWindow("Avg Memory Storage: " + ((double)iTotalMemoryStorage) / iSimCnt);
getLogWindow().insertToLogWindow("************");
iTotalExpandedNode = 0;
iTotalMemoryStorage = 0;
}
});
}
return buttonStartMonteCarloSimulation;
}
private Integer[][] getGoalStateIntArray(int iSize)
{
Integer[][] iDoubArrGoalState = new Integer[iSize][iSize];
int iValue = 1;
for (int iRowNo = 0; iRowNo < iDoubArrGoalState.length; iRowNo++)
{
for (int iColNo = 0; iColNo < iDoubArrGoalState[0].length; iColNo++)
{
iDoubArrGoalState[iRowNo][iColNo] = iValue++;
}
}
iDoubArrGoalState[iSize - 1][iSize - 1] = 0;
return iDoubArrGoalState;
}
private JComboBox getCbMonteCarloPuzzleSize()
{
if(comboBoxMonteCarloPuzzleSize == null)
{
String[] sArr = new String[]{"3x3", "5x5", "7x7"};
comboBoxMonteCarloPuzzleSize = new JComboBox(sArr);
}
return comboBoxMonteCarloPuzzleSize;
}
private JTextField getTfMonteCarloSimulationCnt()
{
if(textFieldMonteCarloSimCnt == null)
{
textFieldMonteCarloSimCnt = new JTextField();
textFieldMonteCarloSimCnt.setText("5");
}
return textFieldMonteCarloSimCnt;
}
private JTextField getTfMonteCarloTrueDistance()
{
if(textFieldTrueDistance == null)
{
textFieldTrueDistance = new JTextField();
textFieldTrueDistance.setText("5");
}
return textFieldTrueDistance;
}
private JPanel getPanelAlgorithmSettings()
{
if(panelAlgorithmSettings == null)
{
panelAlgorithmSettings = new JPanel(new GridBagLayout());
panelAlgorithmSettings.setBorder(new TitledBorder("Algorithm Settings"));
GridBagConstraints gbc1 = new GridBagConstraints();
gbc1.gridx = 0;
gbc1.gridy = 0;
gbc1.fill = GridBagConstraints.HORIZONTAL;
gbc1.insets = new Insets(2,2,2,2);
panelAlgorithmSettings.add(new JLabel("Algorithm:"), gbc1);
GridBagConstraints gbc2 = new GridBagConstraints();
gbc2.gridx = 1;
gbc2.gridy = 0;
gbc2.fill = GridBagConstraints.HORIZONTAL;
gbc2.insets = new Insets(2,2,2,2);
panelAlgorithmSettings.add(getCbAlgorithmSelection(), gbc2);
}
return panelAlgorithmSettings;
}
private JComboBox getCbAlgorithmSelection()
{
if(comboBoxAlgorithmSelection == null)
{
String[] sArr = new String[]{"BFS", "Memoizing DFS", "IDS", "A* with Misplaced Heuristic", "A* with Manhattan Heuristic"};
comboBoxAlgorithmSelection = new JComboBox(sArr);
}
return comboBoxAlgorithmSelection;
}
private JPanel getPanelControlSettings()
{
if(panelControlSettings == null)
{
panelControlSettings = new JPanel(new GridBagLayout());
panelControlSettings.setBorder(new TitledBorder("Control Settings"));
GridBagConstraints gbc0 = new GridBagConstraints();
gbc0.gridx = 0;
gbc0.gridy = 0;
gbc0.fill = GridBagConstraints.HORIZONTAL;
gbc0.gridwidth = 4;
gbc0.insets = new Insets(2,2,2,2);
panelControlSettings.add(getSliderRunningSpeed(), gbc0);
GridBagConstraints gbc1 = new GridBagConstraints();
gbc1.gridx = 0;
gbc1.gridy = 1;
gbc1.fill = GridBagConstraints.HORIZONTAL;
gbc1.insets = new Insets(2,2,2,2);
panelControlSettings.add(getButtonStart(), gbc1);
GridBagConstraints gbc2 = new GridBagConstraints();
gbc2.gridx = 1;
gbc2.gridy = 1;
gbc2.fill = GridBagConstraints.HORIZONTAL;
gbc2.insets = new Insets(2,2,2,2);
panelControlSettings.add(getButtonPause(), gbc2);
GridBagConstraints gbc3 = new GridBagConstraints();
gbc3.gridx = 2;
gbc3.gridy = 1;
gbc3.fill = GridBagConstraints.HORIZONTAL;
gbc3.insets = new Insets(2,2,2,2);
panelControlSettings.add(getButtonNext(), gbc3);
GridBagConstraints gbc4 = new GridBagConstraints();
gbc4.gridx = 3;
gbc4.gridy = 1;
gbc4.fill = GridBagConstraints.HORIZONTAL;
gbc4.insets = new Insets(2,2,2,2);
panelControlSettings.add(getButtonStop(), gbc4);
}
return panelControlSettings;
}
private JButton getButtonStart()
{
if(buttonStart == null)
{
buttonStart = new JButton("Start");
buttonStart.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent arg0)
{
threadAlgoRun = new AlgoRunThread();
threadAlgoRun.start();
}
});
}
return buttonStart;
}
private JButton getButtonPause()
{
if(buttonPause == null)
{
buttonPause = new JButton("Pause");
buttonPause.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent arg0)
{
int iAlgorithmSelection = getCbAlgorithmSelection().getSelectedIndex();
if(threadAlgoRun != null)
{
if(threadAlgoRun.isAlive())
{
if(iAlgorithmSelection == 0)
{
if(bfs != null)
{
if(getButtonPause().getText().compareTo("Continue") == 0)
{
getButtonPause().setText("Pause");
bfs.continueAlgorithm();
}
else
{
getButtonPause().setText("Continue");
bfs.pauseAlgorithm();
}
}
}
else if(iAlgorithmSelection == 1)
{
if(dfs != null)
{
if(getButtonPause().getText().compareTo("Continue") == 0)
{
getButtonPause().setText("Pause");
dfs.continueAlgorithm();
}
else
{
getButtonPause().setText("Continue");
dfs.pauseAlgorithm();
}
}
}
else if(iAlgorithmSelection == 2)
{
if(ids != null)
{
if(getButtonPause().getText().compareTo("Continue") == 0)
{
getButtonPause().setText("Pause");
ids.continueAlgorithm();
}
else
{
getButtonPause().setText("Continue");
ids.pauseAlgorithm();
}
}
}
else if((iAlgorithmSelection == 3) || (iAlgorithmSelection == 4))
{
if(ass != null)
{
if(getButtonPause().getText().compareTo("Continue") == 0)
{
getButtonPause().setText("Pause");
ass.continueAlgorithm();
}
else
{
getButtonPause().setText("Continue");
ass.pauseAlgorithm();
}
}
}
}
}
}
});
}
return buttonPause;
}
private JButton getButtonStop()
{
if(buttonStop == null)
{
buttonStop = new JButton("Stop");
buttonStop.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent arg0)
{
int iAlgorithmSelection = getCbAlgorithmSelection().getSelectedIndex();
if(threadAlgoRun != null)
{
if(threadAlgoRun.isAlive())
{
getButtonPause().setText("Pause");
if(iAlgorithmSelection == 0)
{
if(bfs != null)
bfs.stopAlgorithm();
}
else if(iAlgorithmSelection == 1)
{
if(dfs != null)
dfs.stopAlgorithm();
}
else if(iAlgorithmSelection == 2)
{
if(ids != null)
ids.stopAlgorithm();
}
else if((iAlgorithmSelection == 3) || (iAlgorithmSelection == 4))
{
if(ass != null)
ass.stopAlgorithm();
}
}
}
}
});
}
return buttonStop;
}
private JButton getButtonNext()
{
if(buttonNext == null)
{
buttonNext = new JButton("Next");
buttonNext.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent arg0)
{
int iAlgorithmSelection = getCbAlgorithmSelection().getSelectedIndex();
if(threadAlgoRun != null)
{
if(threadAlgoRun.isAlive())
{
if(iAlgorithmSelection == 0)
{
if(bfs != null)
bfs.stepAlgorithm();
}
else if(iAlgorithmSelection == 1)
{
if(dfs != null)
dfs.stepAlgorithm();
}
else if(iAlgorithmSelection == 2)
{
if(ids != null)
ids.stepAlgorithm();
}
else if((iAlgorithmSelection == 3) || (iAlgorithmSelection == 4))
{
if(ass != null)
ass.stepAlgorithm();
}
}
}
}
});
}
return buttonNext;
}
private class AlgoRunThread extends Thread
{
public void run()
{
int iAlgorithmSelection = getCbAlgorithmSelection().getSelectedIndex();
PuzzleState goalState = null;
if(iAlgorithmSelection == 0)
{
bfs = new BreadthFirstSearch<PuzzleState>(getPuzzleView().getPuzzleState());
bfs.setPuzzleWindow(getPuzzleView());
bfs.setLogWindow(getLogWindow());
goalState = bfs.startBFS();
iTotalExpandedNode += bfs.getExpandedNodeCnt();
iTotalMemoryStorage += bfs.getMemoryStorage();
if(goalState != null)
generateSolution(goalState);
}
else if(iAlgorithmSelection == 1)
{
dfs = new MemoizingDepthFirstSearch<PuzzleState>(getPuzzleView().getPuzzleState());
dfs.setPuzzleWindow(getPuzzleView());
dfs.setLogWindow(getLogWindow());
goalState = dfs.startDFS();
iTotalExpandedNode += dfs.getExpandedNodeCnt();
iTotalMemoryStorage += dfs.getMemoryStorage();
if(goalState != null)
generateSolution(goalState);
}
else if(iAlgorithmSelection == 2)
{
ids = new IterativeDeepeningSearch<PuzzleState>(getPuzzleView().getPuzzleState());
ids.setPuzzleWindow(getPuzzleView());
ids.setLogWindow(getLogWindow());
goalState = ids.startIDS();
iTotalExpandedNode += ids.getExpandedNodeCnt();
iTotalMemoryStorage += ids.getMemoryStorage();
if(goalState != null)
generateSolution(goalState);
}
else if(iAlgorithmSelection == 3)
{
ass = new AStarSearch<PuzzleState>(getPuzzleView().getPuzzleState(), AStarSearch.HEURISTIC_MISPLACED);
ass.setPuzzleWindow(getPuzzleView());
ass.setLogWindow(getLogWindow());
goalState = ass.startAStar();
iTotalExpandedNode += ass.getExpandedNodeCnt();
iTotalMemoryStorage += ass.getMemoryStorage();
if(goalState != null)
generateSolution(goalState);
}
else if(iAlgorithmSelection == 4)
{
ass = new AStarSearch<PuzzleState>(getPuzzleView().getPuzzleState(), AStarSearch.HEURISTIC_MANHATTAN);
ass.setPuzzleWindow(getPuzzleView());
ass.setLogWindow(getLogWindow());
goalState = ass.startAStar();
iTotalExpandedNode += ass.getExpandedNodeCnt();
iTotalMemoryStorage += ass.getMemoryStorage();
if(goalState != null)
generateSolution(goalState);
}
}
}
private void generateSolution(PuzzleState goalState)
{
int iPathLength = -1;
PuzzleState state = goalState;
String sSolution = "Solution Path: ";
Vector<String> vecString = new Vector<String>();
while(state != null)
{
vecString.add("[" + state.getMissingTileX() + "," + state.getMissingTileY() + "]");
state = state.getBackPointer();
iPathLength++;
}
while(vecString.size() != 0)
sSolution += (vecString.remove(vecString.size() - 1) + " ");
getLogWindow().insertToLogWindow("Path Length: " + iPathLength);
getLogWindow().insertToLogWindow(sSolution);
}
public void setPuzzleView(PanelPuzzleView panelPuzzleView)
{
this.panelPuzzleView = panelPuzzleView;
}
private PanelPuzzleView getPuzzleView()
{
return panelPuzzleView;
}
public void setLogWindow(PanelOutputWindow panelLogWindow)
{
this.panelLogWindow = panelLogWindow;
}
public PanelOutputWindow getLogWindow()
{
return panelLogWindow;
}
}
| keremsahin1/npuzzle-solver | src/puzzle/PanelSettings.java | Java | gpl-2.0 | 18,196 |
/* Copyright Statement:
*
* This software/firmware and related documentation ("MediaTek Software") are
* protected under relevant copyright laws. The information contained herein
* is confidential and proprietary to MediaTek Inc. and/or its licensors.
* Without the prior written permission of MediaTek inc. and/or its licensors,
* any reproduction, modification, use or disclosure of MediaTek Software,
* and information contained herein, in whole or in part, shall be strictly prohibited.
*/
/* MediaTek Inc. (C) 2010. All rights reserved.
*
* BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
* THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE")
* RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER ON
* AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT.
* NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE
* SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR
* SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH
* THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES
* THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES
* CONTAINED IN MEDIATEK SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK
* SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
* STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND
* CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE,
* AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE,
* OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO
* MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE.
*
* The following software/firmware and/or related documentation ("MediaTek Software")
* have been modified by MediaTek Inc. All revisions are subject to any receiver's
* applicable license agreements with MediaTek Inc.
*/
package com.mediatek.engineermode.wifi;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.mediatek.engineermode.R;
import com.mediatek.xlog.Xlog;
import java.nio.charset.Charset;
public class WiFiEeprom extends WiFiTestActivity implements OnClickListener {
private static final String TAG = "EM/WiFi_EEPROM";
private EditText mEtWordAddr = null;
private EditText mEtWorkValue = null;
private Button mBtnWordRead = null;
private Button mBtnWordWrite = null;
private EditText mEtStringAddr = null;
private EditText mEtStringLength = null;
private EditText mEtStringValue = null;
private Button mBtnStringRead = null;
private Button mBtnStringWrite = null;
private EditText mEtShowWindow = null;
private static final int RADIX_16 = 16;
private static final int DEFAULT_EEPROM_SIZE = 512;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.wifi_eeprom);
mEtWordAddr = (EditText) findViewById(R.id.WiFi_addr_Content);
mEtWorkValue = (EditText) findViewById(R.id.WiFi_value_Content);
mBtnWordRead = (Button) findViewById(R.id.WiFi_Read_Word);
mBtnWordWrite = (Button) findViewById(R.id.WiFi_Write_Word);
mEtStringAddr = (EditText) findViewById(R.id.WiFi_addr_Content_String);
mEtStringLength = (EditText) findViewById(R.id.WiFi_length_Content_String);
mEtStringValue = (EditText) findViewById(R.id.WiFi_value_Content_String);
mBtnStringRead = (Button) findViewById(R.id.WiFi_Read_String);
mBtnStringWrite = (Button) findViewById(R.id.WiFi_Write_String);
mEtShowWindow = (EditText) findViewById(R.id.WiFi_ShowWindow);
mBtnWordRead.setOnClickListener(this);
mBtnWordWrite.setOnClickListener(this);
mBtnStringRead.setOnClickListener(this);
mBtnStringWrite.setOnClickListener(this);
}
@Override
protected void onResume() {
super.onResume();
if (EMWifi.setEEPRomSize(DEFAULT_EEPROM_SIZE) != 0) {
Xlog.d(TAG, "initial setEEPRomSize to 512 failed");
}
}
@Override
public void onClick(View arg0) {
if (!EMWifi.sIsInitialed) {
showDialog(DIALOG_WIFI_ERROR);
return;
}
long u4Addr = 0;
long u4Value = 0;
long u4Length = 0;
CharSequence inputVal;
String text;
if (arg0.getId() == mBtnWordRead.getId()) {
long[] u4Val = new long[1];
try {
u4Addr = Long.parseLong(mEtWordAddr.getText().toString(),
RADIX_16);
} catch (NumberFormatException e) {
Toast.makeText(this, "invalid input value",
Toast.LENGTH_SHORT).show();
return;
}
EMWifi.readEEPRom16(u4Addr, u4Val);
mEtWorkValue.setText(Long.toHexString(u4Val[0]));
} else if (arg0.getId() == mBtnWordWrite.getId()) {
try {
u4Addr = Long.parseLong(mEtWordAddr.getText().toString(),
RADIX_16);
u4Value = Long.parseLong(mEtWorkValue.getText().toString(),
RADIX_16);
} catch (NumberFormatException e) {
Toast.makeText(this, "invalid input value",
Toast.LENGTH_SHORT).show();
return;
}
EMWifi.writeEEPRom16(u4Addr, u4Value);
EMWifi.setEEPromCKSUpdated();
} else if (arg0.getId() == mBtnStringRead.getId()) {
byte[] acSzTmp = new byte[DEFAULT_EEPROM_SIZE];
try {
u4Addr = Long.parseLong(mEtStringAddr.getText().toString(),
RADIX_16);
u4Length = Long.parseLong(mEtStringLength.getText().toString());
} catch (NumberFormatException e) {
Toast.makeText(this, "invalid input value",
Toast.LENGTH_SHORT).show();
return;
}
if (u4Length == 0) {
return;
}
EMWifi.eepromReadByteStr(u4Addr, u4Length, acSzTmp);
text = new String(acSzTmp, 0, (int) u4Length * 2, Charset.defaultCharset());
mEtStringValue.setText(text);
} else if (arg0.getId() == mBtnStringWrite.getId()) {
String szTmp;
inputVal = mEtStringAddr.getText();
if (TextUtils.isEmpty(inputVal)) {
Toast.makeText(this, "invalid input value",
Toast.LENGTH_SHORT).show();
return;
}
try {
u4Addr = Long.parseLong(inputVal.toString(), RADIX_16);
// u4Length = Long.parseLong(mEtStringLength.getText().toString());
} catch (NumberFormatException e) {
Toast.makeText(this, "invalid input value",
Toast.LENGTH_SHORT).show();
return;
}
szTmp = mEtStringValue.getText().toString();
// szTmp = inputVal.toString();
int len = szTmp.length();
if ((len == 0) || (len % 2 == 1)) {
mEtShowWindow.append("Byte string length error:" + len
+ "bytes\n");
return;
}
EMWifi.eepromWriteByteStr(u4Addr, (len / 2), szTmp);
EMWifi.setEEPromCKSUpdated();
} else {
Xlog.v(TAG, "unknown button");
}
}
}
| rex-xxx/mt6572_x201 | mediatek/packages/apps/EngineerMode/src/com/mediatek/engineermode/wifi/WiFiEeprom.java | Java | gpl-2.0 | 7,984 |
/*
* Created on Oct 29, 2003
*
* To change the template for this generated file go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
package javax.microedition.lcdui;
class TickerThread extends Thread {
Display display;
int step; // pos if ticker was active
TickerThread(Display display){
this.display = display;
}
public void run() {
while(true){
try{
Thread.sleep(200);
}
catch(InterruptedException e){
}
Displayable curr = display.current;
if(curr instanceof Screen) {
Screen scr = (Screen) curr;
if(scr.ticker != null){
String t = scr.ticker.getString();
t = t.substring(step % t.length()) + " --- " + t;
step ++;
if(scr.tickerComponent.location == null){
scr.titleComponent.setText(scr.title + " "+t);
scr.titleComponent.repaint();
}
else {
scr.tickerComponent.setText(t);
scr.tickerComponent.setInvisible(false);
scr.tickerComponent.repaint();
}
}
else if(step != 0){
step = 0;
if(scr.tickerComponent.location == null){
scr.titleComponent.setText(scr.title);
scr.titleComponent.repaint();
}
else{
scr.tickerComponent.setInvisible(true);
scr.container.repaint();
}
}
}
}
}
}
| Icenowy/me4se-mobianthon | src/javax/microedition/lcdui/TickerThread.java | Java | gpl-2.0 | 1,307 |
package com.underplex.tickay.strategy;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.underplex.tickay.info.GameInfo;
import com.underplex.tickay.info.PlayInfo;
import com.underplex.tickay.info.PlayerInfoMe;
import com.underplex.tickay.info.SecondTakePlayInfo;
import com.underplex.tickay.info.TicketChoicePlayInfo;
import com.underplex.tickay.info.TicketInfo;
/**
* A fairly basic strategy for Ticket to Ride (America).
* @author Brandon Irvine
*
*/
public class StandardStrategy implements AmericaStrategy{
public PlayInfo chooseRegularPlay(GameInfo game, PlayerInfoMe player,
Set<PlayInfo> plays) {
// what's a basic way to choose plays?
// if I can build toward a route for one of my tickets, I should...
return null;
}
public Set<TicketInfo> discardFirstTickets(GameInfo game,
PlayerInfoMe player, Set<TicketInfo> options) {
return new HashSet<TicketInfo>();
}
public SecondTakePlayInfo chooseSecondTake(GameInfo game,
PlayerInfoMe player, Set<SecondTakePlayInfo> options) {
// TODO Auto-generated method stub
return null;
}
public TicketChoicePlayInfo chooseReturnTickets(GameInfo game,
PlayerInfoMe player, List<TicketChoicePlayInfo> options) {
// TODO Auto-generated method stub
return null;
}
public String getIdentifier(){
return this.getClass().getSimpleName();
}
}
| underplex/tickay | src/main/java/com/underplex/tickay/strategy/StandardStrategy.java | Java | gpl-2.0 | 1,415 |
package core;
import processing.core.PShape;
import processing.core.PVector;
public class Collider {
public Collider(){
}
public boolean circleAndRect(PShape circle, PShape rectangles){
PVector center;
PVector radius;
float x, y;
float dist;
float[] circleParameters;
float[] obstacleParameters;
float[] obstacle_limits = new float[4];
float[] farthest_lines = new float[4];
circleParameters = circle.getParams();
center = new PVector(circleParameters[0], circleParameters[1]);
radius = new PVector(circleParameters[2], circleParameters[3]);
System.out.println("nb rects : " + rectangles.getChildCount());
for(int i=0; i < rectangles.getChildCount(); i++){
obstacleParameters = rectangles.getChild(i).getParams();
//left
obstacle_limits[0] = obstacleParameters[0] - .5f*obstacleParameters[2];
//right
obstacle_limits[1] = obstacleParameters[0] + .5f*obstacleParameters[2];
//upper
obstacle_limits[2] = obstacleParameters[1] - .5f*obstacleParameters[3];
//lower
obstacle_limits[3] = obstacleParameters[1] + .5f*obstacleParameters[3];
// Test Center
if(center.x >= obstacle_limits[0] && center.x <= obstacle_limits[1])
if(center.y >= obstacle_limits[2] && center.y <= obstacle_limits[3])
return true;
// The center is not colliding, test corners
for(int j=0; j<2; j++){
x = obstacle_limits[j];
for(int k=2; k<4; k++){
y = obstacle_limits[k];
dist= (float)Math.sqrt(
Math.pow((x-center.x), 2) +
Math.pow((y-center.y), 2)
);
if(dist <= radius.x)
return true;
}
}
// The corners are not colliding, test limits
//left of Agent
farthest_lines[0] = center.x - radius.x;
//right of Agent
farthest_lines[1] = center.x + radius.x;
//up of Agent
farthest_lines[2] = center.y - radius.y;
//down of Agent
farthest_lines[3] = center.y + radius.y;
for(int j =0; j<4; j++)
{
if (farthest_lines[j] >= obstacle_limits[0] && farthest_lines[j] <= obstacle_limits[1])
if(farthest_lines[j] >= obstacle_limits[2] && farthest_lines[j] <= obstacle_limits[3])
return true;
}
}
return false;
}
public boolean rectAndRectGroup(PShape rect, PShape obstacles){
PVector pos, size;
float[] obstacleParameters;
float[] rectParameters;
rectParameters = rect.getParams();
pos = new PVector(rectParameters[0], rectParameters[1]);
size = new PVector(rectParameters[2], rectParameters[3]);
PVector[] corners = new PVector[4];
for (int i=0;i<4;i++)
corners[i] = new PVector(0, 0);
float[] obstacle_limits = new float[4];
float[] farthest_lines = new float[4];
float x, y;
float dist;
for(int i=0; i < obstacles.getChildCount(); i++){
obstacleParameters = obstacles.getChild(i).getParams();
//left
obstacle_limits[0] = obstacleParameters[0] - .5f*obstacleParameters[2];
//right
obstacle_limits[1] = obstacleParameters[0] + .5f*obstacleParameters[2];
//upper
obstacle_limits[2] = obstacleParameters[1] - .5f*obstacleParameters[3];
//lower
obstacle_limits[3] = obstacleParameters[1] + .5f*obstacleParameters[3];
// Test Center
if(pos.x + size.x/.5f >= obstacle_limits[0] && pos.x + size.x/.5f <= obstacle_limits[1])
if(pos.y + size.y/.5f>= obstacle_limits[2] && pos.y + size.y/.5f<= obstacle_limits[3])
return true;
// // The center is not colliding, test corners
// for(int j=0; j<2; j++){
// x = obstacle_limits[j];
// for(int k=2; k<4; k++){
// y = obstacle_limits[k];
// dist= (float)Math.sqrt(
// Math.pow((x-pos.x), 2) +
// Math.pow((y-pos.y), 2)
// );
// if(dist <= size.x/2.0f)
// return true;
// }
//
// }
// The corners are not colliding, test bounding box
//left of rect
farthest_lines[0] = pos.x;
//right of rect
farthest_lines[1] = pos.x + size.x;
//up of rect
farthest_lines[2] = pos.y;
//down of rect
farthest_lines[3] = pos.y + size.y;
for(int j =0; j<4; j++)
{
if (farthest_lines[j] >= obstacle_limits[0] && farthest_lines[j] <= obstacle_limits[1])
if(farthest_lines[j] >= obstacle_limits[2] && farthest_lines[j] <= obstacle_limits[3])
return true;
}
}
return false;
}
}
| TeamBEAR/OOOI | src/core/Collider.java | Java | gpl-2.0 | 4,443 |
package org.openmrs.module.inventory.web.controller.substore;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.openmrs.Obs;
import org.openmrs.Role;
import org.openmrs.api.context.Context;
import org.openmrs.module.hospitalcore.model.InventoryStore;
import org.openmrs.module.hospitalcore.model.InventoryStoreDrugPatient;
import org.openmrs.module.hospitalcore.model.InventoryStoreDrugPatientDetail;
import org.openmrs.module.hospitalcore.model.InventoryStoreRoleRelation;
import org.openmrs.module.inventory.InventoryService;
import org.openmrs.module.inventory.util.PagingUtil;
import org.openmrs.module.inventory.util.RequestUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
@Controller("ListPatientController")
@RequestMapping("/module/inventory/subStoreListPatient.form")
public class ListPatientController {
@RequestMapping(method = RequestMethod.GET)
public String list( @RequestParam(value="pageSize",required=false) Integer pageSize,
@RequestParam(value="currentPage",required=false) Integer currentPage,
@RequestParam(value="issueName",required=false) String issueName,
@RequestParam(value="fromDate",required=false) String fromDate,
@RequestParam(value="toDate",required=false) String toDate,
@RequestParam(value="receiptId",required=false) Integer receiptId,
Map<String, Object> model, HttpServletRequest request
) {
InventoryService inventoryService = (InventoryService) Context.getService(InventoryService.class);
//InventoryStore store = inventoryService.getStoreByCollectionRole(new ArrayList<Role>(Context.getAuthenticatedUser().getAllRoles()));
List <Role>role=new ArrayList<Role>(Context.getAuthenticatedUser().getAllRoles());
InventoryStoreRoleRelation srl=null;
Role rl = null;
for(Role r: role){
if(inventoryService.getStoreRoleByName(r.toString())!=null){
srl = inventoryService.getStoreRoleByName(r.toString());
rl=r;
}
}
InventoryStore store =null;
if(srl!=null){
store = inventoryService.getStoreById(srl.getStoreid());
}
/*if(store != null && store.getParent() != null && store.getIsDrug() != 1){
return "redirect:/module/inventory/subStoreIssueDrugAccountList.form";
}*/
int total = inventoryService.countStoreDrugPatient(store.getId(), issueName, fromDate, toDate);
String temp = "";
if(issueName != null){
if(StringUtils.isBlank(temp)){
temp = "?issueName="+issueName;
}else{
temp +="&issueName="+issueName;
}
}
if(!StringUtils.isBlank(fromDate)){
if(StringUtils.isBlank(temp)){
temp = "?fromDate="+fromDate;
}else{
temp +="&fromDate="+fromDate;
}
}
if(!StringUtils.isBlank(toDate)){
if(StringUtils.isBlank(temp)){
temp = "?toDate="+toDate;
}else{
temp +="&toDate="+toDate;
}
}
if(receiptId != null){
if(StringUtils.isBlank(temp)){
temp = "?receiptId="+receiptId;
}else{
temp +="&receiptId="+receiptId;
}
}
PagingUtil pagingUtil = new PagingUtil( RequestUtil.getCurrentLink(request)+temp , pageSize, currentPage, total );
List<InventoryStoreDrugPatient> listIssue = inventoryService.listStoreDrugPatient(store.getId(),receiptId, issueName,fromDate, toDate, pagingUtil.getStartPos(), pagingUtil.getPageSize());
for(InventoryStoreDrugPatient in :listIssue)
{
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
String created = sdf.format(in.getCreatedOn());
String changed = sdf.format(new Date());
int value= changed.compareTo(created);
in.setValues(value);
in=inventoryService.saveStoreDrugPatient(in);
}
model.put("issueName", issueName );
model.put("receiptId", receiptId );
model.put("toDate", toDate );
model.put("fromDate", fromDate );
model.put("pagingUtil", pagingUtil );
model.put("listIssue", listIssue );
model.put("store", store );
return "/module/inventory/substore/subStoreListPatient";
}
}
| kenyaehrs/inventory | omod/src/main/java/org/openmrs/module/inventory/web/controller/substore/ListPatientController.java | Java | gpl-2.0 | 4,678 |
/*
* Copyright (C) 2001, 2005 Gérard Milmeister
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of version 2 of the GNU General Public
* License as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*
*/
package org.rubato.math.module;
import org.rubato.math.module.morphism.ModuleMorphism;
import org.rubato.math.module.morphism.TranslationMorphism;
/**
* The abstract base class for <code>proper</code> free modules.
* All free modules that are <code>proper</code> free modules are derived
* from this. <code>Proper</code> means that the module is not of
* dimension 1, because in that case the corresponding ring is used.
* @see org.rubato.math.module.ProperFreeElement
*
* @author Gérard Milmeister
*/
public abstract class ProperFreeModule implements FreeModule {
public ProperFreeModule(int dimension) {
dimension = (dimension < 0)?0:dimension;
this.dimension = dimension;
}
public final ModuleMorphism getIdentityMorphism() {
return ModuleMorphism.getIdentityMorphism(this);
}
public final ModuleMorphism getTranslation(ModuleElement element) {
return TranslationMorphism.make(this, element);
}
public final ModuleMorphism getProjection(int index) {
if (index < 0) { index = 0; }
if (index > getDimension()-1) { index = getDimension()-1; }
return _getProjection(index);
}
public final ModuleMorphism getInjection(int index) {
if (index < 0) { index = 0; }
if (index > getDimension()-1) { index = getDimension()-1; }
return _getInjection(index);
}
public final boolean isRing() {
return false;
}
public int compareTo(Module object) {
if (object instanceof FreeModule) {
FreeModule m = (FreeModule)object;
int c;
if ((c = getRing().compareTo(m.getRing())) != 0) {
return c;
}
else {
return getDimension()-m.getDimension();
}
}
else {
return toString().compareTo(object.toString());
}
}
public final int getDimension() {
return dimension;
}
protected abstract ModuleMorphism _getProjection(int index);
protected abstract ModuleMorphism _getInjection(int index);
private final int dimension;
}
| wells369/Rubato | java/src/org/rubato/math/module/ProperFreeModule.java | Java | gpl-2.0 | 2,921 |
package org.apache.torque.engine.database.model;
/*
* Copyright 2001-2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import org.xml.sax.Attributes;
/**
* A Class for information regarding possible objects representing a table
*
* @author <a href="mailto:[email protected]">John McNally</a>
* @version $Id: Inheritance.java 239624 2005-08-24 12:18:03Z henning $
*/
public class Inheritance
{
private String key;
private String className;
private String ancestor;
private Column parent;
/**
* Imports foreign key from an XML specification
*
* @param attrib the xml attributes
*/
public void loadFromXML (Attributes attrib)
{
setKey(attrib.getValue("key"));
setClassName(attrib.getValue("class"));
setAncestor(attrib.getValue("extends"));
}
/**
* Get the value of key.
* @return value of key.
*/
public String getKey()
{
return key;
}
/**
* Set the value of key.
* @param v Value to assign to key.
*/
public void setKey(String v)
{
this.key = v;
}
/**
* Get the value of parent.
* @return value of parent.
*/
public Column getColumn()
{
return parent;
}
/**
* Set the value of parent.
* @param v Value to assign to parent.
*/
public void setColumn(Column v)
{
this.parent = v;
}
/**
* Get the value of className.
* @return value of className.
*/
public String getClassName()
{
return className;
}
/**
* Set the value of className.
* @param v Value to assign to className.
*/
public void setClassName(String v)
{
this.className = v;
}
/**
* Get the value of ancestor.
* @return value of ancestor.
*/
public String getAncestor()
{
return ancestor;
}
/**
* Set the value of ancestor.
* @param v Value to assign to ancestor.
*/
public void setAncestor(String v)
{
this.ancestor = v;
}
/**
* String representation of the foreign key. This is an xml representation.
*
* @return string representation in xml
*/
public String toString()
{
StringBuffer result = new StringBuffer();
result.append(" <inheritance key=\"")
.append(key)
.append("\" class=\"")
.append(className)
.append('\"');
if (ancestor != null)
{
result.append(" extends=\"")
.append(ancestor)
.append('\"');
}
result.append("/>");
return result.toString();
}
}
| donatellosantoro/freESBee | freesbeeSLA/lib/torque-gen-3.2/src/torque-gen-3.2/src/java/org/apache/torque/engine/database/model/Inheritance.java | Java | gpl-2.0 | 3,285 |
package org.minicastle.crypto.params;
public class DHKeyParameters
extends AsymmetricKeyParameter
{
private DHParameters params;
protected DHKeyParameters(
boolean isPrivate,
DHParameters params)
{
super(isPrivate);
this.params = params;
}
public DHParameters getParameters()
{
return params;
}
public boolean equals(
Object obj)
{
if (!(obj instanceof DHKeyParameters))
{
return false;
}
DHKeyParameters dhKey = (DHKeyParameters)obj;
return (params != null && !params.equals(dhKey.getParameters()));
}
}
| AcademicTorrents/AcademicTorrents-Downloader | frostwire-merge/org/minicastle/crypto/params/DHKeyParameters.java | Java | gpl-2.0 | 678 |
package edu.stanford.nlp.util;
import java.util.*;
/**
* PriorityQueue with explicit double priority values. Larger doubles are higher priorities. BinaryHeap-backed.
*
* @author Dan Klein
* @author Christopher Manning
* For each entry, uses ~ 24 (entry) + 16? (Map.Entry) + 4 (List entry) = 44 bytes?
*/
public class BinaryHeapPriorityQueue<E> extends AbstractSet<E> implements PriorityQueue<E>, Iterator<E> {
/**
* An <code>Entry</code> stores an object in the queue along with
* its current location (array position) and priority.
* uses ~ 8 (self) + 4 (key ptr) + 4 (index) + 8 (priority) = 24 bytes?
*/
private static final class Entry<E> {
public E key;
public int index;
public double priority;
@Override
public String toString() {
return key + " at " + index + " (" + priority + ")";
}
}
public boolean hasNext() {
return size() > 0;
}
public E next() {
return removeFirst();
}
public void remove() {
throw new UnsupportedOperationException();
}
/**
* <code>indexToEntry</code> maps linear array locations (not
* priorities) to heap entries.
*/
private List<Entry<E>> indexToEntry;
/**
* <code>keyToEntry</code> maps heap objects to their heap
* entries.
*/
private Map<Object,Entry<E>> keyToEntry;
private Entry<E> parent(Entry<E> entry) {
int index = entry.index;
return (index > 0 ? getEntry((index - 1) / 2) : null);
}
private Entry<E> leftChild(Entry<E> entry) {
int leftIndex = entry.index * 2 + 1;
return (leftIndex < size() ? getEntry(leftIndex) : null);
}
private Entry<E> rightChild(Entry<E> entry) {
int index = entry.index;
int rightIndex = index * 2 + 2;
return (rightIndex < size() ? getEntry(rightIndex) : null);
}
private int compare(Entry<E> entryA, Entry<E> entryB) {
return compare(entryA.priority, entryB.priority);
}
private static int compare(double a, double b) {
double diff = a - b;
if (diff > 0.0) {
return 1;
}
if (diff < 0.0) {
return -1;
}
return 0;
}
/**
* Structural swap of two entries.
*
*/
private void swap(Entry<E> entryA, Entry<E> entryB) {
int indexA = entryA.index;
int indexB = entryB.index;
entryA.index = indexB;
entryB.index = indexA;
indexToEntry.set(indexA, entryB);
indexToEntry.set(indexB, entryA);
}
/**
* Remove the last element of the heap (last in the index array).
*/
private void removeLastEntry() {
Entry<E> entry = indexToEntry.remove(size() - 1);
keyToEntry.remove(entry.key);
}
/**
* Get the entry by key (null if none).
*/
private Entry<E> getEntry(E key) {
return keyToEntry.get(key);
}
/**
* Get entry by index, exception if none.
*/
private Entry<E> getEntry(int index) {
Entry<E> entry = indexToEntry.get(index);
return entry;
}
private Entry<E> makeEntry(E key) {
Entry<E> entry = new Entry<E>();
entry.index = size();
entry.key = key;
entry.priority = Double.NEGATIVE_INFINITY;
indexToEntry.add(entry);
keyToEntry.put(key, entry);
return entry;
}
/**
* iterative heapify up: move item o at index up until correctly placed
*/
private void heapifyUp(Entry<E> entry) {
while (true) {
if (entry.index == 0) {
break;
}
Entry<E> parentEntry = parent(entry);
if (compare(entry, parentEntry) <= 0) {
break;
}
swap(entry, parentEntry);
}
}
/**
* On the assumption that
* leftChild(entry) and rightChild(entry) satisfy the heap property,
* make sure that the heap at entry satisfies this property by possibly
* percolating the element o downwards. I've replaced the obvious
* recursive formulation with an iterative one to gain (marginal) speed
*/
private void heapifyDown(Entry<E> entry) {
Entry<E> currentEntry = entry;
Entry<E> bestEntry; // initialized below
do {
bestEntry = currentEntry;
Entry<E> leftEntry = leftChild(currentEntry);
if (leftEntry != null) {
if (compare(bestEntry, leftEntry) < 0) {
bestEntry = leftEntry;
}
}
Entry<E> rightEntry = rightChild(currentEntry);
if (rightEntry != null) {
if (compare(bestEntry, rightEntry) < 0) {
bestEntry = rightEntry;
}
}
if (bestEntry != currentEntry) {
// Swap min and current
swap(bestEntry, currentEntry);
// at start of next loop, we set currentIndex to largestIndex
// this indexation now holds current, so it is unchanged
}
} while (bestEntry != currentEntry);
// System.err.println("Done with heapify down");
// verify();
}
private void heapify(Entry<E> entry) {
heapifyUp(entry);
heapifyDown(entry);
}
/**
* Finds the object with the highest priority, removes it,
* and returns it.
*
* @return the object with highest priority
*/
public E removeFirst() {
E first = getFirst();
remove(first);
return first;
}
/**
* Finds the object with the highest priority and returns it, without
* modifying the queue.
*
* @return the object with minimum key
*/
public E getFirst() {
if (isEmpty()) {
throw new NoSuchElementException();
}
return getEntry(0).key;
}
/**
* Gets the priority of the highest-priority element of the queue.
*/
public double getPriority() {
if (isEmpty()) {
throw new NoSuchElementException();
}
return getEntry(0).priority;
}
/**
* Searches for the object in the queue and returns it. May be useful if
* you can create a new object that is .equals() to an object in the queue
* but is not actually identical, or if you want to modify an object that is
* in the queue.
* @return null if the object is not in the queue, otherwise returns the
* object.
*/
public E getObject(E key) {
if ( ! contains(key)) return null;
Entry<E> e = getEntry(key);
return e.key;
}
/**
* Get the priority of a key -- if the key is not in the queue, Double.NEGATIVE_INFINITY is returned.
*
*/
public double getPriority(E key) {
Entry<E> entry = getEntry(key);
if (entry == null) {
return Double.NEGATIVE_INFINITY;
}
return entry.priority;
}
/**
* Adds an object to the queue with the minimum priority
* (Double.NEGATIVE_INFINITY). If the object is already in the queue
* with worse priority, this does nothing. If the object is
* already present, with better priority, it will NOT cause an
* a decreasePriority.
*
* @param key an <code>Object</code> value
* @return whether the key was present before
*/
@Override
public boolean add(E key) {
if (contains(key)) {
return false;
}
makeEntry(key);
return true;
}
/**
* Convenience method for if you want to pretend relaxPriority doesn't exist, or if you really want add's return conditions.
*/
public boolean add(E key, double priority) {
// System.err.println("Adding " + key + " with priority " + priority);
if (add(key)) {
relaxPriority(key, priority);
return true;
}
return false;
}
@SuppressWarnings("unchecked")
@Override
public boolean remove(Object key) {
E eKey = (E) key;
Entry<E> entry = getEntry(eKey);
if (entry == null) {
return false;
}
removeEntry(entry);
return true;
}
private void removeEntry(Entry<E> entry) {
Entry<E> lastEntry = getLastEntry();
if (entry != lastEntry) {
swap(entry, lastEntry);
removeLastEntry();
heapify(lastEntry);
} else {
removeLastEntry();
}
}
private Entry<E> getLastEntry() {
return getEntry(size() - 1);
}
/**
* Promotes a key in the queue, adding it if it wasn't there already. If the specified priority is worse than the current priority, nothing happens. Faster than add if you don't care about whether the key is new.
*
* @param key an <code>Object</code> value
* @return whether the priority actually improved.
*/
public boolean relaxPriority(E key, double priority) {
Entry<E> entry = getEntry(key);
if (entry == null) {
entry = makeEntry(key);
}
if (compare(priority, entry.priority) <= 0) {
return false;
}
entry.priority = priority;
heapifyUp(entry);
return true;
}
/**
* Demotes a key in the queue, adding it if it wasn't there already. If the specified priority is better than the current priority, nothing happens. If you decrease the priority on a non-present key, it will get added, but at it's old implicit priority of Double.NEGATIVE_INFINITY.
*
* @param key an <code>Object</code> value
* @return whether the priority actually improved.
*/
public boolean decreasePriority(E key, double priority) {
Entry<E> entry = getEntry(key);
if (entry == null) {
entry = makeEntry(key);
}
if (compare(priority, entry.priority) >= 0) {
return false;
}
entry.priority = priority;
heapifyDown(entry);
return true;
}
/**
* Changes a priority, either up or down, adding the key it if it wasn't there already.
*
* @param key an <code>Object</code> value
* @return whether the priority actually changed.
*/
public boolean changePriority(E key, double priority) {
Entry<E> entry = getEntry(key);
if (entry == null) {
entry = makeEntry(key);
}
if (compare(priority, entry.priority) == 0) {
return false;
}
entry.priority = priority;
heapify(entry);
return true;
}
/**
* Checks if the queue is empty.
*
* @return a <code>boolean</code> value
*/
@Override
public boolean isEmpty() {
return indexToEntry.isEmpty();
}
/**
* Get the number of elements in the queue.
*
* @return queue size
*/
@Override
public int size() {
return indexToEntry.size();
}
/**
* Returns whether the queue contains the given key.
*/
@Override
public boolean contains(Object key) {
return keyToEntry.containsKey(key);
}
public List<E> toSortedList() {
List<E> sortedList = new ArrayList<E>(size());
BinaryHeapPriorityQueue<E> queue = this.deepCopy();
while (!queue.isEmpty()) {
sortedList.add(queue.removeFirst());
}
return sortedList;
}
public BinaryHeapPriorityQueue<E> deepCopy(MapFactory<Object, Entry<E>> mapFactory) {
BinaryHeapPriorityQueue<E> queue =
new BinaryHeapPriorityQueue<E>(mapFactory);
for (Entry<E> entry : keyToEntry.values()) {
queue.relaxPriority(entry.key, entry.priority);
}
return queue;
}
public BinaryHeapPriorityQueue<E> deepCopy() {
return deepCopy(MapFactory.<Object,Entry<E>>hashMapFactory());
}
@Override
public Iterator<E> iterator() {
return Collections.unmodifiableCollection(toSortedList()).iterator();
}
/**
* Clears the queue.
*/
@Override
public void clear() {
indexToEntry.clear();
keyToEntry.clear();
}
// private void verify() {
// for (int i = 0; i < indexToEntry.size(); i++) {
// if (i != 0) {
// // check ordering
// if (compare(getEntry(i), parent(getEntry(i))) < 0) {
// System.err.println("Error in the ordering of the heap! ("+i+")");
// System.exit(0);
// }
// }
// // check placement
// if (i != ((Entry)indexToEntry.get(i)).index)
// System.err.println("Error in placement in the heap!");
// }
// }
@Override
public String toString() {
return toString(0);
}
/** {@inheritDoc} */
public String toString(int maxKeysToPrint) {
if (maxKeysToPrint <= 0) maxKeysToPrint = Integer.MAX_VALUE;
List<E> sortedKeys = toSortedList();
StringBuilder sb = new StringBuilder("[");
for (int i = 0; i < maxKeysToPrint && i < sortedKeys.size(); i++) {
E key = sortedKeys.get(i);
sb.append(key).append("=").append(getPriority(key));
if (i < maxKeysToPrint - 1 && i < sortedKeys.size() - 1) {
sb.append(", ");
}
}
sb.append("]");
return sb.toString();
}
public String toVerticalString() {
List<E> sortedKeys = toSortedList();
StringBuilder sb = new StringBuilder();
for (Iterator<E> keyI = sortedKeys.iterator(); keyI.hasNext();) {
E key = keyI.next();
sb.append(key);
sb.append("\t");
sb.append(getPriority(key));
if (keyI.hasNext()) {
sb.append("\n");
}
}
return sb.toString();
}
public BinaryHeapPriorityQueue() {
this(MapFactory.<Object,Entry<E>>hashMapFactory());
}
public BinaryHeapPriorityQueue(int initCapacity) {
this(MapFactory.<Object,Entry<E>>hashMapFactory(),initCapacity);
}
public BinaryHeapPriorityQueue(MapFactory<Object, Entry<E>> mapFactory) {
indexToEntry = new ArrayList<Entry<E>>();
keyToEntry = mapFactory.newMap();
}
public BinaryHeapPriorityQueue(MapFactory<Object, Entry<E>> mapFactory, int initCapacity) {
indexToEntry = new ArrayList<Entry<E>>(initCapacity);
keyToEntry = mapFactory.newMap(initCapacity);
}
public static void main(String[] args) {
BinaryHeapPriorityQueue<String> queue =
new BinaryHeapPriorityQueue<String>();
queue.add("a", 1.0);
System.out.println("Added a:1 " + queue);
queue.add("b", 2.0);
System.out.println("Added b:2 " + queue);
queue.add("c", 1.5);
System.out.println("Added c:1.5 " + queue);
queue.relaxPriority("a", 3.0);
System.out.println("Increased a to 3 " + queue);
queue.decreasePriority("b", 0.0);
System.out.println("Decreased b to 0 " + queue);
System.out.println("removeFirst()=" + queue.removeFirst());
System.out.println("queue=" + queue);
System.out.println("removeFirst()=" + queue.removeFirst());
System.out.println("queue=" + queue);
System.out.println("removeFirst()=" + queue.removeFirst());
System.out.println("queue=" + queue);
}
}
| PeterisP/LVTagger | src/main/java/edu/stanford/nlp/util/BinaryHeapPriorityQueue.java | Java | gpl-2.0 | 14,594 |
package com.school.www.office.bo;
import java.io.Serializable;
import java.util.List;
/**
* Created by lxq on 16/3/13.
*/
public class BatchStudent implements Serializable {
String studentId;
List<BatchCourse> newCourseList;
List<BatchCourse> deletedCourseList;
List<BatchCourse> updatedCourseList;
public class BatchCourse {
Integer courseId;
String teacherId;
String time;
public Integer getCourseId() {
return courseId;
}
public void setCourseId(Integer courseId) {
this.courseId = courseId;
}
public String getTeacherId() {
return teacherId;
}
public void setTeacherId(String teacherId) {
this.teacherId = teacherId;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
}
public String getStudentId() {
return studentId;
}
public void setStudentId(String studentId) {
this.studentId = studentId;
}
public List<BatchCourse> getNewCourseList() {
return newCourseList;
}
public void setNewCourseList(List<BatchCourse> newCourseList) {
this.newCourseList = newCourseList;
}
public List<BatchCourse> getDeletedCourseList() {
return deletedCourseList;
}
public void setDeletedCourseList(List<BatchCourse> deletedCourseList) {
this.deletedCourseList = deletedCourseList;
}
public List<BatchCourse> getUpdatedCourseList() {
return updatedCourseList;
}
public void setUpdatedCourseList(List<BatchCourse> updatedCourseList) {
this.updatedCourseList = updatedCourseList;
}
}
| lxqfirst/mySchool | src/main/java/com/school/www/office/bo/BatchStudent.java | Java | gpl-2.0 | 1,776 |
package processors;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Table;
import com.google.common.collect.TreeBasedTable;
import database.TransformationServiceReversible;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
public class ReverseJsonDecodeMapManyColsAndKeysOut extends TransformationServiceReversible {
public ReverseJsonDecodeMapManyColsAndKeysOut()
{
colsIn = Integer.MAX_VALUE;
colsOut = 1;
rowsIn = Integer.MAX_VALUE;
rowsOut = Integer.MAX_VALUE;
}
public Table<Integer, Integer, String> doWork(Table<Integer, Integer, String> input)
{
ObjectMapper mapper = new ObjectMapper();
mapper.enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS);
mapper.enable(DeserializationFeature.USE_BIG_INTEGER_FOR_INTS);
Table<Integer, Integer, String> outTable = TreeBasedTable.create();
for( int row=0; row < input.rowKeySet().size(); row++ ){
Map<String,Object> outMap = new TreeMap(); //Sort alphabetically by key.
for( int col=0; col < input.columnKeySet().size(); col+=2 ){
String key=input.get(row, col);
if( key != null ){
try {
Object obj = mapper.readValue(input.get(row, col + 1), Object.class);
outMap.put(key, obj);
}
catch( IOException e ){
}
}
}
try {
outTable.put(row, 0, mapper.writeValueAsString(outMap));
}
catch( IOException e ){
}
}
return outTable;
}
@Override
public TransformationServiceReversible getReverseTransformer() {
return new JsonDecodeMapManyColsAndKeysOut();
}
}
| Crashthatch/PatternRecogniserPublic | src/main/java/processors/ReverseJsonDecodeMapManyColsAndKeysOut.java | Java | gpl-2.0 | 1,674 |
/*
* Copyright (c) 2012 Patrick Meyer
*
* 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.itemanalysis.jmetrik.scoring;
import com.itemanalysis.jmetrik.selector.MultipleSelectionPanel;
import com.itemanalysis.jmetrik.sql.DataTableName;
import com.itemanalysis.jmetrik.sql.DatabaseName;
import com.itemanalysis.jmetrik.swing.DataTable;
import com.itemanalysis.psychometrics.data.VariableAttributes;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.TreeSet;
public class ScoringToolDialog extends JDialog{
private JButton okButton;
private JButton cancelButton;
private JScrollPane scoringTableScrollPane;
private DataTable scoringTable;
private JTextArea syntaxTextArea;
private JScrollPane textScrollPane;
private OptionScoreTableModel optionScoreTableModel = null;
private ArrayList<OptionScoreKey> keys = null;
private ScoringCommand command = null;
private boolean canRun = false;
private DatabaseName dbName = null;
private DataTableName tableName = null;
private ArrayList<VariableAttributes> variables = null;
private TreeSet<VariableAttributes> scoredVariable = null;
private MultipleSelectionPanel selectionPanel = null;
/**
* If true, variables moved from unselectedVariableList to selectedList.
* If false, variables moved from selectedList to unselectedVariableList.
*/
private boolean selectVariables = true;
/** Creates new form ScoringToolDialog */
public ScoringToolDialog(JFrame parent, DatabaseName dbName, DataTableName tableName, ArrayList<VariableAttributes> variables) {
super(parent, "Advanced Item Scoring", true);
this.dbName = dbName;
this.tableName = tableName;
this.variables = variables;
scoredVariable = new TreeSet<VariableAttributes>();
keys = new ArrayList<OptionScoreKey>();
initComponents();
setLocationRelativeTo(parent);
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
scoringTableScrollPane = new JScrollPane();
scoringTable = new DataTable();
okButton = new JButton("OK");
okButton.addActionListener(new OkActionListener());
cancelButton = new JButton("Cancel");
cancelButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setVisible(false);
}
});
textScrollPane = new JScrollPane();
syntaxTextArea = new JTextArea();
optionScoreTableModel = new OptionScoreTableModel();
selectionPanel = new MultipleSelectionPanel();
// VariableType filterType = new VariableType(VariableType.NO_FILTER, VariableType.NO_FILTER);
// selectionPanel.addUnselectedFilterType(filterType);
// selectionPanel.addSelectedFilterType(filterType);
selectionPanel.setVariables(variables);
selectionPanel.setUnselectedListCellRenderer(new ScoredItemListCellRenderer());
selectionPanel.getButton1().setText("Submit");
selectionPanel.getButton1().addActionListener(new SubmitButtonActionListener());
selectionPanel.getButton2().setText("Reset");
selectionPanel.getButton2().addActionListener(new ClearActionListener());
selectionPanel.getButton3().setVisible(false);
selectionPanel.getButton4().setVisible(false);
setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
scoringTable.setModel(optionScoreTableModel);
scoringTableScrollPane.setViewportView(scoringTable);
textScrollPane.setBorder(BorderFactory.createTitledBorder("Scoring Syntax"));
syntaxTextArea.setColumns(20);
syntaxTextArea.setEditable(false);
syntaxTextArea.setRows(5);
textScrollPane.setViewportView(syntaxTextArea);
GroupLayout layout = new GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(254, 254, 254)
.addComponent(okButton, GroupLayout.DEFAULT_SIZE, 69, Short.MAX_VALUE)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(cancelButton, GroupLayout.DEFAULT_SIZE, 69, Short.MAX_VALUE)
.addGap(251, 251, 251))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(scoringTableScrollPane, GroupLayout.PREFERRED_SIZE, 229, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(selectionPanel, GroupLayout.DEFAULT_SIZE, 414, Short.MAX_VALUE)
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(textScrollPane, GroupLayout.DEFAULT_SIZE, 603, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(selectionPanel, GroupLayout.DEFAULT_SIZE, 272, Short.MAX_VALUE)
.addComponent(scoringTableScrollPane, 0, 0, Short.MAX_VALUE))
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(textScrollPane, GroupLayout.PREFERRED_SIZE, 110, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(cancelButton)
.addComponent(okButton))
.addContainerGap())
);
pack();
}// </editor-fold>
public boolean canRun(){
return canRun;
}
public ScoringCommand getCommand(){
return command;
}
private void resetLists(){
selectionPanel.reset();
selectionPanel.repaintLists();
}
class OkActionListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
command = new ScoringCommand();
command.getPairedOptionList("data").addValue("db", dbName.getName());
command.getPairedOptionList("data").addValue("table", tableName.getTableName());
int size = keys.size();
if(size==0){
JOptionPane.showMessageDialog(ScoringToolDialog.this,
"You must provide scoring for one or more variables.",
"No Scoring Provided",
JOptionPane.ERROR_MESSAGE);
}else{
command.getFreeOption("keys").add(keys.size());
for(OptionScoreKey k : keys){
command.getPairedOptionList(k.getKeyName()).addValue("options", k.getOptions());
command.getPairedOptionList(k.getKeyName()).addValue("scores", k.getScores());
command.getPairedOptionList(k.getKeyName()).addValue("variables", k.getVariableNames());
if(!k.getOmitCode().trim().equals("")){
command.getPairedOptionList(k.getKeyName()).addValue("omit", k.getOmitCode());
}
if(!k.getNotReachedCode().trim().equals("")){
command.getPairedOptionList(k.getKeyName()).addValue("nr", k.getNotReachedCode());
}
}
canRun = true;
setVisible(false);
}
}
}
class SubmitButtonActionListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
VariableAttributes[] varAttr = selectionPanel.getSelectedVariables();
int size = varAttr.length;
if(size==0){
JOptionPane.showMessageDialog(ScoringToolDialog.this, "You must select one or more variables. \n " +
"Select variables from the list.", "No Variables Selected", JOptionPane.ERROR_MESSAGE);
}else{
String varString = "variables = (";
ArrayList<String> varNames = new ArrayList<String>();
for(int i=0;i<size;i++){
scoredVariable.add(varAttr[i]);
varNames.add(varAttr[i].getName().toString());
varString += varAttr[i].getName().toString() + ", ";
}
varString = varString.trim();
varString = varString.substring(0, varString.length()-1);
// OptionScoreKey scoreKey = new OptionScoreKey("key" + (keys.size()+1),
// optionScoreTableModel.getOptionString(),
// optionScoreTableModel.getScoreString(),
// varNames);
OptionScoreKey scoreKey = new OptionScoreKey("key" + (keys.size()+1), optionScoreTableModel, varNames);
keys.add(scoreKey);
String omit = scoreKey.getOmitCode().trim();
String notReached = scoreKey.getNotReachedCode().trim();
String scoringText = "options = " + scoreKey.getOptions();
scoringText += ", scores = " + scoreKey.getScores();
if(!omit.equals("")) scoringText += ", omit = " + omit;
if(!notReached.equals("")) scoringText += ", nr = " + notReached;
// scoringText += ", scores = " + scoreKey.getScores();
scoringText += ", " + varString + ");";
String syntax = syntaxTextArea.getText();
syntaxTextArea.setText(syntax + scoringText + "\n");
optionScoreTableModel.clearAll();
resetLists();
}
}
}
class ClearActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
syntaxTextArea.setText("");
keys.clear();
optionScoreTableModel.clearAll();
scoredVariable.clear();
resetLists();
}
}
class ScoredItemListCellRenderer extends DefaultListCellRenderer{
public ScoredItemListCellRenderer(){
}
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus){
Font labelFont = UIManager.getFont("Label.font");
JLabel label = (JLabel)super.getListCellRendererComponent(list,value,index,isSelected,cellHasFocus);
VariableAttributes v = (VariableAttributes)value;
if(scoredVariable.contains(v)){
label.setFont(labelFont.deriveFont(Font.BOLD)) ;
}else{
label.setFont(labelFont.deriveFont(Font.PLAIN));
}
return this;
}
}
}
| meyerjp3/jmetrik | src/main/java/com/itemanalysis/jmetrik/scoring/ScoringToolDialog.java | Java | gpl-2.0 | 12,665 |
/**
This package is part of the application VIF.
Copyright (C) 2011-2015, Benno Luthiger
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 org.hip.vif.core.internal.service;
import org.hip.vif.core.ApplicationConstants;
import org.hip.vif.core.service.PreferencesHandler;
import org.osgi.service.component.ComponentContext;
import org.osgi.service.prefs.PreferencesService;
/** The client class for service component binding the <code>PreferencesService</code>.
*
* @author Luthiger Created: 08.01.2012 */
public class PreferencesComponent {
/** Accessing the <code>PreferencesService</code> using the lookup strategy.
*
* @param inContext {@link ComponentContext} */
public void activate(final ComponentContext inContext) {
final PreferencesService lPreferences = (PreferencesService) inContext
.locateService(ApplicationConstants.PREFERENCES_SERVICE_NAME);
LoggingHelper.setLoggingEnvironment(lPreferences);
PreferencesHandler.INSTANCE.setPreferences(lPreferences);
}
}
| aktion-hip/vif | org.hip.vif.core/src/org/hip/vif/core/internal/service/PreferencesComponent.java | Java | gpl-2.0 | 1,736 |
/**
* OWASP Benchmark Project v1.1
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>.
*
* The Benchmark is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation, version 2.
*
* The Benchmark is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details
*
* @author Dave Wichers <a href="https://www.aspectsecurity.com">Aspect Security</a>
* @created 2015
*/
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/BenchmarkTest08758")
public class BenchmarkTest08758 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String param = "";
java.util.Enumeration<String> headerNames = request.getHeaderNames();
if (headerNames.hasMoreElements()) {
param = headerNames.nextElement(); // just grab first element
}
String bar = new Test().doSomething(param);
boolean randNumber = new java.util.Random().nextBoolean();
response.getWriter().println("Weak Randomness Test java.util.Random.nextBoolean() executed");
} // end doPost
private class Test {
public String doSomething(String param) throws ServletException, IOException {
java.util.List<String> valuesList = new java.util.ArrayList<String>( );
valuesList.add("safe");
valuesList.add( param );
valuesList.add( "moresafe" );
valuesList.remove(0); // remove the 1st safe value
String bar = valuesList.get(1); // get the last 'safe' value
return bar;
}
} // end innerclass Test
} // end DataflowThruInnerClass
| iammyr/Benchmark | src/main/java/org/owasp/benchmark/testcode/BenchmarkTest08758.java | Java | gpl-2.0 | 2,431 |
package tracker.diagram.edit.commands;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.gmf.runtime.common.core.command.CommandResult;
import org.eclipse.gmf.runtime.emf.type.core.commands.EditElementCommand;
import org.eclipse.gmf.runtime.emf.type.core.requests.CreateRelationshipRequest;
import tracker.Chronos;
import tracker.Clerk;
import tracker.diagram.edit.policies.TrackerBaseItemSemanticEditPolicy;
/**
* @generated
*/
public class ChronosClerkCreateCommand extends EditElementCommand {
/**
* @generated
*/
private final EObject source;
/**
* @generated
*/
private final EObject target;
/**
* @generated
*/
public ChronosClerkCreateCommand(CreateRelationshipRequest request, EObject source, EObject target) {
super(request.getLabel(), null, request);
this.source = source;
this.target = target;
}
/**
* @generated
*/
public boolean canExecute() {
if (source == null && target == null) {
return false;
}
if (source != null && false == source instanceof Chronos) {
return false;
}
if (target != null && false == target instanceof Clerk) {
return false;
}
if (getSource() == null) {
return true; // link creation is in progress; source is not defined yet
}
// target may be null here but it's possible to check constraint
return TrackerBaseItemSemanticEditPolicy.getLinkConstraints().canCreateChronosClerk_4001(getSource(),
getTarget());
}
/**
* @generated
*/
protected CommandResult doExecuteWithResult(IProgressMonitor monitor, IAdaptable info) throws ExecutionException {
if (!canExecute()) {
throw new ExecutionException("Invalid arguments in create link command"); //$NON-NLS-1$
}
if (getSource() != null && getTarget() != null) {
getSource().setClerk(getTarget());
}
return CommandResult.newOKCommandResult();
}
/**
* @generated
*/
protected void setElementToEdit(EObject element) {
throw new UnsupportedOperationException();
}
/**
* @generated
*/
protected Chronos getSource() {
return (Chronos) source;
}
/**
* @generated
*/
protected Clerk getTarget() {
return (Clerk) target;
}
}
| CarlAtComputer/tracker | src/java_version/tracker_model/tracker_model.diagram/src/tracker/diagram/edit/commands/ChronosClerkCreateCommand.java | Java | gpl-2.0 | 2,268 |
package in.shabhushan.cp_trials.stack;
import org.junit.Test;
import static in.shabhushan.cp_trials.stack.PolishNotation.getReversePolishNotation;
import static org.junit.Assert.assertEquals;
public class PolishNotationTest {
@Test
public void testGetReversePolishNotation() {
assertEquals("54+33*+", getReversePolishNotation("5+4+(3*3)"));
assertEquals("ABC*DEF^/G*-H*+", getReversePolishNotation("A+(B*C-(D/E^F)*G)*H"));
}
}
| Shashi-Bhushan/General | cp-trials/src/test/java/in/shabhushan/cp_trials/stack/PolishNotationTest.java | Java | gpl-2.0 | 445 |
/*
* 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.cloudstack.storage.image.db;
import java.util.List;
import java.util.Map;
import javax.naming.ConfigurationException;
import org.springframework.stereotype.Component;
import org.apache.cloudstack.engine.subsystem.api.storage.ZoneScope;
import org.apache.cloudstack.storage.datastore.db.ImageStoreDao;
import org.apache.cloudstack.storage.datastore.db.ImageStoreVO;
import com.cloud.storage.DataStoreRole;
import com.cloud.storage.ScopeType;
import com.cloud.utils.db.GenericDaoBase;
import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria;
@Component
public class ImageStoreDaoImpl extends GenericDaoBase<ImageStoreVO, Long> implements ImageStoreDao {
private SearchBuilder<ImageStoreVO> nameSearch;
private SearchBuilder<ImageStoreVO> providerSearch;
private SearchBuilder<ImageStoreVO> regionSearch;
@Override
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
super.configure(name, params);
nameSearch = createSearchBuilder();
nameSearch.and("name", nameSearch.entity().getName(), SearchCriteria.Op.EQ);
nameSearch.and("role", nameSearch.entity().getRole(), SearchCriteria.Op.EQ);
nameSearch.done();
providerSearch = createSearchBuilder();
providerSearch.and("providerName", providerSearch.entity().getProviderName(), SearchCriteria.Op.EQ);
providerSearch.and("role", providerSearch.entity().getRole(), SearchCriteria.Op.EQ);
providerSearch.done();
regionSearch = createSearchBuilder();
regionSearch.and("scope", regionSearch.entity().getScope(), SearchCriteria.Op.EQ);
regionSearch.and("role", regionSearch.entity().getRole(), SearchCriteria.Op.EQ);
regionSearch.done();
return true;
}
@Override
public ImageStoreVO findByName(String name) {
SearchCriteria<ImageStoreVO> sc = nameSearch.create();
sc.setParameters("name", name);
return findOneBy(sc);
}
@Override
public List<ImageStoreVO> findByProvider(String provider) {
SearchCriteria<ImageStoreVO> sc = providerSearch.create();
sc.setParameters("providerName", provider);
sc.setParameters("role", DataStoreRole.Image);
return listBy(sc);
}
@Override
public List<ImageStoreVO> findByScope(ZoneScope scope) {
SearchCriteria<ImageStoreVO> sc = createSearchCriteria();
sc.addAnd("role", SearchCriteria.Op.EQ, DataStoreRole.Image);
if (scope.getScopeId() != null) {
SearchCriteria<ImageStoreVO> scc = createSearchCriteria();
scc.addOr("scope", SearchCriteria.Op.EQ, ScopeType.REGION);
scc.addOr("dcId", SearchCriteria.Op.EQ, scope.getScopeId());
sc.addAnd("scope", SearchCriteria.Op.SC, scc);
}
// we should return all image stores if cross-zone scope is passed
// (scopeId = null)
return listBy(sc);
}
@Override
public List<ImageStoreVO> findRegionImageStores() {
SearchCriteria<ImageStoreVO> sc = regionSearch.create();
sc.setParameters("scope", ScopeType.REGION);
sc.setParameters("role", DataStoreRole.Image);
return listBy(sc);
}
@Override
public List<ImageStoreVO> findImageCacheByScope(ZoneScope scope) {
SearchCriteria<ImageStoreVO> sc = createSearchCriteria();
sc.addAnd("role", SearchCriteria.Op.EQ, DataStoreRole.ImageCache);
if (scope.getScopeId() != null) {
sc.addAnd("scope", SearchCriteria.Op.EQ, ScopeType.ZONE);
sc.addAnd("dcId", SearchCriteria.Op.EQ, scope.getScopeId());
}
return listBy(sc);
}
@Override
public List<ImageStoreVO> listImageStores() {
SearchCriteria<ImageStoreVO> sc = createSearchCriteria();
sc.addAnd("role", SearchCriteria.Op.EQ, DataStoreRole.Image);
return listBy(sc);
}
@Override
public List<ImageStoreVO> listImageCacheStores() {
SearchCriteria<ImageStoreVO> sc = createSearchCriteria();
sc.addAnd("role", SearchCriteria.Op.EQ, DataStoreRole.ImageCache);
return listBy(sc);
}
}
| ikoula/cloudstack | engine/storage/src/org/apache/cloudstack/storage/image/db/ImageStoreDaoImpl.java | Java | gpl-2.0 | 5,015 |
/*
* This file is part of DrFTPD, Distributed FTP Daemon.
*
* DrFTPD 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.
*
* DrFTPD 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 DrFTPD; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package net.sf.drftpd.master.command.plugins;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import net.sf.drftpd.master.BaseFtpConnection;
import net.sf.drftpd.master.FtpRequest;
import net.sf.drftpd.master.command.CommandManager;
import net.sf.drftpd.master.command.CommandManagerFactory;
import org.apache.log4j.Logger;
import org.drftpd.commands.CommandHandler;
import org.drftpd.commands.CommandHandlerFactory;
import org.drftpd.commands.Reply;
import org.drftpd.remotefile.LinkedRemoteFileInterface;
/**
* @author mog
* @version $Id: Search.java 1765 2007-08-04 04:14:28Z tdsoul $
*/
public class Search implements CommandHandler, CommandHandlerFactory {
public void unload() {
}
public void load(CommandManagerFactory initializer) {
}
private static void findFile(BaseFtpConnection conn, Reply response,
LinkedRemoteFileInterface dir, Collection searchstrings, boolean files,
boolean dirs) {
//TODO optimize me, checking using regexp for all dirs is possibly slow
if (!conn.getGlobalContext().getConfig().checkPathPermission("privpath", conn.getUserNull(), dir, true)) {
Logger.getLogger(Search.class).debug("privpath: " + dir.getPath());
return;
}
for (Iterator iter = dir.getFiles().iterator(); iter.hasNext();) {
LinkedRemoteFileInterface file = (LinkedRemoteFileInterface) iter.next();
if (file.isDirectory()) {
findFile(conn, response, file, searchstrings, files, dirs);
}
boolean isFind = false;
boolean allFind = true;
if ((dirs && file.isDirectory()) || (files && file.isFile())) {
for (Iterator iterator = searchstrings.iterator();
iterator.hasNext();) {
if (response.size() >= 100) {
return;
}
String searchstring = (String) iterator.next();
if (file.getName().toLowerCase().indexOf(searchstring) != -1) {
isFind = true;
} else {
allFind = false;
}
}
if (isFind && allFind) {
response.addComment(file.getPath());
if (response.size() >= 100) {
response.addComment("<snip>");
return;
}
}
}
}
}
public Reply execute(BaseFtpConnection conn) {
FtpRequest request = conn.getRequest();
if (!request.hasArgument()) {
return Reply.RESPONSE_501_SYNTAX_ERROR;
}
String[] args = request.getArgument().toLowerCase().split(" ");
if (args.length == 0) {
return Reply.RESPONSE_501_SYNTAX_ERROR;
}
Collection searchstrings = Arrays.asList(args);
Reply response = (Reply) Reply.RESPONSE_200_COMMAND_OK.clone();
findFile(conn, response, conn.getCurrentDirectory(), searchstrings,
"SITE DUPE".equals(request.getCommand()),
"SITE SEARCH".equals(request.getCommand()));
return response;
}
public CommandHandler initialize(BaseFtpConnection conn,
CommandManager initializer) {
return this;
}
public String[] getFeatReplies() {
return null;
}
}
| g2x3k/Drftpd2Stable | src/net/sf/drftpd/master/command/plugins/Search.java | Java | gpl-2.0 | 4,229 |
/*
* Copyright 2014, Michael T. Goodrich, Roberto Tamassia, Michael H. Goldwasser
*
* Developed for use with the book:
*
* Data Structures and Algorithms in Java, Sixth Edition
* Michael T. Goodrich, Roberto Tamassia, and Michael H. Goldwasser
* John Wiley & Sons, 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 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 net.datastructures;
/**
* Realization of a stack as an adaptation of a SinglyLinkedList.
* All operations are performed in constant time.
*
* @author Michael T. Goodrich
* @author Roberto Tamassia
* @author Michael H. Goldwasser
* @see SinglyLinkedList
*/
public class LinkedStack<E> implements Stack<E> {
/** The primary storage for elements of the stack */
private SinglyLinkedList<E> list = new SinglyLinkedList<>(); // an empty list
/** Constructs an initially empty stack. */
public LinkedStack() { } // new stack relies on the initially empty list
/**
* Returns the number of elements in the stack.
* @return number of elements in the stack
*/
@Override
public int size() { return list.size(); }
/**
* Tests whether the stack is empty.
* @return true if the stack is empty, false otherwise
*/
@Override
public boolean isEmpty() { return list.isEmpty(); }
/**
* Inserts an element at the top of the stack.
* @param element the element to be inserted
*/
@Override
public void push(E element) { list.addFirst(element); }
/**
* Returns, but does not remove, the element at the top of the stack.
* @return top element in the stack (or null if empty)
*/
@Override
public E top() { return list.first(); }
/**
* Removes and returns the top element from the stack.
* @return element removed (or null if empty)
*/
@Override
public E pop() { return list.removeFirst(); }
/** Produces a string representation of the contents of the stack.
* (ordered from top to bottom)
*
* This exists for debugging purposes only.
*
* @return textual representation of the stack
*/
public String toString() {
return list.toString();
}
}
| fletchto99/CSI2110 | Labs/resources/net/datastructures/LinkedStack.java | Java | gpl-2.0 | 2,713 |
package me.ryleykimmel.brandywine.network.frame;
import me.ryleykimmel.brandywine.common.util.ByteBufUtil;
import me.ryleykimmel.brandywine.network.frame.FrameBuffer.ReadingFrameBuffer;
import com.google.common.base.Preconditions;
public final class FrameReader extends ReadingFrameBuffer {
public FrameReader(Frame frame) {
super(frame.getPayload());
}
public String getString() {
checkByteAccess();
return ByteBufUtil.readJString(buffer);
}
public int getSignedSmart() {
checkByteAccess();
int peek = buffer.getUnsignedByte(buffer.readerIndex());
int value = peek > Byte.MAX_VALUE ? buffer.readShort() - 49152 : buffer.readByte() - 64;
return value;
}
public int getUnsignedSmart() {
checkByteAccess();
int peek = buffer.getUnsignedByte(buffer.readerIndex());
int value = peek > Byte.MAX_VALUE ? buffer.readShort() + Short.MIN_VALUE : buffer.readByte();
return value;
}
public long getSigned(DataType type) {
return getSigned(type, DataOrder.BIG, DataTransformation.NONE);
}
public long getSigned(DataType type, DataOrder order) {
return getSigned(type, order, DataTransformation.NONE);
}
public long getSigned(DataType type, DataTransformation transformation) {
return getSigned(type, DataOrder.BIG, transformation);
}
public long getSigned(DataType type, DataOrder order, DataTransformation transformation) {
long longValue = get(type, order, transformation);
if (type != DataType.LONG) {
int max = (int) (Math.pow(2, type.getBytes() * 8 - 1) - 1);
if (longValue > max) {
longValue -= (max + 1) * 2;
}
}
return longValue;
}
public long getUnsigned(DataType type) {
return getUnsigned(type, DataOrder.BIG, DataTransformation.NONE);
}
public long getUnsigned(DataType type, DataOrder order) {
return getUnsigned(type, order, DataTransformation.NONE);
}
public long getUnsigned(DataType type, DataTransformation transformation) {
return getUnsigned(type, DataOrder.BIG, transformation);
}
public long getUnsigned(DataType type, DataOrder order, DataTransformation transformation) {
Preconditions.checkArgument(type != DataType.LONG, "due to java restrictions, longs must be read as signed types");
return get(type, order, transformation) & 0xFFFFFFFFFFFFFFFFL;
}
private long get(DataType type, DataOrder order, DataTransformation transformation) {
checkByteAccess();
long longValue = 0;
int length = type.getBytes();
switch (order) {
case BIG:
for (int i = length - 1; i >= 0; i--) {
if (i == 0 && transformation != DataTransformation.NONE) {
switch (transformation) {
case ADD:
longValue |= buffer.readByte() - 128 & 0xFFL;
break;
case NEGATE:
longValue |= -buffer.readByte() & 0xFFL;
break;
case SUBTRACT:
longValue |= 128 - buffer.readByte() & 0xFFL;
break;
default:
throw new UnsupportedOperationException(transformation + " is not supported!");
}
} else {
longValue |= (buffer.readByte() & 0xFFL) << i * 8;
}
}
break;
case LITTLE:
for (int i = 0; i < length; i++) {
if (i == 0 && transformation != DataTransformation.NONE) {
switch (transformation) {
case ADD:
longValue |= buffer.readByte() - 128 & 0xFFL;
break;
case NEGATE:
longValue |= -buffer.readByte() & 0xFFL;
break;
case SUBTRACT:
longValue |= 128 - buffer.readByte() & 0xFFL;
break;
default:
throw new UnsupportedOperationException(transformation + " is not supported!");
}
} else {
longValue |= (buffer.readByte() & 0xFFL) << i * 8;
}
}
break;
case MIDDLE:
Preconditions.checkArgument(transformation == DataTransformation.NONE, "middle endian cannot be transformed");
Preconditions.checkArgument(type == DataType.INT, "middle endian can only be used with an integer");
longValue |= (buffer.readByte() & 0xFF) << 8;
longValue |= buffer.readByte() & 0xFF;
longValue |= (buffer.readByte() & 0xFF) << 24;
longValue |= (buffer.readByte() & 0xFF) << 16;
break;
case INVERSED_MIDDLE:
Preconditions.checkArgument(transformation == DataTransformation.NONE, "inversed middle endian cannot be transformed");
Preconditions.checkArgument(type == DataType.INT, "inversed middle endian can only be used with an integer");
longValue |= (buffer.readByte() & 0xFF) << 16;
longValue |= (buffer.readByte() & 0xFF) << 24;
longValue |= buffer.readByte() & 0xFF;
longValue |= (buffer.readByte() & 0xFF) << 8;
break;
default:
throw new UnsupportedOperationException(order + " is not supported!");
}
return longValue;
}
public int getBits(int amount) {
Preconditions.checkArgument(amount >= 0 && amount <= 32, "Number of bits must be between 1 and 32 inclusive.");
checkBitAccess();
int bytePos = bitIndex >> 3;
int bitOffset = 8 - (bitIndex & 7);
int value = 0;
bitIndex += amount;
for (; amount > bitOffset; bitOffset = 8) {
value += (buffer.getByte(bytePos++) & BIT_MASKS[bitOffset]) << amount - bitOffset;
amount -= bitOffset;
}
if (amount == bitOffset) {
value += buffer.getByte(bytePos) & BIT_MASKS[bitOffset];
} else {
value += buffer.getByte(bytePos) >> bitOffset - amount & BIT_MASKS[amount];
}
return value;
}
public void getBytes(byte[] bytes) {
checkByteAccess();
for (int i = 0; i < bytes.length; i++) {
bytes[i] = buffer.readByte();
}
}
public void getBytes(DataTransformation transformation, byte[] bytes) {
if (transformation == DataTransformation.NONE) {
getBytesReverse(bytes);
} else {
for (int i = 0; i < bytes.length; i++) {
bytes[i] = (byte) getSigned(DataType.BYTE, transformation);
}
}
}
public void getBytesReverse(byte[] bytes) {
checkByteAccess();
for (int i = bytes.length - 1; i >= 0; i--) {
bytes[i] = buffer.readByte();
}
}
public void getBytesReverse(DataTransformation transformation, byte[] bytes) {
if (transformation == DataTransformation.NONE) {
getBytesReverse(bytes);
} else {
for (int i = bytes.length - 1; i >= 0; i--) {
bytes[i] = (byte) getSigned(DataType.BYTE, transformation);
}
}
}
} | atomicint/brandywine | src/main/java/me/ryleykimmel/brandywine/network/frame/FrameReader.java | Java | gpl-2.0 | 6,245 |
/**
* @Title: AlbumVo.java
* @Package com.shangwupanlv.vo
* @Description: TODO(用一句话描述该文件做什么)
* @author Alex.Z
* @date 2013-5-28 上午10:38:47
* @version V1.0
*/
package com.peiban.vo;
import java.io.Serializable;
import net.tsz.afinal.annotation.sqlite.Id;
import net.tsz.afinal.annotation.sqlite.Table;
import net.tsz.afinal.annotation.sqlite.Transient;
@Table(name = "photo")
public class PhotoVo implements Serializable{
@Transient
private static final long serialVersionUID = -5094078474942062095L;
@Id
private String pid; // 相片id
private String aid;
private String photoName;//照片名
private String photoUrl;// 相片路径
private String auth;// 相片认证
public String getPid() {
return pid == null ? "" : pid;
}
public String getAid() {
return aid == null ? "" : aid;
}
public String getPhotoUrl() {
return photoUrl == null ? "" : photoUrl;
}
public void setPid(String pid) {
this.pid = pid;
}
public void setAid(String aid) {
this.aid = aid;
}
public void setPhotoUrl(String photoUrl) {
this.photoUrl = photoUrl;
}
public String getAuth() {
return auth == null ? "" : auth;
}
public void setAuth(String auth) {
this.auth = auth;
}
public String getPhotoName() {
return photoName;
}
public void setPhotoName(String photoName) {
this.photoName = photoName;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((aid == null) ? 0 : aid.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;
PhotoVo other = (PhotoVo) obj;
if (aid == null) {
if (other.aid != null)
return false;
} else if (!aid.equals(other.aid))
return false;
return true;
}
}
| sidney9111/Weixin_android | src/com/peiban/vo/PhotoVo.java | Java | gpl-2.0 | 1,890 |
/*
* #%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;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Set;
import loci.common.RandomAccessInputStream;
import loci.formats.in.MetadataLevel;
import loci.formats.in.MetadataOptions;
import loci.formats.meta.MetadataStore;
/**
* DelegateReader is a file format reader that selects which reader to use
* for a format if there are two readers which handle the same format.
*/
public abstract class DelegateReader extends FormatReader {
/** Flag indicating whether to use legacy reader by default. */
protected boolean useLegacy;
/** Native reader. */
protected IFormatReader nativeReader;
/** Legacy reader. */
protected IFormatReader legacyReader;
/** Flag indicating that the native reader was successfully initialized. */
protected boolean nativeReaderInitialized;
/** Flag indicating that the legacy reader was successfully initialized. */
protected boolean legacyReaderInitialized;
// -- Constructor --
/** Constructs a new delegate reader. */
public DelegateReader(String format, String suffix) {
super(format, suffix);
}
/** Constructs a new delegate reader. */
public DelegateReader(String format, String[] suffixes) {
super(format, suffixes);
}
// -- DelegateReader API methods --
/** Sets whether to use the legacy reader by default. */
public void setLegacy(boolean legacy) { useLegacy = legacy; }
/** Gets whether to use the legacy reader by default. */
public boolean isLegacy() { return useLegacy; }
// -- IMetadataConfigurable API methods --
/* @see IMetadataConfigurable#getSupportedMetadataLevels() */
@Override
public Set<MetadataLevel> getSupportedMetadataLevels() {
return nativeReader.getSupportedMetadataLevels();
}
/* @see IMetadataConfigurable#getMetadataOptions() */
@Override
public MetadataOptions getMetadataOptions() {
return nativeReader.getMetadataOptions();
}
/* @see IMetadataConfigurable#setMetadataOptions(MetadataOptions) */
@Override
public void setMetadataOptions(MetadataOptions options) {
nativeReader.setMetadataOptions(options);
legacyReader.setMetadataOptions(options);
}
// -- IFormatReader API methods --
/* @see IFormatReader#isThisType(String, boolean) */
@Override
public boolean isThisType(String name, boolean open) {
return nativeReader.isThisType(name, open);
}
/* @see IFormatReader#isThisType(RandomAccessInputStream) */
@Override
public boolean isThisType(RandomAccessInputStream stream) throws IOException {
return nativeReader.isThisType(stream);
}
/* @see IFormatReader#setSeries(int) */
@Override
public void setSeries(int no) {
super.setSeries(no);
if (nativeReaderInitialized) nativeReader.setSeries(no);
if (legacyReaderInitialized) legacyReader.setSeries(no);
}
/* @see IFormatReader#setCoreIndex(int) */
@Override
public void setCoreIndex(int no) {
super.setCoreIndex(no);
if (nativeReaderInitialized) nativeReader.setCoreIndex(no);
if (legacyReaderInitialized) legacyReader.setCoreIndex(no);
}
/* @see IFormatReader#setResolution(int) */
@Override
public void setResolution(int resolution) {
super.setResolution(resolution);
if (nativeReaderInitialized) nativeReader.setResolution(resolution);
if (legacyReaderInitialized) legacyReader.setResolution(resolution);
}
/* @see IFormatReader#setNormalized(boolean) */
@Override
public void setNormalized(boolean normalize) {
super.setNormalized(normalize);
nativeReader.setNormalized(normalize);
legacyReader.setNormalized(normalize);
}
/* @see IFormatReader#setOriginalMetadataPopulated(boolean) */
@Override
public void setOriginalMetadataPopulated(boolean populate) {
super.setOriginalMetadataPopulated(populate);
nativeReader.setOriginalMetadataPopulated(populate);
legacyReader.setOriginalMetadataPopulated(populate);
}
/* @see IFormatReader#setGroupFiles(boolean) */
@Override
public void setGroupFiles(boolean group) {
super.setGroupFiles(group);
nativeReader.setGroupFiles(group);
legacyReader.setGroupFiles(group);
}
/* @see IFormatReader#setFlattenedResolutions(boolean) */
@Override
public void setFlattenedResolutions(boolean flattened) {
super.setFlattenedResolutions(flattened);
nativeReader.setFlattenedResolutions(flattened);
legacyReader.setFlattenedResolutions(flattened);
}
/* @see IFormatReader#setMetadataFiltered(boolean) */
@Override
public void setMetadataFiltered(boolean filter) {
super.setMetadataFiltered(filter);
nativeReader.setMetadataFiltered(filter);
legacyReader.setMetadataFiltered(filter);
}
/* @see IFormatReader#setMetadataStore(MetadataStore) */
@Override
public void setMetadataStore(MetadataStore store) {
super.setMetadataStore(store);
nativeReader.setMetadataStore(store);
legacyReader.setMetadataStore(store);
}
/* @see IFormatReader#get8BitLookupTable() */
@Override
public byte[][] get8BitLookupTable() throws FormatException, IOException {
if (useLegacy || (legacyReaderInitialized && !nativeReaderInitialized)) {
return legacyReader.get8BitLookupTable();
}
return nativeReader.get8BitLookupTable();
}
/* @see IFormatReader#get16BitLookupTable() */
@Override
public short[][] get16BitLookupTable() throws FormatException, IOException {
if (useLegacy || (legacyReaderInitialized && !nativeReaderInitialized)) {
return legacyReader.get16BitLookupTable();
}
return nativeReader.get16BitLookupTable();
}
/* @see IFormatReader#getSeriesUsedFiles(boolean) */
@Override
public String[] getSeriesUsedFiles(boolean noPixels) {
if (useLegacy || (legacyReaderInitialized && !nativeReaderInitialized)) {
return legacyReader.getSeriesUsedFiles(noPixels);
}
return nativeReader.getSeriesUsedFiles(noPixels);
}
/* @see IFormatReader#openBytes(int, byte[], int, int, int, int) */
@Override
public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h)
throws FormatException, IOException
{
if (useLegacy || (legacyReaderInitialized && !nativeReaderInitialized)) {
return legacyReader.openBytes(no, buf, x, y, w, h);
}
return nativeReader.openBytes(no, buf, x, y, w, h);
}
/* @see IFormatReader#close(boolean) */
@Override
public void close(boolean fileOnly) throws IOException {
super.close(fileOnly);
if (nativeReader != null) nativeReader.close(fileOnly);
if (legacyReader != null) legacyReader.close(fileOnly);
if (!fileOnly) {
nativeReaderInitialized = legacyReaderInitialized = false;
}
}
/* @see IFormatReader#getOptimalTileWidth() */
@Override
public int getOptimalTileWidth() {
if (useLegacy || (legacyReaderInitialized && !nativeReaderInitialized)) {
return legacyReader.getOptimalTileWidth();
}
return nativeReader.getOptimalTileWidth();
}
/* @see IFormatReader#getOptimalTileHeight() */
@Override
public int getOptimalTileHeight() {
if (useLegacy || (legacyReaderInitialized && !nativeReaderInitialized)) {
return legacyReader.getOptimalTileHeight();
}
return nativeReader.getOptimalTileHeight();
}
/* @see IFormatReader#reopenFile() */
@Override
public void reopenFile() throws IOException {
if (useLegacy) {
legacyReader.reopenFile();
}
else {
nativeReader.reopenFile();
}
}
// -- IFormatHandler API methods --
/* @see IFormatHandler#setId(String) */
@Override
public void setId(String id) throws FormatException, IOException {
super.setId(id);
if (useLegacy) {
try {
legacyReader.setId(id);
legacyReaderInitialized = true;
}
catch (FormatException e) {
LOGGER.debug("", e);
nativeReader.setId(id);
nativeReaderInitialized = true;
}
}
else {
Exception exc = null;
try {
nativeReader.setId(id);
nativeReaderInitialized = true;
}
catch (FormatException e) { exc = e; }
catch (IOException e) { exc = e; }
if (exc != null) {
nativeReaderInitialized = false;
LOGGER.info("", exc);
legacyReader.setId(id);
legacyReaderInitialized = true;
}
if (legacyReaderInitialized) {
nativeReaderInitialized = false;
}
}
if (nativeReaderInitialized) {
core = new ArrayList<CoreMetadata>(nativeReader.getCoreMetadataList());
metadata = nativeReader.getGlobalMetadata();
metadataStore = nativeReader.getMetadataStore();
}
if (legacyReaderInitialized) {
core = new ArrayList<CoreMetadata>(legacyReader.getCoreMetadataList());
metadata = legacyReader.getGlobalMetadata();
metadataStore = legacyReader.getMetadataStore();
}
}
}
| imunro/bioformats | components/formats-api/src/loci/formats/DelegateReader.java | Java | gpl-2.0 | 10,413 |
/*
* Copyright (c) 2012, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* The Universal Permissive License (UPL), Version 1.0
*
* Subject to the condition set forth below, permission is hereby granted to any
* person obtaining a copy of this software, associated documentation and/or
* data (collectively the "Software"), free of charge and under any and all
* copyright rights in the Software, and any and all patent rights owned or
* freely licensable by each licensor hereunder covering either (i) the
* unmodified Software as contributed to or provided by such licensor, or (ii)
* the Larger Works (as defined below), to deal in both
*
* (a) the Software, and
*
* (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if
* one is included with the Software each a "Larger Work" to which the Software
* is contributed by such licensors),
*
* without restriction, including without limitation the rights to copy, create
* derivative works of, display, perform, and distribute the Software and make,
* use, sell, offer for sale, import, export, have made, and have sold the
* Software and the Larger Work(s), and to sublicense the foregoing rights on
* either these or other terms.
*
* This license is subject to the following condition:
*
* The above copyright notice and either this complete permission notice or at a
* minimum a reference to the UPL must 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 com.oracle.truffle.dsl.processor.parser;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeMirror;
import com.oracle.truffle.dsl.processor.ProcessorContext;
import com.oracle.truffle.dsl.processor.java.ElementUtils;
import com.oracle.truffle.dsl.processor.model.MethodSpec;
import com.oracle.truffle.dsl.processor.model.ParameterSpec;
import com.oracle.truffle.dsl.processor.model.TemplateMethod;
import com.oracle.truffle.dsl.processor.model.TypeCastData;
import com.oracle.truffle.dsl.processor.model.TypeSystemData;
class TypeCastParser extends TypeSystemMethodParser<TypeCastData> {
TypeCastParser(ProcessorContext context, TypeSystemData typeSystem) {
super(context, typeSystem);
}
@Override
public MethodSpec createSpecification(ExecutableElement method, AnnotationMirror mirror) {
TypeMirror targetTypeMirror = ElementUtils.getAnnotationValue(TypeMirror.class, mirror, "value");
ParameterSpec returnTypeSpec = new ParameterSpec("returnType", targetTypeMirror);
returnTypeSpec.setAllowSubclasses(false);
MethodSpec spec = new MethodSpec(returnTypeSpec);
spec.addRequired(new ParameterSpec("value", getContext().getType(Object.class)));
return spec;
}
@Override
public TypeCastData create(TemplateMethod method, boolean invalid) {
TypeMirror targetType = resolveCastOrCheck(method);
TypeMirror sourceType = getContext().getType(Object.class);
return new TypeCastData(method, sourceType, targetType);
}
@Override
public DeclaredType getAnnotationType() {
return types.TypeCast;
}
}
| smarr/Truffle | truffle/src/com.oracle.truffle.dsl.processor/src/com/oracle/truffle/dsl/processor/parser/TypeCastParser.java | Java | gpl-2.0 | 3,803 |
/*
* Copyright (c) 2020, 2020, 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.oracle.svm.core.jfr.traceid;
import org.graalvm.compiler.api.replacements.Fold;
import org.graalvm.nativeimage.ImageSingletons;
import org.graalvm.nativeimage.Platform;
import org.graalvm.nativeimage.Platforms;
import com.oracle.svm.core.annotate.Uninterruptible;
import com.oracle.svm.core.thread.VMOperation;
/**
* Class holding the current JFR epoch. JFR uses an epoch system to safely separate constant pool
* entries between adjacent chunks. Used to get the current or previous epoch and switch from one
* epoch to another across an uninterruptible safepoint operation.
*/
public class JfrTraceIdEpoch {
private static final long EPOCH_0_BIT = 0b01;
private static final long EPOCH_1_BIT = 0b10;
private boolean epoch;
@Fold
public static JfrTraceIdEpoch getInstance() {
return ImageSingletons.lookup(JfrTraceIdEpoch.class);
}
@Platforms(Platform.HOSTED_ONLY.class)
public JfrTraceIdEpoch() {
}
@Uninterruptible(reason = "Called from uninterruptible code.", mayBeInlined = true)
public void changeEpoch() {
assert VMOperation.isInProgressAtSafepoint();
epoch = !epoch;
}
@Uninterruptible(reason = "Called from uninterruptible code.", mayBeInlined = true)
long thisEpochBit() {
return epoch ? EPOCH_1_BIT : EPOCH_0_BIT;
}
@Uninterruptible(reason = "Called from uninterruptible code.", mayBeInlined = true)
long previousEpochBit() {
return epoch ? EPOCH_0_BIT : EPOCH_1_BIT;
}
@Uninterruptible(reason = "Called from uninterruptible code.", mayBeInlined = true)
public boolean currentEpoch() {
return epoch;
}
@Uninterruptible(reason = "Called by uninterruptible code.", mayBeInlined = true)
public boolean previousEpoch() {
return !epoch;
}
}
| smarr/Truffle | substratevm/src/com.oracle.svm.core/src/com/oracle/svm/core/jfr/traceid/JfrTraceIdEpoch.java | Java | gpl-2.0 | 3,039 |
/*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.doclets.formats.html;
import java.io.IOException;
import com.sun.javadoc.*;
import com.sun.tools.javac.jvm.Profile;
import com.sun.tools.doclets.internal.toolkit.*;
import com.sun.tools.doclets.internal.toolkit.util.*;
/**
* The factory that returns HTML writers.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*
* @author Jamie Ho
* @since 1.5
*/
public class WriterFactoryImpl implements WriterFactory {
private final ConfigurationImpl configuration;
public WriterFactoryImpl(ConfigurationImpl configuration) {
this.configuration = configuration;
}
/**
* {@inheritDoc}
*/
public ConstantsSummaryWriter getConstantsSummaryWriter() throws Exception {
return new ConstantsSummaryWriterImpl(configuration);
}
/**
* {@inheritDoc}
*/
public PackageSummaryWriter getPackageSummaryWriter(PackageDoc packageDoc,
PackageDoc prevPkg, PackageDoc nextPkg) throws Exception {
return new PackageWriterImpl(configuration, packageDoc,
prevPkg, nextPkg);
}
/**
* {@inheritDoc}
*/
public ProfileSummaryWriter getProfileSummaryWriter(Profile profile,
Profile prevProfile, Profile nextProfile) throws Exception {
return new ProfileWriterImpl(configuration, profile,
prevProfile, nextProfile);
}
/**
* {@inheritDoc}
*/
public ProfilePackageSummaryWriter getProfilePackageSummaryWriter(PackageDoc packageDoc,
PackageDoc prevPkg, PackageDoc nextPkg, Profile profile) throws Exception {
return new ProfilePackageWriterImpl(configuration, packageDoc,
prevPkg, nextPkg, profile);
}
/**
* {@inheritDoc}
*/
public ClassWriter getClassWriter(ClassDoc classDoc, ClassDoc prevClass,
ClassDoc nextClass, ClassTree classTree) throws IOException {
return new ClassWriterImpl(configuration, classDoc,
prevClass, nextClass, classTree);
}
/**
* {@inheritDoc}
*/
public AnnotationTypeWriter getAnnotationTypeWriter(
AnnotationTypeDoc annotationType, Type prevType, Type nextType)
throws Exception {
return new AnnotationTypeWriterImpl(configuration,
annotationType, prevType, nextType);
}
/**
* {@inheritDoc}
*/
public AnnotationTypeOptionalMemberWriter
getAnnotationTypeOptionalMemberWriter(
AnnotationTypeWriter annotationTypeWriter) throws Exception {
return new AnnotationTypeOptionalMemberWriterImpl(
(SubWriterHolderWriter) annotationTypeWriter,
annotationTypeWriter.getAnnotationTypeDoc());
}
/**
* {@inheritDoc}
*/
public AnnotationTypeRequiredMemberWriter
getAnnotationTypeRequiredMemberWriter(AnnotationTypeWriter annotationTypeWriter) throws Exception {
return new AnnotationTypeRequiredMemberWriterImpl(
(SubWriterHolderWriter) annotationTypeWriter,
annotationTypeWriter.getAnnotationTypeDoc());
}
/**
* {@inheritDoc}
*/
public EnumConstantWriterImpl getEnumConstantWriter(ClassWriter classWriter)
throws Exception {
return new EnumConstantWriterImpl((SubWriterHolderWriter) classWriter,
classWriter.getClassDoc());
}
/**
* {@inheritDoc}
*/
public FieldWriterImpl getFieldWriter(ClassWriter classWriter)
throws Exception {
return new FieldWriterImpl((SubWriterHolderWriter) classWriter,
classWriter.getClassDoc());
}
/**
* {@inheritDoc}
*/
public MethodWriterImpl getMethodWriter(ClassWriter classWriter)
throws Exception {
return new MethodWriterImpl((SubWriterHolderWriter) classWriter,
classWriter.getClassDoc());
}
/**
* {@inheritDoc}
*/
public ConstructorWriterImpl getConstructorWriter(ClassWriter classWriter)
throws Exception {
return new ConstructorWriterImpl((SubWriterHolderWriter) classWriter,
classWriter.getClassDoc());
}
/**
* {@inheritDoc}
*/
public MemberSummaryWriter getMemberSummaryWriter(
ClassWriter classWriter, int memberType)
throws Exception {
switch (memberType) {
case VisibleMemberMap.CONSTRUCTORS:
return getConstructorWriter(classWriter);
case VisibleMemberMap.ENUM_CONSTANTS:
return getEnumConstantWriter(classWriter);
case VisibleMemberMap.FIELDS:
return getFieldWriter(classWriter);
case VisibleMemberMap.INNERCLASSES:
return new NestedClassWriterImpl((SubWriterHolderWriter)
classWriter, classWriter.getClassDoc());
case VisibleMemberMap.METHODS:
return getMethodWriter(classWriter);
default:
return null;
}
}
/**
* {@inheritDoc}
*/
public MemberSummaryWriter getMemberSummaryWriter(
AnnotationTypeWriter annotationTypeWriter, int memberType)
throws Exception {
switch (memberType) {
case VisibleMemberMap.ANNOTATION_TYPE_MEMBER_OPTIONAL:
return (AnnotationTypeOptionalMemberWriterImpl)
getAnnotationTypeOptionalMemberWriter(annotationTypeWriter);
case VisibleMemberMap.ANNOTATION_TYPE_MEMBER_REQUIRED:
return (AnnotationTypeRequiredMemberWriterImpl)
getAnnotationTypeRequiredMemberWriter(annotationTypeWriter);
default:
return null;
}
}
/**
* {@inheritDoc}
*/
public SerializedFormWriter getSerializedFormWriter() throws Exception {
return new SerializedFormWriterImpl(configuration);
}
}
| karianna/jdk8_tl | langtools/src/share/classes/com/sun/tools/doclets/formats/html/WriterFactoryImpl.java | Java | gpl-2.0 | 7,264 |
package com.jclock;
import java.awt.*;
import java.text.SimpleDateFormat;
import java.util.Vector;
public class Options {
static boolean alwaysOnTop = false,
isMoveable = true;
static int formatNum = 2,fontSize = 60;
final static String timeFormat[] = {"h:mm","hh:mm","h:mm a","hh:mm a"};
static SimpleDateFormat clockStyle = new SimpleDateFormat(timeFormat[formatNum]);
static Color color = Color.GREEN;
static Vector<Color> colors = new Vector<Color>();
}// end Options
| seemywingz/JClock | src/com/jclock/Options.java | Java | gpl-2.0 | 502 |
import edu.stanford.nlp.ie.AbstractSequenceClassifier;
import edu.stanford.nlp.ie.crf.*;
import edu.stanford.nlp.io.IOUtils;
import edu.stanford.nlp.ling.CoreLabel;
import edu.stanford.nlp.ling.CoreAnnotations;
import java.util.List;
/**
* This is a demo of calling CRFClassifier programmatically.
* <p>
* Usage: {@code java -mx400m -cp "stanford-ner.jar:." NERDemo [serializedClassifier [fileName]] }
* <p>
* If arguments aren't specified, they default to
* classifiers/english.all.3class.distsim.crf.ser.gz and some hardcoded sample text.
* <p>
* To use CRFClassifier from the command line:
* </p><blockquote>
* {@code java -mx400m edu.stanford.nlp.ie.crf.CRFClassifier -loadClassifier [classifier] -textFile [file] }
* </blockquote><p>
* Or if the file is already tokenized and one word per line, perhaps in
* a tab-separated value format with extra columns for part-of-speech tag,
* etc., use the version below (note the 's' instead of the 'x'):
* </p><blockquote>
* {@code java -mx400m edu.stanford.nlp.ie.crf.CRFClassifier -loadClassifier [classifier] -testFile [file] }
* </blockquote>
*
* @author Jenny Finkel
* @author Christopher Manning
*/
public class NERDemo {
public static void main(String[] args) throws Exception {
String serializedClassifier = "classifiers/english.all.3class.distsim.crf.ser.gz";
if (args.length > 0) {
serializedClassifier = args[0];
}
AbstractSequenceClassifier<CoreLabel> classifier = CRFClassifier.getClassifier(serializedClassifier);
/* For either a file to annotate or for the hardcoded text example,
this demo file shows two ways to process the output, for teaching
purposes. For the file, it shows both how to run NER on a String
and how to run it on a whole file. For the hard-coded String,
it shows how to run it on a single sentence, and how to do this
and produce an inline XML output format.
*/
if (args.length > 1) {
String fileContents = IOUtils.slurpFile(args[1]);
List<List<CoreLabel>> out = classifier.classify(fileContents);
for (List<CoreLabel> sentence : out) {
for (CoreLabel word : sentence) {
System.out.print(word.word() + '/' + word.get(CoreAnnotations.AnswerAnnotation.class) + ' ');
}
System.out.println();
}
System.out.println("---");
out = classifier.classifyFile(args[1]);
for (List<CoreLabel> sentence : out) {
for (CoreLabel word : sentence) {
System.out.print(word.word() + '/' + word.get(CoreAnnotations.AnswerAnnotation.class) + ' ');
}
System.out.println();
}
} else {
// String[] example = {"Good afternoon Rajat Raina, how are you today?",
// "I go to school at Stanford University, which is located in California." };
String[] example = {"Raja went to Temple",
"Rajah is working at university of moratuwa"};
for (String str : example) {
System.out.println(classifier.classifyToString(str));
}
System.out.println("---");
for (String str : example) {
// This one puts in spaces and newlines between tokens, so just print not println.
System.out.print(classifier.classifyToString(str, "slashTags", false));
}
System.out.println("---");
for (String str : example) {
System.out.println(classifier.classifyWithInlineXML(str));
}
System.out.println("---");
for (String str : example) {
System.out.println(classifier.classifyToString(str, "xml", true));
}
System.out.println("---");
int i = 0;
for (String str : example) {
for (List<CoreLabel> lcl : classifier.classify(str)) {
for (CoreLabel cl : lcl) {
System.out.print(i++ + ": ");
System.out.println(cl.toShorterString());
}
}
}
}
}
}
| ThamayanthyS/Stanford_ner_extended_for_dict_chunking | NERDemo.java | Java | gpl-2.0 | 4,289 |
// Copyright (C) 2008 Philip Aston
// All rights reserved.
//
// This file is part of The Grinder software distribution. Refer to
// the file LICENSE which is part of The Grinder distribution for
// licensing details. The Grinder distribution is available on the
// Internet at http://grinder.sourceforge.net/
//
// 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.
package net.grinder.common;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import java.net.Socket;
/**
* Static utility methods to close resource handles.
*
* <p>
* I considered a template method approach, but that's equally ugly.
* </p>
*
* <p>
* The methods are intended to be called from finally blocks, and so handle all
* exceptions quietly; with the exception of {@link InterruptedException}s
* which are always converted to {@link UncheckedInterruptedException}s.
*
* @author Philip Aston
*/
public final class Closer {
/** Disabled constructor. Package scope for unit tests. */
Closer() {
throw new UnsupportedOperationException();
}
/**
* Close the resource.
*
* @param reader The resource to close.
*/
public static void close(Reader reader) {
if (reader != null) {
try {
reader.close();
}
catch (IOException e) {
UncheckedInterruptedException.ioException(e);
}
}
}
/**
* Close the resource.
*
* @param writer The resource to close.
*/
public static void close(Writer writer) {
if (writer != null) {
try {
writer.close();
}
catch (IOException e) {
UncheckedInterruptedException.ioException(e);
}
}
}
/**
* Close the resource.
*
* @param inputStream The resource to close.
*/
public static void close(InputStream inputStream) {
if (inputStream != null) {
try {
inputStream.close();
}
catch (IOException e) {
UncheckedInterruptedException.ioException(e);
}
}
}
/**
* Close the resource.
*
* @param outputStream The resource to close.
*/
public static void close(OutputStream outputStream) {
if (outputStream != null) {
try {
outputStream.close();
}
catch (IOException e) {
UncheckedInterruptedException.ioException(e);
}
}
}
/**
* Close the resource.
*
* @param socket The resource to close.
*/
public static void close(Socket socket) {
if (socket != null) {
try {
socket.close();
}
catch (IOException e) {
UncheckedInterruptedException.ioException(e);
}
}
}
}
| slantview/DrupalLoadTest | lib/grinder/grinder-core/src/main/java/net/grinder/common/Closer.java | Java | gpl-2.0 | 3,422 |
package com.djtu.signExam.action.compt;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/man/admin/comptCalendar")
public class ComptManCalendarController {
private static final String NAV = "navbar";
private static final String CAL = "calendar";
@RequestMapping(value = "/list")
public String list(Model model){
model.addAttribute(NAV, CAL);
return "";
}
@RequestMapping(value = "/add")
public String add(){
return "";
}
@RequestMapping(value = "/delete")
public @ResponseBody String delete(){
return "";
}
}
| doomdagger/CompetitionHub | src/main/java/com/djtu/signExam/action/compt/ComptManCalendarController.java | Java | gpl-2.0 | 768 |
// $Id: ModelMemberFilePersister.java 9528 2005-12-18 13:34:51Z rastaman $
// Copyright (c) 1996-2005 The Regents of the University of California. All
// Rights Reserved. Permission to use, copy, modify, and distribute this
// software and its documentation without fee, and without a written
// agreement is hereby granted, provided that the above copyright notice
// and this paragraph appear in all copies. This software program and
// documentation are copyrighted by The Regents of the University of
// California. The software program and documentation are supplied "AS
// IS", without any accompanying services from The Regents. The Regents
// does not warrant that the operation of the program will be
// uninterrupted or error-free. The end-user understands that the program
// was developed for research purposes and is advised not to rely
// exclusively on the program for any reason. IN NO EVENT SHALL THE
// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,
// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF
// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF
// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE
// PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF
// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,
// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
package org.argouml.persistence;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.HashMap;
import org.apache.log4j.Logger;
import org.argouml.kernel.Project;
import org.argouml.kernel.ProjectMember;
import org.argouml.model.Model;
import org.argouml.model.UmlException;
import org.argouml.model.XmiWriter;
import org.argouml.uml.ProjectMemberModel;
import org.xml.sax.InputSource;
/**
* The file persister for the UML model.
* @author Bob Tarling
*/
public class ModelMemberFilePersister extends MemberFilePersister {
/**
* Logger.
*/
private static final Logger LOG =
Logger.getLogger(ModelMemberFilePersister.class);
/**
* Loads a model (XMI only) from an input source. BE ADVISED this
* method has a side effect. It sets _UUIDREFS to the model.<p>
*
* If there is a problem with the xmi file, an error is set in the
* getLastLoadStatus() field. This needs to be examined by the
* calling function.<p>
*
* @see org.argouml.persistence.MemberFilePersister#load(org.argouml.kernel.Project,
* java.io.InputStream)
*/
public void load(Project project, InputStream inputStream)
throws OpenException {
InputSource source = new InputSource(inputStream);
Object mmodel = null;
// 2002-07-18
// Jaap Branderhorst
// changed the loading of the projectfiles to solve hanging
// of argouml if a project is corrupted. Issue 913
// Created xmireader with method getErrors to check if parsing went well
try {
source.setEncoding("UTF-8");
XMIParser.getSingleton().readModels(project ,source);
mmodel = XMIParser.getSingleton().getCurModel();
} catch (OpenException e) {
LastLoadInfo.getInstance().setLastLoadStatus(false);
LastLoadInfo.getInstance().setLastLoadMessage(
"UmlException parsing XMI.");
LOG.error("UmlException caught", e);
throw new OpenException(e);
}
// This should probably be inside xmiReader.parse
// but there is another place in this source
// where XMIReader is used, but it appears to be
// the NSUML XMIReader. When Argo XMIReader is used
// consistently, it can be responsible for loading
// the listener. Until then, do it here.
Model.getUmlHelper().addListenersToModel(mmodel);
project.addMember(mmodel);
project.setUUIDRefs(new HashMap(XMIParser.getSingleton().getUUIDRefs()));
}
/**
* @see org.argouml.persistence.MemberFilePersister#getMainTag()
*/
public String getMainTag() {
return "XMI";
}
/**
* Save the project model to XMI.
*
* @see org.argouml.persistence.MemberFilePersister#save(
* org.argouml.kernel.ProjectMember, java.io.Writer,
* java.lang.Integer)
*/
public void save(ProjectMember member, Writer w, Integer indent)
throws SaveException {
if (w == null) {
throw new IllegalArgumentException("No Writer specified!");
}
try {
ProjectMemberModel pmm = (ProjectMemberModel) member;
Object model = pmm.getModel();
File tempFile = null;
Writer writer = null;
if (indent != null) {
// If we have an indent then we are adding this file
// to a superfile.
// That is most likely inserting the XMI into the .uml file
tempFile = File.createTempFile("xmi", null);
tempFile.deleteOnExit();
writer =
new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream(tempFile), "UTF-8"));
//writer = new FileWriter(tempFile);
XmiWriter xmiWriter = Model.getXmiWriter(model, writer);
xmiWriter.write();
addXmlFileToWriter((PrintWriter) w, tempFile,
indent.intValue());
} else {
// Othewise we are writing into a zip writer.
XmiWriter xmiWriter = Model.getXmiWriter(model, w);
xmiWriter.write();
}
} catch (IOException e) {
throw new SaveException(e);
} catch (UmlException e) {
throw new SaveException(e);
}
}
}
| carvalhomb/tsmells | sample/argouml/argouml/org/argouml/persistence/ModelMemberFilePersister.java | Java | gpl-2.0 | 6,279 |
/*
* Copyright 2007-2009 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., 16 Network Circle, Menlo
* Park, CA 94025 or visit www.sun.com if you need additional
* information or have any questions.
*/
package com.sun.labs.aura.music.web;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.core.BaseException;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.LinkedHashMap;
import java.util.Map;
/**
*
* @author plamere
*/
public class Cache<T> {
private int maxMemoryObjects;
private int maxAgeInDays;
private File cacheDir;
private XStream xstream;
private Map<String, T> objectCache = new ObjectMap<String, T>();
public Cache(int maxMemoryObjects, int maxAgeInDays, File cacheDir) {
this.maxMemoryObjects = maxMemoryObjects;
this.maxAgeInDays = maxAgeInDays;
this.cacheDir = cacheDir;
this.xstream = new XStream();
}
public synchronized T get(String name) {
T object = null;
object = objectCache.get(name);
if (object == null && cacheDir != null) {
object = readObjectFromFile(name);
}
return object;
}
public synchronized void put(String name, T object) {
if (object != null) {
objectCache.put(name, object);
if (cacheDir != null) {
writeObjectToFile(name, object);
}
}
}
private T readObjectFromFile(String id) {
T object = null;
try {
File file = getXmlFile(id);
if (file.exists() && !expired(file)) {
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
object = (T) xstream.fromXML(reader);
reader.close();
}
} catch (IOException ioe) {
System.err.println("trouble reading " + id);
} catch (BaseException e) {
System.err.println("trouble reading xml" + id);
}
return object;
}
private File getXmlFile(String id) throws IOException {
// there will likely be tens of thousands of these
// xml files, we don't want to overwhelm a diretory, so
// lets spread them out over 256 directories.'
id = id.replaceAll("/", "_");
id = id + ".obj.xml";
String dir = id.substring(0, 2).toLowerCase();
File fullPath = new File(cacheDir, dir);
if (!fullPath.exists()) {
if (!fullPath.mkdirs()) {
throw new IOException("Can't create " + fullPath);
}
}
return new File(fullPath, id);
}
/**
* Checks to see if a file is older than
* the expired time
*/
private boolean expired(File file) {
if (maxAgeInDays == 0) {
return false;
} else {
long staleTime = System.currentTimeMillis() -
maxAgeInDays * 24L * 60L * 60L * 1000L;
return (file.lastModified() < staleTime);
}
}
private void writeObjectToFile(String name, T object) {
// System.out.println("Saving to " + file);
try {
File file = getXmlFile(name);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
xstream.toXML(object, writer);
writer.close();
} catch (IOException ioe) {
System.err.println("can't save details to " + name);
}
}
class ObjectMap<V, O> extends LinkedHashMap<V, O> {
@Override
protected boolean removeEldestEntry(Map.Entry eldest) {
return size() > maxMemoryObjects;
}
}
}
| SunLabsAST/AURA | sitm/src/com/sun/labs/aura/music/web/Cache.java | Java | gpl-2.0 | 4,779 |
/**
* OWASP Benchmark Project v1.1
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>.
*
* The Benchmark is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation, version 2.
*
* The Benchmark is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details
*
* @author Nick Sanidas <a href="https://www.aspectsecurity.com">Aspect Security</a>
* @created 2015
*/
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/BenchmarkTest14514")
public class BenchmarkTest14514 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 {
javax.servlet.http.Cookie[] cookies = request.getCookies();
String param = null;
boolean foundit = false;
if (cookies != null) {
for (javax.servlet.http.Cookie cookie : cookies) {
if (cookie.getName().equals("foo")) {
param = cookie.getValue();
foundit = true;
}
}
if (!foundit) {
// no cookie found in collection
param = "";
}
} else {
// no cookies
param = "";
}
String bar = doSomething(param);
javax.servlet.http.Cookie cookie = new javax.servlet.http.Cookie("SomeCookie","SomeValue");
cookie.setSecure(false);
response.addCookie(cookie);
} // end doPost
private static String doSomething(String param) throws ServletException, IOException {
String bar;
// Simple if statement that assigns constant to bar on true condition
int i = 86;
if ( (7*42) - i > 200 )
bar = "This_should_always_happen";
else bar = param;
return bar;
}
}
| iammyr/Benchmark | src/main/java/org/owasp/benchmark/testcode/BenchmarkTest14514.java | Java | gpl-2.0 | 2,447 |
/*! LICENSE
*
* Copyright (c) 2015, The Agile Factory SA and/or its affiliates. All rights
* reserved.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; version 2 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package framework.utils;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.inject.Singleton;
import org.apache.commons.io.IOUtils;
import framework.commons.IFrameworkConstants;
import framework.services.session.IUserSessionManagerPlugin;
import framework.services.storage.IAttachmentManagerPlugin;
import models.framework_models.common.Attachment;
import play.Logger;
import play.cache.Cache;
import play.mvc.Controller;
import play.mvc.Http.MultipartFormData;
import play.mvc.Http.MultipartFormData.FilePart;
import play.mvc.Result;
/**
* An utility class which manages the extraction of uploaded (one or more) files
* from a form and the database update (with an {@link Attachment} object.<br/>
* WARNING: please see the documentation of each method. Some requires an Ebean
* transaction to be active in order to rollback the operation in case of
* exception.
*
* @author Pierre-Yves Cloux
* @author Johann Kohler
*/
@Singleton
public class FileAttachmentHelper {
private static final int AUTHZ_FILE_DURATION = 1800;
public static final String FILE_ATTRIBUTE_PREFIX = "_file_field_";
private static Logger.ALogger log = Logger.of(FileAttachmentHelper.class);
public static String getFileTypeInputName(String fieldName) {
return FILE_ATTRIBUTE_PREFIX + fieldName + "_type";
}
public static String getFileNameInputName(String fieldName) {
return FILE_ATTRIBUTE_PREFIX + fieldName + "_name";
}
public static String getFileInputName(String fieldName, FileType fileType) {
return FILE_ATTRIBUTE_PREFIX + fieldName + "_" + fileType.name();
}
/**
* Get the file type.
*
* @param fieldName
* the field name
*/
public static FileType getFileType(String fieldName) {
MultipartFormData body = Controller.request().body().asMultipartFormData();
String fileType = body.asFormUrlEncoded().get(getFileTypeInputName(fieldName))[0];
return FileType.valueOf(fileType);
}
/**
* Get the file name.
*
* @param fieldName
* the field name
*/
public static String getFileName(String fieldName) {
MultipartFormData body = Controller.request().body().asMultipartFormData();
String fileName = body.asFormUrlEncoded().get(getFileNameInputName(fieldName))[0];
FileType fileType = getFileType(fieldName);
if (fileName != null && !fileName.equals("")) {
// for UPLOAD type we add the extension
if (fileType.equals(FileType.UPLOAD)) {
String extension = "";
String[] values = getFilePart(fieldName).getFilename().split("\\.");
if (values.length > 1) {
extension = "." + values[values.length - 1];
}
fileName += extension;
}
return fileName;
} else {
switch (fileType) {
case UPLOAD:
return getFilePart(fieldName).getFilename();
case URL:
String label = getUrl(fieldName);
String[] values = label.split("/");
if (values.length > 1) {
label = values[values.length - 1];
}
return label;
default:
return null;
}
}
}
/**
* Return true if the specified form contains a valid file field.
*
* @param fieldName
* the field name
*
* @return a boolean
*/
public static boolean hasFileField(String fieldName) {
boolean r = false;
MultipartFormData body = Controller.request().body().asMultipartFormData();
if (body != null) {
FileType fileType = getFileType(fieldName);
String fileFieldName = getFileInputName(fieldName, fileType);
switch (fileType) {
case UPLOAD:
if (body.getFile(fileFieldName) != null) {
r = true;
}
break;
case URL:
if (body.asFormUrlEncoded().get(fileFieldName)[0] != null && !body.asFormUrlEncoded().get(fileFieldName)[0].equals("")) {
r = true;
}
break;
}
}
return r;
}
/**
* Get the file part of the attachment for UPLOAD type.
*
* @param fieldName
* the field name
*/
public static FilePart getFilePart(String fieldName) {
FileType fileType = getFileType(fieldName);
if (fileType.equals(FileType.UPLOAD)) {
MultipartFormData body = Controller.request().body().asMultipartFormData();
FilePart filePart = body.getFile(getFileInputName(fieldName, fileType));
return filePart;
}
return null;
}
/**
* Get the URL of the attachment for URL type.
*
* @param fieldName
* the field name
*/
public static String getUrl(String fieldName) {
FileType fileType = getFileType(fieldName);
if (fileType.equals(FileType.URL)) {
MultipartFormData body = Controller.request().body().asMultipartFormData();
return body.asFormUrlEncoded().get(getFileInputName(fieldName, fileType))[0];
}
return null;
}
/**
* Save the specified file as an attachment.
*
* @param fieldName
* the field name
* @param objectClass
* the object class
* @param objectId
* the object id
* @param attachmentPlugin
* the service which is managing attachments
*/
public static Long saveAsAttachement(String fieldName, Class<?> objectClass, Long objectId, IAttachmentManagerPlugin attachmentPlugin) throws IOException {
FileInputStream fIn = null;
try {
FileType fileType = getFileType(fieldName);
switch (fileType) {
case UPLOAD:
FilePart filePart = getFilePart(fieldName);
fIn = new FileInputStream(filePart.getFile());
return attachmentPlugin.addFileAttachment(fIn, filePart.getContentType(), getFileName(fieldName), objectClass, objectId);
case URL:
return attachmentPlugin.addUrlAttachment(getUrl(fieldName), getFileName(fieldName), objectClass, objectId);
default:
return null;
}
} catch (Exception e) {
String message = String.format("Failure while creating the attachments for : %s [class %s]", objectId, objectClass);
throw new IOException(message, e);
} finally {
IOUtils.closeQuietly(fIn);
}
}
/**
* Ensure that the specified attachment can be displayed by the end user.<br/>
* WARNING: this process is overwriting any previously set authorizations.
* @param attachementId an attachment id
* @param sessionManagerPlugin
* the service which is managing user sessions
*/
public static void authorizeFileAttachementForDisplay(Long attachementId, IUserSessionManagerPlugin sessionManagerPlugin){
Set<Long> allowedIds=new HashSet<Long>();
allowedIds.add(attachementId);
String uid = sessionManagerPlugin.getUserSessionId(Controller.ctx());
allocateReadAuthorization(allowedIds, uid);
}
/**
* Ensure that the specified attachment can be displayed by the end user.<br/>
* WARNING: this process is overwriting any previously set authorizations.
* @param attachementId an attachment id
* @param sessionManagerPlugin
* the service which is managing user sessions
*/
public static void authorizeFileAttachementForUpdate(Long attachementId, IUserSessionManagerPlugin sessionManagerPlugin){
Set<Long> allowedIds=new HashSet<Long>();
allowedIds.add(attachementId);
String uid = sessionManagerPlugin.getUserSessionId(Controller.ctx());
allocateUpdateAuthorization(allowedIds, uid);
}
/**
* Get attachments for display.<br/>
* Return a list of attachments which is to be displayed to the end user.
* <br/>
* If this method is called this means that the user is "allowed" to
* download the file.<br/>
* This methods thus generates an authorization token which contains the id
* of the attachment. This "authorization token" is set in the session of
* the user. The attachment download function will check this token before
* allowing the download. This is to prevent any unauthorized download.
*
* @param objectClass
* the object class
* @param objectId
* the object id
* @param attachmentManagerPlugin
* the service which is managing attachments
* @param sessionManagerPlugin
* the service which is managing user sessions
*/
public static List<Attachment> getFileAttachmentsForDisplay(Class<?> objectClass, Long objectId, IAttachmentManagerPlugin attachmentManagerPlugin,
IUserSessionManagerPlugin sessionManagerPlugin) {
return getFileAttachmentsForUpdateOrDisplay(objectClass, objectId, false, attachmentManagerPlugin, sessionManagerPlugin);
}
/**
* Get attachments for update.<br/>
* Return a list of attachments which is to be displayed and possibly
* updated by the end user.<br/>
* If this method is called this means that the user is "allowed" to
* download the file.<br/>
* This methods thus generates an authorization token which contains the id
* of the attachment. This "authorization token" is set in the session of
* the user. The attachment download function will check this token before
* allowing the update. This is to prevent any unauthorized update.
*
* @param objectClass
* the object class
* @param objectId
* the object id
* @param attachmentManagerPlugin
* the service which is managing attachments
* @param sessionManagerPlugin
* the service which is managing user sessions
*/
public static List<Attachment> getFileAttachmentsForUpdate(Class<?> objectClass, Long objectId, IAttachmentManagerPlugin attachmentManagerPlugin,
IUserSessionManagerPlugin sessionManagerPlugin) {
return getFileAttachmentsForUpdateOrDisplay(objectClass, objectId, true, attachmentManagerPlugin, sessionManagerPlugin);
}
/**
* Return a list of attachments for display or update.
*
* @param objectClass
* the class of the object to which the attachment belong
* @param objectId
* the id of the object to which the attachment belong
* @param canUpdate
* true if the update authorization should be allocated
* @param attachmentManagerPlugin
* the service which is managing attachments
* @param sessionManagerPlugin
* the service which is managing user sessions
*/
private static List<Attachment> getFileAttachmentsForUpdateOrDisplay(Class<?> objectClass, Long objectId, boolean canUpdate,
IAttachmentManagerPlugin attachmentManagerPlugin, IUserSessionManagerPlugin sessionManagerPlugin) {
List<Attachment> attachments = attachmentManagerPlugin.getAttachmentsFromObjectTypeAndObjectId(objectClass, objectId, false);
Set<Long> allowedIds = new HashSet<Long>();
for (Attachment attachment : attachments) {
allowedIds.add(attachment.id);
}
String uid = sessionManagerPlugin.getUserSessionId(Controller.ctx());
allocateReadAuthorization(allowedIds, uid);
if (canUpdate) {
allocateUpdateAuthorization(allowedIds, uid);
}
return attachments;
}
/**
* Add read authorization for the specified list of attachments.
*
* @param allowedIds
* a list of ids
* @param uid
* the uid of the authorized user
*/
private static void allocateReadAuthorization(Set<Long> allowedIds, String uid) {
if (Cache.get(IFrameworkConstants.ATTACHMENT_READ_AUTHZ_CACHE_PREFIX + uid) != null) {
@SuppressWarnings("unchecked")
Set<Long> otherAllowerIds = (Set<Long>) Cache.get(IFrameworkConstants.ATTACHMENT_READ_AUTHZ_CACHE_PREFIX + uid);
allowedIds.addAll(otherAllowerIds);
}
Cache.set(IFrameworkConstants.ATTACHMENT_READ_AUTHZ_CACHE_PREFIX + uid, allowedIds, AUTHZ_FILE_DURATION);
}
/**
* Add update authorization for the specified list of attachments.
*
* @param allowedIds
* a list of ids
* @param uid
* the uid of the authorized user
*/
private static void allocateUpdateAuthorization(Set<Long> allowedIds, String uid) {
if (Cache.get(IFrameworkConstants.ATTACHMENT_WRITE_AUTHZ_CACHE_PREFIX + uid) != null) {
@SuppressWarnings("unchecked")
Set<Long> otherAllowerIds = (Set<Long>) Cache.get(IFrameworkConstants.ATTACHMENT_WRITE_AUTHZ_CACHE_PREFIX + uid);
allowedIds.addAll(otherAllowerIds);
}
Cache.set(IFrameworkConstants.ATTACHMENT_WRITE_AUTHZ_CACHE_PREFIX + uid, allowedIds, AUTHZ_FILE_DURATION);
}
/**
* This method is to be integrated within a controller.<br/>
* It looks for the specified attachment and returns it if the user is
* allowed to access it.
*
* @param attachmentId
* the id of an attachment
* @param attachmentManagerPlugin
* the service which is managing attachments
* @param sessionManagerPlugin
* the service which is managing user sessions
* @return the attachment as a stream
*/
public static Result downloadFileAttachment(Long attachmentId, IAttachmentManagerPlugin attachmentManagerPlugin,
IUserSessionManagerPlugin sessionManagerPlugin) {
@SuppressWarnings("unchecked")
Set<Long> allowedIds = (Set<Long>) Cache
.get(IFrameworkConstants.ATTACHMENT_READ_AUTHZ_CACHE_PREFIX + sessionManagerPlugin.getUserSessionId(Controller.ctx()));
if (allowedIds != null && allowedIds.contains(attachmentId)) {
try {
Attachment attachment = attachmentManagerPlugin.getAttachmentFromId(attachmentId);
if (attachment.mimeType.equals(FileAttachmentHelper.FileType.URL.name())) {
return Controller.redirect(attachment.path);
} else {
Controller.response().setHeader("Content-Disposition", "attachment; filename=\"" + attachment.name + "\"");
return Controller.ok(attachmentManagerPlugin.getAttachmentContent(attachmentId));
}
} catch (IOException e) {
log.error("Error while retreiving the attachment content for " + attachmentId);
return Controller.badRequest();
}
}
return Controller.badRequest();
}
/**
* This method is to be integrated within a controller.<br/>
* It looks for the specified attachment and delete it if the user is
* allowed to erase it.<br/>
* It is to be called by an AJAX GET with a single attribute : the id of the
* attachment.
*
* @param attachmentId
* the id of an attachment
* @param attachmentManagerPlugin
* the service which is managing attachments
* @param sessionManagerPlugin
* the service which is managing user sessions
* @return the result
*/
public static Result deleteFileAttachment(Long attachmentId, IAttachmentManagerPlugin attachmentManagerPlugin,
IUserSessionManagerPlugin sessionManagerPlugin) {
@SuppressWarnings("unchecked")
Set<Long> allowedIds = (Set<Long>) Cache
.get(IFrameworkConstants.ATTACHMENT_WRITE_AUTHZ_CACHE_PREFIX + sessionManagerPlugin.getUserSessionId(Controller.ctx()));
if (allowedIds != null && allowedIds.contains(attachmentId)) {
try {
attachmentManagerPlugin.deleteAttachment(attachmentId);
return Controller.ok();
} catch (IOException e) {
log.error("Error while deleting the attachment content for " + attachmentId);
return Controller.badRequest();
}
}
return Controller.badRequest();
}
/**
* The possible file types.
*
* @author Johann Kohler
*
*/
public static enum FileType {
UPLOAD, URL;
public String getLabel() {
return Msg.get("form.input.file_field.type." + name() + ".label");
}
}
}
| theAgileFactory/app-framework | app/framework/utils/FileAttachmentHelper.java | Java | gpl-2.0 | 17,798 |
package org.cedar.onestop.user.config;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.cedar.onestop.user.domain.OnestopUser;
import org.cedar.onestop.user.service.OnestopUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.oauth2.core.DefaultOAuth2AuthenticatedPrincipal;
import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal;
import org.springframework.security.oauth2.server.resource.introspection.OpaqueTokenIntrospector;
import org.springframework.web.reactive.function.client.WebClient;
import java.util.Map;
public class UserInfoOpaqueTokenIntrospector implements OpaqueTokenIntrospector {
private static final Logger logger = LoggerFactory.getLogger(UserInfoOpaqueTokenIntrospector.class);
private final ObjectMapper mapper = new ObjectMapper();
private final WebClient rest = WebClient.create();
private final OnestopUserService userService;
public UserInfoOpaqueTokenIntrospector(OnestopUserService userService) {
this.userService = userService;
}
@Override
public OAuth2AuthenticatedPrincipal introspect(String token) {
logger.info("OAuth2AuthenticatedPrincipal introspect()");
logger.info(token);
return requestUserInfo(token);
}
private OAuth2AuthenticatedPrincipal requestUserInfo(String token) {
logger.info("Requesting OIDC profile");
String jsonUserInfo = this.rest.get()
.uri("https://idp.int.identitysandbox.gov/api/openid_connect/userinfo")
.headers(h -> h.setBearerAuth(token))
.retrieve()
.bodyToMono(String.class)
.block();
Map<String, Object> attributes = null;
try {
logger.info("Retrieved OIDC profile");
attributes = mapper.readValue(jsonUserInfo, Map.class);
logger.info(attributes.toString());
} catch (JsonProcessingException e) {
e.printStackTrace();
return null;
}
String id = attributes.get("sub").toString();
logger.info("Logging in user: " + attributes.get("sub").toString());
OnestopUser user = userService.findOrCreateUser(id);
Map<String, Object> userMap = user.toMap();
logger.info("Populating security context");
logger.info(userMap.toString());
logger.info(user.getPrivilegesAsAuthorities().toString());
userMap.put("sub", userMap.get("id"));
OAuth2AuthenticatedPrincipal principal = new DefaultOAuth2AuthenticatedPrincipal(userMap, user.getPrivilegesAsAuthorities());
return principal;
}
} | cedardevs/onestop | user/src/main/java/org/cedar/onestop/user/config/UserInfoOpaqueTokenIntrospector.java | Java | gpl-2.0 | 2,565 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package licao11;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import static java.sql.Types.NULL;
import org.lwjgl.BufferUtils;
import static org.lwjgl.opengl.GL11.GL_LINEAR;
import static org.lwjgl.opengl.GL11.GL_NO_ERROR;
import static org.lwjgl.opengl.GL11.GL_QUADS;
import static org.lwjgl.opengl.GL11.GL_RGBA;
import static org.lwjgl.opengl.GL11.GL_TEXTURE_2D;
import static org.lwjgl.opengl.GL11.GL_TEXTURE_MAG_FILTER;
import static org.lwjgl.opengl.GL11.GL_TEXTURE_MIN_FILTER;
import static org.lwjgl.opengl.GL11.GL_UNSIGNED_BYTE;
import static org.lwjgl.opengl.GL11.glBegin;
import static org.lwjgl.opengl.GL11.glBindTexture;
import static org.lwjgl.opengl.GL11.glEnd;
import static org.lwjgl.opengl.GL11.glGetError;
import static org.lwjgl.opengl.GL11.glLoadIdentity;
import static org.lwjgl.opengl.GL11.glTexCoord2f;
import static org.lwjgl.opengl.GL11.glTexParameteri;
import static org.lwjgl.opengl.GL11.glTranslatef;
import static org.lwjgl.opengl.GL11.glVertex2f;
import org.newdawn.slick.opengl.PNGDecoder;
import static org.lwjgl.opengl.GL11.glDeleteTextures;
import static org.lwjgl.opengl.GL11.glGenTextures;
import static org.lwjgl.opengl.GL11.glTexImage2D;
/**
*
* @author nynha
*/
public class LTexture11 {
public int mTextureID = 0;
//Initialize texture dimensions
public int mTextureWidth = 0;
public int mTextureHeight = 0;
public boolean loadTextureFromFile(String caminho) throws IOException
{
freeTexture();
boolean textureLoaded = false;
PNGDecoder decoder = new PNGDecoder(new FileInputStream(caminho));
ByteBuffer buffer = BufferUtils.createByteBuffer(4 * decoder.getWidth() * decoder.getHeight());
decoder.decode(buffer, decoder.getWidth() * 4, PNGDecoder.RGBA);
// buffer.flip();
mTextureWidth = decoder.getWidth();
mTextureHeight = decoder.getHeight();
textureLoaded = loadTextureFromPixels32(buffer, mTextureWidth, mTextureHeight);
return textureLoaded;
}
public boolean loadTextureFromPixels32(ByteBuffer buffer, int width, int height)
{
//Free texture if it exists
freeTexture();
//Get texture dimensions
mTextureWidth = width;
mTextureHeight = height;
//Generate texture glGenTextures( 1, &mTextureID );ID
mTextureID = glGenTextures();
//Bind texture ID
glBindTexture(GL_TEXTURE_2D, mTextureID);
//Generate texture
buffer.flip();
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer);
//Set texture parameters
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
//Unbind texture
glBindTexture(GL_TEXTURE_2D, NULL);
//Checagem de erros
int erro = glGetError();
if(erro != GL_NO_ERROR)
{
System.out.println("Erro de pixels");
return false;
}
return true;
}
public void freeTexture()
{
//Delete texture
if(mTextureID != 0)
{
glDeleteTextures(mTextureID);
mTextureID = 0;
}
mTextureWidth = 0;
mTextureHeight = 0;
}
public void render(float x, float y, LFRect stretch)
{
//If the texture exists
if( mTextureID != 0 )
{
//Remove any previous transformations
glLoadIdentity();
//Texture coordinates
float texTop = 0.f;
float texBottom = 1.f;
float texLeft = 0.f;
float texRight = 1.f;
//Vertex coordinates
float quadWidth = mTextureWidth;
float quadHeight = mTextureHeight;
//Handle Stretching
if(stretch != null)
{
quadWidth = stretch.w;
quadHeight = stretch.h;
}
//Move to rendering point
glTranslatef(x, y, 0.f);
//Set texture ID
glBindTexture(GL_TEXTURE_2D, mTextureID);
//Render textured quad
glBegin(GL_QUADS);
glTexCoord2f(texLeft, texTop);
glVertex2f(0.f, 0.f);
glTexCoord2f(texRight, texTop);
glVertex2f(quadWidth, 0.f);
glTexCoord2f(texRight, texBottom);
glVertex2f(quadWidth, quadHeight);
glTexCoord2f(texLeft, texBottom);
glVertex2f(0.f, quadHeight);
glEnd();
}
}
public int getTextureID()
{
return mTextureID;
}
public int textureWidth()
{
return mTextureWidth;
}
public int textureHeight()
{
return mTextureHeight;
}
}
| swamilima/Tutoriais-CG-Java-LWJGL-2.9.x | Codigos_Java-LWJGL/Licao11/src/licao11/LTexture11.java | Java | gpl-2.0 | 5,116 |
/*
* Copyright (c) 2020, OpenCloudDB/MyCAT and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software;Designed and Developed mainly by many Chinese
* opensource volunteers. 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.
*
* Any questions about this component can be directed to it's project Web address
* https://code.google.com/p/opencloudb/.
*
*/
package io.mycat.route;
import com.alibaba.druid.sql.ast.SQLStatement;
import io.mycat.config.model.SchemaConfig;
import io.mycat.route.parser.util.PageSQLUtil;
import io.mycat.sqlengine.mpp.HavingCols;
import io.mycat.util.FormatUtil;
import java.io.Serializable;
import java.util.*;
import java.util.Map.Entry;
/**
* @author mycat
*/
public final class RouteResultset implements Serializable {
private String statement; // 原始语句
private final int sqlType;
private RouteResultsetNode[] nodes; // 路由结果节点
private Set<String> subTables;
private SQLStatement sqlStatement;
private int limitStart;
private boolean cacheAble;
// used to store table's ID->datanodes cache
// format is table.primaryKey
private String primaryKey;
// limit output total
private int limitSize;
private SQLMerge sqlMerge;
private boolean callStatement = false; // 处理call关键字
// 是否为全局表,只有在insert、update、delete、ddl里会判断并修改。默认不是全局表,用于修正全局表修改数据的反馈。
private boolean globalTableFlag = false;
//是否完成了路由
private boolean isFinishedRoute = false;
//是否自动提交,此属性主要用于记录ServerConnection上的autocommit状态
private boolean autocommit = true;
private boolean isLoadData=false;
//是否可以在从库运行,此属性主要供RouteResultsetNode获取
private Boolean canRunInReadDB;
// 强制走 master,可以通过 RouteResultset的属性canRunInReadDB=false
// 传给 RouteResultsetNode 来实现,但是 强制走 slave需要增加一个属性来实现:
private Boolean runOnSlave = null; // 默认null表示不施加影响
//key=dataNode value=slot
private Map<String,Integer> dataNodeSlotMap=new HashMap<>();
private boolean selectForUpdate;
private boolean autoIncrement;
private Map<String, List<String>> subTableMaps;
public boolean isSelectForUpdate() {
return selectForUpdate;
}
public void setSelectForUpdate(boolean selectForUpdate) {
this.selectForUpdate = selectForUpdate;
}
private List<String> tables;
public List<String> getTables() {
return tables;
}
public void setTables(List<String> tables) {
this.tables = tables;
}
public Map<String, Integer> getDataNodeSlotMap() {
return dataNodeSlotMap;
}
public void setDataNodeSlotMap(Map<String, Integer> dataNodeSlotMap) {
this.dataNodeSlotMap = dataNodeSlotMap;
}
public Boolean getRunOnSlave() {
return runOnSlave;
}
public String getRunOnSlaveDebugInfo() {
return runOnSlave == null?"default":Boolean.toString(runOnSlave);
}
public void setRunOnSlave(Boolean runOnSlave) {
this.runOnSlave = runOnSlave;
}
private Procedure procedure;
public Procedure getProcedure()
{
return procedure;
}
public void setProcedure(Procedure procedure)
{
this.procedure = procedure;
}
public boolean isLoadData()
{
return isLoadData;
}
public void setLoadData(boolean isLoadData)
{
this.isLoadData = isLoadData;
}
public boolean isFinishedRoute() {
return isFinishedRoute;
}
public void setFinishedRoute(boolean isFinishedRoute) {
this.isFinishedRoute = isFinishedRoute;
}
public boolean isGlobalTable() {
return globalTableFlag;
}
public void setGlobalTable(boolean globalTableFlag) {
this.globalTableFlag = globalTableFlag;
}
public RouteResultset(String stmt, int sqlType) {
this.statement = stmt;
this.limitSize = -1;
this.sqlType = sqlType;
}
public void resetNodes() {
if (nodes != null) {
for (RouteResultsetNode node : nodes) {
node.resetStatement();
}
}
}
public void copyLimitToNodes() {
if(nodes!=null)
{
for (RouteResultsetNode node : nodes)
{
if(node.getLimitSize()==-1&&node.getLimitStart()==0)
{
node.setLimitStart(limitStart);
node.setLimitSize(limitSize);
}
}
}
}
public SQLMerge getSqlMerge() {
return sqlMerge;
}
public boolean isCacheAble() {
return cacheAble;
}
public void setCacheAble(boolean cacheAble) {
this.cacheAble = cacheAble;
}
public boolean needMerge() {
return limitSize > 0 || sqlMerge != null;
}
public int getSqlType() {
return sqlType;
}
public boolean isHasAggrColumn() {
return (sqlMerge != null) && sqlMerge.isHasAggrColumn();
}
public int getLimitStart() {
return limitStart;
}
public String[] getGroupByCols() {
return (sqlMerge != null) ? sqlMerge.getGroupByCols() : null;
}
private SQLMerge createSQLMergeIfNull() {
if (sqlMerge == null) {
sqlMerge = new SQLMerge();
}
return sqlMerge;
}
public Map<String, Integer> getMergeCols() {
return (sqlMerge != null) ? sqlMerge.getMergeCols() : null;
}
public void setLimitStart(int limitStart) {
this.limitStart = limitStart;
}
public String getPrimaryKey() {
return primaryKey;
}
public boolean hasPrimaryKeyToCache() {
return primaryKey != null;
}
public void setPrimaryKey(String primaryKey) {
if (!primaryKey.contains(".")) {
throw new java.lang.IllegalArgumentException(
"must be table.primarykey fomat :" + primaryKey);
}
this.primaryKey = primaryKey;
}
/**
* return primary key items ,first is table name ,seconds is primary key
*
* @return
*/
public String[] getPrimaryKeyItems() {
return primaryKey.split("\\.");
}
public void setOrderByCols(LinkedHashMap<String, Integer> orderByCols) {
if (orderByCols != null && !orderByCols.isEmpty()) {
createSQLMergeIfNull().setOrderByCols(orderByCols);
}
}
public void setHasAggrColumn(boolean hasAggrColumn) {
if (hasAggrColumn) {
createSQLMergeIfNull().setHasAggrColumn(true);
}
}
public void setGroupByCols(String[] groupByCols) {
if (groupByCols != null && groupByCols.length > 0) {
createSQLMergeIfNull().setGroupByCols(groupByCols);
}
}
public void setMergeCols(Map<String, Integer> mergeCols) {
if (mergeCols != null && !mergeCols.isEmpty()) {
createSQLMergeIfNull().setMergeCols(mergeCols);
}
}
public LinkedHashMap<String, Integer> getOrderByCols() {
return (sqlMerge != null) ? sqlMerge.getOrderByCols() : null;
}
public String getStatement() {
return statement;
}
public RouteResultsetNode[] getNodes() {
return nodes;
}
public void setNodes(RouteResultsetNode[] nodes) {
if(nodes!=null)
{
int nodeSize=nodes.length;
for (RouteResultsetNode node : nodes)
{
node.setTotalNodeSize(nodeSize);
}
}
this.nodes = nodes;
}
/**
* @return -1 if no limit
*/
public int getLimitSize() {
return limitSize;
}
public void setLimitSize(int limitSize) {
this.limitSize = limitSize;
}
public void setStatement(String statement) {
this.statement = statement;
}
public boolean isCallStatement() {
return callStatement;
}
public void setCallStatement(boolean callStatement) {
this.callStatement = callStatement;
if(nodes!=null)
{
for (RouteResultsetNode node : nodes)
{
node.setCallStatement(callStatement);
}
}
}
public void changeNodeSqlAfterAddLimit(SchemaConfig schemaConfig, String sourceDbType, String sql, int offset, int count, boolean isNeedConvert) {
if (nodes != null)
{
Map<String, String> dataNodeDbTypeMap = schemaConfig.getDataNodeDbTypeMap();
Map<String, String> sqlMapCache = new HashMap<>();
for (RouteResultsetNode node : nodes)
{
String dbType = dataNodeDbTypeMap.get(node.getName());
if (dbType.equalsIgnoreCase("mysql"))
{
node.setStatement(sql); //mysql之前已经加好limit
} else if (sqlMapCache.containsKey(dbType))
{
node.setStatement(sqlMapCache.get(dbType));
} else if(isNeedConvert)
{
String nativeSql = PageSQLUtil.convertLimitToNativePageSql(dbType, sql, offset, count);
sqlMapCache.put(dbType, nativeSql);
node.setStatement(nativeSql);
} else {
node.setStatement(sql);
}
node.setLimitStart(offset);
node.setLimitSize(count);
}
}
}
public boolean isAutocommit() {
return autocommit;
}
public void setAutocommit(boolean autocommit) {
this.autocommit = autocommit;
}
public Boolean getCanRunInReadDB() {
return canRunInReadDB;
}
public void setCanRunInReadDB(Boolean canRunInReadDB) {
this.canRunInReadDB = canRunInReadDB;
}
public HavingCols getHavingCols() {
return (sqlMerge != null) ? sqlMerge.getHavingCols() : null;
}
public void setSubTables(Set<String> subTables) {
this.subTables = subTables;
}
public void setHavings(HavingCols havings) {
if (havings != null) {
createSQLMergeIfNull().setHavingCols(havings);
}
}
// Added by winbill, 20160314, for having clause, Begin ==>
public void setHavingColsName(Object[] names) {
if (names != null && names.length > 0) {
createSQLMergeIfNull().setHavingColsName(names);
}
}
// Added by winbill, 20160314, for having clause, End <==
public SQLStatement getSqlStatement() {
return this.sqlStatement;
}
public void setSqlStatement(SQLStatement sqlStatement) {
this.sqlStatement = sqlStatement;
}
public Set<String> getSubTables() {
return this.subTables;
}
public boolean isDistTable(){
if(this.getSubTables()!=null && !this.getSubTables().isEmpty() ){
return true;
}
return false;
}
@Override
public String toString() {
StringBuilder s = new StringBuilder();
s.append(statement).append(", route={");
if (nodes != null) {
for (int i = 0; i < nodes.length; ++i) {
s.append("\n ").append(FormatUtil.format(i + 1, 3));
s.append(" -> ").append(nodes[i]);
}
}
s.append("\n}");
return s.toString();
}
public void setAutoIncrement(boolean b) {
autoIncrement = b;
}
public boolean getAutoIncrement() {
return autoIncrement;
}
public Map<String, List<String>> getSubTableMaps() {
return subTableMaps;
}
public void setSubTableMaps(Map<String, List<String>> subTableMaps) {
this.subTableMaps = subTableMaps;
}
/**
* 合并路由节点相同的节点
*/
public void mergeSameNode() {
Map<String, RouteResultsetNode> mapNodes = new HashMap<>(64);
for (RouteResultsetNode node : nodes) {
if (mapNodes.containsKey(node.getName())) {
// merge node
RouteResultsetNode tmpNode = mapNodes.get(node.getName());
tmpNode.setStatement(tmpNode.getStatement() + ";" + node.getStatement());
} else {
mapNodes.put(node.getName(), node);
}
}
RouteResultsetNode[] newNodes = new RouteResultsetNode[mapNodes.size()];
int i = 0;
for (Entry<String, RouteResultsetNode> entry : mapNodes.entrySet()) {
newNodes[i++] = entry.getValue();
}
this.setNodes(newNodes);
}
}
| MyCATApache/Mycat-Server | src/main/java/io/mycat/route/RouteResultset.java | Java | gpl-2.0 | 13,374 |
package icoor.web.db;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for select1 complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="select1">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "select1")
public class Select1 {
}
| Exiliot/department-coordinator | iCoorClient/src/icoor/web/db/Select1.java | Java | gpl-2.0 | 692 |
package com.example.nikola.cloud;
/**
* Created by nikola on 13.04.16..
*/
import android.content.Context;
import android.view.LayoutInflater;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.Collections;
import java.util.List;
public class NavigationDrawerAdapter extends RecyclerView.Adapter<NavigationDrawerAdapter.MyViewHolder> {
List<NavDrawerItem> data = Collections.emptyList();
private LayoutInflater inflater;
private Context context;
public NavigationDrawerAdapter(Context context, List<NavDrawerItem> data) {
this.context = context;
inflater = LayoutInflater.from(context);
this.data = data;
}
public void delete(int position) {
data.remove(position);
notifyItemRemoved(position);
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.nav_drawer_row, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
NavDrawerItem current = data.get(position);
holder.title.setText(current.getTitle());
}
@Override
public int getItemCount() {
return data.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView title;
public MyViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.title);
}
}
}
| GlavinaNikola/HappyCloud | Cloud/app/src/main/java/com/example/nikola/cloud/NavigationDrawerAdapter.java | Java | gpl-2.0 | 1,644 |
package pl.djvuhtml5.client;
import java.util.Arrays;
import java.util.List;
import com.google.gwt.canvas.client.Canvas;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.dom.client.Element;
import com.google.gwt.i18n.client.Dictionary;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.Widget;
import com.lizardtech.djvu.DjVuInfo;
import com.lizardtech.djvu.GMap;
import com.lizardtech.djvu.Utils;
import com.lizardtech.djvu.text.DjVuText;
import pl.djvuhtml5.client.TileRenderer.TileInfo;
import pl.djvuhtml5.client.ui.Scrollbar;
import pl.djvuhtml5.client.ui.SinglePageLayout;
import pl.djvuhtml5.client.ui.TextLayer;
import pl.djvuhtml5.client.ui.Toolbar;
import pl.djvuhtml5.client.ui.UIHider;
/**
* Entry point classes define <code>onModuleLoad()</code>.
*/
public class Djvu_html5 implements EntryPoint {
private static final String WELCOME_MESSAGE =
"Starting djvu-html5 viewer v0.3.0-beta1 from https://github.com/mateusz-matela/djvu-html5";
private static final String CONTEXT_GLOBAL_VARIABLE = "DJVU_CONTEXT";
private static final List<String> STATUS_IMAGE_ORDER = Arrays.asList(ProcessingContext.STATUS_LOADING,
ProcessingContext.STATUS_ERROR);
private static Djvu_html5 instance;
private Dictionary context;
private RootPanel container;
private Canvas canvas;
private SinglePageLayout pageLayout;
private TextLayer textLayer;
private Toolbar toolbar;
private Scrollbar horizontalScrollbar;
private Scrollbar verticalScrollbar;
private DataStore dataStore;
private BackgroundProcessor backgroundProcessor;
private Label statusImage;
private String currentStatus;
/**
* This is the entry point method.
*/
@Override
public void onModuleLoad() {
log(WELCOME_MESSAGE);
container = RootPanel.get("djvuContainer");
String url = Window.Location.getParameter("file");
if (url == null || url.isEmpty())
url = container.getElement().getAttribute("file");
if (url == null || url.isEmpty())
url = DjvuContext.getIndexFile();
if (url == null || url.isEmpty()) {
log("ERROR: No djvu file defined");
return;
}
DjvuContext.setUrl(Utils.url(GWT.getHostPageBaseURL(), url));
dataStore = new DataStore();
container.add(prepareCanvas());
container.add(textLayer = new TextLayer(this));
container.add(toolbar = new Toolbar());
container.add(horizontalScrollbar = new Scrollbar(true));
container.add(verticalScrollbar = new Scrollbar(false));
container.add(statusImage = new Label());
statusImage.setStyleName("statusImage");
int uiHideDelay = DjvuContext.getUiHideDelay();
if (uiHideDelay > 0) {
UIHider uiHider = new UIHider(uiHideDelay, textLayer);
uiHider.addUIElement(toolbar, "toolbarHidden");
uiHider.addUIElement(horizontalScrollbar, "scrollbarHidden");
uiHider.addUIElement(verticalScrollbar, "scrollbarHidden");
}
if (DjvuContext.getUseWebWorkers() && BackgroundWorker.isAvailable()) {
BackgroundWorker.init(new MainProcessingContext());
} else {
backgroundProcessor = new BackgroundProcessor(new MainProcessingContext());
}
pageLayout = new SinglePageLayout(this);
toolbar.setPageLayout(pageLayout);
}
private Widget prepareCanvas() {
canvas = Canvas.createIfSupported();
if (canvas == null) {
// TODO
throw new RuntimeException("Canvas not supported!");
}
canvas.setTabIndex(0);
final SimplePanel panel = new SimplePanel(canvas);
panel.setStyleName("content");
Window.addResizeHandler(e -> resizeCanvas());
Scheduler.get().scheduleFinally(() -> resizeCanvas());
return panel;
}
private void resizeCanvas() {
Widget panel = canvas.getParent();
int width = panel.getOffsetWidth();
int height = panel.getOffsetHeight();
canvas.setWidth(width + "px");
canvas.setCoordinateSpaceWidth(width);
canvas.setHeight(height + "px");
canvas.setCoordinateSpaceHeight(height);
if (pageLayout != null)
pageLayout.canvasResized();
}
public RootPanel getContainer() {
return container;
}
public Canvas getCanvas() {
return canvas;
}
public DataStore getDataStore() {
return dataStore;
}
private void setStatus(String status) {
if (status == currentStatus)
return;
statusImage.setVisible(status != null);
if (status != null && !ProcessingContext.STATUS_ERROR.equals(currentStatus)) {
int imagePosition = STATUS_IMAGE_ORDER.indexOf(status);
statusImage.getElement().getStyle().setProperty("backgroundPosition",
-imagePosition * statusImage.getOffsetHeight() + "px 0px");
}
if (status == null || !ProcessingContext.STATUS_ERROR.equals(currentStatus))
currentStatus = status;
}
public SinglePageLayout getPageLayout() {
return pageLayout;
}
/** @return current text layer or {@code null} if disabled. */
public TextLayer getTextLayer() {
return textLayer;
}
public Toolbar getToolbar() {
return toolbar;
}
public Scrollbar getHorizontalScrollbar() {
return horizontalScrollbar;
}
public Scrollbar getVerticalScrollbar() {
return verticalScrollbar;
}
public static native void log(String message) /*-{
console.log(message);
}-*/;
public static native String getComputedStyleProperty(Element element, String property) /*-{
var cs = $doc.defaultView.getComputedStyle(element, null);
return cs.getPropertyValue(property);
}-*/;
private class MainProcessingContext implements ProcessingContext {
@Override
public void setStatus(String status) {
Djvu_html5.this.setStatus(status);
}
@Override
public void startProcessing() {
backgroundProcessor.start();
}
@Override
public void interruptProcessing() {
backgroundProcessor.interrupt();
}
@Override
public void setPageCount(int pageCount) {
dataStore.setPageCount(pageCount);
}
@Override
public void setPageInfo(int pageNum, DjVuInfo info) {
dataStore.setPageInfo(pageNum, info);
}
@Override
public void setText(int pageNum, DjVuText text) {
dataStore.setText(pageNum, text);
}
@Override
public void setTile(TileInfo tileInfo, GMap bufferGMap) {
dataStore.setTile(tileInfo, bufferGMap);
}
@Override
public void releaseTileImages(List<TileInfo> tiles) {
dataStore.releaseTileImages(tiles);
}
}
}
| mateusz-matela/djvu-html5 | djvu-html5/src/pl/djvuhtml5/client/Djvu_html5.java | Java | gpl-2.0 | 6,434 |
package games.strategy.util;
/**
* Designed to remove/replace<br>
* / \b \n \r \t \0 \f ` ? * \ < > | " ' : . , ^ [ ] = + ;
*
* @author Mark Christopher Duncan (veqryn)
*
*/
public class IllegalCharacterRemover
{
private static final char[] ILLEGAL_CHARACTERS = { '/', '\b', '\n', '\r', '\t', '\0', '\f', '`', '?', '*', '\\', '<', '>', '|', '\"', '\'', ':', '.', ',', '^', '[', ']', '=', '+', ';' };
/**
* Designed to remove / \b \n \r \t \0 \f ` ? * \ < > | " ' : . , ^ [ ] = + ;
*
* @param text
* @return
*/
public static String removeIllegalCharacter(final String text)
{
final StringBuilder rVal = new StringBuilder();
for (int i = 0; i < text.length(); ++i)
{
if (!isIllegalFileNameChar(text.charAt(i)))
rVal.append(text.charAt(i));
}
return rVal.toString();
}
/**
* Designed to replace / \b \n \r \t \0 \f ` ? * \ < > | " ' : . , ^ [ ] = + ;
*
* @param text
* @param replacement
* @return
*/
public static String replaceIllegalCharacter(final String text, final char replacement)
{
final StringBuilder rVal = new StringBuilder();
for (int i = 0; i < text.length(); ++i)
{
if (!isIllegalFileNameChar(text.charAt(i)))
rVal.append(text.charAt(i));
else
rVal.append(replacement);
}
return rVal.toString();
}
private static boolean isIllegalFileNameChar(final char c)
{
boolean isIllegal = false;
for (int i = 0; i < ILLEGAL_CHARACTERS.length; i++)
{
if (c == ILLEGAL_CHARACTERS[i])
{
isIllegal = true;
break;
}
}
return isIllegal;
}
}
| tea-dragon/triplea | src/main/java/games/strategy/util/IllegalCharacterRemover.java | Java | gpl-2.0 | 1,556 |
/*
* Copyright (C) 2016-2022 ActionTech.
* License: http://www.gnu.org/licenses/gpl.html GPL version 2 or higher.
*/
package com.actiontech.dble.services.manager.response;
import com.actiontech.dble.DbleServer;
import com.actiontech.dble.backend.mysql.PacketUtil;
import com.actiontech.dble.config.Fields;
import com.actiontech.dble.config.model.user.UserConfig;
import com.actiontech.dble.config.model.user.UserName;
import com.actiontech.dble.net.mysql.*;
import com.actiontech.dble.services.manager.ManagerService;
import com.actiontech.dble.util.StringUtil;
import java.nio.ByteBuffer;
import java.util.Map;
public final class ShowWhiteHost {
private ShowWhiteHost() {
}
private static final int FIELD_COUNT = 2;
private static final ResultSetHeaderPacket HEADER = PacketUtil.getHeader(FIELD_COUNT);
private static final FieldPacket[] FIELDS = new FieldPacket[FIELD_COUNT];
private static final EOFPacket EOF = new EOFPacket();
static {
int i = 0;
byte packetId = 0;
HEADER.setPacketId(++packetId);
FIELDS[i] = PacketUtil.getField("IP", Fields.FIELD_TYPE_VARCHAR);
FIELDS[i++].setPacketId(++packetId);
FIELDS[i] = PacketUtil.getField("USER", Fields.FIELD_TYPE_VARCHAR);
FIELDS[i].setPacketId(++packetId);
EOF.setPacketId(++packetId);
}
public static void execute(ManagerService service) {
ByteBuffer buffer = service.allocate();
// write header
buffer = HEADER.write(buffer, service, true);
// write fields
for (FieldPacket field : FIELDS) {
buffer = field.write(buffer, service, true);
}
// write eof
buffer = EOF.write(buffer, service, true);
// write rows
byte packetId = EOF.getPacketId();
Map<UserName, UserConfig> map = DbleServer.getInstance().getConfig().getUsers();
for (Map.Entry<UserName, UserConfig> entry : map.entrySet()) {
if (entry.getValue().getWhiteIPs().size() > 0) {
for (String whiteIP : entry.getValue().getWhiteIPs()) {
RowDataPacket row = getRow(whiteIP, entry.getKey().toString(), service.getCharset().getResults());
row.setPacketId(++packetId);
buffer = row.write(buffer, service, true);
}
}
}
// write last eof
EOFRowPacket lastEof = new EOFRowPacket();
lastEof.setPacketId(++packetId);
lastEof.write(buffer, service);
}
private static RowDataPacket getRow(String ip, String user, String charset) {
RowDataPacket row = new RowDataPacket(FIELD_COUNT);
row.add(StringUtil.encode(ip, charset));
row.add(StringUtil.encode(user, charset));
return row;
}
}
| actiontech/dble | src/main/java/com/actiontech/dble/services/manager/response/ShowWhiteHost.java | Java | gpl-2.0 | 2,816 |
package ca.ualberta.cs.mrijlaar_reflex;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class Buzz3PActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_buzz_3p);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_buzz3, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
| MRijlaar/mrijlaar-reflexNew | app/src/main/java/ca/ualberta/cs/mrijlaar_reflex/Buzz3PActivity.java | Java | gpl-2.0 | 1,134 |
package com.itcse.databinding_m.ViewHolder;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import com.itcse.databinding_m.POJO.SimpleInfo;
import com.itcse.databinding_m.databinding.RecycleviewChildBinding;
/**
* View Holder class extending RecycleView's ViewHolder.
*/
public class SimpleViewHolder extends RecyclerView.ViewHolder {
RecycleviewChildBinding recycleviewChildBinding;
// Construction to get the ViewDataBinding object
public SimpleViewHolder(final RecycleviewChildBinding recycleviewChildBinding) {
super(recycleviewChildBinding.getRoot());
this.recycleviewChildBinding = recycleviewChildBinding;
}
// Setting the SimpleInfo class in the ViewDataBinding adapter. The ViewDataBinding adapter will
// then automatically populate Views on the basis of data members of the SimpleInfo class.
public void bindConnection(final SimpleInfo simpleInfo) {
recycleviewChildBinding.setSimpleInfo(simpleInfo);
}
}
| rohankandwal/Marshmallow-Databinding-w-RecyclerView | app/src/main/java/com/itcse/databinding_m/ViewHolder/SimpleViewHolder.java | Java | gpl-2.0 | 1,006 |
/*
* File : PRUDPPacketReplyAnnounce.java
* Created : 20-Jan-2004
* By : parg
*
* Azureus - a Java Bittorrent client
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details ( see the LICENSE file ).
*
* 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 org.gudy.azureus2.core3.tracker.protocol.udp;
/**
* @author parg
*
*/
import com.aelitis.net.udp.uc.PRUDPPacketReply;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
public class
PRUDPPacketReplyAnnounce
extends PRUDPPacketReply
{
protected int interval;
protected static final int BYTES_PER_ENTRY = 6;
protected int[] addresses;
protected short[] ports;
public
PRUDPPacketReplyAnnounce(
int trans_id )
{
super( PRUDPPacketTracker.ACT_REPLY_ANNOUNCE, trans_id );
}
protected
PRUDPPacketReplyAnnounce(
DataInputStream is,
int trans_id )
throws IOException
{
super( PRUDPPacketTracker.ACT_REPLY_ANNOUNCE, trans_id );
interval = is.readInt();
addresses = new int[is.available()/BYTES_PER_ENTRY];
ports = new short[addresses.length];
for (int i=0;i<addresses.length;i++){
addresses[i] = is.readInt();
ports[i] = is.readShort();
}
}
public void
setInterval(
int value )
{
interval = value;
}
public int
getInterval()
{
return( interval );
}
public void
setPeers(
int[] _addresses,
short[] _ports )
{
addresses = _addresses;
ports = _ports;
}
public int[]
getAddresses()
{
return( addresses );
}
public short[]
getPorts()
{
return( ports );
}
public void
serialise(
DataOutputStream os )
throws IOException
{
super.serialise(os);
os.writeInt( interval );
if ( addresses != null ){
for (int i=0;i<addresses.length;i++){
os.writeInt( addresses[i] );
os.writeShort( ports[i] );
}
}
}
public String
getString()
{
return( super.getString().concat("[interval=").concat(String.valueOf(interval)).concat(", addresses=").concat(String.valueOf(addresses.length)).concat("]") );
}
}
| thangbn/Direct-File-Downloader | src/src/org/gudy/azureus2/core3/tracker/protocol/udp/PRUDPPacketReplyAnnounce.java | Java | gpl-2.0 | 2,647 |
/**
* Copyright (c) 2009--2010 Red Hat, Inc.
*
* This software is licensed to you under the GNU General Public License,
* version 2 (GPLv2). There is NO WARRANTY for this software, express or
* implied, including the implied warranties of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
* along with this software; if not, see
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
*
* Red Hat trademarks are not licensed under GPLv2. No permission is
* granted to use or replicate Red Hat trademarks that are incorporated
* in this software or its documentation.
*/
package com.redhat.rhn.common.errors;
import com.redhat.rhn.common.conf.Config;
import com.redhat.rhn.common.conf.ConfigDefaults;
import com.redhat.rhn.common.hibernate.LookupException;
import com.redhat.rhn.common.messaging.MessageQueue;
import com.redhat.rhn.domain.user.User;
import com.redhat.rhn.frontend.events.TraceBackEvent;
import com.redhat.rhn.frontend.struts.RequestContext;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ExceptionHandler;
import javax.servlet.http.HttpServletRequest;
/**
* LookupExceptionHandler
* @version $Rev$
*/
public class LookupExceptionHandler extends ExceptionHandler {
private LookupException exception;
/**
* {@inheritDoc}
*/
protected void logException(Exception ex) {
Logger log = Logger.getLogger(LookupExceptionHandler.class);
exception = (LookupException) ex;
log.warn(exception.getMessage());
}
protected void storeException(HttpServletRequest request, String property,
ActionMessage msg, ActionForward forward, String scope) {
if (Config.get().getBoolean(ConfigDefaults.LOOKUP_EXCEPT_SEND_EMAIL)) {
TraceBackEvent evt = new TraceBackEvent();
RequestContext requestContext = new RequestContext(request);
User usr = requestContext.getLoggedInUser();
evt.setUser(usr);
evt.setRequest(request);
evt.setException(exception);
MessageQueue.publish(evt);
}
request.setAttribute("error", exception);
}
}
| colloquium/spacewalk | java/code/src/com/redhat/rhn/common/errors/LookupExceptionHandler.java | Java | gpl-2.0 | 2,296 |
package es.indra.formacion.springmvc.validator;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import es.indra.formacion.springmvc.model.Producto;
@Component
public class ProductoValidator implements Validator {
@Override
public boolean supports(Class<?> clase) {
return Producto.class.equals(clase);
}
@Override
public void validate(Object obj, Errors errores) {
Producto p = (Producto) obj;
ValidationUtils.rejectIfEmptyOrWhitespace(errores, "nombre", "producto.error.nombreInvalido");
ValidationUtils.rejectIfEmptyOrWhitespace(errores, "precio", "producto.error.precioInvalido");
if (p.getPrecio() != null && p.getPrecio() <= 0)
errores.rejectValue("precio", "producto.error.precioMenorQue0");
}
}
| camposer/curso_springmvc | TiendaWeb/src/es/indra/formacion/springmvc/validator/ProductoValidator.java | Java | gpl-2.0 | 883 |
/*
* $RCSfile$
*
* Copyright 2005-2008 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. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun 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 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.
*
* $Revision: 892 $
* $Date: 2008-02-28 20:18:01 +0000 (Thu, 28 Feb 2008) $
* $State$
*/
package javax.media.j3d;
import javax.vecmath.*;
/**
* The ShaderAttributeRetained object encapsulates a uniform attribute for a
* shader programs.
*/
abstract class ShaderAttributeRetained extends NodeComponentRetained {
/**
* Name of the shader attribute (immutable)
*/
String attrName;
/**
* Package scope constructor
*/
ShaderAttributeRetained() {
}
void initializeAttrName(String attrName) {
this.attrName = attrName;
}
/**
* Retrieves the name of this shader attribute.
*
* @return the name of this shader attribute
*/
String getAttributeName() {
return attrName;
}
void initMirrorObject() {
((ShaderAttributeObjectRetained)mirror).initializeAttrName(this.attrName);
}
}
| philipwhiuk/j3d-core | src/classes/share/javax/media/j3d/ShaderAttributeRetained.java | Java | gpl-2.0 | 2,094 |
package domination.fftoolbox.scraper;
import java.util.List;
import org.junit.Test;
import domination.common.Player;
/**
* Test classes for the FFToolboxKeyGenerator
*/
public class FFToolboxKeyGeneratorTest {
@Test
public void printKeys() {
List<Player> players = FFToolboxDriver.readPlayers(1, "");
for (Player player : players) {
System.out.println(player.getKey());
}
}
}
| zyfrain/domination | FFToolboxScraper/test/domination/fftoolbox/scraper/FFToolboxKeyGeneratorTest.java | Java | gpl-2.0 | 396 |
/* ========================================================================
* JCommon : a free general purpose class library for the Java(tm) platform
* ========================================================================
*
* (C) Copyright 2000-2005, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jcommon/index.html
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Java is a trademark or registered trademark of Sun Microsystems, Inc.
* in the United States and other countries.]
*
* ----------------------
* RefineryUtilities.java
* ----------------------
* (C) Copyright 2000-2005, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): Jon Iles;
*
* $Id: RefineryUtilities.java,v 1.10 2007/05/21 17:13:59 taqua Exp $
*
* Changes (from 26-Oct-2001)
* --------------------------
* 26-Oct-2001 : Changed package to com.jrefinery.ui.*;
* 26-Nov-2001 : Changed name to SwingRefinery.java to make it obvious that this is not part of
* the Java APIs (DG);
* 10-Dec-2001 : Changed name (again) to JRefineryUtilities.java (DG);
* 28-Feb-2002 : Moved system properties classes into com.jrefinery.ui.about (DG);
* 19-Apr-2002 : Renamed JRefineryUtilities-->RefineryUtilities. Added drawRotatedString()
* method (DG);
* 21-May-2002 : Changed frame positioning methods to accept Window parameters, as suggested by
* Laurence Vanhelsuwe (DG);
* 27-May-2002 : Added getPointInRectangle method (DG);
* 26-Jun-2002 : Removed unnecessary imports (DG);
* 12-Jul-2002 : Added workaround for rotated text (JI);
* 14-Oct-2002 : Fixed errors reported by Checkstyle (DG);
* 08-May-2003 : Added a new drawRotatedString() method (DG);
* 09-May-2003 : Added a drawRotatedShape() method (DG);
* 10-Jun-2003 : Updated aligned and rotated string methods (DG);
* 29-Oct-2003 : Added workaround for font alignment in PDF output (DG);
* 07-Nov-2003 : Added rotateShape() method (DG);
* 16-Mar-2004 : Moved rotateShape() method to ShapeUtils.java (DG);
* 07-Apr-2004 : Modified text bounds calculation with TextUtilities.getTextBounds() (DG);
* 21-May-2004 : Fixed bug 951870 - precision in drawAlignedString() method (DG);
* 30-Sep-2004 : Deprecated and moved a number of methods to the TextUtilities class (DG);
* 04-Oct-2004 : Renamed ShapeUtils --> ShapeUtilities (DG);
* 11-Jan-2005 : Removed deprecated code in preparation for the 1.0.0 release (DG);
*
*/
package org.jfree.ui;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.Window;
import java.awt.Point;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.lang.reflect.Method;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
/**
* A collection of utility methods relating to user interfaces.
*
* @author David Gilbert
*/
public class RefineryUtilities {
private RefineryUtilities() {
}
/** Access to logging facilities. */
// private static final LogContext logger = Log.createContext(RefineryUtilities.class);
/**
* Computes the center point of the current screen device. If this method is called on JDK 1.4, Xinerama-aware
* results are returned. (See Sun-Bug-ID 4463949 for details).
*
* @return the center point of the current screen.
*/
public static Point getCenterPoint ()
{
final GraphicsEnvironment localGraphicsEnvironment = GraphicsEnvironment.getLocalGraphicsEnvironment();
try
{
final Method method = GraphicsEnvironment.class.getMethod("getCenterPoint", (Class[]) null);
return (Point) method.invoke(localGraphicsEnvironment, (Object[]) null);
}
catch(Exception e)
{
// ignore ... will fail if this is not a JDK 1.4 ..
}
final Dimension s = Toolkit.getDefaultToolkit().getScreenSize();
return new Point (s.width / 2, s.height / 2);
}
/**
* Computes the maximum bounds of the current screen device. If this method is called on JDK 1.4, Xinerama-aware
* results are returned. (See Sun-Bug-ID 4463949 for details).
*
* @return the maximum bounds of the current screen.
*/
public static Rectangle getMaximumWindowBounds ()
{
final GraphicsEnvironment localGraphicsEnvironment = GraphicsEnvironment.getLocalGraphicsEnvironment();
try
{
final Method method = GraphicsEnvironment.class.getMethod("getMaximumWindowBounds", (Class[]) null);
return (Rectangle) method.invoke(localGraphicsEnvironment, (Object[]) null);
}
catch(Exception e)
{
// ignore ... will fail if this is not a JDK 1.4 ..
}
final Dimension s = Toolkit.getDefaultToolkit().getScreenSize();
return new Rectangle (0, 0, s.width, s.height);
}
/**
* Positions the specified frame in the middle of the screen.
*
* @param frame the frame to be centered on the screen.
*/
public static void centerFrameOnScreen(final Window frame) {
positionFrameOnScreen(frame, 0.5, 0.5);
}
/**
* Positions the specified frame at a relative position in the screen, where 50% is considered
* to be the center of the screen.
*
* @param frame the frame.
* @param horizontalPercent the relative horizontal position of the frame (0.0 to 1.0,
* where 0.5 is the center of the screen).
* @param verticalPercent the relative vertical position of the frame (0.0 to 1.0, where
* 0.5 is the center of the screen).
*/
public static void positionFrameOnScreen(final Window frame,
final double horizontalPercent,
final double verticalPercent) {
final Rectangle s = getMaximumWindowBounds();
final Dimension f = frame.getSize();
final int w = Math.max(s.width - f.width, 0);
final int h = Math.max(s.height - f.height, 0);
final int x = (int) (horizontalPercent * w) + s.x;
final int y = (int) (verticalPercent * h) + s.y;
frame.setBounds(x, y, f.width, f.height);
}
/**
* Positions the specified frame at a random location on the screen while ensuring that the
* entire frame is visible (provided that the frame is smaller than the screen).
*
* @param frame the frame.
*/
public static void positionFrameRandomly(final Window frame) {
positionFrameOnScreen(frame, Math.random(), Math.random());
}
/**
* Positions the specified dialog within its parent.
*
* @param dialog the dialog to be positioned on the screen.
*/
public static void centerDialogInParent(final Dialog dialog) {
positionDialogRelativeToParent(dialog, 0.5, 0.5);
}
/**
* Positions the specified dialog at a position relative to its parent.
*
* @param dialog the dialog to be positioned.
* @param horizontalPercent the relative location.
* @param verticalPercent the relative location.
*/
public static void positionDialogRelativeToParent(final Dialog dialog,
final double horizontalPercent,
final double verticalPercent) {
final Dimension d = dialog.getSize();
final Container parent = dialog.getParent();
final Dimension p = parent.getSize();
final int baseX = parent.getX() - d.width;
final int baseY = parent.getY() - d.height;
final int w = d.width + p.width;
final int h = d.height + p.height;
int x = baseX + (int) (horizontalPercent * w);
int y = baseY + (int) (verticalPercent * h);
// make sure the dialog fits completely on the screen...
final Rectangle s = getMaximumWindowBounds();
x = Math.min(x, (s.width - d.width));
x = Math.max(x, 0);
y = Math.min(y, (s.height - d.height));
y = Math.max(y, 0);
dialog.setBounds(x + s.x, y + s.y, d.width, d.height);
}
/**
* Creates a panel that contains a table based on the specified table model.
*
* @param model the table model to use when constructing the table.
*
* @return The panel.
*/
public static JPanel createTablePanel(final TableModel model) {
final JPanel panel = new JPanel(new BorderLayout());
final JTable table = new JTable(model);
for (int columnIndex = 0; columnIndex < model.getColumnCount(); columnIndex++) {
final TableColumn column = table.getColumnModel().getColumn(columnIndex);
final Class c = model.getColumnClass(columnIndex);
if (c.equals(Number.class)) {
column.setCellRenderer(new NumberCellRenderer());
}
}
panel.add(new JScrollPane(table));
return panel;
}
/**
* Creates a label with a specific font.
*
* @param text the text for the label.
* @param font the font.
*
* @return The label.
*/
public static JLabel createJLabel(final String text, final Font font) {
final JLabel result = new JLabel(text);
result.setFont(font);
return result;
}
/**
* Creates a label with a specific font and color.
*
* @param text the text for the label.
* @param font the font.
* @param color the color.
*
* @return The label.
*/
public static JLabel createJLabel(final String text, final Font font, final Color color) {
final JLabel result = new JLabel(text);
result.setFont(font);
result.setForeground(color);
return result;
}
/**
* Creates a {@link JButton}.
*
* @param label the label.
* @param font the font.
*
* @return The button.
*/
public static JButton createJButton(final String label, final Font font) {
final JButton result = new JButton(label);
result.setFont(font);
return result;
}
}
| nologic/nabs | client/trunk/shared/libraries/jcommon-1.0.10/source/org/jfree/ui/RefineryUtilities.java | Java | gpl-2.0 | 11,477 |
// Copyright (c) 2014, Facebook, Inc. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
package org.rocksdb;
import java.util.List;
/**
* <p>This class is used to access information about backups and
* restore from them.</p>
*
* <p>Note: {@code dispose()} must be called before this instance
* become out-of-scope to release the allocated
* memory in c++.</p>
*
*/
public class RestoreBackupableDB extends RocksObject {
/**
* <p>Construct new estoreBackupableDB instance.</p>
*
* @param options {@link org.rocksdb.BackupableDBOptions} instance
*/
public RestoreBackupableDB(BackupableDBOptions options) {
super();
nativeHandle_ = newRestoreBackupableDB(options.nativeHandle_);
}
/**
* <p>Restore from backup with backup_id.</p>
*
* <p><strong>Important</strong>: If options_.share_table_files == true
* and you restore DB from some backup that is not the latest, and you
* start creating new backups from the new DB, they will probably
* fail.</p>
*
* <p><strong>Example</strong>: Let's say you have backups 1, 2, 3, 4, 5
* and you restore 3. If you add new data to the DB and try creating a new
* backup now, the database will diverge from backups 4 and 5 and the new
* backup will fail. If you want to create new backup, you will first have
* to delete backups 4 and 5.</p>
*
* @param backupId id pointing to backup
* @param dbDir database directory to restore to
* @param walDir directory where wal files are located
* @param restoreOptions {@link org.rocksdb.RestoreOptions} instance.
*
* @throws RocksDBException thrown if error happens in underlying
* native library.
*/
public void restoreDBFromBackup(long backupId, String dbDir, String walDir,
RestoreOptions restoreOptions) throws RocksDBException {
assert(isInitialized());
restoreDBFromBackup0(nativeHandle_, backupId, dbDir, walDir,
restoreOptions.nativeHandle_);
}
/**
* <p>Restore from the latest backup.</p>
*
* @param dbDir database directory to restore to
* @param walDir directory where wal files are located
* @param restoreOptions {@link org.rocksdb.RestoreOptions} instance
*
* @throws RocksDBException thrown if error happens in underlying
* native library.
*/
public void restoreDBFromLatestBackup(String dbDir, String walDir,
RestoreOptions restoreOptions) throws RocksDBException {
assert(isInitialized());
restoreDBFromLatestBackup0(nativeHandle_, dbDir, walDir,
restoreOptions.nativeHandle_);
}
/**
* <p>Deletes old backups, keeping latest numBackupsToKeep alive.</p>
*
* @param numBackupsToKeep of latest backups to keep
*
* @throws RocksDBException thrown if error happens in underlying
* native library.
*/
public void purgeOldBackups(int numBackupsToKeep) throws RocksDBException {
assert(isInitialized());
purgeOldBackups0(nativeHandle_, numBackupsToKeep);
}
/**
* <p>Deletes a specific backup.</p>
*
* @param backupId of backup to delete.
*
* @throws RocksDBException thrown if error happens in underlying
* native library.
*/
public void deleteBackup(int backupId) throws RocksDBException {
assert(isInitialized());
deleteBackup0(nativeHandle_, backupId);
}
/**
* <p>Returns a list of {@link BackupInfo} instances, which describe
* already made backups.</p>
*
* @return List of {@link BackupInfo} instances.
*/
public List<BackupInfo> getBackupInfos() {
assert(isInitialized());
return getBackupInfo(nativeHandle_);
}
/**
* <p>Returns a list of corrupted backup ids. If there
* is no corrupted backup the method will return an
* empty list.</p>
*
* @return array of backup ids as int ids.
*/
public int[] getCorruptedBackups() {
assert(isInitialized());
return getCorruptedBackups(nativeHandle_);
}
/**
* <p>Will delete all the files we don't need anymore. It will
* do the full scan of the files/ directory and delete all the
* files that are not referenced.</p>
*
* @throws RocksDBException thrown if error happens in underlying
* native library.
*/
public void garbageCollect() throws RocksDBException {
assert(isInitialized());
garbageCollect(nativeHandle_);
}
/**
* <p>Release the memory allocated for the current instance
* in the c++ side.</p>
*/
@Override public synchronized void disposeInternal() {
dispose(nativeHandle_);
}
private native long newRestoreBackupableDB(long options);
private native void restoreDBFromBackup0(long nativeHandle, long backupId,
String dbDir, String walDir, long restoreOptions)
throws RocksDBException;
private native void restoreDBFromLatestBackup0(long nativeHandle,
String dbDir, String walDir, long restoreOptions)
throws RocksDBException;
private native void purgeOldBackups0(long nativeHandle, int numBackupsToKeep)
throws RocksDBException;
private native void deleteBackup0(long nativeHandle, int backupId)
throws RocksDBException;
private native List<BackupInfo> getBackupInfo(long handle);
private native int[] getCorruptedBackups(long handle);
private native void garbageCollect(long handle)
throws RocksDBException;
private native void dispose(long nativeHandle);
}
| Jacklli/ActionDB | rocksdb-3.9/java/org/rocksdb/RestoreBackupableDB.java | Java | gpl-2.0 | 5,554 |
package org.jdamico.jgitbkp.commons;
/*
* This file is part of J-GIT-BACKUP (written by Jose Damico).
*
* J-GIT-BACKUP 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.
*
* J-GIT-BACKUP 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 J-GIT-BACKUP. If not, see <http://www.gnu.org/licenses/>.
*/
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class LoggerManager{
private static final Logger logger = Logger.getLogger("LoggerManager");
private static LoggerManager INSTANCE;
public static LoggerManager getInstance() {
if (INSTANCE == null) {
INSTANCE = new LoggerManager();
}
return INSTANCE;
}
private LoggerManager(){}
public void logAtDebugTime(String className, String logLine){
log(className, logLine, false);
}
public void logAtExceptionTime(String className, String logLine) {
log(className, logLine, true);
}
/**
* Check if log direction is SystemOut or a separate file
* Check if a log file exist
* If there is no file create, on the contrary, use the file
* @throws IOException
*
*/
private void log(String className, String logLine, boolean logLevel) {
String formatedLog = " ("+className+") "+logLine;
String fileName = Constants.LOG_NAME;
fileName = Constants.LOG_FOLDER + fileName;
String stime = Utils.getInstance().getCurrentDateTimeFormated(Constants.DATE_FORMAT);
if(logLevel){
formatedLog = stime+Constants.SEVERE_LOGLEVEL+formatedLog+"\n";
logger.log(Level.SEVERE, formatedLog);
}else{
formatedLog = stime+Constants.NORMAL_LOGLEVEL+formatedLog+"\n";
}
int limit = Constants.FIXED_LOGLIMIT;
File listenerLog = null;
FileWriter fw = null;
BufferedWriter bwr = null;
try{
listenerLog = new File(fileName);
if(!listenerLog.exists()){
listenerLog.createNewFile();
} else if(listenerLog.length() > limit){
/*
* check if file is too big
*/
listenerLog.delete();
listenerLog.createNewFile();
}
fw = new FileWriter(fileName, true);
bwr = new BufferedWriter(fw);
bwr.write(formatedLog);
bwr.close();
fw.close();
}catch(IOException ioe){
System.err.println("write log error");
}finally{
try {
if(bwr!=null) bwr.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
if(fw!=null) fw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
listenerLog = null;
fw = null;
bwr = null;
}
}
// public ArrayList getLogsData(){
// /*
// * Scan logs folder
// */
// ArrayList logsArray = new ArrayList();
// LogData logData = null;
//
// File foldersLog = new File(Constants.APP_FOLDER);
//
// String[] logsList = foldersLog.list();
//
// if (logsList == null) {
// logAtExceptionTime(this.getClass().getName(), "No log files found! Check system configuration.");
// } else {
// for (int i=0; i< logsList.length; i++) {
// logData = new LogData();
// String logName = logsList[i];
// logData.setLogName(logName);
// logData.setLogPrefix(logName.replaceAll("_"+Constants.LOG_NAME, ""));
// logData.setLogSize(getLogSize(logName));
// logData.setLogLines(getLogLines(logName));
// logsArray.add(logData);
// }
// }
// return logsArray;
// }
// private int getLogLines(String fileName) {
// int lines = 0;
// try {
// FileReader fr = new FileReader(Constants.APP_FOLDER+fileName);
// BufferedReader fileInput = new BufferedReader(fr);
// while ((fileInput.readLine()) != null) {
// lines++;
// }
// fileInput.close();
// fr.close();
// } catch (IOException e) {
// logAtExceptionTime(this.getClass().getName(), "getLogLines(String fileName) "+e.getMessage());
// }
// return lines;
// }
// private long getLogSize(String fileName) {
// File listenerLog = new File(Constants.APP_FOLDER+fileName);
// return listenerLog.length();
// }
} | damico/j-git-backup | src/org/jdamico/jgitbkp/commons/LoggerManager.java | Java | gpl-2.0 | 4,469 |
/*
* Copyright (c) 2013 Denis Solonenko.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v2.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*/
package com.flowzr.rates;
import android.text.TextUtils;
import android.util.Log;
import com.flowzr.http.HttpClientWrapper;
import com.flowzr.model.Currency;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Created with IntelliJ IDEA.
* User: dsolonenko
* Date: 2/16/13
* Time: 6:27 PM
*/
//@NotThreadSafe
public class OpenExchangeRatesDownloader extends AbstractMultipleRatesDownloader {
private static final String TAG = OpenExchangeRatesDownloader.class.getSimpleName();
private static final String GET_LATEST = "http://openexchangerates.org/api/latest.json?app_id=";
private final String appId;
private final HttpClientWrapper httpClient;
private JSONObject json;
public OpenExchangeRatesDownloader(HttpClientWrapper httpClient, String appId) {
this.httpClient = httpClient;
this.appId = appId;
}
@Override
public ExchangeRate getRate(Currency fromCurrency, Currency toCurrency) {
ExchangeRate rate = createRate(fromCurrency, toCurrency);
try {
downloadLatestRates();
if (hasError(json)) {
rate.error = error(json);
} else {
updateRate(json, rate, fromCurrency, toCurrency);
}
} catch (Exception e) {
rate.error = error(e);
}
return rate;
}
private ExchangeRate createRate(Currency fromCurrency, Currency toCurrency) {
ExchangeRate r = new ExchangeRate();
r.fromCurrencyId = fromCurrency.id;
r.toCurrencyId = toCurrency.id;
return r;
}
private void downloadLatestRates() throws Exception {
if (json == null) {
if (appIdIsNotSet()) {
throw new RuntimeException("App ID is not set");
}
Log.i(TAG, "Downloading latest rates...");
json = httpClient.getAsJson(getLatestUrl());
Log.i(TAG, json.toString());
}
}
private boolean appIdIsNotSet() {
return TextUtils.getTrimmedLength(appId) == 0;
}
private String getLatestUrl() {
return GET_LATEST+appId;
}
private boolean hasError(JSONObject json) throws JSONException {
return json.optBoolean("error", false);
}
private String error(JSONObject json) {
String status = json.optString("status");
String message = json.optString("message");
String description = json.optString("description");
return status+" ("+message+"): "+description;
}
private String error(Exception e) {
return "Unable to get exchange rates: "+e.getMessage();
}
private void updateRate(JSONObject json, ExchangeRate exchangeRate, Currency fromCurrency, Currency toCurrency) throws JSONException {
JSONObject rates = json.getJSONObject("rates");
double usdFrom = rates.getDouble(fromCurrency.name);
double usdTo = rates.getDouble(toCurrency.name);
exchangeRate.rate = usdTo * (1 / usdFrom);
exchangeRate.date = 1000*json.optLong("timestamp", System.currentTimeMillis());
}
@Override
public ExchangeRate getRate(Currency fromCurrency, Currency toCurrency, long atTime) {
throw new UnsupportedOperationException("Not yet implemented");
}
}
| emmanuel-florent/flowzr-android-black | src/main/java/com/flowzr/rates/OpenExchangeRatesDownloader.java | Java | gpl-2.0 | 3,594 |
package spim.fiji.plugin.apply;
import bdv.BigDataViewer;
import bdv.viewer.ViewerFrame;
import java.awt.Button;
import java.awt.Checkbox;
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.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowEvent;
import java.text.DecimalFormat;
import java.util.Timer;
import java.util.TimerTask;
import org.scijava.java3d.Transform3D;
import javax.swing.SwingUtilities;
import net.imglib2.realtransform.AffineTransform3D;
public class BigDataViewerTransformationWindow
{
final AffineTransform3D t;
final protected Timer timer;
protected boolean isRunning = true;
protected boolean wasCancelled = false;
protected boolean ignoreScaling = true;
public BigDataViewerTransformationWindow( final BigDataViewer bdv )
{
this.t = new AffineTransform3D();
final Frame frame = new Frame( "Current Global Transformation" );
frame.setSize( 400, 200 );
/* Instantiation */
final GridBagLayout layout = new GridBagLayout();
final GridBagConstraints c = new GridBagConstraints();
final Label text1 = new Label( "1.00000 0.00000 0.00000 0.00000", Label.CENTER );
final Label text2 = new Label( "0.00000 1.00000 0.00000 0.00000", Label.CENTER );
final Label text3 = new Label( "0.00000 0.00000 1.00000 0.00000", Label.CENTER );
text1.setFont( new Font( Font.MONOSPACED, Font.PLAIN, 14 ) );
text2.setFont( new Font( Font.MONOSPACED, Font.PLAIN, 14 ) );
text3.setFont( new Font( Font.MONOSPACED, Font.PLAIN, 14 ) );
final Button apply = new Button( "Apply Transformation" );
final Button cancel = new Button( "Cancel" );
final Checkbox ignoreScale = new Checkbox( "Ignore scaling factor from BigDataViewer", ignoreScaling );
/* Location */
frame.setLayout( layout );
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
frame.add( text1, c );
++c.gridy;
frame.add( text2, c );
++c.gridy;
frame.add( text3, c );
c.insets = new Insets( 20,0,0,0 );
++c.gridy;
frame.add( ignoreScale, c );
c.insets = new Insets( 20,0,0,0 );
++c.gridy;
frame.add( apply, c );
c.insets = new Insets( 0,0,0,0 );
++c.gridy;
frame.add( cancel, c );
apply.addActionListener( new ApplyButtonListener( frame, bdv ) );
cancel.addActionListener( new CancelButtonListener( frame, bdv ) );
ignoreScale.addItemListener( new ItemListener(){ public void itemStateChanged( final ItemEvent arg0 ) { ignoreScaling = ignoreScale.getState(); } });
frame.setVisible( true );
timer = new Timer();
timer.schedule( new BDVChecker( bdv, text1, text2, text3 ), 500 );
}
public AffineTransform3D getTransform() { return t; }
public boolean isRunning() { return isRunning; }
public boolean wasCancelled() { return wasCancelled; }
protected void close( final Frame parent, final BigDataViewer bdv )
{
if ( parent != null )
parent.dispose();
isRunning = false;
}
protected class CancelButtonListener implements ActionListener
{
final Frame parent;
final BigDataViewer bdv;
public CancelButtonListener( final Frame parent, final BigDataViewer bdv )
{
this.parent = parent;
this.bdv = bdv;
}
@Override
public void actionPerformed( final ActionEvent arg0 )
{
wasCancelled = true;
close( parent, bdv );
}
}
protected class BDVChecker extends TimerTask
{
final BigDataViewer bdv;
final Label text1, text2, text3;
public BDVChecker(
final BigDataViewer bdv,
final Label text1,
final Label text2,
final Label text3 )
{
this.bdv = bdv;
this.text1 = text1;
this.text2 = text2;
this.text3 = text3;
}
@Override
public void run()
{
if ( isRunning )
{
if ( bdv != null )
bdv.getViewer().getState().getViewerTransform( t );
t.set( 0, 0, 3 );
t.set( 0, 1, 3 );
t.set( 0, 2, 3 );
if ( ignoreScaling )
{
final double[] m = new double[ 16 ];
int i = 0;
for ( int row = 0; row < 3; ++row )
for ( int col = 0; col < 4; ++col )
m[ i++ ] = t.get( row, col );
m[ 15 ] = 1;
final Transform3D trans = new Transform3D( m );
trans.setScale( 1 );
trans.get( m );
i = 0;
for ( int row = 0; row < 3; ++row )
for ( int col = 0; col < 4; ++col )
t.set( m[ i++ ], row, col );
}
final DecimalFormat df = new DecimalFormat( "0.00000" );
text1.setText(
df.format( t.get( 0, 0 ) ).substring( 0, 7 ) + " " + df.format( t.get( 0, 1 ) ).substring( 0, 7 ) + " " +
df.format( t.get( 0, 2 ) ).substring( 0, 7 ) + " " + df.format( t.get( 0, 3 ) ).substring( 0, 7 ) );
text2.setText(
df.format( t.get( 1, 0 ) ).substring( 0, 7 ) + " " + df.format( t.get( 1, 1 ) ).substring( 0, 7 ) + " " +
df.format( t.get( 1, 2 ) ).substring( 0, 7 ) + " " + df.format( t.get( 1, 3 ) ).substring( 0, 7 ) );
text3.setText(
df.format( t.get( 2, 0 ) ).substring( 0, 7 ) + " " + df.format( t.get( 2, 1 ) ).substring( 0, 7 ) + " " +
df.format( t.get( 2, 2 ) ).substring( 0, 7 ) + " " + df.format( t.get( 2, 3 ) ).substring( 0, 7 ) );
// Reschedule myself (new instance is required, why?)
timer.schedule( new BDVChecker( bdv,text1, text2, text3 ), 500 );
}
}
}
protected class ApplyButtonListener implements ActionListener
{
final Frame parent;
final BigDataViewer bdv;
public ApplyButtonListener( final Frame parent, final BigDataViewer bdv )
{
this.parent = parent;
this.bdv = bdv;
}
@Override
public void actionPerformed( final ActionEvent arg0 )
{
wasCancelled = false;
close( parent, bdv );
}
}
public static void disposeViewerWindow( final BigDataViewer bdv )
{
try
{
SwingUtilities.invokeAndWait( new Runnable()
{
@Override
public void run()
{
final ViewerFrame frame = bdv.getViewerFrame();
final WindowEvent windowClosing = new WindowEvent( frame, WindowEvent.WINDOW_CLOSING );
frame.dispatchEvent( windowClosing );
}
} );
}
catch ( final Exception e )
{}
}
}
| psteinb/SPIM_Registration | src/main/java/spim/fiji/plugin/apply/BigDataViewerTransformationWindow.java | Java | gpl-2.0 | 6,249 |
/*
* Copyright (c) 2012, 2017, 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 jdk.packager.internal.windows;
import com.oracle.tools.packager.Platform;
import java.util.List;
public final class WindowsDefender {
private WindowsDefender() {}
public static final boolean isThereAPotentialWindowsDefenderIssue() {
boolean result = false;
if (Platform.getPlatform() == Platform.WINDOWS &&
Platform.getMajorVersion() == 10) {
// If DisableRealtimeMonitoring is not enabled then there
// may be a problem.
if (!WindowsRegistry.readDisableRealtimeMonitoring() &&
!isTempDirectoryInExclusionPath()) {
result = true;
}
}
return result;
}
private static final boolean isTempDirectoryInExclusionPath() {
boolean result = false;
// If the user temp directory is not found in the exclusion
// list then there may be a problem.
List<String> paths = WindowsRegistry.readExclusionsPaths();
String tempDirectory = getUserTempDirectory();
for (String s : paths) {
if (s.equals(tempDirectory)) {
result = true;
break;
}
}
return result;
}
public static final String getUserTempDirectory() {
String tempDirectory = System.getProperty("java.io.tmpdir");
return tempDirectory;
}
}
| teamfx/openjfx-9-dev-rt | modules/jdk.packager/src/main/java/jdk/packager/internal/windows/WindowsDefender.java | Java | gpl-2.0 | 2,602 |
//
// Diese Datei wurde mit der JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.11 generiert
// Siehe <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Änderungen an dieser Datei gehen bei einer Neukompilierung des Quellschemas verloren.
// Generiert: 2014.11.06 um 02:47:13 AM CET
//
package de.idealo.offers.imports.offermanager.ebay.api.binding.jaxb.trading;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
/**
*
* This type defines the <b>Variation</b> container, which provides full
* details on each item variation in a multi-variation listing.
*
*
* <p>Java-Klasse für VariationType complex type.
*
* <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist.
*
* <pre>
* <complexType name="VariationType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="SKU" type="{urn:ebay:apis:eBLBaseComponents}SKUType" minOccurs="0"/>
* <element name="StartPrice" type="{urn:ebay:apis:eBLBaseComponents}AmountType" minOccurs="0"/>
* <element name="Quantity" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
* <element name="VariationSpecifics" type="{urn:ebay:apis:eBLBaseComponents}NameValueListArrayType" minOccurs="0"/>
* <element name="UnitsAvailable" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
* <element name="UnitCost" type="{urn:ebay:apis:eBLBaseComponents}AmountType" minOccurs="0"/>
* <element name="SellingStatus" type="{urn:ebay:apis:eBLBaseComponents}SellingStatusType" minOccurs="0"/>
* <element name="VariationTitle" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="VariationViewItemURL" type="{http://www.w3.org/2001/XMLSchema}anyURI" minOccurs="0"/>
* <element name="Delete" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
* <element name="SellingManagerProductInventoryStatus" type="{urn:ebay:apis:eBLBaseComponents}SellingManagerProductInventoryStatusType" minOccurs="0"/>
* <element name="WatchCount" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/>
* <element name="PrivateNotes" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="DiscountPriceInfo" type="{urn:ebay:apis:eBLBaseComponents}DiscountPriceInfoType" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "VariationType", propOrder = {
"sku",
"startPrice",
"quantity",
"variationSpecifics",
"unitsAvailable",
"unitCost",
"sellingStatus",
"variationTitle",
"variationViewItemURL",
"delete",
"sellingManagerProductInventoryStatus",
"watchCount",
"privateNotes",
"discountPriceInfo"
})
public class VariationType {
@XmlElement(name = "SKU")
protected String sku;
@XmlElement(name = "StartPrice")
protected AmountType startPrice;
@XmlElement(name = "Quantity")
protected Integer quantity;
@XmlElement(name = "VariationSpecifics")
protected NameValueListArrayType variationSpecifics;
@XmlElement(name = "UnitsAvailable")
protected Integer unitsAvailable;
@XmlElement(name = "UnitCost")
protected AmountType unitCost;
@XmlElement(name = "SellingStatus")
protected SellingStatusType sellingStatus;
@XmlElement(name = "VariationTitle")
protected String variationTitle;
@XmlElement(name = "VariationViewItemURL")
@XmlSchemaType(name = "anyURI")
protected String variationViewItemURL;
@XmlElement(name = "Delete", defaultValue = "false")
protected Boolean delete;
@XmlElement(name = "SellingManagerProductInventoryStatus")
protected SellingManagerProductInventoryStatusType sellingManagerProductInventoryStatus;
@XmlElement(name = "WatchCount")
protected Long watchCount;
@XmlElement(name = "PrivateNotes")
protected String privateNotes;
@XmlElement(name = "DiscountPriceInfo")
protected DiscountPriceInfoType discountPriceInfo;
/**
* Ruft den Wert der sku-Eigenschaft ab.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSKU() {
return sku;
}
/**
* Legt den Wert der sku-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSKU(String value) {
this.sku = value;
}
/**
* Ruft den Wert der startPrice-Eigenschaft ab.
*
* @return
* possible object is
* {@link AmountType }
*
*/
public AmountType getStartPrice() {
return startPrice;
}
/**
* Legt den Wert der startPrice-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link AmountType }
*
*/
public void setStartPrice(AmountType value) {
this.startPrice = value;
}
/**
* Ruft den Wert der quantity-Eigenschaft ab.
*
* @return
* possible object is
* {@link Integer }
*
*/
public Integer getQuantity() {
return quantity;
}
/**
* Legt den Wert der quantity-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link Integer }
*
*/
public void setQuantity(Integer value) {
this.quantity = value;
}
/**
* Ruft den Wert der variationSpecifics-Eigenschaft ab.
*
* @return
* possible object is
* {@link NameValueListArrayType }
*
*/
public NameValueListArrayType getVariationSpecifics() {
return variationSpecifics;
}
/**
* Legt den Wert der variationSpecifics-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link NameValueListArrayType }
*
*/
public void setVariationSpecifics(NameValueListArrayType value) {
this.variationSpecifics = value;
}
/**
* Ruft den Wert der unitsAvailable-Eigenschaft ab.
*
* @return
* possible object is
* {@link Integer }
*
*/
public Integer getUnitsAvailable() {
return unitsAvailable;
}
/**
* Legt den Wert der unitsAvailable-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link Integer }
*
*/
public void setUnitsAvailable(Integer value) {
this.unitsAvailable = value;
}
/**
* Ruft den Wert der unitCost-Eigenschaft ab.
*
* @return
* possible object is
* {@link AmountType }
*
*/
public AmountType getUnitCost() {
return unitCost;
}
/**
* Legt den Wert der unitCost-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link AmountType }
*
*/
public void setUnitCost(AmountType value) {
this.unitCost = value;
}
/**
* Ruft den Wert der sellingStatus-Eigenschaft ab.
*
* @return
* possible object is
* {@link SellingStatusType }
*
*/
public SellingStatusType getSellingStatus() {
return sellingStatus;
}
/**
* Legt den Wert der sellingStatus-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link SellingStatusType }
*
*/
public void setSellingStatus(SellingStatusType value) {
this.sellingStatus = value;
}
/**
* Ruft den Wert der variationTitle-Eigenschaft ab.
*
* @return
* possible object is
* {@link String }
*
*/
public String getVariationTitle() {
return variationTitle;
}
/**
* Legt den Wert der variationTitle-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setVariationTitle(String value) {
this.variationTitle = value;
}
/**
* Ruft den Wert der variationViewItemURL-Eigenschaft ab.
*
* @return
* possible object is
* {@link String }
*
*/
public String getVariationViewItemURL() {
return variationViewItemURL;
}
/**
* Legt den Wert der variationViewItemURL-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setVariationViewItemURL(String value) {
this.variationViewItemURL = value;
}
/**
* Ruft den Wert der delete-Eigenschaft ab.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean getDelete() {
return delete;
}
/**
* Legt den Wert der delete-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setDelete(Boolean value) {
this.delete = value;
}
/**
* Ruft den Wert der sellingManagerProductInventoryStatus-Eigenschaft ab.
*
* @return
* possible object is
* {@link SellingManagerProductInventoryStatusType }
*
*/
public SellingManagerProductInventoryStatusType getSellingManagerProductInventoryStatus() {
return sellingManagerProductInventoryStatus;
}
/**
* Legt den Wert der sellingManagerProductInventoryStatus-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link SellingManagerProductInventoryStatusType }
*
*/
public void setSellingManagerProductInventoryStatus(SellingManagerProductInventoryStatusType value) {
this.sellingManagerProductInventoryStatus = value;
}
/**
* Ruft den Wert der watchCount-Eigenschaft ab.
*
* @return
* possible object is
* {@link Long }
*
*/
public Long getWatchCount() {
return watchCount;
}
/**
* Legt den Wert der watchCount-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link Long }
*
*/
public void setWatchCount(Long value) {
this.watchCount = value;
}
/**
* Ruft den Wert der privateNotes-Eigenschaft ab.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPrivateNotes() {
return privateNotes;
}
/**
* Legt den Wert der privateNotes-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPrivateNotes(String value) {
this.privateNotes = value;
}
/**
* Ruft den Wert der discountPriceInfo-Eigenschaft ab.
*
* @return
* possible object is
* {@link DiscountPriceInfoType }
*
*/
public DiscountPriceInfoType getDiscountPriceInfo() {
return discountPriceInfo;
}
/**
* Legt den Wert der discountPriceInfo-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link DiscountPriceInfoType }
*
*/
public void setDiscountPriceInfo(DiscountPriceInfoType value) {
this.discountPriceInfo = value;
}
}
| Team-OfferManager/ebay-jaxb-bindings | src/main/java/de/idealo/offers/imports/offermanager/ebay/api/binding/jaxb/trading/VariationType.java | Java | gpl-2.0 | 11,951 |
package org.wheatgenetics.coordinate.database;
/**
* Uses:
* android.content.Context
*
* androidx.annotation.IntRange
* androidx.annotation.NonNull
* androidx.annotation.Nullable
* androidx.annotation.RestrictTo
* androidx.annotation.RestrictTo.Scope
*
* org.wheatgenetics.coordinate.model.AllGridsUniqueEntryModels
* org.wheatgenetics.coordinate.model.AllGridsUniqueEntryModels.Checker
* org.wheatgenetics.coordinate.model.AllGridsUniqueJoinedGridModel
* org.wheatgenetics.coordinate.model.AllGridsUniqueJoinedGridModels
* org.wheatgenetics.coordinate.model.BaseJoinedGridModels
* org.wheatgenetics.coordinate.model.DatabaseUniqueEntryModels.DatabaseDuplicateCheckException
* org.wheatgenetics.coordinate.model.EntryModels
* org.wheatgenetics.coordinate.model.JoinedGridModel
*
* org.wheatgenetics.coordinate.database.AllGridsUniqueEntriesTable
* org.wheatgenetics.coordinate.database.EntriesTable
* org.wheatgenetics.coordinate.database.GridsTable
*/
public class AllGridsUniqueGridsTable extends org.wheatgenetics.coordinate.database.GridsTable
implements org.wheatgenetics.coordinate.model.AllGridsUniqueEntryModels.Checker
{
private boolean exists(final long id, final java.lang.String value)
{
final java.lang.String sql;
{
final java.lang.String
GRIDS_TABLE = '[' +
org.wheatgenetics.coordinate.database.AllGridsUniqueGridsTable.TABLE_NAME + ']',
ENTRIES_TABLE = '[' +
org.wheatgenetics.coordinate.database.EntriesTable.TABLE_NAME + ']';
final java.lang.String
GRIDS_TABLE_ID_FIELD = GRIDS_TABLE + ".[" +
org.wheatgenetics.coordinate.database.AllGridsUniqueGridsTable.ID_FIELD_NAME +
']',
ENTRIES_TABLE_EDATA_FIELD = ENTRIES_TABLE + ".[" +
org.wheatgenetics.coordinate.database.EntriesTable.EDATA_FIELD_NAME + ']',
ENTRIES_TABLE_GRID_FIELD = ENTRIES_TABLE + ".[" +
org.wheatgenetics.coordinate.database.EntriesTable.GRID_FIELD_NAME + ']';
sql = java.lang.String.format("SELECT ALL %s, %s " +
"FROM %s INNER JOIN %s ON %s = %s " +
"WHERE %s <> ? AND %s = ?",
GRIDS_TABLE_ID_FIELD, ENTRIES_TABLE_EDATA_FIELD,
GRIDS_TABLE, ENTRIES_TABLE, GRIDS_TABLE_ID_FIELD, ENTRIES_TABLE_GRID_FIELD,
GRIDS_TABLE_ID_FIELD, ENTRIES_TABLE_EDATA_FIELD);
}
return org.wheatgenetics.coordinate.database.AllGridsUniqueGridsTable.exists(this.rawQuery(
/* sql => */ sql ,
/* selectionArgs => */ new java.lang.String[]{java.lang.String.valueOf(id), value}));
}
public AllGridsUniqueGridsTable(final android.content.Context context)
{ super(context,"AllGridsUniqueGridsTable"); }
// region Overridden Methods
@androidx.annotation.RestrictTo(androidx.annotation.RestrictTo.Scope.SUBCLASSES)
@java.lang.Override org.wheatgenetics.coordinate.database.EntriesTable makeEntriesTable()
{
return new org.wheatgenetics.coordinate.database.AllGridsUniqueEntriesTable(
this.getContext());
}
@androidx.annotation.RestrictTo(androidx.annotation.RestrictTo.Scope.SUBCLASSES)
@java.lang.Override
org.wheatgenetics.coordinate.model.BaseJoinedGridModels makeJoinedGridModels()
{ return new org.wheatgenetics.coordinate.model.AllGridsUniqueJoinedGridModels(); }
@androidx.annotation.RestrictTo(androidx.annotation.RestrictTo.Scope.SUBCLASSES)
@java.lang.Override org.wheatgenetics.coordinate.model.JoinedGridModel makeJoinedGridModel(
@androidx.annotation.IntRange(from = 1) final long id ,
@androidx.annotation.IntRange(from = 0) final long projectId ,
final java.lang.String person ,
@androidx.annotation.IntRange(from = 0) final int activeRow ,
@androidx.annotation.IntRange(from = 0) final int activeCol ,
@androidx.annotation.Nullable final java.lang.String optionalFields,
@androidx.annotation.IntRange(from = 0) final long timestamp ,
@androidx.annotation.IntRange(from = 1 ) final long templateId ,
final java.lang.String title ,
@androidx.annotation.IntRange(from = 0, to = 2) final int code ,
@androidx.annotation.IntRange(from = 1 ) final int rows ,
@androidx.annotation.IntRange(from = 1 ) final int cols ,
@androidx.annotation.IntRange(from = 0 ) final int generatedExcludedCellsAmount ,
@androidx.annotation.Nullable final java.lang.String initialExcludedCells ,
@androidx.annotation.Nullable final java.lang.String excludedRows ,
@androidx.annotation.Nullable final java.lang.String excludedCols ,
@androidx.annotation.IntRange(from = 0, to = 1) final int colNumbering ,
@androidx.annotation.IntRange(from = 0, to = 1) final int rowNumbering ,
final java.lang.String entryLabel ,
@androidx.annotation.Nullable final java.lang.String templateOptionalFields,
@androidx.annotation.IntRange(from = 0) final long templateTimestamp ,
final org.wheatgenetics.coordinate.model.EntryModels entryModels)
{
return new org.wheatgenetics.coordinate.model.AllGridsUniqueJoinedGridModel(id,
projectId, person, activeRow, activeCol, optionalFields, timestamp, templateId, title,
code, rows, cols, generatedExcludedCellsAmount, initialExcludedCells, excludedRows,
excludedCols, colNumbering, rowNumbering, entryLabel, templateOptionalFields,
templateTimestamp,
(org.wheatgenetics.coordinate.model.AllGridsUniqueEntryModels) entryModels,
this);
}
// region org.wheatgenetics.coordinate.model.AllGridsUniqueEntryModels.Checker Overridden Method
@java.lang.Override @androidx.annotation.Nullable public java.lang.String check(
final long gridId,
@androidx.annotation.Nullable final java.lang.String value ,
@androidx.annotation.NonNull final java.lang.String scope ) throws
org.wheatgenetics.coordinate.model.DatabaseUniqueEntryModels.DatabaseDuplicateCheckException
{
if (this.exists(gridId, value))
throw new org.wheatgenetics.coordinate.model
.DatabaseUniqueEntryModels.DatabaseDuplicateCheckException(scope);
else
return value;
}
// endregion
// endregion
} | trife/Coordinate | app/src/main/java/org/wheatgenetics/coordinate/database/AllGridsUniqueGridsTable.java | Java | gpl-2.0 | 7,075 |
/*
* 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.giffftalk.ui.Components;
import android.annotation.SuppressLint;
import android.content.Context;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import org.giffftalk.messenger.AndroidUtilities;
import org.giffftalk.messenger.ApplicationLoader;
import org.giffftalk.messenger.FileLog;
import org.giffftalk.messenger.LocaleController;
import org.giffftalk.messenger.R;
import org.giffftalk.messenger.browser.Browser;
import org.giffftalk.ui.ActionBar.BottomSheet;
import org.giffftalk.ui.ActionBar.Theme;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class WebFrameLayout extends FrameLayout {
private WebView webView;
private BottomSheet dialog;
private View customView;
private FrameLayout fullscreenVideoContainer;
private WebChromeClient.CustomViewCallback customViewCallback;
private ProgressBar progressBar;
private int width;
private int height;
private String openUrl;
private boolean hasDescription;
private String embedUrl;
final static Pattern youtubeIdRegex = Pattern.compile("(?:youtube(?:-nocookie)?\\.com\\/(?:[^\\/\\n\\s]+\\/\\S+\\/|(?:v|e(?:mbed)?)\\/|\\S*?[?&]v=)|youtu\\.be\\/)([a-zA-Z0-9_-]{11})");
private final String youtubeFrame = "<!DOCTYPE html><html><head><style>" +
"body { margin: 0; width:100%%; height:100%%; background-color:#000; }" +
"html { width:100%%; height:100%%; background-color:#000; }" +
".embed-container iframe," +
".embed-container object," +
" .embed-container embed {" +
" position: absolute;" +
" top: 0;" +
" left: 0;" +
" width: 100%% !important;" +
" height: 100%% !important;" +
" }" +
" </style></head><body>" +
" <div class=\"embed-container\">" +
" <div id=\"player\"></div>" +
" </div>" +
" <script src=\"https://www.youtube.com/iframe_api\"></script>" +
" <script>" +
" var player;" +
" YT.ready(function() {" +
" player = new YT.Player(\"player\", {" +
" \"width\" : \"100%%\"," +
" \"events\" : {" +
" \"onReady\" : \"onReady\"," +
" }," +
" \"videoId\" : \"%1$s\"," +
" \"height\" : \"100%%\"," +
" \"playerVars\" : {" +
" \"start\" : 0," +
" \"rel\" : 0," +
" \"showinfo\" : 0," +
" \"modestbranding\" : 1," +
" \"iv_load_policy\" : 3," +
" \"autohide\" : 1," +
" \"cc_load_policy\" : 1," +
" \"playsinline\" : 1," +
" \"controls\" : 1" +
" }" +
" });" +
" player.setSize(window.innerWidth, window.innerHeight);" +
" });" +
" function onReady(event) {" +
" player.playVideo();" +
" }" +
" window.onresize = function() {" +
" player.setSize(window.innerWidth, window.innerHeight);" +
" }" +
" </script>" +
"</body>" +
"</html>";
@SuppressLint("SetJavaScriptEnabled")
public WebFrameLayout(Context context, final BottomSheet parentDialog, String title, String descripton, String originalUrl, final String url, int w, int h) {
super(context);
embedUrl = url;
hasDescription = descripton != null && descripton.length() > 0;
openUrl = originalUrl;
width = w;
height = h;
if (width == 0 || height == 0) {
width = AndroidUtilities.displaySize.x;
height = AndroidUtilities.displaySize.y / 2;
}
dialog = parentDialog;
fullscreenVideoContainer = new FrameLayout(context);
fullscreenVideoContainer.setBackgroundColor(0xff000000);
if (Build.VERSION.SDK_INT >= 21) {
fullscreenVideoContainer.setFitsSystemWindows(true);
}
parentDialog.setApplyTopPadding(false);
parentDialog.setApplyBottomPadding(false);
dialog.getContainer().addView(fullscreenVideoContainer, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
fullscreenVideoContainer.setVisibility(INVISIBLE);
webView = new WebView(context);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setDomStorageEnabled(true);
if (Build.VERSION.SDK_INT >= 17) {
webView.getSettings().setMediaPlaybackRequiresUserGesture(false);
}
String userAgent = webView.getSettings().getUserAgentString();
if (userAgent != null) {
userAgent = userAgent.replace("Android", "");
webView.getSettings().setUserAgentString(userAgent);
}
if (Build.VERSION.SDK_INT >= 21) {
webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptThirdPartyCookies(webView, true);
}
webView.setWebChromeClient(new WebChromeClient() {
@Override
public void onShowCustomView(View view, int requestedOrientation, CustomViewCallback callback) {
onShowCustomView(view, callback);
}
@Override
public void onShowCustomView(View view, CustomViewCallback callback) {
if (customView != null) {
callback.onCustomViewHidden();
return;
}
customView = view;
if (dialog != null) {
dialog.getSheetContainer().setVisibility(INVISIBLE);
fullscreenVideoContainer.setVisibility(VISIBLE);
fullscreenVideoContainer.addView(view, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
}
customViewCallback = callback;
}
@Override
public void onHideCustomView() {
super.onHideCustomView();
if (customView == null) {
return;
}
if (dialog != null) {
dialog.getSheetContainer().setVisibility(VISIBLE);
fullscreenVideoContainer.setVisibility(INVISIBLE);
fullscreenVideoContainer.removeView(customView);
}
if (customViewCallback != null && !customViewCallback.getClass().getName().contains(".chromium.")) {
customViewCallback.onCustomViewHidden();
}
customView = null;
}
});
webView.setWebViewClient(new WebViewClient() {
@Override
public void onLoadResource(WebView view, String url) {
super.onLoadResource(view, url);
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
progressBar.setVisibility(INVISIBLE);
}
});
addView(webView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT, 0, 0, 0, 48 + 36 + (hasDescription ? 22 : 0)));
progressBar = new ProgressBar(context);
addView(progressBar, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER, 0, 0, 0, (48 + 36 + (hasDescription ? 22 : 0)) / 2));
TextView textView;
if (hasDescription) {
textView = new TextView(context);
textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
textView.setTextColor(0xff222222);
textView.setText(descripton);
textView.setSingleLine(true);
textView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
textView.setEllipsize(TextUtils.TruncateAt.END);
textView.setPadding(AndroidUtilities.dp(18), 0, AndroidUtilities.dp(18), 0);
addView(textView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.BOTTOM, 0, 0, 0, 48 + 9 + 20));
}
textView = new TextView(context);
textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
textView.setTextColor(0xff8a8a8a);
textView.setText(title);
textView.setSingleLine(true);
textView.setEllipsize(TextUtils.TruncateAt.END);
textView.setPadding(AndroidUtilities.dp(18), 0, AndroidUtilities.dp(18), 0);
addView(textView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.BOTTOM, 0, 0, 0, 48 + 9));
View lineView = new View(context);
lineView.setBackgroundColor(0xffdbdbdb);
addView(lineView, new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 1, Gravity.LEFT | Gravity.BOTTOM));
((LayoutParams) lineView.getLayoutParams()).bottomMargin = AndroidUtilities.dp(48);
FrameLayout frameLayout = new FrameLayout(context);
frameLayout.setBackgroundColor(0xffffffff);
addView(frameLayout, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.LEFT | Gravity.BOTTOM));
textView = new TextView(context);
textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
textView.setTextColor(0xff19a7e8);
textView.setGravity(Gravity.CENTER);
textView.setBackgroundDrawable(Theme.createBarSelectorDrawable(Theme.ACTION_BAR_AUDIO_SELECTOR_COLOR, false));
textView.setPadding(AndroidUtilities.dp(18), 0, AndroidUtilities.dp(18), 0);
textView.setText(LocaleController.getString("Close", R.string.Close).toUpperCase());
textView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
frameLayout.addView(textView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT));
textView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (dialog != null) {
dialog.dismiss();
}
}
});
LinearLayout linearLayout = new LinearLayout(context);
linearLayout.setOrientation(LinearLayout.HORIZONTAL);
frameLayout.addView(linearLayout, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.RIGHT));
textView = new TextView(context);
textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
textView.setTextColor(0xff19a7e8);
textView.setGravity(Gravity.CENTER);
textView.setBackgroundDrawable(Theme.createBarSelectorDrawable(Theme.ACTION_BAR_AUDIO_SELECTOR_COLOR, false));
textView.setPadding(AndroidUtilities.dp(18), 0, AndroidUtilities.dp(18), 0);
textView.setText(LocaleController.getString("Copy", R.string.Copy).toUpperCase());
textView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
linearLayout.addView(textView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT));
textView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
try {
android.content.ClipboardManager clipboard = (android.content.ClipboardManager) ApplicationLoader.applicationContext.getSystemService(Context.CLIPBOARD_SERVICE);
android.content.ClipData clip = android.content.ClipData.newPlainText("label", openUrl);
clipboard.setPrimaryClip(clip);
} catch (Exception e) {
FileLog.e("tmessages", e);
}
Toast.makeText(getContext(), LocaleController.getString("LinkCopied", R.string.LinkCopied), Toast.LENGTH_SHORT).show();
if (dialog != null) {
dialog.dismiss();
}
}
});
textView = new TextView(context);
textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
textView.setTextColor(0xff19a7e8);
textView.setGravity(Gravity.CENTER);
textView.setBackgroundDrawable(Theme.createBarSelectorDrawable(Theme.ACTION_BAR_AUDIO_SELECTOR_COLOR, false));
textView.setPadding(AndroidUtilities.dp(18), 0, AndroidUtilities.dp(18), 0);
textView.setText(LocaleController.getString("OpenInBrowser", R.string.OpenInBrowser).toUpperCase());
textView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
linearLayout.addView(textView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT));
textView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Browser.openUrl(getContext(), openUrl);
if (dialog != null) {
dialog.dismiss();
}
}
});
setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
return true;
}
});
parentDialog.setDelegate(new BottomSheet.BottomSheetDelegate() {
@Override
public void onOpenAnimationEnd() {
HashMap<String, String> args = new HashMap<>();
args.put("Referer", "http://youtube.com");
boolean ok = false;
try {
Uri uri = Uri.parse(openUrl);
String host = uri.getHost().toLowerCase();
if (host != null && host.endsWith("youtube.com") || host.endsWith("youtu.be")) {
Matcher matcher = youtubeIdRegex.matcher(openUrl);
String id = null;
if (matcher.find()) {
id = matcher.group(1);
}
if (id != null) {
ok = true;
webView.loadDataWithBaseURL("http://youtube.com", String.format(youtubeFrame, id), "text/html", "UTF-8", "http://youtube.com");
}
}
} catch (Exception e) {
FileLog.e("tmessages", e);
}
if (!ok) {
try {
webView.loadUrl(embedUrl, args);
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
}
});
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
try {
removeView(webView);
webView.stopLoading();
webView.loadUrl("about:blank");
webView.destroy();
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
float scale = width / parentWidth;
int h = (int) Math.min(height / scale, AndroidUtilities.displaySize.y / 2);
super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(h + AndroidUtilities.dp(48 + 36 + (hasDescription ? 22 : 0)) + 1, MeasureSpec.EXACTLY));
}
}
| digantDj/Gifff-Talk | TMessagesProj/src/main/java/org/giffftalk/ui/Components/WebFrameLayout.java | Java | gpl-2.0 | 17,121 |
package com.hunter.dm;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
} | wfwzhxd/none | app/src/androidTest/java/com/hunter/dm/ApplicationTest.java | Java | gpl-2.0 | 344 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.