content
stringlengths 86
88.9k
| title
stringlengths 0
150
| question
stringlengths 1
35.8k
| answers
list | answers_scores
list | non_answers
list | non_answers_scores
list | tags
list | name
stringlengths 30
130
|
---|---|---|---|---|---|---|---|---|
Q:
Using both public and private cloud kit database synched with CoreData
I have watched Nick Gillette's WWDC2020 talk on using the public Cloud Kit database synched with CoreData but I am confused on how to tell the system I wish two entities to be in the public database and the rest to be in the private database. The use case is some help text which is available to all users as well as images that are available to all users, everything else requires a share invite. The app has been working fine with just the private database and shares, now I am trying to add the public data. I have already made the mods needed to configure the public store so I think all I need is the ability to tell Cloud Kit which entities are public.
Can anyone point me in the right direction?
A:
I think you'll need a feature of NSManagedObjectModel called Configurations to create a config that contains only the public entities. And also use CloudKitContainerOptions on an extra store description that uses the config and the public database.
These are covered in Nick's talk a year earlier: Using Core Data with Cloudkit WWDC 2019
|
Using both public and private cloud kit database synched with CoreData
|
I have watched Nick Gillette's WWDC2020 talk on using the public Cloud Kit database synched with CoreData but I am confused on how to tell the system I wish two entities to be in the public database and the rest to be in the private database. The use case is some help text which is available to all users as well as images that are available to all users, everything else requires a share invite. The app has been working fine with just the private database and shares, now I am trying to add the public data. I have already made the mods needed to configure the public store so I think all I need is the ability to tell Cloud Kit which entities are public.
Can anyone point me in the right direction?
|
[
"I think you'll need a feature of NSManagedObjectModel called Configurations to create a config that contains only the public entities. And also use CloudKitContainerOptions on an extra store description that uses the config and the public database.\nThese are covered in Nick's talk a year earlier: Using Core Data with Cloudkit WWDC 2019\n"
] |
[
0
] |
[] |
[] |
[
"cloudkit",
"core_data"
] |
stackoverflow_0074662759_cloudkit_core_data.txt
|
Q:
Why do zero-sized types cause real allocations in some cases?
I was playing with zero-sized types (ZSTs) as I was curious about how they are actually implemented under the hood. Given that ZSTs do not require any space in memory and taking a raw pointer is a safe operation, I was interested what raw pointers I would get from different kinds of ZST "allocations" and how weird (for safe Rust) the results would be.
My first attempt (test_stk.rs) was to take const pointers to a few on-stack instances of ZSTs:
struct Empty;
struct EmptyAgain;
fn main() {
let stk_ptr: *const Empty = &Empty;
let stk_ptr_again: *const EmptyAgain = &EmptyAgain;
let nested_stk_ptr = nested_stk();
println!("Pointer to on-stack Empty: {:?}", stk_ptr);
println!("Pointer to on-stack EmptyAgain: {:?}", stk_ptr_again);
println!("Pointer to Empty in nested frame: {:?}", nested_stk_ptr);
}
fn nested_stk() -> *const Empty {
&Empty
}
Compiling and running this produced the following result:
$ rustc test_stk.rs -o test_stk
$ ./test_stk
Pointer to on-stack Empty: 0x55ab86fc6000
Pointer to on-stack EmptyAgain: 0x55ab86fc6000
Pointer to Empty in nested frame: 0x55ab86fc6000
A short analysis of the process memory map showed that 0x55ab86fc6000 was actually not a stack allocation, but the very beginning of the .rodata section. This seems logical: the compiler pretends that there is a single zero-sized value for each ZST, known at compile time, and each of these values resides in .rodata, as compile-time constants do.
The second attempt was with boxed ZSTs (test_box.rs):
struct Empty;
struct EmptyAgain;
fn main() {
let ptr = Box::into_raw(Box::new(Empty));
let ptr_again = Box::into_raw(Box::new(EmptyAgain));
let nested_ptr = nested_box();
println!("Pointer to boxed Empty: {:?}", ptr);
println!("Pointer to boxed EmptyAgain: {:?}", ptr_again);
println!("Pointer to boxed Empty in nested frame: {:?}", nested_ptr);
}
fn nested_box() -> *mut Empty {
Box::into_raw(Box::new(Empty))
}
Running this snippet gave:
$ rustc test_box.rs -o test_box
$ ./test_box
Pointer to boxed Empty: 0x1
Pointer to boxed EmptyAgain: 0x1
Pointer to boxed Empty in nested frame: 0x1
Quick debugging showed that this is how the allocator works for ZSTs (Rust's liballoc/alloc.rs):
unsafe fn exchange_malloc(size: usize, align: usize) -> *mut u8 {
if size == 0 {
align as *mut u8
} else {
// ...
}
}
The minimum possible alignment is 1 (as per the Nomicon), so for ZSTs the box operator calls exchange_malloc(0, 1) and the resulting address is 0x1.
After noticing that into_raw() returns a mutable pointer, I decided to retry the previous test (on-stack) with mutable pointers (test_stk_mut.rs):
struct Empty;
struct EmptyAgain;
fn main() {
let stk_ptr: *mut Empty = &mut Empty;
let stk_ptr_again: *mut EmptyAgain = &mut EmptyAgain;
let nested_stk_ptr = nested_stk();
println!("Pointer to on-stack Empty: {:?}", stk_ptr);
println!("Pointer to on-stack EmptyAgain: {:?}", stk_ptr_again);
println!("Pointer to Empty in nested frame: {:?}", nested_stk_ptr);
}
fn nested_stk() -> *mut Empty {
&mut Empty
}
And running this printed the following:
$ rustc test_stk_mut.rs -o test_stk_mut
$ ./test_stk_mut
Pointer to on-stack Empty: 0x7ffc3817b5e0
Pointer to on-stack EmptyAgain: 0x7ffc3817b5f0
Pointer to Empty in nested frame: 0x7ffc3817b580
It turns out that this time I had real stack-allocated values, each having its own address! When I tried to declare them sequentially (test_stk_seq.rs), I discovered that each of these values occupied eight bytes:
struct Empty;
fn main() {
let mut stk1 = Empty;
let mut stk2 = Empty;
let mut stk3 = Empty;
let mut stk4 = Empty;
let mut stk5 = Empty;
let stk_ptr1: *mut Empty = &mut stk1;
let stk_ptr2: *mut Empty = &mut stk2;
let stk_ptr3: *mut Empty = &mut stk3;
let stk_ptr4: *mut Empty = &mut stk4;
let stk_ptr5: *mut Empty = &mut stk5;
println!("Pointer to on-stack Empty: {:?}", stk_ptr1);
println!("Pointer to on-stack Empty: {:?}", stk_ptr2);
println!("Pointer to on-stack Empty: {:?}", stk_ptr3);
println!("Pointer to on-stack Empty: {:?}", stk_ptr4);
println!("Pointer to on-stack Empty: {:?}", stk_ptr5);
}
Run:
$ rustc test_stk_seq.rs -o test_stk_seq
$ ./test_stk_seq
Pointer to on-stack Empty: 0x7ffdba303840
Pointer to on-stack Empty: 0x7ffdba303848
Pointer to on-stack Empty: 0x7ffdba303850
Pointer to on-stack Empty: 0x7ffdba303858
Pointer to on-stack Empty: 0x7ffdba303860
So, here are the things I cannot understand:
Why do boxed ZST allocations use the dumb 0x1 address instead of something more meaningful, like in case of "on-stack" values?
Why is there need to allocate real space for on-stack ZST values when there are mutable raw pointers to them?
Why are exactly eight bytes used for mutable on-stack allocations? Should I treat this size as "0 bytes of actual type size + 8 bytes of alignment"?
A:
The reason that boxed ZST allocations use the dumb 0x1 address is because the allocator is not aware of the type of the value being allocated. It just sees that the size is 0 and the alignment is 1, so it returns 0x1.
There is no need to allocate real space for on-stack ZST values when there are mutable raw pointers to them. The raw pointers are just pointers to the memory location where the value is stored, and the value itself doesn't take up any space.
The reason that eight bytes are used for mutable on-stack allocations is because that is the minimum alignment that the allocator can provide. The allocator needs to ensure that the values are properly aligned so that they can be safely accessed.
A:
So if the allocator API doesn't support zero-sized allocations, what on earth do we store as our allocation? NonNull::dangling() of course! Almost every operation with a ZST is a no-op since ZSTs have exactly one value, and therefore no state needs to be considered to store or load them. This actually extends to ptr::read and ptr::write: they won't actually look at the pointer at all. As such we never need to change the pointer.
A:
In Rust, zero-sized types (ZSTs) are types that do not require any space in memory. This means that when a ZST is allocated on the stack or in the heap, no memory is actually allocated for it. However, when a ZST is allocated on the stack, the compiler pretends that there is a single zero-sized value for each ZST, known at compile time, and each of these values resides in the .rodata section. When a ZST is allocated in the heap, the allocator returns a pointer to a fixed address (0x1) for all ZST allocations. This is because the allocator's exchange_malloc() function returns a pointer to the requested alignment when the size parameter is 0.
|
Why do zero-sized types cause real allocations in some cases?
|
I was playing with zero-sized types (ZSTs) as I was curious about how they are actually implemented under the hood. Given that ZSTs do not require any space in memory and taking a raw pointer is a safe operation, I was interested what raw pointers I would get from different kinds of ZST "allocations" and how weird (for safe Rust) the results would be.
My first attempt (test_stk.rs) was to take const pointers to a few on-stack instances of ZSTs:
struct Empty;
struct EmptyAgain;
fn main() {
let stk_ptr: *const Empty = &Empty;
let stk_ptr_again: *const EmptyAgain = &EmptyAgain;
let nested_stk_ptr = nested_stk();
println!("Pointer to on-stack Empty: {:?}", stk_ptr);
println!("Pointer to on-stack EmptyAgain: {:?}", stk_ptr_again);
println!("Pointer to Empty in nested frame: {:?}", nested_stk_ptr);
}
fn nested_stk() -> *const Empty {
&Empty
}
Compiling and running this produced the following result:
$ rustc test_stk.rs -o test_stk
$ ./test_stk
Pointer to on-stack Empty: 0x55ab86fc6000
Pointer to on-stack EmptyAgain: 0x55ab86fc6000
Pointer to Empty in nested frame: 0x55ab86fc6000
A short analysis of the process memory map showed that 0x55ab86fc6000 was actually not a stack allocation, but the very beginning of the .rodata section. This seems logical: the compiler pretends that there is a single zero-sized value for each ZST, known at compile time, and each of these values resides in .rodata, as compile-time constants do.
The second attempt was with boxed ZSTs (test_box.rs):
struct Empty;
struct EmptyAgain;
fn main() {
let ptr = Box::into_raw(Box::new(Empty));
let ptr_again = Box::into_raw(Box::new(EmptyAgain));
let nested_ptr = nested_box();
println!("Pointer to boxed Empty: {:?}", ptr);
println!("Pointer to boxed EmptyAgain: {:?}", ptr_again);
println!("Pointer to boxed Empty in nested frame: {:?}", nested_ptr);
}
fn nested_box() -> *mut Empty {
Box::into_raw(Box::new(Empty))
}
Running this snippet gave:
$ rustc test_box.rs -o test_box
$ ./test_box
Pointer to boxed Empty: 0x1
Pointer to boxed EmptyAgain: 0x1
Pointer to boxed Empty in nested frame: 0x1
Quick debugging showed that this is how the allocator works for ZSTs (Rust's liballoc/alloc.rs):
unsafe fn exchange_malloc(size: usize, align: usize) -> *mut u8 {
if size == 0 {
align as *mut u8
} else {
// ...
}
}
The minimum possible alignment is 1 (as per the Nomicon), so for ZSTs the box operator calls exchange_malloc(0, 1) and the resulting address is 0x1.
After noticing that into_raw() returns a mutable pointer, I decided to retry the previous test (on-stack) with mutable pointers (test_stk_mut.rs):
struct Empty;
struct EmptyAgain;
fn main() {
let stk_ptr: *mut Empty = &mut Empty;
let stk_ptr_again: *mut EmptyAgain = &mut EmptyAgain;
let nested_stk_ptr = nested_stk();
println!("Pointer to on-stack Empty: {:?}", stk_ptr);
println!("Pointer to on-stack EmptyAgain: {:?}", stk_ptr_again);
println!("Pointer to Empty in nested frame: {:?}", nested_stk_ptr);
}
fn nested_stk() -> *mut Empty {
&mut Empty
}
And running this printed the following:
$ rustc test_stk_mut.rs -o test_stk_mut
$ ./test_stk_mut
Pointer to on-stack Empty: 0x7ffc3817b5e0
Pointer to on-stack EmptyAgain: 0x7ffc3817b5f0
Pointer to Empty in nested frame: 0x7ffc3817b580
It turns out that this time I had real stack-allocated values, each having its own address! When I tried to declare them sequentially (test_stk_seq.rs), I discovered that each of these values occupied eight bytes:
struct Empty;
fn main() {
let mut stk1 = Empty;
let mut stk2 = Empty;
let mut stk3 = Empty;
let mut stk4 = Empty;
let mut stk5 = Empty;
let stk_ptr1: *mut Empty = &mut stk1;
let stk_ptr2: *mut Empty = &mut stk2;
let stk_ptr3: *mut Empty = &mut stk3;
let stk_ptr4: *mut Empty = &mut stk4;
let stk_ptr5: *mut Empty = &mut stk5;
println!("Pointer to on-stack Empty: {:?}", stk_ptr1);
println!("Pointer to on-stack Empty: {:?}", stk_ptr2);
println!("Pointer to on-stack Empty: {:?}", stk_ptr3);
println!("Pointer to on-stack Empty: {:?}", stk_ptr4);
println!("Pointer to on-stack Empty: {:?}", stk_ptr5);
}
Run:
$ rustc test_stk_seq.rs -o test_stk_seq
$ ./test_stk_seq
Pointer to on-stack Empty: 0x7ffdba303840
Pointer to on-stack Empty: 0x7ffdba303848
Pointer to on-stack Empty: 0x7ffdba303850
Pointer to on-stack Empty: 0x7ffdba303858
Pointer to on-stack Empty: 0x7ffdba303860
So, here are the things I cannot understand:
Why do boxed ZST allocations use the dumb 0x1 address instead of something more meaningful, like in case of "on-stack" values?
Why is there need to allocate real space for on-stack ZST values when there are mutable raw pointers to them?
Why are exactly eight bytes used for mutable on-stack allocations? Should I treat this size as "0 bytes of actual type size + 8 bytes of alignment"?
|
[
"\nThe reason that boxed ZST allocations use the dumb 0x1 address is because the allocator is not aware of the type of the value being allocated. It just sees that the size is 0 and the alignment is 1, so it returns 0x1.\n\nThere is no need to allocate real space for on-stack ZST values when there are mutable raw pointers to them. The raw pointers are just pointers to the memory location where the value is stored, and the value itself doesn't take up any space.\n\nThe reason that eight bytes are used for mutable on-stack allocations is because that is the minimum alignment that the allocator can provide. The allocator needs to ensure that the values are properly aligned so that they can be safely accessed.\n\n\n",
"So if the allocator API doesn't support zero-sized allocations, what on earth do we store as our allocation? NonNull::dangling() of course! Almost every operation with a ZST is a no-op since ZSTs have exactly one value, and therefore no state needs to be considered to store or load them. This actually extends to ptr::read and ptr::write: they won't actually look at the pointer at all. As such we never need to change the pointer.\n",
"In Rust, zero-sized types (ZSTs) are types that do not require any space in memory. This means that when a ZST is allocated on the stack or in the heap, no memory is actually allocated for it. However, when a ZST is allocated on the stack, the compiler pretends that there is a single zero-sized value for each ZST, known at compile time, and each of these values resides in the .rodata section. When a ZST is allocated in the heap, the allocator returns a pointer to a fixed address (0x1) for all ZST allocations. This is because the allocator's exchange_malloc() function returns a pointer to the requested alignment when the size parameter is 0.\n"
] |
[
0,
0,
0
] |
[] |
[] |
[
"pointers",
"rust"
] |
stackoverflow_0058529934_pointers_rust.txt
|
Q:
How to remove white space on website from SVG symbol at botton of index.html
On youtube I learned how to place my SVG code inside a elements at the bottom of my index.html and whenever I want to use the SVG then I would use the tags. Doing this makes sure that my code remains clean and it worked.
Now I am finished with my project but under my footer, there is this big white space. When using chrome inspect, I can see that the white space is used for the bottom SVG's. Even when styling the SVG to visibility: hidden; , it is still showing the white space.
How should I approach this problem so that the bottom SVG's are in my index.html but not on my live server page?
In the image: the brown part is my footer and the white space underneath is what I am talking about.
enter image description here
In the first part you can see how I use the elements
<article class="service-blocks service-block1">
<div class="square">
<svg class="cog-icon" width="80"><use href="#cog-icon"></use></svg>
</div>
<div class="triangle"></div>
<div class="service-text">
<h3><strong>Mobile first</strong></h3>
<p>Start with mobile and work your way up with media queries.</p>
</div>
</article>
Here you see the SVG saved at the bottom
<!-- SVG 3 column top ---------------------------------------------->
<div class="svgs">
<svg style="visibility: hidden;">
<symbol id="cog-icon"
class="icons"
aria-hidden="true"
focusable="false"
data-prefix="fas"
data-icon="cog"
role="img"
viewBox="0 0 512 512"
xmlns="http://www.w3.org/2000/svg">
<path fill="white"
d="M487.4 315.7l-42.6-24.6c4.3-23.2
4.3-47 0-70.2l42.6-24.6c4.9-2.8
7.1-8.6 5.5-14-11.1-35.6-30-67.8-54.7-94.6-3.8-4.1-10-5.1-14.8-2.3L380.8
110c-17.9-15.4-38.5-27.3-60.8-35.1V25.8c0-5.6-3.9-10.5-9.4-11.7-36.7-8.2-74.3-7.8-109.2 0-5.5 1.2-9.4
6.1-9.4 11.7V75c-22.2 7.9-42.8 19.8-60.8 35.1L88.7
85.5c-4.9-2.8-11-1.9-14.8 2.3-24.7 26.7-43.6 58.9-54.7
94.6-1.7 5.4.6 11.2 5.5 14L67.3 221c-4.3 23.2-4.3 47
0 70.2l-42.6 24.6c-4.9 2.8-7.1 8.6-5.5 14 11.1 35.6
30 67.8 54.7 94.6 3.8 4.1 10 5.1 14.8 2.3l42.6-24.6c17.9
15.4 38.5 27.3 60.8 35.1v49.2c0 5.6 3.9 10.5 9.4 11.7 36.7
8.2 74.3 7.8 109.2 0 5.5-1.2 9.4-6.1 9.4-11.7v-49.2c22.2-7.9
42.8-19.8 60.8-35.1l42.6 24.6c4.9 2.8 11 1.9 14.8-2.3 24.7-26.7
43.6-58.9 54.7-94.6 1.5-5.5-.7-11.3-5.6-14.1zM256 336c-44.1
0-80-35.9-80-80s35.9-80 80-80 80 35.9 80 80-35.9 80-80 80z">
</path>
</symbol>
</svg>
</body>
</html>
I tried removing the bottom SVG's and the white space disappeared. But then I lost the purpose of this technique to not clutter my code with SVG-code.
I tried using an direct style on the SVG --> visiblility: hidden; but the space was still showing
I put the SVG's in a div and give the div a visibility: hidden; style but I had the same issue as above.
A:
To make the bottom SVG invisible you can set the height and width to 0. The CSS property visibility will hide content, but it will still take up the space on the page.
Also, to remove the white space around the icon in the top set both width and height.
<article class="service-blocks service-block1">
<div class="square">
<svg xmlns="http://www.w3.org/2000/svg" class="cog-icon" width="80" height="80">
<use href="#cog-icon" />
</svg>
</div>
<div class="triangle"></div>
<div class="service-text">
<h3><strong>Mobile first</strong></h3>
<p>Start with mobile and work your way up with media queries.</p>
</div>
</article>
<!-- SVG 3 column top ---------------------------------------------->
<svg width="0" height="0" style="display:none" xmlns="http://www.w3.org/2000/svg">
<symbol id="cog-icon"
class="icons"
aria-hidden="true"
focusable="false"
data-prefix="fas"
data-icon="cog"
role="img"
viewBox="0 0 512 512" >
<path fill="orange" d="M 487.4 315.7 l -42.6 -24.6 c 4.3 -23.2 4.3 -47 0 -70.2 l 42.6 -24.6 c 4.9 -2.8 7.1 -8.6 5.5 -14 c -11.1 -35.6 -30 -67.8 -54.7 -94.6 c -3.8 -4.1 -10 -5.1 -14.8 -2.3 L 380.8 110 c -17.9 -15.4 -38.5 -27.3 -60.8 -35.1 V 25.8 c 0 -5.6 -3.9 -10.5 -9.4 -11.7 c -36.7 -8.2 -74.3 -7.8 -109.2 0 c -5.5 1.2 -9.4 6.1 -9.4 11.7 V 75 c -22.2 7.9 -42.8 19.8 -60.8 35.1 L 88.7 85.5 c -4.9 -2.8 -11 -1.9 -14.8 2.3 c -24.7 26.7 -43.6 58.9 -54.7 94.6 c -1.7 5.4 0.6 11.2 5.5 14 L 67.3 221 c -4.3 23.2 -4.3 47 0 70.2 l -42.6 24.6 c -4.9 2.8 -7.1 8.6 -5.5 14 c 11.1 35.6 30 67.8 54.7 94.6 c 3.8 4.1 10 5.1 14.8 2.3 l 42.6 -24.6 c 17.9 15.4 38.5 27.3 60.8 35.1 v 49.2 c 0 5.6 3.9 10.5 9.4 11.7 c 36.7 8.2 74.3 7.8 109.2 0 c 5.5 -1.2 9.4 -6.1 9.4 -11.7 v -49.2 c 22.2 -7.9 42.8 -19.8 60.8 -35.1 l 42.6 24.6 c 4.9 2.8 11 1.9 14.8 -2.3 c 24.7 -26.7 43.6 -58.9 54.7 -94.6 c 1.5 -5.5 -0.7 -11.3 -5.6 -14.1 z M 256 336 c -44.1 0 -80 -35.9 -80 -80 s 35.9 -80 80 -80 s 80 35.9 80 80 s -35.9 80 -80 80 z" />
</symbol>
</svg>
|
How to remove white space on website from SVG symbol at botton of index.html
|
On youtube I learned how to place my SVG code inside a elements at the bottom of my index.html and whenever I want to use the SVG then I would use the tags. Doing this makes sure that my code remains clean and it worked.
Now I am finished with my project but under my footer, there is this big white space. When using chrome inspect, I can see that the white space is used for the bottom SVG's. Even when styling the SVG to visibility: hidden; , it is still showing the white space.
How should I approach this problem so that the bottom SVG's are in my index.html but not on my live server page?
In the image: the brown part is my footer and the white space underneath is what I am talking about.
enter image description here
In the first part you can see how I use the elements
<article class="service-blocks service-block1">
<div class="square">
<svg class="cog-icon" width="80"><use href="#cog-icon"></use></svg>
</div>
<div class="triangle"></div>
<div class="service-text">
<h3><strong>Mobile first</strong></h3>
<p>Start with mobile and work your way up with media queries.</p>
</div>
</article>
Here you see the SVG saved at the bottom
<!-- SVG 3 column top ---------------------------------------------->
<div class="svgs">
<svg style="visibility: hidden;">
<symbol id="cog-icon"
class="icons"
aria-hidden="true"
focusable="false"
data-prefix="fas"
data-icon="cog"
role="img"
viewBox="0 0 512 512"
xmlns="http://www.w3.org/2000/svg">
<path fill="white"
d="M487.4 315.7l-42.6-24.6c4.3-23.2
4.3-47 0-70.2l42.6-24.6c4.9-2.8
7.1-8.6 5.5-14-11.1-35.6-30-67.8-54.7-94.6-3.8-4.1-10-5.1-14.8-2.3L380.8
110c-17.9-15.4-38.5-27.3-60.8-35.1V25.8c0-5.6-3.9-10.5-9.4-11.7-36.7-8.2-74.3-7.8-109.2 0-5.5 1.2-9.4
6.1-9.4 11.7V75c-22.2 7.9-42.8 19.8-60.8 35.1L88.7
85.5c-4.9-2.8-11-1.9-14.8 2.3-24.7 26.7-43.6 58.9-54.7
94.6-1.7 5.4.6 11.2 5.5 14L67.3 221c-4.3 23.2-4.3 47
0 70.2l-42.6 24.6c-4.9 2.8-7.1 8.6-5.5 14 11.1 35.6
30 67.8 54.7 94.6 3.8 4.1 10 5.1 14.8 2.3l42.6-24.6c17.9
15.4 38.5 27.3 60.8 35.1v49.2c0 5.6 3.9 10.5 9.4 11.7 36.7
8.2 74.3 7.8 109.2 0 5.5-1.2 9.4-6.1 9.4-11.7v-49.2c22.2-7.9
42.8-19.8 60.8-35.1l42.6 24.6c4.9 2.8 11 1.9 14.8-2.3 24.7-26.7
43.6-58.9 54.7-94.6 1.5-5.5-.7-11.3-5.6-14.1zM256 336c-44.1
0-80-35.9-80-80s35.9-80 80-80 80 35.9 80 80-35.9 80-80 80z">
</path>
</symbol>
</svg>
</body>
</html>
I tried removing the bottom SVG's and the white space disappeared. But then I lost the purpose of this technique to not clutter my code with SVG-code.
I tried using an direct style on the SVG --> visiblility: hidden; but the space was still showing
I put the SVG's in a div and give the div a visibility: hidden; style but I had the same issue as above.
|
[
"To make the bottom SVG invisible you can set the height and width to 0. The CSS property visibility will hide content, but it will still take up the space on the page.\nAlso, to remove the white space around the icon in the top set both width and height.\n\n\n<article class=\"service-blocks service-block1\">\n <div class=\"square\">\n <svg xmlns=\"http://www.w3.org/2000/svg\" class=\"cog-icon\" width=\"80\" height=\"80\">\n <use href=\"#cog-icon\" />\n </svg>\n </div>\n <div class=\"triangle\"></div>\n <div class=\"service-text\">\n <h3><strong>Mobile first</strong></h3>\n <p>Start with mobile and work your way up with media queries.</p>\n </div>\n</article>\n\n<!-- SVG 3 column top ---------------------------------------------->\n<svg width=\"0\" height=\"0\" style=\"display:none\" xmlns=\"http://www.w3.org/2000/svg\">\n <symbol id=\"cog-icon\" \n class=\"icons\" \n aria-hidden=\"true\" \n focusable=\"false\" \n data-prefix=\"fas\" \n data-icon=\"cog\" \n role=\"img\" \n viewBox=\"0 0 512 512\" >\n <path fill=\"orange\" d=\"M 487.4 315.7 l -42.6 -24.6 c 4.3 -23.2 4.3 -47 0 -70.2 l 42.6 -24.6 c 4.9 -2.8 7.1 -8.6 5.5 -14 c -11.1 -35.6 -30 -67.8 -54.7 -94.6 c -3.8 -4.1 -10 -5.1 -14.8 -2.3 L 380.8 110 c -17.9 -15.4 -38.5 -27.3 -60.8 -35.1 V 25.8 c 0 -5.6 -3.9 -10.5 -9.4 -11.7 c -36.7 -8.2 -74.3 -7.8 -109.2 0 c -5.5 1.2 -9.4 6.1 -9.4 11.7 V 75 c -22.2 7.9 -42.8 19.8 -60.8 35.1 L 88.7 85.5 c -4.9 -2.8 -11 -1.9 -14.8 2.3 c -24.7 26.7 -43.6 58.9 -54.7 94.6 c -1.7 5.4 0.6 11.2 5.5 14 L 67.3 221 c -4.3 23.2 -4.3 47 0 70.2 l -42.6 24.6 c -4.9 2.8 -7.1 8.6 -5.5 14 c 11.1 35.6 30 67.8 54.7 94.6 c 3.8 4.1 10 5.1 14.8 2.3 l 42.6 -24.6 c 17.9 15.4 38.5 27.3 60.8 35.1 v 49.2 c 0 5.6 3.9 10.5 9.4 11.7 c 36.7 8.2 74.3 7.8 109.2 0 c 5.5 -1.2 9.4 -6.1 9.4 -11.7 v -49.2 c 22.2 -7.9 42.8 -19.8 60.8 -35.1 l 42.6 24.6 c 4.9 2.8 11 1.9 14.8 -2.3 c 24.7 -26.7 43.6 -58.9 54.7 -94.6 c 1.5 -5.5 -0.7 -11.3 -5.6 -14.1 z M 256 336 c -44.1 0 -80 -35.9 -80 -80 s 35.9 -80 80 -80 s 80 35.9 80 80 s -35.9 80 -80 80 z\" />\n </symbol>\n</svg>\n\n\n\n"
] |
[
0
] |
[] |
[] |
[
"css",
"html",
"svg",
"symbols",
"visibility"
] |
stackoverflow_0074666882_css_html_svg_symbols_visibility.txt
|
Q:
Return boolean if postgresql match is found
I am a beginner when it comes to databases. I would like to return true in postgresql if there is a player in my players table with is_active set to true and return false otherwise. Should I use a procedure or function for this ? I tried did this with simple select but i guess its not good idea.
How should it look like ?
CREATE TABLE player (
user_id INT8 PRIMARY KEY,
is_active BOOLEAN NOT NULL
);
```
A:
You don't need a function or a loop:
select exists (select *
from player
where is_active)
|
Return boolean if postgresql match is found
|
I am a beginner when it comes to databases. I would like to return true in postgresql if there is a player in my players table with is_active set to true and return false otherwise. Should I use a procedure or function for this ? I tried did this with simple select but i guess its not good idea.
How should it look like ?
CREATE TABLE player (
user_id INT8 PRIMARY KEY,
is_active BOOLEAN NOT NULL
);
```
|
[
"You don't need a function or a loop:\nselect exists (select * \n from player\n where is_active)\n\n"
] |
[
0
] |
[] |
[] |
[
"loops",
"postgresql",
"procedure",
"sql"
] |
stackoverflow_0074669679_loops_postgresql_procedure_sql.txt
|
Q:
Error While Using Multiprocessing Library in Python
I am getting an error on Python when using the Multiprocessing library.
I have a list of 18,000 ids to collect via a GET from an external API (function update_events()) and then save each json file to blob storage in Azure . This would take a long time in a single-threaded environment so I decided to use a thread pool.
import logging
LOGGER = logging.getLogger(__name__)
logging.basicConfig(level=logging.ERROR)
logging.getLogger(__name__).setLevel(logging.DEBUG)
import json
from Multiprocessing import Pool
def update_events(id:int):
try:
events = get_events(id) ### This is a GET to an external API
file_name = str(id) + '.json'
upsert_obj(file_name,'events',json.dumps(events))
except Exception:
LOGGER.error("Unable to write " + file_name + " to events folder")
### This command writes the file to Azure Blob Storage
def upsert_obj(file_name: str, container_name: str, sb_data: dict):
try:
blob_client = blob_service_client.get_blob_client(
container=PATH+"/"+str(container_name), blob=file_name)
blob_client.upload_blob(sb_data, overwrite=True)
LOGGER.info("Successfully upsert " +
file_name + " to " + container_name)
except Exception as e:
LOGGER.error(e)
## This is the multithreaded function
def get_data_multithreaded(new_ids:list):
with Pool(60) as p:
p.map(update_events,new_ids)
def collect_data(new_events_ids):
LOGGER.info('Starting collection...')
start_time = time.time()
get_data(new_events_ids)
LOGGER.info("--- %s seconds ---" % (time.time() - start_time))
So I open jupyter-notebook and type the following:
new_ids= [1234,4567,6789] # just an example, many more ids in reality
collect_data [new_ids]
And it works for the most part. However, at some point during the collection I hit an error:
UnboundLocalError: local variable 'file_name' referenced before assignment
As this is multi-threaded, I'm not very sure how or if I have error handled correctly. I'm also not sure if the error is coming from update_events() or upsert_obj(). As far as I know we are not hitting any rate limits on the API.
A:
Thanks @Axe319 for the solution, it looks like I need to initialize file_name before everything else, as in here:
def update_events(id:int):
try:
### Initialize first to ensure it's defined for error log
file_name = str(id) + '.json'
### If get_events errors out now, Exception will log properly
events = get_events(id)
upsert_obj(file_name,'events',json.dumps(events))
except Exception:
LOGGER.error("Unable to write " + file_name + " to events folder")
I can confirm this fixed the initial issue after writing the logs to a text file. The multithreaded approach confused me at first but I think I understand now.
|
Error While Using Multiprocessing Library in Python
|
I am getting an error on Python when using the Multiprocessing library.
I have a list of 18,000 ids to collect via a GET from an external API (function update_events()) and then save each json file to blob storage in Azure . This would take a long time in a single-threaded environment so I decided to use a thread pool.
import logging
LOGGER = logging.getLogger(__name__)
logging.basicConfig(level=logging.ERROR)
logging.getLogger(__name__).setLevel(logging.DEBUG)
import json
from Multiprocessing import Pool
def update_events(id:int):
try:
events = get_events(id) ### This is a GET to an external API
file_name = str(id) + '.json'
upsert_obj(file_name,'events',json.dumps(events))
except Exception:
LOGGER.error("Unable to write " + file_name + " to events folder")
### This command writes the file to Azure Blob Storage
def upsert_obj(file_name: str, container_name: str, sb_data: dict):
try:
blob_client = blob_service_client.get_blob_client(
container=PATH+"/"+str(container_name), blob=file_name)
blob_client.upload_blob(sb_data, overwrite=True)
LOGGER.info("Successfully upsert " +
file_name + " to " + container_name)
except Exception as e:
LOGGER.error(e)
## This is the multithreaded function
def get_data_multithreaded(new_ids:list):
with Pool(60) as p:
p.map(update_events,new_ids)
def collect_data(new_events_ids):
LOGGER.info('Starting collection...')
start_time = time.time()
get_data(new_events_ids)
LOGGER.info("--- %s seconds ---" % (time.time() - start_time))
So I open jupyter-notebook and type the following:
new_ids= [1234,4567,6789] # just an example, many more ids in reality
collect_data [new_ids]
And it works for the most part. However, at some point during the collection I hit an error:
UnboundLocalError: local variable 'file_name' referenced before assignment
As this is multi-threaded, I'm not very sure how or if I have error handled correctly. I'm also not sure if the error is coming from update_events() or upsert_obj(). As far as I know we are not hitting any rate limits on the API.
|
[
"Thanks @Axe319 for the solution, it looks like I need to initialize file_name before everything else, as in here:\ndef update_events(id:int):\n try: \n ### Initialize first to ensure it's defined for error log\n file_name = str(id) + '.json' \n\n ### If get_events errors out now, Exception will log properly\n events = get_events(id) \n\n upsert_obj(file_name,'events',json.dumps(events))\n except Exception:\n LOGGER.error(\"Unable to write \" + file_name + \" to events folder\") \n\nI can confirm this fixed the initial issue after writing the logs to a text file. The multithreaded approach confused me at first but I think I understand now.\n"
] |
[
1
] |
[] |
[] |
[
"concurrency",
"multithreading",
"python",
"python_logging",
"python_multiprocessing"
] |
stackoverflow_0074659662_concurrency_multithreading_python_python_logging_python_multiprocessing.txt
|
Q:
View on_failure_callback DAG logger
Let's take an example DAG.
Here is the code for it.
import logging
from airflow import DAG
from datetime import datetime, timedelta
from airflow.models import TaskInstance
from airflow.operators.python import PythonOperator
from airflow.operators.dummy import DummyOperator
def task_failure_notification_alert(context):
logging.info("Task context details: %s", str(context))
def dag_failure_notification_alert(context):
logging.info("DAG context details: %s", str(context))
def red_exception_task(ti: TaskInstance, **kwargs):
raise Exception('red')
default_args = {
"owner": "analytics",
"start_date": datetime(2021, 12, 12),
'retries': 0,
'retry_delay': timedelta(),
"schedule_interval": "@daily"
}
dag = DAG('logger_dag',
default_args=default_args,
catchup=False,
on_failure_callback=dag_failure_notification_alert
)
start_task = DummyOperator(task_id="start_task", dag=dag, on_failure_callback=task_failure_notification_alert)
red_task = PythonOperator(
dag=dag,
task_id='red_task',
python_callable=red_exception_task,
provide_context=True,
on_failure_callback=task_failure_notification_alert
)
end_task = DummyOperator(task_id="end_task", dag=dag, on_failure_callback=task_failure_notification_alert)
start_task >> red_task >> end_task
We can see two functions i.e. task_failure_notification_alert and dag_failure_notification_alert are being called in case of failures.
We can see logs in case of Task failure by the below steps.
We can see logs for the task as below.
but I am unable to find logs for the on_failure_callback of DAG anywhere in UI. Where can we see it?
A:
Under airflow/logs find the "scheduler" folder, under it look for the specific date you ran the Dag for example 2022-12-03 and there you will see name of the dag_file.log.
|
View on_failure_callback DAG logger
|
Let's take an example DAG.
Here is the code for it.
import logging
from airflow import DAG
from datetime import datetime, timedelta
from airflow.models import TaskInstance
from airflow.operators.python import PythonOperator
from airflow.operators.dummy import DummyOperator
def task_failure_notification_alert(context):
logging.info("Task context details: %s", str(context))
def dag_failure_notification_alert(context):
logging.info("DAG context details: %s", str(context))
def red_exception_task(ti: TaskInstance, **kwargs):
raise Exception('red')
default_args = {
"owner": "analytics",
"start_date": datetime(2021, 12, 12),
'retries': 0,
'retry_delay': timedelta(),
"schedule_interval": "@daily"
}
dag = DAG('logger_dag',
default_args=default_args,
catchup=False,
on_failure_callback=dag_failure_notification_alert
)
start_task = DummyOperator(task_id="start_task", dag=dag, on_failure_callback=task_failure_notification_alert)
red_task = PythonOperator(
dag=dag,
task_id='red_task',
python_callable=red_exception_task,
provide_context=True,
on_failure_callback=task_failure_notification_alert
)
end_task = DummyOperator(task_id="end_task", dag=dag, on_failure_callback=task_failure_notification_alert)
start_task >> red_task >> end_task
We can see two functions i.e. task_failure_notification_alert and dag_failure_notification_alert are being called in case of failures.
We can see logs in case of Task failure by the below steps.
We can see logs for the task as below.
but I am unable to find logs for the on_failure_callback of DAG anywhere in UI. Where can we see it?
|
[
"Under airflow/logs find the \"scheduler\" folder, under it look for the specific date you ran the Dag for example 2022-12-03 and there you will see name of the dag_file.log.\n"
] |
[
1
] |
[] |
[] |
[
"airflow",
"directed_acyclic_graphs"
] |
stackoverflow_0074660082_airflow_directed_acyclic_graphs.txt
|
Q:
sh: symfony-cmd: command not found
I have downgraded a Symfony 5.2 app template to use Symfony 4.4 in order to allow the use of some libraries that require an older version of Symfony. The problem is that when I do composer install, I get this error near the end of the installation:
sh: symfony-cmd: command not found
It seems that the installations are mostly successful, as my vendor folder is created and populated. But I'm worried about the error.
What does this error mean? How do I fix it?
====
Edit: Here's my composer.json file:
{
"type": "project",
"license": "proprietary",
"minimum-stability": "dev",
"prefer-stable": true,
"require": {
"php": ">=7.4.0",
"ext-ctype": "*",
"ext-iconv": "*",
"ext-json": "*",
"composer/package-versions-deprecated": "1.11.99.1",
"cweagans/composer-patches": "^1.7",
"doctrine/doctrine-bundle": "^2.4",
"doctrine/doctrine-migrations-bundle": "^3.1",
"doctrine/orm": "^2.9",
"phpdocumentor/reflection-docblock": "*",
"sensio/framework-extra-bundle": "*",
"symfony/framework-bundle": "4.4.*",
"symfony/http-client": "*",
"symfony/intl": "*",
"symfony/mailer": "*",
"symfony/mime": "*",
"symfony/monolog-bundle": "^3.1",
"symfony/notifier": "*",
"symfony/process": "*",
"symfony/property-access": "*",
"symfony/property-info": "*",
"symfony/proxy-manager-bridge": "*",
"symfony/security-bundle": "*",
"symfony/serializer": "*",
"symfony/string": "*",
"symfony/translation": "*",
"symfony/twig-bundle": "*",
"symfony/validator": "*",
"symfony/web-link": "*",
"symfony/yaml": "*",
"twig/extra-bundle": "*",
"twig/twig": "*"
},
"require-dev": {
"doctrine/doctrine-fixtures-bundle": "^3.4",
"roave/security-advisories": "dev-master",
"symfony/browser-kit": "*",
"symfony/css-selector": "*",
"symfony/debug-bundle": "*",
"symfony/maker-bundle": "*",
"symfony/phpunit-bridge": "*",
"symfony/stopwatch": "*",
"symfony/var-dumper": "*",
"symfony/web-profiler-bundle": "*",
"vimeo/psalm": "^4.9"
},
"config": {
"optimize-autoloader": true,
"preferred-install": {
"*": "dist"
},
"sort-packages": true
},
"autoload": {
"psr-4": {
"App\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"App\\Tests\\": "tests/"
}
},
"replace": {
"symfony/polyfill-ctype": "*",
"symfony/polyfill-iconv": "*",
"symfony/polyfill-php72": "*"
},
"scripts": {
"auto-scripts": {
"cache:clear": "symfony-cmd",
"assets:install %PUBLIC_DIR%": "symfony-cmd"
},
"post-install-cmd": [
"@auto-scripts"
],
"post-update-cmd": [
"@auto-scripts"
]
},
"conflict": {
"symfony/symfony": "*"
},
"extra": {
"symfony": {
"allow-contrib": false,
"require": "5.2.*"
},
"patches": {
"symfony/maker-bundle": {
"Provide flag to force annotation in make entity command": "https://raw.githubusercontent.com/vklux/maker-bundle-force-annotation/master/maker-force-annotation-flag.patch"
}
}
}
}
A:
For those who have the symfony/flex package installed and are still getting the error, make sure the symfony/flex package is allowed to execute code when running composer.
This is because since Composer 2.2.0 the allow-plugins option adds a layer of security that allows you to restrict which Composer plugins can execute code at startup time.
So make sure you have the appropriate line in the allow-plugins config in your composer.json file
"config": {
// other config...
"allow-plugins": {
"symfony/flex": true
}
},
A:
symfony-cmd is a part of Symfony Flex. Your composer.json does not contain any requirement for Flex, so running composer require symfony/flex might resolve that problem.
A:
While adding symfony/flex to the project is one solution, keep in mind that Flex is optional. If you want to get rid of the error without installing Flex, simply remove the symfony-cmd command references from your composer.json.
Before:
"scripts": {
"auto-scripts": {
"cache:clear": "symfony-cmd",
"assets:install %PUBLIC_DIR%": "symfony-cmd"
},
"post-install-cmd": [
"@auto-scripts"
],
"post-update-cmd": [
"@auto-scripts"
]
},
After:
"scripts": {
"auto-scripts": {},
"post-install-cmd": [],
"post-update-cmd": []
},
A:
I ran into a special case were an old deploy script added --no-plugins to my composer command. Removing that solved my issue with using deployer v6.
set('composer_options', '{{composer_action}} --verbose --prefer-dist --no-progress --no-interaction --no-dev --optimize-autoloader');
Apparently you need plugins for flex to work, and I'm assuming since the scripts block has some commands you need that too. So having no script/plugins will break your installation.
|
sh: symfony-cmd: command not found
|
I have downgraded a Symfony 5.2 app template to use Symfony 4.4 in order to allow the use of some libraries that require an older version of Symfony. The problem is that when I do composer install, I get this error near the end of the installation:
sh: symfony-cmd: command not found
It seems that the installations are mostly successful, as my vendor folder is created and populated. But I'm worried about the error.
What does this error mean? How do I fix it?
====
Edit: Here's my composer.json file:
{
"type": "project",
"license": "proprietary",
"minimum-stability": "dev",
"prefer-stable": true,
"require": {
"php": ">=7.4.0",
"ext-ctype": "*",
"ext-iconv": "*",
"ext-json": "*",
"composer/package-versions-deprecated": "1.11.99.1",
"cweagans/composer-patches": "^1.7",
"doctrine/doctrine-bundle": "^2.4",
"doctrine/doctrine-migrations-bundle": "^3.1",
"doctrine/orm": "^2.9",
"phpdocumentor/reflection-docblock": "*",
"sensio/framework-extra-bundle": "*",
"symfony/framework-bundle": "4.4.*",
"symfony/http-client": "*",
"symfony/intl": "*",
"symfony/mailer": "*",
"symfony/mime": "*",
"symfony/monolog-bundle": "^3.1",
"symfony/notifier": "*",
"symfony/process": "*",
"symfony/property-access": "*",
"symfony/property-info": "*",
"symfony/proxy-manager-bridge": "*",
"symfony/security-bundle": "*",
"symfony/serializer": "*",
"symfony/string": "*",
"symfony/translation": "*",
"symfony/twig-bundle": "*",
"symfony/validator": "*",
"symfony/web-link": "*",
"symfony/yaml": "*",
"twig/extra-bundle": "*",
"twig/twig": "*"
},
"require-dev": {
"doctrine/doctrine-fixtures-bundle": "^3.4",
"roave/security-advisories": "dev-master",
"symfony/browser-kit": "*",
"symfony/css-selector": "*",
"symfony/debug-bundle": "*",
"symfony/maker-bundle": "*",
"symfony/phpunit-bridge": "*",
"symfony/stopwatch": "*",
"symfony/var-dumper": "*",
"symfony/web-profiler-bundle": "*",
"vimeo/psalm": "^4.9"
},
"config": {
"optimize-autoloader": true,
"preferred-install": {
"*": "dist"
},
"sort-packages": true
},
"autoload": {
"psr-4": {
"App\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"App\\Tests\\": "tests/"
}
},
"replace": {
"symfony/polyfill-ctype": "*",
"symfony/polyfill-iconv": "*",
"symfony/polyfill-php72": "*"
},
"scripts": {
"auto-scripts": {
"cache:clear": "symfony-cmd",
"assets:install %PUBLIC_DIR%": "symfony-cmd"
},
"post-install-cmd": [
"@auto-scripts"
],
"post-update-cmd": [
"@auto-scripts"
]
},
"conflict": {
"symfony/symfony": "*"
},
"extra": {
"symfony": {
"allow-contrib": false,
"require": "5.2.*"
},
"patches": {
"symfony/maker-bundle": {
"Provide flag to force annotation in make entity command": "https://raw.githubusercontent.com/vklux/maker-bundle-force-annotation/master/maker-force-annotation-flag.patch"
}
}
}
}
|
[
"For those who have the symfony/flex package installed and are still getting the error, make sure the symfony/flex package is allowed to execute code when running composer.\nThis is because since Composer 2.2.0 the allow-plugins option adds a layer of security that allows you to restrict which Composer plugins can execute code at startup time.\nSo make sure you have the appropriate line in the allow-plugins config in your composer.json file\n\"config\": { \n // other config...\n\n \"allow-plugins\": {\n \"symfony/flex\": true\n }\n},\n\n",
"symfony-cmd is a part of Symfony Flex. Your composer.json does not contain any requirement for Flex, so running composer require symfony/flex might resolve that problem.\n",
"While adding symfony/flex to the project is one solution, keep in mind that Flex is optional. If you want to get rid of the error without installing Flex, simply remove the symfony-cmd command references from your composer.json.\nBefore:\n \"scripts\": {\n \"auto-scripts\": {\n \"cache:clear\": \"symfony-cmd\",\n \"assets:install %PUBLIC_DIR%\": \"symfony-cmd\"\n },\n \"post-install-cmd\": [\n \"@auto-scripts\"\n ],\n \"post-update-cmd\": [\n \"@auto-scripts\"\n ]\n },\n\nAfter:\n \"scripts\": {\n \"auto-scripts\": {},\n \"post-install-cmd\": [],\n \"post-update-cmd\": []\n },\n\n",
"I ran into a special case were an old deploy script added --no-plugins to my composer command. Removing that solved my issue with using deployer v6.\nset('composer_options', '{{composer_action}} --verbose --prefer-dist --no-progress --no-interaction --no-dev --optimize-autoloader');\nApparently you need plugins for flex to work, and I'm assuming since the scripts block has some commands you need that too. So having no script/plugins will break your installation.\n"
] |
[
24,
12,
5,
0
] |
[] |
[] |
[
"composer_php",
"symfony",
"symfony_flex"
] |
stackoverflow_0068973158_composer_php_symfony_symfony_flex.txt
|
Q:
How to call any phone number using only internet?
I really need for help.
I want to use in my application a call option.
The device will be connected to the internet, I want to call any phone number including the landline (the second device who will receive the call, will not be connected to internet), from the internet, is this possible?
If yes, are there any services or APIs to do this?
I would be grateful for any help
A:
This is a vague question.
If you want to programmatically call any phone number, I wonder what you are intending to do once the call is connected. Play a pre-recorded message?
Or have a voice-grade, two-way conversation? How does the local end of the call connect to a human?
Are you asking this in the context of a VOIP system that connects to the PSTN such as asterisk VOIP system?
Do you actually mean that you want to send a text message to any phone number?
There are lots of services and APIs available, you just have to know how to ask better questions.
|
How to call any phone number using only internet?
|
I really need for help.
I want to use in my application a call option.
The device will be connected to the internet, I want to call any phone number including the landline (the second device who will receive the call, will not be connected to internet), from the internet, is this possible?
If yes, are there any services or APIs to do this?
I would be grateful for any help
|
[
"This is a vague question.\nIf you want to programmatically call any phone number, I wonder what you are intending to do once the call is connected. Play a pre-recorded message?\nOr have a voice-grade, two-way conversation? How does the local end of the call connect to a human?\nAre you asking this in the context of a VOIP system that connects to the PSTN such as asterisk VOIP system?\nDo you actually mean that you want to send a text message to any phone number?\nThere are lots of services and APIs available, you just have to know how to ask better questions.\n"
] |
[
0
] |
[] |
[] |
[
"android",
"android_studio",
"phone_call"
] |
stackoverflow_0074669719_android_android_studio_phone_call.txt
|
Q:
input unicode character string ('u+2022') and output character
I have a Python program that uses a dictionary with Unicode number strings in it, then prints out the actual character. My code looks like this:
unicodeChars = {'bullet': 'u+2022'}
print(chr(unicodeChars['bullet']))
But I am receiving the following error:
TypeError: 'str' object cannot be interpreted as an integer
Can I solve this somehow?
A:
Take a look at the Unicode HOWTO. You will see that you really are looking for this instead:
unicodeChars = {'bullet': '\u2022'}
print(unicodeChars['bullet'])
|
input unicode character string ('u+2022') and output character
|
I have a Python program that uses a dictionary with Unicode number strings in it, then prints out the actual character. My code looks like this:
unicodeChars = {'bullet': 'u+2022'}
print(chr(unicodeChars['bullet']))
But I am receiving the following error:
TypeError: 'str' object cannot be interpreted as an integer
Can I solve this somehow?
|
[
"Take a look at the Unicode HOWTO. You will see that you really are looking for this instead:\nunicodeChars = {'bullet': '\\u2022'}\nprint(unicodeChars['bullet'])\n\n"
] |
[
0
] |
[] |
[] |
[
"list",
"python",
"python_3.x",
"python_unicode"
] |
stackoverflow_0074669668_list_python_python_3.x_python_unicode.txt
|
Q:
Adding new points to point cloud in real time - Open3D
I am using Open3D to visualize point clouds in Python. Essentially, what I want to do is add another point to the point cloud programmatically and then render it in real time.
This is what I have so far. I could not find any solution to this.
In the code below, I show one possible solution, but it is not effective. The points get added and a new window is opened as soon as the first one is closed. This is not what I want. I want it to dynamically show new points, without closing and opening again. As well as the fact that a new variable is created, which I think can be problematic when working with larger and larger data sets
import open3d as o3d
import numpy as np
#Create two random points
randomPoints = np.random.rand(2, 3)
pointSet = o3d.geometry.PointCloud()
pointSet.points = o3d.utility.Vector3dVector(randomPoints)
#Visualize the two random points
o3d.visualization.draw_geometries([pointSet])
#Here I want to add more points to the pointSet
#This solution does not work effective
#Create another random set
p1 = np.random.rand(3, 3)
p2 = np.concatenate((pointSet.points, p1), axis=0)
pointSet2 = o3d.geometry.PointCloud()
pointSet2.points = o3d.utility.Vector3dVector(p2)
o3d.visualization.draw_geometries([pointSet2])
Is there any possible solution to this?
If not, what other libraries can I look at that has the ability to render new incoming points in real time.
A:
In below page, it explains how to update visualizer without close the window.
http://www.open3d.org/docs/release/tutorial/visualization/non_blocking_visualization.html
Code may look like below:
// set up an new empty pcd
// init visualizer
// for loop :
//add new points into pcd
//visualizer update as sample code
//done
A:
New points can be added and visualized interactively to a PointCloud by extending PointCloud.points with the new coordinates.
This is because when we use numpy arrays, we need to create a Vector3dVector isntance which has the convenient method extend implemented. From the docs:
extend(*args, **kwargs)
Overloaded function.
extend(self: open3d.cpu.pybind.utility.Vector3dVector, L:
open3d.cpu.pybind.utility.Vector3dVector) -> None
Extend the list by appending all the items in the given list
extend(self: open3d.cpu.pybind.utility.Vector3dVector, L: Iterable) ->
None
Extend the list by appending all the items in the given list
So we can use different object instances e.g. ndarrays, Vector3dVector, lists etc.
A toy example and its result:
import open3d as o3d
import numpy as np
import time
# create visualizer and window.
vis = o3d.visualization.Visualizer()
vis.create_window(height=480, width=640)
# initialize pointcloud instance.
pcd = o3d.geometry.PointCloud()
# *optionally* add initial points
points = np.random.rand(10, 3)
pcd.points = o3d.utility.Vector3dVector(points)
# include it in the visualizer before non-blocking visualization.
vis.add_geometry(pcd)
# to add new points each dt secs.
dt = 0.01
# number of points that will be added
n_new = 10
previous_t = time.time()
# run non-blocking visualization.
# To exit, press 'q' or click the 'x' of the window.
keep_running = True
while keep_running:
if time.time() - previous_t > dt:
# Options (uncomment each to try them out):
# 1) extend with ndarrays.
pcd.points.extend(np.random.rand(n_new, 3))
# 2) extend with Vector3dVector instances.
# pcd.points.extend(
# o3d.utility.Vector3dVector(np.random.rand(n_new, 3)))
# 3) other iterables, e.g
# pcd.points.extend(np.random.rand(n_new, 3).tolist())
vis.update_geometry(pcd)
previous_t = time.time()
keep_running = vis.poll_events()
vis.update_renderer()
vis.destroy_window()
Why not create an updated geometry and remove the old one?
For completeness, other (which I believe to be not better) alternative approach could consist on the following steps:
Remove the current PointCloud
concatenate the new points as in the OP's question
Create new Pointcloud and add it to the visualizer.
This yields worse perfomance and barely allows interaction with the visualization.
To see this, let's have a look to the following comparison, with the same settings (code below). Both versions run the same time (~10 secs).
Using extend
Removing and creating PointCloud
✔️ Allows interaction
❌ Difficult interaction
Mean execution time (for adding points): 0.590 ms
Mean execution time (for adding points): 1.550 ms
Code to reproduce:
import open3d as o3d
import numpy as np
import time
# Global settings.
dt = 3e-2 # to add new points each dt secs.
t_total = 10 # total time to run this script.
n_new = 10 # number of points that will be added each iteration.
#---
# 1st, using extend. Run non-blocking visualization.
# create visualizer and window.
vis = o3d.visualization.Visualizer()
vis.create_window(height=480, width=640)
# initialize pointcloud instance.
pcd = o3d.geometry.PointCloud()
# *optionally* add initial points
points = np.random.rand(10, 3)
pcd.points = o3d.utility.Vector3dVector(points)
# include it in the visualizer before non-blocking visualization.
vis.add_geometry(pcd)
exec_times = []
current_t = time.time()
t0 = current_t
while current_t - t0 < t_total:
previous_t = time.time()
while current_t - previous_t < dt:
s = time.time()
# Options (uncomment each to try it out):
# 1) extend with ndarrays.
pcd.points.extend(np.random.rand(n_new, 3))
# 2) extend with Vector3dVector instances.
# pcd.points.extend(
# o3d.utility.Vector3dVector(np.random.rand(n_new, 3)))
# 3) other iterables, e.g
# pcd.points.extend(np.random.rand(n_new, 3).tolist())
vis.update_geometry(pcd)
current_t = time.time()
exec_times.append(time.time() - s)
vis.poll_events()
vis.update_renderer()
print(f"Using extend\t\t\t# Points: {len(pcd.points)},\n"
f"\t\t\t\t\t\tMean execution time:{np.mean(exec_times):.5f}")
vis.destroy_window()
# ---
# 2nd, using remove + create + add PointCloud. Run non-blocking visualization.
# create visualizer and window.
vis = o3d.visualization.Visualizer()
vis.create_window(height=480, width=640)
# initialize pointcloud instance.
pcd = o3d.geometry.PointCloud()
points = np.random.rand(10, 3)
pcd.points = o3d.utility.Vector3dVector(points)
vis.add_geometry(pcd)
exec_times = []
current_t = time.time()
t0 = current_t
previous_t = current_t
while current_t - t0 < t_total:
previous_t = time.time()
while current_t - previous_t < dt:
s = time.time()
# remove, create and add new geometry.
vis.remove_geometry(pcd)
pcd = o3d.geometry.PointCloud()
points = np.concatenate((points, np.random.rand(n_new, 3)))
pcd.points = o3d.utility.Vector3dVector(points)
vis.add_geometry(pcd)
current_t = time.time()
exec_times.append(time.time() - s)
current_t = time.time()
vis.poll_events()
vis.update_renderer()
print(f"Without using extend\t# Points: {len(pcd.points)},\n"
f"\t\t\t\t\t\tMean execution time:{np.mean(exec_times):.5f}")
vis.destroy_window()
|
Adding new points to point cloud in real time - Open3D
|
I am using Open3D to visualize point clouds in Python. Essentially, what I want to do is add another point to the point cloud programmatically and then render it in real time.
This is what I have so far. I could not find any solution to this.
In the code below, I show one possible solution, but it is not effective. The points get added and a new window is opened as soon as the first one is closed. This is not what I want. I want it to dynamically show new points, without closing and opening again. As well as the fact that a new variable is created, which I think can be problematic when working with larger and larger data sets
import open3d as o3d
import numpy as np
#Create two random points
randomPoints = np.random.rand(2, 3)
pointSet = o3d.geometry.PointCloud()
pointSet.points = o3d.utility.Vector3dVector(randomPoints)
#Visualize the two random points
o3d.visualization.draw_geometries([pointSet])
#Here I want to add more points to the pointSet
#This solution does not work effective
#Create another random set
p1 = np.random.rand(3, 3)
p2 = np.concatenate((pointSet.points, p1), axis=0)
pointSet2 = o3d.geometry.PointCloud()
pointSet2.points = o3d.utility.Vector3dVector(p2)
o3d.visualization.draw_geometries([pointSet2])
Is there any possible solution to this?
If not, what other libraries can I look at that has the ability to render new incoming points in real time.
|
[
"In below page, it explains how to update visualizer without close the window.\nhttp://www.open3d.org/docs/release/tutorial/visualization/non_blocking_visualization.html\nCode may look like below:\n// set up an new empty pcd\n// init visualizer\n// for loop :\n//add new points into pcd\n\n//visualizer update as sample code\n\n//done\n",
"New points can be added and visualized interactively to a PointCloud by extending PointCloud.points with the new coordinates.\nThis is because when we use numpy arrays, we need to create a Vector3dVector isntance which has the convenient method extend implemented. From the docs:\n\nextend(*args, **kwargs)\nOverloaded function.\n\nextend(self: open3d.cpu.pybind.utility.Vector3dVector, L:\nopen3d.cpu.pybind.utility.Vector3dVector) -> None\n\nExtend the list by appending all the items in the given list\n\nextend(self: open3d.cpu.pybind.utility.Vector3dVector, L: Iterable) ->\nNone\n\nExtend the list by appending all the items in the given list\n\nSo we can use different object instances e.g. ndarrays, Vector3dVector, lists etc.\nA toy example and its result:\n\nimport open3d as o3d\nimport numpy as np\nimport time\n\n\n# create visualizer and window.\nvis = o3d.visualization.Visualizer()\nvis.create_window(height=480, width=640)\n\n# initialize pointcloud instance.\npcd = o3d.geometry.PointCloud()\n# *optionally* add initial points\npoints = np.random.rand(10, 3)\npcd.points = o3d.utility.Vector3dVector(points)\n\n# include it in the visualizer before non-blocking visualization.\nvis.add_geometry(pcd)\n\n# to add new points each dt secs.\ndt = 0.01\n# number of points that will be added\nn_new = 10\n\nprevious_t = time.time()\n\n# run non-blocking visualization. \n# To exit, press 'q' or click the 'x' of the window.\nkeep_running = True\nwhile keep_running:\n \n if time.time() - previous_t > dt:\n # Options (uncomment each to try them out):\n # 1) extend with ndarrays.\n pcd.points.extend(np.random.rand(n_new, 3))\n \n # 2) extend with Vector3dVector instances.\n # pcd.points.extend(\n # o3d.utility.Vector3dVector(np.random.rand(n_new, 3)))\n \n # 3) other iterables, e.g\n # pcd.points.extend(np.random.rand(n_new, 3).tolist())\n \n vis.update_geometry(pcd)\n previous_t = time.time()\n\n keep_running = vis.poll_events()\n vis.update_renderer()\n\nvis.destroy_window()\n\n\nWhy not create an updated geometry and remove the old one?\nFor completeness, other (which I believe to be not better) alternative approach could consist on the following steps:\n\nRemove the current PointCloud\nconcatenate the new points as in the OP's question\nCreate new Pointcloud and add it to the visualizer.\n\nThis yields worse perfomance and barely allows interaction with the visualization.\nTo see this, let's have a look to the following comparison, with the same settings (code below). Both versions run the same time (~10 secs).\n\n\n\n\nUsing extend\nRemoving and creating PointCloud\n\n\n\n\n✔️ Allows interaction\n❌ Difficult interaction\n\n\n\n\n\n\nMean execution time (for adding points): 0.590 ms\nMean execution time (for adding points): 1.550 ms\n\n\n\n\nCode to reproduce:\nimport open3d as o3d\nimport numpy as np\nimport time\n\n# Global settings.\ndt = 3e-2 # to add new points each dt secs.\nt_total = 10 # total time to run this script.\nn_new = 10 # number of points that will be added each iteration.\n\n#---\n# 1st, using extend. Run non-blocking visualization.\n\n# create visualizer and window.\nvis = o3d.visualization.Visualizer()\nvis.create_window(height=480, width=640)\n\n# initialize pointcloud instance.\npcd = o3d.geometry.PointCloud()\n# *optionally* add initial points\npoints = np.random.rand(10, 3)\npcd.points = o3d.utility.Vector3dVector(points)\n# include it in the visualizer before non-blocking visualization.\nvis.add_geometry(pcd)\n\nexec_times = []\n\ncurrent_t = time.time()\nt0 = current_t\n\nwhile current_t - t0 < t_total:\n\n previous_t = time.time()\n\n while current_t - previous_t < dt:\n s = time.time()\n\n # Options (uncomment each to try it out):\n # 1) extend with ndarrays.\n pcd.points.extend(np.random.rand(n_new, 3))\n\n # 2) extend with Vector3dVector instances.\n # pcd.points.extend(\n # o3d.utility.Vector3dVector(np.random.rand(n_new, 3)))\n\n # 3) other iterables, e.g\n # pcd.points.extend(np.random.rand(n_new, 3).tolist())\n\n vis.update_geometry(pcd)\n\n current_t = time.time()\n exec_times.append(time.time() - s)\n\n vis.poll_events()\n vis.update_renderer()\n\nprint(f\"Using extend\\t\\t\\t# Points: {len(pcd.points)},\\n\"\n f\"\\t\\t\\t\\t\\t\\tMean execution time:{np.mean(exec_times):.5f}\")\n\nvis.destroy_window()\n\n# ---\n# 2nd, using remove + create + add PointCloud. Run non-blocking visualization.\n\n# create visualizer and window.\nvis = o3d.visualization.Visualizer()\nvis.create_window(height=480, width=640)\n\n# initialize pointcloud instance.\npcd = o3d.geometry.PointCloud()\npoints = np.random.rand(10, 3)\npcd.points = o3d.utility.Vector3dVector(points)\nvis.add_geometry(pcd)\n\nexec_times = []\n\ncurrent_t = time.time()\nt0 = current_t\nprevious_t = current_t\n\nwhile current_t - t0 < t_total:\n\n previous_t = time.time()\n\n while current_t - previous_t < dt:\n s = time.time()\n\n # remove, create and add new geometry.\n vis.remove_geometry(pcd)\n pcd = o3d.geometry.PointCloud()\n points = np.concatenate((points, np.random.rand(n_new, 3)))\n pcd.points = o3d.utility.Vector3dVector(points)\n vis.add_geometry(pcd)\n\n current_t = time.time()\n exec_times.append(time.time() - s)\n\n current_t = time.time()\n\n vis.poll_events()\n vis.update_renderer()\n\nprint(f\"Without using extend\\t# Points: {len(pcd.points)},\\n\"\n f\"\\t\\t\\t\\t\\t\\tMean execution time:{np.mean(exec_times):.5f}\")\n\nvis.destroy_window()\n\n"
] |
[
0,
0
] |
[] |
[] |
[
"numpy",
"open3d",
"python"
] |
stackoverflow_0065774814_numpy_open3d_python.txt
|
Q:
How does VS Code automatically detect port allocated by the command and start port forwarding it when working remotely?
I know that this question look similar to VSCode [Remote Development] [Forward Port] work? but it isn't.
When I launch a command which starts a web server on a random port (and prints out the url to access it),
VS Code auto detects the newly allocated port and starts port forwarding that port to my host machine.
How does this happen? Does VS Code check for newly allocated port by the current command ? If so, how does the shell script for this look like ?
A:
This has been answered by VSCode developer on github here.
To summarize, VSCode will actively look into the proc file system ie. /proc directory and detect the port that was allocated and then start auto portforwarding it.
A:
Assuming remote.autoForwardPorts is set to true, it depends on the operating system that VS Code is running on.
On Windows and Mac remotes, it picks up from the terminal output (the output option under remote.autoForwardPortsSource):
Note: on Windows and Mac remotes, selecting the process option has no effect and output will be used.
On other operating system remotes, if the process option is selected, VS Code watches for processes that start with a port included, and automatically forwards ports for those:
|
How does VS Code automatically detect port allocated by the command and start port forwarding it when working remotely?
|
I know that this question look similar to VSCode [Remote Development] [Forward Port] work? but it isn't.
When I launch a command which starts a web server on a random port (and prints out the url to access it),
VS Code auto detects the newly allocated port and starts port forwarding that port to my host machine.
How does this happen? Does VS Code check for newly allocated port by the current command ? If so, how does the shell script for this look like ?
|
[
"This has been answered by VSCode developer on github here.\nTo summarize, VSCode will actively look into the proc file system ie. /proc directory and detect the port that was allocated and then start auto portforwarding it.\n",
"Assuming remote.autoForwardPorts is set to true, it depends on the operating system that VS Code is running on.\nOn Windows and Mac remotes, it picks up from the terminal output (the output option under remote.autoForwardPortsSource):\n\nNote: on Windows and Mac remotes, selecting the process option has no effect and output will be used.\nOn other operating system remotes, if the process option is selected, VS Code watches for processes that start with a port included, and automatically forwards ports for those:\n\n"
] |
[
1,
0
] |
[] |
[] |
[
"portforwarding",
"ssh",
"ssh_tunnel",
"visual_studio_code"
] |
stackoverflow_0071128644_portforwarding_ssh_ssh_tunnel_visual_studio_code.txt
|
Q:
Why Puppeteer not working in Brave™ portable?
All versions Works fine But , in the Brave™ portable from portapps (Edited Version) ,not working i use puppeteerSharp with Plugin Extrasharp, so when i try to open the browser , the browser open but without navigation , this is the output of browser logs :
D:/a/brave-portable/brave-portable/main.go:109 > Cannot import registry key error="reg file C:\\portapps\\brave-portable\\reg\\Brave-Browser-Development.reg not found" Fri, 20 May 2022 14:10:52 CEST INF ..\..\..\runneradmin\go\pkg\mod\github.com\portapps\portapps\[email protected]\portapps.go:168 > Process: C:\portapps\brave-portable\app\brave.exe Fri, 20 May 2022 14:10:52 CEST INF ..\..\..\runneradmin\go\pkg\mod\github.com\portapps\portapps\[email protected]\portapps.go:169 > Args (config file): Fri, 20 May 2022 14:10:52 CEST INF ..\..\..\runneradmin\go\pkg\mod\github.com\portapps\portapps\[email protected]\portapps.go:170 > Args (cmd line): --disable-background-networking --enable-features=NetworkService,NetworkServiceInProcess --disable-background-timer-throttling --disable-backgrounding-occluded-windows --disable-breakpad --disable-client-side-phishing-detection --disable-component-extensions-with-background-pages --disable-default-apps --disable-dev-shm-usage --disable-features=TranslateUI --disable-hang-monitor --disable-ipc-flooding-protection --disable-popup-blocking --disable-prompt-on-repost --disable-renderer-backgrounding --disable-sync --force-color-profile=srgb --metrics-recording-only --no-first-run --password-store=basic --use-mock-keychain about:blank --disable-notifications --disable-blink-features=AutomationControlled --remote-debugging-port=0 --user-data-dir=C:\Users\pc\AppData\Local\Temp\ov5gvgs3.hsi Fri, 20 May 2022 14:10:52 CEST INF ..\..\..\runneradmin\go\pkg\mod\github.com\portapps\portapps\[email protected]\portapps.go:171 > Args (hardcoded): --user-data-dir=C:\portapps\brave-portable\data --disable-brave-update --no-default-browser-check --disable-logging --disable-breakpad --disable-machine-id --disable-encryption-win Fri, 20 May 2022 14:10:52 CEST INF ..\..\..\runneradmin\go\pkg\mod\github.com\portapps\portapps\[email protected]\portapps.go:172 > Working dir: C:\portapps\brave-portable\app Fri, 20 May 2022 14:10:52 CEST INF ..\..\..\runneradmin\go\pkg\mod\github.com\portapps\portapps\[email protected]\portapps.go:173 > App path: C:\portapps\brave-portable\app Fri, 20 May 2022 14:10:52 CEST INF ..\..\..\runneradmin\go\pkg\mod\github.com\portapps\portapps\[email protected]\portapps.go:174 > Data path: C:\portapps\brave-portable\data Fri, 20 May 2022 14:10:52 CEST INF ..\..\..\runneradmin\go\pkg\mod\github.com\portapps\portapps\[email protected]\portapps.go:175 > Previous path: C:\portapps\brave-portable Fri, 20 May 2022 14:10:52 CEST INF ..\..\..\runneradmin\go\pkg\mod\github.com\portapps\portapps\[email protected]\portapps.go:181 > Launching Brave Fri, 20 May 2022 14:10:52 CEST INF ..\..\..\runneradmin\go\pkg\mod\github.com\portapps\portapps\[email protected]\portapps.go:191 > Exec C:\portapps\brave-portable\app\brave.exe --disable-background-networking --enable-features=NetworkService,NetworkServiceInProcess --disable-background-timer-throttling --disable-backgrounding-occluded-windows --disable-breakpad --disable-client-side-phishing-detection --disable-component-extensions-with-background-pages --disable-default-apps --disable-dev-shm-usage --disable-features=TranslateUI --disable-hang-monitor --disable-ipc-flooding-protection --disable-popup-blocking --disable-prompt-on-repost --disable-renderer-backgrounding --disable-sync --force-color-profile=srgb --metrics-recording-only --no-first-run --password-store=basic --use-mock-keychain about:blank --disable-notifications --disable-blink-features=AutomationControlled --remote-debugging-port=0 --user-data-dir=C:\Users\pc\AppData\Local\Temp\ov5gvgs3.hsi --user-data-dir=C:\portapps\brave-portable\data --disable-brave-update --no-default-browser-check --disable-logging --disable-breakpad --disable-machine-id --disable-encryption-win
More details :
Platform: OB2 (Openbullet 2)
OS : Windows 10
Tested On : 97.XX and 101.XX
App Log : PuppeteerSharp.ProcessException: Timed out after 30000 ms while trying to connect to Base!
N.B : Work Fine On Selenium
A:
"TimeoutError: Timed out after 30000 ms while trying to connect to the browser! Only Chrome at revision r1056772 is guaranteed to work." might be an explanation, as of 12/2022. Tried on Chrome Portable and got this error, very similar to yours.
|
Why Puppeteer not working in Brave™ portable?
|
All versions Works fine But , in the Brave™ portable from portapps (Edited Version) ,not working i use puppeteerSharp with Plugin Extrasharp, so when i try to open the browser , the browser open but without navigation , this is the output of browser logs :
D:/a/brave-portable/brave-portable/main.go:109 > Cannot import registry key error="reg file C:\\portapps\\brave-portable\\reg\\Brave-Browser-Development.reg not found" Fri, 20 May 2022 14:10:52 CEST INF ..\..\..\runneradmin\go\pkg\mod\github.com\portapps\portapps\[email protected]\portapps.go:168 > Process: C:\portapps\brave-portable\app\brave.exe Fri, 20 May 2022 14:10:52 CEST INF ..\..\..\runneradmin\go\pkg\mod\github.com\portapps\portapps\[email protected]\portapps.go:169 > Args (config file): Fri, 20 May 2022 14:10:52 CEST INF ..\..\..\runneradmin\go\pkg\mod\github.com\portapps\portapps\[email protected]\portapps.go:170 > Args (cmd line): --disable-background-networking --enable-features=NetworkService,NetworkServiceInProcess --disable-background-timer-throttling --disable-backgrounding-occluded-windows --disable-breakpad --disable-client-side-phishing-detection --disable-component-extensions-with-background-pages --disable-default-apps --disable-dev-shm-usage --disable-features=TranslateUI --disable-hang-monitor --disable-ipc-flooding-protection --disable-popup-blocking --disable-prompt-on-repost --disable-renderer-backgrounding --disable-sync --force-color-profile=srgb --metrics-recording-only --no-first-run --password-store=basic --use-mock-keychain about:blank --disable-notifications --disable-blink-features=AutomationControlled --remote-debugging-port=0 --user-data-dir=C:\Users\pc\AppData\Local\Temp\ov5gvgs3.hsi Fri, 20 May 2022 14:10:52 CEST INF ..\..\..\runneradmin\go\pkg\mod\github.com\portapps\portapps\[email protected]\portapps.go:171 > Args (hardcoded): --user-data-dir=C:\portapps\brave-portable\data --disable-brave-update --no-default-browser-check --disable-logging --disable-breakpad --disable-machine-id --disable-encryption-win Fri, 20 May 2022 14:10:52 CEST INF ..\..\..\runneradmin\go\pkg\mod\github.com\portapps\portapps\[email protected]\portapps.go:172 > Working dir: C:\portapps\brave-portable\app Fri, 20 May 2022 14:10:52 CEST INF ..\..\..\runneradmin\go\pkg\mod\github.com\portapps\portapps\[email protected]\portapps.go:173 > App path: C:\portapps\brave-portable\app Fri, 20 May 2022 14:10:52 CEST INF ..\..\..\runneradmin\go\pkg\mod\github.com\portapps\portapps\[email protected]\portapps.go:174 > Data path: C:\portapps\brave-portable\data Fri, 20 May 2022 14:10:52 CEST INF ..\..\..\runneradmin\go\pkg\mod\github.com\portapps\portapps\[email protected]\portapps.go:175 > Previous path: C:\portapps\brave-portable Fri, 20 May 2022 14:10:52 CEST INF ..\..\..\runneradmin\go\pkg\mod\github.com\portapps\portapps\[email protected]\portapps.go:181 > Launching Brave Fri, 20 May 2022 14:10:52 CEST INF ..\..\..\runneradmin\go\pkg\mod\github.com\portapps\portapps\[email protected]\portapps.go:191 > Exec C:\portapps\brave-portable\app\brave.exe --disable-background-networking --enable-features=NetworkService,NetworkServiceInProcess --disable-background-timer-throttling --disable-backgrounding-occluded-windows --disable-breakpad --disable-client-side-phishing-detection --disable-component-extensions-with-background-pages --disable-default-apps --disable-dev-shm-usage --disable-features=TranslateUI --disable-hang-monitor --disable-ipc-flooding-protection --disable-popup-blocking --disable-prompt-on-repost --disable-renderer-backgrounding --disable-sync --force-color-profile=srgb --metrics-recording-only --no-first-run --password-store=basic --use-mock-keychain about:blank --disable-notifications --disable-blink-features=AutomationControlled --remote-debugging-port=0 --user-data-dir=C:\Users\pc\AppData\Local\Temp\ov5gvgs3.hsi --user-data-dir=C:\portapps\brave-portable\data --disable-brave-update --no-default-browser-check --disable-logging --disable-breakpad --disable-machine-id --disable-encryption-win
More details :
Platform: OB2 (Openbullet 2)
OS : Windows 10
Tested On : 97.XX and 101.XX
App Log : PuppeteerSharp.ProcessException: Timed out after 30000 ms while trying to connect to Base!
N.B : Work Fine On Selenium
|
[
"\"TimeoutError: Timed out after 30000 ms while trying to connect to the browser! Only Chrome at revision r1056772 is guaranteed to work.\" might be an explanation, as of 12/2022. Tried on Chrome Portable and got this error, very similar to yours.\n"
] |
[
0
] |
[] |
[] |
[
"brave",
"brave_browser",
"c#",
"puppeteer",
"puppeteer_sharp"
] |
stackoverflow_0072475232_brave_brave_browser_c#_puppeteer_puppeteer_sharp.txt
|
Q:
In C#, how do I extract the two UInt64 values that make up a UInt128?
Suppose I have a UInt128 like this
UInt64 upperA = 7, lowerA = 8;
UInt128 foo = new(upperA, lowerA);
++foo;
And now I want to extract the two UInt64s from the updated foo.
If they were properties, I could do this
UInt64 upperB = foo.Upper, lowerB = foo.Lower;
But they aren't, so how do I get them?
A:
By converting to UInt64 you can get the lower bits already; to get the upper one you can apply a bit shift first:
var lower = (UInt64)foo;
var upper = (UInt64)(foo >> 64);
|
In C#, how do I extract the two UInt64 values that make up a UInt128?
|
Suppose I have a UInt128 like this
UInt64 upperA = 7, lowerA = 8;
UInt128 foo = new(upperA, lowerA);
++foo;
And now I want to extract the two UInt64s from the updated foo.
If they were properties, I could do this
UInt64 upperB = foo.Upper, lowerB = foo.Lower;
But they aren't, so how do I get them?
|
[
"By converting to UInt64 you can get the lower bits already; to get the upper one you can apply a bit shift first:\nvar lower = (UInt64)foo;\nvar upper = (UInt64)(foo >> 64);\n\n"
] |
[
3
] |
[] |
[] |
[
"c#",
"int128",
"integer"
] |
stackoverflow_0074669686_c#_int128_integer.txt
|
Q:
how do I overwrite text I've already written to the console?
I am trying to get this to
Read the text from screen #Working
Output the text #Working
Delete Output #Not working
Replace with Output every 5 second. #Not working as depended on prior
Can someone help?
I am trying to get this algo to read the screen every 5 seconds, but it seems to only do it once.
Any suggestions?
import time
import cv2
import mss
import numpy
import pytesseract
import matplotlib.pyplot as plt
import io
import pandas as pd
from PIL import Image
pytesseract.pytesseract.tesseract_cmd = 'C:\\Program Files\\Tesseract-OCR\\tesseract.exe'
with mss.mss() as mss_instance:
mon = mss_instance.monitors[0]
screenshot = mss_instance.grab(mon)
with mss.mss() as sct:
while True:
im = numpy.asarray(sct.grab(mon))
plt.imshow(cv2.cvtColor(im, cv2.COLOR_BGR2RGB))
text = pytesseract.image_to_string(im)
plt.show()
print(text)
time.sleep(5) # One screenshot per 5 seconds
if cv2.waitKey(25) & 0xFF == ord("q"):
cv2.destroyAllWindows()
continue
A:
So, your question really is "how to I overwrite text I've already written to the console?" There are two ways.
If there is only one line of text, just write a carriage return at the end instead of a newline. For example:
print(text, end='\r')
If there are multiple lines of text, you can clear the screen before writing:
os.system('cls')
print(text)
Note that "cls" is specifically for Windows, which is what you are using. If you intend this to be used on other operating systems, you would need something like:
if sys.platform == 'win32':
os.system('cls')
else:
os.system('clear')
|
how do I overwrite text I've already written to the console?
|
I am trying to get this to
Read the text from screen #Working
Output the text #Working
Delete Output #Not working
Replace with Output every 5 second. #Not working as depended on prior
Can someone help?
I am trying to get this algo to read the screen every 5 seconds, but it seems to only do it once.
Any suggestions?
import time
import cv2
import mss
import numpy
import pytesseract
import matplotlib.pyplot as plt
import io
import pandas as pd
from PIL import Image
pytesseract.pytesseract.tesseract_cmd = 'C:\\Program Files\\Tesseract-OCR\\tesseract.exe'
with mss.mss() as mss_instance:
mon = mss_instance.monitors[0]
screenshot = mss_instance.grab(mon)
with mss.mss() as sct:
while True:
im = numpy.asarray(sct.grab(mon))
plt.imshow(cv2.cvtColor(im, cv2.COLOR_BGR2RGB))
text = pytesseract.image_to_string(im)
plt.show()
print(text)
time.sleep(5) # One screenshot per 5 seconds
if cv2.waitKey(25) & 0xFF == ord("q"):
cv2.destroyAllWindows()
continue
|
[
"So, your question really is \"how to I overwrite text I've already written to the console?\" There are two ways.\nIf there is only one line of text, just write a carriage return at the end instead of a newline. For example:\n print(text, end='\\r')\n\nIf there are multiple lines of text, you can clear the screen before writing:\n os.system('cls')\n print(text)\n\nNote that \"cls\" is specifically for Windows, which is what you are using. If you intend this to be used on other operating systems, you would need something like:\n if sys.platform == 'win32':\n os.system('cls')\n else:\n os.system('clear')\n\n"
] |
[
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0074646615_python.txt
|
Q:
Snake Algorithm (active contour) in python
Find contour on the right side of the chest image as indicated with red circle and by using Python and scikit-image package for the image below
this is the image i have to process
to make it like this result:
the result must be like this
I don't know a lot of python thats why I need to know what I have to do
A:
To find the contour on the right side of the chest image, you can use the find_contours function from the scikit-image package. This function takes an image as input and returns a list of all the contours in the image.
Here is an example of how you can use this function to find the contour on the right side of the chest image:
from skimage import io
from skimage.color import rgb2gray
from skimage.filters import threshold_otsu
from skimage.measure import find_contours
# Load the image
image = io.imread('chest_image.png')
# Convert the image to grayscale
gray_image = rgb2gray(image)
# Apply thresholding to the image using Otsu's method
threshold = threshold_otsu(gray_image)
binary_image = gray_image > threshold
# Find the contours in the binary image
contours = find_contours(binary_image, 0.8)
# Select the contour on the right side of the chest
right_side_contour = contours[0]
# Plot the contour on the image
plt.imshow(image, cmap='gray')
plt.plot(right_side_contour[:, 1], right_side_contour[:, 0], linewidth=2)
plt.show()
This code will first load the chest image and convert it to grayscale. Then it will apply thresholding to the image using Otsu's method, which will create a binary image with the chest region being white and the background being black. Finally, it will use the find_contours function to find the contours in the binary image, select the contour on the right side of the chest, and plot it on the image.
You can further refine this code to select the contour on the right side of the chest more accurately, depending on the specific details of your image. For example, you can use the coordinates of the red circle in the image to determine which contour is the one on the right side of the chest.
|
Snake Algorithm (active contour) in python
|
Find contour on the right side of the chest image as indicated with red circle and by using Python and scikit-image package for the image below
this is the image i have to process
to make it like this result:
the result must be like this
I don't know a lot of python thats why I need to know what I have to do
|
[
"To find the contour on the right side of the chest image, you can use the find_contours function from the scikit-image package. This function takes an image as input and returns a list of all the contours in the image.\nHere is an example of how you can use this function to find the contour on the right side of the chest image:\nfrom skimage import io\nfrom skimage.color import rgb2gray\nfrom skimage.filters import threshold_otsu\nfrom skimage.measure import find_contours\n\n# Load the image\nimage = io.imread('chest_image.png')\n\n# Convert the image to grayscale\ngray_image = rgb2gray(image)\n\n# Apply thresholding to the image using Otsu's method\nthreshold = threshold_otsu(gray_image)\nbinary_image = gray_image > threshold\n\n# Find the contours in the binary image\ncontours = find_contours(binary_image, 0.8)\n\n# Select the contour on the right side of the chest\nright_side_contour = contours[0]\n\n# Plot the contour on the image\nplt.imshow(image, cmap='gray')\nplt.plot(right_side_contour[:, 1], right_side_contour[:, 0], linewidth=2)\nplt.show()\n\nThis code will first load the chest image and convert it to grayscale. Then it will apply thresholding to the image using Otsu's method, which will create a binary image with the chest region being white and the background being black. Finally, it will use the find_contours function to find the contours in the binary image, select the contour on the right side of the chest, and plot it on the image.\nYou can further refine this code to select the contour on the right side of the chest more accurately, depending on the specific details of your image. For example, you can use the coordinates of the red circle in the image to determine which contour is the one on the right side of the chest.\n"
] |
[
1
] |
[] |
[] |
[
"computer_vision",
"image_processing",
"python"
] |
stackoverflow_0074669771_computer_vision_image_processing_python.txt
|
Q:
Zend Framework 2 Doctrine 2 one-to-many checkbox hydration
I have a ManyToMany that I broke into OneToMany and ManyToOne relationship. I want to build a form that has checkboxes instead of collection, and I am using the 'DoctrineObject' hydrator, but it does not work and I don't know what is going wrong.
I removed from my code below all of the other not related fields.
Role Entity:
/**
* @orm\Entity
* @orm\Table(name="roles")
*/
class RolesEntity extends HemisEntity {
/**
* @orm\Id
* @orm\Column(type="integer");
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
protected $id;
/**
* @orm\Column(name="role_code",type="string")
*/
protected $roleCode;
/**
* @orm\OneToMany(targetEntity="RolesPermissionsEntity", mappedBy="role", cascade={"persist"})
*/
protected $rolePermissions;
public function __construct()
{
$this->rolePermissions = new ArrayCollection();
}
public function setRolePermissions($rolePermissions)
{
$this->rolePermissions = $rolePermissions;
return $this;
}
public function addRolePermissions(Collection $rolePermissions)
{
foreach ($rolePermissions as $rolePermission) {
$rolePermission->setRole($this);
$this->rolePermissions->add($rolePermission);
}
}
public function removeRolePermissions(Collection $rolePermissions)
{
foreach ($rolePermissions as $rolePermission) {
$rolePermission->setRole(null);
$this->rolePermissions->removeElement($rolePermission);
}
}
public function getRolePermissions()
{
return $this->rolePermissions;
}
}
The ManyToMany table entity (it has more fields and so I broke it):
/**
* @orm\Entity
* @orm\Table(name="roles_permissions")
*/
class RolesPermissionsEntity extends HemisEntity {
/**
* @orm\Id
* @orm\Column(type="integer");
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
protected $id;
/**
* @orm\ManyToOne(targetEntity="RolesEntity", inversedBy="rolePermissions")
* @orm\JoinColumn(name="role_id", referencedColumnName="id")
**/
protected $role;
/**
* @orm\ManyToOne(targetEntity="PermissionsEntity", inversedBy="permissionRoles")
* @orm\JoinColumn(name="permission_id", referencedColumnName="id")
**/
protected $permission;
public function setRole($role)
{
$this->role = $role;
return $this;
}
public function getRole()
{
return $this->role;
}
public function setPermission($permission)
{
$this->permission = $permission;
return $this;
}
public function getPermission()
{
return $this->permission;
}
}
My form look like this:
class RoleForm extends Form implements InputFilterProviderInterface
{
public function __construct(ObjectManager $objectManager)
{
parent::__construct('role');
$this->setHydrator(new DoctrineHydrator($objectManager))
->setObject(new RolesEntity());
$this->add(array(
'type' => 'Zend\Form\Element\Hidden',
'name' => 'id'
));
$this->add(array(
'type' => 'Zend\Form\Element\Text',
'name' => 'roleCode',
'options' => array(
'label' => 'Role Code'
),
));
$this->add(array(
'name' => 'rolePermissions',
'type' => 'DoctrineModule\Form\Element\ObjectMultiCheckbox',
'options' => array(
'label' => 'Permissions',
'object_manager' => $objectManager,
'target_class' => 'Hemis\Fnd\PermissionsEntity',
'property' => 'permissionDesc'
),
));
$this->add(array(
'name' => 'submit',
'type' => 'Submit',
'attributes' => array(
'value' => 'Submit',
),
));
}
public function getInputFilterSpecification()
{
return array(
'roleCode' => array(
'required' => false
),
'rolePermissions' => array(
'required' => true
)
);
}
}
The problem is that when I dump the $role it does not contains any rolePermissions and even that they are passed from the form they are just not hydrated into the object. I hope that my question is clear.
Any idea about what is wrong with my code or there is a better way to do that using checkboxes?
A:
To create a form with checkboxes for a OneToMany relationship in Doctrine, you can use the ObjectMultiCheckbox element provided by the DoctrineModule. The ObjectMultiCheckbox element allows you to create a group of checkboxes, where each checkbox corresponds to a different object in the relationship.
Here is an example of how you could use the ObjectMultiCheckbox element in your form:
$this->add(array(
'name' => 'rolePermissions',
'type' => 'DoctrineModule\Form\Element\ObjectMultiCheckbox',
'options' => array(
'label' => 'Role Permissions',
'object_manager' => $objectManager,
'target_class' => 'RolesPermissionsEntity',
'property' => 'permission'
),
));
In the example above, the ObjectMultiCheckbox element will create a group of checkboxes, where each checkbox corresponds to a different RolesPermissionsEntity object in the rolePermissions relationship. The property option specifies which property of the RolesPermissionsEntity objects should be displayed as the label for each checkbox.
When the form is submitted, the selected RolesPermissionsEntity objects will be added to the rolePermissions property of the RolesEntity object. You can use the addRolePermissions and removeRolePermissions methods on the RolesEntity class to manage the relationship.
It is important to note that you must use the DoctrineObject hydrator for this to work properly. This hydrator will handle the conversion between the selected checkboxes and the corresponding RolesPermissionsEntity objects. You can set the hydrator for the form using the setHydrator method, as shown below:
$this->setHydrator(new DoctrineHydrator($objectManager))
->setObject(new RolesEntity());
|
Zend Framework 2 Doctrine 2 one-to-many checkbox hydration
|
I have a ManyToMany that I broke into OneToMany and ManyToOne relationship. I want to build a form that has checkboxes instead of collection, and I am using the 'DoctrineObject' hydrator, but it does not work and I don't know what is going wrong.
I removed from my code below all of the other not related fields.
Role Entity:
/**
* @orm\Entity
* @orm\Table(name="roles")
*/
class RolesEntity extends HemisEntity {
/**
* @orm\Id
* @orm\Column(type="integer");
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
protected $id;
/**
* @orm\Column(name="role_code",type="string")
*/
protected $roleCode;
/**
* @orm\OneToMany(targetEntity="RolesPermissionsEntity", mappedBy="role", cascade={"persist"})
*/
protected $rolePermissions;
public function __construct()
{
$this->rolePermissions = new ArrayCollection();
}
public function setRolePermissions($rolePermissions)
{
$this->rolePermissions = $rolePermissions;
return $this;
}
public function addRolePermissions(Collection $rolePermissions)
{
foreach ($rolePermissions as $rolePermission) {
$rolePermission->setRole($this);
$this->rolePermissions->add($rolePermission);
}
}
public function removeRolePermissions(Collection $rolePermissions)
{
foreach ($rolePermissions as $rolePermission) {
$rolePermission->setRole(null);
$this->rolePermissions->removeElement($rolePermission);
}
}
public function getRolePermissions()
{
return $this->rolePermissions;
}
}
The ManyToMany table entity (it has more fields and so I broke it):
/**
* @orm\Entity
* @orm\Table(name="roles_permissions")
*/
class RolesPermissionsEntity extends HemisEntity {
/**
* @orm\Id
* @orm\Column(type="integer");
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
protected $id;
/**
* @orm\ManyToOne(targetEntity="RolesEntity", inversedBy="rolePermissions")
* @orm\JoinColumn(name="role_id", referencedColumnName="id")
**/
protected $role;
/**
* @orm\ManyToOne(targetEntity="PermissionsEntity", inversedBy="permissionRoles")
* @orm\JoinColumn(name="permission_id", referencedColumnName="id")
**/
protected $permission;
public function setRole($role)
{
$this->role = $role;
return $this;
}
public function getRole()
{
return $this->role;
}
public function setPermission($permission)
{
$this->permission = $permission;
return $this;
}
public function getPermission()
{
return $this->permission;
}
}
My form look like this:
class RoleForm extends Form implements InputFilterProviderInterface
{
public function __construct(ObjectManager $objectManager)
{
parent::__construct('role');
$this->setHydrator(new DoctrineHydrator($objectManager))
->setObject(new RolesEntity());
$this->add(array(
'type' => 'Zend\Form\Element\Hidden',
'name' => 'id'
));
$this->add(array(
'type' => 'Zend\Form\Element\Text',
'name' => 'roleCode',
'options' => array(
'label' => 'Role Code'
),
));
$this->add(array(
'name' => 'rolePermissions',
'type' => 'DoctrineModule\Form\Element\ObjectMultiCheckbox',
'options' => array(
'label' => 'Permissions',
'object_manager' => $objectManager,
'target_class' => 'Hemis\Fnd\PermissionsEntity',
'property' => 'permissionDesc'
),
));
$this->add(array(
'name' => 'submit',
'type' => 'Submit',
'attributes' => array(
'value' => 'Submit',
),
));
}
public function getInputFilterSpecification()
{
return array(
'roleCode' => array(
'required' => false
),
'rolePermissions' => array(
'required' => true
)
);
}
}
The problem is that when I dump the $role it does not contains any rolePermissions and even that they are passed from the form they are just not hydrated into the object. I hope that my question is clear.
Any idea about what is wrong with my code or there is a better way to do that using checkboxes?
|
[
"To create a form with checkboxes for a OneToMany relationship in Doctrine, you can use the ObjectMultiCheckbox element provided by the DoctrineModule. The ObjectMultiCheckbox element allows you to create a group of checkboxes, where each checkbox corresponds to a different object in the relationship.\nHere is an example of how you could use the ObjectMultiCheckbox element in your form:\n$this->add(array(\n 'name' => 'rolePermissions',\n 'type' => 'DoctrineModule\\Form\\Element\\ObjectMultiCheckbox',\n 'options' => array(\n 'label' => 'Role Permissions',\n 'object_manager' => $objectManager,\n 'target_class' => 'RolesPermissionsEntity',\n 'property' => 'permission'\n ),\n));\n\nIn the example above, the ObjectMultiCheckbox element will create a group of checkboxes, where each checkbox corresponds to a different RolesPermissionsEntity object in the rolePermissions relationship. The property option specifies which property of the RolesPermissionsEntity objects should be displayed as the label for each checkbox.\nWhen the form is submitted, the selected RolesPermissionsEntity objects will be added to the rolePermissions property of the RolesEntity object. You can use the addRolePermissions and removeRolePermissions methods on the RolesEntity class to manage the relationship.\nIt is important to note that you must use the DoctrineObject hydrator for this to work properly. This hydrator will handle the conversion between the selected checkboxes and the corresponding RolesPermissionsEntity objects. You can set the hydrator for the form using the setHydrator method, as shown below:\n$this->setHydrator(new DoctrineHydrator($objectManager))\n ->setObject(new RolesEntity());\n\n"
] |
[
0
] |
[] |
[] |
[
"doctrine_orm",
"zend_form2",
"zend_framework2"
] |
stackoverflow_0017722415_doctrine_orm_zend_form2_zend_framework2.txt
|
Q:
How to find a random number in python
I have a random number and I want to create a bot that find it automatically but I'm stuck. Can you help me pls
I have these two variables:
a = random.randint(0,50)
b = 50
I want to make the bot find a using b.
I tried this but it's too long to make:
if b != a:
b = statistics.mean(0,b)
if b > a:
b = statistics.mean(0,b)
elif b < a:
min = b
b = statistics.mean(min,50)
elif b == a:
"GG"
A:
import random
a = random.randint(0,50)
b = 50
i = b//2
while b!=a:
if b<a:
b+=i
elif b>a:
b-=i
if i>1:
i//=2
print(a,b)
|
How to find a random number in python
|
I have a random number and I want to create a bot that find it automatically but I'm stuck. Can you help me pls
I have these two variables:
a = random.randint(0,50)
b = 50
I want to make the bot find a using b.
I tried this but it's too long to make:
if b != a:
b = statistics.mean(0,b)
if b > a:
b = statistics.mean(0,b)
elif b < a:
min = b
b = statistics.mean(min,50)
elif b == a:
"GG"
|
[
"import random\na = random.randint(0,50)\nb = 50\ni = b//2\nwhile b!=a:\n if b<a:\n b+=i\n elif b>a:\n b-=i \n if i>1:\n i//=2\nprint(a,b)\n\n"
] |
[
2
] |
[] |
[] |
[
"bots",
"python",
"random"
] |
stackoverflow_0074669751_bots_python_random.txt
|
Q:
Add users to an existing group
I am trying to make an tracker app in witch I an user can create a group and when clicked on "show on map" it would show all of members position. I have made group info page in witch there is a Add members button. When clicked it takes the user to a new page. In that new page he searches for an different user witch he wants to add. When clicked on search icon under the TextFormField there is an ListTile. When tapped on that ListTile searched user should be added to that group and the searcher should be redirected back to group info page.
I am stuck at the part in which I try to add users to an existing group but I get an error:
Bad state: field does not exist within the DocumentSnapshotPlatform.
Here is the code for adding different users to a group
import 'package:cloud_firestore/cloud_firestore.dart';
class DatabaseService {
final String? uid;
DatabaseService({this.uid});
// reference for collection
final CollectionReference userCollection =
FirebaseFirestore.instance.collection("users");
final CollectionReference groupCollection =
FirebaseFirestore.instance.collection("groups");
// saving the user data
Future savingUserData(String name, String email) async {
return await userCollection.doc(uid).set({
"name": name,
"email": email,
"friends": [],
"groups": [],
"profilePicture": "",
"uid": uid,
"latitude": "",
"longitude": "",
});
}
//getting user data
Future gettingUserData(String email) async {
QuerySnapshot snapshot =
await userCollection.where("email", isEqualTo: email).get();
return snapshot;
}
// create a group
Future createGroup(String name, String groupName, String id) async {
DocumentReference groupDocumentReference = await groupCollection.add({
"groupName": groupName,
"groupIcon": "",
"groupCreator": "",
"admins": [],
"members": [],
"groupId": "",
});
await groupDocumentReference.update({
"admins": FieldValue.arrayUnion(["${uid}_$name"]),
"groupCreator": FieldValue.arrayUnion(["${id}_$name"]),
"groupId": groupDocumentReference.id
});
DocumentReference userDocumentReference = userCollection.doc(uid);
return await userDocumentReference.update({
"groups":
FieldValue.arrayUnion(["${groupDocumentReference.id}_$groupName"])
});
}
getUserGroups() async {
return userCollection.doc(uid).snapshots();
}
//search
searchByEmail(String userEmail) async {
return userCollection.where('email', isEqualTo: userEmail).get();
}
//get group admins
getGroupAdmins(String groupId) async {
return groupCollection.doc(groupId).snapshots();
}
getGroupMembers(String groupId) async {
return groupCollection.doc(groupId).snapshots();
}
Future addMember(
String groupId,
String groupName,
String memeberId,
memberName,
) async {
DocumentReference userDocumentReference = userCollection.doc(memeberId);
DocumentReference groupDocumentReference = groupCollection.doc(groupId);
DocumentSnapshot userdocumentSnapshot = await userDocumentReference.get();
List<dynamic> groups = await userdocumentSnapshot['groups'];
DocumentSnapshot groupDocumentSnapshot = await groupDocumentReference.get();
List<dynamic> members = await groupDocumentSnapshot['members'];
if (groups.contains("${groupId}_$groupName") &
members.contains("${memeberId}_$memberName")) {
return null;
} else {
await groupCollection.doc(groupId).update({
"members": FieldValue.arrayUnion(["${memeberId}_$memberName"])
});
}
}
}
Here is the AddMemberPage
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:tracker_app/page_changer/page_changer.dart';
import 'package:tracker_app/pages/app_pages/info_page.dart';
import 'package:tracker_app/services/database_service.dart';
import '../../theme/theme.dart';
class AddMembers extends StatefulWidget {
final String groupId;
final String groupName;
const AddMembers({super.key, required this.groupId, required this.groupName});
@override
State<AddMembers> createState() => _AddMembersState();
}
class _AddMembersState extends State<AddMembers> {
QuerySnapshot? searchSnapshot;
TextEditingController emailController = TextEditingController();
String email = "";
String friendId = "";
String friendName = "";
bool isLoading = false;
bool hasUserSearched = false;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(
"Add members",
style: TextStyle(fontSize: 30, fontWeight: FontWeight.w500),
),
centerTitle: true,
),
body: SingleChildScrollView(
child: Column(children: [
const Divider(
height: 5,
indent: 5,
endIndent: 5,
thickness: 1.5,
),
Container(
height: 10,
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 10),
child: TextFormField(
controller: emailController,
cursorColor: AppColors.secondary,
decoration: InputDecoration(
errorBorder: OutlineInputBorder(
borderSide: const BorderSide(color: Colors.red),
borderRadius: BorderRadius.circular(50)),
focusedBorder: OutlineInputBorder(
borderSide: const BorderSide(
color: AppColors.secondary,
),
borderRadius: BorderRadius.circular(50)),
enabledBorder: OutlineInputBorder(
borderSide: const BorderSide(
color: AppColors.secondary,
),
borderRadius: BorderRadius.circular(50)),
labelText: "email",
labelStyle: const TextStyle(
color: AppColors.secondary,
fontWeight: FontWeight.w500,
),
suffixIcon: InkWell(
splashColor: AppColors.secondary,
borderRadius: BorderRadius.circular(360),
onTap: () {
initiateSearchMethod();
},
child: const Icon(
Icons.search,
color: AppColors.secondary,
),
),
hintText: "Enter persons email"),
onChanged: (value) {
setState(() {
email = value;
});
},
),
),
userList(),
]),
),
);
}
initiateSearchMethod() async {
if (emailController != null) {
setState(() {
isLoading = true;
});
await DatabaseService(uid: FirebaseAuth.instance.currentUser!.uid)
.searchByEmail(email)
.then((snapshot) {
setState(() {
searchSnapshot = snapshot;
isLoading = false;
hasUserSearched = true;
friendId = snapshot!.docs[0]['id'];
friendName = snapshot!.docs[0]['name'];
});
});
}
}
userList() {
return hasUserSearched
? ListView.builder(
shrinkWrap: true,
itemCount: searchSnapshot!.docs.length,
itemBuilder: (context, index) {
return friendSearchTile();
},
)
: Container();
}
friendSearchTile() {
// check if user is friend
//GdzhH8YGCsTMhmPf6aAeXvb09GH3
return ListTile(
leading: CircleAvatar(
radius: 25,
backgroundColor: AppColors.secondary,
child: Text(
searchSnapshot!.docs[0]['name'].substring(0, 1).toUpperCase(),
style: const TextStyle(color: Colors.white)),
),
title: Text(friendName),
subtitle: Text(searchSnapshot!.docs[0]['email']),
trailing: InkWell(
borderRadius: BorderRadius.circular(360),
onTap: () {
DatabaseService(uid: FirebaseAuth.instance.currentUser!.uid)
.addMember(
widget.groupId,
widget.groupName,
searchSnapshot!.docs[0]['id'],
searchSnapshot!.docs[0]['name']);
nextScreenReplace(context,
InfoPage(groupName: widget.groupName, groupId: widget.groupId));
print("friendId: $friendId");
},
splashColor: AppColors.secondary,
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 10),
child: const Icon(
Icons.add,
),
),
),
);
}
}
A:
After more searching I found the solution. In AddMembers page when clicked to add an user required groupId, groupName, friendId(that users id), friendName(that friends name). The problem was with firendId. The line searchSnapshot!.docs[0]['id] was wrong. In the firebase I marked the users id as 'uid'.After changing that it started working.
The line:
DatabaseService(uid: FirebaseAuth.instance.currentUser!.uid)
.addMember(
widget.groupId,
widget.groupName,
searchSnapshot!.docs[0]['id'],
searchSnapshot!.docs[0]['name']);
I changed to:
DatabaseService(uid: FirebaseAuth.instance.currentUser!.uid)
.addMember(
widget.groupId,
widget.groupName,
searchSnapshot!.docs[0]['uid'],
searchSnapshot!.docs[0]['name']);
A:
It looks like the issue is with how you are getting the groups and members arrays from the DocumentSnapshot objects for the user and group documents. In your addMember() function, you are using the await keyword to get the values of the groups and members fields from the DocumentSnapshot objects, but these fields are not async, so using await with them will not work.
To fix this, you can simply remove the await keywords when getting the values of the groups and members fields, like this:
List<dynamic> groups = userdocumentSnapshot['groups'];
List<dynamic> members = groupDocumentSnapshot['members'];
You can then use the contains() method on the groups and members lists to check if they already contain the new member and group, and add the new member to the group if they do not already exist in the lists.
Here is how your addMember() function should look like after making these changes:
Future addMember(
String groupId,
String groupName,
String memeberId,
memberName,
) async {
DocumentReference userDocumentReference = userCollection.doc(memeberId);
DocumentReference groupDocumentReference = groupCollection.doc(groupId);
DocumentSnapshot userdocumentSnapshot = await userDocumentReference.get();
List<dynamic> groups = userdocumentSnapshot['groups'];
DocumentSnapshot groupDocumentSnapshot = await groupDocumentReference.get();
List<dynamic> members = groupDocumentSnapshot['members'];
if (!groups.contains("${groupId}_$groupName") ||
!members.contains("${memeberId}_$memberName")) {
await groupCollection.doc(groupId).update({
"members": FieldValue.arrayUnion(["${memeberId}_$memberName"])
});
}
}
I hope this helps!
|
Add users to an existing group
|
I am trying to make an tracker app in witch I an user can create a group and when clicked on "show on map" it would show all of members position. I have made group info page in witch there is a Add members button. When clicked it takes the user to a new page. In that new page he searches for an different user witch he wants to add. When clicked on search icon under the TextFormField there is an ListTile. When tapped on that ListTile searched user should be added to that group and the searcher should be redirected back to group info page.
I am stuck at the part in which I try to add users to an existing group but I get an error:
Bad state: field does not exist within the DocumentSnapshotPlatform.
Here is the code for adding different users to a group
import 'package:cloud_firestore/cloud_firestore.dart';
class DatabaseService {
final String? uid;
DatabaseService({this.uid});
// reference for collection
final CollectionReference userCollection =
FirebaseFirestore.instance.collection("users");
final CollectionReference groupCollection =
FirebaseFirestore.instance.collection("groups");
// saving the user data
Future savingUserData(String name, String email) async {
return await userCollection.doc(uid).set({
"name": name,
"email": email,
"friends": [],
"groups": [],
"profilePicture": "",
"uid": uid,
"latitude": "",
"longitude": "",
});
}
//getting user data
Future gettingUserData(String email) async {
QuerySnapshot snapshot =
await userCollection.where("email", isEqualTo: email).get();
return snapshot;
}
// create a group
Future createGroup(String name, String groupName, String id) async {
DocumentReference groupDocumentReference = await groupCollection.add({
"groupName": groupName,
"groupIcon": "",
"groupCreator": "",
"admins": [],
"members": [],
"groupId": "",
});
await groupDocumentReference.update({
"admins": FieldValue.arrayUnion(["${uid}_$name"]),
"groupCreator": FieldValue.arrayUnion(["${id}_$name"]),
"groupId": groupDocumentReference.id
});
DocumentReference userDocumentReference = userCollection.doc(uid);
return await userDocumentReference.update({
"groups":
FieldValue.arrayUnion(["${groupDocumentReference.id}_$groupName"])
});
}
getUserGroups() async {
return userCollection.doc(uid).snapshots();
}
//search
searchByEmail(String userEmail) async {
return userCollection.where('email', isEqualTo: userEmail).get();
}
//get group admins
getGroupAdmins(String groupId) async {
return groupCollection.doc(groupId).snapshots();
}
getGroupMembers(String groupId) async {
return groupCollection.doc(groupId).snapshots();
}
Future addMember(
String groupId,
String groupName,
String memeberId,
memberName,
) async {
DocumentReference userDocumentReference = userCollection.doc(memeberId);
DocumentReference groupDocumentReference = groupCollection.doc(groupId);
DocumentSnapshot userdocumentSnapshot = await userDocumentReference.get();
List<dynamic> groups = await userdocumentSnapshot['groups'];
DocumentSnapshot groupDocumentSnapshot = await groupDocumentReference.get();
List<dynamic> members = await groupDocumentSnapshot['members'];
if (groups.contains("${groupId}_$groupName") &
members.contains("${memeberId}_$memberName")) {
return null;
} else {
await groupCollection.doc(groupId).update({
"members": FieldValue.arrayUnion(["${memeberId}_$memberName"])
});
}
}
}
Here is the AddMemberPage
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:tracker_app/page_changer/page_changer.dart';
import 'package:tracker_app/pages/app_pages/info_page.dart';
import 'package:tracker_app/services/database_service.dart';
import '../../theme/theme.dart';
class AddMembers extends StatefulWidget {
final String groupId;
final String groupName;
const AddMembers({super.key, required this.groupId, required this.groupName});
@override
State<AddMembers> createState() => _AddMembersState();
}
class _AddMembersState extends State<AddMembers> {
QuerySnapshot? searchSnapshot;
TextEditingController emailController = TextEditingController();
String email = "";
String friendId = "";
String friendName = "";
bool isLoading = false;
bool hasUserSearched = false;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(
"Add members",
style: TextStyle(fontSize: 30, fontWeight: FontWeight.w500),
),
centerTitle: true,
),
body: SingleChildScrollView(
child: Column(children: [
const Divider(
height: 5,
indent: 5,
endIndent: 5,
thickness: 1.5,
),
Container(
height: 10,
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 10),
child: TextFormField(
controller: emailController,
cursorColor: AppColors.secondary,
decoration: InputDecoration(
errorBorder: OutlineInputBorder(
borderSide: const BorderSide(color: Colors.red),
borderRadius: BorderRadius.circular(50)),
focusedBorder: OutlineInputBorder(
borderSide: const BorderSide(
color: AppColors.secondary,
),
borderRadius: BorderRadius.circular(50)),
enabledBorder: OutlineInputBorder(
borderSide: const BorderSide(
color: AppColors.secondary,
),
borderRadius: BorderRadius.circular(50)),
labelText: "email",
labelStyle: const TextStyle(
color: AppColors.secondary,
fontWeight: FontWeight.w500,
),
suffixIcon: InkWell(
splashColor: AppColors.secondary,
borderRadius: BorderRadius.circular(360),
onTap: () {
initiateSearchMethod();
},
child: const Icon(
Icons.search,
color: AppColors.secondary,
),
),
hintText: "Enter persons email"),
onChanged: (value) {
setState(() {
email = value;
});
},
),
),
userList(),
]),
),
);
}
initiateSearchMethod() async {
if (emailController != null) {
setState(() {
isLoading = true;
});
await DatabaseService(uid: FirebaseAuth.instance.currentUser!.uid)
.searchByEmail(email)
.then((snapshot) {
setState(() {
searchSnapshot = snapshot;
isLoading = false;
hasUserSearched = true;
friendId = snapshot!.docs[0]['id'];
friendName = snapshot!.docs[0]['name'];
});
});
}
}
userList() {
return hasUserSearched
? ListView.builder(
shrinkWrap: true,
itemCount: searchSnapshot!.docs.length,
itemBuilder: (context, index) {
return friendSearchTile();
},
)
: Container();
}
friendSearchTile() {
// check if user is friend
//GdzhH8YGCsTMhmPf6aAeXvb09GH3
return ListTile(
leading: CircleAvatar(
radius: 25,
backgroundColor: AppColors.secondary,
child: Text(
searchSnapshot!.docs[0]['name'].substring(0, 1).toUpperCase(),
style: const TextStyle(color: Colors.white)),
),
title: Text(friendName),
subtitle: Text(searchSnapshot!.docs[0]['email']),
trailing: InkWell(
borderRadius: BorderRadius.circular(360),
onTap: () {
DatabaseService(uid: FirebaseAuth.instance.currentUser!.uid)
.addMember(
widget.groupId,
widget.groupName,
searchSnapshot!.docs[0]['id'],
searchSnapshot!.docs[0]['name']);
nextScreenReplace(context,
InfoPage(groupName: widget.groupName, groupId: widget.groupId));
print("friendId: $friendId");
},
splashColor: AppColors.secondary,
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 10),
child: const Icon(
Icons.add,
),
),
),
);
}
}
|
[
"After more searching I found the solution. In AddMembers page when clicked to add an user required groupId, groupName, friendId(that users id), friendName(that friends name). The problem was with firendId. The line searchSnapshot!.docs[0]['id] was wrong. In the firebase I marked the users id as 'uid'.After changing that it started working.\nThe line:\nDatabaseService(uid: FirebaseAuth.instance.currentUser!.uid)\n .addMember(\n widget.groupId,\n widget.groupName,\n searchSnapshot!.docs[0]['id'],\n searchSnapshot!.docs[0]['name']);\n\nI changed to:\nDatabaseService(uid: FirebaseAuth.instance.currentUser!.uid)\n .addMember(\n widget.groupId,\n widget.groupName,\n searchSnapshot!.docs[0]['uid'],\n searchSnapshot!.docs[0]['name']);\n\n",
"It looks like the issue is with how you are getting the groups and members arrays from the DocumentSnapshot objects for the user and group documents. In your addMember() function, you are using the await keyword to get the values of the groups and members fields from the DocumentSnapshot objects, but these fields are not async, so using await with them will not work.\nTo fix this, you can simply remove the await keywords when getting the values of the groups and members fields, like this:\nList<dynamic> groups = userdocumentSnapshot['groups'];\nList<dynamic> members = groupDocumentSnapshot['members'];\n\nYou can then use the contains() method on the groups and members lists to check if they already contain the new member and group, and add the new member to the group if they do not already exist in the lists.\nHere is how your addMember() function should look like after making these changes:\nFuture addMember(\n String groupId,\n String groupName,\n String memeberId,\n memberName,\n ) async {\n DocumentReference userDocumentReference = userCollection.doc(memeberId);\n DocumentReference groupDocumentReference = groupCollection.doc(groupId);\n\n DocumentSnapshot userdocumentSnapshot = await userDocumentReference.get();\n List<dynamic> groups = userdocumentSnapshot['groups'];\n\n DocumentSnapshot groupDocumentSnapshot = await groupDocumentReference.get();\n List<dynamic> members = groupDocumentSnapshot['members'];\n\n if (!groups.contains(\"${groupId}_$groupName\") ||\n !members.contains(\"${memeberId}_$memberName\")) {\n await groupCollection.doc(groupId).update({\n \"members\": FieldValue.arrayUnion([\"${memeberId}_$memberName\"])\n });\n }\n }\n\nI hope this helps!\n"
] |
[
0,
0
] |
[] |
[] |
[
"firebase",
"flutter",
"google_cloud_firestore"
] |
stackoverflow_0074669346_firebase_flutter_google_cloud_firestore.txt
|
Q:
Set Parent view (xaml, maui)
I have a main layout with a content view that I want to populate with a bunch a different views.
I thought I would set the parent view from the child, but I haven't figured out how. There may be a better way to accomplish this though.
Layout file:
<ContentPage ...>
<Grid RowDefinitions="*,Auto,*">
...
<ContentView x:Name="ViewToPopulate"
Grid.Row="1"/>
...
</ContentPage>
Sublayout file:
<ContentView ...
Parent="StaticResource ViewToPopulate">
<GridView >
...
</GridView>
</ContentView>
A:
Like @Jason said, you don't set the parent from the child.
I found the best way to do this is follow this suggestion that @Jason also made in the comment of:
Header and Footer in .NET MAUI
|
Set Parent view (xaml, maui)
|
I have a main layout with a content view that I want to populate with a bunch a different views.
I thought I would set the parent view from the child, but I haven't figured out how. There may be a better way to accomplish this though.
Layout file:
<ContentPage ...>
<Grid RowDefinitions="*,Auto,*">
...
<ContentView x:Name="ViewToPopulate"
Grid.Row="1"/>
...
</ContentPage>
Sublayout file:
<ContentView ...
Parent="StaticResource ViewToPopulate">
<GridView >
...
</GridView>
</ContentView>
|
[
"Like @Jason said, you don't set the parent from the child.\nI found the best way to do this is follow this suggestion that @Jason also made in the comment of:\nHeader and Footer in .NET MAUI\n"
] |
[
0
] |
[] |
[] |
[
".net",
"c#",
"maui",
"visual_studio",
"xaml"
] |
stackoverflow_0074564179_.net_c#_maui_visual_studio_xaml.txt
|
Q:
How can I get numbers from number (like this : 731===>[7,3,1]) with recursive function
Here I can use down method to do this
Get a whole number (192)============> (1,9,2)
#include <iostream> // I Know This way
using namespace std;
int argam(int n);
int main()
{
int a;
cout << "Please enter num : ";
cin >> a;
argam(a);
}
int argam(int n)
{
do
{
cout << n % 10 << "\n";
n /= 10;
} while (n > 0);
}
5
4
3
I want to get same answer with recursive function.
A:
It's even shorter when done recursively:
void argam(int n)
{
if (n == 0) return; // end condition for the recursion
cout << n % 10 << "\n"; // print 1 digit
argam(n / 10); // call the same function again without that digit
}
|
How can I get numbers from number (like this : 731===>[7,3,1]) with recursive function
|
Here I can use down method to do this
Get a whole number (192)============> (1,9,2)
#include <iostream> // I Know This way
using namespace std;
int argam(int n);
int main()
{
int a;
cout << "Please enter num : ";
cin >> a;
argam(a);
}
int argam(int n)
{
do
{
cout << n % 10 << "\n";
n /= 10;
} while (n > 0);
}
5
4
3
I want to get same answer with recursive function.
|
[
"It's even shorter when done recursively:\nvoid argam(int n)\n{\n if (n == 0) return; // end condition for the recursion\n cout << n % 10 << \"\\n\"; // print 1 digit\n argam(n / 10); // call the same function again without that digit\n}\n\n"
] |
[
1
] |
[] |
[] |
[
"c++"
] |
stackoverflow_0074669769_c++.txt
|
Q:
Highlighting the SEND button in MFMessageComposeViewController
I have generated an MFMessageComposeViewController to send a preconfigured SMS message, and I now want to draw the user's attention to the send button. The user has already initiated the "send message" process from within the app, but they must then press the send button within the MFMessageComposeViewController to actually send the message. The send button in the standard MFMessageComposeViewController is "hidden away" in the bottom corner of the message body where some, not so tech-savvy users, struggle to find it (a fact not opinion, as I have had test users ask what to do next)!
Apple does not allow this message compose interface to be modified, except for certain exceptions. I have looked into the UIAppearance protocol, which provides limited options to modify aspects of the MFMessageComposeViewController, but the options do not apply to the send button.
I have looked into the documentation, and there are options to highlight or focus on interface objects using the accessibility options, but I can not find a way of linking this to the send button within the MFMessageComposeViewController where I have limited access to the UI components.
How do I highlight the send button within the MFMessageComposeViewController, or access the button so that I can draw the user's attention to it?
A:
To draw the user's attention to the send button within the MFMessageComposeViewController, you can use the accessibilityPerformMagicTap() method. This method will perform the default action for the element that currently has focus.
To use this method, you will need to set the accessibilityTraits property on the send button to .button. This will tell the system that the element is a button and should be treated as such.
Here is an example of how you can use these methods to draw the user's attention to the send button:
// Get a reference to the send button in the MFMessageComposeViewController
let sendButton = messageComposeViewController.sendButton
// Set the accessibilityTraits property on the send button to .button
sendButton.accessibilityTraits = .button
// Call the accessibilityPerformMagicTap() method to perform the default action for the element
sendButton.accessibilityPerformMagicTap()
Please note that this method will only work if VoiceOver is enabled on the device. If VoiceOver is not enabled, this method will not have any effect.
A:
You can use the setAccessibilityFocused method on the send button to set it as the currently focused element on the screen. This will highlight the button and make it more visible to the user.
To access the send button, you can use the viewWithTag method on the MFMessageComposeViewController instance to get a reference to the button. The tag of the send button is 1, so you can use the following code to get a reference to the button and set it as the focused element:
let sendButton = messageComposeViewController.viewWithTag(1) as? UIButton
sendButton?.setAccessibilityFocused(true)
Once you have set the send button as the focused element, you can also use the accessibilityLabel property to set a custom label for the button that will be read out loud to users who have enabled voiceover on their device. This will make it even easier for the user to find the send button and complete the send action.
sendButton?.accessibilityLabel = "Send Message"
This will set the label for the send button to "Send Message", which will be read out loud to users who have enabled voiceover on their device. You can customize the label as needed to make it more user-friendly and easy to understand for your target audience.
|
Highlighting the SEND button in MFMessageComposeViewController
|
I have generated an MFMessageComposeViewController to send a preconfigured SMS message, and I now want to draw the user's attention to the send button. The user has already initiated the "send message" process from within the app, but they must then press the send button within the MFMessageComposeViewController to actually send the message. The send button in the standard MFMessageComposeViewController is "hidden away" in the bottom corner of the message body where some, not so tech-savvy users, struggle to find it (a fact not opinion, as I have had test users ask what to do next)!
Apple does not allow this message compose interface to be modified, except for certain exceptions. I have looked into the UIAppearance protocol, which provides limited options to modify aspects of the MFMessageComposeViewController, but the options do not apply to the send button.
I have looked into the documentation, and there are options to highlight or focus on interface objects using the accessibility options, but I can not find a way of linking this to the send button within the MFMessageComposeViewController where I have limited access to the UI components.
How do I highlight the send button within the MFMessageComposeViewController, or access the button so that I can draw the user's attention to it?
|
[
"To draw the user's attention to the send button within the MFMessageComposeViewController, you can use the accessibilityPerformMagicTap() method. This method will perform the default action for the element that currently has focus.\nTo use this method, you will need to set the accessibilityTraits property on the send button to .button. This will tell the system that the element is a button and should be treated as such.\nHere is an example of how you can use these methods to draw the user's attention to the send button:\n// Get a reference to the send button in the MFMessageComposeViewController\nlet sendButton = messageComposeViewController.sendButton\n\n// Set the accessibilityTraits property on the send button to .button\nsendButton.accessibilityTraits = .button\n\n// Call the accessibilityPerformMagicTap() method to perform the default action for the element\nsendButton.accessibilityPerformMagicTap()\n\nPlease note that this method will only work if VoiceOver is enabled on the device. If VoiceOver is not enabled, this method will not have any effect.\n",
"You can use the setAccessibilityFocused method on the send button to set it as the currently focused element on the screen. This will highlight the button and make it more visible to the user.\nTo access the send button, you can use the viewWithTag method on the MFMessageComposeViewController instance to get a reference to the button. The tag of the send button is 1, so you can use the following code to get a reference to the button and set it as the focused element:\nlet sendButton = messageComposeViewController.viewWithTag(1) as? UIButton\nsendButton?.setAccessibilityFocused(true)\n\nOnce you have set the send button as the focused element, you can also use the accessibilityLabel property to set a custom label for the button that will be read out loud to users who have enabled voiceover on their device. This will make it even easier for the user to find the send button and complete the send action.\nsendButton?.accessibilityLabel = \"Send Message\"\n\nThis will set the label for the send button to \"Send Message\", which will be read out loud to users who have enabled voiceover on their device. You can customize the label as needed to make it more user-friendly and easy to understand for your target audience.\n"
] |
[
0,
0
] |
[] |
[] |
[
"ios",
"swift"
] |
stackoverflow_0068045448_ios_swift.txt
|
Q:
How can I open a modal upon triggering a function?
I have been trying to open a Modal in my react app which will be triggered whenever I will click on a button.
First, I am passing the event of the button as a parameter to another component
{orders.map((item, i) => <OrderHistory item={item} serial={i + 1} key={item._id} viewDetails={ViewDetails(item)} />)}
In the OrderHistory component it receives the function and also return it after successfully execution:
<td><button className="btn btn-primary btn-sm" onClick={viewDetails}>View Details</button></td>
But in the ViewDetails(item), I am trying to open a modal which will popup but whenever I am going to this approach :
`
const ViewDetails = item => () => {
console.log(item);
// toggleModal();
<Modal />
}
return (
<Layout title="Dashboard" className="container-fluid">
{ViewDetails}
<div className="row">
<div className="col-sm-3">
<UserLinks />
</div>
<div className="col-sm-9">
<UserInfo />
{orders ? <PurchaseHistory /> : ""}
</div>
</div>
</Layout>
)
`
it is giving an error :
Warning: Functions are not valid as a React child. This may happen if you return a Component instead of from render. Or maybe you meant to call this function rather than return it.
I have tried to add the whole Modal code in my function as:
`
const toggleModal = () => {
setModalStatus(!modalStatus);
};
const ViewDetails = item => () => {
console.log(item);
setModalStatus(!modalStatus);
if (modalStatus) {
document.body.classList.add('active-modal')
} else {
document.body.classList.remove('active-modal')
}
{
modalStatus && (
<div className="modal">
<div onClick={toggleModal} className="overlay"></div>
<div className="modal-content">
<h2>Hello Modal</h2>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Provident
perferendis suscipit officia recusandae, eveniet quaerat assumenda
id fugit, dignissimos maxime non natus placeat illo iusto!
Sapiente dolorum id maiores dolores? Illum pariatur possimus
quaerat ipsum quos molestiae rem aspernatur dicta tenetur. Sunt
placeat tempora vitae enim incidunt porro fuga ea.
</p>
<button className="close-modal" onClick={toggleModal}>
CLOSE
</button>
</div>
</div>
)
}
}
Also I have tried to use:
return (
<Layout title="Dashboard" className="container-fluid">
{<ViewDetails />}
<div className="row">
<div className="col-sm-3">
<UserLinks />
</div>
<div className="col-sm-9">
<UserInfo />
{orders ? <PurchaseHistory /> : ""}
</div>
</div>
</Layout>
)
`
my CSS code is as follows:
`
body.active-modal {
overflow-y: hidden;
}
.btn-modal {
padding: 10px 20px;
display: block;
margin: 100px auto 0;
font-size: 18px;
color: green;
}
.modal,
.overlay {
width: 100vw;
height: 100vh;
top: 0;
left: 0;
right: 0;
bottom: 0;
position: fixed;
}
.overlay {
background: rgba(49, 49, 49, 0.8);
}
.modal-content {
position: absolute;
top: 40%;
left: 50%;
transform: translate(-50%, -50%);
line-height: 1.4;
background: #f1f1f1;
padding: 14px 28px;
border-radius: 3px;
max-width: 600px;
min-width: 300px;
}
.close-modal {
position: absolute;
top: 10px;
right: 10px;
padding: 5px 7px;
}
`
The event triggers but any kind of Modal is not showing up. I am expecting to change the state upon triggering of an event and then the modal will Show up. But the modal is not showing up.
A:
You can't return the Modal component directly from the ViewDetails function. You should return the Modal component from the main component, and toggle the modal based on the state of the modal.
Then, in the ViewDetails function, you can update the state of the modal to show it when the button is clicked.
function App() {
const [modalStatus, setModalStatus] = useState(false); // Initialize state for modal
const toggleModal = () => {
setModalStatus(!modalStatus); // Update state to show/hide modal
};
const ViewDetails = item => () => {
console.log(item);
toggleModal(); // Show modal when button is clicked
};
return (
<Layout title="Dashboard" className="container-fluid">
{modalStatus && ( // If modal is open, show Modal component
<Modal>
<h2>Hello Modal</h2>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Provident
perferendis suscipit officia recusandae, eveniet quaerat assumenda
id fugit, dignissimos maxime non natus placeat illo iusto!
Sapiente dolorum id maiores dolores? Illum pariatur possimus
quaerat ipsum quos molestiae rem aspernatur dicta tenetur. Sunt
placeat tempora vitae enim incidunt porro fuga ea.
</p>
<button className="close-modal" onClick={toggleModal}>
CLOSE
</button>
</Modal>
)}
<div className="row">
<div className="col-sm-3">
<UserLinks />
</div>
<div className="col-sm-9">
<UserInfo />
{orders ? <PurchaseHistory /> : ""}
</div>
</div>
</Layout>
);
}
the Modal component is only rendered if the modalStatus is true. The toggleModal function is used to update the state of the modal, and the ViewDetails function calls the toggleModal function to show the modal when the button is clicked.
|
How can I open a modal upon triggering a function?
|
I have been trying to open a Modal in my react app which will be triggered whenever I will click on a button.
First, I am passing the event of the button as a parameter to another component
{orders.map((item, i) => <OrderHistory item={item} serial={i + 1} key={item._id} viewDetails={ViewDetails(item)} />)}
In the OrderHistory component it receives the function and also return it after successfully execution:
<td><button className="btn btn-primary btn-sm" onClick={viewDetails}>View Details</button></td>
But in the ViewDetails(item), I am trying to open a modal which will popup but whenever I am going to this approach :
`
const ViewDetails = item => () => {
console.log(item);
// toggleModal();
<Modal />
}
return (
<Layout title="Dashboard" className="container-fluid">
{ViewDetails}
<div className="row">
<div className="col-sm-3">
<UserLinks />
</div>
<div className="col-sm-9">
<UserInfo />
{orders ? <PurchaseHistory /> : ""}
</div>
</div>
</Layout>
)
`
it is giving an error :
Warning: Functions are not valid as a React child. This may happen if you return a Component instead of from render. Or maybe you meant to call this function rather than return it.
I have tried to add the whole Modal code in my function as:
`
const toggleModal = () => {
setModalStatus(!modalStatus);
};
const ViewDetails = item => () => {
console.log(item);
setModalStatus(!modalStatus);
if (modalStatus) {
document.body.classList.add('active-modal')
} else {
document.body.classList.remove('active-modal')
}
{
modalStatus && (
<div className="modal">
<div onClick={toggleModal} className="overlay"></div>
<div className="modal-content">
<h2>Hello Modal</h2>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Provident
perferendis suscipit officia recusandae, eveniet quaerat assumenda
id fugit, dignissimos maxime non natus placeat illo iusto!
Sapiente dolorum id maiores dolores? Illum pariatur possimus
quaerat ipsum quos molestiae rem aspernatur dicta tenetur. Sunt
placeat tempora vitae enim incidunt porro fuga ea.
</p>
<button className="close-modal" onClick={toggleModal}>
CLOSE
</button>
</div>
</div>
)
}
}
Also I have tried to use:
return (
<Layout title="Dashboard" className="container-fluid">
{<ViewDetails />}
<div className="row">
<div className="col-sm-3">
<UserLinks />
</div>
<div className="col-sm-9">
<UserInfo />
{orders ? <PurchaseHistory /> : ""}
</div>
</div>
</Layout>
)
`
my CSS code is as follows:
`
body.active-modal {
overflow-y: hidden;
}
.btn-modal {
padding: 10px 20px;
display: block;
margin: 100px auto 0;
font-size: 18px;
color: green;
}
.modal,
.overlay {
width: 100vw;
height: 100vh;
top: 0;
left: 0;
right: 0;
bottom: 0;
position: fixed;
}
.overlay {
background: rgba(49, 49, 49, 0.8);
}
.modal-content {
position: absolute;
top: 40%;
left: 50%;
transform: translate(-50%, -50%);
line-height: 1.4;
background: #f1f1f1;
padding: 14px 28px;
border-radius: 3px;
max-width: 600px;
min-width: 300px;
}
.close-modal {
position: absolute;
top: 10px;
right: 10px;
padding: 5px 7px;
}
`
The event triggers but any kind of Modal is not showing up. I am expecting to change the state upon triggering of an event and then the modal will Show up. But the modal is not showing up.
|
[
"You can't return the Modal component directly from the ViewDetails function. You should return the Modal component from the main component, and toggle the modal based on the state of the modal.\nThen, in the ViewDetails function, you can update the state of the modal to show it when the button is clicked.\nfunction App() {\n const [modalStatus, setModalStatus] = useState(false); // Initialize state for modal\n\n const toggleModal = () => {\n setModalStatus(!modalStatus); // Update state to show/hide modal\n };\n\n const ViewDetails = item => () => {\n console.log(item);\n toggleModal(); // Show modal when button is clicked\n };\n\n return (\n <Layout title=\"Dashboard\" className=\"container-fluid\">\n {modalStatus && ( // If modal is open, show Modal component\n <Modal>\n <h2>Hello Modal</h2>\n <p>\n Lorem ipsum dolor sit amet consectetur adipisicing elit. Provident\n perferendis suscipit officia recusandae, eveniet quaerat assumenda\n id fugit, dignissimos maxime non natus placeat illo iusto!\n Sapiente dolorum id maiores dolores? Illum pariatur possimus\n quaerat ipsum quos molestiae rem aspernatur dicta tenetur. Sunt\n placeat tempora vitae enim incidunt porro fuga ea.\n </p>\n <button className=\"close-modal\" onClick={toggleModal}>\n CLOSE\n </button>\n </Modal>\n )}\n <div className=\"row\">\n <div className=\"col-sm-3\">\n <UserLinks />\n </div>\n <div className=\"col-sm-9\">\n <UserInfo />\n {orders ? <PurchaseHistory /> : \"\"}\n </div>\n </div>\n </Layout>\n );\n}\n\nthe Modal component is only rendered if the modalStatus is true. The toggleModal function is used to update the state of the modal, and the ViewDetails function calls the toggleModal function to show the modal when the button is clicked.\n"
] |
[
0
] |
[] |
[] |
[
"modal_dialog",
"reactjs"
] |
stackoverflow_0074669730_modal_dialog_reactjs.txt
|
Q:
Fetching instagram feed as JSON
im fetching photos from my instagram account from an api, and get the JSON in my console. However, i dont know how to get the photo displayed in my HTML
This is my JS, where i fetch the photos as JSON.
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var requestOptions = {
method: "get",
headers: myHeaders,
redirect: "follow",
};
fetch("https://v1.nocodeapi.com/aps/instagram/pjCNBSyiUmzTFIzO", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
document.getElementById("test").innerHTML = result;
A:
To display the photos from your Instagram account in your HTML, you will need to parse the JSON response from the API and extract the URLs of the photos. You can then create img elements in your HTML and set the src attribute of each element to the URL of the corresponding photo.
Here is an example of how you might do this:
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var requestOptions = {
method: "get",
headers: myHeaders,
redirect: "follow",
};
fetch("https://v1.nocodeapi.com/aps/instagram/pjCNBSyiUmzTFIzO", requestOptions)
.then((response) => response.json())
.then((result) => {
// Parse the JSON response and extract the photo URLs
const photoUrls = result.data.map((photo) => photo.media_url);
// Create img elements for each photo
const photoElements = photoUrls.map((url) => {
const imgElement = document.createElement("img");
imgElement.src = url;
return imgElement;
});
// Append the img elements to the HTML element with the ID "test"
const testElement = document.getElementById("test");
photoElements.forEach((imgElement) => testElement.appendChild(imgElement));
})
.catch((error) => console.log("error", error));
In this example, the JSON response from the API is parsed and the URLs of the photos are extracted and stored in the photoUrls array. Then, an img element is created for each photo URL, and the src attribute of each element is set to the URL of the corresponding photo. Finally, the img elements are appended to the test element in the HTML.
This will display the photos from your Instagram account in the HTML element with the ID "test". You can customize the code to suit your specific needs, such as by setting the width and height of the photos, or by adding captions or other information. Consult the documentation for the API you are using for more information on the structure of the JSON response and the available data.
|
Fetching instagram feed as JSON
|
im fetching photos from my instagram account from an api, and get the JSON in my console. However, i dont know how to get the photo displayed in my HTML
This is my JS, where i fetch the photos as JSON.
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var requestOptions = {
method: "get",
headers: myHeaders,
redirect: "follow",
};
fetch("https://v1.nocodeapi.com/aps/instagram/pjCNBSyiUmzTFIzO", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
document.getElementById("test").innerHTML = result;
|
[
"To display the photos from your Instagram account in your HTML, you will need to parse the JSON response from the API and extract the URLs of the photos. You can then create img elements in your HTML and set the src attribute of each element to the URL of the corresponding photo.\nHere is an example of how you might do this:\nvar myHeaders = new Headers();\nmyHeaders.append(\"Content-Type\", \"application/json\");\nvar requestOptions = {\n method: \"get\",\n headers: myHeaders,\n redirect: \"follow\",\n};\n\nfetch(\"https://v1.nocodeapi.com/aps/instagram/pjCNBSyiUmzTFIzO\", requestOptions)\n .then((response) => response.json())\n .then((result) => {\n // Parse the JSON response and extract the photo URLs\n const photoUrls = result.data.map((photo) => photo.media_url);\n\n // Create img elements for each photo\n const photoElements = photoUrls.map((url) => {\n const imgElement = document.createElement(\"img\");\n imgElement.src = url;\n return imgElement;\n });\n\n // Append the img elements to the HTML element with the ID \"test\"\n const testElement = document.getElementById(\"test\");\n photoElements.forEach((imgElement) => testElement.appendChild(imgElement));\n })\n .catch((error) => console.log(\"error\", error));\n\n\nIn this example, the JSON response from the API is parsed and the URLs of the photos are extracted and stored in the photoUrls array. Then, an img element is created for each photo URL, and the src attribute of each element is set to the URL of the corresponding photo. Finally, the img elements are appended to the test element in the HTML.\nThis will display the photos from your Instagram account in the HTML element with the ID \"test\". You can customize the code to suit your specific needs, such as by setting the width and height of the photos, or by adding captions or other information. Consult the documentation for the API you are using for more information on the structure of the JSON response and the available data.\n"
] |
[
0
] |
[] |
[] |
[
"fetch_api",
"javascript"
] |
stackoverflow_0074669665_fetch_api_javascript.txt
|
Q:
A Python program to print the longest consecutive chain of words of the same length from a sentence
I got tasked with writing a Python script that would output the longest chain of consecutive words of the same length from a sentence. For example, if the input is "To be or not to be", the output should be "To, be, or".
text = input("Enter text: ")
words = text.replace(",", " ").replace(".", " ").split()
x = 0
same = []
same.append(words[x])
for i in words:
if len(words[x]) == len(words[x+1]):
same.append(words[x+1])
x += 1
elif len(words[x]) != len(words[x+1]):
same = []
x += 1
else:
print("No consecutive words of the same length")
print(words)
print("Longest chain of words with similar length: ", same)
In order to turn the string input into a list of words and to get rid of any punctuation, I used the replace() and split() methods. The first word of this list would then get appended to a new list called "same", which would hold the words with the same length. A for-loop would then compare the lengths of the words one by one, and either append them to this list if their lengths match, or clear the list if they don't.
if len(words[x]) == len(words[x+1]):
~~~~~^^^^^
IndexError: list index out of range
This is the problem I keep getting, and I just can't understand why the index is out of range.
I will be very grateful for any help with solving this issue and fixing the program. Thank you in advance.
A:
using groupby you can get the result as
from itertools import groupby
string = "To be or not to be"
sol = ', '.join(max([list(b) for a, b in groupby(string.split(), key=len)], key=len))
print(sol)
# 'To, be, or'
A:
len() function takes a string as an argument, for instance here in this code according to me first you have to convert the words variable into a list then it might work.
Thank You !!!
|
A Python program to print the longest consecutive chain of words of the same length from a sentence
|
I got tasked with writing a Python script that would output the longest chain of consecutive words of the same length from a sentence. For example, if the input is "To be or not to be", the output should be "To, be, or".
text = input("Enter text: ")
words = text.replace(",", " ").replace(".", " ").split()
x = 0
same = []
same.append(words[x])
for i in words:
if len(words[x]) == len(words[x+1]):
same.append(words[x+1])
x += 1
elif len(words[x]) != len(words[x+1]):
same = []
x += 1
else:
print("No consecutive words of the same length")
print(words)
print("Longest chain of words with similar length: ", same)
In order to turn the string input into a list of words and to get rid of any punctuation, I used the replace() and split() methods. The first word of this list would then get appended to a new list called "same", which would hold the words with the same length. A for-loop would then compare the lengths of the words one by one, and either append them to this list if their lengths match, or clear the list if they don't.
if len(words[x]) == len(words[x+1]):
~~~~~^^^^^
IndexError: list index out of range
This is the problem I keep getting, and I just can't understand why the index is out of range.
I will be very grateful for any help with solving this issue and fixing the program. Thank you in advance.
|
[
"using groupby you can get the result as\nfrom itertools import groupby\nstring = \"To be or not to be\"\nsol = ', '.join(max([list(b) for a, b in groupby(string.split(), key=len)], key=len))\nprint(sol)\n# 'To, be, or'\n\n",
"len() function takes a string as an argument, for instance here in this code according to me first you have to convert the words variable into a list then it might work.\nThank You !!!\n"
] |
[
2,
0
] |
[] |
[] |
[
"for_loop",
"list",
"python",
"string"
] |
stackoverflow_0074669723_for_loop_list_python_string.txt
|
Q:
Firebase getChildrenCount not working in Android app
the maxid integer variable should have the value for the getChildrenCount() from the firebase database, but it seems that the addValueEventListener is not working.
The following is my java code from Android Studio:
@IgnoreExtraProperties
public class ProfileID_Generator extends AppCompatActivity {
public int maxid;
private int ProfileID;
private String value;
private final DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("User");
public ProfileID_Generator(){}
public int profileID_generate(){
ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
if(snapshot.exists()){
maxid = (int) snapshot.getChildrenCount();
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
throw error.toException();
}
});
ref.child(Integer.toString(maxid)).child("ProfileID").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
if(snapshot.exists()){
String val = snapshot.getValue(String.class);
value = val;
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
throw error.toException();
}
});
if(maxid==0){
ProfileID = 10001;
}
else{
ProfileID = Integer.parseInt(value)+1;
}
return ProfileID;
}
}
The following is the data from the realtime database from firebase:
A:
All data is loaded from Firebase (and most cloud APIs) asynchronously, which changes the order in which code executes from what you may expect and be used to.
The problem is not that getChildrenCount isn't working, but that ref.child(Integer.toString(maxid)) is executed before maxid = (int) snapshot.getChildrenCount();. It's easiest to see this if you add some logging:
Log.i("Firebase", "Start loading maxid")
ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
if(snapshot.exists()){
Log.i("Firebase", "Got data for maxid")
maxid = (int) snapshot.getChildrenCount();
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
throw error.toException();
}
});
Log.i("Firebase", "Start loading ProfileID")
ref.child(Integer.toString(maxid)).child("ProfileID").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
if(snapshot.exists()){
String val = snapshot.getValue(String.class);
value = val;
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
throw error.toException();
}
});
When you run this code it logs:
Start loading maxId
Start loading ProfileID
Got data for maxid
This may not be the order in which you expected the output, but it is working as designed and explains perfectly why your code doesn't work: by the time you starting loading the ProfileID, the maxid isn't known yet.
The solution for this type of problem is always the same: any code that needs the data from the database has to be inside onDataChange, be called from there, or otherwise synchronized.
So the simplest fix is to move the code that loads the ProfileID into the onDataChange that sets maxid:
ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
if(snapshot.exists()){
maxid = (int) snapshot.getChildrenCount();
ref.child(Integer.toString(maxid)).child("ProfileID").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
if(snapshot.exists()){
String val = snapshot.getValue(String.class);
value = val;
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
throw error.toException();
}
});
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
throw error.toException();
}
});
This is an incredibly common problem and stumbling block for developers that are new to asynchronous APIs, so I recommend reading up on some more questions about it, such as:
getContactsFromFirebase() method return an empty list
Setting Singleton property value in Firebase Listener
|
Firebase getChildrenCount not working in Android app
|
the maxid integer variable should have the value for the getChildrenCount() from the firebase database, but it seems that the addValueEventListener is not working.
The following is my java code from Android Studio:
@IgnoreExtraProperties
public class ProfileID_Generator extends AppCompatActivity {
public int maxid;
private int ProfileID;
private String value;
private final DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("User");
public ProfileID_Generator(){}
public int profileID_generate(){
ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
if(snapshot.exists()){
maxid = (int) snapshot.getChildrenCount();
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
throw error.toException();
}
});
ref.child(Integer.toString(maxid)).child("ProfileID").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
if(snapshot.exists()){
String val = snapshot.getValue(String.class);
value = val;
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
throw error.toException();
}
});
if(maxid==0){
ProfileID = 10001;
}
else{
ProfileID = Integer.parseInt(value)+1;
}
return ProfileID;
}
}
The following is the data from the realtime database from firebase:
|
[
"All data is loaded from Firebase (and most cloud APIs) asynchronously, which changes the order in which code executes from what you may expect and be used to.\nThe problem is not that getChildrenCount isn't working, but that ref.child(Integer.toString(maxid)) is executed before maxid = (int) snapshot.getChildrenCount();. It's easiest to see this if you add some logging:\nLog.i(\"Firebase\", \"Start loading maxid\")\nref.addValueEventListener(new ValueEventListener() {\n @Override\n public void onDataChange(@NonNull DataSnapshot snapshot) {\n if(snapshot.exists()){\n Log.i(\"Firebase\", \"Got data for maxid\")\n maxid = (int) snapshot.getChildrenCount();\n }\n }\n @Override\n public void onCancelled(@NonNull DatabaseError error) {\n throw error.toException();\n }\n});\n\nLog.i(\"Firebase\", \"Start loading ProfileID\")\nref.child(Integer.toString(maxid)).child(\"ProfileID\").addValueEventListener(new ValueEventListener() {\n @Override\n public void onDataChange(@NonNull DataSnapshot snapshot) {\n if(snapshot.exists()){\n String val = snapshot.getValue(String.class);\n value = val;\n }\n }\n @Override\n public void onCancelled(@NonNull DatabaseError error) {\n throw error.toException();\n }\n});\n\nWhen you run this code it logs:\n\nStart loading maxId\nStart loading ProfileID\nGot data for maxid\n\nThis may not be the order in which you expected the output, but it is working as designed and explains perfectly why your code doesn't work: by the time you starting loading the ProfileID, the maxid isn't known yet.\n\nThe solution for this type of problem is always the same: any code that needs the data from the database has to be inside onDataChange, be called from there, or otherwise synchronized.\nSo the simplest fix is to move the code that loads the ProfileID into the onDataChange that sets maxid:\nref.addValueEventListener(new ValueEventListener() {\n @Override\n public void onDataChange(@NonNull DataSnapshot snapshot) {\n if(snapshot.exists()){\n maxid = (int) snapshot.getChildrenCount();\n\n ref.child(Integer.toString(maxid)).child(\"ProfileID\").addValueEventListener(new ValueEventListener() {\n @Override\n public void onDataChange(@NonNull DataSnapshot snapshot) {\n if(snapshot.exists()){\n String val = snapshot.getValue(String.class);\n value = val;\n }\n }\n @Override\n public void onCancelled(@NonNull DatabaseError error) {\n throw error.toException();\n }\n });\n }\n }\n @Override\n public void onCancelled(@NonNull DatabaseError error) {\n throw error.toException();\n }\n});\n\nThis is an incredibly common problem and stumbling block for developers that are new to asynchronous APIs, so I recommend reading up on some more questions about it, such as:\n\ngetContactsFromFirebase() method return an empty list\nSetting Singleton property value in Firebase Listener\n\n"
] |
[
0
] |
[] |
[] |
[
"android",
"firebase_realtime_database",
"java"
] |
stackoverflow_0074669470_android_firebase_realtime_database_java.txt
|
Q:
how to fix 'cmd package install-create -r -t -S 1699739' returns error 'Unknown failure: cmd: Can't find service: package'
How to fix ("cmd package install-create -r -t -S 1699739' returns error 'Unknown failure: cmd: Can't find service: package") error when i launch the emulator.
'cmd package install-create -r -t -S 1699739' returns error 'Unknown failure: cmd: Can't find service: package'
20:20 Session 'app': Install failed.
Installation failed
Rerun
A:
It's not your fault. The problem is with the functionality of emulator .
SO,
Close the Emulator.
Go to AVD manager and edit virtual device Quick Boot to Cold Boot.
A:
Try the following steps:
Close the emulator
Cold boot app
Clean Build
Open emulator
Run app
A:
1- Close your emulator
2- Go to AVD Manager
3- Click the down arrow next to your emulator -> cold boot now
A:
I had same problem. This is what I did.
Force quit the emulator.
Go to Android Studio, Click on AVD Manager.
In the action column (last column), click the arrow facing down.
Click Cold Boot Now.
Run code from Android Studio again. Things should run normally.
Usually, this happened because the emulator freeze due to the laptop goes to sleep for a long time.
A:
I would suggest you to run the app again. I was also having the similar problem but when i run the app again, the issues got fixed. If it doesn't solve the problem then create a new adv and start launching your app on it.
A:
Do check once if there are multiple instances of emulator running. I got this error when I had 2 instances of emulator running.
|
how to fix 'cmd package install-create -r -t -S 1699739' returns error 'Unknown failure: cmd: Can't find service: package'
|
How to fix ("cmd package install-create -r -t -S 1699739' returns error 'Unknown failure: cmd: Can't find service: package") error when i launch the emulator.
'cmd package install-create -r -t -S 1699739' returns error 'Unknown failure: cmd: Can't find service: package'
20:20 Session 'app': Install failed.
Installation failed
Rerun
|
[
"It's not your fault. The problem is with the functionality of emulator .\nSO,\nClose the Emulator.\nGo to AVD manager and edit virtual device Quick Boot to Cold Boot.\n",
"Try the following steps:\n\nClose the emulator\nCold boot app\nClean Build\nOpen emulator\nRun app\n\n",
"1- Close your emulator\n2- Go to AVD Manager\n\n3- Click the down arrow next to your emulator -> cold boot now\n\n",
"I had same problem. This is what I did.\n\nForce quit the emulator.\nGo to Android Studio, Click on AVD Manager.\nIn the action column (last column), click the arrow facing down.\nClick Cold Boot Now.\nRun code from Android Studio again. Things should run normally.\n\nUsually, this happened because the emulator freeze due to the laptop goes to sleep for a long time.\n",
"I would suggest you to run the app again. I was also having the similar problem but when i run the app again, the issues got fixed. If it doesn't solve the problem then create a new adv and start launching your app on it.\n",
"Do check once if there are multiple instances of emulator running. I got this error when I had 2 instances of emulator running.\n"
] |
[
35,
14,
9,
8,
0,
0
] |
[
"\nGo To AVD Manager on Android studio\nSelect the Edit option\nSelect Boot Option as \"Cold Boot\"\nLaunch the Emulator\nThis should fix your problem\n\n"
] |
[
-1
] |
[
"android",
"android_studio"
] |
stackoverflow_0057256664_android_android_studio.txt
|
Q:
Is their a better way to create a SwiftUI list looping through an array than looping for each VStack
I am trying to create a table that scrolls horizontally after the first column inside, I have a for loop for each column to get data from an array. I know this isn't the correct way because of how many times i am looping the same array but i cant figure out a better solution of doing this.
struct SampleData: Identifiable {
let id = UUID()
let Entity: String
let address1: String
let address2: String
let city: String
let state: String
let zip: Int
let website: String
let billToName: String
let billable: Bool
let hours: String
let accountNo: Int
let BillToEntity: String
let email: String
}
let datas = [
SampleData(
Entity: "Entity 1", address1: "1234 N. Main", address2: "Suite 200", city: "austin",
state: "TX", zip: 12345, website: "www.website.com", billToName: "Test Name 1", billable: false,
hours: "8-5 M-F", accountNo: 123_456_789, BillToEntity: "Bill To Entity 1",
email: "[email protected]"),
SampleData(
Entity: "Entity 2", address1: "5678 N. Main", address2: "Suite 300", city: "livingston",
state: "TX", zip: 12345, website: "www.website.com", billToName: "Test Name 2", billable: false,
hours: "8-5 M-F", accountNo: 123_456_789, BillToEntity: "Bill To Entity 2",
email: "[email protected]"),
SampleData(
Entity: "Entity 3", address1: "90025 N. Main", address2: "Suite 400", city: "houston",
state: "TX", zip: 12345, website: "www.website.com", billToName: "Test Name 3", billable: true,
hours: "8-5 M-F", accountNo: 123_456_789, BillToEntity: "Bill To Entity 3",
email: "[email protected]"),
SampleData(
Entity: "Entity 4", address1: "4456 N. Main", address2: "Suite 500", city: "spring",
state: "TX", zip: 12345, website: "www.website.com", billToName: "Test Name 4", billable: true,
hours: "8-5 M-F", accountNo: 123_456_789, BillToEntity: "Bill To Entity 4",
email: "[email protected]"),
SampleData(
Entity: "Entity 5", address1: "4456 N. Main", address2: "Suite 500", city: "spring",
state: "TX", zip: 12345, website: "www.website.com", billToName: "Test Name 4", billable: true,
hours: "8-5 M-F", accountNo: 123_456_789, BillToEntity: "Bill To Entity 4",
email: "[email protected]"),
SampleData(
Entity: "Entity 6", address1: "56 N. Main", address2: "Suite 500", city: "spring", state: "TX",
zip: 12345, website: "www.website.com", billToName: "Test Name 4", billable: false,
hours: "8-5 M-F", accountNo: 123_456_789, BillToEntity: "Bill To Entity 4",
email: "[email protected]"),
SampleData(
Entity: "Entity 7", address1: "4456 N", address2: "Suite 500", city: "spring", state: "TX",
zip: 12345, website: "www.website.com", billToName: "Test Name 4", billable: true,
hours: "8-5 M-F", accountNo: 123_456_789, BillToEntity: "Bill To Entity 4",
email: "[email protected]"),
SampleData(
Entity: "Entity 8", address1: "44 Main", address2: "Suite 500", city: "spring", state: "TX",
zip: 12345, website: "www.website.com", billToName: "Test Name 4", billable: true,
hours: "8-5 M-F", accountNo: 123_456_789, BillToEntity: "Bill To Entity 4",
email: "[email protected]"),
]
struct TablesView: View {
@State var billable = false
var body: some View {
HStack (alignment: .top){
VStack {
Text("Entity")
HStack(spacing: 16) {
VStack {
ForEach(datas) { val in
Text(val.Entity)
}
}
}
}
ScrollView(.horizontal) {
HStack(alignment: .top) {
VStack {
VStack {
Text("Address1")
ForEach(datas) { val in
Text(val.address1)
}
}
}
VStack {
VStack {
Text("Address2")
ForEach(datas) { val in
Text(val.address2)
}
}
}
VStack {
VStack {
Text("City")
ForEach(datas) { val in
Text(val.city)
}
}
}
VStack {
VStack {
Text("State")
ForEach(datas) { val in
Text(val.state)
}
}
}
VStack {
VStack {
Text("Zip")
ForEach(datas) { val in
Text(String(val.zip))
}
}
}
VStack {
VStack {
Text("Website")
ForEach(datas) { val in
Text(val.website)
}
}
}
VStack {
VStack {
Text("Bill To")
ForEach(datas) { val in
Text(val.billToName)
}
}
}
VStack {
VStack {
Text("Billable")
ForEach(datas) { val in
Image(systemName: val.billable ? "checkmark.square.fill" : "square")
.foregroundColor(val.billable ? Color(UIColor.systemBlue) : Color.secondary)
.onTapGesture {
self.billable.toggle()
}
}
}
}
}
}
}
}
}
List with horizontal scrolling
A:
Using a Grid could make this much nicer. Didn't type out the whole thing here but you get the idea
ScrollView(.horizontal) {
Grid(alignment: .leading) {
GridRow {
Text("Address 1")
Text("Address 2")
Text("city")
}
ForEach(datas) { data in
GridRow {
Text(data.address1)
Text(data.address2)
Text(data.city)
}
}
}
}
A:
SwiftUI already has a Table built-in, e.g.
var body: some View {
Table(datas) {
TableColumn("Address 1", value: \.address1)
TableColumn("Address 2", value: \.address2)
TableColumn("City", value: \.city)
}
}
|
Is their a better way to create a SwiftUI list looping through an array than looping for each VStack
|
I am trying to create a table that scrolls horizontally after the first column inside, I have a for loop for each column to get data from an array. I know this isn't the correct way because of how many times i am looping the same array but i cant figure out a better solution of doing this.
struct SampleData: Identifiable {
let id = UUID()
let Entity: String
let address1: String
let address2: String
let city: String
let state: String
let zip: Int
let website: String
let billToName: String
let billable: Bool
let hours: String
let accountNo: Int
let BillToEntity: String
let email: String
}
let datas = [
SampleData(
Entity: "Entity 1", address1: "1234 N. Main", address2: "Suite 200", city: "austin",
state: "TX", zip: 12345, website: "www.website.com", billToName: "Test Name 1", billable: false,
hours: "8-5 M-F", accountNo: 123_456_789, BillToEntity: "Bill To Entity 1",
email: "[email protected]"),
SampleData(
Entity: "Entity 2", address1: "5678 N. Main", address2: "Suite 300", city: "livingston",
state: "TX", zip: 12345, website: "www.website.com", billToName: "Test Name 2", billable: false,
hours: "8-5 M-F", accountNo: 123_456_789, BillToEntity: "Bill To Entity 2",
email: "[email protected]"),
SampleData(
Entity: "Entity 3", address1: "90025 N. Main", address2: "Suite 400", city: "houston",
state: "TX", zip: 12345, website: "www.website.com", billToName: "Test Name 3", billable: true,
hours: "8-5 M-F", accountNo: 123_456_789, BillToEntity: "Bill To Entity 3",
email: "[email protected]"),
SampleData(
Entity: "Entity 4", address1: "4456 N. Main", address2: "Suite 500", city: "spring",
state: "TX", zip: 12345, website: "www.website.com", billToName: "Test Name 4", billable: true,
hours: "8-5 M-F", accountNo: 123_456_789, BillToEntity: "Bill To Entity 4",
email: "[email protected]"),
SampleData(
Entity: "Entity 5", address1: "4456 N. Main", address2: "Suite 500", city: "spring",
state: "TX", zip: 12345, website: "www.website.com", billToName: "Test Name 4", billable: true,
hours: "8-5 M-F", accountNo: 123_456_789, BillToEntity: "Bill To Entity 4",
email: "[email protected]"),
SampleData(
Entity: "Entity 6", address1: "56 N. Main", address2: "Suite 500", city: "spring", state: "TX",
zip: 12345, website: "www.website.com", billToName: "Test Name 4", billable: false,
hours: "8-5 M-F", accountNo: 123_456_789, BillToEntity: "Bill To Entity 4",
email: "[email protected]"),
SampleData(
Entity: "Entity 7", address1: "4456 N", address2: "Suite 500", city: "spring", state: "TX",
zip: 12345, website: "www.website.com", billToName: "Test Name 4", billable: true,
hours: "8-5 M-F", accountNo: 123_456_789, BillToEntity: "Bill To Entity 4",
email: "[email protected]"),
SampleData(
Entity: "Entity 8", address1: "44 Main", address2: "Suite 500", city: "spring", state: "TX",
zip: 12345, website: "www.website.com", billToName: "Test Name 4", billable: true,
hours: "8-5 M-F", accountNo: 123_456_789, BillToEntity: "Bill To Entity 4",
email: "[email protected]"),
]
struct TablesView: View {
@State var billable = false
var body: some View {
HStack (alignment: .top){
VStack {
Text("Entity")
HStack(spacing: 16) {
VStack {
ForEach(datas) { val in
Text(val.Entity)
}
}
}
}
ScrollView(.horizontal) {
HStack(alignment: .top) {
VStack {
VStack {
Text("Address1")
ForEach(datas) { val in
Text(val.address1)
}
}
}
VStack {
VStack {
Text("Address2")
ForEach(datas) { val in
Text(val.address2)
}
}
}
VStack {
VStack {
Text("City")
ForEach(datas) { val in
Text(val.city)
}
}
}
VStack {
VStack {
Text("State")
ForEach(datas) { val in
Text(val.state)
}
}
}
VStack {
VStack {
Text("Zip")
ForEach(datas) { val in
Text(String(val.zip))
}
}
}
VStack {
VStack {
Text("Website")
ForEach(datas) { val in
Text(val.website)
}
}
}
VStack {
VStack {
Text("Bill To")
ForEach(datas) { val in
Text(val.billToName)
}
}
}
VStack {
VStack {
Text("Billable")
ForEach(datas) { val in
Image(systemName: val.billable ? "checkmark.square.fill" : "square")
.foregroundColor(val.billable ? Color(UIColor.systemBlue) : Color.secondary)
.onTapGesture {
self.billable.toggle()
}
}
}
}
}
}
}
}
}
List with horizontal scrolling
|
[
"Using a Grid could make this much nicer. Didn't type out the whole thing here but you get the idea\n ScrollView(.horizontal) {\n Grid(alignment: .leading) {\n GridRow {\n Text(\"Address 1\")\n Text(\"Address 2\")\n Text(\"city\")\n }\n \n ForEach(datas) { data in\n GridRow {\n Text(data.address1)\n Text(data.address2)\n Text(data.city)\n }\n }\n }\n }\n\n\n",
"SwiftUI already has a Table built-in, e.g.\nvar body: some View {\n Table(datas) {\n TableColumn(\"Address 1\", value: \\.address1)\n TableColumn(\"Address 2\", value: \\.address2)\n TableColumn(\"City\", value: \\.city)\n }\n}\n\n"
] |
[
0,
0
] |
[] |
[] |
[
"swift",
"swiftui",
"swiftui_list"
] |
stackoverflow_0074663827_swift_swiftui_swiftui_list.txt
|
Q:
Smarty html_options
For smarty's html_options function, is there a way to avoid having to do this (other than not using smarty that is)?
{if $smarty.post}
{html_options name=option_1 options=$options selected=$smarty.post.option_1}
{else}
{html_options name=option_1 options=$options}
{/if}
I realize that it won't show up in the template, but it seems like a bad practice to leave something that is not defined in the template (it also fills up my error logs with noise about undefined indexes).
[edit]
What I am looking for is a way to do it like this without having the undefined index errors show up, as well as reducing the smarty noise in the template files.
{html_options name=option_1 options=$options selected=$smarty.post.option_1}
I guess it would more likely be a modified html_options plugin?
[edit]
As per @mmcgrail's idea:
{if isset($smarty.post.option_1)}
{assign var=selected value=$smarty.post.option_1}
{else}
{assign var=selected value=$default.option_1}
{/if}
{html_options name=option_1 options=$options selected=$selected}
I find this even worse because it is creating new variables in the template, straying from the supposed goal of smarty.
I guess this works:
or:
<?php
//[... snip ...]
$option_1 = isset($_POST['option_1'])? $_POST['option_1'] : $default['option_1'];
$template->assign('option_1', $option_1);
$template->display('my_template.tpl');
And in the template:
{html_options name=option_1 options=$options selected=$option_1}
But then what is the point of smarty keeping track of all of the post/get/request/cookie/server/constants if you can't use them in the template without doubling the amount of code you have to write?
A:
try this
{if isset($smarty.post)}
{html_options name=option_1 optins=$options selected=$smarty.post.option_1}
{/if}
i think that answer your question
A:
I know it's like 12y later but ...
While migrating an app to php 8.1 I just hit this same issue :)
So the real solution that worked was
{html_options name=option_1 options=$options selected=$default.option_1|default:""}
A:
Turns out that without writing a separate plugin what I want is not possible... maybe I will do that, something like:
{html_options name=option_1 options=$options selected=$default.option_1 post=option_1}
|
Smarty html_options
|
For smarty's html_options function, is there a way to avoid having to do this (other than not using smarty that is)?
{if $smarty.post}
{html_options name=option_1 options=$options selected=$smarty.post.option_1}
{else}
{html_options name=option_1 options=$options}
{/if}
I realize that it won't show up in the template, but it seems like a bad practice to leave something that is not defined in the template (it also fills up my error logs with noise about undefined indexes).
[edit]
What I am looking for is a way to do it like this without having the undefined index errors show up, as well as reducing the smarty noise in the template files.
{html_options name=option_1 options=$options selected=$smarty.post.option_1}
I guess it would more likely be a modified html_options plugin?
[edit]
As per @mmcgrail's idea:
{if isset($smarty.post.option_1)}
{assign var=selected value=$smarty.post.option_1}
{else}
{assign var=selected value=$default.option_1}
{/if}
{html_options name=option_1 options=$options selected=$selected}
I find this even worse because it is creating new variables in the template, straying from the supposed goal of smarty.
I guess this works:
or:
<?php
//[... snip ...]
$option_1 = isset($_POST['option_1'])? $_POST['option_1'] : $default['option_1'];
$template->assign('option_1', $option_1);
$template->display('my_template.tpl');
And in the template:
{html_options name=option_1 options=$options selected=$option_1}
But then what is the point of smarty keeping track of all of the post/get/request/cookie/server/constants if you can't use them in the template without doubling the amount of code you have to write?
|
[
"try this \n {if isset($smarty.post)}\n {html_options name=option_1 optins=$options selected=$smarty.post.option_1}\n {/if}\n\ni think that answer your question\n",
"I know it's like 12y later but ...\nWhile migrating an app to php 8.1 I just hit this same issue :)\nSo the real solution that worked was\n{html_options name=option_1 options=$options selected=$default.option_1|default:\"\"}\n\n",
"Turns out that without writing a separate plugin what I want is not possible... maybe I will do that, something like:\n{html_options name=option_1 options=$options selected=$default.option_1 post=option_1}\n\n"
] |
[
1,
0,
-1
] |
[] |
[] |
[
"php",
"smarty",
"undefined_index"
] |
stackoverflow_0002509846_php_smarty_undefined_index.txt
|
Q:
Bootstrap burger menu not worked
I copied the navbar from the bootstrap navbar documentation, but when I click, the hamburger menu does not work for me, it just does not display the nav items for me.
my hamburger menu
My code in bs-navbar.component.html
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container-fluid">
<img src="../../assets/images/logo.png" alt="" width="55" height="60"/>
<a class="navbar-brand fw-bold ms-4" href="#">medochek</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarText" aria-controls="navbarText" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarText">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link" href="#">Замовити</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Контакти</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Галерея</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Про мед</a>
</li>
</ul>
<span class="navbar-text">
+380 66-842-45-32
</span>
</div>
</div>
</nav>
I use Angular so I'm imported bootstrap like this: @import "~bootstrap/dist/css/bootstrap.css" in styles.css
A:
You need the following imports in your framework's import style to be imported for the bootstrap navbar button to work and also for all the styles visible completely.
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
The compatible versions of the above links you can check & replace for the bootstrap version you are using.
The second option is you can write your own javascript code to add/remove dynamic CSS active class from your navbar menu.
|
Bootstrap burger menu not worked
|
I copied the navbar from the bootstrap navbar documentation, but when I click, the hamburger menu does not work for me, it just does not display the nav items for me.
my hamburger menu
My code in bs-navbar.component.html
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container-fluid">
<img src="../../assets/images/logo.png" alt="" width="55" height="60"/>
<a class="navbar-brand fw-bold ms-4" href="#">medochek</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarText" aria-controls="navbarText" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarText">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link" href="#">Замовити</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Контакти</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Галерея</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Про мед</a>
</li>
</ul>
<span class="navbar-text">
+380 66-842-45-32
</span>
</div>
</div>
</nav>
I use Angular so I'm imported bootstrap like this: @import "~bootstrap/dist/css/bootstrap.css" in styles.css
|
[
"You need the following imports in your framework's import style to be imported for the bootstrap navbar button to work and also for all the styles visible completely.\n\n <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css\">\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js\"></script>\n <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js\"></script>\n\n\nThe compatible versions of the above links you can check & replace for the bootstrap version you are using.\nThe second option is you can write your own javascript code to add/remove dynamic CSS active class from your navbar menu.\n"
] |
[
1
] |
[] |
[] |
[
"angular",
"bootstrap_5",
"css",
"html"
] |
stackoverflow_0074669672_angular_bootstrap_5_css_html.txt
|
Q:
Can't open label file. (This can be normal only if you use MSCOCO) YoloV4
I'm working with YoloV4 model object detection. I'm trying to train the custom dataset but I'm constantly getting this error line:
Can't open label file. (This can be normal only if you use MSCOCO): data/obj/13_PNG.rf.c87d3ef90086ec0d21254a8a7c97147a.txt
Can't open label file. (This can be normal only if you use MSCOCO): data/obj/13_PNG.rf.c87d3ef90086ec0d21254a8a7c97147a.txt
Can't open label file. (This can be normal only if you use MSCOCO): data/obj/13_PNG.rf.c87d3ef90086ec0d21254a8a7c97147a.txt
Training file paths don't seem to match but I can't figure out how to fix that problem. I'm struggling for hours.
The command I'm trying to run the training process with:
!./darknet detector train data/obj.data cfg/custom-yolov4-detector.cfg yolov4.conv.137 -dont_show
And the train files and directories:
%cd /content/darknet/
%cp {dataset.location}/train/_classes.txt data/obj.names
%mkdir -p data/obj
#copy image and labels
%cp {dataset.location}/train/*.jpg data/obj/
%cp {dataset.location}/valid/*.jpg data/obj/
%cp {dataset.location}/train/*.txt data/obj/
%cp {dataset.location}/valid/*.txt data/obj/
with open('data/obj.data', 'w') as out:
out.write('classes = 2\n')
out.write('train = data/train.txt\n')
out.write('valid = data/valid.txt\n')
out.write('names = data/obj.names\n')
out.write('backup = backup/')
#write train file (just the image list)
import os
with open('data/train.txt', 'w') as out:
for img in [f for f in os.listdir(dataset.location + '/train') if f.endswith('jpg')]:
out.write('data/obj/' + img + '\n')
#write the valid file (just the image list)
import os
with open('data/valid.txt', 'w') as out:
for img in [f for f in os.listdir(dataset.location + '/valid') if f.endswith('jpg')]:
out.write('data/obj/' + img + '\n')
A:
Make sure that your labels(annotations) and the training image names are the same. If there is a difference between labels and image names, then it will cause this particular error. I had the same error when working with annotation files. For me, it happened when I had to convert from .png to .jpg and that changed the filename in the process.
|
Can't open label file. (This can be normal only if you use MSCOCO) YoloV4
|
I'm working with YoloV4 model object detection. I'm trying to train the custom dataset but I'm constantly getting this error line:
Can't open label file. (This can be normal only if you use MSCOCO): data/obj/13_PNG.rf.c87d3ef90086ec0d21254a8a7c97147a.txt
Can't open label file. (This can be normal only if you use MSCOCO): data/obj/13_PNG.rf.c87d3ef90086ec0d21254a8a7c97147a.txt
Can't open label file. (This can be normal only if you use MSCOCO): data/obj/13_PNG.rf.c87d3ef90086ec0d21254a8a7c97147a.txt
Training file paths don't seem to match but I can't figure out how to fix that problem. I'm struggling for hours.
The command I'm trying to run the training process with:
!./darknet detector train data/obj.data cfg/custom-yolov4-detector.cfg yolov4.conv.137 -dont_show
And the train files and directories:
%cd /content/darknet/
%cp {dataset.location}/train/_classes.txt data/obj.names
%mkdir -p data/obj
#copy image and labels
%cp {dataset.location}/train/*.jpg data/obj/
%cp {dataset.location}/valid/*.jpg data/obj/
%cp {dataset.location}/train/*.txt data/obj/
%cp {dataset.location}/valid/*.txt data/obj/
with open('data/obj.data', 'w') as out:
out.write('classes = 2\n')
out.write('train = data/train.txt\n')
out.write('valid = data/valid.txt\n')
out.write('names = data/obj.names\n')
out.write('backup = backup/')
#write train file (just the image list)
import os
with open('data/train.txt', 'w') as out:
for img in [f for f in os.listdir(dataset.location + '/train') if f.endswith('jpg')]:
out.write('data/obj/' + img + '\n')
#write the valid file (just the image list)
import os
with open('data/valid.txt', 'w') as out:
for img in [f for f in os.listdir(dataset.location + '/valid') if f.endswith('jpg')]:
out.write('data/obj/' + img + '\n')
|
[
"Make sure that your labels(annotations) and the training image names are the same. If there is a difference between labels and image names, then it will cause this particular error. I had the same error when working with annotation files. For me, it happened when I had to convert from .png to .jpg and that changed the filename in the process.\n"
] |
[
0
] |
[] |
[] |
[
"google_colaboratory",
"neural_network",
"python"
] |
stackoverflow_0073652439_google_colaboratory_neural_network_python.txt
|
Q:
Artifacts not uploaded on Sentry on Vercel build
As I am using a private Gitlab server, this is the way I am deploying my app using vercel cli
DEPLOYMENT_URL=$(VERCEL_ORG_ID=$VERCEL_ORG_ID VERCEL_PROJECT_ID=$VERCEL_PROJECT_ID vercel --yes --force \
--token $VERCEL_TOKEN \
--env NEXT_PUBLIC_SENTRY_DSN=$SENTRY_DNS \
--build-env NEXT_PUBLIC_SENTRY_DSN=$SENTRY_DNS \
--build-env SENTRY_AUTH_TOKEN=$SENTRY_AUTH_TOKEN \
--build-env SENTRY_RELEASE=$CI_COMMIT_SHA \
--env SENTRY_RELEASE=$CI_COMMIT_SHA \
--regions fra1 )
vercel alias set $DEPLOYMENT_URL $APPLICATION_URL -t $VERCEL_TOKEN --scope ajouve
When I am running a npm run build in my local environment or in my gitlab-ci pipeline with the variables SENTRY_AUTH_TOKEN set I have my artifacts uploaded on sentry
I expect the artifacts to be uploaded with Vercel
See the attached screenshot, the 0 are the deploys from vercel and the 166 from local or gitlab ci
A:
I had a similar issue with Nextjs, Vercel and Sentry.
Creating a PR on Github triggered a new Vercel deployment and I expected the Sentry-Vercel integration to upload the sourcemaps to Sentry, which didn't work. It created a new release in Sentry but the artifacts were zero (same as shown in your screen shot)
I tried running yarn build locally which did work (created a release and added the artifacts).
But, it seems that this is actually the expected behaviour as described here:
https://github.com/getsentry/sentry-javascript/issues/6035#issuecomment-1292880824
https://github.com/getsentry/sentry-javascript/pull/5603
In general, sourcemaps shouldn't be uploaded to Sentry for anything but prod deployments...
Setting disableClientWebpackPlugin or disableServerWebpackPlugin to false fixed it for me.
Content of my next.config.js file:
// eslint-disable-next-line @typescript-eslint/no-var-requires
const { withSentryConfig } = require("@sentry/nextjs");
/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
appDir: true,
serverComponentsExternalPackages: ["@prisma/client"],
},
eslint: {
dirs: ["."],
},
};
const moduleExports = {
...nextConfig,
sentry: {
hideSourceMaps: true,
disableServerWebpackPlugin: false,
disableClientWebpackPlugin: false,
},
};
const sentryWebpackPluginOptions = {
silent: true,
};
module.exports = withSentryConfig(moduleExports, sentryWebpackPluginOptions);
Hope that helps!
|
Artifacts not uploaded on Sentry on Vercel build
|
As I am using a private Gitlab server, this is the way I am deploying my app using vercel cli
DEPLOYMENT_URL=$(VERCEL_ORG_ID=$VERCEL_ORG_ID VERCEL_PROJECT_ID=$VERCEL_PROJECT_ID vercel --yes --force \
--token $VERCEL_TOKEN \
--env NEXT_PUBLIC_SENTRY_DSN=$SENTRY_DNS \
--build-env NEXT_PUBLIC_SENTRY_DSN=$SENTRY_DNS \
--build-env SENTRY_AUTH_TOKEN=$SENTRY_AUTH_TOKEN \
--build-env SENTRY_RELEASE=$CI_COMMIT_SHA \
--env SENTRY_RELEASE=$CI_COMMIT_SHA \
--regions fra1 )
vercel alias set $DEPLOYMENT_URL $APPLICATION_URL -t $VERCEL_TOKEN --scope ajouve
When I am running a npm run build in my local environment or in my gitlab-ci pipeline with the variables SENTRY_AUTH_TOKEN set I have my artifacts uploaded on sentry
I expect the artifacts to be uploaded with Vercel
See the attached screenshot, the 0 are the deploys from vercel and the 166 from local or gitlab ci
|
[
"I had a similar issue with Nextjs, Vercel and Sentry.\nCreating a PR on Github triggered a new Vercel deployment and I expected the Sentry-Vercel integration to upload the sourcemaps to Sentry, which didn't work. It created a new release in Sentry but the artifacts were zero (same as shown in your screen shot)\nI tried running yarn build locally which did work (created a release and added the artifacts).\nBut, it seems that this is actually the expected behaviour as described here:\n\nhttps://github.com/getsentry/sentry-javascript/issues/6035#issuecomment-1292880824\nhttps://github.com/getsentry/sentry-javascript/pull/5603\n\n\nIn general, sourcemaps shouldn't be uploaded to Sentry for anything but prod deployments...\n\nSetting disableClientWebpackPlugin or disableServerWebpackPlugin to false fixed it for me.\nContent of my next.config.js file:\n// eslint-disable-next-line @typescript-eslint/no-var-requires\nconst { withSentryConfig } = require(\"@sentry/nextjs\");\n\n/** @type {import('next').NextConfig} */\nconst nextConfig = {\n experimental: {\n appDir: true,\n serverComponentsExternalPackages: [\"@prisma/client\"],\n },\n eslint: {\n dirs: [\".\"],\n },\n};\n\nconst moduleExports = {\n ...nextConfig,\n\n sentry: {\n hideSourceMaps: true,\n disableServerWebpackPlugin: false,\n disableClientWebpackPlugin: false,\n },\n};\n\nconst sentryWebpackPluginOptions = {\n silent: true,\n};\n\nmodule.exports = withSentryConfig(moduleExports, sentryWebpackPluginOptions);\n\n\nHope that helps!\n"
] |
[
1
] |
[] |
[] |
[
"next.js",
"sentry",
"vercel"
] |
stackoverflow_0074581114_next.js_sentry_vercel.txt
|
Q:
Maven maven-surefire-plugin not all tests are running
for some reason when i run Maven test using version 2.20 of maven-surefire-plugin My Java Integration Tests And Unit Tests are executing. When I use 2.22.1 of maven-surefire-plugin it runs only Mock and Smoke tests. What can be the solution to run all tests at once?
pom.xml file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>weatherProject</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
</plugins>
</build>
I tried using multiple version but it didn't help. Tried using newest version of maven-surefire-plugin
A:
Perhaps this is your problem?
Directly from the Surefire Plugin website, Upgrade Check for JUnit 4.x
As of Surefire version 2.7, the algorithm for choosing which tests to run has changed. From 2.7 and on, only valid JUnit tests are run for all versions of JUnit, where older versions of the plugin would also run invalid tests that satisfied the naming convention.
When upgrading from a Surefire version prior to 2.7, the build can be run with the flag -Dsurefire.junit4.upgradecheck. This will perform a check and notify you of any invalid tests that will not be run with this version of Surefire (and the build fails). This is only meant to be used as a tool when upgrading to check that all expected tests will be run. It is a transitional feature that will be removed in a future version of surefire.
|
Maven maven-surefire-plugin not all tests are running
|
for some reason when i run Maven test using version 2.20 of maven-surefire-plugin My Java Integration Tests And Unit Tests are executing. When I use 2.22.1 of maven-surefire-plugin it runs only Mock and Smoke tests. What can be the solution to run all tests at once?
pom.xml file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>weatherProject</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
</plugins>
</build>
I tried using multiple version but it didn't help. Tried using newest version of maven-surefire-plugin
|
[
"Perhaps this is your problem?\nDirectly from the Surefire Plugin website, Upgrade Check for JUnit 4.x\n\nAs of Surefire version 2.7, the algorithm for choosing which tests to run has changed. From 2.7 and on, only valid JUnit tests are run for all versions of JUnit, where older versions of the plugin would also run invalid tests that satisfied the naming convention.\n\n\nWhen upgrading from a Surefire version prior to 2.7, the build can be run with the flag -Dsurefire.junit4.upgradecheck. This will perform a check and notify you of any invalid tests that will not be run with this version of Surefire (and the build fails). This is only meant to be used as a tool when upgrading to check that all expected tests will be run. It is a transitional feature that will be removed in a future version of surefire.\n\n"
] |
[
0
] |
[] |
[] |
[
"java",
"maven",
"maven_surefire_plugin",
"pom.xml"
] |
stackoverflow_0074669795_java_maven_maven_surefire_plugin_pom.xml.txt
|
Q:
Livewire Session flash not showing after redirect to another page
I'm using livewire to create a form that a user has to fill up.After that if the form is completed i redirect the user to his dashboard with a session flash.
//CreateAppointment.php
public function createAppointment(){
$this->insertAppointment();
session()->flash("appointment", "Your appointment sent successfully!");
redirect()->to('/dashboard');
$this->sendNotification();
$this->emit('alert_remove');
}
And this is how i display that message on the dashboards blade file:
@if(session()->has("appointment"))
<div id = "ecim" class="alert-success mb-10 border-t-4 border-green-500 rounded-b text-green-900 px-4 py-3 shadow-md" role="alert">
<div class="flex">
<div>
<p class="font-bold">{{ session("appointment") }}</p>
</div>
</div>
</div>
@elseif(session()->has("appointmentError"))
<div id = "nkEcim" class="alert-error mb-10 border-t-4 border-red-500 rounded-b text-red-900 px-4 py-3 shadow-md" role="alert">
<div class="flex">
<div>
<p class="font-bold">{{ session("appointmentError") }}</p>
</div>
</div>
</div>
@endif
@push('scripts')
<script type="text/javascript">
$(document).ready(function(){
window.livewire.on('alert_remove',()=>{
console.log("test");
setTimeout(function(){
$("#ecim").fadeOut('slow');
}, 3000); // 3 secs
});
});
$(document).ready(function(){
window.livewire.on('alert_remove_failed',()=>{
setTimeout(function(){
$("#nkEcim").fadeOut('slow');
}, 3000); // 3 secs
});
});
</script>
@endpush
Appointment Error message shows up fine but the "appointment" message it doesnt show up.
Checking the developer tools the console.log message also shows up.
A:
The issue is likely caused by the redirect()->to('/dashboard') call in the createAppointment method. When you redirect the user to a new page, the current page is terminated and any data in the session is lost. This means that when the user is redirected to the /dashboard page, the "appointment" session flash is no longer available and is not displayed on the page.
To fix this issue, you can use the with method on the redirect instance to pass data to the new page. This will allow you to keep the "appointment" session flash data when the user is redirected to the /dashboard page.
Here's how you might modify the createAppointment method to pass the "appointment" session flash data to the /dashboard page:
public function createAppointment()
{
$this->insertAppointment();
session()->flash("appointment", "Your appointment sent successfully!");
// Pass the "appointment" session flash data to the /dashboard page
redirect()->to('/dashboard')->with(["appointment" => session("appointment")]);
$this->sendNotification();
$this->emit('alert_remove');
}
With this change, the "appointment" session flash data will be preserved when the user is redirected to the /dashboard page, and it will be displayed on that page.
|
Livewire Session flash not showing after redirect to another page
|
I'm using livewire to create a form that a user has to fill up.After that if the form is completed i redirect the user to his dashboard with a session flash.
//CreateAppointment.php
public function createAppointment(){
$this->insertAppointment();
session()->flash("appointment", "Your appointment sent successfully!");
redirect()->to('/dashboard');
$this->sendNotification();
$this->emit('alert_remove');
}
And this is how i display that message on the dashboards blade file:
@if(session()->has("appointment"))
<div id = "ecim" class="alert-success mb-10 border-t-4 border-green-500 rounded-b text-green-900 px-4 py-3 shadow-md" role="alert">
<div class="flex">
<div>
<p class="font-bold">{{ session("appointment") }}</p>
</div>
</div>
</div>
@elseif(session()->has("appointmentError"))
<div id = "nkEcim" class="alert-error mb-10 border-t-4 border-red-500 rounded-b text-red-900 px-4 py-3 shadow-md" role="alert">
<div class="flex">
<div>
<p class="font-bold">{{ session("appointmentError") }}</p>
</div>
</div>
</div>
@endif
@push('scripts')
<script type="text/javascript">
$(document).ready(function(){
window.livewire.on('alert_remove',()=>{
console.log("test");
setTimeout(function(){
$("#ecim").fadeOut('slow');
}, 3000); // 3 secs
});
});
$(document).ready(function(){
window.livewire.on('alert_remove_failed',()=>{
setTimeout(function(){
$("#nkEcim").fadeOut('slow');
}, 3000); // 3 secs
});
});
</script>
@endpush
Appointment Error message shows up fine but the "appointment" message it doesnt show up.
Checking the developer tools the console.log message also shows up.
|
[
"The issue is likely caused by the redirect()->to('/dashboard') call in the createAppointment method. When you redirect the user to a new page, the current page is terminated and any data in the session is lost. This means that when the user is redirected to the /dashboard page, the \"appointment\" session flash is no longer available and is not displayed on the page.\nTo fix this issue, you can use the with method on the redirect instance to pass data to the new page. This will allow you to keep the \"appointment\" session flash data when the user is redirected to the /dashboard page.\nHere's how you might modify the createAppointment method to pass the \"appointment\" session flash data to the /dashboard page:\npublic function createAppointment()\n{\n $this->insertAppointment();\n session()->flash(\"appointment\", \"Your appointment sent successfully!\");\n\n // Pass the \"appointment\" session flash data to the /dashboard page\n redirect()->to('/dashboard')->with([\"appointment\" => session(\"appointment\")]);\n\n $this->sendNotification();\n $this->emit('alert_remove');\n}\n\nWith this change, the \"appointment\" session flash data will be preserved when the user is redirected to the /dashboard page, and it will be displayed on that page.\n"
] |
[
0
] |
[] |
[] |
[
"jquery",
"laravel",
"laravel_blade",
"laravel_livewire"
] |
stackoverflow_0074667302_jquery_laravel_laravel_blade_laravel_livewire.txt
|
Q:
How to conditionally initialize a member of a struct?
I am beginning to learn C++ struct. After creating a struct named Person, I tried to declare a boolean variable named genderBoolean in the struct of Person, and a string variable named gender. I tried to use if-else statement for the following condition: if genderBoolean is true, then gender is male, but if genderBoolean is false, then gender is female. I tried to put the if-else statement outside of the struct, but the IDE says
Identifier "genderBoolean" is undefined
which causes another compilation error.
It seems that if-else statement cannot be used within struct in C++. I found out that adding a # before the if statement and adding #endif can solve the compilation error of "expected a declaration" in Microsoft Visual Code 2022, but the output of the program is:
"Name = Mike Gender = Age = 50 Nationality = American"
I expected its output to be :
"Name = Mike Gender = male Age = 50 Nationality = American"
My code also generates compilation message that says the variable genderBoolean is uninitialized, but it can run:
#include <iostream>
using namespace std;
int main() {
struct Person {
string name;
bool genderBoolean;
string gender;
string age;
string nationality;
#if(genderBoolean == true) {
gender = "male";
}
else if (genderBoolean == false) {
gender = "female";
}
#endif
};
Person person1;
person1.name = "Mike";
person1.genderBoolean = true;
person1.age = "50";
person1.nationality = "American";
cout << "Name = " << person1.name << " Gender = " << person1.gender <<
" Age = " << person1.age << " Nationality = " << person1.nationality <<
endl;
return 0;
}
I tried to put the if-else statement outside of the struct but it says identifier "genderBoolean" is undefined.
I expected its output to be :
"Name = Mike Gender = male Age = 50 Nationality = American"
What actually resulted :
"Name = Mike Gender = Age = 50 Nationality = American"
A:
Here are a few different ways to handle it using a constructor and a setter. Keep in mind that adding a parameterized constructor means the struct does not have a default constructor so you'd need special care to put it in an array and such. Adding a default constructor is left to you. I would advise making the member variables private and providing methods to set them so you can add error checking and preserve invariants like keeping the two gender variables in sync.
I added #include <string> because you should always include what you use and not depend on another file to include it since that may not always be the case and removed using namespace std; because it's a bad habit. Read Why is "using namespace std;" considered bad practice? for more information.
#include <iostream>
#include <string>
enum class Gender
{
Male,
Female
};
struct Person
{
std::string name;
bool genderBoolean;
std::string gender;
std::string age;
std::string nationality;
Person(const std::string& name, Gender genderType,
const std::string& age, const std::string& nationality)
: name(name)
, genderBoolean(genderType == Gender::Male)
// A way to initialize the gender
, gender(genderType == Gender::Male ? "male" : "female")
, age(age)
, nationality(nationality)
{
// A way to assign the gender
// If you use this remove the one above
// You don't need both
//if (genderBoolean)
//{
// gender = "male";
//}
//else
//{
// gender = "female";
//}
}
void setGender(Gender genderType)
{
// A way to change the gender
// Would be best if the member variables were private
// But would not prevent the class from making them mismatch
// by modifying the gender variable directly
if (genderType == Gender::Male)
{
gender = "male";
}
else
{
gender = "female";
}
}
friend std::ostream& operator<<(std::ostream& out, const Person& p);
};
std::ostream& operator<<(std::ostream& out, const Person& p)
{
out << "Name = " << p.name
<< ", Gender = " << p.gender
<< ", Age = " << p.age
<< ", Nationality = " << p.nationality
<< "\n";
return out;
}
int main()
{
Person person1("Mike", Gender::Male, "50", "American");
std::cout << person1;
person1.setGender(Gender::Female);
std::cout << person1;
return 0;
}
Demo
Output:
Name = Mike, Gender = male, Age = 50, Nationality = American
Name = Mike, Gender = female, Age = 50, Nationality = American
|
How to conditionally initialize a member of a struct?
|
I am beginning to learn C++ struct. After creating a struct named Person, I tried to declare a boolean variable named genderBoolean in the struct of Person, and a string variable named gender. I tried to use if-else statement for the following condition: if genderBoolean is true, then gender is male, but if genderBoolean is false, then gender is female. I tried to put the if-else statement outside of the struct, but the IDE says
Identifier "genderBoolean" is undefined
which causes another compilation error.
It seems that if-else statement cannot be used within struct in C++. I found out that adding a # before the if statement and adding #endif can solve the compilation error of "expected a declaration" in Microsoft Visual Code 2022, but the output of the program is:
"Name = Mike Gender = Age = 50 Nationality = American"
I expected its output to be :
"Name = Mike Gender = male Age = 50 Nationality = American"
My code also generates compilation message that says the variable genderBoolean is uninitialized, but it can run:
#include <iostream>
using namespace std;
int main() {
struct Person {
string name;
bool genderBoolean;
string gender;
string age;
string nationality;
#if(genderBoolean == true) {
gender = "male";
}
else if (genderBoolean == false) {
gender = "female";
}
#endif
};
Person person1;
person1.name = "Mike";
person1.genderBoolean = true;
person1.age = "50";
person1.nationality = "American";
cout << "Name = " << person1.name << " Gender = " << person1.gender <<
" Age = " << person1.age << " Nationality = " << person1.nationality <<
endl;
return 0;
}
I tried to put the if-else statement outside of the struct but it says identifier "genderBoolean" is undefined.
I expected its output to be :
"Name = Mike Gender = male Age = 50 Nationality = American"
What actually resulted :
"Name = Mike Gender = Age = 50 Nationality = American"
|
[
"Here are a few different ways to handle it using a constructor and a setter. Keep in mind that adding a parameterized constructor means the struct does not have a default constructor so you'd need special care to put it in an array and such. Adding a default constructor is left to you. I would advise making the member variables private and providing methods to set them so you can add error checking and preserve invariants like keeping the two gender variables in sync.\nI added #include <string> because you should always include what you use and not depend on another file to include it since that may not always be the case and removed using namespace std; because it's a bad habit. Read Why is \"using namespace std;\" considered bad practice? for more information.\n#include <iostream>\n#include <string>\n\nenum class Gender\n{\n Male,\n Female\n};\n\nstruct Person \n{\n std::string name;\n bool genderBoolean;\n std::string gender;\n std::string age;\n std::string nationality;\n\n Person(const std::string& name, Gender genderType, \n const std::string& age, const std::string& nationality)\n : name(name)\n , genderBoolean(genderType == Gender::Male)\n // A way to initialize the gender\n , gender(genderType == Gender::Male ? \"male\" : \"female\")\n , age(age)\n , nationality(nationality)\n {\n // A way to assign the gender\n // If you use this remove the one above\n // You don't need both\n //if (genderBoolean)\n //{\n // gender = \"male\";\n //}\n //else\n //{\n // gender = \"female\";\n //}\n }\n\n void setGender(Gender genderType)\n {\n // A way to change the gender\n // Would be best if the member variables were private\n // But would not prevent the class from making them mismatch\n // by modifying the gender variable directly\n if (genderType == Gender::Male)\n {\n gender = \"male\";\n }\n else\n {\n gender = \"female\";\n }\n }\n\n friend std::ostream& operator<<(std::ostream& out, const Person& p);\n};\n\nstd::ostream& operator<<(std::ostream& out, const Person& p)\n{\n out << \"Name = \" << p.name \n << \", Gender = \" << p.gender\n << \", Age = \" << p.age\n << \", Nationality = \" << p.nationality\n << \"\\n\";\n\n return out;\n}\n\nint main() \n{\n Person person1(\"Mike\", Gender::Male, \"50\", \"American\");\n std::cout << person1;\n person1.setGender(Gender::Female);\n std::cout << person1;\n\n return 0;\n}\n\nDemo\nOutput:\nName = Mike, Gender = male, Age = 50, Nationality = American\nName = Mike, Gender = female, Age = 50, Nationality = American\n\n"
] |
[
0
] |
[] |
[] |
[
"boolean",
"c++",
"if_statement",
"struct"
] |
stackoverflow_0074665520_boolean_c++_if_statement_struct.txt
|
Q:
Nodejs, TypeScript, ts-node-dev & top-level await
I have spent an hour now searching for a solution to a new error after needing top-level await. Everything else I have tried so far did not solve the error such as adding "type": "module" to the package.json file.
The message of the error is Cannot use import statement outside a module when starting the service.
If I revert the change "module": "ESNext", to "module": "commonjs",, it works fine (except the await keywords have to be removed and somehow refactored to work without await).
In addition, I use ts-node-dev to run the service which can be seen in the package.json file.
The new package I need is kafkajs.
node version: v14.9.0
TypeScript version: 4.0
package.json
{
"name": "",
"version": "1.0.0",
"description": "microservice",
"main": "src/index.ts",
"author": "",
"type": "module",
"license": "MIT",
"scripts": {
"dev": "NODE_ENV=development tsnd --respawn --files src/index.ts",
"prod": "NODE_ENV=production tsnd --respawn --transpile-only --files src/index.ts",
"test": "mocha --exit -r ts-node/register tests/**/*.spec.ts",
"eslint": "eslint src/**/*.ts"
},
tsconfig.json
{
"compilerOptions": {
"target": "ES2020",
"module": "ESNext",
"moduleResolution": "node",
"outDir": "dist",
"sourceMap": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true
},
"ts-node": {
"files": true,
"transpileOnly": true
},
"include": ["src/**/*.ts", "declariations/**.d.ts"],
"exclude": ["node_modules", ".vscode"]
}
A:
TL;DR: Don't use ECMAScript modules with ts-node or ts-node-dev (yet); just refactor the top-level await out
Today I tumbled down the same rabbit hole, starting with the innocuous error:
Top-level 'await' expressions are only allowed when the 'module' option is set to 'esnext' or 'system', and the 'target' option is set to 'es2017' or higher.
As a result, I felt inclined to edit my tsconfig.json and set module to esnext, which in turn forced me to set moduleResolution to node and finally add type: module to my package.json. What I failed to realize (and IMO they shouldn't suggest this in the error message-- you can just simply refactor the top-level await out), that this switches the module resolution strategy of NodeJS from CommonJS to ESM. This is actually a big deal for many reasons:
ESM support is still experimental in ts-node
Mixing CJS and ESM modules may lead to problems
There are open issues with ESM support in NodeJS itself
I feel that at this time (december 2020) the NodeJS ecosystem is still in transition from the classic CommonJS modules to the new ECMAScript modules. As a result other tech like ts-node or ts-node-dev are transitioning as well and support can be flaky. My advice is to stick with CommonJS until the dust has settled and these things "just work" out of the box.
A:
Update Node v18.12.0
You can now also use the built-in --watch flag from Node.
Assuming your entry file is src/index.ts:
node --watch --loader ts-node/esm --experimental-specifier-resolution node src
Original Answer
I know, the question is quite old already, but for people passing by this issue like I did earlier today:
I just managed to get it to work. Not with ts-node-dev directly, but with the combination of nodemon and ts-node.
You need to install nodemon and ts-node and then, assuming your entry file is src/index.ts, you can use this command:
nodemon --ext ts --loader ts-node/esm --experimental-specifier-resolution node src
(Tested with Node v16.13.0)
This was the key post for me to figure it out: https://github.com/TypeStrong/ts-node/issues/1007
|
Nodejs, TypeScript, ts-node-dev & top-level await
|
I have spent an hour now searching for a solution to a new error after needing top-level await. Everything else I have tried so far did not solve the error such as adding "type": "module" to the package.json file.
The message of the error is Cannot use import statement outside a module when starting the service.
If I revert the change "module": "ESNext", to "module": "commonjs",, it works fine (except the await keywords have to be removed and somehow refactored to work without await).
In addition, I use ts-node-dev to run the service which can be seen in the package.json file.
The new package I need is kafkajs.
node version: v14.9.0
TypeScript version: 4.0
package.json
{
"name": "",
"version": "1.0.0",
"description": "microservice",
"main": "src/index.ts",
"author": "",
"type": "module",
"license": "MIT",
"scripts": {
"dev": "NODE_ENV=development tsnd --respawn --files src/index.ts",
"prod": "NODE_ENV=production tsnd --respawn --transpile-only --files src/index.ts",
"test": "mocha --exit -r ts-node/register tests/**/*.spec.ts",
"eslint": "eslint src/**/*.ts"
},
tsconfig.json
{
"compilerOptions": {
"target": "ES2020",
"module": "ESNext",
"moduleResolution": "node",
"outDir": "dist",
"sourceMap": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true
},
"ts-node": {
"files": true,
"transpileOnly": true
},
"include": ["src/**/*.ts", "declariations/**.d.ts"],
"exclude": ["node_modules", ".vscode"]
}
|
[
"TL;DR: Don't use ECMAScript modules with ts-node or ts-node-dev (yet); just refactor the top-level await out\nToday I tumbled down the same rabbit hole, starting with the innocuous error:\nTop-level 'await' expressions are only allowed when the 'module' option is set to 'esnext' or 'system', and the 'target' option is set to 'es2017' or higher.\n\nAs a result, I felt inclined to edit my tsconfig.json and set module to esnext, which in turn forced me to set moduleResolution to node and finally add type: module to my package.json. What I failed to realize (and IMO they shouldn't suggest this in the error message-- you can just simply refactor the top-level await out), that this switches the module resolution strategy of NodeJS from CommonJS to ESM. This is actually a big deal for many reasons:\n\nESM support is still experimental in ts-node\nMixing CJS and ESM modules may lead to problems\nThere are open issues with ESM support in NodeJS itself\n\nI feel that at this time (december 2020) the NodeJS ecosystem is still in transition from the classic CommonJS modules to the new ECMAScript modules. As a result other tech like ts-node or ts-node-dev are transitioning as well and support can be flaky. My advice is to stick with CommonJS until the dust has settled and these things \"just work\" out of the box.\n",
"Update Node v18.12.0\nYou can now also use the built-in --watch flag from Node.\nAssuming your entry file is src/index.ts:\nnode --watch --loader ts-node/esm --experimental-specifier-resolution node src\n\nOriginal Answer\nI know, the question is quite old already, but for people passing by this issue like I did earlier today:\nI just managed to get it to work. Not with ts-node-dev directly, but with the combination of nodemon and ts-node.\nYou need to install nodemon and ts-node and then, assuming your entry file is src/index.ts, you can use this command:\nnodemon --ext ts --loader ts-node/esm --experimental-specifier-resolution node src\n\n(Tested with Node v16.13.0)\nThis was the key post for me to figure it out: https://github.com/TypeStrong/ts-node/issues/1007\n"
] |
[
71,
11
] |
[
"Know that there is already an accepted answer to this question, but I think that is outdated right now (as of Dec 2022). Still ts-node-esm support is marked experimental. You can easily set up the flow you want though.\nhttps://github.com/TypeStrong/ts-node#native-ecmascript-modules for the relevant section in ts-node and a code base example if needed: https://github.com/vishnup95/ts-node-top-level-await/tree/main.\n// tsconfig.json\n\n{\n\n \"extends\": \"ts-node/node16/tsconfig.json\",\n \"ts-node\": {\n \"esm\": true,\n ....\n \"compilerOptions\": {\n \"module\": \"ESNext\",\n \"target\": \"ES2017\"\n }\n },\n \"compilerOptions\": {\n // Just to make the lint shut up!\n \"module\": \"ESNext\",\n \"target\": \"ES2017\"\n }\n}\n\nDon't forget \"type\": \"module\" in package.json\nPlease consider changing the accepted answer/updating it.\n"
] |
[
-1
] |
[
"async_await",
"node.js",
"top_level_await",
"typescript"
] |
stackoverflow_0064610476_async_await_node.js_top_level_await_typescript.txt
|
Q:
Search Data not working Angular NodeJS API
i am created the search part using angular and node js. i have tested through the postman it is working fine. when connect with frond end anqular application is it not working error displayed
Failed to load resource: the server responded with a status of 404 (Not Found)
what i tried so far i attached below please check.
i tried on the url http://localhost:9001/user/findOne?first_name=kobinath
this is working well on postman but tested through the anqular didn't work. i attached the code what i tried so far.
employee.component.ts
search()
{
let name= {
"first_name" : this.first_name
};
this.http.post("http://localhost:9001/user/findOne",name).subscribe((resultData: any)=>
{
console.log(resultData);
});
}
employee.component.html
<form>
<div class="form-group">
<label>First Name</label>
<input type="text" [(ngModel)]="first_name" [ngModelOptions]="{standalone: true}" class="form-control" id="name" placeholder="Enter Name">
</div>
<button type="submit" class="btn btn-primary mt-4" (click)="search()" >Search</button>
</form>
</div>
A:
What I noticed: With Postman you send first_name as a query parameter, but in your Angular-code you attach it to the request-body.
To achieve the equivalent of what you do in Postman, you could use the following code:
search(firstName: string) {
const params = new HttpParams().set('first_name', firstName);
const body = {
first_name : firstName
};
this.http.post("http://localhost:9001/user/findOne", body, { params: params })
.subscribe((resultData: any)=>
{
console.log(resultData);
});
}
Btw: Why don't you use GET instead of POST?
|
Search Data not working Angular NodeJS API
|
i am created the search part using angular and node js. i have tested through the postman it is working fine. when connect with frond end anqular application is it not working error displayed
Failed to load resource: the server responded with a status of 404 (Not Found)
what i tried so far i attached below please check.
i tried on the url http://localhost:9001/user/findOne?first_name=kobinath
this is working well on postman but tested through the anqular didn't work. i attached the code what i tried so far.
employee.component.ts
search()
{
let name= {
"first_name" : this.first_name
};
this.http.post("http://localhost:9001/user/findOne",name).subscribe((resultData: any)=>
{
console.log(resultData);
});
}
employee.component.html
<form>
<div class="form-group">
<label>First Name</label>
<input type="text" [(ngModel)]="first_name" [ngModelOptions]="{standalone: true}" class="form-control" id="name" placeholder="Enter Name">
</div>
<button type="submit" class="btn btn-primary mt-4" (click)="search()" >Search</button>
</form>
</div>
|
[
"What I noticed: With Postman you send first_name as a query parameter, but in your Angular-code you attach it to the request-body.\nTo achieve the equivalent of what you do in Postman, you could use the following code:\nsearch(firstName: string) {\n const params = new HttpParams().set('first_name', firstName);\n const body = {\n first_name : firstName\n };\n\n this.http.post(\"http://localhost:9001/user/findOne\", body, { params: params })\n .subscribe((resultData: any)=>\n {\n console.log(resultData); \n });\n}\n\nBtw: Why don't you use GET instead of POST?\n"
] |
[
0
] |
[] |
[] |
[
"angular",
"node.js"
] |
stackoverflow_0074667349_angular_node.js.txt
|
Q:
How to change color of text in text area using button in react function
``
hi everyone, I want to take color as input and then change the color of text according to it but it's not working can anybody help me.
import React, {useState} from 'react'
export default function Textform(props) {
//this is function
const newColor =()=>{
const x = document.getElementById("mybox")
let newc =color;
if(x.style.color==="black"){
x.style.color = setcolor(newc)
}
else{
x.style.color = "black"
}
}
const changeColor =(event)=>{
setcolor(event.target.value);
}
const onChange =(event)=>{
setText(event.target.value);
}
const [text, setText] = useState("");
const [color, setcolor] = useState("")
return (
<>
//text area input
<div className="mb-3">
<textarea className="form-control" value={text} onChange={onChange} placeholder="Enter text " name="" id="mybox" rows="8"></textarea>
</div>
//our color choice input
<div className="mb-3">
<textarea className="form-control" value={color} onChange={changeColor} placeholder="Enter your color choice" name="" id="mybox" rows="3"></textarea>
</div>
//this is my button
<button className="btn btn-primary mx-1" onClick={newColor}> Change Color</button>
</>
)
}
I tried to create a text Area which take text as input and another text Area which take color as input and then created a button. when we press the button, it will change the color of text as per our choice.
but I am going wrong in implementing this logic.
A:
You can easily do this with hooks but if you insist in this way there are a some issues with your code.
First, you are using the setcolor function to set the color state value, but you are not using it to set the color of the text.
You are using the
x.style.color = setcolor(newc)
line, which is setting the color property of the element to the return value of the setcolor function, which is undefined.
You should be using the setcolor function to set the color of the text like this:
x.style.color = color
Also you are using the const keyword to define the x variable, which is a reference to the element with the ID mybox.
x variable cannot be reassigned, but you are trying to reassign it in the else block of your newColor function.
Instead, you should use the let keyword to define the x variable so that it can be reassigned.
import React, {useState} from 'react'
export default function Textform(props) {
const newColor = () => {
let x = document.getElementById("mybox")
let newc = color;
if (x.style.color === "black") {
x.style.color = color
} else {
x.style.color = "black"
}
}
const changeColor = (event) => {
setcolor(event.target.value);
}
const onChange = (event) => {
setText(event.target.value);
}
const [text, setText] = useState("");
const [color, setcolor] = useState("")
return (
<>
<div className="mb-3">
<textarea className="form-control" value={text} onChange={onChange} placeholder="Enter text " name="" id="mybox" rows="8"></textarea>
</div>
<div className="mb-3">
<textarea className="form-control" value={color} onChange={changeColor} placeholder="Enter your color choice" name="" id="mybox" rows="3"></textarea>
</div>
<button className="btn btn-primary mx-1" onClick={newColor}>Change Color</button>
</>
)
}
I removed the const keyword before the x variable in the newColor function and replaced it with the let keyword. This allows the x variable to be reassigned in the else block.
A:
You can make use of style tag and color property to style and a state to check if button is clicked
sample e.g.
const {useState} = React;
function App() {
const [text, setText] = useState('');
const [color, setcolor] = useState('');
const [clicked, setClicked] = useState(false);
//this is function
const newColor = () => {
setClicked(!clicked);
};
const changeColor = (event) => {
setcolor(event.target.value);
};
const onChange = (event) => {
setText(event.target.value);
};
return (
<React.Fragment>
//text area input
<div className="mb-3">
<textarea
className="form-control"
value={text}
onChange={onChange}
placeholder="Enter text "
name=""
id="mybox"
style={{ color: clicked ? color : 'black' }}
rows={8}
></textarea>
</div>
//our color choice input
<div className="mb-3">
<textarea
className="form-control"
value={color}
onChange={changeColor}
placeholder="Enter your color choice"
name=""
id="mybox"
rows={3}
></textarea>
</div>
//this is my button
<button className="btn btn-primary mx-1" onClick={newColor}>
{' '}
{clicked ? `Change color to black` : `Change Color to ${color}`}
</button>
</React.Fragment>
);
}
ReactDOM.createRoot(
document.getElementById("root")
).render(
<App/>
);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>
A:
Ideally you shouldn't be using native DOM methods interrogate/update the DOM. Instead use a separate state. When the button is clicked transfer the text from the colorText state to the activeColor state, and use that value in the textarea's style attribute.
const { useState } = React;
function Example() {
// Set up the states
const [ colorText, setColorText ] = useState('');
const [ activeColor, setActiveColor ] = useState('');
const [ text, setText ] = useState('Example text');
// One function to update the `colorText` state
function handleColorText(e) {
setColorText(e.target.value);
}
// One function to update the text from the
// textarea
function handleText(e) {
setText(e.target.value);
}
// One function to take the value in the `colorText`
// state, and apply it to the `activeColor` state
function handleClick() {
setActiveColor(colorText);
setColorText('');
}
// The textarea now has a style attribute. It's
// value is the value of `activeColor`.
return (
<div>
<input
type="text"
name="color"
value={colorText}
onChange={handleColorText}
/>
<button onClick={handleClick}>
Change color
</button>
<textarea
style={{ color: activeColor }}
name="text"
value={text}
onChange={handleText}
></textarea>
</div>
);
}
ReactDOM.render(
<Example />,
document.getElementById('react')
);
textarea { display: block; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>
|
How to change color of text in text area using button in react function
|
``
hi everyone, I want to take color as input and then change the color of text according to it but it's not working can anybody help me.
import React, {useState} from 'react'
export default function Textform(props) {
//this is function
const newColor =()=>{
const x = document.getElementById("mybox")
let newc =color;
if(x.style.color==="black"){
x.style.color = setcolor(newc)
}
else{
x.style.color = "black"
}
}
const changeColor =(event)=>{
setcolor(event.target.value);
}
const onChange =(event)=>{
setText(event.target.value);
}
const [text, setText] = useState("");
const [color, setcolor] = useState("")
return (
<>
//text area input
<div className="mb-3">
<textarea className="form-control" value={text} onChange={onChange} placeholder="Enter text " name="" id="mybox" rows="8"></textarea>
</div>
//our color choice input
<div className="mb-3">
<textarea className="form-control" value={color} onChange={changeColor} placeholder="Enter your color choice" name="" id="mybox" rows="3"></textarea>
</div>
//this is my button
<button className="btn btn-primary mx-1" onClick={newColor}> Change Color</button>
</>
)
}
I tried to create a text Area which take text as input and another text Area which take color as input and then created a button. when we press the button, it will change the color of text as per our choice.
but I am going wrong in implementing this logic.
|
[
"You can easily do this with hooks but if you insist in this way there are a some issues with your code.\nFirst, you are using the setcolor function to set the color state value, but you are not using it to set the color of the text.\nYou are using the\n\nx.style.color = setcolor(newc)\n\nline, which is setting the color property of the element to the return value of the setcolor function, which is undefined.\nYou should be using the setcolor function to set the color of the text like this:\n\nx.style.color = color\n\nAlso you are using the const keyword to define the x variable, which is a reference to the element with the ID mybox.\nx variable cannot be reassigned, but you are trying to reassign it in the else block of your newColor function.\nInstead, you should use the let keyword to define the x variable so that it can be reassigned.\nimport React, {useState} from 'react'\n\nexport default function Textform(props) {\n const newColor = () => {\n let x = document.getElementById(\"mybox\")\n let newc = color;\n if (x.style.color === \"black\") {\n x.style.color = color\n } else {\n x.style.color = \"black\"\n }\n }\n\n const changeColor = (event) => {\n setcolor(event.target.value);\n }\n\n const onChange = (event) => {\n setText(event.target.value);\n }\n\n const [text, setText] = useState(\"\");\n const [color, setcolor] = useState(\"\")\n\n return (\n <>\n <div className=\"mb-3\">\n <textarea className=\"form-control\" value={text} onChange={onChange} placeholder=\"Enter text \" name=\"\" id=\"mybox\" rows=\"8\"></textarea>\n </div>\n\n <div className=\"mb-3\">\n <textarea className=\"form-control\" value={color} onChange={changeColor} placeholder=\"Enter your color choice\" name=\"\" id=\"mybox\" rows=\"3\"></textarea>\n </div>\n\n <button className=\"btn btn-primary mx-1\" onClick={newColor}>Change Color</button>\n </>\n )\n}\n\nI removed the const keyword before the x variable in the newColor function and replaced it with the let keyword. This allows the x variable to be reassigned in the else block.\n",
"You can make use of style tag and color property to style and a state to check if button is clicked\nsample e.g.\n\n\nconst {useState} = React;\n\n\nfunction App() {\n const [text, setText] = useState('');\n const [color, setcolor] = useState('');\n const [clicked, setClicked] = useState(false);\n //this is function\n const newColor = () => {\n setClicked(!clicked);\n };\n\n const changeColor = (event) => {\n setcolor(event.target.value);\n };\n\n const onChange = (event) => {\n setText(event.target.value);\n };\n\n return (\n <React.Fragment>\n //text area input\n <div className=\"mb-3\">\n <textarea\n className=\"form-control\"\n value={text}\n onChange={onChange}\n placeholder=\"Enter text \"\n name=\"\"\n id=\"mybox\"\n style={{ color: clicked ? color : 'black' }}\n rows={8}\n ></textarea>\n </div>\n //our color choice input\n <div className=\"mb-3\">\n <textarea\n className=\"form-control\"\n value={color}\n onChange={changeColor}\n placeholder=\"Enter your color choice\"\n name=\"\"\n id=\"mybox\"\n rows={3}\n ></textarea>\n </div>\n //this is my button\n <button className=\"btn btn-primary mx-1\" onClick={newColor}>\n {' '}\n {clicked ? `Change color to black` : `Change Color to ${color}`}\n </button>\n </React.Fragment>\n );\n}\n\nReactDOM.createRoot(\n document.getElementById(\"root\")\n).render(\n <App/>\n);\n<div id=\"root\"></div>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js\"></script>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js\"></script>\n\n\n\n",
"Ideally you shouldn't be using native DOM methods interrogate/update the DOM. Instead use a separate state. When the button is clicked transfer the text from the colorText state to the activeColor state, and use that value in the textarea's style attribute.\n\n\nconst { useState } = React;\n\nfunction Example() {\n\n // Set up the states\n const [ colorText, setColorText ] = useState('');\n const [ activeColor, setActiveColor ] = useState('');\n const [ text, setText ] = useState('Example text');\n\n // One function to update the `colorText` state\n function handleColorText(e) {\n setColorText(e.target.value);\n }\n\n // One function to update the text from the\n // textarea\n function handleText(e) {\n setText(e.target.value);\n }\n\n // One function to take the value in the `colorText`\n // state, and apply it to the `activeColor` state\n function handleClick() {\n setActiveColor(colorText);\n setColorText('');\n }\n\n // The textarea now has a style attribute. It's\n // value is the value of `activeColor`.\n return (\n <div>\n <input\n type=\"text\"\n name=\"color\"\n value={colorText}\n onChange={handleColorText}\n />\n <button onClick={handleClick}>\n Change color\n </button>\n <textarea\n style={{ color: activeColor }}\n name=\"text\"\n value={text}\n onChange={handleText}\n ></textarea>\n </div>\n );\n\n}\n\nReactDOM.render(\n <Example />,\n document.getElementById('react')\n);\ntextarea { display: block; }\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js\"></script>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js\"></script>\n<div id=\"react\"></div>\n\n\n\n"
] |
[
0,
0,
0
] |
[] |
[] |
[
"html",
"javascript",
"react_functional_component",
"reactjs"
] |
stackoverflow_0074669548_html_javascript_react_functional_component_reactjs.txt
|
Q:
Vuejs Jwt Token Authentication
I want to use Jwt token in my project. So I'm using this function after every api request;
function handleResponse(response) {
return response.text().then(text => {
if (response.status == 401) {
var user = JSON.parse(localStorage.getItem('user'))
if (user && user.tokens) {
tokenService.refresh()
console.log(response);
return Api(response.url)
}
}
const data = text && JSON.parse(text);
return data;
});
}
Token service is refreshing successfully but after refresh I want to send last request again. I can get url but I can't get sended body credentials. How can I do that?
A:
If you want to send the same request again after you refresh the token, you can store the request details (e.g., URL, method, body, headers) in a variable before you refresh the token, and then use that information to make the request again after the token has been refreshed.
Here's an example of how you could do this:
function handleResponse(response) {
return response.text().then(text => {
if (response.status == 401) {
var user = JSON.parse(localStorage.getItem('user'))
if (user && user.tokens) {
// Store the request details in a variable.
const requestDetails = {
url: response.url,
method: response.method,
body: response.body,
headers: response.headers,
};
tokenService.refresh()
.then(() => {
// Make the request again using the stored request details.
return Api(requestDetails.url, {
method: requestDetails.method,
body: requestDetails.body,
headers: requestDetails.headers,
});
});
}
}
const data = text && JSON.parse(text);
return data;
});
}
In the example above, after the token is refreshed, the request is made again using the same details as the original request. This will ensure that the request is sent with the updated token.
|
Vuejs Jwt Token Authentication
|
I want to use Jwt token in my project. So I'm using this function after every api request;
function handleResponse(response) {
return response.text().then(text => {
if (response.status == 401) {
var user = JSON.parse(localStorage.getItem('user'))
if (user && user.tokens) {
tokenService.refresh()
console.log(response);
return Api(response.url)
}
}
const data = text && JSON.parse(text);
return data;
});
}
Token service is refreshing successfully but after refresh I want to send last request again. I can get url but I can't get sended body credentials. How can I do that?
|
[
"If you want to send the same request again after you refresh the token, you can store the request details (e.g., URL, method, body, headers) in a variable before you refresh the token, and then use that information to make the request again after the token has been refreshed.\nHere's an example of how you could do this:\nfunction handleResponse(response) {\n return response.text().then(text => {\n if (response.status == 401) {\n var user = JSON.parse(localStorage.getItem('user'))\n if (user && user.tokens) {\n // Store the request details in a variable.\n const requestDetails = {\n url: response.url,\n method: response.method,\n body: response.body,\n headers: response.headers,\n };\n\n tokenService.refresh()\n .then(() => {\n // Make the request again using the stored request details.\n return Api(requestDetails.url, {\n method: requestDetails.method,\n body: requestDetails.body,\n headers: requestDetails.headers,\n });\n });\n }\n }\n const data = text && JSON.parse(text);\n return data;\n });\n}\n\nIn the example above, after the token is refreshed, the request is made again using the same details as the original request. This will ensure that the request is sent with the updated token.\n"
] |
[
1
] |
[] |
[] |
[
"jwt",
"vue.js"
] |
stackoverflow_0074669842_jwt_vue.js.txt
|
Q:
In webView leads to crash and UI unresponsiveness
I have added a WebView to load HTML and the baseUrl method. But it leads to crashing the app and showing a warning
This method should not be called on the main thread as it may lead to
UI unresponsiveness.
//load HTML
let htmlPath = Bundle.main.path(forResource: "index", ofType: "html")
let folderPath = Bundle.main.bundlePath
let baseUrl = URL(fileURLWithPath: folderPath, isDirectory: true)
do {
let htmlString = try NSString(contentsOfFile: htmlPath!, encoding: String.Encoding.utf8.rawValue)
self.webView.loadHTMLString(htmlString as String, baseURL: URL(string: newBaseURL))
} catch {
// catch error
print(error.localizedDescription)
}
I have called this piece of code in viewDidLoad(). Also it has been added in dispatch queue. Any help is much appreciated.
A:
Call loadHTMLString from the main thread.
DispatchQueue.main.async {
self.webView.loadHTMLString(htmlString as String, baseURL: URL(string: newBaseURL))
}
A:
It looks like you are calling the loadHTMLString() method on the main thread, which can lead to UI unresponsiveness. To avoid this, you should call this method on a background thread.
One way to do this is to use a DispatchQueue to run the code on a background thread. Here is an example:
let htmlPath = Bundle.main.path(forResource: "index", ofType: "html")
let folderPath = Bundle.main.bundlePath
let baseUrl = URL(fileURLWithPath: folderPath, isDirectory: true)
DispatchQueue.global(qos: .background).async {
do {
let htmlString = try NSString(contentsOfFile: htmlPath!, encoding: String.Encoding.utf8.rawValue)
DispatchQueue.main.async {
self.webView.loadHTMLString(htmlString as String, baseURL: URL(string: newBaseURL))
}
} catch {
// catch error
print(error.localizedDescription)
}
}
In this example, the loadHTMLString() method is called on the main thread using DispatchQueue.main.async, which ensures that the UI is updated properly.
|
In webView leads to crash and UI unresponsiveness
|
I have added a WebView to load HTML and the baseUrl method. But it leads to crashing the app and showing a warning
This method should not be called on the main thread as it may lead to
UI unresponsiveness.
//load HTML
let htmlPath = Bundle.main.path(forResource: "index", ofType: "html")
let folderPath = Bundle.main.bundlePath
let baseUrl = URL(fileURLWithPath: folderPath, isDirectory: true)
do {
let htmlString = try NSString(contentsOfFile: htmlPath!, encoding: String.Encoding.utf8.rawValue)
self.webView.loadHTMLString(htmlString as String, baseURL: URL(string: newBaseURL))
} catch {
// catch error
print(error.localizedDescription)
}
I have called this piece of code in viewDidLoad(). Also it has been added in dispatch queue. Any help is much appreciated.
|
[
"Call loadHTMLString from the main thread.\nDispatchQueue.main.async {\n self.webView.loadHTMLString(htmlString as String, baseURL: URL(string: newBaseURL))\n\n}\n\n",
"It looks like you are calling the loadHTMLString() method on the main thread, which can lead to UI unresponsiveness. To avoid this, you should call this method on a background thread.\nOne way to do this is to use a DispatchQueue to run the code on a background thread. Here is an example:\nlet htmlPath = Bundle.main.path(forResource: \"index\", ofType: \"html\")\nlet folderPath = Bundle.main.bundlePath\nlet baseUrl = URL(fileURLWithPath: folderPath, isDirectory: true)\n\nDispatchQueue.global(qos: .background).async {\n do {\n let htmlString = try NSString(contentsOfFile: htmlPath!, encoding: String.Encoding.utf8.rawValue)\n DispatchQueue.main.async {\n self.webView.loadHTMLString(htmlString as String, baseURL: URL(string: newBaseURL))\n }\n } catch {\n // catch error\n print(error.localizedDescription)\n }\n}\n\nIn this example, the loadHTMLString() method is called on the main thread using DispatchQueue.main.async, which ensures that the UI is updated properly.\n"
] |
[
0,
0
] |
[] |
[] |
[
"ios",
"swift",
"webview",
"wkwebview",
"xcode"
] |
stackoverflow_0074120763_ios_swift_webview_wkwebview_xcode.txt
|
Q:
generate a number sequence, and then sort the sequence
I am supposed to write a program that processes a sequence of 100 positive numbers. The program should have 3 different functions, which could be chosen from a menu.
Generate a number sequence with a random generator and print the numbers on the screen. The numbers generated should be in the range 0 ≤ n ≤ 900
I have to sort the sequence with bubble sort and then the numbers must be printed and I cannot use built-in sorting functions, such as qsort.
Quit program.
The 1 and 2 must be in own functions.
Lasly every time the program prints out the number, it should be printed as a table with ten rows and ten columns. Choice two can not be made unless choice one has been chosen.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 100
#define N 10
#define INVALID 0
#define VALID 1
void randomNum() {
//random number gen
int num[SIZE] = {0};
int i = 0;
srand(time(NULL));
for(i = 0; i < SIZE; i++) {
num[i] = rand() % 901;
}
for(i = 0; i < SIZE; i++) {
printf("%4d", num[i]);
if(i % 10 == 9)
printf("\n");
}
}
void sort() {
//sort of the generated number sequence
int num[SIZE] = {0};
int i = 0;
int j = 0;
int temp = 0;
for (int i = 0 ; i < SIZE; i++)
{
for (int j = 0; j < SIZE - 1; j++)
{
if (num[j] > num[j+1])
{
temp = num[j];
num[j] = num[j+1];
num[j+1] = temp;
}
}
}
for(i = 0; i < SIZE; i++) {
printf("%4d", num[i]);
if(i % 10 == 9)
printf("\n");
}
}
int main() {
randomNum();
printf("\n");
sort();
return 0;
}
I have figured out the solutions for how to generate a sequene and sort it and it works correct when all the code are in main() , however, when I put in in own functions above the main() it does not work. I'm stuck and don't know how to move forward. When i run the program it generates a random sequence but then the sorting function just prints out 100 zeros.
A:
I fixed up your code, to try to do mostly the same thing in a very straight forward fashion.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 100
void fill_random_array( int array[const], size_t sz )
{
srand(time(NULL));
for(int i = 0; i < sz; ++i)
{
array[i] = rand() % 901;
printf("%3d%s", array[i], (i+1)%16? " ": "\n" );
}
}
void sort( int array[const], size_t sz )
{
for (int i = 0 ; i < SIZE; i++)
{
for (int j = 0; j < SIZE - 1; j++)
{
if (array[j] > array[j+1])
{
int temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}
}
int main()
{
int data[SIZE];
fill_random_array( data, SIZE );
printf("\n\nResult:\n");
sort( data, SIZE );
for(int i = 0; i < SIZE; ++i)
{
printf("%3d%s", data[i], (i+1)%16? " ": "\n" );
}
return 0;
}
Example Output:
Success #stdin #stdout 0s 5536KB
757 872 260 877 827 747 839 279 468 311 361 584 382 364 528 24
848 32 307 479 594 59 172 54 811 530 550 451 618 893 39 474
261 597 450 187 740 686 467 307 393 224 288 775 588 816 195 832
848 502 707 838 859 879 892 769 806 839 616 523 831 656 97 191
352 844 676 488 629 539 796 121 763 183 896 747 395 190 74 639
89 781 873 47 759 865 212 60 199 828 584 129 880 77 618 628
20 690 216 650
Result:
20 24 32 39 47 54 59 60 74 77 89 97 121 129 172 183
187 190 191 195 199 212 216 224 260 261 279 288 307 307 311 352
361 364 382 393 395 450 451 467 468 474 479 488 502 523 528 530
539 550 584 584 588 594 597 616 618 618 628 629 639 650 656 676
686 690 707 740 747 747 757 759 763 769 775 781 796 806 811 816
827 828 831 832 838 839 839 844 848 848 859 865 872 873 877 879
880 892 893 896
A:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 100
#define N 10
void fill_random_array( int array[SIZE], size_t size )
{
int i= 0;
srand(time(NULL));
for(i = 0; i < SIZE; ++i)
{
array[i] = rand() % 901;
}
for(i = 0; i < SIZE; i++) {
printf("%4d", array[i]);
if(i % 10 == 9)
printf("\n");
}
}
void sort( int array[SIZE], size_t size )
{
int i = 0;
int j = 0;
for (i = 0 ; i < SIZE; i++)
{
for (j = 0; j < SIZE - 1; j++)
{
if (array[j] > array[j+1])
{
int temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}
for(i = 0; i < SIZE; i++) {
printf("%4d", array[i]);
if(i % 10 == 9)
printf("\n");
}
}
void calculations(int array[SIZE], size_t size) {
//max och min
int i = 0;
int max = 0;
int min = 900;
int sum = 0;
double average = 0;
double median = 0;
for(i = 0; i < SIZE; i++){
if(array[i] > max) {
max = array[i];
}
if(array[i] < min) {
min = array[i];
}
}
//average
for(i = 0; i < SIZE; i++) {
sum += array[i];
}
average = sum / SIZE;
//median
median = (array[49] + array[50])/2;
printf("Max: %d Min: %d Average: %f Median: %f\n", max, min, average, median);
}
void binsearch(int array[SIZE], size_t size) {
//binary search
int i = 0;
int pos = 0; //position
int start = 0; //start position i vector
int end = 99; //end position i vector
int number = 0;
int flag;
int row = 0; //row
int col = 0; //column
printf("Enter number: \n");
scanf("%d", &number);
flag = 0;
while(start <= end) {
pos = (start + end)/2;
if(array[pos] == number){
row = (pos / N) + 1;
col = (pos % N) + 1;
printf("The number %d was found in position %d and row %d and column %d\n", number, pos, row, col);
flag = 1;
break;
}
else if(array[pos] < number)
start = pos + 1;
else if(array[pos] > number)
end = pos - 1;
break;
}
if(flag == 0)
printf("Number not found\n");
}
int main()
{
int data[SIZE];
fill_random_array( data, SIZE );
printf("\n");
sort( data, SIZE );
printf("\n");
calculations( data, SIZE);
printf("\n");
binsearch(data, SIZE);
return 0;
}
This is what my code looks like now. The program works okay now I think but when I run it, it generates a random number sequence, and sort it and then print out max min, average value and median. But when I enter a number for the binarysearch it says: number not found even though the number is in the sorted sequence, how come it does that? And how do I fix it?
|
generate a number sequence, and then sort the sequence
|
I am supposed to write a program that processes a sequence of 100 positive numbers. The program should have 3 different functions, which could be chosen from a menu.
Generate a number sequence with a random generator and print the numbers on the screen. The numbers generated should be in the range 0 ≤ n ≤ 900
I have to sort the sequence with bubble sort and then the numbers must be printed and I cannot use built-in sorting functions, such as qsort.
Quit program.
The 1 and 2 must be in own functions.
Lasly every time the program prints out the number, it should be printed as a table with ten rows and ten columns. Choice two can not be made unless choice one has been chosen.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 100
#define N 10
#define INVALID 0
#define VALID 1
void randomNum() {
//random number gen
int num[SIZE] = {0};
int i = 0;
srand(time(NULL));
for(i = 0; i < SIZE; i++) {
num[i] = rand() % 901;
}
for(i = 0; i < SIZE; i++) {
printf("%4d", num[i]);
if(i % 10 == 9)
printf("\n");
}
}
void sort() {
//sort of the generated number sequence
int num[SIZE] = {0};
int i = 0;
int j = 0;
int temp = 0;
for (int i = 0 ; i < SIZE; i++)
{
for (int j = 0; j < SIZE - 1; j++)
{
if (num[j] > num[j+1])
{
temp = num[j];
num[j] = num[j+1];
num[j+1] = temp;
}
}
}
for(i = 0; i < SIZE; i++) {
printf("%4d", num[i]);
if(i % 10 == 9)
printf("\n");
}
}
int main() {
randomNum();
printf("\n");
sort();
return 0;
}
I have figured out the solutions for how to generate a sequene and sort it and it works correct when all the code are in main() , however, when I put in in own functions above the main() it does not work. I'm stuck and don't know how to move forward. When i run the program it generates a random sequence but then the sorting function just prints out 100 zeros.
|
[
"I fixed up your code, to try to do mostly the same thing in a very straight forward fashion.\n#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n#include <time.h>\n\n#define SIZE 100\n\nvoid fill_random_array( int array[const], size_t sz )\n{\n srand(time(NULL)); \n for(int i = 0; i < sz; ++i)\n {\n array[i] = rand() % 901;\n printf(\"%3d%s\", array[i], (i+1)%16? \" \": \"\\n\" );\n } \n}\n\nvoid sort( int array[const], size_t sz )\n{\n for (int i = 0 ; i < SIZE; i++)\n {\n for (int j = 0; j < SIZE - 1; j++)\n {\n if (array[j] > array[j+1]) \n {\n int temp = array[j];\n array[j] = array[j+1];\n array[j+1] = temp;\n }\n }\n }\n}\n\n\nint main()\n{\n int data[SIZE];\n fill_random_array( data, SIZE );\n printf(\"\\n\\nResult:\\n\");\n sort( data, SIZE );\n \n for(int i = 0; i < SIZE; ++i)\n {\n printf(\"%3d%s\", data[i], (i+1)%16? \" \": \"\\n\" );\n } \n\n return 0; \n}\n\nExample Output:\nSuccess #stdin #stdout 0s 5536KB\n757 872 260 877 827 747 839 279 468 311 361 584 382 364 528 24\n848 32 307 479 594 59 172 54 811 530 550 451 618 893 39 474\n261 597 450 187 740 686 467 307 393 224 288 775 588 816 195 832\n848 502 707 838 859 879 892 769 806 839 616 523 831 656 97 191\n352 844 676 488 629 539 796 121 763 183 896 747 395 190 74 639\n 89 781 873 47 759 865 212 60 199 828 584 129 880 77 618 628\n 20 690 216 650 \n\nResult:\n 20 24 32 39 47 54 59 60 74 77 89 97 121 129 172 183\n187 190 191 195 199 212 216 224 260 261 279 288 307 307 311 352\n361 364 382 393 395 450 451 467 468 474 479 488 502 523 528 530\n539 550 584 584 588 594 597 616 618 618 628 629 639 650 656 676\n686 690 707 740 747 747 757 759 763 769 775 781 796 806 811 816\n827 828 831 832 838 839 839 844 848 848 859 865 872 873 877 879\n880 892 893 896 \n\n",
"#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n#include <time.h>\n\n#define SIZE 100\n#define N 10\n\nvoid fill_random_array( int array[SIZE], size_t size )\n{\nint i= 0;\nsrand(time(NULL)); \nfor(i = 0; i < SIZE; ++i)\n{\n array[i] = rand() % 901; \n} \nfor(i = 0; i < SIZE; i++) {\n printf(\"%4d\", array[i]);\n if(i % 10 == 9)\n printf(\"\\n\");\n}\n}\n\nvoid sort( int array[SIZE], size_t size )\n{\nint i = 0;\nint j = 0;\nfor (i = 0 ; i < SIZE; i++)\n{\n for (j = 0; j < SIZE - 1; j++)\n {\n if (array[j] > array[j+1]) \n {\n int temp = array[j];\n array[j] = array[j+1];\n array[j+1] = temp;\n }\n }\n}\nfor(i = 0; i < SIZE; i++) {\n printf(\"%4d\", array[i]);\n if(i % 10 == 9)\n printf(\"\\n\");\n } \n}\n\nvoid calculations(int array[SIZE], size_t size) {\n//max och min\n\nint i = 0;\nint max = 0;\nint min = 900;\nint sum = 0;\ndouble average = 0;\ndouble median = 0;\nfor(i = 0; i < SIZE; i++){\n\n if(array[i] > max) {\n max = array[i]; \n }\n if(array[i] < min) {\n min = array[i];\n } \n} \n//average\nfor(i = 0; i < SIZE; i++) {\n sum += array[i];\n}\naverage = sum / SIZE;\n//median\nmedian = (array[49] + array[50])/2;\nprintf(\"Max: %d Min: %d Average: %f Median: %f\\n\", max, min, average, median); \n}\n\nvoid binsearch(int array[SIZE], size_t size) {\n//binary search\n\nint i = 0;\nint pos = 0; //position\nint start = 0; //start position i vector\nint end = 99; //end position i vector\nint number = 0;\nint flag;\nint row = 0; //row\nint col = 0; //column\nprintf(\"Enter number: \\n\");\nscanf(\"%d\", &number);\nflag = 0;\nwhile(start <= end) {\n \n pos = (start + end)/2;\n if(array[pos] == number){\n row = (pos / N) + 1;\n col = (pos % N) + 1;\n printf(\"The number %d was found in position %d and row %d and column %d\\n\", number, pos, row, col);\n \n flag = 1;\n break;\n }\n else if(array[pos] < number)\n start = pos + 1;\n else if(array[pos] > number)\n end = pos - 1;\n \n break;\n}\n if(flag == 0)\n printf(\"Number not found\\n\"); \n} \n\nint main()\n{\nint data[SIZE];\nfill_random_array( data, SIZE );\nprintf(\"\\n\");\nsort( data, SIZE );\nprintf(\"\\n\");\ncalculations( data, SIZE);\nprintf(\"\\n\");\nbinsearch(data, SIZE);\n\nreturn 0; \n}\n\nThis is what my code looks like now. The program works okay now I think but when I run it, it generates a random number sequence, and sort it and then print out max min, average value and median. But when I enter a number for the binarysearch it says: number not found even though the number is in the sorted sequence, how come it does that? And how do I fix it?\n"
] |
[
0,
0
] |
[] |
[] |
[
"c"
] |
stackoverflow_0074660943_c.txt
|
Q:
How to limit number of concurrent tasks executing in a TaskGroup
The following function will download image data for assets passed into the function, transforming an array of PHAsset to an array of Data asynchronously and concurrently using a task group in Swift's async/await.
When called providing for example 100 PHAssets, all tasks are added to the group right away, and thus 100 data download requests are kicked off at the same time. At least in testing - it's my understanding the system can decide how to limit it.
How can you limit the number of concurrent tasks executing at a time in the group? For example in this scenario perhaps I'd like to only allow it to download a maximum of 10 photos at a time rather than all 100 (or 1000) that were provided.
func loadImageData(for assets: [PHAsset]) {
Task {
do {
let imagesData = try await withThrowingTaskGroup(of: (id: String, data: Data).self) { group in
for asset in assets {
group.addTask {
return (id: asset.localIdentifier, data: try await self.imageData(for: asset))
}
}
var dictionary = [String: Data]()
for try await item in group {
dictionary[item.id] = item.data
print("Downloaded \(dictionary.count) of \(assets.count)")
}
return assets.compactMap { dictionary[$0.localIdentifier] }
}
print("Done")
} catch {
print(error)
}
}
}
func imageData(for asset: PHAsset) async throws -> Data() {
//code here makes PHImageManager.requestImageDataAndOrientation play nicely with async/await
}
A:
I don't think there is wayt to limit it on TaskGroup. But for my CLI apps, I needed to limit number of simultaneously executed task, so while app runs in background, I still could work with my mac. So I wrtoe pool drainer
Usage:
let pool = AsyncOperationsPool<Int>(maxConcurrentOperationCount: 5)
for i in 0..<1024 {
pool.add { /* some heavy async task */ }
}
for try await i in pool {
// process result
}
|
How to limit number of concurrent tasks executing in a TaskGroup
|
The following function will download image data for assets passed into the function, transforming an array of PHAsset to an array of Data asynchronously and concurrently using a task group in Swift's async/await.
When called providing for example 100 PHAssets, all tasks are added to the group right away, and thus 100 data download requests are kicked off at the same time. At least in testing - it's my understanding the system can decide how to limit it.
How can you limit the number of concurrent tasks executing at a time in the group? For example in this scenario perhaps I'd like to only allow it to download a maximum of 10 photos at a time rather than all 100 (or 1000) that were provided.
func loadImageData(for assets: [PHAsset]) {
Task {
do {
let imagesData = try await withThrowingTaskGroup(of: (id: String, data: Data).self) { group in
for asset in assets {
group.addTask {
return (id: asset.localIdentifier, data: try await self.imageData(for: asset))
}
}
var dictionary = [String: Data]()
for try await item in group {
dictionary[item.id] = item.data
print("Downloaded \(dictionary.count) of \(assets.count)")
}
return assets.compactMap { dictionary[$0.localIdentifier] }
}
print("Done")
} catch {
print(error)
}
}
}
func imageData(for asset: PHAsset) async throws -> Data() {
//code here makes PHImageManager.requestImageDataAndOrientation play nicely with async/await
}
|
[
"I don't think there is wayt to limit it on TaskGroup. But for my CLI apps, I needed to limit number of simultaneously executed task, so while app runs in background, I still could work with my mac. So I wrtoe pool drainer\nUsage:\nlet pool = AsyncOperationsPool<Int>(maxConcurrentOperationCount: 5)\nfor i in 0..<1024 {\n pool.add { /* some heavy async task */ }\n}\n\nfor try await i in pool {\n // process result\n}\n\n"
] |
[
0
] |
[] |
[] |
[
"async_await",
"ios",
"swift"
] |
stackoverflow_0072890856_async_await_ios_swift.txt
|
Q:
Failed to resolve import "react-dom/client" from "src\main.jsx". Does the file exist?
Getting This problem
Failed to resolve import "react-dom/client" from "src\main.jsx". Does the file exist?
this is my main.jsx file
import React from 'react'
import ReactDOM from 'react-dom/client'
// import {render} from "react-dom";
import App from './components/App.jsx'
import './index.css'
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<App />
</React.StrictMode>
)
I also tried to do this
import React from 'react'
import {render} from "react-dom";
import App from './components/App.jsx'
import './index.css'
const container = document.getElementById("root");
render(
<React.StrictMode>
<App />
</React.StrictMode>,
container
);
But this one shows blank page
please see this if someone can help
I am trying to make codepen copy project
these are my dependencies in pakage.json
"dependencies": {
"@fortawesome/fontawesome-svg-core": "^1.2.31",
"@fortawesome/free-brands-svg-icons": "^5.15.0",
"@fortawesome/free-solid-svg-icons": "^5.15.0",
"@fortawesome/react-fontawesome": "^0.1.11",
"@testing-library/jest-dom": "^4.2.4",
"@testing-library/react": "^9.5.0",
"@testing-library/user-event": "^7.2.1",
"codemirror": "^5.58.1",
"react": "^16.13.1",
"react-codemirror2": "^7.2.1",
"react-dom": "^16.13.1",
"react-scripts": "3.4.3"
},
A:
You're trying to import ReactDOM from react-dom/client, but that module does not exist so import ReactDOM from the react-dom package.
import React from 'react'
import ReactDOM from 'react-dom' // Import ReactDOM from the react-dom package
import App from './components/App.jsx'
import './index.css'
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<App />
</React.StrictMode>
)
Second code is correct but the container variable is never defined, so it will throw an error.
You need to define the container variable before you can use it.
import React from 'react'
import {render} from "react-dom";
import App from './components/App.jsx'
import './index.css'
// Define the container variable
const container = document.getElementById("root");
render(
<React.StrictMode>
<App />
</React.StrictMode>,
container // Use the container variable to render your app
);
|
Failed to resolve import "react-dom/client" from "src\main.jsx". Does the file exist?
|
Getting This problem
Failed to resolve import "react-dom/client" from "src\main.jsx". Does the file exist?
this is my main.jsx file
import React from 'react'
import ReactDOM from 'react-dom/client'
// import {render} from "react-dom";
import App from './components/App.jsx'
import './index.css'
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<App />
</React.StrictMode>
)
I also tried to do this
import React from 'react'
import {render} from "react-dom";
import App from './components/App.jsx'
import './index.css'
const container = document.getElementById("root");
render(
<React.StrictMode>
<App />
</React.StrictMode>,
container
);
But this one shows blank page
please see this if someone can help
I am trying to make codepen copy project
these are my dependencies in pakage.json
"dependencies": {
"@fortawesome/fontawesome-svg-core": "^1.2.31",
"@fortawesome/free-brands-svg-icons": "^5.15.0",
"@fortawesome/free-solid-svg-icons": "^5.15.0",
"@fortawesome/react-fontawesome": "^0.1.11",
"@testing-library/jest-dom": "^4.2.4",
"@testing-library/react": "^9.5.0",
"@testing-library/user-event": "^7.2.1",
"codemirror": "^5.58.1",
"react": "^16.13.1",
"react-codemirror2": "^7.2.1",
"react-dom": "^16.13.1",
"react-scripts": "3.4.3"
},
|
[
"You're trying to import ReactDOM from react-dom/client, but that module does not exist so import ReactDOM from the react-dom package.\nimport React from 'react'\nimport ReactDOM from 'react-dom' // Import ReactDOM from the react-dom package\nimport App from './components/App.jsx'\nimport './index.css'\n\nReactDOM.createRoot(document.getElementById('root')).render(\n <React.StrictMode>\n <App />\n </React.StrictMode>\n)\n\nSecond code is correct but the container variable is never defined, so it will throw an error.\nYou need to define the container variable before you can use it.\nimport React from 'react'\nimport {render} from \"react-dom\";\nimport App from './components/App.jsx'\nimport './index.css'\n\n// Define the container variable\nconst container = document.getElementById(\"root\");\nrender(\n <React.StrictMode>\n <App />\n </React.StrictMode>,\n container // Use the container variable to render your app\n );\n\n"
] |
[
0
] |
[] |
[] |
[
"compiler_errors",
"reactjs",
"vite"
] |
stackoverflow_0074669429_compiler_errors_reactjs_vite.txt
|
Q:
IF statement inside a function to get value from an ACF field
I'm trying to create custom function in WordPress with ACF, and use it as a shortcode.
What I want to do is quite simple:
Get a field from ACF
Check if the text is "not found" or something else
If it's something else, I'll show an H2 and a sentence with field content.
If its "not found" I don't want to show anything
I tried various code, here's my last one:
// write a shortcode that creates a text if the field is not "not found"
function show_alliance() {
$alliance = get_field('field_6383d4b46deed');
if ($alliance !='not found'): {
return '<h2>TITLE</h2><p>This is... '. $alliance .' </p>';
}
else: {
return '';}
}
add_shortcode('alliance', 'show_alliance')
By WordPress always comes up with errors when I save my snippet. I can't find a way to make it work.
(I use Code Snippets in WordPress)
Any ideas?
(I'm sure it's very simple...)
--
Tried different syntax, but WordPress never validates the code snippet.
Last one is:
`L’extrait de code que vous essayez d’enregistrer a produit une erreur fatale à la ligne 11 :
syntax error, unexpected '}'`
When I delete the } to put it a the end it tells me that I should not have it there...
A:
Please try this code I think this is working fine.
**PHP Code**
<?php if(get_field('field_6383d4b46deed')){ ?><h2>TITLE</h2><p>This is... '. $alliance .' </p>
else ?>
echo' ';
<?php } ?>
A:
It looks like you have a syntax error in your code. The error message you provided suggests that you have an unexpected '}' character on line 11.
To fix this error, make sure that you have properly matched your curly braces '{' and '}'. In your code, you have an opening curly brace '{' after the if statement on line 5, but you are missing the closing curly brace '}' before the else statement on line 9.
You can fix this error by adding the missing closing curly brace '}' before the else statement, like this:
function show_alliance() {
$alliance = get_field('field_6383d4b46deed');
if ($alliance !='not found') {
return '<h2>TITLE</h2><p>This is... '. $alliance .' </p>';
}
else {
return '';
}
A:
Here's the answer that works :
function show_alliance() {
$alliance = get_field('field_6383d4b46deed');
if ($alliance !='not found') {
return '<h2>TITLE</h2><p>This is... '. $alliance .' </p>';
}
else {
return '';
}
}
add_shortcode('alliance', 'show_alliance');
|
IF statement inside a function to get value from an ACF field
|
I'm trying to create custom function in WordPress with ACF, and use it as a shortcode.
What I want to do is quite simple:
Get a field from ACF
Check if the text is "not found" or something else
If it's something else, I'll show an H2 and a sentence with field content.
If its "not found" I don't want to show anything
I tried various code, here's my last one:
// write a shortcode that creates a text if the field is not "not found"
function show_alliance() {
$alliance = get_field('field_6383d4b46deed');
if ($alliance !='not found'): {
return '<h2>TITLE</h2><p>This is... '. $alliance .' </p>';
}
else: {
return '';}
}
add_shortcode('alliance', 'show_alliance')
By WordPress always comes up with errors when I save my snippet. I can't find a way to make it work.
(I use Code Snippets in WordPress)
Any ideas?
(I'm sure it's very simple...)
--
Tried different syntax, but WordPress never validates the code snippet.
Last one is:
`L’extrait de code que vous essayez d’enregistrer a produit une erreur fatale à la ligne 11 :
syntax error, unexpected '}'`
When I delete the } to put it a the end it tells me that I should not have it there...
|
[
"Please try this code I think this is working fine.\n**PHP Code**\n\n<?php if(get_field('field_6383d4b46deed')){ ?><h2>TITLE</h2><p>This is... '. $alliance .' </p>\nelse ?>\necho' ';\n<?php } ?>\n\n",
"It looks like you have a syntax error in your code. The error message you provided suggests that you have an unexpected '}' character on line 11.\nTo fix this error, make sure that you have properly matched your curly braces '{' and '}'. In your code, you have an opening curly brace '{' after the if statement on line 5, but you are missing the closing curly brace '}' before the else statement on line 9.\nYou can fix this error by adding the missing closing curly brace '}' before the else statement, like this:\nfunction show_alliance() {\n$alliance = get_field('field_6383d4b46deed');\nif ($alliance !='not found') {\n return '<h2>TITLE</h2><p>This is... '. $alliance .' </p>';\n}\nelse {\n return '';\n}\n\n",
"Here's the answer that works :\nfunction show_alliance() {\n $alliance = get_field('field_6383d4b46deed');\n if ($alliance !='not found') {\n return '<h2>TITLE</h2><p>This is... '. $alliance .' </p>';\n }\n else {\n return '';\n }\n}\nadd_shortcode('alliance', 'show_alliance');\n\n"
] |
[
0,
0,
0
] |
[] |
[] |
[
"advanced_custom_fields",
"code_snippets",
"php",
"shortcode",
"wordpress"
] |
stackoverflow_0074669407_advanced_custom_fields_code_snippets_php_shortcode_wordpress.txt
|
Q:
Parenthesis in a recursive way (Python)
def paren(s, cnt=0):
if s == '':
return True
if s[0] == '(':
return paren(s[1:], cnt + 1)
elif s[0] == ')':
return paren(s[1:], cnt - 1)
return cnt == 0
So this code works for all cases if there is the same number of "(" and ")".
But for example it doesn't work for "))(( ".
how can I modify the code for this to work that for every opening bracket there is a closing one, then it returns True.
A:
def paren(s):
_s = s.replace('()','')
if not _s:
return True
elif _s==s:
return False
return paren(_s)
print(paren(')()('))
A:
Check if at any point c < 0, and fix the return for when s == ''
def paren(s, cnt=0):
if c < 0: return False
elif s == '': return c == 0
elif s[0] == '(':
return paren(s[1:], cnt + 1)
elif s[0] == ')':
return paren(s[1:], cnt - 1)
# here, there's a non-parentheses character. I'll assume you want to ignore these
# if they're impossible, just remove this line
return parent(s[1:], cnt)
A:
To check that for every opening bracket there is a closing bracket, you can simply check if the final value of cnt is 0. If it is, then it means that there was an equal number of opening and closing brackets, so the string is balanced. Here is one way you could modify the code to do this:
def paren(s, cnt=0):
if s == '':
# If the string is empty, return True if the count is 0,
# otherwise return False
return cnt == 0
if s[0] == '(':
# If the first character is an opening bracket, increment the count
return paren(s[1:], cnt + 1)
elif s[0] == ')':
# If the first character is a closing bracket, decrement the count
return paren(s[1:], cnt - 1)
# If the first character is neither an opening nor closing bracket,
# just recurse on the rest of the string
return paren(s[1:], cnt)
This code should work for the example you gave, "))(( ". When it reaches the first closing bracket, cnt will be decremented to -1. When it reaches the next closing bracket, cnt will be decremented again to -2. When it reaches the first opening bracket, cnt will be incremented to -1. Finally, when it reaches the last opening bracket, cnt will be incremented again to 0. When the string is empty, cnt will be 0, so the function will return True.
|
Parenthesis in a recursive way (Python)
|
def paren(s, cnt=0):
if s == '':
return True
if s[0] == '(':
return paren(s[1:], cnt + 1)
elif s[0] == ')':
return paren(s[1:], cnt - 1)
return cnt == 0
So this code works for all cases if there is the same number of "(" and ")".
But for example it doesn't work for "))(( ".
how can I modify the code for this to work that for every opening bracket there is a closing one, then it returns True.
|
[
"def paren(s):\n _s = s.replace('()','')\n if not _s:\n return True\n elif _s==s:\n return False\n return paren(_s)\n\nprint(paren(')()('))\n\n",
"Check if at any point c < 0, and fix the return for when s == ''\ndef paren(s, cnt=0):\n if c < 0: return False\n elif s == '': return c == 0\n elif s[0] == '(':\n return paren(s[1:], cnt + 1)\n elif s[0] == ')':\n return paren(s[1:], cnt - 1)\n # here, there's a non-parentheses character. I'll assume you want to ignore these\n # if they're impossible, just remove this line\n return parent(s[1:], cnt)\n\n",
"To check that for every opening bracket there is a closing bracket, you can simply check if the final value of cnt is 0. If it is, then it means that there was an equal number of opening and closing brackets, so the string is balanced. Here is one way you could modify the code to do this:\ndef paren(s, cnt=0):\nif s == '':\n # If the string is empty, return True if the count is 0,\n # otherwise return False\n return cnt == 0\nif s[0] == '(':\n # If the first character is an opening bracket, increment the count\n return paren(s[1:], cnt + 1)\nelif s[0] == ')':\n # If the first character is a closing bracket, decrement the count\n return paren(s[1:], cnt - 1)\n# If the first character is neither an opening nor closing bracket,\n# just recurse on the rest of the string\nreturn paren(s[1:], cnt)\n\nThis code should work for the example you gave, \"))(( \". When it reaches the first closing bracket, cnt will be decremented to -1. When it reaches the next closing bracket, cnt will be decremented again to -2. When it reaches the first opening bracket, cnt will be incremented to -1. Finally, when it reaches the last opening bracket, cnt will be incremented again to 0. When the string is empty, cnt will be 0, so the function will return True.\n"
] |
[
0,
0,
0
] |
[] |
[] |
[
"python",
"python_3.x"
] |
stackoverflow_0074669803_python_python_3.x.txt
|
Q:
React Native Scrollview is not scrolling down
i gave been trying to create a scrollable screen every thing looks fine however the screen is not scrolling for some reason i'm not sure what's the problem this is my first time working with react native and all the diffrent components are bugging me. This is my code i'll be removing some extra code like the imports, logic and the fetch request cause it's too long:
import React, { useEffect, useState } from 'react'
import {
View,
ScrollView,
Image,
Text,
StyleSheet,
TouchableOpacity,
FlatList,
Dimensions,
SafeAreaView} from 'react-native'
let {width} = Dimensions.get('window');
let {height} = Dimensions.get('window');
const PriceComparison = ( { route, navigation: { goBack } } ) => {
const {onAdd} = useStateContext();
const {itemId, itemName, itemStore, itemCategory} = route.params;
const [data, setData] = useState();
const [isLoading, setIsLoading] = useState(false);
const screenHeight = Dimensions.get('window').height
return (
<SafeAreaView style={
{
flex: 1,
}
}>
{isLoading ? (
<ScrollView contentContainerStyle={{ flexGrow: 1, width: width, height: height}} keyboardShouldPersistTaps='handled'>
<Text>Loading....</Text>
</ScrollView>
) : (
<View style={{height: screenHeight, backgroundColor: '#fff'}}>
<ScrollView contentContainerStyle={{ flexGrow: 1 }}>
<View style={{height: '100%'}}>
<View style={styles.Header}>
<TouchableOpacity
style={styles.button}
onPress={() => goBack()}
>
<Icon icon ='arrow-back-outline' color='#000'/>
</TouchableOpacity>
<Text style={{fontWeight: '800', fontSize: 20}}>Price Comparison</Text>
</View >
{ (dataLength !== 0) ?
<View style={{height: '100%'}}>
{data?.sort((a,b) => {return a.price-b.price}).slice(0, 1).map((product) => (
<View style={{height: '50%'}}>
<View style={{height: '100%'}}>
{dummyData.storesData.filter((img) => img.store === product.store ).map((img) => (
<View style={styles.Cheapest}>
<View style={styles.CheapestLogo}>
<Image
style={styles.CheapestLogoImage}
source={{ uri: `${img.shopbyimg}` }}
/>
</View>
<View style={styles.CheapestDetails}>
<Image
style={styles.ProductImage}
source={{ uri: `${product.image}` }}
/>
<View style={styles.CheapestTitle}>
<View style={{width: '70%'}}>
<Text style={styles.CheapestName}> {product.name} <Text style={styles.CheapestMeasurement}> {product.measurement} </Text></Text>
</View>
<Text style={styles.CheapestPrice}> ${product.price}</Text>
</View>
<View style={styles.CheapestSavings}>
<Text style={styles.SavePrice}> Save: ${saving} </Text>
<Text style={styles.SavePercentage}> Save up to {percentageSaving}% </Text>
</View>
<TouchableOpacity
style={{backgroundColor: COLORS.primary, padding: 15, borderRadius: 4, width: '92%', marginTop: 10, marginLeft: 'auto', marginRight: 'auto'}}
onPress={() => {onAdd(product, qty)}}
>
<Text
style={{
color: '#fff',
fontWeight: '600',
textAlign: 'center'
}}>
ADD TO CART
</Text>
</TouchableOpacity>
</View>
</View>
))}
</View>
</View>
))}
{data?.sort((a,b) => {return a.price-b.price}).slice(1, data.length).map((product) => (
<View
style={{
height: '50%',
marginTop: 80,
backgroundColor: 'transparent',
marginTop: 100,
width: '92%',
marginLeft: 'auto',
marginRight: 'auto',
borderRadius: 8
}}>
{dummyData.storesData.filter((img) => img.store === product.store ).map((img) => (
<View style={styles.otherProducts}>
<View style={styles.otherProductsImage}>
<Image
style={styles.otherImages}
source={{ uri: `${product.image}` }}
/>
</View>
<View style={styles.otherProductsDetails}>
<Image
style={styles.otherImagesLogo}
source={{ uri: `${img.image}` }}
/>
<View>
<Text style={styles.CheapestName}> {product.name}</Text>
<Text style={styles.CheapestMeasurement}> {product.measurement} </Text>
</View>
<Text style={styles.CheapestPrice}> ${product.price}</Text>
<TouchableOpacity
style={{backgroundColor: COLORS.primary, padding: 10, borderRadius: 4, width: '92%', marginTop: 10,}}
onPress={() => {onAdd(product, qty)}}
>
<Text
style={{
color: '#fff',
fontWeight: '600',
textAlign: 'center'
}}>
ADD TO CART
</Text>
</TouchableOpacity>
</View>
</View>
))}
</View>
))}
</View>
: <><Text> No other product available for price comparison </Text>
<Text onPress={() => goBack()}> Return to the previous page </Text></> }
</View>
<BottomTabs/>
</ScrollView>
</View>
)}
</SafeAreaView>
)
}
export default PriceComparison
const Icon = (props) => (
<View>
<Ionicons
name={props.icon}
size={25}
style={{
marginBottom: 3,
alignSelf: 'center'
}}
color={props.color}
/>
</View>
)
const styles = StyleSheet.create({
scroller: {
flex: 1,
flexDirection: 'column'
},
Header: {
marginTop: 40,
flexDirection: 'row',
marginHorizontal: 5,
justifyContent: 'space-between',
marginLeft: 20,
marginRight: 20
},
Cheapest: {
height: '40%',
},
CheapestLogoImage: {
width: '50%',
height: '50%',
marginLeft: 'auto',
marginRight: 'auto',
marginTop: 10
},
CheapestDetails: {
marginTop: 5,
height: '100%'
},
ProductImage: {
width: '80%',
height: '80%',
marginLeft: 'auto',
marginRight: 'auto',
resizeMode: "contain"
},
CheapestDetails: {
width: '100%',
},
CheapestTitle: {
flexDirection: 'row',
justifyContent: 'space-between',
marginTop: 20,
marginLeft: 10,
marginRight: 10
},
CheapestName: {
fontSize: 14,
fontWeight: '600',
lineHeight: 19
},
CheapestMeasurement: {
fontSize: 14,
fontWeight: '500',
lineHeight: 19,
color: COLORS.darkGray2
},
CheapestPrice: {
fontSize: 14,
fontWeight: '600',
lineHeight: 19
},
CheapestSavings: {
flexDirection: 'row',
justifyContent: 'flex-start',
marginLeft: 10,
marginTop: 5,
marginBottom: 5,
marginRight: 10
},
SavePrice: {
fontSize: 14,
fontWeight: '600',
lineHeight: 19,
color: COLORS.primary
},
SavePercentage: {
fontSize: 14,
fontWeight: '600',
lineHeight: 19,
color: COLORS.Tomato
},
otherProducts: {
flexDirection: 'row',
},
otherImages: {
width: 120,
height: 120,
resizeMode: "contain",
},
otherProductsDetails: {
marginTop: 20,
width: '65%',
},
otherImagesLogo: {
height: '20%',
width: 120,
marginBottom: 10,
borderRadius: 6
}
});
A:
Delete the outer view. Add style={{ flex: 1 }} to the ScrollView.
Explanation: think of ScrollViews as having two levels - an outer and inner View. The inner View is styled with contentContainerStyle. The outer view is styled with style. The outer View needs flex: 1 to allocate space.
|
React Native Scrollview is not scrolling down
|
i gave been trying to create a scrollable screen every thing looks fine however the screen is not scrolling for some reason i'm not sure what's the problem this is my first time working with react native and all the diffrent components are bugging me. This is my code i'll be removing some extra code like the imports, logic and the fetch request cause it's too long:
import React, { useEffect, useState } from 'react'
import {
View,
ScrollView,
Image,
Text,
StyleSheet,
TouchableOpacity,
FlatList,
Dimensions,
SafeAreaView} from 'react-native'
let {width} = Dimensions.get('window');
let {height} = Dimensions.get('window');
const PriceComparison = ( { route, navigation: { goBack } } ) => {
const {onAdd} = useStateContext();
const {itemId, itemName, itemStore, itemCategory} = route.params;
const [data, setData] = useState();
const [isLoading, setIsLoading] = useState(false);
const screenHeight = Dimensions.get('window').height
return (
<SafeAreaView style={
{
flex: 1,
}
}>
{isLoading ? (
<ScrollView contentContainerStyle={{ flexGrow: 1, width: width, height: height}} keyboardShouldPersistTaps='handled'>
<Text>Loading....</Text>
</ScrollView>
) : (
<View style={{height: screenHeight, backgroundColor: '#fff'}}>
<ScrollView contentContainerStyle={{ flexGrow: 1 }}>
<View style={{height: '100%'}}>
<View style={styles.Header}>
<TouchableOpacity
style={styles.button}
onPress={() => goBack()}
>
<Icon icon ='arrow-back-outline' color='#000'/>
</TouchableOpacity>
<Text style={{fontWeight: '800', fontSize: 20}}>Price Comparison</Text>
</View >
{ (dataLength !== 0) ?
<View style={{height: '100%'}}>
{data?.sort((a,b) => {return a.price-b.price}).slice(0, 1).map((product) => (
<View style={{height: '50%'}}>
<View style={{height: '100%'}}>
{dummyData.storesData.filter((img) => img.store === product.store ).map((img) => (
<View style={styles.Cheapest}>
<View style={styles.CheapestLogo}>
<Image
style={styles.CheapestLogoImage}
source={{ uri: `${img.shopbyimg}` }}
/>
</View>
<View style={styles.CheapestDetails}>
<Image
style={styles.ProductImage}
source={{ uri: `${product.image}` }}
/>
<View style={styles.CheapestTitle}>
<View style={{width: '70%'}}>
<Text style={styles.CheapestName}> {product.name} <Text style={styles.CheapestMeasurement}> {product.measurement} </Text></Text>
</View>
<Text style={styles.CheapestPrice}> ${product.price}</Text>
</View>
<View style={styles.CheapestSavings}>
<Text style={styles.SavePrice}> Save: ${saving} </Text>
<Text style={styles.SavePercentage}> Save up to {percentageSaving}% </Text>
</View>
<TouchableOpacity
style={{backgroundColor: COLORS.primary, padding: 15, borderRadius: 4, width: '92%', marginTop: 10, marginLeft: 'auto', marginRight: 'auto'}}
onPress={() => {onAdd(product, qty)}}
>
<Text
style={{
color: '#fff',
fontWeight: '600',
textAlign: 'center'
}}>
ADD TO CART
</Text>
</TouchableOpacity>
</View>
</View>
))}
</View>
</View>
))}
{data?.sort((a,b) => {return a.price-b.price}).slice(1, data.length).map((product) => (
<View
style={{
height: '50%',
marginTop: 80,
backgroundColor: 'transparent',
marginTop: 100,
width: '92%',
marginLeft: 'auto',
marginRight: 'auto',
borderRadius: 8
}}>
{dummyData.storesData.filter((img) => img.store === product.store ).map((img) => (
<View style={styles.otherProducts}>
<View style={styles.otherProductsImage}>
<Image
style={styles.otherImages}
source={{ uri: `${product.image}` }}
/>
</View>
<View style={styles.otherProductsDetails}>
<Image
style={styles.otherImagesLogo}
source={{ uri: `${img.image}` }}
/>
<View>
<Text style={styles.CheapestName}> {product.name}</Text>
<Text style={styles.CheapestMeasurement}> {product.measurement} </Text>
</View>
<Text style={styles.CheapestPrice}> ${product.price}</Text>
<TouchableOpacity
style={{backgroundColor: COLORS.primary, padding: 10, borderRadius: 4, width: '92%', marginTop: 10,}}
onPress={() => {onAdd(product, qty)}}
>
<Text
style={{
color: '#fff',
fontWeight: '600',
textAlign: 'center'
}}>
ADD TO CART
</Text>
</TouchableOpacity>
</View>
</View>
))}
</View>
))}
</View>
: <><Text> No other product available for price comparison </Text>
<Text onPress={() => goBack()}> Return to the previous page </Text></> }
</View>
<BottomTabs/>
</ScrollView>
</View>
)}
</SafeAreaView>
)
}
export default PriceComparison
const Icon = (props) => (
<View>
<Ionicons
name={props.icon}
size={25}
style={{
marginBottom: 3,
alignSelf: 'center'
}}
color={props.color}
/>
</View>
)
const styles = StyleSheet.create({
scroller: {
flex: 1,
flexDirection: 'column'
},
Header: {
marginTop: 40,
flexDirection: 'row',
marginHorizontal: 5,
justifyContent: 'space-between',
marginLeft: 20,
marginRight: 20
},
Cheapest: {
height: '40%',
},
CheapestLogoImage: {
width: '50%',
height: '50%',
marginLeft: 'auto',
marginRight: 'auto',
marginTop: 10
},
CheapestDetails: {
marginTop: 5,
height: '100%'
},
ProductImage: {
width: '80%',
height: '80%',
marginLeft: 'auto',
marginRight: 'auto',
resizeMode: "contain"
},
CheapestDetails: {
width: '100%',
},
CheapestTitle: {
flexDirection: 'row',
justifyContent: 'space-between',
marginTop: 20,
marginLeft: 10,
marginRight: 10
},
CheapestName: {
fontSize: 14,
fontWeight: '600',
lineHeight: 19
},
CheapestMeasurement: {
fontSize: 14,
fontWeight: '500',
lineHeight: 19,
color: COLORS.darkGray2
},
CheapestPrice: {
fontSize: 14,
fontWeight: '600',
lineHeight: 19
},
CheapestSavings: {
flexDirection: 'row',
justifyContent: 'flex-start',
marginLeft: 10,
marginTop: 5,
marginBottom: 5,
marginRight: 10
},
SavePrice: {
fontSize: 14,
fontWeight: '600',
lineHeight: 19,
color: COLORS.primary
},
SavePercentage: {
fontSize: 14,
fontWeight: '600',
lineHeight: 19,
color: COLORS.Tomato
},
otherProducts: {
flexDirection: 'row',
},
otherImages: {
width: 120,
height: 120,
resizeMode: "contain",
},
otherProductsDetails: {
marginTop: 20,
width: '65%',
},
otherImagesLogo: {
height: '20%',
width: 120,
marginBottom: 10,
borderRadius: 6
}
});
|
[
"Delete the outer view. Add style={{ flex: 1 }} to the ScrollView.\nExplanation: think of ScrollViews as having two levels - an outer and inner View. The inner View is styled with contentContainerStyle. The outer view is styled with style. The outer View needs flex: 1 to allocate space.\n"
] |
[
1
] |
[] |
[] |
[
"react_native",
"react_native_scrollview",
"reactjs"
] |
stackoverflow_0074669190_react_native_react_native_scrollview_reactjs.txt
|
Q:
Implementing an interface in python
I am pretty new to Python and couldn't understand the origin of this problem.
I'm trying to implement an interface, I have downloaded the zope.interface package, and imported it in my file like this
import zope.interface
Now when I write
class MyInterface(zope.interface.Interface)
I get this error:
"message": "Inheriting 'zope.interface.Interface', which is not a class."
but when I do
class MyInterface(zope.interface.interface.InterfaceClass):
it works fine.
I don't understand the difference.
A:
I am new to python too, but I will try to help using the little knowledge I have.
Actually I tested your code, and it works for me, it doesn't give me that error message. But concerning the difference between both statements, I wrote the following code to figure out the difference:
import zope.interface
class MyInterface(zope.interface.Interface):
pass
print(type(MyInterface))
class MyInterface1(zope.interface.interface.InterfaceClass):
pass
print(type(MyInterface1))
class TestClass:
pass
print(type(TestClass))
This code gave me this output:
<class 'zope.interface.interface.InterfaceClass'>
<class 'type'>
<class 'type'>
So to answer your question about the difference between the two statements, the first one, MyInterface, is a declaration of an interface which is, according to the official documentation is an instance of the zop.interface.interface.InterfaceClass.
MyInterface1, however,is a normal class (object of the mega class type, of which all classes are objects. As an exemple, TestClass is also an object of the mega class type), and it is just inheriting from the class zope.interface.interface.InterfaceClass
Of course this is just an educated guess, I am new to python interfaces and OOP myself, but I hope this at least helps answer your questions.
A:
I don't know if this might help, but this code works for me:
import zope.interface
class MyInterface(zope.interface.Interface):
pass
while this one doesn't, it doesn't compile
import zope.interface
class MyInterface(zope.interface.Interface)
A:
Problem solved ,
turns out there was no problem at all !
I was getting an error on my IDE (vsCode) so I didn't bother to build, however, when I did try to build my code, it woked just fine with no build errors whatsoever.
According to many forums online , vscode does quite frequently show "false" errors and that's fixable (see link below)
https://superuser.com/questions/1639666/visual-studio-code-false-errors-at-random
|
Implementing an interface in python
|
I am pretty new to Python and couldn't understand the origin of this problem.
I'm trying to implement an interface, I have downloaded the zope.interface package, and imported it in my file like this
import zope.interface
Now when I write
class MyInterface(zope.interface.Interface)
I get this error:
"message": "Inheriting 'zope.interface.Interface', which is not a class."
but when I do
class MyInterface(zope.interface.interface.InterfaceClass):
it works fine.
I don't understand the difference.
|
[
"I am new to python too, but I will try to help using the little knowledge I have.\nActually I tested your code, and it works for me, it doesn't give me that error message. But concerning the difference between both statements, I wrote the following code to figure out the difference:\n import zope.interface\n class MyInterface(zope.interface.Interface):\n pass\n print(type(MyInterface))\n\n class MyInterface1(zope.interface.interface.InterfaceClass):\n pass\n print(type(MyInterface1))\n\n class TestClass:\n pass\n print(type(TestClass))\n\nThis code gave me this output:\n <class 'zope.interface.interface.InterfaceClass'>\n <class 'type'>\n <class 'type'>\n\nSo to answer your question about the difference between the two statements, the first one, MyInterface, is a declaration of an interface which is, according to the official documentation is an instance of the zop.interface.interface.InterfaceClass.\nMyInterface1, however,is a normal class (object of the mega class type, of which all classes are objects. As an exemple, TestClass is also an object of the mega class type), and it is just inheriting from the class zope.interface.interface.InterfaceClass\nOf course this is just an educated guess, I am new to python interfaces and OOP myself, but I hope this at least helps answer your questions.\n",
"I don't know if this might help, but this code works for me:\n import zope.interface \n \n class MyInterface(zope.interface.Interface):\n pass\n\nwhile this one doesn't, it doesn't compile\n import zope.interface \n \n class MyInterface(zope.interface.Interface)\n\n",
"Problem solved ,\nturns out there was no problem at all !\nI was getting an error on my IDE (vsCode) so I didn't bother to build, however, when I did try to build my code, it woked just fine with no build errors whatsoever.\nAccording to many forums online , vscode does quite frequently show \"false\" errors and that's fixable (see link below)\nhttps://superuser.com/questions/1639666/visual-studio-code-false-errors-at-random\n"
] |
[
0,
0,
0
] |
[] |
[] |
[
"python",
"zope",
"zope.interface"
] |
stackoverflow_0074665243_python_zope_zope.interface.txt
|
Q:
Can you add an iframe inside another iframe?
I am trying to inspect using javascript "google.com" to add a youtube video on google page
A:
you CAN add an iframe inside an iframe, as long as they are both from the same site or domain or they are from a third party mutual trusted sites (Access-Control-Allow-Origin cookie to include the domain and server you allow to call your site),
if not, then the cross-site-scripting defense mechanism of the browser will prevent it from happening,
to get google html to display a frame from youtube, you need youtube to contain some cookie that allows Google to call youtube, for instance:
Access-Control-Allow-Origin: https://www.google.com
-- or --
Access-Control-Allow-Origin: *
(which youtube obviously don't send that cookie)
read more here: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
but if you use Youtube's Embed URL (on a video press share button and click embed, copy the code and paste it into google's html),
in this way you can embed even on a google page (with F12 developers tools, not for public usage of-course)
the code
the outcome
|
Can you add an iframe inside another iframe?
|
I am trying to inspect using javascript "google.com" to add a youtube video on google page
|
[
"you CAN add an iframe inside an iframe, as long as they are both from the same site or domain or they are from a third party mutual trusted sites (Access-Control-Allow-Origin cookie to include the domain and server you allow to call your site),\nif not, then the cross-site-scripting defense mechanism of the browser will prevent it from happening,\nto get google html to display a frame from youtube, you need youtube to contain some cookie that allows Google to call youtube, for instance:\nAccess-Control-Allow-Origin: https://www.google.com\n-- or --\nAccess-Control-Allow-Origin: *\n(which youtube obviously don't send that cookie)\nread more here: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS\nbut if you use Youtube's Embed URL (on a video press share button and click embed, copy the code and paste it into google's html),\nin this way you can embed even on a google page (with F12 developers tools, not for public usage of-course)\nthe code\nthe outcome\n"
] |
[
0
] |
[] |
[] |
[
"dom",
"html",
"javascript"
] |
stackoverflow_0074669225_dom_html_javascript.txt
|
Q:
How does k8s operators implement images for other resources
I wonder how does a kubernetes operator such as the jaeger operator call other images.
A problem I am having with the Jaeger operator for instance, is when I set up a new instance and the operator creates the required components, it calls images for those components from quay.io. Now on my setup, I am required to pull images from our local registry.
How can I set up the operator to use local registry instead of quay.io?
A:
To use a local registry with the Jaeger operator, you can edit the values.yaml file for the operator and specify the location of your local registry in the imagePullSecrets section. This will tell the operator to use your local registry when pulling images for the Jaeger components.
Here is an example of what the values.yaml file might look like with the local registry specified:
# Configuration for the Jaeger operator
operator:
# Image settings
image:
# Repository containing the operator image
repository: quay.io/jaegertracing/jaeger-operator
# Image tag
tag: latest
# Image pull policy
pullPolicy: IfNotPresent
# Configuration for the Jaeger components
jaeger:
# Image settings
image:
# Repository containing the Jaeger images
repository: my-local-registry.com/jaeger
# Image tag
tag: latest
# Image pull policy
pullPolicy: IfNotPresent
# Image pull secrets
imagePullSecrets:
- name: my-registry-secret
# Other configuration options
...
After updating the values.yaml file, you can apply the changes by running the kubectl apply command. This will update the operator's configuration and instruct it to use your local registry when pulling images for the Jaeger components.
|
How does k8s operators implement images for other resources
|
I wonder how does a kubernetes operator such as the jaeger operator call other images.
A problem I am having with the Jaeger operator for instance, is when I set up a new instance and the operator creates the required components, it calls images for those components from quay.io. Now on my setup, I am required to pull images from our local registry.
How can I set up the operator to use local registry instead of quay.io?
|
[
"To use a local registry with the Jaeger operator, you can edit the values.yaml file for the operator and specify the location of your local registry in the imagePullSecrets section. This will tell the operator to use your local registry when pulling images for the Jaeger components.\nHere is an example of what the values.yaml file might look like with the local registry specified:\n# Configuration for the Jaeger operator\noperator:\n # Image settings\n image:\n # Repository containing the operator image\n repository: quay.io/jaegertracing/jaeger-operator\n # Image tag\n tag: latest\n # Image pull policy\n pullPolicy: IfNotPresent\n\n# Configuration for the Jaeger components\njaeger:\n # Image settings\n image:\n # Repository containing the Jaeger images\n repository: my-local-registry.com/jaeger\n # Image tag\n tag: latest\n # Image pull policy\n pullPolicy: IfNotPresent\n # Image pull secrets\n imagePullSecrets:\n - name: my-registry-secret\n\n# Other configuration options\n...\n\nAfter updating the values.yaml file, you can apply the changes by running the kubectl apply command. This will update the operator's configuration and instruct it to use your local registry when pulling images for the Jaeger components.\n"
] |
[
0
] |
[] |
[] |
[
"jaeger",
"kubernetes",
"kubernetes_operator"
] |
stackoverflow_0074665307_jaeger_kubernetes_kubernetes_operator.txt
|
Q:
Nested collection views with dynamic content
I am using two nested collection views. I have added the ChildCollectionView to the ParentCollectionViewCell, and ChildCollectionView have 3 cells in it but the ParentCollectionViewCell does not adjust the frame of the cell as per the content.
Here's the code,
ParentCollectionView
class ViewController: UIViewController {
var parentCollectionView: UICollectionView = {
let _collectionView = UICollectionView.init(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout.init())
return _collectionView
}()
let id = "ParentCollectionViewCell"
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
view.addSubview(parentCollectionView)
parentCollectionView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
parentCollectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
parentCollectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
parentCollectionView.topAnchor.constraint(equalTo: view.topAnchor),
parentCollectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
parentCollectionView.dataSource = self
parentCollectionView.register(UINib(nibName: id, bundle: nil), forCellWithReuseIdentifier: id)
if let flowLayout = parentCollectionView.collectionViewLayout as? UICollectionViewFlowLayout {
flowLayout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
}
}
}
extension ViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
1
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: id, for: indexPath) as! ParentCollectionViewCell
cell.backgroundColor = .red
return cell
}
}
ParentCollectionViewCell
class ParentCollectionViewCell: UICollectionViewCell {
var childCollectionView: UICollectionView = {
let _collectionView = UICollectionView.init(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout.init())
return _collectionView
}()
let reuseId = "ChildCollectionViewCell"
private let data = ["ChildCell1","ChildCell2","ChildCell3"]
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
setupViews()
}
func setupViews() {
contentView.addSubview(childCollectionView)
childCollectionView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
childCollectionView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
childCollectionView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
childCollectionView.topAnchor.constraint(equalTo: contentView.topAnchor),
childCollectionView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor),
childCollectionView.widthAnchor.constraint(equalToConstant: 360)
])
childCollectionView.dataSource = self
childCollectionView.register(UINib(nibName: reuseId, bundle: nil), forCellWithReuseIdentifier: reuseId)
if let flowLayout = childCollectionView.collectionViewLayout as? UICollectionViewFlowLayout {
flowLayout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
}
}
}
extension ParentCollectionViewCell: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
data.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseId, for: indexPath) as! ChildCollectionViewCell
cell.backgroundColor = .gray
cell.setupViews()
return cell
}
}
ChildCollectionViewCell
class ChildCollectionViewCell: UICollectionViewCell {
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
func setupViews() {
let label = UILabel()
label.text = "Child Collection"
label.numberOfLines = 0
label.font = label.font.withSize(50)
contentView.addSubview(label)
label.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
label.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
label.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
label.topAnchor.constraint(equalTo: contentView.topAnchor),
label.bottomAnchor.constraint(equalTo: contentView.bottomAnchor)
])
}
}
Current Output
Current Output
Expected Output
Expected Output
A:
To adjust the frame of the parent collection view cell as per the content of the child collection view, you need to specify the preferred width of the child collection view and use it as the width constraint for the parent collection view cell.
Here is an example code snippet that demonstrates how to do this:
class ParentCollectionViewCell: UICollectionViewCell {
// Set the preferred width for the child collection view
let childCollectionViewPreferredWidth: CGFloat = 360
// ...
func setupViews() {
contentView.addSubview(childCollectionView)
childCollectionView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
// Use the preferred width as the width constraint for the parent collection view cell
contentView.widthAnchor.constraint(equalToConstant: childCollectionViewPreferredWidth),
// ...
])
// ...
}
}
By specifying the preferred width of the child collection view and using it as the width constraint for the parent collection view cell, you can ensure that the parent collection view cell adjusts its frame as per the content of the child collection view. This will ensure that the child collection view is displayed properly without any clipping or overflow.
A:
To adjust the size of the parent collection view cell to fit the content of its nested collection view, you can set the UICollectionViewFlowLayout's estimatedItemSize property to UICollectionViewFlowLayout.automaticSize in the parent collection view's flow layout. This will allow the parent collection view cell to size itself automatically based on the size of its content.
Here is an example of how to do this:
if let flowLayout = parentCollectionView.collectionViewLayout as? UICollectionViewFlowLayout {
flowLayout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
}
You should be able to add this code in the viewDidLoad() method of your ViewController class.
Additionally, you may want to set the parentCollectionViewCell's translatesAutoresizingMaskIntoConstraints property to false and add constraints to it so that it is properly positioned and sized within the parent view. This will allow the cell to resize itself as needed to fit its content.
|
Nested collection views with dynamic content
|
I am using two nested collection views. I have added the ChildCollectionView to the ParentCollectionViewCell, and ChildCollectionView have 3 cells in it but the ParentCollectionViewCell does not adjust the frame of the cell as per the content.
Here's the code,
ParentCollectionView
class ViewController: UIViewController {
var parentCollectionView: UICollectionView = {
let _collectionView = UICollectionView.init(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout.init())
return _collectionView
}()
let id = "ParentCollectionViewCell"
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
view.addSubview(parentCollectionView)
parentCollectionView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
parentCollectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
parentCollectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
parentCollectionView.topAnchor.constraint(equalTo: view.topAnchor),
parentCollectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
parentCollectionView.dataSource = self
parentCollectionView.register(UINib(nibName: id, bundle: nil), forCellWithReuseIdentifier: id)
if let flowLayout = parentCollectionView.collectionViewLayout as? UICollectionViewFlowLayout {
flowLayout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
}
}
}
extension ViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
1
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: id, for: indexPath) as! ParentCollectionViewCell
cell.backgroundColor = .red
return cell
}
}
ParentCollectionViewCell
class ParentCollectionViewCell: UICollectionViewCell {
var childCollectionView: UICollectionView = {
let _collectionView = UICollectionView.init(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout.init())
return _collectionView
}()
let reuseId = "ChildCollectionViewCell"
private let data = ["ChildCell1","ChildCell2","ChildCell3"]
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
setupViews()
}
func setupViews() {
contentView.addSubview(childCollectionView)
childCollectionView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
childCollectionView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
childCollectionView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
childCollectionView.topAnchor.constraint(equalTo: contentView.topAnchor),
childCollectionView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor),
childCollectionView.widthAnchor.constraint(equalToConstant: 360)
])
childCollectionView.dataSource = self
childCollectionView.register(UINib(nibName: reuseId, bundle: nil), forCellWithReuseIdentifier: reuseId)
if let flowLayout = childCollectionView.collectionViewLayout as? UICollectionViewFlowLayout {
flowLayout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
}
}
}
extension ParentCollectionViewCell: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
data.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseId, for: indexPath) as! ChildCollectionViewCell
cell.backgroundColor = .gray
cell.setupViews()
return cell
}
}
ChildCollectionViewCell
class ChildCollectionViewCell: UICollectionViewCell {
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
func setupViews() {
let label = UILabel()
label.text = "Child Collection"
label.numberOfLines = 0
label.font = label.font.withSize(50)
contentView.addSubview(label)
label.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
label.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
label.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
label.topAnchor.constraint(equalTo: contentView.topAnchor),
label.bottomAnchor.constraint(equalTo: contentView.bottomAnchor)
])
}
}
Current Output
Current Output
Expected Output
Expected Output
|
[
"To adjust the frame of the parent collection view cell as per the content of the child collection view, you need to specify the preferred width of the child collection view and use it as the width constraint for the parent collection view cell.\nHere is an example code snippet that demonstrates how to do this:\nclass ParentCollectionViewCell: UICollectionViewCell {\n\n // Set the preferred width for the child collection view\n let childCollectionViewPreferredWidth: CGFloat = 360\n\n // ...\n\n func setupViews() {\n contentView.addSubview(childCollectionView)\n\n childCollectionView.translatesAutoresizingMaskIntoConstraints = false\n\n NSLayoutConstraint.activate([\n // Use the preferred width as the width constraint for the parent collection view cell\n contentView.widthAnchor.constraint(equalToConstant: childCollectionViewPreferredWidth),\n\n // ...\n ])\n\n // ...\n }\n}\n\nBy specifying the preferred width of the child collection view and using it as the width constraint for the parent collection view cell, you can ensure that the parent collection view cell adjusts its frame as per the content of the child collection view. This will ensure that the child collection view is displayed properly without any clipping or overflow.\n",
"To adjust the size of the parent collection view cell to fit the content of its nested collection view, you can set the UICollectionViewFlowLayout's estimatedItemSize property to UICollectionViewFlowLayout.automaticSize in the parent collection view's flow layout. This will allow the parent collection view cell to size itself automatically based on the size of its content.\nHere is an example of how to do this:\nif let flowLayout = parentCollectionView.collectionViewLayout as? UICollectionViewFlowLayout {\n flowLayout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize\n}\n\nYou should be able to add this code in the viewDidLoad() method of your ViewController class.\nAdditionally, you may want to set the parentCollectionViewCell's translatesAutoresizingMaskIntoConstraints property to false and add constraints to it so that it is properly positioned and sized within the parent view. This will allow the cell to resize itself as needed to fit its content.\n"
] |
[
0,
0
] |
[] |
[] |
[
"ios",
"swift",
"uicollectionview",
"uicollectionviewcell",
"uicollectionviewlayout"
] |
stackoverflow_0073623069_ios_swift_uicollectionview_uicollectionviewcell_uicollectionviewlayout.txt
|
Q:
How to refund Google Developer Account after failed to verify identity?
I'm from Iraq, i paid the 25$ to activate my google developer console account, but now i can't post any apps because they don't verify my identity, after a couple tries and asks, i realized that Iraq is not supported.
now i've tried to ask to refund my 25$, i've sent them multiple emails from various forms, after one month of trying to get a suitable answer i get this:-
Hi Hedi,
Thanks for contacting Google Play Developer support.
Unfortunately, we are unable to provide refund for Play Console registration fee if we cannot verify your ID.
they let me pay, won't verify my account because of my country, and they refuse to refund because i haven't verified my account.
is there any hope to get back my 25$?
|
How to refund Google Developer Account after failed to verify identity?
|
I'm from Iraq, i paid the 25$ to activate my google developer console account, but now i can't post any apps because they don't verify my identity, after a couple tries and asks, i realized that Iraq is not supported.
now i've tried to ask to refund my 25$, i've sent them multiple emails from various forms, after one month of trying to get a suitable answer i get this:-
Hi Hedi,
Thanks for contacting Google Play Developer support.
Unfortunately, we are unable to provide refund for Play Console registration fee if we cannot verify your ID.
they let me pay, won't verify my account because of my country, and they refuse to refund because i haven't verified my account.
is there any hope to get back my 25$?
|
[] |
[] |
[
"Salam Hedi ,\nYou can request a full refund for the registration fee, go to the bottom of this page and look at Frequently asked questions/ My identity verification failed, can I get a refund for the $25 sign-up fee?\nhttps://support.google.com/googleplay/android-developer/answer/9198012?hl=en#zippy=%2Cmy-identity-verification-failed-can-i-get-a-refund-for-the-sign-up-fee\nOr by contacting the support team on this special link :\nhttps://support.google.com/googleplay/android-developer/contact/dev_registration?extra.IssueType=cancel\nSalam from Morocco\n"
] |
[
-1
] |
[
"google_developers_console"
] |
stackoverflow_0072020344_google_developers_console.txt
|
Q:
registerIdlingResources deprecation replacement doesn't work
I'm trying to replace my Espresso registerIdlingResources and unregisterIdlingResources deprecated method by using IdlingRegistry method according to android documentation.
Some of my tests worked before the update and no longer works now... These tests work unitarily but not together.
I noticed that there is a little difference with the old version (of Espresso class), this line is not present in IdlingRegistry class :
baseRegistry.sync(IdlingRegistry.getInstance().getResources(), IdlingRegistry.getInstance().getLoopers());
I think this sync method is very important for my custom IdlingResource...
How can I sync my looper without this line ?
Thanks you for your help.
Edit: I use EspressoCore 3.0.1 with runner/rules 1.0.1
Edit2: Link of documentation who has been specify deprecation : Here and Here.
A:
Be sure to run the latest version of androidx.test
If your tests run one at a time, but fail when run together, Android Test Orchestrator ("ATO") can solve that problem.
ATO runs each test method in a new process, so any in memory state is cleared.
From the docs, the basic gradle setup is:
android {
defaultConfig {
...
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
// The following argument makes the Android Test Orchestrator run its
// "pm clear" command after each test invocation. This command ensures
// that the app's state is completely cleared between tests.
testInstrumentationRunnerArguments clearPackageData: 'true'
}
testOptions {
execution 'ANDROIDX_TEST_ORCHESTRATOR'
}
}
dependencies {
androidTestImplementation 'androidx.test:runner:1.3.0'
androidTestUtil 'androidx.test:orchestrator:1.3.0'
}
The docs also include setup for installing and using Android Test Orchestrator without gradle.
You can also use ATO on Firebase Test Lab:
via web UI
via CLI
If you still have problems with your IdlingResources you can try the busybee library which simplifies using IdlingResources and makes them easier to debug.
(disclaimer, I am a maintainer of that library)
A:
The registerIdlingResources and unregisterIdlingResources methods in Espresso have been deprecated and replaced by the IdlingRegistry class. To use the IdlingRegistry class, you will need to do the following:
Import the IdlingRegistry class:
import androidx.test.espresso.idling.IdlingRegistry;
Instead of calling registerIdlingResources and unregisterIdlingResources, you will now call the register and unregister methods on the IdlingRegistry instance. For example:
// Old code:
Espresso.registerIdlingResources(idlingResource);
// New code:
IdlingRegistry.getInstance().register(idlingResource);
// Old code:
Espresso.unregisterIdlingResources(idlingResource);
// New code:
IdlingRegistry.getInstance().unregister(idlingResource);
Note that the IdlingRegistry class is a singleton, so you can always get the instance by calling IdlingRegistry.getInstance().
The sync method that you mentioned is no longer necessary, as the register and unregister methods will automatically sync the resources and loopers.
|
registerIdlingResources deprecation replacement doesn't work
|
I'm trying to replace my Espresso registerIdlingResources and unregisterIdlingResources deprecated method by using IdlingRegistry method according to android documentation.
Some of my tests worked before the update and no longer works now... These tests work unitarily but not together.
I noticed that there is a little difference with the old version (of Espresso class), this line is not present in IdlingRegistry class :
baseRegistry.sync(IdlingRegistry.getInstance().getResources(), IdlingRegistry.getInstance().getLoopers());
I think this sync method is very important for my custom IdlingResource...
How can I sync my looper without this line ?
Thanks you for your help.
Edit: I use EspressoCore 3.0.1 with runner/rules 1.0.1
Edit2: Link of documentation who has been specify deprecation : Here and Here.
|
[
"Be sure to run the latest version of androidx.test\nIf your tests run one at a time, but fail when run together, Android Test Orchestrator (\"ATO\") can solve that problem.\nATO runs each test method in a new process, so any in memory state is cleared.\nFrom the docs, the basic gradle setup is:\nandroid {\n defaultConfig {\n ...\n testInstrumentationRunner \"androidx.test.runner.AndroidJUnitRunner\"\n\n // The following argument makes the Android Test Orchestrator run its\n // \"pm clear\" command after each test invocation. This command ensures\n // that the app's state is completely cleared between tests.\n testInstrumentationRunnerArguments clearPackageData: 'true'\n }\n\n testOptions {\n execution 'ANDROIDX_TEST_ORCHESTRATOR'\n }\n}\n\ndependencies {\n androidTestImplementation 'androidx.test:runner:1.3.0'\n androidTestUtil 'androidx.test:orchestrator:1.3.0'\n}\n\nThe docs also include setup for installing and using Android Test Orchestrator without gradle.\nYou can also use ATO on Firebase Test Lab:\n\nvia web UI\nvia CLI\n\nIf you still have problems with your IdlingResources you can try the busybee library which simplifies using IdlingResources and makes them easier to debug.\n(disclaimer, I am a maintainer of that library)\n",
"The registerIdlingResources and unregisterIdlingResources methods in Espresso have been deprecated and replaced by the IdlingRegistry class. To use the IdlingRegistry class, you will need to do the following:\nImport the IdlingRegistry class:\nimport androidx.test.espresso.idling.IdlingRegistry;\n\nInstead of calling registerIdlingResources and unregisterIdlingResources, you will now call the register and unregister methods on the IdlingRegistry instance. For example:\n// Old code:\nEspresso.registerIdlingResources(idlingResource);\n\n// New code:\nIdlingRegistry.getInstance().register(idlingResource);\n\n// Old code:\nEspresso.unregisterIdlingResources(idlingResource);\n\n// New code:\nIdlingRegistry.getInstance().unregister(idlingResource);\n\nNote that the IdlingRegistry class is a singleton, so you can always get the instance by calling IdlingRegistry.getInstance().\nThe sync method that you mentioned is no longer necessary, as the register and unregister methods will automatically sync the resources and loopers.\n"
] |
[
0,
0
] |
[] |
[] |
[
"android",
"android_espresso",
"android_testing"
] |
stackoverflow_0046059677_android_android_espresso_android_testing.txt
|
Q:
Im trying to build an Installer for some packages that my programm needs. I also want to have a Status bar which shows the current progress
import tkinter as tk
import multiprocessing
from tkinter import messagebox
def installPackages_1(self):
self.t = ""
label = tk.Label(fenster, text="Checking for packages...").place(x=60, y=100)
pb = ttk.Progressbar(fenster, orient='horizontal', mode='determinate', length=280)
pb.place(x=180, y=100)
fenster.update()
packages = ["pandas", "openpyxl", "odfpy"]
for i in packages:
t1 = multiprocessing.Process(target=self.installPackages_2(i))
t1.start()
pb['value'] += 100 / 3
fenster.update()
label1 = tk.Label(fenster, text="Done").place(x=30, y=100, width=450, height=25)
fenster.update()
m_text = "\nStatus:\n%s" % (self.t)
tk.messagebox.showinfo(message=m_text, title="Installation")
def installPackages_2(self,package):
s = ""
s = str(subprocess.check_output([sys.executable, '-m', 'pip', 'install', package]))[2:12]
if s == "Collecting":
self.t += "Package '%s' installed\n" % (package)
else:
self.t += "[OK]: Paket '%s' found\n" % (package)
When i convert my python programm into an .exe the tkinter window open up multiple times, I think this is caused because th subprocess interrupts the process of the tkinterr window. I tried to implement some kind of multiprocessing but it didnt change anything.I convert through auto-py-to-exe.
A:
Pyinstaller already bundles the libraries with your executable, you don't need to check for them.
checking for libraries and installing them is completely unnecessary (and isn't as simple as you expect), don't call either functions inside your executable and your app will work just fine, as you don't need to call them anyway.
needless to say checking for their existence this way will fail and will cause a lot of undesirable behavior, as the application is no longer running as a python executable on a script but as an embedded interpreter, in other words sys.executable no longer points to python.exe.
also the correct way to check that a certain library exists is to use, importlib.util.find_spec, which should correctly work for frozen applications, but again, you don't need it for you executable because pyinstaller already packages all dependencies.
|
Im trying to build an Installer for some packages that my programm needs. I also want to have a Status bar which shows the current progress
|
import tkinter as tk
import multiprocessing
from tkinter import messagebox
def installPackages_1(self):
self.t = ""
label = tk.Label(fenster, text="Checking for packages...").place(x=60, y=100)
pb = ttk.Progressbar(fenster, orient='horizontal', mode='determinate', length=280)
pb.place(x=180, y=100)
fenster.update()
packages = ["pandas", "openpyxl", "odfpy"]
for i in packages:
t1 = multiprocessing.Process(target=self.installPackages_2(i))
t1.start()
pb['value'] += 100 / 3
fenster.update()
label1 = tk.Label(fenster, text="Done").place(x=30, y=100, width=450, height=25)
fenster.update()
m_text = "\nStatus:\n%s" % (self.t)
tk.messagebox.showinfo(message=m_text, title="Installation")
def installPackages_2(self,package):
s = ""
s = str(subprocess.check_output([sys.executable, '-m', 'pip', 'install', package]))[2:12]
if s == "Collecting":
self.t += "Package '%s' installed\n" % (package)
else:
self.t += "[OK]: Paket '%s' found\n" % (package)
When i convert my python programm into an .exe the tkinter window open up multiple times, I think this is caused because th subprocess interrupts the process of the tkinterr window. I tried to implement some kind of multiprocessing but it didnt change anything.I convert through auto-py-to-exe.
|
[
"Pyinstaller already bundles the libraries with your executable, you don't need to check for them.\nchecking for libraries and installing them is completely unnecessary (and isn't as simple as you expect), don't call either functions inside your executable and your app will work just fine, as you don't need to call them anyway.\nneedless to say checking for their existence this way will fail and will cause a lot of undesirable behavior, as the application is no longer running as a python executable on a script but as an embedded interpreter, in other words sys.executable no longer points to python.exe.\nalso the correct way to check that a certain library exists is to use, importlib.util.find_spec, which should correctly work for frozen applications, but again, you don't need it for you executable because pyinstaller already packages all dependencies.\n"
] |
[
0
] |
[] |
[] |
[
"multiprocessing",
"python",
"subprocess",
"tkinter"
] |
stackoverflow_0074669815_multiprocessing_python_subprocess_tkinter.txt
|
Q:
Is it normal for Tokio to open this many threads/processes?
Is it normal for Tokio to open this many threads?
top - 19:50:25 up 5:55, 2 users, load average: 0.00, 0.00, 0.00
Threads: 9 total, 0 running, 9 sleeping, 0 stopped, 0 zombie
%Cpu(s): 0.0 us, 0.0 sy, 0.0 ni,100.0 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st
MiB Mem : 19963.7 total, 19046.5 free, 268.3 used, 648.9 buff/cache
MiB Swap: 0.0 total, 0.0 free, 0.0 used. 19449.8 avail Mem
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
1665 root 20 0 17556 4 0 S 0.0 0.0 0:00.00 nfwd
1666 root 20 0 17556 4 0 S 0.0 0.0 0:00.00 tokio-runtime-w
1667 root 20 0 17556 4 0 S 0.0 0.0 0:00.00 tokio-runtime-w
1668 root 20 0 17556 4 0 S 0.0 0.0 0:00.00 tokio-runtime-w
1669 root 20 0 17556 4 0 S 0.0 0.0 0:00.00 tokio-runtime-w
1670 root 20 0 17556 4 0 S 0.0 0.0 0:00.00 tokio-runtime-w
1671 root 20 0 17556 4 0 S 0.0 0.0 0:00.00 tokio-runtime-w
1672 root 20 0 17556 4 0 S 0.0 0.0 0:00.00 tokio-runtime-w
1673 root 20 0 17556 4 0 S 0.0 0.0 0:00.00 tokio-runtime-w
All I'm doing is using the tokio::net::UnixListener to listen on a socket. But as you can see in top Tokio has opened 8 different processes/threads named tokio-runtime-w.
What is causing this, it is necessary to have this many and can it be limited/omited?
pub struct StreamServer {
pub socket: UnixListener,
}
impl StreamServer {
pub async fn new() -> Result<Self, Box<dyn Error>> {
let directory = temp_dir();
let path = directory.as_path().join("d");
if path.exists() {
remove_file(&path).await?;
}
let socket = UnixListener::bind(&path)?;
Ok(Self { socket })
}
pub async fn run(&mut self) -> Result<(), Box<dyn Error>> {
loop {
match &self.socket.accept().await {
Ok((stream, addr)) => loop {
match &self.stream.readable().await {
Ok(()) => {
let mut buf = Vec::with_capacity(1024);
match &self.stream.try_read_buf(&mut buf) {
Ok(n) => {
let msg = String::from_utf8((&buf.as_slice()[..*n]).to_vec())?;
Ok((msg, *n))
}
Err(ref e) if e.kind() == ErrorKind::WouldBlock => {
Ok(("".to_string(), 0))
}
Err(e) => todo!("{:?}", e),
}
}
Err(e) => todo!("{:?}", e),
}
},
Err(ref e) if e.kind() == ErrorKind::WouldBlock => {
continue;
}
Err(_) => todo!(),
};
}
}
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let mut stream = StreamServer::new().await?;
stream.run().await?;
}
A:
Yes, this looks like a normal result.
There are a fixed number of worker_threads:
The default value is the number of cores available to the system.
And a dynamic number of blocking_threads:
The default value is 512.
You can configure the Runtime using the methods linked above, or worker_threads is configurable in the attribute like so:
#[tokio::main(worker_threads = 2)]
|
Is it normal for Tokio to open this many threads/processes?
|
Is it normal for Tokio to open this many threads?
top - 19:50:25 up 5:55, 2 users, load average: 0.00, 0.00, 0.00
Threads: 9 total, 0 running, 9 sleeping, 0 stopped, 0 zombie
%Cpu(s): 0.0 us, 0.0 sy, 0.0 ni,100.0 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st
MiB Mem : 19963.7 total, 19046.5 free, 268.3 used, 648.9 buff/cache
MiB Swap: 0.0 total, 0.0 free, 0.0 used. 19449.8 avail Mem
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
1665 root 20 0 17556 4 0 S 0.0 0.0 0:00.00 nfwd
1666 root 20 0 17556 4 0 S 0.0 0.0 0:00.00 tokio-runtime-w
1667 root 20 0 17556 4 0 S 0.0 0.0 0:00.00 tokio-runtime-w
1668 root 20 0 17556 4 0 S 0.0 0.0 0:00.00 tokio-runtime-w
1669 root 20 0 17556 4 0 S 0.0 0.0 0:00.00 tokio-runtime-w
1670 root 20 0 17556 4 0 S 0.0 0.0 0:00.00 tokio-runtime-w
1671 root 20 0 17556 4 0 S 0.0 0.0 0:00.00 tokio-runtime-w
1672 root 20 0 17556 4 0 S 0.0 0.0 0:00.00 tokio-runtime-w
1673 root 20 0 17556 4 0 S 0.0 0.0 0:00.00 tokio-runtime-w
All I'm doing is using the tokio::net::UnixListener to listen on a socket. But as you can see in top Tokio has opened 8 different processes/threads named tokio-runtime-w.
What is causing this, it is necessary to have this many and can it be limited/omited?
pub struct StreamServer {
pub socket: UnixListener,
}
impl StreamServer {
pub async fn new() -> Result<Self, Box<dyn Error>> {
let directory = temp_dir();
let path = directory.as_path().join("d");
if path.exists() {
remove_file(&path).await?;
}
let socket = UnixListener::bind(&path)?;
Ok(Self { socket })
}
pub async fn run(&mut self) -> Result<(), Box<dyn Error>> {
loop {
match &self.socket.accept().await {
Ok((stream, addr)) => loop {
match &self.stream.readable().await {
Ok(()) => {
let mut buf = Vec::with_capacity(1024);
match &self.stream.try_read_buf(&mut buf) {
Ok(n) => {
let msg = String::from_utf8((&buf.as_slice()[..*n]).to_vec())?;
Ok((msg, *n))
}
Err(ref e) if e.kind() == ErrorKind::WouldBlock => {
Ok(("".to_string(), 0))
}
Err(e) => todo!("{:?}", e),
}
}
Err(e) => todo!("{:?}", e),
}
},
Err(ref e) if e.kind() == ErrorKind::WouldBlock => {
continue;
}
Err(_) => todo!(),
};
}
}
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let mut stream = StreamServer::new().await?;
stream.run().await?;
}
|
[
"Yes, this looks like a normal result.\nThere are a fixed number of worker_threads:\n\nThe default value is the number of cores available to the system.\n\nAnd a dynamic number of blocking_threads:\n\nThe default value is 512.\n\nYou can configure the Runtime using the methods linked above, or worker_threads is configurable in the attribute like so:\n#[tokio::main(worker_threads = 2)]\n\n"
] |
[
1
] |
[] |
[] |
[
"asynchronous",
"rust",
"rust_cargo",
"rust_tokio",
"unix"
] |
stackoverflow_0074669733_asynchronous_rust_rust_cargo_rust_tokio_unix.txt
|
Q:
Is parsing state from child component up in react a good practice
I am trying to change the state in the App components from a child components and I fell i would result to an issue later in my app
i tried passing the setFunction down to the child components then having it change the value in the app components
A:
You'll need to be careful while doing it, but yes, you can do it.
Basically the issue you can encounter while doing this is: if the child AND the parent component try to update the state, thus leading to an infinite loop. (child updates the states which leads parent to re-render, and then updates the states, which leads the child to re-render etc...)
But if your parent component only "reads" from it, that's fine.
One another way to pass data to ANY component in your app would be to use React Contexts, but that's only if you need in many places. If that's just between one component and its child, the way you've done it is fine.
A:
In general, it is not a good idea to pass state from a child component to a parent component in React. Instead, it is better to manage the state in the parent component and pass the necessary data and functions to the child components as props. This helps to keep the child components reusable and makes the application easier to manage and maintain.
-------- another way -----------
It depends on the specific scenario and the design of the application. In general, it is better to avoid parsing state from a child component up to the parent in React, as it can lead to unnecessary complexity and can make the code more difficult to manage and maintain. Instead, it is often better to use a state management library like Redux or MobX to manage the global state of the application and allow components to access and update the state in a more organized and predictable way.
A:
It will be easier to use a library to state manage or React context. I highly recommend you eventrix it has a built-in event bus so you can communicate between components by events and manage global state. It's easy to implement and very fast.
|
Is parsing state from child component up in react a good practice
|
I am trying to change the state in the App components from a child components and I fell i would result to an issue later in my app
i tried passing the setFunction down to the child components then having it change the value in the app components
|
[
"You'll need to be careful while doing it, but yes, you can do it.\nBasically the issue you can encounter while doing this is: if the child AND the parent component try to update the state, thus leading to an infinite loop. (child updates the states which leads parent to re-render, and then updates the states, which leads the child to re-render etc...)\nBut if your parent component only \"reads\" from it, that's fine.\nOne another way to pass data to ANY component in your app would be to use React Contexts, but that's only if you need in many places. If that's just between one component and its child, the way you've done it is fine.\n",
"In general, it is not a good idea to pass state from a child component to a parent component in React. Instead, it is better to manage the state in the parent component and pass the necessary data and functions to the child components as props. This helps to keep the child components reusable and makes the application easier to manage and maintain.\n-------- another way -----------\nIt depends on the specific scenario and the design of the application. In general, it is better to avoid parsing state from a child component up to the parent in React, as it can lead to unnecessary complexity and can make the code more difficult to manage and maintain. Instead, it is often better to use a state management library like Redux or MobX to manage the global state of the application and allow components to access and update the state in a more organized and predictable way.\n",
"It will be easier to use a library to state manage or React context. I highly recommend you eventrix it has a built-in event bus so you can communicate between components by events and manage global state. It's easy to implement and very fast.\n"
] |
[
0,
0,
0
] |
[] |
[] |
[
"frontend",
"javascript",
"react_hooks",
"reactjs"
] |
stackoverflow_0074664892_frontend_javascript_react_hooks_reactjs.txt
|
Q:
How do you pull specific information out of a text file? Python
Here is an example of some of the information in the text file:
Ticker : Ticker representing the company | Company: Name | Title: Position of trader | Trade Type: Buy or sell | Value: Monetary value
Ticker : AKUS | Company: Akouos, Inc. | Title: 10% | Trade Type: P - Purchase | Value: +$374,908,350
Ticker : HHC | Company: Howard Hughes Corp | Title: Dir, 10% | Trade Type: P - Purchase | Value: +$109,214,243
Where each time it says ticker, it's a new line. Is there a way to pull out specific information and set it to a dictionary? For example, would I be able to get a dictionary filled with all the tickers, all the positions and all of the monetary values?
A:
The best way I can think of is to import into a dataframe (df), and then convert to a dictionary (if that is what you really want).
Firstly import the data into a pandas dataframe:
import pandas as pd
filename = 'file1.txt'
df = pd.read_csv(filename,
sep = ':\s+|\s\|',
engine='python',
usecols=[1,3,5,7,9]
)
df.columns = ['Ticker', 'Company', 'Title', 'Trade Type', 'Value']
print(df)
This is the dataframe:
You can then convert this into a dictionary using the following code:
data_dictionary = df.to_dict()
print(data_dictionary)
OUTPUT:
{'Ticker': {0: 'AKUS', 1: 'HHC'}, 'Company': {0: 'Akouos, Inc.', 1: 'Howard Hughes Corp'}, 'Title': {0: '10%', 1: 'Dir, 10%'}, 'Trade Type': {0: 'P - Purchase', 1: 'P - Purchase'}, 'Value': {0: '+$374,908,350', 1: '+$109,214,243'}}
Dict Usage
Should you actually want to use the dictionary for retrieval (instead of the dataframe), and if you would want to search based on ticker symbols. Then this is how I would approach it:
Search for Value of ticker symbol 'AKUS'
tickers = {v:k for k,v in data_dictionary.get('Ticker').items()}
print('AKUS Value:', data_dictionary['Value'][tickers.get('AKUS')])
Output:
AKUS Value: +$374,908,350
A:
My suggestion would be that the dictionary should be keyed on ticker name. Each value for the ticker is itself a dictionary which makes access to the data very easy. Something like this:
ticker = {}
with open('ticker.txt') as tdata:
next(tdata) # skip first line
for row in tdata:
if columns := row.split('|'):
_, t = columns[0].split(':')
ticker[t.strip()] = {k.strip(): v.strip() for k, v in [column.split(':') for column in columns[1:]]}
print(ticker)
Output:
{'AKUS': {'Company': 'Akouos, Inc.', 'Title': '10%', 'Trade Type': 'P - Purchase', 'Value': '+$374,908,350'}, 'HHC': {'Company': 'Howard Hughes Corp', 'Title': 'Dir, 10%', 'Trade Type': 'P - Purchase', 'Value': '+$109,214,243'}}
Usage:
For example, to get the value associated with HHC then it's:
ticker['HHC']['Value']
|
How do you pull specific information out of a text file? Python
|
Here is an example of some of the information in the text file:
Ticker : Ticker representing the company | Company: Name | Title: Position of trader | Trade Type: Buy or sell | Value: Monetary value
Ticker : AKUS | Company: Akouos, Inc. | Title: 10% | Trade Type: P - Purchase | Value: +$374,908,350
Ticker : HHC | Company: Howard Hughes Corp | Title: Dir, 10% | Trade Type: P - Purchase | Value: +$109,214,243
Where each time it says ticker, it's a new line. Is there a way to pull out specific information and set it to a dictionary? For example, would I be able to get a dictionary filled with all the tickers, all the positions and all of the monetary values?
|
[
"The best way I can think of is to import into a dataframe (df), and then convert to a dictionary (if that is what you really want).\n\nFirstly import the data into a pandas dataframe:\nimport pandas as pd\n\nfilename = 'file1.txt'\n\ndf = pd.read_csv(filename,\n sep = ':\\s+|\\s\\|',\n engine='python',\n usecols=[1,3,5,7,9]\n )\ndf.columns = ['Ticker', 'Company', 'Title', 'Trade Type', 'Value']\n\nprint(df)\n\n\nThis is the dataframe:\n\n\n\nYou can then convert this into a dictionary using the following code:\ndata_dictionary = df.to_dict()\nprint(data_dictionary)\n\nOUTPUT:\n{'Ticker': {0: 'AKUS', 1: 'HHC'}, 'Company': {0: 'Akouos, Inc.', 1: 'Howard Hughes Corp'}, 'Title': {0: '10%', 1: 'Dir, 10%'}, 'Trade Type': {0: 'P - Purchase', 1: 'P - Purchase'}, 'Value': {0: '+$374,908,350', 1: '+$109,214,243'}}\n\n\n\nDict Usage\nShould you actually want to use the dictionary for retrieval (instead of the dataframe), and if you would want to search based on ticker symbols. Then this is how I would approach it:\n\nSearch for Value of ticker symbol 'AKUS'\ntickers = {v:k for k,v in data_dictionary.get('Ticker').items()}\n\nprint('AKUS Value:', data_dictionary['Value'][tickers.get('AKUS')])\n\nOutput:\nAKUS Value: +$374,908,350\n\n",
"My suggestion would be that the dictionary should be keyed on ticker name. Each value for the ticker is itself a dictionary which makes access to the data very easy. Something like this:\nticker = {}\n\nwith open('ticker.txt') as tdata:\n next(tdata) # skip first line\n for row in tdata:\n if columns := row.split('|'):\n _, t = columns[0].split(':')\n ticker[t.strip()] = {k.strip(): v.strip() for k, v in [column.split(':') for column in columns[1:]]}\n\nprint(ticker)\n\nOutput:\n{'AKUS': {'Company': 'Akouos, Inc.', 'Title': '10%', 'Trade Type': 'P - Purchase', 'Value': '+$374,908,350'}, 'HHC': {'Company': 'Howard Hughes Corp', 'Title': 'Dir, 10%', 'Trade Type': 'P - Purchase', 'Value': '+$109,214,243'}}\n\nUsage:\nFor example, to get the value associated with HHC then it's:\nticker['HHC']['Value']\n\n"
] |
[
2,
1
] |
[] |
[] |
[
"python",
"txt"
] |
stackoverflow_0074669178_python_txt.txt
|
Q:
Fastest way to get ONLY unique values from array?
I have an array like this
students = [{name: 'Abbey', age: 25}, {name: 'Brian', age: 45},
{name: 'Colin', age: 25}, {name: 'Dan', age: 78}]
and I want the output to be;
uniqueAges = [45, 78]
To be clear, if there is an age value that appears more than once in the students array, I do not want any of the objects with that age in my uniqueAges array. 'Abbey' and 'Colin' have the same age so they are both out.
I know I can do something like this and run uniqueAgeGetter(students)
function uniqueAgeGetter(list){
var listCopy = list.slice();
var uniqueAges = list.slice();
for (var i = list.length - 1; i >= 0; i--) {
for (var j = listCopy.length - 1; j >= 0; j--) {
if(listCopy[j].name !== list[i].name &&
listCopy[j].age == list[i].age){
uniqueAges.splice(i, 1)
}
}
}
console.log(uniqueAges)
return uniqueAges
}
But is it possible to do it without a second loop? I'm not an expert on time complexity but I am trying to find if it is possible this task can be O(n).
Edit:
I am not asking if uniqueAgeGetter be rewritten to read nicer or use functions like map, reduce or filter (as my understanding is they are ultimately a loop as well).
My question is can uniqueAgeGetter be refactored in a way that reduces the time complexity? Can it be done with only one loop?
Thank you.
A:
This can be done in O(n) time by counting the number of times an age has been seen, and filtering out the ages with a count more than one.
Since ages have reasonable limits, we can use an integer array of length equal to the maximum possible age to store the age counts. In the example below, I take the maximum possible age to be a comfortable 200.
var students = [
{name: 'Abbey', age: 25 },
{name: 'Brian', age: 45 },
{name: 'Colin', age: 25 },
{name: 'Dan', age: 78 }
];
var studentAges = students.map(val => val.age);
var ageCounts = Array(200).fill(0);
studentAges.forEach(age => ageCounts[age] += 1);
var uniqueAges = studentAges.filter(age => ageCounts[age] == 1);
console.log(uniqueAges);
A:
The first idea, we can do over two step:
Step1: Sort the array
-- There are many algorithms to do it. As I know, currently, the complexity of best algorithm now is O(Nlog(N)) with N is the number of array.
Step2: Remove the duplicated elements
-- The complexity of this step is O(N)
So, over two steps, the complexity is O(N) + O(Nlog(N)). Finally, the complexity is O(Nlog(N))
The second idea
This also has the complexity is O(Nlog(N)) but it will be O(N) for next time you want to get the unique age.
Instead of saving the data in array, you can rebuild in a binary search tree with a little custom. This node in this tree will save all the elements with same age.
The complexity for the first time you build the tree is O(Nlog(N))
About the algorithm which has the complexity is O(N), currently, I think there are no technique to solve it. :D
A:
You can use reduce
The first reduce is to summarise the array and convert it into an object using the age as a the key. Using the age as the key will make it easier to check if the age already exist. The object properties will have an array value like [2,true], where the first element is the age and the second element tells if the age has duplicates. Using Object.values will convert the object into an array.
The second reduce is to form the desired output.
let students = [{name: 'Abbey', age: 25 }, {name: 'Brian', age: 45 },{name: 'Colin', age: 25 }, {name: 'Dan', age: 78 }];
let uniqueAges = Object.values(students.reduce((c, v) => {
if (c[v.age] === undefined) c[v.age] = [v.age, true];
else c[v.age][1] = false;
return c;
}, {})).reduce((c, v) => {
if (v[1]) c.push(v[0]);
return c;
}, []);
console.log(uniqueAges);
A:
Here is one way you could do it. I think the time complexity would be O(n^2) where n is the number of elements in the original array and m is the number of unique elements in the output array.
const students = [
{name: 'Abbey', age: 25 },
{name: 'Brian', age: 45 },
{name: 'Colin', age: 25 },
{name: 'Dan', age: 78 }
];
const uniqueStudents = students.map(val => val.age)
.sort()
.reduce((current, next) => {
return current.length === 0 ? [].concat(current, next)
: current[current.length - 1] !== next ? [].concat(current, next)
: current.slice(0, -1);
}, []);
console.log(uniqueStudents);
A:
The fastest way with a single iteration.
const students = [
{name: `Abbey`, age: 25},
{name: `Brian`, age: 45},
{name: `Colin`, age: 25},
{name: `Dan`, age: 78},
{name: `Dan`, age: 25}
]
// no global variables
function unique(key) {
const occurrences = {}
const list = {}
return (result, next, index, {length}) => {
const value = next[key]
if (list[value]) {
occurrences[value] = value
}
else {
list[value] = value
result.push(value)
}
return index === length - 1 ? result.filter(v => !occurrences[v]) : result
}
}
const uniqueNames = students.reduce(unique(`name`), [])
const uniqueAges = students.reduce(unique(`age`), [])
console.log(uniqueAges)
A:
for getting unique elements
const data = [128, 128,128,121,127,127,121,121,121,121,122,125];
const uniqueData = Object.keys(data.reduce((r,c) => {r[c] = true; return r;}, {}))
console.log(uniqueData)
But doing this will sort the array and will not keep the original order of the array
Complexity O(n)
|
Fastest way to get ONLY unique values from array?
|
I have an array like this
students = [{name: 'Abbey', age: 25}, {name: 'Brian', age: 45},
{name: 'Colin', age: 25}, {name: 'Dan', age: 78}]
and I want the output to be;
uniqueAges = [45, 78]
To be clear, if there is an age value that appears more than once in the students array, I do not want any of the objects with that age in my uniqueAges array. 'Abbey' and 'Colin' have the same age so they are both out.
I know I can do something like this and run uniqueAgeGetter(students)
function uniqueAgeGetter(list){
var listCopy = list.slice();
var uniqueAges = list.slice();
for (var i = list.length - 1; i >= 0; i--) {
for (var j = listCopy.length - 1; j >= 0; j--) {
if(listCopy[j].name !== list[i].name &&
listCopy[j].age == list[i].age){
uniqueAges.splice(i, 1)
}
}
}
console.log(uniqueAges)
return uniqueAges
}
But is it possible to do it without a second loop? I'm not an expert on time complexity but I am trying to find if it is possible this task can be O(n).
Edit:
I am not asking if uniqueAgeGetter be rewritten to read nicer or use functions like map, reduce or filter (as my understanding is they are ultimately a loop as well).
My question is can uniqueAgeGetter be refactored in a way that reduces the time complexity? Can it be done with only one loop?
Thank you.
|
[
"This can be done in O(n) time by counting the number of times an age has been seen, and filtering out the ages with a count more than one.\nSince ages have reasonable limits, we can use an integer array of length equal to the maximum possible age to store the age counts. In the example below, I take the maximum possible age to be a comfortable 200.\n\n\nvar students = [\r\n {name: 'Abbey', age: 25 }, \r\n {name: 'Brian', age: 45 },\r\n {name: 'Colin', age: 25 }, \r\n {name: 'Dan', age: 78 }\r\n];\r\n\r\nvar studentAges = students.map(val => val.age);\r\nvar ageCounts = Array(200).fill(0);\r\n\r\nstudentAges.forEach(age => ageCounts[age] += 1);\r\n\r\nvar uniqueAges = studentAges.filter(age => ageCounts[age] == 1);\r\n\r\nconsole.log(uniqueAges);\n\n\n\n",
"\nThe first idea, we can do over two step:\nStep1: Sort the array\n-- There are many algorithms to do it. As I know, currently, the complexity of best algorithm now is O(Nlog(N)) with N is the number of array.\nStep2: Remove the duplicated elements\n-- The complexity of this step is O(N)\nSo, over two steps, the complexity is O(N) + O(Nlog(N)). Finally, the complexity is O(Nlog(N))\nThe second idea\nThis also has the complexity is O(Nlog(N)) but it will be O(N) for next time you want to get the unique age.\nInstead of saving the data in array, you can rebuild in a binary search tree with a little custom. This node in this tree will save all the elements with same age.\nThe complexity for the first time you build the tree is O(Nlog(N))\n\nAbout the algorithm which has the complexity is O(N), currently, I think there are no technique to solve it. :D\n",
"You can use reduce\nThe first reduce is to summarise the array and convert it into an object using the age as a the key. Using the age as the key will make it easier to check if the age already exist. The object properties will have an array value like [2,true], where the first element is the age and the second element tells if the age has duplicates. Using Object.values will convert the object into an array.\nThe second reduce is to form the desired output.\n\n\nlet students = [{name: 'Abbey', age: 25 }, {name: 'Brian', age: 45 },{name: 'Colin', age: 25 }, {name: 'Dan', age: 78 }];\r\n\r\nlet uniqueAges = Object.values(students.reduce((c, v) => {\r\n if (c[v.age] === undefined) c[v.age] = [v.age, true];\r\n else c[v.age][1] = false;\r\n return c;\r\n}, {})).reduce((c, v) => {\r\n if (v[1]) c.push(v[0]);\r\n return c;\r\n}, []);\r\n\r\nconsole.log(uniqueAges);\n\n\n\n",
"Here is one way you could do it. I think the time complexity would be O(n^2) where n is the number of elements in the original array and m is the number of unique elements in the output array.\n\n\nconst students = [\r\n {name: 'Abbey', age: 25 }, \r\n {name: 'Brian', age: 45 },\r\n {name: 'Colin', age: 25 }, \r\n {name: 'Dan', age: 78 }\r\n];\r\n\r\nconst uniqueStudents = students.map(val => val.age)\r\n .sort()\r\n .reduce((current, next) => {\r\n return current.length === 0 ? [].concat(current, next)\r\n : current[current.length - 1] !== next ? [].concat(current, next)\r\n : current.slice(0, -1);\r\n }, []);\r\n \r\nconsole.log(uniqueStudents);\n\n\n\n",
" The fastest way with a single iteration.\n\n\nconst students = [\r\n {name: `Abbey`, age: 25}, \r\n {name: `Brian`, age: 45},\r\n {name: `Colin`, age: 25}, \r\n {name: `Dan`, age: 78},\r\n {name: `Dan`, age: 25}\r\n]\r\n\r\n// no global variables\r\nfunction unique(key) {\r\n const occurrences = {}\r\n const list = {}\r\n return (result, next, index, {length}) => {\r\n const value = next[key]\r\n if (list[value]) {\r\n occurrences[value] = value\r\n }\r\n else {\r\n list[value] = value\r\n result.push(value)\r\n }\r\n return index === length - 1 ? result.filter(v => !occurrences[v]) : result\r\n }\r\n}\r\n\r\nconst uniqueNames = students.reduce(unique(`name`), [])\r\nconst uniqueAges = students.reduce(unique(`age`), [])\r\n\r\nconsole.log(uniqueAges)\n\n\n\n",
"for getting unique elements\n\n\nconst data = [128, 128,128,121,127,127,121,121,121,121,122,125];\nconst uniqueData = Object.keys(data.reduce((r,c) => {r[c] = true; return r;}, {}))\nconsole.log(uniqueData)\n\n\n\nBut doing this will sort the array and will not keep the original order of the array\nComplexity O(n)\n"
] |
[
5,
3,
1,
0,
0,
0
] |
[] |
[] |
[
"algorithm",
"javascript",
"node.js",
"time_complexity"
] |
stackoverflow_0049269452_algorithm_javascript_node.js_time_complexity.txt
|
Q:
Xamarin.Essentials.Preferences set/get with generic type in Xamarin.Forms
public class PreferenceManager
{
private static PreferenceManager _instance = null;
private static readonly object _lock = new object();
private PreferenceManager() { }
public static PreferenceManager Instance
{
get
{
lock (_lock)
{
if (_instance == null)
_instance = new PreferenceManager();
return _instance;
}
}
}
public void SetPreference<T>(string key, T value)
{
Preferences.Set(key, value);
}
public T GetPreference<T>(string key)
{
object value = Preferences.Get(key, null);
return (T)Convert.ChangeType(value, typeof(T));
}
}
I'd like to make wrapper class for manage all process about Xamarin.Essentials.Preferences.
There are so many overrides with different types for getting/setting in Essentials class.
So, I tried to change return value with generic and set value also, because I think it looks more simple.
But, there is an error in SetPreference method : cannot convert from 'T' to 'string'.
Is there any good solution for making wrapper class?
I want to handle all processes in here with one method.... :-(
A:
According to Xamarin Essentials Preferences.shared.cs on Github, set method in Preferences doesn't support generic type. So we could not wrap it in a generic setter directly.
And only seven data types are supported in Xamarin Preferences accoridng to Xamarin.Essentials: Preferences. I could only code for each data types like the following code:
public void SetPreference<T>(string key,T value)
{
if (value is string)
{
Preferences.Set(key, Convert.ToString(value));
}
if (value is double)
{
Preferences.Set(key, Convert.ToDouble(value));
}
...
}
Hope it works for you.
A:
If you want to store classes only, you could simply use a serializer:
public class PreferenceManager
{
private static readonly Lazy<PreferenceManager> LazyInstance = new Lazy<PreferenceManager>(() => new PreferenceManager());
private PreferenceManager() { }
public static PreferenceManager Instance => LazyInstance.Value;
public void SetPreference<T>(string key, T value) where T : class => Preferences.Set(key, JsonSerializer.Serialize(value));
public T GetPreference<T>(string key) where T : class => Preferences.Get(key, null) is string value
? JsonSerializer.Deserialize<T>(value)
: default;
}
If you want to store also non-classes, then easiest way would to wrap the object into a class:
public class PreferenceManager
{
private static readonly Lazy<PreferenceManager> LazyInstance = new(() => new PreferenceManager());
private PreferenceManager() { }
public static PreferenceManager Instance => LazyInstance.Value;
public void SetPreference<T>(string key, T value) => Preferences.Set(key, JsonSerializer.Serialize(new StoredObject<T>(value)));
public T GetPreference<T>(string key)
{
var o = Preferences.Get(key, null) is { } value
? JsonSerializer.Deserialize<StoredObject<T>>(value)
: null;
return o is not null ? o.Value : default;
}
internal class StoredObject<T>
{
internal StoredObject(T value)
{
Value = value;
}
internal T Value { get; }
}
}
|
Xamarin.Essentials.Preferences set/get with generic type in Xamarin.Forms
|
public class PreferenceManager
{
private static PreferenceManager _instance = null;
private static readonly object _lock = new object();
private PreferenceManager() { }
public static PreferenceManager Instance
{
get
{
lock (_lock)
{
if (_instance == null)
_instance = new PreferenceManager();
return _instance;
}
}
}
public void SetPreference<T>(string key, T value)
{
Preferences.Set(key, value);
}
public T GetPreference<T>(string key)
{
object value = Preferences.Get(key, null);
return (T)Convert.ChangeType(value, typeof(T));
}
}
I'd like to make wrapper class for manage all process about Xamarin.Essentials.Preferences.
There are so many overrides with different types for getting/setting in Essentials class.
So, I tried to change return value with generic and set value also, because I think it looks more simple.
But, there is an error in SetPreference method : cannot convert from 'T' to 'string'.
Is there any good solution for making wrapper class?
I want to handle all processes in here with one method.... :-(
|
[
"According to Xamarin Essentials Preferences.shared.cs on Github, set method in Preferences doesn't support generic type. So we could not wrap it in a generic setter directly.\nAnd only seven data types are supported in Xamarin Preferences accoridng to Xamarin.Essentials: Preferences. I could only code for each data types like the following code:\npublic void SetPreference<T>(string key,T value)\n{\n if (value is string)\n {\n Preferences.Set(key, Convert.ToString(value)); \n }\n if (value is double)\n {\n Preferences.Set(key, Convert.ToDouble(value));\n }\n ...\n}\n\nHope it works for you.\n",
"If you want to store classes only, you could simply use a serializer:\n public class PreferenceManager\n {\n private static readonly Lazy<PreferenceManager> LazyInstance = new Lazy<PreferenceManager>(() => new PreferenceManager());\n\n private PreferenceManager() { }\n public static PreferenceManager Instance => LazyInstance.Value;\n\n public void SetPreference<T>(string key, T value) where T : class => Preferences.Set(key, JsonSerializer.Serialize(value));\n\n public T GetPreference<T>(string key) where T : class => Preferences.Get(key, null) is string value\n ? JsonSerializer.Deserialize<T>(value)\n : default;\n }\n\nIf you want to store also non-classes, then easiest way would to wrap the object into a class:\npublic class PreferenceManager\n{\n private static readonly Lazy<PreferenceManager> LazyInstance = new(() => new PreferenceManager());\n\n private PreferenceManager() { }\n public static PreferenceManager Instance => LazyInstance.Value;\n\n public void SetPreference<T>(string key, T value) => Preferences.Set(key, JsonSerializer.Serialize(new StoredObject<T>(value)));\n\n public T GetPreference<T>(string key)\n {\n var o = Preferences.Get(key, null) is { } value\n ? JsonSerializer.Deserialize<StoredObject<T>>(value)\n : null;\n\n return o is not null ? o.Value : default;\n }\n\n internal class StoredObject<T>\n {\n internal StoredObject(T value)\n {\n Value = value;\n }\n\n internal T Value { get; }\n }\n}\n\n"
] |
[
1,
0
] |
[] |
[] |
[
"c#",
"generics",
"xamarin",
"xamarin.essentials",
"xamarin.forms"
] |
stackoverflow_0074649728_c#_generics_xamarin_xamarin.essentials_xamarin.forms.txt
|
Q:
Header and Footer in .NET MAUI
I wanted to do the same as this question, but for .NET MAUI:
Same header & footer in all WPF windows
It is same header and footer for all windows.
A:
If you don't want to click the link @Jason provided in the comment, here is a shortened version.
PageLayout.xaml file:
<ContentPage ...>
<Grid RowDefinitions="Auto,*,Auto">
<!--Row 1 : Header-->
<Grid>
<!--header content-->
</Grid>
<!--Row 2 : Content-->
<Grid Grid.Row="1"
Name="PrimaryPageLayout">
</Grid>
<!--Row 3 : Footer-->
<Grid Grid.Row="2">
<!--footer content-->
</Grid>
</Grid>
</ContentPage>
PageLayout.xaml.cs file :
public partial class PageLayout : ContentPage
{
public IList<IView> PageLayoutContent => PrimaryPageLayout.Children;
public PageLayout()
{
InitializeComponent();
}
}
SubView.xaml file:
<PageLayout ... >
<views:PageLayout.PageLayoutContent>
<!--Main content-->
</views:PageLayout.PageLayoutContent>
</PageLayout>
|
Header and Footer in .NET MAUI
|
I wanted to do the same as this question, but for .NET MAUI:
Same header & footer in all WPF windows
It is same header and footer for all windows.
|
[
"If you don't want to click the link @Jason provided in the comment, here is a shortened version.\nPageLayout.xaml file:\n<ContentPage ...>\n\n <Grid RowDefinitions=\"Auto,*,Auto\">\n\n <!--Row 1 : Header-->\n <Grid>\n <!--header content-->\n </Grid>\n\n <!--Row 2 : Content-->\n <Grid Grid.Row=\"1\"\n Name=\"PrimaryPageLayout\">\n </Grid>\n\n <!--Row 3 : Footer-->\n <Grid Grid.Row=\"2\">\n <!--footer content-->\n </Grid>\n \n </Grid>\n</ContentPage>\n\nPageLayout.xaml.cs file :\npublic partial class PageLayout : ContentPage\n{\n public IList<IView> PageLayoutContent => PrimaryPageLayout.Children;\n\n public PageLayout()\n {\n InitializeComponent();\n }\n}\n\nSubView.xaml file:\n<PageLayout ... >\n <views:PageLayout.PageLayoutContent>\n <!--Main content-->\n </views:PageLayout.PageLayoutContent>\n</PageLayout>\n\n"
] |
[
1
] |
[] |
[] |
[
"maui",
"xaml"
] |
stackoverflow_0074668855_maui_xaml.txt
|
Q:
How to customize dj-rest-auth Login serializer
I am using dj-rest-auth, django-allauth and djangorestframework-simplejwt.I want to customize dj-rest-auth Login serializer to include the following additional fields: (first_name, last_name, phone_number), validate them, authenticate them and login properly. Also i am using email instead of username as my main identifier.
This is my Custom User Model:
from django.db import models
from django.contrib.auth.models import AbstractUser, BaseUserManager
from phonenumber_field.modelfields import PhoneNumberField
class CustomUserManager(BaseUserManager):
def _create_user(self, email, password, **extra_fields):
if not email:
raise ValueError("An email has to be set")
user = self.model(email=self.normalize_email(email), **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, email, password, **extra_fields):
extra_fields.setdefault("is_staff", False)
extra_fields.setdefault("is_superuser", False)
return self._create_user(email, password, **extra_fields)
def create_superuser(self, email, password, **extra_fields):
extra_fields.setdefault("is_staff", True)
extra_fields.setdefault("is_superuser", True)
if extra_fields.get("is_staff") is not True:
raise ValueError("Superuser must have is_staff=True.")
if extra_fields.get("is_superuser") is not True:
raise ValueError("Superuser must have is_superuser=True.")
return self._create_user(email, password, **extra_fields)
class CustomUserModel(AbstractUser):
username = None
email = models.EmailField(unique=True)
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
phone_number = PhoneNumberField()
bio = models.TextField(null=True, blank=True)
age = models.PositiveIntegerField(null=True, blank=True)
USERNAME_FIELD = "email"
REQUIRED_FIELDS = [
"first_name",
"last_name",
"phone_number",
]
def __str__(self):
return self.first_name + " " + self.last_name
objects = CustomUserManager()
This is my serializer.py:
from django.conf import settings
from django.contrib.auth import get_user_model, authenticate
from rest_framework import serializers, exceptions
from dj_rest_auth.registration.serializers import RegisterSerializer
from dj_rest_auth.serializers import LoginSerializer
from allauth.account.adapter import get_adapter
from phonenumber_field.serializerfields import PhoneNumberField
class UserListSerializer(serializers.ModelSerializer):
class Meta:
model = get_user_model()
read_only_fields = [
"id",
"is_superuser",
"first_name",
"last_name",
"phone_number",
"bio",
"age",
"date_joined",
]
fields = [
"id",
"is_superuser",
"first_name",
"last_name",
"phone_number",
"bio",
"age",
"date_joined",
]
class UserDetailSerializer(serializers.ModelSerializer):
class Meta:
model = get_user_model()
fields = [
"id",
"is_superuser",
"email",
"password",
"first_name",
"last_name",
"phone_number",
"date_joined",
"last_login",
"bio",
"age",
]
read_only_fields = [
"is_superuser",
"password",
]
class CustomRegisterSerializer(RegisterSerializer):
username = None
first_name = serializers.CharField(max_length=50)
last_name = serializers.CharField(max_length=50)
phone_number = PhoneNumberField()
class Meta:
model = get_user_model()
fields = [
"email",
"first_name",
"last_name",
"phone_number",
"password",
]
def get_cleaned_data(self):
return {
"email": self.validated_data.get("email", ""),
"first_name": self.validated_data.get("first_name", ""),
"last_name": self.validated_data.get("last_name", ""),
"phone_number": self.validated_data.get("phone_number", ""),
"password1": self.validated_data.get("password1", ""),
"password2": self.validated_data.get("password2", ""),
}
def save(self, request):
adapter = get_adapter()
user = adapter.new_user(request)
self.cleaned_data = self.get_cleaned_data()
user.first_name = self.cleaned_data.get("first_name")
user.last_name = self.cleaned_data.get("last_name")
user.phone_number = self.cleaned_data.get("phone_number")
user.save()
adapter.save_user(request, user, self)
return user
UserModel = get_user_model()
class CustomLoginSerializer(LoginSerializer):
username = None
first_name = serializers.CharField()
last_name = serializers.CharField()
phone_number = PhoneNumberField()
def authenticate(self, **options):
return authenticate(self.context["request"], **options)
def validate(self, attrs):
email = attrs.get("email")
first_name = attrs.get("first_name")
last_name = attrs.get("last_name")
phone_number = attrs.get("phone_number")
password = attrs.get("password")
if email and first_name and last_name and phone_number and password:
user = authenticate(
email=email,
first_name=first_name,
last_name=last_name,
phone_number=phone_number,
pasword=password,
)
if not user:
msg = "Incorrect credentials."
raise serializers.ValidationError(msg, code="authorization")
else:
msg = "No email provided."
raise exceptions.ValidationError(msg)
attrs["user"] = user
return attrs
This is my views.py:
from django.contrib.auth import get_user_model
from rest_framework import generics
from .serializers import UserListSerializer, UserDetailSerializer
class UserListView(generics.ListCreateAPIView):
queryset = get_user_model().objects.all()
serializer_class = UserListSerializer
class UserDetailView(generics.RetrieveUpdateDestroyAPIView):
queryset = get_user_model().objects.all()
serializer_class = UserDetailSerializer
I have all the settings setup correctly, so i have no problems there. My custom registration work fine too, eveything works fine. I just can't correctly override the Loginserializer. And for my endpoint url i am using dj-rest-auth 's default "dj-rest-auth/registration/" address.
A:
I hope you were able to find the right way to do it. I also had the same issue with LoginSerializer until I've added this to settings.py
ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_EMAIL_REQUIRED = True
This is my serializers.py
class AccountLoginSerializer(LoginSerializer):
username = None
def authenticate(self, **options):
return authenticate(self.context["request"], **options)
def validate(self, attrs):
email = attrs.get("email")
ip_address = get_client_ip(self.context["request"])[0]
password = attrs.get("password")
if email and password:
'''Check if IP address belongs to account with given email address'''
try:
if Account.objects.get(email=email).ip_address.filter(ip_address=ip_address).exists():
user = authenticate(
email=email,
password=password,
)
else:
msg = "IP address doesn't match. An email has been sent to verify this IP address."
raise serializers.ValidationError(msg, code="authorization")
if not user:
msg = "Invalid credentials."
raise serializers.ValidationError(msg, code="authorization")
except ObjectDoesNotExist:
msg = "Invalid credentials."
raise serializers.ValidationError(msg, code="authorization")
else:
msg = "No email provided."
raise exceptions.ValidationError(msg)
attrs["user"] = user
return attrs
Hope it helps someone with the same issue.
|
How to customize dj-rest-auth Login serializer
|
I am using dj-rest-auth, django-allauth and djangorestframework-simplejwt.I want to customize dj-rest-auth Login serializer to include the following additional fields: (first_name, last_name, phone_number), validate them, authenticate them and login properly. Also i am using email instead of username as my main identifier.
This is my Custom User Model:
from django.db import models
from django.contrib.auth.models import AbstractUser, BaseUserManager
from phonenumber_field.modelfields import PhoneNumberField
class CustomUserManager(BaseUserManager):
def _create_user(self, email, password, **extra_fields):
if not email:
raise ValueError("An email has to be set")
user = self.model(email=self.normalize_email(email), **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, email, password, **extra_fields):
extra_fields.setdefault("is_staff", False)
extra_fields.setdefault("is_superuser", False)
return self._create_user(email, password, **extra_fields)
def create_superuser(self, email, password, **extra_fields):
extra_fields.setdefault("is_staff", True)
extra_fields.setdefault("is_superuser", True)
if extra_fields.get("is_staff") is not True:
raise ValueError("Superuser must have is_staff=True.")
if extra_fields.get("is_superuser") is not True:
raise ValueError("Superuser must have is_superuser=True.")
return self._create_user(email, password, **extra_fields)
class CustomUserModel(AbstractUser):
username = None
email = models.EmailField(unique=True)
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
phone_number = PhoneNumberField()
bio = models.TextField(null=True, blank=True)
age = models.PositiveIntegerField(null=True, blank=True)
USERNAME_FIELD = "email"
REQUIRED_FIELDS = [
"first_name",
"last_name",
"phone_number",
]
def __str__(self):
return self.first_name + " " + self.last_name
objects = CustomUserManager()
This is my serializer.py:
from django.conf import settings
from django.contrib.auth import get_user_model, authenticate
from rest_framework import serializers, exceptions
from dj_rest_auth.registration.serializers import RegisterSerializer
from dj_rest_auth.serializers import LoginSerializer
from allauth.account.adapter import get_adapter
from phonenumber_field.serializerfields import PhoneNumberField
class UserListSerializer(serializers.ModelSerializer):
class Meta:
model = get_user_model()
read_only_fields = [
"id",
"is_superuser",
"first_name",
"last_name",
"phone_number",
"bio",
"age",
"date_joined",
]
fields = [
"id",
"is_superuser",
"first_name",
"last_name",
"phone_number",
"bio",
"age",
"date_joined",
]
class UserDetailSerializer(serializers.ModelSerializer):
class Meta:
model = get_user_model()
fields = [
"id",
"is_superuser",
"email",
"password",
"first_name",
"last_name",
"phone_number",
"date_joined",
"last_login",
"bio",
"age",
]
read_only_fields = [
"is_superuser",
"password",
]
class CustomRegisterSerializer(RegisterSerializer):
username = None
first_name = serializers.CharField(max_length=50)
last_name = serializers.CharField(max_length=50)
phone_number = PhoneNumberField()
class Meta:
model = get_user_model()
fields = [
"email",
"first_name",
"last_name",
"phone_number",
"password",
]
def get_cleaned_data(self):
return {
"email": self.validated_data.get("email", ""),
"first_name": self.validated_data.get("first_name", ""),
"last_name": self.validated_data.get("last_name", ""),
"phone_number": self.validated_data.get("phone_number", ""),
"password1": self.validated_data.get("password1", ""),
"password2": self.validated_data.get("password2", ""),
}
def save(self, request):
adapter = get_adapter()
user = adapter.new_user(request)
self.cleaned_data = self.get_cleaned_data()
user.first_name = self.cleaned_data.get("first_name")
user.last_name = self.cleaned_data.get("last_name")
user.phone_number = self.cleaned_data.get("phone_number")
user.save()
adapter.save_user(request, user, self)
return user
UserModel = get_user_model()
class CustomLoginSerializer(LoginSerializer):
username = None
first_name = serializers.CharField()
last_name = serializers.CharField()
phone_number = PhoneNumberField()
def authenticate(self, **options):
return authenticate(self.context["request"], **options)
def validate(self, attrs):
email = attrs.get("email")
first_name = attrs.get("first_name")
last_name = attrs.get("last_name")
phone_number = attrs.get("phone_number")
password = attrs.get("password")
if email and first_name and last_name and phone_number and password:
user = authenticate(
email=email,
first_name=first_name,
last_name=last_name,
phone_number=phone_number,
pasword=password,
)
if not user:
msg = "Incorrect credentials."
raise serializers.ValidationError(msg, code="authorization")
else:
msg = "No email provided."
raise exceptions.ValidationError(msg)
attrs["user"] = user
return attrs
This is my views.py:
from django.contrib.auth import get_user_model
from rest_framework import generics
from .serializers import UserListSerializer, UserDetailSerializer
class UserListView(generics.ListCreateAPIView):
queryset = get_user_model().objects.all()
serializer_class = UserListSerializer
class UserDetailView(generics.RetrieveUpdateDestroyAPIView):
queryset = get_user_model().objects.all()
serializer_class = UserDetailSerializer
I have all the settings setup correctly, so i have no problems there. My custom registration work fine too, eveything works fine. I just can't correctly override the Loginserializer. And for my endpoint url i am using dj-rest-auth 's default "dj-rest-auth/registration/" address.
|
[
"I hope you were able to find the right way to do it. I also had the same issue with LoginSerializer until I've added this to settings.py\nACCOUNT_AUTHENTICATION_METHOD = 'email'\nACCOUNT_EMAIL_REQUIRED = True\n\nThis is my serializers.py\nclass AccountLoginSerializer(LoginSerializer):\nusername = None\n\ndef authenticate(self, **options):\n return authenticate(self.context[\"request\"], **options)\n\ndef validate(self, attrs):\n email = attrs.get(\"email\")\n ip_address = get_client_ip(self.context[\"request\"])[0]\n password = attrs.get(\"password\")\n if email and password:\n '''Check if IP address belongs to account with given email address'''\n try:\n if Account.objects.get(email=email).ip_address.filter(ip_address=ip_address).exists():\n user = authenticate(\n email=email,\n password=password,\n )\n \n else:\n msg = \"IP address doesn't match. An email has been sent to verify this IP address.\"\n raise serializers.ValidationError(msg, code=\"authorization\")\n if not user:\n msg = \"Invalid credentials.\"\n raise serializers.ValidationError(msg, code=\"authorization\") \n except ObjectDoesNotExist:\n msg = \"Invalid credentials.\"\n raise serializers.ValidationError(msg, code=\"authorization\")\n else:\n msg = \"No email provided.\"\n raise exceptions.ValidationError(msg)\n attrs[\"user\"] = user\n\n return attrs\n\nHope it helps someone with the same issue.\n"
] |
[
0
] |
[] |
[] |
[
"dj_rest_auth",
"django_allauth",
"django_rest_framework",
"django_rest_framework_simplejwt"
] |
stackoverflow_0073455860_dj_rest_auth_django_allauth_django_rest_framework_django_rest_framework_simplejwt.txt
|
Q:
Small file upload to s3 hangs with 100% CPU usage using Paperclip
I have a directory of <20MB pdf files (each pdf represents an ad) on an AWS EC2 large instance. I'm trying to upload each pdf file to S3 using ruby and DM-Paperclip.
Most files upload successfully but some seem to take hours with the CPU hanging at 100%. I've located the line of code that causes the issue by printing debug statements in the relevant section.
# Takes an array of pdf file paths and uploads each to S3 using dm-paperclip
def save_pdfs(pdfs_files)
pdf_files.each do |path|
pdf = File.open(path)
ad = Ad.new
ad.pdf.assign(pdf) # <= Last debug statment is printed before this line
begin
ad.save
rescue => e
# log error
ensure
pdf.close
end
end
To help troubleshoot the issue I attached strace to the process while it was stuck at 100%. The result was hundreds of thousands of lines like this:
...
stat("/etc/localtime", {st_mode=S_IFREG|0644, st_size=3543, ...}) = 0
stat("/etc/localtime", {st_mode=S_IFREG|0644, st_size=3543, ...}) = 0
stat("/etc/localtime", {st_mode=S_IFREG|0644, st_size=3543, ...}) = 0
... 500K lines
Followed by a few thousand:
...
brk(0x1224d0000) = 0x1224d0000
brk(0x1224f3000) = 0x1224f3000
brk(0x122514000) = 0x122514000
...
During an upload that doesn't hang, strace looks like this:
...
ppoll([{fd=12, events=POLLOUT}], 1, NULL, NULL, 8) = 1 ([{fd=12, revents=POLLOUT}])
fstat(12, {st_mode=S_IFSOCK|0777, st_size=0, ...}) = 0
fcntl(12, F_GETFL) = 0x2 (flags O_RDWR)
write(12, "%PDF-1.3\n%\342\343\317\323\n8 0 obj\n<</Filter"..., 4096) = 4096
ppoll([{fd=12, events=POLLOUT}], 1, NULL, NULL, 8) = 1 ([{fd=12, revents=POLLOUT}])
write(12, "S\34\367\23~\277u\272,h\204_\35\215\35\341\347\324\310\307u\370#\364\315\t~^\352\272\26\374"..., 4096) = 4096
ppoll([{fd=12, events=POLLOUT}], 1, NULL, NULL, 8) = 1 ([{fd=12, revents=POLLOUT}])
write(12, "\216%\267\2454`\350\177\4\36\315\211\7B\217g\33\217!e\347\207\256\264\245vy\377\304\256\307\375"..., 4096) = 4096
...
The pdf files that cause this issue seem random. They are all valid pdf files, and they are all relatively small. They vary between ~100KB to ~50MB.
Is the strace with the seemingly excessive stat system calls related to my issue?
A:
Based on the strace output, it appears that your program is stuck in a tight loop of calling the stat() system call on the same file (in this case, /etc/localtime) repeatedly. This could be caused by a bug in the Paperclip library or in your code.
|
Small file upload to s3 hangs with 100% CPU usage using Paperclip
|
I have a directory of <20MB pdf files (each pdf represents an ad) on an AWS EC2 large instance. I'm trying to upload each pdf file to S3 using ruby and DM-Paperclip.
Most files upload successfully but some seem to take hours with the CPU hanging at 100%. I've located the line of code that causes the issue by printing debug statements in the relevant section.
# Takes an array of pdf file paths and uploads each to S3 using dm-paperclip
def save_pdfs(pdfs_files)
pdf_files.each do |path|
pdf = File.open(path)
ad = Ad.new
ad.pdf.assign(pdf) # <= Last debug statment is printed before this line
begin
ad.save
rescue => e
# log error
ensure
pdf.close
end
end
To help troubleshoot the issue I attached strace to the process while it was stuck at 100%. The result was hundreds of thousands of lines like this:
...
stat("/etc/localtime", {st_mode=S_IFREG|0644, st_size=3543, ...}) = 0
stat("/etc/localtime", {st_mode=S_IFREG|0644, st_size=3543, ...}) = 0
stat("/etc/localtime", {st_mode=S_IFREG|0644, st_size=3543, ...}) = 0
... 500K lines
Followed by a few thousand:
...
brk(0x1224d0000) = 0x1224d0000
brk(0x1224f3000) = 0x1224f3000
brk(0x122514000) = 0x122514000
...
During an upload that doesn't hang, strace looks like this:
...
ppoll([{fd=12, events=POLLOUT}], 1, NULL, NULL, 8) = 1 ([{fd=12, revents=POLLOUT}])
fstat(12, {st_mode=S_IFSOCK|0777, st_size=0, ...}) = 0
fcntl(12, F_GETFL) = 0x2 (flags O_RDWR)
write(12, "%PDF-1.3\n%\342\343\317\323\n8 0 obj\n<</Filter"..., 4096) = 4096
ppoll([{fd=12, events=POLLOUT}], 1, NULL, NULL, 8) = 1 ([{fd=12, revents=POLLOUT}])
write(12, "S\34\367\23~\277u\272,h\204_\35\215\35\341\347\324\310\307u\370#\364\315\t~^\352\272\26\374"..., 4096) = 4096
ppoll([{fd=12, events=POLLOUT}], 1, NULL, NULL, 8) = 1 ([{fd=12, revents=POLLOUT}])
write(12, "\216%\267\2454`\350\177\4\36\315\211\7B\217g\33\217!e\347\207\256\264\245vy\377\304\256\307\375"..., 4096) = 4096
...
The pdf files that cause this issue seem random. They are all valid pdf files, and they are all relatively small. They vary between ~100KB to ~50MB.
Is the strace with the seemingly excessive stat system calls related to my issue?
|
[
"Based on the strace output, it appears that your program is stuck in a tight loop of calling the stat() system call on the same file (in this case, /etc/localtime) repeatedly. This could be caused by a bug in the Paperclip library or in your code.\n"
] |
[
0
] |
[
"It appears to be a problem of the original file permissions on failed files sent along with the file from origin computer. All pdf's(files Tobe saved into server) to be 0644 assigned in the script or if script uses original permissions at pickup to send from client.\nBasically the server OS and configurations is rejecting it because the file permissions are not 0644 on write to disc.\n"
] |
[
-1
] |
[
"amazon_s3",
"cpu",
"paperclip",
"upload"
] |
stackoverflow_0018244861_amazon_s3_cpu_paperclip_upload.txt
|
Q:
How do you de-elevate privileges for a child process
I know how to launch a process with Admin privileges from a process using:
proc.StartInfo.UseShellExecute = true;
proc.StartInfo.Verb = "runas";
where proc is a System.Diagnostics.Process. But how does one do the opposite?
If the process you're in is already elevated, how do you launch the new process without admin privileges? More accurately, we need to launch the new process with the same permission level as Windows Explorer, so no change if UAC is disabled, but if UAC is enabled, but our process is running elevated, we need to perform a certain operation un-elevated because we're creating a virtual drive and if it's created with elevated permissions and Windows explorer is running unelevated it won't show up.
Feel free to change the title to something better, I couldn't come up with a good description.
A:
The solution for you is to use EXPLORER.exe process.
The idea is to run the process in UN-ELEVATED mode, using windows's file explorer process explorer.exe (info).
Lets say the process that we want to launch is on $TEMP\MyUnElevatedProcess.exe.
So, for NSIS code, I will just write: (but can be run in ANY language)
Exec '"$WINDIR\explorer.exe" "$TEMP\MyUnElevatedProcess.exe"'
Example code (using NSIS installer)
Exec '"$WINDIR\explorer.exe" "$TEMP\MyUnElevatedProcess.exe"'
***code taken from http://mdb-blog.blogspot.com/2013/01/nsis-lunch-program-as-user-from-uac.html
A:
We ended up using the sample from this Code Project article: High elevation can be bad for your application: How to start a non-elevated process at the end of the installation
It seems to work so far, I gather it injects into RunDll32.exe, my C++/Win32 is fairly weak so I didn't look too much into the actual implementation, just it's use. Confirmed that it works in Vista and Win7 both x86 and x64 (at least for us, x86 and x64 require different dll's which is checked for at install time and the proper one is used).
A:
Raymond Chen addressed this in his blog:
How can I launch an unelevated process from my elevated process and vice versa?
Searching in GitHub for a C# version of this code, I found the following implementation in Microsoft's Node.js tools for Visual Studio repository: SystemUtilities.cs (the ExecuteProcessUnElevated function).
Just in case the file disappears, here's the file's contents:
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Runtime.InteropServices;
namespace Microsoft.NodejsTools.SharedProject
{
/// <summary>
/// Utility for accessing window IShell* interfaces in order to use them to launch a process unelevated
/// </summary>
internal class SystemUtility
{
/// <summary>
/// We are elevated and should launch the process unelevated. We can't create the
/// process directly without it becoming elevated. So to workaround this, we have
/// explorer do the process creation (explorer is typically running unelevated).
/// </summary>
internal static void ExecuteProcessUnElevated(string process, string args, string currentDirectory = "")
{
var shellWindows = (IShellWindows)new CShellWindows();
// Get the desktop window
object loc = CSIDL_Desktop;
object unused = new object();
int hwnd;
var serviceProvider = (IServiceProvider)shellWindows.FindWindowSW(ref loc, ref unused, SWC_DESKTOP, out hwnd, SWFO_NEEDDISPATCH);
// Get the shell browser
var serviceGuid = SID_STopLevelBrowser;
var interfaceGuid = typeof(IShellBrowser).GUID;
var shellBrowser = (IShellBrowser)serviceProvider.QueryService(ref serviceGuid, ref interfaceGuid);
// Get the shell dispatch
var dispatch = typeof(IDispatch).GUID;
var folderView = (IShellFolderViewDual)shellBrowser.QueryActiveShellView().GetItemObject(SVGIO_BACKGROUND, ref dispatch);
var shellDispatch = (IShellDispatch2)folderView.Application;
// Use the dispatch (which is unelevated) to launch the process for us
shellDispatch.ShellExecute(process, args, currentDirectory, string.Empty, SW_SHOWNORMAL);
}
/// <summary>
/// Interop definitions
/// </summary>
private const int CSIDL_Desktop = 0;
private const int SWC_DESKTOP = 8;
private const int SWFO_NEEDDISPATCH = 1;
private const int SW_SHOWNORMAL = 1;
private const int SVGIO_BACKGROUND = 0;
private readonly static Guid SID_STopLevelBrowser = new Guid("4C96BE40-915C-11CF-99D3-00AA004AE837");
[ComImport]
[Guid("9BA05972-F6A8-11CF-A442-00A0C90A8F39")]
[ClassInterfaceAttribute(ClassInterfaceType.None)]
private class CShellWindows
{
}
[ComImport]
[Guid("85CB6900-4D95-11CF-960C-0080C7F4EE85")]
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
private interface IShellWindows
{
[return: MarshalAs(UnmanagedType.IDispatch)]
object FindWindowSW([MarshalAs(UnmanagedType.Struct)] ref object pvarloc, [MarshalAs(UnmanagedType.Struct)] ref object pvarlocRoot, int swClass, out int pHWND, int swfwOptions);
}
[ComImport]
[Guid("6d5140c1-7436-11ce-8034-00aa006009fa")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface IServiceProvider
{
[return: MarshalAs(UnmanagedType.Interface)]
object QueryService(ref Guid guidService, ref Guid riid);
}
[ComImport]
[Guid("000214E2-0000-0000-C000-000000000046")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface IShellBrowser
{
void VTableGap01(); // GetWindow
void VTableGap02(); // ContextSensitiveHelp
void VTableGap03(); // InsertMenusSB
void VTableGap04(); // SetMenuSB
void VTableGap05(); // RemoveMenusSB
void VTableGap06(); // SetStatusTextSB
void VTableGap07(); // EnableModelessSB
void VTableGap08(); // TranslateAcceleratorSB
void VTableGap09(); // BrowseObject
void VTableGap10(); // GetViewStateStream
void VTableGap11(); // GetControlWindow
void VTableGap12(); // SendControlMsg
IShellView QueryActiveShellView();
}
[ComImport]
[Guid("000214E3-0000-0000-C000-000000000046")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface IShellView
{
void VTableGap01(); // GetWindow
void VTableGap02(); // ContextSensitiveHelp
void VTableGap03(); // TranslateAcceleratorA
void VTableGap04(); // EnableModeless
void VTableGap05(); // UIActivate
void VTableGap06(); // Refresh
void VTableGap07(); // CreateViewWindow
void VTableGap08(); // DestroyViewWindow
void VTableGap09(); // GetCurrentInfo
void VTableGap10(); // AddPropertySheetPages
void VTableGap11(); // SaveViewState
void VTableGap12(); // SelectItem
[return: MarshalAs(UnmanagedType.Interface)]
object GetItemObject(UInt32 aspectOfView, ref Guid riid);
}
[ComImport]
[Guid("00020400-0000-0000-C000-000000000046")]
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
private interface IDispatch
{
}
[ComImport]
[Guid("E7A1AF80-4D96-11CF-960C-0080C7F4EE85")]
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
private interface IShellFolderViewDual
{
object Application { [return: MarshalAs(UnmanagedType.IDispatch)] get; }
}
[ComImport]
[Guid("A4C6892C-3BA9-11D2-9DEA-00C04FB16162")]
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface IShellDispatch2
{
void ShellExecute([MarshalAs(UnmanagedType.BStr)] string File, [MarshalAs(UnmanagedType.Struct)] object vArgs, [MarshalAs(UnmanagedType.Struct)] object vDir, [MarshalAs(UnmanagedType.Struct)] object vOperation, [MarshalAs(UnmanagedType.Struct)] object vShow);
}
}
}
A:
If you want to start an unelevated process from an elevated one you could copy the access token of the shell process and use it to start a new process.
public static class UnelevatedProcessStarter
{
public static void Start(string cmdArgs)
{
// 1. Get the shell
var shell = NativeMethods.GetShellWindow();
if (shell == IntPtr.Zero)
{
throw new Exception("Could not find shell window");
}
// 2. Copy the access token of the process
NativeMethods.GetWindowThreadProcessId(shell, out uint shellProcessId);
var hShellProcess = NativeMethods.OpenProcess(0x00000400 /* QueryInformation */, false, (int)shellProcessId);
if (!NativeMethods.OpenProcessToken(hShellProcess, 2 /* TOKEN_DUPLICATE */, out IntPtr hShellToken))
{
throw new Win32Exception();
}
// 3. Duplicate the acess token
uint tokenAccess = 8 /*TOKEN_QUERY*/ | 1 /*TOKEN_ASSIGN_PRIMARY*/ | 2 /*TOKEN_DUPLICATE*/ | 0x80 /*TOKEN_ADJUST_DEFAULT*/ | 0x100 /*TOKEN_ADJUST_SESSIONID*/;
var securityAttributes = new SecurityAttributes();
NativeMethods.DuplicateTokenEx(
hShellToken,
tokenAccess,
ref securityAttributes,
2 /* SecurityImpersonation */,
1 /* TokenPrimary */,
out IntPtr hToken);
// 4. Create a new process with the copied token
var si = new Startupinfo();
si.cb = Marshal.SizeOf(si);
if (!NativeMethods.CreateProcessWithTokenW(
hToken,
0x00000002 /* LogonNetcredentialsOnly */,
null,
cmdArgs,
0x00000010 /* CreateNewConsole */,
IntPtr.Zero,
null,
ref si,
out ProcessInformation _))
{
throw new Win32Exception();
}
}
public class NativeMethods
{
[DllImport("user32.dll")]
public static extern IntPtr GetShellWindow();
[DllImport("user32.dll", SetLastError = true)]
public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr OpenProcess(int processAccess, bool bInheritHandle, int processId);
[DllImport("advapi32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool OpenProcessToken(IntPtr processHandle, UInt32 desiredAccess, out IntPtr tokenHandle);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool DuplicateTokenEx(IntPtr hExistingToken, uint dwDesiredAccess,
ref SecurityAttributes lpTokenAttributes,
int impersonationLevel,
int tokenType,
out IntPtr phNewToken);
[DllImport("advapi32", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern bool CreateProcessWithTokenW(
IntPtr hToken, int dwLogonFlags,
string lpApplicationName, string lpCommandLine,
int dwCreationFlags, IntPtr lpEnvironment,
string lpCurrentDirectory, [In] ref Startupinfo lpStartupInfo, out ProcessInformation lpProcessInformation);
}
[StructLayout(LayoutKind.Sequential)]
public struct ProcessInformation
{
public IntPtr hProcess;
public IntPtr hThread;
public int dwProcessId;
public int dwThreadId;
}
[StructLayout(LayoutKind.Sequential)]
public struct SecurityAttributes
{
public int nLength;
public IntPtr lpSecurityDescriptor;
public int bInheritHandle;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct Startupinfo
{
public Int32 cb;
public string lpReserved;
public string lpDesktop;
public string lpTitle;
public Int32 dwX;
public Int32 dwY;
public Int32 dwXSize;
public Int32 dwYSize;
public Int32 dwXCountChars;
public Int32 dwYCountChars;
public Int32 dwFillAttribute;
public Int32 dwFlags;
public Int16 wShowWindow;
public Int16 cbReserved2;
public IntPtr lpReserved2;
public IntPtr hStdInput;
public IntPtr hStdOutput;
public IntPtr hStdError;
}
}
A:
Based on @NtFreX I created another solution, that
takes the token from the current identity (seems to work and needs less code), - sorry, that doesn't always work
handles running from an already unelevated process (because in this case CreateProcessWithTokenW fails with error code 1314 - "A required privilege is not held by the client") and
returns the process id so that the calling code can await it etc.
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Security.Principal;
public static class UnelevatedProcessStarter
{
public static int Start(string cmdArgs)
{
// 1. Get the shell
var shell = NativeMethods.GetShellWindow();
if (shell == IntPtr.Zero)
{
throw new Exception("Could not find shell window");
}
// 2. Copy the access token of the process
uint shellProcessId;
NativeMethods.GetWindowThreadProcessId(shell, out shellProcessId);
var hShellProcess = NativeMethods.OpenProcess(0x00000400 /* QueryInformation */, false, (int)shellProcessId);
IntPtr hShellToken;
if (!NativeMethods.OpenProcessToken(hShellProcess, 2 /* TOKEN_DUPLICATE */, out hShellToken))
{
throw new Win32Exception();
}
// 3. Duplicate the access token
uint tokenAccess = 8 /*TOKEN_QUERY*/ | 1 /*TOKEN_ASSIGN_PRIMARY*/ | 2 /*TOKEN_DUPLICATE*/ | 0x80 /*TOKEN_ADJUST_DEFAULT*/ | 0x100 /*TOKEN_ADJUST_SESSIONID*/;
var securityAttributes = new SecurityAttributes();
IntPtr hToken;
if (!NativeMethods.DuplicateTokenEx(
hShellToken,
tokenAccess,
ref securityAttributes,
2 /* SecurityImpersonation */,
1 /* TokenPrimary */,
out hToken))
{
throw new Win32Exception();
}
// 4. Create a new process with the copied token
var si = new Startupinfo();
si.cb = Marshal.SizeOf(si);
ProcessInformation processInfo;
if (!NativeMethods.CreateProcessWithTokenW(
hToken,
0x00000002 /* LogonNetcredentialsOnly */,
null,
cmdArgs,
0x00000010 /* CreateNewConsole */,
IntPtr.Zero,
null,
ref si,
out processInfo))
{
// Can't do that when not elevated (see https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-createprocesswithtokenw)
// -> start the process as usual
if (Marshal.GetLastWin32Error() == 1314)
{
SecurityAttributes processSecurityAttributes = new SecurityAttributes();
SecurityAttributes threadSecurityAttributes = new SecurityAttributes();
if (!NativeMethods.CreateProcessAsUser(
IntPtr.Zero,
null,
cmdArgs,
ref processSecurityAttributes,
ref threadSecurityAttributes,
true,
0x00000010 /* CreateNewConsole */,
IntPtr.Zero,
null,
ref si,
out processInfo))
{
throw new Win32Exception();
}
}
else
{
throw new Win32Exception();
}
}
return processInfo.dwProcessId;
}
public class NativeMethods
{
[DllImport("user32.dll")]
public static extern IntPtr GetShellWindow();
[DllImport("user32.dll", SetLastError = true)]
public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr OpenProcess(int processAccess, bool bInheritHandle, int processId);
[DllImport("advapi32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool OpenProcessToken(IntPtr processHandle, UInt32 desiredAccess, out IntPtr tokenHandle);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool DuplicateTokenEx(IntPtr hExistingToken, uint dwDesiredAccess,
ref SecurityAttributes lpTokenAttributes,
int impersonationLevel,
int tokenType,
out IntPtr phNewToken);
[DllImport("advapi32", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern bool CreateProcessWithTokenW(
IntPtr hToken, int dwLogonFlags,
string lpApplicationName, string lpCommandLine,
int dwCreationFlags, IntPtr lpEnvironment,
string lpCurrentDirectory,
[In] ref Startupinfo lpStartupInfo,
out ProcessInformation lpProcessInformation);
[DllImport("advapi32.dll", SetLastError=true, CharSet=CharSet.Unicode)]
public static extern bool CreateProcessAsUser(
IntPtr hToken,
string lpApplicationName,
string lpCommandLine,
ref SecurityAttributes lpProcessAttributes,
ref SecurityAttributes lpThreadAttributes,
bool bInheritHandles,
uint dwCreationFlags,
IntPtr lpEnvironment,
string lpCurrentDirectory,
ref Startupinfo lpStartupInfo,
out ProcessInformation lpProcessInformation);
}
[StructLayout(LayoutKind.Sequential)]
public struct ProcessInformation
{
public IntPtr hProcess;
public IntPtr hThread;
public int dwProcessId;
public int dwThreadId;
}
[StructLayout(LayoutKind.Sequential)]
public struct SecurityAttributes
{
public int nLength;
public IntPtr lpSecurityDescriptor;
public int bInheritHandle;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct Startupinfo
{
public Int32 cb;
public string lpReserved;
public string lpDesktop;
public string lpTitle;
public Int32 dwX;
public Int32 dwY;
public Int32 dwXSize;
public Int32 dwYSize;
public Int32 dwXCountChars;
public Int32 dwYCountChars;
public Int32 dwFillAttribute;
public Int32 dwFlags;
public Int16 wShowWindow;
public Int16 cbReserved2;
public IntPtr lpReserved2;
public IntPtr hStdInput;
public IntPtr hStdOutput;
public IntPtr hStdError;
}
}
|
How do you de-elevate privileges for a child process
|
I know how to launch a process with Admin privileges from a process using:
proc.StartInfo.UseShellExecute = true;
proc.StartInfo.Verb = "runas";
where proc is a System.Diagnostics.Process. But how does one do the opposite?
If the process you're in is already elevated, how do you launch the new process without admin privileges? More accurately, we need to launch the new process with the same permission level as Windows Explorer, so no change if UAC is disabled, but if UAC is enabled, but our process is running elevated, we need to perform a certain operation un-elevated because we're creating a virtual drive and if it's created with elevated permissions and Windows explorer is running unelevated it won't show up.
Feel free to change the title to something better, I couldn't come up with a good description.
|
[
"The solution for you is to use EXPLORER.exe process.\nThe idea is to run the process in UN-ELEVATED mode, using windows's file explorer process explorer.exe (info).\nLets say the process that we want to launch is on $TEMP\\MyUnElevatedProcess.exe.\nSo, for NSIS code, I will just write: (but can be run in ANY language)\n Exec '\"$WINDIR\\explorer.exe\" \"$TEMP\\MyUnElevatedProcess.exe\"'\n\nExample code (using NSIS installer)\nExec '\"$WINDIR\\explorer.exe\" \"$TEMP\\MyUnElevatedProcess.exe\"'\n\n***code taken from http://mdb-blog.blogspot.com/2013/01/nsis-lunch-program-as-user-from-uac.html \n",
"We ended up using the sample from this Code Project article: High elevation can be bad for your application: How to start a non-elevated process at the end of the installation\nIt seems to work so far, I gather it injects into RunDll32.exe, my C++/Win32 is fairly weak so I didn't look too much into the actual implementation, just it's use. Confirmed that it works in Vista and Win7 both x86 and x64 (at least for us, x86 and x64 require different dll's which is checked for at install time and the proper one is used). \n",
"Raymond Chen addressed this in his blog:\nHow can I launch an unelevated process from my elevated process and vice versa?\nSearching in GitHub for a C# version of this code, I found the following implementation in Microsoft's Node.js tools for Visual Studio repository: SystemUtilities.cs (the ExecuteProcessUnElevated function).\nJust in case the file disappears, here's the file's contents:\n// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Runtime.InteropServices;\n\nnamespace Microsoft.NodejsTools.SharedProject\n{\n /// <summary>\n /// Utility for accessing window IShell* interfaces in order to use them to launch a process unelevated\n /// </summary>\n internal class SystemUtility\n {\n /// <summary>\n /// We are elevated and should launch the process unelevated. We can't create the\n /// process directly without it becoming elevated. So to workaround this, we have\n /// explorer do the process creation (explorer is typically running unelevated).\n /// </summary>\n internal static void ExecuteProcessUnElevated(string process, string args, string currentDirectory = \"\")\n {\n var shellWindows = (IShellWindows)new CShellWindows();\n\n // Get the desktop window\n object loc = CSIDL_Desktop;\n object unused = new object();\n int hwnd;\n var serviceProvider = (IServiceProvider)shellWindows.FindWindowSW(ref loc, ref unused, SWC_DESKTOP, out hwnd, SWFO_NEEDDISPATCH);\n\n // Get the shell browser\n var serviceGuid = SID_STopLevelBrowser;\n var interfaceGuid = typeof(IShellBrowser).GUID;\n var shellBrowser = (IShellBrowser)serviceProvider.QueryService(ref serviceGuid, ref interfaceGuid);\n\n // Get the shell dispatch\n var dispatch = typeof(IDispatch).GUID;\n var folderView = (IShellFolderViewDual)shellBrowser.QueryActiveShellView().GetItemObject(SVGIO_BACKGROUND, ref dispatch);\n var shellDispatch = (IShellDispatch2)folderView.Application;\n\n // Use the dispatch (which is unelevated) to launch the process for us\n shellDispatch.ShellExecute(process, args, currentDirectory, string.Empty, SW_SHOWNORMAL);\n }\n\n /// <summary>\n /// Interop definitions\n /// </summary>\n private const int CSIDL_Desktop = 0;\n private const int SWC_DESKTOP = 8;\n private const int SWFO_NEEDDISPATCH = 1;\n private const int SW_SHOWNORMAL = 1;\n private const int SVGIO_BACKGROUND = 0;\n private readonly static Guid SID_STopLevelBrowser = new Guid(\"4C96BE40-915C-11CF-99D3-00AA004AE837\");\n\n [ComImport]\n [Guid(\"9BA05972-F6A8-11CF-A442-00A0C90A8F39\")]\n [ClassInterfaceAttribute(ClassInterfaceType.None)]\n private class CShellWindows\n {\n }\n\n [ComImport]\n [Guid(\"85CB6900-4D95-11CF-960C-0080C7F4EE85\")]\n [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]\n private interface IShellWindows\n {\n [return: MarshalAs(UnmanagedType.IDispatch)]\n object FindWindowSW([MarshalAs(UnmanagedType.Struct)] ref object pvarloc, [MarshalAs(UnmanagedType.Struct)] ref object pvarlocRoot, int swClass, out int pHWND, int swfwOptions);\n }\n\n [ComImport]\n [Guid(\"6d5140c1-7436-11ce-8034-00aa006009fa\")]\n [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]\n private interface IServiceProvider\n {\n [return: MarshalAs(UnmanagedType.Interface)]\n object QueryService(ref Guid guidService, ref Guid riid);\n }\n\n [ComImport]\n [Guid(\"000214E2-0000-0000-C000-000000000046\")]\n [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]\n private interface IShellBrowser\n {\n void VTableGap01(); // GetWindow\n void VTableGap02(); // ContextSensitiveHelp\n void VTableGap03(); // InsertMenusSB\n void VTableGap04(); // SetMenuSB\n void VTableGap05(); // RemoveMenusSB\n void VTableGap06(); // SetStatusTextSB\n void VTableGap07(); // EnableModelessSB\n void VTableGap08(); // TranslateAcceleratorSB\n void VTableGap09(); // BrowseObject\n void VTableGap10(); // GetViewStateStream\n void VTableGap11(); // GetControlWindow\n void VTableGap12(); // SendControlMsg\n IShellView QueryActiveShellView();\n }\n\n [ComImport]\n [Guid(\"000214E3-0000-0000-C000-000000000046\")]\n [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]\n private interface IShellView\n {\n void VTableGap01(); // GetWindow\n void VTableGap02(); // ContextSensitiveHelp\n void VTableGap03(); // TranslateAcceleratorA\n void VTableGap04(); // EnableModeless\n void VTableGap05(); // UIActivate\n void VTableGap06(); // Refresh\n void VTableGap07(); // CreateViewWindow\n void VTableGap08(); // DestroyViewWindow\n void VTableGap09(); // GetCurrentInfo\n void VTableGap10(); // AddPropertySheetPages\n void VTableGap11(); // SaveViewState\n void VTableGap12(); // SelectItem\n\n [return: MarshalAs(UnmanagedType.Interface)]\n object GetItemObject(UInt32 aspectOfView, ref Guid riid);\n }\n\n [ComImport]\n [Guid(\"00020400-0000-0000-C000-000000000046\")]\n [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]\n private interface IDispatch\n {\n }\n\n [ComImport]\n [Guid(\"E7A1AF80-4D96-11CF-960C-0080C7F4EE85\")]\n [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]\n private interface IShellFolderViewDual\n {\n object Application { [return: MarshalAs(UnmanagedType.IDispatch)] get; }\n }\n\n [ComImport]\n [Guid(\"A4C6892C-3BA9-11D2-9DEA-00C04FB16162\")]\n [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]\n public interface IShellDispatch2\n {\n void ShellExecute([MarshalAs(UnmanagedType.BStr)] string File, [MarshalAs(UnmanagedType.Struct)] object vArgs, [MarshalAs(UnmanagedType.Struct)] object vDir, [MarshalAs(UnmanagedType.Struct)] object vOperation, [MarshalAs(UnmanagedType.Struct)] object vShow);\n }\n }\n}\n\n",
"If you want to start an unelevated process from an elevated one you could copy the access token of the shell process and use it to start a new process.\npublic static class UnelevatedProcessStarter\n{\n public static void Start(string cmdArgs)\n {\n // 1. Get the shell\n var shell = NativeMethods.GetShellWindow();\n if (shell == IntPtr.Zero)\n {\n throw new Exception(\"Could not find shell window\");\n }\n\n // 2. Copy the access token of the process\n NativeMethods.GetWindowThreadProcessId(shell, out uint shellProcessId);\n var hShellProcess = NativeMethods.OpenProcess(0x00000400 /* QueryInformation */, false, (int)shellProcessId);\n if (!NativeMethods.OpenProcessToken(hShellProcess, 2 /* TOKEN_DUPLICATE */, out IntPtr hShellToken))\n {\n throw new Win32Exception();\n }\n\n // 3. Duplicate the acess token\n uint tokenAccess = 8 /*TOKEN_QUERY*/ | 1 /*TOKEN_ASSIGN_PRIMARY*/ | 2 /*TOKEN_DUPLICATE*/ | 0x80 /*TOKEN_ADJUST_DEFAULT*/ | 0x100 /*TOKEN_ADJUST_SESSIONID*/;\n var securityAttributes = new SecurityAttributes();\n\n NativeMethods.DuplicateTokenEx(\n hShellToken,\n tokenAccess,\n ref securityAttributes,\n 2 /* SecurityImpersonation */,\n 1 /* TokenPrimary */,\n out IntPtr hToken);\n\n // 4. Create a new process with the copied token\n var si = new Startupinfo();\n si.cb = Marshal.SizeOf(si);\n\n if (!NativeMethods.CreateProcessWithTokenW(\n hToken,\n 0x00000002 /* LogonNetcredentialsOnly */,\n null,\n cmdArgs,\n 0x00000010 /* CreateNewConsole */,\n IntPtr.Zero,\n null,\n ref si,\n out ProcessInformation _))\n {\n throw new Win32Exception();\n }\n }\n\n public class NativeMethods\n {\n [DllImport(\"user32.dll\")]\n public static extern IntPtr GetShellWindow();\n [DllImport(\"user32.dll\", SetLastError = true)]\n public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);\n [DllImport(\"kernel32.dll\", SetLastError = true)]\n public static extern IntPtr OpenProcess(int processAccess, bool bInheritHandle, int processId);\n [DllImport(\"advapi32.dll\", SetLastError = true)]\n [return: MarshalAs(UnmanagedType.Bool)]\n public static extern bool OpenProcessToken(IntPtr processHandle, UInt32 desiredAccess, out IntPtr tokenHandle);\n [DllImport(\"advapi32.dll\", CharSet = CharSet.Auto, SetLastError = true)]\n public static extern bool DuplicateTokenEx(IntPtr hExistingToken, uint dwDesiredAccess,\n ref SecurityAttributes lpTokenAttributes,\n int impersonationLevel,\n int tokenType,\n out IntPtr phNewToken);\n [DllImport(\"advapi32\", SetLastError = true, CharSet = CharSet.Unicode)]\n public static extern bool CreateProcessWithTokenW(\n IntPtr hToken, int dwLogonFlags,\n string lpApplicationName, string lpCommandLine,\n int dwCreationFlags, IntPtr lpEnvironment,\n string lpCurrentDirectory, [In] ref Startupinfo lpStartupInfo, out ProcessInformation lpProcessInformation);\n }\n\n [StructLayout(LayoutKind.Sequential)]\n public struct ProcessInformation\n {\n public IntPtr hProcess;\n public IntPtr hThread;\n public int dwProcessId;\n public int dwThreadId;\n }\n\n [StructLayout(LayoutKind.Sequential)]\n public struct SecurityAttributes\n {\n public int nLength;\n public IntPtr lpSecurityDescriptor;\n public int bInheritHandle;\n }\n \n [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]\n public struct Startupinfo\n {\n public Int32 cb;\n public string lpReserved;\n public string lpDesktop;\n public string lpTitle;\n public Int32 dwX;\n public Int32 dwY;\n public Int32 dwXSize;\n public Int32 dwYSize;\n public Int32 dwXCountChars;\n public Int32 dwYCountChars;\n public Int32 dwFillAttribute;\n public Int32 dwFlags;\n public Int16 wShowWindow;\n public Int16 cbReserved2;\n public IntPtr lpReserved2;\n public IntPtr hStdInput;\n public IntPtr hStdOutput;\n public IntPtr hStdError;\n }\n}\n\n",
"Based on @NtFreX I created another solution, that\n\ntakes the token from the current identity (seems to work and needs less code), - sorry, that doesn't always work\nhandles running from an already unelevated process (because in this case CreateProcessWithTokenW fails with error code 1314 - \"A required privilege is not held by the client\") and\nreturns the process id so that the calling code can await it etc.\n\nusing System;\nusing System.ComponentModel;\nusing System.Runtime.InteropServices;\nusing System.Security.Principal;\n\npublic static class UnelevatedProcessStarter\n{\n public static int Start(string cmdArgs)\n {\n // 1. Get the shell\n var shell = NativeMethods.GetShellWindow();\n if (shell == IntPtr.Zero)\n {\n throw new Exception(\"Could not find shell window\");\n }\n\n // 2. Copy the access token of the process\n uint shellProcessId;\n NativeMethods.GetWindowThreadProcessId(shell, out shellProcessId);\n var hShellProcess = NativeMethods.OpenProcess(0x00000400 /* QueryInformation */, false, (int)shellProcessId);\n IntPtr hShellToken;\n if (!NativeMethods.OpenProcessToken(hShellProcess, 2 /* TOKEN_DUPLICATE */, out hShellToken))\n {\n throw new Win32Exception();\n }\n\n // 3. Duplicate the access token\n uint tokenAccess = 8 /*TOKEN_QUERY*/ | 1 /*TOKEN_ASSIGN_PRIMARY*/ | 2 /*TOKEN_DUPLICATE*/ | 0x80 /*TOKEN_ADJUST_DEFAULT*/ | 0x100 /*TOKEN_ADJUST_SESSIONID*/;\n var securityAttributes = new SecurityAttributes();\n IntPtr hToken;\n if (!NativeMethods.DuplicateTokenEx(\n hShellToken,\n tokenAccess,\n ref securityAttributes,\n 2 /* SecurityImpersonation */,\n 1 /* TokenPrimary */,\n out hToken))\n {\n throw new Win32Exception();\n }\n\n // 4. Create a new process with the copied token\n var si = new Startupinfo();\n si.cb = Marshal.SizeOf(si);\n ProcessInformation processInfo;\n if (!NativeMethods.CreateProcessWithTokenW(\n hToken,\n 0x00000002 /* LogonNetcredentialsOnly */,\n null,\n cmdArgs,\n 0x00000010 /* CreateNewConsole */,\n IntPtr.Zero,\n null,\n ref si,\n out processInfo))\n {\n // Can't do that when not elevated (see https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-createprocesswithtokenw)\n // -> start the process as usual\n if (Marshal.GetLastWin32Error() == 1314)\n {\n SecurityAttributes processSecurityAttributes = new SecurityAttributes();\n SecurityAttributes threadSecurityAttributes = new SecurityAttributes();\n if (!NativeMethods.CreateProcessAsUser(\n IntPtr.Zero,\n null,\n cmdArgs,\n ref processSecurityAttributes,\n ref threadSecurityAttributes,\n true,\n 0x00000010 /* CreateNewConsole */,\n IntPtr.Zero,\n null,\n ref si,\n out processInfo))\n {\n throw new Win32Exception();\n }\n }\n else\n {\n throw new Win32Exception();\n }\n }\n\n return processInfo.dwProcessId;\n }\n\n public class NativeMethods\n {\n [DllImport(\"user32.dll\")]\n public static extern IntPtr GetShellWindow();\n [DllImport(\"user32.dll\", SetLastError = true)]\n public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);\n [DllImport(\"kernel32.dll\", SetLastError = true)]\n public static extern IntPtr OpenProcess(int processAccess, bool bInheritHandle, int processId);\n [DllImport(\"advapi32.dll\", SetLastError = true)]\n [return: MarshalAs(UnmanagedType.Bool)]\n public static extern bool OpenProcessToken(IntPtr processHandle, UInt32 desiredAccess, out IntPtr tokenHandle);\n [DllImport(\"advapi32.dll\", CharSet = CharSet.Auto, SetLastError = true)]\n public static extern bool DuplicateTokenEx(IntPtr hExistingToken, uint dwDesiredAccess,\n ref SecurityAttributes lpTokenAttributes,\n int impersonationLevel,\n int tokenType,\n out IntPtr phNewToken);\n [DllImport(\"advapi32\", SetLastError = true, CharSet = CharSet.Unicode)]\n public static extern bool CreateProcessWithTokenW(\n IntPtr hToken, int dwLogonFlags,\n string lpApplicationName, string lpCommandLine,\n int dwCreationFlags, IntPtr lpEnvironment,\n string lpCurrentDirectory,\n [In] ref Startupinfo lpStartupInfo,\n out ProcessInformation lpProcessInformation);\n\n [DllImport(\"advapi32.dll\", SetLastError=true, CharSet=CharSet.Unicode)]\n public static extern bool CreateProcessAsUser(\n IntPtr hToken,\n string lpApplicationName,\n string lpCommandLine,\n ref SecurityAttributes lpProcessAttributes,\n ref SecurityAttributes lpThreadAttributes,\n bool bInheritHandles,\n uint dwCreationFlags,\n IntPtr lpEnvironment,\n string lpCurrentDirectory,\n ref Startupinfo lpStartupInfo,\n out ProcessInformation lpProcessInformation);\n }\n\n [StructLayout(LayoutKind.Sequential)]\n public struct ProcessInformation\n {\n public IntPtr hProcess;\n public IntPtr hThread;\n public int dwProcessId;\n public int dwThreadId;\n }\n\n [StructLayout(LayoutKind.Sequential)]\n public struct SecurityAttributes\n {\n public int nLength;\n public IntPtr lpSecurityDescriptor;\n public int bInheritHandle;\n }\n \n [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]\n public struct Startupinfo\n {\n public Int32 cb;\n public string lpReserved;\n public string lpDesktop;\n public string lpTitle;\n public Int32 dwX;\n public Int32 dwY;\n public Int32 dwXSize;\n public Int32 dwYSize;\n public Int32 dwXCountChars;\n public Int32 dwYCountChars;\n public Int32 dwFillAttribute;\n public Int32 dwFlags;\n public Int16 wShowWindow;\n public Int16 cbReserved2;\n public IntPtr lpReserved2;\n public IntPtr hStdInput;\n public IntPtr hStdOutput;\n public IntPtr hStdError;\n }\n}\n\n"
] |
[
21,
9,
7,
1,
0
] |
[
"You can use ProcessStartInfo.UserName and ProcessStartInfo.Password to specify the account you want your process to run under.\nclass Program\n{\n static void Main(string[] args)\n {\n var psi = new ProcessStartInfo(@\"c:\\windows\\system32\\whoami.exe\");\n var password = new SecureString();\n password.AppendChar('s');\n password.AppendChar('e');\n password.AppendChar('c');\n password.AppendChar('r');\n password.AppendChar('e');\n password.AppendChar('t');\n psi.Password = password;\n psi.UserName = \"username\";\n psi.UseShellExecute = false;\n psi.RedirectStandardOutput = true;\n\n var p = new Process();\n p.StartInfo = psi;\n p.Start();\n p.WaitForExit();\n\n Console.WriteLine(p.StandardOutput.ReadToEnd());\n }\n}\n\n"
] |
[
-1
] |
[
"c#",
"elevation",
"process",
"uac"
] |
stackoverflow_0001173630_c#_elevation_process_uac.txt
|
Q:
Component cannot be used as a JSX component. Its return type 'Element[]' is not a valid JSX element
I'm currently getting the following error on the Todos component inside TodoApp.tsx: 'Todos' cannot be used as a JSX component.
Its return type 'Element[]' is not a valid JSX element.
Type 'Element[]' is missing the following properties from type 'Element': type, props, key
And this is my folder structure
TodoApp.tsx
function TodoApp() {
return (
<Body>
<AppDiv>
<Form />
<Todos />
<Footer />
</AppDiv>
</Body>
);
}
Todos.tsx
function Todos(): JSX.Element[] {
const todos = useSelector((state: RootState) => state.todos);
const footer = useSelector((state: RootState) => state.footer);
if (footer.hideAll) {
if (footer.showCompleted) {
return todos
.filter((todo) => !todo.completed)
.map((todo: any) => (
<>
<ul>
<Todo todo={todo} />
</ul>
</>
));
}
return todos.map((todo) => (
<>
<div>
<Todo todo={todo} />
</div>
</>
));
}
return todos.map(() => (
<>
<div></div>
</>
));
}
Todo.tsx
type Todo = {
todo: TodoProps;
};
const Todo = ({ todo }: Todo) : JSX.Element => {
const [isEditing, edit] = useState<boolean>(false);
const dispatch = useDispatch();
if (!isEditing) {
return (
<TodoDiv>
<Li
key={todo.id}
completed={todo.completed}
onClick={() => dispatch(completeTodo(todo.id))}
// style={{
// textDecoration: todo.completed ? "line-through" : "none"
// }}
>
{todo.text}
</Li>
<TodoBttns>
<Button edit onClick={() => edit(!isEditing)}>
<img src={editBttn} alt="Edit Button" />
</Button>
<Button delete onClick={() => dispatch(deleteTodo(todo.id))}>
<img src={deleteBttn} alt="Delete Button" />
</Button>
</TodoBttns>
</TodoDiv>
);
} else {
return (
<FormEdit>
<InputForm key={todo.id} {...{ todo, edit }} />
</FormEdit>
);
}
};
and the TodoProps interface is the following:
interface TodoProps {
text: string;
completed: boolean;
id: string;
}
already tried the fix of wraping the map items with fragments, but I still can't make it work. The only thing that as of now is fixing the issue is declaring at the top of Todos.tsx as this function Todos(): any
As a side note: I'm using Styled Components, but I don't think the issue is related to the library.
A:
A component needs to return a single root element. You can use fragments to package an array of elements as a single element, by using the fragment as that single root element.
So this does nothing:
function Todos(): JSX.Element {
return todos.map(todo => (
<>
<li>{todo.task}</li>
</>
)
}
Because it's now returning an array of [<><li/></>, <><li/></>, ...]. That fragment needs to be the single root element.
You need to use the fragment like this:
function Todos(): JSX.Element {
return <>{
todos.map(todo => <li>{todo.task}</li>)
}</>
}
You nest all returned JSX in one single fragment.
Using that pattern you may end up with somehting like this:
function Todos(): JSX.Element {
const todos = useSelector((state: RootState) => state.todos);
const footer = useSelector((state: RootState) => state.footer);
if (footer.hideAll) {
if (footer.showCompleted) {
return <>{
todos
.filter((todo) => !todo.completed)
.map((todo: any) => (
<ul>
<Todo todo={todo} />
</ul>
))
}</>
}
return <>{
todos.map((todo) => (
<div>
<Todo todo={todo} />
</div>
))
}</>
}
return <>{
todos.map(() => (
<div></div>
))
}</>
}
// Works without error
<Todos />
Note how each return statement returns just one JSX.Element: the fragment.
Playground
A:
You need to return a JSX Element, not an array.
Wrapping the whole component is a solution, but you need to do it outside of the map/filter function.
Todos.tsx
function Todos(): JSX.Element {
const todos = useSelector((state: RootState) => state.todos);
const footer = useSelector((state: RootState) => state.footer);
if (footer.hideAll) {
if (footer.showCompleted) {
return (
<>
{todos.filter((todo) => !todo.completed).map((todo: any) => (
<ul>
<Todo todo={todo} />
</ul>
));
}
</>
}
return (
<>
{todos.map((todo) => (
<div>
<Todo todo={todo} />
</div>
));
}
</>
}
return (
<>{todos.map(() => <div />)}</>
);
}
A:
In case anyone is facing issue with React + Typescript stack, try adding below setting in tsconfig.json. It worked for me.
"allowSyntheticDefaultImports" : true
A:
For a scenario when someone has upgraded to later React, e.g., 16 -> 17 it could start happening.
Now, while looking for @types/react in your project, you could notice many npm packages have @types/react : "*",. The solution to get rid off the problem, in that scenario, would be to add into your package.json:
"resolutions": {
"@types/react": "^17.0.38"
}
A:
In my case, it was a forgotten import. Basically copy-pasted some of my code and forgot to import one of the components and this was the error message I get.
A:
There's a possibility that you have installed (and probably failed) a new package, which could also cause this error.
If that's the case (that you have recently installed and failed or cancelled a package), you can delete node_modules and run npm i or yarn install then try again.
A:
I'm facing the same issue about this error. I add the below code to my package.json file.
"resolutions": {
"@types/react": "17.0.2",
"@types/react-dom": "17.0.2",
"graphql": "^16.5.0"
},
Then, Run yarn install on a terminal.
It works for me.
A:
You need to install types for react npm install @types/react or yarn add @types/react
A:
Sometimes this error can occur when you use the switch case syntax to render your component.
For example:
switch (loading) {
case "pending":
return <span>Pending</span>;
case "succeeded":
return <span>Succeeded</span>;
case "failed":
return <span>Failed</span>;
Sometimes your loading status can mistakenly have a value that you didn't specify in the case, so your component will return undefined. Therefore, you should add a default value:
default: return <span>¯\_(ツ)_/¯</span>;
A:
This answer is related to same problem on react-native.
Adding typescript to my newly created react-native app and moving App.js to App.tsx, I met the same error for component named Section. The solution for me was a component type React.Fc<{...}>.
This is the problematic Section component after the fix when all errors disappeared and my app started as expected.
import React, { ReactNode } from 'react';
import {
SafeAreaView,
ScrollView,
StatusBar,
StyleSheet,
Text,
useColorScheme,
View,
} from 'react-native';
import {
Colors,
DebugInstructions,
Header,
LearnMoreLinks,
ReloadInstructions,
} from 'react-native/Libraries/NewAppScreen';
const Section: React.FC<{
children: ReactNode;
title: string;
}> = ({children, title}) => {
const isDarkMode = useColorScheme() === 'dark';
return (
<View style={styles.sectionContainer}>
<Text
style={[
styles.sectionTitle,
{
color: isDarkMode ? Colors.white : Colors.black,
},
]}>
{title}
</Text>
<Text
style={[
styles.sectionDescription,
{
color: isDarkMode ? Colors.light : Colors.dark,
},
]}>
{children}
</Text>
</View>
);
};
A:
Another common cause of the "Component cannot be used as a JSX component" error is when we return anything other than a JSX element or null from a component, or forget to return a value.
The App component returns undefined because we have placed our return statement on one line and the JSX code on the next without using parentheses.
We aren't allowed to return undefined from a component, so the error occurs.
|
Component cannot be used as a JSX component. Its return type 'Element[]' is not a valid JSX element
|
I'm currently getting the following error on the Todos component inside TodoApp.tsx: 'Todos' cannot be used as a JSX component.
Its return type 'Element[]' is not a valid JSX element.
Type 'Element[]' is missing the following properties from type 'Element': type, props, key
And this is my folder structure
TodoApp.tsx
function TodoApp() {
return (
<Body>
<AppDiv>
<Form />
<Todos />
<Footer />
</AppDiv>
</Body>
);
}
Todos.tsx
function Todos(): JSX.Element[] {
const todos = useSelector((state: RootState) => state.todos);
const footer = useSelector((state: RootState) => state.footer);
if (footer.hideAll) {
if (footer.showCompleted) {
return todos
.filter((todo) => !todo.completed)
.map((todo: any) => (
<>
<ul>
<Todo todo={todo} />
</ul>
</>
));
}
return todos.map((todo) => (
<>
<div>
<Todo todo={todo} />
</div>
</>
));
}
return todos.map(() => (
<>
<div></div>
</>
));
}
Todo.tsx
type Todo = {
todo: TodoProps;
};
const Todo = ({ todo }: Todo) : JSX.Element => {
const [isEditing, edit] = useState<boolean>(false);
const dispatch = useDispatch();
if (!isEditing) {
return (
<TodoDiv>
<Li
key={todo.id}
completed={todo.completed}
onClick={() => dispatch(completeTodo(todo.id))}
// style={{
// textDecoration: todo.completed ? "line-through" : "none"
// }}
>
{todo.text}
</Li>
<TodoBttns>
<Button edit onClick={() => edit(!isEditing)}>
<img src={editBttn} alt="Edit Button" />
</Button>
<Button delete onClick={() => dispatch(deleteTodo(todo.id))}>
<img src={deleteBttn} alt="Delete Button" />
</Button>
</TodoBttns>
</TodoDiv>
);
} else {
return (
<FormEdit>
<InputForm key={todo.id} {...{ todo, edit }} />
</FormEdit>
);
}
};
and the TodoProps interface is the following:
interface TodoProps {
text: string;
completed: boolean;
id: string;
}
already tried the fix of wraping the map items with fragments, but I still can't make it work. The only thing that as of now is fixing the issue is declaring at the top of Todos.tsx as this function Todos(): any
As a side note: I'm using Styled Components, but I don't think the issue is related to the library.
|
[
"A component needs to return a single root element. You can use fragments to package an array of elements as a single element, by using the fragment as that single root element.\nSo this does nothing:\nfunction Todos(): JSX.Element {\n return todos.map(todo => (\n <>\n <li>{todo.task}</li>\n </>\n )\n}\n\nBecause it's now returning an array of [<><li/></>, <><li/></>, ...]. That fragment needs to be the single root element.\nYou need to use the fragment like this:\nfunction Todos(): JSX.Element {\n return <>{\n todos.map(todo => <li>{todo.task}</li>)\n }</>\n}\n\nYou nest all returned JSX in one single fragment.\nUsing that pattern you may end up with somehting like this:\nfunction Todos(): JSX.Element {\n const todos = useSelector((state: RootState) => state.todos);\n const footer = useSelector((state: RootState) => state.footer);\n\n if (footer.hideAll) {\n if (footer.showCompleted) {\n return <>{\n todos\n .filter((todo) => !todo.completed)\n .map((todo: any) => (\n <ul>\n <Todo todo={todo} />\n </ul>\n ))\n }</>\n }\n return <>{\n todos.map((todo) => (\n <div>\n <Todo todo={todo} />\n </div>\n ))\n }</>\n }\n\n return <>{\n todos.map(() => (\n <div></div>\n ))\n }</>\n}\n\n// Works without error\n<Todos />\n\nNote how each return statement returns just one JSX.Element: the fragment.\nPlayground\n",
"You need to return a JSX Element, not an array.\nWrapping the whole component is a solution, but you need to do it outside of the map/filter function.\nTodos.tsx\n\nfunction Todos(): JSX.Element {\n const todos = useSelector((state: RootState) => state.todos);\n const footer = useSelector((state: RootState) => state.footer);\n\n if (footer.hideAll) {\n if (footer.showCompleted) {\n return (\n <>\n {todos.filter((todo) => !todo.completed).map((todo: any) => (\n <ul>\n <Todo todo={todo} />\n </ul>\n ));\n }\n </>\n }\n return (\n <>\n {todos.map((todo) => (\n <div>\n <Todo todo={todo} />\n </div>\n ));\n }\n </>\n }\n\n return (\n <>{todos.map(() => <div />)}</>\n );\n}\n\n",
"In case anyone is facing issue with React + Typescript stack, try adding below setting in tsconfig.json. It worked for me.\n\"allowSyntheticDefaultImports\" : true\n",
"For a scenario when someone has upgraded to later React, e.g., 16 -> 17 it could start happening.\nNow, while looking for @types/react in your project, you could notice many npm packages have @types/react : \"*\",. The solution to get rid off the problem, in that scenario, would be to add into your package.json:\n\"resolutions\": {\n \"@types/react\": \"^17.0.38\"\n}\n\n",
"In my case, it was a forgotten import. Basically copy-pasted some of my code and forgot to import one of the components and this was the error message I get.\n",
"There's a possibility that you have installed (and probably failed) a new package, which could also cause this error.\nIf that's the case (that you have recently installed and failed or cancelled a package), you can delete node_modules and run npm i or yarn install then try again.\n",
"I'm facing the same issue about this error. I add the below code to my package.json file.\n\"resolutions\": {\n \"@types/react\": \"17.0.2\",\n \"@types/react-dom\": \"17.0.2\",\n \"graphql\": \"^16.5.0\"\n},\n\nThen, Run yarn install on a terminal.\nIt works for me.\n",
"You need to install types for react npm install @types/react or yarn add @types/react\n",
"Sometimes this error can occur when you use the switch case syntax to render your component.\nFor example:\nswitch (loading) {\n case \"pending\":\n return <span>Pending</span>;\n case \"succeeded\":\n return <span>Succeeded</span>;\n case \"failed\":\n return <span>Failed</span>;\n\nSometimes your loading status can mistakenly have a value that you didn't specify in the case, so your component will return undefined. Therefore, you should add a default value:\ndefault: return <span>¯\\_(ツ)_/¯</span>;\n\n",
"This answer is related to same problem on react-native.\nAdding typescript to my newly created react-native app and moving App.js to App.tsx, I met the same error for component named Section. The solution for me was a component type React.Fc<{...}>.\nThis is the problematic Section component after the fix when all errors disappeared and my app started as expected.\n import React, { ReactNode } from 'react';\n import {\n SafeAreaView,\n ScrollView,\n StatusBar,\n StyleSheet,\n Text,\n useColorScheme,\n View,\n } from 'react-native';\n \n import {\n Colors,\n DebugInstructions,\n Header,\n LearnMoreLinks,\n ReloadInstructions,\n } from 'react-native/Libraries/NewAppScreen';\n \n const Section: React.FC<{ \n children: ReactNode; \n title: string; \n}> = ({children, title}) => {\n const isDarkMode = useColorScheme() === 'dark';\n return (\n <View style={styles.sectionContainer}>\n <Text\n style={[\n styles.sectionTitle,\n {\n color: isDarkMode ? Colors.white : Colors.black,\n },\n ]}>\n {title}\n </Text>\n <Text\n style={[\n styles.sectionDescription,\n {\n color: isDarkMode ? Colors.light : Colors.dark,\n },\n ]}>\n {children}\n </Text>\n </View>\n );\n };\n\n",
"Another common cause of the \"Component cannot be used as a JSX component\" error is when we return anything other than a JSX element or null from a component, or forget to return a value.\nThe App component returns undefined because we have placed our return statement on one line and the JSX code on the next without using parentheses.\nWe aren't allowed to return undefined from a component, so the error occurs.\n"
] |
[
147,
15,
9,
7,
3,
2,
1,
1,
1,
0,
0
] |
[
"In my case I forgot to put back ticks after styled(PreviousStyledElement);\nAfter I put them the code started to work.\n\n\nexport const MyNewStyledElement = styled(PreviousStyledElement)``;\n\n\n\n"
] |
[
-1
] |
[
"reactjs",
"typescript"
] |
stackoverflow_0062702485_reactjs_typescript.txt
|
Q:
ASP .NET Core Web API - how to create cookie with custom domain?
I have an application which consists of two parts: Backend created in ASP .NET Core Web API and frontend created in React.js. App uses authentication with JWT - frontend makes a POST request to login, if credentials are correct backend creates cookie with token, then frontend makes a GET request to get informations about the logged user.
When both backend and frontend apps were working locally, everything worked fine. But after deploying them to Azure, the GET user endpoint always returns error 401. I think the problem is, that both apps run in different domains. When I login using swagger, everything works fine and I can see the right cookie in devtools. When I login using frontend, there is no cookie in devtools, so it doesn't work.
URLs look like that:
Backend: https://somerandomname.azurewebsites.net/
Frontend: https://anotherrandomname.azurestaticapps.net/
I create cookies like that:
Response.Cookies.Append("jwt", jwt, new CookieOptions
{
HttpOnly = true
});
I read about CookieOptions class, so I tried something like this:
Response.Cookies.Append("jwt", jwt, new CookieOptions
{
HttpOnly = true,
Domain = ".azurestaticapps.net"
});
but not only it doesn't fix the problem, when I type something into CookieOptions.Domain I can't see any cookie at all, even in Postman.
So my question is: what am I doing wrong? How to set the cookie's domain so that my frontend could read them?
A:
It looks like the problem is that your backend and frontend are running on different domains.
When you set a cookie in your backend, the cookie is only accessible on that domain. In order for your frontend to be able to access the cookie, you will need to set the domain of the cookie to a domain that your frontend has access to. In this case, it looks like you are setting the domain to ".azurestaticapps.net", which is the domain of your frontend app. However, it looks like this is not the correct domain for your cookie.
Set the domain of the cookie to ".azurewebsites.net". This will allow your frontend app to access the cookie on the ".azurewebsites.net" domain. You can do this by setting the domain property of the CookieOptions object when you append the cookie to the response, like this:
Response.Cookies.Append("jwt", jwt, new CookieOptions
{
HttpOnly = true,
Domain = ".azurewebsites.net"
});
You can also set the domain of the cookie to ".azurestaticapps.net" and then configure your backend app to allow your frontend app to access the cookie on this domain. This can be done by setting the Access-Control-Allow-Origin header in your backend app's response to ".azurestaticapps.net". This will allow
|
ASP .NET Core Web API - how to create cookie with custom domain?
|
I have an application which consists of two parts: Backend created in ASP .NET Core Web API and frontend created in React.js. App uses authentication with JWT - frontend makes a POST request to login, if credentials are correct backend creates cookie with token, then frontend makes a GET request to get informations about the logged user.
When both backend and frontend apps were working locally, everything worked fine. But after deploying them to Azure, the GET user endpoint always returns error 401. I think the problem is, that both apps run in different domains. When I login using swagger, everything works fine and I can see the right cookie in devtools. When I login using frontend, there is no cookie in devtools, so it doesn't work.
URLs look like that:
Backend: https://somerandomname.azurewebsites.net/
Frontend: https://anotherrandomname.azurestaticapps.net/
I create cookies like that:
Response.Cookies.Append("jwt", jwt, new CookieOptions
{
HttpOnly = true
});
I read about CookieOptions class, so I tried something like this:
Response.Cookies.Append("jwt", jwt, new CookieOptions
{
HttpOnly = true,
Domain = ".azurestaticapps.net"
});
but not only it doesn't fix the problem, when I type something into CookieOptions.Domain I can't see any cookie at all, even in Postman.
So my question is: what am I doing wrong? How to set the cookie's domain so that my frontend could read them?
|
[
"It looks like the problem is that your backend and frontend are running on different domains.\nWhen you set a cookie in your backend, the cookie is only accessible on that domain. In order for your frontend to be able to access the cookie, you will need to set the domain of the cookie to a domain that your frontend has access to. In this case, it looks like you are setting the domain to \".azurestaticapps.net\", which is the domain of your frontend app. However, it looks like this is not the correct domain for your cookie.\nSet the domain of the cookie to \".azurewebsites.net\". This will allow your frontend app to access the cookie on the \".azurewebsites.net\" domain. You can do this by setting the domain property of the CookieOptions object when you append the cookie to the response, like this:\nResponse.Cookies.Append(\"jwt\", jwt, new CookieOptions\n{\nHttpOnly = true,\nDomain = \".azurewebsites.net\"\n});\n\nYou can also set the domain of the cookie to \".azurestaticapps.net\" and then configure your backend app to allow your frontend app to access the cookie on this domain. This can be done by setting the Access-Control-Allow-Origin header in your backend app's response to \".azurestaticapps.net\". This will allow\n"
] |
[
0
] |
[] |
[] |
[
"asp.net_core",
"asp.net_core_webapi",
"authentication",
"cookies",
"reactjs"
] |
stackoverflow_0074669129_asp.net_core_asp.net_core_webapi_authentication_cookies_reactjs.txt
|
Q:
Make `Box>` peekable
Playground
I have the following type definition:
pub struct UTF8Chars {
bytes: Peekable<Box<dyn Iterator<Item = u8>>>,
}
Now I'm wondering how to actually create an instance of this struct.
I've tried (and yes, this is inside a trait implementation if that is an important detail):
impl<'a> ToUTF8Chars for &'a str {
fn utf8_chars(self) -> UTF8Chars {
let bytes = Box::new(self.bytes()).peekable();
UTF8Chars { bytes }
}
}
That gives me the error:
expected struct `Peekable<Box<(dyn Iterator<Item = u8> + 'static)>>`
found struct `Peekable<Box<std::str::Bytes<'_>>>`
Forgive me if I try weird things, but I haven't gotten the hang of this intricate trait stuff yet. For all I know, rust-analyzer was telling me that Bytes in fact an impl Iterator<Item = u8>. So, next thing I tried was casting it first:
let bytes = Box::new(self.bytes()) as Box<dyn Iterator<Item = u8>>;
UTF8Chars { bytes: bytes.peekable() }
That sort of works, but now the lifetime checker is complaining:
impl<'a> ToUTF8Chars for &'a str {
-- lifetime `'a` defined here
fn utf8_chars(self) -> UTF8Chars {
let bytes = Box::new(self.bytes()) as Box<dyn Iterator<Item = u8>>;
^^^^^^^^^^^^^^^^^^^^^^ cast requires that `'a` must outlive `'static`
I'm not exactly sure what is going out of scope here... as far as I know, I own the result from .bytes() (I also tried with an additional .clone() in case that assumption was incorrect), I own the Box, the Box is passed to Peekable, and finally Peekable is passed to UTF8Chars. What exactly is the issue here? Why do I somehow need to outlive static...?
I found this issue that seems similar, sadly no answer: Peekable of an Iterator in struct.
Why I want to do this?
Well, mainly because I don't really care, or am unable to care what exactly the underlying data is. I just need to know that I can .peek(), and .next(), etc. This is, because sometimes I want to assign different things to self.bytes. For example, Chain<...>, or Copied<...> instead of a simple vec::IntoIter<...>.
If there is an alternative approach to this, I'm happy to hear about it.
A:
So, next thing I tried was casting it first:
let bytes = Box::new(self.bytes()) as Box<dyn Iterator<Item = u8>>;
This is the right thing to do in this situation, though I would write it with a type annotation on the let, instead of as.
let bytes: Box<dyn Iterator<Item = u8>> = Box::new(self.bytes());
In particular, there must be a point at which the unsizing coercion from Box<Bytes> to Box<dyn Iterator<Item = u8>> happens, and that point must be before the Box is contained in something else (because it actually produces a different Box, one with a vtable pointer added).
In some cases, just as _ (unspecified type) is sufficient to prompt the compiler into not immediately concluding that the type is the same as the incoming type.
I'm not exactly sure what is going out of scope here...
Every trait object (dyn) type has a lifetime, often implicit. This lifetime specifies how long instances of that type are guaranteed valid — or, from the opposite perspective, what references the trait object is allowed to borrow/contain.
When you don't specify that lifetime, and the trait object is in a Box, lifetime elision rules make that lifetime be 'static. That's why you have an error: you're trying to put a Bytes<'a> in a place where 'static is required.
In order to allow your boxed iterator to borrow, you must define the types and traits to have a lifetime.
use core::iter::Peekable;
pub struct UTF8Chars<'a> {
bytes: Peekable<Box<dyn Iterator<Item = u8> + 'a>>,
}
trait ToUTF8Chars<'a> {
fn utf8_chars(self) -> UTF8Chars<'a>;
}
impl<'a> ToUTF8Chars<'a> for &'a str {
fn utf8_chars(self) -> UTF8Chars<'a> {
let bytes: Box<dyn Iterator<Item = u8> + 'a> = Box::new(self.bytes());
UTF8Chars {
bytes: bytes.peekable(),
}
}
}
If you don't want to add a lifetime, then you must only use owning iterators (e.g. String::into_bytes(s).into_iter()). With the lifetime, you can use both owning and borrowing iterators.
A:
The issue is that dyn Trait types are actually dyn Trait + 'static by default, which means they're not allowed to borrow any data. That's a problem for you because the iterator returned by calling bytes() on a &'a str borrows from that str and thus cannot outlive 'a. But 'a doesn't outlive 'static so you can't make a dyn Iterator + 'static from it.
As you might have guessed, the solution here is adding some more general lifetime bounds, first to the struct:
pub struct UTF8Chars<'a> {
// ^^^^ now generic over 'a
bytes: Peekable<Box<dyn Iterator<Item = u8> + 'a>>,
// ------------------------^^^^
// the iterator is now allowed to borrow data for 'a
}
Then to the trait:
trait ToUTF8Chars {
fn utf8_chars<'a>(self) -> UTF8Chars<'a> where Self: 'a;
// ^^^^ also generic over 'a ^^^^^^^^ self can borrow data for 'a
}
Depending on your exact use case, using a borrowed receiver might be nicer, though:
trait ToUTF8Chars {
fn utf8_chars<'a>(&'a self) -> UTF8Chars<'a>;
// ^^^^ just borrow `self` for 'a
}
I'm sure there's a cases where these two aren't the same (object safety, probably?) but I can't pin point a specific situation off the top of my head.
And finally the implementation:
impl<'b> ToUTF8Chars for &'b str {
fn utf8_chars<'a>(self) -> UTF8Chars<'a> where Self: 'a {
let bytes = Box::new(self.bytes()) as Box<dyn Iterator<Item = u8>>;
UTF8Chars { bytes: bytes.peekable() }
}
}
or
impl ToUTF8Chars for str {
fn utf8_chars<'a>(&'a str) -> UTF8Chars<'a> {
let bytes = Box::new(self.bytes()) as Box<dyn Iterator<Item = u8>>;
UTF8Chars { bytes: bytes.peekable() }
}
}
for the alternative version of ToUTF8Chars.
|
Make `Box>` peekable
|
Playground
I have the following type definition:
pub struct UTF8Chars {
bytes: Peekable<Box<dyn Iterator<Item = u8>>>,
}
Now I'm wondering how to actually create an instance of this struct.
I've tried (and yes, this is inside a trait implementation if that is an important detail):
impl<'a> ToUTF8Chars for &'a str {
fn utf8_chars(self) -> UTF8Chars {
let bytes = Box::new(self.bytes()).peekable();
UTF8Chars { bytes }
}
}
That gives me the error:
expected struct `Peekable<Box<(dyn Iterator<Item = u8> + 'static)>>`
found struct `Peekable<Box<std::str::Bytes<'_>>>`
Forgive me if I try weird things, but I haven't gotten the hang of this intricate trait stuff yet. For all I know, rust-analyzer was telling me that Bytes in fact an impl Iterator<Item = u8>. So, next thing I tried was casting it first:
let bytes = Box::new(self.bytes()) as Box<dyn Iterator<Item = u8>>;
UTF8Chars { bytes: bytes.peekable() }
That sort of works, but now the lifetime checker is complaining:
impl<'a> ToUTF8Chars for &'a str {
-- lifetime `'a` defined here
fn utf8_chars(self) -> UTF8Chars {
let bytes = Box::new(self.bytes()) as Box<dyn Iterator<Item = u8>>;
^^^^^^^^^^^^^^^^^^^^^^ cast requires that `'a` must outlive `'static`
I'm not exactly sure what is going out of scope here... as far as I know, I own the result from .bytes() (I also tried with an additional .clone() in case that assumption was incorrect), I own the Box, the Box is passed to Peekable, and finally Peekable is passed to UTF8Chars. What exactly is the issue here? Why do I somehow need to outlive static...?
I found this issue that seems similar, sadly no answer: Peekable of an Iterator in struct.
Why I want to do this?
Well, mainly because I don't really care, or am unable to care what exactly the underlying data is. I just need to know that I can .peek(), and .next(), etc. This is, because sometimes I want to assign different things to self.bytes. For example, Chain<...>, or Copied<...> instead of a simple vec::IntoIter<...>.
If there is an alternative approach to this, I'm happy to hear about it.
|
[
"\nSo, next thing I tried was casting it first:\nlet bytes = Box::new(self.bytes()) as Box<dyn Iterator<Item = u8>>;\n\n\nThis is the right thing to do in this situation, though I would write it with a type annotation on the let, instead of as.\nlet bytes: Box<dyn Iterator<Item = u8>> = Box::new(self.bytes());\n\nIn particular, there must be a point at which the unsizing coercion from Box<Bytes> to Box<dyn Iterator<Item = u8>> happens, and that point must be before the Box is contained in something else (because it actually produces a different Box, one with a vtable pointer added).\nIn some cases, just as _ (unspecified type) is sufficient to prompt the compiler into not immediately concluding that the type is the same as the incoming type.\n\nI'm not exactly sure what is going out of scope here...\n\nEvery trait object (dyn) type has a lifetime, often implicit. This lifetime specifies how long instances of that type are guaranteed valid — or, from the opposite perspective, what references the trait object is allowed to borrow/contain.\nWhen you don't specify that lifetime, and the trait object is in a Box, lifetime elision rules make that lifetime be 'static. That's why you have an error: you're trying to put a Bytes<'a> in a place where 'static is required.\nIn order to allow your boxed iterator to borrow, you must define the types and traits to have a lifetime.\nuse core::iter::Peekable;\n\npub struct UTF8Chars<'a> {\n bytes: Peekable<Box<dyn Iterator<Item = u8> + 'a>>,\n}\n\ntrait ToUTF8Chars<'a> {\n fn utf8_chars(self) -> UTF8Chars<'a>;\n}\n\nimpl<'a> ToUTF8Chars<'a> for &'a str {\n fn utf8_chars(self) -> UTF8Chars<'a> {\n let bytes: Box<dyn Iterator<Item = u8> + 'a> = Box::new(self.bytes());\n\n UTF8Chars {\n bytes: bytes.peekable(),\n }\n }\n}\n\nIf you don't want to add a lifetime, then you must only use owning iterators (e.g. String::into_bytes(s).into_iter()). With the lifetime, you can use both owning and borrowing iterators.\n",
"The issue is that dyn Trait types are actually dyn Trait + 'static by default, which means they're not allowed to borrow any data. That's a problem for you because the iterator returned by calling bytes() on a &'a str borrows from that str and thus cannot outlive 'a. But 'a doesn't outlive 'static so you can't make a dyn Iterator + 'static from it.\nAs you might have guessed, the solution here is adding some more general lifetime bounds, first to the struct:\npub struct UTF8Chars<'a> {\n // ^^^^ now generic over 'a\n bytes: Peekable<Box<dyn Iterator<Item = u8> + 'a>>,\n // ------------------------^^^^\n // the iterator is now allowed to borrow data for 'a\n}\n\nThen to the trait:\ntrait ToUTF8Chars {\n fn utf8_chars<'a>(self) -> UTF8Chars<'a> where Self: 'a;\n // ^^^^ also generic over 'a ^^^^^^^^ self can borrow data for 'a\n}\n\nDepending on your exact use case, using a borrowed receiver might be nicer, though:\ntrait ToUTF8Chars {\n fn utf8_chars<'a>(&'a self) -> UTF8Chars<'a>;\n // ^^^^ just borrow `self` for 'a\n}\n\nI'm sure there's a cases where these two aren't the same (object safety, probably?) but I can't pin point a specific situation off the top of my head.\nAnd finally the implementation:\nimpl<'b> ToUTF8Chars for &'b str {\n fn utf8_chars<'a>(self) -> UTF8Chars<'a> where Self: 'a {\n let bytes = Box::new(self.bytes()) as Box<dyn Iterator<Item = u8>>;\n\n UTF8Chars { bytes: bytes.peekable() }\n }\n}\n\nor\nimpl ToUTF8Chars for str {\n fn utf8_chars<'a>(&'a str) -> UTF8Chars<'a> {\n let bytes = Box::new(self.bytes()) as Box<dyn Iterator<Item = u8>>;\n\n UTF8Chars { bytes: bytes.peekable() }\n }\n}\n\nfor the alternative version of ToUTF8Chars.\n"
] |
[
3,
1
] |
[] |
[] |
[
"rust"
] |
stackoverflow_0074669017_rust.txt
|
Q:
kubectl copy logs from pod when terminating
We are trying to get the logs of pods after multiple restarts but we dont want to use any external solution like efk.
i tried below config but its not working. does the below cmd run on the pod or it will run on node level
lifecycle:
preStop:
exec:
command: ["/bin/sh", "-c", "kubectl logs appworks-0 > /container-stoped.txt"]
A:
i tried below config but its not working. does the below cmd run on
the pod or it will run on node level
it will run on the POD level, not on Node level
You can use the Hostpath in POD configuration
apiVersion: v1
kind: Pod
metadata:
name: test-pd
spec:
containers:
- image: alpine
name: test-container
command: ["tail"]
args: ["-f", "/dev/null"]
volumeMounts:
- mountPath: /host
name: test-volume
volumes:
- name: test-volume
hostPath:
path: /
type: Directory
Hostpath will directly will create one Dir at the Node level and save logs over there, if you don't want this solution you can add your solution of lifecycle hook also however when you can directly write app logs to Host don't add lifecycle hook extra.
Note : Make sure if your Node goes down hostpath or emptyDir logs you will miss.
A:
there is an issue with the command you are using in the preStop hook. The kubectl logs command is used to print the logs of a container, but it is not a command that can be run inside a container. Instead, you can use the logs command of the busybox image, which is a small Linux utility image that includes many common Unix command line utilities.
For example, you could use the following preStop hook to print the logs of the appworks-0 container to the file /container-stopped.txt before the container is terminated:
lifecycle:
preStop:
exec:
command: ["/bin/sh", "-c", "logs appworks-0 > /container-stopped.txt"]
You will also need to make sure that the appworks-0 container has the /container-stopped.txt file mounted as a volume, so that it is accessible to the preStop hook.
It's important to note that the preStop hook will only run if the container is terminated. If the container is restarted, the preStop hook will not be executed again.
|
kubectl copy logs from pod when terminating
|
We are trying to get the logs of pods after multiple restarts but we dont want to use any external solution like efk.
i tried below config but its not working. does the below cmd run on the pod or it will run on node level
lifecycle:
preStop:
exec:
command: ["/bin/sh", "-c", "kubectl logs appworks-0 > /container-stoped.txt"]
|
[
"\ni tried below config but its not working. does the below cmd run on\nthe pod or it will run on node level\n\nit will run on the POD level, not on Node level\nYou can use the Hostpath in POD configuration\napiVersion: v1\nkind: Pod\nmetadata:\n name: test-pd\nspec:\n containers: \n - image: alpine\n name: test-container\n command: [\"tail\"]\n args: [\"-f\", \"/dev/null\"] \n volumeMounts:\n - mountPath: /host\n name: test-volume\n volumes:\n - name: test-volume\n hostPath:\n path: /\n type: Directory\n\nHostpath will directly will create one Dir at the Node level and save logs over there, if you don't want this solution you can add your solution of lifecycle hook also however when you can directly write app logs to Host don't add lifecycle hook extra.\nNote : Make sure if your Node goes down hostpath or emptyDir logs you will miss.\n",
"there is an issue with the command you are using in the preStop hook. The kubectl logs command is used to print the logs of a container, but it is not a command that can be run inside a container. Instead, you can use the logs command of the busybox image, which is a small Linux utility image that includes many common Unix command line utilities.\nFor example, you could use the following preStop hook to print the logs of the appworks-0 container to the file /container-stopped.txt before the container is terminated:\nlifecycle:\n preStop:\n exec:\n command: [\"/bin/sh\", \"-c\", \"logs appworks-0 > /container-stopped.txt\"]\n\nYou will also need to make sure that the appworks-0 container has the /container-stopped.txt file mounted as a volume, so that it is accessible to the preStop hook.\nIt's important to note that the preStop hook will only run if the container is terminated. If the container is restarted, the preStop hook will not be executed again.\n"
] |
[
0,
0
] |
[] |
[] |
[
"kubernetes",
"logging"
] |
stackoverflow_0074650507_kubernetes_logging.txt
|
Q:
How to change color based on random number
I want to make a part that will change color depending on the seed.
Example:
if seed = 1 then
part.Color3 = red
end
which is like this, but with randomization
Nothing, im really dont know to make or try this
A:
Make a list of the items, then use the math.random function to pick one out of the list.
-- create a list of colors
local colors = {
Color3.fromRGB(255, 0, 0), --red
Color3.fromRGB(0, 255, 0), --green
Color3.fromRGB(0, 0, 255), --blue
}
-- select a random number based on the length of the list
local index = math.random(#colors)
-- choose a color from the list
local rndColor = colors[index]
-- locate the part
local part = script.Parent
-- assign the color to the part
part.Color3 = rndColor
|
How to change color based on random number
|
I want to make a part that will change color depending on the seed.
Example:
if seed = 1 then
part.Color3 = red
end
which is like this, but with randomization
Nothing, im really dont know to make or try this
|
[
"Make a list of the items, then use the math.random function to pick one out of the list.\n-- create a list of colors\nlocal colors = {\n Color3.fromRGB(255, 0, 0), --red\n Color3.fromRGB(0, 255, 0), --green\n Color3.fromRGB(0, 0, 255), --blue\n}\n\n-- select a random number based on the length of the list\nlocal index = math.random(#colors)\n\n-- choose a color from the list\nlocal rndColor = colors[index]\n\n-- locate the part\nlocal part = script.Parent\n\n-- assign the color to the part\npart.Color3 = rndColor\n\n"
] |
[
0
] |
[] |
[] |
[
"lua",
"roblox"
] |
stackoverflow_0074665995_lua_roblox.txt
|
Q:
DefaultRenderer error in xamarin.forms (Android)
I am using xamarin forms... And sometimes when I try to go back to my previous page I see this (Android device):
System.NotSupportedException: Unable to activate instance of type Xamarin.Forms.Platform.Android.Platform+DefaultRenderer from native handle 0xbeb4a30c
I saw this same issue with label renderer and box renderer but I solved it by creating a constructor in a custom renderer as the link below suggests:
MonoDroid: Error when calling constructor of custom view - TwoDScrollView
But there's nothing about DefaultRenderer error as all where I have searched in for these last 30 days...I am getting crazy...
complete exception:
System.NotSupportedException: Unable to activate instance of type Xamarin.Forms.Platform.Android.Platform+DefaultRenderer from native handle 0xbecdf3ac (key_handle 0x24da7695).
04-04 11:51:53.914 D/Mono (30832): DllImport attempting to load: '/system/lib/liblog.so'. 04-04 11:51:53.914 D/Mono (30832): DllImport loaded library '/system/lib/liblog.so'. 04-04 11:51:53.914 D/Mono (30832): DllImport searching in: '/system/lib/liblog.so' ('/system/lib/liblog.so'). 04-04 11:51:53.914 D/Mono (30832): Searching for '__android_log_print'. 04-04 11:51:53.914 D/Mono (30832): Probing '__android_log_print'. 04-04 11:51:53.914 D/Mono (30832): Found as '__android_log_print'. 04-04 11:51:53.924 I/MonoDroid(30832): UNHANDLED EXCEPTION: 04-04 11:51:53.944 I/MonoDroid(30832): System.NotSupportedException: Unable to activate instance of type Xamarin.Forms.Platform.Android.Platform+DefaultRenderer from native handle 0xbecdf3ac (key_handle 0x24da7695). ---> System.MissingMethodException: No constructor found for Xamarin.Forms.Platform.Android.Platform+DefaultRenderer::.ctor(System.IntPtr, Android.Runtime.JniHandleOwnership) ---> Java.Interop.JavaLocationException: Exception of type 'Java.Interop.JavaLocationException' was thrown. 04-04 11:51:53.944 I/MonoDroid(30832): --- End of inner exception stack trace --- 04-04 11:51:53.944 I/MonoDroid(30832): at Java.Interop.TypeManager.CreateProxy (System.Type type, System.IntPtr handle, Android.Runtime.JniHandleOwnership transfer) [0x00054] in <e79c73bcbbb547688bef6c7e9665c95e>:0 04-04 11:51:53.944 I/MonoDroid(30832): at Java.Interop.TypeManager.CreateInstance (System.IntPtr handle, Android.Runtime.JniHandleOwnership transfer, System.Type targetType) [0x00111] in <e79c73bcbbb547688bef6c7e9665c95e>:0 04-04 11:51:53.944 I/MonoDroid(30832): --- End of inner exception stack trace --- 04-04 11:51:53.944 I/MonoDroid(30832): at Java.Interop.TypeManager.CreateInstance (System.IntPtr handle, Android.Runtime.JniHandleOwnership transfer, System.Type targetType) [0x0017d] in <e79c73bcbbb547688bef6c7e9665c95e>:0 04-04 11:51:53.944 I/MonoDroid(30832): at Java.Lang.Object.GetObject (System.IntPtr handle, Android.Runtime.JniHandleOwnership transfer, System.Type type) [0x000b9] in <e79c73bcbbb547688bef6c7e9665c95e>:0 04-04 11:51:53.944 I/MonoDroid(30832): at Java.Lang.Object._GetObject[T] (System.IntPtr handle, Android.Runtime.JniHandleOwnership transfer) [0x00017] in <e79c73bcbbb547688bef6c7e9665c95e>:0 04-04 11:51:53.944 I/MonoDroid(30832): at Java.Lang.Object.GetObject[T] (System.IntPtr handle, Android.Runtime.JniHandleOwnership transfer) [0x00000] in <e79c73bcbbb547688bef6c7e9665c95e>:0 04-04 11:51:53.944 I/MonoDroid(30832): at Java.Lang.Object.GetObject[T] (System.IntPtr jnienv, System.IntPtr handle, Android.Runtime.JniHandleOwnership transfer) [0x00006] in <e79c73bcbbb547688bef6c7e9665c95e>:0 04-04 11:51:53.944 I/MonoDroid(30832): at Android.Views.View.n_DispatchTouchEvent_Landroid_view_MotionEvent_ (System.IntPtr jnienv, System.IntPtr native__this, System.IntPtr native_e) [0x00000] in <e79c73bcbbb547688bef6c7e9665c95e>:0 04-04 11:51:53.944 I/MonoDroid(30832): at (wrapper dynamic-method) System.Object:cce836e4-e6e4-4d51-a0da-36412953d80b (intptr,intptr,intptr) 04-04 11:51:53.964 W/art (30832): JNI RegisterNativeMethods: attempt to register 0 native methods for android.runtime.JavaProxyThrowable 04-04 11:51:53.964 D/Mono (30832): DllImport searching in: '__Internal' ('(null)'). 04-04 11:51:53.964 D/Mono (30832): Searching for 'java_interop_jnienv_throw'. 04-04 11:51:53.964 D/Mono (30832): Probing 'java_interop_jnienv_throw'. 04-04 11:51:53.964 D/Mono (30832): Found as 'java_interop_jnienv_throw'. Unhandled Exception:
System.NotSupportedException: Unable to activate instance of type Xamarin.Forms.Platform.Android.Platform+DefaultRenderer from native handle 0xbecdf3ac (key_handle 0x24da7695).
04-04 11:51:57.014 I/art (30832): Thread[2,tid=30839,WaitingInMainSignalCatcherLoop,Thread*=0xaf90e400,peer=0x12c4d080,"Signal Catcher"]: reacting to signal 3 04-04 11:51:57.584 I/art (30832): Wrote stack traces to '/data/anr/traces.txt' 04-04 11:52:07.844 I/MonoDroid(30832): UNHANDLED EXCEPTION: 04-04 11:52:07.894 I/MonoDroid(30832): System.NotSupportedException: Unable to activate instance of type Xamarin.Forms.Platform.Android.Platform+DefaultRenderer from native handle 0xbecdf3ac (key_handle 0x24da7695). ---> System.MissingMethodException: No constructor found for Xamarin.Forms.Platform.Android.Platform+DefaultRenderer::.ctor(System.IntPtr, Android.Runtime.JniHandleOwnership) ---> Java.Interop.JavaLocationException: Exception of type 'Java.Interop.JavaLocationException' was thrown. 04-04 11:52:07.894 I/MonoDroid(30832): --- End of inner exception stack trace --- 04-04 11:52:07.894 I/MonoDroid(30832): at Java.Interop.TypeManager.CreateProxy (System.Type type, System.IntPtr handle, Android.Runtime.JniHandleOwnership transfer) [0x00054] in <e79c73bcbbb547688bef6c7e9665c95e>:0 04-04 11:52:07.894 I/MonoDroid(30832): at Java.Interop.TypeManager.CreateInstance (System.IntPtr handle, Android.Runtime.JniHandleOwnership transfer, System.Type targetType) [0x00111] in <e79c73bcbbb547688bef6c7e9665c95e>:0 04-04 11:52:07.894 I/MonoDroid(30832): --- End of inner exception stack trace --- 04-04 11:52:07.894 I/MonoDroid(30832): at (wrapper dynamic-method) System.Object:cce836e4-e6e4-4d51-a0da-36412953d80b (intptr,intptr,intptr) 04-04 11:52:07.894 I/MonoDroid(30832): at (wrapper managed-to-native) Java.Interop.NativeMethods:java_interop_jnienv_call_nonvirtual_void_method_a (intptr,intptr&,intptr,intptr,intptr,Java.Interop.JniArgumentValue*) 04-04 11:52:07.894 I/MonoDroid(30832): at Java.Interop.JniEnvironment+InstanceMethods.CallNonvirtualVoidMethod (Java.Interop.JniObjectReference instance, Java.Interop.JniObjectReference type, Java.Interop.JniMethodInfo method, Java.Interop.JniArgumentValue* args) [0x00073] in <e8c0e16a54534fa885244f0ad837c79e>:0 04-04 11:52:07.894 I/MonoDroid(30832): at Java.Interop.JniPeerMembers+JniInstanceMethods.InvokeVirtualVoidMethod (System.String encodedMember, Java.Interop.IJavaPeerable self, Java.Interop.JniArgumentValue* parameters) [0x0005d] in <e8c0e16a54534fa885244f0ad837c79e>:0 04-04 11:52:07.894 I/MonoDroid(30832): at Android.Views.ViewGroup.RemoveAllViews () [0x0000a] in <e79c73bcbbb547688bef6c7e9665c95e>:0 04-04 11:52:07.894 I/MonoDroid(30832): at Xamarin.Forms.Platform.Android.VisualElementRenderer`1[TElement].Dispose (System.Boolean disposing) [0x00088] in D:\agent_work\1\s\Xamarin.Forms.Platform.Android\VisualElementRenderer.cs:238 04-04 11:52:07.894 I/MonoDroid(30832): at Java.Lang.Object.Dispose () [0x00000] in <e79c73bcbbb547688bef6c7e9665c95e>:0 04-04 11:52:07.894 I/MonoDroid(30832): at Xamarin.Forms.Platform.Android.ListViewRenderer.ClearRenderer (Android.Views.View renderedView) [0x00032] in D:\agent_work\1\s\Xamarin.Forms.Platform.Android\Renderers\ListViewRenderer.cs:295 04-04 11:52:07.894 I/MonoDroid(30832): at Xamarin.Forms.Platform.Android.ListViewRenderer.Dispose (System.Boolean disposing) [0x0001e] in D:\agent_work\1\s\Xamarin.Forms.Platform.Android\Renderers\ListViewRenderer.cs:59 04-04 11:52:07.894 I/MonoDroid(30832): at Java.Lang.Object.Dispose () [0x00000] in <e79c73bcbbb547688bef6c7e9665c95e>:0 04-04 11:52:07.894 I/MonoDroid(30832): at Xamarin.Forms.Platform.Android.VisualElementRenderer`1[TElement].Dispose (System.Boolean disposing) [0x0007b] in D:\agent_work\1\s\Xamarin.Forms.Platform.Android\VisualElementRenderer.cs:234 04-04 11:52:07.894 I/MonoDroid(30832): at Java.Lang.Object.Dispose () [0x00000] in <e79c73bcbbb547688bef6c7e9665c95e>:0 04-04 11:52:07.894 I/MonoDroid(30832): at Xamarin.Forms.Platform.Android.VisualElementRenderer`1[TElement].Dispose (System.Boolean disposing) [0x0007b] in D:\agent_work\1\s\Xamarin.Forms.Platform.Android\VisualElementRenderer.cs:234 04-04 11:52:07.894 I/MonoDroid(30832): at Xamarin.Forms.Platform.Android.PageRenderer.Dispose (System.Boolean disposing) [0x00011] in D:\agent_work\1\s\Xamarin.Forms.Platform.Android\Renderers\PageRenderer.cs:33 04-04 11:52:07.894 I/MonoDroid(30832): at Java.Lang.Object.Dispose () [0x00000] in <e79c73bcbbb547688bef6c7e9665c95e>:0 04-04 11:52:07.894 I/MonoDroid(30832): at Xamarin.Forms.Platform.Android.AppCompat.FragmentContainer.OnDestroyView () [0x0003c] in D:\agent_work\1\s\Xamarin.Forms.Platform.Android\AppCompat\FragmentContainer.cs:91 04-04 11:52:07.894 I/MonoDroid(30832): at Android.Support.V4.App.Fragment.n_OnDestroyView (System.IntPtr jnienv, System.IntPtr native__this) [0x00008] in <1e89c43d3c7d48b5ba69bfc0b1bdf114>:0 04-04 11:52:07.894 I/MonoDroid(30832): at (wrapper dynamic-method) System.Object:1df32498-cacf-4686-8c6a-cd4a5d878faf (intptr,intptr) 04-04 11:52:07.914 E/mono-rt (30832): Stacktrace: 04-04 11:52:07.914 E/mono-rt (30832): 04-04 11:52:07.914 E/mono-rt (30832): at <unknown> <0xffffffff> 04-04 11:52:07.914 E/mono-rt (30832): at (wrapper managed-to-native) Java.Interop.NativeMethods.java_interop_jnienv_new_string (intptr,intptr&,char*,int) <0x00043> 04-04 11:52:07.914 E/mono-rt (30832): at Java.Interop.JniEnvironment/Strings.NewString (char*,int) [0x00009] in <e8c0e16a54534fa885244f0ad837c79e>:0 04-04 11:52:07.924 E/mono-rt (30832): at Java.Interop.JniEnvironment/Strings.NewString (string) [0x00024] in <e8c0e16a54534fa885244f0ad837c79e>:0 04-04 11:52:07.924 E/mono-rt (30832): at Android.Runtime.JNIEnv.NewString (string) [0x0000a] in <e79c73bcbbb547688bef6c7e9665c95e>:0 04-04 11:52:07.924 E/mono-rt (30832): at Java.Lang.Error..ctor (string) [0x00020] in <e79c73bcbbb547688bef6c7e9665c95e>:0 04-04 11:52:07.924 E/mono-rt (30832): at Android.Runtime.JavaProxyThrowable..ctor (System.Exception) [0x00007] in <e79c73bcbbb547688bef6c7e9665c95e>:0 04-04 11:52:07.924 E/mono-rt (30832): at Java.Lang.Throwable.FromException (System.Exception) [0x0001e] in <e79c73bcbbb547688bef6c7e9665c95e>:0 04-04 11:52:07.924 E/mono-rt (30832): at Android.Runtime.AndroidEnvironment.UnhandledException (System.Exception) [0x00068] in <e79c73bcbbb547688bef6c7e9665c95e>:0 04-04 11:52:07.924 E/mono-rt (30832): at (wrapper dynamic-method) object.1df32498-cacf-4686-8c6a-cd4a5d878faf (intptr,intptr) [0x00029] in <657aa8fea4454dc898a9e5f379c58734>:0 04-04 11:52:07.924 E/mono-rt (30832): at (wrapper native-to-managed) object.1df32498-cacf-4686-8c6a-cd4a5d878faf (intptr,intptr) [0x00021] in <657aa8fea4454dc898a9e5f379c58734>:0 04-04 11:52:07.924 E/mono-rt (30832): /proc/self/maps:
A:
This should be solved by using old JNI constructors and legacy renderers
public MyLabelRenderer(IntPtr handle, JniHandleOwnership transfer)
{
}
and by setting UseLegacyRenderers flag in MainActivity
Forms.SetFlags("UseLegacyRenderers");
A:
The DefaultRenderer error you're encountering is caused by an exception thrown in the constructor of the DefaultRenderer class. This error is typically caused by a missing or incorrect implementation of the Xamarin.Forms.Platform.Android.IVisualElementRenderer interface in a custom renderer.
To fix this error, you need to ensure that your custom renderer correctly implements the IVisualElementRenderer interface, and that it has a constructor with the following signature:
public MyCustomRenderer(Context context) : base(context)
{
// Initialization code here...
}
This constructor should call the base class's constructor with the Context argument provided as a parameter.
Once you have added this constructor to your custom renderer, the DefaultRenderer error should no longer occur. If the issue persists, you may need to clear the app's data or uninstall and reinstall the app to fully resolve the issue.
|
DefaultRenderer error in xamarin.forms (Android)
|
I am using xamarin forms... And sometimes when I try to go back to my previous page I see this (Android device):
System.NotSupportedException: Unable to activate instance of type Xamarin.Forms.Platform.Android.Platform+DefaultRenderer from native handle 0xbeb4a30c
I saw this same issue with label renderer and box renderer but I solved it by creating a constructor in a custom renderer as the link below suggests:
MonoDroid: Error when calling constructor of custom view - TwoDScrollView
But there's nothing about DefaultRenderer error as all where I have searched in for these last 30 days...I am getting crazy...
complete exception:
System.NotSupportedException: Unable to activate instance of type Xamarin.Forms.Platform.Android.Platform+DefaultRenderer from native handle 0xbecdf3ac (key_handle 0x24da7695).
04-04 11:51:53.914 D/Mono (30832): DllImport attempting to load: '/system/lib/liblog.so'. 04-04 11:51:53.914 D/Mono (30832): DllImport loaded library '/system/lib/liblog.so'. 04-04 11:51:53.914 D/Mono (30832): DllImport searching in: '/system/lib/liblog.so' ('/system/lib/liblog.so'). 04-04 11:51:53.914 D/Mono (30832): Searching for '__android_log_print'. 04-04 11:51:53.914 D/Mono (30832): Probing '__android_log_print'. 04-04 11:51:53.914 D/Mono (30832): Found as '__android_log_print'. 04-04 11:51:53.924 I/MonoDroid(30832): UNHANDLED EXCEPTION: 04-04 11:51:53.944 I/MonoDroid(30832): System.NotSupportedException: Unable to activate instance of type Xamarin.Forms.Platform.Android.Platform+DefaultRenderer from native handle 0xbecdf3ac (key_handle 0x24da7695). ---> System.MissingMethodException: No constructor found for Xamarin.Forms.Platform.Android.Platform+DefaultRenderer::.ctor(System.IntPtr, Android.Runtime.JniHandleOwnership) ---> Java.Interop.JavaLocationException: Exception of type 'Java.Interop.JavaLocationException' was thrown. 04-04 11:51:53.944 I/MonoDroid(30832): --- End of inner exception stack trace --- 04-04 11:51:53.944 I/MonoDroid(30832): at Java.Interop.TypeManager.CreateProxy (System.Type type, System.IntPtr handle, Android.Runtime.JniHandleOwnership transfer) [0x00054] in <e79c73bcbbb547688bef6c7e9665c95e>:0 04-04 11:51:53.944 I/MonoDroid(30832): at Java.Interop.TypeManager.CreateInstance (System.IntPtr handle, Android.Runtime.JniHandleOwnership transfer, System.Type targetType) [0x00111] in <e79c73bcbbb547688bef6c7e9665c95e>:0 04-04 11:51:53.944 I/MonoDroid(30832): --- End of inner exception stack trace --- 04-04 11:51:53.944 I/MonoDroid(30832): at Java.Interop.TypeManager.CreateInstance (System.IntPtr handle, Android.Runtime.JniHandleOwnership transfer, System.Type targetType) [0x0017d] in <e79c73bcbbb547688bef6c7e9665c95e>:0 04-04 11:51:53.944 I/MonoDroid(30832): at Java.Lang.Object.GetObject (System.IntPtr handle, Android.Runtime.JniHandleOwnership transfer, System.Type type) [0x000b9] in <e79c73bcbbb547688bef6c7e9665c95e>:0 04-04 11:51:53.944 I/MonoDroid(30832): at Java.Lang.Object._GetObject[T] (System.IntPtr handle, Android.Runtime.JniHandleOwnership transfer) [0x00017] in <e79c73bcbbb547688bef6c7e9665c95e>:0 04-04 11:51:53.944 I/MonoDroid(30832): at Java.Lang.Object.GetObject[T] (System.IntPtr handle, Android.Runtime.JniHandleOwnership transfer) [0x00000] in <e79c73bcbbb547688bef6c7e9665c95e>:0 04-04 11:51:53.944 I/MonoDroid(30832): at Java.Lang.Object.GetObject[T] (System.IntPtr jnienv, System.IntPtr handle, Android.Runtime.JniHandleOwnership transfer) [0x00006] in <e79c73bcbbb547688bef6c7e9665c95e>:0 04-04 11:51:53.944 I/MonoDroid(30832): at Android.Views.View.n_DispatchTouchEvent_Landroid_view_MotionEvent_ (System.IntPtr jnienv, System.IntPtr native__this, System.IntPtr native_e) [0x00000] in <e79c73bcbbb547688bef6c7e9665c95e>:0 04-04 11:51:53.944 I/MonoDroid(30832): at (wrapper dynamic-method) System.Object:cce836e4-e6e4-4d51-a0da-36412953d80b (intptr,intptr,intptr) 04-04 11:51:53.964 W/art (30832): JNI RegisterNativeMethods: attempt to register 0 native methods for android.runtime.JavaProxyThrowable 04-04 11:51:53.964 D/Mono (30832): DllImport searching in: '__Internal' ('(null)'). 04-04 11:51:53.964 D/Mono (30832): Searching for 'java_interop_jnienv_throw'. 04-04 11:51:53.964 D/Mono (30832): Probing 'java_interop_jnienv_throw'. 04-04 11:51:53.964 D/Mono (30832): Found as 'java_interop_jnienv_throw'. Unhandled Exception:
System.NotSupportedException: Unable to activate instance of type Xamarin.Forms.Platform.Android.Platform+DefaultRenderer from native handle 0xbecdf3ac (key_handle 0x24da7695).
04-04 11:51:57.014 I/art (30832): Thread[2,tid=30839,WaitingInMainSignalCatcherLoop,Thread*=0xaf90e400,peer=0x12c4d080,"Signal Catcher"]: reacting to signal 3 04-04 11:51:57.584 I/art (30832): Wrote stack traces to '/data/anr/traces.txt' 04-04 11:52:07.844 I/MonoDroid(30832): UNHANDLED EXCEPTION: 04-04 11:52:07.894 I/MonoDroid(30832): System.NotSupportedException: Unable to activate instance of type Xamarin.Forms.Platform.Android.Platform+DefaultRenderer from native handle 0xbecdf3ac (key_handle 0x24da7695). ---> System.MissingMethodException: No constructor found for Xamarin.Forms.Platform.Android.Platform+DefaultRenderer::.ctor(System.IntPtr, Android.Runtime.JniHandleOwnership) ---> Java.Interop.JavaLocationException: Exception of type 'Java.Interop.JavaLocationException' was thrown. 04-04 11:52:07.894 I/MonoDroid(30832): --- End of inner exception stack trace --- 04-04 11:52:07.894 I/MonoDroid(30832): at Java.Interop.TypeManager.CreateProxy (System.Type type, System.IntPtr handle, Android.Runtime.JniHandleOwnership transfer) [0x00054] in <e79c73bcbbb547688bef6c7e9665c95e>:0 04-04 11:52:07.894 I/MonoDroid(30832): at Java.Interop.TypeManager.CreateInstance (System.IntPtr handle, Android.Runtime.JniHandleOwnership transfer, System.Type targetType) [0x00111] in <e79c73bcbbb547688bef6c7e9665c95e>:0 04-04 11:52:07.894 I/MonoDroid(30832): --- End of inner exception stack trace --- 04-04 11:52:07.894 I/MonoDroid(30832): at (wrapper dynamic-method) System.Object:cce836e4-e6e4-4d51-a0da-36412953d80b (intptr,intptr,intptr) 04-04 11:52:07.894 I/MonoDroid(30832): at (wrapper managed-to-native) Java.Interop.NativeMethods:java_interop_jnienv_call_nonvirtual_void_method_a (intptr,intptr&,intptr,intptr,intptr,Java.Interop.JniArgumentValue*) 04-04 11:52:07.894 I/MonoDroid(30832): at Java.Interop.JniEnvironment+InstanceMethods.CallNonvirtualVoidMethod (Java.Interop.JniObjectReference instance, Java.Interop.JniObjectReference type, Java.Interop.JniMethodInfo method, Java.Interop.JniArgumentValue* args) [0x00073] in <e8c0e16a54534fa885244f0ad837c79e>:0 04-04 11:52:07.894 I/MonoDroid(30832): at Java.Interop.JniPeerMembers+JniInstanceMethods.InvokeVirtualVoidMethod (System.String encodedMember, Java.Interop.IJavaPeerable self, Java.Interop.JniArgumentValue* parameters) [0x0005d] in <e8c0e16a54534fa885244f0ad837c79e>:0 04-04 11:52:07.894 I/MonoDroid(30832): at Android.Views.ViewGroup.RemoveAllViews () [0x0000a] in <e79c73bcbbb547688bef6c7e9665c95e>:0 04-04 11:52:07.894 I/MonoDroid(30832): at Xamarin.Forms.Platform.Android.VisualElementRenderer`1[TElement].Dispose (System.Boolean disposing) [0x00088] in D:\agent_work\1\s\Xamarin.Forms.Platform.Android\VisualElementRenderer.cs:238 04-04 11:52:07.894 I/MonoDroid(30832): at Java.Lang.Object.Dispose () [0x00000] in <e79c73bcbbb547688bef6c7e9665c95e>:0 04-04 11:52:07.894 I/MonoDroid(30832): at Xamarin.Forms.Platform.Android.ListViewRenderer.ClearRenderer (Android.Views.View renderedView) [0x00032] in D:\agent_work\1\s\Xamarin.Forms.Platform.Android\Renderers\ListViewRenderer.cs:295 04-04 11:52:07.894 I/MonoDroid(30832): at Xamarin.Forms.Platform.Android.ListViewRenderer.Dispose (System.Boolean disposing) [0x0001e] in D:\agent_work\1\s\Xamarin.Forms.Platform.Android\Renderers\ListViewRenderer.cs:59 04-04 11:52:07.894 I/MonoDroid(30832): at Java.Lang.Object.Dispose () [0x00000] in <e79c73bcbbb547688bef6c7e9665c95e>:0 04-04 11:52:07.894 I/MonoDroid(30832): at Xamarin.Forms.Platform.Android.VisualElementRenderer`1[TElement].Dispose (System.Boolean disposing) [0x0007b] in D:\agent_work\1\s\Xamarin.Forms.Platform.Android\VisualElementRenderer.cs:234 04-04 11:52:07.894 I/MonoDroid(30832): at Java.Lang.Object.Dispose () [0x00000] in <e79c73bcbbb547688bef6c7e9665c95e>:0 04-04 11:52:07.894 I/MonoDroid(30832): at Xamarin.Forms.Platform.Android.VisualElementRenderer`1[TElement].Dispose (System.Boolean disposing) [0x0007b] in D:\agent_work\1\s\Xamarin.Forms.Platform.Android\VisualElementRenderer.cs:234 04-04 11:52:07.894 I/MonoDroid(30832): at Xamarin.Forms.Platform.Android.PageRenderer.Dispose (System.Boolean disposing) [0x00011] in D:\agent_work\1\s\Xamarin.Forms.Platform.Android\Renderers\PageRenderer.cs:33 04-04 11:52:07.894 I/MonoDroid(30832): at Java.Lang.Object.Dispose () [0x00000] in <e79c73bcbbb547688bef6c7e9665c95e>:0 04-04 11:52:07.894 I/MonoDroid(30832): at Xamarin.Forms.Platform.Android.AppCompat.FragmentContainer.OnDestroyView () [0x0003c] in D:\agent_work\1\s\Xamarin.Forms.Platform.Android\AppCompat\FragmentContainer.cs:91 04-04 11:52:07.894 I/MonoDroid(30832): at Android.Support.V4.App.Fragment.n_OnDestroyView (System.IntPtr jnienv, System.IntPtr native__this) [0x00008] in <1e89c43d3c7d48b5ba69bfc0b1bdf114>:0 04-04 11:52:07.894 I/MonoDroid(30832): at (wrapper dynamic-method) System.Object:1df32498-cacf-4686-8c6a-cd4a5d878faf (intptr,intptr) 04-04 11:52:07.914 E/mono-rt (30832): Stacktrace: 04-04 11:52:07.914 E/mono-rt (30832): 04-04 11:52:07.914 E/mono-rt (30832): at <unknown> <0xffffffff> 04-04 11:52:07.914 E/mono-rt (30832): at (wrapper managed-to-native) Java.Interop.NativeMethods.java_interop_jnienv_new_string (intptr,intptr&,char*,int) <0x00043> 04-04 11:52:07.914 E/mono-rt (30832): at Java.Interop.JniEnvironment/Strings.NewString (char*,int) [0x00009] in <e8c0e16a54534fa885244f0ad837c79e>:0 04-04 11:52:07.924 E/mono-rt (30832): at Java.Interop.JniEnvironment/Strings.NewString (string) [0x00024] in <e8c0e16a54534fa885244f0ad837c79e>:0 04-04 11:52:07.924 E/mono-rt (30832): at Android.Runtime.JNIEnv.NewString (string) [0x0000a] in <e79c73bcbbb547688bef6c7e9665c95e>:0 04-04 11:52:07.924 E/mono-rt (30832): at Java.Lang.Error..ctor (string) [0x00020] in <e79c73bcbbb547688bef6c7e9665c95e>:0 04-04 11:52:07.924 E/mono-rt (30832): at Android.Runtime.JavaProxyThrowable..ctor (System.Exception) [0x00007] in <e79c73bcbbb547688bef6c7e9665c95e>:0 04-04 11:52:07.924 E/mono-rt (30832): at Java.Lang.Throwable.FromException (System.Exception) [0x0001e] in <e79c73bcbbb547688bef6c7e9665c95e>:0 04-04 11:52:07.924 E/mono-rt (30832): at Android.Runtime.AndroidEnvironment.UnhandledException (System.Exception) [0x00068] in <e79c73bcbbb547688bef6c7e9665c95e>:0 04-04 11:52:07.924 E/mono-rt (30832): at (wrapper dynamic-method) object.1df32498-cacf-4686-8c6a-cd4a5d878faf (intptr,intptr) [0x00029] in <657aa8fea4454dc898a9e5f379c58734>:0 04-04 11:52:07.924 E/mono-rt (30832): at (wrapper native-to-managed) object.1df32498-cacf-4686-8c6a-cd4a5d878faf (intptr,intptr) [0x00021] in <657aa8fea4454dc898a9e5f379c58734>:0 04-04 11:52:07.924 E/mono-rt (30832): /proc/self/maps:
|
[
"This should be solved by using old JNI constructors and legacy renderers\npublic MyLabelRenderer(IntPtr handle, JniHandleOwnership transfer)\n{\n}\n\nand by setting UseLegacyRenderers flag in MainActivity\nForms.SetFlags(\"UseLegacyRenderers\");\n\n",
"The DefaultRenderer error you're encountering is caused by an exception thrown in the constructor of the DefaultRenderer class. This error is typically caused by a missing or incorrect implementation of the Xamarin.Forms.Platform.Android.IVisualElementRenderer interface in a custom renderer.\nTo fix this error, you need to ensure that your custom renderer correctly implements the IVisualElementRenderer interface, and that it has a constructor with the following signature:\npublic MyCustomRenderer(Context context) : base(context)\n{\n // Initialization code here...\n}\n\nThis constructor should call the base class's constructor with the Context argument provided as a parameter.\nOnce you have added this constructor to your custom renderer, the DefaultRenderer error should no longer occur. If the issue persists, you may need to clear the app's data or uninstall and reinstall the app to fully resolve the issue.\n"
] |
[
0,
0
] |
[] |
[] |
[
"android",
"mobile",
"renderer",
"xamarin.forms"
] |
stackoverflow_0049619076_android_mobile_renderer_xamarin.forms.txt
|
Q:
Advice on how to debug python code using Pycharm
I am a relatively new python user, and wanted advice on how best to debug my code.
Currently, I have a script (main.py), that I run in debug mode using PyCharm. This file is quite short, as most of my functions are contained within another module I have written (i.e. functionsmodule.py). If I put breakpoints in the function I want to modify in functionsmodule.py, this works quite well - then I can explore the variables available inside this function.
However, if I update the function in 'functionsmodule.py', save the file, then reload using importlib.reload, the breakpoints don't seem to be recognised anymore. I then have to rerun the whole of main.py to get to the breakpoint again.
Is there a better solution to this? Thanks for your help!
A:
You can specify a breakpoint in the code directly using the built-in breakpoint()function, which might help in a case like this.
See PEP-553 for more details.
|
Advice on how to debug python code using Pycharm
|
I am a relatively new python user, and wanted advice on how best to debug my code.
Currently, I have a script (main.py), that I run in debug mode using PyCharm. This file is quite short, as most of my functions are contained within another module I have written (i.e. functionsmodule.py). If I put breakpoints in the function I want to modify in functionsmodule.py, this works quite well - then I can explore the variables available inside this function.
However, if I update the function in 'functionsmodule.py', save the file, then reload using importlib.reload, the breakpoints don't seem to be recognised anymore. I then have to rerun the whole of main.py to get to the breakpoint again.
Is there a better solution to this? Thanks for your help!
|
[
"You can specify a breakpoint in the code directly using the built-in breakpoint()function, which might help in a case like this.\nSee PEP-553 for more details.\n"
] |
[
1
] |
[] |
[] |
[
"debugging",
"pycharm",
"python"
] |
stackoverflow_0074669843_debugging_pycharm_python.txt
|
Q:
Flutter, I get an error when using CupertinoTabScaffold
CupertinoTabScaffold(
tabBar: CupertinoTabBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: '',
),
BottomNavigationBarItem(
icon: Icon(Icons.favorite),
label: '',
),
BottomNavigationBarItem(
icon: Icon(Icons.shopping_cart),
label: '',
),
],
),
tabBuilder: (context, index) {
switch (index) {
case 0:
return CupertinoTabView(builder: (context) {
return const CupertinoPageScaffold(
child: Categories(), );
});
case 1:
return CupertinoTabView(builder: (context) {
return const CupertinoPageScaffold(
child: FavPage(), );
});
case 2:
return CupertinoTabView(builder: (context) {
return const CupertinoPageScaffold(
child: Cart(), );
});
default:
return CupertinoTabView(builder: (context) {
return const CupertinoPageScaffold(
child: Categories(), );
});
}
},
);
error message:
Could not find a generator for route RouteSettings("/categoryDetails", GzE5usW4fApu38pjA) in the_CupertinoTabViewState.
when I click on a category in the "Categories" screen it has to navigate to "CategoryDetails" screen
A:
This should fix it
CupertinoTabScaffold(
tabBar: CupertinoTabBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: '',
),
BottomNavigationBarItem(
icon: Icon(Icons.favorite),
label: '',
),
BottomNavigationBarItem(
icon: Icon(Icons.shopping_cart),
label: '',
),
],
),
tabBuilder: (BuildContext context, int index) {
assert(index >= 0 && index <= 2);
switch (index) {
case 0:
return CupertinoTabView(
builder: (BuildContext context) => Categories(),,
);
break;
case 1:
return CupertinoTabView(
builder: (BuildContext context) => FavPage(),
);
break;
case 2:
return CupertinoTabView(
builder: (BuildContext context) => Cart(),
);
break;
}
return CupertinoTabView(
builder: (BuildContext context) => Categories(),
);
}
},
);
A:
Use as routes or onGenererateRoutes according to your requirements in TabViewState of CuptinoTabBar.
Something like this...
return CupertinoTabView(
routes: appRoutes,
//or
onGenerateRoutes: ...,
|
Flutter, I get an error when using CupertinoTabScaffold
|
CupertinoTabScaffold(
tabBar: CupertinoTabBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: '',
),
BottomNavigationBarItem(
icon: Icon(Icons.favorite),
label: '',
),
BottomNavigationBarItem(
icon: Icon(Icons.shopping_cart),
label: '',
),
],
),
tabBuilder: (context, index) {
switch (index) {
case 0:
return CupertinoTabView(builder: (context) {
return const CupertinoPageScaffold(
child: Categories(), );
});
case 1:
return CupertinoTabView(builder: (context) {
return const CupertinoPageScaffold(
child: FavPage(), );
});
case 2:
return CupertinoTabView(builder: (context) {
return const CupertinoPageScaffold(
child: Cart(), );
});
default:
return CupertinoTabView(builder: (context) {
return const CupertinoPageScaffold(
child: Categories(), );
});
}
},
);
error message:
Could not find a generator for route RouteSettings("/categoryDetails", GzE5usW4fApu38pjA) in the_CupertinoTabViewState.
when I click on a category in the "Categories" screen it has to navigate to "CategoryDetails" screen
|
[
"This should fix it\nCupertinoTabScaffold(\n tabBar: CupertinoTabBar(\n items: const <BottomNavigationBarItem>[\n BottomNavigationBarItem(\n icon: Icon(Icons.home),\n label: '',\n ),\n BottomNavigationBarItem(\n icon: Icon(Icons.favorite),\n label: '',\n ),\n BottomNavigationBarItem(\n icon: Icon(Icons.shopping_cart),\n label: '',\n ),\n ],\n ),\n tabBuilder: (BuildContext context, int index) {\n assert(index >= 0 && index <= 2);\n switch (index) {\n case 0:\n return CupertinoTabView(\n builder: (BuildContext context) => Categories(),,\n );\n break;\n \n case 1:\n return CupertinoTabView(\n builder: (BuildContext context) => FavPage(),\n );\n break;\n \n case 2:\n return CupertinoTabView(\n builder: (BuildContext context) => Cart(),\n );\n break;\n }\n return CupertinoTabView(\n builder: (BuildContext context) => Categories(),\n ); \n }\n }, \n ); \n\n\n",
"Use as routes or onGenererateRoutes according to your requirements in TabViewState of CuptinoTabBar.\nSomething like this...\nreturn CupertinoTabView(\n routes: appRoutes,\n//or\n onGenerateRoutes: ...,\n\n"
] |
[
0,
0
] |
[] |
[] |
[
"dart",
"flutter",
"flutter_bottomnavigation"
] |
stackoverflow_0073198210_dart_flutter_flutter_bottomnavigation.txt
|
Q:
Replacing words in a string with words given in a 2D array
I'm currently working on a program that corrects given words in a sentence to be more polite.
I'm building a function that is given the original sentence and a 2D array, that stores the words we should look for and the ones we will replace them with.
This is my main function where the "dictionary" is declared:
int main(){
const char * d1 [][2] =
{
{ "hey", "hello" },
{ "bro", "sir" },
{ NULL, NULL }
};
printf("%s\n", newSpeak("well hey bro", d1) );
}
This functions job is to go through every pointer of the original string and check it with the first character of each word, that could potentially be 'bad'. If it catches the first letter, then it will go through the rest of the word and if it goes all the way to the end of the word, it will skip the original word and replace it with the 'good' word.
This is the function itself:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <assert.h>
char * newSpeak ( const char * text, const char * (*replace)[2] )
{
char * result = (char*)malloc( sizeof(char) );
int resIndex = 0; // Pointer to final text
int matches = 0; // 1 - Matches word from library, 0 - Does not
// Run through the whole original text
for ( int index = 0; text[index] != '\0'; index++ ){
for ( int line = 0; replace[line][0] != NULL; line++ ){
// If the first letter of the word matches, do the others match too?
// If yes, don't rewrite the original word, skip it, and write the replacement one by one.
if ( replace[line][0][0] == text[index] ){
matches = 1;
// Check one by one if letters from the word align with letters in the original string
for ( int letter = 0; replace[line][0][letter] != '\0'; letter++ ){
if ( replace[line][0][letter] != text[index + letter] ){
matches = 0;
break;
}
}
// If the whole word matches, skip what would be copied from original text (the bad word) and put in replacement letter by letter
if ( matches == 1 ){
// Push pointer of original string after the word
index += strlen( replace[line][0] );
for ( int r = 0; r < strlen( replace[line][1] ); r++){
result = (char*)realloc(result, (strlen( result ) + 1) * sizeof(char));
result[resIndex + r] = replace[line][1][r];
index += r;
}
}
}
}
if ( matches == 0 ){
result = (char*)realloc(result, (strlen( result ) + 1) * sizeof(char));
result[resIndex] = text[index];
}
resIndex++;
}
return result;
}
After this is run, my expected outcome is well hello sir, but instead, the function only returns well hello.
I am looking for an explanation to why the loop would stop and not check for the rest of the string, any help would be appreciated.
A:
At least this problem:
strlen( result ) in result = (char*)realloc(result, (strlen( result ) + 1) * sizeof(char)); is not valid as result does not point to a string. Missing null character.
|
Replacing words in a string with words given in a 2D array
|
I'm currently working on a program that corrects given words in a sentence to be more polite.
I'm building a function that is given the original sentence and a 2D array, that stores the words we should look for and the ones we will replace them with.
This is my main function where the "dictionary" is declared:
int main(){
const char * d1 [][2] =
{
{ "hey", "hello" },
{ "bro", "sir" },
{ NULL, NULL }
};
printf("%s\n", newSpeak("well hey bro", d1) );
}
This functions job is to go through every pointer of the original string and check it with the first character of each word, that could potentially be 'bad'. If it catches the first letter, then it will go through the rest of the word and if it goes all the way to the end of the word, it will skip the original word and replace it with the 'good' word.
This is the function itself:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <assert.h>
char * newSpeak ( const char * text, const char * (*replace)[2] )
{
char * result = (char*)malloc( sizeof(char) );
int resIndex = 0; // Pointer to final text
int matches = 0; // 1 - Matches word from library, 0 - Does not
// Run through the whole original text
for ( int index = 0; text[index] != '\0'; index++ ){
for ( int line = 0; replace[line][0] != NULL; line++ ){
// If the first letter of the word matches, do the others match too?
// If yes, don't rewrite the original word, skip it, and write the replacement one by one.
if ( replace[line][0][0] == text[index] ){
matches = 1;
// Check one by one if letters from the word align with letters in the original string
for ( int letter = 0; replace[line][0][letter] != '\0'; letter++ ){
if ( replace[line][0][letter] != text[index + letter] ){
matches = 0;
break;
}
}
// If the whole word matches, skip what would be copied from original text (the bad word) and put in replacement letter by letter
if ( matches == 1 ){
// Push pointer of original string after the word
index += strlen( replace[line][0] );
for ( int r = 0; r < strlen( replace[line][1] ); r++){
result = (char*)realloc(result, (strlen( result ) + 1) * sizeof(char));
result[resIndex + r] = replace[line][1][r];
index += r;
}
}
}
}
if ( matches == 0 ){
result = (char*)realloc(result, (strlen( result ) + 1) * sizeof(char));
result[resIndex] = text[index];
}
resIndex++;
}
return result;
}
After this is run, my expected outcome is well hello sir, but instead, the function only returns well hello.
I am looking for an explanation to why the loop would stop and not check for the rest of the string, any help would be appreciated.
|
[
"At least this problem:\nstrlen( result ) in result = (char*)realloc(result, (strlen( result ) + 1) * sizeof(char)); is not valid as result does not point to a string. Missing null character.\n"
] |
[
0
] |
[] |
[] |
[
"arrays",
"c",
"string"
] |
stackoverflow_0074669710_arrays_c_string.txt
|
Q:
React > Define a common useEffect to use across components
Innocent React question here.
I have a useEffect method that closes a modal on the escape keypress, that is duplicated a few times in my code, that looks like this:
const [shouldShowModal, setShouldShowModal] = useProfileModal();
useEffect(() => {
const closeModalOnEscape = (e: KeyboardEvent | any): void => {
if (e.key === "Escape") setShouldShowModal(false);
};
document.addEventListener("keydown", closeModalOnEscape);
return () => {
document.removeEventListener("keydown", closeModalOnEscape);
};
}, [setShouldShowModal]);
Is there a way I can define the useEffect piece to use across multiple components?
A:
Just define a custom hook that takes in a setter
const useCloseModalOnEscape = (setShouldShowModal) => {
useEffect(() => {
const closeModalOnEscape = (e: KeyboardEvent | any): void => {
if (e.key === "Escape") setShouldShowModal(false);
};
document.addEventListener("keydown", closeModalOnEscape);
return () => {
document.removeEventListener("keydown", closeModalOnEscape);
};
}, [setShouldShowModal]);
}
And then use it like this:
const [shouldShowModal, setShouldShowModal] = useProfileModal();
useCloseModalOnEscape(setShouldShowModal);
You can rename setShouldShowModal or useCloseModalOnEscape to be something more accurate to your other use cases if they're not all in the context of closing modals.
If every instance of useProfileModal will close on escape, then you should just include the useEffect (from inside of useCloseModalOnEscape) in useProfileModal.
A:
Since every use of useProfileModal uses the effect, just put the effect inside useProfileModal. That way, the code in every component only needs to be
const [shouldShowModal, setShouldShowModal] = useProfileModal();
and have, in useProfileModal:
const useProfileModal = () => {
// ...
useEffect(() => {
const closeModalOnEscape = (e: KeyboardEvent | any): void => {
if (e.key === "Escape") setShouldShowModal(false);
};
document.addEventListener("keydown", closeModalOnEscape);
return () => {
document.removeEventListener("keydown", closeModalOnEscape);
};
}, [setShouldShowModal]);
// ...
return [shouldShowModal, setShouldShowModal];
A:
Yes, the useEffect code can be defined as a separate function and then called from multiple components.
// Define a custom hook to handle the keydown event
function useCloseModalOnEscape(toggleModal) {
useEffect(() => {
const closeModalOnEscape = (e: KeyboardEvent | any): void => {
if (e.key === "Escape") toggleModal({ shouldShowModal: false });
};
document.addEventListener("keydown", closeModalOnEscape);
return () => {
document.removeEventListener("keydown", closeModalOnEscape);
};
}, [toggleModal]);
}
// Define a component that uses the custom hook
function MyComponent() {
const [{ shouldShowModal, profile }, toggleModal] = useProfileModal();
// Call the custom hook to handle the keydown event
useCloseModalOnEscape(toggleModal);
// Other component code...
}
useCloseModalOnEscape function is a custom hook that takes the toggleModal function as an argument and handles the keydown event.
The MyComponent component uses the useProfileModal hook to get the toggleModal function, and then calls the `useClose
|
React > Define a common useEffect to use across components
|
Innocent React question here.
I have a useEffect method that closes a modal on the escape keypress, that is duplicated a few times in my code, that looks like this:
const [shouldShowModal, setShouldShowModal] = useProfileModal();
useEffect(() => {
const closeModalOnEscape = (e: KeyboardEvent | any): void => {
if (e.key === "Escape") setShouldShowModal(false);
};
document.addEventListener("keydown", closeModalOnEscape);
return () => {
document.removeEventListener("keydown", closeModalOnEscape);
};
}, [setShouldShowModal]);
Is there a way I can define the useEffect piece to use across multiple components?
|
[
"Just define a custom hook that takes in a setter\nconst useCloseModalOnEscape = (setShouldShowModal) => {\n useEffect(() => {\n const closeModalOnEscape = (e: KeyboardEvent | any): void => {\n if (e.key === \"Escape\") setShouldShowModal(false);\n };\n document.addEventListener(\"keydown\", closeModalOnEscape);\n return () => {\n document.removeEventListener(\"keydown\", closeModalOnEscape);\n };\n }, [setShouldShowModal]);\n}\n\nAnd then use it like this:\nconst [shouldShowModal, setShouldShowModal] = useProfileModal();\n\nuseCloseModalOnEscape(setShouldShowModal);\n\nYou can rename setShouldShowModal or useCloseModalOnEscape to be something more accurate to your other use cases if they're not all in the context of closing modals.\n\nIf every instance of useProfileModal will close on escape, then you should just include the useEffect (from inside of useCloseModalOnEscape) in useProfileModal.\n",
"Since every use of useProfileModal uses the effect, just put the effect inside useProfileModal. That way, the code in every component only needs to be\nconst [shouldShowModal, setShouldShowModal] = useProfileModal();\n\nand have, in useProfileModal:\nconst useProfileModal = () => {\n // ...\n useEffect(() => {\n const closeModalOnEscape = (e: KeyboardEvent | any): void => {\n if (e.key === \"Escape\") setShouldShowModal(false);\n };\n document.addEventListener(\"keydown\", closeModalOnEscape);\n return () => {\n document.removeEventListener(\"keydown\", closeModalOnEscape);\n };\n }, [setShouldShowModal]);\n // ...\n return [shouldShowModal, setShouldShowModal];\n\n",
"Yes, the useEffect code can be defined as a separate function and then called from multiple components.\n// Define a custom hook to handle the keydown event\nfunction useCloseModalOnEscape(toggleModal) {\n useEffect(() => {\n const closeModalOnEscape = (e: KeyboardEvent | any): void => {\n if (e.key === \"Escape\") toggleModal({ shouldShowModal: false });\n };\n document.addEventListener(\"keydown\", closeModalOnEscape);\n return () => {\n document.removeEventListener(\"keydown\", closeModalOnEscape);\n };\n }, [toggleModal]);\n}\n\n// Define a component that uses the custom hook\nfunction MyComponent() {\n const [{ shouldShowModal, profile }, toggleModal] = useProfileModal();\n\n // Call the custom hook to handle the keydown event\n useCloseModalOnEscape(toggleModal);\n\n // Other component code...\n}\n\nuseCloseModalOnEscape function is a custom hook that takes the toggleModal function as an argument and handles the keydown event.\nThe MyComponent component uses the useProfileModal hook to get the toggleModal function, and then calls the `useClose\n"
] |
[
1,
1,
0
] |
[] |
[] |
[
"next.js",
"react_hooks",
"reactjs",
"typescript"
] |
stackoverflow_0074669565_next.js_react_hooks_reactjs_typescript.txt
|
Q:
How do I implement a custom UITextInputTokenizer?
I have a UITextView and am using its tokenizer to check which words the user taps on.
My goal is to change what the tokenizer thinks of as a word. Currently it seems to define words as consecutive alphanumeric characters, I want a word to be defined as consecutive characters that aren't a space character (" ").
For example: 'foo-bar', 'foo/bar' and 'foo@@bar' will all currently be treated as two separate words ('foo' and 'bar') but I want them all to be treated as a single word (as none of them contain spaces).
The documentation talks about subclassing the UITextInputStringTokenizer class but I can't find a single example of someone doing this and I can't figure out how I would go about implementing the required methods:
func isPosition(position: UITextPosition, atBoundary granularity: UITextGranularity, inDirection direction: UITextDirection) -> Bool
func isPosition(position: UITextPosition, withinTextUnit granularity: UITextGranularity, inDirection direction: UITextDirection) -> Bool
func positionFromPosition(position: UITextPosition, toBoundary granularity: UITextGranularity, inDirection direction: UITextDirection) -> UITextPosition?
func rangeEnclosingPosition(position: UITextPosition, withGranularity granularity: UITextGranularity, inDirection direction: UITextDirection) -> UITextRange?
A:
To summarize, create your implementation that extends UITextInputStringTokenizer and leave most methods untouched (or just calling super)
You just need to override isPosition(_:atBoundary:inDirection:) and isPosition(_:withinTextUnit:inDirection:) when granularity is word to check if the characters next to that position are considered to be in a word boundary, i.e., alphanumeric character and space together. The default implementation will return true also for other non-spaces that are considered not part of a word, you instead consider those as forming part of a word.
When granularity is not word, you can default to super as well.
A:
// Create a subclass of UITextInputStringTokenizer
class CustomTokenizer: UITextInputStringTokenizer {
// Override the rangeEnclosingPosition method so that it looks for characters that are not a space (" ")
override func rangeEnclosingPosition(position: UITextPosition, withGranularity granularity: UITextGranularity, inDirection direction: UITextDirection) -> UITextRange? {
// First check if the range enclosing the position is not nil
guard let range = super.rangeEnclosingPosition(position: position, withGranularity: granularity, inDirection: direction) else {
return nil
}
// Then define a string of characters that are not a space (" ")
let nonSpaceCharacterSet = CharacterSet.init(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLKMNOPQRSTUVWXYZ1234567890_")
// Then define a range which will be used to search for the non space characters
let startIndex = range.start
let endIndex = range.end
let searchRange = startIndex..<endIndex
// Then define a string based on the range
let text = self.textInput.text(in: searchRange)
// Then search the string for any characters that are not a space (" ")
if let _ = text?.rangeOfCharacter(from: nonSpaceCharacterSet) {
// If any characters that are not a space (" ") are found, then return the range
return range
} else {
// Otherwise, return nil
return nil
}
}
}
// Then set the tokenizer of the UITextView to the CustomTokenizer
textView.tokenizer = CustomTokenizer(textInput: textView)
|
How do I implement a custom UITextInputTokenizer?
|
I have a UITextView and am using its tokenizer to check which words the user taps on.
My goal is to change what the tokenizer thinks of as a word. Currently it seems to define words as consecutive alphanumeric characters, I want a word to be defined as consecutive characters that aren't a space character (" ").
For example: 'foo-bar', 'foo/bar' and 'foo@@bar' will all currently be treated as two separate words ('foo' and 'bar') but I want them all to be treated as a single word (as none of them contain spaces).
The documentation talks about subclassing the UITextInputStringTokenizer class but I can't find a single example of someone doing this and I can't figure out how I would go about implementing the required methods:
func isPosition(position: UITextPosition, atBoundary granularity: UITextGranularity, inDirection direction: UITextDirection) -> Bool
func isPosition(position: UITextPosition, withinTextUnit granularity: UITextGranularity, inDirection direction: UITextDirection) -> Bool
func positionFromPosition(position: UITextPosition, toBoundary granularity: UITextGranularity, inDirection direction: UITextDirection) -> UITextPosition?
func rangeEnclosingPosition(position: UITextPosition, withGranularity granularity: UITextGranularity, inDirection direction: UITextDirection) -> UITextRange?
|
[
"To summarize, create your implementation that extends UITextInputStringTokenizer and leave most methods untouched (or just calling super)\nYou just need to override isPosition(_:atBoundary:inDirection:) and isPosition(_:withinTextUnit:inDirection:) when granularity is word to check if the characters next to that position are considered to be in a word boundary, i.e., alphanumeric character and space together. The default implementation will return true also for other non-spaces that are considered not part of a word, you instead consider those as forming part of a word.\nWhen granularity is not word, you can default to super as well.\n",
"// Create a subclass of UITextInputStringTokenizer\nclass CustomTokenizer: UITextInputStringTokenizer {\n// Override the rangeEnclosingPosition method so that it looks for characters that are not a space (\" \")\noverride func rangeEnclosingPosition(position: UITextPosition, withGranularity granularity: UITextGranularity, inDirection direction: UITextDirection) -> UITextRange? {\n // First check if the range enclosing the position is not nil\n guard let range = super.rangeEnclosingPosition(position: position, withGranularity: granularity, inDirection: direction) else {\n return nil\n }\n \n // Then define a string of characters that are not a space (\" \")\n let nonSpaceCharacterSet = CharacterSet.init(charactersIn: \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLKMNOPQRSTUVWXYZ1234567890_\")\n \n // Then define a range which will be used to search for the non space characters\n let startIndex = range.start\n let endIndex = range.end\n let searchRange = startIndex..<endIndex\n \n // Then define a string based on the range\n let text = self.textInput.text(in: searchRange)\n \n // Then search the string for any characters that are not a space (\" \")\n if let _ = text?.rangeOfCharacter(from: nonSpaceCharacterSet) {\n // If any characters that are not a space (\" \") are found, then return the range\n return range\n } else {\n // Otherwise, return nil\n return nil\n }\n}\n\n}\n// Then set the tokenizer of the UITextView to the CustomTokenizer\ntextView.tokenizer = CustomTokenizer(textInput: textView)\n"
] |
[
0,
0
] |
[] |
[] |
[
"ios",
"swift",
"tokenize",
"uitextview"
] |
stackoverflow_0029434960_ios_swift_tokenize_uitextview.txt
|
Q:
How to make a Constructor without parameters?
I have to write a program that has a constructor without parameters. I created another short program as an example to show what I do not understand.
So I have a class with the main-method:
public class Dog {
public static void main(String[] args) {
CharacteristicsOfTheDog Dog1 = new CharacteristicsOfTheDog(20, 40);
System.out.println(Dog1.toString());
}
}
Now implemented another class:
public class CharacteristicsOfTheDog {
int size = 0;
int kilogram = 0;
public CharacteristicsOfTheDog(/*int size, int kilogram*/) {
// this.size = size;
// this.kilogram = kilogram;
}
public double getSize() {
return size;
}
public double getKilogram() {
return kilogram;
}
public String toString() {
return "The Dog is " + getSize() + " cm and " + getKilogram() + " kg";
}
}
In the class "CharacteristicsOfTheDog" in "public CharacteristicsOfTheDog()" I removed the parameters by commenting them out. So the Problem is: if I remove the parameters the program does not work:/ but my task is to do this without the parameters (as far as I understood). Can someone help me please?
A:
Keep your no-arg constructor and then add setters for your properties:
public class CharacteristicsOfTheDog {
int size = 0;
int kilogram = 0;
public CharacteristicsOfTheDog() {
}
public void setSize(int size){
this.size = size;
}
public void setKilogram(int kilogram){
this.kilogram = kilogram;
}
}
In your other class, call:
CharacteristicsOfTheDog dog1 = new CharacteristicsOfTheDog();
dog.setSize(20);
dog.setKilogram(40);
As a suggestion, the naming of your class as CharacteristicsOfTheDog is rather literal and stating the obvious. Properties and methods of a class are what describes the characteristics of a class in terms of it's properties and behavior. If you just name your class Dog, that would be perfect. No need to state the obvious.
A:
Unless CharacteristicsOfTheDog is a subclass or you have a constructor with parameters, you don't need an empty constructor. Just omit it. The following works just fine.
If the parent class has a constructor with arguments, then the parent class will need an explicit empty constructor, but the following should still work.
CharacteristicsOfTheDog cotd = new CharacteristicsOfTheDog();
cotd.setKilogram(100);
}
class CharacteristicsOfTheDog {
int size = 0;
int kilogram = 0;
public void setSize(int size){
this.size = size;
}
public void setKilogram(int kilogram){
this.kilogram = kilogram;
}
}
Depending on your use case, you might want to make the Characteristics class an interface and implement it.
|
How to make a Constructor without parameters?
|
I have to write a program that has a constructor without parameters. I created another short program as an example to show what I do not understand.
So I have a class with the main-method:
public class Dog {
public static void main(String[] args) {
CharacteristicsOfTheDog Dog1 = new CharacteristicsOfTheDog(20, 40);
System.out.println(Dog1.toString());
}
}
Now implemented another class:
public class CharacteristicsOfTheDog {
int size = 0;
int kilogram = 0;
public CharacteristicsOfTheDog(/*int size, int kilogram*/) {
// this.size = size;
// this.kilogram = kilogram;
}
public double getSize() {
return size;
}
public double getKilogram() {
return kilogram;
}
public String toString() {
return "The Dog is " + getSize() + " cm and " + getKilogram() + " kg";
}
}
In the class "CharacteristicsOfTheDog" in "public CharacteristicsOfTheDog()" I removed the parameters by commenting them out. So the Problem is: if I remove the parameters the program does not work:/ but my task is to do this without the parameters (as far as I understood). Can someone help me please?
|
[
"Keep your no-arg constructor and then add setters for your properties:\npublic class CharacteristicsOfTheDog {\n\n int size = 0;\n int kilogram = 0;\n\n public CharacteristicsOfTheDog() {\n }\n\n public void setSize(int size){\n this.size = size;\n }\n\n public void setKilogram(int kilogram){\n this.kilogram = kilogram;\n }\n}\n\nIn your other class, call:\nCharacteristicsOfTheDog dog1 = new CharacteristicsOfTheDog();\ndog.setSize(20);\ndog.setKilogram(40);\n\nAs a suggestion, the naming of your class as CharacteristicsOfTheDog is rather literal and stating the obvious. Properties and methods of a class are what describes the characteristics of a class in terms of it's properties and behavior. If you just name your class Dog, that would be perfect. No need to state the obvious.\n",
"Unless CharacteristicsOfTheDog is a subclass or you have a constructor with parameters, you don't need an empty constructor. Just omit it. The following works just fine.\nIf the parent class has a constructor with arguments, then the parent class will need an explicit empty constructor, but the following should still work.\nCharacteristicsOfTheDog cotd = new CharacteristicsOfTheDog();\n cotd.setKilogram(100);\n}\n\nclass CharacteristicsOfTheDog {\n int size = 0;\n int kilogram = 0;\n\n\n public void setSize(int size){\n this.size = size;\n }\n\n public void setKilogram(int kilogram){\n this.kilogram = kilogram;\n }\n}\n\nDepending on your use case, you might want to make the Characteristics class an interface and implement it.\n"
] |
[
2,
1
] |
[] |
[] |
[
"class",
"constructor",
"java",
"object"
] |
stackoverflow_0074669711_class_constructor_java_object.txt
|
Q:
Will using Template Typdefs force us to duplicate iterator objects in C++23 even though "Deducing this" eliminates this problem?
One of the problems Deducing this solves is duplication by making member functions cvref aware of the cvref-ness of the object the function is being called on. By declaring Alias templates (Template Typdefs) and returning them in the member functions rather than just returning auto are we not forced to have two iterator objects?
template <typename T>
struct const_list_iterator{
typedef const T& reference;
typedef const T* pointer;
reference operator*() const{/***/}
pointer operator ->() const{/***/}
};
and
template <typename T >
struct list_iterator{
typedef T& reference;
typedef T* pointer;
reference operator*(){/***/}
pointer operator ->(){/***/}
};
However, with Deducing this if the return type is auto can we simply have a single iterator object?
template <typename T>
struct list_iterator
template <typename itself>
auto operator*(this itself&& self){/***/}
template <typename itself>
auto operator->(this itself&& self){/***/}
};
Which we can use as below:
template <typename T>
struct list{
using iterator = list_iterator<T>;
auto begin() -> iterator {
iterator(node -> next);
}
auto begin() const -> iterator{
iterator(node -> next)
}
};
So, will using typedefs force us to duplicate iterator objects?
A:
Your example code does not propagate const correctly from the container to the iterator. begin() const will return the same type as begin(). So any deduction on the operator* of the iterator is irrelevant; the fact that const was involved has already been lost.
In order to propagate the const from the container's begin to the iterator, begin must return a different type when the container is called via const. It could be a different specialization of the same iterator template (list_iterator<const T>, for example), but it needs to be a different type.
You can give begin an explicit object parameter and deduce the const-ness from it. But it'd just be doing this:
template <typename Self>
auto begin(this Self&& self)
{
if constexpr(std::is_const_v<Self>)
return list_iterator<const T>(...);
else
return list_iterator<T>(...);
}
But personally, that's not more readable to me compared to just using traditional syntax.
list_iterator<const T> begin() const
{
return list_iterator<const T>(...);
}
list_iterator<T> begin()
{
return list_iterator<T>(...);
}
|
Will using Template Typdefs force us to duplicate iterator objects in C++23 even though "Deducing this" eliminates this problem?
|
One of the problems Deducing this solves is duplication by making member functions cvref aware of the cvref-ness of the object the function is being called on. By declaring Alias templates (Template Typdefs) and returning them in the member functions rather than just returning auto are we not forced to have two iterator objects?
template <typename T>
struct const_list_iterator{
typedef const T& reference;
typedef const T* pointer;
reference operator*() const{/***/}
pointer operator ->() const{/***/}
};
and
template <typename T >
struct list_iterator{
typedef T& reference;
typedef T* pointer;
reference operator*(){/***/}
pointer operator ->(){/***/}
};
However, with Deducing this if the return type is auto can we simply have a single iterator object?
template <typename T>
struct list_iterator
template <typename itself>
auto operator*(this itself&& self){/***/}
template <typename itself>
auto operator->(this itself&& self){/***/}
};
Which we can use as below:
template <typename T>
struct list{
using iterator = list_iterator<T>;
auto begin() -> iterator {
iterator(node -> next);
}
auto begin() const -> iterator{
iterator(node -> next)
}
};
So, will using typedefs force us to duplicate iterator objects?
|
[
"Your example code does not propagate const correctly from the container to the iterator. begin() const will return the same type as begin(). So any deduction on the operator* of the iterator is irrelevant; the fact that const was involved has already been lost.\nIn order to propagate the const from the container's begin to the iterator, begin must return a different type when the container is called via const. It could be a different specialization of the same iterator template (list_iterator<const T>, for example), but it needs to be a different type.\nYou can give begin an explicit object parameter and deduce the const-ness from it. But it'd just be doing this:\ntemplate <typename Self>\nauto begin(this Self&& self)\n{\n if constexpr(std::is_const_v<Self>)\n return list_iterator<const T>(...);\n else\n return list_iterator<T>(...);\n}\n\nBut personally, that's not more readable to me compared to just using traditional syntax.\nlist_iterator<const T> begin() const\n{\n return list_iterator<const T>(...);\n}\n\nlist_iterator<T> begin()\n{\n return list_iterator<T>(...);\n}\n\n"
] |
[
0
] |
[] |
[] |
[
"c++",
"c++23",
"const_iterator",
"iterator"
] |
stackoverflow_0074665600_c++_c++23_const_iterator_iterator.txt
|
Q:
Is specializing std::hash for a constrained std::tuple considered undefined behaviour?
I know that specializing std::hash for a general std::tuple is undefined behaviour.
However, what about specializing std::hash for a specific tuple?
For example,
namespace std {
template<>
struct hash<std::tuple<MyType, float>> {
size_t operator()(const std::tuple<MyType, float>& t) const {
// ...
}
};
}
Or even std::tuple<Ts ...> with some kind of required is_all_same_as_v<Ts…, MyType> C++20 constraint.
E.g., this
namespace std {
template<typename... Ts>
requires is_all_same_as_v<Ts..., MyType>
struct hash<std::tuple<Ts...>> {
size_t operator()(const std::tuple<Ts...>& t) const {
// ...
}
};
}
Is that still considered undefined behaviour? If so, why?
A:
Specializing std::hash for a std::tuple is not considered undefined behavior in C++.
std::hash is a template class in the C++ standard library, which means that it can be specialized for different types to define a custom hash function for those types. This is perfectly valid.
However, it is important to note that, in order for a specialization of std::hash to be well-defined, it must satisfy the requirements for a hash function. These requirements include that the function must be deterministic, ie. must produce the same result for the same input every time it is called (restriction only limited to a single runtime instance; this allows salted hashes preventing collision DoS attacks), and must not throw exceptions.
Additionally, the function must produce different results for different inputs, unless those inputs are equal (according to the operator == function).
The code example you mentioned is a specialization of the std::hash template class for std::tuples that contain a MyType and a float, and it defines a custom hash function for those tuples. This should also work fine in case of custom tuples.
|
Is specializing std::hash for a constrained std::tuple considered undefined behaviour?
|
I know that specializing std::hash for a general std::tuple is undefined behaviour.
However, what about specializing std::hash for a specific tuple?
For example,
namespace std {
template<>
struct hash<std::tuple<MyType, float>> {
size_t operator()(const std::tuple<MyType, float>& t) const {
// ...
}
};
}
Or even std::tuple<Ts ...> with some kind of required is_all_same_as_v<Ts…, MyType> C++20 constraint.
E.g., this
namespace std {
template<typename... Ts>
requires is_all_same_as_v<Ts..., MyType>
struct hash<std::tuple<Ts...>> {
size_t operator()(const std::tuple<Ts...>& t) const {
// ...
}
};
}
Is that still considered undefined behaviour? If so, why?
|
[
"Specializing std::hash for a std::tuple is not considered undefined behavior in C++.\nstd::hash is a template class in the C++ standard library, which means that it can be specialized for different types to define a custom hash function for those types. This is perfectly valid.\nHowever, it is important to note that, in order for a specialization of std::hash to be well-defined, it must satisfy the requirements for a hash function. These requirements include that the function must be deterministic, ie. must produce the same result for the same input every time it is called (restriction only limited to a single runtime instance; this allows salted hashes preventing collision DoS attacks), and must not throw exceptions.\nAdditionally, the function must produce different results for different inputs, unless those inputs are equal (according to the operator == function).\nThe code example you mentioned is a specialization of the std::hash template class for std::tuples that contain a MyType and a float, and it defines a custom hash function for those tuples. This should also work fine in case of custom tuples.\n"
] |
[
2
] |
[] |
[] |
[
"c++",
"c++20"
] |
stackoverflow_0074669755_c++_c++20.txt
|
Q:
Cannot fine 'logger' in scope despite importing all the packages
So I'll keep this short. I imported all the packages just fine and the app was working just fine until I started with the Firebase Auth stuff. I'm getting the following error: "Cannot find 'logger' in scope". I have all the packages imported as shown in the image. Would appreciate any recommendation. Thanks!
A:
import OSLog
That's it. You just needed to know the right framework.
Then you need to create an instance.
let logger = Logger()
A:
I had to do import OSLog at the top of the file and then write the actual log statement like this: Logger.info(tag: "myTag", message: "myMessage")
|
Cannot fine 'logger' in scope despite importing all the packages
|
So I'll keep this short. I imported all the packages just fine and the app was working just fine until I started with the Firebase Auth stuff. I'm getting the following error: "Cannot find 'logger' in scope". I have all the packages imported as shown in the image. Would appreciate any recommendation. Thanks!
|
[
"import OSLog\n\nThat's it. You just needed to know the right framework.\nThen you need to create an instance.\nlet logger = Logger()\n\n",
"I had to do import OSLog at the top of the file and then write the actual log statement like this: Logger.info(tag: \"myTag\", message: \"myMessage\")\n"
] |
[
2,
0
] |
[] |
[] |
[
"firebase",
"firebase_authentication",
"swift",
"xcode"
] |
stackoverflow_0072626030_firebase_firebase_authentication_swift_xcode.txt
|
Q:
Django form with multi input from loop save only last record to database
I have a problem with saving data from a form in django. Only the last record is saved. I generate a list of dates (days of the month) in the view and display it in the form in templates along with the fields next to the type. Everything is displayed correctly in templates, but when I submit to, only the last record from the form appears in the save view. What am I doing wrong, can someone help?
forms.py
class DoctorsSchedule(forms.ModelForm):
# work_hours = models.CharField(max_length=50, blank=True, null=True, default='8:00-21:00')
# official_hours = models.CharField(max_length=50, blank=True, null=True, default='8:00-19:00')
class Meta:
model = DoctorSchedule
fields = ['date', 'day_type', 'work_hours', 'scheme', 'official_hours']
model.py
class DoctorSchedule(models.Model):
id = models.AutoField(primary_key=True, unique=True)
date = models.DateField(blank=True, null=True)
day_type = models.CharField(max_length=255, blank=True, null=True, default='Pracujący')
work_hours = models.CharField(max_length=50, blank=True, null=True, default='8:00-21:00')
scheme = models.CharField(max_length=255, blank=True, null=True, default='20')
official_hours = models.CharField(max_length=50, blank=True, null=True, default='8:00-19:00')
def __str__(self):
return self.date
view.py
def terminarz(request):
today = datetime.now()
now = date.today()
locale.setlocale(locale.LC_TIME, 'pl_PL')
def months():
months = {'1': 'Styczeń', '2': 'Luty', '3': 'Marzec', '4': 'Kwiecień', '5': 'Maj', '6': 'Czerwiec',
'7': 'Lipiec',
'8': 'Sierpień', '9': 'Wrzesień', '10': 'Październik', '11': 'Listopad', '12': 'Grudzień'}
return months
##################### days of month list ######################################
def days_of_month_list():
if request.GET.get('year') and request.GET.get('month'):
y = int(request.GET.get('year'))
m = int(request.GET.get('month'))
btn_y = int(request.GET.get('year'))
else:
y = today.year
m = today.month
btn_y = today.year
date_list = {}
for d in range(1, monthrange(y, m)[1] + 1):
x = '{:04d}-{:02d}-{:02d}'.format(y, m, d)
dayName = datetime.strptime(x, '%Y-%m-%d').weekday()
date_list[x] = calendar.day_name[dayName].capitalize()
################### end days of month list #################################
return date_list
months = months()
date_list = days_of_month_list()
btn_today = today.year
btn_today_1 = today.year + 1
btn_today_2 = today.year + 2
if request.GET.get('year') and request.GET.get('month'):
btn_y = int(request.GET.get('year'))
else:
btn_y = today.year
if request.method == 'POST':
form = DoctorsSchedule(request.POST)
if form.is_valid():
form.save()
else:
print(form.is_valid()) # form contains data and errors
print(form.errors)
form = DoctorsSchedule()
else:
form = DoctorsSchedule
context = {
'form': form,
'today': today,
'now': now,
'months': months,
'date_list': date_list,
'btn_today': btn_today,
'btn_today_1': btn_today_1,
'btn_today_2': btn_today_2
}
return render(request, "vita/panel/terminarz.html", context)
templates.html
<div class="card-body">
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<div class="row p-3 text-center">
{% include 'vita/messages.html' %}
<div class="text-center p-2">
<a role="button" class="btn btn-info" href='terminarz?month={{today.month}}&year={{btn_today}}'>{{ btn_today }}</a>
<a role="button" class="btn btn-info" href='terminarz?month={{today.month}}&year={{ btn_today_1 }}'>{{ btn_today_1 }}</a>
<a role="button" class="btn btn-info" href='terminarz?month={{today.month}}&year={{ btn_today_2 }}'>{{ btn_today_2 }}</a>
</div>
{% for nr, month in months.items %}
<div class="col text-center">
{% if btn_y == btn_today_1 %}
<a role="button" class="btn btn-primary p-2" href="terminarz?month={{nr}}&year={{btn_today_1}}">{{month|upper}}</a>
{% elif btn_y == btn_today_2 %}
<a role="button" class="btn btn-primary p-2" href="terminarz?month={{nr}}&year={{btn_today_2}}">{{month|upper}}</a>
{% else %}
<a role="button" class="btn btn-primary p-2" href="terminarz?month={{nr}}&year={{btn_today}}">{{month|upper}}</a>
{% endif %}
</div>
{% endfor %}
</div>
<table class="table table-striped table-sm table-responsive">
<thead class="text-light" style="background: #26396F;">
<tr>
<th>Data</th>
<th class="text-center">Dzień pracy</th>
<th class="text-center">Godziny oficjalne</th>
<th class="text-center">Godziny pracy</th>
<th class="text-center">Przedział</th>
<th class="text-center">Ilość wizyt</th>
</tr>
</thead>
<tbody>
{% for date, day in date_list.items %}
<tr>
<td class="p-1">
<a href="/panel/{{ date }}">
<b>{{ date }}</b> -
{% if day == 'Sobota' or day == 'Niedziela' %}
<span class="text-danger">{{ day }}</span>
{% else %}
<span class="text-success">{{ day }}</span>
{% endif %}
</a>
<input type="hidden" name="data" value="{{date}}" />
</td>
<td class="p-1">
<select name="day_type">
{% if day == 'Sobota' or day == 'Niedziela' %}
<option value="Wolny" selected>Wolny</option>
<option value="Pracujący">Pracujący</option>
{% else %}
<option value="Pracujący" selected>Pracujący</option>
<option value="Wolny" >Wolny</option>
{% endif %}
</select>
</td>
{% if day == 'Sobota' or day == 'Niedziela' %}
<td></td>
<td></td>
<td></td>
<td></td>
{% else %}
<td class="p-1 text-center"><input name="official_hours_start" type="time" value="08:00" />-<input name="official_hours_end" type="time" value="19:00" /></td>
<td class="p-1 text-center"><input name="work_hours_start" type="time" value="08:00" />-<input name="work_hours_end" type="time" value="21:00" /></td>
<td class="p-1 text-center">
<select name="scheme">
<option value="10">10 min</option>
<option value="15">15 min</option>
<option value="20">20 min</option>
<option value="25">25 min</option>
<option value="30" selected>30 min</option>
</select>
</td>
<td class="p-1 text-center">0</td>
{% endif %}
</tr>
{% endfor %}
</tbody>
</table>
<div class="text-center"><input class="btn btn-success" type="submit" name="update_schedule" value="Uaktualnij terminarz" /></div>
</form>
</div>
A:
You need to pass the form to the template. Now this is OK in your code. But I thing the problem come with the way you manage your form lifecycle.
If I understand your code the workflow is the following:
A GET REQUEST Initialize to form with the current states
You use several GET requests (buttons) to update states/values
Then A POST request to save the form
And you end up with some bad values ?
It's quite Normal ...
let me explain if I'm correct :
First GET You initialize the page data and the form with the an initial state (but maybe not I don't see it)
In other intermediate steps, you use GET request where you modify the page data with the current state but not the form
Finally you save the form with ??? ...
How to fix it:
At each intermediate step update the form data but don't save it. Therefore at the last step, The POST request will normally save correct data
change this:
...
else:
form = DoctorsSchedule()
...
# into
...
else:
form = DoctorsSchedule({
'date': <place here the current correct value for this field>,
'day_type': <place here the current correct value for this field>,
etc...
})
and please replace
form = DoctorsSchedule # this is a Form class not an instance
# with
form = DoctorsSchedule()
# or better
form = DoctorsSchedule(initial_data={<your data>})
# or also better
form = DoctorsSchedule(<some DoctorsSchedule (the Model one) instance>)
you should use a form instance not a form class in your template
and you should rename one of DoctorsSchedule Model or DoctorsSchedule Form in order to avoid confusion
You can also Write some javascript code in order to propagate page changes into the form input fields data directly in the page
A:
Update:
I print(request.POST) and this is the result. When I use form.is_valid it's not show errors and form.save() save only last record from QueryDict
<QueryDict: {'csrfmiddlewaretoken': ['mzIuVQEY1a6s15UEInWD5xZOm6HapMyOAikLItkMTvIGOizxIU9NErfh4SUkfiR9'], 'data': ['2022-12-01', '2022-12-02', '2022-12-03', '2022-12-04', '2022-12-05', '2022-12-06', '2022-12-07', '2022-12-08', '2022
-12-09', '2022-12-10', '2022-12-11', '2022-12-12', '2022-12-13', '2022-12-14', '2022-12-15', '2022-12-16', '2022-12-17', '2022-12-18', '2022-12-19', '2022-12-20', '2022-12-21', '2022-12-22', '2022-12-23', '2022-12-24', '2022-12-25',
'2022-12-26', '2022-12-27', '2022-12-28', '2022-12-29', '2022-12-30', '2022-12-31'], 'day_type': ['Pracujący', 'Pracujący', 'Wolny', 'Wolny', 'Pracujący', 'Pracujący', 'Pracujący', 'Pracujący', 'Pracujący', 'Wolny', 'Wolny', 'Pracu
jący', 'Pracujący', 'Pracujący', 'Pracujący', 'Pracujący', 'Wolny', 'Wolny', 'Pracujący', 'Pracujący', 'Pracujący', 'Pracujący', 'Pracujący', 'Wolny', 'Wolny', 'Pracujący', 'Pracujący', 'Pracujący', 'Pracujący', 'Pracujący', 'Wolny'
], 'official_hours_start': ['08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19
:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00'], 'work_hours_start': ['08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21
:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00'], 'scheme': ['30', '30', '30', '30', '30', '30', '30', '30', '30', '30', '30', '30', '30', '30', '30', '30', '30', '30', '30', '30', '30', '30'], 'update_schedule': ['Uaktualnij terminarz']}>
A:
This is resolve my problem
if request.method == "POST":
if form.is_valid():
x1 = request.POST #get data from request and getlist from QueryDict
data_l = x1.getlist('data')
day_type_l = x1.getlist('day_type')
work_hours_l = x1.getlist('work_hours_start')
scheme_l = x1.getlist('scheme')
official_hours_l = x1.getlist('official_hours_start')
for date, day_type, work_hours, official_hours, scheme in zip(data_l,day_type_l,work_hours_l,official_hours_l,scheme_l):
post_dict = {'date': date, 'day_type': day_type, 'work_hours': work_hours, 'official_hours': official_hours, 'scheme': scheme}
form = DoctorsScheduleForm(post_dict)
form.save()
else:
form = DoctorsScheduleForm()
|
Django form with multi input from loop save only last record to database
|
I have a problem with saving data from a form in django. Only the last record is saved. I generate a list of dates (days of the month) in the view and display it in the form in templates along with the fields next to the type. Everything is displayed correctly in templates, but when I submit to, only the last record from the form appears in the save view. What am I doing wrong, can someone help?
forms.py
class DoctorsSchedule(forms.ModelForm):
# work_hours = models.CharField(max_length=50, blank=True, null=True, default='8:00-21:00')
# official_hours = models.CharField(max_length=50, blank=True, null=True, default='8:00-19:00')
class Meta:
model = DoctorSchedule
fields = ['date', 'day_type', 'work_hours', 'scheme', 'official_hours']
model.py
class DoctorSchedule(models.Model):
id = models.AutoField(primary_key=True, unique=True)
date = models.DateField(blank=True, null=True)
day_type = models.CharField(max_length=255, blank=True, null=True, default='Pracujący')
work_hours = models.CharField(max_length=50, blank=True, null=True, default='8:00-21:00')
scheme = models.CharField(max_length=255, blank=True, null=True, default='20')
official_hours = models.CharField(max_length=50, blank=True, null=True, default='8:00-19:00')
def __str__(self):
return self.date
view.py
def terminarz(request):
today = datetime.now()
now = date.today()
locale.setlocale(locale.LC_TIME, 'pl_PL')
def months():
months = {'1': 'Styczeń', '2': 'Luty', '3': 'Marzec', '4': 'Kwiecień', '5': 'Maj', '6': 'Czerwiec',
'7': 'Lipiec',
'8': 'Sierpień', '9': 'Wrzesień', '10': 'Październik', '11': 'Listopad', '12': 'Grudzień'}
return months
##################### days of month list ######################################
def days_of_month_list():
if request.GET.get('year') and request.GET.get('month'):
y = int(request.GET.get('year'))
m = int(request.GET.get('month'))
btn_y = int(request.GET.get('year'))
else:
y = today.year
m = today.month
btn_y = today.year
date_list = {}
for d in range(1, monthrange(y, m)[1] + 1):
x = '{:04d}-{:02d}-{:02d}'.format(y, m, d)
dayName = datetime.strptime(x, '%Y-%m-%d').weekday()
date_list[x] = calendar.day_name[dayName].capitalize()
################### end days of month list #################################
return date_list
months = months()
date_list = days_of_month_list()
btn_today = today.year
btn_today_1 = today.year + 1
btn_today_2 = today.year + 2
if request.GET.get('year') and request.GET.get('month'):
btn_y = int(request.GET.get('year'))
else:
btn_y = today.year
if request.method == 'POST':
form = DoctorsSchedule(request.POST)
if form.is_valid():
form.save()
else:
print(form.is_valid()) # form contains data and errors
print(form.errors)
form = DoctorsSchedule()
else:
form = DoctorsSchedule
context = {
'form': form,
'today': today,
'now': now,
'months': months,
'date_list': date_list,
'btn_today': btn_today,
'btn_today_1': btn_today_1,
'btn_today_2': btn_today_2
}
return render(request, "vita/panel/terminarz.html", context)
templates.html
<div class="card-body">
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<div class="row p-3 text-center">
{% include 'vita/messages.html' %}
<div class="text-center p-2">
<a role="button" class="btn btn-info" href='terminarz?month={{today.month}}&year={{btn_today}}'>{{ btn_today }}</a>
<a role="button" class="btn btn-info" href='terminarz?month={{today.month}}&year={{ btn_today_1 }}'>{{ btn_today_1 }}</a>
<a role="button" class="btn btn-info" href='terminarz?month={{today.month}}&year={{ btn_today_2 }}'>{{ btn_today_2 }}</a>
</div>
{% for nr, month in months.items %}
<div class="col text-center">
{% if btn_y == btn_today_1 %}
<a role="button" class="btn btn-primary p-2" href="terminarz?month={{nr}}&year={{btn_today_1}}">{{month|upper}}</a>
{% elif btn_y == btn_today_2 %}
<a role="button" class="btn btn-primary p-2" href="terminarz?month={{nr}}&year={{btn_today_2}}">{{month|upper}}</a>
{% else %}
<a role="button" class="btn btn-primary p-2" href="terminarz?month={{nr}}&year={{btn_today}}">{{month|upper}}</a>
{% endif %}
</div>
{% endfor %}
</div>
<table class="table table-striped table-sm table-responsive">
<thead class="text-light" style="background: #26396F;">
<tr>
<th>Data</th>
<th class="text-center">Dzień pracy</th>
<th class="text-center">Godziny oficjalne</th>
<th class="text-center">Godziny pracy</th>
<th class="text-center">Przedział</th>
<th class="text-center">Ilość wizyt</th>
</tr>
</thead>
<tbody>
{% for date, day in date_list.items %}
<tr>
<td class="p-1">
<a href="/panel/{{ date }}">
<b>{{ date }}</b> -
{% if day == 'Sobota' or day == 'Niedziela' %}
<span class="text-danger">{{ day }}</span>
{% else %}
<span class="text-success">{{ day }}</span>
{% endif %}
</a>
<input type="hidden" name="data" value="{{date}}" />
</td>
<td class="p-1">
<select name="day_type">
{% if day == 'Sobota' or day == 'Niedziela' %}
<option value="Wolny" selected>Wolny</option>
<option value="Pracujący">Pracujący</option>
{% else %}
<option value="Pracujący" selected>Pracujący</option>
<option value="Wolny" >Wolny</option>
{% endif %}
</select>
</td>
{% if day == 'Sobota' or day == 'Niedziela' %}
<td></td>
<td></td>
<td></td>
<td></td>
{% else %}
<td class="p-1 text-center"><input name="official_hours_start" type="time" value="08:00" />-<input name="official_hours_end" type="time" value="19:00" /></td>
<td class="p-1 text-center"><input name="work_hours_start" type="time" value="08:00" />-<input name="work_hours_end" type="time" value="21:00" /></td>
<td class="p-1 text-center">
<select name="scheme">
<option value="10">10 min</option>
<option value="15">15 min</option>
<option value="20">20 min</option>
<option value="25">25 min</option>
<option value="30" selected>30 min</option>
</select>
</td>
<td class="p-1 text-center">0</td>
{% endif %}
</tr>
{% endfor %}
</tbody>
</table>
<div class="text-center"><input class="btn btn-success" type="submit" name="update_schedule" value="Uaktualnij terminarz" /></div>
</form>
</div>
|
[
"You need to pass the form to the template. Now this is OK in your code. But I thing the problem come with the way you manage your form lifecycle.\nIf I understand your code the workflow is the following:\n\nA GET REQUEST Initialize to form with the current states\nYou use several GET requests (buttons) to update states/values\nThen A POST request to save the form\n\nAnd you end up with some bad values ?\nIt's quite Normal ...\nlet me explain if I'm correct :\n\nFirst GET You initialize the page data and the form with the an initial state (but maybe not I don't see it)\nIn other intermediate steps, you use GET request where you modify the page data with the current state but not the form\nFinally you save the form with ??? ...\n\nHow to fix it:\n\nAt each intermediate step update the form data but don't save it. Therefore at the last step, The POST request will normally save correct data\n\nchange this:\n...\nelse:\n form = DoctorsSchedule()\n...\n# into\n\n...\nelse:\n form = DoctorsSchedule({\n 'date': <place here the current correct value for this field>, \n 'day_type': <place here the current correct value for this field>, \n etc...\n })\n\n\nand please replace\n form = DoctorsSchedule # this is a Form class not an instance\n# with \n form = DoctorsSchedule()\n# or better\n form = DoctorsSchedule(initial_data={<your data>})\n# or also better\n form = DoctorsSchedule(<some DoctorsSchedule (the Model one) instance>)\n\nyou should use a form instance not a form class in your template\nand you should rename one of DoctorsSchedule Model or DoctorsSchedule Form in order to avoid confusion\n\nYou can also Write some javascript code in order to propagate page changes into the form input fields data directly in the page\n\n",
"Update:\nI print(request.POST) and this is the result. When I use form.is_valid it's not show errors and form.save() save only last record from QueryDict\n<QueryDict: {'csrfmiddlewaretoken': ['mzIuVQEY1a6s15UEInWD5xZOm6HapMyOAikLItkMTvIGOizxIU9NErfh4SUkfiR9'], 'data': ['2022-12-01', '2022-12-02', '2022-12-03', '2022-12-04', '2022-12-05', '2022-12-06', '2022-12-07', '2022-12-08', '2022\n-12-09', '2022-12-10', '2022-12-11', '2022-12-12', '2022-12-13', '2022-12-14', '2022-12-15', '2022-12-16', '2022-12-17', '2022-12-18', '2022-12-19', '2022-12-20', '2022-12-21', '2022-12-22', '2022-12-23', '2022-12-24', '2022-12-25',\n '2022-12-26', '2022-12-27', '2022-12-28', '2022-12-29', '2022-12-30', '2022-12-31'], 'day_type': ['Pracujący', 'Pracujący', 'Wolny', 'Wolny', 'Pracujący', 'Pracujący', 'Pracujący', 'Pracujący', 'Pracujący', 'Wolny', 'Wolny', 'Pracu\njący', 'Pracujący', 'Pracujący', 'Pracujący', 'Pracujący', 'Wolny', 'Wolny', 'Pracujący', 'Pracujący', 'Pracujący', 'Pracujący', 'Pracujący', 'Wolny', 'Wolny', 'Pracujący', 'Pracujący', 'Pracujący', 'Pracujący', 'Pracujący', 'Wolny'\n], 'official_hours_start': ['08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19\n:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00', '08:00-19:00'], 'work_hours_start': ['08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21\n:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00', '08:00-21:00'], 'scheme': ['30', '30', '30', '30', '30', '30', '30', '30', '30', '30', '30', '30', '30', '30', '30', '30', '30', '30', '30', '30', '30', '30'], 'update_schedule': ['Uaktualnij terminarz']}>\n\n",
"This is resolve my problem\n\n if request.method == \"POST\":\n if form.is_valid():\n x1 = request.POST #get data from request and getlist from QueryDict\n data_l = x1.getlist('data')\n day_type_l = x1.getlist('day_type')\n work_hours_l = x1.getlist('work_hours_start')\n scheme_l = x1.getlist('scheme')\n official_hours_l = x1.getlist('official_hours_start')\n\n for date, day_type, work_hours, official_hours, scheme in zip(data_l,day_type_l,work_hours_l,official_hours_l,scheme_l):\n\n post_dict = {'date': date, 'day_type': day_type, 'work_hours': work_hours, 'official_hours': official_hours, 'scheme': scheme}\n \n form = DoctorsScheduleForm(post_dict)\n form.save()\n\n else:\n form = DoctorsScheduleForm()\n\n"
] |
[
1,
0,
0
] |
[] |
[] |
[
"django",
"forms",
"html",
"python"
] |
stackoverflow_0074615371_django_forms_html_python.txt
|
Q:
CsvHelper Exception Speed
I'm using CsvHelper to import a csv like so. Its being done line by line to deal with type conversion errors. I can then import the ones that worked and report the ones that fail. Its exceedingly fast when there are no errors, 1 second for 3000k lines. But if there are lots of errors, and lets say all the 3000k had type conversion issue, the time to complete is 60 seconds. Any advice on speeding up error handling?
csv.Read();
csv.ReadHeader();
while (await csv.ReadAsync())
{
try
{
var record = csv.GetRecord<CollectionQueue>();
}
catch (TypeConverterException conversionEx)
{
var errorMessage = $"Error converting value '{conversionEx.Text}' to type '{conversionEx.MemberMapData.Type.Name}' for field '{conversionEx.MemberMapData.Names[0]}'";
}
}
A:
Using some of the ideas from @dbc, I have a couple of suggestions.
I noticed about a 30% increase in speed if I used Configuration.ReadingExceptionOccurred to catch the exception.
async void Main()
{
List<Foo> records = new List<Foo>();
for (int i = 0; i < 300000; i++)
{
var amount = (i + 1).ToString();
if (i % 5 == 0)
{
amount = $"${i + 1}";
}
records.Add(new Foo {Id = i + 1, Amount = amount});
}
using (var writer = new StreamWriter(@"C:\Temp\TypeConverterException.csv"))
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
csv.WriteRecords(records);
}
var errors = new List<string>();
var config = new CsvConfiguration(CultureInfo.InvariantCulture)
{
ReadingExceptionOccurred = args =>
{
if (args.Exception.GetType() == typeof(TypeConverterException))
{
var conversionEx = (TypeConverterException)args.Exception;
errors.Add(
$"Error on line {conversionEx.Context.Parser.RawRow} converting value '{conversionEx.Text}' to type '{conversionEx.MemberMapData.Type.Name}' for field '{conversionEx.MemberMapData.Names[0]}'"
);
return false;
}
else
{
return true;
}
}
};
using (var reader = new StreamReader(@"C:\Temp\TypeConverterException.csv"))
using (var csv = new CsvReader(reader, config))
{
var start = DateTime.Now;
csv.Read();
csv.ReadHeader();
var barRecords = new List<Bar>();
while (await csv.ReadAsync())
{
var record = csv.GetRecord<Bar>();
if (record != null)
barRecords.Add(record);
}
var end = DateTime.Now;
var difference = end - start;
difference.TotalSeconds.Dump();
}
}
public class Foo
{
public int Id { get; set; }
public string Amount { get; set; }
}
public class Bar
{
public int Id { get; set; }
public decimal Amount { get; set; }
}
However, it was considerably faster if I could use another class to import the records that had string for the properties that could have conversion errors and then manually did a TryParse() before converting to the final class that I wanted.
async void Main()
{
List<Foo> records = new List<Foo>();
for (int i = 0; i < 300000; i++)
{
var amount = (i + 1).ToString();
if (i % 5 == 0)
{
amount = $"${i + 1}";
}
records.Add(new Foo {Id = i + 1, Amount = amount});
}
using (var writer = new StreamWriter(@"C:\Temp\TypeConverterException.csv"))
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
csv.WriteRecords(records);
}
var errors = new List<string>();
using (var reader = new StreamReader(@"C:\Temp\TypeConverterException.csv"))
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
var start = DateTime.Now;
var fooRecords = csv.GetRecordsAsync<Foo>();
var barRecords = new List<Bar>();
await foreach (var record in fooRecords)
{
var canParce = decimal.TryParse(record.Amount, out decimal barAmount);
if (canParce)
{
barRecords.Add(new Bar { Id = record.Id, Amount = barAmount});
}
else
{
errors.Add($"Error converting value '{record.Amount}' to decimal for field Amount");
}
}
var end = DateTime.Now;
var difference = end - start;
difference.TotalSeconds.Dump();
}
}
public class Foo
{
public int Id { get; set; }
public string Amount { get; set; }
}
public class Bar
{
public int Id { get; set; }
public decimal Amount { get; set; }
}
|
CsvHelper Exception Speed
|
I'm using CsvHelper to import a csv like so. Its being done line by line to deal with type conversion errors. I can then import the ones that worked and report the ones that fail. Its exceedingly fast when there are no errors, 1 second for 3000k lines. But if there are lots of errors, and lets say all the 3000k had type conversion issue, the time to complete is 60 seconds. Any advice on speeding up error handling?
csv.Read();
csv.ReadHeader();
while (await csv.ReadAsync())
{
try
{
var record = csv.GetRecord<CollectionQueue>();
}
catch (TypeConverterException conversionEx)
{
var errorMessage = $"Error converting value '{conversionEx.Text}' to type '{conversionEx.MemberMapData.Type.Name}' for field '{conversionEx.MemberMapData.Names[0]}'";
}
}
|
[
"Using some of the ideas from @dbc, I have a couple of suggestions.\nI noticed about a 30% increase in speed if I used Configuration.ReadingExceptionOccurred to catch the exception.\nasync void Main()\n{\n List<Foo> records = new List<Foo>();\n \n for (int i = 0; i < 300000; i++)\n {\n var amount = (i + 1).ToString();\n \n if (i % 5 == 0)\n {\n amount = $\"${i + 1}\";\n }\n \n records.Add(new Foo {Id = i + 1, Amount = amount});\n }\n \n using (var writer = new StreamWriter(@\"C:\\Temp\\TypeConverterException.csv\"))\n using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))\n {\n csv.WriteRecords(records);\n }\n \n var errors = new List<string>();\n \n var config = new CsvConfiguration(CultureInfo.InvariantCulture)\n {\n ReadingExceptionOccurred = args =>\n {\n if (args.Exception.GetType() == typeof(TypeConverterException))\n {\n var conversionEx = (TypeConverterException)args.Exception;\n\n errors.Add(\n $\"Error on line {conversionEx.Context.Parser.RawRow} converting value '{conversionEx.Text}' to type '{conversionEx.MemberMapData.Type.Name}' for field '{conversionEx.MemberMapData.Names[0]}'\"\n );\n \n return false;\n } \n else\n {\n return true;\n }\n }\n };\n \n using (var reader = new StreamReader(@\"C:\\Temp\\TypeConverterException.csv\"))\n using (var csv = new CsvReader(reader, config))\n {\n var start = DateTime.Now;\n csv.Read();\n csv.ReadHeader();\n \n var barRecords = new List<Bar>();\n \n while (await csv.ReadAsync())\n { \n var record = csv.GetRecord<Bar>();\n \n if (record != null)\n barRecords.Add(record); \n }\n \n var end = DateTime.Now;\n \n var difference = end - start;\n \n difference.TotalSeconds.Dump();\n }\n}\n\npublic class Foo\n{\n public int Id { get; set; }\n public string Amount { get; set; }\n}\n\npublic class Bar\n{\n public int Id { get; set; }\n public decimal Amount { get; set; }\n}\n\nHowever, it was considerably faster if I could use another class to import the records that had string for the properties that could have conversion errors and then manually did a TryParse() before converting to the final class that I wanted.\nasync void Main()\n{\n List<Foo> records = new List<Foo>();\n \n for (int i = 0; i < 300000; i++)\n {\n var amount = (i + 1).ToString();\n \n if (i % 5 == 0)\n {\n amount = $\"${i + 1}\";\n }\n \n records.Add(new Foo {Id = i + 1, Amount = amount});\n }\n \n using (var writer = new StreamWriter(@\"C:\\Temp\\TypeConverterException.csv\"))\n using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))\n {\n csv.WriteRecords(records);\n }\n \n var errors = new List<string>();\n \n using (var reader = new StreamReader(@\"C:\\Temp\\TypeConverterException.csv\"))\n using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))\n {\n var start = DateTime.Now;\n \n var fooRecords = csv.GetRecordsAsync<Foo>();\n var barRecords = new List<Bar>();\n \n await foreach (var record in fooRecords)\n {\n var canParce = decimal.TryParse(record.Amount, out decimal barAmount);\n \n if (canParce)\n {\n barRecords.Add(new Bar { Id = record.Id, Amount = barAmount});\n } \n else\n {\n errors.Add($\"Error converting value '{record.Amount}' to decimal for field Amount\");\n }\n }\n\n var end = DateTime.Now;\n\n var difference = end - start;\n\n difference.TotalSeconds.Dump();\n }\n}\n\npublic class Foo\n{\n public int Id { get; set; }\n public string Amount { get; set; }\n}\n\npublic class Bar\n{\n public int Id { get; set; }\n public decimal Amount { get; set; }\n}\n\n"
] |
[
2
] |
[] |
[] |
[
"csvhelper"
] |
stackoverflow_0074667755_csvhelper.txt
|
Q:
how to change the colour of bottom navigation bar in Android Studio?
In themes.xml when I add
<item name="android:windowBackground">@color/white</item>
the icon in red circle will also change to white in colour,how can I change the colour back to grey ?
Here is my code in themes.xml
<resources xmlns:tools="http://schemas.android.com/tools">
<!-- Base application theme. -->
<style name="Theme.CardHolderapp" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
<!-- Primary brand color. -->
<item name="colorPrimary">@color/blue_200</item>
<item name="colorPrimaryVariant">@color/blue_200</item>
<item name="colorOnPrimary">@color/white</item>
<!-- Secondary brand color. -->
<item name="colorSecondary">@color/blue_200</item>
<item name="colorSecondaryVariant">@color/blue_200</item>
<item name="colorOnSecondary">@color/white</item>
<!-- Status bar color. -->
<item name="android:statusBarColor"> @android:color/transparent</item>
<!-- Customize your theme here. -->
<item name="android:windowLightStatusBar">
true
</item>
<item name="android:windowBackground">@color/white
</item>
<item name="android:nav">@color/white
</item>
</style>
</resources>
How to change the colour of bottom selection bar in android studio?
A:
You can create a new theme for bottom navigation menu in styles
<style name="Theme.App" parent="Theme.MaterialComponents.*">
...
<item name="bottomNavigationStyle">@style/Widget.App.BottomNavigationView</item>
</style>
<style name="Widget.App.BottomNavigationView" parent="Widget.MaterialComponents.BottomNavigationView.Colored">
<item name="materialThemeOverlay">@style/ThemeOverlay.App.BottomNavigationView</item>
</style>
<style name="ThemeOverlay.App.BottomNavigationView" parent="">
<item name="colorPrimary">@color/COLOR_1</item>
<item name="colorOnPrimary">@color/COLOR_2</item>
</style>
for more details refer here
|
how to change the colour of bottom navigation bar in Android Studio?
|
In themes.xml when I add
<item name="android:windowBackground">@color/white</item>
the icon in red circle will also change to white in colour,how can I change the colour back to grey ?
Here is my code in themes.xml
<resources xmlns:tools="http://schemas.android.com/tools">
<!-- Base application theme. -->
<style name="Theme.CardHolderapp" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
<!-- Primary brand color. -->
<item name="colorPrimary">@color/blue_200</item>
<item name="colorPrimaryVariant">@color/blue_200</item>
<item name="colorOnPrimary">@color/white</item>
<!-- Secondary brand color. -->
<item name="colorSecondary">@color/blue_200</item>
<item name="colorSecondaryVariant">@color/blue_200</item>
<item name="colorOnSecondary">@color/white</item>
<!-- Status bar color. -->
<item name="android:statusBarColor"> @android:color/transparent</item>
<!-- Customize your theme here. -->
<item name="android:windowLightStatusBar">
true
</item>
<item name="android:windowBackground">@color/white
</item>
<item name="android:nav">@color/white
</item>
</style>
</resources>
How to change the colour of bottom selection bar in android studio?
|
[
"You can create a new theme for bottom navigation menu in styles\n<style name=\"Theme.App\" parent=\"Theme.MaterialComponents.*\">\n ...\n <item name=\"bottomNavigationStyle\">@style/Widget.App.BottomNavigationView</item>\n</style>\n\n<style name=\"Widget.App.BottomNavigationView\" parent=\"Widget.MaterialComponents.BottomNavigationView.Colored\">\n <item name=\"materialThemeOverlay\">@style/ThemeOverlay.App.BottomNavigationView</item>\n</style>\n\n<style name=\"ThemeOverlay.App.BottomNavigationView\" parent=\"\">\n <item name=\"colorPrimary\">@color/COLOR_1</item>\n <item name=\"colorOnPrimary\">@color/COLOR_2</item>\n</style>\n\nfor more details refer here\n"
] |
[
0
] |
[] |
[] |
[
"android",
"imageview",
"java"
] |
stackoverflow_0074667683_android_imageview_java.txt
|
Q:
Clear specific ranges on 5 sheets
I have little VBA experience but was given a challenge to build a better audit/order sheet for tobacco products for the company I work for with individual store inputs. They perform these audits each week and I need a button to clear multiple cell ranges on several different sheets. I just want to be able to clear the contents of several ranges with one button but leave all Formulas alone
'Clear cells that have count data in them
Worksheets("Master List").Activate
Range.ClearContents ("B2,B130")
This is what I started with as a test and was giving me a debug error
A:
Try this:
Worksheets("Master List").Range("B2,B130").ClearContents
That will clear cells B2 and B130 - if you mean to clear the range from B2 to B130 then you need Range("B2:B130")
Note you rarely need to select/activate anything to work with it in VBA - that's an artifact of the macro recorder.
|
Clear specific ranges on 5 sheets
|
I have little VBA experience but was given a challenge to build a better audit/order sheet for tobacco products for the company I work for with individual store inputs. They perform these audits each week and I need a button to clear multiple cell ranges on several different sheets. I just want to be able to clear the contents of several ranges with one button but leave all Formulas alone
'Clear cells that have count data in them
Worksheets("Master List").Activate
Range.ClearContents ("B2,B130")
This is what I started with as a test and was giving me a debug error
|
[
"Try this:\nWorksheets(\"Master List\").Range(\"B2,B130\").ClearContents \n\nThat will clear cells B2 and B130 - if you mean to clear the range from B2 to B130 then you need Range(\"B2:B130\")\nNote you rarely need to select/activate anything to work with it in VBA - that's an artifact of the macro recorder.\n"
] |
[
0
] |
[] |
[] |
[
"excel",
"range",
"vba"
] |
stackoverflow_0074669897_excel_range_vba.txt
|
Q:
How to select buyers who increased their order quantity with each consecutive order
I have table Buyer
BuyId
QuantityOrdered
dateordered
1
10
2021-11-04
1
20
2022-01-22
2
50
2022-02-20
2
60
2022-05-02
3
10
2022-05-02
4
10
2022-05-02
I need to select all BuyId's who consecutively had higher QuantityOrder in each new record
buyid=1 had first order with quantity=10, second order with quantity=20
buyid=2 had first order with quantity=50, second order with quantity=60
So BuyId=1 and 2 would enter the results, while 3 and 4 would be filtered out because they had only one order or they did not have orders with consecutively higher quantities ordered
I tried with this, and I'm aware that this query gives me only buyid's who have more than one order, but I am missing the rule where I have to filter results out by quantity increased with each new order
select buyid, count(*) as ordered
from buyer
group by buyid
having count(*) >1
How would I write out that rule in a query, to select only BuyId's who had multiple orders, and in each new order they ordered higher quantities than in previous orders?
A:
Taking advantage of the fact that count() doesn't takes into account NULL values:
select buyid from (
select buyid, count(QuantityOrdered) as norders, count(mod) as nqttyincreasing
from (
select d.*,
case when nvl(lag(QuantityOrdered) over(partition by buyid order by dateordered),0) < QuantityOrdered then 1 end as mod
from data d
)
group by buyid
) where norders = nqttyincreasing ;
A:
With this query, it will check if all purchases as bigger in quantity as the last and will not show buyers id. that have only one purchase or sold equal or less than the last time4
CREATE TABLE buyers
([BuyId] int, [QuantityOrdered] int, [dateordered] date)
;
INSERT INTO buyers
([BuyId], [QuantityOrdered], [dateordered])
VALUES
(1, 10, '2021-11-04'),
(1, 20, '2022-01-22'),
(1, 30, '2022-02-22'),
(2, 50, '2022-02-20'),
(2, 60, '2022-05-02'),
(3, 60, '2022-05-02'),
(4, 10, '2022-05-02'),
(4, 6, '2022-06-02')
;
8 rows affected
WITH CTE as (SELECT
[BuyId], [QuantityOrdered], [dateordered],
(SELECT COUNT(*) FROM buyers b1 WHERE b1.[BuyId] = buyers.[BuyId]) _count_
,CASE WHEn [QuantityOrdered] >
LAG([QuantityOrdered]) OVER(PARTITION BY [BuyId] ORDER BY [dateordered])
THEn 1
ELSe
CASE WHEN LAG([QuantityOrdered]) OVER(PARTITION BY [BuyId] ORDER BY [dateordered]) IS NULL
THEN 1 ELSE 0 END
END _bigger_
FROM buyers)
SELECT DISTINCT [BuyId] FROM CTE
WHERE _count_ > 1 AND NOT EXISTS ( SELECT 1 FROM CTE c1
WHERE c1.[BuyId] = CTE.[BuyId] AND c1._bigger_ = 0)
BuyId
1
2
fiddle
|
How to select buyers who increased their order quantity with each consecutive order
|
I have table Buyer
BuyId
QuantityOrdered
dateordered
1
10
2021-11-04
1
20
2022-01-22
2
50
2022-02-20
2
60
2022-05-02
3
10
2022-05-02
4
10
2022-05-02
I need to select all BuyId's who consecutively had higher QuantityOrder in each new record
buyid=1 had first order with quantity=10, second order with quantity=20
buyid=2 had first order with quantity=50, second order with quantity=60
So BuyId=1 and 2 would enter the results, while 3 and 4 would be filtered out because they had only one order or they did not have orders with consecutively higher quantities ordered
I tried with this, and I'm aware that this query gives me only buyid's who have more than one order, but I am missing the rule where I have to filter results out by quantity increased with each new order
select buyid, count(*) as ordered
from buyer
group by buyid
having count(*) >1
How would I write out that rule in a query, to select only BuyId's who had multiple orders, and in each new order they ordered higher quantities than in previous orders?
|
[
"Taking advantage of the fact that count() doesn't takes into account NULL values:\nselect buyid from (\nselect buyid, count(QuantityOrdered) as norders, count(mod) as nqttyincreasing\nfrom (\n select d.*, \n case when nvl(lag(QuantityOrdered) over(partition by buyid order by dateordered),0) < QuantityOrdered then 1 end as mod\n from data d\n)\ngroup by buyid\n) where norders = nqttyincreasing ;\n\n",
"With this query, it will check if all purchases as bigger in quantity as the last and will not show buyers id. that have only one purchase or sold equal or less than the last time4\nCREATE TABLE buyers\n ([BuyId] int, [QuantityOrdered] int, [dateordered] date)\n;\n \nINSERT INTO buyers\n ([BuyId], [QuantityOrdered], [dateordered])\nVALUES\n (1, 10, '2021-11-04'),\n (1, 20, '2022-01-22'),\n (1, 30, '2022-02-22'),\n (2, 50, '2022-02-20'),\n (2, 60, '2022-05-02'),\n (3, 60, '2022-05-02'),\n (4, 10, '2022-05-02'),\n (4, 6, '2022-06-02')\n;\n\n\n8 rows affected\n\nWITH CTE as (SELECT\n[BuyId], [QuantityOrdered], [dateordered],\n (SELECT COUNT(*) FROM buyers b1 WHERE b1.[BuyId] = buyers.[BuyId]) _count_\n,CASE WHEn [QuantityOrdered] > \n LAG([QuantityOrdered]) OVER(PARTITION BY [BuyId] ORDER BY [dateordered])\nTHEn 1 \n ELSe \n CASE WHEN LAG([QuantityOrdered]) OVER(PARTITION BY [BuyId] ORDER BY [dateordered]) IS NULL \n THEN 1 ELSE 0 END\n END _bigger_\nFROM buyers)\nSELECT DISTINCT [BuyId] FROM CTE \n WHERE _count_ > 1 AND NOT EXISTS ( SELECT 1 FROM CTE c1 \n WHERE c1.[BuyId] = CTE.[BuyId] AND c1._bigger_ = 0)\n\n\n\n\n\nBuyId\n\n\n\n\n1\n\n\n2\n\n\n\n\nfiddle\n"
] |
[
0,
0
] |
[] |
[] |
[
"sql",
"sql_server",
"sql_server_2019"
] |
stackoverflow_0074669688_sql_sql_server_sql_server_2019.txt
|
Q:
When to use a namespace or a struct?
I was just reading a little bit on them from http://www.cplusplus.com/doc/tutorial/namespaces/
and it seems like a struct is capable of the same things? Or even a class for that matter. Maybe someone here can better define what a namespace is, and how it differs from a struct/class?
A:
Namespaces and class-types are not capable of the same things. Namespaces are mainly used to group types and functions together to avoid name collisions, while class-types hold data and operations that work on that data.
To just group functions and objects by using a class-types you'd have to make them static:
struct X {
static void f();
};
Without static you'd have to create instances of the class-types to use them. A namespace is much better suited here:
namespace X {
void f();
}
Another important thing are using declarations and directives:
namespace X {
void f();
void g();
}
void h() {
using X::f;
f(); // f() now visible in current scope
using namespace X;
f(); g(); // both visible
}
With class-types there simply is no mechanism that allows that.
What class-types give you over namespaces is that you can have multiple instances with differing state - if you need that use a class-type.
A:
Well, seems everyone's going at it, so I'll add my own arguments.
First things first, namespace and struct are completely different beasts: they have different syntax and different semantics.
The obvious:
a struct introduces a type, you can use as templates argument
a namespace can be spread in several files
Syntactically:
both can be "aliased", namespace with namespace ns = mylong::name::space; and struct with typedef mylong::name::Space lilstruct;
ADL (or Argument Dependent Lookup) is tailored for namespaces
Semantically:
a namespace only defines a scope for the definition of symbols, which allows to group together objects that work together (classes and free-functions) while isolating them for the rest of the world (name clashes). As such it often represents a logical unit of work within the project (for small projects, there is a single namespace).
a struct or class defines a logical binding between data and the methods to act upon it, which is the corner stone of encapsulation. It usually has one clear responsability and a number of invariants.
Note that sometimes a struct or class is just used to bind together objects that work together without having any logic, for example struct Person { std::string name, firstName; };.
That being said: there is no point in C++ for a struct of static methods. It's just a perversion from Java or C# and their "pure" OO approach. C++ supports free functions, so there is no point not using them, especially since it's better for encapsulation (they don't have access to private/protected parts, so you can't mess up an invariant and they don't depend on the representation of the class either).
A:
If it can be done with a namespace, use a namespace.
A struct does much more than defining a scope. It defines a type.
A:
If you don't want people to use the "using" feature of C++ with your class, which can be dangerous and is often ill advised in complex code, then go ahead and use struct with statics.
In other words: if your functions should always be referred to with "group::function", then you can box in your users by declaring as a struct.
In addition, and importantly, you can forward-declare structs in older versions of C++. You cannot do this with namespaces until C++ 11.
Consider:
std::string out zip::pack(const std::string &in)
std::string out zip::unpack(const std::string &in)
In this case, requiring users to specify zip:: makes sense. It's a short, specific and informative. And the names of the underlying functions are ambiguous without it. Use a struct with statics.
Consider:
std::string out CorpDataUtils::zipPack(const std::string &in)
std::string out CorpDataUtils::zipUnpack(const std::string &in)
These should certainly be in a namespace. The namespace name is long, and uninformative, probably more to do with the organization of whoever is maintaining it - which is fine... but really it should be a namespace... not a struct.
A:
In C++ a struct is exactly the same as a class, except structs are public by default. Classes are private. So whenever you want to group free functions together use a namespace. When you want to group data and functions, use a struct/class, and optionally a namespace around it all.
Notice that If you put your functions in a struct then you would have to have an instance of your struct when you want to call those functions, unless they are static.
A:
When creating your own library, it's normally good practice to namespace all your exported functions and classes.
That way, if someone includes your library, they won't be polluting their namespace, and there is less likelyhood of name clashes.
A:
This is a counter example where using a struct instead of a namespace gives some unexpected benefits.
I wanted to generalise a solution to a 2D problem to K dimensions. The 2D solution was enclosed in a namespace.
Templates to the rescue. I started changing the implementation:
struct Point;
to
template< size_t DIMS >
struct Point;
I needed to template most classes, structs, and functions. That was tedious, repetitive, and error prone. And then I had this mischevios idea. I changed
namespace KDimSpace {
to
template< size_t DIMS >
struct KDimSpace {
and that was pretty much it. I could rip off all template< size_t DIMS > junk inside. This is so much easier - the number of dimensions DIMS is declared only once and used consistently by all types and functions.
And then, there is one more thing - rather than hiding internals of the implementation behind ::detail (sub)namespace there is public: and private:!
There are two annoyances:
functions have to be marked as static
it is not possible to define operators (e.g. operator<< for std::ostream) because operators cannot be marked as static (and then ADL might get in the way as well).
Bottom line - C++ could be a better language with fewer primitives not more. I would like namespaces to be as close to structs as classes are.
|
When to use a namespace or a struct?
|
I was just reading a little bit on them from http://www.cplusplus.com/doc/tutorial/namespaces/
and it seems like a struct is capable of the same things? Or even a class for that matter. Maybe someone here can better define what a namespace is, and how it differs from a struct/class?
|
[
"Namespaces and class-types are not capable of the same things. Namespaces are mainly used to group types and functions together to avoid name collisions, while class-types hold data and operations that work on that data.\nTo just group functions and objects by using a class-types you'd have to make them static:\nstruct X {\n static void f();\n};\n\nWithout static you'd have to create instances of the class-types to use them. A namespace is much better suited here:\nnamespace X {\n void f();\n}\n\nAnother important thing are using declarations and directives:\nnamespace X {\n void f();\n void g();\n}\n\nvoid h() {\n using X::f;\n f(); // f() now visible in current scope\n using namespace X;\n f(); g(); // both visible\n}\n\nWith class-types there simply is no mechanism that allows that.\nWhat class-types give you over namespaces is that you can have multiple instances with differing state - if you need that use a class-type.\n",
"Well, seems everyone's going at it, so I'll add my own arguments.\nFirst things first, namespace and struct are completely different beasts: they have different syntax and different semantics.\nThe obvious:\n\na struct introduces a type, you can use as templates argument\na namespace can be spread in several files\n\nSyntactically:\n\nboth can be \"aliased\", namespace with namespace ns = mylong::name::space; and struct with typedef mylong::name::Space lilstruct;\nADL (or Argument Dependent Lookup) is tailored for namespaces\n\nSemantically:\n\na namespace only defines a scope for the definition of symbols, which allows to group together objects that work together (classes and free-functions) while isolating them for the rest of the world (name clashes). As such it often represents a logical unit of work within the project (for small projects, there is a single namespace).\na struct or class defines a logical binding between data and the methods to act upon it, which is the corner stone of encapsulation. It usually has one clear responsability and a number of invariants.\n\nNote that sometimes a struct or class is just used to bind together objects that work together without having any logic, for example struct Person { std::string name, firstName; };.\nThat being said: there is no point in C++ for a struct of static methods. It's just a perversion from Java or C# and their \"pure\" OO approach. C++ supports free functions, so there is no point not using them, especially since it's better for encapsulation (they don't have access to private/protected parts, so you can't mess up an invariant and they don't depend on the representation of the class either).\n",
"If it can be done with a namespace, use a namespace.\nA struct does much more than defining a scope. It defines a type.\n",
"If you don't want people to use the \"using\" feature of C++ with your class, which can be dangerous and is often ill advised in complex code, then go ahead and use struct with statics. \nIn other words: if your functions should always be referred to with \"group::function\", then you can box in your users by declaring as a struct. \nIn addition, and importantly, you can forward-declare structs in older versions of C++. You cannot do this with namespaces until C++ 11.\nConsider: \nstd::string out zip::pack(const std::string &in)\nstd::string out zip::unpack(const std::string &in)\n\nIn this case, requiring users to specify zip:: makes sense. It's a short, specific and informative. And the names of the underlying functions are ambiguous without it. Use a struct with statics.\nConsider: \nstd::string out CorpDataUtils::zipPack(const std::string &in)\nstd::string out CorpDataUtils::zipUnpack(const std::string &in)\n\nThese should certainly be in a namespace. The namespace name is long, and uninformative, probably more to do with the organization of whoever is maintaining it - which is fine... but really it should be a namespace... not a struct.\n",
"In C++ a struct is exactly the same as a class, except structs are public by default. Classes are private. So whenever you want to group free functions together use a namespace. When you want to group data and functions, use a struct/class, and optionally a namespace around it all. \nNotice that If you put your functions in a struct then you would have to have an instance of your struct when you want to call those functions, unless they are static. \n",
"When creating your own library, it's normally good practice to namespace all your exported functions and classes.\nThat way, if someone includes your library, they won't be polluting their namespace, and there is less likelyhood of name clashes.\n",
"This is a counter example where using a struct instead of a namespace gives some unexpected benefits.\nI wanted to generalise a solution to a 2D problem to K dimensions. The 2D solution was enclosed in a namespace.\nTemplates to the rescue. I started changing the implementation:\nstruct Point;\n\nto\ntemplate< size_t DIMS >\nstruct Point;\n\nI needed to template most classes, structs, and functions. That was tedious, repetitive, and error prone. And then I had this mischevios idea. I changed\n namespace KDimSpace {\n\nto\n template< size_t DIMS >\n struct KDimSpace {\n\nand that was pretty much it. I could rip off all template< size_t DIMS > junk inside. This is so much easier - the number of dimensions DIMS is declared only once and used consistently by all types and functions.\nAnd then, there is one more thing - rather than hiding internals of the implementation behind ::detail (sub)namespace there is public: and private:!\nThere are two annoyances:\n\nfunctions have to be marked as static\nit is not possible to define operators (e.g. operator<< for std::ostream) because operators cannot be marked as static (and then ADL might get in the way as well).\n\nBottom line - C++ could be a better language with fewer primitives not more. I would like namespaces to be as close to structs as classes are.\n"
] |
[
24,
10,
4,
4,
2,
2,
0
] |
[] |
[] |
[
"c++",
"namespaces",
"struct"
] |
stackoverflow_0002614314_c++_namespaces_struct.txt
|
Q:
Extracting information from a list of json Python
Identifier Properties
1 [{"$id":"2","SMName":"pia.redoabs.com","Type":"sms"},{"$id":"3","Name":"_18_Lucene41_0.doc","Type":"file"}]
2 [{"$id":"2","SMName":"pred.redocad.com","Type":"sms"},{"$id":"3","Name":"_18_Nil41_0.doc","Type":"file"}]
3 [{"$id":"2","SMName":"promomaster.com","Type":"sms"},{"$id":"3","Name":"_17_Litre41_0.doc","Type":"file"}]
4 [{"$id":"2","SMName":"admaster.com","Type":"sms"},{"$id":"3","Name":"_k.pos","Type":"file"}]
5 [{"$id":"2","SMName":"plan.com.com","Type":"sms"},{"$id":"3","Name":"_3_Lucene41_0.doc","Type":"file"}]
6 [{"$id":"2","Name":"jm460","ETNDomain":"ent.ad.ent","Sid":"S-1-5-21-117609710-2111687655-839522115-432193","AadUserId":"7133971dffgh5r-b9b8-4af3-bbfd-85b1b56d1f6f","IsDomainJoined":true,"Type":"account","UserPrincipalName":"[email protected]"},{"$id":"3","Directory":"C:\\CR\\new_cbest_malware","Name":"ent_Survey.zip","hash":[{"$id":"4","Algorithm":"hsa1","Value":"cecce931f21697876efc80f5897a31481c396795","Type":"hash"},{"$id":"5","Algorithm":"MI5","Value":"12c216630a5f24faab06d463c9ce72a5","Type":"hash"},{"$id":"6","Algorithm":"TM345","Value":"cbb327b70a83fefeaf744458f2ed62021e529ce0ece36566761779f17d4c07a6","Type":"hash"}],"CreatedTimeUtc":"2022-08-22T17:42:02.4272869Z","Type":"file"},{"$ref":"4"},{"$ref":"5"},{"$ref":"6"},{"$id":"7","ProcessId":"54884","CommandLine":"\"7zG.exe\" a -i#7zMap23807:40278:7zEvent24942 -ad -saa -- \"C:\\CR\\CR_2\"","ElevationToken":"Default","CreationTimeUtc":"2022-10-03T17:59:35.2339055Z","ImageFile":{"$id":"8","Directory":"C:\\Program Files\\7-Zip","Name":"9zG.exe","FileHashes":[{"$id":"9","Algorithm":"HSA2","Value":"df22612647e9404a515d48ebad490349685250de","Type":"hash"},{"$id":"10","Algorithm":"MI5","Value":"04fb3ae7f05c8bc333125972ba907398","Type":"hash"},{"$id":"11","Algorithm":"hsa1","Value":"2fb898bacb587f2484c9c4aa6da2729079d93d1f923a017bb84beef87bf74fef","Type":"hash"}],"CreatedTimeUtc":"2020-09-21T16:34:33.1299959Z","Type":"file"},"ParentProcess":{"$id":"12","ProcessId":"13516","CreationTimeUtc":"2022-09-21T12:41:32.4609401Z","CreatedTimeUtc":"2022-09-21T12:41:32.4609401Z","Type":"process"},"CreatedTimeUtc":"2022-10-03T17:59:35.2339055Z","Type":"process"},{"$ref":"12"},{"$ref":"8"},{"$ref":"9"},{"$ref":"10"},{"$ref":"11"},{"$id":"13","DnsDomain":"ent.ad.ent.com","HostName":"ilch-l788441","OSFamily":"Windows","OSVersion":"20H2","Tags":[{"ProviderName":"tmdp","TagId":"VwanPov","TagName":"VwanPov","TagType":"UserDefined"},{"ProviderName":"dmpt","TagId":"Proxy Allow Personal Storage","TagName":"Proxy Allow Personal Storage","TagType":"UserDefined"},{"ProviderName":"dmpt","TagId":"Proxy Allow Webmail","TagName":"Proxy Allow Webmail","TagType":"UserDefined"},{"ProviderName":"dmpt","TagId":"proxy-allow-social-media","TagName":"proxy-allow-social-media","TagType":"UserDefined"}],"Type":"host","dmptDeviceId":"fa52ff90ab60ee6eac86ec60ed2ac748a33e29fa","FQDN":"ilch-567.ent.ad.ent.com","AadDeviceId":"e1d59b69-dd3f-4f33-96b5-db9233654c16","RiskScore":"Medium","HealthStatus":"Active","LastSeen":"2022-10-03T18:09:32.7812655","LastExternalIpAddress":"208.95.144.39","LastIpAddress":"10.14.126.52","AvStatus":"Updated","OnboardingStatus":"Onboarded","LoggedOnUsers":[{"AccountName":"jmjklo460","DomainName":"ENT"}]}]
This is a dataframe with 2 columns "Identifier" & "Properties". The "Properties" column appears as a list of json.The aim is to create 2 different columns for "sms" & "file".
I noticed that one of the rows have entirely different information & I would need a few of them.For eg- ENTDomain,UserPrincipalName
The code that you provided works for the first 5 observations but tends to fail when it encounters the 6th observation.
Can we make the code dynamic to be able to extract any values ?
Further I used kql to parse this data & it was relatively straightforward.
A:
You can try:
import json
df["Properties"] = df["Properties"].apply(
lambda x: {
d["Type"]: (d["SMName"] if d["Type"] == "sms" else d["Name"])
for d in json.loads(x)
}
)
df = pd.concat([df, df.pop("Properties").apply(pd.Series)], axis=1)
print(df)
Prints:
Identifier sms file
0 1 pia.redoabs.com _18_Lucene41_0.doc
1 2 pred.redocad.com _18_Nil41_0.doc
2 3 promomaster.com _17_Litre41_0.doc
3 4 admaster.com _k.pos
4 5 plan.com.com _3_Lucene41_0.doc
|
Extracting information from a list of json Python
|
Identifier Properties
1 [{"$id":"2","SMName":"pia.redoabs.com","Type":"sms"},{"$id":"3","Name":"_18_Lucene41_0.doc","Type":"file"}]
2 [{"$id":"2","SMName":"pred.redocad.com","Type":"sms"},{"$id":"3","Name":"_18_Nil41_0.doc","Type":"file"}]
3 [{"$id":"2","SMName":"promomaster.com","Type":"sms"},{"$id":"3","Name":"_17_Litre41_0.doc","Type":"file"}]
4 [{"$id":"2","SMName":"admaster.com","Type":"sms"},{"$id":"3","Name":"_k.pos","Type":"file"}]
5 [{"$id":"2","SMName":"plan.com.com","Type":"sms"},{"$id":"3","Name":"_3_Lucene41_0.doc","Type":"file"}]
6 [{"$id":"2","Name":"jm460","ETNDomain":"ent.ad.ent","Sid":"S-1-5-21-117609710-2111687655-839522115-432193","AadUserId":"7133971dffgh5r-b9b8-4af3-bbfd-85b1b56d1f6f","IsDomainJoined":true,"Type":"account","UserPrincipalName":"[email protected]"},{"$id":"3","Directory":"C:\\CR\\new_cbest_malware","Name":"ent_Survey.zip","hash":[{"$id":"4","Algorithm":"hsa1","Value":"cecce931f21697876efc80f5897a31481c396795","Type":"hash"},{"$id":"5","Algorithm":"MI5","Value":"12c216630a5f24faab06d463c9ce72a5","Type":"hash"},{"$id":"6","Algorithm":"TM345","Value":"cbb327b70a83fefeaf744458f2ed62021e529ce0ece36566761779f17d4c07a6","Type":"hash"}],"CreatedTimeUtc":"2022-08-22T17:42:02.4272869Z","Type":"file"},{"$ref":"4"},{"$ref":"5"},{"$ref":"6"},{"$id":"7","ProcessId":"54884","CommandLine":"\"7zG.exe\" a -i#7zMap23807:40278:7zEvent24942 -ad -saa -- \"C:\\CR\\CR_2\"","ElevationToken":"Default","CreationTimeUtc":"2022-10-03T17:59:35.2339055Z","ImageFile":{"$id":"8","Directory":"C:\\Program Files\\7-Zip","Name":"9zG.exe","FileHashes":[{"$id":"9","Algorithm":"HSA2","Value":"df22612647e9404a515d48ebad490349685250de","Type":"hash"},{"$id":"10","Algorithm":"MI5","Value":"04fb3ae7f05c8bc333125972ba907398","Type":"hash"},{"$id":"11","Algorithm":"hsa1","Value":"2fb898bacb587f2484c9c4aa6da2729079d93d1f923a017bb84beef87bf74fef","Type":"hash"}],"CreatedTimeUtc":"2020-09-21T16:34:33.1299959Z","Type":"file"},"ParentProcess":{"$id":"12","ProcessId":"13516","CreationTimeUtc":"2022-09-21T12:41:32.4609401Z","CreatedTimeUtc":"2022-09-21T12:41:32.4609401Z","Type":"process"},"CreatedTimeUtc":"2022-10-03T17:59:35.2339055Z","Type":"process"},{"$ref":"12"},{"$ref":"8"},{"$ref":"9"},{"$ref":"10"},{"$ref":"11"},{"$id":"13","DnsDomain":"ent.ad.ent.com","HostName":"ilch-l788441","OSFamily":"Windows","OSVersion":"20H2","Tags":[{"ProviderName":"tmdp","TagId":"VwanPov","TagName":"VwanPov","TagType":"UserDefined"},{"ProviderName":"dmpt","TagId":"Proxy Allow Personal Storage","TagName":"Proxy Allow Personal Storage","TagType":"UserDefined"},{"ProviderName":"dmpt","TagId":"Proxy Allow Webmail","TagName":"Proxy Allow Webmail","TagType":"UserDefined"},{"ProviderName":"dmpt","TagId":"proxy-allow-social-media","TagName":"proxy-allow-social-media","TagType":"UserDefined"}],"Type":"host","dmptDeviceId":"fa52ff90ab60ee6eac86ec60ed2ac748a33e29fa","FQDN":"ilch-567.ent.ad.ent.com","AadDeviceId":"e1d59b69-dd3f-4f33-96b5-db9233654c16","RiskScore":"Medium","HealthStatus":"Active","LastSeen":"2022-10-03T18:09:32.7812655","LastExternalIpAddress":"208.95.144.39","LastIpAddress":"10.14.126.52","AvStatus":"Updated","OnboardingStatus":"Onboarded","LoggedOnUsers":[{"AccountName":"jmjklo460","DomainName":"ENT"}]}]
This is a dataframe with 2 columns "Identifier" & "Properties". The "Properties" column appears as a list of json.The aim is to create 2 different columns for "sms" & "file".
I noticed that one of the rows have entirely different information & I would need a few of them.For eg- ENTDomain,UserPrincipalName
The code that you provided works for the first 5 observations but tends to fail when it encounters the 6th observation.
Can we make the code dynamic to be able to extract any values ?
Further I used kql to parse this data & it was relatively straightforward.
|
[
"You can try:\nimport json\n\ndf[\"Properties\"] = df[\"Properties\"].apply(\n lambda x: {\n d[\"Type\"]: (d[\"SMName\"] if d[\"Type\"] == \"sms\" else d[\"Name\"])\n for d in json.loads(x)\n }\n)\n\ndf = pd.concat([df, df.pop(\"Properties\").apply(pd.Series)], axis=1)\n\nprint(df)\n\nPrints:\n Identifier sms file\n0 1 pia.redoabs.com _18_Lucene41_0.doc\n1 2 pred.redocad.com _18_Nil41_0.doc\n2 3 promomaster.com _17_Litre41_0.doc\n3 4 admaster.com _k.pos\n4 5 plan.com.com _3_Lucene41_0.doc\n\n"
] |
[
0
] |
[] |
[] |
[
"json",
"list",
"python"
] |
stackoverflow_0074669506_json_list_python.txt
|
Q:
How to change color scheme using css only?
Hey can any one tell me that is there any way to change the color scheme within the website. Wait I will explain it clearly with some code.
@media (prefers-color-scheme: dark) {}
@media (prefers-color-scheme: light) {}
Is there any way that by using HTML button can we change the color scheme light to dark.
I have searched the whole internet and didn't find a right answer. Although I am new to Css. So please solve my query.
A:
If you use CSS variables you can change them with JavaScript like so:
var usesDarkTheme = false;
function changeColorTheme() {
const body = document.body;
if (usesDarkTheme) {
body.style.setProperty('--main-color', 'white');
usesDarkTheme = false;
} else {
body.style.setProperty('--main-color', 'black');
usesDarkTheme = true;
}
}
body {
--main-color: white;
}
.content {
background-color: var(--main-color);
width: 100px;
height: 100px;
}
<div class="content"> </div>
<button onclick="changeColorTheme()">Change Color Theme</button>
A:
You can make it automatically change or manually, like this:
document.getElementById("theme").addEventListener("click", () => {
const meta = document.querySelector('meta[name="color-scheme"]');
if (meta.content === "light") {
meta.content = "dark";
document.body.classList.remove("light-mode");
document.body.classList.add("dark-mode");
} else {
meta.content = "light";
document.body.classList.remove("dark-mode");
document.body.classList.add("light-mode");
}
});
@media (prefers-color-scheme: dark) {
:root {
--color-primary: #0a0a0a;
--color-secondary: #339eff;
}
}
@media (prefers-color-scheme: light) {
:root {
--color-primary: #ffffff;
--color-secondary: #ff7e33;
}
}
.light-mode {
--color-primary: #ffffff;
--color-secondary: #ff7e33;
}
.dark-mode {
--color-primary: #0a0a0a;
--color-secondary: #339eff;
}
body {
background-color: var(--color-primary);
color: var(--color-secondary);
}
<!DOCTYPE html>
<html lang="pt-BR" xmlns="http://www.w3.org/1999/xhtml" xml:lang="pt-br">
<head>
<meta name="color-scheme" content="dark light" />
<meta name="theme-color" media="(prefers-color-scheme: dark)" />
<meta name="theme-color" media="(prefers-color-scheme: light)" />
</head>
<body>
This is a test
<button id="theme">Change theme</button>
</body>
</html>
You can change it to your needs, but this is according to web.dev. Remember to set the prefers-color-scheme colors, and then change it automatically or by a manual toggle, using the .light-mode and .dark-mode classes.
A:
How to change color scheme using css only?
There are multiple ways to update a color scheme on a web page.
If you don't intend to write your own elaborately customised themes, there is a way to update a color scheme (between Operating System Light Color Scheme and Operating System Dark Color Scheme) via CSS and at page level (ie. not at Browser or Operating System level).
To achieve this, you can take advantage of the CSS declaration:
:root {
color-scheme: normal;
}
A couple of notes before we continue:
Most importantly, note that color-scheme has a very specific application here - pertaining to Interactive Form Elements - so updating color-scheme will affect the appearance of only a limited subset of non-styled HTML elements including <input type="text">, <textarea> etc. and also :root
Also note that colors produced by color-scheme: light and color-scheme: dark cannot be customised. They explicitly refer to the Light Color Scheme and Dark Color Scheme of whatever Operating System you're using
Thirdly, note that this approach isn't strictly css-only because you will still need JavaScript to update the CSS property on :root:
e.g. document.documentElement.style.setProperty('color-scheme', 'dark');
Fourthly, note that although we're using JavaScript to update CSS here and not HTML, :root {color-scheme: dark;} is the CSS equivalent of the HTML metatag <meta name="color-scheme" content="dark" />
Working Example:
Try the radio buttons below:
const radioButtons = document.querySelector('.radio-buttons');
const textboxes = document.querySelectorAll('.textbox');
const toggleMode = (e) => {
let colorScheme = e.target.dataset.mode;
document.documentElement.style.setProperty('color-scheme', colorScheme);
textboxes.forEach((textbox, i) => {
if ((i === 1) || (i === 3)) {
textbox.value = 'Page Color Scheme\n(' + colorScheme + ')';
}
});
}
radioButtons.addEventListener('change', toggleMode);
:root {
color-scheme: normal;
}
fieldset {
display: inline-block;
float: left;
border: none;
}
.radio-buttons {
width: 110px;
line-height: 36px;
}
label {
cursor: pointer;
}
.textbox {
display: inline-block;
float: left;
margin: 0 4px 4px 0;
width: 158px;
height: 48px;
line-height: 24px;
text-align: center;
border: 1px solid rgb(255, 0, 0);
overflow: hidden;
resize: none;
}
.textbox:nth-of-type(odd) {
clear: left;
}
.normal-scheme {
color-scheme: normal;
}
.light-theme {
color: rgb(7, 7, 7);
background-color: rgb(247, 247, 247);
}
.dark-theme {
color: rgb(247, 247, 247);
background-color: rgb(7, 7, 7);
}
@media (prefers-color-scheme: dark) {
.normal-theme {
color: rgb(247, 247, 247);
background-color: rgb(7, 7, 7);
}
}
@media (prefers-color-scheme: light) {
.normal-theme {
color: rgb(7, 7, 7);
background-color: rgb(247, 247, 247);
}
}
<form>
<fieldset class="radio-buttons">
<label><input type="radio" name="mode" data-mode="normal" checked /> OS Default</label>
<label><input type="radio" name="mode" data-mode="light" /> Light Mode</label>
<label><input type="radio" name="mode" data-mode="dark" /> Dark Mode</label>
</fieldset>
<fieldset>
<textarea class="textbox light-theme">
CSS Hardcoded
(light theme)
</textarea>
<textarea class="textbox">
Page Color Scheme
(normal)
</textarea>
<textarea class="textbox dark-theme">
CSS Hardcoded
(dark theme)
</textarea>
<textarea class="textbox">
Page Color Scheme
(normal)
</textarea>
<textarea class="textbox normal-theme">
CSS @media Query
(refers to OS Setting)
</textarea>
<textarea class="textbox normal-scheme">
Browser Color Scheme
(browser default)
</textarea>
</fieldset>
</form>
A few more notes:
The dark and light themes I've hardcoded into the CSS above are (deliberately) slightly darker than the System-native dark and light themes. This is so that whenever styles update above, you can see whether the new styles have come from the CSS Stylesheet or from the Operating System
You'll see that the radio buttons alone are sufficient to change the Page Color Scheme from normal to light to dark - and that when they do, the styling comes from the Operating System
If you then go into your browser tools and simulate OS Dark Mode, you'll see the bottom left <textbox> update from Light to Dark - when it does, you'll see the styling comes from the styles declared in the prefers-color-scheme @mediaQuery in the CSS Stylesheet
In Summary: you can toggle the presentation of unstyled Interactive Form Elements between Operating System Light Color Scheme and Operating System Dark Color Scheme at page level via CSS and a very small amount of JavaScript. But this isn't (at all) the same as writing your own Light Theme and Dark Theme and toggling between them.
|
How to change color scheme using css only?
|
Hey can any one tell me that is there any way to change the color scheme within the website. Wait I will explain it clearly with some code.
@media (prefers-color-scheme: dark) {}
@media (prefers-color-scheme: light) {}
Is there any way that by using HTML button can we change the color scheme light to dark.
I have searched the whole internet and didn't find a right answer. Although I am new to Css. So please solve my query.
|
[
"If you use CSS variables you can change them with JavaScript like so:\n\n\nvar usesDarkTheme = false;\n\nfunction changeColorTheme() {\n const body = document.body;\n if (usesDarkTheme) {\n body.style.setProperty('--main-color', 'white');\n usesDarkTheme = false;\n } else {\n body.style.setProperty('--main-color', 'black');\n usesDarkTheme = true;\n }\n}\nbody {\n --main-color: white;\n}\n\n.content {\n background-color: var(--main-color);\n width: 100px;\n height: 100px;\n}\n<div class=\"content\"> </div>\n\n<button onclick=\"changeColorTheme()\">Change Color Theme</button>\n\n\n\n",
"You can make it automatically change or manually, like this:\n\n\n document.getElementById(\"theme\").addEventListener(\"click\", () => {\n const meta = document.querySelector('meta[name=\"color-scheme\"]');\n if (meta.content === \"light\") {\n meta.content = \"dark\";\n document.body.classList.remove(\"light-mode\");\n document.body.classList.add(\"dark-mode\");\n } else {\n meta.content = \"light\";\n document.body.classList.remove(\"dark-mode\");\n document.body.classList.add(\"light-mode\");\n }\n });\n@media (prefers-color-scheme: dark) {\n :root {\n --color-primary: #0a0a0a;\n --color-secondary: #339eff;\n }\n}\n\n@media (prefers-color-scheme: light) {\n :root {\n --color-primary: #ffffff;\n --color-secondary: #ff7e33;\n }\n}\n\n.light-mode {\n --color-primary: #ffffff;\n --color-secondary: #ff7e33;\n}\n\n.dark-mode {\n --color-primary: #0a0a0a;\n --color-secondary: #339eff;\n}\n\nbody {\n background-color: var(--color-primary);\n color: var(--color-secondary);\n}\n<!DOCTYPE html>\n<html lang=\"pt-BR\" xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"pt-br\">\n <head>\n <meta name=\"color-scheme\" content=\"dark light\" />\n <meta name=\"theme-color\" media=\"(prefers-color-scheme: dark)\" />\n <meta name=\"theme-color\" media=\"(prefers-color-scheme: light)\" />\n </head>\n <body>\n This is a test\n\n <button id=\"theme\">Change theme</button>\n </body>\n</html>\n\n\n\nYou can change it to your needs, but this is according to web.dev. Remember to set the prefers-color-scheme colors, and then change it automatically or by a manual toggle, using the .light-mode and .dark-mode classes.\n",
"\nHow to change color scheme using css only?\n\nThere are multiple ways to update a color scheme on a web page.\nIf you don't intend to write your own elaborately customised themes, there is a way to update a color scheme (between Operating System Light Color Scheme and Operating System Dark Color Scheme) via CSS and at page level (ie. not at Browser or Operating System level).\nTo achieve this, you can take advantage of the CSS declaration:\n:root {\n color-scheme: normal;\n}\n\n\nA couple of notes before we continue:\n\nMost importantly, note that color-scheme has a very specific application here - pertaining to Interactive Form Elements - so updating color-scheme will affect the appearance of only a limited subset of non-styled HTML elements including <input type=\"text\">, <textarea> etc. and also :root\n\nAlso note that colors produced by color-scheme: light and color-scheme: dark cannot be customised. They explicitly refer to the Light Color Scheme and Dark Color Scheme of whatever Operating System you're using\n\nThirdly, note that this approach isn't strictly css-only because you will still need JavaScript to update the CSS property on :root:\ne.g. document.documentElement.style.setProperty('color-scheme', 'dark');\n\nFourthly, note that although we're using JavaScript to update CSS here and not HTML, :root {color-scheme: dark;} is the CSS equivalent of the HTML metatag <meta name=\"color-scheme\" content=\"dark\" />\n\n\n\nWorking Example:\nTry the radio buttons below:\n\n\nconst radioButtons = document.querySelector('.radio-buttons');\nconst textboxes = document.querySelectorAll('.textbox');\n\nconst toggleMode = (e) => {\n \n let colorScheme = e.target.dataset.mode;\n document.documentElement.style.setProperty('color-scheme', colorScheme);\n textboxes.forEach((textbox, i) => {\n \n if ((i === 1) || (i === 3)) {\n textbox.value = 'Page Color Scheme\\n(' + colorScheme + ')';\n }\n });\n}\n\nradioButtons.addEventListener('change', toggleMode);\n:root {\n color-scheme: normal;\n}\n\nfieldset {\n display: inline-block;\n float: left;\n border: none;\n}\n\n.radio-buttons {\n width: 110px;\n line-height: 36px;\n}\n\nlabel {\n cursor: pointer;\n}\n\n.textbox {\n display: inline-block;\n float: left;\n margin: 0 4px 4px 0;\n width: 158px;\n height: 48px;\n line-height: 24px;\n text-align: center;\n border: 1px solid rgb(255, 0, 0);\n overflow: hidden;\n resize: none;\n}\n\n.textbox:nth-of-type(odd) {\n clear: left;\n}\n\n.normal-scheme {\n color-scheme: normal;\n}\n\n.light-theme {\n color: rgb(7, 7, 7);\n background-color: rgb(247, 247, 247);\n}\n\n.dark-theme {\n color: rgb(247, 247, 247);\n background-color: rgb(7, 7, 7);\n}\n\n@media (prefers-color-scheme: dark) {\n .normal-theme {\n color: rgb(247, 247, 247);\n background-color: rgb(7, 7, 7);\n }\n}\n\n@media (prefers-color-scheme: light) {\n .normal-theme {\n color: rgb(7, 7, 7);\n background-color: rgb(247, 247, 247);\n }\n}\n<form>\n\n<fieldset class=\"radio-buttons\">\n<label><input type=\"radio\" name=\"mode\" data-mode=\"normal\" checked /> OS Default</label>\n<label><input type=\"radio\" name=\"mode\" data-mode=\"light\" /> Light Mode</label>\n<label><input type=\"radio\" name=\"mode\" data-mode=\"dark\" /> Dark Mode</label>\n</fieldset>\n\n<fieldset>\n<textarea class=\"textbox light-theme\">\nCSS Hardcoded\n(light theme)\n</textarea>\n\n<textarea class=\"textbox\">\nPage Color Scheme\n(normal)\n</textarea>\n\n<textarea class=\"textbox dark-theme\">\nCSS Hardcoded\n(dark theme)\n</textarea>\n\n<textarea class=\"textbox\">\nPage Color Scheme\n(normal)\n</textarea>\n\n<textarea class=\"textbox normal-theme\">\nCSS @media Query\n(refers to OS Setting)\n</textarea>\n\n<textarea class=\"textbox normal-scheme\">\nBrowser Color Scheme\n(browser default)\n</textarea>\n</fieldset>\n</form>\n\n\n\nA few more notes:\n\nThe dark and light themes I've hardcoded into the CSS above are (deliberately) slightly darker than the System-native dark and light themes. This is so that whenever styles update above, you can see whether the new styles have come from the CSS Stylesheet or from the Operating System\n\nYou'll see that the radio buttons alone are sufficient to change the Page Color Scheme from normal to light to dark - and that when they do, the styling comes from the Operating System\n\nIf you then go into your browser tools and simulate OS Dark Mode, you'll see the bottom left <textbox> update from Light to Dark - when it does, you'll see the styling comes from the styles declared in the prefers-color-scheme @mediaQuery in the CSS Stylesheet\n\n\nIn Summary: you can toggle the presentation of unstyled Interactive Form Elements between Operating System Light Color Scheme and Operating System Dark Color Scheme at page level via CSS and a very small amount of JavaScript. But this isn't (at all) the same as writing your own Light Theme and Dark Theme and toggling between them.\n"
] |
[
0,
0,
0
] |
[
"I didn't understand you completely but if you want to change primary color just use javascript and add onclick in html button\n"
] |
[
-1
] |
[
"css",
"html"
] |
stackoverflow_0067717909_css_html.txt
|
Q:
Is there a way to reformat w/ zero-fill a regex match group?
Suppose I have a file with 9%, 22%, 100% and so on.
Is there a Perl (or other) regex way to turn the numbers into "009", 022, and 100 respectively?
perl -p -i -e "s/width: (\d+)%/width_\1/g;" ...
correctly returns width_9, width_22, and width_100, which is okay, but if there's a clever, yet simple way to take the \1 matched group and add in formatting, it would be nice.
A:
You can use
perl -i -pe 's/width: (\d+)%/sprintf "width_%03s", $1/ge' file
Here, width: (\d+)% matches width: , then captures one or more digits into Group 1 ($1, not \1!), and a % char is also consumed right after, and the match is replaced with width_ + the reformatted number.
See the online demo:
#!/bin/bash
s='width: 9%, width: 22%, width: 100%'
perl -pe 's/width: (\d+)%/sprintf "width_%03s", $1/ge' <<< "$s"
Output:
width_009, width_022, width_100
|
Is there a way to reformat w/ zero-fill a regex match group?
|
Suppose I have a file with 9%, 22%, 100% and so on.
Is there a Perl (or other) regex way to turn the numbers into "009", 022, and 100 respectively?
perl -p -i -e "s/width: (\d+)%/width_\1/g;" ...
correctly returns width_9, width_22, and width_100, which is okay, but if there's a clever, yet simple way to take the \1 matched group and add in formatting, it would be nice.
|
[
"You can use\nperl -i -pe 's/width: (\\d+)%/sprintf \"width_%03s\", $1/ge' file\n\nHere, width: (\\d+)% matches width: , then captures one or more digits into Group 1 ($1, not \\1!), and a % char is also consumed right after, and the match is replaced with width_ + the reformatted number.\nSee the online demo:\n#!/bin/bash\ns='width: 9%, width: 22%, width: 100%'\nperl -pe 's/width: (\\d+)%/sprintf \"width_%03s\", $1/ge' <<< \"$s\"\n\nOutput:\nwidth_009, width_022, width_100\n\n"
] |
[
5
] |
[] |
[] |
[
"perl"
] |
stackoverflow_0074669892_perl.txt
|
Q:
How to fix Failed to connect to ESP32: Timed out waiting for packet header error?
I tried to flash an ESP32 but I didn't succeed, I tried with esptool.py and Arduino IDE. I tried to press the boot button and reset but it didn't work. Here is the error:
A fatal error occurred: Failed to connect to ESP32: Timed out waiting for packet header
A:
DISCLAIMER! May not be correct answer but may help to save time for someone.
Quick answer if you do not want read my experience: Disconnect all wires from pins and try uploading again! It may help.
I came across with the same error and could not figure it out. I first thought that something is wrong with the code, because it happened after I edited working code while figuring out where to connect what pin . I also wasn't able to upload simple HelloWorld after it happened with connected wires. But then I disconnected all my wires from the board and the upload works fine.
I can not figure out the WHY factor but I think it must had been the input/data pin I was using, in my case D13. I have the DevKit with fewer pins. Maybe someone can comment why connected pins may make the error come up?
A:
To make your ESP32 board go into flashing/uploading mode automatically, you can connect a 10 μF electrolytic capacitor between the EN pin and GND. When I had the same problem, when I followed this advice, the problem was solved.
References
Failed to connect to ESP32: Timed out waiting for packet header
espressif/arduino-esp32 - issue
A:
On some AliExpress-like ESP32s you have to press the boot button in order to upload your sketch.
If you are watching the Arduino IDE console ouput and Connecting ... appears, you have to press the boot button for approximately 2 seconds until the console output changes.
A:
Try to do this one after the other
Press the boot button when press uploading button until it write the code.
Try disconnect esp32 from the board/header/pcb that you are using right at the time.
Disconnect any other connection that your esp32 might have.
Do not connect to anything even your hand if possible.
Try put it in something that doesnt have a moist surface. look pic number 3.
MY CASES(30 pin version):
Case 1: I dont know why. I was connecting the pin to a female header it doesnt work and sometimes it just work like that. look pic number 1.
Case 2: when Im holding esp32 on my hand sometimes it wont work then i put it on my table and another time it doing well.
Case 3: pressing boot button when uploading it helped sometimes, and the other time it just work like it should.
Case 4: when it connected to pcb its simply just wont work, but when disconnected boom it work like nothing ever happen. look pic number 2.
Maybe just maybe something with capacitive or something like that (just assuming because number Case 1). hope that will help you out.
pic 1pic 2pic 3
A:
With Arduino IDE
Make sure the Com port is selected under Tools menu. My experience with ESP32 is Com 5.
If it is not available as an option, try changing USB ports and/or re-select Tools - Board - ESP32 dev module.
Watch the "Compiling Sketch" window.
Press the "Boot" button as soon as you get the red message "Serial port Com 5" You can release the button as soon as it starts to upload.
If this doesn't work,try plugging into another USB port.
The Reset button only resets the uploaded sketch to re-initialise and has nothing to do with the uploading.
A:
This technique definitely working
Goto Tools > programmer, Select ISP and Upload Your Code.
if you can't see any programmer, then download 1.8.12 version.
https://www.arduino.cc/en/software/OldSoftwareReleases
A:
Install expressif.exe and port drivers,connect the port and flash the esp32 ,upload the code using ardiuno,solve the error
A:
If using the Arduino IDE, try lowering the upload speed (Tools/Upload Speed). Lowering mine from 921600 to 460800 did the trick.
First ensure that you are in download mode:
Start the serial monitor and set the speed (mine is 115200).
While pressing the "boot" button, press and release the "en" button (your buttons may be labeled differently).
You should see something like this on the serial monitor:
waiting for download
Now start the upload
My development machine, a 2013 iMac is connected via USB to the USB-c port on my ESP32 Dev Module. Apparently the iMac's USB or ESP32 board's USB cannot keep up at the 921600 upload speed.
A:
in my case buttons are new but not shorting properly as multimeter showed ..opened both scratched resoldered and all working
A:
Just download the drivers x)
CP210x: CP210x USB to UART Bridge VCP Drivers
FTDI: FTDI Virtual COM Port Drivers
|
How to fix Failed to connect to ESP32: Timed out waiting for packet header error?
|
I tried to flash an ESP32 but I didn't succeed, I tried with esptool.py and Arduino IDE. I tried to press the boot button and reset but it didn't work. Here is the error:
A fatal error occurred: Failed to connect to ESP32: Timed out waiting for packet header
|
[
"DISCLAIMER! May not be correct answer but may help to save time for someone.\nQuick answer if you do not want read my experience: Disconnect all wires from pins and try uploading again! It may help.\nI came across with the same error and could not figure it out. I first thought that something is wrong with the code, because it happened after I edited working code while figuring out where to connect what pin . I also wasn't able to upload simple HelloWorld after it happened with connected wires. But then I disconnected all my wires from the board and the upload works fine.\nI can not figure out the WHY factor but I think it must had been the input/data pin I was using, in my case D13. I have the DevKit with fewer pins. Maybe someone can comment why connected pins may make the error come up?\n",
"To make your ESP32 board go into flashing/uploading mode automatically, you can connect a 10 μF electrolytic capacitor between the EN pin and GND. When I had the same problem, when I followed this advice, the problem was solved.\n\nReferences\n\nFailed to connect to ESP32: Timed out waiting for packet header\nespressif/arduino-esp32 - issue\n\n",
"On some AliExpress-like ESP32s you have to press the boot button in order to upload your sketch.\nIf you are watching the Arduino IDE console ouput and Connecting ... appears, you have to press the boot button for approximately 2 seconds until the console output changes.\n",
"Try to do this one after the other\n\nPress the boot button when press uploading button until it write the code.\nTry disconnect esp32 from the board/header/pcb that you are using right at the time.\nDisconnect any other connection that your esp32 might have.\nDo not connect to anything even your hand if possible.\nTry put it in something that doesnt have a moist surface. look pic number 3.\n\nMY CASES(30 pin version):\nCase 1: I dont know why. I was connecting the pin to a female header it doesnt work and sometimes it just work like that. look pic number 1.\nCase 2: when Im holding esp32 on my hand sometimes it wont work then i put it on my table and another time it doing well.\nCase 3: pressing boot button when uploading it helped sometimes, and the other time it just work like it should.\nCase 4: when it connected to pcb its simply just wont work, but when disconnected boom it work like nothing ever happen. look pic number 2.\nMaybe just maybe something with capacitive or something like that (just assuming because number Case 1). hope that will help you out.\npic 1pic 2pic 3\n",
"With Arduino IDE\nMake sure the Com port is selected under Tools menu. My experience with ESP32 is Com 5.\nIf it is not available as an option, try changing USB ports and/or re-select Tools - Board - ESP32 dev module.\nWatch the \"Compiling Sketch\" window.\nPress the \"Boot\" button as soon as you get the red message \"Serial port Com 5\" You can release the button as soon as it starts to upload.\nIf this doesn't work,try plugging into another USB port.\nThe Reset button only resets the uploaded sketch to re-initialise and has nothing to do with the uploading.\n",
"This technique definitely working\nGoto Tools > programmer, Select ISP and Upload Your Code.\nif you can't see any programmer, then download 1.8.12 version.\nhttps://www.arduino.cc/en/software/OldSoftwareReleases\n",
"Install expressif.exe and port drivers,connect the port and flash the esp32 ,upload the code using ardiuno,solve the error\n",
"If using the Arduino IDE, try lowering the upload speed (Tools/Upload Speed). Lowering mine from 921600 to 460800 did the trick.\nFirst ensure that you are in download mode:\n\nStart the serial monitor and set the speed (mine is 115200).\nWhile pressing the \"boot\" button, press and release the \"en\" button (your buttons may be labeled differently).\nYou should see something like this on the serial monitor:\nwaiting for download\nNow start the upload\n\nMy development machine, a 2013 iMac is connected via USB to the USB-c port on my ESP32 Dev Module. Apparently the iMac's USB or ESP32 board's USB cannot keep up at the 921600 upload speed.\n",
"in my case buttons are new but not shorting properly as multimeter showed ..opened both scratched resoldered and all working\n",
"Just download the drivers x)\nCP210x: CP210x USB to UART Bridge VCP Drivers\nFTDI: FTDI Virtual COM Port Drivers\n"
] |
[
4,
2,
2,
1,
0,
0,
0,
0,
0,
-1
] |
[] |
[] |
[
"arduino",
"arduino_esp32",
"esp32",
"nodemcu"
] |
stackoverflow_0070532139_arduino_arduino_esp32_esp32_nodemcu.txt
|
Q:
Make API call for every item in a collection and return final results in list
I am trying to make an API call (getAccounts) that returns a list, then make a second list that by making a call(get for details of every object in that list (instead of just the first in the block below). How do I do that and then notify the observer when that series of calls is complete?
viewModelScope.launch {
gateway.getAccounts(
).fold(
onSuccess = { v ->
// fetch account details for first credit account in list
gateway.getCreditAccountDetails(v.first().accountId, v.first().accountIdType).fold(
onSuccess = { v -> addAccountToList(v)}
)
}
)
}
Coroutines functions:
suspend fun getAccounts(): Result<List<LOCAccountInfo>> {
return withContext(Dispatchers.IO) {
AccountServicing.getCreditAccounts(creditAuthClient)
}
}
suspend fun getCreditAccountDetails(accountId: AccountId, accountIdType: AccountIdType): Result<LOCAccount> {
return getCreditAccountDetails(accountId, accountIdType, creditAuthClient)
}
A:
Instead of fold you could use the function map to iterate over the original list and create a new list with the details. Then, you could just assign the result to the LiveData/StateFlow or whatever reactive object you are using there.
A:
What about applying map to the list, and using async function along with the awaitAll extension?
The async function will run the subtasks parallelly with concurrent coroutines. Finally, the awaitAll extension will wait till all coroutines are complete.
viewModelScope.launch {
gateway.getAccounts().map { account ->
println("Account -> $account")
async {
gateway.getCreditAccountDetails(
account.first().accountId,
account.first().accountIdType
).let { creditDetails ->
println("Credit Details -> $creditDetails")
}
}
}.awaitAll()
// Notify the View/Observer
println("All API execution is complete")
}
Notes: Instead of using the hardcoded Dispatchers.IO in your gateway, pass the dispatcher from the ViewModel or DI module. This is helpful if you plan to unit test and swap the IO dispatcher with the Main dispatcher.
|
Make API call for every item in a collection and return final results in list
|
I am trying to make an API call (getAccounts) that returns a list, then make a second list that by making a call(get for details of every object in that list (instead of just the first in the block below). How do I do that and then notify the observer when that series of calls is complete?
viewModelScope.launch {
gateway.getAccounts(
).fold(
onSuccess = { v ->
// fetch account details for first credit account in list
gateway.getCreditAccountDetails(v.first().accountId, v.first().accountIdType).fold(
onSuccess = { v -> addAccountToList(v)}
)
}
)
}
Coroutines functions:
suspend fun getAccounts(): Result<List<LOCAccountInfo>> {
return withContext(Dispatchers.IO) {
AccountServicing.getCreditAccounts(creditAuthClient)
}
}
suspend fun getCreditAccountDetails(accountId: AccountId, accountIdType: AccountIdType): Result<LOCAccount> {
return getCreditAccountDetails(accountId, accountIdType, creditAuthClient)
}
|
[
"Instead of fold you could use the function map to iterate over the original list and create a new list with the details. Then, you could just assign the result to the LiveData/StateFlow or whatever reactive object you are using there.\n",
"What about applying map to the list, and using async function along with the awaitAll extension?\nThe async function will run the subtasks parallelly with concurrent coroutines. Finally, the awaitAll extension will wait till all coroutines are complete.\nviewModelScope.launch {\n gateway.getAccounts().map { account ->\n println(\"Account -> $account\")\n\n async {\n gateway.getCreditAccountDetails(\n account.first().accountId,\n account.first().accountIdType\n ).let { creditDetails ->\n println(\"Credit Details -> $creditDetails\")\n }\n }\n }.awaitAll()\n\n // Notify the View/Observer\n println(\"All API execution is complete\")\n }\n\nNotes: Instead of using the hardcoded Dispatchers.IO in your gateway, pass the dispatcher from the ViewModel or DI module. This is helpful if you plan to unit test and swap the IO dispatcher with the Main dispatcher.\n"
] |
[
0,
0
] |
[] |
[] |
[
"android",
"kotlin_coroutines"
] |
stackoverflow_0074539633_android_kotlin_coroutines.txt
|
Q:
Oracle SYS_CONNECT_BY_PATH equivalent query into SQL Server
I'm trying to convert a complex query involving the Oracle SYS_CONNECT_BY_PATH syntax into SQL Server:
SELECT
DISTINCT TO_CHAR(CONCAT(@ROOT, SYS_CONNECT_BY_PATH(CONCAT('C_',X), '.'))) AS X_ALIAS
, TO_CHAR(CONCAT(@ROOT, PRIOR SYS_CONNECT_BY_PATH(CONCAT('C_',X), '.'))) AS X_ALIAS_FATHER
, TO_CHAR(X) AS X_ALIAS_LEAF
, LEVEL AS LVL
FROM MY_TABLE
LEFT JOIN MY_TABLE_BIS MY_TABLE_BIS_ALIAS ON MY_TABLE_BIS_ALIAS.MY_ID = COL_X
LEFT JOIN OTHER_TABLE
ON OTHER_TABLE.MY_ID = COL_X
CONNECT BY (PRIOR ID_SON = ID_FATHER)
AND LEVEL <= MAXDEPTH
START WITH ID_FATHER
IN (SELECT AN_ID AS ID_FATHER FROM BIG_TABLE)
Here is what I obtained using this website
WITH n(LEVEL, X_ALIAS, X_ALIAS_FATHER, X_ALIAS_LEAF) AS
( SELECT 1, CONCAT('C_',X), CONCAT('C_',X), CAST(X AS VARCHAR(30))
FROM MY_TABLE
LEFT JOIN MY_TABLE_BIS MY_TABLE_BIS_ALIAS
ON MY_TABLE_BIS_ALIAS.MY_ID = COL_X
LEFT JOIN OTHER_TABLE
ON OTHER_TABLE.MY_ID = COL_X
WHERE ID_FATHER IN (SELECT AN_ID AS ID_FATHER
FROM listAllCfaCfq)
UNION ALL
SELECT n.level + 1, n.X_ALIAS + '.' + nplus1.X_ALIAS, n.X_ALIAS_FATHER + '.' + nplus1.X_ALIAS_FATHER, CAST(X AS VARCHAR(30)
FROM MY_TABLE
LEFT JOIN MY_TABLE_BIS MY_TABLE_BIS_ALIAS
ON MY_TABLE_BIS_ALIAS.MY_ID = COL_X
LEFT JOIN OTHER_TABLE
ON OTHER_TABLE.MY_ID = COL_X AS nplus1, n
WHERE n.ID_SON = nplus1.ID_FATHER)
SELECT DISTINCT LEVEL, X_ALIAS, X_ALIAS_FATHER, X_ALIAS_LEAF
WHERE LEVEL <= @MAXDEPTH;
I changed the name of the tables and I could have done mistakes while doing so, don't hesitate to tell me about that in the comments
A:
All can be solved using several FUNCTIONs, and it is simple with some recursion, (note that max recursion level in T-SQL is 32)
Assuming we have the following table: (to a very small company)
TableName: Employees
id.....name..............manager_id
1 Big Boss NULL
2 Sales Manager 1
3 Support Manager 1
4 R&D Manager 1
5 Sales man 2
6 Support man 3
7 R&D Team leader 4
8 QA Team leader 4
9 C Developer 7
10 QA man 8
11 Java Developer 7
We just need a function to check if there is link between 2 ids, and another function to give the path from one to the other.
The first function is very simple using recursive :
Create Function dbo.Do_WE_Have_path(@id int, @boss_id int, @max_level int) returns int
Begin
declare @res int, @man int
set @res = 0
if @id = @boss_id
set @res = 1
else if @max_level > 0
Begin
Select @man=manager_id from Employees where id=@id
set @res = Do_WE_Have_path(@man, @boss_id, @max_level-1) --recursion
End
return res
End
Using the above Function we can select all entities with a connection shorter or equal to a specified level, so now we can write a method which build the path if it exists, note that a not exist path should be filter using the above method.
Create Function dbo.Make_The_path(@id int, @boss_id int, @max_level int) returns varchar(max)
Begin
declare @res varchar(max), @man int
select @res = name from Employees where id=@id
if max_level > 0 AND @id <> @boss_id
Begin
select @man = manager_id from Employees where id = @id
set @res = dbo.Make_The_path(@man, @boss_id, max_level-1) + '/' + @res
End
return @res
End
Now we can use both functions to get the path from the boss to the workers:
Select dbo.Make_The_path(id, 1, 3) Where Do_WE_Have_path(id, 1, 3)=1
Both Function can be merged to a one, and maybe you'll need to write it again for every structure, but the important thing is that it is possible.
A:
You probably want an recursive CTE for the heirarchial part, and then use FOR XML for the path building. FOR XML was intended to convert your results into XML, but you can use it to transform your results in to all kinds of interesting text formats.
FOR XML PATH clause in SQL Server
FOR XML (SQL Server) Microsoft Reference
A:
CREATE TABLE #MY_TABLE
(
ID INT
,ID_FATHER INT
,COL_X INT
)
CREATE TABLE #MY_TABLE_BIS
(
MY_ID INT
,X VARCHAR(50)
)
CREATE TABLE #OTHER_TABLE
(
MY_ID INT
,[ROOT] VARCHAR(50)
)
CREATE TABLE #BIG_TABLE
(
AN_ID INT
)
go
DECLARE @MAXDEPTH INT = 10
;WITH
cte_prepare
AS
(
SELECT
ID
,ID_FATHER
,TB.X
,OT.[ROOT]
FROM #MY_TABLE T
LEFT JOIN #MY_TABLE_BIS TB
ON TB.MY_ID = COL_X
LEFT JOIN #OTHER_TABLE OT
ON OT.MY_ID = COL_X
),
cte_connect (LVL, ID, X_ALIAS, X_ALIAS_FATHER, X_ALIAS_LEAF)
AS
(
SELECT 1
,T.ID
,CAST(CONCAT(T.[ROOT], '.C_', T.X) AS VARCHAR(MAX))
,CAST(CONCAT(T.[ROOT], '.') AS VARCHAR(MAX))
,CAST(T.X AS VARCHAR(30))
FROM cte_prepare T
WHERE T.ID_FATHER IN
(
SELECT AN_ID AS ID_FATHER
FROM #BIG_TABLE
)
UNION ALL
SELECT F.LVL + 1
,S.ID
,CAST(CONCAT(F.X_ALIAS, '.C_' + S.X) AS VARCHAR(MAX))
,CAST(F.X_ALIAS AS VARCHAR(MAX))
,CAST(S.X AS VARCHAR(30))
FROM cte_prepare S
INNER JOIN cte_connect F
ON S.ID_FATHER = F.ID
WHERE F.LVL < @MAXDEPTH
)
SELECT DISTINCT
CT.X_ALIAS
,CT.X_ALIAS_FATHER
,CT.X_ALIAS_LEAF
,CT.LVL
FROM cte_connect CT
-- Uncomment this and set depth when it's greater than 100.
--OPTION (MAXRECURSION 0) -- value between 0 and 32,767 (default is 100), 0 = unlimited
see also
https://learn.microsoft.com/en-us/sql/t-sql/queries/with-common-table-expression-transact-sql?view=sql-server-ver15
A:
It looks like there are a few issues with the SQL Server query you provided. Here are a few changes that you can make to fix it:
In the first SELECT statement of the CTE (common table expression),
you are trying to concatenate the value of the X column with the
string 'C_'. However, you have not specified which table the X
column belongs to. You need to include the table name before the X
column, like this:
SELECT 1, CONCAT('C_', MY_TABLE.X), CONCAT('C_', MY_TABLE.X), CAST(MY_TABLE.X AS VARCHAR(30))
In the second SELECT statement of the CTE, you are trying to
concatenate the X_ALIAS and X_ALIAS_FATHER values from the nplus1
table with the X_ALIAS and X_ALIAS_FATHER values from the n table,
respectively. However, you have not specified the table name before
these columns in the concatenation. You need to include the table
name before the column name, like this:
SELECT n.level + 1, n.X_ALIAS + '.' + nplus1.X_ALIAS, n.X_ALIAS_FATHER + '.' + nplus1.X_ALIAS_FATHER, CAST(X AS VARCHAR(30)
In the WHERE clause of the second SELECT statement of the CTE, you
are trying to compare the ID_SON column from the n table with the
ID_FATHER column from the nplus1 table. However, you have not
specified the table name before these columns in the comparison. You
need to include the table name before the column name, like this:
WHERE n.ID_SON = nplus1.ID_FATHER
In the final SELECT statement, you are trying to filter the result
by the LEVEL column. However, you have not specified the table name
before the LEVEL column in the WHERE clause. You need to include the
table name before the column name, like this:
SELECT DISTINCT LEVEL, X_ALIAS, X_ALIAS_FATHER, X_ALIAS_LEAF
WHERE n.LEVEL <= @MAXDEPTH;
Here is the updated query with these changes:
WITH n(LEVEL, X_ALIAS, X_ALIAS_FATHER, X_ALIAS_LEAF) AS
( SELECT 1, CONCAT('C_', MY_TABLE.X), CONCAT('C_', MY_TABLE.X), CAST(MY_TABLE.X AS VARCHAR(30))
FROM MY_TABLE
LEFT JOIN MY_TABLE_BIS MY_TABLE_BIS_ALIAS
ON MY_TABLE_BIS_ALIAS.MY_ID = COL_X
LEFT JOIN OTHER_TABLE
ON OTHER_TABLE.MY_ID = COL_X
WHERE ID_FATHER IN (SELECT AN_ID AS ID_FATHER
FROM listAllCfaCfq)
UNION ALL
SELECT n.level + 1, n.X_ALIAS + '.' + nplus1
|
Oracle SYS_CONNECT_BY_PATH equivalent query into SQL Server
|
I'm trying to convert a complex query involving the Oracle SYS_CONNECT_BY_PATH syntax into SQL Server:
SELECT
DISTINCT TO_CHAR(CONCAT(@ROOT, SYS_CONNECT_BY_PATH(CONCAT('C_',X), '.'))) AS X_ALIAS
, TO_CHAR(CONCAT(@ROOT, PRIOR SYS_CONNECT_BY_PATH(CONCAT('C_',X), '.'))) AS X_ALIAS_FATHER
, TO_CHAR(X) AS X_ALIAS_LEAF
, LEVEL AS LVL
FROM MY_TABLE
LEFT JOIN MY_TABLE_BIS MY_TABLE_BIS_ALIAS ON MY_TABLE_BIS_ALIAS.MY_ID = COL_X
LEFT JOIN OTHER_TABLE
ON OTHER_TABLE.MY_ID = COL_X
CONNECT BY (PRIOR ID_SON = ID_FATHER)
AND LEVEL <= MAXDEPTH
START WITH ID_FATHER
IN (SELECT AN_ID AS ID_FATHER FROM BIG_TABLE)
Here is what I obtained using this website
WITH n(LEVEL, X_ALIAS, X_ALIAS_FATHER, X_ALIAS_LEAF) AS
( SELECT 1, CONCAT('C_',X), CONCAT('C_',X), CAST(X AS VARCHAR(30))
FROM MY_TABLE
LEFT JOIN MY_TABLE_BIS MY_TABLE_BIS_ALIAS
ON MY_TABLE_BIS_ALIAS.MY_ID = COL_X
LEFT JOIN OTHER_TABLE
ON OTHER_TABLE.MY_ID = COL_X
WHERE ID_FATHER IN (SELECT AN_ID AS ID_FATHER
FROM listAllCfaCfq)
UNION ALL
SELECT n.level + 1, n.X_ALIAS + '.' + nplus1.X_ALIAS, n.X_ALIAS_FATHER + '.' + nplus1.X_ALIAS_FATHER, CAST(X AS VARCHAR(30)
FROM MY_TABLE
LEFT JOIN MY_TABLE_BIS MY_TABLE_BIS_ALIAS
ON MY_TABLE_BIS_ALIAS.MY_ID = COL_X
LEFT JOIN OTHER_TABLE
ON OTHER_TABLE.MY_ID = COL_X AS nplus1, n
WHERE n.ID_SON = nplus1.ID_FATHER)
SELECT DISTINCT LEVEL, X_ALIAS, X_ALIAS_FATHER, X_ALIAS_LEAF
WHERE LEVEL <= @MAXDEPTH;
I changed the name of the tables and I could have done mistakes while doing so, don't hesitate to tell me about that in the comments
|
[
"All can be solved using several FUNCTIONs, and it is simple with some recursion, (note that max recursion level in T-SQL is 32)\nAssuming we have the following table: (to a very small company)\nTableName: Employees\nid.....name..............manager_id\n1 Big Boss NULL\n2 Sales Manager 1\n3 Support Manager 1\n4 R&D Manager 1 \n5 Sales man 2\n6 Support man 3\n7 R&D Team leader 4\n8 QA Team leader 4\n9 C Developer 7\n10 QA man 8\n11 Java Developer 7 \n\nWe just need a function to check if there is link between 2 ids, and another function to give the path from one to the other.\nThe first function is very simple using recursive :\nCreate Function dbo.Do_WE_Have_path(@id int, @boss_id int, @max_level int) returns int\nBegin\n declare @res int, @man int\n set @res = 0\n if @id = @boss_id \n set @res = 1\n else if @max_level > 0 \n Begin\n Select @man=manager_id from Employees where id=@id\n set @res = Do_WE_Have_path(@man, @boss_id, @max_level-1) --recursion\n End\n return res \nEnd\n\nUsing the above Function we can select all entities with a connection shorter or equal to a specified level, so now we can write a method which build the path if it exists, note that a not exist path should be filter using the above method.\nCreate Function dbo.Make_The_path(@id int, @boss_id int, @max_level int) returns varchar(max)\nBegin\n declare @res varchar(max), @man int\n select @res = name from Employees where id=@id\n if max_level > 0 AND @id <> @boss_id\n Begin \n select @man = manager_id from Employees where id = @id\n set @res = dbo.Make_The_path(@man, @boss_id, max_level-1) + '/' + @res\n End\n return @res\nEnd\n\nNow we can use both functions to get the path from the boss to the workers:\nSelect dbo.Make_The_path(id, 1, 3) Where Do_WE_Have_path(id, 1, 3)=1 \n\nBoth Function can be merged to a one, and maybe you'll need to write it again for every structure, but the important thing is that it is possible. \n",
"You probably want an recursive CTE for the heirarchial part, and then use FOR XML for the path building. FOR XML was intended to convert your results into XML, but you can use it to transform your results in to all kinds of interesting text formats.\nFOR XML PATH clause in SQL Server\nFOR XML (SQL Server) Microsoft Reference\n",
"CREATE TABLE #MY_TABLE\n(\n ID INT\n ,ID_FATHER INT\n ,COL_X INT\n)\n\nCREATE TABLE #MY_TABLE_BIS\n(\n MY_ID INT\n ,X VARCHAR(50)\n)\n\nCREATE TABLE #OTHER_TABLE\n(\n MY_ID INT\n ,[ROOT] VARCHAR(50)\n)\n\nCREATE TABLE #BIG_TABLE\n(\n AN_ID INT\n)\ngo\n\nDECLARE @MAXDEPTH INT = 10\n\n;WITH\n cte_prepare\n AS\n (\n SELECT\n ID\n ,ID_FATHER\n ,TB.X\n ,OT.[ROOT]\n FROM #MY_TABLE T\n LEFT JOIN #MY_TABLE_BIS TB\n ON TB.MY_ID = COL_X\n LEFT JOIN #OTHER_TABLE OT\n ON OT.MY_ID = COL_X\n ),\n cte_connect (LVL, ID, X_ALIAS, X_ALIAS_FATHER, X_ALIAS_LEAF)\n AS\n (\n SELECT 1\n ,T.ID\n ,CAST(CONCAT(T.[ROOT], '.C_', T.X) AS VARCHAR(MAX))\n ,CAST(CONCAT(T.[ROOT], '.') AS VARCHAR(MAX))\n ,CAST(T.X AS VARCHAR(30))\n FROM cte_prepare T\n WHERE T.ID_FATHER IN\n (\n SELECT AN_ID AS ID_FATHER\n FROM #BIG_TABLE\n )\n\n UNION ALL\n\n SELECT F.LVL + 1\n ,S.ID\n ,CAST(CONCAT(F.X_ALIAS, '.C_' + S.X) AS VARCHAR(MAX))\n ,CAST(F.X_ALIAS AS VARCHAR(MAX))\n ,CAST(S.X AS VARCHAR(30))\n FROM cte_prepare S\n INNER JOIN cte_connect F\n ON S.ID_FATHER = F.ID\n WHERE F.LVL < @MAXDEPTH\n )\nSELECT DISTINCT\n CT.X_ALIAS\n ,CT.X_ALIAS_FATHER\n ,CT.X_ALIAS_LEAF\n ,CT.LVL\nFROM cte_connect CT\n-- Uncomment this and set depth when it's greater than 100.\n--OPTION (MAXRECURSION 0) -- value between 0 and 32,767 (default is 100), 0 = unlimited\n\nsee also\nhttps://learn.microsoft.com/en-us/sql/t-sql/queries/with-common-table-expression-transact-sql?view=sql-server-ver15\n",
"It looks like there are a few issues with the SQL Server query you provided. Here are a few changes that you can make to fix it:\n\nIn the first SELECT statement of the CTE (common table expression),\nyou are trying to concatenate the value of the X column with the\nstring 'C_'. However, you have not specified which table the X\ncolumn belongs to. You need to include the table name before the X\ncolumn, like this:\nSELECT 1, CONCAT('C_', MY_TABLE.X), CONCAT('C_', MY_TABLE.X), CAST(MY_TABLE.X AS VARCHAR(30))\n\nIn the second SELECT statement of the CTE, you are trying to\nconcatenate the X_ALIAS and X_ALIAS_FATHER values from the nplus1\ntable with the X_ALIAS and X_ALIAS_FATHER values from the n table,\nrespectively. However, you have not specified the table name before\nthese columns in the concatenation. You need to include the table\nname before the column name, like this:\nSELECT n.level + 1, n.X_ALIAS + '.' + nplus1.X_ALIAS, n.X_ALIAS_FATHER + '.' + nplus1.X_ALIAS_FATHER, CAST(X AS VARCHAR(30)\n\nIn the WHERE clause of the second SELECT statement of the CTE, you\nare trying to compare the ID_SON column from the n table with the\nID_FATHER column from the nplus1 table. However, you have not\nspecified the table name before these columns in the comparison. You\nneed to include the table name before the column name, like this:\nWHERE n.ID_SON = nplus1.ID_FATHER\n\nIn the final SELECT statement, you are trying to filter the result\nby the LEVEL column. However, you have not specified the table name\nbefore the LEVEL column in the WHERE clause. You need to include the\ntable name before the column name, like this:\nSELECT DISTINCT LEVEL, X_ALIAS, X_ALIAS_FATHER, X_ALIAS_LEAF\nWHERE n.LEVEL <= @MAXDEPTH;\n\n\nHere is the updated query with these changes:\nWITH n(LEVEL, X_ALIAS, X_ALIAS_FATHER, X_ALIAS_LEAF) AS\n ( SELECT 1, CONCAT('C_', MY_TABLE.X), CONCAT('C_', MY_TABLE.X), CAST(MY_TABLE.X AS VARCHAR(30))\n FROM MY_TABLE\n LEFT JOIN MY_TABLE_BIS MY_TABLE_BIS_ALIAS \n ON MY_TABLE_BIS_ALIAS.MY_ID = COL_X\n LEFT JOIN OTHER_TABLE \n ON OTHER_TABLE.MY_ID = COL_X\n WHERE ID_FATHER IN (SELECT AN_ID AS ID_FATHER \n FROM listAllCfaCfq)\n UNION ALL\n SELECT n.level + 1, n.X_ALIAS + '.' + nplus1\n\n"
] |
[
0,
0,
0,
0
] |
[] |
[] |
[
"hierarchical_data",
"recursive_query",
"sql_server",
"tsql"
] |
stackoverflow_0043872295_hierarchical_data_recursive_query_sql_server_tsql.txt
|
Q:
how to call a parent member function in the overriding function?
just asking what can I put instead of super.draw() to call the parent class function within the overriding function?
class base {
void draw() {
}
}
class derived {
void draw() {
super.draw();
}
}
I know that for constructors the base constructor is automatically called at the derived constructor, I want basically the same thing for other methods. thanks
A:
First dervied needs to derived from base so that you can access its methods. Qualifying the call with base:: will make the compiler look for the base class:
class derived : public base {
void draw() {
base::draw();
}
};
|
how to call a parent member function in the overriding function?
|
just asking what can I put instead of super.draw() to call the parent class function within the overriding function?
class base {
void draw() {
}
}
class derived {
void draw() {
super.draw();
}
}
I know that for constructors the base constructor is automatically called at the derived constructor, I want basically the same thing for other methods. thanks
|
[
"First dervied needs to derived from base so that you can access its methods. Qualifying the call with base:: will make the compiler look for the base class:\nclass derived : public base {\n void draw() {\n base::draw();\n }\n};\n\n"
] |
[
1
] |
[] |
[] |
[
"c++"
] |
stackoverflow_0074669959_c++.txt
|
Q:
How to change on hover background color in pickerInput?
I need to change the background color with which the pickerInput highlights the on hover option.
How can I achieve it?.
Below is a minimal example, I have tried changing the style but I can't get it
library(shiny)
shinyApp(
ui = basicPage(
pickerInput("state", "State", split(state.name, state.division),
choicesOpt = list(style = rep(("hover {background: blue; color: black; font-weight: bold}"),100)))
),
server = function(input, output) {}
)
As you can see in the example, the background of the on hover option is light gray and not blue.
A:
use the style parameter within the choicesOpt list.
easily can be done by css though.
pickerInput("state", "State", split(state.name, state.division),
choicesOpt = list(
style = rep(
":hover {background: blue; color: black; font-weight: bold}",
100
)
)
)
|
How to change on hover background color in pickerInput?
|
I need to change the background color with which the pickerInput highlights the on hover option.
How can I achieve it?.
Below is a minimal example, I have tried changing the style but I can't get it
library(shiny)
shinyApp(
ui = basicPage(
pickerInput("state", "State", split(state.name, state.division),
choicesOpt = list(style = rep(("hover {background: blue; color: black; font-weight: bold}"),100)))
),
server = function(input, output) {}
)
As you can see in the example, the background of the on hover option is light gray and not blue.
|
[
"use the style parameter within the choicesOpt list.\neasily can be done by css though.\npickerInput(\"state\", \"State\", split(state.name, state.division),\n choicesOpt = list(\n style = rep(\n \":hover {background: blue; color: black; font-weight: bold}\",\n 100\n )\n )\n)\n\n"
] |
[
0
] |
[] |
[] |
[
"hover",
"pickerinput"
] |
stackoverflow_0074669962_hover_pickerinput.txt
|
Q:
Is there PHP shorthand for testing variable value for multiple conditions without using in_array?
I find myself doing this a lot, and I assume there is a short hand way to make this faster. Yet in my research about shorthand and ternary operations, I can't quite seem to wrap my head around how to do it.
// below variable only be impactful if it's SET, not Null, and === important value.
$verbose_instructively_named_variable = $other_variable. "_modifier";
if(isset($verbose_instructively_named_variable) && $verbose_instructively_named_variable !== null && $verbose_instructively_named_variable === "key_text_modifier"):
// Now do important thing here;
endif;
I am a beginning programmer obviously, but find myself attracted to longer variable names so when I revisit things later it flows linearly for me. So I find myself wanting to do the below all the time, and am frustrated I can't.
if(isset($verbose_instructively_named_variable) && !==null && === "key_text_modifier"):
// Now do important stuff;
endif;
I know this is a PHP question, but I find myself wanting this form of chained logic in javascript also. Am I missing a basic step of some kind?
Is there an altogether different way to test ONE variable for multiple conditions quickly and efficiently?
I have tried combinations of things found in similar questions. Like the in_array solution provided in this answer: In PHP, is there a short way to compare a variable to multiple values?
As well as things like the below standard shortcut/shorthand.
$result = $initial ?: 'default';
But what I want often is something more like this.
$result = ($initial !==null && !=="bad" && !in_array($initial,$record_set_from_mysql_query) ? $initial : 'default');
And keep in mind the main reason I don't like and don't want to do this:
$result = ($initial !==null && $initial !=="bad" $initial !=="even_worse" ? $initial : 'default');
Is because "$initial" maybe named something like $always_make_this_value_green_when_blue_present or something otherwise cumbersome to type repeatedly and it makes the code hard to read later with multi-line parameters in the functions etc.
Presently my best work around for this is to do this.
$a = $long_verbose_instructively_named_variable;
$result = $a !== null && $a !== "bad" && $a !== "even_worse" ? $a : 'default';
But this means in a function with a half dozen little small if/else checks I end up with a, aa, aaa, a_4, a_5 variables all over the place and it just gets cumbersome.
A:
I will still recommend you use in_array at this point. When the array is not big enough, the speed of in_array is still good enough. Because your code will be more easier to read.
As Markus Zeller commented, you can also use a match() method at this condition, you can read from here.
PHP also support array key with characters, it's mean you can use isset() method for your problem, you can read on here.
A tips, you may read PSR-1.
A:
There's a tradeoff between legible code that may be more verbose, and clever code that is shorter but harder to understand. That being said, this is a bit of a kludge but seems to achieve your goal of only referencing $long_verbose_instructively_named_variable once:
switch ($result = ($long_verbose_instructively_named_variable ?? 'default')) {
//case NULL:
case 'bad':
case 'even_worse':
$result = 'default';
}
The results for various test cases:
For [unset] got 'default'
For false got false
For NULL got 'default'
For 'bad' got 'default'
For 'even_worse' got 'default'
For 'foo' got 'foo'
How I generated these test cases:
$test_cases = [ FALSE, NULL, 'bad', 'even_worse', 'foo' ];
for ( $i=-1; $i < sizeof($test_cases); $i++ ) {
if ( -1 == $i ) {
unset($long_verbose_instructively_named_variable);
} else {
$long_verbose_instructively_named_variable = $test_cases[$i];
}
echo "For " . ( (-1 == $i ) ? '[unset]' : var_export($long_verbose_instructively_named_variable, TRUE) );
switch ($result = ($long_verbose_instructively_named_variable ?? 'default')) {
//case NULL:
case 'bad':
case 'even_worse':
$result = 'default';
}
echo " got " . var_export($result, TRUE) . "\n";
}
|
Is there PHP shorthand for testing variable value for multiple conditions without using in_array?
|
I find myself doing this a lot, and I assume there is a short hand way to make this faster. Yet in my research about shorthand and ternary operations, I can't quite seem to wrap my head around how to do it.
// below variable only be impactful if it's SET, not Null, and === important value.
$verbose_instructively_named_variable = $other_variable. "_modifier";
if(isset($verbose_instructively_named_variable) && $verbose_instructively_named_variable !== null && $verbose_instructively_named_variable === "key_text_modifier"):
// Now do important thing here;
endif;
I am a beginning programmer obviously, but find myself attracted to longer variable names so when I revisit things later it flows linearly for me. So I find myself wanting to do the below all the time, and am frustrated I can't.
if(isset($verbose_instructively_named_variable) && !==null && === "key_text_modifier"):
// Now do important stuff;
endif;
I know this is a PHP question, but I find myself wanting this form of chained logic in javascript also. Am I missing a basic step of some kind?
Is there an altogether different way to test ONE variable for multiple conditions quickly and efficiently?
I have tried combinations of things found in similar questions. Like the in_array solution provided in this answer: In PHP, is there a short way to compare a variable to multiple values?
As well as things like the below standard shortcut/shorthand.
$result = $initial ?: 'default';
But what I want often is something more like this.
$result = ($initial !==null && !=="bad" && !in_array($initial,$record_set_from_mysql_query) ? $initial : 'default');
And keep in mind the main reason I don't like and don't want to do this:
$result = ($initial !==null && $initial !=="bad" $initial !=="even_worse" ? $initial : 'default');
Is because "$initial" maybe named something like $always_make_this_value_green_when_blue_present or something otherwise cumbersome to type repeatedly and it makes the code hard to read later with multi-line parameters in the functions etc.
Presently my best work around for this is to do this.
$a = $long_verbose_instructively_named_variable;
$result = $a !== null && $a !== "bad" && $a !== "even_worse" ? $a : 'default';
But this means in a function with a half dozen little small if/else checks I end up with a, aa, aaa, a_4, a_5 variables all over the place and it just gets cumbersome.
|
[
"I will still recommend you use in_array at this point. When the array is not big enough, the speed of in_array is still good enough. Because your code will be more easier to read.\nAs Markus Zeller commented, you can also use a match() method at this condition, you can read from here.\nPHP also support array key with characters, it's mean you can use isset() method for your problem, you can read on here.\nA tips, you may read PSR-1.\n",
"There's a tradeoff between legible code that may be more verbose, and clever code that is shorter but harder to understand. That being said, this is a bit of a kludge but seems to achieve your goal of only referencing $long_verbose_instructively_named_variable once:\nswitch ($result = ($long_verbose_instructively_named_variable ?? 'default')) {\n //case NULL:\n case 'bad':\n case 'even_worse':\n $result = 'default';\n}\n\nThe results for various test cases:\nFor [unset] got 'default'\nFor false got false\nFor NULL got 'default'\nFor 'bad' got 'default'\nFor 'even_worse' got 'default'\nFor 'foo' got 'foo'\n\nHow I generated these test cases:\n$test_cases = [ FALSE, NULL, 'bad', 'even_worse', 'foo' ];\n\nfor ( $i=-1; $i < sizeof($test_cases); $i++ ) {\n if ( -1 == $i ) {\n unset($long_verbose_instructively_named_variable);\n } else {\n $long_verbose_instructively_named_variable = $test_cases[$i];\n }\n\n echo \"For \" . ( (-1 == $i ) ? '[unset]' : var_export($long_verbose_instructively_named_variable, TRUE) );\n\n switch ($result = ($long_verbose_instructively_named_variable ?? 'default')) {\n //case NULL:\n case 'bad':\n case 'even_worse':\n $result = 'default';\n }\n\n echo \" got \" . var_export($result, TRUE) . \"\\n\";\n}\n\n"
] |
[
0,
0
] |
[] |
[] |
[
"php",
"shorthand",
"ternary"
] |
stackoverflow_0074667887_php_shorthand_ternary.txt
|
Q:
Qt5 VideoOverview example won't work
I am stucked for a month with video example given in Qt Video Overview.
I tried that code, but only I get is blank square (QWidget). I am using GStreamer0.10 for media playback over Qt5. I also played video with gst-launch-0.10 command and it works okay, but I cannot determine what's happening in Qt and why it won't work?
I looked in error log of X Server, located in /etc/X11/Xorg.0.log, and when I use fbdev as a display driver configured in /etc/X11/xorg.conf it shows me the error:
"FBDEV(0): FBIOPUTCMAP: Invalid argument"
when I use modesetting driver everything acts the same but no errors. I figured out that when I delete xorg.conf file and start X server again, video works but with lack of colors and with flickering also example works well on my Ubuntu VM and via vnc client. Every advice and help will be appreciated.
Target machine: BeagleBone Black
Distribution: Debian Jessie 8.2
Kernel Version: 4.1.15-ti-rt-r43
List of available drivers in /usr/lib/xorg/modules/drivers: ati_drv.so, mach64_drv.so, nouveau_drv.so, r128_drv.so, vesa_drv.so, fbdev_drv.so, modesetting_drv.so, omap_drv.so, radeon_drv.so
Here is a full error log from Xorg when I try to launch my Qt application on BeagleBone Black under Debian Jessie 8.2 -> http://pastebin.com/4x8KztBk
xorg.conf file from /etc/X11 -> http://pastebin.com/4WhX8pJc
A:
Based on the information you provided, it looks like the issue may be with the fbdev driver that you are using for the display. The error "FBDEV(0): FBIOPUTCMAP: Invalid argument" indicates that there may be a problem with the color palette being used by the driver.
One potential solution would be to try using a different display driver, such as the modesetting driver, which is known to work well with GStreamer. You can specify the display driver to use by modifying the "Driver" field in the "Screen" section of your xorg.conf file.
Alternatively, you can try removing the xorg.conf file and allowing the X server to use the default settings. This may resolve the issue with the fbdev driver and allow your Qt application to work properly.
If the issue persists, it may be worth checking the GStreamer debug logs to see if there are any other error messages that may provide more insight into the problem. You can enable GStreamer debug logging by setting the GST_DEBUG environment variable. For example:
export GST_DEBUG=3
This will enable verbose debugging output from GStreamer, which you can then view in the terminal where your application is running. This may help identify any issues with the GStreamer pipeline that is being used for video playback.
|
Qt5 VideoOverview example won't work
|
I am stucked for a month with video example given in Qt Video Overview.
I tried that code, but only I get is blank square (QWidget). I am using GStreamer0.10 for media playback over Qt5. I also played video with gst-launch-0.10 command and it works okay, but I cannot determine what's happening in Qt and why it won't work?
I looked in error log of X Server, located in /etc/X11/Xorg.0.log, and when I use fbdev as a display driver configured in /etc/X11/xorg.conf it shows me the error:
"FBDEV(0): FBIOPUTCMAP: Invalid argument"
when I use modesetting driver everything acts the same but no errors. I figured out that when I delete xorg.conf file and start X server again, video works but with lack of colors and with flickering also example works well on my Ubuntu VM and via vnc client. Every advice and help will be appreciated.
Target machine: BeagleBone Black
Distribution: Debian Jessie 8.2
Kernel Version: 4.1.15-ti-rt-r43
List of available drivers in /usr/lib/xorg/modules/drivers: ati_drv.so, mach64_drv.so, nouveau_drv.so, r128_drv.so, vesa_drv.so, fbdev_drv.so, modesetting_drv.so, omap_drv.so, radeon_drv.so
Here is a full error log from Xorg when I try to launch my Qt application on BeagleBone Black under Debian Jessie 8.2 -> http://pastebin.com/4x8KztBk
xorg.conf file from /etc/X11 -> http://pastebin.com/4WhX8pJc
|
[
"Based on the information you provided, it looks like the issue may be with the fbdev driver that you are using for the display. The error \"FBDEV(0): FBIOPUTCMAP: Invalid argument\" indicates that there may be a problem with the color palette being used by the driver.\nOne potential solution would be to try using a different display driver, such as the modesetting driver, which is known to work well with GStreamer. You can specify the display driver to use by modifying the \"Driver\" field in the \"Screen\" section of your xorg.conf file.\nAlternatively, you can try removing the xorg.conf file and allowing the X server to use the default settings. This may resolve the issue with the fbdev driver and allow your Qt application to work properly.\nIf the issue persists, it may be worth checking the GStreamer debug logs to see if there are any other error messages that may provide more insight into the problem. You can enable GStreamer debug logging by setting the GST_DEBUG environment variable. For example:\nexport GST_DEBUG=3\n\nThis will enable verbose debugging output from GStreamer, which you can then view in the terminal where your application is running. This may help identify any issues with the GStreamer pipeline that is being used for video playback.\n"
] |
[
0
] |
[] |
[] |
[
"beagleboneblack",
"gstreamer",
"linux",
"qt5",
"qtmultimedia"
] |
stackoverflow_0035983985_beagleboneblack_gstreamer_linux_qt5_qtmultimedia.txt
|
Q:
How to make a scrollable table with fixed header using angular and ionic
I am trying to create an scrollable table horizontal and vertical scroll bars with fixed headers using ionic grid.
i am able to achieve the scroll part but not able to make the headers fixed.
HTML:
<ion-content class="{{selectedTheme}} inventory-content">
<div class="{{selectedTheme}} reports-table">
<ion-grid>
<ion-row nowrap class="headers">
<ion-col size="5" class="single-border">
Name
</ion-col>
<ion-col size="2" class="single-border">
Model
</ion-col>
<ion-col size="3" class="single-border">
Make
</ion-col>
<ion-col size="3" class="single-border">
Year
</ion-col>
</ion-row>
<ion-row nowrap class="content" *ngFor="let inventory of sortedInventoryList">
<ion-col size="5"> {{ inventory.Name }} </ion-col>
<ion-col size="2"> {{ inventory.Model }} </ion-col>
<ion-col size="3"> {{ inventory.Make }} </ion-col>
<ion-col size="3"> {{ inventory.Year }} </ion-col>
</ion-row>
</ion-grid>
</div>
</ion-content>
CSS:
.reports-table {
overflow-x: auto;
}
.inventory-content {
background-color: #f0f1f2;
}
.headers {
color: #454f63;
font-family: "Open Sans";
font-weight: bold;
font-size: 14px;
margin-top: 10px;
word-wrap: break-word;
}
.border,
.single-border {
border-bottom: 2px solid #989898;
}
.single-border {
padding-top: 12px;
}
.content {
color: #454f63;
font-family: "Open Sans";
font-size: 10px;
}
A:
It is late.. but it is use for some one else.. below code works fine for me
Change ur herader css to
.headers {
color: #454f63;
font-family: "Open Sans";
font-weight: bold;
font-size: 14px;
margin-top: 10px;
word-wrap: break-word;
background-color: #f0f1f2;;
// Fixed Header
position: sticky;
top: 0;
left: 0;
right: 0;
z-index: 9999;
}
A:
Adding to Ajt's answer, I also had to remove the .reports-table css. Otherwise, the header row scrolled with the rest of the grid.
|
How to make a scrollable table with fixed header using angular and ionic
|
I am trying to create an scrollable table horizontal and vertical scroll bars with fixed headers using ionic grid.
i am able to achieve the scroll part but not able to make the headers fixed.
HTML:
<ion-content class="{{selectedTheme}} inventory-content">
<div class="{{selectedTheme}} reports-table">
<ion-grid>
<ion-row nowrap class="headers">
<ion-col size="5" class="single-border">
Name
</ion-col>
<ion-col size="2" class="single-border">
Model
</ion-col>
<ion-col size="3" class="single-border">
Make
</ion-col>
<ion-col size="3" class="single-border">
Year
</ion-col>
</ion-row>
<ion-row nowrap class="content" *ngFor="let inventory of sortedInventoryList">
<ion-col size="5"> {{ inventory.Name }} </ion-col>
<ion-col size="2"> {{ inventory.Model }} </ion-col>
<ion-col size="3"> {{ inventory.Make }} </ion-col>
<ion-col size="3"> {{ inventory.Year }} </ion-col>
</ion-row>
</ion-grid>
</div>
</ion-content>
CSS:
.reports-table {
overflow-x: auto;
}
.inventory-content {
background-color: #f0f1f2;
}
.headers {
color: #454f63;
font-family: "Open Sans";
font-weight: bold;
font-size: 14px;
margin-top: 10px;
word-wrap: break-word;
}
.border,
.single-border {
border-bottom: 2px solid #989898;
}
.single-border {
padding-top: 12px;
}
.content {
color: #454f63;
font-family: "Open Sans";
font-size: 10px;
}
|
[
"It is late.. but it is use for some one else.. below code works fine for me\nChange ur herader css to\n .headers {\n color: #454f63;\n font-family: \"Open Sans\";\n font-weight: bold;\n font-size: 14px;\n margin-top: 10px;\n word-wrap: break-word;\n background-color: #f0f1f2;;\n \n // Fixed Header\n position: sticky;\n top: 0;\n left: 0;\n right: 0;\n z-index: 9999;\n }\n\n",
"Adding to Ajt's answer, I also had to remove the .reports-table css. Otherwise, the header row scrolled with the rest of the grid.\n"
] |
[
1,
0
] |
[] |
[] |
[
"angular",
"css",
"html",
"ionic4",
"ionic_framework"
] |
stackoverflow_0058914595_angular_css_html_ionic4_ionic_framework.txt
|
Q:
How to disable scrolling in LazyColumn and Column
I want to disable scrolling in my LazyColumn or Column.
Modifier.scrollable(state = rememberScrollState(), enabled = false, orientation = Orientation.Vertical)
or
Modifier.verticalScroll(...)
doesnt work.
Here is my Code:
Column(
modifier = Modifier
.fillMaxSize()
) {
Box(
modifier = Modifier
.padding(15.dp)
.height(60.dp)
.clip(RoundedCornerShape(30))
) {
TitleSection(text = stringResource(id = R.string...))
}
LazyColumn(
contentPadding = PaddingValues(start = 7.5.dp, end = 7.5.dp, bottom = 100.dp),
modifier = Modifier
.fillMaxHeight()
) {
items(categoryItemContents.size) { items ->
CategoryItem(categoryItemContents[items], navController = navController)
}
}
}
A:
A simple approach is to place the LazyColumn inside a Box that contains another Box. The nested Box can be composed to intercept scrolling, thus preventing the LazyColumn from receiving any scrolling events. To enable scrolling, just prevent the nested Box from being added. As for disabling scrolling in a Column, that is the default. Columns by default don't have scrolling:
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
startActivity(intent)
setContent {
var scrollingEnabled by remember { mutableStateOf(true) }
Column() {
Row(verticalAlignment = Alignment.CenterVertically) {
Text("Scrolling Enabled")
Switch(
checked = scrollingEnabled,
onCheckedChange = { scrollingEnabled = it }
)
}
Box(modifier = Modifier.fillMaxSize()) {
LazyColumn(Modifier.fillMaxWidth(), state = rememberLazyListState()) {
items((1..100).toList()) {
Text("$it")
}
}
if (!scrollingEnabled) {
Box(modifier = Modifier.fillMaxSize().verticalScroll(rememberScrollState())) {}
}
}
}
}
}
}
A:
With the LazyColumn you can use the userScrollEnabled parameter to disable the scrolling.
LazyColumn(
state = state,
userScrollEnabled = false
){
//items
}
Note that you can still scroll programmatically using the state even when it is disabled.
|
How to disable scrolling in LazyColumn and Column
|
I want to disable scrolling in my LazyColumn or Column.
Modifier.scrollable(state = rememberScrollState(), enabled = false, orientation = Orientation.Vertical)
or
Modifier.verticalScroll(...)
doesnt work.
Here is my Code:
Column(
modifier = Modifier
.fillMaxSize()
) {
Box(
modifier = Modifier
.padding(15.dp)
.height(60.dp)
.clip(RoundedCornerShape(30))
) {
TitleSection(text = stringResource(id = R.string...))
}
LazyColumn(
contentPadding = PaddingValues(start = 7.5.dp, end = 7.5.dp, bottom = 100.dp),
modifier = Modifier
.fillMaxHeight()
) {
items(categoryItemContents.size) { items ->
CategoryItem(categoryItemContents[items], navController = navController)
}
}
}
|
[
"A simple approach is to place the LazyColumn inside a Box that contains another Box. The nested Box can be composed to intercept scrolling, thus preventing the LazyColumn from receiving any scrolling events. To enable scrolling, just prevent the nested Box from being added. As for disabling scrolling in a Column, that is the default. Columns by default don't have scrolling:\nclass MainActivity : ComponentActivity() {\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n\n startActivity(intent)\n\n setContent {\n var scrollingEnabled by remember { mutableStateOf(true) }\n\n Column() {\n Row(verticalAlignment = Alignment.CenterVertically) {\n Text(\"Scrolling Enabled\")\n\n Switch(\n checked = scrollingEnabled,\n onCheckedChange = { scrollingEnabled = it }\n )\n }\n\n Box(modifier = Modifier.fillMaxSize()) {\n LazyColumn(Modifier.fillMaxWidth(), state = rememberLazyListState()) {\n items((1..100).toList()) {\n Text(\"$it\")\n }\n }\n\n if (!scrollingEnabled) {\n Box(modifier = Modifier.fillMaxSize().verticalScroll(rememberScrollState())) {}\n }\n }\n }\n }\n }\n}\n\n\n",
"With the LazyColumn you can use the userScrollEnabled parameter to disable the scrolling.\nLazyColumn(\n state = state,\n userScrollEnabled = false\n){\n //items\n}\n\nNote that you can still scroll programmatically using the state even when it is disabled.\n"
] |
[
0,
0
] |
[] |
[] |
[
"android",
"android_jetpack",
"android_jetpack_compose",
"kotlin",
"lazycolumn"
] |
stackoverflow_0070306710_android_android_jetpack_android_jetpack_compose_kotlin_lazycolumn.txt
|
Q:
Attempting to install Stable Diffusion via Python
I've trawled through stack overflow, several youtube videos and can't for the life of me work this out.
I've unpackaged and pulled from git, all files are where they need to be as far as the installation for Stable Diffusion goes - but when I go to run I get two errors, one being the pip version. I upgraded via 'pip install --upgrade pip' and though the version updated, I'm still getting the below error.
The other issue is that pytorch doesn't seem to have installed. I've added it to the requirements.txt and run 'pip install -r requirements.txt' which doesn't seem to work either. I also downloaded 1.12.1+cu113 and ran pip install "path/" and received the error "ERROR: torch-1.12.1+cu113-cp39-cp39-win_amd64.whl is not a supported wheel on this platform."
Error received below:
stderr: ERROR: Could not find a version that satisfies the requirement torch==1.12.1+cu113 (from versions: none)
ERROR: No matching distribution found for torch==1.12.1+cu113
WARNING: You are using pip version 20.1.1; however, version 22.3 is available.
You should consider upgrading via the 'C:\Users\XXX\Downloads\STABLE\stable-diffusion-webui\venv\Scripts\python.exe -m pip install --upgrade pip' command.
Any help would be greatly appreciated, I've tried my best to be self-sufficient so I'm putting it to the people who may know how to help.
A:
One of the easiest methods to install SD is with Automatic1111
https://github.com/AUTOMATIC1111/stable-diffusion-webui
Instructions on this page in a section titled "Automatic Installation on Windows" (since you're using windows paths in your post)
Install Python 3.10.6, checking "Add Python to PATH" Install git.
Download the stable-diffusion-webui repository, for example by running git clonehttps://github.com/AUTOMATIC1111/stable-diffusion-webui.git.
Place model.ckpt in the models directory (see dependencies for where to
get it).
(Optional) Place GFPGANv1.4.pth in the base directory,
alongside webui.py (see dependencies for where to get it).
Run webui-user.bat from Windows Explorer as normal, non-administrator,
user.
This is much easier and improved from the early days of Automatic and Stable Diffusion itself.
|
Attempting to install Stable Diffusion via Python
|
I've trawled through stack overflow, several youtube videos and can't for the life of me work this out.
I've unpackaged and pulled from git, all files are where they need to be as far as the installation for Stable Diffusion goes - but when I go to run I get two errors, one being the pip version. I upgraded via 'pip install --upgrade pip' and though the version updated, I'm still getting the below error.
The other issue is that pytorch doesn't seem to have installed. I've added it to the requirements.txt and run 'pip install -r requirements.txt' which doesn't seem to work either. I also downloaded 1.12.1+cu113 and ran pip install "path/" and received the error "ERROR: torch-1.12.1+cu113-cp39-cp39-win_amd64.whl is not a supported wheel on this platform."
Error received below:
stderr: ERROR: Could not find a version that satisfies the requirement torch==1.12.1+cu113 (from versions: none)
ERROR: No matching distribution found for torch==1.12.1+cu113
WARNING: You are using pip version 20.1.1; however, version 22.3 is available.
You should consider upgrading via the 'C:\Users\XXX\Downloads\STABLE\stable-diffusion-webui\venv\Scripts\python.exe -m pip install --upgrade pip' command.
Any help would be greatly appreciated, I've tried my best to be self-sufficient so I'm putting it to the people who may know how to help.
|
[
"One of the easiest methods to install SD is with Automatic1111\nhttps://github.com/AUTOMATIC1111/stable-diffusion-webui\nInstructions on this page in a section titled \"Automatic Installation on Windows\" (since you're using windows paths in your post)\n\nInstall Python 3.10.6, checking \"Add Python to PATH\" Install git.\nDownload the stable-diffusion-webui repository, for example by running git clonehttps://github.com/AUTOMATIC1111/stable-diffusion-webui.git.\nPlace model.ckpt in the models directory (see dependencies for where to\nget it).\n(Optional) Place GFPGANv1.4.pth in the base directory,\nalongside webui.py (see dependencies for where to get it).\nRun webui-user.bat from Windows Explorer as normal, non-administrator,\nuser.\n\nThis is much easier and improved from the early days of Automatic and Stable Diffusion itself.\n"
] |
[
0
] |
[] |
[] |
[
"pip",
"python",
"stable_diffusion"
] |
stackoverflow_0074313444_pip_python_stable_diffusion.txt
|
Q:
Could not find a generator for route RouteSettings("map-screen", null) in the _CustomTabViewState
Building a multi-vending grocery application. Code was going well and working great, but when I added the persistent_bottom_nav_bar plugin and used PersistentTabView as my bottom navigator I am getting Could not find a generator for route RouteSettings("map-screen", null) in the _CustomTabViewState error in my console.
This error occurs whenever I click on my buttons.
Similarly when I click on Sign-Out button I am getting this error Could not find a generator for route RouteSettings("welcome-screen", null) in the _CustomTabViewState.
Here is my main.dart code
import 'dart:async';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:multi_vending_grocery_app/providers/auth_provider.dart';
import 'package:multi_vending_grocery_app/providers/location_provider.dart';
import 'package:multi_vending_grocery_app/providers/store_provider.dart';
import 'package:multi_vending_grocery_app/screens/home_screen.dart';
import 'package:multi_vending_grocery_app/screens/landing_screen.dart';
import 'package:multi_vending_grocery_app/screens/login_screen.dart';
import 'package:multi_vending_grocery_app/screens/main_screen.dart';
import 'package:multi_vending_grocery_app/screens/map_screen.dart';
import 'package:multi_vending_grocery_app/screens/register_screen.dart';
import 'package:multi_vending_grocery_app/screens/splash_screen.dart';
import 'package:multi_vending_grocery_app/screens/welcome_screen.dart';
import 'package:provider/provider.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(
MultiProvider(
providers: [
ChangeNotifierProvider(
create: (_) => AuthProvider(),
),
ChangeNotifierProvider(
create: (_) => LocationProvider(),
),
ChangeNotifierProvider(
create: (_) => StoreProvider(),
),
],
child: const MyApp(),
),
);
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
initialRoute: SplashScreen.id,
routes: {
SplashScreen.id: (context) => const SplashScreen(),
HomeScreen.id: (context) => const HomeScreen(),
WelcomeScreen.id: (context) => const WelcomeScreen(),
MapScreen.id: (context) => const MapScreen(),
LoginScreen.id: (context) => const LoginScreen(),
RegistrationScreen.id: (context) => const RegistrationScreen(),
LandingScreen.id: (context) => const LandingScreen(),
MainScreen.id: (context) => const MainScreen(),
},
debugShowCheckedModeBanner: false,
theme: ThemeData(primarySwatch: Colors.deepPurple, fontFamily: 'Lato'),
);
}
}
Here is my profile_screen.dart code
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:multi_vending_grocery_app/screens/welcome_screen.dart';
class ProfileScreen extends StatelessWidget {
const ProfileScreen({Key? key}) : super(key: key);
static const String id = 'profile-screen';
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Center(
child: Text("Profile Section"),
),
ElevatedButton(onPressed: () {
FirebaseAuth.instance.signOut();
Navigator.pushReplacementNamed(context, WelcomeScreen.id);
}, child: const Text("Sign-Out"))
],
));
}
}
Here is my welcome_screen.dart code
import 'package:flutter/material.dart';
import 'package:multi_vending_grocery_app/providers/auth_provider.dart';
import 'package:multi_vending_grocery_app/providers/location_provider.dart';
import 'package:multi_vending_grocery_app/screens/map_screen.dart';
import 'package:multi_vending_grocery_app/screens/on_board_screen.dart';
import 'package:provider/provider.dart';
class WelcomeScreen extends StatefulWidget {
const WelcomeScreen({Key? key}) : super(key: key);
static const String id = 'welcome-screen';
@override
State<WelcomeScreen> createState() => _WelcomeScreenState();
}
class _WelcomeScreenState extends State<WelcomeScreen> {
@override
Widget build(BuildContext context) {
final auth = Provider.of<AuthProvider>(context);
final Size size = MediaQuery.of(context).size;
TextEditingController _phoneNumberController = TextEditingController();
final locationData = Provider.of<LocationProvider>(context, listen: false);
bool _validPhoneNumber = false;
void showBottomSheet(context) {
showModalBottomSheet(
context: context,
builder: (BuildContext context) {
return StatefulBuilder(
builder: (BuildContext context, StateSetter stateSetter) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Padding(
padding: EdgeInsets.only(top: 20.0, left: 20),
child: Text(
"Login",
style:
TextStyle(fontSize: 25, fontWeight: FontWeight.bold),
),
),
const Padding(
padding: EdgeInsets.only(top: 5.0, left: 20),
child: Text(
"Enter Your Phone Number",
style: TextStyle(fontSize: 18, color: Colors.grey),
),
),
Padding(
padding:
const EdgeInsets.only(top: 8.0, left: 20, right: 20),
child: TextField(
controller: _phoneNumberController,
maxLength: 10,
style: const TextStyle(fontSize: 20),
keyboardType: TextInputType.phone,
decoration: const InputDecoration(
prefix: Text(
"+91 ",
style: TextStyle(fontSize: 20),
),
labelText: "Enter Your Phone Number",
),
autofocus: true,
onChanged: (value) {
if (value.length == 10) {
stateSetter(() {
_validPhoneNumber = true;
});
} else {
stateSetter(
() {
_validPhoneNumber = false;
},
);
}
},
),
),
Row(
children: [
Expanded(
child: SizedBox(
height: size.height / 18,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: AbsorbPointer(
absorbing: _validPhoneNumber ? false : true,
child: ElevatedButton(
style: ButtonStyle(
backgroundColor: _validPhoneNumber
? MaterialStateProperty.all(
Colors.deepPurple)
: MaterialStateProperty.all(
Colors.grey)),
onPressed: () {
stateSetter(() {
auth.isLoading = true;
});
String number =
'+91${_phoneNumberController.text}';
auth.verifyPhoneNumber(
context: context,
number: number,
// latitude: null,
// longitude: null,
// address: null
);
// auth.isLoading = false;
},
child: auth.isLoading
? const Center(
child: CircularProgressIndicator(
valueColor:
AlwaysStoppedAnimation<Color>(
Colors.white),
),
)
: Text(
_validPhoneNumber
? "Continue"
: "Enter Phone Number",
style: const TextStyle(
fontSize: 20,
),
),
),
),
),
),
)
],
)
],
);
},
);
},
);
}
return Container(
color: Colors.deepPurpleAccent,
child: SafeArea(
child: Scaffold(
body: SizedBox(
child: Stack(
children: [
Align(
alignment: Alignment.topRight,
child: Container(
height: size.height / 10,
width: size.width / 3.5,
alignment: Alignment.center,
decoration: const BoxDecoration(
color: Color.fromRGBO(178, 182, 231, 1.0),
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(1000),
),
),
child: InkWell(
onTap: () {},
child: Icon(
Icons.arrow_forward,
size: size.width / 12,
),
),
),
),
Column(
children: [
const Expanded(child: OnBoardScreen()),
const Text(
"Ready to Order from your Nearest Shop?",
style:
TextStyle(fontSize: 18, fontWeight: FontWeight.w300),
),
SizedBox(
height: size.height / 45,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text("New User?",style: TextStyle(fontSize: 20,fontWeight: FontWeight.bold),),
SizedBox(height: 50,child: Image.asset('assets/forward_arrow.gif')),
TextButton(
style: ButtonStyle(
elevation: MaterialStateProperty.all(1),
backgroundColor: MaterialStateProperty.all(
const Color.fromRGBO(178, 182, 231, 1.0),
)),
onPressed: () async {
setState(() {
locationData.isLoading = true;
});
await locationData.getMyCurrentPosition();
if (locationData.permissionAllowed) {
Navigator.pushReplacementNamed(context, MapScreen.id);
setState(() {
locationData.isLoading = false;
});
} else {
setState(() {
locationData.isLoading = false;
});
}
},
child: locationData.isLoading
? const Center(
child: CircularProgressIndicator(
valueColor:
AlwaysStoppedAnimation<Color>(Colors.white),
),
)
: const Text(
"Set Location",
style: TextStyle(
color: Colors.black,
fontSize: 16,
),
),
),
],
),
SizedBox(
height: size.height / 45,
),
TextButton(
onPressed: () {
setState(() {
auth.screen = "Login";
});
showBottomSheet(context);
},
child: RichText(
text: const TextSpan(
text: "Already a customer?",
children: [
TextSpan(
text: " Login",
style: TextStyle(
fontSize: 17,
color: Colors.deepPurpleAccent,
fontWeight: FontWeight.w500))
],
style: TextStyle(fontSize: 15, color: Colors.black87),
),
),
),
SizedBox(
height: size.height / 30,
),
],
),
],
),
),
),
),
);
}
}
A:
You have to explicitly provide route settings for specific PersistentBottomNavBarItem to navigate from that page.
For Example: in your PersistentTabView, you have a Home tab that navigates to HomeScreen(). Now you want to navigate to ProfileScreen() from HomeScreen() then you have to provide a route setting in your PersistentBottomNavBarItem.
PersistentBottomNavBarItem(
icon: Icon(Icons.home),
title: "Home",
activeColorPrimary: primaryColor,
inactiveColorPrimary: Colors.grey,
inactiveColorSecondary: Colors.purple,
routeAndNavigatorSettings: RouteAndNavigatorSettings(
routes: {
"/profile": (context)=> ProfileScreen(),
},
)
),
Now you can call Navigator.pushNamed(context, "/profile") from your HomeScreen() to navigate to ProfileScreen().
A:
Yes @Sizajul Islam said right
You can explore the navigation bar which ever you are using. It must has a property like routes or onGenerateRoutes. Make a seprate class for routes and then call them in your navigation.
For CupertinoTabBar
**return CupertinoTabView(
routes: appRoutes,
//Or
onGenerateRoutes: ....
.......................
**
Similary as for above mentioned, set routes in your navigation:
PersistentBottomNavBarItem(
..............,
routeAndNavigatorSettings: RouteAndNavigatorSettings(
routes: {},
//Or
onGenerateRoutes: ....
|
Could not find a generator for route RouteSettings("map-screen", null) in the _CustomTabViewState
|
Building a multi-vending grocery application. Code was going well and working great, but when I added the persistent_bottom_nav_bar plugin and used PersistentTabView as my bottom navigator I am getting Could not find a generator for route RouteSettings("map-screen", null) in the _CustomTabViewState error in my console.
This error occurs whenever I click on my buttons.
Similarly when I click on Sign-Out button I am getting this error Could not find a generator for route RouteSettings("welcome-screen", null) in the _CustomTabViewState.
Here is my main.dart code
import 'dart:async';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:multi_vending_grocery_app/providers/auth_provider.dart';
import 'package:multi_vending_grocery_app/providers/location_provider.dart';
import 'package:multi_vending_grocery_app/providers/store_provider.dart';
import 'package:multi_vending_grocery_app/screens/home_screen.dart';
import 'package:multi_vending_grocery_app/screens/landing_screen.dart';
import 'package:multi_vending_grocery_app/screens/login_screen.dart';
import 'package:multi_vending_grocery_app/screens/main_screen.dart';
import 'package:multi_vending_grocery_app/screens/map_screen.dart';
import 'package:multi_vending_grocery_app/screens/register_screen.dart';
import 'package:multi_vending_grocery_app/screens/splash_screen.dart';
import 'package:multi_vending_grocery_app/screens/welcome_screen.dart';
import 'package:provider/provider.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(
MultiProvider(
providers: [
ChangeNotifierProvider(
create: (_) => AuthProvider(),
),
ChangeNotifierProvider(
create: (_) => LocationProvider(),
),
ChangeNotifierProvider(
create: (_) => StoreProvider(),
),
],
child: const MyApp(),
),
);
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
initialRoute: SplashScreen.id,
routes: {
SplashScreen.id: (context) => const SplashScreen(),
HomeScreen.id: (context) => const HomeScreen(),
WelcomeScreen.id: (context) => const WelcomeScreen(),
MapScreen.id: (context) => const MapScreen(),
LoginScreen.id: (context) => const LoginScreen(),
RegistrationScreen.id: (context) => const RegistrationScreen(),
LandingScreen.id: (context) => const LandingScreen(),
MainScreen.id: (context) => const MainScreen(),
},
debugShowCheckedModeBanner: false,
theme: ThemeData(primarySwatch: Colors.deepPurple, fontFamily: 'Lato'),
);
}
}
Here is my profile_screen.dart code
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:multi_vending_grocery_app/screens/welcome_screen.dart';
class ProfileScreen extends StatelessWidget {
const ProfileScreen({Key? key}) : super(key: key);
static const String id = 'profile-screen';
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Center(
child: Text("Profile Section"),
),
ElevatedButton(onPressed: () {
FirebaseAuth.instance.signOut();
Navigator.pushReplacementNamed(context, WelcomeScreen.id);
}, child: const Text("Sign-Out"))
],
));
}
}
Here is my welcome_screen.dart code
import 'package:flutter/material.dart';
import 'package:multi_vending_grocery_app/providers/auth_provider.dart';
import 'package:multi_vending_grocery_app/providers/location_provider.dart';
import 'package:multi_vending_grocery_app/screens/map_screen.dart';
import 'package:multi_vending_grocery_app/screens/on_board_screen.dart';
import 'package:provider/provider.dart';
class WelcomeScreen extends StatefulWidget {
const WelcomeScreen({Key? key}) : super(key: key);
static const String id = 'welcome-screen';
@override
State<WelcomeScreen> createState() => _WelcomeScreenState();
}
class _WelcomeScreenState extends State<WelcomeScreen> {
@override
Widget build(BuildContext context) {
final auth = Provider.of<AuthProvider>(context);
final Size size = MediaQuery.of(context).size;
TextEditingController _phoneNumberController = TextEditingController();
final locationData = Provider.of<LocationProvider>(context, listen: false);
bool _validPhoneNumber = false;
void showBottomSheet(context) {
showModalBottomSheet(
context: context,
builder: (BuildContext context) {
return StatefulBuilder(
builder: (BuildContext context, StateSetter stateSetter) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Padding(
padding: EdgeInsets.only(top: 20.0, left: 20),
child: Text(
"Login",
style:
TextStyle(fontSize: 25, fontWeight: FontWeight.bold),
),
),
const Padding(
padding: EdgeInsets.only(top: 5.0, left: 20),
child: Text(
"Enter Your Phone Number",
style: TextStyle(fontSize: 18, color: Colors.grey),
),
),
Padding(
padding:
const EdgeInsets.only(top: 8.0, left: 20, right: 20),
child: TextField(
controller: _phoneNumberController,
maxLength: 10,
style: const TextStyle(fontSize: 20),
keyboardType: TextInputType.phone,
decoration: const InputDecoration(
prefix: Text(
"+91 ",
style: TextStyle(fontSize: 20),
),
labelText: "Enter Your Phone Number",
),
autofocus: true,
onChanged: (value) {
if (value.length == 10) {
stateSetter(() {
_validPhoneNumber = true;
});
} else {
stateSetter(
() {
_validPhoneNumber = false;
},
);
}
},
),
),
Row(
children: [
Expanded(
child: SizedBox(
height: size.height / 18,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: AbsorbPointer(
absorbing: _validPhoneNumber ? false : true,
child: ElevatedButton(
style: ButtonStyle(
backgroundColor: _validPhoneNumber
? MaterialStateProperty.all(
Colors.deepPurple)
: MaterialStateProperty.all(
Colors.grey)),
onPressed: () {
stateSetter(() {
auth.isLoading = true;
});
String number =
'+91${_phoneNumberController.text}';
auth.verifyPhoneNumber(
context: context,
number: number,
// latitude: null,
// longitude: null,
// address: null
);
// auth.isLoading = false;
},
child: auth.isLoading
? const Center(
child: CircularProgressIndicator(
valueColor:
AlwaysStoppedAnimation<Color>(
Colors.white),
),
)
: Text(
_validPhoneNumber
? "Continue"
: "Enter Phone Number",
style: const TextStyle(
fontSize: 20,
),
),
),
),
),
),
)
],
)
],
);
},
);
},
);
}
return Container(
color: Colors.deepPurpleAccent,
child: SafeArea(
child: Scaffold(
body: SizedBox(
child: Stack(
children: [
Align(
alignment: Alignment.topRight,
child: Container(
height: size.height / 10,
width: size.width / 3.5,
alignment: Alignment.center,
decoration: const BoxDecoration(
color: Color.fromRGBO(178, 182, 231, 1.0),
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(1000),
),
),
child: InkWell(
onTap: () {},
child: Icon(
Icons.arrow_forward,
size: size.width / 12,
),
),
),
),
Column(
children: [
const Expanded(child: OnBoardScreen()),
const Text(
"Ready to Order from your Nearest Shop?",
style:
TextStyle(fontSize: 18, fontWeight: FontWeight.w300),
),
SizedBox(
height: size.height / 45,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text("New User?",style: TextStyle(fontSize: 20,fontWeight: FontWeight.bold),),
SizedBox(height: 50,child: Image.asset('assets/forward_arrow.gif')),
TextButton(
style: ButtonStyle(
elevation: MaterialStateProperty.all(1),
backgroundColor: MaterialStateProperty.all(
const Color.fromRGBO(178, 182, 231, 1.0),
)),
onPressed: () async {
setState(() {
locationData.isLoading = true;
});
await locationData.getMyCurrentPosition();
if (locationData.permissionAllowed) {
Navigator.pushReplacementNamed(context, MapScreen.id);
setState(() {
locationData.isLoading = false;
});
} else {
setState(() {
locationData.isLoading = false;
});
}
},
child: locationData.isLoading
? const Center(
child: CircularProgressIndicator(
valueColor:
AlwaysStoppedAnimation<Color>(Colors.white),
),
)
: const Text(
"Set Location",
style: TextStyle(
color: Colors.black,
fontSize: 16,
),
),
),
],
),
SizedBox(
height: size.height / 45,
),
TextButton(
onPressed: () {
setState(() {
auth.screen = "Login";
});
showBottomSheet(context);
},
child: RichText(
text: const TextSpan(
text: "Already a customer?",
children: [
TextSpan(
text: " Login",
style: TextStyle(
fontSize: 17,
color: Colors.deepPurpleAccent,
fontWeight: FontWeight.w500))
],
style: TextStyle(fontSize: 15, color: Colors.black87),
),
),
),
SizedBox(
height: size.height / 30,
),
],
),
],
),
),
),
),
);
}
}
|
[
"You have to explicitly provide route settings for specific PersistentBottomNavBarItem to navigate from that page.\nFor Example: in your PersistentTabView, you have a Home tab that navigates to HomeScreen(). Now you want to navigate to ProfileScreen() from HomeScreen() then you have to provide a route setting in your PersistentBottomNavBarItem.\nPersistentBottomNavBarItem(\n icon: Icon(Icons.home),\n title: \"Home\",\n activeColorPrimary: primaryColor,\n inactiveColorPrimary: Colors.grey,\n inactiveColorSecondary: Colors.purple,\n routeAndNavigatorSettings: RouteAndNavigatorSettings(\n routes: {\n \"/profile\": (context)=> ProfileScreen(),\n },\n )\n ),\n\nNow you can call Navigator.pushNamed(context, \"/profile\") from your HomeScreen() to navigate to ProfileScreen().\n",
"Yes @Sizajul Islam said right\nYou can explore the navigation bar which ever you are using. It must has a property like routes or onGenerateRoutes. Make a seprate class for routes and then call them in your navigation.\nFor CupertinoTabBar\n**return CupertinoTabView(\nroutes: appRoutes,\n//Or\nonGenerateRoutes: ....\n.......................\n**\nSimilary as for above mentioned, set routes in your navigation:\nPersistentBottomNavBarItem(\n..............,\n routeAndNavigatorSettings: RouteAndNavigatorSettings(\n routes: {},\n//Or\n onGenerateRoutes: ....\n\n"
] |
[
1,
0
] |
[] |
[] |
[
"dart",
"flutter"
] |
stackoverflow_0071216042_dart_flutter.txt
|
Q:
I am trying to add elements to listbox in ASP.net but array looks empty in if or case statements
`
protected void Button1_Click(object sender, EventArgs e)
{
int ürün_sayısı = Convert.ToInt32(Interaction.InputBox("Ürün Sayısını Giriniz"));
Ürün[] ürün_listesi = new Ürün[ürün_sayısı];
for (int i = 0; i < ürün_sayısı; i++)
{
Ürün yeni_ürün = new Ürün();
yeni_ürün.barkod = Convert.ToInt32(Interaction.InputBox("Ürün Barkodunu Giriniz"));
yeni_ürün.ürün_adı = Interaction.InputBox("Ürün Adını Giriniz");
yeni_ürün.ürün_kategorisi = Interaction.InputBox("Ürün Kategorisini Giriniz");
yeni_ürün.ürün_fiyatı = Convert.ToInt32(Interaction.InputBox("Ürün Fiyatını Giriniz"));
int devam = Convert.ToInt32(Interaction.InputBox("Devam Etmek İstiyorsanız 1 i tuşlayın Devam etmek istemiyorsanız 2 yi tuşlayın"));
ürün_listesi[i] = yeni_ürün;
if (devam == 2 )
{
break;
}
}
int islem_secimi = Convert.ToInt32(Interaction.InputBox("Barkoda Göre Arama yapmak istiyorsanız 1 i tuşlayın ;Kategoriye Göre Arama yapmak istiyorsanız 2 i tuşlayın ;Minimum fiyata Göre Arama yapmak istiyorsanız 3 i tuşlayın ;Bütün sonuçları görmek istiyorsanız 4 ü tuşlayın "));
/*switch (islem_secimi)
{
case 1:
int aranan_barkod = Convert.ToInt32(Interaction.InputBox("Aranan Ürün Barkodunu Giriniz"));
foreach (var gelen_ürün in ürün_listesi)
{
if (gelen_ürün.barkod == aranan_barkod)
{
ListBox1.Items.Add(gelen_ürün.ürün_bilgisi_ver());
}
}
break;
case 2:
string aranan_kategori = Interaction.InputBox("Aranan Ürün Kategorisini Giriniz");
foreach (var gelen_ürün in ürün_listesi)
{
if (gelen_ürün.ürün_kategorisi == aranan_kategori)
{
ListBox1.Items.Add(gelen_ürün.ürün_bilgisi_ver());
}
}
break;
case 3:
int aranan_minimum = Convert.ToInt32(Interaction.InputBox("Aranan Minimum Fiyatı Giriniz"));
foreach (var gelen_ürün in ürün_listesi)
{
if (gelen_ürün.ürün_fiyatı >= aranan_minimum)
{
ListBox1.Items.Add(gelen_ürün.ürün_bilgisi_ver());
}
}
break;
case 4:
foreach (Ürün gelen_ürün in ürün_listesi)
{
ListBox1.Items.Add(gelen_ürün.ürün_bilgisi_ver());
}
break;
/* int aranan_barkod = Convert.ToInt32(Interaction.InputBox("Aranan Ürün Barkodunu Giriniz"));
foreach (var gelen_ürün in ürün_listesi)
{
if (gelen_ürün.barkod == aranan_barkod)
{
ListBox1.Items.Add(gelen_ürün.ürün_bilgisi_ver());
}
else { ListBox1.Items.Add("Böyle Bir Ürün Bulunmamaktadır"); }
}*/
/*string aranan_kategori = Interaction.InputBox("Aranan Ürün Kategorisini Giriniz");
foreach (var gelen_ürün in ürün_listesi)
{
if (gelen_ürün.ürün_kategorisi == aranan_kategori)
{
ListBox1.Items.Add(gelen_ürün.ürün_bilgisi_ver());
}
}*/
/*int aranan_minimum = Convert.ToInt32(Interaction.InputBox("Aranan Minimum Fiyatı Giriniz"));
foreach (var gelen_ürün in ürün_listesi)
{
if (gelen_ürün.ürün_fiyatı >= aranan_minimum)
{
ListBox1.Items.Add(gelen_ürün.ürün_bilgisi_ver());
}
}*/
if(islem_secimi==1)
foreach (Ürün gelen_ürün in ürün_listesi)
{
ListBox1.Items.Add(gelen_ürün.ürün_bilgisi_ver());
}
}
I commented my code because if ı code like this`;
`
foreach (Ürün gelen_ürün in ürün_listesi)
{
ListBox1.Items.Add(gelen_ürün.ürün_bilgisi_ver());
}
`
Everything works perfectly but when foreach nested in switch or if statements;I get an error says gelen_ürün is null.
Why my array turns null in if/switch statements.
I would like to return values depends on the filter like ısbn number of product or category , ı tried everyone of them separate and everything works fine until switch/if statement came .
A:
It looks like you're trying to populate a listbox with items based on user input. The issue you're encountering is that the array that you're using to store the items is empty in the if and case statements.
The reason for this is that the array is being created and populated in the Button1_Click method, but it is not being passed to the other methods where you're using it. As a result, the array is empty in those methods.
To fix this, you can pass the array as a parameter to the other methods where you're using it. For example, you could modify your Button1_Click method to look like this :
protected void Button1_Click(object sender, EventArgs e)
{
int ürün_sayısı = Convert.ToInt32(Interaction.InputBox("Ürün Sayısını Giriniz"));
Ürün[] ürün_listesi = new Ürün[ürün_sayısı];
for (int i = 0; i < ürün_sayısı; i++)
{
Ürün yeni_ürün = new Ürün();
yeni_ürün.barkod = Convert.ToInt32(Interaction.InputBox("Ürün Barkodunu Giriniz"));
yeni_ürün.ürün_adı = Interaction.InputBox("Ürün Adını Giriniz");
yeni_ürün.ürün_kategorisi = Interaction.InputBox("Ürün Kategorisini Giriniz");
yeni_ürün.ürün_fiyatı = Convert.ToInt32(Interaction.InputBox("Ürün Fiyatını Giriniz"));
int devam = Convert.ToInt32(Interaction.InputBox("Devam Etmek İstiyorsanız 1 i tuşlayın Devam etmek istemiyorsanız 2 yi tuşlayın"));
ürün_listesi[i] = yeni_ürün;
if (devam == 2 )
{
break;
}
}
// Call the method that populates the listbox, passing the array as a parameter
PopulateListbox(ürün_listesi);
}
|
I am trying to add elements to listbox in ASP.net but array looks empty in if or case statements
|
`
protected void Button1_Click(object sender, EventArgs e)
{
int ürün_sayısı = Convert.ToInt32(Interaction.InputBox("Ürün Sayısını Giriniz"));
Ürün[] ürün_listesi = new Ürün[ürün_sayısı];
for (int i = 0; i < ürün_sayısı; i++)
{
Ürün yeni_ürün = new Ürün();
yeni_ürün.barkod = Convert.ToInt32(Interaction.InputBox("Ürün Barkodunu Giriniz"));
yeni_ürün.ürün_adı = Interaction.InputBox("Ürün Adını Giriniz");
yeni_ürün.ürün_kategorisi = Interaction.InputBox("Ürün Kategorisini Giriniz");
yeni_ürün.ürün_fiyatı = Convert.ToInt32(Interaction.InputBox("Ürün Fiyatını Giriniz"));
int devam = Convert.ToInt32(Interaction.InputBox("Devam Etmek İstiyorsanız 1 i tuşlayın Devam etmek istemiyorsanız 2 yi tuşlayın"));
ürün_listesi[i] = yeni_ürün;
if (devam == 2 )
{
break;
}
}
int islem_secimi = Convert.ToInt32(Interaction.InputBox("Barkoda Göre Arama yapmak istiyorsanız 1 i tuşlayın ;Kategoriye Göre Arama yapmak istiyorsanız 2 i tuşlayın ;Minimum fiyata Göre Arama yapmak istiyorsanız 3 i tuşlayın ;Bütün sonuçları görmek istiyorsanız 4 ü tuşlayın "));
/*switch (islem_secimi)
{
case 1:
int aranan_barkod = Convert.ToInt32(Interaction.InputBox("Aranan Ürün Barkodunu Giriniz"));
foreach (var gelen_ürün in ürün_listesi)
{
if (gelen_ürün.barkod == aranan_barkod)
{
ListBox1.Items.Add(gelen_ürün.ürün_bilgisi_ver());
}
}
break;
case 2:
string aranan_kategori = Interaction.InputBox("Aranan Ürün Kategorisini Giriniz");
foreach (var gelen_ürün in ürün_listesi)
{
if (gelen_ürün.ürün_kategorisi == aranan_kategori)
{
ListBox1.Items.Add(gelen_ürün.ürün_bilgisi_ver());
}
}
break;
case 3:
int aranan_minimum = Convert.ToInt32(Interaction.InputBox("Aranan Minimum Fiyatı Giriniz"));
foreach (var gelen_ürün in ürün_listesi)
{
if (gelen_ürün.ürün_fiyatı >= aranan_minimum)
{
ListBox1.Items.Add(gelen_ürün.ürün_bilgisi_ver());
}
}
break;
case 4:
foreach (Ürün gelen_ürün in ürün_listesi)
{
ListBox1.Items.Add(gelen_ürün.ürün_bilgisi_ver());
}
break;
/* int aranan_barkod = Convert.ToInt32(Interaction.InputBox("Aranan Ürün Barkodunu Giriniz"));
foreach (var gelen_ürün in ürün_listesi)
{
if (gelen_ürün.barkod == aranan_barkod)
{
ListBox1.Items.Add(gelen_ürün.ürün_bilgisi_ver());
}
else { ListBox1.Items.Add("Böyle Bir Ürün Bulunmamaktadır"); }
}*/
/*string aranan_kategori = Interaction.InputBox("Aranan Ürün Kategorisini Giriniz");
foreach (var gelen_ürün in ürün_listesi)
{
if (gelen_ürün.ürün_kategorisi == aranan_kategori)
{
ListBox1.Items.Add(gelen_ürün.ürün_bilgisi_ver());
}
}*/
/*int aranan_minimum = Convert.ToInt32(Interaction.InputBox("Aranan Minimum Fiyatı Giriniz"));
foreach (var gelen_ürün in ürün_listesi)
{
if (gelen_ürün.ürün_fiyatı >= aranan_minimum)
{
ListBox1.Items.Add(gelen_ürün.ürün_bilgisi_ver());
}
}*/
if(islem_secimi==1)
foreach (Ürün gelen_ürün in ürün_listesi)
{
ListBox1.Items.Add(gelen_ürün.ürün_bilgisi_ver());
}
}
I commented my code because if ı code like this`;
`
foreach (Ürün gelen_ürün in ürün_listesi)
{
ListBox1.Items.Add(gelen_ürün.ürün_bilgisi_ver());
}
`
Everything works perfectly but when foreach nested in switch or if statements;I get an error says gelen_ürün is null.
Why my array turns null in if/switch statements.
I would like to return values depends on the filter like ısbn number of product or category , ı tried everyone of them separate and everything works fine until switch/if statement came .
|
[
"It looks like you're trying to populate a listbox with items based on user input. The issue you're encountering is that the array that you're using to store the items is empty in the if and case statements.\nThe reason for this is that the array is being created and populated in the Button1_Click method, but it is not being passed to the other methods where you're using it. As a result, the array is empty in those methods.\nTo fix this, you can pass the array as a parameter to the other methods where you're using it. For example, you could modify your Button1_Click method to look like this :\nprotected void Button1_Click(object sender, EventArgs e)\n{\n int ürün_sayısı = Convert.ToInt32(Interaction.InputBox(\"Ürün Sayısını Giriniz\"));\n Ürün[] ürün_listesi = new Ürün[ürün_sayısı];\n for (int i = 0; i < ürün_sayısı; i++)\n {\n Ürün yeni_ürün = new Ürün();\n yeni_ürün.barkod = Convert.ToInt32(Interaction.InputBox(\"Ürün Barkodunu Giriniz\"));\n yeni_ürün.ürün_adı = Interaction.InputBox(\"Ürün Adını Giriniz\");\n yeni_ürün.ürün_kategorisi = Interaction.InputBox(\"Ürün Kategorisini Giriniz\");\n yeni_ürün.ürün_fiyatı = Convert.ToInt32(Interaction.InputBox(\"Ürün Fiyatını Giriniz\"));\n int devam = Convert.ToInt32(Interaction.InputBox(\"Devam Etmek İstiyorsanız 1 i tuşlayın Devam etmek istemiyorsanız 2 yi tuşlayın\"));\n ürün_listesi[i] = yeni_ürün;\n if (devam == 2 )\n {\n break;\n }\n }\n // Call the method that populates the listbox, passing the array as a parameter\n PopulateListbox(ürün_listesi);\n}\n\n"
] |
[
0
] |
[] |
[] |
[
".net",
"asp.net",
"c#"
] |
stackoverflow_0074669958_.net_asp.net_c#.txt
|
Q:
How to pass rand() values from a function to the main function?
Haven't program for a while, but I have this game project where I need to randomized who will be player 1 and player 2 and I need to use a user-defined function because it will be part of a bigger function. Player 1 and 2 should reflect whaat will be printed above. How can I improve my code? I also cannot use global variables.
#include<stdio.h>
int randomColor(int nRandom, int nRed, int nBlue)
{
srand(time(NULL));
nRandom = (rand()%2);
switch (nRandom)
{
case 0:
nRed = 1;
nBlue = 2;
printf("\n\n\tPlayer %d = Red\n", nRed);
printf("\tPlayer %d = Blue\n", nBlue);
break;
case 1:
nRed = 2;
nBlue = 1;
printf("\n\n\tPlayer %d = Blue\n", nRed);
printf("\tPlayer %d = Red\n", nBlue);
break;
}
}
int main()
{
int nRandom, nRed, nBlue;
randomColor(nRandom, nRed, nBlue);
printf("\nPlayer %d (R) turn", nRed);
printf("\nPlayer %d (B) turn", nBlue);
}
A:
Here is one way you can improve your code to return the values of nDark and nLight from the randomColor function, so that they can be used in the main function:
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
// Define a struct to store the values of nDark and nLight.
typedef struct {
int nDark;
int nLight;
} RandomColor;
RandomColor randomColor()
{
RandomColor color;
srand(time(NULL));
int nRandom = (rand()%2);
switch (nRandom)
{
case 0:
color.nDark = 1;
color.nLight = 2;
printf("\n\n\tPlayer %d = Dark\n", color.nDark);
printf("\tPlayer %d = Light\n", color.nLight);
break;
case 1:
color.nDark = 2;
color.nLight = 1;
printf("\n\n\tPlayer %d = Light\n", color.nLight);
printf("\tPlayer %d = Dark\n", color.nDark);
break;
}
return color;
}
int main()
{
// Call the randomColor function to get the values of nDark and nLight.
RandomColor color = randomColor();
printf("\nPlayer %d (D) turn", color.nDark);
printf("\nPlayer %d (L) turn", color.nLight);
}
In this code, I have defined a struct called RandomColor to store the values of nDark and nLight that are generated by the randomColor function. The randomColor function now returns a RandomColor struct, which contains the values of nDark and nLight that are generated.
In the main function, I call the randomColor function and store the return value in a variable of type RandomColor. I can then access the nDark and nLight values in this variable to use them in the printf statements.
I have also made a few other changes to your code:
I have added the stdlib.h and time.h headers, which are needed for the rand and time functions that are used in the code.
I have removed the unnecessary parameters from the randomColor function, since the values of nDark and nLight are now stored in the struct that is returned by the function.
I have changed the randomColor function to have a return type of RandomColor, so that it can return the struct containing the nDark and nLight values.
A:
Although what you have is fine, you could be more efficient by having one boolean variable instead of the two.
Player1Dark=True or False
Then Player2Dark is not required, its just !Player1Dark
As they are mustually exclusive
|
How to pass rand() values from a function to the main function?
|
Haven't program for a while, but I have this game project where I need to randomized who will be player 1 and player 2 and I need to use a user-defined function because it will be part of a bigger function. Player 1 and 2 should reflect whaat will be printed above. How can I improve my code? I also cannot use global variables.
#include<stdio.h>
int randomColor(int nRandom, int nRed, int nBlue)
{
srand(time(NULL));
nRandom = (rand()%2);
switch (nRandom)
{
case 0:
nRed = 1;
nBlue = 2;
printf("\n\n\tPlayer %d = Red\n", nRed);
printf("\tPlayer %d = Blue\n", nBlue);
break;
case 1:
nRed = 2;
nBlue = 1;
printf("\n\n\tPlayer %d = Blue\n", nRed);
printf("\tPlayer %d = Red\n", nBlue);
break;
}
}
int main()
{
int nRandom, nRed, nBlue;
randomColor(nRandom, nRed, nBlue);
printf("\nPlayer %d (R) turn", nRed);
printf("\nPlayer %d (B) turn", nBlue);
}
|
[
"Here is one way you can improve your code to return the values of nDark and nLight from the randomColor function, so that they can be used in the main function:\n#include<stdio.h>\n#include<stdlib.h>\n#include<time.h>\n\n// Define a struct to store the values of nDark and nLight.\ntypedef struct {\n int nDark;\n int nLight;\n} RandomColor;\n\nRandomColor randomColor()\n{\n RandomColor color;\n srand(time(NULL)); \n int nRandom = (rand()%2); \n\n switch (nRandom)\n {\n case 0: \n color.nDark = 1;\n color.nLight = 2;\n printf(\"\\n\\n\\tPlayer %d = Dark\\n\", color.nDark);\n printf(\"\\tPlayer %d = Light\\n\", color.nLight);\n break;\n case 1: \n color.nDark = 2;\n color.nLight = 1;\n printf(\"\\n\\n\\tPlayer %d = Light\\n\", color.nLight);\n printf(\"\\tPlayer %d = Dark\\n\", color.nDark);\n break; \n }\n\n return color;\n}\n\nint main()\n{\n // Call the randomColor function to get the values of nDark and nLight.\n RandomColor color = randomColor();\n\n printf(\"\\nPlayer %d (D) turn\", color.nDark);\n printf(\"\\nPlayer %d (L) turn\", color.nLight); \n}\n\nIn this code, I have defined a struct called RandomColor to store the values of nDark and nLight that are generated by the randomColor function. The randomColor function now returns a RandomColor struct, which contains the values of nDark and nLight that are generated.\nIn the main function, I call the randomColor function and store the return value in a variable of type RandomColor. I can then access the nDark and nLight values in this variable to use them in the printf statements.\nI have also made a few other changes to your code:\nI have added the stdlib.h and time.h headers, which are needed for the rand and time functions that are used in the code.\nI have removed the unnecessary parameters from the randomColor function, since the values of nDark and nLight are now stored in the struct that is returned by the function.\nI have changed the randomColor function to have a return type of RandomColor, so that it can return the struct containing the nDark and nLight values.\n",
"Although what you have is fine, you could be more efficient by having one boolean variable instead of the two.\nPlayer1Dark=True or False\nThen Player2Dark is not required, its just !Player1Dark\nAs they are mustually exclusive\n"
] |
[
0,
0
] |
[] |
[] |
[
"c",
"random"
] |
stackoverflow_0074669928_c_random.txt
|
Q:
Why do I keep getting lnK2019 error In clion using QT
I am trying to make a qt project in Clion but every time I try to run it it gives me this error it says there is a unresolved external in function WinMain but it doesn't exist
"
[1/1] Linking CXX executable untitled.exe
FAILED: untitled.exe
cmd.exe /C "cd . && "C:\Program Files\JetBrains\CLion 2022.2.4\bin\cmake\win\bin\cmake.exe" -E vs_link_exe --intdir=CMakeFiles\untitled.dir --rc=C:\PROGRA~2\WI3CF2~1\10\bin\100220~1.0\x64\rc.exe --mt=C:\PROGRA~2\WI3CF2~1\10\bin\100220~1.0\x64\mt.exe --manifests -- C:\PROGRA~1\MIB055~1\2022\COMMUN~1\VC\Tools\MSVC\1434~1.319\bin\Hostx64\x64\link.exe /nologo CMakeFiles\untitled.dir\untitled_autogen\mocs_compilation.cpp.obj /out:untitled.exe /implib:untitled.lib /pdb:untitled.pdb /version:0.0 /machine:x64 /debug /INCREMENTAL /subsystem:windows -DYNAMICBASE -NXCOMPAT -LARGEADDRESSAWARE C:\Qt\6.4.1\msvc2019_64\lib\Qt6Widgetsd.lib C:\Qt\6.4.1\msvc2019_64\lib\Qt6Guid.lib C:\Qt\6.4.1\msvc2019_64\lib\Qt6Cored.lib mpr.lib userenv.lib C:\Qt\6.4.1\msvc2019_64\lib\Qt6EntryPointd.lib shell32.lib d3d11.lib dxgi.lib dxguid.lib kernel32.lib user32.lib gdi32.lib winspool.lib shell32.lib ole32.lib oleaut32.lib uuid.lib comdlg32.lib advapi32.lib && cd ."
LINK Pass 1: command "C:\PROGRA~1\MIB055~1\2022\COMMUN~1\VC\Tools\MSVC\1434~1.319\bin\Hostx64\x64\link.exe /nologo CMakeFiles\untitled.dir\untitled_autogen\mocs_compilation.cpp.obj /out:untitled.exe /implib:untitled.lib /pdb:untitled.pdb /version:0.0 /machine:x64 /debug /INCREMENTAL /subsystem:windows -DYNAMICBASE -NXCOMPAT -LARGEADDRESSAWARE C:\Qt\6.4.1\msvc2019_64\lib\Qt6Widgetsd.lib C:\Qt\6.4.1\msvc2019_64\lib\Qt6Guid.lib C:\Qt\6.4.1\msvc2019_64\lib\Qt6Cored.lib mpr.lib userenv.lib C:\Qt\6.4.1\msvc2019_64\lib\Qt6EntryPointd.lib shell32.lib d3d11.lib dxgi.lib dxguid.lib kernel32.lib user32.lib gdi32.lib winspool.lib shell32.lib ole32.lib oleaut32.lib uuid.lib comdlg32.lib advapi32.lib /MANIFEST /MANIFESTFILE:CMakeFiles\untitled.dir/intermediate.manifest CMakeFiles\untitled.dir/manifest.res" failed (exit code 1120) with the following output:
Qt6EntryPointd.lib(qtentrypoint_win.cpp.obj) : error LNK2019: unresolved external symbol main referenced in function WinMain
untitled.exe : fatal error LNK1120: 1 unresolved externals
ninja: build stopped: subcommand failed."
"
here is my cmake file as well
"
cmake_minimum_required(VERSION 3.16)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_INCLUDE_CURRENT_DIR ON)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
if (WIN32)
project(untitled LANGUAGES CXX)
elseif(UNIX)
project(untitled)
endif()
set(CMAKE_CONFIGURATION_TYPES "Release;RelWithDebInfo" CACHE STRING "" FORCE)
#======================= INCLUSION OF Qt =======================#
set(CMAKE_PREFIX_PATH "C:/dev/vcpkg/ports")
find_package(Qt6 REQUIRED
COMPONENTS Core Widgets Gui
)
set(CMAKE_INCLUDE_CURRENT_DIR ON)
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)
set(CMAKE_AUTOUIC ON)
#=================== INCLUSION OF Project Files ====================#
set(FORMS_DIR "${CMAKE_SOURCE_DIR}/forms")
set(INCLUDE_DIR "${CMAKE_SOURCE_DIR}/include")
set(SOURCE_DIR "${CMAKE_SOURCE_DIR}/src")
include_directories(${FORMS_DIR})
include_directories(${INCLUDE_DIR})
include_directories(${SOURCE_DIR})
file(GLOB_RECURSE SOURCES
"${FORMS_DIR}/*.ui"
"${FORMS_DIR}/*.qrc"
"${INCLUDE_DIR}/*.h"
"${SOURCE_DIR}/*.cpp"
)
#=================== SETUP EXECTUABLE ====================#
# Enable debug logging on RELWITHDEBINFO configuration
set_property(DIRECTORY APPEND PROPERTY COMPILE_DEFINITIONS
$<$<CONFIG:RELWITHDEBINFO>:QT_MESSAGELOGCONTEXT>
)
# Add the forms directory to the AUTOUIC search paths
set(CMAKE_AUTOUIC_SEARCH_PATHS ${CMAKE_AUTOUIC_SEARCH_PATHS} ${FORMS_DIR})
# Add the executable
if (WIN32)
qt_add_executable(untitled WIN32 ${SOURCES})
elseif(UNIX)
qt_add_executable(untitled ${SOURCES})
endif()
# Add the target includes for MY_PROJECT
target_include_directories(untitled PRIVATE ${FORMS_DIR})
target_include_directories(untitled PRIVATE ${INCLUDE_DIR})
target_include_directories(untitled PRIVATE ${SOURCE_DIR})
#===================== LINKING LIBRARIES =======================#
target_link_libraries(untitled PRIVATE Qt6::Widgets Qt6::Core Qt6::Gui)
"
I tried searching other posts and qt website but found nothing I looked up the error but was unable to find where this function "WinMain" came from
A:
It looks like your CMakeLists.txt file is missing the line that specifies the source files for your project. The error message mentions the unresolved external symbol "main", which suggests that the linker is unable to find a main() function in your project. This may be because you have not specified any source files in your CMakeLists.txt file.
To fix this error, you will need to add a line to your CMakeLists.txt file that specifies the source files for your project. For example, if your project has a main.cpp file, you can add the following line to your CMakeLists.txt file:
add_executable(untitled main.cpp)
This line tells CMake to create an executable named "untitled" using the main.cpp file as the source. You will need to replace "main.cpp" with the actual names of the source files for your project.
Once you have added this line to your CMakeLists.txt file, you can try building your project again. This should resolve the error and allow your project to be built successfully.
-response generated by ChatGPT by OpenAI
|
Why do I keep getting lnK2019 error In clion using QT
|
I am trying to make a qt project in Clion but every time I try to run it it gives me this error it says there is a unresolved external in function WinMain but it doesn't exist
"
[1/1] Linking CXX executable untitled.exe
FAILED: untitled.exe
cmd.exe /C "cd . && "C:\Program Files\JetBrains\CLion 2022.2.4\bin\cmake\win\bin\cmake.exe" -E vs_link_exe --intdir=CMakeFiles\untitled.dir --rc=C:\PROGRA~2\WI3CF2~1\10\bin\100220~1.0\x64\rc.exe --mt=C:\PROGRA~2\WI3CF2~1\10\bin\100220~1.0\x64\mt.exe --manifests -- C:\PROGRA~1\MIB055~1\2022\COMMUN~1\VC\Tools\MSVC\1434~1.319\bin\Hostx64\x64\link.exe /nologo CMakeFiles\untitled.dir\untitled_autogen\mocs_compilation.cpp.obj /out:untitled.exe /implib:untitled.lib /pdb:untitled.pdb /version:0.0 /machine:x64 /debug /INCREMENTAL /subsystem:windows -DYNAMICBASE -NXCOMPAT -LARGEADDRESSAWARE C:\Qt\6.4.1\msvc2019_64\lib\Qt6Widgetsd.lib C:\Qt\6.4.1\msvc2019_64\lib\Qt6Guid.lib C:\Qt\6.4.1\msvc2019_64\lib\Qt6Cored.lib mpr.lib userenv.lib C:\Qt\6.4.1\msvc2019_64\lib\Qt6EntryPointd.lib shell32.lib d3d11.lib dxgi.lib dxguid.lib kernel32.lib user32.lib gdi32.lib winspool.lib shell32.lib ole32.lib oleaut32.lib uuid.lib comdlg32.lib advapi32.lib && cd ."
LINK Pass 1: command "C:\PROGRA~1\MIB055~1\2022\COMMUN~1\VC\Tools\MSVC\1434~1.319\bin\Hostx64\x64\link.exe /nologo CMakeFiles\untitled.dir\untitled_autogen\mocs_compilation.cpp.obj /out:untitled.exe /implib:untitled.lib /pdb:untitled.pdb /version:0.0 /machine:x64 /debug /INCREMENTAL /subsystem:windows -DYNAMICBASE -NXCOMPAT -LARGEADDRESSAWARE C:\Qt\6.4.1\msvc2019_64\lib\Qt6Widgetsd.lib C:\Qt\6.4.1\msvc2019_64\lib\Qt6Guid.lib C:\Qt\6.4.1\msvc2019_64\lib\Qt6Cored.lib mpr.lib userenv.lib C:\Qt\6.4.1\msvc2019_64\lib\Qt6EntryPointd.lib shell32.lib d3d11.lib dxgi.lib dxguid.lib kernel32.lib user32.lib gdi32.lib winspool.lib shell32.lib ole32.lib oleaut32.lib uuid.lib comdlg32.lib advapi32.lib /MANIFEST /MANIFESTFILE:CMakeFiles\untitled.dir/intermediate.manifest CMakeFiles\untitled.dir/manifest.res" failed (exit code 1120) with the following output:
Qt6EntryPointd.lib(qtentrypoint_win.cpp.obj) : error LNK2019: unresolved external symbol main referenced in function WinMain
untitled.exe : fatal error LNK1120: 1 unresolved externals
ninja: build stopped: subcommand failed."
"
here is my cmake file as well
"
cmake_minimum_required(VERSION 3.16)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_INCLUDE_CURRENT_DIR ON)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
if (WIN32)
project(untitled LANGUAGES CXX)
elseif(UNIX)
project(untitled)
endif()
set(CMAKE_CONFIGURATION_TYPES "Release;RelWithDebInfo" CACHE STRING "" FORCE)
#======================= INCLUSION OF Qt =======================#
set(CMAKE_PREFIX_PATH "C:/dev/vcpkg/ports")
find_package(Qt6 REQUIRED
COMPONENTS Core Widgets Gui
)
set(CMAKE_INCLUDE_CURRENT_DIR ON)
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)
set(CMAKE_AUTOUIC ON)
#=================== INCLUSION OF Project Files ====================#
set(FORMS_DIR "${CMAKE_SOURCE_DIR}/forms")
set(INCLUDE_DIR "${CMAKE_SOURCE_DIR}/include")
set(SOURCE_DIR "${CMAKE_SOURCE_DIR}/src")
include_directories(${FORMS_DIR})
include_directories(${INCLUDE_DIR})
include_directories(${SOURCE_DIR})
file(GLOB_RECURSE SOURCES
"${FORMS_DIR}/*.ui"
"${FORMS_DIR}/*.qrc"
"${INCLUDE_DIR}/*.h"
"${SOURCE_DIR}/*.cpp"
)
#=================== SETUP EXECTUABLE ====================#
# Enable debug logging on RELWITHDEBINFO configuration
set_property(DIRECTORY APPEND PROPERTY COMPILE_DEFINITIONS
$<$<CONFIG:RELWITHDEBINFO>:QT_MESSAGELOGCONTEXT>
)
# Add the forms directory to the AUTOUIC search paths
set(CMAKE_AUTOUIC_SEARCH_PATHS ${CMAKE_AUTOUIC_SEARCH_PATHS} ${FORMS_DIR})
# Add the executable
if (WIN32)
qt_add_executable(untitled WIN32 ${SOURCES})
elseif(UNIX)
qt_add_executable(untitled ${SOURCES})
endif()
# Add the target includes for MY_PROJECT
target_include_directories(untitled PRIVATE ${FORMS_DIR})
target_include_directories(untitled PRIVATE ${INCLUDE_DIR})
target_include_directories(untitled PRIVATE ${SOURCE_DIR})
#===================== LINKING LIBRARIES =======================#
target_link_libraries(untitled PRIVATE Qt6::Widgets Qt6::Core Qt6::Gui)
"
I tried searching other posts and qt website but found nothing I looked up the error but was unable to find where this function "WinMain" came from
|
[
"It looks like your CMakeLists.txt file is missing the line that specifies the source files for your project. The error message mentions the unresolved external symbol \"main\", which suggests that the linker is unable to find a main() function in your project. This may be because you have not specified any source files in your CMakeLists.txt file.\nTo fix this error, you will need to add a line to your CMakeLists.txt file that specifies the source files for your project. For example, if your project has a main.cpp file, you can add the following line to your CMakeLists.txt file:\nadd_executable(untitled main.cpp)\nThis line tells CMake to create an executable named \"untitled\" using the main.cpp file as the source. You will need to replace \"main.cpp\" with the actual names of the source files for your project.\nOnce you have added this line to your CMakeLists.txt file, you can try building your project again. This should resolve the error and allow your project to be built successfully.\n-response generated by ChatGPT by OpenAI\n"
] |
[
0
] |
[] |
[] |
[
"c++",
"qt"
] |
stackoverflow_0074669965_c++_qt.txt
|
Q:
How to fix the geom_col(width = 1) in R
I struggled to fit the geom_col(width = 1) in ggplot2.
Here are my codes:
df <- data.frame(Y = c(0.45, 0.25, 0.05, -0.05, -0.25, -0.45),
X = rep(9, n = 6))
df
library(dplyr)
library(ggplot2)
df %>%
mutate(color = case_when(Y %in% c(-0.45, 0.45, -0.25, 0.25) ~ '#6BD7AF',
TRUE ~ 'grey')) %>%
ggplot(aes(x = X, y = factor(Y), fill = color)) +
geom_col(width = 1) +
scale_fill_manual('', values = c('#6BD7AF' = '#6BD7AF', 'grey' = 'grey'),
labels = c('Incorrect', 'Correct')) +
theme_classic() +
labs(y = 'y', x = ' x') +
coord_cartesian(expand = FALSE, xlim = c(1, NA)) +
scale_x_continuous(breaks = seq(1, 9, by = 1))+
scale_y_discrete(labels = seq(-0.5, 0.5, by = 0.2))
I want to fit the grey area in my diagram exactly between -0.1 and +0.1. The codes work perfectly, but not sure why the grey does not fit between -0.1 and +0.1. I also want to use density and angle for the green colour.
A:
You are using a discrete scale, and the centre of bars will always be at the tick marks, so this probably isn't the way to go. A geom_rect would make more sense here. For density and angle fills, you will need ggpattern
library(ggplot2)
library(ggpattern)
df <- data.frame(xmin = rep(0, 3), xmax = rep(9, 3),
ymin = c(-Inf, -0.1, 0.1), ymax = c(-0.1, 0.1, Inf),
fill = c("Incorrect", "Correct", "Incorrect"))
ggplot(df) +
geom_rect_pattern(aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax,
pattern = fill, pattern_fill = fill, fill = fill),
pattern_colour = NA, pattern_angle = 45,
pattern_density = 0.3, pattern_spacing = 0.02) +
theme_classic() +
labs(y = 'y', x = ' x') +
coord_cartesian(expand = FALSE, xlim = c(1, NA)) +
scale_x_continuous(breaks = seq(1, 9, by = 1), limits = c(0, 9)) +
scale_y_continuous(limits = c(-0.5, 0.5), breaks = seq(-0.5, 0.5, 0.2)) +
scale_pattern_fill_manual(NULL, values = c("gray", '#6BD7AF')) +
scale_fill_manual(NULL, values = c("gray", "white")) +
scale_pattern_manual(NULL, values = c("none", "stripe"))
Created on 2022-12-03 with reprex v2.0.2
|
How to fix the geom_col(width = 1) in R
|
I struggled to fit the geom_col(width = 1) in ggplot2.
Here are my codes:
df <- data.frame(Y = c(0.45, 0.25, 0.05, -0.05, -0.25, -0.45),
X = rep(9, n = 6))
df
library(dplyr)
library(ggplot2)
df %>%
mutate(color = case_when(Y %in% c(-0.45, 0.45, -0.25, 0.25) ~ '#6BD7AF',
TRUE ~ 'grey')) %>%
ggplot(aes(x = X, y = factor(Y), fill = color)) +
geom_col(width = 1) +
scale_fill_manual('', values = c('#6BD7AF' = '#6BD7AF', 'grey' = 'grey'),
labels = c('Incorrect', 'Correct')) +
theme_classic() +
labs(y = 'y', x = ' x') +
coord_cartesian(expand = FALSE, xlim = c(1, NA)) +
scale_x_continuous(breaks = seq(1, 9, by = 1))+
scale_y_discrete(labels = seq(-0.5, 0.5, by = 0.2))
I want to fit the grey area in my diagram exactly between -0.1 and +0.1. The codes work perfectly, but not sure why the grey does not fit between -0.1 and +0.1. I also want to use density and angle for the green colour.
|
[
"You are using a discrete scale, and the centre of bars will always be at the tick marks, so this probably isn't the way to go. A geom_rect would make more sense here. For density and angle fills, you will need ggpattern\nlibrary(ggplot2)\nlibrary(ggpattern)\n\ndf <- data.frame(xmin = rep(0, 3), xmax = rep(9, 3), \n ymin = c(-Inf, -0.1, 0.1), ymax = c(-0.1, 0.1, Inf),\n fill = c(\"Incorrect\", \"Correct\", \"Incorrect\"))\n\nggplot(df) +\n geom_rect_pattern(aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax, \n pattern = fill, pattern_fill = fill, fill = fill),\n pattern_colour = NA, pattern_angle = 45,\n pattern_density = 0.3, pattern_spacing = 0.02) +\n theme_classic() +\n labs(y = 'y', x = ' x') +\n coord_cartesian(expand = FALSE, xlim = c(1, NA)) +\n scale_x_continuous(breaks = seq(1, 9, by = 1), limits = c(0, 9)) +\n scale_y_continuous(limits = c(-0.5, 0.5), breaks = seq(-0.5, 0.5, 0.2)) +\n scale_pattern_fill_manual(NULL, values = c(\"gray\", '#6BD7AF')) +\n scale_fill_manual(NULL, values = c(\"gray\", \"white\")) +\n scale_pattern_manual(NULL, values = c(\"none\", \"stripe\"))\n\n\nCreated on 2022-12-03 with reprex v2.0.2\n"
] |
[
2
] |
[] |
[] |
[
"ggplot2",
"r"
] |
stackoverflow_0074669805_ggplot2_r.txt
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.