instruction
stringlengths
0
30k
How to edit a textinput within a list
I am trying to decode data matrix qr codes using `pylibdmtx`. I have below image [![enter image description here][1]][1] [1]: https://i.stack.imgur.com/l4VRO.png and using the below code: import cv2 from pylibdmtx import pylibdmtx import time import os image = cv2.imread('file1.png', cv2.IMREAD_UNCHANGED); gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) ret, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU) t1 = time.time() msg = pylibdmtx.decode(thresh) print(msg) if msg: print(msg[0].data.decode('utf-8')) t2 = time.time() print(t2-t1) It prints nothing. Is there anything I am missing in the code. I tried some [data matrix decoder online](https://www.dynamsoft.com/barcode-reader/barcode-types/datamatrix/), and they were able to decode it so I am sure image is correct but may be something is wrong in the code. Can anyone please help me out. Thanks
Error decoding data matrix code using pylibdmtx in Python
|python-3.x|opencv|qr-code|datamatrix|
I'm trying to build a table set in the form of a P&L in Looker studio. To build a table inside Looker you need to use the Pivot form, and it's not meeting my requirements (ex. I want a line 5 to be the sum of line 1, 2, 3, 4, then I want line 7 to be the difference between line 5 and 6...). So, how can I do to have this flexibility avoiding the only option of a pivot table in looker studio? Thnx for the help I tried to add a table on Looker studio but it's impossible to customize meeting my requirements
Looker P&L building table
|looker-studio|looker|
null
The mistake is the result set from that query has _two columns_. Otherwise, this dataset is a poor choice for demonstrating the JOIN types, because there are no values that are unique to A and B, such that the OUTER join types will always closely resemble the INNER join types. Really, the _only_ difference for the INNER join is excluding the `null` rows, because `null` is never equal to itself. You might also change the ordering of the sets for left vs right, but without an `ORDER BY` clause the order is meaningless and you are free to write the results in whatever order you want... and many databases will often silently rewrite RIGHT JOIN as the equivalent LEFT JOIN and give you the results as if you'd written it that way in the first place... ordering and all. Finally, the correct listing of the join types is left, right, inner, cross, and full. You do not list "outer", because its already included as part of left right and full. More recently you might also include a sixth LATERAL type (APPLY in SQL Server).
### Create some data To illustrate the difference, let's construct some data: ```r # Example dataset (dat <- data.frame( category = rep(c("A", "B"), each = 3), value = c(1, 2, 3, 4, 5, 6) )) # category value # 1 A 1 # 2 A 2 # 3 A 3 # 4 B 4 # 5 B 5 # 6 B 6 ``` And let's construct the barebones of a plot without a grouping variable (such as `color` or `fill` mapped to a plot aesthetic). ```r g <- ggplot(dat, aes(x = category, y = value)) + theme_minimal(base_size = 24) ``` ### `position_dodge()` If we try to apply `position_dodge()` to this data, it does not actually dodge the bars. They are stacked on top of each other, each one unit taller than the previous one on the y-axis: ```r g + geom_bar( stat = "identity", position = position_dodge(), color = "black", fill = NA ) ``` [![enter image description here][1]][1] ### `position_dodge2()` Conversely, `position_dodge2()` understands the bars should appear side-by-side: ```r g + geom_bar( stat = "identity", position = position_dodge2(padding = 0), color = "black", fill = NA ) ``` [![enter image description here][2]][2] [1]: https://i.stack.imgur.com/h0Zs4.png [2]: https://i.stack.imgur.com/5LOP6.png ### Other differences You might also noticed I provided `padding = 0`. That's because the `position_dodge2()` function takes two parameters, `padding` and `reverse`, that `position_dodge()` does not. These are set out in the [docs](https://ggplot2.tidyverse.org/reference/position_dodge.html). In those functions with a grouping variable, where you can use either, you need to set `position_dodge2(padding = 0)` to get identical output to `position_dodge()`.
null
using System; namespace Q1 { public class Q1 { static void Main() { // Keep the following line intact Console.WriteLine("==========================="); // Insert your solution here. const string EMPTY = "You have 0 eggs which equals 0 dozen and 0 eggs left over."; const string ZEROEGG = "You have 0 eggs which equals 0 dozen and 0 eggs left over."; const string NEGATIVEGG = "You have 0 eggs which equals 0 dozen and 0 eggs left over."; const string TWELVEEGG = "You have 12 eggs which equals 1 dozen and 0 eggs left over."; Console.WriteLine("Enter the number of chickens:"); int chickens = Convert.ToInt32(Console.ReadLine()); { if (chickens <= 0) { Console.WriteLine(EMPTY); Console.WriteLine("==========================="); return; } Console.WriteLine("Eggs:"); int egg_ = Convert.ToInt32(Console.ReadLine()); if (chickens == 1) { switch (egg_) { case 0: Console.WriteLine(ZEROEGG); break; case <= -1: Console.WriteLine(NEGATIVEGG); break; case 1: Console.WriteLine("You have " + egg_ + " egg which equals 0 dozen and " + egg_ + " egg left over."); break; case <= 11: Console.WriteLine("You have " + egg_ + " eggs which equals 0 dozen and " + egg_ + " eggs left over."); break; case 12: Console.WriteLine(TWELVEEGG); break; case 13: Console.WriteLine("You have " + egg_ + " eggs which equals 1 dozen and " + (egg_ - 12) + " egg left over."); break; case < 24: Console.WriteLine("You have " + egg_ + " eggs which equals 1 dozen and " + (egg_ - 12) + " eggs left over."); break; case 24: Console.WriteLine("You have " + egg_ + " eggs which equals 2 dozen and 0 eggs left over."); break; case > 24: Console.WriteLine("You have " + egg_ + " eggs which equals " + (egg_ / 12) + " dozen " + (egg_ - 12) + " eggs left over."); break; } for (int i = 0; i < chickens; ++i) { Console.Write("Eggs:"); egg_ = Convert.ToInt32(Console.ReadLine()); } } I want the code to prompt the user with the writeline statement equal to the number of chickens i.e. chickens = 4, Console.Write("Eggs:") 4 times. Ive tried while loop and if statements but couldn't figure it out.
I'm new to nodejs and express-session. As far as i know, when saveUninitialized is set to FALSE, the uninitialized session cookie will not be saved into sessionStore (mongodb in my case). Here is my session configs session: { secret: 'tuxcoder', store: initializes.sessionStore, resave: true, **saveUninitialized: false**, cookie: { name: 'demo_app_cookie', maxAge: 60000, // 6 minutes secure: process.env.NODE_ENV !== 'production' ? false : true, expires: 24 * 60 * 60 * 1000 * 7, // seven days\ httpOnly: true } } In my database, the [sessions] collection is empty. I also delete all browser cookie. But everytime I make a request, there will be a session document in my collection. { "_id": "WTN_EJhKTKnTQu5OPIpmhkIlTnJKVGKQ", "expires": ISODate("2024-04-05T05:56:00.346Z"), "session": { "cookie": { "originalMaxAge": NumberInt("604800000"), "expires": ISODate("2024-04-05T05:56:00.346Z"), "secure": false, "httpOnly": true, "domain": null, "path": "/", "sameSite": null }, "flash": { } } } WHY? Thanks for your time!
I'm updating my Spring Boot application from Java 11 to Java 17, and Spring Boot `2.7.18` to `3.2.4`, and running the tests I'm getting an error. So, I have a entity called `WorkloadDAO` like this: ``` @Entity @Table(name = "workloads") @IdClass(WorkloadId.class) public class WorkloadDAO { @Id @NonNull() private String id; @Id @Column(name = "created_at", insertable = false, updatable = false, columnDefinition = "TIMESTAMP") private LocalDateTime createdAt; // more attributes @PrePersist protected void onCreate() { createdAt = LocalDateTime.now(); } ``` The `createdAt` attribute will always be received with null value, and it will be set by the `onCreate()` method annotated with `@PrePersist` before save the instance in the database. As you can see in the annotation `@IdClass(WorkloadId.class)`, I'm setting `WorkloadId` as the id of this class. The `WorkloadId` class is like this: ``` public class WorkloadId implements Serializable { private String id; private LocalDateTime createdAt; } ``` So far, so good until the test. For example, I'm running this test: ``` @Test void testSaveWorkload() { String id = "someid"; WorkloadDAO dao = WorkloadDAO.builder() .id(id) .build(); WorkloadDAO response = repository.saveAndFlush(dao); assertThat(repository.findById(WorkloadId.builder() .id(id) .createdAt(response.getCreatedAt()) .build())) .get() .extracting("createdAt").isNotNull(); } ``` Before updating Java and Spring Boot, this test was running successfully. But now, I'm getting the following error: ``` org.springframework.orm.jpa.JpaSystemException: identifier of an instance of com.adevinta.delivery.workloadapi.data.WorkloadDAO was altered from WorkloadId(id=someid, createdAt=2024-03-28T12:26:34.355098) to WorkloadId(id=someid, createdAt=null) ``` Can you help me to understand why I'm getting this? Thanks! What I expect to happen is the test works, without setting the field `createdAt` beforehand.
|sql|mariadb|visualization|apache-superset|
I spent hours on this problem. I wanted to access the selected categories of my page in Typo3 Fluid, but there is no default way to do that.
Typo3 Fluid: How to get selected page categories in fluid
|typo3|typoscript|fluid|
There **is** no default way of doing this. You need to query the database and join tables yourself. Thanks for nothing Typo3 – nobody could have expected, that developers would actually want to access the selected categories in their templates. (╯°□°)╯︵ ┻━┻ In the setup Typoscript in the Fluidtemplate, add a DatabaseQueryProcessor: ```typoscript page = PAGE page { typeNum = 0 (...) 10 = FLUIDTEMPLATE 10 { (...) dataProcessing { (...) 30 = TYPO3\CMS\Frontend\DataProcessing\DatabaseQueryProcessor 30 { table = sys_category selectFields = sys_category.* pidInList = root,-1 recursive = 99 join = sys_category_record_mm ON (sys_category_record_mm.uid_local=sys_category.uid) where = sys_category_record_mm.tablenames='pages' AND sys_category_record_mm.uid_foreign = ###pageuid### orderBy = sorting markers.pageuid.field = uid as = pageCategories } } } } ``` This snippet creates a variable called `pageCategories`, which is an array of all selected categories for the current page. You can the access the title e. g. by `pageCategories.0.data.title` or loop over it in fluid: ```html <f:for each='{pageCategories}' as='category' iteration='inter'> <span class='category-tag'>{category.data.title}</span> </f:for> ``` To be honest, I don’t understand the query syntax myself, but this is a working solution. There were just a few google results for this problem, and they either didn't work in my case, of where just never answered, so I wanted to share my solution. Credits go to [t3brightside][1] who maintains the [pagelist][2] extension from which this code snippet was ~~inspired~~ (stolen). [1]: https://github.com/t3brightside [2]: https://github.com/t3brightside/pagelist
Padding pushing items in a flex div?
|html|css|flexbox|padding|
I get this warning message in the browser's console even if it is a blank tab **"Third-party cookie will be blocked. Learn more in the Issues tab"** and it keeps counting hundreds of warnings been blocked. Is this related to "tracking blocking" or some sort of a plugin issue and what is the way to check it.
Warning: Third-party cookie will be blocked
|google-chrome|google-chrome-devtools|
#include <stdio.h> void main() { // Write C code here int arr[] = {10,20,30,40}; int *p1 = arr; int *p2 = &arr[2]; printf("%d",p2-p1); } Output : 2 I was suprised to see the output as 2. I don't know why the output is 2.
Why is the output of following pointer program giving output as 2?
|c|pointers|pointer-arithmetic|
null
wordpress site. at very start of functions.php i have session_start() but i get an error message saying "headers already sent". the error_log doesn't give any info about where/what, etc. is there a way to determine why/where headers are being sent prior to the functions.php being run. I've tried making sure there's no white space and i've checked header.php, etc. i've tried using it with the "init" hook and also without it.
|oracle-apex|oracleforms|
My program has a main while loop as the main logic, with an inner while loop for running the logic of the "command function". When inside the inner while loop, I want `EOF` (Ctrl + D) to exit from the inner while loop only and continue with the outer loop (to listen to more commands). However, its exiting from both the inner "command" loop and outer main while loop. ```java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main { public static void main(String[] args) { String line; BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); try { while ((line = reader.readLine()) != null) { if (line.compareTo("echo") == 0) { while ((line = reader.readLine()) != null) System.out.println("echo: " + line); // Ctrl+D (EOF) will exit loop System.out.println("Stop echo-ing"); } else System.out.println("Cmd not recognized"); // No EOF given, should not exit this loop } System.out.println("Exit main loop"); } catch (IOException e) { System.err.println(e.getMessage()); } } } ``` To replicate problem: 1. Copy and paste code, and run it 2. Type `echo` to enter into inner while loop 3. Press `Ctrl` + `D` to provide `EOF` to standard input The following is printed: ```shell ^D Stop echo-ing Exit main loop ``` "Exit main loop" is printed unexpectedly. How can I exit only the inner while loop when `Ctrl` + `D` is pressed?
|html|angular|list|drop-down-menu|ng-template|
I have an antd table in my project version of antd : 4.25.15 react: "^16.8.6" It looks like this: ``` <Table dataSource={data} columns={columnsForRender} expandable={expandable} /> ``` expandable props: ``` const expandable = { expandIcon: ({ expanded, onExpand, record }) => { if (!record.children) { return null; } return expanded ? ( <MinusOutlined className='ant-table-row-expand-icon' onClick={e => onExpand(record, e)} /> ) : ( <PlusOutlined className='ant-table-row-expand-icon' onClick={e => onExpand(record, e)} /> ); }, }; ``` But this button doesn't look quite standard. I want to use the standard button that is in the Table example: 1st photo - my button[![enter image description here](https://i.stack.imgur.com/HfrB9.png)](https://i.stack.imgur.com/HfrB9.png) 2nd photo - standard antd button [![enter image description here](https://i.stack.imgur.com/Qh38O.png)](https://i.stack.imgur.com/Qh38O.png) And i cant use this expandedRowRender and rowExpandable because this way create a new column I try to use diffren classes, but a cant use expand and collapsed classes (maybe i dont know how)
How to use standard ExpandIcon of Table in antd
|reactjs|antd|
null
I subscribe to several nodes at the same time, so that I receive a notification only when the values change. I have to save the data to a csv file and I write rows with the timestamp + all the values of the nodes. I implemented asyncio.Queue to handle the simultaneous writing but still if I receive more than one notification at the same time, the file gets updated with the first notification but not the other ones which are lost. Here the output: ``` sv_writer_task started Queue list: <Queue maxsize=0> Datachange notification received. 29032024 14:10:16Data change notification was received and queued: ns=2;s=Unit_SB.UC3.TEMP.TEMP_v 19.731399536132812 Datachange notification received. 29032024 14:10:16Data change notification was received and queued: ns=2;s=Unit_SB.UC3.HUMI.HUMI_v 36.523399353027344 Dequeue value: 19.731399536132812 val name: TEMP Prefix UC1 is no match for node: Unit_SB.UC3.TEMP.TEMP_v. Skipping. Prefix UC2 is no match for node: Unit_SB.UC3.TEMP.TEMP_v. Skipping. csv file: UC3.csv Appending new row Data written to file UC3.csv succesfully Dequeue value: 36.523399353027344 val name: HUMI Prefix UC1 is no match for node: Unit_SB.UC3.HUMI.HUMI_v. Skipping. Prefix UC2 is no match for node: Unit_SB.UC3.HUMI.HUMI_v. Skipping. csv file: UC3.csv Updating existing row Data written to file UC3.csv succesfully ``` In the csv file one can see in last line that only the TEMP value, which arrived first, was changed, but not the HUMI one: ``` Timestamp,OUT_G,OUT_U,HUMI,TEMP 29032024 14:08:42,True,True,47.38769912719727,15.043899536132812 29032024 14:10:16,True,True,47.38769912719727,19.731399536132812 ``` here the code so far. Since I'm subscribing to several subsystem and each of them has it's own data file, I'm checking to which file to write: ``` # this is the consumer which consumes items from the queue async def csv_writer_task(queue): print("csv_writer_task started") print('Queue list: ') print(queue) print('') while True: try: dte, node, val = await queue.get() print('Dequeue value: ', val) except Exception as e: print(f"Error in csv_writer_task while retrieving value fromt he queue: {e}") node_id_str = str(node.nodeid.Identifier) node_parts = node_id_str[len("Unit_SB."):].split('.') val_name = node_parts[-1].replace('_v', '') print('val name: ', val_name) for key, header_row in prefix_mapping.items(): if f"Unit_SB.{key}" in node_id_str: csv_file = f"{key}.csv" print('csv file: ', csv_file) break else: print(f"Prefix {key} is no match for node: {node_id_str}. Skipping.") df = pd.read_csv(csv_file) last_row = df.iloc[-1].copy() if last_row['Timestamp'] == dte: print("Updating existing row") last_row[val_name] = val else: print("Appending new row") new_row = last_row.copy() new_row['Timestamp'] = dte new_row[val_name] = val df = pd.concat([df, new_row.to_frame().T], ignore_index=True) df.to_csv(csv_file, index=False) print(f'Data written to file {csv_file} succesfully') queue.task_done() class SubscriptionHandler(object): def __init__(self, wsconn): self.wsconn = wsconn self.q = asyncio.Queue() self.queuwriter = asyncio.create_task(csv_writer_task(self.q)) # this is the producer which produces items and puts them into a queue async def datachange_notification(self, node, val, data): print("Datachange notification received.") dte = data.monitored_item.Value.ServerTimestamp.strftime("%d%m%Y %H:%M:%S") await self.q.put((dte, node, val)) print(dte + "Data change notification was received and queued: ", node, val) class SBConnection(): def __init__(self): self.listOfWSNode = [] self.dpsList = ... async def connectAndSubscribeToServer(self): self.csv_file = '' async with Client(url=self.url) as self.client: for element in self.dpsList: node = "ns=" + element["NS"] + ";s=" + element["Name"] var = self.client.get_node(node) self.listOfWSNode.append(var) print("Subscribe to ", self.listOfWSNode) handler = SubscriptionHandler(self) sub = await self.client.create_subscription(period=10, handler=handler) await sub.subscribe_data_change(self.listOfWSNode) print('subscription created') # create infinite loop while True: await asyncio.sleep(0.1) async def main(): uc = SBConnection() await uc.connectAndSubscribeToServer() if __name__ == '__main__': asyncio.run(main()) ``` Anyone can help me in finding the problem? Thanks
I created my custom context menu using UIView. Im trying to change the corner radius when the context menu is active, but I have no idea how. I tried masks, layer whatsoever, but nothing worked. The provided current code is not rounding the corners. When I tried to set the background color to clear, then in between the fuzzy color and the content appeared a color that is the background color. Any idea? Here is the undesired behavior (you can see the distinct corner rounding): [![enter image description here][1]][1] import SwiftUI struct CustomContextMenu<Content: View>: View { var content: Content var menu: UIMenu? var previewBackgroundColor: UIColor init( @ViewBuilder content: @escaping ()->Content, actions: @escaping ()-> UIMenu?, previewBackgroundColor: UIColor ) { self.content = content() self.menu = actions() self.previewBackgroundColor = previewBackgroundColor } var body: some View { content .hidden() .overlay( ContextMenuHelper(content: content, actions: menu, previewBackgroundColor: previewBackgroundColor) ) } } struct ContextMenuHelper<Content: View>: UIViewRepresentable { var content: Content var actions: UIMenu? var previewBackgroundColor: UIColor init(content: Content, actions: UIMenu?, previewBackgroundColor: UIColor) { self.content = content self.actions = actions self.previewBackgroundColor = previewBackgroundColor } func makeCoordinator() -> Coordinator { return Coordinator(parent: self ) } func makeUIView(context: Context) -> UIView { // uiview let view = UIView() view.backgroundColor = UIColor.clear view.layer.cornerRadius = 20 // host view let hostView = UIHostingController(rootView: content) hostView.view.translatesAutoresizingMaskIntoConstraints = false hostView.view.backgroundColor = .clear view.addSubview(hostView.view) // add subview view.addConstraints( // add constraints [ hostView.view.topAnchor.constraint(equalTo: view.topAnchor), hostView.view.leadingAnchor.constraint(equalTo: view.leadingAnchor), hostView.view.trailingAnchor.constraint(equalTo: view.trailingAnchor), hostView.view.bottomAnchor.constraint(equalTo: view.bottomAnchor), hostView.view.widthAnchor.constraint(equalTo: view.widthAnchor), hostView.view.heightAnchor.constraint(equalTo: view.heightAnchor) ] ) if self.actions != nil { // if any menu item has been loaded // interaction let interaction = UIContextMenuInteraction(delegate: context.coordinator) view.addInteraction(interaction) } return view } func updateUIView(_ uiView: UIView, context: Context) { } class Coordinator: NSObject, UIContextMenuInteractionDelegate { var parent: ContextMenuHelper init(parent: ContextMenuHelper) { self.parent = parent } func contextMenuInteraction(_ interaction: UIContextMenuInteraction, configurationForMenuAtLocation location: CGPoint) -> UIContextMenuConfiguration? { interaction.view?.layer.cornerRadius = 30 guard let viewFrame = interaction.view?.frame else { return nil } // obtain child view size return UIContextMenuConfiguration(identifier: nil) { let previewController = UIHostingController(rootView: self.parent.content) previewController.view.backgroundColor = self.parent.previewBackgroundColor previewController.preferredContentSize = CGSize(width: viewFrame.width, height: viewFrame.height) return previewController } actionProvider: { items in return self.parent.actions } } } } **EDIT:** When Im wrapping the view into another view it changes the inner view, not the outer view: [![enter image description here][2]][2] func contextMenuInteraction(_ interaction: UIContextMenuInteraction, configurationForMenuAtLocation location: CGPoint) -> UIContextMenuConfiguration? { interaction.view?.layer.cornerRadius = 30 guard let viewFrame = interaction.view?.frame else { return nil } // obtain child view size return UIContextMenuConfiguration(identifier: nil) { let previewView = self.parent.content .background(Color(self.parent.previewBackgroundColor).edgesIgnoringSafeArea(.all)) .cornerRadius(30) let previewController = UIHostingController(rootView: previewView) previewController.preferredContentSize = CGSize(width: viewFrame.width, height: viewFrame.height) return previewController } actionProvider: { items in return self.parent.actions } } [1]: https://i.stack.imgur.com/n8O68.png [2]: https://i.stack.imgur.com/n7gDW.png
I have a chronicle queue version 5.25ea12 and I receive the following error at net.openhft.chronicle.core.internal.ClassUtil.getSetAccessible0Method(ClassUtil.java:32) at net.openhft.chronicle.core.internal.ClassUtil.<clinit>(ClassUtil.java:13) at net.openhft.chronicle.core.Jvm.getField(Jvm.java:541) at net.openhft.chronicle.core.Jvm.maxDirectMemory0(Jvm.java:906) at net.openhft.chronicle.core.Jvm.<clinit>(Jvm.java:145) at com.innova.egonext.ferm400.grpc.server.FrontendServer.run(FrontendServer.java:202) at com.innova.egonext.ferm400.grpc.server.FrontendServer$$FastClassBySpringCGLIB$$90fb6742.invoke(<generated>) at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218) at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:771) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749) at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:95) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749) at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:691) at com.innova.egonext.ferm400.grpc.server.FrontendServer$$EnhancerBySpringCGLIB$$2adf00a2.run(<generated>) at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1144) at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:642) at java.base/java.lang.Thread.run(Thread.java:1570) Caused by: java.lang.reflect.InvocationTargetException at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:118) at java.base/java.lang.reflect.Method.invoke(Method.java:580) at net.openhft.chronicle.core.internal.ClassUtil.getSetAccessible0Method(ClassUtil.java:26) ... 18 more Caused by: java.lang.IllegalAccessException: module java.base does not open java.lang.reflect to unnamed module @566776ad at java.base/java.lang.invoke.MethodHandles.privateLookupIn(MethodHandles.java:279) at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:103) ... 20 more I'm trying to run the application under JDK17 and with the given parameters -Dio.netty.tryReflectionSetAccessible=true --add-exports=java.base/jdk.internal.ref=ALL-UNNAMED --add-exports=jav a.base/sun.nio.ch=ALL-UNNAMED --add-exports=jdk.unsupported/sun.misc=ALL-UNNAMED --add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED --add-opens=jdk.compiler/com.sun.tools.javac=ALL-UNNAMED --add-opens=java.base/java .lang=ALL-UNNAMED --add-opens=java.base/java.lang.reflect=ALL-UNNAMED --add-opens=java.base/java.io=ALL-UNNAMED --add-opens=java.base/java.util=ALL-UNNAMED --add-opens=java.base/sun.nio.ch=ALL-UNNAMED Any suggestions? Thanks in advance
<!-- language-all: sh --> The registry key of origin and the comparison operand imply that you're dealing with _version numbers_. To meaningfully compare version numbers based on their _string representations_, cast them to `[version]`: ``` [version] $soft.DisplayVersion -lt [version] '124.0' ``` Note: * For brevity, you could omit the RHS `[version]` cast, because the LHS cast would implicitly coerce the RHS to `[version]` too. However, using it on both sides can help conceptual clarity. * For a [`[version]`](https://learn.microsoft.com/en-US/dotnet/api/System.Version) cast to succeed, the input string must have _at least 2_ components (e.g. `[version] '124.0'` and _at most 4_ (e.g, `[version] '124.0.1.2'`), and each component must be a positive decimal integer (including `0`). * `[version]` is _not_ capable of parsing [_semantic_ version numbers](https://semver.org/), however, which are limited to _3 components_ and may contain non-numeric suffixes (e.g., `7.5.0-preview.2`). * Use [`[semver]`](https://learn.microsoft.com/en-US/dotnet/api/System.Management.Automation.SemanticVersion) to parse semantic versions; however, that type is available in [_PowerShell (Core) 7_](https://github.com/PowerShell/PowerShell/blob/master/README.md) only. * Unlike with `[version]`, a _single_ component is sufficient in the input string of a `[semver]` cast; e.g., `[semver] '124'` works to create version `124.0.0`.
Long story short, PEBCAK - sort of. But I will leave this here in case someone else runs into a similar problem. What I started out with was something like this - given that I was only expecting plain text data: ``` let data = ""; request.on("data", chunk => { data += chunk.toString(); }); request.on("end", chunk => { if (chunk) { data += chunk.toString(); } doSomethingWithTheBinaryData(data); } ``` This, however, was pushing binary data into strings, causing the binary content to be modified, and `zlib` to no longer be able to decompress it. The proper way to receive binary data is: A proper way to receive binary data from an http request is something like: ``` let data = []; request.on("data", chunk => { data.push(chunk); }); request.on("end", chunk => { if (chunk) { data.push(chunk); } allData = Buffer.concat(data); doSomethingWithTheBinaryData(allData); } ``` Once I switched to this second form, both text and compressed data started to be received and processed correctly.
I have a pretty simple class: ```swift class TestClass {} ``` then I created an instance of this class: ```swift let instance = TestClass() ``` After that I started my project (debug build) and ran command in Xcode console: ``` language swift refcount instance ``` and what I got was: > refcount data: (strong = 3, unowned = 1, weak = 1) I wonder why my instance has 3 strong references, 1 unowned and 1 weak, if in fact there is only 1 strong reference.
|swift|xcode|lldb|
-(nullable NSArray<UIView*>*) swipeTableCell:(nonnull MGSwipeTableCell*) cell swipeButtonsForDirection:(MGSwipeDirection)direction swipeSettings:(nonnull MGSwipeSettings*) swipeSettings expansionSettings:(nonnull MGSwipeExpansionSettings*) expansionSettings { swipeSettings.transition = MGSwipeTransition3D; // 滑出动画 if (direction == MGSwipeDirectionRightToLeft) { expansionSettings.fillOnTrigger = YES; expansionSettings.threshold = 1.5; CGFloat padding = 10; MGSwipeButton *isTop = [MGSwipeButton buttonWithTitle:@"" icon:[UIImage imageNamed:@"top"] backgroundColor:[UIColor colorWithRed:243/256.0 green:243/256.0 blue:243/256.0 alpha:1] padding:padding callback:^BOOL(MGSwipeTableCell *sender) { NSIndexPath *indexPath = [self.tableView indexPathForCell:sender]; TrackNumbersCellModel*model = self.dataSource[indexPath.row]; if (model.isTop) { model.isTop = NO; [self.dataSource removeObject:model]; [self.dataSource insertObject:model atIndex:self.dataSource.count - 1]; [[TrackNumbersNetTools shareIntance] trackTable_MR_update_top_Entity:model.t_number isTop:NO]; [self.tableView reloadData]; }else{ model.isTop = YES; [self.dataSource removeObject:model]; [self.dataSource insertObject:model atIndex:0]; [[TrackNumbersNetTools shareIntance] trackTable_MR_update_top_Entity:model.t_number isTop:YES]; [self.tableView reloadData]; } return YES; }]; [isTop centerIconOverTextWithSpacing:7]; MGSwipeButton *isDelete = [MGSwipeButton buttonWithTitle:@"" icon:[UIImage imageNamed:@"delet"] backgroundColor:[UIColor colorWithRed:243/256.0 green:243/256.0 blue:243/256.0 alpha:1] padding:padding callback:^BOOL(MGSwipeTableCell *sender) { NSIndexPath *indexPath = [self.tableView indexPathForCell:sender]; TrackNumbersCellModel*model = self.dataSource[indexPath.row]; [self.dataSource removeObjectAtIndex:indexPath.row]; [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft]; [[TrackNumbersNetTools shareIntance] trackTable_MR_deleteEntity:model.t_number onFinished:^{ if (self.deleteBlock) { self.deleteBlock(); } }]; return YES; }]; [isDelete centerIconOverTextWithSpacing:7]; return @[isTop,isDelete]; } return nil; } My problem is that when I click on the "isTop" MGSwipeButton. I tried to change the image on the MGSwipeButton and used the following method, but it didn't work. Please help. With a link to "MGSwipeTableCell":https://github.com/MortimerGoro/MGSwipeTableCell ``` -(BOOL)swipeTableCell:(MGSwipeTableCell*)cell tappedButtonAtIndex:(NSInteger)index direction:(MGSwipeDirection)direction fromExpansion:(BOOL)fromExpansion{ if (direction == MGSwipeDirectionRightToLeft && index == 0) { id button = cell.leftButtons[index]; MGSwipeButton * pressedBtn = button; [pressedBtn setImage:[UIImage imageNamed:@"yy"] forState:UIControlStateNormal]; NSLog(@"pressedBtn title: %@",pressedBtn.titleLabel.text);} return YES; } ```
null
I find myself in the position of needing to really use intrinsics for the first time as optimization for image conversion. I found this project here: [https://github.com/jabernet/YCbCr2RGB/blob/master/conversion.cpp ](https://github.com/jabernet/YCbCr2RGB/blob/master/conversion.cpp) and it almost works, but my output target needs to be in r8g8b8a8 while this is outputting in r8g8b8. I tried modifiying this bit here: const __m128 rgb1_1 = _mm_shuffle_ps( _mm_shuffle_ps(b1, g1, _MM_SHUFFLE(0, 0, 0, 0)), _mm_shuffle_ps(r1, b1, _MM_SHUFFLE(1, 1, 0, 0)), _MM_SHUFFLE(2, 0, 2, 0)); const __m128 rgb1_2 = _mm_shuffle_ps( _mm_shuffle_ps(g1, r1, _MM_SHUFFLE(1, 1, 1, 1)), _mm_shuffle_ps(b1, g1, _MM_SHUFFLE(2, 2, 2, 2)), _MM_SHUFFLE(2, 0, 2, 0)); const __m128 rgb1_3 = _mm_shuffle_ps( _mm_shuffle_ps(r1, b1, _MM_SHUFFLE(3, 3, 2, 2)), _mm_shuffle_ps(g1, r1, _MM_SHUFFLE(3, 3, 3, 3)), _MM_SHUFFLE(2, 0, 2, 0)); const __m128 rgb2_1 = _mm_shuffle_ps( _mm_shuffle_ps(b2, g2, _MM_SHUFFLE(0, 0, 0, 0)), _mm_shuffle_ps(r2, b2, _MM_SHUFFLE(1, 1, 0, 0)), _MM_SHUFFLE(2, 0, 2, 0)); const __m128 rgb2_2 = _mm_shuffle_ps( _mm_shuffle_ps(g2, r2, _MM_SHUFFLE(1, 1, 1, 1)), _mm_shuffle_ps(b2, g2, _MM_SHUFFLE(2, 2, 2, 2)), _MM_SHUFFLE(2, 0, 2, 0)); const __m128 rgb2_3 = _mm_shuffle_ps( _mm_shuffle_ps(r2, b2, _MM_SHUFFLE(3, 3, 2, 2)), _mm_shuffle_ps(g2, r2, _MM_SHUFFLE(3, 3, 3, 3)), _MM_SHUFFLE(2, 0, 2, 0)); const __m128 rgb3_1 = _mm_shuffle_ps( _mm_shuffle_ps(b3, g3, _MM_SHUFFLE(0, 0, 0, 0)), _mm_shuffle_ps(r3, b3, _MM_SHUFFLE(1, 1, 0, 0)), _MM_SHUFFLE(2, 0, 2, 0)); const __m128 rgb3_2 = _mm_shuffle_ps( _mm_shuffle_ps(g3, r3, _MM_SHUFFLE(1, 1, 1, 1)), _mm_shuffle_ps(b3, g3, _MM_SHUFFLE(2, 2, 2, 2)), _MM_SHUFFLE(2, 0, 2, 0)); const __m128 rgb3_3 = _mm_shuffle_ps( _mm_shuffle_ps(r3, b3, _MM_SHUFFLE(3, 3, 2, 2)), _mm_shuffle_ps(g3, r3, _MM_SHUFFLE(3, 3, 3, 3)), _MM_SHUFFLE(2, 0, 2, 0)); const __m128 rgb4_1 = _mm_shuffle_ps( _mm_shuffle_ps(b4, g4, _MM_SHUFFLE(0, 0, 0, 0)), _mm_shuffle_ps(r4, b4, _MM_SHUFFLE(1, 1, 0, 0)), _MM_SHUFFLE(2, 0, 2, 0)); const __m128 rgb4_2 = _mm_shuffle_ps( _mm_shuffle_ps(g4, r4, _MM_SHUFFLE(1, 1, 1, 1)), _mm_shuffle_ps(b4, g4, _MM_SHUFFLE(2, 2, 2, 2)), _MM_SHUFFLE(2, 0, 2, 0)); const __m128 rgb4_3 = _mm_shuffle_ps( _mm_shuffle_ps(r4, b4, _MM_SHUFFLE(3, 3, 2, 2)), _mm_shuffle_ps(g4, r4, _MM_SHUFFLE(3, 3, 3, 3)), _MM_SHUFFLE(2, 0, 2, 0)); const __m128i pack1l = _mm_packs_epi32(_mm_cvtps_epi32(rgb1_1), _mm_cvtps_epi32(rgb1_2)); const __m128i pack1h = _mm_packs_epi32(_mm_cvtps_epi32(rgb1_3), _mm_cvtps_epi32(rgb2_1)); const __m128i pack1 = _mm_packus_epi16(pack1l, pack1h); const __m128i pack2l = _mm_packs_epi32(_mm_cvtps_epi32(rgb2_2), _mm_cvtps_epi32(rgb2_3)); const __m128i pack2h = _mm_packs_epi32(_mm_cvtps_epi32(rgb3_1), _mm_cvtps_epi32(rgb3_2)); const __m128i pack2 = _mm_packus_epi16(pack2l, pack2h); const __m128i pack3l = _mm_packs_epi32(_mm_cvtps_epi32(rgb3_3), _mm_cvtps_epi32(rgb4_1)); const __m128i pack3h = _mm_packs_epi32(_mm_cvtps_epi32(rgb4_2), _mm_cvtps_epi32(rgb4_3)); const __m128i pack3 = _mm_packus_epi16(pack3l, pack3h); const __m128i packAlpha = { 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF }; // and finally store in output _mm_storeu_si128((__m128i*)(pixels + ((wh - width) * 4) - h * width * 4 + w * 4 + 0 * 16), pack1); _mm_storeu_si128((__m128i*)(pixels + ((wh - width) * 4) - h * width * 4 + w * 4 + 1 * 16), pack2); _mm_storeu_si128((__m128i*)(pixels + ((wh - width) * 4) - h * width * 4 + w * 4 + 2 * 16), pack3); _mm_storeu_si128((__m128i*)(pixels + ((wh - width) * 4) - h * width * 4 + w * 4 + 3 * 16), packAlpha); with the packAlpha lines added by me. I thought it would line things up properly, but what I ended up with was grayscale and had vertical while lines throughout. It's also flipped on both axes, but that was true before my changes, and can be solved by rotating the texture that pixels is given too later. Edit: appended the calculation for the rgbX_Y variables to the top of the code block, per comment request. Also edited the numbers in the storing functions to reflect that I did in fact change those 3s to 4s
Is anyone familiar with Proxmox API? Specificly on how to create VM, as part of my bootcamp I'm trying to develop a friendly UI (https://github.com/sbendarsky/Proxify.git) using next.js for proxmox and I cannot find a solution on how to do that. I tried to search the web on how to do that but didn't find anything, I've only found solution on start/stop a VM but not on how to create one. import axios from 'axios'; import https from 'https'; import { serverRuntimeConfig } from 'next.config'; const proxmox_url = serverRuntimeConfig.proxmoxURL; const proxmox_token_id = serverRuntimeConfig.proxmox_token_id; const proxmox_secret = serverRuntimeConfig.proxmox_secret; const client = axios.create({ baseURL: `${proxmox_url}/api2/json`, headers: { Authorization: `PVEAPIToken=${proxmox_token_id}@pam=${proxmox_secret}`, }, httpsAgent: new https.Agent({ rejectUnauthorized: false }), }); export default async (req, res) => { try { const node = 'proxmox24'; const vmid = '101'; const vmConfig = { vmid, ostype: 'l26', disk: '10', cores: '2', memory: '2048', storage: 'local', net0: 'virtio,bridge=vmbr159', ide2: 'local:iso/Fedora-Workstation-Live-x86_64-39-1.5.iso', // Specify the ISO image correctly }; const response = await client.post(`/nodes/${node}/qemu/`, vmConfig); if (response.status === 200) { res.json({ message: 'VM created successfully' }); } else { res.json({ message: 'Failed to create VM' }); } } catch (error) { console.error(error); res.json({ message: 'An error occurred' }); } };
|c++|opengl|linker|
Background notification also get muted on removing "sound" from presentationOptions in @capacitor-firebase/messaging?
I Have a hql file which is being used in oozie hive action. I am running hive on spark engine by specifying the below in my hql file. `set hive.execution.engine=spark;` But the job is failing with error : `java.lang.NoClassDefFoundError: org/antlr/runtime/tree/CommonTree` `Caused by: java.lang.ClassNotFoundException: org.antlr.runtime.tree.CommonTree` I researched about it and trying to solve this by setting `spark.executor.extraClassPath` & `spark.driver.extraClassPath` I found this can be done by adding the entry in hive-site.xml . But I am trying to set this on run time by adding the below command in my hql file like below : set spark.executor.extraClassPath=/abc/external_jars/antlr-runtime-4.7.jar; set spark.driver.extraClassPath=/abc/external_jars/antlr-runtime-4.7.jar; But how can I add multiple jar file like this or is this the correct way to set the Classpath in runtime via hive ? Thanks Tried to run hive query via oozie action by setting the engine as spark. But it is failing with Exception : `java.lang.NoClassDefFoundError: org/antlr/runtime/tree/CommonTree` Expecting to run the job successfully by correctly identifying the antlr jar file. Thanks
[enter image description here][1] -(nullable NSArray<UIView*>*) swipeTableCell:(nonnull MGSwipeTableCell*) cell swipeButtonsForDirection:(MGSwipeDirection)direction swipeSettings:(nonnull MGSwipeSettings*) swipeSettings expansionSettings:(nonnull MGSwipeExpansionSettings*) expansionSettings { swipeSettings.transition = MGSwipeTransition3D; // 滑出动画 if (direction == MGSwipeDirectionRightToLeft) { expansionSettings.fillOnTrigger = YES; expansionSettings.threshold = 1.5; CGFloat padding = 10; MGSwipeButton *isTop = [MGSwipeButton buttonWithTitle:@"" icon:[UIImage imageNamed:@"top"] backgroundColor:[UIColor colorWithRed:243/256.0 green:243/256.0 blue:243/256.0 alpha:1] padding:padding callback:^BOOL(MGSwipeTableCell *sender) { NSIndexPath *indexPath = [self.tableView indexPathForCell:sender]; TrackNumbersCellModel*model = self.dataSource[indexPath.row]; if (model.isTop) { model.isTop = NO; [self.dataSource removeObject:model]; [self.dataSource insertObject:model atIndex:self.dataSource.count - 1]; [[TrackNumbersNetTools shareIntance] trackTable_MR_update_top_Entity:model.t_number isTop:NO]; [self.tableView reloadData]; }else{ model.isTop = YES; [self.dataSource removeObject:model]; [self.dataSource insertObject:model atIndex:0]; [[TrackNumbersNetTools shareIntance] trackTable_MR_update_top_Entity:model.t_number isTop:YES]; [self.tableView reloadData]; } return YES; }]; [isTop centerIconOverTextWithSpacing:7]; MGSwipeButton *isDelete = [MGSwipeButton buttonWithTitle:@"" icon:[UIImage imageNamed:@"delet"] backgroundColor:[UIColor colorWithRed:243/256.0 green:243/256.0 blue:243/256.0 alpha:1] padding:padding callback:^BOOL(MGSwipeTableCell *sender) { NSIndexPath *indexPath = [self.tableView indexPathForCell:sender]; TrackNumbersCellModel*model = self.dataSource[indexPath.row]; [self.dataSource removeObjectAtIndex:indexPath.row]; [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft]; [[TrackNumbersNetTools shareIntance] trackTable_MR_deleteEntity:model.t_number onFinished:^{ if (self.deleteBlock) { self.deleteBlock(); } }]; return YES; }]; [isDelete centerIconOverTextWithSpacing:7]; return @[isTop,isDelete]; } return nil; } My problem is that when I click on the "isTop" MGSwipeButton. I tried to change the image on the MGSwipeButton and used the following method, but it didn't work. Please help. With a link to "MGSwipeTableCell":https://github.com/MortimerGoro/MGSwipeTableCell ``` -(BOOL)swipeTableCell:(MGSwipeTableCell*)cell tappedButtonAtIndex:(NSInteger)index direction:(MGSwipeDirection)direction fromExpansion:(BOOL)fromExpansion{ if (direction == MGSwipeDirectionRightToLeft && index == 0) { id button = cell.leftButtons[index]; MGSwipeButton * pressedBtn = button; [pressedBtn setImage:[UIImage imageNamed:@"yy"] forState:UIControlStateNormal]; NSLog(@"pressedBtn title: %@",pressedBtn.titleLabel.text);} return YES; } ``` [1]: https://i.stack.imgur.com/DTYcx.jpg
I use segmented picker in iOS which contains few items. When user tap on not selected item this item becomes selected. Some of items can contain sub items. So when user tap on already selected type I need to show modal window with subitems for choosing one of them. But taps on already selected items of segmented picker are not handling. I tried to use "long press" but it not works as well. I would like to use native iOS design that's why I don't want use "buttons" instead segmented picker. So the question is how I can handle tap on already selected item of segmented picker for showing sub items to choosing one of them? It can be "long press" or other alternative which will be intuitive for user. ``` import SwiftUI struct CustomSegmentedPicker: View { @State private var showModalSelectD: Bool = false enum periods { case A, B, C, D, All } @State var predefinedPeriod: periods = periods.All @State var predefinedPeriodD: String = "D1" var body: some View { ZStack { Color.clear .sheet(isPresented: $showModalSelectD, content: { List { Picker("D", selection: $predefinedPeriodD) { Text("D1").tag("D1") Text("D2").tag("D2") Text("D3").tag("D3") } .pickerStyle(.inline) } }) VStack { HStack { Picker("Please choose a currency", selection: $predefinedPeriod) { Text("A").tag(periods.A) Text("B").tag(periods.B) Text("C").tag(periods.C) Text("D (\(predefinedPeriodD))").tag(periods.D) .contentShape(Rectangle()) .simultaneousGesture(LongPressGesture().onEnded { _ in print("Got Long Press") showModalSelectD.toggle() }) .simultaneousGesture(TapGesture().onEnded{ print("Got Tap") showModalSelectD.toggle() }) Text("All").tag(periods.All) } .pickerStyle(SegmentedPickerStyle()) } } } } } ```
For future readers. The IntelliJ plugin works fine for "trivial" cases. I had a more complex case. The online tool below did it correctly: https://env.simplestep.ca/ The "text" of the site above is: "Environment Variable Generator for Spring Boot apps" (in case the website dies in the future) Example of my complex case: things: combinations: - nameOf: favoriteColor valueOfValue: green - nameOfName: favoritePlanet valueOfValue: Mars result from simplestep.ca THINGS_COMBINATIONS_0_NAMEOF=favoriteColor THINGS_COMBINATIONS_0_VALUEOFVALUE=green THINGS_COMBINATIONS_1_NAMEOFNAME=favoritePlanet THINGS_COMBINATIONS_1_VALUEOFVALUE=Mars and this matches the spring documentation for "complex" types. https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.external-config.typesafe-configuration-properties.merging-complex-types below is code snipplets from the docs.spring.io link above. @ConfigurationProperties("my") public class MyProperties { private final List<MyPojo> list = new ArrayList<>(); public List<MyPojo> getList() { return this.list; } } yaml my: list: - name: "my name" description: "my description" application.properties my.list[0].name=my name my.list[0].description=my description
How to read a file that contains both ANSI and UTF-8 encoded characters
I have 6 workload files like workloads, workloadb, workload etc. I am using the below command to load the data. ./bin/ycsb.sh load Redis -s - P workloads/workloada -p recordcount=400000 -threads 100 dbname> outputdata.txt As same above I will be running Run command aswell After inserting the 400000 records then I need to append some more records If I use the above command then the existing records getting deleted here. How Can I append the records I have tried with different workload file but the existing records getting deleted. How can I append the records here
Is it possible to append the data in Redis command
|database|performance|redis|in-memory-database|
null
I wrote a code which exposes an C++ object to QML and I would like to check declared properties of the object with native JS things, but they does not work as it expected. I wrote `FizzBuzzDerived.properties` method and it works file as I would expect `Object.keys` work. Result in case of calling the functions ```js Object.keys(FizzBuzz); // -> [] Object.values(FizzBuzz); // -> [] JSON.stringify(FizzBuzz); // -> {} FizzBuzz.properties(); // -> ["objectName", "fizz", "buzz", "foo", "bar"] ``` Here is the code. main.cpp ```c++ #include "myplugin.h" #include <QApplication> #include <QQmlApplicationEngine> #include <QQmlEngine> #include <QQmlExtensionPlugin> int main(int argc, char *argv[]) { QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); QGuiApplication app(argc, argv); QQmlApplicationEngine engine; MyPlugin plugin; plugin.registerTypes("ObjectStorage"); const QUrl url = QStringLiteral("qrc:/main.qml"); QObject::connect(&engine, &QQmlApplicationEngine::objectCreated, &app, [url](QObject *obj, const QUrl &objUrl) { if (!obj && url == objUrl) QCoreApplication::exit(-1); }, Qt::QueuedConnection); engine.load(url); return app.exec(); } ``` myplugin.h ```c++ #ifndef MYPLUGIN_H #define MYPLUGIN_H #include "objectstorage.h" #include <QObject> #include <QQmlExtensionPlugin> class MyPlugin : public QQmlExtensionPlugin { Q_OBJECT Q_PLUGIN_METADATA(IID QQmlExtensionInterface_iid) public: void registerTypes(const char *uri) override { Q_ASSERT(QLatin1String(uri) == QLatin1String("ObjectStorage")); qmlRegisterSingletonType<FizzBuzzDerived>("Model", 1, 0, "FizzBuzz", ObjectStorage::provider); } }; #endif // MYPLUGIN_H ``` objectstorage.h ```c++ #ifndef OBJECTSTORAGE_H #define OBJECTSTORAGE_H #include "fizzbuzzderived.h" #include <QObject> #include <QQmlEngine> class ObjectStorage : public QObject { Q_OBJECT public: static QObject *provider(QQmlEngine *qml, QJSEngine *js) { Q_UNUSED(qml) Q_UNUSED(js) FizzBuzzDerived *object = new FizzBuzzDerived(); object->setFizz(45); object->setBuzz(24.42); object->setFoo(false); object->setBar(Bar::B); return object; } }; #endif // OBJECTSTORAGE_H ``` fizzbuzzderived.h ```c++ #ifndef FIZZBUZZDERIVED_H #define FIZZBUZZDERIVED_H #include "fizzbuzz.h" #include <QObject> #include <QDebug> class FizzBuzzDerived : public QObject { Q_OBJECT Q_PROPERTY(int fizz READ fizz WRITE setFizz NOTIFY fizzChanged); Q_PROPERTY(double buzz READ buzz WRITE setBuzz NOTIFY buzzChanged) Q_PROPERTY(bool foo READ foo WRITE setFoo NOTIFY fooChanged) Q_PROPERTY(int bar READ bar WRITE setBar NOTIFY barChanged) public: explicit FizzBuzzDerived(QObject *parent = nullptr); Q_INVOKABLE QList<QString> properties() const; int fizz() const; double buzz() const; bool foo() const; int bar() const; public slots: void setFizz(int fizz); void setBuzz(double buzz); void setFoo(bool foo); void setBar(int bar); signals: void fizzChanged(int fizz); void buzzChanged(double buzz); void fooChanged(bool foo); void barChanged(int bar); private: FizzBuzz m_object; }; Q_DECLARE_METATYPE(FizzBuzzDerived *) #endif // FIZZBUZZDERIVED_H ``` fizzbuzzderived.cpp ```c++ #include "fizzbuzzderived.h" #include <QMetaProperty> FizzBuzzDerived::FizzBuzzDerived(QObject *parent) : QObject(parent) { } QList<QString> FizzBuzzDerived::properties() const { QList<QString> names; const QMetaObject *metaObject = this->metaObject(); for (int i = 0; i < metaObject->propertyCount(); ++i) { QMetaProperty property = metaObject->property(i); names << QString(property.name()); } return names; } int FizzBuzzDerived::fizz() const { return m_object.fizz; } double FizzBuzzDerived::buzz() const { return m_object.buzz; } bool FizzBuzzDerived::foo() const { return m_object.foo; } int FizzBuzzDerived::bar() const { return m_object.bar; } void FizzBuzzDerived::setFizz(int fizz) { if (m_object.fizz != fizz) { m_object.fizz = fizz; emit fizzChanged(m_object.fizz); } } void FizzBuzzDerived::setBuzz(double buzz) { if (m_object.buzz != buzz) { m_object.buzz = buzz; emit buzzChanged(m_object.buzz); } } void FizzBuzzDerived::setFoo(bool foo) { if (m_object.foo != foo) { m_object.foo = foo; emit fooChanged(m_object.foo); } } void FizzBuzzDerived::setBar(int bar) { if (m_object.bar != bar) { m_object.bar = static_cast<Bar>(bar); emit barChanged(m_object.bar); } } ``` main.qml ```qml import QtQuick 2.0 import Model 1.0 Item { property FizzBuzz item: FizzBuzz Component.onCompleted: { const object = item; const props = object.properties(); console.info(`object: ${object}`) console.info(props.map(prop => `${prop}: ${JSON.stringify(object[prop])}`).join(", ")); } } ``` Tried to get the object keys from C++ side and it works. Don't have a clue why this is happening. By the way, I use Qt 5.14.2.
I'm creating a small program to create a batch of documents. In the footer of each created document, I tried to reflect the serial number of the current page and the total number of pages in the document, that is, to provide a line like: “Page 1 of 3.” However, it is not possible to correctly reflect the total number of pages in one document. The footer appears to display the total number of pages for the entire document package. Here is part of my code: ```java XWPFHeaderFooterPolicy headerFooterPolicy = firstDocument.getHeaderFooterPolicy(); if (headerFooterPolicy == null) headerFooterPolicy = firstDocument.createHeaderFooterPolicy(); XWPFFooter footer = headerFooterPolicy.createFooter(XWPFHeaderFooterPolicy.DEFAULT); XWPFParagraph parafooter = footer.createParagraph(); parafooter.setAlignment(ParagraphAlignment.RIGHT); XWPFRun runfooter = parafooter.createRun(); runfooter.setText("First line"); runfooter.setFontFamily("Times New Roman"); XWPFParagraph parafooter1 = footer.createParagraph(); parafooter1.setAlignment(ParagraphAlignment.RIGHT); XWPFRun runfooter1 = parafooter1.createRun(); runfooter1.setText("page no. "); runfooter1.getCTR().addNewPgNum(); runfooter1=parafooter1.createRun(); runfooter1.setText(" of " + firstDocument.getBodyElements().size()); runfooter1.setFontFamily("Times New Roman"); firstDocument.write(new FileOutputStream(new File(fileString + "\\FirstFile.doc"))); firstDocument.close(); ``` This is the result that appears in the footer: ```none First line page no. 1 of 41 ``` I tried using different functions, but did not achieve a positive result.
The total number of document pages in the footer is not calculated correctly
i am currently an apprentice an pretty new to delphi (Using Delphi 11 in RAD Studio) so i apologize if there is something obvious i'm missing. And i have to note i have to work with a 22 years old lagacy code with approx 600k lines so that could be an error factor as well :D I was tasked to code a way to save all currently open Forms with their properties like size, position and window state and then restoring it after reopening the program. For that i decided to add in the FormCloseQuery in the Main Form a procedure which goes through all Forms and writes their data (if Visible true) in a .ini File. Works pretty great so far and this is how it looks like: ``` procedure SaveFormInformation(); var i : Integer; form : TForm; iniFile : TIniFile; begin iniFile := TIniFile.Create(ExtractFilePath(Application.ExeName) + 'FormInfo.ini'); try for i := 0 to Screen.FormCount - 1 do begin form := Screen.Forms[i]; if form.Visible then begin iniFile.WriteInteger(form.Name, 'Width', form.Width); iniFile.WriteInteger(form.Name, 'Height', form.Height); iniFile.WriteInteger(form.Name, 'Left', form.Left); iniFile.WriteInteger(form.Name, 'Top', form.Top); iniFile.WriteBool(form.Name, 'Visible', form.Visible); iniFile.WriteBool(form.Name, 'IsMaximized', form.WindowState = wsMaximized) end; end; finally iniFile.Free; end; end; ``` And in the end the .ini File it looks like this: ``` [F_Main] Width=719 Height=542 Left=600 Top=305 Visible=1 IsMaximized=0 [F_PartList] Width=1126 Height=716 Left=71 Top=301 Visible=1 IsMaximized=0 ``` Now to my problem... the restoring. At first i tried the same way with Screen.FormCount and if Visible, read the .ini File and replace the values. That only worked partially because we have so many forms (masks), we decided to not initialize some of the forms in the beginning because perfomance. Then i decided to turn things around and include a loop which reads the .ini and only changes whats written there. But before it changes the properties it looks if the form exists in the first place and creates it when not there. This part does not work the way i intent it to. The if statement - lookup works: ``` if Application.FindComponent(Sections[i]) as TForm = nil then ``` But the Application.CreateForm() doen't. It seems like it cannot find the classes with their respective names alone. Thankfully we have a naming convention here so every TForm starts with F_ and every TFormClass with TF_ so it should theoretically be possible. Here the procedure of RestoreForms(): ``` procedure RestoreForms(); var i : Integer; iniFile : TIniFile; form : TForm; FormClass : TFormClass; Sections : TStringList; begin iniFile := TIniFile.Create(ExtractFilePath(Application.ExeName) + 'FormInfo.ini'); Sections := TStringList.Create; try IniFile.ReadSections(Sections); for i := 0 to Sections.Count -1 do begin {form := Application.FindComponent(Sections[i]) as TForm; if not Assigned(form) then begin FormClass := TFormClass(GetClass('T' + Sections[i])); Application.CreateForm(FormClass, form); form.Free; end;} //Since not all Forms are initialized in the beginning this bit //does it for you. If the Form is nil then create Form if Application.FindComponent(Sections[i]) as TForm = nil then begin //FormClass := TFormClass(FindClass('T' + Sections[i])); FormClass := TFormClass(GetClass('T' + Sections[i])); form := Application.FindComponent(Sections[i]) as TForm; Application.CreateForm(FormClass, form); form.Free; end; //this puts the current read form of the ini File in a TForm Object //to then change its properties form := Application.FindComponent(Sections[i]) as TForm; with form do begin form.Top := IniFile.ReadInteger(form.Name, 'Top', Top); form.Left := IniFile.ReadInteger(form.Name, 'Left', Left); form.Height := IniFile.ReadInteger(form.Name, 'Height', Height); form.Width := IniFile.ReadInteger(form.Name, 'Width', Width); if iniFile.ReadBool(form.Name, 'IsMaximized', WindowState = wsMaximized) then form.WindowState := wsMaximized else form.WindowState := wsNormal; form.Position := poDesigned; if not (Sections[i] = 'F_Main') then form.Visible := IniFile.ReadBool(form.Name, 'Visible', Visible); end; end; finally Sections.Free; form.Free; iniFile.Free; end; end; ``` Currently the code "opens" the program but no Form will be seen. Only Services in Taskmanager can free me of the process ^^" I also thought about saving their Window States of all open Forms in their respective FormClass itself, but since we have like 1k Forms / Masks this task is close to impossible. I hope you guys can give me some pointers or ideas since neither google nor stackoverflow nor AI could give me any answers as of now.
Trying to calculate the area of a polygon recursively using the shoelace theorem and splitting it into triangles. ``` public static double calculatePolygonArea(ArrayList<Point> points) { if (points.size() < 3) { return 0; } if (points.size() == 3) { return calculateTriangleArea(points.get(0), points.get(1), points.get(2)); } return calculateTriangleArea(points.get(0), points.get(1), points.get(2)) + calculatePolygonArea(new ArrayList<>(points.subList(1, points.size()))); } private static double calculateTriangleArea(Point p1, Point p2, Point p3) { return Math.abs((p1.getX() * p2.getY() + p2.getX() * p3.getY() + p3.getX() * p1.getY() - p1.getY() * p2.getX() - p2.getY() * p3.getX() - p3.getY() * p1.getX()) / 2.0); } ``` The code does not return the correct area and its always less than the actual area.
I had the same issue. When there is an exception in any of the threads the library creates, the process hangs waiting for it to finish for hours. After running in one thread I found out the issue and fixed it. With the exception no longer occurring, the process hang is fixed.
I built glib [link][1] with coverage. `glib` uses the `meson` build system which requires the build to be generated in a separate directory. I run `gcov` on each `gcno` file generated in order to get function coverage. I am interested in coverage broken down by function. I ran into two problems: 1- For `gcno` files inside the build directory I get errors like ``` File '../glib/gcharset.c' Lines executed:11.40% of 228 Creating 'gcharset.c.gcov' Cannot open source file ../glib/gcharset.c File '../glib/gstrfuncs.h' Lines executed:100.00% of 1 Creating 'gstrfuncs.h.gcov' Cannot open source file ../glib/gstrfuncs.h ``` I solved this by moving all the `gcno` and `gcda` files into a newly created directory in the root src directory of glib called `coverage_files`. This way this relative path for the c files would be work. 2- The second problem is the one I am currently stuck on. I get coverage for some functions exceeding 100%. ``` Function 'g_get_charset' Lines executed:106.25% of 16 ``` This is seen across many functions in different files and I can't figure out why or how this is even possible. This is an example of the output for one `gcno` file. ``` gcov -f gcharset.c.gcno Function 'g_get_language_names_with_category' Lines executed:0.00% of 26 Function 'g_get_language_names' Lines executed:0.00% of 2 Function 'language_names_cache_free' Lines executed:0.00% of 6 Function 'guess_category_value' Lines executed:0.00% of 14 Function 'g_get_locale_variants' Lines executed:0.00% of 6 Function 'append_locale_variants' Lines executed:0.00% of 22 Function 'explode_locale' Lines executed:0.00% of 19 Function 'unalias_lang' Lines executed:0.00% of 14 Function 'read_aliases' Lines executed:0.00% of 24 Function 'g_get_console_charset' Lines executed:0.00% of 2 Function 'g_get_codeset' Lines executed:0.00% of 3 Function '_g_get_ctype_charset' Lines executed:0.00% of 14 Function '_g_get_time_charset' Lines executed:0.00% of 14 Function 'g_get_charset' Lines executed:106.25% of 16 Function 'charset_cache_free' Lines executed:0.00% of 6 Function 'g_utf8_get_charset_internal' Lines executed:58.82% of 17 Function '_g_charset_get_aliases' Lines executed:0.00% of 3 Function 'get_alias_hash' Lines executed:0.00% of 21 File '../glib/gcharset.c' Lines executed:11.40% of 228 Creating 'gcharset.c.gcov' File '../glib/gstrfuncs.h' Lines executed:100.00% of 1 Creating 'gstrfuncs.h.gcov' Lines executed:11.79% of 229 ``` [1]: https://docs.gtk.org/glib/
GCOV showing coverage for functions more than 100%
|glib|gcov|gcovr|
I was able to find out why it was throwing the error, so thought that i would answer the question myself. The issue was `AuthRoute.tsx`, it should have passed as an element of the <Route /> example: ``` <Route key={route.path} path={route.path} element={ <AuthRoute path={route.path} Component={route.component} exact={route.exact} requiredPermission={route.requiredPermission} /> } /> ```
The program was written using version Qt 6.4.3 **CMakeLists.txt** file: ``` cmake_minimum_required(VERSION 3.16) project(youtube_video VERSION 0.1 LANGUAGES CXX) set(CMAKE_CXX_STANDARD_REQUIRED ON) find_package(Qt6 6.4 REQUIRED COMPONENTS Quick WebEngineQuick) qt_standard_project_setup() qt_add_executable(appyoutube_video main.cpp ) qt_add_qml_module(appyoutube_video URI youtube_video VERSION 1.0 QML_FILES Main.qml ) # Qt for iOS sets MACOSX_BUNDLE_GUI_IDENTIFIER automatically since Qt 6.1. # If you are developing for iOS or macOS you should consider setting an # explicit, fixed bundle identifier manually though. set_target_properties(appyoutube_video PROPERTIES # MACOSX_BUNDLE_GUI_IDENTIFIER com.example.appyoutube_video MACOSX_BUNDLE_BUNDLE_VERSION ${PROJECT_VERSION} MACOSX_BUNDLE_SHORT_VERSION_STRING ${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR} MACOSX_BUNDLE TRUE WIN32_EXECUTABLE TRUE ) target_link_libraries(appyoutube_video PRIVATE Qt6::Quick Qt6::WebEngineQuick ) include(GNUInstallDirs) install(TARGETS appyoutube_video BUNDLE DESTINATION . LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} ) ``` **main.cpp** file: ``` #include <QGuiApplication> #include <QQmlApplicationEngine> #include <QtWebEngineQuick/qtwebenginequickglobal.h> int main(int argc, char *argv[]) { QtWebEngineQuick::initialize(); QGuiApplication app(argc, argv); QQmlApplicationEngine engine; const QUrl url(u"qrc:/youtube_video/Main.qml"_qs); QObject::connect( &engine, &QQmlApplicationEngine::objectCreationFailed, &app, []() { QCoreApplication::exit(-1); }, Qt::QueuedConnection); engine.load(url); return app.exec(); } ``` **Main.qml** file: ``` import QtQuick import QtQuick.Controls import QtQuick.Window import QtWebEngine Window { width: 640 height: 480 visible: true title: qsTr("Hello World") WebEngineView { anchors.fill: parent url: "https://www.youtube.com/embed/cabBXCq7_P8" } } ``` Shows a preview after launch: [after launch](https://i.stack.imgur.com/rsuHE.png) But trying to play the video results in an error: [error message](https://i.stack.imgur.com/RB2eI.png) Can anyone tell me what the error is and how to fix it? As a result, the video is expected to play
I fixed it with #txa_movieEditComment {-fx-background: #191919;} I dont know why you can't use #txa_movieEditComment {-fx-background-color: #191919;} but it fixed it for me. [This is how it's supposed to look][1] [1]: https://i.stack.imgur.com/fv4nS.png
I have created the following code for easy logging. It creates an UTF-8 file without BOM when executed in PowerShell 5. It works as expected for me. Feel free to customize it to your needs :-) Function myWriteLog{ # $LogFilePath has to be defined before calling the function # And, "$SciptName=$MyInvocation.MyCommand.Name" has to be set before calling the function Param( [Parameter(Mandatory=$true, ValueFromPipeline=$true)] [string]$content ) # disallow an NULL or an EMPTY value if ([string]::IsNullOrEmpty($content.Trim())){ throw "Found 'EMPTY or NULL': must be provide a nonNull and nonEmpty string to function ""myWriteLog""" return 0 } else { if((Test-Path $LogFilePath) -eq $False){ # Creates the file, please note that option "-NoNewline" has to be set "" | Out-file -FilePath $LogFilePath -Encoding ascii -Force -NoNewline # Create a string as a line separator for a file header $t ="".PadLeft(("Logfile for : $SciptName").Length,"#") Add-Content -path $LogFilePath -value "$t" Add-Content -path $LogFilePath -value "Logfile for : $SciptName" Add-Content -path $LogFilePath -value "LogFile Created: $(Get-date -F "yyyy-MM-dd-HH-mm-ss")" Add-Content -path $LogFilePath -value "$t" Add-Content -path $LogFilePath -value "" #and now add the content to Add-Content -path $LogFilePath -value "$(Get-date -F "yyyy-MM-dd-HH-mm-ss") : $content" -Encoding UTF8 -force }else{ Add-Content -path $LogFilePath -value "$(Get-date -F "yyyy-MM-dd-HH-mm-ss") : $content" -Encoding UTF8 -force } } }
I have now a different approach. After I clicked the Login Button I load the AppShell again with different visibility settings. In my LoginViewModel [RelayCommand(CanExecute = nameof(CanLogin))] private async Task Login(object obj) { await Task.Run(() => { if (Application.Current != null) { // Reload the AppShell Application.Current.MainPage = new AppShell(new AppShellViewModel(true)); } }); } In my AppShellViewModel public AppShellViewModel(bool login) { // Check if user made a login if (login) { // Set Visibility Propertys } }
While learning and playing around with asyncio and aiohttp, faced this and was wondering if this was an occurance limited to VSC only? This one keeps leaving residues from the previous loops. ``` while True: loop.run_until_complete(get_data()) ``` [![](https://i.stack.imgur.com/OiuBe.png)](https://i.stack.imgur.com/OiuBe.png) This runs without any residual tasks. ``` while True: asyncio.run(get_data()) ``` [![](https://i.stack.imgur.com/Ju2RG.png)](https://i.stack.imgur.com/Ju2RG.png) ``` session = aiohttp.ClientSession() async def fetch(url, params=None): async with semaphore: async with session.get(url, params=params) as response: return await response.json() ``` I tried moving the while loop inside the called method itself but still the same result. Also tried using semaphores with no better luck. I was trying to manage multiple rest api call methods using aiohttp from within a single loop but with this happening, guess I am stuck with having to use asyncio.run separately for each api related method. So the only way right now is to keep closing and reopening separate loops. Need I even to worry about the forever created tasks? I read that these are just residues from the previous loops and the impact load is nonexistent even with them constantly stacking up. Could this possibly be a VSC related issue?
Figured it out by initializing the calendar correctly according to the version of the CDN I was using. I corrected to the latest version 6. ``` <script src='https://cdn.jsdelivr.net/npm/fullcalendar@6.1.11/index.global.min.js'></script> var calendarEl = document.getElementById('calendar'); var calendar = new FullCalendar.Calendar(calendarEl, { }); calendar.render(); ```
If the warnings do not affect your code execution or performance, you can choose to ignore them. import warnings warnings.filterwarnings("ignore", category=FutureWarning)
This should probably be considered an implementation detail of the `json` package, and also it might be a Python version thing. In any case, it becomes crucial with your implementation: - The `dump()` function internally calls the `iterencode()` method on your encoder (see lines 169 and 176 [in the actual source code][1]. - Yet, the `dumps()` function internally calls `encode()` (see lines 231 and 238). You can verify this by adjusting `encode()` and overriding `iterencode()` in your `JSONSerializer` like so: ```python class JSONSerializer(json.JSONEncoder): def encode(self, obj): print("encode called") ... # Your previous code here return super().encode(obj) def iterencode(self, *args, **kwargs): print("iterencode called") return super().iterencode(*args, **kwargs) ``` … and you will see that only "iterencode called" will be printed with your test code, but not "encode called". The other Stack Overflow question that you linked in your question seems to have the same issue by the way, at least when using a rather recent version of Python (I am currently on 3.11 for writing this) – see my [comment][2] to the corresponding answer. I have two solutions: 1. *Either* use `dumps()` in your `Agent.memorize()` method, e.g. like so: ```python def memorize(self): with open("memory.json", "w") as w: w.write(json.dumps(self.G, cls=JSONSerializer)) ``` 2. *Or* move your own implementation from `encode()` to `iterencode()`, e.g. like so: ```python class JSONSerializer(json.JSONEncoder): def iterencode(self, obj, *args, **kwargs): if isinstance(obj, MutableMapping): for key in list(obj.keys()): if isinstance(key, tuple): strkey = "%d:%d" % key obj[strkey] = obj.pop(key) yield from super().iterencode(obj, *args, **kwargs) ``` This 2nd solution seems to have the benefit that it works with both `dump()` and `dumps()` (see note below). A note for completion: The `dumps()` function later seems to result in a call of `iterencode()`, as well (I did not track the source code so far as to see where exactly that happens, but from the printouts that I added it definitely happens). This has the following effects: (1) In the 1st proposed solution, as `encode()` is called first and we can make all adjustments for making our data JSON-serializable there, at this later point, calling `iterencode()` will not result in an error, any more. (2) In the 2nd proposed solution, as we reimplemented `iterencode()`, our data will be made JSON-serializable at this point. **Update**: There is actually a third solution, thanks to the comment of @AbdulAzizBarkat: we can override the [`default()`][3] method. However, we have to make sure that we hand over an object type for serialization that is not handled by the regular encoder, or otherwise we will never reach the `default()` method with it. In the given code, we can for example pass the `Agent` instance itself to `dump()` or `dumps()`, rather than its dictionary field `G`. So we have to make two adjustments: 1. Adjust `memorize()` to pass `self`, rather than `self.G`, e.g. like so: ```python def memorize(self): with open("memory.json", "w") as w: json.dump(self, w, cls=JSONSerializer) ``` 2. Adjust `JSONSerializer.default()` to handle the `Agent` instance, e.g. like so (we won't need `encode()` and `iterencode()`, any more): ```python class JSONSerializer(json.JSONEncoder): def default(self, obj): if isinstance(obj, Agent): new_obj = {} for key in obj.G.keys(): new_key = ("%d:%d" % key) if isinstance(key, tuple) else key new_obj[new_key] = obj.G[key] return new_obj # Return the adjusted dictionary return super().default(obj) ``` Final side note: In the first two solutions, the keys of the original dictionary are altered. You probably don't want to have this as actually your instance should not change just because you dump a copy of it. So you might rather want to create a new dictionary with the altered keys and original values. I took care of this in the 3rd solution. [1]: https://github.com/python/cpython/blob/6c8ac8a32fd6de1960526561c44bc5603fab0f3e/Lib/json/__init__.py#L169 [2]: https://stackoverflow.com/questions/72931719/json-serializer-class-why-json-dumps-works-while-json-dump-does-not/72932299#comment137929561_72932299 [3]: https://docs.python.org/3/library/json.html#json.JSONEncoder.default
I have the following three tables in a mysql database: grades: id st_id Q1 Q1 ------------------------------- 1 20001 93 89 2 20002 86 84 3 20003 89 92 4 20001 93 89 5 20002 86 84 6 20003 89 92 ------------------------------- subjects: id subject yr ------------------------------- 1 English 2023 2 Math 2023 3 Science 2023 ------------------------------- grades_subject: sbj_id st_id grd_id ---------------------------- 1 20001 20001 1 20002 20002 1 20003 20003 2 20001 20001 2 20002 20002 2 20003 20003 ---------------------------- The grades table containes an id (primary key) student_id and quiz scores. A student_id can appear multiple times in this table. The Subjects table is a simple list of subjects with a primary key. The grades_subject table links the two with a subject id, grade id (The st_id links another table with student information). All three are a primary keys. As you can see, a subject id can appear many times in this table as each student in the grades table can have multiple subjects. 20001 appears twice, once with subject id 1 and again with subject id 2 etc. Each subject id can also appear numerous times as numerous student_ids in the grades table can share one subject. Im tyring to get all records in the grades table, grouped by subject id. So the result would be: sbj_id 1...then all the students in that class with their respective grades. sbj_id 2... and so one for all subjects. I have tried various solutions from this site and many combinations of different types of joins, groupings and also used select distinct. I either get duplicate values, or the correct records in the grades table but only 2 subject_ids, or student grades getting repeated for each subject and other inaccurate results.I have also tried subqueries. This is the closest I have gotten to the correct results (I understand I do not neet the group by grades_subject.sbj_id in the below query, its just to demonstrate that it works): `SELECT grades.*, grades_subject.sbj_id FROM grades JOIN grades_subject ON grades.st_id = grades_subject.grd_id where grades_subject.sbj_id = 49 group by grades_subject.sbj_id, grades_subject.grd_id` It results in all the scores for all students in that class which demonstrates that with my current setup I should be able to get what I am looking for with the right query or grouping. When I remove the where clause, I should get each sbj_id, and then all students in that subject with their scores, then the next subject etc. However, it will retrieve the scores for the first student in the subject, then duplicate those results for all other students in that subject as shown below: sbj_Id | grd_id | Q1 | Q2 | .... '1', '20001', '50', '80', '1', '20001', '50', '80', '1', '20001', '50', '80', '2', '20002', '80', '85', '2', '20002', '80', '85', '2', '20002', '80', '85', Select Distint does not work, various join types do not work, selecting and grouping by ids in the grades table does not work including the primary id. Instead of listing everything I have tried that does not work... How I can get my desired results with my current set up without changing my table setup as other tables and coding are built on it. The set up works well with all other types of queries that I need except when Im trying to get all student grades accross all subjects. If I must change the set up, please ellaborate on the simplest way. Thank you.
I have Blazor page where I want to make a to-do list that updates either when a button is pressed, or when the user hits enter. I want "enter" and the button to do the same action (adding what I've typed into the box to my todo list. Right now 'enter' works, but I have to hit enter twice. I only want to have to hit it once. The button works as intended. ``` <input placeholder="Text Here" type="text" @onkeydown="@Enter" @bind="newTodo" /> <button @onclick="AddTodo">Add todo</button> @code { private string newTodo; private IList<TodoItem> todos = new List<TodoItem>(); private void AddTodo() { // Todo: Add the todo if (!string.IsNullOrWhiteSpace(newTodo)) { todos.Add(new TodoItem { Title = newTodo }); newTodo = string.Empty; } } public void Enter(KeyboardEventArgs e) { if (e.Key == "Enter") { // Todo: Add the todo if (!string.IsNullOrWhiteSpace(newTodo)) { todos.Add(new TodoItem { Title = newTodo }); newTodo = string.Empty; } } } } <ul> @foreach (var todo in todos) { <li> <input type="checkbox" @bind="todo.IsDone" /> <input @bind="todo.Title" /> </li> } </ul> ``` I've tried removing @onkeydown="@Enter", but then obviously nothing fires but the button and if (e.Key == "Enter") { AddTodo() } I was hoping the later would skip some step that is requiring an extra input, but it made me double paste the code there.
Why do I have to double click enter on Blazor?
|html|c++|list|button|blazor|
null
Given a **host** compiler that supports it, you can use `std::bit_cast` in CUDA C++20 **device** code to initialize a `constexpr` variable. You just need to tell nvcc to make it possible by passing [`--expt-relaxed-constexpr`][1]. [1]: https://docs.nvidia.com/cuda/cuda-compiler-driver-nvcc/index.html#expt-relaxed-constexpr-expt-relaxed-constexpr
Want to understand the difference between System and Integration Testing. Are they both same? What are the key areas the testing is different. Which precedes first, Is Integration testing or System Testing. Appreciate if someone clarify in detail
What is the difference between System Testing and Integrated Testing?
|testing|
null
Maybe you can achieve this using ***dplyr*** and ***rowwise()*** operation to calculate the mean closeness for each row based on the friendship type specified. Here's how you can do it: data2 <- data %>% rowwise() %>% mutate(mean_c = mean(c(friend1_closeness_friend2, friend1_closeness_friend3, friend2_closeness_friend3)[c(friendshipType_1, friendshipType_2, friendshipType_3) == "C"], na.rm = TRUE)) the mean_c column represents the mean closeness among friends categorized as type "C" for each participant. Hope it helps you!
Why saveUninitialized is set to FALSE but the session still saved into database?
|node.js|express|express-session|connect-mongo|
“camera.init_buffers(2);” try a larger buffer size here.
### Error I was getting this when I tried to start the rails server: ```none rails server /Users/st/.rbenv/versions/3.2.1/lib/ruby/gems/3.2.0/gems/bootsnap-1.11.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:30:in `require': dlopen(/Users/st/.rbenv/versions/3.2.1/lib/ruby/gems/3.2.0/gems/pg-1.3.5/lib/pg_ext.bundle, 0x0009): Library not loaded: /opt/homebrew/opt/postgresql@14/lib/postgresql@14/libpq.5.dylib (LoadError) Referenced from: <C859835A-2D0F-3B4A-BFAB-2AD961F6197B> /Users/st/.rbenv/versions/3.2.1/lib/ruby/gems/3.2.0/gems/pg-1.3.5/lib/pg_ext.bundle Reason: tried: '/opt/homebrew/opt/postgresql@14/lib/postgresql@14/libpq.5.dylib' (no such file), '/System/Volumes/Preboot/Cryptexes/OS/opt/homebrew/opt/postgresql@14/lib/postgresql@14/libpq.5.dylib' (no such file), '/opt/homebrew/opt/postgresql@14/lib/postgresql@14/libpq.5.dylib' (no such file), '/usr/local/lib/libpq.5.dylib' (mach-o file, but is an incompatible architecture (have 'x86_64', need 'arm64')), '/usr/lib/libpq.5.dylib' (no such file, not in dyld cache) - /Users/st/.rbenv/versions/3.2.1/lib/ruby/gems/3.2.0/gems/pg-1.3.5/lib/pg_ext.bundle from /Users/st/.rbenv/versions/3.2.1/lib/ruby/gems/3.2.0/gems/bootsnap-1.11.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:30:in `require' from /Users/st/.rbenv/versions/3.2.1/lib/ruby/gems/3.2.0/gems/pg-1.3.5/lib/pg.rb:49:in `block in <module:PG>' from /Users/st/.rbenv/versions/3.2.1/lib/ruby/gems/3.2.0/gems/pg-1.3.5/lib/pg.rb:37:in `block in <module:PG>' from /Users/st/.rbenv/versions/3.2.1/lib/ruby/gems/3.2.0/gems/pg-1.3.5/lib/pg.rb:42:in `<module:PG>' from /Users/st/.rbenv/versions/3.2.1/lib/ruby/gems/3.2.0/gems/pg-1.3.5/lib/pg.rb:6:in `<main>' from /Users/st/.rbenv/versions/3.2.1/lib/ruby/gems/3.2.0/gems/bootsnap-1.11.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:30:in `require' from /Users/st/.rbenv/versions/3.2.1/lib/ruby/gems/3.2.0/gems/bootsnap-1.11.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:30:in `require' from /Users/st/.rbenv/versions/3.2.1/lib/ruby/gems/3.2.0/gems/bundler-2.3.19/lib/bundler/runtime.rb:60:in `block (2 levels) in require' from /Users/st/.rbenv/versions/3.2.1/lib/ruby/gems/3.2.0/gems/bundler-2.3.19/lib/bundler/runtime.rb:55:in `each' from /Users/st/.rbenv/versions/3.2.1/lib/ruby/gems/3.2.0/gems/bundler-2.3.19/lib/bundler/runtime.rb:55:in `block in require' from /Users/st/.rbenv/versions/3.2.1/lib/ruby/gems/3.2.0/gems/bundler-2.3.19/lib/bundler/runtime.rb:44:in `each' from /Users/st/.rbenv/versions/3.2.1/lib/ruby/gems/3.2.0/gems/bundler-2.3.19/lib/bundler/runtime.rb:44:in `require' from /Users/st/.rbenv/versions/3.2.1/lib/ruby/gems/3.2.0/gems/bundler-2.3.19/lib/bundler.rb:188:in `require' from /Users/st/rails/checkeasy/config/application.rb:7:in `<main>' from /Users/st/.rbenv/versions/3.2.1/lib/ruby/gems/3.2.0/gems/bootsnap-1.11.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:30:in `require' from /Users/st/.rbenv/versions/3.2.1/lib/ruby/gems/3.2.0/gems/bootsnap-1.11.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:30:in `require' from /Users/st/.rbenv/versions/3.2.1/lib/ruby/gems/3.2.0/gems/railties-7.0.2.4/lib/rails/commands/server/server_command.rb:137:in `block in perform' from <internal:kernel>:90:in `tap' from /Users/st/.rbenv/versions/3.2.1/lib/ruby/gems/3.2.0/gems/railties-7.0.2.4/lib/rails/commands/server/server_command.rb:134:in `perform' from /Users/st/.rbenv/versions/3.2.1/lib/ruby/gems/3.2.0/gems/thor-1.2.2/lib/thor/command.rb:27:in `run' from /Users/st/.rbenv/versions/3.2.1/lib/ruby/gems/3.2.0/gems/thor-1.2.2/lib/thor/invocation.rb:127:in `invoke_command' from /Users/st/.rbenv/versions/3.2.1/lib/ruby/gems/3.2.0/gems/thor-1.2.2/lib/thor.rb:392:in `dispatch' from /Users/st/.rbenv/versions/3.2.1/lib/ruby/gems/3.2.0/gems/railties-7.0.2.4/lib/rails/command/base.rb:87:in `perform' from /Users/st/.rbenv/versions/3.2.1/lib/ruby/gems/3.2.0/gems/railties-7.0.2.4/lib/rails/command.rb:48:in `invoke' from /Users/st/.rbenv/versions/3.2.1/lib/ruby/gems/3.2.0/gems/railties-7.0.2.4/lib/rails/commands.rb:18:in `<main>' from /Users/st/.rbenv/versions/3.2.1/lib/ruby/gems/3.2.0/gems/bootsnap-1.11.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:30:in `require' from /Users/st/.rbenv/versions/3.2.1/lib/ruby/gems/3.2.0/gems/bootsnap-1.11.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:30:in `require' from bin/rails:4:in `<main>' ``` ### Solution The solution was really easy: uninstall and reinstall the `pg` (postgres) ruby gem for that rails app: ```sh gem uninstall pg ``` then reinstall it ```sh bundle install ``` now `rails server` works!
I am not a pro at server administration, however, I can install the latest version of ImageMagick 7.1.1 and Imagick 3.7.0 in a server which is not controlled by Plesk. But, I am using an AWS instance which is controlled by Plesk. The current version of ImageMagick is 6.9 and Imagick 3.7.0 in my Plesk server. But, I want to install the latest version of ImageMagick 7.1.1, as some of my website needs the new version. But, I don't know how to do it in Plesk server. How can purge/uninstall the current one and How can I install the New one and compile it with PHP? Is there anyone who can provide me with the full step by step guide and what commands should I run via SSH? I tried this instruction, but it just didn't work in Plesk Server. ``` sudo apt remove --purge imagemagick ``` ``` sudo apt-get update && apt-get install -y -qq \ build-essential chrpath debhelper dh-exec dpkg-dev g++ ghostscript gsfonts libbz2-dev \ libdjvulibre-dev libexif-dev libfftw3-dev libfontconfig1-dev libfreetype6-dev \ libjpeg-dev liblcms2-dev liblqr-1-0-dev libltdl-dev liblzma-dev libopenexr-dev \ libpango1.0-dev libperl-dev libpng-dev librsvg2-bin librsvg2-dev libtiff-dev libwebp-dev \ libwmf-dev libx11-dev libxext-dev libxml2-dev libxt-dev pkg-config pkg-kde-tools zlib1g-dev ``` ``` git clone https://github.com/ImageMagick/ImageMagick.git ImageMagick-7.1.1 cd ImageMagick-7.1.1 ./configure --with-rsvg --with-modules make sudo make install sudo ldconfig /usr/local/lib ``` ``` git clone https://github.com/Imagick/imagick cd imagick phpize && ./configure make make install ``` I have also added **extension=imagick.so** into my php.ini
How can I install ImageMagick and Imagick latest in a Plesk server
|imagemagick|imagick|
null
Please note that it could be that AEC works but is unable to handle your environment/setups - for example very long echo tail. Please see the following post https://solicall.com/analyze-the-echo-path-yourself/
{"Voters":[{"Id":1159478,"DisplayName":"Servy"},{"Id":2756409,"DisplayName":"TylerH"},{"Id":1974224,"DisplayName":"Cristik"}]}
> **Note** that: To access user information, you need to generate access token by passing **`User.Read.All`** scope. Created a Microsoft Entra ID application: ![enter image description here](https://i.imgur.com/s5BXlPW.png) Generated **access token** by using below endpoint: ```json https://login.microsoftonline.com/common/oauth2/v2.0/authorize? &client_id=ClientID &response_type=token+id_token &redirect_uri=https://jwt.ms &response_mode=fragment &scope=openid offline_access User.Read.All &state=12345 &nonce=12345 ``` ***Access and ID tokens generated successfully:*** ![enter image description here](https://i.imgur.com/3J0BvKO.png) If you make use of ID token to access user information you will get **`401`** error, hence **make use of access token to fetch user details**. Decode the access token and make sure that the **aud** is Microsoft Graph and **`User.Read.All`** scope is present: ![enter image description here](https://i.imgur.com/XeC1JAd.png) Pass the above access token, and **I am able to access token user information successfully**: ```json https://graph.microsoft.com/v1.0/users?$select=DisplayName,EmployeeId,employeeHireDate,employeeLeaveDateTime,employeeType ``` ![enter image description here](https://i.imgur.com/YMAxYVl.png)
Many to Many relationship get all grouped records
|mysql|sqlalchemy|mysql-python|