instruction stringlengths 0 30k ⌀ |
|---|
I reopened the GitHub Desktop app and that helped. |
I also installed via `.pkg`, I had a lot of permission errors lately and wanted to use `nvm` so had to uninstall the current version. Found the below script from [here][1]
sudo rm -rf /usr/local/{bin/{node,npm},lib/node_modules/npm,lib/node,share/man/*/node.*}
[1]: https://medium.com/@abuabdirohman/how-to-uninstall-node-js-that-installed-via-pkg-on-macos-ffab7cd852bb |
I've been working on a Python discord bot and wanted to containerize it, which has worked pretty well, but while testing one of the features (bot -> open API) via HTTPS I'm getting the following error:
```
ssl.SSLError: Cannot create a client socket with a PROTOCOL_TLS_SERVER context (_ssl.c:811)
```
I've read various articles and tutorials online but they either seem to half answer my question or partially relate to other applications altogether, such as configuring Nginx, which I think is just muddying the water a little.
So far I've encountered people mentioning to create and move some certs and one answer saying to include `--network host` into the `Dockerfile`, but it doesn't seem like there is any issue with the network connectivity itself.
I was tempted to just change the request URL to use HTTP instead as there's no credentials or sensitive data being transmitted but would feel a lot more comfortable knowing it's using HTTPS instead.
My Dockerfile is as below (note: I added the `RUN apt-get update ...` block after my investigations hoping that would generate a certificate and the error would magically clear up but that's not the case).
```lang-docker
FROM python:3.10-bullseye
COPY requirements.txt /app/
COPY ./bot/ /app
RUN apt-get update \
&& apt-get install openssl \
&& apt-get install ca-certificates
RUN update-ca-certificates
WORKDIR /app
RUN pip install -r requirements.txt
COPY . .
CMD ["python3", "-u", "v1.py"]
```
I tried a little bit basic of diagnostics through the container like checking the directories for certs and trying to curl to a HTTPS URL. |
i have this page component for each product information:
```
export default function Product() {
const { data } = useContext(ShopContext);
const { id } = useParams();
if (!data) {
return <div>Loading product...</div>;
}
const product = data.find((item) => item.id === id);
return (
<div>
{product.title}
</div>
);
}
```
somehow product is undefined though data and id can be logged into console and their value is available, i made sure of it like this:
```
export default function Product() {
const { data } = useContext(ShopContext);
const { id } = useParams();
if (!data) {
return <div>Loading product...</div>;
}
const product = data.find((item) => item.id === id);
return (
<div>
<div>{id}</div> {/*this div is displayed as expected*/}
<div> {/*this div is displayed as expected*/}
{data.map((item) => (
<div key={item.id}>{item.title}</div>
))}
</div>
<div>{product?.title}</div> {/*this div is empty*/}
</div>
);
}
```
for additional information i'm fetching the data from [fakestoreapi.com](fakestoreapi.com) in the app component and it works fine in other components. here's the fetching piece:
```
useEffect(() => {
async function FetchData() {
try {
const response = await fetch("https://fakestoreapi.com/products");
if (!response.ok) {
throw new Error(`HTTP error: Status ${response.status}`);
}
let postsData = await response.json();
postsData.sort((a, b) => {
const nameA = a.title.toLowerCase();
const nameB = b.title.toLowerCase();
return nameA.localeCompare(nameB);
});
setData(postsData);
setError(null);
} catch (err) {
setData(null);
setError(err.message);
} finally {
setLoading(false);
}
}
FetchData();
}, []);
```
this is the context:
```
import { createContext } from "react";
export const ShopContext = createContext({
data: [],
loading: true,
error: "",
setData: () => {},
cart: [],
addToCart: () => {},
removeFromCart: () => {},
});
```
and this is its states in app component:
```
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const [cart, setCart] = useState([]);
const addToCart = (productId) => {
....
};
const removeFromCart = (productId) => {
.....
};
return (
<ShopContext.Provider
value={{
data,
loading,
error,
setData,
cart,
addToCart,
removeFromCart,
}}
>
<Header />
<Body />
<Footer />
</ShopContext.Provider>
);
```
okay i figured out that i was using === and ids had different types. i'm stupid yay
```
const product = data.find((item) => item.id === Number(id));
```
|
Is there a way to validate the cell format (from excel) to fetch the symbol from it (in Java)? |
|java|excel| |
null |
I am not sure what is wrong. I have a basic understanding of git, but I am not an expert.
In my remote branch, I have a file that has a bunch of changes, etc in it.
In my local branch, this file is completely empty.
When I open up github, and the file, I notice it has something like this, so I believe something is out of sync:
<<<<<<< HEAD:my_repo/category_1/run_daily_jobs/summary_daily_job.kjb
<xloc>1328</xloc>
<yloc>80</yloc>
=======
<xloc>1280</xloc>
<yloc>128</yloc>
>>>>>>> 44abcxyzbunchofvalues:my_repo/summary_daily_job.kjb
Based on the comments, here is what I have done:
1. Went to github
2. Found the file
3. Googled "how to read a merge conflict in github" and edited the file appropriately.
4. Ran "git pull origin/my_branch"
When I ran this command here is what the message said:
From my_repository
* branch my_branch -> FETCH_HEAD
updating some value
Fast-forward
.../name_of_file.kjb | 367 --------------------
1 file changed, 367 deletions(-)
5. For some reason, the file is still blank though when I open it in the software I am using (Pentaho). Maybe this is a software issue at this point though?
Here is how I edited my file, compared to what I have above:
<xloc>1328</xloc>
<yloc>80</yloc>
|
I can't explain exactly why it happens, but Lex Li's comment about how old Server 2012 R2 is made me think well, maybe it is related to age. So I made a VM and installed a modern server OS with newer IIS and the problem resolved itself.
Now since it could be any number of things that are different between the two servers, but the application itself is the exact same. So while I cannot definitively point to old IIS as a problem, I'd recommend if having the same problem under 2012 to test your app on a newer platform instead. |
section data is where I get the error
section data
queen_row db 4 ; Fila inicial de la Reina
queen_col db 4 ; Columna inicial de la Reina
timer_ticks db 0 ; Contador de ticks del temporizador
section .text
global _start
_start:
; Configurar temporizador
mov al, 0B6h ; Modo 3 del temporizador (modo binario)
out 43h, al ; Envía el comando al controlador del temporizador
mov ax, 1193h ; Valor inicial del temporizador para 10ms
out 40h, al ; Envía el byte menos significativo
mov al, ah
out 40h, al ; Envía el byte más significativo
timer_loop:
mov al, 0 ; Esperar a que el temporizador alcance su intervalo
in al, 61h ; Leer el registro del controlador del teclado
test al, 1 ; Verificar si el bit 0 está activo (indicando que se ha producido un tick)
jz timer_loop ; Si no se ha producido un tick, esperar
inc byte [timer_ticks] ; Incrementar contador de ticks
cmp byte [timer_ticks], 5
jne timer_loop; Mover la Reina a una nueva posición cada 5 ticks
; Mover la Reina a una nueva posición en el tablero (aquí iría tu lógica de movimiento)
; Reiniciar el contador de ticks
mov byte [timer_ticks], 0
jmp timer_loop ; Volver a esperar al próximo tick del temporizador |
ran into this issue with gradle when i tried to create a signed bundle |
|android-gradle-plugin| |
null |
When your `m_data` object is constructed, its constructor first adds a *copy* of the `data1..data5` members to the `data` list *before* those members have been initialized. Those members are initialized *after* the `data` list is populated, and the pointers stored in the `data` list are never being updated.
So, when your loop later retrieves a stored pointer from `m_data->data[i]` and tries to dereference that pointer, you experience *Undefined Behavior*, resulting in a runtime crash.
Try this instead for your `Data` struct:
```
struct Data {
Data() {
data1 = new QBarDataRow;
data2 = new QBarDataRow;
data3 = new QBarDataRow;
data4 = new QBarDataRow;
data5 = new QBarDataRow;
//initialize the list here...
data = QList<QBarDataRow *>{ data1, data2, data3, data4, data5 };
}
~Data() {
delete data1;
delete data2;
delete data3;
delete data4;
delete data5;
}
public:
//don't initialize the list here...
//QList<QBarDataRow *> data{ data1, data2, data3, data4, data5 };
QList<QBarDataRow *> data;
QBarDataRow *data1;
QBarDataRow *data2;
QBarDataRow *data3;
QBarDataRow *data4;
QBarDataRow *data5;
};
``` |
### Problem description
I'm writing a python library and I am planning to upload both sdist (.tar.gz) and wheel to PyPI. The [build docs say](https://build.pypa.io/) that running
```
python -m build
```
I get sdist created from the source tree and *wheel created from the sdist*, which is nice since I get the sdist tested here "for free". Now I want to run tests (pytest) against the wheel with multiple python versions. What is the easiest way to do that?
I have been using tox and I see there's an option for [setting package to "wheel"](https://tox.wiki/en/latest/config.html#package):
```
[testenv]
description = run the tests with pytest
package = wheel
wheel_build_env = .pkg
```
But that does not say *how* the wheel is produced; I am unsure if it
a) creates wheel directly from source tree<br>
b) creates wheel from sdist which is created from source tree in a way which *is identical to* `python -m build`<br>
c) creates wheel from sdist which is created from source tree in a way which *differs from* `python -m build`
*Even if the answer would be c), the wheel tested by tox would not be the same wheel that would be uploaded, so it is not testing the correct thing. **Most likely I should somehow give the wheel as an argument to tox / test runner.***
## Question
I want to create a wheel from sdist which is created from the source tree, and I want to run unit tests against the wheel(s) with multiple python versions. What would be the idiomatic way to run the tests against the *same* wheel(s) which I would upload to PyPI? Can I use tox for that?
|
this error can happen for a number of reasons but one way or another what's happening is that your PHP can't find your database to connect, here's a few suggestions on how you can troubleshoot this issue.
1 - verify the database exists
------------------------------
make sure that you have created your database before trying to reference in your .env file, sometimes we can get ahead of ourselves and end up skipping steps.
2 - verify the name of your database
------------------------------------
most likely in your .env file you are giving the wrong reference to the database and that's why you won't be able to connect, check for typos and make sure that the name on your .env is EXACTLY the same name as your database, note that this is case-sensitve.
this are the most common reasons to this type of error but if this doesn't help on your case please share a little more information, specially how you're trying to connect on the .env file of your laravel project. |
I started using **Sequelize** with **SQLite**. When I try to insert or update a value, it doesn't check for type-errors. For example I can use **string** values in a column with **sequelize.BOOLEAN** type.
I know [**SQLite** allows this][1], but what about **Sequelize**? It doesn't check or I am missing something?
Should I add a validation check for each datatype? Is there an easy way of checking types instead of validating one by one in every model?
[1]: https://sqlite.org/faq.html#q3 |
The accepted answer is not correct. In Python/Java, list/Arraylist store object references instead of actual values. these reference are stored contiguously, not the entire actual data. Hence python list is not as cache friendly as say c++ vector or numpy array. Although I did wrote code to check how close the memory for data is allocated, I found out they are stored like chunks of contiguous blocks with a certain pattern. I do not know whether this is advantages , or an actual implementation detail created for optimization when like in my case if we use small homogeneous data types like int32. CPython experts can answer this or who are willing to understand the source code. |
In the below code:
package main
import (
"errors"
"fmt"
"math"
)
func area(r float64, shapeConstant float64, result *float64) error {
if r <= 0 {
return errors.New("r must be positive")
}
*result = shapeConstant * r * r
return nil
}
const (
shapeConstantForSquare = 1.0
shapeConstantForCircle = math.Pi
shapeConstantForHexagon = 3 * math.Sqrt(3) / 2 // 3 * 1.73205080757 / 2
)
func areaOfSquare(r float64, result *float64) error {
return area(r, shapeConstantForSquare, result)
}
func areaOfCircle(r float64, result *float64) error {
return area(r, shapeConstantForCircle, result)
}
func areaOfHexagon(r float64, result *float64) error {
return area(r, shapeConstantForHexagon, result)
}
func main() {
var result float64
err := areaOfSquare(3, &result)
display(err, &result)
areaOfCircle(3, &result)
display(err, &result)
areaOfHexagon(3, &result)
display(err, &result)
}
func display(err error, result *float64) {
if err != nil {
fmt.Println(err)
return
}
fmt.Println(*result)
}
----------
`const shapeConstantForHexagon = 3 * math.Sqrt(3) / 2` needs runtime to evaluate expression(RHS) and provide value to LHS. Compile error.
What is the best approach to avoid expression evaluation in RHS, at runtime? in const declaration
Does below approach lose precision?
const(
sqrtOfThree = 1.73205080757
shapeConstantForHexagon = 3 * sqrtOfThree / 2
) |
lexer
```
%{
#include "parser.tab.h"
enum {
STRING = yy::parser::token::STR
};
extern int yylval;
%}
%option noyywrap c++ debug
WORD "\""(\\.|\\\n|[^\\\"])*"\""
%%
{WORD} return STRING;
[\n\t ] ;
%%
```
parser
```
%{
#include <iostream>
int yylex();
%}
%skeleton "lalr1.cc"
%require "3.0.2"
%define api.value.type variant
%token <std::string> STR
%start program
%%
program : STR[a]
{
std::cout << $a << std::endl;
}
;
%%
int main()
{
yy::parser parser;
parser.parse();
}
namespace yy
{
void parser::error(const std::string& m)
{
std::cerr << m << std::endl;
}
}
```
error
```
parser.tab.c: In member function ‘virtual int yy::parser::parse()’:
parser.tab.c:531:46: error: too many arguments to function ‘int yylex()’
531 | yyla.kind_ = yytranslate_ (yylex (&yyla.value));
| ~~~~~~^~~~~~~~~~~~~
parser:3:13: note: declared here
3 | int yylex();
| ^~~~~
```
We checked various websites in different languages, including our native tongue, but found no help at all because only very difficult examples were provided.
Essentially, the program should be simpler than a calculator that just receives a string interactively and outputs it. |
Using a same-named element (such as your `name` example) as a child of two ***different*** parent elements such as `person` and `car` is natural and fully supported by XML and its related standards:
- DTD supports defining same-named elements with different parents
```
<!DOCTYPE people_list [
<!ELEMENT person (name, age)>
<!ELEMENT car (name, price)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT age (#PCDATA)>
<!ELEMENT price (#PCDATA)>
]>
```
- XSD supports it too: See [Basic Concepts: The Purchase Order][1] in the XSD primer.
- XPath (and therefore XSLT) differentiates between `/stuff/person/name` versus `/stuff/car/name`.
- Etcetera.
Note that the content models of `name` could even be different for the `name` of a `person` vs the `name` of a `car`. *Well-formed* XML allows the content models to differ for same-named elements with the ***same*** parent even, but XML schemas (such as DTD and XSD) generally do not support the definition of such elements, so such XML would generally not be able to be considered *valid*.
See also
--
- https://stackoverflow.com/q/134494/290085
- https://stackoverflow.com/q/33746/290085
[1]: https://www.w3.org/TR/xmlschema-0/#PO |
If you install gitlab runner binary on Ubuntu 20.04 you can uninstall it completely by run below commands:
# Stop and remove the service
sudo gitlab-runner stop
sudo gitlab-runner uninstall
sudo systemctl daemon-reload
# Remove gitlab-runner files and config
sudo rm -rf /usr/local/bin/gitlab-runner
sudo userdel gitlab-runner
sudo rm -rf /home/gitlab-runner/
|
null |
I'm using below extension function to Upsert data with EF Core with EFCore.BulkExtensions, but the issue is the execution for this function when I tried to insert 2 millions record is taking around 17 minutes and lately it throws this exception
**Could not allocate space for object 'dbo.SORT temporary run storage: 140737501921280' in database 'tempdb' because the 'PRIMARY' filegroup is full. Create disk space by deleting unneeded files, dropping objects in the filegroup, adding additional files to the filegroup, or setting autogrowth on for existing files in the filegroup.\r\nThe transaction log for database 'tempdb' is full due to 'ACTIVE_TRANSACTION' and the holdup lsn is (41:136:347)**,
and I can see the storage for "C" partition is decreasing when I executed this function.
[![enter image description here][1]][1]
when I restart the sql server, the free space becomes around 30 GB,
I tried to use multi threading (Parallel) with the insertion with no noticed time change, so what do you recommend or is there any issue in the code blow,
**Note:** the for loop is not taking too much time even if it was 2 millions records.
```
public static async Task<OperationResultDto> AddOrUpdateBulkByTransactionAsync<TEntity>(this DbContext _myDatabaseContext, List<TEntity> data) where TEntity : class
{
using (var transaction = await _myDatabaseContext.Database.BeginTransactionAsync())
{
try
{
_myDatabaseContext.Database.SetCommandTimeout(0);
var currentTime = DateTime.Now;
// Disable change tracking
_myDatabaseContext.ChangeTracker.AutoDetectChangesEnabled = false;
// Set CreatedDate and UpdatedDate for each entity
foreach (var entity in data)
{
var createdDateProperty = entity.GetType().GetProperty("CreatedDate");
if (createdDateProperty != null && (createdDateProperty.GetValue(entity) == null || createdDateProperty.GetValue(entity).Equals(DateTime.MinValue)))
{
// Set CreatedDate only if it's not already set
createdDateProperty.SetValue(entity, currentTime);
}
var updatedDateProperty = entity.GetType().GetProperty("UpdatedDate");
if (updatedDateProperty != null)
{
updatedDateProperty.SetValue(entity, currentTime);
}
}
// Bulk insert or update
var updateByProperties = GetUpdateByProperties<TEntity>();
var bulkConfig = new BulkConfig()
{
UpdateByProperties = updateByProperties,
CalculateStats = true,
SetOutputIdentity = false
};
// Batch size for processing
int batchSize = 50000;
for (int i = 0; i < data.Count; i += batchSize)
{
var batch = data.Skip(i).Take(batchSize).ToList();
await _myDatabaseContext.BulkInsertOrUpdateAsync(batch, bulkConfig);
}
// Commit the transaction if everything succeeds
await transaction.CommitAsync();
return new OperationResultDto
{
OperationResult = bulkConfig.StatsInfo
};
}
catch (Exception ex)
{
// Handle exceptions and roll back the transaction if something goes wrong
transaction.Rollback();
return new OperationResultDto
{
Error = new ErrorDto
{
Details = ex.Message + ex.InnerException?.Message
}
};
}
finally
{
// Re-enable change tracking
_myDatabaseContext.ChangeTracker.AutoDetectChangesEnabled = true;
}
}
}
```
[1]: https://i.stack.imgur.com/ts9IF.png |
im new to nodejs and i was just wants to update integer in mongodb but i con't do so.
i dont understand what im doing wrong here.no matter what i try findAndUpdate only returning original document without updating it even on mongodb atlus the document is unaltered. I also tried typecasting integer value but still didn't work.
```const id = "6606ff9e1a5c69a06612219b"
// const objid = new mongoose.Types.ObjectId(id)
export const UpdateMoisture = async (req, res) => {
try {
const moist = req.body.moisture
const update = {$set:{"moisture":parseInt(moist)}}
const result = await Sensor_data.findOneAndUpdate(
{_id:id},
update,
{
new:true
}
)
console.log(result)
// Return the updated data
return res.status(200).json({ result, success: true });
} catch (error) {
// Log and return error response
console.error('Error while updating moisture:', error);
return res.status(500).json({ msg: 'Error while updating moisture data', error: error, success: false });
}
}```
|
Most of your comments are fine.
Others may need some rewording:
> movl %edx, %eax # edx is an address, take the value inside that address into eax
"**take the value inside that address**"
This just puts a copy of what is in the EDX register into the EAX register. The fact that in this case EDX contains an address is of no importance.
> leal (%edx), %ecx # () tells us to go to the address inside edx, take the address itself into ecx (lea)
"**go to the address inside**"
We're not *going* to an address. The CPU calculates the address that the leftmost operand represents and stores it as such into the destination register ECX.
|
how to create a chess board with Queen in the central position and all its moves in assembler code |
|cassandra| |
null |
If you installed it via snap, try the deb version in case the versions are different: https://code.visualstudio.com/download |
When I install the [chatmessenger package][1] in my Laravel SaaS project, I encounter an error:
> Call to undefined function getAdminPanelUrlPrefix()
Below is the error I get in my code editor.
[![enter image description here][2]][2]
[![enter image description here][3]][3]
And this is the error I get on the browser:
[![enter image description here][4]][4]
I'm unsure of the cause of this issue. However, when I remove the syntaxlexx/chatmessenger package, the project functions correctly.
[1]: https://github.com/syntaxlexx/laravel-5-messenger
[2]: https://i.stack.imgur.com/bB6BP.png
[3]: https://i.stack.imgur.com/gEOo2.png
[4]: https://i.stack.imgur.com/ub9Li.png |
|php|laravel|chat|laravel-10|php-8| |
I'm writing some data to disk with `io_uring` and noticed that the file offset does not increase automatically after a write request is issued. Thus, if I issue two write requests through `liburing`, the second one will overwrite the first one since both are trying to write to the beginning of the file. Using these posix apis by themselves (`write` and `writev`) do not cause any issues, but using them through `liburing` never advances the file offset. The man page for `liburing` says setting `offset` to -1 will advance the file offset automatically, but that does not seem to be the case.
A small example is below. The expected behavior is that 4096 bytes of numbers from 0 to 1023 are written to the file, followed by 4096 bytes of 0s. However, the file only contains 4096 bytes of 0s. If I remove the line `write_buffer_to_file(2)`, it now contains 4096 bytes of numbers, so it seems that the second call is overwriting the content of the first one. The fact that `lseek` always returns 0 confirms that the file offset never changes.
The code snippet is compiled with gcc and ran on RHEL 9.3 with kernel 5.14.
```
#include <cstring>
#include <iostream>
#include <liburing.h>
#include <unistd.h>
// a small macro to check for errors
#define SYSCALL(expr) if ((expr) < 0) { \
perror("System call error"); \
}
const int WRITE_SIZE = 4096; // satisfy alignment requirement of O_DIRECT
int fd; // file descriptor
int *buffer; // write buffer
struct io_uring ring;
// write the content of the buffer to fd; the data argument sets user_data in the sqe, which shouldn't affect the result
void write_buffer_to_file(int data) {
struct io_uring_sqe *sqe = io_uring_get_sqe(&ring);
io_uring_sqe_set_data(sqe, (void*)(intptr_t)data);
// according to the documentation, setting offset to -1 will advance the offset
// neither 0 nor -1 work in my testing
io_uring_prep_write(sqe, fd, buffer, WRITE_SIZE, -1);
SYSCALL(io_uring_submit(&ring))
std::cout << "Submitted " << sqe->user_data << std::endl;
// now wait for it to complete
struct io_uring_cqe *cqe;
SYSCALL(io_uring_wait_cqe(&ring, &cqe));
if (cqe->res < 0) {
perror("cqe res less than 0");
std::cerr << std::strerror(-cqe->res) << std::endl;
}
io_uring_cqe_seen(&ring, cqe);
std::cout << "Reaped " << io_uring_cqe_get_data(cqe) << std::endl;
// this line always prints 0 even though it's supposed to advanced 4096 bytes
std::cout << "Current offset: " << lseek(fd, 0, SEEK_CUR) << std::endl;
}
int main() {
// set up the file and the write buffer
fd = open("test_file", O_CREAT | O_WRONLY | O_DIRECT, 0744);
SYSCALL(fd);
// O_DIRECT has stricter memory alignment requirements
posix_memalign((void**)&buffer, 512, WRITE_SIZE);
for (int i = 0; i < WRITE_SIZE / sizeof(int); i++) {
buffer[i] = i;
}
io_uring_queue_init(5, &ring, 0);
write_buffer_to_file(1);
// set everything in the buffer to 0 and then write again
memset(buffer, 0, WRITE_SIZE);
write_buffer_to_file(2);
io_uring_queue_exit(&ring);
close(fd);
return 0;
}
``` |
Reading this https://devdojo.com/tnylea/laravel-livewire-trix-editor-component article
I added trix-editor on laravel 10 / livewire 3 app / kubuntu 22.04 / Google Chrome
Version 123 / trix 1.3.1 . I dispatch event when I need to update state of parent editor component.
It works, but problem is that changing state with dispatch render method(I retrieve data from db in it) is called again and
I lose all changes in the editor.
I have a trix editor component app/Livewire/TrixEditor.php :
namespace App\Livewire;
use Illuminate\Support\Facades\Storage;
use Livewire\Component;
use Livewire\WithFileUploads;
class TrixEditor extends Component
{
const EVENT_VALUE_UPDATED = 'trix_value_updated';
const IMAGES_PATH = 'public/photos';
public $value;
public $imagesPath;
public $trixId;
public function mount($value = '', $imagesPath = ''){
$this->value = $value;
}
$this->imagesPath = $imagesPath;
$this->trixId = 'trix-' . uniqid();
}
public function updatedValue($value){
$this->value = $value;
$this->dispatch(self::EVENT_VALUE_UPDATED, $this->value); // DISPATCH DATA TO PARENT COMPONENT
}
public function render()
{
return view('livewire.trix-editor');
}
}
in resources/views/livewire/trix-editor.blade.php :
<div wire:ignore>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/trix/1.3.1/trix.min.css"/>
<input id="{{ $trixId }}" type="hidden" name="trix_content" value="{{ $value }}">
<trix-editor
wire:ignore input="{{ $trixId }}"
></trix-editor>
<script src="https://cdnjs.cloudflare.com/ajax/libs/trix/1.3.1/trix.min.js"></script>
</div>
<script>
addEventListener('runInitTrixEditor', event => {
console.log('runInitTrixEditor event.detail::')
console.log(event.detail)
initTrixEditor();
event.stopPropagation();
return false;
})
function initTrixEditor() {
// alert( 'initTrixEditor::' )
console.log('trixEditor FROM initTrixEditor::')
var trixEditor = document.getElementById("{{ $trixId }}")
var mimeTypes = ["image/png", "image/jpeg", "image/jpg"];
addEventListener("trix-blur", function (event) {
console.log('trix-blur trixEditor.getAttribute(value)::')
console.log(trixEditor.getAttribute('value'))
@this.set('value', trixEditor.getAttribute('value')); // I SET VALUE OF app/Livewire/TrixEditor.php component
})
} // function initTrixEditor() {
</script>
and in parent component editor app/Livewire/Admin/NewsCategoryEditor.php I try to use $pageInited var to fetch data only once :
namespace App\Livewire\Admin;
use App\Enums\AppColorEnum;
use App\Enums\DispatchAlertTypeEnum;
use App\Enums\NewsCategory\NewsCategoryActiveEnum;
use App\Library\GetImageProps;
use App\Models\NewsCategory;
use Livewire\Component;
use App\Livewire\Forms\NewsCategoryForm;
use App\Livewire\TrixEditor;
class NewsCategoryEditor extends Component
{
public NewsCategoryForm $form;
public string $id = '';
public array $activeSelectionItems = [];
public array $appColorSelectionItems = [];
public string $updateMode = 'edit';
public bool $pageInited = false;
protected $listeners = [TrixEditor::EVENT_VALUE_UPDATED => 'trixValueUpdated' ];
public function mount(string $id)
{
$this->id = $id;
$this->activeSelectionItems = NewsCategoryActiveEnum::getActiveSelectionItems();
$this->appColorSelectionItems = AppColorEnum::getAppColorSelectionItems();
}
public function render()
{
\Log::info(varDump($this->id, ' -1 NewsCategoryEditor $this->id::'));
\Log::info(varDump($this->pageInited, ' -199 NewsCategoryEditor $this->pageInited::'));
// if(!$this->pageInited) return; // THAT DOES NOT WORK - IT RAISE ERROR
if(!$this->pageInited) {
$newsCategory = NewsCategory
::getById($this->id)
->withCount('news')
->first();
$this->form->setNewsCategory($newsCategory);
$this->form->id = $this->id;
$this->form->created_at = \App\Library\Facades\DateConv::getFormattedDateTime($this->form->created_at);
$this->form->updated_at = ! empty($this->form->updated_at) ? \App\Library\Facades\DateConv::getFormattedDateTime($this->form->updated_at) : '';
$this->dispatch('runInitTrixEditor', ['description'=> $this->form->description]); // I CALL JS METHOD TO FIIL IT WITH DATA FROM DB
$this->dispatch('adminPageChanged', [
'item' => 'NewsCategory',
'item_id' => $this->form->id,
'browser_title' => 'News category editing',
'template_container_id' => "news_category_admin_page_container"
]
);
}
$this->pageInited = true;
return view('livewire.admin.news-category-editor')->layout('components.layouts.admin');
}
public function trixValueUpdated($value){ // THIS METHOD IS USED TO GET DATA FROM TRIX EDITOR
$this->form->setDescription($value);
}
}
When in opened editor I edit data in trix component it works ok only once, but next editing of trix component nothing happens and
console output inside of
addEventListener("trix-blur", function (event) {
mehods show text value I entered first time and I can not catch why so and how that can be fixed ?
|
Why editing data in trix-editor of livewire page rendor method is called again? |
|javascript|laravel-livewire|trix| |
The nextTick and microTask occur on the tick that moves phase by phase.
This means that if the tick does not occur, nextTick or microTask will not occur.
So if Timer, Pending, etc. don't have Callback, Polling is in a waiting state, and nextTick doesn't happen forever, is that correct?
|
What happens if nextTick runs when waiting in Polling phase? |
|node.js|event-loop| |
I am a beginner in Laravel. In one of my forms, I store the text of the textarea in the database.
{!! Form::textarea('mline', isset($mline) ? strip_tags($mline) : null, ['style'=>'height: 113px;width:150%;','class'=>'p-2']) !!}
If the text inside the textarea is multiple lines, each line is stored in the database with the `<p>` tag at the beginning and end of the line. As below:
<p>line 1</p><p>line 2</p>
In the edit form, when reading from the database and writing to the textarea as it is stored in the database, the text is displayed with the `<p>` tag.
While I want the text to be displayed in the original format and the lines below it without the `<p>` tag.
I also used the strip_tags($string) function, but it only removes the `<p>` tags and the lines are displayed consecutively and stuck together.
How can I display lines in html format without displaying tags?
|
how to write multiline text to textarea in laravel |
|laravel| |
I am reaching out to inquire about the feasibility of integrating user status information from Microsoft Teams into our SharePoint Framework (SPFx) solution.
As we strive to enhance collaboration and communication within our organization, we believe that having real-time visibility into users' availability statuses hours (such as available, away, busy, in a call, out of office hours) directly within our SharePoint environment could greatly improve productivity and streamline workflow processes.
Could anyone please provide insight into whether it is possible to access and retrieve user status information from Teams programmatically? Additionally, we are interested in understanding any potential challenges or limitations associated with implementing such functionality within SPFx.
Your expertise in this matter would be greatly appreciated. |
Inquiry Regarding Feasibility of Fetching User login hours(In numbers) Status from Teams for SPFx Integration |
Actually what happens is ,I saved my all code HTML, CSS and JavaScript code using notepad but when locally run in my laptop everything is functioning well except css code no colour, bg , table are shown.
I tried using a website called codepen the results are shown there properly but not while using the website locally. Kindly help me out. |
My HTML, CSS, and JavaScript code run fine on CodePen but locally on my laptop, the CSS doesn't apply? |
A trie of characters. A tree-like data structure used to store a dynamic set of strings where each node represents a single character.
[![enter image description here][1]][1]
* Time Efficiency: Search, Insertion & Deletion: With a time complexity of O(m) where m is the length of the string.
* Space Efficiency: Store the unique characters present in the strings. This can be a space advantage compared to storing the entire strings.
Example:
```cpp
#include <unordered_map>
#include <string_view> // (Since C++17)
#include <memory>
#include <iostream>
// A trie of characters.
class Trie final
{
public:
// Function to insert a string into the trie.
void Insert(const std::string_view string_view)
{
if (!string_view.empty()) {
Insert(root_, string_view);
}
}
// Function to find the common prefix among trie strings.
auto CommonPrefix() const
{
std::string common_prefix{};
CommonPrefix(root_, common_prefix);
return common_prefix;
}
private:
// Trie__
// Structure representing a node in the trie.
struct Node final
{
std::unordered_map<char, std::unique_ptr<Node>> child_node{}; // Map of child nodes.
bool end_of_string{ false }; // Flag to indicate end of a string
};
Node root_{}; // Root node of the trie (Represents a null prefix.)
// __Trie
// Recursive function to insert a string into the trie.
void Insert(Node& root, const std::string_view string_view)
{
if (string_view.empty()) {
root.end_of_string = true; // Mark the end of the string
return;
}
char first_char{ string_view[0] }; // Get the first character of the string.
std::string_view remaining_view{ string_view.substr(1) }; // Get the substring starting from index 1.
if (root.child_node.find(first_char) == root.child_node.end()) {
// If the character does not exist in the trie, create a new node and insert it into the child nodes map.
root.child_node[first_char] = std::make_unique<Node>();
}
Insert(*root.child_node[first_char], remaining_view); // Recursively insert the remaining substring.
}
// Recursive function to find the common prefix among all inserted strings.
void CommonPrefix(const Node& root, std::string& common_prefix) const
{
// Check if there's only one child node and it's not the end of a string
if (root.child_node.size() != 1 || root.end_of_string) {
return;
}
common_prefix += root.child_node.begin()->first; // Append the current character to the common prefix.
CommonPrefix(*root.child_node.begin()->second, common_prefix); // Recursively find the common prefix in the next node.
}
};
int main()
{
// Create a trie object.
Trie trie{};
// Insert strings into the trie.
trie.Insert("/home/texai/www/app/application/cron/logCron.log");
trie.Insert("/home/texai/www/app/application/jobs/logCron.log");
trie.Insert("/home/texai/www/app/var/log/application.log");
trie.Insert("/home/texai/www/app/public/imagick.log");
trie.Insert("/home/texai/www/app/public/status.log");
// Find and print the common prefix among all inserted strings.
std::cout << "common prefix: " << trie.CommonPrefix() << std::endl;
}
```
Output:
```
common prefix: /home/texai/www/app/
```
[Demo][2]
--
PATRICIA trie. It can be even more efficient with PATRICIA (Practical Algorithm To Retrieve Information Coded In Alphanumeric), as @greybeared drew my attention to. You can read about it here: https://en.m.wikipedia.org/wiki/Radix_tree#PATRICIA
[1]: https://i.stack.imgur.com/NQOHB.png
[2]: https://onlinegdb.com/XoYMFq0hC |
i was testing for an attendance website, logging attendance on different dates (manually changing the date on my device) i have a status column 1 for present and 0 for absent. when i log an attendance where some are absent, the status column on that date are reflected correctly but when I log an attendance where all are present, the status column values on all dates (including the ones with '0') are all changed to '1'. below is the code for the save
```
if(isset($_POST['save'])){
$studentNo=$_POST['studentNo'];
$check=$_POST['check'];
$N = count($studentNo);
$status = "";
$qurty=mysqli_query($conn,"select * from tblattendance where subject = '$id' and date = '$dateTaken' and status = '1'");
$count = mysqli_num_rows($qurty);
if($count > 0){
$statusMsg = "<div class='alert alert-danger' style='margin-right:700px;'>Attendance has been taken for today!<button type='button' class='close' data-dismiss='alert' aria-label='Close'><span aria-hidden='true'>×</span></button></div>";
}else
{
for($i = 0; $i < $N; $i++)
{
$studentNo[$i];
if(isset($check[$i]))
{
$qquery=mysqli_query($conn,"update tblattendance set status='1' where studentNo= '$check[$i]'");
if ($qquery) {
$statusMsg = "<div class='alert alert-success' style='margin-right:700px;'>Attendance Taken Successfully!<button type='button' class='close' data-dismiss='alert' aria-label='Close'><span aria-hidden='true'>×</span></button></div>";
}
else
{
$statusMsg = "<div class='alert alert-danger' style='margin-right:700px;'>An error Occurred!</div>";
}
}
}
}
}
```
```
$query = "SELECT tblsection.section,tblassignteach.secId,tblclass.className,tblsubject.subject,tblstudents.secId,tblstudents.studentNum,tblstudents.firstName,tblstudents.lastName,tblstudents.mname,tblstudents.sex,tblstudents.classId FROM tblstudents
INNER JOIN tblassignteach ON tblassignteach.secId = tblstudents.secId
INNER JOIN tblsection ON tblsection.Id = tblstudents.secId
INNER JOIN tblclass ON tblclass.Id = tblstudents.classId
INNER JOIN tblclassarms ON tblclassarms.Id = tblassignteach.classArmId
WHERE tblassignteach.subject='$id'";
$rs = mysqli_query($conn, $query);
$num = $rs->num_rows;
$sn=0;
$status="";
if($num > 0)
{
while ($rows = $rs->fetch_assoc())
{
$sn = $sn + 1;
echo"
<tr>
<td><input name='check[]' type='checkbox' value=".$rows['studentNum']." class='form-control'></td>
<td>".$sn."</td>
<td>".$rows['studentNum']."</td>
<td>".$rows['lastName']."</td>
<td>".$rows['firstName']."</td>
<td>".$rows['mname']."</td>
<td>".$rows['sex']."</td>
<td>".$rows['className']."</td>
<td>".$rows['section']."</td>
<td>".$rows['subject']."</td>
</tr>";
echo "<input name='studentNo[]' value=".$rows['studentNum']." type='hidden' class='form-control'>";
}
}
```
```
$qurty=mysqli_query($conn,"SELECT * from tblattendance where subject= '$id' and dateTimeTaken = '$dateTaken'");
$count=mysqli_num_rows($qurty);
if($count == 0){
$qus=mysqli_query($conn,"SELECT tblstudents.studentNum,tblassignteach.subject from tblstudents
inner join tblassignteach on tblassignteach.secId = tblstudents.secId
where tblassignteach.subject= '$id'");
while ($ros = $qus->fetch_assoc())
{
$qquery=mysqli_query($conn,"INSERT into tblattendance(studentNo,subject,sessionTermId,status,dateTimeTaken,timeTaken)
VALUES('$ros[studentNum]','$id','$sessionTermId','0', '$dateTaken', '$ttimeTaken')");
}
```
i'm wondering why all the values in all logged dates in the db are changed to '1' and if there is a way to fix this. if you need anything else, please dont hesitate to let me know and I really appreciate all the help i can get. thank you in advance! |
Could someone explain what the `PhantomReference` class is intended for in Java older than Java 9? This class was introduced at December 1998 in Java 1.2 by Mark Reinhold and it's not clear what was the intention of the author. At September 2017 in Java 9 the `finalize()` method was deprecated and marked for removal but it isn't removed even in Java 22. As an alternative to that deprecated method the `Cleaner` class was added, that uses the `PhantomReference` class internally to free resources without using a reference to the garbage collected object that holds them. Using the `PhantomReference` class directly (i.e. before the `Cleaner` class was introduced) seems to be over complicated. And considering that even the `finalize()` method is rarely used even in code for Java older than Java 9 the `PhantomReference` class seems to be practically never used before Java 9. I can't imagine anyone writing something like the following homemade analogue of the `Cleaner` class instead of implementing just the `finalize()` method before Java 9.
```java
import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;
import java.util.*;
class ModernFinalizingObject {
private static final ReferenceQueue<ModernFinalizingObject> referenceQueue = new ReferenceQueue<>();
private static final Set<FinalizingPhantomReference> phantomSet = new HashSet<>();
protected final Collection<AutoCloseable> resources = new LinkedList<>();
{
phantomSet.add(new FinalizingPhantomReference(this, referenceQueue, resources));
}
static {
var th = new Thread(() -> {
while (true) {
try {
var phantomRef = (FinalizingPhantomReference) referenceQueue.remove();
phantomRef.modernFinalize();
phantomSet.remove(phantomRef);
} catch (InterruptedException e) {
throw new RuntimeException("someone is cheating", e);
}
}
});
th.setDaemon(true); // don't block shutting down
th.start();
}
protected <T extends AutoCloseable> T meetResource(T resource) {
resources.add(resource);
return resource;
}
}
class FinalizingPhantomReference extends PhantomReference<ModernFinalizingObject> {
private final Collection<AutoCloseable> resources;
public FinalizingPhantomReference(ModernFinalizingObject referent,
ReferenceQueue<? super ModernFinalizingObject> referenceQueue,
Collection<AutoCloseable> resources) {
super(referent, referenceQueue);
this.resources = resources;
}
public void modernFinalize() {
resources.forEach(r -> {
try {
r.close();
} catch (Exception e) {
// ignore
}
});
}
}
class Resource implements AutoCloseable {
public void doSomething() {
System.out.println("Resource " + hashCode() + " is doing something");
}
@Override
public void close() {
System.out.println("Resource " + hashCode() + " is closed.");
}
}
class ModernFinalizingService extends ModernFinalizingObject {
private Resource resource1 = meetResource(new Resource());
private Resource resource2 = meetResource(new Resource());
public void doSomething() {
System.out.println("Service is doing something...");
resource1.doSomething();
resource2.doSomething();
}
}
class Main {
public static void main(String[] args) throws Exception {
ModernFinalizingService service = new ModernFinalizingService();
service.doSomething();
// make it ready to be collected as a garbage
service = null;
// advice the JVM to run Garbage Collector
System.gc();
// emulate the real work is continuing, giving some time to all the above finalization finishing
Thread.sleep(500);
System.out.println("Bye!");
}
}
``` |
What the PhantomReference class is intended for besides its usage in the Cleaner class? |
## The Really Easy Way to Generate SwiftUI Custom Shapes
[](https://i.stack.imgur.com/fPUBP.png)
### Why would I do this?
As developers we, sooner or later, find ourselves wanting to add some clever custom shape to our application user interface. SwiftUI provides basic shapes like ellipse, rectangle and rounded rectangle and also the ability to produce a more complex shape in code but no tools to do that. Yes, SVG or PDF will definitely do the job if you need resolution independent graphics and you can certainly drop in a PNG if you don’t need to worry about scaling artifacts but all of these options have a couple of drawbacks
**Size:** Even the simplest PDF or SVG is a text file with the coordinates of the control points stored as text. SVG is pretty sparse but even a simple ellipse saved as a PDF is going to cost you seven or eight kilobytes. More complex shapes are going to be even worse.
Even though the code to create a SwiftUI Shape is also text in a swift file, it’s important to remember that that file is compiled down to a set of binary instructions in the compiled app and therefor is likely to be quite a bit smaller.
**Versatility:** A SwiftUI Shape can be easily rotated, scaled, skewed etc. and it can have complex shading and stroking applied to it. Also a single shape can be reused in code with different transformations and shading for each instance.
**Security:** Image files like SVG, PDF, PNG etc. are in your application bundle as files and can be copied out of the apps bundle. This is particularly easy in MacOS apps. A shape that is compiled into the applications code can’t be borrowed.
## What do I need to do this?
Since it's now allowed to name an app, no matter how useful to solving the problem at hand, I'm going to not name the app that is so helpful. If you are intrigued you can go look at inexpensive graphics apps on the app store to try and guess which one it is. From here on I will call this mystery app Garbanzo.
As has been suggested by other writers in these forums there are a number of tools and utilities that used together can get you from a bezier shape to a SwiftUI code snippet to do a shape in code. But it turns out that there is an unknown and highly underrated app on the Mac App Store called Garbanzo that will the the whole job from start to finish with relatively easy to use tools in just a few steps.
The one catch is that you can do all the drawings you want in Garbanzo for free but you cannot export or print anything without paying a small monthly subscription (about the cost of a mocha at Starbucks or a half hour at minimum wage). If you are trying this for the first time and maybe don’t need to do it often there is a free one month trial period and you can easily cancel the subscription after that.
## How do I do this?
Here’s the problem you need to solve. You want to add the letter “A” as a shape to a view in your SwiftUI app so that you can render it with a custom gradient fill and a stroke. You would like a SwiftUI.Path for this but even a simple shape like an ellipse has difficult geometry to write as code on your own. Here are the steps in Garbanzo
1. Open DoodleCAD to a new canvas.
2. Select the text tool.
3. Click drag a box on the canvas for that text, make it pretty big. [](https://i.stack.imgur.com/eixlZ.png)
4. In the text inspector in the panel on the right (you might have to expand it) type “A”
5. Select the text in the inspector and in the windows text properties on the top left of the window select the font and size you want. I used 92 point Noteworthy since it’s kind of a fun font.[](https://i.stack.imgur.com/M81NI.png)
6. Expand the box around the text if some of it is obscured.
7. Right click on the the text box on the canvas and at the bottom of the contextual menu click “Text Element” -\> “Convert to Path Group”
8. The app creates a group containing a shape for each of the characters in the text even if it’s a single character so you will want to ungroup it by clicking the little ungroup button in the toolbar. You might have to unselect and reselect to get the toolbar to update. The original text will still be there so you might want to delete it to avoid confusion. Also I'm using a character converted to a path as a good, quick example that's pretty cool but you can draw any sort of shape you want with the tools. [](https://i.stack.imgur.com/vApps.png)[](https://i.stack.imgur.com/1wKei.png)
9. Scale and rotate the shape however you want and also, if you want, you can edit the path one vertex at a time.
10. Select the shape and then click in the menu bar File -\> Export to … -\> SwiftUI Path …
11. Even without a subscription you can see the code snippet that was generated and if you want to use it, click the “Copy to Clipboard” button that appears if you have a subscription (or free trial).[](https://i.stack.imgur.com/X7c0r.png)
12. Just create a new Swift file in your Xcode project with a struct or class that can hold the code and paste the snippet in.
13. You're done. Now just use the shape in your code.
Here's a fragment of the generated SwiftUI code:
```
// Stroke, Fill and Line Widgets not supported yet.
// SwiftUI Code for A
@ViewBuilder
var a: some View {
SwiftUI.Path { path in
path.move(to: CGPoint(x: 42.24, y: 39.92))
path.addCurve(
to: CGPoint(x: 38.80, y: 43.84),
control1: CGPoint(x: 42.24, y: 42.48),
control2: CGPoint(x: 41.09, y: 43.79)
)
path.addCurve(
to: CGPoint(x: 40.56, y: 48.80),
control1: CGPoint(x: 39.07, y: 45.07),
control2: CGPoint(x: 39.65, y: 46.72)
)
```
## Conclusion:
As you can see, by far the most complicated part of this is creating the path for the letter "A" and even that isn't very complicated. Happy coding. |
I am using a Huawei E3372 4G USB dongle on Win8.1. This dongle's settings can be accessed via browser by typing 192.168.8.1 and the user can enable a 4G connection by manually clicking the "Enable mobile data" button.
This is the script I am trying to use to "Enable mobile data" connection, knowing I'm doing something wrong only on line 4:
```
#!/bin/bash
curl -s -X GET "http://192.168.8.1/api/webserver/token" > token.xml
TOKEN=$(grep -v '<?xml version="1.0" encoding="UTF-8"?><response><token>' -v '</token></response>' token.xml)
curl "http://192.168.8.1/api/dialup/mobile-dataswitch" -H "Host: 192.168.8.1" -H "User-Agent: Mozilla/5.0 (Windows NT 6.3; rv:68.0) Gecko/20100101 Goanna/4.8 Firefox/68.0 PaleMoon/29.0.1" -H "Accept: */*" -H "Accept-Language: en-US,en;q=0.5" --compressed -H "Content-Type: application/x-www-form-urlencoded; charset=UTF-8;" -H "_ResponseSource: Broswer" -H "__RequestVerificationToken: $TOKEN" -H "X-Requested-With: XMLHttpRequest" -H "Referer: http://192.168.8.1/html/content.html" -H "Cookie: SessionID=AgVjkIjBxOC0xPbys3nne7rA4I8GXNzUkZCcSOGPR8P3xss8XOuqRbdb0EgHidXhQXZ903xf0nk0F8J81ISqHpZ7kYvZaSW5wHWDqJ9w90pXj90cPwCm7F01fFcmp0gv" -H "Connection: keep-alive" --data-raw "<?xml version=""1.0"" encoding=""UTF-8""?><request><dataswitch>1</dataswitch></request>"
date
exec $SHELL
```
Upon executing the first curl command, the xml file's content would look like this:
```
<?xml version="1.0" encoding="UTF-8"?><response><token>ZsxY7Q9G90jh4FqUiAjxD9XmqLWf0rYg4RUNf6FoVzeTIlPPms0Ov1RERFFRY77o</token></response>
```
Just for test purposes, if I manually insert the token in the bash script, it works like a charm:
```
#!/bin/bash
curl "http://192.168.8.1/api/dialup/mobile-dataswitch" -H "Host: 192.168.8.1" -H "User-Agent: Mozilla/5.0 (Windows NT 6.3; rv:68.0) Gecko/20100101 Goanna/4.8 Firefox/68.0 PaleMoon/29.0.1" -H "Accept: */*" -H "Accept-Language: en-US,en;q=0.5" --compressed -H "Content-Type: application/x-www-form-urlencoded; charset=UTF-8;" -H "_ResponseSource: Broswer" -H "__RequestVerificationToken: ZsxY7Q9G90jh4FqUiAjxD9XmqLWf0rYg4RUNf6FoVzeTIlPPms0Ov1RERFFRY77o" -H "X-Requested-With: XMLHttpRequest" -H "Referer: http://192.168.8.1/html/content.html" -H "Cookie: SessionID=AgVjkIjBxOC0xPbys3nne7rA4I8GXNzUkZCcSOGPR8P3xss8XOuqRbdb0EgHidXhQXZ903xf0nk0F8J81ISqHpZ7kYvZaSW5wHWDqJ9w90pXj90cPwCm7F01fFcmp0gv" -H "Connection: keep-alive" --data-raw "<?xml version=""1.0"" encoding=""UTF-8""?><request><dataswitch>1</dataswitch></request>"
date
exec $SHELL
```
I've found several suggestions for the same or similar dongles, none of them worked for me, it must be due to my insufficient knowledge. My cry for help is about line 4 of the top-most script. I am making a mistake somewhere obviously.
Thank you in advance for your help.
===== EDIT: SOLUTION IS FOUND ! =====
markp-fuso's suggestion was the path to my solution. Kudos. I just noticed that besides a variable "token" which was changing upon each "on/off" action, this dongle also had a less variable "SesTokInfo" which is not being changed upon each "on/off" action (I just tested that manually) and it is different than what it was yesterday. It could be "plug/unplug" of dongle that causes that, I honestly can't know.
To whom it may concern: The final form of the working script which I've just tested with positive result twice would be:
```
#!/bin/bash
curl -s -X GET "http://192.168.8.1/api/webserver/token" > token.xml
curl -s -X GET "http://192.168.8.1/api/webserver/SesTokInfo" > sestoken.xml
TOKEN=$(sed -En 's|.*<token>(.*)</token>.*|\1|p' token.xml)
SESTOKEN=$(sed -En 's|.*<SesInfo>(.*)</SesInfo>.*|\1|p' sestoken.xml)
typeset -p TOKEN
typeset -p SESTOKEN
curl "http://192.168.8.1/api/dialup/mobile-dataswitch" -H "Host: 192.168.8.1" -H "User-Agent: Mozilla/5.0 (Windows NT 6.3; rv:68.0) Gecko/20100101 Goanna/4.8 Firefox/68.0 PaleMoon/29.0.1" -H "Accept: */*" -H "Accept-Language: en-US,en;q=0.5" --compressed -H "Content-Type: application/x-www-form-urlencoded; charset=UTF-8;" -H "_ResponseSource: Broswer" -H "__RequestVerificationToken: $TOKEN" -H "X-Requested-With: XMLHttpRequest" -H "Referer: http://192.168.8.1/html/content.html" -H "Cookie: SessionID=$SESTOKEN" -H "Connection: keep-alive" --data-raw "<?xml version=""1.0"" encoding=""UTF-8""?><request><dataswitch>1</dataswitch></request>"
date
exec $SHELL
``` |
You should use `schema`, not `columns` as parameter to set up the column names in [`DataFrame`](https://docs.pola.rs/py-polars/html/reference/dataframe/index.html):
```
df = pl.DataFrame(noisy_data.tolist(),
schema=[f'col_{i}' for i in range(num_columns)])
```
As described in the documentation:
> schema: Sequence of str, (str,DataType) pairs, or a {str:DataType,} dict
>
> The schema of the resulting DataFrame. The schema may be declared in several ways:
>
> - As a dict of {name:type} pairs; if type is None, it will be auto-inferred.
>
> - **As a list of column names; in this case types are automatically inferred.**
>
> - As a list of (name,type) pairs; this is equivalent to the dictionary form.
>
> If you supply a list of column names that does not match the names in the underlying data, the names given here will overwrite them. The
> number of names given in the schema should match the underlying data
> dimensions.
>
> If set to None (default), the schema is inferred from the data.
|
C:\Users\user>npm --version
The syntax of the command is incorrect.
Tried uninstalling and installing node the error persists.. Tried node installing 20,18 these two versions still same..
[1]: https://i.stack.imgur.com/b9N2X.png |
@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
|
Spring boot project |
|java|spring-boot|jpql| |
null |
The MedaCy library is dependent on Python version 3.7. Using Python version 3.7.0 worked completely fine. Follow the below steps with python 3.7 installed:
1. `pip install git+https://github.com/NLPatVCU/medaCy.git`
2. `pip install git+https://github.com/NLPatVCU/medaCy_model_clinical_notes.git`
[output image][1]
[1]: https://i.stack.imgur.com/dI6jf.png |
I've managed to run Visual Studio 2022 from WSL2 this way:
```bash
# Path to Visual Studio executable
VSRUN='C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\Visual Studio 2022.lnk'
function open_in_vs() {
# Take first passed argument and generate absolute path
FIRST_ARG=`realpath $1`
# Convert path (which is now in Unix style) to Windows path
PATH_TO_FILE=`wslpath -w $FIRST_ARG`
# Run process using PowerShell
powershell.exe "Start-Process '${VSRUN}' '${PATH_TO_FILE}'"
}
# open_in_vs ./testfile.txt
# This adds an `openvs` alias you can use in your terminal to open any file in VS
alias openvs=open_in_vs
``` |
I integrate with DocuSign as an ISV (SaaS product).
I want the authentication process to be of the Admin Consent type using code grant flow.
According to what I checked in this way, if a user with admin privileges in DocuSign performs the authentication, he thereby eliminates the need for the other users in his organization to do the identification and grant permissions to my application.
According to what I understood, in order for this process to happen the side that allows me to connect to his DocuSign account needs to have an account with Admin and Organization management capabilities (in DocuSign terms).
I did a POC that simulates this process and in the exchange process of the ```code``` in the ```access_token``` I really received a response that contains the ```id_token field```.
When I decoded the ```id_token```, I received an object with several fields, but as far as I understand, the ```coid``` field, which is necessary to continue the process, is not there.
My questions are:
1. Am I correct in my assumption about Admin Consent?
My goal is that based on the authentication of one user I will be able to make API requests on behalf of the other users.
2. Is the ```coid``` field really necessary to fulfill the above requirement? And if so, why doesn't it appear for me?
---
Update - 31/03
Inbar and Larry thanks for your answers.
I read what you wrote and made several changes so that my current situation is this:
1. I have a demo account that serves as the host for the integration app (holds the integration and secret keys).
2. I have another account that simulates my customer account. In this account I defined an organization, made a domain claim and added 2 users with an email that matches the domain.
I performed the admin consent process again through one of the users who is defined as admin so that I got to the point where I receive the code and turn it into an access token.
In the reponse of that request I received the id_token field. After I decoded it I got a list of fields but the coid field was not part of them.
What am I missing here?
And is it really recommended to do this process and not simply ask for consent from each user individually?
It's just that my product manager is very pushing for me to implement the Admin Consent to make it easier for our users to use the integration I'm developing. |
I want to use the deepL API in a C# project. I want to translate from one into 3 different languages and work with a single glossary for each language pair.
However - a glossary is not static and from time to time it needs to be updated - e.g. by extending it by a new word pair or replacing or deleting an old one.
In the deepL API documentation @gitHub I find only methods to create or delete a glossary completely:
// Create an English to German glossary with two terms:
var entriesDictionary = new Dictionary<string, string>{{"artist", "Maler"}, {"prize", "Gewinn"}};
var glossaryEnToDe = await translator.CreateGlossaryAsync("My glossary", "EN", "DE",
new GlossaryEntries(entriesDictionary));
After that I can get the glossary ID and work with it referencing the glossary by its ID.
But I don't find a method of how to extend and update the glossary once it was created.
Let's say I want to add the new pair {"age", "Alter"} - How can I add it to the existing glossary?
Besides that I want to check if there is already an entry for "age" and then replace the pairing by the new one.
A possibility to delete existing entries would also be necessary.
The only solution I found so far would be to export the whole glossary, do the described actions on the exported list, then delete the original glossary and create a new one.
But that seems to be ridiculous - and I would end up with a new glossary ID every time. |
I have a bearer token that is generated upon successful login. However, when I use this token in the 'auth:api' middleware to recognize the user via `$request->user`, it nullifies my image description. How can I configure my project to apply JWT, without losing anything in the `config/app.php` file?
[enter image description here](https://i.stack.imgur.com/EgKnM.png)
[enter image description here](https://i.stack.imgur.com/BUnEN.png)
I want to fix the problem to run my project. |
Authenticating with JWT in Laravel 11 |
|php|laravel|laravel-11| |
We had to motion detect a pendulum by filming it,track the pendulum with a given software and store the t,x and y values in a txt-file. Since my hands were very shaky, the graph is very shaky (image attached).
[data and fit](https://i.stack.imgur.com/UW8tu.png)
This is my code:
```
import sys
sys.path.insert(0, "..")
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
%matplotlib inline
import pandas as pd
data = np.loadtxt('newdata.txt', delimiter = ',', skiprows = 1)
t = data[:,0]
x = data[:,1]
def cos_func(times, amplitude, frequency):
return amplitude * np.cos(frequency * times)
def period2freq(period):
return 1.0 / period * 2.0 * np.pi
def freq2period(freq):
return 1.0 / freq * 2.0 * np.pi
popt, pcov = curve_fit(cos_func, # our function
t, # measured x values
x, # measured y values
p0=(200, period2freq(150))) # the initial guess for the two parameters
fig, ax = plt.subplots(1, 1)
ax.plot(t, x, label='Measured')
ax.plot(t, cos_func(t, popt[0], popt[1]), label='Best Fit')
ax.legend()
```
I tried something, this is my code now and the image, still bad:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
# Laden der Daten
data = np.loadtxt('newdata.txt', delimiter = ',', skiprows = 1)
t = data[:,0]
x = data[:,1]
# Definition der Fit-Funktion mit Offset und Phase
def cos_func(times, amplitude, frequency, phase, offset):
return amplitude * np.cos(frequency * times + phase) + offset
# Startparameter für den Fit
initial_amplitude = (np.max(x) - np.min(x)) / 2 # Amplitude als Hälfte der Amplitude der Daten
initial_frequency = 2 * np.pi / 150 # Annahme für die Frequenz
initial_phase = 0 # Startphase
initial_offset = -220 # Ihr Offset-Wert
shift = 10 # Verschiebung um 5 Einheiten nach rechts
# Durchführung des Fits
p0 = (initial_amplitude, initial_frequency, initial_phase, initial_offset)
popt, pcov = curve_fit(cos_func, t, x, p0=p0)
# Anpassen der Phase für die Verschiebung nach rechts
popt[2] += shift * initial_frequency
# Plotten der Daten und des Fits
plt.figure(figsize=(10, 6))
plt.plot(t, x, label='Measured')
plt.plot(t, cos_func(t, *popt), label='Best Fit')
plt.legend()
plt.xlabel('Time')
plt.ylabel('Position')
plt.title('Fit of Pendulum Motion')
plt.show()
<!-- end snippet -->
[new photo][1]
I honestly just played around so it looked a bit better, but it's still bad and I don't understand it.
[1]: https://i.stack.imgur.com/ZYoFu.png |
Writes in io_uring do not advance the file offset |
|linux|io|io-uring| |
null |
null |
In .Net 9 you could do the below using LINQ.
var wordFrequencies = text.Split()
.CountBy(word => word)
.OrderByDescending(freq => freq.Value);
foreach (var word in wordFrequencies)
{
Console.WriteLine($"{word.Key}: {word.Value}");
} |
As it stands, its not going to be possible since the return type of the function is dependent on a runtime argument - the compiler cannot determine what is the return type of the function.
On a side but slightly related note, there is a talk in cppcon23 about symbolic calculus, which relates to how symbols and expressions can be represented in C++: https://www.youtube.com/watch?v=lPfA4SFojao
|
Undefined function getAdminPanelUrlPrefix()'error in Laravel SaaS project after installing chatmessenger |
The relevant part of [the documentation](https://doc.rust-lang.org/std/fs/fn.rename.html) is this:
> On Unix, if […] `from` is not a directory, `to` must also be not a directory. In contrast, on Windows, `from` can be anything, but `to` must not be a directory.
I.e. `to` *may not be* a directory, but you've passed the name of a directory to the second parameter.
So you'll have to append the file name to the directory name yourself:
```rust
let file_path = PathBuf::from("apps/a");
let mut destination_path = PathBuf::from("apps/test/");
destination_path.push(file_path.file_name().unwrap());
let result = fs::rename(file_path, destination_path).unwrap();
``` |
`h2o.predict` returns an "H2OFrame". That is not expected as almost all predict methods return a data.frame. You transform the input data to a H2OFrame, but you also need to transform the output data to a data.frame:
```
dnn_pred <- function(model, data, ...) {
predict(model, newdata=as.h2o(data), ...) |> as.data.frame()
}
p <- predict(logo, model=dl_model, fun=dnn_pred)
plot(p, nr=1, mar=c(1,2,1,4))
```
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/im7jc.png |
I found a solution. It is probably a dirty solution, but it works.
The problem was to terminate my Activity just after the user manually grant the right MANAGE_EXTERNAL_STORAGE, knowing that :
- even after the user grant the permission, my Activity did not have the right (1)
- more over, if I end my Activity by finish() and start the app again, the new activity have not the right. I do not find explanation for that , It look like the new activity keep some context of the previous one.
My solution is to kill my pid. I had implemented in my app the ability to launch bash commands. So I kill the pid of my Activity after launching new activity:
static String HaraKiri = "sleep 2;PID=$(ps -ef | grep 'eu.eduphone.install' | grep -v 'grep' | grep -v 'eu.eduphone.install.' |awk '{ print $2 }');echo \"PID=$PID\";kill -15 \"$PID\"";
...
private void Restart() {
Intent intent = new Intent();
String name=getActivity().getPackageName();
Log.d("Thierry", "Restartn Name = "+name);
intent.setComponent(new ComponentName(name, name+".MainActivity"));
startActivity(intent);
ShellExec(HaraKiri);
}
That works, the new activity can read the USB Dongle.
**(1) About the reason what we must restart Activity to get the right after the user grant it :**
In another discussion, https://github.com/termux/termux-app/issues/71#issuecomment-1869222653 , https://github.com/agnostic-apollo says that :
- Unreliable/Removable volumes like USB OTG devices that are only
available on the /mnt/media_rw paths with their own filesystem
(vfat/exfat) are assigned the root (0) owner and external_storage
(1077) group.
- If an app has been granted the MANAGE_EXTERNAL_STORAGE permission,
then the external_storage (1077) group is added to list of groups
that are assigned to the app process when its forked from zygote,
allowing it to access unreliable/removable volumes with the
external_storage (1077) group.
My running activity is not in the group 1077 because it has been forked before this group was assigned to the app.
|
Typing a function decorator with conditional output type, in Python |
|python|mypy|python-typing| |
{"Voters":[{"Id":8446,"DisplayName":"Roger Lipscombe"},{"Id":446594,"DisplayName":"DarkBee"},{"Id":4267244,"DisplayName":"Dalija Prasnikar"}],"SiteSpecificCloseReasonIds":[18]} |
What is the area of the 2-dimensional shape given by the inequality x^2 ≤ y ≤ exp(–x^2), rounded to 4 decimal digits?
I tried to solve it but i couldn't, even google was not of a great help , so please help me
thank you so much in advance |
Solving the area of a 2 dimensional shape |
|math| |
null |
I do understand how `Cache-Control` header works. However, I noticed that **the browser treats the document request differently from other requests**. The document request here is **the first request that the browser makes** when the user types the domain on the address bar and hits enter.
I tested an HTML page with the response header as follows:
```
Cache-Control: public, max-age=31536000, immutable
```
The header tells that the browser should cache the response for 1 year. **But in the case document request, both Chrome and Firefox will revalidate it anyway**. The evidence for it is the **304 response status**.
[![enter image description here][1]][1]
Here is the test URL: https://test-http-cache-2exijs7pxj7x.runkit.sh/
I can not find an official document for this behavior. So it would be nice if someone could explain **how the browser caches the document request** and **refers to an official document**.
Thanks in advance!
# Edit
The outcome mentioned above is the result of a **soft reload** (when the user hits the reload button or re-enters the same address). For navigation requests, the browser respects the Cache-Control and serves the response from the cache
[1]: https://i.stack.imgur.com/qTvrQ.png |
{"Voters":[{"Id":182668,"DisplayName":"Pointy"},{"Id":16540390,"DisplayName":"jabaa"},{"Id":14732669,"DisplayName":"ray"}],"SiteSpecificCloseReasonIds":[13]} |
I have setup & initiate an RecyclerView `mainWatchList`, and ArrayList `stockPriceList` in MainActivity `OnCreate()` function, and also have `StockPrice()` function in MainActivity in which I am adding data to ArrayList `stockPriceList`, and using `minWatchList` recyclerView adapter `stockPriceAdapter.notifyDataSetChanged();` to refresh the data changed.
I have create 2 RecyclerViews `suggestList & mainWatchList` and when someone clicks itemView of `suggestList` itemView.OnClickFunction is called and It passes the arrayList postion and also calls the `StockPrice` Function.
But at last, When I am trying to run program it shows error that `stockPriceList.add(new defualtWatchListModel(Name, symbol, price));` stockPriceList is null and you can't add into.
Error:[![Here is the Image of Error][1]][1]
Code of MainActivity.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
suggestList = findViewById(R.id.suggestList);
searchBar = findViewById(R.id.searchBar);
stockModelClassesArray = new ArrayList<>();
requestQueue = Volley.newRequestQueue(MainActivity.this);
suggestList.setLayoutManager(new LinearLayoutManager(this));
suggestAdapter = new stockSuggestAdapter(stockModelClassesArray, MainActivity.this);
suggestList.setAdapter(suggestAdapter);
// Setting up Main Activity ArrayList.
mainWatchList = findViewById(R.id.defaultWatchList);
stockPriceList = new ArrayList<>();
mainWatchList.setLayoutManager(new LinearLayoutManager(this));
stockPriceAdapter = new StockPriceAdapter(stockPriceList, MainActivity.this);
mainWatchList.setAdapter(stockPriceAdapter);
}
also in Main Activity StockPrice Function Code:
public void StockPrice() {
String name = Name;
String Symbol = symbol;
String price = "$20";
stockPriceList.add(new defualtWatchListModel(Name, symbol, price));
stockPriceAdapter.notifyDataSetChanged();
}
}
Code From suggestList RecyclerView Adapter in which StockPrice() function have been called:
public class ViewHolder extends RecyclerView.ViewHolder {
TextView symbol, name, exchange, type;
public ConstraintLayout listContainer;
public ViewHolder(@NonNull View itemView) {
super(itemView);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MainActivity mainActivity = new MainActivity();
stockModelClass positionedStock = stockModelClassArrayList.get(getAbsoluteAdapterPosition());
mainActivity.OnClickItemViewListener(positionedStock.getName(), positionedStock.getSymbol());
// Run this one
mainActivity.StockPrice();
stockModelClassArrayList.clear();
notifyDataSetChanged();
}
});
}
}
[1]: https://i.stack.imgur.com/P3bgT.png |
In an application i have 2 types of users `vendor` and `buyer` want to manage the routing in such a away the vendor can not access buyer pages and vice versa using React Router Dom V6. Attempt to do so should route to an access denied page.
Login logic from the login page
```
if (res.data.data.user?.role?.name.toLowerCase() === "vendor") {
navigate("/dashboard")
}
else {
navigate("/buyer-dashboard")
}
```
**App.jsx**
```
<BrowserRouter>
<BuyerRoute />
<VendorRoute />
<PublicRoute />
</BrowserRouter>
```
**PublicRoute.jsx**
```
<Routes>
<Route index element={<Login />} />
<Route path='/signup' element={<SignUp />} />
<Route path='/email-confirmation' element={<Confirmation />} />
<Route path='/forget-password' element={<ForgetPassword />} />
<Route path='/set-password/:email' element={<SetPassword />} />
<Route path='*' element={<>404</>} />
</Routes>
```
**BuyerRoute.jsx**
```
<Routes>
<Route path="/buyer-dashboard" element={<Dashboard />} />
<Route path="/other" element={< Other />} />
</Routes>
```
**VendorRoute.jsx**
```
<Routes>
<Route path="/dashboard" element={<VendorDashboard />} />
<Route path="/items" element={< Items />} />
</Routes>
```
Login successfully route to the expected page, buy i change the route in the address bar i am able to navigate to `dashboard` when i logged in as a `buyer`.
|
How can i prevent certain type of user role to access other role route using React Router Dom V6 |
|javascript|reactjs|react-router|react-router-dom| |
null |
**dependencies:**
```
sqflite: ^2.0.0+3
path_provider: ^2.0.11
permission_handler: ^10.0.0
```
**Export ( back up)**
=====================
To export SQFLite database , I came across some errors , some of the error are
1) FileSystemException: Cannot open file, path
2) error: permission denied, errno = 13
3) etc........
I want to export my **Database** into **Download** folder that is ,
this is my Database path **/data/user/0/com.example.reminder_app/databases/notes.db** , it's a application directory path so my aim is to export **notes.db** file into this path
**/storage/emulated/0/Download/**
1) Expanding **dBToCopy** functions , this function will give path of **Database**
```
Future<File> dBToCopy() async {
final db = await instance.database;
final dbPath = await getDatabasesPath();
var afile = File(dbPath);
return afile;
}
```
2) full code bellow
```
dbExportToDownloadFolder() async {
File result = await NotesDatabase.instance.dBToCopy();
print("lllllllllllllllllll ${result.absolute.path}");
Directory documentsDirectory =
Directory("storage/emulated/0/Download/");
String newPath = join(documentsDirectory.absolute.path + 'abcde.db');
File b =
File("/data/user/0/com.example.reminder_app/databases/notes.db");
if ( await Permission.storage.request().isGranted &&
await Permission.accessMediaLocation.request().isGranted &&
await Permission.manageExternalStorage.request().isGranted )
{
File a = await b.copy(newPath);
} else {
print("No Permission Granted");
}
}
```
**Note**
```
File result = await NotesDatabase.instance.dBToCopy();
print("lllllllllllllllllll ${result.absolute.path}");
```
**OutPut print**
> lllllllllllllllllll /data/user/0/com.example.reminder_app/databases
this **result** file not contain the **notes.db** file , only contain this path
**/data/user/0/com.example.reminder_app/databases**
To get the **DatabaseFile**
```
File b = File("/data/user/0/com.example.reminder_app/databases/notes.db");
or
File b = File("${result.path}"+"/notes.db");
```
so using the file **b** we can copy the file to Download folder file that is **abcde.db**
To do that create a file in **Download** , that is **abcde.db**
```
Directory documentsDirectory = Directory("storage/emulated/0/Download/");
String newPath = join(documentsDirectory.absolute.path + 'abcde.db');
```
and using the **copy** method , to copy one file to another file
```
File a = await b.copy(newPath);
```
**Note**
If you are getting permission denied errors and **OS** errors please add all permission in **manifest** , and using **permission_handler** allow all permissions
```
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_MEDIA_LOCATION"/>
```
after the copying , A new file created in **Download** folder that is **abcde.db**
**Import (restore)**
====================
To import **abcde.db** file from Download to databases folder file that is **notes.db**
```
importDataBaseFile () async {
String recoveryPath =
"/data/user/0/com.example.noteapp/databases/notedb.db";
Directory backupPath = Directory("storage/emulated/0/Download/");
String newPath = join("${backupPath.absolute.path}" + 'abcde.db');
File backupFile = File(newPath);
backupFile.copy(recoveryPath);
NotesDatabase.instance.readAllNotes();
},
```
Expanding function readAllNotes ()
```
Future<List<Note>> readAllNotes() async {
final db = await instance.database;
final orderBy = '${NoteFields.time} ASC';
final result = await db.query(tableNotes, orderBy: orderBy);
return result.map((json) => Note.fromJson(json)).toList();
}
```
so importing operation is performs reversing the export operation .
use a **FilePicker** to pick Database file instead
**Import from file picker ( restore from file picker )**
====================
**dependencies:**
```
sqflite: ^2.0.0+3
path_provider: ^2.0.11
permission_handler: ^10.0.0
file_picker: ^5.0.1
```
full code :
```
importDataBaseFile () async {
bool? clear = await FilePicker.platform.clearTemporaryFiles();
print(clear);
FilePickerResult? result =
await FilePicker.platform.pickFiles();
String recoveryPath =
"/data/user/0/com.example.reminder_app/databases/notes.db";
String newPath = "${result!.files.single.path}";
File backupFile = File(newPath);
backupFile.copy(recoveryPath);
refreshNotes();
}
```
**Note**
this is the demo example so you can add encryptions and choose a different path to store the backup according to you
|
null |
[Realm](https://realm.io/) formally known as MongoDB Realm aka Atlas Device SDK, is an object-oriented database widely used as an alternative to CoreDate, SQLite & ORMs. Realm supports a variety of platforms including Android, iOS, Linux, macOS, and Windows.
Realm can be used as a local-only data store or synchronized to MongoDB’s multi-cloud database platform [Atlas](https://www.mongodb.com/atlas) via a built-in, real-time device-to-cloud sync service – [Realm Sync](https://www.mongodb.com/realm/mobile/sync).
Originally released in 2016, Realm was acquired by MongoDB in 2019. It remains open source under the Apache License.
### Useful Links
* [Get Started with Realm SDKs](https://www.mongodb.com/docs/realm/sdk/)
- [Realm Java SDK](https://www.mongodb.com/docs/realm/sdk/java/)
- [Realm Kotlin SDK](https://www.mongodb.com/docs/realm/sdk/kotlin/)
- [Realm .NET SDK](https://www.mongodb.com/docs/realm/sdk/dotnet/)
- [Realm Node.js SDK](https://www.mongodb.com/docs/realm/sdk/node/)
- [Realm React Native SDK](https://www.mongodb.com/docs/realm/sdk/react-native/)
- [Realm Swift SDK](https://www.mongodb.com/docs/realm/sdk/swift/)
- [Realm Web SDK](https://www.mongodb.com/docs/realm/web/)
- [Realm Flutter SDK(alpha)](https://www.mongodb.com/docs/realm/sdk/flutter/)
* [Get Started with Realm Sync](https://www.mongodb.com/docs/realm/sync/learn/overview/)
* [MongoDB Community Forums - Realm SDKs](https://www.mongodb.com/community/forums/c/realm/realm-sdks/58)
* [Realm GitHub org](https://github.com/realm)
* [Projects built with Realm](https://realm.io/community-projects)
* [Realm articles on Medium](https://medium.com/realm)
* [Realm articles on MongoDB Developer Hub](https://www.mongodb.com/developer/learn/?products=Realm)
* [Monthly Realm Newsletter](https://www.mongodb.com/community/forums/c/realm/realm-news/127)
* [Product Feedback: How can we improve Realm?](https://www.mongodb.com/community/forums/c/realm/realm-news/127) |
Here is a generalization based on the answers by [@moodymudskipper][1] and [@SamR][2]
```
f <- function(
...,
val = 1,
op = c("==", "<", ">", ">=", "<=", "!="),
how = c("|", "&")) {
Reduce(as.symbol(how), lapply(list(...), as.symbol(op), val))
}
```
[1]: https://stackoverflow.com/a/78226974/12158757
[2]: https://stackoverflow.com/a/78210348/12158757 |
I'm trying to convert a date field to a format that represents the number of days since 1999. I want to convert **03-25-2024** to **45376**, like the General cells format in MS Excel. I've tried converting the date to an int, get error message, converting/casting date to vchar and then converting to int.
Here are some samples of the coding I tried:
```
SELECT CONVERT(int,cast('02-02-2024' as date));
```
The output is an error message.
```
CONVERT( int, CONVERT( nchar(8), cd_commission_statement_date, 112))
as comdt_conv
```
**cd_commission_statement_date** has a data type of date in table. Here is the output of this example.
```2024-03-01 = 20240301```
This method works (not sure why),
```
SELECT CONVERT(INT, GETDATE())
```
Output is **45376** |
null |
I'm trying to convert a date column to a format that represents the number of days since 1999. I want to convert **03-25-2024** to **45376**, like the General cells format in MS Excel. I've tried converting the date to an int, get error message, converting/casting date to varchar and then converting to int.
Here are some samples of the coding I tried:
```
SELECT CONVERT(int, CAST('02-02-2024' AS date));
```
The output is an error message.
```
CONVERT(int, CONVERT(nchar(8), cd_commission_statement_date, 112)) AS comdt_conv
```
`cd_commission_statement_date` has a data type of `date` in table.
Here is the output of this example.
2024-03-01 = 20240301
This method works (not sure why):
```
SELECT CONVERT(INT, GETDATE())
```
Output is **45376** |
Convert SQL table date column to numeric value for days since 1999 like Excel |
|sql|sql-server|excel| |
Another possible solution, which uses `regex` to find the matches, and `list comprehension`:
import re
pd.DataFrame(
[[x, y] for x in FrameA.A for y in FrameB.A if re.match(f'.*{x}.*',y)],
columns=list('AB'))
Output:
A B
0 00281378554 AT411513000281378554
1 10862520000 AT424480010862520000
2 82540193700 AT742011182540193700
3 76015394900 AT531200076015394900
4 00134355050 AT511634000134355050
5 21864009 HU02142201082186400900000000
|