public static Triple<Double, Double, Double> getMinMaxAvg(List<Double> values) { if (values.isEmpty()) return new ImmutableTriple<Double, Double, Double>(0.0, 0.0, 0.0); double minVal = Double.POSITIVE_INFINITY; double maxVal = Double.NEGATIVE_INFINITY; double avgVal = 0.0; for (double v : values) { minVal = Math.min(v, minVal); maxVal = Math.max(v, maxVal); avgVal += v / values.size(); } return new ImmutableTriple<Double, Double, Double>(minVal, maxVal, avgVal); }
private static Triple<Double, Double, Double> getBoldsEDCapitalizedWordcount(String query, int rank, List<Pair<String, Integer>> websearchBolds){ double minEdDist = 1.0; double capitalized = 0; double avgNumWords = 0; int boldsCount = 0; for (Pair<String, Integer> p : websearchBolds) if (p.second == rank) { boldsCount++; minEdDist = Math.min(minEdDist, SmaphUtils.getMinEditDist(query, p.first)); if (Character.isUpperCase(p.first.charAt(0))) capitalized++; avgNumWords += p.first.split("\\W+").length; } if (boldsCount != 0) avgNumWords /= boldsCount; return new ImmutableTriple<>(minEdDist, capitalized, avgNumWords); }
private List<Triple<Annotation, AnnotationFeaturePack, Boolean>> getAdvancedARToFtrsAndPresence( String query, QueryInformation qi, HashSet<Annotation> goldStandardAnn, MatchRelation<Annotation> annotationMatch) { List<Triple<Annotation, AnnotationFeaturePack, Boolean>> annAndFtrsAndPresence = new Vector<>(); for (Annotation a : IndividualLinkback.getAnnotations(query, qi.allCandidates(), anchorMaxED, e2a, wikiApi)) { boolean inGold = false; for (Annotation goldAnn : goldStandardAnn) if (annotationMatch.match(goldAnn, a)) { inGold = true; break; } //if (e2a.containsId(a.getConcept())) { AnnotationFeaturePack features = new AnnotationFeaturePack(a, query, qi, wikiApi, wikiToFreeb, e2a); annAndFtrsAndPresence.add(new ImmutableTriple<Annotation, AnnotationFeaturePack, Boolean>(a, features, inGold)); //} else // LOG.warn("No anchors found for id={}", a.getConcept()); } return annAndFtrsAndPresence; }
private List<Triple<HashSet<Annotation>, BindingFeaturePack, Double>> getLBBindingToFtrsAndF1(String query, QueryInformation qi, HashSet<Annotation> goldStandardAnn, MatchRelation<Annotation> match, Set<Tag> acceptedEntities, SmaphDebugger debugger) { Collection<Pair<HashSet<Annotation>, BindingFeaturePack>> bindingAndFeaturePacks = CollectiveLinkBack .getBindingFeaturePacks(query, acceptedEntities, qi, bg, wikiApi, wikiToFreeb, e2a, debugger); List<Triple<HashSet<Annotation>, BindingFeaturePack, Double>> res = new Vector<>(); for (Pair<HashSet<Annotation>, BindingFeaturePack> bindingAndFeaturePack : bindingAndFeaturePacks) { HashSet<Annotation> binding = bindingAndFeaturePack.first; BindingFeaturePack bindingFeatures = bindingAndFeaturePack.second; Metrics<Annotation> m = new Metrics<>(); float f1 = m.getSingleF1(goldStandardAnn, binding, match); res.add(new ImmutableTriple<HashSet<Annotation>, BindingFeaturePack, Double>( binding, bindingFeatures, (double) f1)); } return res; }
public GrpcHystrixCommand(String serviceName, String methodName, Boolean isEnabledFallBack) { super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey(serviceName))// .andCommandKey(HystrixCommandKey.Factory.asKey(serviceName + ":" + methodName))// .andCommandPropertiesDefaults( HystrixCommandProperties.Setter().withCircuitBreakerRequestVolumeThreshold(20)// 10秒钟内至少19此请求失败,熔断器才发挥起作用 .withCircuitBreakerSleepWindowInMilliseconds(30000)// 熔断器中断请求30秒后会进入半打开状态,放部分流量过去重试 .withCircuitBreakerErrorThresholdPercentage(50)// 错误率达到50开启熔断保护 .withExecutionTimeoutEnabled(false)// 禁用这里的超时 .withFallbackEnabled(isEnabledFallBack))// .andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter().withCoreSize(100) .withAllowMaximumSizeToDivergeFromCoreSize(true).withMaximumSize(Integer.MAX_VALUE))); this.serviceName = serviceName; this.methodName = methodName; this.start = System.currentTimeMillis(); this.rpcContext = new ImmutableTriple<Map<String, String>, Map<String, Object>, Set<Class>>( RpcContext.getContext().getAttachments(), RpcContext.getContext().get(), RpcContext.getContext().getHoldenGroups()); RpcContext.removeContext(); }
@BeforeClass public static void initClass() throws IOException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { CONTENTS.add(new ImmutableTriple<MsgData[], String[], Hint[]>(new MsgData[]{ new MsgData(Origin.User, "Ich suche ein ruhiges und romantisches Restaurant in Berlin für heute Abend.")}, new String[]{"ruhiges", "romantisches"}, new Hint[]{})); CONTENTS.add(new ImmutableTriple<MsgData[], String[], Hint[]>(new MsgData[]{ new MsgData(Origin.User, "Ich suche ein nettes Restaurant in Berlin für den kommenden Montag.")}, new String[]{"nettes"}, //NOTE: not kommenden, because this is in the ignored list new Hint[]{})); CONTENTS.add(new ImmutableTriple<MsgData[], String[], Hint[]>(new MsgData[]{ new MsgData(Origin.User, "Bitte kein chinesisches oder indisches Restaurant.")}, new String[]{"chinesisches","indisches"}, new Hint[]{Hint.negated})); //those attributes are negated OpenNlpPosProcessor pos = new OpenNlpPosProcessor(Collections.singleton(new LanguageGerman())); NegationProcessor negation = new NegationProcessor(Arrays.asList(new GermanNegationRule())); REQUIRED_PREPERATORS = Arrays.asList(pos, negation); }
@Override public void execute() { ArrayList<TaskAttributes> fullMatches = taskDb.getAll().stream() .map(this::constructFullMatchCancidate) .filter(this::isValidCandidate) .sorted(this::candidateCompare) .map(ImmutableTriple::getRight) .collect(Collectors.toCollection(ArrayList::new)); results = new ArrayList<>(fullMatches); results.addAll(taskDb.getAll().stream() .map(this::constructStemMatchCandidate) .filter(this::isValidCandidate) .sorted(this::candidateCompare) .map(ImmutableTriple::getRight) .filter(task -> !fullMatches.contains(task)) .collect(Collectors.toCollection(ArrayList::new))); logger.info(String.format("Search completed. %d results found.", results.size())); eventBus.post(new SearchDoneEvent(results, keywords)); }
private void evaluate() { scoredTest = new ArrayList<>(); // run through all example chunks for(int i = 0; i < featuresTest.size(); i++) { INDArray testData = featuresTest.get(i); INDArray labels = labelsTest.get(i); int nRows = testData.rows(); // go through each example individually for(int j = 0; j < nRows; j++) { INDArray example = testData.getRow(j); int digit = (int)labels.getDouble(j); double score = net.score(new DataSet(example,example)); scoredTest.add(new ImmutableTriple<Double, Integer, INDArray>(new Double(score), new Integer(digit), example)); } } // sort for increasing score Collections.sort(scoredTest, new Comparator<Triple<Double, Integer, INDArray>>() { @Override public int compare(Triple<Double, Integer, INDArray> o1, Triple<Double, Integer, INDArray> o2) { return(o1.getLeft().compareTo(o2.getLeft())); } }); }
private ImmutableTriple<String, String, String> findResourcePathFromFreemarkerRouteMap(String uri) { //2.查找不到,则从docRoutesMap中查找 例如 //uri: /root/web/page/index.ftl //key: /root/web //value: static/ for (String key : freemarkerRoutesMap.keySet()) { if (uri.startsWith(key + "/")) { //uri: /root/web/page/index.ftl //key: /root/web //value: static/ //key: /root/web/ String subPath = StringUtils.removeStart(uri, key + "/"); //subPath: page/index.ftl //uri解码,即可完美支持中文 subPath = URIEncoderDecoder.decode(subPath); return new ImmutableTriple<String, String, String>(key + "/", freemarkerRoutesMap.get(key), subPath); } } return null; }
private CompletableFuture<List<Segment>> getSuccessorsForSegment(final int number) { return getHistoryTable() .thenApply(historyTable -> { CompletableFuture<Segment> segmentFuture = getSegment(number); CompletableFuture<Data<T>> indexTableFuture = getIndexTable(); return new ImmutableTriple<>(historyTable, segmentFuture, indexTableFuture); }) .thenCompose(triple -> CompletableFuture.allOf(triple.getMiddle(), triple.getRight()) .thenCompose(x -> { final Segment segment = triple.getMiddle().join(); List<Integer> candidates = TableHelper.findSegmentSuccessorCandidates(segment, triple.getRight().join().getData(), triple.getLeft().getData()); return findOverlapping(segment, candidates); })); }
/** * For a set of ApiFilters collect by dimension, field and operation, and union their value sets. * * @param filterStream Stream of ApiFilters whose values are to be unioned * * @return A set of filters with the same operations but values unioned */ protected static Set<ApiFilter> unionMergeFilterValues(Stream<ApiFilter> filterStream) { Function<ApiFilter, Triple<Dimension, DimensionField, FilterOperation>> filterGroupingIdentity = filter -> new ImmutableTriple<>(filter.getDimension(), filter.getDimensionField(), filter.getOperation()); Map<Triple<Dimension, DimensionField, FilterOperation>, Set<String>> filterMap = filterStream.collect(Collectors.groupingBy( filterGroupingIdentity::apply, Collectors.mapping( ApiFilter::getValues, Collectors.reducing(Collections.emptySet(), StreamUtils::setMerge) ) )); return filterMap.entrySet().stream() .map(it -> new ApiFilter( it.getKey().getLeft(), it.getKey().getMiddle(), it.getKey().getRight(), it.getValue() )) .collect(Collectors.toSet()); }
/** * Prints an overview of customers and their orders. */ public void print() { System.out.println("Customer Overview:"); System.out.println(StringUtils.rightPad("", 80, "-")); System.out.print("| "); System.out.print(StringUtils.rightPad("customer", 15)); System.out.print(" | "); System.out.print(StringUtils.rightPad("#orders", 7)); System.out.print(" | "); System.out.println("order ids"); System.out.println(StringUtils.rightPad("", 80, "-")); ordersByCustomer.entrySet().stream().sequential() .map(e -> new ImmutableTriple<>(e.getKey(), e.getValue().size(), StringUtils.join(e.getValue(), ','))) .sorted((lhs, rhs) -> Long.compare(rhs.getMiddle(), lhs.getMiddle())) .forEachOrdered(e -> System.out .println(String.format("| %s | %s | %s", StringUtils.rightPad(e.getLeft(), 15), StringUtils.center(e.getMiddle().toString(), 7), e.getRight()))); System.out.println(); }
void configureRegexRegions(Configuration conf) throws ConfigurationException { List<String> regexRegionGroupList = conf.getList(REGEX_REGION_GROUP).stream().map(o -> o.toString()).collect(Collectors.toList()); List<String> regexRegionSearchList = conf.getList(REGEX_REGION_SEARCH).stream().map(o -> o.toString()).collect(Collectors.toList()); List<String> regexRegionReplaceList = conf.getList(REGEX_REGION_REPLACE).stream().map(o -> o.toString()).collect(Collectors.toList()); int groupListSize = regexRegionGroupList.size(); int searchListSize = regexRegionSearchList.size(); int replaceListSize = regexRegionReplaceList.size(); if (!(groupListSize == searchListSize && searchListSize == replaceListSize)) { // all lists must be the same size throw new ConfigurationException("Error initializing class. All regexRegion lists must be the same size"); } groupSearchReplaceList = new ArrayList<>(groupListSize); for (int index = 0; index < regexRegionGroupList.size(); index++) { Pattern pattern = Pattern.compile(regexRegionGroupList.get(index)); String regex = regexRegionSearchList.get(index); String replacement = regexRegionReplaceList.get(index); ImmutableTriple<Pattern, String, String> triple = new ImmutableTriple<>(pattern, regex, replacement); groupSearchReplaceList.add(triple); } }
private Triple<ExternalResource, AnyType, Provision> connObjectInit( final String resourceKey, final String anyTypeKey) { ExternalResource resource = resourceDAO.authFind(resourceKey); if (resource == null) { throw new NotFoundException("Resource '" + resourceKey + "'"); } AnyType anyType = anyTypeDAO.find(anyTypeKey); if (anyType == null) { throw new NotFoundException("AnyType '" + anyTypeKey + "'"); } Optional<? extends Provision> provision = resource.getProvision(anyType); if (!provision.isPresent()) { throw new NotFoundException("Provision on resource '" + resourceKey + "' for type '" + anyTypeKey + "'"); } return ImmutableTriple.of(resource, anyType, provision.get()); }
@Override @SuppressWarnings("unchecked") public Triple<List<T>, URI, List<ClientAnnotation>> fetchPartial(final URI uri, final Class<T> typeRef) { final ODataPropertyRequest<ClientProperty> req = getClient().getRetrieveRequestFactory().getPropertyRequest(uri); req.setPrefer(getClient().newPreferences().includeAnnotations("*")); final ODataRetrieveResponse<ClientProperty> res = req.execute(); final List<T> resItems = new ArrayList<T>(); final ClientProperty property = res.getBody(); if (property != null && !property.hasNullValue()) { for (ClientValue item : property.getCollectionValue()) { resItems.add((T) item.asPrimitive().toValue()); } } return new ImmutableTriple<List<T>, URI, List<ClientAnnotation>>( resItems, null, Collections.<ClientAnnotation>emptyList()); }
/** * Given a list of conditions that contain Druid valid operations and * a list that contains those that contain any non-supported operation, * it outputs a triple with three different categories: * 1-l) condition filters on the timestamp column, * 2-m) condition filters that can be pushed to Druid, * 3-r) condition filters that cannot be pushed to Druid. */ private static Triple<List<RexNode>, List<RexNode>, List<RexNode>> splitFilters( final RexBuilder rexBuilder, final DruidQuery input, final List<RexNode> validPreds, final List<RexNode> nonValidPreds, final int timestampFieldIdx) { final List<RexNode> timeRangeNodes = new ArrayList<>(); final List<RexNode> pushableNodes = new ArrayList<>(); final List<RexNode> nonPushableNodes = new ArrayList<>(nonValidPreds); // Number of columns with the dimensions and timestamp for (RexNode conj : validPreds) { final RelOptUtil.InputReferencedVisitor visitor = new RelOptUtil.InputReferencedVisitor(); conj.accept(visitor); if (visitor.inputPosReferenced.contains(timestampFieldIdx)) { if (visitor.inputPosReferenced.size() != 1) { // Complex predicate, transformation currently not supported nonPushableNodes.add(conj); } else { timeRangeNodes.add(conj); } } else { pushableNodes.add(conj); } } return ImmutableTriple.of(timeRangeNodes, pushableNodes, nonPushableNodes); }
public void onMatch(RelOptRuleCall call) { final Aggregate aggregate = call.rel(0); final DruidQuery query = call.rel(1); if (!DruidQuery.isValidSignature(query.signature() + 'a')) { return; } if (aggregate.indicator || aggregate.getGroupSets().size() != 1 || BAD_AGG.apply(ImmutableTriple.of(aggregate, (RelNode) aggregate, query)) || !validAggregate(aggregate, query)) { return; } final RelNode newAggregate = aggregate.copy(aggregate.getTraitSet(), ImmutableList.of(Util.last(query.rels))); call.transformTo(DruidQuery.extendQuery(query, newAggregate)); }
@Override public Map<String, Triple<Double, Double, Double>> getLocationsAsMap(List<String> regionNames) { Map<String, Triple<Double, Double, Double>> result = new HashMap<>(); try { for (String regionName : regionNames) { HttpResponse<JsonNode> request = Unirest.get(geoAPIURL) .field("sensor", true) .field("key", geoAPICode) .field("address", regionName) .asJson(); JSONObject response = request.getBody().getObject().getJSONArray(RESULTS).getJSONObject(0).getJSONObject(GEOMETRY); JSONObject location = response.getJSONObject(LOCATION); JSONObject bounds = response.getJSONObject(BOUNDS); Point center = getCenter(location); Double distance = getDistance(bounds); result.put(regionName, new ImmutableTriple<>(center.getX(), center.getY(), distance)); } } catch (UnirestException | JSONException e) { logger.error(e.getMessage(), e); } return result; }
@NotNull @Override public RestServiceResult query( @NotNull Class<? extends DaoObject> clazz, int page, int itemPerPage, @NotNull String filters ) throws ServiceException { List<ImmutableTriple<String,String,String>> filterList; try { filterList = filterParserService.parse(filters); } catch (FilterParserServiceException e) { throw new ServiceException( QueryServiceRestImpl.class.getName(), BAD_REQUEST, ExceptionUtils.getStackTrace(e), Messages.get("java.service.result.generic.error.msg") ); } JavaServiceResult jsr = queryServiceJava.load(clazz, page, itemPerPage, filterList); if(jsr.getHttpStatus() == NO_CONTENT) { return RestServiceResult.buildServiceResult(NO_CONTENT); } return RestServiceResult.buildServiceResult(OK, Json.toJson(jsr.getListContent())); }
@NotNull @Override public JavaServiceResult load( @NotNull Class<? extends DaoObject> clazz, int page, int itemPerPage, @NotNull String filters ) throws ServiceException { List< ImmutableTriple<String, String, String> > filterList = null; if(!filters.isEmpty()) { try { filterList = filterParserService.parse(filters); } catch (FilterParserServiceException e) { throw new ServiceException( QueryServiceJavaImpl.class.getName(), BAD_REQUEST, ExceptionUtils.getStackTrace(e), Messages.get("java.service.result.generic.error.msg") ); } } return load(clazz, page, itemPerPage, filterList); }
@NotNull @Override public JavaServiceResult load( @NotNull Class<? extends DaoObject> clazz, int page, int itemPerPage, @Nullable List<ImmutableTriple<String,String,String>> filterList ) throws ServiceException { List<? extends DaoObject> entityList; try { entityList = dao.load(clazz, page, itemPerPage, filterList); } catch (IllegalArgumentException | DaoException e) { throw new ServiceException( QueryServiceJavaImpl.class.getName(), BAD_REQUEST, ExceptionUtils.getStackTrace(e), Messages.get("java.service.result.generic.error.msg") ); } if(entityList == null || entityList.size() == 0) { return JavaServiceResult.buildServiceResult(NO_CONTENT); } else { return JavaServiceResult.buildServiceResult(OK, entityList); } }
@NotNull @Override public JavaServiceResult count(@NotNull Class<? extends DaoObject> clazz, @NotNull String filters) throws ServiceException { List< ImmutableTriple<String, String, String> > filterList = null; if(!filters.isEmpty()) { try { filterList = filterParserService.parse(filters); } catch (FilterParserServiceException e) { throw new ServiceException( GetServiceJavaImpl.class.getName(), BAD_REQUEST, ExceptionUtils.getStackTrace(e), Messages.get("java.service.result.generic.error.msg") ); } } return count(clazz, filterList); }
@Test public void parse_invalidRestFilter() { String invalidRestFilter = "name{like]lot|code[eq4"; FilterParserServiceImpl service = new FilterParserServiceImpl(); List<ImmutableTriple<String, String, String>> res = new ArrayList<>(); boolean exceptionThrown = false; try { res = service.parse(invalidRestFilter); } catch (FilterParserServiceException e) { Assert.assertNotNull(e); exceptionThrown = true; } Assert.assertTrue(exceptionThrown); Assert.assertTrue("res.size() should be equal to 0", (res.size() == 0)); }
private ImmutableTriple<Integer, HashMap<String, Double>, Boolean> addEntityFeatures( HashMap<String, List<Triple<Integer, HashMap<String, Double>, Boolean>>> source, String query, int wid, HashMap<String, Double> features, boolean accepted) { if (!source.containsKey(query)) source.put( query, new Vector<Triple<Integer, HashMap<String, Double>, Boolean>>()); ImmutableTriple<Integer, HashMap<String, Double>, Boolean> ftrTriple = new ImmutableTriple<>( wid, features, accepted); source.get(query).add(ftrTriple); return ftrTriple; }
private void addSourceSearchResult( HashMap<String, List<Triple<Integer, String, Integer>>> source, String query, HashMap<Integer, Integer> rankToIdNS, List<String> urls) { if (!source.containsKey(query)) source.put(query, new Vector<Triple<Integer, String, Integer>>()); for (int i = 0; i < urls.size(); i++) source.get(query).add( new ImmutableTriple<>(i, urls.get(i), rankToIdNS .containsKey(i) ? rankToIdNS.get(i) : -1)); }
/** * ==============help method============= */ private Triple<String, String, String> getmachineInfo(String providerAndConsumerKv, String groupService) { String thralUrl = consulClient.getKVValue(providerAndConsumerKv).getValue().getDecodedValue(); GrpcURL url = GrpcURL.valueOf(thralUrl); String flagAndIp = StringUtils.remove(providerAndConsumerKv, groupService + "/"); String[] serverInfos = StringUtils.split(flagAndIp, "/"); String machineFlag = serverInfos[1]; return new ImmutableTriple<String, String, String>(machineFlag, url.getAddress(), url.getParameter(Constants.HTTP_PORT_KEY)); }
private Triple<String, String, String> getPortHostService(String serviceId) { String[] args = StringUtils.split(serviceId, "-"); String hostRpcPort = args[0]; String service = args[1]; String version = "1.0.0"; if (args.length > 2) { version = args[2]; } return new ImmutableTriple<String, String, String>(hostRpcPort, service, version); }
public Triple<Long, String, Long> loadClientByToken(String tokenId) { String clientId = accessTokenRepository.findOneByTokenId(tokenId)// .map(accessTokenEntity -> accessTokenEntity.getClientId())// .orElseThrow(() -> new UsernameNotFoundException( "Token " + tokenId + " was not found in the database")); ClientDetailsEntity details = clientDetailsRepository.findOneByClientId(clientId).get(); ClientDetailsLimitEntity clientLimit = details.getClientLimit(); return new ImmutableTriple<Long, String, Long>(clientLimit.getIntervalInMills(), clientId, clientLimit.getLimits()); }
/** * @return Left:ColumnName Middle:ColumnType Right:ColumnTypeName */ public static Triple<List<String>, List<Integer>, List<String>> getColumnMetaData( Connection conn, String tableName, String column) { Statement statement = null; ResultSet rs = null; Triple<List<String>, List<Integer>, List<String>> columnMetaData = new ImmutableTriple<List<String>, List<Integer>, List<String>>( new ArrayList<String>(), new ArrayList<Integer>(), new ArrayList<String>()); try { statement = conn.createStatement(); String queryColumnSql = "select " + column + " from " + tableName + " where 1=2"; rs = statement.executeQuery(queryColumnSql); ResultSetMetaData rsMetaData = rs.getMetaData(); for (int i = 0, len = rsMetaData.getColumnCount(); i < len; i++) { columnMetaData.getLeft().add(rsMetaData.getColumnName(i + 1)); columnMetaData.getMiddle().add(rsMetaData.getColumnType(i + 1)); columnMetaData.getRight().add( rsMetaData.getColumnTypeName(i + 1)); } return columnMetaData; } catch (SQLException e) { throw DataXException .asDataXException(DBUtilErrorCode.GET_COLUMN_INFO_FAILED, String.format("获取表:%s 的字段的元信息时失败. 请联系 DBA 核查该库、表信息.", tableName), e); } finally { DBUtil.closeDBResources(rs, statement, null); } }
private ImmutableTriple<Long, Integer, TaskAttributes> constructFullMatchCancidate(TaskAttributes task) { String[] parts = task.getDescription().split("\\s+"); int wordCount = parts.length; long rank = Arrays.stream(parts) .filter(this::isFullMatch) .count(); return new ImmutableTriple<Long, Integer, TaskAttributes>(rank, wordCount, task); }
private ImmutableTriple<Long, Integer, TaskAttributes> constructStemMatchCandidate(TaskAttributes task) { String[] parts = task.getDescription().split("\\s+"); int wordCount = parts.length; long rank = Arrays.stream(parts) .map(stemmer::stem) .filter(this::isStemMatch) .count(); return new ImmutableTriple<Long, Integer, TaskAttributes>(rank, wordCount, task); }
private int candidateCompare(ImmutableTriple<Long, Integer, TaskAttributes> left, ImmutableTriple<Long, Integer, TaskAttributes> right) { if (left.getLeft() > right.getLeft()) { return -1; } else if (left.getLeft() < right.getLeft()) { return 1; } else { return left.getMiddle() - right.getMiddle(); } }
private static Triple<String, String, String> buildATriple() { Triple<String, String, String> toReturn = new ImmutableTriple<>( "Left", "Middle", "Right" ); return toReturn; }
private void bfgs() { System.out.println("BFGS:"); res = 0; int nbatches = 100; int nepoch = 1000; int batchsize = fb_h.size() / nbatches; for (int epoch = 0; epoch < nepoch; epoch++) { res = 0; for (int batch = 0; batch < nbatches; batch++) { relation_tmp = relation_vec.clone(); entity_tmp = entity_vec.clone(); for (int k = 0; k < batchsize; k++) { int i = rand_max(fb_h.size()); int j = rand_max(entity_num); double pr = 1000.0 * right_num.get(fb_r.get(i)) / (right_num.get(fb_r.get(i)) + left_num.get(fb_r.get(i))); if (method == 0) pr = 500; if (rand_max(1000) < pr) { while (ok.contains(new ImmutableTriple<>(fb_h.get(i), fb_r.get(i), j))) j = rand_max(entity_num); train_kb(fb_h.get(i), fb_l.get(i), fb_r.get(i), fb_h.get(i), j, fb_r.get(i)); } else { while (ok.contains(new ImmutableTriple<>(j, fb_r.get(i), fb_l.get(i)))) j = rand_max(entity_num); train_kb(fb_h.get(i), fb_l.get(i), fb_r.get(i), j, fb_l.get(i), fb_r.get(i)); } norm(relation_tmp[fb_r.get(i)]); norm(entity_tmp[fb_h.get(i)]); norm(entity_tmp[fb_l.get(i)]); norm(entity_tmp[j]); } relation_vec = relation_tmp; entity_vec = entity_tmp; } System.out.println("epoch:" + epoch + ' ' + res); } }
private void add(int e1, int e2, int r) { fb_h.add(e1); fb_r.add(r); fb_l.add(e2); Triple<Integer, Integer, Integer> triple = new ImmutableTriple<>(e1, r, e2); ok.add(triple); }
private void prepare() { List<String> entities = new ArrayList<>(); List<String> relations = new ArrayList<>(); List<Triple<String, String, String>> triples = new ArrayList<>(); try (Transaction tx = db.beginTx()) { for (Node node : db.getAllNodes()) { if (!node.hasLabel(Label.label(JavaCodeExtractor.CLASS)) && !node.hasLabel(Label.label(JavaCodeExtractor.INTERFACE)) && !node.hasLabel(Label.label(JavaCodeExtractor.METHOD)) && !node.hasLabel(Label.label(JavaCodeExtractor.FIELD))) continue; entities.add("" + node.getId()); } for (Relationship rel : db.getAllRelationships()) { Node node1 = rel.getStartNode(); if (!node1.hasLabel(Label.label(JavaCodeExtractor.CLASS)) && !node1.hasLabel(Label.label(JavaCodeExtractor.INTERFACE)) && !node1.hasLabel(Label.label(JavaCodeExtractor.METHOD)) && !node1.hasLabel(Label.label(JavaCodeExtractor.FIELD))) continue; Node node2 = rel.getEndNode(); if (!node2.hasLabel(Label.label(JavaCodeExtractor.CLASS)) && !node2.hasLabel(Label.label(JavaCodeExtractor.INTERFACE)) && !node2.hasLabel(Label.label(JavaCodeExtractor.METHOD)) && !node2.hasLabel(Label.label(JavaCodeExtractor.FIELD))) continue; triples.add(new ImmutableTriple<>("" + node1.getId(), "" + node2.getId(), rel.getType().name())); if (!relations.contains(rel.getType().name())) relations.add(rel.getType().name()); } tx.success(); } transE.prepare(entities, relations, triples); }
/** * Registers a new document from the resultset alongside with the information whether it was a hit or not. * Updates the retrieval statistics. * * @param docID ID of the document that was retrieved. * @param k The rank of the retrieved document. * @param relevant Boolean that indicates whether the document was relevant (true) or not (false). */ public final void documentAvailable(String docID, int k, boolean relevant) { if (k < 1) { throw new IllegalArgumentException(String.format("The value k must be greater than 0 (is: %d).", k)); } if (k < this.pk.size()) { throw new IllegalArgumentException(String.format("The provided rank %d has already been evaluated.", k)); } if (relevant) { this.intersection += 1; } this.retrieved += 1; Triple<String,Float,Float> triple = new ImmutableTriple<>(docID, (float)this.intersection/(float)k, (float)this.intersection/(float)this.relevant); this.pk.add(triple); }
/** * Split the path of a filename into the extensionless path (for URI construction) and the URI scheme (based on the file extension) * * @param path * The relative path within the contents directory * @return a triple of the path (left), the attribute(middle), and the URI scheme (right) */ public static Triple<String, String, Scheme> extractScheme(String path) { int chop = path.lastIndexOf('.'); if (chop < 0) return null; String schemeName = path.substring(chop); String attr = null; Scheme scheme = ext2scheme.get(schemeName); if (scheme == null) { scheme = raw2scheme.get(schemeName); if (scheme == null) { scheme = BLOB; // Oooerr - unmatched extensions will be blobs (THIS IS GOOD, BELIEVE ME) } else { path = path.substring(0, chop); } switch (scheme) { case BLOB: attr = getResolver().getMimeTypeFromPath(path); break; case SCRIPT: attr = schemeName.equals(".jjs") ? "jjs" : "raw"; break; default: throw new Error("Severe: Unhandled scheme in raw2scheme map"); // can only happen if a bad checkin is made } } else { path = path.substring(0, chop); } return ImmutableTriple.of(path, attr, scheme); }
private List<Triple<Integer, Optional<Double>, Boolean>> alterUntilBreakPoint(SolutionPerJob solPerJob, Function<Integer, Integer> updateFunction, Function<Double, Double> fromResult, Predicate<Double> feasibilityCheck, Predicate<Double> stoppingCondition, BiPredicate<Double, Double> incrementCheck, Predicate<Integer> vmCheck) { List<Triple<Integer, Optional<Double>, Boolean>> lst = new ArrayList<>(); Optional<Double> previous = Optional.empty(); boolean shouldKeepGoing = true; while (shouldKeepGoing) { Pair<Optional<Double>, Long> simulatorResult = dataProcessor.simulateClass(solPerJob); Optional<Double> maybeResult = simulatorResult.getLeft(); Optional<Double> interestingMetric = maybeResult.map(fromResult); Integer nVM = solPerJob.getNumberVM(); lst.add(new ImmutableTriple<>(nVM, maybeResult, interestingMetric.filter(feasibilityCheck).isPresent ())); boolean terminationCriterion = ! checkState() || vmCheck.test(nVM) || interestingMetric.filter(stoppingCondition).isPresent (); if (previous.isPresent() && interestingMetric.isPresent()) { terminationCriterion |= incrementCheck.test(previous.get(), interestingMetric.get()); } shouldKeepGoing = ! terminationCriterion; previous = interestingMetric; if (shouldKeepGoing) { String message = String.format("class %s -> num VM: %d, simulator result: %f, metric: %f", solPerJob.getId(), nVM, maybeResult.orElse(Double.NaN), interestingMetric.orElse(Double.NaN)); logger.info(message); solPerJob.updateNumberVM(updateFunction.apply(nVM)); } } return lst; }
public static void main(final String[] args) { ImmutableTriple<String, String, String> _immutableTriple = new ImmutableTriple<String, String, String>("NOT_CHECK", "0", "未审核"); ImmutableTriple<String, String, String> _immutableTriple_1 = new ImmutableTriple<String, String, String>("OK", "1", "通过"); ImmutableTriple<String, String, String> _immutableTriple_2 = new ImmutableTriple<String, String, String>("NO", "2", "不通过"); ArrayList<Triple<String, String, String>> _newArrayList = CollectionLiterals.<Triple<String, String, String>>newArrayList(_immutableTriple, _immutableTriple_1, _immutableTriple_2); String _enumKlass = Enums.enumKlass("BgStatus", _newArrayList); InputOutput.<String>println(_enumKlass); }