@SuppressWarnings({"rawtypes", "unchecked"}) protected <M extends Map, F> M buildCompositeMap( Function<F, M> mapMaker, PreferenceValueFunction<M> preferenceValueFunction, Collection<? extends IStylesheetData> defaults, M... extraDataMaps) { final M compositeMap = mapMaker.apply(null); // Add data from the stylesheet descriptor for (final IStylesheetData defaultData : defaults) { final String defaultValue = defaultData.getDefaultValue(); final String name = defaultData.getName(); compositeMap.put(name, defaultValue); } // Add any pre-existing data to the composite map for (final M existingValue : extraDataMaps) { compositeMap.putAll(existingValue); } // Iterate through scopes adding data from each stylesheet user prefs objects for (final Scope scope : Scope.values()) { final IStylesheetUserPreferences stylesheetUserPreferences = this.getStylesheetUserPreferences(scope, false); if (stylesheetUserPreferences != null) { final Map preferences = preferenceValueFunction.getPreferences(stylesheetUserPreferences); compositeMap.putAll(preferences); } } return compositeMap; }
@Override public void run() { for (int currentScale = 0; currentScale < nscales; currentScale++) { compute_coefs(retinexScales[currentScale]); if (channel == 0) { System.out.println("B:\t" + coefs.B); System.out.println("b0:\t" + coefs.b[0]); System.out.println("b1:\t" + coefs.b[1]); System.out.println("b2:\t" + coefs.b[2]); System.out.println("b3:\t" + coefs.b[3]); System.out.println("sigma:\t" + coefs.sigma); } for (int row = 0; row < height; row++) { gaussSmooth(row * width, width, 1); } for (int i = 0; i < channelSize; i++) { in[i] = out[i]; out[i] = 0; } for (int col = 0; col < width; col++) { gaussSmooth(col, height, width); } for (int i = 0; i < channelSize; i++) { dest[i * 3 + channel] += (float) (weight * (M.log(translate(myByte(i)) + 1) - M.log(out[i]))); } } }
@RequestMapping(value = "batch/delete") public String deleteInBatch( @RequestParam(value = "ids", required = false) ID[] ids, @RequestParam(value = Constants.BACK_URL, required = false) String backURL, RedirectAttributes redirectAttributes) { if (permissionList != null) { permissionList.assertHasDeletePermission(); } // 如果要求不严格 此处可以删除判断 前台已经判断过了 Searchable searchable = Searchable.newSearchable().addSearchFilter("id", SearchOperator.in, ids); List<M> mList = baseService.findAllWithNoPageNoSort(searchable); for (M m : mList) { if (m.isRoot()) { redirectAttributes.addFlashAttribute(Constants.ERROR, "您删除的数据中包含根节点,根节点不能删除"); return redirectToUrl(backURL); } } baseService.deleteSelfAndChild(mList); redirectAttributes.addFlashAttribute(Constants.MESSAGE, "删除成功"); return redirectToUrl(backURL); }
@RequestMapping(value = "{source}/move", method = RequestMethod.GET) @PageableDefaults(sort = {"parentIds=asc", "weight=asc"}) public String showMoveForm( HttpServletRequest request, @RequestParam(value = "async", required = false, defaultValue = "false") boolean async, @PathVariable("source") M source, Searchable searchable, Model model) { if (this.permissionList != null) { this.permissionList.assertHasEditPermission(); } List<M> models = null; // 排除自己及子子孙孙 searchable.addSearchFilter("id", SearchOperator.ne, source.getId()); searchable.addSearchFilter( "parentIds", SearchOperator.notLike, source.makeSelfAsNewParentIds() + "%"); if (!async) { models = baseService.findAllWithSort(searchable); } else { models = baseService.findRootAndChild(searchable); } model.addAttribute("trees", convertToZtreeList(request.getContextPath(), models, async, true)); model.addAttribute(Constants.OP_NAME, "移动节点"); return viewName("moveForm"); }
@Override public void doRequest(ServerData serverData) { CentralizedServiceWorker<I, ?, ?> serviceWorker = serverData.getServiceWorker(); // Get the initial size of ByteArrayVertexIdMessages per partition // on this worker. To make sure every ByteArrayVertexIdMessages to have // enough space to store the messages, we divide the original one-to-all // message size by the number of partitions and double the size // (Assume the major component in one-to-all message is a id list. // Now each target id has a copy of message, // therefore we double the buffer size) // to get the initial size of ByteArrayVertexIdMessages. int initialSize = oneToAllMsgs.getSize() / serverData.getPartitionStore().getNumPartitions() * 2; // Create ByteArrayVertexIdMessages for // message reformatting. Int2ObjectOpenHashMap<ByteArrayVertexIdMessages> partitionIdMsgs = new Int2ObjectOpenHashMap<ByteArrayVertexIdMessages>(); // Put data from ByteArrayOneToAllMessages to ByteArrayVertexIdMessages ExtendedDataInput reader = oneToAllMsgs.getOneToAllMessagesReader(); I vertexId = getConf().createVertexId(); M msg = oneToAllMsgs.createMessage(); int idCount = 0; int partitionId = 0; try { while (reader.available() != 0) { msg.readFields(reader); idCount = reader.readInt(); for (int i = 0; i < idCount; i++) { vertexId.readFields(reader); PartitionOwner owner = serviceWorker.getVertexPartitionOwner(vertexId); partitionId = owner.getPartitionId(); ByteArrayVertexIdMessages<I, M> idMsgs = partitionIdMsgs.get(partitionId); if (idMsgs == null) { idMsgs = new ByteArrayVertexIdMessages<I, M>(getConf().<M>getOutgoingMessageValueFactory()); idMsgs.setConf(getConf()); idMsgs.initialize(initialSize); partitionIdMsgs.put(partitionId, idMsgs); } idMsgs.add(vertexId, msg); } } } catch (IOException e) { throw new RuntimeException("doRequest: Got IOException ", e); } // Read ByteArrayVertexIdMessages and write to message store try { for (Entry<Integer, ByteArrayVertexIdMessages> idMsgs : partitionIdMsgs.entrySet()) { if (!idMsgs.getValue().isEmpty()) { serverData .getIncomingMessageStore() .addPartitionMessages(idMsgs.getKey(), idMsgs.getValue()); } } } catch (IOException e) { throw new RuntimeException("doRequest: Got IOException.", e); } }
@Override public Enumeration<String> getKeys() { List<String> keys = new LinkedList<String>(); for (M messageCode : EnumSet.allOf(messageCodeClass)) { keys.add(messageCode.getCode()); } return Collections.enumeration(keys); }
@Override protected Object handleGetObject(String key) { if (key == null) { throw new GenNullPointerException("key"); } M messageCode = Enum.valueOf(messageCodeClass, key); return messageCode.getMessagePattern(); }
// **********************************************************************************************// // ***クラスタリングの実行***// public static void Clustering(Grand grand, ant[] ant) { Point P = new Point(); grand.set(ant.length); long start = System.nanoTime(), end; Random rnd = new Random(); // 「Interation」の数だけ繰り返し for (int i = 0; i <= Iteration; i++) { // 回数表示 if (i % (Iteration / 100) == 0 && i != 0) { end = System.nanoTime(); System.out.println("field =" + (end - start) + "μs"); if (i % (Iteration / 10) == 0) NotAntCheck(grand); start = System.nanoTime(); } // すべての蟻で実行 for (int an = 0; an < ant.length; an++) { // drop if (is_carryingObject(ant[an]) && is_cellEmpty(ant[an].Location, grand.state)) // if(dropObject(grand.AroundR(ant[an],1),i)){ if (grand.AroundR(ant[an], 1) > rnd.nextInt(4)) { grand.state[ant[an].Location.y][ant[an].Location.x] = ant[an].State; ant[an].State = 0; ant[an].time = 0; ant[an].Memory.set_memory(ant[an].Location, ant[an].State); } else ant[an].time++; // pick else if (is_unloading(ant[an]) && has_object(ant[an].Location, grand.state)) // if(pickObject(grand.AroundR(ant[an],1),i)){ if (grand.AroundR(ant[an], 1) < rnd.nextInt(8)) { ant[an].State = grand.state[ant[an].Location.y][ant[an].Location.x]; grand.state[ant[an].Location.y][ant[an].Location.x] = 0; ant[an].time = 0; } else ant[an].time++; // メモリの受け渡し if (ant[an].Memory.all == false) { for (int j = 1; j <= MAX_kind; j++) if (ant[an].Memory.serch_memory(j)) { // ある物体の情報がないとき P = antOperation.Memory(grand.ant, ant[an], ant, j); if (0 < P.x && 0 < P.y) // 付近のアリが情報を持っているならば ant[an].Memory.set_memory(P, j); } ant[an].Memory.all_serch(MAX_kind); } // 物を持っている かつ メモリに保存されている とき if (ant[an].State != 0 && ant[an].Memory.serch_memory(ant[an].State)) // ジャンプ先予定地に蟻がいなければジャンプ if (is_stayingAnt(grand.ant, ant[an].Memory.P[ant[an].State])) { grand.MovingANT( ant[an].Memory.P[ant[an].State].x, ant[an].Memory.P[ant[an].State].y, ant[an]); M.Moves(ant[an], grand); } // 蟻の移動 M.Moves(ant[an], grand); } } System.out.println("\r "); }
/** * 获取表名 * * @return */ private String getTableName() { M m = getInstantce(); TableName tableName = m.getClass().getAnnotation(TableName.class); if (tableName != null) { return tableName.value(); } return ""; }
@Override public Optional<M> fill(DataHolder dataHolder, M manipulator, MergeFunction overlap) { if (!supports(dataHolder)) { return Optional.empty(); } else { final M merged = checkNotNull(overlap).merge(manipulator.copy(), from(dataHolder).orElse(null)); return Optional.of(manipulator.set(this.key, merged.get(this.key).get())); } }
@Override protected ByteBuf encodeMessage(ChannelHandlerContext ctx, M msg) { ByteBuf buf = ctx.alloc().buffer(); encodeHeader(buf, msg.getHeader()); encodeExtras(buf, msg.getExtras()); encodeKey(buf, msg.getKey()); return buf; }
@Override public void loadMarking(M newMarking) { if (newMarking.getPetriNet() != this) return; if (this.marking.equals(newMarking)) return; this.marking.clear(); for (Map.Entry<P, Integer> entry : newMarking.entrySet()) { this.marking.put(entry.getKey(), entry.getValue()); } }
@Override public void delete(Long[] ids) { Map<String, Object> searchParams = Maps.newHashMap(); searchParams.put("id_in", ids); Searchable searchable = Searchable.newSearchable(searchParams); Page<M> page = getCoreRepository().findAll(searchable); for (M m : page.getContent()) { attachmentImageService.delete(m.getWork().getId()); } super.delete(ids); }
private <V, M extends Map<Object, V>> M _convertValues( Map<?, ?> map, Class<M> mapClass, Class<V> valueClass) { M newMap = (M) MapUtils.of(mapClass); for (Entry entry : map.entrySet()) { try { V v = convert(entry.getValue(), valueClass); newMap.put(entry.getKey(), v); } catch (ConversionException ex) { } } return newMap; }
@Override public void run() { int start = 0, stop = 0; int three = width * height / 3; switch (third) { case 0: stop = three; break; case 1: start = three; stop = 2 * three; break; case 2: start = 2 * three; stop = width * height; break; } for (int i = start; i < stop; i++) { int first = (hasAlpha) ? i * 4 + 1 : i * 3; int destFirst = i * 3; float logl = (float) M.log( translate(original[first]) + translate(original[first + 1]) + translate(original[first + 2]) + 3.0); dest[destFirst] = gain * (float) (M.log(alpha * (translate(original[first]) + 1) - logl) * dest[destFirst]) + offset; dest[destFirst + 1] = gain * (float) (M.log(alpha * (translate(original[first + 1]) + 1) - logl) * dest[destFirst + 1]) + offset; dest[destFirst + 2] = gain * (float) (M.log(alpha * (translate(original[first + 2]) + 1) - logl) * dest[destFirst + 2]) + offset; } }
private <K, V, M extends Map<K, V>> M _convertContents( Map<?, ?> map, Class<M> mapClass, Class<K> keyClass, Class<V> valueClass) { M newMap = (M) MapUtils.of(mapClass); for (Entry entry : map.entrySet()) { try { K k = convert(entry.getKey(), keyClass); V v = convert(entry.getValue(), valueClass); newMap.put(k, v); } catch (ConversionException ex) { } } setCacheKeyValueTypes(map, keyClass, valueClass); return newMap; }
@Override public String toString() { M msgObj = null; try { msgObj = get(); } catch (IllegalStateException e) { // It is ok. might not be able to avoid this case in some situations. return super.toString() + "{could not be deserialized}"; } if (msgObj == null) { return super.toString(); } return msgObj.toString(); }
/** * Convert a Map to a Map with keys and values of the desired types. If it is a Map and it is of * the same Map, Key and Value types it is returned as is, otherwise a new Map is created with all * keys and values converted to the desired type. If it is a String representation of a Map it is * converted to a Map. * * @param <K> The key type. * @param <V> The value type. * @param <M> The Map type. * @param obj The Object to be converted. * @param mapType The desired Map type. * @param keyType The desired key type. * @param valueType The desired value type. * @param emptyIfNull Whether or not an empty Map should be returned if the Map could not be * converted. * @return The converted Collection. */ public <K, V, M extends Map<K, V>> M convertToMap( Object obj, Class<M> mapType, Class<K> keyType, Class<V> valueType, boolean emptyIfNull) { if (obj != null) { if (obj instanceof Map) { // If it's already a collection Map map = (Map) obj; Pair<Class<?>, Class<?>> cachedType = getCachedKeyValueTypes(map); // Look up the cached types if available, if they can be downcast to the // requested types do so and update cache if (cachedType != null && keyType.isAssignableFrom(cachedType.getKey()) && valueType.isAssignableFrom(cachedType.getValue())) { setCacheKeyValueTypes(map, keyType, valueType); return (M) map; } else { return _convertContents(map, mapType, keyType, valueType); } } else { try { // If it's a string representation of key-value pairs M m = MapUtils.of(mapType); String string = convert(obj, String.class); if (string.startsWith("{") && string.endsWith("}")) { string = string.substring(1, string.length() - 1); } String[] entries = TextUtils.splitOnSpacesAndCommas(string); for (String str : entries) { String[] split = str.split("="); if (split.length == 2) { try { K k = convert(split[0], keyType); V v = convert(split[1], valueType); m.put(k, v); } catch (ConversionException ex) { } } } if (!m.isEmpty()) { return m; } } catch (ConversionException ex) { } } } if (emptyIfNull) { return MapUtils.of(mapType); } return null; }
@Override public void edit(final M model) { // guard against multiple calls to edit() if (this.model != null) { this.model.getItemsChangedEvent().removeListener(itemsChangedListener); this.model.getPropertyChangedEvent().removeListener(propertyChangedListener); } this.model = model; model.getItemsChangedEvent().addListener(itemsChangedListener); model.getPropertyChangedEvent().addListener(propertyChangedListener); enabled = model.getIsChangable(); setVisible(model.getIsAvailable()); init(model); }
@Override public void validate(W webModel, M serviceModel) { assertError( webModel.isNotifyUsers() && !webModel.isCreateUsers(), "Notify users flag does not make sense unless create user flag is set"); assertError( webModel.isCreateUsers() && !userHelper.canAddUsers(), "Create users flag does not make sense unless writable user directory is configured or number of already registered users increased."); serviceModel.setCreateUsers(webModel.isCreateUsers()); serviceModel.setNotifyUsers(webModel.isNotifyUsers()); serviceModel.setCcAssignee(webModel.isCcAssignee()); serviceModel.setCcWatcher(webModel.isCcWatcher()); serviceModel.setStripQuotes(webModel.isStripQuotes()); }
/** * Checks if the given map is not null or empty. * * @param <T> the generic type of the elements in the given collection * @param <K> the generic type of the key from the given Map * @param <V> the generic type of the value from the given Map * @param <M> the generic type of the given Map * @param map the map to check * @param name the name of the given collection * @return if the check is successful a reference to this object. This case is if the given map is * not null or empty. * @throws IllegalArgumentException when the given {@code map} is null or empty. */ public <T, K, V, M extends Map<K, V>> Check notEmpty(final M map, final String name) { nullCheck(map, name); if (map.isEmpty()) { throw new IllegalArgumentException("Given map '" + name + "' may not be empty."); } return this; }
@Override public int hashCode() { int result = left != null ? left.hashCode() : 0; result = 31 * result + (middle != null ? middle.hashCode() : 0); result = 31 * result + (right != null ? right.hashCode() : 0); return result; }
@RequestMapping( value = "ajax/{parent}/appendChild", method = RequestMethod.GET, produces = "application/json") @ResponseBody public Object ajaxAppendChild(HttpServletRequest request, @PathVariable("parent") M parent) { if (permissionList != null) { permissionList.assertHasCreatePermission(); } M child = newModel(); child.setName("新节点"); baseService.appendChild(parent, child); return convertToZtree(child, true, true); }
@RequestMapping(value = "{source}/move", method = RequestMethod.POST) @PageableDefaults(sort = {"parentIds=asc", "weight=asc"}) public String move( HttpServletRequest request, @RequestParam(value = "async", required = false, defaultValue = "false") boolean async, @PathVariable("source") M source, @RequestParam("target") M target, @RequestParam("moveType") String moveType, Searchable searchable, Model model, RedirectAttributes redirectAttributes) { if (this.permissionList != null) { this.permissionList.assertHasEditPermission(); } if (target.isRoot() && !moveType.equals("inner")) { model.addAttribute(Constants.ERROR, "不能移动到根节点之前或之后"); return showMoveForm(request, async, source, searchable, model); } baseService.move(source, target, moveType); redirectAttributes.addFlashAttribute(Constants.MESSAGE, "移动节点成功"); return redirectToUrl(viewName("success")); }
/** * 模型对象转化为ContentValues对象 * * @param m * @param values */ private void fillColumn(M m, ContentValues values) { Field[] fields = m.getClass().getDeclaredFields(); for (Field item : fields) { item.setAccessible(true); Column column = item.getAnnotation(Column.class); if (column != null) { String key = column.value(); try { String value = item.get(m).toString(); if (value.length() > 0) { values.put(key, value); } } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } } } }
/** * 填充模型对象 * * @param cursor * @param m */ private void fillField(Cursor cursor, M m) { Field[] fields = m.getClass().getDeclaredFields(); for (Field item : fields) { item.setAccessible(true); Column column = item.getAnnotation(Column.class); if (column != null) { int columnIndex = cursor.getColumnIndex(column.value()); String value = cursor.getString(columnIndex); try { if (item.getType() == int.class) { item.set(m, Integer.valueOf(value)); } else if (item.getType() == long.class) { item.set(m, Long.valueOf(value)); } else { item.set(m, value); } } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } } } }
private void readAll() throws IOException { String[] columns = (String[]) _lkv.get("[columns]"); String[][] domains = parseModelDomains(columns.length); _model = makeModel(columns, domains); _model._uuid = readkv("uuid"); _model._category = hex.ModelCategory.valueOf((String) readkv("category")); _model._supervised = readkv("supervised"); _model._nfeatures = readkv("n_features"); _model._nclasses = readkv("n_classes"); _model._balanceClasses = readkv("balance_classes"); _model._defaultThreshold = readkv("default_threshold"); _model._priorClassDistrib = readkv("prior_class_distrib"); _model._modelClassDistrib = readkv("model_class_distrib"); _model._offsetColumn = readkv("offset_column"); readModelData(); }
private double selectDeath(RandomGenerator e, C conf, M modif, double[] out) { int size = conf.size(clazz); if (size < this.n) { return 0.; } int denom = 1; int d[] = new int[this.n]; for (int i = 0; i < this.n; ++i, --size) { d[i] = (size == 1) ? 0 : sample(e, size); for (int j = 0; j < i; ++j) if (d[j] <= d[i]) ++d[i]; // skip already selected indices for (int j = 0; j < i; ++j) if (d[j] == d[i]) { LOGGER.error("sampled " + d[i] + " twice"); } Iterator<T> it = conf.iterator(clazz); for (int j = 0; j < d[i]; j++) { it.next(); } T t = it.next(); modif.insertDeath(t); double[] outTmp = new double[this.builder.size()]; this.builder.setCoordinates(t, outTmp); for (int j = 0; j < this.builder.size(); j++) { out[i * this.builder.size() + j] = outTmp[j]; } denom *= size; } return 1. / (double) denom; }
private double selectBirth(RandomGenerator e, C conf, M modif, double[] in) { int beg = conf.size(clazz) - modif.getDeath().size() + 1; int end = beg + this.n; int denom = 1; int current = 0; for (int size = beg; size < end; ++size) { double[] v = new double[this.dimension]; for (int i = 0; i < this.dimension; i++) { v[i] = in[i + current]; } modif.insertBirth(this.builder.build(v)); current += this.dimension; denom *= size; } return 1. / (double) denom; }
@SuppressWarnings("unchecked") public String getStringValue(M model, String property) { if (propertyProviders != null && propertyProviders.containsKey(property)) { return propertyProviders.get(property).getStringValue(model, property); } if (classProviders != null && model.get(property) != null) { Class<?> clz = model.<Object>get(property).getClass(); if (classProviders.containsKey(clz)) { return classProviders.get(clz).getStringValue(model, property); } } ModelStringProvider<M> temp = stringProvider != null ? stringProvider : (ModelStringProvider) defaultProvider; return temp.getStringValue(model, property); }