问:
How Can I Duplicate a Schema/Database in DBeaver?
I am on a Mac (macOS Monterey 12.6.1) using DBeaver 22.2.4 accessing an AWS Aurora MySQL 5.7 database. During the following process I am using the MySQL 5.7.39 local client (/usr/local/Cellar/mysql@5.7/5.7.39).

I would like to duplicate a schema in the database and am trying the Dump Database / Restore Database functionality in DBeaver.

I can use the Dump to create a file (dump-confluence_qa_713-202212141823.sql) on my Mac. I then need to create a new schema to restore to:

CREATE DATABASE confluence_qa_719_dbeaver CHARACTER SET utf8mb4 COLLATE utf8mb4_bin;
GRANT ALL PRIVILEGES ON confluence_qa_719_dbeaver.* TO 'confluenceuser'@'%' IDENTIFIED BY 'password';
```
<p>And this works fine as well.</p>
<p>When try the Restore Database I get the following warning:</p>
<blockquote>
<p>You are about to restore database confluence_qa_719_dbeaver from
/Users/shepherd/dump-confluence_qa_713-202212141823.sql</p>
<p>It may corrupt your database. Are you sure?</p>
</blockquote>
<p>Perhaps this is because I am restoring to a different target than the original? I click Yes and get a Task execution failed error with the following information</p>
<pre class="lang-none prettyprint-override"><code>--------------

SET @@SESSION.SQL_LOG_BIN= 0

--------------

Task 'MySQL restore' finished at Thu Dec 15 10:11:43 PST 2022
2022-12-15 10:11:43.138 - IO error: Process failed (exit code = 1). See error log.
2022-12-15 10:11:43.139 - java.io.IOException: Process failed (exit code = 1). See error log.
    at org.jkiss.dbeaver.tasks.nativetool.AbstractNativeToolHandler.validateErrorCode(AbstractNativeToolHandler.java:242)
    at org.jkiss.dbeaver.tasks.nativetool.AbstractNativeToolHandler.executeProcess(AbstractNativeToolHandler.java:223)
    at org.jkiss.dbeaver.tasks.nativetool.AbstractNativeToolHandler.doExecute(AbstractNativeToolHandler.java:262)
    at org.jkiss.dbeaver.ext.mysql.tasks.MySQLNativeToolHandler.doExecute(MySQLNativeToolHandler.java:47)
    at org.jkiss.dbeaver.tasks.nativetool.AbstractNativeToolHandler.lambda$0(AbstractNativeToolHandler.java:83)
    at org.jkiss.dbeaver.runtime.RunnableContextDelegate.lambda$0(RunnableContextDelegate.java:39)
    at org.eclipse.jface.operation.ModalContext$ModalContextThread.run(ModalContext.java:122)
</code>```

I'm not sure why the Dump worked but the Restore failed. I'm trying to use root credentials for the database.

My end result is I want a copy of the schema. Perhaps there is a better way of doing it than a Dump / Restore? Or, how can I properly do the Restore function?

Body:
I am on a Mac (macOS Monterey 12.6.1) using DBeaver 22.2.4 accessing an AWS Aurora MySQL 5.7 database. During the following process I am using the MySQL 5.7.39 local client (/usr/local/Cellar/mysql@5.7/5.7.39).

I would like to duplicate a schema in the database and am trying the Dump Database / Restore Database functionality in DBeaver.

I can use the Dump to create a file (dump-confluence_qa_713-202212141823.sql) on my Mac. I then need to create a new schema to restore to:

CREATE DATABASE confluence_qa_719_dbeaver CHARACTER SET utf8mb4 COLLATE utf8mb4_bin;
GRANT ALL PRIVILEGES ON confluence_qa_719_dbeaver.* TO 'confluenceuser'@'%' IDENTIFIED BY 'password';

And this works fine as well.

When try the Restore Database I get the following warning:

You are about to restore database confluence_qa_719_dbeaver from
/Users/shepherd/dump-confluence_qa_713-202212141823.sql

It may corrupt your database. Are you sure?

Perhaps this is because I am restoring to a different target than the original? I click Yes and get a Task execution failed error with the following information

--------------

SET @@SESSION.SQL_LOG_BIN= 0

--------------

Task 'MySQL restore' finished at Thu Dec 15 10:11:43 PST 2022
2022-12-15 10:11:43.138 - IO error: Process failed (exit code = 1). See error log.
2022-12-15 10:11:43.139 - java.io.IOException: Process failed (exit code = 1). See error log.
    at org.jkiss.dbeaver.tasks.nativetool.AbstractNativeToolHandler.validateErrorCode(AbstractNativeToolHandler.java:242)
    at org.jkiss.dbeaver.tasks.nativetool.AbstractNativeToolHandler.executeProcess(AbstractNativeToolHandler.java:223)
    at org.jkiss.dbeaver.tasks.nativetool.AbstractNativeToolHandler.doExecute(AbstractNativeToolHandler.java:262)
    at org.jkiss.dbeaver.ext.mysql.tasks.MySQLNativeToolHandler.doExecute(MySQLNativeToolHandler.java:47)
    at org.jkiss.dbeaver.tasks.nativetool.AbstractNativeToolHandler.lambda$0(AbstractNativeToolHandler.java:83)
    at org.jkiss.dbeaver.runtime.RunnableContextDelegate.lambda$0(RunnableContextDelegate.java:39)
    at org.eclipse.jface.operation.ModalContext$ModalContextThread.run(ModalContext.java:122)

I'm not sure why the Dump worked but the Restore failed. I'm trying to use root credentials for the database.

My end result is I want a copy of the schema. Perhaps there is a better way of doing it than a Dump / Restore? Or, how can I properly do the Restore function?


来源: stackexchange

问:
I need to stamp an existing pdf with HTML in itext 7, how is it possible? What was apparently from version 5 but is incompatible
I need to add a text that is html in an existing pdf, it will be a kind of stamp in the document, I'm using the Paragraph of itext to be able to format it in the question of the position that it will be in the document and everything. The problem is that everything here creates a new pdf with the html content, but I just need the content and add it to my document as a paragraph in the code below has what I tried to do with an example here on the stack, ms the class element is already incompatible because it is from another version of itext, I need something equivalent to be able to use it.

The class I tried to use was Element from the Element class but it's from itext5 and the compilation error because it's not compatible anymore, I've looked for a lot of answers and I still haven't found one that works, this is already an example that I have here on the stack

public class Inputfiles2

    public static final String HTML = "" +
        "" +
        "
testede paragrafo
";

@SneakyThrows
public static void main(String[] args) {

    PdfFont font = PdfFontFactory.createFont(FONT, PdfEncodings.WINANSI,         PdfFontFactory.EmbeddingStrategy.FORCE_EMBEDDED);
    PdfFont fontMontSerrat = PdfFontFactory.createFont(FONT_MONTSERRAT, PdfEncodings.WINANSI, PdfFontFactory.EmbeddingStrategy.FORCE_EMBEDDED);
    PdfFont fontMontSerratBold = PdfFontFactory.createFont(FONT_MONTSERRAT_BOLD, PdfEncodings.WINANSI, PdfFontFactory.EmbeddingStrategy.PREFER_NOT_EMBEDDED);

    Paragraph comb = new Paragraph();
    StringBuilder sb = new StringBuilder();
    sb.append(HTML);
    ElementList list = XMLWorkerHelper.parseToElementList(sb.toString(),null);

    for (Element element : list) {
        comb.add(element);
        }

    PdfReader reader = new PdfReader(src); // input PDF
    PdfWriter writer = new PdfWriter(dest); //
    output pdf
    PdfDocument pdf = new PdfDocument(reader, writer); // criação de base pdf
    Document document = new Document(pdf); // recebe a base pdf para edição

    document.add(comb
    .setFont(fontMontSerratBold)
    .setFontSize(10)
    .setTextAlignment(TextAlignment.LEFT)
    .setFixedPosition(30, 540, 510));

    document.close();
}
```

ContentLicense: CC BY-SA 4.0


问:
Jersey Migration from 1.x to 2.x
We are migrating our project from jersey 1.X version to 2.X .

```<code>public static Filter buildFilter(String s) throws Exception {
JSONJAXBContext context = new JSONJAXBContext(JSONConfiguration.natural().build(),FilterModel.class);
JSONUnmarshaller unmarshaller = context.createJSONUnmarshaller();
FilterModel model = unmarshaller.unmarshalFromJSON(new StringReader(s),
FilterModel.class);
return model.build();
  }
</code>```

So my question is how we can do the changes and compatible the above code to Jersey 2.X ?

Thanks advance.

Title: Jersey Migration from 1.x to 2.x

Body:
We are migrating our project from jersey 1.X version to 2.X .

public static Filter buildFilter(String s) throws Exception {
JSONJAXBContext context = new JSONJAXBContext(JSONConfiguration.natural().build(),FilterModel.class);
JSONUnmarshaller unmarshaller = context.createJSONUnmarshaller();
FilterModel model = unmarshaller.unmarshalFromJSON(new StringReader(s),
FilterModel.class);
return model.build();
  }

So my question is how we can do the changes and compatible the above code to Jersey 2.X ?

Thanks advance.


问:
Unable to generate .aab file in react native. Expo error
i am unable to generate an .aab file for android release. Our Releases are stuck since 2 days. Looked at multiple answers here and there, but nothing worked. Will appreciate any possible solutions.

What i am doing? Running ./gradlew bundleProductionRelease from the android folder in the react native project.

What i am expecting? That this should create a bundle(.aab) file for the app.

Getting below expo related errors.

Below are my react native and expo library versions in the project.

```<code>"expo": "44.0.6",

"expo-application": "4.0.2",

"expo-updates": "0.11.6",

"react-native": "0.66.4",
</code>```

Thanks in advance, and can share other details if necessary for getting to root cause.

Body:
i am unable to generate an .aab file for android release. Our Releases are stuck since 2 days. Looked at multiple answers here and there, but nothing worked. Will appreciate any possible solutions.

What i am doing? Running ./gradlew bundleProductionRelease from the android folder in the react native project.

What i am expecting? That this should create a bundle(.aab) file for the app.

Getting below expo related errors.

Below are my react native and expo library versions in the project.

"expo": "44.0.6",

"expo-application": "4.0.2",

"expo-updates": "0.11.6",

"react-native": "0.66.4",

Thanks in advance, and can share other details if necessary for getting to root cause.


问:
Can Playwright handle Dialpad popup with Chrome
Is it possible to catch the Open Dialpad popup (which Chrome opens for you when you click a phone number and typically ask you if you want to use FaceTime for macOS users) It looks pretty similar to a regular Alert window, but it doesn't work like one.

I tried to catch this window with page.on method with Playwright, but as I mentioned previously it only works with "alert", "confirm" and "prompt" popups

```<code>    page.on('dialog', async dialog => {
        console.log(dialog.message())
        await dialog.dismiss();
      });
</code>```

An example window could be checked on zoom.us page where they have their phone number

Body:
Is it possible to catch the Open Dialpad popup (which Chrome opens for you when you click a phone number and typically ask you if you want to use FaceTime for macOS users) It looks pretty similar to a regular Alert window, but it doesn't work like one.

I tried to catch this window with page.on method with Playwright, but as I mentioned previously it only works with "alert", "confirm" and "prompt" popups

    page.on('dialog', async dialog => {
        console.log(dialog.message())
        await dialog.dismiss();
      });

An example window could be checked on zoom.us page where they have their phone number


问:
Are class variables accessed via self used as loop variables good practice/pythonic?
Is it appropriate to use a class variable accessed with self as a loop variable (aka loop counter, target_list, or iterated item)?  I have not found a standard which describes this situation.  The following python code is valid and produces the expected result ("1, 2, 3") but it feels wrong somehow:

class myClass():
    foo = None
    def myfunc(self):
        for self.foo in [1, 2, 3]:
            print(self.foo)
        return

myClass().myfunc()
```

I have not found a definitive answer that suggests using self.foo would be considered good or bad programming.

More specifically:

Does the MWE pass muster for standards?

Is the MWE behaving like I claim or is something else happening here?

Body:
Is it appropriate to use a class variable accessed with self as a loop variable (aka loop counter, target_list, or iterated item)?  I have not found a standard which describes this situation.  The following python code is valid and produces the expected result ("1, 2, 3") but it feels wrong somehow:

class myClass():
    foo = None
    def myfunc(self):
        for self.foo in [1, 2, 3]:
            print(self.foo)
        return

myClass().myfunc()

I have not found a definitive answer that suggests using self.foo would be considered good or bad programming.

More specifically:

Does the MWE pass muster for standards?

Is the MWE behaving like I claim or is something else happening here?


问:
JsPDF not printing my html WEBPAGE IN A4 size it give blank page on button click
Getting blank page of A4 while using JSPDF Lib
Here is the code i have attached, i have me using to convert the html page into a4 pdf file using jspdf file
but i get blank white page don't know why I need to help is my css is causing the issue or i have using wrong dimensions for the A4 i have attached my html webpage pic alsoenter image description here</p>
```<code>var element = document.getElementById("clickbind");
element.addEventListener("click", onClick);

function onClick() {
  var pdf = new jsPDF('p', 'mm', 'a4');
  pdf.canvas.height = 297;
  pdf.canvas.width = 210;

  pdf.fromHTML(document.body);

  pdf.save('test.pdf');
};

</code>```

Body:
Getting blank page of A4 while using JSPDF Lib
Here is the code i have attached, i have me using to convert the html page into a4 pdf file using jspdf file
but i get blank white page don't know why I need to help is my css is causing the issue or i have using wrong dimensions for the A4 i have attached my html webpage pic alsoenter image description here

var element = document.getElementById("clickbind");
element.addEventListener("click", onClick);

function onClick() {
  var pdf = new jsPDF('p', 'mm', 'a4');
  pdf.canvas.height = 297;
  pdf.canvas.width = 210;

  pdf.fromHTML(document.body);

  pdf.save('test.pdf');
};


问:
Unable to install the Rahlir/theme-gruvbox to JupyterLab due to conflicting dependencies
I am currently facing a problem installing a jupyterlab theme that is called rahlir/theme gruvbox.
Since I have installed the jupyterlab extensions and numerous other custom themes I thought that this shouldn't be a
problem.
Although, after many tries, I haven't managed to install it.
The message im getting is this:

Dependency confliction

I have tried using the instructions straight from the github repo but didn't seem to work.

First I tried to install via pip in the command prompt like that:
jupyterlab extension install @ahlir/theme-gruvbox

Unfortunately this didn't work!

After that I tried installng via the extension manager from jupyterlab itself but unfortunately I got the same message!

Note that I have already installed the latest version of jupyterLab and also I have recently update all the packages in my
Anaconda distribution and anaconda itself!

Any help will be greatly appreciated!

Thanks in advance!


问:
Syntax error when trying to create a graph
Can anybody help with the following syntax:

```<code>with(predict(spl_bin,
             dosex_bin,
             xref_bin,
             expo = TRUE),{
               plot(get("rcs(dose,knots_bin)dose"),
                    pred,
                    type="l",
                    ylim=c(0.4,10),
                    ylab="cardiovascular disease relative risk",
                    xlab="alcohol consumption (g/d)",
                    log ="y",
                    bty="l",
                    las=1)
               matlines(get("rcs(dose,knots_bin)dose"),
                        cbind(ci.ub, ci.lb),
                        col = 1,
                        lty = "dashed")
               })
</code>```

I have tried to fix the above-mentioned syntax with no success.
The following message always came up:

> unexpected symbol in
"with(predict(spl_bin,dosex_bin,xref_bin,expo = TRUE),{plot(get("rcs(dose,knots_bin)dose"), pred,type="l", ylim=c(0.4,10), ylab="cardiovascular disease relative risk", xlab="alcohol consumption"
```

Any help will be appreciated. I am new with R and have so much to learn.

Body:
Can anybody help with the following syntax:

with(predict(spl_bin,
             dosex_bin,
             xref_bin,
             expo = TRUE),{
               plot(get("rcs(dose,knots_bin)dose"),
                    pred,
                    type="l",
                    ylim=c(0.4,10),
                    ylab="cardiovascular disease relative risk",
                    xlab="alcohol consumption (g/d)",
                    log ="y",
                    bty="l",
                    las=1)
               matlines(get("rcs(dose,knots_bin)dose"),
                        cbind(ci.ub, ci.lb),
                        col = 1,
                        lty = "dashed")
               })

I have tried to fix the above-mentioned syntax with no success.
The following message always came up:

> unexpected symbol in
"with(predict(spl_bin,dosex_bin,xref_bin,expo = TRUE),{plot(get("rcs(dose,knots_bin)dose"), pred,type="l", ylim=c(0.4,10), ylab="cardiovascular disease relative risk", xlab="alcohol consumption"

Any help will be appreciated. I am new with R and have so much to learn.


问:
How can I acess to WhatsApp API with R?
I need to download my received WhatsApp messages, including pictures, videos and audio.

I have been trying to download using {RSelenium} in WhatsApp Web, but this is difficult because the source code only shows what is in the screen.

A few days ago I found the WhatsApp API for Business, but I couldn't find a tutorial teaching how to connect and use it with R.

I have been trying this:

# Initializing API Call
call <- "https://graph.facebook.com/v15.0/IDNUMBER"
token <- "AIDHiasudhuiasdhuiasdhasjkdhasuiddghw"

content <- httr::GET(call, httr::add_headers("token-auth" = token))

content

#Response [https://graph.facebook.com/v15.0/IDNUMBER]
#  Date: 2022-12-15 19:44
#  Status: 400
#  Content-Type: application/json
#  Size: 151 B

str(httr::content(content))

#$error
#$error$message
#[1] "An access token is required to request this resource."
#
#$error$type
#[1] "OAuthException"
#
#$error$code
#[1] 104
#
#$error$fbtrace_id
#[1] "sdfsdfsdfsdf"
```

Why I have the error An access token is required to request this resource ?

How can I check for my received messages?

Title: How can I acess to WhatsApp API with R?

Body:
I need to download my received WhatsApp messages, including pictures, videos and audio.

I have been trying to download using {RSelenium} in WhatsApp Web, but this is difficult because the source code only shows what is in the screen.

A few days ago I found the WhatsApp API for Business, but I couldn't find a tutorial teaching how to connect and use it with R.

I have been trying this:

# Initializing API Call
call <- "https://graph.facebook.com/v15.0/IDNUMBER"
token <- "AIDHiasudhuiasdhuiasdhasjkdhasuiddghw"

content <- httr::GET(call, httr::add_headers("token-auth" = token))

content

#Response [https://graph.facebook.com/v15.0/IDNUMBER]
#  Date: 2022-12-15 19:44
#  Status: 400
#  Content-Type: application/json
#  Size: 151 B

str(httr::content(content))

#$error
#$error$message
#[1] "An access token is required to request this resource."
#
#$error$type
#[1] "OAuthException"
#
#$error$code
#[1] 104
#
#$error$fbtrace_id
#[1] "sdfsdfsdfsdf"

Why I have the error An access token is required to request this resource ?

How can I check for my received messages?


问:
serial.serialutil.SerialTimeoutException: Write timeout
Sketch uses 260925 bytes (24%) of program storage space. Maximum is 1044464 bytes.
Global variables use 27984 bytes (34%) of dynamic memory, leaving 53936 bytes for local variables. Maximum is 81920 bytes.

```<code>esptool.py v3.0
Serial port COM3
Connecting...
Traceback (most recent call last):
  File "C:/Users/Vicky/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/3.0.2/tools/pyserial\serial\serialwin32.py", line 325, in write
    raise SerialTimeoutException('Write timeout')
serial.serialutil.SerialTimeoutException: Write timeout
Failed uploading: uploading error: exit status 1
</code>```

I want to upload Blink Code in "ESP - 12E" model but getting this error.

Body:
Sketch uses 260925 bytes (24%) of program storage space. Maximum is 1044464 bytes.
Global variables use 27984 bytes (34%) of dynamic memory, leaving 53936 bytes for local variables. Maximum is 81920 bytes.

esptool.py v3.0
Serial port COM3
Connecting...
Traceback (most recent call last):
  File "C:/Users/Vicky/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/3.0.2/tools/pyserial\serial\serialwin32.py", line 325, in write
    raise SerialTimeoutException('Write timeout')
serial.serialutil.SerialTimeoutException: Write timeout
Failed uploading: uploading error: exit status 1

I want to upload Blink Code in "ESP - 12E" model but getting this error.


问:
Python listen for mouse button click
I want to listen for mouse button click. How can I do that with pywin32?
My solution is bad cause CPU 45%...
As I understand, I need something like GetMessage, but I dont know how to do it correctly.

My current solution:

```<code>while True:
        if win32api.GetAsyncKeyState(win32con.VK_XBUTTON1) != 0 :
            ...
</code>```

Title: Python listen for mouse button click

Body:
I want to listen for mouse button click. How can I do that with pywin32?
My solution is bad cause CPU 45%...
As I understand, I need something like GetMessage, but I dont know how to do it correctly.

My current solution:

while True:
        if win32api.GetAsyncKeyState(win32con.VK_XBUTTON1) != 0 :
            ...


问:
getting pk of item in test unit
There is a test unit that gets request and pk of an item in Form and the problem is that I can't figure how to create a new item in the database and get the pk from it in the test unit function:

```<code>class test_editTransfer_admin(TestCase):

    def test_editTransfer_page_open(self):
        url = reverse(views.editTransfer)
        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'admin_u/editTransfer.html')

    def test_editTransfer_view_deployed_to_page(self):
        factory = RequestFactory()
        request = factory.get('admin_u/editTransfer')
        response = views.editTransfer(request, #pk here )
        self.assertEqual(response.status_code, 200)

</code>```

I tried to define a setUp function that creates the product but without success..

Title: getting pk of item in test unit

Body:
There is a test unit that gets request and pk of an item in Form and the problem is that I can't figure how to create a new item in the database and get the pk from it in the test unit function:

class test_editTransfer_admin(TestCase):

    def test_editTransfer_page_open(self):
        url = reverse(views.editTransfer)
        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'admin_u/editTransfer.html')

    def test_editTransfer_view_deployed_to_page(self):
        factory = RequestFactory()
        request = factory.get('admin_u/editTransfer')
        response = views.editTransfer(request, #pk here )
        self.assertEqual(response.status_code, 200)

I tried to define a setUp function that creates the product but without success..


问:
How to use lambda to list tags for resources (accounts)
I am working on a project to list all accounts in the organization. I created a lambda function with Read permissions for Organization and I am able to get Accounts using boto3 SDK (list_all_accounts). The problem is that the JSON I get does not provide info about the tag that is assigned for this resource. Is it possible to use Lambda to read the account tag?

I went over boto3 documentation and I was not able to find a method that would allow me to do it https://boto3.amazonaws.com/v1/documentation/api/1.9.42/reference/services/organizations.html

I am able to get tags of accounts using CLI
https://docs.aws.amazon.com/organizations/latest/APIReference/API_ListTagsForResource.html


问:
Writing barcode data to Edittext with Bluetooth Barcode device
I want to take the data to edittext with a Bluetooth barcode scanner and save it to the list. I read the data from the edittext with the textwatcher.I want to automatically save it to the list and read the other barcode without pressing any button. However, when I receive the data from the textwatcher, the data is read as a single letter. There are many different barcode types and the exact number of characters is not clear, so I got stuck here. When I enter it with barcode, I want to automatically list it and update the recyclerview. Is there a way to capture the data from the edittext according to the barcode?

My code is as follows;

```<code> binding.barcodeTxtDevice.addTextChangedListener(object : TextWatcher {
            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            if(p0==null)return
            barcodList.add(p0.toString())
            barcodeAdapter.notifyDataSetChanged()
           }
        }
</code>```

Body:
I want to take the data to edittext with a Bluetooth barcode scanner and save it to the list. I read the data from the edittext with the textwatcher.I want to automatically save it to the list and read the other barcode without pressing any button. However, when I receive the data from the textwatcher, the data is read as a single letter. There are many different barcode types and the exact number of characters is not clear, so I got stuck here. When I enter it with barcode, I want to automatically list it and update the recyclerview. Is there a way to capture the data from the edittext according to the barcode?

My code is as follows;

 binding.barcodeTxtDevice.addTextChangedListener(object : TextWatcher {
            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            if(p0==null)return
            barcodList.add(p0.toString())
            barcodeAdapter.notifyDataSetChanged()
           }
        }


问:
Unable to Capture File Path
With the code below, I split the files after "/" and upload them to a list. But in this shredding process, I also need to write the actual path of the file in the filepath field. What should I do?

For example;

```<code>/dowload/b/a
Loop-1;SubItem = new Treeview()
{
    name = download
    Level = 2,
    **filepath = /download/b/a,
    SubItems = new List<Treeview>()
};

Loop-2;subItem = new Treeview()
{
    name = b,
    Level = 2,
    **filepath = /download/b/a,
    **SubItems = new List<Treeview>()
};
</code>```

Must be;

```<code>Loop-1;subItem = new Treeview()
{
    name = download Level = 2,
    **filepath = /download,
    **SubItems = new List<Treeview>()
};

Loop-2;subItem = new Treeview()
{
    name = b,
    Level = 2,
    **filepath = /download/b,
    **SubItems = new List<Treeview>()
};
</code>```
```<code>private void FilePath(System.Windows.Controls.TreeView treeView, IEnumerable<string> paths, char pathSeparator)
{
    List<Treeview> sourceCollection = new List<Treeview>();
    foreach (string path in paths)
    {
        string[] fileItems = path.Split(pathSeparator);
        if (fileItems.Any())
        {
            Treeview root = sourceCollection.FirstOrDefault(x => x.Name.Equals(fileItems[0]) && x.Level.Equals(1));
            if (root == null)
            {
                root = new Treeview()
                {
                    Level = 1,
                    Name = fileItems[0],
                    filepath = path,
                    SubItems = new List<Treeview>()
                };
                sourceCollection.Add(root);
            } // if

            if (fileItems.Length > 1)
            {
                Treeview parentItem = root;
                int level = 2;
                for (int i = 1; i < fileItems.Length; ++i)
                {
                    Treeview subItem = parentItem.SubItems.FirstOrDefault(x => x.Name.Equals(fileItems[i]) && x.Level.Equals(level));
                    if (subItem == null)
                    {
                        subItem = new Treeview()
                        {
                            Name = fileItems[i],
                            Level = level,
                            filepath = path,
                            SubItems = new List<Treeview>
                        };
                              parentItem.SubItems.Add(subItem);
                    } // if

                    parentItem = subItem;
                    level++;
                } // for
            } // if
        } // if
    } // foreach
    TreeView.ItemsSource = sourceCollection;
} // void
</code>```

Title: Unable to Capture File Path

Body:
With the code below, I split the files after "/" and upload them to a list. But in this shredding process, I also need to write the actual path of the file in the filepath field. What should I do?

For example;

/dowload/b/a
Loop-1;SubItem = new Treeview()
{
    name = download
    Level = 2,
    **filepath = /download/b/a,
    SubItems = new List<Treeview>()
};

Loop-2;subItem = new Treeview()
{
    name = b,
    Level = 2,
    **filepath = /download/b/a,
    **SubItems = new List<Treeview>()
};

Must be;

Loop-1;subItem = new Treeview()
{
    name = download Level = 2,
    **filepath = /download,
    **SubItems = new List<Treeview>()
};

Loop-2;subItem = new Treeview()
{
    name = b,
    Level = 2,
    **filepath = /download/b,
    **SubItems = new List<Treeview>()
};

private void FilePath(System.Windows.Controls.TreeView treeView, IEnumerable<string> paths, char pathSeparator)
{
    List<Treeview> sourceCollection = new List<Treeview>();
    foreach (string path in paths)
    {
        string[] fileItems = path.Split(pathSeparator);
        if (fileItems.Any())
        {
            Treeview root = sourceCollection.FirstOrDefault(x => x.Name.Equals(fileItems[0]) && x.Level.Equals(1));
            if (root == null)
            {
                root = new Treeview()
                {
                    Level = 1,
                    Name = fileItems[0],
                    filepath = path,
                    SubItems = new List<Treeview>()
                };
                sourceCollection.Add(root);
            } // if

            if (fileItems.Length > 1)
            {
                Treeview parentItem = root;
                int level = 2;
                for (int i = 1; i < fileItems.Length; ++i)
                {
                    Treeview subItem = parentItem.SubItems.FirstOrDefault(x => x.Name.Equals(fileItems[i]) && x.Level.Equals(level));
                    if (subItem == null)
                    {
                        subItem = new Treeview()
                        {
                            Name = fileItems[i],
                            Level = level,
                            filepath = path,
                            SubItems = new List<Treeview>
                        };
                              parentItem.SubItems.Add(subItem);
                    } // if

                    parentItem = subItem;
                    level++;
                } // for
            } // if
        } // if
    } // foreach
    TreeView.ItemsSource = sourceCollection;
} // void


问:
Button Functionality not working after selecting loading a different fragment and then moving back
I'm having a strange issue in a project I'm currently working on. I'm currently creating an enigma machine app on Android Studio, the project is not complete as most of my time has been trying to get the UI stuff to work.

When I press the letter q on the lower keyboard I want the upper keyboard's q to light up as well. This works properly when I launch the app for the first time, but when I move to a new fragment using the navigation bar, then move back to the Enigma Machine fragment, when I press the letter q, the upper keyboard does not light up.

I tried using Log to track if the onKeyboardClick method was still being ran, and the if statement inside. Both are functioning correctly, the only thing that does now work, is the letters colorFill does not change (after coming from a different fragment).

lampboardAL is an arraylist that contains all the letters in the upper image

```<code>@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    int buttonID;
    View rootView = inflater.inflate(R.layout.fragment_enigma, container, false);
    RelativeLayout keyButton = rootView.findViewById(R.id.parent);

    for (int i = 0; i < keyButton.getChildCount(); i++) {
        //Log.i("OnKeyboardClick", String.valueOf(keyButton.getChildAt(i)));
        if(keyButton.getChildAt(i) instanceof AppCompatImageView && i <= 3) {
            ImageView rotorImage = (ImageView) keyButton.getChildAt(i);
            RotorAL.add(rotorImage);
        }
        if(keyButton.getChildAt(i) instanceof AppCompatImageView && i > 3){
            ImageView lampboard = (ImageView) keyButton.getChildAt(i);
            lampboardAL.add(lampboard);
        }else if(keyButton.getChildAt(i) instanceof AppCompatImageButton){
            ImageButton keyboard = (ImageButton) keyButton.getChildAt(i);
            keyboard.setOnClickListener(this::onKeyboardClick);
        }
    }
    blink = AnimationUtils.loadAnimation(getActivity().getApplicationContext(),R.anim.blink);
    LampOnColor = ContextCompat.getColor(this.requireActivity(), R.color.electric_yellow);

    if(savedInstanceState == null){
        rotor1 = new Rotor(1,1);
        rotor2 = new Rotor(2,1);
        rotor3 = new Rotor(3,1);
        reflect = new Rotor(4,1);
    }else{
        String rotorState = savedInstanceState.getString(ROTOR_STATE);
        rotor1 = new Rotor(Character.getNumericValue(rotorState.charAt(0)),Character.getNumericValue(rotorState.charAt(1)));
        rotor2 = new Rotor(Character.getNumericValue(rotorState.charAt(2)),Character.getNumericValue(rotorState.charAt(3)));
        rotor3 = new Rotor(Character.getNumericValue(rotorState.charAt(4)),Character.getNumericValue(rotorState.charAt(5)));
        reflect = new Rotor(Character.getNumericValue(rotorState.charAt(6)),Character.getNumericValue(rotorState.charAt(7)));
    }

    return rootView;
</code>```
```<code>private void onKeyboardClick(@NonNull View view){
    Log.i("OnKeyboardClick", String .valueOf(view.getId()));
    if(view.getId() == R.id.key_q){
        Log.i("AfterKeyboardClick", String.valueOf(lampboardAL.get(0)));
        lampboardAL.get(0).setColorFilter(LampOnColor);
    }

}
</code>```

I'm not sure where to start when it comes to fixing this issue because both the onKeybardClick function triggers and the if statment, the only issue is that the setColorFilter does not work after you've loaded a different fragment then returned to the enigma machine fragment.

Body:
I'm having a strange issue in a project I'm currently working on. I'm currently creating an enigma machine app on Android Studio, the project is not complete as most of my time has been trying to get the UI stuff to work.

When I press the letter q on the lower keyboard I want the upper keyboard's q to light up as well. This works properly when I launch the app for the first time, but when I move to a new fragment using the navigation bar, then move back to the Enigma Machine fragment, when I press the letter q, the upper keyboard does not light up.

I tried using Log to track if the onKeyboardClick method was still being ran, and the if statement inside. Both are functioning correctly, the only thing that does now work, is the letters colorFill does not change (after coming from a different fragment).

lampboardAL is an arraylist that contains all the letters in the upper image

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    int buttonID;
    View rootView = inflater.inflate(R.layout.fragment_enigma, container, false);
    RelativeLayout keyButton = rootView.findViewById(R.id.parent);

    for (int i = 0; i < keyButton.getChildCount(); i++) {
        //Log.i("OnKeyboardClick", String.valueOf(keyButton.getChildAt(i)));
        if(keyButton.getChildAt(i) instanceof AppCompatImageView && i <= 3) {
            ImageView rotorImage = (ImageView) keyButton.getChildAt(i);
            RotorAL.add(rotorImage);
        }
        if(keyButton.getChildAt(i) instanceof AppCompatImageView && i > 3){
            ImageView lampboard = (ImageView) keyButton.getChildAt(i);
            lampboardAL.add(lampboard);
        }else if(keyButton.getChildAt(i) instanceof AppCompatImageButton){
            ImageButton keyboard = (ImageButton) keyButton.getChildAt(i);
            keyboard.setOnClickListener(this::onKeyboardClick);
        }
    }
    blink = AnimationUtils.loadAnimation(getActivity().getApplicationContext(),R.anim.blink);
    LampOnColor = ContextCompat.getColor(this.requireActivity(), R.color.electric_yellow);

    if(savedInstanceState == null){
        rotor1 = new Rotor(1,1);
        rotor2 = new Rotor(2,1);
        rotor3 = new Rotor(3,1);
        reflect = new Rotor(4,1);
    }else{
        String rotorState = savedInstanceState.getString(ROTOR_STATE);
        rotor1 = new Rotor(Character.getNumericValue(rotorState.charAt(0)),Character.getNumericValue(rotorState.charAt(1)));
        rotor2 = new Rotor(Character.getNumericValue(rotorState.charAt(2)),Character.getNumericValue(rotorState.charAt(3)));
        rotor3 = new Rotor(Character.getNumericValue(rotorState.charAt(4)),Character.getNumericValue(rotorState.charAt(5)));
        reflect = new Rotor(Character.getNumericValue(rotorState.charAt(6)),Character.getNumericValue(rotorState.charAt(7)));
    }

    return rootView;

private void onKeyboardClick(@NonNull View view){
    Log.i("OnKeyboardClick", String .valueOf(view.getId()));
    if(view.getId() == R.id.key_q){
        Log.i("AfterKeyboardClick", String.valueOf(lampboardAL.get(0)));
        lampboardAL.get(0).setColorFilter(LampOnColor);
    }

}

I'm not sure where to start when it comes to fixing this issue because both the onKeybardClick function triggers and the if statment, the only issue is that the setColorFilter does not work after you've loaded a different fragment then returned to the enigma machine fragment.


问:
How to change CacheStorage key for dll caching?
I am currently working on developing a Blazor WASM application that is a framework for a form builder which executes on a web forms application. The issue I've been experiencing is that the caching of the dll's on chrome all appear to have specific keys that target the current url. These cached dlls share the same hash however we use the URLS for encoding data, they are slightly different depending on which user you select. When you select the same user the cached dll's load just fine.

All examples regarding the Cache Storage of Blazor WASM dll's share the same 'blazor-resources~/~' key however ours are being structured however ours are being structured like this.

so every new page the users enters will not used the already cached framework and instead create a new cache and key for it.


问:
Minimizing the browser window in selenium testing
How can I minimize the browser window in selenium? I have looked for possible solutions on the web and couldn't find anything related to this.</p>


问:
Notify errors of my applications in android market
I have check my Android developer console and notice that my application has 1 error report. Is there any way to config some alert, as an email, to inform you about this error, also new purchases, etc? If not I wont know that the application has failed until I check my android market account, isnt it?</p>

ContentLicense: CC BY-SA 3.0


问:
$response->redirect not works
I have an IVR that plays some audios for the user and then I need to redirect to another php file. The strange thing is that this redirect does not work.

NOTE 1: the redirect that does not work is the last one ($response->redirect("./chooseLicense.php?rs=$rs"))

NOTE 2: if I put it in if(!is_object($rs)) it works perfectly.

Can anyone tell me why this happens?

Snippet of my code:

```<code>$rs = json_decode(Curl::post(baseUrl . "users/auth/", $cpfOrCnpj, $password));

// logText('rs in login', $rs);

if(!is_object($rs)) {
    $gather->play("https://digital-lock-api.azurewebsites.net/ura-hmg/assets/audios/licenseNotFound.mp3");
}

if($rs->licenses === []) {
    $gather->play("https://digital-lock-api.azurewebsites.net/ura-hmg/assets/audios/licenseNotFound.mp3");
}

if(count($rs->licenses) == 1) {
    $licenseId = $rs->licenses[0]->id;
    $isBlocked = $rs->licenses[0]->blocked;
    $token = $rs->auth->token;
    $response->redirect("./waitForFlip.php?licenseId=$licenseId&isBlocked=$isBlocked&token=$token");
}

if(count($rs->licenses) > 1) {
    $count = 0;
    foreach($rs->licenses as $license) {
        $count++;
        $gather->play("https://digital-lock-api.azurewebsites.net/ura-hmg/assets/audios/chooseLicense$count.mp3");
        $gather->play($license->nicknameAudioUrl);
    }

    $rs = json_encode($rs);

    logText("rs encode", $rs);

    $response->redirect("./chooseLicense.php?rs=$rs");
}
</code>```

Title: $response->redirect not works

Body:
I have an IVR that plays some audios for the user and then I need to redirect to another php file. The strange thing is that this redirect does not work.

NOTE 1: the redirect that does not work is the last one ($response->redirect("./chooseLicense.php?rs=$rs"))

NOTE 2: if I put it in if(!is_object($rs)) it works perfectly.

Can anyone tell me why this happens?

Snippet of my code:

$rs = json_decode(Curl::post(baseUrl . "users/auth/", $cpfOrCnpj, $password));

// logText('rs in login', $rs);

if(!is_object($rs)) {
    $gather->play("https://digital-lock-api.azurewebsites.net/ura-hmg/assets/audios/licenseNotFound.mp3");
}

if($rs->licenses === []) {
    $gather->play("https://digital-lock-api.azurewebsites.net/ura-hmg/assets/audios/licenseNotFound.mp3");
}

if(count($rs->licenses) == 1) {
    $licenseId = $rs->licenses[0]->id;
    $isBlocked = $rs->licenses[0]->blocked;
    $token = $rs->auth->token;
    $response->redirect("./waitForFlip.php?licenseId=$licenseId&isBlocked=$isBlocked&token=$token");
}

if(count($rs->licenses) > 1) {
    $count = 0;
    foreach($rs->licenses as $license) {
        $count++;
        $gather->play("https://digital-lock-api.azurewebsites.net/ura-hmg/assets/audios/chooseLicense$count.mp3");
        $gather->play($license->nicknameAudioUrl);
    }

    $rs = json_encode($rs);

    logText("rs encode", $rs);

    $response->redirect("./chooseLicense.php?rs=$rs");
}


问:
react-refresh: OriginalFactory is undefined | Cannot read properties of undefined (reading 'call')
While trying to use moduleFederationPlugin from webpack, we are getting below error:

` Cannot read properties of undefined (reading 'call')

originalFactory.call(this, moduleObject, moduleExports, webpackRequire);`

Its seems to be an issue with react-refresh plugin, the above line is breaking and originalFactory is undefined.

I wanted to create a Micro - FrontEnd architecture.

I was expecting the code to run without any issues.


问:
React.js + CSS: Splash Screen Animation to FadeOut
```<code>    "leaflet": "^1.9.2",
    "react": "^18.2.0",
</code>```

I've built a web app using React frontend and Leaflet. The amount of data (over 3,000 objects) means the app has a 3-6 second lag when loading the page. To combat this my idea was to build a "splash screen".

.css

```<code>    animation: fadeOut 1s linear forwards;
    animation-delay: 5s;
    width: 101%;
    height: 101vh;
    background-color: #428bca;
    color: whitesmoke;
    z-index: 99999999;
    display: flex;
    justify-content: center;
    align-items: center;
    text-align: center;
}

@keyframes fadeOut {
    0% {
        opacity: 1;
        visibility:visible;
    }
    100% {
        opacity: 0;
        visibility:hidden;
    }
}
</code>```

App.js

```<code>import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import Splash from "./components/Splash";
import Footer from "./components/Footer";
import Navbar from "./components/Nav";
import MapPage from "./pages/MapPage";
import Admin from "./pages/Admin";
import "./index.css";
import "./App.css";
import "./styles/splash.css";
import logoimg from "./img/logo.png";

function App() {

  // function will move to a component once it's complete and working.
  function splash() {
    return (
      <main id="splash-bck">
        <article id="splash-container">
          <img
            src={logoimg}
            style={{
              width: "35%",
            }}
          />
          <p id="splash-tagline">
            <em>Input your location to find warm spaces near you</em>
          </p>
          <div id="splash-search">
            <input
              type="text"
              placeholder="ex: Sheffield"
              style={{
                border: "3px solid #428bca",
                borderWidth: "2px",
                borderStyle: "solid",
                borderColor: "#428bca",
                borderRadius: "1.5rem",
                color: "grey",
                padding: ".5rem",
                fontSize: "1.3rem",
                textAlign: "center",
              }}
            />
          </div>
        </article>
      </main>
    );
  }

  return (
    <>
      <Router>
        {splash()}
        {/* <Splash /> */}
        <div className="overlay">
          <Navbar />
        </div>
        <Routes>
          <Route index element={<MapPage />} />
          <Route path="/admin" element={<Admin />} />
        </Routes>
        <Footer />
      </Router>
    </>
  );
}

export default App;

</code>```

I've tried different transition types and 'display: none; / visibility: hidden' where both give the same results. The idea is to show a component for 6s before it transitions (fade-out) to show the map underneath. What i currently get is the transition fades out to a white/blank page.

Body:
    "leaflet": "^1.9.2",
    "react": "^18.2.0",

I've built a web app using React frontend and Leaflet. The amount of data (over 3,000 objects) means the app has a 3-6 second lag when loading the page. To combat this my idea was to build a "splash screen".

.css

    animation: fadeOut 1s linear forwards;
    animation-delay: 5s;
    width: 101%;
    height: 101vh;
    background-color: #428bca;
    color: whitesmoke;
    z-index: 99999999;
    display: flex;
    justify-content: center;
    align-items: center;
    text-align: center;
}

@keyframes fadeOut {
    0% {
        opacity: 1;
        visibility:visible;
    }
    100% {
        opacity: 0;
        visibility:hidden;
    }
}

App.js

import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import Splash from "./components/Splash";
import Footer from "./components/Footer";
import Navbar from "./components/Nav";
import MapPage from "./pages/MapPage";
import Admin from "./pages/Admin";
import "./index.css";
import "./App.css";
import "./styles/splash.css";
import logoimg from "./img/logo.png";

function App() {

  // function will move to a component once it's complete and working.
  function splash() {
    return (

            Input your location to find warm spaces near you

            <input
              type="text"
              placeholder="ex: Sheffield"
              style={{
                border: "3px solid #428bca",
                borderWidth: "2px",
                borderStyle: "solid",
                borderColor: "#428bca",
                borderRadius: "1.5rem",
                color: "grey",
                padding: ".5rem",
                fontSize: "1.3rem",
                textAlign: "center",
              }}
            />

    );
  }

  return (
    <>
      <Router>
        {splash()}
        {/* <Splash /> */}

          <Navbar />

        <Routes>
          <Route index element={<MapPage />} />
          <Route path="/admin" element={<Admin />} />
        </Routes>

      </Router>
    </>
  );
}

export default App;

I've tried different transition types and 'display: none; / visibility: hidden' where both give the same results. The idea is to show a component for 6s before it transitions (fade-out) to show the map underneath. What i currently get is the transition fades out to a white/blank page.


问:
Allow approved and logged in users to download files from Google Cloud Storage bucket
I have a bucket on Google Cloud Storage. It contains multiple .csv files. I would like to create a WordPress site that allows me to give access to logged in users to download files from this bucket.

Is the easiest way to do this to simply create a basic page behind a log-in screen with a list of download URLs from GCS?

This seems like:

It would be unsecure on the GCS side (i.e., I have to allow anyone that has the link to download it, so it could be shared by a logged in user with someone that is not a user on my website)

The website and the GCS bucket are not synced (i.e., if I upload a file to my GCS bucket, I have to go to the WordPress website and add a link to the download URL).

I would like to have it set-up so that

In order to download a file you have to be logged in to my website and you have be approved by GCS to download a file.

I only have to worry about uploading media to my GCS bucket and not updating individual download links on my website as I will have hundreds of files.

If it is possible to assign specific users permission to download only specific sub-folders or individual files in GCS, that would be a bonus.

I have looked at the wp-stateless plugin but this doesn't seem to really accomplish what I want. This just takes the normal WordPress media functionality and stores them in a new bucket on GCS but I already have hundreds of files in a GCS bucket that I would like to serve.


问:
Process miscomunication with mmap
I cant get this program to work.
It should convert capital letters to normal and vice versa, and numberso into three asterisks (***), and rewrite the file that i give as an argument with said changes, mapped into memory.
The parent process must do the letter conversion, and the child process must do the numbers. They must procceed in halves: the first half of the file, and then the second half of it. The first half seems to be doing fine, but the second one is all corrupted.

I tried making buffer a char *buffer, and using the various methos commented in the code, but nothing seems to work properly.
Here is the code and output:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <signal.h>
#include <sys/wait.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

int main(int argc, char **argv)
{
    // Comprobamos que se haya proporcionado un nombre de archivo como argumento
    if (argc < 2) {
    printf("Error: se debe proporcionar el nombre del archivo como argumento.\n");
    exit(EXIT_FAILURE);
    }
    // Abrimos el archivo en modo lectura/escritura
    int file = open(argv[1], O_RDWR);
    if (file < 0) {
        printf("Error: no se puede abrir el archivo %s.\n", argv[1]);
        exit(EXIT_FAILURE);
    }

    // Obtenemos el estado del archivo
    struct stat estado;
    if (fstat(file, &estado) < 0) {
        printf("Error: no se puede obtener el estado del archivo %s.\n", argv[1]);
        exit(EXIT_FAILURE);// Función que se ejecuta cuando se recibe una señal
    }
    // Comprobamos que el archivo sea un archivo regular
    if (!S_ISREG(estado.st_mode)) {
        printf("Error: %s no es un archivo regular.\n", argv[1]);
        exit(EXIT_FAILURE);
    }

    // Mapeamos el archivo en memoria
    char *map = (char*) mmap(NULL, estado.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, file, 0);
    if (map == MAP_FAILED) {
        printf("Error: no se puede mapear el archivo %s en memoria.\n", argv[1]);
        exit(EXIT_FAILURE);
    }

    printf("\n---------------PROCESO DE LECTURA EN CURSO---------------\n");
    char texto ='\0';
    int lr = 0;
    for (int i = 0; i < estado.st_size; i++) {
        // Comenzamos a leer el archivo
        if ((lr = read(file, &texto, 1)) < 0) {
            printf("\nError intentando leer el archivo\n");
            exit(EXIT_FAILURE);
        }
        // Comprobamos que se está leyendo correctamente el contenido del archivo (y cuál es)
        printf("%c", texto);
    }

    // Creamos un proceso hijo
    pid_t pid = fork();
    if (pid < 0) {
        printf("Error: no se puede crear el proceso hijo.\n");
        exit(EXIT_FAILURE);
    }

    if (pid == 0) {
        // Proceso hijo
        // Esperamos a que el padre procese la mitad del archivo
        raise(SIGSTOP); // Paramos el proceso para esperar la señal del padre
        int mitadArchivo = estado.st_size / 2;
        // Obtenemos el tamaño final del archivo (con la sustitución de números por asteriscos)
        int tamanioFinal = estado.st_size;
        for (int i = 0; i < estado.st_size; i++) {
            if (isdigit(map[i])) {
                tamanioFinal += 2;
            }
        }

        // Redimensionamos el archivo para ajustarlo al tamaño final
        if (ftruncate(file, tamanioFinal) < 0) {
            printf("Error: no se puede redimensionar el archivo %s.\n", argv[1]);
            exit(EXIT_FAILURE);
        }
                // Procesamos la segunda mitad del archivo
        char buffer[/*mitadArchivo*/estado.st_size];
        int j = 0, k = 0;
        printf("\n---------IMPRIMIR DESDE EL HIJO---------\n");
        for (int i = 0; i < estado.st_size; i++) {
            if (isdigit(map[i])) {
                // Si el caracter es un número, lo sustituimos por tres asteriscos
                buffer[j++] = '*';
                buffer[j++] = '*';
                buffer[j++] = '*';
            } else {
                // Si el caracter no es un número, lo copiamos tal cual al buffer
                buffer[j++] = map[i];
            }
            printf("%c", buffer[i]);
            if (i == mitadArchivo) { // Hemos llegado a la mitad
                    memcpy(map, buffer, /*2*(estado.st_size + j)*/ mitadArchivo + j); // Escribimos la  primera mitad ya modificada
                    raise(SIGSTOP); // Paramos el proceso para esperar la señal del padre
                    printf("\nSegunda mitad del archivo: \n");
                    if (isdigit(map[i])) {
                        // Si el caracter es un número, lo sustituimos por tres asteriscos
                        buffer[k++] = '*';
                        buffer[k++] = '*';
                        buffer[k++] = '*';
                    } else {
                        // Si el caracter no es un número, lo copiamos tal cual al buffer
                        buffer[k++] = map[i];
                    }
                    memcpy(buffer, map + (mitadArchivo + j), /*2*(estado.st_size + j)*/  tamanioFinal - (mitadArchivo + j)); // Leemos la segunda mitad que queda por transformar
                }
        }
        printf("\n");

        // Copiamos el contenido del buffer al archivo
        //memcpy(map /*+ mitadArchivo*/, buffer, j);

        // Modificamos el tamaño del archivo para que tenga en cuenta los cambios
        //ftruncate(file, 2*(estado.st_size + j) /*- mitadArchivo*/);

        // Finalizamos el proceso hijo
        exit(EXIT_SUCCESS);
    } else {
        // Proceso padre
        // Procesamos la primera mitad del archivo
        char buffer[estado.st_size];
        int mitadArchivo = estado.st_size / 2;
        int j = 0;
        for (int i = 0; i < estado.st_size /*/ 2*/; i++) {
            if (islower(map[i])) {
                // Si el caracter es una letra minúscula, la convertimos en mayúscula
                buffer[j++] = toupper(map[i]);
            } else if (isupper(map[i])) {
                // Si el caracter es una letra mayúscula, la convertimos en minúscula
                buffer[j++] = tolower(map[i]);
            } else {
                // Si el caracter no es una letra, lo copiamos tal cual al buffer
                buffer[j++] = map[i];
            }
            if (i == estado.st_size / 2){
                sleep(1);
                // Copiamos el contenido del buffer al archivo
                memcpy(map, buffer, j);
                // Indicamos al proceso hijo que puede continuar
                kill(pid, SIGCONT);
            }
        }
            // Copiamos el contenido del buffer al archivo
            memcpy(buffer, map, j);
            sleep(1);
            // Indicamos al proceso hijo que puede continuar
            kill(pid, SIGCONT);

            // Esperamos a que el proceso hijo termine
            waitpid(pid, NULL, 0);

            printf("\n---------IMPRIMIR DESDE LA SALIDA DESDE MEMORIA---------\n");
            for (int i = 0; i < estado.st_size; i++)
                    printf("%c", map[i]);
            printf("\n");

            // Finalizamos el proceso padre
            exit(EXIT_SUCCESS);
        }

    return 0;
}
</code>```

Output:

```<code>---------------PROCESO DE LECTURA EN CURSO---------------
esta 5 es 6 la
prueba 89 para 531 ver si
35 el programa 7 funciona

---------IMPRIMIR DESDE EL HIJO---------
ESTA *** ES *** LA
PRUEBA ****** P
Segunda mitad del archivo:
ARA ********* ARA ********* ���c�

---------IMPRIMIR DESDE LA SALIDA DESDE MEMORIA---------
ESTA *** ES *** LA
PRUEBA ****** PARA ********* ���c���of�/����
</code>```

Title: Process miscomunication with mmap

Body:
I cant get this program to work.
It should convert capital letters to normal and vice versa, and numberso into three asterisks (***), and rewrite the file that i give as an argument with said changes, mapped into memory.
The parent process must do the letter conversion, and the child process must do the numbers. They must procceed in halves: the first half of the file, and then the second half of it. The first half seems to be doing fine, but the second one is all corrupted.

I tried making buffer a char *buffer, and using the various methos commented in the code, but nothing seems to work properly.
Here is the code and output:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <signal.h>
#include <sys/wait.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

int main(int argc, char **argv)
{
    // Comprobamos que se haya proporcionado un nombre de archivo como argumento
    if (argc < 2) {
    printf("Error: se debe proporcionar el nombre del archivo como argumento.\n");
    exit(EXIT_FAILURE);
    }
    // Abrimos el archivo en modo lectura/escritura
    int file = open(argv[1], O_RDWR);
    if (file < 0) {
        printf("Error: no se puede abrir el archivo %s.\n", argv[1]);
        exit(EXIT_FAILURE);
    }

    // Obtenemos el estado del archivo
    struct stat estado;
    if (fstat(file, &estado) < 0) {
        printf("Error: no se puede obtener el estado del archivo %s.\n", argv[1]);
        exit(EXIT_FAILURE);// Función que se ejecuta cuando se recibe una señal
    }
    // Comprobamos que el archivo sea un archivo regular
    if (!S_ISREG(estado.st_mode)) {
        printf("Error: %s no es un archivo regular.\n", argv[1]);
        exit(EXIT_FAILURE);
    }

    // Mapeamos el archivo en memoria
    char *map = (char*) mmap(NULL, estado.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, file, 0);
    if (map == MAP_FAILED) {
        printf("Error: no se puede mapear el archivo %s en memoria.\n", argv[1]);
        exit(EXIT_FAILURE);
    }

    printf("\n---------------PROCESO DE LECTURA EN CURSO---------------\n");
    char texto ='\0';
    int lr = 0;
    for (int i = 0; i < estado.st_size; i++) {
        // Comenzamos a leer el archivo
        if ((lr = read(file, &texto, 1)) < 0) {
            printf("\nError intentando leer el archivo\n");
            exit(EXIT_FAILURE);
        }
        // Comprobamos que se está leyendo correctamente el contenido del archivo (y cuál es)
        printf("%c", texto);
    }

    // Creamos un proceso hijo
    pid_t pid = fork();
    if (pid < 0) {
        printf("Error: no se puede crear el proceso hijo.\n");
        exit(EXIT_FAILURE);
    }

    if (pid == 0) {
        // Proceso hijo
        // Esperamos a que el padre procese la mitad del archivo
        raise(SIGSTOP); // Paramos el proceso para esperar la señal del padre
        int mitadArchivo = estado.st_size / 2;
        // Obtenemos el tamaño final del archivo (con la sustitución de números por asteriscos)
        int tamanioFinal = estado.st_size;
        for (int i = 0; i < estado.st_size; i++) {
            if (isdigit(map[i])) {
                tamanioFinal += 2;
            }
        }

        // Redimensionamos el archivo para ajustarlo al tamaño final
        if (ftruncate(file, tamanioFinal) < 0) {
            printf("Error: no se puede redimensionar el archivo %s.\n", argv[1]);
            exit(EXIT_FAILURE);
        }
                // Procesamos la segunda mitad del archivo
        char buffer[/*mitadArchivo*/estado.st_size];
        int j = 0, k = 0;
        printf("\n---------IMPRIMIR DESDE EL HIJO---------\n");
        for (int i = 0; i < estado.st_size; i++) {
            if (isdigit(map[i])) {
                // Si el caracter es un número, lo sustituimos por tres asteriscos
                buffer[j++] = '*';
                buffer[j++] = '*';
                buffer[j++] = '*';
            } else {
                // Si el caracter no es un número, lo copiamos tal cual al buffer
                buffer[j++] = map[i];
            }
            printf("%c", buffer[i]);
            if (i == mitadArchivo) { // Hemos llegado a la mitad
                    memcpy(map, buffer, /*2*(estado.st_size + j)*/ mitadArchivo + j); // Escribimos la  primera mitad ya modificada
                    raise(SIGSTOP); // Paramos el proceso para esperar la señal del padre
                    printf("\nSegunda mitad del archivo: \n");
                    if (isdigit(map[i])) {
                        // Si el caracter es un número, lo sustituimos por tres asteriscos
                        buffer[k++] = '*';
                        buffer[k++] = '*';
                        buffer[k++] = '*';
                    } else {
                        // Si el caracter no es un número, lo copiamos tal cual al buffer
                        buffer[k++] = map[i];
                    }
                    memcpy(buffer, map + (mitadArchivo + j), /*2*(estado.st_size + j)*/  tamanioFinal - (mitadArchivo + j)); // Leemos la segunda mitad que queda por transformar
                }
        }
        printf("\n");

        // Copiamos el contenido del buffer al archivo
        //memcpy(map /*+ mitadArchivo*/, buffer, j);

        // Modificamos el tamaño del archivo para que tenga en cuenta los cambios
        //ftruncate(file, 2*(estado.st_size + j) /*- mitadArchivo*/);

        // Finalizamos el proceso hijo
        exit(EXIT_SUCCESS);
    } else {
        // Proceso padre
        // Procesamos la primera mitad del archivo
        char buffer[estado.st_size];
        int mitadArchivo = estado.st_size / 2;
        int j = 0;
        for (int i = 0; i < estado.st_size /*/ 2*/; i++) {
            if (islower(map[i])) {
                // Si el caracter es una letra minúscula, la convertimos en mayúscula
                buffer[j++] = toupper(map[i]);
            } else if (isupper(map[i])) {
                // Si el caracter es una letra mayúscula, la convertimos en minúscula
                buffer[j++] = tolower(map[i]);
            } else {
                // Si el caracter no es una letra, lo copiamos tal cual al buffer
                buffer[j++] = map[i];
            }
            if (i == estado.st_size / 2){
                sleep(1);
                // Copiamos el contenido del buffer al archivo
                memcpy(map, buffer, j);
                // Indicamos al proceso hijo que puede continuar
                kill(pid, SIGCONT);
            }
        }
            // Copiamos el contenido del buffer al archivo
            memcpy(buffer, map, j);
            sleep(1);
            // Indicamos al proceso hijo que puede continuar
            kill(pid, SIGCONT);

            // Esperamos a que el proceso hijo termine
            waitpid(pid, NULL, 0);

            printf("\n---------IMPRIMIR DESDE LA SALIDA DESDE MEMORIA---------\n");
            for (int i = 0; i < estado.st_size; i++)
                    printf("%c", map[i]);
            printf("\n");

            // Finalizamos el proceso padre
            exit(EXIT_SUCCESS);
        }

    return 0;
}

Output:

---------------PROCESO DE LECTURA EN CURSO---------------
esta 5 es 6 la
prueba 89 para 531 ver si
35 el programa 7 funciona

---------IMPRIMIR DESDE EL HIJO---------
ESTA *** ES *** LA
PRUEBA ****** P
Segunda mitad del archivo:
ARA ********* ARA ********* ���c�

---------IMPRIMIR DESDE LA SALIDA DESDE MEMORIA---------
ESTA *** ES *** LA
PRUEBA ****** PARA ********* ���c���of�/����


问:
How to display a dynamically allocated array in the ARM KEIL 5.36 debugger?
I can easily show static arrays in watch window, but for dynamic arrays KEIL shows only value at the pointer. Is there any way to specify watch window command for that or maybe cast dynamic array pointer to the static array pointer

I've already tried to do it this and this way, but with no positive result


问:
Set work area or screen dimension for electron window on moving
I have an frameless window and i want to set default screen and this window must move only in to the this screen dimension.

For example

Look

This window only move in to "x" positions. I looked and tryed on "move" event but i failed. And this solution should work on cross platform.


问:
Xcode 4.1 building dependent project with different compiler, ignoring GCC_VERSION
I've moved my project from gcc to clang, and Xcode (4.1) builds it using clang, but my project depends on another xcodeproject (three20), and Xcode builds this using gcc. I want it to build everything using clang.

I'm using xcconfig files, and I set GCC_VERSION to com.apple.compilers.llvm.clang.1_0 in the xcconfig that my main project depends on.

There's no GCC_VERSION defined in the xcconfig that three20 depends on, and I can't change that, because it's a shared project that other projects depend on (they may not want to move to clang).

Is there a way to change the default compiler globally in some way?

If there's no way to fix this, and XCode will use gcc to build three20, is it safe to link together files built using different compilers?


问:
Create Build in Jenkins by using command line with ssh
I hope you're doing well,

I'm traying to automate a Jenkins process using a bash script in Linux, in which I need to create a build, then with created build I need to create a build using the option "Build with parameters" and use a specific build to create it.

First I'm creating the build with a similar command (it is corking fine it created the build successfully):

```<code>ssh -l MyUser -p JENK_PORT JENK_SERver build job-build -s –v
</code>```

it creates the build number 10 then I need to use this build to create another one for the job job-deploy, something like:

```<code>ssh -l MyUser -p JENK_PORT JENK_SERver build job-deploy -p COPY_PROMOTION_LEVEL=1 -p BUILD_SELECTOR="\<SpecificBuildSelector plugin=\"copyartifact@1.37\"\>  \<buildNumber\>10 \</buildNumber\>\</SpecificBuildSelector\>" -s -v
</code>```

when I ran it, I'm getting this error:

ERROR: Too many arguments: plugin=copyartifact@1.37>

If I change the "space" for &nbsp/&#032 or adding a back slash between SpecificBuildSelector and plugin=copyartifact@1.37, I got this error:

ERROR: Unexpected exception occurred while performing build command.
com.thoughtworks.xstream.io.StreamException:  : only whitespace
content allowed before start tag and not \ (position: START_DOCUMENT
seen ... @1:1)

Do you know how can I do it??, create the build for an specific build in the command line by passing the build parameters with -p option?

Thanks in advance.

Body:
I hope you're doing well,

I'm traying to automate a Jenkins process using a bash script in Linux, in which I need to create a build, then with created build I need to create a build using the option "Build with parameters" and use a specific build to create it.

First I'm creating the build with a similar command (it is corking fine it created the build successfully):

ssh -l MyUser -p JENK_PORT JENK_SERver build job-build -s –v

it creates the build number 10 then I need to use this build to create another one for the job job-deploy, something like:

ssh -l MyUser -p JENK_PORT JENK_SERver build job-deploy -p COPY_PROMOTION_LEVEL=1 -p BUILD_SELECTOR="\<SpecificBuildSelector plugin=\"copyartifact@1.37\"\>  \<buildNumber\>10 \</buildNumber\>\</SpecificBuildSelector\>" -s -v

when I ran it, I'm getting this error:

ERROR: Too many arguments: plugin=copyartifact@1.37>

If I change the "space" for &nbsp/&#032 or adding a back slash between SpecificBuildSelector and plugin=copyartifact@1.37, I got this error:

ERROR: Unexpected exception occurred while performing build command.
com.thoughtworks.xstream.io.StreamException:  : only whitespace
content allowed before start tag and not \ (position: START_DOCUMENT
seen ... @1:1)

Do you know how can I do it??, create the build for an specific build in the command line by passing the build parameters with -p option?

Thanks in advance.


问:
c# System.Net.Http.HttpRequestException: An error occurred while sending the request
```<code>System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a send. ---> System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. ---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
   at System.Net.Sockets.Socket.EndReceive(IAsyncResult asyncResult)
   at System.Net.Sockets.NetworkStream.EndRead(IAsyncResult asyncResult)
   --- End of inner exception stack trace ---
   at System.Net.TlsStream.EndWrite(IAsyncResult asyncResult)
   at System.Net.ConnectStream.WriteHeadersCallback(IAsyncResult ar)
   --- End of inner exception stack trace ---
   at System.Net.HttpWebRequest.EndGetRequestStream(IAsyncResult asyncResult, TransportContext& context)
   at System.Net.Http.HttpClientHandler.GetRequestStreamCallback(IAsyncResult ar)
   --- End of inner exception stack trace ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at CanadianTireDashboard.Controllers.HomeController.<pickUpApi>d__109.MoveNext() in C:\Users\sbaqai\Documents\TFS\CanadianTireDashboard\CanadianTireDashboard\Controllers\HomeController.cs:line 865
</code>```

I have given up. Idk why this works on our dev server but not on prod. Our dev and prod are on IIS. I am still new to C# and .NET Framework but after Googling around I still can't fix this error.
Nothing works.

Here is my code that is trying to call HttpClient.PostAsync

```<code>private async Task pickUpApi(string billOfLading)
{
    ErrorFile f = new ErrorFile();

    HomeController hc = new HomeController();
    HttpResponseMessage pickUpRequestCall = null;

    //Send a request to url with an xml body
    try
    {

        //var url = "http://www.saiasecure.com/webservice/shipment/xml.aspx?";
        var url = "https://www.tst-cfexpress.com/xml/pickup";

        XmlSerializer xmlSerializer = new XmlSerializer(typeof(pickuprequest));
        XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
        ns.Add("", "");
        pickuprequest cdn = new pickuprequest();

        var values = cdn.getAll(billOfLading);

        try
        {
            var path = $@"C:\CDNTireJobs\Test\{billOfLading}.xml";
            var encoding = Encoding.GetEncoding("ISO-8859-1");
            using (XmlTextWriter tw = new XmlTextWriter(path, encoding))
            {
                xmlSerializer.Serialize(tw, values, ns);
                tw.Close();
            }
        }
        catch (FileNotFoundException e)
        {
            f.errorFile($"File Exception {e.Message}");
        }

        var xmlcontent = System.IO.File.ReadAllText($@"C:\CDNTireJobs\Test\{billOfLading}.xml");
        var content = new StringContent(xmlcontent,
                        Encoding.GetEncoding("ISO-8859-1"), "application/xml");

        ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12;
        ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;

        pickUpRequestCall = await httpClient.PostAsync(url, content);
        f.errorFile(pickUpRequestCall.StatusCode.ToString());
        if (pickUpRequestCall.StatusCode == HttpStatusCode.OK)
        {
            var strResBody = pickUpRequestCall.Content.ReadAsStringAsync().Result;
            f.errorFile(strResBody);
        }
    }
    catch(HttpRequestException e)
    {
        f.errorFile(e.ToString());
    }
}

</code>```

I tried using
System.Net.ServicePointManager.SecurityProtocol =  SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

Body:
System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a send. ---> System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. ---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
   at System.Net.Sockets.Socket.EndReceive(IAsyncResult asyncResult)
   at System.Net.Sockets.NetworkStream.EndRead(IAsyncResult asyncResult)
   --- End of inner exception stack trace ---
   at System.Net.TlsStream.EndWrite(IAsyncResult asyncResult)
   at System.Net.ConnectStream.WriteHeadersCallback(IAsyncResult ar)
   --- End of inner exception stack trace ---
   at System.Net.HttpWebRequest.EndGetRequestStream(IAsyncResult asyncResult, TransportContext& context)
   at System.Net.Http.HttpClientHandler.GetRequestStreamCallback(IAsyncResult ar)
   --- End of inner exception stack trace ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at CanadianTireDashboard.Controllers.HomeController.<pickUpApi>d__109.MoveNext() in C:\Users\sbaqai\Documents\TFS\CanadianTireDashboard\CanadianTireDashboard\Controllers\HomeController.cs:line 865

I have given up. Idk why this works on our dev server but not on prod. Our dev and prod are on IIS. I am still new to C# and .NET Framework but after Googling around I still can't fix this error.
Nothing works.

Here is my code that is trying to call HttpClient.PostAsync

private async Task pickUpApi(string billOfLading)
{
    ErrorFile f = new ErrorFile();

    HomeController hc = new HomeController();
    HttpResponseMessage pickUpRequestCall = null;

    //Send a request to url with an xml body
    try
    {

        //var url = "http://www.saiasecure.com/webservice/shipment/xml.aspx?";
        var url = "https://www.tst-cfexpress.com/xml/pickup";

        XmlSerializer xmlSerializer = new XmlSerializer(typeof(pickuprequest));
        XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
        ns.Add("", "");
        pickuprequest cdn = new pickuprequest();

        var values = cdn.getAll(billOfLading);

        try
        {
            var path = $@"C:\CDNTireJobs\Test\{billOfLading}.xml";
            var encoding = Encoding.GetEncoding("ISO-8859-1");
            using (XmlTextWriter tw = new XmlTextWriter(path, encoding))
            {
                xmlSerializer.Serialize(tw, values, ns);
                tw.Close();
            }
        }
        catch (FileNotFoundException e)
        {
            f.errorFile($"File Exception {e.Message}");
        }

        var xmlcontent = System.IO.File.ReadAllText($@"C:\CDNTireJobs\Test\{billOfLading}.xml");
        var content = new StringContent(xmlcontent,
                        Encoding.GetEncoding("ISO-8859-1"), "application/xml");

        ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12;
        ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;

        pickUpRequestCall = await httpClient.PostAsync(url, content);
        f.errorFile(pickUpRequestCall.StatusCode.ToString());
        if (pickUpRequestCall.StatusCode == HttpStatusCode.OK)
        {
            var strResBody = pickUpRequestCall.Content.ReadAsStringAsync().Result;
            f.errorFile(strResBody);
        }
    }
    catch(HttpRequestException e)
    {
        f.errorFile(e.ToString());
    }
}

I tried using
System.Net.ServicePointManager.SecurityProtocol =  SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;


问:
How to set a custom User-Agent in Perl's Selenium::Remote::Driver
I use Selenium::Remote::Driver and need to set up a "normal" user-agent. I've tried to use Selenium::UserAgent, but it has only some User-Agents for mobiles and tables, and none for usual desktop PC's. Maybe there's a way to expand the list of devices in Selenium::UserAgent, or how to set up a correct User-Agent (I'd like would be Firefox) in Selenium::Remote:Driver manually?

Update:

I'm trying to parse a website which is protected from bots (solve the puzzle if you are a human). When I try to parse it with the default Selenium+Firefox UserAgent - the protection appears.

I've tried to use Selenium::UserAgent and it worked - the protection has disappeared, but I wasn't able to scrape the needed data, because the target site promotes it's mobile apllication instead of showing the needed data this way.

So, after that I've checked the UserAgent of my home computer's browser and set it up using LWP::UserAgent:

```<code>my $ua = LWP::UserAgent->new( "Mozilla/5.0 (X11; Linux x86_64; rv:105.0) Gecko/20100101 Firefox/105.0" );

my $driver = Selenium::Remote::Driver->new( browser_name => 'firefox', ua => $ua );
</code>```

But this way the protection arrived again.

After that, I've connected to my server through the VNC viewer, opened the same Firefox I've been using with Selenium, and there was no anti-bot protection this way. So, that's why I'm sure that I need to use a correct UserAgent and/or some other settings.

Body:
I use Selenium::Remote::Driver and need to set up a "normal" user-agent. I've tried to use Selenium::UserAgent, but it has only some User-Agents for mobiles and tables, and none for usual desktop PC's. Maybe there's a way to expand the list of devices in Selenium::UserAgent, or how to set up a correct User-Agent (I'd like would be Firefox) in Selenium::Remote:Driver manually?

Update:

I'm trying to parse a website which is protected from bots (solve the puzzle if you are a human). When I try to parse it with the default Selenium+Firefox UserAgent - the protection appears.

I've tried to use Selenium::UserAgent and it worked - the protection has disappeared, but I wasn't able to scrape the needed data, because the target site promotes it's mobile apllication instead of showing the needed data this way.

So, after that I've checked the UserAgent of my home computer's browser and set it up using LWP::UserAgent:

my $ua = LWP::UserAgent->new( "Mozilla/5.0 (X11; Linux x86_64; rv:105.0) Gecko/20100101 Firefox/105.0" );

my $driver = Selenium::Remote::Driver->new( browser_name => 'firefox', ua => $ua );

But this way the protection arrived again.

After that, I've connected to my server through the VNC viewer, opened the same Firefox I've been using with Selenium, and there was no anti-bot protection this way. So, that's why I'm sure that I need to use a correct UserAgent and/or some other settings.


问:
Joomla 4 Custom module in template head
I try to insert in Joomla 4 custom module in template head.

In old Joomla 2.5 I was able to do it like this:

```<code><head> ... <jdoc:include type="modules" name="CustomTop" /> ... </head>
</code>```

This method seems don't work any more in Cassiopeia index.php

Title: Joomla 4 Custom module in template head

Body:
I try to insert in Joomla 4 custom module in template head.

In old Joomla 2.5 I was able to do it like this:

 ... <jdoc:include type="modules" name="CustomTop" /> ...

This method seems don't work any more in Cassiopeia index.php


问:
HTML ng-submit form not executing angularJS function in VSCode live server extension?
I have the following HTML:

```<code><!DOCTYPE html>
<html>
  <head>
    <title>My Login Form</title>
  </head>
  <body>
    <form class="login-form" ng-submit="login(credentials)" ng-controller = "loginScreenController">
      <label for="username">Username:</label><br>
      <input type="text" id="username" name="username" ng-model="credentials.username"><br>
      <label for="password">Password:</label><br>
      <input type="password" id="password" name="password" ng-model="credentials.password"><br><br>
      <input type="submit" value="Login">
    </form>
  </body>
</html>
</code>```

Associated is an angularJS script which is used to execute the login() function:

```<code> var webApp = angular.module('App.module', [ngCookies]);
 webApp.controller('loginScreenController',loginScreenController);
 loginScreenController.$inject = ['$https','$cookies'];
function loginScreenController($https,$cookies) {
      console.log("We launched the function!")
      print("ffs is it working yet?")

      var vm = this;

      vm.login = login;

      // Credentials is passed not explciitly as a JSON object, but formatted thusly and the server handle it as if it is JSON
      function login(credentials) {
    console.log("Print something")
    }
}
</code>```

I am using the "Live Server" extension in VSCode to host the HTML. I am expecting the console.log to print something to terminal in VSCode when the but nothing happens upon clicking the button. I also checked "Output" and nothing happens there. Am I looking in the wrong spot? Is there something wrong with my code?

Body:
I have the following HTML:

<!DOCTYPE html>

    <title>My Login Form</title>

    <form class="login-form" ng-submit="login(credentials)" ng-controller = "loginScreenController">
      Username:

      <input type="text" id="username" name="username" ng-model="credentials.username">

      Password:

      <input type="password" id="password" name="password" ng-model="credentials.password">

      <input type="submit" value="Login">
    </form>

Associated is an angularJS script which is used to execute the login() function:

 var webApp = angular.module('App.module', [ngCookies]);
 webApp.controller('loginScreenController',loginScreenController);
 loginScreenController.$inject = ['$https','$cookies'];
function loginScreenController($https,$cookies) {
      console.log("We launched the function!")
      print("ffs is it working yet?")

      var vm = this;

      vm.login = login;

      // Credentials is passed not explciitly as a JSON object, but formatted thusly and the server handle it as if it is JSON
      function login(credentials) {
    console.log("Print something")
    }
}

I am using the "Live Server" extension in VSCode to host the HTML. I am expecting the console.log to print something to terminal in VSCode when the but nothing happens upon clicking the button. I also checked "Output" and nothing happens there. Am I looking in the wrong spot? Is there something wrong with my code?


问:
Mirror/setup of a Python rdflib graph from a remote SPARQL endpoint
How do I setup a Python rdflib graph from a remote SPARQL endpoint?

I have done a SELECT ?s ?p ?o WHERE { ?s ?p ?o } SPARQL query to the remote endpoint to get all triples and I have downloaded the resulting XML file. I was then expecting there would be a function somewhere in rdflib to build the local rdflib graph in a Python one-liner.

The closest I have is:

from rdflib.plugins.sparql.results.xmlresults import XMLResultParser
result = XMLResultParser().parse('dump.xml')
```
<p>This is not the original graph but rather the SPARQL result.</p>
<p>I suppose I would then have to iterate through the <code>result.bindings</code> variable adding the data with the Graph.add method, like</p>
<pre class="lang-py prettyprint-override"><code>g = rdflib.Graph()
for binding in result.bindings:
   g.add((binding[rdflib.term.Variable('s')],
          binding[rdflib.term.Variable('p')],
          binding[rdflib.term.Variable('o')]))
</code>```

It seems to be possible to query the original graph via g.query.

So is this it or would there be a more direct way of mirroring the remote triple store?

Body:
How do I setup a Python rdflib graph from a remote SPARQL endpoint?

I have done a SELECT ?s ?p ?o WHERE { ?s ?p ?o } SPARQL query to the remote endpoint to get all triples and I have downloaded the resulting XML file. I was then expecting there would be a function somewhere in rdflib to build the local rdflib graph in a Python one-liner.

The closest I have is:

from rdflib.plugins.sparql.results.xmlresults import XMLResultParser
result = XMLResultParser().parse('dump.xml')

This is not the original graph but rather the SPARQL result.

I suppose I would then have to iterate through the result.bindings variable adding the data with the Graph.add method, like

g = rdflib.Graph()
for binding in result.bindings:
   g.add((binding[rdflib.term.Variable('s')],
          binding[rdflib.term.Variable('p')],
          binding[rdflib.term.Variable('o')]))

It seems to be possible to query the original graph via g.query.

So is this it or would there be a more direct way of mirroring the remote triple store?


问:
Row-based or column-based convention for storing data in multi-arrays?
Suppose we have m vectors in R^n (or R^(n,1)) with m >> n.

We want to transform these by a linear transformation (applying a Matrix A^(k, n)) and by a translation given by a vector b in R^n. This is obviously faster with a 2D NumPy array then with a list of vectors.

When designing an API, would it be preferable to have a Matrix V of shape (n, m) or (m, n)?

The former, V_1.shape = (n, m), is what we are used to from mathematics. It is easy to apply A, simply write A @ V_1. Translating V_1 by b is not that easy though, we would need to reshape vector b in this case.

If V_2.shape = (m, n) then translating V_2 by b is easy (thanks to NumPy broadcasting), but applying A to V_2 couldn't be done by calculating A @ V_2 anymore. Instead we would need to use something like V_2 @ A.T.

It appears (from limited research) that SciPy, Scikit usually prefer the latter convention (NumPy itself doesn't seem too opinionated on this problem). Why is that?

Note my question centers around which convention to use in terms of the API and not in regard to the data layout in memory.


问:
Mapping elements for the navbar is not rendering in react
I am using a constant folder in which I have created all the arrays and object which includes the static data which I am going to render on my Web page
I am trying to render the nav element using map Method but it showing nothing.

```<code>import React from 'react'
import { useState } from 'react'
import { close, logo, menu } from "../assets";

import { navLinks } from '../constants/index'

const Navbar = () => {
  return (
    <div className="w-full flex py-6 justify-between items-center navbar">
      <img src={logo} alt="logo" className='w-[124px] h-[32px' />
      <ul className='list-none s,:flex hidden justify-end items-center flex-1'>
        {navLinks.map((nav, index) => {
          return (
            <li
              key={nav.id}
              className={`font-poppins font-normal cursor-pointer text-[16px] text-white`}>
              <a href={`#${nav.id}`}>
                {nav.title}
              </a>
            </li>

          )

        })}
      </ul>
    </div>
  )
}

export default Navbar
</code>```

Body:
I am using a constant folder in which I have created all the arrays and object which includes the static data which I am going to render on my Web page
I am trying to render the nav element using map Method but it showing nothing.

import React from 'react'
import { useState } from 'react'
import { close, logo, menu } from "../assets";

import { navLinks } from '../constants/index'

const Navbar = () => {
  return (

        {navLinks.map((nav, index) => {
          return (
            <li
              key={nav.id}
              className={`font-poppins font-normal cursor-pointer text-[16px] text-white`}>
              <a href={`#${nav.id}`}>
                {nav.title}

          )

        })}

  )
}

export default Navbar


问:
How to manage overlapping dates in React Native Calendars with multi-period marking
I'm using React Native Calendars with the markingType "multi-period", which needs to be in the following format:

```<code>markedDates={{
    '2017-12-14': {
      periods: [
        {startingDay: false, endingDay: true, color: '#5f9ea0'},
        {startingDay: false, endingDay: true, color: '#ffa500'},
        {startingDay: true, endingDay: false, color: '#f0e68c'}
      ]
    },
    '2017-12-15': {
      periods: [
        {startingDay: true, endingDay: false, color: '#ffa500'},
        {color: 'transparent'},
        {startingDay: false, endingDay: false, color: '#f0e68c'}
      ]
    }
  }}
</code>```

Lets say for example that we have two periods: 2022-12-14 - 2022-12-17 and 2022-12-16 - 2022-12-19. They have overlapping days. 2022-12-18 and 2022-12-19 need to have two "invisible" dates before them, so that in the final result they will be on the same height. Hardcoded it would look like this:

```<code>markedDates={{
    '2017-12-14': {
      periods: [
        {startingDay: true, endingDay: false, color: '#5f9ea0'}
      ]
    },
    '2017-12-15': {
      periods: [
        {startingDay: false, endingDay: false, color: '#ffa500'}
      ]
    },
    '2017-12-16': {
      periods: [
        {startingDay: false, endingDay: false, color: '#5f9ea0'},
        {startingDay: true, endingDay: false, color: '#5f9ea0'}
      ]
    },
    '2017-12-17': {
      periods: [
        {startingDay: false, endingDay: true, color: '#ffa500'},
        {startingDay: false, endingDay: false, color: '#5f9ea0'}
      ]
    },
    '2017-12-18': {
      periods: [
        {color: 'transparent'},
        {startingDay: false, endingDay: false, color: '#5f9ea0'}
      ]
    },
    '2017-12-19': {
      periods: [
        {color: 'transparent'},
        {startingDay: false, endingDay: true, color: '#ffa500'}
      ]
    },
  }}
</code>```

How would the code look like, when dynamically setting markedDates from fetched data and caring about overlapping dates, means inserting

```<code>{color: 'transparent'}
</code>```

when needed since the position in the array is important?

Body:
I'm using React Native Calendars with the markingType "multi-period", which needs to be in the following format:

markedDates={{
    '2017-12-14': {
      periods: [
        {startingDay: false, endingDay: true, color: '#5f9ea0'},
        {startingDay: false, endingDay: true, color: '#ffa500'},
        {startingDay: true, endingDay: false, color: '#f0e68c'}
      ]
    },
    '2017-12-15': {
      periods: [
        {startingDay: true, endingDay: false, color: '#ffa500'},
        {color: 'transparent'},
        {startingDay: false, endingDay: false, color: '#f0e68c'}
      ]
    }
  }}

Lets say for example that we have two periods: 2022-12-14 - 2022-12-17 and 2022-12-16 - 2022-12-19. They have overlapping days. 2022-12-18 and 2022-12-19 need to have two "invisible" dates before them, so that in the final result they will be on the same height. Hardcoded it would look like this:

markedDates={{
    '2017-12-14': {
      periods: [
        {startingDay: true, endingDay: false, color: '#5f9ea0'}
      ]
    },
    '2017-12-15': {
      periods: [
        {startingDay: false, endingDay: false, color: '#ffa500'}
      ]
    },
    '2017-12-16': {
      periods: [
        {startingDay: false, endingDay: false, color: '#5f9ea0'},
        {startingDay: true, endingDay: false, color: '#5f9ea0'}
      ]
    },
    '2017-12-17': {
      periods: [
        {startingDay: false, endingDay: true, color: '#ffa500'},
        {startingDay: false, endingDay: false, color: '#5f9ea0'}
      ]
    },
    '2017-12-18': {
      periods: [
        {color: 'transparent'},
        {startingDay: false, endingDay: false, color: '#5f9ea0'}
      ]
    },
    '2017-12-19': {
      periods: [
        {color: 'transparent'},
        {startingDay: false, endingDay: true, color: '#ffa500'}
      ]
    },
  }}

How would the code look like, when dynamically setting markedDates from fetched data and caring about overlapping dates, means inserting

{color: 'transparent'}

when needed since the position in the array is important?


问:
How to remove Core Data Object from memory?
I have a for loop to go trough all relationships for a single Core Data Object, and check if the relationship has a valid image:

```<code>
let context = CDStack.persitentContainer.newBackgroundContext()

let counter = 0
let object = Object.find(by: UUID, in context)

context.perform {
  for item in object.items {
     guard let item = item as? ObjectItem else {
        return
     }
     if let data = item.data {
        if UIImage(data: data) != nil {
           counter += 1
        }
     }
  }
}

</code>```

The issue is that the object has thousands of items and the memory is growing too quickly. Is there a way to remove the item from context memory once I have done the necessary check and incremented my counter?

Thank you.

Body:
I have a for loop to go trough all relationships for a single Core Data Object, and check if the relationship has a valid image:

let context = CDStack.persitentContainer.newBackgroundContext()

let counter = 0
let object = Object.find(by: UUID, in context)

context.perform {
  for item in object.items {
     guard let item = item as? ObjectItem else {
        return
     }
     if let data = item.data {
        if UIImage(data: data) != nil {
           counter += 1
        }
     }
  }
}

The issue is that the object has thousands of items and the memory is growing too quickly. Is there a way to remove the item from context memory once I have done the necessary check and incremented my counter?

Thank you.