instruction stringlengths 0 30k ⌀ |
|---|
|google-apps-script|google-slides| |
One option would be to pass a vector of colors to `hc_colors` where the of the colors is set according to the order of your categories:
``` r
library(highcharter)
colors <- df |>
dplyr::distinct(name, COLOR) |>
dplyr::arrange(name) |>
dplyr::pull(COLOR)
hchart(df,
"line",
hcaes(x = row_labels, y = y, group = name),
dataLabels = list(enabled = TRUE)
) %>%
hc_colors(color = colors)
```
<!-- --> |
null |
Solution to your problem:(MYSQL 8.0)
WITH CTE AS
(
SELECT dp1.DID,
dp1.Description,
dp1.uid as uid1,
dp2.uid as uid2,
COUNT(*) OVER(PARTITION BY dp1.DID,dp1.UID) as total_participants,
COUNT(CASE WHEN r.type in ('club member','family') or dp1.UID = dp2.UID THEN 1 END)
OVER(PARTITION BY dp1.DID,dp1.UID) as related_participants
FROM day_package dp1
LEFT JOIN day_package dp2
ON dp1.did = dp2.did
LEFT JOIN related r
ON dp1.UID = r.person1_uid AND dp2.UID = r.person2_UID
)
SELECT DISTINCT DID,
Description,
related_participants as Participant_Count
FROM CTE
WHERE related_participants = total_participants
AND total_participants != 1
ORDER BY DID,Participant_Count
DB Fiddle link - https://dbfiddle.uk/11xmARuy |
Toggle "conversation view" in Outlook with VBA |
|vba|outlook| |
The `causal_conv1d` implementation for Mamba comes from [this repo](https://github.com/Dao-AILab/causal-conv1d/tree/main), which implements the `causal_conv1d` operation using custom cuda kernels.
Cuda kernels can't run on Mac silicon. To run `causal_conv1d` on Mac silicon, you would need to rewrite the kernels in Metal or another Mac compatible framework.
To my knowledge a Mac compatible version does not currently exist. |
at the top
public TMP_Text savingIndicatorText;
start
private void Start()
{
// Initialize savingIndicatorText to be fully transparent initially
SetTextAlpha(savingIndicatorText, 0f);
// Start autosave with a small initial delay and repeat every 10 seconds
InvokeRepeating(nameof(AutosaveNotes), 2f, 10f);
}
then the two methods for the fade in out:
public IEnumerator FadeTextToFullAlpha(float t, TMP_Text i)
{
// Start fading in
i.color = new Color(i.color.r, i.color.g, i.color.b, 0);
while (i.color.a < 1.0f)
{
SetTextAlpha(i, i.color.a + (Time.deltaTime / t));
yield return null;
}
// Wait for a moment when fully visible
yield return new WaitForSeconds(1f);
// Start fading out
while (i.color.a > 0.0f)
{
SetTextAlpha(i, i.color.a - (Time.deltaTime / t));
yield return null;
}
}
and
private void SetTextAlpha(TMP_Text textElement, float alpha)
{
textElement.color = new Color(textElement.color.r, textElement.color.g, textElement.color.b, alpha);
}
and autosavenotes
private void AutosaveNotes()
{
if (saveToFile && inputField.gameObject.activeSelf)
{
SaveToFile(inputField.text);
StartCoroutine(FadeTextToFullAlpha(1f, savingIndicatorText));
}
}
what it does now it's fading out the text once one time.
and i want it to fade out/in or in/out depending on setting time for example 3 so it will fade out/in for 3 seconds. |
How to use invokerepeating and make ui text fade in/out over time? |
|c#|unity-game-engine| |
```
#include <msp430.h>
static int next = 0;
#pragma vector=USCI_A0_VECTOR
interrupt void bc_uart_irq(void) {
int transmit_flag = UCA0IFG & UCTXIFG;
if (transmit_flag && next == 0) {
next = 1;
UCA0TXBUF = 0x01; // should clear UCTXIFG
} else if (transmit_flag) {
next = 0;
UCA0TXBUF = 0x55; // should clear UCTXIFG (doesnt!)
}
}
/**
* main.c
*/
int main(void)
{
WDTCTL = WDTPW | WDTHOLD; // stop watchdog timer
// Setup UART pins
P3SEL |= 0x18; // default UCA0TXD/UCA0RXD on P3.3/4
P3DIR |= BIT3 + BIT4;
// source TA0 from SMCLK for debugging
TA0CTL = 0x0220;
UCA0CTL1 |= UCSWRST;
// source USCIA0 from SMCLK
UCA0CTL1 |= UCSSEL__SMCLK;
// set USCI module to UART mode
UCA0CTL0 &= ~UCSYNC;
// configure UART
UCA0CTL0 &= ~UCPEN; // no parity bit
UCA0CTL0 &= ~UC7BIT; // 8-bit data
UCA0CTL0 &= ~UCMSB; // LSB first
UCA0CTL0 &= ~UCMODE0; // UART mode (00)
UCA0CTL0 &= ~UCMODE1;
// Set baud rate to 9600 (br = 104, brs = 1, brf = 0)
UCA0BR0 = 107;
UCA0BR1 = 0;
UCA0MCTL = 0x02; // UCBRSx = 1
UCA0CTL1 &= ~UCSWRST;
UCA0IE |= 0xFFFF; // enable tx and rx interrupts
__bis_SR_register(GIE);
while(1) {}
return 0;
}
```
I've spent a while debugging this, in all cases dumping data to the transmit buffer does not clear the flag automatically (I've also tried clearing it myself in the interrupt) and does not set UCBUSY high. I also tried using the A1 UART module instead of A0, moving the pinout to 4.4/5 (as I've seen in some other questions), different clocks (I originally had ACLK), as well as setting the UCLISTEN bit high. I'm not sure what else I can try as this seems the same as code I've seen other questions about. I've confirmed that SMCLK is running as the timer goes up with each step of the debugger; the most reasonable culprit is that the clock is simply not getting to the USCI peripheral, but I don't know if that is true nor how to test it. (I'm using CCS and the only weird thing I've gotten is that the compiler yells at me if the data memory model is not small (code is large)). |
{"Voters":[{"Id":22180364,"DisplayName":"Jan"},{"Id":2530121,"DisplayName":"L Tyrone"},{"Id":16217248,"DisplayName":"CPlus"}]} |
{"Voters":[{"Id":22180364,"DisplayName":"Jan"},{"Id":354577,"DisplayName":"Chris"},{"Id":16217248,"DisplayName":"CPlus"}],"SiteSpecificCloseReasonIds":[13]} |
{"Voters":[{"Id":5514747,"DisplayName":"Harun24hr"}],"DeleteType":1} |
I'm developing the following `Modal` in a [Storybook](https://storybook.js.org/) story:
```
import React from 'react';
import type { Meta, StoryObj } from '@storybook/react';
import { Modal } from '@repo/ui/Modal';
import Title from '@repo/ui/Title';
import Field from '@repo/ui/Field';
import { DialogHeader } from '@repo/ui/radix/dialog';
type ItemModalProps = {
avatarUrl: string;
maxWidth?: 'sm' | 'md' | 'lg';
isOpen: boolean;
hasFullImage?: boolean;
onCloseModal?: () => void;
};
const ItemModal: React.FC<ItemModalProps> = ({
avatarUrl,
maxWidth = 'sm',
isOpen,
hasFullImage,
onCloseModal = () => {},
}) => (
<Modal
isOpen={isOpen}
onCloseModal={onCloseModal}
hasFullImage={hasFullImage}
maxWidth={maxWidth}
>
<DialogHeader className="relative h-60">
<img src={avatarUrl} className="absolute h-full w-full object-cover" />
</DialogHeader>
<div className="flex flex-col items-center space-y-4 p-6">
<Title>Test</Title>
<div className="grid grid-cols-2 gap-x-10 gap-y-2">
<Field label="Name" text="Name" />
</div>
</div>
</Modal>
);
const meta: Meta<typeof ItemModal> = {
title: 'Example/Modal',
component: ItemModal,
};
export default meta;
type Story = StoryObj<typeof ItemModal>;
export const DefaultModal: Story = {
args: {
avatarUrl: 'https://placehold.co/100',
isOpen: true,
hasFullImage: true,
onCloseModal: () => {},
},
};
```
How to change the code so that `onCloseModal` makes `isOpen` to become `false`? |
I'm working on developing a wake word model for my AI assistant. My model architecture includes an LSTM layer to process audio data, followed by a Linear Layer. However, I'm encountering an unexpected output shape from the Linear Layer, which is causing confusion.
After passing the LSTM output (shape: 4, 32, 32) to the Linear Layer, I expected an output shape of (4, 32, 1). However, the actual output shape is (4, 32, 1).
In my binary classification task, I aim to distinguish between two classes: 0 for "do not wake up" and 1 for "wake up the AI." My batch size is 32, and I anticipated the output to be in the shape (32, 1) to represent one prediction for each audio MFCC input.
Could someone advise on the correct configuration of the Linear Layer or any processing steps needed to achieve the desired output shape of (32, 1)? Any insights or code examples would be greatly appreciated. |
I have a dashboard in **Datadog** that uses a "status" variable to filter the log messages. This works fine for the majority of the entries.
There are some actual errors that do not have status=Error. They are logged as Info.
When I select "Error" from the variable dropdown I would like to get the entries with status=Error and any other entry (regardless of the status) which has the work "Error" as part of the content. If I select status="Debug" or status="Info" I would like to get the entries that match that status.
I can't figure out how to construct the query. Please, help.
I tried different queries but they did not produce the result I wanted. I am new to datadog, so I am not sure how to construct the query. |
'bun' is not recognized as an internal or external command |
|windows|tailwind-css|flowbite| |
I need to print the bounding box coordinates of a walking person in a video. Using YOLOv5 I detect the persons in the video. Each person is tracked. I need to print each person's bounding box coordinate with the frame number. Using Python how to do this.
The following is the code to detect, track persons and display coordinates in a video using YOLOv5.
```
#display bounding boxes coordinates
import cv2
from ultralytics import YOLO
# Load the YOLOv8 model
model = YOLO('yolov8n.pt')
# Open the video file
cap = cv2.VideoCapture("Shoplifting001_x264_15.mp4")
#get total frames
frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
print(f"Frames count: {frame_count}")
# Initialize the frame id
frame_id = 0
# Loop through the video frames
while cap.isOpened():
# Read a frame from the video
success, frame = cap.read()
if success:
# Run YOLOv8 tracking on the frame, persisting tracks between frames
results = model.track(frame, persist=True,classes=[0])
# Visualize the results on the frame
annotated_frame = results[0].plot()
# Print the bounding box coordinates of each person in the frame
print(f"Frame id: {frame_id}")
for result in results:
for r in result.boxes.data.tolist():
if len(r) == 7:
x1, y1, x2, y2, person_id, score, class_id = r
print(r)
else:
print(r)
# Display the annotated frame
cv2.imshow("YOLOv5 Tracking", annotated_frame)
# Increment the frame id
frame_id += 1
# Break the loop if 'q' is pressed
if cv2.waitKey(1) & 0xFF == ord("q"):
break
else: # Break the loop if the end of the video is reached
break
# Release the video capture object and close the display window
cap.release()
cv2.destroyAllWindows()
```
The above code is working and display the coordinates of tracked persons.
But the problem is in some videos it is not working properly
```
0: 384x640 6 persons, 1292.9ms Speed: 370.7ms preprocess, 1292.9ms inference, 20.8ms postprocess per image at shape (1, 3, 384, 640) Frame id: 0 [849.5707397460938, 103.34817504882812, 996.0990600585938, 371.2213439941406, 1.0, 0.9133888483047485, 0.0] [106.60043334960938, 74.8958740234375, 286.6423645019531, 562.144287109375, 2.0, 0.8527513742446899, 0.0] [221.3446044921875, 60.8421630859375, 354.4775390625, 513.18017578125, 3.0, 0.7955091595649719, 0.0] [472.7821044921875, 92.33056640625, 725.2569580078125, 632.264404296875, 4.0, 0.7659056782722473, 0.0] [722.457763671875, 222.010986328125, 885.9102783203125, 496.00372314453125, 5.0, 0.7482866644859314, 0.0] [371.93310546875, 46.2138671875, 599.2041625976562, 437.1387939453125, 6.0, 0.7454277873039246, 0.0]
```
This output is correct.
But for another video there are only three people in the video but at the beginning of the video at 1st frame identify as 6 person.
```
0: 480x640 6 persons, 810.5ms
Speed: 8.0ms preprocess, 810.5ms inference, 8.9ms postprocess per image at shape (1, 3, 480, 640)
Frame id: 0
[0.0, 10.708396911621094, 37.77726745605469, 123.68929290771484, 0.36418795585632324, 0.0]
[183.0453338623047, 82.82539367675781, 231.1952667236328, 151.8341522216797, 0.2975049912929535, 0.0]
[154.15158081054688, 74.86528778076172, 231.10934448242188, 186.2017822265625, 0.23649221658706665, 0.0]
[145.61187744140625, 69.76246643066406, 194.42532348632812, 150.91973876953125, 0.16918501257896423, 0.0]
[177.25042724609375, 82.43289947509766, 266.5430908203125, 182.33889770507812, 0.131477952003479, 0.0]
[145.285400390625, 69.32669067382812, 214.907470703125, 184.0771026611328, 0.12087596207857132, 0.0]
```
Also, the output does not show the person ID here. Only display coordinates, confidence score, and class id. What is the reason for that?
|
```
data(murders)
murders_2 <- murders %>%
mutate(rate=total/population*100000) %>%
mutate(idx=case_when(rate < median(rate) ~ "low",
TRUE ~ "high")) %>%
select(state, region, rate, idx) %>%
group_by(idx)
# group_by(idx) is not applicable.
```
What's the problem?
I hope the results are sorted according to idx |
{"Voters":[{"Id":23836145,"DisplayName":"Sonic"}],"DeleteType":1} |
I'm using magento 2.4.2-p1 and getting this error continously in my app as exceptions.
Report ID: webapi-6605b783361ad; Message: Notice: fil
e_get_contents(): file created in the system's temporary directory in /bitnami/magento/ven
dor/laminas/laminas-http/src/PhpEnvironment/Request.php on line 96
Why these errors are happening, anyone have idea? |
file_get_contents(): file created in the system's temporary directory error in Magento |
|magento|laminas| |
null |
You have a typo in your code.
<br>It must be `classpath("com.google.gms:google-services:4.4.1"` instead of `classpath("com.google.gms.google-services:4.4.1"`.
<br>
Notice the symbol after `gms`. |
I've downloaded **SFML-2.6.1** and created Xcode project from template on my **M1 Mac**. Although project is building, it can not run, raising this error in the **Xcode** terminal:
```
dyld[7793]: Library not loaded: @rpath/sfml-system.framework/Versions/2.6.1/sfml-system
Referenced from: <1E3396AD-BA26-30F7-9B22-99E9329A24A5> /Users/zolars/Library/
Developer/Xcode/DerivedData/RayMarching-ahreigxcnvvlrmauhbbbcgvxsxku/Build/Products/Debug/RayMarching.app/Contents/MacOS/RayMarching
Reason: tried: '/Users/zolars/Library/Developer/Xcode/DerivedData/RayMarching-ahreigxcnvvlrmauhbbbcgvxsxku/
Build/Products/Debug/sfml-system.framework/Versions/2.6.1/sfml-system' (no such file),
'/Users/zolars/Library/Developer/Xcode/DerivedData/RayMarching-ahreigxcnvvlrmauhbbbcgvxsxku/
Build/Products/Debug/RayMarching.app/Contents/MacOS/../Frameworks/sfml-system.framework/Versions/2.6.1/sfml-system' (no such file),
'/Users/zolars/Library/Developer/Xcode/DerivedData/RayMarching-ahreigxcnvvlrmauhbbbcgvxsxku/
Build/Products/Debug/RayMarching.app/Contents/MacOS/../Frameworks/sfml-system.framework/Versions/2.6.1/sfml-system' (no such file)
```
I searched internet about similar errors but without any luck so far.
Can anybody help me? |
function Parent() {
return (
//...
<View>
onLayout={event=>{
const { width, height } = event.nativeEvent.layout
}}
<Child/>
</View>
//...
)
You can retrieve the actual component width and height by implementing onLayout prop on the wrapper component of your child component. Then you should save them as either state or ref variable according use case. |
EDIT.
This is a tcl tk bug in Windows. This can be seen by double clicking on the window title.
```
from tkinter import *
def window_clicked(event):
print("window_clicked", event.x, event.y)
root = Tk()
root.geometry("600x300")
root.bind("<Button-1>", window_clicked)
root.mainloop()
-------------------
window_clicked 418 99
window_clicked 423 77
window_clicked 489 93
```
An event is logged that should not occur. |
I've been struggling with this issue for two days and still haven't found a solution. I would be thrilled if you could help. I'm using PrelineUI in my project.
The input select looks like this:
<select multiple wire:model="category" id="category"
data-hs-select='{
"placeholder": "Select multiple options...",
"toggleTag": "<button type=\"button\"></button>",
}'
class="hidden">
<option value="">Choose</option>
@foreach ($servicecategories as $category)
<option value="{{ $category->id }}">{{ $category->title }}</option>
@endforeach
</select>
$category comes null on the Component side because I'm using PrelineUI.
On the JavaScript side, I can get the value like this:
const category = HSSelect.getInstance('#category').value;
But I needed help getting this category value on the Component side. I also tried the @this.set('getCategory', category) method, but it failed. I'm waiting for your help. Thank you in advance.
@this.set('getCategory', category)
Livewire.emit('getCategory', category) //livewire.emit is not a function
|
Laravel Livewire get data from blade |
I have a dgrid -> Cache store application to which I want to add sortable columns. The problem is that the REST provider cannot do the sorting, so I want any sort() request to trigger a fetch of the entire contents, and then further sorting and fetching to be done locally in memory.
In other words, before a sort is requested, I am happy for the Request store to query for the the desired ranges, but there cannon be rest queries passing sort keys to the server.
I have been mucking around with canCacheQuery, but I can't seem to get it to behave as required.
Can someone suggest a way to hook this up?
|
Caching store that fetches all when a sort is requ |
|sorting|caching|dstore| |
I would like some help with a problem that has had stumped me for two days.
I have 'results' table like this:
```
result_id competition_id competitor_id competitor_ranking
1 1 1 0.1
2 1 2 0.4
3 1 3 0.2
4 1 4 0.3
5 2 1 0.4
6 2 2 0.1
7 2 3 0.2
8 2 5 0.3
9 3 3 0.1
10 3 4 0.4
11 3 5 0.2
12 3 6 0.3
```
From the 'results' table I want to get a grouped ranking of competitors with penalties points (+1.0) included, like this:
```
competitor_id competitions rankings ranking_with_penalties
1 1; 2; M 0.1; 0.4 0.1; 0.4; +1.0
2 1; 2; M 0.4; 0.1 0.4; 0.1; +1.0
3 1; 2; 3 0.2; 0.2; 0.1 0.2; 0.2; 0.1
4 1; M; 3 0.3; 0.4 0.3; +1.0; 0.4
5 M; 2; 3 0.3; 0.2 +1.0; 0.3; 0.2
6 3 M; M; 0.3 0.3; +1.0; +1.0
```
I know that group_concat function is an aggregate function that concatenates all non-null values in a column. I understand that the task is quite trivial. But I can not solve it.
```
CREATE TABLE results (
result_id INTEGER PRIMARY KEY,
competition_id INTEGER,
competitor_id INTEGER,
competitor_ranking
);
INSERT INTO results(competition_id, competitor_id, competitor_ranking) VALUES
(1, 1, 0.1), (1, 2, 0.4), (1, 3, 0.2), (1, 4, 0.3),
(2, 1, 0.4), (2, 2, 0.1), (2, 3, 0.2), (2, 5, 0.3),
(3, 3, 0.1), (3, 4, 0.4), (3, 5, 0.2), (3, 6, 0.3)
;
SELECT
competitor_id,
group_concat(coalesce(competition_id, NULL), '; ') AS competitions,
group_concat(coalesce(competitor_ranking, NULL), '; ') AS rankings,
group_concat(coalesce(NULLIF(competitor_ranking, NULL), '+1.0'), '; ') AS ranking_with_penalties
FROM results
GROUP BY competitor_id;
```
I'm looking forward to any help.
|
MSP430F5529 on the MSPEXP430F5529LP: UART is not actually transmitting despite seemingly correct setup. What is wrong? |
|embedded|msp430| |
null |
When we call vectorized function for some vector, for some reason it is called twice for the first vector element.
What is the reason, and can we get rid of this strange effect (e.g. when this function needs to have some side effect, e.g. counts some sum etc)
Example:
```python
import numpy
@numpy.vectorize
def test(x):
print(x)
test([1,2,3])
```
Result:
```
1
1
2
3
```
numpy 1.26.4 |
Why numpy.vectorize calls vectorized function more times than elements in the vector? |
|python|numpy| |
I want to know is it possible to create anonymous Blade component (without controller) and that it has some variable and method which is called inside it and changes variable state.
For example: I have few links (like nav-bar) and on click, I want to change activeTab value.
I noticed it's always looking for called function inside controller and I don't know how to change it. |
Function in anonymous Blade component |
|php|laravel|laravel-blade|anonymous-class| |
null |
### The problem
When I use **the portal protocol of yarn** to add my **local package** it just gets installed from the npm registry instead.
I want to develop said package so I need to be working with the latest code not the one published to the registry.
### What I tried
I tried using `yarn add vexflow-repl@portal:../../vexflow-repl` by following the example provided by [yarn's official website](https://yarnpkg.com/protocol/portal).
Before I run the above command my dependencies look like this:
[![dependencies before][1]][1]
After I run the command they look like this:
[![dependencies after][2]][2]
Nothing else changed in my **package.json** and the package is installed from the **npm registry** instead of my local folder.
### Observations
If I instead use `yarn add file:..\..\vexflow-repl` the package does get installed from my local folder and my dependencies look like this:
[![dependencies after adding with file protocol][3]][3]
With **yarn's file protocol** I can work as I intended with the latest code from my package at the expense of duplicate files and some overhead.
### System information
I use windows.
[1]: https://i.stack.imgur.com/c8tvg.png
[2]: https://i.stack.imgur.com/7JAln.png
[3]: https://i.stack.imgur.com/ksEDz.png |
How to use yarn's portal protocol? |
|npm|yarnpkg-v2| |
|python|if-statement| |
Correct - "I found that guest users are only to manage tenants".
B2C does not have a concept of guest users as "users". Guest users are simply admins. on the B2C portal.
To add custom claims, you can either add them in a user flow or use extension attributes in a custom flow.
Refer [here][1] for both options.
[1]: https://learn.microsoft.com/en-us/azure/active-directory-b2c/user-flow-custom-attributes?pivots=b2c-user-flow
|
'New messages' separator like WhatsApp |
|flutter|dart| |
The error in your comment says `save_frequency` is an unknown keyword for `ModelCheckpoint`. [In the docs][1] it shows that `ModelCheckpoint` expects `save_freq` as an argument. Also beware that if you set an integer for `save_freq`, it saves each x batches, not epochs. If you just want it to save every epoch, you can set
```python
save_freq='epoch'
```
which is also the default.
Why this woked in 2.15, I can not say, the docs for 2.15 also have `save_freq` in it. Maybe it was compatible with `save_frequency` in the background up to that point. It is better to use `save_freq`, as it is officially supported.
If you want to change a package version in colab, use
%pip install -U "tensorflow~=2.15.0"
`%` enables the pip command outside the python environment, `-U` upgrades (or in your case downgrades) existing versions and you need `""` and either == or ~= for the version numbers. == for exact this version and ~= for, in this example "2.15.x", where x is the newest version.
[1]: https://www.tensorflow.org/api_docs/python/tf/keras/callbacks/ModelCheckpoint#args |
The code `char *line; line = strncpy(line, req, size);` has undefined behavior: `line` is an uninitialized pointer, so you cannot copy anything to it.
My recommendation is [**you should never use `strncpy`**][1]: it does not do what you think.
In your code, you should instead use `char *line = strndup(req, size);` which allocates memory and copies the string fragment to it. The memory should be freed after use with `free(line)`.
`strndup()` is part of POSIX so it is available on most systems, but it your target does not have it, it can be defined this way:
```
#include <stdlib.h>
char *strndup(const char *s, size_t n) {
char *p;
size_t i;
for (i = 0; i < n && s[i] != '\0'; i++)
continue;
p = malloc(i + 1);
if (p != NULL) {
memory(p, s, i);
p[i] = '\0';
}
return p;
}
```
There are other problems in your code:
- `strcmp(req, "GET")` returns `0` is the strings have the same characters, so you should write:
```
if (strcmp(req, "GET") == 0) {
return GET;
}
```
or
```
if (!strcmp(req, "GET")) {
return GET;
}
```
- you should reverse the order of the tests in `while((*(req + size) != '\n') && (size < req_size))` to avoid accessing `req[req_size]`.
* in `accept_incoming_request` you should allocate the destination array with an extra byte for the null terminator and set this null byte at the end of the received packet with:
buffer[recvd_bytes] = '\0';
[1]: https://randomascii.wordpress.com/2013/04/03/stop-using-strncpy-already/ |
This is the script to run typescript project:
node --require ts-node/register --loader=ts-node/esm --trace-warnings ./src/home-client.ts
With pm2, I tried:
pm2 start ./src/home-client.ts --node-args="--require ts-node/register --loader=ts-node/esm --trace-warnings"
Logs display an error: `0|home-cli | error: Script not found "ts-node/register"`
Whats the correct way to run typescrpit project with pm2 and node?
|
running typescript with pm2, node and ts-node as argument |
So Leadership Team is how I want the end result
` atGroupsDefaultColors: {
LeadershipTeam: "rgba(255, 3, 3, 1)",
DeveloperTeam: "rgba(230, 83, 0, 0.5)",
ManagementTeam: "rgba(0, 255, 145, 0.5)",
SnrAdmin: "rgba(11, 175, 255, 0.5)",
Admin: "rgba(11, 175, 255, 0.5)",
SnrModerator: "rgba(11, 175, 255, 0.5)",
Moderator: "rgba(11, 175, 255, 0.5)",
trialMod: "rgba(11, 175, 255, 0.5)",
},
staffTeamPage: {
LeadershipTeam: [`
Tried ChatGPT didn't come up with anything useful. |
I want to add a space inbetween the group and team |
|javascript| |
null |
I'm working on developing a wake word model for my AI assistant. My model architecture includes an LSTM layer to process audio data, followed by a Linear Layer. However, I'm encountering an unexpected output shape from the Linear Layer, which is causing confusion.
After passing the LSTM output (shape: 4, 32, 32) to the Linear Layer, I expected an output shape of (4, 32, 1). However, the actual output shape is (4, 32, 1).
In my binary classification task, I aim to distinguish between two classes: 0 for "do not wake up" and 1 for "wake up the AI." My batch size is 32, and I anticipated the output to be in the shape (32, 1) to represent one prediction for each audio MFCC input.
Could someone advise on the correct configuration of the Linear Layer or any processing steps needed to achieve the desired output shape of (32, 1)? Any insights or code examples would be greatly appreciated. Below is my model code for reference:
```python
class LSTMWakeWord(nn.Module):
def __init__(self,input_size,hidden_size,num_layers,dropout,bidirectional,num_of_classes, device='cpu'):
super(LSTMWakeWord, self).__init__()
self.input_size = input_size
self.hidden_size = hidden_size
self.num_layers = num_layers
self.device = device
self.bidirectional = bidirectional
self.directions = 2 if bidirectional else 1
self.lstm = nn.LSTM(input_size=input_size,
hidden_size = hidden_size,
num_layers = num_layers,
dropout=dropout,
bidirectional=bidirectional,
batch_first=True)
self.layernorm = nn.LayerNorm(input_size)
self.classifier = nn.Linear(hidden_size , num_of_classes)
def _init_hidden(self,batch_size):
n, d, hs = self.num_layers, self.directions, self.hidden_size
return (torch.zeros(n * d, batch_size, hs).to(self.device),
torch.zeros(n * d, batch_size, hs).to(self.device))
def forward(self,x):
# the values with e+xxx are gone. so it normalizes the values
x = self.layernorm(x)
# x shape -> feature(n_mfcc),batch,seq_len(time)
hidden = self._init_hidden(x.size()[0])
out, (hn, cn) = self.lstm(x, hidden)
print("hn "+str(hn.shape))# directions∗num_layers, batch, hidden_size
#print("out " + str(out.shape))# batch, seq_len, direction(2 or 1)*hidden_size
out = self.classifier(hn)
print("out2 " + str(out.shape))
return out
```
I'd greatly appreciate any insights or guidance on how to handle the Linear Layer output for binary classification. |
|sql|sqlite|group-by|ranking|group-concat| |
I've encountered an issue with my Node.js Telegram bot. The bot is responsible for sending approximately 1000 requests per second. Given Node.js's reputation for fast request handling, it seemed like the ideal choice for this task.
I've set up a cronjob to periodically check the getConnectionCount result every 2 seconds. Generally, this function returns N1->0, indicating that everything is functioning smoothly. However, during periods of exceptionally high usage, I've noticed that getConnectionCount returns unusually high results, such as:
> 14.03 05:07:41 N95->1431
>
> 14.03 05:07:43 N81->1440
>
> 14.03 05:07:45 N99->1976
>
> 14.03 05:07:47 N96->1437
>
> 14.03 05:07:49 N100->1979
>
> 14.03 05:07:51 N84->1455
>
> 14.03 05:07:53 N101->1977
>
> 14.03 05:07:55 N101->1992
Initially, I suspected that these spikes were due to latency issues with the Telegram server. However, upon further investigation, I found that sending curl requests (e.g., sendMessage) to the Telegram server directly from the same server yielded consistently fast responses.
Interestingly, a quick remedy for this issue is to simply restart the Node.js app using pm2 restart app. After the restart, the bot resumes normal operation, with getConnectionCount consistently returning N1->0.
I'm puzzled as to why these requests get stuck after some time, despite the server being capable of handling the same volume of requests. What might be causing this?
My node app code:
var express = require('express');
const axios = require("axios");
const Noderavel = require("@movilizame/noderavel");
const nodelaravel = require("node-laravel-queue");
const {uuid} = require("node-laravel-queue/lib/tools");
const redis = require("redis");
const {serialize} = require("php-serialize");
var app = express();
app.use(express.json({limit: '100mb'}));
app.use(express.urlencoded({limit: '100mb', extended: true, parameterLimit: 50000}));
const nocache = require('nocache');
const processId = process.pid;
app.use(nocache());
app.use(function (err, req, res, next) {
console.error(err.stack);
res.status(500).send('Something broke!');
});
let connectionCount = 0;
let pendingCount = 0;
// Middleware to track connections
app.use((req, res, next) => {
connectionCount++;
res.on('finish', () => {
connectionCount--;
});
next();
});
app.get("/getConnectionCount", function (req, res) {
res.send(connectionCount.toString() + "->" + pendingCount.toString());
});
async function sendPostRequest(url, postData) {
try {
pendingCount++;
// Make the POST request using axios
const response = await axios.post(url, postData);
pendingCount--;
return response.data;
// console.log(response.data);
} catch (error) {
pendingCount--;
return error.response ? error.response.data : error.message;
}
}
app.post('/sendRequest/:bot_token', async function (req, res) {
// for (let index = 0; index < 1e7; index++);
let bot_token = req.params['bot_token'];
const postData = req.body;
let method = postData.method;
let data = postData.data;
let get_result = parseInt(postData.get_result);
let url = "https://api.telegram.org/bot" + bot_token + "/" + method;
if (get_result == 1) {
res.send(await sendPostRequest(url, data));
return;
}
sendPostRequest(url, data);
res.send("1");
});
var server = app.listen(3000, function () {
console.log(`Server Started in process ${processId}`);
console.log('Example app listening on port 3000!');
});
server.keepAliveTimeout = 65000; // Ensure all inactive connections are terminated by the ALB, by setting this a few seconds higher than the ALB idle timeout
server.headersTimeout = 66000; // Ensure the headersTimeout is set higher than the keepAliveTimeout due to this nodejs regression bug: https://github.com/nodejs/node/issues/27363
server.setTimeout(10000);
|
I am trying to do web scraping to download a file from MS webpage. I am using Selenium webdriver to achieve this using chrome. But whatever I do, the downloaded file automatically gets saved under the default Downloads folder. Below is the code I am using to achieve this, with Selenium v4.11.2
```
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("--headless")
chrome_options.add_argument("window-size=1900,1080");
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument("--disable-dev-shm-usage")
chrome_prefs = {"download.default_directory": download_dir, "download.directory_upgrade": True, "savefile.default_directory": download_dir}
chrome_options.experimental_options["prefs"] = chrome_prefs
#service = Service(executable_path='C:\Python_Works\chromedriver-win64\chromedriver.exe')
options = webdriver.ChromeOptions()
#driver = webdriver.Chrome(service=service, options=options)
driver = webdriver.Chrome(options=options)
driver.get(url)
time.sleep(5)
```
Selenium version on my computer:[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/nbIP9.png
Could someone please advise where exactly I am wrong here. Do I need to have admin privileges to change the default download directory, as this is my work laptop? |
Default Download DirectoryNot changing with Selenium Webdriver |
|selenium-webdriver|selenium-chromedriver| |
I have a Yii2 app. And I try to add the patterns array in the urlManager of web.php. And I serached a lot and fount a lot of links with the correct soltuion. For example:
```
https://stackoverflow.com/questions/41873686/yii2-apply-custom-url-rule-class
https://www.yiiframework.com/doc/guide/2.0/en/runtime-routing
```
But It didn't resolved the issue.
So if I do it like:
```
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
'class' => 'yii\rest\UrlRule',
'controller' => 'v1/user',
'POST' => 'v1/user/signup',
'POST' => 'v1/user/login',
],
],
```
And in postman I do a post on this url: ```http://localhost:8080/v1/user/login```
everything works fine. But if I do this:
```
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
'class' => 'yii\rest\UrlRule',
'controller' => 'v1/user',
'patterns' => [
'POST' => 'signup',
'POST login' => 'login',
'OPTIONS login' => 'options',
],
],
],
```
the whole web.php file looks:
```
<?php
// phpcs:ignoreFile
$params = require __DIR__ . '/params.php';
$db = require __DIR__ . '/db.php';
$config = [
'id' => 'basic',
'name' => 'internetsuite 2.0',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'aliases' => [
'@bower' => '@vendor/bower-asset',
'@npm' => '@vendor/npm-asset',
],
'modules' => [
'v1' => [
'class' => 'app\modules\v1\Module',
],
],
'components' => [
'request' => [
'parsers' => [
'application/json' => 'yii\web\JsonParser',
],
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => 'OEtCunrAfQNETtmUSDnZw1JPHTB44i3A',
],
'cache' => [
'class' => 'yii\caching\FileCache',
],
'user' => [
'identityClass' => 'app\models\User',
'enableAutoLogin' => true,
],
'errorHandler' => [
'errorAction' => 'site/error',
],
'mailer' => [
'class' => \yii\symfonymailer\Mailer::class,
'viewPath' => '@app/mail',
// send all mails to a file by default.
'useFileTransport' => true,
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'db' => $db,
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'enableStrictParsing' => true,
'rules' => [[
'class' => 'yii\rest\UrlRule',
'controller' => 'v1/user',
'pluralize' => false,
],
'extraPatterns' => [
'OPTIONS {login}' => 'options',
'POST signup' => 'signup',
'POST login' => 'login',
],
],
],
],
'params' => $params,
];
if (YII_ENV_DEV) {
// configuration adjustments for 'dev' environment
$config['bootstrap'][] = 'debug';
$config['modules']['debug'] = [
'class' => 'yii\debug\Module',
// uncomment the following to add your IP if you are not connecting from localhost.
//'allowedIPs' => ['127.0.0.1', '::1'],
];
$config['bootstrap'][] = 'gii';
$config['modules']['gii'] = [
'class' => 'yii\gii\Module',
// uncomment the following to add your IP if you are not connecting from localhost.
//'allowedIPs' => ['127.0.0.1', '::1'],
];
}
return $config;
```
I get this error:
```
Unknown Property – yii\base\UnknownPropertyException
Setting unknown property: yii\web\UrlRule::POST
```
And I need the OPTIONS parameter because I ccall an api call from an react app.
Question: how to implement the pattern in the urlManager correctly? |
Handling thousands of async POST requests in Express.js |
If you post the actual command stream, I can test it for you.
Or use a SW TPM to debug, e.g., https://github.com/kgoldman/ibmswtpm2.
On Windows, the MS Store has a command decoder that might help. |
I have this search box which is expanding when activated.
However, I would like to make the search box overflow other content on the page.
The search box is inside a Bootstrap column - how can I make it expand break out of it?
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
.search-area {
transition: all .3s ease-in;
width: 3rem
}
.search-area:focus-within,
.search-area:hover {
width: 100%;
}
.page-searchform {
position: relative
}
.header-search {
padding-right: 2rem;
border: 0;
background-color: #fff;
}
.header-search-btn {
position: absolute;
top: 50%;
right: 0;
transform: translateY(-50%);
display: flex;
align-items: center;
justify-content: center;
}
/* Presentation onæly */
.row {
background: #f8f9fa;
margin-top: 20px;
}
.col {
padding: 10px;
border: 1px solid #ccc;
}
<!-- language: lang-html -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css">
<div class="container">
<div class="row">
<div class="col col-10">
Column 1 - Make search input overflow me!
</div>
<div class="col d-flex justify-content-end align-self-center">
<div class="search-area">
<form class="page-searchform" action="" method="get">
<label for="headerSearch" class="visually-hidden"></label>
<input name="" id="headerSearch" class="header-search form-control" type="search" placeholder="Search...">
<button class="btn header-search-btn" type="submit" id="headerSearchBtn">Go
</button>
</form>
</div>
</div>
</div>
</div>
<!-- end snippet -->
[JsFiddle here][1].
[1]: https://jsfiddle.net/965rdbtc/1/ |
You can use [ZREMRANGEBYRANK][1] to remove the rest of the elements, that is,
`ZREMRANGEBYRANK key 0 -1501`
You can execute this command periodically / after each insertion / after each _k_ insertions. The most appropriate methods would depend on your use case.
[1]: https://redis.io/commands/zremrangebyrank/ |
Don't split the `CLOB` into a table of values; instead you can find a sub-string match for the terms within the `CLOB` (matching preceding and following delimiters to ensure you are matching complete terms):
```lang-sql
SELECT *
FROM Abc a
WHERE EXISTS(
SELECT 1
FROM clob_tab c
WHERE ',' || c.col1 || ',' LIKE '%,' || a.Col2 || ',%'
)
```
Which, for the sample data:
```
CREATE TABLE clob_tab (col1) as
SELECT EMPTY_CLOB()
|| '27,88,100,25,26,210,2,3,3000'
|| RPAD(',1', 4000, '0')
FROM DUAL;
CREATE TABLE abc (col2) as
SELECT 20 + LEVEL
FROM DUAL
CONNECT BY LEVEL <= 10;
```
Outputs:
| COL2 |
| ----:|
| 25 |
| 26 |
| 27 |
[fiddle](https://dbfiddle.uk/UwQH5_nG)
|
Your example uses the shorthand version `container`. To use this syntax you must specify both a name and a type separated by a slash:
```container: container-name / container-type;```
If you just want to specify the type, use `container-type` instead.
The reason your example doesn't work as expected, is because `inline-size` is assumed to be the container name, and the container type defaults to `normal`.
<!-- begin snippet: js hide: false console: true babel: null -->
<!-- language: lang-html -->
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
.container {
container-type: inline-size;
max-width: 500px;
background-color: rgb(213, 213, 213);
}
p {
font-size: 2cqw;
}
</style>
</head>
<body>
<div class="container">
<p>Paragraph with font-size:2cqw, inside container with 90% width max-width=500px.</p>
</div>
</html>
<!-- end snippet -->
|
Due to incompatibility with some packages on a Vue project, `wavesurfer` needs to go down to `v6.6.4` from `v7.7.0`. And while trying to make player work again, I got stuck on progress bar.
Here's the problem: Progress bar is loaded with all its peaks from the start, it just expands as gets closer to finish:
[](https://i.stack.imgur.com/xLftH.png)
[](https://i.stack.imgur.com/10gpc.png)
```
this.baseAudioPlayer = WaveSurfer.create({
container: this.$refs.container as HTMLDivElement,
waveColor: COLORS.GRAY_400,
progressColor: COLORS.BLUE_700,
barWidth: 3,
barRadius: 4,
height: 28,
autoCenterImmediately: true,
normalize: true
})
this.baseAudioPlayer.load(url)
... // init events: audioprocess, init, ready, finish.
// on ready event wavesurfer play method is called
```
I thought it could be some issue with params in `create`, but even if I leave only `container` property, problem still occurs.
Before downgrading `create` also had `fetchParams` and `dragToSeek` params.
Also `timeupdate` event was changed on `audioprocess`, cause on `6.6.4` such event didn't exist. |
|node.js|typescript|pm2|ts-node| |
I opened the link you provided; it seems the file name is 'Underwate_test.py' but the file you are running is 'Underwater_test.py' so it does not exist. |
You change `display` of `td` thus breaking its table cell layout.
Just select a different way, for example, position the input absolutely or add a wrapper DIV:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
td{
border: 1px solid gray;
width:100px;
height:40px;
}
.checkbox-cell{
position:relative;
}
.checkbox-cell input{
position: absolute;
top:50%;
left:50%;
margin-top:-6px;
margin-left:-6px;
}
.checkbox-cell2{
position:relative;
}
.checkbox-cell2 > div{
position: absolute;
inset: 0;
display:flex;
align-items: center;
justify-content: center;
}
<!-- language: lang-html -->
<table>
<tr><td class="checkbox-cell"><input type="checkbox"></td></tr>
</table>
<table>
<tr><td class="checkbox-cell2"><div><input type="checkbox"></div></td></tr>
</table>
<!-- end snippet -->
|
Cannot delete FOO.mdf from the data_files location as it says its currently in use. But the database using this mdf file has already been dropped. My guess is something corrupt went on during the dropping process.
How do I get this file deleted? I can't even copy the file to a different destination.
|
Cannot delete SQL datafile (.mdf) as its currently in use |
|sql|sql-server|database| |
The problem is because your UI **is not rebuild** when you focus the TextField.
You must call the `setState()` to update your UI.
### Method 1: Using your existing `FocusNode`
Since you have already creating the focus node and set color in the ternary operator, you just need to add the following code:
class _SignInState extends State<SignIn> {
...
FocusNode emailText = FocusNode();
...
// add listener to your FocusNode
@override
void initState() {
super.initState();
emailText.addListener(_onEmailFocusChange);
}
// the listener action is setting state when focus change
void _onEmailFocusChange() {
setState(() {});
debugPrint("Email is focus: ${emailText.hasFocus.toString()}");
}
// don't forget to dispose your listener
@override
void dispose() {
super.dispose();
emailText.removeListener(_onEmailFocusChange);
emailText.dispose();
}
@override
Widget build(BuildContext context) {
...
...
...
}
}
And this is your final code:
import 'package:flutter/material.dart';
class SignIn extends StatefulWidget {
const SignIn({Key? key}) : super(key: key);
@override
_SignInState createState() => _SignInState();
}
class _SignInState extends State<SignIn> {
bool isPasswordVisible = false;
bool _isEmail = true;
bool _isPassword = true;
TextEditingController emailInput = TextEditingController();
TextEditingController passwordInput = TextEditingController();
FocusNode emailText = FocusNode();
@override
void initState() {
super.initState();
emailText.addListener(_onEmailFocusChange);
}
void _onEmailFocusChange() {
setState(() {});
debugPrint("Email is focus: ${emailText.hasFocus.toString()}");
}
@override
void dispose() {
super.dispose();
emailText.removeListener(_onEmailFocusChange);
emailText.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: SingleChildScrollView(
child: Container(
padding: EdgeInsets.all(30.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('Sign In to Coinify',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 24.0,
fontFamily: "Graphik",
)),
SizedBox(height: 20.0),
Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Email',
style: TextStyle(
fontWeight: FontWeight.w600,
fontSize: 16.0,
color:
emailText.hasFocus ? Colors.blue : Colors.black,
fontFamily: "Graphik",
),
),
SizedBox(height: 8.0),
TextFormField(
focusNode: emailText,
controller: emailInput,
decoration: InputDecoration(
contentPadding: EdgeInsets.symmetric(
vertical: 10, horizontal: 10),
border: OutlineInputBorder(),
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.grey)),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.blue)),
errorBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.red),
),
focusedErrorBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.red)),
hintText: 'Enter your email',
errorText:
_isEmail ? null : "Email must not be empty",
),
)
],
),
SizedBox(height: 20.0),
Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Password',
style: TextStyle(
fontWeight: FontWeight.w600,
fontSize: 16.0,
fontFamily: "Graphik",
),
),
SizedBox(height: 8.0),
TextFormField(
controller: passwordInput,
obscureText: !isPasswordVisible,
decoration: InputDecoration(
contentPadding: EdgeInsets.symmetric(
vertical: 10, horizontal: 10),
border: OutlineInputBorder(),
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.grey)),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.blue)),
errorBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.red),
),
focusedErrorBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.red),
),
hintText: 'Enter your password',
errorText: _isPassword
? null
: "Password must not be empty",
suffixIcon: GestureDetector(
onTap: () {
setState(() {
isPasswordVisible = !isPasswordVisible;
});
},
child: Icon(
isPasswordVisible
? Icons.visibility
: Icons.visibility_off,
),
),
),
)
],
),
SizedBox(height: 50.0),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
MouseRegion(
cursor: SystemMouseCursors.click,
child: GestureDetector(
onTap: () {
Navigator.pushNamed(
context, '/forgot-password');
},
child: Text('Forgot password?',
style: TextStyle(
color: Colors.blue,
)))),
MouseRegion(
cursor: SystemMouseCursors.click,
child: GestureDetector(
onTap: () {
Navigator.pushNamed(
context, '/privacy-policy');
},
child: Text('Privacy policy',
style: TextStyle(
color: Colors.blue,
)))),
]),
SizedBox(height: 20.0),
ElevatedButton(
onPressed: () {
setState(() {
if (emailInput.text == "") {
_isEmail = false;
} else {
_isEmail = true;
}
if (passwordInput.text == "") {
_isPassword = false;
} else {
_isPassword = true;
}
if (_isEmail && _isPassword) {
Navigator.pushNamed(context, '/sign-in-code');
}
});
},
child: Text(
"Sign in",
style: TextStyle(
fontSize: 14.0,
fontWeight: FontWeight.normal,
color: Colors.white),
),
style: ButtonStyle(
shape:
MaterialStateProperty.all<RoundedRectangleBorder>(
RoundedRectangleBorder(
borderRadius:
BorderRadius.circular(5.0))),
minimumSize:
MaterialStateProperty.all(Size.fromHeight(60.0)),
backgroundColor:
MaterialStateProperty.all(Colors.blue),
shadowColor:
MaterialStateProperty.all(Colors.transparent)),
)
])),
));
}
}
### Method 2: Using `Focus` widget
The second method is more simple, it just only wrap your `TextFormField` with `Focus` widget and call the `setState` in the `onFocusChange` like below:
Focus( // <- wrap with this
onFocusChange: (focus) {
setState(() {}); // <- and call setState
print("Email is focus: $focus");
},
child: TextFormField(
focusNode: emailText,
controller: emailInput,
decoration: InputDecoration(
...
),
),
),
And this is your final code using this method:
import 'package:flutter/material.dart';
class SignIn extends StatefulWidget {
const SignIn({Key? key}) : super(key: key);
@override
_SignInState createState() => _SignInState();
}
class _SignInState extends State<SignIn> {
bool isPasswordVisible = false;
bool _isEmail = true;
bool _isPassword = true;
TextEditingController emailInput = TextEditingController();
TextEditingController passwordInput = TextEditingController();
FocusNode emailText = FocusNode();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: SingleChildScrollView(
child: Container(
padding: EdgeInsets.all(30.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('Sign In to Coinify',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 24.0,
fontFamily: "Graphik",
)),
SizedBox(height: 20.0),
Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Email',
style: TextStyle(
fontWeight: FontWeight.w600,
fontSize: 16.0,
color:
emailText.hasFocus ? Colors.blue : Colors.black,
fontFamily: "Graphik",
),
),
SizedBox(height: 8.0),
Focus(
onFocusChange: (focus) {
setState(() {});
print("Email is focus: $focus");
},
child: TextFormField(
focusNode: emailText,
controller: emailInput,
decoration: InputDecoration(
contentPadding: EdgeInsets.symmetric(
vertical: 10, horizontal: 10),
border: OutlineInputBorder(),
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.grey)),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.blue)),
errorBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.red),
),
focusedErrorBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.red)),
hintText: 'Enter your email',
errorText:
_isEmail ? null : "Email must not be empty",
),
),
),
],
),
SizedBox(height: 20.0),
Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Password',
style: TextStyle(
fontWeight: FontWeight.w600,
fontSize: 16.0,
fontFamily: "Graphik",
),
),
SizedBox(height: 8.0),
TextFormField(
controller: passwordInput,
obscureText: !isPasswordVisible,
decoration: InputDecoration(
contentPadding: EdgeInsets.symmetric(
vertical: 10, horizontal: 10),
border: OutlineInputBorder(),
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.grey)),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.blue)),
errorBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.red),
),
focusedErrorBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.red),
),
hintText: 'Enter your password',
errorText: _isPassword
? null
: "Password must not be empty",
suffixIcon: GestureDetector(
onTap: () {
setState(() {
isPasswordVisible = !isPasswordVisible;
});
},
child: Icon(
isPasswordVisible
? Icons.visibility
: Icons.visibility_off,
),
),
),
)
],
),
SizedBox(height: 50.0),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
MouseRegion(
cursor: SystemMouseCursors.click,
child: GestureDetector(
onTap: () {
Navigator.pushNamed(
context, '/forgot-password');
},
child: Text('Forgot password?',
style: TextStyle(
color: Colors.blue,
)))),
MouseRegion(
cursor: SystemMouseCursors.click,
child: GestureDetector(
onTap: () {
Navigator.pushNamed(
context, '/privacy-policy');
},
child: Text('Privacy policy',
style: TextStyle(
color: Colors.blue,
)))),
]),
SizedBox(height: 20.0),
ElevatedButton(
onPressed: () {
setState(() {
if (emailInput.text == "") {
_isEmail = false;
} else {
_isEmail = true;
}
if (passwordInput.text == "") {
_isPassword = false;
} else {
_isPassword = true;
}
if (_isEmail && _isPassword) {
Navigator.pushNamed(context, '/sign-in-code');
}
});
},
child: Text(
"Sign in",
style: TextStyle(
fontSize: 14.0,
fontWeight: FontWeight.normal,
color: Colors.white),
),
style: ButtonStyle(
shape:
MaterialStateProperty.all<RoundedRectangleBorder>(
RoundedRectangleBorder(
borderRadius:
BorderRadius.circular(5.0))),
minimumSize:
MaterialStateProperty.all(Size.fromHeight(60.0)),
backgroundColor:
MaterialStateProperty.all(Colors.blue),
shadowColor:
MaterialStateProperty.all(Colors.transparent)),
)
])),
));
}
}
And this is the result:
[![demo][1]][1]
Hopefully it can solve your problem, Thanks
[1]: https://i.stack.imgur.com/s6zLF.gif |
One thing you can check is, if all of your beans are in the same package or sub package of the @SpringBootApplication. Spring automatically scans for the beans in the package&sub-packages where the springboot application is defined.
If the bean that you are trying to access is not within the @SpringBootApplication package, you might probably need to import the package to tell the spring to scan that pacakge for beans.
Thanks:)
Happy Coding! |
{"Voters":[{"Id":14732669,"DisplayName":"ray"},{"Id":22192445,"DisplayName":"taller"},{"Id":1115360,"DisplayName":"Andrew Morton"}],"SiteSpecificCloseReasonIds":[13]} |
I am trying to write a personal project in JavaScript.
So I started with an empty folder with two files:
card.js
constants.js
and in `card.js`, I used on the first line:
import { SUIT } from "./constants.js";
and run it using `node card.js`. It doesn't work, giving the error:
> (node:91577) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
First,
> set "type": "module" in the package.json
I don't even have a package.json. Must I use it? Can I not use one? If I set "type": "module", does that make my own project become a module?
Second, I have never seen any `.mjs` file ever before. What is it about? I can use that and forget everything about NodeJS or package.json?
If I look at the [docs for import][1], it has:
import { myExport } from "/modules/my-module.js";
So I used `mkdir modules` and moved that `constants.js` in there.
And then I used:
import { SUIT } from "/modules/constants.js"
and it still has the same error. That doc doesn't not mention `package.json` whatsoever.
I am wondering if this `import` is the same as `import` in the context of NodeJS (and so it may be different in Deno).
How is it done?
**P.S.** I renamed `constants.js` to `constants.mjs` and got the same error.
**P.P.S.** I can use `npm init` to init the project and create a package.json file, except it looks like that will make my project become an npm package. But my project is meant to be an app, not a package.
[1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import |
|c#|github|github-actions| |
*There is very good post about trimming 1fr to 0: https://stackoverflow.com/questions/52861086/why-does-minmax0-1fr-work-for-long-elements-while-1fr-doesnt*
In general I would like to have a cell which expands as the content grows, but within the limits of its parent.
Currently I have a grid with cell with such lengthy content that even without expanding it is bigger than the entire screen. So I would to do two things -- clip the size of the cell, and secondly -- provide the scroll.
I used `minmax(0, 1fr)` from the post I mentioned, so grid has free hand to squash the cell to zero, but it still allows to grow it up to the content size (which is too big). As the effect the scrolling is not triggered.
Usually I use scroller as two-div component (see the code), I thought it could be the cause of the problem, but even with single `div` for scrolling the cell is still not clipped.
<!-- begin snippet: js hide: false console: false babel: false -->
<!-- language: lang-html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
body
{
width: 100vw;
height: 100vh;
margin: 0;
padding: 0;
overflow: hidden;
}
.page
{
display: flex;
flex-direction: column;
height: 100%;
}
.header
{
}
.content
{
flex-grow: 1;
}
.quiz-grid
{
height: 100%;
max-height: 100%;
display: grid;
grid-template-columns: minmax(0, 1fr) auto minmax(0, 1fr);
grid-template-rows: minmax(0, 1fr) min-content;
grid-template-areas:
"left main right"
"footer footer footer";
}
.quiz-cell-left
{
grid-area: left;
min-height: 0;
}
.quiz-cell-right
{
grid-area: right;
min-height: 0;
}
.quiz-cell-main
{
grid-area: main;
border: 1px red solid;
min-height: 0;
}
.quiz-cell-footer
{
grid-area: footer;
justify-self: center;
align-self: center;
}
/* my scroll view component */
.scroll-container
{
position: relative;
width: 100%;
min-height: 0;
background-color: azure;
}
.scroll-content
{
height: 100%;
width: 100%;
overflow-y: auto;
}
/* simplified scroller */
.scroll-direct
{
overflow-y: auto;
background-color: azure;
width: 100%;
}
</style>
</head>
<body>
<div class="page">
<div class="header">Header</div>
<div class="content">
<div class="quiz-grid">
<div class="quiz-cell-main">
<!-- <div class="scroll-container"> <div class="scroll-content">-->
<div class="scroll-direct">
<h1>something<h1>
<h1>else<h1>
<h1>alice<h1>
<h1>cat<h1>
<h1>or dog<h1>
<h1>now<h1>
<h1>world<h1>
<h1>something<h1>
<h1>else<h1>
<h1>alice<h1>
<h1>cat<h1>
<h1>or dog<h1>
<h1>now<h1>
<h1>world<h1>
<h1>something<h1>
<h1>else<h1>
<h1>alice<h1>
<h1>cat<h1>
<h1>or dog<h1>
<h1>now<h1>
<h1>world<h1>
<h1>something<h1>
<h1>else<h1>
<h1>alice<h1>
<h1>cat<h1>
<h1>or dog<h1>
<h1>now<h1>
<h1>world<h1>
<!-- </div> </div> -->
</div>
</div>
<div class="quiz-cell-footer">
footer
</div>
</div>
</div>
</div>
</body>
</html>
<!-- end snippet -->
*Comment to the code: the content sits in cell "main", the other elements (header, footer) are just to make sure the solution would not be over simplified.* |
How to clip grid cell and provide scroll as well? |
|css|scroll|css-grid| |
In stripe I have 2 products.
Monthly subscription ($50 for beginner).
Monthly subscription ($70 for advanced).
The user (a parent) can complete a form "Add student to courses". The result is creating tabs with content specific for each kid they sign up to classes.
If the user pays a subscription for each kid, in my supabase "subscriptions" table, a column student_id will be populated with the student's id that is the foreign key to a students table.
So the parent can have multiple subscriptions for each of his/her kids.
Problem: Let's say both kids are beginners for the classes. If I go to stripe customer portal from the parent's page, I will have 2 subscriptions, both named "Monthly subscription".
How can I differentiate between the 2? Something like "Monthly Subscription for Hannah" and "Monthly Subscription for Paul", or maybe add a description or a tag with their names, idk. I'm stuck...
It looks like I can only create one customer portal, but then all I can see are 2 subscriptions "Monthly Subscription" |
I'd like to add another reason for not using `apply` that was not mentioned in other answers. `apply` can cause nasty mutation bugs, i.e. `df.apply(func, axis=1)` applies the same object to the given function. Try this:
```
import pandas as pd
df = pd.DataFrame({"A": [9, 4, 2, 1], "B": [12, 7, 5, 4]})
print(df.apply(id, axis=1))
# 0 2771319967472
# 1 2771319967472
# 2 2771319967472
# 3 2771319967472
```
(the `id` is the same for all values)
[The documentation for apply][1] states:
> Functions that mutate the passed object can produce unexpected behavior or errors and are not supported.
But even knowing that, and avoiding mutations, is not enough. Consider the following code:
```
from asyncio import run, gather, sleep
import pandas as pd
async def afunc(row):
await sleep(1)
print(row)
async def main():
df = pd.DataFrame({"A": [9, 4, 2, 1], "B": [12, 7, 5, 4]})
coros = df.apply(afunc, axis=1)
await gather(*coros)
run(main())
```
As you see, we have not mutated any row in our `afunc`. But if you run the code, you'll notice that only the last row gets applied...
Another example without `async`:
```
import pandas as pd
applied = []
def func(row):
applied.append(row)
df = pd.DataFrame({"A": [9, 4, 2, 1], "B": [12, 7, 5, 4]})
df.apply(func, axis=1)
print(pd.DataFrame(applied))
# A B
# 3 1 4
# 3 1 4
# 3 1 4
# 3 1 4
```
[1]: https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.apply.html |
i was testing for an attendance website, logging attendance on different dates (manually changing the date on my device) i have a status column 1 for present and 0 for absent. when i log an attendance where some are absent, the status column on that date are reflected correctly but when I log an attendance where all are present, the status column values on all dates (including the ones with '0') are all changed to '1'. below is the code for the save
```
if(isset($_POST['save'])){
$studentNo=$_POST['studentNo'];
$check=$_POST['check'];
$N = count($studentNo);
$status = "";
$qurty=mysqli_query($conn,"select * from tblattendance where subject = '$id' and date = '$dateTaken' and status = '1'");
$count = mysqli_num_rows($qurty);
if($count > 0){
$statusMsg = "<div class='alert alert-danger' style='margin-right:700px;'>Attendance has been taken for today!<button type='button' class='close' data-dismiss='alert' aria-label='Close'><span aria-hidden='true'>×</span></button></div>";
}else
{
for($i = 0; $i < $N; $i++)
{
$studentNo[$i];
if(isset($check[$i]))
{
$qquery=mysqli_query($conn,"update tblattendance set status='1' where studentNo= '$check[$i]'");
if ($qquery) {
$statusMsg = "<div class='alert alert-success' style='margin-right:700px;'>Attendance Taken Successfully!<button type='button' class='close' data-dismiss='alert' aria-label='Close'><span aria-hidden='true'>×</span></button></div>";
}
else
{
$statusMsg = "<div class='alert alert-danger' style='margin-right:700px;'>An error Occurred!</div>";
}
}
}
}
}
```
```
$query = "SELECT tblsection.section,tblassignteach.secId,tblclass.className,tblsubject.subject,tblstudents.secId,tblstudents.studentNum,tblstudents.firstName,tblstudents.lastName,tblstudents.mname,tblstudents.sex,tblstudents.classId FROM tblstudents
INNER JOIN tblassignteach ON tblassignteach.secId = tblstudents.secId
INNER JOIN tblsection ON tblsection.Id = tblstudents.secId
INNER JOIN tblclass ON tblclass.Id = tblstudents.classId
INNER JOIN tblclassarms ON tblclassarms.Id = tblassignteach.classArmId
WHERE tblassignteach.subject='$id'";
$rs = mysqli_query($conn, $query);
$num = $rs->num_rows;
$sn=0;
$status="";
if($num > 0)
{
while ($rows = $rs->fetch_assoc())
{
$sn = $sn + 1;
echo"
<tr>
<td><input name='check[]' type='checkbox' value=".$rows['admissionNumber']." class='form-control'></td>
<td>".$sn."</td>
<td>".$rows['admissionNumber']."</td>
<td>".$rows['lastName']."</td>
<td>".$rows['firstName']."</td>
<td>".$rows['mname']."</td>
<td>".$rows['sex']."</td>
<td>".$rows['className']."</td>
<td>".$rows['section']."</td>
<td>".$rows['subject']."</td>
</tr>";
echo "<input name='studentNo[]' value=".$rows['studentNum']." type='hidden' class='form-control'>";
}
}
```
```
$qurty=mysqli_query($conn,"SELECT * from tblattendance where subject= '$id' and dateTimeTaken = '$dateTaken'");
$count=mysqli_num_rows($qurty);
if($count == 0){
$qus=mysqli_query($conn,"SELECT tblstudents.studentNum,tblassignteach.subject from tblstudents
inner join tblassignteach on tblassignteach.secId = tblstudents.secId
where tblassignteach.subject= '$id'");
while ($ros = $qus->fetch_assoc())
{
$qquery=mysqli_query($conn,"INSERT into tblattendance(studentNo,subject,sessionTermId,status,dateTimeTaken,timeTaken)
VALUES('$ros[studentNum]','$id','$sessionTermId','0', '$dateTaken', '$ttimeTaken')");
}
```
i'm wondering why all the values in all logged dates in the db are changed to '1' and if there is a way to fix this. if you need anything else, please dont hesitate to let me know and I really appreciate all the help i can get. thank you in advance! |
status table for all entries (even in different dates) in database changing value when all checkboxes are checked |
|php|mysql|checkbox|time-and-attendance| |
null |
I have such component which renders the `BBCode` image tag on my website on `React`:
**Code:**
**BBCodeComponent.tsx:**
import React from "react";
import ReactDOMServer from "react-dom/server";
import CustomTooltip from "./CustomTooltip";
const BBCodeComponent = ({content}) => {
const parseBBCode = (text) => {
return text
.replace(/\[img=(.*?)\](.*?)\[\/img\]/g, (match, title, src) => {
return ReactDOMServer.renderToString(<CustomTooltip msg={title}><img src={src} alt={title} /></CustomTooltip>);
})
.replace(/\[quote](.*?)\[\/quote\]/g, "<blockquote>$1</blockquote>");
};
return <div dangerouslySetInnerHTML={{__html: parseBBCode(content)}} />;
};
export default BBCodeComponent;
**CustomTooltip.tsx:**
import React from "react";
import {Tooltip} from "react-tippy";
export type Position =
| "top"
| "top-start"
| "top-end"
| "bottom"
| "bottom-start"
| "bottom-end"
| "left"
| "left-start"
| "left-end"
| "right"
| "right-start"
| "right-end";
export type Size = "small" | "regular" | "big";
export type Theme = "dark" | "light" | "transparent";
interface IToolTip {
children: React.ReactNode;
msg: string;
pos?: Position,
tooltipSize?: Size,
tooltipTheme?: Theme
}
const CustomTooltip = ({children, msg, pos = "top", tooltipSize = "big", tooltipTheme = "light"} : IToolTip) => {
return (
<Tooltip title={msg} position={pos} size={tooltipSize} theme={tooltipTheme} followCursor={true}>{children}</Tooltip>
);
};
export default CustomTooltip;
The issue is that it incorrectly renders the `CustomTooltip` component. It just renders the default browser tooltip instead of the `react-tippy`. Any ideas how to render it properly to display `react-tippy` image title? |
null |
This post will help you to get rid of the problem and it works for me. It is because of your PC timezone is not the same as your browser.
Check it out the down link:
https://enddesign.medium.com/a-problem-you-might-have-while-doing-the-chain-middleware-to-create-a-time-server-challenge-from-44027ca483b9 |
Okay so basically the date format is dd-mm-yyyy (it's the format here in Portugal) , and the hour is hh:mm, and my code is this:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
struct DateTime {
int day, month, year, hour, minute;
};
// Function to convert date and time to minutes since midnight
int minutes_since_midnight(struct DateTime dt) {
return dt.hour * 60 + dt.minute;
}
// Function to calculate time difference
int calculate_time_difference(char date_in[], char time_in[], char date_out[], char time_out[]) {
struct DateTime dt1, dt2;
sscanf(date_in, "%d-%d-%d", &dt1.day, &dt1.month, &dt1.year);
sscanf(time_in, "%d:%d", &dt1.hour, &dt1.minute);
sscanf(date_out, "%d-%d-%d", &dt2.day, &dt2.month, &dt2.year);
sscanf(time_out, "%d:%d", &dt2.hour, &dt2.minute);
// Convert date and time to minutes since midnight
int minutes1 = minutes_since_midnight(dt1);
int minutes2 = minutes_since_midnight(dt2);
// Calculate total difference in minutes
int time_difference = abs(minutes2 - minutes1);
// Calculate day difference in minutes
int day_difference = dt2.day - dt1.day;
// If the date of departure is before the date of arrival, adjust the day difference
if (day_difference < 0) {
// Add a full day of minutes
day_difference += 1;
// Add the remaining hours of the departure day
time_difference += (24 - dt1.hour) * 60 + (60 - dt1.minute);
// Add the hours of the arrival day
time_difference += dt2.hour * 60 + dt2.minute;
} else {
// If the date of departure is after the date of arrival, just add the remaining minutes
time_difference += day_difference * 24 * 60;
}
return time_difference;
}
int main() {
int time_diff = calculate_time_difference("01-01-2024", "19:05", "02-01-2024", "9:05");
printf("Time difference->%i\n", time_diff);
return 0;
}
```
And as you can probably tell by the example I let in the main function, in this case where **input 1= "01-01-2024", "19:05"** and **input 2= "02-01-2024", "9:05"** the time difference in minutes **should be 840** (14 hours *60 minutes), but the code when I run it says : **Time difference->2040** . How can I fix this??
Ignore leap years by the way for this example |
Is it allowed to apply `std::bit_cast` to an object of empty class, converting it to some not-empty class of the same size? And especially is it allowed to do in a constant expression?
I was surprised to find that the following simple program
```c++
#include <bit>
struct A {};
struct B { unsigned char b; };
// ok in MSVC and GCC, fail in Clang
static_assert( 0 == std::bit_cast<B>(A{}).b );
```
is accepted by both GCC and MSVC, and only Clang complains:
```
error: static assertion expression is not an integral constant expression
```
Online demo: https://gcc.godbolt.org/z/cGW3Mq3je
What is the correct behavior here according to the standard? |