instruction stringlengths 0 30k ⌀ |
|---|
Fine grained resource mangement and heap memory in flink task slot |
|apache-flink|flink-streaming| |
I’m making an in app purchase for my game on Steam. On my server I use python 3. I’m trying to make an https request as follows:
conn = http.client.HTTPSConnection("partner.steam-api.com")
orderid = uuid.uuid4().int & (1<<64)-1
print("orderid = ", orderid)
key = "xxxxxxxxxxxxxxxxxxx" # omitted for security reason
steamid = "xxxxxxxxxxxxxxxxxxx" # omitted for security reason
pid = "testItem1"
appid = "480"
itemcount = 1
currency = 'CNY'
amount = 350
description = 'testing_description'
urlSandbox = "/ISteamMicroTxnSandbox/"
s = f'{urlSandbox}InitTxn/v3/?key={key}&orderid={orderid}&appid={appid}&steamid={steamid}&itemcount={itemcount}¤cy={currency}&itemid[0]={pid}&qty[0]={1}&amount[0]={amount}&description[0]={description}'
print("s = ", s)
conn.request('POST', s)
r = conn.getresponse()
print("InitTxn result = ", r.read())
I checked the s in console, which is:
```
s = /ISteamMicroTxnSandbox/InitTxn/v3/?key=xxxxxxx&orderid=11506775749761176415&appid=480&steamid=xxxxxxxxxxxx&itemcount=1¤cy=CNY&itemid[0]=testItem1&qty[0]=1&amount[0]=350&description[0]=testing_description
```
However I got a bad request response:
```
InitTxn result = b"<html><head><title>Bad Request</title></head><body><h1>Bad Request</h1>Required parameter 'orderid' is missing</body></html>"
````
How to solve this? Thank you!
BTW I use almost the same way to call GetUserInfo, except changing parameters and replace POST with GET request, and it works well.
Just read that I should put parameters in post. So I changed the codes to as follows, but still get the same error of "Required parameter 'orderid' is missing"
params = {
'key': key,
'orderid': orderid,
'appid': appid,
'steamid': steamid,
'itemcount': itemcount,
'currency': currency,
'pid': pid,
'qty[0]': 1,
'amount[0]': amount,
'description[0]': description
}
s = urllib.parse.urlencode(params)
# In console: s = key=xxxxx&orderid=9231307508782239594&appid=480&steamid=xxx&itemcount=1¤cy=CNY&pid=testItem1&qty%5B0%5D=1&amount%5B0%5D=350&description%5B0%5D=testing_description
print("s = ", s)
conn.request('POST', url=f'{urlSandbox}InitTxn/v3/', body=s)
==== update ====
Format issue has been solved. Please see the answer below.
Thought I get to send the HTTPs request in proper format, I still got a failure response ```b'{"response":{"result":"Failure","params":{"orderid":"9829049831725601326"},"error":{"errorcode":3,"errordesc":"Item 0 - Invalid item id"}}}'```
If anyone know how to solve this, please let me know, thank you! |
In base R, it is possible to automatically use the Freedman-Diaconis rule for setting bin width in a histogram:
```r
hist(rnorm(100), breaks = "FD")
```
There does not appear to be this behavior in base ggplot. I have been trying to implement this method for easier use with `geom_histogram`.
I would like to be able to modify the function so that it can be called without specifying the original dataframe and column.
```r
bin_number <- function(data_vector = NULL) {
if (is.null(data_vector)) {
data_vector <- # something
}
bin_width <-
2 * stats::IQR(data_vector) / (length(data_vector) ^ (1 / 3))
number_bins <- ceiling(diff(range(data_vector)) / bin_width)
return(number_bins)
}
df <- data.frame(xval = rnorm(100))
ggplot(data = df) +
geom_histogram(
mapping = aes(
x = xval,
y = after_stat(density)
),
bins = bin_number()
)
```
I have looked through the ggplot documentation, but I haven't been able to find a way to get the aesthetics of the current dataframe easily.
My current method requires calling the data vector directly, which does work but can be clunky and makes the code for histograms harder to reproduce.
```r
bin_number <- function(data_vector) {
bin_width <-
2 * stats::IQR(data_vector) / (length(data_vector) ^ (1 / 3))
number_bins <- ceiling(diff(range(data_vector)) / bin_width)
return(number_bins)
}
df <- data.frame(xval = rnorm(100))
ggplot(data = df) +
geom_histogram(
mapping = aes(
x = xval,
y = after_stat(density)
),
bins = bin_number(df$xval)
)
``` |
Call ggplot2 aesthetics in another function |
|r|ggplot2| |
null |
This should be a [question](https://stackoverflow.com/questions/ask), not a discussion post.
|
null |
In my case, I am sure the defendency is included, but even if the dependency is included, we need ensure the JAR file containing ObjectMapper is on the classpath.
This usually happens automatically with build tools, but double-check if you're manually managing the classpath.
i was able to solve this error by changing the module-info file. What i noticed is, I imported jackson using the keyword requires static.
it should be imported using "requires" only |
After drop_na it shows 0 obs. of 68 variables:
[![enter image description here][1]][1]
[![enter image description here][2]][2]
[![enter image description here][3]][3]
[![https://i.stack.imgur.com/R7nfg.png[4][4]
After drop_na I don't see any results in the Table except dates. This was not the case when I tried it before, I could see the values in the table.
```r
library(tidyverse)
WDI_GDP <- read_csv("C:/Users/ASYA/Desktop/P_Data_Extract_From_World_Development_Indicators/b0351889-13b3-4cbe-a5c0-a2dd9d633eab_Data.csv")
WDI_GDP <- WDI_GDP %>%
mutate(across(contains("[YR"), ~na_if(.x,"..")) %>%
mutate(across(contains("[YR"), as.numeric)))
WDI_GDP <- drop_na(WDI_GDP)
```
[enter image description here][4]
[1]: https://i.stack.imgur.com/oqjo8.png
[2]: https://i.stack.imgur.com/elrGR.png
[3]: https://i.stack.imgur.com/txJEv.png
[4]: https://i.stack.imgur.com/R7nfg.png |
Method 1:- Try to remove imports of 'dart:js_interop' as it may be imported by default in many of your project files.
Method 2:- NOTE that this import are certainly due to usage of StreamBuilder in your app , so try to use any alternative widgets to do the same work inorder to solve your problem if NOT solved by first method. . |
Sorry my bad English.
I connected my website to Analytics 4 via GTM. However, I have a request: I want GA4 not to count the traffic coming to a link I specify within my site. Is something like this possible?
For example, let's say I set website.com/link_url. It won't count traffic to it.
But it will continue to calculate all traffic to the website.com domain normally, except for the URL address I chose.
Thank you...
I tried on GTM but it didn't work |
Preventing Google Analytics from counting traffic to a custom URL |
|google-analytics|google-tag-manager| |
null |
I have created Monorepo
The problem is that share eslint
I think package dependencies can be linked together
But, my package doesn it!
At root .eslintrc.js, it extends '@packages/eslint-config-custom' but output msg say that:
[](https://i.stack.imgur.com/5s3OD.png)
How can i fix it?
[My-repo](https://github.com/coo-kiee/Mono-Lab/tree/develop) |
Why my Monorepo eslint-config-custom's dependencies doesn't installed together? |
|monorepo|yarn-workspaces|yarn-berry| |
null |
solution:
```
CREATE OR REPLACE FUNCTION set_note_id()
RETURNS TRIGGER AS $f$
DECLARE
max_identifier INTEGER;
BEGIN
SELECT MAX(id)+1 INTO max_identifier
FROM test.notes
WHERE user_id = NEW.user_id;
IF max_identifier IS NULL THEN
max_identifier := 1;
END IF;
NEW.id := max_identifier;
RETURN NEW;
END;
$f$ LANGUAGE plpgsql;
CREATE TRIGGER before_insert_trigger_notes
BEFORE INSERT ON test.notes
FOR EACH ROW
EXECUTE FUNCTION set_note_id();
``` |
```
Below is sample doc of collection.
{
name:"sam",
age:20,
hobbies: [ {id:1, value: "football"}, {id:2 value:"chess"} ]
},
{
"name": "Bob",
"age": 30,
"hobbies": [
{ "id": 1, "value": "painting" },
{ "id": 2, "value": "gardening" }
]
},
{
"name": "Charlie",
"age": 22,
"hobbies": [
{ "id": 1, "value": "cycling" },
{ "id": 2, "value": "playing the guitar" },
{ "id": 3, "value": "photography" }
]
}
```
I have tried using the below query, it only sorts the array of hobbies not the documents of the collection.
```
{$sort : {"hobbies.value": 1}}
```
I want to sort documents of the collection based on hobbies.value and also sort objects inside the array.
The expected result will be something like below for asc. .
```
{
name:"sam",
age:20,
hobbies: [ {id:2 value:"chess"}, {id:1, value: "football"} ]
},
{
"name": "Charlie",
"age": 22,
"hobbies": [
{ "id": 1, "value": "cycling" },
{ "id": 2, "value": "playing the guitar" },
{ "id": 3, "value": "photography" }
]
},
{
"name": "Bob",
"age": 30,
"hobbies": [
{ "id": 1, "value": "painting" },
{ "id": 2, "value": "gardening" }
]
}
``` |
In Normal Operation, Maven Calculates and Downloads Transitive Dependencies
---
There's a presumption in the question that it was _normal and expected_ by Wiremock's development team that you would add jetty-util as a dependency. That's not true: *This was a bug.*
The alternative to standalone jars is not needing to add dependencies yourself. The alternative to standalone JARs is having the POM for a project specify compatibility constraints on all its dependencies, so that Maven can combine all the constraints of all the dependencies and try to calculate a dependency set that satisfies all those constraints.
---
### Vendoring Dependencies Sets Up Conflicts
Let's say that you're using library A, which requires C version 1.2.3 or newer (but not past 1.4.99); and library B, which requires C version 1.3.0 or newer (but not 2.0+).
When Maven is calculating a dependency set, this is easy: it knows that the overall project requires a version of C that's at least 1.3.0, and not 1.5+. It thus might pick, say, 1.4.15.
By contrast, if library A bundled in C==1.2.3 to a standalone jar, _that version of C is on the overall project's classpath_, so library B can end up getting C 1.2.3 even though it doesn't work with any version of C older than 1.3.0.
There are mechanisms like OSGi to try to have multiple classloaders with different dependency versions active within the same JVM at the same time, but these add a great deal of complexity on their own -- it's very much best avoided.
---
Versioning Dependencies Prevents Security Updates
---
You're using Library A in standalone mode, which _vendors_ C 1.2.3.
There's a major vulnerability discovered in C releases older than 1.4.13. Now what?
If you weren't operating in standalone mode, Maven could resolve to the newest available version that was compatible with everything in your dependency chain; but because you're letting your dependencies pull in versions of transitive dependencies _they_ packaged at build time, now you need to wait until library A publishes a new release.
If they only publish that new release on a branch you aren't compatible with -- too bad, so sad, nothing you can do about it without a bunch of build engineering work to pull content out of the jar they distributed at build time. |
I have a jiobook 2023, I want to flash a costume rom in it. Specifically ubuntu touch. Is there any way to flash?
Flashing laptops by going into bios mode doesn't work. It is more like a Android mobile without volume buttons. |
Jiobook flashing |
|android|arm|flashing| |
null |
The first thing I noticed was the lack of dots next to the php variables, I didn't check the code.
```
$qurty=mysqli_query($conn,"select * from tblattendance where subject = ".$id." and date = ".$dateTaken." and status = '1'");
$count = mysqli_num_rows($qurty);
$qquery=mysqli_query($conn,"update tblattendance set status='1' where studentNo= ".$check[$i].");
``` |
Is there any difference between using map and using function if everything is known at compile time. (I'm new to Kotlin/Java and i couldn't find answer to this) Maximal number of items will never be higher than 200 and for the most of the time it would be below 10
Example:
```kt
val mappings = mapOf(
"PL" to "Poland",
"EN" to "England",
"DE" to "Germany",
"US" to "United States of America",
)
fun mappingsFunc(code: String): String? {
return when (code) {
"PL" -> "Poland"
"EN" -> "England"
"DE" -> "Germany"
"US" -> "United States of America"
else -> null
}
}
fun main() {
println(mappings["PL"]!!)
println(mappingsFunc("US")!!)
}
```
Playground: https://pl.kotl.in/vBE4Pozok
Both of them works, both syntax's are fine for me but i dunno which one is recommended. |
null |
After drop_na it shows 0 obs. of 68 variables:
[![enter image description here][1]][1]
[![enter image description here][2]][2]
[![enter image description here][3]][3]
After drop_na I don't see any results in the Table except dates. This was not the case when I tried it before, I could see the values in the table.
```r
library(tidyverse)
WDI_GDP <- read_csv("C:/Users/ASYA/Desktop/P_Data_Extract_From_World_Development_Indicators/b0351889-13b3-4cbe-a5c0-a2dd9d633eab_Data.csv")
WDI_GDP <- WDI_GDP %>%
mutate(across(contains("[YR"), ~na_if(.x,"..")) %>%
mutate(across(contains("[YR"), as.numeric)))
WDI_GDP <- drop_na(WDI_GDP)
```
![enter image description here][4]
[1]: https://i.stack.imgur.com/oqjo8.png
[2]: https://i.stack.imgur.com/elrGR.png
[3]: https://i.stack.imgur.com/txJEv.png
[4]: https://i.stack.imgur.com/R7nfg.png |
null |
the main problem is in Multi-part form data it not using in react-admin :
details:
I have a Django REST Framework backend API with a ProductViewSet that handles product creation. When creating a new product, I'm expecting to receive an image file along with other product data from a React-admin frontend. Here's the relevant part of my backend API:
```
class ProductViewSet(ModelViewSet):
queryset = Product.objects.all()
serializer_class = ProductSerializer
filter_backends = [DjangoFilterBackend, SearchFilter]
search_fields = ['name', 'description']
ordering_fields = ['price', 'name']
def create(self, request, *args, **kwargs):
try:
data = request.data
with transaction.atomic():
# Extract product_type, company, unit_of_measure from request data
# Extract image path from request data
image_path = None
if "image" in data:
raw_file = data["image"].get("rawFile")
if raw_file and "path" in raw_file:
image_path = raw_file["path"]
# Create Product instance with extracted data
product = Product(
name=data.get("name"),
image=image_path,
# Other product fields...
)
product.save()
# Add many-to-many relationships
# Serialize and return the created product
serializer = ProductSerializer(product, many=False)
return Response(serializer.data, status=status.HTTP_201_CREATED)
except Exception as e:
print("Error:", e)
return Response({"error": str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
```
On the frontend side, I'm using React-admin for the product creation form. Here's the relevant part of my frontend code:
```
import * as React from 'react';
import {
Create,
TextInput,
ImageInput,
} from 'react-admin';
const ProductCreate = () => {
return (
<Create>
<TextInput source="name" label="Product Name" fullWidth />
<ImageInput
source="image"
label="Thumbnail"
accept="image/*"
/>
</Create>
);
};
export default ProductCreate;
```
The issue I'm facing is that when I save a new product with an image file, the image file is not being uploaded to the media folder on the server. Instead, only the image file name (media/some.png) is being saved to the database. How can I ensure that the image file is correctly uploaded to the media folder?
the image save to database as image:"media/some.png"
is correct but the image file not move to default medai postion in /media/
# settings.py
# ...
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
# urls.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... Your existing URL patterns ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) |
just do `npm i pnpm --global` it will install pnpm global. |
{"Voters":[{"Id":1544327,"DisplayName":"user1544327"}],"DeleteType":1} |
For elevation you'd need some data source / provider. `elevatr` package potentially can provide you values for point locations, for example through *Amazon Web Service Terrain Tiles*, but you'd probably need to evaluate those results and work out acceptable resolution / zoom levels.
Here I'm assuming that "relative elevation estimation" means an elevation range, though it can be a number of metrics when it comes to a linestring. Linestring length is kind of trivial when working with `sf` : `st_length()` ; for building those linestrings, perhaps try dplyr-style `group()` + `summarise()` first, you can look into alternatives if it proves to be impractical due to the number of points.
``` r
library(elevatr)
library(dplyr)
library(sf)
#> Linking to GEOS 3.11.2, GDAL 3.6.2, PROJ 9.2.0; sf_use_s2() is TRUE
aus_sf <-
aus |>
# make sure points are correctyl sorted
arrange(country, id, point_id) |>
# convert to sf object
st_as_sf(coords = c("lon", "lat"), crs = "WGS84") |>
# get elevation from Amazon Web Service Terrain Tiles
get_elev_point(src = "aws")
aus_sf
#> Simple feature collection with 17 features and 5 fields
#> Geometry type: POINT
#> Dimension: XY
#> Bounding box: xmin: 129.251 ymin: -20.06129 xmax: 137.2865 ymax: -18.30723
#> Geodetic CRS: WGS 84
#> First 10 features:
#> id country point_id geometry elevation elev_units
#> 1 1 Australia 0 POINT (130.1491 -19.5752) 382 meters
#> 2 1 Australia 1 POINT (129.9958 -19.4876) 425 meters
#> 3 1 Australia 2 POINT (129.7156 -19.25788) 444 meters
#> 4 1 Australia 3 POINT (129.7104 -19.20223) 441 meters
#> 5 2 Australia 0 POINT (129.251 -18.59016) 376 meters
#> 6 2 Australia 1 POINT (129.5436 -18.30723) 398 meters
#> 7 3 Australia 0 POINT (137.284 -20.06129) 229 meters
#> 8 3 Australia 1 POINT (137.2865 -20.04308) 234 meters
#> 9 3 Australia 2 POINT (137.1915 -20.00782) 237 meters
#> 10 3 Australia 3 POINT (137.122 -19.97166) 234 meters
```
Build linestrings from ordered points:
``` r
aus_lines <-
aus_sf |>
# group by `country` to keep it as attribute and by `id`
# to create 4 multipoints, one per id
group_by(country, id) |>
# points to multipoints,
# do not use do_union as it will likely change point order,
# add elevation range
summarise(elev_range = max(elevation) - min(elevation), do_union = FALSE, .groups = "drop") |>
# multipoints to linestrings
st_cast("LINESTRING") |>
# add length column
mutate(length = st_length(geometry))
```
Resulting linestrings with elevation range and length:
``` r
aus_lines
#> Simple feature collection with 4 features and 4 fields
#> Geometry type: LINESTRING
#> Dimension: XY
#> Bounding box: xmin: 129.251 ymin: -20.06129 xmax: 137.2865 ymax: -18.30723
#> Geodetic CRS: WGS 84
#> # A tibble: 4 × 5
#> country id elev_range geometry length
#> * <chr> <int> <dbl> <LINESTRING [°]> [m]
#> 1 Australia 1 62 (130.1491 -19.5752, 129.9958 -19.4876, 129.… 63941.
#> 2 Australia 2 22 (129.251 -18.59016, 129.5436 -18.30723) 44072.
#> 3 Australia 3 8 (137.284 -20.06129, 137.2865 -20.04308, 137… 48462.
#> 4 Australia 4 4 (136.8961 -19.85932, 136.8791 -19.88669, 13… 10190.
```
Dataset example:
``` r
aus <- read.table(header = TRUE, text =
"id country point_id lon lat
1 Australia 0 130.1491 -19.57520
1 Australia 1 129.9958 -19.48760
1 Australia 2 129.7156 -19.25788
1 Australia 3 129.7104 -19.20223
2 Australia 0 129.2510 -18.59016
2 Australia 1 129.5436 -18.30723
3 Australia 0 137.2840 -20.06129
3 Australia 1 137.2865 -20.04308
3 Australia 2 137.1915 -20.00782
3 Australia 3 137.1220 -19.97166
3 Australia 4 137.0650 -19.91363
3 Australia 5 136.8961 -19.85932
4 Australia 0 136.8961 -19.85932
4 Australia 1 136.8791 -19.88669
4 Australia 2 136.8594 -19.91227
4 Australia 3 136.8454 -19.92507
4 Australia 4 136.8360 -19.92976")
```
|
I am using nestJS (typescript) for developing server. I have to access GCP datastore to update and fetch data.
Currently I am doing development locally so I want to access GCP datastore locally.
In GCP console, I have done following steps in already created project:
1. Created Service Account with role as Owner.
2. I went to keys section of Service account and created new key and downloaded json.
In my nestJS project, I have installed to npm package "@google-cloud/datastore" to access datastore through library.
I have set .env file value:
GOOGLE_APPLICATION_CREDENTIALS=gcp-key.json
I have datastoreService.ts file to perform CRUD action on datastore
```
@Injectable()
@Injectable({ scope: Scope.TRANSIENT })
export class DatastoreService {
datastore: Datastore;
kind: string;
constructor(
@InjectPinoLogger(DatastoreService.name) private logger: PinoLogger,
) {
this.datastore = new Datastore();
}
async upsert(data: any, id: string, kindName = this.kind): Promise<any> {
try {
this.logger.info(`Upsert operation in Datastore for id : ${JSON.stringify(id)}`);
let taskKey = this.datastore.key([kindName, id]);
let task = {
key: taskKey,
data: data
};
this.logger.info(`task: ${task}`);
return this.datastore.upsert(task);
}
catch (err) {
this.logger.error(`Error querying Datastore ${JSON.stringify(err)}`);
throw err;
}
}
}
```
Getting error:
```
{"code":5,"details":"","metadata":{"x-debug-tracking-id":["xxxxxxxxx;o=1"]}}
```
After checking online , Code 5 means auth related issue.
Things I tried:
1. I had provided Service Account permission and IAM role with owner .
2. Later I added all Datastore related role also.
3. Later , In Datastore client of DatastoreService, I passed projectId , keyFilename (absolute path), namespace.
But I am still facing same issue. Please point out where I am doing wrong.
Please point out where I am doing wrong. |
Unable to call datastore using GCP service account key json |
|node.js|google-cloud-platform|nestjs|google-oauth|google-cloud-datastore| |
So I have a "sign in with google" button on my site that uses the oauth2 flow to identity the user, but we don't request their email address as we don't strictly need it. This works fine and I can use the returned subject to identify users.
I would now like to create a file in a drive, and share it with this logged in user. I can create the file ok, but sharing it seems to require the users email.
Can I share a file to an external subject somehow, or will I need to ask them for an email address, either as an oauth2 scope or later once they have signed in?
The docs here:
https://developers.google.com/drive/api/guides/manage-sharing#create-permission
Say "When you create a permission where type=user or type=group, you must also provide an emailAddress to tie the specific user or group to the permission."
So maybe this is not possible? |
Microsoft doesn't provide the clearest documentation on the autodetect of relationships. It has been improving over the years. It used to be so bad, many developers would go into the settings and turn off autodetect for relationships. We would then manually create them. In general, it's a good practice to investigate every relationship for cardinality, and filter direction of data.
[Here's][1] Microsoft's documentation.
[1]: https://learn.microsoft.com/en-us/power-bi/transform-model/desktop-create-and-manage-relationships |
I have a react native iOS app in which I have to get/record user voice query and respond to that.
Now the thing is that I want this feature 'Interaction Less'. Like I don't want how ChatGPT mobile app did it. Like they had a headphone button, I press it, record my query and get answer. I don't want like this.
I want it 'Interaction Less' like we have Siri. Even if my iPhone is on side of the table and I say 'Hey Siri', it will start listening me. I want it like this.
So thinking to do it like this: Like user will say 'Hey {AppName}' and voice assistant of my app should start listening me.
Also thinking to do it via Siri because if my app went in background state [Auto-locked], even then I want my voice assistant to listen me.
Trying to figure out some way to implement this. But unable to find any way.
Can somebody guide me, how can I implement above thing in my ReactNative iOS app.
P.S: 'Interaction Less' means that phone shouldn't be in his hand. It can be in his pocket or on the side of the table.
Looking for documentation/guidance of how to incorporate Siri in React Native iOS app, to perform some functionality in my app through voice. |
How to incorporate Siri in React Native iOS app |
|ios|react-native|siri|sirikit|sirishortcuts| |
null |
What is the required mapping to rename a column label with a string function?
e.g. this works for all columns:
df.rename(columns=str.upper)
But with
df.rename(columns={'Col 2': str.upper})
the resulting label is:
<method 'upper' of 'str' objects>
----
import pandas as pd
import numpy as np
n = 4
df = pd.DataFrame(np.random.randint(0, 100, size=(5, n)),
columns=[f'Col {i}' for i in range(n)])
renamed = df.rename(columns={'Col 2': str.upper})
print(df)
print(renamed)
|
Mapping to rename a single column label with a function? |
|pandas|indexing|rename| |
So basically, I'm trying to do a Task manager on Android Studio with some additionnal features.
I began the project by doing a drawer menu which led me to do some fragment.
I am now doing the Task managing part, following this tutorial : https://www.youtube.com/watch?v=27MXFSWC1_4&list=PLzEWSvaHx_Z2MeyGNQeUCEktmnJBp8136&index=3&ab_channel=PenguinCoders
However, I have a slight problem using the ToDoAdapter :
```
public Todoadapter(TaskFragment activity){
activity.getActivity() = activity;}
```
Using this function I am doing a :
```
taskadapter = new Todoadapter(this);
```
And I getting an error that says :
```
unexpected type activity.getActivity() = activity;
required : variable
found : value
```
How could I resolve this issue ?
I tried changing the function with some different things, but that led me to basically nothing |
Are C labels instructions or constants |
|c|label|goto| |
null |
I have this data the id here (lr_01HT89SX627dFDPCAXBS4H2T9d) is dynamic.
https://www.example.com/api/pub/v2/verifications/lr_01HT89SX627dFDPCAXBS4H2T9d
I need to extract the id- lr_01HT89SX627dFDPCAXBS4H2T9d from https://www.example.com/api/pub/v2/verifications/ the id will be different for every response.
Header: HTTP/2 201
Header: date: Sat, 30 Mar 2024 18:26:29 GMT
Header: content-length: 0
Header: location: https://www.example.com/api/pub/v2/verifications/lr_01HT89SX627dFDPCAXBS4H2T9d
Header: cf-cache-status: DYNAMIC
How I got the above data
list($headers, $content) = explode("\r\n\r\n",$result,2);
foreach (explode("\r\n",$headers) as $hdr)
printf('<p>Header: %s</p>', $hdr);
echo $content;
I cant figure out how to do it. |
`foo()` is taking in a primitive `int` *by value*, so it is a *copy* of whatever value you pass in. There is no reference.
It doesn't matter what `foo()` does to `y`, that value is not reflected back to the caller.
Also, there is no such thing as "point at a value", either. You can point at a variable, but not at a value.
> then `x` becomes 3 because `y=y+2` and `y` was pointing at the value 1 of `x`.
>
> `foo(a[x])` is called with `a[3]` (which doesnt exists). `x` is decremented to 2.
This is incorrect. It is `y`, not `x`, that becomes 3. `x` is still 0 at this point. So the subsequent call to `foo(a[x])` is using `a[0]` instead, which decrements `x` to -1 and then sets `x` to 5. |
I think you have misunderstood CORS. You try to fetch some youtube URLs from localhost (with xhr I assume) which YOUTUBE doesn't allow with its CORS. Changing your own API CORS will allow other sites to fetch from your API
I also have a couple of notes on the question/update:
1. When asked what OPTIONS **returns**, we need the response, not the request
2. You added some CORS config to an `/api/` path but I can't see any in your screenshot of the structure.
Now, guessing a bit here since I can't be sure of what happens here, if you want to fetch a youtube video in your NextJS app, you need to fetch it FROM an API or a server component.
Anyways... You say that the `getYoutubeTranscript` is a server component and it fetches from youtube so I also think there is an error in the definition here somewhere since, if it was, you wouldn't have any CORS issues. I guess a missing `'use server'` somewhere...
My 2 cents on an alternative: As a rule, I never change my `page.tsx` to client components so that I can always fetch the necessary data there.
Final note: As far as I know, you are not allowed to fetch `youtube.com/watch` URLs only the embedded ones. Youtube videos will actually not play if not on their domains. But I may be mistaken here... |
I figured it out. I had to change the folder that this component was in. I had it in the same folder as the page.
The `/src` folder had both `page.tsx` and `icon.tsx`
I moved the `icon.tsx` to `/src/api/` and that resolved it. I feel silly for not realizing that but this page of the Next.js docs helped: https://nextjs.org/docs/app/building-your-application/routing/route-handlers#route-resolution |
Can you use the Drive API to share a file in Google Drive to an oath2 subject rather than email address? |
|google-drive-api| |
null |
Step 1: Install VS Code\
Step 2: Get ESP-IDF Explorer Extension\
Step 3: Click View -> Command Palette\
Step 4: Write "ESP-IDF: Configure ESP-IDF extension" and click\
Step 5: Click "EXPRESS"
I then get the error message: Invalid ESP-IDF
|
I get error message "Invalid ESP-IDF" when I configure the ESP-IDF extension |
I am trying to add overlay text to images using the GD library in php, while it works perfectly for characters in english, I am having rendering issues when the text is in hindi, even when the font used supports hindi text. Upon transformation and rendering on the image using the font, the result is not as desired.
I am using the font downloaded from here [RozhaOne](https://fonts.google.com/specimen/Rozha+One)
This is the code which I am executing
```
function createImageWithText()
{
$image = imagecreatefromjpeg($this->asset_url.'/images/input.jpeg');
$fontSize = 32;
list($r, $g, $b) = sscanf("#00bfff", "#%02x%02x%02x");
$fontColor = imagecolorallocate($image, $r, $g, $b);
$font = $this->asset_url.'/fonts/RozhaOne-Regular.ttf';
$text = "कृति";
imagettftext(
$image,
$fontSize,
0,
500,
500,
$fontColor,
$font,
$text
);
$save_path = $this->asset_url.'/images/output.png';
imagepng($image, $save_path);
imagedestroy($image);
}
```
Actual Output
[](https://i.stack.imgur.com/MzHf7.png)
Expected Output
[](https://i.stack.imgur.com/MTTPH.png)
I have tried the solution suggested [here](https://stackoverflow.com/questions/21188046/writing-hindi-fonts-with-gd-library-do-not-render-as-desired) and [here](https://stackoverflow.com/questions/16075553/gd-library-create-image-with-dynamic-text-on-it) but it did not work when I am using the font specified or other hindi supported fonts.
This seems to be an issue with the GD library (Using php 7.4) handling hindi font, would be great to get some insights on how this can be solved/supported. |
I have stuck with a pretty simple problem - I can't communicate with process' stdout.
The process is a simple stopwatch, so I'd be able to start it, stop and get current time.
The code of stopwatch is:
```python
import argparse
import time
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument('start', type=int, default=0)
start = parser.parse_args().start
while True:
print(start)
start += 1
time.sleep(1)
if __name__ == "__main__":
main()
```
And its manager is:
```python
import asyncio
class RobotManager:
def __init__(self):
self.cmd = ["python", "stopwatch.py", "10"]
self.robot = None
async def start(self):
self.robot = await asyncio.create_subprocess_exec(
*self.cmd,
stdout=asyncio.subprocess.PIPE,
)
async def stop(self):
if self.robot:
self.robot.kill()
stdout = await self.robot.stdout.readline()
print(stdout)
await self.robot.wait()
self.robot = None
async def main():
robot = RobotManager()
await robot.start()
await asyncio.sleep(3)
await robot.stop()
await robot.start()
await asyncio.sleep(3)
await robot.stop()
asyncio.run(main())
```
But `stdout.readline` returns an empty byte string every time.
When adding `await self.robot.stdout.readline()` to the end of the `RobotManager.start` method, it hangs forever.
However, when removing `stdout=asyncio.subprocess.PIPE` and all `readline` calls, the subprocess prints to the terminal as expected.
How do I read from the subprocess stdout correctly? |
Try using Scala 2 syntax (still working in Scala 3 so far)
fastparse.parse("1234", implicit p => parseAll(MyParser.int(p)))
https://scastie.scala-lang.org/DmytroMitin/MrFZ0EhiSPeFDHd1IyBhrA
Possible Scala 3 syntaxes are a little awkward:
fastparse.parse("1234", p => {given P[_] = p; parseAll(MyParser.int(p))})
https://scastie.scala-lang.org/DmytroMitin/MrFZ0EhiSPeFDHd1IyBhrA/11
fastparse.parse("1234", { case p @ given P[_] => parseAll(MyParser.int(p))})
https://scastie.scala-lang.org/DmytroMitin/MrFZ0EhiSPeFDHd1IyBhrA/13
fastparse.parse("1234", p => parseAll(MyParser.int(using p))(using p))
https://scastie.scala-lang.org/DmytroMitin/MrFZ0EhiSPeFDHd1IyBhrA/16
It would be nice if `fastparse.parse("1234", p ?=> parseAll(MyParser.int(p)))` worked, but this would require support on fastparse side.
---
https://stackoverflow.com/questions/72034665/correct-scala-3-syntax-for-providing-a-given-from-a-higher-order-function-argume
https://github.com/scala/scala3/discussions/12007 |
I write code for the ESP32 microcontroller.
I set up a class named "dmhWebServer".
This is the call to initiate my classes:
An object of the dmhFS class is created and I give it to the contructor of the dmhWebServer class by reference.
```
#include <dmhFS.h>
#include <dmhNetwork.h>
#include <dmhWebServer.h>
void setup()
{
// initialize filesystems
dmhFS fileSystem = dmhFS(SCK, MISO, MOSI, CS); // compiler is happy I have an object now
// initialize Activate Busy Handshake
dmhActivateBusy activateBusy = dmhActivateBusy();
// initialize webserver
dmhWebServer webServer(fileSystem, activateBusy); // compiler also happy (call by reference)
}
```
The class dmhFS has a custom constructor (header file, all good in here):
```
#include <Arduino.h>
#include <SD.h>
#include <SPI.h>
#include <LittleFS.h>
#include <dmhPinlist.h>
#ifndef DMHFS_H_
#define DMHFS_H_
class dmhFS
{
private:
// serial peripheral interface
SPIClass spi;
String readFile(fs::FS &fs, const char *path);
void writeFile(fs::FS &fs, const char *path, const char *message);
void appendFile(fs::FS &fs, const char *path, const char *message);
void listDir(fs::FS &fs, const char *dirname, uint8_t levels);
public:
dmhFS(uint16_t sck, uint16_t miso, uint16_t mosi, uint16_t ss);
void writeToSDCard();
void saveData(std::string fileName, std::string contents);
String readFileSDCard(std::string fileName);
};
#endif
```
Header file of the dmhWebServer class (not the whole thing):
```
public:
dmhWebServer(dmhFS &fileSystem, dmhActivateBusy &activateBusyHandshake);
};
```
This is the constructor of the dmhWebServer class:
```
#include <dmhWebServer.h>
#include <dmhFS.h>
#include <dmhActivateBusy.h>
// This is the line where the compiler throws an error ,character 85 is ")"
dmhWebServer::dmhWebServer(dmhFS &fileSystem, dmhActivateBusy &activateBusyHandshake)
{
// webserver sites handlers
setupHandlers();
dmhActivateBusy abh = activateBusyHandshake;
dmhFS sharedFileSystem = fileSystem;
// start web server, object "server" is instantiated as private member in header file
server.begin();
}
```
My compiler says: "src/dmhWebServer.cpp:5:85: error: no matching function for call to 'dmhFS::dmhFS()'"
Line 5:85 is at the end of the constructor function declaration
This is my first question on stackoverflow since only lurking around here :) I try to clarify if something is not alright with the question.
I checked that I do the call by reference in c++ right. I am giving the constructor "dmhWebServer" what he wants. What is the problem here? |
I'm encountering an issue in Code::Blocks where attempting to build C++ code results in the error message "Error: id returned 5 exit status," even when there are no syntax errors present in the code. Here's an example:
```
#include <iostream>
int main() {
std::cout<<"hello world";
}
```
Even for this simple code snippet, the same error occurs.
I've tried various troubleshooting steps such as granting full control permissions to the entire Code::Blocks folder for all users and temporarily disabling my antivirus software. However, none of these solutions resolved the issue.
Interestingly, I discovered that running Code::Blocks as an administrator and then using the file manager to navigate to the .cpp file, followed by building and running the code, works fine. However, this workaround doesn't apply when opening a project that includes external libraries.
I'm using the default GNU GCC compiler in Code::Blocks.
I appreciate any suggestions or insights on how to resolve this issue. Thank you!
Initially, I attempted to resolve the issue by granting full control permissions to the entire Code::Blocks folder for all users and temporarily disabling my antivirus software. However, these efforts did not resolve the error. My expectation was that these troubleshooting steps would rectify the issue and allow me to build C++ code without encountering the "Error: id returned 5 exit status" message. |
Title: Error: id returned 5 exit status when building C++ code in Code::Blocks |
|c++|access-denied| |
null |
i implemented chatbot in dart ... my issue which is i have many lists like greeting list , bye list and so on
when the use enter the question , the response will be only for the longest key
for example :
greeting list has [ hello ] --> return Hello how can i help you
bye list has [ Good Bye ] --> see you later
if the user input was : Hello good bye
the expected output : Hello how can i help you see you later
but the result was ' see you later '
i wanna it work as the expected
the chatbot i implemented depends on similarity between input and keys
```
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutterapp/screens/home_screen.dart';
import 'package:flutterapp/screens/search_screen.dart';
import 'package:flutterapp/screens/task_manager.dart';
import 'package:google_nav_bar/google_nav_bar.dart';
import 'package:google_fonts/google_fonts.dart';
import '../widgets/widgets.dart';
import 'chats_screen.dart';
import 'package:string_similarity/string_similarity.dart';
List<String> Letters =['\0','\0','\0'];
class chatbot_Screen extends StatefulWidget {
final int selectedIndex;
const chatbot_Screen({Key? key, required this.selectedIndex}) : super(key: key);
@override
State<chatbot_Screen> createState() => _chatbot_ScreenState(selectedIndex);
}
class _chatbot_ScreenState extends State<chatbot_Screen> {
_chatbot_ScreenState(this._selectedIndex);
int _selectedIndex = 2;
final List<String> _messages = [];
final TextEditingController _controller = TextEditingController();
void _handleSubmitted(String text) {
_controller.clear();
setState(() {
_messages.add("You \n$text");
_messages.add("Bot \n${_getResponse(text)}");
});
}
String? greetingList(String userText) {
List<String> greetings = [
'hello',
'hi',
'hey',
'howdy',
'hi there',
'hello there',
'greetings',
'good morning',
'good afternoon',
'good evening',
'hey there',
'yo',
'hiya',
'what\'s up',
'how\'s it going',
'nice to see you',
'how are you',
'how do you do',
'what\'s new',
'what\'s happening',
'sup',
'hola',
'bonjour',
'ciao',
'namaste',
'hallo',
'salutations',
'top of the morning to you',
'how are things',
'pleased to meet you',
'how\'s everything',
'what\'s cracking',
'what\'s good',
'how are you doing',
'good to see you',
'long time no see',
'how have you been',
'what\'s the news',
'how\'s your day',
'howdy-do',
'g\'day mate',
'hi-ya',
'how goes it',
'good day',
'what\'s popping',
'what\'s the craic',
'what\'s cooking',
'good to meet you',
'how\'s life',
'hi-ho',
'well hello there',
'what\'s the buzz',
'hi-de-ho',
'hi-ya',
'hi there, partner',
'how\'s your day going',
'what\'s the good word',
'what\'s shakin\'',
'what\'s happening',
'how\'s your morning',
'what\'s new with you',
'greetings and salutations',
'what\'s the latest',
'what\'s been happening',
'how are things going',
'how are you keeping',
'how\'s tricks',
'how\'s your day been',
'how goes the battle',
'how goes the day',
'how goes your day',
'how do you do',
'how\'s your afternoon',
'what\'s the news',
'how\'s your evening',
'good morning to you',
'how\'s it hanging',
'what\'s new with you',
'how\'s your day been',
'how are things with you',
'how do you fare',
'how\'s your afternoon been',
'how have you been doing',
'how\'s your day treating you',
'what\'s been going on',
];
// Define the target phrases for other responses
// Initialize variables to keep track of the maximum similarity and the best matching phrase
double maxSimilarity = 0; // to count the similarity of the user input and keys
String bestPhrase = ''; // the key has the most maxSimilarity it's gonna be ourphrase
// Iterate through the list of greetings and find the one with the highest similarity
for (String greeting in greetings) { //for i=0 , greeting[i] != null, i++
double similarity = userText.similarityTo(
greeting); //compareTwoString(str1,str2)
//and value between 0 to 1
if (similarity >
maxSimilarity) { //find the maximum similarity of the list
maxSimilarity = similarity;
bestPhrase =
greeting; //the phrase needed assigned to variable bestPhrase
}
}
// Iterate through the list of other phrases and find the one with the highest similarity
// Set a threshold for similarity score
double threshold = 0.5; // Adjust as needed
// If the best matching phrase has a similarity score above the threshold, respond accordingly
if (maxSimilarity >= threshold) {
Letters[0]='g';
if (bestPhrase == 'hello' || bestPhrase == 'hi') {
return 'Hello there! How can I help you today?';
} else if (bestPhrase == 'hey') {
return 'Hey! What can I do for you?';
} else if (bestPhrase == 'howdy') {
return 'Howdy! How can I assist you?';
} else if (bestPhrase == 'hi there') {
return 'Hi there! How may I assist you?';
} else if (bestPhrase == 'hello there') {
return 'Hello there! How can I assist you today?';
} else if (bestPhrase == 'greetings') {
return 'Greetings! How can I assist you today?';
} else if (bestPhrase == 'good morning') {
return 'Good morning! How may I help you?';
} else if (bestPhrase == 'good afternoon') {
return 'Good afternoon! How can I assist you today?';
} else if (bestPhrase == 'good evening') {
return 'Good evening! How may I assist you?';
} else if (bestPhrase == 'hey there') {
return 'Hey there! How can I help you today?';
} else if (bestPhrase == 'yo') {
return 'Yo! How can I assist you?';
} else if (bestPhrase == 'hiya') {
return 'Hiya! How may I help you?';
} else if (bestPhrase == 'what\'s up') {
return 'Hey! What\'s up?';
} else if (bestPhrase == 'how\'s it going') {
return 'Hey! How\'s it going?';
} else if (bestPhrase == 'nice to see you') {
return 'Nice to see you too! What can I assist you with?';
} else if (bestPhrase == 'how are you') {
return 'I\'m just a bot, but thanks for asking!';
} else if (bestPhrase == 'how do you do') {
return 'How do you do? How can I assist you today?';
} else if (bestPhrase == 'what\'s new') {
return 'Not much, just here to assist you. How about you?';
} else if (bestPhrase == 'what\'s happening') {
return 'Not much, just here to assist you. How about you?';
} else if (bestPhrase == 'sup') {
return 'Sup! How can I assist you today?';
} else if (bestPhrase == 'hola') {
return 'Hola! How can I assist you today?';
} else if (bestPhrase == 'bonjour') {
return 'Bonjour! How can I assist you today?';
} else if (bestPhrase == 'ciao') {
return 'Ciao! How may I assist you?';
} else if (bestPhrase == 'namaste') {
return 'Namaste! How can I help you today?';
} else if (bestPhrase == 'hallo') {
return 'Hallo! How may I assist you?';
} else if (bestPhrase == 'salutations') {
return 'Salutations! How can I assist you today?';
} else if (bestPhrase == 'top of the morning to you') {
return 'Top of the morning to you! How can I help you today?';
} else if (bestPhrase == 'how are things') {
return 'How are things with you? How can I assist you today?';
} else if (bestPhrase == 'pleased to meet you') {
return 'Pleased to meet you too! What can I assist you with?';
} else if (bestPhrase == 'how\'s everything') {
return 'How\'s everything going? How can I assist you today?';
} else if (bestPhrase == 'what\'s cracking') {
return 'Not much, just here to assist you. How about you?';
} else if (bestPhrase == 'what\'s good') {
return 'Not much, just here to assist you. How about you?';
} else if (bestPhrase == 'how are you doing') {
return 'I\'m just a bot, but thanks for asking!';
} else if (bestPhrase == 'good to see you') {
return 'Good to see you too! What can I assist you with?';
} else if (bestPhrase == 'long time no see') {
return 'Long time no see indeed! How may I assist you?';
} else if (bestPhrase == 'how have you been') {
return 'I\'m just a bot, but thanks for asking!';
} else if (bestPhrase == 'what\'s the news') {
return 'Not much, just here to assist you. How about you?';
} else if (bestPhrase == 'how\'s your day') {
return 'How\'s your day going? How can I assist you today?';
} else if (bestPhrase == 'howdy-do') {
return 'Howdy-do! How may I assist you?';
} else if (bestPhrase == 'g\'day mate') {
return 'G\'day mate! How can I assist you today?';
} else if (bestPhrase == 'hi-ya') {
return 'Hi-ya! How may I assist you?';
} else if (bestPhrase == 'how goes it') {
return 'How goes it? How may I assist you?';
} else if (bestPhrase == 'good day') {
return 'Good day! How can I assist you today?';
} else if (bestPhrase == 'what\'s popping') {
return 'What\'s popping? How may I assist you?';
} else if (bestPhrase == 'what\'s the craic') {
return 'What\'s the craic? How may I assist you?';
} else if (bestPhrase == 'what\'s cooking') {
return 'What\'s cooking? How may I assist you?';
} else if (bestPhrase == 'good to meet you') {
return 'Good to meet you too! What can I assist you with?';
} else if (bestPhrase == 'how\'s life') {
return 'How\'s life going? How may I assist you?';
} else if (bestPhrase == 'hi-ho') {
return 'Hi-ho! How may I assist you?';
} else if (bestPhrase == 'well hello there') {
return 'Well hello there! How may I assist you?';
} else if (bestPhrase == 'what\'s the buzz') {
return 'What\'s the buzz?';
} else if (bestPhrase == 'hi-de-ho') {
return 'Hi-de-ho! How may I assist you?';
} else if (bestPhrase == 'hi there, partner') {
return 'Hi there, partner! How may I assist you?';
} else if (bestPhrase == 'how\'s your day going') {
return 'How\'s your day going? How may I assist you?';
} else if (bestPhrase == 'what\'s the good word') {
return 'What\'s the good word? How may I assist you?';
} else if (bestPhrase == 'what\'s shakin\'') {
return 'What\'s shakin\'? How may I assist you?';
} else if (bestPhrase == 'what\'s happening') {
return 'What\'s happening? How may I assist you?';
} else if (bestPhrase == 'how\'s your morning') {
return 'How\'s your morning? How may I assist you?';
} else if (bestPhrase == 'what\'s new with you') {
return 'What\'s new with you? How may I assist you?';
} else if (bestPhrase == 'greetings and salutations') {
return 'Greetings and salutations! How may I assist you?';
} else if (bestPhrase == 'what\'s the latest') {
return 'What\'s the latest? How may I assist you?';
} else if (bestPhrase == 'what\'s been happening') {
return 'What\'s been happening? How may I assist you?';
} else if (bestPhrase == 'how are things going') {
return 'How are things going? How may I assist you?';
} else if (bestPhrase == 'how are you keeping') {
return 'How are you keeping? How may I assist you?';
} else if (bestPhrase == 'how\'s tricks') {
return 'How\'s tricks? How may I assist you?';
} else if (bestPhrase == 'how\'s your day been') {
return 'How\'s your day been? How may I assist you?';
} else if (bestPhrase == 'how goes the battle') {
return 'How goes the battle? How may I assist you?';
} else if (bestPhrase == 'how goes the day') {
return 'How goes the day? How may I assist you?';
} else if (bestPhrase == 'how goes your day') {
return 'How goes your day? How may I assist you?';
} else if (bestPhrase == 'how do you do') {
return 'How do you do? How may I assist you?';
} else if (bestPhrase == 'how\'s your afternoon') {
return 'How\'s your afternoon? How may I assist you?';
} else if (bestPhrase == 'what\'s the news') {
return 'What\'s the news? How may I assist you?';
} else if (bestPhrase == 'how\'s your evening') {
return 'How\'s your evening? How may I assist you?';
} else if (bestPhrase == 'good morning to you') {
return 'Good morning to you! How may I assist you?';
} else if (bestPhrase == 'how\'s it hanging') {
return 'How\'s it hanging? How may I assist you?';
} else if (bestPhrase == 'what\'s new with you') {
return 'What\'s new with you? How may I assist you?';
} else if (bestPhrase == 'how\'s your day been') {
return 'How\'s your day been? How may I assist you?';
} else if (bestPhrase == 'how are things with you') {
return 'How are things with you? How may I assist you?';
} else if (bestPhrase == 'how do you fare') {
return 'How do you fare? How may I assist you?';
} else if (bestPhrase == 'how\'s your afternoon been') {
return 'How\'s your afternoon been? How may I assist you?';
} else if (bestPhrase == 'how have you been doing') {
return 'How have you been doing? How may I assist you?';
} else if (bestPhrase == 'how\'s your day treating you') {
return 'How\'s your day treating you? How may I assist you?';
} else if (bestPhrase == 'what\'s been going on') {
return 'What\'s been going on? How may I assist you?';
}
}
// Fallback response
return null;
}
String? byeList(String userText) {
List<String> byeWords = [
'bye',
'goodbye',
'see you later',
'farewell',
'take care',
'see you',
'catch you later',
'adios',
'later',
'so long',
'until next time',
'bye for now',
'bye-bye',
'see ya',
'thank you',
'thanks',
'i love you',
];
double maxSimilarity = 0;
String bestPhrase = '';
for (String byeWord in byeWords) {
double similarity = userText.similarityTo(byeWord);
if (similarity > maxSimilarity) {
maxSimilarity = similarity;
bestPhrase = byeWord;
}
}
double threshold = 0.5;
// If the best matching phrase has a similarity score above the threshold, respond accordingly
if (maxSimilarity >= threshold) {
Letters[1]='b';
if (bestPhrase == 'bye' || bestPhrase == 'goodbye' || bestPhrase == 'thank you'
|| bestPhrase == 'thanks' || bestPhrase == 'i love you'
)
{
return 'Goodbye! Have a great day!';
}
else if (bestPhrase == 'see you later') {
return 'See you later! Take care!';
} else if (bestPhrase == 'farewell') {
return 'Farewell! Until we meet again!';
} else if (bestPhrase == 'take care') {
return 'Take care! See you soon!';
} else if (bestPhrase == 'catch you later') {
return 'Catch you later! Bye!';
} else if (bestPhrase == 'adios') {
return 'Adios! Hasta luego!';
} else if (bestPhrase == 'later') {
return 'Later! Take care!';
} else if (bestPhrase == 'so long') {
return 'So long! See you soon!';
} else if (bestPhrase == 'until next time') {
return 'Until next time! Bye!';
} else if (bestPhrase == 'bye for now') {
return 'Bye for now! See you later!';
} else if (bestPhrase == 'bye-bye') {
return 'Bye-bye! Take care!';
} else if (bestPhrase == 'see ya') {
return 'See ya! Have a good one!';
}
// Add more response conditions here for other bye words as needed
}
// Fallback response
return null;
}
String? drEmail(String userText) {
List<String>Dr_Names = [
'bassam hammo',
'firas alghanim',
'ahmad altamimi',
'ammar odeh'
,
'abdallah qusef',
'hazem qattous',
'abdullah al refai',
'rania alzubaidi'
];
double maxSimilarity = 0;
String bestPhrase = '';
for (String DrName in Dr_Names) {
double similarity = userText.similarityTo(DrName);
if (similarity > maxSimilarity) {
maxSimilarity = similarity;
bestPhrase = DrName;
}
}
double threshold = 0.4;
if (maxSimilarity >= threshold) {
Letters[2] = 'd';
if (bestPhrase == 'bassam hammo') {
return 'Email of Dr.Bassam Hammo that you are looking for is b.hammo@psut.edu.jo';
} else if (bestPhrase == 'firas alghanim') {
return 'Email of Dr.Firas Alghanim that you are looking for is f.ghanim@psut.edu.jo';
}
else if (bestPhrase == 'ahmad altamimi') {
return 'Email of Dr.Ahmad Altamimi that you are looking for is a.altamimi@psut.edu.jo';
}
else if (bestPhrase == 'ammar odeh') {
return 'Email of Dr.Ammar Odeh that you are looking for is a.odeh@psut.edu.jo';
}
else if (bestPhrase == 'abdallah qusef') {
return 'Email of Dr.Abdallah Qusef that you are looking for is a.qusef@psut.edu.jo';
}
else if (bestPhrase == 'hazem qattous') {
return 'Email of Dr.Hazem Qattous that you are looking for is h.qattous@psut.edu.jo';
}
else if (bestPhrase == 'abdullah al refai') {
return 'Email of Dr.Abdullah Al-Refai that you are looking for is a.alrefai@psut.edu.jo';
}
else if (bestPhrase == 'rania alzubaidi') {
return 'Email of Dr.Rania Alzubaidi that you are looking for is r.alzubaidi@psut.edu.jo';
}
}
return null;
}
String _getResponse(String userText) {
// Lowercase the user text to simplify matching
userText = userText.toLowerCase(); //Get the message from the user .
//to make sure we filled the list with the letters
String? isGreeting=greetingList(userText);
String? isBye=byeList(userText);
String? isDr=drEmail(userText);
//check which query needed
if (isGreeting!=null && isBye!=null && isDr!=null) {
return isGreeting + isBye + isDr;
}
else if (isGreeting!=null && isDr!=null) {
return isGreeting +isDr;
}
else if (isGreeting!=null && isBye!=null ) {
return isGreeting + isBye;
}
else if (isBye!=null && isDr!=null) {
return isBye + isDr;
}
else if (isGreeting!=null) {
return isGreeting;
}
else if (isBye!=null ) {
return isBye;
}
else if (isDr!=null) {
return isDr;
}
else {
return 'Sorry, I\'m not sure how to respond to that.';
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: const Text(
'Ask AI',
style: TextStyle(
color: Colors.blue,
fontSize: 30,
fontWeight: FontWeight.bold,
),
),
),
body: Column(
children: <Widget>[
Expanded(
child: ListView.builder(
padding: const EdgeInsets.all(8.0),
reverse: true,
itemCount: _messages.length,
itemBuilder: (_, int index) => Align(
alignment: Alignment.centerRight,
child: ListTile(
leading: _messages.reversed.toList()[index].contains("You")
? const Icon(Icons.person, color: Colors.blue)
: const Icon(Icons.chat_bubble_outline),
title: Text(
_messages.reversed.toList()[index],
style: TextStyle(
fontWeight: _messages.reversed.toList()[index].contains("You")
? FontWeight.normal
: FontWeight.normal,
),
),
),
),
),
),
const Divider(height: 1.0),
Container(
decoration: BoxDecoration(
color: Theme.of(context).cardColor,
),
child: _buildTextComposer(),
),
],
),
bottomNavigationBar: Container(
color: Colors.blue,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 15.0, vertical: 15.0),
child: GNav(
backgroundColor: Colors.blue,
color: Colors.white,
activeColor: Colors.white,
tabBackgroundColor: Colors.blue.shade200,
gap: 8,
selectedIndex: _selectedIndex,
onTabChange: _onItemTapped,
padding: const EdgeInsets.all(18),
tabs: [
GButton(
icon: Icons.home,
text: 'Home',
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const HomeScreen(selectedIndex: 0)),
);
},
),
GButton(
icon: Icons.chat_outlined,
text: 'Chats',
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const chatScreen(selectedIndex: 1)),
);
},
),
GButton(
icon: Icons.question_answer_outlined,
text: 'Ask AI',
),
GButton(
icon: Icons.assignment_sharp,
text: 'Task manager',
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const TaskManagar_Screen(selectedIndex: 3)),
);
},
),
],
),
),
),
);
}
Widget _buildTextComposer() {
return IconTheme(
data: IconThemeData(color: Theme.of(context).colorScheme.secondary),
child: Container(
margin: const EdgeInsets.symmetric(horizontal: 20.0, vertical: 8),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Flexible(
child: TextField(
controller: _controller,
onSubmitted: _handleSubmitted,
decoration: InputDecoration(
hintText: 'How can I help you today?',
hintStyle: GoogleFonts.albertSans(color: Colors.black54.withOpacity(0.5)),
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(
color: Colors.black.withOpacity(0.5),
width: 1,
),
borderRadius: BorderRadius.circular(20),
),
),
),
),
Container(
margin: const EdgeInsets.symmetric(horizontal: 4.0),
child: IconButton(
icon: const Icon(Icons.send),
onPressed: () => _handleSubmitted(_controller.text),
color: Colors.blue,
),
),
],
),
),
);
}
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
}
@override
void initState() {
super.initState();
_selectedIndex = widget.selectedIndex;
}
}
```
|
chatbot respond to onequery type |
|flutter|firebase|dart|package|chatbot| |
null |
I define a dx-data-grid with its proper dataSource (defined on the component) and a
<dx-<dxo-master-detail [enabled]="true" template="detail">
</dxo-master-detail>
<div *dxTemplate="let item of 'detail'">..
I'm trying to invoke a function when one of the grid rows is expanded.
The function makes an http request to fetch the proper data by passing the "row id".
Such data (an array of objects) should be shown inside the box of the dxo-master-detail.
I tried using onRowExpanded event function:
async onRowExpanded(e) {
const rowKey = e.key;
let userData= await this.getUserData(e.key.user_id);
return userData.data;
}
Eventhough the data is correctly returned from the function I not able to render it. |
DevExtreme dxo-master-detail load data function |
|typescript|devextreme|angular11| |
As stated in the top rated answer, it is not possible to directly configure a fallback font via JavaFX's css.
But it is possible when leveraging the internal JavaFX API. It is possible by directly manipulating the underlying `FontResource` of the `Font` via the Reflection API.
Here is a [demo](https://github.com/duoduobingbing/javafx-custom-font-fallback-demo) that shows how this can be done with JavaFX 21. |
There are two ways to filter documents that match a kNN query [pre-filters and post-filters][1]: You can choose the one that suits your use case.
1. pre-filtering – filter is applied during the approximate kNN search to ensure that `k` matching documents are returned.
2. post-filtering – filter is applied after the approximate kNN search completes, which results in fewer than `k` results, even when there are enough matching documents.
Yes, the first approach can be slow and the second approach can has low recall. You can increase the speed by decreasing the `num_candidates` value and you can tune the search relevancy by increasing the `num_candidates`. It's a trade-off between the search speed and relevancy.
### Pre-filtering
Pre-filtering is supported through the filter parameter **inside** of the kNN query. It creates a logical `OR` condition between `lexical search` and `kNN search`.
### Post-filtering
Post-filtering is supported through the filter parameter **outside** of the kNN query. It creates a logical `AND` condition between `lexical search` and `kNN search`.
---
> Continue to read for more details and an example.
separated kNN search and lexical search results
#match query
#1 hits.
GET collection-with-embeddings/_search
{
"query": {
"match": {
"text": "GLOSSARY"
}
}
}
#kNN query
#908 hits
GET collection-with-embeddings/_search
{
"knn": {
"field": "text_embedding.predicted_value",
"query_vector_builder": {
"text_embedding": {
"model_id": "sentence-transformers__msmarco-minilm-l-12-v3",
"model_text": "how do I cook my pasta?"
}
},
"k": 1000,
"num_candidates": 1000
},
"_source": [
"id",
"text"
]
}
\* pre-filtering (lexical filter outside of the kNN)
#hits: 908
GET collection-with-embeddings/_search
{
"query": {
"term": {
"text": "GLOSSARY"
}
},
"knn": {
"field": "text_embedding.predicted_value",
"query_vector_builder": {
"text_embedding": {
"model_id": "sentence-transformers__msmarco-minilm-l-12-v3",
"model_text": "how do I cook my pasta?"
}
},
"k": 1000,
"num_candidates": 1000
},
"_source": [
"id",
"text"
]
}
> The way vector and lexical matches are combined is through a
> disjunction (i.e., a logical OR condition) where the score of each
> document is computed using Convex Combination, i.e. the weighted sum
> of its vector and lexical scores, as we saw earlier.
> https://opster.com/guides/elasticsearch/operations/elasticsearch-hybrid-search/#Hybrid-search-with-dense-models
\* post-filtering (lexical filter inside of the kNN)
#hits 1
GET collection-with-embeddings/_search
{
"knn": {
"field": "text_embedding.predicted_value",
"query_vector_builder": {
"text_embedding": {
"model_id": "sentence-transformers__msmarco-minilm-l-12-v3",
"model_text": "how do I cook my pasta?"
}
},
"filter": {
"match": {
"text": "GLOSSARY"
}
},
"k": 1000,
"num_candidates": 1000
},
"_source": [
"id",
"text"
]
}
[1]: https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-knn-query.html#knn-query-filtering |
I'm 5 years late, but in case anybody else ever runs into this issue, you need to use the [browser runtime module][1] if you want to refer to files in your project directory. Something like this should work:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const htmlURL = chrome.runtime.getURL('index.html');
iframe.src = htmlURL
<!-- end snippet -->
[1]: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/runtime |
{"Voters":[{"Id":2152082,"DisplayName":"Stephan"},{"Id":1940850,"DisplayName":"karel"},{"Id":3074564,"DisplayName":"Mofi"}],"SiteSpecificCloseReasonIds":[11]} |
You can only **EMBED** Youtube videos in an *iframe* and it'll only work if they're not very popular (ie: most music videos with tons of views get blocked).
Here's how I do it, however... it is based on **data:text/html** to create a "openable" page on the fly and I'm not sure if this still works in the latest browser versions!
It may have been dropped for "security" reasons (read stupid reasons) like so many other wonderful things; and the reason I use a custom browser with older engines. :)
Anyway, in case it **does** work in the latest commercial browsers, here's how to do it...
let YT='https://www.youtube-nocookie.com/embed/vWq-mIxvH3k'; // change the last part after the slash to play another video
let Url='data:text/html;charset=utf-8,<html><head><title>Embedded video</title></head><body>'+
'<iframe width="0" height="0" src="'+YT+'" frameborder="0" style="position:absolute;left:0;top:0;width:100%;height:100%;background:black;" allowfullscreen>'+
'</iframe></body></html>';
let a=document.createElement('A');
a.target='_blank';
a.href=Url;
a.click();
|
On successful paid orders for all payment gateways *others than Bank wire, cheque or Cash on delivery,* you can use dedicated [`woocommerce_payment_complete` hook located in `WC_Order` `payment_complete()` method][1] instead of more generic hook `woocommerce_thankyou`, like:
```
add_action( 'woocommerce_payment_complete', 'action_payment_complete', 10, 2 );
function action_payment_complete( $order_id, $order ) {
// Here add your code
}
````
Note that you can use defined `$order_id` and `$order` function arguments. Also this hook is only triggered once, avoiding repetitions.
--------
**For Bank wire (bacs), Cheque (cheque) or Cash on delivery (cod)** payment methods, As the shop manager confirm manually that order is paid by changing order status, you can use the dedicated hook `woocommerce_order_status_changed` as follows.
```
add_action( 'woocommerce_order_status_changed', 'bacs_cheque_cod_payment_complete', 10, 4 );
function bacs_cheque_cod_payment_complete( $order_id, $old_status, $new_status, $order ) {
// 1. For Bank wire and cheque payments
if( in_array( $order->get_payment_method(), array('bacs', 'cheque') )
&& in_array( $new_status, wc_get_is_paid_statuses() ) ) {
// Do something
}
// 2. For Cash on delivery payments
if( 'cod' === $order->get_payment_method() && 'completed' === $new_status ) {
// Do something
}
}
```
Note that you can use defined `$order_id` and `$order` function arguments. Also this hook will be triggered once, on order status change, avoiding repetitions.
------
**Related:** https://stackoverflow.com/questions/48464499/after-a-successful-payment-what-hook-is-triggered-in-woocommerce/48468736#48468736
[1]: https://github.com/woocommerce/woocommerce/blob/4.9.0/includes/class-wc-order.php#L121 |
I have the following bash shell script which I want to schedule every day at 5:00 PM using lambda custom run time.
```
#!/usr/bin/bash
declare -a end_points
end_points=$(aws ec2 describe-vpc-endpoints --filters "Name=vpc-endpoint-type,Values=Interface" --query 'VpcEndpoints[*].VpcEndpointId' --output text)
for ((i=0; i < ${#end_points[@]}; i++ ));
do
echo "${end_points[$i]}";
done
```
Here is what I did using the AWS console -
1. Selected Amazon Linux 2 as the custom runtime
2. Added the layer -- arn:aws:lambda:<region>:744348701589:layer:bash:8
3. Here is my function.sh ( Just to test before I could run my above script) --
```
function handler ()
{ EVENT_DATA=$1
DATA=$(aws s3 ls)
RESPONSE="{\"statusCode\": 200, \"body\": \"$DATA\"}"
echo $RESPONSE
```
I am getting the following error -- */var/task/function.sh: line 10:
/opt/bin/aws: cannot execute: required file not found* |
Unable to run Bash Script using AWS Custom Lambda Runtime |
|amazon-web-services|aws-lambda| |
<!-- language-all: js -->
*Here's one approach (**`non-regex`**) you may test out in Sheets:*
=let(Λ,A2, Σ,map(sequence(rounddown(len(Λ)/2)),lambda(Σ,{left(Λ,Σ),left(Λ,Σ)=mid(Λ,Σ+1,Σ)})),
ifna(+filter(Σ,index(Σ,,2)),"-"))
[![enter image description here][1]][1]
- lists all probabilities using **`left()`** and **`mid()`** to filter out the
possible match if any...
[1]: https://i.stack.imgur.com/f7ve6.png |
Creating a module for this purpose is inevitable and not a strenuous task at all. All u need is a `package.json` with an `exports` field to limit which submodules can be loaded from within the package. From the [official Node.js docs](https://nodejs.org/api/packages.html#exports):
> The "exports" field allows defining the entry points of a package when imported by name loaded via a node_modules lookup. It is an alternative to the "main" that can support defining subpath exports and conditional exports while encapsulating internal unexported modules
⚠️ Note that all paths defined in the `"exports"` must be relative file URLs starting with `./` except for the default one `.`
So in your case, the `package.json` inside your `facade` folder would be:
```json
{
"name": "@facade",
"private": true,
"version": "0.0.0",
"exports": {
"./B.tsx": "./B.tsx"
}
}
```
Now the external code outside of the `facade` folder (a.k.a the `@facade` package) can only `import {B} from "@facade/B.tsx";`. Both `@facade/A.tsx` and `"@facade/C.tsx"` are inaccessible to the external code. |
`app` defined in *app.py* and `app` created within the `client` fixture are **two different `Flask` instances**, and the instance from the fixture doesn't have the route applied via the `@app.route` decorator.
The solution is to use the same `app` object from *app.py* in your tests. That obviously means that you would need to change the way the application is configured so that it uses `TestConfig`. Unfortunately, the way I used to configure Flask when I was working with it is too complex to describe in this answer, and I don't have an alternative good solution on hand.
Therefore, take the following code sample rather as a crude fix and **NOT as a solid example for production code**:
```python
import pytest
from app import app as real_app
from config import TestConfig
@pytest.fixture(scope="session")
def app():
# WARNING: existing config keys not specified in TestConfig
# would not be removed
real_app.config.from_object(TestingConfig)
real_app.test_request_context().push()
return real_app
@pytest.fixture
def client(app):
with app.test_client() as client:
yield client
def test_login_get(client):
response = client.get("/login")
assert response.status_code == 200
``` |
How to solve compiler error: no matching function for call to 'class::ctor()' in my case? |
|c++|class|object|constructor|esp32| |
null |
I am trying to configure records on aws by looping instructions from my data source.
the data source looks like this:
```
data "dns_instructions" "example-dns-instructions" {
id = "123"
instructions {
name = "www.example.com"
type = "A"
value = "1.2.3.4"
}
instructions {
name = "a.example.com"
type = "TXT"
value = "value 1"
}
}
```
I tried the following:
```
resource "aws_route53_record" "my-records" {
for_each = {
for inst in data.dns_instructions.example-dns-instructions.instructions :
"${inst.id}" => inst
}
zone_id = "ABCSDSD....."
name = each.value.name
type = each.value.type
ttl = 300
records = each.value.value
}
```
I do see the data source with all details in the TF state but when trying to apply, getting:
```
data.dns_instructions.example-dns-instructions.instructions is null
│
│ A null value cannot be used as the collection in a 'for' expression.
```
I am probably missing something basic in terraform, can someone please assist?
|
Terraform - loop over complex data in data source |
|terraform| |
I'm working on a Rails application where I'm using amCharts 5 to create charts. I have a requirement to display the legend name along with its corresponding color in the tooltip text for each series in the chart. I've tried several approaches, including customizing the tooltip function, but I'm encountering difficulties in achieving the desired result.
[](https://i.stack.imgur.com/nwpQU.png)
```
` series.columns.template.set("tooltipHTML", am5.Tooltip.new(root, {
tooltipHTML: function(dataItem) {
var seriesName = dataItem.series.name;
var color = dataItem.series.fill.hex;
var valueX = dataItem.categoryX;
var valueY = dataItem.valueY;
var seriesColorBox = '<span style="display:inline-block; width:12px; height:12px; background-color:' + color + '; margin-right: 5px;"></span>';
return valueX + ', Number of appointments<br>' +
'Total: ' + valueY + '<br>' +
seriesColorBox +
'<span style="color: black;">' + seriesName + ': ' + valueY + '</span><br>';
}
}));`
```
Despite trying this approach and others, I'm not achieving the desired outcome. The tooltip text is not displaying the legend name and color correctly.
Any insights or suggestions on how to resolve this issue and correctly display the legend colors in the tooltip text would be greatly appreciated! |
How to display legend box in tooltip text for amCharts 5 in Rails application? |
|javascript|ruby-on-rails|chart.js|tooltip|amcharts| |
null |
I have developed a tool [here](https://github.com/ae-creator/CosmosJS/tree/fix-declarations
) to facilitate my development with bun.sh using workspaces that will be used as npm package however I have 2 problems,
When I bun install the 'core' packages from npm and test a sample, I get this error:
Could not find a declaration file for module '@cosmoosjs/core', index.js' implicitly has an 'any' type.
I tried [this](https://stackoverflow.com/a/41307319/15431338), but it doesn't work
The second problem is that when I try to build the typescript declarations for the hono package [here](https://github.com/ae-creator/CosmosJS/tree/fix-declarations/packages/hono-openapi-adapter), it crashes and can't load them because it refers to the other module via a workspace. I can't build the declarations but I can build the project.
|