repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
Nutty101/NPC_Destinations2
NPCDestinations-V1_15_R1/src/main/java/net/livecar/nuttyworks/npc_destinations/particles/PlayParticle_1_15_R1.java
683
package net.livecar.nuttyworks.npc_destinations.particles; import org.bukkit.Location; import org.bukkit.Particle; import org.bukkit.entity.Player; public class PlayParticle_1_15_R1 implements PlayParticleInterface { public void PlayOutHeartParticle(Location partLocation, Player player) { player.spawnParticle(Particle.HEART, partLocation.clone().add(0, 1, 0), 1); } public void PlayOutParticle(Location partLocation, Player player, SupportedParticles particle) { Particle part = Particle.valueOf(particle.toString()); if (part == null) return; player.spawnParticle(part, partLocation.clone().add(0, 1, 0), 1); } }
gpl-3.0
mydzigear/weka.kmeanspp.silhouette_score
wekafiles/packages/distributedWekaHadoopCore/src/main/java/weka/distributed/hadoop/WekaScoringHadoopJob.java
15180
/* * 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/>. */ /* * WekaScoringHadoopJob * Copyright (C) 2013 University of Waikato, Hamilton, New Zealand * */ package weka.distributed.hadoop; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.Vector; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import weka.core.CommandlineRunnable; import weka.core.Environment; import weka.core.Option; import weka.core.OptionHandler; import weka.core.Utils; import weka.distributed.DistributedWekaException; import distributed.core.DistributedJob; import distributed.core.DistributedJobConfig; import distributed.hadoop.HDFSUtils; /** * Hadoop job for scoring new data using an existing Weka classifier or * clusterer. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: 11837 $ */ public class WekaScoringHadoopJob extends HadoopJob implements CommandlineRunnable { /** The subdirectory of the output directory to save the job outputs to */ protected static final String OUTPUT_SUBDIR = "/scoring"; /** For serialization */ private static final long serialVersionUID = 2899919003194014468L; /** The columns from the original input data to output in the scoring results */ protected String m_colsRange = "first-last"; /** The path (HDFS or local) to the model to use for scoring */ protected String m_modelPath = ""; /** ARFF header job (if necessary) */ protected ArffHeaderHadoopJob m_arffHeaderJob = new ArffHeaderHadoopJob(); /** Options to the ARFF header job */ protected String m_wekaCsvToArffMapTaskOpts = ""; /** * Constructor */ public WekaScoringHadoopJob() { super("Scoring job", "Score data with a Weka model"); m_mrConfig.setMapperClass(WekaScoringHadoopMapper.class.getName()); // turn off the reducer phase as we only need mappers m_mrConfig.setMapOutputKeyClass(LongWritable.class.getName()); m_mrConfig.setMapOutputValueClass(Text.class.getName()); } /** * Help information for this job * * @return help information for this job */ public String globalInfo() { return "Score new data using a previously trained model."; } /** * Tip text for this property * * @return the tip text for this property */ public String modelPathTipText() { return "The path (HDFS or local) to the model to use for scoring"; } /** * Set the path (HDFS or local) to the model to use for scoring. * * @param modelPath the path to the model to use for scoring */ public void setModelPath(String modelPath) { m_modelPath = modelPath; } /** * Get the path (HDFS or local) to the model to use for scoring. * * @return the path to the model to use for scoring */ public String getModelPath() { return m_modelPath; } /** * Tip text for this property * * @return the tip text for this property */ public String columnsToOutputInScoredDataTipText() { return "The columns to output (as a comma-separated list of indexes) in " + "the scored data. 'first' and 'last' may be used as well (" + "e.g. 1,2,10-last)"; } /** * Set the columns to output (as a comma-separated list of indexes) in the * scored data. 'first' and 'last' may be used as well (e.g. 1,2,10-last). * * @param cols the columns to output in the scored data */ public void setColumnsToOutputInScoredData(String cols) { m_colsRange = cols; } /** * Get the columns to output (as a comma-separated list of indexes) in the * scored data. 'first' and 'last' may be used as well (e.g. 1,2,10-last). * * @return the columns to output in the scored data */ public String getColumnsToOutputInScoredData() { return m_colsRange; } /** * Set the options for the ARFF header job * * @param opts options for the ARFF header job */ public void setCSVMapTaskOptions(String opts) { m_wekaCsvToArffMapTaskOpts = opts; } /** * Get the options for the ARFF header job * * @return the options for the ARFF header job */ public String getCSVMapTaskOptions() { return m_wekaCsvToArffMapTaskOpts; } @Override public Enumeration<Option> listOptions() { Vector<Option> result = new Vector<Option>(); result.add(new Option( "\tPath to model file to use for scoring (can be \n\t" + "local or in HDFS", "model-file", 1, "-model-file <path to model file>")); result.add(new Option( "\tColumns to output in the scored data. Specify as\n\t" + "a range, e.g. 1,4,5,10-last (default = first-last).", "columns-to-output", 1, "-columns-to-output")); result.add(new Option("", "", 0, "\nOptions specific to ARFF training header creation:")); ArffHeaderHadoopJob tempArffJob = new ArffHeaderHadoopJob(); Enumeration<Option> arffOpts = tempArffJob.listOptions(); while (arffOpts.hasMoreElements()) { result.add(arffOpts.nextElement()); } return result.elements(); } @Override public void setOptions(String[] options) throws Exception { String modelPath = Utils.getOption("model-file", options); if (!DistributedJobConfig.isEmpty(modelPath)) { setModelPath(modelPath); } String range = Utils.getOption("columns-to-output", options); if (!DistributedJobConfig.isEmpty(range)) { setColumnsToOutputInScoredData(range); } // copy the options at this point so that we can set // general hadoop configuration for the ARFF header // job String[] optionsCopy = options.clone(); super.setOptions(options); m_arffHeaderJob.setOptions(optionsCopy); String optsToCSVTask = Utils.joinOptions(m_arffHeaderJob.getOptions()); if (!DistributedJobConfig.isEmpty(optsToCSVTask)) { setCSVMapTaskOptions(optsToCSVTask); } } @Override public String[] getOptions() { List<String> options = new ArrayList<String>(); if (!DistributedJobConfig.isEmpty(getModelPath())) { options.add("-model-file"); options.add(getModelPath()); } options.add("-columns-to-output"); options.add(getColumnsToOutputInScoredData()); if (!DistributedJobConfig.isEmpty(getCSVMapTaskOptions())) { try { String[] csvOpts = Utils.splitOptions(getCSVMapTaskOptions()); for (String s : csvOpts) { options.add(s); } } catch (Exception ex) { ex.printStackTrace(); } } return options.toArray(new String[options.size()]); } public String[] getJobOptionsOnly() { List<String> options = new ArrayList<String>(); if (!DistributedJobConfig.isEmpty(getModelPath())) { options.add("-model-file"); options.add(getModelPath()); } options.add("-columns-to-output"); options.add(getColumnsToOutputInScoredData()); return options.toArray(new String[options.size()]); } /** * Loads the user-supplied model and sets the job name based on the classifier * and its options. * * @param is InputStream to read the model from * @throws IOException if a problem occurs */ protected void loadClassifierAndSetJobName(InputStream is) throws IOException { ObjectInputStream ois = null; try { ois = new ObjectInputStream(new BufferedInputStream(is)); Object model = ois.readObject(); String className = model.getClass().toString(); String options = ""; if (model instanceof OptionHandler) { options = " " + Utils.joinOptions(((OptionHandler) model).getOptions()); } setJobName("Scoring job: " + className + options); } catch (Exception ex) { throw new IOException(ex); } finally { if (ois != null) { ois.close(); } } } /** * Handles loading the user-supplied model from either HDFS or the local file * system * * @param conf the Configuration for the job * @return the file name only part of the path to the model * @throws IOException if a problem occurs */ protected String handleModelFile(Configuration conf) throws IOException { String modelPath = getModelPath(); try { modelPath = environmentSubstitute(modelPath); } catch (Exception ex) { } if (modelPath.startsWith("hdfs://")) { modelPath = modelPath.replace("hdfs://", ""); // strip the host and port (if provided) modelPath = modelPath.substring(modelPath.indexOf("/")); } String modelNameOnly = null; String hdfsPath = ""; File f = new File(modelPath); boolean success = false; if (f.exists()) { // local model file if (modelPath.lastIndexOf(File.separator) >= 0) { modelNameOnly = modelPath.substring(modelPath.lastIndexOf(File.separator) + File.separator.length(), modelPath.length()); } else { modelNameOnly = modelPath; } hdfsPath = HDFSUtils.WEKA_TEMP_DISTRIBUTED_CACHE_FILES + modelNameOnly; logMessage("Copying local model file (" + modelPath + ") to HDFS."); HDFSUtils.copyToHDFS(modelPath, hdfsPath, m_mrConfig.getHDFSConfig(), m_env, true); loadClassifierAndSetJobName(new FileInputStream(f)); success = true; } else { // hdfs source hdfsPath = modelPath; modelNameOnly = modelPath.substring(modelPath.lastIndexOf("/") + 1, modelPath.length()); Configuration tempConf = new Configuration(); m_mrConfig.getHDFSConfig().configureForHadoop(tempConf, m_env); FileSystem fs = FileSystem.get(tempConf); Path p = new Path(hdfsPath); FSDataInputStream di = fs.open(p); loadClassifierAndSetJobName(di); success = true; } if (!success) { throw new IOException("Unable to locate model file: " + modelPath + " on " + "the local file system or in HDFS."); } System.err.println("Adding " + hdfsPath + " to the distributed cache."); HDFSUtils.addFileToDistributedCache(m_mrConfig.getHDFSConfig(), conf, hdfsPath, m_env); return modelNameOnly; } /** * Initializes and executes the ARFF header job if necessary * * @return true if the job succeeds * @throws DistributedWekaException if a problem occurs */ protected boolean initializeAndRunArffJob() throws DistributedWekaException { if (m_env == null) { m_env = Environment.getSystemWide(); } m_arffHeaderJob.setEnvironment(m_env); if (!m_arffHeaderJob.runJob()) { statusMessage("Unable to continue - creating the ARFF header failed!"); logMessage("Unable to continue - creating the ARFF header failed!"); return false; } // configure our output subdirectory String outputPath = m_mrConfig.getOutputPath(); outputPath += OUTPUT_SUBDIR; outputPath = environmentSubstitute(outputPath); m_mrConfig.setOutputPath(outputPath); return true; } @Override public boolean runJob() throws DistributedWekaException { if (DistributedJobConfig.isEmpty(getModelPath())) { throw new DistributedWekaException( "No model file specified - can't continue"); } boolean success = false; ClassLoader orig = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader( this.getClass().getClassLoader()); setJobStatus(JobStatus.RUNNING); if (!initializeAndRunArffJob()) { return false; } // set zero reducers - map only job m_mrConfig.setNumberOfReducers("0"); String pathToHeader = environmentSubstitute(m_arffHeaderJob.getAggregatedHeaderPath()); Configuration conf = new Configuration(); try { // add the arff header to the distributed cache HDFSUtils.addFileToDistributedCache(m_mrConfig.getHDFSConfig(), conf, pathToHeader, m_env); String modelNameOnly = handleModelFile(conf); String arffNameOnly = pathToHeader.substring(pathToHeader.lastIndexOf("/") + 1, pathToHeader.length()); String colRange = environmentSubstitute(getColumnsToOutputInScoredData()); String mapOptions = "-arff-header " + arffNameOnly + " -model-file-name " + modelNameOnly + (!DistributedJobConfig.isEmpty(colRange) ? " -columns-to-output " + colRange : ""); m_mrConfig.setUserSuppliedProperty( WekaScoringHadoopMapper.SCORING_MAP_TASK_OPTIONS, mapOptions); // Need these for row parsing via open-csv m_mrConfig.setUserSuppliedProperty( CSVToArffHeaderHadoopMapper.CSV_TO_ARFF_HEADER_MAP_TASK_OPTIONS, environmentSubstitute(getCSVMapTaskOptions())); installWekaLibrariesInHDFS(conf); Job job = null; job = m_mrConfig.configureForHadoop(getJobName(), conf, m_env); cleanOutputDirectory(job); statusMessage("Submitting scoring job: " + getJobName()); logMessage("Submitting scoring job: " + getJobName()); success = runJob(job); } catch (IOException ex) { throw new DistributedWekaException(ex); } catch (ClassNotFoundException e) { throw new DistributedWekaException(e); } } finally { Thread.currentThread().setContextClassLoader(orig); } return success; } public static void main(String[] args) { WekaScoringHadoopJob wsj = new WekaScoringHadoopJob(); wsj.run(wsj, args); } @Override public void run(Object toRun, String[] args) throws IllegalArgumentException { if (!(toRun instanceof WekaScoringHadoopJob)) { throw new IllegalArgumentException( "Object to run is not a WekaScoringHadoopJob"); } try { WekaScoringHadoopJob wsj = (WekaScoringHadoopJob) toRun; if (Utils.getFlag('h', args)) { String help = DistributedJob.makeOptionsStr(wsj); System.err.println(help); System.exit(1); } wsj.setOptions(args); wsj.runJob(); } catch (Exception ex) { ex.printStackTrace(); } } }
gpl-3.0
chusobadenas/ACMEButchers
app/src/main/java/com/acmebutchers/app/presentation/map/MapFragment.java
6272
package com.acmebutchers.app.presentation.map; import android.Manifest; import android.annotation.SuppressLint; import android.content.Context; import android.content.pm.PackageManager; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.Snackbar; import android.support.v4.content.ContextCompat; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.acmebutchers.app.R; import com.acmebutchers.app.common.di.components.MainComponent; import com.acmebutchers.app.common.util.LocationUtils; import com.acmebutchers.app.common.util.UIUtils; import com.acmebutchers.app.data.entity.LocationEntity; import com.acmebutchers.app.domain.Place; import com.acmebutchers.app.presentation.base.BaseFragment; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import java.util.List; import javax.inject.Inject; import butterknife.ButterKnife; import butterknife.Unbinder; public class MapFragment extends BaseFragment implements MapMvpView, OnMapReadyCallback { private static final int REQUEST_LOCATION = 1; private static final float ZOOM = 14.0f; @Inject MapPresenter mapPresenter; private GoogleMap googleMap; private Unbinder unbinder; /** * Creates a new instance of {@link MapFragment}. */ public static MapFragment newInstance() { return new MapFragment(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getComponent(MainComponent.class).inject(this); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View fragmentView = inflater.inflate(R.layout.fragment_map, container, false); unbinder = ButterKnife.bind(this, fragmentView); mapPresenter.attachView(this); return fragmentView; } @Override public void onStart() { super.onStart(); askForPermissions(); } @Override public void onDestroyView() { super.onDestroyView(); unbinder.unbind(); } @Override public void onDestroy() { super.onDestroy(); mapPresenter.detachView(); } @Override public void showLoading() { // Nothing to do } @Override public void hideLoading() { // Nothing to do } @Override public void showRetry() { // Nothing to do } @Override public void hideRetry() { // Nothing to do } @Override public void showError(String message) { UIUtils.showToastMessage(context(), message); } private void refreshMap() { // Load map SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map_fragment); if (mapFragment != null) { mapFragment.getMapAsync(this); } } /** * Shows the user location in the map */ @SuppressLint("MissingPermission") private void displayMapLocation() { if (LocationUtils.isLocationEnabled(context())) { googleMap.setMyLocationEnabled(true); } else { // Show settings to enable location LocationUtils.showLocationSettings(context(), getView()); } } /** * Request the location permission */ private void requestLocationPermission() { requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION); } /** * Ask for permissions */ private void askForPermissions() { // Check location permission if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager .PERMISSION_GRANTED) { refreshMap(); } else { requestLocationPermission(); } } private void loadButcherShops() { mapPresenter.loadButcherShops(); } @Override public void showButcherShops(List<Place> shops) { // Add butcher shops as markers in the map for (Place shop : shops) { MarkerOptions marker = new MarkerOptions() .position(new LatLng(shop.location().latitude(), shop.location().longitude())) .title(shop.name()); googleMap.addMarker(marker); } // Center map mapPresenter.centerMap(); } @Override public void centerMap(LocationEntity location) { if (location != null) { LatLng latLng = new LatLng(location.latitude(), location.longitude()); googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, ZOOM)); } } @Override public void onMapReady(GoogleMap googleMap) { this.googleMap = googleMap; // Show current location displayMapLocation(); // Load butcher shops loadButcherShops(); } /** * Shows a dialog to request location permission */ private void showDialog2RequestLocation() { if (shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_FINE_LOCATION)) { // Provide an additional rationale to the user if the permission was not granted Snackbar.make(getView(), R.string.permission_location_rationale, Snackbar.LENGTH_INDEFINITE) .setAction(android.R.string.ok, new View.OnClickListener() { @Override public void onClick(View view) { requestLocationPermission(); } }).show(); } else { // User does not want to request permission again Snackbar.make(getView(), R.string.permission_location_not_granted, Snackbar.LENGTH_SHORT).show(); } } /** * {@inheritDoc} */ @Override public final void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == REQUEST_LOCATION && grantResults.length == 1) { if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { refreshMap(); } // Permission NOT granted else { showDialog2RequestLocation(); } } else { super.onRequestPermissionsResult(requestCode, permissions, grantResults); } } @Override public Context context() { return getActivity(); } }
gpl-3.0
lichfolky/Simulazione
Simulazione/src/analyticalmethods/TestEquazioniBilanciamento.java
2181
/* * 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 analyticalmethods; import analyticalmodels.ClosedQueueModel; import analyticalmodels.StationType; import distributions.Distribution; import distributions.NegExp; import java.util.Arrays; import random.MTRandomHiroshima; /** * * @author mattiafolcarelli */ public class TestEquazioniBilanciamento { public static void main(String[] args) { double s0 = 4.0; double s1 = 40.0; double s2 = 2.0; double s3 = 30.0; double s4 = 200.0; int nStations = 5; int seed = 123; int nJobs = 16; MTRandomHiroshima r = new MTRandomHiroshima(seed); Distribution[] serviceDistibutions = new Distribution[nStations]; serviceDistibutions[0] = new NegExp(r, s0); serviceDistibutions[1] = new NegExp(r, s1); serviceDistibutions[2] = new NegExp(r, s2); serviceDistibutions[3] = new NegExp(r, s3); serviceDistibutions[4] = new NegExp(r, s4); double[][] q = new double[nStations][nStations]; for (int i = 0; i < nStations; i++) { for (int j = 0; j < nStations; j++) { q[i][j] = 0.0; } } q[1][1] = 0.2; q[1][2] = 0.8; q[2][1] = 0.6; q[2][3] = 0.4; q[3][0] = 0.8; q[3][4] = 0.2; q[0][1] = 1.0; q[4][0] = 1.0; StationType[] stationType = new StationType[nStations]; stationType[0] = StationType.INFINITE_SERVER; stationType[1] = StationType.SINGLE_SERVER; stationType[2] = StationType.SINGLE_SERVER; stationType[3] = StationType.INFINITE_SERVER; stationType[4] = StationType.INFINITE_SERVER; analyticalmodels.ClosedQueueModel modello = new ClosedQueueModel(stationType, serviceDistibutions, q); for (int i = 0; i < modello.getNStations(); i++) { System.out.println(Arrays.toString(EquazioniDiBilanciamento.getVisitVector(modello.getTransitionMatrix(), i))); } } }
gpl-3.0
KyleGrund/ViTeMBP-BEJava
ViTeMBP Services/src/com/vitembp/services/sensors/SensorFactory.java
3698
/* * Video Telemetry for Mountain Bike Platform back-end services. * Copyright (C) 2017 Kyle Grund * * 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.vitembp.services.sensors; import com.vitembp.embedded.data.Capture; import java.util.HashMap; import java.util.Map; import java.util.UUID; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; /** * A factory class which creates sensor objects. */ public class SensorFactory { /** * Class logger instance. */ private static final Logger LOGGER = LogManager.getLogger(); /** * Gets a sensor for the name and type provided. * @param name The name of the sensor to build. * @param type The type of the sensor to build. * @param calData The sensor calibration data. * @return A sensor object for the provided name and type. * @throws InstantiationException If the sensor type is unknown. */ public static Sensor getSensor(String name, UUID type, String calData) throws InstantiationException { // build sensor object based on type UUID if (RotaryEncoderEAW0J.TYPE_UUID.equals(type)) { return new RotaryEncoderEAW0J(name, calData); } else if (AccelerometerFXOS8700CQSerial.TYPE_UUID.equals(type)) { return new AccelerometerFXOS8700CQSerial(name, calData); } else if (DistanceVL53L0X.TYPE_UUID.equals(type)) { return new DistanceVL53L0X(name, calData); }else if (DistanceVL6180X.TYPE_UUID.equals(type)) { return new DistanceVL6180X(name, calData); } else if (AccelerometerADXL326.TYPE_UUID.equals(type)){ return new AccelerometerADXL326(name, calData); } // throw exception indicating no sensor type could be built throw new InstantiationException( "Could not create sensor named \"" + name + "\" with ID \"" + type.toString() + "\"."); } /** * Builds sensor objects for all known sensors in the capture. * @param toBuildFor The capture to build sensors for. * @return A list containing sensor objects for all known sensors. */ public static Map<String, Sensor> getSensors(Capture toBuildFor) { Map<String, Sensor> toReturn = new HashMap<>(); toBuildFor.getSensorTypes().entrySet().stream() .map((entry) -> { try { return SensorFactory.getSensor( entry.getKey(), entry.getValue(), toBuildFor.getSensorCalibrations().get(entry.getKey())); } catch (InstantiationException ex) { LOGGER.error("Unknown sensor: " + entry.getKey() + ", " + entry.getValue().toString() + ".", ex); return null; } }) .forEach(s -> toReturn.put(s.getName(), s)); return toReturn; } }
gpl-3.0
TypedScroll/LCPD
core/src/main/java/com/shatteredpixel/lovecraftpixeldungeon/effects/particles/RainbowParticle.java
1953
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2016 Evan Debenham * * 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.shatteredpixel.lovecraftpixeldungeon.effects.particles; import com.watabou.noosa.particles.Emitter; import com.watabou.noosa.particles.PixelParticle; import com.watabou.utils.PointF; import com.watabou.utils.Random; public class RainbowParticle extends PixelParticle { public static final Emitter.Factory BURST = new Emitter.Factory() { @Override public void emit( Emitter emitter, int index, float x, float y ) { ((RainbowParticle)emitter.recycle( RainbowParticle.class )).resetBurst( x, y ); } @Override public boolean lightMode() { return true; } }; public RainbowParticle() { super(); color( Random.Int( 0x1000000 ) ); lifespan = 0.5f; } public void reset( float x, float y ) { revive(); this.x = x; this.y = y; speed.set( Random.Float(-5, +5), Random.Float( -5, +5 ) ); left = lifespan; } public void resetBurst( float x, float y ) { revive(); this.x = x; this.y = y; speed.polar( Random.Float( PointF.PI2 ), Random.Float( 16, 32 ) ); left = lifespan; } @Override public void update() { super.update(); // alpha: 1 -> 0; size: 1 -> 5 size( 5 - (am = left / lifespan) * 4 ); } }
gpl-3.0
mebrah2/api-themoviedb
src/main/java/com/omertron/themoviedbapi/methods/TmdbLists.java
8592
/* * Copyright (c) 2004-2015 Stuart Boston * * This file is part of TheMovieDB API. * * TheMovieDB API 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 * any later version. * * TheMovieDB API 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 TheMovieDB API. If not, see <http://www.gnu.org/licenses/>. * */ package com.omertron.themoviedbapi.methods; import com.fasterxml.jackson.core.type.TypeReference; import com.omertron.themoviedbapi.MovieDbException; import com.omertron.themoviedbapi.model.list.ListStatusCode; import com.omertron.themoviedbapi.model.StatusCode; import com.omertron.themoviedbapi.model.list.ListItem; import com.omertron.themoviedbapi.model.list.ListItemStatus; import com.omertron.themoviedbapi.model.movie.MovieInfo; import com.omertron.themoviedbapi.tools.ApiUrl; import com.omertron.themoviedbapi.tools.HttpTools; import com.omertron.themoviedbapi.tools.MethodBase; import com.omertron.themoviedbapi.tools.MethodSub; import com.omertron.themoviedbapi.tools.Param; import com.omertron.themoviedbapi.tools.PostBody; import com.omertron.themoviedbapi.tools.PostTools; import com.omertron.themoviedbapi.tools.TmdbParameters; import java.io.IOException; import java.net.URL; import org.apache.commons.lang3.StringUtils; import org.yamj.api.common.exception.ApiExceptionType; /** * Class to hold the List Methods * * @author stuart.boston */ public class TmdbLists extends AbstractMethod { /** * Constructor * * @param apiKey * @param httpTools */ public TmdbLists(String apiKey, HttpTools httpTools) { super(apiKey, httpTools); } /** * Get a list by its ID * * @param listId * @return The list and its items * @throws MovieDbException */ public ListItem<MovieInfo> getList(String listId) throws MovieDbException { TmdbParameters parameters = new TmdbParameters(); parameters.add(Param.ID, listId); URL url = new ApiUrl(apiKey, MethodBase.LIST).buildUrl(parameters); String webpage = httpTools.getRequest(url); try { return MAPPER.readValue(webpage, new TypeReference<ListItem<MovieInfo>>() { }); } catch (IOException ex) { throw new MovieDbException(ApiExceptionType.MAPPING_FAILED, "Failed to get list", url, ex); } } /** * Check to see if an ID is already on a list. * * @param listId * @param mediaId * @return true if the movie is on the list * @throws MovieDbException */ public boolean checkItemStatus(String listId, int mediaId) throws MovieDbException { TmdbParameters parameters = new TmdbParameters(); parameters.add(Param.ID, listId); parameters.add(Param.MOVIE_ID, mediaId); URL url = new ApiUrl(apiKey, MethodBase.LIST).subMethod(MethodSub.ITEM_STATUS).buildUrl(parameters); String webpage = httpTools.getRequest(url); try { return MAPPER.readValue(webpage, ListItemStatus.class).isItemPresent(); } catch (IOException ex) { throw new MovieDbException(ApiExceptionType.MAPPING_FAILED, "Failed to get item status", url, ex); } } /** * This method lets users create a new list. A valid session id is required. * * @param sessionId * @param name * @param description * @return The list id * @throws MovieDbException */ public String createList(String sessionId, String name, String description) throws MovieDbException { TmdbParameters parameters = new TmdbParameters(); parameters.add(Param.SESSION_ID, sessionId); String jsonBody = new PostTools() .add(PostBody.NAME, StringUtils.trimToEmpty(name)) .add(PostBody.DESCRIPTION, StringUtils.trimToEmpty(description)) .build(); URL url = new ApiUrl(apiKey, MethodBase.LIST).buildUrl(parameters); String webpage = httpTools.postRequest(url, jsonBody); try { return MAPPER.readValue(webpage, ListStatusCode.class).getListId(); } catch (IOException ex) { throw new MovieDbException(ApiExceptionType.MAPPING_FAILED, "Failed to create list", url, ex); } } /** * This method lets users delete a list that they created. A valid session id is required. * * @param sessionId * @param listId * @return * @throws MovieDbException */ public StatusCode deleteList(String sessionId, String listId) throws MovieDbException { TmdbParameters parameters = new TmdbParameters(); parameters.add(Param.ID, listId); parameters.add(Param.SESSION_ID, sessionId); URL url = new ApiUrl(apiKey, MethodBase.LIST).buildUrl(parameters); String webpage = httpTools.deleteRequest(url); try { return MAPPER.readValue(webpage, StatusCode.class); } catch (IOException ex) { throw new MovieDbException(ApiExceptionType.MAPPING_FAILED, "Failed to delete list", url, ex); } } /** * Modify a list * * This can be used to add or remove an item from the list * * @param sessionId * @param listId * @param movieId * @param operation * @return * @throws MovieDbException */ private StatusCode modifyMovieList(String sessionId, String listId, int movieId, MethodSub operation) throws MovieDbException { TmdbParameters parameters = new TmdbParameters(); parameters.add(Param.SESSION_ID, sessionId); parameters.add(Param.ID, listId); String jsonBody = new PostTools() .add(PostBody.MEDIA_ID, movieId) .build(); URL url = new ApiUrl(apiKey, MethodBase.LIST).subMethod(operation).buildUrl(parameters); String webpage = httpTools.postRequest(url, jsonBody); try { return MAPPER.readValue(webpage, StatusCode.class); } catch (IOException ex) { throw new MovieDbException(ApiExceptionType.MAPPING_FAILED, "Failed to remove item from list", url, ex); } } /** * This method lets users add new items to a list that they created. * * A valid session id is required. * * @param sessionId * @param listId * @param mediaId * @return * @throws MovieDbException */ public StatusCode addItem(String sessionId, String listId, int mediaId) throws MovieDbException { return modifyMovieList(sessionId, listId, mediaId, MethodSub.ADD_ITEM); } /** * This method lets users delete items from a list that they created. * * A valid session id is required. * * @param sessionId * @param listId * @param mediaId * @return * @throws MovieDbException */ public StatusCode removeItem(String sessionId, String listId, int mediaId) throws MovieDbException { return modifyMovieList(sessionId, listId, mediaId, MethodSub.REMOVE_ITEM); } /** * Clear all of the items within a list. * * This is a irreversible action and should be treated with caution. * * A valid session id is required. A call without confirm=true will return status code 29. * * @param sessionId * @param listId * @param confirm * @return * @throws MovieDbException */ public StatusCode clear(String sessionId, String listId, boolean confirm) throws MovieDbException { TmdbParameters parameters = new TmdbParameters(); parameters.add(Param.SESSION_ID, sessionId); parameters.add(Param.ID, listId); parameters.add(Param.CONFIRM, confirm); URL url = new ApiUrl(apiKey, MethodBase.LIST).subMethod(MethodSub.CLEAR).buildUrl(parameters); String webpage = httpTools.postRequest(url, ""); try { return MAPPER.readValue(webpage, StatusCode.class); } catch (IOException ex) { throw new MovieDbException(ApiExceptionType.MAPPING_FAILED, "Failed to clear list", url, ex); } } }
gpl-3.0
jlgconsulting/JADE-JavaAsterixDecoderEncoder
src/main/java/jlg/jade/asterix/cat062/item390/Cat062Item390Subfield5.java
2041
/* * Created by dan-geabunea on 5/11/2016. * This code is the property of JLG Consulting. Please * check the license terms for this product to see under what * conditions you can use or modify this source code. */ package jlg.jade.asterix.cat062.item390; import jlg.jade.asterix.AsterixItemLength; import jlg.jade.asterix.FixedLengthAsterixData; import java.io.UnsupportedEncodingException; /** * Item 390 Subfield 5 - Type of Aircraft * Each one of the four Octets composing the type of an aircraft contains an * ASCII Character (upper-case alphabetic characters with trailing spaces) */ public class Cat062Item390Subfield5 extends FixedLengthAsterixData { private String typeOfAircraft; @Override protected int setSizeInBytes() { return AsterixItemLength.FOUR_BYTES.getValue(); } @Override protected void decodeFromByteArray(byte[] input, int offset) { try { this.typeOfAircraft = new String(input, offset, getSizeInBytes(), "UTF-8").replace(" ", ""); appendItemDebugMsg("Type of aircraft", this.typeOfAircraft); } catch (UnsupportedEncodingException e) { appendErrorMessage("Unsupported encoding exception"); } } @Override public byte[] encode() { if(this.typeOfAircraft.length() > this.sizeInBytes){ throw new RuntimeException("Invalid type of aircraft. Length exceeded. Value: " + this.typeOfAircraft); } byte[] itemAsByteArray = this.typeOfAircraft.getBytes(); return itemAsByteArray; } /** * @return The type of the aircraft, as a String */ public String getTypeOfAircraft() { return typeOfAircraft; } /** * Set the type of aircraft. Maximum 4 characters. * @param typeOfAircraft */ public void setTypeOfAircraft(String typeOfAircraft) { this.typeOfAircraft = typeOfAircraft; } @Override protected String setDisplayName() { return "Cat062Item390Subfield5 - Type of Aircraft"; } }
gpl-3.0
ceskaexpedice/kramerius
shared/common/src/test/java/cz/incad/kramerius/fedora/om/RELSEXTSPARQLBuilderImplTest.java
1586
package cz.incad.kramerius.fedora.om; import cz.incad.kramerius.FedoraAccess; import cz.incad.kramerius.fedora.impl.DataPrepare; import cz.incad.kramerius.fedora.om.impl.RELSEXTSPARQLBuilderImpl; import junit.framework.TestCase; import org.apache.commons.io.IOUtils; import org.junit.Assert; import org.xml.sax.SAXException; import javax.xml.parsers.ParserConfigurationException; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Created by pstastny on 11/1/2017. */ public class RELSEXTSPARQLBuilderImplTest extends TestCase{ public void testRelsExtSParql() throws IOException, RepositoryException, SAXException, ParserConfigurationException { URL resource = RELSEXTSPARQLBuilderImplTest.class.getClassLoader().getResource("cz/incad/kramerius/fedora/om/5035a48a-5e2e-486c-8127-2fa650842e46.xml"); String s = IOUtils.toString(resource.openStream(), "UTF-8"); RELSEXTSPARQLBuilderImpl impl = new RELSEXTSPARQLBuilderImpl(); String sparqlProps = impl.sparqlProps(s, null); System.out.println(sparqlProps); Assert.assertTrue(sparqlProps.contains("<> <info:fedora/fedora-system:def/model#hasModel> <model:monograph>.")); Assert.assertTrue(sparqlProps.contains("<> <http://www.openarchives.org/OAI/2.0/#itemID> \"uuid:5035a48a-5e2e-486c-8127-2fa650842e46\".")); for(int i=1;i<=36;i++) { Assert.assertTrue(sparqlProps.contains("<> <http://www.nsdl.org/ontologies/relationships#hasPage> <#page"+i+">.")); } } }
gpl-3.0
Dacktar13/Power_Storage
common/powerstorage/configuration/ConfigurationHandler.java
8778
package powerstorage.configuration; import static net.minecraftforge.common.Configuration.CATEGORY_GENERAL; import java.io.File; import java.util.logging.Level; import net.minecraftforge.common.Configuration; import powerstorage.lib.BlockIds; import powerstorage.lib.ItemIds; import powerstorage.lib.Reference; import powerstorage.lib.Strings; import cpw.mods.fml.common.FMLLog; /** * PowerStorage * * ConfigurationHandler * * @author Dacktar * @license Lesser GNU Public License v3 (http://www.gnu.org/licenses/lgpl.html) * */ public class ConfigurationHandler { public static Configuration configuration; public static final String CATEGORY_KEYBIND = "keybindings"; public static final String CATEGORY_GRAPHICS = "graphics"; public static final String CATEGORY_AUDIO = "audio"; public static final String CATEGORY_TRANSMUTATION = "transmutation"; public static final String CATEGORY_BLOCK_PROPERTIES = Configuration.CATEGORY_BLOCK + Configuration.CATEGORY_SPLITTER + "properties"; public static final String CATEGORY_MERCURY_LIQUID_PROPERTIES = CATEGORY_BLOCK_PROPERTIES + Configuration.CATEGORY_SPLITTER + "mercury_liquid"; public static final String CATEGORY_DURABILITY = Configuration.CATEGORY_ITEM + Configuration.CATEGORY_SPLITTER + "durability"; public static void init(File configFile) { configuration = new Configuration(configFile); try { configuration.load(); /* General configs */ ConfigurationSettings.DISPLAY_VERSION_RESULT = configuration.get(CATEGORY_GENERAL, ConfigurationSettings.DISPLAY_VERSION_RESULT_CONFIGNAME, ConfigurationSettings.DISPLAY_VERSION_RESULT_DEFAULT).getBoolean(ConfigurationSettings.DISPLAY_VERSION_RESULT_DEFAULT); ConfigurationSettings.LAST_DISCOVERED_VERSION = configuration.get(CATEGORY_GENERAL, ConfigurationSettings.LAST_DISCOVERED_VERSION_CONFIGNAME, ConfigurationSettings.LAST_DISCOVERED_VERSION_DEFAULT).getString(); ConfigurationSettings.LAST_DISCOVERED_VERSION_TYPE = configuration.get(CATEGORY_GENERAL, ConfigurationSettings.LAST_DISCOVERED_VERSION_TYPE_CONFIGNAME, ConfigurationSettings.LAST_DISCOVERED_VERSION_TYPE_DEFAULT).getString(); /* Graphic configs */ ConfigurationSettings.ENABLE_PARTICLE_FX = configuration.get(CATEGORY_GRAPHICS, ConfigurationSettings.ENABLE_PARTICLE_FX_CONFIGNAME, ConfigurationSettings.ENABLE_PARTICLE_FX_DEFAULT).getBoolean(ConfigurationSettings.ENABLE_PARTICLE_FX_DEFAULT); ConfigurationSettings.ENABLE_OVERLAY_WORLD_TRANSMUTATION = configuration.get(CATEGORY_GRAPHICS, ConfigurationSettings.ENABLE_OVERLAY_WORLD_TRANSMUTATION_CONFIGNAME, ConfigurationSettings.ENABLE_OVERLAY_WORLD_TRANSMUTATION_DEFAULT).getBoolean(ConfigurationSettings.ENABLE_OVERLAY_WORLD_TRANSMUTATION_DEFAULT); ConfigurationSettings.TARGET_BLOCK_OVERLAY_POSITION = configuration.get(CATEGORY_GRAPHICS, ConfigurationSettings.TARGET_BLOCK_OVERLAY_POSITION_CONFIGNAME, ConfigurationSettings.TARGET_BLOCK_OVERLAY_POSITION_DEFAULT).getInt(ConfigurationSettings.TARGET_BLOCK_OVERLAY_POSITION_DEFAULT); try { ConfigurationSettings.TARGET_BLOCK_OVERLAY_SCALE = Float.parseFloat(configuration.get(CATEGORY_GRAPHICS, ConfigurationSettings.TARGET_BLOCK_OVERLAY_SCALE_CONFIGNAME, ConfigurationSettings.TARGET_BLOCK_OVERLAY_SCALE_DEFAULT).getString()); if (ConfigurationSettings.TARGET_BLOCK_OVERLAY_SCALE <= 0F) { ConfigurationSettings.TARGET_BLOCK_OVERLAY_SCALE = ConfigurationSettings.TARGET_BLOCK_OVERLAY_SCALE_DEFAULT; } } catch (Exception e) { ConfigurationSettings.TARGET_BLOCK_OVERLAY_SCALE = ConfigurationSettings.TARGET_BLOCK_OVERLAY_SCALE_DEFAULT; } try { ConfigurationSettings.TARGET_BLOCK_OVERLAY_OPACITY = Float.parseFloat(configuration.get(CATEGORY_GRAPHICS, ConfigurationSettings.TARGET_BLOCK_OVERLAY_OPACITY_CONFIGNAME, ConfigurationSettings.TARGET_BLOCK_OVERLAY_OPACITY_DEFAULT).getString()); if (ConfigurationSettings.TARGET_BLOCK_OVERLAY_OPACITY < 0F || ConfigurationSettings.TARGET_BLOCK_OVERLAY_OPACITY > 1F) { ConfigurationSettings.TARGET_BLOCK_OVERLAY_OPACITY = ConfigurationSettings.TARGET_BLOCK_OVERLAY_OPACITY_DEFAULT; } } catch (Exception e) { ConfigurationSettings.TARGET_BLOCK_OVERLAY_OPACITY = ConfigurationSettings.TARGET_BLOCK_OVERLAY_OPACITY_DEFAULT; } /* Audio configs */ ConfigurationSettings.ENABLE_SOUNDS = configuration.get(CATEGORY_AUDIO, ConfigurationSettings.ENABLE_SOUNDS_CONFIGNAME, ConfigurationSettings.ENABLE_SOUNDS_DEFAULT).getString(); /* Block configs */ BlockIds.MERCURY_ORE = configuration.getBlock(Strings.MERCURY_ORE_NAME, BlockIds.MERCURY_ORE_DEFAULT).getInt(BlockIds.MERCURY_ORE_DEFAULT); BlockIds.BATTERTY_BOX = configuration.getBlock(Strings.BATTERTY_BOX_NAME, BlockIds.BATTERTY_BOX_DEFAULT).getInt(BlockIds.BATTERTY_BOX_DEFAULT); BlockIds.CONDENSER = configuration.getBlock(Strings.CONDENSER_NAME, BlockIds.CONDENSER_DEFAULT).getInt(BlockIds.CONDENSER_DEFAULT); BlockIds.MERCURY_CUBE_EMPTY = configuration.getBlock(Strings.MERCURY_CUBE_EMPTY_NAME, BlockIds.MERCURY_CUBE_EMPTY_DEFAULT).getInt(BlockIds.MERCURY_CUBE_EMPTY_DEFAULT); BlockIds.MERCURY_CUBE_FULL = configuration.getBlock(Strings.MERCURY_CUBE_FULL_NAME, BlockIds.MERCURY_CUBE_FULL_DEFAULT).getInt(BlockIds.MERCURY_CUBE_FULL_DEFAULT); BlockIds.MERCURY_LIQUID_STILL = configuration.getBlock(Strings.MERCURY_LIQUID_STILL_NAME, BlockIds.MERCURY_LIQUID_STILL_DEFAULT).getInt(BlockIds.MERCURY_LIQUID_STILL_DEFAULT); BlockIds.MERCURY_LIQUID_MOVING = configuration.getBlock(Strings.MERCURY_LIQUID_MOVING_NAME, BlockIds.MERCURY_LIQUID_MOVING_DEFAULT).getInt(BlockIds.MERCURY_LIQUID_MOVING_DEFAULT); /* Block property configs */ configuration.addCustomCategoryComment(CATEGORY_BLOCK_PROPERTIES, "Custom block properties"); /* Red Water configs */ configuration.addCustomCategoryComment(CATEGORY_MERCURY_LIQUID_PROPERTIES, "Configuration settings for various properties of Mercury Liquid"); ConfigurationSettings.MERCURY_LIQUID_DURATION_BASE = configuration.get(CATEGORY_MERCURY_LIQUID_PROPERTIES, ConfigurationSettings.MERCURY_LIQUID_DURATION_BASE_CONFIGNAME, ConfigurationSettings.MERCURY_LIQUID_DURATION_BASE_DEFAULT).getInt(ConfigurationSettings.MERCURY_LIQUID_DURATION_BASE_DEFAULT); ConfigurationSettings.MERCURY_LIQUID_DURATION_MODIFIER = configuration.get(CATEGORY_MERCURY_LIQUID_PROPERTIES, ConfigurationSettings.MERCURY_LIQUID_DURATION_MODIFIER_CONFIGNAME, ConfigurationSettings.MERCURY_LIQUID_DURATION_MODIFIER_DEFAULT).getInt(ConfigurationSettings.MERCURY_LIQUID_DURATION_MODIFIER_DEFAULT); ConfigurationSettings.MERCURY_LIQUID_RANGE_BASE = configuration.get(CATEGORY_MERCURY_LIQUID_PROPERTIES, ConfigurationSettings.MERCURY_LIQUID_RANGE_BASE_CONFIGNAME, ConfigurationSettings.MERCURY_LIQUID_RANGE_BASE_DEFAULT).getInt(ConfigurationSettings.MERCURY_LIQUID_RANGE_BASE_DEFAULT); ConfigurationSettings.MERCURY_LIQUID_RANGE_MODIFIER = configuration.get(CATEGORY_MERCURY_LIQUID_PROPERTIES, ConfigurationSettings.MERCURY_LIQUID_RANGE_MODIFIER_CONFIGNAME, ConfigurationSettings.MERCURY_LIQUID_RANGE_MODIFIER_DEFAULT).getInt(ConfigurationSettings.MERCURY_LIQUID_RANGE_MODIFIER_DEFAULT); /* Item configs */ ItemIds.MERCURY_PIPE = configuration.getItem(Strings.MERCURY_PIPE_NAME, ItemIds.MERCURY_PIPE_DEFAULT).getInt(ItemIds.MERCURY_PIPE_DEFAULT); ItemIds.MERCURY_INGOT = configuration.getItem(Strings.MERCURY_INGOT_NAME, ItemIds.MERCURY_INGOT_DEFAULT).getInt(ItemIds.MERCURY_INGOT_DEFAULT); ItemIds.BUCKET_MERCURY = configuration.getItem(Strings.BUCKET_MERCURY_NAME, ItemIds.BUCKET_MERCURY_DEFAULT).getInt(ItemIds.BUCKET_MERCURY_DEFAULT); } catch (Exception e) { FMLLog.log(Level.SEVERE, e, Reference.MOD_NAME + " has had a problem loading its configuration"); } finally { configuration.save(); } } public static void set(String categoryName, String propertyName, String newValue) { configuration.load(); if (configuration.getCategoryNames().contains(categoryName)) { if (configuration.getCategory(categoryName).containsKey(propertyName)) { configuration.getCategory(categoryName).get(propertyName).set(newValue); } } configuration.save(); } }
gpl-3.0
sklintyg/webcert
web/src/test/java/se/inera/intyg/webcert/web/web/controller/facade/LogControllerTest.java
1732
/* * Copyright (C) 2022 Inera AB (http://www.inera.se) * * This file is part of sklintyg (https://github.com/sklintyg). * * sklintyg 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. * * sklintyg 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 se.inera.intyg.webcert.web.web.controller.facade; import static org.mockito.Mockito.verify; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import se.inera.intyg.webcert.web.service.facade.ErrorLogFacadeService; import se.inera.intyg.webcert.web.web.controller.facade.dto.ErrorLogRequestDTO; @ExtendWith(MockitoExtension.class) public class LogControllerTest { @Mock private ErrorLogFacadeService errorLogFacadeService; @InjectMocks private LogController logController; @Nested class LogError { @Test void shallCallErrorLogFacadeService() { ErrorLogRequestDTO request = new ErrorLogRequestDTO(); logController.logError(request); verify(errorLogFacadeService).log(request); } } }
gpl-3.0
mathisdt/trackworktime
app/src/main/java/org/zephyrsoft/trackworktime/location/Result.java
1065
/* * This file is part of TrackWorkTime (TWT). * * TWT is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License 3.0 as published by * the Free Software Foundation. * * TWT 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 3.0 for more details. * * You should have received a copy of the GNU General Public License 3.0 * along with TWT. If not, see <http://www.gnu.org/licenses/>. */ package org.zephyrsoft.trackworktime.location; /** * Result which gets returned by {@link LocationTracker#startTrackingByLocation(double, double, double, boolean)}. */ public enum Result { /** successfully started the tracking */ SUCCESS, /** could not start the tracking because is was already running */ FAILURE_ALREADY_RUNNING, /** could not start the tracking, the app doesn't have the necessary rights */ FAILURE_INSUFFICIENT_RIGHTS }
gpl-3.0
suwhs/android-plugins-annotations-compiler
src/main/java/su/whs/plugins/core/PluginReceiverCodeGenerator.java
7203
package su.whs.plugins.core; import java.io.IOException; import java.util.List; import javax.lang.model.element.TypeElement; import su.whs.plugins.annotations.Plugin; /** * Created by igor n. boulliev on 14.08.15. */ public class PluginReceiverCodeGenerator extends BaseCodeGenerator { public PluginReceiverCodeGenerator(GenerationEnvironment env, PluginInterfacesGroup interfaces, PluginAnnotatedGroup plugins) { super(env, interfaces, plugins); } @Override public void generate() throws IOException, InterruptedException { super.generate(); /* next, generate BroadcastReceiver WHSPluginsBroadcastReceiver */ /* connect to IWHSHostServiceCb */ StringBuilder broadcastReceiverCode = new StringBuilder(); broadcastReceiverCode.append("package ").append(mEnvironment.getAndroidPackageName()).append(";\n\n"); injectImports(broadcastReceiverCode); injectReceiverCode(broadcastReceiverCode); } public String getReceiverClassName() { return "WHSPluginsBroadcastReceiver"; } private String mPluginTargetPackage = null; public String getPluginTargetPackage() { if (mPluginTargetPackage==null) { for (TypeElement plugin : mPluginsGroup.mItems) { Plugin annotation = plugin.getAnnotation(Plugin.class); if (annotation!=null) { mPluginTargetPackage = annotation.forPackage(); break; } } } return mPluginTargetPackage; } public String getManifestInjectCode() { return new StringBuilder("<receiver android:name=\".") .append(getReceiverClassName()) .append("\" android:enabled=true>") .append("\n") .append("<intent-filter>\n") .append("<action android:name=\"") .append(getReceiverAction()) .append("\"/>\n") .append("</intent-filter>\n</receiver>").toString(); } private static String[] DEFAULT_JAVA_IMPORTS = new String[] { "android.content.BroadcastReceiver", "android.content.Context", "android.content.Intent", "android.os.Bundle", "import android.util.Log" }; private StringBuilder injectImports(StringBuilder code) { for (String importPackage : DEFAULT_JAVA_IMPORTS) { code.append("import ").append(importPackage).append(";\n"); } for (TypeElement plugin : mPluginsGroup.mItems) { code.append("import ").append(plugin.getQualifiedName()).append(";\n"); } for (TypeElement pluginInterface : mInterfacesGroup.mItems) { String pp = mEnvironment.getElementUtils().getPackageOf(pluginInterface).getQualifiedName().toString(); String cn = pluginInterface.getSimpleName().toString(); code.append("import ").append(pp).append("I").append(cn).append("Cb;\n"); } return code.append("\n"); } private StringBuilder injectReceiverCode(StringBuilder code) { code .append("/* PluginReceiverCodeGenerator.injectReceiverCode */\n") .append("public class ") .append(getReceiverClassName()) .append(" extends BroadcastReceiver {\n") .append(" private ").append(Constants.whsHostServiceInterface).append(" mHostSvc;\n") .append(" private boolean mIsRegistered = false;\n") .append(" private List<IPluginInterface> mRegistered = new ArrayList<IPluginInterface>();\n") .append(generateServiceConnection()) .append(" @Override\n public void onReceive(Context context, Intent intent) {\n") .append(" if (\"").append(getReceiverAction()).append("\".equals(intent.getAction()) {\n") .append(" handlePresenceAction(context,intent)\n }\n }\n\n"); code .append(" private void handlePresenceAction(Context context, Intent intent) {\n") .append(generatePresenceHandler()) .append(" }") .append(" private void registerPlugins() {\n"); for (TypeElement plugin : mPluginsGroup.mItems) { code.append(generatePluginRegistrationCode(plugin)); } code .append("\n mIsRegistered = true;\n }") .append(" private void unregisterPlugins() {\n") .append(" for(IPpluginInterface ipi : mRegistered) ipi.unregister();\n") .append(" mRegistered.clear();\n mIsRegistered = false;\n }\n"); return code; } private String getReceiverAction() { return new StringBuilder(Constants.whsHostBroadcastIntentPrefix) .append(mPluginTargetPackage) .append(Constants.whsHostBroadcastIntentSuffix).toString(); } private String generateServiceConnection() { StringBuilder serviceConn = new StringBuilder(" private ServiceConnection mServiceConn = new ServiceConnection() {\n") .append(" @Override\n") .append(" public void onServiceConnected(ComponentName name, IBinder service) {\n") .append(" mHostSvc = ").append(Constants.whsHostServiceStub).append(".asInterface(service);\n") .append(" registerPlugins();\n") .append(" }\n") .append(" @Override\n") .append(" public void onServiceDisconnected(ComponentName name) {\n") .append(" unregisterPlugins();\n") .append(" }\n") .append(" }\n"); return serviceConn.toString(); } private String generatePresenceHandler() { StringBuilder handler = new StringBuilder(); handler.append(" if (mRegistered) return;\n"); return handler.toString(); } private String generatePluginRegistrationCode(TypeElement plugin) { StringBuilder code = new StringBuilder(); TypeElement pluginInterface = mPluginsGroup.getInterfaceForPlugin(plugin); String interfaceName = "I"+pluginInterface.getSimpleName().toString()+"Cb"; code .append("final ").append(plugin.getSimpleName()).append(" _").append(plugin.getSimpleName()) .append(" = new ").append(plugin.getSimpleName()).append("();\n") .append("mHostSvc.register_").append(interfaceName).append("(new ").append(interfaceName) .append(".Stub() {\n"); injectInterfaceStub(pluginInterface, "_" + plugin.getSimpleName().toString(), code) .append("}\n"); /* */ return code.toString(); } private StringBuilder injectInterfaceStub(TypeElement pluginInterface, String instance, StringBuilder code) { // marshalled method declarations! List<MarshalMethodDef> methods = mInterfacesGroup.getMarshalMethodDef(pluginInterface); return code; } }
gpl-3.0
JerryI00/releasing-codes-java
src/jmetal/metaheuristics/moead/DPPDRA_Epsilon.java
23390
/** * DPPDRA_Epsilon.java * * This is main implementation of ED/DPP-DRA. * * Author: * Ke Li <k.li@exeter.ac.uk> * * Affliation: * Department of Computer Science, University of Exeter * * Reference: * K. Li, S. Kwong, K. Deb, * ¡°A Dual Population Paradigm for Evolutionary Multiobjective Optimization¡±, * Information Sciences (INS). 309: 50¨C72, 2015. * * Homepage: * https://coda-group.github.io/ * * Copyright (c) 2017 Ke Li * * Note: This is a free software developed based on the open source project * jMetal<http://jmetal.sourceforge.net>. The copy right of jMetal belongs to * its original authors, Antonio J. Nebro and Juan J. Durillo. Nevertheless, * this current version can be redistributed and/or modified under the terms of * the GNU Lesser 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package jmetal.metaheuristics.moead; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.StringTokenizer; import java.util.Vector; import jmetal.core.Algorithm; import jmetal.core.Operator; import jmetal.core.Problem; import jmetal.core.Solution; import jmetal.core.SolutionSet; import jmetal.util.Distance; import jmetal.util.JMException; import jmetal.util.PseudoRandom; public class DPPDRA_Epsilon extends Algorithm { int gen = 0; private int populationSize_; private SolutionSet population_; // Pareto-based archive private SolutionSet archive_pop; // decomposition-based archive private SolutionSet mixed_pop; // mixed population private SolutionSet final_pop; // final output population private Solution[] savedValues_; // Stores the values of the individuals private double[] utility_; double[] zp_; // ideal point for Pareto-based population double[] zd_; // ideal point for decomposition-based archive double[] nzp_; // nadir point for Pareto-based population double[] nzd_; // nadir point for decomposition-based population double[][] lambda_; // Lambda vectors int T_; // neighborhood size int evaluations_; // counter of evaluation times double delta_; // probability that parent solutions are selected from neighborhood int[][] neighborhood_; // neighborhood structure String functionType_; Operator crossover_; Operator mutation_; String dataDirectory_; double[] epsilon_; int[][] subregionMatrix_; // subregion occupation record /***********************************************************************************/ /** * Constructor * * @param problem * Problem to solve */ public DPPDRA_Epsilon(Problem problem) { super(problem); // functionType_ = "_TCHE1"; functionType_ = "_TCHE2"; // functionType_ = "PBI"; } // DMOEA public SolutionSet execute() throws JMException, ClassNotFoundException { int maxEvaluations; evaluations_ = 0; dataDirectory_ = this.getInputParameter("dataDirectory").toString(); maxEvaluations = ((Integer) this.getInputParameter("maxEvaluations")).intValue(); populationSize_ = ((Integer) this.getInputParameter("populationSize")).intValue(); population_ = new SolutionSet(populationSize_); savedValues_ = new Solution[populationSize_]; utility_ = new double[populationSize_]; for (int i = 0; i < utility_.length; i++) utility_[i] = 1.0; T_ = 20; delta_ = 0.9; neighborhood_ = new int[populationSize_][T_]; zp_ = new double[problem_.getNumberOfObjectives()]; // ideal point for Pareto-based population zd_ = new double[problem_.getNumberOfObjectives()]; // ideal point for decomposition-based population nzp_ = new double[problem_.getNumberOfObjectives()]; // nadir point for Pareto-based population nzd_ = new double[problem_.getNumberOfObjectives()]; // nadir point for decomposition-based archive lambda_ = new double[populationSize_][problem_.getNumberOfObjectives()]; crossover_ = operators_.get("crossover"); mutation_ = operators_.get("mutation"); archive_pop = new SolutionSet(populationSize_); epsilon_ = new double[problem_.getNumberOfObjectives()]; for (int i = 0; i < problem_.getNumberOfObjectives(); i++) epsilon_[i] = 1 / 600; // UF1-UF7(1/600), UF8-UF10(1/60), MOP1-MOP5(1/13), MOP6-MOP7(1/23) // populationSize:105(1/13),210(1/19),300(1/23),406(1/27),595(1/33),820(1/40) subregionMatrix_ = new int[populationSize_][populationSize_]; for (int i = 0; i < populationSize_; i++) subregionMatrix_[i][i] = 1; // STEP 1. Initialization initUniformWeight(); initNeighborhood(); initPopulation(); initIdealPoint(); initNadirPoint(); // STEP 2. Update do { int[] permutation = new int[populationSize_]; Utils.randomPermutation(permutation, populationSize_); List<Integer> order = tour_selection(10); for (int i = 0; i < order.size(); i++) { int n = order.get(i); int type; double rnd = PseudoRandom.randDouble(); // STEP 2.1. Mating selection based on probability if (rnd < delta_) // if (rnd < realb) type = 1; // neighborhood else type = 2; // whole population Solution child; Solution[] parents = new Solution[3]; Vector<Integer> p = new Vector<Integer>(); parents = matingSelection(p, n, 2, type); // STEP 2.2. Reproduction // Apply DE crossover child = (Solution) crossover_.execute(new Object[] {population_.get(n), parents }); // Apply mutation mutation_.execute(child); // Evaluation problem_.evaluate(child); evaluations_++; // STEP 2.4. Update ideal and nadir points updateReference(child, zp_); updateReference(child, zd_); updateNadirPoint(child, nzp_); updateNadirPoint(child, nzd_); // STEP 2.5. Update of solutions updateProblem(child); updateArchive(child); } // for gen++; if (gen % 50 == 0) { comp_utility(); } } while (evaluations_ < maxEvaluations); final_pop = filtering(populationSize_); return final_pop; } public List<Integer> tour_selection(int depth) { // selection based on utility List<Integer> selected = new ArrayList<Integer>(); List<Integer> candidate = new ArrayList<Integer>(); for (int k = 0; k < problem_.getNumberOfObjectives(); k++) selected.add(k); // WARNING! HERE YOU HAVE TO USE THE WEIGHT PROVIDED BY QINGFU (NOT SORTED!!!!) for (int n = problem_.getNumberOfObjectives(); n < populationSize_; n++) candidate.add(n); // set of unselected weights while (selected.size() < (int) (populationSize_ / 5.0)) { int best_idd = (int) (PseudoRandom.randDouble() * candidate.size()); int i2; int best_sub = candidate.get(best_idd); int s2; for (int i = 1; i < depth; i++) { i2 = (int) (PseudoRandom.randDouble() * candidate.size()); s2 = candidate.get(i2); if (utility_[s2] > utility_[best_sub]) { best_idd = i2; best_sub = s2; } } selected.add(best_sub); candidate.remove(best_idd); } return selected; } /** * Initialize the weight vectors for subproblems (We only use the data that are already available) */ public void initUniformWeight() { String dataFileName; dataFileName = "W" + problem_.getNumberOfObjectives() + "D_" + populationSize_ + ".dat"; try { // Open the file FileInputStream fis = new FileInputStream(dataDirectory_ + "/" + dataFileName); InputStreamReader isr = new InputStreamReader(fis); BufferedReader br = new BufferedReader(isr); int i = 0; int j = 0; String aux = br.readLine(); while (aux != null) { StringTokenizer st = new StringTokenizer(aux); j = 0; while (st.hasMoreTokens()) { double value = (new Double(st.nextToken())).doubleValue(); lambda_[i][j] = value; j++; } aux = br.readLine(); i++; } br.close(); } catch (Exception e) { System.out .println("initUniformWeight: failed when reading for file: " + dataDirectory_ + "/" + dataFileName); e.printStackTrace(); } } // initUniformWeight /** * update the utility of each subproblem */ public void comp_utility() { double f1, f2, uti, delta; for (int i = 0; i < populationSize_; i++) { f1 = fitnessFunction(population_.get(i), lambda_[i]); f2 = fitnessFunction(savedValues_[i], lambda_[i]); delta = f2 - f1; if (delta > 0.001) utility_[i] = 1.0; else { uti = 0.95 * (1.0 + delta / 0.001) * utility_[i]; utility_[i] = uti < 1.0 ? uti : 1.0; } savedValues_[i] = new Solution(population_.get(i)); } } /** * Initialize the neighborhood structure */ public void initNeighborhood() { double[] x = new double[populationSize_]; int[] idx = new int[populationSize_]; for (int i = 0; i < populationSize_; i++) { // calculate the distances based on weight vectors for (int j = 0; j < populationSize_; j++) { x[j] = Utils.distVector(lambda_[i], lambda_[j]); idx[j] = j; } // for // find 'niche' nearest neighboring subproblems Utils.minFastSort(x, idx, populationSize_, T_); for (int k = 0; k < T_; k++) { neighborhood_[i][k] = idx[k]; } } // for } // initNeighborhood /** * Initialize the population * * @throws JMException * @throws ClassNotFoundException */ public void initPopulation() throws JMException, ClassNotFoundException { for (int i = 0; i < populationSize_; i++) { Solution newSolution = new Solution(problem_); problem_.evaluate(newSolution); evaluations_++; population_.add(newSolution); newSolution.setRegion(i); archive_pop.add(newSolution); addIndiv(newSolution, i); savedValues_[i] = new Solution(newSolution); } } // initPopulation /** * Initialize the ideal objective vector * @throws JMException * @throws ClassNotFoundException */ void initIdealPoint() throws JMException, ClassNotFoundException { for (int i = 0; i < problem_.getNumberOfObjectives(); i++) zp_[i] = 1.0e+30; for (int i = 0; i < populationSize_; i++) updateReference(population_.get(i), zp_); zd_ = zp_; } // initIdealPoint /** * Initialize the nadir point * * @throws JMException * @throws ClassNotFoundException */ void initNadirPoint() throws JMException, ClassNotFoundException { for (int i = 0; i < problem_.getNumberOfObjectives(); i++) nzp_[i] = -1.0e+30; for (int i = 0; i < populationSize_; i++) updateNadirPoint(population_.get(i), nzp_); nzd_ = nzp_; } // initNadirPoint /** * Restricted mating selection: select mating parents * * @param list: the set of the indexes of selected mating parents * @param cid : the id of current subproblem * @param size: the number of selected mating parents * @param type: 1 - neighborhood; otherwise - whole population */ public Solution[] matingSelection(Vector<Integer> list, int cid, int size, int type) { int ss, r, p; Solution[] parents = new Solution[3]; ss = neighborhood_[cid].length; while (list.size() < size) { if (type == 1) { r = PseudoRandom.randInt(0, ss - 1); p = neighborhood_[cid][r]; } else { p = PseudoRandom.randInt(0, populationSize_ - 1); } boolean flag = true; for (int i = 0; i < list.size(); i++) { if (list.get(i) == p) // p is in the list { flag = false; break; } } if (flag) { list.addElement(p); } } parents[0] = population_.get(list.get(0)); parents[1] = population_.get(list.get(1)); parents[2] = population_.get(cid); int idx = countSols(list.get(0)); if (idx != -1) parents[0] = archive_pop.get(idx); return parents; } // matingSelection /** * Update the ideal objective vector * @param indiv */ void updateReference(Solution indiv, double[] z_) { for (int i = 0; i < problem_.getNumberOfObjectives(); i++) { if (indiv.getObjective(i) < z_[i]) { z_[i] = indiv.getObjective(i); } } } // updateReference /** * Update the nadir point * * @param individual */ void updateNadirPoint(Solution individual, double[] nz_) { for (int i = 0; i < problem_.getNumberOfObjectives(); i++) { if (individual.getObjective(i) > nz_[i]) nz_[i] = individual.getObjective(i); } } // updateNadirPoint /** * update the Pareto-based archive * * @param indiv */ public void updateArchive(Solution indiv) { Solution temp = null; setLocation(indiv, zp_, nzp_); int end = 0; for (int i = 0; i < archive_pop.size() && end != 1; i++) { Solution Parent = archive_pop.get(i); if (Parent == null) continue; switch (checkBoxDominance(indiv, Parent)) { case 1: { // Child dominates Parent archive_pop.replace(i, temp); deleteIndiv(Parent, i); break; } case 2: { // Parent dominates Child return; } case 3: { // both are non-dominated and are in different boxes break; } case 4: { // both are non-dominated and are in same hyper-box end = 1; switch (checkDominance(indiv, Parent)) { case 1: { archive_pop.replace(i, indiv); deleteIndiv(Parent, i); addIndiv(indiv, i); break; } case -1: { return; } case 0: { double d1 = 0.0; double d2 = 0.0; for (int j = 0; j < problem_.getNumberOfObjectives(); j++) { d1 += Math .pow((indiv.getObjective(j) - (int) Math .floor((indiv.getObjective(j) - zp_[j]) / epsilon_[j])) / epsilon_[j], 2.0); d2 += Math .pow((Parent.getObjective(j) - (int) Math .floor((Parent.getObjective(j) - zp_[j]) / epsilon_[j])) / epsilon_[j], 2.0); } if (d1 <= d2) { archive_pop.replace(i, indiv); deleteIndiv(Parent, i); addIndiv(indiv, i); } break; } } break; } } } if (end == 0) { Vector<Integer> emptyList = new Vector<Integer>(); int archiveSize = 0; for (int i = 0; i < populationSize_; i++) { if (archive_pop.get(i) != null) archiveSize++; else emptyList.addElement(i); } if (archiveSize < populationSize_) { int idx = emptyList.get(PseudoRandom.randInt(0, emptyList.size() - 1)); archive_pop.replace(emptyList.get(idx), indiv); addIndiv(indiv, emptyList.get(idx)); } else { int tempIdx = jmetal.util.PseudoRandom.randInt(0, archiveSize - 1); archive_pop.replace(tempIdx, indiv); deleteIndiv(archive_pop.get(tempIdx), tempIdx); addIndiv(indiv, tempIdx); } } } /** * update the decomposition-based archive * * @param indiv * */ void updateProblem(Solution indiv) { double cur_func, prev_func; setLocation(indiv, zd_, nzd_); int location = indiv.readRegion(); Solution prevSol = population_.get(location); cur_func = fitnessFunction(indiv, lambda_[location]); prev_func = fitnessFunction(prevSol, lambda_[location]); if (cur_func < prev_func) population_.replace(location, indiv); } // updateProblem /** * evaluate the fitness value based on the aggregation function * * @param indiv * @param lambda * @return */ double fitnessFunction(Solution indiv, double[] lambda) { double fitness; fitness = 0.0; if (functionType_.equals("_TCHE1")) { double maxFun = -1.0e+30; for (int i = 0; i < problem_.getNumberOfObjectives(); i++) { double diff = Math.abs(indiv.getObjective(i) - zd_[i]); double feval; if (lambda[i] == 0) { feval = 0.0001 * diff; } else { feval = diff * lambda[i]; } if (feval > maxFun) { maxFun = feval; } } // for fitness = maxFun; } else if (functionType_.equals("_TCHE2")) { double maxFun = -1.0e+30; for (int i = 0; i < problem_.getNumberOfObjectives(); i++) { double diff = Math.abs(indiv.getObjective(i) - zd_[i]); double feval; if (lambda[i] == 0) { feval = diff / 0.000001; } else { feval = diff / lambda[i]; } if (feval > maxFun) { maxFun = feval; } } // for fitness = maxFun; } else if(functionType_.equals("_OO")) { for (int i = 0; i < problem_.getNumberOfObjectives(); i++) { fitness += indiv.getObjective(i); } } else if (functionType_.equals("_PBI")) { double theta; // penalty parameter theta = 5.0; // normalize the weight vector (line segment) double nd = norm_vector(lambda); for (int i = 0; i < problem_.getNumberOfObjectives(); i++) lambda[i] = lambda[i] / nd; double[] realA = new double[problem_.getNumberOfObjectives()]; double[] realB = new double[problem_.getNumberOfObjectives()]; // difference between current point and reference point for (int n = 0; n < problem_.getNumberOfObjectives(); n++) realA[n] = (indiv.getObjective(n) - zd_[n]); // distance along the line segment double d1 = Math.abs(innerproduct(realA, lambda)); // distance to the line segment for (int n = 0; n < problem_.getNumberOfObjectives(); n++) realB[n] = (indiv.getObjective(n) - (zd_[n] + d1 * lambda[n])); double d2 = norm_vector(realB); // fitness = d2; fitness = d1 + theta * d2; }else { System.out.println("MOEAD.fitnessFunction: unknown type " + functionType_); System.exit(-1); } return fitness; } // fitnessEvaluation /** * Find a solution from the specific subregion in the Pareto-based archive * * @param idx * @return */ public int countSols(int idx) { Vector<Integer> list = new Vector<Integer>(); for (int i = 0; i < populationSize_; i++) { if (subregionMatrix_[idx][i] == 1) list.addElement(i); } if (list.size() == 0) return -1; else return list.get(PseudoRandom.randInt(0, list.size() - 1)); } /** * delete 'indiv' from the subregion record * * @param indiv * @param idx */ public void deleteIndiv(Solution indiv, int idx) { int location = indiv.readRegion(); subregionMatrix_[location][idx] = 0; } public void addIndiv(Solution indiv, int idx) { int location = indiv.readRegion(); subregionMatrix_[location][idx] = 1; } /** * Set the location of a solution based on the orthogonal distance * * @param indiv */ public void setLocation(Solution indiv, double[] z_, double[] nz_) { int minIdx; double distance, minDist; minIdx = 0; distance = calculateDistance2(indiv, lambda_[0], z_, nz_); minDist = distance; for (int i = 1; i < populationSize_; i++) { distance = calculateDistance2(indiv, lambda_[i], z_, nz_); if (distance < minDist) { minIdx = i; minDist = distance; } } indiv.setRegion(minIdx); indiv.Set_associateDist(minDist); } /** * Calculate the perpendicular distance between the solution and reference line * * @param individual * @param lambda * @return */ public double calculateDistance(Solution individual, double[] lambda) { double scale; double distance; double[] vecInd = new double[problem_.getNumberOfObjectives()]; double[] vecProj = new double[problem_.getNumberOfObjectives()]; // vecInd has been normalized to the range [0,1] for (int i = 0; i < problem_.getNumberOfObjectives(); i++) vecInd[i] = (individual.getObjective(i) - zd_[i]) / (nzd_[i] - zd_[i]); scale = innerproduct(vecInd, lambda) / innerproduct(lambda, lambda); for (int i = 0; i < problem_.getNumberOfObjectives(); i++) vecProj[i] = vecInd[i] - scale * lambda[i]; distance = norm_vector(vecProj); return distance; } public double calculateDistance2(Solution indiv, double[] lambda, double[] z_, double[] nz_) { // normalize the weight vector (line segment) double nd = norm_vector(lambda); for (int i = 0; i < problem_.getNumberOfObjectives(); i++) lambda[i] = lambda[i] / nd; double[] realA = new double[problem_.getNumberOfObjectives()]; double[] realB = new double[problem_.getNumberOfObjectives()]; // difference between current point and reference point for (int i = 0; i < problem_.getNumberOfObjectives(); i++) realA[i] = (indiv.getObjective(i) - z_[i]); // distance along the line segment double d1 = Math.abs(innerproduct(realA, lambda)); // distance to the line segment for (int i = 0; i < problem_.getNumberOfObjectives(); i++) realB[i] = (indiv.getObjective(i) - (z_[i] + d1 * lambda[i])); double distance = norm_vector(realB); return distance; } /** * Calculate the dot product of two vectors * * @param vec1 * @param vec2 * @return */ public double innerproduct(double[] vec1, double[] vec2) { double sum = 0; for (int i = 0; i < vec1.length; i++) sum += vec1[i] * vec2[i]; return sum; } /** * Calculate the norm of the vector * @param z * @return */ public double norm_vector(double[] z) { double sum = 0; for (int i = 0; i < problem_.getNumberOfObjectives(); i++) sum += z[i] * z[i]; return Math.sqrt(sum); } /** * Check the Pareto dominance relation between 'a' and 'b' * * @param a * @param b * @return */ public int checkDominance(Solution a, Solution b) { int flag1, flag2; flag1 = flag2 = 0; for (int i = 0; i < problem_.getNumberOfObjectives(); i++) { if (a.getObjective(i) < b.getObjective(i)) { flag1 = 1; } else { if (a.getObjective(i) > b.getObjective(i)) { flag2 = 1; } } } if (flag1 == 1 && flag2 == 0) { return 1; } else { if (flag1 == 0 && flag2 == 1) { return -1; } else { return 0; } } } /** * Check the epsilon-dominance relation between 'a' and 'b' * * @param a * @param b * @return */ public int checkBoxDominance(Solution a, Solution b) { int flag1, flag2; flag1 = flag2 = 0; for (int i = 0; i < problem_.getNumberOfObjectives(); i++) { if ((int) Math.floor((a.getObjective(i) - zp_[i]) / epsilon_[i]) < (int) Math .floor((b.getObjective(i) - zp_[i]) / epsilon_[i])) { flag1 = 1; } else { if ((int) Math.floor((a.getObjective(i) - zp_[i]) / epsilon_[i]) > (int) Math .floor((b.getObjective(i) - zp_[i]) / epsilon_[i])) { flag2 = 1; } } } if (flag1 == 1 && flag2 == 0) { return 1; } else { if (flag1 == 0 && flag2 == 1) { return 2; } else { if (flag1 == 1 && flag2 == 1) { return 3; } else { return 4; } } } } public SolutionSet filtering(int final_size) { Vector<Integer> list = new Vector<Integer>(); int archiveSize = 0; for (int i = 0; i < populationSize_; i++) { if (archive_pop.get(i) != null) { archiveSize++; list.addElement(i); } } int popsize = populationSize_ + archiveSize; mixed_pop = new SolutionSet(popsize); for (int i = 0; i < populationSize_; i++) { mixed_pop.add(population_.get(i)); } for (int i = 0; i < archiveSize; i++) { mixed_pop.add(archive_pop.get(list.get(i))); } return mixed_pop; } } // DPPDRA_Epsilon
gpl-3.0
tompecina/retro
pmi80/temp/ServoDisc.java
1601
/* ServoDisc.java * * Copyright (C) 2015, Tomáš Pecina <tomas@pecina.cz> * * This file is part of cz.pecina.retro, retro 8-bit computer emulators. * * This application 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 application 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 cz.pecina.retro.pmi80; import javax.swing.JLabel; import javax.swing.ImageIcon; public class ServoDisc extends JLabel { private static final ImageIcon[] icons = new ImageIcon[Constants.NUMBER_SERVO_STATES]; private static boolean iconsLoaded = false; private int state = 0; public ServoDisc() { if (!iconsLoaded) { for (int i = 0; i < Constants.NUMBER_SERVO_STATES; i++) { icons[i] = IconCache.get("servo/servo-" + Constants.servoDiscWidth + "x" + Constants.servoDiscHeight + "-" + i + ".png"); } iconsLoaded = true; } setIcon(icons[0]); repaint(); } public void setState(int state) { this.state = state; setIcon(icons[state]); repaint(); } public int getState() { return state; } }
gpl-3.0
AlecWazzy/Miscellaneous
Data Structures and XML Parsing/src/domain/DLLNode.java
283
package domain; /** * DLL NODE CLASS * Created by 645111 on 11/26/2015. */ public class DLLNode<T> { protected T element; protected DLLNode next; protected DLLNode prev; protected DLLNode(T element) { this.element = element; } }
gpl-3.0
Duke2k/jatf
jatf-core/src/main/java/jatf/annotations/MustOverride.java
848
/** * This file is part of JATF. * <p> * JATF 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 3 of the License. * <p> * JATF is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * <p> * You should have received a copy of the GNU General Public License * along with JATF. If not, see <http://www.gnu.org/licenses/>. */ package jatf.annotations; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Retention(RetentionPolicy.RUNTIME) public @interface MustOverride { String[] methodNames() default {}; }
gpl-3.0
nickalaskreynolds/Momobutt
src/io/ph/bot/commands/fun/EightBall.java
1798
package io.ph.bot.commands.fun; import java.awt.Color; import java.util.Random; import io.ph.bot.commands.Command; import io.ph.bot.commands.CommandCategory; import io.ph.bot.commands.CommandData; import io.ph.bot.model.Permission; import io.ph.util.MessageUtils; import io.ph.util.Util; import net.dv8tion.jda.core.EmbedBuilder; import net.dv8tion.jda.core.entities.Message; /** * Magic eight ball for a response * @author Nick */ @CommandData ( defaultSyntax = "eightball", aliases = {"magicball"}, category = CommandCategory.FUN, permission = Permission.NONE, description = "Ask the magic eight ball a question", example = "Is this thing rigged?" ) public class EightBall extends Command { String[] responses = new String[] { "It is certain", "It is decidedly so", "Without a doubt", "Yes, definitely", "You may rely on it", "As I see it, yes", "Most likely", "Outlook good", "Yes", "Signs point to yes", "Reply hazy, try again", "Ask again later", "Better not tell you now", "Cannot predict now", "Concentrate and ask again", "Don't count on it", "My reply is no", "My sources say no", "Outlook not so good", "Very doubtful" }; @Override public void executeCommand(Message msg) { String content = Util.getCommandContents(msg); if(content.equals("")) { MessageUtils.sendIncorrectCommandUsage(msg, this); return; } EmbedBuilder em = new EmbedBuilder(); int r = new Random().nextInt(responses.length); em.setTitle(content, null) .setDescription(responses[r]); Color c; if(r < 10) c = Color.GREEN; else if(r >= 10 && r <= 14) c = Color.CYAN; else c = Color.RED; em.setColor(c); msg.getChannel().sendMessage(em.build()).queue(); } }
gpl-3.0
robward-scisys/sldeditor
modules/application/src/test/java/com/sldeditor/test/unit/ui/detail/config/FieldConfigVendorOptionTest.java
11361
/* * SLD Editor - The Open Source Java SLD Editor * * Copyright (C) 2016, SCISYS UK Limited * * 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.sldeditor.test.unit.ui.detail.config; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import com.sldeditor.common.vendoroption.GeoServerVendorOption; import com.sldeditor.common.vendoroption.VersionData; import com.sldeditor.common.xml.ui.FieldIdEnum; import com.sldeditor.ui.detail.RasterSymbolizerDetails; import com.sldeditor.ui.detail.config.FieldConfigBase; import com.sldeditor.ui.detail.config.FieldConfigCommonData; import com.sldeditor.ui.detail.config.FieldConfigPopulate; import com.sldeditor.ui.detail.config.FieldConfigString; import com.sldeditor.ui.detail.config.FieldConfigVendorOption; import com.sldeditor.ui.detail.vendor.geoserver.VendorOptionInterface; import com.sldeditor.ui.detail.vendor.geoserver.raster.VendorOptionRasterFactory; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.Test; import org.opengis.filter.expression.Expression; /** * The unit test for FieldConfigVendorOption. * * <p>{@link com.sldeditor.ui.detail.config.FieldConfigVendorOption} * * @author Robert Ward (SCISYS) */ public class FieldConfigVendorOptionTest { /** * Test method for {@link * com.sldeditor.ui.detail.config.FieldConfigVendorOption#internalSetEnabled(boolean)}. Test * method for {@link com.sldeditor.ui.detail.config.FieldConfigVendorOption#isEnabled()}. Test * method for {@link com.sldeditor.ui.detail.config.FieldConfigVendorOption#createUI()}. */ @Test public void testSetEnabled() { // Value only, no attribute/expression dropdown List<VendorOptionInterface> veList = null; boolean valueOnly = true; FieldConfigVendorOption field = new FieldConfigVendorOption( new FieldConfigCommonData( Double.class, FieldIdEnum.NAME, "label", valueOnly, false), veList); // Text field will not have been created boolean expectedValue = true; field.internalSetEnabled(expectedValue); assertTrue(field.isEnabled()); // Create text field field.createUI(); assertEquals(expectedValue, field.isEnabled()); expectedValue = false; field.internalSetEnabled(expectedValue); assertTrue(field.isEnabled()); // Has attribute/expression dropdown valueOnly = false; FieldConfigVendorOption field2 = new FieldConfigVendorOption( new FieldConfigCommonData( Double.class, FieldIdEnum.NAME, "label", valueOnly, false), veList); // Text field will not have been created expectedValue = true; field2.internalSetEnabled(expectedValue); assertTrue(field2.isEnabled()); // Create text field field2.createUI(); assertEquals(expectedValue, field2.isEnabled()); expectedValue = false; field2.internalSetEnabled(expectedValue); assertTrue(field2.isEnabled()); } /** * Test method for {@link * com.sldeditor.ui.detail.config.FieldConfigVendorOption#setVisible(boolean)}. */ @Test public void testSetVisible() { List<VendorOptionInterface> veList = null; boolean valueOnly = true; FieldConfigVendorOption field = new FieldConfigVendorOption( new FieldConfigCommonData( Double.class, FieldIdEnum.NAME, "label", valueOnly, false), veList); boolean expectedValue = true; field.setVisible(expectedValue); field.createUI(); field.setVisible(expectedValue); expectedValue = false; field.setVisible(expectedValue); } /** * Test method for {@link * com.sldeditor.ui.detail.config.FieldConfigVendorOption#generateExpression()}. Test method for * {@link com.sldeditor.ui.detail.config.FieldConfigVendorOption#getStringValue()}. Test method * for {@link * com.sldeditor.ui.detail.config.FieldConfigVendorOption#populateExpression(java.lang.Object)}. */ @Test public void testGenerateExpression() { boolean valueOnly = true; List<VendorOptionInterface> veList = null; class TestFieldConfigVendorOption extends FieldConfigVendorOption { public TestFieldConfigVendorOption( FieldConfigCommonData commonData, List<VendorOptionInterface> veList) { super(commonData, veList); } /* (non-Javadoc) * @see com.sldeditor.ui.detail.config.FieldConfigVendorOption#generateExpression() */ @Override protected Expression generateExpression() { return super.generateExpression(); } } TestFieldConfigVendorOption field = new TestFieldConfigVendorOption( new FieldConfigCommonData( Double.class, FieldIdEnum.NAME, "label", valueOnly, false), veList); assertNull(field.getStringValue()); field.populateExpression(null); assertNull(field.generateExpression()); } /** * Test method for {@link * com.sldeditor.ui.detail.config.FieldConfigVendorOption#revertToDefaultValue()}. */ @Test public void testRevertToDefaultValue() { List<VendorOptionInterface> veList = null; boolean valueOnly = true; FieldConfigVendorOption field = new FieldConfigVendorOption( new FieldConfigCommonData( Double.class, FieldIdEnum.NAME, "label", valueOnly, false), veList); field.revertToDefaultValue(); field.createUI(); field.revertToDefaultValue(); } /** * Test method for {@link * com.sldeditor.ui.detail.config.FieldConfigVendorOption#createCopy(com.sldeditor.ui.detail.config.FieldConfigBase)}. */ @Test public void testCreateCopy() { boolean valueOnly = true; class TestFieldConfigVendorOption extends FieldConfigVendorOption { public TestFieldConfigVendorOption( FieldConfigCommonData commonData, List<VendorOptionInterface> veList) { super(commonData, veList); } public FieldConfigPopulate callCreateCopy(FieldConfigBase fieldConfigBase) { return createCopy(fieldConfigBase); } } TestFieldConfigVendorOption field = new TestFieldConfigVendorOption( new FieldConfigCommonData( Double.class, FieldIdEnum.NAME, "label", valueOnly, false), null); FieldConfigVendorOption copy = (FieldConfigVendorOption) field.callCreateCopy(null); assertNull(copy); copy = (FieldConfigVendorOption) field.callCreateCopy(field); assertEquals(field.getFieldId(), copy.getFieldId()); assertTrue(field.getLabel().compareTo(copy.getLabel()) == 0); assertEquals(field.isValueOnly(), copy.isValueOnly()); // Try and copy something that isn't a FieldConfigVendorOption assertNull( field.callCreateCopy( new FieldConfigString( new FieldConfigCommonData( String.class, FieldIdEnum.NAME, "test label", valueOnly, false), "button text"))); } /** * Test method for {@link * com.sldeditor.ui.detail.config.FieldConfigVendorOption#addToOptionBox(javax.swing.Box)}. */ @Test public void testAddToOptionBox() { FieldConfigVendorOption field = new FieldConfigVendorOption( new FieldConfigCommonData( Double.class, FieldIdEnum.NAME, "label", false, false), null); field.addToOptionBox(null); } /** * Test method for {@link * com.sldeditor.ui.detail.config.FieldConfigVendorOption#vendorOptionsUpdated(java.util.List)}. */ @Test public void testVendorOptionsUpdated() { RasterSymbolizerDetails panel = new RasterSymbolizerDetails(); VendorOptionRasterFactory vendorOptionRasterFactory = new VendorOptionRasterFactory(getClass(), panel); // CHECKSTYLE:OFF List<VendorOptionInterface> veList = vendorOptionRasterFactory.getVendorOptionList( "com.sldeditor.ui.detail.vendor.geoserver.raster.VOGeoServerContrastEnhancementNormalizeOverall"); // CHECKSTYLE:ON for (VendorOptionInterface extension : veList) { extension.setParentPanel(panel); } FieldConfigVendorOption field = new FieldConfigVendorOption( new FieldConfigCommonData( Double.class, FieldIdEnum.NAME, "label", false, false), veList); field.vendorOptionsUpdated(null); field.createUI(); List<VersionData> vendorOptionVersionsList = new ArrayList<VersionData>(); vendorOptionVersionsList.add(VersionData.getLatestVersion(GeoServerVendorOption.class)); field.vendorOptionsUpdated(vendorOptionVersionsList); } /** * Test method for {@link * com.sldeditor.ui.detail.config.FieldConfigVendorOption#attributeSelection(java.lang.String)}. */ @Test public void testAttributeSelection() { boolean valueOnly = true; FieldConfigVendorOption field = new FieldConfigVendorOption( new FieldConfigCommonData( Double.class, FieldIdEnum.NAME, "label", valueOnly, false), null); field.attributeSelection(null); field.createUI(); field.createUI(); assertTrue(field.isEnabled()); field.attributeSelection("test"); assertTrue(field.isEnabled()); field.attributeSelection(null); assertTrue(field.isEnabled()); } }
gpl-3.0
JumpMind/sqlexplorer-vaadin
src/main/java/org/jumpmind/vaadin/ui/sqlexplorer/DbTreeNode.java
5597
/** * Licensed to JumpMind Inc under one or more contributor * license agreements. See the NOTICE file distributed * with this work for additional information regarding * copyright ownership. JumpMind Inc licenses this file * to you under the GNU General Public License, version 3.0 (GPLv3) * (the "License"); you may not use this file except in compliance * with the License. * * You should have received a copy of the GNU General Public License, * version 3.0 (GPLv3) along with this library; if not, see * <http://www.gnu.org/licenses/>. * * 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.jumpmind.vaadin.ui.sqlexplorer; import java.io.Serializable; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.jumpmind.db.model.Table; import org.jumpmind.db.platform.IDatabasePlatform; import org.jumpmind.properties.TypedProperties; import com.vaadin.server.Resource; public class DbTreeNode implements Serializable { private static final long serialVersionUID = 1L; protected String name; protected String description; protected String type; protected Resource icon; protected TypedProperties properties = new TypedProperties(); protected DbTreeNode parent; protected List<DbTreeNode> children = new ArrayList<DbTreeNode>(); protected DbTree dbTree; public DbTreeNode(DbTree dbTree, String name, String type, Resource icon, DbTreeNode parent) { this.name = name; this.type = type; this.parent = parent; this.icon = icon; this.dbTree = dbTree; } public DbTreeNode() { } public void setParent(DbTreeNode parent) { this.parent = parent; } public DbTreeNode getParent() { return parent; } public void setName(String name) { this.name = name; } public String getName() { return name; } public String getType() { return type; } public void setType(String type) { this.type = type; } @Override public String toString() { return name; } public boolean hasChildren() { return children.size() > 0; } public List<DbTreeNode> getChildren() { return children; } public void setChildren(List<DbTreeNode> children) { this.children = children; } public DbTreeNode find(DbTreeNode node) { if (this.equals(node)) { return this; } else if (children != null && children.size() > 0) { Iterator<DbTreeNode> it = children.iterator(); while (it.hasNext()) { DbTreeNode child = (DbTreeNode) it.next(); if (child.equals(node)) { return child; } } for (DbTreeNode child : children) { DbTreeNode target = child.find(node); if (target != null) { return target; } } } return null; } protected Table getTableFor() { IDb db = dbTree.getDbForNode(this); IDatabasePlatform platform = db.getPlatform(); TypedProperties nodeProperties = getProperties(); return platform.getTableFromCache( nodeProperties.get(DbTree.PROPERTY_CATALOG_NAME), nodeProperties.get(DbTree.PROPERTY_SCHEMA_NAME), name, false); } public boolean delete(DbTreeNode node) { if (children != null && children.size() > 0) { Iterator<DbTreeNode> it = children.iterator(); while (it.hasNext()) { DbTreeNode child = (DbTreeNode) it.next(); if (child.equals(node)) { it.remove(); return true; } } for (DbTreeNode child : children) { if (child.delete(node)) { return true; } } } return false; } public void setDescription(String description) { this.description = description; } public String getDescription() { return description; } public void setIcon(Resource icon) { this.icon = icon; } public Resource getIcon() { return icon; } public List<String> findTreeNodeNamesOfType(String type) { List<String> names = new ArrayList<String>(); if (this.getType().equals(type)) { names.add(getName()); } findTreeNodeNamesOfType(type, getChildren(), names); return names; } public void findTreeNodeNamesOfType(String type, List<DbTreeNode> treeNodes, List<String> names) { for (DbTreeNode treeNode : treeNodes) { if (treeNode.getType().equals(type)) { names.add(treeNode.getName()); } findTreeNodeNamesOfType(type, treeNode.getChildren(), names); } } public void setProperties(TypedProperties properties) { this.properties = properties; } public TypedProperties getProperties() { return properties; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((type == null) ? 0 : type.hashCode()); result = prime * result + ((parent == null) ? 0 : parent.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; DbTreeNode other = (DbTreeNode) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (type == null) { if (other.type != null) return false; } else if (!type.equals(other.type)) return false; if (parent == null) { if (other.parent != null) { return false; } } else if (!parent.equals(other.parent)) { return false; } return true; } }
gpl-3.0
Shuanghua/LikeGank
app/src/main/java/com/shua/likegank/ui/itembinder/HomeItemBinder.java
4244
package com.shua.likegank.ui.itembinder; import android.graphics.Color; import android.text.Spannable; import android.text.SpannableString; import android.text.style.ForegroundColorSpan; import android.view.LayoutInflater; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.navigation.Navigation; import androidx.recyclerview.widget.RecyclerView; import com.shua.likegank.R; import com.shua.likegank.data.entity.Home; import com.shua.likegank.databinding.ItemHomeBinding; import com.shua.likegank.ui.HomeFragmentDirections; import com.shua.likegank.ui.WebActivity; import com.shua.likegank.utils.AppUtils; import me.drakeet.multitype.ItemViewBinder; /** * FuLiViewProvider * Created by SHUA on 2017/4/17. */ public class HomeItemBinder extends ItemViewBinder<Home, HomeItemBinder.HomeHolder> { @NonNull @Override protected HomeHolder onCreateViewHolder(@NonNull LayoutInflater inflater , @NonNull ViewGroup viewGroup) { return new HomeHolder(ItemHomeBinding.inflate(inflater, viewGroup, false)); } @Override protected void onBindViewHolder(@NonNull HomeHolder holder, @NonNull Home home) { switch (home.type) { case "Android": holder.mImageView.setImageResource(R.mipmap.ic_menu_android); break; case "iOS": holder.mImageView.setImageResource(R.mipmap.ic_menu_ios); break; case "瞎推荐": holder.mImageView.setImageResource(R.mipmap.ic_recommend); break; case "福利": holder.mImageView.setImageResource(R.mipmap.ic_menu_fuli); break; case "拓展资源": holder.mImageView.setImageResource(R.mipmap.ic_web); break; case "休息视频": holder.mImageView.setImageResource(R.mipmap.ic_video); break; default: holder.mImageView.setImageResource(R.mipmap.likegank_launcher_round); break; } holder.mTextTime.setText(AppUtils.gankSubTimeString(home.createdAt)); SpannableString span = new SpannableString(new StringBuilder() .append(home.title) .append("(via-") .append(home.who) .append(")")); span.setSpan(new ForegroundColorSpan(Color.parseColor("#eeb211")) , home.title.length() , span.length() , Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); holder.mTextTitle.setText(span); holder.url = home.url; holder.title = home.title; holder.type = home.type; // set TextColor or use SpannableStringBuilder.addend + StringStyles.format // SpannableStringBuilder builder = new SpannableStringBuilder(data.title) // .append(StringStyles.format( // holder.gank.getContext(), // " (by- " + // data.who + ")", // R.style.xxx)); } static class HomeHolder extends RecyclerView.ViewHolder { private final ImageView mImageView; private final TextView mTextTitle; private final TextView mTextTime; private String url; private String title; private String type; HomeHolder(ItemHomeBinding binding) { super(binding.getRoot()); this.mImageView = binding.homeImage; this.mTextTitle = binding.homeTitle; this.mTextTime = binding.homeTime; itemView.setOnClickListener(v -> { if ("Girl".equals(type)) { HomeFragmentDirections.ActionNavHomeToNavPhoto action = HomeFragmentDirections.actionNavHomeToNavPhoto(url); Navigation.findNavController(v).navigate(action); } else { itemView.getContext().startActivity(WebActivity .newIntent(itemView.getContext(), url, title)); } }); } } }
gpl-3.0
sanke69/fr.xs.jtk
src/main/java/fr/xs/jtk/graphics/fx3d/shapes/Capsule.java
2501
/* * Copyright (C) 2013-2015 F(X)yz, * Sean Phillips, Jason Pollastrini and Jose Pereda * All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package fr.xs.jtk.graphics.fx3d.shapes; import fr.xs.jtk.graphics.fx3d.shapes.containers.ShapeContainer; import fr.xs.jtk.graphics.fx3d.shapes.primitives.CapsuleMesh; import javafx.beans.property.DoubleProperty; import javafx.scene.paint.Color; import javafx.scene.paint.Material; import javafx.scene.shape.CullFace; import javafx.scene.shape.DrawMode; /** * * @author Dub */ public class Capsule extends ShapeContainer<CapsuleMesh>{ private CapsuleMesh mesh; public Capsule() { super(new CapsuleMesh()); this.mesh = getShape(); } public Capsule(double radius, double height){ this(); mesh.setRadius(radius); mesh.setHeight(height); } public Capsule(Color c){ this(); this.setDiffuseColor(c); } public Capsule(double radius, double height, Color c){ this(radius, height); this.setDiffuseColor(c); } public final void setRadius(double value) { mesh.setRadius(value); } public final void setHeight(double value) { mesh.setHeight(value); } public final void setMaterial(Material value) { mesh.setMaterial(value); } public final void setDrawMode(DrawMode value) { mesh.setDrawMode(value); } public final void setCullFace(CullFace value) { mesh.setCullFace(value); } public final double getRadius() { return mesh.getRadius(); } public DoubleProperty radiusProperty() { return mesh.radiusProperty(); } public final double getHeight() { return mesh.getHeight(); } public DoubleProperty heightProperty() { return mesh.heightProperty(); } }
gpl-3.0
Karlosjp/Clase-DAM
Luis Braille/2 DAM/Desarrollo de interfaces/1 Trimestre/PracticasInterfacesNB/src/practica2/gui/JFPrincipal.java
5990
/* * 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 practica2.gui; import javax.swing.table.DefaultTableModel; import practica2.dto.Cliente; /** * * @author CarlosJaquezPayamps */ public class JFPrincipal extends javax.swing.JFrame { /** * Creates new form Principal */ public JFPrincipal() { initComponents(); inicializarTabla(); } /** * Inicializa la tabla clientes con las columnas asignadas */ private void inicializarTabla() { DefaultTableModel dtm = new DefaultTableModel(); dtm.setColumnIdentifiers(new String[]{"Nombre", "Apellidos", "Fecha Alta", "Provincia"}); jTClientes.setModel(dtm); } public void anadirCliente(Cliente cliente) { DefaultTableModel dtm = (DefaultTableModel) jTClientes.getModel(); dtm.addRow(cliente.toArrayString()); } /** * 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() { jScrollPane1 = new javax.swing.JScrollPane(); jTClientes = new javax.swing.JTable(); jMenuBar1 = new javax.swing.JMenuBar(); jMClientes = new javax.swing.JMenu(); jMIAlta = new javax.swing.JMenuItem(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jTClientes.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); jScrollPane1.setViewportView(jTClientes); jMClientes.setText("Clientes"); jMIAlta.setText("Alta..."); jMIAlta.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMIAltaActionPerformed(evt); } }); jMClientes.add(jMIAlta); jMenuBar1.add(jMClientes); setJMenuBar(jMenuBar1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(18, Short.MAX_VALUE) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(17, Short.MAX_VALUE) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 275, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jMIAltaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMIAltaActionPerformed JDAlta dialogoAlta = new JDAlta(this, true); dialogoAlta.setVisible(true); }//GEN-LAST:event_jMIAltaActionPerformed /** * @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(JFPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(JFPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(JFPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(JFPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new JFPrincipal().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JMenu jMClientes; private javax.swing.JMenuItem jMIAlta; private javax.swing.JMenuBar jMenuBar1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTable jTClientes; // End of variables declaration//GEN-END:variables }
gpl-3.0
jesusc/eclectic
tests/org.eclectic.test.streaming.largemodels/src-gen/DOM/SwitchStatement.java
2117
/** * <copyright> * </copyright> * * $Id$ */ package DOM; import org.eclipse.emf.common.util.EList; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Switch Statement</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * <ul> * <li>{@link DOM.SwitchStatement#getExpression <em>Expression</em>}</li> * <li>{@link DOM.SwitchStatement#getStatements <em>Statements</em>}</li> * </ul> * </p> * * @see DOM.DOMPackage#getSwitchStatement() * @model * @generated */ public interface SwitchStatement extends Statement { /** * Returns the value of the '<em><b>Expression</b></em>' containment reference. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Expression</em>' containment reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Expression</em>' containment reference. * @see #setExpression(Expression) * @see DOM.DOMPackage#getSwitchStatement_Expression() * @model containment="true" required="true" ordered="false" * @generated */ Expression getExpression(); /** * Sets the value of the '{@link DOM.SwitchStatement#getExpression <em>Expression</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Expression</em>' containment reference. * @see #getExpression() * @generated */ void setExpression(Expression value); /** * Returns the value of the '<em><b>Statements</b></em>' containment reference list. * The list contents are of type {@link DOM.Statement}. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Statements</em>' containment reference list isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Statements</em>' containment reference list. * @see DOM.DOMPackage#getSwitchStatement_Statements() * @model containment="true" * @generated */ EList<Statement> getStatements(); } // SwitchStatement
gpl-3.0
VojtechBruza/parasim
extensions/computation-verification-impl/src/main/java/org/sybila/parasim/computation/verification/VerifierExtension.java
1232
/** * Copyright 2011-2016, Sybila, Systems Biology Laboratory and individual * contributors by the @authors tag. * * This file is part of Parasim. * * Parasim 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 org.sybila.parasim.computation.verification; import org.sybila.parasim.core.api.loader.ExtensionBuilder; import org.sybila.parasim.core.spi.LoadableExtension; /** * @author <a href="mailto:xpapous1@fi.muni.cz">Jan Papousek</a> */ public class VerifierExtension implements LoadableExtension { @Override public void register(ExtensionBuilder builder) { builder.extension(VerifierRegistrar.class); } }
gpl-3.0
alberh/LifeTries
core/src/com/lifetries/Mappers.java
1132
package com.lifetries; import com.badlogic.ashley.core.ComponentMapper; import com.lifetries.components.ActorComponent; import com.lifetries.components.*; public abstract class Mappers { public static final ComponentMapper<PositionComponent> position = ComponentMapper.getFor(PositionComponent.class); public static final ComponentMapper<VelocityComponent> velocity = ComponentMapper.getFor(VelocityComponent.class); public static final ComponentMapper<TargetPositionComponent> targetPosition = ComponentMapper.getFor(TargetPositionComponent.class); public static final ComponentMapper<AnimationComponent> animation = ComponentMapper.getFor(AnimationComponent.class); public static final ComponentMapper<ColorComponent> color = ComponentMapper.getFor(ColorComponent.class); public static final ComponentMapper<EnergyComponent> energy = ComponentMapper.getFor(EnergyComponent.class); public static final ComponentMapper<StateComponent> state = ComponentMapper.getFor(StateComponent.class); public static final ComponentMapper<ActorComponent> actor = ComponentMapper.getFor(ActorComponent.class); }
gpl-3.0
KayuraTeam/kayura-tags
src/main/java/org/kayura/tags/easyui/TagRender.java
6421
/** * Copyright 2015-2016 the original author or authors. * HomePage: http://www.kayura.org */ package org.kayura.tags.easyui; import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.tagext.BodyTagSupport; import javax.servlet.jsp.tagext.Tag; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.kayura.tags.easyui.types.Toolbar; import org.kayura.tags.types.FucString; import org.kayura.tags.types.RawString; import org.kayura.tags.types.TagUtils; /** * EasyUI 标签库基础渲染器。 * * @author liangxia@live.com */ public abstract class TagRender extends BodyTagSupport { private static final long serialVersionUID = -2565725992851402935L; public static final String ANIMATION_SLIDE = "slide"; public static final String ANIMATION_FADE = "fade"; public static final String ANIMATION_SHOW = "show"; protected final Log logger = LogFactory.getLog(this.getClass()); private Boolean disabledTag = false; private String classStyle; private String style; /** * 获取 EasyUI 定义的标签样式名. */ public abstract String getEasyUITag(); /** * 获取 EasyUI 标签使用的 HTML 标签名,默认使用 div 标签. */ public String getHtmlTag() { return "div"; } /** * 表示为一个无Body的标签, 返回 true &lt;input /&gt; 否则如 &lt;div&gt;&lt;/div&gt; * * @return */ public Boolean emptyBody() { return false; } /** * 当生成标签时的用于添加属性,如:&lt;div {动作} &gt;&lt;/div&gt; * * @param writer */ public void doRenderProperty(JspWriter out) throws Exception { } /** * 当生成标签内容时的动作,如:&lt;div&gt;{动作}&lt;/div&gt; * * @param writer */ public void doRenderBody(JspWriter out) throws Exception { } public abstract Map<String, Object> makeOptions(); public void putMap(Map<String, Object> map, String key, Object value) { if (value != null) { map.put(key, value); } } public String json(Object value) { return TagUtils.json(value); } public String json(List<Toolbar> toolbars) { if (toolbars == null || toolbars.isEmpty()) { return ""; } StringBuilder sb = new StringBuilder(); Boolean hasNext = false; sb.append("["); for (Toolbar t : toolbars) { if (hasNext) { sb.append(","); } sb.append("{"); if (!isEmpty(t.getText())) { sb.append("text:\"" + t.getText() + "\","); } if (!isEmpty(t.getIconCls())) { sb.append("iconCls:\"" + t.getIconCls() + "\","); } sb.append("handler:function(){ " + t.getHandler() + " }"); sb.append("}"); hasNext = true; } sb.append("]"); return sb.toString(); } /** * 将 EasyUI 选项参数集转换为字符表示形式. * * @return */ public String optionsToString() { StringBuilder sb = new StringBuilder(""); Map<String, Object> map = makeOptions(); if (map != null) { for (Entry<String, Object> o : map.entrySet()) { Object v = o.getValue(); if (v != null) { String k = o.getKey(); if (v instanceof RawString) { String rs = ((RawString) v).getValue(); if (!isEmpty(rs)) { sb.append("," + k + ":" + rs); } } else if (v instanceof FucString) { String fs = ((FucString) v).getContent(); if (!isEmpty(fs)) { sb.append("," + k + ":" + fs); } } else if (v instanceof Integer || v instanceof Boolean || v instanceof Double) { sb.append("," + k + ":" + v); } else if (v instanceof String || v instanceof Enum) { sb.append("," + k + ":\"" + v + "\""); } else if (v instanceof Object) { sb.append("," + k + ":").append(json(v)); } } } } if (sb.length() > 0) { sb.delete(0, 1); } return sb.toString(); } protected Boolean isEmpty(String value) { return value == null || "".equals(value.trim()); } public void doBeforeStart(JspWriter out) throws Exception { } public void doBeforeEnd(JspWriter out) throws Exception { } public void doAfterEnd(JspWriter out) throws Exception { } @Override public int doStartTag() { JspWriter out = this.pageContext.getOut(); try { doBeforeStart(out); out.write("<" + this.getHtmlTag()); if (!isEmpty(getId())) { out.write(" id=\"" + getId() + "\""); } if (!isEmpty(getEasyUITag())) { if (disabledTag) { if (!isEmpty(getClassStyle())) { out.write(" class=\"" + getClassStyle().trim() + "\""); } } else { if (!isEmpty(getClassStyle())) { out.write(" class=\"easyui-" + getEasyUITag() + " " + getClassStyle().trim() + "\""); } else { out.write(" class=\"easyui-" + getEasyUITag() + "\""); } } } else { if (!isEmpty(getClassStyle())) { out.write(" class=\"" + getClassStyle().trim() + "\""); } } if (!isEmpty(getStyle())) { out.write(" style=\"" + getStyle() + "\""); } String options = optionsToString(); if (!isEmpty(options)) { options = options.replace('\'', '"'); out.write(" data-options='" + options + "'"); } doRenderProperty(out); if (emptyBody()) { out.write("/>"); } else { out.write(">"); doRenderBody(out); } } catch (Exception e) { e.printStackTrace(); logger.error(e.getMessage(), e); } return EVAL_BODY_INCLUDE; } @Override public int doEndTag() throws JspException { JspWriter out = this.pageContext.getOut(); try { if (!emptyBody()) { doBeforeEnd(out); out.write("</" + getHtmlTag() + ">"); } doAfterEnd(out); } catch (Exception e) { e.printStackTrace(); } return Tag.EVAL_PAGE; } public String getClassStyle() { return this.classStyle; } public void setClassStyle(String classStyle) { this.classStyle = classStyle; } public String getStyle() { return style; } public void setStyle(String style) { this.style = style; } public Boolean getDisabledTag() { return disabledTag; } public void setDisabledTag(Boolean disabledTag) { this.disabledTag = disabledTag; } }
gpl-3.0
XeliteXirish/Quantum-Energistics-2
src/main/Common/com/XeliteXirish/QuantumEnergistics2/reference/Textures.java
1285
package com.XeliteXirish.QuantumEnergistics2.reference; import com.XeliteXirish.QuantumEnergistics2.util.ResourceLocationHelper; import net.minecraft.util.ResourceLocation; public class Textures { // Model base directory public static final String MODEL_FILE_PATH = "textures/model/"; public static final String GUI_FILE_PATH = "textures/gui/"; // Gui's public static final ResourceLocation GUI_GENERATOR = ResourceLocationHelper.getResourceLocation(GUI_FILE_PATH + "guiGenerator.png"); public static final ResourceLocation GUI_MACERATOR = ResourceLocationHelper.getResourceLocation(GUI_FILE_PATH + "guiMacerator.png"); // Block Models public static final ResourceLocation MODEL_PALLADIUM_WIRE = ResourceLocationHelper.getResourceLocation(MODEL_FILE_PATH + "qmPalladiumWireWIP.png"); public static final ResourceLocation MODEL_ENERGY_CELL_CREATIVE = ResourceLocationHelper.getResourceLocation(MODEL_FILE_PATH + "creativeEnergyCell.png"); public static final ResourceLocation MODEL_ENERGY_CELL_BASIC = ResourceLocationHelper.getResourceLocation(MODEL_FILE_PATH + "basicEnergyCell.png"); public static final ResourceLocation MODEL_POTION_DISPENCER = ResourceLocationHelper.getResourceLocation(MODEL_FILE_PATH + "potionDispencer.png"); }
gpl-3.0
pavloff-de/spark4knime
src/de/pavloff/spark4knime/jsnippet/ui/JSnippetTextArea.java
4795
/* * ------------------------------------------------------------------------ * Copyright by KNIME GmbH, Konstanz, Germany * Website: http://www.knime.org; Email: contact@knime.org * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License, Version 3, 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, see <http://www.gnu.org/licenses>. * * Additional permission under GNU GPL version 3 section 7: * * KNIME interoperates with ECLIPSE solely via ECLIPSE's plug-in APIs. * Hence, KNIME and ECLIPSE are both independent programs and are not * derived from each other. Should, however, the interpretation of the * GNU GPL Version 3 ("License") under any applicable laws result in * KNIME and ECLIPSE being a combined program, KNIME GMBH herewith grants * you the additional permission to use and propagate KNIME together with * ECLIPSE with only the license terms in place for ECLIPSE applying to * ECLIPSE and the GNU GPL Version 3 applying for KNIME, provided the * license terms of ECLIPSE themselves allow for the respective use and * propagation of ECLIPSE together with KNIME. * * Additional permission relating to nodes for KNIME that extend the Node * Extension (and in particular that are based on subclasses of NodeModel, * NodeDialog, and NodeView) and that only interoperate with KNIME through * standard APIs ("Nodes"): * Nodes are deemed to be separate and independent programs and to not be * covered works. Notwithstanding anything to the contrary in the * License, the License does not apply to Nodes, you are not required to * license Nodes under the License, and you are granted a license to * prepare and propagate Nodes, in each case even if such Nodes are * propagated with or for interoperation with KNIME. The owner of a Node * may freely choose the license terms applicable to such Node, including * when such Node is propagated with or for interoperation with KNIME. * ------------------------------------------------------------------------ * * History * 24.11.2011 (hofer): created */ package de.pavloff.spark4knime.jsnippet.ui; import java.awt.Color; import org.fife.ui.rsyntaxtextarea.Token; import org.fife.ui.rsyntaxtextarea.folding.FoldParserManager; import org.knime.base.node.util.KnimeSyntaxTextArea; import de.pavloff.spark4knime.jsnippet.JavaSnippet; import de.pavloff.spark4knime.jsnippet.JavaSnippetDocument; import de.pavloff.spark4knime.jsnippet.guarded.GuardedDocument; import de.pavloff.spark4knime.jsnippet.guarded.GuardedSection; import de.pavloff.spark4knime.jsnippet.guarded.GuardedSectionsFoldParser; /** * A text area for the java snippet expression. * * @author Heiko Hofer */ @SuppressWarnings("serial") public class JSnippetTextArea extends KnimeSyntaxTextArea { /** * Create a new component. * @param snippet the snippet */ public JSnippetTextArea(final JavaSnippet snippet) { // initial text != null causes a null pointer exception super(new JavaSnippetDocument(), null, 20, 60); setDocument(snippet.getDocument()); addParser(snippet.getParser()); boolean parserInstalled = FoldParserManager.get().getFoldParser( SYNTAX_STYLE_JAVA) instanceof GuardedSectionsFoldParser; if (!parserInstalled) { FoldParserManager.get().addFoldParserMapping(SYNTAX_STYLE_JAVA, new GuardedSectionsFoldParser()); } setCodeFoldingEnabled(true); setSyntaxEditingStyle(SYNTAX_STYLE_JAVA); } /** * {@inheritDoc} */ @Override public Color getForegroundForToken(final Token t) { if (isInGuardedSection(t.getOffset())) { return Color.gray; } else { return super.getForegroundForToken(t); } } /** * Returns true when offset is within a guarded section. * * @param offset the offset to test * @return true when offset is within a guarded section. */ private boolean isInGuardedSection(final int offset) { GuardedDocument doc = (GuardedDocument)getDocument(); for (String name : doc.getGuardedSections()) { GuardedSection gs = doc.getGuardedSection(name); if (gs.contains(offset)) { return true; } } return false; } }
gpl-3.0
talek69/curso
stimulsoft/src/com/stimulsoft/base/json/JSONStringer.java
391
/* * Decompiled with CFR 0_114. */ package com.stimulsoft.base.json; import com.stimulsoft.base.json.JSONWriter; import java.io.StringWriter; import java.io.Writer; public class JSONStringer extends JSONWriter { public JSONStringer() { super(new StringWriter()); } public String toString() { return this.mode == 'd' ? this.writer.toString() : null; } }
gpl-3.0
innoticaltesters/myswaasth
self_help_run.java
3323
package version2; import java.io.File; import java.io.IOException; import java.util.concurrent.TimeUnit; import org.apache.commons.io.FileUtils; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.annotations.Test; public class selfhelprun { @Test public void home() throws InterruptedException, IOException { System.setProperty("webdriver.chrome.driver", "D://chromedriver.exe"); WebDriver driver=new ChromeDriver(); driver.manage().window().maximize(); driver.get("http://myswaasth.sia.co.in"); driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS); Myswaasthhomepage.Selfhelp(driver).click(); driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS); selfhelppage.conditions(driver).click(); File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); FileUtils.copyFile(scrFile, new File("D:\\Myswassth\\conditionspage.png")); selfhelppage.procedures(driver).click(); Thread.sleep(4000); File scrFile1 = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); FileUtils.copyFile(scrFile1, new File("D:\\Myswassth\\procedurepage.png")); selfhelppage.medications(driver).click(); Thread.sleep(4000); File scrFile2 = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); FileUtils.copyFile(scrFile2, new File("D:\\Myswassth\\medicationspage.png")); selfhelppage.Doctors(driver).click(); Thread.sleep(4000); File scrFile3 = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); FileUtils.copyFile(scrFile3, new File("D:\\Myswassth\\doctorespage.png")); selfhelppage.Hospiotals(driver).click(); Thread.sleep(4000); File scrFile4 = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); FileUtils.copyFile(scrFile4, new File("D:\\Myswassth\\hospitalspage.png")); selfhelppage.symptoms(driver).click(); Thread.sleep(4000); File scrFile5 = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); FileUtils.copyFile(scrFile5, new File("D:\\Myswassth\\symptonspage.png")); selfhelppage.rotate(driver).click(); Thread.sleep(4000); File scrFile6 = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); FileUtils.copyFile(scrFile6, new File("D:\\Myswassth\\rotate.png")); selfhelppage.femalerotate(driver).click(); Thread.sleep(4000); File scrFile7 = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); FileUtils.copyFile(scrFile7, new File("D:\\Myswassth\\female.png")); selfhelppage.rotate(driver).click(); Thread.sleep(4000); File scrFile8 = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); FileUtils.copyFile(scrFile8, new File("D:\\Myswassth\\femaleback.png")); selfhelppage.Avatar(driver).click(); Thread.sleep(4000); File scrFile9 = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); FileUtils.copyFile(scrFile9, new File("D:\\Myswassth\\avatar.png")); selfhelppage.Allsymptoms(driver).click(); Thread.sleep(4000); File scrFile10 = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); FileUtils.copyFile(scrFile10, new File("D:\\Myswassth\\allsymptoms.png")); } }
gpl-3.0
Baseform/Baseform-Epanet-Java-Library
src/org/addition/epanet/network/FieldsMap.java
10815
/* * Copyright (C) 2012 Addition, Lda. (addition at addition dot pt) * * 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 org.addition.epanet.network; import org.addition.epanet.Constants; import org.addition.epanet.util.ENException; import org.addition.epanet.network.io.Keywords; import org.addition.epanet.network.structures.Field; import org.addition.epanet.util.Utilities; import java.util.LinkedHashMap; import java.util.Map; /** * * Units report properties & conversion support class */ public class FieldsMap { /** * Network variables */ static public enum Type { ELEV (0,Keywords.t_ELEV ), // nodal water quality DEMAND (1,Keywords.t_DEMAND ), // nodal demand flow HEAD (2,Keywords.t_HEAD ), // link flow velocity PRESSURE (3,Keywords.t_PRESSURE ), // avg. reaction rate in link QUALITY (4,Keywords.t_QUALITY ), // link friction factor LENGTH (5,Keywords.t_LENGTH ), // avg. water quality in link DIAM (6,Keywords.t_DIAM ), // nodal hydraulic head FLOW (7,Keywords.t_FLOW ), // link diameter VELOCITY (8,Keywords.t_VELOCITY ), // time to fill a tank HEADLOSS (9,Keywords.t_HEADLOSS ), // link head loss LINKQUAL (10,Keywords.t_LINKQUAL ), // link status STATUS (11,Keywords.t_STATUS ), // tank volume SETTING (12,Keywords.t_SETTING ), // simulation time REACTRATE (13,Keywords.t_REACTRATE), // pump power output FRICTION (14,Keywords.t_FRICTION ), // link flow rate POWER (15), // pump/valve setting TIME (16), // simulation time of day VOLUME (17), // time to drain a tank CLOCKTIME (18), // nodal elevation FILLTIME (19), // link length DRAINTIME (20); // nodal pressure /** * Get field type from string. * @param text String to be parsed. * @return Parsed Field, null the string doesn't match any of the possible types. */ public static Type parse(String text){ for (Type type : Type.values()) if (Utilities.match(text, type.parseStr)) return type; return null; } /** * Field sequencial id. */ public final int id; /** * Field string. */ public final String parseStr; private Type(int id){this.id = id;this.parseStr = "";} private Type(int id, String pStr){this.id = id;this.parseStr = pStr;} } /** * Report fields properties. */ private Map<Type,Field> fields; /** * Fields units values. */ private Map<Type,Double> units; /** * Init fields default configuration */ public FieldsMap() { try{ fields = new LinkedHashMap<Type,Field>(); units = new LinkedHashMap<Type,Double>(); for(Type type: Type.values()) setField(type,new Field(type.parseStr)); getField(Type.FRICTION).setPrecision(3); for (int i= Type.DEMAND.id;i<= Type.QUALITY.id; i++) getField(Type.values()[i]).setEnabled(true); for (int i= Type.FLOW.id;i<= Type.HEADLOSS.id; i++) getField(Type.values()[i]).setEnabled(true); } catch (ENException e){ e.printStackTrace(); } } /** * Get report field properties from type. * @param type Field type. * @return Report field. * @throws org.addition.epanet.util.ENException If specified type not found. */ public Field getField(Type type) throws ENException { Object obj = fields.get(type); if(obj==null) throw new ENException(201,type.parseStr); else return (Field)obj; } /** * Get conversion value from field type. * @param type Field type. * @return Conversion units value (from user units to system units) * @throws ENException If specified type not found. */ public Double getUnits(Type type) throws ENException { Object obj = units.get(type); if(obj==null) throw new ENException(201,type.parseStr); else return (Double)obj; } /** * Update fields and units, after loading the INP. * @param targetUnits * @param flowFlag * @param pressFlag * @param qualFlag * @param ChemUnits * @param SpGrav * @param Hstep */ public void prepare(PropertiesMap.UnitsType targetUnits, PropertiesMap.FlowUnitsType flowFlag, PropertiesMap.PressUnitsType pressFlag, PropertiesMap.QualType qualFlag, String ChemUnits, Double SpGrav, Long Hstep) throws ENException { double dcf, ccf, qcf, hcf, pcf, wcf; if (targetUnits == PropertiesMap.UnitsType.SI) { getField(Type.DEMAND).setUnits(flowFlag.parseStr); getField(Type.ELEV).setUnits(Keywords.u_METERS); getField(Type.HEAD).setUnits(Keywords.u_METERS); if (pressFlag == PropertiesMap.PressUnitsType.METERS) getField(Type.PRESSURE).setUnits(Keywords.u_METERS); else getField(Type.PRESSURE).setUnits(Keywords.u_KPA); getField(Type.LENGTH).setUnits(Keywords.u_METERS); getField(Type.DIAM).setUnits(Keywords.u_MMETERS); getField(Type.FLOW).setUnits(flowFlag.parseStr); getField(Type.VELOCITY).setUnits(Keywords.u_MperSEC); getField(Type.HEADLOSS).setUnits("m"+Keywords.u_per1000M); getField(Type.FRICTION).setUnits(""); getField(Type.POWER).setUnits(Keywords.u_KW); dcf = 1000.0* Constants.MperFT; qcf = Constants.LPSperCFS; if (flowFlag == PropertiesMap.FlowUnitsType.LPM) qcf = Constants.LPMperCFS; if (flowFlag == PropertiesMap.FlowUnitsType.MLD) qcf = Constants.MLDperCFS; if (flowFlag == PropertiesMap.FlowUnitsType.CMH) qcf = Constants.CMHperCFS; if (flowFlag == PropertiesMap.FlowUnitsType.CMD) qcf = Constants.CMDperCFS; hcf = Constants.MperFT; if (pressFlag == PropertiesMap.PressUnitsType.METERS) pcf = Constants.MperFT*SpGrav; else pcf = Constants.KPAperPSI*Constants.PSIperFT*SpGrav; wcf = Constants.KWperHP; } else { getField(Type.DEMAND).setUnits(flowFlag.parseStr); getField(Type.ELEV).setUnits(Keywords.u_FEET); getField(Type.HEAD).setUnits(Keywords.u_FEET); getField(Type.PRESSURE).setUnits(Keywords.u_PSI); getField(Type.LENGTH).setUnits(Keywords.u_FEET); getField(Type.DIAM).setUnits(Keywords.u_INCHES); getField(Type.FLOW).setUnits(flowFlag.parseStr); getField(Type.VELOCITY).setUnits(Keywords.u_FTperSEC); getField(Type.HEADLOSS).setUnits("ft"+Keywords.u_per1000FT); getField(Type.FRICTION).setUnits(""); getField(Type.POWER).setUnits(Keywords.u_HP); dcf = 12.0; qcf = 1.0; if (flowFlag == PropertiesMap.FlowUnitsType.GPM) qcf = Constants.GPMperCFS; if (flowFlag == PropertiesMap.FlowUnitsType.MGD) qcf = Constants.MGDperCFS; if (flowFlag == PropertiesMap.FlowUnitsType.IMGD)qcf = Constants.IMGDperCFS; if (flowFlag == PropertiesMap.FlowUnitsType.AFD) qcf = Constants.AFDperCFS; hcf = 1.0; pcf = Constants.PSIperFT*SpGrav; wcf = 1.0; } getField(Type.QUALITY).setUnits(""); ccf = 1.0; if (qualFlag == PropertiesMap.QualType.CHEM) { ccf = 1.0/Constants.LperFT3; getField(Type.QUALITY).setUnits(ChemUnits); getField(Type.REACTRATE).setUnits(ChemUnits + Keywords.t_PERDAY); } else if (qualFlag == PropertiesMap.QualType.AGE) getField(Type.QUALITY).setUnits(Keywords.u_HOURS); else if (qualFlag == PropertiesMap.QualType.TRACE) getField(Type.QUALITY).setUnits(Keywords.u_PERCENT); setUnits(Type.DEMAND,qcf); setUnits(Type.ELEV,hcf); setUnits(Type.HEAD,hcf); setUnits(Type.PRESSURE,pcf); setUnits(Type.QUALITY,ccf); setUnits(Type.LENGTH,hcf); setUnits(Type.DIAM,dcf); setUnits(Type.FLOW,qcf); setUnits(Type.VELOCITY,hcf); setUnits(Type.HEADLOSS,hcf); setUnits(Type.LINKQUAL,ccf); setUnits(Type.REACTRATE,ccf); setUnits(Type.FRICTION,1.0); setUnits(Type.POWER,wcf); setUnits(Type.VOLUME,hcf*hcf*hcf); if (Hstep < 1800) { setUnits(Type.TIME,1.0/60.0); getField(Type.TIME).setUnits(Keywords.u_MINUTES); } else { setUnits(Type.TIME,1.0/3600.0); getField(Type.TIME).setUnits(Keywords.u_HOURS); } } /** * Revert system units to user units. * @param type Field type. * @param value Value to be converted. * @return Value in user units. * @throws ENException */ public double revertUnit(Type type,double value) throws ENException { return type!=null?value*getUnits(type):value; } public double convertUnitToSystem(Type type,double value) throws ENException { return value/getUnits(type); } /** * Set field properties. * @param type Field type. * @param value Report field reference. */ private void setField(Type type,Field value) { fields.put(type,value); } /** * Set conversion value from field type. * @param type Field type. * @param value Field value. */ private void setUnits(Type type,Double value) { units.put(type,value); } }
gpl-3.0
kromonos/Mustard-Mod
src/org/mumod/urlshortener/B1tit.java
1393
package org.mumod.urlshortener; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.JSONObject; import org.mumod.util.HttpManager; import org.mumod.util.MustardException; import android.content.Context; public class B1tit implements UrlShortener { protected Context mContext; protected String b1tUrl = "http://b1t.it/"; public B1tit(Context context) { mContext=context; } public String doShort(String longUrl, HashMap<String, String> params) throws MustardException { return doShort(longUrl, "", ""); } public String doShort(String longUrl, String urlStr, String yourlsAPIKey) throws MustardException { URL uri = null; try { uri =new URL(b1tUrl); } catch (MalformedURLException e) { throw new MustardException(e.getMessage()); } HttpManager hm = new HttpManager(mContext,uri.getHost()); ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("url", longUrl)); try { JSONObject o = hm.getJsonObject(b1tUrl, HttpManager.POST,params); String b1t = o.getString("id"); return b1tUrl + b1t; } catch (Exception e) { throw new MustardException(e.getMessage()); } } public String getShorterName() { return "b1t.it"; } }
gpl-3.0
epam/Wilma
wilma-application/modules/wilma-route-engine/src/main/java/com/epam/wilma/router/RoutingService.java
5552
package com.epam.wilma.router; /*========================================================================== Copyright since 2013, EPAM Systems This file is part of Wilma. Wilma 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. Wilma 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 Wilma. If not, see <http://www.gnu.org/licenses/>. ===========================================================================*/ import com.epam.wilma.common.helper.OperationMode; import com.epam.wilma.domain.http.WilmaHttpEntity; import com.epam.wilma.domain.http.WilmaHttpRequest; import com.epam.wilma.domain.stubconfig.StubDescriptor; import com.epam.wilma.router.command.StubDescriptorModificationCommand; import com.epam.wilma.router.configuration.RouteEngineConfigurationAccess; import com.epam.wilma.router.configuration.domain.PropertyDTO; import com.epam.wilma.router.domain.ResponseDescriptorDTO; import com.epam.wilma.router.evaluation.StubDescriptorEvaluator; import com.epam.wilma.router.evaluation.StubModeEvaluator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; /** * Contains route logic of request messages. * * @author Tunde_Kovacs * @author Tamas_Bihari */ @Component public class RoutingService { private final Map<String, ResponseDescriptorDTO> responseDescriptorMap = new HashMap<>(); private final Object guard = new Object(); private Map<String, StubDescriptor> stubDescriptors = new LinkedHashMap<>(); private OperationMode operationMode; @Autowired private StubDescriptorEvaluator stubDescriptorEvaluator; @Autowired private StubModeEvaluator stubModeEvaluator; @Autowired private RouteEngineConfigurationAccess configurationAccess; /** * Redirects requests based on their content. If a request needs to be redirected to the stub, * it will be added to a map that will provide response information for the stub. * * @param request the request message that is checked * @return true if message should be redirected to the webapp. False otherwise. */ public boolean redirectRequestToStub(final WilmaHttpRequest request) { boolean redirect; ResponseDescriptorDTO responseDescriptorDTO = stubDescriptorEvaluator.findResponseDescriptor(stubDescriptors, request); if (responseDescriptorDTO == null) { responseDescriptorDTO = stubModeEvaluator.getResponseDescriptorForStubMode(request, operationMode); } redirect = responseDescriptorDTO != null; if (redirect) { //need to add this extra header, helping the stub to identify the response request.addHeaderUpdate(WilmaHttpEntity.WILMA_LOGGER_ID, request.getWilmaMessageId()); saveInResponseDescriptorMap(request, responseDescriptorDTO); } return redirect; } /** * Reads a value matched to a key from the response descriptor map and * if the value is found it deletes it from the map in order to free the map from it. * * @param key search parameter * @return a {@link ResponseDescriptorDTO} matching the given <tt>key</tt> */ public ResponseDescriptorDTO getResponseDescriptorDTOAndRemove(final String key) { ResponseDescriptorDTO responseDescriptor = responseDescriptorMap.get(key); if (responseDescriptor != null) { responseDescriptorMap.remove(key); } return responseDescriptor; } /** * Sets the new operation mode. * * @param operationMode the new operation mode coming from a UI config */ public void setOperationMode(final OperationMode operationMode) { this.operationMode = operationMode; } public Map<String, StubDescriptor> getStubDescriptors() { return stubDescriptors; } public boolean isStubModeOn() { return operationMode == OperationMode.STUB; } private void getOperationMode() { if (operationMode == null) { PropertyDTO properties = configurationAccess.getProperties(); operationMode = properties.getOperationMode(); } } private void saveInResponseDescriptorMap(final WilmaHttpRequest request, final ResponseDescriptorDTO responseDescriptorDTO) { responseDescriptorMap.put(request.getWilmaMessageId(), responseDescriptorDTO); } /** * This method execute the given command. The given command is any operation which works with the stubDescriptors collection. * * @param command is the given operation * @throws ClassNotFoundException if problem happens */ public void performModification(final StubDescriptorModificationCommand command) throws ClassNotFoundException { synchronized (guard) { stubDescriptors = command.modify(stubDescriptors); } getOperationMode(); } }
gpl-3.0
wisteso/wirc
src/handlers/InputHandler.java
375
package handlers; import core.Facade; import structures.ServerSource; /** * * @author Will */ public abstract class InputHandler { private final Facade mgr; public InputHandler(Facade mgr) { this.mgr = mgr; } public Facade getManager() { return mgr; } public abstract String[] getHooks(); public abstract void process(String msg, ServerSource source); }
gpl-3.0
Duke2k/jatf
jatf-tests/src/main/java/jatf/suites/AllArchitectureTests.java
1261
/** * This file is part of JATF. * <p> * JATF 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 3 of the License. * <p> * JATF is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * <p> * You should have received a copy of the GNU General Public License * along with JATF. If not, see <http://www.gnu.org/licenses/>. */ package jatf.suites; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.runner.RunWith; import org.junit.runners.Suite; @RunWith(Suite.class) @Suite.SuiteClasses({ ConventionTests.class, DependencyTests.class, MetricsTests.class, PatternTests.class, SecurityTests.class }) public class AllArchitectureTests extends ArchitectureTestSuiteBase { private static long startTime; @BeforeClass public static void startUpSuite() { startTime = System.currentTimeMillis(); } @AfterClass public static void endSuite() { endSuite(AllArchitectureTests.class, startTime); } }
gpl-3.0
sosilent/euca
clc/modules/www/src/main/java/com/eucalyptus/webui/client/view/FooterViewImpl.java
2520
package com.eucalyptus.webui.client.view; import java.util.logging.Logger; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiHandler; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.Widget; public class FooterViewImpl extends Composite implements FooterView { private static Logger LOG = Logger.getLogger( "FooterViewImpl" ); private static FooterViewImplUiBinder uiBinder = GWT.create( FooterViewImplUiBinder.class ); interface FooterViewImplUiBinder extends UiBinder<Widget, FooterViewImpl> {} @UiField LogSwitch logSwitch; @UiField Label version; @UiField Image loadingIcon; @UiField Image errorIcon; @UiField Label status; private Presenter presenter; public FooterViewImpl( ) { initWidget( uiBinder.createAndBindUi( this ) ); clearStatus( ); } @UiHandler( "logSwitch" ) void handleLogSwitchClickedEvent( ClickEvent e ) { if ( this.presenter != null ) { if ( this.logSwitch.isClicked( ) ) { this.presenter.onShowLogConsole( ); } else { this.presenter.onHideLogConsole( ); } } } @Override public void setPresenter( Presenter presenter ) { this.presenter = presenter; } @Override public void setVersion( String version ) { this.version.setText( version ); } private void clearStatus( ) { this.loadingIcon.setVisible( false ); this.errorIcon.setVisible( false ); this.status.setText( "" ); } @Override public void showStatus( StatusType type, String status, int clearDelay ) { switch ( type ) { case LOADING: this.loadingIcon.setVisible( true ); this.errorIcon.setVisible( false ); break; case ERROR: this.loadingIcon.setVisible( false ); this.errorIcon.setVisible( true ); break; default: this.loadingIcon.setVisible( false ); this.errorIcon.setVisible( false ); break; } this.status.setText( status ); if ( clearDelay > 0 ) { Timer timer = new Timer( ) { @Override public void run( ) { clearStatus( ); } }; timer.schedule( clearDelay ); } } }
gpl-3.0
nagyistoce/Wilma
wilma-message-search/modules/wilma-message-search-lucene/src/test/java/com/epam/wilma/message/search/lucene/index/FolderIndexerTest.java
2699
package com.epam.wilma.message.search.lucene.index; /*========================================================================== Copyright 2013-2015 EPAM Systems This file is part of Wilma. Wilma 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. Wilma 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 Wilma. If not, see <http://www.gnu.org/licenses/>. ===========================================================================*/ import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import java.io.File; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; /** * Unit tests for the class {@link FolderIndexer}. * @author Tunde_Kovacs * */ public class FolderIndexerTest { private static final String FILE_PATH = "src/test/resources/test-folder1/test-file.txt"; private static final String FOLDER_PATH = "src/test/resources/test-folder1"; private File file; private File folder1; @Mock private File folder2; @Mock private FileIndexer fileIndexer; @InjectMocks private FolderIndexer underTest; @BeforeMethod public void setUp() { MockitoAnnotations.initMocks(this); folder1 = new File(FOLDER_PATH); file = new File(FILE_PATH); } @Test public void testIndexFolderWhenFolderExistsShouldIndexFolder() { //GIVEN in setUp //WHEN underTest.indexFolder(folder1); //THEN verify(fileIndexer).indexFile(file); } @Test public void testIndexFolderWhenFolderCannotBeReadShouldDoNothing() { //GIVEN in setUp //WHEN underTest.indexFolder(new File("folder")); //THEN verify(fileIndexer, never()).indexFile(file); } @Test public void testIndexFolderWhenFolderEmptyShouldDoNothing() { //GIVEN given(folder2.canRead()).willReturn(true); given(folder2.isDirectory()).willReturn(true); given(folder2.list()).willReturn(null); //WHEN underTest.indexFolder(folder2); //THEN verify(fileIndexer, never()).indexFile(file); } }
gpl-3.0
jub77/grafikon
grafikon-model/src/main/java/net/parostroj/timetable/visitors/TrainDiagramVisitor.java
1085
package net.parostroj.timetable.visitors; import net.parostroj.timetable.model.*; /** * Train diagram visitor. * * @author jub */ public interface TrainDiagramVisitor { public void visit(TrainDiagram diagram); public void visit(Net net); public void visit(Train train); public void visit(Node node); public void visit(Line line); public void visit(LineTrack track); public void visit(NodeTrack track); public void visit(TrainType type); public void visit(Route route); public void visit(EngineClass engineClass); public void visit(TrainsCycle cycle); public void visit(TextItem item); public void visit(TimetableImage image); public void visit(LineClass lineClass); public void visit(OutputTemplate template); public void visit(TrainsCycleType type); public void visit(Group group); public void visit(FreightNet net); public void visit(Region region); public void visit(Company company); public void visit(Output output); public void visit(TrackConnector connector); }
gpl-3.0
Niky4000/UsefulUtils
projects/tutorials-master/tutorials-master/persistence-modules/spring-boot-persistence/src/test/java/com/baeldung/boot/test/UserRepositoryMultipleSqlFilesIntTest.java
934
package com.baeldung.boot.test; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; import com.baeldung.boot.domain.User; import com.baeldung.boot.repository.UserRepository; import java.util.Collection; import static org.assertj.core.api.Assertions.assertThat; /** * Created by adam. */ @RunWith(SpringRunner.class) @DataJpaTest @ActiveProfiles("multiplesqlfiles") public class UserRepositoryMultipleSqlFilesIntTest { @Autowired private UserRepository userRepository; @Test public void givenTwoImportFilesWhenFindAllShouldReturnSixUsers() { Collection<User> users = userRepository.findAll(); assertThat(users.size()).isEqualTo(6); } }
gpl-3.0
gysgogo/levetube
app/src/main/java/free/rm/skytube/businessobjects/GetSubscriptionVideosTask.java
5196
/* * SkyTube * Copyright (C) 2016 Ramon Mifsud * * 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 3 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 free.rm.skytube.businessobjects; import android.content.SharedPreferences; import android.widget.Toast; import com.google.api.client.util.DateTime; import java.io.IOException; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import free.rm.skytube.R; import free.rm.skytube.businessobjects.db.SubscriptionsDb; import free.rm.skytube.app.SkyTubeApp; import free.rm.skytube.gui.businessobjects.SubscriptionsFragmentListener; import static free.rm.skytube.app.SkyTubeApp.getContext; /** * A task that returns the videos of channel the user has subscribed too. Used to detect if new * videos have been published since last time the user used the app. */ public class GetSubscriptionVideosTask extends AsyncTaskParallel<Void, Void, Void> { private List<GetChannelVideosTask> tasks = new ArrayList<>(); private SubscriptionsFragmentListener listener; private int numTasksLeft = 0; private int numTasksFinished = 0; public GetSubscriptionVideosTask(SubscriptionsFragmentListener listener) { this.listener = listener; } @Override protected Void doInBackground(Void... voids) { try { List<YouTubeChannel> channels = SubscriptionsDb.getSubscriptionsDb().getSubscribedChannels(false); for(YouTubeChannel channel : channels) { tasks.add(new GetChannelVideosTask(channel)); } numTasksLeft = tasks.size(); int numToStart = tasks.size() >= 4 ? 4 : tasks.size(); // Start fetching videos for up to 4 channels simultaneously. for(int i=0;i<numToStart;i++) { tasks.get(0).executeInParallel(); tasks.remove(0); } } catch (IOException e) { e.printStackTrace(); } return null; } private class GetChannelVideosTask extends AsyncTaskParallel<Void, Void, List<YouTubeVideo>> { private GetChannelVideos getChannelVideos = new GetChannelVideos(); private YouTubeChannel channel; public GetChannelVideosTask(YouTubeChannel channel) { try { getChannelVideos.init(); /** * Get the last time all subscriptions were updated, and only fetch videos that were published after this. * Any new channels that have been subscribed to since the last time this refresh was done will have any * videos published after the last published time stored in the database, so we don't need to worry about missing * any. */ long l = SkyTubeApp.getPreferenceManager().getLong(SkyTubeApp.KEY_SUBSCRIPTIONS_LAST_UPDATED, -1); if(l != -1) { DateTime subscriptionsLastUpdated = new DateTime(l); if (subscriptionsLastUpdated != null) getChannelVideos.setPublishedAfter(subscriptionsLastUpdated); else // For the first fetch, default to only videos published in the last month. getChannelVideos.setPublishedAfter(getOneMonthAgo()); } getChannelVideos.setQuery(channel.getId()); this.channel = channel; } catch (IOException e) { e.printStackTrace(); Toast.makeText(getContext(), String.format(getContext().getString(R.string.could_not_get_videos), channel.getTitle()), Toast.LENGTH_LONG).show(); } } @Override protected List<YouTubeVideo> doInBackground(Void... voids) { List<YouTubeVideo> videos = null; if (!isCancelled()) { videos = getChannelVideos.getNextVideos(); } if(videos != null) { for (YouTubeVideo video : videos) channel.addYouTubeVideo(video); SubscriptionsDb.getSubscriptionsDb().saveChannelVideos(channel); } return videos; } @Override protected void onPostExecute(List<YouTubeVideo> youTubeVideos) { numTasksFinished++; boolean videosDeleted = false; if(numTasksFinished < numTasksLeft) { if(tasks.size() > 0) { // More channels to fetch videos from tasks.get(0).executeInParallel(); tasks.remove(0); } } else { videosDeleted = SubscriptionsDb.getSubscriptionsDb().trimSubscriptionVideos(); // All channels have finished querying. Update the last time this refresh was done. SharedPreferences.Editor editor = SkyTubeApp.getPreferenceManager().edit(); editor.putLong(SkyTubeApp.KEY_SUBSCRIPTIONS_LAST_UPDATED, new DateTime(new Date()).getValue()); editor.commit(); } if(listener != null) listener.onChannelVideosFetched(channel, youTubeVideos != null ? youTubeVideos.size() : 0, videosDeleted); } private DateTime getOneMonthAgo() { Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.MONTH, -1); Date date = calendar.getTime(); return new DateTime(date); } } }
gpl-3.0
ThePieMonster/PunnettSquare
app/src/main/java/net/piestudios/app/punnettsquare/VersionActivity.java
17707
package net.piestudios.app.punnettsquare; import android.animation.ValueAnimator; import android.annotation.SuppressLint; import android.content.pm.ActivityInfo; import android.content.res.Configuration; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Matrix; import android.graphics.Rect; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.ShapeDrawable; import android.support.v7.app.*; import android.os.Bundle; import android.os.Handler; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.view.Display; import android.view.MotionEvent; import android.view.Surface; import android.view.View; import android.view.MenuItem; import android.support.v4.app.NavUtils; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.content.Context; import android.view.Window; import android.view.WindowManager; import android.view.animation.Animation; import android.view.animation.TranslateAnimation; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; /** * An example full-screen activity that shows and hides the system UI (i.e. * status bar and navigation/system bar) with user interaction. */ public class VersionActivity extends AppCompatActivity implements SensorEventListener { // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ private float mLastX, mLastY, mLastZ; private boolean mInitialized; private SensorManager mSensorManager; private Sensor mAccelerometer; private final float NOISE = (float) 2.0; ImageView imageViewChromoX; ImageView imageViewChromoY; float gyroXaxis; float gyroYaxis; float gyroZaxis; private Matrix matrix = new Matrix(); private Matrix savedMatrix = new Matrix(); int counter = 0; int temp = 0; // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ /** * Whether or not the system UI should be auto-hidden after * {@link #AUTO_HIDE_DELAY_MILLIS} milliseconds. */ private static final boolean AUTO_HIDE = true; /** * If {@link #AUTO_HIDE} is set, the number of milliseconds to wait after * user interaction before hiding the system UI. */ private static final int AUTO_HIDE_DELAY_MILLIS = 3000; /** * Some older devices needs a small delay between UI widget updates * and a change of the status and navigation bar. */ private static final int UI_ANIMATION_DELAY = 300; private final Handler mHideHandler = new Handler(); private View mContentView; private final Runnable mHidePart2Runnable = new Runnable() { @SuppressLint("InlinedApi") @Override public void run() { // Delayed removal of status and navigation bar // Note that some of these constants are new as of API 16 (Jelly Bean) // and API 19 (KitKat). It is safe to use them, as they are inlined // at compile-time and do nothing on earlier devices. mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION); } }; //private View mControlsView; private final Runnable mShowPart2Runnable = new Runnable() { @Override public void run() { // Delayed display of UI elements ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.show(); } //mControlsView.setVisibility(View.VISIBLE); } }; private boolean mVisible; private final Runnable mHideRunnable = new Runnable() { @Override public void run() { hide(); } }; /** * Touch listener to use for in-layout UI controls to delay hiding the * system UI. This is to prevent the jarring behavior of controls going away * while interacting with activity UI. */ private final View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { if (AUTO_HIDE) { delayedHide(AUTO_HIDE_DELAY_MILLIS); } return false; } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_version); // Lock rotation to portait super.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); } // ++++++++++++++++++++++++++++++++++++++++ onCreate ++++++++++++++++++++++++++++++++++++++++++++ mInitialized = false; mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL); // Create Chromo X & Y images imageViewChromoX = (ImageView) findViewById(R.id.chromosome_x); Drawable drawableChromoX = getDrawable(R.drawable.chromosome_x); imageViewChromoX.setImageDrawable(drawableChromoX); imageViewChromoY = (ImageView) findViewById(R.id.chromosome_y); Drawable drawableChromoY = getDrawable(R.drawable.chromosome_y); imageViewChromoY.setImageDrawable(drawableChromoY); final DisplayMetrics displayMetrics = getResources().getDisplayMetrics(); final Rect parentRect = new Rect(0, 0, displayMetrics.widthPixels, displayMetrics.heightPixels); final PointF offsetPoint = new PointF(); /* imageViewChromoX.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(final View view, final MotionEvent motionEvent) { final int action = motionEvent.getAction(); switch (action & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: offsetPoint.x = motionEvent.getX(); offsetPoint.y = motionEvent.getY(); break; case MotionEvent.ACTION_MOVE: float x = motionEvent.getX(); float y = motionEvent.getY(); imageViewChromoX.offsetLeftAndRight((int) (x - offsetPoint.x)); imageViewChromoX.offsetTopAndBottom((int) (y - offsetPoint.y)); // check boundaries if (imageViewChromoX.getRight() > parentRect.right) { imageViewChromoX.offsetLeftAndRight(-(imageViewChromoX.getRight() - parentRect.right)); } else if (imageViewChromoX.getLeft() < parentRect.left) { imageViewChromoX.offsetLeftAndRight((parentRect.left - imageViewChromoX.getLeft())); } if (imageViewChromoX.getBottom() > parentRect.bottom) { imageViewChromoX.offsetTopAndBottom(-(imageViewChromoX.getBottom() - parentRect.bottom)); } else if (imageViewChromoX.getTop() < parentRect.top) { imageViewChromoX.offsetTopAndBottom((parentRect.top - imageViewChromoX.getTop())); } break; } return true; } }); */ View.OnTouchListener listener = new View.OnTouchListener() { PointF DownPT = new PointF(); // Record Mouse Position When Pressed Down PointF StartPT = new PointF(); // Record Start Position of 'img' @Override public boolean onTouch(View v, MotionEvent event) { if (v.getTag() != null && v.getTag().equals("chromX")) { int eid = event.getAction(); switch (eid) { case MotionEvent.ACTION_MOVE : PointF mv = new PointF(event.getX() - DownPT.x, event.getY() - DownPT.y); imageViewChromoX.setX((int) (StartPT.x + mv.x)); imageViewChromoX.setY((int) (StartPT.y + mv.y)); StartPT = new PointF(imageViewChromoX.getX(), imageViewChromoX.getY()); break; case MotionEvent.ACTION_DOWN : DownPT.x = event.getX(); DownPT.y = event.getY(); StartPT = new PointF(imageViewChromoX.getX(), imageViewChromoX.getY() ); break; case MotionEvent.ACTION_UP : // Nothing have to do break; default : break; } } else if (v.getTag() != null && v.getTag().equals("chromY")) { int eid = event.getAction(); switch (eid) { case MotionEvent.ACTION_MOVE : PointF mv = new PointF( event.getX() - DownPT.x, event.getY() - DownPT.y); imageViewChromoY.setX((int)(StartPT.x+mv.x)); imageViewChromoY.setY((int)(StartPT.y+mv.y)); StartPT = new PointF(imageViewChromoY.getX(), imageViewChromoY.getY() ); break; case MotionEvent.ACTION_DOWN : DownPT.x = event.getX(); DownPT.y = event.getY(); StartPT = new PointF(imageViewChromoY.getX(), imageViewChromoY.getY() ); break; case MotionEvent.ACTION_UP : // Nothing have to do break; default : break; } } return true; } }; imageViewChromoX.setOnTouchListener(listener); imageViewChromoY.setOnTouchListener(listener); // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ mVisible = true; //mControlsView = findViewById(R.id.fullscreen_content_controls); mContentView = findViewById(R.id.fullscreen_content); // Set up the user interaction to manually show or hide the system UI. mContentView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { toggle(); } }); // Upon interacting with UI controls, delay any scheduled hide() // operations to prevent the jarring behavior of controls going away // while interacting with the UI. //findViewById(R.id.dummy_button).setOnTouchListener(mDelayHideTouchListener); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); // Trigger the initial hide() shortly after the activity has been // created, to briefly hint to the user that UI controls // are available. delayedHide(100); } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == android.R.id.home) { // This ID represents the Home or Up button. NavUtils.navigateUpFromSameTask(this); return true; } return super.onOptionsItemSelected(item); } private void toggle() { if (mVisible) { hide(); } else { //show(); } } private void hide() { // Hide UI first ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.hide(); } //mControlsView.setVisibility(View.GONE); mVisible = false; // Schedule a runnable to remove the status and navigation bar after a delay mHideHandler.removeCallbacks(mShowPart2Runnable); mHideHandler.postDelayed(mHidePart2Runnable, UI_ANIMATION_DELAY); } @SuppressLint("InlinedApi") private void show() { // Show the system bar mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION); mVisible = true; // Schedule a runnable to display UI elements after a delay mHideHandler.removeCallbacks(mHidePart2Runnable); mHideHandler.postDelayed(mShowPart2Runnable, UI_ANIMATION_DELAY); } /** * Schedules a call to hide() in [delay] milliseconds, canceling any * previously scheduled calls. */ private void delayedHide(int delayMillis) { mHideHandler.removeCallbacks(mHideRunnable); mHideHandler.postDelayed(mHideRunnable, delayMillis); } // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ protected void onResume() { super.onResume(); mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL); } protected void onPause() { super.onPause(); mSensorManager.unregisterListener(this); } @Override protected void onStop() { mSensorManager.unregisterListener(this); super.onStop(); } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { // Do nothing } @Override public void onSensorChanged(SensorEvent event) { // *** Accelerometer *** //TextView tvX = (TextView) findViewById(R.id.a_x_axis); //TextView tvY = (TextView) findViewById(R.id.a_y_axis); //TextView tvZ = (TextView) findViewById(R.id.a_z_axis); float x = event.values[0]; float y = event.values[1]; float z = event.values[2]; if (!mInitialized) { mLastX = x; mLastY = y; mLastZ = z; //tvX.setText("0.0"); //tvY.setText("0.0"); //tvZ.setText("0.0"); mInitialized = true; } else { float deltaX = Math.abs(mLastX - x); float deltaY = Math.abs(mLastY - y); float deltaZ = Math.abs(mLastZ - z); if (deltaX < NOISE) deltaX = (float) 0.0; if (deltaY < NOISE) deltaY = (float) 0.0; if (deltaZ < NOISE) deltaZ = (float) 0.0; mLastX = x; mLastY = y; mLastZ = z; //tvX.setText(Float.toString(deltaX)); //tvY.setText(Float.toString(deltaY)); //tvZ.setText(Float.toString(deltaZ)); // *** Gyroscope *** // If sensor is unreliable, return void if (event.accuracy == SensorManager.SENSOR_STATUS_UNRELIABLE) { return; } // Else it will output the Roll, Pitch and Yawn values //TextView tgX = (TextView) findViewById(R.id.g_x_axis); //TextView tgY = (TextView) findViewById(R.id.g_y_axis); //TextView tgZ = (TextView) findViewById(R.id.g_z_axis); gyroXaxis = event.values[2]; gyroYaxis = event.values[1]; gyroZaxis = event.values[0]; //tgX.setText(Float.toString(gyroXaxis)); //tgY.setText(Float.toString(gyroYaxis)); //tgZ.setText(Float.toString(gyroZaxis)); // Testing temp = (int) gyroYaxis; temp = temp * 1000; // raw values are to small to notice //if (counter == 10) { //imageMove(); //} counter++; } } public class PointF { public float x = 0; public float y = 0; public PointF(){}; public PointF( float _x, float _y ){ x = _x; y = _y; } } public void imageMove() { ValueAnimator animator = ValueAnimator.ofInt(temp); animator.setDuration(1000); animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) imageViewChromoX.getLayoutParams(); int animVar = (Integer) animation.getAnimatedValue(); //lp.setMargins(0, (Integer) animation.getAnimatedValue(), 0, 0); lp.setMargins(0,0,200,200); imageViewChromoX.setLayoutParams(lp); } }); animator.start(); } // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ }
gpl-3.0
dloman/OpenScoreboard
app/src/main/java/com/openscoreboard/ShotClockActivity.java
4902
package com.openscoreboard; import android.app.Dialog; import android.content.Context; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.TextView; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.concurrent.TimeUnit; public class ShotClockActivity extends Fragment implements OnClickListener, View.OnLongClickListener { public ShotClockActivity() {} @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Bundle bundle = getArguments(); mScoreboardData = bundle.getParcelable("ScoreboardData"); mShotClockActivity = getActivity(); View ShotClockView = inflater.inflate(R.layout.shotclock_layout, container, false); mAnimation = AnimationUtils.loadAnimation(getActivity(), R.anim.abc_slide_in_top); mAnimation.setDuration(400); mShotClock = (TextView) ShotClockView.findViewById(R.id.shotclock_value); mShotClock.setOnLongClickListener(this); ShotClockView.findViewById(R.id.shotclock_start_stop).setOnClickListener(this); ShotClockView.findViewById(R.id.shotclock_reset).setOnClickListener(this); mClockStartStopButton = ((Button)ShotClockView.findViewById(R.id.shotclock_start_stop)); mClockStartStopButton.setOnClickListener(this); mClockResetButton = ((Button)ShotClockView.findViewById(R.id.shotclock_reset)); mClockResetButton.setOnClickListener(this); mClockResetButton.setOnLongClickListener(this); UpdateShotClock(); return ShotClockView; } @Override public void onClick(View v) { int ViewId = v.getId(); switch(ViewId) { case R.id.shotclock_start_stop: if (mScoreboardData.IsShotClockRunning()) { mScoreboardData.SetShotClockRunning(false); } else { mScoreboardData.SetShotClockRunning(true); } break; case R.id.shotclock_reset: mScoreboardData.ResetShotClock(); break; } UpdateShotClock(); } @Override public boolean onLongClick(View v) { int ViewId = v.getId(); switch (ViewId) { case R.id.shotclock_value: ResetClock(false); mScoreboardData.SetShotClockRunning(false); break; case R.id.shotclock_reset: ResetClock(true); break; } return true; } public static void UpdateShotClock() { NumberFormat numberFormat = new DecimalFormat("00"); long shotClockTime = mScoreboardData.GetShotClock(); shotClockTime = TimeUnit.MILLISECONDS.toSeconds(shotClockTime); if (Integer.parseInt((String) mShotClock.getText()) != shotClockTime) { mShotClock.setText(String.valueOf(numberFormat.format(shotClockTime))); mShotClock.startAnimation(mAnimation); Scoreboard.sendPacket(getShotClockString(), Scoreboard.PacketType.eShotClock); } if (mScoreboardData.IsShotClockRunning() && mScoreboardData.GetShotClock() != 0) { mClockStartStopButton.setText("Stop Clock"); } else { mClockStartStopButton.setText("Start Clock"); } } private static String getShotClockString() { return mShotClock.getText().toString(); } private void ResetClock(boolean resetDefaultTime) { String title = "Set Current Shot Clock Time"; NumberPickerDialog.NumberPickerReasons numberPickerReasons = NumberPickerDialog.NumberPickerReasons.eSetCurrentShotClock; int maxValue = (int)mScoreboardData.GetDefaultShotClockTime()/1000; Long initialTimePickerValue = mScoreboardData.GetShotClock(); if (resetDefaultTime) { title = "Set Default Shot Clock Time"; initialTimePickerValue = mScoreboardData.GetDefaultShotClockTime(); numberPickerReasons = NumberPickerDialog.NumberPickerReasons.eSetDefaultShotClock; maxValue = 99; } DialogFragment dialogFragment = NumberPickerDialog.createInstance(title, "Time", initialTimePickerValue, numberPickerReasons, maxValue); dialogFragment.show(mShotClockActivity.getSupportFragmentManager(), "NumberEditor"); } private static FragmentActivity mShotClockActivity; private static ScoreboardData mScoreboardData; private static Animation mAnimation; private static Button mClockStartStopButton; private static Button mClockResetButton; private static TextView mShotClock; }
gpl-3.0
TrucklistStudio/truckliststudio
src/truckliststudio/mixers/Frame.java
3731
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package truckliststudio.mixers; import java.awt.Color; import java.awt.Graphics2D; //import java.awt.image.BufferStrategy; //import java.awt.GraphicsConfiguration; //import java.awt.GraphicsDevice; //import java.awt.GraphicsEnvironment; import java.awt.image.BufferedImage; import static truckliststudio.TrucklistStudio.audioFreq; /** * * @author patrick */ public class Frame { private int x = 0; private int y = 0; private int w = 320; private int h = 240; private int opacity = 100; private float audioVolume = 1; private byte[] audioData; private int zOrder = 0; private String uuid = null; private long frameNb = 0; private int aFreq = audioFreq; // GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment(); // GraphicsDevice device = env.getDefaultScreenDevice(); // GraphicsConfiguration config = device.getDefaultConfiguration(); private BufferedImage image; //= config.createCompatibleImage(320, 240, BufferedImage.TYPE_INT_ARGB) public Frame(String id, BufferedImage img, byte[] audio) { image = img; audioData = audio; uuid = id; } public Frame(int w, int h, int rate) { this.w = w; this.h = h; image = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); audioData = new byte[(aFreq * 2 * 2) / rate]; } public void setFrameNumber(long n) { frameNb = n; } public long getFrameNumber() { return frameNb; } public void copyFrame(Frame frame) { BufferedImage imageSrc = frame.getImage(); byte[] audioSrc = frame.getAudioData(); if (imageSrc != null) { Graphics2D g = image.createGraphics(); g.setBackground(new Color(0, 0, 0, 0)); g.clearRect(0, 0, w, h); g.drawImage(imageSrc, 0, 0, null); g.dispose(); } if (audioSrc != null && audioSrc.length == audioData.length) { System.arraycopy(audioSrc, 0, audioData, 0, audioSrc.length); } } public String getID() { return uuid; } public void setZOrder(int z) { zOrder = z; } public int getZOrder() { return zOrder; } public void setID(String id) { uuid = id; } public void setImage(BufferedImage img) { if (img != null) { Graphics2D g = image.createGraphics(); g.setRenderingHint(java.awt.RenderingHints.KEY_INTERPOLATION, java.awt.RenderingHints.VALUE_INTERPOLATION_BILINEAR); g.setBackground(new Color(0, 0, 0, 0)); g.clearRect(0, 0, w, h); // System.out.println("W:"+w+" H:"+h); g.drawImage(img, 0, 0, null); g.dispose(); } } public void setAudio(byte[] data) { if (data != null) { audioData = data.clone(); } } public void setOutputFormat(int x, int y, int w, int h, int opacity, float volume) { this.x = x; this.y = y; this.w = w; this.h = h; this.opacity = opacity; this.audioVolume = volume; } public BufferedImage getImage() { return image; } public byte[] getAudioData() { return audioData; } public int getX() { return x; } public int getY() { return y; } public int getWidth() { return w; } public int getHeight() { return h; } public int getOpacity() { return opacity; } public float getVolume() { return audioVolume; } }
gpl-3.0
cgrabowski/disco-wormhole
DiscoWormhole-desktop/src/com/adamantine/discowormhole/LogcatReader.java
2247
package com.adamantine.discowormhole; import java.io.IOException; import java.util.Scanner; public class LogcatReader implements Runnable { Scanner sc; Thread t; String line; String[] splits; LogcatReader() { sc = new Scanner(System.in); t = new Thread(this, "scanner thread"); System.out.println("Logcat Reader Active"); t.start(); } @Override public void run() { if (System.in == null) { try { throw new Exception(); } catch (Exception e) { e.printStackTrace(); System.exit(-1); } } while (true) { line = sc.nextLine(); System.out.println(line); if (line.equals("")) { continue; } splits = line.split(":|,"); if (splits.length != 3) { System.out.println("splits length is not 3 : length is " + splits.length); for (String s : splits) { System.out.println(s); } System.out.println("splits outputted"); continue; } splits = line.split("[(]"); if (!splits[0].equals("I/WormholePrefsChange")) { System.out.println("wrong tag: " + splits[0]); continue; } splits = line.split(": |, "); synchronized (PreferencePasser.getLock()) { if (splits[1].equals("color1")) { PreferencePasser.color1 = Integer.parseInt(splits[2]); } else if (splits[1].equals("color2")) { PreferencePasser.color2 = Integer.parseInt(splits[2]); } else if (splits[1].equals("color3")) { PreferencePasser.color3 = Integer.parseInt(splits[2]); } else if (splits[1].equals("flightSpeed")) { PreferencePasser.flightSpeed = Integer.parseInt(splits[2]); } else if (splits[1].equals("numRings")) { PreferencePasser.numRings = Integer.parseInt(splits[2]); } else if (splits[1].equals("particleSpeed")) { PreferencePasser.particleSpeed = Integer .parseInt(splits[2]); } else if (splits[1].equals("stretchX")) { PreferencePasser.stretchX = Integer.parseInt(splits[2]); } else if (splits[1].equals("stretchY")) { PreferencePasser.stretchY = Integer.parseInt(splits[2]); } else { try { throw new IOException(); } catch (IOException e) { System.out.println("no match found for: " + splits[1]); } } PreferencePasser.prefsChanged = true; } } } }
gpl-3.0
CCAFS/ccafs-ap
impactPathways/src/main/java/org/cgiar/ccafs/ap/data/dao/mysql/MySQLLiaisonInstitutionDAO.java
7547
/***************************************************************** * This file is part of CCAFS Planning and Reporting Platform. * CCAFS P&R is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * at your option) any later version. * CCAFS P&R is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with CCAFS P&R. If not, see <http://www.gnu.org/licenses/>. *****************************************************************/ package org.cgiar.ccafs.ap.data.dao.mysql; import org.cgiar.ccafs.ap.data.dao.LiaisonInstitutionDAO; import org.cgiar.ccafs.utils.db.DAOManager; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.google.inject.Inject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author Hernán David Carvajal B. - CIAT/CCAFS */ public class MySQLLiaisonInstitutionDAO implements LiaisonInstitutionDAO { private static Logger LOG = LoggerFactory.getLogger(MySQLLiaisonInstitutionDAO.class); private DAOManager daoManager; @Inject public MySQLLiaisonInstitutionDAO(DAOManager daoManager) { this.daoManager = daoManager; } @Override public Map<String, String> getLiaisonInstitution(int liaisionInstitutionID) { Map<String, String> liaisonInstitution = new HashMap<>(); String query = "SELECT * FROM liaison_institutions WHERE id = " + liaisionInstitutionID; try (Connection con = daoManager.getConnection()) { ResultSet rs = daoManager.makeQuery(query, con); if (rs.next()) { liaisonInstitution.put("id", rs.getString("id")); liaisonInstitution.put("name", rs.getString("name")); liaisonInstitution.put("acronym", rs.getString("acronym")); liaisonInstitution.put("ip_program", rs.getString("ip_program")); } } catch (SQLException e) { LOG.error("getLiaisonInstitution() > Exception raised trying to get the liaison institution {}.", liaisionInstitutionID, e); } return liaisonInstitution; } @Override public List<Map<String, String>> getLiaisonInstitutionByUser(int userID) { List<Map<String, String>> liaisonInstitutions = new ArrayList<>(); StringBuilder query = new StringBuilder(); query.append("SELECT li.id, li.name, li.acronym FROM liaison_institutions li "); query.append("INNER JOIN liaison_users lu ON li.id = lu.institution_id "); query.append("INNER JOIN users u ON lu.user_id = u.id "); query.append("WHERE u.id = "); query.append(userID); try (Connection con = daoManager.getConnection()) { ResultSet rs = daoManager.makeQuery(query.toString(), con); while (rs.next()) { Map<String, String> liaisonInstitution = new HashMap<>(); liaisonInstitution.put("id", rs.getString("id")); liaisonInstitution.put("name", rs.getString("name")); liaisonInstitution.put("acronym", rs.getString("acronym")); liaisonInstitutions.add(liaisonInstitution); } } catch (SQLException e) { LOG.error( "getLiaisonInstitution() > Exception raised trying to get the liaison institution linked to the user {}.", userID, e); } return liaisonInstitutions; } @Override public List<Map<String, String>> getLiaisonInstitutions() { List<Map<String, String>> liaisonInstitutions = new ArrayList<>(); StringBuilder query = new StringBuilder(); query.append("SELECT * "); query.append("FROM liaison_institutions li "); try (Connection con = daoManager.getConnection()) { ResultSet rs = daoManager.makeQuery(query.toString(), con); while (rs.next()) { Map<String, String> liaisonInstitution = new HashMap<>(); liaisonInstitution.put("id", rs.getString("id")); liaisonInstitution.put("name", rs.getString("name")); liaisonInstitution.put("acronym", rs.getString("acronym")); liaisonInstitutions.add(liaisonInstitution); } } catch (SQLException e) { LOG.error("getLiaisonInstitutions() > Exception raised trying to get the liaison institutions.", e); } return liaisonInstitutions; } @Override public List<Map<String, String>> getLiaisonInstitutionsCenter() { List<Map<String, String>> liaisonInstitutions = new ArrayList<>(); StringBuilder query = new StringBuilder(); query.append("SELECT * "); query.append("FROM liaison_institutions li where id not in (1,2,3,4,5,6,7,8,9,10)"); try (Connection con = daoManager.getConnection()) { ResultSet rs = daoManager.makeQuery(query.toString(), con); while (rs.next()) { Map<String, String> liaisonInstitution = new HashMap<>(); liaisonInstitution.put("id", rs.getString("id")); liaisonInstitution.put("name", rs.getString("name")); liaisonInstitution.put("acronym", rs.getString("acronym")); liaisonInstitutions.add(liaisonInstitution); } } catch (SQLException e) { LOG.error("getLiaisonInstitutions() > Exception raised trying to get the liaison institutions.", e); } return liaisonInstitutions; } @Override public List<Map<String, String>> getLiaisonInstitutionsCrps() { List<Map<String, String>> liaisonInstitutions = new ArrayList<>(); StringBuilder query = new StringBuilder(); query.append("SELECT * "); query.append("FROM liaison_institutions li where id not in(1) "); try (Connection con = daoManager.getConnection()) { ResultSet rs = daoManager.makeQuery(query.toString(), con); while (rs.next()) { Map<String, String> liaisonInstitution = new HashMap<>(); liaisonInstitution.put("id", rs.getString("id")); liaisonInstitution.put("name", rs.getString("name")); liaisonInstitution.put("acronym", rs.getString("acronym")); liaisonInstitutions.add(liaisonInstitution); } } catch (SQLException e) { LOG.error("getLiaisonInstitutions() > Exception raised trying to get the liaison institutions.", e); } return liaisonInstitutions; } @Override public List<Map<String, String>> getLiaisonInstitutionsSynthesis() { List<Map<String, String>> liaisonInstitutions = new ArrayList<>(); StringBuilder query = new StringBuilder(); query.append("SELECT * "); query.append("FROM liaison_institutions li where id in(2,3,4,5,6,7,8,9,10) "); try (Connection con = daoManager.getConnection()) { ResultSet rs = daoManager.makeQuery(query.toString(), con); while (rs.next()) { Map<String, String> liaisonInstitution = new HashMap<>(); liaisonInstitution.put("id", rs.getString("id")); liaisonInstitution.put("name", rs.getString("name")); liaisonInstitution.put("acronym", rs.getString("acronym")); liaisonInstitution.put("ip_program", rs.getString("ip_program")); liaisonInstitutions.add(liaisonInstitution); } } catch (SQLException e) { LOG.error("getLiaisonInstitutions() > Exception raised trying to get the liaison institutions.", e); } return liaisonInstitutions; } }
gpl-3.0
hyperbox/vbox-5.0
modules/server/core/src/main/java/io/kamax/vbox5_0/setting/machine/OsTypeSettingAction.java
1638
/* * Hyperbox - Virtual Infrastructure Manager * Copyright (C) 2015 Maxime Dor * * http://kamax.io/hbox/ * * 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 io.kamax.vbox5_0.setting.machine; import io.kamax.hbox.constant.MachineAttribute; import io.kamax.tools.setting._Setting; import io.kamax.vbox.settings.general.OsTypeSetting; import io.kamax.vbox5_0.setting._MachineSettingAction; import org.virtualbox_5_0.IMachine; import org.virtualbox_5_0.LockType; public class OsTypeSettingAction implements _MachineSettingAction { @Override public LockType getLockType() { return LockType.Write; } @Override public String getSettingName() { return MachineAttribute.OsType.toString(); } @Override public void set(IMachine machine, _Setting setting) { String osType = setting.getValue().toString(); machine.setOSTypeId(osType); } @Override public _Setting get(IMachine machine) { return new OsTypeSetting(machine.getOSTypeId()); } }
gpl-3.0
csimons/primula-vulgaris
src/main/java/RBNpackage/OneRelData.java
10173
/* * OneRelData.java * * Copyright (C) 2009 Aalborg University * * contact: * jaeger@cs.aau.dk http://www.cs.aau.dk/~jaeger/Primula.html * * 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 RBNpackage; import java.util.Vector; import mymath.MyMathOps; import RBNutilities.rbnutilities; import myio.*; import org.dom4j.Element; /** An object of the class OneRelData represents one observation of * all or some atoms of one probabilistic relation for one given input * domain. * * @author jaeger * */ public class OneRelData { Rel rel; /** The default value for atoms of this relation: 'false' or '?' */ String defaultval; /**Vector of int[]; elements are maintained in *lexical order: 001 < 010 < 020 etc. */ Vector<int[]> trueAtoms; Vector<int[]> falseAtoms; /* For relations of arity 0 (globals): r()=true is * represented by trueAtoms = ([0]), falseAtoms = (); * r() = false is represented by trueAtoms = (), falseAtoms = ([0]) * r() uninstantiated is represented by trueAtoms = (), falseAtoms = () */ OneRelData() { } public OneRelData(Rel r, String dv) { rel = r; defaultval = dv; trueAtoms = new Vector<int[]>(); falseAtoms = new Vector<int[]>(); } /* Returns 1 if this global relation was not already set to * tv; 0 else; */ int setGlobal(boolean tv){ int result = 0; if (rel.arity != 0){ throw new RuntimeException("setGlobal applied to relation of arity >0"); } if (tv){ if (trueAtoms.size()==0){ falseAtoms = new Vector<int[]>(); trueAtoms.add(new int[1]); result = 1; } } else { if (falseAtoms.size()==0){ trueAtoms = new Vector<int[]>(); falseAtoms.add(new int[1]); result = 1; } } return result; } void add(int[][] tuples, boolean tv){ int[] nexttuple; int start = 0; for (int i=0;i<tuples.length;i++){ nexttuple = tuples[i]; start = add(nexttuple,tv,start); } } /* adds tuple; startindex is an index such that * tuple > this.true(false)Atoms[startindex] * Returns position at which tuple was inserted * and -1 if tuple was already there. */ public int add(int[] tuple, boolean tv, int startindex) { int pos = startindex; delete(tuple,!tv); Vector<int[]> atoms; if (tv) atoms = trueAtoms; else atoms = falseAtoms; boolean containsalready = false; if (atoms.size()==0) atoms.add(tuple); else{ int[] nexttup = (int[])atoms.elementAt(startindex); boolean movright = false; int compval=rbnutilities.arrayCompare(tuple,nexttup); if (compval==-1) movright = true; if (compval==0) containsalready=true; while (movright && pos < atoms.size()-1){ pos++; nexttup = (int[])atoms.elementAt(pos); compval = rbnutilities.arrayCompare(tuple,nexttup); if (compval != -1) movright = false; if (compval == 0) containsalready = true; } if (pos==atoms.size()-1){ if (compval==-1) // last element in atoms smaller than // new tuple atoms.add(tuple); if (compval==1) // last element in atoms larger than // new tuple atoms.add(pos,tuple); } else{ if (!containsalready) atoms.add(pos,tuple); } } if (containsalready){ return -1; } else return pos; } /** Returns all the atoms instantiated to true as * a vector of int[]. Objects are represented by * their internal index */ public Vector<int[]> allTrue(){ return trueAtoms; } public int numtrue(){ return trueAtoms.size(); } public int numfalse(){ return falseAtoms.size(); } /** Returns all the atoms instantiated to false as * a vector of int[]. Objects are represented by * their internal index */ public Vector<int[]> allFalse(){ return falseAtoms; } /** Returns all the atoms which are not instantiated * to either true or false. d is the domainsize, i.e. * the maximal index of an object to be considered. */ public Vector<int[]> allUnInstantiated(int d){ Vector<int[]> result = new Vector<int[]> (); int[] nextatom; int nextintrue = 0; int nextinfalse = 0; for (int i=0;i< MyMathOps.intPow(d,rel.getArity());i++){ nextatom = rbnutilities.indexToTuple(i,rel.getArity(),d); if (nextintrue < trueAtoms.size() && rbnutilities.arrayEquals(nextatom,(int[])trueAtoms.elementAt(nextintrue))) nextintrue++; else if (nextinfalse < falseAtoms.size() && rbnutilities.arrayEquals(nextatom,(int[])falseAtoms.elementAt(nextinfalse))) nextinfalse++; else result.add(nextatom); } return result; } /** Returns all the atoms instantiated to true as * a vector of strings. Objects are represented by * their name in structure A */ public Vector<String> allTrue(RelStruc A){ Vector<String> result = new Vector<String> (); for (int i=0;i<trueAtoms.size();i++) result.add( A.namesAt( (int[])trueAtoms.elementAt(i) )); return result; } /** Returns all the atoms instantiated to false as * a vector of strings. Objects are represented by * their name in structure A */ public Vector<String> allFalse(RelStruc A){ Vector<String> result = new Vector<String> (); for (int i=0;i<falseAtoms.size();i++) result.add( A.namesAt( (int[])falseAtoms.elementAt(i) )); return result; } /** Delete all atoms containing a * @param a */ public void delete(int a){ int pos = 0; int[] nextatom; while (pos < trueAtoms.size()){ nextatom = trueAtoms.elementAt(pos); if (rbnutilities.inArray(nextatom,a)) trueAtoms.remove(pos); else pos++; } pos = 0; while (pos < falseAtoms.size()){ nextatom = falseAtoms.elementAt(pos); if (rbnutilities.inArray(nextatom,a)) falseAtoms.remove(pos); else pos++; } } public void delete(int[] tuple,boolean tv) { Vector<int[]> atoms; if (tv) atoms = trueAtoms; else atoms = falseAtoms; int[] currtuple; int i = 0; while (i<atoms.size()){ currtuple = (int[])atoms.elementAt(i); if (rbnutilities.arrayEquals(currtuple,tuple)) atoms.remove(i); else i++; } } public void delete(int[][] tuples,boolean tv) { Vector<int[]> atoms; if (tv) atoms = trueAtoms; else atoms = falseAtoms; int[] nexttuple; int removeindex = 0; int i = 0; int compval; while (i<atoms.size() && removeindex < tuples.length){ nexttuple = (int[])atoms.elementAt(i); compval = rbnutilities.arrayCompare(tuples[removeindex],nexttuple); switch (compval){ case 0: atoms.remove(i); removeindex++; break; case 1: removeindex++; break; case -1: i++; } } } public Rel rel(){ return rel; } public String dv(){ return defaultval; } public String printAsString(RelStruc A, String pref){ /* pref is a string prefixed to every result line * used for example to prefix the gnuplot comment symbol * when result is written into a logfile used for plotting */ String result = ""; for (int j=0;j<trueAtoms.size();j++){ result = result + pref + rel.name.name + A.namesAt((int[])trueAtoms.elementAt(j))+ " = true" + '\n'; } for (int j=0;j<falseAtoms.size();j++){ result = result + pref + rel.name.name + A.namesAt((int[])falseAtoms.elementAt(j)) + " = false" + '\n'; } return result; } int truthValueOf(int[] tuple) { if (rel.arity ==0){ if (trueAtoms.size() > 0) return 1; if (falseAtoms.size() >0) return 0; return -1; } else { int result = -1; for (int i = 0; i<trueAtoms.size();i++){ if (rbnutilities.arrayEquals((int[])trueAtoms.elementAt(i),tuple)) result = 1; } for (int i = 0; i<falseAtoms.size();i++) { if (rbnutilities.arrayEquals((int[])falseAtoms.elementAt(i),tuple)) result = 0; } if (result == -1 && defaultval.equals("false")) result =0; return result; } } boolean isEmpty(){ if (trueAtoms.size()>0 || falseAtoms.size()>0) return false; else return true; } /**Returns the binary tuples from the specified node to some other node *This method is usable ONLY with binary relations */ public Vector getBinDirs(int node){ Vector<int[]> hits = new Vector<int[]>(); for(int i=0; i<trueAtoms.size(); ++i){ int[] temp = (int[])trueAtoms.elementAt(i); if(temp[0] == node) hits.addElement(temp); } return hits; } public void addRelData(Element el, RelStruc struc){ for (int i=0;i<trueAtoms.size();i++){ Element dl = el.addElement("d"); dl.addAttribute("rel", rel.name.name); dl.addAttribute("args", struc.namesAt(trueAtoms.elementAt(i))); dl.addAttribute("val", "true"); } if (defaultval != "false"){ for (int i=0;i<falseAtoms.size();i++){ Element dl = el.addElement("d"); dl.addAttribute("rel", rel.name.name); dl.addAttribute("args", struc.namesAt(falseAtoms.elementAt(i))); dl.addAttribute("val", "false"); } } } /** * Replaces all arguments b of trueAtoms and falseAtoms lists * by b-1 if b>a (needed after the deletion of node with index a from * the underlying SparseRelStruc) * @param a */ public void shiftArgs(int a){ int[] currtuple; if (rel.arity != 0){ for (int i=0;i<trueAtoms.size();i++){ currtuple = (int[])trueAtoms.elementAt(i); rbnutilities.arrayShiftArgs(currtuple,a); } for (int i=0;i<falseAtoms.size();i++){ currtuple = (int[])falseAtoms.elementAt(i); rbnutilities.arrayShiftArgs(currtuple,a); } } } }
gpl-3.0
kapitarg/time-management
time-management-app/src/main/java/ch/bbv/timemanagement/list/ListActivity.java
2320
package ch.bbv.timemanagement.list; import android.content.Intent; import android.os.Bundle; import android.view.KeyEvent; import android.view.View; import android.widget.AdapterView; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ListView; import ch.bbv.timemanagement.R; import ch.bbv.timemanagement.matrix.MatrixActivity; import ch.bbv.timemanagement.touch.GestureDetector; import ch.bbv.timemanagement.touch.Gestures; import com.google.inject.Inject; import roboguice.activity.RoboActivity; import roboguice.inject.InjectView; import static android.widget.AdapterView.OnItemClickListener; /** * Displays tasks in a single quadrant. */ public class ListActivity extends RoboActivity { @InjectView(R.id.addTask) private ImageButton addTask; @InjectView(R.id.todoEntryTitle) private EditText todoEntryTitle; @InjectView(R.id.todoList) private ListView todoList; @Inject private TaskListAdapter listAdapter; @Inject private ListController controller; @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(controller.model().getLayout()); createTodoList(); createButtons(); todoList.setOnTouchListener(new GestureDetector(controller.model().getMotionListener(), Gestures.values())); } @Override protected void onResume() { super.onResume(); controller.loadTasks(); } private void createTodoList() { todoList.setAdapter(listAdapter); todoList.setFastScrollEnabled(true); todoList.setScrollingCacheEnabled(false); controller.model().addPropertyChangeListener(listAdapter); todoList.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(final AdapterView<?> parent, final View view, final int position, final long id) { controller.toggleTaskSelectionAt(position); } }); } private void createButtons() { addTask.setOnClickListener(new AddTaskAction(controller, todoEntryTitle)); } @Override public boolean onKeyDown(final int keyCode, final KeyEvent event) { if (event.getKeyCode() != KeyEvent.KEYCODE_BACK) { return super.onKeyDown(keyCode, event); } startActivity(new Intent(this, MatrixActivity.class)); return true; } }
gpl-3.0
flakibr/Tetris
src/graphics/GameInformationPanel.java
3200
package graphics; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import javax.swing.JPanel; import javax.swing.JLabel; import logic.Tetris; import logic.ShapePrototypes; import logic.Vector2; public class GameInformationPanel extends JPanel { // PROPERTIES final GameWindow window; JLabel scoreLabel; // INITIALISATION public GameInformationPanel (GameWindow window) { this.window = window; setPreferredSize(new Dimension((int)window.getSize().getWidth(), window.gameInfoPanelHeight)); setVisible(true); addScoreLabel(); System.out.println("GameInformationPanel created!"); } // METHODS void addScoreLabel () { scoreLabel = new JLabel ("Score: 0", javax.swing.SwingConstants.LEFT); //scoreLabel.setBackground(new Color (200, 200, 200, 100) ); scoreLabel.setVisible(true); scoreLabel.setOpaque(true); scoreLabel.setBounds(0, 10, (int)this.getSize().getWidth(), 40); this.add(scoreLabel); } // PAINTING public void paintComponent (Graphics g) { super.paintComponent(g); drawTopLine(g); updateScoreLabel(g); drawNextShape(g); } void drawTopLine (Graphics g) { g.setColor(Color.BLACK); g.fillRect(0, 0, (int)this.getSize().getWidth(), 2); } void updateScoreLabel (Graphics g) { scoreLabel.setText("Score: " + window.getGamePanel().getGame().getCurrentScore() + "\nLevel: " + window.getGamePanel().getGame().getLevel()); } void drawNextShape(Graphics g) { if (window.getGamePanel().getGame().getNextShape() == null) return; ShapePrototypes nextShape = window.getGamePanel().getGame().getNextShape().getPrototype(); for (Vector2 pos : nextShape.getPositions()) { drawSinglePiece (g, pos.x, pos.y, nextShape.getColor()); } } void drawSinglePiece (Graphics g, int x, int y, Color c) { // Get the PixelPositions for left, right top and bottom Tetris game = window.getGamePanel().getGame(); int pieceSize = game.getPieceSize() / 2; int firstPixelX = pieceSize * x + 10; int firstPixelY = pieceSize * y + 10; int lastPixelX = firstPixelX + pieceSize - 1; int lastPixelY = firstPixelY + pieceSize - 1; // Fill the middle of the square. g.setColor(c); g.fillRect(firstPixelX, firstPixelY, pieceSize - 1, pieceSize - 1); // Draw the top and left border with a brighter color. g.setColor(c.brighter()); g.drawLine(firstPixelX, firstPixelY, lastPixelX, firstPixelY); // top left to top (right-1) g.drawLine(firstPixelX, firstPixelY + 1, firstPixelX, lastPixelY); // (top-1) left to bottom left // Draw the bottom and right border with a darker color. g.setColor(c.darker()); g.drawLine(lastPixelX, firstPixelY + 1, lastPixelX, lastPixelY - 1); // top right to (bottom-1) right g.drawLine(firstPixelX + 1, lastPixelY, lastPixelX, lastPixelY); // bottom (left+1) to bottom right //System.out.println("Single Piece drawn at: (" + x + ", " + y + ")"); } }
gpl-3.0
weizengke/gdoj
gdoj/src/com/gdoj/bean/OnlineUserBean.java
1617
package com.gdoj.bean; import java.util.Date; import org.apache.struts2.json.annotations.JSON; public class OnlineUserBean { private String username; private Date loginDate; private Date lastAccessTime; /* Óû§×î½üÒ»´Îpingʱ¼ä */ private Integer statusFlag; /* ÉÏÏß(1) or ÀëÏß(0) */ private Integer level; private String levelTitle; public Integer getStatusFlag() { return statusFlag; } public void setStatusFlag(Integer statusFlag) { this.statusFlag = statusFlag; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public Date getLoginDate() { return loginDate; } public void setLoginDate(Date loginDate) { this.loginDate = loginDate; } @JSON(format="yyyy-MM-dd HH:mm:ss") public Date getLastAccessTime() { return lastAccessTime; } public void setLastAccessTime(Date lastAccessTime) { this.lastAccessTime = lastAccessTime; } public OnlineUserBean() { super(); this.loginDate = new Date(); this.lastAccessTime = new Date(); this.statusFlag = 1; } public OnlineUserBean(String username, Date loginDate, Date lastAccessTime) { super(); this.username = username; this.loginDate = loginDate; this.lastAccessTime = lastAccessTime; this.statusFlag = 1; } public void setLevel(Integer level) { this.level = level; } public Integer getLevel() { return level; } public void setLevelTitle(String levelTitle) { this.levelTitle = levelTitle; } public String getLevelTitle() { return levelTitle; } }
gpl-3.0
pietrobraione/jbse
src/main/java/jbse/mem/Instance_METALEVELBOX.java
371
package jbse.mem; /** * Class that represents an instance in the heap whose * only purpose is to encapsulate an object at the * meta-level. * * @author Pietro Braione * */ public interface Instance_METALEVELBOX extends Instance { /** * Gets the encapsulated object. * * @return an {@link Object}. */ Object get(); Instance_METALEVELBOX clone(); }
gpl-3.0
MinestrapTeam/Minestrappolation-4
src/main/java/minestrapteam/mods/minestrappolation/item/ItemInertCrystalHeart.java
826
package minestrapteam.mods.minestrappolation.item; import minestrapteam.mods.minestrappolation.lib.MAchievements; import minestrapteam.mods.minestrappolation.lib.MItems; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.DamageSource; import net.minecraft.world.World; public class ItemInertCrystalHeart extends Item { @Override public ItemStack onItemRightClick(ItemStack itemStackIn, World worldIn, EntityPlayer playerIn) { if (playerIn.getMaxHealth() > 10F) { playerIn.addStat(MAchievements.crystal_heart, 1); playerIn.attackEntityFrom(DamageSource.causeIndirectMagicDamage(playerIn, playerIn), (float) 10); itemStackIn.setItem(MItems.crystal_heart); itemStackIn.stackSize = 1; } return itemStackIn; } }
gpl-3.0
NeuroMorphoOrg/LiterMate
LiteratureCrossRefServiceBoot/src/main/java/org/neuromorpho/literature/crossref/service/CrossRefService.java
6478
package org.neuromorpho.literature.crossref.service; import com.mongodb.gridfs.GridFSDBFile; import com.mongodb.gridfs.GridFSFile; import java.io.ByteArrayInputStream; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.Map; import org.neuromorpho.literature.crossref.communication.CrossRefConnection; import org.neuromorpho.literature.crossref.model.Article; import org.neuromorpho.literature.crossref.model.Author; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.gridfs.GridFsOperations; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.ByteArrayHttpMessageConverter; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; @Service public class CrossRefService { private final Logger log = LoggerFactory.getLogger(this.getClass()); @Value("${token}") private String token; @Autowired GridFsOperations gridOperations; @Autowired protected CrossRefConnection crossRefConnection; public Article retrieveArticleData(String doi) throws Exception { Article article = new Article(); Map message = crossRefConnection.findMetadataFromDOI(doi); log.debug("Message from CrossRef: " + message); List<String> titles = (ArrayList) message.get("title"); article.setTitle(titles.get(0)); ArrayList<Map> authors = (ArrayList) message.get("author"); List<Author> authorList = new ArrayList(); if (authors != null) { for (Map a : authors) { String given = (String) a.get("given"); String family = (String) a.get("family"); Author author = new Author(given + " " + family, null); authorList.add(author); } } article.setAuthorList(authorList); List<String> journalList = (List) message.get("container-title"); if (journalList != null && journalList.size() > 0) { article.setJournal(journalList.get(0)); } Map created = (Map) message.get("created"); String sortDateStr = (String) created.get("date-time"); article.setPublishedDate(this.tryParseDate(sortDateStr)); ArrayList<Map> links = (ArrayList) message.get("link"); for (Map link : links) { String contentType = (String) link.get("content-type"); if (contentType.equals("application/pdf")) { article.setPdfLink((String) link.get("URL")); } } article.setDoi(doi); log.debug("Article found: " + article.toString()); return article; } public void downloadPDFFromDOI(String doi, String id) throws Exception { Map message = crossRefConnection.findMetadataFromDOI(doi); ArrayList<Map> links = (ArrayList) message.get("link"); GridFSFile file = null; for (Map link : links) { String contentType = (String) link.get("content-type"); if (contentType.equals("application/pdf") || contentType.equals("unspecified")) { try { //Download pdf RestTemplate restTemplate = new RestTemplate(); restTemplate.getMessageConverters().add( new ByteArrayHttpMessageConverter()); HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_OCTET_STREAM)); headers.set("CR-Clickthrough-Client-Token", token); HttpEntity<String> entity = new HttpEntity<>(headers); String url = (String) link.get("URL"); log.debug("Accesing download pdf: " + url); ResponseEntity<byte[]> response = restTemplate.exchange( url, HttpMethod.GET, entity, byte[].class); while (response.getStatusCode() == HttpStatus.SEE_OTHER || response.getStatusCode() == HttpStatus.FOUND || response.getStatusCode() == HttpStatus.MOVED_PERMANENTLY) { response = restTemplate.exchange( response.getHeaders().getLocation(), HttpMethod.GET, entity, byte[].class); } if (response.getStatusCode() == HttpStatus.OK) { GridFSDBFile dbfile = this.findPDF(id); if (dbfile == null) { // if is not already in DB download byte[] pdf = response.getBody(); file = gridOperations.store(new ByteArrayInputStream(pdf), id); } } else { log.warn("Error in call" + response.getStatusCode()); } } catch (Exception ex) { log.debug("CrossRef link not working, trying other links"); } } else { log.warn("Article in CrossRef but no pdf associated"); } } } public GridFSDBFile findPDF(String id) { log.debug("Reading PDF filename: " + id); Query query = new Query(); Criteria criteria = Criteria.where("filename").is(id); query.addCriteria(criteria); GridFSDBFile dbfile = gridOperations.findOne(query); return dbfile; } protected Date tryParseDate(String dateStr) { String[] formatStrings = {"yyyy-MM-dd"}; for (String formatString : formatStrings) { try { return new SimpleDateFormat(formatString, Locale.US).parse(dateStr.toLowerCase()); } catch (ParseException e) { } } return null; } }
gpl-3.0
xiaoligit/hypersocket-framework
hypersocket-client/src/main/java/com/hypersocket/client/HypersocketClientAdapter.java
449
package com.hypersocket.client; public class HypersocketClientAdapter<T> implements HypersocketClientListener<T> { @Override public void connectStarted(HypersocketClient<T> client) { } @Override public void connectFailed(Exception e, HypersocketClient<T> client) { } @Override public void connected(HypersocketClient<T> client) { } @Override public void disconnected(HypersocketClient<T> client, boolean onError) { } }
gpl-3.0
lecousin/net.lecousin.framework-0.1
net.lecousin.framework.ui/src/net/lecousin/framework/ui/eclipse/control/text/lcml/LCMLText.java
4545
package net.lecousin.framework.ui.eclipse.control.text.lcml; import java.util.List; import net.lecousin.framework.Pair; import net.lecousin.framework.event.Event.Listener; import net.lecousin.framework.thread.RunnableWithData; import net.lecousin.framework.ui.eclipse.control.text.lcml.internal.LCMLParser; import net.lecousin.framework.ui.eclipse.control.text.lcml.internal.Link; import net.lecousin.framework.ui.eclipse.control.text.lcml.internal.Paragraph; import net.lecousin.framework.ui.eclipse.control.text.lcml.internal.SectionContainer.GetAllFinder; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.ScrolledComposite; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; /** * Supports the following:<ul> * <li>b: for bold section</li> * <li>i: for italic section</li> * <li>br: for break line</li> * <li>a: for hyperlink<ul> * <li>href: link url, to be catched by an hyperlink listener</li> * </ul></li> * <li>p: for paragraph<ul> * <li>marginTop: spacing before the paragraph (default is 3)</li> * <li>marginBotton: spacing after the paragraph (default is 0)</li> * <li>marginLeft: indentation of the paragraph (default is 0)</li> * </ul></li> * </ul> * */ public class LCMLText { public LCMLText(Composite parent, boolean hScroll, boolean vScroll) { this.hScroll = hScroll; this.vScroll = vScroll; if (hScroll || vScroll) { int style = 0; if (hScroll) style |= SWT.H_SCROLL; if (vScroll) style |= SWT.V_SCROLL; scroll = new ScrolledComposite(parent, style); if (!hScroll) scroll.setExpandHorizontal(true); if (!vScroll) scroll.setExpandVertical(true); panel = new Panel(scroll); scroll.setContent(panel); } else panel = new Panel(parent); panel.setBackground(parent.getBackground()); // panel.addControlListener(new ControlListener() { // public void controlMoved(ControlEvent e) { // } // public void controlResized(ControlEvent e) { // if (resizing) return; // refreshPanel(); // } // }); } private ScrolledComposite scroll; private Composite panel; private boolean hScroll, vScroll; private Paragraph text; public Control getControl() { return scroll != null ? scroll : panel; } public void setText(String ml) { if (text != null) text.removeControls(); text = LCMLParser.parse(ml); refreshPanel(); } public void addLinkListener(String href, Runnable listener) { Link link = text.findLink(href); if (link != null) link.addLinkListener(listener); } public void addLinkListener(Listener<String> listener) { List<Link> links = text.findSections(Link.class, new GetAllFinder<Link>()); for (Link link : links) link.addLinkListener(new RunnableWithData<Pair<String,Listener<String>>>(new Pair<String,Listener<String>>(link.getHRef(), listener)) { public void run() { data().getValue2().fire(data().getValue1()); } }); } public void setLayoutData(Object o) { (scroll != null ? scroll : panel).setLayoutData(o); } // private boolean resizing = false; private void refreshPanel() { int width; if (scroll == null) width = panel.getSize().x; else { if (hScroll) width = -1; else width = scroll.getClientArea().width; } if (width == 0) return; if (text == null) return; Point size = text.refreshControls(panel, width); // resizing = true; if (!size.equals(panel.getSize())) { panel.setSize(size); } if (!vScroll && scroll != null) { // TODO resize scroll vertically ??? } // resizing = false; } private class Panel extends Composite { public Panel(Composite parent) { super(parent, SWT.NONE); setLayout(new Layout()); addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e) { scroll = null; panel = null; text = null; } }); } @Override public Point computeSize(int hint, int hint2, boolean changed) { if (text == null) return new Point(0,0); return text.refreshSize(panel, hint == SWT.DEFAULT ? -1 : hint, false); } private class Layout extends org.eclipse.swt.widgets.Layout { @Override protected Point computeSize(Composite composite, int hint, int hint2, boolean flushCache) { return Panel.this.computeSize(hint, hint2, flushCache); } @Override protected void layout(Composite composite, boolean flushCache) { refreshPanel(); } } } }
gpl-3.0
SuperMap-iDesktop/SuperMap-iDesktop-Cross
Controls/src/main/java/com/supermap/desktop/controls/GeometryPropertyBindWindow/IPropertyBindWindow.java
517
package com.supermap.desktop.controls.GeometryPropertyBindWindow; import com.supermap.desktop.Interface.IFormMap; import com.supermap.mapping.Layer; import com.supermap.ui.MapControl; public interface IPropertyBindWindow { void registEvents(); void removeEvents(); IBindWindow getBindWindow(); void setBindWindow(IBindWindow bindWindow, MapControl mapControl); IBindProperty getBindProperty(); void setBindProperty(IBindProperty bindProperty); void setFormMap(IFormMap formMap); }
gpl-3.0
b3dgs/lionengine
lionengine-core/src/test/java/com/b3dgs/lionengine/graphic/engine/SequenceFailMock.java
1569
/* * Copyright (C) 2013-2022 Byron 3D Games Studio (www.b3dgs.com) Pierre-Alexandre (contact@b3dgs.com) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.b3dgs.lionengine.graphic.engine; import com.b3dgs.lionengine.Context; import com.b3dgs.lionengine.LionEngineException; import com.b3dgs.lionengine.Resolution; import com.b3dgs.lionengine.graphic.Graphic; /** * Mock sequence. */ final class SequenceFailMock extends Sequence { /** * Constructor. * * @param context The context reference. */ SequenceFailMock(Context context) { super(context, new Resolution(320, 200, 60)); } @Override public void load() { // Mock } @Override public void update(double extrp) { throw new LionEngineException("expected failure"); } @Override public void render(Graphic g) { // Mock } }
gpl-3.0
FroMage/jax-doclets
doclets/src/main/java/com/lunatech/doclets/jax/jpa/model/Registry.java
1410
/* Copyright 2009-2011 Lunatech Research Copyright 2009-2011 Stéphane Épardaud This file is part of jax-doclets. jax-doclets 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 3 of the License, or (at your option) any later version. jax-doclets 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 jax-doclets. If not, see <http://www.gnu.org/licenses/>. */ package com.lunatech.doclets.jax.jpa.model; import java.util.Collection; import java.util.HashMap; import java.util.Map; public class Registry { private Map<String, JPAClass> jpaClasses = new HashMap<String, JPAClass>(); public void addJPAClass(JPAClass klass) { jpaClasses.put(klass.getQualifiedClassName(), klass); } public boolean isJPAClass(String className) { return jpaClasses.containsKey(className); } public JPAClass getJPAClass(String name) { return jpaClasses.get(name); } public Collection<JPAClass> getJPAClasses() { return jpaClasses.values(); } }
gpl-3.0
buschmais/jqa-commandline-tool
application/src/main/java/com/buschmais/jqassistant/commandline/Main.java
13327
package com.buschmais.jqassistant.commandline; import java.io.*; import java.net.URL; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.*; import com.buschmais.jqassistant.commandline.task.DefaultTaskFactoryImpl; import com.buschmais.jqassistant.core.plugin.api.PluginConfigurationReader; import com.buschmais.jqassistant.core.plugin.api.PluginRepository; import com.buschmais.jqassistant.core.plugin.impl.PluginConfigurationReaderImpl; import com.buschmais.jqassistant.core.plugin.impl.PluginRepositoryImpl; import org.apache.commons.cli.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The main class, i.e. the entry point for the CLI. * * @author jn4, Kontext E GmbH, 23.01.14 * @author Dirk Mahler */ public class Main { private static final Logger LOGGER = LoggerFactory.getLogger(Main.class); private static final String ENV_JQASSISTANT_HOME = "JQASSISTANT_HOME"; private static final String DIRECTORY_PLUGINS = "plugins"; private static final String OPTION_HELP = "-help"; private final TaskFactory taskFactory; /** * The main method. * * @param args * The command line arguments. * @throws IOException * If an error occurs. */ public static void main(String[] args) { try { DefaultTaskFactoryImpl taskFactory = new DefaultTaskFactoryImpl(); new Main(taskFactory).run(args); } catch (CliExecutionException e) { String message = getErrorMessage(e); LOGGER.error(message); System.exit(e.getExitCode()); } } /** * Constructor. * * @param taskFactory * The task factory to use. */ public Main(TaskFactory taskFactory) { this.taskFactory = taskFactory; } /** * Run tasks according to the given arguments. * * @param args * The arguments. * @throws CliExecutionException * If execution fails. */ public void run(String[] args) throws CliExecutionException { Options options = gatherOptions(taskFactory); CommandLine commandLine = getCommandLine(args, options); interpretCommandLine(commandLine, options, taskFactory); } /** * Extract an error message from the given exception and its causes. * * @param e * The exception. * @return The error message. */ private static String getErrorMessage(CliExecutionException e) { StringBuffer messageBuilder = new StringBuffer(); Throwable current = e; do { messageBuilder.append("-> "); messageBuilder.append(current.getMessage()); current = current.getCause(); } while (current != null); return messageBuilder.toString(); } /** * Initialize the plugin repository. * * @return The repository. * @throws CliExecutionException * If initialization fails. */ private PluginRepository getPluginRepository() throws CliExecutionException { PluginConfigurationReader pluginConfigurationReader = new PluginConfigurationReaderImpl(createPluginClassLoader()); return new PluginRepositoryImpl(pluginConfigurationReader); } /** * Gather all options which are supported by the task (i.e. including standard and specific options). * * @return The options. */ private Options gatherOptions(TaskFactory taskFactory) { final Options options = new Options(); gatherTasksOptions(taskFactory, options); gatherStandardOptions(options); return options; } /** * Gathers the standard options shared by all tasks. * * @param options * The standard options. */ @SuppressWarnings("static-access") private void gatherStandardOptions(final Options options) { options.addOption(OptionBuilder.withArgName("p").withDescription( "Path to property file; default is jqassistant.properties in the class path").withLongOpt("properties").hasArg().create("p")); options.addOption(new Option("help", "print this message")); } /** * Gathers the task specific options for all tasks. * * @param options * The task specific options. */ private void gatherTasksOptions(TaskFactory taskFactory, Options options) { for (Task task : taskFactory.getTasks()) { for (Option option : task.getOptions()) { options.addOption(option); } } } /** * Returns a string containing the names of all supported tasks. * * @return The names of all supported tasks. */ private String gatherTaskNames(TaskFactory taskFactory) { final StringBuilder builder = new StringBuilder(); for (String taskName : taskFactory.getTaskNames()) { builder.append("'").append(taskName).append("' "); } return builder.toString().trim(); } /** * Parse the command line and execute the requested task. * * @param commandLine * The command line. * @param options * The known options. * @throws CliExecutionException * If an error occurs. */ private void interpretCommandLine(CommandLine commandLine, Options options, TaskFactory taskFactory) throws CliExecutionException { if(commandLine.hasOption(OPTION_HELP)) { printUsage(options, null); System.exit(1); } List<String> taskNames = commandLine.getArgList(); if (taskNames.isEmpty()) { printUsage(options, "A task must be specified, i.e. one of " + gatherTaskNames(taskFactory)); System.exit(1); } List<Task> tasks = new ArrayList<>(); for (String taskName : taskNames) { Task task = taskFactory.fromName(taskName); if (task == null) { printUsage(options, "Unknown task " + taskName); } tasks.add(task); } Map<String, Object> properties = readProperties(commandLine); PluginRepository pluginRepository = getPluginRepository(); executeTasks(tasks, options, commandLine, pluginRepository, properties); } private void executeTasks(List<Task> tasks, Options options, CommandLine commandLine, PluginRepository pluginRepository, Map<String, Object> properties) throws CliExecutionException { try { pluginRepository.initialize(); for (Task task : tasks) { executeTask(task, options, commandLine, pluginRepository, properties); } } finally { pluginRepository.destroy(); } } /** * Parse the command line * * @param args * The arguments. * @param options * The known options. * @return The command line. */ private CommandLine getCommandLine(String[] args, Options options) { final CommandLineParser parser = new BasicParser(); CommandLine commandLine = null; try { commandLine = parser.parse(options, args); } catch (ParseException e) { printUsage(options, e.getMessage()); System.exit(1); } return commandLine; } /** * Executes a task. * * @param task * The task. * @param option * The option. * @param commandLine * The command line. * @param properties * The plugin properties * @throws IOException */ private void executeTask(Task task, Options option, CommandLine commandLine, PluginRepository pluginRepository, Map<String, Object> properties) throws CliExecutionException { try { task.withStandardOptions(commandLine); task.withOptions(commandLine); } catch (CliConfigurationException e) { printUsage(option, e.getMessage()); System.exit(1); } task.initialize(pluginRepository, properties); task.run(); } /** * Read the plugin properties file if specified on the command line or if it exists on the class path. * * @param commandLine * The command line. * @return The plugin properties. * @throws CliConfigurationException * If an error occurs. */ private Map<String, Object> readProperties(CommandLine commandLine) throws CliConfigurationException { final Properties properties = new Properties(); InputStream propertiesStream; if (commandLine.hasOption("p")) { File propertyFile = new File(commandLine.getOptionValue("p")); if (!propertyFile.exists()) { throw new CliConfigurationException("Property file given by command line does not exist: " + propertyFile.getAbsolutePath()); } try { propertiesStream = new FileInputStream(propertyFile); } catch (FileNotFoundException e) { throw new CliConfigurationException("Cannot open property file.", e); } } else { propertiesStream = Main.class.getResourceAsStream("/jqassistant.properties"); } Map<String, Object> result = new HashMap<>(); if (propertiesStream != null) { try { properties.load(propertiesStream); } catch (IOException e) { throw new CliConfigurationException("Cannot load properties from file.", e); } for (String name : properties.stringPropertyNames()) { result.put(name, properties.getProperty(name)); } } return result; } /** * Print usage information. * * @param options * The known options. * @param errorMessage * The error message to append. */ private void printUsage(final Options options, final String errorMessage) { if(errorMessage != null) { System.out.println("Error: " + errorMessage); } final HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(120); formatter.printHelp(Main.class.getCanonicalName() + " <task> [options]", options); System.out.println("Tasks are: " + gatherTaskNames(taskFactory)); System.out.println("Example: " + Main.class.getCanonicalName() + " scan -f java:classpath::target/classes java:classpath::target/test-classes"); } /** * Determine the JQASSISTANT_HOME directory. * * @return The directory or `null`. */ private File getHomeDirectory() { String dirName = System.getenv(ENV_JQASSISTANT_HOME); if (dirName != null) { File dir = new File(dirName); if (dir.exists()) { LOGGER.debug("Using JQASSISTANT_HOME '" + dir.getAbsolutePath() + "'."); return dir; } else { LOGGER.warn("JQASSISTANT_HOME '" + dir.getAbsolutePath() + "' points to a non-existing directory."); return null; } } LOGGER.warn("JQASSISTANT_HOME is not set."); return null; } /** * Create the class loader to be used for detecting and loading plugins. * * @return The plugin class loader. * @throws com.buschmais.jqassistant.commandline.CliExecutionException * If the plugins cannot be loaded. */ private ClassLoader createPluginClassLoader() throws CliExecutionException { ClassLoader parentClassLoader = Task.class.getClassLoader(); File homeDirectory = getHomeDirectory(); if (homeDirectory != null) { File pluginDirectory = new File(homeDirectory, DIRECTORY_PLUGINS); if (pluginDirectory.exists()) { final List<URL> urls = new ArrayList<>(); final Path pluginDirectoryPath = pluginDirectory.toPath(); SimpleFileVisitor<Path> visitor = new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (file.toFile().getName().endsWith(".jar")) { urls.add(file.toFile().toURI().toURL()); } return FileVisitResult.CONTINUE; } }; try { Files.walkFileTree(pluginDirectoryPath, visitor); } catch (IOException e) { throw new CliExecutionException("Cannot read plugin directory.", e); } LOGGER.debug("Using plugin URLs: " + urls); return new com.buschmais.jqassistant.commandline.PluginClassLoader(urls, parentClassLoader); } } return parentClassLoader; } }
gpl-3.0
yescallop/QRCode
src/main/java/cn/yescallop/qrcode/Language.java
4508
package cn.yescallop.qrcode; import cn.nukkit.Server; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; public class Language { private static Map<String, String> lang; private static Map<String, String> fallbackLang; private Language() { //no instance } static void load(String langName) { if (lang != null) { return; } try { lang = loadLang(Language.class.getClassLoader().getResourceAsStream("lang/" + langName + ".ini")); } catch (NullPointerException e) { lang = new HashMap<>(); } fallbackLang = loadLang(Language.class.getClassLoader().getResourceAsStream("lang/eng.ini")); } public static String translate(String str, Object... params) { String baseText = get(str); baseText = parseTranslation(baseText != null ? baseText : str); for (int i = 0; i < params.length; i++) { baseText = baseText.replace("{%" + i + "}", parseTranslation(String.valueOf(params[i]))); } return baseText; } public static String translate(String str, String... params) { String baseText = get(str); baseText = parseTranslation(baseText != null ? baseText : str); for (int i = 0; i < params.length; i++) { baseText = baseText.replace("{%" + i + "}", parseTranslation(params[i])); } return baseText; } private static Map<String, String> loadLang(InputStream stream) { try { BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); Map<String, String> d = new HashMap<>(); String line; while ((line = reader.readLine()) != null) { line = line.trim(); if (line.isEmpty() || line.charAt(0) == '#') { continue; } int index = line.indexOf('='); if (index <= 0 || index == line.length() - 1) continue; d.put(line.substring(0, index), line.substring(index + 1, line.length())); } return d; } catch (IOException e) { Server.getInstance().getLogger().logException(e); return null; } } private static String internalGet(String id) { if (lang.containsKey(id)) { return lang.get(id); } else if (fallbackLang.containsKey(id)) { return fallbackLang.get(id); } return null; } private static String get(String id) { if (lang.containsKey(id)) { return lang.get(id); } else if (fallbackLang.containsKey(id)) { return fallbackLang.get(id); } return id; } private static String parseTranslation(String text) { StringBuilder newString = new StringBuilder(); StringBuilder replaceString = null; int len = text.length(); for (int i = 0; i < len; ++i) { char c = text.charAt(i); if (replaceString != null) { if ((c >= 0x30 && c <= 0x39) // 0-9 || (c >= 0x41 && c <= 0x5a) // A-Z || (c >= 0x61 && c <= 0x7a) || // a-z c == '.' || c == '-') { replaceString.append(c); } else { String t = internalGet(replaceString.substring(1)); if (t != null) { newString.append(t); } else { newString.append(replaceString); } replaceString = null; if (c == '%') { replaceString = new StringBuilder().append(c); } else { newString.append(c); } } } else if (c == '%') { replaceString = new StringBuilder().append(c); } else { newString.append(c); } } if (replaceString != null) { String t = internalGet(replaceString.substring(1)); if (t != null) { newString.append(t); } else { newString.append(replaceString); } } return newString.toString(); } }
gpl-3.0
hewie/moco
src/main/java/de/uni/bremen/monty/moco/ast/declaration/ClassDeclarationVariation.java
5197
package de.uni.bremen.monty.moco.ast.declaration; import de.uni.bremen.monty.moco.ast.Block; import de.uni.bremen.monty.moco.ast.ClassScope; import de.uni.bremen.monty.moco.ast.ResolvableIdentifier; import de.uni.bremen.monty.moco.ast.Scope; import de.uni.bremen.monty.moco.ast.statement.Statement; import java.util.ArrayList; import java.util.Collection; import java.util.List; public class ClassDeclarationVariation extends ClassDeclaration { private List<ClassDeclaration> concreteGenericTypes; public ClassDeclarationVariation(ClassDeclaration classDecl, ResolvableIdentifier identifier, List<ClassDeclaration> concreteGenericTypes) { super(classDecl.getPosition(), identifier, classDecl.getSuperClassIdentifiers(), new Block( classDecl.getBlock().getPosition()), classDecl.isAbstract(), classDecl.getAbstractGenericTypes()); this.concreteGenericTypes = concreteGenericTypes; setParentNode(classDecl.getParentNode()); ClassScope classScope = new ClassScope(classDecl.getScope().getParentScope()); classScope.addParentClassScope((ClassScope) classDecl.getScope()); setScope(classScope); classDecl.addVariation(this); Collection<ProcedureDeclaration> procedureDeclarations = mapFunctions(classDecl.getVirtualMethodTable()); getVirtualMethodTable().addAll(procedureDeclarations); mapBlock(classDecl.getBlock()); getBlock().setParentNode(this); ProcedureDeclaration defaultInitializer = mapFunction(classDecl.getDefaultInitializer()); setDefaultInitializer(defaultInitializer); for (Declaration procedureDeclaration : getBlock().getDeclarations()) { if (!(procedureDeclaration instanceof ProcedureDeclaration) || !((ProcedureDeclaration) procedureDeclaration).isDefaultInitializer()) { classScope.define(procedureDeclaration); } } classScope.define(defaultInitializer); } private void mapBlock(Block block) { for (Statement statement : block.getStatements()) { getBlock().addStatement(statement); } for (Declaration declaration : block.getDeclarations()) { if (declaration instanceof ProcedureDeclaration) { declaration = mapFunction((ProcedureDeclaration) declaration); } else if (declaration instanceof VariableDeclaration) { declaration = mapDeclaration((VariableDeclaration) declaration); } getBlock().addDeclaration(declaration); } } private Collection<ProcedureDeclaration> mapFunctions(List<ProcedureDeclaration> originalVirtualMethods) { ArrayList<ProcedureDeclaration> procedureDeclarations = new ArrayList<>(); for (ProcedureDeclaration procedureDeclaration : originalVirtualMethods) { procedureDeclarations.add(mapFunction(procedureDeclaration)); } return procedureDeclarations; } private ProcedureDeclaration mapFunction(ProcedureDeclaration procedureDeclaration) { ProcedureDeclaration funDecl; if (procedureDeclaration.isFunction()) { TypeDeclaration returnType = mapGenericType((procedureDeclaration).getReturnType()); funDecl = new ConcreteProcDecl(this, procedureDeclaration, returnType); } else { funDecl = new ConcreteProcDecl(this, procedureDeclaration); } funDecl.getParameter().addAll(mapParameter(procedureDeclaration.getParameter(), funDecl)); funDecl.setParentNode(this); funDecl.setScope(procedureDeclaration.getScope()); return funDecl; } private TypeDeclaration mapGenericType(TypeDeclaration type) { if (type instanceof AbstractGenericType) { return mapAbstractToConcrete((AbstractGenericType) type); } else { return type; } } public ClassDeclaration mapAbstractToConcrete(AbstractGenericType type) { int index = getAbstractGenericTypes().indexOf(type); if (index >= 0) { return concreteGenericTypes.get(index); } else { throw new RuntimeException("is this really an Error?"); } } public List<ClassDeclaration> getConcreteGenericTypes() { return concreteGenericTypes; } private List<VariableDeclaration> mapParameter(List<VariableDeclaration> parameter, ProcedureDeclaration decl) { ArrayList<VariableDeclaration> params = new ArrayList<>(); for (VariableDeclaration variableDeclaration : parameter) { VariableDeclaration var; TypeDeclaration abstractType = variableDeclaration.getType(); if (abstractType instanceof AbstractGenericType) { ClassDeclaration type = mapAbstractToConcrete((AbstractGenericType) abstractType); var = new VariableDeclaration(variableDeclaration.getPosition(), variableDeclaration.getIdentifier(), type, variableDeclaration.getDeclarationType()); var.setParentNode(decl); var.setScope(getScope()); } else { var = variableDeclaration; } params.add(var); } return params; } private Declaration mapDeclaration(VariableDeclaration declaration) { VariableDeclaration variableDeclaration = new VariableDeclaration(declaration.getPosition(), declaration.getIdentifier(), mapGenericType(declaration.getType()), declaration.getDeclarationType()); variableDeclaration.setParentNode(this); variableDeclaration.setScope(getScope()); variableDeclaration.setAttributeIndex(declaration.getAttributeIndex()); return variableDeclaration; } }
gpl-3.0
trade12/ToBeNamed
src/main/java/com/trade12/Archangel/addon/enchiridion/EnchiridionHandler.java
732
package com.trade12.Archangel.addon.enchiridion; import com.trade12.Archangel.Items.ItemLoader; import com.trade12.Archangel.lib.Ref; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.relauncher.Side; import enchiridion.api.GuideHandler; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.WeightedRandom; /** * Created by Kieran on 24/08/2014. */ public class EnchiridionHandler { public static Item guideBook = ItemLoader.guideBook; public static void load() { if (FMLCommonHandler.instance().getSide() == Side.CLIENT) { GuideHandler.registerBook(new ItemStack(guideBook), Ref.MOD_ID, "guideBook", 0xB3825F); } } }
gpl-3.0
TsMaster7/MultiprocessorModel
src/cachemodeler_multyprocessor/BlockAddress.java
515
package cachemodeler_multyprocessor; /** * структура для определения местоположения блока в кэше */ public class BlockAddress { public int moduleNumber; //номер модуля, где может храниться блок public int tag; //номер блока в модуле - тэг блока public BlockAddress(int moduleNumber, int tag) { this.moduleNumber = moduleNumber; this.tag = tag; } }
gpl-3.0
slashchenxiaojun/wall.e
src/main/java/org/hacker/module/common/DateKit.java
14481
package org.hacker.module.common; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; /** * DateHelper for DB operate and Simple Date tools * * @author Mr.J. * * @since 1.0 * **/ public class DateKit { /** * 这个函数将返回一个星期区间,根据参数d给出的时间为中轴 * 比如今天是2014-10-11,那么返回的就是2014-10-06和2014-10-12 * * @param d :一个日期对象 * @param pattern :日期的格式 * * @return String[] :<p>String[0]是StarDate</p><p>String[1]是EndDate</p> * **/ public static String[] getWeekStarDateAndEndDate(Date d, String pattern){ String[] results = new String[2]; SimpleDateFormat sdf = new SimpleDateFormat(pattern); Calendar c1 = Calendar.getInstance(); Calendar c2 = Calendar.getInstance(); c1.setTime(d); c2.setTime(d); int week = c1.get(Calendar.DAY_OF_WEEK)-1; if(week < 0) week = 1; if(week == 0){ c1.set(c1.get(Calendar.YEAR),c1.get(Calendar.MONTH),c1.get(Calendar.DATE)-6); results[0] = sdf.format(c1.getTime()); results[1] = sdf.format(d); }else{ c1.set(c1.get(Calendar.YEAR),c1.get(Calendar.MONTH),(c1.get(Calendar.DATE)-(c1.get(Calendar.DAY_OF_WEEK)-1)+1)); results[0] = sdf.format(c1.getTime()); c2.set(c2.get(Calendar.YEAR),c2.get(Calendar.MONTH),c2.get(Calendar.DATE)+7-(c2.get(Calendar.DAY_OF_WEEK)-1)); results[1] = sdf.format(c2.getTime()); } return results; } public static String format(Date d, String pattern){ SimpleDateFormat sdf = new SimpleDateFormat(pattern); return sdf.format(d); } public static Date format(String dateStr, String pattern){ SimpleDateFormat sdf = new SimpleDateFormat(pattern); try { return sdf.parse(dateStr); } catch (ParseException e) { e.printStackTrace(); } return null; } /** * 该函数返回提前或者是推后的天数的日期的字符串 * 如今天是2014-10-13,number:2;b_or_l:before,则返回2014-10-11的Date对象 * <p>(当然日期的格式还需要自己调用格式的函数)</p> * * @param d :给定的Date对象 * @param number :提前或者是推后的天数 * @param b_or_l :参数如果是"before" 则返回的是提前的天数,否则"later"返回推后的天数 * @throws StringParamException * **/ public static Date getBeforeOrLaterDate(Date d,int number, String b_or_l) throws Exception{ Calendar c = Calendar.getInstance(); c.setTime(d); if(b_or_l.equals("before")){ c.set(c.get(Calendar.YEAR),c.get(Calendar.MONTH),c.get(Calendar.DATE)-number); }else if(b_or_l.equals("later")){ c.set(c.get(Calendar.YEAR),c.get(Calendar.MONTH),c.get(Calendar.DATE)+number); }else{ throw new Exception("b_or_l param异常,请检查你的参数是否正确--->\"before\" of \"later\""); } c.set(Calendar.HOUR_OF_DAY,0); c.set(Calendar.MINUTE,0); c.set(Calendar.SECOND,0); c.set(Calendar.MILLISECOND,0); return c.getTime(); } /** * 提前或者推后月份并且day都为1 * @param d * @param number * @param b_or_l * @return * @throws Exception */ public static Date getBeforeOrLaterMonth(Date d,int number, String b_or_l) throws Exception{ Calendar c = Calendar.getInstance(); c.setTime(d); if(b_or_l.equals("before")){ c.set(c.get(Calendar.YEAR),c.get(Calendar.MONTH) - number, 1); }else if(b_or_l.equals("later")){ c.set(c.get(Calendar.YEAR),c.get(Calendar.MONTH) + number, 1); }else{ throw new Exception("b_or_l param异常,请检查你的参数是否正确--->\"before\" of \"later\""); } c.set(Calendar.HOUR_OF_DAY,0); c.set(Calendar.MINUTE,0); c.set(Calendar.SECOND,0); c.set(Calendar.MILLISECOND,0); return c.getTime(); } /** * 这个函数将返回一个月区间,根据参数d给出的时间为中轴 * 比如今天是2014-10-11,那么返回的就是2014-10-01和2014-10-31 * * @param d :一个日期对象 * @param pattern :日期的格式 * * @return String[] :<p>String[0]是StarDate</p><p>String[1]是EndDate</p> * **/ public static String[] getMonthStarDateAndEndDate(Date d, String pattern){ String[] results = new String[2]; SimpleDateFormat sdf = new SimpleDateFormat(pattern); Calendar c1 = Calendar.getInstance(); Calendar c2 = Calendar.getInstance(); c1.setTime(d); c2.setTime(d); c1.set(c1.get(Calendar.YEAR),c1.get(Calendar.MONTH),1); results[0] = sdf.format(c1.getTime()); int last = getMonthLastDay(c2.get(Calendar.YEAR),c1.get(Calendar.MONTH) + 1); c2.set(c2.get(Calendar.YEAR),c2.get(Calendar.MONTH),last); results[1] = sdf.format(c2.getTime()); return results; } /** * 取得当月天数 * */ public static int getCurrentMonthLastDay() { Calendar a = Calendar.getInstance(); a.set(Calendar.DATE, 1);//把日期设置为当月第一天 a.roll(Calendar.DATE, -1);//日期回滚一天,也就是最后一天 int maxDate = a.get(Calendar.DATE); return maxDate; } /** * 得到指定月的天数 * */ public static int getMonthLastDay(int year, int month) { Calendar a = Calendar.getInstance(); a.set(Calendar.YEAR, year); a.set(Calendar.MONTH, month - 1); a.set(Calendar.DATE, 1);//把日期设置为当月第一天 a.roll(Calendar.DATE, -1);//日期回滚一天,也就是最后一天 int maxDate = a.get(Calendar.DATE); return maxDate; } /** * 获取某年第一天日期 * @param year 年份 * * @return Date */ public static Date getYearFirstDay(int year){ Calendar calendar = Calendar.getInstance(); calendar.clear(); calendar.set(Calendar.YEAR, year); Date currYearFirst = calendar.getTime(); return currYearFirst; } /** * 获取当年的第一天 * @return */ public static Date getCurrentYearFirstDay(){ Calendar calendar = Calendar.getInstance(); return getYearFirstDay(calendar.get(Calendar.YEAR)); } /** * 获取当年的最后一天(最后的时刻23:59:59) * @return */ public static Date getCurrentYearLastDay(){ Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.MONTH, calendar.getActualMaximum(Calendar.MONTH)); calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH)); calendar.set(Calendar.HOUR_OF_DAY,23); calendar.set(Calendar.SECOND,59); calendar.set(Calendar.MINUTE,59); calendar.set(Calendar.MILLISECOND,0); return calendar.getTime(); } /** * 获取当月的第一天(最开始的时刻00:00:00) * @return */ public static Date getCurrentMonth(){ Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.DAY_OF_MONTH, 1); calendar.set(Calendar.HOUR_OF_DAY,0); calendar.set(Calendar.SECOND,0); calendar.set(Calendar.MINUTE,0); calendar.set(Calendar.MILLISECOND,0); return calendar.getTime(); } /** * 获取上个月的第一天(最开始的时刻00:00:00) * @return */ public static Date getLastMonth(){ Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.MONTH, -1); calendar.set(Calendar.DAY_OF_MONTH, 1); calendar.set(Calendar.HOUR_OF_DAY,0); calendar.set(Calendar.SECOND,0); calendar.set(Calendar.MINUTE,0); calendar.set(Calendar.MILLISECOND,0); return calendar.getTime(); } /** * 获取下个月的第一天(最开始的时刻00:00:00) * @return */ public static Date getNextMonth(){ Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.MONTH, 1); calendar.set(Calendar.DAY_OF_MONTH, 1); calendar.set(Calendar.HOUR_OF_DAY,0); calendar.set(Calendar.SECOND,0); calendar.set(Calendar.MINUTE,0); calendar.set(Calendar.MILLISECOND,0); return calendar.getTime(); } /** * 获取上个月的第一天(最开始的时刻00:00:00) * @return */ public static Date getLastMonthFirstDay(){ Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.MONTH, -1); calendar.set(Calendar.DAY_OF_MONTH, 1); calendar.set(Calendar.HOUR_OF_DAY,0); calendar.set(Calendar.SECOND,0); calendar.set(Calendar.MINUTE,0); calendar.set(Calendar.MILLISECOND,0); return calendar.getTime(); } /** * 获取上个月的最后第一天(最后的时刻23:59:59) * @return */ public static Date getLastMonthLastDay(){ Calendar calendar = Calendar.getInstance(); int month = calendar.get(Calendar.MONTH); calendar.set(Calendar.MONTH, month - 1); calendar.set(Calendar.DAY_OF_MONTH,calendar.getActualMaximum(Calendar.DAY_OF_MONTH)); calendar.set(Calendar.HOUR_OF_DAY,23); calendar.set(Calendar.SECOND,59); calendar.set(Calendar.MINUTE,59); calendar.set(Calendar.MILLISECOND,0); return calendar.getTime(); } /** * 获取昨天 * @return */ public static Date getYesterday(){ Calendar calendar = Calendar.getInstance(); int day = calendar.get(Calendar.DAY_OF_MONTH); calendar.set(Calendar.DAY_OF_MONTH, day - 1); calendar.set(Calendar.HOUR_OF_DAY,0); calendar.set(Calendar.SECOND,0); calendar.set(Calendar.MINUTE,0); calendar.set(Calendar.MILLISECOND,0); return calendar.getTime(); } /** * 获取明天 * @return */ public static Date getTomorrow(){ Calendar calendar = Calendar.getInstance(); int day = calendar.get(Calendar.DAY_OF_MONTH); calendar.set(Calendar.DAY_OF_MONTH, day + 1); calendar.set(Calendar.HOUR_OF_DAY,0); calendar.set(Calendar.SECOND,0); calendar.set(Calendar.MINUTE,0); calendar.set(Calendar.MILLISECOND,0); return calendar.getTime(); } /** * 获取当年的数值 * @return */ public static int getYear(){ Calendar calendar = Calendar.getInstance(); return calendar.get(Calendar.YEAR); } /** * 获取当年的数值 * @return */ public static int getYear(Date date){ Calendar calendar = Calendar.getInstance(); calendar.setTime(date); return calendar.get(Calendar.YEAR); } /** * 获取当月的数值 * @return */ public static int getMonth(){ Calendar calendar = Calendar.getInstance(); return calendar.get(Calendar.MONTH) + 1; } /** * 获取当月的数值 * @return */ public static int getDayOfMonth(Date date){ Calendar calendar = Calendar.getInstance(); calendar.setTime(date); return calendar.get(Calendar.DAY_OF_MONTH) + 1; } /** * 获取当年的数值 * @return */ public static int getMonthOfYear(Date date){ Calendar calendar = Calendar.getInstance(); calendar.setTime(date); return calendar.get(Calendar.MONTH) + 1; } /** * 返回2个日期相差多少个月 * * @param start_date * @param end_date * @return */ public static int subtractAndReturnMonth(Date start_date, Date end_date) { if(start_date.getTime() - end_date.getTime() > 0) throw new IllegalArgumentException("Oop! start_date > end_date"); Calendar calendar = Calendar.getInstance(); calendar.setTime(start_date); int s_year = calendar.get(Calendar.YEAR); int s_month = calendar.get(Calendar.MONTH) + 1; calendar.setTime(end_date); int e_year = calendar.get(Calendar.YEAR); int e_month = calendar.get(Calendar.MONTH) + 1; int subtract_year = e_year - s_year; // 同一年的情况下 if(subtract_year == 0) { // 同一年的情况不会出现e_month < s_month return e_month - s_month; // 不同年的情况下 }else { // 月份有小于大于等于3种情况 int subtract_month = e_month - s_month; if(subtract_month == 0) return subtract_year * 12; else if(subtract_month < 0) return subtract_year * 12 - Math.abs(subtract_month); else return subtract_year * 12 + Math.abs(subtract_month); } } /** * 返回2个日期相差多少天 * 格式必须为yyyy-MM-dd * * @param start_date * @param end_date * @return */ public static int subtractAndReturnDay(Date start_date, Date end_date) { long subtract = end_date.getTime() - start_date.getTime(); if(subtract < 0) throw new IllegalArgumentException("Oop! start_date > end_date"); long result = subtract / (24 * 60 * 60 * 1000); return Integer.parseInt(result + ""); } /** * 获取到date月份的第一天 * example: * assert getMonthFirstDay("2016-09-21") == "2016-09-01" * @param date * @return */ public static String getMonthFirstDay(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.set(Calendar.DAY_OF_MONTH, 1); return format(calendar.getTime(), "yyyy-MM-dd"); } /** * 获取到date月份的第一天 * example: * assert getMonthFirstDay("2016-09-21") == "2016-09-01" * @param date * @return */ public static String getMonthFirstDay(String date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(format(date, "yyyy-MM-dd")); calendar.set(Calendar.DAY_OF_MONTH, 1); return format(calendar.getTime(), "yyyy-MM-dd"); } /** * 获取到date月份的最后一天 * example: * assert getMonthFirstDay("2016-09-21") == "2016-09-30" * @param date * @return */ public static String getMonthLastDay(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH)); return format(calendar.getTime(), "yyyy-MM-dd"); } }
gpl-3.0
gamegineer/dev
main/table/org.gamegineer.table.core/src/org/gamegineer/table/core/ContainerListener.java
2630
/* * ContainerListener.java * Copyright 2008-2015 Gamegineer contributors and others. * All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Created on Mar 29, 2012 at 8:48:39 PM. */ package org.gamegineer.table.core; import net.jcip.annotations.Immutable; /** * Default implementation of {@link IContainerListener}. * * <p> * All methods of this class do nothing. * </p> */ @Immutable public class ContainerListener implements IContainerListener { // ====================================================================== // Constructors // ====================================================================== /** * Initializes a new instance of the {@code ContainerListener} class. */ public ContainerListener() { } // ====================================================================== // Methods // ====================================================================== /** * This implementation does nothing. * * @see org.gamegineer.table.core.IContainerListener#componentAdded(org.gamegineer.table.core.ContainerContentChangedEvent) */ @Override public void componentAdded( final ContainerContentChangedEvent event ) { // do nothing } /** * This implementation does nothing. * * @see org.gamegineer.table.core.IContainerListener#componentRemoved(org.gamegineer.table.core.ContainerContentChangedEvent) */ @Override public void componentRemoved( final ContainerContentChangedEvent event ) { // do nothing } /** * This implementation does nothing. * * @see org.gamegineer.table.core.IContainerListener#containerLayoutChanged(org.gamegineer.table.core.ContainerEvent) */ @Override public void containerLayoutChanged( final ContainerEvent event ) { // do nothing } }
gpl-3.0
TMMOB-BMO/TOYS
Toys/JavaSource/tr/com/arf/toys/db/model/iletisim/Adres.java
12829
package tr.com.arf.toys.db.model.iletisim; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import tr.com.arf.framework.db.enumerated._common.EvetHayir; import tr.com.arf.framework.utility.tool.DateUtil; import tr.com.arf.framework.utility.tool.KeyUtil; import tr.com.arf.toys.db.enumerated.iletisim.AdresTipi; import tr.com.arf.toys.db.enumerated.iletisim.AdresTuru; import tr.com.arf.toys.db.model.base.ToysBaseEntity; import tr.com.arf.toys.db.model.kisi.Kisi; import tr.com.arf.toys.db.model.kisi.Kurum; import tr.com.arf.toys.db.model.system.Ilce; import tr.com.arf.toys.db.model.system.Sehir; import tr.com.arf.toys.db.model.system.Ulke; @Entity @Table(name = "ADRES") public class Adres extends ToysBaseEntity { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(updatable = false, unique = true, nullable = false, name = "RID") private Long rID; @ManyToOne @JoinColumn(name = "KISIREF") private Kisi kisiRef; @ManyToOne @JoinColumn(name = "KURUMREF") private Kurum kurumRef; @Enumerated(EnumType.ORDINAL) @Column(name = "VARSAYILAN") private EvetHayir varsayilan; @Column(name = "ADRESTURU") private AdresTuru adresturu; @Enumerated(EnumType.ORDINAL) @Column(name = "ADRESTIPI") private AdresTipi adrestipi; @Temporal(TemporalType.DATE) @Column(name = "KPSGUNCELLEMETARIHI") private Date kpsGuncellemeTarihi; @Column(name = "ACIKADRES") private String acikAdres; @Column(name = "ADRESNO") private String adresNo; @Column(name = "BINAADA") private String binaAda; @Column(name = "BINAPAFTA") private String binaPafta; @Column(name = "BINAPARSEL") private String binaParsel; @Temporal(TemporalType.DATE) @Column(name = "TASINMATARIHI") private Date tasinmaTarihi; @Temporal(TemporalType.DATE) @Column(name = "BEYANTARIHI") private Date beyanTarihi; @Temporal(TemporalType.DATE) @Column(name = "TESCILTARIHI") private Date tescilTarihi; @Column(name = "BINABLOKADI") private String binaBlokAdi; @Column(name = "BINAKODU") private String binaKodu; @Column(name = "BINASITEADI") private String binaSiteAdi; @Column(name = "CSBM") private String csbm; @Column(name = "CSBMKODU") private String csbmKodu; @Column(name = "DISKAPINO") private String disKapiNo; @Column(name = "ICKAPINO") private String icKapiNo; @ManyToOne @JoinColumn(name = "ULKEREF") private Ulke ulkeRef; @ManyToOne @JoinColumn(name = "SEHIRREF") private Sehir sehirRef; @ManyToOne @JoinColumn(name = "ILCEREF") private Ilce ilceRef; @Column(name = "MAHALLE") private String mahalle; @Column(name = "MAHALLEKODU") private String mahalleKodu; @Column(name = "KOY") private String koy; @Column(name = "KOYKOD") private String koykod; @Column(name = "BUCAK") private String bucak; @Column(name = "BUCAKKOD") private String bucakkod; @Column(name = "YABANCIULKE") private String yabanciulke; @Column(name = "YABANCISEHIR") private String yabancisehir; @Column(name = "YABANCIADRES") private String yabanciadres; public Adres() { super(); this.varsayilan = EvetHayir._HAYIR; } @Override public Long getRID() { return this.rID; } @Override public void setRID(Long rID) { this.rID = rID; } public Kisi getKisiRef() { return kisiRef; } public void setKisiRef(Kisi kisiRef) { this.kisiRef = kisiRef; } public Kurum getKurumRef() { return kurumRef; } public void setKurumRef(Kurum kurumRef) { this.kurumRef = kurumRef; } public AdresTuru getAdresturu() { return this.adresturu; } public void setAdresturu(AdresTuru adresturu) { this.adresturu = adresturu; } public EvetHayir getVarsayilan() { return varsayilan; } public void setVarsayilan(EvetHayir varsayilan) { this.varsayilan = varsayilan; } public AdresTipi getAdrestipi() { return adrestipi; } public void setAdrestipi(AdresTipi adrestipi) { this.adrestipi = adrestipi; } public Date getKpsGuncellemeTarihi() { return kpsGuncellemeTarihi; } public void setKpsGuncellemeTarihi(Date kpsGuncellemeTarihi) { this.kpsGuncellemeTarihi = kpsGuncellemeTarihi; } public String getAcikAdres() { return acikAdres; } public void setAcikAdres(String acikAdres) { this.acikAdres = acikAdres; } public String getAdresNo() { return adresNo; } public void setAdresNo(String adresNo) { this.adresNo = adresNo; } public String getBinaBlokAdi() { return binaBlokAdi; } public void setBinaBlokAdi(String binaBlokAdi) { this.binaBlokAdi = binaBlokAdi; } public String getBinaKodu() { return binaKodu; } public void setBinaKodu(String binaKodu) { this.binaKodu = binaKodu; } public String getBinaSiteAdi() { return binaSiteAdi; } public void setBinaSiteAdi(String binaSiteAdi) { this.binaSiteAdi = binaSiteAdi; } public String getCsbm() { return csbm; } public void setCsbm(String csbm) { this.csbm = csbm; } public String getCsbmKodu() { return csbmKodu; } public void setCsbmKodu(String csbmKodu) { this.csbmKodu = csbmKodu; } public String getDisKapiNo() { return disKapiNo; } public void setDisKapiNo(String disKapiNo) { this.disKapiNo = disKapiNo; } public String getIcKapiNo() { return icKapiNo; } public void setIcKapiNo(String icKapiNo) { this.icKapiNo = icKapiNo; } public Ulke getUlkeRef() { return ulkeRef; } public void setUlkeRef(Ulke ulkeRef) { this.ulkeRef = ulkeRef; } public Sehir getSehirRef() { return sehirRef; } public void setSehirRef(Sehir sehirRef) { this.sehirRef = sehirRef; } public Ilce getIlceRef() { return ilceRef; } public void setIlceRef(Ilce ilceRef) { this.ilceRef = ilceRef; } public String getMahalle() { return mahalle; } public void setMahalle(String mahalle) { this.mahalle = mahalle; } public String getMahalleKodu() { return mahalleKodu; } public void setMahalleKodu(String mahalleKodu) { this.mahalleKodu = mahalleKodu; } public String getBinaAda() { return binaAda; } public void setBinaAda(String binaAda) { this.binaAda = binaAda; } public String getBinaPafta() { return binaPafta; } public void setBinaPafta(String binaPafta) { this.binaPafta = binaPafta; } public String getBinaParsel() { return binaParsel; } public void setBinaParsel(String binaParsel) { this.binaParsel = binaParsel; } public Date getTasinmaTarihi() { return tasinmaTarihi; } public void setTasinmaTarihi(Date tasinmaTarihi) { this.tasinmaTarihi = tasinmaTarihi; } public Date getBeyanTarihi() { return beyanTarihi; } public void setBeyanTarihi(Date beyanTarihi) { this.beyanTarihi = beyanTarihi; } public Date getTescilTarihi() { return tescilTarihi; } public void setTescilTarihi(Date tescilTarihi) { this.tescilTarihi = tescilTarihi; } public String getKoy() { return koy; } public void setKoy(String koy) { this.koy = koy; } public String getKoykod() { return koykod; } public void setKoykod(String koykod) { this.koykod = koykod; } public String getBucak() { return bucak; } public void setBucak(String bucak) { this.bucak = bucak; } public String getBucakkod() { return bucakkod; } public void setBucakkod(String bucakkod) { this.bucakkod = bucakkod; } public String getYabanciulke() { return yabanciulke; } public void setYabanciulke(String yabanciulke) { this.yabanciulke = yabanciulke; } public String getYabancisehir() { return yabancisehir; } public void setYabancisehir(String yabancisehir) { this.yabancisehir = yabancisehir; } public String getYabanciadres() { return yabanciadres; } public void setYabanciadres(String yabanciadres) { this.yabanciadres = yabanciadres; } @Override public String toString() { return "tr.com.arf.toys.db.model.iletisim.Adres[id=" + this.getRID() + "]"; } @Override public String getUIString() { if (getAdrestipi()!=null){ return getAdrestipi().getLabel() + ""; } return ""; } @Override public void initValues(boolean defaultValues) { if (defaultValues) { // TODO Initialize with default values } else { this.rID = null; this.kisiRef = null; this.kurumRef = null; this.adresturu = AdresTuru._NULL; this.varsayilan = EvetHayir._HAYIR; this.adrestipi = AdresTipi._NULL; this.kpsGuncellemeTarihi = null; this.acikAdres = null; this.adresNo = null; this.binaBlokAdi = null; this.binaKodu = null; this.binaSiteAdi = null; this.csbm = null; this.csbmKodu = null; this.disKapiNo = null; this.icKapiNo = null; this.sehirRef = null; this.ilceRef = null; this.mahalle = null; this.mahalleKodu = null; this.tescilTarihi = null; this.beyanTarihi = null; this.tasinmaTarihi = null; this.binaAda = null; this.binaPafta = null; this.binaParsel = null; this.ulkeRef = null; this.bucakkod=null; this.bucak=null; this.koy=null; this.koykod=null; this.yabanciadres=null; this.yabancisehir=null; this.yabanciulke=null; } } @Override public String getValue() { StringBuilder value = new StringBuilder(""); if(getKisiRef() != null) { value.append(KeyUtil.getLabelValue("adres.kisiRef") + " : " + getKisiRef().getUIString() + "<br />"); } if(getKurumRef() != null) { value.append(KeyUtil.getLabelValue("adres.kurumRef") + " : " + getKurumRef().getUIString() + "<br />"); } if(getVarsayilan() != null) { value.append(KeyUtil.getLabelValue("adres.varsayilan") + " : " + getVarsayilan() + "<br />"); } if(getAdresturu() != null) { value.append(KeyUtil.getLabelValue("adres.adresturu") + " : " + getAdresturu().getLabel() + ""); } if(getAdrestipi() != null) { value.append(KeyUtil.getLabelValue("adres.adrestipi") + " : " + getAdrestipi().getLabel() + ""); } if(getKpsGuncellemeTarihi() != null) { value.append(KeyUtil.getLabelValue("adres.kpsGuncellemeTarihi") + " : " + DateUtil.dateToDMY(getKpsGuncellemeTarihi())); } if(getAcikAdres() != null) { value.append(KeyUtil.getLabelValue("adres.acikAdres") + " : " + getAcikAdres()); } if(getAdresNo() != null) { value.append(KeyUtil.getLabelValue("adres.adresNo") + " : " + getAdresNo()); } if(getBinaBlokAdi() != null) { value.append(KeyUtil.getLabelValue("adres.binaBlokAdi") + " : " + getBinaBlokAdi()); } if(getBinaKodu() != null) { value.append(KeyUtil.getLabelValue("adres.binaKodu") + " : " + getBinaKodu()); } if(getBinaSiteAdi() != null) { value.append(KeyUtil.getLabelValue("adres.binaSiteAdi") + " : " + getBinaSiteAdi()); } if(getCsbm() != null) { value.append(KeyUtil.getLabelValue("adres.csbm") + " : " + getCsbm()); } if(getCsbmKodu() != null) { value.append(KeyUtil.getLabelValue("adres.csbmKodu") + " : " + getCsbmKodu()); } if(getDisKapiNo() != null) { value.append(KeyUtil.getLabelValue("adres.disKapiNo") + " : " + getDisKapiNo()); } if(getIcKapiNo() != null) { value.append(KeyUtil.getLabelValue("adres.icKapiNo") + " : " + getIcKapiNo()); } if(getSehirRef() != null) { value.append(KeyUtil.getLabelValue("adres.sehirRef") + " : " + getSehirRef().getAd()); } if(getIlceRef() != null) { value.append(KeyUtil.getLabelValue("adres.ilceRef") + " : " + getIlceRef().getAd()); } if(getMahalle() != null) { value.append(KeyUtil.getLabelValue("adres.mahalle") + " : " + getMahalle()); } if(getMahalleKodu() != null) { value.append(KeyUtil.getLabelValue("adres.mahalleKodu") + " : " + getMahalleKodu()); } if(getBucak() != null) { value.append(KeyUtil.getLabelValue("adres.bucak") + " : " + getBucak()); } if(getBucakkod() != null) { value.append(KeyUtil.getLabelValue("adres.bucakkod") + " : " + getBucakkod()); } if(getKoy() != null) { value.append(KeyUtil.getLabelValue("adres.koy") + " : " + getKoy()); } if(getKoykod() != null) { value.append(KeyUtil.getLabelValue("adres.koykod") + " : " + getKoykod()); } if(getYabanciadres() != null) { value.append(KeyUtil.getLabelValue("adres.yabanciadres") + " : " + getYabanciadres()); } if(getYabancisehir() != null) { value.append(KeyUtil.getLabelValue("adres.yabancisehir") + " : " + getYabancisehir()); } if(getYabanciulke() != null) { value.append(KeyUtil.getLabelValue("adres.yabanciulke") + " : " + getYabanciulke()); } return value.toString(); } }
gpl-3.0
iceblow/beilaile
src/main/java/com/warehouse/service/AccessoryRationService.java
953
package com.warehouse.service; import com.warehouse.entity.AccessoryRation; import org.apache.ibatis.annotations.Param; import javax.servlet.http.HttpServletRequest; import java.util.List; import java.util.Map; /** * Created by admin on 2017/1/10. */ public interface AccessoryRationService { // 带条件查询总条数 int getAccessoryRationByPageCount(Map<String, Object> anyVal); // 带条件分页查询 List<AccessoryRation> findConditionAccessoryRationByPage(Map<String, Object> anyVal); // 修改获取数据根据id AccessoryRation getAccessoryRationById(@Param("id") Integer id); AccessoryRation rationPurchasing(Integer amId, HttpServletRequest request); AccessoryRation rejectRation(Integer amId, HttpServletRequest request); AccessoryRation rationPrepareComplete(Integer amId, HttpServletRequest request); AccessoryRation rationAlreadyIssue(Integer amId, HttpServletRequest request); }
gpl-3.0
zpxocivuby/freetong_mobile
ItafMobileApp/src/itaf/mobile/app/ui/UserDeliveryAddress.java
8077
package itaf.mobile.app.ui; import itaf.framework.base.dto.WsPageResult; import itaf.framework.merchant.dto.BzUserDeliveryAddressDto; import itaf.mobile.app.R; import itaf.mobile.app.bean.PopupWindowItem; import itaf.mobile.app.services.TaskService; import itaf.mobile.app.task.netreader.UserDeliveryAddressDeleteTask; import itaf.mobile.app.task.netreader.UserDeliveryAddressListTask; import itaf.mobile.app.third.pull.PullToRefreshBase; import itaf.mobile.app.third.pull.PullToRefreshBase.OnRefreshListener; import itaf.mobile.app.third.pull.PullToRefreshListView; import itaf.mobile.app.ui.adapter.UserDeliveryAddressAdapter; import itaf.mobile.app.ui.base.BaseUIActivity; import itaf.mobile.app.ui.base.UIRefresh; import itaf.mobile.app.ui.custom.PopCommon; import itaf.mobile.app.util.AlertDialogHelper; import itaf.mobile.app.util.OnClickListenerHelper; import itaf.mobile.app.util.ToastHelper; import itaf.mobile.core.app.AppApplication; import itaf.mobile.core.utils.StringHelper; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import android.app.Activity; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.text.format.DateUtils; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.Button; import android.widget.ListView; /** * 用户发货地址 * * * @author XINXIN * * @UpdateDate 2014年9月15日 */ public class UserDeliveryAddress extends BaseUIActivity implements UIRefresh { private static final int RC_REFRESH = 1; // 返回按钮 private Button btn_uda_back; // 保存按钮 private Button btn_uda_add; // 用户好友列表 private PullToRefreshListView plv_uda_content; private UserDeliveryAddressAdapter adapter; private List<BzUserDeliveryAddressDto> adapterContent = new ArrayList<BzUserDeliveryAddressDto>(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.user_delivery_address); initPageAttribute(); initListView(); addUserDeliveryAddressListTask(); } private void initPageAttribute() { btn_uda_back = (Button) this.findViewById(R.id.btn_uda_back); btn_uda_back.setOnClickListener(OnClickListenerHelper .finishActivity(UserDeliveryAddress.this)); btn_uda_add = (Button) this.findViewById(R.id.btn_uda_add); btn_uda_add.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); intent.setClass(UserDeliveryAddress.this, UserDeliveryAddressCreate.class); startActivityForResult(intent, RC_REFRESH); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == Activity.RESULT_OK) { if (requestCode == RC_REFRESH) { addUserDeliveryAddressListTask(); } } } private void initListView() { // ListView初始化 plv_uda_content = (PullToRefreshListView) findViewById(R.id.plv_uda_content); plv_uda_content.setShowIndicator(false);// 取消箭头 adapter = new UserDeliveryAddressAdapter(UserDeliveryAddress.this, adapterContent); plv_uda_content.setAdapter(adapter); plv_uda_content.setOnRefreshListener(new OnRefreshListener<ListView>() { @Override public void onRefresh(PullToRefreshBase<ListView> refreshView) { String label = DateUtils.formatDateTime( getApplicationContext(), System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL); // Update the LastUpdatedLabel refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label); addUserDeliveryAddressListTask(); } }); plv_uda_content.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { BzUserDeliveryAddressDto dto = adapterContent.get(position - 1); Intent intent = new Intent(); intent.putExtra( UserDeliveryAddressDetail.AP_BZ_USER_DELIVERY_ADDRESS_ID, dto.getId()); intent.setClass(UserDeliveryAddress.this, UserDeliveryAddressDetail.class); startActivity(intent); } }); plv_uda_content.getRefreshableView().setOnItemLongClickListener( new OnItemLongClickListener() { public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { BzUserDeliveryAddressDto dto = adapterContent .get(position - 1); final Long addressId = dto.getId(); showPopCommon(addressId); return false; } }); } private void showPopCommon(final Long addressId) { List<PopupWindowItem> popItems = new ArrayList<PopupWindowItem>(); popItems.add(new PopupWindowItem("修改", new OnClickListener() { public void onClick(View v) { PopCommon.dismiss(); Intent intent = new Intent(); intent.putExtra( UserDeliveryAddressEdit.AP_BZ_USER_DELIVERY_ADDRESS_ID, addressId); intent.setClass(UserDeliveryAddress.this, UserDeliveryAddressEdit.class); startActivityForResult(intent, RC_REFRESH); } })); popItems.add(new PopupWindowItem("删除", new OnClickListener() { public void onClick(View v) { PopCommon.dismiss(); AlertDialogHelper.showDialog(UserDeliveryAddress.this, "提醒", "确认要删除吗?", "确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { addUserDeliveryAddressDeleteTask(addressId); } }); } })); PopCommon.show(UserDeliveryAddress.this, popItems); } private void addUserDeliveryAddressDeleteTask(final Long addressId) { Map<String, Object> params = new HashMap<String, Object>(); params.put( UserDeliveryAddressDeleteTask.TP_BZ_USER_DELIVERY_ADDRESS_ID, addressId); TaskService.addTask(new UserDeliveryAddressDeleteTask( UserDeliveryAddress.this, params)); showProgressDialog(PD_LOADING); } private void addUserDeliveryAddressListTask() { Map<String, Object> map = new HashMap<String, Object>(); map.put(UserDeliveryAddressListTask.TP_BZ_MERCHANT_ID, AppApplication .getInstance().getSessionUser().getId()); TaskService.addTask(new UserDeliveryAddressListTask( UserDeliveryAddress.this, map)); showProgressDialog(PD_LOADING); } @SuppressWarnings("unchecked") @Override public void refresh(Object... args) { dismissProgressDialog(); int taskId = (Integer) args[0]; if (UserDeliveryAddressListTask.getTaskId() == taskId) { if (args[1] == null) { plv_uda_content.onRefreshComplete(); return; } WsPageResult<BzUserDeliveryAddressDto> result = (WsPageResult<BzUserDeliveryAddressDto>) args[1]; if (WsPageResult.STATUS_ERROR.equals(result.getStatus())) { if (StringHelper.isEmpty(result.getErrorMsg())) { ToastHelper.showToast(this, "加载异常"); } else { ToastHelper.showToast(this, result.getErrorMsg()); } plv_uda_content.onRefreshComplete(); return; } adapterContent.clear(); adapterContent.addAll(result.getContent()); adapter.notifyDataSetChanged(); plv_uda_content.getRefreshableView().setSelection(0); plv_uda_content.onRefreshComplete(); } else if (UserDeliveryAddressDeleteTask.getTaskId() == taskId) { if (args[1] == null) { return; } WsPageResult<BzUserDeliveryAddressDto> result = (WsPageResult<BzUserDeliveryAddressDto>) args[1]; if (WsPageResult.STATUS_ERROR.equals(result.getStatus())) { if (StringHelper.isEmpty(result.getErrorMsg())) { ToastHelper.showToast(UserDeliveryAddress.this, "删除失败"); } else { ToastHelper.showToast(UserDeliveryAddress.this, result.getErrorMsg()); } return; } ToastHelper.showToast(UserDeliveryAddress.this, "删除成功"); addUserDeliveryAddressListTask(); } } }
gpl-3.0
PangeaHIV/DSPS-HIV_PANGEA
Code/trees/TreePruner.java
3414
package trees; import java.util.*; /** * class to prune a transmission tree to only the sampled nodes * @author Samantha Lycett * @created 1 July 2013 * @version 1 July 2013 * @version 2 July 2013 * @author Emma Hodcroft * @version 1 Nov 2013 - Added params/functions to create Nexus files (based off the Newick functions). Call TransmissionTree.toNexus */ public class TreePruner { boolean pruned = false; TransmissionTree tt; String fullNewick = null; String prunedNewick = null; String binaryPrunedNewick = null; String fullNexus = null; String prunedNexus = null; String binaryPrunedNexus = null; public TreePruner(TransmissionTree tt) { this.tt = tt; } ////////////////////////////////////////////////////////////// public void prune() { if (!pruned) { // record full newick of unpruned tree fullNewick = tt.toNewick(); // remove the unsampled tips, note this changes the transmission tree forever tt.removeUnsampledTips(); prunedNewick = tt.toNewick(); // remove the one child nodes, note this changes the transmission tree forever tt.removeOneChildNodes(); // internals tt.removeOneChildNodes(); // connected to sampled binaryPrunedNewick = tt.toNewick(); pruned = true; } } /** * Emma Hodcroft - 1 Nov 2013 */ public void pruneNexus() { if (!pruned) { // record full nexus of unpruned tree fullNexus = tt.toNexus(); // remove the unsampled tips, note this changes the transmission tree forever tt.removeUnsampledTips(); prunedNexus = tt.toNexus(); // remove the one child nodes, note this changes the transmission tree forever tt.removeOneChildNodes(); // internals tt.removeOneChildNodes(); // connected to sampled binaryPrunedNexus = tt.toNexus(); pruned = true; } } /** * returns full unpruned newick string of the transmission tree * @return */ public String getFullNewick() { if (fullNewick == null) { prune(); } return fullNewick; } /** * returns newick with sampled tips only, but note that there are 1 child nodes (OK for FigTree not OK for R-ape). * @return */ public String getPrunedNewick() { if (prunedNewick == null) { prune(); } return prunedNewick; } /** * returns binary tree with sampled tips only. * @return */ public String getBinaryPrunedNewick() { if (binaryPrunedNewick == null) { prune(); } return binaryPrunedNewick; } /////////Nexus versions /** * returns full unpruned nexus string of the transmission tree * Emma Hodcroft - 1 Nov 2013 * @return */ public String getFullNexus() { if (fullNexus == null) { pruneNexus(); } return fullNexus; } /** * returns nexus with sampled tips only, but note that there are 1 child nodes (OK for FigTree not OK for R-ape). * Emma Hodcroft - 1 Nov 2013 * @return */ public String getPrunedNexus() { if (prunedNexus == null) { pruneNexus(); } return prunedNexus; } /** * returns binary nexus tree with sampled tips only. * Emma Hodcroft - 1 Nov 2013 * @return */ public String getBinaryPrunedNexus() { if (binaryPrunedNexus == null) { pruneNexus(); } return binaryPrunedNexus; } }
gpl-3.0
robworth/patientview
patientview-parent/radar/src/main/java/org/patientview/radar/service/alport/GeneticsManager.java
1234
/* * PatientView * * Copyright (c) Worth Solutions Limited 2004-2013 * * This file is part of PatientView. * * PatientView 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. * PatientView 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 PatientView in a file * titled COPYING. If not, see <http://www.gnu.org/licenses/>. * * @package PatientView * @link http://www.patientview.org * @author PatientView <info@patientview.org> * @copyright Copyright (c) 2004-2013, Worth Solutions Limited * @license http://www.gnu.org/licenses/gpl-3.0.html The GNU General Public License V3.0 */ package org.patientview.radar.service.alport; import org.patientview.radar.model.Genetics; public interface GeneticsManager { void save(Genetics genetics); Genetics get(Long radarNo); }
gpl-3.0
danielhuson/megan-ce
src/megan/dialogs/lrinspector/ReadLayoutPane.java
35309
/* * ReadLayoutPane.java Copyright (C) 2021. Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * 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 megan.dialogs.lrinspector; import javafx.beans.property.*; import javafx.collections.ListChangeListener; import javafx.event.EventHandler; import javafx.scene.Group; import javafx.scene.Node; import javafx.scene.control.*; import javafx.scene.effect.DropShadow; import javafx.scene.input.Clipboard; import javafx.scene.input.ClipboardContent; import javafx.scene.input.MouseEvent; import javafx.scene.layout.Pane; import javafx.scene.paint.Color; import javafx.scene.shape.Line; import javafx.scene.text.Font; import jloda.fx.control.AMultipleSelectionModel; import jloda.fx.util.FXSwingUtilities; import jloda.swing.util.BasicSwing; import jloda.util.Basic; import jloda.util.Pair; import jloda.util.ProgramProperties; import jloda.util.interval.Interval; import jloda.util.interval.IntervalTree; import megan.chart.ChartColorManager; import megan.classification.Classification; import megan.classification.ClassificationManager; import megan.data.IMatchBlock; import java.net.MalformedURLException; import java.net.URL; import java.util.*; /** * pane displaying all alignments to a read * Daniel Huson, Feb 2017 */ public class ReadLayoutPane extends Pane { static public final int DEFAULT_LABELED_HEIGHT = 110; private static final Color LIGHTGRAY_SEMITRANSPARENT = Color.color(0.827451f, 0.827451f, 0.827451f, 0.5); private static Font font = new Font("Courier", ProgramProperties.get("LongReadLabelFontSize", 10)); private static int arrowHeight = 10; private static final Object lock = new Object(); private final IntegerProperty preferredHeightUnlabeled = new SimpleIntegerProperty(30); private final IntegerProperty preferredHeightLabeled = new SimpleIntegerProperty(DEFAULT_LABELED_HEIGHT); private final IntervalTree<IMatchBlock> intervals; private final ArrayList<GeneArrow> geneArrows; private final String[] cNames; private final Set<String> classificationLabelsShowing = new HashSet<>(); private final Group[] geneLabels; private final Map<IMatchBlock, GeneArrow> match2GeneArrow = new HashMap<>(); private final ReadOnlyIntegerProperty maxReadLength; private final ReadOnlyDoubleProperty layoutWidth; private final AMultipleSelectionModel<IMatchBlock> matchSelection = new AMultipleSelectionModel<>(); private final ReadLayoutPaneSearcher readLayoutPaneSearcher; private boolean hasHidden = false; private final LongProperty previousSelectionTime = new SimpleLongProperty(0); /** * creates the visualization pane * * @param cNames * @param readLength * @param intervalTree * @param maxReadLength * @return */ public ReadLayoutPane(final String[] cNames, final int readLength, IntervalTree<IMatchBlock> intervalTree, final ReadOnlyIntegerProperty maxReadLength, final ReadOnlyDoubleProperty layoutWidth) { this.intervals = intervalTree; this.cNames = cNames; this.maxReadLength = maxReadLength; this.layoutWidth = layoutWidth; readLayoutPaneSearcher = new ReadLayoutPaneSearcher(null, this, matchSelection); geneArrows = new ArrayList<>(); geneLabels = new Group[cNames.length]; for (int i = 0; i < geneLabels.length; i++) { geneLabels[i] = new Group(); } preferredHeightUnlabeled.addListener((observable, oldValue, newValue) -> layoutLabels()); preferredHeightLabeled.addListener((observable, oldValue, newValue) -> layoutLabels()); setPrefWidth(readLength); setPrefHeight(30); final Line line = new Line(); line.setStartX(1); line.setStroke(Color.DARKGRAY); getChildren().add(line); final Label lengthLabel = new Label(String.format("%,d", readLength)); lengthLabel.setFont(new Font("Courier", 10)); lengthLabel.setTextFill(Color.DARKGRAY); getChildren().add(lengthLabel); final Set<Integer> starts = new HashSet<>(); final Map<Pair<Integer, Integer>, GeneArrow> coordinates2geneArrow = new HashMap<>(); for (Interval<IMatchBlock> interval : intervalTree) { final IMatchBlock matchBlock = interval.getData(); final GeneArrow geneArrow; final boolean forward; if (matchBlock.getText().contains("Strand = Plus") || matchBlock.getText().contains("Strand=Plus") || matchBlock.getText().contains("Frame = +") || matchBlock.getText().contains("Frame=+")) forward = true; else if (matchBlock.getText().contains("Strand = Minus") || matchBlock.getText().contains("Strand=Minus") || matchBlock.getText().contains("Frame = -") || matchBlock.getText().contains("Frame=-")) forward = false; else forward = (matchBlock.getAlignedQueryStart() < matchBlock.getAlignedQueryEnd()); final int alignedQueryStart; final int alignedQueryEnd; if (forward) { alignedQueryStart = Math.min(matchBlock.getAlignedQueryStart(), matchBlock.getAlignedQueryEnd()); alignedQueryEnd = Math.max(matchBlock.getAlignedQueryStart(), matchBlock.getAlignedQueryEnd()); } else { alignedQueryStart = Math.max(matchBlock.getAlignedQueryStart(), matchBlock.getAlignedQueryEnd()); alignedQueryEnd = Math.min(matchBlock.getAlignedQueryStart(), matchBlock.getAlignedQueryEnd()); } final Pair<Integer, Integer> coordinates = new Pair<>(alignedQueryStart, alignedQueryEnd); if (coordinates2geneArrow.containsKey(coordinates)) geneArrow = coordinates2geneArrow.get(coordinates); else { geneArrow = new GeneArrow(cNames, readLength, getArrowHeight(), 1, 30, coordinates.getFirst(), coordinates.getSecond(), starts); coordinates2geneArrow.put(coordinates, geneArrow); geneArrows.add(geneArrow); getChildren().add(geneArrow); } geneArrow.addMatchBlock(matchBlock); geneArrow.setFill(Color.TRANSPARENT); geneArrow.setStroke(Color.BLACK); geneArrow.setOnMousePressed(mousePressedHandler); geneArrow.setOnMouseClicked(mouseClickedHandler); geneArrow.setOnMouseReleased(mouseReleasedHandler); EventHandler<MouseEvent> mouseDraggedHandlerY = event -> { Node node = (Node) event.getSource(); node.setLayoutY(node.getLayoutY() + (event.getSceneY() - mouseDown[1])); mouseDown[1] = event.getSceneY(); }; geneArrow.setOnMouseDragged(mouseDraggedHandlerY); match2GeneArrow.put(matchBlock, geneArrow); } matchSelection.setItems(intervalTree.values()); widthProperty().addListener((observable, oldValue, newValue) -> { final double readWidth = (layoutWidth.get() - 60) / maxReadLength.get() * readLength; line.setEndX(readWidth); lengthLabel.setLayoutX(readWidth + 2); final Set<Integer> starts12 = new HashSet<>(); for (final GeneArrow geneArrow : geneArrows) { geneArrow.rescale(maxReadLength.get(), arrowHeight, layoutWidth.get() - 60, getHeight(), starts12); } layoutLabels(); }); heightProperty().addListener((observable, oldValue, newValue) -> { line.setStartY(0.5 * getHeight()); line.setEndY(0.5 * getHeight()); lengthLabel.setLayoutY(0.5 * (getHeight() - lengthLabel.getHeight())); final Set<Integer> starts1 = new HashSet<>(); for (final GeneArrow geneArrow : geneArrows) { geneArrow.rescale(maxReadLength.get(), arrowHeight, layoutWidth.get() - 60, getHeight(), starts1); } layoutLabels(); }); matchSelection.getSelectedItems().addListener((ListChangeListener<IMatchBlock>) c -> { while (c.next()) { for (IMatchBlock matchBlock : c.getAddedSubList()) { final GeneArrow geneArrow = match2GeneArrow.get(matchBlock); if (geneArrow != null) { geneArrow.setEffect(new DropShadow(5, Color.RED)); for (Node label : geneArrow.getLabels()) { label.setEffect(new DropShadow(5, Color.RED)); } } } for (IMatchBlock matchBlock : c.getRemoved()) { final GeneArrow geneArrow = match2GeneArrow.get(matchBlock); if (geneArrow != null) { geneArrow.setEffect(null); for (Node label : geneArrow.getLabels()) { label.setEffect(null); } } } } }); setOnMousePressed(mousePressedHandler); } public static void setFontSize(int size) { if (font.getSize() != size) { synchronized (lock) { font = new Font("Courier", size); ProgramProperties.put("LongReadLabelFontSize", size); } } } public static int getFontSize() { return (int) Math.round(font.getSize()); } private static int getArrowHeight() { return arrowHeight; } public static void setArrowHeight(int arrowHeight) { ReadLayoutPane.arrowHeight = arrowHeight; } public ArrayList<GeneArrow> getGeneArrows() { return geneArrows; } /** * show or hide the gene labels for the given classification * * @param selectedCNames * @param show */ private void showLabels(Collection<String> selectedCNames, boolean show) { if (show) { if (selectedCNames.size() > 0 && classificationLabelsShowing.size() == 0) { setPrefHeight(preferredHeightLabeled.get()); } classificationLabelsShowing.addAll(selectedCNames); } else { if (classificationLabelsShowing.size() == 0) return; // already nothing showing classificationLabelsShowing.removeAll(selectedCNames); if (classificationLabelsShowing.size() == 0) { getChildren().removeAll(geneLabels); setPrefHeight(preferredHeightUnlabeled.get()); return; } } for (int cid = 0; cid < cNames.length; cid++) { String cName = cNames[cid]; if (!classificationLabelsShowing.contains(cName)) { getChildren().remove(geneLabels[cid]); } else { if (!getChildren().contains(geneLabels[cid])) getChildren().add(geneLabels[cid]); } } } public boolean isLabelsShowing(String cName) { return classificationLabelsShowing.contains(cName); } /** * layout gene labels */ public void layoutLabels() { boolean labelsVisible = false; for (Group group : geneLabels) { if (getChildren().contains(group)) { labelsVisible = true; break; } } if (labelsVisible) { final int fontSize = (int) Math.round(font.getSize()); setPrefHeight(preferredHeightLabeled.get()); double centerMargin = (getPrefHeight() <= 110 ? 2 : 0.01 * getPrefHeight()); int numberOfTracksPerDirection = Math.max(2, (int) Math.round((0.5 * preferredHeightLabeled.get() - 1.2 * ReadLayoutPane.getArrowHeight() - centerMargin) / fontSize)); final double[] trackPos = new double[2 * numberOfTracksPerDirection]; trackPos[numberOfTracksPerDirection - 1] = 0.5 * getPrefHeight() - 1.2 * ReadLayoutPane.getArrowHeight() - fontSize - centerMargin; for (int i = numberOfTracksPerDirection - 2; i >= 0; i--) trackPos[i] = trackPos[i + 1] - fontSize; trackPos[numberOfTracksPerDirection] = 0.5 * getPrefHeight() + 1.2 * ReadLayoutPane.getArrowHeight() + centerMargin; for (int i = numberOfTracksPerDirection + 1; i < trackPos.length; i++) trackPos[i] = trackPos[i - 1] + fontSize; final IntervalTree<Label>[] intervalTrees = new IntervalTree[trackPos.length]; for (int i = 0; i < intervalTrees.length; i++) intervalTrees[i] = new IntervalTree<>(); final double xScaleFactor = layoutWidth.get() / maxReadLength.get(); final Map<String, ArrayList<Label>> text2OldLabels = new HashMap<>(); // recycle old labels... for (Group currentGeneLabels : geneLabels) { for (Node node : currentGeneLabels.getChildren()) { if (node instanceof Label) { final Label label = (Label) node; if (label.getFont().getSize() != ReadLayoutPane.font.getSize()) label.setFont(ReadLayoutPane.font); ArrayList<Label> labels = text2OldLabels.computeIfAbsent(label.getText(), k -> new ArrayList<>()); labels.add(label); } } currentGeneLabels.getChildren().clear(); } for (GeneArrow geneArrow : geneArrows) { geneArrow.getLabels().clear(); for (int c = 0; c < cNames.length; c++) { final Group currentGeneLabels = geneLabels[c]; if (getChildren().contains(currentGeneLabels)) { for (IMatchBlock matchBlock : geneArrow.getMatchBlocks()) { int classId = matchBlock.getId(cNames[c]); if (classId > 0) { final String fullLabel = getClassName(c, classId).replaceAll("\\s+", " "); final String abbreviatedLabel = Basic.abbreviateDotDotDot(fullLabel, 60); double anchorX = xScaleFactor * geneArrow.getMiddle(); int estimatedPreferredLabelWidth = (int) Math.round(0.6 * fontSize * abbreviatedLabel.length()); double labelStartPos = Math.max(1, anchorX - 0.5 * estimatedPreferredLabelWidth); final Label label = createLabel(abbreviatedLabel, fullLabel, text2OldLabels); /* // todo: this highlights hydrazine synthase for the MEGAN-LR paper if(label.getText().startsWith("hydrazine syn")) label.setFont(Font.font(label.getFont().getFamily(), FontWeight.BOLD,label.getFont().getSize())); */ final Interval<Label> interval = new Interval<>((int) Math.round(labelStartPos), (int) Math.round(labelStartPos + estimatedPreferredLabelWidth), label); if (!geneArrow.isReverse()) { for (int j = numberOfTracksPerDirection - 1; j >= 0; j--) { final Label labelToUse = processLabel(j, 0, labelStartPos, trackPos[j], interval, intervalTrees[j], currentGeneLabels); if (labelToUse != null) { // could be the one we provided or one already present if (labelToUse.getFont().getSize() != ReadLayoutPane.font.getSize()) labelToUse.setFont(ReadLayoutPane.font); geneArrow.getLabels().add(labelToUse); labelToUse.setUserData(extendByOne((IMatchBlock[]) labelToUse.getUserData(), matchBlock)); if (geneArrow.isVisible()) labelToUse.setVisible(true); break; } } } else { for (int j = numberOfTracksPerDirection; j < trackPos.length; j++) { final Label labelToUse = processLabel(j, trackPos.length - 1, labelStartPos, trackPos[j], interval, intervalTrees[j], currentGeneLabels); if (labelToUse != null) { if (labelToUse.getFont().getSize() != ReadLayoutPane.font.getSize()) labelToUse.setFont(ReadLayoutPane.font); geneArrow.getLabels().add(labelToUse); labelToUse.setUserData(extendByOne((IMatchBlock[]) labelToUse.getUserData(), matchBlock)); if (geneArrow.isVisible()) labelToUse.setVisible(true); break; } } } } } } } } } else setPrefHeight(preferredHeightUnlabeled.get()); } /** * grow the array of matches by one entry * * @param array * @param matchBlock * @return extended array */ private IMatchBlock[] extendByOne(IMatchBlock[] array, IMatchBlock matchBlock) { if (array == null) return new IMatchBlock[]{matchBlock}; else { final IMatchBlock[] result = new IMatchBlock[array.length + 1]; System.arraycopy(array, 0, result, 0, array.length); result[result.length - 1] = matchBlock; return result; } } /** * process a label * * @param j * @param lastJ * @param yPos * @param interval * @param intervalTree * @return true, if label used */ private static Label processLabel(int j, int lastJ, double xPos, double yPos, Interval<Label> interval, IntervalTree<Label> intervalTree, Group geneLabels) { final Collection<Interval<Label>> intervals = intervalTree.getIntervals(interval); if (intervalTree.getIntervals(interval).size() == 0 || j == lastJ) { final Label label = interval.getData(); geneLabels.getChildren().add(label); intervalTree.add(interval); label.setLayoutX(xPos); label.setLayoutY(yPos); label.setVisible(false); // will make this visible, if one of the associated gene arrows is visible return label; // found a place for this label... } else { for (Interval<Label> other : intervals) { if (other.getData().getText().equals(interval.getData().getText())) return other.getData(); // label already present } } return null; // can't place label in this row and haven't found it either } /** * color arrows by bit score * * @param colorManager * @param maxScore */ public void colorByBitScore(ChartColorManager colorManager, float maxScore) { setPrefHeight(preferredHeightUnlabeled.get()); showLabels(Arrays.asList(cNames), false); for (GeneArrow geneArrow : geneArrows) { geneArrow.setFill(FXSwingUtilities.getColorFX(colorManager.getHeatMapTable().getColor(Math.round(geneArrow.getBestBitScore()), Math.round(maxScore) + 1), 0.5)); } } /** * scolor arrows by normalized bit score * * @param colorManager * @param maxNormalizedScore */ public void colorByNormalizedBitScore(ChartColorManager colorManager, float maxNormalizedScore) { setPrefHeight(preferredHeightUnlabeled.get()); showLabels(Arrays.asList(cNames), false); for (GeneArrow geneArrow : geneArrows) { geneArrow.setFill(FXSwingUtilities.getColorFX(colorManager.getHeatMapTable().getColor(Math.round(1000 * geneArrow.getBestNormalizedScore()), Math.round(maxNormalizedScore) + 1), 0.5)); } } /** * color gene arrows by class * * @param colorManager * @param activeClassifications */ public void colorByClassification(ChartColorManager colorManager, Collection<String> activeClassifications, String keyClassification, int keyClassId, boolean colorByPosition) { if (/*activeClassifications.contains(keyClassification) && */ keyClassId > 0) { for (GeneArrow geneArrow : geneArrows) { final Classification classification = ClassificationManager.get(keyClassification, false); boolean hasClass = false; boolean colored = false; for (IMatchBlock matchBlock : geneArrow) { final int classId = matchBlock.getId(keyClassification); if (classId > 0) { hasClass = true; if (!classification.getIdMapper().getDisabledIds().contains(classId)) { final int colorClassId = (colorByPosition ? classification.getFullTree().getChildAbove(keyClassId, classId) : classId); if (colorClassId > 0) { final String className = classification.getName2IdMap().get(colorClassId); if (className != null) { final Color color = FXSwingUtilities.getColorFX(colorManager.getClassColor(className), 0.5); geneArrow.setFill(color); colored = true; break; } } } } } if (!colored) { geneArrow.setFill(hasClass ? LIGHTGRAY_SEMITRANSPARENT : Color.TRANSPARENT); } } } else // key classification not showing { for (GeneArrow geneArrow : geneArrows) { boolean hasClass = false; for (IMatchBlock matchBlock : geneArrow) { for (String cName : activeClassifications) { final int classId = matchBlock.getId(cName); if (classId > 0) { hasClass = true; break; } } } geneArrow.setFill(hasClass ? Color.LIGHTGRAY : Color.TRANSPARENT); } } showLabels(activeClassifications, true); layoutLabels(); } private final double[] mouseDown = {0, 0}; private final EventHandler<MouseEvent> mousePressedHandler = event -> { final Node node = (Node) event.getSource(); if (event.isPopupTrigger()) { if (node instanceof Label) { showLabelContextMenu((Label) node, event.getScreenX(), event.getScreenY()); event.consume(); } else if (node instanceof GeneArrow) { ((GeneArrow) node).showContextMenu(event.getScreenX(), event.getScreenY()); event.consume(); } } else { if (!event.isShiftDown()) matchSelection.clearSelection(); mouseDown[0] = event.getSceneX(); mouseDown[1] = event.getSceneY(); final ArrayList<IMatchBlock> matchBlocks = new ArrayList<>(); if (node.getUserData() instanceof IMatchBlock) { matchBlocks.add((IMatchBlock) node.getUserData()); } else if (node.getUserData() instanceof GeneArrow) { matchBlocks.addAll(((GeneArrow) node.getUserData()).getMatchBlocks()); } else if (node.getUserData() instanceof IMatchBlock[]) { matchBlocks.addAll(Arrays.asList((IMatchBlock[]) node.getUserData())); } else if (node instanceof GeneArrow) { matchBlocks.addAll(((GeneArrow) node).getMatchBlocks()); } if (matchBlocks.size() > 0) { for (IMatchBlock matchBlock : matchBlocks) { previousSelectionTimeProperty().set(System.currentTimeMillis()); // so that we don't scroll the table view matchSelection.select(matchBlock); } event.consume(); } } }; private final EventHandler<MouseEvent> mouseClickedHandler = event -> { final Node node = (Node) event.getSource(); if (node instanceof GeneArrow) { final GeneArrow geneArrow = (GeneArrow) node; System.out.println(geneArrow.toString()); } else if (node instanceof Label) { if (((Label) node).getTooltip() != null) System.out.println(((Label) node).getTooltip().getText()); else System.out.println(((Label) node).getText()); } }; private final EventHandler<MouseEvent> mouseReleasedHandler = event -> { final Node node = (Node) event.getSource(); if (event.isPopupTrigger()) { if (node instanceof Label) { showLabelContextMenu((Label) node, event.getScreenX(), event.getScreenY()); event.consume(); } else if (node instanceof GeneArrow) { ((GeneArrow) node).showContextMenu(event.getScreenX(), event.getScreenY()); event.consume(); } } }; private final EventHandler<MouseEvent> mouseDraggedHandler = event -> { Node node = (Node) event.getSource(); node.setLayoutX(node.getLayoutX() + (event.getSceneX() - mouseDown[0])); node.setLayoutY(node.getLayoutY() + (event.getSceneY() - mouseDown[1])); mouseDown[0] = event.getSceneX(); mouseDown[1] = event.getSceneY(); }; /** * shows the label context menu * * @param screenX * @param screenY */ private void showLabelContextMenu(final Label label, double screenX, double screenY) { final ContextMenu contextMenu = new ContextMenu(); final MenuItem selectAllSimilar = new MenuItem("Select Similar"); selectAllSimilar.setOnAction(event -> { for (Group group : getVisibleGroups()) { for (Node node : group.getChildren()) { if (node instanceof Label) { if (((Label) node).getText().equals(label.getText())) { if (node.getUserData() instanceof IMatchBlock[]) { for (IMatchBlock matchBlock : (IMatchBlock[]) node.getUserData()) { matchSelection.select(matchBlock); } } } } } } }); contextMenu.getItems().add(selectAllSimilar); final MenuItem copy = new MenuItem("Copy Label"); copy.setOnAction(event -> { final Clipboard clipboard = Clipboard.getSystemClipboard(); final ClipboardContent content = new ClipboardContent(); content.putString(label.getTooltip().getText()); clipboard.setContent(content); }); contextMenu.getItems().add(copy); contextMenu.getItems().add(new SeparatorMenuItem()); final MenuItem webSearch = new MenuItem("Web Search..."); webSearch.setOnAction(event -> { try { final String text; if (label.getTooltip() != null) text = label.getTooltip().getText(); else text = label.getText(); final String searchURL = ProgramProperties.get(ProgramProperties.SEARCH_URL, ProgramProperties.defaultSearchURL); final URL url = new URL(String.format(searchURL, text.trim().replaceAll("\\s+", "+"))); //System.err.println(url); BasicSwing.openWebPage(url); } catch (MalformedURLException e) { Basic.caught(e); } }); contextMenu.getItems().add(webSearch); contextMenu.show(this, screenX, screenY); } public List<Group> getVisibleGroups() { ArrayList<Group> list = new ArrayList<>(); for (Group group : geneLabels) { if (group != null && getChildren().contains(group)) list.add(group); } return list; } public ReadLayoutPaneSearcher getSearcher() { return readLayoutPaneSearcher; } public int getPreferredHeightUnlabeled() { return preferredHeightUnlabeled.get(); } public IntegerProperty preferredHeightUnlabeledProperty() { return preferredHeightUnlabeled; } public void setPreferredHeightUnlabeled(int preferredHeightUnlabeled) { this.preferredHeightUnlabeled.set(preferredHeightUnlabeled); } public int getPreferredHeightLabeled() { return preferredHeightLabeled.get(); } public IntegerProperty preferredHeightLabeledProperty() { return preferredHeightLabeled; } public void setPreferredHeightLabeled(int preferredHeightLabeled) { this.preferredHeightLabeled.set(preferredHeightLabeled); } public IntervalTree<IMatchBlock> getIntervals() { return intervals; } public String[] getCNames() { return cNames; } /** * creates a label * * @param text * @return label */ private Label createLabel(String text, String fullText, Map<String, ArrayList<Label>> text2oldLabels) { if (text2oldLabels.size() > 0) // if there are some old labels, try to reuse one... { final ArrayList<Label> labels = text2oldLabels.get(text); if (labels != null) { final Label label = labels.remove(0); label.setVisible(true); if (labels.size() == 0) text2oldLabels.remove(text); return label; } } final Label label = new Label(); if (text != null) label.setText(text); label.setFont(font); label.setUserData(new IMatchBlock[0]); label.setTooltip(new Tooltip(Basic.abbreviateDotDotDot(fullText.replaceAll("\\s+", " "), 100))); label.setOnMousePressed(mousePressedHandler); label.setOnMouseClicked(mouseClickedHandler); label.setOnMouseReleased(mouseReleasedHandler); label.setOnMouseDragged(mouseDraggedHandler); return label; } /** * get a class name * * @param classificationId * @param classId * @return non-null class name */ private String getClassName(int classificationId, int classId) { String name = ClassificationManager.get(cNames[classificationId], true).getName2IdMap().get(classId); return (name != null ? name : String.format("%s: %d", (cNames[classificationId].equals("INTERPRO2GO") ? "IPR" : cNames[classificationId]), classId)); } /** * hide all selected items */ public void hideSelected() { for (IMatchBlock matchBlock : matchSelection.getSelectedItems()) { final GeneArrow geneArrow = match2GeneArrow.get(matchBlock); if (geneArrow != null) { geneArrow.setVisible(false); for (Label label : geneArrow.getLabels()) label.setVisible(false); hasHidden = true; } } } /** * show all items */ public void showAll() { hasHidden = false; for (IMatchBlock matchBlock : match2GeneArrow.keySet()) { final GeneArrow geneArrow = match2GeneArrow.get(matchBlock); if (geneArrow != null) { geneArrow.setVisible(true); for (Label label : geneArrow.getLabels()) label.setVisible(true); } } } /** * select all matches that are not an ancestor of the taxon to which this read is assigned * * @param classId */ public void selectAllCompatibleTaxa(boolean compatible, String classificationName, int classId) { if (classId > 0) { if (classificationName.equals(Classification.Taxonomy)) { final Classification classification = ClassificationManager.get(Classification.Taxonomy, true); for (IMatchBlock matchBlock : match2GeneArrow.keySet()) { int matchClassId = matchBlock.getId(classificationName); boolean isCompatibleWith = (matchClassId > 0 && (matchClassId == classId || classification.getFullTree().isDescendant(classId, matchClassId))); if (compatible == isCompatibleWith) matchSelection.select(matchBlock); else matchSelection.clearSelection(matchBlock); } } else { for (IMatchBlock matchBlock : match2GeneArrow.keySet()) { if (matchBlock.getId(classificationName) == classId) matchSelection.select(matchBlock); else matchSelection.clearSelection(matchBlock); } } } } public AMultipleSelectionModel<IMatchBlock> getMatchSelection() { return matchSelection; } public boolean hasHiddenAlignments() { return hasHidden; } public Set<String> getClassificationLabelsShowing() { return classificationLabelsShowing; } public GeneArrow getMatch2GeneArrow(IMatchBlock matchBlock) { return match2GeneArrow.get(matchBlock); } public LongProperty previousSelectionTimeProperty() { return previousSelectionTime; } }
gpl-3.0
schuylernathaniel/PixelDungeon2--edited
src/com/watabou/pixeldungeon/utils/SystemTime.java
861
/* * Copyright (C) 2012-2014 Oleg Dolya * * 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.watabou.pixeldungeon.utils; public class SystemTime { public static long now; public static void tick() { now = System.currentTimeMillis(); } }
gpl-3.0
Angelic47/Nukkit
src/main/java/cn/nukkit/entity/item/EntityExpBottle.java
2883
package cn.nukkit.entity.item; import cn.nukkit.Player; import cn.nukkit.entity.Entity; import cn.nukkit.entity.projectile.EntityProjectile; import cn.nukkit.level.format.FullChunk; import cn.nukkit.level.particle.EnchantParticle; import cn.nukkit.level.particle.Particle; import cn.nukkit.level.particle.SpellParticle; import cn.nukkit.math.NukkitRandom; import cn.nukkit.nbt.tag.CompoundTag; import cn.nukkit.network.protocol.AddEntityPacket; /** * Created on 2015/12/25 by xtypr. * Package cn.nukkit.entity in project Nukkit . */ public class EntityExpBottle extends EntityProjectile { public static final int NETWORK_ID = 68; @Override public int getNetworkId() { return NETWORK_ID; } @Override public float getWidth() { return 0.25f; } @Override public float getLength() { return 0.25f; } @Override public float getHeight() { return 0.25f; } @Override protected float getGravity() { return 0.1f; } @Override protected float getDrag() { return 0.01f; } public EntityExpBottle(FullChunk chunk, CompoundTag nbt) { this(chunk, nbt, null); } public EntityExpBottle(FullChunk chunk, CompoundTag nbt, Entity shootingEntity) { super(chunk, nbt, shootingEntity); } @Override public boolean onUpdate(int currentTick) { if (this.closed) { return false; } this.timings.startTiming(); int tickDiff = currentTick - this.lastUpdate; boolean hasUpdate = super.onUpdate(currentTick); if (this.age > 1200) { this.kill(); hasUpdate = true; } if (this.isCollided) { this.kill(); Particle particle1 = new EnchantParticle(this); this.getLevel().addParticle(particle1); Particle particle2 = new SpellParticle(this, 0x00385dc6); this.getLevel().addParticle(particle2); hasUpdate = true; NukkitRandom random = new NukkitRandom(); int add = 1; for (int ii = 1; ii <= random.nextRange(3, 11); ii += add) { getLevel().dropExpOrb(this, add); add = random.nextRange(1, 3); } } this.timings.stopTiming(); return hasUpdate; } @Override public void spawnTo(Player player) { AddEntityPacket pk = new AddEntityPacket(); pk.type = EntityExpBottle.NETWORK_ID; pk.eid = this.getId(); pk.x = (float) this.x; pk.y = (float) this.y; pk.z = (float) this.z; pk.speedX = (float) this.motionX; pk.speedY = (float) this.motionY; pk.speedZ = (float) this.motionZ; pk.metadata = this.dataProperties; player.dataPacket(pk); super.spawnTo(player); } }
gpl-3.0
Satantarkov/ocmanager
src/test/java/com/ocarballo/ocmanager/repository/JPARecipeElementDaoTests.java
1515
package com.ocarballo.ocmanager.repository; import java.util.List; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.ocarballo.ocmanager.domain.Recipe; import com.ocarballo.ocmanager.domain.RecipeElement; import com.ocarballo.ocmanager.repository.RecipeElementDao; public class JPARecipeElementDaoTests { private ApplicationContext context; private RecipeElementDao recipeElementDao; private RecipeDao recipeDao; @Before public void setUp() { context = new ClassPathXmlApplicationContext("classpath:test-context.xml"); recipeElementDao = (RecipeElementDao) context.getBean("recipeElementDao"); recipeDao = (RecipeDao) context.getBean("recipeDao"); } @Test public void testGetRecipeElementsList() { List<RecipeElement> reList = recipeElementDao.getRecipeElementsList(); assertNotNull(reList); assertTrue("List of RecipeElements empty or less than zero.", reList.size() > 0); } @Test public void testfindRecipeElementsByRecipe() { List<RecipeElement> recipeElements; Recipe recipe = recipeDao.getRecipesList().get(0); recipeElements = recipeElementDao.findRecipeElementsByRecipe(recipe); System.out.println("Testing testfindRecipeElementsByRecipe..."); for (RecipeElement re : recipeElements) { System.out.println(re.getMaterial().getDescription() + ": " + re.getQuantity() + ";"); } } }
gpl-3.0
fracturedatlas/ATHENA
helpers/lock/src/main/java/org/fracturedatlas/athena/helper/lock/manager/AthenaLockManager.java
15571
/* ATHENA Project: Management Tools for the Cultural Sector Copyright (C) 2010, Fractured Atlas 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 org.fracturedatlas.athena.helper.lock.manager; import com.sun.jersey.api.NotFoundException; import java.io.InputStream; import java.text.ParseException; import java.util.Collection; import java.util.Date; import java.util.HashSet; import java.util.Properties; import java.util.Set; import java.util.UUID; import javax.servlet.http.HttpServletRequest; import org.fracturedatlas.athena.apa.ApaAdapter; import org.fracturedatlas.athena.apa.impl.jpa.PropField; import org.fracturedatlas.athena.apa.impl.jpa.TicketProp; import org.fracturedatlas.athena.client.PTicket; import org.fracturedatlas.athena.exception.AthenaException; import org.fracturedatlas.athena.helper.lock.exception.TicketsLockedException; import org.fracturedatlas.athena.helper.lock.model.AthenaLock; import org.fracturedatlas.athena.helper.lock.model.AthenaLockStatus; import org.fracturedatlas.athena.id.IdAdapter; import org.fracturedatlas.athena.search.AthenaSearch; import org.fracturedatlas.athena.search.AthenaSearchConstraint; import org.fracturedatlas.athena.search.Operator; import org.fracturedatlas.athena.util.date.DateUtil; import org.joda.time.DateTime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.ClassPathResource; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolderStrategy; import org.springframework.security.core.userdetails.User; import org.springframework.stereotype.Component; @Component public class AthenaLockManager { public static final String LOCK_TYPE = "ticket"; public static final String LOCK_ID = "lockId"; public static final String LOCKED_BY_API_KEY = "lockedByApiKey"; public static final String LOCKED_BY_IP = "lockedByIp"; public static final String LOCK_EXPIRES = "lockExpires"; public static final String LOCK_TIMES = "lockTimes"; public static final String NO_USER = "[NONE]"; @Autowired ApaAdapter apa; @Autowired SecurityContextHolderStrategy contextHolderStrategy; static Properties props; Logger logger = LoggerFactory.getLogger(this.getClass().getName()); static { props = new Properties(); ClassPathResource cpr = new ClassPathResource("athena-lock.properties"); try{ InputStream in = cpr.getInputStream(); props.load(in); in.close(); } catch (Exception e) { Logger log2 = LoggerFactory.getLogger(AthenaLockManager.class); log2.error(e.getMessage(),e); } } public AthenaLock getLock(String id, HttpServletRequest request) throws Exception { AthenaSearch apaSearch = new AthenaSearch .Builder(new AthenaSearchConstraint(AthenaLockManager.LOCK_ID, Operator.EQUALS, id)) .and(new AthenaSearchConstraint(AthenaLockManager.LOCKED_BY_API_KEY, Operator.EQUALS, getCurrentUsername())) .type("ticket") .build(); Collection<PTicket> tickets = apa.findTickets(apaSearch); if(tickets == null || tickets.size() == 0) { throw new NotFoundException("Transaction with id [" + id + "] was not found"); } PTicket firstTicket = tickets.iterator().next(); Set<String> ids = getTicketIds(tickets); AthenaLock tran = new AthenaLock(); tran.setId(id); tran.setLockedByApi(firstTicket.get(AthenaLockManager.LOCKED_BY_API_KEY)); tran.setLockedByIp(firstTicket.get(AthenaLockManager.LOCKED_BY_IP)); tran.setLockExpires(DateUtil.parseDate(firstTicket.get(AthenaLockManager.LOCK_EXPIRES))); tran.setTickets(ids); return tran; } public AthenaLock createLock(HttpServletRequest request, AthenaLock tran) throws Exception { //Load all the tickets Set<PTicket> tickets = new HashSet<PTicket>(); Set<String> ticketIds = tran.getTickets(); for(String id : ticketIds) { PTicket t = apa.getRecord(LOCK_TYPE, id); if(t == null) { throw new TicketsLockedException("Invalid ticket involved with transaction"); } if(isInvolvedInActiveTransaction(t)) { throw new TicketsLockedException("Unable to obtain lock on tickets"); } } tran.setId(UUID.randomUUID().toString()); tran.setLockedByApi(getCurrentUsername()); tran.setLockedByIp(request.getRemoteAddr()); tran.setStatus(AthenaLockStatus.OK); DateTime lockExpires = new DateTime(new Date()); lockExpires = lockExpires.plusMinutes(Integer.parseInt(props.getProperty("athena.lock.lock_time_in_minutes"))); tran.setLockExpires(lockExpires.toDate()); lockTickets(ticketIds, tran); return tran; } private String getCurrentUsername() { Authentication authentication = contextHolderStrategy.getContext().getAuthentication(); if(authentication != null && authentication.getPrincipal() != null && User.class.isAssignableFrom(authentication.getPrincipal().getClass()) ) { User user = (User) authentication.getPrincipal(); return user.getUsername(); } return NO_USER; } private void lockTickets(Set<String> ticketIds, AthenaLock tran) throws Exception { PropField lockId = apa.getPropField(AthenaLockManager.LOCK_ID); PropField lockedByIpField = apa.getPropField(AthenaLockManager.LOCKED_BY_IP); PropField lockedByApiKeyField = apa.getPropField(AthenaLockManager.LOCKED_BY_API_KEY); PropField lockExpiresField = apa.getPropField(AthenaLockManager.LOCK_EXPIRES); PropField lockTimesField = apa.getPropField(AthenaLockManager.LOCK_TIMES); for(String id : ticketIds) { PTicket t = apa.getRecord(LOCK_TYPE, id); //TODO: This might not work t.put(lockId.getName(), tran.getId()); t.put(lockedByApiKeyField.getName(), tran.getLockedByApi()); t.put(lockedByIpField.getName(), tran.getLockedByIp()); t.put(lockTimesField.getName(), "1"); t.put(lockExpiresField.getName(), DateUtil.formatDate(tran.getLockExpires())); apa.saveRecord(t); } } public AthenaLock updateLock(String id, HttpServletRequest request, AthenaLock tran) throws Exception { //Load all the tickets Set<String> ticketIds = new HashSet<String>(); Set<PTicket> ticketsInTransaction = getTicketsInTransaction(tran.getId()); //This looks a little stupid: loading the tickets from apa even though the client is sending us //an array of tickets. We do this though to prevent the client from adding in extra tickets //beyond those that were locked with the initial lock for(PTicket ticket : ticketsInTransaction) { ticketIds.add(ticket.getId().toString()); } PropField lockTimesField = apa.getPropField(AthenaLockManager.LOCK_TIMES); AthenaLock transactionFromTickets = null; for(String ticketId : ticketIds) { PTicket t = apa.getRecord(LOCK_TYPE, ticketId); if(t == null) { throw new TicketsLockedException("Invalid ticket involved with transaction"); } Integer numTimesLocked = Integer.parseInt(t.get(lockTimesField.getName())); logger.debug("", numTimesLocked); logger.debug(props.getProperty("athena.transaction.number_of_renewals")); logger.debug("", isRenewing(tran)); if(numTimesLocked > Integer.parseInt(props.getProperty("athena.lock.number_of_renewals")) && isRenewing(tran)) { throw new AthenaException("Cannot lock tickets"); } transactionFromTickets = loadTransactionFromTicket(t); if(!isOwnerOfTransaction(request, transactionFromTickets)) { throw new AthenaException("Cannot process the transaction"); } } DateTime now = new DateTime(); DateTime expiresOn = now.plusMinutes(Integer.parseInt(props.getProperty("athena.lock.renewal_time_in_minutes"))); tran.setLockExpires(expiresOn.toDate()); tran.setTickets(ticketIds); if(isCompleting(tran)) { completeTicketPurchase(tran); } else if(isRenewing(tran)) { renewLockOnTickets(tran); } else { throw new AthenaException("Did not understand status of [" + tran.getStatus() + "]"); } tran.setStatus(AthenaLockStatus.OK); return tran; } private Boolean isRenewing(AthenaLock tran) { if(tran.getStatus() == null) { return false; } return tran.getStatus().equalsIgnoreCase(AthenaLockStatus.RENEW); } private Boolean isCompleting(AthenaLock tran) { if(tran.getStatus() == null) { return false; } return tran.getStatus().equalsIgnoreCase(AthenaLockStatus.COMPLETE); } private void completeTicketPurchase(AthenaLock tran) throws Exception { Set<String> ticketIds = tran.getTickets(); for(String ticketId : ticketIds) { PTicket t = apa.getRecord(LOCK_TYPE, ticketId); t.put("status", "sold"); apa.saveRecord(t); } } private void renewLockOnTickets(AthenaLock tran) throws Exception { Set<String> ticketIds = tran.getTickets(); for(String ticketId : ticketIds) { PTicket t = apa.getRecord(LOCK_TYPE, ticketId); t.put(AthenaLockManager.LOCK_EXPIRES, DateUtil.formatDate(tran.getLockExpires())); Integer times = Integer.parseInt(t.get(AthenaLockManager.LOCK_TIMES)); times++; t.put(AthenaLockManager.LOCK_TIMES, times.toString()); apa.saveRecord(t); } } /* * This method intentionally does not return NotFound for locks * because this would allow someone to brute force scan for locks and delete them * * TODO: Check for lock ownership before deleting */ public void deleteLock(String id, HttpServletRequest request) throws Exception { //get the tickets on the tran Set<PTicket> ticketsInTransaction = getTicketsInTransaction(id); logger.info("TICKETS IN THIS TRANSACTION: {}", ticketsInTransaction); if(ticketsInTransaction == null || ticketsInTransaction.size() == 0) { return; } PropField lockIdField = apa.getPropField(AthenaLockManager.LOCK_ID); PropField lockedByIpField = apa.getPropField(AthenaLockManager.LOCKED_BY_IP); PropField lockedByApiKeyField = apa.getPropField(AthenaLockManager.LOCKED_BY_API_KEY); PropField lockExpiresField = apa.getPropField(AthenaLockManager.LOCK_EXPIRES); PropField lockTimesField = apa.getPropField(AthenaLockManager.LOCK_TIMES); AthenaLock transactionFromTickets = loadTransactionFromTicket(ticketsInTransaction.iterator().next()); if(!isOwnerOfTransaction(request, transactionFromTickets)) { throw new AthenaException("Cannot delete the transaction"); } for(PTicket ticket : ticketsInTransaction) { TicketProp prop = apa.getTicketProp(AthenaLockManager.LOCK_ID, "ticket", ticket.getId()); apa.deleteTicketProp(prop); prop = apa.getTicketProp(AthenaLockManager.LOCKED_BY_IP, "ticket", ticket.getId()); apa.deleteTicketProp(prop); prop = apa.getTicketProp(AthenaLockManager.LOCKED_BY_API_KEY, "ticket", ticket.getId()); apa.deleteTicketProp(prop); prop = apa.getTicketProp(AthenaLockManager.LOCK_EXPIRES, "ticket", ticket.getId()); apa.deleteTicketProp(prop); PTicket t = apa.getRecord(LOCK_TYPE, ticket.getId()); t.put(AthenaLockManager.LOCK_TIMES, "0"); apa.saveRecord(t); } } private Set<PTicket> getTicketsInTransaction(String lockId) { AthenaSearch search = new AthenaSearch(); search.setType("ticket"); search.addConstraint(AthenaLockManager.LOCK_ID, Operator.EQUALS, lockId); Set<PTicket> ticketsInTransaction = apa.findTickets(search); return ticketsInTransaction; } private AthenaLock loadTransactionFromTicket(PTicket t) throws ParseException { logger.info("LOADING FROM TICKET: {}", t); AthenaLock tran = new AthenaLock(); tran.setId(t.get(AthenaLockManager.LOCK_ID)); tran.setLockedByApi(t.get(AthenaLockManager.LOCKED_BY_API_KEY)); tran.setLockedByIp(t.get(AthenaLockManager.LOCKED_BY_IP)); tran.setLockExpires(DateUtil.parseDate(t.get(AthenaLockManager.LOCK_EXPIRES))); logger.info("Loaded transaction: {}", tran); return tran; } private Boolean isOwnerOfTransaction(HttpServletRequest request, AthenaLock tran) { Boolean checkApiKey = Boolean.parseBoolean(props.getProperty("athena.lock.username_check_enabled")); if(!checkApiKey) { logger.info("username check is OFF"); return true; } String username = getCurrentUsername(); logger.info("Checking API KEY"); logger.info("Request key [{}]", username); logger.info("Key on tix [{}]", tran.getLockedByApi()); if (username == null) { return false; } else { return username.equals(tran.getLockedByApi()); } } /** * Will determine if the ticket has a lockId and the tran has not expired * * @param ticket the ticket */ private Boolean isInvolvedInActiveTransaction(PTicket ticket) { String ticketTranId = ticket.get(AthenaLockManager.LOCK_ID); if(ticketTranId != null) { return (new DateTime(ticket.get(AthenaLockManager.LOCK_EXPIRES))).isAfterNow(); } return false; } private Set<String> getTicketIds(Collection<PTicket> tickets) { Set<String> ids = new HashSet<String>(); for(PTicket t : tickets) { ids.add(IdAdapter.toString(t.getId())); } return ids; } public SecurityContextHolderStrategy getContextHolderStrategy() { return contextHolderStrategy; } public void setContextHolderStrategy(SecurityContextHolderStrategy contextHolderStrategy) { this.contextHolderStrategy = contextHolderStrategy; } public ApaAdapter getApa() { return apa; } public void setApa(ApaAdapter apa) { this.apa = apa; } }
gpl-3.0
idega/com.idega.block.creditcard
src/java/com/idega/block/creditcard/data/KortathjonustanAuthorisationEntriesBMPBean.java
7360
package com.idega.block.creditcard.data; import java.sql.Date; import java.util.Collection; import javax.ejb.FinderException; import com.idega.data.GenericEntity; import com.idega.data.IDOLookup; import com.idega.data.IDOLookupException; import com.idega.data.query.Column; import com.idega.data.query.MatchCriteria; import com.idega.data.query.SelectQuery; import com.idega.data.query.Table; import com.idega.data.query.WildCardColumn; import com.idega.util.IWTimestamp; /** * @author gimmi */ public class KortathjonustanAuthorisationEntriesBMPBean extends GenericEntity implements KortathjonustanAuthorisationEntries, CreditCardAuthorizationEntry { private static final String TABLE_NAME = "CC_KORTTHJ_AUTH_ENTRIES"; private static final String COLUMN_AMOUNT = "AMOUNT"; private static final String COLUMN_AUTHORIZATION_CODE = "AUTH_CODE"; private static final String COLUMN_BRAND_NAME = "BRAND_NAME"; private static final String COLUMN_CARD_EXPIRES = "CARD_EXPIRES"; private static final String COLUMN_CARD_NUMBER = "CARD_NUMBER"; private static final String COLUMN_CURRENCY = "CURRENCY"; private static final String COLUMN_DATE = "ENTRY_DATE"; private static final String COLUMN_ERROR_NUMBER = "ERROR_NUMBER"; private static final String COLUMN_ERROR_TEXT = "ERROR_TEXT"; private static final String COLUMN_SERVER_RESPONSE = "SERVER_RESPONSE"; private static final String COLUMN_PARENT_ID = "PARENT_ID"; private static final String COLUMN_TRANSACTION_TYPE = "TRANSACTION_TYPE"; //sale or refund ? public String getEntityName() { return TABLE_NAME; } public void initializeAttributes() { addAttribute(getIDColumnName()); addAttribute(COLUMN_AMOUNT, "amount", true, true, Double.class); addAttribute(COLUMN_AUTHORIZATION_CODE, "auth_code", true, true, String.class); addAttribute(COLUMN_BRAND_NAME, "brand_name", true, true, String.class); addAttribute(COLUMN_CARD_EXPIRES, "card expire date", true, true, String.class); addAttribute(COLUMN_CARD_NUMBER, "card number", true, true, String.class); addAttribute(COLUMN_CURRENCY, "currency", true, true, String.class); addAttribute(COLUMN_DATE, "date", true, true, Date.class); addAttribute(COLUMN_ERROR_NUMBER, "error number", true, true , String.class); addAttribute(COLUMN_ERROR_TEXT, "error text", true, true , String.class); addAttribute(COLUMN_TRANSACTION_TYPE, "transaction_type", true, true, String.class); addOneToOneRelationship(COLUMN_PARENT_ID, KortathjonustanAuthorisationEntries.class); addAttribute(COLUMN_SERVER_RESPONSE, "server response", true, true, String.class, 1000); } public double getAmount() { return getDoubleColumnValue(COLUMN_AMOUNT); } public void setAmount(double amount) { setColumn(COLUMN_AMOUNT, amount); } public String getCurrency() { return getStringColumnValue(COLUMN_CURRENCY); } public void setCurrency(String currency) { setColumn(COLUMN_CURRENCY, currency); } public Date getDate() { return getDateColumnValue(COLUMN_DATE); } public void setDate(Date date) { setColumn(COLUMN_DATE, date); } public String getCardExpires() { return getStringColumnValue(COLUMN_CARD_EXPIRES); } public void setCardExpires(String expires) { setColumn(COLUMN_CARD_EXPIRES, expires); } public String getCardNumber() { return getStringColumnValue(COLUMN_CARD_NUMBER); } public void setCardNumber(String number) { setColumn(COLUMN_CARD_NUMBER, number); } public String getBrandName() { return getStringColumnValue(COLUMN_BRAND_NAME); } public void setBrandName(String name) { setColumn(COLUMN_BRAND_NAME, name); } public String getAuthorizationCode() { return getStringColumnValue(COLUMN_AUTHORIZATION_CODE); } public void setAuthorizationCode(String code) { setColumn(COLUMN_AUTHORIZATION_CODE, code); } public String getTransactionType() { return getStringColumnValue(COLUMN_TRANSACTION_TYPE); } public void setTransactionType(String type) { setColumn(COLUMN_TRANSACTION_TYPE, type); } public int getParentID() { return getIntColumnValue(COLUMN_PARENT_ID); } public CreditCardAuthorizationEntry getParent() { return (KortathjonustanAuthorisationEntries) getColumnValue(COLUMN_PARENT_ID); } public void setParentID(int id) { setColumn(COLUMN_PARENT_ID, id); } public Object ejbFindByAuthorizationCode(String code, IWTimestamp stamp) throws FinderException { Table table = new Table(this); Column auth = new Column(table, COLUMN_AUTHORIZATION_CODE); Column date = new Column(table, COLUMN_DATE); SelectQuery query = new SelectQuery(table); query.addColumn(new WildCardColumn(table)); query.addCriteria(new MatchCriteria(auth, MatchCriteria.EQUALS, code)); query.addCriteria(new MatchCriteria(date, MatchCriteria.EQUALS, stamp.getDate().toString())); return this.idoFindOnePKBySQL(query.toString()); //return this.idoFindOnePKByColumnBySQL(COLUMN_AUTHORIZATION_CODE, code); } public Collection ejbFindByDates(IWTimestamp from, IWTimestamp to) throws FinderException { to.addDays(1); Table table = new Table(this); Column date = new Column(table, COLUMN_DATE); SelectQuery query = new SelectQuery(table); query.addColumn(new WildCardColumn(table)); query.addCriteria(new MatchCriteria(date, MatchCriteria.GREATEREQUAL, from.getDate().toString())); query.addCriteria(new MatchCriteria(date, MatchCriteria.LESSEQUAL, to.getDate().toString())); return this.idoFindPKsByQuery(query); } public void setErrorNumber(String errorNumber) { setColumn(COLUMN_ERROR_NUMBER, errorNumber); } public String getErrorNumber() { return getStringColumnValue(COLUMN_ERROR_NUMBER); } public void setErrorText(String errorText) { setColumn(COLUMN_ERROR_TEXT, errorText); } public String getErrorText() { return getStringColumnValue(COLUMN_ERROR_TEXT); } public void setServerResponse(String response) { setColumn(COLUMN_SERVER_RESPONSE, response); } public String getServerResponse() { return getStringColumnValue(COLUMN_SERVER_RESPONSE); } public String getExtraField() { return getServerResponse(); } public CreditCardAuthorizationEntry getChild() throws FinderException { Object obj = this.idoFindOnePKByColumnBySQL(COLUMN_PARENT_ID, this.getPrimaryKey().toString()); if (obj != null) { KortathjonustanAuthorisationEntriesHome home; try { home = (KortathjonustanAuthorisationEntriesHome) IDOLookup.getHome(KortathjonustanAuthorisationEntries.class); return home.findByPrimaryKey(obj); } catch (IDOLookupException e) { throw new FinderException(e.getMessage()); } } return null; } public Collection ejbFindRefunds(IWTimestamp from, IWTimestamp to) throws FinderException { to.addDays(1); Table table = new Table(this); Column date = new Column(table, COLUMN_DATE); Column code = new Column(table, COLUMN_TRANSACTION_TYPE); SelectQuery query = new SelectQuery(table); query.addColumn(new Column(table, getIDColumnName())); query.addCriteria(new MatchCriteria(code, MatchCriteria.EQUALS, KortathjonustanAuthorisationEntries.AUTHORIZATION_TYPE_REFUND)); query.addCriteria(new MatchCriteria(date, MatchCriteria.GREATEREQUAL, from.getDate().toString())); query.addCriteria(new MatchCriteria(date, MatchCriteria.LESSEQUAL, to.getDate().toString())); return this.idoFindPKsByQuery(query); } }
gpl-3.0
Zerrens/Chain-Reaction
src/main/java/com/zerren/chainreaction/item/itemblock/ItemBlockMetalMaterial.java
459
package com.zerren.chainreaction.item.itemblock; import chainreaction.api.block.CRBlocks; import com.zerren.chainreaction.reference.Names; import net.minecraft.block.Block; import net.minecraft.item.ItemMultiTexture; /** * Created by Zerren on 2/19/2015. */ public class ItemBlockMetalMaterial extends ItemMultiTexture { public ItemBlockMetalMaterial(Block block) { super(CRBlocks.metals, CRBlocks.metals, Names.Blocks.METAL_SUBTYPES); } }
gpl-3.0
ledyba/Haduki
client/HadukiSocketLib/src/psi/haduki/lib/stream/HTTP_HeaderInputStream.java
788
package psi.haduki.lib.stream; import java.io.*; /** * <p>ƒ^ƒCƒgƒ‹: u‚͂«v”Ä—pƒ\ƒPƒbƒgƒ‰ƒCƒuƒ‰ƒŠ</p> * * <p>à–¾: SocketƒNƒ‰ƒX‚̃TƒuƒNƒ‰ƒX‚Æ‚µ‚ÄŽÀ‘•‚µ‚½”Ä—pƒ‰ƒCƒuƒ‰ƒŠ</p> * * <p>’˜ìŒ : Copyright (c) 2007 PSI</p> * * <p>‰ïŽÐ–¼: </p> * * @author –¢“ü—Í * @version 1.0 */ public class HTTP_HeaderInputStream extends InputStream { InputStream is; public HTTP_HeaderInputStream(InputStream in) { is = in; } private boolean eof = false; private int data = 0; public int read() throws IOException { if (eof) { return -1; } int b = is.read(); data = data << 8 | b; eof = (b == -1 || data == 0x0d0a0d0a || (data & 0xffff) == 0x0a0a); return b; } }
gpl-3.0
osebelin/verdandi
src/main/java/verdandi/ui/ProjectImporter.java
1711
/******************************************************************************* * Copyright 2010 Olaf Sebelin * * This file is part of Verdandi. * * Verdandi 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. * * Verdandi 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 Verdandi. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package verdandi.ui; import java.util.Collection; import verdandi.event.ErrorEvent; import verdandi.model.CostUnit; import verdandi.model.VerdandiModel; import verdandi.persistence.PersistenceException; public class ProjectImporter extends Thread { private Collection<CostUnit> projects; protected ProjectImporter(Collection<CostUnit> projects) { super(); this.projects = projects; } /** * {@inheritDoc} */ @Override public void run() { try { ImportProgressView ipw = new ImportProgressView(VerdandiModel .getDefaultParentFrame()); // ImportProgressView ipw = new ImportProgressView(null); ipw.setVisible(true); VerdandiModel.getPersistence().saveAll(projects, ipw); } catch (PersistenceException e) { VerdandiModel.fireEvent(new ErrorEvent(e)); } } }
gpl-3.0
Sar777/onliner
app/src/main/java/by/orion/onlinertasks/presentation/main/fragments/profiles/mappers/ProfileListSectionToProfileSectionItemMapper.java
1331
package by.orion.onlinertasks.presentation.main.fragments.profiles.mappers; import android.content.Context; import android.support.annotation.NonNull; import java.util.List; import by.orion.onlinertasks.R; import by.orion.onlinertasks.common.GenericObjectMapper; public class ProfileListSectionToProfileSectionItemMapper implements GenericObjectMapper<List<String>, String> { private static final int MAX_VISIBLE_SECTIONS = 2; @NonNull private final Context context; public ProfileListSectionToProfileSectionItemMapper(@NonNull Context context) { this.context = context; } @NonNull @Override public String map(@NonNull List<String> sections) { StringBuilder builder = new StringBuilder(); builder.append(sections.get(0)).append(", "); for (int i = 1; i < sections.size() && i < MAX_VISIBLE_SECTIONS; ++i) { builder.append(sections.get(i).toLowerCase()) .append(", "); } builder.delete(builder.length() - 2, builder.length()); if (sections.size() > 2) { builder.append(" + ") .append(sections.size() - 2) .append(" ") .append(context.getString(R.string.msg_profile_section)); } return builder.toString(); } }
gpl-3.0
kronwiz/randomstuff
greenfoot/scroller/Blocco.java
713
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class Blocco here. * * @author (your name) * @version (a version number or a date) */ public class Blocco extends Actor { private int width = getImage().getWidth(); private int height = getImage().getHeight(); /** * Act - do whatever the Blocco wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { move(-1); if ( getX() < -width ) { MyWorld world = (MyWorld) getWorld(); setLocation( world.margineDestro, getY() ); } } }
gpl-3.0
yangweijun213/Java
数据结构和算法/DataStructure/src/com/jun/top_k/test3.java
1856
package com.jun.top_k; import java.util.Arrays; public class test3 { public static void main(String[] args) { int[] list = { 4, 1, 2, 5, 6, 7 }; // 找出Top Kth int k = 3; int kthElement = findKthLargest(list, k); System.out.println("找出Top Kth: "+kthElement); } // 解决TOP K -快速选择 - 找出Kth // 参考: http://www.cnblogs.com/en-heng/p/6336625.html // 平均:O(nlog2^n) 最好:O(nlog2^n) 最坏:O(n^2) http://www.jianshu.com/p/42f81846c0fb public static int findKthLargest(int[] nums, int k) { return quickSelect(nums, k, 0, nums.length - 1); } // quick select to find the kth-largest element public static int quickSelect(int[] arr, int k, int left, int right) { if (left == right) return arr[right]; // 如果只有1个,直接返回这个数 int index = partition(arr, left, right); // 快选,返回主元素 if (index - left + 1 > k) // 从主元素和第一个元素之间的元素差数 大于K, 然后在主元素的左边寻找。 return quickSelect(arr, k, left, index - 1); else if (index - left + 1 == k)// 主元素的位置和K元素的位置相同。 return arr[index]; else return quickSelect(arr, k - index + left - 1, index + 1, right); } // partition subarray a[left..right] so that a[left..j-1] >= a[j] >= // a[j+1..right] // and return index j // 从大到小 private static int partition(int arr[], int left, int right) { int i = left, j = right + 1, pivot = arr[left]; while (true) { while (i < right && arr[++i] > pivot) if (i == right) break; while (j > left && arr[--j] < pivot) if (j == left) break; if (i >= j) break; swap(arr, i, j); } swap(arr, left, j); // swap pivot and a[j] return j; } private static void swap(int[] arr, int i, int j) { int tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; } }
gpl-3.0
GameModsBR/MyChunks
src/main/java/br/com/gamemods/mychunks/cmd/GlobalCommands.java
2410
package br.com.gamemods.mychunks.cmd; import br.com.gamemods.mychunks.MyChunks; import br.com.gamemods.mychunks.data.state.ClaimedChunk; import br.com.gamemods.mychunks.data.state.PlayerName; import br.com.gamemods.mychunks.data.state.WorldFallbackContext; import com.flowpowered.math.vector.Vector3i; import org.spongepowered.api.command.CommandException; import org.spongepowered.api.command.CommandResult; import org.spongepowered.api.command.CommandSource; import org.spongepowered.api.command.args.CommandContext; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.text.Text; import org.spongepowered.api.text.format.TextColors; import org.spongepowered.api.world.Location; import org.spongepowered.api.world.World; import java.util.Optional; import java.util.UUID; import static br.com.gamemods.mychunks.Util.blockToChunk; /** * Commands that are available for everyone */ public class GlobalCommands { private final MyChunks plugin; public GlobalCommands(MyChunks plugin) { this.plugin = plugin; } public CommandResult map(CommandSource src, CommandContext args) throws CommandException { //TODO Implement src.sendMessage(Text.of("Unsupported")); return CommandResult.empty(); } public CommandResult claim(CommandSource src, CommandContext commandContext) { Player player = (Player) src; Location<World> location = player.getLocation(); UUID worldId = location.getExtent().getUniqueId(); Vector3i chunkPosition = blockToChunk(location.getPosition().toInt()); Optional<WorldFallbackContext> opt = plugin.getWorldContext(worldId); if(opt.isPresent()) { String reason = "Failed to load the world context for the world "+location.getExtent().getName(); player.sendMessage(Text.builder(reason).color(TextColors.RED).build()); return CommandResult.empty(); } WorldFallbackContext worldContext = opt.get(); ClaimedChunk claimedChunk = new ClaimedChunk(worldContext, chunkPosition); claimedChunk.setOwner(new PlayerName(player.getUniqueId(), player.getName())); plugin.getChunkMap(worldId).get().put(chunkPosition, claimedChunk); player.sendMessage(Text.of("The chunk "+chunkPosition+" is now protected")); return CommandResult.success(); } }
gpl-3.0
Koekiebox-PTY-LTD/Fluid
fluid-api/src/main/java/com/fluidbpm/package-info.java
118
/** * Root package for Fluid-BPM. * * @since 1.8 * @author jasonbruwer * @version 1.8 */ package com.fluidbpm;
gpl-3.0
drbizzaro/diggime
base/main/src/com/diggime/modules/health/components/HealthEventLabel.java
1836
package com.diggime.modules.health.components; import com.diggime.modules.health.model.HealthEvent; import com.diggime.modules.health.model.HealthEventType; import com.diggime.modules.health.model.IllnessType; import com.diggime.modules.health.model.TrainingType; import org.foilage.http.html.ComponentGroup; import org.foilage.http.html.HtmlComponentImpl; import org.foilage.http.html.body.BR; import org.foilage.http.html.body.Span; public class HealthEventLabel extends HtmlComponentImpl { private ComponentGroup.Builder builder; public HealthEventLabel(HealthEvent healthEvent) { builder = new ComponentGroup.Builder(); if(healthEvent.getType()== HealthEventType.WEIGHT) { builder.add(new Span.Builder(healthEvent.getDataMap().getString("weight") + " kg").style("color: purple;").build(), BR.I1); } else if(healthEvent.getType()== HealthEventType.HEIGHT) { builder.add(new Span.Builder(healthEvent.getDataMap().getInt("height") + " cm").style("color: purple;").build(), BR.I1); } else if(healthEvent.getType()==HealthEventType.TRAINING) { builder.add(new Span.Builder(TrainingType.getById(healthEvent.getDataMap().getInt("training_type")).name()+" ("+ healthEvent.getDataMap().getInt("training_length") + " min)").style("color: purple;").build(), BR.I1); } else if(healthEvent.getType()==HealthEventType.ILLNESS) { builder.add(new Span.Builder(IllnessType.getById(healthEvent.getDataMap().getInt("illness_type")).name()+" ("+ healthEvent.getDataMap().getInt("serious_level") + " ap)").style("color: purple;").build(), BR.I1); } } @Override protected void generateHtmlSpecific(HtmlComponentImpl parent, boolean onSameRow) { htmlBuilder.append(builder.build().getHtml(parent, false)); } }
gpl-3.0
robworth/patientview
patientview-parent/radar/src/main/java/org/patientview/radar/model/exception/UserEmailAlreadyExists.java
1414
/* * PatientView * * Copyright (c) Worth Solutions Limited 2004-2013 * * This file is part of PatientView. * * PatientView 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. * PatientView 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 PatientView in a file * titled COPYING. If not, see <http://www.gnu.org/licenses/>. * * @package PatientView * @link http://www.patientview.org * @author PatientView <info@patientview.org> * @copyright Copyright (c) 2004-2013, Worth Solutions Limited * @license http://www.gnu.org/licenses/gpl-3.0.html The GNU General Public License V3.0 */ package org.patientview.radar.model.exception; /** * thrown during professional registration is email address already exists */ public class UserEmailAlreadyExists extends Exception { public UserEmailAlreadyExists(String message) { super(message); } public UserEmailAlreadyExists(String message, Throwable cause) { super(message, cause); } }
gpl-3.0
incad/registrdigitalizace.harvest
src/main/java/cz/registrdigitalizace/harvest/metadata/ModsMetadataParser.java
5291
/* * Copyright (C) 2011 Jan Pokorsky * * 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 cz.registrdigitalizace.harvest.metadata; import java.io.InputStream; import java.io.Reader; import java.io.StringReader; import java.io.StringWriter; import java.net.URL; import java.util.logging.Level; import java.util.logging.Logger; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import javax.xml.bind.util.JAXBResult; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; /** * Parses MODS metadata of digital object. It uses XSL transformation * to {@link DigobjectType digobject} schema * in order to simplify customization for different libraries content * at some time in the future. For now it is optimized for MZK MODS. * * @author Jan Pokorsky */ public final class ModsMetadataParser { public static final String MZK_STYLESHEET = "mods3-digobjekt.xsl"; private static final Logger LOG = Logger.getLogger(ModsMetadataParser.class.getName()); private Transformer transformer; private Unmarshaller digObjReader; public ModsMetadataParser(String stylesheet) { try { initUnmarshaler(); initTransformer(stylesheet); } catch (TransformerConfigurationException ex) { throw new IllegalStateException(ex); } catch (JAXBException ex) { throw new IllegalStateException(ex); } } private void initUnmarshaler() throws JAXBException { JAXBContext jaxbCtx = JAXBContext.newInstance(DigobjectType.class); digObjReader = jaxbCtx.createUnmarshaller(); } private void initTransformer(String stylesheet) throws TransformerConfigurationException { TransformerFactory tfactory = TransformerFactory.newInstance(); URL xslt = ModsMetadataParser.class.getResource(stylesheet); if (xslt == null) { throw new TransformerConfigurationException("Missing stylesheet."); } transformer = tfactory.newTransformer(new StreamSource(xslt.toExternalForm())); } public DigobjectType parse(InputStream modsxml) { return parse(new StreamSource(modsxml)); } public DigobjectType parse(Reader modsxml) { return parse(new StreamSource(modsxml)); } public DigobjectType parse(Source src) { try { JAXBResult result = new JAXBResult(digObjReader); if (LOG.isLoggable(Level.FINE)) { StringWriter buffer = new StringWriter(); transformer.transform(src, new StreamResult(buffer)); dumpTransformedXml(buffer.toString(), result, Level.FINE); } else { transformer.transform(src, result); } DigobjectType dobj = (DigobjectType) result.getResult(); if (LOG.isLoggable(Level.FINE)) { LOG.fine(toString(dobj)); } return dobj; } catch (TransformerException ex) { throw new IllegalStateException(ex); } catch (JAXBException ex) { throw new IllegalStateException(ex); } } /** * helper to log transformed XML and copy contents to original Result */ private static void dumpTransformedXml(String xml, Result result, Level level) { try { TransformerFactory tfactory = TransformerFactory.newInstance(); Transformer t = tfactory.newTransformer(); t.transform(new StreamSource(new StringReader(xml)), result); LOG.log(level, xml); } catch (TransformerException ex) { throw new IllegalStateException(ex); } } public static String toString(DigobjectType dobj) { if (dobj == null) { return "null"; } return String.format("DigobjectType[\n title: %s,\n isbn: %s, issn: %s, ccnb: %s,\n" + " author: %s,\n publisher: %s,\n signature: %s, sigla: %s, year: %s]", dobj.getTitle(), dobj.getIsbn(), dobj.getIssn(), dobj.getCcnb(), dobj.getAuthor(), dobj.getPublisher(), dobj.getSignature(), dobj.getSigla(), dobj.getYear()); } }
gpl-3.0
raymondbh/TFC-Additions
src/main/java/org/rbh/tfcadditions/Blocks/BlockSetup.java
7285
package org.rbh.tfcadditions.Blocks; import cpw.mods.fml.common.registry.GameRegistry; import net.minecraft.block.Block; import org.rbh.tfcadditions.Api.Blocks; import org.rbh.tfcadditions.Blocks.Dent.BlockIGEXDent; import org.rbh.tfcadditions.Blocks.Dent.BlockIGINDent; import org.rbh.tfcadditions.Blocks.Dent.BlockMMDent; import org.rbh.tfcadditions.Blocks.Dent.BlockSEDDent; import org.rbh.tfcadditions.Blocks.DentSmall.BlockIGEXDentSmall; import org.rbh.tfcadditions.Blocks.DentSmall.BlockIGINDentSmall; import org.rbh.tfcadditions.Blocks.DentSmall.BlockMMDentSmall; import org.rbh.tfcadditions.Blocks.DentSmall.BlockSEDDentSmall; import org.rbh.tfcadditions.Blocks.Dent.BlockPlank2Dent; import org.rbh.tfcadditions.Blocks.Dent.BlockPlankDent; import org.rbh.tfcadditions.Blocks.Planks.*; import org.rbh.tfcadditions.Core.CreativeTabs; import org.rbh.tfcadditions.Items.ItemBlocks.ItemBlock; import org.rbh.tfcadditions.Items.ItemBlocks.ItemBlockPlanks; import org.rbh.tfcadditions.TFCAdditions; /** * Created by raymondbh on 15.07.2015. */ public class BlockSetup extends Blocks { public static void LoadBlocks(){ TFCAdditions.LOG.info(new StringBuilder().append("Loading Blocks").toString()); StoneMMDent = new BlockMMDent().setHardness(15F).setStepSound(Block.soundTypeStone).setBlockName("MMRockDent").setCreativeTab(CreativeTabs.TFCAdditions_Tab); StoneMMDentSmall = new BlockMMDentSmall().setHardness(15F).setStepSound(Block.soundTypeStone).setBlockName("MMRockDentSmall").setCreativeTab(CreativeTabs.TFCAdditions_Tab); StoneIGEXDent = new BlockIGEXDent().setHardness(16F).setStepSound(Block.soundTypeStone).setBlockName("IgExRockDent").setCreativeTab(CreativeTabs.TFCAdditions_Tab); StoneIGEXDentSmall = new BlockIGEXDentSmall().setHardness(16F).setStepSound(Block.soundTypeStone).setBlockName("IgExRockDentSmall").setCreativeTab(CreativeTabs.TFCAdditions_Tab); StoneIGINDent = new BlockIGINDent().setHardness(16F).setStepSound(Block.soundTypeStone).setBlockName("IgInRockDent").setCreativeTab(CreativeTabs.TFCAdditions_Tab); StoneIGINDentSmall = new BlockIGINDentSmall().setHardness(16F).setStepSound(Block.soundTypeStone).setBlockName("IgInRockDentSmall").setCreativeTab(CreativeTabs.TFCAdditions_Tab); StoneSEDDent = new BlockSEDDent().setHardness(16F).setStepSound(Block.soundTypeStone).setBlockName("SedRockDent").setCreativeTab(CreativeTabs.TFCAdditions_Tab); StoneSEDDentSmall = new BlockSEDDentSmall().setHardness(16F).setStepSound(Block.soundTypeStone).setBlockName("SedRockDentSmall").setCreativeTab(CreativeTabs.TFCAdditions_Tab); PlanksOutline = new BlockPlankDent().setHardness(4.0F).setResistance(5.0F).setStepSound(Block.soundTypeWood).setBlockName("PlanksOutline").setCreativeTab(CreativeTabs.TFCAdditions_Tab); PlanksOutline2 = new BlockPlank2Dent().setHardness(4.0F).setResistance(5.0F).setStepSound(Block.soundTypeWood).setBlockName("PlanksOutline2").setCreativeTab(CreativeTabs.TFCAdditions_Tab); PlanksLarge = new BlockPlanksLarge().setHardness(4.0F).setResistance(5.0F).setStepSound(Block.soundTypeWood).setBlockName("PlanksLarge").setCreativeTab(CreativeTabs.TFCAdditions_Tab); PlanksLarge2 = new BlockPlanksLarge2().setHardness(4.0F).setResistance(5.0F).setStepSound(Block.soundTypeWood).setBlockName("PlanksLarge2").setCreativeTab(CreativeTabs.TFCAdditions_Tab); PlanksParquet = new BlockPlanksParquet().setHardness(4.0F).setResistance(5.0F).setStepSound(Block.soundTypeWood).setBlockName("PlanksParquet").setCreativeTab(CreativeTabs.TFCAdditions_Tab); PlanksParquet2 = new BlockPlanksParquet2().setHardness(4.0F).setResistance(5.0F).setStepSound(Block.soundTypeWood).setBlockName("PlanksParquet2").setCreativeTab(CreativeTabs.TFCAdditions_Tab); //PlanksNorm = new BlockPlanksNorm().setHardness(4.0F).setResistance(5.0F).setStepSound(Block.soundTypeWood).setBlockName("PlanksNorm").setCreativeTab(CreativeTabs.TFCAdditions_Tab); //PlanksNorm2 = new BlockPlanksNorm2().setHardness(4.0F).setResistance(5.0F).setStepSound(Block.soundTypeWood).setBlockName("PlanksNorm2").setCreativeTab(CreativeTabs.TFCAdditions_Tab); PlanksVert = new BlockPlanksVert().setHardness(4.0F).setResistance(5.0F).setStepSound(Block.soundTypeWood).setBlockName("PlanksVert").setCreativeTab(CreativeTabs.TFCAdditions_Tab); PlanksVert2 = new BlockPlanksVert2().setHardness(4.0F).setResistance(5.0F).setStepSound(Block.soundTypeWood).setBlockName("PlanksVert2").setCreativeTab(CreativeTabs.TFCAdditions_Tab); StoneMMDent.setHarvestLevel("pickaxe", 0); StoneMMDentSmall.setHarvestLevel("pickaxe", 0); StoneIGEXDent.setHarvestLevel("pickaxe", 0); StoneIGEXDentSmall.setHarvestLevel("pickaxe", 0); StoneIGINDent.setHarvestLevel("pickaxe", 0); StoneIGINDentSmall.setHarvestLevel("pickaxe", 0); StoneSEDDent.setHarvestLevel("pickaxe", 0); StoneSEDDentSmall.setHarvestLevel("pickaxe", 0); PlanksOutline.setHarvestLevel("axe", 0); PlanksOutline2.setHarvestLevel("axe", 0); PlanksLarge.setHarvestLevel("axe", 0); PlanksLarge2.setHarvestLevel("axe", 0); PlanksParquet.setHarvestLevel("axe", 0); PlanksParquet2.setHarvestLevel("axe", 0); //PlanksNorm.setHarvestLevel("axe", 0); //PlanksNorm2.setHarvestLevel("axe", 0); PlanksVert.setHarvestLevel("axe", 0); PlanksVert2.setHarvestLevel("axe", 0); } public static void RegisterBlocks(){ TFCAdditions.LOG.info(new StringBuilder().append("Register Blocks").toString()); GameRegistry.registerBlock(StoneMMDent, ItemBlock.class, "StoneMMDent"); GameRegistry.registerBlock(StoneMMDentSmall, ItemBlock.class, "StoneMMDentSmall"); GameRegistry.registerBlock(StoneIGEXDent, ItemBlock.class, "StoneIGEXDent"); GameRegistry.registerBlock(StoneIGEXDentSmall, ItemBlock.class, "StoneIGEXDentSmall"); GameRegistry.registerBlock(StoneIGINDent, ItemBlock.class, "StoneIGINDent"); GameRegistry.registerBlock(StoneIGINDentSmall, ItemBlock.class, "StoneIGINDentSmall"); GameRegistry.registerBlock(StoneSEDDent, ItemBlock.class, "StoneSEDDent"); GameRegistry.registerBlock(StoneSEDDentSmall, ItemBlock.class, "StoneSEDDentSmall"); GameRegistry.registerBlock(PlanksOutline, ItemBlockPlanks.class, "OutlinedPlanks"); GameRegistry.registerBlock(PlanksOutline2, ItemBlockPlanks.class, "OutlinedPlanks2"); GameRegistry.registerBlock(PlanksLarge, ItemBlockPlanks.class, "LargePlanks"); GameRegistry.registerBlock(PlanksLarge2, ItemBlockPlanks.class, "LargePlanks2"); GameRegistry.registerBlock(PlanksParquet, ItemBlockPlanks.class, "ParquetPlanks"); GameRegistry.registerBlock(PlanksParquet2, ItemBlockPlanks.class, "ParquetPlanks2"); //GameRegistry.registerBlock(PlanksNorm, ItemBlockPlanks.class, "NormalPlanks"); //GameRegistry.registerBlock(PlanksNorm2, ItemBlockPlanks.class, "NormalPlanks2"); GameRegistry.registerBlock(PlanksVert, ItemBlockPlanks.class, "VerticalPlanks"); GameRegistry.registerBlock(PlanksVert2, ItemBlockPlanks.class, "VerticalPlanks2"); } }
gpl-3.0
SPACEDAC7/TrabajoFinalGrado
uploads/34f7f021ecaf167f6e9669e45c4483ec/java_source/android/support/design/internal/BottomNavigationAnimationHelperBase.java
342
/* * Decompiled with CFR 0_115. * * Could not load the following classes: * android.view.ViewGroup */ package android.support.design.internal; import android.view.ViewGroup; class BottomNavigationAnimationHelperBase { BottomNavigationAnimationHelperBase() { } void beginDelayedTransition(ViewGroup viewGroup) { } }
gpl-3.0
adofsauron/KEEL
src/keel/Algorithms/ImbalancedClassification/Resampling/SMOTE_RSB/Rough_Sets/FastVector.java
10951
package keel.Algorithms.ImbalancedClassification.Resampling.SMOTE_RSB.Rough_Sets; import java.io.Serializable; import java.util.Enumeration; /** * Implements a fast vector class without synchronized * methods. Replaces java.util.Vector. (Synchronized methods tend to * be slow.) * * @author Eibe Frank (eibe@cs.waikato.ac.nz) * @version $Revision: 1.1 $ */ public class FastVector implements Copyable, Serializable { /** * Class for enumerating the vector's elements. */ public class FastVectorEnumeration implements Enumeration { /** The counter. */ private int m_Counter; // These JML commands say how m_Counter implements Enumeration //@ in moreElements; //@ private represents moreElements = m_Counter < m_Vector.size(); //@ private invariant 0 <= m_Counter && m_Counter <= m_Vector.size(); /** The vector. */ private /*@non_null@*/ FastVector m_Vector; /** Special element. Skipped during enumeration. */ private int m_SpecialElement; //@ private invariant -1 <= m_SpecialElement; //@ private invariant m_SpecialElement < m_Vector.size(); //@ private invariant m_SpecialElement>=0 ==> m_Counter!=m_SpecialElement; /** * Constructs an enumeration. * * @param vector the vector which is to be enumerated */ public FastVectorEnumeration(/*@non_null@*/FastVector vector) { m_Counter = 0; m_Vector = vector; m_SpecialElement = -1; } /** * Constructs an enumeration with a special element. * The special element is skipped during the enumeration. * * @param vector the vector which is to be enumerated * @param special the index of the special element */ //@ requires 0 <= special && special < vector.size(); public FastVectorEnumeration(/*@non_null@*/FastVector vector, int special){ m_Vector = vector; m_SpecialElement = special; if (special == 0) { m_Counter = 1; } else { m_Counter = 0; } } /** * Tests if there are any more elements to enumerate. * * @return true if there are some elements left */ public final /*@pure@*/ boolean hasMoreElements() { if (m_Counter < m_Vector.size()) { return true; } return false; } /** * Returns the next element. * * @return the next element to be enumerated */ //@ also requires hasMoreElements(); public final Object nextElement() { Object result = m_Vector.elementAt(m_Counter); m_Counter++; if (m_Counter == m_SpecialElement) { m_Counter++; } return result; } } /** The array of objects. */ private /*@spec_public@*/ Object[] m_Objects; //@ invariant m_Objects != null; //@ invariant m_Objects.length >= 0; /** The current size; */ private /*@spec_public@*/ int m_Size = 0; //@ invariant 0 <= m_Size; //@ invariant m_Size <= m_Objects.length; /** The capacity increment */ private /*@spec_public@*/ int m_CapacityIncrement = 1; //@ invariant 1 <= m_CapacityIncrement; /** The capacity multiplier. */ private /*@spec_public@*/ int m_CapacityMultiplier = 2; //@ invariant 1 <= m_CapacityMultiplier; // Make sure the size will increase... //@ invariant 3 <= m_CapacityMultiplier + m_CapacityIncrement; /** * Constructs an empty vector with initial * capacity zero. */ public FastVector() { m_Objects = new Object[0]; } /** * Constructs a vector with the given capacity. * * @param capacity the vector's initial capacity */ //@ requires capacity >= 0; public FastVector(int capacity) { m_Objects = new Object[capacity]; } /** * Adds an element to this vector. Increases its * capacity if its not large enough. * * @param element the element to add */ public final void addElement(Object element) { Object[] newObjects; if (m_Size == m_Objects.length) { newObjects = new Object[m_CapacityMultiplier * (m_Objects.length + m_CapacityIncrement)]; System.arraycopy(m_Objects, 0, newObjects, 0, m_Size); m_Objects = newObjects; } m_Objects[m_Size] = element; m_Size++; } /** * Returns the capacity of the vector. * * @return the capacity of the vector */ //@ ensures \result == m_Objects.length; public final /*@pure@*/ int capacity() { return m_Objects.length; } /** * Produces a shallow copy of this vector. * * @return the new vector */ public final Object copy() { FastVector copy = new FastVector(m_Objects.length); copy.m_Size = m_Size; copy.m_CapacityIncrement = m_CapacityIncrement; copy.m_CapacityMultiplier = m_CapacityMultiplier; System.arraycopy(m_Objects, 0, copy.m_Objects, 0, m_Size); return copy; } /** * Clones the vector and shallow copies all its elements. * The elements have to implement the Copyable interface. * * @return the new vector */ public final Object copyElements() { FastVector copy = new FastVector(m_Objects.length); copy.m_Size = m_Size; copy.m_CapacityIncrement = m_CapacityIncrement; copy.m_CapacityMultiplier = m_CapacityMultiplier; for (int i = 0; i < m_Size; i++) { copy.m_Objects[i] = ((Copyable)m_Objects[i]).copy(); } return copy; } /** * Returns the element at the given position. * * @param index the element's index * @return the element with the given index */ //@ requires 0 <= index; //@ requires index < m_Objects.length; public final /*@pure@*/ Object elementAt(int index) { return m_Objects[index]; } /** * Returns an enumeration of this vector. * * @return an enumeration of this vector */ public final /*@pure@*/ Enumeration elements() { return new FastVectorEnumeration(this); } /** * Returns an enumeration of this vector, skipping the * element with the given index. * * @param index the element to skip * @return an enumeration of this vector */ //@ requires 0 <= index && index < size(); public final /*@pure@*/ Enumeration elements(int index) { return new FastVectorEnumeration(this, index); } /** * added by akibriya */ public /*@pure@*/ boolean contains(Object o) { if(o==null) return false; for(int i=0; i<m_Objects.length; i++) if(o.equals(m_Objects[i])) return true; return false; } /** * Returns the first element of the vector. * * @return the first element of the vector */ //@ requires m_Size > 0; public final /*@pure@*/ Object firstElement() { return m_Objects[0]; } /** * Searches for the first occurence of the given argument, * testing for equality using the equals method. * * @param element the element to be found * @return the index of the first occurrence of the argument * in this vector; returns -1 if the object is not found */ public final /*@pure@*/ int indexOf(/*@non_null@*/ Object element) { for (int i = 0; i < m_Size; i++) { if (element.equals(m_Objects[i])) { return i; } } return -1; } /** * Inserts an element at the given position. * * @param element the element to be inserted * @param index the element's index */ public final void insertElementAt(Object element, int index) { Object[] newObjects; if (m_Size < m_Objects.length) { System.arraycopy(m_Objects, index, m_Objects, index + 1, m_Size - index); m_Objects[index] = element; } else { newObjects = new Object[m_CapacityMultiplier * (m_Objects.length + m_CapacityIncrement)]; System.arraycopy(m_Objects, 0, newObjects, 0, index); newObjects[index] = element; System.arraycopy(m_Objects, index, newObjects, index + 1, m_Size - index); m_Objects = newObjects; } m_Size++; } /** * Returns the last element of the vector. * * @return the last element of the vector */ //@ requires m_Size > 0; public final /*@pure@*/ Object lastElement() { return m_Objects[m_Size - 1]; } /** * Deletes an element from this vector. * * @param index the index of the element to be deleted */ //@ requires 0 <= index && index < m_Size; public final void removeElementAt(int index) { System.arraycopy(m_Objects, index + 1, m_Objects, index, m_Size - index - 1); m_Size--; } /** * Removes all components from this vector and sets its * size to zero. */ public final void removeAllElements() { m_Objects = new Object[m_Objects.length]; m_Size = 0; } /** * Appends all elements of the supplied vector to this vector. * * @param toAppend the FastVector containing elements to append. */ public final void appendElements(FastVector toAppend) { setCapacity(size() + toAppend.size()); System.arraycopy(toAppend.m_Objects, 0, m_Objects, size(), toAppend.size()); m_Size = m_Objects.length; } /** * Returns all the elements of this vector as an array * * @return an array containing all the elements of this vector */ public final Object [] toArray() { Object [] newObjects = new Object[size()]; System.arraycopy(m_Objects, 0, newObjects, 0, size()); return newObjects; } /** * Sets the vector's capacity to the given value. * * @param capacity the new capacity */ public final void setCapacity(int capacity) { Object[] newObjects = new Object[capacity]; System.arraycopy(m_Objects, 0, newObjects, 0, Math.min(capacity, m_Size)); m_Objects = newObjects; if (m_Objects.length < m_Size) m_Size = m_Objects.length; } /** * Sets the element at the given index. * * @param element the element to be put into the vector * @param index the index at which the element is to be placed */ //@ requires 0 <= index && index < size(); public final void setElementAt(Object element, int index) { m_Objects[index] = element; } /** * Returns the vector's current size. * * @return the vector's current size */ //@ ensures \result == m_Size; public final /*@pure@*/ int size() { return m_Size; } /** * Swaps two elements in the vector. * * @param first index of the first element * @param second index of the second element */ //@ requires 0 <= first && first < size(); //@ requires 0 <= second && second < size(); public final void swap(int first, int second) { Object help = m_Objects[first]; m_Objects[first] = m_Objects[second]; m_Objects[second] = help; } /** * Sets the vector's capacity to its size. */ public final void trimToSize() { Object[] newObjects = new Object[m_Size]; System.arraycopy(m_Objects, 0, newObjects, 0, m_Size); m_Objects = newObjects; } }
gpl-3.0
D4Delta/MamePlaylistBuilder
src/main/java/fr/d4delta/mame/playlist/builder/MamePlaylistBuilder.java
7694
/* Copyright (C) 2017 D4Delta 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, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package fr.d4delta.mame.playlist.builder; import java.awt.EventQueue; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Properties; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; /** * * @author delta */ public class MamePlaylistBuilder { final static String MAME_LPL = "MAME.lpl"; final static String LPL = "DETECT" + System.lineSeparator() + "DETECT" + System.lineSeparator() + "00000000|crc" + System.lineSeparator() + MAME_LPL; final static String NAME_DB = "NamesDB.properties"; public static void main(String[] args) { try { if(args.length >= 2 && args[1].equalsIgnoreCase("buildNameDB")) { createNameDB(); } else { createPlaylist(); } } catch(Exception e) { printException(e); } } static void createPlaylist() throws Exception { JOptionPane.showMessageDialog(null, "Please select your MAME rom directory."); EventQueue.invokeAndWait(() -> { try { JFileChooser chooser = new JFileChooser(); chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); chooser.showOpenDialog(null); File mameRomsDir = chooser.getSelectedFile(); if(mameRomsDir == null) { return; } File output = new File(MAME_LPL); JOptionPane.showMessageDialog(null, "The playlist will be created after you close this message." + System.lineSeparator() + "It will be saved to: " + output.getAbsolutePath() + System.lineSeparator() + "This may take a while, depending on how much rom you own; You will get a notification when it's done."); Properties namesDB = new Properties(); try(InputStream inputStream = MamePlaylistBuilder.class.getResourceAsStream("/" + NAME_DB); PrintWriter writer = new PrintWriter(output)) { namesDB.load(inputStream); File[] files = mameRomsDir.listFiles((File pathname) -> !pathname.isDirectory()); for(File f: files) { String romName = f.getName(); int dotIndex = romName.lastIndexOf("."); romName = romName.substring(0, dotIndex); String fullName = namesDB.getProperty(romName); if(fullName != null) { writer.println(f.getAbsolutePath()); writer.println(fullName); writer.println(LPL); } } } JOptionPane.showMessageDialog(null, "Done! The playlist has been saved to: " + output.getAbsolutePath()); } catch(Exception e) { printException(e); } }); } static void createNameDB() throws Exception { JOptionPane.showMessageDialog(null, "Select the mame.xml"); EventQueue.invokeAndWait(() -> { try { JFileChooser chooser = new JFileChooser(); chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); chooser.showOpenDialog(null); File mameXMLFile = chooser.getSelectedFile(); if(mameXMLFile == null) { return; } File output = new File(NAME_DB); JOptionPane.showMessageDialog(null, "Name Database will be generated after you close this message." + System.lineSeparator() + "Name Database will be saved in " + output.getAbsolutePath() + "." + System.lineSeparator() + "This will take a while, and I recommend increasing JVM's heap size to avoid swapping."); //Start doing actual stuff DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); try(PrintWriter writer = new PrintWriter(output, "UTF-8")) { DocumentBuilder builder = factory.newDocumentBuilder(); Document mameXML = builder.parse(mameXMLFile); Element root = mameXML.getDocumentElement(); NodeList machineList = root.getElementsByTagName("machine"); for(int i = 0; i < machineList.getLength(); i++) { Element machine = (Element)machineList.item(i); writer.println(machine.getAttribute("name") + "=" + machine.getElementsByTagName("description").item(0).getTextContent()); } } JOptionPane.showMessageDialog(null, "Done. The Name database has been saved to: " + output.getAbsolutePath()); } catch(Exception e) { printException(e); } }); } static void printException(Exception ex) { DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss"); Date date = new Date(); String now = dateFormat.format(date); File logFile = new File("MamePlaylistBuilder-Crash-" + now + ".txt"); try(PrintWriter pw = new PrintWriter(logFile)) { ex.printStackTrace(pw); JOptionPane.showMessageDialog(null, "An error has occured. The crash log has been saved to : " + logFile + System.lineSeparator() + System.lineSeparator() + "If you report this bug, please copy the content of this log along with your bug report."); } catch (IOException ex1) { //Writing the crash log failed; Trying to print it in a dialog try(StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw)) { ex.printStackTrace(pw); JOptionPane.showMessageDialog(null, "There was an error, and this error could not be written in a log file. Here are the details:" + System.lineSeparator() + System.lineSeparator() + sw.toString() + System.lineSeparator() + System.lineSeparator() + "If you report this bug, please attach a screenshot of this dialog along with your bug report."); } catch (IOException ex2) { //Even converting it into a string using StringWriter failed; Trying to print it in the console (System.err) JOptionPane.showMessageDialog(null, "There was an error, and this error could not be converted into a string. Please check the console for more details"); ex.printStackTrace(System.err); } } } }
gpl-3.0
pkiraly/metadata-qa-marc
src/test/java/de/gwdg/metadataqa/marc/definition/tags/bltags/Tag598Test.java
462
package de.gwdg.metadataqa.marc.definition.tags.bltags; import org.junit.Test; public class Tag598Test extends BLTagTest { public Tag598Test() { super(Tag598.getInstance()); } @Test public void testValidFields() { validField("a", "unable to replace out of print 18.11.94"); } @Test public void testInvalidFields() { invalidField("c", "NLS copy dimensions: 16 cm."); invalidField("1", "a", "NLS copy dimensions: 16 cm."); } }
gpl-3.0
danielhams/mad-java
3UTIL/util-audio-gui/src/uk/co/modularaudio/util/audio/gui/patternsequencer/PatternSequenceNoteGridMouseListener.java
5823
/** * * Copyright (C) 2015 - Daniel Hams, Modular Audio Limited * daniel.hams@gmail.com * * Mad 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. * * Mad 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 Mad. If not, see <http://www.gnu.org/licenses/>. * */ package uk.co.modularaudio.util.audio.gui.patternsequencer; import java.awt.Dimension; import java.awt.Point; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import uk.co.modularaudio.util.audio.gui.patternsequencer.model.PatternSequenceModel; import uk.co.modularaudio.util.audio.gui.patternsequencer.model.PatternSequenceStep; import uk.co.modularaudio.util.audio.midi.MidiNote; import uk.co.modularaudio.util.audio.midi.MidiUtils; public class PatternSequenceNoteGridMouseListener implements MouseListener, MouseMotionListener { private static Log log = LogFactory.getLog( PatternSequenceNoteGridMouseListener.class.getName() ); private final PatternSequenceNoteGrid table; private final PatternSequenceModel dataModel; private final Dimension tableCellDimensions; private final Dimension tableSize; private final int numMidiNotes; private boolean lastNoteChangeWasSet = true; private final Point cellPoint = new Point(); private final Point previouslySetCellPoint = new Point(-1,-1); public PatternSequenceNoteGridMouseListener( final PatternSequenceNoteGrid patternSequencerTable, final PatternSequenceModel dataModel ) { this.table = patternSequencerTable; this.dataModel = dataModel; this.tableCellDimensions = table.getCellDimensions(); this.tableSize = table.getTableSize(); numMidiNotes = MidiUtils.getNumMidiNotes(); } @Override public void mouseDragged( final MouseEvent e ) { // log.debug("Got a drag event " + e.toString() ); final Point dragPoint = e.getPoint(); calculateCellIndexesFromPoint( dragPoint, cellPoint ); if( !cellPoint.equals( previouslySetCellPoint ) ) { // log.debug("Was for a new cell, will call set note for point"); setNoteForPoint( dragPoint, true ); previouslySetCellPoint.x = cellPoint.x; previouslySetCellPoint.y = cellPoint.y; } } @Override public void mouseMoved( final MouseEvent e ) { } @Override public void mouseClicked( final MouseEvent e ) { } @Override public void mousePressed( final MouseEvent e ) { // log.debug("Mouse pressed"); final Point clickPoint = e.getPoint(); calculateCellIndexesFromPoint( clickPoint, cellPoint ); if( !cellPoint.equals( previouslySetCellPoint ) ) { lastNoteChangeWasSet = setNoteForPoint( clickPoint, false ); previouslySetCellPoint.x = cellPoint.x; previouslySetCellPoint.y = cellPoint.y; } } private void calculateCellIndexesFromPoint( final Point clickPoint, final Point outputPoint ) { outputPoint.x = (clickPoint.x / tableCellDimensions.width); outputPoint.y = (clickPoint.y / tableCellDimensions.height); } private boolean setNoteForPoint( final Point clickPoint, final boolean isDrag ) { boolean wasASet = false; if( clickPoint.x >= 0 && clickPoint.x <= (tableSize.width - 1) && clickPoint.y >= 0 && clickPoint.y <= (tableSize.height - 1) ) { // log.debug("Within bounds. Will calculate which cell"); final Point cellPoint = new Point(); calculateCellIndexesFromPoint( clickPoint, cellPoint ); final int cellCol = cellPoint.x; final int cellRow = cellPoint.y; // log.debug("Is (" + cellCol + ", " + cellRow + ")"); if( cellCol < 0 || cellRow < 0 || cellCol > (dataModel.getNumSteps() - 1) || cellRow > (numMidiNotes - 1) ) { return false; } try { final MidiNote relatedNote = MidiUtils.getMidiNoteFromNumberReturnNull( (numMidiNotes - 1) - cellRow ); if( relatedNote == null ) { return false; } // log.debug("Toggling note " + relatedNote.toString() ); // If it's already set, unset it final PatternSequenceStep psn = dataModel.getNoteAtStep( cellCol ); final MidiNote noteFound = psn.note; final boolean continuation = ( psn.note == null ? dataModel.getContinuationState() : psn.isContinuation ); final float amp = ( psn.note == null ? dataModel.getDefaultAmplitude() : psn.amp ); if( (!isDrag && noteFound == relatedNote ) || (isDrag && lastNoteChangeWasSet == false && noteFound == relatedNote ) ) { dataModel.unsetNoteAtStep( cellCol ); wasASet = false; } else { if( !isDrag || (isDrag && lastNoteChangeWasSet) ) { if( psn.note != null ) { // Re-use the existing amp/continuation dataModel.setNoteAtStep( cellCol, relatedNote ); } else { dataModel.setNoteAtStepWithAmp( cellCol, relatedNote, continuation, amp ); } wasASet = true; } } } catch (final Exception e1) { final String msg = "Exception caught adding contents to table: " + e1.toString(); log.error( msg, e1 ); } } return wasASet; } @Override public void mouseReleased( final MouseEvent e ) { // log.debug("Received release event."); previouslySetCellPoint.x = -1; previouslySetCellPoint.y = -1; } @Override public void mouseEntered( final MouseEvent e ) { } @Override public void mouseExited( final MouseEvent e ) { } }
gpl-3.0
danielhams/mad-java
2COMMONPROJECTS/audio-services/src/uk/co/modularaudio/mads/base/cvtoaudio4/ui/CvToAudio4MadUiDefinition.java
2438
/** * * Copyright (C) 2015 - Daniel Hams, Modular Audio Limited * daniel.hams@gmail.com * * Mad 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. * * Mad 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 Mad. If not, see <http://www.gnu.org/licenses/>. * */ package uk.co.modularaudio.mads.base.cvtoaudio4.ui; import uk.co.modularaudio.mads.base.audiocvgen.mu.AudioToCvGenInstanceConfiguration; import uk.co.modularaudio.mads.base.audiocvgen.ui.AudioToCvGenMadUiDefinition; import uk.co.modularaudio.mads.base.cvtoaudio4.mu.CvToAudio4MadDefinition; import uk.co.modularaudio.mads.base.cvtoaudio4.mu.CvToAudio4MadInstance; import uk.co.modularaudio.util.audio.gui.mad.MadUIStandardBackgrounds; import uk.co.modularaudio.util.exception.DatastoreException; import uk.co.modularaudio.util.table.Span; public class CvToAudio4MadUiDefinition extends AudioToCvGenMadUiDefinition<CvToAudio4MadDefinition, CvToAudio4MadInstance, CvToAudio4MadUiInstance> { final static Span SPAN = new Span( 1, 1 ); public CvToAudio4MadUiDefinition( final CvToAudio4MadDefinition definition ) throws DatastoreException { this( definition, instanceConfigToUiConfig( CvToAudio4MadDefinition.INSTANCE_CONFIGURATION ) ); } private static CvToAudio4UiInstanceConfiguration instanceConfigToUiConfig( final AudioToCvGenInstanceConfiguration instanceConfiguration ) { return new CvToAudio4UiInstanceConfiguration( instanceConfiguration ); } private CvToAudio4MadUiDefinition( final CvToAudio4MadDefinition definition, final CvToAudio4UiInstanceConfiguration uiConfiguration ) throws DatastoreException { super( definition, MadUIStandardBackgrounds.STD_1X1_LIGHTGRAY, SPAN, CvToAudio4MadUiInstance.class, uiConfiguration.getChanIndexes(), uiConfiguration.getChanPosis(), uiConfiguration.getControlNames(), uiConfiguration.getControlTypes(), uiConfiguration.getControlClasses(), uiConfiguration.getControlBounds() ); } }
gpl-3.0
eisental/RedstoneChips
src/main/java/org/redstonechips/command/RCprotect.java
10013
package org.redstonechips.command; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.redstonechips.RCPermissions; import org.redstonechips.RCPrefs; import org.redstonechips.wireless.BroadcastChannel; /** * * @author Tal Eisenberg */ public class RCprotect extends RCCommand { private enum ProtectSubCommand { PROTECT, UNPROTECT, ADD, REMOVE } @Override public void run(CommandSender sender, Command command, String label, String[] args) { if (args.length == 0) { RChelp.printCommandHelp(sender, command.getName(), rc); } else if (args.length == 1) { if (args[0].equalsIgnoreCase("listchannels")) { listChannels(sender); } else channelInfo(sender, args[0]); } else if (args.length >= 2) { try { switch (ProtectSubCommand.valueOf(args[1].toUpperCase())) { case PROTECT: protect(sender, args); break; case UNPROTECT: unprotect(sender, args); break; case ADD: add(sender, args); break; case REMOVE: remove(sender, args); break; } } catch (IllegalArgumentException ie) { if (sender != null) sender.sendMessage(RCPrefs.getErrorColor() + "Unknown command: " + args[1]); } } } private void channelInfo(CommandSender sender, String channelName) { if (!rc.channelManager().getBroadcastChannels().containsKey(channelName)) { if (sender != null) sender.sendMessage(RCPrefs.getErrorColor() + "Channel " + channelName + " not found."); return; } ChatColor extraColor = ChatColor.YELLOW; BroadcastChannel curChannel = rc.channelManager().getChannelByName(channelName, false); if (curChannel.isProtected()) { if (RCPermissions.enforceChannel(sender, curChannel, true)) return; String owners = ""; String users = ""; for (String owner : curChannel.owners) { owners += owner + ", "; } for (String user : curChannel.users) { users += user + ", "; } if (!owners.isEmpty()) if (sender != null) sender.sendMessage(RCPrefs.getInfoColor() + "admins: " + extraColor + owners.substring(0, owners.length()-2)); if (!users.isEmpty()) if (sender != null) sender.sendMessage(RCPrefs.getInfoColor() + "users: " + extraColor + users.substring(0, users.length()-2)); } else { if (sender != null) sender.sendMessage(RCPrefs.getErrorColor() + "Channel " + channelName + " is not protected."); } } private void protect(CommandSender sender, String[] args) { BroadcastChannel curChannel = rc.channelManager().getChannelByName(args[0], true); if (!curChannel.isProtected()) { if (!(sender instanceof Player) && args.length < 3) { if (sender != null) sender.sendMessage(RCPrefs.getErrorColor() + "Usernames must be specified if run from console."); return; } if (args.length > 2) { if (!addUsers(args, curChannel)) { if (sender != null) sender.sendMessage(RCPrefs.getErrorColor() + "Unable to parse user list."); return; } } if (sender instanceof Player) { if (!curChannel.owners.contains(((Player)sender).getName().toLowerCase())) curChannel.owners.add(((Player)sender).getName().toLowerCase()); } if (sender != null) sender.sendMessage(RCPrefs.getInfoColor() + "Channel " + args[0] + " has been protected."); } else { if (sender != null) sender.sendMessage(RCPrefs.getErrorColor() + "Channel " + args[0] + " is already protected."); } } private void unprotect(CommandSender sender, String[] args) { if (rc.channelManager().getBroadcastChannels().containsKey(args[0])) { BroadcastChannel curChannel = rc.channelManager().getChannelByName(args[0], false); if (!RCPermissions.enforceChannel(sender, curChannel, true)) return; if (curChannel.isProtected()) { curChannel.owners.clear(); curChannel.users.clear(); if (sender != null) sender.sendMessage(RCPrefs.getInfoColor() + "Channel " + args[0] + " has been unprotected."); } else { if (sender != null) sender.sendMessage(RCPrefs.getErrorColor() + "Channel " + args[0] + " is not protected."); } } else { if (sender != null) sender.sendMessage(RCPrefs.getErrorColor() + "Channel " + args[0] + " not found."); } } private void add(CommandSender sender, String[] args) { if (rc.channelManager().getBroadcastChannels().containsKey(args[0])) { BroadcastChannel curChannel = rc.channelManager().getChannelByName(args[0], false); if (!RCPermissions.enforceChannel(sender, curChannel, true)) return; if (curChannel.isProtected()) { if (args.length > 2) { if (!addUsers(args, curChannel)) { if (sender != null) sender.sendMessage(RCPrefs.getErrorColor() + "Unable to parse user list."); return; } if (sender != null) sender.sendMessage(RCPrefs.getInfoColor() + "Channel " + args[0] + " has been updated."); } else { if (sender != null) sender.sendMessage(RCPrefs.getErrorColor() + "No usernames passed."); } } else { if (sender != null) sender.sendMessage(RCPrefs.getErrorColor() + "Channel " + args[0] + " is not protected."); } } else { if (sender != null) sender.sendMessage(RCPrefs.getErrorColor() + "Channel " + args[0] + " not found."); } } private boolean addUsers(String[] args, BroadcastChannel curChannel) { String[] userList; for (int i = 2; i < 4; i++) { if (i == args.length) return true; userList = args[i].toLowerCase().split("[:,]"); switch (userList[0]) { case "users": for (int j = 1; j < userList.length; j++) { if (!curChannel.users.contains(userList[j])) curChannel.users.add(userList[j]); } break; case "admins": for (int j = 1; j < userList.length; j++) { if (!curChannel.owners.contains(userList[j])) curChannel.owners.add(userList[j]); } break; default: return false; } } return true; } private void remove(CommandSender sender, String[] args) { if (rc.channelManager().getBroadcastChannels().containsKey(args[0])) { BroadcastChannel curChannel = rc.channelManager().getChannelByName(args[0], true); if (!RCPermissions.enforceChannel(sender, curChannel, true)) return; if (curChannel.isProtected()) { if (args.length > 2) { if (!removeUsers(args, curChannel)) { if (sender != null) sender.sendMessage(RCPrefs.getErrorColor() + "Unable to parse user list."); } else if (sender != null) sender.sendMessage(RCPrefs.getInfoColor() + "Channel " + args[0] + " has been updated."); } else { if (sender != null) sender.sendMessage(RCPrefs.getErrorColor() + "No usernames passed."); } } else { if (sender != null) sender.sendMessage(RCPrefs.getErrorColor() + "Channel " + args[0] + " is not protected."); } } else { if (sender != null) sender.sendMessage(RCPrefs.getErrorColor() + "Channel " + args[0] + " not found."); } } private boolean removeUsers(String[] args, BroadcastChannel curChannel) { String[] userList; for (int i = 2; i < 4; i++) { if (i == args.length) return true; userList = args[i].toLowerCase().split("[:,]"); switch (userList[0]) { case "users": for (int j = 1; j < userList.length; j++) { curChannel.users.remove(userList[j]); } break; case "admins": for (int j = 1; j < userList.length; j++) { curChannel.owners.remove(userList[j]); } break; default: return false; } } return true; } private void listChannels(CommandSender sender) { String protectedChannels = ""; for (BroadcastChannel curChannel : rc.channelManager().getBroadcastChannels().values()) { if (curChannel.isProtected()) { protectedChannels += curChannel.name + ", "; } } if (!protectedChannels.isEmpty()) { if (sender != null) sender.sendMessage(RCPrefs.getInfoColor() + "Protected Channels: " + protectedChannels.substring(0, protectedChannels.length()-2)); } else { if (sender != null) sender.sendMessage(RCPrefs.getInfoColor() + "There are no protected channels."); } } }
gpl-3.0
tmoskun/JSNMPWalker
lib/mibble-2.9.3/src/java/net/percederberg/mibble/snmp/SnmpObjectIdentity.java
4769
/* * SnmpObjectIdentity.java * * This work 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 work 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 * * Copyright (c) 2004-2013 Per Cederberg. All rights reserved. */ package net.percederberg.mibble.snmp; import net.percederberg.mibble.MibException; import net.percederberg.mibble.MibLoaderLog; import net.percederberg.mibble.MibSymbol; import net.percederberg.mibble.MibType; import net.percederberg.mibble.MibValue; import net.percederberg.mibble.MibValueSymbol; import net.percederberg.mibble.value.ObjectIdentifierValue; /** * The SNMP object identity macro type. This macro type was added to * SMIv2 and is defined in RFC 2578. * * @see <a href="http://www.ietf.org/rfc/rfc2578.txt">RFC 2578 (SNMPv2-SMI)</a> * * @author Per Cederberg, <per at percederberg dot net> * @version 2.10 * @since 2.0 */ public class SnmpObjectIdentity extends SnmpType { /** * The object identity status. */ private SnmpStatus status; /** * The object identity reference. */ private String reference; /** * Creates a new SNMP object identity. * * @param status the object identity status * @param description the object identity description * @param reference the object identity reference, or null */ public SnmpObjectIdentity(SnmpStatus status, String description, String reference) { super("OBJECT-IDENTITY", description); this.status = status; this.reference = reference; } /** * Initializes the MIB type. This will remove all levels of * indirection present, such as references to types or values. No * information is lost by this operation. This method may modify * this object as a side-effect, and will return the basic * type.<p> * * <strong>NOTE:</strong> This is an internal method that should * only be called by the MIB loader. * * @param symbol the MIB symbol containing this type * @param log the MIB loader log * * @return the basic MIB type * * @throws MibException if an error was encountered during the * initialization * * @since 2.2 */ public MibType initialize(MibSymbol symbol, MibLoaderLog log) throws MibException { if (!(symbol instanceof MibValueSymbol)) { throw new MibException(symbol.getLocation(), "only values can have the " + getName() + " type"); } return this; } /** * Checks if the specified value is compatible with this type. A * value is compatible if and only if it is an object identifier * value. * * @param value the value to check * * @return true if the value is compatible, or * false otherwise */ public boolean isCompatible(MibValue value) { return value instanceof ObjectIdentifierValue; } /** * Returns the object identity status. * * @return the object identity status */ public SnmpStatus getStatus() { return status; } /** * Returns the object identity reference. * * @return the object identity reference, or * null if no reference has been set */ public String getReference() { return reference; } /** * Returns a string representation of this object. * * @return a string representation of this object */ public String toString() { StringBuilder buffer = new StringBuilder(); buffer.append(super.toString()); buffer.append(" ("); buffer.append("\n Status: "); buffer.append(status); buffer.append("\n Description: "); buffer.append(getDescription(" ")); if (reference != null) { buffer.append("\n Reference: "); buffer.append(reference); } buffer.append("\n)"); return buffer.toString(); } }
gpl-3.0
elefher/CpuHandler
src/com/elefher/customclasses/DisplayText.java
417
package com.elefher.customclasses; import android.app.Activity; import android.widget.TextView; public class DisplayText { Activity activity; public DisplayText(Activity act){ activity = act; } public static void updateText(Activity act, int rIdGovText, String descriptionString){ TextView currentCpuString = (TextView) act.findViewById(rIdGovText); currentCpuString.setText(descriptionString); } }
gpl-3.0
tvesalainen/util
util/src/test/java/org/vesalainen/io/RewindableInputStreamTest.java
1810
/* * Copyright (C) 2014 Timo Vesalainen * * 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 org.vesalainen.io; import java.io.InputStream; import java.io.InputStreamReader; import static org.junit.Assert.*; import org.junit.Test; /** * * @author Timo Vesalainen */ public class RewindableInputStreamTest { public RewindableInputStreamTest() { } /** * Test of rewind method, of class RewindableReader. */ @Test public void test1() throws Exception { try (InputStream is = RewindableInputStreamTest.class.getClassLoader().getResourceAsStream("test.txt"); RewindableInputStream ris = new RewindableInputStream(is, 64, 32); ) { byte[] buf = new byte[20]; int rc = ris.read(buf); while (rc == buf.length) { String s1 = new String(buf); ris.rewind(10); rc = ris.read(buf); String s2 = new String(buf); assertEquals(s1.substring(10), s2.substring(0, 10)); rc = ris.read(buf); } } } }
gpl-3.0
gysgogo/levetube
lib/src/main/java/com/google/android/exoplayer2/decoder/Decoder.java
2093
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.exoplayer.com.google.android.exoplayer2.decoder; /** * A media decoder. * * @param <I> The type of buffer input to the decoder. * @param <O> The type of buffer output from the decoder. * @param <E> The type of exception thrown from the decoder. */ public interface Decoder<I, O, E extends Exception> { /** * Returns the name of the decoder. * * @return The name of the decoder. */ String getName(); /** * Dequeues the next input buffer to be filled and queued to the decoder. * * @return The input buffer, which will have been cleared, or null if a buffer isn't available. * @throws E If a decoder error has occurred. */ I dequeueInputBuffer() throws E; /** * Queues an input buffer to the decoder. * * @param inputBuffer The input buffer. * @throws E If a decoder error has occurred. */ void queueInputBuffer(I inputBuffer) throws E; /** * Dequeues the next output buffer from the decoder. * * @return The output buffer, or null if an output buffer isn't available. * @throws E If a decoder error has occurred. */ O dequeueOutputBuffer() throws E; /** * Flushes the decoder. Ownership of dequeued input buffers is returned to the decoder. The caller * is still responsible for releasing any dequeued output buffers. */ void flush(); /** * Releases the decoder. Must be called when the decoder is no longer needed. */ void release(); }
gpl-3.0