答:
Both lattice and ggplot offer solutions. Regardless, as @davide suggests, "melting" your data or converting it from a "wide" format to a "long" is a very good practice. Values of interest are placed in a single variable and a parallel factor is created to identify the group associated with each value.

This can be done in base R by several methods. The use of stack() is shown here. In addition, by converting the factor or character representation of the date into a Date object, the plotting routines in lattice and ggplot2 will do a better job managing axes labels for you.

```<code>df <- data.frame(Date = as.Date(plotData$Date), stack(plotData[2:3]))
(names(df)) # stack names the data 'values and the grouping factor 'ind'
levels(df$ind) <- c("ARIMA+GARCH", "Buy & Hold") # simplifies legends
</code>```

Here's a somewhat simple plot with few additions for grid lines and legend (key):

```<code>xyplot(values ~ Date, data = df, groups = ind, type = c("g", "l"), auto.key = TRUE)
</code>```

The plots can be customized with lattice through panel functions and elements in auto.key. Although using col = c("darkred", "darkblue") at the top level of the function would color the lines in the plot, passing it through the optional par.settings argument makes it available for the legend function.

```<code>xyplot(values ~ Date, data = df, groups = ind,
  panel = function(...) {
    panel.grid(h = -1, v = -1)
    panel.refline(h = 0, lwd = 3)
    panel.xyplot(..., type = "l")},
  auto.key = list(points = FALSE, lines = TRUE, columns = 2),
  par.settings = list(superpose.line = list(col = c("darkred", "darkblue"))))
</code>```

Title: How to xyplot multiple lines in R

Body:
I would like to plot graphs with multiple lines in R like this:

2 lines

x axis is date

y axis is the log return

I have data in 3 vectors

print(class(TradeDate))
print(class(ArimaGarchCurve))
print(class(CompareCurve))
---------------------------------------------
[1] "factor"
[1] "numeric"
[1] "numeric"

I search and found that xyplot may be useful, but I don't know how to use it. I have tried.

pdf("Testing.pdf")
plotData <- data.frame(Date=TradeDate,
                       Arima=ArimaGarchCurve,
                       BuyHold=BuyHoldCurve)
print(xyplot(
    Arima ~ Date,
    data=plotData,
    superpose=T,
    col=c("darkred", "darkblue"),
    lwd=2,
    key=list(
        text=list(
            c("ARIMA+GARCH", "Buy & Hold")
        ),
        lines=list(
            lwd=2, col=c("darkred", "darkblue")
        )
    )
))
dev.off()

Here is the result:

Learn from here

Thank you very much.

dput(head(plotData,20))
structure(list(Date = structure(1:20, .Label = c("2001-12-03",
"2001-12-04", "2001-12-05", "2001-12-06", "2001-12-07", "2001-12-10",
"2001-12-11", "2001-12-12", "2001-12-13", "2001-12-14", "2001-12-17",
"2001-12-18", "2001-12-19", "2001-12-20", "2001-12-21", "2001-12-24",
"2001-12-25", "2001-12-26", "2001-12-27", "2001-12-28", "2001-12-31",
"2002-01-01", "2002-01-02", "2002-01-03", "2002-01-04", "2002-01-07",
"2019-05-22", "2019-05-23"), class = "factor"), Arima = c(-0.0134052258713131,
-0.00542641764174324, 0.0128513670753771, 0.0282761455973665,
0.0179931884968989, 0.0281714817318116, 0.0435962602538011, 0.0462004298658309,
0.0194592964361352, 0.0248069155406948, 0.032807001046888, 0.0381120657516546,
0.0381120657516546, 0.030090589527961, -0.0146168717909267, -0.00630652663076437,
-0.00630652663076437, -0.00630652663076437, 0.0100429785563596,
0.0100429785563596), BuyHold = c(-0.0134052258713131, -0.00542641764174324,
0.0128513670753771, 0.0282761455973665, 0.0384544388322794, 0.0281714817318116,
0.0125050470584384, 0.0151092166704679, -0.0116319167592278,
-0.0170082867113405, -0.0090082012051471, -0.00370313650038065,
-0.00370313650038065, -0.0117246127240743, -0.056432074042962,
-0.0481217288827996, -0.0481217288827996, -0.0481217288827996,
-0.0317722236956757, -0.0317722236956757)), row.names = c(NA,
20L), class = "data.frame")

Body:
Both lattice and ggplot offer solutions. Regardless, as @davide suggests, "melting" your data or converting it from a "wide" format to a "long" is a very good practice. Values of interest are placed in a single variable and a parallel factor is created to identify the group associated with each value.

This can be done in base R by several methods. The use of stack() is shown here. In addition, by converting the factor or character representation of the date into a Date object, the plotting routines in lattice and ggplot2 will do a better job managing axes labels for you.

df <- data.frame(Date = as.Date(plotData$Date), stack(plotData[2:3]))
(names(df)) # stack names the data 'values and the grouping factor 'ind'
levels(df$ind) <- c("ARIMA+GARCH", "Buy & Hold") # simplifies legends

Here's a somewhat simple plot with few additions for grid lines and legend (key):

xyplot(values ~ Date, data = df, groups = ind, type = c("g", "l"), auto.key = TRUE)

The plots can be customized with lattice through panel functions and elements in auto.key. Although using col = c("darkred", "darkblue") at the top level of the function would color the lines in the plot, passing it through the optional par.settings argument makes it available for the legend function.

xyplot(values ~ Date, data = df, groups = ind,
  panel = function(...) {
    panel.grid(h = -1, v = -1)
    panel.refline(h = 0, lwd = 3)
    panel.xyplot(..., type = "l")},
  auto.key = list(points = FALSE, lines = TRUE, columns = 2),
  par.settings = list(superpose.line = list(col = c("darkred", "darkblue"))))


来源: stackexchange

问:
TStringGrid doesn't recognize VK_DELETE as a keypress
I have a number of TStringGrids inside TTab's and have been using

if (Key==VK_RETURN) for years (its an old app) as the trigger to execute code pertaining the the cell entry.

I would now like the option to delete the Cell contents, by writing a empty string to it, so tried using
if (Key==VK_DELETE)

yet the Delete Button does not trigger the OnKeyPress event at all in my case.

I was hoping to capture the event via the following code pertaining to the specific active Stringrid1

```<code>void __fastcall TPagesDlgLoadEditorFixed::StringGrid1KeyPress(TObject
*Sender, char &Key)
{
   int Grid = 1;
   EntriesOnStringGrid(Key, Grid);
}
</code>```

and with the KeyPress then passed on code that is common to all the StringGrids, as follows:

```<code>void TPagesDlgLoadEditorFixed::EntriesOnStringGrid(char &Key, int Grid)
{

 if (Key==VK_RETURN)
 {
   //code works fine
 }
 if (Key==VK_DELETE)
 {
   //code has no effect
 }

}
</code>```

However whilst in debug mode, one can see that the StringGrid1KeyPress event is not triggered at all by the "Delete" button.

Any advise would be greatly appreciated.

答:
It's generally better to use OnKeyUp and OnKeyDown when checking for virtual key codes instead of OnKeyPress.

So using that should fix your problem and then it will detect VK_DELETE when it's pressed or let go.

ContentLicense: CC BY-SA 4.0

Body:
I have a number of TStringGrids inside TTab's and have been using

if (Key==VK_RETURN) for years (its an old app) as the trigger to execute code pertaining the the cell entry.

I would now like the option to delete the Cell contents, by writing a empty string to it, so tried using
if (Key==VK_DELETE)

yet the Delete Button does not trigger the OnKeyPress event at all in my case.

I was hoping to capture the event via the following code pertaining to the specific active Stringrid1

void __fastcall TPagesDlgLoadEditorFixed::StringGrid1KeyPress(TObject
*Sender, char &Key)
{
   int Grid = 1;
   EntriesOnStringGrid(Key, Grid);
}

and with the KeyPress then passed on code that is common to all the StringGrids, as follows:

void TPagesDlgLoadEditorFixed::EntriesOnStringGrid(char &Key, int Grid)
{

 if (Key==VK_RETURN)
 {
   //code works fine
 }
 if (Key==VK_DELETE)
 {
   //code has no effect
 }

}

However whilst in debug mode, one can see that the StringGrid1KeyPress event is not triggered at all by the "Delete" button.

Any advise would be greatly appreciated.


问:
Update the provider array & increment count only if providerId is not there in Document
I am stuck in a situation like this. I have the following document.

```<code>{
    "_id" : ObjectId("5ceba7c419b48423e452972a"),
    "userId" : ObjectId("5ceba7c419b48423e4529727"),
    "providers" : [
        "1689736266",
        "1598763690",
        "1528069614",
        "1831364272",
        "1548463045",
        "1245301159",
        "1386616399",
        "1790775971",
        "1629462130",
        "1992169783"
    ],
    "countByType" : {
        "doctors" : 6,
        "labs" : 0,
        "hospitals" : 0,
        "imagingCenters" : 0,
        "other" : 4
    }
}
</code>```

Initially, I fetch the providerArray from elastic search, added to providers array and incremented the count by using the following query.

```<code>let updateProviderId = await userProviderCollection.update(
   regUserId, {
     $set:  {
       providers: combinedProviderArray,
       countByType: providerCountType
     }
});
</code>```

where combinedProviderArray is a combined array of providers. ProviderId is created when a new report is generated. The above condition will work if reports already there.
But when a new report comes, I need to check in providers array and increment the count if not in an array, else do nothing. How can I achieve this.

Please see the code below when a report with providerId is already in an array.

```<code>// Searching for Providers in Elastic Search
   let searchForProviders = await esHelper.getProvidersById(combinedProviderArray, true);
   searchForProviders.forEach((getCategory) => {
     let prCategory = getCategory.category;
     prCategory.forEach((cat) => {

       // Combining categories
       categoryArray = categoryArray.concat(cat);
     });
   });

   let counts = {
     "doctor": 0,
     "laboratory": 0,
     "hospital": 0,
     "imagingcenter": 0,
     "other": 0
   };
   let x;
   categoryArray.forEach(function(x) {
     counts[x] = (counts[x] || 0)+1;
   });

   let providerCountType = {
     "doctors": counts.doctor,
     "labs": counts.laboratory,
     "hospitals": counts.hospital,
     "imagingCenters": counts.imagingcenter,
     "other": counts.other
   }

   // Updating npiId & category count
   userproviderData.getDataSource().connector.connect(async (err, db) => {
     let userProviderCollection = db.collection("UserProviders");
     let regUserId = { userId: userId};
     let updateProviderId = await userProviderCollection.update(
       regUserId, {
         $set:  {
           providers: combinedProviderArray,
           countByType: providerCountType
         }
       });
   });
</code>```

Please provide an appropriate solution for the same. Any help would be really appreciated. I am stuck on how to add a provider to array & increment the count according to that.

答:
Instead of rebuilding the array every time, you can use $addToSet. This has the effect of adding the value to the array, but only if it is not already present...

```<code>let updateProviderId = await userProviderCollection.update(
   regUserId, {
     $addToSet:  {
       providers: providerID
     }
});
</code>```

As for the counts, it can be done similarly, using $inc.

```<code>let updateProviderId = await userProviderCollection.update(
   regUserId, {
     $inc:  {
       "countByType.doctors": 1
     }
});
</code>```

You could build your increment object easily:

```<code>let $inc= {
  "countByType.doctors": counts.doctor,
  "countByType.labs": counts.laboratory,
  "countByType.hospitals": counts.hospital,
  "countByType.imagingCenters": counts.imagingcenter,
  "countByType.other": counts.other
}
let updateProviderId = await userProviderCollection.update(regUserId, {$inc});
</code>```

If you are just adding one, and want to do everything at the same time, you could just the first 2 examples:

```<code>let $inc = {};
$inc["countByType."+categoryName] =  1;
let updateProviderId = await userProviderCollection.update(
   regUserId, {
     $addToSet:  {
       providers: providerID
     },
     $inc
});
</code>```

But it would increment the count even tough the provider was already present... So you'd need to check if the $addToSet worked, and then do the increment:

```<code>let updateProviderId = await userProviderCollection.update(
   regUserId, {
     $addToSet:  {
       providers: providerID
     }
});
if(updateProviderId["nMatched"] === 1 //A document was matched
    && updateProviderId["nModified"] === 1 //A document was modified
){
    let updateProviderCount = await userProviderCollection.update(regUserId, {$inc});
}
</code>```

Body:
I am stuck in a situation like this. I have the following document.

{
    "_id" : ObjectId("5ceba7c419b48423e452972a"),
    "userId" : ObjectId("5ceba7c419b48423e4529727"),
    "providers" : [
        "1689736266",
        "1598763690",
        "1528069614",
        "1831364272",
        "1548463045",
        "1245301159",
        "1386616399",
        "1790775971",
        "1629462130",
        "1992169783"
    ],
    "countByType" : {
        "doctors" : 6,
        "labs" : 0,
        "hospitals" : 0,
        "imagingCenters" : 0,
        "other" : 4
    }
}

Initially, I fetch the providerArray from elastic search, added to providers array and incremented the count by using the following query.

let updateProviderId = await userProviderCollection.update(
   regUserId, {
     $set:  {
       providers: combinedProviderArray,
       countByType: providerCountType
     }
});

where combinedProviderArray is a combined array of providers. ProviderId is created when a new report is generated. The above condition will work if reports already there.
But when a new report comes, I need to check in providers array and increment the count if not in an array, else do nothing. How can I achieve this.

Please see the code below when a report with providerId is already in an array.

// Searching for Providers in Elastic Search
   let searchForProviders = await esHelper.getProvidersById(combinedProviderArray, true);
   searchForProviders.forEach((getCategory) => {
     let prCategory = getCategory.category;
     prCategory.forEach((cat) => {

       // Combining categories
       categoryArray = categoryArray.concat(cat);
     });
   });

   let counts = {
     "doctor": 0,
     "laboratory": 0,
     "hospital": 0,
     "imagingcenter": 0,
     "other": 0
   };
   let x;
   categoryArray.forEach(function(x) {
     counts[x] = (counts[x] || 0)+1;
   });

   let providerCountType = {
     "doctors": counts.doctor,
     "labs": counts.laboratory,
     "hospitals": counts.hospital,
     "imagingCenters": counts.imagingcenter,
     "other": counts.other
   }

   // Updating npiId & category count
   userproviderData.getDataSource().connector.connect(async (err, db) => {
     let userProviderCollection = db.collection("UserProviders");
     let regUserId = { userId: userId};
     let updateProviderId = await userProviderCollection.update(
       regUserId, {
         $set:  {
           providers: combinedProviderArray,
           countByType: providerCountType
         }
       });
   });

Please provide an appropriate solution for the same. Any help would be really appreciated. I am stuck on how to add a provider to array & increment the count according to that.

Body:
Instead of rebuilding the array every time, you can use $addToSet. This has the effect of adding the value to the array, but only if it is not already present...

let updateProviderId = await userProviderCollection.update(
   regUserId, {
     $addToSet:  {
       providers: providerID
     }
});

As for the counts, it can be done similarly, using $inc.

let updateProviderId = await userProviderCollection.update(
   regUserId, {
     $inc:  {
       "countByType.doctors": 1
     }
});

You could build your increment object easily:

let $inc= {
  "countByType.doctors": counts.doctor,
  "countByType.labs": counts.laboratory,
  "countByType.hospitals": counts.hospital,
  "countByType.imagingCenters": counts.imagingcenter,
  "countByType.other": counts.other
}
let updateProviderId = await userProviderCollection.update(regUserId, {$inc});

If you are just adding one, and want to do everything at the same time, you could just the first 2 examples:

let $inc = {};
$inc["countByType."+categoryName] =  1;
let updateProviderId = await userProviderCollection.update(
   regUserId, {
     $addToSet:  {
       providers: providerID
     },
     $inc
});

But it would increment the count even tough the provider was already present... So you'd need to check if the $addToSet worked, and then do the increment:

let updateProviderId = await userProviderCollection.update(
   regUserId, {
     $addToSet:  {
       providers: providerID
     }
});
if(updateProviderId["nMatched"] === 1 //A document was matched
    && updateProviderId["nModified"] === 1 //A document was modified
){
    let updateProviderCount = await userProviderCollection.update(regUserId, {$inc});
}


问:
Is defining a default value for a Boolean input property in Angular bad practice?
I'm looking through an old Angular project and one component has an input property:

```<code>@Input()
isNotAdmin = true;
</code>```

Is directly assigning a value to the property within it's declaration like this considered bad practice? I understand that it depends on the context e.g. if we would like each of these components to have this property set to true if not stated, but I feel like boolean properties should be explicitly stated either way (true or false). Should the approach instead have a setter method as the input and a check to see if a value is passed, and if not, assign the property a default value?

答:
No, it isn't a bad practice.

In fact, it would even be a best practice.

The reason is that inputs are set only on ngOnChanges runs, so that means that until this function is ran, your value is undefined.

For a boolean, it's no big deal. But imagine a complex object, and you do operations on that object, something like

```<code>if (this.myInput.type.ref.date.modifiedAt.includes('+1'))
</code>```

Then your condition would throw an error.

Moreover, this allows for no-value inputs : imagine you create a custom select, and you want to assign a multiple input : what is the best approach for a dev ?

Personnaly, I like the first one. To achieve that, you can use this :

```<code>@Input('multiple') doNotShowMultipleValues = true;
</code>```

When the dev will use the first syntax, the value will become '', which is falsy, thus inverting the condition. Something you can not do without an initial value !

But in the end, it all comes to personal preference, and if you don't feel confident assigning a default value, then you should simply not do it.

Body:
I'm looking through an old Angular project and one component has an input property:

@Input()
isNotAdmin = true;

Is directly assigning a value to the property within it's declaration like this considered bad practice? I understand that it depends on the context e.g. if we would like each of these components to have this property set to true if not stated, but I feel like boolean properties should be explicitly stated either way (true or false). Should the approach instead have a setter method as the input and a check to see if a value is passed, and if not, assign the property a default value?

Body:
No, it isn't a bad practice.

In fact, it would even be a best practice.

The reason is that inputs are set only on ngOnChanges runs, so that means that until this function is ran, your value is undefined.

For a boolean, it's no big deal. But imagine a complex object, and you do operations on that object, something like

if (this.myInput.type.ref.date.modifiedAt.includes('+1'))

Then your condition would throw an error.

Moreover, this allows for no-value inputs : imagine you create a custom select, and you want to assign a multiple input : what is the best approach for a dev ?

Personnaly, I like the first one. To achieve that, you can use this :

@Input('multiple') doNotShowMultipleValues = true;

When the dev will use the first syntax, the value will become '', which is falsy, thus inverting the condition. Something you can not do without an initial value !

But in the end, it all comes to personal preference, and if you don't feel confident assigning a default value, then you should simply not do it.


问:
How to save variables in Variable Explorer of Spyder IDE
I am using Spyder IDE. I want to save the variables in the Variable Explorer of Spyder to a csv/excel/pdf. I am automating a task. Hence I want to save the results every time I run the script. My variable explorer looks like this:

Or is there a way I can write all the variables to a csv or pdf?

答:
It may not be the most efficient way but what about:

```<code>import pandas as pd
import time
</code>```

you save every variable as a dataframe, but to do it with float/int values you have to create dataframe like:

```<code>b = 4
x = pd.DataFrame({"col" : [b]})
</code>```

use time to mark time of file creation

```<code>t = time.localtime()
timestamp = time.strftime('%b-%d-%Y_%H%M', t)

writer = pd.ExcelWriter(path + '\\results_EC_' + timestamp  + ".xlsx")
</code>```

at this point select all dataframes, which you want to export:

```<code>x.to_excel(writer,sheet_name="Results1", index = False)

writer.save()
print("done")
</code>```

Body:
It may not be the most efficient way but what about:

import pandas as pd
import time

you save every variable as a dataframe, but to do it with float/int values you have to create dataframe like:

b = 4
x = pd.DataFrame({"col" : [b]})

use time to mark time of file creation

t = time.localtime()
timestamp = time.strftime('%b-%d-%Y_%H%M', t)

writer = pd.ExcelWriter(path + '\\results_EC_' + timestamp  + ".xlsx")

at this point select all dataframes, which you want to export:

x.to_excel(writer,sheet_name="Results1", index = False)

writer.save()
print("done")


问:
printing the cpus a task is allowed to run on?
I'm trying to printk the cpus that a specific task is allowed to run on.

Inside struct task_struct (which can be find here) there's the cpumask_t cpus_allowed which from what I understand contains exactly what Im looking for .
Is that right ?

If so, how do I extract the cpus' numbers that are allowed ?

for example my comp has 8 logical cores - so Im expecting that somewhere inside cpus_allowed I can find those numbers (for example - 0,2,5)

答:
Use the function cpumask_pr_args() defined inside cpumask.h.

Usage:

```<code> printk("%*pbl\n", cpumask_pr_args(mask));
</code>```

See here for information about the %*pbl placeholder.

Body:
Use the function cpumask_pr_args() defined inside cpumask.h.

Usage:

 printk("%*pbl\n", cpumask_pr_args(mask));

See here for information about the %*pbl placeholder.


问:
OpenSSl error using composer behind proxy on ubuntu
when i tried to run composer install on ubuntu 18.04 i got this:

```<code>The "https://packagist.org/packages.json" file could not be downloaded: SSL
operation failed with code 1. OpenSSL Error messages:
error:1408F10B:SSL routines:ssl3_get_record:wrong version number
Failed to enable crypto
failed to open stream: operation failed
</code>```

I got the rigth proxy configuration on my /etc/apt/apt.conf and /etc/profile, but the error goes on and on, no mather what i do.

答:
The proxy configuration needed for using composer is located in /etc/enviroment file.</p>

```<code>PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games"

http_proxy="http://username:password@10.4.1.20:3128"
https_proxy="http://username:password@10.4.1.20:3128"
</code>```

Body:
when i tried to run composer install on ubuntu 18.04 i got this:

The "https://packagist.org/packages.json" file could not be downloaded: SSL
operation failed with code 1. OpenSSL Error messages:
error:1408F10B:SSL routines:ssl3_get_record:wrong version number
Failed to enable crypto
failed to open stream: operation failed

I got the rigth proxy configuration on my /etc/apt/apt.conf and /etc/profile, but the error goes on and on, no mather what i do.

Body:
The proxy configuration needed for using composer is located in /etc/enviroment file.

PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games"

http_proxy="http://username:password@10.4.1.20:3128"
https_proxy="http://username:password@10.4.1.20:3128"


问:
How do I prevent Selenium RC from stealing window focus while my tests are running?
I know I'm probably in a small minority, but I have to use my machine at the same time my tests are running. The thing that always gets in my way is that the browser window is always stealing focus when I run test cases using Selenium RC. Which prevents me from running my tests more than once a day, at the end of the day right before I log out. I tried Selenium Grid, but I can't get it to only listen for requests on localhost, not 0.0.0.0 (a requirement from my network admin).

I've dug through the Selenium documentation, and tons of Selenium sites, but I haven't been able to find a definitive answer. Can I prevent Selenium RC tests from Stealing windows focus while my test are running?

I'm using Firefox 3.6.13.

答:
We solved this problem by sharing the selenium instance between tests. Then selenium only tries to steal focus once during the entire test run, which isn't too bad.

If you're using JUnit to script Selenium, you can use Spring's SpringJUnit4ClassRunner to inject the selenium instance as a bean.

Define a test context for Spring selenium.xml (google it if you're not familiar with how to set up a Spring XML configuration file) and include a selenium instance:

```<code><bean class="com.thoughtworks.selenium.DefaultSelenium" name="selenium">
    <constructor-arg index="0">
        <value>localhost</value>
    </constructor-arg>
    <constructor-arg index="1">
        <value>4444</value>
    </constructor-arg>
    <constructor-arg index="2">
        <value>*firefox</value>
    </constructor-arg>
    <constructor-arg index="3">
        <value>http://localhost:8080/webapp/</value>
    </constructor-arg>
</bean>
</code>```

Then in your test, inject the selenium instance instead of new'ing it:

```<code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:selenium.xml")
public class WebappIT {

    @Resource
    private Selenium selenium;

    ... test code ...

}
</code>```

I've simplified this somewhat, in our actual code we wrap the selenium instance in a provider class so that we can call selenium.start() once only.

ContentLicense: CC BY-SA 3.0

Body:
We solved this problem by sharing the selenium instance between tests. Then selenium only tries to steal focus once during the entire test run, which isn't too bad.

If you're using JUnit to script Selenium, you can use Spring's SpringJUnit4ClassRunner to inject the selenium instance as a bean.

Define a test context for Spring selenium.xml (google it if you're not familiar with how to set up a Spring XML configuration file) and include a selenium instance:

<bean class="com.thoughtworks.selenium.DefaultSelenium" name="selenium">
    <constructor-arg index="0">
        <value>localhost</value>
    </constructor-arg>
    <constructor-arg index="1">
        <value>4444</value>
    </constructor-arg>
    <constructor-arg index="2">
        <value>*firefox</value>
    </constructor-arg>
    <constructor-arg index="3">
        <value>http://localhost:8080/webapp/</value>
    </constructor-arg>
</bean>

Then in your test, inject the selenium instance instead of new'ing it:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:selenium.xml")
public class WebappIT {

    @Resource
    private Selenium selenium;

    ... test code ...

}

I've simplified this somewhat, in our actual code we wrap the selenium instance in a provider class so that we can call selenium.start() once only.


问:
mouseenter and mouseleave keep triggering when i have mouse focus over the element
I am trying to make a tooltip for a hover over icon:

```<code><div class="question-description-tooltip" style="display:inline-block;">
    <img class="question-icon" src="icon.png" />
    <span class="question-description-tooltip-text">Description</span>
</div>

$('.question-icon').on({
   mouseenter: function (event) {
       showTooltip(event,this);
   },
   mouseleave: function () {
       $('.question-description-tooltip-text').css('visibility','hidden');
   }
 });
</code>```

So when I hover over icon the mouseenter and mouseleave events keep triggering so tooltip is flickering and I don't know why.

Css of elements:

```<code>.question-description-tooltip .question-description-tooltip-text {
  background-color: #4c4c4c;
  visibility: hidden;
  white-space: pre-wrap;
  color: #fff;
  text-align: center;
  border-radius: 6px;
  /*Position the tooltip*/
  position: absolute;
  z-index: 1;
  padding: 7px;
}
</code>```

showTooltip function:

```<code>    showTooltip(e, ui){
       //calculate margins so I reposition tooltip it is above icon,
       because description always has differen width and height
       var descriptionTooltip = $(ui).parent().find('.question-description-tooltip-text');
       descriptionTooltip.css("margin-left", -marginLeft);
       descriptionTooltip.css("margin-top", -marginTop);
       $(ui).parent().find('.question-description-tooltip-text').css('visibility', 'visible');
    }
</code>```

答:
use mouseover() and mouseout() instead
https://api.jquery.com/category/events/mouse-events/

Body:
I am trying to make a tooltip for a hover over icon:

    Description

$('.question-icon').on({
   mouseenter: function (event) {
       showTooltip(event,this);
   },
   mouseleave: function () {
       $('.question-description-tooltip-text').css('visibility','hidden');
   }
 });

So when I hover over icon the mouseenter and mouseleave events keep triggering so tooltip is flickering and I don't know why.

Css of elements:

.question-description-tooltip .question-description-tooltip-text {
  background-color: #4c4c4c;
  visibility: hidden;
  white-space: pre-wrap;
  color: #fff;
  text-align: center;
  border-radius: 6px;
  /*Position the tooltip*/
  position: absolute;
  z-index: 1;
  padding: 7px;
}

showTooltip function:

    showTooltip(e, ui){
       //calculate margins so I reposition tooltip it is above icon,
       because description always has differen width and height
       var descriptionTooltip = $(ui).parent().find('.question-description-tooltip-text');
       descriptionTooltip.css("margin-left", -marginLeft);
       descriptionTooltip.css("margin-top", -marginTop);
       $(ui).parent().find('.question-description-tooltip-text').css('visibility', 'visible');
    }


问:
How to align the origin in a 3-d figure?
I want to set origins in x and y axis same in a 3-d figure using matplotlib. However, I cannot do this. My code is:

```<code>axs.set_xlim([-60, 60])
axs.set_ylim([-60, 60])
</code>```

I also try:

```<code>plt.xlim([-60, 60])
plt.xlim([-60, 60])
</code>```

both of them are not work.

答:
```<code>ax = plt.subplot(projection='3d')
ax.set_xlim(-60, 60)
ax.set_ylim(-60, 60)
ax.set_zlim(-60, 60)
</code>```

Body:
I want to set origins in x and y axis same in a 3-d figure using matplotlib. However, I cannot do this. My code is:

axs.set_xlim([-60, 60])
axs.set_ylim([-60, 60])

I also try:

plt.xlim([-60, 60])
plt.xlim([-60, 60])

both of them are not work.


问:
Submit gcloud ai-platform training job programmatically (from python code)
To submit a training job from gcloud ai-platform (ex gcloud ml-engine) you use the following command from the gcloud SDK:

gcloud ai-platform jobs submit COMMAND [GCLOUD_WIDE_FLAG …]

I want to do this programmatically, i.e. from python code (or any other language). Something like

```<code>import gcloud-ai-platform as gap
gap.submit_job(COMMAND)
</code>```

Is there such a command? And if it does not exist, how can I build a workaround? (using gcloud sdk programmatically)

答:
For submitting a training job, here you have an example that you can follow.

It has both methods, using gcloud and the equivalent python code.

Body:
To submit a training job from gcloud ai-platform (ex gcloud ml-engine) you use the following command from the gcloud SDK:

gcloud ai-platform jobs submit COMMAND [GCLOUD_WIDE_FLAG …]

I want to do this programmatically, i.e. from python code (or any other language). Something like

import gcloud-ai-platform as gap
gap.submit_job(COMMAND)

Is there such a command? And if it does not exist, how can I build a workaround? (using gcloud sdk programmatically)


问:
Json like object in path params in Express 4
The requirement is to have object structure in received params from req object in the express.

For example:
/users/items[\:]id-:id/items[\:]type-:type

In this, I get below value in req.params

```<code>{
  id: 1,
  type: 'general'
}
</code>```

when called with /users/items:id-1/items:type-general

Is there any way to get it like below:

```<code>{
  items:{
    id: 1,
    type: 'general'
  }
}
</code>```

EDIT

Another sample route to support:  /users/items:id-1/boxes:type-general

```<code>{
  items:{
    id: 1,
  },
  boxes:{
    type: 'general'
  }
}
</code>```

答:
You can try something like.

```<code>app.param(['id', 'type'], (req, res, next, value, key) => {
  req.params.items = req.params.items ? req.params.items : {};
  req.params.items[key] = value;
  // Removing the default properties which gets added.
  delete req.params[key];
  next();
});
</code>```

This would help you make changes to a key in req.params.

Reference: https://expressjs.com/en/4x/api.html#app.param

[or]

The other way is to use a middleware, with respect to your edited question. You can try something like

```<code>const getParamsAsJSONObject = (req, res, next) => {
  const [emptypart, ...parts] = req.url.split('/');
  console.log(parts);
  req.customParams = parts.reduce((paramsObj, currentPart) => {
    console.log(paramsObj);
    console.log(currentPart);
    const [parentKey, childKeyValue] = currentPart.split(':');
    paramsObj[parentKey] = paramsObj[parentKey] ? paramsObj[parentKey] : {};
    const [childKey, childValue] = childKeyValue.split('-');
    paramsObj[parentKey][childKey] = childValue;
    return paramsObj;
  }, {});
  next();
};

app.use('/users', getParamsAsJSONObject, (req, res, next) => {
  console.log(req.customParams);
  // Remaining Piece of the code to be added.
});
</code>```

Body:
The requirement is to have object structure in received params from req object in the express.

For example:
/users/items[\:]id-:id/items[\:]type-:type

In this, I get below value in req.params

{
  id: 1,
  type: 'general'
}

when called with /users/items:id-1/items:type-general

Is there any way to get it like below:

{
  items:{
    id: 1,
    type: 'general'
  }
}

EDIT

Another sample route to support:  /users/items:id-1/boxes:type-general

{
  items:{
    id: 1,
  },
  boxes:{
    type: 'general'
  }
}

Body:
You can try something like.

app.param(['id', 'type'], (req, res, next, value, key) => {
  req.params.items = req.params.items ? req.params.items : {};
  req.params.items[key] = value;
  // Removing the default properties which gets added.
  delete req.params[key];
  next();
});

This would help you make changes to a key in req.params.

Reference: https://expressjs.com/en/4x/api.html#app.param

[or]

The other way is to use a middleware, with respect to your edited question. You can try something like

const getParamsAsJSONObject = (req, res, next) => {
  const [emptypart, ...parts] = req.url.split('/');
  console.log(parts);
  req.customParams = parts.reduce((paramsObj, currentPart) => {
    console.log(paramsObj);
    console.log(currentPart);
    const [parentKey, childKeyValue] = currentPart.split(':');
    paramsObj[parentKey] = paramsObj[parentKey] ? paramsObj[parentKey] : {};
    const [childKey, childValue] = childKeyValue.split('-');
    paramsObj[parentKey][childKey] = childValue;
    return paramsObj;
  }, {});
  next();
};

app.use('/users', getParamsAsJSONObject, (req, res, next) => {
  console.log(req.customParams);
  // Remaining Piece of the code to be added.
});


问:
Ignore duplicate entries and commit successful ones on DbContext.SaveChanges() in EF Core
I have an ASP .Net Core 2.2 Web API. In one of my controller actions, I am adding a bunch of rows to a MySQL database table (I'm using Pomelo).

So for example:

```<code>_dbContext.AddRange(entities);
_dbContext.SaveChanges();
</code>```

The entities I'm adding have two primary keys (composite primary key) and the keys are already populated in the entities collection when I add them to DbContext (i.e. I am setting the keys myself - there is no "auto increment" or anything like that where the database generates the keys)

If any of the entities I'm adding already exist in the database, in terms of a duplicate primary key, then obviously SaveChanges() throws an exception, and the entire transaction rolls back.

Is there a way to tell EF Core to ignore the entities that failed? i.e. to ignore the entities that already existed in the database, and commit the entities that succeeded (i.e. that did not exist in the database)? Instead of the current behaviour which is to throw an exception and roll back the entire transaction?

Thanks

答:
Looks like you have a business problem in place. 1st you need to decide what will happen when you already have an entity with the same id in place and someone tries to insert a new one (new information) with the same id.

It looks like you already decided: You want to drop the action.

That's somehow unusual because if you receive some new data from clients of that API about an entity that already existed in your database -> that looks more like an Update.

There exists some libraries that can do something similar: https://github.com/borisdj/EFCore.BulkExtensions (which is currently working only with MsSQL)

Using this library (which is a known one and was already mentioned by Microsoft as being an EF Core Tool: https://learn.microsoft.com/en-us/ef/core/extensions/) you have the possibility to:

Insert or Update all the data (all columns) if you find an entity with the same id (Upsert):

context.BulkInsertOrUpdateAsync(entitiesList);

Synchronize entities from your database with whatever entities you receive from clients:

context.BulkInsertOrUpdateOrDeleteAsync(entitiesList);

Most probably you won't find something already implemented for your case but you can adjust this library with:

```<code>BulkInsertOrDropAsync
</code>```

Which will do something like:

```<code>WHEN MATCHED THEN UPDATE SET A.ID=A.ID --The ID's are already the same so nothing will happen
WHEN NOT MATCHED THEN INSERT(A.ID,A.NAME,A.CODE,A.DESCRIPTION)
</code>```

Which is not really a DROP, but it will leave your data intact.

Body:
I have an ASP .Net Core 2.2 Web API. In one of my controller actions, I am adding a bunch of rows to a MySQL database table (I'm using Pomelo).

So for example:

_dbContext.AddRange(entities);
_dbContext.SaveChanges();

The entities I'm adding have two primary keys (composite primary key) and the keys are already populated in the entities collection when I add them to DbContext (i.e. I am setting the keys myself - there is no "auto increment" or anything like that where the database generates the keys)

If any of the entities I'm adding already exist in the database, in terms of a duplicate primary key, then obviously SaveChanges() throws an exception, and the entire transaction rolls back.

Is there a way to tell EF Core to ignore the entities that failed? i.e. to ignore the entities that already existed in the database, and commit the entities that succeeded (i.e. that did not exist in the database)? Instead of the current behaviour which is to throw an exception and roll back the entire transaction?

Thanks

Body:
Looks like you have a business problem in place. 1st you need to decide what will happen when you already have an entity with the same id in place and someone tries to insert a new one (new information) with the same id.

It looks like you already decided: You want to drop the action.

That's somehow unusual because if you receive some new data from clients of that API about an entity that already existed in your database -> that looks more like an Update.

There exists some libraries that can do something similar: https://github.com/borisdj/EFCore.BulkExtensions (which is currently working only with MsSQL)

Using this library (which is a known one and was already mentioned by Microsoft as being an EF Core Tool: https://learn.microsoft.com/en-us/ef/core/extensions/) you have the possibility to:

Insert or Update all the data (all columns) if you find an entity with the same id (Upsert):

context.BulkInsertOrUpdateAsync(entitiesList);

Synchronize entities from your database with whatever entities you receive from clients:

context.BulkInsertOrUpdateOrDeleteAsync(entitiesList);

Most probably you won't find something already implemented for your case but you can adjust this library with:

BulkInsertOrDropAsync

Which will do something like:

WHEN MATCHED THEN UPDATE SET A.ID=A.ID --The ID's are already the same so nothing will happen
WHEN NOT MATCHED THEN INSERT(A.ID,A.NAME,A.CODE,A.DESCRIPTION)

Which is not really a DROP, but it will leave your data intact.


Title: How to perform functions that reference previous row on subset of data in a dataframe using groupby

Body:
I have some log data that represents an item (id) and a timestamp that an action was a started and I want to determine the time between actions on each item.

for example, I have some data that looks like this:

data = [{"timestamp":"2019-05-21T14:17:29.265Z","id":"ff9dad92-e7c1-47a5-93a7-6e49533a6e25"},{"timestamp":"2019-05-21T14:21:49.722Z","id":"ff9dad92-e7c1-47a5-93a7-6e49533a6e25"},{"timestamp":"2019-05-21T15:16:25.695Z","id":"ff9dad92-e7c1-47a5-93a7-6e49533a6e25"},{"timestamp":"2019-05-21T15:16:25.696Z","id":"ff9dad92-e7c1-47a5-93a7-6e49533a6e25"},{"timestamp":"2019-05-22T07:51:17.49Z","id":"ff12891e-5786-438b-891c-abd4244723b4"},{"timestamp":"2019-05-22T08:11:13.948Z","id":"ff12891e-5786-438b-891c-abd4244723b4"},{"timestamp":"2019-05-22T11:52:59.897Z","id":"ff12891e-5786-438b-891c-abd4244723b4"},{"timestamp":"2019-05-22T11:53:03.406Z","id":"ff12891e-5786-438b-891c-abd4244723b4"},{"timestamp":"2019-05-22T11:53:03.481Z","id":"ff12891e-5786-438b-891c-abd4244723b4"},{"timestamp":"2019-05-21T14:23:08.147Z","id":"fe55bb22-fe5b-4b12-8aaf-d5f0320ac7fa"},{"timestamp":"2019-05-21T14:29:18.228Z","id":"fe55bb22-fe5b-4b12-8aaf-d5f0320ac7fa"},{"timestamp":"2019-05-21T15:17:09.831Z","id":"fe55bb22-fe5b-4b12-8aaf-d5f0320ac7fa"},{"timestamp":"2019-05-21T15:17:09.834Z","id":"fe55bb22-fe5b-4b12-8aaf-d5f0320ac7fa"},{"timestamp":"2019-05-21T14:02:19.072Z","id":"fd3554cd-b83d-49af-a8e6-7bf41c741cd0"},{"timestamp":"2019-05-21T14:02:34.867Z","id":"fd3554cd-b83d-49af-a8e6-7bf41c741cd0"},{"timestamp":"2019-05-21T14:12:28.877Z","id":"fd3554cd-b83d-49af-a8e6-7bf41c741cd0"},{"timestamp":"2019-05-21T15:19:19.567Z","id":"fd3554cd-b83d-49af-a8e6-7bf41c741cd0"},{"timestamp":"2019-05-21T15:19:19.582Z","id":"fd3554cd-b83d-49af-a8e6-7bf41c741cd0"},{"timestamp":"2019-05-21T09:58:02.185Z","id":"f89c2e3e-06dc-467b-813b-dc92f2692f63"},{"timestamp":"2019-05-21T10:07:24.044Z","id":"f89c2e3e-06dc-467b-813b-dc92f2692f63"}]
stack = pd.DataFrame(data)
stack.head()

I have tried getting all the unique ids to split the data frame and then getting the time taken with the index to recombine with the original set like, but the function is extremely slow on large data-sets and messes up both the index
 and timestamp order resulting in results getting miss matched.

import ciso8601 as time
records = []
for i in list(stack.id.unique()):
    dff = stack[stack.id == i]
    time_taken = []
    times = []
    i = 0
    for _, row in dff.iterrows():
        if bool(times):
            print(_)
            current_time = time.parse_datetime(row.timestamp)
            prev_time = times[i]
            time_taken = current_time - prev_time
            times.append(current_time)
            i+=1
            records.append(dict(index = _, time_taken = time_taken.seconds))
        else:
            records.append(dict(index = _, time_taken = 0))
            times.append(time.parse_datetime(row.timestamp))

x = pd.DataFrame(records).set_index('index')
stack.merge(x, left_index=True, right_index=True, how='inner')

Is there a neat pandas groupby and apply way of doing this so that I don't have to split the frame and store it in memory so that can reference the previous row in the subset?

Thanks

Body:
If dont need replace timestamp to datetimes create Series filled by datetimes by to_datetime and pass to DataFrameGroupBy.diff, then convert to seconds by Series.dt.total_seconds, if necessary round by Series.round and replace missing values by 0:

t = pd.to_datetime(stack['timestamp'])
stack['time_taken'] = t.groupby(stack['id']).diff().dt.total_seconds().round().fillna(0)

print (stack)
                                      id                 timestamp  time_taken
0   ff9dad92-e7c1-47a5-93a7-6e49533a6e25  2019-05-21T14:17:29.265Z         0.0
1   ff9dad92-e7c1-47a5-93a7-6e49533a6e25  2019-05-21T14:21:49.722Z       260.0
2   ff9dad92-e7c1-47a5-93a7-6e49533a6e25  2019-05-21T15:16:25.695Z      3276.0
3   ff9dad92-e7c1-47a5-93a7-6e49533a6e25  2019-05-21T15:16:25.696Z         0.0
4   ff12891e-5786-438b-891c-abd4244723b4   2019-05-22T07:51:17.49Z         0.0
5   ff12891e-5786-438b-891c-abd4244723b4  2019-05-22T08:11:13.948Z      1196.0
6   ff12891e-5786-438b-891c-abd4244723b4  2019-05-22T11:52:59.897Z     13306.0
7   ff12891e-5786-438b-891c-abd4244723b4  2019-05-22T11:53:03.406Z         4.0
8   ff12891e-5786-438b-891c-abd4244723b4  2019-05-22T11:53:03.481Z         0.0
9   fe55bb22-fe5b-4b12-8aaf-d5f0320ac7fa  2019-05-21T14:23:08.147Z         0.0
10  fe55bb22-fe5b-4b12-8aaf-d5f0320ac7fa  2019-05-21T14:29:18.228Z       370.0
11  fe55bb22-fe5b-4b12-8aaf-d5f0320ac7fa  2019-05-21T15:17:09.831Z      2872.0
12  fe55bb22-fe5b-4b12-8aaf-d5f0320ac7fa  2019-05-21T15:17:09.834Z         0.0
13  fd3554cd-b83d-49af-a8e6-7bf41c741cd0  2019-05-21T14:02:19.072Z         0.0
14  fd3554cd-b83d-49af-a8e6-7bf41c741cd0  2019-05-21T14:02:34.867Z        16.0
15  fd3554cd-b83d-49af-a8e6-7bf41c741cd0  2019-05-21T14:12:28.877Z       594.0
16  fd3554cd-b83d-49af-a8e6-7bf41c741cd0  2019-05-21T15:19:19.567Z      4011.0
17  fd3554cd-b83d-49af-a8e6-7bf41c741cd0  2019-05-21T15:19:19.582Z         0.0
18  f89c2e3e-06dc-467b-813b-dc92f2692f63  2019-05-21T09:58:02.185Z         0.0
19  f89c2e3e-06dc-467b-813b-dc92f2692f63  2019-05-21T10:07:24.044Z       562.0

Or if need replace timestamp to datetimes use @yatu answer.


问:
call() a function within its own context

var f = function() {
  this.x = 5;
  (function() {
    this.x = 3;
  })();
  console.log(this.x);
};

f.call(f);

f();

f.call();```

Running var f as f.call(f) outputs 5. When running it as f() or f.call() outputs 3.

What happens in each case? What does the inner function's this refer to?

答:
'this' keyword refers to the context object in which the current code is executing. Outside any function this refers to the global object.

By using call(), apply() functions the value of this can pass from one context to another context.

So in the 1st case [f.call(f)] by calling the call function and
giving the first argument as f, this.x refers to 5. So answer is
printed as 5.

2nd case [f()] it is calling the function without using call
function. So it refers the execution context of this as 3. So it
prints as 3.

In the third case [f.call()], inside the call function no
argument is mentioned. So it refers to the global object and prints 3
as the output.

Body:
var f = function() {
  this.x = 5;
  (function() {
    this.x = 3;
  })();
  console.log(this.x);
};

f.call(f);

f();

f.call();

Running var f as f.call(f) outputs 5. When running it as f() or f.call() outputs 3.

What happens in each case? What does the inner function's this refer to?


问:
Function pointer only works inside main?
Code below shows a simple insert into a binary search tree (hand written NOT STL) i have used function pointers in my bst and would like to traverse the tree from outside of main. how do i get it to work outside of main?

i get an error at tree.inorder() saying no instance of overloaded function

handler class

```<code>#include <iostream>
using namespace std;

void printTree(int & a)
{
    cout << a << endl;
}

handler::handler()
{

}

void handler::printTree()
{

    BinarySearchTree<int> tree;

    tree.insert(10);
    tree.insert(5);
    tree.insert(2);
    tree.insert(20);

    tree.inorder(printTree);
}

</code>```

main class

```<code>#include <iostream>

#include "BinarySearchTree.h"
#include "handler.h"

int main()
{
    handler handle;

    handle.printTree();
}
</code>```

```<code>template<class T>
inline void BinarySearchTree<T>::inorder(Node * root, void(*inorderPtr)(T &)) const
{
    if (root != nullptr)
    {
        if (root->left != nullptr)
        {
            inorder(root->left, inorderPtr);
        }
        inorderPtr(root->data);
        if (root->right != nullptr)
        {
            inorder(root->right, inorderPtr);
        }
    }
    else
    {
        cout << "No data" << endl;
    }
}

template<class T>
inline void BinarySearchTree<T>::inorder(void(*inorderPtr)(T &)) const
{
    inorder(this->root, inorderPtr);
}

</code>```

答:
BinarySearchTree<T>::inorder is declared const hence root->data is const and you cannot call inorderPtr(root->data); because inorderPtr (aka printTree(int&)) expects a non-const int&.

Fix it by fixing const-correctness. You could have two BinarySearchTree<T>::inorder. One const taking a void(*inorderPtr)(const T &) and the other non-const, taking a void(*inorderPtr)(T &).

Body:
Code below shows a simple insert into a binary search tree (hand written NOT STL) i have used function pointers in my bst and would like to traverse the tree from outside of main. how do i get it to work outside of main?

i get an error at tree.inorder() saying no instance of overloaded function

handler class

#include <iostream>
using namespace std;

void printTree(int & a)
{
    cout << a << endl;
}

handler::handler()
{

}

void handler::printTree()
{

    BinarySearchTree<int> tree;

    tree.insert(10);
    tree.insert(5);
    tree.insert(2);
    tree.insert(20);

    tree.inorder(printTree);
}

main class

#include <iostream>

#include "BinarySearchTree.h"
#include "handler.h"

int main()
{
    handler handle;

    handle.printTree();
}

template<class T>
inline void BinarySearchTree<T>::inorder(Node * root, void(*inorderPtr)(T &)) const
{
    if (root != nullptr)
    {
        if (root->left != nullptr)
        {
            inorder(root->left, inorderPtr);
        }
        inorderPtr(root->data);
        if (root->right != nullptr)
        {
            inorder(root->right, inorderPtr);
        }
    }
    else
    {
        cout << "No data" << endl;
    }
}

template<class T>
inline void BinarySearchTree<T>::inorder(void(*inorderPtr)(T &)) const
{
    inorder(this->root, inorderPtr);
}


问:
Why does my fixed hologram not scale with head movement?
I am placing a Direct X sphere using a fixed frame of reference. When I move my head, the sphere hologram stays in place. But it does not scale. It DOES scale when I first place it using PositionHologramAtGaze() (based on example code).

Do I have to handle the scaling when in C++ / Direct X?

// The code below is based on or identical to example code...

```<code>SpatialPointerPose^ pointerPoseStationary =
SpatialPointerPose::TryGetAtTimestamp(m_stationaryReferenceFrame-
>CoordinateSystem, prediction->Timestamp);

m_Sphere->PositionHologramAtGaze(pointerPoseStationary, 2.5f);
</code>```

The sphere draws fine, and stays at a fixed world position, but doesn't scale as I move my head / hololens further away.

For instance in this image we have a person looking at a holographic spherePerson wearing a hololens looking at holographic sphere

And what they see is
Holographic Sphere as seen by wearer

Now the user wearing the hololens hardware steps a few meters backwards:

Person takes a few steps back

And what they should see is a smaller sphere:
Smaller sphere

I also observe this in Microsoft's example here:

https://github.com/microsoft/Windows-universal-samples/tree/master/Samples/BasicHologram

The cube spins but does not change size as I move backwards.

答:
I found my own answer.

The HolographicFaceTracking Example uses the coordinate system relative to the glasses.
Line 281
    SpatialCoordinateSystem^ currentCoordinateSystem = m_referenceFrame-

GetStationaryCoordinateSystemAtTimestamp(prediction->Timestamp);

I misunderstood this method as getting the "Stationary", i.e. "World" coordinate system. But "Stationary" doesn't have this meaning in this context.

It doesn't quite explain why the cube wouldn't change size, or have a reverse scaling, but, once I switched to using this code from the BasicHologram example:

```<code>// The simplest way to render world-locked holograms is to create a
stationary reference frame
// based on a SpatialLocator. This is roughly analogous to creating a "world"
coordinate system
// with the origin placed at the device's position as the app is launched.
m_stationaryReferenceFrame = m_spatialLocator-
>CreateStationaryFrameOfReferenceAtCurrentLocation();
</code>```

and then

```<code>pose = SpatialPointerPose::TryGetAtTimestamp(m_stationaryReferenceFrame-
>CoordinateSystem, prediction->Timestamp);
</code>```

switching to using the CreateStationaryFrameOfReferenceAtCurrentLocation()

gives me the "world locked" coordinate frame.

I think, in my defense, ;>) , the over-loading of the word "stationary" all over the place is a bit confusing, and one needs to be careful. I'm changing my own code to make sure to use "world" and "headset" to refer to the coordinate frames to help eliminate confusion...

Hopefully my answer here will help someone else....

Body:
I am placing a Direct X sphere using a fixed frame of reference. When I move my head, the sphere hologram stays in place. But it does not scale. It DOES scale when I first place it using PositionHologramAtGaze() (based on example code).

Do I have to handle the scaling when in C++ / Direct X?

// The code below is based on or identical to example code...

SpatialPointerPose^ pointerPoseStationary =
SpatialPointerPose::TryGetAtTimestamp(m_stationaryReferenceFrame-
>CoordinateSystem, prediction->Timestamp);

m_Sphere->PositionHologramAtGaze(pointerPoseStationary, 2.5f);

The sphere draws fine, and stays at a fixed world position, but doesn't scale as I move my head / hololens further away.

For instance in this image we have a person looking at a holographic spherePerson wearing a hololens looking at holographic sphere

And what they see is
Holographic Sphere as seen by wearer

Now the user wearing the hololens hardware steps a few meters backwards:

Person takes a few steps back

And what they should see is a smaller sphere:
Smaller sphere

I also observe this in Microsoft's example here:

https://github.com/microsoft/Windows-universal-samples/tree/master/Samples/BasicHologram

The cube spins but does not change size as I move backwards.

Body:
I found my own answer.

The HolographicFaceTracking Example uses the coordinate system relative to the glasses.
Line 281
    SpatialCoordinateSystem^ currentCoordinateSystem = m_referenceFrame-

GetStationaryCoordinateSystemAtTimestamp(prediction->Timestamp);

I misunderstood this method as getting the "Stationary", i.e. "World" coordinate system. But "Stationary" doesn't have this meaning in this context.

It doesn't quite explain why the cube wouldn't change size, or have a reverse scaling, but, once I switched to using this code from the BasicHologram example:

// The simplest way to render world-locked holograms is to create a
stationary reference frame
// based on a SpatialLocator. This is roughly analogous to creating a "world"
coordinate system
// with the origin placed at the device's position as the app is launched.
m_stationaryReferenceFrame = m_spatialLocator-
>CreateStationaryFrameOfReferenceAtCurrentLocation();

and then

pose = SpatialPointerPose::TryGetAtTimestamp(m_stationaryReferenceFrame-
>CoordinateSystem, prediction->Timestamp);

switching to using the CreateStationaryFrameOfReferenceAtCurrentLocation()

gives me the "world locked" coordinate frame.

I think, in my defense, ;>) , the over-loading of the word "stationary" all over the place is a bit confusing, and one needs to be careful. I'm changing my own code to make sure to use "world" and "headset" to refer to the coordinate frames to help eliminate confusion...

Hopefully my answer here will help someone else....


问:
How to check for vertical velocity in 2d unity?
I am trying to animate my sprite when my vertical velocity is less than 0 (moving downwards). How do you do it?

```<code>if (VERTICALVELOCITY < 0) {
animator.SetFloat("IsFalling", true);
}
</code>```

Try to change VERTICALVELOCITY and maybe help with the code.
Also, should I do it in Void Update or FixedUpdate?

答:
If you're using a rigibody you may do this:

```<code>public class CheckSpeed : MonoBehaviour
{
    private Rigidbody2D rb2D;

    void Start() => rb2D = GetComponent<Rigidbody2D>();

    private float GetVerticalSpeed() => rb2D.velocity.y;
}
</code>```

Your code will become:

```<code>if (GetVerticalSpeed() < 0) {
animator.SetFloat("IsFalling", true);
}
</code>```

Since this is related to an animation I would set it to LateUpdate.

Body:
I am trying to animate my sprite when my vertical velocity is less than 0 (moving downwards). How do you do it?

if (VERTICALVELOCITY < 0) {
animator.SetFloat("IsFalling", true);
}

Try to change VERTICALVELOCITY and maybe help with the code.
Also, should I do it in Void Update or FixedUpdate?

Body:
If you're using a rigibody you may do this:

public class CheckSpeed : MonoBehaviour
{
    private Rigidbody2D rb2D;

    void Start() => rb2D = GetComponent<Rigidbody2D>();

    private float GetVerticalSpeed() => rb2D.velocity.y;
}

Your code will become:

if (GetVerticalSpeed() < 0) {
animator.SetFloat("IsFalling", true);
}

Since this is related to an animation I would set it to LateUpdate.


问:
How to find routines that are created with SET ANSI_NULLS OFF?
I have created a filtered non-clustered index in order to optimize particular set of queries, but I started to get the following errors from various sources:

UPDATE failed because the following SET options have incorrect
  settings: 'ANSI_NULLS'. Verify that SET options are correct for use
  with indexed views and/or indexes on computed columns and/or filtered
  indexes and/or query notifications and/or XML data type methods and/or
  spatial index operations.

It seems that some of the legacy routines are created with the SET ANSI_NULLS OFF option and when the engine is trying to update the destination table from given context the error is thrown.

I am wondering is there a way to see which of the routines are created with this option. For example, if you script such routine you get something like this:

```<code>SET ANSI_NULLS OFF
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE ....
</code>```

I usually use scripts like the below one to found things in the objects definitions, but this settings is not part of it:

```<code>DECLARE @SearchWord NVARCHAR(128) = 'SET ANSI_NULLS OFF'
SELECT [ROUTINE_NAME]
FROM [INFORMATION_SCHEMA].[ROUTINES]
WHERE [ROUTINE_DEFINITION] LIKE '%' + @SearchWord+'%'
UNION
SELECT OBJECT_NAME([id])
FROM [SYSCOMMENTS]
WHERE [text] LIKE '%' + @SearchWord + '%'
GROUP BY OBJECT_NAME([id])
UNION
SELECT OBJECT_NAME(object_id)
FROM [sys].[sql_modules]
WHERE [definition] LIKE '%' + @SearchWord + '%' ;
</code>```

答:
a simple search could do this, like this for example</p>

```<code>SELECT DISTINCT
       o.name AS Object_Name,
       o.type_desc,
       m.*
FROM   sys.sql_modules m
  INNER JOIN sys.objects o ON m.object_id = o.object_id
WHERE  m.uses_ansi_nulls = 0
</code>```

Body:
I have created a filtered non-clustered index in order to optimize particular set of queries, but I started to get the following errors from various sources:

UPDATE failed because the following SET options have incorrect
  settings: 'ANSI_NULLS'. Verify that SET options are correct for use
  with indexed views and/or indexes on computed columns and/or filtered
  indexes and/or query notifications and/or XML data type methods and/or
  spatial index operations.

It seems that some of the legacy routines are created with the SET ANSI_NULLS OFF option and when the engine is trying to update the destination table from given context the error is thrown.

I am wondering is there a way to see which of the routines are created with this option. For example, if you script such routine you get something like this:

SET ANSI_NULLS OFF
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE ....

I usually use scripts like the below one to found things in the objects definitions, but this settings is not part of it:

DECLARE @SearchWord NVARCHAR(128) = 'SET ANSI_NULLS OFF'
SELECT [ROUTINE_NAME]
FROM [INFORMATION_SCHEMA].[ROUTINES]
WHERE [ROUTINE_DEFINITION] LIKE '%' + @SearchWord+'%'
UNION
SELECT OBJECT_NAME([id])
FROM [SYSCOMMENTS]
WHERE [text] LIKE '%' + @SearchWord + '%'
GROUP BY OBJECT_NAME([id])
UNION
SELECT OBJECT_NAME(object_id)
FROM [sys].[sql_modules]
WHERE [definition] LIKE '%' + @SearchWord + '%' ;

Body:
a simple search could do this, like this for example

SELECT DISTINCT
       o.name AS Object_Name,
       o.type_desc,
       m.*
FROM   sys.sql_modules m
  INNER JOIN sys.objects o ON m.object_id = o.object_id
WHERE  m.uses_ansi_nulls = 0


问:
input_shape not recognised in Keras model
I am trying to use Tensorflow's 2.0 new MirroredStrategy but I am receiving an error saying:

ValueError: We currently do not support distribution strategy with a `Sequential` model that is created without `input_shape`/`input_dim` set in its first layer or a subclassed model.
```

<p>Model:
</p>

<pre class="lang-py prettyprint-override"><code>class Model(kr.Model):
    def __init__(self, input_shape, conv_sizes, num_outputs):
        super().__init__('model_1')
        self.num_outputs = num_outputs

        rows, cols, depth = input_shape
        self.one_hot = kl.Lambda(lambda x: tf.one_hot(tf.cast(x, 'int32'), num_outputs), input_shape=(rows, cols))
        self.concat = kl.Concatenate(axis=-1)
        vision_layers = []
        for i, (filters, kernel, stride) in enumerate(conv_sizes):
            if not i:
                depth += num_outputs - 1
                vision_layers += [kl.Conv2D(filters, kernel, stride, activation='relu',
                                            input_shape=(rows, cols, depth))]
            else:
                vision_layers += [kl.Conv2D(filters, kernel, stride, activation='relu')]
            vision_layers += [kl.MaxPool2D(pool_size=(2, 2))]

        flatten = kl.Flatten()
        dense = kl.Dense(num_outputs)
        self.net = kr.Sequential(vision_layers+[flatten]+[dense])
        self.build(input_shape=(None, ) + input_shape)

    def call(self, inputs):
        one_hot = self.one_hot(inputs[:, :, :, -1])
        return self.net(self.concat([inputs[:, :, :, :-1], one_hot]))
</code>```

Reproduction code:

model_args = {'conv_sizes': [(32, (2, 2), 1), (32, (2, 2), 1), (32, (2, 2), 1)],
               'input_shape': (50, 50, 6),
               'num_outputs': 5}

def dummy_loss(values, targets):
    return tf.reduce_sum(values-targets, axis=-1)

mirrored_strategy = tf.distribute.MirroredStrategy()
with mirrored_strategy.scope():
    model = Model(**model_args)
    model.compile(optimizer=kr.optimizers.Adam(learning_rate=0.01), loss=dummy_loss)
```

<p>Output:
</p>

<pre class="lang-sh prettyprint-override"><code>Traceback (most recent call last):
  File "/home/joao/anaconda3/envs/tf2/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 3296, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-4-dc492e7c638b>", line 18, in <module>
    model.compile(optimizer=kr.optimizers.Adam(learning_rate=0.01), loss=dummy_loss)
  File "/home/joao/anaconda3/envs/tf2/lib/python3.6/site-packages/tensorflow/python/training/tracking/base.py", line 456, in _method_wrapper
    result = method(self, *args, **kwargs)
  File "/home/joao/anaconda3/envs/tf2/lib/python3.6/site-packages/tensorflow/python/keras/engine/training.py", line 263, in compile
    'We currently do not support distribution strategy with a '
ValueError: We currently do not support distribution strategy with a `Sequential` model that is created without `input_shape`/`input_dim` set in its first layer or a subclassed model.
</code>```

Model Summary (model.summary()):

Model: "model_1"
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
lambda (Lambda)              multiple                  0
_________________________________________________________________
concatenate (Concatenate)    multiple                  0
_________________________________________________________________
sequential (Sequential)      (None, 5)                 13573
=================================================================
Total params: 13,573
Trainable params: 13,573
Non-trainable params: 0
```

答:
I would do away with the Sequential approach and use the Model class directly:

def create_model(input_shape, conv_sizes, fc_sizes, num_outputs):
    num_outputs = num_outputs
    rows, cols, depth = input_shape
    input_layer = kl.Input(shape=(rows, cols, depth))
    actions = tf.slice(input_layer, [0, 0, 0, depth - 1], [-1, rows, cols, 1])
    non_actions = tf.slice(input_layer, [0, 0, 0, 0], [-1, rows, cols, depth - 1])
    one_hot = kl.Lambda(lambda x: tf.one_hot(tf.cast(x, 'int32'), num_outputs),
                        input_shape=(rows, cols))(actions)
    concat = kl.Concatenate(axis=-1)([non_actions, tf.reshape(one_hot, (-1, rows, cols, num_outputs))])
    vision_layer = concat
    for i, (filters, kernel, stride) in enumerate(conv_sizes):
        vision_layer = kl.Conv2D(filters, kernel, stride, activation='relu')(vision_layer)
        vision_layer = kl.MaxPool2D(pool_size=(2, 2))(vision_layer)

    flatten = kl.Flatten()(vision_layer)
    dense = kl.Dense(num_outputs)(flatten)
    return kr.Model(inputs=input_layer, outputs=[dense])
```

Body:
I am trying to use Tensorflow's 2.0 new MirroredStrategy but I am receiving an error saying:

ValueError: We currently do not support distribution strategy with a `Sequential` model that is created without `input_shape`/`input_dim` set in its first layer or a subclassed model.

Model:

class Model(kr.Model):
    def __init__(self, input_shape, conv_sizes, num_outputs):
        super().__init__('model_1')
        self.num_outputs = num_outputs

        rows, cols, depth = input_shape
        self.one_hot = kl.Lambda(lambda x: tf.one_hot(tf.cast(x, 'int32'), num_outputs), input_shape=(rows, cols))
        self.concat = kl.Concatenate(axis=-1)
        vision_layers = []
        for i, (filters, kernel, stride) in enumerate(conv_sizes):
            if not i:
                depth += num_outputs - 1
                vision_layers += [kl.Conv2D(filters, kernel, stride, activation='relu',
                                            input_shape=(rows, cols, depth))]
            else:
                vision_layers += [kl.Conv2D(filters, kernel, stride, activation='relu')]
            vision_layers += [kl.MaxPool2D(pool_size=(2, 2))]

        flatten = kl.Flatten()
        dense = kl.Dense(num_outputs)
        self.net = kr.Sequential(vision_layers+[flatten]+[dense])
        self.build(input_shape=(None, ) + input_shape)

    def call(self, inputs):
        one_hot = self.one_hot(inputs[:, :, :, -1])
        return self.net(self.concat([inputs[:, :, :, :-1], one_hot]))

Reproduction code:

model_args = {'conv_sizes': [(32, (2, 2), 1), (32, (2, 2), 1), (32, (2, 2), 1)],
               'input_shape': (50, 50, 6),
               'num_outputs': 5}

def dummy_loss(values, targets):
    return tf.reduce_sum(values-targets, axis=-1)

mirrored_strategy = tf.distribute.MirroredStrategy()
with mirrored_strategy.scope():
    model = Model(**model_args)
    model.compile(optimizer=kr.optimizers.Adam(learning_rate=0.01), loss=dummy_loss)

Output:

Traceback (most recent call last):
  File "/home/joao/anaconda3/envs/tf2/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 3296, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-4-dc492e7c638b>", line 18, in <module>
    model.compile(optimizer=kr.optimizers.Adam(learning_rate=0.01), loss=dummy_loss)
  File "/home/joao/anaconda3/envs/tf2/lib/python3.6/site-packages/tensorflow/python/training/tracking/base.py", line 456, in _method_wrapper
    result = method(self, *args, **kwargs)
  File "/home/joao/anaconda3/envs/tf2/lib/python3.6/site-packages/tensorflow/python/keras/engine/training.py", line 263, in compile
    'We currently do not support distribution strategy with a '
ValueError: We currently do not support distribution strategy with a `Sequential` model that is created without `input_shape`/`input_dim` set in its first layer or a subclassed model.

Model Summary (model.summary()):

Model: "model_1"
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
lambda (Lambda)              multiple                  0
_________________________________________________________________
concatenate (Concatenate)    multiple                  0
_________________________________________________________________
sequential (Sequential)      (None, 5)                 13573
=================================================================
Total params: 13,573
Trainable params: 13,573
Non-trainable params: 0


问:
How to add scoped css in react?
Is there a React equivalent of scoped css as in Vue that's super easy to work with, without a bunch of re-writes? One which I can just import an existing css file, and hook it up to a component, and it just works?

In Vue, it's as easy as

```

<p>And Bam! Your css is now scoped to your component.</p>

<p><strong>Is there anything similar in React</strong>? Something like
</p>

```// import the css file
import styles from "./boxes.css";

// hook it to a component, or using any other methods
@inject(styles)
class Boxes extends Component {
  render(){

       /* must support multiple classes out-of-the-box, unlike CSSModule where you have to
       re-write into a super long array like className={[styles.box, styles.green, styles.large]} */

  }
}
```

答:
https://facebook.github.io/create-react-app/docs/adding-a-css-modules-stylesheet

Button.module.css

```<code>.error {
  background-color: red;
}
</code>```

another-stylesheet.css

```<code>.error {
  color: red;
}
</code>```

Button.js

```<code>import React, { Component } from 'react';
import styles from './Button.module.css'; // Import css modules stylesheet as styles
import './another-stylesheet.css'; // Import regular stylesheet

class Button extends Component {
  render() {
    // reference as a js object
    return <button className={styles.error}>Error Button</button>;
  }
}
</code>```

Result: No clashes from other .error class names

```<code><!-- This button has red background but not red text -->
<button class="Button_error_ax7yz">Error Button</button>
</code>```

Title: How to add scoped css in react?

Body:
Is there a React equivalent of scoped css as in Vue that's super easy to work with, without a bunch of re-writes? One which I can just import an existing css file, and hook it up to a component, and it just works?

In Vue, it's as easy as

And Bam! Your css is now scoped to your component.

Is there anything similar in React? Something like

// import the css file
import styles from "./boxes.css";

// hook it to a component, or using any other methods
@inject(styles)
class Boxes extends Component {
  render(){

       /* must support multiple classes out-of-the-box, unlike CSSModule where you have to
       re-write into a super long array like className={[styles.box, styles.green, styles.large]} */

  }
}

Body:
https://facebook.github.io/create-react-app/docs/adding-a-css-modules-stylesheet

Button.module.css

.error {
  background-color: red;
}

another-stylesheet.css

.error {
  color: red;
}

Button.js

import React, { Component } from 'react';
import styles from './Button.module.css'; // Import css modules stylesheet as styles
import './another-stylesheet.css'; // Import regular stylesheet

class Button extends Component {
  render() {
    // reference as a js object
    return <button className={styles.error}>Error Button</button>;
  }
}

Result: No clashes from other .error class names

<!-- This button has red background but not red text -->
<button class="Button_error_ax7yz">Error Button</button>


问:
How to get screen size in Firemonkey FM3?
How to get screen dimensions with Firemonkey FM³ ? The following code:

```<code>var
  Size: TPointF;
begin
  Size := FMX.Platform.IFMXScreenService.GetScreenSize;
  ...
end;
</code>```

Results in this compiler error:

[dcc32 Error] Unit1.pas(46): E2018 Record, object or class type required
```

How should I use IFMXScreenService interface to get screen size ?

答:
Here's a different solution that doesn't require multiplication by scale:

```<code>var
  aResolution      : JPoint;
begin
  aResolution := TJPoint.Create;
  TAndroidHelper.Display.getRealSize(aResolution);
end;
</code>```

Works well in Delphi 10.3 RIO. From what I understand, "getRealSize" requires at least Android 4.2, but since Delphi RIO doesn't even support old versions of Android, I don't believe this is a show-stopper.

Body:
How to get screen dimensions with Firemonkey FM³ ? The following code:

var
  Size: TPointF;
begin
  Size := FMX.Platform.IFMXScreenService.GetScreenSize;
  ...
end;

Results in this compiler error:

[dcc32 Error] Unit1.pas(46): E2018 Record, object or class type required

How should I use IFMXScreenService interface to get screen size ?

Body:
Here's a different solution that doesn't require multiplication by scale:

var
  aResolution      : JPoint;
begin
  aResolution := TJPoint.Create;
  TAndroidHelper.Display.getRealSize(aResolution);
end;

Works well in Delphi 10.3 RIO. From what I understand, "getRealSize" requires at least Android 4.2, but since Delphi RIO doesn't even support old versions of Android, I don't believe this is a show-stopper.


问:
nodeJS "exec" isn't executing a "sed" command that works from the command line
I can't figure out why my code isn't working.

I'm trying to edit this yml file:
apktool.yml

```<code>...
versionInfo:
  versionCode: '1'
  versionName: '1.0'
</code>```

In windows, this command line modifies versionCode to '2' successfuly:

```<code>sed -i 's/versionCode: \'1\'/versionCode: \'2\'/g' app-debug\\apktool.yml
</code>```

However, executed from the same directory, this nodeJS code fails to modify the file:

```<code>const {exec} = require('child_process');
const {promisify} = require('util');
const exec_async = promisify(exec);
await exec_async("sed -i 's/versionCode: \'1\'/versionCode: \'2\'/g' app-debug\\apktool.yml")
    .catch(err => {console.log(err)});
</code>```

No error is catched, and the file isn't modified. I also tried to "sleep 5" before the command to make sure it's not a timing issue. Any ideas what's wrong here?

答:
Alright, that was a brain-breaker, but solved it:
the sed command needs to include double quotes to contain single quotes, and the nodeJS exec argument should also be wrapped in escaped, double quotes. this worked:</p>

```<code>await exec_async("sed -i \"s/versionCode: '1'/versionCode: '2'/g\" app-debug\\apktool.yml")
</code>```

Body:
I can't figure out why my code isn't working.

I'm trying to edit this yml file:
apktool.yml

...
versionInfo:
  versionCode: '1'
  versionName: '1.0'

In windows, this command line modifies versionCode to '2' successfuly:

sed -i 's/versionCode: \'1\'/versionCode: \'2\'/g' app-debug\\apktool.yml

However, executed from the same directory, this nodeJS code fails to modify the file:

const {exec} = require('child_process');
const {promisify} = require('util');
const exec_async = promisify(exec);
await exec_async("sed -i 's/versionCode: \'1\'/versionCode: \'2\'/g' app-debug\\apktool.yml")
    .catch(err => {console.log(err)});

No error is catched, and the file isn't modified. I also tried to "sleep 5" before the command to make sure it's not a timing issue. Any ideas what's wrong here?

Body:
Alright, that was a brain-breaker, but solved it:
the sed command needs to include double quotes to contain single quotes, and the nodeJS exec argument should also be wrapped in escaped, double quotes. this worked:

await exec_async("sed -i \"s/versionCode: '1'/versionCode: '2'/g\" app-debug\\apktool.yml")


问:
How to change the position of a node in a plane?
I'm working on a project but I want to change the position of a 3D asset(example, Andy) when a button is tapped.

I've been using .getLocalPosition to get the position the asset but I don't know if it is the correct function.

If it is correct, I don't know whether .setLocalPosoition would work. Any help please

答:
This is the portion of the code that needs to change the position of the room. I tried .setLocalPosition() but it didn't change position of the model but .setWorldPosition() worked. Please any solution?

private void changeNodeDetails(float psX, float psY, float psZ,String fnName) {
Vector3 furnPosition;
        furnPosition = new Vector3(psX,psY,psZ);

```<code>    this.newOptimizeName = fnName;
    this.psResults = furnPosition;

    List<Node> nodes = arFragment.getArSceneView().getScene().getChildren();

    Optional<Node> optionalNode = nodes.stream().filter(n->n.getName().equals(fnName)).findFirst();`
</code>```

if(optionalNode.isPresent()){
            ``Node node = optionalNode.get();
            ``try{
                ``Vector3 x = new Vector3(0,0,0);
                ``Node childNode = node.getChildren().get(0);
                ``childNode.setWorldPosition(furnPosition);
                ``node.removeChild(node.getChildren().get(0));
                ```node.addChild(childNode);
                ```Log.i("Furniture Name",String.valueOf(childNode.getName()));

```<code>            ```Log.i("Furniture Position x,y,z",String.valueOf(childNode.getWorldPosition()));`

        ``}
        ``catch (IndexOutOfBoundsException ioobe){ ioobe.printStackTrace(); }

    }
```

Body:
This is the portion of the code that needs to change the position of the room. I tried .setLocalPosition() but it didn't change position of the model but .setWorldPosition() worked. Please any solution?

private void changeNodeDetails(float psX, float psY, float psZ,String fnName) {
Vector3 furnPosition;
        furnPosition = new Vector3(psX,psY,psZ);

    this.newOptimizeName = fnName;
    this.psResults = furnPosition;

    List<Node> nodes = arFragment.getArSceneView().getScene().getChildren();

    Optional<Node> optionalNode = nodes.stream().filter(n->n.getName().equals(fnName)).findFirst();`

if(optionalNode.isPresent()){
            ``Node node = optionalNode.get();
            ``try{
                ``Vector3 x = new Vector3(0,0,0);
                ``Node childNode = node.getChildren().get(0);
                ``childNode.setWorldPosition(furnPosition);
                ``node.removeChild(node.getChildren().get(0));
                ```node.addChild(childNode);
                ```Log.i("Furniture Name",String.valueOf(childNode.getName()));

            ```Log.i("Furniture Position x,y,z",String.valueOf(childNode.getWorldPosition()));`

        ``}
        ``catch (IndexOutOfBoundsException ioobe){ ioobe.printStackTrace(); }

    }


问:
Custom "Repair" and "Uninstall" functions for MSI installers (when called from the Control Panel)
The Add/Remove Programs (or Programs and Features) Control Panel applet usually allows to uninstall or repair a program.

For a non-MSI installation it's easy to define what should happen, when a user clicks the "Change" or "Uninstall" button. Just set the appropriate keys in the Registry (HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\<AppName>).

My question is how to make the "Change", "Repair", and "Uninstall" buttons to work my way (e.g. to start a custom program) if an MSI-installation is used?

答:
In MSI parlance that would be kicking off of a custom action (which can be a .EXE). Windows installer has a pretty steep learning curve... and generally trying to make it "work my way" is a short cut to lots of frustration.

If you're headed down this route you should look into Wix.sourceforge.net. Its got a very active user community that is deeply knowledgeable about windows installer.

OwnerDisplayName: Toro

LastEditorDisplayName: Jeffrey Hantin

ContentLicense: CC BY-SA 2.5


问:
How to find the list of pairs in an array using ruby?
Input:

```<code>a = [4, 5, 5, 5, 6, 6, 4, 1, 4, 4, 3, 6, 6, 3, 6, 1, 4, 5, 5, 5]
</code>```

How to list out no of pairs in an array.

Output:

9

Description

```<code>#no 1(1 pair)
#no 3(1 pair)
#no 4(2 pairs)
#no 5(3 pairs)
#no 6(2 pairs)
#so total 9 pairs
</code>```

答:
```<code>arr = [4, 5, 5, 5, 6, 6, 4, 1, 4, 4, 3, 6, 6, 3, 6, 1, 4, 5, 5, 5]
hash = Hash.new(0)
arr.each { |e| hash[e] += 1 }
hash.values.reduce(0) { |s, n| s += n / 2 } // => 9
</code>```

Since from what I can gather you are basically removing integers the moment they got paired once so technically it's just an integer division by two.

[1] How to count identical string elements in a Ruby array

[2] Reduce Hash Values

Body:
Input:

a = [4, 5, 5, 5, 6, 6, 4, 1, 4, 4, 3, 6, 6, 3, 6, 1, 4, 5, 5, 5]

How to list out no of pairs in an array.

Output:

9

Description

#no 1(1 pair)
#no 3(1 pair)
#no 4(2 pairs)
#no 5(3 pairs)
#no 6(2 pairs)
#so total 9 pairs

Body:
arr = [4, 5, 5, 5, 6, 6, 4, 1, 4, 4, 3, 6, 6, 3, 6, 1, 4, 5, 5, 5]
hash = Hash.new(0)
arr.each { |e| hash[e] += 1 }
hash.values.reduce(0) { |s, n| s += n / 2 } // => 9

Since from what I can gather you are basically removing integers the moment they got paired once so technically it's just an integer division by two.

[1] How to count identical string elements in a Ruby array

[2] Reduce Hash Values


问:
Axios unable to get JSON from Django view
I want to implement a front-end and back-end data interaction with axios and django view. Now I have succeed in posting data to django view with code below.

```<code>axios.post("{% url 'main:getCommodityInfo'%}",
                        param,
                        {headers:{'X-CSRFToken': this.getCookie('csrftoken')}})
                .then(response=>{
                  console.log(response);
                  alert("response has been caught");
                })
                .catch(error=>{
                  console.log(error);
                  alert("connection has error")
                })
</code>```

But when I want to return json from view to axios:

```<code>def getCommodityInfo(request):
    if request.method=="POST":
        # get POST parameters
        searchKey = request.POST.get('searchKey')
        category = request.POST.get('category')
        print("Enter the POST view!  ", searchKey, category)
        # unique ID for each record for DB
        uniqueId = str(uuid4())
        # spider setting
        settings = {
            'unique_id': uniqueId,
            'USER_AGENT': 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'
        }
        # taskId to indentify each task
        task = scrapyd.schedule('JDSpider', 'getCommodityInfo',
                                settings=settings, searchKey=searchKey, category=category)

        print("It seems everything is running well? ")
        return JsonResponse({'taskId': task, 'uniqueId': uniqueId, 'status': 'started'},safe=False)
</code>```

the browser has no change! Firstly, I tried to figure out why it occurred independently. The potential clue maybe lie in urls.py.

```<code>urlpatterns = [
    # eg:127.0.0.1:8000/main/
    path('', views.index, name = 'index'),
    path('getCommodityInfo/',views.getCommodityInfo, name = 'getCommodityInfo'),
    path('getCommodityCommentDetail/',views.getCommodityCommentDetail, name="getCommodityCommentDetail"),
    path('commodityInfo/<str:category>/<str:searchKey>/',views.commodityInfoPage, name = 'commodityInfoPage'),
    path('commentsInfo/<str:commodityId>/',views.commodityCommentPage,name = 'commodityCommentPage'),
    # path('?searchkey=<str:searchKey>&categroy=<str:category>/',views.getCommodityInfo, name = 'getCommodityInfo'),
]
</code>```

Because I found that the initial url http://127.0.0.1:8000/main/ in my browser after clicking on the button to post data to getCommodityInfo view became http://127.0.0.1:8000/main/?searchKey=switch&category=Electronics . This url seems not to match any url patterns in urls.py. So I tried to append an additional urlpattern path('?searchkey=<str:searchKey>&categroy=<str:category>/',views.getCommodityInfo, name = 'getCommodityInfo'). Unfortunately, it doesn't work.

After that, I am searching for a long time on net. But no use. Please tell me whether my idea to solve right. Or try to give some ideas how to achieve this.Thanks in advance.

Edit 1  My console logs were asked.

This is my console log after click the button to post data.

And when I click on the alert, the browser go to http://127.0.0.1:8000/main/?searchKey=switch&category=Electronics and the chrome network loading shows like:

And there are no log output in console.

Edit 2  There are some doubts on whether axios send the request by POST or GET, and I try to indentify it in my django view

My python console output this, meaning getCommodityInfo did indentify the request as POST(You could review my code)

Edit 3  @dirkgroten pointed out likely I have sended both POST and GET. So I give the whole code related in my template

And here is my form. And whole js related.

```<code><form action="" id="searchForm">
<label for="searchKey">KeyWords</label>
<input v-model="searchKey" palceholder="Input Search Key" type="string" class="form-control" id="searchKey" name="searchKey">
<label for="category">Commodity Category</label>
<select v-model="selected" id="category" name="category">
    <option v-for="option in options" v-bind:value="option.value">
        ${option.text}
    </option>
</select>

<button v-on:click="startSpider"  class="btn btn-default" >Submit</button>
<p>KeyWords : ${ searchKey }</p>
<p>Category : ${ selected }</p>

</form>

<script type="text/javascript">
    var searchApp = new Vue({
        delimiters:['${','}'],
        el: "#searchForm",
        data:{
          searchKey:'',
          selected:'',
          options: [
            {text: 'Baby', value:'Baby'},
            {text: 'Book', value:'Book'},
            {text: 'Electronics', value:'Electronics'},
            {text: 'Fashion', value:'Fashion'},
            {text: 'Food', value:'Food'},
            {text: 'Health&Beauty', value:'Health&Beauty'},
            {text: 'Home', value:'Home'},
            {text: 'Industrial&Scientific', value:'Industrial&Scientific'},
            {text: 'Motor', value:'Motor'},
            {text: 'Pet', value:'Pet'},
            {text: 'Sports', value:'Sports'},
            {text: 'Other', value:'Other'},
          ]
        },
        created:function(){
          this.selected = "";
        },
        methods:{
          startSpider:function(event){
            console.log(this.searchKey);
            console.log(this.selected);
            alert("spider is ready to run!");
            var param = new URLSearchParams();
            param.append('searchKey',this.searchKey);
            param.append('category',this.selected);

            axios.post("{% url 'main:getCommodityInfo'%}",
                        param,
                        {headers:{'X-CSRFToken': this.getCookie('csrftoken')}})
                .then(response=>{
                  this.searchKey = "!!!";
                  this.category = "Baby";
                  console.log(response.data)
                  alert("response has been caught");
                  console.log(response.data)
                })
                .catch(error=>{
                  console.log(error);
                  alert("connection has error")
                })
          },
          getCookie:function(name) {
              var value = '; ' + document.cookie
              var parts = value.split('; ' + name + '=')
              if (parts.length === 2) return parts.pop().split(';').shift()
            },
        }
    });
</script>
</code>```

答: Acutally, I have found the mistake. It's all about the <form>... The solution is here

Body:
I want to implement a front-end and back-end data interaction with axios and django view. Now I have succeed in posting data to django view with code below.

axios.post("{% url 'main:getCommodityInfo'%}",
                        param,
                        {headers:{'X-CSRFToken': this.getCookie('csrftoken')}})
                .then(response=>{
                  console.log(response);
                  alert("response has been caught");
                })
                .catch(error=>{
                  console.log(error);
                  alert("connection has error")
                })

But when I want to return json from view to axios:

def getCommodityInfo(request):
    if request.method=="POST":
        # get POST parameters
        searchKey = request.POST.get('searchKey')
        category = request.POST.get('category')
        print("Enter the POST view!  ", searchKey, category)
        # unique ID for each record for DB
        uniqueId = str(uuid4())
        # spider setting
        settings = {
            'unique_id': uniqueId,
            'USER_AGENT': 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'
        }
        # taskId to indentify each task
        task = scrapyd.schedule('JDSpider', 'getCommodityInfo',
                                settings=settings, searchKey=searchKey, category=category)

        print("It seems everything is running well? ")
        return JsonResponse({'taskId': task, 'uniqueId': uniqueId, 'status': 'started'},safe=False)

the browser has no change! Firstly, I tried to figure out why it occurred independently. The potential clue maybe lie in urls.py.

urlpatterns = [
    # eg:127.0.0.1:8000/main/
    path('', views.index, name = 'index'),
    path('getCommodityInfo/',views.getCommodityInfo, name = 'getCommodityInfo'),
    path('getCommodityCommentDetail/',views.getCommodityCommentDetail, name="getCommodityCommentDetail"),
    path('commodityInfo/<str:category>/<str:searchKey>/',views.commodityInfoPage, name = 'commodityInfoPage'),
    path('commentsInfo/<str:commodityId>/',views.commodityCommentPage,name = 'commodityCommentPage'),
    # path('?searchkey=<str:searchKey>&categroy=<str:category>/',views.getCommodityInfo, name = 'getCommodityInfo'),
]

Because I found that the initial url http://127.0.0.1:8000/main/ in my browser after clicking on the button to post data to getCommodityInfo view became http://127.0.0.1:8000/main/?searchKey=switch&category=Electronics . This url seems not to match any url patterns in urls.py. So I tried to append an additional urlpattern path('?searchkey=<str:searchKey>&categroy=<str:category>/',views.getCommodityInfo, name = 'getCommodityInfo'). Unfortunately, it doesn't work.

After that, I am searching for a long time on net. But no use. Please tell me whether my idea to solve right. Or try to give some ideas how to achieve this.Thanks in advance.

Edit 1  My console logs were asked.

This is my console log after click the button to post data.

And when I click on the alert, the browser go to http://127.0.0.1:8000/main/?searchKey=switch&category=Electronics and the chrome network loading shows like:

And there are no log output in console.

Edit 2  There are some doubts on whether axios send the request by POST or GET, and I try to indentify it in my django view

My python console output this, meaning getCommodityInfo did indentify the request as POST(You could review my code)

Edit 3  @dirkgroten pointed out likely I have sended both POST and GET. So I give the whole code related in my template

And here is my form. And whole js related.

<form action="" id="searchForm">
KeyWords
<input v-model="searchKey" palceholder="Input Search Key" type="string" class="form-control" id="searchKey" name="searchKey">
Commodity Category
<select v-model="selected" id="category" name="category">
    <option v-for="option in options" v-bind:value="option.value">
        ${option.text}
    </option>
</select>

<button v-on:click="startSpider"  class="btn btn-default" >Submit</button>

KeyWords : ${ searchKey }

Category : ${ selected }

</form>


问:
Use gradle module as a dependency with specific flavor
I have a library module called library that has two flavors flavor1 and flavor2. Then I have two application modules, lets call them app1 and app2 that will use this library module and each one will use it with specific flavor .. eg. app1 will always use library with flavor1 flavor. How should I configure gradle dependencies to make it do what I want to? If I try just implementation project(':library') in app1 build.gradle it obviously does not work because it doesn't know which flavor to choose .. so I’ve tried something like implementation project(path: ':library', configuration: 'flavor1Release') but  that does not work too, it prints a lot of errors like

```<code>ERROR: Unable to resolve dependency for ':app1@debug/compileClasspath': Could not resolve project :library.
Show Details
Affected Modules: app1

ERROR: Unable to resolve dependency for ':app1@debugAndroidTest/compileClasspath': Could not resolve project :library.
Show Details
Affected Modules: app1

ERROR: Unable to resolve dependency for ':app1@debugUnitTest/compileClasspath': Could not resolve project :library.
Show Details
Affected Modules: app1

ERROR: Unable to resolve dependency for ':app1@release/compileClasspath': Could not resolve project :library.
Show Details
Affected Modules: app1

ERROR: Unable to resolve dependency for ':app1@releaseUnitTest/compileClasspath': Could not resolve project :library.
Show Details
Affected Modules: app1
</code>```

I've seen some questions here on SO like here that says to copy flavors from library module to main app module, but it does not make sense to me, app1 doesn't know anything about flavor2 and I don't want to introduce it there.

答:
You should define missingDimensionStrategy for both app1 and app2.

For example:

```<code>// app1/build.gradle

 defaultConfig {
    missingDimensionStrategy 'library', 'flavor1'
}

// app2/build.gradle

 defaultConfig {
    missingDimensionStrategy 'library', 'flavor2'
}
</code>```

Body:
I have a library module called library that has two flavors flavor1 and flavor2. Then I have two application modules, lets call them app1 and app2 that will use this library module and each one will use it with specific flavor .. eg. app1 will always use library with flavor1 flavor. How should I configure gradle dependencies to make it do what I want to? If I try just implementation project(':library') in app1 build.gradle it obviously does not work because it doesn't know which flavor to choose .. so I’ve tried something like implementation project(path: ':library', configuration: 'flavor1Release') but  that does not work too, it prints a lot of errors like

ERROR: Unable to resolve dependency for ':app1@debug/compileClasspath': Could not resolve project :library.
Show Details
Affected Modules: app1

ERROR: Unable to resolve dependency for ':app1@debugAndroidTest/compileClasspath': Could not resolve project :library.
Show Details
Affected Modules: app1

ERROR: Unable to resolve dependency for ':app1@debugUnitTest/compileClasspath': Could not resolve project :library.
Show Details
Affected Modules: app1

ERROR: Unable to resolve dependency for ':app1@release/compileClasspath': Could not resolve project :library.
Show Details
Affected Modules: app1

ERROR: Unable to resolve dependency for ':app1@releaseUnitTest/compileClasspath': Could not resolve project :library.
Show Details
Affected Modules: app1

I've seen some questions here on SO like here that says to copy flavors from library module to main app module, but it does not make sense to me, app1 doesn't know anything about flavor2 and I don't want to introduce it there.

Body:
You should define missingDimensionStrategy for both app1 and app2.

For example:

// app1/build.gradle

 defaultConfig {
    missingDimensionStrategy 'library', 'flavor1'
}

// app2/build.gradle

 defaultConfig {
    missingDimensionStrategy 'library', 'flavor2'
}