instruction stringlengths 0 30k ⌀ |
|---|
|java|computer-vision|ellipse| |
null |
You can achieve the desire animation using zoom in effect, we can learn it through the flutter doc, or refer below code.
https://api.flutter.dev/flutter/widgets/ScaleTransition-class.html
class _ManageScale extends State<YourClass> with TickerProviderStateMixin{
late final AnimationController controller = AnimationController(
duration: const Duration(seconds:2), //you can put any seconds to show zoom in?out effect
vsync: this,
)..repeat(reverse:true) ;//putting repeat reverse true is make your container big and small in same order
late final Animation<double> _animation = CurvedAnimation(
parent: _controller,
curve:Curve.fastOutSlowIn,
);
//for proper implementation of above stateful widget see doc
now use above animation as a property in your widget which is _animation
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: ScaleTransition(
scale: _animation,
child: const Padding(
padding: EdgeInsets.all(8.0),
child: <Place_Your_Heart_Shape>(size: 150.0),
),
),
),
);
}
|
List of errors:
```
Data: [['Target', 'Hit'], ['Mission', ''], ['Optical/IR', 'Optical'], ['Arm', ''], ['Optical Zoom', 0], ['Digital Zoom', 0], ['Pitch', 0], ['Yaw', 0], ['Reset Camera', 0], ['Target Selection', 0], ['Take Screenshot', 0]]
Data: [['Target', 'Hit'], ['Mission', ''], ['Optical/IR', 'Optical'], ['Arm', ''], ['Optical Zoom', 0], ['Digital Zoom', 0], ['Pitch', 0], ['Yaw', 0], ['Reset Camera', 0], ['Target Selection', 0], ['Take Screenshot', 0]]
invalid load key, '\x00'.
could not find MARK
unpickling stack underflow
could not find MARK
invalid load key, 'A'.
the STRING opcode argument must be quoted
unpickling stack underflow
could not find MARK
unpickling stack underflow
unpickling stack underflow
could not find MARK
unpickling stack underflow
could not find MARK
could not find MARK
could not find MARK
could not find MARK
invalid load key, '\x00'.
unpickling stack underflow
111
unpickling stack underflow
invalid load key, '\x0f'.
6
'utf-8' codec can't decode byte 0x94 in position 4: invalid start byte
unpickling stack underflow
could not find MARK
unpickling stack underflow
unpickling stack underflow
invalid load key, '\x00'.
invalid load key, '\x00'.
unpickling stack underflow
Data: [['Target', 'Hit'], ['Mission', ''], ['Optical/IR', 'Optical'], ['Arm', ''], ['Optical Zoom', 0], ['Digital Zoom', 0], ['Pitch', 0], ['Yaw', 0], ['Reset Camera', 0], ['Target Selection', 0], ['Take Screenshot', 0]]
Data: [['Target', 'Hit'], ['Mission', ''], ['Optical/IR', 'Optical'], ['Arm', ''], ['Optical Zoom', 0], ['Digital Zoom', 0], ['Pitch', 0], ['Yaw', 0], ['Reset Camera', 0], ['Target Selection', 0], ['Take Screenshot', 0]]
```
The data is received continuously through Socket Stream
Here is the code that I have used to read the data from socket:
```
def receive_data(self):
while True:
try:
count_bytes=self.client_socket.recv(1024)
#t=chardet.detect(count_bytes)
#print(t['encoding'])
count = pickle.loads(count_bytes)
print("Data: ", count)
time.sleep(0.1)
except Exception as e:
print(e)
```
The data sent from the other pc is dumped correctly but I am thinking something is wrong at the receiving end. Can someone please solve this issue and let me know how can I rewrite this code.
The solution given on internet are for file handling.
Below should be the continuous output.
Data: [['Target', 'Hit'], ['Mission', ''], ['Optical/IR', 'Optical'], ['Arm', ''], ['Optical Zoom', 0], ['Digital Zoom', 0], ['Pitch', 0], ['Yaw', 0], ['Reset Camera', 0], ['Target Selection', 0], ['Take Screenshot', 0]] |
null |
After you put the list in your question in A:B, and set the target dates (or date strings) in D2:D, you may want to use the formula like what I wrote below:
```
=ARRAYFORMULA(
IF(D2:D<>"",
FILTER(B2:B,
(YEAR(DATEVALUE(A2:A))=YEAR(DATEVALUE(D2:D)))
*
(MONTH(DATEVALUE(A2:A))=MONTH(DATEVALUE(D2:D)))
),
)
)
```
The keys are
1. <a href="https://support.google.com/docs/answer/3093039">`DATEVALUE`</a> to cast strings into date values, so that you can use
2. <a href="https://support.google.com/docs/answer/3093061">`YEAR`</a> and <a href="https://support.google.com/docs/answer/3093052">`MONTH`</a> to extract the year and the month of both the list and the targets alternatively.
However, the solution provided above is correct only in the scenario where you do not have any target out of the range of list. If the scenario is in the case, you may want to use the revised version below:
```
=MAP(D2:D,
LAMBDA(target,
IF(target<>"",
IFERROR(FILTER(B2:B,
(YEAR(DATEVALUE(A2:A))=YEAR(DATEVALUE(target)))
*
(MONTH(DATEVALUE(A2:A))=MONTH(DATEVALUE(target)))
), ""),
"")))
```
Demo is noted here:
https://docs.google.com/spreadsheets/d/1HcL1ZFJ-26HU9lZVKJufE63cSDCOtVWYXOAqwnJPn40/edit#gid=0 |
The error was at the `console.error` statements. Changing `console.error("Error:", response);` to `console.error("Error:", response.error);` solved the issue. |
**How to use Next js in windows 7**
I am using windows 7 os. In windows 7 os i have installed nodejs of version 17 and npm(*By using releases zip files and changing some environment in system*). After this i am able to use react but when I move on to use **Nextjs** it will require nodejs of version 18.1 or later but I am not able to upgrade nodejs more, due to compatibly issues so I am looking for a way to use next js in windows 7?
how to accomplish this?
I have tried different previous version of nextjs and but when I tried to run development sever it not worked |
Next js installation in windows 7 os |
|windows|web|next.js|version| |
null |
{"Voters":[{"Id":354577,"DisplayName":"Chris"},{"Id":16217248,"DisplayName":"CPlus"},{"Id":1974224,"DisplayName":"Cristik"}]} |
For some reason, I cannot get the client-side validation to work from my Razor views. However when I created a Razor page by itself without using the Layout page, it works. I'm not sure why. Appreciate any help I can get. Thanks.
Here is the markup and code from my project's `Layout` page:
```
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"] - DotNetCore8TestSite</title>
<environment include="Development">
<link href="~/lib/bootstrap/dist/css/bootstrap.css" rel="stylesheet" />
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/jquery-validate/jquery.validate.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
</environment>
<environment include="Staging">
<link href="~/lib/bootstrap/dist/css/bootstrap.css" rel="stylesheet" />
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/jquery-validation/dist/jquery.validate.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
</environment>
<environment include="Production">
<link href="~/lib/bootstrap/dist/css/bootstrap.css" rel="stylesheet" />
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/jquery-validation/dist/jquery.validate.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
</environment>
</head>
<body>
<header>
<nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
<div class="container">
<a class="navbar-brand" asp-area="" asp-page="/Index">DotNetCore8TestSite</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target=".navbar-collapse" aria-controls="navbarSupportedContent"
aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="navbar-collapse collapse d-sm-inline-flex justify-content-between">
<ul class="navbar-nav flex-grow-1">
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-page="/Index">Home</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-page="/Privacy">Privacy</a>
</li>
</ul>
</div>
</div>
</nav>
</header>
<div class="container">
<main role="main" class="pb-3">
@RenderBody()
</main>
</div>
<footer class="border-top footer text-muted">
<div class="container">
© 2024 - DotNetCore8TestSite - <a asp-area="" asp-page="/Privacy">Privacy</a>
</div>
</footer>
@await RenderSectionAsync("Scripts", required: false)
</body>
</html>
```
And below is the markup in my Razor view:
```
@model DotNetCore8TestSite.Models.ContactForm
@{
ViewData["Title"] = "CreateMessage";
Layout = "~/Pages/Shared/_Layout.cshtml";
// ViewContext.ClientValidationEnabled = true;
}
<h1>CreateMessage</h1>
<h4>ContactForm</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="CreateMessage" method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Email" class="control-label"></label>
<input asp-for="Email" class="form-control" />
<span asp-validation-for="Email" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Message" class="control-label"></label>
<input asp-for="Message" class="form-control" />
<span asp-validation-for="Message" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
@section Scripts {
@{
await Html.RenderPartialAsync("_ValidationScriptsPartial");
}
}
```
This is the code from the model class:
```
using Microsoft.AspNetCore.Mvc;
using System.ComponentModel.DataAnnotations;
namespace DotNetCore8TestSite.Models
{
public class ContactForm
{
[BindProperty]
[Required(ErrorMessage = "Name cannot be blank"), MinLength(3)]
public string Name { get; set; }
[BindProperty]
[Required(ErrorMessage = "Email cannot be blank"), MinLength(3)]
public string Email { get; set; }
[BindProperty]
[Required(ErrorMessage = "Message cannot be blank"), MinLength(5)]
public string Message { get; set; }
}
}
```
I was expecting the field validators to display the appropriate messages when the fields were validated on hitting the Create Message button, but that's not happening. On the contrary the form is posting back to the server and the Post method is being called.
Strangely, if I create a Razor page without a View and Layout page, using the same class the client-side validation works. So I have figured it has something to do with the Layout page. |
ASP.NET Core 8.0 client-side validation not working |
|asp.net-core-mvc|client-side-validation|asp.net-core-8| |
I'm trying to set up a Nginx redirect and I'm slowly losing my mind trying to figure it out.
I have my Nginx server listening at 80, and it performs great. I have a page with a form where I want to be able to send `.json` POSTs from that page to a Python HTTP server that can process the requests. I have the server at port 8000.
On the website, I want to be able to reach the server by navigating to `<IP>:/sub/folder/` so that I can send the `.json` POSTs from my `<IP>:/sub/index.html` page by making a simple relative request to `./folder`.
When I send a curl to `<IP>:8000`, I reach the server and get the correct response.
I have tried to set up Nginx `proxy_pass` with the following configuration:
location /sub/folder/ {
proxy_pass http://127.0.0.1:8000/;
}
This results in a 301 which sends me from `<url>/sub/folder` to `/sub/folder/`, followed by a 404 at `/sub/folder/`.
If I go back to the Nginx config and turn `/sub/folder/` into `/sub/folder`, navigating to `<url>/sub/folder` returns a 404.
I've tried using `https`, I've tried changing out `127.0.0.1` for `localhost`, I've tried removing the final `/` in the `proxy_pass` line, I've tried redirecting to `https://<IP>:<port>/sub/folder` even though the HTTP server is at root, among more.
Any advice at all is greatly appreciated. |
I centered 3 divs on the middle of the screen, each one has an icon from fontawesome, but some icons like the dice and the code are a bit offset, except for the smile. (I assume this happened because the smile is rounded just like the div, but I'm not sure) I wanted to know how I can make all the icons centered on their own divs. Codepen with the whole code: [Smooth Buttons with Fontawesome Icons](https://codepen.io/Bernardo-Libertucio/pen/rNbGeKd)
Here's the HTML and CSS code:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
body {
background-color: #333;
font-size: 1.5em;
padding: 0;
}
.buttons {
display: flex;
gap: 25px;
justify-content: center;
align-items: center;
text-align: center;
line-height: 50px;
vertical-align: bottom;
float: center;
}
.button {
padding 5px;
color: black;
height: 50px;
width: 50px;
border: 15px solid #2b2b2b;
background-color: #2b2b2b;
border-radius: 100%;
transition: all ease-in-out 0.5s;
}
<!-- language: lang-html -->
<div class="buttons">
<div class="button"><i class="fa fa-dice fa-2xl"></i></div>
<div class="button"><i class="fa fa-code fa-2xl"></i></div>
<div class="button"><i class="fa fa-smile fa-2xl"></i></div>
</div>
<!-- end snippet -->
I've already tried changing the margin, display type and text-align, but nothing worked. |
null |
I'm using Composables in Android Studio Kotlin, It creates a spanned string via specified keywords via looking up within foreach loop, How to make it append just one time or remove duplicated appended text?
```
buildAnnotatedString {
note.value.title.forEachIndexed { index, character ->
append(character)
if (index > queryString.count() - 1 && note.value.title.substring(
index - (queryString.count() + 1 - 1), index
) == queryString
) {
withStyle(style = SpanStyle(color = Color.Blue))
{
append(queryString)
}
}
}
}
```
Actually its not possible to avoid writing two times or reverse code and delete duplicates |
|android|kotlin|android-jetpack-compose| |
`in` is a Python keyword so it can't be used as a variable name in Cython.
There's no real reasons why the argument names you tell Cython about have to match the real C argument names - they're just for documentation.
Convention would probably be just to change `in` to `in_` to keep the intent obvious. |
To jump straight to solution, scroll down to the solution part.
**Background**
I installed NixOS on October 2023, coming from Ubuntu 20.04, with neovim as my default text editor and Personal Development Environment.
So, everything on my neovim inside a fresh NixOS should go back to normal... right? Well, it didn't. That's why I'm here.
**The LSP problem**
Ever since the debut of NixOS on my laptop, lua-language-server (lua language server) never worked. I tried everything; a different version of Lua, installation of luaJIT; I even reset packer a couple of times (maybe I downloaded a corrupt version of lspconfig?), and reinstall all plugins, NOTHING worked. The following is a list of LSPs that didn't work (there may be more!):
- Lua-Language-Server (luals)
- rust-analyzer
- clangd (for c/c++)
So I came into terms that I may not enjoy the ravishes of auto-completions for Lua, as theprimeagen highly praised it (who is definitely not working for Netflix); and for the other above languages. This went on until a happy accident occurred.
**The accident**
Fast forward to March 2024, while fooling around with `sudo chown -R -755 .`, I accidentally ran it while on my home directory. I was immediately hit with negative effects; notifications on some apps crashing, permission denied while running apps; it was mayhem all over. While I knew I could get by, by restoring some permissions; for my laptop to be back to absolute normal, I believed I had to reinstall NixOS. So I did just that.
**Tiny light in a sea of regrets**
After coming into terms that I will lose about a day to return my laptop into its former glory, I backed up my nix and home configurations, then reinstalled NixOS. Then overwritten the default nix config with mine truly and did the classic `sudo nix-channel --update && sudo nixos-rebuild switch --upgrade` and copied my configurations back to home directory.
After it completed, I opened up neovim. After packer initializations and installations, I reopened again, this time opening neovim configuration folder with `cd ~/.config/nvim && nvim .`
Oooooh! I couldn't believe it! lua-language-server spun to life, indexing the nvim folder! highlighting every file with error on nvim-tree float window. On that moment, all the regrets poofed away.
**But.. how?**
While exasperating lua-language-server with bunch of erroneous codes, this question kept bugging me at the back of my head, how could it be? What happened different this time? Can we replicate it again? We should definitely try to replicate this.
"If it works don't touch it! or will break!" I tried to comfort myself.
More questions kept popping up: what if you restart and it doesn't work any more? What if you install something else and scrambles this precious "one-of-a-kind" setup?
"Aaargh! Now I have to figure out how this came to be!" I talked to myself.
**Lets go for a hunt then..**
So, where do we start? at neovim's `:Mason` of course. Let's reinstall lua-language-server and see if it will still be working.
"But, hey; there's no going back after this.." said to myself cautiously as I stared at the line highlighting lua-language-server on Mason popup. Hit `<S-x>` fast, uninstalled it; then navigated down and hit `i` for installation...
"Nothing! Nothing is working!" I yelled while banging the table angrily.
Yeah, But this time its different!
This time, we now know FOR SURE that lua-language-server CAN run on NixOS without any problems! my thoughts calmed me.
So, we know that lua-language-server was working, until we tried to reinstall it. Safe to say that Mason is the culprit here.
**Solution (for lua-language-server and others alike)**
So I opened Mason configurations in neovim with `cd ~/.local/share/nvim/mason/ && nvim .`, navigated through `bin` directory on nvim-tree, and found lua-language-server softlink file. opened it:
```
1 #!/usr/bin/env bash
2
3 exec "/packages/lua-language-server/libexec/bin/lua-language-server" "$@"
~
```
Then I remembered, the error: `lua-language-server: cannot execute: required file not found`
What if I change the file path here, as to a built in (installed via nixpkgs)?
Alas, I hopped into [search.nixos.org][1] and searched for `lua language server`, installed on my laptop with `nix-env -iA nixos.lua-language-server`
Then found out I had already installed it since I wrote it on my configuration.nix file, (that's why it worked on a brief moment, until I screwed it up)
I then ran `which lua-language-server` to confirm its local location. there after i ran `which lua-language-server | wl-copy` to copy the path to clipboard, and pasted to the file above. It now looked like this:
```
1 #!/usr/bin/env bash
2
3 exec "/home/your-username/.nix-profile/bin/lua-language-server" "$@"
~
```
saved the file and exit with `:wq` and entered the neovim configuration folder again with `cd ~/.config/nvim && nvim .`
She's working once again!
lua-language-server has been working ever since.
**Solution (for rust-analyzer, clanigd and others alike)**
After successive solving of lua LSP, and recovered some wit on me; I decided to tackle rust-analyzer next. So I opened Mason configurations in neovim, once again with `cd ~/.local/share/nvim/mason/ && nvim .`, navigated through `bin` directory on nvim-tree, and hopped into rust-analyzer softlink file.
Uum, 45mb? what is in this file? yap, pure byte code ladies and gentlemen! No paths to swap here.
But, since this is a softlink file, we can create a new link to a new rust-analyzer installed with nixpkgs. This should work, right? one way to find out.
I dove into [search.nixos.org][1] and searched for `rust-analyzer`, installed on my laptop with `nix-env -iA nixos.rust-analyzer`
I, then ran `which rust-analyzer` to confirm its local location. There after I ran `which rust-analyzer | wl-copy` to copy the path to clipboard.
Then I renamed the existing rust-analyzer softlink file in the `bin` folder into rust-analyzer1
There after, I pasted the path on the terminal and construct a softlink command as follows (make sure you execute the below command while inside the `bin` folder of mason configuration):
run command: `ln --symbolic -T /home/your-username/.nix-profile/bin/rust-analyzer rust-analyzer`
After the above procedures, I had the following files in the `bin` folder:
[rust-analyzer and rust-analyzer1][2]
There after, I closed neovim, and used neovim to open any rust file, and voila! rust-analyzer is chugging along, spitting out errors; uuhg, the burrow checker; nice to see you again.
**Post Script**
1. Summary: there 2 solution approaches to the LSP issue. depending on whether there is a path to executable inside softlink file or NOT, pick one of the approaches.
2. For the above 'patching' to work, you need to first install the LSPs through Mason. only then will you be able to successfully rip the fruits.
3. Do not update the patched LSP through Mason, as it will override it, get you back to zero LSPing.
4. I don't think that Mason is the culprit for all these "fiascos", he's just the easiest to trick IMO.
[1]: https://search.nixos.org
[2]: https://i.stack.imgur.com/CVGbg.png |
When I run your `grep -v ... -v ... token.xml` call I get an error:
$ grep -v '<?xml version="1.0" encoding="UTF-8"?><response><token>' -v '</token></response>' token.xml
grep: </token></response>: No such file or directory
After `TOKEN` has been populated I recommend you add `typeset -p TOKEN` (to show the contents of `TOKEN`); I'm guessing `TOKEN` does not contain what you think it does.
While xml should probably be parsed by a xml-capable tool, if you are 100% sure of the format of the contents in `token.xml` then the following should extract the token for you:
$ sed -En 's|.*<token>(.*)</token>.*|\1|p' token.xml
ZsxY7Q9G90jh4FqUiAjxD9XmqLWf0rYg4RUNf6FoVzeTIlPPms0Ov1RERFFRY77o
Then update your script with the following `TOKEN=$(...)` line:
$ TOKEN=$(sed -En 's|.*<token>(.*)</token>.*|\1|p' token.xml)
$ typeset -p TOKEN
declare -- TOKEN="ZsxY7Q9G90jh4FqUiAjxD9XmqLWf0rYg4RUNf6FoVzeTIlPPms0Ov1RERFFRY77o"
|
|sql|mysql|select|left-join| |
I can see corepack about to download yarn v1.22 when I run the `yarn` command:
```text
user@laptop:~/empty-directory$ yarn
Corepack is about to download https://registry.yarnpkg.com/yarn/-/yarn-1.22.22.tgz.
Do you want to continue? [Y/n]
```
I'm using corepack v0.25.2.
The latest release of yarn is v4.11 at the time of writing: https://github.com/yarnpkg/berry/releases
Why is this version being downloaded, and how can I make yarn 4.1.1 the default version that Corepack uses? |
{"Voters":[{"Id":1145388,"DisplayName":"Stephen Ostermiller"}],"SiteSpecificCloseReasonIds":[18]} |
Windows 11
I would like to filter double values.
[![enter image description here][1]][1]
[![enter image description here][2]][2]
[1]: https://i.stack.imgur.com/ZckkI.png
[2]: https://i.stack.imgur.com/ICCrr.png
1. testo = text
2. numerico = numeric
3. valuta = currency
I can filter Strings
Dim srchStr As String = Me.TextBox1.text
Dim strFilter As String = "MyCol1 LIKE '*" & srchStr.Replace("'", "''") & "*'"
dv.RowFilter = strFilter
I can filter Integers
Dim srchStr As String = Me.TextBox1.Text
Dim id As Integer
If Integer.TryParse(srchStr, id) Then
dv.RowFilter = "code = " & id
Else
MessageBox.Show("Error: ........")
End If
Dim strFilter As String = "code = " & id
dv.RowFilter = strFilter
but I can not filter a double value.
I actually use this code to filter strings in my DataGridView
Private Sub MyTabDataGridView_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyTabDataGridView.DoubleClick
Try
'MyRow
Dim row As Integer = MyTabDataGridView.CurrentRow.Index
'MyColumn
Dim column As Integer = MyTabDataGridView.CurrentCell.ColumnIndex
'MyColumn and MyRow
Dim ColumnRow As String = MyTabDataGridView(column, row).FormattedValue.ToString
'Header Text
Dim HeaderText As String = MyTabDataGridView.Columns(column).HeaderText
'I exclude the errors
If HeaderText = "id" Or HeaderText = "MyCol3" Or HeaderText = "MyCol4" Or HeaderText = "MyCol5" Then
Exit Sub
End If
'Ready to filter
Dim strFilter As String = HeaderText & " Like '*" & ColomnRow.Replace("'", "''") & "*'"
dv.RowFilter = strFilter
Catch ex As Exception
End Try
Any suggestion will be highly appreciated.
Solution:
Private Sub MyTabDataGridView_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyTabDataGridView.DoubleClick
Try
System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("en-US")
'MyRow
Dim row As Integer = MyTabDataGridView.CurrentRow.Index
'MyColumn
Dim column As Integer = MyTabDataGridView.CurrentCell.ColumnIndex
'MyColumn and MyRow
Dim ColumnRow As String = MyTabDataGridView(column, row).FormattedValue.ToString
'Header Text
Dim HeaderText As String = MyTabDataGridView.Columns(column).HeaderText
'I exclude the errors
If HeaderText = "id" Then
Exit Sub
End If
If HeaderText = "MyCol1" Or HeaderText = "MyCol2" Then
'Si filtra
Dim strFilter As String = HeaderText & " Like '*" & ColumnRow & "*'"
dv.RowFilter = strFilter
ElseIf HeaderText = "MyCol3" Or HeaderText = "MyCol4" Or HeaderText = "MyCol5" Then
Dim strFilter2 As String = HeaderText & "= " & ColumnRow.Replace(",", ".")
dv.RowFilter = strFilter2
End If
System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("it-IT")
'Refresh il DataGridView
Me.MyTabDataGridView.Refresh()
Catch ex As Exception
Dim lNewVariable2 As String = "mailto:myadd@libero.it?subject=Invio Dati " & "&body= {0}{1}{2}"
System.Diagnostics.Process.Start(String.Format(lNewVariable2, ex.Message, Environment.NewLine, ex.StackTrace))
End Try
End Sub
|
There are so many issues happening, but I will try to address the most important ones. First thing I notice is that all the videos are set to be autoplay by default, so they all run when the page is loaded:
```
<iframe class="frame"
width="225"
height="340"
src="https://www.youtube.com/embed/JfVOs4VSpmA?autoplay=1&mute=1&vq=hd1080"
title="YouTube video player"
frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
allowfullscreen
></iframe>
```
In the above code, see that there is query params in the src attribute `autoplay=1`, we should first remove them from all the iframes.
The next problem is that you query the DOM wrong:
```
function onHover() {
const currentCard = $(this);
hoverTimeout = setTimeout(() => {
currentCard.find('.card__front').hide();
currentCard.find('.iframe').show();
var src = currentCard.find('.iframe').attr("src");
...
```
The class `.iframe` doesn't exist, since you assigned the iframes with `.frame` class instead. But to fix this, we can just select the DOM by its tag name, e.g.:
```
currentCard.find('iframe').show();
```
And then, since we have removed the autoplay query params, we need to readd them when `hover` event happens, we can trigger the play by appending `autoplay=1` to the query params, but when `hover` event happens like this inside the `onHover()` function:
```
currentCard.find('iframe').attr("src", src + '&autoplay=1');
```
Then finally, we need to fix the `clearTimeout`, it seems like the `setTimeout`s are triggered multiple times, i'm not sure why, but basically we can store the `timeout` id to an object so that we can store and clear all of them:
```
var hoverTimeout = {}; // an object to store timeout id
```
And then update the `onHover()` function:
```
function onHover() {
const currentCard = $(this);
if (hoverTimeout[currentCard.attr('id')] === undefined) {
hoverTimeout[currentCard.attr('id')] = []; // initialize timeout id array according to element id
}
hoverTimeout[currentCard.attr('id')].push(setTimeout(() => {
currentCard.find('.card__front').hide();
currentCard.find('iframe').show();
var src = currentCard.find('iframe').attr("src");
currentCard.find('iframe').attr("src", src + '&autoplay=1');
currentCard.find('iframe').on('click', function() {
$(this).requestFullscreen();
});
}, 5000)); // 5000 milliseconds (5 seconds)
}
```
Finally, we can update the `onHoverTime` function to this, so we can clear the timeout ids correctly:
```
function onHoverTime() {
while (hoverTimeout[$(this).attr('id')].length > 0) {
clearTimeout(hoverTimeout[$(this).attr('id')][0]); // Clear the timeout to prevent actions if the user moves away before 5 seconds
hoverTimeout[$(this).attr('id')].shift();
}
$(this).find('.card__front').show();
$(this).find('iframe').hide();
var src = $(this).find('iframe').attr("src");
if (src) {
$(this).find('iframe').attr("src", src.replace('?autoplay=1', ''));
}
}
```
[Here is the working fiddle][1].
[1]: https://jsfiddle.net/damzaky/bLovwqnm/ |
How to resolve these Unpickling Errors? |
|python-3.x|multithreading|pickle| |
null |
I am trying to make an application that teaches English words, sentences and phrases. Can you help me how to design the database of this application?
Notes:
- I use C# and SQL Server
- Windows Forms
I can't upload them all here, so I'll leave the link
https://drive.google.com/drive/u/1/folders/158X_TwNhbrCc6d_zldutBd8D0-VwxtgC
CREATE TABLE tblTurkishWords
(
WordID INT PRIMARY KEY,
TurkishWords nvarchar(100) NOT NULL,
);
CREATE TABLE tblEnglishWords
(
WordsID INT PRIMARY KEY,
EnglishWords nvarchar(100) NOT NULL,
);
CREATE TABLE tblDescriptions
(
DescriptionID INT PRIMARY KEY,
EnglishWordDescription nchar(100) NOT NULL,
EnglishSentenceDescription nchar(100) NOT NULL,
EnglishPhraseDescription nchar(100) NOT NULL,
);
CREATE TABLE tblPhonetic
(
PhoneticID INT PRIMARY KEY,
EnglishWordPhonetic nchar(100) NOT NULL,
EnglishSentencePhonetic nchar(100) NOT NULL,
EnglishPhrasePhonetic nchar(100) NOT NULL,
);
CREATE TABLE tblMedia
(
MediaID INT PRIMARY KEY,
EnglishWordMedia nchar(100) NOT NULL,
EnglishSentenceMedia nchar(100) NOT NULL,
EnglishPhraseMedia nchar(100) NOT NULL,
);
--there will be pictures related to the relevant words in the media section
CREATE TABLE tblYouTubeLink
(
LinkID INT PRIMARY KEY,
EnglishWordLink nchar(100) NOT NULL,
EnglishSentenceLink nchar(100) NOT NULL,
EnglishPhraseLink nchar(100) NOT NULL,
);
--here will be film scenes from youtube to illustrate the words
CREATE TABLE tblReadingAudioFiles
(
AudioFileID INT PRIMARY KEY,
EnglishWordAudioFile nchar(100) NOT NULL,
EnglishSentenceAudioFile nchar(100) NOT NULL,
EnglishPhraseAudioFile nchar(100) NOT NULL,
);
CREATE TABLE tblKnown?
(
KnownID INT PRIMARY KEY,
EnglishWordKnown bit NOT NULL,
EnglishSentenceKnown bit NOT NULL,
EnglishPhraseKnown bit NOT NULL,
);
CREATE TABLE tblWrong
(
WrongID INT PRIMARY KEY,
EnglishWordWrong INT NOT NULL,
EnglishSentenceWrong INT NOT NULL,
EnglishPhraseWrong INT NOT NULL,
);
CREATE TABLE tblCorrect
(
CorrectID INT PRIMARY KEY,
EnglishWordCorrect INT NOT NULL,
EnglishSentenceCorrect INT NOT NULL,
EnglishPhraseCorrect INT NOT NULL,
);
CREATE TABLE tblTurkishFamousWord
(
WordID INT PRIMARY KEY,
TurkishWord nchar(255) NOT NULL
);
CREATE TABLE tblEnglishFamousWord
(
WordID INT PRIMARY KEY,
EnglishWord nchar(255) NOT NULL
);
CREATE TABLE tblTurkishSentence
(
SentenceID INT PRIMARY KEY,
TurkishSentence nchar(255) NOT NULL
);
CREATE TABLE tblEnglishSentence
(
SentenceID INT PRIMARY KEY,
EnglishSentence nchar(255) NOT NULL
);
CREATE TABLE tblTurkishPhrase
(
PhraseID INT PRIMARY KEY,
TurkishPhrase nchar(255) NOT NULL
);
CREATE TABLE tblEnglishPhrase
(
PhraseID INT PRIMARY KEY,
EnglishPhrase nchar(255) NOT NULL
);
I tried to prepare a database as I gave in the example, but I didn't get much idea about how to make their relationship |
Yes, you can use **model_validator** for that
```
from pydantic import BaseModel, model_validator
from typing import Optional
class Cfdi(BaseModel):
relation_type: Optional[...] = None
document_list: Optional[list[str]] = None
@model_validator(mode="after")
@classmethod
def check_two_fields_together(cls, data: dict) -> dict:
if relation_type and len(document_list) < 1:
raise ValueError("Error text")
return data
```
|
I don't know if it is the best solution, but if you specify in yout golang container
> restart: always
, the container will restart until it connects to the database.
version: '3'
services:
app:
restart: always
build: ./
volumes:
- ./internal/app:/app
- ./logs:/var/log/parser
depends_on:
- mysqldb
links:
- db
db:
image: mysql:8
container_name: mysqldb
ports:
- "3306:3306"
volumes:
- ./docker/mysql/conf:/etc/mysql/conf/conf.d
- ./docker/mysql/logs/:/var/log/mysql
- ./docker/mysql/init:/docker-entrypoint-initdb.d
- ./docker/mysql/data:/var/lib/mysql
environment:
MYSQL_ROOT_PASSWORD: pass
MYSQL_DATABASE: data
MYSQL_USER: user
MYSQL_PASSWORD: pass |
In this case "proc.communicate" cannot be used; it's not suitable for the purpose, since the OP wants to interrupt a running process. The sample code in the Python docs also shows how to directly read the piped stdout in these cases, so there is in principle nothing wrong with doing that.
The main problem is that the stopwatch process is buffering the output.
Try using as command: `["python", "-u", "stopwatch.py", "3"]`
For debugging it will also help to add some prints indicating when the robot started and ended. The following works for me:
```
class RobotManager:
def __init__(self):
self.cmd = ["python", "-u", "stopwatch.py", "3"]
self.robot = None
async def start(self):
print("======Starting======")
self.robot = await asyncio.create_subprocess_exec(
*self.cmd,
stdout=asyncio.subprocess.PIPE,
)
async def stop(self):
if self.robot:
self.robot.kill()
stdout = await self.robot.stdout.readline()
while stdout:
print(stdout)
stdout = await self.robot.stdout.readline()
await self.robot.wait()
print("======Terminated======")
self.robot = None
```
|
How to properly set hashes in script-src CSP policy header? |
Jump instructions do two things :
1. Testing the condition
2. Jumping to the branch if the condition is true.
It takes one cycle to test the condition. In your case, `brne` tests the 'Zero Flag'.
Then, if the test is true, it takes one more cycle to jump to the label. Otherwise, the program continues to the next instruction.
Example from the AVR Instruction Set Manual :
eor r27,r27 ; Clear r27
loop: inc r27 ; Increase r27
...
cpi r27,5 ; Compare r27 to 5
brne loop ; Branch if r27<>5
nop ; Loop exit (do nothing)
`brne` will need 2 cycles the 5 first iterations because `r27` is not equal to 5, and only one on the 6th, when `r27` is equal to 5
|
Firebase downloading size incredibly high on ny social platform |
|android|firebase-realtime-database| |
null |
You want to see a minimalist solution?
import math
highway_number = int(input())
exclude = [0,100,200,300,400,500,600,700,800,900]
if highway_number <= 99 and not (highway_number in exclude):
remain = math.fmod(highway_number, 2)
direction = 'north/south.' if remain == 1 else 'east/west.'
print(f"I-{highway_number} is primary, going {direction}")
elif (highway_number < 1000) and not (highway_number in exclude):
math_highway = math.fmod(highway_number, 100)
remain = math.fmod(math_highway, 2)
direction = 'north/south.' if remain == 1 else 'east/west.'
main_highway = int(math_highway)
print('I-{0} is auxiliary, serving I-{1}, going {2}'.format(highway_number, main_highway, direction))
else:
print (highway_number, 'is not a valid interstate highway number.')
|
I am following this [tutorial][1] to fetch the auth token for the HERE maps. I am able to fetch the token with my iOS app, However I cannot seem to get the token with Android. I keep getting the error `errorCode: '401300'. Signature mismatch. Authorization signature or client credential is wrong."`
Below is my code to fetch the token :
**HEREOAuthManager.java**
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
public void fetchOAuthToken(final HereTokenFetchListener callback) {
String timestamp = String.valueOf(String.valueOf(Instant.now().getEpochSecond()));
String nonce = Util.randomStringGenerator();
String grant_type = "grant_type=client_credentials";
String oauth_consumer_key = "&oauth_consumer_key=" + clientID ;
String oauth_nonce = "&oauth_nonce=" + nonce;
String oauth_signature_method = "&oauth_signature_method=HMAC-SHA256";
String oauth_timestamp = "&oauth_timestamp=" + timestamp;
String oauth_version = "&oauth_version=1.0";
String paramsString = grant_type + oauth_consumer_key + oauth_nonce + oauth_signature_method + oauth_timestamp + oauth_version;
String baseString = "POST&" + Util.urlEncode(tokenEndpoint) + "&" + Util.urlEncode(paramsString);
// Generate signature
String secret = Util.urlEncode(clientSecret) + "&";
String signature = Util.calculateHmacSha256(secret, baseString);
// Construct Authorization header
String authString = "OAuth oauth_consumer_key=\"" + clientID + "\",oauth_nonce=\"" + nonce +
"\",oauth_signature=\"" + Util.urlEncode(signature) + "\",oauth_signature_method=\"HMAC-SHA256\"," +
"oauth_timestamp=\"" + timestamp + "\",oauth_version=\"1.0\"";
// Create HTTP client
OkHttpClient client = new OkHttpClient();
// Create request body
RequestBody requestBody = new FormBody.Builder()
.add("grant_type", "client_credentials")
.build();
// // Create HTTP request
Request request = new Request.Builder()
.url(tokenEndpoint)
.post(requestBody)
.addHeader("Authorization", authString)
.addHeader("Content-Type", "application/x-www-form-urlencoded")
.build();
}
<!-- end snippet -->
**Utils.java**
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
public static String calculateHmacSha256(String secret, String data) {
try {
String secretWithAmpersand = secret + "&";
SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(secretKeySpec);
byte[] hmacData = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
String baseEncodedSignature = Base64.getEncoder().encodeToString(hmacData);
return urlEncode(baseEncodedSignature);
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
e.printStackTrace();
return null;
}
}
public static String urlEncode(String stringToEncode) {
try {
return java.net.URLEncoder.encode(stringToEncode, "UTF-8")
.replace("+", "%20") // Replace '+' with '%20'
.replace("=", "%3D")
.replace("*", "%2A") // Replace '*' with '%2A'
.replace("&", "%26")
.replace( "~","%7E"); // Replace '~' with '%7E';
} catch (java.io.UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
}
public static String randomStringGenerator()
{
String ALLOWED_CHARACTERS ="0123456789qwertyuiopasdfghjklzxcvbnm";
final Random random=new Random();
final StringBuilder sb=new StringBuilder(8);
for(int i=0;i<8;++i)
sb.append(ALLOWED_CHARACTERS.charAt(random.nextInt(ALLOWED_CHARACTERS.length())));
return sb.toString();
}
<!-- end snippet -->
What could I be missing? Any help is appreciated
[1]: https://www.here.com/docs/bundle/identity-and-access-management-developer-guide/page/topics/sdk.html |
I'm developing a DLL that is injected into a process and uses some memory addresses. My idea is that my DLL finds and updates those addresses automatically, as I have the patterns and I can find them perfectly in IDA with **Search -> Sequence of bytes...**
[![enter image description here][1]][1]
As you can see it finds the sequence of bytes with wildcards
[![enter image description here][2]][2]
Now, I'm trying to replicate this IDA functionality in my DLL.
What I've tried so far in my code is the following:
uintptr_t mainModule = NULL;
DWORD WINAPI MainFunc(HMODULE hModule) {
AllocConsole();
FILE* f;
freopen_s(&f, "CONOUT$", "w", stdout);
mainModule = (uintptr_t)GetModuleHandle(L"client.dll");
if (hModule)
{
if (GetPatterns()) while (true) Sleep(1);
}
else
{
std::cout << "Main module not found, press ENTER to exit..." << std::endl;
getchar();
}
fclose(f);
FreeConsole();
FreeLibraryAndExitThread(hModule, 0);
return 0;
}
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
CloseHandle(CreateThread(nullptr, 0, (LPTHREAD_START_ROUTINE)MainFunc, hModule, 0, nullptr));
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
bool Compare(const BYTE* pData, const BYTE* pMask, const char* pszMask) {
for (; *pszMask; ++pszMask, ++pData, ++pMask) {
if (*pszMask == 'x' && *pData != *pMask) {
return false;
}
}
return (*pszMask) == NULL;
}
uintptr_t FindPattern(uintptr_t dwAddress, DWORD dwLen, BYTE* bMask, const char* szMask) {
for (DWORD i = 0; i < dwLen; i++)
if (Compare((BYTE*)(dwAddress + i), bMask, szMask))
return (uintptr_t)(dwAddress + i);
return 0;
}
MODULEINFO mInfo;
bool GetPattern(BYTE pattern[], const char* mask)
{
DWORD foundAddress = FindPattern(mainModule, mInfo.SizeOfImage, pattern, mask);
if (foundAddress != 0) {
std::cout << "Found pattern at: 0x" << std::hex << foundAddress << std::endl;
return true;
}
std::cout << "Error: pattern not found" << std::endl;
return false;
}
bool GetPatterns()
{
if (GetModuleInformation(GetCurrentProcess(), (HMODULE)mainModule, &mInfo, sizeof(mInfo))) {
BYTE pattern[] = { 0x48, 0x8B, 0x05, 0x00, 0x00, 0x00, 0x00, 0x48, 0x85, 0xC0, 0x74, 0x00, 0x8B, 0x88 };
const char* mask = "xxx????xxxx?xx";
if (!GetPattern(pattern, mask)) return false;
}
else {
std::cout << "Error: unable to get module info" << std::endl;
return false;
}
return true;
}
And I'm getting an address as output **Found pattern at: 0xcae401b0** that takes to nowhere:
[![enter image description here][3]][3]
(Trying client.dll + the output address but also takes to nowhere)
[1]: https://i.stack.imgur.com/SH5A7.png
[2]: https://i.stack.imgur.com/skOsp.png
[3]: https://i.stack.imgur.com/4SSJF.png |
How should I make database relationships |
I'm trying to make a TTS on a open source LLM with local API that is streaming me the response to my questions but it's very hard to do it and I find nothing on that subject.
Here's the code:
```import pyttsx3
import threading
from queue import Queue
from openai import OpenAI
import time
tts_engine = pyttsx3.init()
client = OpenAI(base_url="http://localhost:1234/v1", api_key="not-needed")
history = [
{"role": "system", "content": "Vous êtes un assistant intelligent appelé Bob. Vous fournissez toujours des réponses rapides et précises, à la fois justes et utiles et toujours en langue française."},
{"role": "user", "content": "Bonjour, présentez-vous à quelqu'un qui ouvre ce programme pour la première fois. Soyez concis."},
]
while True:
user_input = input("> ")
history.append({"role": "user", "content": user_input})
start_time = time.time() # Temps de début de la requête à l'API
completion = client.chat.completions.create(
model="local-model",
messages=history,
temperature=0.8,
stream=True,
)
new_message = {"role": "assistant", "content": ""}
for chunk in completion:
if chunk.choices[0].delta.content:
generated_text = chunk.choices[0].delta.content
print(generated_text, end="", flush=True)
new_message["content"] += generated_text
history.append(new_message)
end_time = time.time()
response_time = end_time - start_time
print("\nTemps de réponse de l'API:", response_time, "secondes")
```
So I tried multiple thing like a loop that is looking for the new word that is being generating but I think that is not good approach and it doesn't work.
Any suggestions? |
I am making a multiselect component in Next.js and I am using states and setting states. However, this error occurs:
[](https://i.stack.imgur.com/m8zuP.png)
whenever I click this:
[](https://i.stack.imgur.com/I8x9Z.png)
This is the code of MultiSelect.tsx:
```javascript
import { useState } from "react";
import {
Command,
CommandDialog,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
CommandSeparator,
CommandShortcut,
} from "@/components/ui/command";
interface MultiSelectProps {
placeholder: string
collections: CollectionType[]
value: string[]
onChange: (value: string) => void
onRemove: (value: string) => void
}
const MultiSelect: React.FC<MultiSelectProps> = ({
placeholder,
collections,
value,
onChange,
onRemove,
}) => {
const [inputValue, setInputValue] = useState("");
const [open, setOpen] = useState(false);
return (
<Command className="overflow-visible bg-white">
<CommandInput
placeholder={placeholder}
value={inputValue}
onValueChange={setInputValue}
onBlur={() => setOpen(false)}
onFocus={() => setOpen(true)}
/>
<div className="relative mt-2">
{open && (
<CommandGroup className="absolute w-full z-10 top-0 overflow-auto border rounded-md shadow-md">
{collections.map((collection) => (
<CommandItem key={collection._id}>{collection.title}</CommandItem>
))}
</CommandGroup>
)}
</div>
</Command>
);
};
export default MultiSelect;
```
and here is the code from the ProductForm.tsx:
```javascript
"use client";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import { Separator } from "../ui/separator";
import { z } from "zod";
import { Button } from "@/components/ui/button";
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Textarea } from "../ui/textarea";
import ImageUpload from "../custom ui/ImageUpload";
import { useParams, useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import toast from "react-hot-toast";
import Delete from "../custom ui/Delete";
import MultiText from "../custom ui/MultiText";
import MultiSelect from "../custom ui/MultiSelect";
const formSchema = z.object({
title: z.string().min(2).max(20),
description: z.string().min(2).max(500).trim(),
media: z.array(z.string()),
category: z.string(),
collections: z.array(z.string()),
tags: z.array(z.string()),
size: z.array(z.string()),
colors: z.array(z.string()),
price: z.coerce.number().min(0.1),
expense: z.coerce.number().min(0.1),
});
interface ProductFormProps {
initialData?: ProductType | null; // Must have ? to make it optional
}
const ProductForm: React.FC<ProductFormProps> = ({ initialData }) => {
const router = useRouter();
//const params = useParams();
const [loading, setLoading] = useState(false);
const [collections, setCollections] = useState<CollectionType[]>([]);
const getCollections = async () => {
try{
setLoading(true)
const res = await fetch("/api/collections", {
method: "GET",
})
const data = await res.json()
setCollections(data)
setLoading(false)
}catch(err) {
console.log("[collections_GET]", err)
toast.error("Something went wrong. Please try again.")
}
}
useEffect(() => {
getCollections()
}, [])
// 1. Define your form.
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues: initialData
? initialData
: {
title: "",
description: "",
media: [],
category: "",
collections: [],
tags: [],
sizes: [],
colors: [],
price: 0.1,
expense: 0.1,
},
});
const handleKeyPress = (
e:
| React.KeyboardEvent<HTMLInputElement>
| React.KeyboardEvent<HTMLTextAreaElement>
) => {
if (e.key === "Enter") {
e.preventDefault();
}
};
// 2. Define a submit handler.
const onSubmit = async (values: z.infer<typeof formSchema>) => {
// Do something with the form values.
// ✅ This will be type-safe and validated.
//console.log(values)
try {
setLoading(true);
const url = initialData
? `/api/products/${initialData._id}`
: "/api/products";
const res = await fetch(url, {
method: "POST",
body: JSON.stringify(values),
});
if (res.ok) {
setLoading(false);
toast.success(`Product ${initialData ? "updated" : "created"}.`);
window.location.href = "/products";
router.push("/products");
}
} catch (err) {
console.log("[products_POST]", err);
toast.error("Something went wrong. Please try again.");
}
};
return (
<div className="p-10">
{initialData ? (
<div className="flex items-center justify-between">
<p className="text-heading2-bold">Edit Product</p>
<Delete id={initialData._id} />
</div>
) : (
<p className="text-heading2-bold">Create Product</p>
)}
<Separator className="bg-grey-1 my-4 mb-7" />
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
<FormField
control={form.control}
name="title"
render={({ field }) => (
<FormItem>
<FormLabel>Title</FormLabel>
<FormControl>
<Input
placeholder="Title"
{...field}
onKeyDown={handleKeyPress}
/>
</FormControl>
<FormDescription>The title of the product.</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="description"
render={({ field }) => (
<FormItem>
<FormLabel>Description</FormLabel>
<FormControl>
<Textarea
placeholder="Description"
{...field}
rows={5}
onKeyDown={handleKeyPress}
/>
</FormControl>
<FormDescription>
The description of the product.
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="media"
render={({ field }) => (
<FormItem>
<FormLabel>Image</FormLabel>
<FormControl>
<ImageUpload
value={field.value}
onChange={(url) => field.onChange([...field.value, url])}
onRemove={(url) =>
field.onChange([
...field.value.filter((image) => image !== url),
])
}
/>
</FormControl>
<FormDescription>The image of the product.</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<div className="md: grid md:grid-cols-3 md:gap-8">
<FormField
control={form.control}
name="price"
render={({ field }) => (
<FormItem>
<FormLabel>Price ($)</FormLabel>
<FormControl>
<Input
type="number"
placeholder="Price"
{...field}
onKeyDown={handleKeyPress}
/>
</FormControl>
<FormDescription>The price of the product.</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="expense"
render={({ field }) => (
<FormItem>
<FormLabel>Expense ($)</FormLabel>
<FormControl>
<Input
type="number"
placeholder="Expense"
{...field}
onKeyDown={handleKeyPress}
/>
</FormControl>
<FormDescription>The expense of the product.</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="category"
render={({ field }) => (
<FormItem>
<FormLabel>Category</FormLabel>
<FormControl>
<Input
placeholder="Category"
{...field}
onKeyDown={handleKeyPress}
/>
</FormControl>
<FormMessage className="text-red-1" />
</FormItem>
)}
/>
<FormField
control={form.control}
name="tags"
render={({ field }) => (
<FormItem>
<FormLabel>Tags</FormLabel>
<FormControl>
<MultiText
placeholder="Tags"
value={field.value}
onChange={(tag) => field.onChange([...field.value, tag])}
onRemove={(tagToRemove) =>
field.onChange([
...field.value.filter((tag) => tag !== tagToRemove),
])
}
/>
</FormControl>
<FormMessage className="text-red-1" />
</FormItem>
)}
/>
<FormField
control={form.control}
name="collections"
render={({ field }) => (
<FormItem>
<FormLabel>Collections</FormLabel>
<FormControl>
<MultiSelect
placeholder="Collections"
collections={collections}
value={field.value}
onChange={(_id) => field.onChange([...field.value, _id])}
onRemove={(idToRemove) =>
field.onChange([
...field.value.filter((collectionId) => collectionId !== idToRemove),
])
}
/>
</FormControl>
<FormMessage className="text-red-1" />
</FormItem>
)}
/>
</div>
<div className="flex gap-10">
<Button type="submit" className="bg-blue-1 text-white">
Submit
</Button>
<Button
type="button"
onClick={() => router.push("/collections")}
className="bg-blue-1 text-white"
>
Discard
</Button>
</div>
</form>
</Form>
</div>
);
};
export default ProductForm;
```
When I click the multiselect component, I am expecting it to show the current collection list. |
If I understand correctly, you want to be able to drag the blue button along the arc of the progress bar and the progress should be filled with color to correspond to the button position.
I don't quite understand why it would make sense to be able to adjust the progress manually like this, but anyway, if this is the right understanding then the following changes can be used to get it working:
- Use the limits consistently. The function `updateProgress` was using min/max limits of -110 degrees to +110 degrees, but then it was capping the result at 88.8 degrees for some reason. Also, the progress arc was being drawn from 0.3 to 0.9, which would represent an angle of 216 degrees. I've stuck with -110 degrees to +110 degrees (= 220 degrees total) and adapted the other limits accordingly.
- If the blue button is positioned at 12 o' clock when the angle is 0, then the computed progress angle can simply be applied as a rotation effect, instead of adjusting x and y offsets. To position the button at 12 o' clock, all it takes is a negative y-offset equal to the radius.
- Likewise, it is much simpler if the progress bar starts at 0 and then a rotation effect is used to change the start position to -110 degrees, instead of trimming from 0.3 to 0.9 and applying a rotation effect of 54.5 degrees (which should have actually been 54 degrees).
- I would suggest using `Double` for `progressValue` as it simplifies some of the computation.
- The function `angle` needs to take the size of the button into consideration.
- To make the animation more responsive to small drag movements, supply a `minimumDistance` to the `DragGesture`, for example, `minimumDistance: 1`.
- The progress bar does not need to be passed a binding to the progress level, because it is read-only. It can be a `let` property instead.
- The button does not need to be passed the progress level at all.
- Large movements can be smoothed by adding an `.animation` modifier to the `ZStack`.
Here you go, hope it helps:
```swift
struct SemiCircularProgressBar: View {
@State private var progressValue: Double = 0.0
@State private var degrees: Double = -110
var body: some View {
VStack {
ZStack {
ProgressBar(progress: progressValue) // self.$progressValue
.frame(width: 250.0, height: 250.0)
.padding(40.0)
ProgressThumb() // self.$progressValue
.frame(width: 30, height: 30)
.offset(y: -125) // circle radius
.rotationEffect(.degrees(degrees))
// .offset(x: self.thumbOffset().x, y: self.thumbOffset().y)
// .rotationEffect(.degrees(54.5))
.gesture(
DragGesture(minimumDistance: 1)
.onChanged { gesture in
// let angle = self.angle(for: gesture.location)
let angle = location2Degrees(location: gesture.location)
updateProgress(for: angle)
}
)
}
.animation(.easeInOut(duration: 0.15), value: degrees)
Spacer()
}
}
// private func angle(for location: CGPoint) -> Double {
// let vector = CGVector(dx: location.x, dy: location.y)
// let angle = atan2(vector.dy, vector.dx)
// return Double(angle * 180 / .pi)
// }
private func location2Degrees(location: CGPoint) -> Double {
let halfButtonSize = 30.0 / 2
let radians = atan2(location.x - halfButtonSize, halfButtonSize - location.y)
let degrees = radians * 180 / .pi
return degrees < -180
? degrees + 360
: degrees > 180 ? degrees - 360 : degrees
}
private func updateProgress(for angle: Double) {
let totalAngle: Double = 220
let minAngle: Double = -110
let maxAngle: Double = minAngle + totalAngle
let normalizedAngle = min(max(minAngle, angle), maxAngle)
// if normalizedAngle > 88.8 {
// normalizedAngle = 88.8
// }
self.progressValue = (normalizedAngle - minAngle) / totalAngle
self.degrees = normalizedAngle
}
// private func thumbOffset() -> CGPoint {
// let thumbRadius: CGFloat = 125 // half of progress bar diameter
// let radians = CGFloat(degrees) * .pi / -100
// let x = thumbRadius * cos(radians)
// let y = thumbRadius * sin(radians)
// return CGPoint(x: x, y: y)
// }
}
struct ProgressBar: View {
let progress: Double // @Binding var progress: Float
var body: some View {
ZStack {
Circle()
.trim(from: 0, to: 220.0 / 360) // (from: 0.3, to: 0.9)
.stroke(style: StrokeStyle(lineWidth: 12.0, lineCap: .round, lineJoin: .round))
.opacity(0.3)
.foregroundColor(Color.gray)
.rotationEffect(.degrees(-110 - 90)) // .degrees(54.5)
Circle()
.trim(from: 0, to: (progress * 220.0) / 360) // (from: 0.3, to: CGFloat(self.progress))
.stroke(style: StrokeStyle(lineWidth: 12.0, lineCap: .round, lineJoin: .round))
.fill(AngularGradient(gradient: Gradient(stops: [
.init(color: Color(hex: "ED4D4D"), location: 0), // 0.39000002
.init(color: Color(hex: "E59148"), location: 65.0 / 260), // 0.48000002
.init(color: Color(hex: "EFBF39"), location: 110.0 / 360), // 0.5999999
.init(color: Color(hex: "EEED56"), location: 175.0 / 360), // 0.7199998
.init(color: Color(hex: "32E1A0"), location: 220.0 / 360), // 0.8099997
.init(color: Color(hex: "ED4D4D"), location: 1)
]),center: .center))
.rotationEffect(.degrees(-110 - 90)) // .degrees(54.5)
VStack {
Text("824").font(Font.system(size: 44)).bold().foregroundColor(Color(hex: "314058"))
Text("Great Score!").bold().foregroundColor(Color(hex: "32E1A0"))
}
}
}
}
struct ProgressThumb: View {
var body: some View {
Circle()
.fill(Color.blue)
.frame(width: 30, height: 30)
}
}
```
 |
The objective of my code is to plot soil pressure from data extracted from another software. The output of this other software gives me the value of this pressure for each of the joints of a shell that must be interpolated to present the pressure throughout this shell. As each shell can have different shapes and the set of shells can have concavities and openings in the geometry, I am plotting the stress for each of the shells separately on the axis.
The problem is that as the number of shells increases, the plotting time increases exponentially, so that plotting 10 images with 100 shells each is faster than plotting an image with 1000 shells. An image with 4000 shells, for example, takes tens of minutes and as I will need to plot several images this execution time is impractical for daily use.
I would like to know if it is possible to speed up this plotting process. If my approach to the problem is not the best, I also accept suggestions.
Below is the portion of the code that does what I described above:
```
# Plotagem da tensão no solo no gráfico
fig, ax = plt.subplots()
levels = np.linspace(tensaoInf, tensaoSup, num=14).tolist()
levels = [num * fator for num in levels]
norm = mpl.colors.BoundaryNorm(levels, coresSAP.N, extend='both')
print(' Desenhando a imagem...')
comp = len(shellgroup.id_shells)
i = 0
for shell in shellgroup.id_shells:
i += 1
print(f' Concluído {round(i * 100/comp, 1)}%', end='\r')
plotx = []
ploty = []
plotz = []
for joint in shellgroup.lista_joints[shell]:
plotx.append(pontos_x[joint])
ploty.append(pontos_y[joint])
plotz.append(dicTensaoJoint[joint] * fator)
xpt = np.array(plotx)
ypt = np.array(ploty)
zpt = np.array(plotz)
linhas = ax.tricontour(xpt, ypt, zpt, levels=levels, colors='k', linewidths=esp_linha, linestyles='dashed')
colorido = ax.tricontourf(xpt, ypt, zpt, levels=levels, norm=norm, cmap=coresSAP, extend='both')
# ax.plot(xpt, ypt, 'ko', ms=2)
pontos = np.array([(plotx[i], ploty[i]) for i in range(len(plotx))])
hull = ConvexHull(pontos)
for simplex in hull.simplices:
ax.plot(pontos[simplex, 0], pontos[simplex, 1], 'k-', linewidth=esp_linha)
# Desenho da escala de cores
fig.colorbar(mpl.cm.ScalarMappable(norm=norm, cmap=coresSAP),
ax=ax, orientation='vertical', extendrect=True,
ticks=levels, extendfrac='auto', label=textoEscala,
fraction=fracao, pad=0.04, format="{x:.2f}")
if not os.path.exists("./FigurasPySAP"):
os.makedirs("./FigurasPySAP")
fig.savefig(f"./FigurasPySAP/tensao-{grupo}-{combsolo}.png", dpi=400, bbox_inches='tight')
```
[And an example of the type of image I'm generating](https://i.stack.imgur.com/7dO8c.png) |
```
[
{
"B4": 14,
"B5": 12
},
{
"B4": 58,
"B5": 54
},
{
"B4": 26,
"B5": 65
}
]
```
I want to create index id in my uploaded json file. The json file look like as in the image. I want it to be like the following.
[
1: {
"B4": 14,
"B5": 12
},
2: {
"B4": 58,
"B5": 54
},
3: {
"B4": 26,
"B5": 65
}
]
It's just to do some some calculations for each set and display the results. |
How to give index id to my uploaded json file in FastAPI? |
|python|json|pandas|indexing|fastapi| |
null |
My current challenge revolves around Azure Test Plan's robust test management features, which unfortunately [do not include built-in support for importing JUnit test results](https://learn.microsoft.com/en-us/azure/devops/test/associate-automated-test-with-test-case?view=azure-devops#test-types). This poses an obstacle for teams relying on JUnit for testing, as it disrupts the seamless integration and comprehensive reporting within Azure DevOps.
To address this issue, one potential remedy involves harnessing annotations and REST APIs within the test framework itself. By embedding annotations into the test code and utilizing REST APIs to interact with Azure Test Plan, teams can create a tailored integration that bridges the gap between JUnit and Azure Test Plan. However, successfully implementing this solution necessitates careful consideration of both the capabilities of the test framework and the complexities of Azure Test Plan's APIs.
This is why I created this simple [`PowerShell module`](https://powershellgallery.com/packages/Import-JUnitToAzTestPlan) that will assist anyone interested in publishing their JUnit Test Report to Azure TestPlan.
### PowerShell Command for Importing JUnit Results
The [`Import-JUnitToAzTestPlan`](https://www.powershellgallery.com/packages/Import-JUnitToAzTestPlan) PowerShell module simplifies the process of importing JUnit test results into Azure Test Plan, streamlining the integration of JUnit tests into your CI/CD pipelines.
### Getting Started: Step-by-Step Guide
1. **Install the Module**: Begin by installing the "Import-JUnitToAzTestPlan" module from the PowerShell Gallery using the [`Install-Module`](https://learn.microsoft.com/en-us/powershell/module/powershellget/install-module?view=powershellget-3.x) cmdlet.
```
Install-Module -Name Import-JUnitToAzTestPlan
```
2. **Execute the Import Command**: Utilize the [`Import-JUnitToAzTestPlan`](https://www.powershellgallery.com/packages/Import-JUnitToAzTestPlan) command, specifying the required parameters such as the Azure DevOps organization URL, project URL, test plan ID, and JUnit test result file path.
```
Import-JUnitToAzTestPlan -Token $(System.AccessToken) -ProjectUrl "https://dev.azure.com/yourorganization/yourproject" -TestPlanID 1 -TestSuiteID 11 -TestConfiguration "Windows 10" -ExecutionReport "path/to/your/junit-results.xml"
```
3. **Customize Parameters**: Adjust the parameters according to your project's configuration and requirements. For example, specify the appropriate test configuration and test suite ID.
4. **Integration with CI/CD Pipelines**: Incorporate the import command into your CI/CD pipeline workflow, ensuring seamless execution of JUnit tests and automatic import of test results into Azure Test Plan.
- Task on Azure Pipeline YAML
```yaml
- task: PowerShell@2
inputs:
targetType: 'inline'
script: |
Import-JUnitToAzTestPlan -Token <PAT> `
-ProjectUrl "https://dev.azure.com/yourorganization/yourproject" `
-TestPlanID "<TargetTestPlanID>" `
-TestSuiteID "<TargetTestSuiteID>" `
-TestConfiguration "<TargetTestConfiguration" `
-ExecutionReport "path/to/your/junit-results.xml"
pwsh: true
```
- `pwsh` is set to True as powershell core required for the module.
## Results:
[](https://i.stack.imgur.com/5Vd0R.png) |
**Uvicorn** has the option `--root-path` (https://www.uvicorn.org/settings/#http) that helps a lot if the application is mounted to a specific path, distinct to `/`. For example, in case of a Django application I can run it with:
```
uvicorn myproj.asgi:application --host=localhost --port=8001 --root-path="/myproj-custom-path"
```
So if I configure the Nginx location `/myproj-custom-path/` as `proxy_pass http://localhost:8001/`, I can access the application by `http://localhost:80/myproj-custom-path` with all the functionality, including the Admin panel, without the need to specify the root path anywhere else in the project.
Is there a similar option or a way to do the same with **uWSGI**? |
Root path analogue in uWSGI as in Uvicorn |
|python|django|nginx|uwsgi|uvicorn| |
```plugins {
id("com.android.application")
id("org.jetbrains.kotlin.android")
id("com.google.devtools.ksp")
id("com.google.dagger.hilt.android") version "2.49" apply false
}
android {
namespace = "com.example.notesapp"
compileSdk = 34
defaultConfig {
multiDexEnabled = true
applicationId = "com.example.notesapp"
minSdk = 30
targetSdk = 34
versionCode = 1
versionName = "1.0"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
vectorDrawables {
useSupportLibrary = true
}
}
buildTypes {
release {
isMinifyEnabled = false
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro"
)
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = "1.8"
}
buildFeatures {
compose = true
}
composeOptions {
kotlinCompilerExtensionVersion = "1.5.1"
}
packaging {
resources {
excludes += "/META-INF/{AL2.0,LGPL2.1}"
}
}
}
dependencies {
implementation("androidx.compose.material3:material3-android:1.2.1")
implementation("androidx.compose.material3:material3-desktop:1.2.1")
implementation("androidx.tv:tv-material:1.0.0-alpha10")
implementation("androidx.wear.compose:compose-material:1.3.0")
implementation("androidx.wear.compose:compose-material3:1.0.0-alpha19")
val room_version = "2.6.1"
val multidex_version = "2.0.1"
implementation("androidx.core:core-ktx:1.12.0")
implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.7.0")
implementation("androidx.activity:activity-compose:1.8.2")
implementation(platform("androidx.compose:compose-bom:2023.08.00"))
implementation("androidx.compose.ui:ui")
implementation("androidx.compose.ui:ui-graphics")
implementation("androidx.compose.ui:ui-tooling-preview")
implementation("androidx.compose.material3:material3")
testImplementation("junit:junit:4.13.2")
androidTestImplementation("androidx.test.ext:junit:1.1.5")
androidTestImplementation("androidx.test.espresso:espresso-core:3.5.1")
androidTestImplementation(platform("androidx.compose:compose-bom:2023.08.00"))
androidTestImplementation("androidx.compose.ui:ui-test-junit4")
debugImplementation("androidx.compose.ui:ui-tooling")
debugImplementation("androidx.compose.ui:ui-test-manifest")
implementation("androidx.multidex:multidex:$multidex_version")
// Compose dependencies
implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.7.0")
implementation("androidx.navigation:navigation-compose:2.7.7")
implementation("androidx.compose.material:material-icons-extended:")
implementation("androidx.hilt:hilt-navigation-compose:1.2.0")
implementation("androidx.compose.material:material:1.6.4")
// Coroutines
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3")
// Dagger - Hilt
implementation("com.google.dagger:hilt-android:2.49")
ksp("com.google.dagger:hilt-android-compiler:2.44")
// Room
implementation("androidx.room:room-runtime:$room_version")
ksp("androidx.room:room-compiler:$room_version")
// optional - Kotlin Extensions and Coroutines support for Room
implementation("androidx.room:room-ktx:$room_version")
}
```
every time i run the project in android studio it gives me this error
Caused by: org.gradle.workers.internal.DefaultWorkerExecutor$WorkExecutionException: A failure occurred while executing com.android.build.gradle.internal.tasks.CheckDuplicatesRunnable
i tried checking for duplicate dependencies and toggled the offline mode
still nothing works
|
using `openssl`
here is a script to print out human readable text `cert-etime-check.sh`
```bash
#!/bin/bash
set -euo pipefail
### get a cert file
declare -r cert_file=${1:? error ... cert_file ?}
### start and end dates
declare -r beg_date=$(openssl x509 -noout -startdate -in $cert_file)
declare -r end_date=$(openssl x509 -noout -enddate -in $cert_file)
### subject and issuer
declare -r subject=$(openssl x509 -noout -subject -in $cert_file)
declare -r issuer=$(openssl x509 -noout -issuer -in $cert_file)
### calculate days gone and left
declare -ir beg_sec=$(date --date="${beg_date##*=}" +%s)
declare -ir end_sec=$(date --date="${end_date##*=}" +%s)
declare -ir now_sec=$(date +%s)
declare -ir day_gone=$(( $((now_sec - beg_sec)) / 86400))
declare -ir day_left=$(( $((end_sec - now_sec)) / 86400))
### print result
date --date="${beg_date##*=}" +"beg: %F-%A (gone: $day_gone)"
date --date="${end_date##*=}" +"end: %F-%A (left: $day_left)"
echo sum: $((day_gone + $day_left))
echo sub: ${subject##* = }
echo iss: ${issuer##* = }
echo
date +"now: %F-%A"
```
usage: `./cert-etime-check.sh cert.pem`
output:
```
beg: 2024-03-04-Monday (gone: 26)
end: 2024-06-02-Sunday (left: 63)
sum: 89
sub: ******.***
iss: R3
now: 2024-03-31-Sunday
``` |
As a beginner, I want to know what I've did wrong in my code, I asked chatgpt, but it's not giving me good info. any help is appreciated.
```
web-1 | 2024/03/31 14:26:43 /usr/src/app/handlers/ads.go:59 ERROR: column "country" is of type text[] but expression is of type record (SQLSTATE 42804)
web-1 | [0.248ms] [rows:0] INSERT INTO "conditions" ("created_at","updated_at","deleted_at","ad_id","age_start","age_end","gender","country","platform") VALUES ('2024-03-31 14:26:43.751','2024-03-31 14:26:43.751',NULL,5,20,30,('M'),('TW','JP'),('android','ios')) ON CONFLICT ("id") DO UPDATE SET "ad_id"="excluded"."ad_id" RETURNING "id"
```
```go
package models
import (
"time"
"gorm.io/gorm"
)
type AD struct {
gorm.Model
Title string `json:"title" gorm:"type:text"`
StartAt time.Time `json:"startAt" gorm:"type:timestamp"`
EndAt time.Time `json:"endAt" gorm:"type:timestamp"`
IsActive bool `gorm:"default:False;type:boolean"`
Conditions []Conditions `json:"conditions"`
}
type Conditions struct {
gorm.Model
ADID uint
AgeStart int `json:"ageStart" gorm:"default:0;type:integer"`
AgeEnd int `json:"ageEnd" gorm:"default:100;type:integer"`
Gender []string `json:"gender" gorm:"type:text[]"`
Country []string `json:"country" gorm:"type:text[]"`
Platform []string `json:"platform" gorm:"type:text[]"`
}
```
```go
func CreateAd(c *fiber.Ctx) error {
ad := new(models.AD)
if err := c.BodyParser(ad); err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
"error": err.Error(),
})
}
if IsAdAlive(*ad) {
ad.IsActive = true
} else {
ad.IsActive = false
}
fmt.Println(ad)
database.DB.Db.Model(models.AD{}).Create(&ad)
return c.Status(200).JSON(ad)
}
```
I asked chatGPT, it said this:
*Review GORM Documentation: Ensure that you're using GORM's features correctly for handling arrays. GORM should abstract away the need to manually format arrays for PostgreSQL. If there's a discrepancy in how GORM expects arrays to be formatted versus what your PostgreSQL version expects, this could lead to issues. Checking the latest GORM documentation for array support or any open issues related to array handling could provide insights or solutions.*
but I can't find those. |
How to find a sequence of bytes on the target program from my injected dll? |
|c++|dll|reverse-engineering|ida|cheat-engine| |
You want to see a minimalist solution?
import math
highway_number = int(input())
exclude = [0,100,200,300,400,500,600,700,800,900]
if highway_number <= 99 and not (highway_number in exclude):
remain = math.fmod(highway_number, 2)
direction = 'north/south.' if remain == 1 else 'east/west.'
print(f"I-{highway_number} is primary, going {direction}")
elif (highway_number < 1000) and not (highway_number in exclude):
math_highway = math.fmod(highway_number, 100)
remain = math.fmod(math_highway, 2)
direction = 'north/south.' if remain == 1 else 'east/west.'
main_highway = int(math_highway)
print('I-{0} is auxiliary, serving I-{1}, going {2}'.format(highway_number, main_highway, direction))
else:
print (highway_number, 'is not a valid interstate highway number.')
|
I have a Mauiapp which I debug and test on a physical android device. All the time I had no problems but now when I switch to two sides in my app it crashes. The crash only appears in release mode and not while debuging. As mentioned it crashes only for two sides from the flyoutmenu all other sides and flyoutmenu sides work perfektly.
I don't really now what to do because I don't have any error messages or hints where the error appears.
I allready tried to delete obj and bin folder or to clean and rebuild the project.
If you need any parts of the code or something else please write a comment and thanks for your help!
UPDATE
After using Logcat I found these entries which could be a good clue:
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/Q4R6D.png
Time Device Name Type PID Tag Message
03-31 10:39:49.845 Samsung SM-A546E Verbose 1310 WindowManager Setting visibility of Window{d8681d9 u0 com.engelberthdeveloping.passwortapp/crc6451514aa4f2d5798b.MainActivity EXITING}: false, caller=com.android.server.wm.WindowContainer.sendAppVisibilityToClients:1281 com.android.server.wm.WindowToken.setClientVisible:447 com.android.server.wm.ActivityRecord.setClientVisible:7988 com.android.server.wm.ActivityRecord.postApplyAnimation:6593 com.android.server.wm.ActivityRecord.commitVisibility:6536
Time Device Name Type PID Tag Message
03-31 10:39:49.845 Samsung SM-A546E Warning 1310 WindowManager Exception thrown during dispatchAppVisibility Window{d8681d9 u0 com.engelberthdeveloping.passwortapp/crc6451514aa4f2d5798b.MainActivity EXITING}
Time Device Name Type PID Tag Message
03-31 10:39:49.845 Samsung SM-A546E Warning 1310 WindowManager android.os.DeadObjectException
at android.os.BinderProxy.transactNative(Native Method)
at android.os.BinderProxy.transact(BinderProxy.java:662)
at android.view.IWindow$Stub$Proxy.dispatchAppVisibility(IWindow.java:631)
at com.android.server.wm.WindowState.sendAppVisibilityToClients(WindowState.java:3982)
at com.android.server.wm.WindowContainer.sendAppVisibilityToClients(WindowContainer.java:1281)
at com.android.server.wm.WindowToken.setClientVisible(WindowToken.java:447)
at com.android.server.wm.ActivityRecord.setClientVisible(ActivityRecord.java:7988)
at com.android.server.wm.ActivityRecord.postApplyAnimation(ActivityRecord.java:6593)
at com.android.server.wm.ActivityRecord.commitVisibility(ActivityRecord.java:6536)
at com.android.server.wm.Transition.finishTransition(Transition.java:1400)
at com.android.server.wm.TransitionController.finishTransition(TransitionController.java:1036)
at com.android.server.wm.WindowOrganizerController.finishTransition(WindowOrganizerController.java:429)
at android.window.IWindowOrganizerController$Stub.onTransact(IWindowOrganizerController.java:286)
at com.android.server.wm.WindowOrganizerController.onTransact(WindowOrganizerController.java:207)
at android.os.Binder.execTransactInternal(Binder.java:1380)
at android.os.Binder.execTransact(Binder.java:1311)
Time Device Name Type PID Tag Message
03-31 10:39:49.845 Samsung SM-A546E Info 1310 Process Sending signal. PID: 28268 SIG: 9
Time Device Name Type PID Tag Message
03-31 10:39:49.846 Samsung SM-A546E Verbose 1310 WindowManager Remove Window{d8681d9 u0 com.engelberthdeveloping.passwortapp/crc6451514aa4f2d5798b.MainActivity EXITING}: mSurfaceController=Surface(name=com.engelberthdeveloping.passwortapp/crc6451514aa4f2d5798b.MainActivity$_28268)/@0x3fdc60a mAnimatingExit=true mRemoveOnExit=true mHasSurface=true surfaceShowing=true animating=false app-animation=false mDisplayFrozen=false callers=com.android.server.wm.WindowToken.removeAllWindowsIfPossible:258 com.android.server.wm.ActivityRecord.removeIfPossible:5063 com.android.server.wm.ActivityRecord.handleCompleteDeferredRemoval:5070 com.android.server.wm.WindowContainer.handleCompleteDeferredRemoval:1456 com.android.server.wm.TaskFragment.handleCompleteDeferredRemoval:3345 com.android.server.wm.WindowContainer.handleCompleteDeferredRemoval:1456
Time Device Name Type PID Tag Message
03-31 10:39:49.847 Samsung SM-A546E Info 1310 WindowManager Destroying surface Surface(name=com.engelberthdeveloping.passwortapp/crc6451514aa4f2d5798b.MainActivity$_28268)/@0x3fdc60a called by com.android.server.wm.WindowStateAnimator.destroySurface:789 com.android.server.wm.WindowStateAnimator.destroySurfaceLocked:472 com.android.server.wm.WindowState.removeImmediately:2904 com.android.server.wm.WindowState.removeIfPossible:3140 com.android.server.wm.WindowToken.removeAllWindowsIfPossible:258 com.android.server.wm.ActivityRecord.removeIfPossible:5063 com.android.server.wm.ActivityRecord.onRemovedFromDisplay:5145 com.android.server.wm.ActivityRecord.removeImmediately:5053
|
I'm a basic developer working on a pet project and getting myself in knots on the best approach for displaying this in a React Native app via Flatlist.
First off, this is the format of the JSON file. There are approx 7,000 of these records in the file.
```
name: "Meeting 1"
timezone: "America/Los_Angeles"
day: 2
time: "19:00"
url: "https://teams.meetings.com/xyz321"
```
What I would like to do is;
1. Get the local timezone of the user and
2. filter all meetings occurring on the current day only and
3. filter these meetings that are happening within the next hour and
4. display these meeting details in the user's local date / time as individual items within a React Native Flatlist.
I'd really appreciate if someone could offer some guidance. The DateTime functions are very difficult to get a handle on.
```
function calculateTimeDifference(timezone1, timezone2) {
// Get current date and time
const now = new Date();
const hourBefore = now.setHours(now.getHours() -1);
// Create DateTimeFormat instances for both timezones
const formatter1 = new Intl.DateTimeFormat('en-US', {
timeZone: timezone1,
hour12: false,
hour: 'numeric',
minute: 'numeric',
second: 'numeric'
});
const formatter2 = new Intl.DateTimeFormat('en-US', {
timeZone: timezone2,
hour12: false,
hour: 'numeric',
minute: 'numeric',
second: 'numeric'
});
const day1 = new Intl.DateTimeFormat('en-US', {
timeZone: timezone1,
weekday: 'long',
});
const day2 = new Intl.DateTimeFormat('en-US', {
timeZone: timezone2,
weekday: 'long',
});
// Format the current time in both timezones
const timeInZone1 = formatter1.format(hourBefore);
const timeInZone2 = formatter2.format(hourBefore);
const dayInZone1 = day1.format(now);
const dayInZone2 = day2.format(now);
// Convert the formatted times to Date objects
const dateInZone1 = new Date(`1970-01-01T${timeInZone1}Z`);
const dateInZone2 = new Date(`1970-01-01T${timeInZone2}Z`);
// Calculate the time difference in milliseconds
const timeDifferenceMs = dateInZone1 - dateInZone2;
// Convert milliseconds to hours
const hoursDifference = Math.abs(timeDifferenceMs / (1000 * 60 * 60));
console.log('-----------')
console.log(`The time at ${timezone1} is ${timeInZone1}.`);
console.log(`The time at ${timezone2} is ${timeInZone2}.`);
console.log(`The day at ${timezone1} is ${dayInZone1}.`);
console.log(`The day at ${timezone2} is ${dayInZone2}.`);
console.log(`The time difference between ${timezone1} and ${timezone2} is ${hoursDifference} hours.`);
// const hourSearch = hourBefore.substring(0,3);
const searchHour = timeInZone1.toString().substring(0,2) + ':00';
console.log(searchHour);
return searchHour;
}
```
|
TLDR: Try passing `method='basic'` or `method='percentile`'. Also, pass a NumPy `Generator` for the random state (e.g. `random_state=np.random.default_rng()`).
```python3
import numpy as np
from scipy import stats
from time import perf_counter
rng = np.random.default_rng(234893458942534)
data = np.random.rand(2**15)
data = np.array([data])
start = perf_counter()
bs = stats.bootstrap(data, np.mean, batch=1, n_resamples=10)
end = perf_counter()
print(end-start) # 13.304466278000064
start = perf_counter()
bs = stats.bootstrap(data, np.mean, batch=None, n_resamples=10,
method='basic', random_state=rng)
end = perf_counter()
print(end-start) # 0.0040362729999969815
```
This should free up enough time to do more resamples.
---
The default `method='BCa'`. This is the bias-corrected and accelerated bootstrap, which performs the jackknife to estimate the acceleration parameter. The jackknife evaluates the statistic with *N* jackknife resamples, where *N* is the number of observations in the sample; each is your original sample with one observation removed. This explains why reducing the number of bootstrap resamples does not reduce the execution time much: it's dominated by the jackknife. The other methods don't need to do the jackknife.
Passing the `Generator` for the random state boosts the speed a bit because it's faster at generating the resamples than the old `RandomState` (default).
> Setting a higher batch number increases the time consumption, as you can see above.
When the sample size is large, sure, but not in general. For smaller samples with a vectorized statistic function like `np.mean`, leaving `batch=None` or using a moderate value (e.g. `batch=100`) tends to be much faster than `batch=1` because less Python looping is required. |
**Update** The `usmap` has been modernized in version [`0.7.0`](https://github.com/cran/usmap/blob/master/NEWS.md#usmap-070) and now returns data as simple features. Hence, getting the coordinates for the scatter pies requires slightly more effort to retrieve the coordinates from the sf object:
``` r
library(usmap)
library(ggplot2)
library(scatterpie)
states <- us_map("states")
centroids <- usmapdata::centroid_labels("states")
centroids <- cbind(
abbr = centroids$abbr,
sf::st_coordinates(centroids)
) |>
as.data.frame() |>
transform(
X = as.numeric(X),
Y = as.numeric(Y)
)
data_merged <- merge(
data, centroids,
by.x = "region", by.y = "abbr",
all.x = TRUE
)
plot_usmap(regions = "states") +
geom_scatterpie(
aes(x = X, y = Y),
data = data_merged, cols = c("gas", "coal", "wind", "solar")
) +
geom_text(aes(X, Y, label = region),
data = data_merged, vjust = 1, nudge_y = -100000
)
```
<!-- -->
**Original answer**
Using the `usmap` and the `scatterpie` packages this could be achieved via `ggplot2` like so:
1. Add coordinates for the pies to your data. In the code below I use the coordinates of the state centers provided by `usmapdata::centroid_labels`
2. Add the pies from your data via `geom_scatterpie`
``` r
library(usmap)
library(ggplot2)
library(scatterpie)
states <- us_map("states")
centroids <- usmapdata::centroid_labels("states")[c("x", "y", "abbr")]
data <- merge(data, centroids, by.x = "region", by.y = "abbr", all.x = TRUE)
plot_usmap(regions = "states") +
geom_scatterpie(aes(x, y, group = region),
data = data, cols = c("gas", "coal", "wind", "solar")
) +
geom_text(aes(x, y, label = region),
data = data, vjust = 1, nudge_y = -100000
)
```

**EDIT** If you want to exclude some states (or include only some states) you could do so via the `exclude` or `include` argument of `plot_usmap`:
``` r
plot_usmap(regions = "states", exclude = c("AK", "HI")) +
geom_scatterpie(aes(x, y, group = region),
data = data, cols = c("gas", "coal", "wind", "solar")
) +
geom_text(aes(x, y, label = region),
data = data, vjust = 1, nudge_y = -100000
)
```

**DATA**
```
data <- data.frame(
region = c("AL", "AR", "AZ", "CA", "IA"),
gas = c(25, 45, 45, 60, 75),
coal = c(45, 50, 45, 20, 15),
wind = c(30, 5, 10, 20, 10),
solar = c(10, 10, 10, 10, 10)
)
```
|
This might work for you (GNU sed):
sed '/please/{x;s/^./&/m3;x;t;H;d}' file
Use the hold space as a counter for the lines containing the word `please`.
If a line contains `please` then:
Swap to the hold space, substitute the first character of the third line with itself and swap back to the pattern space.
If the substitution was successful, carry out no further processing of this line.
Otherwise, append the line to the hold space and delete the current line. |
{"Voters":[{"Id":21894964,"DisplayName":"juicy"}],"DeleteType":1} |
{"OriginalQuestionIds":[66252831],"Voters":[{"Id":442760,"DisplayName":"cafce25","BindingReason":{"GoldTagBadge":"rust"}}]} |
{"Voters":[{"Id":3001761,"DisplayName":"jonrsharpe"},{"Id":4645291,"DisplayName":"Igor Moraru"},{"Id":3840170,"DisplayName":"user3840170"}],"SiteSpecificCloseReasonIds":[11]} |
{"Voters":[{"Id":21894964,"DisplayName":"juicy"}]} |
{"Voters":[{"Id":1145388,"DisplayName":"Stephen Ostermiller"}],"SiteSpecificCloseReasonIds":[16]} |
I would think of a viewModel as being for a specific product purpose. One activity will have one or more view models. Some can be reused by other activities if desired. You can have as many api calls as you want for that product purpose connected to the viewModel. |
Here is a derivation for the control points of a unit circle segment:
https://web.archive.org/web/20221205142713/https://www.whizkidtech.redprince.net/bezier/circle/kappa/
Every possible ellipse can be generated by applying the appropriate affine transformation. |
I'm developing a library for obtaining information from files in the portable executable format.
It is important for me that the library works in both 32bit and 64bit modes.
During testing, I used hard paths for example: L"C:\\Windows\\System32\\ntoskrnl.exe" to display a list of exported functions.
In win10, I discovered that in administrator mode, my 32bit application returns error code 2 (ERROR_FILE_NOT_FOUND) when trying to open an EXISTING file, while the 64bit application successfully opens this file.
In win7 on another computer, both applications successfully open this file.
In addition, I discovered that many applications on win10, in particular total commander, winhex, x32dbg, ollydbg, do not see many files in the system32 folder.
I can read them from disk by jumping around the file system, is there any easier way? |
32 bit applications do not display some files in Windows 10 |
|windows|createfile| |
null |
public class JavaReverseNumbers {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
String input;
long remainder,inputlength,counter = 1;
System.out.println("Enter a number: ");
input = keyboard.next();
long i = Integer.parseInt(input);
inputlength = input.length();
while (counter <= inputlength){
remainder = i % 10;
i = i / 10;
System.out.print(remainder);
counter++;
}
}}
I'm new to this program, sorry for my mistakes.
Here I used a conversion from String type to int type |
ERROR: column "country" is of type text[] but expression is of type record (SQLSTATE 42804) |
|go|orm|go-gorm| |
null |
When I ran those CLI commands in my environment, I too got **same response** like this:
```bash
az ad sp create-for-rbac
az ad sp list --show-mine
```
**Response:**

This happens if the signed-in user has Admin roles like *Global Administrator* of the tenant, that won't be added as **Owner** of newly created service principal which can be checked here in Enterprise applications:

But when I ran the same commands by signing in with new user account not having *Global Administrator* access, got **response** successfully like this:
```bash
az ad sp create-for-rbac
az ad sp list --show-mine
```
**Response:**

In such cases where you are logging with Admin accounts, you can make use of below bash script that adds signed-in user as **Owner** of newly created service principal explicitly:
```bash
sp_create=$(az ad sp create-for-rbac)
echo "Output of 'az ad sp create-for-rbac':"
echo "$sp_create"
appId=$(echo $sp_create | jq -r '.appId')
# Retrieve the objectId of the service principal
spObjectId=$(az ad sp show --id $appId --query id --output tsv)
echo "Service Principal Object ID: $spObjectId"
# Get the objectId for the signed-in user
ownerObjectId=$(az ad signed-in-user show --query id -o tsv)
echo "Owner Object ID: $ownerObjectId"
# Add the signed-in user as an owner to the service principal
add_owner_response=$(az rest -m POST -u https://graph.microsoft.com/beta/servicePrincipals/$spObjectId/owners/\$ref -b "{\"@odata.id\": \"https://graph.microsoft.com/beta/directoryObjects/$ownerObjectId\"}")
echo "Owner added successfully to the service principal."
```
**Response:**

To confirm that, I checked the same in Portal where signed-in user is added as **Owner** of service principal like this:

When I ran the same command now to list applications owned by signed-in user having Admin access, I got **response** with expected results:
```bash
az ad sp list --show-mine
```
**Response:**

**Reference:**
[Overview of enterprise application ownership - Microsoft Entra ID](https://learn.microsoft.com/en-us/entra/identity/enterprise-apps/overview-assign-app-owners) |
null |
As mentioned by Mark Rotteveel the Windows on Windows 64 (WOW64) performs automatic redirection of certain file system (e.g. C:\Windows\System32, C:\Program Files) directories and registry keys (e.g. HKLM\Software, HKCU\Software) for 32-bit programs running on 64-bit systems.
The file system redirection can be turned off by calling [Wow64DisableWow64FsRedirection][1] and then re-enabled with [Wow64RevertWow64FsRedirection][2]
For the registry there is a flag (KEY_WOW64_32KEY) in the RegOpenKeyEx function to see the 32-bit view of the registry.
[1]: https://learn.microsoft.com/en-us/windows/win32/api/wow64apiset/nf-wow64apiset-wow64disablewow64fsredirection
[2]: https://learn.microsoft.com/en-us/windows/win32/api/wow64apiset/nf-wow64apiset-wow64revertwow64fsredirection |
null |
[Eventually I came up with a solution myself](https://codeberg.org/xmobar/xmobar/pulls/696/files), which was merged with the [PR #696](https://codeberg.org/xmobar/xmobar/pulls/696/commits).
When I wrote
> I know I can just wrap the text of the monitor in ``<action=`the command`>`` and `</action>` to make it clickable, but I have no clue what the command should be.
I was making the mistake of thinking that I have to know `the command` that does the right thing whatever the current layout, but that's incorrect, as I can just compute a different command for each layout, which will simply switch to the next one.
To give a concrete example, if I install the plugin like this,
```haskell
Run $ Kbd [("it", "IT"), ("ru(phonetic)", "RU"), ("us", "US")]
```
the text I want to print when each of the 3 layouts is selected is as follows:
- ``"<action=`setxkbmap -layout ru -variant phonetic` button=1>IT</action>"``
- ``"<action=`setxkbmap -layout us` button=1>RU</action>"``
- ``"<action=`setxkbmap -layout it` button=1>US</action>"``
This allow switching layouts in the order `IT`->`RU`->`US`. In the code I've contributed to xmobar, I've also wrapped those in actions to navigate the opposite direction with `button=3`. |
`enter code here
You can achieve the desire animation using zoom in effect, we can learn it through the flutter doc, or refer below code.
https://api.flutter.dev/flutter/widgets/ScaleTransition-class.html
class _ManageScale extends State<YourClass> with TickerProviderStateMixin{
late final AnimationController controller = AnimationController(
duration: const Duration(seconds:2), //you can put any seconds to show zoom in?out effect
vsync: this,
)..repeat(reverse:true) ;//putting repeat reverse true is make your container big and small in same order
late final Animation<double> _animation = CurvedAnimation(
parent: _controller,
curve:Curve.fastOutSlowIn,
);
//for proper implementation of above stateful widget see doc
now use above animation as a property in your widget which is _animation
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: ScaleTransition(
scale: _animation,
child: const Padding(
padding: EdgeInsets.all(8.0),
child: <Place_Your_Heart_Shape>(size: 150.0),
),
),
),
);
}
`
|
`enter code here
Hello`
You can achieve the desire animation using zoom in effect, we can learn it through the flutter doc, or refer below code.
https://api.flutter.dev/flutter/widgets/ScaleTransition-class.html
class _ManageScale extends State<YourClass> with TickerProviderStateMixin{
late final AnimationController controller = AnimationController(
duration: const Duration(seconds:2), //you can put any seconds to show zoom in?out effect
vsync: this,
)..repeat(reverse:true) ;//putting repeat reverse true is make your container big and small in same order
late final Animation<double> _animation = CurvedAnimation(
parent: _controller,
curve:Curve.fastOutSlowIn,
);
//for proper implementation of above stateful widget see doc
now use above animation as a property in your widget which is _animation
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: ScaleTransition(
scale: _animation,
child: const Padding(
padding: EdgeInsets.all(8.0),
child: <Place_Your_Heart_Shape>(size: 150.0),
),
),
),
);
}
`
|
Kafka provides a feature where we can specify the producer batch size. This is the size of the messages that can be sent to the Queue at once. The advantage being we can reduce the number of network calls the the Queue. Do we have anything similar in Service Bus? The only batching Service Bus does is when the message is delivered to the Queue. But this doesn’t reduce the number of I/O calls made.
The objective here is to batch the messages being sent to the Service Bus Queue by producer to reduce the number of network calls. |
Producer Batching Service Bus Vs Kafka |
|azure|apache-kafka|azureservicebus|servicebus| |
null |
This is more a hint than a question:
The goal is to parse a command line **AND** create a useful *usage* message
code:
for arg in "$@" ; do
case "${1:-}" in
--edit) # edit file
cd "$(dirname $0)" && exec $0;;
--noN) # do NOT create 'NHI1/../tags'
let noN=1;;
--noS) # doe NOT create 'HOME/src/*-latest/tags'
let noS=1;;
*) echo -e "usage: $(basename $0) options...\n$(awk '/--?\w+\)/' "$0")" && exit ;;
esac
done
this create the *usage* message:
> build_tags.bash -x
usage: build_tags.bash options...
--edit) # edit file
--noN) # do NOT create 'NHI1/../tags'
--noS) # doe NOT create 'HOME/src/*-latest/tags'
the clue is that the *definition* of the *case* target is also the *documentation* of the *case* target.
|
parse command line arguments with bash and write useful usage message |
|bash|command-line|command-line-arguments| |
I would like to put spaces when entering an amount like this. Do I have to use javascript?
Thank you for your help me[enter image description here][1]
[1]: https://i.stack.imgur.com/KAYLy.png |
put white spaces when entering an amount moneytype symfony |
|jquery|symfony-forms| |
Yes, SQLite explicitly supports multi-database transactions (see https://www.sqlite.org/atomiccommit.html#_multi_file_commit for technical details):
> When multiple database files are modified within a single transaction, all files are updated atomically. In other words, either all of the database files are updated or else none of them are.
However, this is only true for [journal modes](https://www.sqlite.org/pragma.html#pragma_journal_mode) involving a rollback journal (like the default `journal_mode=DELETE`). If the database file is in the more performant [WAL mode][1], then the above guarantee is changed to:
> Transactions that involve changes against multiple ATTACHed databases
> are atomic for each individual database, but are not atomic across all
> databases as a set.
[1]: https://www.sqlite.org/wal.html |