instruction stringlengths 0 30k β |
|---|
It sounds like you are on the right track using [`pl.DataFrame.join_asof`](https://docs.pola.rs/py-polars/html/reference/dataframe/api/polars.DataFrame.join_asof.html). To group by the symbol the `by` parameter can be used.
```python
(
fr
.join_asof(
events,
left_on="Date", right_on="Earnings_Date",
by="Symbol",
)
)
```
```
shape: (5, 5)
βββββββββ¬βββββββββ¬βββββββββββββ¬ββββββββββββββββ¬ββββββββ
β index β Symbol β Date β Earnings_Date β Event β
β --- β --- β --- β --- β --- β
β u32 β str β date β date β i64 β
βββββββββͺβββββββββͺβββββββββββββͺββββββββββββββββͺββββββββ‘
β 0 β A β 2010-08-29 β 2010-06-01 β 1 β
β 1 β A β 2010-09-01 β 2010-09-01 β 4 β
β 2 β A β 2010-09-05 β 2010-09-01 β 4 β
β 3 β A β 2010-11-30 β 2010-09-01 β 4 β
β 4 β A β 2010-12-02 β 2010-12-01 β 7 β
βββββββββ΄βββββββββ΄βββββββββββββ΄ββββββββββββββββ΄ββββββββ
```
Now, I understand that you'd like each event to be matched *at most once*. I don't believe this is possible with `join_asof` alone. However, we can set all event rows that equal the previous row to `Null`. For this, an [`pl.when().then()`](https://docs.pola.rs/py-polars/html/reference/expressions/api/polars.when.html) construct can be used.
```python
(
fr
.join_asof(
events,
left_on="Date", right_on="Earnings_Date",
by="Symbol",
)
.with_columns(
pl.when(
pl.col("Earnings_Date", "Event").is_first_distinct()
).then(
pl.col("Earnings_Date", "Event")
).over("Symbol")
)
)
```
```
shape: (5, 5)
βββββββββ¬βββββββββ¬βββββββββββββ¬ββββββββββββββββ¬ββββββββ
β index β Symbol β Date β Earnings_Date β Event β
β --- β --- β --- β --- β --- β
β u32 β str β date β date β i64 β
βββββββββͺβββββββββͺβββββββββββββͺββββββββββββββββͺββββββββ‘
β 0 β A β 2010-08-29 β 2010-06-01 β 1 β
β 1 β A β 2010-09-01 β 2010-09-01 β 4 β
β 2 β A β 2010-09-05 β null β null β
β 3 β A β 2010-11-30 β null β null β
β 4 β A β 2010-12-02 β 2010-12-01 β 7 β
βββββββββ΄βββββββββ΄βββββββββββββ΄ββββββββββββββββ΄ββββββββ
``` |
Getting Run-time error '13': Type Mismatch using .Find |
|excel|vba| |
As you can read in the [documentation of `list.sort`][1]
> This method modifies the sequence in place for economy of space when sorting a large sequence. **To remind users that it operates by side effect, it does not return the sorted sequence** (use sorted() to explicitly request a new sorted list instance).
(bold text by me)
[1]: https://docs.python.org/3/library/stdtypes.html#list.sort |
I have $10$ random variables $X_1, X_2, \ldots X_{10} \sim \mathcal{N(0,1)}$, I want to generate $5000$ samples for them such that $X_1 < a$ and $X_i > a \forall i \in {2, 3, \ldots, 10}$.
The problem is I want this to be replicable given the same initial seed. By this I mean that if the seed supplied is the same, this should give rise to identical samples.
I don't know in advance how many samples to generate such that after filtering it gives rise to $5000$ good simulations (meets the filtering criteria). I tried to run it in blocks of say $100,000$ setting the initial seed to some fixed value $s$, if the first block fails to generate a sufficient number of samples, I have to rerun the simulation for another block, but obviously can't use the same seed again. Also, I am not sure if setting the seed to some other value for each block will not give rise to unwanted correlations between the samples in different blocks.
Is there a way to achieve this? I also want to point out that performance is important, so if possible please suggest something amenable to parallelization, or something that can be sped up by using numba.
Thanks a lot.
|
Producing filtered random samples which can be replicated using the same seed |
|numpy|random|filter|random-seed| |
format() method would work here as well:
for i in range(triangle_height + 1):
print('{}{}'.format(triangle_char, " ") * i)
i += 1
|
I'm experimenting with GLFW (compiling with **g++ -o nxtBluePixel nxtBluePixel.cpp -lglfw -lGLEW -lGL** ) to simply draw a blue box and move it up/down/left/right. I want to output a message "out of bounds" when the box touches the edges of the visible area, which should logically be -1 or 1 (in those so-called normalized OpenGL coordinates, so I read). But the box keeps continuing to move in an "invisible" region outside (and is invisible) but no message is displayed until a while (at least 10 hits or so on a key outside the edge boundary ... ChatGPT 4 can't help me, it says:
*"Correct Boundary Check: If you want the "out of bounds" message to appear as soon as the point is about to leave the visible area, your original check without the large epsilon is logically correct. However, if the message appears too late or too early, it might be due to how the point's position is updated or rendered, not the boundary check itself."*
any ideas? I never use OpenGL, so I wanted to try... but this is typically the kind of very annoying problem I hate!
and here my code:
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <iostream>
#include <string>
#include <cctype>
GLint worldWidth = 400;
GLint worldHeight = 300;
// Starting position of the pixel
float currX = 0.0f;
float currY = 0.0f;
float stepSize = 1.0f / worldWidth;
float speed = 2.0f;
void updateWorld(char keyPressed, float speed){
switch (keyPressed) {
case 'W':
//up
currY += stepSize*speed;
break;
case 'A':
//left
currX -= stepSize*speed;
break;
case 'S':
//down
currY -= stepSize*speed;
break;
case 'D':
//right
currX += stepSize*speed;
break;
}
//using openGL 'normalized' coords i.e. between -1 and 1
if (currX >= 1.0 || currX <= -1.0 || currY >= 1.0 || currY <= -1.0){
printf("OUT OF BOUNDS !!!!");
}
}
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) {
char key_str = '0';
if (action == GLFW_PRESS || action == GLFW_REPEAT) {
switch (key) {
case GLFW_KEY_W:
key_str = 'W';
break;
case GLFW_KEY_A:
key_str = 'A';
break;
case GLFW_KEY_S:
key_str = 'S';
break;
case GLFW_KEY_D:
key_str = 'D';
break;
case GLFW_KEY_Q:
printf("Bye ...");
glfwSetWindowShouldClose(window, GL_TRUE);
break;
default:
printf("unknown key pressed \n");
break;
}
updateWorld(key_str, speed);
}
}
int main(void) {
GLFWwindow* window;
// Initialize the library
if (!glfwInit())
return -1;
//remove win frame
//glfwWindowHint(GLFW_DECORATED, GLFW_FALSE);
// Create a windowed mode window and its OpenGL context
window = glfwCreateWindow(worldWidth, worldHeight, "Move Pixel with Keyboard", NULL, NULL);
if (!window) {
glfwTerminate();
return -1;
}
// Make the window's context current
glfwMakeContextCurrent(window);
// Set the keyboard input callback
glfwSetKeyCallback(window, key_callback);
// Initialize GLEW
glewExperimental = GL_TRUE;
if (glewInit() != GLEW_OK) {
std::cerr << "Failed to initialize GLEW" << std::endl;
return -1;
}
//glfwGetFramebufferSize(window, &worldWidth, &worldHeight);
// Define the viewport dimensions
glViewport(0, 0, worldWidth, worldHeight);
// Set point size
glPointSize(10.0f); // Increase if you want the "pixel" to be bigger
// Loop until the user closes the window
while (!glfwWindowShouldClose(window)) {
// Render here
glClear(GL_COLOR_BUFFER_BIT);
// Set the drawing color to blue
glColor3f(0.0f, 0.0f, 1.0f); // RGB: Blue
// Draw a point at the current position
glBegin(GL_POINTS);
glVertex2f(currX, currY); // Use the updated position
glEnd();
// Swap front and back buffers
glfwSwapBuffers(window);
// Poll for and process events
glfwPollEvents();
}
glfwTerminate();
return 0;
}
In the worst case i can debug step by step with printf ... but well it will take a long time...
|
i have being building a telegram bot with nodejs where people can send in a url of a tweet and if it contains a media of type video. it downloads it and sends it to the user. Thats the purpose, which i already completed.
The problem i have is with setting a paywall on this bot account so that after 2 or 3 request, the user interacting with the bot have to make a payment to continue.
so i used the [sendInvoice](https://core.telegram.org/bots/api#sendinvoice) method.
FYI, i'm not using any external librarys, i'm directly interacting with the telegram api endpoints.
I'm using stripe for payments in test mode. the problem i have is as you can see this picture:
[This is whats happening/showing after some time](https://i.stack.imgur.com/Vm69E.png)
After i send the invoice, then the user clicks the pay button and adds all the necessary card details then after hitting the pay. it keeps buffering and then time outs.
I also tried the [createInvoiceLink](https://core.telegram.org/bots/api#createinvoicelink) method and the same thing happened.
Ofcourse its some mistake in my solution, but i dont know where that is. May be i have to use a webhook or something to catch the checkout initiation/completion. but how can i let the Telegram api know about my payment webhook path (assuming something like that exists).
The only one i found is the method [setWebhook](https://core.telegram.org/bots/api#setwebhook) which is an alternative approach for polling. And that is what i am doing locally with ngrok.
A Part of my code, this is an abstract version of the functionality:
```
const app = express();
const port = 3000;
const botToken = process.env.TELEGRAM_BOT_TOKEN;
app.use(bodyParser.json());
app.post(`/bot${botToken}`, async (req, res) => {
const { message } = req.body;
console.log({ message });
if (message && message.text) {
const chatId = message.chat.id;
const messageText = message.text;
// after successfull 3 responses from the bot, send an invoice
const invoiceRes = await sendInvoice(
chatId,
"Premium Subscription",
"Unlock premium content with a subscription.",
"premium_subscription",
process.env.PROVIDER_TOKEN,
"subscription",
"USD",
[{ label: "Subscription", amount: 1000 }],
);
console.log(JSON.stringify(invoiceRes, null, 2));
}
res.status(200).end();
});
async function sendInvoice(
chatId,
title,
description,
payload,
providerToken,
startParameter,
currency,
prices,
) {
const apiUrl = `https://api.telegram.org/bot${botToken}/sendInvoice`;
const invoice = {
chat_id: chatId,
title: title,
description: description,
payload: payload,
provider_token: providerToken,
start_parameter: startParameter,
currency: currency,
prices: prices,
};
try {
const response = await fetch(apiUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(invoice),
});
const data = await response.json();
// console.log(data);
return data;
} catch (error) {
console.error("There was a problem sending the invoice:", error);
return error.message;
}
}
```
I googled a lot to find some answers, there isnt anything specified in the [payment section of the docs](https://core.telegram.org/bots/payments) either rather than getting the provider token (not anything specifically if i have to do on the stripe account dashboard like adding a webhook endpoint, even if that was the case how would telegram know that is the webhook it should communicate too)
I have been mentioning webhook a lot, because in my mind i am assuming that is my missing solution. if it isnt i'm sorry for doing so. I don't have much experience with stripe or building a telegram bot.
I hope i could get some help with this problem. even a small guidance will be enough if you are busy. just something i can go with that's all i ask. |
Stripe Pre-Checkout Timeout Error while making a Test Payment from Telegram Bot |
Since `mod_dav_svn.so` and `mod_authz_svn.so` were not present in SVN (TortoiseSVN), I downloaded the files from https://github.com/nono303/win-svn/tree/master/vc15/x64 and moved them to `C:\Apache24\modules`.
I then added the following lines to the `httpd.conf` file in Apache24:
```
# Subversion Configuration
LoadModule dav_svn_module modules/mod_dav_svn.so
LoadModule authz_svn_module modules/mod_authz_svn.so
```
However, upon doing so, the service failed to start. Subsequently, the following error occurred:
```
httpd.exe: Syntax error on line 188 of C:/Apache24/conf/httpd.conf: Cannot load modules/mod_dav_svn.so into server: \x8ew\x92\xe8\x82\xb3\x82\xea\x82\xbd\x83\x82\x83W\x83\x85\x81[\x83\x8b\x82\xaa\x8c\xa9\x82\xc2\x82\xa9\x82\xe8\x82\xdc\x82\xb9\x82\xf1\x81
```
I am using Windows 11 with x64 architecture.
These comments are enabled:
```
LoadModule dav_module modules/mod_dav.so
LoadModule dav_fs_module modules/mod_dav_fs.so
``` |
I'm having a huge problem.
I have a struct
```c++
struct Particle {
int x = -1;
int y = -1;
int type = -1;
int number = -1;
bool operator==(Particle p) {
if (this->x == p.x && this->y == p.y && this->type == p.type
&& this->number == p.number) { return true; }
else { return false; }
}
};
```
and an array of vectors of them `std::vector<Particle> energies[5];` on which I call the method `std::erase(energies[neighbor.type], neighbor);`
The problem I have is that compiling using `g++ crystal.cpp -std=g++23 -o crystal $(root-config --cflags --glibs)` (the latter part is for the CERN ROOT library which I need in my program) gives me the compiler error
```
$: g++ crystal.cpp -std=c++23 -o crystal `root-config --cflags --glibs`
crystal.cpp: In lambda function:
crystal.cpp:94:22: error: βeraseβ is not a member of βstdβ
std::erase(energies[neighbor.type], neighbor);
```
and I have no clue why that is.
Running `g++ --version` says I have 13.2.1 and that function should have been added in version 9 according to this table https://en.cppreference.com/w/Template:cpp/compiler_support/20. The error I get is the same if I substitute g++ with clang++.
Running the mock code
```c++
#include <vector>
#include <iostream>
struct Particle {
int x = -1;
int y = -1;
bool operator==(Particle p) {
if (this->x == p.x && this->y == p.y) { return true; }
else { return false; }
}
};
int main() {
std::vector<Particle> v = {{1, 0}, {0, 1}, {1, 1}};
Particle to_erase = {1, 0};
std::erase(v, to_erase);
for (auto &entry : v) {
std::cout << entry.x << ' ' << entry.y << std::endl;
}
std::cout << std::endl;
}
```
in an online compiler https://www.onlinegdb.com/ compiles and works as expected.
I have absolutely no idea why this case of "doesn't work on my machine" has struck me, but I couldn't find any issues akin to mine online.
Please help, I'm desperate.
EDIT: adding minimal non-working example
```c++
#include <fstream>
#include <iostream>
#include <functional>
#include "TApplication.h"
#include "TRandom3.h"
#include "TGraph.h"
#include "TSystem.h"
#include "TPad.h"
#include "TCanvas.h"
//#include <unistd.h>
#include <vector>
#include <stdio.h>
struct Particle {
int x = -1;
int y = -1;
int type = -1;
int number = -1;
bool operator==(Particle const&) const = default;
};
int main() {
TApplication app("app", 0, 0);
TRandom3 rng;
rng.SetSeed(12345);
int mat_size = 50;
int max_particles = 10;
Particle empty_site = {-1, -1, -1, -1};
std::vector<std::vector<Particle>> positions;
for (auto &vector : positions) {
std::fill(std::begin(vector), std::end(vector), empty_site);
}
std::vector<Particle> energies[5];
// manual memory allocation
for (auto &vector : energies) {
vector.reserve(max_particles);
}
// Periodic Boundary Conditions
auto Index = [&mat_size](int i) -> int {
return ((i % mat_size) + mat_size) % mat_size;
};
auto MoveIn = [&positions, &energies, &Index, &empty_site] (int x, int y, int number) -> void {
Particle neighbors[4] = {positions[Index(y+1)][x], positions[y][Index(x-1)], positions[Index(y-1)][x], positions[y][Index(x+1)]};
int num_neighbors = 0;
for (auto &neighbor : neighbors) {
if (neighbor.type != empty_site.type) {
// calculate number of neighbors for that site
num_neighbors++;
// update neighbor at energy with new energy
std::erase(energies[neighbor.type], neighbor);
neighbor.type++;
energies[neighbor.type].push_back(neighbor);
// update neighbor at position with new energy
positions.at(neighbor.y).at(neighbor.x) = neighbor;
}
}
// insert particle in site
Particle deposited = {x, y, num_neighbors, number};
// update positions and energies with the corrected particles
positions.at(y).at(x) = deposited;
energies[deposited.type].push_back(deposited);
};
app.Run(true);
return 0;
}
``` |
The hitbox positions are wrong i think
```haxe
final hitboxBlasterRatio:Int = blaster.width * 0.5; //adjust
final hitboxRatio:Int = soul.width * 0.5;
final bCornerUp:FlxPoint = FlxPoint.weak(blaster.x + blaster.width / 2 - hitboxBlasterRatio / 2, blaster.y + blaster.height / 2 - hitboxBlasterRatio / 2);
final bCornerDown:FlxPoint = hitboxBlasterRatio + blaster.width / 2 + hitboxRatio / 2, blaster.y + blaster.height / 2 + hitboxBlasterRatio / 2);
final sCornerUp:FlxPoint = FlxPoint.weak(soul.x + soul.width / 2 - hitboxRatio / 2, soul.y + soul.height / 2 - hitboxRatio / 2);
final sCornerDown:FlxPoint = FlxPoint.weak(soul.x + soul.width / 2 + hitboxRatio / 2, soul.y + soul.height / 2 + hitboxRatio / 2);
final hitboxBlaster:FlxRect = new FlxRect.fromTwoPoints(bCornerUp, bCorderDown);
final hitboxSoul:FlxRect = new FlxRect.fromTwoPoints(sCornerUp, sCorderDown);
hitbox.getRotatedBounds(blaster.angle, blaster.getMidpoint(), hitboxBlaster);
```
try with that |
|python|state-pattern| |
s = ("If Iβm not in a hurry, then I should stay. " +
"On the other hand, if I leave, then I can sleep.")
re.findall(r'[Ii]f (.*), then', s)
The output is:
Iβm not in a hurry, then I should stay. On the other hand, if I leave
The question is: Why aren't the words "If" and "then" not included in the output?
Something like this:
If Iβm not in a hurry, then I should stay. On the other hand, if I leave, then |
Python and regex, can't understand why some words are left out of the match |
|python|regex| |
I am building a registration. I built the page and here is a sample code block from that:
class RegistrationPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Color(0xFFB0C4DE),
body: SafeArea(
child: SingleChildScrollView(
padding: EdgeInsets.all(16.0),
child: Column(
children: [
SizedBox(height: 32.0),
RegistrationField(
label: 'Email',
placeholder: 'Enter Email',
isPassword: false,
),
RegistrationField(
label: 'Password *',
placeholder: 'Enter Password',
isPassword: true,
),
RegistrationField(
label: 'Re-enter Password *',
placeholder: 'Re-enter Password',
isPassword: true,
),
SizedBox(height: 32.0),
and another button and text down the line. It looks cut off at the bottom despite having more space to the bottom of the page.
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/FuxJB.png
How can I make the fields use the full page height? As you see in the picture, the button is not visible and therefore not clickable. I can't scroll down (I don't have a mouse just a mouse pad) and on a real build, I don't want it to look like this, I want it to fit the screen.
How can I somehow make all these elements fit and disable any kind of overflow to the bottom like in the picture?
Is there a way to set rule for auto-sizin so that it automatically fits the screen?
If this is not possible, how do I make it scrollable? |
I have a data structure on Qdrant that in the payload, I have something like this:
```
{
"attributes": [
{
"attribute_value_id": 22003,
"id": 1252,
"key": "Environment",
"value": "Casual/Daily",
},
{
"attribute_value_id": 98763,
"id": 1254,
"key": "Color",
"value": "Multicolored",
},
{
"attribute_value_id": 22040,
"id": 1255,
"key": "Material",
"value": "Polyester",
},
],
"brand": {
"id": 114326,
"logo": None,
"slug": "happiness-istanbul-114326",
"title": "Happiness Istanbul",
},
}
```
According to [Qdrant documentations][1], I implemented filtering for brand like this:
```
filters_list = []
if param_filters:
brands = param_filters.get("brand_params")
if brands:
filter = models.FieldCondition(
key="brand.id",
match=models.MatchAny(any=[int(brand) for brand in brands]),
)
filters_list.append(filter)
search_results = qd_client.search(
query_filter=models.Filter(must=filters_list),
collection_name=f"lang{lang}_products",
query_vector=query_vector,
search_params=models.SearchParams(hnsw_ef=128, exact=False),
limit=limit,
)
```
Which so far works. But things get complicated when I try to filter on the "attributes" field. As you see, it is a list of dictionaries, containing dictionaries like:
```
{
"attribute_value_id": 22040,
"id": 1255,
"key": "Material",
"value": "Polyester",
}
```
And the `attrs` filter sent from the front-end is in this structure:
```
attrs structure: {"attr_id": [attr_value_ids], "attr_id": [att_value_ids]}
>>> example: {'1237': ['21727', '21759'], '1254': ['52776']}
```
How can I filter to see if the provided `attr_id` in the query filter params (here, it is either `1237`, or `1254`) exists in the `attributes` field and has one of the `attr_value_id`s provided in the list (e.g. `['21727', '21759']` here)?
This is what I've tried so far:
```
if attrs:
# attrs structure: {"attr_id": [attr_value_ids], "attr_id": [att_value_ids]}
print("attrs from search function:", attrs)
for attr_id, attr_value_ids in attrs.items():
# Convert attribute value IDs to integers
attr_value_ids = [
int(attr_value_id) for attr_value_id in attr_value_ids
]
# Add a filter for each attribute ID and its values
filter = models.FieldCondition(
key=f"attributes.{attr_id}.attr_value_id",
match=models.MatchAny(any=attr_value_ids),
)
filters_list.append(filter)
```
The problem is that `key=f"attributes.{attr_id}.attr_value_id",` is wrong and I do not know how to achieve this.
UPDATE: Maybe one step close:
I decided to flatten out the data in the db, to maybe do this better. First, I created a new filed named flattened_attributes, that is as below:
```
[
{
"1237": 21720
},
{
"1254": 52791
},
{
"1255": 22044
},
]
```
Also, before filtering, I followed the same approach on the attr filters sent from front-end:
```
if attrs:
# attrs structure: {"attr_id": [attr_value_ids], "attr_id": [att_value_ids]}
# we need to flatten attrs to filter on payloads
flattened_attr = []
for attr_id, attr_value_ids in attrs.items():
for attr_value_id in attr_value_ids:
flattened_attr.append({attr_id:int(attr_value_id)})
```
Now, i have two similar list of dicts, and i want to filter those who has at leas one of which is received from front-end (`flattened_attr`).
There is one type of filtering that we filter if the value of the key exists in a list of values, as mentioned [here in the docs][2]. But I do not know how to check if a dict exists in the `flattened_attributes` field in the db.
[1]: https://qdrant.tech/documentation/concepts/filtering/
[2]: https://qdrant.tech/documentation/concepts/filtering/#match-any |
The results of `scipy.stats.shapiro` are unlikely to be incorrect here; as mentioned in the comments, the p-value is consistent with that produced by R's `shapiro.test`.
```R
options(digits=16)
x = seq(2, 43)
shapiro.test(x)
# W = 0.95605246967015, p-value = 0.1065549026935
```
Compared to other normality tests, the Shapiro-Wilk test has good power with respect to *most* alternatives; however, it seems like you've found a case in which its power is not great. You have many other options:
```python3
import numpy as np
from scipy import stats
a = np.arange(2, 44, 1)
print(stats.normaltest(a)) # NormaltestResult(statistic=10.128923354263879, pvalue=0.006317310740453355)
print(stats.kurtosistest(a)) # KurtosistestResult(statistic=-3.0094922587552966, pvalue=0.0026168474735435423)
print(stats.jarque_bera(a)) # SignificanceResult(statistic=2.5257207700096096, pvalue=0.2828438260708052)
print(stats.skewtest(a)) # SkewtestResult(statistic=1.0353162312819313, pvalue=0.30052125208274305)
```
All of them except `skewtest` detect the departure from normality with a sufficiently large sample.
```python3
a = np.arange(2, 44, 0.25)
print(stats.shapiro(a)) # ShapiroResult(statistic=0.9546093344688416, pvalue=2.9430553695419803e-05)
print(stats.normaltest(a)) # NormaltestResult(statistic=73.03250642958905, pvalue=1.3841805073962513e-16)
print(stats.kurtosistest(a)) # KurtosistestResult(statistic=-8.485467131605999, pvalue=2.1485385463319168e-17)
print(stats.jarque_bera(a)) # SignificanceResult(statistic=10.08142867266492, pvalue=0.006469125535965709)
print(stats.skewtest(a)) # SkewtestResult(statistic=1.014570839332235, pvalue=0.31031044559967047)
```
and the failure of `skewtest` is understandable, since it only attempts to detect whether the skewness is nonzero (and for your sample, it is not). |
`LIBRARY_PATH` is used by linker (ld)
`LD_LIBRARY_PATH` is used by loader (ld.so) |
You can do :
xl info | grep "total_memory"
which gives you your host memory in KB. |
> My expectation would be that creating the instance `Base` with the specified type `str` it is used for `V` which should be compatible in the `test()` return value as it converts to `Test[str](t)`
Your `b = Base[str]()` line has no retroactive effect on the definition of `class Base(Generic[V]):` whatsoever - the definition of `Base.test` simply fails the type check because `t` is `str` (via `t = '1'`), and so what's being returned is `Test[str]` and not a generic `Test[V]` - it's not a way to return "mix" types (see the [`typing.AnyStr`](https://docs.python.org/3/library/typing.html#typing.AnyStr) as an example and the documentation there has a discussion on this). Changing that assignment to `t = 1` and to `b = Base[int]()`, mypy will complain about the opposite:
```lang-text
error: Argument 1 to "Test" has incompatible type "int"; expected "str" [arg-type]
```
Using `pyright` actually gives a somewhat better error message:
```lang-text
/tmp/so_78174062.py:16:24 - error: Argument of type "Literal['1']"
cannot be assigned to parameter "a" of type "V@Base" in function "__init__"
Β Β Type "Literal['1']" cannot be assigned to type "V@Base" (reportArgumentType)
```
Which clearly highlights that these are two distinct types (one being a `str` and the other being a [`TypeVar` (type variable)](https://docs.python.org/3/library/typing.html#typing.TypeVar)").
Moreover, using the syntax introduced in [PEP 695](https://peps.python.org/pep-0695/) may in fact clear up some confusion (refer to the PEP for details); reformatting your example code in that syntax may help make clear what the intent actually is:
```python
@dataclass
class Test[V: (str, int)]:
a: V
class Base[V: (str, int)]:
def test(self) -> Test[V: (str, int)]:
t = 1
return Test[V: (str, int)](t)
# or alternatively
def test2(self) -> Test[V]:
t = 1
return Test[V](t)
```
It's a bit more clear that defining a return type `Test[V: (str, int)]` under this paradigm is not sensible, as the return type isn't one of the constrained types (so either `int` or `str`, and not whatever that `V: ...` tries to do). Not to mention that without the `class` prefixing `Test` pyright interpreted the subsequent `Test[V: (str, int)]` as a `slice` operation which is also nonsensical in that context. As for `test2`, the `V` is not bound to a concrete type at that context - the `V` in the `class` definition only serves as a placeholder for some concrete type that is defined to be either `int` or `str` which must be defined at the function return type context, so again, invalid.
Based on the given code in the question, the `test` method really should have this signature:
```lang-python
def test(self) -> Test[str]:
t = '1'
return Test[str](t)
```
The above would type check correctly.
|
The error states there KeyError: "['1'] not found in axis", meaning that you don't refer to the right column or '1' doesn't even exist in the dataframe.
To see columns in your dataframe, you can check with
df.columns
or
print(df.columns)
To delete (or drop i might say) column you can do like following
df.drop(['column_name1', 'column_name2'], axis=1, inplace=True)
* your to be dropped column 'column_name' stored in the list which you can drop more than 1 column
* axis=1 means that you want to drop column axis (axis=0 dropping the
row axis by index), and
* inplace=True means that the changes is
automatically applied to the dataframe without assigning it to
variable. |
Well the issue was on the `Output Directory`, the default directory was set to `dist` but my build was `dist/client/`. All I needed to do was to edit the vercel output directory to match the `dist/client/` path. |
IIUC use:
b = housing_labels['median_house_value'].to_numpy()
out = np.median(b[idx], axis=1)
print (out) |
1. Add the [Plugin.Maui.Audio](https://www.nuget.org/packages/Plugin.Maui.Audio/) Nuget Package
````
<PackageReference Include="Plugin.Maui.Audio" Version="2.1.0" />
````
2. Add the following line to the `MauiProgram.cs`
````
builder.Services.AddSingleton(AudioManager.Current);
````
3. Add the sound file under the `Resource/Raw` folder (mp3, wav, ..)
[![enter image description here][1]][1]
4. Set the `Copy to Output Directory` to `Copy if newer` for the sound files
[![enter image description here][2]][2]
[1]: https://i.stack.imgur.com/gh78v.png
[2]: https://i.stack.imgur.com/zErJq.png
5. Play the sound like this
````
public static class SoundExtensions
{
public static void PlaySound(this IAudioManager audioManager)
{
Stream track = FileSystem.OpenAppPackageFileAsync("YourSoundFileName").Result;
IAudioPlayer player = _audioManager.CreatePlayer(track);
player.Play();
}
}
````
and you can inject `IAudioManager` and use it.
<hr/>
**Notes**
1. The package is maintained by a Microsoft Engineer
2. Here is a [YouTube video](https://www.youtube.com/watch?v=oIYnEuZ9oew) that explains it |
I want to use the Flutter Custom Clipper to create a shape like the picture below, but it doesn't work. Is there anyone who can help?
[![enter image description here][1]][1]
```dart
class MyCustomClipper extends CustomClipper<Path> {
@override
Path getClip(Size size) {
List<Offset> polygon = [
Offset(0, 10),
Offset(size.width - 30, 10),
Offset(size.width - 25, 0),
Offset(size.width - 20, 10),
Offset(size.width, 10),
Offset(size.width, size.height),
Offset(0, size.height),
Offset(0, 10),
];
Path path = Path()
..addPolygon(polygon, false)
..close();
return path;
}
@override
bool shouldReclip(CustomClipper<Path> oldClipper) {
return true;
}
}
```
[Svg code]
<svg width="132" height="110" viewBox="0 0 132 110" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M111.858 1.73511L111.434 1.05619L111.01 1.73512L107.096 8H5.997C2.96081 8 0.5 10.4627 0.5 13.5V103.5C0.5 106.537 2.96081 109 5.997 109H125.925C128.961 109 131.422 106.537 131.422 103.5V13.5C131.422 10.4627 128.961 8 125.925 8H115.771L111.858 1.73511Z" fill="white" stroke="#EAECEE"/>
</svg>
Actually, I used this path through polygon, but I couldn't give it a border, so I guess I don't know much.
[1]: https://i.stack.imgur.com/YXJ78.png |
|python|widget|jupyter|ipywidgets|pandas-profiling| |
You can capture initial zeros and 3 alhpanumeric chars right after them in one group, the middle part into a second group, and then the last 4 alphanumeric chars into a third group, then only replace each char in the second group.
Here is an example (Java 11 compliant):
```java
String text = "0001113033AA55608981";
Matcher mr = Pattern.compile("^(0*\\w{3})(.*)(\\w{4})$").matcher(text);
text = mr.replaceFirst(m -> m.group(1) + "*".repeat(m.group(2).length()) + m.group(3));
System.out.println(text); // => 000111**********8981
```
See the [Java demo][1].
The regex matches
- `^` - start of string
- `(0*\w{3})` - Group 1: zero or more `0` chars and then any three alphnumeric/underscore chars
- `(.*)` - Group 2: any zero or more chars other than line break chars (replace with `\w*` if you only allow "word" chars)
- `(\w{4})` - Group 3: four "word" chars
- `$` - end of string.
[1]: https://ideone.com/gTjIiN |
More in detail:
I would like to choose one specific column based on a header value from snakemake rule input file and then select this specific column's first value. I was considering something like this: (df['colname'].iloc[0]) but now I am getting confused when {input} comes also into a play. So instead of a 'df' mention above should be {input}. Perhaps there is a better alternative to python .iloc? Thank you in advance for any advice. |
How to apply python iloc on snakemake input file? |
|python|pandas|function|indexing|snakemake| |
null |
this one worked for me
auth('sanctum')->user()->tokens()->delete(); |
As **backend developers**, we often encounter theoretical concepts during our education or self-study, such as transactions in MongoDB or the principles of ACID (Atomicity, Consistency, Isolation, Durability). However, in practical scenarios within organizations, do we find ourselves actually implementing these concepts?
Share your experiences, insights, and best practices regarding integrating theoretical knowledge into real-world applications. How do you approach incorporating concepts like transactions in MongoDB into your development workflow? Have you encountered specific challenges or benefits in doing so? Let's discuss the relevance and application of these theoretical concepts in our day-to-day backend development work. |
Do Backend Developers Truly Apply Theoretical Concepts like Transactions in MongoDB and ACID Principle in Real-world Applications? |
.NET (and consequently PowerShell) distinguishes between value types and reference types - value types are data types whose values are _copied_ on reference, whereas reference types are data types whose values are _passed by reference_.
This means that "an array of hashtables" is not actually that - it's an array of _references_ to hashtable(s).
When you do: `@($something) * 3`, PowerShell creates and concatenates 3 copies of the `@(...)` array literal. If `$something` is of a reference type (like `[hashtable]` is), then the resulting array contains 3 copies of _a reference_ to whatever `$something` references - which is exactly why changes to the hashtable referenced at 1 index of the array is reflected in the two other array references - because they're _the same object_.
Use a loop (or the `ForEach-Object` cmdlet) to create 3 distinct hashtables instead of using `@(...) * 3`:
$array = @(1..3|%{@{Status = $_}}) |
Make UI fit the screen in dart on mobile view |
|flutter|dart|android-studio|mobile| |
{"OriginalQuestionIds":[65833341],"Voters":[{"Id":14868997,"DisplayName":"Charlieface","BindingReason":{"GoldTagBadge":"c#"}}]} |
I have a C cli program that I compiled to was with Emscripten. I'm trying to run that program each time a button is pressed, and read from a textbox into stdin and from stdout to another textbox. However, I can only call `Module.callMain()` successfully once. Each subsequent invocation does not execute. How to properly setup this?
Here is the HTML code.
```html
<!doctype html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>title</title>
</head>
<body>
<textarea id="input" rows="8"></textarea>
<button onclick="exec()">run</button>
<textarea id="output" rows="8"></textarea>
<script>
var input_box = document.getElementById('input');
var input_text = "";
let i = 0;
var Module = {
noInitialRun: true,
noExitRuntime: true,
print: (function() {
var element = document.getElementById('output');
if (element) element.value = ''; // clear browser cache
return (...args) => {
var text = args.join(' ');
console.log(text);
if (element) {
element.value += text + "\n";
element.scrollTop = element.scrollHeight; // focus on bottom
}
};
})(),
stdin: (function() {
return () => {
if(i >= input_text.length) {
return null;
} else {
return input_text.charCodeAt(i++);
}
};
})(),
};
function exec() {
console.log(i);
i = 0;
input_text = input_box.value;
console.log(input_text);
Module.callMain([]);
}
</script>
<script async type="text/javascript" src="main.js"></script>
</body>
</html>
```
The .js file is the one output from emscripten without modifications.
Here are the flags used to compile:
```
-s 'EXIT_RUNTIME=0' -s EXPORTED_RUNTIME_METHODS='[\"callMain\",\"run\"]' -s ENVIRONMENT=web
``` |
As others mentioned before, in 2 steps:
1. Dex2jar
2. Pick up a decompiler
I will focus on step 2.
Take a look at this research paper : [The Strengths and Behavioral Quirks of Java Bytecode Decompilers][1]
Understand the strength and weaknesses of each decompiler.
1. [CFR][2]: Considered by many as the absolute best decompiler, its specificity is that it takes a lot a liberty in graph transformations to maximise the chance of good results, at the expense of original code ordering, and has a lot of technical settings. The last version has a line number mapping but no line number realignment.
2. [Procyon][3]: This one has the best chances to produce well structured code, adds final keywords everywhere it can, but often adds unexpected illegal casts. It has also a GUI project [Luyten][4].
3. [Fernflower][5]: It's the decompiler from the popular IDE Intellij Idea. It often decompiles right but code is sometimes not ideally structured and has very bad naming of exception variables var1..n.
4. [Vineflower][6]: It's a fork of fernflower which brings improvements and bug fixes, with a test suite borrowed to CFR.
5. [JD-GUI][7]: It's the GUI of the [JD-CORE][8] project. The new version of JD-CORE structures the code into a control flow graph and an abstract syntax tree. The previous version which was present until v1.4.2 of JD-GUI was another decompiler based on bytecode pattern matching like [JAD][9]. JD-CORE is focused on producing a recompilable output on many open source projects and also on getting line number realignment right for a debug-ready output.
6. [JADX][10]: This project looks actively maintained and promising, but for the time being, the results are not very solid.
The following GUI projects support several decompilers:
- [Recaf][11]: provides support for the following decompilers: CFR Β· FernFlower Β· Procyon
- [Bytecodeviewer][12]: A Java 8+ Jar & Android APK Reverse Engineering Suite (Editor, Debugger, decompilers like CFR, JD-GUI etc.)
- [JD-GUI-DUO][13] : this project uses forks of JD-CORE projects and revives the old algorithm in project named [jd-core-v0][14] and brings improvements and bug fixes in a fork of [jd-core v1][15]. Also supports CFR, Procyon, Vineflower & JADX.
Also Eclipse plugins are worth mentioning:
- [ECD][16] and this [fork][17]
- [JD-Eclipse][18] and this [fork][19]
[1]: https://www.researchgate.net/profile/Cesar_Soto-Valero/publication/334465294_The_Strengths_and_Behavioral_Quirks_of_Java_Bytecode_Decompilers/links/
[2]: https://github.com/leibnitz27/cfr
[3]: https://github.com/mstrobel/procyon
[4]: https://github.com/deathmarine/Luyten
[5]: https://github.com/JetBrains/intellij-community/tree/master/plugins/java-decompiler/engine
[6]: https://github.com/Vineflower/vineflower
[7]: https://github.com/java-decompiler/jd-gui
[8]: https://github.com/java-decompiler/jd-core
[9]: http://www.kpdus.com/jad.html
[10]: https://github.com/skylot/jadx
[11]: https://github.com/Col-E/Recaf
[12]: https://github.com/Konloch/bytecode-viewer
[13]: https://github.com/nbauma109/jd-gui-duo
[14]: https://github.com/nbauma109/jd-core-v0
[15]: https://github.com/nbauma109/jd-core
[16]: https://github.com/ecd-plugin/ecd
[17]: https://github.com/nbauma109/ecd
[18]: https://github.com/java-decompiler/jd-eclipse
[19]: https://github.com/nbauma109/jd-eclipse |
i need to set up text to bar using BarGraphItem with pyqtgraph
I need something like this:
[enter image description here](https://i.stack.imgur.com/pOMlM.png)
or set the names in the middle.
there was an idea to set TextItem by coordinates,
but after writing it, it turned out that with a large number of such elements, they begin to slow down.
|
The problem I found that I cannot make Postgres use GIN index when I use **jsonb_*** functions in my queries.
The problem exists for both **jsonb_ops** and **jsonb_path_ops** operator classes.
Let's first make preparations.
Create the table
```lang-sql
CREATE TABLE applications
(
id TEXT PRIMARY KEY,
application JSONB
);
CREATE INDEX ON applications USING gin (application jsonb_path_ops);
```
Let's fill the table with some bulk of data (to make Postgres use GIN index)
```lang-sql
INSERT INTO applications(id, application)
VALUES ('1', '{
"type_code": 1,
"persons": [
{
"type_code": 4,
"firstname": "John",
"lastname": "Doe"
}
]
}');
INSERT INTO applications (SELECT i, a.application FROM applications a, generate_series(2, 100000) i);
```
Then I try to select the data like the following:
```lang-sql
EXPLAIN ANALYZE
SELECT * FROM applications
WHERE applications.application @? '$.persons[*] ? (@.type_code == 3)';
```
Note that GIN index was used
```lang-sql
-- Bitmap Heap Scan on applications (cost=64.00..68.01 rows=1 width=130) (actual time=0.410..0.419 rows=0 loops=1)
-- " Recheck Cond: (application @? '$.""persons""[*]?(@.""type_code"" == 3)'::jsonpath)"
-- -> Bitmap Index Scan on applications_application_idx (cost=0.00..64.00 rows=1 width=0) (actual time=0.095..0.096 rows=0 loops=1)
-- " Index Cond: (application @? '$.""persons""[*]?(@.""type_code"" == 3)'::jsonpath)"
-- Planning Time: 1.493 ms
-- Execution Time: 0.861 ms
```
Now I try to select the data like this:
```lang-sql
EXPLAIN ANALYZE
SELECT * FROM applications
WHERE jsonb_path_exists(
applications.application,
'$.persons[*] ? (@.type_code == 3)'
);
```
You can see that GIN index was not used in this case:
```lang-sql
-- Aggregate (cost=3374.33..3374.34 rows=1 width=8) (actual time=114.048..114.055 rows=1 loops=1)
-- -> Seq Scan on applications (cost=0.00..3291.00 rows=33333 width=0) (actual time=0.388..109.580 rows=100000 loops=1)
-- " Filter: jsonb_path_exists(application, '$.""persons""[*]?(@.""type_code"" == 3)'::jsonpath, '{}'::jsonb, false)"
-- Planning Time: 1.514 ms
-- Execution Time: 114.674 ms
```
Is it possible to make Postgres use GIN index in the second query?
Using jsonb_* functions is preferred for me because I can use positional parameters to build query:
```lang-sql
SELECT * FROM applications
WHERE jsonb_path_exists(
applications.application,
'$.persons[*] ? (@.type_code == $person_type_code)',
jsonb_build_object('person_type_code', $1)
);
``` |
How to make Postgres GIN index work with jsonb_* functions? |
|postgresql|indexing|jsonb| |
null |
Here is some interesting information from the official documentation regarding hosts : https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_vars_facts.html#information-about-ansible-magic-variables
I recommend using the inventory_hostname as you define it yourself.
Since you also define the address in the inventory, you can set that in the hostfile. Given an inventory snippet:
---
mariadb-servers:
hosts:
mariadb1.example.com:
ansible_host: 1.2.3.4 # IP for the hostname, external or internal
ansible_user: ubuntu
vars:
mariadb_target_group: mariadb-servers
Then as a pre_task you can have something like:
- name: Build hosts file
ansible.builtin.lineinfile:
path: /etc/hosts
regexp: '.*{{ item }}$'
line: "{{ hostvars[item].ansible_host }} {{ item }}"
state: present
mode: "0644"
when: hostvars[item].ansible_host is defined
loop: "{{ groups[mariadb_target_group] }}"
That way the name of the server is consistent and it will also resolve to what you set without the need for DNS ( which you may or may not want ).
The other suggestion for setting up the hostname properly to be the FQDN can be done on top of this if needed.
Various tools use various ways to get the hostname, so it is best to be consistent from setup of the host.
With the fqdn set properly on Linux, you will also have consistent output for ansible_fqdn.
|
My original post - https://stackoverflow.com/a/57224037/1979465
To call a stored procedure and get the result into a list of model in EF Core, we have to follow 3 steps.
**Step 1.**
You need to add a new class just like your entity class. Which should have properties with all the columns in your SP. For example if your SP is returning two columns called `Id` and `Name` then your new class should be something like
public class MySPModel
{
public int Id {get; set;}
public string Name {get; set;}
}
**Step 2.**
Then you have to add one `DbQuery` property into your DBContext class for your SP.
public partial class Sonar_Health_AppointmentsContext : DbContext
{
public virtual DbSet<Booking> Booking { get; set; } // your existing DbSets
...
public virtual DbQuery<MySPModel> MySP { get; set; } // your new DbQuery
...
}
**Step 3.**
Now you will be able to call and get the result from your SP from your DBContext.
var result = await _context.Query<MySPModel>()
.AsNoTracking()
.FromSql(string.Format("EXEC {0} {1}", functionName, parameter))
.ToListAsync();
I am using a generic UnitOfWork & Repository. So my function to execute the SP is
/// <summary>
/// Execute function. Be extra care when using this function as there is a risk for SQL injection
/// </summary>
public async Task<IEnumerable<T>> ExecuteFuntion<T>(string functionName, string parameter) where T : class
{
return await _context.Query<T>()
.AsNoTracking()
.FromSql(string.Format("EXEC {0} {1}", functionName, parameter)).ToListAsync();
}
Hope it will be helpful for someone !!! |
Sometimes after adding new columns to a table we face with problem of strange aliases in projection columns: new columns have aliases of old columns names. Columns were added like `alter table DMA.test_migrations add column my_column int`
Example of DDL:
```
CREATE TABLE DMA.test_migrations
(
launch_id int NOT NULL,
datamart varchar(128),
actual_date date,
time_sla interval,
kek int,
lol int,
lolkek int,
my_column int,
my_column2 int,
my_column3 int,
my_column4 int,
my_column5 int,
my_column6 int,
my_column7 int
);
CREATE PROJECTION DMA.test_migrations_super /*+basename(test_migrations),createtype(P)*/
(
launch_id,
datamart,
actual_date,
time_sla,
kek,
lol,
lolkek,
my_column,
my_column2,
my_column3,
my_column4,
my_column5,
my_column6,
my_column7
)
AS
SELECT test_migrations.launch_id,
test_migrations.datamart,
test_migrations.actual_date,
test_migrations.time_sla,
test_migrations.kek,
test_migrations.lol,
test_migrations.lolkek,
test_migrations.my_column AS launch_id,
test_migrations.my_column2 AS datamart,
test_migrations.my_column3 AS actual_date,
test_migrations.my_column4 AS time_sla,
test_migrations.my_column5 AS kek,
test_migrations.my_column6 AS lol,
test_migrations.my_column7 AS lolkek
FROM DMA.test_migrations
ORDER BY test_migrations.datamart,
test_migrations.actual_date
UNSEGMENTED ALL NODES;
SELECT MARK_DESIGN_KSAFE(1);
```
This situation leads to `DDL statement interfered with this statement` error while `select analyze_histogram('DMA.test_migrations')`
Does anyone face with such a problem?
We did't succeed in finding hypoteses of such behaviour.
The complete sequence of actions that led to the problem:
```
create table if not exists dma.test_migrations
(
launch_id int not null,
datamart varchar(128),
actual_date date,
time_sla interval
)
order by datamart, actual_date
unsegmented all nodes;
ALTER TABLE dma.test_migrations ADD COLUMN kek int ;
ALTER TABLE dma.test_migrations ADD COLUMN lol int ;
alter table dma.test_migrations drop column lol;
ALTER TABLE dma.test_migrations ADD COLUMN lol int ;
ALTER TABLE dma.test_migrations ADD COLUMN lolkek int ;
ALTER TABLE dma.test_migrations ADD COLUMN my_column int ;
ALTER TABLE dma.test_migrations ADD COLUMN my_column2 int ;
ALTER TABLE dma.test_migrations ADD COLUMN my_column3 int ;
ALTER TABLE dma.test_migrations ADD COLUMN my_column4 int ;
ALTER TABLE dma.test_migrations ADD COLUMN my_column5 int ;
ALTER TABLE dma.test_migrations ADD COLUMN my_column6 int ;
ALTER TABLE dma.test_migrations ADD COLUMN my_column7 int ;
``` |
`#{}` is a placeholder in prepared statement, so you cannot use it in a literal.
Although it is technically possible to generate such literal using `${}` instead of `#{}`, it is not recommended because it is difficult to prevent SQL injection that way (see this [FAQ](https://github.com/mybatis/mybatis-3/wiki/FAQ#what-is-the-difference-between--and-) entry).
I'll show you three alternative solutions.
1. Join the string list and use `STRING_TO_ARRAY` on the right side
2. Use `ARRAY[...]::TEXT[]` syntax
3. Use a custom type handler
---
## 1\. Join the string list and use `STRING_TO_ARRAY` on the right side
There maybe a few options for how to use the joined `phenoms`.
One way is to add a new method to the `WhetherObj`.
```java
public String getPhenomsStr() {
return String.join(",", phenoms);
}
```
Then the `WHERE` clause in the mapper would look like this.
```sql
WHERE
string_to_array(weather.custom_phenoms, ',') &&
string_to_array(#{phenomsStr} ',')
```
---
## 2\. Use `ARRAY[...]::TEXT[]` syntax
The idea is similar to your original solution.
```xml
WHERE
string_to_array(weather.custom_phenoms, ',') &&
<foreach item="phenom" collection="phenoms"
open="ARRAY[" separator="," close="]::TEXT[]">
#{phenom}
</foreach>
```
---
## 3\. Use a custom type handler
You can write a custom type handler that calls `java.sql.PreparedStatement#setArray()`.
```java
import java.sql.Array;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
public class StringListTypeHandler extends BaseTypeHandler<List<String>> {
@Override
public void setNonNullParameter(PreparedStatement ps, int i, List<String> parameter, JdbcType jdbcType)
throws SQLException {
Array array = ps.getConnection().createArrayOf("TEXT", parameter.toArray());
ps.setArray(i, array);
array.free();
}
// ...
}
```
Note: complete implementation of this type handler is in this executable [demo](https://github.com/harawata/mybatis-issues/tree/master/so-64930633).
Then, you can specify the type handler in the parameter reference.
```sql
WHERE
string_to_array(weather.custom_phenoms, ',') &&
#{phenoms,typeHandler=my.pkg.StringListTypeHandler}
```
|
You can work with [**`replicateM :: Int -> m a -> m [a]`**](https://hackage.haskell.org/package/base-4.19.1.0/docs/Control-Monad.html#v:replicateM):
import Control.Monad(replicateM)
generate :: Int -> [[Int]]
generate = replicateM <*> enumFromTo 1
The `replicateM` essentially works as:
<pre><code>(\x<sub>1</sub> x<sub>2</sub> … x<sub>n</sub> -> [x<sub>1</sub>, x<sub>2</sub>, …, x<sub>n</sub>]) <$> fx <*> fx <*> … <*> fx</code></pre>
where we repeat `fx` *n* times. Here we use `[1 .. n]`, so that means we pick an element from `[1 .. n]`, then another one for `[1 .. n]` and so on, until we picked `n` elements, and then combine these. |
I am trying to download a .stl file from a URL:- `https://cdn.thingiverse.com/assets/99/39/31/f9/33/90_Degree_-_4_Segments.stl`
I have created a service for the same - **app-stl.service.ts**, which accepts the URL and returns the required file --
import { Injectable } from '@angular/core';
import { HttpHeaders, HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class ImlStlAppService {
constructor(private http: HttpClient) { }
fetchData(filename:string) {
let headers = new HttpHeaders();
headers = headers.set('Accept', 'application/STL');
return this.http.get(filename, { headers: headers, responseType: 'blob' });
}
}
Next in the app-stl.component.ts , I have the following code :-
constructimage() {
this.service.fetchData(this.filename)
.subscribe((blob : any) => {
let objectURL =URL.createObjectURL(blob);
this.stlimage = this.sanitizer.bypassSecurityTrustUrl(objectURL);
//-------------------------------------------------------------
url = URL.createObjectURL(blob),
img = new Image();
img.src=url;
//-----------------------------------------------------------------
else {
downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
downloadLink.onclick = document.body.removeChild(event.target);
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
}
downloadLink.click();
});
I am not able to make it work. Could you please suggest any changes? |
Check to see that you set your .recordSelectionFormula before you assign the report to the reportsource property of the viewer.
This Doesn't seem to Work
CrystalReportViewer1.ReportSource = reportDoc
reportDoc.RecordSelectionFormula = "{MyField} = '1008'"
CrystalReportViewer1.Show()
This woks for me.
reportDoc.RecordSelectionFormula = "{MyField} = '1008'"
CrystalReportViewer1.ReportSource = reportDoc
CrystalReportViewer1.Show()
|
# Docker Traefik Provider Example
---
## Case
For example, in case a WebDav service is behind a TLS reverse-proxy (e.g. Traefik, port `443`), and the service itself is running on non-TLS protocol (i.e. port `80`), and renaming a file (i.e. HTTP method `MOVE`) in Nginx may result in error:
```
..."MOVE /dav/test.txt HTTP/1.1" 400...
...[error] 39#39: *4 client sent invalid "Destination" header...
```
Related: [Seafdav - MOVE command causing 502](https://forum.seafile.com/t/seafdav-move-command-causing-502/11582/23).
---
## Solution
### Static (i.e. `traefik.yaml`)
```yaml
experimental:
plugins:
rewriteHeaders:
modulename: 'github.com/bitrvmpd/traefik-plugin-rewrite-headers'
version: 'v0.0.1'
```
### Dynamic
```yaml
services:
app:
image: php
volumes:
- '/var/docker/data/app/config/:/etc/nginx/conf.d/:ro'
- '/var/docker/data/app/data/:/var/www/'
networks:
reverse-proxy:
labels:
- 'traefik.enable=true'
- 'traefik.http.services.app.loadbalancer.server.port=80'
# Replace 'Destination' request header: 'https://' -> 'http://'
- 'traefik.http.middlewares.rewriteHeadersMW.plugin.traefik-plugin-rewrite-headers.rewrites.request[0].header=Destination'
- 'traefik.http.middlewares.rewriteHeadersMW.plugin.traefik-plugin-rewrite-headers.rewrites.request[0].regex=^https://(.+)$'
- 'traefik.http.middlewares.rewriteHeadersMW.plugin.traefik-plugin-rewrite-headers.rewrites.request[0].replacement=http://$1'
- 'traefik.http.routers.app.rule=Host(`sub.example.com`)'
- 'traefik.http.routers.app.entrypoints=https'
- 'traefik.http.routers.app.priority=2'
- 'traefik.http.routers.app.middlewares=rewriteHeadersMW'
networks:
reverse-proxy:
name: reverse-proxy
external: true
```
---
Non-Traefik alternative: Nginx module [`headers-more-nginx-module`](https://github.com/openresty/headers-more-nginx-module).
---
# Related
- [Traefik Plugin Page](https://plugins.traefik.io/plugins/63718c14c672f04dd500d1a0/rewrite-headers);
- [GitHub Plugin Page](https://github.com/bitrvmpd/traefik-plugin-rewrite-headers). |
No, you cannot transition a background.
The simplest solution is to use an SVG element in your HTML. This is what SVG is good at: vector graphics. You then apply styles to that element using CSS.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
.heart {
width: 200px;
aspect-ratio: 1;
transition: 1.5s;
fill: red;
}
.heart:hover {
fill: blue;
}
<!-- language: lang-html -->
<svg class="heart" viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
<path d="M 200 60 C 200 75.138 194.394 88.967 185.144 99.523 L 100 200.009 L 14.856 99.523 C 5.606 88.967 0 75.138 0 60 C 0 26.863 26.863 0 60 0 C 75.367 0 89.385 5.777 100 15.278 C 110.615 5.777 124.633 0 140 0 C 173.137 0 200 26.863 200 60 Z"/>
</svg>
<!-- end snippet -->
But if you are stuck with HTML from somewhere else and therefore want to do it all in CSS, you could achieve it using two pseudo-elements and animating the `opacity` of one of them.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
.heart {
width: 200px;
aspect-ratio: 1;
position: relative;
}
.heart::before, .heart::after {
content: '';
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: -1;
}
.heart::before {
background-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 200 200' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M 200 60 C 200 75.138 194.394 88.967 185.144 99.523 L 100 200.009 L 14.856 99.523 C 5.606 88.967 0 75.138 0 60 C 0 26.863 26.863 0 60 0 C 75.367 0 89.385 5.777 100 15.278 C 110.615 5.777 124.633 0 140 0 C 173.137 0 200 26.863 200 60 Z' style='fill: red;'/%3E%3C/svg%3E");
}
.heart::after {
background-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 200 200' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M 200 60 C 200 75.138 194.394 88.967 185.144 99.523 L 100 200.009 L 14.856 99.523 C 5.606 88.967 0 75.138 0 60 C 0 26.863 26.863 0 60 0 C 75.367 0 89.385 5.777 100 15.278 C 110.615 5.777 124.633 0 140 0 C 173.137 0 200 26.863 200 60 Z' style='fill: blue;'/%3E%3C/svg%3E");
opacity: 0;
transition: 1.5s;
}
.heart:hover::after {
opacity: 1;
}
<!-- language: lang-html -->
<div class="heart">
<button id="widget-toggle" class="widget-toggle-open drawer-toggle widget-toggle-style-default" data-toggle-target="#widget-drawer" data-toggle-body-class="showing-widget-drawer" aria-expanded="false" data-set-focus=".widget-toggle-close">
<span class="widget-toggle-label">MENU</span>
<span class="widget-toggle-icon">
</span>
</button>
</div>
<!-- end snippet -->
|
Player class with boolean settings which I want to get in another class and change
public Dictionary<string, bool>? Settings
{
get
{
Dictionary<string, bool> settings = null!;
foreach (var property in GetType().GetProperties().Where(p => p.PropertyType == typeof(bool)))
{
settings?.Add(property.Name, (bool) property.GetValue(this, null)!);
}
return settings;
}
}
p.s. f i add log to foreach then I will see the variable and its state
if this is important, then I use the latest version of the counterstrikesharp API, but the problem here is most likely not in the API
```
private void CreateMenu(CCSPlayerController? player)
{
if (player == null) return;
if (!_players.TryGetValue(player.SteamID.ToString(), out var user)) return;
var title = "RES";
user!.Menu = Config.UseCenterHtmlMenu ? new CenterHtmlMenu(title) : new ChatMenu(title);
if (user.Menu == null)
{
Console.WriteLine("user.Menu == null");
return;
}
_logUtils.Log(user.Settings?.Count.ToString()); // empty log
foreach (var (feature, state) in user.Settings!) // user.Settings empty too
{
_logUtils.Log("TEST 6");
var featureState = state switch
{
true => "[ΠΠΠ]",
false => "[ΠΠ«ΠΠ]"
};
user.Menu.AddMenuOption(
feature + ($"[{featureState}]"),
(controller, _) =>
{
var returnState = featureState;
player.PrintToChat($"{feature}: {(returnState == featureState ? "[ΠΠΠ]" : "[ΠΠ«ΠΠ]")}");
if (Config.ReOpenMenuAfterItemClick)
CreateMenu(controller);
});
}
if (Config.UseCenterHtmlMenu)
MenuManager.OpenCenterHtmlMenu(this, player, (CenterHtmlMenu)user.Menu);
else
MenuManager.OpenChatMenu(player, (ChatMenu)user.Menu);
}
```
I marked problem areas with comments
I logged and debugged, but I canβt understand what the problem is
|
Unable to get bool settings from class |
I'm having a huge problem.
I have a struct
```c++
struct Particle {
int x = -1;
int y = -1;
int type = -1;
int number = -1;
bool operator==(Particle p) {
if (this->x == p.x && this->y == p.y && this->type == p.type
&& this->number == p.number) { return true; }
else { return false; }
}
};
```
and an array of vectors of them `std::vector<Particle> energies[5];` on which I call the method `std::erase(energies[neighbor.type], neighbor);`
The problem I have is that compiling using `g++ crystal.cpp -std=c++23 -o crystal $(root-config --cflags --glibs)` (the latter part is for the CERN ROOT library which I need in my program) gives me the compiler error
```
$: g++ crystal.cpp -std=c++23 -o crystal `root-config --cflags --glibs`
crystal.cpp: In lambda function:
crystal.cpp:94:22: error: βeraseβ is not a member of βstdβ
std::erase(energies[neighbor.type], neighbor);
```
and I have no clue why that is.
Running `g++ --version` says I have 13.2.1 and that function should have been added in version 9 according to this table https://en.cppreference.com/w/Template:cpp/compiler_support/20. The error I get is the same if I substitute g++ with clang++.
Running the mock code
```c++
#include <vector>
#include <iostream>
struct Particle {
int x = -1;
int y = -1;
bool operator==(Particle p) {
if (this->x == p.x && this->y == p.y) { return true; }
else { return false; }
}
};
int main() {
std::vector<Particle> v = {{1, 0}, {0, 1}, {1, 1}};
Particle to_erase = {1, 0};
std::erase(v, to_erase);
for (auto &entry : v) {
std::cout << entry.x << ' ' << entry.y << std::endl;
}
std::cout << std::endl;
}
```
in an online compiler https://www.onlinegdb.com/ compiles and works as expected.
I have absolutely no idea why this case of "doesn't work on my machine" has struck me, but I couldn't find any issues akin to mine online.
Please help, I'm desperate.
EDIT: adding minimal non-working example
```c++
#include <fstream>
#include <iostream>
#include <functional>
#include "TApplication.h"
#include "TRandom3.h"
#include "TGraph.h"
#include "TSystem.h"
#include "TPad.h"
#include "TCanvas.h"
//#include <unistd.h>
#include <vector>
#include <stdio.h>
struct Particle {
int x = -1;
int y = -1;
int type = -1;
int number = -1;
bool operator==(Particle const&) const = default;
};
int main() {
TApplication app("app", 0, 0);
TRandom3 rng;
rng.SetSeed(12345);
int mat_size = 50;
int max_particles = 10;
Particle empty_site = {-1, -1, -1, -1};
std::vector<std::vector<Particle>> positions;
for (auto &vector : positions) {
std::fill(std::begin(vector), std::end(vector), empty_site);
}
std::vector<Particle> energies[5];
// manual memory allocation
for (auto &vector : energies) {
vector.reserve(max_particles);
}
// Periodic Boundary Conditions
auto Index = [&mat_size](int i) -> int {
return ((i % mat_size) + mat_size) % mat_size;
};
auto MoveIn = [&positions, &energies, &Index, &empty_site] (int x, int y, int number) -> void {
Particle neighbors[4] = {positions[Index(y+1)][x], positions[y][Index(x-1)], positions[Index(y-1)][x], positions[y][Index(x+1)]};
int num_neighbors = 0;
for (auto &neighbor : neighbors) {
if (neighbor.type != empty_site.type) {
// calculate number of neighbors for that site
num_neighbors++;
// update neighbor at energy with new energy
std::erase(energies[neighbor.type], neighbor);
neighbor.type++;
energies[neighbor.type].push_back(neighbor);
// update neighbor at position with new energy
positions.at(neighbor.y).at(neighbor.x) = neighbor;
}
}
// insert particle in site
Particle deposited = {x, y, num_neighbors, number};
// update positions and energies with the corrected particles
positions.at(y).at(x) = deposited;
energies[deposited.type].push_back(deposited);
};
app.Run(true);
return 0;
}
``` |
You need to call `dispose()` on the first instance first.
Then use another.
final matching = PixelMatching();
// setup target image
await matching?.initialize(image: image);
// compare image
final double? similarity = await matching?.similarity(cameraImage);
// dispose
matching?.dispose(); |
I want to generate a list given a number n which returns all possible combinations from one to `n` recursively and without imports.
For example
```
generate 3
```
should return:
```
[[1,1,1],[1,1,2],[1,1,3],[1,2,1],[1,2,2],[1,2,3],[1,3,1],[1,3,2],[1,3,3],[2,1,1],[2,1,2],[2,1,3],[2,2,1],[2,2,2],[2,2,3],[2,3,1],[2,3,2],[2,3,3],[3,1,1],[3,1,2],[3,1,3],[3,2,1],[3,2,2],[3,2,3],[3,3,1],[3,3,2],[3,3,3]]
```
Logically something like this, which obviously returns an error:
```
generate n = [replicate n _ | _ <- [1..n]]
``` |
You can create a RandomRange class, you can create as many as you want and put into a list
public class RandomRange
{
public int Start { get; set; }
public int End { get; set; }
public int Exception { get; set; }
public RandomRange(int start, int end, int exception)
{
Start = start;
End = end;
Exception = exception;
}
public int getRandomIndex()
{
Random random = new Random();
int index = random.Next(Start-1, End+1);
if (index < Start || index > End)
{
index = Exception;
}
return index;
}
}
In your main program, simply call it
static void Main(string[] args)
{
Random random = new Random();
// Define your ranges
List<RandomRange> ranges = new List<RandomRange>
{
new RandomRange(2, 10, 15), // Represents indices from 2 to 9
new RandomRange(15, 20, 25), // Represents indices from 15 to 19
new RandomRange(25, 30, 35) // Represents indices from 25 to 29
};
//i use random here in this case, but u can simply change it to a user input
RandomRange selectedRange = ranges[random.Next(ranges.Count)];
Console.WriteLine($"Selected Index: {selectedRange.getRandomIndex()}");
}
You can then use the `selectedRange.getRandomIndex()` to get your list item
Note that there is no check for index out of bound exception and i presume you already done all the list indexing exception handling
I hope the RandomRange class is easy enough |
I'm experimenting with GLFW (compiling with **g++ -o nxtBluePixel nxtBluePixel.cpp -lglfw -lGLEW -lGL** ) to simply draw a blue box and move it up/down/left/right. I want to output a message "out of bounds" when the box touches the edges of the visible area, which should logically be -1 or 1 (in those so-called normalized OpenGL coordinates, so I read). But the box keeps continuing to move in an "invisible" region outside (and is invisible) but no message is displayed until a while (at least 10 hits or so on a key outside the edge boundary ... ChatGPT 4 can't help me, it says:
*"Correct Boundary Check: If you want the "out of bounds" message to appear as soon as the point is about to leave the visible area, your original check without the large epsilon is logically correct. However, if the message appears too late or too early, it might be due to how the point's position is updated or rendered, not the boundary check itself."*
any ideas? I never use OpenGL, so I wanted to try... but this is typically the kind of very annoying problem I hate!
and here my code:
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <iostream>
#include <string>
#include <cctype>
GLint worldWidth = 400;
GLint worldHeight = 300;
// Starting position of the pixel
float currX = 0.0f;
float currY = 0.0f;
float stepSize = 1.0f / worldWidth;
float speed = 2.0f;
void updateWorld(char keyPressed, float speed){
switch (keyPressed) {
case 'W':
//up
currY += stepSize*speed;
break;
case 'A':
//left
currX -= stepSize*speed;
break;
case 'S':
//down
currY -= stepSize*speed;
break;
case 'D':
//right
currX += stepSize*speed;
break;
}
//using openGL 'normalized' coords i.e. between -1 and 1
if (currX >= 1.0 || currX <= -1.0 || currY >= 1.0 || currY <= -1.0){
printf("OUT OF BOUNDS !!!!");
}
}
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) {
char key_str = '0';
if (action == GLFW_PRESS || action == GLFW_REPEAT) {
switch (key) {
case GLFW_KEY_W:
key_str = 'W';
break;
case GLFW_KEY_A:
key_str = 'A';
break;
case GLFW_KEY_S:
key_str = 'S';
break;
case GLFW_KEY_D:
key_str = 'D';
break;
case GLFW_KEY_Q:
printf("Bye ...");
glfwSetWindowShouldClose(window, GL_TRUE);
break;
default:
printf("unknown key pressed \n");
break;
}
updateWorld(key_str, speed);
}
}
int main(void) {
GLFWwindow* window;
// Initialize the library
if (!glfwInit())
return -1;
//remove win frame
//glfwWindowHint(GLFW_DECORATED, GLFW_FALSE);
// Create a windowed mode window and its OpenGL context
window = glfwCreateWindow(worldWidth, worldHeight, "Move Pixel with Keyboard", NULL, NULL);
if (!window) {
glfwTerminate();
return -1;
}
// Make the window's context current
glfwMakeContextCurrent(window);
// Set the keyboard input callback
glfwSetKeyCallback(window, key_callback);
// Initialize GLEW
glewExperimental = GL_TRUE;
if (glewInit() != GLEW_OK) {
std::cerr << "Failed to initialize GLEW" << std::endl;
return -1;
}
//glfwGetFramebufferSize(window, &worldWidth, &worldHeight);
// Define the viewport dimensions
glViewport(0, 0, worldWidth, worldHeight);
// Set point size
glPointSize(10.0f); // Increase if you want the "pixel" to be bigger
// Loop until the user closes the window
while (!glfwWindowShouldClose(window)) {
// Render here
glClear(GL_COLOR_BUFFER_BIT);
// Set the drawing color to blue
glColor3f(0.0f, 0.0f, 1.0f); // RGB: Blue
// Draw a point at the current position
glBegin(GL_POINTS);
glVertex2f(currX, currY); // Use the updated position
glEnd();
// Swap front and back buffers
glfwSwapBuffers(window);
// Poll for and process events
glfwPollEvents();
}
glfwTerminate();
return 0;
}
In the worst case i can debug step by step with `printf` ... but well it will take a long time and it won't necessarily allow me to understand from where this behavior stems.
|
Clone gist with SSH:
$ git clone git@gist.github.com:<hash>.git mygist
HTTP clone worked fine, but ran into HTTP authentication problems at `git push`. |
The IsShuttingDown property is a internal static property of Apllication class therefore you can access to value of it with bellow code
var isShuttingDownProp = typeof(Application).GetProperty("IsShuttingDown", BindingFlags.Static | BindingFlags.NonPublic);
var isShuttingDown = isShuttingDownProp.GetValue(Application.Current, null); |
The [`Kbd`](https://codeberg.org/xmobar/xmobar/src/branch/master/doc/plugins.org#user-content-headline-24) monitor plugin can be installed in the xmobar status bar like this,
```haskell
Run $ Kbd [("it", "IT"), ("ru(phonetic)", "RU")]
```
and then switch keyboard via `setxkbmap`, the monitor will reflect the change.
So far so good.
Now, assume that
- I want to make the monitor clickable,
- and that the click should "rotate" the keyboard layout (among those provided, see the `[]` above)
even if this means writing `MyOwnKbd` plugin.
Also assume that another requirement is that I don't want the logic of rotation to be encoded in an external script.
---
Since I don't want to bind a key to switching between keyboardsΒΉ, I was thinking about allowing the switch via clicking on the monitor itself.
I know I can just wrap the text of the monitor in ``<action=`the command`>`` and `</action>` to make it clickable, but I have no clue what `the command` should be.
I know that I could write a shell script that detects the state of the keyboard and sets the other one, but I want to use the very list above, `[("it", "IT"), ("ru(phonetic)", "RU")]` as the source of what keyboard layouts clicking the monitor should loop through, so the question becomes: can I feed the click-on-monitor event back to the business logic of the monitor?
Or, if that's not possible, what other alternatives do I have?
---
(ΒΉ) E.g. I could have done
```bash
setxkbmap -layout it,ru -variant ,phonetic -option 'grp:caps_toggle'
```
once and for all, and <kbd>Caps Lock</kbd> would allow to switch between those two layouts, and the plugin, as is, would reflect which layout is in use. But I don't want to map any key to the layout switching action.
Well, it's not that I don't want that solution, but I'm curious to know what another solution would be.
---
(I've deleted [a previous question](https://stackoverflow.com/questions/78149534/how-can-i-feed-the-event-that-an-xmobar-plugin-monitor-has-been-clicked-back-to) because the specific scenario that led me to formulate it was actually complicating the matter. I'll un-delete it if the answer to this question will be insufficient for that.) |
|firefox|gpo| |
i try to run this code
```
#!/bin/bash
source BBSW.sh
declare -g HTXApiKey=""
declare -g HTXSecretKey=""
declare -g HTXIdApi=""
function _Init_Huobi_ApiSecretIDData() {
if [ -z "$1" ]; then
echo "Errore: Nome exchange mancante."
return 1
fi
exchange_name="$1"
if [ "$2" == "DEBUG" ]; then
echo "Debug mode attivato."
fi
db_file="ConfigDB.db"
query="SELECT ApiKey, SecreatKey, IDapi FROM key_exchange WHERE exchange = '$exchange_name';"
result=$(sqlite3 "$db_file" "$query")
if [ -n "$result" ]; then
HTXApiKey=$(echo "$result" | cut -d '|' -f 1)
HTXSecretKey=$(echo "$result" | cut -d '|' -f 2)
HTXIdApi=$(echo "$result" | cut -d '|' -f 3)
if [ "$2" == "DEBUG" ]; then
echo "Dati dell'exchange $exchange_name:"
echo "HTXApiKey: $HTXApiKey"
echo "HTXSecretKey: $HTXSecretKey"
echo "HTXIdApi: $HTXIdApi"
fi
else
echo "Exchange $exchange_name non trovato nel database."
fi
}
response=""
_Huobi_Get_all_Accounts_of_the_Current_User() {
_Init_Huobi_ApiSecretIDData "huobi"
local PRE_URL="v1/account/accounts"
local apiUrl="$HTXApiUrl$PRE_URL"
local ACCESSKEYID="AccessKeyId=$HTXApiKey"
local SIGNATUREVERSION="SignatureVersion=2"
local SIGNATUREMETHOD="SignatureMethod=HmacSHA256"
local TIMESTAMP="Timestamp=$(date -u +"%Y-%m-%dT%H:%M:%S" | sed 's/:/%3A/g')"
local QUERYSTRING=$(echo -n "$ACCESSKEYID&$SIGNATUREMETHOD&$SIGNATUREVERSION&$TIMESTAMP" | sort)
local SIGNATURE=$(echo -n "GET\n$HTXApiUrl\n$PRE_URL\n$QUERYSTRING" | openssl dgst -sha256 -hmac $HTXSecretKey | cut -c 18-)
local SIGNATUREPARAM="Signature=$SIGNATURE"
response=$(curl -s -H "Content-Type: application/json" -X GET "$apiUrl?$QUERYSTRING&$SIGNATUREPARAM")
echo "curl -H 'Content-Type: application/json' -X GET \"$apiUrl?$QUERYSTRING&$SIGNATUREPARAM\""
}
_Initialize_Api_Huobi --api-typo "huobi"
_Huobi_Get_all_Accounts_of_the_Current_User
echo "$response"
```
but always return:
```
{"status":"error","err-code":"api-signature-not-valid","err-msg":"Signature not valid: Verification failure [ζ ‘ιͺε€±θ΄₯]","data":null}
```
i tryed also this code
```
#!/bin/bash
# Set API keys
access_key=""
secret_key=""
host="api.huobi.pro"
path="/v1/account/accounts"
method="GET"
# Generates a timestamp in UTC format
timestamp() {
date -u +"%Y-%m-%dT%H:%M:%S"
}
# URL-encode parameters
urlencode() {
local string="${1}"
local strlen=${#string}
local encoded=""
local pos c o
for (( pos=0 ; pos<strlen ; pos++ )); do
c=${string:$pos:1}
case "$c" in
[-_.~a-zA-Z0-9] ) o="${c}" ;;
* ) printf -v o '%%%02x' "'$c"
esac
encoded+="${o}"
done
echo "${encoded}"
}
# Generate the signature
generate_signature() {
local params="AccessKeyId=$access_key&SignatureVersion=2&SignatureMethod=HmacSHA256&Timestamp=$(urlencode "$(timestamp)")"
local pre_signed_string="$method\n$host\n$path\n$params"
echo -en "${pre_signed_string}" | openssl dgst -sha256 -hmac "${secret_key}" -binary | base64
}
# Send the GET request
send_request() {
local signature=$(generate_signature)
local signed_params="AccessKeyId=$access_key&SignatureVersion=2&SignatureMethod=HmacSHA256&Timestamp=$(urlencode "$(timestamp)")&Signature=$(urlencode "$signature")"
local request_url="https://${host}${path}?${signed_params}"
echo "Full request URL: $request_url"
curl -s -H "Content-Type: application/x-www-form-urlencoded" -X GET "${request_url}"
}
# Main execution
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
response=$(send_request)
echo "Response: $response"
fi
```
but nothing return always {"status":"error","err-code":"api-signature-not-valid","err-msg":"Signature not valid: Verification failure [ζ ‘ιͺε€±θ΄₯]","data":null}, but i follow the manual https://www.htx.com/en-us/opend/newApiPages/?id=419 anyone have some idea? thanks
|
why this code return api signature not valid in huobi api? |
|bash|huobi| |
I am working on an Angular application where I need to upload files or images to an S3 server using the http.put method. I have written the following code, but I am encountering issues with the upload process. Here is my code:
uploadFileToS3(fileUrl: string, file: File): Observable<any> {
const formData = new FormData();
formData.append('data', file);
const headers = new HttpHeaders({
'Content-Type': file.type
});
return this.http.put<any>(fileUrl, formData, { headers: headers });
}
url = [link](https://s3.us-west-2.amazonaws.com/dummy.com/bucket-name/1011/application/doc-verification/25767/11-2-2/test_pan.jpg?X-Amz-Security-Token=IQoJb3JpZ2luX2VjEKL%2F%2F%2F%2F%2F%2F%2F%2F%2F%2FwEaCXVzLXdlc3QtMiJHMEUCIBjrdA65geL6AGOnCmlnz2PZBS1VSmen9DscegfDVV8NAiEAxLSJFhiNbFoEInohFYBuZ%2FFLMVzzwNdHLcPj61efl1AqxAUIu%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2FARAFGgw3NzM5ODc1MTIzNjkiDCGnL0VXztrPg4GakCqYBRD54tGDyjQm3mBr89JQY4Sf90o0RV2AiEJw2%2BIc3VeeWpwdXhdVw4JvUdUELNZ%2FUFzo1QYCedWyfQNTqjQNZGozcOk%2FxReUTBpQpzi%2B9QHhgV4ucnFhcwkTLKdlI21N4r%2FXi31TrYgpwgR96eOZztrIR3xmAEZi0mw1WUM6sdQkX3%2FvOFgkO5npLFk9twLT7fbHxYrRoV8HxjQNbXxkHsyJXzJ0fOGI%2Bp8PmwmtsLGdi2IbEOfyTyDJ38K3mtL%2FZacYnbaLVgZ%2FKXnHaS4nhcuz0yCFG0FXbJqkxJovb%2FHrGBKN%2FDNqX9cJd31VUdL8Th8laOxX4%2BrIQtofttmzEMpwGlt0%2BE5Vz8yCbuCF0JV82VdhtTwrl%2F%2Fca8tbbfZDSqKaYtn6NU1jrLTmjRlzEI%2F5dA8j0RPavxsQ80giRF7zL2M%2FKu4U%2Bt4jYabal87JJjH2USEnkc4IJCwk4rVdlFPAOrm%2F4v9MuuRIy65%2BoxKl0yO6pOdutP7RrLbI693AzZAFtZ85ZNObDtENI5kRxp%2BQlXkALLwn1sPhFOEH5hGKVbkyAqCHzdIaRD5QGeAHIV%2BAKEb9UCwYsfl8g92XMPdI2rarDEx%2B0IRxh9JXNG8E6O0YdYq6C3nfZWXfOLc8mDIch2YU%2FR4AqEb2GmWqihrE35qIm5Uv3R%2Byo4vzq577o2Y91dm0ND%2B3EsTiNsut3TqGdB3izdyLB%2Btj6oNQSr3HjLnH0aY4EF8aIAMmUeQyH1lF%2B%2B011WCJ4EiE5oBfrSL5mn8lT%2Bw2J76m7jF72ZqgPUFBuq0LAWc%2B3NDBf4A8xEX1DSuDQUw6tFsThYVIbYUtmRHxLnfWeMaek01m5Xbn4dNHOarck3JBMeDkEDWj5gj75InLNSEwis2PsAY6sQEHNZb8t9vdLw7XJOVXg9JaJShKMnO0F4wbcDdVUWfJlxlrxDGmaiEU73hCo5JzkE%2FOBl4r1HvGCrAyj1EnpDb1CKsFwCT6Ur%2F0vbLL6JSqgHxTsYRpZR3i%2FXevzGjHVZTn32iwaVzQ7pph4JFyfyaJGefscWgdpOVJQHXA1SxuokinxKkr1O8rj3sMEffPeBJYmr0Xfgk7LrWcGIUX5iAV%2B5bloqQn1QQlrtmergj2PP4%3D&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20240327T102356Z&X-Amz-SignedHeaders=host&X-Amz-Expires=7200&X-Amz-Credential=ASIA3INKAGAYSTYCWKHQ%2F20240327%2Fus-west-2%2Fs3%2Faws4_request&X-Amz-Signature=56b9f1b526c037c8b8c72610bb8ae75b1c948e7b2180abeab65dd19737125a88)
However, when I try to upload a file using this function, I receive a response stating "the request has no data available." I have also tried setting the content type in the headers, but it doesn't seem to work.
Could anyone please guide me on how to fix this issue and successfully upload files or images to the S3 server using Angular's HTTP PUT method? Is there anything specific I need to consider in terms of headers or formatting the request?
when i tried to download or see this file its showing issue

the code for uploading file to s3
uploadFileToS3(fileUrl, file) {
var formData = new FormData();
formData.append('data', file);
const headers = new HttpHeaders({
'Content-Type': "multipart/form-data"
});
return this.http.put<any>(fileUrl, formData, {
responseType: 'text' as 'json'
});
}
Thank you in advance for your help!
|
How to obtain the capacity of a USB drive on Android. Some devices mount USB drives to/mnt/media_rw.
Cannot obtain the capacity of the USB drive through StatFs. The files in the USB drive will not be scanned into MediaStore, so they cannot be obtained through MediaStore. My app is not a system application. Is there any way to obtain capacity? |
How to obtain USB drive capacityοΌ |
|usb| |
null |
The most efficient approach is to sort both lists by time then concurrent run through both lists. Complexity is 2 sorts plus O(n), where "n = min(runEvents.Count, heartBeats.Count)" |
I have a program that aims to function like an etch-a-sketch.
If you hit A, the X coordinate will change, and if you hit B the Y coordinate will change.
I use a sprite as the 'crosshair' and pressing A+B will plot a point at the current coordinate. The problem is whenever there's a sprite on the screen plot just doesn't work.
[![image description][1]][1]
[1]: https://i.stack.imgur.com/vZ3T3.png
|
You can use this code belo
```
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Center(
child: CustomPaint(
painter: MyPainter(),
child: Container(
height: 300,
width:400,
padding:
EdgeInsets.only(left: 15, right: 15, bottom: 20, top: 20),
child: Center(
child:
Text("Some content",
style: TextStyle(
color: Colors.black,
)),
)),
),
),
));
}
}
class MyPainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
Paint paint = Paint();
Paint stroke = Paint()
..style = PaintingStyle.stroke
..strokeWidth = 6.0
..color = Colors.green;
Path path = Path();
// Path number 1
paint.color = Color(0x3d3ded).withOpacity(1);
path = Path();
path.moveTo(size.width * 0.14, size.height * 0.11);
path.cubicTo(size.width * 0.14, size.height * 0.11, size.width * 0.05,
size.height * 0.11, size.width * 0.05, size.height * 0.11);
path.cubicTo(size.width * 0.01, size.height * 0.11, 0, size.height * 0.16,
0, size.height * 0.19);
path.cubicTo(
0, size.height * 0.19, 0, size.height * 0.9, 0, size.height * 0.9);
path.cubicTo(0, size.height, size.width * 0.04, size.height,
size.width * 0.06, size.height);
path.cubicTo(size.width * 0.06, size.height, size.width * 0.94, size.height,
size.width * 0.94, size.height);
path.cubicTo(size.width, size.height, size.width, size.height * 0.93,
size.width, size.height * 0.9);
path.cubicTo(size.width, size.height * 0.9, size.width, size.height * 0.19,
size.width, size.height * 0.19);
path.cubicTo(size.width, size.height * 0.11, size.width * 0.96,
size.height * 0.1, size.width * 0.94, size.height * 0.11);
path.cubicTo(size.width * 0.94, size.height * 0.11, size.width * 0.27,
size.height * 0.11, size.width * 0.27, size.height * 0.11);
path.cubicTo(size.width * 0.27, size.height * 0.11, size.width / 5, 0,
size.width / 5, 0);
path.cubicTo(size.width / 5, 0, size.width * 0.14, size.height * 0.11,
size.width * 0.14, size.height * 0.11);
path.cubicTo(size.width * 0.14, size.height * 0.11, size.width * 0.14,
size.height * 0.11, size.width * 0.14, size.height * 0.11);
canvas.drawPath(path, paint);
canvas.drawPath(path, stroke);
}
@override
bool shouldRepaint(CustomPainter oldDelegate) {
return true;
}
}
```
[![custom shape][1]][1]
you may have to create a paint for stroke and paint it twice as shown at the end of this code
[1]: https://i.stack.imgur.com/ugcem.png |
we have recently set up rootless docker alongside our existing docker but ran into problems injecting host GPUs into the rootless containers. A workaround was presented in a Github [issue](https://github.com/NVIDIA/nvidia-container-toolkit/issues/85) (toggling no-cgroups to switch between rootful and rootless) with a mention of a better solution coming as a experimental feature in Docker 25, that feature being Nvidia OCI.
This is a mirror of Github [Issue](https://github.com/NVIDIA/nvidia-container-toolkit/issues/434) from the [nvidia-container-toolkit](https://github.com/NVIDIA/nvidia-container-toolkit) page. The exact setup can be found there.
We have set up the yaml file and confirmed the CDI devices:
```
sudo nvidia-ctk cdi generate --output=/etc/cdi/nvidia.yaml
...
INFO[0000] Found 5 CDI devices
nvidia.com/gpu=0
nvidia.com/gpu=1
nvidia.com/gpu=2
nvidia.com/gpu=4
nvidia.com/gpu=all
```
OCI injection works fine for the regular Docker (26.0) instance:
```
$ docker run --rm -ti --runtime=nvidia -e NVIDIA_VISIBLE_DEVICES=nvidia.com/gpu=all ubuntu nvidia-smi -L
GPU 0: NVIDIA A100-SXM4-40GB (UUID: GPU-b6022b4d-71db-8f15-15de-26a719f6b3e1)
GPU 1: NVIDIA A100-SXM4-40GB (UUID: GPU-22420f7d-6edb-e44a-c322-4ce539cade19)
GPU 2: NVIDIA A100-SXM4-40GB (UUID: GPU-5e3444e2-8577-0e99-c6ee-72f6eb2bd28c)
GPU 3: NVIDIA A100-SXM4-40GB (UUID: GPU-dd1f811d-a280-7e2e-bf7e-b84f7a977cc1)
```
but produces the following errors for the rootless (26.0.0) version:
```
$ docker run --rm -ti --runtime=nvidia -e NVIDIA_VISIBLE_DEVICES=nvidia.com/gpu=all ubuntu nvidia-smi -L
docker: Error response from daemon: failed to create task for container: failed to create shim task: OCI runtime create failed: could not apply required modification to OCI specification: error modifying OCI spec: failed to inject CDI devices: unresolvable CDI devices nvidia.com/gpu=all: unknown.
```
**Note:** That OCI support is still experimental in Docker 25 and requires `export DOCKER_CLI_EXPERIMENTAL=enabled`
Does anyone have experience with this usecase? |
You should use for example:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
<Lightbox
activeProps={{
style: {
width: "100%",
height: "100%",
},
}}
>
</Lightbox>
<!-- end snippet -->
with this code you can style the image under lightbox when it is open. |
We have a website where we provide the assignment service user are experiencing the issue of unable to go to payment gateway
https://www.ignougalaxy.in/handwritten-assignments-order
This is the link to the order form it is linked to paymnet gateway
Some of the users are saying that they cannot click on the payment button or pay now button
What would be the possible ussue tk thisss. I have attached the error also please check. (https://i.stack.imgur.com/dgRB9.jpg)
When our user are going to do the payment in our website we are experiencing thisss issue |
Issue in payment form gateway |
|php|payment-gateway|payment| |
null |
It's my first time deploying a website via github pages and I've noticed a problem with embedding videos (mp4 in my case). Everything else is working and loading fine (including images) however whenever I try to view any of the embedded videos on my website, I get the following black screen with the controls greyed out:
[Video not loading](https://i.stack.imgur.com/hjr6s.png)
(for reference the video in this screen shot is only 2.89 MB)
I found this weird, because while building the website and testing things on local host, everything was working fine and all embedded videos were working perfectly with full audio and video. I've researched a bit on what the issue is but can't seem to get a clear solution as some people recommend hosting the videos externally like on youtube and then embedding that link but I really want the videos to work embedded within the website without having to host the videos anywhere else wich is a last resort.
For reference, following are the snippets of my code relating to how I'm displaying these videos and cannot seem to find any errors so far:
index.html:
```
<video class="responsive-video" id="knowPros_vid" controls>
<source src="./assets/knowPros_Demo.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
```
style.css:
```
/* Applying CSS limits for videos used in the carousel to avoid distortion */
.responsive-video {
max-width: 100%;
height: auto;
display: block;
margin: 0 auto;
}
```
Out of the 3 videos I have on this webpage, only one is a large video file (143 MB) but the other two are both small video files (2.89 MB & 4.39 MB), however this issue is being had with all of them which is why I think it's safe to rule out a git-lfs problem since that's only used for the largest video file.
I also don't have a gitattributes file for this repository, idk if I should cause everything has been working fine without one. (don't know if it's important but just thought I should mention it just incase)
Please let me know if anyone has faced a similar issue and if so how it can be tackled. Also if any methodologies have expired as of currently, plese let me know. Thanks :)
|
I am trying to write my version of the function `strncmp` that already exists in the C language. Below is the solution I have found; I have tested it with a handful of cases and compared the results with the original `strncmp` C function and I have got same results. Please let me know if there are any flaws in my solution, any errors, etc:
```
/*
* IT IS ENOUGH TO CHECK IF WE REACHED THE LENGTH OF ONE
* OF THE STRINGS! :)
*/
int my_strncmp(char *s1, char *s2, unsigned int n)
{
unsigned int i;
i = 0;
while ((s1[i] == s2[i]) && (s1[i] != 0) && (i < n))
i++;
return (s1[i] - s2[i]);
}
#include <stdio.h>
#include <string.h>
int main(void)
{
char *str1 = "Hello";
char *barrier = "XXXXXX";
char *str2 = "Hellz";
int n = -1;
int max_len = 0;
int res;
max_len = strlen(str1);
if (strlen(str1) < strlen(str2))
max_len = strlen(str2);
// making sure that n is tested way beyond the strlen of strings
max_len += 2;
while (n < max_len)
{
res = strncmp(str1, str2, n);
printf(" strncmp(\"%s\",\"%s\", %d) = %d\n", \
str1, str2, n, res);
res = my_strncmp(str1, str2, n);
printf("my_strncmp(\"%s\",\"%s\", %d) = %d\n\n", \
str1, str2, n, res);
n++;
}
return (0);
}
``` |
I had problems using Java 21 in VSCode with Gradle on WSL. VSCode has an internal Java 17 runtime (March 2024) [as described here][1]. In order to let VSCode use your default Java 21 installation add the 'java.jdt.ls.java.home' setting, for me it looks like this:
"java.jdt.ls.java.home": "/usr/lib/jvm/java-21-openjdk-amd64"
Settings -> 'java.jdt.ls.java.home' -> 'edit in settings.json'
[1]: https://github.com/microsoft/vscode-gradle/blob/develop/README.md |
Want descending order of data in hive:
Requirement: Our requirement is we want to get pnote column in a way that data for particular invoice number should be in descending order. As we want to get the most recent date record from the top of the array (zeroth element) from pnote column.
Currect outputs:
1. selecting concat_dispute_notes
SELECT concat(to_date(t.modified_on),"-",b.named_user,"-",t.notes) as concat_dispute_notes
FROM Table
1. output of concat_dispute_notes that we are getting.
2023-05-31-LMINCU2-chased for pym plan
2023-08-16-LMINCU2-chased for pym plan
2023-12-07-LMINCU2-chased for pym plan
2024-01-11-LMINCU2-chased for pym plan
2024-01-22-LMINCU2-chased for pym plan
2023-05-16-LMINCU2-chased for pym plan
2023-05-02-LMINCU2-chased for pym plan
2023-03-22-LMINCU2-chased for pym plan
2022-11-22-LMINCU2-chased for pym plan
Time taken: 31.091 seconds, Fetched: 9 row(s)
------------------------------------------------------------------------------------------------------------------------------------------
2. selecting pnote from concat_dispute_note
Query->
SELECT concat_ws("... ",collect_set(case when trim(concat_dispute_notes) <>"" then concat_dispute_notes end)) as PNOTE
from (SELECT concat(to_date(t.modified_on),"-",b.named_user,"-",t.notes) as concat_dispute_notes
FROM Table
2. output of pnote that we are getting->
2023-05-31-LMINCU2-chased for pym plan... 2023-08-16-LMINCU2-chased for pym plan... 2023-12-07-LMINCU2-chased for pym plan... 2024-01-11-LMINCU2-chased for pym plan... 2024-01-22-LMINCU2-chased for pym plan... 2023-05-16-LMINCU2-chased for pym plan... 2023-05-02-LMINCU2-chased for pym plan... 2023-03-22-LMINCU2-chased for pym plan... 2022-11-22-LMINCU2-chased for pym plan
Time taken: 41.456 seconds, Fetched: 1 row(s)
------------------------------------------------------------------------------------------------------------------------------------------
**We have tried using order by but not getting required order of output
SELECT concat_ws("... ",collect_set(case when trim(concat_dispute_notes) <>"" then concat_dispute_notes end)) as PNOTE
from (SELECT concat(to_date(t.modified_on),"-",b.named_user,"-",t.notes) as concat_dispute_notes
FROM Table) order by t.modified_on desc) as t2 order by PNOTE;
**output by order by
2023-05-31-LMINCU2-chased for pym plan... 2023-08-16-LMINCU2-chased for pym plan... 2023-12-07-LMINCU2-chased for pym plan... 2024-01-11-LMINCU2-chased for pym plan... 2024-01-22-LMINCU2-chased for pym plan... 2023-05-16-LMINCU2-chased for pym plan... 2023-05-02-LMINCU2-chased for pym plan... 2023-03-22-LMINCU2-chased for pym plan... 2022-11-22-LMINCU2-chased for pym plan
Time taken: 38.52 seconds, Fetched: 1 row(s)
We tried sort_Array:
SELECT concat_ws("...", sort_array(collect_set(case when trim(concat_dispute_notes) <> "" then concat_dispute_notes end))) as PNOTE
FROM (
SELECT concat(to_date(t.modified_on), "-", b.named_user, "-", t.notes) as concat_dispute_notes
FROM Table) AS Tablepnote11;
Output of Sort_Array:
2022-11-22-LMINCU2-chased for pym plan...2023-03-22-LMINCU2-chased for pym plan...2023-05-02-LMINCU2-chased for pym plan...2023-05-16-LMINCU2-chased for pym plan...2023-05-31-LMINCU2-chased for pym plan...2023-08-16-LMINCU2-chased for pym plan...2023-12-07-LMINCU2-chased for pym plan...2024-01-11-LMINCU2-chased for pym plan...2024-01-22-LMINCU2-chased for pym plan
Time taken: 31.719 seconds, Fetched: 1 row(s)
The output of sort array is Ascending order. We need descending order.
------------------------------------------------------------------------------------------------------------------------------------------
We have also tried sort by, cluster by, reverse sort, sort_array(---,false) but did not get required output.
we have tried all the above tried using Sort_Array which sort in Ascending order, tried ranking, sort_by, cluster_by, order_by, group_by, Reverse_array sort array(,false) but nothing worked to get it in descending order as a single record. |
which running pdb in docker shell/container, in order to exit
run ```pdb.disable()``` and then ```exit()``` |
|javascript|dropbox| |
i want to turn windows on and off from java code so to do this need to execute cmd command with admin privilege to do this please any one help me
i tried this but it is not running as admin public void execute_cmd2() {
Process exec = Runtime.getRuntime().exec("cmd");
OutputStream outputStream = exec.getOutputStream();
InputStream inputStream = exec.getInputStream();
PrintStream printStream = new PrintStream(outputStream);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream,"utf-8"));
printStream.println("netsh advfirewall set allprofile state off");
//printStream.println("winget uninstall \"voidtools.Everything\"");
printStream.flush(); |
execute cmd commands as admin with java code |
|java|cmd|admin| |
null |
I have two different services (Service A and Service B) that share Redis Session and both services were using Spring-boot 1.5
Service A is the authentication service (SSO)
While Service B is the User service
Recently, Service B was upgraded to Spring-boot 2.7.
It has become a problem to share session Id between these two services.
We do not want to upgrade Service A (at least for now) as other services depends on it.
How can the Session serialization be dealt-with without upgrading service A.
I have tried custom serialization for Redis but proved abortive.
```java
@Configuration
public class RedisConfig {
@Autowired
@Qualifier("springSessionDefaultRedisSerializer")
private RedisSerializer<Object> serializer;
@Bean
public JedisConnectionFactory jedisConnectionFactory() {
RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration("redis", 6379);
return new JedisConnectionFactory(redisStandaloneConfiguration);
}
@Bean
public RedisTemplate<String, Object> redisTemplate() {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(jedisConnectionFactory());
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(new JdkSerializationRedisSerializer());
redisTemplate.setValueSerializer(serializer);
redisTemplate.setEnableTransactionSupport(true);
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
}
@Configuration
@Slf4j
public class SpringSessionConfig implements BeanClassLoaderAware {
private ClassLoader loader;
@Bean("springSessionDefaultRedisSerializer")
public RedisSerializer<Object> springSessionDefaultRedisSerializer() {
return new GenericJackson2JsonRedisSerializer(objectMapper());
}
/**
* Customized {@link ObjectMapper} to add mix-in for class that doesn't have default constructors
*
* @return the {@link ObjectMapper} to use
*/
private ObjectMapper objectMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// mapper.registerModules(SecurityJackson2Modules.getModules(this.loader));
return mapper;
}
/*
* @see
* org.springframework.beans.factory.BeanClassLoaderAware#setBeanClassLoader(java.lang
* .ClassLoader)
*/
@Override
public void setBeanClassLoader(ClassLoader classLoader) {
this.loader = classLoader;
}
}
``` |
How can I change XMobar's Kbd monitor plugin such that clicking on it loops throught the layouts? |
{"Voters":[{"Id":23918954,"DisplayName":"payam jabbari"}],"DeleteType":1} |
I've created a new Blazor 'Web App' project in .net 8.
I include 'Individual Accounts' when setting up the project.
I've setup email delivery and try a password reset. It sends the reset email first, I click then enter the email and new passwords, upon doing that I get this error:
"A valid antiforgery token was not provided with the request. Add an antiforgery token, or disable antiforgery validation for this endpoint."
This is an out of the box solution, I haven't changed anything. This can't be right?
I've researched this and it talks about various things that don't apply here, eg
https://github.com/dotnet/aspnetcore/issues/50760
However it relates to login. Someone suggests this
"use app.UseAntiforgery() after app.UseAuthentication()" - but 'UseAuthentication' isn't present in Program.cs.
This surely shouldn't fail like this out of the box, any idea how I can fix this?
Thanks |