public-method 相关问题


Laravel POST 方法返回状态:405 不允许在 POST 方法上使用方法

请查找以下信息: NoteController.php 请查找以下信息: NoteController.php <?php namespace App\Http\Controllers; use App\Http\Requests\NoteRequest; use App\Models\Note; use Illuminate\Http\JsonResponse; class NoteController extends Controller { public function index():JsonResponse { $notes = Note::all(); return response()->json($notes, 200); } public function store(NoteRequest $request):JsonResponse { $note = Note::create( $request->all() ); return response()->json([ 'success' => true, 'data' => $note ], 201); } public function show($id):JsonResponse { $note = Note::find($id); return response()->json($note, 200); } public function update(NoteRequest $request, $id):JsonResponse { $note = Note::find($id); $note->update($request->all()); return response()->json([ 'success' => true, 'data' => $note, ], 200); } public function destroy($id):JsonResponse { Note::find($id)->delete(); return response()->json([ 'success' => true ], 200); } } NoteRequest.php <?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class NoteRequest extends FormRequest { public function authorize() { return true; } public function rules() { return [ 'title', 'required|max:255|min:3', 'content', 'nullable|max:255|min:10', ]; } } Note.php(模型) <?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Note extends Model { use HasFactory; protected $guarded = []; } api.php <?php use App\Http\Controllers\NoteController; use Illuminate\Support\Facades\Route; Route::prefix('v1')->group(function () { Route::resource('/note', NoteController::class); }); php artisan 路线:列表 GET|HEAD / ...................................................................................................................... POST _ignition/execute-solution ............... ignition.executeSolution › Spatie\LaravelIgnition › ExecuteSolutionController GET|HEAD _ignition/health-check ........................... ignition.healthCheck › Spatie\LaravelIgnition › HealthCheckController POST _ignition/update-config ........................ ignition.updateConfig › Spatie\LaravelIgnition › UpdateConfigController GET|HEAD api/v1/note .......................................................................... note.index › NoteController@index POST api/v1/note .......................................................................... note.store › NoteController@store GET|HEAD api/v1/note/create ................................................................. note.create › NoteController@create GET|HEAD api/v1/note/{note} ..................................................................... note.show › NoteController@show PUT|PATCH api/v1/note/{note} ................................................................. note.update › NoteController@update DELETE api/v1/note/{note} ............................................................... note.destroy › NoteController@destroy GET|HEAD api/v1/note/{note}/edit ................................................................ note.edit › NoteController@edit GET|HEAD sanctum/csrf-cookie .................................. sanctum.csrf-cookie › Laravel\Sanctum › CsrfCookieController@show 迅雷请求(同邮递员) JSON 请求 { "title": "Hello World", "content": "Lorem ipsum." } 尝试发出 JSON POST 请求并获取状态:405 方法不允许并且我正在使用 php artisan 服务,如果需要,我可以提供 GIT 项目。请告诉我。 您的验证规则看起来不正确。在您的 NoteRequest 类中,规则应该是一个关联数组,其中键是字段名称,值是验证规则。但是,在您的代码中,规则被定义为以逗号分隔的字符串列表。这可能会导致验证失败并返回 405 Method Not allowed 错误。 public function rules() { return [ 'title' => 'required|max:255|min:3', 'content' => 'nullable|max:255|min:10', ]; }


Laravel 购物车页面,表单内有一个表单,用于处理删除和提交数据更新数据库

我有一个购物车页面,表格内有一个表格,也许你可以建议我应该做什么? 根据图片,我给出的蓝色圆圈是一个表格 我的刀片代码 我有一个购物车页面,表格内有一个表格,也许你可以建议我应该做什么?根据图片我给出的蓝色圆圈是一个表格我的刀片代码<table class="table"> <thead> <tr> <th scope="col">No</th> <th scope="col">Nama Barang</th> <th scope="col">Quantity</th> <th scope="col">Action</th> </tr> </thead> <tbody> @php $no = 1; @endphp @forelse ($permintaans as $b) <tr> <td>{{ $no ++ }}</td> <td> {{ $b->nama_kategori }} {{ $b->nama_atk }} </td> <td> <form action="{{ route('permintaan.update', $b->id) }}" method="POST" style="display: inline-block;"> @csrf @method('PUT') <div class="input-group input-group-sm mb-3"> <input type="number" class="form-control" aria-label="Sizing example input" aria-describedby="inputGroup-sizing-sm" name="satuan_permintaan" min="0" max={{ $b->stok }} required> <span class="input-group-text" id="inputGroup-sizing-sm">{{ $b->subsatuan_atk }}</span> </div> </td> <td> <form action="{{ route('permintaan.destroy', $b->id) }}" method="POST" style="display: inline-block;"> @csrf @method('DELETE') <button type="submit" class="btn custom2-btn"><svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" fill="red" class="bi bi-trash" viewBox="0 0 16 16"> <path d="M5.5 5.5A.5.5 0 0 1 6 6v6a.5.5 0 0 1-1 0V6a.5.5 0 0 1 .5-.5m2.5 0a.5.5 0 0 1 .5.5v6a.5.5 0 0 1-1 0V6a.5.5 0 0 1 .5-.5m3 .5a.5.5 0 0 0-1 0v6a.5.5 0 0 0 1 0z"/> <path d="M14.5 3a1 1 0 0 1-1 1H13v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V4h-.5a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1H6a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1h3.5a1 1 0 0 1 1 1zM4.118 4 4 4.059V13a1 1 0 0 0 1 1h6a1 1 0 0 0 1-1V4.059L11.882 4zM2.5 3h11V2h-11z"/> </svg></button> </form> </td> </tr> @empty @endforelse </tbody> </table> 我的控制器public function store(Request $request) { $task = new Permintaan(); $task->atk_id = $request->input('atk_id'); $task->proses = 'Proses'; if (Permintaan::where('atk_id', $task->atk_id)->exists()){ return redirect('/atk/permintaan')->with(['info' => 'ATK Sudah Dalam Permintaan']); } else{ $task->save(); return redirect()->route('permintaan.index'); } } public function destroy($id) { $permintaan = Permintaan::find($id); $permintaan->delete(); return redirect()->route('permintaan.index'); } 我要处理删除并提交数据更新数据库 在开始销毁表单之前关闭更新表单第一个表单标签(缺少)。


在 C# 中将 Task<T> 转换为 Task<object>,无需 T

我有一个充满扩展方法的静态类,其中每个方法都是异步的并返回一些值 - 像这样: 公共静态类 MyContextExtensions{ 公共静态异步任务 我有一个充满扩展方法的静态类,其中每个方法都是异步的并返回一些值 - 像这样: public static class MyContextExtensions{ public static async Task<bool> SomeFunction(this DbContext myContext){ bool output = false; //...doing stuff with myContext return output; } public static async Task<List<string>> SomeOtherFunction(this DbContext myContext){ List<string> output = new List<string>(); //...doing stuff with myContext return output; } } 我的目标是能够从另一个类中的单个方法调用这些方法中的任何一个,并将其结果作为对象返回。它看起来像这样: public class MyHub: Hub{ public async Task<object> InvokeContextExtension(string methodName){ using(var context = new DbContext()){ //This fails because of invalid cast return await (Task<object>)typeof(MyContextExtensions).GetMethod(methodName).Invoke(null, context); } } } 问题是转换失败。我的困境是我无法将任何类型参数传递给“InvokeContextExtension”方法,因为它是 SignalR 中心的一部分并且由 javascript 调用。在某种程度上,我不关心扩展方法的返回类型,因为它只会序列化为 JSON 并发送回 javascript 客户端。但是,我确实必须将 Invoke 返回的值转换为任务才能使用等待运算符。我必须为该“任务”提供一个通用参数,否则它将把返回类型视为 void。因此,这一切都归结为如何成功地将具有通用参数 T 的任务转换为具有对象通用参数的任务,其中 T 表示扩展方法的输出。 您可以分两步完成 - await使用基类执行任务,然后使用反射或dynamic收获结果: using(var context = new DbContext()) { // Get the task Task task = (Task)typeof(MyContextExtensions).GetMethod(methodName).Invoke(null, context); // Make sure it runs to completion await task.ConfigureAwait(false); // Harvest the result return (object)((dynamic)task).Result; } 这是一个完整的运行示例,它将上述通过反射调用 Task 的技术置于上下文中: class MainClass { public static void Main(string[] args) { var t1 = Task.Run(async () => Console.WriteLine(await Bar("Foo1"))); var t2 = Task.Run(async () => Console.WriteLine(await Bar("Foo2"))); Task.WaitAll(t1, t2); } public static async Task<object> Bar(string name) { Task t = (Task)typeof(MainClass).GetMethod(name).Invoke(null, new object[] { "bar" }); await t.ConfigureAwait(false); return (object)((dynamic)t).Result; } public static Task<string> Foo1(string s) { return Task.FromResult("hello"); } public static Task<bool> Foo2(string s) { return Task.FromResult(true); } } 一般来说,要将 Task<T> 转换为 Task<object>,我会简单地采用简单的连续映射: Task<T> yourTaskT; // .... Task<object> yourTaskObject = yourTaskT.ContinueWith(t => (object) t.Result); (文档链接在这里) 但是,您实际的具体需求是 通过反射调用 Task 并获取其(未知类型)结果 。 为此,您可以参考完整的dasblinkenlight的答案,它应该适合您的具体问题。 我想提供一个实现,恕我直言,这是早期答案的最佳组合: 精确的参数处理 无动态调度 通用扩展方法 给你: /// <summary> /// Casts a <see cref="Task"/> to a <see cref="Task{TResult}"/>. /// This method will throw an <see cref="InvalidCastException"/> if the specified task /// returns a value which is not identity-convertible to <typeparamref name="T"/>. /// </summary> public static async Task<T> Cast<T>(this Task task) { if (task == null) throw new ArgumentNullException(nameof(task)); if (!task.GetType().IsGenericType || task.GetType().GetGenericTypeDefinition() != typeof(Task<>)) throw new ArgumentException("An argument of type 'System.Threading.Tasks.Task`1' was expected"); await task.ConfigureAwait(false); object result = task.GetType().GetProperty(nameof(Task<object>.Result)).GetValue(task); return (T)result; } 您不能将 Task<T> 转换为 Task<object>,因为 Task<T> 不是协变的(也不是逆变的)。最简单的解决方案是使用更多反射: var task = (Task) mi.Invoke (obj, null) ; var result = task.GetType ().GetProperty ("Result").GetValue (task) ; 这很慢且效率低下,但如果不经常执行此代码则可用。顺便说一句,如果您要阻塞等待其结果,那么异步 MakeMyClass1 方法有什么用呢? 另一种可能性是为此目的编写一个扩展方法: public static Task<object> Convert<T>(this Task<T> task) { TaskCompletionSource<object> res = new TaskCompletionSource<object>(); return task.ContinueWith(t => { if (t.IsCanceled) { res.TrySetCanceled(); } else if (t.IsFaulted) { res.TrySetException(t.Exception); } else { res.TrySetResult(t.Result); } return res.Task; } , TaskContinuationOptions.ExecuteSynchronously).Unwrap(); } 它是非阻塞解决方案,将保留任务的原始状态/异常。 最有效的方法是自定义等待者: struct TaskCast<TSource, TDestination> where TSource : TDestination { readonly Task<TSource> task; public TaskCast(Task<TSource> task) { this.task = task; } public Awaiter GetAwaiter() => new Awaiter(task); public struct Awaiter : System.Runtime.CompilerServices.INotifyCompletion { System.Runtime.CompilerServices.TaskAwaiter<TSource> awaiter; public Awaiter(Task<TSource> task) { awaiter = task.GetAwaiter(); } public bool IsCompleted => awaiter.IsCompleted; public TDestination GetResult() => awaiter.GetResult(); public void OnCompleted(Action continuation) => awaiter.OnCompleted(continuation); } } 具有以下用法: Task<...> someTask = ...; await TaskCast<..., object>(someTask); 这种方法的局限性在于结果不是 Task<object> 而是一个可等待的对象。 我根据dasblinkenlight的回答做了一个小小的扩展方法: public static class TaskExtension { public async static Task<T> Cast<T>(this Task task) { if (!task.GetType().IsGenericType) throw new InvalidOperationException(); await task.ConfigureAwait(false); // Harvest the result. Ugly but works return (T)((dynamic)task).Result; } } 用途: Task<Foo> task = ... Task<object> = task.Cast<object>(); 这样您就可以将 T 中的 Task<T> 更改为您想要的任何内容。 对于最佳方法,不使用反射和动态丑陋语法,也不传递泛型类型。我将使用两种扩展方法来实现这个目标。 public static async Task<object> CastToObject<T>([NotNull] this Task<T> task) { return await task.ConfigureAwait(false); } public static async Task<TResult> Cast<TResult>([NotNull] this Task<object> task) { return (TResult) await task.ConfigureAwait(false); } 用途: Task<T1> task ... Task<T2> task2 = task.CastToObject().Cast<T2>(); 这是我的第二种方法,但不推荐: public static async Task<TResult> Cast<TSource, TResult>([NotNull] this Task<TSource> task, TResult dummy = default) { return (TResult)(object) await task.ConfigureAwait(false); } 用途: Task<T1> task ... Task<T2> task2 = task.Cast((T2) default); // Or Task<T2> task2 = task.Cast<T1, T2>(); 这是我的第三种方法,但是不推荐:(类似于第二种) public static async Task<TResult> Cast<TSource, TResult>([NotNull] this Task<TSource> task, Type<TResult> type = null) { return (TResult)(object) await task.ConfigureAwait(false); } // Dummy type class public class Type<T> { } public static class TypeExtension { public static Type<T> ToGeneric<T>(this T source) { return new Type<T>(); } } 用途: Task<T1> task ... Task<T2> task2 = task.Cast(typeof(T2).ToGeneric()); // Or Task<T2> task2 = task.Cast<T1, T2>(); 将 await 与动态/反射调用混合使用并不是一个好主意,因为 await 是一条编译器指令,它会围绕调用的方法生成大量代码,并且使用更多反射来“模拟”编译器工作并没有真正的意义,延续、包装等 因为您需要的是在运行时管理代码,然后忘记在编译时工作的 asyc await 语法糖。重写 SomeFunction 和 SomeOtherFunction 而不使用它们,并在运行时创建的您自己的任务中开始操作。您将得到相同的行为,但代码非常清晰。


使用 InertiaJs 和 Laravel 从数据库中删除用户

我在从数据库中删除记录时遇到问题。我正在使用 InertiaJS 和 Laravel。 组件代码 以下是链接/按钮代码: 我在从数据库中删除记录时遇到问题。我正在使用 InertiaJS 和 Laravel。 组件代码 以下是链接/按钮代码: <Link class="trash" @click="submit(result.ChildID)"> Move to Trash </Link> 注意: ChildID 是数据库中子记录的 id。 现在:当用户单击此链接时,将调用一个方法,如下所示。 methods: { submit: function (ChildID) { alert(ChildID) if (confirm("Are you sure you want to delete this child?")) { this.$inertia.delete('destroy/ChildID'); } }, }, 路线代码 Route::delete('destroy/{childID}',[childrenController::class,'destroy']); 控制器代码 public function destroy(children $childID){ $childID->delete(); return redirect()->route('View_Child_Profile'); } 现在,当我点击删除按钮时,我收到以下错误: 试试这个。我认为你犯了错误“this.$inertia.delete('destroy/ChildID');” methods: { submit: function (ChildID) { alert(ChildID) if (confirm("Are you sure you want to delete this child?")) { this.$inertia.delete(`destroy/${ChildID}`); // or this.$inertia.delete('destroy/'+ChildID); } }, }, 这是我处理删除过程的方式。 前视+惯性: import { Link } from '@inertiajs/inertia-vue3'; 在模板中: <Link method="delete" :href="route('admin.insta_feeds.destroy',id)">Delete</Link> 后端 Laravel: 路线: Route::resource('insta_feeds', InstaFeedsController::class); 控制器功能: public function destroy(InstaFeed $insta_feed) { if(isset($insta_feed->image_path)){ Storage::delete($insta_feed->image_path); } $insta_feed->delete(); return Redirect::route('admin.insta_feeds.index'); }


如何在node js中使用DOM更改文本内容

我想做的是 我想在输入错误密码时将标签更改为错误密码 但出现错误 ReferenceError:文档未定义 这是我的 HTML 文件 我想做的是 我想在输入错误密码时将 标签更改为错误密码 但出现错误 ReferenceError:文档未定义 这是我的 HTML 文件 <form action="/check" method="POST"> <label for="password">Password:</label> <input type="text" id="password" name="password" required> <input type="submit" value="Submit"> <p></p> </form> 这是我的 javascript 文件内容 import express from "express"; import {dirname} from "path"; import { fileURLToPath } from "url"; import bodyParser from "body-parser"; const __dirname = dirname(fileURLToPath(import.meta.url)); const app = express(); const port = 3000; const pass = "ILoveProgramming"; var enter = ""; app.use(bodyParser.urlencoded({extended:true})); function checker(req, res, next){ enter = req.body.password; console.log(enter); next(); } app.use(checker); app.get("/", (req,res) =>{ res.sendFile(__dirname +"/public/index.html"); }); app.post("/check",(req,res)=>{ if(pass === enter){ res.sendFile(__dirname+"/public/secret.html"); } else{ document.querySelector("p").textContent("The paswrd is wrong"); console.log("The password is incorrect"); } // console.log(enter); }); app.use(bodyParser); app.listen(port, () =>{ console.log(`server is live at ${port}`); }); 我对这一切都是新手所以把我当作一个没有任何经验的人 document对象是浏览器DOM API的一部分,它在服务器端不可用。在浏览器控制台上,它是 window 对象的属性。 window.document。 您正在尝试操作服务器上的 DOM,这是不可能的。您应该在浏览器接收并呈现 HTML 页面后在客户端处理 DOM 操作。为此,您应该在 HTML 文件内有一个 script 标签。 <script> // inside here you add your logic to access document <script/> script标签将在浏览器上执行,您可以访问此标签内的document对象


Struts 2 与 Apache Shiro 集成时如何显示结果页面

使用: struts2 2.5.10, 春天 4.x, struts2-spring-插件2.5.10, 希罗1.4.0, Shiro-Spring 1.4.0。 网络.xml: 使用: struts2 2.5.10, 春季 4.x, struts2-spring-插件2.5.10, 四郎1.4.0, shiro-spring 1.4.0. web.xml: <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <display-name>Archetype Created Web Application</display-name> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:beans.xml</param-value> </context-param> <filter> <filter-name>shiroFilter</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> <init-param> <param-name>targetFilterLifecycle</param-name> <param-value>true</param-value> </init-param> </filter> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <!-- shiro filter mapping has to be first --> <filter-mapping> <filter-name>shiroFilter</filter-name> <url-pattern>/*</url-pattern> <dispatcher>REQUEST</dispatcher> <dispatcher>FORWARD</dispatcher> <dispatcher>INCLUDE</dispatcher> <dispatcher>ERROR</dispatcher> </filter-mapping> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app> beanx.xml: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd "> <bean name="loginAction" class="example.shiro.action.LoginAction" > </bean> <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> <property name="securityManager" ref="securityManager" /> <property name="loginUrl" value="/login.jsp" /> <property name="filterChainDefinitions"> <value> /login.jsp = authc /logout = logout /* = authc </value> </property> </bean> <bean id="iniRealm" class="org.apache.shiro.realm.text.IniRealm"> <property name="resourcePath" value="classpath:shiro.ini" /> </bean> <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> <property name="realm" ref="iniRealm" /> </bean> <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/> </beans> struts.xml: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <constant name="struts.devMode" value="true" /> <package name="default" extends="struts-default"> <action name="list" class="loginAction" method="list"> <result name="success">/success.jsp</result> <result name="error">error.jsp</result> </action> </package> </struts> index.jsp: <body> <s:action name="list" /> </body> login.jsp 看起来像: <form name="loginform" action="" method="post"> <table align="left" border="0" cellspacing="0" cellpadding="3"> <tr> <td>Username:</td> <td><input type="text" name="username" maxlength="30"></td> </tr> <tr> <td>Password:</td> <td><input type="password" name="password" maxlength="30"></td> </tr> <tr> <td colspan="2" align="left"><input type="checkbox" name="rememberMe"><font size="2">Remember Me</font></td> </tr> <tr> <td colspan="2" align="right"><input type="submit" name="submit" value="Login"></td> </tr> </table> </form> LoginAction.list(): public String list() { Subject currentUser = SecurityUtils.getSubject(); if(currentUser.isAuthenticated()) {System.out.println("user : "+currentUser.getPrincipal()); System.out.println("You are authenticated!"); } else { System.out.println("Hey hacker, hands up!"); } return "success"; } shiro.ini: [users] root=123,admin guest=456,guest frank=789,roleA,roleB # role name=permission1,permission2,..,permissionN [roles] admin=* roleA=lightsaber:* roleB=winnebago:drive:eagle5 index.jsp、login.jsp、success.jsp放在webapp下 我想要的是:输入LoginAction.list()需要进行身份验证,如果登录成功,则运行LoginAction.list()并返回"success"然后显示定义为Struts操作结果的success.jsp。 现在登录成功后可以执行LoginAction.list(),但是success.jsp不显示,浏览器是空白页面。 为什么? 我找到了原因:我在index.jsp中使用了<s:action name="list" />,但是struts文档说如果我们想用<s:action>看到结果页面,那么我们必须将其属性executeResult设置为true,即就像<s:action name="list" executeResult="true"/>。 在我看来,这有点奇怪,这个属性默认应该是 true。 有一个示例,您应该如何使用 Shiro applicationContext.xml 进行配置: <property name="filterChainDefinitions"> <value> # some example chain definitions: /admin/** = authc, roles[admin] /** = authc # more URL-to-FilterChain definitions here </value> </property> 以 /admin/ 开头的 URL 通过角色 admin 进行保护,任何其他 URL 均不受保护。如果 Struts 操作和结果 JSP 不在受保护区域中,则会显示它们。


在Java中将流转换为字符串

我想将 Map<> 的流转换为字符串,并将其附加到文本区域。我尝试了一些方法,最后一个使用 StringBuilder,但它们不起作用。 公开 我想将 Map<> 的流转换为字符串,并将其附加到文本区域。我尝试了一些方法,最后一个使用 StringBuilder,但它们不起作用。 public <K, V extends Comparable<? super V>> String sortByAscendentValue(Map<K, V> map, int maxSize) { StringBuilder sBuilder = new StringBuilder(); Stream<Map.Entry<K,V>> sorted = map.entrySet().stream() .sorted(Collections.reverseOrder(Map.Entry.comparingByValue())); BufferedReader br = new BufferedReader(new InputStreamReader((InputStream) sorted)); String read; try { while ((read=br.readLine()) != null) { //System.out.println(read); sBuilder.append(read); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } sorted.limit(maxSize).forEach(System.out::println); return sBuilder.toString(); } 您可以将条目收集到一个String中,如下所示: String sorted = map.entrySet().stream() .sorted(Collections.reverseOrder(Map.Entry.comparingByValue())) .map(e-> e.getKey().toString() + "=" + e.getValue().toString()) .collect(Collectors.joining (",")); 考虑对 @Eran 的代码进行轻微更改,因为 HashMap.Entry.toString() 已经通过 = 为您加入了: String sorted = map.entrySet().stream() .sorted(Collections.reverseOrder(Map.Entry.comparingByValue())) .map(Objects::toString) .collect(Collectors.joining(",")); 这很容易做到,您可以使用 Steams API 来做到这一点。首先,将映射中的每个条目映射到单个字符串 - 键和值的连接字符串。一旦你有了这个,你就可以简单地使用 reduce() 方法或 collect() 方法来做到这一点。 使用“reduce()”方法的代码片段将如下所示: Map<String, String> map = new HashMap<>(); map.put("sam1", "sam1"); map.put("sam2", "sam2"); String concatString = map.entrySet() .stream() .map(element-> element.getKey().toString() + " : " + element.getValue().toString()) .reduce("", (str1,str2) -> str1 + " , " + str2).substring(3); System.out.println(concatString); 这将为您提供以下输出: sam2 : sam2 , sam1 : sam1 您还可以使用 collect()' method instead ofreduce()` 方法。它看起来像这样: String concatString = map.entrySet() .stream() .map(element-> element.getKey().toString() + " : " + element.getValue().toString()) .collect(Collectors.reducing("", (str1,str2) -> str1 + " , " + str2)).substring(3); 两种方法给出相同的输出。


将 YAML 文件注入构造函数

我有这个 YAML 文件 src/main/resources/foo.yml: 酒吧: - 你好 - 世界 巴兹: - 洛雷姆 - ipsum 这个组件: @成分 公共类我的组件{ 公共我的组件(地图 我有这个 YAML 文件 src/main/resources/foo.yml: bar: - hello - world baz: - lorem - ipsum 这个组件: @Component public class MyComponent { public MyComponent(Map<String, List<String>> foo) { // foo.get("bar") } } 使用 Spring Boot 2.7,是否可以将配置按原样(自己的文件,无前缀,无类)注入到构造函数中? 你可以这样做 @Configuration public class MyConfiguration { @Bean public Map<String, Object> foo(@Value("classpath:foo.yaml") Resource yaml) { Yaml yaml = new Yaml(); return yaml.load(yaml.getInputStream()); } } @Component public class MyComponent { public MyComponent(@Qualifier("foo") Map<String, Object> foo) { ... } }


将属性值从父级用户控件传递到子级的 DependencyProperty

如何将属性(SomeProperty)从ParentUserControl上下文传递到ChildUserControl的DependencyProperty(MyDProperty)? 在 XAML 中,它应该是: 如何将 ParentUserControl 上下文中的 property (SomeProperty) 传递到 ChildUserControl 的 DependencyProperty (MyDProperty)? 在XAML中,应该是: 但是,由于某种原因,MyDProperty 永远不会使用 Parent.DataContext.SomeProperty 设置。 就我而言,我正在传递一个操作,但这并不重要。我认为问题出在绑定上。 家长用户控制: public Action RemoveEsl1 => throw new NotImplementedException(); <uc:ChildUserControl Title="ESL 1" RemoveEslAction="{Binding RemoveEsl1}" DataContext="{Binding Esl1}"/> 子用户控件: public static readonly DependencyProperty RemoveEslActionProperty = DependencyProperty.Register(nameof(RemoveEslAction), typeof(Action), typeof(ChildUserControl), new PropertyMetadata(delegate { })); public Action RemoveEslAction { get => (Action)GetValue(RemoveEslActionProperty); set => SetValue(RemoveEslActionProperty, value); } 我在这里找到了各种技巧,但没有一个适合我或有效。 回答我自己的问题(检查 ParentUserControl): 型号: public class RootModel : ViewModelBase { private ParentModel parentModel = new(); public ParentModel ParentModel { get => parentModel; set => RisePropertyChanged(ref parentModel, value); } } public class ParentModel : ViewModelBase { private ChildModel childModel = new(); public ChildModel ChildModel { get => childModel; set => RisePropertyChanged(ref childModel, value); } public string ParentModelProperty => "Correct value from ParentModel"; } public class ChildModel : ViewModelBase { private string childModelProperty = "Wrong default value from ChildModel"; public string ChildModelProperty { get => childModelProperty; set => RisePropertyChanged(ref childModelProperty, value); } } 主窗口: <Window.DataContext> <model:RootModel/> </Window.DataContext> <uc:ParentUserControl DataContext="{Binding ParentModel}"/> 家长用户控件: <uc:ChildUserControl ChildDependency="{Binding DataContext.ParentModelProperty, RelativeSource={RelativeSource AncestorType=UserControl}}" DataContext="{Binding ChildModel}"/> 子用户控件: <StackPanel> <Label Content="Dependency property:"/> <Label Content="{Binding ChildDependency, RelativeSource={RelativeSource AncestorType=UserControl}}"/> <Separator/> <Label Content="Property:"/> <Label Content="{Binding ChildModelProperty}"/> </StackPanel> public partial class ChildUserControl : UserControl { public static readonly DependencyProperty ChildDependencyProperty = DependencyProperty.Register(nameof(ChildDependency), typeof(string), typeof(ChildUserControl), new ("Wrong default DP value from ChildUserControl")); public string ChildDependency { get => (string)GetValue(ChildDependencyProperty); set => SetValue(ChildDependencyProperty, value); } public ChildUserControl() { InitializeComponent(); } } 这就是如何将属性 (SomeProperty) 从 ParentUserControl 上下文传递到 ChildUserControl 的 DependencyProperty (MyDProperty)。


如何检查系统深色模式是否启用

binding.switchh.setOnCheckedChangeListener(新CompoundButton.OnCheckedChangeListener(){ @覆盖 public void onCheckedChanged(CompoundButtoncompoundButton, 布尔检查...


pandas 系列替换为回填替代品

pandas.Series.replace 的文档包含一个示例: >> 将 pandas 导入为 pd >> s = pd.Series([1, 2, 3, 4, 5]) >> s.replace([1, 2], method='bfill') 0 3 1 3 2 3 ...


Chainlink 反应热烈

我从 chainlink 文档运行此代码,但没有获得图像。 函数 requestBytes() public returns (bytes32 requestId) { 地址预言=“


这两种转换方式有什么区别?

我有以下代码(从浮点数转换为十六进制数): 浮点数小数 = 12.1; int num = (int) 小数; // <- (Method 1) int num2 = (*(int*) &decimal); // <- (M...


顺风未加载颜色

有简单的html: 公共/index.html: 有简单的html: public/index.html: <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="styles.css"> </head> <body class="text-red-600"> some text </body> css 是从 tailwindcss -i src/styles.css -o public/styles.css 获取的 src/styles.css: @tailwind base; @tailwind components; @tailwind utilities; tailwind.config.js: module.exports = { content: ["./src/**/*.{html,js}"], theme: { extend: {}, }, plugins: [], } <body>标签中的红色不适用。默认的顺风类别是否导入到public/styles.css? Tailwind 配置中的 public/index.html 文件似乎没有覆盖 content 文件。您必须确保使用 Tailwind 类的源代码文件被 content 文件 glob 覆盖,否则 Tailwind 将不会扫描这些文件,也不会为存在的类名生成 CSS 规则。考虑阅读有关配置的文档content。 module.exports = { content: [ "./src/**/*.{html,js}", "./public/index.html", ], theme: { extend: {}, }, plugins: [], }


子控件中的绑定命令?

我有一个 UserControl,用作窗口对话框的“模板”。 它包含一个关闭按钮和一个取消按钮。 我有一个 UserControl,用作窗口对话框的“模板”。 它包含一个关闭按钮和一个取消按钮。 <UserControl x:Class="TombLib.WPF.Controls.WindowControlButtons" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:TombLib.WPF.Controls" mc:Ignorable="d" xmlns:darkUI="clr-namespace:DarkUI.WPF;assembly=DarkUI.WPF" xmlns:vm="clr-namespace:TombLib.WPF.ViewModels" xmlns:sg="clr-namespace:SpacedGridControl;assembly=SpacedGridControl" d:DesignHeight="100" d:DesignWidth="300" x:Name="root"> <StackPanel VerticalAlignment="Center" HorizontalAlignment="Right" Height="Auto" Orientation="Horizontal"> <Button Name="oKButton" Margin="{x:Static darkUI:Defaults.MediumThickness}" Width="100" Height="Auto" Command="{Binding Close}" CommandParameter="{Binding Window}" Content="OK"></Button> <Button Name="cancelButton" Margin="{x:Static darkUI:Defaults.MediumThickness}" Width="100" Height="Auto" Command="{Binding Path=Cancel}" CommandParameter="{Binding Window}" Content="Cancel"></Button> </StackPanel> </UserControl> public partial class WindowControlButtons : UserControl { public static readonly DependencyProperty CancelProperty = DependencyProperty.Register( nameof(Cancel), typeof(ICommand), typeof(WindowControlButtons), new PropertyMetadata(null)); public ICommand Cancel { get { return (ICommand)GetValue(CancelProperty); } set { SetValue(CancelProperty, value); } } public static readonly DependencyProperty CloseProperty = DependencyProperty.Register( nameof(Close), typeof(ICommand), typeof(WindowControlButtons), new PropertyMetadata(null)); public ICommand Close { get { return (ICommand)GetValue(CloseProperty); } set { SetValue(CloseProperty, value); } } public static readonly DependencyProperty WindowParameter = DependencyProperty.Register( nameof(Window), typeof(object), typeof(WindowControlButtons), new PropertyMetadata(null)); public object? Window { get { return GetValue(WindowParameter); } set { SetValue(WindowParameter, value); } } public WindowControlButtons() { InitializeComponent(); } } 我想在以下窗口中使用它: <Window x:Class="TombLib.WPF.Windows.SelectIdWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:TombLib.WPF.Windows" mc:Ignorable="d" xmlns:ctrl="clr-namespace:TombLib.WPF.Controls" xmlns:vm="clr-namespace:TombLib.WPF.ViewModels" xmlns:sg="clr-namespace:SpacedGridControl;assembly=SpacedGridControl" xmlns:darkUI="clr-namespace:DarkUI.WPF;assembly=DarkUI.WPF" Title="SelectIdWindow" Height="100" Width="300" d:DataContext="{d:DesignInstance Type=vm:SelectIdViewModel }" x:Name="Self"> <sg:SpacedGrid Margin="{x:Static darkUI:Defaults.MediumThickness}"> <!-- REDACTED --> <ctrl:WindowControlButtons DataContext="{Binding ElementName=Self}" Window="{Binding ElementName=Self, Mode=OneWay}" Close="{Binding CloseCommand,Mode=OneWay}" Cancel="{Binding CancelCommand,Mode=OneWay}" Height="Auto" Width="Auto" Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2" HorizontalAlignment="Right"/> </sg:SpacedGrid> </Window> public partial class SelectIdWindow : Window { public ICommand? CloseCommand { get; set; } public ICommand? CancelCommand { get; set; } public SelectIdWindow() { CloseCommand = new WindowCloseCommand(); InitializeComponent(); } } public class SelectIdViewModel { public string RequestedId { get; set; } = string.Empty; public IEnumerable<string> TakenIds { get; set;} public SelectIdViewModel(IEnumerable<string> takenIDs) { TakenIds = takenIDs; } } 但是,当我打开窗口时如下: SelectIdWindow w = new SelectIdWindow(); var takenIDs = Entities.Select(kv => kv.Key.Name); w.DataContext = new SelectIdViewModel(takenIDs); w.ShowDialog(); 我在绑定 WindowControlButtons 时收到以下错误: DataContext 显式设置为 Self,它应该代表 Window,而不是 ViewModel。我在这里做错了什么? 绑定错误表明问题出在 Button.ICommand 属性上: 要修复此问题,请在 WindowControlButtons 绑定中添加 ElementName=root,以便绑定到声明的依赖项属性而不是 DataContext: <UserControl x:Class="TombLib.WPF.Controls.WindowControlButtons" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:TombLib.WPF.Controls" mc:Ignorable="d" xmlns:darkUI="clr-namespace:DarkUI.WPF;assembly=DarkUI.WPF" xmlns:vm="clr-namespace:TombLib.WPF.ViewModels" xmlns:sg="clr-namespace:SpacedGridControl;assembly=SpacedGridControl" d:DesignHeight="100" d:DesignWidth="300" x:Name="root"> <StackPanel VerticalAlignment="Center" HorizontalAlignment="Right" Height="Auto" Orientation="Horizontal"> <Button Name="oKButton" ... Command="{Binding Close, ElementName=root}" CommandParameter="{Binding Window, ElementName=root}" Content="OK"/> <Button Name="cancelButton" ... Command="{Binding Path=Cancel, ElementName=root}" CommandParameter="{Binding Window, ElementName=root}" Content="Cancel"/> </StackPanel> </UserControl>


安装Spring Boot执行器

我有一个 SpringBoot 应用程序,其配置在端口 8081 上运行: @豆 public SecurityFilterChain filterChain(HttpSecurity http) 抛出异常 { http.csrf(AbstractHttpConf...


服务器返回“405 Method Not allowed”。仅限一条路线

主页的web.php中的这条路线 路线::get('/', 'App\Http\Controllers\IndexController@index'); 如果我运行 php artisan optimize 或 artisan route:cache,页面会变成错误 405 哎呀!错误


指向 std::vector 的指针作为输出参数

我将一个指向向量的指针作为函数中的输出参数,我不知道这是否是最佳实践: 状态接口::method(const std::vector** outVec); 我正在写...


使用 StructureMap 连接不同的实现

我有一个非常简单的通用存储库: 公共接口IRepository 其中 TEntity : EntityObject 其中 TNotFound : TEntity, new() { 列表 我有一个非常简单的通用存储库: public interface IRepository<TEntity, TNotFound> where TEntity : EntityObject where TNotFound : TEntity, new() { IList<TEntity> GetAll(); TEntity With(int id); TEntity Persist(TEntity itemToPersist); void Delete(TEntity itemToDelete); } 我想为 Term 类型的存储库定义一个合约,没有任何特殊行为。所以它看起来像这样: public class TermNotFound : Term { public TermNotFound() : base(String.Empty, String.Empty) { } } public interface ITermRepository : IRepository<Term, TermNotFound> { } 现在为了测试,我想创建通用存储库的内存中实现,所以我有这个(为简洁起见,未完成): public class InMemoryRepository<TEntity, TNotFound> : IRepository<TEntity, TNotFound> where TEntity : EntityObject where TNotFound : TEntity, new() { private IList<TEntity> _repo = new List<TEntity>(); public IList<TEntity> GetAll() { return this._repo; } public TEntity With(int id) { return this._repo.SingleOrDefault(i => i.Id == id) ?? new TNotFound(); } public TEntity Persist(TEntity itemToPersist) { throw new NotImplementedException(); } public void Delete(TEntity itemToDelete) { throw new NotImplementedException(); } } 不难看出我希望它如何工作。对于我的测试,我希望注入通用 InMemoryRepository 实现来创建我的 ITermRepository。 好吧,我无法让 StructureMap 来做这件事。我尝试在扫描仪中使用 WithDefaultConventions 和 ConnectImplementationsToTypesClosing(typeof(IRepository<,>)) 但没有成功。接下来我可以尝试什么? 您的 InMemoryRepository 未实现 ITermRepository 接口。这就是为什么你无法连接它们。 你能用你所拥有的最好的办法就是注射 InMemoryRepository<Term, TermNotFound> 以获得 IRepository<Term, TermNotFound>。 如果你确实需要注入ITermRepository,那么你需要有另一个存储库类继承InMemoryRepository并实现ITermRepository: public class InMemoryTermRepository : InMemoryRepository<Term, TermNotFound>, ITermRepository { } 现在您可以使用以下方法将 ITermRepository 连接到 InMemoryTermRepository: .For<ITermRepository>().Use<InMemoryTermRepository>() 如果您有很多像 ITermRepository 这样的接口,您可以创建一个 StructureMap 约定,将 I...Repository 连接到 InMemory...Repository。默认约定是将 IClass 连接到 Class。


如何比较两个对象属性?

公共类 CellAtt { 私人琴弦品牌; 私人长连载; 私人双价; public CellAtt(字符串品牌,长序列,双倍价格) { this.brand = 品牌; ...


自定义 Weblogic HTTP 扩展日志记录格式

当前在我的 weblogic 服务器中我已启用 HTTP 日志记录。以下是当前配置。 格式为“扩展”。 扩展日志格式字段为“日期时间 cs-method cs-uri sc-status time...


“无法为受信任的根颁发机构构建证书链。”升级到 .NET 8 后

我使用以下代码来配置 Saml2 public static voidConfigureSaml2(此IServiceCollection服务,IConfiguration配置) { 服务.配置(


我应该如何使用多部分文件作为RequestParam来测试这个Java API

我正在尝试在控制器上测试以下API: @PostMapping("/{code}") public ResponseEntity importFichier(@PathVariable("code") 字符串代码...


为什么方法的值在select方法中不会改变?

我有一个从 Postgres 中的序列返回值的方法: public long GetSId(DatabaseFacade d,字符串序列名称) { var result = new NpgsqlParameter(":result", NpgsqlDbType.Integ...


用 Ruby 编写一个脚本,将所有 *.htm 文件重命名为 *.html

我需要用 Ruby 编写一个脚本,将给定的所有 *.htm 文件重命名为 *.html 目录。 我收到的剧本有一些缺失。 我需要使用适当的方法名称“METHOD”...


将值从用户控件传递到同一用户控件wpf c#中的另一个?

我有四个用户控件,我尝试将值从用户控件传递到另一个用户控件,这些用户控件存在于同一个用户控件中。 这个 xml 主页面 ` 我有四个用户控件,我尝试将值从用户控件传递到另一个用户控件,这些用户控件存在于同一个用户控件中。 这个 xml 主页面 ` <Grid> <StackPanel Background="#FFF"> <local:mwidget x:Name="mwidget" Loaded="UserControl1_Loaded"/> <local:addemploy x:Name="addemploy" Visibility="Hidden"/> <local:editemploy x:Name="editemploy" Visibility="Hidden" /> </StackPanel> </Grid>` 还有这个代码 ` private void UserControl1_Loaded(object sender, RoutedEventArgs e) { mwidget.ShowUserControl2Requested += OnShowUserControl2Requested; addemploy.ShowUserControl1Requested += OnShowUserControl1Requested; editemploy.ShowUserControl1Requestedd += ShowUserControl1Requestedd; mwidget.ShowUserControl2Requestedd += ShowUserControl1Requesteddd; } private void OnShowUserControl2Requested(object sender, EventArgs e) { addemploy.Visibility = Visibility.Visible; mwidget.Visibility = Visibility.Collapsed; } private void OnShowUserControl1Requested(object sender, EventArgs e) { mwidget.Visibility = Visibility.Visible; addemploy.Visibility = Visibility.Collapsed; } private void ShowUserControl1Requestedd(object sender, EventArgs e) { mwidget.Visibility = Visibility.Visible; editemploy.Visibility = Visibility.Collapsed; } private void ShowUserControl1Requesteddd(object sender, EventArgs e) { editemploy.Visibility = Visibility.Visible; mwidget.Visibility = Visibility.Collapsed; }` 这个代码mwidget ` public partial class mwidget : UserControl { public event EventHandler ShowUserControl2Requested; public event EventHandler ShowUserControl2Requestedd; public mwidget() { InitializeComponent(); } private void add_employ(object sender, RoutedEventArgs e) { ShowUserControl2Requested?.Invoke(this, EventArgs.Empty); } private void edit_employ(object sender, System.Windows.RoutedEventArgs e) { ShowUserControl2Requestedd?.Invoke(this, EventArgs.Empty); } }` 所以我想将值从 mwidget 传递到 editemploy,我尝试了一些解决方案,但不起作用 您需要在 mwidget 和 editemploy 中创建 DependencyPropertys 并将它们相互绑定。 (注意:在下面的示例中,我使用了 OneWayToSource。这可以防止 editemploy 更改 mwidget 中的值。如果您不想这样做,请将其更改为 TwoWay。) m小部件: public static readonly DependencyProperty MyValueProperty = DependencyProperty.Register( nameof(MyValue), typeof(bool), typeof(mwidget)); public bool MyValue { get => (bool)GetValue(MyValueProperty); set => SetValue(MyValueProperty, value); } 编辑雇佣: public static readonly DependencyProperty MyPassedValueProperty = DependencyProperty.Register( nameof(MyPassedValue), typeof(bool), typeof(editemploy)); public bool MyPassedValue { get => (bool)GetValue(MyPassedValueProperty); set => SetValue(MyPassedValueProperty, value); } xaml: <local:mwidget x:Name="mwidget" Loaded="UserControl1_Loaded"/> <local:addemploy x:Name="addemploy" Visibility="Hidden"/> <local:editemploy x:Name="editemploy" Visibility="Hidden" MyPassedValue="{Binding ElementName=mwidget, Path=MyValue, Mode=OneWayToSource}" />


ML.net - CreateTimeSeriesEngine

我正在使用 ML.net 进行时间序列分析项目。在这里我尝试预测欧元兑美元的交易汇率。我从 CSV 文件加载数据并使用内存数据创建 IDataView。 列表 我正在使用 ML.net 进行时间序列分析项目。在这里我尝试预测欧元兑美元的交易汇率。我从 CSV 文件加载数据并使用内存数据创建 IDataView。 List<RateData> infoList = new List<RateData>(); // populate list infoList = FileParser(infoList); IDataView data = mlContext.Data.LoadFromEnumerable<RateData>(infoList); 我设法像这样运行预测估计器 var forecastEstimator = mlContext.Forecasting.ForecastBySsa( outputColumnName: nameof(RatePrediction.CurrentRate), inputColumnName: nameof(RateData.HistoricalRate), windowSize: 14, seriesLength: numRateDataPoints, trainSize: numRateDataPoints, horizon: 1, confidenceLevel: 0.95f ); SsaForecastingTransformer forecaster = forecastEstimator.Fit(RateDataSeries); 然后我尝试创建这样的预测引擎 var ForecastEngine = Forecaster.CreateTimeSeriesEngine(mlContext); 这里我遇到了一些错误。 我的输入和输出类如下: public class RateData { public DateTime TransactionDate { get; set; } public float HistoricalRate { get; set; } } public class RatePrediction { public float CurrentRate; } 我有这样的错误 System.InvalidOperationException: Can't bind the IDataView column 'CurrentRate' of type 'Vector<Single, 1>' to field or property 'CurrentRate' of type 'System.Single'. at Microsoft.ML.Data.TypedCursorable`1..ctor(IHostEnvironment env, IDataView data, Boolean ignoreMissingColumns, InternalSchemaDefinition schemaDefn) at Microsoft.ML.Data.TypedCursorable`1.Create(IHostEnvironment env, IDataView data, Boolean ignoreMissingColumns, SchemaDefinition schemaDefinition) at Microsoft.ML.Transforms.TimeSeries.TimeSeriesPredictionEngine`2.PredictionEngineCore(IHostEnvironment env, InputRow`1 inputRow, IRowToRowMapper mapper, Boolean ignoreMissingColumns, SchemaDefinition outputSchemaDefinition, Action& disposer, IRowReadableAs`1& outputRow) at Microsoft.ML.PredictionEngineBase`2..ctor(IHostEnvironment env, ITransformer transformer, Boolean ignoreMissingColumns, SchemaDefinition inputSchemaDefinition, SchemaDefinition outputSchemaDefinition, Boolean ownsTransformer) at Microsoft.ML.Transforms.TimeSeries.TimeSeriesPredictionEngine`2..ctor(IHostEnvironment env, ITransformer transformer, Boolean ignoreMissingColumns, SchemaDefinition inputSchemaDefinition, SchemaDefinition outputSchemaDefinition) at Microsoft.ML.Transforms.TimeSeries.PredictionFunctionExtensions.CreateTimeSeriesEngine[TSrc,TDst](ITransformer transformer, IHostEnvironment env, Boolean ignoreMissingColumns, SchemaDefinition inputSchemaDefinition, SchemaDefinition outputSchemaDefinition) at USD_EURO_Conversion_rate.TimeSeriesModelHelper.FitAndSaveModel(MLContext mlContext, IDataView RateDataSeries, String outputModelPath) 预测类中的属性需要是float[]类型;向量/数组而不是单个值,例如 public class RatePrediction { public float[] CurrentRate; } 类似于此处的Microsoft 示例。


带有 saml2 sso 的 Springboot:未找到依赖方注册

我有一个简单的 Springboot 3.1.2 应用程序,带有 SAML2,使用 okta 作为身份提供者。 我的安全配置是: @豆 public SecurityFilterChain filterChain(HttpSecurity http, SuezGebruikersServ...


主窗口后面出现应用内购买弹出窗口 - Flutter Win32 C++ 应用程序

我正在使用 Flutter Method Channel 开发 Windows 桌面应用程序,并且遇到了应用内购买功能的问题。触发后,购买模式对话框出现在主应用程序后面


macOS 14 中的 FortiClient VPN 白色空白屏幕

FortiClient版本:7.0.9.0360 系统版本:macOS 14 Public Beta 2(包括macOS 13.4) 当我打开 FortiClient VPN-Only(包括完整版)时,会显示白色空白屏幕。 截屏 然后我...


进入该片段后屏幕变白。第二次应用程序停止工作。怎么解决这个问题?

@覆盖 public View onCreateView(LayoutInflater inflater, ViewGroup 容器, 捆绑已保存实例状态) { 上下文= getActivity(); view = inflater.inflate(R.layout.fragment_shor1, 包含...


.NET MAUI:自定义Shell TitleView并绑定到当前页面标题

我想用我自己的自定义布局替换默认的 Shell 标头,如下所示: 我想用我自己的自定义布局替换默认的 Shell 标头,如下所示: <?xml version="1.0" encoding="UTF-8" ?> <Shell x:Class="MyNamespace.App.AppShell" xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:local="clr-namespace:MyNamespace.App" xmlns:pages="clr-namespace:MyNamespace.App.Pages" BindingContext="{x:Static local:MainView.Instance}" Shell.FlyoutBehavior="{Binding ShellFlyoutType}" x:Name="shellMain"> <Shell.TitleView> <Grid ColumnDefinitions="*,200"> <Label BindingContext="{x:Reference shellMain}" Text="{Binding Path=CurrentPage.Title, Mode=OneWay}" FontSize="Large" TextColor="White" /> <ActivityIndicator IsRunning="{Binding IsBusy}" Color="Orange" Grid.Column="1" HorizontalOptions="End" /> </Grid> </Shell.TitleView> <ShellContent Title=" Login" ContentTemplate="{DataTemplate local:MainPage}" Route="login" FlyoutItemIsVisible="False" /> <ShellContent Title="Dashboard" ContentTemplate="{DataTemplate pages:DashboardPage}" Route="dashboard" /> </Shell> 我无法绑定当前页面标题。 我的 AppShell.xaml Shell 声明如下 <Shell ... x:Name="shellMain"> 作为替代方案,您可以在 OnNaviged 方法中设置 titleview : 在 AppShell.xaml 中,定义标签的名称 <Shell.TitleView> <Grid ColumnDefinitions="*,200"> <Label BindingContext="{x:Reference shellMain}" x:Name="mylabel" FontSize="Large" TextColor="White" /> <ActivityIndicator IsRunning="{Binding IsBusy}" Color="Orange" Grid.Column="1" HorizontalOptions="End" /> </Grid> </Shell.TitleView> 在AppShell.xaml.cs中,重写OnNaviged方法,获取当前项目 protected override void OnNavigated(ShellNavigatedEventArgs args) { base.OnNavigated(args); var shellItem = Shell.Current?.CurrentItem; string title = shellItem?.Title; int iterationCount = 0; while (shellItem != null && title == null) { title = shellItem.Title; shellItem = shellItem.CurrentItem; if (iterationCount > 10) break; // max nesting reached iterationCount++; } myLabel.Text = title; } 希望它对你有用。 我正在尝试同样的方法来修改 TitleView 的外观。它可以在 iOS 上运行,尽管那里还有另一个错误。但在 Android 上我遇到了同样的问题。在前进导航中,它会更新标题,但当您按后退按钮时,标题不会更新。我已经打开了一个问题并添加了一个存储库。 https://github.com/dotnet/maui/issues/12416#issuecomment-1372627514 还有其他方法可以修改TitleView的外观吗? 我使用视图模型开发了这个解决方法,主要不是为了提供 MVVM 解决方案,而是因为其他建议的答案对我不起作用。 (我怀疑 Liqun Shen 2 月 15 日针对他自己的问题的评论中的建议会起作用。但我没有注意到这一点,直到我自己修复)。 当前页面的标题保存在可由 shell 的视图模型和每个内容页面的视图模型访问的类中: public class ServiceHelper { private static ServiceHelper? _default; public static ServiceHelper Default => _default ??= new ServiceHelper(); internal string CurrentPageTitle { get; set; } = string.Empty; } shell 中每个内容页面的视图模型提供其页面标题。为了促进这一点,大部分工作都是由基本视图模型完成的,它们都是从该模型派生而来的: public abstract class ViewModelBase(string title) : ObservableObject { private ServiceHelper? _serviceHelper; public string Title { get; } = title; internal ServiceHelper ServiceHelper { get => _serviceHelper ??= ServiceHelper.Default; set => _serviceHelper = value; // For unit testing. } public virtual void OnAppearing() { ServiceHelper.CurrentPageTitle = Title; } } 每个 shell 内容页面视图模型只需要让其基础视图模型知道它的标题: public class LocationsViewModel : ViewModelBase { public LocationsViewModel() : base("Locations") { } } 每个 shell 内容页面都需要在其视图模型中触发所需的事件响应方法: public partial class LocationsPage : ContentPage { private LocationsViewModel? _viewModel; public LocationsPage() { InitializeComponent(); } private LocationsViewModel ViewModel => _viewModel ??= (LocationsViewModel)BindingContext; protected override void OnAppearing() { base.OnAppearing(); ViewModel.OnAppearing(); } } Shell 的视图模型为标题栏提供当前页面的标题: public class AppShellViewModel() : ViewModelBase(Global.ApplicationTitle) { private string _currentPageTitle = string.Empty; public string CurrentPageTitle { get => _currentPageTitle; set { _currentPageTitle = value; OnPropertyChanged(); } } public void OnNavigated() { CurrentPageTitle = ServiceHelper.CurrentPageTitle; } } Shell 需要在其视图模型中触发所需的事件响应方法: public partial class AppShell : Shell { private AppShellViewModel? _viewModel; public AppShell() { InitializeComponent(); } private AppShellViewModel ViewModel => _viewModel ??= (AppShellViewModel)BindingContext; protected override void OnNavigated(ShellNavigatedEventArgs args) { base.OnNavigated(args); ViewModel.OnNavigated(); } } 最后,Shell 的 XAML 在标题栏/导航栏上显示由 Shell 视图模型提供的当前页面的标题: <Shell.TitleView> <HorizontalStackLayout VerticalOptions="Fill"> <Image Source="falcon_svg_repo_com.png" HeightRequest="50"/> <Label x:Name="CurrentPageTitleLabel" Text="{Binding CurrentPageTitle}" FontSize="24" Margin="10,0" VerticalTextAlignment="Center"/> </HorizontalStackLayout> </Shell.TitleView>


Java 和 Xerces:找不到属性 XMLConstants.ACCESS_EXTERNAL_DTD

我在这个博客上查找了类似的帖子,但找不到我的问题的答案,所以我决定寻求帮助。 我用 Java 编写了这个简单的函数: public void open(InputStream stream) 抛出


AnimationSet 未按预期执行顺序动画

如果我手动执行多个连续动画。它按预期工作。这是我的可行代码 扩展.xml 如果我手动执行多个连续动画。它按预期工作。这是我的可行代码 scale_up.xml <?xml version="1.0" encoding="utf-8"?> <scale xmlns:android="http://schemas.android.com/apk/res/android" android:fromXScale="1.0" android:fromYScale="1.0" android:toXScale="1.1" android:toYScale="1.1" android:pivotX="50%" android:pivotY="50%" android:fillAfter="true" android:interpolator="@android:anim/decelerate_interpolator" android:duration="@android:integer/config_shortAnimTime" /> scale_down.xml <?xml version="1.0" encoding="utf-8"?> <scale xmlns:android="http://schemas.android.com/apk/res/android" android:fromXScale="1.1" android:fromYScale="1.1" android:toXScale="1.0" android:toYScale="1.0" android:pivotX="50%" android:pivotY="50%" android:fillAfter="true" android:interpolator="@android:anim/decelerate_interpolator" android:duration="@android:integer/config_shortAnimTime" /> 手动执行连续动画 public void startAnimation(Button button) { // Define the scale up animation Animation scaleUpAnimation = AnimationUtils.loadAnimation(this, R.anim.scale_up); // Define the scale down animation Animation scaleDownAnimation = AnimationUtils.loadAnimation(this, R.anim.scale_down); scaleUpAnimation.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { button.startAnimation(scaleDownAnimation); } @Override public void onAnimationRepeat(Animation animation) { } }); button.startAnimation(scaleUpAnimation); } 结果 但是,如果我尝试使用 AnimationSet 替换上述代码,动画结果就会损坏。 public void startAnimation(Button button) { // Define the scale up animation Animation scaleUpAnimation = AnimationUtils.loadAnimation(this, R.anim.scale_up); // Define the scale down animation Animation scaleDownAnimation = AnimationUtils.loadAnimation(this, R.anim.scale_down); // Create an AnimationSet to combine both animations // (It makes no difference whether I am using true or false) AnimationSet animationSet = new AnimationSet(true); animationSet.addAnimation(scaleUpAnimation); animationSet.addAnimation(scaleDownAnimation); // Apply the animation to the button button.startAnimation(animationSet); } 使用AnimationSet的结果(动画不流畅) 我可以知道为什么AnimationSet不起作用吗?谢谢。 我们需要使用setStartOffset来延迟第二个动画的执行。这是解决上述问题的完整代码片段。 public void startAnimation(Button button) { int config_shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime); // Define the scale up animation ScaleAnimation scaleUpAnimation = new ScaleAnimation( 1f, 1.02f, 1f, 1.02f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f ); scaleUpAnimation.setInterpolator(new DecelerateInterpolator()); scaleUpAnimation.setDuration(config_shortAnimTime); scaleUpAnimation.setFillAfter(true); // Define the scale down animation ScaleAnimation scaleDownAnimation = new ScaleAnimation( 1.02f, 1f, 1.02f, 1f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f ); scaleDownAnimation.setInterpolator(new AccelerateInterpolator()); scaleDownAnimation.setDuration(config_shortAnimTime); scaleDownAnimation.setFillAfter(true); scaleDownAnimation.setStartOffset(scaleUpAnimation.getDuration()); // Create an AnimationSet to combine both animations AnimationSet animationSet = new AnimationSet(false); animationSet.addAnimation(scaleUpAnimation); animationSet.addAnimation(scaleDownAnimation); // Apply the animation to the button button.startAnimation(animationSet); }


MVC ASP.NET Core Identity,创建登录、注册操作。 AuthController

公共类AuthController:控制器 { SignInManager _signInManager { 获取; } UserManager _userManager { 获取; } 角色管理器 public class AuthController : Controller { SignInManager<AppUser> _signInManager { get; } UserManager<AppUser> _userManager { get; } RoleManager<IdentityRole> _roleManager { get; } public AuthController(SignInManager<AppUser> signInManager, UserManager<AppUser> userManager, RoleManager<IdentityRole> roleManager) { _signInManager = signInManager; _userManager = userManager; _roleManager = roleManager; } public IActionResult Login() { return View(); } [HttpPost] public async Task<IActionResult> Login(string? returnUrl,LoginVM vm) { AppUser user; if (!ModelState.IsValid) { return View(vm); } if (vm.UsernameOrEmail.Contains("@")) { user = await _userManager.FindByEmailAsync(vm.UsernameOrEmail); } else { user = await _userManager.FindByNameAsync(vm.UsernameOrEmail); } if (user == null) { ModelState.AddModelError("", "Username or password is wrong"); return View(vm); } var result = await _signInManager.PasswordSignInAsync(user, vm.Password, vm.IsRemember, true); if (!result.Succeeded) { if (result.IsLockedOut) { ModelState.AddModelError("", "Too many attempts wait until " + DateTime.Parse(user.LockoutEnd.ToString()).ToString("HH:mm")); } else { ModelState.AddModelError("", "Username or password is wrong"); } return View(vm); } if (returnUrl != null) { return LocalRedirect(returnUrl); } return RedirectToAction("Index","Home"); } public IActionResult Register() { return View(); } [HttpPost] public async Task<IActionResult> Register(RegisterVM vm) { if (!ModelState.IsValid) { return View(vm); } var user = new AppUser { Fullname = vm.Fullname, Email = vm.Email, UserName = vm.Username }; var result = await _userManager.CreateAsync(user, vm.Password); if (!result.Succeeded) { foreach (var error in result.Errors) { ModelState.AddModelError("", error.Description); } return View(vm); } var roleResult = await _userManager.AddToRoleAsync(user, Roles.Member.ToString()); if (!roleResult.Succeeded) { ModelState.AddModelError("", "Something went wrong. Please contact admin"); return View(vm); } return View(); } public async Task<IActionResult> Logout() { await _signInManager.SignOutAsync(); return RedirectToAction("Index", "Home"); } public async Task<bool> CreateRoles() { foreach (var item in Enum.GetValues(typeof(Roles))) { if (!await _roleManager.RoleExistsAsync(item.ToString())) { var result = await _roleManager.CreateAsync(new IdentityRole { Name = item.ToString() }); if (!result.Succeeded) { return false; } } } return true; } } } 所以,我在代码中搞乱了登录、注册和注销,现在这个 RoleManager 的事情让我摸不着头脑。我只是想为我的管理员用户提供一些额外的权力,但我有点不知道该怎么做。如果您能用简单的语言解释步骤或需要进行哪些更改来帮助我,那就太棒了。 我的目标是让管理员用户在我的系统中体验更好,您对此的建议非常有用。尝试了解 RoleManager 的事情以及如何为我的管理员用户提供更多能力。您直接的帮助可能会对我解决这个问题产生很大的影响! 定义管理员角色 创建管理员用户 更新注册流程: var roleResult =等待_userManager.AddToRoleAsync(用户,vm.IsAdmin? Roles.Admin.ToString() : Roles.Member.ToString()); 使用管理员角色: [授权(角色=“管理员”)] 公共 IActionResult AdminDashboard() { // 特定于管理的逻辑 } 5.提升管理能力: if (User.IsInRole("管理员")) { // 特定于管理的逻辑 } 中间件配置: services.AddIdentity() .AddRoles() .AddEntityFrameworkStores(); 7.创建角色方法: 公共无效配置(IApplicationBuilder 应用程序,IHostingEnvironment env) { // 其他中间件配置 // Create roles during application startup var authController = new AuthController(/* inject your dependencies here */); authController.CreateRoles().GetAwaiter().GetResult(); }


声明一个带有泛型的函数,用作查找映射中的值

我做错了什么,但不确定是什么。 尝试制作一个查找地图,为我提供可以调用的功能。 简单演示一下问题: java public class aa { /** 没关系...


为什么我在GWT中无法隐藏UiBinder中的DialogBox?

在 Test.ui.xml 中 测试 一些小部件.. 在Test.ui.xml <g:DialogBox ui:field="wishlistDialogBox" autoHide="true"> <g:caption>Test</g:caption> <g:HTMLPanel> some widgets..</g:HTMLPanel> </g:DialogBox> 运行后,应用程序仍然显示DialogBox,所以我尝试在TestView.java中为“wishlistDialogBox”设置隐藏,但没有成功。 @UiField DialogBox wishlistDialogBox; @Inject public TestView(final Binder binder) { widget = binder.createAndBindUi(this); wishlistDialogBox.hide(); } 然后我在TestPresenter.java中为它设置了隐藏,但仍然不起作用 @Override protected void onBind() { super.onBind(); getView().getWishlistDialogBox().hide(); } 怎么了,古德尔根本没有解释。 另外,DialogBox如何重复使用? 当谈论将它们添加到 DOM 时,DialogBox(以及一般的 PopupPanel)不像任何其他小部件那样工作。您永远不应该像以前那样将它们直接附加到它(即 panel.add(yourDialogBox) 或在 UiBinder XML 文件中)。相反,您应该创建它们,然后简单地调用 hide()/show() 以及类似的方法,以使其显示/隐藏(即,在 DOM 的末尾附加/分离)。 对我有用的是与任何其他小部件分开创建一个对话框。所以它有自己的 Java 文件和自己的 ui.xml 文件: UiBinder xml文件: <ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder" xmlns:g="urn:import:com.google.gwt.user.client.ui"> <g:DialogBox ui:field="dialog"> <g:caption>My Dialog</g:caption> <g:HTMLPanel> <g:Button ui:field="closeButton" text="close" /> </g:HTMLPanel> </g:DialogBox> </ui:UiBinder> Java 文件: public class MyDialog { // here you do not inherit anything private static MyDialogUiBinder uiBinder = GWT.create(MyDialogUiBinder.class); interface MyDialogUiBinder extends UiBinder<Widget, MyDialog> { } @UiField DialogBox dialog; @UiField Button closeButton; public MyDialog() { // make cast to DialogBox dialog = (DialogBox) (uiBinder.createAndBindUi(this)); } public void hide() { dialog.hide(); } public void show() { dialog.center(); } @UiHandler("closeButton") public void onClick(ClickEvent event) { hide(); } } 最后我想出了一个办法,那就是把DialogBox放到一个看不见的HTMLPanel <g:HTMLPanel visible="false"> <g:DialogBox ui:field="wishlistDialogBox" autoHide="true"> <g:caption>Test</g:caption> <g:HTMLPanel> some widgets..</g:HTMLPanel> </g:DialogBox> </g:HTMLPanel> 然后像往常一样调用 show & hide DialogBox,即使 DialogBox 被包裹在一个看不见的 DialogBox 中,它也会显示 HTMLPanel。 getView().getWishlistDialogBox().show();


wkhtmltopdf 文档在开发与生产中的生成方式不同

以下用于生成 PDF 的布局设置为使用 Rails 应用程序的 asset/public 目录中的 css 文件,因为 wicked-pdf gem 需要静态链接。它会根据每个环境进行调整...


如何获取应用程序的屏幕空间或 MAUI 中顶部和底部栏的高度?

我在计算某些项目的位置时遇到问题,以及它们是否在 MAUI 的屏幕上可见,使用如下函数 public Point GetScreenCoords(VisualElement视图) { var 结果 = 新...


为什么FormData会导致400错误请求?

更新: 一些奇怪的行为。如果我发布到控制器,它就会工作并且我会获取文件和数据。但是,如果我发布到页面本身(Razor 代码后面) public void OnPost(...) 我收到 400 错误。是


资源提供的整数在运行时出现乱码

在我的 Android 应用程序中,我创建了文件 app/src/main/res/values/integers.xml: 在我的 Android 应用程序中,我创建了文件 app/src/main/res/values/integers.xml: <?xml version="1.0" encoding="utf-8"?> <resources> <integer name="server_port">8080</integer> </resources> 然后我就有了 public class MyApplication extends Application { final MyServer server = new MyServer(R.integer.server_port); } 但是,当应用程序启动时,日志语句显示该值(即 R.integer.server_port)为 2131296322。 为什么数值会出现乱码?这不是整数资源应该如何实现的吗? R.integer.server_port 给出整数的资源 ID,而不是整数本身。为了获得实际的整数,你必须做getResources().getInteger(R.integer.server_port)。但是,这需要对原始代码进行一些修改,因为在实例化 MyApplication 时尚未设置资源。相反,你可以这样做 public class MyApplication extends Application { MyServer server; @Override public void onCreate() { super.onCreate(); server = new MyServer(getResources().getInteger(R.integer.server_port)); } }


访问 ExpandoObject 中的动态视图

我有以下方法来创建这个 ExpandoObject: List 示例 = new List(); foreach(费率中的变量率) { varrateObject = new ExpandoObject() as IDictionar... 我有以下方法来创建这个ExpandoObject: List<object> example = new List<object>(); foreach (var rate in rates) { var rateObject = new ExpandoObject() as IDictionary<string, object>; rateObject["Id"] = rate.Id; rateObject["RateType"] = rate.RateType; rateObject["Units"] = rate.R6Item.Unit.Symbol; rateObject["Schedule"] = rate.R6Item.Schedule.Description; rateObject["R6Code"] = rate.R6Item.Code; rateObject["R6Description"] = rate.R6Item.Description; rateObject["R7Code"] = rate.R7Item.Code; rateObject["R7Description"] = rate.R7Item.Description; rateObject["DICODE"] = rate.R6Item.Schedule.Discipline.Code; foreach (var currency in rate.Project.ProjectCurrencies) { rateObject[currency.Currency.Name] = currency.Currency.Name; } example.Add(rateObject); } 现在,当我展开示例对象时,它看起来像这样: 如果我进一步扩展,就像这样: 现在我想要的数据是如何在动态视图中显示的,有没有办法能够访问它?并有与 ExpandoObject 的动态视图相同的示例? 您肯定可以做很多事情来增强您的调试体验。这是我的快速尝试: 我必须使用组合来扩展密封类ExpandoObject,其属性为: class MyExpando { [DebuggerBrowsable(DebuggerBrowsableState.Never)] public ExpandoObject Value { get; } = new(); [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public List<KeyValuePair<string, object?>> Properties => Value.ToList(); public void Add(string key, object value) => ((IDictionary<string, object?>)Value)[key] = value; public override string ToString() => string.Join(", ", Value.Select(o => $"{o.Key}={o.Value}")); } 有: 覆盖显示集合时使用的ToString()方法, 隐藏在调试器属性 Value 中以访问 ExpandoObject, 属性 Properties 用于在调试器 KeyValuePair 条目中可视化。


访问 Expando 对象内的动态视图

我有以下方法来创建这个expandoObject: List 示例 = new List(); foreach(费率中的变量率) { var 速率对象 = 新 我有以下方法来创建这个expandoObject: List<object> example = new List<object>(); foreach (var rate in rates) { var rateObject = new ExpandoObject() as IDictionary<string, object>; rateObject["Id"] = rate.Id; rateObject["RateType"] = rate.RateType; rateObject["Units"] = rate.R6Item.Unit.Symbol; rateObject["Schedule"] = rate.R6Item.Schedule.Description; rateObject["R6Code"] = rate.R6Item.Code; rateObject["R6Description"] = rate.R6Item.Description; rateObject["R7Code"] = rate.R7Item.Code; rateObject["R7Description"] = rate.R7Item.Description; rateObject["DICODE"] = rate.R6Item.Schedule.Discipline.Code; foreach (var currency in rate.Project.ProjectCurrencies) { rateObject[currency.Currency.Name] = currency.Currency.Name; } example.Add(rateObject); } 现在,当我展开示例对象时,它看起来像这样: 如果我进一步扩展,就像这样: 现在我想要的数据是如何在动态视图中显示的,有没有办法能够访问它?并有与 ExpandoObject 的动态视图相同的示例吗? 您肯定可以做很多事情来增强您的调试体验。这是我的快速尝试: 我必须使用组合来扩展密封类ExpandoObject,其属性为: class MyExpando { [DebuggerBrowsable(DebuggerBrowsableState.Never)] public ExpandoObject Value { get; } = new(); [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public List<KeyValuePair<string, object?>> Properties => Value.ToList(); public void Add(string key, object value) => ((IDictionary<string, object?>)Value)[key] = value; public override string ToString() => string.Join(", ", Value.Select(o => $"{o.Key}={o.Value}")); } 有: 覆盖显示集合时使用的ToString()方法, 隐藏在调试器属性 Value 中以访问 ExpandoObject, 属性 Properties 用于在调试器 KeyValuePair 条目中可视化和编辑。


使用php以动态形式考虑用户输入

考虑我有一个像这样的简单表格: 考虑我有一个像这样的简单表格: <form method="post" action="index.php"> <input id='textsearch' type="text" placeholder="Enter a character" name="search"> <button onclick="addfields()">Add</button> </form> 此处,当用户单击“添加”按钮时,会触发 onclick 事件并激活 addfields() 功能。在该函数中,我设法在此表单中添加一个输入字段,表单现在如下所示: <form method="post" action="index.php"> <input id='textsearch' type="text" placeholder="Enter a character" name="search"> <input id='textsearch_1' type="text" placeholder="Enter a character" name="search_1"> <button onclick="addfields()">Add</button> </form> 但是,出现了一个问题。如果我使用 php 来访问这些变量,我可以使用这样的东西: <?php $first_char=$_POST["search"]; $second_char=$_POST["search_1"]; ?> 但是它到哪里结束呢?我事先不知道用户创建了多少字段并在这些字段中输入了数据。那么有什么办法可以解决呢? 注意:我知道许多用户不赞成使用 onclick() 功能。我仍然坚持这个不好的使用习惯。对此表示歉意。谢谢。 你可以尝试这个概念 HTML 表单 <form method="post" action="index.php"> <input id='textsearch' type="text" name="search[]"> <input id='textsearch_1' type="text" name="search[]"> <button onclick="addfields()">Add</button> </form> PHP <?php $search_text_array=$_POST["search"]; print_r($search_text_array); ?> 你应该得到这个 PHP 结果 Array ( [0] => textsearch [1] => textsearch_1 ) 在此示例中,javascript 使用onclick() 不相关,但解释如何获取 PHP 部分


Velocity 在 Spring Boot 中找不到模板资源

我使用 Velocity 模板引擎在我的 Spring boot 应用程序中使用电子邮件模板发送电子邮件实用程序。 当前的代码如下所示。 pom.xml: 我正在使用 Velocity 模板引擎在我的 Spring boot 应用程序中使用电子邮件模板发送电子邮件实用程序。 当前代码如下所示。 pom.xml: <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity</artifactId> <version>1.7</version> </dependency> <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity-tools</artifactId> <version>2.0</version> </dependency> 速度引擎 bean 配置: @Configuration public class VelocityConfig { @Bean public VelocityEngine velocityEngine() { VelocityEngine ve = new VelocityEngine(); ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath"); ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName()); ve.init(); return ve; } } 电子邮件模板放置在 src/main/resources/email-templates/summary-email.vm <!DOCTYPE html> <head> <title>Summary</title> </head> <body> <h1>Claims Summary</h1> </body> </html> 放置在以下目录中: src ├── main │ ├── java │ │ └── com │ │ └── packageNameioot │ │ └── SpringBootApplication.java │ ├── resources │ │ ├── email-templates │ │ │ └── summary-email.vm │ │ └── application.properties 使用模板发送电子邮件的服务类: @Slf4j @Service @RequiredArgsConstructor public class EmailSummaryService { private final EmailConnector connector; private final VelocityEngine velocityEngine; public Mono<Void> sendFinanceClaimsRunEmailSummary(FinancePeriodRunEntity periodRunEntity, int successCount, int errorCount) { EmailDto emailDto = EmailDto.builder() .recipients(Set.of("[email protected]")) .subject("Claims summary") .body(createEmailBody()) .html(true) .build(); return connector.submitEmailRequest(emailDto); } private String createEmailBody() { VelocityContext context = new VelocityContext(); Template template = velocityEngine.getTemplate("email-templates/summary-email.vm"); StringWriter writer = new StringWriter(); template.merge(context, writer); return writer.toString(); } } 但是Velocity无法定位模板,出现以下错误。 ERROR velocity:96 - ResourceManager : unable to find resource 'email-templates/summary-email.vm' in any resource loader. org.apache.velocity.exception.ResourceNotFoundException: Unable to find resource 'email-templates/summary-email.vm' 属性应该这样设置: VelocityEngine ve = new VelocityEngine(); ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath"); ve.setProperty("resource.loader.classpath.class", ClasspathResourceLoader.class.getName()); 根据 Apache Velocity Engine 文档。


使用 Javascript 更改 HTML 中的文本

如何用 Javascript 替换 HTML 中的文本? 在下面的代码片段中,我需要将文本“作者说”替换为“关于作者”。 谢谢你! 如何用 Javascript 替换 HTML 中的文本? 在下面的代码片段中,我需要将文本“作者说”替换为“关于作者”。 谢谢! <div id="author-info"> <div class="author-image"> <a class="author-avatar" href="https://www.test.com"><img alt=""></a> </div> <div class="author_name_wrap"> <h4 class="author_name"><a href="https://www.test.com/author/">Author say</a></h4> <div class="author_socicons"></div> </div> </div> 要更改 html 标签的内容,请使用 innerHTML 属性: var h4 = document.getElementsByClassName("author_name")[0], target = h4.childNodes[0]; target.innerHTML = "About the author"; 这是代码: document.getElementById("id-of-element").innerHTML = "new text"; <!DOCTYPE html> <html> <body> <p id="id-of-element">This text will be replaced</p> </body> </html> 这非常简单,您只需使用innerText或textcontent,如下例所示 //textConent Method const authorName = document.querySelectorAll('author_name').textContent="Text Here" //innerText Method const authorName = document.querySelectorAll('author_name').innerText="Text Here" 如果您使用jQuery,您可以轻松更改。 $("h4.author_name a").text('关于作者'); 您可以在这里找到详细的文章


.NET MAUI、ios UseSafeArea 不工作 StackLayout、VerticalStackLayout 和 Grid

<?xml version="1.0" encoding="utf-8" ?> <ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="Test.Views.Activities.ActivityMapList" xmlns:maps="clr-namespace:Microsoft.Maui.Controls.Maps;assembly=Microsoft.Maui.Controls.Maps" xmlns:sensors="clr-namespace:Microsoft.Maui.Devices.Sensors;assembly=Microsoft.Maui.Essentials" xmlns:ios="clr-namespace:Microsoft.Maui.Controls.PlatformConfiguration.iOSSpecific;assembly=Microsoft.Maui.Controls" ios:Page.UseSafeArea="False" Shell.NavBarIsVisible="False" Style="{StaticResource Key=DefaultPage}"> <ContentPage.Content> <StackLayout> <maps:Map VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand"> <x:Arguments> <MapSpan> <x:Arguments> <sensors:Location> <x:Arguments> <x:Double>36.9628066</x:Double> <x:Double>-122.0194722</x:Double> </x:Arguments> </sensors:Location> <x:Double>0.01</x:Double> <x:Double>0.01</x:Double> </x:Arguments> </MapSpan> </x:Arguments> </maps:Map> </StackLayout> </ContentPage.Content> </ContentPage> StackLayout 或 Grid 内的地图控件,iOS 的 SafeArea 为 false,如图所示。 你有什么解决办法吗? 我需要在地图上使用网格或堆栈布局 默认情况下.NET MAUI 将考虑安全区域。所以使用特定于平台的UseSafeArea就是禁用安全区域。目前,将 UseSafeArea 设置为 false 不会改变行为(尽管应该如此),这是一个错误。另请参阅 MAUI github 上的问题:https://github.com/dotnet/maui/issues/5856 您还可以设置 IgnoreSafeArea 属性来实现相同的目的。但是,它不再在 .NET 7 中工作,请参阅以下问题:https://github.com/dotnet/maui/issues/12823 要解决您的问题,您需要将 IgnoreSafeArea="True" 添加到您的 Grid 或 StackLayout 并将 ios:Page.UseSafeArea="False" 添加到您的页面。这应该不是必需的,但这是对我有用的解决方法。 有关在 iOS 上禁用安全区域的文档可以在此处找到:https://learn.microsoft.com/en-us/dotnet/maui/ios/platform-specifics/page-safe-area-layout?view=net-毛伊岛-7.0 您可以设置 Page Padding 值来实现。在OnAppearing方法中,设置页面的safeInsets,如下代码: protected override void OnAppearing() { base.OnAppearing(); DeviceSafeInsetsService d = new DeviceSafeInsetsService(); double topArea = d.GetSafeAreaTop(); double bottomArea = d.GetSafeAreaBottom(); var safeInsets = On<iOS>().SafeAreaInsets(); safeInsets.Top = -topArea; safeInsets.Bottom = -bottomArea; Padding = safeInsets; } 要获取 topArea 和 bottomArea 值,您应该编写平台代码。答案末尾附有有关此内容的更详细教程。 首先你可以在Project文件夹中生成一个新的类文件并将其更改为部分类。生成两个部分方法。 public partial class DeviceSafeInsetsService { public partial double GetSafeAreaTop(); public partial double GetSafeAreaBottom(); } 然后在iOS平台生成部分文件并实现。该文件位于 Project/Platform/iOS 文件夹中,我想提一下的是,该文件是一个部分文件,因此命名空间应与上面的文件相同。生成此文件时,请删除命名空间中的 .Platforms.iOS 后缀。 public partial class DeviceSafeInsetsService { public partial double GetSafeAreaBottom() { if (UIDevice.CurrentDevice.CheckSystemVersion(11, 0)) { UIWindow window = UIApplication.SharedApplication.Delegate.GetWindow(); var bottomPadding = window.SafeAreaInsets.Bottom; return bottomPadding; } return 0; } public partial double GetSafeAreaTop() { if (UIDevice.CurrentDevice.CheckSystemVersion(11, 0)) { UIWindow window = UIApplication.SharedApplication.Delegate.GetWindow(); var TopPadding = window.SafeAreaInsets.Top; return TopPadding; } return 0; } } 更多信息,您可以参考如何在.NET MAUI中编写特定于平台的代码和MauiPlatformCode示例代码 希望它对你有用。


如何在 Xamarin Forms 中缩放 WebView?

我无法缩放 Xamarin.Forms 中的 Web 视图。下面是代码,请有人帮助我。谢谢 我无法缩放 Xamarin.Forms 中的 Web 视图。下面是代码,请有人帮助我。谢谢你 <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="highchart.MainPage"> <ScrollView> <WebView VerticalOptions="FillAndExpand" WidthRequest="80" HorizontalOptions="FillAndExpand"> <WebView.Source WebView.EnableZoomControls="true" WebView.ScalesPageToFit = "true"> <HtmlWebViewSource x:Name="HighChart"/> </WebView.Source> </WebView> </ScrollView> </ContentPage> 针对 Android 特定(在共享项目 [FORMS] 内) XAML 解决方案: <ContentPage ... xmlns:android="clr-namespace:Xamarin.Forms.PlatformConfiguration.AndroidSpecific;assembly=Xamarin.Forms.Core"> <WebView Source="https://www.xamarin.com" android:WebView.EnableZoomControls="true" android:WebView.DisplayZoomControls="true" /> C# 解决方案: using Xamarin.Forms.PlatformConfiguration; using Xamarin.Forms.PlatformConfiguration.AndroidSpecific; ... WebView.On<Android>().EnableZoomControls(true); WebView.On<Android>().DisplayZoomControls(true); 我在iOS上的Android上测试过,看来这个问题只出现在Android上。 您可以创建一个自定义渲染器来实现缩放功能,它在我这边工作得很好。 [assembly: ExportRenderer(typeof(WebView), typeof(CustomWebViewRenderer))] namespace PDFPOC.Droid { public class CustomWebViewRenderer : WebViewRenderer { public CustomWebViewRenderer(Context context) : base(context) { } protected override void OnElementChanged(ElementChangedEventArgs<WebView> e) { base.OnElementChanged(e); if (e.NewElement != null) { Control.Settings.AllowUniversalAccessFromFileURLs = true; Control.Settings.SetSupportZoom(true); Control.Settings.BuiltInZoomControls = true; Control.Settings.DisplayZoomControls = true; } } } }


Laravel 中的策略对我不起作用,这是我的代码

我无法让策略在我的 Laravel 项目中工作,我安装了一个新项目来从头开始测试,我有这个控制器: 我无法让策略在我的 Laravel 项目中工作,我安装了一个新项目来从头开始测试,我有这个控制器: <?php namespace App\Http\Controllers; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use App\Models\User; class UserController extends Controller { public function index() { $this->authorize('viewAny', auth()->user()); return response("Hello world"); } } 本政策: <?php namespace App\Policies; use Illuminate\Auth\Access\Response; use App\Models\User; class UserPolicy { public function viewAny(User $user): bool { return true; } } 这是我的模型 <?php namespace App\Models; // use Illuminate\Contracts\Auth\MustVerifyEmail; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; use Laravel\Sanctum\HasApiTokens; class User extends Authenticatable { use HasApiTokens, HasFactory, Notifiable; /** * The attributes that are mass assignable. * * @var array<int, string> */ protected $fillable = [ 'name', 'email', 'password', ]; /** * The attributes that should be hidden for serialization. * * @var array<int, string> */ protected $hidden = [ 'password', 'remember_token', ]; /** * The attributes that should be cast. * * @var array<string, string> */ protected $casts = [ 'email_verified_at' => 'datetime', 'password' => 'hashed', ]; } 我收到错误 403:此操作未经授权。我希望有人能帮助我解决我的问题。谢谢你 我也尝试过修改AuthServiceProvider文件,但没有任何改变。 必须在 App\Providers\AuthServiceProvider 中添加您的策略吗? protected $policies = [ User::class => UserPolicy::class ]; 您需要指定您正在使用的模型。具体来说,就是User。因此,传递当前登录的用户: $this->authorize('viewAny', auth()->user()); 此外,您正在尝试验证用户是否有权访问该页面。确保尝试访问该页面的人是用户,以便策略可以授权或不授权。 要在没有入门套件的情况下进行测试,请创建一个用户并使用它登录。 <?php namespace App\Http\Controllers; use Illuminate\Support\Facades\Auth; class UserController extends Controller { public function index() { $user = \App\Models\User::factory()->create(); Auth::login($user); $this->authorize('viewAny', auth()->user()); return response("Hello world"); } } 但是,如果您希望授予访客用户访问权限,您可以使用 ? 符号将 User 模型设为可选: public function viewAny(?User $user) { return true; }


如何使用 Bootstrap 5 将嵌入水平居中

我正在尝试使用上面的图像进行集中输入。我按照位置文档进行操作,但不知何故图像没有水平集中: 代码: 我正在尝试使用上面的图像进行集中输入。我按照位置文档进行操作,但不知何故图像没有水平集中: 代码: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Title --> <title>Title</title> <!-- Css --> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous"> </head> <body> <div class="container position-absolute top-50 start-50 translate-middle"> <embed class="logo" src="https://www.google.com.br/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png" alt="Logo"> <form action="/streams" method="POST"> <div class="input-group"> <input class="form-control border-danger border-5" type="text" aria-describedby="start-button"> <button class="btn btn-danger" type="submit" id="start-button">Click</button> </div> </form> </div> </body> </html> 我尝试手动执行此操作并使用 display flex,但没有成功。 使用text-center链接 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Title --> <title>Title</title> <!-- Css --> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous"> </head> <body> <div class="container text-center"> <embed class="logo " src="https://www.google.com.br/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png" alt="Logo"> <form action="/streams" method="POST"> <div class="input-group"> <input class="form-control border-danger border-5" type="text" aria-describedby="start-button"> <button class="btn btn-danger" type="submit" id="start-button">Click</button> </div> </form> </div> </body> </html>


© www.soinside.com 2019 - 2024. All rights reserved.