instruction stringlengths 0 30k β |
|---|
I am making a battleship project from scratch. What would be a way to identify a *specific* point on the map, and let you choose it, and then print out the chosen grid, with the "#" replaced with something else like a "X"?
Here's the code:
```
turns = 10
alphabet = ["A","B","C","D","E","F","G","H","I","J","a","b","c","d","e","f","g","h","i","j"]
def StartScreen():
print("Welcome to Battleship!")
print('''
1. Start
2. Exit
''')
choice = int(input("Enter your number: "))
if choice == 1:
GameScreen()
elif choice == 2:
exit()
else:
print("Please choose a valid number.")
StartScreen()
def GameScreen():
print("\n")
print(" A B C D E F G H I J")
row = [" # ", "# ", "# ", "# ", "# ", "# ", "# ", "# ", "# ", "# "]
i = -1
while i != 9:
print(i+1, row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7], row[8], row[9])
i = i + 1
print("\n")
rowx = input("Choose a letter(A-J): ")
rowy = int(input("Enter a number(0-9): "))
if rowx in alphabet and rowy in range(0,10):
print(f'you chose {rowx.upper()}{rowy}')
else:
print("Please choose a valid point(A-J/0-9)\n")
StartScreen()
``` |
{"Voters":[{"Id":23922491,"DisplayName":"Piotr GasidΕo"}]} |
A `foreach()` loop will allow array data to be unpacked into variables use array destructuring syntax, but the example below will only get the first email from each subset.
Code: ([Demo][1])
foreach ($array as ['email_do_convidado' => [$email]]) {
echo "$email\n";
}
Result:
johndoe@gmail.com
lorem@gmail.com
If your input array had more than one email per subset, you'd need a nested iterator like: ([Demo][2])
foreach ($array as ['email_do_convidado' => $emails]) {
foreach ($emails as $email) {
echo "$email\n";
}
}
---
If you want to merely fetch all of the emails as a delimited string, you can use functional-style programming to isolate a column of values, flatten the results, then implode. ([Demo][3])
echo implode(
"\n",
array_merge(
...array_column(
$array,
'email_do_convidado'
)
)
);
[1]: https://3v4l.org/drauQ
[2]: https://3v4l.org/utXkE
[3]: https://3v4l.org/s918i |
null |
A bit beter patch:
+ if (p->nullValue[0] != '\0' && cli_strcmp(z, p->nullValue)==0) sqlite3_bind_null(pStmt, i+1);
+ else sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
Now, when .nullvalue is set its value is replaced to NULL while importing CSV/TSV file. |
Here is my code: https://github.com/d0uble-happiness/DiscogsCsvVue
App.vue
<template>
<div>
<FileUpload @file="setFile" />
<ParseCsvToArray v-if="file" :file="file" />
<ProcessReleaseData />
<FetchRelease />
<DownloadCSV />
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import FileUpload from './components/FileUpload.vue';
import ParseCsvToArray from './components/ParseCsvToArray.vue';
import ProcessReleaseData from './components/ProcessReleaseData';
import FetchRelease from './components/FetchRelease';
import DownloadCSV from './components/DownloadCSV';
export default defineComponent({
name: 'App',
components: {
FileUpload,
ParseCsvToArray,
ProcessReleaseData,
FetchRelease,
DownloadCSV
},
data() {
return {
file: null as null | File,
}
},
methods: {
setFile(file: File) {
console.log("Received file:", file)
this.file = file;
}
},
mounted() {
console.log("mounted");
},
});
</script>
<style></style>
processReleaseData.vue
import { type GetReleaseResponse } from '@lionralfs/discogs-client/types/types';
export default {
name: 'ProcessReleaseData',
methods: {
processReleaseData
}
}
export function processReleaseData(releaseId: string, data: GetReleaseResponse) {
const { country = 'Unknown', genres = [], styles = [], year = 'Unknown' } = data;
const artists = data.artists?.map?.(artist => artist.name);
const barcode = data.identifiers.filter(id => id.type === 'Barcode').map(barcode => barcode.value);
const catno = data.labels.map(catno => catno.catno);
const uniqueCatno = [...new Set(catno)];
const descriptions = data.formats.map(descriptions => descriptions.descriptions);
const format = data.formats.map(format => format.name);
const labels = data.labels.map(label => label.name);
const uniqueLabels = [...new Set(labels)];
const qty = data.formats.map(format => format.qty);
const tracklist = data.tracklist.map(track => track.title);
// const delimiter = document.getElementById('delimiter').value || '|';
const delimiter = '|';
const formattedBarcode = barcode.join(delimiter);
const formattedCatNo = uniqueCatno.join(delimiter);
const formattedGenres = genres.join(delimiter);
const formattedLabels = uniqueLabels.join(delimiter);
const formattedStyles = styles.join(delimiter);
const formattedTracklist = tracklist.join(delimiter);
const preformattedDescriptions = descriptions.toString().replace('"', '""').replace(/,/g, ', ');
const formattedDescriptions = '"' + preformattedDescriptions + '"';
const formattedData: any[] = [
releaseId,
artists,
format,
qty,
formattedDescriptions,
formattedLabels,
formattedCatNo,
country,
year,
formattedGenres,
formattedStyles,
formattedBarcode,
formattedTracklist
];
return formattedData;
}
But for some reason I'm getting this error when I try to run my app:
> Internal server error: Failed to resolve import "@lionralfs/discogs-client/types/types" from "src/components/ProcessReleaseData.ts". Does the file exist?
I checked tsconfig.app.json, and it looks fine to me:
{
"extends": "@vue/tsconfig/tsconfig.dom.json",
"include": ["env.d.ts", "src/**/*", "src/**/*.vue", "csv.ts", "src/**/*.ts"],
"exclude": ["src/**/__tests__/*"],
"compilerOptions": {
"composite": true,
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
}
}
}
Module "d:/MY DOCUMENTS/CODE/DISCOGS API CLIENT/DiscogsCsvVue/node_modules/@lionralfs/discogs-client/types/types" appears to be valid and is showing up just fine in VsCode. I copied the location from the VSCode pop-up so I don't see any issue there. `import { DiscogsClient } from '@lionralfs/discogs-client';` is working just fine in another file in the same directory.
Any tips please? TIA |
Failed to resolve import, but the path is valid, and detected as such by VSCode |
|typescript|vue.js| |
day_of_week feb_23 mar_23 apr_23 may_23 jun_23
<chr> <int> <int> <int> <int> <int>
sunday 24575 48314 83366 84074 116821
monday 32208 46043 78434 85285 122528
tuesday 41347 56317 101060 76440 101694
wednesday 25792 51056 61445 98910 94837
thursday 21852 46027 71823 83957 117189
friday 38517 69504 75012 131155 104023
saturday 24284 24948 73140 84078 130631
I am trying to do a line graph with theses informations, but I can't do it. I would like to use each day of week in a line to represent each month.
I've tried several ways but I deleted the previous ones. The last one was:
ggplot(trip_id, aes(y=day_of_week))+geom_line(aes(x=feb_23))+geom_line(aes(x=mar_23))+geom_line(aes(x=apr_23))
|
How can I solve this problem in Geom_line? |
|r|charts|line|geom| |
null |
The OP's problem qualifies perfectly for a solution of mainly 2 combined techniques ...
1) the [`map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) based creation of a list of [async function/s (expressions)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/async_function), each function representing a delaying broadcast task (_delaying_ and not _delayed_ because the task executes immediately but delays its resolving/returning time).
2) the creation of an [async generator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AsyncGenerator) via an [async generator-function (expression)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/async_function*), where the latter consumes / works upon the created list of delaying tasks, and where the async generator itself will be iterated via the [`for await...of` statement](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of).
In addition one needs to write kind of a `wait` function which can be achieved easily via an async function which returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise) instance, where the latter resolves the promise via [`setTimeout`](https://developer.mozilla.org/en-US/docs/Web/API/setTimeout) and a customizable delay value.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const queueData =
["Sample Data 1", "Sample Data 2", "Sample Data 3"];
// create a list of async function based "delaying tasks".
const delayingTasks = queueData
.map(data => async () => {
wss.broadcast(
JSON.stringify({ data })
);
await wait(1500);
return `successful broadcast of "${ data }"`;
});
// create an async generator from the "delaying tasks".
const scheduledTasksPool = (async function* (taskList) {
let task;
while (task = taskList.shift()) {
yield await task();
}
})(delayingTasks);
// utilize the async generator of "delaying tasks".
(async () => {
for await (const result of scheduledTasksPool) {
console.log({ result });
}
})();
<!-- language: lang-css -->
.as-console-wrapper { min-height: 100%!important; top: 0; }
<!-- language: lang-html -->
<script>
const wss = {
broadcast(payload) {
console.log('broadcast of payload ...', payload);
},
};
async function wait(timeInMsec = 1_000) {
return new Promise(resolve =>
setTimeout(resolve, Math.max(0, Math.min(timeInMsec, 20_000)))
);
}
</script>
<!-- end snippet -->
And since the approach is two folded, one even can customize each delay in between two tasks ... one just slightly has to change the format of the to be queued data and the task generating mapper functionality (2 lines of code are effected) ...
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
// changed format.
const queueData = [
{ data: "Sample Data 1", delay: 1000 },
{ data: "Sample Data 2", delay: 3000 },
{ data: "Sample Data 3", delay: 2000 },
{ data: "Sample Data 4" },
];
// create a list of async function based "delaying tasks".
const delayingTasks = queueData
.map(({ data, delay = 0 }) => async () => { // changed argument.
wss.broadcast(
JSON.stringify({ data })
);
await wait(delay); // changed ... custom delay.
return `successful broadcast of "${ data }"`;
});
// create an async generator from the "delaying tasks".
const scheduledTasksPool = (async function* (taskList) {
let task;
while (task = taskList.shift()) {
yield await task();
}
})(delayingTasks);
// utilize the async generator of "delaying tasks".
(async () => {
for await (const result of scheduledTasksPool) {
console.log({ result });
}
})();
<!-- language: lang-css -->
.as-console-wrapper { min-height: 100%!important; top: 0; }
<!-- language: lang-html -->
<script>
const wss = {
broadcast(payload) {
console.log('broadcast of payload ...', payload);
},
};
async function wait(timeInMsec = 1_000) {
return new Promise(resolve =>
setTimeout(resolve, Math.max(0, Math.min(timeInMsec, 20_000)))
);
}
</script>
<!-- end snippet -->
|
I guess this is silly question, but I am confused as to how can regex `.*` match all the strings?
`*`: zero or more occurrences of the preceding element,
`.`: matches any one character,
So, in `.*`, `.` should match any one character( say 'x'), then `*` would mean 0 or more occurrences of 'x',
thus giving us strings like:
"",
"x",
"xx",
"xxx",
"xxxxxxx",.. etc.
But how is it able to match any random string like "ab12b3v34"?
Shouldn't this be actually the case for `[.*]*`?
What am i missing here please explain. |
Clarity on how can `.*` match all strings? |
|regex|string-matching| |
null |
I am writing a program in which I need to analyse the impact of rounding off on the result. The algorithm shall be implemented as fixed-point math eventually.
In my program I need to see what impact it has if I round off certain part of the calculation to 4, 3, 2, 1 decimal places and also integer. However, I found that C++ contains the round() method but this only gives integer result.
How is it that, C++ does not contain a way to round to specific number of decimal places that is built into it?
I found this from somewhere on the internet:
double round_up(double value, int decimal_places) {
const double multiplier = std::pow(10.0, decimal_places);
return std::ceil(value * multiplier) / multiplier;
}
But why should this be required, C++ is supposed to have a built in method to do this!
EDIT:
I am creating a design for FPGA implementation. The design shall be written in SystemVerilog. I want to investigate how many digits after decimal I should use for the fixed point maths. Yes, I am designing an actual ALU for discrete cosine transform IN HARDWARE. I could go into ASIC later i.e on silicon. I want to see how many digits I should have after decimal that is a reasonable trade-off for area vs accuracy. This is why I wrote a C++ program to investigate this. However, it seems that this was a false idea all along. |
from django import forms
from django.contrib.auth.models import User
class SignupForm(forms.ModelForm):
class Meta:
model = User
fields = ['username', 'password',
'first_name', 'last_name',
'email']
widgets = {
'password': forms.PasswordInput()
}
|
I am trying to setup node 15.3.2 version using docker compose file. I have added all the necessary requirements in dockerfile. But after executing ```docker compose up``` command, I am facing below error. I tried ```docker compose --build``` command as well. If any one have any solution please let me know.
Dockerfile
FROM node:15-alpine3.10
WORKDIR /var/apps/frontend
COPY frontend /var/apps/frontend/
RUN apk update
RUN apk add alpine-sdk
RUN apk add --update npm
RUN apk add --update python3 make g++ && rm -rf /var/cache/apk/*
RUN npm install -g npm@9.9.2
RUN rm -rf node_modules
RUN npm cache clean --force
RUN npm rebuild node-sass --force
RUN npm i react@15.3.2 --legacy-peer-deps
RUN npm install --legacy-peer-deps
CMD [ "npm", "start" ]
docker-compose.yml
frontend:
build:
context: .
dockerfile: ./docker/frontend/Dockerfile
container_name: ui
command: bash -c "npm config set package-lock false && npm install && yarn run docker"
networks: ['ao_platform_network']
depends_on: ['django']
ports:
- "8081:8081"
environment:
- RAILS_ENV=development
- RAKE_ENV=development
- NODE_ENV=development
volumes:
- type: bind
source: ./frontend
target: /var/apps/frontend
Error:
node:internal/modules/cjs/loader:927
throw err;
^
Error: Cannot find module '/var/apps/frontend/bash'
at Function.Module._resolveFilename (node:internal/modules/cjs/loader:924:15)
at Function.Module._load (node:internal/modules/cjs/loader:769:27)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:76:12)
at node:internal/main/run_main_module:17:47 {
code: 'MODULE_NOT_FOUND',
requireStack: []
} |
Error: Cannot find module '/var/apps/frontend/bash' |
|node.js|dockerfile| |
Hey here's my settings and value of confPath String, it worked after I moved the file to src/main/resources
[1]: https://i.stack.imgur.com/GCWEt.png |
It's possible only if you check the checkbox "Keep my email addresses private", in which case all web-based Git operations will use the generated `@users.noreply.github.com` email.
Downside: You can't use your public email in your web commits either.
If you don't check this option, GitHub will leak your "private" primary email in a few cases that I know of (from my experience with this "feature"):
* When you commit something via the web UI and forget to select your public email in the dropdown menu - the primary email sometimes is selected by default, even if you've been using your public email in all of the commits prior to that
* When maintainers merge your pull requests via the squash strategy - this one is not obvious, I've had this happen to me a couple of times
|
In React component can not debounce handleChange |
|reactjs|debouncing| |
embedPy needs to make a call to Python.
It tests `python3` first and if that fails it tries `python`.
You can test on your command prompt to check if they run:
```
C:\Users\rianoc>where python3
C:\Users\rianoc\AppData\Local\Microsoft\WindowsApps\python3.exe
C:\Users\rianoc>where python
C:\Users\rianoc\AppData\Local\Microsoft\WindowsApps\python.exe
C:\Users\rianoc>python3 -c "print('.'.join([str(getattr(__import__('sys').version_info,x))for x in ['major','minor']]));"
3.11
C:\Users\rianoc>python -c "print('.'.join([str(getattr(__import__('sys').version_info,x))for x in ['major','minor']]));"
3.11
```
These can also be tested from `q`:
```
q)system"where python3"
"C:\\Users\\rianoc\\AppData\\Local\\Microsoft\\WindowsApps\\python3.exe"
q)system"where python"
"C:\\Users\\rianoc\\AppData\\Local\\Microsoft\\WindowsApps\\python.exe"
q)system"python3 -c \"print('.'.join([str(getattr(__import__('sys').version_info,x))for x in ['major','minor']]));\""
"3.11"
q)system"python -c \"print('.'.join([str(getattr(__import__('sys').version_info,x))for x in ['major','minor']]));\""
"3.11"
``` |
I've encountered an issue where I need to remove a MongoDB document by its `_id` without utilizing ObjectId in the PyMongo library. Typically, it seems that ObjectId needs to be imported and used for identifying documents for removal. However, I'm exploring whether there's an alternative method to achieve this without relying on `ObjectId`. As an example below is the document that i wish to remove
MongoDB Document
```js
{ _id: ObjectId("65fee1b40839f1f886ee94a9"), category: 'Cars' }
```
Python code with PyMongo
```py
import pymongo
from bson import ObjectId
document_id = ObjectId("65fee1b40839f1f886ee94a9")
result = collection.delete_one({"_id": document_id})
if result:
return result.deleted_count
```
In This example i have used `ObectId` for document removal. Could anyone provide insights or suggestions on how to remove a document by its `_id` using PyMongo without explicitly using ObjectId? |
I have a following piece of code:
```
...
body: TabBarView(
controller: tabController,
children: <Widget>[
FutureBuilder(
future: customerController.getAllCustomers(),
builder: (BuildContext context,
AsyncSnapshot<List<CustomerModel>> snapshot) {
if (snapshot.hasData) {
print('showing real data: ${timer.elapsedMilliseconds}ms');
return AllCustomerView(
customerList: snapshot.data!,
setState: setState,
);
} else {
print('shimmer: ${timer.elapsedMilliseconds}ms');
return Shimmer.fromColors(
baseColor: Colors.grey.shade300,
highlightColor: Colors.grey.shade100,
enabled: true,
child: ListView.builder(
key: new PageStorageKey('customerList'),
itemCount: 20,
itemBuilder: (context, index) {
return Padding(
padding: const EdgeInsets.only(left: 8.0, right: 8),
child: ListWidget(
isSaved: false,
isShowingLoader: true,
),
);
},
),
);
}
}),
...
```
and debug Console shows the timings I made using Stopwatch (see "print" calls in the code)
```
I/flutter (25917): initState: 3ms
I/flutter (25917): before setState: 6ms
I/flutter (25917): after setState: 7ms
I/flutter (25917): initState END: 10ms
I/flutter (25917): build finished: 44ms
I/flutter (25917): shimmer: 220ms
I/flutter (25917): getAllCustomers timer1: 1551ms
I/flutter (25917): getAllCustomers timer2: 26ms
I/flutter (25917): getAllCustomers timer3: 41ms
I/flutter (25917): showing real data: 11026ms
```
The problem is, I never get to see the shimmer. The app hangs on the previous screen until after snapshot.hasData is true in the FutureBuilder. Then I see the complete pupulated list (AllCustomerView).
It seems the flutter prioritizes the getAllCustomers call, instead of UI rendering the page.
Any Ideas what I might be doing wrong? |
I am using pg-promise for performing a multi row insert of around 800k records and facing the following error:
Error: Connection terminated unexpectedly
at Connection.<anonymous> (/usr/src/app/node_modules/pg/lib/client.js:132:73)
at Object.onceWrapper (node:events:509:28)
at Connection.emit (node:events:390:28)
at Socket.<anonymous> (/usr/src/app/node_modules/pg/lib/connection.js:63:12)
at Socket.emit (node:events:390:28)
at TCP.<anonymous> (node:net:687:12)
I have already tried to configure the connection with parameters like idleTimeoutMillis, connectionTimeoutMillis (also tried adding and removing parameters like keepAlive, keepalives_idle, statement_timeout, query_timeout) and still facing the issue.
const db = pgp({
host: host,
port: port,
database: database,
user: user,
password: pass,
idleTimeoutMillis: 0, // tried with multiple values
connectionTimeoutMillis: 0, // tried with multiple values
keepAlive: true,
keepalives_idle: 300,
statement_timeout: false,
query_timeout: false,
});
Any help is highly appreciated.
PS: I am able to insert around 300k records without defining any of the extra parameters mentioned above. |
A bit beter patch:
+ if (p->nullValue[0] != '\0' && cli_strcmp(z, p->nullValue)==0) sqlite3_bind_null(pStmt, i+1);
+ else sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
- sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
Now, when .nullvalue is set its value is replaced to NULL while importing CSV/TSV file. |
How to implement a sorted custom list class |
Someone deployed a ChatGPT Web app in Azure for me, but the version installed from the repository is from a few months ago. I'm trying to figure out how to update the external Git, but if I reconnect it, the whole app breaks (I get a 500 error).
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/TdnAL.png |
How to update to the latest external Git in Azure Web App? |
|azure|github| |
The standard way to define a file is to use a FILE definition that is saved to the CICS CSD. When defining a FILE you use the dataset name (DSNAME attribute) as the base, path or alternate index.
See the IBM docs for more details
https://www.ibm.com/docs/bg/cics-ts/5.3?topic=resources-file-attributes |
A bit late on the topic, but I was struggling with the same error.
What solved the issue for me was renaming the `layout.js` file to `_layout.js`.
For some reason the file was not rendered without the underscore as prefix. |
Another slight variation for benchmark, though the change is not that radical.
``` r
df_update <- function(df) {
if("col3" %in% names(df)){
df$col3[is.na(df$col3) & (df$col1 %in% c("v2", "v3"))] <- "VAL"
}
df
}
lapply(my_list, df_update)
# microbenchmark::microbenchmark() :
#> Unit: milliseconds
#> expr min lq mean median uq max neval
#> lapply_subset 7.9087 8.46455 9.880332 8.72160 9.6610 24.2403 100
#> floop 12.8077 13.43235 15.302831 13.80615 14.6502 35.7991 100
#> lapply 91.1871 95.82220 101.641103 100.16710 104.2413 156.0194 100
```
``` r
my_list <- list(structure(list(col1 = c("v1", "v2", "v3", "V2", "V1"), col2 = c("wood", NA, "water", NA, "water"), col3 = c("cup", NA, "fork", NA, NA), col4 = c(NA, "pear", "banana", NA, "apple")), class = "data.frame", row.names = c(NA, -5L)), structure(list(col1 = c("v1", "v2"), col2 = c("wood", NA), col4 = c(NA, "pear")), class = "data.frame", row.names = c(NA, -2L)), structure(list(col1 = c("v1", "v2", "v3", "V3"), col3 = c("cup", NA, NA, NA), col4 = c(NA, "pear", "banana", NA)), class = "data.frame", row.names = c(NA, -4L)))
set.seed(42)
big_list <- my_list[sample(1:3, 1e3, replace=TRUE)]
microbenchmark::microbenchmark(
lapply_subset=lapply(big_list, df_update),
floop={
for (s in seq_along(big_list)) {
x <- big_list[[s]]
if ('col3' %in% names(x)) {
x$col3[is.na(x$col3) & x$col1 %in% c('v2', 'v3')] <- 'VAL'
big_list[[s]] <- x
}
}
big_list
},
lapply=lapply(
big_list,
\(x) if ('col3' %in% names(x)) {
transform(x, col3=replace(col3,
is.na(col3) & col1 %in% c('v2', 'v3'),
'VAL'))
} else {
x
}),
check='identical')
``` |
Filter by JSON object by keys |
|javascript|reactjs|json|object|filter| |
There is a trick to accomplish this. I'm assuming the title and subTitle will have a maximum of three lines. The idea is to create a Text with a placeholder that has up to three lines. Then add the overlay of your two title and subTitle `View`s to this placeholder.
```swift
struct TextWrapper: View {
//Make sure the placeHolder reaches 3 lines
private let placeHolder = "Title that wraps to two lines Subtitle that wraps to two line"
private let maxLines = 3
let title: String
let titleFont: Font
let subTitle: String
let subTitleFont: Font
var body: some View {
Text(placeHolder)
.lineLimit(maxLines)
.hidden()
.overlay(alignment: .top) {
VStack {
Text(title)
.font(.headline)
.lineLimit(maxLines)
.layoutPriority(2) //Title has higher priority
Text(subTitle)
.font(.subheadline)
.lineLimit(maxLines)
.layoutPriority(1)
}
}
.frame(maxWidth: .infinity)
}
}
```
This is the output when `titleFont = .title3` and `subTitleFont = .subheadline`:
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/Tdns5.png |
I'm implementing a type of BSP tree in Rust, and I am wanting to write a function that tells which side of a parent node a node belongs to. This is what I have
```
enum Side {
L = 0,
R = 1,
}
enum RegionKind {
Split {
subregion: [Option<Rc<Region>>; 2],
},
Client{
window: i32,
},
}
struct Region {
kind: RegionKind,
container: Option<Rc<Region>>,
tags: u8,
}
impl Region {
fn from(&self) -> Option<Side> {
if let RegionKind::Split{subregion,..} = &self.container.as_ref()?.kind {
match &subregion[0] {
None => None,
Some(r) => if eq(Rc::<Region>::as_ptr(&r),self) {
Some(Side::L)
} else {
None
}.or_else(|| { match &subregion[1] {
None => None,
Some(r) => if eq(Rc::<Region>::as_ptr(&r),self) {
Some(Side::R)
} else {
None
}
}})
}
} else {
None
}
}
}
```
There are currently two things in place that are making this function quite the behemoth.
1. I need to repeat the check on on subregion[0] and subregion[1]. I would really like to be able to return the `Side` of the index (given that L = 0 and R = 1 like shown in the enum declaration) and be able to combine these into one, hence why I am asking to match over the elements of the array. Something like how you use `Some(r) => ...` to unbox the `r` out of the `Some`
2. I need to check if the `RegionKind` is `Split`. I can assert that any Region's `container` will always have `RegionKind::Split` as their `kind`, so I would like to be able to eliminate the `if let else` entirely (I would prefer to `panic!()` in that else block if I must have it as well, but the compiler gets upset about return types so I need to add the `None` at the end anyways, which just ends up getting marked as unreachable)
I figure there's probably some arcane Rust syntax that can make this much more concise and I just don't know it or don't know how to employ it here. This same function can be a single line macro in C. |
I have the following mongo model:
```
{
"_id" : "5f5a1c1f6976570001783ab7",
"date" : NumberLong(1590624000),
"source" : "here",
}
```
I would like to have the number of documents, group by date, that have source field at here value for example:
```
{
"date" : NumberLong(1590624000),
"count": 5
},
{
"date" : NumberLong(1590710400),
"count": 10
}
```
What mongo query should I use to have the following result? |
Mongo count number of objects grouped by a field value |
|mongodb|mongodb-query|aggregation-framework| |
Have you tried stopping the project and then restarting it? Changes involving native-end plugins typically require a project restart to take effect. |
When attempting to get a time using mktime, I get a overflow exception. This occurs on a Debian docker image, but not on my host machine:
```
docker pull python:3.9.7
```
https://hub.docker.com/layers/library/python/3.9.7/images/sha256-9d7d2a6ce11fe5a12c74f81b860f5142fd91192427ece0b566c4fb962353325e?context=explore
pytz==2021.3
Here's a toy example:
```
import datetime
import time
import pytz
ts = 1655043357
tz = 'Canada/Eastern'
utc_time = datetime.datetime.now(tz=pytz.utc)
tz = pytz.timezone(tz)
tz_aware = datetime.datetime.now(tz=tz)
time.mktime(utc_time.timetuple()) # No exception
time.mktime(tz_aware.timetuple()) # <----Results in exception
```
Exception:
```
Traceback (most recent call last):
File "/home/toy_example.py", line 15, in <module>
time.mktime(tz_aware.timetuple())
OverflowError: mktime argument out of range
```
There is no exception when running on my host machine and works as expected. Any idea why that's happening?
edit:
Interestingly, if I change my current system time to last week March 7, 2024 it works without an exception being raised |
|python|database|informix| |
Recast removes comments from file |
Hey here's my settings and value of confPath String, it worked after I moved the file to src/main/resources
[ide pic][1]
[1]: https://i.stack.imgur.com/iPQ6I.png |
I'm working on an Angular form where users can input their phone numbers. I've added a custom directive appPhoneExtMask for phone number formatting and applied Angular form validation for minlength and maxlength. However, I'm facing an issue where if the user only enters spaces into the input field, it triggers a validation error. I want the form to ignore or trim spaces before performing validation checks. Here is the code snippet for the input field:
**i am expect get only number and ignore string value also count only number in minimum and maximum lenght**
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
import {
Directive,
HostListener
} from '@angular/core';
import {
NgControl,
Validators
} from '@angular/forms';
@Directive({
selector: '[formControlName][appPhoneExtMask]',
})
export class PhoneExtentionMaskDirective {
constructor(public ngControl: NgControl) {}
@HostListener('ngModelChange', ['$event'])
onModelChange(event) {
this.onInputChange(event, false);
}
@HostListener('keydown.backspace', ['$event'])
keydownBackspace(event) {
this.onInputChange(this.ngControl.control.value, true);
}
ngOnInit() {
this.formatValue(this.ngControl.control.value, false);
}
onInputChange(event, backspace) {
this.formatValue(event, backspace);
}
formatValue(event, backspace) {
if (event === null) {
return; // Exit early if event is null
}
let newVal = event.replace(/\D/g, '');
if (backspace && newVal.length <= 6) {
newVal = newVal.substring(0, newVal.length - 1);
}
if (newVal.length === 0) {
newVal = '';
} else if (newVal.length <= 3) {
newVal = newVal.replace(/^(\d{0,3})/, '$1');
} else if (newVal.length <= 6) {
newVal = newVal.replace(/^(\d{0,3})(\d{0,3})/, '$1-$2');
} else if (newVal.length == 10) {
newVal = newVal.replace(/^(\d{0,3})(\d{0,3})(\d{0,4})/, '$1-$2-$3');
} else if (newVal.length <= 10) {
newVal = newVal.replace(/^(\d{0,3})(\d{0,3})(\d{0,4})/, '$1-$2-$3');
} else if (newVal.length <= 20) {
newVal = newVal.substring(0, 20);
newVal = newVal.replace(
/^(\d{0,3})(\d{0,3})(\d{0,4})(\d{0,5})/,
'$1-$2-$3 x $4'
);
} else {
if (newVal.length >= 12) {
newVal = newVal.substring(0, 12);
newVal = newVal.replace(
/^(\d{0,3})(\d{0,3})(\d{0,4})(\d{0,5})/,
'$1-$2-$3 x$4'
);
} else {
newVal = newVal.substring(0, 12);
newVal = newVal.replace(/^(\d{0,3})(\d{0,3})(\d{0,4})/, '$1-$2-$3');
}
}
this.ngControl.valueAccessor.writeValue(newVal);
if (newVal.length == 12 || newVal.length == 20)
this.ngControl.control.setErrors(null);
else
this.ngControl.control.setValidators([Validators.pattern(/^(1\s?)?(\d{3}|\(\d{3}\))[\s\-]?\d{3}[\s\-]?\d{4}( ?x([0-9]{3}))?$/)]);
}
}
<!-- language: lang-html -->
<input type="text" placeholder="Phone" class="form-control" formControlName="phone" minlength="12" maxlength="20" appPhoneExtMask [ngClass]="{ 'is-invalid': (isSaved && contactForm.get('phone').errors)}">
<!-- end snippet -->
|
Flutter not showing rendered shimmer, but waits for future builder to have data before showing |
|flutter| |
Try To connect to your MongoDB instance with specified database name, use the following connection string from outside the container
'mongodb://localhost:27017/my-db'
and this from inside the container
'mongodb://mongo-db:27017/my-db'
add this to docker-compose
environment:
- MONGO_INITDB_DATABASE=my-db
If this configuration does not work, you can change the exposed port:
ports:
- 27018:27017 |
I've downloaded Docker Desktop to run it, but when I open it, I get an error message: **Docker Desktop - Unexpected WSL error**:
```
`(Docker Desktop - Unexpected WSL error btrd.
An unexpected error was encountered while executing a WSL command. Common causes include access rights issues, which occur after waking the computer or not being connected to your domain/active directory.
Please try shutting WSL down (ws --shutdown) and/or rebooting your computer. If not Docker Engine sufficient, WSL may need to be reinstalled fully. As a last resort, try to uninstall/reinstall Docker Desktop. If the issue persists please collect diagnostics and submit an issue )`
```
[enter image description here](https://i.stack.imgur.com/NwAlJ.jpg)
I've tried using **wsl --shutdown**, but it didn't work. After checking the Docker documentation, I found out that Docker requires WSL 2 and Hyper-V, so I updated to the latest version of WSL 2 and installed Hyper-V. However, Docker still doesn't work.
When I use the **wsl -l -v** command to list all installed Linux distributions in Windows Subsystem for Linux (WSL), I noticed that in WSL 1, I had Ubuntu version 1. Since Docker requires version 2, I used the wsl --set-default-version 2 command to switch to WSL 2. However, I couldn't see any Linux distributions listed, which I believe is causing the Docker issue.
I tried to switch Ubuntu to version 2 using the **wsl --set-version Ubuntu 2** command, but I encountered the error:
```
(Failed to configure network (networkingMode Nat). To disable networking, set wsl2.networkingMode=None in C:\Users\DELL\.wslconfig. Error code: Wsl/Service/CreateVm/ConfigureNetworking/HNS/0x80041002.)
```
So, I decided to uninstall the current Ubuntu and reinstall a different one using **wsl --install -d Ubuntu**. However, I still encounter the same error.
```
(WslRegisterDistribution failed with error: 0x80041002 Error: 0x80041002 (null))
```
I've also tried enabling **Hyper-V, Virtual Machine, and Windows Subsystem for Linux**, and I've enabled virtualization in the BIOS. I've tried various solutions from Google and YouTube, but none of them worked.
[enter image description here](https://i.stack.imgur.com/iBeRA.jpg)
Windows 11 Home Single Language
WSL 2
Could someone please help me with this? |
Docker Desktop - Unexpected WSL error And WslRegisterDistribution failed with error: 0x80041002 Error: 0x80041002 (null) |
|docker|windows-subsystem-for-linux| |
null |
I am trying to create a webpage which is made up of a header and bellow the header a list of items. I want the list of items to be vertically scrollable. I also would like the webpage to take up the entire window but not be bigger. Currently my problem is the list of items is not scrollable and instead extends far below the bottom of the window and this is causing the window to be scrollable. What should the *CSS* properties be on the *html*, *body*, *header* and *list items*?
```html
doctype html
html
head
link(href="css/style.css" rel="stylesheet")
body
div#wrapper
h1 Interactive Contact Directory
div(class="tools")
|Search:
br
input(type="text" id="searchBox")
select(name="searchBy" id="searchBy")
option(value='firstname') First Name
option(value='lastname') Last Name
option(value='email') Email
br
br
div(id="listingHolder")
ul(id="listing")
div(id="listingView")
```
Bellow is the current style sheet I have
```css
html{
height: 100%;
}
body {
background:#121212;
margin:0px;
padding:0px;
font-family:"Open Sans", sans-serif;
height: 100%;
}
#wrapper {
max-height: 100%;
}
h1 {
margin:0px;
color:#fff;
padding:20px;
text-align:center;
font-weight:100;
}
.tools {
text-align:center;
color:#fff;
}
#searchBox {
padding:7px;
border:none;
border-radius:5px;
font-size:1.2em;
}
a.filter {
display:inline-block;
padding:5px 10px;
margin:5px;
background:#0472C0;
color:#fff;
text-decoration:none;
border-radius:3px;
}
a.filter:hover {
background:#0B9DE0;
color:#fff;
}
ul#listing {
list-style:none;
padding:0px;
margin:0px;
background:#fff;
width:100%;
}
ul#listing li {
list-style:none;
border-bottom:1px solid #eee;
display:block;
}
ul#listing li .list-header {
padding:10px;
cursor:pointer;
display:block;
}
ul#listing li .list-header:hover {
background:#7893AB;
color:#fff;
}
ul#listing li .list-header.active {
background:#447BAB;
color:#fff;
}
ul#listing li .details {
display:none;
background:#efefef;
padding:20px;
font-size:0.9em;
}
#listingHolder{
width: 50%;
overflow: scroll;
}
``` |
|python|qtpy| |
[this is my result][1]I ran the deep learning for regression, it is a multimodal model with two loss functions. the mse and mae are acceptable, but the r2 is so horrible.the r2 started from very big negative number and then decreasing during one epoch. any idea can explain it? what should I check? Thanks!!!!!
this is my code.
def r_squared(y_true, y_pred):
SS_res = K.sum(K.square(y_true - y_pred))
SS_tot = K.sum(K.square(y_true - K.mean(y_true)))
return 1 - SS_res/(SS_tot + K.epsilon())
optimizer1 = keras.optimizers.Adam(1e-5, clipnorm=0.3, epsilon=1e-4)
model.compile(optimizer=optimizer1, loss=losses1, loss_weights=loss_weights1, metrics=['mse',r_squared,'mae'])
[1]: https://i.stack.imgur.com/MA8x2.jpg |
I have the following `array` that I converted from a JSON response of the `WP REST API`:
[
[
'id' => 6,
'convite_id' => [4],
'nome_do_convidado' => 'John Doe',
'email_do_convidado' => ['johndoe@gmail.com', 'another@example'],
],
[
'id' => 5,
'convite_id' => [4],
'nome_do_convidado' => 'Lorem',
'email_do_convidado' => ['lorem@gmail.com'],
],
]
And I'm trying to loop the `email_do_convidado` value as:
- johndoe@gmail.com
- lorem@gmail.com
I've tried with `foreach()` loop and just get the last one, and now I've tried with `while()` and get one result too, follow my script:
while (list ($key, $val) = each ($myArray) )
echo $val['email_do_convidado'][$key];
And the result is:
`johndoe@gmail.com`
What I'm doing wrong here? |
How to access deep values from a particular column of a multidimensional array |
|php|arrays|loops|multidimensional-array| |
null |
I'm new to DynamoDb. So if someone could explain to me, what am I doing wrong, or what I miss in my understanding that would be great.
I'm trying to get the most effiicient way of searching for a row, that contains some value.
'm playing around with some test data to see how it works and how to design everything.
I have a table with about 1700 rows. Some rows have quite some data in them.
There is PK - Id, And some other attributes like Name, Nationality, Description etc.
I also added GSI on 'Name' With projection type 'KEYS_ONLY'
Now, my scenario is to find a person, that name contains given string. Let's say Name is 'Pablo Picasso', and I want to find any 'Picasso'
My assumtion was, that if I am scanning the GSI it should be pretty fast, I understand, Scan can only go thorugh !mb of data, but I assumed, that My GSI looked something like this:
| Name. | Id |
| -------- | --- |
| A Hopper | 2 |
| Timoty c | 3 |
| Donald Duck | 14 |
Having that in mind, I was sure it should find my row on first scan. Unfortunetaly my first scan went only through like 340 rows. I was able to find my row after 4 calls to Dynamo.
When I made simillar scan, but not on the GSI it took 5 calls. which doesn't seem like that different.
Am I doing something wrong? Or do I missunderstood anything?
For testing purposes I'm using C# code like this:
```
var result = await _dynamoDb.ScanAsync(new ScanRequest(DynamoConstants.ArtistsTableName)
{
IndexName = "NameIndex",
FilterExpression = "contains(#Name, :name)",
ExpressionAttributeNames = new Dictionary<string, string>() { { "#Name", "name" } },
ExpressionAttributeValues = new Dictionary<string, AttributeValue>()
{ { ":name", new AttributeValue("Picasso") } }
});
```
My index looks like this:
```
var nameIndex = new GlobalSecondaryIndex
{
IndexName = "NameIndex",
ProvisionedThroughput = new ProvisionedThroughput
{
ReadCapacityUnits = 5,
WriteCapacityUnits = 5
},
Projection = new Projection { ProjectionType = "KEYS_ONLY" },
KeySchema = new List<KeySchemaElement> {
new() { AttributeName = "name", KeyType = "HASH"}
}
};
```
EDIT:
I did some more digging and found out, that in fact GSI size is the same as the whole table.
```
...
"TableSizeBytes": 5435537,
"ItemCount": 1792,
"TableArn": "arn:aws:dynamodb:ddblocal:000000000000:table/artists",
"GlobalSecondaryIndexes": [
{
"IndexName": "NameIndex",
"KeySchema": [
{
"AttributeName": "name",
"KeyType": "HASH"
}
],
"Projection": {
"ProjectionType": "KEYS_ONLY"
},
"IndexStatus": "ACTIVE",
"ProvisionedThroughput": {
"ReadCapacityUnits": 5,
"WriteCapacityUnits": 5
},
"IndexSizeBytes": 5435537,
"ItemCount": 1792,
.....
```
But why? Is there anything wrong with my Index creation? |
Pattern matching over entries of an array/split |
|rust|pattern-matching| |
I am new in react native and I want to achieve text chat functionality with agora in react native.
Currently, I'm encountering an issue where if a user is not on the chat screen and receives messages from another user, those unread messages are appended at the end after the older messages load. Additionally, when the user sends a new message, it gets added along with the same old unread messages.
Please suggest what I did wrong, also if my explanation needs some data, please let me know.
Thanks in advance
Below is my code implementation:
```
import { Image, Platform, StyleSheet, Text, TextInput, View } from 'react-native'
import React, { useState, useCallback, useEffect, useContext, useRef } from 'react'
import { GiftedChat, Send, Bubble } from 'react-native-gifted-chat'
import { IconButton } from 'react-native-paper'
import { ChatMessage, ChatMessageChatType } from 'react-native-agora-chat'
import MCIcon from 'react-native-vector-icons/MaterialCommunityIcons'
import { useFocusEffect } from '@react-navigation/native'
import { AuthContext } from '../../../context/AuthContext'
function CustomInputToolbar(props) {
const { text, setText, sendmsg } = props
return (
<View
style={{
// flex: 1,
flexDirection: 'row',
alignItems: 'center',
gap: 10,
marginHorizontal: 8,
}}
>
<TextInput
style={[styles.input, { paddingTop: 10 }]}
placeholder="Message"
placeholderTextColor="gray"
value={text}
onChangeText={setText}
multiline
/>
<MCIcon
name="send"
color="#dd1077"
size={32}
onPress={() => {
if (text !== '') {
sendmsg()
setText('')
}
}}
/>
</View>
)
}
function ChatScreen({ route, navigation }) {
const { tokenData, profileData, chatClient, chatManager } = route.params
const logoutCalled = useRef(false)
const [messages, setMessages] = useState([])
const [text, setText] = React.useState('')
const { chatNotification } = useContext(AuthContext)
// console.log(JSON.stringify(tokenData))
const { markChatRead } = useContext(AuthContext)
// Custom bubble component to change background color to pink
const renderBubble = (props) => (
<Bubble
{...props}
wrapperStyle={{
right: {
backgroundColor: '#dd1077',
},
left: {
backgroundColor: 'white',
},
}}
/>
)
useEffect(() => {
markChatRead(tokenData.conversationId)
const login = async () => {
console.log('start login ...')
try {
await chatClient.isLoginBefore()
await chatClient.loginWithAgoraToken(tokenData?.username, tokenData?.token)
console.log('login operation success.')
loadOldMessages()
} catch (error) {
console.log(`login fail: ${JSON.stringify(error)}`)
}
}
const loadOldMessages = async () => {
try {
const res = await chatManager.fetchHistoryMessagesByOptions(tokenData.toUsername, 0, {
cursor: '',
pageSize: 50,
})
const newMessages = res.list.map((message) => ({
_id: message.msgId,
text: message.body.content,
createdAt: new Date(message.serverTime),
user: {
_id: message.from,
name: message.from,
avatar: '',
},
received: true,
}))
setMessages((previousMessages) => GiftedChat.append(previousMessages, newMessages))
setMessageListener() // Call setMessageListener after setting the messages
} catch (error) {
console.error('Error fetching old messages:', error)
}
}
const setMessageListener = () => {
const msgListener = {
onMessagesReceived(receivedMessages) {
const newMessages = receivedMessages
.filter((message) => message.from === tokenData.toUsername)
.map((message) => ({
_id: message.msgId,
text: message.body.content,
createdAt: new Date(message.serverTime),
user: {
_id: message.from,
name: message.from,
avatar: '',
},
received: false,
}))
setMessages((previousMessages) => GiftedChat.append(previousMessages, newMessages))
},
onCmdMessagesReceived: (messages) => {},
onMessagesRead: (messages) => {},
onGroupMessageRead: (groupMessageAcks) => {},
onMessagesDelivered: (messages) => {},
onMessagesRecalled: (messages) => {},
onConversationsUpdate: () => {},
onConversationRead: (from, to) => {},
}
chatManager.removeAllMessageListener()
chatManager.addMessageListener(msgListener)
}
login()
}, [])
useFocusEffect(
React.useCallback(
() => () => {
if (!logoutCalled.current) {
logoutCalled.current = true
logout()
if (navigation && navigation.getState().routes.slice(-1)[0].name !== 'ChatList') {
navigation.goBack()
}
// navigation.goBack()
}
},
[navigation]
)
)
const onSend = useCallback((messages = []) => {
setMessages((previousMessages) => GiftedChat.append(previousMessages, messages))
}, [])
const logout = () => {
console.log('start logout ...')
chatClient
.logout()
.then(() => {
console.log('logout success.')
})
.catch((reason) => {
console.log(`logout fail:${JSON.stringify(reason)}`)
})
}
// Sends a text message to somebody.
const sendmsg = () => {
let msg = ChatMessage.createTextMessage(
tokenData.toUsername,
text,
ChatMessageChatType.PeerChat
)
const callback = new (class {
onProgress(locaMsgId, progress) {
console.log(`send message process: ${locaMsgId}, ${progress}`)
}
onError(locaMsgId, error) {
console.log(`send message fail: ${locaMsgId}, ${JSON.stringify(error)}`)
}
onSuccess(message) {
console.log(`send message success: ${message.localMsgId}`)
const newMessage = {
_id: message.msgId,
text: message.body.content,
createdAt: new Date(message.serverTime),
user: {
_id: message.from,
name: message.from,
avatar: '',
},
sent: true,
}
console.log(JSON.stringify(newMessage))
chatNotification(tokenData.conversationId, message.body.content)
setMessages((previousMessages) => GiftedChat.append(previousMessages, newMessage))
}
})()
console.log('start send message ...')
chatClient.chatManager
.sendMessage(msg, callback)
.then(() => {
console.log(`send message: ${msg.localMsgId} ${JSON.stringify(msg)}`)
})
.catch((reason) => {
console.log(`send fail: ${JSON.stringify(reason)}`)
})
}
function CustomSendButton(props) {
return (
<Send {...props}>
<View style={{ marginRight: 10, marginBottom: 10 }}>
<Image
source={require('../../../../assets/icons/bookmark-white.png')}
resizeMode={'cover'}
/>
</View>
</Send>
)
}
return (
<>
<View
style={{
flexDirection: 'row',
alignItems: 'center',
paddingLeft: 16,
}}
>
{/* Arrow icon */}
<IconButton
icon={() => <MCIcon name="chevron-left" color="#fff" size={30} />}
onPress={() => {
logoutCalled.current = true
logout()
navigation.goBack()
}}
/>
{/* Profile image */}
<Image
source={{
uri: profileData.profileImageUrl || profileData.profileImage,
}}
style={{ width: 50, height: 50, borderRadius: 40 }}
/>
<View
style={{ flexDirection: 'column', alignItems: 'flex-start', marginLeft: 10, width: 200 }}
>
<Text style={{ fontSize: 12, color: 'white' }}>
{(profileData.role
? profileData.role.charAt(0).toUpperCase() + profileData.role.slice(1)
: '') ||
(profileData.type
? profileData.type.charAt(0).toUpperCase() + profileData.type.slice(1)
: '')}
</Text>
<Text style={{ fontSize: 16, fontWeight: 'bold', color: 'white', flexWrap: 'wrap' }}>
{profileData.firstName} {profileData.lastName}{' '}
<Text style={{ fontSize: 10 }}>{profileData.title}</Text>
</Text>
<Text style={{ fontSize: 12, color: 'white' }}>
{profileData.university || profileData.institution}
</Text>
</View>
</View>
<GiftedChat
messages={messages}
onSend={(messages) => onSend(messages)}
alwaysShowSend
renderAvatar={null}
renderSend={(props) => <CustomSendButton {...props} />}
renderInputToolbar={(props) => (
<CustomInputToolbar {...props} text={text} setText={setText} sendmsg={sendmsg} />
)}
renderBubble={renderBubble}
bottomOffset={Platform.OS === 'ios' ? 100 : 0}
// messagesContainerStyle={{ }}
user={{
_id: tokenData.username,
}}
/>
</>
)
}
export default ChatScreen
const styles = StyleSheet.create({
input: {
flex: 1,
backgroundColor: 'white',
color: 'black',
height: 40,
borderRadius: 8,
paddingHorizontal: 16,
fontSize: 16,
},
})
``` |
i'm working on React and Firebase and i'm trying to integrate Firebase Cloud Messaging. My main challenge is passing my app credentials to the ```firebase-messaging-sw.js```. This file is in the public folder and can't access ```.env``` file. I've been looking at a number of tutorials and they cover FCM setup but not how to hide environment variables from public folder.
There is a similar [question][1] but for Next.js. I followed the instructions but didn't get the right outcome.
```
//firebase-messaging.sw.js
// eslint-disable-next-line no-undef
importScripts("https://www.gstatic.com/firebasejs/8.10.1/firebase-app.js");
// // eslint-disable-next-line no-undef
importScripts(
"https://www.gstatic.com/firebasejs/8.10.1/firebase-messaging.js"
);
importScripts("swenv.js");
firebase.initializeApp({
apiKey: process.env.REACT_APP_APIKEY,
authDomain: process.env.REACT_APP_AUTHDOMAIN,
projectId: process.env.REACT_APP_PROJECTID,
storageBucket: process.env.REACT_APP_STORAGEBUCKET,
messagingSenderId: process.env.REACT_APP_MESSAGINGSENDERID,
appId: process.env.REACT_APP_APPID,
measurementId: process.env.REACT_APP_MEASUREMENTID,
});
const messaging = firebase.messaging();
messaging.onBackgroundMessage((payload) => {
console.log(
"[firebase-messaging-sw.js] Received background message ",
payload
);
// Customize notification here
const notificationTitle = payload.notification.title;
const notificationOptions = {
body: payload.notification.body,
icon: payload.notification.image,
};
// eslint-disable-next-line no-restricted-globals
self.registration.showNotification(notificationTitle, notificationOptions);
});
```
How do i share my environment variables with my ```firebase-messaging.sw.js``` in the public folder?
[1]: https://stackoverflow.com/questions/76057342/how-can-i-access-environment-variables-from-a-file-sitting-inside-the-public-fol |
Firebase Cloud Messaging: how do i get access to environment variables the public folder |
|reactjs|firebase|firebase-cloud-messaging| |
# Answer no longer valid
The `@import` syntax was removed from `CSSStyleSheet.replace()`
* [Chrome][1]
* [Mozilla][2]
## <s>Constructable Stylesheets</s>
This is a new feature that allows for the construction of `CSSStyleSheet` objects. These can have their contents set or imported from a css file using JavaScript and be applied to both documents and web components' shadow roots. It will be available in Chrome with version 73 and probably in the near future for Firefox.
There's a [good writeup on the Google developers site](https://developers.google.com/web/updates/2019/02/constructable-stylesheets) but I'll summarize it briefly below with an example at the bottom.
### Creating a style sheet
You create a new sheet by calling the constructor:
```
const sheet = new CSSStyleSheet();
```
### Setting and replacing the style:
A style can be applied by calling the methods `replace` or `replaceSync`.
* `replaceSync` is synchronous, and can't use any external resources:
```
sheet.replaceSync(`.redText { color: red }`);
```
* `replace` is [asynchronous](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function) and can accept `@import` statements referencing external resources. Note that `replace` returns a `Promise` which needs to be handled accordingly.
```
sheet.replace('@import url("myStyle.css")')
.then(sheet => {
console.log('Styles loaded successfully');
})
.catch(err => {
console.error('Failed to load:', err);
});
```
### Applying the style to a document or shadow DOM
The style can be applied by setting the `adoptedStyleSheets` attribute of either the `document` or a shadow DOM.
```
document.adoptedStyleSheets = [sheet]
```
The array in `adoptedStyleSheets` is frozen and can't be mutated with `push()`, but you can concatenate by combining with its existing value:
```
document.adoptedStyleSheets = [...document.adoptedStyleSheets, sheet];
```
### Inheriting from the document
A shadow DOM can inherit constructed styles from the document's `adoptedStyleSheets` in the same way:
```
// in the custom element class:
this.shadowRoot.adoptedStyleSheets = [...document.adoptedStyleSheets, myCustomSheet];
```
Note that if this is run in the constructor, the component will only inherit the style sheets that were adopted prior to its creation. Setting `adoptedStyleSheets` in the `connectedCallback` will inherit for each instance when it is connected. Notably, this will not cause an [FOUC](https://en.wikipedia.org/wiki/Flash_of_unstyled_content).
### Example with Web Components
Let's create a component called `x-card` that wraps text in a nicely styled `div`.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
// Create the component inside of an IIFE
(function() {
// template used for improved performance
const template = document.createElement('template');
template.innerHTML = `
<div id='card'></div>
`;
// create the stylesheet
const sheet = new CSSStyleSheet();
// set its contents by referencing a file
sheet.replace('@import url("xCardStyle.css")')
.then(sheet => {
console.log('Styles loaded successfully');
})
.catch(err => {
console.error('Failed to load:', err);
});
customElements.define('x-card', class extends HTMLElement {
constructor() {
super();
this.attachShadow({
mode: 'open'
});
// apply the HTML template to the shadow DOM
this.shadowRoot.appendChild(
template.content.cloneNode(true)
);
// apply the stylesheet to the shadow DOM
this.shadowRoot.adoptedStyleSheets = [sheet];
}
connectedCallback() {
const card = this.shadowRoot.getElementById('card');
card.textContent = this.textContent;
}
});
})();
<!-- language: lang-html -->
<x-card>Example Text</x-card>
<x-card>More Text</x-card>
<!-- end snippet -->
[1]: https://github.com/WICG/construct-stylesheets/issues/119#issuecomment-588352418
[2]: https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet/replace#parameters |
You should encode the cookie value. The [.NET method][1] is `UrlEncode` in the `System.Web.HttpUtility` API. In .NET Framework, this `UrlEncode` method [was provided by][2] the `System.Web.HttpServerUtility` API. See also [this SO answer][3].
[1]: https://learn.microsoft.com/en-us/dotnet/api/system.web.httputility.urlencode?view=net-8.0
[2]: https://learn.microsoft.com/en-us/dotnet/api/system.web.httpserverutility.urlencode?view=netframework-4.8.1
[3]: https://stackoverflow.com/questions/2700628/safe-way-to-encode-a-cookie-value-in-c-sharp |
null |
I just solve this problem for myself. I changed `includePath` in *c_cpp_properties.json* from
```
"${workspaceFolder}/**",
"C:\\msys64\\usr\\lib\\gcc\\x86_64-pc-msys\\11.3.0\\include\\**",
"C:\\msys64\\usr\\lib\\gcc\\x86_64-pc-msys\\11.3.0\\include-fixed\\**",
"C:\\msys64\\usr\\include\\**"
```
to
```
"${workspaceFolder}/**",
"C:/msys64/usr/lib/gcc/x86_64-pc-msys/11.3.0/include/c++",
"C:/msys64/usr/lib/gcc/x86_64-pc-msys/11.3.0/include/c++/x86_64-pc-msys",
"C:/msys64/usr/lib/gcc/x86_64-pc-msys/11.3.0/include/c++/backward",
"C:/msys64/usr/lib/gcc/x86_64-pc-msys/11.3.0/include",
"C:/msys64/usr/lib/gcc/x86_64-pc-msys/11.3.0/include-fixed",
"C:/msys64/usr/include",
"C:/msys64/usr/lib/gcc/x86_64-pc-msys/11.3.0/../../../../lib/../include/w32api"
```
. I get this list from typing `gcc -v -E -x c++ -` in the terminal. |
What does this mean "Error connecting to SMTP server: (421, b'Service not available')" |
|python|html|css|flask|smtp| |
null |
Customise switch appearance in AndroidX preference activity |
I am developing a multi-module Gradle (8.7) project, structured such that one module acts as the main application, while the others are libraries used by this application. All unit tests are located within the application module. Although these tests cover code paths in the library modules, Jacoco does not seem to generate coverage reports for these submodules, leading to inaccurately low coverage metrics.
Here is the structure:
```
repository-root/
βββ application/
βββ app/
β βββ src/
β β βββ main/
β β β βββ java/
β β βββ test/
β βββ build.gradle.kts
βββ common/
β βββ src/
β β βββ main/
β β βββ java/
β βββ build.gradle.kts
βββ build.gradle.kts
```
Issue:
Main Problem: Despite having tests that cover library module code, Jacoco's reports only reflect coverage for the application module.
Goal: Achieve a coverage report that accurately includes data from all modules, reflecting the true coverage achieved through tests run in the application module.
I tried to include coverage for one of the library modules (:common) by configuring the jacocoTestReport task in app/build.gradle.kts in the application module's build.gradle as follows:
```
tasks.jacocoTestReport {
val common = project(":common")
dependsOn(tasks.test)
dependsOn(common.tasks.test)
classDirectories.setFrom(
files("$buildDir/classes/java/main"),
files("${common.buildDir}/classes/java/main"))
sourceDirectories.setFrom(
files("${projectDir}src/main/java"),
files("${common.projectDir}/src/main/java"))
executionData.setFrom(
files("$buildDir/jacoco/test.exec"),
files("${common.buildDir}/jacoco/test.exec"))
reports {
xml.required.set(true)
csv.required.set(false)
html.required.set(true)
}
}
```
I want to specify that I found this solution on some forum, but no test.exec is generated in my common module. So also other solutions like generate an aggregated RootReport that I found on other question maybe won't be suitable for my case. |
Jacoco Coverage in Multi-Module Gradle Project Not Including Submodules |
|java|spring-boot|gradle|sonarqube|jacoco| |
null |
I had the same problem while following the Scrumdinger tutorial on the Apple Developer site. Finally I found a comment by some guy on a similar problem. It turned out that his development machine has no mic. That explains why the tutorial code works fine on my iPhone.
Then I connected my iPhone to my Mac Mini as a webcam. After that, both the preview and simulator worked smoothly. I cannot find the post with that comment, but the credit for this answer and my thanks go to the anonymous guy who posted it. |
I'm relatively new to using neo4j. I've connected to a database with the py2neo library and populated the database with the faker library to create nodes for Person and Address each with attributes attached to them. I'm interested in creating indexes and testing the performance of different indexes. These were the two indexes I had created
```
`# Step 3: Create Indexes for Persons and Addresses
graph.run(" CREATE INDEX IF NOT EXISTS FOR (p:Person) ON (p.name, p.dob, p.email, p.gender)")
graph.run("CREATE INDEX IF NOT EXISTS FOR (a:Address) ON (a.address, a.postcode, a.country)")'
```
I created some indexes and used the command
```
`graph.run("SHOW INDEXES;")`
```
[Output][1]
I was expecting 2 indexes to show but 3 indexes returned. The final one was a Look up type and had some null properties. That attached image shows the output, Why is this index showing up? Thanks.
I was expecting only 2 to return, so I'm thinking maybe this is some lack of understanding on my part? I've started reading through the Neo4j documentation on indexes but I'm still unsure. Any help would be appreciated. Thanks!
[1]: https://i.stack.imgur.com/6Hw4J.png |
CUDA Toolkit 12.4 (latest up to March 2024) doesn't provide xgetri function which is used in LAPACK for matrix inversion, in their cuSolver collection of LAPACK functions for dense matrices. I really don't know why they have not included xgetri in CUDA Toolkit, but if I want to implement matrix inversion using xgetrf+xgetrs, then I need to compose an identity matrix as right-hand-side which has leading dimension like the coefficient matrix and just fill its diagonal with one and leave large part of the memory on the device i.e., graphic card as zeros. This is not optimal from memory point of view, so I am wondering if anyone has any suggestion to do this task efficiently? I was also wondering if right-hand-side matrix (identity matrix in this case) can be stored in sparse format, but the library doesn't support it. Any help is highly appreciated.
Regards,
Dan |
CUDA matrix inversion |
|matrix|cuda|lapack|inversion| |
I am using macOS.
I have multiple `LazyVGrid` in my `ScrollView`. I am using `.scrollPosition()` to track the scroll position. Without using this modifier, I don't have any issues, but if, the scrolling is broken.
The problem is similiar to this one: https://stackoverflow.com/questions/66397921/add-multiple-lazyvgrid-to-scrollview
Unfortunately, I cannot use this solution, because my Grids definitely have different heights and this will cause the problem.
Here is an example code:
```
struct ContentView: View {
@State var scrollPosition: UUID? = nil
struct MyStruct: Identifiable {
let id = UUID()
let text: String
let uneven: Bool
}
@State var elements: [MyStruct]
init() {
var el = [MyStruct]()
for i in 1..<30 {
el.append(MyStruct(text: "Item\(i)", uneven: i % 2 == 0))
}
self.elements = el
}
var body: some View {
VStack {
ScrollView(.vertical) {
LazyVStack {
ForEach(self.elements) { element in
VStack {
Text(element.text)
LazyVGrid(columns: Array(repeating: GridItem(.fixed(30)), count: 7), content: {
ForEach(0..<7 * (element.uneven == true ? 6 : 7), id: \.self) { index in
Text("\(index)")
}
})
.padding(.bottom, 20)
}
}
} // end LazVStack
.scrollTargetLayout()
.frame(width: 600)
}
.scrollPosition(id: self.$scrollPosition)
}
}
}
```
You will experience the problem when you completely scroll down the list and then scroll up. Scrolling up is not possible anymore.
If you remove the `.scrollPosition`-modifier, it works. If you change the `ForEach` line to this:
`ForEach(0..<7 * 7, id: \.self) { index in`
it will work too, because then every Grid has the same height.
Adding a fake row will solve the problem, but it will also leave some extra space. Adding a negative padding or offset will not help, it will cause the problem again.
I am sure, that this is a bug in SwiftUI and I will file it. But because Apple barely fixes such bugs, does anyone has an idea for a workaround? |
ScrollView with multiple LazyVGrids jumping around when using .scrollPosition |
|swiftui|scrollview|lazyvgrid| |
Im new to using javaFx and programming in general so this might be a stupid question. Im trying to make a function that makes the thread wait without crashing the program which would result in something like the image above. [What Im trying to achive](https://i.stack.imgur.com/9ScnL.png)
I have tried using thread.sleep but it crashed the gui and also something like a Timeline or PauseTransition like this:
```
public static void wait(int milliseconds) {
Timeline timeline = new Timeline(new KeyFrame(Duration.millis(milliseconds)));
timeline.setOnFinished(event -> {
});
timeline.play();
}
```
but it doesn't work since the javafx things work on a different thread. |
I have a project where I define a "heterogenous list" like the following. I'm not sure what this trick is called but I've found it to be useful:
```haskell
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE TypeOperators #-}
import Data.Kind (Type)
data (a :: Type) :> (b :: Type) = a :> b
deriving Show
infixr :>
```
With this, I can write arbitrarily long lists of values like this:
```
val :: Int :> Bool :> String
val = 42 :> True :> "asdf"
```
I'm trying to write a function to test if such a value contains a given type, and if so extract it as a `Maybe`. For example,
```haskell
-- | getInt (42 :> "asdf") -> Just 42
-- | getInt (True :> "asdf") -> Nothing
getInt :: a :> b -> Maybe Int
getInt _ = ???
```
But I haven't figured out a way to write functions like this. I tried using
`cast` from `Data.Typeable`, but ran into various problems trying to destructure at the type level. |
I have a dataset of investments that shows a value for the investment, a coupon rate, and an annual income. Some investments generate no income, and some investments have a coupon rate but the annual income is not computed. How do I update the income column when there is a valid coupon but no number in the income column? Here is some sample data:
```
import pandas as pd
import numbers
data = {'value':[100, 150, 200, 250], 'coupon':[3,'-',4,5], 'income':[3,'-',8,'-']}
df = pd.DataFrame(data)
```
Rows 0 and 2 are complete, and don't need updating. Row 1 has no value for income, and no value for coupon, so it also doesn't need updating.
[](https://i.stack.imgur.com/wkBHk.jpg)
Only the income value in the bottom row should be updated, to 12.5.
Like in my dummy data set, the cells without meaningful numbers have dashes in them, they're not empty.
I wrote a function to execute this algorithm, but I don't know how to apply it to the dataframe:
```
def filler(value, coupon, income):
if ~isinstance(income, numbers.Number) and isinstance(coupon, numbers.Number):
income = (coupon * value)/100
return(income)
else:
pass
```
|
How do I update a dataframe column with a formula that uses values from other columns? |
|python|pandas| |
null |
I've developed a Telegram bot "mini app" that allows users to visit a website and open a "ticket" by entering text to explain their issue. Following this, a message "An admin will arrive soon" is sent to the user through the bot interface, and a Discord message is dispatched via a webhook to notify moderators that a new ticket has been created, including a command in the format **/admin_start <user_id>**. This is contained within a first file named "Ticket.py".
In a second file named "TelegramChat.py", as described below, the code implements a messaging system between users and administrators using two separate Telegram bots. This code is supposed to support three main functions:
```
#!/usr/bin/env python
# pylint: disable=unused-argument
from telegram import Update
from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes
# Configuration of bot tokens
USER_BOT_TOKEN = ""
ADMIN_BOT_TOKEN = ""
# Dictionary to track conversations: key = user ID, value = admin ID
conversations = {}
# Initialize applications for user and admin bots
user_bot_app = Application.builder().token(USER_BOT_TOKEN).build()
admin_bot_app = Application.builder().token(ADMIN_BOT_TOKEN).build()
async def admin_start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Admin initiates a conversation with a user."""
if context.args:
user_id = context.args[0] # Assuming the command is "/admin_start <user_id>"
admin_id = update.effective_user.id
conversations[user_id] = str(admin_id)
await context.bot.send_message(chat_id=admin_id, text=f"Connected with user {user_id}.")
await context.bot.send_message(chat_id=user_id, text="An admin has joined the chat.")
else:
await update.message.reply_text("Please provide the user ID. Format: /admin_start <user_id>.")
async def handle_user_message(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Forward messages from users to their linked admin."""
user_id = str(update.effective_user.id)
if user_id in conversations:
admin_id = conversations[user_id]
await context.bot.send_message(chat_id=admin_id, text=f"Message from user {user_id}: {update.message.text}")
else:
await update.message.reply_text("Please wait, connecting you to an admin...")
async def handle_admin_message(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Forward messages from the admin to the linked user."""
admin_id = str(update.effective_user.id)
user_ids = [user_id for user_id, admin in conversations.items() if admin == admin_id]
if user_ids:
for user_id in user_ids:
await context.bot.send_message(chat_id=user_id, text=f"Message from admin: {update.message.text}")
# Add handlers to the user bot
user_bot_app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_user_message))
# Add handlers to the admin bot
admin_bot_app.add_handler(CommandHandler("start", admin_start))
admin_bot_app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_admin_message))
if __name__ == "__main__":
# Run the bots in polling mode
user_bot_app.run_polling()
admin_bot_app.run_polling()
```
1. **For Administrators**: A command `/admin_start <user_id>` allows an administrator to initiate a conversation with a user. The administrator's ID is then recorded in the `conversations` dictionary with the user's ID as the key.
2. **Messages from Users**: When a user sends a message, if a conversation has been established with an administrator (verified in the `conversations` dictionary), the message is forwarded to that administrator.
3. **Messages from Administrators**: When an administrator sends a message, it is forwarded to all users linked to this administrator in the `conversations` dictionary.
However, the command **/admin_start <user_id>** does not work and does not allow the initiation of conversation between the user and the admin. I expected that when the admin uses the command "/admin_start <user_id>", a connection would be created allowing the exchange of messages between the admin and the user via Telegram bots. However, nothing happens on the admin side, the user side, or in the logs.
Could anyone help diagnose why the `/admin_start <user_id>` command isn't initiating the conversation as expected?
Also, to test the code, I created a file named "CombinedBot.py" that combines Ticket.py and TelegramChat.py. I've already had issues of type 'telegram.error.Conflict', but now I no longer have them. The part from "Ticket.py" works correctly, but the chat part does not. |
I am unable to create a build with this command:
`docker build -t feedback-node .`
Although docker was working fine previously.
I have also tried almost all the available suggestions but found nothing that could resolve it.
[](https://i.stack.imgur.com/igImj.png)
I was trying to build an image with the tag feedback-node and was expecting the id of the image after build.
This is the Dockerfile
`FROM node:14
WORKDIR /app
# .represents the current directory
COPY package.json .
RUN npm install
COPY . .
EXPOSE 80
CMD ["node", "server.js"]
` |