问:
R vs. SPSS mixed model repeated measures code [from Cross Validated]
NOTE: This question was originally posted on Cross Validated, where it was suggested that it should be asked in StackOverflow instead.

I am trying to model a 3-way repeated measures experiment, FixedFactorA * FixedFactorB * Time[days]. There are no missing observations, but my groups (FactorA * FactorB) are unequal (close, but not completely balanced). From reading online, the best way to model a repeated measures experiment in which observation order matters (due to the response mean and variance changing in a time-dependent way) and for unequal groups is to use a mixed model and specify an appropriate covariance structure.  However, I am new to the idea of mixed models and I am confused as to whether I am using the correct syntax to model what I am trying to model.

I would like to do a full factorial analysis, such that I could detect significant time * factor interactions.  For example, for subjects with FactorA = 1, their responses over time might have a different slope and/or intercept than subjects with FactorA =2.  I also want to be able to check whether certain combinations of FactorA and FactorB have significantly different responses over time (hence the full three-way interaction term).

From reading online, it seems like AR1 is a reasonable covariance structure for longitudinal-like data, so I decided to try that.  Also, I saw that one is supposed to use ML if one plans to compare two different models, so I chose that approach in anticipation of needing to fine-tune the model.  It is also my understanding that the goal is to minimize the AIC during model selection.

This is the code in the log for what I tried in SPSS (for long-form data), which yielded an AIC of 2471:

```<code>MIXED RESPONSE BY FactorA FactorB Day
  /CRITERIA=CIN(95) MXITER(100) MXSTEP(10) SCORING(1) SINGULAR(0.000000000001) HCONVERGE(0,
ABSOLUTE) LCONVERGE(0, ABSOLUTE) PCONVERGE(0.000001, ABSOLUTE)
  /FIXED=FactorA FactorB Day FactorA*FactorB FactorA*Day FactorB*Day FactorA*FactorB*Day | SSTYPE(3)
  /METHOD=ML
  /PRINT=SOLUTION TESTCOV
  /REPEATED=Day | SUBJECT(Subject_ID) COVTYPE(AR1)
</code>```

This is what I tried in R, which yielded an AIC of 2156:

```<code>    require(nlme)

    #output error fix: https://stats.stackexchange.com/questions/40647/lme-error-iteration-limit-reached

    ctrl <- lmeControl(opt='optim')  #I used this b/c otherwise I get the iteration limit reached error

    fit1 <- lme(RESPONSE ~ Day*FactorA*FactorB, random = ~ Day|Subject_ID, control=ctrl,
        correlation=corAR1(form=~Day), data, method="ML")

    summary(fit1)
</code>```

These are my questions:

The SPSS code above yielded a model with AIC = 2471, while the R code yielded a model with AIC = 2156.  What is it about the codes that makes the models different?

From what I described above, are either of these models appropriate for what I am trying to test? If not, what would be a better way, and how would I do it in both programs to get the same results?

Edits

Another thing to note is that I didn't dummy-code my factors.  I don't know if this is a problem for either software, or if the built-in coding is different in SPSS vs R.  I also don't know if this will be a problem for my three-way interaction term.

Also, when I say "factor", I mean an unchanging group or characteristic (like "sex").

答:
Start with an unconditional model, one with an identity variance-covariance structure at level-1 and one with an AR(1) var-covar structure at level 1:

```<code>unconditional.identity<-lme(RESPONSE~Day, random=~Day|Subject_ID, data=data, method='ML')
unconditional.ar1<-lme(RESPONSE~Day, random=~Day|Subject_ID, correlation=corAR1(form=~Day), data=data, method='ML')
</code>```

Find the intra-class correlation coefficient of this unconditional model, which is the level-2 error divided by the sum of level-1 and level-2 errors. This is probably easier in a spreadsheet program, but in R:

intervals(unconditional.identity)$reStruct$Subject_ID[2]^2/(intervals(unconditional.identity)$reStruct$Subject_ID[2]^2+intervals(unconditional.identity)$sigma[2]^2)

intervals(unconditional.ar1)$reStruct$Subject_ID[2]^2/(intervals(unconditional.ar1)$reStruct$Subject_ID[2]^2+intervals(unconditional.ar1)$sigma[2]^2)

It depends on your field, but in educational research, an ICC below 0.2, definitely below 0.1, is considered not ready for hierarchical linear models. That is to say, multiple regression would be better because the assumption of independence is confirmed. If your ICC is below a cutoff for your field, then do not use a hierarchical longitudinal model.

If your ICC is acceptable for hierarchical linear models, then add in your control grouping variable with identity and AR(1) var-covar matrix:

```<code>conditional1.identity<-lme(RESPONSE~Day+Group, random=~Day+Group|Subject_ID, data=data, method='ML')
conditional1.ar1<-lme(RESPONSE~Day+Group, random=~Day+Group|Subject_ID, correlation=corAR1(form=~Day), data=data, method='ML')
</code>```

If your factors are time-invariant (which you said on Cross Validated), then your model gets bigger because time and group are nested in these fixed effects:

```<code>conditional2.identity<-lme(RESPONSE~Day+Group+FactorA+FactorB+FactorA*Day+FactorB*Day+FactorA*Group+FactorB*Group+FactorB, random=~Day+Group|Subject_ID, data=data, method='ML')
conditional2.ar1<-lme(Day+Group+FactorA+FactorB+FactorA*Day+FactorB*Day+FactorA*Group+FactorB*Group+FactorB, random=~Day+Group|Subject_ID, correlation=corAR1(form=~Day), data=data, method='ML')
</code>```

You can get confidence intervals on the coefficients with intervals() or p-values with summary(). Remember, lme reports error terms in standard deviation format.

I do not know your area of study, so I can't say if your three-way interaction effect makes theoretical sense. But your model is getting quite dense at this point. The more parameters you estimate, the more degrees of freedom the model has when you compare them, so the statistical significance will be biased. If you are really interested in a three-way interaction effect, I suggest you consider the theoretical meaning of such an interaction and what it would mean if such an interaction did occur. Nonetheless, you can estimate it by adding it to the code above:

```<code>conditional3.identity<-lme(RESPONSE~Day+Group+FactorA+FactorB+FactorA*Day+FactorB*Day+FactorA*Group+FactorB*Group+FactorB+Day*FactorA*FactorB, random=~Day+Group|Subject_ID, data=data, method='ML')
conditional3.ar1<-lme(Day+Group+FactorA+FactorB+FactorA*Day+FactorB*Day+FactorA*Group+FactorB*Group+FactorB+Day*FactorA*FactorB, random=~Day+Group|Subject_ID, correlation=corAR1(form=~Day), data=data, method='ML')
</code>```

Finally, compare the nested models:

anova(unconditional.identity,conditional1.identity,conditional2.identity,conditional3.identity)

anova(unconditional.ar1,conditional1.ar1,conditional2.ar1,conditional3.ar1)

Like I said, the more parameters you estimate, the more biased your statistical significance will be: i.e., more parameters = more degrees of freedom = less chance of a statistically significant model.

HOWEVER, the best part about multi-level models is comparing effect sizes, so then you don't have to worry about p-values at all. Effect sizes are in the form of a "proportional reduction in variance explained."

This is comparing models. For example, to comapre the proportional reduction in variance explained in level 1 from the unconditional model to the conditional1 model:

(intervals(unconditional.identity)$sigma[2]^2 - intervals(conditional1.identity)$sigma[2]^2) / intervals(unconditional.identity)$sigma[2]^2

Hopefully you can "plug and play" the same code for the number of level-2 error terms you have (which is more than one in some of your cases). Make sure to compare only nested models in this way.

Body:
NOTE: This question was originally posted on Cross Validated, where it was suggested that it should be asked in StackOverflow instead.

I am trying to model a 3-way repeated measures experiment, FixedFactorA * FixedFactorB * Time[days]. There are no missing observations, but my groups (FactorA * FactorB) are unequal (close, but not completely balanced). From reading online, the best way to model a repeated measures experiment in which observation order matters (due to the response mean and variance changing in a time-dependent way) and for unequal groups is to use a mixed model and specify an appropriate covariance structure.  However, I am new to the idea of mixed models and I am confused as to whether I am using the correct syntax to model what I am trying to model.

I would like to do a full factorial analysis, such that I could detect significant time * factor interactions.  For example, for subjects with FactorA = 1, their responses over time might have a different slope and/or intercept than subjects with FactorA =2.  I also want to be able to check whether certain combinations of FactorA and FactorB have significantly different responses over time (hence the full three-way interaction term).

From reading online, it seems like AR1 is a reasonable covariance structure for longitudinal-like data, so I decided to try that.  Also, I saw that one is supposed to use ML if one plans to compare two different models, so I chose that approach in anticipation of needing to fine-tune the model.  It is also my understanding that the goal is to minimize the AIC during model selection.

This is the code in the log for what I tried in SPSS (for long-form data), which yielded an AIC of 2471:

MIXED RESPONSE BY FactorA FactorB Day
  /CRITERIA=CIN(95) MXITER(100) MXSTEP(10) SCORING(1) SINGULAR(0.000000000001) HCONVERGE(0,
ABSOLUTE) LCONVERGE(0, ABSOLUTE) PCONVERGE(0.000001, ABSOLUTE)
  /FIXED=FactorA FactorB Day FactorA*FactorB FactorA*Day FactorB*Day FactorA*FactorB*Day | SSTYPE(3)
  /METHOD=ML
  /PRINT=SOLUTION TESTCOV
  /REPEATED=Day | SUBJECT(Subject_ID) COVTYPE(AR1)

This is what I tried in R, which yielded an AIC of 2156:

    require(nlme)

    #output error fix: https://stats.stackexchange.com/questions/40647/lme-error-iteration-limit-reached

    ctrl <- lmeControl(opt='optim')  #I used this b/c otherwise I get the iteration limit reached error

    fit1 <- lme(RESPONSE ~ Day*FactorA*FactorB, random = ~ Day|Subject_ID, control=ctrl,
        correlation=corAR1(form=~Day), data, method="ML")

    summary(fit1)

These are my questions:

The SPSS code above yielded a model with AIC = 2471, while the R code yielded a model with AIC = 2156.  What is it about the codes that makes the models different?

From what I described above, are either of these models appropriate for what I am trying to test? If not, what would be a better way, and how would I do it in both programs to get the same results?

Edits

Another thing to note is that I didn't dummy-code my factors.  I don't know if this is a problem for either software, or if the built-in coding is different in SPSS vs R.  I also don't know if this will be a problem for my three-way interaction term.

Also, when I say "factor", I mean an unchanging group or characteristic (like "sex").

Body:
Start with an unconditional model, one with an identity variance-covariance structure at level-1 and one with an AR(1) var-covar structure at level 1:

unconditional.identity<-lme(RESPONSE~Day, random=~Day|Subject_ID, data=data, method='ML')
unconditional.ar1<-lme(RESPONSE~Day, random=~Day|Subject_ID, correlation=corAR1(form=~Day), data=data, method='ML')

Find the intra-class correlation coefficient of this unconditional model, which is the level-2 error divided by the sum of level-1 and level-2 errors. This is probably easier in a spreadsheet program, but in R:

intervals(unconditional.identity)$reStruct$Subject_ID[2]^2/(intervals(unconditional.identity)$reStruct$Subject_ID[2]^2+intervals(unconditional.identity)$sigma[2]^2)

intervals(unconditional.ar1)$reStruct$Subject_ID[2]^2/(intervals(unconditional.ar1)$reStruct$Subject_ID[2]^2+intervals(unconditional.ar1)$sigma[2]^2)

It depends on your field, but in educational research, an ICC below 0.2, definitely below 0.1, is considered not ready for hierarchical linear models. That is to say, multiple regression would be better because the assumption of independence is confirmed. If your ICC is below a cutoff for your field, then do not use a hierarchical longitudinal model.

If your ICC is acceptable for hierarchical linear models, then add in your control grouping variable with identity and AR(1) var-covar matrix:

conditional1.identity<-lme(RESPONSE~Day+Group, random=~Day+Group|Subject_ID, data=data, method='ML')
conditional1.ar1<-lme(RESPONSE~Day+Group, random=~Day+Group|Subject_ID, correlation=corAR1(form=~Day), data=data, method='ML')

If your factors are time-invariant (which you said on Cross Validated), then your model gets bigger because time and group are nested in these fixed effects:

conditional2.identity<-lme(RESPONSE~Day+Group+FactorA+FactorB+FactorA*Day+FactorB*Day+FactorA*Group+FactorB*Group+FactorB, random=~Day+Group|Subject_ID, data=data, method='ML')
conditional2.ar1<-lme(Day+Group+FactorA+FactorB+FactorA*Day+FactorB*Day+FactorA*Group+FactorB*Group+FactorB, random=~Day+Group|Subject_ID, correlation=corAR1(form=~Day), data=data, method='ML')

You can get confidence intervals on the coefficients with intervals() or p-values with summary(). Remember, lme reports error terms in standard deviation format.

I do not know your area of study, so I can't say if your three-way interaction effect makes theoretical sense. But your model is getting quite dense at this point. The more parameters you estimate, the more degrees of freedom the model has when you compare them, so the statistical significance will be biased. If you are really interested in a three-way interaction effect, I suggest you consider the theoretical meaning of such an interaction and what it would mean if such an interaction did occur. Nonetheless, you can estimate it by adding it to the code above:

conditional3.identity<-lme(RESPONSE~Day+Group+FactorA+FactorB+FactorA*Day+FactorB*Day+FactorA*Group+FactorB*Group+FactorB+Day*FactorA*FactorB, random=~Day+Group|Subject_ID, data=data, method='ML')
conditional3.ar1<-lme(Day+Group+FactorA+FactorB+FactorA*Day+FactorB*Day+FactorA*Group+FactorB*Group+FactorB+Day*FactorA*FactorB, random=~Day+Group|Subject_ID, correlation=corAR1(form=~Day), data=data, method='ML')

Finally, compare the nested models:

anova(unconditional.identity,conditional1.identity,conditional2.identity,conditional3.identity)

anova(unconditional.ar1,conditional1.ar1,conditional2.ar1,conditional3.ar1)

Like I said, the more parameters you estimate, the more biased your statistical significance will be: i.e., more parameters = more degrees of freedom = less chance of a statistically significant model.

HOWEVER, the best part about multi-level models is comparing effect sizes, so then you don't have to worry about p-values at all. Effect sizes are in the form of a "proportional reduction in variance explained."

This is comparing models. For example, to comapre the proportional reduction in variance explained in level 1 from the unconditional model to the conditional1 model:

(intervals(unconditional.identity)$sigma[2]^2 - intervals(conditional1.identity)$sigma[2]^2) / intervals(unconditional.identity)$sigma[2]^2

Hopefully you can "plug and play" the same code for the number of level-2 error terms you have (which is more than one in some of your cases). Make sure to compare only nested models in this way.


来源: stackexchange

问:
Webpack ProvidePlugin global variable (Cannot find module)
I'm pretty new to Webpack, but can't figure out why my ProvidePlugin call is not working as expected.

I have the following file:

App.js

var App = function() {
    getSomething: function(size) {}
}();

module.exports = App;
```

<p>I want this 'App' variable to be globally accessible because other files use it like this:</p>

<h2>Layout.js</h2>

<pre class="lang-js prettyprint-override"><code>var Layout = function () {
    App.getSomething('md');
}();
</code>```

webpack.config.js

In webpack.config.js I have the following line:

new webpack.ProvidePlugin({ App: 'app' })
```

<p>This is my entry:</p>

<pre class="lang-js prettyprint-override"><code>entry: {
    'app': './angularApp/metronicapp.ts',
}
</code>```

metronicapp.ts

import './metronic/global/scripts/app';```

Where app is my app.js which is displayed above.

I get the following error in the browser:
Cannot find module "app"

And when I compile webpack in the console:
Module not found: Error: Can't resolve 'app'

I can't figure what I'm missing. Is my app.js not in the correct format? Why is App still not available globally?

答:
webpack.config.js

ProvidePlugin needs the path to your global module App.js.

```<code>const path = require('path');
...
plugins: [
  new webpack.ProvidePlugin({
    App: path.resolve(__dirname, './path_to_App.js')
  })
]
</code>```

global.d.ts

For Typescript not to complain about undefined constructs create
global.d.ts

```<code>declare var App: any;
</code>```

metronicapp.ts

No need to import ./metronic/global/scripts/app inside metronicapp.ts, webpack will resolve App on build.

```<code>App.getSomething('foo');
</code>```

Layout.js

```<code>var Layout = function() {
  App.getSomething('md');
}();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm pretty new to Webpack, but can't figure out why my ProvidePlugin call is not working as expected.

I have the following file:

App.js

var App = function() {
    getSomething: function(size) {}
}();

module.exports = App;

I want this 'App' variable to be globally accessible because other files use it like this:

Layout.js

var Layout = function () {
    App.getSomething('md');
}();

webpack.config.js

In webpack.config.js I have the following line:

new webpack.ProvidePlugin({ App: 'app' })

This is my entry:

entry: {
    'app': './angularApp/metronicapp.ts',
}

metronicapp.ts

import './metronic/global/scripts/app';

Where app is my app.js which is displayed above.

I get the following error in the browser:
Cannot find module "app"

And when I compile webpack in the console:
Module not found: Error: Can't resolve 'app'

I can't figure what I'm missing. Is my app.js not in the correct format? Why is App still not available globally?

Body:
webpack.config.js

ProvidePlugin needs the path to your global module App.js.

const path = require('path');
...
plugins: [
  new webpack.ProvidePlugin({
    App: path.resolve(__dirname, './path_to_App.js')
  })
]

global.d.ts

For Typescript not to complain about undefined constructs create
global.d.ts

declare var App: any;

metronicapp.ts

No need to import ./metronic/global/scripts/app inside metronicapp.ts, webpack will resolve App on build.

App.getSomething('foo');

Layout.js

var Layout = function() {
  App.getSomething('md');
}();


问:
Using array_push() to add elements to an array in the form of 'key => object'
I have a set of objects I want to put into an array and I want to distinguish them with keys.

The initial code I wrote was:

```<code>array_push($array[$key], new myObj(param1, param2, etc));
</code>```

When I run it I get the warning:

```<code>PHP Warning:  array_push() expects parameter 1 to be array, null given in file.php on line 56
</code>```

I added a var_dump() to see what was actually happening and it was filling the array with each element '$key => null'  as suggested by the error.

If I remove the [$key] from the line then it fills the array with instances of myObj as expected so I know that the constructor is functioning correctly and not really returning 'null'.

答:
Keys in associative arrays need to be unique, so if you want to keep the notion of a key/value pair where you can access things directly by the key, don't use array_push, simply set the key (this is fine to do in PHP):

```<code>$array[$key] = new myObj(param1, param2, etc)
</code>```

On the other hand, if you want to have a list of key/value pairs, like a stack, and you're adding just one key/value pair at a time, don't use array_push, simply add to the array using PHP's shorthand syntax (as the manual says, this is faster as it saves you a function call):

```<code>$stack[] = array($key => new myObj(param1, param2, etc));
</code>```

One more possibility, if you have a bunch of key/value pairs, and you want to add all of them to some stack like structure (but not be able to index directly by some key), then you should use array_push:

```<code>array_push($stack,
    array($key1 => new myObj(param1, param2, etc)),
    array($key2 => new myObj(param3, param4, etc))
);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a set of objects I want to put into an array and I want to distinguish them with keys.

The initial code I wrote was:

array_push($array[$key], new myObj(param1, param2, etc));

When I run it I get the warning:

PHP Warning:  array_push() expects parameter 1 to be array, null given in file.php on line 56

I added a var_dump() to see what was actually happening and it was filling the array with each element '$key => null'  as suggested by the error.

If I remove the [$key] from the line then it fills the array with instances of myObj as expected so I know that the constructor is functioning correctly and not really returning 'null'.

Body:
Keys in associative arrays need to be unique, so if you want to keep the notion of a key/value pair where you can access things directly by the key, don't use array_push, simply set the key (this is fine to do in PHP):

$array[$key] = new myObj(param1, param2, etc)

On the other hand, if you want to have a list of key/value pairs, like a stack, and you're adding just one key/value pair at a time, don't use array_push, simply add to the array using PHP's shorthand syntax (as the manual says, this is faster as it saves you a function call):

$stack[] = array($key => new myObj(param1, param2, etc));

One more possibility, if you have a bunch of key/value pairs, and you want to add all of them to some stack like structure (but not be able to index directly by some key), then you should use array_push:

array_push($stack,
    array($key1 => new myObj(param1, param2, etc)),
    array($key2 => new myObj(param3, param4, etc))
);


问:
How to use multiple && ORs in a PHP If statement?
How I adjust this in order to get the brackets to work?</p>

```<code>if (mysql_num_rows($printPricealertsdata) < 5 && ($_POST['pricetype'] == "pricebelow" && $_POST['price'] < $marketdata['priceusd']) OR ($_POST['pricetype'] == "priceabove" && $_POST['price'] > $marketdata['priceusd'])) {
   echo "success";
}else{
   echo "fail";
}
</code>```

答:
Try this (without placing brackets around each condition):</p>

```<code>if(mysql_num_rows($printPricealertsdata) < 5 && $_POST['pricetype'] == "pricebelow" && $_POST['price'] < $marketdata['priceusd']) OR $_POST['pricetype'] == "priceabove" && $_POST['price'] > $marketdata['priceusd']) {
   echo "success";
}else{
   echo "fail";
}
</code>```

Body:
How I adjust this in order to get the brackets to work?

if (mysql_num_rows($printPricealertsdata) < 5 && ($_POST['pricetype'] == "pricebelow" && $_POST['price'] < $marketdata['priceusd']) OR ($_POST['pricetype'] == "priceabove" && $_POST['price'] > $marketdata['priceusd'])) {
   echo "success";
}else{
   echo "fail";
}

Body:
Try this (without placing brackets around each condition):

if(mysql_num_rows($printPricealertsdata) < 5 && $_POST['pricetype'] == "pricebelow" && $_POST['price'] < $marketdata['priceusd']) OR $_POST['pricetype'] == "priceabove" && $_POST['price'] > $marketdata['priceusd']) {
   echo "success";
}else{
   echo "fail";
}


问:
Create EXCEL and open it
I'm creating an excel file, and I must open it immediately.
Obviously, when I create it on localhost, I can get the file, but when I publish my web application on IIS this not works because I suppose It's creating on server side...

So I create the excel file and try to upload to the server and after that download it, but I can't create it, If I run this on localhost works, but when I publish don't work.

Any advice?

this is my code:

I use this libraries for Excel:

```<code>using Microsoft.Office.Core;
using Excelo = Microsoft.Office.Interop.Excel;
using Microsoft.Office.Interop;
using System.Reflection;
using System.Globalization;
</code>```

Then, I start my excel file:

```<code>private void sacConsulPend_GenRemito()
{   // DB
    string conn = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
    DataSet dsRemito = new DataSet();
    DataTable dtCons = new DataTable();

    using (SqlConnection sqlCon = new SqlConnection(conn))
    {
        using (SqlCommand cmd = new SqlCommand())
        {
            try
            {   //SP for data query
                cmd.CommandType = System.Data.CommandType.StoredProcedure;
                cmd.CommandText = "SACBUS_CONSUL_SOLICITUDEXIST";
                cmd.Parameters.AddWithValue("@ID_CONSULTA",
                    Convert.ToInt32(lblSac_ConPenDet_idCons.Text.Replace(" ", "")));

                cmd.Connection = sqlCon;
                sqlCon.Open();

                SqlDataAdapter dapC = new SqlDataAdapter(cmd);
                dapC.Fill(dsRemito);

            }
            catch (Exception sqlex)
            {
                throw sqlex;
            }
        }
    }

    Excelo.Application oXL;
    Excelo._Workbook oWB;
    Excelo._Worksheet oSheet;
    Excelo.Range oRng;

    try
    {

        //Start Excel
        oXL = new Excelo.Application();

        //new blank workbook.
        oWB = (Excelo._Workbook)(oXL.Workbooks.Add(System.Reflection.Missing.Value));
        oSheet = (Excelo._Worksheet)oWB.ActiveSheet;
        object misValue = System.Reflection.Missing.Value;

        //Text Format
        oSheet.get_Range("A1", "Z1000").Font.Name = "Courier New";
        oSheet.get_Range("A1", "Z1000").Font.Size = 7;
        oSheet.get_Range("A1", "Z1000").Font.Bold = true;
        oSheet.get_Range("A1", "Z1000").NumberFormat = "@";

        oSheet.get_Range("D1", "E1").Cells.Merge();
        oSheet.get_Range("A1", "F1").Font.Bold = true;
        oSheet.get_Range("A1", "F1").Font.Italic = true;
        oSheet.get_Range("A1", "F1").VerticalAlignment = Excelo.XlVAlign.xlVAlignCenter;
        oSheet.get_Range("A1", "F1").HorizontalAlignment = Excelo.XlVAlign.xlVAlignCenter;
        oSheet.get_Range("A1", "F1").Font.Size = 9;

        //Logo Lockers
        oSheet.Shapes.AddPicture(Server.MapPath("~/images/LockersLogo.jpg"), MsoTriState.msoFalse, MsoTriState.msoCTrue, 0, 0, 60, 20);

        /*
        Excel Content
        */

         //Save ExcelFile
        var filePath = Path.Combine(HttpContext.Current.Server.MapPath("~/Files/Envios/"), lblSac_ConPenDet_idCons.Text.Replace(" ", "") + ".xlsx");
        oWB.SaveAs(filePath, Excelo.XlFileFormat.xlOpenXMLWorkbook, Missing.Value,
        Missing.Value, false, false, Excelo.XlSaveAsAccessMode.xlNoChange,
        Excelo.XlSaveConflictResolution.xlUserResolution, true,
        Missing.Value, Missing.Value, Missing.Value);

    }
    catch (Exception thex)
    {
        String errorMessage;
        errorMessage = "Error en la creacion del archivo Excel: ";
        errorMessage = String.Concat(errorMessage, thex.Message);
        errorMessage = String.Concat(errorMessage, " Line: ");
        errorMessage = String.Concat(errorMessage, thex.Source);
    }

}
</code>```

答:
This is my code now, Using EEPlus It's not finished, but works, creating one file in server side, after that, I download the same created file.

```<code>using OfficeOpenXml;
using System.IO;
using System.Drawing;
using OfficeOpenXml.Drawing;

using System.Data;
using System.Data.SqlClient;
using System.Configuration;
</code>```

This is the most relevant:

```<code>public static string GenerarExcel(DirectoryInfo outputDir)
{
    string conn = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
    DataSet dsRemito = new DataSet();
    DataTable dtCons = new DataTable();

    using (SqlConnection sqlCon = new SqlConnection(conn))
    {
        using (SqlCommand cmd = new SqlCommand())
        {
            try
            {//SP for sql query
                cmd.CommandType = System.Data.CommandType.StoredProcedure;
                cmd.CommandText = "SACBUS_CONSUL_SOLICITUDEXIST";
                cmd.Parameters.AddWithValue("@ID_CONSULTA", 66);
                //66 wil be a variable, this is only for my tests

                cmd.Connection = sqlCon;
                sqlCon.Open();

                SqlDataAdapter dapC = new SqlDataAdapter(cmd);
                dapC.Fill(dsRemito);

            }
            catch (Exception sqlex)
            {
                throw sqlex;
            }
        }
    }

    FileInfo newFile = new FileInfo(outputDir.FullName + @"\Sample1.xlsx");

    if (newFile.Exists)
    {
        newFile.Delete();
        newFile = new FileInfo(outputDir.FullName + @"\Sample1.xlsx"); //preparar nombre archivo
    }

    using (ExcelPackage package = new ExcelPackage(newFile))
    {
        // Agregar hoja a worbook
        ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Envios");

        // Header
        worksheet.Cells[1, 3].Value = "SISTEMA DE GESTIÓN DE CALIDAD ISO 9001:2008";
        worksheet.Cells[2, 3].Value = "PEDIDO DE CONSULTA A BODEGA";
        worksheet.Cells[1, 5].Value = "Código:";
        worksheet.Cells[1, 6].Value = "FOR-PCV-COM-SAC-PEBOD-02  ";
        worksheet.Cells[2, 5, 2, 6].Merge = true;

        // Estilo del Encabezado
        using (var range = worksheet.Cells[1, 1, 1, 5]) // De la celda 1,1 a la 1,5
        {
            range.Style.Font.Bold = true; // Negrita
            range.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid; // Solido lleno
            range.Style.Fill.BackgroundColor.SetColor(Color.DarkBlue); //Background
            range.Style.Font.Color.SetColor(Color.White);// Font color
        }

        // Pie de Pagina
        // lineas en la cuadricula
        worksheet.Cells["A5:E5"].Style.Border.Top.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
        worksheet.Cells["A5:E5"].Style.Font.Bold = true; // estilo del pie de pagina

        //Formatos
        //Formato Numerico
        worksheet.Cells["C2:C5"].Style.Numberformat.Format = "#,##0";   // Formato Entero
        worksheet.Cells["D2:E5"].Style.Numberformat.Format = "#,##0.00";    // Formato Decimal

               worksheet.Cells["A2:A4"].Style.Numberformat.Format = "@"; //Formato texto
        worksheet.Cells.AutoFitColumns(0); //AutoAjustar celdas

        // Numero de pagina + total de paginas a la derecha del pie de pagina
        worksheet.HeaderFooter.OddFooter.RightAlignedText = string.Format("Pagina {0} of {1}", ExcelHeaderFooter.PageNumber, ExcelHeaderFooter.NumberOfPages);

        // Nombre de la hoja al centro del pie de pagina
        worksheet.HeaderFooter.OddFooter.CenteredText = ExcelHeaderFooter.SheetName;

        // Ruta a la izquierda del pie de pagina
        worksheet.HeaderFooter.OddFooter.LeftAlignedText = ExcelHeaderFooter.FilePath + ExcelHeaderFooter.FileName;

        //System.Drawing.Image img = System.Drawing.Image.FromFile(@"C:\temporal\asp\ExcelLibrary\LockersLogo.jpg");
        System.Drawing.Image img = System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath("~/image/LockersLogo.jpg"));

        ExcelPicture pic = worksheet.Drawings.AddPicture("Sample", img);
        pic.SetPosition(0, 0, 6, 0);
        pic.SetSize(150, 75);

        //Items consultados
        var registros = 0;
        for (int i = 0; i < dsRemito.Tables[0].Rows.Count; i++)
        {
            worksheet.Cells[8 + i, 1].Value = dsRemito.Tables[0].Rows[i]["CAJA_CODIGO"];
            worksheet.Cells[8 + i, 2].Value = dsRemito.Tables[0].Rows[i]["CAJA_NUMERO"];
            worksheet.Cells[8 + i, 3].Value = dsRemito.Tables[0].Rows[i]["CAJA_CONTENIDO_NUMERO"];
            worksheet.Cells[8 + i, 4].Value = dsRemito.Tables[0].Rows[i]["ITEM"];

            registros = i;
        }

        package.Save(); //guardar workbook

    }

    return newFile.FullName;
}

protected void DownloadFile()
{

    string rutaUsr = "~/" + "Files/";
    string filePath = rutaUsr + "Sample1" + ".xlsx";
    Response.ContentType = ContentType;
    Response.AppendHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(filePath));
    Response.WriteFile(filePath);
    Response.End();

}

protected void Page_Load(object sender, EventArgs e)
{
    try
    {
        //DirectoryInfo outputDir = new DirectoryInfo(@"C:\temporal\asp\ExcelLibrary");
        DirectoryInfo outputDir = new DirectoryInfo(HttpContext.Current.Server.MapPath("~/Files/"));
        GenerarExcel(outputDir);

        DownloadFile();
    }

    catch (Exception ex)
    {
        Console.WriteLine("Error: {0}", ex.Message);
    }

}
</code>```

Title: Create EXCEL and open it

Body:
I'm creating an excel file, and I must open it immediately.
Obviously, when I create it on localhost, I can get the file, but when I publish my web application on IIS this not works because I suppose It's creating on server side...

So I create the excel file and try to upload to the server and after that download it, but I can't create it, If I run this on localhost works, but when I publish don't work.

Any advice?

this is my code:

I use this libraries for Excel:

using Microsoft.Office.Core;
using Excelo = Microsoft.Office.Interop.Excel;
using Microsoft.Office.Interop;
using System.Reflection;
using System.Globalization;

Then, I start my excel file:

private void sacConsulPend_GenRemito()
{   // DB
    string conn = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
    DataSet dsRemito = new DataSet();
    DataTable dtCons = new DataTable();

    using (SqlConnection sqlCon = new SqlConnection(conn))
    {
        using (SqlCommand cmd = new SqlCommand())
        {
            try
            {   //SP for data query
                cmd.CommandType = System.Data.CommandType.StoredProcedure;
                cmd.CommandText = "SACBUS_CONSUL_SOLICITUDEXIST";
                cmd.Parameters.AddWithValue("@ID_CONSULTA",
                    Convert.ToInt32(lblSac_ConPenDet_idCons.Text.Replace(" ", "")));

                cmd.Connection = sqlCon;
                sqlCon.Open();

                SqlDataAdapter dapC = new SqlDataAdapter(cmd);
                dapC.Fill(dsRemito);

            }
            catch (Exception sqlex)
            {
                throw sqlex;
            }
        }
    }

    Excelo.Application oXL;
    Excelo._Workbook oWB;
    Excelo._Worksheet oSheet;
    Excelo.Range oRng;

    try
    {

        //Start Excel
        oXL = new Excelo.Application();

        //new blank workbook.
        oWB = (Excelo._Workbook)(oXL.Workbooks.Add(System.Reflection.Missing.Value));
        oSheet = (Excelo._Worksheet)oWB.ActiveSheet;
        object misValue = System.Reflection.Missing.Value;

        //Text Format
        oSheet.get_Range("A1", "Z1000").Font.Name = "Courier New";
        oSheet.get_Range("A1", "Z1000").Font.Size = 7;
        oSheet.get_Range("A1", "Z1000").Font.Bold = true;
        oSheet.get_Range("A1", "Z1000").NumberFormat = "@";

        oSheet.get_Range("D1", "E1").Cells.Merge();
        oSheet.get_Range("A1", "F1").Font.Bold = true;
        oSheet.get_Range("A1", "F1").Font.Italic = true;
        oSheet.get_Range("A1", "F1").VerticalAlignment = Excelo.XlVAlign.xlVAlignCenter;
        oSheet.get_Range("A1", "F1").HorizontalAlignment = Excelo.XlVAlign.xlVAlignCenter;
        oSheet.get_Range("A1", "F1").Font.Size = 9;

        //Logo Lockers
        oSheet.Shapes.AddPicture(Server.MapPath("~/images/LockersLogo.jpg"), MsoTriState.msoFalse, MsoTriState.msoCTrue, 0, 0, 60, 20);

        /*
        Excel Content
        */

         //Save ExcelFile
        var filePath = Path.Combine(HttpContext.Current.Server.MapPath("~/Files/Envios/"), lblSac_ConPenDet_idCons.Text.Replace(" ", "") + ".xlsx");
        oWB.SaveAs(filePath, Excelo.XlFileFormat.xlOpenXMLWorkbook, Missing.Value,
        Missing.Value, false, false, Excelo.XlSaveAsAccessMode.xlNoChange,
        Excelo.XlSaveConflictResolution.xlUserResolution, true,
        Missing.Value, Missing.Value, Missing.Value);

    }
    catch (Exception thex)
    {
        String errorMessage;
        errorMessage = "Error en la creacion del archivo Excel: ";
        errorMessage = String.Concat(errorMessage, thex.Message);
        errorMessage = String.Concat(errorMessage, " Line: ");
        errorMessage = String.Concat(errorMessage, thex.Source);
    }

}

Body:
This is my code now, Using EEPlus It's not finished, but works, creating one file in server side, after that, I download the same created file.

using OfficeOpenXml;
using System.IO;
using System.Drawing;
using OfficeOpenXml.Drawing;

using System.Data;
using System.Data.SqlClient;
using System.Configuration;

This is the most relevant:

public static string GenerarExcel(DirectoryInfo outputDir)
{
    string conn = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
    DataSet dsRemito = new DataSet();
    DataTable dtCons = new DataTable();

    using (SqlConnection sqlCon = new SqlConnection(conn))
    {
        using (SqlCommand cmd = new SqlCommand())
        {
            try
            {//SP for sql query
                cmd.CommandType = System.Data.CommandType.StoredProcedure;
                cmd.CommandText = "SACBUS_CONSUL_SOLICITUDEXIST";
                cmd.Parameters.AddWithValue("@ID_CONSULTA", 66);
                //66 wil be a variable, this is only for my tests

                cmd.Connection = sqlCon;
                sqlCon.Open();

                SqlDataAdapter dapC = new SqlDataAdapter(cmd);
                dapC.Fill(dsRemito);

            }
            catch (Exception sqlex)
            {
                throw sqlex;
            }
        }
    }

    FileInfo newFile = new FileInfo(outputDir.FullName + @"\Sample1.xlsx");

    if (newFile.Exists)
    {
        newFile.Delete();
        newFile = new FileInfo(outputDir.FullName + @"\Sample1.xlsx"); //preparar nombre archivo
    }

    using (ExcelPackage package = new ExcelPackage(newFile))
    {
        // Agregar hoja a worbook
        ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Envios");

        // Header
        worksheet.Cells[1, 3].Value = "SISTEMA DE GESTIÓN DE CALIDAD ISO 9001:2008";
        worksheet.Cells[2, 3].Value = "PEDIDO DE CONSULTA A BODEGA";
        worksheet.Cells[1, 5].Value = "Código:";
        worksheet.Cells[1, 6].Value = "FOR-PCV-COM-SAC-PEBOD-02  ";
        worksheet.Cells[2, 5, 2, 6].Merge = true;

        // Estilo del Encabezado
        using (var range = worksheet.Cells[1, 1, 1, 5]) // De la celda 1,1 a la 1,5
        {
            range.Style.Font.Bold = true; // Negrita
            range.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid; // Solido lleno
            range.Style.Fill.BackgroundColor.SetColor(Color.DarkBlue); //Background
            range.Style.Font.Color.SetColor(Color.White);// Font color
        }

        // Pie de Pagina
        // lineas en la cuadricula
        worksheet.Cells["A5:E5"].Style.Border.Top.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
        worksheet.Cells["A5:E5"].Style.Font.Bold = true; // estilo del pie de pagina

        //Formatos
        //Formato Numerico
        worksheet.Cells["C2:C5"].Style.Numberformat.Format = "#,##0";   // Formato Entero
        worksheet.Cells["D2:E5"].Style.Numberformat.Format = "#,##0.00";    // Formato Decimal

               worksheet.Cells["A2:A4"].Style.Numberformat.Format = "@"; //Formato texto
        worksheet.Cells.AutoFitColumns(0); //AutoAjustar celdas

        // Numero de pagina + total de paginas a la derecha del pie de pagina
        worksheet.HeaderFooter.OddFooter.RightAlignedText = string.Format("Pagina {0} of {1}", ExcelHeaderFooter.PageNumber, ExcelHeaderFooter.NumberOfPages);

        // Nombre de la hoja al centro del pie de pagina
        worksheet.HeaderFooter.OddFooter.CenteredText = ExcelHeaderFooter.SheetName;

        // Ruta a la izquierda del pie de pagina
        worksheet.HeaderFooter.OddFooter.LeftAlignedText = ExcelHeaderFooter.FilePath + ExcelHeaderFooter.FileName;

        //System.Drawing.Image img = System.Drawing.Image.FromFile(@"C:\temporal\asp\ExcelLibrary\LockersLogo.jpg");
        System.Drawing.Image img = System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath("~/image/LockersLogo.jpg"));

        ExcelPicture pic = worksheet.Drawings.AddPicture("Sample", img);
        pic.SetPosition(0, 0, 6, 0);
        pic.SetSize(150, 75);

        //Items consultados
        var registros = 0;
        for (int i = 0; i < dsRemito.Tables[0].Rows.Count; i++)
        {
            worksheet.Cells[8 + i, 1].Value = dsRemito.Tables[0].Rows[i]["CAJA_CODIGO"];
            worksheet.Cells[8 + i, 2].Value = dsRemito.Tables[0].Rows[i]["CAJA_NUMERO"];
            worksheet.Cells[8 + i, 3].Value = dsRemito.Tables[0].Rows[i]["CAJA_CONTENIDO_NUMERO"];
            worksheet.Cells[8 + i, 4].Value = dsRemito.Tables[0].Rows[i]["ITEM"];

            registros = i;
        }

        package.Save(); //guardar workbook

    }

    return newFile.FullName;
}

protected void DownloadFile()
{

    string rutaUsr = "~/" + "Files/";
    string filePath = rutaUsr + "Sample1" + ".xlsx";
    Response.ContentType = ContentType;
    Response.AppendHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(filePath));
    Response.WriteFile(filePath);
    Response.End();

}

protected void Page_Load(object sender, EventArgs e)
{
    try
    {
        //DirectoryInfo outputDir = new DirectoryInfo(@"C:\temporal\asp\ExcelLibrary");
        DirectoryInfo outputDir = new DirectoryInfo(HttpContext.Current.Server.MapPath("~/Files/"));
        GenerarExcel(outputDir);

        DownloadFile();
    }

    catch (Exception ex)
    {
        Console.WriteLine("Error: {0}", ex.Message);
    }

}


问:
Vim Map extra keys in Razer keyboard
I just bought a Razer mechanical keyboard with extra keys such as M1, M2 to M5.
I'm wondering whether Vim can map those extra keys?
It would be appreciated if anyone can give me some suggestions on how to do it.</p>

答:
As a start, you could see whether Vim thinks they have a useful value already. iCtrl-v then the key you're interested in. (For example, iCtrl-vEnter produces ^M.) You could then bind the resulting key using nnoremap et al.

If they're not already recognised, the solution will be OS-dependent. You'd need to map the keys to something unused (maybe F15-F20?) and bind those in your .vimrc.

Title: Vim Map extra keys in Razer keyboard


问:
Click All Javascript Jquery
When I run:

javascript:

```<code>var inputs = document.getElementsByClassName('subscribe_follow');

for(var i=0;i<inputs.length;i++) {
   inputs[i].click();
}
</code>```

to click all buttons with the class class="subscribe_follow",
it also clicks all buttons with the class class="subscribe_follow ng-hide".

How do I only click the exact class?

答:
You could use the not operator as suggested by Sushanth. The disadvantage here is that you'd have to mention every class that is supposed to be excluded, which may be a pain depending on the number of different classes that you might be using on the same elements.

I recommend declaring classes with the sole purpose of applying js, or targeting the elements by a different attribute that you could set in your HTML.

Here you can find more about alternative targeting:

Find an element in DOM based on an attribute value

Title: Click All Javascript Jquery

Body:
When I run:

javascript:

var inputs = document.getElementsByClassName('subscribe_follow');

for(var i=0;i<inputs.length;i++) {
   inputs[i].click();
}

to click all buttons with the class class="subscribe_follow",
it also clicks all buttons with the class class="subscribe_follow ng-hide".

How do I only click the exact class?


问:
Writtin data to table at start / end times
If i understand correctly "NOT NULL" when used it for any data that can be written at the point of table creation, and if there are colunm data which are required but to be written after table creation thy need to be either DEFAULT NULL or NOT NULL DEFAULT 'xxx'?

Usecase is the session table.
The row is written when the user logs in. So at that point we write the date, IP, session id, member id, etc. But when the user logs off then i need to write the end datetime, the last page he was on, mode of log off, etc.

So for these end colunms if i use NOT NULL there will be no value to write at row creation time. Am i correct or am i missing something  on how data is written?

答: If you set those end columns as NOT NULLs, the database will throw you an exception when you are trying to write data upon user login. Setting a column as NOT NULL means they must not be NULL when insert a new row. In your case, you want to make the end columns (end datetime, last page, etc) to be nullable whereas you make columns like date, IP, session ID, member Id to be NOT NULLs. </p>


问:
Wrong currency info being returned when calling spot price endpoint using Python
I have noticed that the data endpoint for getting the spot price is returning the wrong currency information when using Python. I am using a currency_pair of BTC-USD but getting results for GBP.

Example:

```<code>price = client.get_spot_price(currency_pair = 'BTC-USD')
</code>```

Response:

```<code>{
  "amount": "5578.85",
  "base": "BTC",
  "currency": "GBP"
}
</code>```

Any ideas on whats causing this problem?

答:
A workaround, though not using the official Coinbase client, would be as follows:

```<code>import requests
import json

# Do This to Avoid Warning
headers = {
    'CB-VERSION': '2017-12-08'
}

# Make Request
data = requests.get('https://api.coinbase.com/v2/prices/BTC-USD/sell/', headers=headers).text

# Parse Response, Get Amount
price = json.loads(data)['data']['amount]
</code>```

Obviously not very robust in terms of handling errors, exceptions, or any other types of assertions one would need (that the official client should have) that would be needed to provide the confidence needed for actual buys/sells/transfers.

EDIT: UPDATE

Apparently this is a known issue:

Read here:

https://github.com/coinbase/coinbase-python/issues/32

Supposedly already fixed in the github master, though obviously not reflected in the pip version yet.

Quoting user kflecki:

I fixed this by going into the client.py file and modifying the code to look like this. Works just fine now, however would be nice for the files to come like this. But it's a simple fix that you can do on your own.

```<code>def get_spot_price(self, **params):
"""https://developers.coinbase.com/api/v2#get-spot-price"""
if 'currency_pair' in params:
currency_pair = params['currency_pair']
else:
currency_pair = 'BTC-USD'
response = self._get('v2', 'prices', currency_pair, 'spot', data=params)
return self._make_api_object(response, APIObject)
</code>```

And now the command works like so:

```<code>eth_price = client.get_spot_price(currency_pair = 'ETH-USD')
</code>```

Body:
I have noticed that the data endpoint for getting the spot price is returning the wrong currency information when using Python. I am using a currency_pair of BTC-USD but getting results for GBP.

Example:

price = client.get_spot_price(currency_pair = 'BTC-USD')

Response:

{
  "amount": "5578.85",
  "base": "BTC",
  "currency": "GBP"
}

Any ideas on whats causing this problem?

Body:
A workaround, though not using the official Coinbase client, would be as follows:

import requests
import json

# Do This to Avoid Warning
headers = {
    'CB-VERSION': '2017-12-08'
}

# Make Request
data = requests.get('https://api.coinbase.com/v2/prices/BTC-USD/sell/', headers=headers).text

# Parse Response, Get Amount
price = json.loads(data)['data']['amount]

Obviously not very robust in terms of handling errors, exceptions, or any other types of assertions one would need (that the official client should have) that would be needed to provide the confidence needed for actual buys/sells/transfers.

EDIT: UPDATE

Apparently this is a known issue:

Read here:

https://github.com/coinbase/coinbase-python/issues/32

Supposedly already fixed in the github master, though obviously not reflected in the pip version yet.

Quoting user kflecki:

I fixed this by going into the client.py file and modifying the code to look like this. Works just fine now, however would be nice for the files to come like this. But it's a simple fix that you can do on your own.

def get_spot_price(self, **params):
"""https://developers.coinbase.com/api/v2#get-spot-price"""
if 'currency_pair' in params:
currency_pair = params['currency_pair']
else:
currency_pair = 'BTC-USD'
response = self._get('v2', 'prices', currency_pair, 'spot', data=params)
return self._make_api_object(response, APIObject)

And now the command works like so:

eth_price = client.get_spot_price(currency_pair = 'ETH-USD')


问:
subprocess cp leaves some files empty
I'm trying to copy some files from one directory to another. I want all files in one directory to end up in the root of another directory.

This command does exactly what I want when I run it in the terminal:

```<code>cp -rv ./src/CopyPasteIntoBuildDir/* ./build-root/src/
</code>```

This line of python, however, copies most of the files just like the above command, but it leaves some of the new files empty. Specifically, files in subdirectories are left empty.

```<code>subprocess.check_call("cp -rv ./src/CopyPasteIntoBuildDir/* ./build-root/src/", shell=True)
</code>```

It creates the files if they're not there, and it truncates them if they are.

What is going on?

答:
Assuming that you're decided to use cp rather than native Python operations --

This code will be much more reliable if you write it to not invoke any shell whatsoever. To avoid the need for /* on the source (and the side effects of this -- ie. refusal to copy directories whose names exceed the ARG_MAX combined environment and command-line size storage limit), use . as the last element of the name of the directory whose contents are to be copied, instead of passing a wildcard that needs to be expanded by a shell.

```<code>subprocess.check_call(["cp", "-R", "--", '%s/.' % src, dest])
</code>```

The use of cp -R rather than cp -rv is on account of -R, but not -r, being POSIX-standardized (and thus portable across all compliant UNIXlike platforms).

Demonstrating In Action (copy/pasteable code)

```<code>tempdir=$(mktemp -d -t testdir.XXXXXX)
trap 'rm -rf "$tempdir"' EXIT

cd "$tempdir"
mkdir -p ./src/CopyPasteIntoBuildDir/subdir-1 ./build-root/src/
touch ./src/CopyPasteIntoBuildDir/file-1
touch ./src/CopyPasteIntoBuildDir/subdir-1/file-2

script='
import sys, shutil, subprocess

src = sys.argv[1]
dest = sys.argv[2]
subprocess.check_call(["cp", "-R", "--", "%s/." % src, dest])
'

python -c "$script" ./src/CopyPasteIntoBuildDir ./build-root/src/
find ./build-root -type f -print
rm -rf "$tempdir"
</code>```

...emits output akin to:

```<code>./build-root/src/file-1
./build-root/src/subdir-1/file-2
</code>```

...showing that content was correctly recursively copied with no prefix.

Title: subprocess cp leaves some files empty

Body:
I'm trying to copy some files from one directory to another. I want all files in one directory to end up in the root of another directory.

This command does exactly what I want when I run it in the terminal:

cp -rv ./src/CopyPasteIntoBuildDir/* ./build-root/src/

This line of python, however, copies most of the files just like the above command, but it leaves some of the new files empty. Specifically, files in subdirectories are left empty.

subprocess.check_call("cp -rv ./src/CopyPasteIntoBuildDir/* ./build-root/src/", shell=True)

It creates the files if they're not there, and it truncates them if they are.

What is going on?

Body:
Assuming that you're decided to use cp rather than native Python operations --

This code will be much more reliable if you write it to not invoke any shell whatsoever. To avoid the need for /* on the source (and the side effects of this -- ie. refusal to copy directories whose names exceed the ARG_MAX combined environment and command-line size storage limit), use . as the last element of the name of the directory whose contents are to be copied, instead of passing a wildcard that needs to be expanded by a shell.

subprocess.check_call(["cp", "-R", "--", '%s/.' % src, dest])

The use of cp -R rather than cp -rv is on account of -R, but not -r, being POSIX-standardized (and thus portable across all compliant UNIXlike platforms).

Demonstrating In Action (copy/pasteable code)

tempdir=$(mktemp -d -t testdir.XXXXXX)
trap 'rm -rf "$tempdir"' EXIT

cd "$tempdir"
mkdir -p ./src/CopyPasteIntoBuildDir/subdir-1 ./build-root/src/
touch ./src/CopyPasteIntoBuildDir/file-1
touch ./src/CopyPasteIntoBuildDir/subdir-1/file-2

script='
import sys, shutil, subprocess

src = sys.argv[1]
dest = sys.argv[2]
subprocess.check_call(["cp", "-R", "--", "%s/." % src, dest])
'

python -c "$script" ./src/CopyPasteIntoBuildDir ./build-root/src/
find ./build-root -type f -print
rm -rf "$tempdir"

...emits output akin to:

./build-root/src/file-1
./build-root/src/subdir-1/file-2

...showing that content was correctly recursively copied with no prefix.


问:
Can't debug Java Windows Services with jhat, jps, jstack
I frequently showcase the jhat, jps, and jstack tool set to developers on Linux and Mac.  However, a developer recently indicated that these are unusable in Windows if the Java app in question is running as a Windows Service.

A Sun-filed bug says something very similar, but was closed due to inactivity.

I have tested this out for myself, and indeed it appears true, though I can hardly believe it.  Here is the setup:

Tomcat or similar running as a Windows service with the "Log On As" == "Local System"

A user with Admin privileges logged in to the same Windows machine.

Admin opens Windows Task Manager, can see java.exe running

Admin opens console, types "jps", gets back a list of processes that does not include Tomcat's java service process.

As a brute force attempt, get the PID of tomcat as a service from Windows Task Manager.  Type jstack < pid >.  Get a reply: < pid > no such process

This appears reproducible under Windows XP, Windows 2003 Server, and Windows 7.  Java versions 1.5 and 1.6 yield the same outcome.

Is there a way from the terminal, even though logged in as Admin, to "sudo up" to get JPS and the other tools to see the java service?

答:
Here is the solution that finally worked for me for obtaining stacktraces from unprepared java process running under different user in terminal session or as windows service.

jstack.cmd:

@for /f "usebackq tokens=2" %%I in (`tasklist /NH /FI "imagename eq tomcat.exe" /FI "username eq SYSTEM"`) DO set PID=%%I
@for /f "tokens=2 delims==." %%G in ('wmic os get localdatetime /value') do @set datetime=%%G
@set date_time=%datetime:~0,4%_%datetime:~4,2%_%datetime:~6,2%__%datetime:~8,2%_%datetime:~10,2%_%datetime:~12,2%
PsExec.exe /accepteula -h -s -d cmd /c "%JAVA_HOME%\jstack.exe" -l %PID% ^>"%~dp0jstack_%date_time%.txt"
```

First line determines the PID by process name and user.

Then PsExec with accepted EULA helps to call jstack in elevated mode with properly escaped redirection of the output to jstack*.txt file in script's dir with timestamp included in file name.

You may need to add PsExec and JDK dirs to PATH beforehand.

I've tried to force threaddumps by SendSignal before but it never worked reliably with Windows service processes.

Body:
Here is the solution that finally worked for me for obtaining stacktraces from unprepared java process running under different user in terminal session or as windows service.

jstack.cmd:

@for /f "usebackq tokens=2" %%I in (`tasklist /NH /FI "imagename eq tomcat.exe" /FI "username eq SYSTEM"`) DO set PID=%%I
@for /f "tokens=2 delims==." %%G in ('wmic os get localdatetime /value') do @set datetime=%%G
@set date_time=%datetime:~0,4%_%datetime:~4,2%_%datetime:~6,2%__%datetime:~8,2%_%datetime:~10,2%_%datetime:~12,2%
PsExec.exe /accepteula -h -s -d cmd /c "%JAVA_HOME%\jstack.exe" -l %PID% ^>"%~dp0jstack_%date_time%.txt"

First line determines the PID by process name and user.

Then PsExec with accepted EULA helps to call jstack in elevated mode with properly escaped redirection of the output to jstack*.txt file in script's dir with timestamp included in file name.

You may need to add PsExec and JDK dirs to PATH beforehand.

I've tried to force threaddumps by SendSignal before but it never worked reliably with Windows service processes.

ContentLicense: CC BY-SA 4.0


问:
Unable to format the date in Handlebars.java using {{now}}
I am trying to render the present date using Handlebars in Java. While using the {{now}} handlebar, I am able to print the date as "Dec 8, 2017":

```<code><ul>
 {{#items}}
 {{name}}

     {{now}}

 {{/items}}
</ul>
</code>```

But when I try to format the date by passing a parameter, I am getting a null value. Am I doing something wrong here? -

```<code><ul>
 {{#items}}
 {{name}}

     {{now ["full"]}}

 {{/items}}
</ul>
</code>```

答:
I'm not sure what version of Handlebars, but you may need to specify the format in there?

```<code>{{now ["format"] [DateFormat.FULL]}}
</code>```

Otherwise this  would be a good place to look.

Body:
I am trying to render the present date using Handlebars in Java. While using the {{now}} handlebar, I am able to print the date as "Dec 8, 2017":

 {{#items}}
 {{name}}

     {{now}}

 {{/items}}

But when I try to format the date by passing a parameter, I am getting a null value. Am I doing something wrong here? -

 {{#items}}
 {{name}}

     {{now ["full"]}}

 {{/items}}

Body:
I'm not sure what version of Handlebars, but you may need to specify the format in there?

{{now ["format"] [DateFormat.FULL]}}

Otherwise this  would be a good place to look.


问:
opengl ray picking/tracing with cardboard (GVR)
For the demonstration, I made a small application that draws three squares of random size and random location.
Drawing squares:

```<code>private void renderObject(float[] modelViewProjection, FloatBuffer vertexCoordsBuf, int i) {
        GLES20.glUseProgram(mProgram);
        GLES20.glEnableVertexAttribArray(mPositionHandle);
        GLES20.glVertexAttribPointer(
                mPositionHandle, 3,
                GLES20.GL_FLOAT, false,
                12, vertexCoordsBuf);

        GLES20.glUniform4fv(mColorHandle,
                1, colors, i * 4);

        GLES20.glUniformMatrix4fv(mMVPMatrixHandle,
                1, false, modelViewProjection, 0);

        // Draw the square
        GLES20.glDrawElements(
                GLES20.GL_TRIANGLES, 6,
                GLES20.GL_UNSIGNED_SHORT, indexesBuffer);
        // Disable vertex array
        GLES20.glDisableVertexAttribArray(mPositionHandle);
}
</code>```

I also display the cursor (white small square) in the center of the screen using the orthogonal projection:

```<code>private void renderCursor(Eye eye) {
        GLES20.glDepthFunc(GLES20.GL_ALWAYS);
        GLES20.glDepthMask(false);

        GLES20.glUseProgram(mProgram);
        GLES20.glEnableVertexAttribArray(mPositionHandle);
        GLES20.glVertexAttribPointer(
                mPositionHandle, 3,
                GLES20.GL_FLOAT, false,
                12, cursorVertexCoordsBuf);

        GLES20.glUniform4fv(mColorHandle,
                1, colors, 12);

        float[] perspectiveMatrix = eye.getPerspective(Z_NEAR, Z_FAR);
        float[] orthoViewMatrix = new float[16];
        float[] modelViewMatrix = new float[16];
        Matrix.orthoM(orthoViewMatrix, 0, -1, 1, -1, 1, Z_NEAR, Z_FAR);
        Matrix.multiplyMM(modelViewMatrix, 0, perspectiveMatrix, 0, orthoViewMatrix, 0);

        GLES20.glUniformMatrix4fv(mMVPMatrixHandle,
                1, false, modelViewMatrix, 0);

        // Draw the square
        GLES20.glDrawElements(
                GLES20.GL_TRIANGLES, 6,
                GLES20.GL_UNSIGNED_SHORT, indexesBuffer);
        // Disable vertex array
        GLES20.glDisableVertexAttribArray(mPositionHandle);
        GLES20.glDepthFunc(GLES20.GL_LEQUAL);
        GLES20.glDepthMask(true);
    }
</code>```

For clarity in the center of the visible area for stereo mode, I draw red dots. To see how the cursor deviates from the center of the screen.

How it see in stereo mode. How you can see white cursor moved from centers of screens:

If I have disabled the stereo mode then everything works fine. I use a method to determine which object in the center of the screen I'm producing ray tracing for screenWidth/2 and screenHeight/2 coordinates:

```<code>public boolean rayPicking(int viewWidth, int viewHeight, float rx, float ry,
                              float[] viewMatrix, float[] projMatrix, float[] modelViewMatrix,
                              float[] objectCoords, short[] objectIndexes) {
        float[] near_xyz = unProject(rx, ry, 0, viewMatrix, projMatrix, viewWidth, viewHeight);
        float[] far_xyz = unProject(rx, ry, 1, viewMatrix, projMatrix, viewWidth, viewHeight);
        int coordCount = objectCoords.length;
        float[] convertedSquare = new float[coordCount];
        float[] resultVector = new float[4];
        float[] inputVector = new float[4];
        for (int i = 0; i < coordCount; i = i + 3) {
            inputVector[0] = objectCoords[i];
            inputVector[1] = objectCoords[i + 1];
            inputVector[2] = objectCoords[i + 2];
            inputVector[3] = 1;
            Matrix.multiplyMV(resultVector, 0, modelViewMatrix, 0, inputVector, 0);
            convertedSquare[i] = resultVector[0] / resultVector[3];
            convertedSquare[i + 1] = resultVector[1] / resultVector[3];
            convertedSquare[i + 2] = resultVector[2] / resultVector[3];
        }

        ArrayList<Triangle> triangles = new ArrayList<>();
        for (int i = 0; i < objectIndexes.length; i = i + 3) {
            int i1 = objectIndexes[i] * 3;
            int i2 = objectIndexes[i + 1] * 3;
            int i3 = objectIndexes[i + 2] * 3;
            triangles.add(
                    new Triangle(
                            new float[]{
                                    convertedSquare[i1],
                                    convertedSquare[i1 + 1],
                                    convertedSquare[i1 + 2]
                            },
                            new float[]{
                                    convertedSquare[i2],
                                    convertedSquare[i2 + 1],
                                    convertedSquare[i2 + 2]
                            },
                            new float[]{
                                    convertedSquare[i3],
                                    convertedSquare[i3 + 1],
                                    convertedSquare[i3 + 2]
                            }
                    )
            );
        }

        for (Triangle t : triangles) {
            float[] point = new float[3];
            int intersects = Triangle.intersectRayAndTriangle(near_xyz, far_xyz, t, point);
            if (intersects == 1 || intersects == 2) {
                return true;
            }
        }
        return false;
}
</code>```

But if i turn on the stereo mode, the cursor is not displayed in the center of the screen. And for the left eye is moved in the left from the center of the visible area of the left eye, and for the right is appropriately to the right.
And in this case, I do not understand how to get the real screen coordinates for the cursor so that it can produce ray tracing?
I will be glad to any prompts ;)

Full worked sample you can get from github:
https://github.com/Anton111111/AndroidGVRRayPickingSample

And all placed in one file to easy read it:
https://github.com/Anton111111/AndroidGVRRayPickingSample/blob/master/app/src/main/java/com/anton111111/ray_picking/MainActivity.java

P.s. Please, if you want to set minus to my question simple add comment to explain what's wrong with my question.

答:
And i fixed it. Now my ray picking works well in stereo mode.
I add calculateCursorScreenCoords method to get screen coordinates of cursor.
https://github.com/Anton111111/AndroidGVRRayPickingSample/blob/master/app/src/main/java/com/anton111111/ray_picking/MainActivity.java#L196</p>

Body:
For the demonstration, I made a small application that draws three squares of random size and random location.
Drawing squares:

private void renderObject(float[] modelViewProjection, FloatBuffer vertexCoordsBuf, int i) {
        GLES20.glUseProgram(mProgram);
        GLES20.glEnableVertexAttribArray(mPositionHandle);
        GLES20.glVertexAttribPointer(
                mPositionHandle, 3,
                GLES20.GL_FLOAT, false,
                12, vertexCoordsBuf);

        GLES20.glUniform4fv(mColorHandle,
                1, colors, i * 4);

        GLES20.glUniformMatrix4fv(mMVPMatrixHandle,
                1, false, modelViewProjection, 0);

        // Draw the square
        GLES20.glDrawElements(
                GLES20.GL_TRIANGLES, 6,
                GLES20.GL_UNSIGNED_SHORT, indexesBuffer);
        // Disable vertex array
        GLES20.glDisableVertexAttribArray(mPositionHandle);
}

I also display the cursor (white small square) in the center of the screen using the orthogonal projection:

private void renderCursor(Eye eye) {
        GLES20.glDepthFunc(GLES20.GL_ALWAYS);
        GLES20.glDepthMask(false);

        GLES20.glUseProgram(mProgram);
        GLES20.glEnableVertexAttribArray(mPositionHandle);
        GLES20.glVertexAttribPointer(
                mPositionHandle, 3,
                GLES20.GL_FLOAT, false,
                12, cursorVertexCoordsBuf);

        GLES20.glUniform4fv(mColorHandle,
                1, colors, 12);

        float[] perspectiveMatrix = eye.getPerspective(Z_NEAR, Z_FAR);
        float[] orthoViewMatrix = new float[16];
        float[] modelViewMatrix = new float[16];
        Matrix.orthoM(orthoViewMatrix, 0, -1, 1, -1, 1, Z_NEAR, Z_FAR);
        Matrix.multiplyMM(modelViewMatrix, 0, perspectiveMatrix, 0, orthoViewMatrix, 0);

        GLES20.glUniformMatrix4fv(mMVPMatrixHandle,
                1, false, modelViewMatrix, 0);

        // Draw the square
        GLES20.glDrawElements(
                GLES20.GL_TRIANGLES, 6,
                GLES20.GL_UNSIGNED_SHORT, indexesBuffer);
        // Disable vertex array
        GLES20.glDisableVertexAttribArray(mPositionHandle);
        GLES20.glDepthFunc(GLES20.GL_LEQUAL);
        GLES20.glDepthMask(true);
    }

For clarity in the center of the visible area for stereo mode, I draw red dots. To see how the cursor deviates from the center of the screen.

How it see in stereo mode. How you can see white cursor moved from centers of screens:

If I have disabled the stereo mode then everything works fine. I use a method to determine which object in the center of the screen I'm producing ray tracing for screenWidth/2 and screenHeight/2 coordinates:

public boolean rayPicking(int viewWidth, int viewHeight, float rx, float ry,
                              float[] viewMatrix, float[] projMatrix, float[] modelViewMatrix,
                              float[] objectCoords, short[] objectIndexes) {
        float[] near_xyz = unProject(rx, ry, 0, viewMatrix, projMatrix, viewWidth, viewHeight);
        float[] far_xyz = unProject(rx, ry, 1, viewMatrix, projMatrix, viewWidth, viewHeight);
        int coordCount = objectCoords.length;
        float[] convertedSquare = new float[coordCount];
        float[] resultVector = new float[4];
        float[] inputVector = new float[4];
        for (int i = 0; i < coordCount; i = i + 3) {
            inputVector[0] = objectCoords[i];
            inputVector[1] = objectCoords[i + 1];
            inputVector[2] = objectCoords[i + 2];
            inputVector[3] = 1;
            Matrix.multiplyMV(resultVector, 0, modelViewMatrix, 0, inputVector, 0);
            convertedSquare[i] = resultVector[0] / resultVector[3];
            convertedSquare[i + 1] = resultVector[1] / resultVector[3];
            convertedSquare[i + 2] = resultVector[2] / resultVector[3];
        }

        ArrayList<Triangle> triangles = new ArrayList<>();
        for (int i = 0; i < objectIndexes.length; i = i + 3) {
            int i1 = objectIndexes[i] * 3;
            int i2 = objectIndexes[i + 1] * 3;
            int i3 = objectIndexes[i + 2] * 3;
            triangles.add(
                    new Triangle(
                            new float[]{
                                    convertedSquare[i1],
                                    convertedSquare[i1 + 1],
                                    convertedSquare[i1 + 2]
                            },
                            new float[]{
                                    convertedSquare[i2],
                                    convertedSquare[i2 + 1],
                                    convertedSquare[i2 + 2]
                            },
                            new float[]{
                                    convertedSquare[i3],
                                    convertedSquare[i3 + 1],
                                    convertedSquare[i3 + 2]
                            }
                    )
            );
        }

        for (Triangle t : triangles) {
            float[] point = new float[3];
            int intersects = Triangle.intersectRayAndTriangle(near_xyz, far_xyz, t, point);
            if (intersects == 1 || intersects == 2) {
                return true;
            }
        }
        return false;
}

But if i turn on the stereo mode, the cursor is not displayed in the center of the screen. And for the left eye is moved in the left from the center of the visible area of the left eye, and for the right is appropriately to the right.
And in this case, I do not understand how to get the real screen coordinates for the cursor so that it can produce ray tracing?
I will be glad to any prompts ;)

Full worked sample you can get from github:
https://github.com/Anton111111/AndroidGVRRayPickingSample

And all placed in one file to easy read it:
https://github.com/Anton111111/AndroidGVRRayPickingSample/blob/master/app/src/main/java/com/anton111111/ray_picking/MainActivity.java

P.s. Please, if you want to set minus to my question simple add comment to explain what's wrong with my question.


问:
how do vertically align login form between banner and footer
Given I have the html and css in the snippet below the question, how can I vertically centre the login view no matter what screen height is?

I have tried this for the .login-layout__positioner class:

```<code>.login-layout__positioner {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;

    top: 42%;
    transform: translateY(-42%);
}
</code>```

But this does not centre well in large screen heights?

Is there a better way?

body {
  height: 100%;
  background-color: #f7f7f4;
}

.app-layout__body {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.app-layout__container {
  flex: 1 0 auto;
}

.banner__container {
  background-color: #fff
}

.banner__top {
  padding-top: 15px;
}

.login-layout__container {
  background-color: #f7f7f4;
  width: 100%;
}

.login-layout__positioner {
  text-align: center;
  margin: auto;
}

footer {
  background-color: #0065bd;
}

a {
  color: #fff;
}

ul {
  list-style: none;
  margin-left: 0;
}

li {
  display: inline;
}

.form__group {
  background-color: #fff;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div id="root">
    <div class="main-content">
      <div class="app-layout__body">
        <div class="app-layout__container">
          <div class="banner__container">
            <div class="banner__top">
              <div>
                <div>
                  <h2>Banner</h2></div>
              </div>
            </div>
          </div>
          <div class="login-layout__container">
            <div class="login-layout__positioner">
              <div class="form__group">
                <div>
                  <form>
                    <div class="login__container">
                      <div class="login__wrapper">
                        <div>
                          <div>
                            <div class="login__form__elements">
                              <div>
                                <div>
                                  <h2 class="">Sign In</h2></div>
                              </div>
                              <div>
                                <div>
                                  <div>
                                    <label for="email" id="email-label" class="label__default label__strong label__double-margin">Email</label>
                                    <div>
                                      <input type="text" autocomplete="off" class="input__default form-control" id="email" name="email" aria-invalid="false" aria-describedby="email-error" value="">
                                    </div>
                                    <div id="email-error" aria-hidden="true" role="alert"></div>
                                  </div>
                                </div>
                              </div>
                              <div>
                                <div>
                                  <div>
                                    <label for="password" id="password-label">Password</label>
                                    <div>
                                      <input type="password" autocomplete="off" id="password" name="password" aria-invalid="false" aria-describedby="password-error" value="">
                                    </div>
                                    <div id="password-error" aria-hidden="true" role="alert"></div>
                                  </div>
                                </div>
                              </div>
                              <div>
                                <div>Forgotten your password?</div>
                                <div>
                                  <button type="submit">LOGIN</button>
                                </div>
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </form>
                </div>
              </div>
            </div>
          </div>
        </div>
        <footer>
          <div>
            <div>
              <div>
                <ul>
                  <li>About</li>
                  <li>Accessibility</li>
                  <li>Cookies</li>
                  <li>Privacy</li>
                </ul>
              </div>
            </div>
          </div>
        </footer>
      </div>
    </div>
  </div>
</body></code>```

答:
When it comes to centering something both vertically and horizontally I like to use css flex. Adding it to the parent container surrounding the element you wish to center will cause it to flex in all screen dimensions and heights. Justify-content centers it horizontally and align-items centers it vertically. Here is a helpful guide to learn more about flex:https://css-tricks.com/snippets/css/a-guide-to-flexbox/

.parent-container{
width:100vw;
height:100vh;
background-color:black;

display:flex;
justify-content:center;
align-items:center;
}

.child{
width:50%;
background-color:white;
text-align:center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent-container">
  <div class="child">
    <h1>Centered</h1>
  </div><!-- child -->
</div><!-- parent-container --></code>```

Body:
Given I have the html and css in the snippet below the question, how can I vertically centre the login view no matter what screen height is?

I have tried this for the .login-layout__positioner class:

.login-layout__positioner {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;

    top: 42%;
    transform: translateY(-42%);
}

But this does not centre well in large screen heights?

Is there a better way?

body {
  height: 100%;
  background-color: #f7f7f4;
}

.app-layout__body {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.app-layout__container {
  flex: 1 0 auto;
}

.banner__container {
  background-color: #fff
}

.banner__top {
  padding-top: 15px;
}

.login-layout__container {
  background-color: #f7f7f4;
  width: 100%;
}

.login-layout__positioner {
  text-align: center;
  margin: auto;
}

footer {
  background-color: #0065bd;
}

a {
  color: #fff;
}

ul {
  list-style: none;
  margin-left: 0;
}

li {
  display: inline;
}

.form__group {
  background-color: #fff;
}

Banner

                  <form>

Sign In

                                    Email

                                      <input type="text" autocomplete="off" class="input__default form-control" id="email" name="email" aria-invalid="false" aria-describedby="email-error" value="">

                                    Password

                                      <input type="password" autocomplete="off" id="password" name="password" aria-invalid="false" aria-describedby="password-error" value="">

Forgotten your password?

                                  <button type="submit">LOGIN</button>

                  </form>

About

Accessibility

Cookies

Privacy

Body:
When it comes to centering something both vertically and horizontally I like to use css flex. Adding it to the parent container surrounding the element you wish to center will cause it to flex in all screen dimensions and heights. Justify-content centers it horizontally and align-items centers it vertically. Here is a helpful guide to learn more about flex:https://css-tricks.com/snippets/css/a-guide-to-flexbox/

.parent-container{
width:100vw;
height:100vh;
background-color:black;

display:flex;
justify-content:center;
align-items:center;
}

.child{
width:50%;
background-color:white;
text-align:center;
}

<div class="parent-container">
  <div class="child">
    <h1>Centered</h1>
  </div><!-- child -->
</div><!-- parent-container -->


问:
UIGesture failing for unknown reason in IOS
I have a UITextField that is the subview of UIScrollView
I have there exist a single tap gesture (or perhaps the older touch) as part of UITextField that makes it the first responder.  I wanted to add a double tap Gesture to the UITextField.  In order to make the two Gesture's mutually exclusive I needed to overload (though this is not quite the right word because I'm not using the same name) the single tap Gesture.  When I do it works fine so long as the function that it calls doesn't make the UITextField the first responder.  If it does make the textfield the first responder it fails the second time it's called.... wtf. So stack, a little help would go a long way.

this is where I add the gesture

```<code> UITapGestureRecognizer * singleTextTap = [[UITapGestureRecognizer alloc]
             initWithTarget:self action:@selector(handleSingleTextTap:)];
 singleTextTap.numberOfTapsRequired = 1;
 [aTextField addGestureRecognizer:singleTextTap];
</code>```

and this is where it is called

```<code>//single tap text
- (void) handleSingleTextTap:(UITapGestureRecognizer *)gestureRecognizer{
    NSLog(@"handling single tap");
    NSLog(@"textField gestures %@",
          [gestureRecognizer.view.gestureRecognizers descriptionWithLocale:nil]);
    [(UITextField *)gestureRecognizer.view becomeFirstResponder];
}
</code>```

you may notice the NSLog that out puts the gestuers registered to the textField this was to check the state of my singleTextTap gesture. which is 'ended' the first time and all next times this code is never reached

答:
The behaviour you're seeing is due to each time you send a becomeFirstResponder message to a UITextField it sets it's own gesture recognizers up. If you do a log on [textField gestureRecognizers] you'll see it sets up a lot of them. These are to deal with text editing functions such as long press for cursor movement and such. By way of adding these it cancels the ones you have setup. Easiest way to deal with this is something like this.

```<code>- (void) singleTap:(UITapGestureRecognizer*)singleTap {
    if (![self.textField isFirstResponder]) {
        [self.textField becomeFirstResponder];
        self.label.text = @"Single Tap -> Make First Responder";
        [self.label setNeedsDisplay];
    }
}
- (void) doubleTap:(UITapGestureRecognizer*)doubleTap {
    if (![self.textField isFirstResponder]) {
        [self.textField becomeFirstResponder];
        self.label.text = @"Double Tap -> Make First Responder";
        [self.label setNeedsDisplay];
    }
}

- (void) setupTextGestureRecognizers {
    for (UIGestureRecognizer *rec in self.textField.gestureRecognizers) {
        [self.textField removeGestureRecognizer:rec];
    }
    UITapGestureRecognizer *singleTap = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTap:)] autorelease];
    UITapGestureRecognizer *doubleTap = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doubleTap:)] autorelease];
    [singleTap setNumberOfTapsRequired:1];
    [doubleTap setNumberOfTapsRequired:2];
    [singleTap setCancelsTouchesInView:YES];
    [doubleTap setCancelsTouchesInView:YES];
    [singleTap requireGestureRecognizerToFail:doubleTap];
    [self.textField addGestureRecognizer:singleTap];
    [self.textField addGestureRecognizer:doubleTap];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupTextGestureRecognizers];
    self.textField.delegate = self;
}

- (BOOL) textFieldShouldReturn:(UITextField *)tf {
    [tf resignFirstResponder];
    if (tf == self.textField) {
        [self setupTextGestureRecognizers];
    }
    return YES;
}
</code>```

Here is an example project demonstrating this code in use.

Body:
I have a UITextField that is the subview of UIScrollView
I have there exist a single tap gesture (or perhaps the older touch) as part of UITextField that makes it the first responder.  I wanted to add a double tap Gesture to the UITextField.  In order to make the two Gesture's mutually exclusive I needed to overload (though this is not quite the right word because I'm not using the same name) the single tap Gesture.  When I do it works fine so long as the function that it calls doesn't make the UITextField the first responder.  If it does make the textfield the first responder it fails the second time it's called.... wtf. So stack, a little help would go a long way.

this is where I add the gesture

 UITapGestureRecognizer * singleTextTap = [[UITapGestureRecognizer alloc]
             initWithTarget:self action:@selector(handleSingleTextTap:)];
 singleTextTap.numberOfTapsRequired = 1;
 [aTextField addGestureRecognizer:singleTextTap];

and this is where it is called

//single tap text
- (void) handleSingleTextTap:(UITapGestureRecognizer *)gestureRecognizer{
    NSLog(@"handling single tap");
    NSLog(@"textField gestures %@",
          [gestureRecognizer.view.gestureRecognizers descriptionWithLocale:nil]);
    [(UITextField *)gestureRecognizer.view becomeFirstResponder];
}

you may notice the NSLog that out puts the gestuers registered to the textField this was to check the state of my singleTextTap gesture. which is 'ended' the first time and all next times this code is never reached

Body:
The behaviour you're seeing is due to each time you send a becomeFirstResponder message to a UITextField it sets it's own gesture recognizers up. If you do a log on [textField gestureRecognizers] you'll see it sets up a lot of them. These are to deal with text editing functions such as long press for cursor movement and such. By way of adding these it cancels the ones you have setup. Easiest way to deal with this is something like this.

- (void) singleTap:(UITapGestureRecognizer*)singleTap {
    if (![self.textField isFirstResponder]) {
        [self.textField becomeFirstResponder];
        self.label.text = @"Single Tap -> Make First Responder";
        [self.label setNeedsDisplay];
    }
}
- (void) doubleTap:(UITapGestureRecognizer*)doubleTap {
    if (![self.textField isFirstResponder]) {
        [self.textField becomeFirstResponder];
        self.label.text = @"Double Tap -> Make First Responder";
        [self.label setNeedsDisplay];
    }
}

- (void) setupTextGestureRecognizers {
    for (UIGestureRecognizer *rec in self.textField.gestureRecognizers) {
        [self.textField removeGestureRecognizer:rec];
    }
    UITapGestureRecognizer *singleTap = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTap:)] autorelease];
    UITapGestureRecognizer *doubleTap = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doubleTap:)] autorelease];
    [singleTap setNumberOfTapsRequired:1];
    [doubleTap setNumberOfTapsRequired:2];
    [singleTap setCancelsTouchesInView:YES];
    [doubleTap setCancelsTouchesInView:YES];
    [singleTap requireGestureRecognizerToFail:doubleTap];
    [self.textField addGestureRecognizer:singleTap];
    [self.textField addGestureRecognizer:doubleTap];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupTextGestureRecognizers];
    self.textField.delegate = self;
}

- (BOOL) textFieldShouldReturn:(UITextField *)tf {
    [tf resignFirstResponder];
    if (tf == self.textField) {
        [self setupTextGestureRecognizers];
    }
    return YES;
}

Here is an example project demonstrating this code in use.


问:
How do I return a base class variable and delete it?
I'm trying to get the first element in the list and remove it.

If I return the node (ListNode*) then I won't be able to remove it. If I remove it before I return, then there will be nothing to return because it will have already been removed.

I'm trying to keep the remove capability inside the function getFirst() instead of creating a separate remove() function. By creating a temp pointer, I will still run into the same problem (not being able to delete it). I have tried to implement the deletion and ignored the get part of the requirement.

```<code>ListNode* LinkedList::getFirst(){
    ListNode *nodePtr; //traverse the list
    if(head == nullptr){
        std::cout << "List is empty no node to remove"<< std::endl;
        return nullptr;
    }
    else{
        nodePtr = head;
        head = head->next;
        delete nodePtr;
    }

    return nullptr;
}
</code>```

How can I return the pointer and delete it?

答:
The problem you are facing is caused by trying to do too many things in the function.

Don't use getFirst to do anything other than "get the first node".

In addition, removing the first node from the linked list is different than deleting the first node of the linked list.

Here's my suggestion.

```<code>// Return the first node of the linked list.
ListNode* LinkedList::getFirst()
{
   return head;
}

// Remove the first node from the linked list.
void LinkedList::removeFirst()
{
   if(head != nullptr)
   {
      ListNode *nodePtr = head;
      head = head->next;

      delete nodePtr;
   }
}

// Detach the first node from the linked list and return the detached node.
LinkedNode* LinkedList::detachFirst()
{
   if(head == nullptr){
      return nullptr;
   }

   ListNode *nodePtr = head;
   head = head->next;

   return nodePtr;
}
</code>```

Usage:

```<code>LinkedList l;

//
// Fill up the linked list with nodes.
//

ListNode* first = l.getFirst();
if ( first != nullptr )
{
   // Use the first node.
}

// Delete the first node from the linked list.
l.removeFirst();

// Detach the first node from the linked list.
ListNode* first = l.detachFirst();
if ( first != nullptr )
{
   // Use the first node.
   // ...

   // Then delete it.
   delete first;
}
</code>```

Body:
I'm trying to get the first element in the list and remove it.

If I return the node (ListNode*) then I won't be able to remove it. If I remove it before I return, then there will be nothing to return because it will have already been removed.

I'm trying to keep the remove capability inside the function getFirst() instead of creating a separate remove() function. By creating a temp pointer, I will still run into the same problem (not being able to delete it). I have tried to implement the deletion and ignored the get part of the requirement.

ListNode* LinkedList::getFirst(){
    ListNode *nodePtr; //traverse the list
    if(head == nullptr){
        std::cout << "List is empty no node to remove"<< std::endl;
        return nullptr;
    }
    else{
        nodePtr = head;
        head = head->next;
        delete nodePtr;
    }

    return nullptr;
}

How can I return the pointer and delete it?

Body:
The problem you are facing is caused by trying to do too many things in the function.

Don't use getFirst to do anything other than "get the first node".

In addition, removing the first node from the linked list is different than deleting the first node of the linked list.

Here's my suggestion.

// Return the first node of the linked list.
ListNode* LinkedList::getFirst()
{
   return head;
}

// Remove the first node from the linked list.
void LinkedList::removeFirst()
{
   if(head != nullptr)
   {
      ListNode *nodePtr = head;
      head = head->next;

      delete nodePtr;
   }
}

// Detach the first node from the linked list and return the detached node.
LinkedNode* LinkedList::detachFirst()
{
   if(head == nullptr){
      return nullptr;
   }

   ListNode *nodePtr = head;
   head = head->next;

   return nodePtr;
}

Usage:

LinkedList l;

//
// Fill up the linked list with nodes.
//

ListNode* first = l.getFirst();
if ( first != nullptr )
{
   // Use the first node.
}

// Delete the first node from the linked list.
l.removeFirst();

// Detach the first node from the linked list.
ListNode* first = l.detachFirst();
if ( first != nullptr )
{
   // Use the first node.
   // ...

   // Then delete it.
   delete first;
}


问:
How to split an array from a text file by a comma, only getting one array index displayed in Listbox?
First of all I would like to thank anyone willing to help ahead of time. My issue here is that when I attempt to populate my listbox with items in my array, I am getting only "General" added as a listbox item instead of the actual strings in the array. I'm rather new to programming so I apologize if this is an obvious error in my code, although I'm assuming it probably is.

This is my code:

```<code>Private Sub frmSalesSummary_Load(sender As Object, e As EventArgs) Handles
MyBase.Load
    Dim info() As String = IO.File.ReadAllLines("info.txt")
    Dim splitChar As Char = ","
    Dim infoString As String
    For i = 0 To info.GetUpperBound(0)
        infoString = info(i).Split(splitChar)
        lstSummary.Items.Add(infoString(i))
    Next
End Sub
</code>```

The text file contains this for testing "alex,General,7,$105.00" on the first line.

There may be frequent edits to this question as I am actively trying to figure this out myself as well. Apologies.

答:
'info' is your line (comma delimited)
'infoString' is an array of the words that are separated by the Split

So if you want to add a single item from that split you would use
infoString(0) for the name, infoString(1) for the Rank, etc...

So you're taking each line, splitting it and to add the name to the listbox you only need to add infoString(0) because that element of the array holds the name from splitting it out from the line.

Try

```<code>lstSummary.Items.Add(infoString(0))
</code>```

If you're wanting a list like:

```<code>alex
General
7
$105.00
</code>```

You could create another loop inside your current loop and use the iterator for the index.

```<code>For i = 0 to info.GetUpperbound(0)
   infoString = info(i).Split(splitChar)
   For x = 0 to infoString.GetUpperBound(0)
      lstSummary.Items.Add(infoString(x))
   Next
Next
</code>```

This would take each Line, split it and then add the info from each line to the listbox... Keep in mind, you would have the 4 you showed, then the next line would put the next 4 pieces of information until you run out of lines in your text file.

Still not quite sure if that is exactly what you're trying to do, if this still isn't the case, you might mock up some picture of what you're expecting along with information as to whether or not there is more of this information in the text file.

Body:
First of all I would like to thank anyone willing to help ahead of time. My issue here is that when I attempt to populate my listbox with items in my array, I am getting only "General" added as a listbox item instead of the actual strings in the array. I'm rather new to programming so I apologize if this is an obvious error in my code, although I'm assuming it probably is.

This is my code:

Private Sub frmSalesSummary_Load(sender As Object, e As EventArgs) Handles
MyBase.Load
    Dim info() As String = IO.File.ReadAllLines("info.txt")
    Dim splitChar As Char = ","
    Dim infoString As String
    For i = 0 To info.GetUpperBound(0)
        infoString = info(i).Split(splitChar)
        lstSummary.Items.Add(infoString(i))
    Next
End Sub

The text file contains this for testing "alex,General,7,$105.00" on the first line.

There may be frequent edits to this question as I am actively trying to figure this out myself as well. Apologies.

Body:
'info' is your line (comma delimited)
'infoString' is an array of the words that are separated by the Split

So if you want to add a single item from that split you would use
infoString(0) for the name, infoString(1) for the Rank, etc...

So you're taking each line, splitting it and to add the name to the listbox you only need to add infoString(0) because that element of the array holds the name from splitting it out from the line.

Try

lstSummary.Items.Add(infoString(0))

If you're wanting a list like:

alex
General
7
$105.00

You could create another loop inside your current loop and use the iterator for the index.

For i = 0 to info.GetUpperbound(0)
   infoString = info(i).Split(splitChar)
   For x = 0 to infoString.GetUpperBound(0)
      lstSummary.Items.Add(infoString(x))
   Next
Next

This would take each Line, split it and then add the info from each line to the listbox... Keep in mind, you would have the 4 you showed, then the next line would put the next 4 pieces of information until you run out of lines in your text file.

Still not quite sure if that is exactly what you're trying to do, if this still isn't the case, you might mock up some picture of what you're expecting along with information as to whether or not there is more of this information in the text file.


问:
Regex string match in c#
So, I'd like to check if a string of letters and digits is in correct format

Here's what it needs to look like:

```<code>123abc#456def#
</code>```

I've tried something like that:

```<code>Regex r = new Regex(@"^([0-9a-zA-Z]#)([0-9a-zA-Z]#)$");
</code>```

Didn't help me...

答:
I would go for the following regex:

```<code>^([A-Za-z0-9]{6}#){2}$
</code>```

But you didn't specify the format of your strings, so It's actually a guess game. Are those hash-delimited groups only recurring two times? Do you want to match 3 numbers followed by 3 letters in each group?

Title: Regex string match in c#

Body:
So, I'd like to check if a string of letters and digits is in correct format

Here's what it needs to look like:

123abc#456def#

I've tried something like that:

Regex r = new Regex(@"^([0-9a-zA-Z]#)([0-9a-zA-Z]#)$");

Didn't help me...

Body:
I would go for the following regex:

^([A-Za-z0-9]{6}#){2}$

But you didn't specify the format of your strings, so It's actually a guess game. Are those hash-delimited groups only recurring two times? Do you want to match 3 numbers followed by 3 letters in each group?


答:
If you want to return only the value of the node, you can try this:

```<code>int LinkedList::getFirst(){
    ListNode *nodePtr; //traverse the list
    int node_value;
    if(head == nullptr){
        std::cout << "List is empty no node to remove"<< std::endl;
        return nullptr;
    }
    else{
        nodePtr = head;
        node_value = nodePtr->value;
        head = head->next;
        delete nodePtr;
    }

    return node_value;
}
</code>```

Obviously, you have to change the return value of your function (I assume that is an integer).

Title: How do I return a base class variable and delete it?

Body:
If you want to return only the value of the node, you can try this:

int LinkedList::getFirst(){
    ListNode *nodePtr; //traverse the list
    int node_value;
    if(head == nullptr){
        std::cout << "List is empty no node to remove"<< std::endl;
        return nullptr;
    }
    else{
        nodePtr = head;
        node_value = nodePtr->value;
        head = head->next;
        delete nodePtr;
    }

    return node_value;
}

Obviously, you have to change the return value of your function (I assume that is an integer).