instruction stringlengths 0 30k ⌀ |
|---|
null |
Ok , I think to resolve this problem of cyclic dependency!
The problem is that the language gathered by translateservice, if source of browser or manual setting by a combobox changer, is a "behavior" value that need to be syncronize by all components (indipendently if a interceptor, resolver, other component, service, or another thing that in the future will exist...). And only solution to ensure that the lang value is recover well by all without problem of cyclic dependency, but on general, by nothing race condition problem is to implement a "LanguageService" that have a BehaviourSubject to track the lang value .
so the steps are:
a) implement the language service
@Injectable({
providedIn: 'root'
})
export class LanguageService {
private currentLang = new BehaviorSubject<string>('it'); // Default language
setCurrentLang(lang: string): void {
this.currentLang.next(lang);
}
getCurrentLang(): Observable<string> {
return this.currentLang.asObservable();
}
}
The currentlang is the core of solution!
get and set of this field its possibile to update the value by other subscriber (component that read the lang and produce data, and a resolver that consume data before to call, or to intercept a login, or others case use)
b) Use the service , on my case use is a component
constructor(private translateService: TranslateService, private languageService: LanguageService) {
this.translateService.onLangChange.subscribe((event: LangChangeEvent) => {
this.languageService.setCurrentLang(event.lang);
});
}
On constructor of component or into a oninit phase, depend of your architecture and objective, set the lang by your translateservice as usual, and subscribe the value on languageservice implemented at first step.
c) finally consume the data on your application scope, that is a intercept of login, or to call backend with a resolver, that is my case use.
@Injectable({
providedIn: 'root'
})
export class MyResolver implements Resolve<any> {
constructor(private languageService: LanguageService) {}
resolve(): Observable<any> | Promise<any> | any {
return this.languageService.getCurrentLang().pipe(
switchMap(lang => {
// Utilizza `lang` per recuperare i dati internazionalizzati
})
);
}
In this approach, there is not error cyclic dep, there is a deocoupled service that have a behavioursubject that have production and consumption by all subscriber, in this case to manage a lang .
I hope that is usefull to resolve your problem.
see u |
How should I upgrade Cypress tests that relied on preserveOnce beforeEach? |
Devexteme ngautocomplete is lagging and drop down is not showing after api call everytime search is performed Below is code
```
<dx-autocomplete #autocompleteRef [dataSource]="employeesIAM" valueExpr="login" [grouped]="false" [searchExpr]="['login','firstName','lastName']"
label="Enter login or name" labelMode="floating" [showClearButton]="true" [minSearchLength]="3"
(onSelectionChanged)="onSelectionChanged($event);" groupTemplate="group"
(onValueChanged)="search($event)"
itemTemplate="item" [wrapItemText]="true" [searchTimeout]="300" >
</dx-autocomplete>
```
```
this.searchTerms.pipe(
debounceTime(1000),
distinctUntilChanged(),
switchMap((query:string)=> this._crewService.getEmployeeList(query))
).subscribe(res => {
this.employeesIAM = [];
this.employeesIAM = res;
this.employeesIAM.map(abc => abc.login = `${abc.login} ${abc.firstName} ${abc.lastName}`);
this.employeesIAM.map(abc => abc.Name = `${abc.firstName} ${abc.lastName}`);
});
onValueChanged(data: any) {
if (data != null && data.length >= 3) {
this._crewService.getEmployeeList(data).subscribe(res => {
this.employeesIAM = [];
this.employeesIAM = res;
this.employeesIAM.map(abc => abc.loginAndName = `${abc.login} ${abc.firstName} ${abc.lastName}`);
this.employeesIAM.map(abc => abc.Name = `${abc.firstName} ${abc.lastName}`);
});
}
}
```
Can you suggest to prevent this lagging |
ngautocomplete devextreme is lagging to show dropdown and sometimes not load |
|javascript|angular|devexpress|devextreme| |
I am getting the error
An Error Was Encountered
Unable to load the requested class: Email
I can see the site OK.
This is an older version of EE.
I tried looking through the config files to see if there is anything that might need updating but couldn't find anything except pointing the site to the new server. |
Cannot access Admin after site was moved to new server |
|expressionengine| |
null |
A few suggestions:
1. You have an error in console, that say you "can not read properties
of undefined" in meta-new-button.component.ts. So there you have a
variable that you expect have value but it's not. You need check
before
if (my-variable)
other-variable=my-variable.property
2. When we have "nested-forms" (the "form" is declared in the the
parent) in a component, generally we use viewProvider. See that,as
you're using Template Driven Forms, you useExisting: `ngForm` (not
FormDirective)
@Component({
selector: 'base-crud-page',
templateUrl: './base-crud-page.component.html',
viewProviders:[{ provide: ControlContainer, useExisting: NgForm }]
})
3. Try first with a simple component with only a button and one input
to check the problem is not in how you define your inputs
|
{"OriginalQuestionIds":[75344626],"Voters":[{"Id":12046409,"DisplayName":"JohanC","BindingReason":{"GoldTagBadge":"python"}}]} |
I am trying to add an Windows AltRoot to my p4 client automatically in command line without needing to edit the client form interactively. I am doing this from a Linux machine. Below is the command I tried:
```
p4 client -o | sed "s@AltRoot:@AltRoot:\n\tN:\\\path\\\to\\\the\\\client@" | p4 client -i
```
However, p4 client is recognizing the drive number `N:` as an invalid p4 client field name.
How do we get around this? |
*from chatgpt*
In CSS, the `auto` and `fit-content` values are often used with properties like `width` and `height` to define the size of elements.
- **Auto:** When `auto` is used, the browser calculates the size of the element based on its content and any other constraints applied. For example, if you have a block-level element with `width: auto;`, it will expand to fill its container horizontally.
- **Fit-content:** On the other hand, `fit-content` sets the size of the element to fit its content, but with a maximum constraint. It's like `auto`, but it won't expand beyond a specified size. For instance, `width: fit-content(200px);` will make the element as wide as its content, up to a maximum of 200 pixels.
So, while both are used to size elements based on their content, `fit-content` adds a limit to how much the element can expand. |
I'm encountering difficulties with extracting request data in a Flask-Lambda application deployed on AWS Lambda using AWS SAM (Serverless Application Model). Here's a breakdown of my concerns:
1. **Background:**
- I've developed a Flask-Lambda application intended to handle various HTTP requests, including POST requests, deployed on AWS Lambda using AWS SAM.
- Initially, I used SAM CLI to create a basic "hello_world" template, and I successfully built and deployed the application. GET requests function as expected.
2. **Issue:**
- However, I'm facing challenges with extracting request data specifically in POST requests.
- When attempting to retrieve the request body using methods like **`request.form.to_dict()`**, **`request.data`**, or **`request.get_json()`**, I consistently receive either empty dictionaries or encounter exceptions.
3. **Troubleshooting Steps Taken:**
- I've verified that the Lambda function is properly configured to handle POST requests.
- The API Gateway integration request mapping templates appear to be set up correctly to pass the request body to the Lambda function.
- I've ensured that Flask-Lambda is integrated correctly within my application and that routes are defined accurately.
- Additionally, I've attempted to debug the issue by introducing logging statements in the Lambda function.
4. **Request for Assistance:**
- Despite these efforts, I'm still unable to extract the request data successfully.
- I'm seeking guidance on potential solutions or further debugging steps to resolve this issue and successfully retrieve request data in POST requests within my Flask-Lambda application deployed on AWS Lambda via AWS SAM.
Sample Input :
```
{
"id":"1",
"name":"Bob",
"age":"40"
}
```
Sample Code
```
import json
import boto3
from flask_lambda import FlaskLambda
from flask import request, jsonify
app = FlaskLambda(__name__)
ddb = boto3.resource('dynamodb')
table = ddb.Table('crm_leads')
@app.route('/')
def healthCheck():
data = {
"message":"Healthy"
}
return (
json.dumps(data),
200,
{"Content-Type":"application/json"}
)
@app.route('/leads', methods=["GET","POST"])
def list_or_add_leads():
if request.method == 'GET':
data = table.scan()['Items']
return (json.dumps(data), 200, {"Content-Type":"application/json"})
elif request.method == 'POST':
try:
# Extract raw request body
print(event)
print(request.body)
# table.put_item(Item=request_body)
data = {
"message":"Successful"
}
return (json.dumps(data), 200, {"Content-Type":"application/json"})
except Exception as e:
data = {"exception":str(e)}
return (json.dumps(data), 400, {"Content-Type":"application/json"})
``` |
So I have a navbar, and in this navbar I have the logo, the options and then the button. Whenever I apply padding to the button it pushes everything else to the left? Any advice cause I have never had this happen before. This happens with other stuff as well, so if I give the logo any padding it also pushes the items around. Why is this happening because I watched some tutorials just to be sure and I have no clue what I am doing wrong. Also just wanted to add that align-items: center also isn't working.
```
<div class="container">
<section class=section1>
<div class="navbar">
<label class="logo">appy</label>
<ul class="nav-buttons">
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Pricing</a></li>
<li><a href="#">Features</a></li>
<li><a href="#">FAQ</a></li>
</ul>
<a href="#" class="sign-up">SIGN UP</a>
</div>
CSS:
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
html{
font-size: 10px;
}
.container{
height: auto;
width: 100%;
/* overflow: hidden; */
}
.section1{
background: rgb(180,135,238);
background: linear-gradient(90deg, rgba(180,135,238,1) 0%, rgba(148,187,233,1) 100%);
}
.logo{
font-size: 4rem;
font-family: "Protest Revolution", sans-serif;
font-weight: 400;
font-style: normal;
color: white;
margin-bottom: 10px;
margin-left: -10px;
}
.navbar{
width: 100%;
font-family: 'Montserrat', sans-serif;
background: rgb(180,135,238);
background: linear-gradient(90deg, rgba(180,135,238,1) 0%, rgba(148,187,233,1) 100%);
display: flex;
justify-content: space-between;
align-items: center;
padding: 25px 40px;
position: sticky;
top: 0;
z-index: 99999;
}
.nav-buttons li{
font-weight: 500;
font-size: 1.7rem;
display: inline-block;
padding: 20px;
list-style: none;
}
.nav-buttons li a{
color: white;
text-decoration: none;
}
.navbar .sign-up{
color: white;
font-size: 1.5rem;
text-decoration: none;
border: 2px solid white;
border-radius: 5px;
padding: 8px 50px 8px 50px;
}
|
I have two endpoints, /login and /index. The /login is for authentication and getting an access_token. The /index is protected and user should login first.
After authentication, the /login sends the access token to the client. The client should be redirect to the /index page after receiving an access token.
It is the code:
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="login")
@app.get("/index")
async def root(
request: Request,
current_user: Annotated[User, Depends(oauth2_scheme)]
):
return templates.TemplateResponse("index.html", {"request": request})
@app.post("/login")
async def login(
request: Request,
data: Annotated[OAuth2PasswordRequestForm, Depends()],
):
user = authenticate_user(data.username, data.password)
if not user:
raise HTTPException(...)
access_token = create_access_token(...)
response.set_cookie(key="access_token", value=access_token, httponly=True)
return Token(access_token=access_token, token_type="bearer")
It is the client form:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login</title>
</head>
<body>
<h1>Login</h1>
<form id="loginForm" >
<table>
<tr>
<td>
<label for="username">Email:</label>
</td>
<td>
<input type="text" id="username" name="username" required>
</td>
</tr>
<tr>
<td>
<label for="password">Pass Code:</label>
</td>
<td>
<input type="text" id="password" name="password" required>
</td>
</tr>
<tr>
<td></td>
<td>
<button type="submit" style="margin-top: 15px">Submit</button>
</td>
</tr>
</table>
</form>
<script>
document.getElementById("loginForm").addEventListener("submit", function (event) {
event.preventDefault();
fetch("/login", {
method: "POST",
body: new FormData(event.target)
})
.then(response => {
if (response.ok) {
return response.json();
} else {
throw new Error('Failed to authenticate');
}
})
.then(data => {
window.location.href = '/index';
})
.catch(error => console.error("Error:", error));
});
</script>
</body>
</html>
This code does not work because of lacking of the authentication header. I get this error:
{"detail":"Not authenticated"}
The test in /docs works because it sends the access token in the Authorization header. This command works:
curl -X 'GET' \
'http://127.0.0.1:8000/index' \
-H 'accept: application/json' \
-H 'Authorization: Bearer A_VALID_TOKEN '
I do not know how I should handle the client side. I am not sure if I should send another fetch for the /index and get the html content and assign it to the body section. I do not know what is the best practice. Maybe I can use RedirectResponse from fastapi.response. I am not sure if it is a good practice or not. /login should send back an access token and not a html code I think.
**Edit**
The access token is stored in cookie. |
Trouble Extracting Request Body in Flask-Lambda Application Deployed on AWS Lambda via AWS SAM |
|python-3.x|amazon-web-services|flask|aws-lambda|request| |
null |
Threading paradigm |
What are the best thing to do to implement a dashboard with summaries, like chart, real time summaries like total establishments, total compliants etc.,
Also, I wanted to implement a inspection scheduling for the establishments, and had a notification reminders.
I am using React and Node Js here, it will really help me if you could suggest such as liblaries, code, or headstart
Looking for an advice |
Dashboard - for React and Node Js |
|reactjs|node.js|mongodb| |
null |
I need to process JSON from different sources who use different models. One is sending me
```json
{
"addressData": {
"street": "Foostreet 1",
"zip": "12345",
"city": "Metropolis"
}
}
```
and the other
```json
{
"addressData": {
"address": {
"street": "Foostreet 1",
"zip": "12345",
"city": "Metropolis"
}
}
}
```
i.e. the inner contents are identical, there might just be one additional layer of wrapping. So far my Java model for deserializing looks like this
```java
class AddressData {
private String street;
private String zip;
private String city;
private Address address;
}
class Address {
private String street;
private String zip;
private String city;
}
```
and I use an additional step in post-processing to normalize this.
Is there an annotation to tell Jackson that the object *might* be wrapped by an additional property, so that I can skip this boilerplate? |
Deserialize object that might be wrapped |
I created a return icon while designing, but this text appeared on it. what is this text and how do I solve it?
there does not seem to be an error in my code, I searched the internet but could not find any results.I don't know how to investigate. |
I created an icon and this text appeared |
|flutter|dart|user-interface| |
null |
The design of your step definitions wasn't done right. Unlike JUnit where a single class with a `@Test` annotated method is instantiated for a test, when using Cucumber all classes with step definition annotations are instantiated for each test.
This also means you'll want to [share state between steps][1], you can do this with [`cucmber-picocontainer`][2]. The tutorial is a bit old, but it works pretty much the same in `io.cucumber` as it did in `info.cukes`.
First add PicoContainer to your dependencies:
```xml
<dependencies>
[...]
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-picocontainer</artifactId>
<version>${cucumber.version}</version>
<scope>test</scope>
</dependency>
[...]
</dependencies>
```
Then create a class to hold your webdriver and lazily instantiate it (this makes tests that don't use the webdriver faster).
```java
public class WebDriverHolder implements Disposable {
private WebDriver driver;
public WebDriverHolder(){
}
public WebDriver getDriver() {
if (driver != null) {
return driver;
}
driver = // instantiate web driver here
return driver;
}
@Override
public void dispose() {
if (driver != null) {
return;
}
driver. // shut down the driver here
}
}
```
Then you inject the holder into other step definition classes and use it:
```java
public class MyStepDefinitions {
private final WebDriverHolder holder;
public MyStepDefinitions(WebDriverHolder holder){
this.holder = holder;
}
@Given("user is on landing page")
public void user_is_on_landing_page() {
WebDriver driver = holder.getDriver();
// Do stuff with your driver, like creating the BasePage
}
}
```
[1]: http://www.thinkcode.se/blog/2017/04/01/sharing-state-between-steps-in-cucumberjvm-using-picocontainer
[2]: https://github.com/cucumber/cucumber-jvm/tree/main/cucumber-picocontainer |
I know that this question is not related to `javascript` but its really easy to import CSV or JSON to `Cloud Firestore` via Javascript.
**Steps:**
1. [Add Firebase to your JavaScript project][1]
2. Convert your CSV data to `JSON` using online tools and paste your data in below function.
3. Add function named 'exportToFirestore' to your `index.js` file (using code below)
4. Run your JavaScript function to import CSV or JSON data to cloud firestore.
Code for exportToFirestore:
<!-- language: lang-js -->
function addTestData() {
const employeesdata = [
// paste your data between [] blocks
{
"name": "Blake Henderson",
"address": "275 Ridge Lane, Waltham MA 02452",
"phone": 1111111111
},
{
"name": "Molly Rutherford",
"address": "112 Joyner Avenue, Nashville TN 37210",
"phone": 2222222222
},
{
"name": "Victor Metcalfe",
"address": "16412 Eastwood Cut Off Road, Louisville KY 40245",
"phone": 3333333333
}
];
employeesdata.forEach(employee => {
db.collection('employees').add({
name: employee.name,
address: employee.address,
phone: employee.phone,
timestamp: firebase.firestore.FieldValue.serverTimestamp()
}).then(function () {
console.log("Document successfully written!");
})
.catch(function (error) {
console.error("Error writing document: ", error);
});
});
}
[1]: https://firebase.google.com/docs/web/setup |
I have a Python/Flask code that executes an SQL query :
`***def valeurs_thematiques():
query_thematiques = """
SELECT NOMTHEMATIQUE
FROM THEMATIQUES
"""
connection = connect(path)
cursor = connection.cursor()
cursor.execute(query_thematiques)
res_them = cursor.fetchall()
connection.close()
return res_them
res_them=valeurs_thematiques()
def valeurs_activites():
query_activites = """
SELECT NOMTHEMATIQUE
FROM THEMATIQUES
"""
connection = connect(path)
cursor = connection.cursor()
cursor.execute(query_activites)
res_act = cursor.fetchall()
connection.close()
return res_act
res_act=valeurs_activites()
@app.route('/formulaire_creat_congres')
def formulaire_creat_congres():
return render_template('formulaire_creat_congres.html', res_them=res_them, res_act=res_act)***`
Then, I have an HTML page with a loop that displays the results of the query in checkbox inputs :
```
*** <table>
<tr>
<td colspan="2" >
<label><strong>Thématiques :</strong></label>
</td>
</tr>
<tr>
<td colspan="2">
{% for t in res_them %}
<div>
<input type="checkbox" id="{{ t[0] }}" name="nomtheme" value="{{ t[0] }}">
<label for="{{ t[0] }}">{{ {t[0]} }}</label>
</div>
{% endfor %}
</td>
</tr>
</table>
<table>
<tr>
<td colspan="2" >
<label><strong>Activités :</strong></label>
</td>
</tr>
<tr>
<td colspan="2">
{% for a in res_act %}
<div>
<input type="checkbox" id="{{ a[0] }}" value="{{ a[0] }}" name="nomactivite">
<label for="{{ a[0] }}">{{ a[0] }}</label>
</div>
{% endfor %}
</td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Ajouter"></td>
</tr>
</table>***
```
I want to retrieve the checkbox parameters with nomtheme=request.args.getlist("nomtheme"). However, when I display the value of the variable nomtheme, I either get an empty list or the list: ['on', 'on'] :
```
***@app.route('/confirmation_creat_congres', methods = ["GET","POST"])
def confirmation_creat_congres():
if request.method=='GET':
codcongres = request.args.get("codcongres")
titrecongres = request.args.get("titrecongres")
numedition = request.args.get("numedition")
date_debut_c = request.args.get("date_debut_c")
date_fin_c = request.args.get("date_fin_c")
URL = request.args.get("URL")
nomtheme = request.args.getlist('nomtheme')
nomactivite = request.args.getlist("nomactivite")
# codcongres=codcongres,titrecongres=titrecongres, numedition=numedition,
#date_debut_c=date_debut_c, date-fin_c=date_fin_c, URL=URL,
nomtheme=nomtheme,nomactivite=nomactivite
else :
codcongres = request.form.get("codcongres")
titrecongres = request.form.get("titrecongres")
numedition = request.form.get("numedition")
date_debut_c = request.form.get("date_debut_c")
date_fin_c = request.form.get("date_fin_c")
URL = request.form.get("URL")
nomtheme = request.form.getlist("nomtheme")
nomactivite = request.form.getlist("nomactivite")
connection = connect(path)
cursor = connection.cursor()
query11 = """
SELECT CODETHEMATIQUE
FROM THEMATIQUES
WHERE NOMTHEMATIQUE = ?
"""
codthemes = []
codactivites = []
for theme in nomtheme:
cursor.execute(query11, (theme,))
codtheme = cursor.fetchone()
if codtheme is not None:
codthemes.append(codtheme)
query22 = """
SELECT CODEACTIVITE
FROM ACTIVITES
WHERE NOMACTIVITE = ?
"""
for activite in nomactivite:
cursor.execute(query22, (activite,))
codactivite = cursor.fetchone()
if codactivite is not None:
codactivites.append(codactivite)
query = """
INSERT INTO congres (CODCONGRES, TITRECONGRES, NUMEDITIONCONGRES, DTDEBUTCONGRES, DTFINCONGRES, URLSITEWEBCONGRES)
VALUES (?, ?, ?, ?, ?, ?)
"""
query1 = """
INSERT INTO TRAITER (CODCONGRES, CODETHEMATIQUE)
VALUES (?, ?)
"""
query2 = """
INSERT INTO PROPOSER (CODEACTIVITE, CODCONGRES)
VALUES (?, ?)
"""
cursor.execute(query, (codcongres,titrecongres,numedition,date_debut_c,date_fin_c,URL))
connection.commit()
for codtheme1 in codthemes:
cursor.execute(query1, (codcongres, codtheme1))
for codactivite1 in codactivites :
cursor.execute(query2,(codactivite1, codcongres))
connection.commit()
connection.close()
message="La création d'un nouveau congrès est réussie ! "
print("Requête HTTP :", request.url)
print("Valeurs de nomtheme :", nomtheme)
return render_template('confirmation_creat_congres.html', message=message, nomtheme=nomtheme)***
```
It should contain the results of the previous query that have been checked (checkbox input). |
Troubleshooting Checkbox Parameters Retrieval in Python/Flask Application |
|python|sql|list|for-loop|flask| |
null |
{"Voters":[{"Id":2860711,"DisplayName":"MaxPower15"}]} |
This produces a python float error:
In [28]: 11.6 ** 422.5
---------------------------------------------------------------------------
OverflowError Traceback (most recent call last)
Cell In[28], line 1
----> 1 11.6 ** 422.5
OverflowError: (34, 'Result too large')
In [29]: np.array(11.6) ** 422.5
Using `numpy`:
C:\Users\14256\AppData\Local\Temp\ipykernel_6764\1884378001.py:1: RuntimeWarning: overflow encountered in power
np.array(11.6) ** 422.5
Out[29]: inf
`numpy`, at least on windows, does not have larger floats:
In [30]: np.array(11.6).astype('float128')
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[30], line 1
----> 1 np.array(11.6).astype('float128')
TypeError: data type 'float128' not understood
But since you are import `mpmath`, you can use that:
In [32]: mpmath.mpf(11.6) ** 422.5
Out[32]: mpf('5.4137780681010568e+449')
|
I'm struggling to implement dynamic role-based routing with the latest version of react-router-dom (v6.22.3). I have some ideas, but I'm finding it difficult to implement them fully.
Notes:
1. I familiar with examples described here [link][1]
2. Goal description :
1. define roles in the router
2. consume it in the outlet
3. The entire path are protected except login. so we dont need to add protected route (the app is function as protected) , just need to handle the role base
Here's what I've tried:
I've set up a mapping for my pages and defined roles for each page:
```
export const paths = {
boo: { path: "/boo", roles: [] },
foo: { path: "/foo", roles: ["admin", "manager"] },
};
```
And here's how I've set up my router: (defining the roles inside the id prop is the best option i found)
```
const router = createBrowserRouter([
{
path: "/",
element: <App />,
children: [
{ path: paths.details.boo, element: <Boo/>, id: createRouteId("boo") },
{ path: paths.details.foo, element: <Foo/>, id: createRouteId("Foo") },
],
errorElement: <ErrorPage />,
},
{
path: "/login",
element: <Login />,
},
]);
export default router;
```
Now, I'm wondering if there's any way to use a property other than "id" to uniquely identify routes. However, let's assume "id" is the best option.
In my App.tsx, I'm using a custom hook to get the user object, which looks like this:
```
{userName:string,roles:roles[],...}
```
I'm also attempting to check if the user has valid roles for the current route:
```
const isValidRole = (userRoles: string[], outletRole: string[]) => {
return userRoles.some((role) => outletRole.includes(role));
};
```
Here's my App.tsx component: (here we use outlet and i try to consume the roles based on the location with the outlet)
```
function App() {
const { user } = useAuth();
const getRouteIdFromOutlet = useOutlet();
const [isValidRole] = useState(isRoleValid(user.roles, JSON.parse(getRouteIdFromOutlet.props.id)));
if (!user) return <Login />;
if(!isValidRole) throw new Error("Unauthorized"); // the error page will know what to render
return (
<Layout>
<NavbarDesktop />
<Content style={{ padding: "0 48px" }}>
<Outlet />
</Content>
</Layout>
);
}
```
now the ```const getRouteIdFromOutlet = useOutlet();``` is the closest option i found in order to read the id from the route and utilize it here
[1]: https://stackoverflow.com/questions/66289122/how-to-create-a-protected-route-with-react-router-domhttps://stackoverflow.com/questions/66289122/how-to-create-a-protected-route-with-react-router-dom |
To pre-select *color* in iris you can use "color" option and pass the color which you need to set.
***Demo Code***:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
$(document).ready(function() {
$(".couleurpicker").iris({
width: 300,
hide: true,
mode: 'hsl',
controls: {
horiz: 's',
vert: 'l',
strip: 'h'
},
border: true,
change: function(event, ui) {
$(event.target).attr('style', 'background-color: ' + ui.color.toString() + ' !important');
}
});
$(document).on("click", function(e) {
if (!$(e.target).is(".iris-picker-inner")) {
$('.couleurpicker').iris('hide');
}
});
$('.couleurpicker').on("click", function(event) {
$('.couleurpicker').iris('hide');
$(this).iris('show');
return false;
});
//..
$("input[name='couleur']").iris('color', '#9bbd4c'); //use this
//^rowData.couleur
});
<!-- language: lang-html -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<script src="https://dev.joshmoto.wtf/iris/dist/iris.min.js"></script>
<div class="mb-5">
<label for="" class="form-label form-labe-custom me-2">Couleur :</label>
<div class="mb-3 parent-select2-colors">
<input type="text" class="couleurpicker form-control" name="couleur" maxlength="7" />
</div>
</div>
<!-- end snippet -->
|
#include <stdio.h>
void main() {
int arr[] = {10,20,30,40};
int *p1 = arr;
int *p2 = &arr[2];
printf("%d",p2-p1);
}
Output : 2
I was suprised to see the output as 2. I don't know why the output is 2. |
I would like to inform earlier that i have not built any code for this as of yet, but have this idea, and want to know how far is this feasible?
So i have this video link: https://youtu.be/Y8xhrUa3KH4?si=7MTdlcXMlnrWggfG this is an excel video of length 52 mins that includes all the excel formula and functions, now can i create short clips of this video for each topic and store them along with their timestamps,so that if I make a call let's say for the topic vlookup, I will get the short clip of this video that only includes the vlookup. |
Extract timestamp of an educational video for extracting particular topics with the respective timestamp using python |
|python|video-streaming| |
I have created a table from Firebase using ListViewBuilder. I also want to view the table in the form of PDF but I have no idea on how to do that. I checked some examples but non of them satisfies what I'm looking for.
StreamBuilder(
stream: FirebaseFirestore...
builder: (context, snapshot){
if(snapshot.hasData){
return Row(
children:[
LitView.Builder(
itemCount: snapshot.data!.docs.length,
builder: (context, index){
final data = snapshot.data!.docs[index];
final date = data["Day"];
final amount = data["Amount"];
return ListTile(
....
);
}
),
TextButton(
onTap:(){
/* I want to view the the table in PDF form on the
press of this button*/
}
)
]
);
}
}
);
This is the code. I want that when I press on the button, I should be able to view the table in a PDF from, and also be able to save and print the pdf. |
|gdal| |
Try `gdalinfo --version` if you have an error like this : `gdalinfo: error while loading shared libraries: libgdal.so.31: cannot open shared object file: No such file or directory`
do this:
1. Find the location of libgdal.so.31 with the command `find / -name libgdal.so*`. for me the result was : `/usr/local/lib64/libgdal.so.31`
2. The folder where is located `libgdal.so.31` should be part of $LD_LIBRARY_PATH.
If it is not: add it with `LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/path_to_your_library` for my case it is `export LD_LIBRARY_PATH=/usr/local/lib64:$LD_LIBRARY_PATH`
3. Try again `gdalinfo --version`, if it works try again to import gdal : `from osgeo import gdal` => Celebrate. If `gdalinfo --version` still work, repeat the process for error message specified libraries => celebrate
|
It's simple without trim method.
```
String s = "your string";
System.out.println(s.substring(10,21));
``` |
null |
It's simple without `trim` method:
```
String s = " Hello World ";
System.out.println(s.substring(10, 21));
``` |
{"Voters":[{"Id":23839105,"DisplayName":"Dodgy Programmer"}]} |
I currently have a simple controller written in kotlin using spring. When hit, it will call `ServiceA` which will do some validation. If `ServiceA` throws an `AccountNotFoundException`, my controller has a `RetryPolicy` class that will be executed to retry.
However in my tests, I am finding it difficult to verify my `RetryPolicy` execution. Even though I can see that it is being run and executed, I can't verify it since my tests are all using autowired and not being mocked.
Is there a simple way in which I can verify that my `RetryPolicy` is being run in my spring test? |
null |
Given a **host** compiler that supports it, you can use `std::bit_cast` in CUDA C++20 **device** code to initialize a `constexpr` variable. You just need to tell nvcc to make it possible by passing [`--expt-relaxed-constexpr`][1].
This flag is labeled as an "Experimental flag", but to me it sounds more like "this flag might be removed/renamed in a future release" than a "here be dragons" in terms of its results. It is also already quite old (See [CUDA 8.0 nvcc docs][2] from 2016), which gives me some confidence.
[1]: https://docs.nvidia.com/cuda/cuda-compiler-driver-nvcc/index.html#expt-relaxed-constexpr-expt-relaxed-constexpr
[2]: https://docs.nvidia.com/cuda/archive/8.0/cuda-compiler-driver-nvcc/index.html#options-for-altering-compiler-linker-behavior |
I have to convert a rvalue to integer, boolean or string i am unable to convert it is giving the error
error: inconsistent deduction for auto return type: ‘int’ and then ‘bool’
```cpp
auto convertData(const crow::json::rvalue &data) {
std::string type = get_type_str(data.t());
if(type == "Number"){
return int(data.i());
} else if(type == "True" || type == "False") {
return bool(data.b());
}
std::string val = data.s();
return std::string(val);
}
```
Can someone please help
Edit: -
// See i am currently doing this
```cpp
bsoncxx::document::value doc_value = builder
<< "id"
<< count
<< "name"
<< reqj["name"].s()
<< "type"
<< reqj["type"].s()
<< "priority"
<< priority
<< "expense_type"
<< reqj["expense_type"].s()
<< "available"
<< bool(reqj["available"].b())
<< "life"
<< int(reqj["life"].i())
<< "quantity"
<< int(reqj["quantity"].i())
<< finalizer;
bsoncxx::document::view docview = doc_value.view();
bsoncxx::stdx::optional<mongocxx::result::insert_one> result = collection.insert_one(docview);
```
//////////////////////////////////////////////////////////////
// Now i want to do like this
```cpp
bsoncxx::builder::stream::document update_builder;
for (auto it = reqj.begin(); it != reqj.end(); ++it) {
if(it->key()=="id") continue;
update_builder << "$set" << bsoncxx::builder::stream::open_document;
update_builder << it->key() << convertData(it->value());
update_builder << bsoncxx::builder::stream::close_document;
}
bsoncxx::document::value update = update_builder << finalizer;
bsoncxx::stdx::optional<mongocxx::result::insert_one> result = collection.insert_one(update_builder());
// The collection.insert_one updates the data in database
``` |
In this code:
for arg in env::args().skip(1) {
numbers.push(u64::from_str(&arg)
.expect("error parsing argument"));
}
I understand u64 is a type, from_str is from trait FromStr. So it means u64 implements FromStr.
But here I am able to call from_str without creating instance of u64.
How does it work?
|
calling a method on a type(not instance) |
|rust| |
You can not write anything to DOM when there is no DOM.
Just like you can not put a sofa in your livingroom when there is no house yet.
That means you have to check with ``this.isConnected`` if the element is attached to the DOM, in the ``set record`` method.
Its an instance of a JavaScript class/object; You can of course attach _anything_ you want to it and have the ``constructor/attributeChangedCallback/connectedCallback`` process it (but really think trough the house/livingroom scenario)
Note _**shadowDOM**_ allows you to create any DOM you want and **not** have it display in the main DOM (yet) (same applies to a DocumentFragment)
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const createElement = (tag, props = {}) => Object.assign(document.createElement(tag), props);
customElements.define('my-track', class extends HTMLElement {
connectedCallback() {
this.append(
this.recordDIV = createElement("div", {
innerHTML: `Default Record content`
}))
}
set record(html) {
if (this.isConnected)
this.recordDIV.innerHTML = html;
else
console.warn(this.id, "Not in the DOM yet")
}
});
const el1 = createElement('my-track', { id: "el1" });
el1.record = "Record " + el1.id;
document.body.append(el1);
const el2 = createElement('my-track', { id: "el2" });
document.body.append(el2);
el2.record = "Record " + el2.id;
<!-- end snippet -->
|
Your output:
```lang-none
this is thread 1
this is thread 2
main exists
thread 2 exists
thread 1 exists
thread 1 exists
```
Before I see that *"it prints "thread 1 exists" twice."*, I see that it prints after "main exists": This behavior can lead to unpredictable results.
--
First, you should array your code:
```cpp
#include <thread>
#include <iostream>
#include <future>
#include <syncstream>
void log(const char* str)
{
std::osyncstream ss(std::cout);
ss << str << std::endl;
}
void worker1(std::future<int> fut)
{
log("this is thread 1");
fut.get();
log("thread 1 exists");
}
void worker2(std::promise<int> prom)
{
log("this is thread 2");
prom.set_value(10);
log("thread 2 exits");
}
int main()
{
std::promise<int> prom;
std::future<int> fut = prom.get_future();
// Fire the 2 threads:
std::thread t1(worker1, std::move(fut));
std::thread t2(worker2, std::move(prom));
t1.join();
t2.join();
log("main exits");
}
```
Key points:
* CRITICAL: Replace the `while` loop and `detach()` with `join()` in the `main()` to ensure that the main thread waits for all child threads to finish before exiting.
* Dilute the `#include` lines to include only what's necessary - For better practice.
* Remove unused variables - For better practice.
* Remove the unused `using namespace` directive - For better practice.
* In addition, I would also replace the `printf()` calls with `std::osyncstream`.
[Demo][1]
Now, the output is:
```lang-none
this is thread 1
this is thread 2
thread 2 exits
thread 1 exits
main exits
```
[1]: https://onlinegdb.com/HG0zRXFJY |
Create PDF file with data from firebase |
```
$upgradeInvoke = Invoke-Command -Session $session -ScriptBlock {
try {
Shutdown.exe /r /f /t 1200 /d p:4:2 /c "Triggerd Reboot Timer for 20 minitus"
$arguments = "/s", "/v`"/qn REBOOT=ReallySuppress`""
$process = Start-Process -FilePath $using:setupFullPath -ArgumentList $arguments -PassThru -Wait -Verb runas
Write-Output $process.ExitCode
}
catch {
Write-Output "An error occurred: $($_.Exception.Message)"
}
} -WarningAction SilentlyContinue -ErrorAction Stop
```
I'm Trying to install VMTools in a remote machine after disabling UAC, The Invoke is working and I could see User32 Event logged in EventViwer for reboot. But Start-Process is not getting triggered. The same script is working when any other user is just logged in via RDP or Direct Console. It looks wierd isn't it? Moreover its working fine with Windows Server 2012 R2, 2016 and 2019 Standard. It's not working with Windows 2022 Standard. |
Start-Process is not working in Invoke-Command |
|powershell|virtual-machine|invoke-command|start-process| |
null |
I have table which represents sequence of points, I need to get sum by all possible combinations. The main problem is how to do it with minimum actions because the Real table is huge
|Col1|col2|col3|col4|col5|col6|ct|
|Id1 |id2 |id3 |id4 |id5 |id6 |30|
|Id8 |id3 |id5 |id2 |id4 |id6 |45|
The expected result is
Id3|id5|75
Id3|id4|75
Id3|id6|75
Id5|id6|75
Id2|id4|75
Id2|id6|75
Id4|id6|75
I would be grateful for any help
|
{"Voters":[{"Id":2343618,"DisplayName":"user2343618"}],"DeleteType":1} |
I am developing a simple test web application with registration and ability to log in. I try to add a new row to the database via Postman using this POST request:
```
https://localhost:7239/api/Auth/Register
```
But I get this issue:
```
System.InvalidOperationException: Unable to resolve service for type 'WebApplication1.Data.AppDbContext' while attempting to activate 'WebApplication1.Controllers.AuthController'.
at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.ThrowHelperUnableToResolveService(Type type, Type requiredBy)
at lambda_method13(Closure, IServiceProvider, Object[])
at Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider.<>c__DisplayClass6_0.<CreateControllerFactory>g__CreateController|0(ControllerContext controllerContext)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|25_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
--- End of stack trace from previous location ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext context)
```
The database is up and running.
Here is my AuthController.cs:
```
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using WebApplication1.Data;
using WebApplication1.Models;
using System.Threading.Tasks;
namespace WebApplication1.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class AuthController : ControllerBase
{
private readonly AppDbContext _context;
public AuthController(AppDbContext context)
{
_context = context;
}
[HttpPost("register")]
public async Task<IActionResult> Register(User user)
{
if (ModelState.IsValid)
{
_context.Users.Add(user);
await _context.SaveChangesAsync();
return Ok("User registered successfully.");
}
return BadRequest("Invalid model state.");
}
[HttpPost("login")]
public async Task<IActionResult> Login(User user)
{
var existingUser = await _context.Users.FirstOrDefaultAsync(u => u.Username == user.Username && u.Password == user.Password);
if (existingUser != null)
{
return Ok("Login successful.");
}
return BadRequest("Invalid username or password.");
}
}
}
```
AppDbContext.cs:
```
using Microsoft.EntityFrameworkCore;
using WebApplication1.Models;
namespace WebApplication1.Data
{
public class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(options)
{
public DbSet<User> Users { get; set; }
}
}
```
Part of Startup.cs:
```
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<AppDbContext>(options =>
options.UseNpgsql(Configuration.GetConnectionString("DefaultConnection")));
services.AddControllers();
}
```
appsettings.json:
```
{
"ConnectionStrings": {
"DefaultConnection": "Host=localhost;Port=5432;Database=database;Username=postgres;Password=qwertyps4;"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
```
And finally model User.cs:
```
using System.ComponentModel.DataAnnotations;
namespace WebApplication1.Models
{
public class User
{
public int Id { get; set; }
[Required]
public string Username { get; set; }
[Required]
public string Password { get; set; }
}
}
```
I have checked all the files several times, but I just can't figure out the problem. |
I am a newbie to c# and ASP.NET Core. I have an issue with connection of my web application to PostgreSQL |
|c#|asp.net-mvc|postgresql|connection| |
null |
[enter image description here][1]I have a block of code that creates a modal window and styles for it. I need to make sure that the styles of the modal window are not affected by the rest of the table styles, because the modal window is not displayed as expected. For example, there is a style for the body and because of this my modal window does not appear on the entire page, since the body contains a style for maximum width. I need to make the styles for the modal window work separately from the general styles and they do not affect each other. In picture one you can see that the window opens halfway, and in picture two there is a style for the body that prevents it from opening completely. Below is the modal window code and its styles.
Modal Window:
```
// Создаем HTML для модального окна
const modalHTML = `
<!-- Модальное окно -->
<div id="mmyMModal" class="mmodalWWindow">
<div class="mmodal-ccontent">
<p id="eerror-ttitle" class="mmodal-ttext"></p>
<div class="success_icon">
<p>X</p>
</div>
<span class="ccloseWWindow">×</span>
<p id="mmodalTText" class="mmodal-ttext"></p>
</div>
</div>
`;
```
Style:
```
const modalStyle = document.createElement('style');
modalStyle.textContent = `
#mmyMModal {
display: none;
position: fixed;
z-index: 9999;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgba(0, 0, 0, 0.4);
animation: fadeIn 0.5s ease;
}
#mmyMModal .mmodal-ccontent {
position: relative;
background-color: #fefefe;
margin: 15% auto;
padding: 20px;
border: 1px solid #888;
width: 40%;
max-width: 600px;
text-align: center;
font-weight: 800;
color: black;
border-radius: 10px;
font: 700 48px/64px Roboto, sans-serif;
}
#mmyMModal .ccloseWWindow {
color: #aaa;
position: absolute;
top: -10px;
right: 10px;
font-size: 28px;
font-weight: bold;
cursor: pointer;
z-index: 9999;
}
#mmyMModal .ccloseWWindow:hover,
#mmyMModal .ccloseWWindow:focus {
color: black;
text-decoration: none;
}
#mmyMModal .mmodal-ttext {
font-size: 24px;
line-height: 1.6;
}
#mmyMModal .success_icon {
display: flex;
justify-content: center;
align-items: center;
margin: 20px auto;
}
#mmyMModal .success_icon p {
display: flex;
justify-content: center;
align-items: center;
font-size: 50px;
color: #fff;
width: 100px;
height: 100px;
border-radius: 50%;
text-align: center;
line-height: 100px;
transform: scale(1);
margin: 0;
transition: all 0.3s ease;
position: relative;
}
#mmyMModal .success_icon p::before {
content: "";
font-size: 50px;
color: #fff;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
display: flex;
justify-content: center;
align-items: center;
}
#mmyMModal .success_icon p::after {
content: "";
position: absolute;
width: 100%;
height: 100%;
border-radius: 50%;
background-color: #ef2c2c;
z-index: -1;
}
```
I tried using priority, pseudo-elements: before, after and nothing helped. I expected modal window styles to work regardless of other styles
[1]: https://i.stack.imgur.com/pQbYj.png |
I have created a database that has one table that keeps track of employee skills and another which displays projects that these employees can be assigned to. I need to have multiple employees asigned to the same project but i do not know how i would do this and when i try to use query to fill in this space with anything that meets these requirements, i get an error for returning multiple rows.
here is the query code
```
UPDATE projects
SET POOL_ID = (
SELECT skills.POOL_ID
FROM skills
WHERE skills.Skill_Name = 'JavaScript'
AND skills.POOL_ID IS NOT NULL
)
WHERE PROJECT_ID = 1;
```
Thanks for any help, I am new to SQL and as such dont know if this is even possible
but ive googled it and cannot find any help there and ive also tried adjusting the query etc |
Starting the development server...
Error: error:0308010C:digital envelope routines::unsupported
at new Hash (node:internal/crypto/hash:68:19)
at Object.createHash (node:crypto:138:10)
at module.exports (E:\Farooq\Software Development\React JS Project\ReactWebSite\react_website\node_modules\webpack\lib\util\createHash.js:90:53)
at NormalModule._initBuildHash (E:\Farooq\Software Development\React JS Project\ReactWebSite\react_website\node_modules\webpack\lib\NormalModule.js:401:16)
at handleParseError (E:\Farooq\Software Development\React JS Project\ReactWebSite\react_website\node_modules\webpack\lib\NormalModule.js:449:10)
at E:\Farooq\Software Development\React JS Project\ReactWebSite\react_website\node_modules\webpack\lib\NormalModule.js:481:5
at E:\Farooq\Software Development\React JS Project\ReactWebSite\react_website\node_modules\webpack\lib\NormalModule.js:342:12
at E:\Farooq\Software Development\React JS Project\ReactWebSite\react_website\node_modules\loader-runner\lib\LoaderRunner.js:373:3
at iterateNormalLoaders (E:\Farooq\Software Development\React JS Project\ReactWebSite\react_website\node_modules\loader-runner\lib\LoaderRunner.js:214:10)
at iterateNormalLoaders (E:\Farooq\Software Development\React JS Project\ReactWebSite\react_website\node_modules\loader-runner\lib\LoaderRunner.js:221:10)
at E:\Farooq\Software Development\React JS Project\ReactWebSite\react_website\node_modules\loader-runner\lib\LoaderRunner.js:236:3
at runSyncOrAsync (E:\Farooq\Software Development\React JS Project\ReactWebSite\react_website\node_modules\loader-runner\lib\LoaderRunner.js:130:11)
at iterateNormalLoaders (E:\Farooq\Software Development\React JS Project\ReactWebSite\react_website\node_modules\loader-runner\lib\LoaderRunner.js:232:2)
at Array.<anonymous> (E:\Farooq\Software Development\React JS Project\ReactWebSite\react_website\node_modules\loader-runner\lib\LoaderRunner.js:205:4)
at Storage.finished (E:\Farooq\Software Development\React JS Project\ReactWebSite\react_website\node_modules\enhanced-resolve\lib\CachedInputFileSystem.js:55:16)
at E:\Farooq\Software Development\React JS Project\ReactWebSite\react_website\node_modules\enhanced-resolve\lib\CachedInputFileSystem.js:91:9
E:\Farooq\Software Development\React JS Project\ReactWebSite\react_website\node_modules\react-scripts\scripts\start.js:19
throw err;
^
Error: error:0308010C:digital envelope routines::unsupported
at new Hash (node:internal/crypto/hash:68:19)
at Object.createHash (node:crypto:138:10)
at module.exports (E:\Farooq\Software Development\React JS Project\ReactWebSite\react_website\node_modules\webpack\lib\util\createHash.js:90:53)
at NormalModule._initBuildHash (E:\Farooq\Software Development\React JS Project\ReactWebSite\react_website\node_modules\webpack\lib\NormalModule.js:401:16)
at E:\Farooq\Software Development\React JS Project\ReactWebSite\react_website\node_modules\webpack\lib\NormalModule.js:433:10
at E:\Farooq\Software Development\React JS Project\ReactWebSite\react_website\node_modules\webpack\lib\NormalModule.js:308:13
at E:\Farooq\Software Development\React JS Project\ReactWebSite\react_website\node_modules\loader-runner\lib\LoaderRunner.js:367:11
at E:\Farooq\Software Development\React JS Project\ReactWebSite\react_website\node_modules\loader-runner\lib\LoaderRunner.js:233:18
at context.callback (E:\Farooq\Software Development\React JS Project\ReactWebSite\react_website\node_modules\loader-runner\lib\LoaderRunner.js:111:13)
at E:\Farooq\Software Development\React JS Project\ReactWebSite\react_website\node_modules\babel-loader\lib\index.js:51:103 {
opensslErrorStack: [ 'error:03000086:digital envelope routines::initialization error' ],
library: 'digital envelope routines',
reason: 'unsupported',
code: 'ERR_OSSL_EVP_UNSUPPORTED'
}
Node.js v20.11.1
PS E:\Farooq\Software Development\React JS Project\ReactWebSite\react_website\public>
i want to resolve this issue |
i have installed react bootstrap in my terminal but i have found this error |
|reactjs|react-bootstrap| |
null |
I have so many problems trying to install some mail clients like Squirrel or postfix ...
I try to install a mail client but i recieve so many fails like cannot conect smtp server or similars and in squirrel only shows a white screen instead the client.
Can someone make a guide to install it please ? |
How can i install a mail client in ubuntu? |
|phpmailer| |
null |
|yaml|swagger|documentation| |
at least in 2024 the real reason is "forms" included in the tailwind config, if you remove it from the plugins section, outlines are back to normal and elements are not bloated in size ignoring e.g. box sizing and other odd things. |
I'm attempting to send a PATCH request as follows, convert it to PSR7 and then validate the request using OpenAPI PSR-7 Message (HTTP Request/Response) Validator, which fails with the following message, "Schema(or data) validation failed: All of the required rules must pass for `{ }`".
I suspect its the request itself, or how I'm using the Symfony PSR bridge.
curl -X PATCH "http://local.domain/api/v1/path/a60360dc-a32e-49a1-bf03-20bf8c2bbbdf" -H "Content-Type: application/json" -H "Accept: application/json" -d '{"property":"value"}'
And converting the HttpFoundation to PSR7 as follows:
$psr17Factory = new \GuzzleHttp\Psr7\HttpFactory();
$psrHttpFactory = new \Symfony\Bridge\PsrHttpMessage\Factory\PsrHttpFactory($psr17Factory, $psr17Factory, $psr17Factory, $psr17Factory);
/** @var \Symfony\Component\HttpFoundation\Request $request */
$psrRequest = $psrHttpFactory->createRequest($request);
When debugging, the request $body from PsrHttpFactory::createRequest() [here][1] (note the 2.2.0 version), appears as seen in the attached screenshot.
[![enter image description here][2]][2]
However, after the conversion, I get the following.
$psrRequest->getParsedBody() is an empty array.
$psrRequest->getBody()->getContents() is an empty string.
[1]: https://github.com/symfony/psr-http-message-bridge/blob/v2.2.0/Factory/PsrHttpFactory.php#L70
[2]: https://i.stack.imgur.com/Sts0f.png |
It's not possible yet (March 2024), but it will be soon!
Check out this [Microsoft Blog post about upcoming `GROUPBY` and `PIVOTBY` functions][1] (currently in beta versions).
As part of implementing these functions, they've discuss **Functions as Arguments** - basically using `LAMBDA` functions. Many existing functions like `SUM`, `AVERAGE`, `MAX` and `MIN` can simply be selected from a list:
[![Selecting SUM from a dropdown list of summary functions][2]][2]
**Plus** they've added this functionality to all the existing functions that currently use `LAMBDA`s!
[![Demonstrating using functions as arguments][3]][3]
I'm very excited to see this roll out to general availability. But in the meantime, your approach of defining a simple lambda for sum, (and count, max, min...) is probably the best way to go.
I've gone with an "L." prefix (for lambda) myself:
```
L.Sum = LAMBDA(x, sum(x));
L.Max = LAMBDA(x, max(x));
L.Min = LAMBDA(x, min(x));
L.Count = LAMBDA(x, count(x));
L.CountA = LAMBDA(x, counta(x));
```
Function Currying
-----------------
Lastly, there is an approach referred to as function 'currying', which I've read about (but not experienced in). It's where you have a function that returns a *function* as a result. So it would be possible to write just a single function that depending on the parameters you pass would be equivalent to a `sum(x)` or `count(x)` function, or even `textjoin(",", x)` or `textjoin("|", x)`. While I don't have an implementation completed, you could imagine a large `IFS` block. Then you could use it like this:
```
=BYCOL(A2:F9, Summary("sum"))
=BYCOL(A2:F9, Summary("count"))
=BYCOL(A2:F9, Summary("max"))
=BYCOL(A2:F9, Summary("textjoin",","))
=BYCOL(A2:F9, Summary("textjoin","|"))
```
Now all you have to do is write the function...!
```
Summary = lambda(func,[optparam],
lambda(x,
ifs(
func="sum",sum(x),
func="max",max(x),
func="min",min(x),
func="count",count(x),
func="textjoin",textjoin(optparam,true,x),
"else"="else",NA()
)
)
);
```
And **it works!!!**
[![A function currying with Excel Lambda functions][4]][4]
This [FlexYourData post][5] may be the only reference online to function currying in Excel. Well, was - this may be the second. :-)
[1]: https://techcommunity.microsoft.com/t5/excel-blog/new-aggregation-functions-groupby-and-pivotby/ba-p/3965765
[2]: https://i.stack.imgur.com/U2Iv3.png
[3]: https://i.stack.imgur.com/YLiKo.gif
[4]: https://i.stack.imgur.com/QPXEU.png
[5]: https://www.flexyourdata.com/blog/excel-lambda-simplified-rolling-aggregate-of-any-function/
|
[enter image description here][1]I created a return icon while designing, but this text appeared on it. what is this text and how do I solve it?
there does not seem to be an error in my code, I searched the internet but could not find any results.I don't know how to investigate.
[1]: https://i.stack.imgur.com/V1z9V.png |
```
const Slider = () => {
const [activeIndex, setActiveIndex] = useState(0);
const handleSlideChange = (swiper) => {
setActiveIndex(swiper.activeIndex);
};
return (
<div className="slider-container">
<Swiper
spaceBetween={30}
centeredSlides={true}
autoplay={{
delay: 4500,
disableOnInteraction: false,
}}
pagination={{
clickable: true,
}}
navigation={true}
loop={true}
initialSlide={0}
modules={[Autoplay, Pagination, Navigation]}
onSlideChange={handleSlideChange}>
{[
<SlideOne isActive={activeIndex === 0} />,
<SlideTwo isActive={activeIndex === 1} />,
<SlideThree isActive={activeIndex === 2} />,
].map((Slide, index) => (
<SwiperSlide key={index} className="swiper-slider">
{Slide}
</SwiperSlide>
))}
</Swiper>
</div>
);
};
export default Slider;
```
I want the loop mode of the swiper to be on, but I cannot trigger the animations I made with gsap while the loop is on. I defined a state to specify the activeIndex, but it does not work because indexing is not done while the loop is on. |
The above answer is close. You need to add widgets to the Panel or Frame and not the Layout itself. The Layout just tells the panels/frames how to organize the widgets added to it.
panel.setLayout(new GridLayout(1,2));
panel.add(<your panel widget>); |
I'm just curious. Do you remember `$(elem).data('somekey', 'somevalue')`, when used NOT for `data-attributes`, but for storing arbitrary values/objects on the jquery element? In fact, data() was used to store anything, often entire object instancies 'on the element'.
It was used a lot and quite handy. Is there any vanilla javascript counterpart? Or, how can that functionality be replicated with vanilla js? |
jquery's data() [storage object] in vanilla javascript? |
|javascript|jquery| |
Based on the comments I think that the problem why the first instance Multi (Maybe a) (Fam a) does not work and if the second one is due to the memory allocation why when you implement this solution it works
```hs
instance (b ~ Fam a) => Multi (Maybe a) b
```
because in this one you are moving (b ~ Fam a) to Multi (Maybe a) where b remains as a reserve
but that's my thinking |
null |
I have a SSRS report that I need to export as PPT file
In order to generate the slides, I put rectangles of the exact size of a slide in cm (33.867 x 19.05 cm), for each slide with the necessary content inside
There is a footer on each page (2cm) so each rectangle has a height of 17,05cm instead of 19,05
I removed margin and make sure report size is greater than body size
I don't know why but i'm not able to export it as I need, one rectangle for each page, there are always blank pages and first rectangle is printing on 2 pages for example
[image export ppt](https://i.stack.imgur.com/KJpIA.png)
Thanks in advance for the help
Search on stackoverflow if this problem has already been described |
SSRS report exporting as PPT file |
|reporting-services|export|powerpoint| |
null |
Ok. So while I was working to my current Android Jetpack Compose project, I managed to get stuck on the following concept related to property delegates, more exactly the keyword "by".
I've already read this post on stackoverflow which was pretty well received:
[Difference between "remember" and "MutableState" in JetpackCompose][1]
Here it says:
[![enter image description here][2]][2]
I've also looked on some other sites trying to better understand the topic:
[kotlin delegated properties][3]
[remember mutableStateOf a cheatsheet][4]
Finally, all I want to understand is if there is a difference between these 2 declarations or they do the same thing:
val showA: MutableState<Boolean> = remember { mutableStateOf(true) }
and
val showA: MutableState<Boolean> by remember { mutableStateOf(true) }
There are plenty of resources that talk about this subject, but I think a summarizing answer would be of big use. So, what is the role of using "by" in such constructs and why does Android Studio throws the following error when using the second code sample making the Alt + Enter option for importing not work:
> Property delegate must have a 'getValue(Nothing?, KProperty*>)' method. None of the following functions are suitable. Import operator State.getValue()
[1]: https://stackoverflow.com/questions/66169601/what-is-the-difference-between-remember-and-mutablestate-in-android-jetpack
[2]: https://i.stack.imgur.com/cpAYm.png
[3]: https://kotlinlang.org/docs/delegated-properties.html
[4]: https://dev.to/zachklipp/remember-mutablestateof-a-cheat-sheet-10ma |
When the loop mode is on in Swiper, animations are not triggered in Gsap animation because they cannot be indexed. How can I do it? |