instruction stringlengths 0 30k ⌀ |
|---|
|c#|regexp-replace| |
null |
when i click on link it is taking me to '/product/api/product/2' URL but I have defined /api/product/<str:pk>/
for backend I'm using django.
```
import React from 'react'
import { Card } from 'react-bootstrap'
import Rating from './Rating'
import { Link } from 'react-router-dom' // we are using this to load in the same page without reloading whole page
function Product({ product }) {
return (
<Card className="my-3 p-3 rounded">
<Link to={`/product/${product._id}`}> {/* here we are using link in place of a & to in place of href */}
<Card.Img src={product.image} />
</Link>
<Card.Body>
<Link to={`/product/${product._id}`}>
<Card.Title as="div">
<strong>{product.name}</strong>
</Card.Title>
</Link>
<Card.Text as="div">
<div className="my-3">
<Rating value={product.rating} text={`${product.numReviews} reviews`} color={'#f8e825'} />
</div>
</Card.Text>
<Card.Text as="h3">
${product.price}
</Card.Text>
</Card.Body>
</Card>
)
}
export default Product;
```
when I place my cursor on product link it is showing the correct URL, but when i click on that link it is taking to wrong pattern on backend server.
Main urls.py code :
```
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path("admin/", admin.site.urls),
path("api/", include('base.urls')),
]
```
django app URLs code :
```
from django.urls import path
from . import views
urlpatterns = [
path('', views.getRoutes, name='routes'),
path('products/', views.getProducts, name='products'),
path('product/<str:pk>/', views.getProduct, name='product'),
]
```
|
Could be an issue you might have duplicated value on the Graphql definition.
remove on of them
example
```gql
query GetUsers {
users {
username
full_name
full_name # remove duplication
email
}
}
``` |
I wrote the following program that has a template parameter pack `Indices` for academic purposes. But the problem is that msvc rejects it but gcc and clang accepts it.
I want to know which compiler is right here? [Demo](https://godbolt.org/z/hdx75jjfK)
```
#include<cstddef>
template <typename T, std::size_t...Indices>
void func(T (&)[sizeof...(Indices)]);
int main()
{
int arr[4];
func<int, 1,2,3,4>(arr); //msvc rejects but clang and gcc accepts
}
```
MSVC says:
```
source>(11): error C2182: 'func': this use of 'void' is not valid
<source>(11): error C2988: unrecognizable template declaration/definition
<source>(11): error C2059: syntax error: ')'
<source>(13): error C2143: syntax error: missing ';' before '{'
<source>(13): error C2447: '{': missing function header (old-style formal list?)
```
Note that I am not looking for a workaround. |
Template parameter pack works in gcc but not in msvc |
|c++| |
{"Voters":[{"Id":6243352,"DisplayName":"ggorlen"},{"Id":17562044,"DisplayName":"Sunderam Dubey"},{"Id":20292589,"DisplayName":"Yaroslavm"}],"SiteSpecificCloseReasonIds":[13]} |
I was just learning the front-end, then I came up with a way to create a module using IIFE and register it to the namespace. From the code below, I still don't understand a few things:
1. Why does the function need a window as an argument?
2. What does this variable declaration mean: `var App = window.App || { };`. And why is it that at the bottom line there is a declaration: `window.App = App`. What is the difference between the two declarations?
```
(function(window){
'use strict';
var App = window.App || {};
function DataStore(){
console.log('running the DataStore function');
}
App.DataStore = DataStore;
window.App = App;
});
```
I didn't understand the workflow of the function, and the site I visited didn't provide a detailed explanation. I hope you all can help me, thank you. |
Adding Modules to a Namespace using IIFE |
|javascript|function|frontend|web-frontend|iife| |
null |
Using the :active pseudo-class isn't the right approach for toggling visibility in the way you're describing. Instead, you can use HTML anchor links and the :target pseudo-class to achieve this effect. Here's how you can do it:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
.content {
display: none;
}
/* Display content when targeted */
.content:target {
display: block;
}
<!-- language: lang-html -->
<!-- Buttons to toggle content -->
<button><a href="#about">About</a></button>
<button><a href="#contact">Contact</a></button>
<!-- Content sections -->
<div id="about" class="content">
<h2>About</h2>
<p>This is the about section.</p>
</div>
<div id="contact" class="content">
<h2>Contact</h2>
<p>This is the contact section.</p>
</div>
<!-- end snippet -->
|
Here is a fragment of my code:
```python
import numpy as np
from copy import copy
from random import randint
# With this matrix it doesn't give an error
matriz_aux = [
[None, 6, None, 9],
[ 9, None, 3, None],
[None, 5, 4, None]
]
# With this matrix it gives an error
matriz_aux = [
[5, 6, None, 5, 5],
[None, None, 3, None, None],
[None, None, 0, None, 1]
]
```
```python
matrix_aux_with_num_decompositions = copy(matriz_aux)
matriz_aux = np.array(matriz_aux)
rows, cols = matriz_aux.shape
seq = np.zeros((rows+cols, rows+cols))
vals = []
# Setup matrix representing system of equations
for i in range(rows):
for j in range(cols):
if matriz_aux[i,j]:
seq[len(vals), i] = 1
seq[len(vals), rows + j] = 1
vals.append(matriz_aux[i,j])
# Set arbitrary values so matrix is non-singular
for extra_eq in range(len(vals), rows+cols):
seq[extra_eq, extra_eq] = 1
vals.append(randint(0, 100))
try:
dcmp = np.linalg.solve(seq, vals)
for row in range(rows):
matrix_aux_with_num_decompositions[row].append(dcmp[row])
matrix_aux_with_num_decompositions.append(list(dcmp[rows:]))
except np.linalg.LinAlgError as e:
print(f"Error {str(e)}: The matrix is singular. The system of linear equations cannot be solved.")
for row in matrix_aux_with_num_decompositions: print(row)
```
A **correct output** could be this descomposition matrix:
```python
matrix_aux_with_num_decompositions = [
[ 5, 6, None, 5, 5, 2],
[None, None, 3, None, None, 1],
[None, None, 0, None, 1, -2],
[ 3, 4, 2, 3, 3]
]
```
In order to be solved as a system of linear equations, all known elements should be distributed so that they can be used to construct a valid system of linear equations, preventing seq from being a singular matrix, that is, a matrix that does not have enough information. to solve the system of linear equations.
Where each of the numerical values that were not None were decomposed into 2 simple numerical values, positive or negative, so that the value of their row and column added together forms them.
And following the logic of decomposing those numerical values of the matrix that are not None, in this case these would be the mathematical operations:
```
ij_number_to_decompose = i_row_value + j_column_value
5 = 2 + 3
6 = 2 + 4
5 = 2 + 3
5 = 2 + 3
3 = 1 + 2
0 = 2 + (-2)
1 = -2 + 3
```
Note that the value of 0 must necessarily be decomposed into 2 values equal in magnitude but opposite in sign; I believe this 0 is what causes problems in the logic of my code. |
Why does the following code detect this matrix as a non-singular matrix? |
|python|python-3.x|list|numpy|matrix| |
An element with "position: fixed" must remain fixed to the viewport. But in the below example, the fixed element moves along with its parent. Can anyone explain why the element isn't fixed to the viewport?
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
<div style="height: 100vh; background-color: lightblue; margin-left: 300px;">
<div style="position: fixed; background-color: tomato; width: 100px; height: 100px;">
</div>
</div>
<!-- end snippet -->
|
null |
Connection timed out error with smtp.gmail.com |
|amazon-web-services|gmail|sendmail|rhel| |
I'm attempting to upload video files to Dustloop, a mediawiki page for ArcSys games, and I've managed to get all the way to acquiring a CSRF token to be able to upload, but I'm struggling on the last part. I believe I have correctly done everything else, But I'm not able to get the file part correctly.
```rs
async fn upload_file(client: &mut reqwest::Client, csrf_token: String) {
let mut params = HashMap::new();
params.insert("action", "upload");
params.insert("filename", "maria-artemis-test.webm");
params.insert("comment", "API test file.");
params.insert("token", csrf_token.as_str());
params.insert("format", "json");
let url = reqwest::Url::parse("https://dustloop.com/wiki/api.php").unwrap();
let file: Vec<u8> = fs::read("output.webm").unwrap();
let file_part = Part::bytes(file).file_name("output.webm").mime_str("video/webm").unwrap();
let form = Form::new().part("video", file_part);
let response = client.post(url).form(¶ms).header(reqwest::header::CONTENT_TYPE, "multipart/form-data").multipart(form).send().await.unwrap();
println!("{:?}", response.headers());
println!("{}", response.text().await.unwrap());
}
```
this is my current code so far, taken from [simmons/reqwest-upload-example.rs](https://gist.github.com/simmons/6c2e6eb3ade5bfcb962250603dd667cf), but this doesnt seem to function for me.
The [mediawiki API docs](https://www.mediawiki.org/wiki/API:Upload) (same API as dustloop) has a python example, and I think ive gotten as close as I can
Any assistance on getting this to correctly upload files? Currently it just dumps the API documentation page back to me, not even responding with a json response (although if I remove `.multipart`, it does respond with JSON, so theres something there going wrong I think). Everything else should be fine, it is just the multipart process that goes wrong. |
I am a beginner trying to build very simple inventory system using PHP + SQL
I have 2 warehouse. I added 2 tables, 1 for each warehouse contains (item id)-(in)- (out) like shown below
table1
| item id | in | out |
| -------- | -- |-----|
| item1 | 10 | 0 |
| item1 | 5 | 0 |
| item2 | 0 | 3 |
| item2 | 0 | 2 |
table2
| item id | in | out |
| -------- | -- |-----|
| item1 | 12 | 0 |
| item1 | 50 | 0 |
| item2 | 0 | 10 |
| item2 | 0 | 30 |
I have report show balance for each warehouse separately by using query below
Select item_id, sum(in-out) as balance from table1 group by item_id
like below
| item id | balance|
| -------- | ------ |
| item1 | 2 |
| item2 | 20 |
My question is how show each warehouse balance in one table like below
| item id | warehouse1 | warehouse2|
| -------- | ---------- |-----------|
| item1 | 7 | 2 |
| item2 | 3 | 20 |
I tired with this query but I get wrong results
SELECT table1.item_id, sum(table1.in)-sum(table1.out) as tb1, sum(table2.in)-sum(table2.out) as tb2 FROM table1 , table2 WHERE table1.item_id=table2.item_id GROUP by item_id
the query above have 2 problems
1. results are not correct
2. only items in both tables are shown , while any item exist in table and not exists in the second one is not shown |
How can I disable TypeScript in VS code. Even though I have installed any plugins for TypeScript, I still get TypeScript warning messages in my Javascript. I referenced the [MS VS Code Documentation](https://code.visualstudio.com/docs/languages/typescript), but it doesn't specify disabling TypeScript. |
Disable typescript in VS Code |
|visual-studio-code| |
I have my own CMS system with settings for an multi language website and I save this in my database. But I can't check that variable in my htacces so I want to check my request url like this:
cms2024.nl/nl/home or cms2024.nl/home and then give different RewriteRules to get my right url order
If there is an language in the url I want these rules:
```
RewriteRule ^([^/]*)/([^/]*)/([^/]*)/([^/]*)/$ /index.php?taal=$1&page=$2&title=$3&beginnenbij=$4 [L]
RewriteRule ^([^/]*)/([^/]*)/([^/]*)/$ /index.php?taal=$1&page=$2&title=$3 [L]
RewriteRule ^([^/]*)/([^/]*)/$ /index.php?taal=$1&title=$2 [L]
```
and otherwise:
```
RewriteRule ^([^/]+)/([^/]+)/([^/]+)/?$ /index.php?page=$1&title=$2&beginnenbij=$3 [QSA,L]
RewriteRule ^([^/]+)/([^/]+)/?$ /index.php?page=$1&title=$2 [QSA,L]
RewriteRule ^([^/]+)/?$ /index.php?title=$1 [QSA,L]
```
how do I check this in my htaccess file for an right url build-up? |
null |
I want to store my object into MongoDB in golang.
The object 'A' contains a field:
`Messages []*Message `bson:"messages,omitempty" json:"messages"``
This array is an array of interface pointers. This is my interface:
`type Message interface {
GetType() enums.MessageType
GetId() string
}`
How can I save this field in mongoDB without creating the messages bson manually?
Today I am creating a bson by iterating on all the messages
This is my insert command:
`_, err := h.db.Collection(collectionName).InsertOne(ctx, A)
`
I tried to convert my array to a Map of [string],*Message and use the bson inline flag.
I tried to Marshall the entire object and got an error that there is no encoder to the interface. |
Save Interface in DB golang |
|mongodb|go|interface|repository| |
null |
{"Voters":[{"Id":207421,"DisplayName":"user207421"},{"Id":3745413,"DisplayName":"Ron Maupin"},{"Id":1940850,"DisplayName":"karel"}],"SiteSpecificCloseReasonIds":[13]} |
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.
|
Assuming you are talking about a DLL or static library with a v142 toolkit and you want to use it as a dependency of a project (DLL or EXE) with other toolkits, there are several cases:
- if the dependant is a static library, both must use the same toolkit, because the static lib must be linked with the same toolkit it has been compiled for.
- if the dependant is a DLL that exposes C++ types, (like `std::string`, `std::list` etc.) in its API; (`dllexport`) the toolkit of both projects must be the same, since the types aren't the same when using other toolkit.
- if all DLL exported types are atomics (like integers, or pointers) each can be compiled with a different toolkit.
Changing the toolkit is not a big issue, if you need to compile it on both toolkits, duplicate the debug and release configuration, and change the toolkit for the new configurations.
|
### About `I would like it to return tab/sheet name "Park Letter" instead.`
When I saw your showing script, `var sheetName = SpreadsheetApp.getActiveSpreadsheet().getName();` is used as the filename of PDF file at `MailApp.sendEmail (emailAddress, subject ,body, {attachments:[{fileName:sheetName+".pdf", content:contents, mimeType:"application//pdf"}]});`. If you want to use the value of `Park Letter` as the filename of a PDF file, how about the following modification?
By the way, I think that `application//pdf` should be `application/pdf`.
### From:
MailApp.sendEmail (emailAddress, subject ,body, {attachments:[{fileName:sheetName+".pdf", content:contents, mimeType:"application//pdf"}]});
### To:
MailApp.sendEmail(emailAddress, subject, body, { attachments: [{ fileName: "Park Letter" + ".pdf", content: contents, mimeType: "application/pdf" }] });
or
MailApp.sendEmail(emailAddress, subject, body, { attachments: [result.getBlob().setName("Park Letter.pdf")] });
By this modification, the filename of the PDF file is `Park Letter.pdf`.
### About `Even better would be a chosen name or a cell within the sheet.`
If you want to use the filename from the cell value, how about the following modification? In this case, please replace `###` to your sheet name. And, the value of cell "A1" is used as the filename. Please modify it to your actual situation.
### From:
MailApp.sendEmail (emailAddress, subject ,body, {attachments:[{fileName:sheetName+".pdf", content:contents, mimeType:"application//pdf"}]});
### To:
var filename = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("###").getRange("A1").getDisplayValue();
MailApp.sendEmail(emailAddress, subject, body, { attachments: [result.getBlob().setName(`${filename}.pdf`)] });
or
var filename = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("###").getRange("A1").getDisplayValue();
MailApp.sendEmail(emailAddress, subject, body, { attachments: [result.getBlob().setName(`${filename}.pdf`)] });
By this modification, the cell value of "A1" of the sheet "###" is used as the filename of the PDF file.
|
My name is Eduardo sorry for my bad English not my native language.
Im playing with Databricks with DLT and I have a question.
When a Play with regular ETL I can full manage the compute resource. I can tur on/off. But when a create a DLT Pipeline the 'job compute' is always on.
If there is an explanation about this ? Is charging me always or only when the pipeline execute.
Best regards
I create differente pipelines, and read some resources. But still don't find a direct answer |
Moving some functions from `generateObjects()` to `Sphere` constructor solved this issue.
>The error comes from the use of `objectReleaseCount` instead of `objects.size()`, for its name and use in other places, `objectReleaseCount` was meant for a totally different usage. Use `objects.size()` as an upper limit for looping, of better yet, use ranged for loops, as is `for (auto& obj : objects) {...}`, and the bug will disappear. |
I'm trying to build a web backend for a chat app using the runtime Bun, the library Elysia to write a REST API and the library socket.io to deliver the messages in realtime.
I went through the documentation of those 3 components, but I can't find a way to make them work together, either my GET requests are discarded by socket.io and never forwared to Elysia, or the opposite, Elysia doesn't forward the requests to socket.io.
I was trying to use the "Express" example of socket.io where they use "createServer(app)" of the http library where app is the express app, but I couldn't manage to do this for the Elysia app...
I know I could use two separate ports for the API and the socket or use Express for my REST API, but that's two options I'd like not to use.
If there is a working example for another modern router library like Hono, I could switch to another library.
Is there any documentation to do what I'm trying to do somewhere ?
Thanks ! |
Using Bun+Elysia+socket.io together |
|web|socket.io|backend|bun| |
null |
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. The full "rebuild all" log is here
-------------- Clean: Release in GraphicsC++ (compiler: GNU GCC
Compiler)---------------
Cleaned "GraphicsC++ - Release"
-------------- Build: Release in GraphicsC++ (compiler: GNU GCC
Compiler)---------------
g++.exe -Wall --verbose -fexceptions -O2 -Iinclude -c
C:\Users\ALEX\Documents\GraphicsC++\main.cpp -o obj\Release\main.o
g++.exe -o bin\Release\GraphicsC++.exe obj\Release\main.o --verbose -
s ..\..\..\..\Windows\SysWOW64\glu32.dll
Using built-in specs.
COLLECT_GCC=g++.exe
Target: x86_64-w64-mingw32
Configured with: ../../../src/gcc-8.1.0/configure --host=x86_64-w64-
mingw32 --build=x86_64-w64-mingw32 --target=x86_64-w64-mingw32 --
prefix=/mingw64 --with-sysroot=/c/mingw810/x86_64-810-posix-seh-rt_v6-
rev0/mingw64 --enable-shared --enable-static --disable-multilib --
enable-languages=c,c++,fortran,lto --enable-libstdcxx-time=yes --
enable-threads=posix --enable-libgomp --enable-libatomic --enable-lto -
-enable-graphite --enable-checking=release --enable-fully-dynamic-
string --enable-version-specific-runtime-libs --disable-libstdcxx-pch -
-disable-libstdcxx-debug --enable-bootstrap --disable-rpath --disable-
win32-registry --disable-nls --disable-werror --disable-symvers --with-
gnu-as --with-gnu-ld --with-arch=nocona --with-tune=core2 --with-
libiconv --with-system-zlib --with-
gmp=/c/mingw810/prerequisites/x86_64-w64-mingw32-static --with-
mpfr=/c/mingw810/prerequisites/x86_64-w64-mingw32-static --with-
mpc=/c/mingw810/prerequisites/x86_64-w64-mingw32-static --with-
isl=/c/mingw810/prerequisites/x86_64-w64-mingw32-static --with-
pkgversion='x86_64-posix-seh-rev0, Built by MinGW-W64 project' --with-
bugurl=https://sourceforge.net/projects/mingw-w64 CFLAGS='-O2 -pipe -
fno-ident -I/c/mingw810/x86_64-810-posix-seh-rt_v6-
rev0/mingw64/opt/include -I/c/mingw810/prerequisites/x86_64-zlib-
static/include -I/c/mingw810/prerequisites/x86_64-w64-mingw32-
static/include' CXXFLAGS='-O2 -pipe -fno-ident -I/c/mingw810/x86_64-
810-posix-seh-rt_v6-rev0/mingw64/opt/include -
I/c/mingw810/prerequisites/x86_64-zlib-static/include -
I/c/mingw810/prerequisites/x86_64-w64-mingw32-static/include'
CPPFLAGS=' -I/c/mingw810/x86_64-810-posix-seh-rt_v6-
rev0/mingw64/opt/include -I/c/mingw810/prerequisites/x86_64-zlib-
static/include -I/c/mingw810/prerequisites/x86_64-w64-mingw32-
static/include' LDFLAGS='-pipe -fno-ident -L/c/mingw810/x86_64-810-
posix-seh-rt_v6-rev0/mingw64/opt/lib -
L/c/mingw810/prerequisites/x86_64-zlib-static/lib -
L/c/mingw810/prerequisites/x86_64-w64-mingw32-static/lib '
Thread model: posix
gcc version 8.1.0 (x86_64-posix-seh-rev0, Built by MinGW-W64 project)
COLLECT_GCC_OPTIONS='-Wall' '-v' '-fexceptions' '-O2' '-I' 'include' '-
c' '-o' 'obj\Release\main.o' '-shared-libgcc' '-mtune=core2' '-
march=nocona'
C:/Program Files/CodeBlocks/MinGW/bin/../libexec/gcc/x86_64-w64-
mingw32/8.1.0/cc1plus.exe -quiet -v -I include -iprefix C:/Program
Files/CodeBlocks/MinGW/bin/../lib/gcc/x86_64-w64-mingw32/8.1.0/ -
D_REENTRANT C:\Users\ALEX\Documents\GraphicsC++\main.cpp -quiet -
dumpbase main.cpp -mtune=core2 -march=nocona -auxbase-strip
obj\Release\main.o -O2 -Wall -version -fexceptions -o
C:\Users\ALEX\AppData\Local\Temp\ccF1iSDG.s
GNU C++14 (x86_64-posix-seh-rev0, Built by MinGW-W64 project) version
8.1.0 (x86_64-w64-mingw32)
compiled by GNU C version 8.1.0, GMP version 6.1.2, MPFR version 4.0.1,
MPC version 1.1.0, isl version isl-0.18-GMP
GGC heuristics: --param ggc-min-expand=100 --param ggc-min- heapsize=131072
ignoring duplicate directory "C:/Program Files/CodeBlocks/MinGW/lib/gcc/../../lib/gcc/x86_64-w64- mingw32/8.1.0/include/c++"
ignoring duplicate directory "C:/Program Files/CodeBlocks/MinGW/lib/gcc/../../lib/gcc/x86_64-w64- mingw32/8.1.0/include/c++/x86_64-w64-mingw32"
ignoring duplicate directory "C:/Program Files/CodeBlocks/MinGW/lib/gcc/../../lib/gcc/x86_64-w64- mingw32/8.1.0/include/c++/backward"
ignoring duplicate directory "C:/Program Files/CodeBlocks/MinGW/lib/gcc/../../lib/gcc/x86_64-w64- mingw32/8.1.0/include"
ignoring nonexistent directory "C:/mingw810/x86_64-810-posix-seh-rt_v6-rev0/mingw64C:/msys64/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/../../../../include"
ignoring duplicate directory "C:/Program Files/CodeBlocks/MinGW/lib/gcc/../../lib/gcc/x86_64-w64-mingw32/8.1.0/include-fixed"
ignoring duplicate directory "C:/Program Files/CodeBlocks/MinGW/lib/gcc/../../lib/gcc/x86_64-w64-mingw32/8.1.0/../../../../x86_64-w64-mingw32/include"
ignoring nonexistent directory "C:/mingw810/x86_64-810-posix-seh-rt_v6-rev0/mingw64/mingw/include"
#include "..." search starts here:
#include <...> search starts here:
include
C:/Program Files/CodeBlocks/MinGW/bin/../lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++
C:/Program Files/CodeBlocks/MinGW/bin/../lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/x86_64-w64-mingw32
C:/Program Files/CodeBlocks/MinGW/bin/../lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/backward
C:/Program Files/CodeBlocks/MinGW/bin/../lib/gcc/x86_64-w64-mingw32/8.1.0/include
C:/Program Files/CodeBlocks/MinGW/bin/../lib/gcc/x86_64-w64-mingw32/8.1.0/include-fixed
C:/Program Files/CodeBlocks/MinGW/bin/../lib/gcc/x86_64-w64-mingw32/8.1.0/../../../../x86_64-w64-mingw32/include
cc version 8.1.0 (x86_64-posix-seh-rev0, Built by MinGW-W64End of search list.
GNU C++14 (x86_64-posix-seh-rev0, Built by MinGW-W64 project) version 8.1.0 (x86_64-w64-mingw32)
compiled by GNU C version 8.1.0, GMP version 6.1.2, MPFR version 4.0.1, MPC version 1.1.0, isl version isl-0.18-GMP
GGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072
Compiler executable checksum: 82f0c9785fd37a38ba7b7f8357369a82
COLLECT_GCC_OPTIONS='-Wall' '-v' '-fexceptions' '-O2' '-I' 'include' '-c' '-o' 'obj\Release\main.o' '-shared-libgcc' '-mtune=core2' '-march=nocona'
C:/Program Files/CodeBlocks/MinGW/bin/../lib/gcc/x86_64-w64- mingw32/8.1.0/../../../../x86_64-w64-mingw32/bin/as.exe -v -I include -o obj\Release\main.o C:\Users\ALEX\AppData\Local\Temp\ccF1iSDG.s
GNU assembler version 2.30 (x86_64-w64-mingw32) using BFD version (GNU Binutils) 2.30
COMPILER_PATH=C:/Program Files/CodeBlocks/MinGW/bin/../libexec/gcc/x86_64-w64- mingw32/8.1.0/;C:/Program Files/CodeBlocks/MinGW/bin/../libexec/gcc/;C:/Program Files/CodeBlocks/MinGW/bin/../lib/gcc/x86_64-w64- mingw32/8.1.0/../../../../x86_64-w64-mingw32/bin/
LIBRARY_PATH=C:/Program Files/CodeBlocks/MinGW/bin/../lib/gcc/x86_64-w64-mingw32/8.1.0/;C:/Program Files/CodeBlocks/MinGW/bin/../lib/gcc/;C:/Program Files/CodeBlocks/MinGW/bin/../lib/gcc/x86_64-w64-mingw32/8.1.0/../../../../x86_64-w64-mingw32/lib/../lib/;C:/Program Files/CodeBlocks/MinGW/bin/../lib/gcc/x86_64-w64- mingw32/8.1.0/../../../../lib/;C:/Program Files/CodeBlocks/MinGW/bin/../lib/gcc/x86_64-w64-mingw32/8.1.0/../../../../x86_64-w64-mingw32/lib/;C:/Program Files/CodeBlocks/MinGW/bin/../lib/gcc/x86_64-w64-mingw32/8.1.0/../../../
COLLECT_GCC_OPTIONS='-Wall' '-v' '-fexceptions' '-O2' '-I' 'include' '-c' '-o' 'obj\Release\main.o' '-shared-libgcc' '-mtune=core2' '- march=nocona'
Using built-in specs.
COLLECT_GCC=g++.exe
COLLECT_LTO_WRAPPER=C:/Program\ Files/CodeBlocks/MinGW/bin/../libexec/gcc/x86_64-w64-mingw32/8.1.0/lto- wrapper.exe
Target: x86_64-w64-mingw32
Configured with: ../../../src/gcc-8.1.0/configure --host=x86_64-w64-mingw32 --build=x86_64-w64-mingw32 --target=x86_64-w64-mingw32 -- prefix=/mingw64 --with-sysroot=/c/mingw810/x86_64-810-posix-seh-rt_v6- rev0/mingw64 --enable-shared --enable-static --disable-multilib --enable- languages=c,c++,fortran,lto --enable-libstdcxx-time=yes --enable- threads=posix --enable-libgomp --enable-libatomic --enable-lto --enable- graphite --enable-checking=release --enable-fully-dynamic-string --enable- version-specific-runtime-libs --disable-libstdcxx-pch --disable-libstdcxx- debug --enable-bootstrap --disable-rpath --disable-win32-registry -- disable-nls --disable-werror --disable-symvers --with-gnu-as --with-gnu-ld --with-arch=nocona --with-tune=core2 --with-libiconv --with-system-zlib -- with-gmp=/c/mingw810/prerequisites/x86_64-w64-mingw32-static --with- mpfr=/c/mingw810/prerequisites/x86_64-w64-mingw32-static --with- mpc=/c/mingw810/prerequisites/x86_64-w64-mingw32-static --with- isl=/c/mingw810/prerequisites/x86_64-w64-mingw32-static --with- pkgversion='x86_64-posix-seh-rev0, Built by MinGW-W64 project' --with- bugurl=https://sourceforge.net/projects/mingw-w64 CFLAGS='-O2 -pipe -fno- ident -I/c/mingw810/x86_64-810-posix-seh-rt_v6-rev0/mingw64/opt/include - I/c/mingw810/prerequisites/x86_64-zlib-static/include - I/c/mingw810/prerequisites/x86_64-w64-mingw32-static/include' CXXFLAGS='-O2 -pipe -fno-ident -I/c/mingw810/x86_64-810-posix-seh-rt_v6- rev0/mingw64/opt/include -I/c/mingw810/prerequisites/x86_64-zlib- static/include -I/c/mingw810/prerequisites/x86_64-w64-mingw32- static/include' CPPFLAGS=' -I/c/mingw810/x86_64-810-posix-seh-rt_v6- rev0/mingw64/opt/include -I/c/mingw810/prerequisites/x86_64-zlib- static/include -I/c/mingw810/prerequisites/x86_64-w64-mingw32- static/include' LDFLAGS='-pipe -fno-ident -L/c/mingw810/x86_64-810-posix- seh-rt_v6-rev0/mingw64/opt/lib -L/c/mingw810/prerequisites/x86_64-zlib- static/lib -L/c/mingw810/prerequisites/x86_64-w64-mingw32-static/lib '
Thread model: posix
gcc version 8.1.0 (x86_64-posix-seh-rev0, Built by MinGW-W64 project)
COMPILER_PATH=C:/Program Files/CodeBlocks/MinGW/bin/../libexec/gcc/x86_64-w64-mingw32/8.1.0/;C:/Program Files/CodeBlocks/MinGW/bin/../libexec/gcc/;C:/Program Files/CodeBlocks/MinGW/bin/../lib/gcc/x86_64-w64-mingw32/8.1.0/../../../../x86_64-w64-mingw32/bin/
LIBRARY_PATH=C:/Program Files/CodeBlocks/MinGW/bin/../lib/gcc/x86_64-w64-mingw32/8.1.0/;C:/Program Files/CodeBlocks/MinGW/bin/../lib/gcc/;C:/Program Files/CodeBlocks/MinGW/bin/../lib/gcc/x86_64-w64-mingw32/8.1.0/../../../../x86_64-w64-mingw32/lib/../lib/;C:/Program Files/CodeBlocks/MinGW/bin/../lib/gcc/x86_64-w64-mingw32/8.1.0/../../../../lib/;C:/Program Files/CodeBlocks/MinGW/bin/../lib/gcc/x86_64-w64-mingw32/8.1.0/../../../../x86_64-w64-mingw32/lib/;C:/Program Files/CodeBlocks/MinGW/bin/../lib/gcc/x86_64-w64-mingw32/8.1.0/../../../
COLLECT_GCC_OPTIONS='-o' 'bin\Release\GraphicsC++.exe' '-v' '-s' '-shared-libgcc' '-mtune=core2' '-march=nocona'
C:/Program Files/CodeBlocks/MinGW/bin/../libexec/gcc/x86_64-w64-mingw32/8.1.0/collect2.exe -plugin C:/Program Files/CodeBlocks/MinGW/bin/../libexec/gcc/x86_64-w64-mingw32/8.1.0/liblto_plugin-0.dll -plugin-opt=C:/Program Files/CodeBlocks/MinGW/bin/../libexec/gcc/x86_64-w64-mingw32/8.1.0/lto-wrapper.exe -plugin-opt=-fresolution=C:\Users\ALEX\AppData\Local\Temp\ccXKJKe8.res -plugin-opt=-pass-through=-lmingw32 -plugin-opt=-pass-through=-lgcc_s -plugin-opt=-pass-through=-lgcc -plugin-opt=-pass-through=-lmoldname -plugin-opt=-pass-through=-lmingwex -plugin-opt=-pass-through=-lmsvcrt -plugin-opt=-pass-through=-lpthread -plugin-opt=-pass-through=-ladvapi32 -plugin-opt=-pass-through=-lshell32 -plugin-opt=-pass-through=-luser32 -plugin-opt=-pass-through=-lkernel32 -plugin-opt=-pass-through=-liconv -plugin-opt=-pass-through=-lmingw32 -plugin-opt=-pass-through=-lgcc_s -plugin-opt=-pass-through=-lgcc -plugin-opt=-pass-through=-lmoldname -plugin-opt=-pass-through=-lmingwex -plugin-opt=-pass-through=-lmsvcrt --sysroot=C:/mingw810/x86_64-810-posix-seh-rt_v6-rev0/mingw64 -m i386pep -Bdynamic -o bin\Release\GraphicsC++.exe -s C:/Program Files/CodeBlocks/MinGW/bin/../lib/gcc/x86_64-w64-mingw32/8.1.0/../../../../x86_64-w64-mingw32/lib/../lib/crt2.o C:/Program Files/CodeBlocks/MinGW/bin/../lib/gcc/x86_64-w64-mingw32/8.1.0/crtbegin.o -LC:/Program Files/CodeBlocks/MinGW/bin/../lib/gcc/x86_64-w64-mingw32/8.1.0 -LC:/Program Files/CodeBlocks/MinGW/bin/../lib/gcc -LC:/Program Files/CodeBlocks/MinGW/bin/../lib/gcc/x86_64-w64-mingw32/8.1.0/../../../../x86_64-w64-mingw32/lib/../lib -LC:/Program Files/CodeBlocks/MinGW/bin/../lib/gcc/x86_64-w64-mingw32/8.1.0/../../../../lib -LC:/Program Files/CodeBlocks/MinGW/bin/../lib/gcc/x86_64-w64-mingw32/8.1.0/../../../../x86_64-w64-mingw32/lib -LC:/Program Files/CodeBlocks/MinGW/bin/../lib/gcc/x86_64-w64-mingw32/8.1.0/../../.. obj\Release\main.o ..\..\..\..\Windows\SysWOW64\glu32.dll -lstdc++ - lmingw32 -lgcc_s -lgcc -lmoldname -lmingwex -lmsvcrt -lpthread -ladvapi32 -lshell32 -luser32 -lkernel32 -liconv -lmingw32 -lgcc_s -lgcc -lmoldname -lmingwex -lmsvcrt C:/Program Files/CodeBlocks/MinGW/bin/../lib/gcc/x86_64- w64-mingw32/8.1.0/crtend.o
collect2.exe: error: ld returned 5 exit status
Process terminated with status 1 (0 minute(s), 0 second(s))
1 error(s), 0 warning(s) (0 minute(s), 0 second(s))
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.
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.
I appreciate any suggestions or insights on how to resolve this issue. Thank you! |
After I plugged my iPhone into my mac, I started debugging my app. For the first few days, it all seemed smooth.
But after a few days, things changed.
The Debug -> Attach to process menu is empty, as shown below. I can't figure out why.
But the weirder thing is that when I debugged my app three months later, the processes on my iPhone were correctly listed on the Attach to process menu, but they all disappeared after a few days.
My device configuration is: iPhone 6 - macOS Sonoma 14.3.1 - Xcode 15.2
[image](https://i.stack.imgur.com/MfmJy.png)
I can't wait a few months before I have a chance to debug my app. So I had to ask for help here.
|
I am making auto white balance calibration application.
I have a chromameter and api. So my application can measure CIExyY and CIEXYZ.
And my app can set R,G,B output value of my devices's LED panel.
I set R,G,B value combination and measureed CIEXYZ three times.
And then I evaluated follow matrix.
[1]: https://i.stack.imgur.com/TFDNW.png
I thought that once I evaluated the matrix, I could calculate CIEXYZ with R,G,B output value.
But It's not correct value.
R,G,B output value is 0~1023. 0 doesn't mean 0 output. 0~1023 is just level.
|
I want write code to predict CIE XYZ from LED driver R,G,B output value |
|colors|led|color-space| |
Here:
```
g++.exe -o bin\Release\GraphicsC++.exe obj\Release\main.o -s ..\..\..\..\Windows\SysWOW64\glu32.dll
```
You are trying to statically link a DLL (glu32.dll). You cannot do that, and your "simple code snippet" does not need OpenGL in any event! Moreover you cannot normally statically link code built using a different incompatible toolchain.
If you do need to link the OpenGL Utility library in your code, you should link the *MinGW provided* export library with the command line switch `-lglu32`. That will cause the _appropriate_ Windows provided DLL to be loaded at runtime. You should not try to link a specific DLL path - and using a relative path is bound to fail at some time, it rather assumes that your project will always be in the same place relative to the DLL!
Linking the OpenGL Utility library on its own with no other OpenGL support probably won't be useful either - but that is a different issue. |
I am trying to extract some links and text in a .json file from a web-page.
I have parsed the HTML tbody > tr > td, and each td contains `<a href="TextWithUrlBehind">Something</a>`
But this `TextWithUrlBehind` in Inspect Element is clickable, it has a link attached to it.
It is not a well-known `<a href=https//...>`
So, my extraction of href is `str: TextWithUrlBehind`, then `text(also str):Something` in the .json file
The code looks like this:
rows = test_results_table.find_all("tr")
# Iterate over each anchor tag
for row in rows:
first_cell = row.find("td")
if first_cell:
anchor_tag = first_cell.find("a", href=True)
self._debug_print("Anchor tag content:", anchor_tag)
if anchor_tag:
href = anchor_tag["href"]
text = anchor_tag.get_text(strip=True)
links.append({"href": href, "text": text})
self._debug_print("Content extracted:", {"href": href, "text": text})
else:
self._debug_print("No anchor tag found in cell:", first_cell)
else:
self._debug_print("No table cell found in row:", row)
I do not understand how that link is attached in HTML, and I don't know how beautifulsoup built-in functions can help me to get that link. |
How to extract url from <a href="TextWithUrlBehind">Something</a> using BeautifulSoup? |
|python|html|beautifulsoup| |
#### _Is it possible to stop the task initiated by system() on stopping the control script?_
As the `system` call simply passes the desired _command_ to the operating system, the operating system will decide whether you specified something that has to be wrapped and executed in a shell (like a batch file) or can be launched as process directly (e.g. when you specify an executable). In your case you have a windows operating system and you have specified a _npm.cmd_ file (where
_cmd_ files are more or less the same as batch (.bat) files).
In order to execute the commands within the specified file, a command processor has to be hosted which is usually `cmd.exe`. So a new console process will be started, hosting the command processor which will execute the commands within the _npm.cmd_ script.
So how can we now stop this launched process when we want to?
There are several possible ways to achieve this (all are of varying complexity and required more or less workload):
- **Approach 1:**
Find the process id of the launched command processor and terminate it whenever you want to.
The first one can be done with a command called [`tasklist`](https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/tasklist).
According to the documentation there are several filter possibilities specifiable by a command line argument called _/fi_ like _IMAGENAME_, _WINDOWTITLE_ and so on in form of a string. With a command line argument called _/fo_ the format of the output can be specified. So as an example `tasklist /V /FI "IMAGENAME eq cmd.exe" /FO CSV` would return all running command processors with their process id and their window title. Usually the window title includes the command that is executed, in the example above it would be exactly _C:\WINDOWS\system32\cmd.exe - tasklist /V /FI "IMAGENAME eq cmd.exe" /FO CSV_
Once the process id is retrieved a command called [`takskill`](https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/taskkill) can be used to kill the desired process.
_Sidenote:_
_Searching for the process id itself can be omitted by directly using the filter capabilities of the `taskkill` command (see [taskkill - parameters](https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/taskkill#parameters) for details)._
**Disadvantages of this approach**:
- It might be rather problematic to find the correct process id if multiple command shells are running and who can really guarantee that this will not be the case? So a rather defensive approach on really finding the correct process id is required.
- The process will be terminated and not gracefully shutdown
- **Approach 2:**
Using the possibilities of the `system` command to retrieve the process id of the launched process. According to the documentation of [`system`](https://www.winccoa.com/documentation/WinCCOA/3.18/de_AT/ControlS_Z/system.html)
> **Return value**
> Returns the return code of the program that was executed. Returns -1 if no argument was specified, a new process could not be created or if the started process was not finished normally.
>
> **In case the "options" mapping is used and the "timeout" is set to -1, the return value will be the PID.** Should an error occur, the return value is -1.
>
> If the process was terminated with "kill" after the "timeout" and "terminateTimeout", -2 is returned.
Therefore all that is needed is to validate the return value of the `system` function call and use the return value as process id. Whenever required, a call to `taskkill` as shown in _Approach 1_ can be executed to terminate the process.
- **Approach 3:**
Using the pmon for the dirty work. As stated in the documentation of the [pmon](https://www.winccoa.com/documentation/WinCCOA/3.18/de_AT/Pmon_Consolepanel/Pmon_Consolepanel-06.html#Pmon_Consolepanel-06__commands) it supports a rather simple command protocol. It might be easier to use the supported commands in order to start and stop the manager (simulator) at will.
#### _When running the simulator via WinCC OA, nothing of the simulator is visible. Is it possible to show a command line screen or a GUI on starting with system()?_
When a function call to the `system` function is executed where arguments for `stdout` and `stderr` are specified, the underlaying operating system process is launched with redirected output- and error streams. Thus all information that is outputted by the launched process will be redirected by the operating system so the hosting process (in your example the control manager) can access this information.
One way to solve this issue might be to force the launched process to write it's output into specified files which can be polled for changes. This can be done by specifying filenames for _stderr_ and _stdout_ in the _options_ mapping for the `system` function call. |
```
var dt_filter = dt_filter_table.DataTable({
ajax: {
url: '/banner/data',
error: function (xhr, error, thrown) {
console.error('DataTables AJAX error:', error);
console.log('XHR response:', xhr.responseText);
}
},
// columns: [
// { data: 'title' },
// { data: 'doctor_id' },
// { data: 'create_date' },
// { data: 'updated_at' },
// { data: 'actions' }
// ],
aoColumns: [
{ "data": "title" },
{ "data": "created_at" },
{ "data": 'updated_at' },
{
"mData": "id",
"mRender": function (data, type, row) {
if (data) {
return '<div class="col-sm-6 p-4"><input type="checkbox" class="switch-input" /><span class="switch-toggle-slider"><span class="switch-on" ></span><span class="switch-off"></span></span></div>'
}
}
},
{
"mData": "id",
"mRender": function (data, type, row) {
return "<div class='d-flex justify-content-center'><a class='btn btn-primary me-2' href='banner/detail/" + data + "'>Edit</a><a class='btn btn-danger mr-2 text-white' onclick='deleteConfirm(" + data + ")'>Delete</a></div>";
}
}
],
orderCellsTop: true,
dom: '<"row"<"col-sm-12 col-md-6"l><"col-sm-12 col-md-6 d-flex justify-content-center justify-content-md-end"f>><"table-responsive"t><"row"<"col-sm-12 col-md-6"i><"col-sm-12 col-md-6"p>>'
});
```
i have this code for rendering datatable with laravel php. i have a problems when i want to render switch component in second last object in aoColumn property. it always says that the checkbox is always null, my current assu,ption is there is a problem between datatable and bootstrap.
how do i solve this problem? |
Assuming the data has been stored in table named Numbers
``` SQL
WITH NUM AS
(
SELECT
A.*,
ROW_NUMBER() OVER(PARTITION BY ID1, ID2 ORDER BY VALUE) AS RN
FROM
NUMBERS A
)
SELECT
A.ID1, A.ID2, A.LOWER, A.VALUE,A.UPPER,
SUM(COALESCE(B.MEASUREMENT, 0) AS DESIRED
FROM
NUM A
LEFT JOIN
NUM B ON A.ID1 = B.ID1
AND A.ID2 = B.ID2
AND A.LOWER >= B.LOWER
AND A.UPPER <= B.UPPER
AND A.RN > B.RN
GROUP BY
1, 2, 3, 4, 5, 6
```
|
if all the images are inside the `public` folder, you can directly refer the images like below.
const imageArray = [
{
name: "choso",
text: "i hate the rain",
file: "/choso.jpg",
},
{
name: "pink planet",
text: "the garden",
file: "/cute-planet.gif",
}
];
The `Image` component will render the images from the public folder if we have not specified a direct path |
The thing you should know is that the size of a pointer is independent of its data type and it is based on the computer architecture; for example, on a 64-bit machine this code snippet always returns 8 which means whatever the type of pointer is it always takes 8 bytes;
int main()
{
int *p;
float *p1;
double *p2;
char *p3;
std::cout <<sizeof(p)<< std::endl;
std::cout <<sizeof(p1)<< std::endl;
std::cout <<sizeof(p2)<< std::endl;
std::cout <<sizeof(p3)<< std::endl;
return 0;
} |
### Problem description
I'm writing a python library and I am planning to upload both sdist (.tar.gz) and wheel to PyPI. The [build docs say](https://build.pypa.io/) that running
```
python -m build
```
I get sdist created from the source tree and *wheel created from the sdist*, which is nice since I get the sdist tested here "for free". Now I want to run tests (pytest) against the wheel with multiple python versions. What is the easiest way to do that?
I have been using tox and I see there's an option for [setting package to "wheel"](https://tox.wiki/en/latest/config.html#package):
```
[testenv]
description = run the tests with pytest
package = wheel
wheel_build_env = .pkg
```
But that does not say *how* the wheel is produced; I am unsure if it
a) creates wheel directly from source tree<br>
b) creates wheel from sdist which is created from source tree in a way which *is identical to* `python -m build`<br>
c) creates wheel from sdist which is created from source tree in a way which *differs from* `python -m build`
*Even if the answer would be c), the wheel tested by tox would not be the same wheel that would be uploaded, so it is not testing the correct thing. **Most likely I should somehow give the wheel as an argument to tox / test runner.***
## Question
I want to create a wheel from sdist which is created from the source tree, and I want to run unit tests against the wheel(s) with multiple python versions. This is a pure python project, so there will be only a single wheel per version of the package. What would be the idiomatic way to run the tests against the *same* wheel(s) which I would upload to PyPI? Can I use tox for that?
|
For eg:
* if today's date is 03/39/2024, it should print after 60 days -05/28/2024
Code to get today's date:
$fromMillis($toMillis($now()), '[M01]/[D01]/[Y0001]')
But how to print for 60 calendar days in jsonata? Can anyone please help?` |
Databricks Delta table / Compute job |
|apache-spark|databricks|delta-live-tables| |
null |
I have to work with the learning history of a Keras model. This is a basic task, but I've measured the performance of the Python built-in min() function, the numpy.min() function, and the numpy ndarray.min() function. The performance of the built-in Python min() function is nothing compared to that of Numpy. However, the ndarray.min() function is twice as fast as numpy.min(). The ndarray.min() documentation refers to the numpy.amin() documentation, which according to the numpy.amin docs, is an alias for numpy.min(). Therefore, I assumed that numpy.min() and ndarray.min() would have the same performance. However, why is the performance of these functions not equal?
```
from timeit import default_timer
import random
a = random.sample(range(1,1000000), 10000)
b = np.array(random.sample(range(1,1000000), 10000))
def time_mgr(func):
tms = []
for i in range(3, 6):
tm = default_timer()
for j in range(10**i):
func()
tm = (default_timer()-tm) / 10**i * 10e6
tms.append(tm)
print(func.__name__, tms)
@time_mgr
def p_min():
min(a)
@time_mgr
def np_min():
np.min(a)
@time_mgr
def np_min_nd():
np.min(b)
@time_mgr
def np_nd_min():
b.min()
```
output:
```
p_min [515.8160021528602, 510.07160008884966, 515.668320003897]
np_min [2975.683999247849, 2990.276100113988, 2991.7960500111803]
np_min_nd [21.873998921364546, 21.262200083583597, 21.36570999864489]
np_nd_min [12.89099920541048, 13.075799914076923, 12.750419997610152]
```
|
Numpy array methods are faster than numpy functions? |
|python|arrays|numpy|multidimensional-array|min| |
null |
You can do this in the following ways.
Using PySpark:
```lang-py
import requests
from pyspark.sql import SparkSession
spark = SparkSession.builder.getOrCreate()
response = requests.get("https://www.imf.org/external/datamapper/api/v1/GG_DEBT_GDP")
json_data = response.json()["values"]["GG_DEBT_GDP"]
data_list = [{"year": year, "country": country, "value": value}
for country, values in json_data.items()
for year, value in values.items()]
df = spark.createDataFrame(data_list, schema="year STRING, country STRING, value STRING")
df.show()
```
Using Pandas + PySpark:
```lang-py
import pandas as pd
from pyspark.sql import SparkSession
spark = SparkSession.builder.getOrCreate()
json_data = pd.read_json("https://www.imf.org/external/datamapper/api/v1/GG_DEBT_GDP")["values"][0]
df = (pd.DataFrame.from_dict(json_data)
.reset_index().rename(columns={"index": "year"})
.melt(id_vars="year", var_name="country", value_name="value"))
spark_df = spark.createDataFrame(df)
spark_df.show()
```
Both give the following output:
```lang-none
+----+-------+---------------+
|year|country| value|
+----+-------+---------------+
|1950| USA|83.126037377225|
|1951| USA|72.955032400931|
|1952| USA| 72.52549154977|
|1953| USA|71.753218636523|
|1954| USA|73.568066469359|
|1955| USA|68.498633447214|
|1956| USA|64.726033476873|
|1957| USA|62.329546033921|
|1958| USA|64.927332482752|
|1959| USA|62.335885122406|
|1960| USA| 60.83294667213|
|1961| USA|61.393351025592|
|1962| USA|59.371677777831|
|1963| USA|57.954915607618|
|1964| USA|55.988828640074|
|1965| USA|53.060492322606|
|1966| USA| 50.14458097802|
|1967| USA|50.395848934109|
|1968| USA|48.736870113876|
|1969| USA|45.939659073617|
+----+-------+---------------+
only showing top 20 rows
``` |
|python|cupy| |
Accessing displayed hyphens of an HTML element with JavaScript |
For python 2.7:
```pip install glob2```
For python 3.7:
```pip3 install glob2```
|
**I want to fetch data from Amazon's website, list the products, and then navigate to Amazon's site by tapping on the listed items in the application. However, I encountered the following error;**
E/flutter (15082): \[ERROR:flutter/runtime/dart_vm_initializer.cc(41)\] Unhandled Exception: Could not launch /sspa/click?
E/flutter (15082): #0 \_AmazonScrapingPageState.\_launchURL (package:web_scraping/main.dart:59:7)
**And that is my code below ;**
```
void _parseProductData(String htmlString) {
var document = dom.parse(htmlString);
var productElements = document.querySelectorAll('.s-result-item');
productElements.forEach((element) {
var titleElement =
element.querySelector('.a-size-base-plus.a-color-base.a-text-normal');
var priceElement = element.querySelector('.a-price');
var linkElement = element.querySelector('a.a-link-normal');
if (titleElement != null && priceElement != null && linkElement != null) {
var title = titleElement.text.trim();
var price = priceElement.text.trim();
var link = linkElement.attributes['href'];
productTitles.add(title);
productPrices.add(price);
productLinks.add(link!);
}
});
}
Future<void> _launchURL(String url) async {
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
}
@override
child: ListView.builder(
itemCount: productTitles.length,
itemBuilder: (context, index) {
return GestureDetector(
onTap: () {
_launchURL(productLinks[index]);
},
```
**The screen displays selected products along with their prices, but when I tap on the products, I can't navigate to the product links. Already tried flutter clean , and closing app then flutter run .** |
In the following piece of code:
type
TDoubleDWORD = record
L, H: Longint;
end;
function BitSelection(const Block: Integer; const A;
const ASize: Integer): Longint;
var
H, L: Longint;
begin
H := TDoubleDWORD(Block).H;
L := TDoubleDWORD(Block).L;
My Questions Are:
1) What is the type of parameter `A`?
2) What does `TDoubleDWORD(Block)` mean? Is that some sort of constructor for the record `TDoubleDWORD`?
Sorry if the questions seem trivial, but I'm pretty new to the Delphi Programming Language and Google isn't much help. |
null |
null |
null |
null |
null |
null |
I have the following input-file (p) ($inputFile)
```
PING 8.8.8.8 (8.8.8.8): 56 data bytes
11:36:27.996138 64 bytes from 8.8.8.8: icmp_seq=1 ttl=109 time=48.066 ms
11:36:28.991554 64 bytes from 8.8.8.8: icmp_seq=2 ttl=109 time=39.374 ms
Request timeout for icmp_seq 3
11:36:31.000927 64 bytes from 8.8.8.8: icmp_seq=4 ttl=109 time=41.830 ms
--- 8.8.8.8 ping statistics ---
4 packets transmitted, 3 packets received, 25.0% packet loss
round-trip min/avg/max/stddev = 30.542/40.064/54.798/6.720 ms
```
I want another file ($outputFile), based on the input-file, which should have this structure:
- write 0 if the line contains the word "bytes"
- write 1 if the line contains the word "timeout"
this **should** give me this
```
0
0
1
0
```
I use this bash function-*fragment* to achieve this
```
while read p; do
if echo "$p" | grep 'bytes from'; then
echo 0
elif echo "$p" | grep 'timeout'; then
echo 1
fi
done <$inputFile >>$outputFile
```
What I really get in the $outputFile is
```
11:36:27.996138 64 bytes from 8.8.8.8: icmp_seq=1 ttl=109 time=48.066 ms
0
11:36:28.991554 64 bytes from 8.8.8.8: icmp_seq=2 ttl=109 time=39.374 ms
0
Request timeout for icmp_seq 3
1
11:36:31.000927 64 bytes from 8.8.8.8: icmp_seq=4 ttl=109 time=41.830 ms
0
```
**How do I get rid of the original lines in the output-file ($outputFile)?**
|
{"Voters":[{"Id":367865,"DisplayName":"Ouroborus"},{"Id":476,"DisplayName":"deceze"}],"SiteSpecificCloseReasonIds":[13]} |
1. Return a pointer to the `Node` of interest instead of updating the out parameter `head_dest`. The stack will implicitly hold `cur_list_dest`.
1. The original implementation changes the original list. To create a new list you need to return a pointer to *copy* of the smallest node or NULL. To emphasize that I made the argument constant with `const Node *head`.
1. Observe that `pairWiseMinimumInNewList_Rec()` either returns a copy of the 1st or 2nd node, or if head is NULL then it's base case and we return NULL. The recursive case is two nodes ahead otherwise we are done and will subsequently invoke the base case. This allows you to collapse all those if statements by making the values conditional instead.
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Node {
int val;
struct Node *pt_next;
} Node;
Node *linked_list_new(int val, Node *pt_next) {
Node *n = malloc(sizeof *n);
if(!n) {
printf("malloc failed\n");
exit(1);
}
n->val = val;
n->pt_next = pt_next;
return n;
}
Node *linked_list_create(size_t n, int *vals) {
Node *head = NULL;
Node **cur = &head;
for(size_t i=0; i < n; i++) {
*cur = linked_list_new(vals[i], NULL);
if(!head) head = *cur;
cur = &(*cur)->pt_next;
}
return head;
}
void linked_list_print(Node *head) {
for(; head; head=head->pt_next)
printf("%d->", head->val);
printf("NULL\n");
}
void linked_list_free(Node *head) {
while(head) {
Node *tmp = head->pt_next;
free(head);
head=tmp;
}
}
Node *pairWiseMinimumInNewList_Rec(const Node* head) {
return head ?
linked_list_new(
(head->pt_next && head->val < head->pt_next->val) || !head->pt_next ?
head->val :
head->pt_next->val,
pairWiseMinimumInNewList_Rec(head->pt_next ? head->pt_next->pt_next : NULL)
) :
NULL;
}
int main() {
Node *head=linked_list_create(7, (int []) {2,1,3,4,5,6,7});
Node* head_dest=pairWiseMinimumInNewList_Rec(head);
linked_list_free(head);
linked_list_print(head_dest);
linked_list_free(head_dest);
}
```
Example run that exercises the 3 code paths:
```
1->3->5->7->NULL
``` |
There were some mentions about higher version doesn't work.
So, I installed **python 3.8.**
Then, I installed as below.
**conda install -y pytorch==1.12.0 torchvision==0.13.0 -c pytorch**
CUDA 11.2 with pytorch gpu works fine.
I confirmed it with nvidia-smi. |
Try implementing Serializable
public class AccountDTO implements Serializable {
//your fields, constructors, methods etc.
}
|
How to find out what rights a user has in a telegram group using an aiogram bot?
I am using the latest version of aiogram 3.4.1 |
How to find out what rights a user has in a telegram group using an aiogram bot |
|python|aiogram| |
there are two files in current dir
```
[root@workspace tmp]# ll
total 8
-rw-------. 1 root root 6 Mar 31 13:18 *
-rw-------. 1 root root 6 Mar 31 13:18 ?
[root@workspace tmp]# for f in "`find . -type f`";do echo "$f";done
./*
./?
[root@workspace tmp]# for f in "`find . -type f`";do echo $f;done
./* ./? ./* ./?
```
I am confused about the output of the two echo ...
the differenct is: the double quote around the $f
why the outputs are so, anyone can explain this?
thanx any help in advance.
|
I would like to add a little bit of info to the Ermiya excellent answer. His changes work for me also but in 2 of my 3 scenarios. You will see that the 403 error you got could be misleading in some cases...
Case 1: Local stack
If you are doing all the above but working locally with the Lambda emulator as in my case, the identity that is used to forge the security token for this presigned URL is you active or default AWS CLI profil ID. So, if you are using an AWS account that is "AdministorAcces" level it will work not problem.
Case 2: Anonymous request from a SPA Web App calling a Lambda API
This were the solution didn't work for me. And it's all related to the role that is assign to the lambda that I used to return the presigned url. You have to known that the temporary access credential that will be used (call to AWS STS) to generate the security token (X-Amz-Security-Token) use the access level that is giving by the role to the lambda. In my case it had the bare minimum to write to the S3 bucket (S3WriteAccessPolicy in SAM jargon). This policy didn't include the s3:PutObjectTagging action required to effectively carry what the x-amz-tagging is asking for. So the result will be a 403 error with the same misleading error msg "403 SignatureDoesNotMatch". But in reality, the PUT request could not be executed because of the lack of access to tagging rights. So this is my last use case that put me on the right track.
Case 3: Authenticated request from a SPA Web App calling another Lambda API
So, this use case was also working correctly with the Ermiya solution but why since the only difference was that one of my app was anonymous and the other one was authenticated (using Cognito). But looking at my code, I realized that the lambda serving my authenticated users was at S3FullAccessPolicy level (that include the s3:PutObjectTagging action right) and the other one was a lot more restricted (since it's anonymous). To confirmed my suspicious, I added the required action for the tagging to my anonymous Lamdba permissions and "boom", it work right away!
So the take away of this trial and error is to also make sure that the process that request the presigned URL has the correct permissions (s3:PutObjectTagging) otherwise your're in for some hair pulling sessions! |
Can anyone tell me why we should set the counter j in the inner for loop to (i+1) not (i=0) (beacause I think setting j to i = 0 will get all elements in the array).
And why we using break;
I am new in programming.
Thanks in advance.
Here I check for the duplicates and if I set (j = i+1) the first element in the array will be skipped (with the index 0) from the comparison isn't it ? |
Setting the counter (j) for (inner for loop) |
|arrays|for-loop|iteration|nested-loops| |
null |
use
from albumentations.augmentations.crops.functional import crop
|
I want to store my object into MongoDB in golang.
The object 'A' contains a field:
`Messages []*Message `bson:"messages,omitempty" json:"messages"``
This array is an array of interface pointers. This is my interface:
`type Message interface {
GetType() enums.MessageType
GetId() string
}`
How can I save this field in mongoDB without creating the messages bson manually?
Today I am creating a bson by iterating on all the messages
This is my insert command:
`_, err := h.db.Collection(collectionName).InsertOne(ctx, A)
`
I tried to convert my array to a Map of [string],*Message and use the bson inline flag.
I tried to Marshall the entire object and got an error that there is no encoder to the interface. |
Bootstrap component does not want to render in Datatables function |
|php|jquery|laravel|datatables|bootstrap-5| |
null |
I was just learning the front-end, then I came up with a way to create a module using IIFE and register it to the namespace. From the code below, I still don't understand a few things:
1. Why does the function need a window as an argument?
2. What does this variable declaration mean: `var App = window.App || { };`. And why is it that at the bottom line there is a declaration: `window.App = App`. What is the difference between the two declarations?
```
(function(window){
'use strict';
var App = window.App || {};
function DataStore(){
console.log('running the DataStore function');
}
App.DataStore = DataStore;
window.App = App;
}) (window);
```
I didn't understand the workflow of the function, and the site I visited didn't provide a detailed explanation. I hope you all can help me, thank you. |
I am learning Spring boot JPA hibernate mapping. I am trying to create 2 tables Employee and Address. It is a unidirectional OneToOne mapping. I am creating foreign key in Employee table. Employee contains address and it is a strong association. Without Employee, Address doesn't exist.
My createEmployee controller is working fine but when I'm trying to updateEmployee, it is creating a new entry in the Address table.
Please tell me if anything I am missing or doing wrong. Thanks!
Below is the code.
**Address.java**
```
@Entity @Table
@NoArgsConstructor @Getter @Setter
public class Address {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "addr_id")
private Integer addressId;
private String addr;
public Address(String addr) {
this.addr = addr;
}
```
**Employee.java**
```
@Table @Entity
@NoArgsConstructor @Getter @Setter
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer empId;
private String name;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "address_id", referencedColumnName = "addr_id")
private Address address;
public Employee(String name, Address address) {
this.name = name;
this.address = address;
}
```
**AddressRepo.java**
```
public interface AddressRepo extends JpaRepository<Address, Integer> {
}
```
```
public interface EmployeeRepo extends JpaRepository<Employee, Integer> {
}
```
```
@Service
public class EmployeeServiceImpl implements EmployeeService {
@Autowired
private EmployeeRepo employeeRepo;
@Override
public Employee createEmployee(Employee employee) {
Employee tempEmployee = this.employeeRepo.save(employee);
return tempEmployee;
}
@Override
public Employee updateEmployee(Employee employee, Integer id) {
Employee tempEmployee = this.employeeRepo.findById(id).get();
tempEmployee.setName(employee.getName());
tempEmployee.setAddress(employee.getAddress());
System.out.println(employee);
return employeeRepo.save(tempEmployee);
}
@Override
public Employee getEmployee(Integer id) {
return this.employeeRepo.findById(id).get();
}
@Override
public Employee deleteEmployee(Integer id) {
Employee employee = getEmployee(id);
this.employeeRepo.deleteById(id);
return employee;
}
@Override
public List<Employee> getAllEmployeees() {
return this.employeeRepo.findAll();
}
}
```
```
@RestController
@RequestMapping("/employee")
public class EmployeeController {
@Autowired
private EmployeeService employeeService;
// Get all employees
@GetMapping("/")
public List<Employee> getAllEmployees() {
return this.employeeService.getAllEmployeees();
}
// Get one employee
@GetMapping("/{employeeId}")
public Employee getEmployee(@PathVariable("employeeId") Integer employeeId) {
return this.getEmployee(employeeId);
}
// save employee
@PostMapping("/")
public Employee createEmployee(@RequestBody Employee employee) {
return this.employeeService.createEmployee(employee);
}
// update employee
@PutMapping("/{employeeId}")
public Employee updateEmployee(@PathVariable("employeeId") Integer employeeId,
@RequestBody Employee employee) {
return this.employeeService.updateEmployee(employee, employeeId);
}
// delete employee
@DeleteMapping("/{employeeId}")
public Employee deleteEmployee(@PathVariable("employeeId") Integer employeeId) {
return this.employeeService.deleteEmployee(employeeId);
}
}
```
[![My HTTP request][1]][1]
[1]: https://i.stack.imgur.com/rQ75G.png |
The answer was not to as suggested.
The application.properties on **consumer** module was redefined to
```
#spring.kafka.consumer.bootstrap-servers=kafka:9092
spring.kafka.consumer.group-id=groupid
spring.kafka.bootstrap-servers=kafka:9092
product.kafkaServer= ${spring.kafka.bootstrap-servers}
spring.kafka.properties.security.protocol=PLAINTEXT
spring.kafka.producer.key-serializer=org.apache.kafka.common.serialization.StringSerializer
spring.kafka.producer.value-serializer=org.apache.kafka.common.serialization.StringSerializer
```
The application.properties on **producer** module was redefined to
```
spring.kafka.bootstrap-servers=kafka:9092
spring.kafka.producer.group-id=groupid
spring.kafka.properties.security.protocol=PLAINTEXT
spring.kafka.producer.key-serializer=org.apache.kafka.common.serialization.StringSerializer
spring.kafka.producer.value-serializer=org.apache.kafka.common.serialization.StringSerializer
```
My Bean had to consume @Value("${spring.kafka.bootstrap-servers}")
Then the environment.yaml
```
version: '1.0'
services:
zookeeper:
image: confluentinc/cp-zookeeper:latest
environment:
ZOOKEEPER_CLIENT_PORT: 2181
ZOOKEEPER_TICK_TIME: 2000
ports:
- 22181:2181
kafka:
image: confluentinc/cp-kafka:latest
depends_on:
- zookeeper
ports:
- 29092:29092
environment:
KAFKA_BROKER_ID: 1
KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:9092,PLAINTEXT_HOST://localhost:29092
#KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:9092,PLAINTEXT_HOST://kafka:29092
KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT
KAFKA_INTER_BROKER_LISTENER_NAME: PLAINTEXT
KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
kafka-ui:
image: provectuslabs/kafka-ui:latest
depends_on:
- kafka
ports:
- 8090:8080
environment:
KAFKA_CLUSTERS_0_NAME: local
KAFKA_CLUSTERS_0_BOOTSTRAPSERVERS: kafka:9092
KAFKA_CLUSTERS_0_ZOOKEEPER: zookeeper:2181
consumer:
image: consumer:1.0.0
hostname: consumer1
container_name: consumer
ports:
- "8081:8081"
depends_on:
- kafka
producer:
image: producer:1.0.0
hostname: producer1
container_name: producer
ports:
- "8080:8080"
depends_on:
- consumer
```
|
Realm Swift - collection changes listener in SwiftUI |
|swift|swiftui|realm| |