instruction stringlengths 0 30k ⌀ |
|---|
null |
ill try to get my first laravel Project running and im using an SQL Server . Ill have just installed sqlsrv and my normal connections do work. But in Laravel ill get a error message "could not find driver" when i i run the enviroment server with "artisan serve"
error message:
Illuminate
\
Database
\
QueryException
PHP 8.2.15
11.0.8
could not find driver
SELECT
top 1 *
FROM
[ sessions ]
WHERE
[ id ] = FnziuCl4Bh7mfDbUW4F3E0OQKfryNLEd21vPSyF3
my php.ini shows me that sqlsrv is enabled
sqlsrv
sqlsrv support enabled
ExtensionVer 5.11.1+17301
Directive Local Value Master Value
sqlsrv.ClientBufferMaxKBSize 10240 10240
sqlsrv.LogSeverity 0 0
sqlsrv.LogSubsystems 0 0
sqlsrv.WarningsReturnAsErrors On On`
my .env look like this:
DB_CONNECTION=sqlsrv
DB_HOST=192.168.xx.xx
DB_PORT=1433
DB_DATABASE=webdev_laravel
DB_USERNAME=webdev_applikation
DB_PASSWORD=password
ill tried
- server restart
- clear cache
i read a lot of other threads with the same error but i dont want to use .PDO and i think its optional , or isnt it ?
Thank you guys
|
There are 8 Linux namespaces which isolates PIDs, Network, Users, etc.
https://man7.org/linux/man-pages/man7/namespaces.7.html
It allows a namespaced process to have independent PIDs, network devices, users, etc.
They are kernel resources but only visible within one specific namespace.
They are guaranteed to not affect other processes.
However BPF code is not. Once injected in one namespace it has access to everything.
Is there a need for BPF namespace? |
Is there a need for BPF Linux namespace? |
|linux|security|linux-kernel|linux-namespaces| |
when click matlab Registration(use the NFRI function),occur matlab has encountered an internal problem needs to close.
[click matlab Registration(use the NFRI function)][1]
this is the error detail.
```
------------------------------------------------------------------------
Access violation detected at Sun Mar 31 11:08:39 2024
------------------------------------------------------------------------
Configuration:
Crash Decoding : Disabled
Default Encoding : GBK
MATLAB Architecture: win64
MATLAB Root : E:\Matlab2013b\Mingchuan Matlab2013B\matlab2013
MATLAB Version : 8.2.0.701 (R2013b)
Operating System : Microsoft Windows 8
Processor ID : x86 Family 175 Model 80 Stepping 0, AuthenticAMD
Virtual Machine : Java 1.7.0_11-b21 with Oracle Corporation Java HotSpot(TM) 64-Bit Server VM mixed mode
Window System : Version 6.2 (Build 9200)
Fault Count: 2
Abnormal termination:
Illegal instruction
Register State (from fault):
RAX = 0000000096366000 RBX = 0000000096367000
RCX = 00000000043ef6b0 RDX = 0000000096797800
RSP = 00000000043ef4c0 RBP = 00000000043eff80
RSI = 00000000043eff88 RDI = 00000000043eff80
R8 = 0000000000000080 R9 = 0000000096367000
R10 = 0000000000000780 R11 = 0000000000000280
R12 = 0000000000000004 R13 = 0000000000000048
R14 = 0000000000000004 R15 = 0000000000000004
RIP = 00000001317805b2 EFL = 00010212
CS = 0033 FS = 0053 GS = 002b
Stack Trace (from fault):
[ 0] 0x00000001317805b2 E:\Matlab2013b\Mingchuan Matlab2013B\matlab2013\bin\win64\mkl.dll+24642994 xerbla+22640098
[ 1] 0x0000000130dbd484 E:\Matlab2013b\Mingchuan Matlab2013B\matlab2013\bin\win64\mkl.dll+14406788 xerbla+12403892
[ 2] 0x0000000130db2db8 E:\Matlab2013b\Mingchuan Matlab2013B\matlab2013\bin\win64\mkl.dll+14364088 xerbla+12361192
[ 3] 0x00000001300d10e5 E:\Matlab2013b\Mingchuan Matlab2013B\matlab2013\bin\win64\mkl.dll+00856293 mkl_cbwr_set+00472453
[ 4] 0x0000000130019d5a E:\Matlab2013b\Mingchuan Matlab2013B\matlab2013\bin\win64\mkl.dll+00105818 dgemm+00000362
[ 5] 0x000000005d0eac3b E:\Matlab2013b\Mingchuan Matlab2013B\matlab2013\bin\win64\libmwmathlinalg.dll+00437307 UMFPACK_ComplexLUFactor::extractFactors+00103211
[ 6] 0x000000005d0eb21d E:\Matlab2013b\Mingchuan Matlab2013B\matlab2013\bin\win64\libmwmathlinalg.dll+00438813 mfMatrixMult+00000125
[ 7] 0x000000005d0ecec3 E:\Matlab2013b\Mingchuan Matlab2013B\matlab2013\bin\win64\libmwmathlinalg.dll+00446147 mfMatrixMult+00007459
[ 8] 0x000000005d0ecfd6 E:\Matlab2013b\Mingchuan Matlab2013B\matlab2013\bin\win64\libmwmathlinalg.dll+00446422 mfMatrixMult+00007734
[ 9] 0x000000005d0ed1e3 E:\Matlab2013b\Mingchuan Matlab2013B\matlab2013\bin\win64\libmwmathlinalg.dll+00446947 mfMatrixMult+00008259
[ 10] 0x000000018000d7ff E:\Matlab2013b\Mingchuan Matlab2013B\matlab2013\bin\win64\m_dispatcher.dll+00055295 Mfh_file::dispatch_fh+00001167
[ 11] 0x000000018000ddb7 E:\Matlab2013b\Mingchuan Matlab2013B\matlab2013\bin\win64\m_dispatcher.dll+00056759 Mfunction_handle::dispatch+00000487
[ 12] 0x0000000011c268a7 E:\Matlab2013b\Mingchuan Matlab2013B\matlab2013\bin\win64\m_interpreter.dll+00420007 inFunctionHandleInterface::DestroyWorkspace+00242727
[ 13] 0x0000000011c29b38 E:\Matlab2013b\Mingchuan Matlab2013B\matlab2013\bin\win64\m_interpreter.dll+00432952 inFunctionHandleInterface::DestroyWorkspace+00255672
```
1、uninstall and reinstall,but also occur
expect result:
can run success
[1]: https://i.stack.imgur.com/Qrhob.jpg |
Problem with a simple code to open windows file explorer on Pycharm |
|python|pycharm| |
null |
It's likely that Firefox is not looking for your `userChrome.css` on startup.
1. Open up a tab and navigate to `about:config` and click `Accept the Risk and Continue`.
2. In the `Search for Preference` box type `userprof`.
3. It should find the `toolkit.legacyUserProfileCustomizations.stylesheets` option. Just click the `toggle` button on the far right to change the setting to `true`.
4. Modify your `userChrome.css` to this:
````css
.tab-background[selected] {
background-color: #dd9933 !important;
background-image: none !important;
}
````
5. Restart your browser.
**Note**: looking with the Browser Toolbox it would appear that Firefox adds a `selected=""` attribute to the currently selected tab which is why your css selector of `.tab-background[selected="true"]` no loger works. |
|amazon-web-services|terraform|aws-route53| |
I would like to leverage [Vue3 Suspense](https://vuejs.org/guide/built-ins/suspense.html#combining-with-other-components) to initiate a loading state at the parent level that triggers animations in the children. When the request resolves at the parent level, I would like to remove the animation from the children.
App Header:
```pug
router-view(v-slot="{ Component, route }")
template(v-if="Component")
transition(:name="route.meta.transition" appear)
KeepAlive
Suspense
component(:is="Component")
template(#fallback='')
div.loading-div LOADING !!
```
Parent Template:
```javascript
<template lang="pug">
section.discover-row
div.discover-row-carousel
DiscoverItem(
v-for="(item, index) in DiscoverItemStore.automobiles"
:key="item._id"
:item="item"
:index="index"
)
</template>
<script setup>
...
import { useDiscoverItemStore } from "@/stores/DiscoverItemStore"
const DiscoverItemStore = useDiscoverItemStore()
DiscoverItemStore.fetchItems()
</script>
```
Child Template:
```pug
Suspense
template(#default='')
div.item SHOW SOME STUFF
template(#fallback='')
div.loading-div CHILD LOADING !!
```
—
Request (from pinia store):
```javascript
async fetchItems() {
this.automobiles = []
this.items = []
this.loading = true
try {
this.items = await fetch(discoverUrl)
.then((response) => response.json())
this.automobiles = [...this.items.Cars, ...this.items.Suvs, ...this.items.Trucks, ...this.items.Vans]
this.loading = false
...
```
————————————————————
How can I trigger the loading state at the parent level then show `CHILD LOADING !!` on each child instance until the request to `fetchItems()` at the parent level is resolved?
[Here's a codesandbox](https://codesandbox.io/p/github/nickbewley/base-app/master?file=%2F.codesandbox%2Ftasks.json&layout=%257B%2522sidebarPanel%2522%253A%2522GIT%2522%252C%2522rootPanelGroup%2522%253A%257B%2522direction%2522%253A%2522horizontal%2522%252C%2522contentType%2522%253A%2522UNKNOWN%2522%252C%2522type%2522%253A%2522PANEL_GROUP%2522%252C%2522id%2522%253A%2522ROOT_LAYOUT%2522%252C%2522panels%2522%253A%255B%257B%2522type%2522%253A%2522PANEL_GROUP%2522%252C%2522contentType%2522%253A%2522UNKNOWN%2522%252C%2522direction%2522%253A%2522vertical%2522%252C%2522id%2522%253A%2522cltyr42a000063b6hop3vnc98%2522%252C%2522sizes%2522%253A%255B82.05364273817773%252C17.94635726182227%255D%252C%2522panels%2522%253A%255B%257B%2522type%2522%253A%2522PANEL_GROUP%2522%252C%2522contentType%2522%253A%2522EDITOR%2522%252C%2522direction%2522%253A%2522horizontal%2522%252C%2522id%2522%253A%2522EDITOR%2522%252C%2522panels%2522%253A%255B%257B%2522type%2522%253A%2522PANEL%2522%252C%2522contentType%2522%253A%2522EDITOR%2522%252C%2522id%2522%253A%2522cltyr42a000023b6h7ct2kh68%2522%257D%255D%257D%252C%257B%2522type%2522%253A%2522PANEL_GROUP%2522%252C%2522contentType%2522%253A%2522SHELLS%2522%252C%2522direction%2522%253A%2522horizontal%2522%252C%2522id%2522%253A%2522SHELLS%2522%252C%2522panels%2522%253A%255B%257B%2522type%2522%253A%2522PANEL%2522%252C%2522contentType%2522%253A%2522SHELLS%2522%252C%2522id%2522%253A%2522cltyr42a000043b6hvkcmbaoi%2522%257D%255D%252C%2522sizes%2522%253A%255B100%255D%257D%255D%257D%252C%257B%2522type%2522%253A%2522PANEL_GROUP%2522%252C%2522contentType%2522%253A%2522DEVTOOLS%2522%252C%2522direction%2522%253A%2522vertical%2522%252C%2522id%2522%253A%2522DEVTOOLS%2522%252C%2522panels%2522%253A%255B%257B%2522type%2522%253A%2522PANEL%2522%252C%2522contentType%2522%253A%2522DEVTOOLS%2522%252C%2522id%2522%253A%2522cltyr42a000053b6h1o64ma4y%2522%257D%255D%252C%2522sizes%2522%253A%255B100%255D%257D%255D%252C%2522sizes%2522%253A%255B63.411808788319505%252C36.588191211680495%255D%257D%252C%2522tabbedPanels%2522%253A%257B%2522cltyr42a000023b6h7ct2kh68%2522%253A%257B%2522id%2522%253A%2522cltyr42a000023b6h7ct2kh68%2522%252C%2522tabs%2522%253A%255B%257B%2522type%2522%253A%2522FILE%2522%252C%2522filepath%2522%253A%2522%252F.codesandbox%252Ftasks.json%2522%252C%2522id%2522%253A%2522cltyr752600bz3b6h1ye1022s%2522%252C%2522mode%2522%253A%2522permanent%2522%252C%2522state%2522%253A%2522IDLE%2522%257D%255D%252C%2522activeTabId%2522%253A%2522cltyr752600bz3b6h1ye1022s%2522%257D%252C%2522cltyr42a000053b6h1o64ma4y%2522%253A%257B%2522id%2522%253A%2522cltyr42a000053b6h1o64ma4y%2522%252C%2522tabs%2522%253A%255B%257B%2522type%2522%253A%2522TASK_PORT%2522%252C%2522taskId%2522%253A%2522serve%2522%252C%2522port%2522%253A8080%252C%2522id%2522%253A%2522cltyr5z50009b3b6hd31reiv0%2522%252C%2522mode%2522%253A%2522permanent%2522%252C%2522path%2522%253A%2522%252F%2522%257D%255D%252C%2522activeTabId%2522%253A%2522cltyr5z50009b3b6hd31reiv0%2522%257D%252C%2522cltyr42a000043b6hvkcmbaoi%2522%253A%257B%2522id%2522%253A%2522cltyr42a000043b6hvkcmbaoi%2522%252C%2522activeTabId%2522%253A%2522cltyr5wz000773b6hg3xybtjb%2522%252C%2522tabs%2522%253A%255B%257B%2522id%2522%253A%2522cltyr42a000033b6h6ta117c7%2522%252C%2522mode%2522%253A%2522permanent%2522%252C%2522type%2522%253A%2522TERMINAL%2522%252C%2522shellId%2522%253A%2522cltyr43al001udlji66oo36h1%2522%257D%252C%257B%2522type%2522%253A%2522TASK_LOG%2522%252C%2522taskId%2522%253A%2522serve%2522%252C%2522id%2522%253A%2522cltyr5wz000773b6hg3xybtjb%2522%252C%2522mode%2522%253A%2522permanent%2522%257D%252C%257B%2522type%2522%253A%2522TASK_LOG%2522%252C%2522taskId%2522%253A%2522CSB_RUN_OUTSIDE_CONTAINER%253D1%2520devcontainer%2520templates%2520apply%2520--template-id%2520%255C%2522ghcr.io%252Fdevcontainers%252Ftemplates%252Fjavascript-node%255C%2522%2520--template-args%2520%27%257B%257D%27%2520--features%2520%27%255B%255D%27%2522%252C%2522id%2522%253A%2522clufrki4b00if3b6hq2hc5i8o%2522%252C%2522mode%2522%253A%2522permanent%2522%257D%255D%257D%257D%252C%2522showDevtools%2522%253Atrue%252C%2522showShells%2522%253Atrue%252C%2522showSidebar%2522%253Atrue%252C%2522sidebarPanelSize%2522%253A14.513888888888886%257D) that approximates the problem (see "home" tab). |
Vue3 Suspense Parent > Child Animation |
|javascript|vue.js|async-await|vuejs3|vue-suspense| |
I'm working with a new JavaFX project. I have legacy Swing control panels. When I try to do `new SwingNode`, I get an exception:
Caused by: java.lang.IllegalAccessError: superclass access check failed: class com.sun.javafx.embed.swing.SwingNodeHelper (in unnamed module @0x35dc99d5) cannot access class com.sun.javafx.scene.NodeHelper (in module javafx.graphics) because module javafx.graphics does not export com.sun.javafx.scene to unnamed module @0x35dc99d5
at java.base/java.lang.ClassLoader.defineClass1(Native Method)
at java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:1027)
at java.base/java.security.SecureClassLoader.defineClass(SecureClassLoader.java:150)
at java.base/jdk.internal.loader.BuiltinClassLoader.defineClass(BuiltinClassLoader.java:862)
at java.base/jdk.internal.loader.BuiltinClassLoader.findClassOnClassPathOrNull(BuiltinClassLoader.java:760)
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClassOrNull(BuiltinClassLoader.java:681)
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:639)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:526)
at javafx.embed.swing.SwingNode.<clinit>(SwingNode.java:135)
at test.app.MJFXtest.start(MJFXtest.java:11)
This is on JavaFX v21. I tried 19, but still the same.
_______________
package test.app;
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.embed.swing.SwingNode;
public class MJFXtest extends Application {
@Override
public void start(Stage primaryStage) {
SwingNode sn = new SwingNode();
}
public static void main(String[] args) {
launch(args);
}
}
_________________
I expect this not to throw an exception on the new SwingNode(); line, but to create a new SwingNode.
I saw this Q/A about the same problem, but I have javafx-swing included in my pom file.
([https://stackoverflow.com/questions/55874607/the-class-swingnode-in-openjfx-causes-problems](https://stackoverflow.com))
This is the javafx section from pom.xml and it looks like all the relevant libraries are there.
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-controls</artifactId>
<version>21</version>
</dependency>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-fxml</artifactId>
<version>21</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.openjfx/javafx-swing -->
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-swing</artifactId>
<version>21</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.openjfx/javafx-web -->
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-web</artifactId>
<version>21</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.openjfx/javafx -->
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx</artifactId>
<version>21</version>
<type>pom</type>
</dependency>
Any assistance would be appreciated. Thank you. |
I am using an ASP.NET Core Web API with Entity Framework Core (pomelo). I have a MariaDB database. I use Swagger UI to explore my API, as per the template. When I try to use it to delete a row, I get the following error:
> Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while saving the entity changes. See the inner exception for details.
>
> MySqlConnector.MySqlException (0x80004005): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'RETURNING 1' at line 3
>
> at MySqlConnector.Core.ServerSession.ReceiveReplyAsync(IOBehavior ioBehavior, CancellationToken cancellationToken) in /_/src/MySqlConnector/Core/ServerSession.cs:line 894
at MySqlConnector.Core.ResultSet.ReadResultSetHeaderAsync(IOBehavior ioBehavior) in /_/src/MySqlConnector/Core/ResultSet.cs:line 37
at MySqlConnector.MySqlDataReader.ActivateResultSet(CancellationToken cancellationToken) in /_/src/MySqlConnector/MySqlDataReader.cs:line 130
at MySqlConnector.MySqlDataReader.InitAsync(CommandListPosition commandListPosition, ICommandPayloadCreator payloadCreator, IDictionary`2 cachedProcedures, IMySqlCommand command, CommandBehavior behavior, Activity activity, IOBehavior ioBehavior, CancellationToken cancellationToken) in /_/src/MySqlConnector/MySqlDataReader.cs:line 483
at MySqlConnector.Core.CommandExecutor.ExecuteReaderAsync(CommandListPosition commandListPosition, ICommandPayloadCreator payloadCreator, CommandBehavior behavior, Activity activity, IOBehavior ioBehavior, CancellationToken cancellationToken) in /_/src/MySqlConnector/Core/CommandExecutor.cs:line 56
at MySqlConnector.MySqlCommand.ExecuteReaderAsync(CommandBehavior behavior, IOBehavior ioBehavior, CancellationToken cancellationToken) in /_/src/MySqlConnector/MySqlCommand.cs:line 357
at MySqlConnector.MySqlCommand.ExecuteDbDataReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken) in /_/src/MySqlConnector/MySqlCommand.cs:line 350
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
The delete should be handled here in my controller and repository, like this:
[HttpDelete("alertId")]
public async Task<IActionResult> DeleteAlert(int alertId)
{
var alert = await _dataRepository.GetAlertAsync(alertId);
if (alert is null)
{
return NotFound("Alert not found");
}
await _dataRepository.DeleteAlertAsync(alert);
return NoContent();
}
and this
public class AlertRepository (IrtsContext context) : IDataRepositoryAlerts
{
readonly IrtsContext _alertContext = context;
public async Task DeleteAlertAsync(Alert entity)
{
if (entity != null)
{
_alertContext.Remove(entity);
await _alertContext.SaveChangesAsync();
}
else
{
throw new NotImplementedException();
}
}
}
I do not understand this. I believe it is my `dbContext` that handles the "saving the entity changes". How can I have a SQL syntax error? I cannot find "Returning 1" anywhere in my code.
I have tried deleting the row manually in my database. That works.
All other operations (GET, POST and PUT) work just fine.
I have tried running this with holding points to see where the error occurs but everything seems to execute without issue.
I am grateful for any hints. I am obviously very new to this ;)
Edit: MariaDB version 11.2.2
Edit2: This is my Alert class:
public partial class Alert
{
public int AlertId { get; set; }
public DateTime? Zeitpunkt { get; set; }
public string? Quelle { get; set; }
public string? AlertStatus { get; set; }
public string? AlertTyp { get; set; }
public string? BetroffeneSysteme { get; set; }
public virtual ICollection<Vorfall> Vorfalls { get; set; } = new List<Vorfall>();
}
and this is its entity configuration:
modelBuilder.Entity<Alert>(entity =>
{
entity.HasKey(e => e.AlertId).HasName("PRIMARY");
entity
.ToTable("alert")
.HasCharSet("utf8mb4")
.UseCollation("utf8mb4");
entity.Property(e => e.AlertId)
.HasColumnType("int(11)")
.HasColumnName("AlertID");
entity.Property(e => e.AlertStatus).HasMaxLength(255);
entity.Property(e => e.AlertTyp).HasMaxLength(255);
entity.Property(e => e.BetroffeneSysteme).HasMaxLength(255);
entity.Property(e => e.Quelle).HasMaxLength(255);
entity.Property(e => e.Zeitpunkt).HasColumnType("datetime");
});
edit3: I found the parameterized query. It goes thus:
[The error in the log with sql query]
[1]: https://i.stack.imgur.com/AFLB5.png
|
Guided by https://github.com/microsoft/vscode-python/issues/14639
---
I suggest to do the following steps:
1. **CTRL + P**
2. Search for **>Preferences: Open User Settings (JSON)** <br> - *(settings.json)* <br>
3. Add `"python.experiments.optInto": ["pythonDiscoveryModule"]`
4. Save the file
5. **View > Comand Palette** and running **Developer: Reload Window**
---
*Another option to monitor performance loss:*
- **help > toggle developer tools > performance tab > start recoding** |
accessibilitytools, wang's avi library and kprogresshud are very old libraries, originally hosted in jcenter but now not available anymore.
Working with old libraries is always difficult. My suggestion is to download the source code from github and try to integrate them into your project (if the license allows it). This comes, of course, with some risks or adjustments in the code.
For the Microsoft library, you can integrate the new one here: https://github.com/Azure/azure-notificationhubs-android
Hope this helps |
I have a relatively large PostgreSQL (v12) table storing JSONB data that has unintentional duplicate data (based on a composite unique index on two columns, `aCol` and `bCol`). In order to create that index, I have to first delete all of the accidental duplicates from the DB. This works fine in 2/3 of our DB servers (servers for different environments, i.e. Dev and Prod, all with the same DB schema), but in the 3rd the query will just never finish, and I've let it run for up to 2 hours (in the other environments it takes a matter of minutes).
I've tried configuring the resources and configuration settings to be the same in all environments; for example, the RAM, disk size and ops, CPU, `effective_io_concurrency`, etc. I've also compared the sizes of the tables and I don't think that's the issue, because one of the servers that does complete has ~2 million records for a total of ~9 GB while the one that fails has ~400,000 records for a total of ~2 GB.
The query in question is:
```sql
DELETE FROM aTable a USING aTable b
WHERE a.aCol = b.aCol
AND a.bCol = b.bCol
AND a.id != b.id
AND a.created_at <= b.created_at
```
I'm not a DBA or SQL expert by any means so I would definitely appreciate any insight into what else might be causing this query to hang in 1 specific environment, or whether there is a more efficient way to achieve what I'm trying to do that could potentially bypass the issue. Thanks in advance
**Edit:** In response to the comments, here are the explain plans for the queries in the two environments.
Working environment:
```
Delete on aTable a (cost=800504.63..5706702.06 rows=72439076 width=12)
-> Merge Join (cost=800504.63..5706702.06 rows=72439076 width=12)
Merge Cond: ((a.aCol = b.aCol) AND (a.bCol = b.bCol))
Join Filter: ((a.id <> b.id) AND (a.created_at <= b.created_at))
-> Sort (cost=400252.31..404391.52 rows=1655683 width=50)
Sort Key: a.aCol, a.bCol
-> Seq Scan on aTable a (cost=0.00..184763.83 rows=1655683 width=50)
-> Materialize (cost=400252.31..408530.73 rows=1655683 width=50)
-> Sort (cost=400252.31..404391.52 rows=1655683 width=50)
Sort Key: b.aCol, b.bCol
-> Seq Scan on aTable b (cost=0.00..184763.83 rows=1655683 width=50)
```
Failing environment:
```
Delete on aTable a (cost=0.00..1794266.00 rows=59613596 width=12)
-> Nested Loop (cost=0.00..1794266.00 rows=59613596 width=12)
-> Seq Scan on aTable a (cost=0.00..40365.00 rows=395600 width=50)
-> Index Scan using idx_aTable_aCol on aTable b (cost=0.00..4.42 rows=1 width=50)
Index Cond: (aCol = a.aCol)
Filter: ((a.id <> id) AND (a.created_at <= created_at) AND (a.bCol = bCol))
```
I notice that the failing table seems to be trying to use a hash index on `aCol`, though the tables in both environments have that exact same index. Not really sure what to make of that, because if anything, I figured that would've sped things up |
C++: undefined reference to `xxx` |
|c++|g++| |
My favorite list of [tips (explained in detail here)][1] is as follows
> 1. Try to restrict the queries result set by using the WHERE clause.
> 2. Try to restrict the queries result set by returning only the particular columns from the table, not all the table's columns.
> 3. Use views and stored procedures instead of heavy-duty queries. (This item usually does not apply to MySQL.)
> 4. Whenever possible, try to avoid using SQL Server or MySQL cursors. (SQL is shines when doing things in bulk.)
> 5. If you need to return the total table's row count, you can use an alternative way instead of the SELECT COUNT(*) statement.
> 6. Try to use constraints instead of triggers, whenever possible.
> 7. Use table variables (if available) instead of temporary tables.
> 8. Try to avoid the HAVING clause, whenever possible.
> 9. Whenever possible, try to avoid using the DISTINCT clause.
> 10. Include SET NOCOUNT ON statement into your stored procedures to stop the message indicating the number of rows affected by a T-SQL
> statement.
> 11. Use select statements with the TOP keyword or the SET ROWCOUNT statement if you need to return only the first n rows. (This is may
> not help much if there is an unavoidable `ORDER BY`.)
> 12. Use the FAST number_rows table hint if you need to quickly return 'number_rows' rows.
> 13. Try to use UNION ALL statement instead of UNION, whenever possible.
> 14. Do not use optimizer hints in your queries.
[1]: http://www.databasejournal.com/features/mssql/article.php/1437391/Transact-SQL-Optimization-Tips.htm |
I've been having the same issue and found that if you execute `which python` on your terminal window, you can validate which interpreter is being used (global or venv).
It's not as visual or friendly, but hope it helps. |
I found this interesting bot from James Bachini https://github.com/jamesbachini/Market-Maker-Bot. I tried on ETH Mainet and works fine then I tried on Sepolia Testenet and I got stuck in a CALL_EXCEPTION'
Here James Bachini's code with Sepolia change.
const ethers = require('ethers');`enter code here`
require("dotenv").config();
const wethAddress = '0xfFf9976782d46CC05630D1f6eBAb18b2324d6B14'; // sepolia weth
const routerAddress = '0x0227628f3F023bb0B980b67D528571c95c6DaC1c'; // Uniswap Router Sepolia
const quoterAddress = '0xEd1f6473345F45b75F8179591dd5bA1888cf2FB3'; // Uniswap Quoter Sepolia
const tokenAddress = '0x1f9840a85d5af5bf1d1762f925bdaddc4201f984'; // Uni Sepolia token
const fee = 3000; // Uniswap pool fee bps 500, 3000, 10000
const buyAmount = ethers.parseUnits('0.001', 'ether');
const targetPrice = BigInt(16); // target exchange rate
const targetAmountOut = buyAmount * targetPrice;
const sellAmount = buyAmount / targetPrice;
const tradeFrequency = 3600 * 1000; // ms (once per hour)
//const provider = new ethers.JsonRpcProvider(`https://eth-mainnet.g.alchemy.com/v2/${process.env.ALCHEMY_API_KEY}`);
const provider = new ethers.JsonRpcProvider(`https://eth-sepolia.g.alchemy.com/v2/${process.env.ALCHEMY_API_KEY}`);
provider.getBlockNumber().then(blockNumber => {
console.log('Connected to Sepolia network. Current block number:', blockNumber);
}).catch(error => {
console.error('Failed to connect to Sepolia network:', error);
});
const wallet = new ethers.Wallet(process.env.PRIVATE_KEY);
const account = wallet.connect(provider);
const token = new ethers.Contract(
tokenAddress,
[
'function approve(address spender, uint256 amount) external returns (bool)',
'function allowance(address owner, address spender) public view returns (uint256)',
],
account
);
const router = new ethers.Contract(
routerAddress,
['function exactInputSingle((address tokenIn, address tokenOut, uint24 fee, address recipient, uint256 deadline, uint256 amountIn, uint256 amountOutMinimum, uint160 sqrtPriceLimitX96)) external payable returns (uint256 amountOut)'],
account
);
const quoter = new ethers.Contract(
quoterAddress,
['function quoteExactInputSingle(address tokenIn, address tokenOut, uint24 fee, uint256 amountIn, uint160 sqrtPriceLimitX96) public view returns (uint256 amountOut)'],
account
);
const buyTokens = async () => {
console.log('Buying Tokens')
const deadline = Math.floor(Date.now() / 1000) + 600;
const tx = await router.exactInputSingle([wethAddress, tokenAddress, fee, wallet.address, deadline, buyAmount, 0, 0], {value: buyAmount});
await tx.wait();
console.log(tx.hash);
}
And the error:
Error: missing revert data (action="call", data=null, reason=null, transaction={ "data": "0xf7729d43000000000000000000000000fff9976782d46cc05630d1f6ebab18b2324d6b140000000000000000000000001f9840a85d5af5bf1d1762f925bdaddc4201f9840000000000000000000000000000000000000000000000000000000000000bb800000000000000000000000000000000000000000000000000038d7ea4c680000000000000000000000000000000000000000000000000000000000000000000", "from":
Thanks
|
I am simulating CPU scheduling algorithms for a class. I have a struct called job that contains the basic info for each job, and I'm trying to order a priority queue of these jobs in order from smallest number of cycles needed to largest number of cycles needed. This is currently my custom comparator to do that:
```
class CompareJobTime {
public:
bool operator()(job job1, job job2) {
if (job1.cycles < job2.cycles) {
return false;
}
else
return true;
}
};
```
and this is how I'm using it in the priority queue declaration:
` priority_queue<job, vector<job>, CompareJobTime> jobTPQ;`
This is the error it keeps throwing:
"Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.34.31933\include\xutility
Line:1096
Expression: invalid comparator"
Any help would be greatly appreciated, as I really don't have a clue where to go from here when it comes to debugging. Thanks!
I've tried changing up the definition in a couple ways, but I'm not sure what's wrong with it. I have also tried using decltype instead of a comparator class, but I couldn't get that to work since I was writing the comparator function as a member of the class this is all being written in. |
Error: id returned 5 exit status when building C++ code in Code::Blocks |
It would have been ideal to use hasManyThrough but this would mean some modifications to your schema.
However, you can achieve this result by chaining Eloquent relationships and a custom query.
For your example, you can do this by
getting all the role IDs of the user then getting all tasks associated with these roles and finally fiter schedules based on this ID'.
Or you can define a custom method on user to do same.
example with code.
```
// In your Schedule model
public static function getSchedulesForUser($user)
{
// Get the role IDs of the user
$roleIds = $user->roles()->pluck('id');
// Get tasks associated with these roles using Eloquent relationship
$tasks = Task::whereHas('roles', function ($query) use ($roleIds) {
$query->whereIn('id', $roleIds);
})->get();
// Extract task IDs from the tasks collection
$taskIds = $tasks->pluck('id');
// Return the schedules associated with these tasks
return self::whereIn('task_id', $taskIds)->get();
}
````
or
```
//in your User model
public function schedules()
{
// Get role IDs
$roleIds = $this->roles()->pluck('roles.id');
// Get task IDs associated with these roles
$taskIds = Task::whereHas('roles', function ($query) use ($roleIds) {
$query->whereIn('roles.id', $roleIds);
})->pluck('tasks.id');
// Return schedules associated with these tasks
return Schedule::whereIn('task_id', $taskIds)->get();
}
```
or
```
//directly in your controller
// Get the logged-in user
$user = Illuminate\Support\Facades\Auth::user();
// Get the role IDs of the logged-in user
$roleIds = $user->roles->pluck('id');
// Get the task IDs associated with these roles
$taskIds = DB::table('task_role')
->whereIn('role_id', $roleIds)
->pluck('task_id');
// Get the schedules associated with these tasks
$schedules = Schedule::whereIn('task_id', $taskIds)->get();
``` |
I have a microphone and speaker connect to a RPI inside an art sculpture, my objective is to record new audio clips of people talking into the mic while playing back 3 random recorded audio clips. It does work but the mic keeps picking up the feedback and echo from the speaker itself, how can I fix this? I cannot order new hardware since I need this by Monday.
```
import pygame
import random
import os
import sounddevice as sd
import numpy as np
import wave
import time
from threading import Thread, Lock
import pyaudio
import webrtcvad
# Function to record audio for a specified duration
def record_audio(filename, sample_rate=16000, chunk_duration_ms=30):
vad = webrtcvad.Vad(3) # Set aggressiveness from 0 to 3
format = pyaudio.paInt16
channels = 1
chunk_size = int(sample_rate * chunk_duration_ms / 1000)
audio = pyaudio.PyAudio()
stream = audio.open(format=format, channels=channels, rate=sample_rate, input=True, frames_per_buffer=chunk_size)
print("Listening for speech...")
frames = []
recording = False
silence_counter = 0
while True:
frame = stream.read(chunk_size)
is_speech = vad.is_speech(frame, sample_rate)
if recording:
frames.append(frame)
if len(frames) >= int(10 * 1000 / chunk_duration_ms): # 10 seconds of audio
# Save the recording
wf = wave.open(filename, 'wb')
wf.setnchannels(channels)
wf.setsampwidth(audio.get_sample_size(format))
wf.setframerate(sample_rate)
wf.writeframes(b''.join(frames))
wf.close()
print(f"Recording saved: {filename}")
return # Stop after saving one 10-second clip
if is_speech:
recording = True
silence_counter = 0
elif recording:
# Increment silence counter if no speech detected
silence_counter += 1
if silence_counter > int(3 * 1000 / chunk_duration_ms): # 3 seconds of silence
recording = False
frames.clear()
stream.stop_stream()
stream.close()
audio.terminate()
# Function to play a random 3-5 second interval from an available file on a given channel with random volume
def play_random_interval_on_channel(channel, current_files, playback_lock):
with playback_lock:
# Filter out files that are currently being played on any channel
available_files = [file for file in audio_files if file not in current_files.values()]
if not available_files:
return
file_path = random.choice(available_files)
sound = pygame.mixer.Sound(os.path.join(audio_files_dir, file_path))
sound_length = sound.get_length()
# Set start time to a random point within the audio clip's length
start_time = random.uniform(0, max(sound_length - 5, 0)) # Ensure there's enough time for a 3-5 second clip
duration = random.uniform(3, 5) # Duration between 3 and 5 seconds
volume = random.uniform(0.7, 1.0) # Random volume adjustment between 70% and 100%
# Adjust duration if it exceeds the available duration
if start_time + duration > sound_length:
duration = sound_length - start_time
sound.set_volume(volume) # Set the adjusted volume
# Ensure that the end time does not exceed the audio clip's length
end_time = min(start_time + duration, sound_length)
# Play the specified interval
sound.play()
# Delay to allow playing only the specified interval
pygame.time.delay(int(start_time * 1000))
# Stop the playback after the interval duration
pygame.time.delay(int((end_time - start_time) * 1000))
sound.stop()
with playback_lock:
# Update the current file being played on this channel
current_files[channel] = file_path
return file_path # Return the file being played
# Function to play tracks and record once simultaneously
def play_and_record(channel, recording_lock, current_files, playback_lock):
while True:
file = play_random_interval_on_channel(channel, current_files, playback_lock)
if file:
current_files[channel] = file
# Try to acquire the lock to ensure only one thread records at a time
if recording_lock.acquire(blocking=False):
try:
new_file_name = os.path.join(audio_files_dir, f"recording_{int(time.time())}.wav")
record_audio(new_file_name)
audio_files.append(new_file_name) # Add new recording to the playlist
finally:
recording_lock.release()
# Initialize pygame and the mixer
pygame.mixer.init()
# Directory containing the audio files
audio_files_dir = "/home/pi/Desktop/art_proj/mp3clips"
# List all files in the directory
audio_files = os.listdir(audio_files_dir)
# Initialize three channels
channels = [pygame.mixer.Channel(i) for i in range(4)]
# Create a lock to control recording access
recording_lock = Lock()
# Create a new lock for playback
playback_lock = Lock()
# Dictionary to track which file is playing on each channel
current_files = {}
# Start threads as daemon threads to play tracks and record on each channel
threads = [Thread(target=play_and_record, args=(channel, recording_lock, current_files, playback_lock), daemon=True) for channel in channels]
for thread in threads:
thread.start()
try:
while True:
pygame.time.Clock().tick(10)
except KeyboardInterrupt:
print("Stopping...")
pygame.quit()
```
|
How to reduce noise in recordings with a known audio file |
Your code has compile errors when I try to run with the version of `iverilog` that I have installed (10.3).
However, the code produces the expected output when I run with the Cadence and Synopsys simulators:
result_matrix[0] = 0.000000
result_matrix[1] = 0.000000
result_matrix[2] = 0.000000
result_matrix[3] = 0.000000
result_matrix[0] = 7.000000
result_matrix[1] = 10.000000
result_matrix[2] = 15.000000
result_matrix[3] = 22.000000
result_matrix[0] = 7.000000
result_matrix[1] = 10.000000
result_matrix[2] = 15.000000
result_matrix[3] = 22.000000
I think it is a bug in the version of `iverilog` you are using. Try your code on [EDA Playground][1].
---
It would be helpful to show the `$time` and hierarchy `%m` in your `$dsiplay` statements.
[1]: https://www.edaplayground.com/ |
Upgrade gradle to the latest version by modifying the url in gradle-wrapper.properties |
I'm asking how are labels managed by C.
EX:
if (false)
label: printf("HELLO ");
printf("WORLD ");
goto label;
Prints WORLD HELLO on GCC
is it undefined behavior? (the label definition isn't handled as an instruction by the compiler) |
`foo()` is taking in a primitive `int` *by value*, so it is a *copy* of whatever value you pass in. There is no reference.
It doesn't matter what `foo()` does to `y`, that value is not reflected back to the caller.
Also, there is no such thing as "point at a value", either. You can point at a variable, but not at a value.
> then `x` becomes 3 because `y=y+2` and `y` was pointing at the value 1 of `x`.
>
> `foo(a[x])` is called with `a[3]` (which doesnt exists). `x` is decremented to 2.
This is incorrect. It is `y`, not `x`, that becomes 3. `x` is still 0 at this point. So the subsequent call to `foo(a[x])` is using `a[0]` instead, which then decrements `x` to -1 and then sets `x` to 5. |
You have not set the `provider` and `registration` properties correctly for Keycloak:
- only `user-name-attribute` is present for `provider` conf, which is not enough
- `issuer-uri` is a `provider` property, not a `registration` one (your IDE should lint that)
- `issuer-uri` is probably `http://localhost:8080/realms/sdia3` (and not `http://localhost:8080/realms/sdia3/account`)
- when you're not using one of the "magic" ones (like `google`is), you should explicitly reference the `provider` to use in the `registration`
As Keycloak is OIDC compliant, setting `spring.security.oauth2.client.provider.keycloak.issuer-uri=` with the **exact value of the `iss` claim in one of your tokens** should be enough (even trailing slash, if any, and case are important). Spring will pull the rest of the conf from the `.well-known/openid-configuration`.
Here is the configuration you're probably looking for (in the YAML format):
```yaml
keycloak-issuer: http://localhost:8080/realms/sdia3
keycloak-client-secret: you-should-not-commit-this-in-git-or-post-it-on-stackoverflow
spring:
security:
oauth2:
client:
provider:
keycloak-provider:
issuer-uri: ${keycloak-issuer}
user-name-attribute: preferred_username
registration:
keycloak-authorization-code:
provider: keycloak-provider
authorization-grant-type: authorization_code
client-id: lient-cree-customer
client-secret: ${keycloak-client-secret}
scope: openid, profile, email, offline_access
client-name: keycloak
```
As you seem to be at the very beginning of your Spring with OAuth2 journey, you might find [this tutorials I wrote](https://github.com/ch4mpy/spring-addons/tree/master/samples/tutorials#securing-spring-applications-with-oauth2) useful. |
I am using an ESP232 devkit and i am trying to start an Access Point where i can enter WiFi data, which then is Used to setup a WiFi Webserver to control Data. But whenever i enter wrong wifi data, it sets of the WatchDog timer. When i enter the right WiFi Data it connects and works.
```
19:18:44:830 -> Trying to connect...
19:18:45:330 -> Trying to connect...
19:18:45:332 -> debug
19:18:45:333 -> debug4
19:18:50:330 -> E (20302) task_wdt: Task watchdog got triggered. The following tasks did not reset the watchdog in time:
19:18:50:339 -> E (20302) task_wdt: - async_tcp (CPU 0/1)
19:18:50:343 -> E (20302) task_wdt: Tasks currently running:
19:18:50:347 -> E (20302) task_wdt: CPU 0: IDLE
19:18:50:350 -> E (20302) task_wdt: CPU 1: loopTask
19:18:50:353 -> E (20302) task_wdt: Aborting.
19:18:50:356 ->
19:18:50:356 -> abort() was called at PC 0x400e8e95 on core 0
19:18:50:360 ->
19:18:50:360 ->
19:18:50:361 -> Backtrace: 0x4008389d:0x3ffbec3c |<-CORRUPTED
19:18:50:365 ->
19:18:50:365 ->
19:18:50:365 ->
19:18:50:365 ->
19:18:50:365 -> ELF file SHA256: 12c7e27a4eeae93f
19:18:50:368 ->
19:18:50:846 -> Rebooting...
19:18:50:848 -> ets Jul 29 2019 12:21:46
```
This is the code i use right now
```
void startAPMode() {
if (apmode == true) {
WiFi.mode(WIFI_AP_STA);
WiFi.softAP(apSSID, apPassword);
apServer.on("/", HTTP_GET, [](AsyncWebServerRequest* request) {
request->send(200, "text/html", ap_mode_html);
});
apServer.on("/setup", HTTP_GET, [](AsyncWebServerRequest* request) {
if (request->hasParam("ssid") && request->hasParam("password")) {
String ssid = request->getParam("ssid")->value();
String password = request->getParam("password")->value();
WiFi.begin(ssid.c_str(), password.c_str());
unsigned long startTime = millis();
bool connectionSuccessful = false;
while (millis() - startTime < 10000) {
esp_task_wdt_reset(); // Reset Watchdog Timer
if (WiFi.status() == WL_CONNECTED) {
connectionSuccessful = true;
break;
}
delay(500);
Serial.println("Versuche zu verbinden...");
}
//esp_task_wdt_reset();
Serial.println("debug");
if (connectionSuccessful) {
IPAddress wifiIP = WiFi.localIP();
String response = R"html(
<!DOCTYPE html>
<html>
<head>
<title>Verbindung Erfolgreich</title>
<style>
html, body { font-family: Arial, sans-serif; margin: 0; padding: 0; display: flex; justify-content: center; align-items: center; flex-direction: column; }
.container { padding: 20px; border: 1px solid #ddd; border-radius: 5px; background-color: #fff; box-shadow: 0 2px 4px rgba(0,0,0,0.1); max-width: 90%; }
.ip-address { font-weight: bold; margin-top: 20px; padding: 10px; background-color: #e9ecef; border-radius: 5px; }
</style>
</head>
<body>
<div class='container'>
Verbindung erfolgreich! Bitte diese IP Adresse aufschreiben oder merken. Über diese IP Adresse kann nun immer die Fenstersteuerung aufgerufen werden!
<div class='ip-address'>Die IP Adresse für die Webseite ist: )html" + wifiIP.toString() + R"html(</div>
</div>
</body>
</html>
)html";
request->send(200, "text/html", response);
Serial.println("debug2");
setupWiFiAndWebServer();
Serial.println("debug3");
}
else {
esp_task_wdt_reset();
Serial.println("debug4");
//WiFi.disconnect(); // Optional: trennt die Verbindung, wenn nicht erfolgreich
String response = "Connection failed! <a href='/'>Try again</a>";
request->send(200, "text/html", response);
Serial.println("debug5");
startAPMode();
}
}
else {
esp_task_wdt_reset();
request->send(200, "text/html", "Missing data! <a href='/'>Back</a>");
startAPMode();
}
});
apServer.begin();
Serial.println("AP-Modus Webserver gestartet auf " + WiFi.softAPIP().toString());
}
}
```
Right now i am reseting the watchdog timer (i think) in the while loop where it checks if the connection was successful. If i dont do that reset it crashes in the while loop already. But since i have the WD reset, it crashes in the else{} part where I print "debug 4". It prints the "debug 4" on the serial monitor and after 5 seconds it crashes.
It should write Connection Failed and then i want it to go back to the Form where i can enter the data. The same for Missing Data.
I know my solution with reseting the timer all the time is no solution either so if you have and other solutions i am happy to hear them.
So i would be glad if anyone could help me resolving this issue!
Thanks!
I entered the wrong Wifi Data and it reset the ESP32 because it triggered the Watchdog. I expected it to Print Connection failed but it reseted. |
Watchdog Timer Reset on ESP32 using Webservers |
|c++|webserver|esp32|arduino-esp32|watchdog| |
null |
@Modifying
@Transactional
@Query("DELETE FROM BusinessTransaction bt WHERE bt.userId.id=:id")
void deleteByUserId(Long id);
-->for this query i am getting "Transaction silently rolled back because it has been marked as rollback-only" this error.
In this query userID is a object of User class joined and mapped with BusinessTransaction class so in where condition i am tring to fetch id of user from userId.id and it should be same as :id variable.
any one please let me out of this error
@Modifying
@Transactional
@Query("DELETE FROM BusinessTransaction bt WHERE bt.userId.id=:id")
void deleteByUserId(Long id);
In this query userID is a object of User class joined and mapped with BusinessTransaction class so in where condition I am trying to fetch id of user from userId.id and it should be same as :id variable.
any one please let me out of this error |
I am trying to run
```
from ydata_profiling import ProfileReport
profile = ProfileReport(merged_data)
profile.to_notebook_iframe()
```
in jupyter notebook. But I am getting an error:
AttributeError: module 'numba' has no attribute 'generated_jit'
I am running jupyter notebook in Docker container with requirements listed below:
```
numpy==1.24.3
pandas==1.4.1
scikit-learn==1.4.1.post1
pyyaml==6.0
dvc==3.48.4
mlflow==2.11.1
seaborn==0.11.2
matplotlib==3.5.1
boto3==1.18.60
jupyter==1.0.0
pandoc==2.3
ydata-profiling==4.7.0
numba==0.59.1
```
I am using WSL Ubuntu in Visual Studio Code.
|
AttributeError: module 'numba' has no attribute 'generated_jit' |
|python|pandas|docker|containers| |
null |
How to solve compiler error: no matching function for call to 'dmhFS::dmhFS()' in my case? |
it seems to me you could achieve your goal by means of formulas
if you insert one column and one row you could use this formula
=IF(SUM(G$5:G5)<G$2;IF(SUM(F6:$F6)<8;1;"");"")
[![enter image description here][1]][1]
or you can keep your original rows and columns layout and adopt this other formula:
=IF(ROW()=5;
IF(COLUMN()=7;
1;
IF(SUM(F5:$G5)<8;1;""));
IF(SUM(G4:G$5)<G$2;
IF(COLUMN()=7;
1;
IF(SUM(F5:$G5)<8;1;""));
"")
)
[![enter image description here][2]][2]
Finally here's the corresponding amendment of your code (forgive the polish):
Sub AutoFill()
Dim ws As Worksheet
Dim col As Integer
Dim row As Integer
Dim suma As Integer
Dim liczba_osob As Integer
' Ustaw arkusz, na którym chcesz dzialac
Set ws = ThisWorkbook.Sheets("01")
' Wyczysc zakres G5:AD36
ws.Range("G5:AD36").ClearContents
' Iteruj przez kolumny od G do Y
For col = 7 To 30
' Pobierz liczbe osób w pracy w danej godzinie
liczba_osob = ws.Cells(2, col).Value
' Ustaw sume kolumny na 0
suma = 0
' Uzupelnij komórki wartoscia 1 do momentu, gdy suma wiersza bedzie równa liczbie osób w pracy
For row = 5 To 36
' Sprawdz, czy w biezacym wierszu nie przekracza liczby osób w pracy '<-----|
If WorksheetFunction.Sum(ws.Range(ws.Cells(row, 7), ws.Cells(row, WorksheetFunction.Max(7, col - 1)))) < 8 Then '<-----|
' Sprawdz, czy suma nie przekracza liczby osób w pracy
If suma < liczba_osob Then
ws.Cells(row, col).Value = 1
suma = suma + 1
Else
' Jesli suma przekroczyla liczbe osób w pracy, zostaw komórke pusta
If Not IsEmpty(ws.Cells(row, col)) Then
ws.Cells(row, col).ClearContents
End If
End If
End If '<-----|
Next row
Next col
End Sub
[1]: https://i.stack.imgur.com/we5Ul.png
[2]: https://i.stack.imgur.com/I4Ouv.png |
I'm a beginner developer so don't be mad |
Change your DATABASE_HOST as follows.
```
...
DATABASE_HOST=host.docker.internal
...
```
If you're using Linux operating system, add this to your docker container. (in your `docker-compose.yml`)
```
extra_hosts:
- "host.docker.internal:host-gateway"
``` |
someone please help me to get rid of this error
Error : [PrivateRoute] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>
PrivateRoute.js :
import React from "react"
import { Route, Navigate } from "react-router-dom"
import { useAuth } from "./AuthContex"
export default function PrivateRoute({ element: Element, ...rest }) {
const { currentUser } = useAuth()
return (
<Route
{...rest}
element={currentUser ? <Element {...rest} /> : <Navigate to="/login" />}
/>
)
}
App.js :
import Signup from "./components/signup"
import { Container } from "react-bootstrap"
import { AuthProvider, useAuth } from './components/AuthContex'
import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom'
import Dashboard from "./components/Dashboard"
import Login from "./components/Login"
import ForgotPassword from "./components/ForgotPassword"
import UpdateProfile from "./components/UpdateProfile"
function App() {
return (
<Container
className="d-flex align-items-center justify-content-center"
style={{ minHeight: "100vh" }}
>
<div className="w-100" style={{ maxWidth: "400px" }}>
<Router>
<AuthProvider>
<Routes>
<PrivateRoute path="/" element={<Dashboard />} />
<Route path="/update-profile" element={<UpdateProfile />} />
<Route path="/signup" element={<Signup />} />
<Route path="/login" element={<Login />} />
<Route path="/forgot-password" element={<ForgotPassword />} />
</Routes>
</AuthProvider>
</Router>
</div>
</Container>
)
}
function PrivateRoute({ element, ...rest }) {
const { currentUser } = useAuth();
// Redirect to login if not authenticated
if (!currentUser) {
return <Navigate to="/login" />;
}
// Render the element if authenticated
return <Route {...rest} element={element} />;
}
export default App`
I am trying to create a signup page using firebase authentication |
PrivateRoute is not a Route component error |
|javascript|reactjs|firebase| |
null |
|machine-learning|extract|openai-api|large-language-model|fine-tuning| |
Looking to match a table of X,Y,Z points between two sets of data.
The difference between the two sets is that the sign of the Y value is flipped.
For example in this screenshot I set "target" as the values I'm looking for, where the Y value is the negative of the value in column D.
![sample data table + desired targets[1]][1]
I am using a combination of index and match, but this finds exact matches not the closest match:
=INDEX($C$7:$C$1048576; MATCH(1; (I120=$D$7:$D$1048576) * (J120=$E$7:$E$1048576) * (K120=$F$7:$F$1048576); 0))
In a data set of a few hundred points, about one hundred won't be exact matches.
I'd like a formula to find the closest match to the target points.
[1]: https://i.stack.imgur.com/UAjp6.png |
After establishing PACE PIN authentication, I am trying to implement secure messaging to be able to send secure APDU commands. I based my implementation on the ICAO 9303 part 11 manual, chapter 9.8, page 63 : https://www.icao.int/publications/Documents/9303_p11_cons_en.pdf,
and on this Java code that I used : https://github.com/ecsec/open-ecard/blob/master/ifd/ifd-protocols/pace/src/main/java/org/openecard/ifd/protocol/pace/SecureMessaging.java, as well as on a log from the PlatinumReader where secure messaging has already been implemented.
Here is my code:
**the method for calculating the APDU**:
public string chipherAPDU(string apdu, string keyEnc, string keyMac)
{
string chipherApdu = "";
byte[] apduBytes = StringToByteArray(apdu);
byte[] KeyENC = StringToByteArray(keyEnc);
byte[] KeyMAC = StringToByteArray(keyMac);
byte[] secureMessagingSSC = StringToByteArray("00000000000000000000000000000001");
SecureMessaging sm = new SecureMessaging(KeyMAC, KeyENC);
chipherApdu = byteToHexStr ( sm.encrypt(apduBytes, secureMessagingSSC) );
return chipherApdu;
}
class SecureMessaging :
internal class SecureMessaging
{
private readonly byte[] NULL = new byte[] { 0x00 };
private const byte PAD = 0x80;
private readonly byte[] secureMessagingSSC;
private readonly byte[] keyMAC;
private readonly byte[] keyENC;
public SecureMessaging(byte[] keyMAC, byte[] keyENC)
{
this.keyENC = keyENC;
this.keyMAC = keyMAC;
secureMessagingSSC = new byte[16];
}
public byte[] encrypt(byte[] apdu)
{
incrementSSC(secureMessagingSSC);
byte[] commandAPDU = encrypt(apdu, secureMessagingSSC);
incrementSSC(secureMessagingSSC);
return commandAPDU;
}
public byte[] encrypt(byte[] apdu, byte[] secureMessagingSSC)
{
MemoryStream outputStream = new MemoryStream();
CardCommandAPDU cAPDU = new CardCommandAPDU(apdu);
if (cAPDU.isSecureMessaging())
{
throw new ArgumentException("Malformed APDU.");
}
byte[] data = cAPDU.data;
byte[] header = cAPDU.header;
int lc = cAPDU.lc;
int le = cAPDU.le;
if (data.Length > 0)
{
data = pad(data, 16);
using (Aes aes = Aes.Create())
{
aes.Key = keyENC;
aes.IV = getCipherIV(secureMessagingSSC);
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.None;
ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
byte[] encryptedData = encryptor.TransformFinalBlock(data, 0, data.Length);
outputStream.Write(new byte[] { 0x01 }, 0, 1);
outputStream.Write(encryptedData, 0, encryptedData.Length);
}
}
return outputStream.ToArray();
}
public byte[] decrypt(byte[] response)
{
if (response.Length < 12)
{
throw new ArgumentException("Malformed Secure Messaging APDU.");
}
return decrypt(response, secureMessagingSSC);
}
private byte[] decrypt(byte[] response, byte[] secureMessagingSSC)
{
MemoryStream outputStream = new MemoryStream();
byte[] statusBytes = new byte[2];
byte[] dataObject = null;
byte[] macObject = new byte[8];
return outputStream.ToArray();
}
public static void incrementSSC(byte[] ssc)
{
for (int i = ssc.Length - 1; i >= 0; i--)
{
ssc[i]++;
if (ssc[i] != 0)
{
break;
}
}
}
// Other methods omitted for brevity
private byte[] pad(byte[] data, int blockSize)
{
byte[] result = new byte[data.Length + (blockSize - data.Length % blockSize)];
Array.Copy(data, 0, result, 0, data.Length);
result[data.Length] = PAD;
return result;
}
private byte[] getCipherIV(byte[] smssc)
{
using (Aes aes = Aes.Create())
{
aes.Key = keyENC;
aes.Mode = CipherMode.ECB;
aes.Padding = PaddingMode.None;
ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, null);
return encryptor.TransformFinalBlock(smssc, 0, smssc.Length);
}
}
}
**class CardCommandAPDU** :
public class CardCommandAPDU
{
public byte[] header = new byte[4];
public int le = -1;
public int lc = -1;
public byte[] data;
public CardCommandAPDU(byte[] commandAPDU)
{
Array.Copy(commandAPDU, 0, header, 0, 4);
setBody(copy(commandAPDU, 4, commandAPDU.Length - 4));
}
/**
* Définit le corps (LE, DATA, LC) de l'APDU.
*
* @param body Corps de l'APDU
*/
public void setBody(byte[] body)
{
/*
* Cas 1. : |CLA|INS|P1|P2|
* Cas 2. : |CLA|INS|P1|P2|LE|
* Cas 2.1: |CLA|INS|P1|P2|EXTLE|
* Cas 3. : |CLA|INS|P1|P2|LC|DATA|
* Cas 3.1: |CLA|INS|P1|P2|EXTLC|DATA|
* Cas 4. : |CLA|INS|P1|P2|LC|DATA|LE|
* Cas 4.1: |CLA|INS|P1|P2|EXTLC|DATA|LE|
* Cas 4.2: |CLA|INS|P1|P2|LC|DATA|EXTLE|
* Cas 4.3: |CLA|INS|P1|P2|EXTLC|DATA|EXTLE|
*/
try
{
using (MemoryStream stream = new MemoryStream(body))
{
int length = (int)stream.Length;
// Nettoyage
lc = -1;
le = -1;
data = new byte[0];
if (length == 0)
{
// Cas 1. : |CLA|INS|P1|P2|
}
else if (length == 1)
{
// Cas 2 |CLA|INS|P1|P2|LE|
le = stream.ReadByte() & 0xFF;
}
else if (length < 65536)
{
int tmp = stream.ReadByte();
if (tmp == 0)
{
// Cas 2.1, 3.1, 4.1, 4.3
if (stream.Length < 3)
{
// Cas 2.1 |CLA|INS|P1|P2|EXTLE|
le = (stream.ReadByte() & 0xFF) << 8 | stream.ReadByte() & 0xFF;
}
else
{
// Cas 3.1, 4.1, 4.3
lc = (stream.ReadByte() & 0xFF) << 8 | stream.ReadByte() & 0xFF;
data = new byte[lc];
stream.Read(data, 0, lc);
if (stream.Length == 1)
{
// Cas 4.1 |CLA|INS|P1|P2|EXTLC|DATA|LE|
le = stream.ReadByte() & 0xFF;
}
else if (stream.Length == 2)
{
// Cas 4.3 |CLA|INS|P1|P2|EXTLC|DATA|EXTLE|
le = (stream.ReadByte() & 0xFF) << 8 | stream.ReadByte() & 0xFF;
}
else if (stream.Length == 3)
{
if (stream.ReadByte() == 0)
{
// Cas 4.3 |CLA|INS|P1|P2|EXTLC|DATA|EXTLE|
le = (stream.ReadByte() & 0xFF) << 8 | stream.ReadByte() & 0xFF;
}
else
{
throw new ArgumentException("APDU malformée.");
}
}
else if (stream.Length > 3)
{
throw new ArgumentException("APDU malformée.");
}
}
}
else if (tmp > 0)
{
// Cas 3, 4, 4.2
lc = tmp & 0xFF;
data = new byte[lc];
stream.Read(data, 0, lc);
if (stream.Length == 1)
{
// Cas 4 |CLA|INS|P1|P2|LC|DATA|LE|
setLE((byte)stream.ReadByte());
}
else if (stream.Length == 3)
{
// Cas 4.2 |CLA|INS|P1|P2|LC|DATA|EXTLE|
stream.ReadByte(); // Ignorer le premier octet
setLE((short)((stream.ReadByte() & 0xFF) << 8 | stream.ReadByte() & 0xFF));
}
else if (stream.Length == 2 || stream.Length > 3)
{
throw new ArgumentException("APDU malformée.");
}
}
else
{
throw new ArgumentException("APDU malformée.");
}
}
else
{
throw new ArgumentException("APDU malformée.");
}
}
}
catch (Exception e)
{
Console.WriteLine("Exception", e);
}
}
/**
* Définit le champ de longueur attendue (LE) de l'APDU.
*
* @param le Champ de longueur attendue (LE)
*/
public void setLE(short le)
{
if (le == (short)0x0000)
{
setLE(65536);
}
else
{
setLE((int)le & 0xFFFF);
}
}
/**
* Définit le champ de longueur attendue (LE) de l'APDU.
*
* @param le Champ de longueur attendue (LE)
*/
public void setLE(int le)
{
if (le < 0 || le > 65536)
{
throw new ArgumentException("La longueur doit être comprise entre '1' et '65535'.");
}
else
{
this.le = le;
}
}
/**
* Copie une plage de bytes.
*
* @param input l'entrée
* @param offset l'offset
* @param length la longueur
* @return le tableau de bytes
*/
public static byte[] copy(byte[] input, int offset, int length)
{
if (input == null)
{
return null;
}
byte[] tmp = new byte[length];
Array.Copy(input, offset, tmp, 0, length);
return tmp;
}
public bool isSecureMessaging()
{
return (header[0] & 0x0F) == 0x0C;
}
}
Here are the data from the PlatinumReader that I used where it works fine, and I'm trying to get the same result:
APDU: Request: 00 a4 04 0c 07 a0 00 00 02 47 10 01
GENERIC P7896 T36084 : APDU: SMRequest - 00000000000000000000000000000001
0c a4 04 0c 1d 87 11 01 a9 48 e4 f1 a8 23 56 c1
1c f1 a6 a0 b1 8d 0c 8f 8e 08 71 b6 0b b9 3b 7a
f1 08 00
Here is the test i do by using the same values :
string apduSM = chipherAPDU("00a4040c07a0000002471001", "3d7155f3791c313c2924f51ae60f1ac9" , "b5feb9488f17be03e54c7d80907e8a1f");
addLogMsg("ADPU SM : " + apduSM);
And here is my result :
ADPU SM : 01A948E4F1A82356C11CF1A6A0B18D0C8F
The Keys used are ephemeral so i can post them and it just a testing phase:
**Key: K_MAC - derived MAC key (K_MAC [PACE])
b5 fe b9 48 8f 17 be 03 e5 4c 7d 80 90 7e 8a 1f**
**Key: K_Enc - derived encryption key (K_Enc [PACE])
3d 71 55 f3 79 1c 31 3c 29 24 f5 1a e6 0f 1a c9**
And here is the test : https://dotnetfiddle.net/l3z7P1
|
Secure Messaging Implementation in C# |
|c#|encryption|cryptography|apdu|ecdh| |
I'm using `iverilog` to compile the following matrix multiplication code and testbench:
```
`timescale 1ns / 1ps
module testbench();
// Testbench parameters
parameter m1 = 2;
parameter n1 = 2;
parameter m2 = 2;
parameter n2 = 2;
// Testbench variables
logic clk;
real matrix_a[m1*n1-1:0];
real matrix_b[m2*n2-1:0];
real result_matrix[m1*n2-1:0];
// Instantiate the module under test
matrix_dot_product #(.m1(m1), .n1(n1), .m2(m2), .n2(n2)) uut (
.clk(clk),
.matrix_a(matrix_a),
.matrix_b(matrix_b),
.result_matrix(result_matrix)
);
initial clk = 0;
always #5 clk = ~clk;
initial begin
$dumpfile("testbench.vcd");
$dumpvars(0, testbench);
#10;
matrix_a[0] = 1.0;
matrix_a[1] = 2.0;
matrix_a[2] = 3.0;
matrix_a[3] = 4.0;
matrix_b[0] = 1.0;
matrix_b[1] = 2.0;
matrix_b[2] = 3.0;
matrix_b[3] = 4.0;
#10;
// $display("Result matrix:");
for (int i = 0; i < m1*n2; i++) begin
$display("result_matrix[%0d] = %f", i, result_matrix[i]);
end
// Finish the simulation
$finish;
end
endmodule
module matrix_dot_product #(
parameter m1 = 2,
parameter n1 = 2,
parameter m2 = 2,
parameter n2 = 2
)(
input logic clk,
input real matrix_a[m1*n1-1:0],
input real matrix_b[m2*n2-1:0],
output real result_matrix[m1*n2-1:0]
);
integer i, j, k;
real sum;
real product;
always @(posedge clk) begin
for (i = 0; i < m1; i++) begin
for (j = 0; j < n2; j++) begin
sum = 0;
for (k = 0; k < n1; k++) begin
product = matrix_a[i*n1+k] * matrix_b[k*n2+j];
sum = sum + product;
end
result_matrix[i*n2+j] = sum;
end
end
for (int i = 0; i < m1*n2; i++) begin
$display("result_matrix[%0d] = %f", i, result_matrix[i]);
end
end
endmodule
```
I get the following output when running this matrix multiply test bench:
MODULE OUTPUT
result_matrix[0] = 0.000000
result_matrix[1] = 0.000000
result_matrix[2] = 0.000000
result_matrix[3] = 0.000000
MODULE OUTPUT
result_matrix[0] = 7.000000
result_matrix[1] = 10.000000
result_matrix[2] = 15.000000
result_matrix[3] = 22.000000
TEST BENCH OUTPUT
result_matrix[0] = 0.000000
result_matrix[1] = 0.000000
result_matrix[2] = 0.000000
result_matrix[3] = 0.000000
Based on my output, the code multiplies correctly when running inside the module; however, it doesn't seem to effect the output of the matrix in the testbench. I'd appreciate any help with this issue. |
Matrix Multiplication Testbench Yields Inconsistent Results |
Your backtracking doesn't work, as you break when the count of a letter drops to 0, but the loop that restores the counts unconditionally adds all the letters back.
If you remove the `break`, then your code will work correctly without cloning.
```java
for (char ch : word.toCharArray()) {
int letterIndex = ch - 'a';
if (letterCount[letterIndex] == 0)
flag = false;
letterCount[letterIndex]--;
sword += score[letterIndex];
}
``` |
|python|echo|feedback|noise-reduction| |
null |
The existing code renders. However, when I remove `Router` from line 2 as an import, even though it's not being used, it breaks.
**Correction: The page still renders when I remove Router. However, it just displays a blank page. When I inspect it, I no longer get anything in the <div id="root"> tags.**
When I compile, of course I get "Line 2:27: 'Router' is defined but never used no-unused-vars"
Why is this? Or does anyone have any insight?
```jsx
import React from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import HomePage from './HomePage';
import PlanTripPage from './PlanTripPage';
import NavBar from './NavBar';
import ItineraryPage from './ItineraryPage';
import './App.css';
function App() {
return (
<div>
<NavBar />
<Routes>
<Route exact path="/" element={<HomePage />} />
<Route path="/plan-trip" element={<PlanTripPage />} />
<Route path="/itinerary" element={<ItineraryPage />} />
</Routes>
</div>
);
}
export default App;
```
Here is my index file.
```jsx
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import App from './App';
import './index.css';
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>,
document.getElementById('root')
);
```
|
For me the only way this worked out was to set UISegmentedControl's background image an empty image using UIImage().
Like so:
`segmentedControl.setBackgroundImage(UIImage(), for: .normal, barMetrics: .default)`
Also,
`segmentedControl.setDividerImage(UIImage(), forLeftSegmentState: .normal, rightSegmentState: .normal, barMetrics: .default)`
if you want to get rid of the divider as well. |
I am using TeamsFx SDK. I want to send a proactive message to a user. From reading documentation, it seems that recommended way is to listen to OnMembersAdded or OnMessageActivity and save the conversation reference to a persistent storage, so it can be later used for sending proactive messages.
But what if for whatever reason the conversation reference didn't get persisted? (let's say the network went down when a user was installing the app/bot into their Teams, so the conversation reference was never saved).
How would I recover from a situation when I need to send a proactive message but I don't have a reference to the conversation reference?
Is that possible to construct the conversation reference just by having the Aad ID of the user and the Bot/App Ids?
thank you
|
In TeamsFx, how to construct ConversationReference without having a saved reference? |
|botframework|teams-toolkit| |
After drop_na it shows 0 obs. of 68 variables:
[![enter image description here][1]][1]
[![enter image description here][2]][2]
[![enter image description here][3]][3]
After drop_na I don't see any results in the Table except dates. This was not the case when I tried it before, I could see the values in the table.
```r
library(tidyverse)
<WDI_GDP <- <read_csv("C:/Users/ASYA/Desktop/P_Data_Extract_From_World_Development_Indicators/b0351889-13b3-4cbe-a5c0-a2dd9d633eab_Data.csv")
> WDI_GDP <- WDI_GDP %>%
+ mutate(across(contains("[YR"), ~na_if(.x,"..")) %>%
+ mutate(across(contains("[YR"), as.numeric)))
> WDI_GDP <- drop_na(WDI_GDP)
>
```
![enter image description here][4]
[1]: https://i.stack.imgur.com/oqjo8.png
[2]: https://i.stack.imgur.com/elrGR.png
[3]: https://i.stack.imgur.com/txJEv.png
[4]: https://i.stack.imgur.com/R7nfg.png |
VSCode lists these errors:
2024-03-30 14:51:04.141 [error] Following setting is deprecated: "python.linting.mypyEnabled"
2024-03-30 14:51:04.141 [error] All settings starting with "python.linting." are deprecated and can be removed from settings.
2024-03-30 14:51:04.141 [error] Linting features have been moved to separate linter extensions.
2024-03-30 14:51:04.141 [error] See here for more information: https://code.visualstudio.com/docs/python/linting
2024-03-30 14:51:04.141 [error] Please install "mypy" extension: https://marketplace.visualstudio.com/items?itemName=ms-python.mypy-type-checker
I don't have any such settings in my settings file. Ctrl+, shows settings.json:
{
"security.workspace.trust.untrustedFiles": "open",
"workbench.layoutControl.enabled": false,
"workbench.settings.editor": "json",
"python.defaultInterpreterPath": "C:\\Program Files\\python312\\python.exe",
"workbench.colorTheme": "Default Dark+",
"files.autoSave": "afterDelay",
"editor.minimap.enabled": false,
"editor.formatOnSaveMode": "file",
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.organizeImports": "explicit"
},
"files.defaultLanguage": "python",
"files.insertFinalNewline": true,
"window.zoomLevel": -1,
"[python]": {
"editor.formatOnType": true
},
"python.analysis.autoImportCompletions": true,
"python.analysis.typeCheckingMode": "strict",
}
Also, mypy is definitely installed:
Mypy Type Checker v2023.6.0
Microsoft microsoft.com 167,479 (6)
Type checking support for Python files using Mypy.
Disable Uninstall Switch to Pre-Release Version
This extension is enabled globally.
How do I fix this? |
Settings file does not have settings listed in error log |
|visual-studio-code| |
I believe that `Image` doesn't like null `src`. You should change your code to something like:
```
"use client"
import { useKindeBrowserClient } from '@kinde-oss/kinde-auth-nextjs'
import Image from 'next/image';
import React from 'react'
function DashboardHeader() {
const {user} = useKindeBrowserClient();
return (
<div>
{user?.picture && <Image src={user?.picture} alt='logo'
width={40}
height={40}
/>}
</div>
)
}
export default DashboardHeader
```
To drop the `Image` if you don't have the data or:
```
"use client"
import { useKindeBrowserClient } from '@kinde-oss/kinde-auth-nextjs'
import Image from 'next/image';
import React from 'react'
function DashboardHeader() {
const {user} = useKindeBrowserClient();
return (
<div>
<Image src={user?.picture ? user.picture : '/some/fallback.png'} alt='logo'
width={40}
height={40}
/>
</div>
)
}
export default DashboardHeader
```
to get a fallback image. |
I am trying to make a primitive minesweeper game, my program has two classes, one of which is Point, that is supposed to be made into an array of objects.
```
public Point(int x, int y, int status, int contents)
```
Those are the values that it takes, an object of a sort is created.
Then, i have to get an array of those objects in specified size^2 that is set by the user.
After that, i take the regular size and assign a Game Field instance, which supposedly creates a 2d array which then is further initialised..
Long story short, i want the 2d array take values of each object from my 1d array as each point.
Now, i'll try show what i want and what do i have on hands.
`public GameField(int size, int treasures, int bullets)`
these are the values field takes, they are being switched based on difficulty the user chooses.
```
public void Initialize(int size, int treasures, int bullets)
{
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
int[i, j] field = new Point(....); //How?
}
}
}
```
My problem appears here. The point has two other attributes that show its status on field and contents (treasure, enemy or blank) that are also being randomised. I had an idea of ditching the coordinates part and make the player call a point by its index in array of objects but that really defeats the meaning of "Point", unless. I need an advice on how to make it make sense. |
null |
The only difference is that they have different expiration times.
- `sessionStorage` will only be accessible while and by the window that created it is open.
- `localStorage` lasts until you delete it or the user deletes it.
Let's say that you wanted to save a login username and password you would want to use `sessionStorage` over `localStorage` for security reasons (i.e. another person accessing their account at a later time).
But if you wanted to save a user's settings on their machine you would probably want `localStorage`.
In conclusion
- `localStorage` - use for long term use.
- `sessionStorage` - use when you need to store something that changes or something temporary
|
Extend androidx.preference.EditTextPreference:
public class EditTextPreferenceExt extends EditTextPreference {
public EditTextPreferenceExt(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.EditTextPreferenceExt);
int inputType = a.getInt(R.styleable.EditTextPreferenceExt_inputType, InputType.TYPE_CLASS_TEXT);
String digits = a.getString(R.styleable.EditTextPreferenceExt_digits);
int maxLength = a.getInt(R.styleable.EditTextPreferenceExt_maxLength, 0);
setOnBindEditTextListener(editText -> {
editText.setInputType(inputType);
if (Tools.isNotEmpty(digits))
editText.setKeyListener(DigitsKeyListener.getInstance(digits));
if (maxLength > 0)
editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(maxLength)});
});
}
}
**attrs.xml**
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="EditTextPreferenceExt">
<attr name="digits" format="string"/>
<attr name="maxLength" format="integer"/>
<attr name="inputType">
<flag name="none" value="0x00000000" />
<flag name="text" value="0x00000001" />
<flag name="textCapCharacters" value="0x00001001" />
<flag name="textCapWords" value="0x00002001" />
<flag name="textCapSentences" value="0x00004001" />
<flag name="textAutoCorrect" value="0x00008001" />
<flag name="textAutoComplete" value="0x00010001" />
<flag name="textMultiLine" value="0x00020001" />
<flag name="textImeMultiLine" value="0x00040001" />
<flag name="textNoSuggestions" value="0x00080001" />
<flag name="textEnableTextConversionSuggestions" value="0x00100001" />
<flag name="textUri" value="0x00000011" />
<flag name="textEmailAddress" value="0x00000021" />
<flag name="textEmailSubject" value="0x00000031" />
<flag name="textShortMessage" value="0x00000041" />
<flag name="textLongMessage" value="0x00000051" />
<flag name="textPersonName" value="0x00000061" />
<flag name="textPostalAddress" value="0x00000071" />
<flag name="textPassword" value="0x00000081" />
<flag name="textVisiblePassword" value="0x00000091" />
<flag name="textWebEditText" value="0x000000a1" />
<flag name="textFilter" value="0x000000b1" />
<flag name="textPhonetic" value="0x000000c1" />
<flag name="textWebEmailAddress" value="0x000000d1" />
<flag name="textWebPassword" value="0x000000e1" />
<flag name="number" value="0x00000002" />
<flag name="numberSigned" value="0x00001002" />
<flag name="numberDecimal" value="0x00002002" />
<flag name="numberPassword" value="0x00000012" />
<flag name="phone" value="0x00000003" />
<flag name="datetime" value="0x00000004" />
<flag name="date" value="0x00000014" />
<flag name="time" value="0x00000024" />
</attr>
</declare-styleable>
</resources>
**preferences.xml**
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<EditTextPreferenceExt
android:key="port"
android:title="@string/title"
app:maxLength="5"
app:inputType="number"
app:digits="0123456789"/>
</PreferenceScreen> |
Uniswap V3 Bot on Sepolia Testenet |
|node.js|dotenv|ethers.js|revert|uniswap| |
|web|glsl|webgl| |
In WooCommerce, I would like the add to cart button to be disabled if a certain attribute value is selected. The attribute taxonomy is "pa_badge-print" and the term slug value is "yes"
I have used this code:
```
add_filter( 'woocommerce_variation_is_purchasable', 'conditional_variation_is_purchasable', 20, 2 );
function conditional_variation_is_purchasable( $purchasable, $product ) {
## ---- Your settings ---- ##
$taxonomy = 'pa_badge-print';
$term_slug = 'yes';
## ---- The active code ---- ##
// Check if the product has attributes
if ( $product->get_attributes() ) {
// Loop through all product attributes in the variation
foreach ( $product->get_variation_attributes() as $variation_attribute => $term_slug ){
// Get the attribute taxonomy
$attribute_taxonomy = str_replace('attribute_', '', $variation_attribute);
// Get the term object by slug
$term = get_term_by( 'slug', $term_slug, $attribute_taxonomy );
// Check if the term exists and its slug is "yes"
if ( $term && $term->slug === $term_slug ) {
$purchasable = false; // Disable purchasable
break; // Exit the loop
}
}
}
return $purchasable;
}
```
And currently it disables add to cart on all attribute values. So for example, if the attribute value was "no", the add to cart should still show.
This is a screen shot of the product with the values no selected. The add to cart button should show with no values selected;
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/IDewo.png |
Hide Add to Cart in WooCommerce for variations with specific attribute value |
|javascript|canvas|webgl|polygon|voronoi| |
The issue is with the authorization header:
```
"Authorization" = "SharedKey "+$storageAccountName+":"+$storageAccountKey
```
You cannot pass the account key in the authorization header. You have to compute its value based on the instructions provided here: https://learn.microsoft.com/en-us/rest/api/storageservices/authorize-with-shared-key. |
null |
I had a Django service which had an app called "User". This app has 2 tables in, which are being migrated to the database using Django migration system. In order to change the architecture from monolith to micro-service, I broke down User app and add the models and APIs in another Fastapi project. But I didn't separate the database and during this time, I was changing User tables in database using my previous Django project migration system. But now I want to break down tables in the database and move them to the new database. What is the best practices of doing this? And how can I change migrations from Django to alembic? |
migrate from django migrations to fastapi alembic |
|django|microservices|fastapi| |
Closest match of X,Y,Z coordinates |
|excel|excel-formula| |
null |
I'm trying to display my frame in my window but for some reason its giving me a blank window. It's my first time using classes with tkinter do i need to call it in the object?
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
from customtkinter import *
class app(CTk):
def __init__(self, title, size):
# main setup
super().__init__()
self.title(title)
self.geometry(f'{size[0]}x{size[1]}')
self.minsize(size[0],size[1])
# widget
self.menu = CTkFrame(self)
# run
self.mainloop()
class Menu(CTkFrame):
def __init__(self, parent):
super().__init__(parent)
self.place(x=0,y=0, relwidth = 0.3, relheight = 1)
self.create_widgets()
def create_widgets(self):
heading_var = StringVar(value="Ethan")
def heading_combo(choice):
print(choice)
heading = CTkComboBox(self, value=["Ethan","Brock", "Liam"], command=heading_combo,variable=heading_var)
self.columnconfigure((0,1,2),weight=1, uniform='a')
self.rowconfigure((0,1,2,3,4),weight=1, uniform='a')
heading.pack()
app('Scoring Software', (600,600))
<!-- end snippet -->
|
Frame not displaying | python tkinter |
|python|tkinter| |
I use JavaScript and node. I need to read the raw bytes from the file.
I create a `Uint8array` and fill it with data from a file using `fs.Read`.
Then I output the data to the console of the array as a whole, and individual elements.
Instead of the values of the elements, I get zeros.
But it is clear that the array has non-zero data.
```
var buf1 = new Uint8Array( 4 );
fs.open( filePath, 'r+', function ( err, fd ) {
if (err) { console.error( err ) };
fs.read( fd, buf1, 0, buf1.length, 4,
function (err, bytes) {
if (err) { console.log(err) };
fs.close( fd, function (err) {
if (err) { console.log(err) };
}) }) });
console.log( buf1 );
console.log( buf1[0] );
console.log( buf1[1] );
console.log( buf1[2] );
console.log( buf1[3] );
```
[In the console, I see this:](https://i.stack.imgur.com/Te1VP.jpg)
```
var buf2 = new Uint32Array( buf1.buffer );
console.log( buf2 );
console.log( buf2[0] );
```
[In the console, I see this:](https://i.stack.imgur.com/cKghH.jpg) |
how to correctly get the value of an element by its index from TypeArray? |
Using attributes from instances of array of objects in other classes |
|c#|arrays|class|random| |
null |
You need to have nested structures that mirror your nested JSON:
struct City: Decodable {
let id: Int
let city: String
}
struct ResponseObject: Decodable {
let items: [City]
let offset: Int
let limit: Int
}
And then:
do {
let result = try JSONDecoder().decode(ResponseObject.self, from: data)
print(result)
let cities = result.items
print(cities)
} catch {
print(error)
}
---
Note, in your original example, you included a JSON key, `updated_at` which was the date represented in number of seconds since 1970 (standard UNIX representation). So, to decode that:
struct City: Decodable {
let id: Int
let city: String
}
struct ResponseObject: Decodable {
let items: [City]
let offset: Int
let limit: Int
let code: Int
let updatedAt: Date
}
And then:
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .secondsSince1970
decoder.keyDecodingStrategy = .convertFromSnakeCase
do {
let result = try decoder.decode(ResponseObject.self, from: data)
print(result)
let cities = result.items
print(cities)
} catch {
print(error)
}
- - -
Note, when you see a somewhat abstract key name, such as `items`, that means that this might be a response structure used for various endpoints. In that case, we might to make this a [generic][1]:
struct ItemsResponse<T: Decodable>: Decodable {
let items: [T]
let offset: Int
let limit: Int
let code: Int
let updatedAt: Date
}
And then:
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .secondsSince1970
decoder.keyDecodingStrategy = .convertFromSnakeCase
do {
let result = try decoder.decode(ItemsResponse<City>.self, from: data)
print(result)
let cities = result.items
print(cities)
} catch {
print(error)
}
[1]: https://docs.swift.org/swift-book/documentation/the-swift-programming-language/generics |
Trying to generate LIN Slave wakeup frame from CAPL script in which I need to simulate below condition
1. System is in sleep.
2. My Node Connected to ECU will wakeup with three 250us pulse (LIN slave wakeup frame on Bus not 999us neither wakeup frame through 0x3C).
3. Send Diagnostic frame to my ECU with Checksum Error
4. send Unconditional frame to my ECU to get response from my ECU whether previous frame checksum Error is detected or not .
5.Again send diagnostic frame to my ECU with checksum Error
6. Again send Unconditional frame to get ECU response for checksum Error Detection.
7. put system in Sleep again.
Repeat 1 to 7 step to check same thing multiple times .
I need to support that anybody know how we can do this as i am able to generate checksum error but not able to generate LIN slave wakeup frame on bus through CAPL script.
its a sequence for one test case that I need to generate to check my LIN driver , as we got some issues from Client side and my LIN driver is failing in their test cases but client cant give their environment for testing (Automotive vehicle manufacturer confidential tools and environment).
Thanks
I tried t generate 250 us pulse through CAPL inbuild LIN function but after checking on Logic level of bus I cant see any pulses |
```typescript
type KeyValueWrapperTypeObject = {
[key: string]: Wrapper<unknown>,
}
type KeyValueUnknownTypeObject = {
[key: string]: unknown,
}
type MyDeterminedTypedObject = {
key1: Wrapper<string>,
key2: Wrapper<number>,
key3: Wrapper<{
nestedKey: boolean,
}>
}
type ConvertValueTypesOfMappedTypeToSpecifiedType<MappedType, SpecifiedType> = {
[K in keyof MappedType]: SpecifiedType;
};
class Wrapper<T> {
#t: T
constructor(t: T) {
this.#t = t
}
reveal(): T {
return this.#t
}
}
function makeKeyValueWrapperObjectFromJson<S extends KeyValueWrapperTypeObject>(json: string): S {
const parsedJson = JSON.parse(json);
const result: any = {};
for (const key in parsedJson) {
if (Object.prototype.hasOwnProperty.call(parsedJson, key)) {
result[key] = new Wrapper(parsedJson[key]);
}
}
return result;
}
const jsonString = '{"key1": "value1", "key2": "123", "key3": {"nestedKey": true}}';
const keyValueWrapperObject = makeKeyValueWrapperObjectFromJson<MyDeterminedTypedObject>(jsonString);
console.log(keyValueWrapperObject.key1.reveal());
console.log(keyValueWrapperObject.key2.reveal()); // how to type check this?
console.log(keyValueWrapperObject.key3.reveal().nestedKey);
```
I am trying to wrap all the values of an arbitrary object with `Wrapper<T>`.
The function `makeKeyValueWrapperObjectFromJson`, first parses a JSON string, then given that parsed TypeScript object, it looks through all its values, construct a new `Wrapper<T>` and setting it as the value corresponding to the key of the object as typed by `MyDeterminedTypedObject`.
`key2` is supposed to be of type `number` but the JSON string has it as `"123"` which is parsed as string.
Is there anyway to write `makeKeyValueWrapperObjectFromJson`, such that it is able to create arbitrary instances of any tips just by 'inspecting' the type argument `MyDeterminedTypedObject` passed into the type parameter of the function?
[Playground](https://www.typescriptlang.org/play?#code/C4TwDgpgBA0hIDUCGAbArhA6gJyWS2AKuBAPIBGAVhAMbBQC8UA3gFBRQDaA1vAFxQAzsGwBLAHYBzALoCceAgB4047uID2Ad3EA+ADSsAvq1ahIseMnQQAqqo3bikCtTqMW7LrxADhYqbJQKmpa4gbGpiRQALIgACIQwBDYALYSEAAmTpkutPRMbBzeAIxyuPjJin4Skvqe3gBMZQqV4mgp5Ml1RfAAzM0V2IqFHFDiEMKZcD5Q5OrqKBBIYZ6GOkYmZtAAwuriAG7JwFYY2YKkAGbRLVkkhOoAypA0oheimdmK1xW3kHpQT1or3evwgOncI04MCgEig3nUFxiN2ygUBLzeHxIAG4jDjWDQUEhBIIoPJBopCOCRgBiYACQgmDg0PZ+NB0dTYAAUdKghAAlB5RlBgAALUSCAB0tPcwFWjKg2Agh1QnL59MFo0VwDQ2HEwrFktpcoiFxUdFEeygKSQvGmJyw5QIuToADFsOoUgApQR7RQPKAQAAeSXEGRJdtQGDJBGyzuAOk5lB94l8IhqaoBGuZ4mEUDASGwgky3stTE9D1IADkJfnCxBE8m+TimSz6IrBGgUDzliAIYY8RwLhyoJzs7nvDC9bWixkS+IBSMOK8R3Ga+7gOothKRUTSNoAArugigCU0VAoTnT4vJ-7ePkLzxC9ud4A8eDSdzjTSkx3JS8Fmc5zfEBpCbR8oGMDgIg4LUdT1Z8uxxCIx3oJM9geNMpHcAByZgACISjwgQ8P2SMIGKPD-gI+AGiIqA8OKBpeko+jvGYgR8PGSYMmmOiRAwQxDGwvEULhSwyOjZI43ca1bXE6xJOwOM3Q9OcvniRJkjScZQQyOMEzQ8QMP8SQwPxFkFggCUUHUSROW8e1FNXEoJUVZUL3vHEx0s6zbPs+So1-JSqDyCVGlcpUlg8psoAAeliqARS0YV1GFKIaBFWhuH1cUAH5zJzHybLshyJKC5y+gi9zVQlLikh4+AwKAA)
|