问:
Can WKWebview.takeSnapshot capture content that is not visible in the viewport?
I am attempting to capture the entire contents of a WKWebView. Currently when I'm taking a screenshot, the content that is not visible in the viewport doesn't render into the screenshot, leaving the screenshot blank in some parts. The empty parts of the screenshot seem to be where the frame was extended to be the same size as the content size.

Is it possible to capture the entire WKWebView in one pass without having to stitch together two different images?


来源: stackexchange

问:
Pinescript in TradingView: Sell gradually while using pyramiding entries
I am using pyramiding entries with a simple strategy in TradingView. This works fine with long/buy entries, which continue being placed (pyramiding up) until the pyramiding limit has been reached.

However, the next sell/short entry sells all the contracts that have been purchased by the long entries so far. Even setting qty parameter as follows strategy.entry("sell", direction=strategy.short, comment="Sell", qty=10) does not change this behavior.

The first chart in this article shows three "long breakout +1" entries followed by a single "Close position order -3". Instead, I'd like to gradually close my positions, i.e. have three "Close position order -1" entries.

Is it possible to have short entries pyramid down just like long entries pyramid up?

ContentLicense: CC BY-SA 4.0


问:
AWS SQL Server stopped connecting after few hours. What can be the reason?
Yesterday I acquired a SQL Server instance on AWS and managed to connect using below.

I even managed to create a new database, create table and insert data. After few hours when I went back it has started timing out like below with message like below.

I see SQL Server available in AWS GUI


问:
Is there a way i can default a value on another dropdown list by selecting a value on a current dropdown list?
The problem is that I have two dropdown lists, citizenship and country. When i select Citizen as a value option in Citizenship, i want the country dropdown list to default to Argentina for example.

This seem to be working when its a dropdown list to an input box but not when its a dropdown list to a dropdown list.

```<code>            <div class="input-icons">
            <select class="input-field" name="citizenship" id="citizenship">
                <option value="">Select citizenship status</option>
                <option value="female">Citizen</option>
                <option value="male">Non Citizen</option>
            </select>
            <span class="my_error">*    <?php echo $errors['citizenship'];?></span>
            </div>

            <div class="input-icons">
            <select class="input-field" name="country" id="country" onchange="onchangeStatus"()>
            <option value="">Select Country</option>
                <option value="AF">Afghanistan</option>
                <option value="AX">Åland Islands</option>
                <option value="AL">Albania</option>
                <option value="DZ">Algeria</option>
                <option value="AS">American Samoa</option>
                <option value="AD">Andorra</option>
                <option value="AO">Angola</option>
                <option value="AI">Anguilla</option>
                <option value="AQ">Antarctica</option>
                <option value="AG">Antigua and Barbuda</option>
                <option value="AR">Argentina</option>
                <option value="AM">Armenia</option>
                <option value="AW">Aruba</option>
            </select>
            <span class="my_error">*    <?php echo $errors['country'];?></span>
            </div>
</code>```

    function onchangeCitizen()
    {

        var status = document.getElementById("citizenship");

        if(status.value == "Citizen"){

            document.getElementById("country").value="Argentina";

        }
    }

I am expecting the program to default to Argentina when I select Citizen as the value. It seems to work with an input box and not a dropdown list.

Body:
The problem is that I have two dropdown lists, citizenship and country. When i select Citizen as a value option in Citizenship, i want the country dropdown list to default to Argentina for example.

This seem to be working when its a dropdown list to an input box but not when its a dropdown list to a dropdown list.

            <select class="input-field" name="citizenship" id="citizenship">
                <option value="">Select citizenship status</option>
                <option value="female">Citizen</option>
                <option value="male">Non Citizen</option>
            </select>
            *    <?php echo $errors['citizenship'];?>

            <select class="input-field" name="country" id="country" onchange="onchangeStatus"()>
            <option value="">Select Country</option>
                <option value="AF">Afghanistan</option>
                <option value="AX">Åland Islands</option>
                <option value="AL">Albania</option>
                <option value="DZ">Algeria</option>
                <option value="AS">American Samoa</option>
                <option value="AD">Andorra</option>
                <option value="AO">Angola</option>
                <option value="AI">Anguilla</option>
                <option value="AQ">Antarctica</option>
                <option value="AG">Antigua and Barbuda</option>
                <option value="AR">Argentina</option>
                <option value="AM">Armenia</option>
                <option value="AW">Aruba</option>
            </select>
            *    <?php echo $errors['country'];?>

    function onchangeCitizen()
    {

        var status = document.getElementById("citizenship");

        if(status.value == "Citizen"){

            document.getElementById("country").value="Argentina";

        }
    }

I am expecting the program to default to Argentina when I select Citizen as the value. It seems to work with an input box and not a dropdown list.


问:
VBA Script to enter data on HTML input Element with Required Attribute
I am working on a script on VBA to capture some repetitive data on a CRM web database but I am having a problem with an input field that has a required attribute and when the script enters the data and i save the values entered the element with the Required attribute does not get saved in the form and it clears the field.

Is there a way to prevent this?

i tried several methods but nothing is working, here is a sample of the way I am trying to enter the values on the input fields.

```<code>sub CRMdata()
    Dim ie As New SHDocVw.InternetExplorerMedium
    Dim htmldoc As MSHTML.HTMLDocument
    Dim htmlcol As MSHTML.IHTMLElementCollection
    Dim htmlbody As MSHTML.IHTMLElement
    Dim htmlobj As MSHTML.IHTMLElement
    Dim iframe As HTMLIFrame
    Dim frame As HTMLFrameElement
    Dim descrip1 As String

    descrip1 = "name1"

    'load webpage and store IE Document
    With ie
        .Visible = True
        .navigate ("my webapge")
    End With
    Do While ie.readyState <> READYSTATE_COMPLETE
        Application.StatusBar = "Loading WebPage..."
        DoEvents
    Loop
    Application.Wait (Now + TimeValue("00:00:03"))
    Set htmldoc = ie.document

    'set iframe work area in CRM Environment
    Set iframe = htmldoc.getElementById("CRMApplicationFrame")
    Set htmldoc = iframe.contentWindow.document

    'set frame work area 1 in CRM enviroment
    Set frame = htmldoc.getElementById("WorkAreaFrame1")
    Set htmldoc = frame.contentWindow.document

    With htmldoc
        .getElementById("C14_W65_V67_V70_V71_btadminh_struct.description").Value = descrip1
    End With

    'Save the CRM opportunity
    'htmldoc.getElementById("C14_W65_V67_thtmlb_button_1").Click

End Sub
</code>```

Body:
I am working on a script on VBA to capture some repetitive data on a CRM web database but I am having a problem with an input field that has a required attribute and when the script enters the data and i save the values entered the element with the Required attribute does not get saved in the form and it clears the field.

Is there a way to prevent this?

i tried several methods but nothing is working, here is a sample of the way I am trying to enter the values on the input fields.

sub CRMdata()
    Dim ie As New SHDocVw.InternetExplorerMedium
    Dim htmldoc As MSHTML.HTMLDocument
    Dim htmlcol As MSHTML.IHTMLElementCollection
    Dim htmlbody As MSHTML.IHTMLElement
    Dim htmlobj As MSHTML.IHTMLElement
    Dim iframe As HTMLIFrame
    Dim frame As HTMLFrameElement
    Dim descrip1 As String

    descrip1 = "name1"

    'load webpage and store IE Document
    With ie
        .Visible = True
        .navigate ("my webapge")
    End With
    Do While ie.readyState <> READYSTATE_COMPLETE
        Application.StatusBar = "Loading WebPage..."
        DoEvents
    Loop
    Application.Wait (Now + TimeValue("00:00:03"))
    Set htmldoc = ie.document

    'set iframe work area in CRM Environment
    Set iframe = htmldoc.getElementById("CRMApplicationFrame")
    Set htmldoc = iframe.contentWindow.document

    'set frame work area 1 in CRM enviroment
    Set frame = htmldoc.getElementById("WorkAreaFrame1")
    Set htmldoc = frame.contentWindow.document

    With htmldoc
        .getElementById("C14_W65_V67_V70_V71_btadminh_struct.description").Value = descrip1
    End With

    'Save the CRM opportunity
    'htmldoc.getElementById("C14_W65_V67_thtmlb_button_1").Click

End Sub


问:
ERROR in ./node_modules/httpntlm/ntlm.js - Module parse failed: Identifier directly after number (427:47)
hi this is my first time asking question on SO and hoping someone could help me. I'm trying to use httpntlm module and while I'm trying to use this code:
const httpntlm = require('httpntlm')
I'm getting error

`

```<code>ERROR in ./node_modules/httpntlm/ntlm.js
Module parse failed: Identifier directly after number (427:47)
You may need an appropriate loader to handle this file type.
|       // 11644473600000 = diff between 1970 and 1601
|       var now = Date.now();
|       var timestamp = ((BigInt(now) + 11644473600000n) * 10000n);
|       var timestampBuffer = Buffer.alloc(8);
|       timestampBuffer.writeBigUInt64LE(timestamp);
 @ ./node_modules/httpntlm/httpntlm.js 13:11-28
 @ ./src/services/createViewingSession.service.ts
 @ ./src/services/index.ts
 @ ./src/index.ts
</code>```

`

I really appreciate your help. Thank you.

I tried to use other version of nvm (15.5.1) and (16.10.0) to create package using this command "npm run package" but no luck.

Body:
hi this is my first time asking question on SO and hoping someone could help me. I'm trying to use httpntlm module and while I'm trying to use this code:
const httpntlm = require('httpntlm')
I'm getting error

`

ERROR in ./node_modules/httpntlm/ntlm.js
Module parse failed: Identifier directly after number (427:47)
You may need an appropriate loader to handle this file type.
|       // 11644473600000 = diff between 1970 and 1601
|       var now = Date.now();
|       var timestamp = ((BigInt(now) + 11644473600000n) * 10000n);
|       var timestampBuffer = Buffer.alloc(8);
|       timestampBuffer.writeBigUInt64LE(timestamp);
 @ ./node_modules/httpntlm/httpntlm.js 13:11-28
 @ ./src/services/createViewingSession.service.ts
 @ ./src/services/index.ts
 @ ./src/index.ts

`

I really appreciate your help. Thank you.

I tried to use other version of nvm (15.5.1) and (16.10.0) to create package using this command "npm run package" but no luck.


问:
Appending Test logs into a file using log4j2
I have spring mvc multi-module project. In each module I have separate java test classes[src/test/java].
When I build the application I noticed test cases also running.
Now I want to append those test results into both console and file using log4j2 configuration.
Under [src/test/resource] I have log4j2.xml file configuration file.

```<code><?xml version="1.0" encoding="UTF-8"?>
<Configuration status="DEBUG">
    <Appenders>
        <Console name="LogToConsole" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
        </Console>
        <File name="LogToFile" fileName="D:/logs/app.log">
            <PatternLayout>
                <Pattern>%d %p %c{1.} [%t] %m%n</Pattern>
            </PatternLayout>
        </File>
    </Appenders>
    <Loggers>
        <Logger name="com.test.packagename" level="debug" additivity="false">
            <AppenderRef ref="LogToFile"/>
            <AppenderRef ref="LogToConsole"/>
        </Logger>
        <Root level="error">
            <AppenderRef ref="LogToFile"/>
            <AppenderRef ref="LogToConsole"/>
        </Root>
    </Loggers>
</Configuration>

</code>```

I'm able to see console results but still file appending is not happening.
Some suggestions would be very helpful.

I have added my code above please check

Body:
I have spring mvc multi-module project. In each module I have separate java test classes[src/test/java].
When I build the application I noticed test cases also running.
Now I want to append those test results into both console and file using log4j2 configuration.
Under [src/test/resource] I have log4j2.xml file configuration file.

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="DEBUG">
    <Appenders>
        <Console name="LogToConsole" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
        </Console>
        <File name="LogToFile" fileName="D:/logs/app.log">
            <PatternLayout>
                <Pattern>%d %p %c{1.} [%t] %m%n</Pattern>
            </PatternLayout>
        </File>
    </Appenders>
    <Loggers>
        <Logger name="com.test.packagename" level="debug" additivity="false">
            <AppenderRef ref="LogToFile"/>
            <AppenderRef ref="LogToConsole"/>
        </Logger>
        <Root level="error">
            <AppenderRef ref="LogToFile"/>
            <AppenderRef ref="LogToConsole"/>
        </Root>
    </Loggers>
</Configuration>

I'm able to see console results but still file appending is not happening.
Some suggestions would be very helpful.

I have added my code above please check


问:
How to pass new Date to Spring Batch Tasklet in every new launch of Spring Batch Job?
The example I am providing is simplified version of my code.

I am using JobLauncher to launch spring batch from @Scheduled method. My application never stops running because I am using @Scheduled

import org.springframework.scheduling.annotation.Scheduled;

```<code>@Scheduled(fixedRate = 30000)
    public void scheduleFixedRate() { //launch job code }
</code>```

I have a spring batch tasklet that uses date to do some logic. The issue is that my date never changes once initialized because @Bean is set when the application loads. The date never changes between run of spring batch job.

```<code>@Bean
public TestTasklet testTasklet(){

    final var tasklet = new TestTasklet();
    tasklet.setTextToLog(LocalDateTime.now().toString());

    return tasklet;
}
</code>```

Is there a way to pass new Date to Spring Batch Tasklet in every new launch of Spring Batch Job? Few potential solutions, I thought of are below. I was wondering if there are better ways.

Generating new date inside execute() method of tasklet.

Setting LocalDateTime parameter value as job parameter value so values changes in every run.

Body:
The example I am providing is simplified version of my code.

I am using JobLauncher to launch spring batch from @Scheduled method. My application never stops running because I am using @Scheduled

import org.springframework.scheduling.annotation.Scheduled;

@Scheduled(fixedRate = 30000)
    public void scheduleFixedRate() { //launch job code }

I have a spring batch tasklet that uses date to do some logic. The issue is that my date never changes once initialized because @Bean is set when the application loads. The date never changes between run of spring batch job.

@Bean
public TestTasklet testTasklet(){

    final var tasklet = new TestTasklet();
    tasklet.setTextToLog(LocalDateTime.now().toString());

    return tasklet;
}

Is there a way to pass new Date to Spring Batch Tasklet in every new launch of Spring Batch Job? Few potential solutions, I thought of are below. I was wondering if there are better ways.

Generating new date inside execute() method of tasklet.

Setting LocalDateTime parameter value as job parameter value so values changes in every run.


问:
How to get Oid of column from the given datatype name
I am implementing a function to get Oid from the given datatype name.
The datatype name is gotten from remote server (ex: MySQL, Postgres, GridDB)

This function like below:

```<code>static Oid
get_oid_from_type(char *column_type)
{
    if (strcmp(column_type, "INT") == 0 ||
        strcmp(column_type, "INTEGER") == 0 ||
        strcmp(column_type, "int4") == 0)
    {
        return INT4OID;
    }

    // TODO: There is a lot of types need to add here
    // I do not know how many data type is enough
}
</code>```

I do not know how many data type is enough to add in this function.
So is there a function of Postgresql can do that?

I think maybe there is a function relate to TYPENAMENSP in Postgresql, that can help me, but I have not found it yet.

Body:
I am implementing a function to get Oid from the given datatype name.
The datatype name is gotten from remote server (ex: MySQL, Postgres, GridDB)

This function like below:

static Oid
get_oid_from_type(char *column_type)
{
    if (strcmp(column_type, "INT") == 0 ||
        strcmp(column_type, "INTEGER") == 0 ||
        strcmp(column_type, "int4") == 0)
    {
        return INT4OID;
    }

    // TODO: There is a lot of types need to add here
    // I do not know how many data type is enough
}

I do not know how many data type is enough to add in this function.
So is there a function of Postgresql can do that?

I think maybe there is a function relate to TYPENAMENSP in Postgresql, that can help me, but I have not found it yet.


问:
My E-Signature I built in PHP/HTML is not working on mobile/tablet/touch device (scrolling)
I created an e-signature area for users to sign that they agree to the terms and conditions before submitting the form. This is then pushed into Microsoft DataVerse backend as an image and stored. There is something wrong because when trying to sign a signature on a mobile/tablet/touch screen device the page is scrolling and not allowing the user to sign correctly.

I've tried supplementing my code with articles I have found online to no avail. I've also been reading other resources to try and figure out why this is happening especially when I have tried :

@media (pointer: coarse) {

body {

```<code>overflow: hidden; /* Needed to prevent the vertical scroll on touch devices */
</code>```

}

}

Some articles used below:

https://medium.com/@divbydiv/build-a-signature-pad-in-html-css-js-canvas-bd174d999392

https://developer.mozilla.org/en-US/docs/Glossary/Signature/Function

https://codepen.io/yguo/pen/OyYGxQ

Body:
I created an e-signature area for users to sign that they agree to the terms and conditions before submitting the form. This is then pushed into Microsoft DataVerse backend as an image and stored. There is something wrong because when trying to sign a signature on a mobile/tablet/touch screen device the page is scrolling and not allowing the user to sign correctly.

I've tried supplementing my code with articles I have found online to no avail. I've also been reading other resources to try and figure out why this is happening especially when I have tried :

@media (pointer: coarse) {

body {

overflow: hidden; /* Needed to prevent the vertical scroll on touch devices */

}

}

Some articles used below:

https://medium.com/@divbydiv/build-a-signature-pad-in-html-css-js-canvas-bd174d999392

https://developer.mozilla.org/en-US/docs/Glossary/Signature/Function

https://codepen.io/yguo/pen/OyYGxQ


问:
type instance error when building trend_identifier using ohlc data
I am attempting to build a function that can identify whether or not the trend of the morning session of a NYSE ticker is 'bullish' or 'bearish', based on the current high/low of day, and which one was made most recently.

an exmaple of two rows of data in my dataset would be:

datetime
open
high
low
close

2021-03-30 09:30:00
394.41
394.73
394.24
394.41

2021-03-30 09:35:00
394.42
394.47
394.02
394.23

I believe that I have the logic properly worked out to track what I am seeking a store it properly, but I seem to have a datatype error somewhere in my 'high' column and I am unable to find it. The error I'm getting is:

TypeError: '>' not supported between instances of 'NaTType' and 'float'

I have read that NATType is specific to data/time fields, but I from what I can see the column does appear to have only the datatype 'float' within it, so I don't see why this is coming in to play. I've checked for standard NULL values and none exist, and I'm not sure how to check for NATType values, as the same code spits an error that NATType is not defined.

the actual function I'm trying to get to work:

```<code>def determine_trend(data):
    high_of_day = data.iloc[0]['high']
    low_of_day = data.iloc[0]['low']
    trend = 'chop'
    new_high = False
    new_low = False

    for i, row in data.iterrows():
        if row['high'] > high_of_day:
            high_of_day = row['high']
            trend = 'up'

        elif row['low'] < low_of_day:
            low_of_day = row['low']
            trend='down'

print(determine_trend(filtered_data))
</code>```

Body:
I am attempting to build a function that can identify whether or not the trend of the morning session of a NYSE ticker is 'bullish' or 'bearish', based on the current high/low of day, and which one was made most recently.

an exmaple of two rows of data in my dataset would be:

datetime
open
high
low
close

2021-03-30 09:30:00
394.41
394.73
394.24
394.41

2021-03-30 09:35:00
394.42
394.47
394.02
394.23

I believe that I have the logic properly worked out to track what I am seeking a store it properly, but I seem to have a datatype error somewhere in my 'high' column and I am unable to find it. The error I'm getting is:

TypeError: '>' not supported between instances of 'NaTType' and 'float'

I have read that NATType is specific to data/time fields, but I from what I can see the column does appear to have only the datatype 'float' within it, so I don't see why this is coming in to play. I've checked for standard NULL values and none exist, and I'm not sure how to check for NATType values, as the same code spits an error that NATType is not defined.

the actual function I'm trying to get to work:

def determine_trend(data):
    high_of_day = data.iloc[0]['high']
    low_of_day = data.iloc[0]['low']
    trend = 'chop'
    new_high = False
    new_low = False

    for i, row in data.iterrows():
        if row['high'] > high_of_day:
            high_of_day = row['high']
            trend = 'up'

        elif row['low'] < low_of_day:
            low_of_day = row['low']
            trend='down'

print(determine_trend(filtered_data))


问:
How to screen capture a Window on WPF
I am currently migrating an old Winforms project to WPF with the MVVM pattern, so I have been strugling with a lot of things. One on the last things I need to understand is how to  do a screen capture of the application Window after a SaveDialog Close. On Winforms is easy and I have the following code that does the job:

```<code>Form frm = Form.ActiveForm;
if (frm != null)
{
    using (Bitmap bmp = new Bitmap(frm.Width, frm.Height))
    {
        frm.DrawToBitmap(bmp, new Rectangle(0, 0, bmp.Width, bmp.Height));
        bmp.Save(saveFileDialog.FileName, ImageFormat.Png);
    }
}
</code>```

I have been struggling a lot with this and I have found something equivalent on WPF:

```<code>double screenLeft = SystemParameters.VirtualScreenLeft;
double screenTop = SystemParameters.VirtualScreenTop;
double screenWidth = SystemParameters.VirtualScreenWidth;
double screenHeight = SystemParameters.VirtualScreenHeight;

using (Bitmap bmp = new Bitmap((int)screenWidth, (int)screenHeight))
{
    using (Graphics g = Graphics.FromImage(bmp))
    {
        g.CopyFromScreen((int)screenLeft, (int)screenTop, 0, 0, bmp.Size);
        bmp.Save(nombreArchivo);
    }
}
</code>```

The problem with the past code is the following:
-First it creates a picture of the Whole screen.
-Second it give me ghosting results as soon as the SaveDialog close.

I just ask a way of how to do it as simple as Winforms using Form.ActiveForm; or the equivalent on WPF which I can't find.

Thanks in advance.

EDIT: Even if is marked as duplicated, none of the "duplicated" questions satisfied my needs, but I finally realized how to do it in a similar way of Winforms (simple), in case anyone needs it.

```<code>Window? window = Application.Current.Windows.OfType<Window>().SingleOrDefault(x => x.IsActive);
if (window != null)
{
    //Render Bitmap for Width and Height of window
    RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap((int)window.ActualWidth, (int)window.ActualHeight, 96, 96, Pixelwindowats.Pbgra32);
    renderTargetBitmap.Render(window);

    //Define encoder png
    PngBitmapEncoder png = new PngBitmapEncoder();
    png.Frames.Add(BitmapFrame.Create(renderTargetBitmap));
    using (Stream stm = File.Create(nombreArchivo))
    {
        png.Save(stm);
    }
}
</code>```

Title: How to screen capture a Window on WPF

Body:
I am currently migrating an old Winforms project to WPF with the MVVM pattern, so I have been strugling with a lot of things. One on the last things I need to understand is how to  do a screen capture of the application Window after a SaveDialog Close. On Winforms is easy and I have the following code that does the job:

Form frm = Form.ActiveForm;
if (frm != null)
{
    using (Bitmap bmp = new Bitmap(frm.Width, frm.Height))
    {
        frm.DrawToBitmap(bmp, new Rectangle(0, 0, bmp.Width, bmp.Height));
        bmp.Save(saveFileDialog.FileName, ImageFormat.Png);
    }
}

I have been struggling a lot with this and I have found something equivalent on WPF:

double screenLeft = SystemParameters.VirtualScreenLeft;
double screenTop = SystemParameters.VirtualScreenTop;
double screenWidth = SystemParameters.VirtualScreenWidth;
double screenHeight = SystemParameters.VirtualScreenHeight;

using (Bitmap bmp = new Bitmap((int)screenWidth, (int)screenHeight))
{
    using (Graphics g = Graphics.FromImage(bmp))
    {
        g.CopyFromScreen((int)screenLeft, (int)screenTop, 0, 0, bmp.Size);
        bmp.Save(nombreArchivo);
    }
}

The problem with the past code is the following:
-First it creates a picture of the Whole screen.
-Second it give me ghosting results as soon as the SaveDialog close.

I just ask a way of how to do it as simple as Winforms using Form.ActiveForm; or the equivalent on WPF which I can't find.

Thanks in advance.

EDIT: Even if is marked as duplicated, none of the "duplicated" questions satisfied my needs, but I finally realized how to do it in a similar way of Winforms (simple), in case anyone needs it.

Window? window = Application.Current.Windows.OfType<Window>().SingleOrDefault(x => x.IsActive);
if (window != null)
{
    //Render Bitmap for Width and Height of window
    RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap((int)window.ActualWidth, (int)window.ActualHeight, 96, 96, Pixelwindowats.Pbgra32);
    renderTargetBitmap.Render(window);

    //Define encoder png
    PngBitmapEncoder png = new PngBitmapEncoder();
    png.Frames.Add(BitmapFrame.Create(renderTargetBitmap));
    using (Stream stm = File.Create(nombreArchivo))
    {
        png.Save(stm);
    }
}


问:
Change pie chart datarange to a formula?
I have a Pie Chart which maps a set of data pretty simply:

These are all meant to represent categories of financial activity. The issue is that, when a positive number is added to the mix, it is treated the same:

This is normal, reasonable behavior, as pie charts use the absolute value of the data provided.

I would like to change this behavior, so that positive numbers are omitted from the pie chart, or perhaps set to 0.

The Chart data range string used to define the area of data seems formula-like to me... Is it possible to change this to a formula that would filter out positive numbers?

I've managed to successfully do this using VBA, by using the Worksheet_Change event to catch the values updating, and setting the chart's data range to only include negative categories. However, using VBA kills the undo history, which is too big of a sacrifice in my case.

I need to accomplish this without duplicating the data elsewhere (such as a bunch of =IF(I11<0,I11,0)'s). Is such a thing possible?


问:
DialogFlow SDK- Creating intent - OutputContext object format is wrong
I am creating Intents using Dialogflow SDK. Everything is working fine except when I try to create output context for the intent. Part of my code is below.

I am getting the error 'Error: 3 INVALID_ARGUMENT: com.google.apps.framework.request.BadRequestException: Resource name does not match format 'projects/{project_id}/agent/sessions/{session_id}/contexts/{context_id}' or 'projects/{project_id}/locations/{location_id}/agent/sessions/{session_id}/contexts/{context_id}'.

let cname ='projects/' +PROJECID + '/agent/sessions/-/contexts/testoutputcontext;

const Context =  {
name: cname,
lifespanCount: 2,
parameters: null

};

ToutputContexts.push(Context);

const intent = {
displayName: displayName,
inputContextNames:[inputContextNames],
outputContexts:[ToutputContexts],
events:[events],
trainingPhrases: trainingPhrases,
messages: [message],
action:action,
isFallback:isFallback,
parentFollowupIntentName:parentFollowupIntentName,
};

const createIntentRequest = {
parent: agentPath,
intent: intent,
};

// Create the intent
const [response] = await intentsClient.createIntent(createIntentRequest);
console.log(Intent ${response.name} created);
}

I believe sessionId is not required with the context name. But it looks like this is throwing me the error.


问:
Can't access POST/PUT/DELETE api but success access GET API in same url
I create my own API using PHP and access it with Javascript. It's successful when the method is GET, but fails for other methods.

error

Access to XMLHttpRequest at 'http://localhost/test/api' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

here are my codes.

api.php

```<code><?php
require_once "method.php";
header("Access-Control-Allow-Origin: *");
header("Access-Control-Expose-Headers: Content-Length, X-JSON");
header("Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Origin, X-Requested-with, Content_Type,Accept,Authorization");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Request-Headers: Content-Type");

...
?>
</code>```

.htaccess

```<code>RewriteEngine On # Turn on the rewriting engine
RewriteRule ^api/?$ api.php [NC,L]
RewriteRule ^api/([0-9]+)/?$ api.php?id=$1 [NC,L]
</code>```

script.js

```<code>function userDelete(id) {
    const xhttp = new XMLHttpRequest();
    xhttp.open("DELETE", "http://localhost/test/api");
    xhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
    xhttp.send(JSON.stringify({
      "id": id
    }));
    xhttp.onreadystatechange = function() {
      if (this.readyState == 4) {
        const objects = JSON.parse(this.responseText);
        Swal.fire(objects['message']);
        loadTable();
      }
    };
  }
</code>```

Body:
I create my own API using PHP and access it with Javascript. It's successful when the method is GET, but fails for other methods.

error

Access to XMLHttpRequest at 'http://localhost/test/api' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

here are my codes.

api.php

<?php
require_once "method.php";
header("Access-Control-Allow-Origin: *");
header("Access-Control-Expose-Headers: Content-Length, X-JSON");
header("Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Origin, X-Requested-with, Content_Type,Accept,Authorization");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Request-Headers: Content-Type");

...
?>

.htaccess

RewriteEngine On # Turn on the rewriting engine
RewriteRule ^api/?$ api.php [NC,L]
RewriteRule ^api/([0-9]+)/?$ api.php?id=$1 [NC,L]

script.js

function userDelete(id) {
    const xhttp = new XMLHttpRequest();
    xhttp.open("DELETE", "http://localhost/test/api");
    xhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
    xhttp.send(JSON.stringify({
      "id": id
    }));
    xhttp.onreadystatechange = function() {
      if (this.readyState == 4) {
        const objects = JSON.parse(this.responseText);
        Swal.fire(objects['message']);
        loadTable();
      }
    };
  }


问:
How to clip ListView items' ripple effect to the ListView's parent, when that parent has rounded corners?
I've created a PopupWindow with a rounded background, like this:

```<code>val popupWindow = PopupWindow(requireContext())
val roundedBackground = ResourcesCompat.getDrawable(resources, R.drawable.popup_menu_background, requireContext().theme)
popupWindow.setBackgroundDrawable(roundedBackground)
</code>```

And I'm using it as a dropdown, with a ListView and an Adapter:

```<code>val listView = ListView(requireContext())
listView.adapter = currencySpinnerAdapter
popupWindow.contentView = listView
</code>```

When clicking on an item, the ripple effect doesn't clip to the PopupWindow's rounded background. As you can see, this ripple doesn't match the top corners of the PopupWindow:

I've tried changing the ListView's background to add a ripple drawable:

```<code>listView.setBackgroundResource(R.drawable.my_ripple)
</code>```

The ripple does match the PopupWindow's contents, but it expands to the whole PopupWindow instead of matching the specific clicked item.

Is there any way to reach this desired effect?

Body:
I've created a PopupWindow with a rounded background, like this:

val popupWindow = PopupWindow(requireContext())
val roundedBackground = ResourcesCompat.getDrawable(resources, R.drawable.popup_menu_background, requireContext().theme)
popupWindow.setBackgroundDrawable(roundedBackground)

And I'm using it as a dropdown, with a ListView and an Adapter:

val listView = ListView(requireContext())
listView.adapter = currencySpinnerAdapter
popupWindow.contentView = listView

When clicking on an item, the ripple effect doesn't clip to the PopupWindow's rounded background. As you can see, this ripple doesn't match the top corners of the PopupWindow:

I've tried changing the ListView's background to add a ripple drawable:

listView.setBackgroundResource(R.drawable.my_ripple)

The ripple does match the PopupWindow's contents, but it expands to the whole PopupWindow instead of matching the specific clicked item.

Is there any way to reach this desired effect?


问:
Spyder shows not modules cv2
Why when I open my spyder using the anaconda prompt, then can use the package cv2 and run my program. However, when I directly open my spyder and run the code, it shows there is no modules cv2. It shouldnt be I had already download the opencv package then I can use the package without running from the anaconda prompt?

Anaconda Prompt

May I know what is the reason? Hope for help

Title: Spyder shows not modules cv2


问:
search delegate build suggestion not showing everything
I have a custom search delegate but the build suggestion doesn't show everything (see attach photo for reference) and giving an error that says RangeError (index): Invalid value: Not in inclusive range. the code below shows the custom search delegate.

```<code>class CustomSearchDelegate extends SearchDelegate{
  List<Product> searchterm = List.from(PRODUCTLIST);

  @override
  Widget buildResults(BuildContext context){
    List<Product> matchQuery = [];
    for(var items in searchterm){
      if(items.name.toLowerCase().contains(query.toLowerCase())){
        matchQuery.add(items);
      }
    }
    Size size = MediaQuery.of(context).size;
    return GridView.builder(
      itemCount: matchQuery.length,
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 2,
        crossAxisSpacing: 12,
        mainAxisSpacing: 12,
        childAspectRatio: size.width  / (size.height * 0.54)
      ),
      itemBuilder: (
        (context, index) =>
        ProductSearch(
          products: matchQuery[index],
        )
      ),
    );
  }
  @override
  Widget buildSuggestions(BuildContext context){
  List<Product> matchQuery = [];
    for(var items in searchterm){
      if(items.name.toLowerCase().contains(query.toLowerCase())){
        matchQuery.add(items);
      }
    }
    Size size = MediaQuery.of(context).size;
    return GridView.builder(
      itemCount: matchQuery.length,
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 2,
        crossAxisSpacing: 12,
        mainAxisSpacing: 12,
        childAspectRatio: size.width  / (size.height * 0.54)
      ),
      itemBuilder: (
        (context, index) =>
        ProductSearch(
          products: matchQuery[index],
        )
      ),
    );
  }
}
</code>```

I couldn't find what causing the error so hoping for your help.

Body:
I have a custom search delegate but the build suggestion doesn't show everything (see attach photo for reference) and giving an error that says RangeError (index): Invalid value: Not in inclusive range. the code below shows the custom search delegate.

class CustomSearchDelegate extends SearchDelegate{
  List<Product> searchterm = List.from(PRODUCTLIST);

  @override
  Widget buildResults(BuildContext context){
    List<Product> matchQuery = [];
    for(var items in searchterm){
      if(items.name.toLowerCase().contains(query.toLowerCase())){
        matchQuery.add(items);
      }
    }
    Size size = MediaQuery.of(context).size;
    return GridView.builder(
      itemCount: matchQuery.length,
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 2,
        crossAxisSpacing: 12,
        mainAxisSpacing: 12,
        childAspectRatio: size.width  / (size.height * 0.54)
      ),
      itemBuilder: (
        (context, index) =>
        ProductSearch(
          products: matchQuery[index],
        )
      ),
    );
  }
  @override
  Widget buildSuggestions(BuildContext context){
  List<Product> matchQuery = [];
    for(var items in searchterm){
      if(items.name.toLowerCase().contains(query.toLowerCase())){
        matchQuery.add(items);
      }
    }
    Size size = MediaQuery.of(context).size;
    return GridView.builder(
      itemCount: matchQuery.length,
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 2,
        crossAxisSpacing: 12,
        mainAxisSpacing: 12,
        childAspectRatio: size.width  / (size.height * 0.54)
      ),
      itemBuilder: (
        (context, index) =>
        ProductSearch(
          products: matchQuery[index],
        )
      ),
    );
  }
}

I couldn't find what causing the error so hoping for your help.


问:
Control between different Spring Batch applications
I have a question while using the spring batch.
Is there a way to control the execution/stop/restart of jobs among the spring batch applications running on each different instance?
Also, I wonder if there is a way for applications to control the flow of Job and execution/stop/restart of each other when using the database in the Spring Batch Meta table together.
Please give me some advice.

The jobs implemented in each application must be controlled by each other.


问:
Under what circumstances should we cache data in the database?
When is it a good idea to cache database data?

For example, when the data is constantly accessed.

I am not sure what is the best case for using cache, so I would like someone to tell me.

I tried it once without using the cache and it used up all the connection pool connections.
So I implemented most of it using the cache and the above mentioned problem disappeared.
But now the CPU of the database is not busy.
So, I wanted to keep the cache to the minimum necessary, so that the CPU is used 60% of the time.


问:
how to view a base64 encoded pdf in react js
The uploaded pdf file in my application is being stored as base64 encoding. I need to give a view pop-up for the same. I'm getting the base64 string along with the filetype, whether it's pdf or jpg/image. I have tried to convert the base64 string to blob as shown in many examples in stack overflow, but I am facing an error. img is the base64 string.

```<code>const byteCharacters = atob(img);
const byteNumbers = new Array(byteCharacters.length);
for (let i = 0; i < byteCharacters.length; i++) {
 byteNumbers[i] = byteCharacters.charCodeAt(i);
 }
const byteArray = new Uint8Array(byteNumbers);
const blob = new Blob([byteArray], {type: "application/pdf"});
var url = URL.createObjectURL(blob);
this.setState({imgData:url})
</code>```

In render this is what I have written:

```<code><Document file={this.state.imgData}>
    <Page pageNumber={1} />
</Document>
</code>```

But the image is not getting displayed and there isnt any error

When I'm pasting my base64 code in https://www.ipvoid.com/base64-to-pdf/
it's working. But why am I unable to view it? Is there any other alternate way?

Body:
The uploaded pdf file in my application is being stored as base64 encoding. I need to give a view pop-up for the same. I'm getting the base64 string along with the filetype, whether it's pdf or jpg/image. I have tried to convert the base64 string to blob as shown in many examples in stack overflow, but I am facing an error. img is the base64 string.

const byteCharacters = atob(img);
const byteNumbers = new Array(byteCharacters.length);
for (let i = 0; i < byteCharacters.length; i++) {
 byteNumbers[i] = byteCharacters.charCodeAt(i);
 }
const byteArray = new Uint8Array(byteNumbers);
const blob = new Blob([byteArray], {type: "application/pdf"});
var url = URL.createObjectURL(blob);
this.setState({imgData:url})

In render this is what I have written:

<Document file={this.state.imgData}>
    <Page pageNumber={1} />
</Document>

But the image is not getting displayed and there isnt any error

When I'm pasting my base64 code in https://www.ipvoid.com/base64-to-pdf/
it's working. But why am I unable to view it? Is there any other alternate way?


问:
Ask NebulaGraph database: Scheduler::analyzeLifetime related questions
I have two questions about the implementation of analyzeLifetime.

why is dfs? Can it be bfs?
If a1->a->b and a1->a->c when both b and c depend on a, then the userCount of both a and its dependent nodes is 2. a's userCount is indeed 2, but is a's dependency necessary?


问:
How to download blob: url video from a website?
I want to download a video file from a website, but in the source code the video file is not mentioned. Is there any way to download this embedded video?

The source code for the video player shows this:
the website name is blurred because this an educational institute, which will eventually remove my access from this paid content after a while.

And the network tab shows these media: no masterm3u8 header

I want to download this mp4, but there is no hosted file available. Is it even possible or is the access blocked within web browsers? Nothing seems to work.


问:
The android keeps crashing after use signPdf function on Chilkat library
I tried to sign Pdf with Android device. I successfully sign the example PDF without any error but when I tried to sign another PDF which file size is bigger than example, the error always occur which is

Fatal signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x0 in tid 16953 (com.chilkattest), pid 16953 (com.chilkattest) pid: 16953, tid: 16953, name: com.chilkattest  >>> com.chilkattest <<< #00 pc 008cdf44  /data/app/~~cJ2uq7xVy9POOEsEnUdOcA==/com.chilkattest-KCcMwMYehe8TciUfXzA62g==/base.apk!libchilkat.so (offset 0xc4000) (BuildId:ceb579f3889717d2c8ae2ef5d22e17d6391eaab9) #01 pc 0051f7b0  /data/app/~~cJ2uq7xVy9POOEsEnUdOcA==/com.chilkattest-KCcMwMYehe8TciUfXzA62g==/base.apk!libchilkat.so (offset 0xc4000) (BuildId: ceb579f3889717d2c8ae2ef5d22e17d6391eaab9) #02 pc 00357054  /data/app/~~cJ2uq7xVy9POOEsEnUdOcA==/com.chilkattest-KCcMwMYehe8TciUfXzA62g==/base.apk!libchilkat.so (offset 0xc4000) (CkPdf::LoadFile(char const*)+128) (BuildId: ceb579f3889717d2c8ae2ef5d22e17d6391eaab9) #03 pc 0029f565  /data/app/~~cJ2uq7xVy9POOEsEnUdOcA==/com.chilkattest-KCcMwMYehe8TciUfXzA62g==/base.apk!libchilkat.so (offset 0xc4000) (Java_com_chilkatsoft_chilkatJNI_CkPdf_1LoadFile+69) (BuildId: ceb579f3889717d2c8ae2ef5d22e17d6391eaab9) #11 pc 0007a62c  /data/data/com.chilkattest/code_cache/.overlay/base.apk/classes3.dex (com.chilkatsoft.CkPdf.LoadFile+4) #14 pc 00043458  /data/data/com.chilkattest/code_cache/.overlay/base.apk/classes3.dex (com.chilkattest.MainActivity.signPDF+20) #17 pc 000433c8  /data/data/com.chilkattest/code_cache/.overlay/base.apk/classes3.dex (com.chilkattest.MainActivity.onCreate+380)

From what I have researched, It might be about memory.

The code that I use is on based on https://www.example-code.com/android/sign_pdf_simple.asp

Is anyone has encountered this error and find any solutions, please help?

I've tried on emulator and physical device. The application always crash.


问:
SAP B1 HANA systemctl Exec format error when trying to run service

Suddenly our SAP B1 running on HANA (SuSE Linux) not working, which is very weird. But after checking some possible issue, we found this error.

sapb1servertools.service: Failed at step EXEC spawning /etc/init.d/sapb1servertools: Exec format error
The error number returned by this process is 8

See image. We cannot re-install the B1 since we have so many applications that connected to it. What else we can do for the issue?


问:
SSRS Web Service with PowerShell: Get a list of users of an SSRS server
I am currently writing a PowerShell script which involves getting a list of SSRS server users. While making an SQL query directly to the SSRS database is very simple:

```<code>SELECT UserName from dbo.Users
</code>```

I am afraid this does not apply to my current context.

Is it possible to use SSRS web service to do the same thing as that SQL statement? Please advice.

```<code>$reportServerUrl = "http://localhost/ReportServer/ReportService2010.asmx?wsdl";
$ssrs = New-WebServiceProxy -Uri "$reportServerUrl" -UseDefaultCredential;
# Get a list of users
</code>```

Body:
I am currently writing a PowerShell script which involves getting a list of SSRS server users. While making an SQL query directly to the SSRS database is very simple:

SELECT UserName from dbo.Users

I am afraid this does not apply to my current context.

Is it possible to use SSRS web service to do the same thing as that SQL statement? Please advice.

$reportServerUrl = "http://localhost/ReportServer/ReportService2010.asmx?wsdl";
$ssrs = New-WebServiceProxy -Uri "$reportServerUrl" -UseDefaultCredential;
# Get a list of users


问:
Elastic Bean Stalk - Memory Issue
I have a NodeJs application. I want to deploy it on an elastic beanstalk. But the issue is when I am using t2.medium, t2.micro, or t2.small machine fails to deploy but when I use t2.large code will deploy. I am not getting an idea of why this issue is creating also when I request the log after deployment. It will take too much time and sometimes request fails. Can anyone tell me what is the issue? My application does not have any issues It is already running on Heroku.</p>

Title: Elastic Bean Stalk - Memory Issue


问:
wrap not sending widgets to next line
In flutter, I have this Widget :

```<code> Wrap(
                    runSpacing: 5.0,
                    spacing: 5.0,
                    children: GenerateSimilarInterests.generate(
                        compareTo: user!,
                        localUser: (BlocProvider.of<ProfileBloc>
                          (context).state
                        as ProfileLoaded)
                            .user),
                  ),
</code>```

And it's looking like this:

As you can see, a person icon is going off of the widget. Is there any way to fix this?

Thanks!

Title: wrap not sending widgets to next line

Body:
In flutter, I have this Widget :

 Wrap(
                    runSpacing: 5.0,
                    spacing: 5.0,
                    children: GenerateSimilarInterests.generate(
                        compareTo: user!,
                        localUser: (BlocProvider.of<ProfileBloc>
                          (context).state
                        as ProfileLoaded)
                            .user),
                  ),

And it's looking like this:

As you can see, a person icon is going off of the widget. Is there any way to fix this?

Thanks!


问:
R rtools failed to install(build) old archived mongolite_1.6.tar.gz
I want to install mongodb in R.
Since our production system is using old mongodb, the new R mongolite version couldn't get connect.
So I decide to install the old version from archive.

However, my win10 using R 4.2.1 faced 1 critical errors

I already downloaded archived package mongolite_1.6.tar.gz from mongo archive link

I run the command: (the first argument need to be replaced by your downloaded location of file)

```<code>install.packages("~/mongolite_1.6.tar.gz", repos = NULL)
</code>```

Then I got error message:

```<code>    gcc -shared -s -static-libgcc -o mongolite.dll tmp.def bson.o client.o collection.o cursor.o gridfs.o hex.o mongo_log.o reader.o utils.o -L. -L../windows/openssl-1.1.0f/lib/x64 -Lmongoc -lstatmongoc -Lbson -lstatbson -lssl -lcrypto -lcrypto -lgdi32 -lcrypt32 -lws2_32 -lsecur32 -ldnsapi -lz -Lc:/rtools42/x86_64-w64-mingw32.static.posix/lib/x64 -Lc:/rtools42/x86_64-w64-mingw32.static.posix/lib -LD:/R/R-42~1.1/bin/x64 -lR
C:\rtools42\x86_64-w64-mingw32.static.posix\bin/ld.exe: ../windows/openssl-1.1.0f/lib/x64/libcrypto.a(pem_lib.o):pem_lib.c:(.text+0xfd): undefined reference to `__imp___iob_func'
C:\rtools42\x86_64-w64-mingw32.static.posix\bin/ld.exe: ../windows/openssl-1.1.0f/lib/x64/libcrypto.a(eng_openssl.o):eng_openssl.c:(.text+0xb): undefined reference to `__imp___iob_func'
C:\rtools42\x86_64-w64-mingw32.static.posix\bin/ld.exe: ../windows/openssl-1.1.0f/lib/x64/libcrypto.a(eng_openssl.o):eng_openssl.c:(.text+0x18f): undefined reference to `__imp___iob_func'
C:\rtools42\x86_64-w64-mingw32.static.posix\bin/ld.exe: ../windows/openssl-1.1.0f/lib/x64/libcrypto.a(ui_openssl.o):ui_openssl.c:(.text+0x19): undefined reference to `__imp___iob_func'
C:\rtools42\x86_64-w64-mingw32.static.posix\bin/ld.exe: ../windows/openssl-1.1.0f/lib/x64/libcrypto.a(ui_openssl.o):ui_openssl.c:(.text+0x782): undefined reference to `__imp___iob_func'
C:\rtools42\x86_64-w64-mingw32.static.posix\bin/ld.exe: ../windows/openssl-1.1.0f/lib/x64/libcrypto.a(ui_openssl.o):ui_openssl.c:(.text+0x7a2): more undefined references to `__imp___iob_func' follow
collect2.exe: error: ld returned 1 exit status
no DLL was created
</code>```

My sessionInfo()

```<code>R version 4.2.1 (2022-06-23 ucrt)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 19044)

Matrix products: default

locale:
[1] LC_COLLATE=Chinese (Simplified)_China.utf8  LC_CTYPE=Chinese (Simplified)_China.utf8    LC_MONETARY=Chinese (Simplified)_China.utf8
[4] LC_NUMERIC=C                                LC_TIME=Chinese (Simplified)_China.utf8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] Rcpp_1.0.9     jsonlite_1.8.0

loaded via a namespace (and not attached):
 [1] digest_0.6.29     magrittr_2.0.3    evaluate_0.15     rlang_1.0.4       cli_3.3.0         rstudioapi_0.13   DT_0.23           rmarkdown_2.14
 [9] tools_4.2.1       htmlwidgets_1.5.4 xfun_0.31         yaml_2.3.5        fastmap_1.1.0     compiler_4.2.1    htmltools_0.5.2   knitr_1.39
</code>```

Body:
I want to install mongodb in R.
Since our production system is using old mongodb, the new R mongolite version couldn't get connect.
So I decide to install the old version from archive.

However, my win10 using R 4.2.1 faced 1 critical errors

I already downloaded archived package mongolite_1.6.tar.gz from mongo archive link

I run the command: (the first argument need to be replaced by your downloaded location of file)

install.packages("~/mongolite_1.6.tar.gz", repos = NULL)

Then I got error message:

    gcc -shared -s -static-libgcc -o mongolite.dll tmp.def bson.o client.o collection.o cursor.o gridfs.o hex.o mongo_log.o reader.o utils.o -L. -L../windows/openssl-1.1.0f/lib/x64 -Lmongoc -lstatmongoc -Lbson -lstatbson -lssl -lcrypto -lcrypto -lgdi32 -lcrypt32 -lws2_32 -lsecur32 -ldnsapi -lz -Lc:/rtools42/x86_64-w64-mingw32.static.posix/lib/x64 -Lc:/rtools42/x86_64-w64-mingw32.static.posix/lib -LD:/R/R-42~1.1/bin/x64 -lR
C:\rtools42\x86_64-w64-mingw32.static.posix\bin/ld.exe: ../windows/openssl-1.1.0f/lib/x64/libcrypto.a(pem_lib.o):pem_lib.c:(.text+0xfd): undefined reference to `__imp___iob_func'
C:\rtools42\x86_64-w64-mingw32.static.posix\bin/ld.exe: ../windows/openssl-1.1.0f/lib/x64/libcrypto.a(eng_openssl.o):eng_openssl.c:(.text+0xb): undefined reference to `__imp___iob_func'
C:\rtools42\x86_64-w64-mingw32.static.posix\bin/ld.exe: ../windows/openssl-1.1.0f/lib/x64/libcrypto.a(eng_openssl.o):eng_openssl.c:(.text+0x18f): undefined reference to `__imp___iob_func'
C:\rtools42\x86_64-w64-mingw32.static.posix\bin/ld.exe: ../windows/openssl-1.1.0f/lib/x64/libcrypto.a(ui_openssl.o):ui_openssl.c:(.text+0x19): undefined reference to `__imp___iob_func'
C:\rtools42\x86_64-w64-mingw32.static.posix\bin/ld.exe: ../windows/openssl-1.1.0f/lib/x64/libcrypto.a(ui_openssl.o):ui_openssl.c:(.text+0x782): undefined reference to `__imp___iob_func'
C:\rtools42\x86_64-w64-mingw32.static.posix\bin/ld.exe: ../windows/openssl-1.1.0f/lib/x64/libcrypto.a(ui_openssl.o):ui_openssl.c:(.text+0x7a2): more undefined references to `__imp___iob_func' follow
collect2.exe: error: ld returned 1 exit status
no DLL was created

My sessionInfo()

R version 4.2.1 (2022-06-23 ucrt)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 19044)

Matrix products: default

locale:
[1] LC_COLLATE=Chinese (Simplified)_China.utf8  LC_CTYPE=Chinese (Simplified)_China.utf8    LC_MONETARY=Chinese (Simplified)_China.utf8
[4] LC_NUMERIC=C                                LC_TIME=Chinese (Simplified)_China.utf8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] Rcpp_1.0.9     jsonlite_1.8.0

loaded via a namespace (and not attached):
 [1] digest_0.6.29     magrittr_2.0.3    evaluate_0.15     rlang_1.0.4       cli_3.3.0         rstudioapi_0.13   DT_0.23           rmarkdown_2.14
 [9] tools_4.2.1       htmlwidgets_1.5.4 xfun_0.31         yaml_2.3.5        fastmap_1.1.0     compiler_4.2.1    htmltools_0.5.2   knitr_1.39


问:
Preprocessing of own handwritten numbers in machine learning
Denoising Autoencoder was created to remove noise from noisy handwritten numbers.

Next, I would like to input noisy handwritten numbers that I have prepared myself into the model I created and remove the noise. I have written code to do this, but it does not generate any errors and does not display the image after noise removal.

The following Denoising Autoencoder was created to remove noise from noisy handwritten numbers.

from keras.datasets import mnist
import numpy as np
import matplotlib.pyplot as plt
import keras
from keras import layers
from keras.callbacks import TensorBoard

(x_train, _), (x_test, _) = mnist.load_data()

x_train = x_train.astype('float32') / 255.
x_test = x_test.astype('float32') / 255.
x_train = np.reshape(x_train, (len(x_train), 28, 28, 1))
x_test = np.reshape(x_test, (len(x_test), 28, 28, 1))

noise_factor = 0.5
x_train_noisy = x_train + noise_factor * np.random.normal(loc=0.0, scale=1.0, size=x_train.shape)
x_test_noisy = x_test + noise_factor * np.random.normal(loc=0.0, scale=1.0, size=x_test.shape)

x_train_noisy = np.clip(x_train_noisy, 0., 1.)
x_test_noisy = np.clip(x_test_noisy, 0., 1.)

input_img = keras.Input(shape=(28, 28, 1))

x = layers.Conv2D(32, (3, 3), activation='relu', padding='same')(input_img)
x = layers.MaxPooling2D((2, 2), padding='same')(x)
x = layers.Conv2D(32, (3, 3), activation='relu', padding='same')(x)
encoded = layers.MaxPooling2D((2, 2), padding='same')(x)

x = layers.Conv2D(32, (3, 3), activation='relu', padding='same')(encoded)
x = layers.UpSampling2D((2, 2))(x)
x = layers.Conv2D(32, (3, 3), activation='relu', padding='same')(x)
x = layers.UpSampling2D((2, 2))(x)
decoded = layers.Conv2D(1, (3, 3), activation='sigmoid', padding='same')(x)

autoencoder = keras.Model(input_img, decoded)
autoencoder.compile(optimizer='adam', loss='binary_crossentropy')

autoencoder.fit(x_train_noisy, x_train,
                epochs=25,
                batch_size=128,
                shuffle=True,
                validation_data=(x_test_noisy, x_test),
                callbacks=[TensorBoard(log_dir='/tmp/tb', histogram_freq=0, write_graph=False)])
autoencoder.save("model_number.h5")
```
<p>Next, I want to input the noisy handwritten number "noise_number1.png" that I have prepared myself, into the created model to remove the noise. I wrote the following code for this purpose, but no error occurs and the denoised image is not displayed. How can I solve this problem? Specific code would be helpful.</p>
<pre class="lang-py prettyprint-override"><code>from PIL import Image
from keras.models import load_model

img = Image.open('/content/noise_number1.png').convert('L')
img=img.resize((28,28))
img = np.array(img)
img=img.reshape(28,28,1)
autoencoder=load_model("model_number.h5")
pred = autoencoder.predict(img[np.newaxis])
</code>```

Body:
Denoising Autoencoder was created to remove noise from noisy handwritten numbers.

Next, I would like to input noisy handwritten numbers that I have prepared myself into the model I created and remove the noise. I have written code to do this, but it does not generate any errors and does not display the image after noise removal.

The following Denoising Autoencoder was created to remove noise from noisy handwritten numbers.

from keras.datasets import mnist
import numpy as np
import matplotlib.pyplot as plt
import keras
from keras import layers
from keras.callbacks import TensorBoard

(x_train, _), (x_test, _) = mnist.load_data()

x_train = x_train.astype('float32') / 255.
x_test = x_test.astype('float32') / 255.
x_train = np.reshape(x_train, (len(x_train), 28, 28, 1))
x_test = np.reshape(x_test, (len(x_test), 28, 28, 1))

noise_factor = 0.5
x_train_noisy = x_train + noise_factor * np.random.normal(loc=0.0, scale=1.0, size=x_train.shape)
x_test_noisy = x_test + noise_factor * np.random.normal(loc=0.0, scale=1.0, size=x_test.shape)

x_train_noisy = np.clip(x_train_noisy, 0., 1.)
x_test_noisy = np.clip(x_test_noisy, 0., 1.)

input_img = keras.Input(shape=(28, 28, 1))

x = layers.Conv2D(32, (3, 3), activation='relu', padding='same')(input_img)
x = layers.MaxPooling2D((2, 2), padding='same')(x)
x = layers.Conv2D(32, (3, 3), activation='relu', padding='same')(x)
encoded = layers.MaxPooling2D((2, 2), padding='same')(x)

x = layers.Conv2D(32, (3, 3), activation='relu', padding='same')(encoded)
x = layers.UpSampling2D((2, 2))(x)
x = layers.Conv2D(32, (3, 3), activation='relu', padding='same')(x)
x = layers.UpSampling2D((2, 2))(x)
decoded = layers.Conv2D(1, (3, 3), activation='sigmoid', padding='same')(x)

autoencoder = keras.Model(input_img, decoded)
autoencoder.compile(optimizer='adam', loss='binary_crossentropy')

autoencoder.fit(x_train_noisy, x_train,
                epochs=25,
                batch_size=128,
                shuffle=True,
                validation_data=(x_test_noisy, x_test),
                callbacks=[TensorBoard(log_dir='/tmp/tb', histogram_freq=0, write_graph=False)])
autoencoder.save("model_number.h5")

Next, I want to input the noisy handwritten number "noise_number1.png" that I have prepared myself, into the created model to remove the noise. I wrote the following code for this purpose, but no error occurs and the denoised image is not displayed. How can I solve this problem? Specific code would be helpful.

from PIL import Image
from keras.models import load_model

img = Image.open('/content/noise_number1.png').convert('L')
img=img.resize((28,28))
img = np.array(img)
img=img.reshape(28,28,1)
autoencoder=load_model("model_number.h5")
pred = autoencoder.predict(img[np.newaxis])


问:
What's wrong with this React Native error dependency config?
When I tried to install on ios (pod install) it shows error below:

```<code>[!] Invalid `Podfile` file: 859: unexpected token at 'TypeError: Cannot read properties of undefined (reading 'configurations')

at Object.dependencyConfig (/Users/macbookair/Desktop/Olsera/StoreMan-Mobile/node_modules/@react-native-community/cli-platform-ios/build/config/index.js:102:37)

at /Users/macbookair/Desktop/Olsera/StoreMan-Mobile/node_modules/@react-native-community/cli-config/build/loadConfig.js:47:61

at Array.reduce (<anonymous>)

at getDependencyConfig (/Users/macbookair/Desktop/Olsera/StoreMan-Mobile/node_modules/@react-native-community/cli-config/build/loadConfig.js:44:51)

at Object.get rn-fetch-blob [as rn-fetch-blob] (/Users/macbookair/Desktop/Olsera/StoreMan-Mobile/node_modules/@react-native-community/cli-config/build/loadConfig.js:99:18)

at /Users/macbookair/Desktop/Olsera/StoreMan-Mobile/node_modules/@react-native-community/cli-config/build/commands/config.js:16:51

at Array.forEach (<anonymous>)

at filterConfig (/Users/macbookair/Desktop/Olsera/StoreMan-Mobile/node_modules/@react-native-community/cli-config/build/commands/config.js:15:38)

at Object.func (/Users/macbookair/Desktop/Olsera/StoreMan-Mobile/node_modules/@react-native-community/cli-config/build/commands/config.js:27:32)

at Command.handleAction (/Users/macbookair/Desktop/Olsera/StoreMan-Mobile/node_modules/@react-native-community/cli/build/index.js:142:23)

info Run CLI with --verbose flag for more details.
</code>```

I clean react-native -cli, rm node_modules, rm package-lock.json. Nothing helps.

Body:
When I tried to install on ios (pod install) it shows error below:

[!] Invalid `Podfile` file: 859: unexpected token at 'TypeError: Cannot read properties of undefined (reading 'configurations')

at Object.dependencyConfig (/Users/macbookair/Desktop/Olsera/StoreMan-Mobile/node_modules/@react-native-community/cli-platform-ios/build/config/index.js:102:37)

at /Users/macbookair/Desktop/Olsera/StoreMan-Mobile/node_modules/@react-native-community/cli-config/build/loadConfig.js:47:61

at Array.reduce (<anonymous>)

at getDependencyConfig (/Users/macbookair/Desktop/Olsera/StoreMan-Mobile/node_modules/@react-native-community/cli-config/build/loadConfig.js:44:51)

at Object.get rn-fetch-blob [as rn-fetch-blob] (/Users/macbookair/Desktop/Olsera/StoreMan-Mobile/node_modules/@react-native-community/cli-config/build/loadConfig.js:99:18)

at /Users/macbookair/Desktop/Olsera/StoreMan-Mobile/node_modules/@react-native-community/cli-config/build/commands/config.js:16:51

at Array.forEach (<anonymous>)

at filterConfig (/Users/macbookair/Desktop/Olsera/StoreMan-Mobile/node_modules/@react-native-community/cli-config/build/commands/config.js:15:38)

at Object.func (/Users/macbookair/Desktop/Olsera/StoreMan-Mobile/node_modules/@react-native-community/cli-config/build/commands/config.js:27:32)

at Command.handleAction (/Users/macbookair/Desktop/Olsera/StoreMan-Mobile/node_modules/@react-native-community/cli/build/index.js:142:23)

info Run CLI with --verbose flag for more details.

I clean react-native -cli, rm node_modules, rm package-lock.json. Nothing helps.


问:
Webpack cant parse fake-indexeddb
I am using fake-indexeddb to unit test my indexeddb implementation in a react app. The unit test runs well.
When I run the project the webpack shows below erorr

But the build is successful in the end and everything works as intended. What should I do to get rid of this error?

Title: Webpack cant parse fake-indexeddb


问:
How to configure file on Astra Theme WordPress
Is there someone know how and where file to configure Astra themes? I mean, I want to remove specific element as shown below

I want to remove  element that link to websitedemos.net

I just try to find where the files but not yet done, and still figuring out.

Maybe someone know where it is, thanks

Remove specific element on Astra Theme WordPress


问:
pandas auto append index number at front of each line in a text file
Sorry i am still new to panda module and still learning python as well. I am trying to extract a row data by filtering a specific subscription from a cell and output to a text file and it work, but i found out each line has a random digit of index with a comma, is there something i need to add to remove the index number? Here is my code:

```<code>import pandas as pd

path = '/Users/myname/Downloads/azure_ip_addresses.csv'
df = pd.read_csv(path)
df = df[(df['Subscription Name'] == "subscription1") | (df['Subscription Name'] ==  "subscription2") | (df['Subscription Name'] ==  "subscription3") | (df['Subscription Name'] ==  "subscription4") | (df['Subscription Name'] ==  "subscription5") | (df['Subscription Name'] ==  "subscription6")]
df = df[["IP Address"]]
df.to_csv("/Users/nleong02/Downloads/result.txt")
</code>```

The output look like this:

```<code>,IP Address
26,10.1.1.1
43,10.1.1.2
48,10.1.1.3
</code>```

I tried using re.sub() or rsplit() but doesn't help much. If i can fix the indexing, i can just the rsplit("\n") again.

Body:
Sorry i am still new to panda module and still learning python as well. I am trying to extract a row data by filtering a specific subscription from a cell and output to a text file and it work, but i found out each line has a random digit of index with a comma, is there something i need to add to remove the index number? Here is my code:

import pandas as pd

path = '/Users/myname/Downloads/azure_ip_addresses.csv'
df = pd.read_csv(path)
df = df[(df['Subscription Name'] == "subscription1") | (df['Subscription Name'] ==  "subscription2") | (df['Subscription Name'] ==  "subscription3") | (df['Subscription Name'] ==  "subscription4") | (df['Subscription Name'] ==  "subscription5") | (df['Subscription Name'] ==  "subscription6")]
df = df[["IP Address"]]
df.to_csv("/Users/nleong02/Downloads/result.txt")

The output look like this:

,IP Address
26,10.1.1.1
43,10.1.1.2
48,10.1.1.3

I tried using re.sub() or rsplit() but doesn't help much. If i can fix the indexing, i can just the rsplit("\n") again.


问:
Category 4 data based on the number range
Use case: The number of rows will be dynamic each time. I will need to assign the category based on the range of number.

I know the formula for Excel and do it one by one:

```<code>=IF(A2>90,"High",IF(A2>60,"Medium","Low"))
</code>```

I will like to add this in VBA with a loop

I can get it going for one by one but i will like to assign a value so it will go into a loop.

step 1) find out how many actual value within one column

step 2) each cell will have a value and assign a tag based on the range (either A, B, C or D)

step 3) add the tag result back the spreadsheet adjacent to the original row

Body:
Use case: The number of rows will be dynamic each time. I will need to assign the category based on the range of number.

I know the formula for Excel and do it one by one:

=IF(A2>90,"High",IF(A2>60,"Medium","Low"))

I will like to add this in VBA with a loop

I can get it going for one by one but i will like to assign a value so it will go into a loop.

step 1) find out how many actual value within one column

step 2) each cell will have a value and assign a tag based on the range (either A, B, C or D)

step 3) add the tag result back the spreadsheet adjacent to the original row


问:
kafka stream doesn't work in bean in spring boot
I'm a beginner with kafka stream,

when I create two sample modules one for "Order" and other is "Payment"

In the "Order" Project I use kafka to send to message to "oder-topic"
then in "Payment" I use Kafka listener to received value then send value to other topic( ex: payment-topic).

I want to use kafka Stream in "Order" module to read value from "payment-topic" I define it Order application java class in a "Order" module like this:

@SpringBootApplication

@EnableKafka

@EnableKafkaStreams

public class OrderServiceApplication {
     // this topic will received all value that were processed

    public static final String OUTPUT_TOPIC_NAME = "ordered";

    // this topic is a places received value from payment and stock send value
    public static final String INPUT_ORDER_TOPIC_NAME = "order-topic-result";

    public static final String INPUT_STOCK_TOPIC_NAME = "stock-topic-result";

    public static void main(String[] args) {
        SpringApplication.run (OrderServiceApplication.class, args);
    }

    @Bean
    public KStream <String, String> readStream (StreamsBuilder kStreamBuilder) {

        KStream <String, String> input = kStreamBuilder.stream(INPUT_ORDER_TOPIC_NAME);

        KStream<String, String> output = input.filter((key, value) -> value.length() > 2);

        output.to(OUTPUT_TOPIC_NAME);

        return output;
    }
```

but the readStream does not work. Please help me

How will I execute the method is automatically after the value was send to this topic

Body:
I'm a beginner with kafka stream,

when I create two sample modules one for "Order" and other is "Payment"

In the "Order" Project I use kafka to send to message to "oder-topic"
then in "Payment" I use Kafka listener to received value then send value to other topic( ex: payment-topic).

I want to use kafka Stream in "Order" module to read value from "payment-topic" I define it Order application java class in a "Order" module like this:

@SpringBootApplication

@EnableKafka

@EnableKafkaStreams

public class OrderServiceApplication {
     // this topic will received all value that were processed

    public static final String OUTPUT_TOPIC_NAME = "ordered";

    // this topic is a places received value from payment and stock send value
    public static final String INPUT_ORDER_TOPIC_NAME = "order-topic-result";

    public static final String INPUT_STOCK_TOPIC_NAME = "stock-topic-result";

    public static void main(String[] args) {
        SpringApplication.run (OrderServiceApplication.class, args);
    }

    @Bean
    public KStream <String, String> readStream (StreamsBuilder kStreamBuilder) {

        KStream <String, String> input = kStreamBuilder.stream(INPUT_ORDER_TOPIC_NAME);

        KStream<String, String> output = input.filter((key, value) -> value.length() > 2);

        output.to(OUTPUT_TOPIC_NAME);

        return output;
    }

but the readStream does not work. Please help me

How will I execute the method is automatically after the value was send to this topic


问:
Why can a typedef not share a name with an object but a tag can?
What are the specific and applied reasons of why can a typedef not share a name with an object but a tag can? I can't help but feeling like there is some huge concept I am missing; that suggests a typedef is doing something a tag is not and merely being a synonym for an existing arrangement does not answer the question of why the difference exists.</p>
```<code>//Allowed:
struct i {int i;};
struct i i;

//Or:
struct {int i;} i;
///////////////////////////////
//Not allowed:
typedef struct i {int i;} i;
i i;

//Nor:
typedef struct {int i;} i;
i i;
</code>```

Body:
What are the specific and applied reasons of why can a typedef not share a name with an object but a tag can? I can't help but feeling like there is some huge concept I am missing; that suggests a typedef is doing something a tag is not and merely being a synonym for an existing arrangement does not answer the question of why the difference exists.

//Allowed:
struct i {int i;};
struct i i;

//Or:
struct {int i;} i;
///////////////////////////////
//Not allowed:
typedef struct i {int i;} i;
i i;

//Nor:
typedef struct {int i;} i;
i i;


问:
Setting up Linaria with Next.js for SSR pages
I am using "linaria": "^4.1.10" and "next-linaria": "^0.11.0" in my Next.js app. I have followed the configuration on this repo. In my app the pages which are not using getServerSideProps are working fine with above configuration, but the pages having SSR approach are not working fine.

Errors such as
Cannot read properties of undefined (reading 'localeCompare'),
EvalError: Cannot read properties of null (reading 'spawn')
comes up in the SSR components during build time.

Any help with the setup of Linaria with Next.js for SSR pages will be amazing to have. Or if you guys can point me to the correct docs.

I have tried the other setup on the Linaria docs, I have also tried the Next.js Example for Linaria.

Nothing seems to work for me.


问:
Python Context Manager for releasing memory
Hi guys I have a quick question about python context manager.

How do I create a context manager where it will release all memory from an array or list? Is it even possible to do something like that?

Say I have the array

```<code>b = [1, 2, 3, 4]
</code>```

We can certainly use clear or del to clear/delete the array but it will still be there in memory. And then we can use gc.collect() to clear it from memory.

```<code>class FileManager():
    def __init__(self, filename, mode):
        self.filename = filename
        self.mode = mode
        self.file = None

    def __enter__(self):
        self.file = open(self.filename, self.mode)
        return self.file

    def __exit__(self, exc_type, exc_value, exc_traceback):
        self.file.close()

with FileManager('test.txt', 'w') as f:
    f.write('Test')
</code>```

But is it possible to create a context manager class to do this? I know they are usually used for file management as I wrote the code above...just wondering how else to use context manager

Body:
Hi guys I have a quick question about python context manager.

How do I create a context manager where it will release all memory from an array or list? Is it even possible to do something like that?

Say I have the array

b = [1, 2, 3, 4]

We can certainly use clear or del to clear/delete the array but it will still be there in memory. And then we can use gc.collect() to clear it from memory.

class FileManager():
    def __init__(self, filename, mode):
        self.filename = filename
        self.mode = mode
        self.file = None

    def __enter__(self):
        self.file = open(self.filename, self.mode)
        return self.file

    def __exit__(self, exc_type, exc_value, exc_traceback):
        self.file.close()

with FileManager('test.txt', 'w') as f:
    f.write('Test')

But is it possible to create a context manager class to do this? I know they are usually used for file management as I wrote the code above...just wondering how else to use context manager


问:
Unreal Engine 5.1 does not compile with CppStandard set to c++20
In a fresh "Blank" project setting "CppStandard = CppStandardVersion.Cpp20;" in "*.Build.cs" leads to compile errors:

0>/opt/unreal-engine/Engine/Source/Runtime/Core/Public/Math/SHMath.h:39:38: Error  : arithmetic between different enumeration types ('TSHVector<2>::(unnamed enum at Runtime/Core/Public/Math/SHMath.h:37:2)' and 'TSHVector<2>::(unnamed enum at Runtime/Core/Public/Math/SHMath.h:38:2)') is deprecated [-Werror,-Wdeprecated-anon-enum-enum-conversion]
enum { NumSIMDVectors = (MaxSHBasis + NumComponentsPerSIMDVector - 1) / NumComponentsPerSIMDVector };
~~~~~~~~~~ ^ ~~~~~~~~~~~~~~~~~~~~~~~~~~
0>/opt/unreal-engine/Engine/Source/Runtime/Core/Public/Math/SHMath.h:460:21: Reference  : in instantiation of template class 'TSHVector<2>' requested here
inline TSHVector<2> TSHVector<2>::SHBasisFunction(const FVector& Vector)

I tried to disable warnings as errors in the "*.Build.cs" file and in the "BuildConfig.xml" with no success. How to build Unreal Engine 5.1 with c++20 standard?

Additional Information:

I am on Linux.

I use JetBrains Rider.

I did not build from sources.


问:
how to do with joblib that multiprocessing inside multiprocessing？
is it workable to do multiprocessing inside multiprocessing with joblib?
such as:

```<code>def func1():
    Parallel(func2)
def func2():
    Parallel(func3)
def func3():
    Parallel(func4)
def func4():
    do something
</code>```

i am doing a heavy computaion with joblib Parallel, some subprocess are time-consuming than others so it could be hang there for quite a time, and i am not sure this situation is proper for multiprocessing. if so, what is the best way to do that?

Body:
is it workable to do multiprocessing inside multiprocessing with joblib?
such as:

def func1():
    Parallel(func2)
def func2():
    Parallel(func3)
def func3():
    Parallel(func4)
def func4():
    do something

i am doing a heavy computaion with joblib Parallel, some subprocess are time-consuming than others so it could be hang there for quite a time, and i am not sure this situation is proper for multiprocessing. if so, what is the best way to do that?


问:
Elasticsearch field conversion on runtime
I have a field in elasticsearch that contains values like this:

```<code>"my_field" : """[{"name": "abcd", "type": "xyz",
"company": "test company", "order_id": 1, "designation": "CEO"}]"""

</code>```

and mapping looks like this:

```<code>{
  "my_test_index" : {
    "mappings" : {
      "my_field" : {
        "full_name" : "my_field",
        "mapping" : {
          "my_field" : {
            "type" : "text",
            "fields" : {
              "keyword" : {
                "type" : "keyword",
                "ignore_above" : 256
              }
            }
          }
        }
      }
    }
  }
}
</code>```

I am fairly new to ES and wanted to check is there any way I can change the field to look like an array on runtime i.e. remove triple quotes so I can do some aggregations on it?

Appreciate any kind of help here. Thanks in advance.

Body:
I have a field in elasticsearch that contains values like this:

"my_field" : """[{"name": "abcd", "type": "xyz",
"company": "test company", "order_id": 1, "designation": "CEO"}]"""

and mapping looks like this:

{
  "my_test_index" : {
    "mappings" : {
      "my_field" : {
        "full_name" : "my_field",
        "mapping" : {
          "my_field" : {
            "type" : "text",
            "fields" : {
              "keyword" : {
                "type" : "keyword",
                "ignore_above" : 256
              }
            }
          }
        }
      }
    }
  }
}

I am fairly new to ES and wanted to check is there any way I can change the field to look like an array on runtime i.e. remove triple quotes so I can do some aggregations on it?

Appreciate any kind of help here. Thanks in advance.


问:
How can rust safely drop a cpp array through FFI?
I have a array T* which is created like the following

```<code>T* array = new T[len];
// Some initialization codes
</code>```

We know we can delete the array like

```<code>delete [] array;
</code>```

However, I am writing a Rust FFI program with C++. I have sent this array pointer to the Rust part of my code, and I want to delete the code now.

So I can implement a function ffi_delete_array_of_T on the C++ part, and the Rust part code will call the function through FFI, attached with the argument array.

```<code>void ffi_delete_array_of_T(void * arr) {
    delete [] reinterpret_cast<T *>(arr);
}
</code>```

However, I already have a function which can delete single element of T.

```<code>void ffi_delete_pointer_of_T(void * arr) {
    delete reinterpret_cast<T *>(arr);
}
</code>```

These two functions are so similar that I wonder if I can combined them into one, so I don't need to write two copy.

```<code>void ffi_delete_whatever_of_T(void * arr, bool is_array) {
    if (is_array)
        delete [] reinterpret_cast<T *>(arr);
    else
        delete reinterpret_cast<T *>(arr);
}
</code>```

However, I still think the above codes redundant. I wonder if I only give ffi_delete_pointer_of_T, is it possible the Rust do some magic, and have ffi_delete_array_of_T for me?

To the best of my knowledge, it is not possible. C++ can delete [] a array without hint of length, because it has already stored the length of array somewhere when array is allocated. However, the Rust part don't know the actual length of this array.

However, I still wonder if there are some other ways to do that?

Body:
I have a array T* which is created like the following

T* array = new T[len];
// Some initialization codes

We know we can delete the array like

delete [] array;

However, I am writing a Rust FFI program with C++. I have sent this array pointer to the Rust part of my code, and I want to delete the code now.

So I can implement a function ffi_delete_array_of_T on the C++ part, and the Rust part code will call the function through FFI, attached with the argument array.

void ffi_delete_array_of_T(void * arr) {
    delete [] reinterpret_cast<T *>(arr);
}

However, I already have a function which can delete single element of T.

void ffi_delete_pointer_of_T(void * arr) {
    delete reinterpret_cast<T *>(arr);
}

These two functions are so similar that I wonder if I can combined them into one, so I don't need to write two copy.

void ffi_delete_whatever_of_T(void * arr, bool is_array) {
    if (is_array)
        delete [] reinterpret_cast<T *>(arr);
    else
        delete reinterpret_cast<T *>(arr);
}

However, I still think the above codes redundant. I wonder if I only give ffi_delete_pointer_of_T, is it possible the Rust do some magic, and have ffi_delete_array_of_T for me?

To the best of my knowledge, it is not possible. C++ can delete [] a array without hint of length, because it has already stored the length of array somewhere when array is allocated. However, the Rust part don't know the actual length of this array.

However, I still wonder if there are some other ways to do that?


问:
Class 'Public_Controller' not found in codeigniter
Same code is run properly in localhost but on server its show error
An uncaught Exception was encountered
Type: Error

Message: Class 'Public_Controller' not found

Filename: /home/referralearn/public_html/techmaa.org/portal/application/controllers/Auth.php

Line Number: 4

Backtrace:

File: /home/referralearn/public_html/techmaa.org/portal/index.php
Line: 314
Function: require_once

help me to solve this


问:
Defined variable in shiny app is not defined
I am trying to use the variable Z in my shiny app, but it says the variable doesn't exist. I clearly defined it a few lines above the lme call. Does anyone know why the value of Z is not preserved?

```<code>#
# This is a Shiny web application. You can run the application by clicking
# the 'Run App' button above.
#
# Find out more about building applications with Shiny here:
#
#    http://shiny.rstudio.com/
#

library(shiny)
library(nlme)

# Define UI for application that draws a histogram

ui = fluidPage(
  titlePanel("Use csv"),
  sidebarLayout(
    sidebarPanel(
      fileInput('file1', 'Choose csv file',
                accept = c(".csv")
      ),
      sliderInput("p",
                  "p:",
                  min = -2,
                  max = 3,
                  value = 1),
      sliderInput("q",
                  "q:",
                  min = -2,
                  max = 3,
                  value = 2),
    ),

    mainPanel(
      plotOutput('sscPlot')
    )
  )
)

server = function(input, output){

  output$sscPlot<-renderPlot({
    inFile <- input$file1

    if(is.null(inFile))
      return(NULL)
    file.rename(inFile$datapath,
                paste(inFile$datapath, ".csv", sep=""))
    df=read.csv(paste(inFile$datapath, ".csv", sep=""), 1)

    visit=df$visit
    K=round(length(unique(visit))/4)
    knots=quantile(unique(visit), seq(0.05, 0.95, length=K))
    Z=outer(visit,knots,"-")
    Z=Z*(Z>0)

    model=lme(data=df, y ~ group + visit, random=list(group=pdIdent(~Z+-1), id=~1))

    plot(1:10)
  })
}

# Run the application
shinyApp(ui = ui, server = server)
</code>```

Error message: Warning: Error in eval: object 'Z' not found

Example data that you can turn into a csv file to try:

```<code>structure(list(id = c(101, 102, 102, 103, 103, 103, 104, 104,
104, 104, 104, 105, 105, 105, 105, 105, 106, 106, 106, 106, 106,
107, 107, 107, 107, 107, 108, 108, 108, 108), visit = c(0, 0,
4, 0, 28, 27, 0, 20, 19, 15, 6, 0, 12, 29, 27, 14, 0, 15, 1,
26, 5, 0, 9, 28, 19, 3, 0, 19, 4, 6), y = c(-1, -1, -1, -1, 0,
0, -1, 0, -1, 0, 1, -1, 1, 0, 1, 0, -1, -1, -1, 0, -1, -1, -1,
1, -1, 0, -1, 0, 0, 1), group = structure(c(1L, 2L, 2L, 2L, 2L,
2L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L,
2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L), .Label = c("0", "1"), class = "factor")), row.names = c(NA,
-30L), class = c("tbl_df", "tbl", "data.frame"))
</code>```

Body:
I am trying to use the variable Z in my shiny app, but it says the variable doesn't exist. I clearly defined it a few lines above the lme call. Does anyone know why the value of Z is not preserved?

#
# This is a Shiny web application. You can run the application by clicking
# the 'Run App' button above.
#
# Find out more about building applications with Shiny here:
#
#    http://shiny.rstudio.com/
#

library(shiny)
library(nlme)

# Define UI for application that draws a histogram

ui = fluidPage(
  titlePanel("Use csv"),
  sidebarLayout(
    sidebarPanel(
      fileInput('file1', 'Choose csv file',
                accept = c(".csv")
      ),
      sliderInput("p",
                  "p:",
                  min = -2,
                  max = 3,
                  value = 1),
      sliderInput("q",
                  "q:",
                  min = -2,
                  max = 3,
                  value = 2),
    ),

    mainPanel(
      plotOutput('sscPlot')
    )
  )
)

server = function(input, output){

  output$sscPlot<-renderPlot({
    inFile <- input$file1

    if(is.null(inFile))
      return(NULL)
    file.rename(inFile$datapath,
                paste(inFile$datapath, ".csv", sep=""))
    df=read.csv(paste(inFile$datapath, ".csv", sep=""), 1)

    visit=df$visit
    K=round(length(unique(visit))/4)
    knots=quantile(unique(visit), seq(0.05, 0.95, length=K))
    Z=outer(visit,knots,"-")
    Z=Z*(Z>0)

    model=lme(data=df, y ~ group + visit, random=list(group=pdIdent(~Z+-1), id=~1))

    plot(1:10)
  })
}

# Run the application
shinyApp(ui = ui, server = server)

Error message: Warning: Error in eval: object 'Z' not found

Example data that you can turn into a csv file to try:

structure(list(id = c(101, 102, 102, 103, 103, 103, 104, 104,
104, 104, 104, 105, 105, 105, 105, 105, 106, 106, 106, 106, 106,
107, 107, 107, 107, 107, 108, 108, 108, 108), visit = c(0, 0,
4, 0, 28, 27, 0, 20, 19, 15, 6, 0, 12, 29, 27, 14, 0, 15, 1,
26, 5, 0, 9, 28, 19, 3, 0, 19, 4, 6), y = c(-1, -1, -1, -1, 0,
0, -1, 0, -1, 0, 1, -1, 1, 0, 1, 0, -1, -1, -1, 0, -1, -1, -1,
1, -1, 0, -1, 0, 0, 1), group = structure(c(1L, 2L, 2L, 2L, 2L,
2L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L,
2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L), .Label = c("0", "1"), class = "factor")), row.names = c(NA,
-30L), class = c("tbl_df", "tbl", "data.frame"))


问:
Email form in PHP form = infinite
already lost all day trying to figure this out but couldn't. I know that running multiple forms in a php loops is problematic so I've tried foreach and while operations with no success. This form should be in each article box so users can report a problem with such article and I get instant emails from it. The problem is that on click sends an email for all articles listed in the page and not only to the single article submit user clicked:

```<code><form action="" method="post">
<input type="submit" value="Report" />
<input type="hidden" name="adid" value="<?php echo osc_item_id(); ?>" />
</form>

<?php

if(isset($_POST['adid']))
{
    $to      = 'email@example.com';
    $subject = 'the subject';
    $message = 'hello';
    $headers = 'From: email@example.com' . "\r\n" .
        'Reply-To: ' . $useremail . '' . "\r\n" .
        'X-Mailer: PHP/' . phpversion();

    mail($to, $subject, $message, $headers);

    echo 'Email sent to (' . $useremail . ')';
}

?>
</code>```

I can get to add a dynamic value to "adid" the problem is after at $_POST don't know how to call that dynamic value. Tried foreach which I think is the way to go but couldn't find a code that I can adapt since I'm not a PHP pro. Hope someone can help me out...

Title: Email form in PHP form = infinite

Body:
already lost all day trying to figure this out but couldn't. I know that running multiple forms in a php loops is problematic so I've tried foreach and while operations with no success. This form should be in each article box so users can report a problem with such article and I get instant emails from it. The problem is that on click sends an email for all articles listed in the page and not only to the single article submit user clicked:

<form action="" method="post">
<input type="submit" value="Report" />
<input type="hidden" name="adid" value="<?php echo osc_item_id(); ?>" />
</form>

<?php

if(isset($_POST['adid']))
{
    $to      = 'email@example.com';
    $subject = 'the subject';
    $message = 'hello';
    $headers = 'From: email@example.com' . "\r\n" .
        'Reply-To: ' . $useremail . '' . "\r\n" .
        'X-Mailer: PHP/' . phpversion();

    mail($to, $subject, $message, $headers);

    echo 'Email sent to (' . $useremail . ')';
}

?>

I can get to add a dynamic value to "adid" the problem is after at $_POST don't know how to call that dynamic value. Tried foreach which I think is the way to go but couldn't find a code that I can adapt since I'm not a PHP pro. Hope someone can help me out...


问:
Function pointer syntax query
I was learning function pointer. I faced one syntax error.
I have implemented sort with comparison function as an additonal arguement.

```<code>// working fine
#include<iostream>
using namespace std;
typedef int (*C_MP)(double d);
template<typename X>
X* sort(X* start, X* last,X size, bool (*comp)(X,X)){
    for(int i=0;i<size;i++){
        for(int j=1;j<size;j++){
            X x=*(start+j-1);
            X y=*(start + j);
            if(!(*comp)(x,y)){
                cout<<i<<" "<<x<<" "<<y<<endl;
                swap(start[j],start[j-1]);
            }
        }
    }
    return start;
}

int fun(double x){
    return x;
}
bool comp(float x, float y){
    if(x>y){
        return 0;
    }
    return 1;
}
int main(){
   C_MP x = fun;
   cout<<(*x)(10)<<endl;
   float arr[] = {2.1,3.2,6.3,8.4,1.9,0.3};
   float* narr = sort<float>(&arr[0],&arr[5],6,&comp);
   for(int i=0;i<6;i++){
    cout<<*(narr+i)<<endl;
   }
}
}
</code>```

In sort function definition, when I remove brackets from the comp it gives compilation error. I just wanted why this bracket is neccessary or is it just an syntax we need to remember and there is no logic behind it or compiler is confusing it with something else? please give some insights. Function pointers are also used in callbacks. Can you give some small idea/project ,if possible,  where  I can implement callbacks using function pointer.

```<code>// Give compilation error
#include<iostream>
using namespace std;
typedef int (*C_MP)(double d);
template<typename X>
X* sort(X* start, X* last,X size, bool *comp(X,X)){
    for(int i=0;i<size;i++){
        for(int j=1;j<size;j++){
            X x=*(start+j-1);
            X y=*(start + j);
            if(!(*comp)(x,y)){
                cout<<i<<" "<<x<<" "<<y<<endl;
                swap(start[j],start[j-1]);
            }
        }
    }
    return start;
}

int fun(double x){
    return x;
}
bool comp(float x, float y){
    if(x>y){
        return 0;
    }
    return 1;
}
int main(){
   C_MP x = fun;
   cout<<(*x)(10)<<endl;
   float arr[] = {2.1,3.2,6.3,8.4,1.9,0.3};
   float* narr = sort<float>(&arr[0],&arr[5],6,&comp);
   for(int i=0;i<6;i++){
    cout<<*(narr+i)<<endl;
   }
}
</code>```

I tried using if similar question existed. I didn't found anything.

Title: Function pointer syntax query

Body:
I was learning function pointer. I faced one syntax error.
I have implemented sort with comparison function as an additonal arguement.

// working fine
#include<iostream>
using namespace std;
typedef int (*C_MP)(double d);
template<typename X>
X* sort(X* start, X* last,X size, bool (*comp)(X,X)){
    for(int i=0;i<size;i++){
        for(int j=1;j<size;j++){
            X x=*(start+j-1);
            X y=*(start + j);
            if(!(*comp)(x,y)){
                cout<<i<<" "<<x<<" "<<y<<endl;
                swap(start[j],start[j-1]);
            }
        }
    }
    return start;
}

int fun(double x){
    return x;
}
bool comp(float x, float y){
    if(x>y){
        return 0;
    }
    return 1;
}
int main(){
   C_MP x = fun;
   cout<<(*x)(10)<<endl;
   float arr[] = {2.1,3.2,6.3,8.4,1.9,0.3};
   float* narr = sort<float>(&arr[0],&arr[5],6,&comp);
   for(int i=0;i<6;i++){
    cout<<*(narr+i)<<endl;
   }
}
}

In sort function definition, when I remove brackets from the comp it gives compilation error. I just wanted why this bracket is neccessary or is it just an syntax we need to remember and there is no logic behind it or compiler is confusing it with something else? please give some insights. Function pointers are also used in callbacks. Can you give some small idea/project ,if possible,  where  I can implement callbacks using function pointer.

// Give compilation error
#include<iostream>
using namespace std;
typedef int (*C_MP)(double d);
template<typename X>
X* sort(X* start, X* last,X size, bool *comp(X,X)){
    for(int i=0;i<size;i++){
        for(int j=1;j<size;j++){
            X x=*(start+j-1);
            X y=*(start + j);
            if(!(*comp)(x,y)){
                cout<<i<<" "<<x<<" "<<y<<endl;
                swap(start[j],start[j-1]);
            }
        }
    }
    return start;
}

int fun(double x){
    return x;
}
bool comp(float x, float y){
    if(x>y){
        return 0;
    }
    return 1;
}
int main(){
   C_MP x = fun;
   cout<<(*x)(10)<<endl;
   float arr[] = {2.1,3.2,6.3,8.4,1.9,0.3};
   float* narr = sort<float>(&arr[0],&arr[5],6,&comp);
   for(int i=0;i<6;i++){
    cout<<*(narr+i)<<endl;
   }
}

I tried using if similar question existed. I didn't found anything.


问:
identifying which jpa mapping between customer and currentPaymentMethod
I have written a Customer class which has two fields.A Set<Payment> payments and a selectedPayment .A customer can have many credit cards and can select one of them for current purchase.The various credit cards are modelled by the payments field.

```<code>@Entity
class Customer{
  ...
  @OneToMany( cascade=CascadeType.ALL,orphanRemoval=true)
  Set<Payment> payments;
  @OneToOne( cascade=CascadeType.ALL)
  Payment selectedPayment;

}

@Entity
class Payment{
   String creditCardNumber;
   String creditCardType;
   ...
}
</code>```

Are these the correct mappings? In the db table ,a customer can only be associated with a single Payment record through selectedPayment field.That is why I made it one-to-one.

Are there any pitfalls I haven't anticipated? Please advise.

ContentLicense: CC BY-SA 3.0

Body:
I have written a Customer class which has two fields.A Set<Payment> payments and a selectedPayment .A customer can have many credit cards and can select one of them for current purchase.The various credit cards are modelled by the payments field.

@Entity
class Customer{
  ...
  @OneToMany( cascade=CascadeType.ALL,orphanRemoval=true)
  Set<Payment> payments;
  @OneToOne( cascade=CascadeType.ALL)
  Payment selectedPayment;

}

@Entity
class Payment{
   String creditCardNumber;
   String creditCardType;
   ...
}

Are these the correct mappings? In the db table ,a customer can only be associated with a single Payment record through selectedPayment field.That is why I made it one-to-one.

Are there any pitfalls I haven't anticipated? Please advise.