instruction stringlengths 0 30k ⌀ |
|---|
null |
In some cases, this is because Pycharm scans and indexes the PYTHONPATH. I figured out that some shared script I was running got changed by some nincompoop (may his severed head soon decorate our moat) and the /homes directory got into the PYTHONPATH.
How to get it out:
Go to **File->Settings->Project:[your project]->Project Interpreter**
On the right hand side you'll see a cogwheel, click it, then select **Show all...**
In the next window, your environment will be selected. There are a few icons on the right hand side of this window, one of them is a directory tree. Click it.
You'll find a list of all interpreter paths. Remove the directory that is causing your problem, dance a little victory dance, and resume work.
|
How can I outsource worker processes within a for loop and then merge them again in node.js? |
|node.js|multithreading|node-worker-threads| |
I'm attempting to display a list of movies on a website using Jinja2 (a template engine for Python) and Bootstrap (a front-end framework). However, I'm having difficulty getting the movie cards to display correctly.When trying to display the movie cards using Jinja2 and Bootstrap, the cards aren't being displayed as expected. I'm facing difficulties in correctly displaying the background image of the card, as well as ensuring that the movie information is displayed clearly and organized.
```
{% extends 'base.html' %}
{% block content %}
<h2 style="text-align:center;">List of Movies</h2>
<hr>
<div class="row">
{% for movie in movies %}
<div class="col-md-3">
<div class="card" style="width: 18rem;">
<img src="http://image.tmdb.org/t/p/w500{{movie.backdrop_path}}" class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">{{movie.title}}</h5>
<p class="card-text">{{movie.overview}}</p>
<hr>
<h4>Average Rating<span class="badge bg-secondary">{{movie.vote_average}}</span></h4>
</div>
</div>
</div>
{% endfor %}
</div>
{% endblock content %}
```
Checking if the URL of the movie's background image is correct and accessible.
Ensuring that all Bootstrap classes are being applied correctly.
Verifying that the movies variable is being passed correctly to the template.
Any help or suggestions would be greatly appreciated! Thank you! |
Displaying a Movie List on a Website Using Jinja2 and Bootstrap |
|python|html|web|bootstrap-4| |
null |
> I would expect both queries reusing the same plan, hence, pointing to the same plan_handle. Is my expectation incorrect?
Your expectation is incorrect. When you hard-code where-clause values, the literal values are available at the time the plan is optimized, and so the different queries may get different plans.
> If you don't explicitly build parameters into the design of your applications, you can also rely on the SQL Server Query Optimizer to automatically parameterize certain queries by using the default behavior of simple parameterization. Alternatively, you can force the Query Optimizer to consider parameterizing all queries in the database by setting the PARAMETERIZATION option of the ALTER DATABASE statement to FORCED.
[Query processing architecture guide][1]
[1]: https://learn.microsoft.com/en-us/sql/relational-databases/query-processing-architecture-guide?view=sql-server-ver16 |
Initialization: We have two sorted arrays, A and B, and we're merging them into a single sorted array, C.
The idea of the merge function is:
1.We iterate through both arrays simultaneously using two indexes, one for each array.
While both arrays have elements remaining, we compare the elements at the current index. The smaller element is appended to the combined array, C.
We increase the index of the array from which we took the smaller element and increase the index of array C.
2. if array A reaches its end before B array, we know that the remaining elements in the other array are already sorted. Therefore, we simply copy the remaining elements from that array into C.
This is done in a separate loop after the main merge loop.(this is the second while loop)
3. The third while loop does the same as 2 but checks the opposite. (if B reaches the end before A ).
hope i helped, good luck in your exam! |
null |
First, some observations:
1. The string size is exponential in n so a(n) takes 10000 bits. The largest number type in C++ is uint64_t with 64 bits.
2. Luckily, the restriction on k means we only have to consider the first 10^15 digits, which is 35 bits and thus fits in a uin64_t.
3. a(49) is the last digit string whose size is below 10^15.
Next, the trivial case: if k <= d(n), where d(n) counts digits of the number n we can just read off the answer.
Then, for n > 50 we can safely assume the wanted digit must reside in the first branch of a(n-1) as a(50) and up no longer fit in 10^^15. We must take care to not index into the *n* prefix, so:
solution(k, n) | n > 50 = solution(k - d(n), n-1)
Once n <= 50, k might also reach the *second* branch of a(n-1). Thus:
solution(k, n) | n <= 50 && k - d(n) <= a(n-1) = solution(k - d(n), n-1)
| otherwise = solution(k - a(n-1) - d(n), n-1)
All that remains to make this efficient is to precalculate a(n) up to 50.
Implementing this in C++ is left as an exercise for the reader. |
null |
null |
Some examples of how to query a json data type field:
```sql
SELECT * FROM users
WHERE JSON_EXTRACT(meta_data, "$.first_name") = 'bob';
SELECT * FROM users
WHERE JSON_EXTRACT(meta_data, "$.age") IS NOT NULL;
SELECT * FROM users
WHERE JSON_EXTRACT(meta_data, "$.accepted_policy") = true;
```
**With mysql 5.7.9 +**
You can also just do this (shortcut for JSON_EXTRACT):
```sql
SELECT * FROM users
WHERE meta_data->"$.first_name" = 'bob'
```
You might notice your json data results are "quoted". You could use JSON_UNQUOTE, or you could use this, which is a shortcut of JSON_EXTRACT & JSON_UNQUOTE:
```sql
SELECT meta_data->>"$.first_name" FROM users
WHERE meta_data->>"$.first_name" IS NOT NULL
```
And to select data from within sub objects:
```sql
SELECT meta_data->>"$.address.tel" FROM users
WHERE meta_data->>"$.address.street" = "123 Main St"
```
docs: https://dev.mysql.com/doc/refman/5.7/en/json-search-functions.html |
null |
null |
null |
null |
null |
I'm not sure that Excel keeps track of the filename, I believe it just gets the image out of the file.
In order to test this, I have created an empty Excel sheet and inserted a picture, using the feature you mentioned. The name of the file was "350450_Something.jpeg". Then I saved the Excel file.
Afterwards I unzipped the Excel file and searched for "350450" in the file, but I didn't find anything (WSL Linux `find` command):
find ./ -type f -exec grep "350450" {} /dev/null \;
If you really need this, I would advise you to write a macro, using a `FileDialog` (or an `OpenFileDialog`), and call the "Place in cell" Excel feature from your macro. That way, you will have full control of the filename. |
I didn't see any examples of this so I am wondering if this is a bad practice to extend DAG class.
Is it a bad practice and why, if it is?
Example of where I can see this useful follows...
Let's say we have a number of DAGs which all share the same behaviour: calling a specific function as a very last thing, regardless of success or failure. This function could be something like invoking some external API, for instance.
My idea to approach this would be something along these lines:
- extend the DAG class creating a new class DAGWithFinishAction
- implement on_success_callback and on_failure_callback in DAGWithFinishAction to do what I wanted to achieve
- use the new class in ```with DAGWithFinishAction(dag_id=..., ...) as dag: ...```
- schedule tasks in each of implementing DAGs
- expect that each of those DAGs call it's success/failure callbacks after all tasks are finished (in any state)
Is there anything wrong with this approach?
I couldn't find anything similar which makes me believe I am missing something.
class DAGWithFinishAction(DAG):
def __init__(self, dag_id, **kwargs):
self.metric_callback = publish_execution_time
on_success_callback = kwargs.get("on_success_callback")
if on_success_callback is None:
on_success_callback = self.metric_callback
else:
if isinstance(on_success_callback, list):
on_success_callback.append(self.metric_callback)
else:
on_success_callback = [on_success_callback, self.metric_callback]
kwargs["on_success_callback"] = on_success_callback
super().__init__(dag_id, **kwargs)
The code above works but I am still not sure if this is something that should be avoided or is it a legitimate approach when designing DAGs. |
Google Maps not displaying in Flutter app despite successful API hits |
|flutter|dart|google-maps| |
null |
With option `enable_events=True` in your `sg.Radio` elements to generate event when clicked, or it won't generate event when you click on them and no update for disabled state of the Input element.
```python
import PySimpleGUI as sg
sg.theme('DarkBlue')
layout =[
[sg.Radio('Yes', 'g', enable_events=True, key=("Radio", 1)),
sg.Radio('No', 'g', enable_events=True, key=("Radio", 2))],
[sg.InputText('3', enable_events=True, key='-S_Window-')],
]
window = sg.Window('Title', layout)
while True:
event, values = window.read()
if event == sg.WIN_CLOSED:
break
elif isinstance(event, tuple) and event[0] == "Radio":
disabled = (event[1]==2)
window['-S_Window-'].update(disabled=disabled)
window.close()
``` |
If the line is `#pod 'GoogleMobileVision/FaceDetector'` it means you or someone else commented out the pod. It won't be installed.
Viewing the `podfile` in Xcode will show the item dimmed. e.g This spec will only install `Purchases`:
[![enter image description here][1]][1]
Change the line to `pod 'GoogleMobileVision/FaceDetector'`.
then `pod install` again.
[1]: https://i.stack.imgur.com/lQUT6.png |
I am looking for a way to use a hot key 's' to capture repeated screenshots. When the script originally runs, I do not want any screenshots being captured, but when I press 's' I want screenshots being recorded at a designated time interval. When I press 's' again I want the screenshots to stop being recorded.
Here is my current script, I have been able to make this work when taking in a video and using Tkinter but in terms of screenshotting the screen based on a toggle switch, I have only gotten it to work when the script screenshots already.
```
import os
import numpy as np
import cv2
from mss import mss
from datetime import datetime
import time
def main():
capturing = False
# Create output directory
output_dir = "output"
os.makedirs(output_dir, exist_ok=True)
capture_number = 0
# Initialize screen capture
with mss() as sct:
monitor = sct.monitors[1] # Adjust the monitor index as needed
interval = 0.1 # Capture interval (10 times per second)
try:
print("Press 's' to start/stop capturing screenshots...")
while True:
start_time = time.time()
frame = np.array(sct.grab(monitor))
if capturing:
name = os.path.join(output_dir, f"capture{capture_number}.png")
cv2.imwrite(name, frame)
# Check for key press to toggle capturing
if cv2.waitKey(1) & 0xFF == ord('s'):
capturing = not capturing
# Sleep to maintain capture rate
sleep_time = interval - (time.time() - start_time)
if sleep_time > 0:
time.sleep(sleep_time)
capture_number +=1
except KeyboardInterrupt:
pass
if __name__ == '__main__':
main()
```
|
Python: Screenshot toggle switch (no Tkinter) |
Use the `debounce` function from npm packages which will make a delay while the user types before making a request to the API.
const debounceDelay = 300;
const handleDebouncedChange = debounce((event) => {
console.log('Debounced value:', event.target.value);
}, debounceDelay);
<input
type="text"
onChange={(e) => handleDebouncedChange(e)}
/> |
I am making a form using next js 14, I made an actions.ts file there I built a generic method that shows a console log.
[form component][1]
[action.ts][2]
In the form component, loginForm.tsx, in the form tag, I use the action property, and from there, I call the generic method that I made in action.ts
[devtools/network tab/payload][3]
What happened is that, when I clicked on the save button of the form, I observed that in the devtools, in the network tab, a request was reflected, but I saw that in the netowrk tab, in the payload option, all the information in the form fields is displayed.
my doubts are:
Why does the user and password information appear in the devtools -> tab network -> in the payload?
Is that considered a security vulnerability?
Is there any idea on how to prevent it from displaying that information?
I was investigating the topic, apparently it has to do with the html tag <form action={}></form>, but there was no mention of how to solve that detail
[1]: https://i.stack.imgur.com/BX8D2.png
[2]: https://i.stack.imgur.com/48uIs.png
[3]: https://i.stack.imgur.com/FlBp2.png |
Given the following C program (MSVC does not optimize away the "work" for me, for other compilers you may need to add an `asm` statement):
```c
#include <inttypes.h>
#include <stdlib.h>
#define SIZE 10000
typedef struct {
int32_t a, b, c;
} Struct;
void do_work(Struct* data) {
int32_t* a = malloc(sizeof(int32_t) * SIZE),
* b = malloc(sizeof(int32_t) * SIZE),
* c = malloc(sizeof(int32_t) * SIZE);
int32_t* a_ptr = a, * b_ptr = b, * c_ptr = c;
for (size_t i = 0; i < SIZE; i++, a_ptr++, b_ptr++, c_ptr++, data++) {
*a_ptr = data->a;
*b_ptr = data->b;
*c_ptr = data->c;
}
free(a);
free(b);
free(c);
}
int main() {
Struct* data = malloc(sizeof(Struct) * SIZE);
for (size_t i = 0; i < SIZE; i++) {
data[i].a = i;
data[i].b = i;
data[i].c = i;
}
for (int i = 0; i < 500000; i++) {
do_work(data);
}
free(data);
}
```
**Edit:** Disassembly of `do_work()`:
```asm
do_work PROC ; COMDAT
$LN12:
mov QWORD PTR [rsp+8], rbx
mov QWORD PTR [rsp+16], rbp
mov QWORD PTR [rsp+24], rsi
push rdi
sub rsp, 32 ; 00000020H
mov rbx, rcx
mov ecx, 40000 ; 00009c40H
call QWORD PTR __imp_malloc
mov ecx, 40000 ; 00009c40H
mov rsi, rax
call QWORD PTR __imp_malloc
mov ecx, 40000 ; 00009c40H
mov rbp, rax
call QWORD PTR __imp_malloc
mov r10, rsi
lea rcx, QWORD PTR [rbx+8]
sub r10, rax
mov r11, rbp
sub r11, rax
mov rdi, rax
mov r8, rax
mov r9d, 10000 ; 00002710H
npad 6
$LL4@do_work:
mov edx, DWORD PTR [rcx-8]
lea rcx, QWORD PTR [rcx+12]
mov DWORD PTR [r10+r8], edx
lea r8, QWORD PTR [r8+4]
mov eax, DWORD PTR [rcx-16]
mov DWORD PTR [r11+r8-4], eax
mov eax, DWORD PTR [rcx-12]
mov DWORD PTR [r8-4], eax
sub r9, 1
jne SHORT $LL4@do_work
mov rcx, rsi
call QWORD PTR __imp_free
mov rcx, rbp
call QWORD PTR __imp_free
mov rcx, rdi
mov rbx, QWORD PTR [rsp+48]
mov rbp, QWORD PTR [rsp+56]
mov rsi, QWORD PTR [rsp+64]
add rsp, 32 ; 00000020H
pop rdi
rex_jmp QWORD PTR __imp_free
do_work ENDP
```
Here's a godbolt: https://godbolt.org/z/nWTPfKPd6.
(I have a similar program in Rust with the same conclusions).
Intel VTune reports that this program is 63.1% memory bound, and 52.4% store bound, with store latency of 26%. It recommends to search for false sharing, but I fail to see how there could be false sharing here. There is no concurrency, all data is owned by one core, the access patterns should be easily predicted and prefetched. I don't see why the CPU needs to stall on the stores here.
I thought that maybe the low and high bits of the addresses of the three allocations are the same and that causes them to be mapped to the same cache lines, but I remember reading that modern CPUs don't just drop some bits to assign a cache line but do more complex calculations.
Another thought was that maybe after the allocations are freed the CPU is still busy flushing the stores, and in the next run they are assigned the same address (or a close one) by the allocator and that brings problems for the CPU as it has to wait before storing new data. So I tried to not free the allocations, but that caused the code to be much slower.
I'm on Windows 11, laptop Intel Core i9-13900HX, 32 logical cores, 8 Performance Cores and 16 Efficient Cores. |
Yeah you can just promote it to production or add a new release once you got the production. For those who need 20 testers can follow the below way ,
I have created this app called Testers Community to solve the problem of 20 testers for 14 days. You can download the app here
https://play.google.com/store/apps/details?id=com.testerscommunity
What is Testers Community ?
We are a Community anyone can join. Here instead of paying 20-100 bucks for testers we just test our apps among ourselves. We ensure everyone get 20 testers for Free. |
I have an HTML code that I need to send email to certain sectors of a company.
When I use the `.HTMLbody` property with html, a syntax error arises.
The VBA code and the HTML code that I tried to pass to the `.HTMLbody` property.
```vba
Sub enviar_email()
Dim linha As Integer
Dim Objeto_outlook As Object
Dim Email As Object
For linha = 3 To 13
Set Objeto_outlook = CreateObject("Outlook.Application")
Set Email = Objeto_outlook.createitem(0)
texto = "<!DOCTYPE html><html><body><p>Hi All,<br><br>" & vbCrLf & _
"Find in" & vbCrLf & _
"<a href="https://alcoainc.sharepoint.com/sites/GSSFinance/Accoutingprocess/SitePages/Home.aspx?RootFolder=%2Fsites%2FGSSFinance%2FAccoutingprocess%2FShared%20Documents%2F2021%20Chargeback%20%2D%20ADI%27s%2F11%2ENovember%2FEurope%2FNorway&FolderCTID=0x0120000D0C1EF00C57724DB137DE9812EE80D4&View=%7B87CB7C73%2DFB6E%2D415F%2D90A5%2D623BE45360BC%7D">Sharepoint</a> & vbCrLf & _
"ADIs regarding November chargeback entries to be posted in your region.<br>Could you please post the entries in GL by Tuesday(Nov 16th)?<br><br>If you identify any issue that should be adjusted or any remap to be done, please let us know.<br>Definitions:IICS - transactions between different Countries;<br>Intercompany – transactions between different Legal Entities inside the same Country.<br>Intracompany - transactions between the same Legal Entities and the same Countries.<br>Note that all ADIs were created considering EParent rules.<br><br>Below is your help chain:<br>" & vbCrLf & _
"Accounting inquires - Brunorio, Fernanda P.A.; Perna, Denise C.S.<br>Plan inquires - Moreira, Leonardo; Silva, Juliana C.<br>Thank you,<br>Célio Melo.</p></body></html>"
Email.display
Email.To = Cells(linha, 7).Value
Email.cc = Cells(linha, 8).Value
Email.Subject = Cells(linha, 6).Value
Email.HTMLbody = texto 'Cells(3, 4).Value
Next linha
End Sub
```
HTML code I'm trying to move to VBA email body property:
<!DOCTYPE html>
<html>
<body>
<p>Hi All,<br><br>
Find in <a href="https://alcoainc.sharepoint.com/sites/GSSFinance/Accoutingprocess/SitePages/Home.aspx?RootFolder=%2Fsites%2FGSSFinance%2FAccoutingprocess%2FShared%20Documents%2F2021%20Chargeback%20%2D%20ADI%27s%2F11%2ENovember%2FEurope%2FNorway&FolderCTID=0x0120000D0C1EF00C57724DB137DE9812EE80D4&View=%7B87CB7C73%2DFB6E%2D415F%2D90A5%2D623BE45360BC%7D
">Sharepoint</a> ADIs regarding November chargeback entries to be posted in your region.<br>
Could you please post the entries in GL by Tuesday(Nov 16th)?<br><br>
If you identify any issue that should be adjusted or any remap to be done, please let us know.<br>
Definitions:
IICS - transactions between different Countries;<br>
Intercompany – transactions between different Legal Entities inside the same Country.<br>
Intracompany - transactions between the same Legal Entities and the same Countries.<br>
Note that all ADIs were created considering EParent rules.<br><br>
Below is your help chain:<br>
Accounting inquires - Brunorio, Fernanda P.A.; Perna, Denise C.S.<br>
Plan inquires - Moreira, Leonardo; Silva, Juliana C.<br>
Thank you,<br>
Célio Melo.</p>
</body>
</html> |
I am trying to make something like a todolist web with flask, and I am inserting new tasks using a jinja loop in index.html
```
{% for x in data %}
<div class="love">
<button type="button" class="tasks" style="background-color: {{x[1]}};">
{{x[0]}}<i class="{{x[2]}}" id="habitIcons"></i>
</button>
</div>
{% endfor %}
```
and I've add some javascript code to define clicked buttons by adding a ("clicked") class to them
```
window.addEventListener("DOMContentLoaded", (event) => {
const habitBtns = document.getElementsByClassName("habits");
const habitBtnsArray = Array.from(habitBtns);
habitBtnsArray.forEach(element => {
element.addEventListener("click", () => {
element.setAttribute("class", "clicked");
element.removeAttribute("style")
reloadCss()
});
})
})
```
the problem is when the window reloads, all the tasks lose there ("clicked") class and it get replaced by the default ("habits") class as you can see in the html code earlier
what can I do to prevent that from happening keep in mind that I use vanilla javascript
I thought of changing the data base but I relised that I am using vanilla javascript. |
how to control jinja loop using javascript |
|javascript|html|sqlite|jinja2| |
null |
I have a form that upload multiple files and their associated meta data. I would like to dynamically add metadata to each file depending on how many files are selected for upload.
I render a list of Title, Description and Document Type controls based on the amount of files selected.
I can link the document title to the object model but not the description or type. I would really appreciate any assistance.
a Link to my working copy of the solution is : https://try.mudblazor.com/snippet/GamouRctzOwKzYVn |
Dynamically bind control to object in Mudblazor page |
|file-upload|mudblazor|dynamic-controls| |
null |
The query looks like this:
**Datatype for month.ty is text**
```
month.ty LIKE '%2024%'
```
I am trying to make it **get year without having to change it when year ends**. Like get current year.
I have tryied with plus special character:
```
month.ty LIKE '%' + YEAR(current_timestamp) + '%'
```
This way it pops an error what ever I put inside the plus characters.
Error is: **Warning: #1292 Truncated incorrect DOUBLE value: '%'**
Also like this:
```
month.ty LIKE YEAR(CURRENT_TIMESTAMP)
```
**In this case it returns nothing.** But this is probbaby since it does not go into comparing cause there is no wildcard sign '%'.
And also like this:
```
month.ty LIKE '%' + CAST(year(CURRENT_TIMESTAMP) AS varchar) + '%'
```
In this case it throws an error **#1064 - You have an error in your SQL syntax;**
Also tryed:
```
month.ty LIKE '%' + YEAR(GETDATE()) + '%'
```
Throws error **#1558 - Column count of mysql.proc is wrong. Expected 21, found 20. Created with MariaDB 100108, now running 100421. Please use mysql_upgrade to fix this error**
I am not sure if I am missing something or there is some other way for it to work.
XAMPP version is 8.1.6-0
/ Server version: 10.4.21-MariaDB
|
```
p1 = new Promise((res,rej)=>{
console.log("p1 setTimeout");
setTimeout(()=>{
res(17);
}, 10000);
});
p2 = new Promise((res,rej)=>{
console.log("p2 setTimeout");
setTimeout(()=>{
res(36);
}, 2000);
});
function checkIt() {
console.log("Started");
let val1 = this.p1;
console.log("P1");
val1.then((data)=>{console.log("P1 => "+data)});
let val2 = this.p2;
console.log("P2");
val2.then((data)=>{console.log("P2 => "+data)});
console.log("End");
}
checkIt();
```
**My understanding of above written JavaScript code was:**
1: In callback queue, p2's setTimeout will be first and then p1's setTimeout (and they will execute in FIFO manner)
2: Callback queue won't execute before microtask queue
3: In microtask queue, p1's callback function will first and then p2's callback function (and they will execute in FIFO manner)
4: Hence this should be deadlock.
**But instead getting output:**
1: p1 setTimeout
2: p2 setTimeout
3: Started
4: P1
5: P2
6: End
7: (After 2 seconds) P2 => 36
8: (After 10 seconds) P1 => 17
**Doubt:** How 7th and 8th line of output are coming?
I have ran the code and getting output as defined above |
I'm trying to check if a package is installed in a Ubuntu based system.
Running the following in my terminal returns `true` (exit code 0) since I have those packages:
```shell
dpkg --get-selections | grep -wq <package>
```
Where the \<packages\> are the following:
- google-chrome
- okular-extra-backends
- scrcpy
- xserver-xorg-video-vmware
When doing this in a script with `set -o pipefail` enabled, for some reason it fails for some of the packages and sometimes don't?
```shell
#!/usr/bin/env bash
set -eEo pipefail
check_package() {
if ! dpkg --get-selections | grep -wq "$1"; then
echo false
else
echo true
fi
}
check_package google-chrome
check_package okular-extra-backends
check_package scrcpy
check_package xserver-xorg-video-vmware
```
- I tried to remove `-eE` options, but the real culprit is `-o pipefail`
- I test commenting out some of the function calls, when doing so, for some reason sometimes the function echoes `true` an other times echoes `false`. I don't get it. Here's some examples:
---
Example 1
```shell
check_package google-chrome
check_package okular-extra-backends
check_package scrcpy
check_package xserver-xorg-video-vmware
```
Result
```text
false
false
false
true
```
Sometimes the result is this
```text
false
false
true
true
```
---
Example 2
```shell
# check_package google-chrome
check_package okular-extra-backends
check_package scrcpy
check_package xserver-xorg-video-vmware
```
Result
```text
false
true
true
```
Sometimes the result is this
```text
false
false
true
```
What is happening there?
|
Why `set -o pipefail` gives different output even though the pipe is not failing |
|linux|bash|shell| |
null |
<!-- language-all: sh -->
To complement [Prodige69's helpful answer](https://stackoverflow.com/a/78182028/45375):
Another way to **wait _only_ for `msiexec.exe`** (and child processes _synchronously_ launched from it, if any) rather than its entire child process _tree_ (`msiexec.exe` plus any child processes launched _asynchronously_ from it, which is the cause of the problem here) is to use **_direct invocation_ or invocation via `cmd.exe /c`**:
These are ***syntactically easier* alternatives** to using `(Start-Process ... -PassThru).WaitForExit()` or `Start-Process ... -PassThru | Wait-Process`, which also automatically reflect `msiexec`'s process exit code in the [automatic `$LASTEXITCODE` variable](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Automatic_Variables#lastexitcode):
Note: I'm using `msiexec.exe` in the sample commands below, but the same applies analogously to any installer; in your case, with the direct invocation technique, substitute `& $installerFile.FullName` for `msiexec`, with the `cmd.exe /c` technique, substitute `"$($installerFile.FullName)"`
* Using **direct invocation**, via a trick to make the call _synchronous_:
```
# To build an argument list *programmatically*, create an *array*
$installerArguments = '/i', 'sample.msi', '/qn'
# Executes *synchronously*, due to `| Out-Null`
# Process exit code is reported in $LASTEXITCODE afterwards.
# Equivalent of:
# msiexec /i sample.msi /qn | Out-Null
msiexec $installerArguments | Out-Null
```
* Calling **via `cmd /c`**, which allows you to control quoting explicitly, which is required for property values that require _partial_ quoting:
```
# Here, encode all arguments in a *single string*, using embedded double-quoting.
$installerArgumentList = '/i sample.msi /qn PROP="Value with spaces"'
# Executes *synchronously*, due to `cmd /c`
# Process exit code is reported in $LASTEXITCODE afterwards.
cmd /c "msiexec $installerArguments"
```
See [this answer](https://stackoverflow.com/a/50868019/45375) for background information.
|
How to apply double quotes in html code within the body property of emails in VBA? |
null |
You have two primary challenges in your question:
1. separating the space-separated word read into `input`; and
2. storage for each word.
While there are may ways to "tokenize" (separate) input, when wanting space-separated words, a very simple way to do that is to just read with `fgets()` to fill `input` (as you have done) and then simply loop over each word in `input` using `sscanf()` with the `%s` conversion specifier (with a proper *field-width* modifier to protect your array bounds) and using the `%n` pseudo-conversion specifier to capture the number of character read on each call to `sscanf()` so you can capture the next word by providing an `offset` from the beginning of `input`.
Using multiple character arrays to hold each word quickly becomes unwieldy (as I suspect you have found). What if you don't know the number of words you are going to read?
Since you emphasize using a *"simple"* approach, by far the simplest is to use a 2D array of characters where each row holds a word. Now you can simply reference each word by the index for the 2D array (a 2D array actually being a 1D "array-of-arrays" in C - so the first index points to the 1st array, and so on). Here you are limited to reading no more than your *rows* number of words -- but with a reasonable number of rows set, that provides a great deal of flexibility. You must remember to check each time you add a word against the number of rows you have so you don't attempt to add more words to your 2D array than you have rows for.
A slightly more complex approach would be to declare a *pointer-to-array* of characters which would allow you to reallocate storage for more words with the only limit being the amount of memory your computer has. (a pointer-to-array allocation also has the benefit of a single-free)
One step further would be to allocate the exact number of characters needed to hold each word and the exact number of pointers needed to keep track of each word in your collection -- but that gets well beyond your "simple" request. Just know there are more flexible ways you will learn in the future.
*What Is This Simple Approach?*
Before looking at the code, let's think through what you want to do. You will need to:
1. Prompt the user and read the words into `input` using `fgets()`
2. Loop checking that you still have a row available to hold the next word; and
3. Pass `input` to `sscanf()`
- separating the next word with `"%s"` (with appropriate *field-width* modifier) to capture the word (you can use a temporary array to hold the separated word and copy to your array, or you can attempt the read directly into your 2D array providing an index); and
- saving the number of characters `sscanf()` read to process that word with `"%n"` so you add that to the offset within `input` to read the next word on your next call to `sscanf()`.
4. You ALWAYS validate that `sscanf()` (or any function) succeeds before going further and handle any error that may arise,
5. Increment the word count (`nwords`) after successfully adding the word to your 2D array of words; and
6. Add the number of characters used by `sscanf()` to an `offset` variable so you are ready to process the next word.
7. After your loop with `sscanf()` ends, you simply loop `nwords` times outputting each word in the format you desire.
A short bit of code that does that could be:
```c
#include <stdio.h>
#include <string.h>
#define MAXWRDS 64
#define WORDLN 64
#define MAXCHR 1024
int main (void) {
char input[MAXCHR] = "", /* storage for line of input */
words[MAXWRDS][WORDLN] = {""}, /* 2D array of MAXWRDS WORDLN words */
word[WORDLN] = ""; /* temporary storage for each word */
size_t nwords = 0; /* number of words (tokens) read */
int offset = 0,
nchars = 0;
fputs ("input: ", stdout); /* prompt */
/* validate EVERY input */
if (fgets (input, sizeof input, stdin) == NULL) {
return 1;
}
/* Loop over every whitespace separated sequence
* of chars reading into word. Use sscanf() to read
* whitespace separated sequences of chars. Use %n to
* get the number of characters processed in each call to
* sscanf() to provide offset to next word in input.
*
* Do NOT forget field-width modifier to protect word array bounds
* for reading into word and check you read no more than MAXWRDS words.
*/
while (nwords < MAXWRDS &&
sscanf (input + offset, "%63s%n", word, &nchars) == 1) {
strcpy (words[nwords], word); /* copy word to array at nwords index */
nwords += 1; /* increment nwords */
offset += nchars; /* increment offset by no. of chars */
}
putchar ('\n'); /* optional newline before order output */
/* loop over each word stored in words outputting order */
for (size_t i = 0; i < nwords; i++) {
printf ("order %2zu: %s\n", i + 1, words[i]);
}
}
```
Using a `#define` up top for each constant you need provides a convenient place to make a single change should you need to adjust how your code behaves later.
**Example Use/Output**
Compiling the code (ALWAYS with *full-compiler-warnings-enabled*), your code will now do what you want. With the code compiled to the file named `sscanfwordsinput2d`, you can do:
```none
$ ./sscanfwordsinput2d
input: my dog has fleas but my cat has none -- lucky cat!
order 1: my
order 2: dog
order 3: has
order 4: fleas
order 5: but
order 6: my
order 7: cat
order 8: has
order 9: none
order 10: --
order 11: lucky
order 12: cat!
```
If you are using gcc / clang, a good compile string for the code, with full-warnings, would be:
```none
$ gcc -Wall -Wextra -pedantic -Wshadow -Werror -std=c11 -O2 -o sscanfwordsinput2d sscanfwordsinput2d.c
```
If using Microsoft `cl.exe` as your compiler (VS, etc..), then a roughly equivalent compile string would be:
```none
$ cl /W3 /wd4996 /Wx /O2 /Fesscanfwordsinput2d /Tcsscanfwordsinput2d.c
```
Looks things over and let me know if you have questions. |
Don't use boolean indexing. Rather set "A" as index:
```
ddd = {
'A': ['a', 'b', 'c', 'd'],
'X': [100.0, 20.0, 5.0, 2.0],
'Y': [6.0, 2.0, 1.0, 1.0]
}
df = pd.DataFrame(ddd).set_index('A')
lst = [('a', 'b'), ('c', 'd')]
out = [df.loc[x]/df.loc[y] for x, y in lst]
```
Output:
```
[X 5.0
Y 3.0
dtype: float64,
X 2.5
Y 1.0
dtype: float64]
```
Or, index all combinations at once:
```
df = pd.DataFrame(ddd).set_index('A')
lst = [('a', 'b'), ('c', 'd')]
x, y = map(list, zip(*lst))
out = (df.loc[x].div(df.loc[y].values)
.set_axis(lst)
)
```
Output:
```
X Y
(a, b) 5.0 3.0
(c, d) 2.5 1.0
```
*NB. I'm assuming letters in "A" are unique.*
`df`:
```
X Y
A
a 100.0 6.0
b 20.0 2.0
c 5.0 1.0
d 2.0 1.0
``` |
I am working on my auth implementation for a side project of mine and I am stuck trying to authorize the user sensing the httpOnly cookie with the token to each subsequent request after login.
The workflow is the following:
- login req from the FE
- login res from the BE that sets the cookie httpOnly
- POST req from FE where I pass credentials: true
- in the BE I allow for the credentials in cors
- in the BE I have a middleware that takes the access_token from the cookie and does all its logic
BUT the token in the middleware does not arrive, and I think it is because it has not been set in the cookie storage of the browser after the login.
I may be wrong anyway.
This is the response from the BE to the login request:
return res
.cookie("access_token", token, {
httpOnly: true,
// secure: true, // Ensure cookie is sent over HTTPS
secure: false, // Set to false for HTTP (localhost). Use true for HTTPS (production).
path: '/', // Ensures the cookie is available for all paths
sameSite: 'lax', // Helps with CSRF protection; strict is better than lax for security reasons
maxAge: 3600000, // Optional: sets cookie expiry time in milliseconds (1 hour here)
// secure: process.env.NODE_ENV === 'production', // Only use Secure in production
// sameSite: process.env.NODE_ENV === 'production' ? 'strict' : 'lax', // Adjust SameSite for local development
})
.status(200)
.json({
authenticated: true,
token,
result: [{
id: user._id,
username: user.username,
email: user.email,
verified: user.verified
}]
});
while this is just a test to get info from the BE about an user which should send the token in the cookies access_token.
This is the login function
fetch(`${api}/user/get-username`, {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
headers: {
'Content-Type': 'application/json'
},
credentials: 'include', // This ensures cookies are included with the request
redirect: 'follow',
referrerPolicy: 'no-referrer',
body: JSON.stringify(email)
})
.then(res => res.json())
.then(data => console.log('data', data))
In the server I have cors that allow cookies and the domain localhost:3000
const corsOptions = {
origin: process.env.CORS_ORIGIN, // localhost:3000
credentials: true, // Allow cookies
};
app.use(cors(corsOptions));
app.use(express.json());
app.use(cookieParser());
And I implemented a middleware that should take the cookie access_token but it is always undefined:
const checkAuth = async (req, res, next) => {
console.log('req: ', req.cookies);
const token = req.cookies['access_token'];
console.log('tokens: ', token);
As per my understanding I should have the cookie set in the cookie storage after the login, but this is not happening as I only see the access_token in the response header as Set-Cookie: access_token(and the token here).
Is the problem that the cookie is not stored in the cookie storage? If yes why this is not happening? |
I'm trying to write my vector, to realize the function of the one in STL as much as possible.
However when I tried to run a test project, Visual Studio told me that, `const` version of `begin()`, `const` version of `end()`, `cbegin()` and `cend()` trigger `C2373` errors due to redefinitions.
I'm sure I didn't define these methods twice. Here is a minimal version to reproduce these errors.
```cpp
#include <algorithm> //for std::reverse_iterator
template <typename Type>
class vector_iterator;
template <typename Type>
class vector
{
friend class vector_iterator<Type>;
public:
// These alies are used as return type.
using iterator = vector_iterator<Type>;
using const_iterator = const vector_iterator<Type>;
using reverse_iterator = std::reverse_iterator<iterator>;
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
constexpr vector() noexcept{}; // simplified constructor
constexpr vector_iterator<Type> begin() noexcept;
constexpr const vector_iterator<Type> begin() const noexcept; // causes C2373.
constexpr const vector_iterator<Type> cbegin() const noexcept; // causes C2373.
constexpr vector_iterator<Type> end() noexcept;
constexpr const vector_iterator<Type> end() const noexcept; // causes C2373.
constexpr const vector_iterator<Type> cend() const noexcept; // causes C2373.
private:
size_t size_ = 0;
Type* ptr_data_ = nullptr;
};
// non-const begin(), normal
template <typename Type>
constexpr typename vector<Type>::iterator vector<Type>::begin() noexcept
{
return vector_iterator<Type>(ptr_data_);
}
// const begin(), causes "C2373: redefinition; different type modifiers"
template <typename Type>
constexpr typename vector<Type>::const_iterator vector<Type>::begin() const noexcept
{
return const_iterator(ptr_data_);
}
// cbegin(), causes "C2373: redefinition; different type modifiers"
template <typename Type>
constexpr typename vector<Type>::const_iterator vector<Type>::cbegin() const noexcept
{
return const_iterator(ptr_data_);
}
// non-const end(), normal
template <typename Type>
constexpr typename vector<Type>::iterator vector<Type>::end() noexcept
{
return iterator(ptr_data_ + size_);
}
// const end(), causes "C2373: redefinition; different type modifiers"
template <typename Type>
constexpr typename vector<Type>::const_iterator vector<Type>::end() const noexcept
{
return const_iterator(ptr_data_ + size_);
}
// cend(), causes "C2373: redefinition; different type modifiers"
template <typename Type>
constexpr typename vector<Type>::const_iterator vector<Type>::cend() const noexcept
{
return const_iterator(ptr_data_ + size_);
}
// simplified vector_iterator
template <typename Type>
class vector_iterator
{
public:
explicit vector_iterator(Type* ptr) : iterator_ptr_(ptr) {}; // iterator constructor
private:
Type* iterator_ptr_ = nullptr;
};
int main(void)
{
vector<int> tmp; // tries to construct a vector
return 0;
}
```
Visual Studio produce an error list as follows:
|Code |Description |Line (marked in the comments)|
| :------: | :-----------------------------------------------------------------------------------------------: |:------------------------------------:|
|`C2373`|'clb_container::vector<Type,Allocator>::begin': redefinition; different type modifiers |43 |
|`C2373`|'clb_container::vector<Type,Allocator>::cbegin': redefinition; different type modifiers|50 |
|`C2373`|'clb_container::vector<Type,Allocator>::end': redefinition; different type modifiers |64 |
|`C2373`|'clb_container::vector<Type,Allocator>::cend': redefinition; different type modifiers |71 |
The debug log is as follows:
```bash
Build started at 21:51...
1>------ Build started: Project: Development Test, Configuration: Debug x64 ------
1>Development Test.cpp
1>Development Test.cpp(43,63): error C2373: 'vector<Type>::begin': redefinition; different type modifiers
1>Development Test.cpp(21,43):
1>see declaration of 'vector<Type>::begin'
1>Development Test.cpp(50,63): error C2373: 'vector<Type>::cbegin': redefinition; different type modifiers
1>Development Test.cpp(22,43):
1>see declaration of 'vector<Type>::cbegin'
1>Development Test.cpp(64,63): error C2373: 'vector<Type>::end': redefinition; different type modifiers
1>Development Test.cpp(25,43):
1>see declaration of 'vector<Type>::end'
1>Development Test.cpp(71,63): error C2373: 'vector<Type>::cend': redefinition; different type modifiers
1>Development Test.cpp(26,43):
1>see declaration of 'vector<Type>::cend'
1>Done building project "Development Test.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
========== Build completed at 21:51 and took 00.648 seconds ==========
```
I have tried the following steps:
- I commented all the methods mentioned above and recompiled it. Errors disappeared at once.
- Then I uncommented them one by one and found that whenever one of `const` version of `begin()`, `const` version of `end`, `cbegin()` and `cend()` is available, `C2373` would occurred again.
- I passed each of these code snippets to Copilot and Claude-3-Sonnet, respectively, and they found no obvious redefinitions.
- At last, I installed "C++ Clang tools for Windows under Desktop development with C++" with Visual Studio Installer, and configured the test project to use Clang. `C2373` disappeared, and the program compiled normally. However, if I changed the "Platform Toolset" back to the default "Visual Studio 2022(v143)", errors occur again. So I think this problem is probably caused by Visual C++ 2022.
However, as a part of my tiny STL, I hope it can compile normally under most compilers, rather than failing for some inexplicable reason, especially on a platform with many users like Visual Studio, but I still can't find the real problem. |
I´m trying to replicate the following graph:
[![graph][1]][1]
I have a dataset with a timeseries of intensity (4 different loads) and coefficient.
Does anyone know which R function is the best to produce graphs like that?
Thanks
I´ve tried the plotly function but didn´t get the desired result
[1]: https://i.stack.imgur.com/Plksb.png |
null |
I'm trying to replicate the following graph:
[![graph][1]][1]
I have a dataset with a timeseries of intensity (4 different loads) and coefficient.
Does anyone know which R function is the best to produce graphs like that?
I've tried the plotly function but didn't get the desired result
[1]: https://i.stack.imgur.com/Plksb.png |
ok, heres whats wrong with your code
1. after assigning the srcObject of a video element you have to call play
2. in the setInterval function you get the image data in your let statement but you havent drawn anything to the canvas yet, although it would be available in the second iteration
3. when you actually invoke face(4) you do not pass the r variable through to the then function, hence when you use it in the while statement its not defined
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
'use strict';
var timer;
var stream;
document.querySelector('input[value=stop]').onclick = e=>{
clearInterval(timer);
if(stream)stream.getTracks().forEach(track=>track.stop());
}
try {
const w = window,
d = document,
ng = navigator,
id = e => {
return d.getElementById(e)
},
cn = id('lh'),
i = id('i'),
o = id('o'),
cx = cn.getContext('2d', {
willReadFrequently: true
}),
face = r => ng.mediaDevices.getUserMedia({
video: {width:100,height:100}
}).then(s => {
stream=s;
i.srcObject = s;
i.play();
i.onloadedmetadata = e => {
timer=setInterval(() => {
let c = 0,
k = -4,
h = cn.height = i.videoHeight,
w = cn.width = i.videoWidth;
cx.drawImage(i, 0, 0, w, h);
let dt = cx.getImageData(0, 0, w, h),
io = dt.data,
dl = io.length,
R, G, B;
R = G = B = 0;
o.src = cn.toDataURL('image/webp');
var r = 4;
while ((k += r*4) < dl) {
++c;
R += io[k];
G += io[k + 1];
B += io[k + 2]
};
['R', 'G', 'B'].forEach(e1 => {
eval(e1 + '=' + `~~(${e1}/c)`)
});
let rgb = `rgb(${R},${G},${B})`;
d.body.style.background = rgb
}, -1)
}
});
face(4)
} catch (e) {
alert(e)
}
<!-- language: lang-css -->
canvas {
border:1px solid lightgray;
}
video {
border:1px solid lightgray;
}
img {
border:1px solid lightgray;
}
input {
font-size:16px;
padding:5px;
}
<!-- language: lang-html -->
<canvas id=lh></canvas>
<video id=i></video>
<img id=o>
<input type=button value=stop>
<!-- end snippet -->
i added a stop feature so it can be turned off with reloading the page
im afraid that it wont actually run in the stackoverflow website, i think they must have webcam access turned off and wont allow video to play
ive created a much neater version for anyone who visits this page at a later date, it needs a canvas element and its derived 2d context
var stream = await navigator.mediaDevices.getUserMedia({video:true});
var video = document.createElement('video');
video.srcObject = stream;
video.play();
(function update(){
ctx.drawImage(video,0,0,canvas.width,canvas.height);
var img = ctx.getImageData(0,0,canvas.width,canvas.height);
var n = img.data.length;
var r = 0;
var g = 0;
var b = 0;
for(var i=0;i<n;i+=4){
r += img.data[i]/n*4;
g += img.data[i+1]/n*4;
b += img.data[i+2]/n*4;
}//for
document.body.style.background = `rgb(${r},${g},${b})`;
if(abort)return;
requestAnimationFrame(update);
})();
[1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_NOT
[2]: https://stackoverflow.com/questions/22003491/animating-canvas-to-look-like-tv-noise
|
{"OriginalQuestionIds":[54055445],"Voters":[{"Id":8620333,"DisplayName":"Temani Afif","BindingReason":{"GoldTagBadge":"css"}}]} |
I know that the question is tagged with c++14 but it may be interesting to have a version for newer versions of the standard where metaprogramming is a little bit easier (not so obvious in this example though).
Moreover, I also needed to have a range of integers not necessarely bigger than 0, so the following code (for c++20):
```
#include <numeric>
#include <array>
template<typename T, T Min, T Max>
constexpr auto make_integer_range ()
{
static_assert (Max>=Min);
// we create an array filled with the integers from the given [Min,Max] bounds.
constexpr auto arr = []
{
std::array<T, Max-Min+1> a;
std::iota (a.begin(), a.end(), Min);
return a;
} ();
// we create the integer sequence from the content of the array
auto build = [&arr] <std::size_t... Is> (std::index_sequence<Is...>)
{
return std::integer_sequence<T, arr[Is]...>{};
};
return build (std::make_index_sequence<arr.size()>{});
}
// integer sequence of -1,0,1,2,3
constexpr auto myrange = make_integer_range<int,-1,3> ();
int main() {}
``` |
I'm trying to make a button that has an image background and text. The text should be invisible and the bg image should be opaque. When you hover the button, the background should go black and the text appear at the same time, with a fading transition, but I cant get only one to display at a time.
I tried adding the text inside the `tablet` div, seperate to the `code_block` div but it just displays beside the image. Then I tried adding the text inside the `code_block` div and it made the image disappear completely. I know I need to have the text `display` set as `none` until I hover over it, but I'm not sure how to set the display to block when I want it to display.
Here's the HTML:
```
<div class="content_container">
<div class="tablet"><p id="text">Text</p><div id="code_block"></div></div>
<div class="tablet"></div>
<div class="tablet"></div>
<div class="tablet"></div>
</div>
```
And here's the css:
```
.content_container {
display: flex;
justify-content: space-evenly;
}
.tablet {
display: inline-flex;
margin-top: 5vh;
/*Height restraints*/
height: var(--medium);
max-height: var(--med-ub);
min-height: var(--med-small-lb);
/*Width restraints*/
width: var(--med-large);
max-width: var(--med-large-ub);
min-width: var(--med-large-lb);
/*Margins*/
margin-right: 1vw;
margin-left: 1vw;
background-color: var(--primary_colour);
border: solid 1px var(--tirtiary_colour);
border-radius: 1vw;
transition: 1s;
}
#code_block {
opacity: 1;
background-image: url("img/code_pic.png");
background-color: rgba(0,0,0,0.5);
background-size: cover;
background-repeat: no-repeat;
transition: opacity 1s ease;
}
#code_block:hover {
opacity: 0;
transition: opacity 1s ease;
}
.tablet:hover {
width: var(--large);
height: var(--medium);
transition: 1s;
}
#text {
display: none;
}
#text:hover {
display: block;
}
```
|
Practically, there is no difference, especially since you are using immutable `Map`s (as opposed to `MutableMap`). I used Amazon's `corretto-18` to compile your code and inspected the bytecode. Those are the conclusions I got from doing so:
`println(mappings["PL"]!!)` compiles to the following bytecode:
```bytecode
LINENUMBER 19 L0
GETSTATIC MainKt.mappings : Ljava/util/Map;
LDC "PL"
INVOKEINTERFACE java/util/Map.get (Ljava/lang/Object;)Ljava/lang/Object; (itf)
DUP
INVOKESTATIC kotlin/jvm/internal/Intrinsics.checkNotNull (Ljava/lang/Object;)V
ASTORE 0
GETSTATIC java/lang/System.out : Ljava/io/PrintStream;
ALOAD 0
INVOKEVIRTUAL java/io/PrintStream.println (Ljava/lang/Object;)V
```
So it:
1. Accesses the global `mappings` object.
2. Invokes `.get()` on it.
3. Checks if the result is not `null`.
4. Accesses the global `System.out` object.
5. Invokes `.println()` on it by passing the `String` gotten from the map.
In case of `println(mappingsFunc("US")!!)`, we have:
```bytecode
LINENUMBER 20 L1
LDC "US"
INVOKESTATIC MainKt.mappingsFunc (Ljava/lang/String;)Ljava/lang/String;
DUP
INVOKESTATIC kotlin/jvm/internal/Intrinsics.checkNotNull (Ljava/lang/Object;)V
ASTORE 0
GETSTATIC java/lang/System.out : Ljava/io/PrintStream;
ALOAD 0
INVOKEVIRTUAL java/io/PrintStream.println (Ljava/lang/Object;)V
```
which differs only in the first two operations. Instead of accessing any object and calling its method, it simply invokes the `mappingsFunc()` method. Let us inspect what it does exactly:
```bytecode
public final static mappingsFunc(Ljava/lang/String;)Ljava/lang/String;
@Lorg/jetbrains/annotations/NotNull;() // invisible
// annotable parameter count: 1 (invisible)
@Lorg/jetbrains/annotations/NotNull;() // invisible, parameter 0
L0
ALOAD 0
LDC "code"
INVOKESTATIC kotlin/jvm/internal/Intrinsics.checkNotNullParameter (Ljava/lang/Object;Ljava/lang/String;)V
L1
LINENUMBER 9 L1
ALOAD 0
ASTORE 1
ALOAD 1
INVOKEVIRTUAL java/lang/String.hashCode ()I
LOOKUPSWITCH
2177: L2
2217: L3
2556: L4
2718: L5
default: L6
L2
LINENUMBER 12 L2
FRAME APPEND [java/lang/String]
ALOAD 1
LDC "DE"
INVOKEVIRTUAL java/lang/String.equals (Ljava/lang/Object;)Z
IFEQ L6
GOTO L7
L3
LINENUMBER 11 L3
FRAME SAME
ALOAD 1
LDC "EN"
INVOKEVIRTUAL java/lang/String.equals (Ljava/lang/Object;)Z
IFEQ L6
GOTO L8
L4
LINENUMBER 10 L4
FRAME SAME
ALOAD 1
LDC "PL"
INVOKEVIRTUAL java/lang/String.equals (Ljava/lang/Object;)Z
IFEQ L6
GOTO L9
L5
LINENUMBER 13 L5
FRAME SAME
ALOAD 1
LDC "US"
INVOKEVIRTUAL java/lang/String.equals (Ljava/lang/Object;)Z
IFEQ L6
GOTO L10
L9
LINENUMBER 10 L9
FRAME SAME
LDC "Poland"
GOTO L11
L8
LINENUMBER 11 L8
FRAME SAME
LDC "England"
GOTO L11
L7
LINENUMBER 12 L7
FRAME SAME
LDC "Germany"
GOTO L11
L10
LINENUMBER 13 L10
FRAME SAME
LDC "United States of America"
GOTO L11
L6
LINENUMBER 14 L6
FRAME SAME
LDC "Unknown"
L11
LINENUMBER 9 L11
FRAME SAME1 java/lang/String
ARETURN
L12
LOCALVARIABLE code Ljava/lang/String; L0 L12 0
MAXSTACK = 2
MAXLOCALS = 2
```
Lots of code, so let us inspect the only relevant part that we should pay attention to:
```bytecode
L1
LINENUMBER 9 L1
ALOAD 0
ASTORE 1
ALOAD 1
INVOKEVIRTUAL java/lang/String.hashCode ()I
LOOKUPSWITCH
2177: L2
2217: L3
2556: L4
2718: L5
default: L6
L2
LINENUMBER 12 L2
FRAME APPEND [java/lang/String]
ALOAD 1
LDC "DE"
INVOKEVIRTUAL java/lang/String.equals (Ljava/lang/Object;)Z
IFEQ L6
GOTO L7
```
Before analyzing it further, it's worth to note that branches `L3`, `L4` and `L5` are basically identical to `L2` - they just differ in a given String literal.
The above bytecode invokes `String::hashCode()` and then `String::equals` to pick the correct branch.
Which is... basically the same thing as what `Map::get()` does.
In conclusion, those constructs are almost equivalent, with a single exception that the memory consumption and initial creation of the `mapping` object takes some time and memory. A negligible amount, though.
In terms of recommendation, it depends on the scope of the usage. If the functions is local and used in a very limited scope, I would probably stick with the `when` expression. However, if those options are loaded from some external config (and potentially need some precomputation), you ough to use the `Map` approach. |
Try this if it works
spring.servlet.multipart.enabled=true
spring.servlet.multipart.file-size-threshold=2KB
spring.servlet.multipart.max-file-size=200MB
spring.servlet.multipart.max-request-size=215MB
|
I am trying to send a music file from my app to WhatsApp using Apple Share sheet which is UIActivityViewController.
I am able to share the music file but the problem is I cannot add metadata to this. I mean I can share audio with url and it can be open and listen in WhatsApp but I cannot figure out how to add metadata to this url, I want to add title, description and image to my url as Apple Music do, then when shared in WhatsApp you can see some data with the file url, not only the audio file. Is It possible ?
Here is my code :
```
func openShareSheet(shareItem: ShareFile, completion: @escaping (String?) -> Void) {
var item: ShareItem = ShareItem(title: shareItem.title, artist: shareItem.artist, url: shareItem.url, coverImage: UIImage(named: "defaultImage"))
getImage(shareItem.coverImage) { image in
if let image = image {
item.coverImage = image
let itemToShare: [Any] = [
item
]
let activityViewController = UIActivityViewController(activityItems: itemToShare, applicationActivities: nil)
activityViewController.popoverPresentationController?.sourceView = self.navigationController?.navigationBar
activityViewController.excludedActivityTypes = [UIActivity.ActivityType.addToReadingList, UIActivity.ActivityType.assignToContact]
activityViewController.completionWithItemsHandler = { (activityType, completed: Bool, returnedItems: [Any]?, error: Error?) in
if completed {
doSomething()
}
self.deleteFile(filePath: shareItem.url)
completion(nil)
}
self.present(activityViewController, animated: true, completion: nil)
} else {
completion("Image error")
}
}
}
import LinkPresentation
class ShareFile {
var title: String
var artist: String
var url: URL
var coverImage: String
init(title: String, artist: String, url: URL, coverImage: String) {
self.title = title
self.artist = artist
self.url = url
self.coverImage = coverImage
}
}
class ShareItem: UIActivityItemProvider {
var title: String
var artist: String
var url: URL
var coverImage: UIImage?
init(title: String, artist: String, url: URL, coverImage: UIImage?) {
self.title = title
self.artist = artist
self.url = url
self.coverImage = coverImage
super.init(placeholderItem: "")
}
override var item: Any {
return url
}
override func activityViewControllerPlaceholderItem(_ activityViewController: UIActivityViewController) -> Any {
return url
}
override func activityViewController(_ activityViewController: UIActivityViewController, itemForActivityType activityType: UIActivity.ActivityType?) -> Any? {
return url
}
override func activityViewController(_ activityViewController: UIActivityViewController, subjectForActivityType activityType: UIActivity.ActivityType?) -> String {
return title
}
@available(iOS 13.0, *)
override func activityViewControllerLinkMetadata(_ activityViewController: UIActivityViewController) -> LPLinkMetadata? {
let metadata: LPLinkMetadata = LPLinkMetadata()
metadata.title = title
metadata.originalURL = URL(fileURLWithPath: artist)
metadata.url = url
metadata.imageProvider = NSItemProvider(object: coverImage ?? UIImage())
return metadata
}
}```
When I open the share sheet with my code I can set metadata image, title and description as you can see in the following image :
https://i.stack.imgur.com/Ymzec.jpg
This following image is when I share a audio music file from my app to WhatsApp, you can see I can share metadata too.
https://i.stack.imgur.com/3qHK9.jpg
The following image it is almost what I want, it is shared by Apple Music app to WhatsApp, you can see the metadata (image, title and some description text)
https://i.stack.imgur.com/WuVus.jpg
Is it possible to do the same thing in my app please ? |
How to share metadata of an audio url file to a WhatsApp conversation with friends |
|ios|swift|whatsapp|uiactivityviewcontroller|ios-sharesheet| |
@Modifying
@Transactional
@Query("DELETE FROM BusinessTransaction bt WHERE bt.userId.id=:id")
void deleteByUserId(Long id);
For this query I am getting the following error:
> Transaction silently rolled back because it has been marked as rollback-only
In this query `userID` is an object of `User` class joined and mapped with `BusinessTransaction` class, so in the `where` condition I am trying to fetch id of user from `userId.id` and it should be same as `:id` variable.
Can anyone please help me resolve this error?
|
Transaction silently rolled back |
You are trying to call the `stop()` method on a `MediaStream` object like `main_pc["local_audio"]` which is no longer how you are supposed to do do it. Instead, you need to stop all tracks of the local stream along the lines of
```
main_pc["local_audio"].getTracks().forEach(track => track.stop())
```
Once all local tracks have been stopped the webcam light will go off and you need to call getUserMedia again. |
<!-- language-all: sh -->
* Your screenshot is not consistent with your code, because it implies that you passed (a variable containing) either `$null`, or an _empty array_ (`@()`) to the `-ArgumentList` parameter of [`Start-Process`](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/start-process)
* Your code as shown would _technically_ work - in the sense that `Start-Process` would succeed in _launching_ [`msiexec.exe`](https://learn.microsoft.com/en-us/windows/win32/msi/command-line-options), but - as [Tanaka Saito's answer](https://stackoverflow.com/a/77985782/45375) notes - the arguments passed to `msiexec.exe`'s do not form a complete command, due to the absence of an `/x` (uninstallation) argument specifying the target `.msi` file.
* Adding this missing information to `$Parameters` would make your `Start-Process` call work:<sup>[1]</sup>
$Params = @(
'/qn'
'/norestart'
'/x'
'someInstaller.msi' # specify the .msi file here
)
* However, there is a **better way to invoke `msiexec.exe` from PowerShell**, namely in a way that:
* is syntactically simpler, due to using direct invocation.
* automatically reflects the installer's _exit code_ in the [automatic `$LASTEXITCODE` variable](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Automatic_Variables#lastexitcode) (with `Start-Process`, you'd have to add `-PassThru` in order to receive and capture a process-information object whose `.ExitCode` property you'd have to query).
# Executes synchronously due to the `| Write-Output` trick,
# reflects the exit code in $LASTEXITCODE.
msiexec /qn /norestart /x someInstaller.msi | Write-Output
* Note:
* Piping to `Write-Output` is a simple way to ensure _synchronous_ execution of _GUI_-subsystem applications such as `msiexec.exe`: involving the [pipeline](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Pipelines) this way makes PowerShell wait for the application's termination and also reports its exit code.
* There are cases where passing property values to `msiexec.exe` from PowerShell causes problems, namely when a value contains _spaces_ and therefore requires _partial quoting_ (e.g. `FOO="bar baz"`). In that case, you can use the following alternative, via `cmd.exe /c`:
# Executes synchronously,
# reflects the exit code in $LASTEXITCODE.
# '...' encloses the entire msiexec command line
# Use "..." if you need string interpolation, and `" for embedded "
cmd /c 'msiexec /qn /norestart /x someInstaller.msi'
* See [this answer](https://stackoverflow.com/a/50868019/45375) for details.
* Finally, note that `Start-Process -Wait` - unlike direct invocation / invocation via `cmd.exe /c` - technically waits for the entire child process _tree_ to terminate, which can cause apparent hangs if an installer happens to _asynchronously_ launch a child process that is designed to outlive the installer process (`msiexec.exe`) itself - see [this post](https://stackoverflow.com/q/78181214/45375) for an example.
---
<sup>[1] However, due to a [long-standing bug](https://github.com/PowerShell/PowerShell/issues/5576), it is ultimately better to encode all arguments in a _single string_, because it makes the situational need for _embedded_ double-quoting explicit - see [this answer](https://stackoverflow.com/a/76713933/45375).</sup> |
I have a DB of 600 talks on various topics by various speakers.
They are in the format of:
-------------------
Topic 1 (Speaker 1)
Event_type_1 - , Topic 2 (Speaker 2)
Event_type_2 - , Topic 3 (Speaker 3)
Topic 4 (subtopic 1) (Speaker 1)
---------------------
Ideally, I would want to convert the DB to the format of:
Topic 1
Topic 2
Topic 3
Topic 4 (subtopic 1)
---------------
Something like =REGEXEXTRACT(Cell_1,"\(.+\)$") would extract the text within brackets but then it would extract all brackets. Combining with IF for only (Speaker 1, Speaker 2, ... , Speaker N) is possible but clumsy.
Similarly, and IF group at the beginning for the (event_type_1, event_type_2, ... , event_type_N) is also possible but clumsy.
Feels like regex is powerful enough to enable me to do it cleaner but I'm lacking the skill. Would appreciate help and pointers! |
this should work
@Scheduled(cron = "${scheduled.everyThreeHours}")
public void runCleanupSchedule() throws IOException {
...
}
in your **application.properties** add **scheduled.everyThreeHours**
scheduled.everyThreeHours=0 0 */3 * * *
and you can change the value for each environment properties file |
You have to change the `keydown` event in your EventListener to be `input` when you add an event listener to the `numberInput`:
```javascript
numberInput.addEventListener
("input", (e) => {
inputCheck(numberInput.value);
if (e.key === "Enter") {
outputField.textContent = toRoman(numberInput.value);
}
});
```
If you also want to be able to track the `Enter` key:
```javascript
function inputCheck() {
const errorNum = parseInt(numberInput.value)
if (isNaN(errorNum) || !errorNum) {
outputField.textContent = "Please enter a valid number";
return false;
} else if (errorNum < 1) {
outputField.textContent = "Please enter a number greater than or equal to 1";
return false;
} else if (errorNum > 3999) {
outputField.textContent = "Please enter a number less than or equal to 3999";
return false;
} else {
outputField.textContent = "";
return true;
};
}
```
```javascript
numberInput.addEventListener("keyup", (e) => {
if (inputCheck(numberInput.value)) {
convertBtn.style.display = 'block';
if (e.key === "Enter") {
outputField.textContent = toRoman(numberInput.value);
} else {
// pass
}
} else {
convertBtn.style.display = 'none';
}
});
```
The `keydown` event comes _before_ anything is typed in the input box. The `input` event is when something actually is typed in.
Here we add return statements in `inputCheck` to see how the check went, if positive, continue on with calculations, otherwise hide the convert button and disable the option to convert with `Enter`.
|
As you haven't shared your buildable code (ViewA is missing), I am sharing some suggestions to answer your question:
1. Use `@Binding` instead of `Binding<Bool>`.
2. Properly handle navigation with `NavigationStack` and `navigationDestination` to handle navigation (This is out of your question). The version of `NavigationLink` you are using is deprecated.
3. I see that in all of your view you need `isLogged` value. Consider wrapping inside an class object and inject as `@EnvironmentObject` so that you don't have to pass as argument in all of the views. |
Good morning. I am working to build a web app using tabulator and appscripts with a google sheet "database" I guess you would call it. I found a tutorial online and have been following along. There have been a few issues that I have been able to find and fix. However; right now I am working to build the functionality where if you change the web app the google sheet updates in the background. I have (as far as I can tell) followed the tutorial exactly but can't seem to get the functionality to work. I have listed the code below and would appreciate any help.
```
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link href="https://unpkg.com/tabulator-tables/dist/css/tabulator.min.css" rel="stylesheet">
</head>
<body>
<h1>Sequencing Webb App Test</h1>
<br>
<br>
<div id="jsData"></div>
<div id="alerts"></div>
<script type="text/javascript" src="https://unpkg.com/tabulator-tables/dist/js/tabulator.min.js"></script>
<script>
const elements = {}
document.addEventListener("DOMContentLoaded", pageLoad)
function pageLoad(){
elements.alerts = document.getElementById("alerts")
loadData();
}
function loadData(){
google.script.run
.withSuccessHandler((jsData) => {
// if data successfully return
const table = new Tabulator("#jsData", {
layout:"fitDataTable",
//height: 300, // set height of table (in CSS or here), this enables the Virtual DOM and improves render speed dramatically (can be any valid css height value)
data:jsData, //assign data to table
layout:"fitColumns", //fit columns to width of table (optional)
pagination: true,
paginationSize: 25,
paginationSizeSelector:[5, 10, 50],
paginationCounter:"rows",
columns:[ //Define Table Columns
{title:"Date", field:"Date"},
{title:"Requester", field:"Requester"},
{title:"Customer", field:"Customer"},
{title:"Issue Summary", field:"Issue Summar"},
{title:"Additional Information", field:"Additional Information"},
{title:"Indy", field:"Indy"},
{title:"Indy Action", field:"Indy Action"},
{title:"RDO", field:"RDO"},
{title:"RDO Action", field:"RDO Action"},
{title:"Capetown", field:"CTAction"},
{title:"Status", field:"Status"},
{title:"Condition", field:"Condition", width:50, editor:"list", editorParams: {values: ["New","In progress","Complete"]}},
{title:"ID", field:"ID", width:20,hozAlign:"center"},
],
})
// trigger an alert message when the row is clicked
// table.on("rowClick", function(e, row){
// alert("Row " + row.getData().Customer + " Clicked!!!!");
// })
table.on("cellEditied", function(cell){
const id = cell._cell.row.data.ID
const val = cell._cell.value
const field = cell._cell.column.field
// if the codition column is updated in the web app activate the if statement
if(field === "Condition"){
elements.alerts.textContent = "Saving Changes..."
google.script.run
.withSuccessHandler(() => {
elements.alerts.textContent = "Change Saved!"
})
.withFailureHandler((er) => {
elements.alerts.textContent = "Error Saving Changes!"
})
.editID({id: id, val: val});
}
})
// end if data successfully returned
})
.withFailureHandler((er) => {
})
.getData()
}
// var tabledata = [
// {id:1, name:"Oli Bob", age:"12", col:"red", dob:""},
// {id:2, name:"Mary May", age:"1", col:"blue", dob:"14/05/1982"},
// {id:3, name:"Christine Lobowski", age:"42", col:"green", dob:"22/05/1982"},
// {id:4, name:"Brendon Philips", age:"125", col:"orange", dob:"01/08/1980"},
// {id:5, name:"Margret Marmajuke", age:"16", col:"yellow", dob:"31/01/1999"},
// ];
</script>
</body>
</html>
```
```
function getData() {
const mainSS = SpreadsheetApp.getActive();
const mainSheet = mainSS.getSheetByName('Data');
const dataRange = mainSheet.getRange('A1').getDataRegion();
const displayDataRange = dataRange.getDisplayValues();
const headers = displayDataRange.shift();
// console.log(headers);
// console.log(dataRange);
const jsData = displayDataRange.map(r => {
const tempObject = {};
headers.forEach((header, i) => {
tempObject[header] = r[i]
})
return tempObject
})
console.log(jsData)
return jsData
}
// End of getData function
function editID(props){
const mainSS = SpreadsheetApp.getActive();
const mainSheet = mainSS.getSheetByName('Data');
const idCellMatch = mainSheet.getRange("N2:N").createTextFinder(props.id).findNext()
if(idCellMatch === null) throw new Error ("No matching record.")
const recordRowNumber = idCellMatch.getRow()
mainSheet.getRange(recordRowNumber, 13).setValue(props.val)
}
```
The expectation of the code is when I update a column (specifically the Condition column) the data will save and be sent back to the google sheet to be saved there as well. Right now, I can bring up the web app table and change the condition column as expected. However; the changes aren't returning to the google sheet to be saved. |
Tabulator and App Script Tutorial save function not working |
|google-apps-script|tabulator| |
null |
I am using the Kendo UI (2015.3.930) Grid Control and I have a integer textbox in a grid filter row that always as decimal when I apply the filter.
Here is my code:
@(Html.Kendo().Grid((IEnumerable<UiController.Lot>)Model.Lots)
.Name("Grid")
.Columns(columns =>
{
columns.Bound(c => c.LotNumber).Title("Lot No")
.Filterable(ftb =>ftb.ItemTemplate("NumericFilter"));
columns.Bound(c => c.BranchName).Title("Branch Name");
})
.HtmlAttributes(new { style = "height: 530px;" })
.Filterable(ftb => ftb.Mode(GridFilterMode.Row))
.DataSource(dataSource => dataSource
.Server()
.Model(model => { model.Id(p => p.Id); })
)
)
My script section shows:
<script>
function NumericFilter(args) {
args.element.kendoNumericTextBox({
"spinners": false,
"format": "n0",
"decimals": 0,
});
}
</script>
For an Integer value of 10, it shows '10.00' after the applying the filter. Is there a way of showing the value without the decimal portion.
Thanks,
|
null |
I am using the Kendo UI (2015.3.930) Grid Control and I have a integer textbox in a grid filter row that always as decimal when I apply the filter.
Here is my code:
@(Html.Kendo().Grid((IEnumerable<UiController.Lot>)Model.Lots)
.Name("Grid")
.Columns(columns =>
{
columns.Bound(c => c.LotNumber).Title("Lot No")
.Filterable(ftb =>ftb.ItemTemplate("NumericFilter"));
columns.Bound(c => c.BranchName).Title("Branch Name");
})
.HtmlAttributes(new { style = "height: 530px;" })
.Filterable(ftb => ftb.Mode(GridFilterMode.Row))
.DataSource(dataSource => dataSource
.Server()
.Model(model => { model.Id(p => p.Id); })
)
)
My script section shows:
<script>
function NumericFilter(args) {
args.element.kendoNumericTextBox({
"spinners": false,
"format": "n0",
"decimals": 0,
});
}
</script>
For an integer value of 10, it shows '10.00' after the applying the filter. Is there a way of showing the value without the decimal portion. |
Given a json object like this
{
link:"https://www.google.com",
image:"../../assets/images/googleicon.png",
},
And then this in the component
<View>
{info.image &&
<Image source={require(info.image)} />
}
</View>
It just yells at me with "Invalid call". If I pass the the path directly it works, like
`<Image source={require('../../assets/images/googleicon.png')} />`
But I can't do that because my view is mapping several images depending on the item viewed. It's not just one item or the same image for all items. It needs to be dynamic. Everything out there points to regular React solutions with HTML. React Native doesn't have HTML as you know |
How i can repair my redirect in php when my db is completed? |
|php|redirect| |
null |
If you are trying import context directly from sqlalchemy try sqlalchemy.orm |
I'm creating my own links manually within a module of a divi theme, since divi doesn't support three links side by side.
It's supposed to look like this:
[Three side-by-side links](https://i.stack.imgur.com/RZ5iM.png)
But when the screen is resized it looks like this: [Split looking link](https://i.stack.imgur.com/RNPZF.png)
Divi breaks its responsive at certain points and this happens before it gets to the tablet size.
This is the code I've placed in the module's css:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
a.work {
background-color: #b7ad68;
font-size: .5em;
font-family: "helvetica", san-serif;
letter-spacing: 2px;
font-weight: 500;
padding: 10px 20px 10px 20px;
border-radius: 50px;
color: white;
}
a:hover.work {
background-color: #ffffff;
border: solid 2px #b7ad68;
color: #b7ad68;
}
a.podcast {
background-color: #f1b36e;
font-size: .5em;
font-family: "helvetica", san-serif;
letter-spacing: 2px;
font-weight: 500;
padding: 10px 20px 10px 20px;
border-radius: 50px;
color: white;
}
a:hover.podcast {
background-color: #ffffff;
border: solid 2px #f1b36e;
color: #f1b36e;
}
a.speak {
background-color: #e58059;
font-size: .5em;
font-family: "helvetica", san-serif;
letter-spacing: 2px;
font-weight: 500;
padding: 10px 20px 10px 20px;
border-radius: 50px;
color: white;
}
a:hover.speak {
background-color: #ffffff;
border: solid 2px #e58059;
color: #e58059;
}
<!-- language: lang-html -->
<p style="text-align: center;">
<a class="work" href="/work-with-me">
<span style="font-family: ETmodules; font-size: 1.5em; font-weight: 300; padding-top: 10px; position: relative; top: .15em;"></span> WORK WITH ME</a> <a class="podcast" href="/work-with-me"><span style="font-family: ETmodules; font-size: 1.5em; font-weight: 300; position: relative; top: .15em;"></span> PODCAST</a>
<a
class="speak"><span style="font-family: ETmodules; font-size: 1.5em; font-weight: 300;position: relative; top: .15em;"></span> SPEAKING</a>
</p>
<!-- end snippet -->
|
|html|css|button|hyperlink| |
sudo pip3 install pillow --upgrade this worked for me in raspberry pi. pillow version 10.2.0 was installed and solved my error. |
Your question explicitly asks for an MVVM compliant way to handle attached UI events (or UI events in general) in the application view model. There is none. Per definition, the view model must not participate in UI logic. There is no reason for the view model to ever handle UI events. All the event handling must take place in the view.
The following UML diagram shows that the view model has to be view agnostic. That's a crucial requirement of the MVVM design pattern.
[![enter image description here][1]][1]
View agnostic of course means that the view model is not allowed to actively participate in UI logic.
While it is technically possible to handle UI events in the application view model, MVVM forbids that and requires that such events are handled in the application view (see the UML diagram). If you want to implement MVVM correctly because you don't want to allow the UI to bleed into the application, then you must handle such events in the view (in C# aka code-behind aka partial classes).
Copy & Paste are pure *view* operations:
1. They involve the user.
2. They exchange data between two UI elements
3. The event args of a UI event is a `RoutedEventArgs` object.
4. The `RoutedEventArgs` exposes the source **UI** elements (via the sender parameter of the delegate, via the `Source` and `OriginalSource` properties of the event args).
5. The `RoutedEventArgs` enables the handler to directly participate in UI logic (e.g. by marking an event as handled or by cancelling the ongoing UI operation etc.).
6. Routed events are always events that relate to UI interaction or UI behavior in context of UI logic.
7. In general, why would the view model be interested in UI events if there is nothing like a UI or a u ser from the point of view of the view model?
These are all hints that the event should not be handled in the view model. Routed events are *always* events that relate to UI interaction or UI behavior or render logic related - they are declared and raised by UI objects.
The view model must not care about any UI elements e.g. when and how they're changing their size. The `Button.Click` event is the only event that should trigger an operation on the view model. Such elements usually implement `ICommandSource` to eliminate the event subscription. However, there is nothing wrong with handling the `Click` event in code-behind and delegating the operation to the view model from there.
Passing all that UI objects to the view model (via the event args, e.g., the `RoutedEventArgs.Source`) is also a clear MVVM violation.
Participating in UI logic (copy & paste) is another MVVM violation. You must either handle the `Pasting` event in the code-behind of a control or implement property validation by letting your view model class implement `INotifyDataErrorInfo`.
From an UX point of view it is *never* a good idea to swallow a user action.
You must always give feedback so that the user can learn that his action is not supported. If you can't prevent it in the first place e.g. by disabling interaction which is usually visualized by grayed out elements, then you must provide error information that explains why the action is not allowed and how to fix it. Data validation is the best solution.
For example, when you fill in a registration form in a web application and enter/paste invalid data to the input field, your action is not silently swallowed.
Instead, you get a red box around the input field and an error message. `INotifyDataErrorInfo` does exactly the same. **And it does not violate MVVM**.
The generally recommended way to achieve your task of validating the user input is to implement `INotifyDataErrorInfo`. See [How to add validation to view model properties or how to implement INotifyDataErrorInfo][2].
A less elegant but still a valid MVVM solution is to implement the event handling of the `DataObject.Pasting` attached event along with the data validation in the view and cancelling the command from code-behind. Note that this solution can violate several UI design rules. You must at least provide proper error feedback to the user in case the pasted content is not accepted by the application.
For your particular case, you should consider implementing a `NumericTextBox`.
This is also an elegant solution where the input validation is completely handled by the input field. A control can provide data validation by implementing `Binding` validation e.g. defining a `ValidationRule`. You will get a convenient way to show e.g. a red box (customizable) and an error message to the user.
When we categorize a validation in syntactical/formal (e.g., is the input numeric?) and semantical (e.g., is the entered person's age valid?) data validation, then we can implement the syntactical data validation at UI level in the input control. Semantical data validation, where we have to validate the input based on business rules must be implemented in the view model and model where such rules are known or defined to guarantee data integrity. Therefore, validating the input to enforce numeric input is a good candidate for being implemented in the view by the input control.
An example `NumericTextBox` that also handles pasted content:
**NumericValidationRule.cs**
The `ValidationRule` used by the `NumericTextBox` to validate the input. The rule is also passed to the binding engine in order to enable the visual validation error feedback that is built into the framework.
```c#
public class NumericValidationRule : ValidationRule
{
private readonly string nonNumericErrorMessage = "Only numeric input allowed.";
private readonly string malformedInputErrorMessage = "Input is malformed.";
private readonly string decimalSeperatorInputErrorMessage = "Only a single decimal seperator allowed.";
private TextBox Source { get; }
public NumericValidationRule(TextBox source) => this.Source = source;
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
ArgumentNullException.ThrowIfNull(cultureInfo, nameof(cultureInfo));
if (value is not string textValue
|| string.IsNullOrWhiteSpace(textValue))
{
return new ValidationResult(false, this.nonNumericErrorMessage);
}
if (IsInputNumeric(textValue, cultureInfo))
{
return ValidationResult.ValidResult;
}
// Input was can still be a valid special character
// like '-', '+' or the decimal seperator of the current culture
ValidationResult validationResult = HandleSpecialNonNumericCharacter(textValue, cultureInfo);
return validationResult;
}
private bool IsInputNumeric(string input, IFormatProvider culture) =>
double.TryParse(input, NumberStyles.Number, culture, out _);
private ValidationResult HandleSpecialNonNumericCharacter(string input, CultureInfo culture)
{
ValidationResult validationResult;
switch (input)
{
// Negative sign is not the first character
case var _ when input.LastIndexOf(culture.NumberFormat.NegativeSign, StringComparison.OrdinalIgnoreCase) != 0:
validationResult = new ValidationResult(false, this.malformedInputErrorMessage);
break;
// Positivre sign is not the first character
case var _ when input.LastIndexOf(culture.NumberFormat.PositiveSign, StringComparison.OrdinalIgnoreCase) != 0:
validationResult = new ValidationResult(false, this.malformedInputErrorMessage);
break;
// Allow single decimal separator
case var _ when input.Equals(culture.NumberFormat.NumberDecimalSeparator, StringComparison.OrdinalIgnoreCase):
{
bool isSingleSeperator = !this.Source.Text.Contains(culture.NumberFormat.NumberDecimalSeparator, StringComparison.CurrentCultureIgnoreCase);
validationResult = isSingleSeperator ? ValidationResult.ValidResult : new ValidationResult(false, this.decimalSeperatorInputErrorMessage);
break;
}
default:
validationResult = new ValidationResult(false, this.nonNumericErrorMessage);
break;
}
return validationResult;
}
}
```
**NumericTextBox.cs**
```c#
class NumericTextBox : TextBox
{
private ValidationRule NumericInputValidationRule { get; set; }
static NumericTextBox()
=> DefaultStyleKeyProperty.OverrideMetadata(typeof(NumericTextBox), new FrameworkPropertyMetadata(typeof(NumericTextBox)));
public NumericTextBox()
{
this.NumericInputValidationRule = new NumericValidationRule(this);
DataObject.AddPastingHandler(this, OnContentPasting);
}
private void OnContentPasting(object sender, DataObjectPastingEventArgs e)
{
if (!e.DataObject.GetDataPresent(DataFormats.Text))
{
e.CancelCommand();
ShowErrorFeedback("Only numeric content supported.");
return;
}
string pastedtext = (string)e.DataObject.GetData(DataFormats.Text);
CultureInfo culture = CultureInfo.CurrentCulture;
ValidationResult validationResult = ValidateText(pastedtext, culture);
if (!validationResult.IsValid)
{
e.CancelCommand();
}
}
#region Overrides of TextBoxBase
/// <inheritdoc />
protected override void OnTextInput(TextCompositionEventArgs e)
{
CultureInfo culture = CultureInfo.CurrentCulture;
string currentTextInput = e.Text;
// Remove any negative sign if '+' was pressed
// or prepend a negative sign if '-' was pressed
if (TryHandleNumericSign(currentTextInput, culture))
{
e.Handled = true;
return;
}
ValidationResult validationResult = ValidateText(currentTextInput, culture);
e.Handled = !validationResult.IsValid;
if (validationResult.IsValid)
{
base.OnTextInput(e);
}
}
#endregion Overrides of TextBoxBase
private ValidationResult ValidateText(string currentTextInput, CultureInfo culture)
{
ValidationResult validationResult = this.NumericInputValidationRule.Validate(currentTextInput, culture);
if (validationResult.IsValid)
{
HideErrorFeedback();
}
else
{
ShowErrorFeedback(validationResult.ErrorContent);
}
return validationResult;
}
private bool TryHandleNumericSign(string input, CultureInfo culture)
{
int oldCaretPosition = this.CaretIndex;
// Remove any negative sign if '+' pressed
if (input.Equals(culture.NumberFormat.PositiveSign, StringComparison.OrdinalIgnoreCase))
{
if (this.Text.StartsWith(culture.NumberFormat.NegativeSign, StringComparison.OrdinalIgnoreCase))
{
this.Text = this.Text.Remove(0, 1);
// Move the caret to the original input position
this.CaretIndex = oldCaretPosition - 1;
}
return true;
}
// Prepend the negative sign if '-' pressed
else if (input.Equals(culture.NumberFormat.NegativeSign, StringComparison.OrdinalIgnoreCase))
{
if (!this.Text.StartsWith(culture.NumberFormat.NegativeSign, StringComparison.OrdinalIgnoreCase))
{
this.Text = this.Text.Insert(0, culture.NumberFormat.NegativeSign);
// Move the caret to the original input position
this.CaretIndex = oldCaretPosition + 1;
}
return true;
}
return false;
}
private void HideErrorFeedback()
{
BindingExpression textPropertyBindingExpression = GetBindingExpression(TextProperty);
bool hasTextPropertyBinding = textPropertyBindingExpression is not null;
if (hasTextPropertyBinding)
{
Validation.ClearInvalid(textPropertyBindingExpression);
}
}
private void ShowErrorFeedback(object errorContent)
{
BindingExpression textPropertyBindingExpression = GetBindingExpression(TextProperty);
bool hasTextPropertyBinding = textPropertyBindingExpression is not null;
if (hasTextPropertyBinding)
{
// Show the error feedbck by triggering the binding engine
// to show the Validation.ErrorTemplate
Validation.MarkInvalid(
textPropertyBindingExpression,
new ValidationError(
this.NumericInputValidationRule,
textPropertyBindingExpression,
errorContent, // The error message
null));
}
}
}
```
**Generic.xaml**
```xaml
<Style TargetType="local:NumericTextBox">
<Style.Resources>
<!-- The visual error feedback -->
<ControlTemplate x:Key="ValidationErrorTemplate1">
<StackPanel>
<Border BorderBrush="Red"
BorderThickness="1"
HorizontalAlignment="Left">
<!-- Placeholder for the NumericTextBox itself -->
<AdornedElementPlaceholder x:Name="AdornedElement" />
</Border>
<Border Background="White"
BorderBrush="Red"
Padding="4"
BorderThickness="1"
HorizontalAlignment="Left">
<ItemsControl ItemsSource="{Binding}"
HorizontalAlignment="Left">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding ErrorContent}"
Foreground="Red" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Border>
</StackPanel>
</ControlTemplate>
</Style.Resources>
<Setter Property="Validation.ErrorTemplate"
Value="{StaticResource ValidationErrorTemplate1}" />
<Setter Property="BorderBrush"
Value="{x:Static SystemColors.ActiveBorderBrush}" />
<Setter Property="BorderThickness"
Value="1" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:NumericTextBox">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
Padding="{TemplateBinding Padding}">
<ScrollViewer Margin="0"
x:Name="PART_ContentHost" />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsEnabled"
Value="False">
<Setter Property="Background"
Value="{x:Static SystemColors.ControlLightBrush}" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
```
[1]: https://i.stack.imgur.com/v71wU.png
[2]: https://stackoverflow.com/a/56608064/3141792 |
Here is my set up:
Specs:
Tomcat 7.0.109
jdk1.8.0_11
IDEA20232.5
When I enter the 'test5_5' method of this action, it will redirect to a 404 page.
```java
if(NumberUtils.notNullEquals(result.getResult(), 0)){//登录失败
return LOGIN;
}
```
The corresponding configuration file
```xml
<action name="test" class="test" method="test5_5">
<result name="login">${page}</result>
<result name="reg">${page}</result>
<result name="doreg" type="chain">
<param name="namespace">/irdUser/login/opac</param>
<param name="actionName">opacRegist</param>
</result>
<result name="backurl" type="redirect">${backurl}</result>
<result type="redirect">${page}</result>
</action>
```
1.I tried to hardcode the path of the page, but it didn't help.
```java
if(NumberUtils.notNullEquals(result.getResult(), 0)){//登录失败
page = "/fixpage/schools/user/login/opacLogin_irdxc.jsp";
return LOGIN;
}
```
2.I tried to redirect, but it didn't work.
```java
if(NumberUtils.notNullEquals(result.getResult(), 0)){//登录失败
return "ceshi";
}
```
|
|java|jsp|configuration|struts2|actionresult| |
I have an array of `value,location` pairs
```bash
arr=(test,meta my,amazon test,amazon this,meta test,google my,google hello,microsoft)
```
and i want to print the duplicate value, the number/count of them, along with the location
eg
```txt
3 test: meta, amazon, google
2 my: amazon, google
1 this: meta
1 hello: microsoft
```
showing `test` appears 3 times, in `meta`, `amazon`, and `google`
So far this code will print the item and location
`printf '%s\n' "${arr[@]}" | awk -F"," '!_[$1]++'`
```txt
test,meta
my,amazon
this,meta
hello,microsoft
```
and this will print the count, but it's taking in the `value,location` as one value
`printf '%s\n' "${arr[@]}" | sort | uniq -c | sort -r`
```txt
1 my,amazon
1 my,google
1 this,meta
1 test,meta
1 test,google
1 test,amazon
1 hello,microsoft
```
|
Bash: Find duplicates in array, print count with pair |
|arrays|bash|awk|uniq| |
I use GraphQL library `HotChocolate`.
Program.cs:
```
var builder = WebApplication.CreateBuilder(args);
builder.Services
.AddGraphQLServer()
.AddAuthorization()
.AddQueryType<ProductQuery>();
builder.Services.AddDbContext<DpcDatabaseContext>();
// ...
var app = builder.Build();
app.UseRouting();
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapGraphQL();
app.Run();
```
I got my context using constructor injection:
```
public DpcProductDatabaseService(DpcDatabaseContext dpcDatabaseContext)
{
_dpcDatabaseContext = dpcDatabaseContext;
}
```
And how I get products:
```
var res = await _dpcDatabaseContext.Products.FirstOrDefaultAsync(z => z.Id == 1, cancellationToken);
```
And what I get:
```
System.ObjectDisposedException: Cannot access a disposed context instance. A common cause of this error is disposing a context instance that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling 'Dispose' on the context instance, or wrapping it in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.
Object name: 'DpcDatabaseContext'.
at Microsoft.EntityFrameworkCore.DbContext.CheckDisposed()
at Microsoft.EntityFrameworkCore.DbContext.get_ContextServices()
at Microsoft.EntityFrameworkCore.DbContext.get_Model()
at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.get_EntityType()
at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.CheckState()
at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.get_EntityQueryable()
at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.System.Linq.IQueryable.get_Provider()
at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ExecuteAsync[TSource,TResult](MethodInfo operatorMethodInfo, IQueryable`1 source, Expression expression, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ExecuteAsync[TSource,TResult](MethodInfo operatorMethodInfo, IQueryable`1 source, LambdaExpression expression, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.FirstOrDefaultAsync[TSource](IQueryable`1 source, Expression`1 predicate, CancellationToken cancellationToken)
at DpcMicroService.Services.DpcProductDatabaseService.GetProductsByFilterFromDbInternalAsync(FilterInput filter, DpcDatabaseContextBase ctx, CancellationToken cancellationToken) in C:\Beeline\DpcMicroService\DpcMicroService\DpcMicroService\Services\DpcProductDatabaseService.cs:line 86
```
Where Im I wrong? If I create my context manually using `new` it works. But this is not a way out for me. Please, helpme to figure out what is wrong.
I also tried to configure DI in this way:
```
builder.Services.AddDbContext<DpcDatabaseContext>(ServiceLifetime.Transient);
```
It did not have any effect. |
HttpOnly cookie is undefined when reaches the backend middleware |
|reactjs|node.js|cookies|jwt| |
The error occurs when you start a script from the editor that should be started by a trigger.
Therefore, the edited cell range cannot be retrieved and an error occurs.
|