List of usage examples for java.lang Character getNumericValue
public static int getNumericValue(int codePoint)
From source file:org.kuali.ole.select.validation.impl.StandardNumberValidationImpl.java
public boolean validateISBN(String input) { // D-DDD-DDDDD-X or DDD-D-DDD-DDDDD-X if (input != null && ((input.length() == 13 && Pattern.matches("\\A\\d{1}\\-\\d{3}\\-\\d{5}\\-[X\\d]\\z", input)) || (input.length() == 13 && Pattern.matches("\\A\\d{1}\\-\\d{4}\\-\\d{4}\\-[X\\d]\\z", input)) || (input.length() == 17//w ww .java 2 s.c o m && Pattern.matches("\\A\\d{3}\\-\\d{1}\\-\\d{2}\\-\\d{6}\\-[X\\d]\\z", input)) || (input.length() == 17 && Pattern.matches("\\A\\d{3}\\-\\d{1}\\-\\d{3}\\-\\d{5}\\-[X\\d]\\z", input)))) { int tot = 0; int remainder = 0; char compChkDigit; input = input.replaceAll("-", ""); switch (input.length()) { case 10: int[] weightFactor = { 10, 9, 8, 7, 6, 5, 4, 3, 2 }; for (int i = 0; i <= 8; i++) tot = tot + (Character.getNumericValue(input.charAt(i)) * weightFactor[i]); remainder = (11 - (tot % 11)) % 11; if (remainder < 10) compChkDigit = Character.forDigit(remainder, 10); else compChkDigit = 'X'; if (compChkDigit == input.charAt(9)) return true; else return false; case 13: int weight = 0; for (int i = 0; i <= 11; i++) { if (i % 2 == 0) weight = 1; else weight = 3; tot = tot + (Character.getNumericValue(input.charAt(i)) * weight); } remainder = (10 - (tot % 10)) % 10; if (remainder < 10) compChkDigit = Character.forDigit(remainder, 10); else compChkDigit = 'X'; if (compChkDigit == input.charAt(12)) return true; else return false; } } return false; }
From source file:eionet.webq.dto.XmlSaveResult.java
/** * Creates {@link eionet.webq.dto.XmlSaveResult} from encoded response. * Encoding format is code(first character, must be an integer) and message(all other characters). * * @param encodedResponse encoded response * @return XmlSaveResult/* w w w . j av a 2 s . co m*/ */ public static XmlSaveResult valueOf(String encodedResponse) { if (StringUtils.isEmpty(encodedResponse)) { return new XmlSaveResult(0, ERROR_MESSAGE + " No response from server."); } int responseCode = Character.getNumericValue(encodedResponse.charAt(0)); return new XmlSaveResult(responseCode, defaultString(MESSAGES_BY_CODE.get(responseCode), ERROR_MESSAGE) + encodedResponse.substring(1)); }
From source file:xmlconverter.controller.logic.SiteToDir.java
/** * This method consists of some nested loops and tries to build correct path * for file creation. Each crafted path will be saved to <code>Set<String> * pathName</code>. This will avoid duplication if any. The path is crafted * manually with given root path and added String values to it * * After the end of this method <code>createDir()</code> method is called. * * @param site/*from www.ja va 2s .c o m*/ * @throws java.io.IOException */ //Flag 0 - Default 1 - Override 2 - Update public void writeDir(Site site) throws IOException { ArrayList<String> detectList = site.getSiteAsArrayList(); ArrayList<File> tempArray = new ArrayList<>(); ArrayList<String> allowOverrideList = new ArrayList<>(); int flag = bean.getUserInputBean().getFlag(); String siteDesc = bean.getEnvBean().getSiteDir().getName(); allowOverrideList.add(siteDesc); for (Panel s : site.getPanelList()) { String panel = s.getDescription(); tempArray.add(new File(format(home.getAbsolutePath() + slash + siteDesc.trim() + slash + panel))); int indexHardware = panel.indexOf("_"); int stationIdHardware = Character.getNumericValue(panel.charAt(indexHardware - 1)); for (String detectionList : detectList) { int index = detectionList.indexOf("_"); int stationId = Character.getNumericValue(detectionList.charAt(index + 1)); if (detectionList.contains("Detektions-Objekt") && stationId == stationIdHardware) { detection = siteDesc.trim() + slash + panel + slash + detectionList.trim(); pathName.add(new File(home, format(detection).replace("!", ""))); } else if (detectionList.contains("Abschnitt") && stationId == stationIdHardware) { build = detection.trim() + slash + detectionList.trim(); pathName.add(new File(home, format(build.trim()).replace("!", ""))); } else if (detectionList.contains("Automatische") && stationId == stationIdHardware) { pathName.add( new File(home, format(build.trim() + slash + detectionList.trim()).replace("!", ""))); } else if (detectionList.contains("Manuelle") && stationId == stationIdHardware) { pathName.add(new File(home, format(build.trim() + slash + detectionList).replace("!", ""))); } else if (detectionList.contains("Stations-Objekt") && stationId == stationIdHardware) { pathName.add(new File(home, format(siteDesc.trim() + slash + panel.trim() + slash + detectionList.trim()) .replace("!", ""))); } } } File[] sortedFiles = pathName.toArray(new File[pathName.size()]); Arrays.sort(sortedFiles); //deletes everything and afterwards revrites as it suppost to. if (flag == 1) { File check = new File(home.getAbsolutePath() + slash + allowOverrideList.get(0)); if (check.exists() && check.isDirectory()) { FileUtils.deleteDirectory(check); } /* This method makes update posible. It findes files that already exist and subtracts them from files that has been created. GG. All already existing file are added to <code>tempArray</code>. */ } else if (flag == 2) { //Somewhat cleaned File beginnDir = new File(home.getAbsolutePath() + slash + allowOverrideList.get(0)); for (File f : sortedFiles) { tempArray.add(f); } tempArray.add(beginnDir); Collection<File> collection = FileUtils.listFilesAndDirs(beginnDir, new NotFileFilter(TrueFileFilter.INSTANCE), DirectoryFileFilter.DIRECTORY); collection.removeAll(tempArray); for (File f : collection) { FileUtils.deleteDirectory(f); } } createDir(sortedFiles); }
From source file:at.medevit.elexis.ehc.core.internal.EhcCoreServiceTest.java
private static String getCheckNumber(String string) { int sum = 0;// w ww . j a v a 2 s . c o m for (int i = 0; i < string.length(); i++) { // reveresd order char character = string.charAt((string.length() - 1) - i); int intValue = Character.getNumericValue(character); if (i % 2 == 0) { sum += intValue * 3; } else { sum += intValue; } } return Integer.toString(sum % 10); }
From source file:com.blackberry.logdriver.timestamp.Rfc5424TimestampParser.java
@Override public long parseTimestatmp(String timestamp) throws ParseException { try {/*from ww w . j a v a 2s . co m*/ // Parse the easy part of the string String firstPart = timestamp.substring(0, 19); Long time; time = dateCache.get(firstPart); if (time == null) { time = dateFormat.parse(firstPart).getTime(); dateCache.put(firstPart, time); } int currentIndex = 19; char c = timestamp.charAt(currentIndex); // Check for fractional seconds to add. We only record up to millisecond // precision, so only grab up to three digits. if (timestamp.charAt(currentIndex) == '.') { // There are fractional seconds, so grab up to 3. // The first digit is guaranteed by the spec. After that, we need to // check if we still have digits. // The spec requires a timezone, so we can't run out of digits // before we run out of string. currentIndex++; c = timestamp.charAt(currentIndex); time += 100 * Character.getNumericValue(c); currentIndex++; c = timestamp.charAt(currentIndex); if (Character.isDigit(c)) { time += 10 * Character.getNumericValue(c); currentIndex++; c = timestamp.charAt(currentIndex); if (Character.isDigit(c)) { time += Character.getNumericValue(c); currentIndex++; c = timestamp.charAt(currentIndex); // Now just go through the digits until we're done. while (Character.isDigit(c)) { currentIndex++; c = timestamp.charAt(currentIndex); } } } } // Now adjust for timezone offset. either Z or +/-00:00 boolean positiveTimeZone = true; if (c == 'Z') { // That's fine. No adjustment. } else { if (c == '+') { positiveTimeZone = true; } else if (c == '-') { positiveTimeZone = false; } else { throw new IllegalArgumentException("Malformed date:" + timestamp); } // Grab the next 2 for hour. Then skip the colon and grab the next // 2. currentIndex++; int hour = Integer.parseInt(timestamp.substring(currentIndex, currentIndex + 2)); currentIndex += 2; c = timestamp.charAt(currentIndex); if (c != ':') { throw new IllegalArgumentException("Malformed date:" + timestamp); } currentIndex++; int minute = Integer.parseInt(timestamp.substring(currentIndex, currentIndex + 2)); int offset = (60 * hour + minute) * 60 * 1000; if (positiveTimeZone) { time -= offset; } else { time += offset; } } // If we support daylight savings, then we need to keep checking if we're // in // daylight savings or not. if (daylightSavings) { time += tz.getOffset(time); } else { time += tzOffset; } return time; } catch (ParseException e) { throw e; } catch (Throwable t) { ParseException e = new ParseException("Unexpected Exception", 0); e.initCause(t); throw e; } }
From source file:edu.oakland.cse480.GCMIntentService.java
public void sendCustNotification(String incomingMsg) { Log.i("incomingMsg = ", "" + incomingMsg); int msgCode;/*from www.j a v a 2 s . c o m*/ try { msgCode = Character.getNumericValue(incomingMsg.charAt(0)); } catch (Exception e) { msgCode = 0; } String msg; //String[] separated = incomingMsg.split("|"); //separated[0] = separated[0]; //discard //separated[1] = separated[1] + ""; //separated[2] = separated[2] + ""; //Additional message with "" to negate a null boolean showNotification = true; Intent intent; switch (msgCode) { case 1: msg = "A new player joined the game"; intent = new Intent("UpdateGameLobby"); intent.putExtra("GAMESTARTED", false); this.sendBroadcast(intent); break; case 2: msg = "The game has started"; intent = new Intent("UpdateGameLobby"); intent.putExtra("GAMESTARTED", true); this.sendBroadcast(intent); break; case 3: msg = "It is your turn to bet"; intent = new Intent("UpdateGamePlay"); this.sendBroadcast(intent); //Stuff break; case 4: msg = "Flop goes"; break; case 5: msg = "A card has been dealt"; //Stuff break; case 6: msg = "The river card, has been dealt"; //Stuff break; case 7: msg = "Hand is over. Winner was " + incomingMsg.substring(1); intent = new Intent("UpdateGamePlay"); intent.putExtra("WINNER", "Winner of last hand: " + incomingMsg.substring(1)); this.sendBroadcast(intent); //Stuff break; case 8: msg = "Game is over. Winner was " + incomingMsg.substring(1); intent = new Intent("UpdateGamePlay"); intent.putExtra("WINNER", "Winner of Game: " + incomingMsg.substring(1)); this.sendBroadcast(intent); //Stuff break; default: msg = "Switch case isn't working"; showNotification = false; //Some default stuff break; } if (showNotification) { mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE); Intent newIntent = new Intent(this, Gameplay.class); newIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, newIntent, 0); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.ic_launcher).setContentTitle("Poker Notification") .setStyle(new NotificationCompat.BigTextStyle().bigText(msg)).setContentText(msg); mBuilder.setContentIntent(contentIntent); Notification notification = mBuilder.build(); notification.defaults |= Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE; notification.flags |= Notification.FLAG_AUTO_CANCEL | Notification.FLAG_SHOW_LIGHTS; mNotificationManager.notify(NOTIFICATION_ID, notification); } }
From source file:org.ensembl.hive.longmult.AddTogether.java
private Object add_together(String b_multiplier, Map<String, Object> partialProduct) { // create accu to write digits to (work out potential length int accuLen = 1 + b_multiplier.length() + numericParamToStr(partialProduct.get("1")).length(); getLog().debug("Adding " + b_multiplier + " to " + partialProduct + ": expected " + accuLen); int[] accu = new int[accuLen]; for (int i = 0; i < accuLen; i++) { accu[i] = 0;//from w ww. j av a2s . c om } // split and reverse the digits in b_multiplier char[] b_digits = StringUtils.reverse(b_multiplier).toCharArray(); // iterate over each digit in b_digits for (int i = 0; i < b_digits.length; i++) { // for each digit char b_digit = b_digits[i]; getLog().debug("i=" + i + ", b_digit=" + b_digit); // get the corresponding partial product for that digit char[] p_digits = StringUtils.reverse(numericParamToStr(partialProduct.get(String.valueOf(b_digit)))) .toCharArray(); // iterate over digits in the product for (int j = 0; j < p_digits.length; j++) { char p_digit = p_digits[j]; getLog().debug("j=" + j + ", p_digit=" + Character.getNumericValue(p_digit) + ", i+j=" + (i + j)); // add to accumulator getLog().debug("[" + i + "+" + j + "] before=" + accu[i + j]); accu[i + j] = accu[i + j] + Character.getNumericValue(p_digit); getLog().debug("[" + i + "+" + j + "] after=" + accu[i + j]); } } // do the carrying int carry = 0; for (int i = 0; i < accu.length; i++) { getLog().debug("Dealing with digit " + i + " of " + accu.length + ": " + accu[i] + ", carry=" + carry); int val = carry + accu[i]; accu[i] = val % 10; carry = val / 10; getLog().debug("Finished dealing with digit " + i + " of " + accu.length + ": " + accu[i] + ", carry=" + carry); } getLog().debug("result=" + Arrays.toString(accu)); // turn accumulator array back into a string and reversing it StringBuilder sb = new StringBuilder(); for (int i = accu.length - 1; i >= 0; i--) { sb.append(accu[i]); } return Long.parseLong(sb.toString()); }
From source file:org.apache.mahout.classifier.sequencelearning.baumwelchmapreduce.BaumWelchUtils.java
public static HmmModel CreateHmmModel(int nrOfHiddenStates, int nrOfOutputStates, Path modelPath, Configuration conf) throws IOException { log.info("Entering Create Hmm Model. Model Path = {}", modelPath.toUri()); Vector initialProbabilities = new DenseVector(nrOfHiddenStates); Matrix transitionMatrix = new DenseMatrix(nrOfHiddenStates, nrOfHiddenStates); Matrix emissionMatrix = new DenseMatrix(nrOfHiddenStates, nrOfOutputStates); // Get the path location where the seq files encoding model are stored Path modelFilesPath = new Path(modelPath, "*"); log.info("Create Hmm Model. ModelFiles Path = {}", modelFilesPath.toUri()); Collection<Path> result = new ArrayList<Path>(); // get all filtered file names in result list FileSystem fs = modelFilesPath.getFileSystem(conf); log.info("Create Hmm Model. File System = {}", fs); FileStatus[] matches = fs.listStatus( FileUtil.stat2Paths(fs.globStatus(modelFilesPath, PathFilters.partFilter())), PathFilters.partFilter());// w w w . j a v a 2 s . co m for (FileStatus match : matches) { log.info("CreateHmmmModel Adding File Match {}", match.getPath().toString()); result.add(fs.makeQualified(match.getPath())); } // iterate through the result path list for (Path path : result) { for (Pair<Writable, MapWritable> pair : new SequenceFileIterable<Writable, MapWritable>(path, true, conf)) { Text key = (Text) pair.getFirst(); log.info("CreateHmmModel Matching Seq File Key = {}", key); MapWritable valueMap = pair.getSecond(); if (key.charAt(0) == 'I') { // initial distribution stripe for (MapWritable.Entry<Writable, Writable> entry : valueMap.entrySet()) { log.info("CreateHmmModel Initial Prob Adding Key, Value = ({} {})", ((IntWritable) entry.getKey()).get(), ((DoubleWritable) entry.getValue()).get()); initialProbabilities.set(((IntWritable) entry.getKey()).get(), ((DoubleWritable) entry.getValue()).get()); } } else if (key.charAt(0) == 'T') { // transition distribution stripe // key is of the form TRANSIT_0, TRANSIT_1 etc // the number after _ is the state ID at char number 11 int stateID = Character.getNumericValue(key.charAt(8)); log.info("CreateHmmModel stateID = key.charAt(8) = {}", stateID); for (MapWritable.Entry<Writable, Writable> entry : valueMap.entrySet()) { log.info("CreateHmmModel Transition Matrix ({}, {}) = {}", new Object[] { stateID, ((IntWritable) entry.getKey()).get(), ((DoubleWritable) entry.getValue()).get() }); transitionMatrix.set(stateID, ((IntWritable) entry.getKey()).get(), ((DoubleWritable) entry.getValue()).get()); } } else if (key.charAt(0) == 'E') { // emission distribution stripe // key is of the form EMIT_0, EMIT_1 etc // the number after _ is the state ID at char number 5 int stateID = Character.getNumericValue(key.charAt(5)); for (MapWritable.Entry<Writable, Writable> entry : valueMap.entrySet()) { log.info("CreateHmmModel Emission Matrix ({}, {}) = {}", new Object[] { stateID, ((IntWritable) entry.getKey()).get(), ((DoubleWritable) entry.getValue()).get() }); emissionMatrix.set(stateID, ((IntWritable) entry.getKey()).get(), ((DoubleWritable) entry.getValue()).get()); } } else { throw new IllegalStateException("Error creating HmmModel from Sequence File Path"); } } } HmmModel model = new HmmModel(transitionMatrix, emissionMatrix, initialProbabilities); HmmUtils.validate(model); return model; }
From source file:org.kuali.ole.select.validation.impl.StandardNumberValidationImpl.java
public boolean validateISSN(String input) { // NNNN-NNNX//w w w . j a v a 2 s .com if (input != null && (input.length() == 9 && Pattern.matches("\\A\\d{4}\\-\\d{3}[X\\d]\\z", input))) { int tot = 0; char compChkDigit; int[] weightFactor = { 8, 7, 6, 5, 4, 3, 2 }; input = input.replaceAll("-", ""); for (int i = 0; i <= 6; i++) tot = tot + (Character.getNumericValue(input.charAt(i)) * weightFactor[i]); int remainder = (11 - (tot % 11)) % 11; if (remainder < 10) compChkDigit = Character.forDigit(remainder, 10); else compChkDigit = 'X'; if (compChkDigit == input.charAt(7)) return true; else return false; } return false; }
From source file:uk.ac.ebi.metabolights.validate.ValidatorMetabolightsUser.java
public static String checkOrcid(String cleanOrcid) { int total = 0; for (int i = 0; i < cleanOrcid.length() - 1; i++) { int digit = Character.getNumericValue(cleanOrcid.charAt(i)); total = (total + digit) * 2;// w w w . j av a 2 s.c o m } int remainder = total % 11; int result = (12 - remainder) % 11; String expectedCheckDigit = result == 10 ? "X" : String.valueOf(result); // If last digit does not match... if (!cleanOrcid.endsWith(expectedCheckDigit)) { return "ORCID doesn't seem to be valid. It doesn't pass the checksum calculations."; } return null; }