问:
How to check whether a directory is a sub directory of another directory
I like to write a template system in Python, which allows to include files.

e.g.

```
    This is a template
    You can safely include files with safe_include`othertemplate.rst`
```

As you know, including files might be dangerous. For example, if I use the template system in a web application which allows users to create their own templates, they might do something like

```
I want your passwords: safe_include`/etc/password`
```

So therefore, I have to restrict the inclusion of files to files which are for example in a certain subdirectory (e.g. /home/user/templates)

The question is now: How can I check, whether /home/user/templates/includes/inc1.rst is in a subdirectory of /home/user/templates?

Would the following code work and be secure?

```<code>import os.path

def in_directory(file, directory, allow_symlink = False):
    #make both absolute
    directory = os.path.abspath(directory)
    file = os.path.abspath(file)

    #check whether file is a symbolic link, if yes, return false if they are not allowed
    if not allow_symlink and os.path.islink(file):
        return False

    #return true, if the common prefix of both is equal to directory
    #e.g. /a/b/c/d.rst and directory is /a/b, the common prefix is /a/b
    return os.path.commonprefix([file, directory]) == directory
</code>```

As long, as allow_symlink is False, it should be secure, I think. Allowing symlinks of course would make it insecure if the user is able to create such links.

UPDATE - Solution
The code above does not work, if intermediate directories are symbolic links.
To prevent this, you have to use realpath instead of abspath.

UPDATE: adding a trailing / to directory to solve the problem with commonprefix() Reorx pointed out.

This also makes allow_symlink unnecessary as symlinks are expanded to their real destination

```<code>import os.path

def in_directory(file, directory):
    #make both absolute
    directory = os.path.join(os.path.realpath(directory), '')
    file = os.path.realpath(file)

    #return true, if the common prefix of both is equal to directory
    #e.g. /a/b/c/d.rst and directory is /a/b, the common prefix is /a/b
    return os.path.commonprefix([file, directory]) == directory
</code>```

答:
```<code>def is_in_directory(filepath, directory):
    return os.path.realpath(filepath).startswith(
        os.path.realpath(directory) + os.sep)
</code>```

Body:
I like to write a template system in Python, which allows to include files.

e.g.

    This is a template
    You can safely include files with safe_include`othertemplate.rst`

As you know, including files might be dangerous. For example, if I use the template system in a web application which allows users to create their own templates, they might do something like

I want your passwords: safe_include`/etc/password`

So therefore, I have to restrict the inclusion of files to files which are for example in a certain subdirectory (e.g. /home/user/templates)

The question is now: How can I check, whether /home/user/templates/includes/inc1.rst is in a subdirectory of /home/user/templates?

Would the following code work and be secure?

import os.path

def in_directory(file, directory, allow_symlink = False):
    #make both absolute
    directory = os.path.abspath(directory)
    file = os.path.abspath(file)

    #check whether file is a symbolic link, if yes, return false if they are not allowed
    if not allow_symlink and os.path.islink(file):
        return False

    #return true, if the common prefix of both is equal to directory
    #e.g. /a/b/c/d.rst and directory is /a/b, the common prefix is /a/b
    return os.path.commonprefix([file, directory]) == directory

As long, as allow_symlink is False, it should be secure, I think. Allowing symlinks of course would make it insecure if the user is able to create such links.

UPDATE - Solution
The code above does not work, if intermediate directories are symbolic links.
To prevent this, you have to use realpath instead of abspath.

UPDATE: adding a trailing / to directory to solve the problem with commonprefix() Reorx pointed out.

This also makes allow_symlink unnecessary as symlinks are expanded to their real destination

import os.path

def in_directory(file, directory):
    #make both absolute
    directory = os.path.join(os.path.realpath(directory), '')
    file = os.path.realpath(file)

    #return true, if the common prefix of both is equal to directory
    #e.g. /a/b/c/d.rst and directory is /a/b, the common prefix is /a/b
    return os.path.commonprefix([file, directory]) == directory


来源: stackexchange

问:
How to set split value in XSL 1.0
I need to set split values in different  parameters.My response like below.

```<code>  `<Response >
     <Result>100002 0 Testing 1500.00 YES</Result>
  </Response>`
</code>```

What i need is to get above split value in different result like below .[please note i have hard coded "select="100002" " values]

```<code>          ` <xsl:element name="ns1:Response">
              <xsl:value-of select="100002">
           </xsl:element>`

     `<xsl:element name="ns1:amount">
              <xsl:value-of select="0 ">
           </xsl:element>`

    `<xsl:element name="ns1:name">
              <xsl:value-of select="Testing  ">
           </xsl:element>`

   `<xsl:element name="ns1:Amount">
              <xsl:value-of select="1500.00">
           </xsl:element>`

 `<xsl:element name="ns1:Other">
              <xsl:value-of select="Yes">
           </xsl:element>`
</code>```

答:
You can use</p>

```<code><xsl:template match="Result">
        <xsl:call-template name="abc">
            <xsl:with-param name="data" select="."></xsl:with-param>
        </xsl:call-template>
    </xsl:template>

        <xsl:template name="abc">
    <xsl:param name="data"/>
    <xsl:element name="ns1:Response">
        <xsl:value-of select="substring-before($data, ' ')"/>
    </xsl:element>

    <xsl:element name="ns1:amount">
        <xsl:value-of select="substring-before(substring-after($data, ' '), ' ')"/>
    </xsl:element>

    <xsl:element name="ns1:name">
        <xsl:value-of select="substring-before(substring-after(substring-after($data, ' '), ' '), ' ')"/>
    </xsl:element>

    <xsl:element name="ns1:Amount">
        <xsl:value-of select="substring-before(substring-after(substring-after(substring-after($data, ' '), ' '), ' '), ' ')"/>
    </xsl:element>

    <xsl:element name="ns1:Other">
        <xsl:value-of select="substring-after(substring-after(substring-after(substring-after($data, ' '), ' '), ' '), ' ')"/>
    </xsl:element>
</xsl:template>
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to set split value in XSL 1.0

Body:
I need to set split values in different  parameters.My response like below.

  `<Response >
     <Result>100002 0 Testing 1500.00 YES</Result>
  </Response>`

What i need is to get above split value in different result like below .[please note i have hard coded "select="100002" " values]

          ` <xsl:element name="ns1:Response">
              <xsl:value-of select="100002">
           </xsl:element>`

     `<xsl:element name="ns1:amount">
              <xsl:value-of select="0 ">
           </xsl:element>`

    `<xsl:element name="ns1:name">
              <xsl:value-of select="Testing  ">
           </xsl:element>`

   `<xsl:element name="ns1:Amount">
              <xsl:value-of select="1500.00">
           </xsl:element>`

 `<xsl:element name="ns1:Other">
              <xsl:value-of select="Yes">
           </xsl:element>`

Body:
You can use

<xsl:template match="Result">
        <xsl:call-template name="abc">
            <xsl:with-param name="data" select="."></xsl:with-param>
        </xsl:call-template>
    </xsl:template>

        <xsl:template name="abc">
    <xsl:param name="data"/>
    <xsl:element name="ns1:Response">
        <xsl:value-of select="substring-before($data, ' ')"/>
    </xsl:element>

    <xsl:element name="ns1:amount">
        <xsl:value-of select="substring-before(substring-after($data, ' '), ' ')"/>
    </xsl:element>

    <xsl:element name="ns1:name">
        <xsl:value-of select="substring-before(substring-after(substring-after($data, ' '), ' '), ' ')"/>
    </xsl:element>

    <xsl:element name="ns1:Amount">
        <xsl:value-of select="substring-before(substring-after(substring-after(substring-after($data, ' '), ' '), ' '), ' ')"/>
    </xsl:element>

    <xsl:element name="ns1:Other">
        <xsl:value-of select="substring-after(substring-after(substring-after(substring-after($data, ' '), ' '), ' '), ' ')"/>
    </xsl:element>
</xsl:template>


问:
What's the best way to determine at runtime if a browser is too slow to gracefully handle complex JavaScript/CSS?
I'm toying with the idea of progressively enabling/disabling JavaScript (and CSS) effects on a page - depending on how fast/slow the browser seems to be.

I'm specifically thinking about low-powered mobile devices and old desktop computers -- not just IE6 :-)

Are there any examples of this sort of thing being done?

What would be the best ways to measure this - accounting for things, like temporary slowdowns on busy CPUs?

Notes:

I'm not interested in browser/OS detection.

At the moment, I'm not interested in bandwidth measurements - only browser/cpu performance.

Things that might be interesting to measure:

Base JavaScript

DOM manipulation

DOM/CSS rendering

I'd like to do this in a way that affects the page's render-speed as little as possible.

BTW: In order to not confuse/irritate users with inconsistent behavior - this would, of course, require on-screen notifications to allow users to opt in/out of this whole performance-tuning process.

[Update: there's a related question that I missed: Disable JavaScript function based on user's computer's performance. Thanks Andrioid!]

答:
You could try timing some basic operations - have a look at Steve Souder's Episodes and Yahoo's boomerang for good ways of timing stuff browserside. However its going to be rather complicated to work out how the metrics relate to an acceptable level of performance / a rewarding user experience.

If you're going to provide a UI to let users opt in / opt out, why not just let the user choose the level of eye candy in the app vs the rendering speed?

ContentLicense: CC BY-SA 2.5


问:
Parsing CSV file on Java to extract String
On Java Ive make a simple program with search bar. Ive also a CSV File 'file.csv' that contains this:

"ID","FIRSTNAME","LASTNAME"
"JM1","Jean","Martial"
"AD1","Audrey","Dubois"
"BX1","Bertrand","Xavier"```
</div>
</div>
</p>

<p>I can open the file on Java with this line.</p>

```String file = "C:\\file.csv";
```

<p>To verify if file exists I use this line.</p>

```if(new File(file).exists()) {
    JOptionPane.showMessageDialog(frame, "Fichier ouvert succes");
}
```

<p>Now I want to parse the file to extract <b>AD1</b> and display true if exist or false if not exists. Ive declared <b>Scanner</b> for this, but i dont know how to setup for this.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>Scanner scanner = null;
try {
  scanner = new Scanner(new File(file));
  scanner.useDelimiter(coma_delimiter);
  while(scanner.hasNext()) {
    String s1= scanner.next();
    System.out.print(s1 +"   ");
    if(s1.equals(search_field.getText())) {
      System.out.print("OKOK");
    } else {
      System.out.println("NOK");
    }
  }

} catch (FileNotFoundException fe) {
  fe.printStackTrace();
} finally {
  scanner.close();
}</code>```

Here the search_field is a JTextField.

答:
You may want to use Apache Commons CSV instead as this is designed to work with csv file, straight from their page is the below example

```<code>Reader in = new FileReader("path/to/file.csv");
Iterable<CSVRecord> records = CSVFormat.EXCEL.parse(in);
for (CSVRecord record : records) {
    String lastName = record.get("Last Name");
    String firstName = record.get("First Name");
}
</code>```

where "Last Name" and "First Name" are all column names.
This way you can clearly check on which column your string is.

Maven dependency below:

```<code><dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-csv</artifactId>
    <version>1.5</version>
</dependency>
</code>```

Body:
On Java Ive make a simple program with search bar. Ive also a CSV File 'file.csv' that contains this:

"ID","FIRSTNAME","LASTNAME"
"JM1","Jean","Martial"
"AD1","Audrey","Dubois"
"BX1","Bertrand","Xavier"

I can open the file on Java with this line.

String file = "C:\\file.csv";

To verify if file exists I use this line.

if(new File(file).exists()) {
    JOptionPane.showMessageDialog(frame, "Fichier ouvert succes");
}

Now I want to parse the file to extract AD1 and display true if exist or false if not exists. Ive declared Scanner for this, but i dont know how to setup for this.

Scanner scanner = null;
try {
  scanner = new Scanner(new File(file));
  scanner.useDelimiter(coma_delimiter);
  while(scanner.hasNext()) {
    String s1= scanner.next();
    System.out.print(s1 +"   ");
    if(s1.equals(search_field.getText())) {
      System.out.print("OKOK");
    } else {
      System.out.println("NOK");
    }
  }

} catch (FileNotFoundException fe) {
  fe.printStackTrace();
} finally {
  scanner.close();
}

Here the search_field is a JTextField.

Body:
You may want to use Apache Commons CSV instead as this is designed to work with csv file, straight from their page is the below example

Reader in = new FileReader("path/to/file.csv");
Iterable<CSVRecord> records = CSVFormat.EXCEL.parse(in);
for (CSVRecord record : records) {
    String lastName = record.get("Last Name");
    String firstName = record.get("First Name");
}

where "Last Name" and "First Name" are all column names.
This way you can clearly check on which column your string is.

Maven dependency below:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-csv</artifactId>
    <version>1.5</version>
</dependency>


答:
For a single column:

```<code>df %>% mutate(Col = ifelse(Col =< 0.66, -1/Value, Value))
</code>```

so for your dataframe (df) check the Column (Col) that would be the name of the column and then use the formula if true or leave it as it is if false.

```<code>mutate_at(e, vars(X0:X5), function(x) ifelse(x < .66, -1 / x, x))
</code>```

Title: use formula -1/n to all column in R

Body:
how can i use formula -1/n to all 100 column if column meets condition less then or equal to 0.66.

>read.table("~/Desktop/foldchange.csv",sep = ",",header = T)-> e
>e$X<-NULL
X85 = c(0.6858110076,
0.6763217948, 0.6777037797, 0.2477567046, 0.150890861, 1.4494420148
), X86 = c(0.6344889595, 0.3238520432, 0.6821503806, 1.2469503345,
0.1967564907, 0.9990678878), X87 = c(0.3741192137, 0.6666912747,
1.3112335946, 0.3164985959, 0.2201466863, 0.4888482588), X88 =

c(0.3119556762,
0.2054043658, 0.5943294282, 1.0861248907, 0.5118729002, 1.6492037186
), X89 = c(1.027412097, 0.0790170448, 1.3589022881, 0.4327791809,
1.4486313814, 0.3194611987), X90 = c(0.894763906, 0.4914006772,
1.1347816469, 0.6430273491, 0.3178809648, 1.073061393), X91 = c(0.628493603,
0.4914143019, 1.0304501567, 0.7207211083, 0.1074300226, 0.3380868057
), X92 = c(1.3026422866, 1.0840773898, 1.3157557712, 0.4775421572,
0.8786902151, 0.5843273081), X93 = c(0.3481263605, 0.4261844178,
1.3500611203, 1.7260437158, 0.2817451212, 0.5406176877), X94 = c(0.7430725423,
0.8863342393, 1.378542478, 1.390921504, 0.7538782912, 0.8613948595
), X95 = c(0.2210888181, 0.3678770932, 0.2777278428, 0.4768601083,
1.1094668285, 0.9609648852), X96 = c(0.2547985487, 0.3360082943,
1.8998726579, 0.8861691474, 0.1442648297, 1.060979381), X97 = c(0.1777107507,
0.8203439062, 1.3921490902, 0.1545204838, 0.2105020128, 1.1803859218
), X98 = c(0.6985609805, 1.1660525045, 0.9002045257, 0.9645039183,
0.3830624545, 0.7138528496), X99 = c(0.5112135444, 0.1983123941,
0.4952269467, 0.7465842632, 0.6262820927, 1.2293865608), X100 = c(1.2151302507,
0.2111249156, 0.9733885591, 0.2127452763, 0.2148471781, 0.3619375307
), X101 = c(0.4816703304, 1.0963122409, 0.9959054752, 1.3647606965,
0.4948024448, 1.0318667062), X102 = c(0.6428557554, 0.2657349241,
1.6929046554, 0.3760316507, 0.4520281529, 0.2360539647)), .Names =    c("Names",
"X0", "X1", "X2", "X3", "X4", "X5", "X6", "X7", "X8", "X9", "X10",
"X11", "X12", "X13", "X14", "X15", "X16", "X17", "X18", "X19",
"X20", "X21", "X22", "X23", "X24", "X25", "X26", "X27", "X28",
"X29", "X30", "X31", "X32", "X33", "X34", "X35", "X36", "X37",
"X38", "X39", "X40", "X41", "X42", "X43", "X44", "X45", "X46",
"X47", "X48", "X49", "X50", "X51", "X52", "X53", "X54", "X55",
"X56", "X57", "X58", "X59", "X60", "X61", "X62", "X63", "X64",
"X65", "X66", "X67", "X68", "X69", "X70", "X71", "X72", "X73",
"X74", "X75", "X76", "X77", "X78", "X79", "X80", "X81", "X82",
"X83", "X84", "X85", "X86", "X87", "X88", "X89", "X90", "X91",
"X92", "X93", "X94", "X95", "X96", "X97", "X98", "X99", "X100",
"X101", "X102"), row.names = c(NA, 6L), class = "data.frame")

I want to apply -1/n  for all values (< 0.66) in column X0 to X5 where n will be the value which will satisfy the condition < 0.66

Body:
For a single column:

df %>% mutate(Col = ifelse(Col =< 0.66, -1/Value, Value))

so for your dataframe (df) check the Column (Col) that would be the name of the column and then use the formula if true or leave it as it is if false.

mutate_at(e, vars(X0:X5), function(x) ifelse(x < .66, -1 / x, x))


问:
Execute a for loop in a R script in SAP HANA
I have written several R scripts which I call in RLANG stored procedures in SAP HANA.

So far, the scripts worked fine until I included a for-loop in the R script. I got this error.

Could not execute 'CREATE_PROCEDURE USE_ML(IN pred "PRED", IN model "MODEL", OUT result "RES") LANGUAGE RLANG ...'

SAP DBTech JDBC: [257]: sql syntax error: unterminated external language"

The piece of code I have included is similar to the following one and works fine if launched directly in my R console.

```<code>pred <- data.frame(vendor = as.factor(c("John", "Jack", "John", "Jack")),
                    product = as.factor(c("Milk", "Water", "Beef", "Water")))
modLevel <- list(vendor = as.factor(c("John", "William", "Jack")),
                  product = as.factor(c("Milk","Beef", "Water", "Peanut")))
params <- c("vendor", "product")
for (p in params){
   pred[,p] <- factor(pred[,p], levels(modLevel[[p]]))
}
</code>```

Needless to say that I have a larger amount of parameters I want to pass in this for-loop.

My question is the following one. Is it (1) possible to include this for-loop from R in the SQL statement without getting the syntax error or (2) must I change the structure of my script (if so, how can I) ?

Any help would be very much appreciated.

EDIT Here is the full SQL procedure in HANA.

```<code>DROP PROCEDURE USE_ML_MODEL;
CREATE PROCEDURE USE_ML_MODEL(IN pred "PRED", IN model "MODEL", OUT result "RES")
LANGUAGE RLANG AS
BEGIN
    modLevel <- unserialize(model$MOD_LEV[[1]])
    params <- c("VENDOR", "PRODUCT")
    for (p in params){
       pred[,p] <- factor(pred[,p], levels(modLevel[[p]]))
    }
    result <- pred
END;

DROP PROCEDURE SQL_R_USE_MODEL;
CREATE PROCEDURE SQL_R_USE_MODEL(OUT result "RES")
LANGUAGE SQLSCRIPT AS
BEGIN
    pred = SELECT VENDOR, PRODUCT FROM "PRED";
    model = SELECT * FROM "MODEL";
    CALL USE_ML_MODEL(:pred, :model , result);
END;

CALL SQL_R_USE_MODEL("RES") WITH OVERVIEW;
</code>```

答:
It appears that using a while loop in the R script solved the problem.

```<code>p <- 1
while (p < length(params)){
   pred[,params[p]] <- factor(pred[,params[p]], levels(modLevel[[params[p]]]))
   p <- p+1
}
</code>```

I'll leave the question open in case someone can explain what is the problem using for.

ContentLicense: CC BY-SA 4.0

Body:
I have written several R scripts which I call in RLANG stored procedures in SAP HANA.

So far, the scripts worked fine until I included a for-loop in the R script. I got this error.

Could not execute 'CREATE_PROCEDURE USE_ML(IN pred "PRED", IN model "MODEL", OUT result "RES") LANGUAGE RLANG ...'

SAP DBTech JDBC: [257]: sql syntax error: unterminated external language"

The piece of code I have included is similar to the following one and works fine if launched directly in my R console.

pred <- data.frame(vendor = as.factor(c("John", "Jack", "John", "Jack")),
                    product = as.factor(c("Milk", "Water", "Beef", "Water")))
modLevel <- list(vendor = as.factor(c("John", "William", "Jack")),
                  product = as.factor(c("Milk","Beef", "Water", "Peanut")))
params <- c("vendor", "product")
for (p in params){
   pred[,p] <- factor(pred[,p], levels(modLevel[[p]]))
}

Needless to say that I have a larger amount of parameters I want to pass in this for-loop.

My question is the following one. Is it (1) possible to include this for-loop from R in the SQL statement without getting the syntax error or (2) must I change the structure of my script (if so, how can I) ?

Any help would be very much appreciated.

EDIT Here is the full SQL procedure in HANA.

DROP PROCEDURE USE_ML_MODEL;
CREATE PROCEDURE USE_ML_MODEL(IN pred "PRED", IN model "MODEL", OUT result "RES")
LANGUAGE RLANG AS
BEGIN
    modLevel <- unserialize(model$MOD_LEV[[1]])
    params <- c("VENDOR", "PRODUCT")
    for (p in params){
       pred[,p] <- factor(pred[,p], levels(modLevel[[p]]))
    }
    result <- pred
END;

DROP PROCEDURE SQL_R_USE_MODEL;
CREATE PROCEDURE SQL_R_USE_MODEL(OUT result "RES")
LANGUAGE SQLSCRIPT AS
BEGIN
    pred = SELECT VENDOR, PRODUCT FROM "PRED";
    model = SELECT * FROM "MODEL";
    CALL USE_ML_MODEL(:pred, :model , result);
END;

CALL SQL_R_USE_MODEL("RES") WITH OVERVIEW;

Body:
It appears that using a while loop in the R script solved the problem.

p <- 1
while (p < length(params)){
   pred[,params[p]] <- factor(pred[,params[p]], levels(modLevel[[params[p]]]))
   p <- p+1
}

I'll leave the question open in case someone can explain what is the problem using for.


问:
serialize only one property of a class
I have a class which have about 20 members. I need to serialize my the object of this  class in a XML. But condition is I need only one member in the XML.

How can I do this.

EDIT : But at some time, I would like to serialize all the members. So I can't use [XMLIgnore] attribute.

答: you can put [XmlIgnore] attribute on all members you do not want to be serialized.</p>

Title: serialize only one property of a class


问:
How tomcat “catalina stop” find and stop the process?
How tomcat implement the catalina stop command? Does it find the process ID and kill the process or invoking any java dervice(JMX) and hat do the real work?</p>

答:
It stops the server with org.apache.catalina.startup.Bootstrap stop.
If it fails, it tries to kill the process using its pid.

You can see what's really happening in the bin/catalina.sh file.


问:
Using GetFunctionInfo to get the name of a function from a FunctionID
I am writing a CLR profiler using the ICorProfilerInfo interface.

When using SetEnterLeaveFunctionHooks, the callback methods are passed a FunctionID.

How do I get the metadata (I am after the name in particular), of a function given this FunctionID?

An MSDN article suggests that the first call should be to GetFunctionInfo. The documentation for this function states:

The profiler code can call ICorProfilerInfo::GetModuleMetaData to obtain a metadata interface for a given module. The metadata token that is returned to the location referenced by pToken can then be used to access the metadata for the function.

It does not elaborate on the last sentence ('the metadata token ... can be used to access metadata for the function').
How does this work?

So far, I am doing the following:

```<code>void MyProfiler::EnterMethod(FunctionID functionID)
{
    ClassID classId = 0;
    ModuleID moduleId = 0;
    mdToken metaDataToken = 0;
    IMetaDataImport* metaDataImport = NULL;

    // (m_info is ICorProfilerInfo3)
    m_info->GetFunctionInfo(functionID, &classId, &moduleId, &metaDataToken);
    m_info->GetModuleMetaData(moduleId, ofRead, IID_IMetaDataImport, (IUnknown**)&metaDataImport);

    // What goes here?
}
</code>```

I have tried to call GetTypeRefProps like this:

```<code>    mdToken ptkResolutionScope;
    WCHAR szName[1024];
    ULONG cchName = 1024;
    ULONG pchName;

    HRESULT result = MetaDataImport->GetTypeRefProps(pToken, &ptkResolutionScope, szName, cchName, &pchName);
</code>```

The final call returns S_FALSE, and does not populate szName.

答:
GetTypeRefProps is only applicable when your token is a TypeRef token, GetFunctionInfo will give you a MethodDef token which requires you to use the GetMethodProps method.

```<code>metaDataImport->GetMethodProps(metaDataToken, NULL, szName, cchName, &pchName, NULL, NULL, NULL, NULL, NULL);
</code>```

Body:
I am writing a CLR profiler using the ICorProfilerInfo interface.

When using SetEnterLeaveFunctionHooks, the callback methods are passed a FunctionID.

How do I get the metadata (I am after the name in particular), of a function given this FunctionID?

An MSDN article suggests that the first call should be to GetFunctionInfo. The documentation for this function states:

The profiler code can call ICorProfilerInfo::GetModuleMetaData to obtain a metadata interface for a given module. The metadata token that is returned to the location referenced by pToken can then be used to access the metadata for the function.

It does not elaborate on the last sentence ('the metadata token ... can be used to access metadata for the function').
How does this work?

So far, I am doing the following:

void MyProfiler::EnterMethod(FunctionID functionID)
{
    ClassID classId = 0;
    ModuleID moduleId = 0;
    mdToken metaDataToken = 0;
    IMetaDataImport* metaDataImport = NULL;

    // (m_info is ICorProfilerInfo3)
    m_info->GetFunctionInfo(functionID, &classId, &moduleId, &metaDataToken);
    m_info->GetModuleMetaData(moduleId, ofRead, IID_IMetaDataImport, (IUnknown**)&metaDataImport);

    // What goes here?
}

I have tried to call GetTypeRefProps like this:

    mdToken ptkResolutionScope;
    WCHAR szName[1024];
    ULONG cchName = 1024;
    ULONG pchName;

    HRESULT result = MetaDataImport->GetTypeRefProps(pToken, &ptkResolutionScope, szName, cchName, &pchName);

The final call returns S_FALSE, and does not populate szName.

Body:
GetTypeRefProps is only applicable when your token is a TypeRef token, GetFunctionInfo will give you a MethodDef token which requires you to use the GetMethodProps method.

metaDataImport->GetMethodProps(metaDataToken, NULL, szName, cchName, &pchName, NULL, NULL, NULL, NULL, NULL);


问:
How to change idle timeout asp mvc app on my shared hosting provider?
I have a site on a shared hosting provider. My site timeouts when on idle and can take up to 40 seconds to start up again, I want to increase the idle timeout. Under manage - Dedicated IIS application Pool, the idle timeout is set to 5 minutes I want to increase it, I called  my provider and they said I am unable to change the settings with a shared hosting account. I was thinking if there was another way Like the web.config folder to increase the timeout time?</p>

答: Uptime services that I've tried didn't actually send HTTP requests to the web app so it didn't help in keeping it alive. However, I found a nice feature in Application Insights called Availability which lets you create recurring tests that actually send GET requests to your website, thus preventing it from recycling.


问:
are there read spinlock and write spinlock?
Like </p>

```<code>pthread_rwlock_t lock;
pthread_rwlock_rdlock(&lock);
pthread_rwlock_wrlock(&lock);
</code>```

<p>Are the similar lock in spinlock? </p>

答:
The difference between a read lock and a write lock is, that a read lock is shared (i.e. can be acquired by multiple threads), but the write lock is exclusive (can only be acquired if no other locks are in effect).

The pthread spinlock interface only supports exclusive locks with pthread_spin_lock(), so this is not possible out of the box. You could however emulate the behaviour described above by maintaining an appropriate (counter) structure and using pthread_spin_trylock() (access to this structure must of course be synchronized, too). This might, however, counter the big advantage of "lightweightness" of spinlocks.

Body:
Like

pthread_rwlock_t lock;
pthread_rwlock_rdlock(&lock);
pthread_rwlock_wrlock(&lock);

Are the similar lock in spinlock?


问:
How do I check that a Gjs class has already been defined?
I am writing the preference view a GNOME shell extension and an facing issues when using the imports.lang function to write the application in an object oriented fashion.

```<code>const Gtk = imports.gi.Gtk
const Lang = imports.lang
Gtk.init(null)
const MyWindow = new Lang.Class({...})
</code>```

Opening the preference window the first time works, but subsequent ones throw the following error: Error: Type name Gjs_MyWindow is already registered. Upon closing the window for the first time, I receive this error: TypeError: prefsModule.init is not a function.

The following more imperative code works:

```<code>const Gtk = imports.gi.Gtk
Gtk.init(null)
const window = new Gtk.Window({ type: Gtk.WindowType.TOPLEVEL })
</code>```

Based on the errors thrown, my guess is that the class is being redefined. How can I avoid redefinition and receive the defined class otherwise? (Are there any docs I can refer to?)

答:
Looks like the right answer is in this discussion.

If you extend a GObject class (anything from St, Clutter, Gtk, etc.), you're registering a new GType, and that's not possible for extensions.

...

Extensions are dynamic modules, and they can be loaded and unloaded - but that's not at all possible for GTypes.

So, don't extend GTypes. Instead, use the "delegate pattern", which looks like that.

```<code>const Class = new Lang.Class({
  Name: "Class",

  _init: function() {
    this.actor = new St.Button();
  }
)};
</code>```

This being said, if you have a look at the extensions installed on your system and do something like grep -rn 'Extends: Gtk' /usr/share/gnome-shell/extensions/, you will see that some extensions still extend GTypes, and it doesn't cause any error. But you will notice that it's never done in the extension.js file...

Don't ask for more details here, that's all I know as of today !

Body:
I am writing the preference view a GNOME shell extension and an facing issues when using the imports.lang function to write the application in an object oriented fashion.

const Gtk = imports.gi.Gtk
const Lang = imports.lang
Gtk.init(null)
const MyWindow = new Lang.Class({...})

Opening the preference window the first time works, but subsequent ones throw the following error: Error: Type name Gjs_MyWindow is already registered. Upon closing the window for the first time, I receive this error: TypeError: prefsModule.init is not a function.

The following more imperative code works:

const Gtk = imports.gi.Gtk
Gtk.init(null)
const window = new Gtk.Window({ type: Gtk.WindowType.TOPLEVEL })

Based on the errors thrown, my guess is that the class is being redefined. How can I avoid redefinition and receive the defined class otherwise? (Are there any docs I can refer to?)

Body:
Looks like the right answer is in this discussion.

If you extend a GObject class (anything from St, Clutter, Gtk, etc.), you're registering a new GType, and that's not possible for extensions.

...

Extensions are dynamic modules, and they can be loaded and unloaded - but that's not at all possible for GTypes.

So, don't extend GTypes. Instead, use the "delegate pattern", which looks like that.

const Class = new Lang.Class({
  Name: "Class",

  _init: function() {
    this.actor = new St.Button();
  }
)};

This being said, if you have a look at the extensions installed on your system and do something like grep -rn 'Extends: Gtk' /usr/share/gnome-shell/extensions/, you will see that some extensions still extend GTypes, and it doesn't cause any error. But you will notice that it's never done in the extension.js file...

Don't ask for more details here, that's all I know as of today !


问:
Query to produce data only within the asked hour range
Oracle SQL:

I been trying to get this some snippet of query working. When you run it, it prompts you for an hour, and displays no records. I don’t want the query to have a static hour as it will need to be run 4 times a day.
So from the ‘&date’ input, I want it to show data for the past 24 hours. Is that possible?

```<code>dt_time = timestamp(6) field

select distinct to_char(dt_ time,'dd/mm/yyyy hh24'), fault_description
from order
where to_char(dt_time,'hh24') <= '&date' -24
order by to_char(dt_ time,'dd/mm/yyyy hh24');
</code>```

Example, if you enter 10 (when query executed) it will show the data from 10(:00) through to 10(:00)next day

[Hope there is enough info for someone to answer, please]

答:
You need to make use of SYSDATE as you are fetching last one day data.
Also if you add or subtract number with a date column the offset will be number of days, not number of hours. So you need to use &date/24

Try this:

```<code>select distinct to_char(dt_time,'dd/mm/yyyy hh24'), fault_description
from order
where dt_time - &date / 24 between TRUNC(sysdate-1) and TRUNC(sysdate)
order by to_char(dt_ time,'dd/mm/yyyy hh24');
</code>```

Please comment.

Body:
Oracle SQL:

I been trying to get this some snippet of query working. When you run it, it prompts you for an hour, and displays no records. I don’t want the query to have a static hour as it will need to be run 4 times a day.
So from the ‘&date’ input, I want it to show data for the past 24 hours. Is that possible?

dt_time = timestamp(6) field

select distinct to_char(dt_ time,'dd/mm/yyyy hh24'), fault_description
from order
where to_char(dt_time,'hh24') <= '&date' -24
order by to_char(dt_ time,'dd/mm/yyyy hh24');

Example, if you enter 10 (when query executed) it will show the data from 10(:00) through to 10(:00)next day

[Hope there is enough info for someone to answer, please]

Body:
You need to make use of SYSDATE as you are fetching last one day data.
Also if you add or subtract number with a date column the offset will be number of days, not number of hours. So you need to use &date/24

Try this:

select distinct to_char(dt_time,'dd/mm/yyyy hh24'), fault_description
from order
where dt_time - &date / 24 between TRUNC(sysdate-1) and TRUNC(sysdate)
order by to_char(dt_ time,'dd/mm/yyyy hh24');

Please comment.


答:
Add the following attribute for all the members you don't want to serialize,</p>

```<code>[XmlIgnore()]
public Type X
{
get;set;
}
</code>```

Title: serialize only one property of a class

Body:
I have a class which have about 20 members. I need to serialize my the object of this  class in a XML. But condition is I need only one member in the XML.

How can I do this.

EDIT : But at some time, I would like to serialize all the members. So I can't use [XMLIgnore] attribute.

Body:
Add the following attribute for all the members you don't want to serialize,

[XmlIgnore()]
public Type X
{
get;set;
}


问:
knockout.js validation on observableArray to require all items (no empty fields)
I have written the following example of using knockout.

HTML

```<code><script id="customMessageTemplate" type="text/html">
    <em class="customMessage" data-bind='validationMessage: field'></em>
</script>
<fieldset>
    <legend>User: <span data-bind='text: errors().length'></span> errors</legend>
    <label>First name: <input data-bind='value: firstName'/></label>
    <label>Last name: <input data-bind='value: lastName'/></label>

    <table>
    <thead>
        <tr><th>Value</th></tr>
    </thead>
    <tbody data-bind="foreach: captcha">
        <tr>
            <td><input data-bind="value: value" type="test" /></td>
        </tr>
    </tbody>
</table>

<button type="button" data-bind='click: submit'>Submit</button>
</code>```

Knockout

```<code>ko.validation.rules.pattern.message = 'Invalid.';

ko.validation.configure({
    registerExtenders: true,
    messagesOnModified: true,
    insertMessages: true,
    parseInputAttributes: true,
    messageTemplate: null
});

var captcha = function (val) {
    return val == 11;
};

var mustEqual = function (val, other) {
    return val == other();
};

var viewModel = {
    firstName: ko.observable().extend({ required: true }),
    lastName: ko.observable().extend({ required: true }),
    captcha: ko.observableArray([{value: "test"}]),

    submit: function () {
        if (viewModel.errors().length == 0) {
            alert('Thank you.');
        } else {
            alert('Please check your submission.');
            viewModel.errors.showAllMessages();
        }
    }
};

viewModel.errors = ko.validation.group(viewModel);

ko.applyBindings(viewModel);
</code>```

What should I add to observableArray to require all items in this array the same way like usual observable object reffrering to input fields FirstName and LastName in presented example?

答:
You can add your custom validation rule like so:

```<code>ko.validation.rules['noEmptyValues'] = {
    validator: function (arr) {
        return arr.every(function(v) {
          return v && v.value; // TODO: confirm this is the test condition
        });
    },
    message: "Array contains empty items"
};

// Some place else:
var arrayThatCannotContainEmptyValues = ko.observableArray([])
  .extend({ noEmptyValues: true });
</code>```

It's not exactly clear what the test should be at the // TODO line, but I'm sure you can figure it out.

Note that this only works when you're modifying the actual array. Since value isn't observable, it won't trigger an update in the example above.

Body:
I have written the following example of using knockout.

HTML

<fieldset>
    <legend>User:  errors</legend>
    First name: <input data-bind='value: firstName'/>
    Last name: <input data-bind='value: lastName'/>

Value

            <input data-bind="value: value" type="test" />

<button type="button" data-bind='click: submit'>Submit</button>

Knockout

ko.validation.rules.pattern.message = 'Invalid.';

ko.validation.configure({
    registerExtenders: true,
    messagesOnModified: true,
    insertMessages: true,
    parseInputAttributes: true,
    messageTemplate: null
});

var captcha = function (val) {
    return val == 11;
};

var mustEqual = function (val, other) {
    return val == other();
};

var viewModel = {
    firstName: ko.observable().extend({ required: true }),
    lastName: ko.observable().extend({ required: true }),
    captcha: ko.observableArray([{value: "test"}]),

    submit: function () {
        if (viewModel.errors().length == 0) {
            alert('Thank you.');
        } else {
            alert('Please check your submission.');
            viewModel.errors.showAllMessages();
        }
    }
};

viewModel.errors = ko.validation.group(viewModel);

ko.applyBindings(viewModel);

What should I add to observableArray to require all items in this array the same way like usual observable object reffrering to input fields FirstName and LastName in presented example?

Body:
You can add your custom validation rule like so:

ko.validation.rules['noEmptyValues'] = {
    validator: function (arr) {
        return arr.every(function(v) {
          return v && v.value; // TODO: confirm this is the test condition
        });
    },
    message: "Array contains empty items"
};

// Some place else:
var arrayThatCannotContainEmptyValues = ko.observableArray([])
  .extend({ noEmptyValues: true });

It's not exactly clear what the test should be at the // TODO line, but I'm sure you can figure it out.

Note that this only works when you're modifying the actual array. Since value isn't observable, it won't trigger an update in the example above.


问:
gridview row count returns 0
I have an aspx page with C# in code behind.

In this page, there are 3 gridviews and a button - export to excel.

On button click, the contents of 3 gridviews will be exported to 3 excel sheets.

The data binding of the gridviews are done in a class file and the gridview is returned.

```<code>string sql1="something1";
classFile.gvBind(gv1,sql1);

string sql2="something2";
classFile.gvBind(gv2,sql2);

string sql3="something3";
classFile.gvBind(gv3,sql3);
</code>```

And it works good. Now on button click, I am looping through the columns and rows of gridviews and exporting them. But always the row count of all gridviews is showing zero. The column headers however are working.

Here is the code on button click:

```<code>XLWorkbook wb = new XLWorkbook();
GridView[] gvExcel = new GridView[] { gv1, gv2, gv3};
string[] name = new string[] { "sheetName1", "sheetName2", "sheetName3"};
        for (int i = 0; i < gvExcel.Length; i++)
        {
            if (gvExcel[i].Visible)
            {
                gvExcel[i].AllowPaging = false;
                gvExcel[i].DataBind();
                DataTable dt = new DataTable(name[i].ToString());
                for (int z = 0; z < gvExcel[i].Columns.Count; z++)
                {
                    dt.Columns.Add(gvExcel[i].Columns[z].HeaderText);
                }

                int x = gvExcel[i].Rows.Count;
                foreach (GridViewRow row in gvExcel[i].Rows)
                {
                    dt.Rows.Add();
                    for (int c = 0; c < gvRow.Cells.Count; c++)
                    {
                        dt.Rows[dt.Rows.Count - 1][c] = gvRow.Cells[c].Text;
                    }
                }

                wb.Worksheets.Add(dt);
                gvExcel[i].AllowPaging = true;
            }
</code>```

The int x is always =0. Where am I doing wrong? Any help?
Thank you.!!

答:
Ok I found the problem. I commented out this line

gvExcel[i].DataBind();

and the row count is coming proper now.
I guess since the dataset and data binding is not executing in this page but from a different .cs file, so when I bind the data again to gridview, its basically null dataset getting bind and rowcnt is also=0.

Title: gridview row count returns 0

Body:
I have an aspx page with C# in code behind.

In this page, there are 3 gridviews and a button - export to excel.

On button click, the contents of 3 gridviews will be exported to 3 excel sheets.

The data binding of the gridviews are done in a class file and the gridview is returned.

string sql1="something1";
classFile.gvBind(gv1,sql1);

string sql2="something2";
classFile.gvBind(gv2,sql2);

string sql3="something3";
classFile.gvBind(gv3,sql3);

And it works good. Now on button click, I am looping through the columns and rows of gridviews and exporting them. But always the row count of all gridviews is showing zero. The column headers however are working.

Here is the code on button click:

XLWorkbook wb = new XLWorkbook();
GridView[] gvExcel = new GridView[] { gv1, gv2, gv3};
string[] name = new string[] { "sheetName1", "sheetName2", "sheetName3"};
        for (int i = 0; i < gvExcel.Length; i++)
        {
            if (gvExcel[i].Visible)
            {
                gvExcel[i].AllowPaging = false;
                gvExcel[i].DataBind();
                DataTable dt = new DataTable(name[i].ToString());
                for (int z = 0; z < gvExcel[i].Columns.Count; z++)
                {
                    dt.Columns.Add(gvExcel[i].Columns[z].HeaderText);
                }

                int x = gvExcel[i].Rows.Count;
                foreach (GridViewRow row in gvExcel[i].Rows)
                {
                    dt.Rows.Add();
                    for (int c = 0; c < gvRow.Cells.Count; c++)
                    {
                        dt.Rows[dt.Rows.Count - 1][c] = gvRow.Cells[c].Text;
                    }
                }

                wb.Worksheets.Add(dt);
                gvExcel[i].AllowPaging = true;
            }

The int x is always =0. Where am I doing wrong? Any help?
Thank you.!!


问:
How to create a rectangle with two rounded corners?
I need to create a rectangle view with two rounded corners using canvas.I used drawRoundRect but i am getting rectangle with four rounded corners.Please anyone suggest me a way that can be helpful in solving my problem.</p>

```<code> rect = new RectF(left, top, right, bottom);

 canvas.drawRoundRect(rect, 20, 20, facePaint);
</code>```

答: There is no built in function to do that.  You'll need to create a Path with the shape you want, then use drawPath to draw the path to the canvas</p>

Body:
I need to create a rectangle view with two rounded corners using canvas.I used drawRoundRect but i am getting rectangle with four rounded corners.Please anyone suggest me a way that can be helpful in solving my problem.

 rect = new RectF(left, top, right, bottom);

 canvas.drawRoundRect(rect, 20, 20, facePaint);


问:
Customize `::-webkit-scrollbar` inline with React
How can I apply the ::-webkit-scrollbar pseudo elements to a component using inline styling in React?

答: You can't write pseudo selector inline, you need to add it in css. Refer this link


问:
Android Studio 3.0 laggy typing experience
I have an extremely disturbing laggy Android Studio editor. I read all proposed optimisation suggestions on the stack and did following things to speed it but nothing helped.

Increased the Heap Size in VM options with following options

Disabled all the plugins regarding git, svn etc.

Checked the followings in Compiler settings

Compiler independent modules

--offline in command line options

Configure on demand

My Device is an MBP from middle 2015 with 16 GB Ram and 512 GB SSD HD.The project is a Java Project which was ok on my other laptop.
Any other things I can do?

答:
Thank you guys for all advices. After having eye cancer with laggy editor  I finally managed to speed it up. Fortunately It was not only the fault of the Android Studio itself, so that we can't blame it directly =)

As @FierceFox suggested I saw that windows server was working quite hard in the background and eating my CPU as well my memory.

```<code>sudo rm /Library/Preferences/com.apple.windowserver.plist
sudo rm ~/Library/Preferences/ByHost/com.apple.windowserver*.plist
</code>```

Restart MacOSX with PRAM reset (hold the P and R keys while holding down the option (⌥) and command (⌘) keys before the gray boot screen appears)

Now My Editor is working fine again.

UPDATE:

As soon as I choose scaled resolution, the editor gets laggy again.!
So it only works fine in default resolution.The problem is actualy only valid for Android Studio.In Xcode it seems to be OK.

Body:
Thank you guys for all advices. After having eye cancer with laggy editor  I finally managed to speed it up. Fortunately It was not only the fault of the Android Studio itself, so that we can't blame it directly =)

As @FierceFox suggested I saw that windows server was working quite hard in the background and eating my CPU as well my memory.

sudo rm /Library/Preferences/com.apple.windowserver.plist
sudo rm ~/Library/Preferences/ByHost/com.apple.windowserver*.plist

Restart MacOSX with PRAM reset (hold the P and R keys while holding down the option (⌥) and command (⌘) keys before the gray boot screen appears)

Now My Editor is working fine again.

UPDATE:

As soon as I choose scaled resolution, the editor gets laggy again.!
So it only works fine in default resolution.The problem is actualy only valid for Android Studio.In Xcode it seems to be OK.


问:
File Upload using AngularJS
Here is my HTML form:

```<code><form name="myForm" ng-submit="">
    <input ng-model='file' type="file"/>
    <input type="submit" value='Submit'/>
</form>
</code>```

I want to upload an image from local machine and want to read the content of the uploaded file. All this I want to do using AngularJS.

When I try to print the value of $scope.file it comes as undefined.

答:
We have used HTML, CSS and AngularJS. Following example shows about how to upload the file using AngularJS.</p>

```<code><html>

   <head>
      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
   </head>

   <body ng-app = "myApp">

      <div ng-controller = "myCtrl">
         <input type = "file" file-model = "myFile"/>
         <button ng-click = "uploadFile()">upload me</button>
      </div>

      <script>
         var myApp = angular.module('myApp', []);

         myApp.directive('fileModel', ['$parse', function ($parse) {
            return {
               restrict: 'A',
               link: function(scope, element, attrs) {
                  var model = $parse(attrs.fileModel);
                  var modelSetter = model.assign;

                  element.bind('change', function(){
                     scope.$apply(function(){
                        modelSetter(scope, element[0].files[0]);
                     });
                  });
               }
            };
         }]);

         myApp.service('fileUpload', ['$http', function ($http) {
            this.uploadFileToUrl = function(file, uploadUrl){
               var fd = new FormData();
               fd.append('file', file);

               $http.post(uploadUrl, fd, {
                  transformRequest: angular.identity,
                  headers: {'Content-Type': undefined}
               })

               .success(function(){
               })

               .error(function(){
               });
            }
         }]);

         myApp.controller('myCtrl', ['$scope', 'fileUpload', function($scope, fileUpload){
            $scope.uploadFile = function(){
               var file = $scope.myFile;

               console.log('file is ' );
               console.dir(file);

               var uploadUrl = "/fileUpload";
               fileUpload.uploadFileToUrl(file, uploadUrl);
            };
         }]);

      </script>

   </body>
</html>
</code>```

Title: File Upload using AngularJS

Body:
Here is my HTML form:

<form name="myForm" ng-submit="">
    <input ng-model='file' type="file"/>
    <input type="submit" value='Submit'/>
</form>

I want to upload an image from local machine and want to read the content of the uploaded file. All this I want to do using AngularJS.

When I try to print the value of $scope.file it comes as undefined.

Body:
We have used HTML, CSS and AngularJS. Following example shows about how to upload the file using AngularJS.

<html>

   <head>
      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
   </head>

   <body ng-app = "myApp">

      <div ng-controller = "myCtrl">
         <input type = "file" file-model = "myFile"/>
         <button ng-click = "uploadFile()">upload me</button>
      </div>

      <script>
         var myApp = angular.module('myApp', []);

         myApp.directive('fileModel', ['$parse', function ($parse) {
            return {
               restrict: 'A',
               link: function(scope, element, attrs) {
                  var model = $parse(attrs.fileModel);
                  var modelSetter = model.assign;

                  element.bind('change', function(){
                     scope.$apply(function(){
                        modelSetter(scope, element[0].files[0]);
                     });
                  });
               }
            };
         }]);

         myApp.service('fileUpload', ['$http', function ($http) {
            this.uploadFileToUrl = function(file, uploadUrl){
               var fd = new FormData();
               fd.append('file', file);

               $http.post(uploadUrl, fd, {
                  transformRequest: angular.identity,
                  headers: {'Content-Type': undefined}
               })

               .success(function(){
               })

               .error(function(){
               });
            }
         }]);

         myApp.controller('myCtrl', ['$scope', 'fileUpload', function($scope, fileUpload){
            $scope.uploadFile = function(){
               var file = $scope.myFile;

               console.log('file is ' );
               console.dir(file);

               var uploadUrl = "/fileUpload";
               fileUpload.uploadFileToUrl(file, uploadUrl);
            };
         }]);

      </script>

   </body>
</html>


问:
Why are there keywords and standard stereotypes?
Some times I use keywords like <<use>> and some times standard stereotypes like <<Create>> .

But I wonder why the two notions exist in UML. I feel that keywords could be integrated in a profile.

So does someone knonw why there is a set of keywords AND standard stereotypes ?

答:
Visually there is no way to distinguish a keyword from a stereotype.

Keywords are a notation feature.
They are used when there is no other notation available or as an alternative notation. This alternative notation is usually a simple rectangle with the name of the meta-type as keyword.

Keywords are used only for existing meta-classes from the UML meta-model. So in the case of «use» you are actually modelling a Usage relation for which the notation is the same as a Dependency with the addition of the «use» keyword.

Stereotypes on the other hand are an extension of the UML meta-model. By defining a stereotype in a profile you are inventing your own meta-classes who extend existing UML meta-classs. The notation for such an extended meta-class is to show the notation for the standard UML metaclass + the name of the stereotype between guillemets («stereotype»)

The standard stereotypes you are referring to are defined in the UML Standard Profile (see specs 2.5 at page 677).

The Standard Profile specifies a set of predefined standard stereotypes. A conforming tool shall support all of the
  stereotypes in the Standard Profile.

The example «Create» is defined in this Standard profile as an extension of the Usage meta-class.

The reason why some concepts are real meta-classes (such as Usage) and others are extended metatypes (stereotypes) defined in the standard profile (such as Create) is not immediately clear. I personally suspect that this whole Standard Profile is the result of a compromise between the different parties in the committee that had to define the UML specs.

By defining it in the Standard Profile instead of as a proper meta-class it is not really in the specs, but also not really out either.


问:
How to change a status bar color in a Fragment page as Transparent in android
Am using this in fragment page

```<code> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                getActivity().getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
                getActivity().getWindow().setStatusBarColor(getResources().getColor(R.color.transparant));
            }
</code>```

答:
Create a Custom class

```<code>public class CommonStatusBarColor {

     public void StatusBarColor(Activity activity, String colorCode)
        {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
            {
                Window window =activity.getWindow();
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                window.setStatusBarColor(Color.parseColor(colorCode));
            }

        }

}
</code>```

Then Call in onCreateView section.

```<code> CommonStatusBarColor commonStatusBarColorObj =new CommonStatusBarColor();
 commonStatusBarColorObj.StatusBarColor(getActivity(),"#00ffffff"); // set your color
</code>```

Body:
Am using this in fragment page

 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                getActivity().getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
                getActivity().getWindow().setStatusBarColor(getResources().getColor(R.color.transparant));
            }

Body:
Create a Custom class

public class CommonStatusBarColor {

     public void StatusBarColor(Activity activity, String colorCode)
        {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
            {
                Window window =activity.getWindow();
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                window.setStatusBarColor(Color.parseColor(colorCode));
            }

        }

}

Then Call in onCreateView section.

 CommonStatusBarColor commonStatusBarColorObj =new CommonStatusBarColor();
 commonStatusBarColorObj.StatusBarColor(getActivity(),"#00ffffff"); // set your color


问:
Webview avoid security alert from google play upon implementation of onReceivedSslError
I am getting security alert from google play saying:

Your APK has been rejected for containing security vulnerabilities, which violates the Malicious Behavior policy. If you submitted an update, the previous version of your app is still live on Google Play.

If I remove onReceivedSslError (handler.proceed()), page won't open.
Is there anyway I can open page in webview and avoid security alert.

and my website to put in my app need http or https ? I'm using http://mywebsite...

答:
Change onReceivedSslError() to:

```<code>@Override
public void onReceivedSslError(WebView v, final SslErrorHandler handler, SslError er) {
final AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());
    builder.setMessage("Problem with Security");
    builder.setPositiveButton("continue", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            handler.proceed();
        }
    });
    builder.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            handler.cancel();
        }
    });
    final AlertDialog dialog = builder.create();
    dialog.show();
}
</code>```

Hope this will help you.

Body:
Change onReceivedSslError() to:

@Override
public void onReceivedSslError(WebView v, final SslErrorHandler handler, SslError er) {
final AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());
    builder.setMessage("Problem with Security");
    builder.setPositiveButton("continue", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            handler.proceed();
        }
    });
    builder.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            handler.cancel();
        }
    });
    final AlertDialog dialog = builder.create();
    dialog.show();
}

Hope this will help you.


问:
How to bypass or intercept the Authentication Required dialog
Is there a way to bypass or intercept the "Authentication Required" dialog in C# so that it automatically authenticates the user on an intranet site?  The dialog I'm referring to is the one indicated below:

At present I've created a new ASP.NET MVC 4 intranet site and have no idea how to stop this dialog from popping up using C# code.

Cheers,

Tim

答:
To bypass do this:

Select project in solution explorer

Right click and go to properties (or press F4)

Set Allow anonymous access to enabled (enabled, allow or whatever the option was).

The problems originates to not having the site added to intranet. You can do that too but the above makes everything easier. Anyway:

Chrome:
Chrome > Options > Under the Hood > Change Proxy Settings > Security (tab) > Local Intranet/Sites > Advanced.

IE:
This

Firefox:
This


问:
How to filter docker process based on image
I have been trying to get the container id of docker instance using docker process command, but when i'm trying with filter by name it works fine for me.

```<code>sudo -S docker ps -q --filter="name=romantic_rosalind"
</code>```

Results container id :

3c7e865f1dfb

But when i filter using image i'm getting all the instance container ids :

```<code>sudo -S docker ps -q  --filter="image=docker-mariadb:1.0.1"
</code>```

Results Container ids :

5570dc09b581

3c7e865f1dfb

But i wish to get only container id of mariadb.

How to get container id of docker process using filter as image ?

答:
```<code>docker ps -a | awk '{ print $1,$2 }' | grep imagename | awk '{print $1 }'
</code>```

This is perfect. if you need you can add a filter of running images of a particular stsatus alone,  like below

```<code>docker ps -a --filter=running | awk '{ print $1,$2 }' | grep rulsoftreg:5000/mypayroll/cisprocessing-printdocsnotifyconsumer:latest | awk '{print $1 }'
</code>```

Various other filter options can be explored here

https://docs.docker.com/v1.11/engine/reference/commandline/ps/

Body:
I have been trying to get the container id of docker instance using docker process command, but when i'm trying with filter by name it works fine for me.

sudo -S docker ps -q --filter="name=romantic_rosalind"

Results container id :

3c7e865f1dfb

But when i filter using image i'm getting all the instance container ids :

sudo -S docker ps -q  --filter="image=docker-mariadb:1.0.1"

Results Container ids :

5570dc09b581

3c7e865f1dfb

But i wish to get only container id of mariadb.

How to get container id of docker process using filter as image ?

Body:
docker ps -a | awk '{ print $1,$2 }' | grep imagename | awk '{print $1 }'

This is perfect. if you need you can add a filter of running images of a particular stsatus alone,  like below

docker ps -a --filter=running | awk '{ print $1,$2 }' | grep rulsoftreg:5000/mypayroll/cisprocessing-printdocsnotifyconsumer:latest | awk '{print $1 }'

Various other filter options can be explored here

https://docs.docker.com/v1.11/engine/reference/commandline/ps/


问:
MySQL - Embedded selects - How to put rows into columns?
Good Morning, I am facing a odd built database and i am trying to requesting it.

My request :

```<code>use redmine_tma_ibp;
SELECT issues.id, custom_fields.name, custom_values.value FROM       redmine_tma_ibp.issues
join custom_values
    on issues.id = custom_values.customized_id
join custom_fields
    on custom_values.custom_field_id = custom_fields.id
join enumerations
    on enumerations.id=issues.priority_id
where (enumerations.type="IssuePriority" and (enumerations.position=1 or enumerations.position=2))
    and (status_id=3 or status_id=5)
    and (custom_fields.name = "Date de résolution" or custom_fields.name="Date d'ouverture")
    and str_to_date(custom_values.value, '%d/%m/%Y %H:%i') > date('2016-01-01');
</code>```

it displays the following :

```<code>13430   Date de résolution  20/01/2016 16:52:27
14336   Date de résolution  04/01/2016 16:07:06
15705   Date d'ouverture    02/01/2016 00:28:46
15705   Date de résolution  04/01/2016 11:11:04
15774   Date d'ouverture    05/01/2016 11:15:06
15774   Date de résolution  05/01/2016 15:55:43
15790   Date d'ouverture    05/01/2016 16:24:20
15790   Date de résolution  06/01/2016 10:42:28
15917   Date d'ouverture    07/01/2016 16:04:31
15917   Date de résolution  07/06/2016 11:43:08
15955   Date d'ouverture    11/01/2016 02:21:48
15955   Date de résolution  12/01/2016 11:19:21
15998   Date de résolution  13/01/2016 10:35:29
</code>```

I need to transform my request in order to have one column with the "Date d'ouverture" and another with the "Date de résolution", corresponding dates inside corresponding columns and grouped by id.

I cannot change the database structure which is read only.

Please help me....

答:
It's a pivot :

```<code>SELECT issues.id,
   MAX(CASE WHEN custom_fields.name='Date de résolution'
       THEN custom_values.value
   ELSE '-'
   END) AS 'Date de résolution',
   MAX(CASE WHEN custom_fields.name='Date d\'ouverture'
       THEN custom_values.value
   ELSE '-'
   END )AS 'Date d\'ouverture'
FROM [....]
GROUP BY issues.id
</code>```

I use the trick with MAX() for the group by.

Body:
Good Morning, I am facing a odd built database and i am trying to requesting it.

My request :

use redmine_tma_ibp;
SELECT issues.id, custom_fields.name, custom_values.value FROM       redmine_tma_ibp.issues
join custom_values
    on issues.id = custom_values.customized_id
join custom_fields
    on custom_values.custom_field_id = custom_fields.id
join enumerations
    on enumerations.id=issues.priority_id
where (enumerations.type="IssuePriority" and (enumerations.position=1 or enumerations.position=2))
    and (status_id=3 or status_id=5)
    and (custom_fields.name = "Date de résolution" or custom_fields.name="Date d'ouverture")
    and str_to_date(custom_values.value, '%d/%m/%Y %H:%i') > date('2016-01-01');

it displays the following :

13430   Date de résolution  20/01/2016 16:52:27
14336   Date de résolution  04/01/2016 16:07:06
15705   Date d'ouverture    02/01/2016 00:28:46
15705   Date de résolution  04/01/2016 11:11:04
15774   Date d'ouverture    05/01/2016 11:15:06
15774   Date de résolution  05/01/2016 15:55:43
15790   Date d'ouverture    05/01/2016 16:24:20
15790   Date de résolution  06/01/2016 10:42:28
15917   Date d'ouverture    07/01/2016 16:04:31
15917   Date de résolution  07/06/2016 11:43:08
15955   Date d'ouverture    11/01/2016 02:21:48
15955   Date de résolution  12/01/2016 11:19:21
15998   Date de résolution  13/01/2016 10:35:29

I need to transform my request in order to have one column with the "Date d'ouverture" and another with the "Date de résolution", corresponding dates inside corresponding columns and grouped by id.

I cannot change the database structure which is read only.

Please help me....

Body:
It's a pivot :

SELECT issues.id,
   MAX(CASE WHEN custom_fields.name='Date de résolution'
       THEN custom_values.value
   ELSE '-'
   END) AS 'Date de résolution',
   MAX(CASE WHEN custom_fields.name='Date d\'ouverture'
       THEN custom_values.value
   ELSE '-'
   END )AS 'Date d\'ouverture'
FROM [....]
GROUP BY issues.id

I use the trick with MAX() for the group by.


问:
Why Float error is different in C?
Please see the pictures:

I'm amazing the result is different.

答:
CGFloat is a double on your machine, therefore what you are doing is this:

```<code>double a = 100.00f
double price = 88888736 / a

float a2 = 100.00f // `float` type enforced by the trailing `f`
double price2 = 88888736 / a2
</code>```

The difference is that in the first case the division is a double division while in the second case this is a float division where the result is then assigned to a double. Since float division has less precision, you get the result you are seeing.

Title: Why Float error is different in C?

Body:
CGFloat is a double on your machine, therefore what you are doing is this:

double a = 100.00f
double price = 88888736 / a

float a2 = 100.00f // `float` type enforced by the trailing `f`
double price2 = 88888736 / a2

The difference is that in the first case the division is a double division while in the second case this is a float division where the result is then assigned to a double. Since float division has less precision, you get the result you are seeing.


问:
The "Modal" function in Flex is different from Java? Don't pause the thread of the parent component?
I'm beginner in Flex 4. I'm trying to pop up a Flex WindowTitle custom component, and after the user choose some values, the parent window must be refreshed.

I'm showing the modal window, the user can't interact with other components, but the problem I detect is the execution of the program flows, even I choosing to show the Input window as modal, the next methods to refresh the page is called before the user close the modal page. I don't know if flex or ActionScript works different from Java, where I used to code.

Please, see the comments on the code example:

```<code><fx:Script>
    <![CDATA[
        import mx.controls.Alert;
        import mx.core.FlexGlobals;
        import mx.managers.PopUpManager;

        public function add_clickHandler(event:MouseEvent):void
        {
            var frm: FrmNovaOpcao = new FrmNovaOpcao();//titleWindow

            //add modal window
            PopUpManager.addPopUp(frm, this, true);
            //center modal window
            PopUpManager.centerPopUp(frm);

            refreshAll(); //this method is being called before the user close the modal window =[

        }
    ]]>
</fx:Script>
</code>```

答:
I solved adding event handlers and callback functions to the modal windows.
I research and understood that flex is event driven, and prioritize the UI refresh, and don't work with threads.

Not bad to a UI driven technology.

```<code><fx:Script>
    <![CDATA[
        import mx.controls.Alert;
        import mx.core.FlexGlobals;
        import mx.managers.PopUpManager;

        protected function add_clickHandler(event:MouseEvent):void
        {
            var frm: FrmNovaOpcao = new FrmNovaOpcao();

            //add modal window
            PopUpManager.addPopUp(frm, this, true);
            //center modal window
            PopUpManager.centerPopUp(frm);

            frm.btnAdd.addEventListener(MouseEvent.CLICK, refreshOptions);

        }

        protected function refreshOptions(mousevent:MouseEvent):void{
             refreshAll();
        }
    ]]>
</code>```

Body:
I'm beginner in Flex 4. I'm trying to pop up a Flex WindowTitle custom component, and after the user choose some values, the parent window must be refreshed.

I'm showing the modal window, the user can't interact with other components, but the problem I detect is the execution of the program flows, even I choosing to show the Input window as modal, the next methods to refresh the page is called before the user close the modal page. I don't know if flex or ActionScript works different from Java, where I used to code.

Please, see the comments on the code example:

<fx:Script>
    <![CDATA[
        import mx.controls.Alert;
        import mx.core.FlexGlobals;
        import mx.managers.PopUpManager;

        public function add_clickHandler(event:MouseEvent):void
        {
            var frm: FrmNovaOpcao = new FrmNovaOpcao();//titleWindow

            //add modal window
            PopUpManager.addPopUp(frm, this, true);
            //center modal window
            PopUpManager.centerPopUp(frm);

            refreshAll(); //this method is being called before the user close the modal window =[

        }
    ]]>
</fx:Script>

Body:
I solved adding event handlers and callback functions to the modal windows.
I research and understood that flex is event driven, and prioritize the UI refresh, and don't work with threads.

Not bad to a UI driven technology.

<fx:Script>
    <![CDATA[
        import mx.controls.Alert;
        import mx.core.FlexGlobals;
        import mx.managers.PopUpManager;

        protected function add_clickHandler(event:MouseEvent):void
        {
            var frm: FrmNovaOpcao = new FrmNovaOpcao();

            //add modal window
            PopUpManager.addPopUp(frm, this, true);
            //center modal window
            PopUpManager.centerPopUp(frm);

            frm.btnAdd.addEventListener(MouseEvent.CLICK, refreshOptions);

        }

        protected function refreshOptions(mousevent:MouseEvent):void{
             refreshAll();
        }
    ]]>


问:
Copy Data from one Sqlite table to another Sqlite table
I need to copy data from one Sqlite table to another.
I wrote method, which return DataTable:

```<code>public static DataTable GetDataFromSecondTable(string filePath)
    {
        DataTable DbTable = new DataTable("Messages");
        using (var connection = new SQLiteConnection(filePath))
        {
            string SelectQuery = "SELECT * FROM Messages";
            using (SQLiteCommand cmd = new SQLiteCommand(SelectQuery, connection))
            {
                connection.Open();

                using (SQLiteDataAdapter adapter = new SQLiteDataAdapter(cmd))
                {
                    adapter.Fill(DbTable);
                }
            }
        }
        return DbTable;
    }
</code>```

Then I need to insert this DataTable to my "main" table, which has same structure:

```<code>public static void MergeData(string mainDbPath, string secondDbPath)
    {
        DataTable secondTable = GetDataFromSecondTable(secondDbPath);

        using(SQLiteConnection connect = new SQLiteConnection(mainDbPath))
        {
            connect.Open();
            using (var cmd = new SQLiteCommand(connect))
            {
                using (var transaction = connect.BeginTransaction())
                {
                    foreach(DataColumn column in secondTable.Columns)
                    {
                        foreach(DataRow row in secondTable.Rows)
                        {
                            //cmd.CommandText = String.Format("INSERT INTO Messages ('{0}') VALUES('{1}')", column.ColumnName, row);
                            cmd.ExecuteNonQuery();
                        }
                    }

                    transaction.Commit();
                }
            }
        }

    }
</code>```

I don't understand how I should set rows and columns to SQLite query. Maybe someone have another solution for this task.

答:
```<code>SQLiteCommand createCommand = sqlConnection.CreateCommand();
createCommand.CommandText = $"CREATE TABLE `{CopyTable}` AS SELECT * FROM `{SourceTable}`";
</code>```

Use this command, this will help you to make a copy of another table.
Copy table - new table name

Body:
I need to copy data from one Sqlite table to another.
I wrote method, which return DataTable:

public static DataTable GetDataFromSecondTable(string filePath)
    {
        DataTable DbTable = new DataTable("Messages");
        using (var connection = new SQLiteConnection(filePath))
        {
            string SelectQuery = "SELECT * FROM Messages";
            using (SQLiteCommand cmd = new SQLiteCommand(SelectQuery, connection))
            {
                connection.Open();

                using (SQLiteDataAdapter adapter = new SQLiteDataAdapter(cmd))
                {
                    adapter.Fill(DbTable);
                }
            }
        }
        return DbTable;
    }

Then I need to insert this DataTable to my "main" table, which has same structure:

public static void MergeData(string mainDbPath, string secondDbPath)
    {
        DataTable secondTable = GetDataFromSecondTable(secondDbPath);

        using(SQLiteConnection connect = new SQLiteConnection(mainDbPath))
        {
            connect.Open();
            using (var cmd = new SQLiteCommand(connect))
            {
                using (var transaction = connect.BeginTransaction())
                {
                    foreach(DataColumn column in secondTable.Columns)
                    {
                        foreach(DataRow row in secondTable.Rows)
                        {
                            //cmd.CommandText = String.Format("INSERT INTO Messages ('{0}') VALUES('{1}')", column.ColumnName, row);
                            cmd.ExecuteNonQuery();
                        }
                    }

                    transaction.Commit();
                }
            }
        }

    }

I don't understand how I should set rows and columns to SQLite query. Maybe someone have another solution for this task.

Body:
SQLiteCommand createCommand = sqlConnection.CreateCommand();
createCommand.CommandText = $"CREATE TABLE `{CopyTable}` AS SELECT * FROM `{SourceTable}`";

Use this command, this will help you to make a copy of another table.
Copy table - new table name


答:
Try this

```<code>if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
</code>```

and remove this android:fitsSystemWindows=”true” from XML

Title: How to change a status bar color in a Fragment page as Transparent in android

Body:
Try this

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }

and remove this android:fitsSystemWindows=”true” from XML


问:
Why does the size of the same identifier differ in C and C++?
```<code>#include <stdio.h>
int T;
int main()
{
    struct T { double x; };
    printf("%zu", sizeof(T));
    return 0;
}
</code>```

If I run this code in C, the result is 4, while in C++ it is 8.

Can someone explain why the difference?

答:
I believe in C to refer to the structure you would need to write struct T while in C++ since a struct is a public class it can be refered to as just T
So both are just taking the most local definition of T they have.

Body:
#include <stdio.h>
int T;
int main()
{
    struct T { double x; };
    printf("%zu", sizeof(T));
    return 0;
}

If I run this code in C, the result is 4, while in C++ it is 8.

Can someone explain why the difference?


问:
Partially deserialize json into POJO but keep some raw json as field
I have a json as follows:

```<code>"customer": {
     "personal": {
        "name": “jim johnson”,
        “miscellaneous”: {
            “active”: “true”,
            “addons”: {
              "location": “us”
            },
        “customer_id”: “1234”
        }
    },
    “source”: “main db”
}
</code>```

I can create an simple POJO mapping everything one to one but what I would like is the following:

I would like to have an object such as follows:

```<code>class Customer {
   Personal personal;
   String source;
}

class Personal {
    String name;
    String customer_id;
    String miscellaneous; // <—— This is the problem
    // JsonObject miscellaneous;
}
</code>```

How can I deserialize the json and have the miscellaneous kept as a string of raw json string? Or even have it as a raw json element?

答:
Because, as per your JSON miscellaneous isn't plain String.

```<code>    “miscellaneous”: {
        “active”: “true”,
        “addons”: {
          "location": “us”
        },
    “customer_id”: “1234”
    }
</code>```

You need to write a class and declare required property for miscellaneous

```<code>   public class Miscellaneous {
       private boolean active;
       private Addons addons;
       private String customerId;
     // getter and setter
    }
</code>```

And, then

```<code>String miscellaneous;
</code>```

should be change to

```<code>Miscellaneous miscellaneous;
</code>```

Body:
I have a json as follows:

"customer": {
     "personal": {
        "name": “jim johnson”,
        “miscellaneous”: {
            “active”: “true”,
            “addons”: {
              "location": “us”
            },
        “customer_id”: “1234”
        }
    },
    “source”: “main db”
}

I can create an simple POJO mapping everything one to one but what I would like is the following:

I would like to have an object such as follows:

class Customer {
   Personal personal;
   String source;
}

class Personal {
    String name;
    String customer_id;
    String miscellaneous; // <—— This is the problem
    // JsonObject miscellaneous;
}

How can I deserialize the json and have the miscellaneous kept as a string of raw json string? Or even have it as a raw json element?

Body:
Because, as per your JSON miscellaneous isn't plain String.

    “miscellaneous”: {
        “active”: “true”,
        “addons”: {
          "location": “us”
        },
    “customer_id”: “1234”
    }

You need to write a class and declare required property for miscellaneous

   public class Miscellaneous {
       private boolean active;
       private Addons addons;
       private String customerId;
     // getter and setter
    }

And, then

String miscellaneous;

should be change to

Miscellaneous miscellaneous;


答:
Short answer: Because they aren't the same identifier, in fact.

In C, structure names and variable names fall into different namespaces, so in C,

```<code>sizeof(T) == sizeof(int) // global variable T
sizeof(struct T) == sizeof(struct T) // not the same namespace
</code>```

In C++, however, structure/class names goes into the same namespace as variables. The "nearest" (most local) name is the result of name lookup, so now

```<code>sizeof(T) == sizeof(struct T) // structure T
sizeof(::T) == sizeof(int) // Note the scope resolution operator
</code>```

And therefore the result is 4 and 8, respectively.

In C++, you can get 4 with sizeof(::T). The "double-colon" scope resolution operator forces the compiler to take T as the name in external namespace, so ::T is the variable of type int that you want.

In C, (structures/unions/enums) and (variables/functions/typedefs) have separate namespaces, so you can write this without worrying about names conflicting.

```<code>struct T T;
</code>```

note the parentheses, that structs, unions and enums share one namespace while the other three share another.

If you try to do this in C++, you'll immediately run into problems.

I like hacck's comment. He got the point that the fundamental reason is that C and C++ are different languages, despite their similarity.

Title: Why does the size of the same identifier differ in C and C++?

Body:
Short answer: Because they aren't the same identifier, in fact.

In C, structure names and variable names fall into different namespaces, so in C,

sizeof(T) == sizeof(int) // global variable T
sizeof(struct T) == sizeof(struct T) // not the same namespace

In C++, however, structure/class names goes into the same namespace as variables. The "nearest" (most local) name is the result of name lookup, so now

sizeof(T) == sizeof(struct T) // structure T
sizeof(::T) == sizeof(int) // Note the scope resolution operator

And therefore the result is 4 and 8, respectively.

In C++, you can get 4 with sizeof(::T). The "double-colon" scope resolution operator forces the compiler to take T as the name in external namespace, so ::T is the variable of type int that you want.

In C, (structures/unions/enums) and (variables/functions/typedefs) have separate namespaces, so you can write this without worrying about names conflicting.

struct T T;

note the parentheses, that structs, unions and enums share one namespace while the other three share another.

If you try to do this in C++, you'll immediately run into problems.

I like hacck's comment. He got the point that the fundamental reason is that C and C++ are different languages, despite their similarity.


问:
X509Certificate - Keyset does not exist
I have a WinForms application that consumes a WCF, and pass as a parameter to a function a certificate:

```<code>mySvcClient.SendDocument(cert.Export(X509ContentType.SerializedCert, "password"));
...
</code>```

In WCF service, I recreated the certificate from the array of bytes:

```<code>public void SendDocument (byte[] binaryCert)
{
     X509Certificate2 cert = new X509Certificate2(binaryCert, "password");
...
</code>```

But when using the certificate to sign a xml, I got the error "Keyset does not exist":

```<code>if (cert.HasPrivateKey) // WORKS!!!
{
    signedXml.SigningKey = cert.PrivateKey; // THROW "keyset does not exist" EXCEPTION
...
</code>```

In my computer, the application works 100%! But in the WebServer, I got this error!

The question is: even X509Certificate2 recreated from an array of bytes, I need some special permission to access private key?

Thank you!

答:
Application Pool Identity accounts don't have access to the certificate store by default.

Either you change to Network Services account as pointed  by Vaibhav.Inspired or you give access to the certificate.

To allow access do the following command:

WinHttpCertCfg.exe -g -c LOCAL_MACHINE\MY -s "IssuedToName" -a
  "AccountName"

Notes:

```<code>- The tool may need to be installed first. The setup will place the tool at `C:\Program Files (x86)\Windows Resource Kits\Tools\WinHttpCertCfg.exe`.
- `IssuedName` is the issuer property of the certificate that the application will attempt to access
- The command must be run from command prompt with elevated privileges
</code>```

Reference :https://support.microsoft.com/en-us/help/901183/how-to-call-a-web-service-by-using-a-client-certificate-for-authentica  Step 2

Also you need to enable the Mark this key as exportable option when installing the certificate.

Title: X509Certificate - Keyset does not exist

Body:
I have a WinForms application that consumes a WCF, and pass as a parameter to a function a certificate:

mySvcClient.SendDocument(cert.Export(X509ContentType.SerializedCert, "password"));
...

In WCF service, I recreated the certificate from the array of bytes:

public void SendDocument (byte[] binaryCert)
{
     X509Certificate2 cert = new X509Certificate2(binaryCert, "password");
...

But when using the certificate to sign a xml, I got the error "Keyset does not exist":

if (cert.HasPrivateKey) // WORKS!!!
{
    signedXml.SigningKey = cert.PrivateKey; // THROW "keyset does not exist" EXCEPTION
...

In my computer, the application works 100%! But in the WebServer, I got this error!

The question is: even X509Certificate2 recreated from an array of bytes, I need some special permission to access private key?

Thank you!

Body:
Application Pool Identity accounts don't have access to the certificate store by default.

Either you change to Network Services account as pointed  by Vaibhav.Inspired or you give access to the certificate.

To allow access do the following command:

WinHttpCertCfg.exe -g -c LOCAL_MACHINE\MY -s "IssuedToName" -a
  "AccountName"

Notes:

- The tool may need to be installed first. The setup will place the tool at `C:\Program Files (x86)\Windows Resource Kits\Tools\WinHttpCertCfg.exe`.
- `IssuedName` is the issuer property of the certificate that the application will attempt to access
- The command must be run from command prompt with elevated privileges

Reference :https://support.microsoft.com/en-us/help/901183/how-to-call-a-web-service-by-using-a-client-certificate-for-authentica  Step 2

Also you need to enable the Mark this key as exportable option when installing the certificate.


问:
C++ modulus small program issue
I'm trying to write a very simple program in C++ that finds the modulus of two numbers as follows:

```<code>#include <iostream>
using namespace std;
int n;
int d;
int modulus;
int main()
{
cout<<"***Welcome to the MODULUS calculator***";
cout<<"Enter the numerator, then press ENTER: ";
cin>>n;
cout<<"Enter the denominator, then press ENTER: ";
cin>>d;
modulus=n%d;
cout<<"The modulus is ---> "<<modulus;
return 0;
}
</code>```

But, when I try to compile it, I get the following:

How can this be solved?

Thanks.

答:
You get the error because the name of your global variable modulus clashes with std::modulus. To fix this, you can:

Make modulus a local variable

Rename the modulus variable

Remove using namespace std and either import the names you need from std individually or qualify them with std::

Title: C++ modulus small program issue

Body:
I'm trying to write a very simple program in C++ that finds the modulus of two numbers as follows:

#include <iostream>
using namespace std;
int n;
int d;
int modulus;
int main()
{
cout<<"***Welcome to the MODULUS calculator***";
cout<<"Enter the numerator, then press ENTER: ";
cin>>n;
cout<<"Enter the denominator, then press ENTER: ";
cin>>d;
modulus=n%d;
cout<<"The modulus is ---> "<<modulus;
return 0;
}

But, when I try to compile it, I get the following:

How can this be solved?

Thanks.


问:
Render a new line from a text interpolation in Angular 4 / Ionic 3
I have the following front code:

```<code><p>{{ news.content }}</p>
</code>```

news.content is stored in my firebase DB.

How can I render a new line in this text interpolation without modifying my front code (nor HTML nor CSS)? I will eventually change my front code if needed but I need I quick backend fix because my app is in prod and I cannot not provide an update within the day...

So I tried \n,
 and
 but none is working...

When I inspect the view, HTML is as follows:

```<code><p>"my text"</p>
</code>```

So I guess the pain point comes from the double quotes...

Just for you to know, I need this to work on the iOS build.

答:
If I understood, you want to be able to render a new line, thanks to the object you gor from your component.

So I think you shoud use [innerHTML] of Angular and the
 tag (https://angular.io/guide/template-syntax#!#property-binding-or-interpolation-) :

app.component.ts

```<code>export class AppComponent{
    sometext = 'some text';
    anothertext = '<br>new line here';
   ...
}
</code>```

app.component.html

```<code><p>{{sometext}} and <span [innerHTML]="anothertext"></span></p>
</code>```

Body:
I have the following front code:

{{ news.content }}

news.content is stored in my firebase DB.

How can I render a new line in this text interpolation without modifying my front code (nor HTML nor CSS)? I will eventually change my front code if needed but I need I quick backend fix because my app is in prod and I cannot not provide an update within the day...

So I tried \n,
 and
 but none is working...

When I inspect the view, HTML is as follows:

"my text"

So I guess the pain point comes from the double quotes...

Just for you to know, I need this to work on the iOS build.

Body:
If I understood, you want to be able to render a new line, thanks to the object you gor from your component.

So I think you shoud use [innerHTML] of Angular and the <br> tag (https://angular.io/guide/template-syntax#!#property-binding-or-interpolation-) :

app.component.ts

export class AppComponent{
    sometext = 'some text';
    anothertext = '<br>new line here';
   ...
}

app.component.html

<p>{{sometext}} and <span [innerHTML]="anothertext"></span></p>


问:
How to compare stored date and time with SimpleDateFormat and display notification?
In my application I want to display the notification based on the time that user have already set and I am storing the Date and Time into local database.

I am getting the Date and Time from Local database and comparing with SimpleDateFormat and parsing with  Date like this

```<code>SimpleDateFormat yourDateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm");
Date date = null;
     try {
          String date_time = "17-11-2017 15:10";
          date = yourDateFormat.parse(date_time);

     } catch (ParseException e) {
          Log.e(TAG, "Parsing date time failed", e);
     }
     Calendar calendar = Calendar.getInstance();
     calendar.setTime(date);

     Calendar current = Calendar.getInstance();
     if (calendar.compareTo(current) <= 0) {

        Toast.makeText(getApplicationContext(), "Invalid Date/Time", Toast.LENGTH_LONG).show();
     } else {
          AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
          Intent myIntent = new Intent(RemainderActivity.this, NotificationReceiver.class);
          PendingIntent displayIntent = PendingIntent.getBroadcast(getBaseContext(), 0, myIntent, 0);
          alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), displayIntent);

    }
</code>```

Some devices it is working fine like above 7.0 android version but below 7.0 versions it is showing java.lang.NullPointerException like this

```<code> Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.Date java.text.SimpleDateFormat.parse(java.lang.String)' on a null object reference
</code>```

and the error is showing here date = yourDateFormat.parse(date_time);.

Please help me out.

Thanks in Advance.

答:
Ok then problem is changed here is your new solution:

Before this:

```<code>Calendar calendar = Calendar.getInstance();
     calendar.setTime(date);
</code>```

Add:

```<code>Locale locale = new Locale("en","US")
</code>```

and then replace:

```<code>Calendar calendar = Calendar.getInstance();
</code>```

with:

```<code>Calendar calendar = Calendar.getInstance(locale);
</code>```

So it looks like this:

```<code>Locale locale = new Locale("en","US")
Calendar calendar = Calendar.getInstance(locale);
calendar.setTime(date);
</code>```

Your whole code you provided will be like :

```<code>SimpleDateFormat yourDateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm");
Date date = null;
 try {
      String date_time = "17-11-2017 15:10";
      date = yourDateFormat.parse(date_time);

 } catch (ParseException e) {
      Log.e(TAG, "Parsing date time failed", e);
 }
 Locale locale = new Locale("en","US")
 Calendar calendar = Calendar.getInstance(locale);
 calendar.setTime(date);

 Calendar current = Calendar.getInstance();
 if (calendar.compareTo(current) <= 0) {

    Toast.makeText(getApplicationContext(), "Invalid Date/Time", Toast.LENGTH_LONG).show();
 } else {
      AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
      Intent myIntent = new Intent(RemainderActivity.this, NotificationReceiver.class);
      PendingIntent displayIntent = PendingIntent.getBroadcast(getBaseContext(), 0, myIntent, 0);
      alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), displayIntent);

}
</code>```

Body:
In my application I want to display the notification based on the time that user have already set and I am storing the Date and Time into local database.

I am getting the Date and Time from Local database and comparing with SimpleDateFormat and parsing with  Date like this

SimpleDateFormat yourDateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm");
Date date = null;
     try {
          String date_time = "17-11-2017 15:10";
          date = yourDateFormat.parse(date_time);

     } catch (ParseException e) {
          Log.e(TAG, "Parsing date time failed", e);
     }
     Calendar calendar = Calendar.getInstance();
     calendar.setTime(date);

     Calendar current = Calendar.getInstance();
     if (calendar.compareTo(current) <= 0) {

        Toast.makeText(getApplicationContext(), "Invalid Date/Time", Toast.LENGTH_LONG).show();
     } else {
          AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
          Intent myIntent = new Intent(RemainderActivity.this, NotificationReceiver.class);
          PendingIntent displayIntent = PendingIntent.getBroadcast(getBaseContext(), 0, myIntent, 0);
          alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), displayIntent);

    }

Some devices it is working fine like above 7.0 android version but below 7.0 versions it is showing java.lang.NullPointerException like this

 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.Date java.text.SimpleDateFormat.parse(java.lang.String)' on a null object reference

and the error is showing here date = yourDateFormat.parse(date_time);.

Please help me out.

Thanks in Advance.

Body:
Ok then problem is changed here is your new solution:

Before this:

Calendar calendar = Calendar.getInstance();
     calendar.setTime(date);

Add:

Locale locale = new Locale("en","US")

and then replace:

Calendar calendar = Calendar.getInstance();

with:

Calendar calendar = Calendar.getInstance(locale);

So it looks like this:

Locale locale = new Locale("en","US")
Calendar calendar = Calendar.getInstance(locale);
calendar.setTime(date);

Your whole code you provided will be like :

SimpleDateFormat yourDateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm");
Date date = null;
 try {
      String date_time = "17-11-2017 15:10";
      date = yourDateFormat.parse(date_time);

 } catch (ParseException e) {
      Log.e(TAG, "Parsing date time failed", e);
 }
 Locale locale = new Locale("en","US")
 Calendar calendar = Calendar.getInstance(locale);
 calendar.setTime(date);

 Calendar current = Calendar.getInstance();
 if (calendar.compareTo(current) <= 0) {

    Toast.makeText(getApplicationContext(), "Invalid Date/Time", Toast.LENGTH_LONG).show();
 } else {
      AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
      Intent myIntent = new Intent(RemainderActivity.this, NotificationReceiver.class);
      PendingIntent displayIntent = PendingIntent.getBroadcast(getBaseContext(), 0, myIntent, 0);
      alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), displayIntent);

}


答:
You are getting different results because C and C++ are different languages.

In C++, when you declare a struct (a special class),

```<code>struct T {
    double x;
};
</code>```

then you can use it as

```<code>T sobj;  // sobj is an object of type T
</code>```

T is a type here.
while in C, T is not a type but struct T is

```<code>struct T sobj;
</code>```

Now use sizeof(T) or sizeof(struct T) in C++ and sizeof(struct T) in C and they will give you the size of struct.

Body:
You are getting different results because C and C++ are different languages.

In C++, when you declare a struct (a special class),

struct T {
    double x;
};

then you can use it as

T sobj;  // sobj is an object of type T

T is a type here.
while in C, T is not a type but struct T is

struct T sobj;

Now use sizeof(T) or sizeof(struct T) in C++ and sizeof(struct T) in C and they will give you the size of struct.