Unnamed: 0
int64
0
9.45k
cwe_id
stringclasses
1 value
source
stringlengths
37
2.53k
target
stringlengths
19
2.4k
9,300
public Commodity modifyInfo(long id, CommodityForm form){ log.info("Method: modifyInfo(), id: {}, form: {}", id, form); commodityRepository.findById(id).ifPresent(it -> { if (form.getName() != null && !form.getName().equals(it.getName())) { it.setName(form.getName()); } if (form.getPrice() != null && !form.getPrice().equals(it.getPrice())) { it.setPrice(form.getPrice()); } if (form.getInventory() != null && !form.getInventory().equals(it.getInventory())) { it.setInventory(form.getInventory()); } if (form.getCategories() != null && form.getCategories().size() != 0) { log.info("category size pre: {}", it.getCategories().size()); it.setCategories(categoryService.findAllById(form.getCategories())); log.info("category size after: {}", it.getCategories()); } commodityRepository.save(it); }); return commodityRepository.findById(id).orElseThrow(() -> new NoSuchElementException("No such Commodity!")); }
public Commodity modifyInfo(long id, CommodityForm form){ commodityRepository.findById(id).ifPresent(it -> { if (Objects.nonNull(form.getName()) && !Objects.equals(form.getName(), it.getName())) { it.setName(form.getName()); } if (Objects.nonNull(form.getPrice()) && !Objects.equals(form.getPrice(), it.getPrice())) { it.setPrice(form.getPrice()); } if (Objects.nonNull(form.getInventory()) && !Objects.equals(form.getInventory(), it.getInventory())) { it.setInventory(form.getInventory()); } if (Objects.nonNull(form.getCategories()) && form.getCategories().size() != 0) { log.info("category size pre: {}", it.getCategories().size()); it.setCategories(categoryService.findAllById(form.getCategories())); log.info("category size after: {}", it.getCategories()); } commodityRepository.save(it); }); return commodityRepository.findById(id).orElseThrow(() -> new NoSuchElementException("No such Commodity!")); }
9,301
protected void compute(){ if (length > 1) { int halfLength = length / 2; BitonicSortTask left = new BitonicSortTask(input, begin, halfLength, true); left.fork(); BitonicSortTask right = new BitonicSortTask(input, begin + halfLength, halfLength, false); right.compute(); left.join(); bitonicMerge(input, begin, length, isUp); } }
protected void compute(){ if (length > 1) { int halfLength = length / 2; BitonicSortTask left = new BitonicSortTask(input, begin, halfLength, true); BitonicSortTask right = new BitonicSortTask(input, begin + halfLength, halfLength, false); invokeAll(left, right); bitonicMerge(input, begin, length, isUp); } }
9,302
public static void recieveStartData(){ String line = ""; try { line = reader.readLine(); } catch (SocketException e) { } catch (IOException e) { e.printStackTrace(); } String[] startData = line.split(", "); String[] size = startData[0].split(" "); DataContainer.setGameboardWidth(Integer.parseInt(size[1])); DataContainer.setGameboardHeight(Integer.parseInt(size[2])); Stack<Integer> shipStack = new Stack<Integer>(); for (int i = 2; i < startData.length; i++) { String[] ship = startData[i].split(" "); shipStack.push(Integer.parseInt(ship[1])); DataContainer.getShipLenghts().push(Integer.parseInt(ship[1])); DataContainer.getShipLengthsAI().push(Integer.parseInt(ship[1])); DataContainer.getShipLengthsInverted().push(Integer.parseInt(ship[1])); } while (!(DataContainer.getShipLengthsInverted().isEmpty())) { DataContainer.addShip(DataContainer.getShipLengthsInverted().pop()); } new PlaceShips(); }
public static void recieveStartData(){ String line = ""; try { line = reader.readLine(); } catch (IOException e) { e.printStackTrace(); } String[] startData = line.split(", "); String[] size = startData[0].split(" "); DataContainer.setGameboardWidth(Integer.parseInt(size[1])); DataContainer.setGameboardHeight(Integer.parseInt(size[2])); for (int i = 2; i < startData.length; i++) { String ship = startData[i].split(" ")[1]; DataContainer.getShipLenghts().push(Integer.parseInt(ship)); DataContainer.getShipLengthsAI().push(Integer.parseInt(ship)); DataContainer.getShipLengthsInverted().push(Integer.parseInt(ship)); } while (!(DataContainer.getShipLengthsInverted().isEmpty())) { DataContainer.addShip(DataContainer.getShipLengthsInverted().pop()); } new PlaceShips(); }
9,303
public void prepare(Map<String, Object> conf){ LOG.info("Preparing black list scheduler"); underlyingScheduler.prepare(conf); this.conf = conf; toleranceTime = ObjectReader.getInt(this.conf.get(DaemonConfig.BLACKLIST_SCHEDULER_TOLERANCE_TIME), DEFAULT_BLACKLIST_SCHEDULER_TOLERANCE_TIME); toleranceCount = ObjectReader.getInt(this.conf.get(DaemonConfig.BLACKLIST_SCHEDULER_TOLERANCE_COUNT), DEFAULT_BLACKLIST_SCHEDULER_TOLERANCE_COUNT); resumeTime = ObjectReader.getInt(this.conf.get(DaemonConfig.BLACKLIST_SCHEDULER_RESUME_TIME), DEFAULT_BLACKLIST_SCHEDULER_RESUME_TIME); String reporterClassName = ObjectReader.getString(this.conf.get(DaemonConfig.BLACKLIST_SCHEDULER_REPORTER), LogReporter.class.getName()); reporter = (IReporter) initializeInstance(reporterClassName, "blacklist reporter"); String strategyClassName = ObjectReader.getString(this.conf.get(DaemonConfig.BLACKLIST_SCHEDULER_STRATEGY), DefaultBlacklistStrategy.class.getName()); blacklistStrategy = (IBlacklistStrategy) initializeInstance(strategyClassName, "blacklist strategy"); nimbusMonitorFreqSecs = ObjectReader.getInt(this.conf.get(DaemonConfig.NIMBUS_MONITOR_FREQ_SECS)); blacklistStrategy.prepare(this.conf); windowSize = toleranceTime / nimbusMonitorFreqSecs; badSupervisorsToleranceSlidingWindow = EvictingQueue.create(windowSize); cachedSupervisors = new HashMap<>(); blacklistHost = new HashSet<>(); StormMetricsRegistry.registerGauge("nimbus:num-blacklisted-supervisor", new Callable<Integer>() { @Override public Integer call() throws Exception { return blacklistHost.size(); } }); }
public void prepare(Map<String, Object> conf){ LOG.info("Preparing black list scheduler"); underlyingScheduler.prepare(conf); this.conf = conf; toleranceTime = ObjectReader.getInt(this.conf.get(DaemonConfig.BLACKLIST_SCHEDULER_TOLERANCE_TIME), DEFAULT_BLACKLIST_SCHEDULER_TOLERANCE_TIME); toleranceCount = ObjectReader.getInt(this.conf.get(DaemonConfig.BLACKLIST_SCHEDULER_TOLERANCE_COUNT), DEFAULT_BLACKLIST_SCHEDULER_TOLERANCE_COUNT); resumeTime = ObjectReader.getInt(this.conf.get(DaemonConfig.BLACKLIST_SCHEDULER_RESUME_TIME), DEFAULT_BLACKLIST_SCHEDULER_RESUME_TIME); String reporterClassName = ObjectReader.getString(this.conf.get(DaemonConfig.BLACKLIST_SCHEDULER_REPORTER), LogReporter.class.getName()); reporter = (IReporter) initializeInstance(reporterClassName, "blacklist reporter"); String strategyClassName = ObjectReader.getString(this.conf.get(DaemonConfig.BLACKLIST_SCHEDULER_STRATEGY), DefaultBlacklistStrategy.class.getName()); blacklistStrategy = (IBlacklistStrategy) initializeInstance(strategyClassName, "blacklist strategy"); nimbusMonitorFreqSecs = ObjectReader.getInt(this.conf.get(DaemonConfig.NIMBUS_MONITOR_FREQ_SECS)); blacklistStrategy.prepare(this.conf); windowSize = toleranceTime / nimbusMonitorFreqSecs; badSupervisorsToleranceSlidingWindow = EvictingQueue.create(windowSize); cachedSupervisors = new HashMap<>(); blacklistHost = new HashSet<>(); StormMetricsRegistry.registerGauge("nimbus:num-blacklisted-supervisor", () -> blacklistHost.size()); }
9,304
public void shouldBundleIsPersisted(){ boolean shouldBundle = ThreadLocalRandom.current().nextBoolean(); AnnotationValuesExtractor annotationValuesExtractorMock = mock(AnnotationValuesExtractor.class); when(annotationValuesExtractorMock.extractAnnotationValues(anyMap())).thenReturn(new HashMap<>()); FrontendDataProvider frontendDataProvider = new FrontendDataProvider(shouldBundle, sourceDirectory, annotationValuesExtractorMock, null, Collections.emptyMap()); boolean actualShouldBundle = frontendDataProvider.shouldBundle(); assertEquals("Expect to have the same value for 'shouldBundle' variable as passed into a constructor", shouldBundle, actualShouldBundle); verify(annotationValuesExtractorMock).extractAnnotationValues(anyMap()); verify(annotationValuesExtractorMock).collectThemedHtmlImports(Matchers.any()); }
public void shouldBundleIsPersisted(){ boolean shouldBundle = ThreadLocalRandom.current().nextBoolean(); AnnotationValuesExtractor annotationValuesExtractorMock = mock(AnnotationValuesExtractor.class); when(annotationValuesExtractorMock.extractAnnotationValues(anyMap())).thenReturn(new HashMap<>()); FrontendDataProvider frontendDataProvider = new TestFrontendDataProvider(shouldBundle, sourceDirectory, annotationValuesExtractorMock, null, Collections.emptyMap()); boolean actualShouldBundle = frontendDataProvider.shouldBundle(); assertEquals("Expect to have the same value for 'shouldBundle' variable as passed into a constructor", shouldBundle, actualShouldBundle); verify(annotationValuesExtractorMock, Mockito.times(2)).extractAnnotationValues(anyMap()); }
9,305
public static List<R> processIntersectingRetrievals(List<IndexCall<R>> retrievals, final int limit){ Preconditions.checkArgument(!retrievals.isEmpty()); Preconditions.checkArgument(limit >= 0, "Invalid limit: %s", limit); List<R> results; int multiplier = Math.min(16, (int) Math.pow(2, retrievals.size() - 1)); int subLimit = Integer.MAX_VALUE; if (Integer.MAX_VALUE / multiplier >= limit) subLimit = limit * multiplier; boolean exhaustedResults; do { exhaustedResults = true; results = null; for (IndexCall<R> call : retrievals) { Collection<R> subResult; try { subResult = call.call(subLimit); } catch (Exception e) { throw new JanusGraphException("Could not process individual retrieval call ", e); } if (subResult.size() >= subLimit) exhaustedResults = false; if (results == null) { results = Lists.newArrayList(subResult); } else { Set<R> subResultSet = ImmutableSet.copyOf(subResult); Iterator resultIterator = results.iterator(); while (resultIterator.hasNext()) { if (!subResultSet.contains(resultIterator.next())) resultIterator.remove(); } } } subLimit = (int) Math.min(Integer.MAX_VALUE - 1, Math.max(Math.pow(subLimit, 1.5), (subLimit + 1) * 2)); } while (results != null && results.size() < limit && !exhaustedResults); return results; }
public static List<R> processIntersectingRetrievals(List<IndexCall<R>> retrievals, final int limit){ Preconditions.checkArgument(!retrievals.isEmpty()); Preconditions.checkArgument(limit >= 0, "Invalid limit: %s", limit); List<R> results; int multiplier = Math.min(16, (int) Math.pow(2, retrievals.size() - 1)); int subLimit = Integer.MAX_VALUE; if (Integer.MAX_VALUE / multiplier >= limit) subLimit = limit * multiplier; boolean exhaustedResults; do { exhaustedResults = true; results = null; for (IndexCall<R> call : retrievals) { Collection<R> subResult; try { subResult = call.call(subLimit); } catch (Exception e) { throw new JanusGraphException("Could not process individual retrieval call ", e); } if (subResult.size() >= subLimit) exhaustedResults = false; if (results == null) { results = Lists.newArrayList(subResult); } else { Set<R> subResultSet = ImmutableSet.copyOf(subResult); results.removeIf(o -> !subResultSet.contains(o)); } } subLimit = (int) Math.min(Integer.MAX_VALUE - 1, Math.max(Math.pow(subLimit, 1.5), (subLimit + 1) * 2)); } while (results != null && results.size() < limit && !exhaustedResults); return results; }
9,306
public App testInterface(@PathVariable(name = "version") VERSION version){ App app = new App("Listing", getVersionedPojos(version)); return app; }
public App testInterface(@PathVariable(name = "version") VERSION version){ return new App("Listing", getVersionedPojos(version)); }
9,307
public List<User> findAll(){ final String findAllQuery = "select * from users order by id"; List<User> result = new ArrayList<>(); Connection connection; Statement statement; ResultSet resultSet; try { Class.forName(POSTRGES_DRIVER_NAME); } catch (ClassNotFoundException e) { System.err.println("JDBC Driver Cannot be loaded!"); throw new RuntimeException("JDBC Driver Cannot be loaded!"); } String jdbcURL = StringUtils.join(DATABASE_URL, DATABASE_PORT, DATABASE_NAME); try { connection = DriverManager.getConnection(jdbcURL, DATABASE_LOGIN, DATABASE_PASSWORD); statement = connection.createStatement(); resultSet = statement.executeQuery(findAllQuery); while (resultSet.next()) { User user = new User(); user.setId(resultSet.getLong(ID)); user.setName(resultSet.getString(NAME)); user.setSurname(resultSet.getString(SURNAME)); user.setLogin(resultSet.getString(LOGIN)); user.setBirthDate(resultSet.getDate(BIRTH_DATE)); user.setWeight(resultSet.getFloat(WEIGHT)); result.add(user); } return result; } catch (SQLException e) { System.err.println(e.getMessage()); throw new RuntimeException("SQL Issues!"); } }
public List<User> findAll(){ final String findAllQuery = "SELECT * FROM users ORDER BY id"; List<User> result = new ArrayList<>(); try { Class.forName(jdbcDriver); } catch (ClassNotFoundException e) { System.err.println("JDBC Driver Cannot be loaded!"); throw new RuntimeException("JDBC Driver Cannot be loaded!"); } try (Connection connection = DriverManager.getConnection(jdbcURL, jdbcLogin, jdbcPassword); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(findAllQuery)) { while (resultSet.next()) { User user = new User(); user.setId(resultSet.getLong(ID)); user.setName(resultSet.getString(NAME)); user.setSurname(resultSet.getString(SURNAME)); user.setLogin(resultSet.getString(LOGIN)); user.setBirthDate(resultSet.getDate(BIRTH_DATE)); user.setWeight(resultSet.getFloat(WEIGHT)); result.add(user); } return result; } catch (SQLException e) { System.err.println(e.getMessage()); throw new RuntimeException("SQL Issues!"); } }
9,308
private Trip doMap(org.onebusaway.gtfs.model.Trip rhs){ Trip lhs = new Trip(AgencyAndIdMapper.mapAgencyAndId(rhs.getId())); lhs.setRoute(routeMapper.map(rhs.getRoute())); lhs.setServiceId(AgencyAndIdMapper.mapAgencyAndId(rhs.getServiceId())); lhs.setTripShortName(rhs.getTripShortName()); lhs.setTripHeadsign(rhs.getTripHeadsign()); lhs.setRouteShortName(rhs.getRouteShortName()); lhs.setDirection(Direction.valueOfGtfsCode(mapDirectionId(rhs))); lhs.setBlockId(rhs.getBlockId()); lhs.setShapeId(AgencyAndIdMapper.mapAgencyAndId(rhs.getShapeId())); lhs.setWheelchairAccessible(rhs.getWheelchairAccessible()); lhs.setTripBikesAllowed(rhs.getTripBikesAllowed()); lhs.setBikesAllowed(rhs.getBikesAllowed()); lhs.setFareId(rhs.getFareId()); return lhs; }
private Trip doMap(org.onebusaway.gtfs.model.Trip rhs){ Trip lhs = new Trip(AgencyAndIdMapper.mapAgencyAndId(rhs.getId())); lhs.setRoute(routeMapper.map(rhs.getRoute())); lhs.setServiceId(AgencyAndIdMapper.mapAgencyAndId(rhs.getServiceId())); lhs.setTripShortName(rhs.getTripShortName()); lhs.setTripHeadsign(rhs.getTripHeadsign()); lhs.setRouteShortName(rhs.getRouteShortName()); lhs.setDirection(Direction.valueOfGtfsCode(mapDirectionId(rhs))); lhs.setBlockId(rhs.getBlockId()); lhs.setShapeId(AgencyAndIdMapper.mapAgencyAndId(rhs.getShapeId())); lhs.setWheelchairAccessible(rhs.getWheelchairAccessible()); lhs.setBikesAllowed(BikeAccessMapper.mapForTrip(rhs)); lhs.setFareId(rhs.getFareId()); return lhs; }
9,309
private void removeListener(@NonNull OrderedRealmCollection<T> data){ if (data instanceof RealmResults) { RealmResults realmResults = (RealmResults) data; realmResults.removeChangeListener(listener); } else if (data instanceof RealmList) { RealmList realmList = (RealmList) data; } else { throw new IllegalArgumentException("RealmCollection not supported: " + data.getClass()); } }
private void removeListener(@NonNull OrderedRealmCollection<T> data){ if (data instanceof RealmResults) { RealmResults realmResults = (RealmResults) data; realmResults.removeChangeListener(listener); } else if (data instanceof RealmList) { } else { throw new IllegalArgumentException("RealmCollection not supported: " + data.getClass()); } }
9,310
private void initGui(){ setBackground(Color.WHITE); title = new JLabel(); title.setText("Learning rate"); String[] learningRatesStrs = { "0.00001", "0.0001", "0.001", "0.003", "0.01", "0.03", "0.1", "0.3", "1", "3", "10" }; learnningRate = new MyComboBox(learningRatesStrs); learnningRate.setMaximumRowCount(11); }
private void initGui(){ title = new JLabel(); title.setText("Learning rate"); String[] learningRatesStrs = { "0.00001", "0.0001", "0.001", "0.003", "0.01", "0.03", "0.1", "0.3", "1", "3", "10" }; learnningRate = new MyComboBox(learningRatesStrs); learnningRate.setMaximumRowCount(11); }
9,311
public Map<String, Object> saveWorkerGroup(User loginUser, int id, String name, String addrList){ Map<String, Object> result = new HashMap<>(); if (isNotAdmin(loginUser, result)) { return result; } if (Constants.DOCKER_MODE && !Constants.KUBERNETES_MODE) { putMsg(result, Status.CREATE_WORKER_GROUP_FORBIDDEN_IN_DOCKER); return result; } if (StringUtils.isEmpty(name)) { putMsg(result, Status.NAME_NULL); return result; } Date now = new Date(); WorkerGroup workerGroup; if (id != 0) { workerGroup = workerGroupMapper.selectById(id); if (workerGroup == null) { workerGroup = new WorkerGroup(); workerGroup.setCreateTime(now); } } else { workerGroup = new WorkerGroup(); workerGroup.setCreateTime(now); } workerGroup.setName(name); workerGroup.setAddrList(addrList); workerGroup.setUpdateTime(now); if (checkWorkerGroupNameExists(workerGroup)) { putMsg(result, Status.NAME_EXIST, workerGroup.getName()); return result; } String invalidAddr = checkWorkerGroupAddrList(workerGroup); if (invalidAddr != null) { putMsg(result, Status.WORKER_ADDRESS_INVALID, invalidAddr); return result; } if (workerGroup.getId() != 0) { workerGroupMapper.updateById(workerGroup); } else { workerGroupMapper.insert(workerGroup); } putMsg(result, Status.SUCCESS); return result; }
public Result<Void> saveWorkerGroup(User loginUser, int id, String name, String addrList){ if (isNotAdmin(loginUser)) { return Result.error(Status.USER_NO_OPERATION_PERM); } if (Constants.DOCKER_MODE && !Constants.KUBERNETES_MODE) { return Result.error(Status.CREATE_WORKER_GROUP_FORBIDDEN_IN_DOCKER); } if (StringUtils.isEmpty(name)) { return Result.error(Status.NAME_NULL); } Date now = new Date(); WorkerGroup workerGroup; if (id != 0) { workerGroup = workerGroupMapper.selectById(id); if (workerGroup == null) { workerGroup = new WorkerGroup(); workerGroup.setCreateTime(now); } } else { workerGroup = new WorkerGroup(); workerGroup.setCreateTime(now); } workerGroup.setName(name); workerGroup.setAddrList(addrList); workerGroup.setUpdateTime(now); if (checkWorkerGroupNameExists(workerGroup)) { return Result.errorWithArgs(Status.NAME_EXIST, workerGroup.getName()); } String invalidAddr = checkWorkerGroupAddrList(workerGroup); if (invalidAddr != null) { return Result.errorWithArgs(Status.WORKER_ADDRESS_INVALID, invalidAddr); } if (workerGroup.getId() != 0) { workerGroupMapper.updateById(workerGroup); } else { workerGroupMapper.insert(workerGroup); } return Result.success(null); }
9,312
public void setSampleRate(SampleRate sampleRate) throws SourceException{ writeDemodRegister(mDeviceHandle, Page.ONE, (short) 0x9F, sampleRate.getRatioHighBits(), 2); writeDemodRegister(mDeviceHandle, Page.ONE, (short) 0xA1, 0, 2); setSampleRateFrequencyCorrection(0); writeDemodRegister(mDeviceHandle, Page.ONE, (short) 0x01, 0x14, 1); writeDemodRegister(mDeviceHandle, Page.ONE, (short) 0x01, 0x10, 1); setSampleRateFilters(sampleRate.getRate()); mSampleRate = sampleRate; mFrequencyController.setSampleRate(sampleRate.getRate()); if (mSampleRateMonitor != null) { mSampleRateMonitor.setSampleRate(mSampleRate.getRate()); } }
public void setSampleRate(SampleRate sampleRate) throws SourceException{ writeDemodRegister(mDeviceHandle, Page.ONE, (short) 0x9F, sampleRate.getRatioHighBits(), 2); writeDemodRegister(mDeviceHandle, Page.ONE, (short) 0xA1, 0, 2); setSampleRateFrequencyCorrection(0); writeDemodRegister(mDeviceHandle, Page.ONE, (short) 0x01, 0x14, 1); writeDemodRegister(mDeviceHandle, Page.ONE, (short) 0x01, 0x10, 1); setSampleRateFilters(sampleRate.getRate()); mSampleRate = sampleRate; mFrequencyController.setSampleRate(sampleRate.getRate()); }
9,313
public void removeMoneyFromBank(String uuid, Integer amount){ if (playerExists(uuid)) { int removed = getGuthaben(uuid) - amount; try { database.updateSQL("UPDATE BANK SET GUTHABEN= '" + removed + "' WHERE UUID= '\" + uuid + \"';"); } catch (SQLException throwables) { throwables.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } else { createBankAccount(uuid); saveMoneyToBank(uuid, amount); } }
public void removeMoneyFromBank(String uuid, Integer amount){ if (playerExists(uuid)) { int removed = getGuthaben(uuid) - amount; try { database.updateSQL("UPDATE BANK SET GUTHABEN= '" + removed + "' WHERE UUID= '\" + uuid + \"';"); } catch (SQLException | ClassNotFoundException throwables) { throwables.printStackTrace(); } } else { createBankAccount(uuid); saveMoneyToBank(uuid, amount); } }
9,314
public char verifyCreditCard(RequestedCard requestedCard){ char ch = 'N'; if (requestedCard == null) ch = 'N'; else { boolean isNumber = PaymentUtils.isNumeric(requestedCard.getCardNum()); if (!isNumber) { ch = 'N'; } else { if (!PaymentUtils.CheckValidNumber(requestedCard.getCardNum())) { ch = 'N'; } else { if (CardType.detect(requestedCard.getCardNum()) == CardType.VISA) { Visa visa = visaRepository.findByCardNum(requestedCard.getCardNum()).get(0); if (visa == null) { ch = 'N'; } else { if (!verifyCard(visa, requestedCard)) ch = 'N'; else { ch = 'Y'; } } } else { if (CardType.detect(requestedCard.getCardNum()) == CardType.MASTERCARD) { Master master = masterRepository.findByCardNum(requestedCard.getCardNum()).get(0); if (master == null) { ch = 'N'; } else { if (!verifyCard(master, requestedCard)) ch = 'N'; else { ch = 'Y'; } } } } } } } return ch; }
public char verifyCreditCard(RequestedCard requestedCard){ char ch = 'N'; if (requestedCard == null) ch = 'N'; else { boolean isNumber = PaymentUtils.isNumeric(requestedCard.getCardNum()); if (!isNumber) { ch = 'N'; } else { CardType cardType = CardType.detect(requestedCard.getCardNum()); if (!PaymentUtils.CheckValidNumber(requestedCard.getCardNum())) { ch = 'N'; } else { CreditCardRepository creditCardRepository = creditCardRepositoryFactory.getCreditCardRepository(cardType); if (creditCardRepository == null) { return 'N'; } CreditCard creditCard = creditCardRepository.findByCardNum(requestedCard.getCardNum()).get(0); if (creditCard == null) { ch = 'N'; } else { if (!verifyCard(creditCard, requestedCard)) ch = 'N'; else { ch = 'Y'; } } } } } return ch; }
9,315
public void onBindViewHolder(@NonNull MatchViewHolder matchViewHolder, int position){ GsonMatch gsonMatch = matchesData.get(position); String utcDate = String.valueOf(gsonMatch.getUtcDate()); String status = String.valueOf(gsonMatch.getStatus()); String matchday = String.valueOf(gsonMatch.getMatchday()); String lastUpdated = String.valueOf(gsonMatch.getLastUpdated()); matchViewHolder.getMatchday().setText(matchday); matchViewHolder.getHometeam().setText(gsonMatch.getHomeTeam().getName()); matchViewHolder.getAwayTeam().setText(gsonMatch.getAwayTeam().getName()); matchViewHolder.getScoreHomeFullTime().setText(String.valueOf(gsonMatch.getScore().getFullTime().getHomeTeam())); matchViewHolder.getScoreAwayFullTime().setText(String.valueOf(gsonMatch.getScore().getFullTime().getAwayTeam())); matchViewHolder.getScoreHomeFullTime().setText(String.valueOf(gsonMatch.getScore().getHalfTime().getHomeTeam())); matchViewHolder.getScoreHomeFullTime().setText(String.valueOf(gsonMatch.getScore().getHalfTime().getHomeTeam())); matchViewHolder.getUtcDate().setText(status); matchViewHolder.getLastUpdated().setText(lastUpdated); matchViewHolder.getStatus().setText(status); }
public void onBindViewHolder(@NonNull MatchViewHolder matchViewHolder, int position){ GsonMatch gsonMatch = matchesData.get(position); String utcDate = String.valueOf(gsonMatch.getUtcDate()); String status = String.valueOf(gsonMatch.getStatus()); String matchday = String.valueOf(gsonMatch.getMatchday()); String lastUpdated = String.valueOf(gsonMatch.getLastUpdated()); matchViewHolder.getMatchday().setText(matchday); matchViewHolder.getHometeam().setText(gsonMatch.getHomeTeam().getName()); matchViewHolder.getAwayTeam().setText(gsonMatch.getAwayTeam().getName()); matchViewHolder.getScoreHomeFullTime().setText(String.valueOf(gsonMatch.getScore().getFullTime().getHomeTeam())); matchViewHolder.getScoreAwayFullTime().setText(String.valueOf(gsonMatch.getScore().getFullTime().getAwayTeam())); matchViewHolder.getScoreHomeFullTime().setText(String.valueOf(gsonMatch.getScore().getHalfTime().getHomeTeam())); matchViewHolder.getScoreHomeFullTime().setText(String.valueOf(gsonMatch.getScore().getHalfTime().getHomeTeam())); }
9,316
public static List<Color> getColors(@NotNull Collection<VcsRef> refs){ MultiMap<VcsRefType, VcsRef> referencesByType = ContainerUtil.groupBy(refs, VcsRef::getType); if (referencesByType.size() == 1) { Map.Entry<VcsRefType, Collection<VcsRef>> firstItem = ObjectUtils.assertNotNull(ContainerUtil.getFirstItem(referencesByType.entrySet())); boolean multiple = firstItem.getValue().size() > 1; Color color = EditorColorsUtil.getGlobalOrDefaultColor(firstItem.getKey().getBgColorKey()); return multiple ? Arrays.asList(color, color) : Collections.singletonList(color); } else { List<Color> colorsList = ContainerUtil.newArrayList(); for (VcsRefType type : referencesByType.keySet()) { Color color = EditorColorsUtil.getGlobalOrDefaultColor(type.getBgColorKey()); if (referencesByType.get(type).size() > 1) { colorsList.add(color); } colorsList.add(color); } return colorsList; } }
public static List<Color> getColors(@NotNull Collection<VcsRef> refs){ MultiMap<VcsRefType, VcsRef> referencesByType = ContainerUtil.groupBy(refs, VcsRef::getType); if (referencesByType.size() == 1) { Map.Entry<VcsRefType, Collection<VcsRef>> firstItem = ObjectUtils.assertNotNull(ContainerUtil.getFirstItem(referencesByType.entrySet())); boolean multiple = firstItem.getValue().size() > 1; Color color = firstItem.getKey().getBackgroundColor(); return multiple ? Arrays.asList(color, color) : Collections.singletonList(color); } else { List<Color> colorsList = ContainerUtil.newArrayList(); for (VcsRefType type : referencesByType.keySet()) { if (referencesByType.get(type).size() > 1) { colorsList.add(type.getBackgroundColor()); } colorsList.add(type.getBackgroundColor()); } return colorsList; } }
9,317
private static String getLocalizedLink(final String link, final ResourceLoader loader){ final String imageFileName = link.substring(Math.max(link.lastIndexOf("/") + 1, 0)); final String firstOption = ASSET_IMAGE_FOLDER + imageFileName; URL replacementUrl = loader.getResource(firstOption); if (replacementUrl == null) { log.error(String.format("Could not find: %s/%s", loader.getMapName(), firstOption)); final String secondFallback = ASSET_IMAGE_FOLDER + ASSET_IMAGE_NOT_FOUND; replacementUrl = loader.getResource(secondFallback); if (replacementUrl == null) { log.error(String.format("Could not find: %s", secondFallback)); return link; } } return replacementUrl.toString(); }
private static String getLocalizedLink(final String link, final File mapContentFolder){ final Path imagesPath = mapContentFolder.toPath().resolve("doc").resolve("images").resolve(link); return FileUtils.toUrl(imagesPath).toString(); }
9,318
private void getUserAction(){ if (gameOver) return; System.out.println(); System.out.println(ANSI_BLACK + "[I] Inventory"); System.out.println("[C] Character"); System.out.println("[M] Map"); System.out.println("[Q] Quit"); String opt = scanner.nextLine().toLowerCase(); switch(opt) { case "i": inventoryManager.openInventoryMenu(); break; case "m": map.showMap(); move(); break; case "c": showCharacter(); break; default: System.out.println("Action invalid."); getUserAction(); break; case "q": System.out.println("Are you sure you want to quit and end the game? [Y] [N]"); switch(scanner.nextLine().toLowerCase()) { case "y": Broadcaster.relayGameOver(); gameOver = true; break; case "n": getUserAction(); } break; } }
private void getUserAction(){ if (gameOver) return; System.out.println(); System.out.println(ANSI_BLACK + "[I] Inventory"); System.out.println("[C] Character"); System.out.println("[M] Map"); System.out.println("[Q] Quit"); String opt = scanner.nextLine().toLowerCase(); switch(opt) { case "i": inventoryService.openInventoryMenu(); break; case "m": move(); break; case "c": showCharacter(); break; default: System.out.println("Action invalid."); getUserAction(); break; case "q": System.out.println("Are you sure you want to quit and end the game? [Y] [N]"); switch(scanner.nextLine().toLowerCase()) { case "y": Broadcaster.relayGameOver(); gameOver = true; break; case "n": getUserAction(); } break; } }
9,319
public InterceptorProcessor parse(Method method, Annotation annotationOnMethod){ InterceptorProcessor interceptorProcessor = new InterceptorProcessor(method.getDeclaringClass().getClassLoader()); InterceptorMethodConfig interceptorMethodConfig = new InterceptorMethodConfig(); interceptorProcessor.setInterceptorMethodConfig(interceptorMethodConfig); interceptorMethodConfig.setOwner(Type.getInternalName(method.getDeclaringClass())); interceptorMethodConfig.setMethodName(method.getName()); interceptorMethodConfig.setMethodDesc(Type.getMethodDescriptor(method)); AtInvoke atInvoke = (AtInvoke) annotationOnMethod; String owner = null; String desc = null; if (!atInvoke.owner().equals(Void.class)) { owner = Type.getType(atInvoke.owner()).getInternalName(); } if (atInvoke.desc().isEmpty()) { desc = null; } List<String> excludes = new ArrayList<String>(); for (String exclude : atInvoke.excludes()) { excludes.add(exclude); } LocationMatcher locationMatcher = new InvokeLocationMatcher(owner, atInvoke.name(), desc, atInvoke.count(), atInvoke.whenComplete(), excludes); interceptorProcessor.setLocationMatcher(locationMatcher); interceptorMethodConfig.setInline(atInvoke.inline()); List<Binding> bindings = BindingParserUtils.parseBindings(method); interceptorMethodConfig.setBindings(bindings); InterceptorMethodConfig errorHandlerMethodConfig = ExceptionHandlerUtils.errorHandlerMethodConfig(atInvoke.suppress(), atInvoke.suppressHandler()); if (errorHandlerMethodConfig != null) { interceptorProcessor.setExceptionHandlerConfig(errorHandlerMethodConfig); } return interceptorProcessor; }
public InterceptorProcessor parse(Method method, Annotation annotationOnMethod){ AtInvoke atInvoke = (AtInvoke) annotationOnMethod; String owner = null; String desc = null; if (!atInvoke.owner().equals(Void.class)) { owner = Type.getType(atInvoke.owner()).getInternalName(); } if (atInvoke.desc().isEmpty()) { desc = null; } List<String> excludes = new ArrayList<String>(); for (String exclude : atInvoke.excludes()) { excludes.add(exclude); } LocationMatcher locationMatcher = new InvokeLocationMatcher(owner, atInvoke.name(), desc, atInvoke.count(), atInvoke.whenComplete(), excludes); return InterceptorParserUtils.createInterceptorProcessor(method, locationMatcher, atInvoke.inline(), atInvoke.suppress(), atInvoke.suppressHandler()); }
9,320
public void onDetonatorUsage(PlayerInteractEvent event){ Player player = event.getPlayer(); if (!Main.isPlayerInGame(player)) return; ItemStack detonator = detonator(); if (!(event.getItem() == null)) { if (event.getItem().equals(detonator) && (event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK)) { for (Location location : locations) { int ticks = location.getBlock().getMetadata("ticks").get(0).asInt(); location.getBlock().setType(Material.AIR); TNTPrimed tnt = (TNTPrimed) location.getWorld().spawn(location.add(0.5, 0.0, 0.5), TNTPrimed.class); for (Player players : Main.getPlayerGameProfile(player).getGame().getConnectedPlayers()) { if (ticks >= 30) { players.playSound(tnt.getLocation(), Sound.ENTITY_TNT_PRIMED, 1.0F, 1.0F); } } Main.registerGameEntity(tnt, Main.getPlayerGameProfile(player).getGame()); tnt.setFuseTicks(ticks); tnt.setMetadata("owner", new FixedMetadataValue(XPWars.getInstance(), player.getUniqueId().toString())); location.getBlock().setType(Material.AIR); locations.remove(location); } event.setCancelled(true); player.getInventory().remove(detonator); } } else return; }
public void onDetonatorUsage(PlayerInteractEvent event){ Player player = event.getPlayer(); if (!Main.isPlayerInGame(player)) return; ItemStack detonator = detonator(); if (!(event.getItem() == null)) { if (event.getItem().equals(detonator) && (event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK)) { for (Location location : locations) { int ticks = location.getBlock().getMetadata("ticks").get(0).asInt(); location.getBlock().setType(Material.AIR); TNTPrimed tnt = location.getWorld().spawn(location.add(0.5, 0.0, 0.5), TNTPrimed.class); for (Player players : Main.getPlayerGameProfile(player).getGame().getConnectedPlayers()) { if (ticks >= 30) { players.playSound(tnt.getLocation(), Sound.ENTITY_TNT_PRIMED, 1.0F, 1.0F); } } Main.registerGameEntity(tnt, Main.getPlayerGameProfile(player).getGame()); tnt.setFuseTicks(ticks); tnt.setMetadata("owner", new FixedMetadataValue(XPWars.getInstance(), player.getUniqueId().toString())); location.getBlock().setType(Material.AIR); locations.remove(location); } event.setCancelled(true); player.getInventory().remove(detonator); } } }
9,321
public PointerHierarchyRepresentationResult run(Database db, Relation<O> relation){ DistanceQuery<O> dq = db.getDistanceQuery(relation, getDistanceFunction()); ArrayDBIDs ids = DBIDUtil.ensureArray(relation.getDBIDs()); final int size = ids.size(); if (size > 0x10000) { throw new AbortException("This implementation does not scale to data sets larger than " + 0x10000 + " instances (~16 GB RAM), at which point the Java maximum array size is reached."); } PointerHierarchyRepresentationBuilder builder = new PointerHierarchyRepresentationBuilder(ids, dq.getDistanceFunction().isSquared()); Int2ObjectOpenHashMap<ModifiableDBIDs> clusters = new Int2ObjectOpenHashMap<>(); double[] distances = new double[AGNES.triangleSize(size)]; ArrayModifiableDBIDs prots = DBIDUtil.newArray(AGNES.triangleSize(size)); DBIDArrayMIter protiter = prots.iter(); DBIDArrayIter ix = ids.iter(), iy = ids.iter(); MiniMax.initializeMatrices(distances, prots, dq, ix, iy); double[] bestd = new double[size]; int[] besti = new int[size]; initializeNNCache(distances, bestd, besti); FiniteProgress prog = LOG.isVerbose() ? new FiniteProgress("Agglomerative clustering", size - 1, LOG) : null; int wsize = size; for (int i = 1; i < size; i++) { findMerge(wsize, distances, protiter, ix, iy, builder, clusters, bestd, besti, dq); LOG.incrementProcessed(prog); } LOG.ensureCompleted(prog); return (PointerPrototypeHierarchyRepresentationResult) builder.complete(); }
public PointerHierarchyRepresentationResult run(Database db, Relation<O> relation){ DistanceQuery<O> dq = db.getDistanceQuery(relation, getDistanceFunction()); final DBIDs ids = relation.getDBIDs(); final int size = ids.size(); PointerHierarchyRepresentationBuilder builder = new PointerHierarchyRepresentationBuilder(ids, dq.getDistanceFunction().isSquared()); Int2ObjectOpenHashMap<ModifiableDBIDs> clusters = new Int2ObjectOpenHashMap<>(); MatrixParadigm mat = new MatrixParadigm(ids); ArrayModifiableDBIDs prots = DBIDUtil.newArray(MatrixParadigm.triangleSize(size)); DBIDArrayMIter protiter = prots.iter(); MiniMax.initializeMatrices(mat, prots, dq); double[] bestd = new double[size]; int[] besti = new int[size]; initializeNNCache(mat.matrix, bestd, besti); FiniteProgress prog = LOG.isVerbose() ? new FiniteProgress("Agglomerative clustering", size - 1, LOG) : null; DBIDArrayIter ix = mat.ix; for (int i = 1, end = size; i < size; i++) { end = AGNES.shrinkActiveSet(ix, builder, end, findMerge(end, mat, protiter, builder, clusters, bestd, besti, dq)); LOG.incrementProcessed(prog); } LOG.ensureCompleted(prog); return (PointerPrototypeHierarchyRepresentationResult) builder.complete(); }
9,322
public void update(Observable o, Object arg){ try { if (o instanceof Map) { System.out.println("Game Over"); } int[][] pos = Snake.getInstance().getSnakepositions(); int[] food = Food.getInstance().getPosition(); byte[] buf = new byte[1920]; buf[(food[1] * Constants.xLen + food[0]) * 3] = (byte) 255; for (int i = 0; i < pos.length; i++) { buf[((((pos[i][1] * Constants.xLen) + pos[i][0]) * 3) + 1)] = (byte) 255; } DatagramPacket packet = new DatagramPacket(buf, buf.length, InetAddress.getByName("151.217.38.29"), 1337); socket.send(packet); } catch (IOException e) { e.printStackTrace(); } }
public void update(Observable o, Object arg){ }
9,323
private static boolean isSuccess(RequestLog log){ if (log.responseCause() != null) { return false; } if (HttpSessionProtocols.isHttp(log.sessionProtocol())) { if (log.statusCode() >= 400) { return false; } } else { if (log.statusCode() != 0) { return false; } } final Object responseContent = log.responseContent(); if (responseContent instanceof RpcResponse) { return !((RpcResponse) responseContent).isCompletedExceptionally(); } return true; }
private static boolean isSuccess(RequestLog log){ if (log.responseCause() != null) { return false; } final int statusCode = log.statusCode(); if (statusCode < 100 || statusCode >= 400) { return false; } final Object responseContent = log.responseContent(); if (responseContent instanceof RpcResponse) { return !((RpcResponse) responseContent).isCompletedExceptionally(); } return true; }
9,324
private Image[] createToUpRightFrames(){ Image[] frames = new Image[5]; try { Image image1 = new Image("pics/robot/image 1232.png"); frames[0] = image1; } catch (SlickException e) { e.printStackTrace(); } try { Image image2 = new Image("pics/robot/image 2312.png"); frames[1] = image2; } catch (SlickException e) { e.printStackTrace(); } try { Image image3 = new Image("pics/robot/image 4852.png"); frames[2] = image3; } catch (SlickException e) { e.printStackTrace(); } try { Image image4 = new Image("pics/robot/image 6532.png"); frames[3] = image4; } catch (SlickException e) { e.printStackTrace(); } try { Image image5 = new Image("pics/robot/image 5892.png"); frames[4] = image5; } catch (SlickException e) { e.printStackTrace(); } return frames; }
private Image[] createToUpRightFrames(){ Image[] frames = new Image[5]; try { Image image1 = new Image("pics/robot/image 1232.png"); frames[0] = image1; Image image2 = new Image("pics/robot/image 2312.png"); frames[1] = image2; Image image3 = new Image("pics/robot/image 4852.png"); frames[2] = image3; Image image4 = new Image("pics/robot/image 6532.png"); frames[3] = image4; Image image5 = new Image("pics/robot/image 5892.png"); frames[4] = image5; } catch (SlickException e) { e.printStackTrace(); } return frames; }
9,325
public ResponseEntity<?> createGame(@RequestBody TicTacToeDTO ticTacToeDTO){ UserDetails principal = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); String username = principal.getUsername(); TicTacToeGameDTO createdGameDto; try { createdGameDto = ticTacToeService.createGame(ticTacToeDTO, username); } catch (RuntimeException e) { return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } template.convertAndSend("/tictactoe/add", createdGameDto); return new ResponseEntity<>(createdGameDto, HttpStatus.OK); }
public ResponseEntity<?> createGame(@RequestBody TicTacToeDTO ticTacToeDTO){ UserDetails principal = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); String username = principal.getUsername(); TicTacToeGameDTO createdGameDto = ticTacToeService.createGame(ticTacToeDTO, username); template.convertAndSend("/tictactoe/add", createdGameDto); return new ResponseEntity<>(createdGameDto, HttpStatus.OK); }
9,326
public void onOpenChooser(ActionEvent actionEvent){ FileChooser chooser = new FileChooser(); chooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("Memo text files", "*.txt")); chooser.setInitialDirectory(new File(System.getProperty("user.home") + "/Desktop")); try { File file = chooser.showOpenDialog(scene.getWindow()); Scanner scanner = new Scanner(file); String line = ""; wordEntryList = new WordEntryList(); while (scanner.hasNextLine()) { line = scanner.nextLine(); if (line.contains(";")) { List<String> colonList = new ArrayList<String>(Arrays.asList(line.split(";"))); for (String s : colonList) { if (s.contains(",")) { List<String> comaList = new ArrayList<String>(Arrays.asList(s.split(","))); WordEntry wordEntry = new WordEntry(comaList.get(0), comaList.get(1)); wordEntryList.addWord(wordEntry); } else { continue; } } } else { continue; } } System.out.println("Chosen: " + file.getAbsolutePath()); filePath.setText(file.getAbsolutePath()); } catch (NullPointerException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); System.out.println("File not found."); } fillTable(wordEntryList); System.out.println(wordEntryList); return; }
public void onOpenChooser(ActionEvent actionEvent){ FileChooser chooser = new FileChooser(); chooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("Memo text files", "*.txt")); chooser.setInitialDirectory(new File(System.getProperty("user.home") + "/Desktop")); try { File file = chooser.showOpenDialog(scene.getWindow()); getWordEntryListFromFile(file); } catch (NullPointerException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); System.out.println("File not found."); } fillTable(wordEntryList); return; }
9,327
public T getTree(Class<T> type){ for (int i = 0; i < trees.length; i++) { AbstractTreeIterator tree = trees[i]; if (type.isInstance(tree)) { return type.cast(tree); } } return null; }
public T getTree(Class<T> type){ for (AbstractTreeIterator tree : trees) { if (type.isInstance(tree)) { return type.cast(tree); } } return null; }
9,328
private void record10SecondsFFTtoCsv(){ if (isRecordingToCsv) return; try { isRecordingToCsv = true; recordtoCsvButton.setText("Recording ..."); CsvFileWriter.crtFile(); startedRecording = new Date(); audioCsvDispatcher.addAudioProcessor(new AudioProcessor() { FFT fft = new FFT(bufferSizeFFT); final float[] amplitudes = new float[bufferSizeFFT]; int iteration = 0; @Override public boolean process(AudioEvent audioEvent) { iteration++; float[] audioBuffer = audioEvent.getFloatBuffer(); fft.forwardTransform(audioBuffer); fft.modulus(audioBuffer, amplitudes); Log.d("d", "got audioBuffer"); runOnUiThread(new Runnable() { @Override public void run() { recordtoCsvButton.setText("Writting ... "); } }); CsvFileWriter.writeLine(fft, amplitudes, sample_rate); if (true) { CsvFileWriter.closeFile(); runOnUiThread(new Runnable() { @Override public void run() { isRecordingToCsv = false; recordtoCsvButton.setText("record to csv"); } }); audioCsvDispatcher.removeAudioProcessor(this); } return true; } @Override public void processingFinished() { } }); } catch (Exception ex) { isRecordingToCsv = false; } }
private void record10SecondsFFTtoCsv(){ if (isRecordingToCsv) return; try { isRecordingToCsv = true; recordtoCsvButton.setText("Recording ..."); CsvFileWriter.crtFile(); audioCsvDispatcher.addAudioProcessor(new AudioProcessor() { FFT fft = new FFT(bufferSizeFFT); final float[] amplitudes = new float[bufferSizeFFT]; @Override public boolean process(AudioEvent audioEvent) { float[] audioBuffer = audioEvent.getFloatBuffer(); fft.forwardTransform(audioBuffer); fft.modulus(audioBuffer, amplitudes); Log.d("d", "got audioBuffer"); runOnUiThread(() -> recordtoCsvButton.setText("Writting ... ")); CsvFileWriter.writeLine(fft, amplitudes, sample_rate); CsvFileWriter.closeFile(); runOnUiThread(() -> { isRecordingToCsv = false; recordtoCsvButton.setText("record to csv"); }); audioCsvDispatcher.removeAudioProcessor(this); return true; } @Override public void processingFinished() { } }); } catch (Exception ex) { isRecordingToCsv = false; } }
9,329
public void onMapReady(GoogleMap googleMap){ mMap = googleMap; getDataFromFirebase(); if (ActivityCompat.checkSelfPermission(this, ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { mMap.setMyLocationEnabled(true); getDeviceLocation(); } final LayoutInflater factory = getLayoutInflater(); final View telephonyView = factory.inflate(R.layout.fragment_telephony, null); MyPhoneStateListener phoneStateListener = new MyPhoneStateListener(this.getApplicationContext(), telephonyView); phoneStateListener.start(); mMap.setOnMyLocationButtonClickListener(this); }
public void onMapReady(GoogleMap googleMap){ mMap = googleMap; getDataFromFirebase(); if (ActivityCompat.checkSelfPermission(this, ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { mMap.setMyLocationEnabled(true); getDeviceLocation(); } mMap.setOnMyLocationButtonClickListener(this); }
9,330
private void sendNodeThreadPoolStats(ThreadPoolStats threadPoolStats){ String prefix = this.getPrefix("thread_pool"); Iterator<ThreadPoolStats.Stats> statsIterator = threadPoolStats.iterator(); while (statsIterator.hasNext()) { ThreadPoolStats.Stats stats = statsIterator.next(); String threadPoolType = prefix + "." + stats.getName(); this.sendGauge(threadPoolType, "threads", stats.getThreads()); this.sendGauge(threadPoolType, "queue", stats.getQueue()); this.sendGauge(threadPoolType, "active", stats.getActive()); this.sendGauge(threadPoolType, "rejected", stats.getRejected()); this.sendGauge(threadPoolType, "largest", stats.getLargest()); this.sendGauge(threadPoolType, "completed", stats.getCompleted()); } }
private void sendNodeThreadPoolStats(ThreadPoolStats threadPoolStats){ String prefix = this.getPrefix("thread_pool"); for (ThreadPoolStats.Stats stats : threadPoolStats) { String threadPoolType = prefix + "." + stats.getName(); this.sendGauge(threadPoolType, "threads", stats.getThreads()); this.sendGauge(threadPoolType, "queue", stats.getQueue()); this.sendGauge(threadPoolType, "active", stats.getActive()); this.sendGauge(threadPoolType, "rejected", stats.getRejected()); this.sendGauge(threadPoolType, "largest", stats.getLargest()); this.sendGauge(threadPoolType, "completed", stats.getCompleted()); } }
9,331
public void add(IDT id, T obj, Object source){ if (obj == null) { throw new IllegalArgumentException("Object to add may not be null"); } Map<T, Set<Object>> map = getConstructingCachedMap(id); Set<Object> set = map.get(obj); boolean fireNew = (set == null); if (fireNew) { set = new WrappedMapSet<>(IdentityHashMap.class); map.put(obj, set); } set.add(source); if (fireNew) { fireDataFacetChangeEvent(id, obj, DataFacetChangeEvent.DATA_ADDED); } }
public void add(IDT id, T obj, Object source){ Objects.requireNonNull(obj); Map<T, Set<Object>> map = getConstructingCachedMap(id); Set<Object> set = map.get(obj); boolean fireNew = (set == null); if (fireNew) { set = new WrappedMapSet<>(IdentityHashMap.class); map.put(obj, set); } set.add(source); if (fireNew) { fireDataFacetChangeEvent(id, obj, DataFacetChangeEvent.DATA_ADDED); } }
9,332
public Map<String, Object> verifyProcessDefinitionName(User loginUser, String projectName, String name){ Map<String, Object> result = new HashMap<>(); Project project = projectMapper.queryByName(projectName); Map<String, Object> checkResult = projectService.checkProjectAndAuth(loginUser, project, projectName); Status resultEnum = (Status) checkResult.get(Constants.STATUS); if (resultEnum != Status.SUCCESS) { return checkResult; } ProcessDefinition processDefinition = processDefineMapper.verifyByDefineName(project.getId(), name); if (processDefinition == null) { putMsg(result, Status.SUCCESS); } else { putMsg(result, Status.PROCESS_DEFINITION_NAME_EXIST, name); } return result; }
public CheckParamResult verifyProcessDefinitionName(User loginUser, String projectName, String name){ Project project = projectMapper.queryByName(projectName); CheckParamResult checkResult = projectService.checkProjectAndAuth(loginUser, project, projectName); if (!Status.SUCCESS.equals(checkResult.getStatus())) { return checkResult; } ProcessDefinition processDefinition = processDefineMapper.verifyByDefineName(project.getId(), name); if (processDefinition == null) { putMsg(checkResult, Status.SUCCESS); } else { putMsg(checkResult, Status.PROCESS_DEFINITION_NAME_EXIST, name); } return checkResult; }
9,333
public Result updateTenant(@ApiIgnore @RequestAttribute(value = Constants.SESSION_USER) User loginUser, @RequestParam(value = "id") int id, @RequestParam(value = "tenantCode") String tenantCode, @RequestParam(value = "queueId") int queueId, @RequestParam(value = "description", required = false) String description) throws Exception{ String userReplace = RegexUtils.escapeNRT(loginUser.getUserName()); String tenantCodeReplace = RegexUtils.escapeNRT(tenantCode); String descReplace = RegexUtils.escapeNRT(description); logger.info("login user {}, create tenant, tenantCode: {}, queueId: {}, desc: {}", userReplace, tenantCodeReplace, queueId, descReplace); Map<String, Object> result = tenantService.updateTenant(loginUser, id, tenantCode, queueId, description); return returnDataList(result); }
public Result<Void> updateTenant(@ApiIgnore @RequestAttribute(value = Constants.SESSION_USER) User loginUser, @RequestParam(value = "id") int id, @RequestParam(value = "tenantCode") String tenantCode, @RequestParam(value = "queueId") int queueId, @RequestParam(value = "description", required = false) String description) throws Exception{ String userReplace = RegexUtils.escapeNRT(loginUser.getUserName()); String tenantCodeReplace = RegexUtils.escapeNRT(tenantCode); String descReplace = RegexUtils.escapeNRT(description); logger.info("login user {}, create tenant, tenantCode: {}, queueId: {}, desc: {}", userReplace, tenantCodeReplace, queueId, descReplace); return tenantService.updateTenant(loginUser, id, tenantCode, queueId, description); }
9,334
private Panel initCommentsPanel(){ Panel comments_ = new Panel(); comments_.setLayout(new BoxLayout(comments_.getComponent(), BoxLayout.PAGE_AXIS)); comments_.add(errorLabel); comments_.add(new ScrollPane(commentsErrors)); comments_.add(roundLabel); comments_.add(new ScrollPane(commentsRound)); return comments_; }
private Panel initCommentsPanel(){ Panel comments_ = Panel.newPageBox(); comments_.add(errorLabel); comments_.add(new ScrollPane(commentsErrors)); comments_.add(roundLabel); comments_.add(new ScrollPane(commentsRound)); return comments_; }
9,335
public CollectorStepResult collect() throws ProcessingException{ String script = getScriptFromFile(); LOGGER.debug("Executing Accessibility Collector"); final String html = jsExecutor.execute(DOCUMENT_OUTER_HTML_SCRIPT).getExecutionResultAsString(); LOGGER.debug("Executing Accessibility Collector"); final String json = jsExecutor.execute(script, standard).getExecutionResultAsString(); List<AccessibilityIssue> issues = parseIssues(json); getElementsPositions(issues, html); String resultId = artifactsDAO.saveArtifactInJsonFormat(properties, issues); return CollectorStepResult.newCollectedResult(resultId); }
public CollectorStepResult collect() throws ProcessingException{ String script = getScriptFromFile(); LOGGER.debug("Executing Accessibility Collector"); final String html = jsExecutor.execute(DOCUMENT_OUTER_HTML_SCRIPT).getExecutionResultAsString(); final String json = jsExecutor.execute(script, standard).getExecutionResultAsString(); List<AccessibilityIssue> issues = parseIssues(json); getElementsPositions(issues, html); String resultId = artifactsDAO.saveArtifactInJsonFormat(properties, issues); return CollectorStepResult.newCollectedResult(resultId); }
9,336
public void removeAll(CharID id, Object source){ Map<T, Set<Object>> componentMap = getCachedMap(id); if (componentMap != null) { List<T> removedKeys = new ArrayList<>(); for (Iterator<Map.Entry<T, Set<Object>>> it = componentMap.entrySet().iterator(); it.hasNext(); ) { Entry<T, Set<Object>> me = it.next(); Set<Object> set = me.getValue(); if (set.remove(source) && set.isEmpty()) { T obj = me.getKey(); it.remove(); removedKeys.add(obj); } } if (componentMap.isEmpty()) { removeCache(id); } for (T obj : removedKeys) { fireDataFacetChangeEvent(id, obj, DataFacetChangeEvent.DATA_REMOVED); } } }
public void removeAll(CharID id, Object source){ Map<T, Set<Object>> componentMap = getCachedMap(id); if (componentMap != null) { Collection<T> removedKeys = new ArrayList<>(); for (Iterator<Map.Entry<T, Set<Object>>> it = componentMap.entrySet().iterator(); it.hasNext(); ) { Entry<T, Set<Object>> me = it.next(); Set<Object> set = me.getValue(); if (set.remove(source) && set.isEmpty()) { T obj = me.getKey(); it.remove(); removedKeys.add(obj); } } if (componentMap.isEmpty()) { removeCache(id); } removedKeys.forEach(obj -> fireDataFacetChangeEvent(id, obj, DataFacetChangeEvent.DATA_REMOVED)); } }
9,337
String[] digest(Thing thing, String path, Collection news){ StringBuilder subject = new StringBuilder(); StringBuilder content = new StringBuilder(); String[] unneededNames = new String[] { AL.is, AL.times, AL.sources, AL.text }; String best = ""; if (!AL.empty(path)) content.append(path).append('\n'); String currentPath = null; for (Iterator it = news.iterator(); it.hasNext(); ) { Thing t = (Thing) it.next(); String nl_text = t.getString(AL.text); if (best.length() == 0 || (nl_text.length() > best.length() && nl_text.length() < 100)) best = nl_text; Collection sources = t.getThings(AL.sources); if (!AL.empty(sources)) { String source = ((Thing) sources.iterator().next()).getName(); if (!AL.empty(source) && !path.equals(source)) { if (currentPath == null || !currentPath.equals(source)) content.append(source).append('\n'); currentPath = source; } } content.append('\"').append(nl_text).append('\"').append('\n'); String[] names = Array.sub(t.getNamesAvailable(), unneededNames); if (!AL.empty(names)) { Writer.toString(content, t, null, names, true); content.append('\n'); } } subject.append(best).append(" (").append(thing.getName()).append(")"); return new String[] { subject.toString(), content.toString() }; }
String[] digest(Thing thing, String path, Collection news){ if (AL.empty(news)) return null; StringBuilder content = new StringBuilder(); String[] unneededNames = new String[] { AL.is, AL.times, AL.sources, AL.text }; if (!AL.empty(path)) content.append(path).append('\n'); String currentPath = null; for (Iterator it = news.iterator(); it.hasNext(); ) { Thing t = (Thing) it.next(); String nl_text = t.getString(AL.text); Collection sources = t.getThings(AL.sources); if (!AL.empty(sources)) { String source = ((Thing) sources.iterator().next()).getName(); if (!AL.empty(source) && !path.equals(source)) { if (currentPath == null || !currentPath.equals(source)) content.append(source).append('\n'); currentPath = source; } } content.append('\"').append(nl_text).append('\"').append('\n'); String[] names = Array.sub(t.getNamesAvailable(), unneededNames); if (!AL.empty(names)) { Writer.toString(content, t, null, names, true); content.append('\n'); } } return new String[] { thing.getName(), content.toString() }; }
9,338
public Collection<AbstractServerHandler> metaServerHandlers(){ Collection<AbstractServerHandler> list = new ArrayList<>(); list.add(metaConnectionHandler()); list.add(getChangeListRequestHandler()); list.add(getNodesRequestHandler()); return list; }
public Collection<AbstractServerHandler> metaServerHandlers(){ Collection<AbstractServerHandler> list = new ArrayList<>(); list.add(metaConnectionHandler()); list.add(getNodesRequestHandler()); return list; }
9,339
void validProductSectionNotExistTest(){ Warehouse warehouse = new Warehouse().warehouseCode("SP").warehouseName("Sao Paulo").build(); Section section = new Section().sectionCode("LA").sectionName("Laticionios").warehouse(warehouse).maxLength(10).build(); when(mockProductRepository.existsProductBySection(any(Section.class))).thenReturn(false); ProductException productException = assertThrows(ProductException.class, () -> productService.validProductSection(section.getSectionCode())); String expectedMessage = "Produto nao faz parte do setor, por favor verifique o setor correto!"; assertTrue(expectedMessage.contains(productException.getMessage())); }
void validProductSectionNotExistTest(){ when(mockProductRepository.existsProductBySection(any(Section.class))).thenReturn(false); ProductException productException = assertThrows(ProductException.class, () -> productService.validProductSection("LA")); String expectedMessage = "Produto nao faz parte do setor, por favor verifique o setor correto!"; assertTrue(expectedMessage.contains(productException.getMessage())); }
9,340
public Map<String, Object> countDefinitionByUser(User loginUser, int projectId){ Map<String, Object> result = new HashMap<>(); Integer[] projectIdArray = getProjectIdsArrays(loginUser, projectId); List<DefinitionGroupByUser> defineGroupByUsers = processDefinitionMapper.countDefinitionGroupByUser(loginUser.getId(), projectIdArray, isAdmin(loginUser)); DefineUserDto dto = new DefineUserDto(defineGroupByUsers); result.put(Constants.DATA_LIST, dto); putMsg(result, Status.SUCCESS); return result; }
public Result<DefineUserDto> countDefinitionByUser(User loginUser, int projectId){ Integer[] projectIdArray = getProjectIdsArrays(loginUser, projectId); List<DefinitionGroupByUser> defineGroupByUsers = processDefinitionMapper.countDefinitionGroupByUser(loginUser.getId(), projectIdArray, isAdmin(loginUser)); DefineUserDto dto = new DefineUserDto(defineGroupByUsers); return Result.success(dto); }
9,341
public Diff getDiffSinceLastFetch(Iterable<RevCommit> newCommits){ Iterator<RevCommit> newCommitsIterator = newCommits.iterator(); if (!newCommitsIterator.hasNext()) { return new Diff(); } List<RevCommit> result = new ArrayList<>(); newCommitsIterator.forEachRemaining(result::add); Diff diffSinceLastFetch = getDiff(result); for (RevCommit commit : result) { List<DiffEntry> diffEntriesInCommit = getDiffEntries(commit); for (DiffEntry diffEntry : diffEntriesInCommit) { for (ChangedFile file : diffSinceLastFetch.getChangedFiles()) { if (diffEntry.getNewPath().contains(file.getName())) { file.addCommit(commit); } } } } return diffSinceLastFetch; }
public Diff getDiffSinceLastFetch(ObjectId oldObjectId, ObjectId newObjectId){ List<RevCommit> newCommits = getCommitsSinceLastFetch(oldObjectId, newObjectId); Diff diffSinceLastFetch = getDiff(newCommits); for (RevCommit commit : newCommits) { List<DiffEntry> diffEntriesInCommit = getDiffEntries(commit); for (DiffEntry diffEntry : diffEntriesInCommit) { for (ChangedFile file : diffSinceLastFetch.getChangedFiles()) { if (diffEntry.getNewPath().contains(file.getName())) { file.addCommit(commit); } } } } return diffSinceLastFetch; }
9,342
public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result){ mOOCCameraUploadSync = mCameraUploadsSyncStorageManager.getCameraUploadSync(null, null, null); String localCameraPath = mConfig.getSourcePath(); File[] localFiles = new File[0]; if (localCameraPath != null) { File cameraFolder = new File(localCameraPath); localFiles = cameraFolder.listFiles(); } if (!result.isSuccess()) { Log_OC.d(TAG, "Remote folder does not exist yet, uploading the files for the " + "first time, if any"); if (result.getCode() == RemoteOperationResult.ResultCode.FILE_NOT_FOUND) { for (File localFile : localFiles) { handleNewFile(localFile); } } } else { ArrayList<Object> remoteObjects = result.getData(); compareFiles(localFiles, FileStorageUtils.castObjectsIntoRemoteFiles(remoteObjects)); } mPerformedOperationsCounter++; boolean mOnlyPictures = mConfig.isEnabledForPictures() && !mConfig.isEnabledForVideos(); boolean mOnlyVideos = mConfig.isEnabledForVideos() && !mConfig.isEnabledForPictures(); boolean mPicturesAndVideos = mConfig.isEnabledForPictures() && mConfig.isEnabledForVideos(); if (mOnlyPictures && mPerformedOperationsCounter == 1 || mOnlyVideos && mPerformedOperationsCounter == 1 || mPicturesAndVideos && mConfig.getUploadPathForPictures().equals(mConfig.getUploadPathForVideos()) && mPerformedOperationsCounter == 1 || mPicturesAndVideos && mPerformedOperationsCounter == 2) { finish(); } }
public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result){ mOOCCameraUploadSync = mCameraUploadsSyncStorageManager.getCameraUploadSync(null, null, null); String localCameraPath = mConfig.getSourcePath(); File[] localFiles = new File[0]; if (localCameraPath != null) { File cameraFolder = new File(localCameraPath); localFiles = cameraFolder.listFiles(); } if (!result.isSuccess()) { if (result.getCode() == RemoteOperationResult.ResultCode.FILE_NOT_FOUND) { Log_OC.d(TAG, "Remote folder does not exist yet, uploading the files for the " + "first time, if any"); for (File localFile : localFiles) { handleNewFile(localFile); } } } else { ArrayList<Object> remoteObjects = result.getData(); compareFiles(localFiles, FileStorageUtils.castObjectsIntoRemoteFiles(remoteObjects)); } mPerformedOperationsCounter++; finishIfOperationsCompleted(); }
9,343
public Collection<AbstractHtml> findTagsByAttributeName(final boolean parallel, final String attributeName) throws NullValueException{ if (attributeName == null) { throw new NullValueException("The attributeName should not be null"); } final List<Lock> locks = new ArrayList<>(getReadLocks(rootTags)); for (final Lock lock : locks) { lock.lock(); } Collections.reverse(locks); try { return buildAllTagsStream(parallel).filter(tag -> getAttributeByNameLockless(tag, attributeName) != null).collect(Collectors.toSet()); } finally { for (final Lock lock : locks) { lock.unlock(); } } }
public Collection<AbstractHtml> findTagsByAttributeName(final boolean parallel, final String attributeName) throws NullValueException{ if (attributeName == null) { throw new NullValueException("The attributeName should not be null"); } final Collection<Lock> locks = lockAndGetReadLocks(rootTags); try { return buildAllTagsStream(parallel).filter(tag -> getAttributeByNameLockless(tag, attributeName) != null).collect(Collectors.toSet()); } finally { for (final Lock lock : locks) { lock.unlock(); } } }
9,344
public PersistencePolicies getPersistence(String topic, boolean applied) throws PulsarAdminException{ try { return getPersistenceAsync(topic, applied).get(this.readTimeoutMs, TimeUnit.MILLISECONDS); } catch (ExecutionException e) { throw (PulsarAdminException) e.getCause(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new PulsarAdminException(e); } catch (TimeoutException e) { throw new PulsarAdminException.TimeoutException(e); } }
public PersistencePolicies getPersistence(String topic, boolean applied) throws PulsarAdminException{ return sync(() -> getPersistenceAsync(topic, applied)); }
9,345
public void createInvoice(String filename){ File invoiceFile = new File(filename); SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); SimpleDateFormat dateTimeFormat = new SimpleDateFormat("dd/MM/yyyy, HH:MM"); String currentTime = dateTimeFormat.format(Calendar.getInstance().getTime()); BufferedWriter bufferedWriter = null; try { bufferedWriter = new BufferedWriter(new FileWriter(invoiceFile)); bufferedWriter.write("INVOICE FOR: " + brand + " " + number + "\r\n"); bufferedWriter.write("--------------------------------------------\r\n"); bufferedWriter.write("PURCHASES\r\n"); bufferedWriter.write("Date\t\tAmount\tDescription\r\n"); for (Purchase purchase : purchases) { bufferedWriter.write(dateFormat.format(purchase.getDate().getTime()) + "\t" + purchase.getAmount() + "\t" + purchase.getDescription() + "\r\n"); } bufferedWriter.write("--------------------------------------------\r\n"); bufferedWriter.write("TOTAL AMOUNT: USD " + balance + "\n"); bufferedWriter.write("Remaining limit: USD " + (limit - balance) + "\n"); bufferedWriter.write("--------------------------------------------\r\n"); bufferedWriter.write("Invoice generated at " + currentTime); System.out.println("CC " + number + " | Invoice generated in " + filename); } catch (IOException e) { System.err.println("Error while exporting credit card invoice: " + e.getMessage()); } finally { try { bufferedWriter.close(); } catch (IOException e) { System.err.println("Error while closing invoice BufferedWriter: " + e.getMessage()); } catch (NullPointerException e) { System.err.println("Error while closing invoice BufferedWriter: " + e.getMessage()); } } }
public void createInvoice(String filename){ File invoiceFile = new File(filename); SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); SimpleDateFormat dateTimeFormat = new SimpleDateFormat("dd/MM/yyyy, HH:MM"); String currentTime = dateTimeFormat.format(Calendar.getInstance().getTime()); BufferedWriter bufferedWriter = null; try { bufferedWriter = new BufferedWriter(new FileWriter(invoiceFile)); bufferedWriter.write("INVOICE FOR: " + brand + " " + number + "\r\n"); bufferedWriter.write("--------------------------------------------\r\n"); bufferedWriter.write("PURCHASES\r\n"); bufferedWriter.write("Date\t\tAmount\tDescription\r\n"); for (Purchase purchase : purchases) { bufferedWriter.write(dateFormat.format(purchase.getDate().getTime()) + "\t" + purchase.getAmount() + "\t" + purchase.getDescription() + "\r\n"); } bufferedWriter.write("--------------------------------------------\r\n"); bufferedWriter.write("TOTAL AMOUNT: USD " + balance + "\n"); bufferedWriter.write("Remaining limit: USD " + (limit - balance) + "\n"); bufferedWriter.write("--------------------------------------------\r\n"); bufferedWriter.write("Invoice generated at " + currentTime); System.out.println("CC " + number + " | Invoice generated in " + filename); } catch (IOException e) { System.err.println("Error while exporting credit card invoice: " + e.getMessage()); } finally { try { bufferedWriter.close(); } catch (IOException | NullPointerException e) { System.err.println("Error while closing invoice BufferedWriter: " + e.getMessage()); } } }
9,346
private void saveData(){ configurationManager.loadProfile(String.valueOf((profileBox.getSelectedItem()))); ConnectionBuilder connParameters = new ConnectionBuilder.Builder(connNameTF.getText()).userName(usernameTF.getText()).password(passwordTF.getText()).url(urlTF.getText()).jar(jarTF.getText()).profile(String.valueOf((profileBox.getSelectedItem()))).driverName(configurationManager.getIProfile().getDriverName()).rawRetainDays(rawDataDaysRetainTF.getText()).olapRetainDays(olapDataDaysRetainTF.getText()).build(); configurationManager.saveConnection(connParameters); }
private void saveData(){ ConnectionBuilder connParameters = new ConnectionBuilder.Builder(connNameTF.getText()).userName(usernameTF.getText()).password(passwordTF.getText()).url(urlTF.getText()).jar(jarTF.getText()).profile(String.valueOf((profileBox.getSelectedItem()))).driverName(configurationManager.getIProfile().getDriverName()).rawRetainDays(rawDataDaysRetainTF.getText()).olapRetainDays(olapDataDaysRetainTF.getText()).build(); configurationManager.saveConnection(connParameters); }
9,347
public void processEl160Test(){ ClassMethodIdVarArg cid_ = getClassMethodId3("myvar.sampleSix(1)", "myvar", MY_CLASS); assertEq("myimpl.MyIntOne", cid_.getClassName()); MethodId id_ = cid_.getConstraints(); assertEq("sampleSix", id_.getName()); StringList params_ = id_.getParametersTypes(); assertEq(1, params_.size()); assertEq("$int", params_.first()); assertTrue(id_.isVararg()); assertEq(0, cid_.getNaturalVararg()); assertTrue(!id_.isStaticMethod()); }
public void processEl160Test(){ ClassMethodIdVarArg cid_ = getClassMethodId3("myvar.sampleSix(1)", "myvar", MY_CLASS); assertEq("myimpl.MyIntOne", cid_.getClassName()); MethodId id_ = cid_.getConstraints(); assertEq("sampleSix", id_.getName()); assertEq(1, id_.getParametersTypesLength()); assertEq("$int", id_.getParametersType(0)); assertTrue(id_.isVararg()); assertEq(0, cid_.getNaturalVararg()); assertTrue(!id_.isStaticMethod()); }
9,348
public void display(ReplayBin bin){ this.displayed = bin; if (bin == null) { this.replayTable.setItems(FXCollections.emptyObservableList()); return; } ObservableList<ReplayEntry> entries = (controller.getTableFilter().isInvalid()) ? bin.getReplaysObservable() : new FilteredList<>(bin.getReplaysObservable(), controller.getTableFilter()); this.replayTable.setItems(entries); this.selectionModel.select(displayed); entries.removeListener(binChangeListener); entries.addListener(binChangeListener); }
public void display(ReplayBin bin){ this.displayed = bin; if (bin == null) { this.replayTable.setItems(FXCollections.emptyObservableList()); return; } ObservableList<ReplayEntry> entries = (controller.getTableFilter().isInvalid()) ? bin.getReplaysObservable() : new FilteredList<>(bin.getReplaysObservable(), controller.getTableFilter()); this.replayTable.setItems(entries); this.selectionModel.select(displayed); }
9,349
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l){ Listing clicked_listing = listingsAdapter.getItem(i); UpdateListing(clicked_listing); Log.d("UPDATE_LISTING_STATUS", String.valueOf(clicked_listing.CRN)); listingsAdapter.notifyDataSetChanged(); }
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l){ Listing clicked_listing = listingsAdapter.getItem(i); UpdateListing(clicked_listing); listingsAdapter.notifyDataSetChanged(); }
9,350
public void handleListItemEvent(){ String key = redisKeys.getSelectionModel().getSelectedItem(); switch(redis.type(key)) { case STRING: redisResult.setText(redis.get(key).string); showResult(true, false, false); break; case SET: redisSetResultListProperty.set(FXCollections.observableArrayList(redis.get(key).set)); showResult(false, true, false); break; case HASH: redisHashControl.setKey(key); redisHashControl.getRedisHashResult().setItems(FXCollections.observableArrayList(redis.get(key).hash.entrySet())); showResult(false, false, true); break; default: break; } }
public void handleListItemEvent(){ String key = redisKeys.getSelectionModel().getSelectedItem(); switch(redis.type(key)) { case STRING: redisResult.setText(redis.get(key).string); showResult(true, false, false); break; case SET: redisSetResultListProperty.set(FXCollections.observableArrayList(redis.get(key).set)); showResult(false, true, false); break; case HASH: redisHashView.setItems(FXCollections.observableArrayList(redis.get(key).hash.entrySet())); showResult(false, false, true); break; default: break; } }
9,351
protected final void tick(final double delta){ camera.transform.translate(movementSpeed * xMovement, movementSpeed * yMovement, movementSpeed * zMovement); camera.transform.rotate(rotationSpeed, pitch, yaw, 0f); super.tick(delta); long elapsed = System.currentTimeMillis() - startTime; float f = elapsed * (0.001f * speed); int size = cubes.size(); for (int i = 0; i < size; i++) { Cube cube = cubes.get(i); float s = (float) Math.sin(f + (float) i / (cubeCount / spread)); float c = (float) Math.cos(f + (float) i / (cubeCount / spread)); float alt = (i % 2 == 0 ? c : s); cube.setPosition(s, c, alt); cube.rotate(speed, c, s, 0); cube.scale(1 + (alt * 0.0008f), 1 + (alt * 0.0008f), 1 + (alt * 0.0008f)); } }
protected final void tick(final double delta){ camera.transform.translate(movementSpeed * xMovement, movementSpeed * yMovement, movementSpeed * zMovement); super.tick(delta); long elapsed = System.currentTimeMillis() - startTime; float f = elapsed * (0.001f * speed); int size = cubes.size(); for (int i = 0; i < size; i++) { Cube cube = cubes.get(i); float s = (float) Math.sin(f + (float) i / (cubeCount / spread)); float c = (float) Math.cos(f + (float) i / (cubeCount / spread)); float alt = (i % 2 == 0 ? c : s); cube.setPosition(s, c, alt); cube.rotate(speed, c, s, 0); cube.scale(1 + (alt * 0.0008f), 1 + (alt * 0.0008f), 1 + (alt * 0.0008f)); } }
9,352
public void draw(int x, int y){ super.draw(x, y); int bodyHeat = eskimo.getBodyHeat(); int stamina = eskimo.getStamina(); ClearSnowPolicy clearSnowPolicy = eskimo.getClearPatchStrategy(); RescueFriendPolicy rescueFriendPolicy = eskimo.getHelpFriendStrategy(); FallInWaterPolicy swimOutPolicy = eskimo.getSwimToShoreStrategy(); Tile tile = eskimo.getTile(); if (Environment.getInstance().getCurrentPlayer() != null) { if (Environment.getInstance().getCurrentPlayer().equals(eskimo)) { GameJFrame.getInstance().CharacterOutInfo(String.format("eskimo\n\nbody heat: %d\nstamina: %d\nclearPatchStrategy: %s\nhelpFriendStrategy: %s\nswimToShoreStrategy: %s\ntile: %d", bodyHeat, stamina, clearSnowPolicy.toString(), rescueFriendPolicy.toString(), swimOutPolicy.toString(), tile.getID())); } } }
public void draw(int x, int y){ super.draw(x, y); int bodyHeat = eskimo.getBodyHeat(); int stamina = eskimo.getStamina(); ClearSnowPolicy clearSnowPolicy = eskimo.getClearPatchStrategy(); RescueFriendPolicy rescueFriendPolicy = eskimo.getHelpFriendStrategy(); FallInWaterPolicy swimOutPolicy = eskimo.getSwimToShoreStrategy(); Tile tile = eskimo.getTile(); if (Environment.getInstance().getCurrentPlayer() != null && Environment.getInstance().getCurrentPlayer().equals(eskimo)) { GameJFrame.getInstance().CharacterOutInfo(String.format("eskimo\n\nbody heat: %d\nstamina: %d\nclearPatchStrategy: %s\nhelpFriendStrategy: %s\nswimToShoreStrategy: %s\ntile: %d", bodyHeat, stamina, clearSnowPolicy.toString(), rescueFriendPolicy.toString(), swimOutPolicy.toString(), tile.getID())); } }
9,353
void postPerson() throws Exception{ mockMvc = MockMvcBuilders.standaloneSetup(personController).build(); mockMvc.perform(MockMvcRequestBuilders.post("/api/person").contentType(MediaType.APPLICATION_JSON_UTF8).content("{\n" + " \"name\" : \"martin2\",\n" + " \"age\" : 20,\n" + " \"bloodType\" : \"A\"\n" + "}")).andDo(print()).andExpect(status().isCreated()); }
void postPerson() throws Exception{ mockMvc.perform(MockMvcRequestBuilders.post("/api/person").contentType(MediaType.APPLICATION_JSON_UTF8).content("{\n" + " \"name\" : \"martin2\",\n" + " \"age\" : 20,\n" + " \"bloodType\" : \"A\"\n" + "}")).andDo(print()).andExpect(status().isCreated()); }
9,354
public void addBookToDB(String sql, Book newBook){ try { Class.forName("org.apache.derby.jdbc.ClientDriver"); try (Connection conn = DriverManager.getConnection("jdbc:derby://localhost/library")) { try (PreparedStatement stm = conn.prepareStatement(sql)) { stm.setString(1, newBook.getBarcode()); stm.setString(2, newBook.getTitle()); stm.setString(3, newBook.getAuthor()); stm.setString(4, newBook.getIsbn()); stm.setInt(5, newBook.getNoOfPages()); stm.setString(6, newBook.getBranch()); stm.setString(7, "BOOK"); int results = stm.executeUpdate(); System.out.println("records amended : " + results); } } } catch (ClassNotFoundException e) { System.out.println(e); } catch (SQLException e) { System.out.println(e); } }
public void addBookToDB(String sql, Book newBook){ try { try (Connection conn = DriverManager.getConnection("jdbc:derby://localhost/library")) { try (PreparedStatement stm = conn.prepareStatement(sql)) { stm.setString(1, newBook.getBarcode()); stm.setString(2, newBook.getTitle()); stm.setString(3, newBook.getAuthor()); stm.setString(4, newBook.getIsbn()); stm.setInt(5, newBook.getNoOfPages()); stm.setString(6, newBook.getBranch()); stm.setString(7, "BOOK"); int results = stm.executeUpdate(); System.out.println("records amended : " + results); } } } catch (SQLException e) { System.out.println(e); } }
9,355
public ResponseEntity<?> makeTransfer(@PathVariable String number1, @PathVariable String number2, @PathVariable Double money) throws AccountDoesNotExistException{ Account firstAccount = accountService.getOneAccount(number1); Account secondAccount = accountService.getOneAccount(number2); List<Account> updatedAccounts = transferService.makeTransfer(firstAccount, secondAccount, money); return new ResponseEntity<>(updatedAccounts, HttpStatus.OK); }
public ResponseEntity<?> makeTransfer(@PathVariable String firstAccountNumber, @PathVariable String secondAccountNumber, @PathVariable Double money) throws AccountDoesNotExistException{ List<Account> updatedAccounts = transferService.makeTransfer(firstAccountNumber, secondAccountNumber, money); return new ResponseEntity<>(updatedAccounts, HttpStatus.OK); }
9,356
public void shouldGetProductsWhenLoginSuccFromNet(){ when(mockActivity.isConnectionAvailable()).thenReturn(true); when(mockActivity.hasGetProducts()).thenReturn(false); presenter.startLogin("user", "password"); verify(userRepository).authorizeUser(any(User.class), loginCB.capture()); UserRepository.UserResponse userResponse = userRepository.new UserResponse(); userResponse.setUserInformation(new User("user", "password")); loginCB.getValue().success(userResponse, null); verify(syncManager).syncProductsWithProgramAsync(getProductsCB.capture()); getProductsCB.getValue().onCompleted(); }
public void shouldGetProductsWhenLoginSuccFromNet(){ when(mockActivity.isConnectionAvailable()).thenReturn(true); when(mockActivity.hasGetProducts()).thenReturn(false); presenter.startLogin("user", "password"); verify(userRepository).authorizeUser(any(User.class), loginCB.capture()); loginCB.getValue().success(new User("user", "password"), null); verify(syncManager).syncProductsWithProgramAsync(getProductsCB.capture()); getProductsCB.getValue().onCompleted(); }
9,357
private static void handleMousePressed(Pane pane, MouseEvent event){ if (firstSelected.isEmpty()) firstSelected = Optional.of(pane); int x = GridPane.getRowIndex(pane), y = GridPane.getColumnIndex(pane); System.out.printf("[Pressed] x: %d, y: %d\n", x, y); selectedPanes.add(new Pair<>(x, y)); event.consume(); }
private static void handleMousePressed(Pane pane, MouseEvent event){ firstSelected = pane; int x = GridPane.getRowIndex(pane), y = GridPane.getColumnIndex(pane); System.out.printf("[Pressed] x: %d, y: %d\n", x, y); selectedPanes.add(new Pair<>(x, y)); event.consume(); }
9,358
public void writeClusterIdAndToken() throws IOException{ Properties properties = new Properties(); setFields(properties); RandomAccessFile file = new RandomAccessFile(new File(metaDir, VERSION_FILE), "rws"); FileOutputStream out = null; try { file.seek(0); out = new FileOutputStream(file.getFD()); properties.store(out, null); file.setLength(out.getChannel().position()); } finally { if (out != null) { out.close(); } file.close(); } }
public void writeClusterIdAndToken() throws IOException{ Properties properties = new Properties(); setFields(properties); writePropertiesToFile(properties, VERSION_FILE); }
9,359
public List<StandUpSituation> getStandUpSituation(){ try { MongoDatabase database = MongoDBDAO.getConnectedDatabase(); MongoCollection<StandUpSituation> situationMongoCollection = database.getCollection(MongoDBDAO.WORRYHEADSSITUATIONS_COLLECTION, StandUpSituation.class); AggregateIterable<StandUpSituation> situations = situationMongoCollection.aggregate(Arrays.asList(Aggregates.sample(1))); StandUpSituation situation = null; for (StandUpSituation temp : situations) { situation = temp; } List<StandUpSituation> standUpSituations = new ArrayList(); standUpSituations.add(situation); return standUpSituations; } catch (NullPointerException ne) { System.out.println("Could not get random stand up situations"); ne.printStackTrace(); return null; } catch (Exception e) { System.out.println("Some problem in getting StandUp situation"); e.printStackTrace(); return null; } }
public StandUpSituation getStandUpSituation(){ try { MongoDatabase database = MongoDBDAO.getConnectedDatabase(); MongoCollection<StandUpSituation> situationMongoCollection = database.getCollection(MongoDBDAO.STANDUPSITUATIONS_COLLECTION, StandUpSituation.class); AggregateIterable<StandUpSituation> situations = situationMongoCollection.aggregate(Arrays.asList(Aggregates.sample(1))); StandUpSituation situation = null; for (StandUpSituation temp : situations) { situation = temp; } return situation; } catch (NullPointerException ne) { System.out.println("Could not get random make believe situation"); ne.printStackTrace(); return null; } catch (Exception e) { System.out.println("Some problem in getting Make believe situation"); e.printStackTrace(); return null; } }
9,360
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults){ if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { mListViewModel.fetchTracks(); } else { mSwipeRefreshLayout.setEnabled(true); mStopTaskFab.hide(); mStartTaskFab.hide(); mMessage.setVisibility(View.VISIBLE); mMessage.setText(R.string.permission_denied); mListViewModel.setLoading(false); showViewPermissionMessage(); } }
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults){ if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { mListViewModel.fetchTracks(); } else { mSwipeRefreshLayout.setEnabled(true); mStartTaskFab.hide(); mMessage.setVisibility(View.VISIBLE); mMessage.setText(R.string.permission_denied); mListViewModel.setLoading(false); showViewPermissionMessage(); } }
9,361
public boolean delete(int id){ if (!books.containsKey(id)) { return false; } books.remove(id); System.out.println("*** Book with id=" + id + " was deleted"); counterService.decrement("book.count"); gaugeService.submit("book.count", counter); return true; }
public boolean delete(int id){ if (!books.containsKey(id)) { return false; } books.remove(id); System.out.println("*** Book with id=" + id + " was deleted"); gaugeService.submit("book.count", books.size()); return true; }
9,362
public void run(){ FilePart fp; byte[] data = new byte[MAX_FILE_PART_SIZE]; while (true) { if (!loggedIn) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } continue; } fp = filePartsToSend.poll(); if (fp != null) { try { fileMessageProcessor.addFileDataToFilePart(fp, MAX_FILE_PART_SIZE, data); } catch (IOException e) { e.printStackTrace(); } if (fp.getFileData() != null) { System.out.println("Sending message part " + fp.getCurrentPartNum() + " of " + fp.getTotalParts() + ", filename: " + fp.getFileName()); Network.sendMsg(new FileMessage(fp.getFileName(), fp.getFilePath(), fp.getFileData(), fp.getTotalParts(), fp.getCurrentPartNum())); } } else { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }
public void run(){ FilePart fp; byte[] data = new byte[MAX_FILE_PART_SIZE]; while (true) { if (!loggedIn) { break; } fp = filePartsToSend.poll(); if (fp != null) { try { fileMessageProcessor.addFileDataToFilePart(fp, MAX_FILE_PART_SIZE, data); } catch (IOException e) { e.printStackTrace(); } if (fp.getFileData() != null) { Network.sendMsg(new FileMessage(fp.getFileName(), fp.getFilePath(), fp.getFileData(), fp.getTotalParts(), fp.getCurrentPartNum())); } } else { try { lock.lock(); condition.await(); lock.unlock(); } catch (InterruptedException e) { e.printStackTrace(); } } } }
9,363
private Map<String, Object> getCreateProcessResult(User loginUser, String currentProjectName, Map<String, Object> result, ProcessMeta processMeta, String processDefinitionName, String importProcessParam){ Map<String, Object> createProcessResult = null; try { createProcessResult = createProcessDefinition(loginUser, currentProjectName, processDefinitionName + "_import_" + DateUtils.getCurrentTimeStamp(), importProcessParam, processMeta.getProcessDefinitionDescription(), processMeta.getProcessDefinitionLocations(), processMeta.getProcessDefinitionConnects()); putMsg(result, Status.SUCCESS); } catch (Exception e) { logger.error("import process meta json data: {}", e.getMessage(), e); putMsg(result, Status.IMPORT_PROCESS_DEFINE_ERROR); } return createProcessResult; }
private Result<Integer> getCreateProcessResult(User loginUser, String currentProjectName, ProcessMeta processMeta, String processDefinitionName, String importProcessParam){ Result<Integer> createProcessResult = null; try { createProcessResult = createProcessDefinition(loginUser, currentProjectName, processDefinitionName + "_import_" + DateUtils.getCurrentTimeStamp(), importProcessParam, processMeta.getProcessDefinitionDescription(), processMeta.getProcessDefinitionLocations(), processMeta.getProcessDefinitionConnects()); } catch (Exception e) { logger.error("import process meta json data: {}", e.getMessage(), e); createProcessResult = Result.error(Status.IMPORT_PROCESS_DEFINE_ERROR); } return createProcessResult; }
9,364
public final boolean equals(final Object o){ if (Arez.areNativeComponentsEnabled()) { if (this == o) { return true; } else if (null == o || !(o instanceof Arez_ReadWriteObserveModel)) { return false; } else { final Arez_ReadWriteObserveModel that = (Arez_ReadWriteObserveModel) o; return $$arezi$$_id() == that.$$arezi$$_id(); } } else { return super.equals(o); } }
public final boolean equals(final Object o){ if (Arez.areNativeComponentsEnabled()) { if (o instanceof Arez_ReadWriteObserveModel) { final Arez_ReadWriteObserveModel that = (Arez_ReadWriteObserveModel) o; return this.$$arezi$$_id() == that.$$arezi$$_id(); } else { return false; } } else { return super.equals(o); } }
9,365
public DynamicObject empty(DynamicObject hash){ assert HashOperations.verifyStore(getContext(), hash); assert HashOperations.verifyStore(getContext(), null, 0, null, null); Layouts.HASH.setStore(hash, null); Layouts.HASH.setSize(hash, 0); Layouts.HASH.setFirstInSequence(hash, null); Layouts.HASH.setLastInSequence(hash, null); assert HashOperations.verifyStore(getContext(), hash); return hash; }
public DynamicObject empty(DynamicObject hash){ assert HashOperations.verifyStore(getContext(), hash); Layouts.HASH.setStore(hash, null); Layouts.HASH.setSize(hash, 0); Layouts.HASH.setFirstInSequence(hash, null); Layouts.HASH.setLastInSequence(hash, null); assert HashOperations.verifyStore(getContext(), hash); return hash; }
9,366
public AttributeValue getCurrentValueRepresentation(IAttribute attribute, IWorkItem workItem) throws TeamRepositoryException{ IAuditableServer auditSrv = workItemServer.getAuditableServer(); Object attributeValue = attribute.getValue(auditSrv, workItem, monitor); IProjectAreaHandle pa = workItem.getProjectArea(); Identifier<IAttribute> identifier = WorkItemAttributes.getPropertyIdentifier(attribute.getIdentifier()); AttributeValue value = new AttributeValue("", ""); ; if (attributeValue != null) { if (WorkItemAttributes.RESOLUTION.equals(identifier)) { value = ResolutionHelpers.getResolution(attributeValue, workItem, workItemServer, monitor); } else if (WorkItemAttributes.STATE.equals(identifier)) { value = StateHelpers.getState(attributeValue, workItem, workItemServer, monitor); } else if (WorkItemAttributes.CATEGORY.equals(identifier)) { value = CategoryHelpers.getCategory(attributeValue, workItemServer, teamRawService, monitor); } else if (WorkItemAttributes.TARGET.equals(identifier)) { value = TargetHelpers.getTarget(attributeValue, auditSrv, workItemServer, teamRawService, monitor); } else if (WorkItemAttributes.VERSION.equals(identifier)) { value = FoundInHelpers.getFoundIn(attributeValue, workItemServer, teamRawService, monitor); } else { value = LiteralHelpers.getLiteral(attribute, attributeValue, workItemServer, monitor); } } return value; }
public AttributeValue getCurrentValueRepresentation(IAttribute attribute, IWorkItem workItem) throws TeamRepositoryException{ IAuditableServer auditSrv = workItemServer.getAuditableServer(); Object attributeValue = attribute.getValue(auditSrv, workItem, monitor); Identifier<IAttribute> identifier = WorkItemAttributes.getPropertyIdentifier(attribute.getIdentifier()); AttributeValue value = new AttributeValue("", ""); if (attributeValue != null) { if (WorkItemAttributes.RESOLUTION.equals(identifier)) { value = ResolutionHelpers.getResolution(attributeValue, workItem, workItemServer, monitor); } else if (WorkItemAttributes.STATE.equals(identifier)) { value = StateHelpers.getState(attributeValue, workItem, workItemServer, monitor); } else if (WorkItemAttributes.CATEGORY.equals(identifier)) { value = CategoryHelpers.getCategory(attributeValue, workItemServer, teamRawService, monitor); } else if (WorkItemAttributes.TARGET.equals(identifier)) { value = TargetHelpers.getTarget(attributeValue, auditSrv, teamRawService, monitor); } else if (WorkItemAttributes.VERSION.equals(identifier)) { value = FoundInHelpers.getFoundIn(attributeValue, workItemServer, teamRawService, monitor); } else { value = LiteralHelpers.getLiteral(attribute, attributeValue, workItemServer, monitor); } } return value; }
9,367
public void actionPerformed(ActionEvent e){ if (fileChooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) { try { new XMLFile(fileChooser.getSelectedFile().getPath(), studentController).writeFile(); } catch (IOException exception) { exception.printStackTrace(); } catch (TransformerException exception) { exception.printStackTrace(); } catch (ParserConfigurationException exception) { exception.printStackTrace(); } mainFrame.updateMainFrame(); } }
public void actionPerformed(ActionEvent e){ if (fileChooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) { try { new XMLFile(fileChooser.getSelectedFile().getPath(), studentController).writeFile(); } catch (IOException | TransformerException | ParserConfigurationException exception) { exception.printStackTrace(); } mainFrame.updateMainFrame(); } }
9,368
protected Void doInBackground(String... params){ PyObject protocol = Global.py.getModule("trezorlib.transport.protocol"); if (tag == 1) { try { boolean ready = isBootloaderMode(params[0]); if (ready) { protocol.put("PROCESS_REPORTER", this); Daemon.commands.callAttr("firmware_update", TextUtils.isEmpty(VersionUpgradeActivity.filePath) ? String.format("%s/bixin.bin", getExternalCacheDir().getPath()) : VersionUpgradeActivity.filePath, params[0]); } else { showPromptMessage(R.string.not_bootloader_mode); cancel(true); } } catch (Exception e) { e.printStackTrace(); protocol.put("HTTP", false); protocol.put("OFFSET", 0); protocol.put("PROCESS_REPORTER", null); cancel(true); showPromptMessage(R.string.update_failed); new Handler().postDelayed(UpgradeBixinKEYActivity.this::finish, 2000); } } return null; }
protected Void doInBackground(String... params){ PyObject protocol = Global.py.getModule("trezorlib.transport.protocol"); if (tag == 1) { try { boolean ready = isBootloaderMode(params[0]); if (ready) { protocol.put("PROCESS_REPORTER", this); Daemon.commands.callAttr("firmware_update", TextUtils.isEmpty(VersionUpgradeActivity.filePath) ? String.format("%s/bixin.bin", getExternalCacheDir().getPath()) : VersionUpgradeActivity.filePath, params[0]); } else { showPromptMessage(R.string.not_bootloader_mode); cancel(true); } } catch (Exception e) { e.printStackTrace(); protocol.put("HTTP", false); protocol.put("OFFSET", 0); protocol.put("PROCESS_REPORTER", null); cancel(true); } } return null; }
9,369
public void videoPlaybackBufferStarted(){ setupWithVideoPlaybackStarted(); Mockito.reset(streamingAnalytics); PlaybackSession playbackSession = mock(PlaybackSession.class); when(streamingAnalytics.getPlaybackSession()).thenReturn(playbackSession); integration.track(new TrackPayloadBuilder().event("Video Playback Buffer Started").properties(new Properties().putValue("asset_id", 7890).putValue("ad_type", "post-roll").putValue("length", 700).putValue("video_player", "youtube").putValue("playbackPosition", 20).putValue("full_screen", false).putValue("bitrate", 500).putValue("sound", 80)).build()); LinkedHashMap<String, String> expected = new LinkedHashMap<>(); expected.put("ns_st_ci", "7890"); expected.put("ns_st_ad", "post-roll"); expected.put("nst_st_cl", "700"); expected.put("ns_st_mp", "youtube"); expected.put("ns_st_vo", "80"); expected.put("ns_st_ws", "norm"); expected.put("ns_st_br", "500000"); expected.put("c3", "*null"); expected.put("c4", "*null"); expected.put("c6", "*null"); verify(streamingAnalytics).notifyBufferStart(20); verify(streamingAnalytics).getPlaybackSession(); verify(playbackSession).setAsset(expected); }
public void videoPlaybackBufferStarted(){ setupWithVideoPlaybackStarted(); PlaybackSession playbackSession = mock(PlaybackSession.class); when(streamingAnalytics.getPlaybackSession()).thenReturn(playbackSession); integration.track(new TrackPayloadBuilder().event("Video Playback Buffer Started").properties(new Properties().putValue("asset_id", 7890).putValue("ad_type", "post-roll").putValue("length", 700).putValue("video_player", "youtube").putValue("playbackPosition", 20).putValue("fullScreen", false).putValue("bitrate", 500).putValue("sound", 80)).build()); LinkedHashMap<String, String> expected = new LinkedHashMap<>(); expected.put("ns_st_ci", "7890"); expected.put("ns_st_ad", "post-roll"); expected.put("nst_st_cl", "700"); expected.put("ns_st_mp", "youtube"); expected.put("ns_st_vo", "80"); expected.put("ns_st_ws", "norm"); expected.put("ns_st_br", "500000"); expected.put("c3", "*null"); expected.put("c4", "*null"); expected.put("c6", "*null"); verify(streamingAnalytics).notifyBufferStart(20); verify(streamingAnalytics).getPlaybackSession(); verify(playbackSession).setAsset(expected); }
9,370
public static Map<String, ArrayList<String>> continetAndItsCountries(String path){ MapReader mapReader = new MapReader(); MapWriter mapWriter = new MapWriter(path); RiskMap riskmap; Map<String, ArrayList<String>> continetAndItsCountries = new HashMap<String, ArrayList<String>>(); try { riskmap = mapReader.readMap(path); Object[] continents = riskmap.getContinents().keySet().toArray(); for (int i = 0; i < continents.length; i++) { continetAndItsCountries.put(continents[i].toString(), mapReader.getCountriesOfContinent(continents[i].toString(), path)); } } catch (Exception e) { e.printStackTrace(); } return continetAndItsCountries; }
public static Map<String, ArrayList<String>> continetAndItsCountries(String path){ MapReader mapReader = new MapReader(); RiskMap riskmap; Map<String, ArrayList<String>> continetAndItsCountries = new HashMap<String, ArrayList<String>>(); try { riskmap = mapReader.readMap(path); Object[] continents = riskmap.getContinents().keySet().toArray(); for (int i = 0; i < continents.length; i++) { continetAndItsCountries.put(continents[i].toString(), mapReader.getCountriesOfContinent(continents[i].toString(), path)); } } catch (Exception e) { e.printStackTrace(); } return continetAndItsCountries; }
9,371
protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_store); checkNetworkConnection(); changeWidgetsFont(); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); getSupportActionBar().setCustomView(R.layout.lang_action_bar_layout); getSupportActionBar().setDisplayHomeAsUpEnabled(true); TextView actionBarTextView = findViewById(R.id.my_text); actionBarTextView.setText(String.valueOf("Book Store")); viewActions(); }
protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_store); checkNetworkConnection(); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); getSupportActionBar().setCustomView(R.layout.lang_action_bar_layout); getSupportActionBar().setDisplayHomeAsUpEnabled(true); TextView actionBarTextView = findViewById(R.id.my_text); actionBarTextView.setText(String.valueOf("Book Store")); viewActions(); }
9,372
void getInfoByIdNotFoundTest(){ assertThrows(NotFoundException.class, () -> { placeService.getInfoById(null); }); }
void getInfoByIdNotFoundTest(){ assertThrows(NotFoundException.class, () -> placeService.getInfoById(null)); }
9,373
void shouldSendNotificationToPartiesWhenAddedToCaseByEmail() throws IOException, NotificationClientException{ final Map<String, Object> expectedParameters = getPartyAddedByEmailNotificationParameters(); List<Representative> representatives = new ArrayList<>(); Representative representative = Representative.builder().email("[email protected]").servingPreferences(EMAIL).build(); representatives.add(representative); given(partyAddedToCaseContentProvider.getPartyAddedToCaseNotificationParameters(callbackRequest().getCaseDetails(), EMAIL)).willReturn(expectedParameters); given(partyAddedToCaseContentProvider.getPartyAddedToCaseNotificationTemplate(EMAIL)).willReturn(PARTY_ADDED_TO_CASE_BY_EMAIL_NOTIFICATION_TEMPLATE); notificationHandler.sendNotificationToPartiesAddedToCase(new PartyAddedToCaseEvent(callbackRequest(), AUTH_TOKEN, USER_ID, representatives)); verify(notificationClient, times(1)).sendEmail(eq(PARTY_ADDED_TO_CASE_BY_EMAIL_NOTIFICATION_TEMPLATE), eq(PARTY_ADDED_TO_CASE_BY_EMAIL_ADDRESS), eq(expectedParameters), eq("12345")); }
void shouldSendNotificationToPartiesWhenAddedToCaseByEmail() throws IOException, NotificationClientException{ final Map<String, Object> expectedParameters = getPartyAddedByEmailNotificationParameters(); List<Representative> representatives = getRepresentatives(EMAIL, PARTY_ADDED_TO_CASE_BY_EMAIL_ADDRESS); given(partyAddedToCaseContentProvider.getPartyAddedToCaseNotificationParameters(callbackRequest().getCaseDetails(), EMAIL)).willReturn(expectedParameters); given(partyAddedToCaseContentProvider.getPartyAddedToCaseNotificationTemplate(EMAIL)).willReturn(PARTY_ADDED_TO_CASE_BY_EMAIL_NOTIFICATION_TEMPLATE); notificationHandler.sendNotificationToPartiesAddedToCase(new PartyAddedToCaseEvent(callbackRequest(), AUTH_TOKEN, USER_ID, representatives)); verify(notificationClient, times(1)).sendEmail(eq(PARTY_ADDED_TO_CASE_BY_EMAIL_NOTIFICATION_TEMPLATE), eq(PARTY_ADDED_TO_CASE_BY_EMAIL_ADDRESS), eq(expectedParameters), eq("12345")); }
9,374
protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); controller = new MainActivityController(this); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { } }); spinner = (Spinner) findViewById(R.id.spDrillsSort); spinner.setAdapter(createSpinnerAdapter()); searchView = (SearchView) findViewById(R.id.searchView); searchView.setVisibility(View.GONE); }
protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); controller = new MainActivityController(this); fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { } }); spinner = (Spinner) findViewById(R.id.spDrillsSort); spinner.setAdapter(createSpinnerAdapter()); searchView = (SearchView) findViewById(R.id.searchView); searchView.setVisibility(View.GONE); }
9,375
void getAllTeamsForSport(){ List<SportTeam> sportTeams = createSportList(); when(sportTeamRepository.findAll()).thenReturn(sportTeams); Map<Sport, Map<String, List<SportTeamDTO>>> returnDTO = sportTeamService.getTeamsForSport(FOOTBALL); assertEquals(returnDTO.size(), 1); assertTrue(returnDTO.containsKey(FOOTBALL)); assertEquals(returnDTO.get(FOOTBALL).get(ETHAN.get()).size(), 2); }
void getAllTeamsForSport(){ List<SportTeam> sportTeams = createSportList(); when(sportTeamRepository.findAll()).thenReturn(sportTeams); Map<String, List<SportTeamDTO>> returnDTO = sportTeamService.getTeamsForSport(FOOTBALL); assertEquals(returnDTO.size(), 1); assertEquals(returnDTO.get(ETHAN.get()).size(), 2); }
9,376
public void process(ASMDataTable asm){ IMethod.super.process(asm); if (ICloneable.DEFAULT_ANNOTATION != null) ICloneable.EXTERNAL_METHOD_MAP.put(ICloneable.DEFAULT_ANNOTATION, ICloneable.DEFAULT_METHOD); processed = true; }
public void process(ASMDataTable asm){ IMethod.super.process(asm); ICloneable.EXTERNAL_METHOD_MAP.put(ICloneable.DEFAULT_ANNOTATION, METHOD_OBJECT_CLONE); processed = true; }
9,377
public String getTooltipText(final CyEdge edge, final int labelInx){ final DEdgeView dev = dGraphView.getDEdgeView(edge); if (dev.isValueLocked(EDGE_TOOLTIP)) return dev.getVisualProperty(EDGE_TOOLTIP); final String text = m_edgeTooltips.get(edge); if (text == null) if (m_edgeTooltipDefault == null) return EDGE_TOOLTIP.getDefault(); else return m_edgeTooltipDefault; return text; }
public String getTooltipText(final CyEdge edge, final int labelInx){ final DEdgeView dev = dGraphView.getDEdgeView(edge); if (dev.isValueLocked(EDGE_TOOLTIP)) return dev.getVisualProperty(EDGE_TOOLTIP); final String text = m_edgeTooltips.get(edge); if (text == null) return m_edgeTooltipDefault == null ? EDGE_TOOLTIP.getDefault() : m_edgeTooltipDefault; return text; }
9,378
private CheckoutPresenter getBasePresenter(final CheckoutView view, final CheckoutProvider provider){ when(configuration.getAdvancedConfiguration()).thenReturn(advancedConfiguration); when(advancedConfiguration.getPaymentResultScreenConfiguration()).thenReturn(new PaymentResultScreenConfiguration.Builder().build()); when(pluginRepository.getInitTask()).thenReturn(new PluginInitializationSuccess()); final CheckoutStateModel model = new CheckoutStateModel(); final CheckoutPresenter presenter = new CheckoutPresenter(model, configuration, amountRepository, userSelectionRepository, discountRepository, groupsRepository, pluginRepository, paymentRepository); presenter.attachResourcesProvider(provider); presenter.attachView(view); return presenter; }
private CheckoutPresenter getBasePresenter(final CheckoutView view, final CheckoutProvider provider){ when(pluginRepository.getInitTask()).thenReturn(new PluginInitializationSuccess()); final CheckoutStateModel model = new CheckoutStateModel(); final CheckoutPresenter presenter = new CheckoutPresenter(model, configuration, amountRepository, userSelectionRepository, discountRepository, groupsRepository, pluginRepository, paymentRepository); presenter.attachResourcesProvider(provider); presenter.attachView(view); return presenter; }
9,379
protected Future<Void> createOrUpdate(Reconciliation reconciliation, KafkaConnector assemblyResource){ Future<Void> createOrUpdateFuture = Future.future(); CreateUpdateConnectorCommand createUpdateConnectorCommand = new CreateUpdateConnectorCommand(); String namespace = reconciliation.namespace(); String name = reconciliation.name(); log.debug("{}: Creating/Updating Kafka Connector", reconciliation, name, namespace); kafkaConnectorServiceAccount(namespace).compose(p -> createUpdateConnectorCommand.run(assemblyResource, name, vertx)).compose(l -> list(assemblyResource, name, vertx)).setHandler(getRes -> { if (getRes.succeeded()) { log.info("Kafka Connector Create/Update Successfully"); createOrUpdateFuture.complete(); } else { log.error("Kafka Connector Create/Update Failed!", getRes.cause()); createOrUpdateFuture.fail(getRes.cause()); } }); return createOrUpdateFuture; }
protected Future<Void> createOrUpdate(Reconciliation reconciliation, KafkaConnector assemblyResource){ Future<Void> createOrUpdateFuture = Future.future(); String namespace = reconciliation.namespace(); String name = reconciliation.name(); log.info("{}: >>>> Creating/Updating Kafka Connector", reconciliation, name, namespace); update(assemblyResource, name, vertx).compose(l -> list(assemblyResource, name, vertx)).setHandler(getRes -> { if (getRes.succeeded()) { log.info("Kafka Connector Create/Update Successfully"); createOrUpdateFuture.complete(); } else { log.error("Kafka Connector Create/Update Failed!", getRes.cause()); createOrUpdateFuture.fail(getRes.cause()); } }); return createOrUpdateFuture; }
9,380
public PersistentResource<T> next(){ if (parent == null) { return new PersistentResource<>(iterator.next(), requestScope); } return new PersistentResource<>(parent, iterator.next(), requestScope); }
public PersistentResource<T> next(){ T obj = iterator.next(); return new PersistentResource<>(obj, parent, requestScope.getUUIDFor(obj), requestScope); }
9,381
protected void onPostExecute(Void result){ TileViewExtended tileView = mTileViewWeakReference.get(); if (tileView != null) { for (float[] path : mPathList) { tileView.drawPathQuickly(path, null); } } }
protected void onPostExecute(Void result){ TileViewExtended tileView = mTileViewWeakReference.get(); if (tileView != null) { tileView.drawRoutes(mRouteList); } }
9,382
public void testRangeWriteAfterPrefixTrim() throws Exception{ ServerContext sc = getContext(); StreamLog log = new StreamLogFiles(sc, false); final long trimMark = 1000; final long trimOverlap = 100; final long numEntries = 200; log.prefixTrim(trimMark); List<LogData> entries = new ArrayList<>(); for (long x = 0; x < numEntries; x++) { long address = trimMark - trimOverlap + x; entries.add(getEntry(address)); } log.append(entries); StreamLog log2 = new StreamLogFiles(sc, false); List<LogData> readEntries = readRange(0L, trimMark - trimOverlap + numEntries, log2); List<LogData> notTrimmed = new ArrayList<>(); for (LogData entry : readEntries) { if (!entry.isTrimmed()) { notTrimmed.add(entry); } } assertThat((long) notTrimmed.size()).isEqualTo(numEntries - trimOverlap - 1); }
public void testRangeWriteAfterPrefixTrim() throws Exception{ StreamLogFiles log = new StreamLogFiles(sc.getStreamLogParams(), sc.getStreamLogDataStore()); final long trimMark = 1000; final long trimOverlap = 100; final long numEntries = 200; log.prefixTrim(trimMark); List<LogData> entries = new ArrayList<>(); for (long x = 0; x < numEntries; x++) { long address = trimMark - trimOverlap + x; entries.add(getEntry(address)); } log.append(entries); StreamLog log2 = new StreamLogFiles(sc.getStreamLogParams(), sc.getStreamLogDataStore()); List<LogData> readEntries = readRange(0L, trimMark - trimOverlap + numEntries, log2); List<LogData> notTrimmed = new ArrayList<>(); for (LogData entry : readEntries) { if (!entry.isTrimmed()) { notTrimmed.add(entry); } } assertThat((long) notTrimmed.size()).isEqualTo(numEntries - trimOverlap - 1); }
9,383
public void executeCommand(DiscordAPI api, Message message, String[] args) throws CommandException{ if (args.length == 0) { message.reply("You need to provide more argument !"); return; } try { if (!isadmin(api, message)) return; Server server = getServer(message); Collection<User> members = server.getMembers(); User user = findUser(members, args[0]); StringBuilder reason = new StringBuilder(); if (args.length >= 2) { for (int i = 1; i < args.length; ++i) { reason.append(args[i] + " "); } user.sendMessage(reason.toString()); EmbedBuilder builder = Responsefactory.getEmbedResponse(this, "tu as été bannis du serveur " + server.getName() + "\nraison: " + reason); user.sendMessage(null, builder).get(); } server.banUser(user).get(); EmbedBuilder builder = Responsefactory.getEmbedResponse(this, "Ban " + user.getName() + "\nraison: " + reason); message.getChannelReceiver().sendMessage(null, builder).get(); } catch (ExecutionException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } { } }
public void executeCommand(DiscordAPI api, Message message, String[] args) throws CommandException{ this.execute(api, message, args, Moderationtype.BAN); }
9,384
public ConditionEvaluation evaluate(){ ConditionEvaluation evaluation = new ConditionEvaluation(); evaluation.state(resource.exists(), "Resource '" + resource + "' does not exist."); return evaluation; }
public ConditionEvaluation evaluate(){ return evaluation().state(resource.exists(), "Resource '" + resource + "' does not exist.").build(); }
9,385
public boolean test(Card c){ if (!super.test(c)) return false; else if (restricted) { Collection<String> formats = new ArrayList<>(c.legalIn()); formats.retainAll(selected); for (String format : formats) if (c.legality().get(format) != Legality.RESTRICTED) return false; return true; } else return true; }
public boolean test(Card c){ if (!super.test(c)) return false; else if (restricted) { var formats = new ArrayList<>(c.legalIn()); formats.retainAll(selected); return formats.stream().noneMatch((f) -> c.legality().get(f) != Legality.RESTRICTED); } else return true; }
9,386
public static Map<String, CompilationUnit> generateAllSourceCode(){ URL INPUT_URL = FileParser.class.getResource("/org/bytedeco/javacpp/opencv_core.txt"); CompilationUnit compilationUnit = readFile(INPUT_URL); Map<String, CompilationUnit> returnMap = new HashMap<>(); DefaultValueCollector collector = new DefaultValueCollector(); collector.add(new PrimitiveDefaultValue(new PrimitiveType(PrimitiveType.Primitive.Double)) { @Override protected Set<String> getDefaultValues() { return Collections.singleton("CV_PI"); } @Override public Expression getDefaultValue(String defaultValue) { return new FieldAccessExpr(new NameExpr("Math"), "PI"); } }); collector.add(new EnumDefaultValue("edu.wpi.grip.core.operations.opencv.enumeration", "FlipCode", "X_AXIS", "Y_AXIS", "BOTH_AXES")); OperationList operationList = new OperationList(new ImportDeclaration(new NameExpr("edu.wpi.grip.generated.opencv_core"), false, true), new ImportDeclaration(new NameExpr("edu.wpi.grip.generated.opencv_imgproc"), false, true)); if (compilationUnit != null) { returnMap.putAll(parseOpenCVCore(compilationUnit, collector, operationList)); } else { System.err.print("Invalid File input"); } URL INPUT_URL2 = FileParser.class.getResource("/org/bytedeco/javacpp/opencv_imgproc.txt"); compilationUnit = readFile(INPUT_URL2); if (compilationUnit != null) { returnMap.putAll(parseOpenImgprc(compilationUnit, collector, operationList)); } returnMap.put(operationList.getClassName(), operationList.getDeclaration()); return returnMap; }
public static Map<String, CompilationUnit> generateAllSourceCode(){ URL INPUT_URL = FileParser.class.getResource("/org/bytedeco/javacpp/opencv_core.txt"); CompilationUnit compilationUnit = readFile(INPUT_URL); Map<String, CompilationUnit> returnMap = new HashMap<>(); DefaultValueCollector collector = new DefaultValueCollector(); collector.add(new PrimitiveDefaultValue(new PrimitiveType(PrimitiveType.Primitive.Double)) { @Override protected Set<String> getDefaultValues() { return Collections.singleton("CV_PI"); } @Override public Expression getDefaultValue(String defaultValue) { return new FieldAccessExpr(new NameExpr("Math"), "PI"); } }); collector.add(new EnumDefaultValue("edu.wpi.grip.core.operations.opencv.enumeration", "FlipCode", "X_AXIS", "Y_AXIS", "BOTH_AXES")); OperationList operationList = new OperationList(new ImportDeclaration(new NameExpr("edu.wpi.grip.generated.opencv_core"), false, true), new ImportDeclaration(new NameExpr("edu.wpi.grip.generated.opencv_imgproc"), false, true)); if (compilationUnit != null) { returnMap.putAll(parseOpenCVCore(compilationUnit, collector, operationList)); } else { System.err.print("Invalid File input"); } URL INPUT_URL2 = FileParser.class.getResource("/org/bytedeco/javacpp/opencv_imgproc.txt"); compilationUnit = readFile(INPUT_URL2); if (compilationUnit != null) { returnMap.putAll(parseOpenImgprc(compilationUnit, collector, operationList)); } return returnMap; }
9,387
public void mergeAttributes(Page other){ assertAttributeEquals(other, ENTITY_PAGE, ATTR_NAME, m_name, other.getName()); if (other.getTitle() != null) { m_title = other.getTitle(); } if (other.getDefault() != null) { m_default = other.getDefault(); } if (other.getPackage() != null) { m_package = other.getPackage(); } if (other.getPath() != null) { m_path = other.getPath(); } if (other.getView() != null) { m_view = other.getView(); } if (other.getStandalone() != null) { m_standalone = other.getStandalone(); } if (other.getTemplate() != null) { m_template = other.getTemplate(); } }
public void mergeAttributes(Page other){ assertAttributeEquals(other, ENTITY_PAGE, ATTR_NAME, m_name, other.getName()); if (other.getTitle() != null) { m_title = other.getTitle(); } if (other.getDefault() != null) { m_default = other.getDefault(); } if (other.getPackage() != null) { m_package = other.getPackage(); } if (other.getPath() != null) { m_path = other.getPath(); } if (other.getView() != null) { m_view = other.getView(); } if (other.getStandalone() != null) { m_standalone = other.getStandalone(); } }
9,388
String convertToPigLatin(String str){ String tmpPunct = ""; if (!stringIsInAlphabet(str)) { for (int i = str.length(); i > 0; i--) { if (isPuncutation(str.charAt(i - 1))) { } else { tmpPunct = str.substring(i, str.length()); str = str.substring(0, i); break; } } if (!stringIsInAlphabet(str)) { return str + tmpPunct; } } int vowel = vowelIndex(str); if (vowel == -1) { return (str + "ay") + tmpPunct; } if (vowel == 0) { return str + "yay"; } if (str.charAt(vowel - 1) == '\'') { vowel = vowel - 1; } String result = str.substring(vowel, str.length()); result = result + str.substring(0, vowel) + "ay"; return result + tmpPunct; }
String convertToPigLatin(String str){ String tmpPunct = ""; if (!stringIsInAlphabet(str)) { tmpPunct = removePunctuation(str); str = str.substring(0, str.length() - 1 - tmpPunct.length()); if (!stringIsInAlphabet(str)) { return str + tmpPunct; } } int vowel = vowelIndex(str); if (vowel == -1) { return (str + "ay") + tmpPunct; } if (vowel == 0) { return str + "yay"; } if (str.charAt(vowel - 1) == '\'') { vowel = vowel - 1; } String result = str.substring(vowel, str.length()); result = result + str.substring(0, vowel) + "ay"; return result + tmpPunct; }
9,389
public static void hideFakeItems(GuiScreenEvent.BackgroundDrawnEvent event){ Minecraft mc = Minecraft.getMinecraft(); if (mc.currentScreen instanceof GuiMEMonitorable) { GuiMEMonitorable g = (GuiMEMonitorable) mc.currentScreen; if (AE2Plugin.HIDE_FAKE_ITEM == null) { AE2Plugin.HIDE_FAKE_ITEM = new HideFakeItem(); } try { ItemRepo r = (ItemRepo) ClientProxy.GuiMEMonitorable_Repo.get(g); IPartitionList<IAEItemStack> pl = (IPartitionList<IAEItemStack>) ClientProxy.ItemRepo_myPartitionList.get(r); if (pl instanceof MergedPriorityList) { MergedPriorityList<IAEItemStack> ml = (MergedPriorityList<IAEItemStack>) pl; Collection<IPartitionList<IAEItemStack>> negative = (Collection<IPartitionList<IAEItemStack>>) AE2Plugin.MergedPriorityList_negative.get(ml); if (!negative.contains(AE2Plugin.HIDE_FAKE_ITEM)) { negative.add(AE2Plugin.HIDE_FAKE_ITEM); r.updateView(); } } else { MergedPriorityList<IAEItemStack> mlist = new MergedPriorityList<>(); ClientProxy.ItemRepo_myPartitionList.set(r, mlist); if (pl != null) mlist.addNewList(pl, true); mlist.addNewList(AE2Plugin.HIDE_FAKE_ITEM, false); r.updateView(); } } catch (Exception e) { } } }
public static void hideFakeItems(GuiScreenEvent.BackgroundDrawnEvent event){ Minecraft mc = Minecraft.getMinecraft(); if (mc.currentScreen instanceof GuiMEMonitorable) { GuiMEMonitorable g = (GuiMEMonitorable) mc.currentScreen; if (AE2Plugin.HIDE_FAKE_ITEM == null) AE2Plugin.HIDE_FAKE_ITEM = new HideFakeItem(); try { ItemRepo r = (ItemRepo) ClientProxy.GuiMEMonitorable_Repo.get(g); IPartitionList<IAEItemStack> pl = (IPartitionList<IAEItemStack>) ClientProxy.ItemRepo_myPartitionList.get(r); if (pl instanceof MergedPriorityList) { MergedPriorityList<IAEItemStack> ml = (MergedPriorityList<IAEItemStack>) pl; Collection<IPartitionList<IAEItemStack>> negative = (Collection<IPartitionList<IAEItemStack>>) AE2Plugin.MergedPriorityList_negative.get(ml); if (!negative.contains(AE2Plugin.HIDE_FAKE_ITEM)) { negative.add(AE2Plugin.HIDE_FAKE_ITEM); r.updateView(); } } else { MergedPriorityList<IAEItemStack> mlist = new MergedPriorityList<>(); ClientProxy.ItemRepo_myPartitionList.set(r, mlist); if (pl != null) mlist.addNewList(pl, true); mlist.addNewList(AE2Plugin.HIDE_FAKE_ITEM, false); r.updateView(); } } catch (Exception ignored) { } } }
9,390
public void onDataChange(@NonNull DataSnapshot dataSnapshot){ Iterable<DataSnapshot> children = dataSnapshot.getChildren(); historyArrayList.clear(); dataSet.clear(); dataSet.addEntry(new Entry(1, 0)); for (DataSnapshot child : children) { History history = child.getValue(History.class); historyArrayList.add(history); adapter.notifyDataSetChanged(); String dateString = new SimpleDateFormat("dd").format(history.getReceipt().getDate()); System.out.println(dateString); float date = Float.valueOf(dateString); float price = (float) history.getReceipt().getTotalPrice(); dataSet.addEntry(new Entry(date, price)); if (maximumReceiptPrice < history.getReceipt().getTotalPrice()) { maximumReceiptPrice = (float) history.getReceipt().getTotalPrice(); chart.getAxisLeft().setAxisMaximum(maximumReceiptPrice + 10); } dataSet.notifyDataSetChanged(); chart.notifyDataSetChanged(); chart.invalidate(); } }
public void onDataChange(@NonNull DataSnapshot dataSnapshot){ Iterable<DataSnapshot> children = dataSnapshot.getChildren(); historyArrayList.clear(); dataSet.clear(); dataSet.addEntry(new Entry(1, 0)); for (DataSnapshot child : children) { History history = child.getValue(History.class); historyArrayList.add(history); adapter.notifyDataSetChanged(); updateGraph(history); } }
9,391
private MethodSpec buildInternalDispose() throws ArezProcessorException{ final MethodSpec.Builder builder = MethodSpec.methodBuilder(GeneratorUtil.INTERNAL_DISPOSE_METHOD_NAME).addModifiers(Modifier.PRIVATE); if (_disposeTrackable || !_roReferences.isEmpty() || !_roInverses.isEmpty() || !_roCascadeDisposes.isEmpty()) { builder.addStatement("this.$N()", GeneratorUtil.INTERNAL_PRE_DISPOSE_METHOD_NAME); } else if (null != _preDispose) { builder.addStatement("super.$N()", _preDispose.getSimpleName()); } if (_observable) { builder.addStatement("this.$N.releaseResources()", GeneratorUtil.KERNEL_FIELD_NAME); } _roObserves.forEach(observe -> observe.buildDisposer(builder)); _roMemoizes.forEach(memoize -> memoize.buildDisposer(builder)); _roObservables.forEach(observable -> observable.buildDisposer(builder)); if (null != _postDispose) { builder.addStatement("super.$N()", _postDispose.getSimpleName()); } return builder.build(); }
private MethodSpec buildInternalDispose() throws ArezProcessorException{ final MethodSpec.Builder builder = MethodSpec.methodBuilder(GeneratorUtil.INTERNAL_DISPOSE_METHOD_NAME).addModifiers(Modifier.PRIVATE); if (hasInternalPreDispose()) { builder.addStatement("this.$N()", GeneratorUtil.INTERNAL_PRE_DISPOSE_METHOD_NAME); } else if (null != _preDispose) { builder.addStatement("super.$N()", _preDispose.getSimpleName()); } _roObserves.forEach(observe -> observe.buildDisposer(builder)); _roMemoizes.forEach(memoize -> memoize.buildDisposer(builder)); _roObservables.forEach(observable -> observable.buildDisposer(builder)); if (null != _postDispose) { builder.addStatement("super.$N()", _postDispose.getSimpleName()); } return builder.build(); }
9,392
public void flush(){ BufferedReader in = new BufferedReader(new StringReader(getBuffer().toString())); while (true) { try { String line = in.readLine(); if (line == null) { break; } switch(type) { default: case DEBUG: { if (logger.isDebugEnabled()) { logger.debug(line); } break; } case INFO: { if (logger.isInfoEnabled()) { logger.info(line); } break; } } } catch (IOException e) { throw new Error(e); } } getBuffer().setLength(0); }
public void flush(){ BufferedReader in = new BufferedReader(new StringReader(getBuffer().toString())); while (true) { try { String line = in.readLine(); if (line == null) { break; } logger.info(line); } catch (IOException e) { throw new Error(e); } } getBuffer().setLength(0); }
9,393
public String getGamePlayers(){ UserInterface ui = new TextUserInterface(); String userInput = ""; boolean inputValid = false; while (!inputValid) { System.out.println("\nThis game can be played in three ways: \n"); System.out.println("\t 1) Computer codemaker and computer codebreaker."); System.out.println("\t 2) Computer codemaker and human codebreaker."); System.out.println("\t 3) Human codemaker and human codebreaker."); System.out.print("\nWhich one would you like to play? Enter 1, 2 or 3 --> "); Scanner user_input = new Scanner(System.in); String players = user_input.next(); if (players.equals("1")) { inputValid = true; userInput = "1"; } else if (players.equals("2")) { inputValid = true; userInput = "2"; } else if (players.equals("3")) { inputValid = true; userInput = "3"; } else { ui.displayInvalidInput(); } } return userInput; }
public String getGamePlayers(){ UserInterface ui = new TextUserInterface(); String userInput = ""; String players = ""; boolean inputValid = false; while (!inputValid) { System.out.println("\nThis game can be played in three ways: \n"); System.out.println("\t 1) Computer codemaker and computer codebreaker."); System.out.println("\t 2) Computer codemaker and human codebreaker."); System.out.println("\t 3) Human codemaker and human codebreaker."); System.out.print("\nWhich one would you like to play? Enter 1, 2 or 3 --> "); Scanner user_input = new Scanner(System.in); players = user_input.next(); if (players.equals("1")) { inputValid = true; } else if (players.equals("2")) { inputValid = true; } else if (players.equals("3")) { inputValid = true; } else { ui.displayInvalidInput(); } } userInput = players; return userInput; }
9,394
private void handleCameraResult(){ spinner.setVisibility(View.VISIBLE); new Thread(() -> { try { Bitmap boardBitmap = getRotatedBoard(); BoardDetection boardDetection = new BoardDetection(boardBitmap, testImg, mainActivity); Board board = new Board(getApplicationContext(), boardDetection.getOrbs()); runOnUiThread(() -> { grid = board.getGrid(); boolean[][] selected = new boolean[8][8]; gridView.setAdapter(new ImageAdapter(context, grid, selected, gridView.getColumnWidth())); gridView.invalidateViews(); resultsList.setResults(BoardUtils.getSortedResults(grid)); spinner.setVisibility(View.INVISIBLE); }); } catch (Exception e) { e.printStackTrace(); } }).start(); }
private void handleCameraResult(){ spinner.setVisibility(View.VISIBLE); new Thread(() -> { try { Bitmap boardBitmap = getRotatedBoard(); BoardDetection boardDetection = new BoardDetection(boardBitmap, testImg, mainActivity); Board board = new Board(getApplicationContext(), boardDetection.getOrbs()); runOnUiThread(() -> { int[][] boardOrbs = board.getGrid(); boardGrid.setBoardOrbs(boardOrbs); resultsList.setResults(BoardUtils.getSortedResults(boardOrbs)); spinner.setVisibility(View.INVISIBLE); }); } catch (Exception e) { e.printStackTrace(); } }).start(); }
9,395
private static Object valueRedisDeserializer(byte[] value) throws Exception{ if (null != value) { return valueRedisSerializer.deserialize(value); } else { return null; } }
private static Object valueRedisDeserializer(byte[] value) throws Exception{ return value != null ? valueRedisSerializer.deserialize(value) : null; }
9,396
public void hb() throws Exception{ byte[] encodedEcPoint = Hex.decode("02a66335a59f1277c193315eb2db69808e6eaf15c944286765c0adcae2"); ECCurve ecCurve = ECNamedCurveTable.getParameterSpec("secp224r1").getCurve(); ECPoint alpha = ecCurve.decodePoint(encodedEcPoint); BigInteger expectedOutput = new BigInteger("99291632524521846780855783327754112432"); BigInteger output = params.hb(alpha, key); assertEquals(expectedOutput, output); }
public void hb() throws Exception{ byte[] encodedEcPoint = Hex.decode("02a66335a59f1277c193315eb2db69808e6eaf15c944286765c0adcae2"); ECPoint alpha = Util.decodeECPoint(encodedEcPoint); BigInteger expectedOutput = new BigInteger("99291632524521846780855783327754112432"); BigInteger output = params.hb(alpha, key); assertEquals(expectedOutput, output); }
9,397
public Result authedDatasource(@ApiIgnore @RequestAttribute(value = Constants.SESSION_USER) User loginUser, @RequestParam("userId") Integer userId){ logger.info("authorized data source, login user:{}, authorized useId:{}", loginUser.getUserName(), userId); Map<String, Object> result = dataSourceService.authedDatasource(loginUser, userId); return returnDataList(result); }
public Result<List<DataSource>> authedDatasource(@ApiIgnore @RequestAttribute(value = Constants.SESSION_USER) User loginUser, @RequestParam("userId") Integer userId){ logger.info("authorized data source, login user:{}, authorized useId:{}", loginUser.getUserName(), userId); return dataSourceService.authedDatasource(loginUser, userId); }
9,398
private void editShowsUpInRecentChangesTestCase(String label, String type) throws RetryableException, ContainedException{ long now = System.currentTimeMillis(); String entityId = repo.get().firstEntityIdForLabelStartingWith(label, "en", type); repo.get().setLabel(entityId, type, label + now, "en"); JSONArray changes = getRecentChanges(new Date(now - 10000), 10); boolean found = false; String title = entityId; if (type.equals("property")) { title = "Property:" + title; } for (Object changeObject : changes) { JSONObject change = (JSONObject) changeObject; if (change.get("title").equals(title)) { found = true; Map<String, Object> c = change; assertThat(c, hasEntry(equalTo("revid"), isA((Class) Long.class))); break; } } assertTrue("Didn't find new page in recent changes", found); Collection<Statement> statements = repo.get().fetchRdfForEntity(entityId); found = false; for (Statement statement : statements) { if (statement.getSubject().stringValue().equals(uris.entity() + entityId)) { found = true; break; } } assertTrue("Didn't find entity information in rdf", found); }
private void editShowsUpInRecentChangesTestCase(String label, String type) throws RetryableException, ContainedException{ long now = System.currentTimeMillis(); String entityId = repo.get().firstEntityIdForLabelStartingWith(label, "en", type); repo.get().setLabel(entityId, type, label + now, "en"); List<RecentChange> changes = getRecentChanges(new Date(now - 10000), 10); boolean found = false; String title = entityId; if (type.equals("property")) { title = "Property:" + title; } for (RecentChange change : changes) { if (change.getTitle().equals(title)) { found = true; assertNotNull(change.getRevId()); break; } } assertTrue("Didn't find new page in recent changes", found); Collection<Statement> statements = repo.get().fetchRdfForEntity(entityId); found = false; for (Statement statement : statements) { if (statement.getSubject().stringValue().equals(uris.entity() + entityId)) { found = true; break; } } assertTrue("Didn't find entity information in rdf", found); }
9,399
public InetAddress processIP(Command.CommandInput input){ String name = input.getPrimaryData(); input.next(); if (name.matches("^(?:[0-9]{1,3}\\.){3}[0-9]{1,3}$")) { try { return InetAddress.getByName(name); } catch (UnknownHostException e) { AdvancedBanLogger.getInstance().logException(e); return null; } } else { InetAddress ip = AdvancedBan.get().getAddress(name).orElse(null); if (ip == null) input.getSender().sendCustomMessage("Ipban.IpNotCashed", true, "NAME", name); return ip; } }
public InetAddress processIP(Command.CommandInput input){ String name = input.next().toLowerCase(); if (name.matches("^(?:[0-9]{1,3}\\.){3}[0-9]{1,3}$")) { try { return InetAddress.getByName(name); } catch (UnknownHostException e) { AdvancedBanLogger.getInstance().logException(e); return null; } } else { InetAddress ip = AdvancedBan.get().getAddress(name).orElse(null); if (ip == null) input.getSender().sendCustomMessage("Ipban.IpNotCashed", true, "NAME", name); return ip; } }