instruction
stringlengths
0
30k
I am building my first React site and having trouble understanding how to best layout pages and running into issues like this: **I have a cursor animation -- throughout the entire webpage, the cursor is a small circle, but when I hover over certain divs within components that make up each section of the page (hero, about, work, etc.), the circle grows.** Trouble is, because each of the effected divs are in a different component, the initial state (small circle) of the cursor resets on each section, making a weird experience and the circle has trouble following the cursor smoothly. So... **is the best way to set something like this up just to have the entire page as one big component?** Or is there a way to route things so that the animation is on the entire page but changes when hovered on certain sections? Am I missing something? For clarity, adding screenshots of how I have the page setup and some of the internal component code as well. [main page build in app.js](https://i.stack.imgur.com/xhrxI.png) [code used for the initial state of the cursor (small circle follow) within a section component](https://i.stack.imgur.com/ut3EL.png) [code used to grow the circle on hover of a div within the section component](https://i.stack.imgur.com/EKjTA.png) I've tried moving the initial state code to the app.js file, but then the hover effect doesn't work because the initial state and the hover state are being called up in different files. I've also tried adding the entire code to each section, but that doesn't work because the inital state has to reset in each section, so sometimes you see the 'small circle' twice on the page, etc.
Why is my pivot table not generating an id column?
|mysql|node.js|sequelize.js|
|c|pointers|segmentation-fault|gdb|
Hovering doesn't want to work by any way. Code Below: - ``` self.setStyleSheet(""" QMenuBar { background-color: white; color: black; border: 3px solid silver; font-weight: bold; font-size: 23px; } QMenuBar::item { background-color: white; border: 2px solid silver; } QMenuBar::item::selected { background-color: grey; } QLabel:hover { #I tried both QLabel and QWidgetAction background-color: grey; } """) ``` And here the QWidgetAction and QLabel below: - ``` self.Menu = QMenuBar(self) self.Menu.resize(self.width(), 40) self.Menu.move(0, 0) self.File = self.Menu.addMenu('File') self.FileNew = QWidgetAction(self.File) self.New = QLabel("New") self.New.setMouseTracking(True) self.New.setAlignment(QtCore.Qt.AlignCenter) self.New.setStyleSheet("border: 2px solid silver; background-color: white; color: black; padding: 4 4 4 4px") self.FileNew.setDefaultWidget(self.New) ``` I searched in many threads and docs abt :hover method and tried it but it didn't work for me. And when I hover with my mouse on the QWidgetAction it stills frozen.
QMainWindow(self).setStyleSheet(""" QWidgetAction:hover {...} """) in QMenuBar isn't working and doesn't want to hover
|python|pyqt5|hover|qlabel|qwidgetaction|
null
I have a set of buttons in a class, and I'm trying to run a function so a piece of HTML will change based on what button was pressed. How would I use if/else statement to change the outcome based on the id of the button? ``` document.querySelector(".pizza").addEventListener('click', function(){ if (document.getElementById("small").clicked == true) { Size_Price = 5; document.getElementById("head1").textContent = "Small"; } else if (document.getElementById("medium").clicked == true) { Size_Price = 10; document.getElementById("head1").textContent = "Medium"; } }) ``` This is what I've tried, to no avail.
I'm encountering difficulties with my Terraform configuration, utilizing Artifactory's terraform-backend repository as the backend for storing tfstates. Configuration Overview: Terraform Backend: **remote: Artifactory | repository type: terraform-backend** Terraform Version: **1.0.2** I would greatly appreciate any insights or guidance on how to effectively retrieve Terraform state or output from Artifactory in this specific scenario. Thank you in advance! I have explored two potential solutions to retrieve Terraform output from the state: **1st Solution:** Attempting to obtain the output directly from the remote state. **Problem:** I haven't found a corresponding Terraform command to achieve this. **2nd Solution:** Downloading the tfstate from the Artifactory terraform-backend repository locally and executing the command: `terraform output -state=terraform.tfstate output-1`. **Problem:** Downloading the file state.latest.json directly from the terraform-backend Artifactory results in a file containing state versions, rather than the expected tfstate content containing outputs.
How to handle an animation across multiple components on a page in React JS website
|reactjs|animation|tailwind-css|mouse-cursor|
null
|python|sql|dataframe|join|pyspark|
{"OriginalQuestionIds":[69326413],"Voters":[{"Id":6395627,"DisplayName":"Slaw"},{"Id":-1,"DisplayName":"Community","BindingReason":{"DuplicateApprovedByAsker":""}}]}
I am attempting to update a Square order from my app, but it's not working. I create the order, and initially, everything seems fine—it gives me a success response and shows up when I make an API call. However, when I try to update the order, for instance, changing the name from 'John' to 'Jan,' and press the update button, the response I receive from Square indicates success, but the values remain unchanged; the name is still 'John' instead of 'Jan'. ```swift @IBAction func ordersSaveBtn(_ sender: UIButton) { let numberOfRows = selectedItemTableView.numberOfRows(inSection: 0) if numberOfRows == 0 { CommonMethods.showAlert(title: "Error", message: "Please Add Items", view: self) } else if resultSearchController.isActive == true { self.searchActive = true self.dismiss(animated: true, completion: nil) } if (searchActive == true) || ((searchActive == false) && (dateLabelBtn.titleLabel?.text != "Date")) { if isCharge { //Checking to see if the order is being edited if isCharge == true then it is being edited let currentDate = Date() let dateString = "\(date)" let dateFormatter = DateFormatter() dateFormatter.dateFormat = "MMMM dd yyyy h:mm a" dateFormatter.locale = Locale(identifier: "en_US_POSIX") if let date = dateFormatter.date(from: dateString) { let isoDateFormatter = ISO8601DateFormatter() isoDateFormatter.formatOptions = [.withInternetDateTime] let pickupAt = isoDateFormatter.string(from: date) let displayName = "\(nameTextField.text ?? "")" let phoneNumber = "\(phoneTextField.text ?? "")" let email = "\(emailTextField.text ?? "")" let priceString = selectedItems.first?.price?.replacingOccurrences(of: "$", with: "").trimmingCharacters(in: .whitespaces) let priceS = priceString?.replacingOccurrences(of: ".", with: "") let price: Int? = Int(priceS ?? "") print("order Id \(orderId)") editSquareOrder(orderId: orderId, updatedOrder: [ "order": [ "line_items": selectedItems.map { [self] selectedItem in var itemData: [String: Any] = [ "quantity": "\(selectedItem.quantity ?? "")" , "base_price_money": [ "amount": price ?? 0, "currency": "USD" ], "modifiers": [ [ "base_price_money": [ "amount": price ?? 0, "currency": "USD" ], "name": selectedItem.variationName ?? "", ] ], "name": selectedItem.itemName ?? "", "variation_name": selectedItem.variationName ?? "", "item_type": "ITEM", ] if let sku = selectedItem.sku { itemData["metadata"] = ["sku": sku] } for i in selectedItems { print("selectedItems.isDone: ",i.isDone) itemData["metadata"] = ["isDone": i.isDone] } return itemData }, "location_id": "M58BD678K1HDZ", "customer_id": "0HR44FFEGH7DV8VHQK0NFPN3TG", "state": "OPEN", "fulfillments": [ [ "type": "PICKUP", "state": "PROPOSED", "placed_at": dateFormatter.string(from: currentDate), "pickup_details": [ "pickup_at": pickupAt, "recipient": [ "display_name": displayName, "phone_number": phoneNumber, "email_address": email ] ] ] ], "taxes": [ [ "uid": "ad24399a-3ef6-42fd-b73f-7e8f1555c045", "name": "PA Sales Tax", "percentage": "6.0", "type": "ADDITIVE", "applied_money": [ "amount": 0, "currency": "USD" ], "scope": "LINE_ITEM" ], ], "pricing_options": [ "auto_apply_discounts": true, "auto_apply_taxes": true ] ] ]){ error in if let error = error { print("Error deleting order: \(error)") } else { } } } else { print("invalid date") } } else { //If the order is not being edited it creates a new order self.createSquareOrder() } } else { CommonMethods.showAlert(title: "Error", message: "Please fill Add PickUp Date", view: self) } } func editSquareOrder(orderId: String, updatedOrder: [String: Any], completion: @escaping (Error?) -> Void) { let accessToken = "EAAAFOSqneaOJbzXjGTEaJ1G6MqvWGVlVmPdKSWwj_2yEiDZBhxeyUjfypfn01kT" let orderAPIURL = "https://connect.squareup.com/v2/orders/\(orderId)" let headers: HTTPHeaders = [ "Authorization": "Bearer \(accessToken)", "Content-Type": "application/json" ] Alamofire.request(orderAPIURL, method: .get, headers: headers).responseJSON { response in switch response.result { case .success(let value): if let jsonResponse = value as? [String: Any], let order = jsonResponse["order"] as? [String: Any], let version = order["version"] as? Int { print("OrginalVersion: ",version) var updatedOrderWithVersion = updatedOrder updatedOrderWithVersion["version"] = version print("versone: \(version)") // Update the order with the new data Alamofire.request(orderAPIURL, method: .put, parameters: ["order": updatedOrderWithVersion], encoding: JSONEncoding.default, headers: headers).responseJSON { response in switch response.result { case .success(let value): print("Update Order API Response: \(value)") // Handle success, call completion handler with nil error completion(nil) self.dismiss(animated: true, completion: nil) case .failure(let error): if let data = response.data { let errorResponse = try? JSONSerialization.jsonObject(with: data, options: []) print("Error updating order: \(error), Response: \(errorResponse ?? "N/A")") } else { print("Error updating order: \(error)") } // Call completion handler with error completion(error) } } } else { let error = NSError(domain: "SquareAPI", code: 0, userInfo: [NSLocalizedDescriptionKey: "Failed to parse order details or missing version"]) completion(error) } case .failure(let error): print("Error fetching order details: \(error)") completion(error) } } } ``` What could be the cause of this problem?
|swift|square|
To create a "backup" of a given table, you can simply run a query and then use ***SAVE RESULTS >> BigQuery Table*** to save to a new table. Now you have a "backup" and if something goes wrong you can restore from this new table. I think the following SQL statement might delete "old" rows for you: ```sql DELETE FROM your_dataset.your_table WHERE STRUCT(document_id, timestamp) NOT IN ( SELECT AS STRUCT document_id, MAX(timestamp) AS timestamp FROM your_dataset.your_table GROUP BY document_id ) ```
I created an array of structures data(1).field = 5; data(2).field = 3; data(3).field = -4; ... I would like to plot one of the fields by accessing something like: data(:).field I get the following error: > Expected one output from a curly brace or dot indexing expression, but there were 1000 results. Is it possible to get the data without using a loop?
Matlab arrayuy of structure
|matlab|matrix|structure|
I'm encountering slow performance when executing a simple `SELECT` query (`SELECT * FROM SampleData`) on a SQL Server database hosted on my local machine. The table contains around 1 million records. Despite the relatively straightforward query, it takes approximately 20 seconds to retrieve the results. However, the result set seems to be lazily loaded (the rows are dynamically added right after I click the execute button). What could be causing this, and what steps can I take to improve it? CREATE TABLE SampleData ( ID BIGINT NOT NULL, Name NVARCHAR(2000) NOT NULL, DataType VARCHAR(115) NOT NULL, DisplayName NVARCHAR(515) NOT NULL, Description VARCHAR(MAX), StartDate BIGINT NOT NULL DEFAULT 0, Status BIGINT DEFAULT 1, CreationTime BIGINT, PRIMARY KEY (ID) ) Thanks.
That is almost the same use-case given as example in the [documentation](https://docs.oracle.com/en/java/javase/22/docs/api/java.base/java/util/Map.html#computeIfAbsent(K,java.util.function.Function)) of `Map.computeIfAbsent()`, which is implemented by `ConcurrentHashMap`: > If the specified key is not already associated with a value (or is mapped to null), attempts to compute its value using the given mapping function and enters it into this map unless null (optional operation). > > ... The most common usage is to construct a new object serving as an initial mapped value or memoized result, as in: > > ... > > Or to implement a multi-value map, Map<K,Collection<V>>, supporting multiple values per key: > ````java > map.computeIfAbsent(key, k -> new HashSet<V>()).add(v); > ```` It can be changed to use an `ArrayList` instead of the `HashSet`: ````java Map<String,List<Integer>> map = new ConcurrentHashMap<>(); void insertVal(String key, int value) { map.computeIfAbsent(key, k -> new ArrayList<>()).add(value); } ````
|javascript|reactjs|spotify|
null
I have a C# game emulator which uses TcpListener and originally had a TCP based client. A new client was introduced which is HTML5 (web socket) based. I wanted to support this without modifying too much of the existing server code, still allowing `TcpListener` and `TcpClient` to work with web socket clients connecting. Here is what I have done, but I feel like I'm missing something, as I am not getting the usual order of packets, therefor handshake never completes. 1. Implement protocol upgrade mechanism public static byte[] GetHandshakeUpgradeData(string data) { const string eol = "\r\n"; // HTTP/1.1 defines the sequence CR LF as the end-of-line marker var response = Encoding.UTF8.GetBytes("HTTP/1.1 101 Switching Protocols" + eol + "Connection: Upgrade" + eol + "Upgrade: websocket" + eol + "Sec-WebSocket-Accept: " + Convert.ToBase64String( System.Security.Cryptography.SHA1.Create().ComputeHash( Encoding.UTF8.GetBytes( new Regex("Sec-WebSocket-Key: (.*)").Match(data).Groups[1].Value.Trim() + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" ) ) ) + eol + eol); return response; } This is then used like so: private async Task OnReceivedAsync(int bytesReceived) { var data = new byte[bytesReceived]; Buffer.BlockCopy(_buffer, 0, data, 0, bytesReceived); var stringData = Encoding.UTF8.GetString(data); if (stringData.Length >= 3 && Regex.IsMatch(stringData, "^GET")) { await _networkClient.WriteToStreamAsync(WebSocketHelpers.GetHandshakeUpgradeData(stringData), false); return; } 2. Encode all messages after switching protocol response public static byte[] EncodeMessage(byte[] message) { byte[] response; var bytesRaw = message; var frame = new byte[10]; var indexStartRawData = -1; var length = bytesRaw.Length; frame[0] = 129; if (length <= 125) { frame[1] = (byte)length; indexStartRawData = 2; } else if (length >= 126 && length <= 65535) { frame[1] = 126; frame[2] = (byte)((length >> 8) & 255); frame[3] = (byte)(length & 255); indexStartRawData = 4; } else { frame[1] = 127; frame[2] = (byte)((length >> 56) & 255); frame[3] = (byte)((length >> 48) & 255); frame[4] = (byte)((length >> 40) & 255); frame[5] = (byte)((length >> 32) & 255); frame[6] = (byte)((length >> 24) & 255); frame[7] = (byte)((length >> 16) & 255); frame[8] = (byte)((length >> 8) & 255); frame[9] = (byte)(length & 255); indexStartRawData = 10; } response = new byte[indexStartRawData + length]; int i, reponseIdx = 0; // Add the frame bytes to the reponse for (i = 0; i < indexStartRawData; i++) { response[reponseIdx] = frame[i]; reponseIdx++; } // Add the data bytes to the response for (i = 0; i < length; i++) { response[reponseIdx] = bytesRaw[i]; reponseIdx++; } return response; } Used here: public async Task WriteToStreamAsync(byte[] data, bool encode = true) { if (encode) { data = WebSocketHelpers.EncodeMessage(data); } 3. Decoding all messages public static byte[] DecodeMessage(byte[] bytes) { var secondByte = bytes[1]; var dataLength = secondByte & 127; var indexFirstMask = dataLength switch { 126 => 4, 127 => 10, _ => 2 }; var keys = bytes.Skip(indexFirstMask).Take(4); var indexFirstDataByte = indexFirstMask + 4; var decoded = new byte[bytes.Length - indexFirstDataByte]; for (int i = indexFirstDataByte, j = 0; i < bytes.Length; i++, j++) { decoded[j] = (byte)(bytes[i] ^ keys.ElementAt(j % 4)); } return decoded; } Which is used here private async Task OnReceivedAsync(int bytesReceived) { var data = new byte[bytesReceived]; Buffer.BlockCopy(_buffer, 0, data, 0, bytesReceived); var stringData = Encoding.UTF8.GetString(data); if (stringData.Length >= 3 && Regex.IsMatch(stringData, "^GET")) { await _networkClient.WriteToStreamAsync(WebSocketHelpers.GetHandshakeUpgradeData(stringData), false); return; } var decodedData = WebSocketHelpers.DecodeMessage(data); if (decodedData[0] == 60) { await OnReceivedPolicyRequest(); } else if (_networkClient != null) { foreach (var packet in DecodePacketsFromBytes(decodedData)) { _packetHandler.HandleAsync(_networkClient, packet); } } } For extra knowledge here is how I decode packets also: protected List<NetworkPacket> DecodePacketsFromBytes(byte[] packet) { if (packet.Length < _constants.FrameLengthByteCount || packet.Length > _constants.BufferByteSize - _constants.FrameLengthByteCount) { return new List<NetworkPacket>(); } using var reader = new BinaryReader(new MemoryStream(packet)); var packetLength = BinaryPrimitives.ReadInt32BigEndian(reader.ReadBytes(4)); var packetData = reader.ReadBytes(packetLength); using var br2 = new BinaryReader(new MemoryStream(packetData)); var packetId = BinaryPrimitives.ReadInt16BigEndian(br2.ReadBytes(2)); var content = new byte[packetData.Length - 2]; Buffer.BlockCopy(packetData, 2, content, 0, packetData.Length - 2); var packets = new List<NetworkPacket>(); if (reader.BaseStream.Length - 4 > packetLength) { var extra = new byte[reader.BaseStream.Length - reader.BaseStream.Position]; Buffer.BlockCopy(packet, (int)reader.BaseStream.Position, extra, 0, (int)(reader.BaseStream.Length - reader.BaseStream.Position)); packets.AddRange(DecodePacketsFromBytes(extra)); } packets.Add(new NetworkPacket(packetId, content)); return packets; }
I'm facing one problem with Hibernate logging. If I enable **org.hibernate.SQL** to debug I can see the native SQL statements in the defined logger. This works in every scenario but the one when the HQL has collections fetches. Digging the code I could find where the execution behaves differently and it might cause the issue. In class *org.hibernate.hql.internal.ast.QueryTranslatorImpl* there's the block if ( hasLimit && containsCollectionFetches() ) { boolean fail = session.getFactory().getSessionFactoryOptions().isFailOnPaginationOverCollectionFetchEnabled(); if (fail) { throw new HibernateException("firstResult/maxResults specified with collection fetch. " + "In memory pagination was about to be applied. " + "Failing because 'Fail on pagination over collection fetch' is enabled."); } else { LOG.firstOrMaxResultsSpecifiedWithCollectionFetch(); } RowSelection selection = new RowSelection(); selection.setFetchSize( queryParameters.getRowSelection().getFetchSize() ); selection.setTimeout( queryParameters.getRowSelection().getTimeout() ); queryParametersToUse = queryParameters.createCopyUsing( selection ); } else { queryParametersToUse = queryParameters; } When the execution get's in the *if ( hasLimit && containsCollectionFetches() )* then the Log of statement done in *org.hibernate.engine.jdbc.spi.SqlStatementLogger* doesn't work. This is the method where statements are logged @AllowSysOut public void logStatement(String statement, Formatter formatter) { if ( logToStdout || LOG.isDebugEnabled() ) { if ( format ) { statement = formatter.format( statement ); } if ( highlight ) { statement = FormatStyle.HIGHLIGHT.getFormatter().format( statement ); } } LOG.debug( statement ); if ( logToStdout ) { String prefix = highlight ? "\u001b[35m[Hibernate]\u001b[0m " : "Hibernate: "; System.out.println( prefix + statement ); } } and the statement that sometimes doesn't work is *LOG.debug( statement );* I inspected the LOG object and the logger and levels were correct (org.hibernate.SQL and DEBUG) Has anybody had a similar issue? It's not a blocking issue but for performance analysis is very useful to have the SQL statement, especially for cases with collection fetches. Many thanks for any help
Problems with Hibernate SQL statements logging
|spring-boot|hibernate-5.x|
I try to create a cron expression like this: every 15 minutes except on sunday from 16h to 18h. I have tried a few generators, but can't find the way to write the "except on sunday between 16h and 18h. Could someone help me or give me a ressource maybe ?
Cron expression with exception on a range time in a specific day
|cron|
You can use `readr::read_csv` with `col_names` and `col_select` arguments. ```r header <- c("A", "B", "C", "D") subset <- c("D", "B") readr::read_csv("sample_data.csv", col_names = header, col_select = any_of(subset)) # # A tibble: 3 × 2 # D B # <dbl> <dbl> # 1 4 2 # 2 8 6 # 3 12 10 ```
I am working on a virtualised data grid for my application. I use transform: translateY for the table offset on scroll to make table virtualised. I developed all the functionality in React 17 project, but when migrated to React 18 I found that the data grid behaviour changed for the worse - the data grid started to bounce on scroll. I prepared the minimal representing code extract, which shows my problem. To assure that the code is the same for React 17 and React 18, I change only the import of ReactDOM from 'react-dom/client' to 'react-dom' (which is of course incorrect, since the latter is deprecated) in my index.tsx file. React 18: ![enter image description here][1] This is the code: index.html ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Virtuailsed table</title> </head> <body> <noscript>You need to enable JavaScript to run this app.</noscript> <div id="root"></div> </body> </html> ``` index.js ``` // import ReactDOM from "react-dom"; import ReactDOM from "react-dom/client"; import { useState } from "react"; import "./styles.css"; let vendors = []; for (let i = 0; i < 1000; i++ ){ vendors.push({ id: i, edrpou: i, fullName: i, address: i }) } const scrollDefaults = { scrollTop: 0, firstNode: 0, lastNode: 70, }; function App() { const [scroll, setScroll] = useState(scrollDefaults); const rowHeight = 20; const tableHeight = rowHeight * vendors.length + 40; const handleScroll = (event) => { const scrollTop = event.currentTarget.scrollTop; const firstNode = Math.floor(scrollTop / rowHeight); setScroll({ scrollTop: scrollTop, firstNode: firstNode, lastNode: firstNode + 70, }); }; const vendorKeys = Object.keys(vendors[0]); return ( <div style={{ height: "1500px", overflow: "auto" }} onScroll={handleScroll} > <div className="table-fixed-head" style={{ height: `${tableHeight}px` }}> <table style={{transform: `translateY(${scroll.scrollTop}px)`}}> <thead style={{ position: "relative" }}> <tr> {vendorKeys.map((key) => <td>{key}</td>)} </tr> </thead> <tbody > {vendors.slice(scroll.firstNode, scroll.lastNode).map((item) => ( <tr style={{ height: rowHeight }} key={item.id}> {vendorKeys.map((key) => <td><div className="data">{item[key]}</div></td>)} </tr> ))} </tbody> </table> </div> </div> ); } // const rootElement = document.getElementById("root"); // ReactDOM.render(<App />, rootElement); const root = ReactDOM.createRoot( document.getElementById('root') ); root.render( <App /> ); ``` styles.css ``` * { padding: 0; margin: 0 } .table-fixed-head thead th{ background-color: white; } .row { line-height: 20px; background: #dafff5; max-width: 200px; margin: 0 auto; box-shadow: 0 0 1px 0 rgba(0, 0, 0, 0.5); } .data{ width: 150px; white-space: nowrap; overflow: hidden; margin-right: 20px; } ``` I have spent 1.5 day trying to find the reason why the table bounces on scroll in React 18 without result. BTW, overscroll-behaviour: none doesn`t work. [1]: https://i.stack.imgur.com/AHoNg.gif
I am trying to use the **Microsoft.Build** nuget package to: - open a solution - enumerate projects in it - discover the DLLs that are created. <sup>\<rant>Failure modes seem to be super-abundant, error messages are uninformative, documentation seems to be scarce and misdirected, and examples are outdated. After hours upon hours of troubleshooting in the dark, and solving issue after issue that popped up, I finally arrived at an "Internal MSBuild Error", which brings me to Stack Overflow.\</rant></sup> My "scratch" solution contains just one net8.0 project, as follows: <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>net8.0</TargetFramework> </PropertyGroup> <ItemGroup> <PackageReference Include="Microsoft.Build" Version="17.9.5" /> <PackageReference Include="Microsoft.Build.Utilities.Core" Version="17.9.5" /> </ItemGroup> </Project> This project contains just one source file, as follows: namespace ConsoleApp1; using System; using System.IO; using System.Collections.Generic; using Microsoft.Build.Construction; using Microsoft.Build.Definition; using Microsoft.Build.Evaluation; using Microsoft.Build.Evaluation.Context; class Program { static void Main( string[] args ) { Directory.SetCurrentDirectory( @"C:\" ); //ensure that the error we encounter further down is not due to the current directory msBuildApiTest( @"D:\Personal\MyVisualStudioSolution\Solution.sln" ); // <-- this fails msBuildApiTest( @"D:\Personal\scratch\scratch.sln" ); // <-- this would also fail } static void msBuildApiTest( string solutionFilePath ) { string msBuildExtensionsPath = @"C:\Program Files\dotnet\sdk\8.0.102"; string msBuildSdksPath = Path.Combine( msBuildExtensionsPath, "Sdks" ); Environment.SetEnvironmentVariable( "MSBuildSDKsPath", msBuildSdksPath ); //Prevents InvalidProjectFileException: The SDK 'Microsoft.NET.Sdk' specified could not be found. Environment.SetEnvironmentVariable( "MSBuildEnableWorkloadResolver", "false" ); //Prevents InvalidProjectFileException: The SDK 'Microsoft.NET.SDK.WorkloadAutoImportPropsLocator' specified could not be found. ProjectOptions projectOptions = new(); projectOptions.EvaluationContext = EvaluationContext.Create( EvaluationContext.SharingPolicy.Shared ); projectOptions.LoadSettings = ProjectLoadSettings.DoNotEvaluateElementsWithFalseCondition; projectOptions.GlobalProperties = new Dictionary<string, string>(); projectOptions.GlobalProperties.Add( "SolutionDir", Path.GetDirectoryName( solutionFilePath ) + "\\" ); //The trailing backslash is OF PARAMOUNT IMPORTANCE. projectOptions.GlobalProperties.Add( "MSBuildExtensionsPath", msBuildExtensionsPath ); //Prevents InvalidProjectFileException: The imported project "D:\Personal\scratch\ConsoleApp1\bin\Debug\net8.0\Current\Microsoft.Common.props" was not found. ProjectCollection projectCollection = new( ToolsetDefinitionLocations.Default ); SolutionFile solutionFile = SolutionFile.Parse( solutionFilePath ); foreach( ProjectInSolution projectInSolution in solutionFile.ProjectsInOrder ) { if( projectInSolution.ProjectType is SolutionProjectType.SolutionFolder or SolutionProjectType.SharedProject ) continue; Console.WriteLine( $"{projectInSolution.ProjectType}\t{projectInSolution.ProjectName}\t{projectInSolution.RelativePath}" ); Project project1 = Project.FromFile( projectInSolution.AbsolutePath, projectOptions ); // <-- this fails Project project2 = new( projectInSolution.AbsolutePath, projectOptions.GlobalProperties, "Current", projectCollection ); // <-- this would also fail } } } Either of the last two statements fails. The exception is a `Microsoft.Build.Exceptions.InvalidProjectFileException`. The message of the exception is as follows: > `The expression "[MSBuild]::GetTargetFrameworkIdentifier(net8.0)" cannot be evaluated.` > `MSB0001: Internal MSBuild Error: A required NuGet assembly was not found.` > `Expected Path: D:\Personal\scratch\ConsoleApp1\bin\Debug\net8.0` > `C:\Program Files\dotnet\sdk\8.0.102\Sdks\Microsoft.NET.Sdk\targets\Microsoft.NET.TargetFrameworkInference.targets` Notes: - The "Expected Path" (whatever that means) points to the output directory of my scratch solution, which makes no sense, because that's not the solution I am trying to parse, and I have not supplied Microsoft.Build with any path to my scratch solution. As a matter of fact, I even switch the current directory to `C:\` so as to make sure that the error is not due to that. - The `@"C:\Program Files\dotnet\sdk\8.0.102"` path works on my machine, you might have to change it for your machine. Automatic discovery would be nice, but it is beyond the scope of this scratch app. - The solution at "D:\Personal\MyVisualStudioSolution\Solution.sln" is the solution that I am trying to parse, consisting of many net8.0 C# projects and one net472 project. However, it does not matter, because I get the exact same failure when I point this simple scratch app to try to parse itself. The question is: Why is this failing, and what must I do to make it work?
In Rust, I have created a struct Foo. I now want to initialise that from a string using a macro, for example: create_struct!("Foo"); I am struggling to do this - any help would be hugely appreciated! Thanks. src/main.rs: pub struct Foo { } // Macro to initialize an instance of the struct with the given name macro_rules! create_task {($struct_name:literal) => {$struct_name {}}}; fn main() {let my_struct = create_struct!("Foo");} Output on compilation: error: macro expansion ignores token `{` and any following --> src/main.rs:8:26 | 8 | $struct_name {} | ^ ... 14 | let my_struct = create_struct!("Foo"); | --------------------- caused by the macro expansion here | = note: the usage of `create_struct!` is likely invalid in expression context
This may have to do with updates in the `scales`, `ggplot2` and/or `cowplot` packages. I would recommend updating all R packages you got to the newest version and trying this again. If this doesn't help, you may want to check out the `adjustedCurves` package, which offers similar functionality.
Your output: ```lang-none this is thread 1 this is thread 2 main exists thread 2 exists thread 1 exists thread 1 exists ``` Before I see that *"it prints "thread 1 exists" twice."*, I see that it prints after "main exists": This behavior can lead to unpredictable results. -- First, you should array your code: ```cpp #include <thread> #include <iostream> #include <future> #include <syncstream> void log(const char* str) { std::osyncstream ss(std::cout); ss << str << std::endl; } void worker1(std::future<int> fut) { log("this is thread 1"); fut.get(); log("thread 1 exists"); } void worker2(std::promise<int> prom) { log("this is thread 2"); prom.set_value(10); log("thread 2 exits"); } int main() { std::promise<int> prom; std::future<int> fut = prom.get_future(); // Fire the 2 threads: std::thread t1(worker1, std::move(fut)); std::thread t2(worker2, std::move(prom)); t1.join(); t2.join(); log("main exits"); } ``` Key points: * CRITICAL: Replace the `while` loop and `detach()` with `join()` in the `main()` to ensure that the main thread waits for all child threads to finish before exiting. * Dilute the `#include` lines to include only what's necessary - For better practice. * Remove unused variables - For better practice. * Remove the unused `using namespace` directive - For better practice. * In addition, I would also replace the `printf()` calls with `std::osyncstream`. [Demo][1] Now, the output is: ```lang-none this is thread 1 this is thread 2 thread 2 exits thread 1 exits main exits ``` -- If it is forbidden to use join(): ```cpp #include <thread> #include <iostream> #include <future> #include <syncstream> #include <mutex> #include <condition_variable> std::mutex mtx; std::condition_variable cv; uint8_t workers_finished = 0; // Counter for finished workers void log(const char* str) { std::osyncstream ss(std::cout); ss << str << std::endl; } void worker1(std::future<int> fut) { log("this is thread 1"); fut.get(); log("thread 1 exits"); std::lock_guard<std::mutex> lock(mtx); ++workers_finished; cv.notify_one(); // Signal main thread } void worker2(std::promise<int> prom) { log("this is thread 2"); prom.set_value(10); log("thread 2 exits"); std::lock_guard<std::mutex> lock(mtx); ++workers_finished; cv.notify_one(); // Signal main thread } int main() { std::promise<int> prom; std::future<int> fut = prom.get_future(); // Fire the 2 threads: std::thread t1(worker1, std::move(fut)); std::thread t2(worker2, std::move(prom)); t1.detach(); t2.detach(); { std::unique_lock<std::mutex> lock(mtx); while (workers_finished < 2) { cv.wait(lock); // Wait until notified (or spurious wakeup) } } log("main exits"); } ``` Now, the output is: ```lang-none this is thread 1 this is thread 2 thread 2 exits thread 1 exits main exits ``` [1]: https://onlinegdb.com/emrwNMgxA
I have some trouble re-building a PHP array. I need to change it for printing a table to a PDF doc with tfPDF Library. I tried it with foreach loops, array_walk, array_walk_recursive, array_chunk and array_slice - so far without success. This is my array $data: ``` Array ( [file_id] => 1394 [user_id] => 463466 [periode] => 2022 [costs] => 64.45 [values] => Array ( [457] => Array ( [1] => Array ( [data_id] => 1 [supplier_id] => 457 [costs1] => 1000 [costs2] => 100 [group_name] => 7% ) [140] => Array ( [data_id] => 140 [supplier_id] => 457 [costs1] => 2000 [costs2] => 50 [group_name] => 19% ) [197] => Array ( [data_id] => 197 [supplier_id] => 457 [costs1] => 3000 [costs2] => 300 [group_name] => special ) ) [430] => Array ( [490] => Array ( [data_id] => 490 [supplier_id] => 430 [costs1] => 500 [costs2] => 30 [group_name] => new 4 ) [552] => Array ( [data_id] => 552 [supplier_id] => 430 [costs1] => 7000 [costs2] => 250 [group_name] => new 5 ) ) [425] => Array ( [1106] => Array ( [data_id] => 1106 [supplier_id] => 425 [costs1] => 10 [costs2] => 4 [group_name] => new 6 ) ) ) ) ``` For the print function the follwing format would be the best: ``` $pdf->Row(array( "data_id \n" . "data_id \n" . "data_id", "supplier_id \n" . "supplier_id \n" . "supplier_id", "costs1 \n" . "costs1 \n" . "costs1", "costs2 \n" . "costs2 \n" . "costs2", "group_name \n" . "group_name \n" . "group_name", )); ``` So I need to change the $data to an array like this: ``` Array ( [file_id] => 1394 [user_id] => 463466 [periode] => 2022 [costs] => 64.45 [values] => Array ( [457] => Array ( [data_id] => 1, 140, 197 [supplier_id] => 457, 457, 457 [costs1] => 1000, 2000, 3000 [costs2] => 100, 50, 300 [group_name] => 7%, 19%, special ) [430] => Array ( [data_id] => 490, 552 [supplier_id] => 430, 430 [costs1] => 500, 7000 [costs2] => 30, 250 [group_name] => new 4, new 5 ) [425] => Array ( [data_id] => 1106 [supplier_id] => 425 [costs1] => 10 [costs2] => 4 [group_name] => new 6 ) ) ) ``` Can you help me? The last step would be the comma separation like this: ``` array_walk($data['values'], function (&$val) { $val[] = implode(", ", $val[]); }); ```
Rebuild an array in PHP: merge array elements and save them to comma separated values
|php|arrays|multidimensional-array|
null
**How do I change the appID based on a parameter passed on the command line when running Maestro tests?** I'm aware that it's possible to set the app ID for a maestro test suite based on an env variable (https://stackoverflow.com/questions/76103428/is-it-possible-to-run-a-single-maestro-flow-against-two-different-app-ids), but how can I programmatically set the appID based on a more simple flag as a parameter? I'd like to be able to run tests with either `maestro test . -e android` or `maestro test . -e iOS`, and for this I'd need to take that parameter and use it to work out the appID string programatically in javascript (I think?). I have a rough idea of the javascript code to do this (see below), but not sure how to pull the parameter for this: ``` output.result = function getAppId() { // Assuming parameters passed to Maestro can be accessed from command line arguments const args = process.argv; const isAndroid = args.includes("android"); // Default app ID let appId = "com.ios.appid"; // If 'android' parameter is present, change the app ID accordingly if (isAndroid) { appId = "com.android.appid"; } return appId; }; ```
How to programatically set appID for Maestro tests based on platform
|android|ios|gui-testing|maestro|
This question is (very) similar to [this post][1], but not a duplicate IMHO, because: - my setting is completely reproducible ( docker ) - I use `gem` to install everything explictly - I have a "non-rails-related" script to "prove" gem is "operational" - the mentioned question is "ancient" in internet time (nearly 8 years old) Here is the completely reproducible docker image of a REST API rails server: ```lang-dockerfile FROM ruby RUN apt-get update RUN apt-get install vim -y RUN gem install rails RUN rails new translator --api --skip-action-mailer --skip-active-record WORKDIR translator RUN gem install syntax_tree COPY routes.rb config COPY translator_controller.rb app/controllers COPY test.rb test.rb COPY primes.rb primes.rb EXPOSE 3000 ``` I build and run my docker image normally: ```bash $ docker build --tag host.front.rb --file Dockerfile . $ docker run -p 8012:3000 -d -t --name front.rb host.front.rb $ docker exec -it front.rb bash ``` First I make sure the `syntax_tree` gem is installed properly: ```bash $ cat test.rb # <----- independent test file require "json" require "syntax_tree" file = File.open('primes.rb') content = file.read file.close program = SyntaxTree.parse(content) puts JSON.dump(program) $ ruby test.rb | head -c 41 {"type":"program","location":[1,0,19,265] # <---- good ! ``` Then I verify I can reach my dockerized server: ```bash # on docker $ rails server -b 0.0.0.0 => Booting Puma => Rails 7.1.3.2 application starting in development < ... omitted for brevity ... > * Listening on http://0.0.0.0:3000 # my local machine $ curl -X POST -F "source=@primes.rb" http://127.0.0.1:8012/translator1 >> 247 $ stat --format=%n:%s primes.rb primes.rb:247 # <----- good ! ``` When I try my second endpoint (which `require`s the `syntax_tree`) it fails: ``` $ curl -X POST -F "source=@primes.rb" http://127.0.0.1:8012/translator2 {"status":500,...,"exception":"LoadError: cannot load such file -- syntax_tree ``` Here is my `translator_controller.rb`: ```ruby require "json" class TranslatorController < ApplicationController def post_handler_simple # get the sent file entity source = params["source"] # read ruby source code file = File.open(source.tempfile) content = file.read file.close # return content length -> works fine ! render plain: ">> #{content.length()}\n" end def post_handler # get the sent file entity source = params["source"] # read ruby source code file = File.open(source.tempfile) content = file.read file.close # this import doesn't work ... require "syntax_tree" # parse it program = SyntaxTree.parse(content) # return AST (json format) render plain: JSON.dump(program) end end ``` And here is my `routes.rb` for completeness ```ruby Rails.application.routes.draw do post "/translator1", to: "translator#post_handler_simple" post "/translator2", to: "translator#post_handler" end ``` [1]: https://stackoverflow.com/questions/38026572/installed-gem-cant-load-from-rails-controller
``` static ArrayList<Integer> LinearSearch(int[] arr,int index,int target) { ArrayList<Integer> iList = new ArrayList<>(); if(index == arr.length){ return iList; } if(arr[index] == target){ iList.add(index); } ArrayList<Integer> temp = LinearSearch(arr,index+1,target); iList.addAll(temp); return iList; } ``` above code is my instructors code i don't understand temp part how indexes adding to temp? example arr = 1,2,3,4,3 should it 4,2 but it returns 2,4 how is this possible i cant understand. what is going on stack anyone can help me understand. this is my code. I can understand this. we collect items. but i cant understand above code. ``` static ArrayList<Integer> LinearSearch(int[] arr,int index,int target) { ArrayList<Integer> iList = new ArrayList<>(); if(index == arr.length){ return iList; } iList = LinearSearch(arr,index+1,target); if(arr[index] == target){ iList.addFirst(index); } return iList; } ```
|java|recursion|
Try [this package][1]: final pngBytes = image.pngUint8List; or final bmpBytes = image.bmpUint8List; [1]: https://pub.dev/packages/flutter_image_converter
It seems you forgot to add permission to access network on release app. ``` <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> ``` Please add the permission and it will solve your current issue
{"Voters":[{"Id":2399035,"DisplayName":"Lelio Faieta"},{"Id":10952503,"DisplayName":"Elikill58"},{"Id":3315779,"DisplayName":"CerebralFart"}]}
Assuming collection type name is **state** and we want to get state by **name** field. > src/api/state/controllers/state.js 'use strict'; /** * state controller */ const { createCoreController } = require('@strapi/strapi').factories; module.exports = createCoreController('api::state.state', ({strapi})=> ({ async findOne(ctx) { const {slug} = ctx.params; const entity = await strapi.db.query('api::state.state').findOne({ where: {name: slug} }); return entity; } })); > src/api/state/routes/custom.js module.exports = { routes: [ { method: 'GET', path: '/states/:slug', handler: 'state.findOne', config: { auth: false } } ] } not modified the content in the file > src/api/state/routes/state.js 'use strict'; /** * state router */ const { createCoreRouter } = require('@strapi/strapi').factories; module.exports = createCoreRouter('api::state.state'); Now we can hit the API like this where "rajasthan" is the name of a state: http://localhost:1337/api/states/rajasthan
I have tried to isolate my problem in a very simple (and working) project. Let's say I have a simple model with 2 fields, and I have configured its properties and a PropertyChanged event. This is a simplified implementation of my model, **please notice the last method just gets a new client object from a list and returns it**: public class Clients : INotifyPropertyChanged { private long _Id = 0; public long Id { get { return this._Id; } set { this._Id = value; RaisePropertyChanged("Id"); } } private String _Name = string.Empty; public String Name { get { return this._Name; } set { if (value is null) this._Name = string.Empty; else this._Name = value; RaisePropertyChanged("Name"); } } public event PropertyChangedEventHandler? PropertyChanged; internal void RaisePropertyChanged(string name) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name)); } // Let's say this is a populated list with 100 clients with different ids and names public static List<Clients> clients = new List<Clients>(); // ...method for loading the list with DB data public static Clients? LoadClient(long id) { return clients.FirstOrDefault(x => x.Id == id); } } And I have a simple .xaml in order to display one client data (id and name...). Each UI control has a binding with the client property and the trigger for updating. I have also 2 configured buttons that will make changes to the client values: <TextBox x:Name="txtClientId" Text="{Binding Id, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"> </TextBox> <TextBox x:Name="txtClientName" Text="{Binding Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"> </TextBox> <Button Name="btnNext" Click="btnNext_Click">Next</Button> <Button Name="btnRandom" Click="btnRandom_Click">Random</Button> Now let's take a look to my .xaml.cs code. Here is the initializing and the code for the 2 buttons: One of them just **modify the client properties** in the DataContext object directly, and the other **just assign a new client object** to the DataContext client: public partial class ClientsPage : Page { private Models.Clients? client = null; public ClientsPage() { InitializeComponent(); // Load all clients data in Models.Clients.clients list... client = new Models.Clients(); DataContext = client; } private void btnNext_Click(object sender, RoutedEventArgs e) { client = Models.Clients.LoadClient(client.Id + 1); } private void btnRandom_Click(object sender, RoutedEventArgs e) { Random random = new Random(); client.Id = random.Next(999); client.Name = "RANDOM"; } } - When I set the DataContext, data is displayed correctly in the UI -> OK - When I make changes directly in the properties of the client object changes are reflected correctly in the UI -> OK - But... when I load a new client object, and assign it to the variable set as DataContext, the PropertyChanged event is not raised. Of course this situation can be solved by assigning property values insted of assigning a new object directly: private void btnNext_Click(object sender, RoutedEventArgs e) { Models.Clients newClient = Models.Clients.LoadClient(client.Id + 1); this.client.Id = newClient.Id; this.client.Name = newClient.Name; } But it is so tedious in a real project with many models and methods that can load/modify an object with a lot of fields. I'm looking for an easy/scalable way for making the PropertyChanged event fire when I asign a new object to the DataContext variable. If you need more detail of my code or have any question I'll be happy to ask.
Asigning an object to another doesn't raise PropertyChanged event in WPF
Create a struct from a string using a macro in Rust
|rust|macros|
null
Indeed, KeyboardAvoidingView is not always easy to handle. Here are a few ideas: 1. Try to use KeyboardAvoidingView without absolute positioning. If needed, wrap such view in another that uses `position: absolute`, but leave this one with relative positioning. 2. Try replacing `position` with `padding` or `height`, and see what works best for your scenario. I usually use `padding` for Android and `position` for iOS. 3. Check if `KeyboardAvoidingView` has been imported from the correct module. 4. Edit your question to include the `styles.container` styling so we can see weather it has any impact on the implementation
It runs tests at mvn clean package and tries to connect to the database, use `mvn clean package -DskipTests` command or click on icon with a crossed out circle in your IntelliJ IDEA maven plugin, it package you jar with skip test mode too
I'm trying to secure my ASP.NET Core 8 Web API with Keycloak. I've created a realm and an user with confidential access-type, so it needs a secret. Everything is well implemented I think, but when I try to make a request from Swagger UI, it gives me the following CORS error: > Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:7777/realms/dc2-local/protocol/openid-connect/auth?xxx (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 200. When I press the link it redirects correctly to the login page of keycloak and after that, I can make requests correctly without the CORS error, but the first request, when I need to authenticate myself, I get the error This is my CORS policy: builder.Services.AddCors(options => { options.AddDefaultPolicy(builder => { builder .AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader(); }); }); /*other code*/ app.UseRouting(); app.UseCors(); app.UseAuthentication(); app.UseAuthorization(); And this are my request headers: GET /realms/dc2-local/protocol/openid-connect/auth?xxx HTTP/1.1 Host: localhost:7777 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/115.0 Accept: application/json Accept-Language: pt-PT Accept-Encoding: gzip, deflate, br Origin: http://localhost:5055 Referer: http://localhost:5055/ DNT: 1 Connection: keep-alive Sec-Fetch-Dest: empty Sec-Fetch-Mode: cors Sec-Fetch-Site: cross-site In my Keycloak configuration, I have the following: - Web Origins: * - Valid redirect URIs: http://localhost:5055/*
Consider this simple code below When I parse the content and get the "txt" with `JSON.parse(e.data).choices[0].delta.content;` then it works fine if it is plain text. However, there are some simple HTML tags in the response like `<strong>` etc. which don't render as HTML in the browser. I don't know how to render it as it is. I realize that the chunks of data, when they arrive, may not have closing HTML tags in them and may also have incomplete HTML tags, but when the stream ends, then all is well usually. How do I ensure that the browser treats the "txt" content as HTML and not as text? The variable thisWebPath is well set and does get streamed data back in JSON Thanks in advance ``` function sendMsg(msg) { var formData = new FormData(); formData.append('msg', msg); formData.append('user_id', USER_ID); fetch(thisWebPath + '/send-message.php', {method: 'POST', body: formData}) .then(response => response.json()) .then(data => { let uuid = uuidv4() const eventSource = new EventSource(thisWebPath + `/event-stream.php?chat_history_id=${data.id}&id=${encodeURIComponent(USER_ID)}`); appendMessage(BOT_NAME, BOT_IMG, "left", "", uuid); const div = document.getElementById(uuid); eventSource.onmessage = function (e) { if (e.data == "[DONE]") { msgerSendBtn.disabled = false; document.getElementById("userSendButtonAV").value="Send"; var elemB = document.getElementById("userSendButtonAV"); elemB.value = "Send"; document.getElementById('userMessageAV').placeholder='Enter your message now...'; document.getElementById('userMessageAV').disabled = false; eventSource.close(); } else { //original code let txt = JSON.parse(e.data).choices[0].delta.content if (isJsonString(e.data)) { let txt = JSON.parse(e.data).choices[0].delta.content; if (txt !== undefined) { div.innerHTML += txt.replace(/(?:\r\n|\r|\n)/g, '<br>'); } } } }; eventSource.onerror = function (e) { var elemC = document.getElementById("userSendButtonAV"); elemC.value = "Send"; msgerSendBtn.disabled = false; document.getElementById('userMessageAV').placeholder='Enter your message now...'; document.getElementById('userMessageAV').disabled = false; //console.log(e); eventSource.close(); }; }) .catch(error => console.error(error)); } ``` I am expecting the text to be handled like HTML Edit: this is how I am currently adding the message ```` function appendMessage(name, img, side, text, id) { // Simple solution for small apps const msgHTML = ` <div class="msg ${side}-msg"> <!--- div class="msg-img" style="background-image: url(${img})"></div ---> <div class="msg-bubble"> <div class="msg-info"> <div class="msg-info-name">${name}</div> <div class="msg-info-time">${formatDate(new Date())}</div> </div> <div class="msg-text" id=${id}>${text}</div> </div> </div> `; if ( typeof(text) !== "undefined" && text !== null ) { msgerChat.insertAdjacentHTML("beforeend", msgHTML); msgerChat.scrollTop += 500; } } insertAdjacentText is a function, but that is even worse... it just writes out the entire text including the html code ```` Edited again: The entire new div gets inside a main tag such as ```` <main class="msger-chat"> </main> ```` And even that gets dynamically generated, along with a bunch of other stuff, which is why insertAdjacentHtml is used How can i simply append the content using innerHtml so that the new div that starts with the following gets added at the end of the "main" element"? ```` <div class="msg ${side}-msg"> ````
We are using Spring Cache abstration and Infinispan server as a remote cache in front of a slow service. I have two requirements: - I would like to create the caches implicitly if they don't exist yet on the remote Infinispan server during access time based on a cache configuration template known by the Infinispan server. - If the connection to the remote Infinispan server cannot be established I am ok to call the slow service behind it. Could you suggest how could I implement this? The built-in `@Cacheable` annotation does not have support for this. Should I use a custom annotation with an Aspect? For the second requirement within the Aspect I could handle the connection issue to remote Infinispan server.
|c#|wpf|data-binding|inotifypropertychanged|datacontext|
``` static ArrayList<Integer> LinearSearch(int[] arr,int index,int target) { ArrayList<Integer> iList = new ArrayList<>(); if(index == arr.length){ return iList; } if(arr[index] == target){ iList.add(index); } ArrayList<Integer> temp = LinearSearch(arr,index+1,target); iList.addAll(temp); return iList; } ``` above code is my instructors code i don't understand temp part how indexes adding to temp? example arr = 1,2,3,4,3 should it 4,2 but it returns 2,4 how is this possible i cant understand. what is going on stack anyone can help me to understand. this is my code. I can understand this. we collect items. but i cant understand above code. ``` static ArrayList<Integer> LinearSearch(int[] arr,int index,int target) { ArrayList<Integer> iList = new ArrayList<>(); if(index == arr.length){ return iList; } iList = LinearSearch(arr,index+1,target); if(arr[index] == target){ iList.addFirst(index); } return iList; } ```
Follow the steps as mentioned in this page on [official playwright site][1] Step 1 to 4 will help you running the first program even without opening any IDE and building your code. Once that works open the solution file/folder from the IDE rather than opening the file by clicking on it. [1]: https://playwright.dev/dotnet/docs/intro
Make sure the YAML indentation and format in the `parameters` section of your `SecretProviderClass` are correct. YAML is very sensitive to indentation, and even a small mistake can lead to parsing errors. You would find a similar error in [`Azure/secrets-store-csi-driver-provider-azure` issue 290](https://github.com/Azure/secrets-store-csi-driver-provider-azure/issues/290) for illustration. ```yaml apiVersion: secrets-store.csi.x-k8s.io/v1 kind: SecretProviderClass metadata: name: test-tls spec: provider: gcp secretObjects: - secretName: test-tls-csi type: kubernetes.io/tls data: - objectName: "testcert.pem" key: tls.key - objectName: "testcert.pem" key: tls.crt parameters: secrets: | - resourceName: "projects/${PROJECT_ID}/secrets/test_ssl_secret/versions/latest" fileName: "testcert.pem" ``` The `resourceName`/`fileName` in the `parameters` section are properly indented as a part of the list under `secrets`.
Requirements(reverse engineered from the question): - the body of the loop knows which iteration it is for self and all parents - the number of loops is between 0 and at least hundreds - memory allocation is no problem i.e. no attempt at limiting it via compartmentalization is required - manual termination of current(but not parent) loop is available - loop counters are int and count upwards from zero - no code is executed except in the leaf loop - recursion not compulsory Here's a stab to try to get the idea across, will try compiling it upon interest. Again : **does not work as currently is**. using Counter = int; using State = std::vector<Counter>; using Condition = std::function<bool(const State &)>; using Action = std::function<void(const State &)>; void run(const std::vector<Condition> & conditions, Action action) { std::vector<Counter> state(conditions.size(), 0); unsigned depth{}; while(depth < conditions.size() && ! conditions[conditions.size()-1-depth]) { if(conditions[conditions.size()-1-depth](state)) { action(state); } else { // Go up the stack of loops. while(depth++ < state.size()) { state[state.size()-1-depth] = 0 ++state[state.size()-2-depth]; } } } }
rails import / require mechanism fails
|ruby-on-rails|rubygems|
I assume your question is "why **doesn't** this crash when the run is short?" This code should definitely crash in the general case since it tries to write an array of CGPoints into space allocated for a single CGPoint. This corrupts other memory and crashes. Classic buffer overflow. But as to why in some cases it doesn't crash, it depends heavily on what comes immediately after `truncationPosition` in memory. The memory you corrupt may not have anything in it. It may have something in it that doesn't "matter." It may be empty due to alignment requirements. The larger the overflow, the more likely you'll run into something important or smash the stack itself. But the short answer is that writing beyond your buffer is undefined behavior, and the system does not promise it will crash. Often it will, but often it may just do strange things or even "work." What happens can change between OS versions, and even between runs of the same code on the same version.
null
Found a number of issues here: First, range in line 25 is calling a sheet, not a range of cells. I have changed it to `e.range` to call on the event object. Also, I believe you have to use an installable onEdit trigger to utilize the mail service. I changed the name of your function from `onEdit` to `onMyEdit` and set up an onEdit trigger. [![Screenshot1][1]][1] [![Screenshot2][2]][2] [![Screenshot3][3]][3] Second there are some misspellings: First, `senEmail()` in line 4 and line 23. Doesn't matter if you don't call that function but you do in the last line of your code. Second, `getRagne()` in line 37 and line 38. Additionally, I got the following error after these corrections had been made: > Exception: The parameters (String,String,String,String,String) don't > match the method signature for MailApp.sendEmail. I combined messageBody, messageBody2, and respondent to bring it in line with the method signature. Lines 34 through Lines 39 need to have `getValue()` to get the cell values displayed in your HTML. Finally, you have name and email calling on the same cell. I changed the name to Column 3, but if this assumption is incorrect it can easily be modified. These changes are reflected in the code below: function onMyEdit(e) { addTimeStamp(e); sendEmail(e); } function addTimeStamp(e){ var sheet = SpreadsheetApp.getActive().getSheetByName("Sheet5") ; var range = e.range; var row = range.getRow(); var col = range.getColumn(); var cellValue = range.getValue(); if (col == 9 && cellValue === true){ sheet.getRange(row,10).setValue(new Date()); } } function sendEmail(e){ var sheet = SpreadsheetApp.getActive().getSheetByName("Sheet5") ; var range = e.range; var row = range.getRow(); var col = range.getColumn(); let cellValue = range.getValue(); // The value of the edited cell // Check if the edit occurred in column 5 and the value is true if (col == 9 && cellValue === true) { let email = sheet.getRange(row, 2).getValue(); let name = sheet.getRange(row, 3).getValue(); let orderID = sheet.getRange(row, 5).getValue(); let orderDate =sheet.getRange(row, 1).getValue(); let methodOfPayment = sheet.getRange(row, 4).getValue(); let numberOfTickets = sheet.getRange(row, 6).getValue(); let payableTotal = sheet.getRange(row, 7).getValue(); let html_link ="https://checkout.payableplugins.com/order/"+orderID; const subject = "PHLL Raffle Fundraiser Follow-Up on Order ID #" + orderID ; const messageBody = 'Dear ' + name + ',' + "\n\n" + 'We hope this message finds you well. We wanted to remind you that we have received your order information for the raffle ticket. According to our records, you have selected the cash method for payment, but we have not yet received the payment.' + "\n\n" + 'If you have already provided the payment to the player, please let us know as soon as possible. This will allow us to coordinate with them to ensure that your payment is collected and your raffle ticket is processed accordingly.' + "\n\n" + 'However, if you have not yet provided the payment to the player, we kindly ask you to do so at your earliest convenience. Once the payment is received, we will promptly send you your raffle ticket.' + "\n\n" + 'Please note that if payment is not received within the specified timeframe, we will have to remove your name from the drawing.' + "\n\n" + 'If you wish to change your method of payment, you may do so by following this link: ' + html_link + ' Should you have any further questions or concerns, please do not hesitate to reach out to us. We are here to assist you in any way we can.' + "\n\n" + 'Best of luck in the raffle drawing!' + "\n\n" + 'Warm regards,' + "\n" + 'Treasurer,' + "\n" + 'EmailAddress' + "\n" + 'Paradise Hills Little League' + "\n\n" + 'ORDER DETAILS' + "\n\n" + 'ORDER DATE: ' + orderDate +"\n" + 'ORDER ID #' + orderID +"\n" + 'METHOD OF PAYMENT: ' + methodOfPayment + "\n" + 'NUMBER OF TICKETS: ' + numberOfTickets +"\n" +'PAYABLE TOTAL: ' + payableTotal; MailApp.sendEmail(email,subject,messageBody); console.log(sendEmail) } } Note: you cannot run this code from the script editor. There needs to be an event object for the script to run. You will need to test it from the spreadsheet itself. If this is not working for you, let me know. [1]: https://i.stack.imgur.com/uv2Fy.png [2]: https://i.stack.imgur.com/F9oaO.png [3]: https://i.stack.imgur.com/eP4uh.png
I have a web route in my laravel project, and in that web route currently I'm calling an Artisan command I have defined in `app/Console/Commands`. I'm doing `Artisan::call(command)`. So, it's my understanding first of all that when I call it like that, my web request will wait for that to complete before it continues into the next bit of code, is that right? Does it wait for `Artisan::call` to complete? I would like a solution that doesn't wait, and I have one potential workaround, but before I use my workaround, I want to make sure `Artisan::callSilent()` doesn't do what I want it to do. If I use `callSilent` instead, will that run the artisan command in the backround without blocking the rest of the web request process?
Slightly confused about what Artisan::callSilent does
|laravel|laravel-artisan|
After few months of exploring options. I found solutions. 1) There is no way to choose other than "AzDevOps" user for Azure DevOps agents running in interactive mode on Azure VMSS instances. But I could configure new user called "AzDevOps" in the base gallery image and add required licenses to that user account. 2) I had to add a custom extension to the VMSS which would change "AzDevOps" account password to a known password after each instance is created, because pipeline generates a random password by default. Also, Test Execute has its tool "SessionCreator" which can create a specific sessions with specified user config per test run and evade this issue with AzDevOps account.
Thanks! I added something to it so that all sublabels are displayed function getAllLabels(){ var results = []; var labels = GmailApp.getUserLabels(); for (var i = 0; i < labels.length; i++) { Logger.log(" Label: " + labels[i].getName()); results.push(labels[i].getName()); } for (var i = 0; i < results.length; i++) { if(results[i].indexOf('/')>0){Logger.log('️ Sub Label: '+results[i])}; } } function processSubLabels(label, prefix) { var subLabels = label.getLabels(); for (var i = 0; i < subLabels.length; i++) { var subLabelName = prefix + "/" + subLabels[i].getName(); Logger.log("subLabel: " + subLabelName); processSubLabels(subLabels[i], subLabelName); } }
![Unwanted text on icon][1] I created a return icon while designing, but this text appeared on it. What is this text and how do I solve this? There does not seem to be an error in my code, I searched the internet but could not find any results.I don't know how to investigate. ``` Container( alignment: Alignment.center, // back icon height: Get.height * 0.0494, width: Get.width * 0.1, decoration: BoxDecoration( color: const Color(0xff2a2a2a), borderRadius: BorderRadius.circular(10), ), child: SuperTextIconButton( 'Back', onPressed: () => Get.back(), getIcon: Icons.arrow_back_ios_new, buttonColor: const Color(0xff7ED550), ), ) ``` [1]: https://i.stack.imgur.com/V1z9V.png
null
This is my predictive modeling code for fraud detection on the AML dataset ``` import torch import torch.nn as nn import torch.utils.data as Data import pandas as pd import numpy as np from sklearn.metrics import accuracy_score, recall_score, precision_score, f1_score, confusion_matrix from sklearn.utils.class_weight import compute_class_weight from imblearn.over_sampling import SMOTE class MyDataset(Data.Dataset): def __init__(self, file_path): df = pd.read_csv(file_path) X = df.values[:, :-1] y = df.values[:, -1] smote = SMOTE() X_resampled, y_resampled = smote.fit_resample(X, y) self.X = torch.tensor(X_resampled, dtype=torch.float32) self.y = torch.tensor(y_resampled, dtype=torch.long) def __len__(self): return len(self.X) def __getitem__(self, index): return self.X[index], self.y[index] class MLP(nn.Module): def __init__(self, input_size, hidden_size, num_classes): super(MLP, self).__init__() self.fc1 = nn.Linear(input_size, hidden_size) self.relu = nn.ReLU() self.fc2 = nn.Linear(hidden_size, num_classes) def forward(self, x): out = self.fc1(x) out = self.relu(out) out = self.fc2(out) return out def calculate_metrics(predictions, targets): accuracy = accuracy_score(targets, predictions) recall = recall_score(targets, predictions) precision = precision_score(targets, predictions) f1 = f1_score(targets, predictions) cm = confusion_matrix(targets, predictions) return accuracy, recall, precision, f1, cm # Define the training function def train(train_loader, val_loader, model, criterion, optimizer, num_epochs): for epoch in range(num_epochs): model.train() for i, (inputs, labels) in enumerate(train_loader): outputs = model(inputs) loss = criterion(outputs, labels) optimizer.zero_grad() loss.backward() optimizer.step() model.eval() with torch.no_grad(): val_predictions = [] val_targets = [] for inputs, labels in val_loader: outputs = model(inputs) _, predicted = torch.max(outputs.data, 1) val_predictions.extend(predicted.tolist()) val_targets.extend(labels.tolist()) val_predictions = np.array(val_predictions) val_targets = np.array(val_targets) accuracy, recall, precision, f1, cm = calculate_metrics(val_predictions, val_targets) print('Epoch [{}/{}], Validation Accuracy: {:.2f}%, Recall: {:.2f}, Precision: {:.2f}, F1 Score: {:.2f}' .format(epoch + 1, num_epochs, accuracy * 100, recall, precision, f1)) print('Confusion Matrix:\n', cm) file_path = 'D:/Program Files/JetBrains/Finance/AML/transactions_processed.csv' dataset = MyDataset(file_path) train_dataset = [] val_dataset = [] test_dataset = [] for i in range(len(dataset)): x, y = dataset[i] timestamp = x[-2] threshold_train = 119 threshold_val = 159 if timestamp < threshold_train: train_dataset.append((x, y)) elif threshold_train <= timestamp < threshold_val: val_dataset.append((x, y)) else: test_dataset.append((x, y)) train_dataset = Data.TensorDataset(torch.stack([sample[0] for sample in train_dataset]), torch.tensor([sample[1] for sample in train_dataset])) val_dataset = Data.TensorDataset(torch.stack([sample[0] for sample in val_dataset]), torch.tensor([sample[1] for sample in val_dataset])) test_dataset = Data.TensorDataset(torch.stack([sample[0] for sample in test_dataset]), torch.tensor([sample[1] for sample in test_dataset])) train_loader = Data.DataLoader(dataset=train_dataset, batch_size=64, shuffle=True) val_loader = Data.DataLoader(dataset=val_dataset, batch_size=64, shuffle=False) test_loader = Data.DataLoader(dataset=test_dataset, batch_size=64, shuffle=False) model = MLP(input_size=7, hidden_size=64, num_classes=2) criterion = nn.CrossEntropyLoss() optimizer = torch.optim.Adam(model.parameters(), lr=0.001) train(train_loader, val_loader, model, criterion, optimizer, num_epochs=10) model.eval() with torch.no_grad(): test_predictions = [] test_targets = [] for inputs, labels in test_loader: outputs = model(inputs) _, predicted = torch.max(outputs.data, 1) test_predictions.extend(predicted.tolist()) test_targets.extend(labels.tolist()) test_predictions = np.array(test_predictions) test_targets = np.array(test_targets) # Calculate metrics for the test set accuracy, recall, precision, f1, cm = calculate_metrics(test_predictions, test_targets) print('Test Accuracy: {:.2f}%, Recall: {:.2f}, Precision: {:.2f}, F1 Score: {:.2f}' .format(accuracy * 100, recall, precision, f1)) print('Confusion Matrix:\n', cm) ``` Here's my output: Epoch [1/10], Validation Accuracy: 97.14%, Recall: 0.94, Precision: 1.00, F1 Score: 0.97 Confusion Matrix: [[266144 0] [ 14861 238894]] Epoch [2/10], Validation Accuracy: 83.31%, Recall: 1.00, Precision: 0.75, F1 Score: 0.85 Confusion Matrix: [[179397 86747] [ 0 253755]] Epoch [3/10], Validation Accuracy: 90.43%, Recall: 0.80, Precision: 1.00, F1 Score: 0.89 Confusion Matrix: [[266144 0] [ 49763 203992]] Epoch [4/10], Validation Accuracy: 99.66%, Recall: 1.00, Precision: 0.99, F1 Score: 1.00 Confusion Matrix: [[264383 1761] [ 0 253755]] Epoch [5/10], Validation Accuracy: 93.68%, Recall: 1.00, Precision: 0.89, F1 Score: 0.94 Confusion Matrix: [[233307 32837] [ 0 253755]] Epoch [6/10], Validation Accuracy: 98.91%, Recall: 0.98, Precision: 1.00, F1 Score: 0.99 Confusion Matrix: [[266144 0] [ 5681 248074]] Epoch [7/10], Validation Accuracy: 99.16%, Recall: 0.98, Precision: 1.00, F1 Score: 0.99 Confusion Matrix: [[266144 0] [ 4360 249395]] Epoch [8/10], Validation Accuracy: 99.78%, Recall: 1.00, Precision: 1.00, F1 Score: 1.00 Confusion Matrix: [[266144 0] [ 1121 252634]] Epoch [9/10], Validation Accuracy: 99.97%, Recall: 1.00, Precision: 1.00, F1 Score: 1.00 Confusion Matrix: [[266144 0] [ 147 253608]] Epoch [10/10], Validation Accuracy: 100.00%, Recall: 1.00, Precision: 1.00, F1 Score: 1.00 Confusion Matrix: [[266144 0] [ 0 253755]] Test Accuracy: 99.97%, Recall: 1.00, Precision: 1.00, F1 Score: 1.00 Confusion Matrix: [[272648 0] [ 155 295508]] I'm trying to figure out why FP and FT are rotating to 0?
Why does my confusion matrix look like this?
|python|confusion-matrix|
null
I have a Firefox extension that for certain pages listens to the [`webRequest.onHeadersReceived`][1] for specific URLs that it opens in order to remove the "content-disposition" header when it contains "attachment". That way some content is shown in the browser rather than downloaded as a file. When the extension opens the URL in a new tab, it works fine; the listener is called and I can modify the headers. But, if I instead open the URL in the currently active tab, it seems the background script gets terminated and the listener is never called. **Is there a way to prevent the background script from terminating, or am I doing something wrong to cause this?** From a content script a message is sent containing a URL, e.g. for an image, to open. The background script: ```lang-ts // background.ts browser.runtime.onMessage.addListener(handleMessage); function handleMessage(message: IMessage, sender: browser.runtime.MessageSender, sendResponse: (response?: any) => void) { const command = message.command; switch (command) { case "OPEN_IMAGE": { const { url, focusTab, newTab } = message.data; return openImage(url, focusTab, newTab); } // other cases... } } async function openImage(url: string, shouldFocus: boolean, newTab: boolean) { let tab: browser.tabs.Tab; if (newTab) { // This branch works as expected. The URL is loaded (below) and the image // is shown rather than downloaded as a file. tab = await browser.tabs.create({ active: shouldFocus }); } else { // Using this tab to load the URL into doesn't work. The image is downloaded // as a file, rather than shown in the tab. const activeTabs = await browser.tabs.query({ active: true, currentWindow: true }); tab = activeTabs[0]; } requestHandler.startListening(url); await browser.tabs.update(tab.id!, { url, loadReplace: newTab }); } ``` Inside `requestHandler.startListening` this is what happens: ```lang-ts class RequestHandler { private readonly _urlsToListenFor: string[] = []; public startListening = (url: string) => { console.log("added"); this._urlsToListenFor.push(url); // I've already checked no listener is added before this browser.webRequest.onHeadersReceived.addListener( this.onHeadersReceived, { urls: ["*://*/*"], types: ["main_frame"] }, ["responseHeaders", "blocking"]); }; private onHeadersReceived = (details: browser.webRequest._OnHeadersReceivedDetails) => { const listenerIndex = this._urlsToListenFor.indexOf(details.url); if (listenerIndex === -1) return; console.log("removed"); this._urlsToListenFor.splice(listenerIndex, 1); return this.getBlockingResponse(details); }; private getBlockingResponse = (details: browser.webRequest._OnHeadersReceivedDetails) => { // Make sure the image is opened in the browser rather than downloaded const contentDispIndex = details.responseHeaders ?.findIndex(h => h.name.toLowerCase() === "content-disposition" && h.value!.toLowerCase().startsWith("attachment")); return { responseHeaders: details.responseHeaders! .filter((_, index) => index !== contentDispIndex) }; }; } console.log("new RequestHandler"); export default new RequestHandler(); ``` Given the `console.log` statements, this is what I see in the console: ```lang-none // newTab === true added removed // newTab === false added new RequestHandler ``` [1]: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/webRequest/onHeadersReceived
|java|visual-studio-code|
Is there a way to play a notification sound as fast as a button click? I feel like there is a delay of a few hundred milliseconds! I'm using this: ``` public void btn_Click(object sender, eventargs e) { playExclamation(); } public void playExclamation() { SystemSounds.Exclamation.Play(); } ```
My goal is to have *select* (dropdowns) handled by [custom-select][1] js library for blocks in **Wagtail Stream Field**. As it is quite easy to add for normal fields when event `DOMContentLoaded` is triggered. But is there any ***event*** or ***hook*** for adding a *block* to **StreamField**? I tried even calling my function in html template for block. But it seems to be called too early because styles are not applied to selects in this html. this is my `.js` *(typescript)* const initColorChoosers = () => { const colorChoosers = Array.from(document.querySelectorAll('.color-chooser select')) as HTMLSelectElement[]; colorChoosers.forEach((chooser) => { if (!chooser.hasAttribute('custom')) { chooser.setAttribute("custom", "true") new CustomSelect(chooser, { customOptionClass: 'option--hero-glow-color' }) } }) } document.addEventListener("DOMContentLoaded", function (event) { window.myfuncs.initColorChoosers = () => initColorChoosers(); }); and my color chooser: class Colors(blocks.ChoiceBlock): choices = [ ('color1', 'color1'), ('color2', 'color2'), ('color2', 'color2'), ] required = False, class Meta: form_classname = 'color-chooser' icon = 'copy' and block template at the end contains: <script> window.myfuncs.initColorChoosers() </script> And it works.. but for already added blocks not for the current one. So if I add a block which contains ColorChooser, it won't apply logic from `custom-select` but when I add another one, for the first one changes will be applied. [1]: https://www.npmjs.com/package/custom-select
How to add custom js for select in Wagtail choice block
|javascript|django|wagtail|wagtail-streamfield|wagtail-admin|
When I hover over this `DateTimeOffset` variable, only the `Hour` value is displayed: [![enter image description here][1]][1] I want to have the full `DateTimeOffset` back. Where is this actually coming from and how can I set/reset it? [1]: https://i.stack.imgur.com/ctsdO.png
In the previous code, I had a problem because I was passing availableOn as an argument. That's why it didn't work. Here is the correct code: @script <script> $wire.on('appointment-modal', async (event) => { let data = await event.availableOn; console.log(data); const modalBody = document.getElementById('modal-body'); data.forEach(time => { console.log(time.day) let timeElement = document.createElement('p'); timeElement.textContent = time.start_time + ' - ' + time.end_time; modalBody.appendChild(timeElement); }); const myModal = new bootstrap.Modal('#showTimes'); myModal.show(); }); </script> @endscript
Firefox extension background script terminated preemptively
|javascript|firefox-addon|firefox-addon-webextensions|
Here the pg_available_extensions word is selected: ![enter image description here](https://i.stack.imgur.com/nWtnd.png) The selection is not visible I tried to find a configuration parameter that would address this issue and could not find one. I lost hours trying to fix this as there are behavior associated to selected text that I use all the time. This issue makes the whole application unusable to me.
{"Voters":[{"Id":3745413,"DisplayName":"Ron Maupin"},{"Id":635608,"DisplayName":"Mat"},{"Id":466862,"DisplayName":"Mark Rotteveel"}],"SiteSpecificCloseReasonIds":[18]}
{"Voters":[{"Id":3074564,"DisplayName":"Mofi"},{"Id":6738015,"DisplayName":"Compo"},{"Id":9214357,"DisplayName":"Zephyr"}],"SiteSpecificCloseReasonIds":[18]}
async await resolve promise only if I return single value
I'm writing a Tkinter program that so far creates a window with a menu bar, a File menu, and a single item. The menu is successfully created, but with two items, the first being one that I did not specify, whose name is "-----". If I don't add an item, the spontaneous one is still added. This still happens if I specify tearoff=0. Any idea why this is happening? Windows 11, Python 3.12.2, Tkinter and Tcl 8.6.
Tkinter menu spontaneously adding extra item
|python|tkinter|