问:
how to remove xml namesapce with SAX parser
I need to do xml transformation with SAX parser, for that i need to remove namespace from the xml. Since we are handling with huge xml, i need to use SAX parser.

sample input xml:

```<code><root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENV="http://www.w3.org/2003/05/soap-envelope"
 xmlns:ns2="http://www.google.com/generation/type">
    <ns2:meta>
        <gender xmlns="" xmlns:ns5="http://www.google.com/generation">M</gender>
        <dateOfBirth xmlns="" xmlns:ns5="http://www.google.com/generation">1976-07-19</dateOfBirth>
        <ns2:languageRef>ENG</ns2:languageRef>
    </ns2:meta>
    <root>
</code>```

with the help of SAX parser, i need the below output.

```<code>       <root>
            <meta>
                <gender>M</gender>
                <dateOfBirth>1976-07-19</dateOfBirth>
                <languageRef>ENG</languageRef>
            </ns2:meta>
        <root>
</code>```

Thanks in advance..

The code which i tried,

i tried with XMLFlterImpl,

```<code>XMLReader xr = new XMLFilterImpl(XMLReaderFactory.createXMLReader()) {

  @Override
  public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {

    if (qName.contains(":")) {
      String[] data = data = qName.split(":");

      super.startElement(uri, localName, data[1], atts);
    } else {
      super.startElement(uri, localName, qName, atts);
    }
  }
</code>```

this removes the element name prefix(namespace), but not sure how to remove the namespace attributes

答:
EDIT:

Ok, with direction from comments from @MichaelKay, here is my updated answer.

To remove namespace from tags:

As suggested in his answer, the startElement should have "" in place of uri. What about Ending tag ?:
In your question I don't understand why you want ns2 for ending meta tag particularly when you want to remove it for the starting tag.
I assume you want it to be removed for ending tag too. So similarly endElement should also have "" in place of uri.

Filter XMLNS attributes:

You could create a new AttributesImpl. Then go through the list of attributes and check if the QName starts with xmlns, if not add it to the AttributesImpl and use it in the startElement as :

super.startElement("", localName, data[1], aImpl);

Also note that as per @MartinHonnen, yes the attributes' uri should also be "" and also the qName should be without prefix as with elements. But if you want to keep the attributes' names as such ( which I don't think you want to ) you can just keep atts.getQName(i) as is.

Also set Namespaces feature to false like :

xf.setFeature("http://xml.org/sax/features/namespaces", false);

Code :

```<code>try {

   InputSource file = new InputSource("filterns.xml");

   XMLFilterImpl xf = new XMLFilterImpl(
           XMLReaderFactory.createXMLReader()) {
       @Override
       public void startElement(String uri, String localName,
           String qName, Attributes atts) throws SAXException {

               AttributesImpl aImpl = new AttributesImpl();

                int l = atts.getLength();
                for (int i = 0; i < l; i++) {

                    if (atts.getQName(i) != null
                            && atts.getQName(i).startsWith("xmlns")) {
                        continue;
                    } else {
                        String aQName = atts.getQName(i);
                        String[] s = aQName.split(":");
                        if (s.length > 1) {
                            aQName = s[1];
                        }

                        aImpl.addAttribute("",
                                atts.getLocalName(i), aQName,
                                atts.getType(i), atts.getValue(i));
                    }

                }

                String[] s = qName.split(":");
                if (s.length > 1) {
                    super.startElement("", localName, s[1], aImpl);
                } else {
                    super.startElement("", localName, qName, aImpl);
                }

       }

       @Override
       public void endElement(String uri, String localName,
              String qName) throws SAXException {

              String[] s = qName.split(":");
              if (s.length > 1) {
                 super.endElement("", localName, s[1]);
               } else {
                  super.endElement("", localName, qName);
                 }

       }

       @Override
       public void startPrefixMapping(String prefix, String uri) {
       }

   };

   xf.setFeature("http://xml.org/sax/features/namespaces", false);
   SAXSource src = new SAXSource(xf, file);

   StringWriter stringWriter = new StringWriter();
   TransformerFactory transformerFactory = TransformerFactory
           .newInstance();
   Transformer transformer = transformerFactory.newTransformer();
   transformer.setOutputProperty(OutputKeys.INDENT, "yes");
   transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,"yes");
   transformer.transform(src, new StreamResult(stringWriter));

   String xml = stringWriter.toString();
   System.out.println(xml);

} catch (Exception e) {
   e.printStackTrace();
}
</code>```

Body:
I need to do xml transformation with SAX parser, for that i need to remove namespace from the xml. Since we are handling with huge xml, i need to use SAX parser.

sample input xml:

<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENV="http://www.w3.org/2003/05/soap-envelope"
 xmlns:ns2="http://www.google.com/generation/type">
    <ns2:meta>
        <gender xmlns="" xmlns:ns5="http://www.google.com/generation">M</gender>
        <dateOfBirth xmlns="" xmlns:ns5="http://www.google.com/generation">1976-07-19</dateOfBirth>
        <ns2:languageRef>ENG</ns2:languageRef>
    </ns2:meta>
    <root>

with the help of SAX parser, i need the below output.

       <root>
            <meta>
                <gender>M</gender>
                <dateOfBirth>1976-07-19</dateOfBirth>
                <languageRef>ENG</languageRef>
            </ns2:meta>
        <root>

Thanks in advance..

The code which i tried,

i tried with XMLFlterImpl,

XMLReader xr = new XMLFilterImpl(XMLReaderFactory.createXMLReader()) {

  @Override
  public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {

    if (qName.contains(":")) {
      String[] data = data = qName.split(":");

      super.startElement(uri, localName, data[1], atts);
    } else {
      super.startElement(uri, localName, qName, atts);
    }
  }

this removes the element name prefix(namespace), but not sure how to remove the namespace attributes

Body:
EDIT:

Ok, with direction from comments from @MichaelKay, here is my updated answer.

To remove namespace from tags:

As suggested in his answer, the startElement should have "" in place of uri. What about Ending tag ?:
In your question I don't understand why you want ns2 for ending meta tag particularly when you want to remove it for the starting tag.
I assume you want it to be removed for ending tag too. So similarly endElement should also have "" in place of uri.

Filter XMLNS attributes:

You could create a new AttributesImpl. Then go through the list of attributes and check if the QName starts with xmlns, if not add it to the AttributesImpl and use it in the startElement as :

super.startElement("", localName, data[1], aImpl);

Also note that as per @MartinHonnen, yes the attributes' uri should also be "" and also the qName should be without prefix as with elements. But if you want to keep the attributes' names as such ( which I don't think you want to ) you can just keep atts.getQName(i) as is.

Also set Namespaces feature to false like :

xf.setFeature("http://xml.org/sax/features/namespaces", false);

Code :

try {

   InputSource file = new InputSource("filterns.xml");

   XMLFilterImpl xf = new XMLFilterImpl(
           XMLReaderFactory.createXMLReader()) {
       @Override
       public void startElement(String uri, String localName,
           String qName, Attributes atts) throws SAXException {

               AttributesImpl aImpl = new AttributesImpl();

                int l = atts.getLength();
                for (int i = 0; i < l; i++) {

                    if (atts.getQName(i) != null
                            && atts.getQName(i).startsWith("xmlns")) {
                        continue;
                    } else {
                        String aQName = atts.getQName(i);
                        String[] s = aQName.split(":");
                        if (s.length > 1) {
                            aQName = s[1];
                        }

                        aImpl.addAttribute("",
                                atts.getLocalName(i), aQName,
                                atts.getType(i), atts.getValue(i));
                    }

                }

                String[] s = qName.split(":");
                if (s.length > 1) {
                    super.startElement("", localName, s[1], aImpl);
                } else {
                    super.startElement("", localName, qName, aImpl);
                }

       }

       @Override
       public void endElement(String uri, String localName,
              String qName) throws SAXException {

              String[] s = qName.split(":");
              if (s.length > 1) {
                 super.endElement("", localName, s[1]);
               } else {
                  super.endElement("", localName, qName);
                 }

       }

       @Override
       public void startPrefixMapping(String prefix, String uri) {
       }

   };

   xf.setFeature("http://xml.org/sax/features/namespaces", false);
   SAXSource src = new SAXSource(xf, file);

   StringWriter stringWriter = new StringWriter();
   TransformerFactory transformerFactory = TransformerFactory
           .newInstance();
   Transformer transformer = transformerFactory.newTransformer();
   transformer.setOutputProperty(OutputKeys.INDENT, "yes");
   transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,"yes");
   transformer.transform(src, new StreamResult(stringWriter));

   String xml = stringWriter.toString();
   System.out.println(xml);

} catch (Exception e) {
   e.printStackTrace();
}


来源: stackexchange

问:
Check if a pointer points to a valid structure
I have N statically allocated structures.

```<code>struct exemple{
     ...
}

struct exemple array[N];
struct exemple *test_ptr = 0x3; /* random address */
</code>```

Can I check if test_prt points to a valid address? i.e. it points to one "struct example" allocated.

答:
I don't know if I get your question properly.

If you want to know if a pointer points to a struct of some type (cast my structs to void * and vice-versa, for example), I do the next way:

```<code>#include <assert.h>
struct my_struct {
#ifndef NDEBUG
#define MY_STRUCT_MAGIC 0x1234abcd
  uint64_t magic;
#endif
  int my_data;
};

void init_struct(struct my_struct *s, int t_data) {
#ifdef MY_STRUCT_MAGIC
  s->magic = MY_STRUCT_MAGIC;
#endif
  s->my_data = t_data;
}

my_struct *my_struct_cast(void *vs) {
  my_struct *s = vs;
#ifdef MY_STRUCT_MAGIC
  assert(MY_STRUCT_MAGIC == s->magic);
#endif
  return s;
}
</code>```

It has a little bit more code because of inclusion of const-casting, but I think you get the idea.

If you want to know if test_ptr points to a aray member, you have to check this way: test_ptr >= array && test_ptr < &array[sizeof(array)/sizeof(array[0])]). If the pointer comes from void, char, or some kind of dangerout ariyhmetic, you could also check for test_ptr % sizeof(array[0])

If you want to know if a pointer points to valid memory "ever allocated" by your program, you will have to intercept allocs functions, save returned chunks pointer & size, and compute like the previous example.

ContentLicense: CC BY-SA 3.0

Body:
I have N statically allocated structures.

struct exemple{
     ...
}

struct exemple array[N];
struct exemple *test_ptr = 0x3; /* random address */

Can I check if test_prt points to a valid address? i.e. it points to one "struct example" allocated.

Body:
I don't know if I get your question properly.

If you want to know if a pointer points to a struct of some type (cast my structs to void * and vice-versa, for example), I do the next way:

#include <assert.h>
struct my_struct {
#ifndef NDEBUG
#define MY_STRUCT_MAGIC 0x1234abcd
  uint64_t magic;
#endif
  int my_data;
};

void init_struct(struct my_struct *s, int t_data) {
#ifdef MY_STRUCT_MAGIC
  s->magic = MY_STRUCT_MAGIC;
#endif
  s->my_data = t_data;
}

my_struct *my_struct_cast(void *vs) {
  my_struct *s = vs;
#ifdef MY_STRUCT_MAGIC
  assert(MY_STRUCT_MAGIC == s->magic);
#endif
  return s;
}

It has a little bit more code because of inclusion of const-casting, but I think you get the idea.

If you want to know if test_ptr points to a aray member, you have to check this way: test_ptr >= array && test_ptr < &array[sizeof(array)/sizeof(array[0])]). If the pointer comes from void, char, or some kind of dangerout ariyhmetic, you could also check for test_ptr % sizeof(array[0])

If you want to know if a pointer points to valid memory "ever allocated" by your program, you will have to intercept allocs functions, save returned chunks pointer & size, and compute like the previous example.


问:
Change Java version for Tomcat running from Netbeans when invoked
I have a set of projects under Netbeans that run on Java 1.7; I am starting one that depends on having Java 1.8. It is a web app, and both Netbeans and the Tomcat server that is configured under Netbeans need to run on 8 for the latter project, but cannot run on 8 for any of the former projects.

I was hoping to create a bat file or something that would allow me to specify the Java version for both Netbeans and the Tomcat that runs under Netbeans.

I found the command line argument for setting the jdkhome for Netbeans; that works for Netbeans. But the JDK configured for the server appears to be a Netbeans setting, and I don't know how to change that at the time that I invoke Netbeans, or with an environment variable (I tried JAVA_HOME, that didn't work).

Does anyone know how/whether this can be done?

答:
Open netbeans IDE and go to Tools-->Servers

Then Select your server (tomcat) and on platform tab select your JDK version and lick on close button.

if Your JAVA platform is not listed in combo box click on Manage Platforms and add new JAVA Paltform.


问:
Code swap. How would I swap the value of one CSV file column to another?
I have two CSV files. The first file(state_abbreviations.csv) has only states abbreviations and their full state names side by side(like the image below), the second file(test.csv) has the state abbreviations with additional info.

I want to replace each state abbreviation in test.csv with its associated state full name from the first file.

My approach was to read reach file, built a dict of the first file(state_abbreviations.csv). Read the second file(test.csv), then compare if an abbreviation matches the first file, if so replace it with the full name.

Any help is appreacited

```<code>import csv

state_initials = ("state_abbr")
state_names = ("state_name")
state_file = open("state_abbreviations.csv","r")
state_reader = csv.reader(state_file)

headers = None
final_state_initial= []
for row in state_reader:
    if not headers:
        headers = []
        for i, col in enumerate(row):
           if col in state_initials:
            headers.append(i)
    else:
        final_state_initial.append((row[0]))

print final_state_initial

headers = None
final_state_abbre= []
for row in state_reader:
    if not headers:
        headers = []
        for i, col in enumerate(row):
           if col in state_initials:
            headers.append(i)
    else:
        final_state_abbre.append((row[1]))

print final_state_abbre

final_state_initial
final_state_abbre
state_dictionary = dict(zip(final_state_initial, final_state_abbre))
print state_dictionary
</code>```

答:
It seems like you are trying to go through the file twice? This is absolutely not necessary: the first time you go through you are already reading all the lines, so you can then create your dictionary items directly.

In addition, comprehension can be very useful when creating lists or dictionaries. In this case it might be a bit less readable though. The alternative would be to create an empty dictionary, start a "real" for-loop and adding all the key:value pairs manually. (i.e: with state_dict[row[abbr]] = row[name])

Finally, I used the with statement when opening the file to ensure it is safely closed when we're done with it. This is good practice when opening files.

```<code>import csv

with open("state_abbreviations.csv") as state_file:
    state_reader = csv.DictReader(state_file)
    state_dict = {row['state_abbr']: row['state_name'] for row in state_reader}

print(state_dict)
</code>```

Edit: note that, like the code you showed, this only creates the dictionary that maps abbreviations to state names. Actually replacing them in the second file would be the next step.

Body:
I have two CSV files. The first file(state_abbreviations.csv) has only states abbreviations and their full state names side by side(like the image below), the second file(test.csv) has the state abbreviations with additional info.

I want to replace each state abbreviation in test.csv with its associated state full name from the first file.

My approach was to read reach file, built a dict of the first file(state_abbreviations.csv). Read the second file(test.csv), then compare if an abbreviation matches the first file, if so replace it with the full name.

Any help is appreacited

import csv

state_initials = ("state_abbr")
state_names = ("state_name")
state_file = open("state_abbreviations.csv","r")
state_reader = csv.reader(state_file)

headers = None
final_state_initial= []
for row in state_reader:
    if not headers:
        headers = []
        for i, col in enumerate(row):
           if col in state_initials:
            headers.append(i)
    else:
        final_state_initial.append((row[0]))

print final_state_initial

headers = None
final_state_abbre= []
for row in state_reader:
    if not headers:
        headers = []
        for i, col in enumerate(row):
           if col in state_initials:
            headers.append(i)
    else:
        final_state_abbre.append((row[1]))

print final_state_abbre

final_state_initial
final_state_abbre
state_dictionary = dict(zip(final_state_initial, final_state_abbre))
print state_dictionary

Body:
It seems like you are trying to go through the file twice? This is absolutely not necessary: the first time you go through you are already reading all the lines, so you can then create your dictionary items directly.

In addition, comprehension can be very useful when creating lists or dictionaries. In this case it might be a bit less readable though. The alternative would be to create an empty dictionary, start a "real" for-loop and adding all the key:value pairs manually. (i.e: with state_dict[row[abbr]] = row[name])

Finally, I used the with statement when opening the file to ensure it is safely closed when we're done with it. This is good practice when opening files.

import csv

with open("state_abbreviations.csv") as state_file:
    state_reader = csv.DictReader(state_file)
    state_dict = {row['state_abbr']: row['state_name'] for row in state_reader}

print(state_dict)

Edit: note that, like the code you showed, this only creates the dictionary that maps abbreviations to state names. Actually replacing them in the second file would be the next step.


问:
chef clients never check-in to chef server
We have setup a chef server and now when I try to register a client via the command listed below. The client shows up in the chef server portal but does not seems to check-in or does not show any client related information.</p>

```<code>knife bootstrap  10.0.34.24 -x ec2-user --sudo -i ~/.ssh/mmc_Dev.pem \
  -N mmcshibboleth -r 'role[infra], role[sudorules]'
</code>```

答:
I was able to get the issue resolved by adding chef server IP address and hostname into /etc/hosts file of the client.

After which tried bootstrapping from Chef workstation and everything worked as expected.

Thanks,

Body:
We have setup a chef server and now when I try to register a client via the command listed below. The client shows up in the chef server portal but does not seems to check-in or does not show any client related information.

knife bootstrap  10.0.34.24 -x ec2-user --sudo -i ~/.ssh/mmc_Dev.pem \
  -N mmcshibboleth -r 'role[infra], role[sudorules]'


问:
Slide element 100% up and all subsequent siblings by the same amount?
Consider this document:

```<code><div id="container" class="no-panel">
  <div id="panel">
    <!-- Can be any DOM with arbitrary, variable height.
         120px is hardcoded only for the demo. -->
    <div style="height: 120px">Some Contents</div>
  </div>
  <div id="contents">
    <!-- Can be any DOM with arbitrary, variable height.
         300px is hardcoded only for the demo. -->
    <div style="height: 300px">Some Contents</div>
  </div>
</div>
</code>```

Both #panel and #contents are supposed to be as tall as their contents, and not more (in the example I forced their height using arbitrary child div's - just  for the demo).

I want to apply a class to #container that will make #panel slide all the way up (so it becomes invisible behind the top border of the viewport). At the same time, #contents should slide up by the same amount #panel did. I like that to be animated too (in the demo I used :hover instead of the class).

How can I do that without using JS? It has to work in Chrome / Firefox, but I don't care about other browsers.

I tried setting translateY(-100%), which works fine on #panel, but then #contents would move 100% relative to its height, not to #panel's height, which is way too much.

Absolute positioning wouldn't work as then I'd need to fix the height of #panel which I'm trying not to do (it's contents are supposed to vary).

JSFiddle with an example on how I'd like it to work. - but with hardcoded value which I don't want.

答:
The trick is putting #contents inside #panel, and using position: absolute to position it at the bottom edge of the #panel div.

```<code><div id="container" class="no-panel">
  <div id="panel">
    <div>text</div>
    <div id="contents">
      <div>text</div>
    </div>
  </div>
</div>

#container {
  height: 100vh;
  overflow: hidden;
}

#panel:hover {
  transform: translateY(-100%);
}

#panel {
  background: orange;
  transition: 0.25s;
  position: relative;
}

#contents {
  background: brown;
  position: absolute;
  top: 100%;
}
</code>```

working fiddle

edit: @kalsowerus has a similar but probably little bit better approach posted in the comments, which doesn't require nesting the elements.

Body:
Consider this document:

Some Contents

Some Contents

Both #panel and #contents are supposed to be as tall as their contents, and not more (in the example I forced their height using arbitrary child div's - just  for the demo).

I want to apply a class to #container that will make #panel slide all the way up (so it becomes invisible behind the top border of the viewport). At the same time, #contents should slide up by the same amount #panel did. I like that to be animated too (in the demo I used :hover instead of the class).

How can I do that without using JS? It has to work in Chrome / Firefox, but I don't care about other browsers.

I tried setting translateY(-100%), which works fine on #panel, but then #contents would move 100% relative to its height, not to #panel's height, which is way too much.

Absolute positioning wouldn't work as then I'd need to fix the height of #panel which I'm trying not to do (it's contents are supposed to vary).

JSFiddle with an example on how I'd like it to work. - but with hardcoded value which I don't want.

Body:
The trick is putting #contents inside #panel, and using position: absolute to position it at the bottom edge of the #panel div.

<div id="container" class="no-panel">
  <div id="panel">
    <div>text</div>
    <div id="contents">
      <div>text</div>
    </div>
  </div>
</div>

#container {
  height: 100vh;
  overflow: hidden;
}

#panel:hover {
  transform: translateY(-100%);
}

#panel {
  background: orange;
  transition: 0.25s;
  position: relative;
}

#contents {
  background: brown;
  position: absolute;
  top: 100%;
}

working fiddle

edit: @kalsowerus has a similar but probably little bit better approach posted in the comments, which doesn't require nesting the elements.


问:
as.h2o skips part of my original (large) R dataframe without error
I am trying to convert larger data.frames consisting of round about 70 numerical columns and one character column to h2o objects.
There is no error message but it only converts a fraction of the data frame and skips the rest (i.e. the number of rows of the resulting h2o object is much lower than the one of the original data frame)
Has anybody an advice?

Here an example (I build an example data frame similar to the one I am trying to analyze in my study.)

```<code>nameDF <- c(paste("O",letters, sep="_"),  paste("T",letters, sep="_"),
   paste("TR",letters, sep="_"))
DF <- matrix( data=numeric(length(nameDF)*1000000), nrow=1000000)
colnames(DF) <- nameDF
DF <- as.data.frame(DF)
DF$char <- rep("bla", 1000000)
DFh2o <- as.h2o(DF)
dim(DFh2o)
dim(DF)
</code>```

答:
I tried the relatively recent H2O 3.10.4.8, ran your code sample, and the behavior of the two dims looks like the correct behavior to me.</p>

```<code>> library(h2o)
> h2o.init()

H2O is not running yet, starting it now...

Note:  In case of errors look at the following log files:
    /var/folders/tt/g5d7cr8d3fg84jmb5jr9dlrc0000gn/T//RtmpCXcmAu/h2o_tomk_started_from_r.out
    /var/folders/tt/g5d7cr8d3fg84jmb5jr9dlrc0000gn/T//RtmpCXcmAu/h2o_tomk_started_from_r.err

java version "1.8.0_112"
Java(TM) SE Runtime Environment (build 1.8.0_112-b16)
Java HotSpot(TM) 64-Bit Server VM (build 25.112-b16, mixed mode)

Starting H2O JVM and connecting: .. Connection successful!

R is connected to the H2O cluster:
    H2O cluster uptime:         2 seconds 605 milliseconds
    H2O cluster version:        3.10.4.8
    H2O cluster version age:    1 month and 15 days
    H2O cluster name:           H2O_started_from_R_tomk_jgy651
    H2O cluster total nodes:    1
    H2O cluster total memory:   3.56 GB
    H2O cluster total cores:    8
    H2O cluster allowed cores:  2
    H2O cluster healthy:        TRUE
    H2O Connection ip:          localhost
    H2O Connection port:        54321
    H2O Connection proxy:       NA
    H2O Internal Security:      FALSE
    R Version:                  R version 3.3.2 (2016-10-31)

Note:  As started, H2O is limited to the CRAN default of 2 CPUs.
       Shut down and restart H2O as shown below to use all your CPUs.
           > h2o.shutdown()
           > h2o.init(nthreads = -1)

> nameDF <- c(paste("O",letters, sep="_"),  paste("T",letters, sep="_"),
+ paste("TR",letters, sep="_"))
> DF <- matrix( data=numeric(length(nameDF)*1000000), nrow=1000000)
> colnames(DF) <- nameDF
> DF <- as.data.frame(DF)
> DF$char <- rep("bla", 1000000)
> View(DF)
> DFh2o <- as.h2o(DF)
  |=====================================================================================================================| 100%
> dim(DFh2o)
[1] 1000000      79
> dim(DF)
[1] 1000000      79
</code>```

Body:
I am trying to convert larger data.frames consisting of round about 70 numerical columns and one character column to h2o objects.
There is no error message but it only converts a fraction of the data frame and skips the rest (i.e. the number of rows of the resulting h2o object is much lower than the one of the original data frame)
Has anybody an advice?

Here an example (I build an example data frame similar to the one I am trying to analyze in my study.)

nameDF <- c(paste("O",letters, sep="_"),  paste("T",letters, sep="_"),
   paste("TR",letters, sep="_"))
DF <- matrix( data=numeric(length(nameDF)*1000000), nrow=1000000)
colnames(DF) <- nameDF
DF <- as.data.frame(DF)
DF$char <- rep("bla", 1000000)
DFh2o <- as.h2o(DF)
dim(DFh2o)
dim(DF)

Body:
I tried the relatively recent H2O 3.10.4.8, ran your code sample, and the behavior of the two dims looks like the correct behavior to me.

> library(h2o)
> h2o.init()

H2O is not running yet, starting it now...

Note:  In case of errors look at the following log files:
    /var/folders/tt/g5d7cr8d3fg84jmb5jr9dlrc0000gn/T//RtmpCXcmAu/h2o_tomk_started_from_r.out
    /var/folders/tt/g5d7cr8d3fg84jmb5jr9dlrc0000gn/T//RtmpCXcmAu/h2o_tomk_started_from_r.err

java version "1.8.0_112"
Java(TM) SE Runtime Environment (build 1.8.0_112-b16)
Java HotSpot(TM) 64-Bit Server VM (build 25.112-b16, mixed mode)

Starting H2O JVM and connecting: .. Connection successful!

R is connected to the H2O cluster:
    H2O cluster uptime:         2 seconds 605 milliseconds
    H2O cluster version:        3.10.4.8
    H2O cluster version age:    1 month and 15 days
    H2O cluster name:           H2O_started_from_R_tomk_jgy651
    H2O cluster total nodes:    1
    H2O cluster total memory:   3.56 GB
    H2O cluster total cores:    8
    H2O cluster allowed cores:  2
    H2O cluster healthy:        TRUE
    H2O Connection ip:          localhost
    H2O Connection port:        54321
    H2O Connection proxy:       NA
    H2O Internal Security:      FALSE
    R Version:                  R version 3.3.2 (2016-10-31)

Note:  As started, H2O is limited to the CRAN default of 2 CPUs.
       Shut down and restart H2O as shown below to use all your CPUs.
           > h2o.shutdown()
           > h2o.init(nthreads = -1)

> nameDF <- c(paste("O",letters, sep="_"),  paste("T",letters, sep="_"),
+ paste("TR",letters, sep="_"))
> DF <- matrix( data=numeric(length(nameDF)*1000000), nrow=1000000)
> colnames(DF) <- nameDF
> DF <- as.data.frame(DF)
> DF$char <- rep("bla", 1000000)
> View(DF)
> DFh2o <- as.h2o(DF)
  |=====================================================================================================================| 100%
> dim(DFh2o)
[1] 1000000      79
> dim(DF)
[1] 1000000      79


问:
Console error: image not found
Some context:
I'm using a .twig file to display some .png images, like this

The images are all named output_icon_(output.slug).png; output.slug has 11 different slugs, same number of pictures I have. here's a picture name example: output_icon_balance.png.

So far so good, it all works as it should, but even tho all 11 pictures are being displayed, the console is showing this
GET URL/path/output_icon_%7B%7B%20output.slug%20%7D%7D.png?v2212 404 not found

答:
You have to use ng-src to render images defined on your scope. The reason is that browser will read it as {{variable}} assigned to your src tag instead of rendering it first and then assigning. So, ng-src will make sure that your variable is first rendered and then assigned to your tag.

For more Info:
https://docs.angularjs.org/api/ng/directive/ngSrc

Title: Console error: image not found


问:
Windows Authentication with Network Service/ ApplicationPoolIdentity when is user Identity used?
Referencing below link:

https://learn.microsoft.com/en-us/iis/manage/configuring-security/application-pool-identities

I am trying to get a better understanding of when the Network Service Identity is used vs the user Identity on the server to access files. Or if the user Identity is even used at all. It was my original understanding that with Windows Authentication the application will use the authenticated user's permissions to gain access to the application directory as well as other directories the user has permission to.

While setting up my application in IIS 7.0, I see that when the application pool identity is set to use the ApplicationPoolIdentity it relies on permissions granted to this virtual account while being accessed.

When would the application rely on the application pool/network Identity vs the user's Identity (if at all).

I am using ASP.NET MVC4

答:
For asp.net,default identity IIS will use be the application pool identity.It comes from this Application Pool identity you have set here

You can override this setting with "Enabling ASP.NET impersonation"

Edit: - More detailed version.

Your asp.net code runs under Application Pool's identity by default but the static files(html,js,css etc) will be using the user credentials coming in the Authentication setting.

If you are using Anonymous Authentication,asp.net code will run under  Application Pool Identity and static files will use IUSR setting coming from here

If you are using Windows Authentication,then asp.net will still use Application Pool identity and static files will use the incoming login user's crednetails.

At anytime you can change the Asp.net impersonation to use the Incoming user credential(Anonymous or Windows or basic authentication).

Basically asp.net will be using the running process (w3wp.exe identity) which is application pool identity.

Hope it clears!


问:
Check if a column exist or not
When I try to check if the column exist or not it crushes the app with this error :

```<code>Caused by: android.database.sqlite.SQLiteException: no such column: perfumes (code 1): , while compiling: SELECT * FROM savedproducts WHERE pid = 1 AND ptype = perfumes
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1113)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:690)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:59)
at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1438)
at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1377)
at app.botikaty.com.DatabaseHandler.CheckIfExist(DatabaseHandler.java:137)
at app.botikaty.com.ViewProductActivity.onCreate(ViewProductActivity.java:80)
</code>```

And what I've tried is this code (DatabaseHandler.java:137) :

```<code> int CheckIfExist(String id,String type) {
        String countQuery = "SELECT * FROM " + TABLE_CONTACTS + " WHERE pid = " + id + " AND ptype = " + type;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);
        return cursor.getCount();
    }
</code>```

ViewProductActivity.java:80

```<code>int issaved = dbHandler.CheckIfExist(theproductid,theproducttype);
            if (issaved != -1){
                savebtn.setLiked(true);
            }else{
                savebtn.setLiked(false);
            }
</code>```

I wish the problem is clear and understandable , what to do please ?

Some files I've used :

DatabaseHandler.java -> https://pastebin.com/94pkJFLd

Contact.java -> https://pastebin.com/P8DiHbxY

答:
You need to change it to this:

```<code> String countQuery = "SELECT * FROM " + TABLE_CONTACTS + " WHERE pid = " + id + " AND ptype = '" + type+"'";
</code>```

this just puts single quotes around your type string to signify that it is a string value to the database

So the query will look like this:
SELECT * FROM savedproducts WHERE pid = 1 AND ptype = 'perfumes'

The difference is ptype = perfumes vs ptype = 'perfumes' in the actual query

You weren't putting the single quotes around your type string, so the database thought that you were trying to get a column when it was you actually trying to tell it a value for ptype

Title: Check if a column exist or not

Body:
When I try to check if the column exist or not it crushes the app with this error :

Caused by: android.database.sqlite.SQLiteException: no such column: perfumes (code 1): , while compiling: SELECT * FROM savedproducts WHERE pid = 1 AND ptype = perfumes
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1113)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:690)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:59)
at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1438)
at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1377)
at app.botikaty.com.DatabaseHandler.CheckIfExist(DatabaseHandler.java:137)
at app.botikaty.com.ViewProductActivity.onCreate(ViewProductActivity.java:80)

And what I've tried is this code (DatabaseHandler.java:137) :

 int CheckIfExist(String id,String type) {
        String countQuery = "SELECT * FROM " + TABLE_CONTACTS + " WHERE pid = " + id + " AND ptype = " + type;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);
        return cursor.getCount();
    }

ViewProductActivity.java:80

int issaved = dbHandler.CheckIfExist(theproductid,theproducttype);
            if (issaved != -1){
                savebtn.setLiked(true);
            }else{
                savebtn.setLiked(false);
            }

I wish the problem is clear and understandable , what to do please ?

Some files I've used :

DatabaseHandler.java -> https://pastebin.com/94pkJFLd

Contact.java -> https://pastebin.com/P8DiHbxY

Body:
You need to change it to this:

 String countQuery = "SELECT * FROM " + TABLE_CONTACTS + " WHERE pid = " + id + " AND ptype = '" + type+"'";

this just puts single quotes around your type string to signify that it is a string value to the database

So the query will look like this:
SELECT * FROM savedproducts WHERE pid = 1 AND ptype = 'perfumes'

The difference is ptype = perfumes vs ptype = 'perfumes' in the actual query

You weren't putting the single quotes around your type string, so the database thought that you were trying to get a column when it was you actually trying to tell it a value for ptype


问:
Can integer promotion happen in the reverse order(eg. long int to int) in variadic functions like printf()?
```<code>#include<stdio.h>
int main() {
    long a = 9;
    printf("a = %d",a);//output is 9 but with a warning 'expecting long int'
}
</code>```

Why can't long here be converted to int?

答:
Following passes a long, yet printf() expects an int due to "%d".  Result: undefined behavior (UB).  If int and long are the same size that UB might look like everything is OK, or it may fail.  It is UB.

```<code>long a = 9;
printf("a = %d",a);  // UB
</code>```

Why can't long here be converted to int?

long can be converted, yet code did not direct that like the below code.

```<code>printf("a = %d", (int) a);  // OK
</code>```

Can integer promotion happen in the reverse order ... in variadic functions like printf()?

Integer promotions do not  happen in the reverse order unless code explicitly down-casts or assigned to a narrower type.

There are cases where demotion will appear to be true with printf().

The below promotes sc to int as it is passed to printf().  printf() will take that int and due to "%hhd" will convert it to signed char and then print that numeric value.

```<code>signed char sc = 1;
printf("a = %hhd", cs); // prints 1
</code>```

The below passes i to printf() as an int.  printf() will take that int and due to "%hhd" will convert it to signed char and then print that numeric value.  So in this case it looks like i was demoted.

```<code>int i = 0x101;
printf("a = %hhd", i);  // prints 1
</code>```

Body:
#include<stdio.h>
int main() {
    long a = 9;
    printf("a = %d",a);//output is 9 but with a warning 'expecting long int'
}

Why can't long here be converted to int?

Body:
Following passes a long, yet printf() expects an int due to "%d".  Result: undefined behavior (UB).  If int and long are the same size that UB might look like everything is OK, or it may fail.  It is UB.

long a = 9;
printf("a = %d",a);  // UB

Why can't long here be converted to int?

long can be converted, yet code did not direct that like the below code.

printf("a = %d", (int) a);  // OK

Can integer promotion happen in the reverse order ... in variadic functions like printf()?

Integer promotions do not  happen in the reverse order unless code explicitly down-casts or assigned to a narrower type.

There are cases where demotion will appear to be true with printf().

The below promotes sc to int as it is passed to printf().  printf() will take that int and due to "%hhd" will convert it to signed char and then print that numeric value.

signed char sc = 1;
printf("a = %hhd", cs); // prints 1

The below passes i to printf() as an int.  printf() will take that int and due to "%hhd" will convert it to signed char and then print that numeric value.  So in this case it looks like i was demoted.

int i = 0x101;
printf("a = %hhd", i);  // prints 1


答:
You almost got it, the approach that is - building out a dict out of the abbreviations is the easiest way to do this:

```<code>with open("state_abbreviations.csv", "r") as f:
    # you can use csv.DictReader() instead but lets strive for performance
    reader = csv.reader(f)
    next(reader)  # skip the header
    # assuming the first column holds the abbreviation, second the full state name
    state_map = {state[0]: state[1] for state in reader}
</code>```

Now you have state_map containing a map of all your state abbreviations, for example: state_map["FL"] contains Florida.

To replace the values in your test.csv, tho, you'll either have to load the whole file into memory, parse it, do the replacement and save it, or create a temporary file and stream-write to it the changes, then overwrite the original file with the temporary file. Assuming that test.csv is not too big to fit into your memory, the first approach is much simpler:

```<code>with open("test.csv", "r+U") as f:  # open the file in read-write mode
    # again, you can use csv.DictReader() for convenience, but this is significantly faster
    reader = csv.reader(f)
    header = next(reader)  # get the header
    rows = []  # hold our rows
    if "state" in header:  # proceed only if `state` column is found in the header
        state_index = header.index("state")  # find the state column index
        for row in reader:  # read the CSV row by row
            current_state = row[state_index]  # get the abbreviated state value
            # replace the abbreviation if it exists in our state_map
            row[state_index] = state_map.get(current_state, current_state)
            rows.append(row)  # append the processed row to our `rows` list
        # now lets overwrite the file with updated data
        f.seek(0)  # seek to the file begining
        f.truncate()  # truncate the rest of the content
        writer = csv.writer(f)  # create a CSV writer
        writer.writerow(header)  # write back the header
        writer.writerows(rows)  # write our modified rows
</code>```

Title: Code swap. How would I swap the value of one CSV file column to another?

Body:
You almost got it, the approach that is - building out a dict out of the abbreviations is the easiest way to do this:

with open("state_abbreviations.csv", "r") as f:
    # you can use csv.DictReader() instead but lets strive for performance
    reader = csv.reader(f)
    next(reader)  # skip the header
    # assuming the first column holds the abbreviation, second the full state name
    state_map = {state[0]: state[1] for state in reader}

Now you have state_map containing a map of all your state abbreviations, for example: state_map["FL"] contains Florida.

To replace the values in your test.csv, tho, you'll either have to load the whole file into memory, parse it, do the replacement and save it, or create a temporary file and stream-write to it the changes, then overwrite the original file with the temporary file. Assuming that test.csv is not too big to fit into your memory, the first approach is much simpler:

with open("test.csv", "r+U") as f:  # open the file in read-write mode
    # again, you can use csv.DictReader() for convenience, but this is significantly faster
    reader = csv.reader(f)
    header = next(reader)  # get the header
    rows = []  # hold our rows
    if "state" in header:  # proceed only if `state` column is found in the header
        state_index = header.index("state")  # find the state column index
        for row in reader:  # read the CSV row by row
            current_state = row[state_index]  # get the abbreviated state value
            # replace the abbreviation if it exists in our state_map
            row[state_index] = state_map.get(current_state, current_state)
            rows.append(row)  # append the processed row to our `rows` list
        # now lets overwrite the file with updated data
        f.seek(0)  # seek to the file begining
        f.truncate()  # truncate the rest of the content
        writer = csv.writer(f)  # create a CSV writer
        writer.writerow(header)  # write back the header
        writer.writerows(rows)  # write our modified rows


问:
Ruby open-uri open method loses file extension opening images
I'm using ruby 1.9.2 along with Rails 3.1.4 and Paperclip 2.4.5.

My issue is trying to save a paperclip attachment from a URI loses the file extension and saves the file without one resulting in issues with things like fancybox that require an extension.

Some example code:

```<code>uri = "http://featherfiles.aviary.com/2012-06-13/bbe5f0de1/0c5a672b88ea47ecb4631ac173e27430.png"
open(uri)
#=> #<File:/var/folders/zc/d69gxhzx10x_bvjrkqgyjgxr0000gn/T/open-uri20120613-27204-i6cldv>
</code>```

Because there is no extension on the temp file paperclip is saving the file without one resulting in issues.

Has anyone run into this issue? I've seen multiple answers about using paperclip to store images from a URI but none seem to address the same problem we're running

答:
Update – Paperclip can do this on its own!

Posted by Aditya Sanghi (thanks a lot!):

```<code>current_comments.pictures.create!(file: URI.parse(image_url))
</code>```

Although keep in mind, that you still need to handle 500, 404, etc
  errors (Paperclip can raise them).

Thanks to: https://mensfeld.pl/2013/12/rails-paperclip-open-uri-downloading-files-from-the-internet-and-saving-them-with-paperclip/

Body:
I'm using ruby 1.9.2 along with Rails 3.1.4 and Paperclip 2.4.5.

My issue is trying to save a paperclip attachment from a URI loses the file extension and saves the file without one resulting in issues with things like fancybox that require an extension.

Some example code:

uri = "http://featherfiles.aviary.com/2012-06-13/bbe5f0de1/0c5a672b88ea47ecb4631ac173e27430.png"
open(uri)
#=> #<File:/var/folders/zc/d69gxhzx10x_bvjrkqgyjgxr0000gn/T/open-uri20120613-27204-i6cldv>

Because there is no extension on the temp file paperclip is saving the file without one resulting in issues.

Has anyone run into this issue? I've seen multiple answers about using paperclip to store images from a URI but none seem to address the same problem we're running

Body:
Update – Paperclip can do this on its own!

Posted by Aditya Sanghi (thanks a lot!):

current_comments.pictures.create!(file: URI.parse(image_url))

Although keep in mind, that you still need to handle 500, 404, etc
  errors (Paperclip can raise them).

Thanks to: https://mensfeld.pl/2013/12/rails-paperclip-open-uri-downloading-files-from-the-internet-and-saving-them-with-paperclip/


问:
.NET - Timer Elapsed Event Overlap
Is there a way to detect that elapsed events of timer are overlapping? For example, I create a Timer with 200ms interval between elapsed events but the executed code at event is taking more than 200ms. As a result, another elapsed event is executed before the last one is finished. Also is there a way to prevent this from happening such that another event is not invoked before the last one is finished?</p>

答: Have a look at using Timer.Stop Method </p>

ContentLicense: CC BY-SA 2.5

Title: .NET - Timer Elapsed Event Overlap

Body: Have a look at using Timer.Stop Method


问:
Faster way to filter dates greater than X, then clear filtered cells?
I have a data set in which I need to find all dates greater than "X" within the range. I then need to clear the contents of any cells matching that criteria. My current code loops through each column, AutoFilters based on the UserForm provided variable "gDate," and then clears any visible cells. The data set can be as large as 54 columns and 1,000+ rows.

I'm still new to VBA and I know creating loops can be less than optimal. That being said, is there a faster, more efficient way to accomplish my task?

```<code>Sub FilterDates()
Dim ws2 As Worksheet
Dim rng As Range
Dim gDate As Date
Dim LastRow2 As Long, LastCol2 As Long
Set ws2 = Sheets("Sheet2")
LastRow2 = ws2.Cells(Rows.count, 1).End(xlUp).row
LastCol2 = ws2.Cells(1, Columns.count).End(xlToLeft).Column
gDate = Sheets("UFinput").Cells(2, 1)
Set rng = ws2.Range(Cells(1, 1), Cells(LastRow2, LastCol2))

'Loops through columns filtering dates > gDate then clears
With rng
On Error Resume Next
    Dim iLoop As Long
    For iLoop = 5 To LastCol2

    .AutoFilter Field:=iLoop, Criteria1:=">" & gDate
    ws2.Range(Cells(2, iLoop), Cells(LastRow2, iLoop)).SpecialCells(xlCellTypeVisible).ClearContents
    .AutoFilter Field:=iLoop

    Next iLoop
End With

ws2.AutoFilterMode = False
End Sub
</code>```

答:
Avoid Volatile Formulas

Volatile formulas are called so because of a reason. Functions such as NOW, TODAY, INDIRECT, RAND, OFFSET etc. recalculate every time there is a change in the workbook.

For example, if you use NOW function in a cell, every time there is a change in the worksheet, the formula would be recalculated and the cell value would update.

This takes additional processing speed and you end up with a slow excel workbook.

As a rule of thumb, avoid volatile formulas. And if you can’t, try and minimize its use.
2. Use Helper Columns

Helper columns are one of the most under-rated design constructs in Excel. I have seen many people shy away from creating helper columns.

DON’T DO That.

The biggest benefit of using ‘Helper Columns’ is that it may help you avoid array formulas.

Now don’t get me wrong. I am not against array formulas. Rather I believe these could be awesome in some situations. But it when you try to do it all with one long formula, it does impact the performance of your Excel workbook. A couple of array formulas here and there shouldn’t hurt, but in case you need to use it in many places, consider using helper columns.

Here are some Examples where helper columns are used:

```<code>Automatically Sort Data in Alphabetical Order using Formula.
Dynamic Excel Filter – Extract Data as you Type.
Creating Multiple Drop-down Lists in Excel without Repetition.
</code>```

Avoid Array Formulas

Array formulas have its own merits – but speed is not one of those.

As explained above, array formulas can take up a lot of data (cell references), analyze it, and give you the result. But doing that takes time.

If there is a way to avoid array formulas (such as using helper column), always take that road.
4. Use Conditional Formatting with Caution

I absolutely love conditional formatting. It makes bland data look so beautiful. Instead of doing the comparison yourself, now you can simply look at a cell’s color or icon and you’d know how it compares with others.

But.. here is the problem.

Not many Excel users know that Excel Conditional Formatting is volatile. While you may not notice the difference with small data sets, it can result in a slow excel spreadsheet if applied on large data sets, or applied multiple times.

Word of advice – Use it Cautiously.
5. Use Excel Tables and Named Ranges

Excel Table and Named Ranges are two amazing features that hold your data and makes referencing super easy. It may take a while to get used to it, but when you start using it, life becomes easy and fast.

In creating data-driven dashboards, it is almost always a good idea to convert your data into an Excel Table.

It also has an added advantage of making your formulas more comprehensible.

For example, what’s easier to understand?

=Sales Price-Cost Price OR =SUM(A1:A10)-SUM(G1:G10)
6. Convert Unused Formulas to Static Values

This is a no-brainer. When you don’t need it, don’t keep it.

Lots of formulas would result in a slow Excel workbook. And if you have formulas that are not even being used – you know who to blame. As a rule of thumb, if you don’t need formulas, it’s better to convert them into a static value (by pasting as values).

Read More: How to quickly convert formulas to values.

Keep All Referenced Data in One Sheet

This may not always be possible, but if you can do this, I guarantee your Excel sheet would become faster.

The logic is simple – formulas in your worksheet don’t have to go far to get the data when it is right next to it in the same sheet.
8. Avoid Using the Entire Row/Column as Reference (A:A)

The only reason I have this one on the list is that I see a lot of people using the entire row/column reference in formulas. This is a bad practice and should be avoided.

While you may think that the row/column only has a few cells with data, Excel doesn’t think that way. When you reference an entire row/column, Excel acts it as a good servant and check it anyways. That takes more time for calculations.
9. Use Manual Calculation Mode

I am just repeating what million people have already said in various forums and blogs. Using Manual calculation gives you the flexibility to tell excel when to calculate, rather than Excel taking its own decisions. This is not something that speeds up your Excel workbook, but if you have a slow Excel spreadsheet, it definitely saves time by not making Excel recalculate again and again.

```<code>To switch to manual mode, go to Formula Tab –> Calculation Options –> Manual (press F9 key to recalculate)
</code>```

Slow Excel spreadsheets - Manual Calculation
10. Use Faster Formulas Techniques

Excel gives you a lot of formulas and formula-combos to do the same thing. It is best to identify and use the fastest ones.

Here are a couple of examples:

```<code>Use IFERROR instead of IF and ISERROR combo (unless you are using Excel 2003 or earlier, which does not have IFERROR).
Use MAX(A1,0) instead do IF(A1>0,A1,0) – This is a cool tip that I learned from Mr. Excel aka Bill Jelen. His research shows that MAX option is 40% faster than IF option (and I am ready to take this stat on his face value).
Use the INDEX/MATCH combo, instead of VLOOKUP – This may raise a lot of eyebrows, but the truth is, there is no way VLOOKUP can be faster if you have 100’s of columns of data. The world is moving towards INDEX/MATCH, and you should make the shift too.
[If you are still confused about what to use, here is a head-on-head comparison of VLOOKUP Vs. INDEX/MATCH].
Use — (double negatives) to convert TRUE’s and FALSE’s to 1’s and 0’s (instead of multiplying it by 1 or adding 0 to it). The speed improvement is noticeable in large data sets.
</code>```

Is this an exhaustive list? Absolutely NOT. These are some good ones that I think are worth sharing as a starting point.

Body:
I have a data set in which I need to find all dates greater than "X" within the range. I then need to clear the contents of any cells matching that criteria. My current code loops through each column, AutoFilters based on the UserForm provided variable "gDate," and then clears any visible cells. The data set can be as large as 54 columns and 1,000+ rows.

I'm still new to VBA and I know creating loops can be less than optimal. That being said, is there a faster, more efficient way to accomplish my task?

Sub FilterDates()
Dim ws2 As Worksheet
Dim rng As Range
Dim gDate As Date
Dim LastRow2 As Long, LastCol2 As Long
Set ws2 = Sheets("Sheet2")
LastRow2 = ws2.Cells(Rows.count, 1).End(xlUp).row
LastCol2 = ws2.Cells(1, Columns.count).End(xlToLeft).Column
gDate = Sheets("UFinput").Cells(2, 1)
Set rng = ws2.Range(Cells(1, 1), Cells(LastRow2, LastCol2))

'Loops through columns filtering dates > gDate then clears
With rng
On Error Resume Next
    Dim iLoop As Long
    For iLoop = 5 To LastCol2

    .AutoFilter Field:=iLoop, Criteria1:=">" & gDate
    ws2.Range(Cells(2, iLoop), Cells(LastRow2, iLoop)).SpecialCells(xlCellTypeVisible).ClearContents
    .AutoFilter Field:=iLoop

    Next iLoop
End With

ws2.AutoFilterMode = False
End Sub

Body:
Avoid Volatile Formulas

Volatile formulas are called so because of a reason. Functions such as NOW, TODAY, INDIRECT, RAND, OFFSET etc. recalculate every time there is a change in the workbook.

For example, if you use NOW function in a cell, every time there is a change in the worksheet, the formula would be recalculated and the cell value would update.

This takes additional processing speed and you end up with a slow excel workbook.

As a rule of thumb, avoid volatile formulas. And if you can’t, try and minimize its use.
2. Use Helper Columns

Helper columns are one of the most under-rated design constructs in Excel. I have seen many people shy away from creating helper columns.

DON’T DO That.

The biggest benefit of using ‘Helper Columns’ is that it may help you avoid array formulas.

Now don’t get me wrong. I am not against array formulas. Rather I believe these could be awesome in some situations. But it when you try to do it all with one long formula, it does impact the performance of your Excel workbook. A couple of array formulas here and there shouldn’t hurt, but in case you need to use it in many places, consider using helper columns.

Here are some Examples where helper columns are used:

Automatically Sort Data in Alphabetical Order using Formula.
Dynamic Excel Filter – Extract Data as you Type.
Creating Multiple Drop-down Lists in Excel without Repetition.

Avoid Array Formulas

Array formulas have its own merits – but speed is not one of those.

As explained above, array formulas can take up a lot of data (cell references), analyze it, and give you the result. But doing that takes time.

If there is a way to avoid array formulas (such as using helper column), always take that road.
4. Use Conditional Formatting with Caution

I absolutely love conditional formatting. It makes bland data look so beautiful. Instead of doing the comparison yourself, now you can simply look at a cell’s color or icon and you’d know how it compares with others.

But.. here is the problem.

Not many Excel users know that Excel Conditional Formatting is volatile. While you may not notice the difference with small data sets, it can result in a slow excel spreadsheet if applied on large data sets, or applied multiple times.

Word of advice – Use it Cautiously.
5. Use Excel Tables and Named Ranges

Excel Table and Named Ranges are two amazing features that hold your data and makes referencing super easy. It may take a while to get used to it, but when you start using it, life becomes easy and fast.

In creating data-driven dashboards, it is almost always a good idea to convert your data into an Excel Table.

It also has an added advantage of making your formulas more comprehensible.

For example, what’s easier to understand?

=Sales Price-Cost Price OR =SUM(A1:A10)-SUM(G1:G10)
6. Convert Unused Formulas to Static Values

This is a no-brainer. When you don’t need it, don’t keep it.

Lots of formulas would result in a slow Excel workbook. And if you have formulas that are not even being used – you know who to blame. As a rule of thumb, if you don’t need formulas, it’s better to convert them into a static value (by pasting as values).

Read More: How to quickly convert formulas to values.

Keep All Referenced Data in One Sheet

This may not always be possible, but if you can do this, I guarantee your Excel sheet would become faster.

The logic is simple – formulas in your worksheet don’t have to go far to get the data when it is right next to it in the same sheet.
8. Avoid Using the Entire Row/Column as Reference (A:A)

The only reason I have this one on the list is that I see a lot of people using the entire row/column reference in formulas. This is a bad practice and should be avoided.

While you may think that the row/column only has a few cells with data, Excel doesn’t think that way. When you reference an entire row/column, Excel acts it as a good servant and check it anyways. That takes more time for calculations.
9. Use Manual Calculation Mode

I am just repeating what million people have already said in various forums and blogs. Using Manual calculation gives you the flexibility to tell excel when to calculate, rather than Excel taking its own decisions. This is not something that speeds up your Excel workbook, but if you have a slow Excel spreadsheet, it definitely saves time by not making Excel recalculate again and again.

To switch to manual mode, go to Formula Tab –> Calculation Options –> Manual (press F9 key to recalculate)

Slow Excel spreadsheets - Manual Calculation
10. Use Faster Formulas Techniques

Excel gives you a lot of formulas and formula-combos to do the same thing. It is best to identify and use the fastest ones.

Here are a couple of examples:

Use IFERROR instead of IF and ISERROR combo (unless you are using Excel 2003 or earlier, which does not have IFERROR).
Use MAX(A1,0) instead do IF(A1>0,A1,0) – This is a cool tip that I learned from Mr. Excel aka Bill Jelen. His research shows that MAX option is 40% faster than IF option (and I am ready to take this stat on his face value).
Use the INDEX/MATCH combo, instead of VLOOKUP – This may raise a lot of eyebrows, but the truth is, there is no way VLOOKUP can be faster if you have 100’s of columns of data. The world is moving towards INDEX/MATCH, and you should make the shift too.
[If you are still confused about what to use, here is a head-on-head comparison of VLOOKUP Vs. INDEX/MATCH].
Use — (double negatives) to convert TRUE’s and FALSE’s to 1’s and 0’s (instead of multiplying it by 1 or adding 0 to it). The speed improvement is noticeable in large data sets.

Is this an exhaustive list? Absolutely NOT. These are some good ones that I think are worth sharing as a starting point.


问:
Heading Expand/Collapse Jquery Working but is Expanded by Default, I need it collapsed by default
So I'm working on a sharepoint site.. I'm completely new to javascript. I have been using a jquery I found to enable an expand/collapse feature that is tied to a heading type. When a heading is clicked, all of the paragraph content beneath the heading expands or collapses.

It works well, the only problem is that when the page loads, all of the content is expanded by default, and then collapses a moment later after the page finishes loading. It looks sloppy when loading so I want to have everything collapsed by default.

I also do not need the function that disables expand/collapse while in edit mode or a wikipage, if that makes this issue any simpler.

Here is the script I'm using:

```<code>    <script language="javascript" type="text/javascript"
src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.2.min.js"></script>
 <script language="javascript" type="text/javascript">

$(document).ready(function () {
 var inEditMode = Utils.checkPageInEditMode();
 // Prevent the collapsing of <h2> blocks when in SharePoint's [Edit Mode]
 if (!inEditMode) {
 UI.collapseContentHeaders();
 UI.toggleContentHeaders();
 }
 });

var UI = {
 collapseContentHeaders: function () {
 $('#DeltaPlaceHolderMain h2').each(function (index, value) {
 // Collapses all <h2> blocks
 {
 $(this).toggleClass('expand').nextUntil('h2').slideToggle(100);
 }
 });
 },

 toggleContentHeaders: function () {
 // Toggles the accordion behavior for <h2> regions onClick
 $('#DeltaPlaceHolderMain h2').click(function () {
 $(this).toggleClass('expand').nextUntil('h2').slideToggle(100);
 });
 }
 }

var Utils = {
 checkPageInEditMode: function () {
 var pageEditMode = null;
 var wikiPageEditMode = null;

// Edit check for Wiki Pages
 if (document.forms[MSOWebPartPageFormName]._wikiPageMode) {
 wikiPageEditMode =
document.forms[MSOWebPartPageFormName]._wikiPageMode.value;
 }
 // Edit check for all other pages
 if (document.forms[MSOWebPartPageFormName].MSOLayout_InDesignMode) {
 pageEditMode =
 document.forms[MSOWebPartPageFormName].MSOLayout_InDesignMode.value;
 }
 // Return the either/or if one of the page types is flagged as in Edit Mode
 if (!pageEditMode && !wikiPageEditMode) {
 return false;
 }
 return pageEditMode == "1" || wikiPageEditMode == "Edit";
}
 }
 </script>
</code>```

答:
Just delete if statement

```<code>if (index > 0) {
</code>```

So i has to be olny $(this).toggleClass('expand').nextUntil('h2').slideToggle(100);

Body:
Just delete if statement

if (index > 0) {

So i has to be olny $(this).toggleClass('expand').nextUntil('h2').slideToggle(100);


问:
Running PHP script from other directory
I have a PHP script of about 10 .php files under the same directory. i.e.

www.domain.com/script_directory/
```

<p>I wanted to run that script from another director and tried the following:</p>

<pre class="lang-html prettyprint-override"><code>www.domain.com/some_directory/index.php
</code>```

where index.php contains

<?php
include "../script_directory/index.php";
?>
```

Of course the above doesn't work.
Is there any way to set the working path of the script in PHP, similar to "HTML base Tag"?
Some files of the script are "called" via ajax and the others with direct links.

答:
You said:

I want user to always stay at www.domain.com/some_directory

To do it, you can put a HTTP redirect in the index.php at the root, something like this:

```<code><?php
header("location:/some_directory");
</code>```

If using Apache, you can do it using .htaccess like this:

```<code>Redirect / http://www.example.com/some_directory
</code>```

But all depends on the rules/behaviour that you want.  Using include in PHP only insert a script into it, allowing to use the code/functions/classes that are into it.

Title: Running PHP script from other directory

Body:
I have a PHP script of about 10 .php files under the same directory. i.e.

www.domain.com/script_directory/

I wanted to run that script from another director and tried the following:

www.domain.com/some_directory/index.php

where index.php contains

<?php
include "../script_directory/index.php";
?>

Of course the above doesn't work.
Is there any way to set the working path of the script in PHP, similar to "HTML base Tag"?
Some files of the script are "called" via ajax and the others with direct links.

Body:
You said:

I want user to always stay at www.domain.com/some_directory

To do it, you can put a HTTP redirect in the index.php at the root, something like this:

<?php
header("location:/some_directory");

If using Apache, you can do it using .htaccess like this:

Redirect / http://www.example.com/some_directory

But all depends on the rules/behaviour that you want.  Using include in PHP only insert a script into it, allowing to use the code/functions/classes that are into it.


问:
UART peripherals on Android Things for Raspberry Pi 3
How do I use UART peripherals on Android Things for Raspberry Pi 3?

It seems that by default it is assigned the linux console.

答: Beginning with Developer Preview 3, in which USB-Serial devices support added, external USB-UART dongles like this can be used instead of built-in UART of Raspberry Pi 3.</p>


问:
Choose Browser while clicking url in UITextView
I have a URL link in my UITextView. And in my iPhone, there are both safari & chrome apps. Whenever I click on the URL link, I want to list both safari & Chrome (and all other browsers in the phone) in a pop up view so that the user can choose which browser they want to open the url. Now it is always opening safari as it is the default browser in my phone. Is there any way I can choose the browser to open the URL? I know there is this delegate

```<code>func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
        // Got the url here. how can i force this url to open in chrome
        return true
    }
</code>```

but how can i force this url to open in chrome or any other browser? And how can I list all available browsers in a view?

答:
To wrap it up,</p>

```<code>func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
    let actionSheet = UIAlertController(title: "Where do you want to open it", message: "", preferredStyle: .actionSheet)

    if UIApplication.shared.canOpenURL(URL(string: "http://www.stackoverflow.com")!) {
        actionSheet.addAction(UIAlertAction(title: "Safari", style: .default, handler: {
            (alert: UIAlertAction!) -> Void in
            UIApplication.shared.open(URL(string: "http://www.stackoverflow.com")!, options: [:], completionHandler: nil)
        }))
    }

    if UIApplication.shared.canOpenURL(URL(string: "googlechrome://www.stackoverflow.com")!) {
        actionSheet.addAction(UIAlertAction(title: "Chrome", style: .default, handler: {
            (alert: UIAlertAction!) -> Void in
            UIApplication.shared.open(URL(string: "googlechrome://www.stackoverflow.com")!, options: [:], completionHandler: nil)
        }))
    }

    if UIApplication.shared.canOpenURL(URL(string: "firefox://open-url?url=http://www.stackoverflow.com")!) {
        actionSheet.addAction(UIAlertAction(title: "Fire Fox", style: .default, handler: {
            (alert: UIAlertAction!) -> Void in
            UIApplication.shared.open(URL(string: "firefox://open-url?url=http://www.stackoverflow.com")!, options: [:], completionHandler: nil)
        }))
    }

    if UIApplication.shared.canOpenURL(URL(string: "opera-http://www.stackoverflow.com")!) {
        actionSheet.addAction(UIAlertAction(title: "Opera", style: .default, handler: {
            (alert: UIAlertAction!) -> Void in
            UIApplication.shared.open(URL(string: "opera-http://www.stackoverflow.com")!, options: [:], completionHandler: nil)
        }))
    }

    actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
    self.present(actionSheet, animated: true, completion: nil)

    return false
}
</code>```

Body:
I have a URL link in my UITextView. And in my iPhone, there are both safari & chrome apps. Whenever I click on the URL link, I want to list both safari & Chrome (and all other browsers in the phone) in a pop up view so that the user can choose which browser they want to open the url. Now it is always opening safari as it is the default browser in my phone. Is there any way I can choose the browser to open the URL? I know there is this delegate

func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
        // Got the url here. how can i force this url to open in chrome
        return true
    }

but how can i force this url to open in chrome or any other browser? And how can I list all available browsers in a view?

Body:
To wrap it up,

func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
    let actionSheet = UIAlertController(title: "Where do you want to open it", message: "", preferredStyle: .actionSheet)

    if UIApplication.shared.canOpenURL(URL(string: "http://www.stackoverflow.com")!) {
        actionSheet.addAction(UIAlertAction(title: "Safari", style: .default, handler: {
            (alert: UIAlertAction!) -> Void in
            UIApplication.shared.open(URL(string: "http://www.stackoverflow.com")!, options: [:], completionHandler: nil)
        }))
    }

    if UIApplication.shared.canOpenURL(URL(string: "googlechrome://www.stackoverflow.com")!) {
        actionSheet.addAction(UIAlertAction(title: "Chrome", style: .default, handler: {
            (alert: UIAlertAction!) -> Void in
            UIApplication.shared.open(URL(string: "googlechrome://www.stackoverflow.com")!, options: [:], completionHandler: nil)
        }))
    }

    if UIApplication.shared.canOpenURL(URL(string: "firefox://open-url?url=http://www.stackoverflow.com")!) {
        actionSheet.addAction(UIAlertAction(title: "Fire Fox", style: .default, handler: {
            (alert: UIAlertAction!) -> Void in
            UIApplication.shared.open(URL(string: "firefox://open-url?url=http://www.stackoverflow.com")!, options: [:], completionHandler: nil)
        }))
    }

    if UIApplication.shared.canOpenURL(URL(string: "opera-http://www.stackoverflow.com")!) {
        actionSheet.addAction(UIAlertAction(title: "Opera", style: .default, handler: {
            (alert: UIAlertAction!) -> Void in
            UIApplication.shared.open(URL(string: "opera-http://www.stackoverflow.com")!, options: [:], completionHandler: nil)
        }))
    }

    actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
    self.present(actionSheet, animated: true, completion: nil)

    return false
}


问:
Applying a third condition to function
I have the following function which appliess css to #screen-nav when the user scrolls up and different css when user scrolls down

```<code>jQuery(document).ready(function($){
 var didScroll;
 var lastScrollTop = 0;
 var delta = 5;
 var navbarHeight = $('nav').outerHeight(true);

$(window).scroll(function(event) { didScroll = true; });

 setInterval(function() {
   if (didScroll) {
    hasScrolled();
   didScroll = false;
 }
 }, 0);

function hasScrolled() {
  if($( window ).width() > 768) {
   var st = $(this).scrollTop();
  if (Math.abs(lastScrollTop - st) <= delta)
   return;
  if (st > lastScrollTop) {
    // Scroll Down
        $('#screen-nav').removeClass('nav-down').addClass('nav-up');
   } else {
        $('#screen-nav').removeClass('nav-up').addClass('nav-down');
   }

 }
   lastScrollTop = st;
 }

});
</code>```

css

```<code> #screen-nav {
  position: fixed;
  top: 0; left: 0; right: 0;
}

#screen-nav.nav-up { top: -100px; }
#screen-nav.nav-down { top: 0; }
</code>```

I want to add a third class. I want  #screen-nav { top: 50px; } when the user is 300px from the top. (so I figure apply a third class .nav-top when the user is in that position) But not sure how to integrate it into my code.

Basically, I want the nav (navigation) to appear lower on the page when the user is at the top, and when it comes down when the user scrolls up, I want it to be right at the top.

答:
add condition of javascript
if(st == 300){ $("#screen-nav").css({ top: '50px' }); }  </p>

```<code><script type="text/javascript">
    jQuery(document).ready(function($){
     var didScroll;
     var lastScrollTop = 0;
     var delta = 5;
     var navbarHeight = $('nav').outerHeight(true);

    $(window).scroll(function(event) { didScroll = true; });

     setInterval(function() {
       if (didScroll) {
        hasScrolled();
       didScroll = false;
     }
     }, 0);

    function hasScrolled() {
      if($( window ).width() > 768) {
       var st = $(this).scrollTop();
      if (Math.abs(lastScrollTop - st) <= delta)
       return;

       if(st == 300)
       {
             $("#screen-nav").css({ top: '50px' });
       }
       else if (st > lastScrollTop) {
            // Scroll Down
            $('#screen-nav').removeClass('nav-down').addClass('nav-up');
       }
       else {
            $('#screen-nav').removeClass('nav-up').addClass('nav-down');
       }

     }
       lastScrollTop = st;
     }

    });
    </script>
</code>```

Title: Applying a third condition to function

Body:
I have the following function which appliess css to #screen-nav when the user scrolls up and different css when user scrolls down

jQuery(document).ready(function($){
 var didScroll;
 var lastScrollTop = 0;
 var delta = 5;
 var navbarHeight = $('nav').outerHeight(true);

$(window).scroll(function(event) { didScroll = true; });

 setInterval(function() {
   if (didScroll) {
    hasScrolled();
   didScroll = false;
 }
 }, 0);

function hasScrolled() {
  if($( window ).width() > 768) {
   var st = $(this).scrollTop();
  if (Math.abs(lastScrollTop - st) <= delta)
   return;
  if (st > lastScrollTop) {
    // Scroll Down
        $('#screen-nav').removeClass('nav-down').addClass('nav-up');
   } else {
        $('#screen-nav').removeClass('nav-up').addClass('nav-down');
   }

 }
   lastScrollTop = st;
 }

});

css

 #screen-nav {
  position: fixed;
  top: 0; left: 0; right: 0;
}

#screen-nav.nav-up { top: -100px; }
#screen-nav.nav-down { top: 0; }

I want to add a third class. I want  #screen-nav { top: 50px; } when the user is 300px from the top. (so I figure apply a third class .nav-top when the user is in that position) But not sure how to integrate it into my code.

Basically, I want the nav (navigation) to appear lower on the page when the user is at the top, and when it comes down when the user scrolls up, I want it to be right at the top.

Body:
add condition of javascript
if(st == 300){ $("#screen-nav").css({ top: '50px' }); }

<script type="text/javascript">
    jQuery(document).ready(function($){
     var didScroll;
     var lastScrollTop = 0;
     var delta = 5;
     var navbarHeight = $('nav').outerHeight(true);

    $(window).scroll(function(event) { didScroll = true; });

     setInterval(function() {
       if (didScroll) {
        hasScrolled();
       didScroll = false;
     }
     }, 0);

    function hasScrolled() {
      if($( window ).width() > 768) {
       var st = $(this).scrollTop();
      if (Math.abs(lastScrollTop - st) <= delta)
       return;

       if(st == 300)
       {
             $("#screen-nav").css({ top: '50px' });
       }
       else if (st > lastScrollTop) {
            // Scroll Down
            $('#screen-nav').removeClass('nav-down').addClass('nav-up');
       }
       else {
            $('#screen-nav').removeClass('nav-up').addClass('nav-down');
       }

     }
       lastScrollTop = st;
     }

    });
    </script>


问:
SCSS change variable depending on parent class?
I have this problem, in my work we have a base project that contains thousands of lines of scss codes and several variables. When this base is needed just for a website all is ok, the development goes fast. I can change the $generalColor variable(s) and the correct color is applied.

The problem comes when somewhere, in the same project, a new set of Colors (variables) are needed (microsite). Then usually one need to search every place where $generalColor is used and add something like:

```<code>$generalColor_SOMETHING: #453543;
.newExtraSetOfColor & {
    background: $generalColor_SOMETHING;
}
</code>```

And that for each variable * each new set of colors. If there are a lot of microsites/color sets it is a nightmare.

Is there a better way to this? (javascript like?)

答:
You could do something like this with a mixin:

$colors: (
  // Default color set
  default: (
    red: #ff0000,
    green: #ff0000,
    blue: #ff0000
  ),
  // Pastel color set
  pastel: (
    red: #ff6961,
    green: #77dd77,
    blue: #aec6cf
  )
);

@mixin color($color) {
  color: map-get(map-get($colors, default), $color);

  .colors--pastel & {
    color: map-get(map-get($colors, pastel), $color);
  }
}

h1 {
  @include color(red);
}
```

<p>Output:</p>

<pre class="lang-css prettyprint-override"><code>h1 {
  color: #ff0000;
}
.colors--pastel h1 {
  color: #ff0000;
}
</code>```

Body:
I have this problem, in my work we have a base project that contains thousands of lines of scss codes and several variables. When this base is needed just for a website all is ok, the development goes fast. I can change the $generalColor variable(s) and the correct color is applied.

The problem comes when somewhere, in the same project, a new set of Colors (variables) are needed (microsite). Then usually one need to search every place where $generalColor is used and add something like:

$generalColor_SOMETHING: #453543;
.newExtraSetOfColor & {
    background: $generalColor_SOMETHING;
}

And that for each variable * each new set of colors. If there are a lot of microsites/color sets it is a nightmare.

Is there a better way to this? (javascript like?)

Body:
You could do something like this with a mixin:

$colors: (
  // Default color set
  default: (
    red: #ff0000,
    green: #ff0000,
    blue: #ff0000
  ),
  // Pastel color set
  pastel: (
    red: #ff6961,
    green: #77dd77,
    blue: #aec6cf
  )
);

@mixin color($color) {
  color: map-get(map-get($colors, default), $color);

  .colors--pastel & {
    color: map-get(map-get($colors, pastel), $color);
  }
}

h1 {
  @include color(red);
}

Output:

h1 {
  color: #ff0000;
}
.colors--pastel h1 {
  color: #ff0000;
}


问:
What's the relationship between sed, grep, find, awk, gawk, which one is preferred?
I'm new to Linux/Unix. I find some task can be accomplished by many ways using these commands. Is there some relationship between them? Or which one is preferred? Which one is outdated?

Thanks.

答:
AWK is a programming language designed by Aho, Weinberger, and Kernighan.  gawk is one implementation of AWK, but there are several others, including mawk, and nawk.  It is a full-blown programming language with variables, control structures, and associative arrays, but generally optimized for dealing with the sorts of text-based data commonly found on UNIX systems.

sed is the stream editor, inspired by ed the editor.  It has a simple command set mostly limited to line-by-line editing.  sed commands can easily by imitated in awk.  The following are equivalent:

```<code>sed -e 's/foo/bar/g'
awk '{ gsub(/foo/, "bar"); print $0 }'
awk '{gsub(/foo/,"bar")}1'
</code>```

grep finds text.  Basic grep functionality can easily be imitated in sed and awk.  The following are equivalent:

```<code>grep 'foo.bar'
sed -n -e '/foo.bar/p'
awk '/foo.bar/ { print $0 }'
awk '/foo.bar/'
</code>```

Oops, missed find.

find walks the filesystem tree, performing actions according to specified criterion.  For example,

```<code>find . -name '.*' -prune -o ! -name '*~' -type f -exec cat '{}' \;
</code>```

will walk all files and directories starting from the current directory ., excluding (and not descending into) any directories with names starting with ., and run cat on every file whose name does not end with ~ (with the result of printing out the contents of that file).  Again, this would be doable in AWK or Perl or many other programming languages (or even pure shell, in this example), but is easier and faster to write and understand with a special-purpose tool.

Body:
AWK is a programming language designed by Aho, Weinberger, and Kernighan.  gawk is one implementation of AWK, but there are several others, including mawk, and nawk.  It is a full-blown programming language with variables, control structures, and associative arrays, but generally optimized for dealing with the sorts of text-based data commonly found on UNIX systems.

sed is the stream editor, inspired by ed the editor.  It has a simple command set mostly limited to line-by-line editing.  sed commands can easily by imitated in awk.  The following are equivalent:

sed -e 's/foo/bar/g'
awk '{ gsub(/foo/, "bar"); print $0 }'
awk '{gsub(/foo/,"bar")}1'

grep finds text.  Basic grep functionality can easily be imitated in sed and awk.  The following are equivalent:

grep 'foo.bar'
sed -n -e '/foo.bar/p'
awk '/foo.bar/ { print $0 }'
awk '/foo.bar/'

Oops, missed find.

find walks the filesystem tree, performing actions according to specified criterion.  For example,

find . -name '.*' -prune -o ! -name '*~' -type f -exec cat '{}' \;

will walk all files and directories starting from the current directory ., excluding (and not descending into) any directories with names starting with ., and run cat on every file whose name does not end with ~ (with the result of printing out the contents of that file).  Again, this would be doable in AWK or Perl or many other programming languages (or even pure shell, in this example), but is easier and faster to write and understand with a special-purpose tool.


问:
Automate git commit of case-sensitive rename on case-insensitve file system
I'm on a case-insensitive file system (Windows) and changed the case of several files (a lot of files are affected, so I'm not eager to do it again).

I expected that committing the changes would be easy. But git is not aware of the changes, so I got stuck.

My feeling is that there must be a way to tell git: "Look at the names as they are currently stored on the disk. Commit them exactly like this, i.e. do git mv Foo foo if the case differs from the file in the index."

I've got TortoiseGit installed but couldn't find such an option. I tried to set core.ignorecase = true but this doesn't seem to make any difference.

Thanks,
TF

答:
You need to get git to refresh your files in the git index, however, it does not pick up on case sensitive changes on a case-intensive OS.

Instead, you can force it to update the index with

```<code>git rm -r --cached .
git add .
</code>```

Do not forget to commit next.

source

Body:
You need to get git to refresh your files in the git index, however, it does not pick up on case sensitive changes on a case-intensive OS.

Instead, you can force it to update the index with

git rm -r --cached .
git add .

Do not forget to commit next.

source


问:
Return both string and integer from a template function in C++
I am trying to write a generic function, using template, that is able to return bool, integer or char* or string.

```<code>template<typename entryType>
entryType getEntry(xml_node node, const char* entryKey)
{
    ...

    if (is_same<entryType, bool>::value) {
         return boolvalue; //returning a boolean
    }
    else if(is_same<entryType, int>::value) {
         return a; //this is an integer
    }
    else if (is_same<entryType, char*>::value) {
         return result; //this is a char*
    }
}
</code>```

and I would like to be able to call it like:

```<code>bool bPublisher = getEntry<bool>(node, "Publisher");
int QoS = getEntry<int>(node, "QualityOfService");
char* sBrokerUrl = getEntry<char*>(node, "BrokerUrl");
</code>```

as an alternative for the char*, a string would be also fine:

```<code>string sBrokerUrl = getEntry<string>(node, "BrokerUrl");
</code>```

I get errors like: "cannot convert from 'bool' to 'char*'. I understand the problem, the compiler is not able to detect that the code execution branch depends on the type I give. I just can't find a solution for that. Could anyone help me? Thanks.

答:
For older versions of C++, you can solve this by forwarding to one of the overloaded functions that return result through argument passed by reference:

```<code>template<typename entryType>
entryType getEntry(xml_node node, const char* entryKey)
{
    entryType result = entryType();
    this->getEntry(node, entryKey, result);
    return result;
}

void getEntry(xml_node node, const char* entryKey, bool& result);
void getEntry(xml_node node, const char* entryKey, int& result);
void getEntry(xml_node node, const char* entryKey, char const *& result);
</code>```

Or you can use std::enable_if (since C++11):

```<code>template<typename entryType>
typename std::enable_if<std::is_same<entryType, bool>::value, entryType>::type
    getEntry(xml_node node, const char* entryKey) {
    ...
}
</code>```

But first solution, IMO, is more readable. You can make overloaded functions private, if you don't want to expose them.

Body:
I am trying to write a generic function, using template, that is able to return bool, integer or char* or string.

template<typename entryType>
entryType getEntry(xml_node node, const char* entryKey)
{
    ...

    if (is_same<entryType, bool>::value) {
         return boolvalue; //returning a boolean
    }
    else if(is_same<entryType, int>::value) {
         return a; //this is an integer
    }
    else if (is_same<entryType, char*>::value) {
         return result; //this is a char*
    }
}

and I would like to be able to call it like:

bool bPublisher = getEntry<bool>(node, "Publisher");
int QoS = getEntry<int>(node, "QualityOfService");
char* sBrokerUrl = getEntry<char*>(node, "BrokerUrl");

as an alternative for the char*, a string would be also fine:

string sBrokerUrl = getEntry<string>(node, "BrokerUrl");

I get errors like: "cannot convert from 'bool' to 'char*'. I understand the problem, the compiler is not able to detect that the code execution branch depends on the type I give. I just can't find a solution for that. Could anyone help me? Thanks.

Body:
For older versions of C++, you can solve this by forwarding to one of the overloaded functions that return result through argument passed by reference:

template<typename entryType>
entryType getEntry(xml_node node, const char* entryKey)
{
    entryType result = entryType();
    this->getEntry(node, entryKey, result);
    return result;
}

void getEntry(xml_node node, const char* entryKey, bool& result);
void getEntry(xml_node node, const char* entryKey, int& result);
void getEntry(xml_node node, const char* entryKey, char const *& result);

Or you can use std::enable_if (since C++11):

template<typename entryType>
typename std::enable_if<std::is_same<entryType, bool>::value, entryType>::type
    getEntry(xml_node node, const char* entryKey) {
    ...
}

But first solution, IMO, is more readable. You can make overloaded functions private, if you don't want to expose them.


问:
Can someone help me point out my error here?
```<code>def target(heart):

    age = input("Enter your age: ")
    rest_heart = input("Enter your resting heart rate: ")
    intensity = input("Enter your heart intensity: ")
    max_heart = 220 - age
    reserve = max_heart - rest_heart
    return rest_heart + intensity * reserve

print(target(heart))
</code>```

Error message:

```<code>Traceback (most recent call last):

  File "<string>", line 9, in <module>

NameError: name 'heart' is not defined
</code>```

If someone could point out the error, that'd be greatly appreciated

答:
You didn't declared the variable heart in your code.

Here, the heart in target(heart) is useless because you try to pass a parameter to a function that doesn't use it.

Also, you call your function with print(target(heart)) but you didn't set heart in this scope, it could work if you put heart = 0 (or anything) above your code but this parameter will still be useless.

Body:
def target(heart):

    age = input("Enter your age: ")
    rest_heart = input("Enter your resting heart rate: ")
    intensity = input("Enter your heart intensity: ")
    max_heart = 220 - age
    reserve = max_heart - rest_heart
    return rest_heart + intensity * reserve

print(target(heart))

Error message:

Traceback (most recent call last):

  File "<string>", line 9, in <module>

NameError: name 'heart' is not defined

If someone could point out the error, that'd be greatly appreciated


问:
Why does Python have a limit on the number of static blocks that can be nested?
The number of statically nested blocks in Python is limited to 20.
That is, nesting 19 for loops will be fine (although excessively time consuming; O(n^19) is insane), but nesting 20 will fail with:

```<code>SyntaxError: too many statically nested blocks
</code>```

What is the underlying reason for having such a limit?
Is there a way to increase the limit?

答:
This has to do with the blockstack, which is a stack of the byte code addresses, and is used to execute code blocks such as loops and exceptions.

It just so happens that a version of C (older than C99) had set this limit to 20, and since the CPython interpreter is built with C, the same convention has been followed:

#define CO_MAXBLOCKS 20 /* Max static block nesting within a function */
```

<p>The constant <code>20</code> seems to be set out of convention, and nothing more.</p>

<p>[Links courtesy Christian Dean.]</p>

<hr>

<h3>Why is the limit 20?</h3>

<p>If the argument of convention isn't convincing, then take a look at <em>The Zen of Python</em>:</p>

```In [4]: import this
The Zen of Python, by Tim Peters

...
Flat is better than nested.
...
```

How can you increase this value?

Since this value is a hardcoded constant, the only way to change it to effect in your programs is to rebuild your python distribution and run your script on the new build.

Download the cpython source code from github

Navigate to cpython/Include/code.h

Change the value of CO_MAXBLOCKS to anything greater than 20

Recompile Python (disable tests, they'll complain)

Body:
The number of statically nested blocks in Python is limited to 20.
That is, nesting 19 for loops will be fine (although excessively time consuming; O(n^19) is insane), but nesting 20 will fail with:

SyntaxError: too many statically nested blocks

What is the underlying reason for having such a limit?
Is there a way to increase the limit?

Body:
This has to do with the blockstack, which is a stack of the byte code addresses, and is used to execute code blocks such as loops and exceptions.

It just so happens that a version of C (older than C99) had set this limit to 20, and since the CPython interpreter is built with C, the same convention has been followed:

#define CO_MAXBLOCKS 20 /* Max static block nesting within a function */

The constant 20 seems to be set out of convention, and nothing more.

[Links courtesy Christian Dean.]

Why is the limit 20?

If the argument of convention isn't convincing, then take a look at The Zen of Python:

In [4]: import this
The Zen of Python, by Tim Peters

...
Flat is better than nested.
...

How can you increase this value?

Since this value is a hardcoded constant, the only way to change it to effect in your programs is to rebuild your python distribution and run your script on the new build.

Download the cpython source code from github

Navigate to cpython/Include/code.h

Change the value of CO_MAXBLOCKS to anything greater than 20

Recompile Python (disable tests, they'll complain)