List of usage examples for java.util ArrayList indexOf
public int indexOf(Object o)
From source file:org.sufficientlysecure.keychain.ui.keyview.loader.IdentityLoader.java
private void correlateOrAddTrustIds(ArrayList<IdentityInfo> identities) { Cursor cursor = contentResolver.query(ApiAutocryptPeer.buildByMasterKeyId(masterKeyId), TRUST_IDS_PROJECTION, null, null, null); if (cursor == null) { Log.e(Constants.TAG, "Error loading trust ids!"); return;// w w w .ja v a 2s. c o m } try { while (cursor.moveToNext()) { String packageName = cursor.getString(INDEX_PACKAGE_NAME); String autocryptPeer = cursor.getString(INDEX_TRUST_ID); Drawable drawable = packageIconGetter.getDrawableForPackageName(packageName); Intent autocryptPeerIntent = getTrustIdActivityIntentIfResolvable(packageName, autocryptPeer); UserIdInfo associatedUserIdInfo = findUserIdMatchingTrustId(identities, autocryptPeer); if (associatedUserIdInfo != null) { int position = identities.indexOf(associatedUserIdInfo); TrustIdInfo autocryptPeerInfo = TrustIdInfo.create(associatedUserIdInfo, autocryptPeer, packageName, drawable, autocryptPeerIntent); identities.set(position, autocryptPeerInfo); } else { TrustIdInfo autocryptPeerInfo = TrustIdInfo.create(autocryptPeer, packageName, drawable, autocryptPeerIntent); identities.add(autocryptPeerInfo); } } } finally { cursor.close(); } }
From source file:com.digium.respoke.ContactManager.java
public void onJoin(RespokeConnection connection, RespokeGroup sender) { if (-1 != groups.indexOf(sender)) { String groupName = sender.getGroupID(); // Get the list of known connections for this group ArrayList<RespokeConnection> groupConnections = groupConnectionArrays.get(groupName); groupConnections.add(connection); // Get the list of known endpoints for this group ArrayList<RespokeEndpoint> groupEndpoints = groupEndpointArrays.get(groupName); // Get the endpoint that owns this new connection RespokeEndpoint parentEndpoint = connection.getEndpoint(); // If this endpoint is not known anywhere, remember it if (-1 == allKnownEndpoints.indexOf(parentEndpoint)) { Log.d(TAG, "Joined: " + parentEndpoint.getEndpointID()); trackEndpoint(parentEndpoint); // Notify any UI listeners that a new endpoint has been discovered Intent intent = new Intent(ENDPOINT_DISCOVERED); intent.putExtra("endpointID", parentEndpoint.getEndpointID()); LocalBroadcastManager.getInstance(context).sendBroadcast(intent); }//from w ww . j a v a 2 s. c o m // If this endpoint is not known in this specific group, remember it if (-1 == groupEndpoints.indexOf(parentEndpoint)) { groupEndpoints.add(parentEndpoint); // Notify any UI listeners that a new endpoint has joined this group // Notify any UI listeners that group membership has changed Intent intent = new Intent(ENDPOINT_JOINED_GROUP); intent.putExtra("endpointID", parentEndpoint.getEndpointID()); intent.putExtra("groupID", sender.getGroupID()); LocalBroadcastManager.getInstance(context).sendBroadcast(intent); } } }
From source file:tdunnick.phinmsx.model.Charts.java
/** * Sort and setup chart data by "constraint" * //from ww w . j a va2s . com * @param r list of constraint, time pairs * @param ends ending date for list * @param days covered by list * @return bar chart data */ private CategoryDataset createBarChartDataset(ArrayList r, long ends, long days) { ArrayList constraints = new ArrayList(); DefaultCategoryDataset dataset = new DefaultCategoryDataset(); // first time through just collect the constraint names for (int i = 0; i < r.size(); i++) { String[] item = (String[]) r.get(i); String k = (String) item[0]; if (!constraints.contains(k)) constraints.add(k); } long interval = days * MS; long start = ends - interval; interval /= 5; int[] counts = new int[constraints.size()]; for (int i = 0; i < constraints.size(); i++) counts[i] = 0; for (int i = 0; i < r.size(); i++) { String[] item = (String[]) r.get(i); long d = Long.parseLong(item[1]); if (d > start) { addBarData(dataset, constraints, start, counts); start += interval; } counts[constraints.indexOf(item[0])]++; } addBarData(dataset, constraints, start, counts); while ((start += interval) < ends) addBarData(dataset, constraints, start, counts); return dataset; }
From source file:tdunnick.phinmsx.model.Charts.java
private XYSeriesCollection createLineChartDataset(ArrayList r, long ends, long days) { ArrayList constraints = new ArrayList(); XYSeriesCollection dataset = new XYSeriesCollection(); // first time through just collect the constraint names for (int i = 0; i < r.size(); i++) { String[] item = (String[]) r.get(i); String k = (String) item[0]; if (!constraints.contains(k)) { constraints.add(k);/*from w w w . java2 s . co m*/ dataset.addSeries(new XYSeries(k)); } } long interval = days * MS; long start = ends - interval; interval /= 5; int[] counts = new int[constraints.size()]; for (int i = 0; i < constraints.size(); i++) counts[i] = 0; for (int i = 0; i < r.size(); i++) { String[] item = (String[]) r.get(i); long d = Long.parseLong(item[1]); if (d > start) { addLineData(dataset, start, counts); start += interval; } int j = constraints.indexOf(item[0]); if (j >= 0) counts[j]++; } addLineData(dataset, start, counts); while ((start += interval) < ends) addLineData(dataset, start, counts); return dataset; }
From source file:tdunnick.jphineas.console.queue.Charts.java
private XYSeriesCollection createLineChartDataset(ArrayList<String[]> r, long ends, long days) { ArrayList<String> constraints = new ArrayList<String>(); XYSeriesCollection dataset = new XYSeriesCollection(); // first time through just collect the constraint names for (int i = 0; i < r.size(); i++) { String[] item = (String[]) r.get(i); String k = (String) item[0]; if (!constraints.contains(k)) { constraints.add(k);//from ww w. j ava 2s.c o m dataset.addSeries(new XYSeries(k)); } } long interval = days * MS; long start = ends - interval; interval /= 5; int[] counts = new int[constraints.size()]; for (int i = 0; i < constraints.size(); i++) counts[i] = 0; for (int i = 0; i < r.size(); i++) { String[] item = (String[]) r.get(i); long d = Long.parseLong(item[1]); if (d > start) { addLineData(dataset, start, counts); start += interval; } int j = constraints.indexOf(item[0]); if (j >= 0) counts[j]++; } addLineData(dataset, start, counts); while ((start += interval) < ends) addLineData(dataset, start, counts); return dataset; }
From source file:com.androguide.honamicontrol.kernel.cpucontrol.CPUActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //noinspection ConstantConditions getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setIcon(getResources().getDrawable(R.drawable.ic_tools_cpu_control)); setContentView(R.layout.card_cpu_control); bootPrefs = getSharedPreferences("BOOT_PREFS", 0); graph = (LineGraph) findViewById(R.id.graph); line = new Line(); LinePoint point = new LinePoint(); point.setX(currX);/*w ww. ja va 2 s.com*/ point.setY(1); line.addPoint(point); line.setColor(Color.parseColor("#FFBB33")); graph.addLine(line); graph.setLineToFill(0); availableFrequencies = new String[0]; String availableFrequenciesLine; mCoresOnline = (TextView) findViewById(R.id.cores_online); mGeneralGovernor = (Spinner) findViewById(R.id.general_governor); mGovernor = (Spinner) findViewById(R.id.governor); mGovernor2 = (Spinner) findViewById(R.id.governor2); mGovernor3 = (Spinner) findViewById(R.id.governor3); mGovernor4 = (Spinner) findViewById(R.id.governor4); Button customizeGov = (Button) findViewById(R.id.governor_customize_btn); customizeGov.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { FragmentManager fm = getSupportFragmentManager(); GovernorDialog editNameDialog = new GovernorDialog(); editNameDialog.show(fm, "governor_fragment"); } }); if (Helpers.doesFileExist(STEPS)) { availableFrequenciesLine = CPUHelper.readOneLineNotRoot(STEPS); if (availableFrequenciesLine != null) { availableFrequencies = availableFrequenciesLine.split(" "); Arrays.sort(availableFrequencies, new Comparator<String>() { @Override public int compare(String object1, String object2) { return Integer.valueOf(object1).compareTo(Integer.valueOf(object2)); } }); } } Switch snakeCharmer = (Switch) findViewById(R.id.snake_charmer_switch); if (!Helpers.doesFileExist(SNAKE_CHARMER_MAX_FREQ)) { LinearLayout cardSnakeCharmer = (LinearLayout) findViewById(R.id.card_snake_charmer); cardSnakeCharmer.setVisibility(View.GONE); } else { if (Helpers.doesFileExist(SNAKE_CHARMER_VERSION)) { TextView snakeTitle = (TextView) findViewById(R.id.snake_charmer); String snakeVersion = CPUHelper.readOneLineNotRoot(SNAKE_CHARMER_VERSION); snakeVersion = snakeVersion.replaceAll("version: ", "v"); snakeTitle.setText(snakeTitle.getText() + " " + snakeVersion); if (snakeVersion.equals("v1.2")) { TextView snakeDesc = (TextView) findViewById(R.id.snake_charmer_text); snakeDesc.setText(snakeDesc.getText() + "\n" + getString(R.string.snake_charmer_built_in)); snakeCharmer.setEnabled(false); } } if (bootPrefs.getBoolean("SNAKE_CHARMER", true)) { snakeCharmer.setChecked(true); snakeCharmerEnabled = true; } snakeCharmer.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean isOn) { snakeCharmerEnabled = isOn; } }); } int frequenciesNum = availableFrequencies.length - 1; Switch thermalControl = (Switch) findViewById(R.id.msm_thermal_switch); if (Helpers.doesFileExist(MSM_THERMAL)) { String thermal = CPUHelper.readOneLineNotRoot(MSM_THERMAL); if (thermal.equals("Y")) thermalControl.setChecked(true); else thermalControl.setChecked(false); thermalControl.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) { if (isChecked) Helpers.CMDProcessorWrapper.runSuCommand("echo Y > " + MSM_THERMAL); else Helpers.CMDProcessorWrapper.runSuCommand("echo N > " + MSM_THERMAL); bootPrefs.edit().putBoolean("MSM_THERMAL", isChecked).commit(); } }); } thermalControl.setChecked(bootPrefs.getBoolean("MSM_THERMAL", true)); perCoreGovernor = (Switch) findViewById(R.id.per_core_governors_switch); perCoreGovernor.setChecked(bootPrefs.getBoolean("PER_CORE_GOV", true)); if (perCoreGovernor.isChecked()) { findViewById(R.id.card_general_governor).setVisibility(View.GONE); findViewById(R.id.card_per_core_governors).setVisibility(View.VISIBLE); } else { findViewById(R.id.card_per_core_governors).setVisibility(View.GONE); findViewById(R.id.card_general_governor).setVisibility(View.VISIBLE); } perCoreGovernor.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) { if (isChecked) { findViewById(R.id.card_general_governor).setVisibility(View.GONE); findViewById(R.id.card_per_core_governors).setVisibility(View.VISIBLE); handleGovernors(); } else { findViewById(R.id.card_per_core_governors).setVisibility(View.GONE); findViewById(R.id.card_general_governor).setVisibility(View.VISIBLE); handleGovernors(); } bootPrefs.edit().putBoolean("PER_CORE_GOV", isChecked).commit(); } }); String currentIo = ""; if (Helpers.doesFileExist(IO_SCHEDULER)) currentIo = CPUHelper.getIOScheduler(); String currentTcp = ""; if (Helpers.doesFileExist(CURR_TCP_ALGORITHM)) currentTcp = Helpers.getCurrentTcpAlgorithm(); String curMaxSpeed = "NaN"; if (Helpers.doesFileExist(MAX_FREQ_ALL_CORES)) curMaxSpeed = CPUHelper.readOneLineNotRoot(MAX_FREQ_ALL_CORES); else if (Helpers.doesFileExist(MAX_FREQ)) curMaxSpeed = CPUHelper.readOneLineNotRoot(MAX_FREQ); String curMinSpeed = "NaN"; if (Helpers.doesFileExist(MIN_FREQ_ALL_CORES)) curMinSpeed = CPUHelper.readOneLineNotRoot(MIN_FREQ_ALL_CORES); else if (Helpers.doesFileExist(MIN_FREQ)) curMinSpeed = CPUHelper.readOneLineNotRoot(MIN_FREQ); if (mIsTegra3) { String curTegraMaxSpeed = "NaN"; if (Helpers.doesFileExist(TEGRA_MAX_FREQ)) { curTegraMaxSpeed = CPUHelper.readOneLineNotRoot(TEGRA_MAX_FREQ); int curTegraMax = 0; try { curTegraMax = Integer.parseInt(curTegraMaxSpeed); if (curTegraMax > 0) { curMaxSpeed = Integer.toString(curTegraMax); } } catch (NumberFormatException ex) { curTegraMax = 0; } } } if (Helpers.doesFileExist(NUM_OF_CPUS)) mNumOfCpus = Helpers.getNumOfCpus(); mCurFreq = (TextView) findViewById(R.id.currspeed); mMaxSlider = (SeekBar) findViewById(R.id.max_slider); mMaxSlider.setMax(frequenciesNum); mMaxSpeedText = (TextView) findViewById(R.id.max_speed_text); mMaxSpeedText.setText(toMHz(curMaxSpeed)); mMaxSlider.setProgress(Arrays.asList(availableFrequencies).indexOf(curMaxSpeed)); mMaxSlider.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if (fromUser) setMaxSpeed(seekBar, progress); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { startSupportActionMode(new ActionMode.Callback() { @Override public boolean onCreateActionMode(ActionMode actionMode, Menu menu) { MenuInflater inflater = actionMode.getMenuInflater(); inflater.inflate(R.menu.contextual_menu, menu); return true; } @Override public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) { return false; } @Override public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) { switch (menuItem.getItemId()) { case R.id.apply: if (mMaxFreqSetting != null && !mMaxFreqSetting.isEmpty()) { bootPrefs.edit().putString("CPU_MAX_FREQ", mMaxFreqSetting).commit(); for (int i = 0; i < mNumOfCpus; i++) Helpers.CMDProcessorWrapper.runSuCommand("busybox echo " + mMaxFreqSetting + " > " + MAX_FREQ.replace("cpu0", "cpu" + i)); if (snakeCharmerEnabled) Helpers.CMDProcessorWrapper.runSuCommand( "busybox echo " + mMaxFreqSetting + " > " + SNAKE_CHARMER_MAX_FREQ); } if (mIsTegra3) { if (mMaxFreqSetting != null && !mMaxFreqSetting.isEmpty()) Helpers.CMDProcessorWrapper.runSuCommand( "busybox echo " + mMaxFreqSetting + " > " + TEGRA_MAX_FREQ); if (snakeCharmerEnabled) Helpers.CMDProcessorWrapper.runSuCommand( "busybox echo " + mMaxFreqSetting + " > " + SNAKE_CHARMER_MAX_FREQ); } actionMode.finish(); return true; default: return false; } } @Override public void onDestroyActionMode(ActionMode actionMode) { } }); } }); mMinSlider = (SeekBar) findViewById(R.id.min_slider); mMinSlider.setMax(frequenciesNum); mMinSpeedText = (TextView) findViewById(R.id.min_speed_text); mMinSpeedText.setText(toMHz(curMinSpeed)); mMinSlider.setProgress(Arrays.asList(availableFrequencies).indexOf(curMinSpeed)); mMinSlider.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if (fromUser) setMinSpeed(seekBar, progress); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { startSupportActionMode(new ActionMode.Callback() { @Override public boolean onCreateActionMode(ActionMode actionMode, Menu menu) { MenuInflater inflater = actionMode.getMenuInflater(); inflater.inflate(R.menu.contextual_menu, menu); return true; } @Override public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) { return false; } @Override public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) { switch (menuItem.getItemId()) { case R.id.apply: if (mMinFreqSetting != null && !mMinFreqSetting.isEmpty()) { bootPrefs.edit().putString("CPU_MIN_FREQ", mMinFreqSetting).commit(); for (int i = 0; i < mNumOfCpus; i++) Helpers.CMDProcessorWrapper.runSuCommand("busybox echo " + mMinFreqSetting + " > " + MIN_FREQ.replace("cpu0", "cpu" + i)); } actionMode.finish(); return true; default: return false; } } @Override public void onDestroyActionMode(ActionMode actionMode) { } }); } }); handleGovernors(); /** TCP Congestion Spinner */ Spinner mTcp = (Spinner) findViewById(R.id.tcp); ArrayAdapter<CharSequence> tcpAdapter = new ArrayAdapter<CharSequence>(this, R.layout.spinner_row); tcpAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); ArrayList<String> algorithms = Helpers.getTcpAlgorithms(); for (String algorithm : algorithms) tcpAdapter.add(algorithm); mTcp.setAdapter(tcpAdapter); mTcp.setSelection(algorithms.indexOf(currentTcp)); mTcp.setOnItemSelectedListener(new TCPListener()); onlineCoresPolling(); }
From source file:controlador.Peticiones.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.// w w w . jav a 2s . c om * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //response.setContentType("text/html;charset=UTF-8"); String target, op, action, view; target = request.getParameter("target"); op = request.getParameter("op"); if (target.equals("login")) { bd = new ControlDB(); bd.cargarDriver(); bd.conectar(); String login = request.getParameter("login"); String pass = request.getParameter("password"); ResultSet r = bd.ejecutarSelect("SELECT * FROM roles WHERE nombreRol='" + login + "' AND passRol='" + Auxiliar.encriptarPass(pass) + "'"); JSONObject objetoJSON = new JSONObject(); response.setContentType("application/json; charset=utf-8"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); try { if (r != null && r.next()) { objetoJSON.put("r", "1"); out.print(objetoJSON); } else { objetoJSON.put("r", "0"); out.print(objetoJSON); } } catch (SQLException ex) { } catch (JSONException ex) { } } else { if (target.equals("pedido")) { bd = new ControlDB(); bd.cargarDriver(); bd.conectar(); String s = request.getParameter("datos"); JSONTokener token = new JSONTokener(s); JSONArray ar = null; ArrayList<Producto> productos = new ArrayList(); try { ar = new JSONArray(token); for (int i = 0; i < ar.length(); i++) { agregarProducto(ar.getJSONObject(i).getInt("idMesa"), ar.getJSONObject(i).getInt("idProducto")); ResultSet rs = bd.ejecutarSelect("SELECT nombreProducto from productos where idProducto = " + ar.getJSONObject(i).getInt("idProducto")); rs.next(); String nombre = rs.getString("nombreProducto"); Producto pr = new Producto(nombre); if (productos.contains(pr)) { int pos = productos.indexOf(pr); productos.get(pos).sumaCantidad(); } else { productos.add(new Producto(nombre)); } } ResultSet nombreMesa = bd.ejecutarSelect( "SELECT nombreMesa, nombreZona from mesas inner join zona on idZona=Zona_Idzona where idmesa=" + ar.getJSONObject(0).getInt("idMesa")); nombreMesa.next(); String nombre = nombreMesa.getString("nombreMesa") + " " + nombreMesa.getString("nombreZona"); Comanda comanda = new Comanda(productos, nombre); System.out.println("Ticket: \n" + comanda.contenidoComanda); Auxiliar.imprimir(comanda.contenidoComanda); } catch (JSONException ex) { System.out.println("Error JSON " + ex.toString()); } catch (SQLException ex) { System.out.println("Error SQL " + ex.toString()); } // Crear un el objeto para enviar a comanda para imprimir, implementar response.setHeader("Content-Type", "application/json"); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); JSONObject obj = new JSONObject(); try { obj.put("r", "recibido"); } catch (JSONException ex) { } out.print(obj); out.flush(); } else { if (target.equals("mesas")) { bd = new ControlDB(); bd.cargarDriver(); bd.conectar(); ResultSet r = bd.ejecutarSelect( "SELECT mesas.idMesa, nombreMesa, nombreZona FROM mesas inner join zona on idzona = Zona_idZona"); JSONArray array = new JSONArray(); ResultSetMetaData rsMetaData = null; int columns = 0; try { rsMetaData = r.getMetaData(); columns = rsMetaData.getColumnCount(); } catch (SQLException ex) { } try { while (r.next()) { JSONObject objetoJSON = new JSONObject(); for (int i = 1; i <= columns; i++) { objetoJSON.put(rsMetaData.getColumnLabel(i), r.getString(i)); } System.out.println(objetoJSON + "\n"); array.put(objetoJSON); } } catch (SQLException ex) { } catch (JSONException ex) { } response.setHeader("Content-Type", "application/json"); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); out.print(array); out.flush(); } else { if (target.equals("familias")) { bd = new ControlDB(); bd.cargarDriver(); bd.conectar(); ResultSet r = bd.ejecutarSelect( "SELECT idFamilia, nombreFamilia FROM `familias` order by idFamilia"); JSONArray array = new JSONArray(); ResultSetMetaData rsMetaData = null; int columns = 0; try { rsMetaData = r.getMetaData(); columns = rsMetaData.getColumnCount(); } catch (SQLException ex) { } try { while (r.next()) { JSONObject objetoJSON = new JSONObject(); for (int i = 1; i <= columns; i++) { objetoJSON.put(rsMetaData.getColumnLabel(i), r.getString(i)); } array.put(objetoJSON); } } catch (SQLException ex) { } catch (JSONException ex) { ; } response.setHeader("Content-Type", "application/json"); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); out.print(array); out.flush(); } else { if (target.equals("productos")) { bd = new ControlDB(); bd.cargarDriver(); bd.conectar(); ResultSet r = bd.ejecutarSelect( "SELECT idProducto, nombreProducto,fotoProducto , precioProducto, Familias_idFamilias FROM productos order by idProducto"); JSONArray array = new JSONArray(); ResultSetMetaData rsMetaData = null; int columns = 0; try { rsMetaData = r.getMetaData(); columns = rsMetaData.getColumnCount(); } catch (SQLException ex) { } try { while (r.next()) { JSONObject objetoJSON = new JSONObject(); for (int i = 1; i <= columns; i++) { objetoJSON.put(rsMetaData.getColumnLabel(i), r.getString(i)); } array.put(objetoJSON); } } catch (SQLException ex) { } catch (JSONException ex) { } response.setHeader("Content-Type", "application/json"); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); out.print(array); out.flush(); } } } } } }
From source file:de.tud.kom.p2psim.impl.network.gnp.topology.GnpSpace.java
/** * /*from w ww .j a v a 2 s. c om*/ * @param noOfDimensions * number of Dimensions must be smaller than number of Monitors * @param monitorResheduling * number of rescheduling the downhill simplex * @param mapRef * reference to HostMap * @return optimized positions for Monitors */ private static GnpSpace getGnpWithDownhillSimplex(int noOfDimensions, int monitorResheduling, HostMap mapRef) { GnpSpace.calculationStepStatus = 1; GnpSpace.calculationInProgress = true; double alpha = 1.0; double beta = 0.5; double gamma = 2; double maxDiversity = 0.5; // N + 1 initial random Solutions int dhs_N = mapRef.getNoOfMonitors(); ArrayList<GnpSpace> solutions = new ArrayList<GnpSpace>(dhs_N + 1); for (int c = 0; c < dhs_N + 1; c++) solutions.add(new GnpSpace(noOfDimensions, mapRef)); // best and worst solution GnpSpace bestSolution = Collections.min(solutions); GnpSpace worstSolution = Collections.max(solutions); double bestError = bestSolution.getObjectiveValueMonitor(); double worstError = worstSolution.getObjectiveValueMonitor(); for (int z = 0; z < monitorResheduling; z++) { GnpSpace.calculationProgressStatus = z; // resheduling int count = 0; for (GnpSpace gnp : solutions) { if (gnp != bestSolution) { GnpPosition monitor = gnp.getMonitorPosition(count); monitor.diversify(gnp.getDimension(), maxDiversity); count++; } } // best and worst solution bestSolution = Collections.min(solutions); worstSolution = Collections.max(solutions); bestError = bestSolution.getObjectiveValueMonitor(); worstError = worstSolution.getObjectiveValueMonitor(); // stop criterion while (worstError - bestError > 0.00001 && calculationInProgress) { // move to center ... GnpSpace center = GnpSpace.getCenterSolution(solutions); GnpSpace newSolution1 = GnpSpace.getMovedSolution(worstSolution, center, 1 + alpha); double newError1 = newSolution1.getObjectiveValueMonitor(); if (newError1 <= bestError) { int IndexOfWorstSolution = solutions.indexOf(worstSolution); GnpSpace newSolution2 = GnpSpace.getMovedSolution(worstSolution, center, 1 + alpha + gamma); double newError2 = newSolution2.getObjectiveValueMonitor(); if (newError2 <= newError1) { solutions.set(IndexOfWorstSolution, newSolution2); bestError = newError2; } else { solutions.set(IndexOfWorstSolution, newSolution1); bestError = newError1; } bestSolution = solutions.get(IndexOfWorstSolution); } else if (newError1 < worstError) { int IndexOfWorstSolution = solutions.indexOf(worstSolution); solutions.set(IndexOfWorstSolution, newSolution1); } else { // ... or contract around best solution for (int c = 0; c < solutions.size(); c++) { if (solutions.get(c) != bestSolution) solutions.set(c, GnpSpace.getMovedSolution(solutions.get(c), bestSolution, beta)); } bestSolution = Collections.min(solutions); bestError = bestSolution.getObjectiveValueMonitor(); } worstSolution = Collections.max(solutions); worstError = worstSolution.getObjectiveValueMonitor(); } } // Set the Coordinate Reference to the Peer for (int c = 0; c < bestSolution.getNumberOfMonitors(); c++) { bestSolution.getMonitorPosition(c).getHostRef() .setPositionReference(bestSolution.getMonitorPosition(c)); } // GnpSpace.calculationStepStatus = 0; // GnpSpace.calculationInProgress = false; return bestSolution; }
From source file:com.ntua.cosmos.hackathonplanneraas.Planner.java
@Deprecated public String retrieveValueOfProb(ArrayList<String> info, ArrayList<String> solutionAttributes, String valueSearched) {/*from w w w . ja v a 2s .com*/ //to be refined!!!!!!!!!!!!!!!! NOT ONLY CONSUMPTION BUT OTHERS LIKE URI AND MESSAGE StoredPaths pan = new StoredPaths(); int size = 0; String probVar = ""; ArrayList<String> solutionValue = new ArrayList<>(); for (String in : info) { if (info.indexOf(in) == info.size() - 4) { break; } else { solutionValue.add(info.get(info.indexOf(in))); } } //Begin the initialisation process. OntModelSpec s = new OntModelSpec(PelletReasonerFactory.THE_SPEC); OntDocumentManager dm = OntDocumentManager.getInstance(); dm.setFileManager(FileManager.get()); s.setDocumentManager(dm); OntModel m = ModelFactory.createOntologyModel(s, null); InputStream in = FileManager.get().open(StoredPaths.casebasepath); if (in == null) { throw new IllegalArgumentException("File: " + StoredPaths.casebasepath + " not found"); } // read the file m.read(in, null); //begin building query string. String queryString = pan.prefixrdf + pan.prefixowl + pan.prefixxsd + pan.prefixrdfs + pan.prefixCasePath; queryString += "\nSELECT distinct ?sol ?prob ?returned WHERE { ?sol base:hasCaseType \"solution\"^^xsd:string ."; for (int i = 0; i < solutionValue.size(); i++) { queryString += " ?param" + i + " a owl:DatatypeProperty ."; } for (int i = 0; i < solutionValue.size(); i++) { queryString += " ?sol ?param" + i + " ?value" + i + " ."; } queryString += " ?sol base:solves ?prob . ?prob base:" + valueSearched + " ?returned ."; for (int i = 0; i < solutionValue.size(); i++) { queryString += " filter regex(str(?param" + i + "), \"^http://www.localstore.casebase.com/CaseBaseOntology#" + solutionAttributes.get(i) + "$\") "; queryString += " filter regex(str(?value" + i + "), \"^" + solutionValue.get(i) + "$\") "; } queryString += "}"; //!!!ATTENTION exact regex string match requires ^ and $ to match the ENTIRE word, else it acts as if searching anything that contains //The above query checks for problems containing the datatypes hasTin, hasTout and hasTdes! //the real way to make it agnostic is to pass each solution variable and use regexes for each one value //PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> //PREFIX owl: <http://www.w3.org/2002/07/owl#> //PREFIX xsd: <http://www.w3.org/2001/XMLSchema#> //PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> //PREFIX base: <http://www.localstore.casebase.com/CaseBaseOntology#> // //SELECT distinct ?sol ?prob ?returned WHERE { // ?sol base:hasCaseType "solution"^^xsd:string . // ?param0 a owl:DatatypeProperty . // ?param1 a owl:DatatypeProperty . // ?sol ?param0 ?value0 . // ?sol ?param1 ?value1 . // ?sol base:solves ?prob . // ?prob base:hasTdes ?returned . // filter regex(str(?param0), "^http://www.localstore.casebase.com/CaseBaseOntology#hasConsumption$" ) . // filter regex(str(?value0), "^630$") . // filter regex(str(?param1), "^http://www.localstore.casebase.com/CaseBaseOntology#exposesMessage$" ) . // filter regex(str(?value1), "^message to differ$" ) //} System.out.println("***************************************"); System.out.println("Query String used: "); System.out.println(queryString); System.out.println("***************************************\n\n"); try { Query query = QueryFactory.create(queryString); QueryExecution qe = QueryExecutionFactory.create(query, m); ResultSet results = qe.execSelect(); size = results.getRowNumber(); for (; results.hasNext();) { QuerySolution soln = results.nextSolution(); // Access variables: soln.get("x"); Literal lit; lit = soln.getLiteral("returned"); probVar = lit.getString(); } qe.close(); } catch (NumberFormatException e) { System.out.println("Query not valid."); } m.close(); System.out.println("Variable value returned is: " + probVar); return probVar; }
From source file:org.structr.core.entity.SchemaRelationshipNode.java
private void renameNameInNonGraphProperties(final AbstractSchemaNode schemaNode, final String toRemove, final String newValue) throws FrameworkException { // examine all views for (final SchemaView view : schemaNode.getSchemaViews()) { final String nonGraphProperties = view.getProperty(SchemaView.nonGraphProperties); if (nonGraphProperties != null) { final ArrayList<String> properties = new ArrayList<>( Arrays.asList(nonGraphProperties.split("[, ]+"))); final int pos = properties.indexOf(toRemove); if (pos != -1) { properties.set(pos, newValue); }//from w ww . java2 s . co m view.setProperty(SchemaView.nonGraphProperties, StringUtils.join(properties, ", ")); } } }