问:
Update azure devops release pipeline: Tasks with versions 'Deploy Plataform 3:1.*' are not valid for deploy job 'Run on agent'
I'm using Azure DevOps Services REST API 5.0 to update a pipeline release.

I have a release with a stage DEV that have two tasks in a 'Run on agent' job:

Deploy plataform 1

Deploy plataform 2

I want to add a new task 'Deploy plataform 3' using the update method from the Azure DevOps Services REST API.

But when I try to UPDATE have the error:

Tasks with versions 'Deploy Plataform 3:1.*' are not valid for deploy job 'Run on agent' in stage DEV.

I get the release definition using the url:
https://vsrm.dev.azure.com/organizationname/projectname/_apis/release/definitions/5?api-version=5.0

I add a new task in the object environments[0].deployPhases[0].workflowTasks.

Workflowtasks object with my new task:

```<code>"workflowTasks": [
    {
        "environment": {},
        "taskId": "501dd25d-1785-43e4-b4e5-a5c78ccc0573",
        "version": "1.*",
        "name": "Deploy Plataform 1",
        "refName": "",
        "enabled": true,
        "alwaysRun": false,
        "continueOnError": false,
        "timeoutInMinutes": 0,
        "definitionType": null,
        "overrideInputs": {},
        "condition": "succeeded()",
        "inputs": {
            "azureSubscription": "3ca9b800-e82b-4678-8483-xxxxx",
            "appType": "$(Parameters.AppType)",
            "appName": "app func name 1",
            "deployToSlotOrASE": "false",
            "resourceGroupName": "",
            "slotName": "production",
            "package": "$(System.DefaultWorkingDirectory)/**/*.zip",
            "runtimeStack": "",
            "startUpCommand": "",
            "customWebConfig": "",
            "appSettings": "",
            "configurationStrings": "",
            "deploymentMethod": "auto"
        }
    },
    { ...
    },
    {
        "environment": {},
        "taskId": "502dd25d-1785-43e4-b4e5-a5c78ccc0573",
        "version": "1.*",
        "name": "Deploy Plataform 3",
        "refName": "",
        "enabled": true,
        "alwaysRun": false,
        "continueOnError": false,
        "timeoutInMinutes": 0,
        "definitionType": "task",
        "overrideInputs": {},
        "condition": "succeeded()",
        "inputs": {
            "azureSubscription": "3ca9b844-e92b-4678-8483-xxxx",
            "appType": "functionApp",
            "appName": "func app name",
            "deployToSlotOrASE": "false",
            "resourceGroupName": "",
            "slotName": "production",
            "package": "$(System.DefaultWorkingDirectory)/**/*.zip",
            "runtimeStack": "",
            "startUpCommand": "",
            "customWebConfig": "",
            "appSettings": "",
            "configurationStrings": "",
            "deploymentMethod": "auto"
        }
    }
]
</code>```

PUT url: https://vsrm.dev.azure.com/{organization}/{project}/_apis/release/definitions?api-version=5.0

Error:

```<code>Invoke-RestMethod : {"$id":"1","innerException":null,"message":"Tasks with versions 'Deploy Plataform 3:1.*' are not valid for deploy job 'Run on agent' in stage DEV.
","typeName":"Microsoft.VisualStudio.Services.ReleaseManagement.Data.Exceptions.InvalidRequestException, Microsoft.VisualStudio.Services.ReleaseManagement2.Data","typeKey":"InvalidRequestException","errorCode":0,"eventId":3000}
Au caractère C:\Projects\TransportConfiguration\AutomationTasks\Build Definitions Supporting Scripts\Update-Release-Stage.ps1:49 : 9
+         Invoke-RestMethod -Uri $uri -Headers ($Header) -Method PUT -B ...
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation : (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
</code>```

Put method:

```<code>function Invoke-WebRequestPut ([PSCustomObject] $releaseDefinition) {

    $uri = "https://vsrm.dev.azure.com/organizationname/projectname/_apis/release/definitions?api-version=5.0"

    $Auth = '{0}:{1}' -f $UserName, $PersonalToken
    $Auth = [System.Text.Encoding]::UTF8.GetBytes($Auth)
    $Auth = [System.Convert]::ToBase64String($Auth)
    $Header = @{Authorization = ("Basic {0}" -f $Auth)}

    $body = $releaseDefinition | ConvertTo-Json -Depth 30

    $body2 = [System.Text.Encoding]::UTF8.GetBytes($body)

    Invoke-RestMethod -Uri $uri -Headers ($Header) -Method PUT -Body $body2 -ContentType "application/json"
}
</code>```

Using this put method I can modify an existing task name successfully (Deploy Plataform 1 => Deploy Plataform X). But can not add a new task.

This is a bug or I'm missing something.

答:
I found the problem.

The new WorkflowTask I add has a field taskId that I was trying to generate. But this taskId field corresponds to the azure pipeline task type I want to use. In my case, I need to set the azure function app task id, 501dd25d-1785-43e4-b4e5-a5c78ccc0573.

The documentation for WorkflowTask is not complete, we only have: TaskId: string

Body:
I'm using Azure DevOps Services REST API 5.0 to update a pipeline release.

I have a release with a stage DEV that have two tasks in a 'Run on agent' job:

Deploy plataform 1

Deploy plataform 2

I want to add a new task 'Deploy plataform 3' using the update method from the Azure DevOps Services REST API.

But when I try to UPDATE have the error:

Tasks with versions 'Deploy Plataform 3:1.*' are not valid for deploy job 'Run on agent' in stage DEV.

I get the release definition using the url:
https://vsrm.dev.azure.com/organizationname/projectname/_apis/release/definitions/5?api-version=5.0

I add a new task in the object environments[0].deployPhases[0].workflowTasks.

Workflowtasks object with my new task:

"workflowTasks": [
    {
        "environment": {},
        "taskId": "501dd25d-1785-43e4-b4e5-a5c78ccc0573",
        "version": "1.*",
        "name": "Deploy Plataform 1",
        "refName": "",
        "enabled": true,
        "alwaysRun": false,
        "continueOnError": false,
        "timeoutInMinutes": 0,
        "definitionType": null,
        "overrideInputs": {},
        "condition": "succeeded()",
        "inputs": {
            "azureSubscription": "3ca9b800-e82b-4678-8483-xxxxx",
            "appType": "$(Parameters.AppType)",
            "appName": "app func name 1",
            "deployToSlotOrASE": "false",
            "resourceGroupName": "",
            "slotName": "production",
            "package": "$(System.DefaultWorkingDirectory)/**/*.zip",
            "runtimeStack": "",
            "startUpCommand": "",
            "customWebConfig": "",
            "appSettings": "",
            "configurationStrings": "",
            "deploymentMethod": "auto"
        }
    },
    { ...
    },
    {
        "environment": {},
        "taskId": "502dd25d-1785-43e4-b4e5-a5c78ccc0573",
        "version": "1.*",
        "name": "Deploy Plataform 3",
        "refName": "",
        "enabled": true,
        "alwaysRun": false,
        "continueOnError": false,
        "timeoutInMinutes": 0,
        "definitionType": "task",
        "overrideInputs": {},
        "condition": "succeeded()",
        "inputs": {
            "azureSubscription": "3ca9b844-e92b-4678-8483-xxxx",
            "appType": "functionApp",
            "appName": "func app name",
            "deployToSlotOrASE": "false",
            "resourceGroupName": "",
            "slotName": "production",
            "package": "$(System.DefaultWorkingDirectory)/**/*.zip",
            "runtimeStack": "",
            "startUpCommand": "",
            "customWebConfig": "",
            "appSettings": "",
            "configurationStrings": "",
            "deploymentMethod": "auto"
        }
    }
]

PUT url: https://vsrm.dev.azure.com/{organization}/{project}/_apis/release/definitions?api-version=5.0

Error:

Invoke-RestMethod : {"$id":"1","innerException":null,"message":"Tasks with versions 'Deploy Plataform 3:1.*' are not valid for deploy job 'Run on agent' in stage DEV.
","typeName":"Microsoft.VisualStudio.Services.ReleaseManagement.Data.Exceptions.InvalidRequestException, Microsoft.VisualStudio.Services.ReleaseManagement2.Data","typeKey":"InvalidRequestException","errorCode":0,"eventId":3000}
Au caractère C:\Projects\TransportConfiguration\AutomationTasks\Build Definitions Supporting Scripts\Update-Release-Stage.ps1:49 : 9
+         Invoke-RestMethod -Uri $uri -Headers ($Header) -Method PUT -B ...
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation : (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

Put method:

function Invoke-WebRequestPut ([PSCustomObject] $releaseDefinition) {

    $uri = "https://vsrm.dev.azure.com/organizationname/projectname/_apis/release/definitions?api-version=5.0"

    $Auth = '{0}:{1}' -f $UserName, $PersonalToken
    $Auth = [System.Text.Encoding]::UTF8.GetBytes($Auth)
    $Auth = [System.Convert]::ToBase64String($Auth)
    $Header = @{Authorization = ("Basic {0}" -f $Auth)}

    $body = $releaseDefinition | ConvertTo-Json -Depth 30

    $body2 = [System.Text.Encoding]::UTF8.GetBytes($body)

    Invoke-RestMethod -Uri $uri -Headers ($Header) -Method PUT -Body $body2 -ContentType "application/json"
}

Using this put method I can modify an existing task name successfully (Deploy Plataform 1 => Deploy Plataform X). But can not add a new task.

This is a bug or I'm missing something.


来源: stackexchange

问:
How to change page heading in activeadmin
I want to change the titles of page as shown in diagram below.

How can I change that?

答:
To change the name of the label in the menu:

```<code>ActiveAdmin.register User do
  index title: "My custom Title"
end
</code>```

Source: https://activeadmin.info/2-resource-customization.html#customize-the-namespace

ContentLicense: CC BY-SA 4.0

Body:
To change the name of the label in the menu:

ActiveAdmin.register User do
  index title: "My custom Title"
end

Source: https://activeadmin.info/2-resource-customization.html#customize-the-namespace


问:
Group by a primary column level of a DataFrame and then applying a function on the each sub level
I have a dataframe with the following structure.
What I want to accomplish is to groupby the dataframe by the primary index level (TCKRA and TCKRB) and then within each apply a function which will calculate ASK - BID and will output only two columns for each level.

```<code>df = pd.DataFrame(np.random.rand(10, 4))*100
df.columns = pd.MultiIndex.from_tuples([('TCKR_A', 'BID'), ('TCKR_A', 'ASK'),
                                      ('TCKR_B', 'BID'), ('TCKR_B', 'ASK')])
df.columns.names = ['Sec', 'Fld']

df

>> df
Sec        TCKR_A                   TCKR_B
Fld   BID          ASK          BID         ASK
0   8.183207    36.627854   51.926086   18.809108
1   79.111061   39.580137   56.137122   41.631460
2   48.757876   11.297864   50.613713   56.089854
3   12.320957   38.624896   81.759719   88.549522
4   8.659632    36.967937   50.086826   20.728593
5   56.019027   77.685117   60.440403   9.726945
6   47.956368   20.087774   31.204852   99.893489
7   21.328761   32.824996   14.175482   13.154170
8   13.344390   90.940015   7.617241    50.501808
9   64.513930   34.020330   50.607016   38.710182

</code>```

I am trying to avoid using a loop, although then it's doable as I can apply the operation for each primary level.
So far I have tried to use pd.df.groupby() but with no luck,

```<code>df.groupby('Security', level=0).apply(lambda x: x.ASK - x.BID)

>> AttributeError: 'DataFrame' object has no attribute 'ASK'

</code>```

Body:
I have a dataframe with the following structure.
What I want to accomplish is to groupby the dataframe by the primary index level (TCKRA and TCKRB) and then within each apply a function which will calculate ASK - BID and will output only two columns for each level.

df = pd.DataFrame(np.random.rand(10, 4))*100
df.columns = pd.MultiIndex.from_tuples([('TCKR_A', 'BID'), ('TCKR_A', 'ASK'),
                                      ('TCKR_B', 'BID'), ('TCKR_B', 'ASK')])
df.columns.names = ['Sec', 'Fld']

df

>> df
Sec        TCKR_A                   TCKR_B
Fld   BID          ASK          BID         ASK
0   8.183207    36.627854   51.926086   18.809108
1   79.111061   39.580137   56.137122   41.631460
2   48.757876   11.297864   50.613713   56.089854
3   12.320957   38.624896   81.759719   88.549522
4   8.659632    36.967937   50.086826   20.728593
5   56.019027   77.685117   60.440403   9.726945
6   47.956368   20.087774   31.204852   99.893489
7   21.328761   32.824996   14.175482   13.154170
8   13.344390   90.940015   7.617241    50.501808
9   64.513930   34.020330   50.607016   38.710182

I am trying to avoid using a loop, although then it's doable as I can apply the operation for each primary level.
So far I have tried to use pd.df.groupby() but with no luck,

df.groupby('Security', level=0).apply(lambda x: x.ASK - x.BID)

>> AttributeError: 'DataFrame' object has no attribute 'ASK'

Body:
Here grouping is not necessary, because Multiindex and possible select columns by DataFrame.xs for DataFrames with same columns names by first level of MultiIndex, so possible subtract:

df1 = df.xs('ASK', level=1, axis=1) - df.xs('BID', level=1, axis=1)
print (df1)
Sec     TCKR_A     TCKR_B
0   -51.040171   1.390744
1   -58.132705  20.100789
2   -47.563213 -18.537630
3    72.634983  83.624726
4    48.298953  68.488183
5     6.468167  53.791475
6   -42.180559 -23.153447
7    -3.664986   3.900489
8    14.290560 -10.863276
9    -5.373369  11.897776

Detail:

print (df.xs('ASK', level=1, axis=1))
Sec     TCKR_A     TCKR_B
0    39.308051  63.787740
1    29.917202  90.320616
2    40.574980  26.707032
3    88.921470  98.472349
4    51.535075  88.601087
5    57.830159  83.719740
6    10.484424   4.659494
7    47.242629  94.349222
8    84.629795  81.936188


问:
How to get the variable name of GameObject
I have a list of GameObject. What I'm doing is Whenever I instantiate a prefab I stored in GameObject variable then destroy it later on.

```<code>List<GameObject> listofGameObject;
blueLine = Instantiate(monitorShapes, transform.position, transform.rotation);
</code>```

Then Later on I'll access that GameObject using listofGameObject[2]. What I'm trying to achieve is get the variable name of the GameObject stored in index 2 of listofGameObject which is blueLine. I tried using listofGameObject[2].name but it returns the name of prefab in asset.

答:
After instantiate, set the name of the GameObject to the variable name</p>

```<code>blueLine = Instantiate(monitorShapes, transform.position, transform.rotation);
blueLine.name = nameof(blueLine);
</code>```

Body:
I have a list of GameObject. What I'm doing is Whenever I instantiate a prefab I stored in GameObject variable then destroy it later on.

List<GameObject> listofGameObject;
blueLine = Instantiate(monitorShapes, transform.position, transform.rotation);

Then Later on I'll access that GameObject using listofGameObject[2]. What I'm trying to achieve is get the variable name of the GameObject stored in index 2 of listofGameObject which is blueLine. I tried using listofGameObject[2].name but it returns the name of prefab in asset.

Body:
After instantiate, set the name of the GameObject to the variable name

blueLine = Instantiate(monitorShapes, transform.position, transform.rotation);
blueLine.name = nameof(blueLine);


问:
Handler.postdelay() not working inside recycler view on scroll state change
I'm basically trying to execute a method in my RecyclerView inside on scroll state change here I'm using a Handler thread to execute a method after some delay but the method is not getting executed at all but however if I put that method outside the handler thread it's getting executed successfully so my question is why am I unable to run Handler thread inside RecyclerView  onscroll here is my code please take a look.

```<code>rvsongs!!.addOnScrollListener(object: RecyclerView.OnScrollListener(){
                override fun onScrollStateChanged(recyclerView: RecyclerView?, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                if(newState== SCROLL_STATE_IDLE) {
                    val timerHandler = Handler()
                    var updater:Runnable?=null
                    updater = object:Runnable {
                        override fun run() {
                            rvsongs!!.setIndexBarVisibility(false)//this method is not getting executed however when put outside handler thread it's executed without any problem
                        }
                    }
                    timerHandler.postDelayed(updater,100)
                }
                else
                {
                    rvsongs!!.setIndexBarVisibility(true)
                }
            }
        })
</code>```

答:
The issue is that you are calling setIndexBarVisibilty after the complete onScrollStateChanged is processed. In other words, the recyclerView is rendered before setIndexBatVisibility.

To solve this, just call invalidate after setIndexBarVisibility

```<code>       ...
       var updater:Runnable?=null
        updater = object:Runnable {
            override fun run() {
                rvsongs!!.setIndexBarVisibility(false)
                rvsongs.invalidate()
            }
        }
        ...
</code>```

Body:
I'm basically trying to execute a method in my RecyclerView inside on scroll state change here I'm using a Handler thread to execute a method after some delay but the method is not getting executed at all but however if I put that method outside the handler thread it's getting executed successfully so my question is why am I unable to run Handler thread inside RecyclerView  onscroll here is my code please take a look.

rvsongs!!.addOnScrollListener(object: RecyclerView.OnScrollListener(){
                override fun onScrollStateChanged(recyclerView: RecyclerView?, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                if(newState== SCROLL_STATE_IDLE) {
                    val timerHandler = Handler()
                    var updater:Runnable?=null
                    updater = object:Runnable {
                        override fun run() {
                            rvsongs!!.setIndexBarVisibility(false)//this method is not getting executed however when put outside handler thread it's executed without any problem
                        }
                    }
                    timerHandler.postDelayed(updater,100)
                }
                else
                {
                    rvsongs!!.setIndexBarVisibility(true)
                }
            }
        })

Body:
The issue is that you are calling setIndexBarVisibilty after the complete onScrollStateChanged is processed. In other words, the recyclerView is rendered before setIndexBatVisibility.

To solve this, just call invalidate after setIndexBarVisibility

       ...
       var updater:Runnable?=null
        updater = object:Runnable {
            override fun run() {
                rvsongs!!.setIndexBarVisibility(false)
                rvsongs.invalidate()
            }
        }
        ...


问:
UI Acceleo Launcher Project fails
I've followed this simple tutorial http://wiki.eclipse.org/Acceleo/Getting_Started to create an UI launcher...but when I finish and I make a right click on my uml model, I don't have the acceleo tag "Acceleo Model to Tex", so I'm unable to run the plugin...do you know how is it possible?
I use th eclipse version 3.6.1 with topcased...</p>

答:
I can see only two ways for this popup menu not to show. The least likely is that the extension of your model does not match the "model file name filter" field from the "new UI project" wizard ("*.uml" by default). I do not think that this is your case, but thought I would mention it anyways.

What I think is the problem in your case is : this tutorial does not really explain to people who are not familiar with Eclipse plugins how to use the UI project. Namely : this new "UI project" is an Eclipse plugin. In order for the menu it contributes to show, you have to deploy the project as a plugin in your Eclipse. This can be done by exporting the project as a deployable plugin (right-click => Export => Deployable plug-ins and fragments) or by spawning a new Eclipse instance from the Eclipse that contains the project (Run => Run Configurations... => double click 'Eclipse Application' then hit "Run").

This last solution is preferred for plugins undergoing development as it allows you to change the plugin and simply spawn a new instance again in order for the changes to show ... however if you do not aim at developping Eclipse plugins, this might not be the best solution as it forces you to have two workspaces : one for the development of the plugin, another for the testing. The UML model on which you will generate code has to be in this "testing" workspace.

ContentLicense: CC BY-SA 3.0

Title: UI Acceleo Launcher Project fails


问:
Creating parent child items
I have the following text and need to create a parent-child relationship between some things.

For example, whenever I encounter start inside another start its considered a child for the earlier parent so in the example step3 is child of step2.

I had opened the file and using regex. I'm trying to extract the steps
and then create a dictionary based on parent-child relationship.

The example text:

```<code>-----Starting Step for step1-----
text1
text2
text3
-----Ending Step for step1-----
-----Starting Step for step2-----
text4
text5
text6
-----Starting Step for step3-----
text7
text8
text9
-----Ending Step for step3-----

text10
text11
text12
-----Ending Step for step2-----
</code>```

My code is:

```<code>with open('notepad_1.txt','r') as f1:
    for line in f1:
        value=re.findall(r'Starting Step for (\w+)',line)
        new_value=re.findall(r'Ending Step for (\w+)',line)
        if value:
            if parent_tag_start:
                parent_tag_start[-1][parent_tag_start[-1].keys()[0]]=value[0]
            else:
                parent_tag_start.append(value[0])
        elif new_value:
            parent_tag_start.remove(new_value[0])
</code>```

Expected output

```<code>{'step1':None,step2:{step3}} # could extend up to n levels
</code>```

答:
I think you overcomplicated your problem. A good idea was to use the list parten_tag_start to keep track of the levels you already "went down", but the way you used it was too complicated.

You simply iterate over the parent_tag_start list whenever you need to add another level. I updated your code to add an empty dictionary on new created levels/children. So using this code:

```<code>import re

parent_tag_start = []
result_dict = {}

with open('notepad_1.txt', 'r') as f1:
    for line in f1:
        value = re.findall(r'Starting Step for (\w+)', line)
        new_value = re.findall(r'Ending Step for (\w+)', line)
        if value:
            level = result_dict
            # Find the current level
            for item in parent_tag_start:
                level = level[item]
            level[value[0]] = {}  # Add an empty dict as new child

            parent_tag_start.append(value[0])
        elif new_value:
            parent_tag_start.remove(new_value[0])  # A level ended

print(result_dict)
</code>```

This results in this output for your example text:

```<code>{'step1': {}, 'step2': {'step3': {}}}
</code>```

To check for another child you can simply check if the value of the current element is an empty dictionary or not.

Title: Creating parent child items

Body:
I have the following text and need to create a parent-child relationship between some things.

For example, whenever I encounter start inside another start its considered a child for the earlier parent so in the example step3 is child of step2.

I had opened the file and using regex. I'm trying to extract the steps
and then create a dictionary based on parent-child relationship.

The example text:

-----Starting Step for step1-----
text1
text2
text3
-----Ending Step for step1-----
-----Starting Step for step2-----
text4
text5
text6
-----Starting Step for step3-----
text7
text8
text9
-----Ending Step for step3-----

text10
text11
text12
-----Ending Step for step2-----

My code is:

with open('notepad_1.txt','r') as f1:
    for line in f1:
        value=re.findall(r'Starting Step for (\w+)',line)
        new_value=re.findall(r'Ending Step for (\w+)',line)
        if value:
            if parent_tag_start:
                parent_tag_start[-1][parent_tag_start[-1].keys()[0]]=value[0]
            else:
                parent_tag_start.append(value[0])
        elif new_value:
            parent_tag_start.remove(new_value[0])

Expected output

{'step1':None,step2:{step3}} # could extend up to n levels

Body:
I think you overcomplicated your problem. A good idea was to use the list parten_tag_start to keep track of the levels you already "went down", but the way you used it was too complicated.

You simply iterate over the parent_tag_start list whenever you need to add another level. I updated your code to add an empty dictionary on new created levels/children. So using this code:

import re

parent_tag_start = []
result_dict = {}

with open('notepad_1.txt', 'r') as f1:
    for line in f1:
        value = re.findall(r'Starting Step for (\w+)', line)
        new_value = re.findall(r'Ending Step for (\w+)', line)
        if value:
            level = result_dict
            # Find the current level
            for item in parent_tag_start:
                level = level[item]
            level[value[0]] = {}  # Add an empty dict as new child

            parent_tag_start.append(value[0])
        elif new_value:
            parent_tag_start.remove(new_value[0])  # A level ended

print(result_dict)

This results in this output for your example text:

{'step1': {}, 'step2': {'step3': {}}}

To check for another child you can simply check if the value of the current element is an empty dictionary or not.


问:
Excel's fullname property with OneDrive
If I want to use the open Workbook object to get the fullname of an Excel file after saving it, but that file has been synchronized to OneDrive, I get a "https" address instead of a local one, which other programs cannot interpret.

How do I get the local filename of a file like this?

Example:

Save a file to "C:\Users\user\OneDrive - Company\Documents".

OneDrive does its synchronization.

Querying Workbook.FullName now shows as "https://..."

答:
Here's a small improvement on Philip Swannell's improvement of Virtuoso's original answer for when the number of "\" to remove from the path is more than 4 / varies (depending on the file, i found i needed to remove 5 or sometimes 6 of these). The shortcomings mentioned by Philip are still there though.</p>

```<code>Private Function Local_Workbook_Name(ByRef wb As Workbook) As String
'returns local wb path or nothing if local path not found
    Dim i As Long
    Dim OneDrivePath As String
    Dim ShortName As String
    Dim testWbkPath As String
    Dim OneDrivePathFound As Boolean

    'Check if it looks like a OneDrive location
    If InStr(1, wb.FullName, "https://", vbTextCompare) > 0 Then
        'Replace forward slashes with back slashes
        ShortName = Replace(wb.FullName, "/", "\")

        'Remove the first four backslashes
        For i = 1 To 4
            ShortName = RemoveTopFolderFromPath(ShortName)
        Next

        'loop through three OneDrive options
        For i = 1 To 3
            OneDrivePath = Environ(Choose(i, "OneDrive", "OneDriveCommercial", "OneDriveConsumer"))
            If Len(OneDrivePath) > 0 Then
                'Loop to see if the tentative LocalWorkbookName is the name of a file that actually exists, if so return the name
                Do While ShortName Like "*\*"
                    testWbkPath = OneDrivePath & "\" & ShortName
                    If Not (Dir(testWbkPath)) = vbNullString Then
                        OneDrivePathFound = True
                        Exit Do
                    End If
                    'remove top folder in path
                    ShortName = RemoveTopFolderFromPath(ShortName)
                Loop
            End If
            If OneDrivePathFound Then Exit For
        Next i
    Else
        Local_Workbook_Name = wb.FullName
    End If

    If OneDrivePathFound Then Local_Workbook_Name = testWbkPath

End Function
Function RemoveTopFolderFromPath(ByVal ShortName As String) As String
    RemoveTopFolderFromPath = Mid(ShortName, InStr(ShortName, "\") + 1)
End Function
</code>```

Title: Excel's fullname property with OneDrive

Body:
Here's a small improvement on Philip Swannell's improvement of Virtuoso's original answer for when the number of "\" to remove from the path is more than 4 / varies (depending on the file, i found i needed to remove 5 or sometimes 6 of these). The shortcomings mentioned by Philip are still there though.

Private Function Local_Workbook_Name(ByRef wb As Workbook) As String
'returns local wb path or nothing if local path not found
    Dim i As Long
    Dim OneDrivePath As String
    Dim ShortName As String
    Dim testWbkPath As String
    Dim OneDrivePathFound As Boolean

    'Check if it looks like a OneDrive location
    If InStr(1, wb.FullName, "https://", vbTextCompare) > 0 Then
        'Replace forward slashes with back slashes
        ShortName = Replace(wb.FullName, "/", "\")

        'Remove the first four backslashes
        For i = 1 To 4
            ShortName = RemoveTopFolderFromPath(ShortName)
        Next

        'loop through three OneDrive options
        For i = 1 To 3
            OneDrivePath = Environ(Choose(i, "OneDrive", "OneDriveCommercial", "OneDriveConsumer"))
            If Len(OneDrivePath) > 0 Then
                'Loop to see if the tentative LocalWorkbookName is the name of a file that actually exists, if so return the name
                Do While ShortName Like "*\*"
                    testWbkPath = OneDrivePath & "\" & ShortName
                    If Not (Dir(testWbkPath)) = vbNullString Then
                        OneDrivePathFound = True
                        Exit Do
                    End If
                    'remove top folder in path
                    ShortName = RemoveTopFolderFromPath(ShortName)
                Loop
            End If
            If OneDrivePathFound Then Exit For
        Next i
    Else
        Local_Workbook_Name = wb.FullName
    End If

    If OneDrivePathFound Then Local_Workbook_Name = testWbkPath

End Function
Function RemoveTopFolderFromPath(ByVal ShortName As String) As String
    RemoveTopFolderFromPath = Mid(ShortName, InStr(ShortName, "\") + 1)
End Function


问:
Specificity in scikit learn
I need specificity for my classification which is defined as :
TN/(TN+FP)

I am writing a custom scorer function :

```<code>from sklearn.metrics import make_scorer
def specificity_loss_func(ground_truth, predictions):
    print predictions
    tp, tn, fn, fp = 0.0,0.0,0.0,0.0
    for l,m in enumerate(ground_truth):
        if m==predictions[l] and m==1:
            tp+=1
        if m==predictions[l] and m==0:
            tn+=1
        if m!=predictions[l] and m==1:
            fn+=1
        if m!=predictions[l] and m==0:
            fp+=1
    `return tn/(tn+fp)

score = make_scorer(specificity_loss_func, greater_is_better=True)
</code>```

Then,

```<code>from sklearn.dummy import DummyClassifier
clf_dummy = DummyClassifier(strategy='most_frequent', random_state=0)
ground_truth = [0,0,1,0,1,1,1,0,0,1,0,0,1]
p  = [0,0,0,1,0,1,1,1,1,0,0,1,0]
clf_dummy = clf_dummy.fit(ground_truth, p)
score(clf_dummy, ground_truth, p)
</code>```

When I run these commands, I get p printed as :

```<code>[0 0 0 0 0 0 0 0 0 0 0 0 0]
1.0
</code>```

Why is my p changing to a series of zeros when I input p  = [0,0,0,1,0,1,1,1,1,0,0,1,0]

答:
As I understand it, 'specificity' is just a special case of 'recall'. Recall is calculated for the actual positive class ( TP / [TP+FN] ), whereas 'specificity' is the same type of calculation but for the actual negative class ( TN / [TN+FP] ).

It really only makes sense to have such specific terminology for binary classification problems. For a multi-class classification problem it would be more convenient to talk about recall with respect to each class. There is no reason why you can't talk about recall in this way even when dealing with binary classification problem (e.g. recall for class 0, recall for class 1).

For example, recall tells us the proportion of patients that actual have cancer, being successfully diagnosed as having cancer. However, to generalize, you could say Class X recall tells us the proportion of samples actually belonging to Class X, being successfully predicted as belonging to Class X.

Given this, you can use from sklearn.metrics import classification_report to produce a dictionary of the precision, recall, f1-score and support for each label/class. You can also rely on from sklearn.metrics import precision_recall_fscore_support as well, depending on your preference. Documentation here.

```<code>from sklearn.metrics import precision_recall_fscore_support

labels = ['dog', 'cat', 'pig']

y_true = np.array(['cat', 'dog', 'pig', 'cat', 'dog', 'pig'])
y_pred = np.array(['cat', 'pig', 'dog', 'cat', 'cat', 'dog'])

prfs = precision_recall_fscore_support(y_true, y_pred, average=None, labels=labels)
precisions = prfs[0]
recalls = prfs[1] #Specificity in Binary Classification
fbeta_scores = prfs[2]
supports = prfs[3]

print(recalls) # Note the order of this array is dependent on the order of your labels array
</code>```

Title: Specificity in scikit learn

Body:
I need specificity for my classification which is defined as :
TN/(TN+FP)

I am writing a custom scorer function :

from sklearn.metrics import make_scorer
def specificity_loss_func(ground_truth, predictions):
    print predictions
    tp, tn, fn, fp = 0.0,0.0,0.0,0.0
    for l,m in enumerate(ground_truth):
        if m==predictions[l] and m==1:
            tp+=1
        if m==predictions[l] and m==0:
            tn+=1
        if m!=predictions[l] and m==1:
            fn+=1
        if m!=predictions[l] and m==0:
            fp+=1
    `return tn/(tn+fp)

score = make_scorer(specificity_loss_func, greater_is_better=True)

Then,

from sklearn.dummy import DummyClassifier
clf_dummy = DummyClassifier(strategy='most_frequent', random_state=0)
ground_truth = [0,0,1,0,1,1,1,0,0,1,0,0,1]
p  = [0,0,0,1,0,1,1,1,1,0,0,1,0]
clf_dummy = clf_dummy.fit(ground_truth, p)
score(clf_dummy, ground_truth, p)

When I run these commands, I get p printed as :

[0 0 0 0 0 0 0 0 0 0 0 0 0]
1.0

Why is my p changing to a series of zeros when I input p  = [0,0,0,1,0,1,1,1,1,0,0,1,0]

Body:
As I understand it, 'specificity' is just a special case of 'recall'. Recall is calculated for the actual positive class ( TP / [TP+FN] ), whereas 'specificity' is the same type of calculation but for the actual negative class ( TN / [TN+FP] ).

It really only makes sense to have such specific terminology for binary classification problems. For a multi-class classification problem it would be more convenient to talk about recall with respect to each class. There is no reason why you can't talk about recall in this way even when dealing with binary classification problem (e.g. recall for class 0, recall for class 1).

For example, recall tells us the proportion of patients that actual have cancer, being successfully diagnosed as having cancer. However, to generalize, you could say Class X recall tells us the proportion of samples actually belonging to Class X, being successfully predicted as belonging to Class X.

Given this, you can use from sklearn.metrics import classification_report to produce a dictionary of the precision, recall, f1-score and support for each label/class. You can also rely on from sklearn.metrics import precision_recall_fscore_support as well, depending on your preference. Documentation here.

from sklearn.metrics import precision_recall_fscore_support

labels = ['dog', 'cat', 'pig']

y_true = np.array(['cat', 'dog', 'pig', 'cat', 'dog', 'pig'])
y_pred = np.array(['cat', 'pig', 'dog', 'cat', 'cat', 'dog'])

prfs = precision_recall_fscore_support(y_true, y_pred, average=None, labels=labels)
precisions = prfs[0]
recalls = prfs[1] #Specificity in Binary Classification
fbeta_scores = prfs[2]
supports = prfs[3]

print(recalls) # Note the order of this array is dependent on the order of your labels array


问:
How to update subtype attribute values in oracle database?
How to update column value of a subtype?

Code like this can't access the grade attribute of student:

```<code>update persons set grade = 'graduated';
</code>```

CREATE OR REPLACE TYPE person (
    name varchar2(20),
    age number,
    address varchar2(20)
) NOT FINAL;

CREATE OR REPLACE TYPE student UNDER person (
    grade varchar2(20)
) NOT FINAL;

CREATE TABLE persons OF person;

INSERT INTO persons VALUES (student('Jon', 'undergraduate'));
```

How I change student grade to 'graduated'?

答:
that should work</p>

```<code>update persons s set VALUE(s) = student(treat(value(s) as student).name, 'graduated');
</code>```

Body:
How to update column value of a subtype?

Code like this can't access the grade attribute of student:

update persons set grade = 'graduated';

CREATE OR REPLACE TYPE person (
    name varchar2(20),
    age number,
    address varchar2(20)
) NOT FINAL;

CREATE OR REPLACE TYPE student UNDER person (
    grade varchar2(20)
) NOT FINAL;

CREATE TABLE persons OF person;

INSERT INTO persons VALUES (student('Jon', 'undergraduate'));

How I change student grade to 'graduated'?

Body:
that should work

update persons s set VALUE(s) = student(treat(value(s) as student).name, 'graduated');


问:
Converting between windows and unix path with sed losses double slash
This command almost gives me what I want :-

```<code>echo "\\123.123.123.123\path1\1 - path2\path3 path4\path5" | sed 's_\\_/_g' | sed 's_ _\\ _g'
/123.123.123.123/path1/1\ -\ path2/path3\ path4/path5
</code>```

But as one can see, its lost the '//' at the beginning!

ie, desired outout :-

```<code>//123.123.123.123/path1/1\ -\ path2/path3\ path4/path5
</code>```

What am I missing?

Edit: After not testing the basics of echo (many thanks to all who pointed that out). I should of also been more clear on the end-game of this question.

I want to use this in a script, and define the windows path at the top.

How can I echo the path to a tmp file for sed?

This obviously wont work :-

```<code>WIN_PATH="\\123.123.123.123\path1\1 - path2\path3 path4\path5"
UNIX_PATH=`echo $WIN_PATH | sed 's_\\_/_g' | sed 's_ _\\ _g'`
</code>```

答:
Bash uses the \ (backslash) as an escape. It isn't being munched by sed, but by bash before passing the string to echo. Try:

```<code>echo "\\123"
</code>```

You'll get:

```<code>\123
</code>```

To solve your problem, put your text into a file, and read it from there to avoid shell escaping:

```<code>$ cat >file
\\123.123.123.123\path1\1 - path2\path3 path4\path5
$ cat file | sed 's_\\_/_g' | sed 's_ _\\ _g'
//123.123.123.123/path1/1\ -\ path2/path3\ path4/path5
</code>```

Body:
This command almost gives me what I want :-

echo "\\123.123.123.123\path1\1 - path2\path3 path4\path5" | sed 's_\\_/_g' | sed 's_ _\\ _g'
/123.123.123.123/path1/1\ -\ path2/path3\ path4/path5

But as one can see, its lost the '//' at the beginning!

ie, desired outout :-

//123.123.123.123/path1/1\ -\ path2/path3\ path4/path5

What am I missing?

Edit: After not testing the basics of echo (many thanks to all who pointed that out). I should of also been more clear on the end-game of this question.

I want to use this in a script, and define the windows path at the top.

How can I echo the path to a tmp file for sed?

This obviously wont work :-

WIN_PATH="\\123.123.123.123\path1\1 - path2\path3 path4\path5"
UNIX_PATH=`echo $WIN_PATH | sed 's_\\_/_g' | sed 's_ _\\ _g'`

Body:
Bash uses the \ (backslash) as an escape. It isn't being munched by sed, but by bash before passing the string to echo. Try:

echo "\\123"

You'll get:

\123

To solve your problem, put your text into a file, and read it from there to avoid shell escaping:

$ cat >file
\\123.123.123.123\path1\1 - path2\path3 path4\path5
$ cat file | sed 's_\\_/_g' | sed 's_ _\\ _g'
//123.123.123.123/path1/1\ -\ path2/path3\ path4/path5


问:
react native how to pass a state to all children
```<code>    import {
    ImageBackground
} from 'react-native';

export const CustomContext = React.createContext(1);
export default class MainBackGround extends React.Component {
    state ={
        lang:'en'
    }
    render() {
        return (
            <CustomContext.Provider value={this.state.lang}>
                <ImageBackground>
                    { this.props.children }
                </ImageBackground>
            </CustomContext.Provider>
        )
    }
}
</code>```

child component

```<code>import MainBackground, {CustomContext} from '../components/MainBackground';
export default class MyChildComponent extends React.Component {

    render() {
        return (
                <CustomContext.Consumer>
                { value => (
                <ScrollView >
                    <Text>{value}</Text>
                </ScrollView>
                )}
                </CustomContext.Consumer>
        );
    }
}
</code>```

How can I pass state a to all the children?

I just update the code closer to my real code

problem I'm getting value as 1 instead of en ( the  is showing 1 instead en)

答:
There are three approaches I see for your problem:-

1) Using render prop pattern

2) Using React.cloneElement

3) Using React.Context API

Here is the code sandbox link with usage of all three methods. Use whichever suits your need.

Hope that helps!!!

Body:
    import {
    ImageBackground
} from 'react-native';

export const CustomContext = React.createContext(1);
export default class MainBackGround extends React.Component {
    state ={
        lang:'en'
    }
    render() {
        return (
            <CustomContext.Provider value={this.state.lang}>
                <ImageBackground>
                    { this.props.children }
                </ImageBackground>
            </CustomContext.Provider>
        )
    }
}

child component

import MainBackground, {CustomContext} from '../components/MainBackground';
export default class MyChildComponent extends React.Component {

    render() {
        return (
                <CustomContext.Consumer>
                { value => (
                <ScrollView >
                    <Text>{value}</Text>
                </ScrollView>
                )}
                </CustomContext.Consumer>
        );
    }
}

How can I pass state a to all the children?

I just update the code closer to my real code

problem I'm getting value as 1 instead of en ( the  is showing 1 instead en)


问:
Could reinterpret_cast turn an invalid pointer value into a valid one?
Consider this union:

```<code>union A{
  int a;
  struct{
    int b;
    } c;
  };
</code>```

c and a are not layout-compatibles types so it is not possible to read the value of b through a:

```<code>A x;
x.c.b=10;
x.a+x.a; //undefined behaviour (UB)
</code>```

Trial 1

For the case below I think that since C++17, I also get an undefined behavior:

```<code>A x;
x.a=10;
auto p = &x.a; //(1)
x.c.b=12;      //(2)
*p+*p;         //(3) UB
</code>```

Let's consider [basic.type]/3:

Every value of pointer type is one of the following:

a pointer to an object or function (the pointer is said to point to the object or function), or

a pointer past the end of an object ([expr.add]), or

the null pointer value ([conv.ptr]) for that type, or

an invalid pointer value.

Let's call this 4 pointer values categories as pointer value genre.

The value of a pointer may transition from of the above mentioned genre to an other, but the standard is not really explicit about that. Fill free to correct me if I am wrong. So I suppose that at (1) the value of p is a pointer to value. Then in (2) a life ends and the value of p becomes an invalid pointer value. So in (3) I get UB because I try to access the value of an object (a) out of its lifetime.

Trial 2

Now consider this weird code:

```<code>A x;
x.a=10;
auto p = &x.a;                 //(1)
x.c.b=12;                      //(2)
p = reinterpret_cast<int*>(p); //(2')
*p+*p;                         //(3) UB?
</code>```

Could the reinterpret_cast<int*>(p) change the pointer value genre from invalid pointer value to a pointer to value.

reinterpret_cast<int*>(p) is defined to be equivalent to static_cast<int*>(static_cast<void*>(p)), so let's consider how is defined the static_cast from void* to int*, [expr.static.cast]/13:

A prvalue of type “pointer to cv1 void” can be converted to a prvalue of type “pointer to cv2 T”, where T is an object type and cv2 is the same cv-qualification as, or greater cv-qualification than, cv1. If the original pointer value represents the address A of a byte in memory and A does not satisfy the alignment requirement of T, then the resulting pointer value is unspecified. Otherwise, if the original pointer value points to an object a, and there is an object b of type T (ignoring cv-qualification) that is pointer-interconvertible with a, the result is a pointer to b. Otherwise, the pointer value is unchanged by the conversion.

So in our case the original pointer pointed to the object a. So I suppose the reinterpret_cast will not help because a is not within its lifetime. Is my reading to strict? Could this code be well defined?

答:
The notion of objects in the standard is rather abstract and differs somewhat from intuition. An object may be within its lifetime or not, and objects not within their lifetimes can have the same address, this is why unions work at all: the definition of active member is "the member that is within its lifetime".

A pointer to an object not within its lifetime is still a pointer to object. reinterpret_cast only casts between the type of the pointer, but not its validity. The UB you get with casting to non-pointer-interconvertible types are due to the strict-aliasing rule, not due to the validity of the pointer.

In all your trials, including your follow up question, you are using an object not within its lifetime in ways that aren't allowed, ie accessing it, and are consequently UB.

Body:
Consider this union:

union A{
  int a;
  struct{
    int b;
    } c;
  };

c and a are not layout-compatibles types so it is not possible to read the value of b through a:

A x;
x.c.b=10;
x.a+x.a; //undefined behaviour (UB)

Trial 1

For the case below I think that since C++17, I also get an undefined behavior:

A x;
x.a=10;
auto p = &x.a; //(1)
x.c.b=12;      //(2)
*p+*p;         //(3) UB

Let's consider [basic.type]/3:

Every value of pointer type is one of the following:

a pointer to an object or function (the pointer is said to point to the object or function), or

a pointer past the end of an object ([expr.add]), or

the null pointer value ([conv.ptr]) for that type, or

an invalid pointer value.

Let's call this 4 pointer values categories as pointer value genre.

The value of a pointer may transition from of the above mentioned genre to an other, but the standard is not really explicit about that. Fill free to correct me if I am wrong. So I suppose that at (1) the value of p is a pointer to value. Then in (2) a life ends and the value of p becomes an invalid pointer value. So in (3) I get UB because I try to access the value of an object (a) out of its lifetime.

Trial 2

Now consider this weird code:

A x;
x.a=10;
auto p = &x.a;                 //(1)
x.c.b=12;                      //(2)
p = reinterpret_cast<int*>(p); //(2')
*p+*p;                         //(3) UB?

Could the reinterpret_cast<int*>(p) change the pointer value genre from invalid pointer value to a pointer to value.

reinterpret_cast<int*>(p) is defined to be equivalent to static_cast<int*>(static_cast<void*>(p)), so let's consider how is defined the static_cast from void* to int*, [expr.static.cast]/13:

A prvalue of type “pointer to cv1 void” can be converted to a prvalue of type “pointer to cv2 T”, where T is an object type and cv2 is the same cv-qualification as, or greater cv-qualification than, cv1. If the original pointer value represents the address A of a byte in memory and A does not satisfy the alignment requirement of T, then the resulting pointer value is unspecified. Otherwise, if the original pointer value points to an object a, and there is an object b of type T (ignoring cv-qualification) that is pointer-interconvertible with a, the result is a pointer to b. Otherwise, the pointer value is unchanged by the conversion.

So in our case the original pointer pointed to the object a. So I suppose the reinterpret_cast will not help because a is not within its lifetime. Is my reading to strict? Could this code be well defined?


问:
Is sed auto in-place substitution?
I have this code, which I do want for replacement of a specific pattern, but not multi in-place replacement.

```<code> echo "ss qq" | sed  "s/ss/qq/g; s/qq/dd/g;"
</code>```

The result is

```<code>dd dd
</code>```

and wish it would be

```<code>qq dd
</code>```

Also via "looping" we get the same result.

```<code>echo "ss qq" | sed  ":loop; s/ss/qq/g; s/qq/dd/g; t loop;"
</code>```

its petty, very disappointing bug !!

Any suggestion why it's happening?

答:
whish it would be

qq dd

then you do the substitution in invert order:

change sed  "s/ss/qq/g;s/qq/dd/g;" -> sed  "s/qq/dd/g;s/ss/qq/g;"

Title: Is sed auto in-place substitution?

Body:
I have this code, which I do want for replacement of a specific pattern, but not multi in-place replacement.

 echo "ss qq" | sed  "s/ss/qq/g; s/qq/dd/g;"

The result is

dd dd

and wish it would be

qq dd

Also via "looping" we get the same result.

echo "ss qq" | sed  ":loop; s/ss/qq/g; s/qq/dd/g; t loop;"

its petty, very disappointing bug !!

Any suggestion why it's happening?


问:
How can i plot the decision boundary for a multilabel SVM problem using caret in R
I've built an SVM model using R's caret package:

```<code>set.seed(1234567)

SVM_caret <- train(x = x_train, y = y_train$label,
               method = "svmLinear", tuneGrid = expand.grid(
              C = c(0.001, 0.01, 0.1, 1)),
              metric = "ROC",
              trControl = trainControl(method = "cv", number = 3, classProbs = T),
              maxit = 100)
</code>```

I tried to implement this code to plot the decision bounday of my model, but i'm getting several errors. This is the model's confusion matrix:

```<code>Confusion Matrix and Statistics

          Reference
Prediction class_1 class_2 class_3 class_4
   class_1       9       0       0       0
   class_2       0       7       0       0
   class_3       3       0       6       0
   class_4       0       0       0       7

Overall Statistics

               Accuracy : 0.9062
                 95% CI : (0.7498, 0.9802)
    No Information Rate : 0.375
    P-Value [Acc > NIR] : 5.706e-10

                  Kappa : 0.8743

 Mcnemar's Test P-Value : NA

Statistics by Class:

                     Class: class_1 Class: class_2 Class: class_3 Class: class_4
Sensitivity                  0.7500         1.0000         1.0000         1.0000
Specificity                  1.0000         1.0000         0.8846         1.0000
Pos Pred Value               1.0000         1.0000         0.6667         1.0000
Neg Pred Value               0.8696         1.0000         1.0000         1.0000
Prevalence                   0.3750         0.2188         0.1875         0.2188
Detection Rate               0.2812         0.2188         0.1875         0.2188
Detection Prevalence         0.2812         0.2188         0.2812         0.2188
Balanced Accuracy            0.8750         1.0000         0.9423         1.0000
</code>```

There are 4 classes to predict, i don't know if is it really possible to get this plot built, but i couldn't figure out how to get it done. Is there any function or way to visualize this decission boundary??

Since i can't just copy paste my data here, i'll add a link to it on google drive, so you can download and reproduce the problem, don't worry for the size as it is really lightweight.

Here are the links:

train_data

train_labels

Thank you very much in advance for your help.

答:
As stated in the comments:

You can only visualize decision boundaries in two dimensional plot when you have two predictors. You are using 10 predictors however, which means every point exists in a 10-dimensional space this can't be plotted the way you intend to.

Choosing a subset of predictors to plot would give you the ability to plot decision boundaries but they won't divide the data in your plot in any meaningful way.

If you definitly want to visualize a set of decision rules you can do a decision tree.

```<code>
dtree <- train(x = svm_data[,-1], y = svm_labels$label,
                   method = "rpart",
                   metric = "Accuracy",
                   trControl = trainControl(method = "cv", number = 3, classProbs = T),
                   cp = 0.005,
                   maxdepth = 3)

plot(dtree$finalModel, margin = 0.2)
text(dtree$finalModel)

</code>```

Body:
I've built an SVM model using R's caret package:

set.seed(1234567)

SVM_caret <- train(x = x_train, y = y_train$label,
               method = "svmLinear", tuneGrid = expand.grid(
              C = c(0.001, 0.01, 0.1, 1)),
              metric = "ROC",
              trControl = trainControl(method = "cv", number = 3, classProbs = T),
              maxit = 100)

I tried to implement this code to plot the decision bounday of my model, but i'm getting several errors. This is the model's confusion matrix:

Confusion Matrix and Statistics

          Reference
Prediction class_1 class_2 class_3 class_4
   class_1       9       0       0       0
   class_2       0       7       0       0
   class_3       3       0       6       0
   class_4       0       0       0       7

Overall Statistics

               Accuracy : 0.9062
                 95% CI : (0.7498, 0.9802)
    No Information Rate : 0.375
    P-Value [Acc > NIR] : 5.706e-10

                  Kappa : 0.8743

 Mcnemar's Test P-Value : NA

Statistics by Class:

                     Class: class_1 Class: class_2 Class: class_3 Class: class_4
Sensitivity                  0.7500         1.0000         1.0000         1.0000
Specificity                  1.0000         1.0000         0.8846         1.0000
Pos Pred Value               1.0000         1.0000         0.6667         1.0000
Neg Pred Value               0.8696         1.0000         1.0000         1.0000
Prevalence                   0.3750         0.2188         0.1875         0.2188
Detection Rate               0.2812         0.2188         0.1875         0.2188
Detection Prevalence         0.2812         0.2188         0.2812         0.2188
Balanced Accuracy            0.8750         1.0000         0.9423         1.0000

There are 4 classes to predict, i don't know if is it really possible to get this plot built, but i couldn't figure out how to get it done. Is there any function or way to visualize this decission boundary??

Since i can't just copy paste my data here, i'll add a link to it on google drive, so you can download and reproduce the problem, don't worry for the size as it is really lightweight.

Here are the links:

train_data

train_labels

Thank you very much in advance for your help.

Body:
As stated in the comments:

You can only visualize decision boundaries in two dimensional plot when you have two predictors. You are using 10 predictors however, which means every point exists in a 10-dimensional space this can't be plotted the way you intend to.

Choosing a subset of predictors to plot would give you the ability to plot decision boundaries but they won't divide the data in your plot in any meaningful way.

If you definitly want to visualize a set of decision rules you can do a decision tree.

dtree <- train(x = svm_data[,-1], y = svm_labels$label,
                   method = "rpart",
                   metric = "Accuracy",
                   trControl = trainControl(method = "cv", number = 3, classProbs = T),
                   cp = 0.005,
                   maxdepth = 3)

plot(dtree$finalModel, margin = 0.2)
text(dtree$finalModel)


问:
NSDATA writeToFile crashes without a reason
I am downloading images from a url using NSDATA and saving them to local file system using

```<code>NSData *dataForStorage = [NSData dataWithData:UIImagePNGRepresentation(img)];

    BOOL saveResult=[ dataForStorage writeToFile:jpegFilePath options:NSDataWritingAtomic error:&error];
    NSLog(@"Write returned error: %@", [error localizedDescription]);
</code>```

My app crashes randomly without even giving a message, though some files are saved (again randomly). When I run the app in Debug mode, I frequently see "EXC_BAD_ACCESS" but continuing execution succeeds in saving some of the files.

This code is executed in background from:

```<code>[self performSelectorInBackground:@selector(loadImageInBackground:) withObject:arr];
</code>```

Please suggest.

答:
One of the problems in your code is that your running code in a thread without an autorelease pool but are using functions that would require one. Put the following code into the loadImageInBackground method:

```<code>NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

// existing code

[pool drain];
</code>```

This is probably just one of several problems. For further assistance, we need to see the stack trace of the crash.

Body:
I am downloading images from a url using NSDATA and saving them to local file system using

NSData *dataForStorage = [NSData dataWithData:UIImagePNGRepresentation(img)];

    BOOL saveResult=[ dataForStorage writeToFile:jpegFilePath options:NSDataWritingAtomic error:&error];
    NSLog(@"Write returned error: %@", [error localizedDescription]);

My app crashes randomly without even giving a message, though some files are saved (again randomly). When I run the app in Debug mode, I frequently see "EXC_BAD_ACCESS" but continuing execution succeeds in saving some of the files.

This code is executed in background from:

[self performSelectorInBackground:@selector(loadImageInBackground:) withObject:arr];

Please suggest.

Body:
One of the problems in your code is that your running code in a thread without an autorelease pool but are using functions that would require one. Put the following code into the loadImageInBackground method:

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

// existing code

[pool drain];

This is probably just one of several problems. For further assistance, we need to see the stack trace of the crash.


问:
How to handle images with webpack encore & assets
so I seem to be a bit confused on how to work with images in webpack encore + assets.

I store all JS & CSS like this

```<code>/assets/js
/assets/css
...
</code>```

With encore I can access them later from my /public/build folder - no issues there.

Now I want to store some images (e.g. file upload).

First idea was to store them inside a folder like /assets/images. But with the current settings & using assets I can only access files inside /public/build folder.

So I tried to use to copyFiles to copy everything from /assets/images to /public/build/images.

But this does not automatically copy my files (e.g. file upload to /assets/images/ does not copy it to /public/build - which is in order not accessible in my project). So I would need to run manually encore - which I don't want.

Second idea was to store the uploaded images directly inside /public/build/images but those files would be deleted when I run encore.

Next I disabled the webpack option cleanupOutputBeforeBuild, so images would not be deleted. But without this option the folder will be flooded by new JS & CSS Files everytime I run encore.

What do I need?

A solution to store my images either way in /assets folder & make them available for my project.

or

store the images directly in /public/build folder without encore deleting them nor flooding the folder with JS/CSS by disabling cleanupOutput Option.

Thanks in advance ~Syllz

答: You can use the CopyWebpackPlugin to do this. You can read this post for more details.

Body:
so I seem to be a bit confused on how to work with images in webpack encore + assets.

I store all JS & CSS like this

/assets/js
/assets/css
...

With encore I can access them later from my /public/build folder - no issues there.

Now I want to store some images (e.g. file upload).

First idea was to store them inside a folder like /assets/images. But with the current settings & using assets I can only access files inside /public/build folder.

So I tried to use to copyFiles to copy everything from /assets/images to /public/build/images.

But this does not automatically copy my files (e.g. file upload to /assets/images/ does not copy it to /public/build - which is in order not accessible in my project). So I would need to run manually encore - which I don't want.

Second idea was to store the uploaded images directly inside /public/build/images but those files would be deleted when I run encore.

Next I disabled the webpack option cleanupOutputBeforeBuild, so images would not be deleted. But without this option the folder will be flooded by new JS & CSS Files everytime I run encore.

What do I need?

A solution to store my images either way in /assets folder & make them available for my project.

or

store the images directly in /public/build folder without encore deleting them nor flooding the folder with JS/CSS by disabling cleanupOutput Option.

Thanks in advance ~Syllz


问:
Show Non matching values query of two columns
Tried this Query:

```<code>
    SELECT     Movements.[date of movement],
               Movements.[Date of value],
               Movements.Description
    FROM       Movements
    INNER JOIN Documents
    on         Movements.Description<> '%' + Documents.Costumer+ '%'
    AND        Documents.[Value with IVA] <> Movements.Value
    Group by   Movements.[date of Movement],
               Movements.[Date of value],
               Movements.Description,
               Documents.Costumer,
               Documents.[Value with IVA]

</code>```

The problem is that He shows me all Costumers that doesnt match with the the description... And what I want is the descriptions that do not match one single time....
 I want to me to show me like:

```<code>Date of movement    Date of Value    Description
12-12-2011           1-12-2011       123123
12-12-2011           12-12-2011      121121
13-12-2011           13-12-2011      121121
</code>```

What it shows me is this

```<code>Date of movement    Date of Value    Description
  12-12-2011           1-12-2011       123123
  12-12-2011           12-12-2011      121121
  13-12-2011           13-12-2011      121121
  12-12-2011           1-12-2011       123123
  12-12-2011           12-12-2011      121121
  13-12-2011           13-12-2011      121121
  12-12-2011           1-12-2011       123123
  12-12-2011           12-12-2011      121121
  13-12-2011           13-12-2011      121121
</code>```

答:
Insted of this:

```<code> SELECT     Movements.[date of movement],
           Movements.[Date of value],
           Movements.Description
FROM       Movements
INNER JOIN Documents
on         Movements.Description<> '%' + Documents.Costumer+ '%'
AND        Documents.[Value with IVA] <> Movements.Value
Group by   Movements.[date of Movement],
           Movements.[Date of value],
           Movements.Description,
           Documents.Costumer,
           Documents.[Value with IVA]
</code>```

Do this:

```<code> SELECT     Movements.[date of movement],
           Movements.[Date of value],
           Movements.Description
FROM       Movements
INNER JOIN Documents
on         Movements.Description<> '%' + Documents.Costumer+ '%'
AND        Documents.[Value with IVA] <> Movements.Value
Group by   Movements.[date of Movement],
           Movements.[Date of value],
           Movements.Description
</code>```

ps: all Credits go to @Squirrel

Body:
Tried this Query:

    SELECT     Movements.[date of movement],
               Movements.[Date of value],
               Movements.Description
    FROM       Movements
    INNER JOIN Documents
    on         Movements.Description<> '%' + Documents.Costumer+ '%'
    AND        Documents.[Value with IVA] <> Movements.Value
    Group by   Movements.[date of Movement],
               Movements.[Date of value],
               Movements.Description,
               Documents.Costumer,
               Documents.[Value with IVA]

The problem is that He shows me all Costumers that doesnt match with the the description... And what I want is the descriptions that do not match one single time....
 I want to me to show me like:

Date of movement    Date of Value    Description
12-12-2011           1-12-2011       123123
12-12-2011           12-12-2011      121121
13-12-2011           13-12-2011      121121

What it shows me is this

Date of movement    Date of Value    Description
  12-12-2011           1-12-2011       123123
  12-12-2011           12-12-2011      121121
  13-12-2011           13-12-2011      121121
  12-12-2011           1-12-2011       123123
  12-12-2011           12-12-2011      121121
  13-12-2011           13-12-2011      121121
  12-12-2011           1-12-2011       123123
  12-12-2011           12-12-2011      121121
  13-12-2011           13-12-2011      121121

Body:
Insted of this:

 SELECT     Movements.[date of movement],
           Movements.[Date of value],
           Movements.Description
FROM       Movements
INNER JOIN Documents
on         Movements.Description<> '%' + Documents.Costumer+ '%'
AND        Documents.[Value with IVA] <> Movements.Value
Group by   Movements.[date of Movement],
           Movements.[Date of value],
           Movements.Description,
           Documents.Costumer,
           Documents.[Value with IVA]

Do this:

 SELECT     Movements.[date of movement],
           Movements.[Date of value],
           Movements.Description
FROM       Movements
INNER JOIN Documents
on         Movements.Description<> '%' + Documents.Costumer+ '%'
AND        Documents.[Value with IVA] <> Movements.Value
Group by   Movements.[date of Movement],
           Movements.[Date of value],
           Movements.Description

ps: all Credits go to @Squirrel


问:
How to extract lower and upper bound in numeric format from a confidence interval string?
Suppose a vector including some confidence intervals as below

```<code>confint <- c("[0.741 ; 2.233]", "[263.917 ; 402.154]", "[12.788 ; 17.975]", "[0.680 ; 2.450]", "[0.650 ; 1.827]", "[0.719 ; 2.190]")
</code>```

I want to have two new vectors one including the lower Limits in numeric format as

```<code>lower <- c(0.741, 263.917, 12.788, 0.680, 0.650 , 0.719)
</code>```

and othe including the upper Limits in numeric format like

```<code>upper <- c(2.233, 402.154, 17.975, 2.450, 1.827, 2.190)
</code>```

答:
Meanwhile, I came up with another base R solution

```<code>lower <- as.numeric(sub(".]*", "", sub(";.*", "", confint)))
upper <- as.numeric(sub("].*", "", sub(".*;", "", confint)))
</code>```

Thank you all!

Body:
Suppose a vector including some confidence intervals as below

confint <- c("[0.741 ; 2.233]", "[263.917 ; 402.154]", "[12.788 ; 17.975]", "[0.680 ; 2.450]", "[0.650 ; 1.827]", "[0.719 ; 2.190]")

I want to have two new vectors one including the lower Limits in numeric format as

lower <- c(0.741, 263.917, 12.788, 0.680, 0.650 , 0.719)

and othe including the upper Limits in numeric format like

upper <- c(2.233, 402.154, 17.975, 2.450, 1.827, 2.190)

Body:
Meanwhile, I came up with another base R solution

lower <- as.numeric(sub(".]*", "", sub(";.*", "", confint)))
upper <- as.numeric(sub("].*", "", sub(".*;", "", confint)))

Thank you all!


问:
async/await doesn't return the built array to the parent array.map()
In the following code, expiringContentsAllBU is populated within async/await function getOnlyContentWhatsNewReport which is inside the array.map(), but expiringContentsAllBU becomes empty when accessing it outside the businessUnits.map() function.

```<code>const getExpiringContents = async () => {
  let businessUnits = Object.keys(contentFulSpaces);
  let expiringContentsAllBU = [];
  businessUnits.map( async (bu) => {
      await getOnlyContentWhatsNewReport(bu, (err, result) => {
        if(result) {
          let expiringContentsByBU = {};
          expiringContentsByBU['businessUnit'] = bu;
          expiringContentsByBU['expiringContents'] = result;
          expiringContentsAllBU.push(JSON.parse(JSON.stringify(expiringContentsByBU)));
        } else console.log('No expiring contents found for WhatsNewSection');
      })
    });
    console.log('result', expiringContentsAllBU);
}
</code>```

答:
Using async with some lodash function for sanity will help -

getExpiringContents = async() => {
  let businessUnits = Object.keys(contentFulSpaces);

  let expiringContentsAllBU = await Promise.map(businessUnits, async businessUnit => {
    let expiringContents = await getOnlyContentWhatsNewReport(businessUnit);

    if (_.isEmpty(expiringContents)) {
      console.log('No expiring contents found for WhatsNewSection');
      return;
    }

    // Choosing names that match the output means you can use the destructuring operator
    let expiringContentsByBU = {
      businessUnit,
      expiringContents
    };

    // A more formalized "clone" function could help here.
    return _.cloneDeep(expiringContentsByBU);
  });

  // As this may contain undefined elements, remove those
  expiringContentsAllBU = _.compact(expiringContentsAllBU);

  console.log('result', expiringContentsAllBU);
}```

Body:
In the following code, expiringContentsAllBU is populated within async/await function getOnlyContentWhatsNewReport which is inside the array.map(), but expiringContentsAllBU becomes empty when accessing it outside the businessUnits.map() function.

const getExpiringContents = async () => {
  let businessUnits = Object.keys(contentFulSpaces);
  let expiringContentsAllBU = [];
  businessUnits.map( async (bu) => {
      await getOnlyContentWhatsNewReport(bu, (err, result) => {
        if(result) {
          let expiringContentsByBU = {};
          expiringContentsByBU['businessUnit'] = bu;
          expiringContentsByBU['expiringContents'] = result;
          expiringContentsAllBU.push(JSON.parse(JSON.stringify(expiringContentsByBU)));
        } else console.log('No expiring contents found for WhatsNewSection');
      })
    });
    console.log('result', expiringContentsAllBU);
}


问:
I was trying to complete a palindrome-check but reverse variable is not having the expected value
The following code should perform a check if the number provided by a user is palindrome or not, but the code in while loop reverse is always not equal to the number even when I enter 12321 as a value.

```<code>number=input("Type the number:")

temp=number
reverse=0
reminder=0

while temp!=0 :
      reminder=int(temp)%10
      reverse=reverse*10+reminder
      temp=int(temp)/10

if reverse==number :
      print("this is a palindrome number")
else:
      print("this is not a palindrome number")
</code>```

答:
The below code should work. Any input entered is always a string. While comparing the result with the input number, convert it to int. Also do floor division ("//").

```<code>number = input("Type the number:")

temp = int(number)
reverse = 0
reminder = 0

while temp != 0:
    reminder = temp % 10
    reverse = reverse*10+reminder
    print(reverse)
    temp = temp//10

if reverse == int(number):
    print("this is a palindrome number")
else:
    print("this is not a palindrome number")

</code>```

If you want a slightly better solution than all the dividing thing. Then the below code should work.

```<code>number = input("Type the number:")

if number.isdigit():
    if number == number[::-1]:
        print('this is a palindrome number')
    else:
        print('this is not a palindrome number')
else:
    print('Input entered is not a number')

</code>```

Body:
The following code should perform a check if the number provided by a user is palindrome or not, but the code in while loop reverse is always not equal to the number even when I enter 12321 as a value.

number=input("Type the number:")

temp=number
reverse=0
reminder=0

while temp!=0 :
      reminder=int(temp)%10
      reverse=reverse*10+reminder
      temp=int(temp)/10

if reverse==number :
      print("this is a palindrome number")
else:
      print("this is not a palindrome number")

Body:
The below code should work. Any input entered is always a string. While comparing the result with the input number, convert it to int. Also do floor division ("//").

number = input("Type the number:")

temp = int(number)
reverse = 0
reminder = 0

while temp != 0:
    reminder = temp % 10
    reverse = reverse*10+reminder
    print(reverse)
    temp = temp//10

if reverse == int(number):
    print("this is a palindrome number")
else:
    print("this is not a palindrome number")

If you want a slightly better solution than all the dividing thing. Then the below code should work.

number = input("Type the number:")

if number.isdigit():
    if number == number[::-1]:
        print('this is a palindrome number')
    else:
        print('this is not a palindrome number')
else:
    print('Input entered is not a number')


问:
How to set up bottlepy with threading for processing in background
I'm trying to set up a web service that processes a rendering in background, which takes a minute. While the rendering is in progress i want the server to be able to handle requests in parallel, returning Id {} not found or the result if there is one.

The tutorials i found mainly handle simple requests without much processing (http://bottlepy.org/docs/dev/async.html, using sleep to emulate processing). So i'm not quite sure how to implement threading - should the bottlepy routes be set up in a thread?

From http://bottlepy.org/docs/dev/tutorial_app.html#server-setup i know that the default server of bottlepy is single-threaded so i tried to switch to another server (PasteServer).

from bottle import Bottle, run, PasteServer
from service import startWithDirectArgs, default_out, default_out_dir
import threading

class BakingThread(threading.Thread):
    # lock = threading.Lock()
    isProcessRunning = False
    resultDict = {}
    currentId = 0

    def __init__(self, bakingId: str, args):
        super().__init__()
        self.bakingId = bakingId
        self.args = args

    def run(self):
        # with BakingThread.lock:
        if BakingThread.isProcessRunning:
            return False

        BakingThread.processRunning = True
        print("\033[1;32;49m" +
              "Starting baking process with id {}".format(self.bakingId) +
              "\033[0;37;49m")
        result = startWithDirectArgs(self.args)
        # result = calculatePi(100_0000_00)
        BakingThread.resultDict[self.bakingId] = str(result)
        BakingThread.isProcessRunning = False
        print("\033[1;32;49m" +
              "Finished baking process with id {}".format(self.bakingId) +
              "\033[0;37;49m")
        return result

def getUniqueId() -> str:
    BakingThread.currentId += 1
    return str(BakingThread.currentId)

def calculatePi(n: int) -> float:
    halfPi = 1.0
    zaehler = 2.0
    nenner = 1.0
    for i in range(n):
        halfPi *= zaehler / nenner
        if i % 2:
            zaehler += 2.0
        else:
            nenner += 2.0
    return 2.0 * halfPi

app = Bottle()

@app.route("/bakeFile/<fileParam>")
def bakeFile(fileParam: str):
    # args = {"file": fileParam, "out": default_out_dir + default_out}
    args = {
        "file": "build/igmodels/AOMaps/Scene.igxc",  # fileParam,
        "out": default_out_dir + default_out
    }
    print(args)
    cid = getUniqueId()
    bt = BakingThread(cid, args)
    bt.start()
    bt.join()

@app.route("/bakeUrl/<urlParam>")
def bakeUrl(urlParam: str):
    args = {"url": urlParam, "out": default_out_dir + default_out}
    print(args)
    cid = getUniqueId()
    bt = BakingThread(cid, args)
    bt.start()
    bt.join()

@app.route("/pullState/<bakingId>")
def pullState(bakingId: str):
    print("\033[1;33;49m" + "pullState id {}".format(BakingThread.currentId) +
          "\033[0;37;49m")
    result = BakingThread.resultDict.get(bakingId,
                                         "Id {} not found".format(bakingId))
    return result

app.run(host="localhost", port=8080, debug=True, server=PasteServer)

```

I expect to be able to run http://localhost:8080/bakeFile/3dGeometryFileName and while the rendering is running i expect calling http://localhost:8080/pullState/1 to respond with Id 1 not found. After the rendering is done the same call should return a result.

Edit: The rendering process was implemented in C++, bound with PyBind. The Global Interpreter Lock (GIL) prevented the concurrent execution of rendering and webserving, so i added py::gil_scoped_release release; before and py::gil_scoped_acquire acquire; after the expensive calculations in the C++ code. In the code above i added a snippet to calculate pi directly in python without C++/PyBind, so the bottlePy developer could point me onto that GIL thing. (Thx Marcel)

答:
Solved it.

The rendering process was implemented in C++, bound with PyBind. The Global Interpreter Lock (GIL) prevented the concurrent execution of rendering and webserving, so i added py::gil_scoped_release release; before and py::gil_scoped_acquire acquire; after the expensive calculations in the C++ code. In the code above i added a snippet to calculate pi directly in python without C++/PyBind, so the bottlePy developer could point me onto that GIL thing. (Thx Marcel)

Body:
I'm trying to set up a web service that processes a rendering in background, which takes a minute. While the rendering is in progress i want the server to be able to handle requests in parallel, returning Id {} not found or the result if there is one.

The tutorials i found mainly handle simple requests without much processing (http://bottlepy.org/docs/dev/async.html, using sleep to emulate processing). So i'm not quite sure how to implement threading - should the bottlepy routes be set up in a thread?

From http://bottlepy.org/docs/dev/tutorial_app.html#server-setup i know that the default server of bottlepy is single-threaded so i tried to switch to another server (PasteServer).

from bottle import Bottle, run, PasteServer
from service import startWithDirectArgs, default_out, default_out_dir
import threading

class BakingThread(threading.Thread):
    # lock = threading.Lock()
    isProcessRunning = False
    resultDict = {}
    currentId = 0

    def __init__(self, bakingId: str, args):
        super().__init__()
        self.bakingId = bakingId
        self.args = args

    def run(self):
        # with BakingThread.lock:
        if BakingThread.isProcessRunning:
            return False

        BakingThread.processRunning = True
        print("\033[1;32;49m" +
              "Starting baking process with id {}".format(self.bakingId) +
              "\033[0;37;49m")
        result = startWithDirectArgs(self.args)
        # result = calculatePi(100_0000_00)
        BakingThread.resultDict[self.bakingId] = str(result)
        BakingThread.isProcessRunning = False
        print("\033[1;32;49m" +
              "Finished baking process with id {}".format(self.bakingId) +
              "\033[0;37;49m")
        return result

def getUniqueId() -> str:
    BakingThread.currentId += 1
    return str(BakingThread.currentId)

def calculatePi(n: int) -> float:
    halfPi = 1.0
    zaehler = 2.0
    nenner = 1.0
    for i in range(n):
        halfPi *= zaehler / nenner
        if i % 2:
            zaehler += 2.0
        else:
            nenner += 2.0
    return 2.0 * halfPi

app = Bottle()

@app.route("/bakeFile/<fileParam>")
def bakeFile(fileParam: str):
    # args = {"file": fileParam, "out": default_out_dir + default_out}
    args = {
        "file": "build/igmodels/AOMaps/Scene.igxc",  # fileParam,
        "out": default_out_dir + default_out
    }
    print(args)
    cid = getUniqueId()
    bt = BakingThread(cid, args)
    bt.start()
    bt.join()

@app.route("/bakeUrl/<urlParam>")
def bakeUrl(urlParam: str):
    args = {"url": urlParam, "out": default_out_dir + default_out}
    print(args)
    cid = getUniqueId()
    bt = BakingThread(cid, args)
    bt.start()
    bt.join()

@app.route("/pullState/<bakingId>")
def pullState(bakingId: str):
    print("\033[1;33;49m" + "pullState id {}".format(BakingThread.currentId) +
          "\033[0;37;49m")
    result = BakingThread.resultDict.get(bakingId,
                                         "Id {} not found".format(bakingId))
    return result

app.run(host="localhost", port=8080, debug=True, server=PasteServer)

I expect to be able to run http://localhost:8080/bakeFile/3dGeometryFileName and while the rendering is running i expect calling http://localhost:8080/pullState/1 to respond with Id 1 not found. After the rendering is done the same call should return a result.

Edit: The rendering process was implemented in C++, bound with PyBind. The Global Interpreter Lock (GIL) prevented the concurrent execution of rendering and webserving, so i added py::gil_scoped_release release; before and py::gil_scoped_acquire acquire; after the expensive calculations in the C++ code. In the code above i added a snippet to calculate pi directly in python without C++/PyBind, so the bottlePy developer could point me onto that GIL thing. (Thx Marcel)


问:
Action after ActivateItem in Caliburn.Micro
I have a question. I have button where i launch ActivateItem:

```<code>    public void LoadTaskManagerPage()
    {
        this.ActivateItem(new TaskManagerViewModel(this.LoggedUser, this.repository));

        if (this.LoggedUser.GetUserTask() != null)
        {
            this.IsActiveTaskButtonVisible = Visibility.Visible;
            this.NotifyOfPropertyChange(() => this.IsActiveTaskButtonVisible);
        }
    }
</code>```

Is it possible to hang an app and go to if statement only, if ActivateItem ends?

How to wait for end of ActivateItem in Caliburn.Micro?

EDIT:

Trying something like:

```<code>    public void LoadTaskManagerPage()
    {
        var taskManagerTask = Task.Run(() => this.ActivateItem(new TaskManagerViewModel(this.LoggedUser, this.repository)));
        taskManagerTask.Wait();

        if (!this.LoggedUser.GetUserTask().IsTaskTakenByUser())
        {
            this.IsActiveTaskButtonVisible = Visibility.Visible;
            this.NotifyOfPropertyChange(() => this.IsActiveTaskButtonVisible);
        }
    }
</code>```

With Tasks, but when i click on LoadTaskManagerPage() it wont show any window, application hangs forever

EDIT2

Based on my issue on github, i upgraded Caliburn to alpha 4.0:

```<code>public void LoadTaskManagerPage()
    {
        this.ActivateItemAsync(new TaskManagerViewModel(this.LoggedUser, this.repository));

        if (!this.LoggedUser.GetUserTask().IsTaskTakenByUser())
        {
            //logic
        }
    }
</code>```

i changed ActiveItem() to ActiveItemAsync() but still, it hit if statement before active item will close. using async/await do the same

EDIT3

When i make async/await it still works the same, look at my view on the right. Its clicked, User Control not appear. In the same time (even when my User Control not show up) im hitting if statement too early. I want to hit it on User Control close.

答:
You should await the ActivateItemAsync method. This means that your LoadTaskManagerPage() should return a Task and you should await this one as well:

```<code>public async Task LoadTaskManagerPageAsynnc()
{
    await this.ActivateItemAsync(new TaskManagerViewModel(this.LoggedUser, this.repository));

    if (!this.LoggedUser.GetUserTask().IsTaskTakenByUser())
    {
        //logic
    }
}
</code>```

Body:
I have a question. I have button where i launch ActivateItem:

    public void LoadTaskManagerPage()
    {
        this.ActivateItem(new TaskManagerViewModel(this.LoggedUser, this.repository));

        if (this.LoggedUser.GetUserTask() != null)
        {
            this.IsActiveTaskButtonVisible = Visibility.Visible;
            this.NotifyOfPropertyChange(() => this.IsActiveTaskButtonVisible);
        }
    }

Is it possible to hang an app and go to if statement only, if ActivateItem ends?

How to wait for end of ActivateItem in Caliburn.Micro?

EDIT:

Trying something like:

    public void LoadTaskManagerPage()
    {
        var taskManagerTask = Task.Run(() => this.ActivateItem(new TaskManagerViewModel(this.LoggedUser, this.repository)));
        taskManagerTask.Wait();

        if (!this.LoggedUser.GetUserTask().IsTaskTakenByUser())
        {
            this.IsActiveTaskButtonVisible = Visibility.Visible;
            this.NotifyOfPropertyChange(() => this.IsActiveTaskButtonVisible);
        }
    }

With Tasks, but when i click on LoadTaskManagerPage() it wont show any window, application hangs forever

EDIT2

Based on my issue on github, i upgraded Caliburn to alpha 4.0:

public void LoadTaskManagerPage()
    {
        this.ActivateItemAsync(new TaskManagerViewModel(this.LoggedUser, this.repository));

        if (!this.LoggedUser.GetUserTask().IsTaskTakenByUser())
        {
            //logic
        }
    }

i changed ActiveItem() to ActiveItemAsync() but still, it hit if statement before active item will close. using async/await do the same

EDIT3

When i make async/await it still works the same, look at my view on the right. Its clicked, User Control not appear. In the same time (even when my User Control not show up) im hitting if statement too early. I want to hit it on User Control close.

Body:
You should await the ActivateItemAsync method. This means that your LoadTaskManagerPage() should return a Task and you should await this one as well:

public async Task LoadTaskManagerPageAsynnc()
{
    await this.ActivateItemAsync(new TaskManagerViewModel(this.LoggedUser, this.repository));

    if (!this.LoggedUser.GetUserTask().IsTaskTakenByUser())
    {
        //logic
    }
}


问:
linux: Print String at The End of Each Output Line
I execute below script

```<code>grep -i 'Exception' Exceptions.log |
sort |
uniq -c |
sort -n
</code>```

and get below result (each time result set will be different)

```<code>6 java.lang.NullPointerException
48 java.sql.SQLException
64 excep.NotFoundException
671 exception.ParseErrorException
690 Exception
</code>```

Actually I want to print the filename as well at the start or end of each line

```<code>6 java.lang.NullPointerException Exceptions
48 java.sql.SQLException Exceptions
64 excep.NotFoundException Exceptions
671 exception.ParseErrorException Exceptions
690 Exception Exceptions
</code>```

OR

```<code>Exceptions 6 java.lang.NullPointerException
Exceptions 48 java.sql.SQLException
Exceptions 64 excep.NotFoundException
Exceptions 671 exception.ParseErrorException
Exceptions 690 Exception
</code>```

Please help me to achieve this object.

答:
Yon can use -H option e.g. grep -H <SEARCH>

```<code>   -H, --with-filename
          Print the file name for each match.  This is  the  default  when
          there is more than one file to search.
</code>```

Check man page for more options

Body:
I execute below script

grep -i 'Exception' Exceptions.log |
sort |
uniq -c |
sort -n

and get below result (each time result set will be different)

6 java.lang.NullPointerException
48 java.sql.SQLException
64 excep.NotFoundException
671 exception.ParseErrorException
690 Exception

Actually I want to print the filename as well at the start or end of each line

6 java.lang.NullPointerException Exceptions
48 java.sql.SQLException Exceptions
64 excep.NotFoundException Exceptions
671 exception.ParseErrorException Exceptions
690 Exception Exceptions

OR

Exceptions 6 java.lang.NullPointerException
Exceptions 48 java.sql.SQLException
Exceptions 64 excep.NotFoundException
Exceptions 671 exception.ParseErrorException
Exceptions 690 Exception

Please help me to achieve this object.

Body:
Yon can use -H option e.g. grep -H <SEARCH>

   -H, --with-filename
          Print the file name for each match.  This is  the  default  when
          there is more than one file to search.

Check man page for more options


答:
You can solve it with small hacks: string representation of number and iterating with negative indices:

```<code>def is_palindrome(num):
    string = str(num)
    for i, e in enumerate(string):
        if e != string[-1 * (i+1)]:
            return False
    return True

is_palindrome(12344321)
</code>```

True

Title: I was trying to complete a palindrome-check but reverse variable is not having the expected value

Body:
You can solve it with small hacks: string representation of number and iterating with negative indices:

def is_palindrome(num):
    string = str(num)
    for i, e in enumerate(string):
        if e != string[-1 * (i+1)]:
            return False
    return True

is_palindrome(12344321)

True


问:
wxPython - Screen resolution 3000x2000 and DPI on 200% problem
I wrote an Tool with a wxPython GUI. On Full HD and less everything runs fine. A friend of mine tested a bit with my tool and he uses a Microsoft Surface Book laptop with a screen resolution of 3000x2000 and DPI set to 200% on Windows 10.

And he has the problem that everything in my GUI is very small.

I tried to prevent that with this piece of code:

```<code>import ctypes
try:
    ctypes.windll.shcore.SetProcessDpiAwareness(True)
except:
    pass
</code>```

But that didnt help at all. Does anybody have experience with a problem like that? What else could i try?

答:
I think there is already a question similar to this in Stackoverflow. Anyway.

So far I think the only thing you can do is to set the app to use System (Enhanced) in the High DPI scaling override box.

It does not matter if you do not have a .exe file. You can change the properties of the resulting python app window when you run it as python myApp.py.

If the picture is not enough, there are more details in the first question here.

Body:
I wrote an Tool with a wxPython GUI. On Full HD and less everything runs fine. A friend of mine tested a bit with my tool and he uses a Microsoft Surface Book laptop with a screen resolution of 3000x2000 and DPI set to 200% on Windows 10.

And he has the problem that everything in my GUI is very small.

I tried to prevent that with this piece of code:

import ctypes
try:
    ctypes.windll.shcore.SetProcessDpiAwareness(True)
except:
    pass

But that didnt help at all. Does anybody have experience with a problem like that? What else could i try?


问:
Botium informations are available but whats the happy path to setup up alexa skill starting point of Botium
What needs to be setup first then the second level what needs to be done .
Eg :

Install botium in vs code with package.json with dependencies

"chai": "^4.2.0",

"mocha": "^6.1.4",

"botium-bindings": "^2.0.13",

"botium-cli": "^0.0.50",

"botium-connector-alexa-avs": "^0.0.3",

"botium-connector-alexa-smapi": "^0.0.5"

2.In vs code Cmd ->node modules ->bin

botium-cli init
  botium-cli run

3.Botium.json file is available in node modules-> bin

4.Add the required dependencies (sample botium.json file for alexa required)

5.Define test cases (The below is for IBM watson.Need the same for amazon alexa)
[https://chatbotsmagazine.com/5-steps-automated-testing-of-chatbots-in-eclipse-ef4c3dcaf233][1]

6.Setup Botium box (This i know in browser with npmjs steps i've done it)

7.Setup Botium-bindings(where does this happen in IDE like eclipse or vs code)

So a happy path of installation steps is required .Now all we have is raw information which can't be connected together to find the start and end point

https://chatbotsmagazine.com/5-steps-automated-testing-of-chatbots-in-eclipse-ef4c3dcaf233

答:
First step, install Botium-CLI and connector:

```<code>> npm install -g botium-cli
> npm install -g botium-connector-alexa-smapi
> botium-cli init
> botium-cli run
</code>```

Second step, connect your Alexa Skill to Botium by adapting the botium.json file. This requires multiple steps, all of them are described here (Install ask-cli, retrieve credentials, copy to botium.json).

For an introduction what Botium is and how to get started writing test cases, I recommend the Botium in a nutshell blog series.

Body:
First step, install Botium-CLI and connector:

> npm install -g botium-cli
> npm install -g botium-connector-alexa-smapi
> botium-cli init
> botium-cli run

Second step, connect your Alexa Skill to Botium by adapting the botium.json file. This requires multiple steps, all of them are described here (Install ask-cli, retrieve credentials, copy to botium.json).

For an introduction what Botium is and how to get started writing test cases, I recommend the Botium in a nutshell blog series.


问:
Argument - simple prolog
Want to expand the argument q(M,N):- that should evaluate true , only if
we can express M as sum of two numbers , that also these same two numbers would give the the product of N. Meaning something like A+B=M and A*B=N (M,N>0 both Integers)

So I've tried something like :

```<code>sum(A,B,M) :- M is A+B.

prod(A,B,N) :- N is A*B.

q(M,N) :- sum(A,B,M),
          prod(A,B,N).
</code>```

But yeah not a great plan.

some expected outcomes should be:

```<code>| ?- q(18,45).
yes
| ?- q(45,18).
no
| ?- q(4,4).
yes
| ?- q(5,5).
no
| ?- q(16,64).
yes
| ?- q(12,25).
no
| ?- q(25,24).
yes
| ?- q(36,120).
no
| ?- q(100,2499).
yes
| ?- q(100,267).
no
| ?- q(653,98770).
yes
| ?- q(653,98880).
no
</code>```

答:
A very basic solution for your problem, using between/3 from swi prolog, without heavilly modifing your program is:

```<code>sum(A,B,M) :- M is A+B.

prod(A,B,N) :- N is A*B.

q(M,N) :-
    between(0,1000,A),
    between(0,1000,B),
    sum(A,B,M),
    prod(A,B,N).
</code>```

In this case, all numbers between 0 and 1000 are considered for A and B. However, there are some weakness. For instance, values for A and B can be exchanged (q(18,45) succeeds for A = 3 and B = 15 and A = 15 and B = 3). To remove this redundancy you can impose B < A. To further improve the algorithm, you can set a range for A and B based on the value of the sum and the product. Certainly both A and B must be less than the value M in your code. Like:

```<code>q(M,N) :-
    between(0,M,A),
    between(0,A,B),
    M is A+B,
    N is A*B.
</code>```

You can add further constraints to improve the performances, for instance considering cases where the product is 0 etc...

You can use also clpfd library to solve this problem.

Title: Argument - simple prolog

Body:
Want to expand the argument q(M,N):- that should evaluate true , only if
we can express M as sum of two numbers , that also these same two numbers would give the the product of N. Meaning something like A+B=M and A*B=N (M,N>0 both Integers)

So I've tried something like :

sum(A,B,M) :- M is A+B.

prod(A,B,N) :- N is A*B.

q(M,N) :- sum(A,B,M),
          prod(A,B,N).

But yeah not a great plan.

some expected outcomes should be:

| ?- q(18,45).
yes
| ?- q(45,18).
no
| ?- q(4,4).
yes
| ?- q(5,5).
no
| ?- q(16,64).
yes
| ?- q(12,25).
no
| ?- q(25,24).
yes
| ?- q(36,120).
no
| ?- q(100,2499).
yes
| ?- q(100,267).
no
| ?- q(653,98770).
yes
| ?- q(653,98880).
no

Body:
A very basic solution for your problem, using between/3 from swi prolog, without heavilly modifing your program is:

sum(A,B,M) :- M is A+B.

prod(A,B,N) :- N is A*B.

q(M,N) :-
    between(0,1000,A),
    between(0,1000,B),
    sum(A,B,M),
    prod(A,B,N).

In this case, all numbers between 0 and 1000 are considered for A and B. However, there are some weakness. For instance, values for A and B can be exchanged (q(18,45) succeeds for A = 3 and B = 15 and A = 15 and B = 3). To remove this redundancy you can impose B < A. To further improve the algorithm, you can set a range for A and B based on the value of the sum and the product. Certainly both A and B must be less than the value M in your code. Like:

q(M,N) :-
    between(0,M,A),
    between(0,A,B),
    M is A+B,
    N is A*B.

You can add further constraints to improve the performances, for instance considering cases where the product is 0 etc...

You can use also clpfd library to solve this problem.