List of usage examples for java.util ArrayList indexOf
public int indexOf(Object o)
From source file:com.thoughtworks.go.server.service.PipelineConfigServicePerformanceTest.java
private void run(Runnable runnable, int numberOfRequests, final ConcurrentHashMap<String, Boolean> results) throws InterruptedException { Boolean finalResult = true;//from w ww . j a v a 2s. c o m LOGGER.info("Tests start now!"); final ArrayList<Thread> threads = new ArrayList<>(); for (int i = 0; i < numberOfRequests; i++) { Thread t = new Thread(runnable, "pipeline" + i); threads.add(t); } for (Thread t : threads) { Thread.sleep(1000 * (new Random().nextInt(3) + 1)); t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { public void uncaughtException(Thread t, Throwable e) { LOGGER.error("Exception " + e + " from thread " + t); results.put(t.getName(), false); } }); t.start(); } for (Thread t : threads) { int i = threads.indexOf(t); if (i == (numberOfRequests - 1)) { // takeHeapDump(dumpDir, i); } t.join(); } for (String threadId : results.keySet()) { finalResult = results.get(threadId) && finalResult; } assertThat(finalResult, is(true)); }
From source file:in.andres.kandroid.ui.TaskEditActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_task_edit); setupActionBar();/*from w w w . j a va2s .c o m*/ editTextTitle = (EditText) findViewById(R.id.edit_task_title); editTextDescription = (EditText) findViewById(R.id.edit_task_description); btnStartDate = (Button) findViewById(R.id.btn_start_date); btnDueDate = (Button) findViewById(R.id.btn_due_date); btnColor = (Button) findViewById(R.id.color_button); btnColor.setOnClickListener(btnColorClick); btnColor.setText(Utils.fromHtml(getString(R.string.taskedit_color, ""))); editHoursEstimated = (EditText) findViewById(R.id.edit_hours_estimated); editHoursSpent = (EditText) findViewById(R.id.edit_hours_spent); spinnerProjectUsers = (Spinner) findViewById(R.id.user_spinner); if (getIntent().hasExtra("task")) { isNewTask = false; task = (KanboardTask) getIntent().getSerializableExtra("task"); taskTitle = task.getTitle(); taskDescription = task.getDescription(); startDate = task.getDateStarted(); dueDate = task.getDateDue(); timeEstimated = task.getTimeEstimated(); timeSpent = task.getTimeSpent(); ownerId = task.getOwnerId(); colorId = task.getColorId(); setActionBarTitle(getString(R.string.taskview_fab_edit_task)); } else { isNewTask = true; projectid = getIntent().getIntExtra("projectid", 0); // colorId = getIntent().getIntExtra("colorid", 0); creatorId = getIntent().getIntExtra("creatorid", 0); ownerId = getIntent().getIntExtra("ownerid", 0); columnId = getIntent().getIntExtra("columnid", 0); swimlaneId = getIntent().getIntExtra("swimlaneid", 0); setActionBarTitle(getString(R.string.taskedit_new_task)); } SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this.getBaseContext()); try { kanboardAPI = new KanboardAPI(preferences.getString("serverurl", ""), preferences.getString("username", ""), preferences.getString("password", "")); kanboardAPI.addOnCreateTaskListener(this); kanboardAPI.addOnUpdateTaskListener(this); kanboardAPI.addOnGetDefaultColorListener(this); kanboardAPI.addOnGetDefaultColorsListener(this); kanboardAPI.addOnGetVersionListener(this); kanboardAPI.getDefaultTaskColor(); kanboardAPI.getDefaultTaskColors(); kanboardAPI.getVersion(); } catch (IOException e) { e.printStackTrace(); } if (getIntent().hasExtra("projectusers")) { if (getIntent().getSerializableExtra("projectusers") instanceof HashMap) { projectUsers = new Hashtable<>( (HashMap<Integer, String>) getIntent().getSerializableExtra("projectusers")); ArrayList<String> possibleOwners = Collections.list(projectUsers.elements()); possibleOwners.add(0, ""); ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, possibleOwners); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinnerProjectUsers.setAdapter(adapter); if (ownerId != 0) { spinnerProjectUsers.setSelection(possibleOwners.indexOf(projectUsers.get(ownerId))); } } } editTextTitle.setText(taskTitle); editTextDescription.setText(taskDescription); editHoursEstimated.setText(Double.toString(timeEstimated)); editHoursSpent.setText(Double.toString(timeSpent)); btnStartDate.setText(Utils.fromHtml(getString(R.string.taskview_date_start, startDate))); btnDueDate.setText(Utils.fromHtml(getString(R.string.taskview_date_due, dueDate))); btnStartDate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Calendar calendar = Calendar.getInstance(); if (startDate != null) calendar.setTime(startDate); DatePickerDialog dlgDate = new DatePickerDialog(TaskEditActivity.this, new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) { Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.YEAR, year); calendar.set(Calendar.MONTH, month); calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth); startDate = calendar.getTime(); btnStartDate.setText( Utils.fromHtml(getString(R.string.taskview_date_start, startDate))); } }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)); dlgDate.setButton(DatePickerDialog.BUTTON_NEUTRAL, getString(R.string.taskedit_clear_date), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { startDate = null; btnStartDate.setText( Utils.fromHtml(getString(R.string.taskview_date_start, startDate))); } }); dlgDate.show(); } }); btnDueDate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Calendar calendar = Calendar.getInstance(); if (dueDate != null) calendar.setTime(dueDate); DatePickerDialog dlgDate = new DatePickerDialog(TaskEditActivity.this, new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) { Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.YEAR, year); calendar.set(Calendar.MONTH, month); calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth); dueDate = calendar.getTime(); btnDueDate.setText(Utils.fromHtml(getString(R.string.taskview_date_due, dueDate))); } }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)); dlgDate.setButton(DatePickerDialog.BUTTON_NEUTRAL, getString(R.string.taskedit_clear_date), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dueDate = null; btnDueDate.setText(Utils.fromHtml(getString(R.string.taskview_date_due, dueDate))); } }); dlgDate.show(); } }); }
From source file:com.ess.tudarmstadt.de.sleepsense.mgraph.SleepEstimGPlotFragment.java
/** * //from w w w . jav a 2 s. c o m * @param i * 0, 1 or -1 * @return current, next or prev date on database */ private String getDate(int i, String currentDate) { ArrayList<String> avalDate = new ArrayList<String>(); LocalTransformationDBMS transformationDB = new LocalTransformationDBMS( getActivity().getApplicationContext()); transformationDB.open(); avalDate = transformationDB.getAllAvalDate(); transformationDB.close(); if (avalDate.isEmpty()) { Log.e(TAG, "no data available!!"); avalDate.add(getCurrentDate()); } int x = avalDate.indexOf(currentDate); if (i == -2) { Calendar c = Calendar.getInstance(); int hour_of_day = c.get(Calendar.HOUR_OF_DAY); if (hour_of_day < 20 && avalDate.size() >= 2) return avalDate.get(avalDate.size() - 2); return avalDate.get(avalDate.size() - 1); // last date (special case) } if (x >= 0) { if (i == 1 && x < avalDate.size() - 1) return avalDate.get(x + i); if (i == -1 && x > 0) return avalDate.get(x + i); } else { if (i == -1) { return avalDate.get(avalDate.size() - 1); // last date } if (i == -1) { return avalDate.get(0); // last date } } return currentDate; }
From source file:org.rti.zcore.dar.struts.action.DeleteEncounterAction.java
/** * Special handling for form id 170 - user info form. *///from w ww .j av a2 s. c om protected ActionForward doExecute(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(); Site site = SessionUtil.getInstance(session).getClientSettings().getSite(); Principal user = request.getUserPrincipal(); String username = user.getName(); Connection conn = null; Long encounterId = null; String userrecord = null; Long patientId = null; Long formId = null; String formName = null; Integer deps = null; String forwardString = null; // Pass forward if you want to override the forward. if (request.getParameter("formId") != null) { formId = Long.valueOf(request.getParameter("formId")); formName = DynaSiteObjects.getFormIdClassNameMap().get(formId); } //formId = (Long) DynaSiteObjects.getFormNameMap().get(formName); if (request.getParameter("encounterId") != null) { //if (formName.equals("UserInfo")) { // userrecord = String.valueOf(request.getParameter("encounterId")); //} else { encounterId = Long.valueOf(request.getParameter("encounterId")); //} } if (request.getParameter("patientId") != null) { patientId = Long.valueOf(request.getParameter("patientId")); } if (request.getParameter("deps") != null) { deps = Integer.valueOf(request.getParameter("deps")); } if (request.getParameter("forward") != null) { forwardString = String.valueOf(request.getParameter("forward")); } Form form = (Form) DynaSiteObjects.getForms().get(Long.valueOf(formId)); try { conn = DatabaseUtils.getZEPRSConnection(Constants.DATABASE_ADMIN_USERNAME); //if ((encounterId != null && formId != null) || formId == 170) { if (encounterId != null) { EncounterData encounter = null; try { //if (formName.equals("UserInfo")) { // PatientRecordUtils.deleteUser(conn, userrecord); //} else { // If this is a MenuItem, save the MenuItem list to xml and refresh DynasiteObjects formName = form.getClassname(); if (!formName.equals("MenuItem")) { try { encounter = (EncounterData) EncountersDAO.getOneById(conn, encounterId); } catch (ObjectNotFoundException e) { // it's ok - may be an admin record. } String eventUuid = null; if (encounter != null) { if (patientId == null) { patientId = encounter.getPatientId(); } else { if (encounter.getPatientId() == null) { // this is an admin form - probably a relationship. encounter.setPatientId(patientId); } } //Long eventId = encounter.getEventId(); eventUuid = encounter.getEventUuid(); formId = encounter.getFormId(); // this could be an admin record, which is will not have patientId or pregnancyId if (patientId != null) { //PatientStatusReport psr = PatientStatusDAO.getOne(conn, patientId); Patient patient = PatientDAO.getOne(conn, patientId); //Long currentFlowEncounterId = patient.getCurrentFlowEncounterId(); String currentFlowEncounterUuid = patient.getCurrentFlowEncounterUuid(); if (formId.longValue() == 1) { String message = "You may not delete the patient registration record. " + "Delete the whole patient record instead by clicking the \"Delete Patient\" link\n" + "on the Demographics page."; request.setAttribute("exception", message); return mapping.findForward("error"); } List outcomes = OutcomeDAO.getAllforEncounter(conn, encounterId); if (outcomes.size() > 0) { if (deps != null && deps.intValue() == 1) { for (int i = 0; i < outcomes.size(); i++) { OutcomeImpl outcome = (OutcomeImpl) outcomes.get(i); OutcomeDAO.deleteOne(conn, outcome.getId()); } } else { String url = "/" + Constants.APP_NAME + "/admin/deleteEncounter.do;jsessionid=" + session.getId() + "?encounterId=" + encounterId + "&formId=" + formName + "&deps=1"; String message = "<p>This record has system-generated problems. " + "Are you sure you want to delete it?.</p>" + "<p><a href=\"" + url + "\">Delete</a></p>"; request.setAttribute("exception", message); return mapping.findForward("error"); } } // Test to see if you are deleting the most recent encounter. //if (encounterId.longValue() == currentFlowEncounterId.longValue()) { if (encounter.getUuid().equals(currentFlowEncounterUuid)) { // Find the previous encounter EncounterData encounterData = EncountersDAO.getPreviousEncounter(conn, patientId, eventUuid, encounterId); Long prevEncId = encounterData.getId(); if (prevEncId != null) { // re-assign values in patient status Long currentFlowId = encounterData.getFlowId(); Map queries = QueryLoader.instance() .load("/" + Constants.SQL_PATIENT_PROPERTIES); String sqlUpdateStatus = (String) queries.get("SQL_MODIFY_STATUS"); EncounterData vo = new EncounterData(); // dummy EncounterData is OK. vo.setUuid(encounterData.getUuid()); PatientStatusDAO.updatePatientStatus(conn, vo, currentFlowId, prevEncId, username, site.getId(), patientId, sqlUpdateStatus); } else { String message = "Unable to delete this record - please contact the system administrator. "; request.setAttribute("exception", message); return mapping.findForward("error"); } } } } EncounterData vo = new EncounterData(); // dummy EncounterData is OK. vo.setPatientId(patientId); //vo.setEventId(eventId); vo.setEventUuid(eventUuid); // DAR-specific code for stock and regimen-related forms - deletes only its associated table record if (formId == 128 || formId == 129 || formId == 130 || formId == 131 || formId == 181) { deleteFromSingleTable(site, username, conn, encounterId, formId, encounter); } else { try { PatientRecordUtils.deleteEncounter(conn, formId, encounterId, username, site, vo, null); } catch (Exception e) { request.setAttribute("exception", e); return mapping.findForward("error"); } } } else { // If this is a MenuItem, save the MenuItem list to xml and refresh DynasiteObjects ArrayList<MenuItem> menuItemList = DynaSiteObjects.getMenuItemList(); int index = 0; for (MenuItem menuItem : menuItemList) { if (encounterId.intValue() == menuItem.getId().intValue()) { index = menuItemList.indexOf(menuItem); //EncounterData encounterMenuItem = (EncounterData) EncountersDAO.getOne(conn, encounterId, "SQL_RETRIEVE_ONE_ADMIN" + formId, MenuItem.class); //MenuItem menuItem = (MenuItem) encounterMenuItem; String templateKey = menuItem.getTemplateKey(); //ignore property files for spacer deletion if (templateKey != null) { Boolean dev = DynaSiteObjects.getDev(); String pathName = null; String deployPathname = null; if (dev == true) { pathName = Constants.DEV_RESOURCES_PATH; deployPathname = Constants.DYNASITE_RESOURCES_PATH; } else { pathName = Constants.DYNASITE_RESOURCES_PATH; } SortedProperties properties = null; ApplicationDefinition applicationDefinition = DynaSiteObjects .getApplicationDefinition(); ArrayList<String> localeList = applicationDefinition.getLocalList(); ; //loop through all property fields and delete this property if (applicationDefinition != null) { localeList = applicationDefinition.getLocalList(); properties = new SortedProperties(); for (String locale : localeList) { try { properties.load( new FileInputStream(pathName + Constants.MENU_ITEM_FILENAME + "_" + locale + ".properties")); properties.remove(templateKey); properties.store( new FileOutputStream(pathName + Constants.MENU_ITEM_FILENAME + "_" + locale + ".properties"), "Deletion by admin"); properties.clear(); } catch (Exception e) { } } properties.clear(); String defaultLocale = applicationDefinition.getDefaultLocale(); if (defaultLocale != null) { try { properties.load( new FileInputStream(pathName + Constants.MENU_ITEM_FILENAME + "_" + defaultLocale + ".properties")); properties.remove(templateKey); properties.store( new FileOutputStream(pathName + Constants.MENU_ITEM_FILENAME + "_" + defaultLocale + ".properties"), "Deletion by admin"); properties.clear(); } catch (FileNotFoundException e) { // not created yet. } } properties.clear(); properties.load(new FileInputStream( pathName + Constants.MENU_ITEM_FILENAME + ".properties")); properties.remove(templateKey); properties.store( new FileOutputStream( pathName + Constants.MENU_ITEM_FILENAME + ".properties"), "Deletion by admin"); properties.clear(); } //Properties properties = new Properties(); String selectedLocale = (String) request.getAttribute("defaultLocale"); boolean isDefaultLocale = false; try { properties.load(new FileInputStream(pathName + Constants.MENU_ITEM_FILENAME + "_" + selectedLocale + ".properties")); //isDefaultLocale = true; } catch (FileNotFoundException e) { try { properties.load(new FileInputStream( pathName + Constants.MENU_ITEM_FILENAME + ".properties")); } catch (FileNotFoundException e1) { e.printStackTrace(); } } properties.remove(templateKey); properties.store(new FileOutputStream(pathName + Constants.MENU_ITEM_FILENAME + (isDefaultLocale ? "_" + selectedLocale : "") + ".properties"), "New Entry"); // copy to tomcat as well if in dev mode if (dev) { for (String locale : localeList) { try { FileUtils.copyQuick( pathName + Constants.MENU_ITEM_FILENAME + "_" + locale + ".properties", deployPathname + Constants.MENU_ITEM_FILENAME + "_" + locale + ".properties"); } catch (Exception e) { } try { FileUtils.copyQuick( pathName + Constants.MENU_ITEM_FILENAME + ".properties", deployPathname + Constants.MENU_ITEM_FILENAME + ".properties"); } catch (Exception e) { e.printStackTrace(); } } } } } } menuItemList.remove(index); DisplayOrderComparator doc = new DisplayOrderComparator(); Collections.sort(menuItemList, doc); DynasiteUtils.refreshMenuItemList(); } //} // part of reload prevention scheme: resetToken(request); StrutsUtils.removeFormBean(mapping, request); // return mapping.findForward("patientHome"); ActionForward forwardForm = null; if (forwardString != null) { forwardForm = new ActionForward(forwardString); forwardForm.setRedirect(true); } else { forwardForm = StrutsUtils.getActionForward("deleteEncounter", patientId, form); } return forwardForm; } catch (ServletException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } catch (ObjectNotFoundException e) { // already deleted or missing - simply send back to home. return mapping.findForward("home"); } } } catch (Exception e) { e.printStackTrace(); request.setAttribute("exception", e); return mapping.findForward("error"); } finally { if (conn != null && !conn.isClosed()) { conn.close(); } } return mapping.findForward("success"); }
From source file:structuredPredictionNLG.DatasetParser.java
/** * * @param attribute//w ww.j a v a 2 s . c om * @param attrValuesToBeMentioned * @return */ public String chooseNextValue(String attribute, HashSet<String> attrValuesToBeMentioned) { HashMap<String, Integer> relevantValues = new HashMap<>(); attrValuesToBeMentioned.stream().forEach((attrValue) -> { String attr = attrValue.substring(0, attrValue.indexOf('=')); String value = attrValue.substring(attrValue.indexOf('=') + 1); if (attr.equals(attribute)) { relevantValues.put(value, 0); } }); if (!relevantValues.isEmpty()) { if (relevantValues.keySet().size() == 1) { for (String value : relevantValues.keySet()) { return value; } } else { String bestValue = ""; int minIndex = Integer.MAX_VALUE; for (String value : relevantValues.keySet()) { if (value.startsWith("x")) { int vI = Integer.parseInt(value.substring(1)); if (vI < minIndex) { minIndex = vI; bestValue = value; } } } if (!bestValue.isEmpty()) { return bestValue; } for (ArrayList<String> mentionedValueSeq : observedAttrValueSequences) { boolean doesSeqContainValues = true; minIndex = Integer.MAX_VALUE; for (String value : relevantValues.keySet()) { int index = mentionedValueSeq.indexOf(attribute + "=" + value); if (index != -1 && index < minIndex) { minIndex = index; bestValue = value; } else if (index == -1) { doesSeqContainValues = false; } } if (doesSeqContainValues) { relevantValues.put(bestValue, relevantValues.get(bestValue) + 1); } } int max = -1; for (String value : relevantValues.keySet()) { if (relevantValues.get(value) > max) { max = relevantValues.get(value); bestValue = value; } } return bestValue; } } return ""; }
From source file:im.neon.util.VectorUtils.java
/** * List the URLs in a text./*www .j av a2s .c o m*/ * * @param text the text to parse * @return the list of URLss */ public static List<String> listURLs(String text) { ArrayList<String> URLs = new ArrayList<>(); // sanity checks if (!TextUtils.isEmpty(text)) { Matcher matcher = mUrlPattern.matcher(text); while (matcher.find()) { int matchStart = matcher.start(1); int matchEnd = matcher.end(); String charBef = ""; String charAfter = ""; if (matchStart > 2) { charBef = text.substring(matchStart - 2, matchStart); } if ((matchEnd - 1) < text.length()) { charAfter = text.substring(matchEnd - 1, matchEnd); } // keep the link between parenthesis, it might be a link [title](link) if (!TextUtils.equals(charAfter, ")") || !TextUtils.equals(charBef, "](")) { String url = text.substring(matchStart, matchEnd); if (URLs.indexOf(url) < 0) { URLs.add(url); } } } } return URLs; }
From source file:org.dkpro.tc.ml.weka.util.WekaUtils.java
/** * Adapts the test data class labels to the training data. Class labels from the test data * unseen in the training data will be deleted from the test data. Class labels from the * training data unseen in the test data will be added to the test data. If training and test * class labels are equal, nothing will be done. *///from w ww . ja v a 2 s . c om @SuppressWarnings({ "rawtypes", "unchecked" }) public static Instances makeOutcomeClassesCompatible(Instances trainData, Instances testData, boolean multilabel) throws Exception { // new (compatible) test data Instances compTestData = null; // ================ SINGLE LABEL BRANCH ====================== if (!multilabel) { // retrieve class labels Enumeration trainOutcomeValues = trainData.classAttribute().enumerateValues(); Enumeration testOutcomeValues = testData.classAttribute().enumerateValues(); ArrayList trainLabels = Collections.list(trainOutcomeValues); ArrayList testLabels = Collections.list(testOutcomeValues); // add new outcome class attribute to test data Add addFilter = new Add(); addFilter.setNominalLabels(StringUtils.join(trainLabels, ',')); addFilter.setAttributeName(Constants.CLASS_ATTRIBUTE_NAME + COMPATIBLE_OUTCOME_CLASS); addFilter.setInputFormat(testData); testData = Filter.useFilter(testData, addFilter); // fill NEW test data with values from old test data plus the new class attribute compTestData = new Instances(testData, testData.numInstances()); for (int i = 0; i < testData.numInstances(); i++) { weka.core.Instance instance = testData.instance(i); String label = (String) testLabels.get((int) instance.value(testData.classAttribute())); if (trainLabels.indexOf(label) != -1) { instance.setValue(testData.attribute(Constants.CLASS_ATTRIBUTE_NAME + COMPATIBLE_OUTCOME_CLASS), label); } else { instance.setMissing(testData.classIndex()); } compTestData.add(instance); } // remove old class attribute Remove remove = new Remove(); remove.setAttributeIndices( Integer.toString(compTestData.attribute(Constants.CLASS_ATTRIBUTE_NAME).index() + 1)); remove.setInvertSelection(false); remove.setInputFormat(compTestData); compTestData = Filter.useFilter(compTestData, remove); // set new class attribute compTestData .setClass(compTestData.attribute(Constants.CLASS_ATTRIBUTE_NAME + COMPATIBLE_OUTCOME_CLASS)); } // ================ MULTI LABEL BRANCH ====================== else { int numTrainLabels = trainData.classIndex(); int numTestLabels = testData.classIndex(); ArrayList<String> trainLabels = getLabels(trainData); // ArrayList<String> testLabels = getLabels(testData); // add new outcome class attributes to test data Add filter = new Add(); for (int i = 0; i < numTrainLabels; i++) { // numTestLabels +i (because index starts from 0) filter.setAttributeIndex(new Integer(numTestLabels + i + 1).toString()); filter.setNominalLabels("0,1"); filter.setAttributeName(trainData.attribute(i).name() + COMPATIBLE_OUTCOME_CLASS); filter.setInputFormat(testData); testData = Filter.useFilter(testData, filter); } // fill NEW test data with values from old test data plus the new class attributes compTestData = new Instances(testData, testData.numInstances()); for (int i = 0; i < testData.numInstances(); i++) { weka.core.Instance instance = testData.instance(i); // fullfill with 0. for (int j = 0; j < numTrainLabels; j++) { instance.setValue(j + numTestLabels, 0.); } // fill the real values: for (int j = 0; j < numTestLabels; j++) { // part of train data: forget labels which are not part of the train data if (trainLabels.indexOf(instance.attribute(j).name()) != -1) { // class label found in test data int index = trainLabels.indexOf(instance.attribute(j).name()); instance.setValue(index + numTestLabels, instance.value(j)); } } compTestData.add(instance); } // remove old class attributes for (int i = 0; i < numTestLabels; i++) { Remove remove = new Remove(); remove.setAttributeIndices("1"); remove.setInvertSelection(false); remove.setInputFormat(compTestData); compTestData = Filter.useFilter(compTestData, remove); } // adapt header and set new class label String relationTag = compTestData.relationName(); compTestData.setRelationName( relationTag.substring(0, relationTag.indexOf("-C") + 2) + " " + numTrainLabels + " "); compTestData.setClassIndex(numTrainLabels); } return compTestData; }
From source file:com.androguide.honamicontrol.kernel.voltagecontrol.VoltageActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //noinspection ConstantConditions getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setIcon(getResources().getDrawable(R.drawable.ic_tools_voltage_control)); setContentView(R.layout.cardsui);/*w ww. ja va2 s. c om*/ final SharedPreferences bootPrefs = getSharedPreferences("BOOT_PREFS", 0); CardUI cardsUI = (CardUI) findViewById(R.id.cardsui); cardsUI.addStack(new CardStack("")); cardsUI.addStack(new CardStack(getString(R.string.voltage_control).toUpperCase())); if (Helpers.doesFileExist(UV_MV_TABLE)) { cardsUI.addCard( new CardTextStripe(getString(R.string.warning), getString(R.string.voltage_warning_text), getString(R.string.play_orange), getString(R.string.play_orange), false)); final ArrayList<Integer> applicableVoltages = new ArrayList<Integer>(); for (int i = 500; i < 1100; i += 5) { applicableVoltages.add(i); } String rawUvTable = CPUHelper.readFileViaShell(UV_MV_TABLE, false); String[] splitTable = rawUvTable.split("\n"); final ArrayList<Integer> currentApplicableTable = new ArrayList<Integer>(); // Counters to avoid applying voltage when launching the activity final int[] spinnerCounters = new int[splitTable.length]; for (int i = 0; i < splitTable.length; i++) spinnerCounters[i] = 0; Boolean areDefaultsSaved = false; String[] defaultTable = new String[splitTable.length]; if (!bootPrefs.getString("DEFAULT_VOLTAGE_TABLE", "null").equals("null")) { areDefaultsSaved = true; defaultTable = bootPrefs.getString("DEFAULT_VOLTAGE_TABLE", "null").split(" "); Log.e("Default Table", "Def Table Size: " + defaultTable.length + " // Default Table: " + bootPrefs.getString("DEFAULT_VOLTAGE_TABLE", "null")); } // for each frequency scaling step we add a card for (int i = 0; i < splitTable.length; i++) { // format each line into a frequency in MHz & a voltage in mV String[] separateFreqFromVolts = splitTable[i].split(":"); String freqLabel = separateFreqFromVolts[0].replace("mhz", " MHz:"); String intVoltage = separateFreqFromVolts[1].replaceAll("mV", ""); intVoltage = intVoltage.replaceAll(" ", ""); int currStepVoltage = Integer.valueOf(intVoltage); currentApplicableTable.add(currStepVoltage); ArrayList<String> possibleVoltages = new ArrayList<String>(); if (areDefaultsSaved) { for (int k = 500; k < 1100; k += 5) { if (k == Integer.valueOf(defaultTable[i])) possibleVoltages.add(k + " mV (default)"); else possibleVoltages.add(k + " mV"); } } else { for (int k = 500; k < 1100; k += 5) { if (k == currStepVoltage) possibleVoltages.add(k + " mV (default)"); else possibleVoltages.add(k + " mV"); } } int currIndex = possibleVoltages.indexOf(currStepVoltage + " mV (default)"); if (currIndex == -1) currIndex = possibleVoltages.indexOf(currStepVoltage + " mV"); final int currStep = i; cardsUI.addCard(new CardSpinnerVoltage("", freqLabel, "#1abc9c", "", currIndex, possibleVoltages, this, new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int pos, long l) { if (spinnerCounters[currStep] > 0) { String toApply = "busybox echo \""; String defaultTable = ""; currentApplicableTable.set(currStep, applicableVoltages.get(pos)); for (int j = 0; j < currentApplicableTable.size(); j++) { if (j == 0) { toApply += currentApplicableTable.get(j); defaultTable += currentApplicableTable.get(j); } else { toApply += " " + currentApplicableTable.get(j); defaultTable += " " + currentApplicableTable.get(j); } } toApply += "\" > " + UV_MV_TABLE; CMDProcessor.runSuCommand(toApply); bootPrefs.edit().putString("CURRENT_VOLTAGE_TABLE", defaultTable).commit(); Log.e("toApply", toApply); } else spinnerCounters[currStep]++; } @Override public void onNothingSelected(AdapterView<?> adapterView) { } })); } if (bootPrefs.getString("DEFAULT_VOLTAGE_TABLE", "null").equals("null")) { String table = ""; for (int j = 0; j < currentApplicableTable.size(); j++) { if (j == 0) table += currentApplicableTable.get(j); else table += " " + currentApplicableTable.get(j); } bootPrefs.edit().putString("DEFAULT_VOLTAGE_TABLE", table).commit(); } } cardsUI.refresh(); }
From source file:com.flexive.faces.javascript.yui.YahooResultProvider.java
/** * Moves the given column to the new index in the user's result preferences. * * @param encodedLocation the location, encoded using fx:encodeEnum * @param encodedViewType the view type, encoded using fx:encodeEnum * @param columnKey the column key (i.e. the property/assignment name) * @param index the new index (0-based), taking into account that the column was previously removed from the list * @return nothing/* w w w.j a v a 2 s .c om*/ * @since 3.1 */ public String reorderResultColumn(long typeId, String encodedViewType, String encodedLocation, String columnKey, int index) throws FxApplicationException { final ResultViewType viewType = (ResultViewType) EnumConverter.getValue(encodedViewType); final ResultLocation location = (ResultLocation) EnumConverter.getValue(encodedLocation); final ResultPreferences preferences = getResultPreferencesEngine().load(typeId, viewType, location); final ArrayList<ResultColumnInfo> columns = Lists.newArrayList(preferences.getSelectedColumns()); if (columnKey.indexOf('/') != -1) { // assignment --> prefix with # columnKey = "#" + columnKey; } // get column index for columnKey ResultColumnInfo column = null; for (ResultColumnInfo rci : columns) { if (rci.getPropertyName().equalsIgnoreCase(columnKey)) { column = rci; break; } } if (column == null) { throw new FxUpdateException("ex.jsf.searchResult.resultPreferences.columnNotFound", columnKey); } // move column to new position columns.remove(columns.indexOf(column)); columns.add(index, column); // store new result preferences getResultPreferencesEngine().saveInSource(new ResultPreferences(columns, preferences.getOrderByColumns(), preferences.getRowsPerPage(), preferences.getThumbBoxSize()), typeId, viewType, location); return "[]"; }
From source file:de.tudarmstadt.ukp.dkpro.tc.weka.util.WekaUtils.java
/** * Adapts the test data class labels to the training data. Class labels from the test data * unseen in the training data will be deleted from the test data. Class labels from the * training data unseen in the test data will be added to the test data. If training and test class * labels are equal, nothing will be done. * * @param trainData/* w w w . jav a2s . c o m*/ * training data * @param testData * test data * @param multilabel * whether this is a multi-label classification problem * @return the adapted test data * @throws Exception */ public static Instances makeOutcomeClassesCompatible(Instances trainData, Instances testData, boolean multilabel) throws Exception { // new (compatible) test data Instances compTestData = null; // ================ SINGLE LABEL BRANCH ====================== if (!multilabel) { // retrieve class labels Enumeration trainOutcomeValues = trainData.classAttribute().enumerateValues(); Enumeration testOutcomeValues = testData.classAttribute().enumerateValues(); ArrayList trainLabels = Collections.list(trainOutcomeValues); ArrayList testLabels = Collections.list(testOutcomeValues); // add new outcome class attribute to test data Add addFilter = new Add(); addFilter.setNominalLabels(StringUtils.join(trainLabels, ',')); addFilter.setAttributeName(Constants.CLASS_ATTRIBUTE_NAME + COMPATIBLE_OUTCOME_CLASS); addFilter.setInputFormat(testData); testData = Filter.useFilter(testData, addFilter); // fill NEW test data with values from old test data plus the new class attribute compTestData = new Instances(testData, testData.numInstances()); for (int i = 0; i < testData.numInstances(); i++) { weka.core.Instance instance = testData.instance(i); String label = (String) testLabels.get((int) instance.value(testData.classAttribute())); if (trainLabels.indexOf(label) != -1) { instance.setValue(testData.attribute(Constants.CLASS_ATTRIBUTE_NAME + COMPATIBLE_OUTCOME_CLASS), label); } else { instance.setMissing(testData.classIndex()); } compTestData.add(instance); } // remove old class attribute Remove remove = new Remove(); remove.setAttributeIndices( Integer.toString(compTestData.attribute(Constants.CLASS_ATTRIBUTE_NAME).index() + 1)); remove.setInvertSelection(false); remove.setInputFormat(compTestData); compTestData = Filter.useFilter(compTestData, remove); // set new class attribute compTestData .setClass(compTestData.attribute(Constants.CLASS_ATTRIBUTE_NAME + COMPATIBLE_OUTCOME_CLASS)); } // ================ MULTI LABEL BRANCH ====================== else { int numTrainLabels = trainData.classIndex(); int numTestLabels = testData.classIndex(); ArrayList<String> trainLabels = getLabels(trainData); // ArrayList<String> testLabels = getLabels(testData); // add new outcome class attributes to test data Add filter = new Add(); for (int i = 0; i < numTrainLabels; i++) { // numTestLabels +i (because index starts from 0) filter.setAttributeIndex(new Integer(numTestLabels + i + 1).toString()); filter.setNominalLabels("0,1"); filter.setAttributeName(trainData.attribute(i).name() + COMPATIBLE_OUTCOME_CLASS); filter.setInputFormat(testData); testData = Filter.useFilter(testData, filter); } // fill NEW test data with values from old test data plus the new class attributes compTestData = new Instances(testData, testData.numInstances()); for (int i = 0; i < testData.numInstances(); i++) { weka.core.Instance instance = testData.instance(i); // fullfill with 0. for (int j = 0; j < numTrainLabels; j++) { instance.setValue(j + numTestLabels, 0.); } // fill the real values: for (int j = 0; j < numTestLabels; j++) { // part of train data: forget labels which are not part of the train data if (trainLabels.indexOf(instance.attribute(j).name()) != -1) { // class label found in test data int index = trainLabels.indexOf(instance.attribute(j).name()); instance.setValue(index + numTestLabels, instance.value(j)); } } compTestData.add(instance); } // remove old class attributes for (int i = 0; i < numTestLabels; i++) { Remove remove = new Remove(); remove.setAttributeIndices("1"); remove.setInvertSelection(false); remove.setInputFormat(compTestData); compTestData = Filter.useFilter(compTestData, remove); } // adapt header and set new class label String relationTag = compTestData.relationName(); compTestData.setRelationName( relationTag.substring(0, relationTag.indexOf("-C") + 2) + " " + numTrainLabels + " "); compTestData.setClassIndex(numTrainLabels); } return compTestData; }