问:
how to convert const WCHAR * to const char *
```<code>CString output ;
const WCHAR* wc = L"Hellow World" ;
if( wc != NULL )
{
     output.Append(wc);
}
printf( "output: %s\n",output.GetBuffer(0) );
</code>```

答:
My code for Linux

```<code>// Debian GNU/Linux 8 "Jessie" (amd64)

#include <locale.h>
#include <stdlib.h>
#include <stdio.h>

// Use wcstombs(3) to convert Unicode-string (wchar_t *) to UTF-8 (char *)
// http://man7.org/linux/man-pages/man3/wcstombs.3.html

int f(const wchar_t *wcs) {
        setlocale(LC_ALL,"ru_RU.UTF-8");
        printf("Sizeof wchar_t: %d\n", sizeof(wchar_t));
        // on Windows, UTF-16 is internal Unicode encoding (UCS2 before WinXP)
        // on Linux, UCS4 is internal Unicode encoding
        for (int i = 0; wcs[i] > 0; i++) printf("%2d %08X\n",i,wcs[i]);
        char s[256];
        size_t len = wcstombs(s,wcs,sizeof(s));
        if (len > 0) {
                s[len] = '\0';
                printf("mbs: %s\n",s);
                for (int i = 0; i < len; i++)
                        printf("%2d %02X\n",i,(unsigned char)s[i]);
                printf("Size of mbs, in bytes: %d\n",len);
                return 0;
        }
        else return -1;
}

int main() {
        f(L"Привет"); // 6 symbols
        return 0;
}
</code>```

How to build

```<code>#!/bin/sh
NAME=`basename $0 .sh`
CC=/usr/bin/g++-4.9
INCS="-I."
LIBS="-L."
$CC ${NAME}.c -o _${NAME} $INCS $LIBS
</code>```

Output

```<code>$ ./_test
Sizeof wchar_t: 4
 0 0000041F
 1 00000440
 2 00000438
 3 00000432
 4 00000435
 5 00000442
mbs: Привет
 0 D0
 1 9F
 2 D1
 3 80
 4 D0
 5 B8
 6 D0
 7 B2
 8 D0
 9 B5
10 D1
11 82
Size of mbs, in bytes: 12
</code>```

Body:
My code for Linux

// Debian GNU/Linux 8 "Jessie" (amd64)

#include <locale.h>
#include <stdlib.h>
#include <stdio.h>

// Use wcstombs(3) to convert Unicode-string (wchar_t *) to UTF-8 (char *)
// http://man7.org/linux/man-pages/man3/wcstombs.3.html

int f(const wchar_t *wcs) {
        setlocale(LC_ALL,"ru_RU.UTF-8");
        printf("Sizeof wchar_t: %d\n", sizeof(wchar_t));
        // on Windows, UTF-16 is internal Unicode encoding (UCS2 before WinXP)
        // on Linux, UCS4 is internal Unicode encoding
        for (int i = 0; wcs[i] > 0; i++) printf("%2d %08X\n",i,wcs[i]);
        char s[256];
        size_t len = wcstombs(s,wcs,sizeof(s));
        if (len > 0) {
                s[len] = '\0';
                printf("mbs: %s\n",s);
                for (int i = 0; i < len; i++)
                        printf("%2d %02X\n",i,(unsigned char)s[i]);
                printf("Size of mbs, in bytes: %d\n",len);
                return 0;
        }
        else return -1;
}

int main() {
        f(L"Привет"); // 6 symbols
        return 0;
}

How to build

#!/bin/sh
NAME=`basename $0 .sh`
CC=/usr/bin/g++-4.9
INCS="-I."
LIBS="-L."
$CC ${NAME}.c -o _${NAME} $INCS $LIBS

Output

$ ./_test
Sizeof wchar_t: 4
 0 0000041F
 1 00000440
 2 00000438
 3 00000432
 4 00000435
 5 00000442
mbs: Привет
 0 D0
 1 9F
 2 D1
 3 80
 4 D0
 5 B8
 6 D0
 7 B2
 8 D0
 9 B5
10 D1
11 82
Size of mbs, in bytes: 12


来源: stackexchange

问:
How do I use SortField to sort my data numerically in Flex/ActionScript?
From the documentation:

SortField () constructor

```<code>public function SortField(name:String = null, caseInsensitive:Boolean = false, descending:Boolean = false, numeric:Object = null)
</code>```

I'm confused on the last part - numeric:Object = null.

Here is my function:

```<code>private function createXMLDataProvider():XMLListCollection{
    var sort:Sort = new Sort();
    sort.fields = [new SortField("@sortorder",true,false,true), new SortField("@label")];
    var searchTypesCollection:XMLListCollection =
        new XMLListCollection(getAssociations(_appData.searchTypes, "category", searchType));
    searchTypesCollection.sort = sort;
    searchTypesCollection.refresh();
    return searchTypesCollection;
}
</code>```

On this line:

```<code>sort.fields = [new SortField("@sortorder",true,false,true), new SortField("@label")];
</code>```

The first SortField is a number but is being compared like it is text. What should I be putting where it says true?

Also from the documentation:

Specifies that if the field being sorted contains numeric (number/int/uint) values, or string representations of numeric values, the comparator use a numeric comparison. If this property is false, fields with string representations of numbers are sorted using strings comparison, so 100 precedes 99, because "1" is a lower string value than "9". If this property is null, the first data item is introspected to see if it is a number or string and the sort proceeds based on that introspection.

The default value is false.

答:
Have a look here for an example of sorting an XMLListCollection:

http://blog.flexexamples.com/2007/08/05/sorting-an-arraycollection-using-the-sortfield-and-sort-classes/

If you scroll down to Vivek's comment, there's an example and a follow-up comment from Peter deHaan.  It looks like he's just omitting the caseInsensitive property, rather than setting it explicitly in the constructor, e.g.:

```<code>var sortField:SortField = new SortField(value);
sortField.numeric = true;
sortField.descending = true;

var sort:Sort = new Sort();
sort.fields = [sortField];
xmlListColl.sort = sort;
return xmlListColl.refresh();
</code>```

Hope that helps! Incidentally, true is correct for the numeric property -- I'm not sure why it accepts Object; it looks like in Flex 2, it was a Boolean, and in Gumbo, it's still an Object, although the following line's been added to the Gumbo docs:

When this property is modified, it
  dispatches the numericChanged event.

A clue, perhaps?  Nevertheless, a Boolean value is fine, yes.

OwnerDisplayName: leif

ContentLicense: CC BY-SA 3.0

Body:
From the documentation:

SortField () constructor

public function SortField(name:String = null, caseInsensitive:Boolean = false, descending:Boolean = false, numeric:Object = null)

I'm confused on the last part - numeric:Object = null.

Here is my function:

private function createXMLDataProvider():XMLListCollection{
    var sort:Sort = new Sort();
    sort.fields = [new SortField("@sortorder",true,false,true), new SortField("@label")];
    var searchTypesCollection:XMLListCollection =
        new XMLListCollection(getAssociations(_appData.searchTypes, "category", searchType));
    searchTypesCollection.sort = sort;
    searchTypesCollection.refresh();
    return searchTypesCollection;
}

On this line:

sort.fields = [new SortField("@sortorder",true,false,true), new SortField("@label")];

The first SortField is a number but is being compared like it is text. What should I be putting where it says true?

Also from the documentation:

Specifies that if the field being sorted contains numeric (number/int/uint) values, or string representations of numeric values, the comparator use a numeric comparison. If this property is false, fields with string representations of numbers are sorted using strings comparison, so 100 precedes 99, because "1" is a lower string value than "9". If this property is null, the first data item is introspected to see if it is a number or string and the sort proceeds based on that introspection.

The default value is false.

Body:
Have a look here for an example of sorting an XMLListCollection:

http://blog.flexexamples.com/2007/08/05/sorting-an-arraycollection-using-the-sortfield-and-sort-classes/

If you scroll down to Vivek's comment, there's an example and a follow-up comment from Peter deHaan.  It looks like he's just omitting the caseInsensitive property, rather than setting it explicitly in the constructor, e.g.:

var sortField:SortField = new SortField(value);
sortField.numeric = true;
sortField.descending = true;

var sort:Sort = new Sort();
sort.fields = [sortField];
xmlListColl.sort = sort;
return xmlListColl.refresh();

Hope that helps! Incidentally, true is correct for the numeric property -- I'm not sure why it accepts Object; it looks like in Flex 2, it was a Boolean, and in Gumbo, it's still an Object, although the following line's been added to the Gumbo docs:

When this property is modified, it
  dispatches the numericChanged event.

A clue, perhaps?  Nevertheless, a Boolean value is fine, yes.

OwnerDisplayName: Christian Nunciato

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Christian Nunciato


问:
Git ignore particular files
I've been playing around with it for a while and I like it very much.
Let me describe my case.

I have two computers where I have my repositories and a remote repository.

in my files I have one configuration file which differs on both computers. so when I do pull on my computers I don't need that config file to be pulled, but everything else. How can I achieve that?

I've read about .gitignore files but I can't figure out how they work or are they the thing that I need in my case.

答:
Please also note that

```<code>git update-index --assume-unchanged file
</code>```

will not help if you try to switch branch

```<code>$ git checkout master
error: Your local changes to the following files would be overwritten by checkout:
    file
Please commit your changes or stash them before you switch branches.
Aborting
</code>```

Title: Git ignore particular files

Body:
Please also note that

git update-index --assume-unchanged file

will not help if you try to switch branch

$ git checkout master
error: Your local changes to the following files would be overwritten by checkout:
    file
Please commit your changes or stash them before you switch branches.
Aborting


问:
How to make a table in ReactJS sortable?
I am building a simple app in ReactJS that works with a JSON array by calling a certain API. I am then populating the results of the array in a table. I now wanted to make the columns of the table sortable. Can someone help me with that. Here is my code.</p>

```<code>class ParentComponent extends Component {
  constructor(props) {
    super(props);
    this.state = { data: [] };
  }

  componentDidMount() {
    fetch("http://hostname:xxxx/yyyy/zzzz")
      .then(function(response) {
        return response.json();
      })
      .then(items => this.setState({ data: items }));
  }

  render() {
    var newdata = this.state.data;

    return (
      <table className="m-table">
        <thead>
          <tr>
            <th>AccountName</th>
            <th>ContractValue</th>
          </tr>
        </thead>
        <tbody>
          {newdata.map(function(account, index) {
            return (
              <tr key={index} data-item={account}>
                <td data-title="Account">{account.accountname}</td>
                <td data-title="Value">{account.negotiatedcontractvalue}</td>
              </tr>
            );
          })}
        </tbody>
      </table>
    );
  }
}

export default ParentComponent;
</code>```

答:
Here's a quick example of how to do it, based on my comment:</p>

```<code>class ParentComponent extends Component {
  constructor(props) {
    super(props);
    this.state = { data: [] };
    this.onSort = this.onSort.bind(this)
  }

  componentDidMount() {
    fetch("http://hostname:xxxx/yyyy/zzzz")
      .then(function(response) {
        return response.json();
      })
      .then(items => this.setState({ data: items }));
  }

  onSort(event, sortKey){
    /*
    assuming your data is something like
    [
      {accountname:'foo', negotiatedcontractvalue:'bar'},
      {accountname:'monkey', negotiatedcontractvalue:'spank'},
      {accountname:'chicken', negotiatedcontractvalue:'dance'},
    ]
    */
    const data = this.state.data;
    data.sort((a,b) => a[sortKey].localeCompare(b[sortKey]))
    this.setState({data})
  }

  render() {
    var newdata = this.state.data;

    return (
      <table className="m-table">
        <thead>
          <tr>
            <th onClick={e => this.onSort(e, 'accountname')}>AccountName</th>
            <th onClick={e => this.onSort(e, 'negotiatedcontractvalue')}>ContractValue</th>
          </tr>
        </thead>
        <tbody>
          {newdata.map(function(account, index) {
            return (
              <tr key={index} data-item={account}>
                <td data-title="Account">{account.accountname}</td>
                <td data-title="Value">{account.negotiatedcontractvalue}</td>
              </tr>
            );
          })}
        </tbody>
      </table>
    );
  }
}

export default ParentComponent;
</code>```

Body:
I am building a simple app in ReactJS that works with a JSON array by calling a certain API. I am then populating the results of the array in a table. I now wanted to make the columns of the table sortable. Can someone help me with that. Here is my code.

class ParentComponent extends Component {
  constructor(props) {
    super(props);
    this.state = { data: [] };
  }

  componentDidMount() {
    fetch("http://hostname:xxxx/yyyy/zzzz")
      .then(function(response) {
        return response.json();
      })
      .then(items => this.setState({ data: items }));
  }

  render() {
    var newdata = this.state.data;

    return (

            AccountName
            ContractValue

          {newdata.map(function(account, index) {
            return (

                {account.accountname}
                {account.negotiatedcontractvalue}

            );
          })}

    );
  }
}

export default ParentComponent;

Body:
Here's a quick example of how to do it, based on my comment:

class ParentComponent extends Component {
  constructor(props) {
    super(props);
    this.state = { data: [] };
    this.onSort = this.onSort.bind(this)
  }

  componentDidMount() {
    fetch("http://hostname:xxxx/yyyy/zzzz")
      .then(function(response) {
        return response.json();
      })
      .then(items => this.setState({ data: items }));
  }

  onSort(event, sortKey){
    /*
    assuming your data is something like
    [
      {accountname:'foo', negotiatedcontractvalue:'bar'},
      {accountname:'monkey', negotiatedcontractvalue:'spank'},
      {accountname:'chicken', negotiatedcontractvalue:'dance'},
    ]
    */
    const data = this.state.data;
    data.sort((a,b) => a[sortKey].localeCompare(b[sortKey]))
    this.setState({data})
  }

  render() {
    var newdata = this.state.data;

    return (
      <table className="m-table">
        <thead>
          <tr>
            <th onClick={e => this.onSort(e, 'accountname')}>AccountName</th>
            <th onClick={e => this.onSort(e, 'negotiatedcontractvalue')}>ContractValue</th>
          </tr>
        </thead>
        <tbody>
          {newdata.map(function(account, index) {
            return (
              <tr key={index} data-item={account}>
                <td data-title="Account">{account.accountname}</td>
                <td data-title="Value">{account.negotiatedcontractvalue}</td>
              </tr>
            );
          })}
        </tbody>
      </table>
    );
  }
}

export default ParentComponent;


问:
Jackson Deserialize Abstract Classes
I am trying to deserialize an object using JSON ObjectMapper. I see the below error when trying to deserialize

com.fasterxml.jackson.databind.JsonMappingException: Can not construct
  instance of com.phoenix.types.OrderItem:
  abstract types either need to be mapped to concrete types, have custom
  deserializer, or contain additional type information  at [Source:
  java.io.StringReader@4bb33f74; line: 112, column: 7] (through
  reference chain:
  com.phoenix.types.GenerateRequest["order"]->com.phoenix.types.Order["orderItems"]->Object[][0])
    at
  com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:261)
    at
  com.fasterxml.jackson.databind.DeserializationContext.instantiationException(DeserializationContext.java:1456)
    at
  com.fasterxml.jackson.databind.DeserializationContext.handleMissingInstantiator(DeserializationContext.java:1012)
    at
  com.fasterxml.jackson.databind.deser.AbstractDeserializer.deserialize(AbstractDeserializer.java:149)
    at
  com.fasterxml.jackson.databind.deser.std.ObjectArrayDeserializer.deserialize(ObjectArrayDeserializer.java:196)
    at
  com.fasterxml.jackson.databind.deser.std.ObjectArrayDeserializer.deserialize(ObjectArrayDeserializer.java:20)
    at
  com.fasterxml.jackson.databind.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:499)
    at
  com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:101)
    at
  com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:276)
    at
  com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:140)
    at
  com.fasterxml.jackson.databind.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:499)
    at
  com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:101)
    at
  com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:276)
    at
  com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:140)
    at
  com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3789)
    at
  com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2833)

I came across this post for performing polymorphic deserialization.  This basically provides the solution for resolving the error listed above. The classes (In this instance OrderItem etc) that I am using for deserialization are part of a jar file.  However is there a way to define JsonDeserialize as part of objectmapper when trying to deserialize instead of adding annotation to the class itself as I don't have access to it.

答:
Yes, you can write your own Custom Deserializer for the abstract class. This deserializer will have to determine which concrete class the JSON represents, and instantiate an instance of it.

There is likely a more idiomatic way of doing this, but here is a quick-and-dirty example:

```<code>public class Test {
    public static void main(String... args) throws IOException {
        final ObjectMapper mapper = new ObjectMapper();
        final SimpleModule module = new SimpleModule();
        module.addDeserializer(Animal.class, new AnimalDeserializer());
        mapper.registerModule(module);

        final String json = "{\"aGoodBoy\": true}";
        final Animal animal = mapper.readValue(json, Animal.class);
        System.out.println(animal.talk());
    }

    public static abstract class Animal {
        public abstract String talk();
    }

    public static class Fish extends Animal {
        @Override
        public String talk() {
            return "blub blub I'm a dumb fish";
        }
    }

    public static class Dog extends Animal {
        public boolean aGoodBoy;

        @Override
        public String talk() {
            return "I am a " + (aGoodBoy ? "good" : "bad") + " dog";
        }
    }

    public static class AnimalDeserializer extends StdDeserializer<Animal> {
        protected AnimalDeserializer() {
            this(null);
        }

        protected AnimalDeserializer(final Class<?> vc) {
            super(vc);
        }

        @Override
        public Animal deserialize(final JsonParser parser, final DeserializationContext context)
        throws IOException, JsonProcessingException {
            final JsonNode node = parser.getCodec().readTree(parser);
            final ObjectMapper mapper = (ObjectMapper)parser.getCodec();
            if (node.has("aGoodBoy")) {
                return mapper.treeToValue(node, Dog.class);
            } else {
                return mapper.treeToValue(node, Fish.class);
            }
        }
    }
}
</code>```

Title: Jackson Deserialize Abstract Classes

Body:
Yes, you can write your own Custom Deserializer for the abstract class. This deserializer will have to determine which concrete class the JSON represents, and instantiate an instance of it.

There is likely a more idiomatic way of doing this, but here is a quick-and-dirty example:

public class Test {
    public static void main(String... args) throws IOException {
        final ObjectMapper mapper = new ObjectMapper();
        final SimpleModule module = new SimpleModule();
        module.addDeserializer(Animal.class, new AnimalDeserializer());
        mapper.registerModule(module);

        final String json = "{\"aGoodBoy\": true}";
        final Animal animal = mapper.readValue(json, Animal.class);
        System.out.println(animal.talk());
    }

    public static abstract class Animal {
        public abstract String talk();
    }

    public static class Fish extends Animal {
        @Override
        public String talk() {
            return "blub blub I'm a dumb fish";
        }
    }

    public static class Dog extends Animal {
        public boolean aGoodBoy;

        @Override
        public String talk() {
            return "I am a " + (aGoodBoy ? "good" : "bad") + " dog";
        }
    }

    public static class AnimalDeserializer extends StdDeserializer<Animal> {
        protected AnimalDeserializer() {
            this(null);
        }

        protected AnimalDeserializer(final Class<?> vc) {
            super(vc);
        }

        @Override
        public Animal deserialize(final JsonParser parser, final DeserializationContext context)
        throws IOException, JsonProcessingException {
            final JsonNode node = parser.getCodec().readTree(parser);
            final ObjectMapper mapper = (ObjectMapper)parser.getCodec();
            if (node.has("aGoodBoy")) {
                return mapper.treeToValue(node, Dog.class);
            } else {
                return mapper.treeToValue(node, Fish.class);
            }
        }
    }
}


问:
What is a good name for this state-like monad
This is something of a combination of State and Writer.  I have checked the monad laws.

```<code>newtype M s a = M { runM :: s -> (s,a) }

instance (Monoid s) => Monad (M s) where
    return = M . const . (mempty,)
    m >>= f = M $ \s ->
        let (s' ,x) = runM m s
            (s'',y) = runM (f x) (s `mappend` s')
        in (s' `mappend` s'', y)
</code>```

StateWriter seems kinda lame.

答:
"Introspective Writer"? It seems that the interesting you can do with it (that you can't do with Writer) is to write an introspect function that examines the state/output and changes it:

```<code>introspect :: (s -> s) -> M s ()
introspect f = M $ \s -> (f s, ())
</code>```

I can't see that you can do this for writer, I think you'd have to make do with a post-transformer instead:

```<code>postW :: Writer w a -> (w -> w) -> Writer w a
postW ma f = Writer $ let (w,a) = getWriter ma in (f w,a)
</code>```

Body:
This is something of a combination of State and Writer.  I have checked the monad laws.

newtype M s a = M { runM :: s -> (s,a) }

instance (Monoid s) => Monad (M s) where
    return = M . const . (mempty,)
    m >>= f = M $ \s ->
        let (s' ,x) = runM m s
            (s'',y) = runM (f x) (s `mappend` s')
        in (s' `mappend` s'', y)

StateWriter seems kinda lame.

Body:
"Introspective Writer"? It seems that the interesting you can do with it (that you can't do with Writer) is to write an introspect function that examines the state/output and changes it:

introspect :: (s -> s) -> M s ()
introspect f = M $ \s -> (f s, ())

I can't see that you can do this for writer, I think you'd have to make do with a post-transformer instead:

postW :: Writer w a -> (w -> w) -> Writer w a
postW ma f = Writer $ let (w,a) = getWriter ma in (f w,a)


问:
jQuery tabs - Selecting all menu ul elements
I'm new to using jQuery and my first bigger improvement to static website is a jQuery tabs which let's me switch main page divs on sidebar and topbar menus.
I can't seem to get the script to work with every nav class element.
As of right now it's working on said elements: Poradnik 1,2,3,4 and I'd also want them to work on Strona główna, Spis treści, Poradniki and O autorze. Basically all elements that are located under nav.
What should I change? Could anyone help me out with it? Thank you.

Below I'll put the code for the required elements.

$(document).ready(function(){

 $('ul.nav ul li').click(function(){
  var tab_id = $(this).attr('data-tab');

  $('ul.nav ul li').removeClass('current');
  $('.tab-content').removeClass('current');

  $(this).addClass('current');
  $("#"+tab_id).addClass('current');
 })
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.tab-content{
 display: none;
 padding: 15px;
}

.tab-content.current{
 display: inherit;
}
.topmenu {
 width: 875px;
 display: block;
 position: relative;
 float: left;
 height: 90px;
 font-size: 20px;
}
.topmenu ul {
 padding: 25px;
}
.topmenu ul.nav a, ul.nav a:visited {
 display: block;
 width: 120px;
 height: 25px;
 border-top-width: 1px;
 border-right-width: 1px;
 border-bottom-width: 1px;
 border-left-width: 1px;
 border-top-style: none;
 border-right-style: none;
 border-bottom-style: none;
 border-left-style: none;
 text-align: center;
 padding: 5px;
}
.topmenu ul.nav li a:hover {
 width: 120px;
 height: 25px;
 background: #D2E2FF;
 color: #000;
 border: 1px solid black;
 padding-top: 4px;
 padding-right: 4px;
 padding-bottom: 8px;
 padding-left: 4px;
}

.topmenu ul.nav li:hover ul {
 left: 0px;
 top: 38px;
 padding: 0px;
 border:solid 1px;
}
.topmenu ul.nav li:hover ul li a {
 padding: 6px;
 width: 250px;
 background-color: #FFFFFF;
 border-top-width: 1px;
 border-right-width: 1px;
 border-bottom-width: 1px;
 border-left-width: 1px;
 border-top-style: solid;
 border-bottom-style: solid;
 border-top-color: #000;
 border-right-color: #000;
 border-bottom-color: #000;
 border-left-color: #000;
 border-right-style: none;
 border-left-style: none;
}

ul.nav {
 list-style: none;
 margin-bottom: 15px;
}
ul.nav li {
float:left;
}
ul.nav a, ul.nav a:visited {
 display: block;
 width: 25px;
 height: 25px;
 text-decoration: none;
 background-color: #FFFFFF;
 padding: 3px;
}

ul.nav li a:hover {
 background-color: #D2E2FF;
 color: #000;
 border: solid 1px black;
 padding: 2px;
}

ul.nav ul a:hover {
 background-color: #D2E2FF;
 color: #000;
 padding: 3px;
 border-top-style: none;
 border-right-style: none;
 border-bottom-style: none;
 border-left-style: none;
}

ul.nav li a:focus, ul.nav li a:active {
 color: #000;
 text-decoration: underline;
}

ul.nav ul {
 position: absolute;
 left: -9999px;
 top: -9999px;
 list-style-type: none;
}
ul.nav li:hover {
 position: relative;
}

ul.nav li:hover ul {
 left: 30px;
 top: 0px;
 padding: 0px;
 border: solid 1px;
}

ul.nav li:hover ul li a {
 padding: 3px;
 width:300px;
 background-color: #FFFFFF;
}

ul.nav li:hover ul li a:hover {
 background: #D2E2FF;
 color: #000;
}</code>```

Strona główna

Spis treści

Poradniki

Poradnik 1

Poradnik 2

Poradnik 3

Poradnik 4

O autorze

Strona główna

Strona główna

Spis treści

Spis treści

Poradnik 1

Poradnik 1

Poradnik 2

Poradnik 2

Poradnik 3

Poradnik 3

Poradnik 4

Poradnik 4

O autorze

O autorze

```

答:
This should work now. The problem is that when you click on one of the inner
's, you are also clicking on one of the outer
's. To avoid this, use this JQuery/JavaScript function:

```<code>$(document).ready(function() {
  $('ul.nav li:not(.innerNav)').click(function() {
    var tab_id = $(this).attr('data-tab');
    $('.ul.nav > li').removeClass('current');
    $('.tab-content').removeClass('current');
    $(this).addClass('current');
    $("#" + tab_id).addClass('current');
  });
});
</code>```

and give the
 with the
 inside, the class innerNav.

$(document).ready(function() {
  $('ul.nav li:not(.innerNav)').click(function() {
    var tab_id = $(this).attr('data-tab');
    $('.ul.nav > li').removeClass('current');
    $('.tab-content').removeClass('current');
    $(this).addClass('current');
    $("#" + tab_id).addClass('current');
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.tab-content {
  display: none;
  padding: 15px;
}
.tab-content.current {
  display: inherit;
}
.topmenu {
  width: 875px;
  display: block;
  position: relative;
  float: left;
  height: 90px;
  font-size: 20px;
}
.topmenu ul {
  padding: 25px;
}
.topmenu ul.nav a, ul.nav a:visited {
  display: block;
  width: 120px;
  height: 25px;
  border-top-width: 1px;
  border-right-width: 1px;
  border-bottom-width: 1px;
  border-left-width: 1px;
  border-top-style: none;
  border-right-style: none;
  border-bottom-style: none;
  border-left-style: none;
  text-align: center;
  padding: 5px;
}
.topmenu ul.nav li a:hover {
  width: 120px;
  height: 25px;
  background: #D2E2FF;
  color: #000;
  border: 1px solid black;
  padding-top: 4px;
  padding-right: 4px;
  padding-bottom: 8px;
  padding-left: 4px;
}
.topmenu ul.nav li:hover ul {
  left: 0px;
  top: 38px;
  padding: 0px;
  border: solid 1px;
}
.topmenu ul.nav li:hover ul li a {
  padding: 6px;
  width: 250px;
  background-color: #FFFFFF;
  border-top-width: 1px;
  border-right-width: 1px;
  border-bottom-width: 1px;
  border-left-width: 1px;
  border-top-style: solid;
  border-bottom-style: solid;
  border-top-color: #000;
  border-right-color: #000;
  border-bottom-color: #000;
  border-left-color: #000;
  border-right-style: none;
  border-left-style: none;
}
ul.nav {
  list-style: none;
  margin-bottom: 15px;
}
ul.nav li {
  float: left;
}
ul.nav a, ul.nav a:visited {
  display: block;
  width: 25px;
  height: 25px;
  text-decoration: none;
  background-color: #FFFFFF;
  padding: 3px;
}
ul.nav li a:hover {
  background-color: #D2E2FF;
  color: #000;
  border: solid 1px black;
  padding: 2px;
}
ul.nav ul a:hover {
  background-color: #D2E2FF;
  color: #000;
  padding: 3px;
  border-top-style: none;
  border-right-style: none;
  border-bottom-style: none;
  border-left-style: none;
}
ul.nav li a:focus, ul.nav li a:active {
  color: #000;
  text-decoration: underline;
}
ul.nav ul {
  position: absolute;
  left: -9999px;
  top: -9999px;
  list-style-type: none;
}
ul.nav li:hover {
  position: relative;
}
ul.nav li:hover ul {
  left: 30px;
  top: 0px;
  padding: 0px;
  border: solid 1px;
}
ul.nav li:hover ul li a {
  padding: 3px;
  width: 300px;
  background-color: #FFFFFF;
}
ul.nav li:hover ul li a:hover {
  background: #D2E2FF;
  color: #000;
}</code>```

<!DOCTYPE html>

  <title></title>

        Strona główna

        Spis treści

        Poradniki

            Poradnik 1

            Poradnik 2

            Poradnik 3

            Poradnik 4

        O autorze

Strona główna

Strona główna

Spis treści

Spis treści

Poradnik 1

Poradnik 1

Poradnik 2

Poradnik 2

Poradnik 3

Poradnik 3

Poradnik 4

Poradnik 4

O autorze

O autorze

```

Body:
I'm new to using jQuery and my first bigger improvement to static website is a jQuery tabs which let's me switch main page divs on sidebar and topbar menus.
I can't seem to get the script to work with every nav class element.
As of right now it's working on said elements: Poradnik 1,2,3,4 and I'd also want them to work on Strona główna, Spis treści, Poradniki and O autorze. Basically all elements that are located under nav.
What should I change? Could anyone help me out with it? Thank you.

Below I'll put the code for the required elements.

$(document).ready(function(){

 $('ul.nav ul li').click(function(){
  var tab_id = $(this).attr('data-tab');

  $('ul.nav ul li').removeClass('current');
  $('.tab-content').removeClass('current');

  $(this).addClass('current');
  $("#"+tab_id).addClass('current');
 })
})

.tab-content{
 display: none;
 padding: 15px;
}

.tab-content.current{
 display: inherit;
}
.topmenu {
 width: 875px;
 display: block;
 position: relative;
 float: left;
 height: 90px;
 font-size: 20px;
}
.topmenu ul {
 padding: 25px;
}
.topmenu ul.nav a, ul.nav a:visited {
 display: block;
 width: 120px;
 height: 25px;
 border-top-width: 1px;
 border-right-width: 1px;
 border-bottom-width: 1px;
 border-left-width: 1px;
 border-top-style: none;
 border-right-style: none;
 border-bottom-style: none;
 border-left-style: none;
 text-align: center;
 padding: 5px;
}
.topmenu ul.nav li a:hover {
 width: 120px;
 height: 25px;
 background: #D2E2FF;
 color: #000;
 border: 1px solid black;
 padding-top: 4px;
 padding-right: 4px;
 padding-bottom: 8px;
 padding-left: 4px;
}

.topmenu ul.nav li:hover ul {
 left: 0px;
 top: 38px;
 padding: 0px;
 border:solid 1px;
}
.topmenu ul.nav li:hover ul li a {
 padding: 6px;
 width: 250px;
 background-color: #FFFFFF;
 border-top-width: 1px;
 border-right-width: 1px;
 border-bottom-width: 1px;
 border-left-width: 1px;
 border-top-style: solid;
 border-bottom-style: solid;
 border-top-color: #000;
 border-right-color: #000;
 border-bottom-color: #000;
 border-left-color: #000;
 border-right-style: none;
 border-left-style: none;
}

ul.nav {
 list-style: none;
 margin-bottom: 15px;
}
ul.nav li {
float:left;
}
ul.nav a, ul.nav a:visited {
 display: block;
 width: 25px;
 height: 25px;
 text-decoration: none;
 background-color: #FFFFFF;
 padding: 3px;
}

ul.nav li a:hover {
 background-color: #D2E2FF;
 color: #000;
 border: solid 1px black;
 padding: 2px;
}

ul.nav ul a:hover {
 background-color: #D2E2FF;
 color: #000;
 padding: 3px;
 border-top-style: none;
 border-right-style: none;
 border-bottom-style: none;
 border-left-style: none;
}

ul.nav li a:focus, ul.nav li a:active {
 color: #000;
 text-decoration: underline;
}

ul.nav ul {
 position: absolute;
 left: -9999px;
 top: -9999px;
 list-style-type: none;
}
ul.nav li:hover {
 position: relative;
}

ul.nav li:hover ul {
 left: 30px;
 top: 0px;
 padding: 0px;
 border: solid 1px;
}

ul.nav li:hover ul li a {
 padding: 3px;
 width:300px;
 background-color: #FFFFFF;
}

ul.nav li:hover ul li a:hover {
 background: #D2E2FF;
 color: #000;
}

Strona główna

Spis treści

Poradniki

Poradnik 1

Poradnik 2

Poradnik 3

Poradnik 4

O autorze

Strona główna

Strona główna

Spis treści

Spis treści

Poradnik 1

Poradnik 1

Poradnik 2

Poradnik 2

Poradnik 3

Poradnik 3

Poradnik 4

Poradnik 4

O autorze

O autorze

Body:
This should work now. The problem is that when you click on one of the inner <li>'s, you are also clicking on one of the outer <li>'s. To avoid this, use this JQuery/JavaScript function:

$(document).ready(function() {
  $('ul.nav li:not(.innerNav)').click(function() {
    var tab_id = $(this).attr('data-tab');
    $('.ul.nav > li').removeClass('current');
    $('.tab-content').removeClass('current');
    $(this).addClass('current');
    $("#" + tab_id).addClass('current');
  });
});

and give the <li> with the <ul> inside, the class innerNav.

$(document).ready(function() {
  $('ul.nav li:not(.innerNav)').click(function() {
    var tab_id = $(this).attr('data-tab');
    $('.ul.nav > li').removeClass('current');
    $('.tab-content').removeClass('current');
    $(this).addClass('current');
    $("#" + tab_id).addClass('current');
  });
});

.tab-content {
  display: none;
  padding: 15px;
}
.tab-content.current {
  display: inherit;
}
.topmenu {
  width: 875px;
  display: block;
  position: relative;
  float: left;
  height: 90px;
  font-size: 20px;
}
.topmenu ul {
  padding: 25px;
}
.topmenu ul.nav a, ul.nav a:visited {
  display: block;
  width: 120px;
  height: 25px;
  border-top-width: 1px;
  border-right-width: 1px;
  border-bottom-width: 1px;
  border-left-width: 1px;
  border-top-style: none;
  border-right-style: none;
  border-bottom-style: none;
  border-left-style: none;
  text-align: center;
  padding: 5px;
}
.topmenu ul.nav li a:hover {
  width: 120px;
  height: 25px;
  background: #D2E2FF;
  color: #000;
  border: 1px solid black;
  padding-top: 4px;
  padding-right: 4px;
  padding-bottom: 8px;
  padding-left: 4px;
}
.topmenu ul.nav li:hover ul {
  left: 0px;
  top: 38px;
  padding: 0px;
  border: solid 1px;
}
.topmenu ul.nav li:hover ul li a {
  padding: 6px;
  width: 250px;
  background-color: #FFFFFF;
  border-top-width: 1px;
  border-right-width: 1px;
  border-bottom-width: 1px;
  border-left-width: 1px;
  border-top-style: solid;
  border-bottom-style: solid;
  border-top-color: #000;
  border-right-color: #000;
  border-bottom-color: #000;
  border-left-color: #000;
  border-right-style: none;
  border-left-style: none;
}
ul.nav {
  list-style: none;
  margin-bottom: 15px;
}
ul.nav li {
  float: left;
}
ul.nav a, ul.nav a:visited {
  display: block;
  width: 25px;
  height: 25px;
  text-decoration: none;
  background-color: #FFFFFF;
  padding: 3px;
}
ul.nav li a:hover {
  background-color: #D2E2FF;
  color: #000;
  border: solid 1px black;
  padding: 2px;
}
ul.nav ul a:hover {
  background-color: #D2E2FF;
  color: #000;
  padding: 3px;
  border-top-style: none;
  border-right-style: none;
  border-bottom-style: none;
  border-left-style: none;
}
ul.nav li a:focus, ul.nav li a:active {
  color: #000;
  text-decoration: underline;
}
ul.nav ul {
  position: absolute;
  left: -9999px;
  top: -9999px;
  list-style-type: none;
}
ul.nav li:hover {
  position: relative;
}
ul.nav li:hover ul {
  left: 30px;
  top: 0px;
  padding: 0px;
  border: solid 1px;
}
ul.nav li:hover ul li a {
  padding: 3px;
  width: 300px;
  background-color: #FFFFFF;
}
ul.nav li:hover ul li a:hover {
  background: #D2E2FF;
  color: #000;
}

<!DOCTYPE html>
<html>
<head>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
  </script>
  <title></title>
</head>
<body>
  <div class="topmenu">
    <ul class="nav">
      <li class="tab-link current" data-tab="strona_glowna">
        <a href="#">Strona główna</a>
      </li>
      <li class="tab-link" data-tab="spis_tresci">
        <a href="#">Spis treści</a>
      </li>
      <li class="innerNav">
        <a href="#">Poradniki</a>
        <ul>
          <li class="tab-link" data-tab="poradnik_1">
            <a href="#">Poradnik 1</a>
          </li>
          <li class="tab-link" data-tab="poradnik_2">
            <a href="#">Poradnik 2</a>
          </li>
          <li class="tab-link" data-tab="poradnik_3">
            <a href="#">Poradnik 3</a>
          </li>
          <li class="tab-link" data-tab="poradnik_4">
            <a href="#">Poradnik 4</a>
          </li>
        </ul>
      </li>
      <li class="tab-link" data-tab="o_autorze">
        <a href="#">O autorze</a>
      </li>
    </ul>
  </div>
  <div class="tab-content current" id="strona_glowna">
    <h1>Strona główna</h1>
    <p>Strona główna</p>
  </div>
  <div class="tab-content" id="spis_tresci">
    <h1>Spis treści</h1>
    <p>Spis treści</p>
  </div>
  <div class="tab-content" id="poradnik_1">
    <h1>Poradnik 1</h1>
    <p>Poradnik 1</p>
  </div>
  <div class="tab-content" id="poradnik_2">
    <h1>Poradnik 2</h1>
    <p>Poradnik 2</p>
  </div>
  <div class="tab-content" id="poradnik_3">
    <h1>Poradnik 3</h1>
    <p>Poradnik 3</p>
  </div>
  <div class="tab-content" id="poradnik_4">
    <h1>Poradnik 4</h1>
    <p>Poradnik 4</p>
  </div>
  <div class="tab-content" id="o_autorze">
    <h1>O autorze</h1>
    <p>O autorze</p>
  </div>
</body>
</html>


问:
Microsoft Graph adding Directory.Read.All permission
We are creating a service that requires permission to view other users' (inside the organization) emails. I'm under the impression that two required permissions are Mail.Read and Directory.Read.All. Since I'm not an admin, I got our admin to try it and he still gets 'Access denied'. Is it possible for the admin to give me the necessary directory permissions?

Am I missing something?

(Sorry if I am ambiguous, I am brand new to Graph. Please ask me any question that will help clarify)

答:
Make sure you've enabled the Mail.Read application permission (Read mail in all mailboxes). There is also a Mail.Read delegated permission (Read user mail), which gives you access only to the signed-in user's mailbox.

An admin must grant that permission in Azure Portal for the application. From that point on, the application by itself (with no signed-in user) should be able to access any user's email in the organization.


问:
Delete string match from another file
i have 1.txt:

```<code>hi aa my name is bb tom
how are you cc today
</code>```

and i have 2.txt ( the word that i dont want )

```<code>aa
bb
cc
</code>```

and my expected output is

```<code>hi my name is tom
how are you today
</code>```

what i have tried so far is

```<code>sed -e "s/$(sed 's:/:\\/:g' 2.txt)/ /"
or
grep -Fvf 2.txt 1.txt
</code>```

i have more than 100 words that i dont want, so i have to put it in one sentence, thanks

答:
gawk solution:

```<code>awk 'NR==FNR{ a[$0]; next }{ for(i in a) gsub("\\<"i"\\> *","",$0) }1' 2.txt 1.txt
</code>```

The output:

```<code>hi my name is tom
how are you today
</code>```

a[$0] - accumulating words which should be removed from each sentence

gsub("\\<"i"\\> *","",$0) - replacing each "unwanted" word (as a whole word) with empty string

Title: Delete string match from another file

Body:
i have 1.txt:

hi aa my name is bb tom
how are you cc today

and i have 2.txt ( the word that i dont want )

aa
bb
cc

and my expected output is

hi my name is tom
how are you today

what i have tried so far is

sed -e "s/$(sed 's:/:\\/:g' 2.txt)/ /"
or
grep -Fvf 2.txt 1.txt

i have more than 100 words that i dont want, so i have to put it in one sentence, thanks

Body:
gawk solution:

awk 'NR==FNR{ a[$0]; next }{ for(i in a) gsub("\\<"i"\\> *","",$0) }1' 2.txt 1.txt

The output:

hi my name is tom
how are you today

a[$0] - accumulating words which should be removed from each sentence

gsub("\\<"i"\\> *","",$0) - replacing each "unwanted" word (as a whole word) with empty string


问:
What does 1. mean in Fortran77
I am a new user to Fortran. The Fortran77 .for file I am trying to understand keeps using 1. in the equations. Does that just mean it is a vector of 1's instead of an integer? Thank you very much.</p>

答:
The . just forces the compiler to treat it as a REAL type (as opposed to an INTEGER type).  Because of how FORTRAN handles mixed-mode expressions (expressions with both INTEGER and REAL types), you have to be careful when performing those kinds of operations.  If an expression mixes both types, the result will be REAL, however the order in how the sub-expressions are evaluated makes a different.

For example:

9 / 2 * 3.0 = 12.0

because 9 / 2 is evaluated as integer arithmetic, thus 9 / 2 = 4.

Changing the order affects the result:

3.0 * 9 / 2 = 13.5

Because the sub expression 3.0 * 9 is evaluated first, and contains a REAL, and forces the result to be REAL.

NOTE: you can fix the problem with the first example by using a .:

9. / 2 * 3.0 = 13.5

It is better to either make sure all of your operands are REAL, or all are INTEGER to make sure you avoid rounding/truncation errors.

Title: What does 1. mean in Fortran77


问:
How to write LaTeX in IPython Notebook?
How can I display LaTeX code in a IPython Notebook?</p>

答:
LaTeX References:

Udacity's Blog has the Best LaTeX Primer I've seen:  It clearly shows how to use LaTeX commands in easy to read, and easy to remember manner !!   Highly recommended.

This Link has Excellent Examples showing both the code, and the rendered result !

You can use this site to quickly learn how to write LaTeX by example.

And, here is a quick Reference for LaTeX commands/symbols.

To Summarize: various ways to indicate LaTeX in Jupyter/IPython:

Examples for Markdown Cells:

inline, wrap in: $

```<code>The equation used depends on whether the the value of
$Vmax$ is R, G, or B.
</code>```

block, wrap in: $$

```<code>$$H←  0 + \frac{30(G−B)}{Vmax−Vmin}  , if Vmax = R$$
</code>```

block, wrap in: \begin{equation} and \end{equation}

```<code>\begin{equation}
H← 60 + \frac{30(B−R)}{Vmax−Vmin}  , if Vmax = G
\end{equation}
</code>```

block, wrap in: \begin{align} and \end{align}

```<code>\begin{align}
H←120 + \frac{30(R−G)}{Vmax−Vmin}  , if Vmax = B
\end{align}
</code>```

Examples for Code Cells:

LaTex Cell: %%latex magic command turns the entire cell into a LaTeX Cell

```<code>%%latex
\begin{align}
\nabla \cdot \vec{\mathbf{E}} & = 4 \pi \rho \\
\nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} & = \vec{\mathbf{0}} \\
\nabla \cdot \vec{\mathbf{B}} & = 0
\end{align}
</code>```

Math object to pass in a raw LaTeX string:

```<code>from IPython.display import Math
Math(r'F(k) = \int_{-\infty}^{\infty} f(x) e^{2\pi i k} dx')
</code>```

Latex class. Note: you have to include the delimiters yourself. This allows you to use other LaTeX modes such as eqnarray:

```<code>from IPython.display import Latex
Latex(r"""\begin{eqnarray}
\nabla \times \vec{\mathbf{B}} -\, \frac1c\, \frac{\partial\vec{\mathbf{E}}}{\partial t} & = \frac{4\pi}{c}\vec{\mathbf{j}} \\
\nabla \cdot \vec{\mathbf{E}} & = 4 \pi \rho \\
\nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} & = \vec{\mathbf{0}} \\
\nabla \cdot \vec{\mathbf{B}} & = 0
\end{eqnarray}""")
</code>```

Docs for Raw Cells:

(sorry, no example here, just the docs)

Raw cells
  Raw cells provide a place in which you can write output directly. Raw cells are not evaluated by the notebook. When passed through nbconvert, raw cells arrive in the destination format unmodified. For example, this allows you to type full LaTeX into a raw cell, which will only be rendered by LaTeX after conversion by nbconvert.

Additional Documentation:

For Markdown Cells, as quoted from Jupyter Notebook docs:

Within Markdown cells, you can also include mathematics in a straightforward way, using standard LaTeX notation: $...$ for inline mathematics and $$...$$ for displayed mathematics. When the Markdown cell is executed, the LaTeX portions are automatically rendered in the HTML output as equations with high quality typography. This is made possible by MathJax, which supports a large subset of LaTeX functionality

Standard mathematics environments defined by LaTeX and AMS-LaTeX (the amsmath package) also work, such as \begin{equation}...\end{equation}, and \begin{align}...\end{align}. New LaTeX macros may be defined using standard methods, such as \newcommand, by placing them anywhere between math delimiters in a Markdown cell. These definitions are then available throughout the rest of the IPython session.

ContentLicense: CC BY-SA 4.0

Title: How to write LaTeX in IPython Notebook?

Body:
LaTeX References:

Udacity's Blog has the Best LaTeX Primer I've seen:  It clearly shows how to use LaTeX commands in easy to read, and easy to remember manner !!   Highly recommended.

This Link has Excellent Examples showing both the code, and the rendered result !

You can use this site to quickly learn how to write LaTeX by example.

And, here is a quick Reference for LaTeX commands/symbols.

To Summarize: various ways to indicate LaTeX in Jupyter/IPython:

Examples for Markdown Cells:

inline, wrap in: $

The equation used depends on whether the the value of
$Vmax$ is R, G, or B.

block, wrap in: $$

$$H←  0 + \frac{30(G−B)}{Vmax−Vmin}  , if Vmax = R$$

block, wrap in: \begin{equation} and \end{equation}

\begin{equation}
H← 60 + \frac{30(B−R)}{Vmax−Vmin}  , if Vmax = G
\end{equation}

block, wrap in: \begin{align} and \end{align}

\begin{align}
H←120 + \frac{30(R−G)}{Vmax−Vmin}  , if Vmax = B
\end{align}

Examples for Code Cells:

LaTex Cell: %%latex magic command turns the entire cell into a LaTeX Cell

%%latex
\begin{align}
\nabla \cdot \vec{\mathbf{E}} & = 4 \pi \rho \\
\nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} & = \vec{\mathbf{0}} \\
\nabla \cdot \vec{\mathbf{B}} & = 0
\end{align}

Math object to pass in a raw LaTeX string:

from IPython.display import Math
Math(r'F(k) = \int_{-\infty}^{\infty} f(x) e^{2\pi i k} dx')

Latex class. Note: you have to include the delimiters yourself. This allows you to use other LaTeX modes such as eqnarray:

from IPython.display import Latex
Latex(r"""\begin{eqnarray}
\nabla \times \vec{\mathbf{B}} -\, \frac1c\, \frac{\partial\vec{\mathbf{E}}}{\partial t} & = \frac{4\pi}{c}\vec{\mathbf{j}} \\
\nabla \cdot \vec{\mathbf{E}} & = 4 \pi \rho \\
\nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} & = \vec{\mathbf{0}} \\
\nabla \cdot \vec{\mathbf{B}} & = 0
\end{eqnarray}""")

Docs for Raw Cells:

(sorry, no example here, just the docs)

Raw cells
  Raw cells provide a place in which you can write output directly. Raw cells are not evaluated by the notebook. When passed through nbconvert, raw cells arrive in the destination format unmodified. For example, this allows you to type full LaTeX into a raw cell, which will only be rendered by LaTeX after conversion by nbconvert.

Additional Documentation:

For Markdown Cells, as quoted from Jupyter Notebook docs:

Within Markdown cells, you can also include mathematics in a straightforward way, using standard LaTeX notation: $...$ for inline mathematics and $$...$$ for displayed mathematics. When the Markdown cell is executed, the LaTeX portions are automatically rendered in the HTML output as equations with high quality typography. This is made possible by MathJax, which supports a large subset of LaTeX functionality

Standard mathematics environments defined by LaTeX and AMS-LaTeX (the amsmath package) also work, such as \begin{equation}...\end{equation}, and \begin{align}...\end{align}. New LaTeX macros may be defined using standard methods, such as \newcommand, by placing them anywhere between math delimiters in a Markdown cell. These definitions are then available throughout the rest of the IPython session.


问:
How to generate helper classes and stub code with wsdl2php for a PHP web service?
I have a WSDL generated by WCF and now this WSDL should be used to create a PHP web service. My WSDL contains mappings to custom .NET classes (complexType) and I would need a PHP WSDL tool which can generate the equivalent PHP classes as well as the stub code (server-side generation).

I read that the wsdl2php would be the right tool to do the job so I tried it at the address:
(http://labs.wso2.org/wsf/php/wsdl2phptool.php)

It worked partly by creating the stub code but it didn't create any helper classes (function parameters seem to be of type anyType and only one parameter is generated for each function). I have also the script version which I can run with the following kind of command in Windows:

php wsdl2php.php -s http://My.Server.com/MyWCFService/MyWCFService.svc?wsdl > MyWebService.php

but for some reason it doesn't seem to work as it outputs an empty file. I'm not a PHP expert as I am a .NET developer but I would need to test how our WSDL works with PHP web services (just to see that it's possible to generate PHP code from our WSDL in the same way as in .NET).

I would be grateful if you could give me a simple example of generating helper classes and stub code for a PHP web service.

Thanks! :)

答:
You can also use T4 templates for generating ServiceProxies and DataContract classes from your Service implementation. I have been developing them for a project of mine, they are released on GitHub including samples:

https://github.com/schaermu/wcf-phpclient-t4

Just in case you want the proxy-generation logic in your .NET solution.


问:
Laravel change get parameter in url string and return
I'm using get parameters for search filters, and need to be able to change a value of the query string variable and return the modified url (as a string variable, nothing fancy, no redirect or anything). This is what I have so far and what is happening:

```<code>public function index(Request $request){

    echo $request->fullUrl();
    // outputs https://test.com/search?type=somestring

    $request->merge(['type' => 'anotherstring']);

    echo $request->fullUrl();
    // still outputs https://test.com/search?type=somestring

    // is there a way to change a parameter value in the url and
    // return the modified url string?

}
</code>```

I figure if worse comes to worse, I'll just parse the string manually, but it feels like there's a "laravel way" to go about this that I happen to be missing?

答:
Worse case you can do:</p>

```<code> echo url()->current().(!empty($request->all())?"?":"").http_build_query($request->all());
</code>```

Body:
I'm using get parameters for search filters, and need to be able to change a value of the query string variable and return the modified url (as a string variable, nothing fancy, no redirect or anything). This is what I have so far and what is happening:

public function index(Request $request){

    echo $request->fullUrl();
    // outputs https://test.com/search?type=somestring

    $request->merge(['type' => 'anotherstring']);

    echo $request->fullUrl();
    // still outputs https://test.com/search?type=somestring

    // is there a way to change a parameter value in the url and
    // return the modified url string?

}

I figure if worse comes to worse, I'll just parse the string manually, but it feels like there's a "laravel way" to go about this that I happen to be missing?

Body:
Worse case you can do:

 echo url()->current().(!empty($request->all())?"?":"").http_build_query($request->all());


问:
get delivery and send receipt using java email
I am using below code. I am tring to get send receipt and delivery receipt for mail. still its not working for this code.

I have tried to add Properties, but of no use. I have a requirement in which i need to check whether an email is delivered successfully or not. I have written the code for email delivery but it prints success even for invalid email address.How to track whether email is delivered or not using javamail API

```<code>import java.io.ByteArrayOutputStream;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;

import javax.activation.DataSource;
import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.util.ByteArrayDataSource;

import org.apache.log4j.Logger;
import org.apache.velocity.app.VelocityEngine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.stereotype.Service;
import org.springframework.ui.velocity.VelocityEngineUtils;
import org.springframework.util.StringUtils;

@Service
public class VelocityMailServiceImpl implements MailService {

    private static final Logger logger = Logger.getLogger(MailService.class);

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private VelocityEngine velocityEngine;

    @Autowired
    private MessageSource messageSource;

    @Value("$env{email.smtp.host}")
    private String emailHost;

    /**
     * This method will send compose and send the message
     * */
    public void sendMail(String to, String from, String subject, String body) {
        SimpleMailMessage message = new SimpleMailMessage();
        String[] emailTos = null;

        try{

        if (to.contains(";")) {
            emailTos = to.split(";");
        } else if (to.contains(",")) {
            emailTos = to.split(",");
        } else {
            emailTos = new String[] { to };
        }
        message.setTo(emailTos);
        message.setFrom(from);
        //message.addFrom(InternetAddress.parse(from));
        message.setSubject(subject);
        message.setText(body);
        Properties props = new Properties();
    //  props.put("Return-Receipt-To", "admin@xyz.com");
    //  mailSender.setJavaMailProperties(props);
        mailSender.send(message);
        }catch(Exception e){
            System.out.println("Error sending amil.....");
        }
    }
</code>```

答:
There's no guaranteed way to determine whether a message was delivered successfully or not.  If that's your requirement, give up now.

The JavaMail FAQ explains why you don't get an exception when you try to use an invalid address.

Many mail servers simply ignore messages sent to invalid addresses, to prevent spammers from "probing" for valid addresses.

There are internet standards for Delivery Status Notifications, but again many servers don't implement the standard or don't return notifications for bad addresses.

The most reliable way to detect whether a message was delivered successfully is to include a link in the message and request the recipient to click on the link to verify that the message was received.  Obviously this is still not perfect because they might never click on the link.

Body:
I am using below code. I am tring to get send receipt and delivery receipt for mail. still its not working for this code.

I have tried to add Properties, but of no use. I have a requirement in which i need to check whether an email is delivered successfully or not. I have written the code for email delivery but it prints success even for invalid email address.How to track whether email is delivered or not using javamail API

import java.io.ByteArrayOutputStream;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;

import javax.activation.DataSource;
import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.util.ByteArrayDataSource;

import org.apache.log4j.Logger;
import org.apache.velocity.app.VelocityEngine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.stereotype.Service;
import org.springframework.ui.velocity.VelocityEngineUtils;
import org.springframework.util.StringUtils;

@Service
public class VelocityMailServiceImpl implements MailService {

    private static final Logger logger = Logger.getLogger(MailService.class);

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private VelocityEngine velocityEngine;

    @Autowired
    private MessageSource messageSource;

    @Value("$env{email.smtp.host}")
    private String emailHost;

    /**
     * This method will send compose and send the message
     * */
    public void sendMail(String to, String from, String subject, String body) {
        SimpleMailMessage message = new SimpleMailMessage();
        String[] emailTos = null;

        try{

        if (to.contains(";")) {
            emailTos = to.split(";");
        } else if (to.contains(",")) {
            emailTos = to.split(",");
        } else {
            emailTos = new String[] { to };
        }
        message.setTo(emailTos);
        message.setFrom(from);
        //message.addFrom(InternetAddress.parse(from));
        message.setSubject(subject);
        message.setText(body);
        Properties props = new Properties();
    //  props.put("Return-Receipt-To", "admin@xyz.com");
    //  mailSender.setJavaMailProperties(props);
        mailSender.send(message);
        }catch(Exception e){
            System.out.println("Error sending amil.....");
        }
    }


问:
Don't get the solution of this java NullPointerException
```<code>class DotCom{
    int[] arr;
    int numOfhits=0;
    void setLocation(int[] location){
        int[] arr=location;
    }

    String checkGuess(int guess){
        System.out.println(guess);
        String result="miss";
        for(int i:arr){
            if (i==guess){
                 result="hit";
                numOfhits++;
                break;
                }

            if(numOfhits==arr.length){
                result="kill";
            }
        }
        System.out.println(result);
        return result;
    }
}

class TestDotCom{
    public static void  main(String[] args){
        DotCom obj=new DotCom();
        int[] location ={1,2,3};
        obj.setLocation(location);
        int userGuess=2;
        String testResult="fail";
        String result=obj.checkGuess(userGuess);

        if(result=="hit"){
            testResult="passed";
            }

        System.out.println(testResult);
    }
}
</code>```

in Dotcom class the int[] arr=location causes error. When I remove that i doesn't get any error what is going on over here? The error I get are

2 Exception in thread "main" java.lang.NullPointerException

```<code>    at DotCom.checkGuess(DotCom.java:12)
    at TestDotCom.main(TestDotCom.java:8)
</code>```

I don't get it what's wrong with the program.

答: In setLocation(): int[] arr=location; supposed to be arr=location;. You're overriding the global arr with a local one.

Body:
class DotCom{
    int[] arr;
    int numOfhits=0;
    void setLocation(int[] location){
        int[] arr=location;
    }

    String checkGuess(int guess){
        System.out.println(guess);
        String result="miss";
        for(int i:arr){
            if (i==guess){
                 result="hit";
                numOfhits++;
                break;
                }

            if(numOfhits==arr.length){
                result="kill";
            }
        }
        System.out.println(result);
        return result;
    }
}

class TestDotCom{
    public static void  main(String[] args){
        DotCom obj=new DotCom();
        int[] location ={1,2,3};
        obj.setLocation(location);
        int userGuess=2;
        String testResult="fail";
        String result=obj.checkGuess(userGuess);

        if(result=="hit"){
            testResult="passed";
            }

        System.out.println(testResult);
    }
}

in Dotcom class the int[] arr=location causes error. When I remove that i doesn't get any error what is going on over here? The error I get are

2 Exception in thread "main" java.lang.NullPointerException

    at DotCom.checkGuess(DotCom.java:12)
    at TestDotCom.main(TestDotCom.java:8)

I don't get it what's wrong with the program.


问:
Unity3d - Particles/Additive displays white instead of black
Particles/Additive on a LineRenderer displays white instead of black. Any idea what is the problem?

```<code> Color edge_color=Color.black;
 edge_color.a = 0.7f;
 GameObject go = new GameObject ();
 var rend=go.AddComponent<LineRenderer> ();
 rend.useWorldSpace = false;
 rend.startWidth = 0.05f;
 rend.endWidth = 0.05f;
 rend.material = new Material(Shader.Find("Mobile/Particles/Additive"));
 rend.material.color = edge_color;
 //rend.SetPositions (...);
</code>```

答:
Solved the problem by changing to Particles\Alpha blended shader. Also used startColor and endColor instead of material.color.
Still don't know why the additive shader won't show the color that I set using startColor and endColor (it becomes transparent after I set these two).</p>

Body:
Particles/Additive on a LineRenderer displays white instead of black. Any idea what is the problem?

 Color edge_color=Color.black;
 edge_color.a = 0.7f;
 GameObject go = new GameObject ();
 var rend=go.AddComponent<LineRenderer> ();
 rend.useWorldSpace = false;
 rend.startWidth = 0.05f;
 rend.endWidth = 0.05f;
 rend.material = new Material(Shader.Find("Mobile/Particles/Additive"));
 rend.material.color = edge_color;
 //rend.SetPositions (...);


问:
replace a string with other string in the same line
Vi editor

Input file text format:

```<code>'': hello.Code1
'': hello.Code2
'': hello.Code3
</code>```

Required output text format:

```<code>'Code1': hello.Code1
'Code2': hello.Code2
'Code3': hello.Code3
</code>```

Idea is I have to copy all the values after "." to the single quotes ''. I can use Vi or SED etc. Linux based. or MAC based.
I have more that 2000 lines in the text file
Thanks

答:
This can be done quite simply with a substitute command and capturing groups. Try the following regex:

```<code>:%s/''\(.*\)\.\(.*\)/'\2'\1.\2
</code>```

This says, Search for quotes '', followed by anything captured into group 1 \(.*\), followed by a literal dot \., followed by anything captured into group 2 \(.*\). This will put

```<code>: hello
</code>```

Into group 1, and

```<code>CodeN
</code>```

into group 2. So then we replace it with group 2 in quotes '\2' followed by group 1 \1, followed by a dot \. and group 2 again \2.

If you put \v at the beginning of the regex, you can get rid of a lot of the backslashes and make it more readable:

```<code>:%s/\v''(.*)\.(.*)/'\2'\1.\2
</code>```

You could also do this with a %normal command. That makes a set of keystrokes be applied to every line in the buffer. I would try this:

```<code>:%norm f.ly$0p
</code>```

This says, On every line, do the following keystrokes :%norm Move forward to a '.' f., move one character to the right l, yank everything to the end of this line y$, move to the beginning of this line 0, and paste what we just yanked p

Body:
Vi editor

Input file text format:

'': hello.Code1
'': hello.Code2
'': hello.Code3

Required output text format:

'Code1': hello.Code1
'Code2': hello.Code2
'Code3': hello.Code3

Idea is I have to copy all the values after "." to the single quotes ''. I can use Vi or SED etc. Linux based. or MAC based.
I have more that 2000 lines in the text file
Thanks

Body:
This can be done quite simply with a substitute command and capturing groups. Try the following regex:

:%s/''\(.*\)\.\(.*\)/'\2'\1.\2

This says, Search for quotes '', followed by anything captured into group 1 \(.*\), followed by a literal dot \., followed by anything captured into group 2 \(.*\). This will put

: hello

Into group 1, and

CodeN

into group 2. So then we replace it with group 2 in quotes '\2' followed by group 1 \1, followed by a dot \. and group 2 again \2.

If you put \v at the beginning of the regex, you can get rid of a lot of the backslashes and make it more readable:

:%s/\v''(.*)\.(.*)/'\2'\1.\2

You could also do this with a %normal command. That makes a set of keystrokes be applied to every line in the buffer. I would try this:

:%norm f.ly$0p

This says, On every line, do the following keystrokes :%norm Move forward to a '.' f., move one character to the right l, yank everything to the end of this line y$, move to the beginning of this line 0, and paste what we just yanked p


问:
Webpack 2: Provide entry name to imported sass modules as variable
I have two entries; bundle-a.js and bundle-b.js.

Both of these entry bundles import component.scss.

I would like to prepend component.scss module with $bundle: '{entry-name}'; e.g. $bundle: 'bundle-b';

Is this possible? I assume loaders or plugins but have no idea where to start.

Thanks in advance :)

答:
Perhaps the Banner Plugin?

https://webpack.js.org/plugins/banner-plugin/

It doesn't solve your issue entirely, but might give you a good head start.


问:
Extract RDD[(Array[String]) from RDD[(String, Array[String]) [Spark/scala]
I have this prbolem, I have one of this kind  RDD[(String, Array[String]), and I would like extract from it a RDD[Array[String]] that contains the values grouped by key:

e.g:

```<code>val x :RDD[(String, Array[String]) =
RDD[(a, Array[ "ra", "re", "ri"]),
(a, Array[ "ta", "te", "ti"]),
(b, Array[ "pa", "pe", "pi"])]
</code>```

I would like get:

```<code>val result: RDD[(String, RDD[Array[String]]) =
RDD[(a, RDD[Array[("ra", "re", "ri"),( "ta", "te", "ti")]]),
(b,  RDD[Array[("pa", "pe", "pi"),...]])
,...]
</code>```

答:
As far as I know, Spark doesn't support nested RDDs (see this StackOverflow discussion).

In case nested arrays are good for what you need, a simple groupByKey will do:

```<code>val x = sc.parallelize(Seq(
  ("a", Array( "ra", "re", "ri" )),
  ("a", Array( "ta", "te", "ti" )),
  ("b", Array( "pa", "pe", "pi" ))
))

val x2 = x.groupByKey

x2.collect.foreach(println)
(a,CompactBuffer([Ljava.lang.String;@75043e31, [Ljava.lang.String;@18656538))
(b,CompactBuffer([Ljava.lang.String;@2cf30d2e))

x2.collect.foreach{ case (a, b) => println(a + ": " + b.map(_.mkString(" "))) }
a: List(ra re ri, ta te ti)
b: List(pa pe pi)
</code>```

Body:
I have this prbolem, I have one of this kind  RDD[(String, Array[String]), and I would like extract from it a RDD[Array[String]] that contains the values grouped by key:

e.g:

val x :RDD[(String, Array[String]) =
RDD[(a, Array[ "ra", "re", "ri"]),
(a, Array[ "ta", "te", "ti"]),
(b, Array[ "pa", "pe", "pi"])]

I would like get:

val result: RDD[(String, RDD[Array[String]]) =
RDD[(a, RDD[Array[("ra", "re", "ri"),( "ta", "te", "ti")]]),
(b,  RDD[Array[("pa", "pe", "pi"),...]])
,...]

Body:
As far as I know, Spark doesn't support nested RDDs (see this StackOverflow discussion).

In case nested arrays are good for what you need, a simple groupByKey will do:

val x = sc.parallelize(Seq(
  ("a", Array( "ra", "re", "ri" )),
  ("a", Array( "ta", "te", "ti" )),
  ("b", Array( "pa", "pe", "pi" ))
))

val x2 = x.groupByKey

x2.collect.foreach(println)
(a,CompactBuffer([Ljava.lang.String;@75043e31, [Ljava.lang.String;@18656538))
(b,CompactBuffer([Ljava.lang.String;@2cf30d2e))

x2.collect.foreach{ case (a, b) => println(a + ": " + b.map(_.mkString(" "))) }
a: List(ra re ri, ta te ti)
b: List(pa pe pi)


问:
Emit one List item at a time from a Flowable
I have a method which returns a Flowable<RealmResults<MyClass>>. For those not familiar with Realm, RealmResults is just a simple List of items.

Given a Flowable<RealmResults<MyClass>>, I'd like to emit each MyClass item so that I can perform a map() operation on each item.

I am looking for something like the following:

```<code>getItems() // returns a Flowable<RealmResults<MyClass>>
    .emitOneAtATime() // Example operator
    .map(obj -> obj + "")
    // etc
</code>```

What operator will emit each List item sequentially?

答:
You would flatMap(aList -> Flowable.fromIterable(aList)).  Then you can map() on each individual item.  There is toList() if you want to recollect the items (note: this would be a new List instance).  Here's an example illustrating how you can use these methods to get the different types using List<Integer>.

```<code>List<Integer> integerList = new ArrayList<>();
Flowable<Integer> intergerListFlowable =
            Flowable
                    .just(integerList)//emits the list
                    .flatMap(list -> Flowable.fromIterable(list))//emits one by one
                    .map(integer -> integer + 1);
</code>```

Body:
I have a method which returns a Flowable<RealmResults<MyClass>>. For those not familiar with Realm, RealmResults is just a simple List of items.

Given a Flowable<RealmResults<MyClass>>, I'd like to emit each MyClass item so that I can perform a map() operation on each item.

I am looking for something like the following:

getItems() // returns a Flowable<RealmResults<MyClass>>
    .emitOneAtATime() // Example operator
    .map(obj -> obj + "")
    // etc

What operator will emit each List item sequentially?

Body:
You would flatMap(aList -> Flowable.fromIterable(aList)).  Then you can map() on each individual item.  There is toList() if you want to recollect the items (note: this would be a new List instance).  Here's an example illustrating how you can use these methods to get the different types using List<Integer>.

List<Integer> integerList = new ArrayList<>();
Flowable<Integer> intergerListFlowable =
            Flowable
                    .just(integerList)//emits the list
                    .flatMap(list -> Flowable.fromIterable(list))//emits one by one
                    .map(integer -> integer + 1);


问:
Neo4j create multiple nodes and relationships
I am using Neo4j to build a huge graph database (over a million nodes). The way I'm doing it right now is running a cypher CREATE (n {property:'value'}) query for each of the node. As expected, this is quite an inefficient method and it takes lots of time. Can somebody suggest me some alternative method to overcome this issue? I've heard that Neo4j also provides some default batch interface to create multiple nodes. I'm currently using this version of code (including the relationship):

create (a { name: "a" })-[:rel1]->(b {name : "b"}),(c {name: "c"})-[:rel2]->(d {name:"d"}),...

Is it an efficient method or are there any better methods?
Thanks in advance! :)

答:
You can use unwind to your advantage.
Assuming you are using the Java API, here's a small snippet using Groovy

```<code>List<Map<String, Object>> props = yourList.collect {["prop1": it.prop1, "prop2":it.prop2]}
String q = "UNWIND {props} AS p create(a {name: p.prop1})-[:rel1]->(b {name: p.prop2}) "
neo4jOperations.query(q, ["props" : props])
</code>```

I've had great success with this method. You should be able to see a speedup of 5-30 times depending on your batch size

Body:
You can use unwind to your advantage.
Assuming you are using the Java API, here's a small snippet using Groovy

List<Map<String, Object>> props = yourList.collect {["prop1": it.prop1, "prop2":it.prop2]}
String q = "UNWIND {props} AS p create(a {name: p.prop1})-[:rel1]->(b {name: p.prop2}) "
neo4jOperations.query(q, ["props" : props])

I've had great success with this method. You should be able to see a speedup of 5-30 times depending on your batch size


问:
Add pages to PDF if certain criteria are met
I am currently in the process of making a couple of forms on Adobe Acrobat, using imported data from Excel. In some cases, there is more data than there are spots on the PDF. I am trying to find a way to show/hide pages when an overflow page is needed. Is there any way I can do this??</p>

答:
Yes. Look into creating page "Templates". Template objects are named pages within the document. These pages may be hidden or visible and can be copied or spawned. They are typically used to dynamically create content, for example, to add pages to an invoice on overflow.

You can use JavaScript to detect when you need the page and then show it and populate the data on that page.

http://help.adobe.com/en_US/acrobat/acrobat_dc_sdk/2015/HTMLHelp/index.html#t=Acro12_MasterBook%2FJS_API_AcroJS%2FTemplate.htm


问:
Access dynamic request variable in javascript

In my controller class, I'm setting some attributes to the request as below.

```<code>for(ConsumerVO dep:quoteVO.getConsumerFamily().getDependents())
            {
                request.setAttribute("dependent_"+depCount+"_birthdateMM", dep.getBirthdateMM());
                request.setAttribute("dependent_"+depCount+"_birthdateDD", dep.getBirthdateDD());
                request.setAttribute("dependent_"+depCount+"_birthdateYYYY", dep.getBirthdateYYYY());
                depCount++;
            }
</code>```

In the jsp, I'm trying to access it by setting the variable name dynamically. But itsn't working. No data is in ${depMM}, ${depDD} etc. I'm looking for something like ${${depMM}}. How can I access the request variables in a loop ?

```<code>    jQuery(function(){

        var dependent_data = [];
        for(j=1;j<16;j++){
            var depMM = "dependent_"+j+"_birthdateMM";
            var depDD = "dependent_"+j+"_birthdateDD";
            var depYY = "dependent_"+j+"_birthdateYYYY";
            if (typeof '${depMM}' !== 'undefined' && '${depMM}' !=="") {
            dependent_data.push('${depMM}','${depDD}','${depYYYY}');
            }
        }
</code>```

PS: When I did this, it printed the data.

```<code>var dependent1MM_data = '${dependent_1_birthdateMM}';
alert(dependent1MM_data);
</code>```

答:
You can't access variables like this. You are mixing JavaScript and JSP. The for loop will run in the client side once the page is loaded. You can't access the variables inside JavaScript. You can instead turn it into a jsp for loop and access the variables in that.

Here are some ways of doing it
1. Create a for loop (JSP for loop or JSTL each) and then access the request parameters and create an input hidden tag, access that in the JS. (OR)
2. you can write a JSON String in the JSP and access that in your JavaScript.

```<code>var myObject = <%= JSON output of dependedents %>;
</code>```

The reason why the following statement works is

```<code>var dependent1MM_data = '${dependent_1_birthdateMM}';
alert(dependent1MM_data);
</code>```

When the JSP template is rendered the template engine sets the value in this variable. It's not tied with JS engine it's tied to your JSP rendering engine.

What I suggest is create a JSON string because if the data is too big then you will be creating more variables and input.hidden elements. So writing JSON will be a good solution

Note: I am not good in JSP or Spring. But I do have some experience in template languages. SO I am just pointing out the mistake here

Body:
In my controller class, I'm setting some attributes to the request as below.

for(ConsumerVO dep:quoteVO.getConsumerFamily().getDependents())
            {
                request.setAttribute("dependent_"+depCount+"_birthdateMM", dep.getBirthdateMM());
                request.setAttribute("dependent_"+depCount+"_birthdateDD", dep.getBirthdateDD());
                request.setAttribute("dependent_"+depCount+"_birthdateYYYY", dep.getBirthdateYYYY());
                depCount++;
            }

In the jsp, I'm trying to access it by setting the variable name dynamically. But itsn't working. No data is in ${depMM}, ${depDD} etc. I'm looking for something like ${${depMM}}. How can I access the request variables in a loop ?

    jQuery(function(){

        var dependent_data = [];
        for(j=1;j<16;j++){
            var depMM = "dependent_"+j+"_birthdateMM";
            var depDD = "dependent_"+j+"_birthdateDD";
            var depYY = "dependent_"+j+"_birthdateYYYY";
            if (typeof '${depMM}' !== 'undefined' && '${depMM}' !=="") {
            dependent_data.push('${depMM}','${depDD}','${depYYYY}');
            }
        }

PS: When I did this, it printed the data.

var dependent1MM_data = '${dependent_1_birthdateMM}';
alert(dependent1MM_data);

Body:
You can't access variables like this. You are mixing JavaScript and JSP. The for loop will run in the client side once the page is loaded. You can't access the variables inside JavaScript. You can instead turn it into a jsp for loop and access the variables in that.

Here are some ways of doing it
1. Create a for loop (JSP for loop or JSTL each) and then access the request parameters and create an input hidden tag, access that in the JS. (OR)
2. you can write a JSON String in the JSP and access that in your JavaScript.

var myObject = <%= JSON output of dependedents %>;

The reason why the following statement works is

var dependent1MM_data = '${dependent_1_birthdateMM}';
alert(dependent1MM_data);

When the JSP template is rendered the template engine sets the value in this variable. It's not tied with JS engine it's tied to your JSP rendering engine.

What I suggest is create a JSON string because if the data is too big then you will be creating more variables and input.hidden elements. So writing JSON will be a good solution

Note: I am not good in JSP or Spring. But I do have some experience in template languages. SO I am just pointing out the mistake here


答:
Remove the new declaration of int arr[] here:</p>

```<code>void setLocation(int[] location) {
    arr = location;
}
</code>```

Title: Don't get the solution of this java NullPointerException

Body:
Remove the new declaration of int arr[] here:

void setLocation(int[] location) {
    arr = location;
}


问:
How to adjust the height of a textview to his content in SWIFT?
In my view controller, I have an UITextView. This textview is filled with a string. The string can be short or long. Depending on the length of the string, the height of the textview has to adjust.
I use storyboards and auto layout.

I have some troubles with the height of the textview.

Sometimes, the height is perfectly adjusted to the text. Sometimes, no, the text is cropped on the first line. Below, the textview is yellow. the blue is a containerview inside a scrollview. Purple is the place for a picture.

The texts are from my core data base, they are string attributes.
Between the screen 1 and 2, the only thing changed is the string.

If I print the strings in the console I have the correct texts :

```<code>my amazing new title

Another funny title for demo
</code>```

The constraints of my textview :

I don't understand why I have 2 different displays.

EDIT

I tried the @Nate advice, in viewDidLoad, I added:

```<code>    myTextViewTitle.text="my amazing new title"

    myTextViewTitle.setContentHuggingPriority(1000, forAxis: UILayoutConstraintAxis.Vertical)
    myTextViewTitle.setContentCompressionResistancePriority(1000, forAxis: UILayoutConstraintAxis.Vertical)
    myTextViewTitle.setTranslatesAutoresizingMaskIntoConstraints(false)

    let views = ["new_view": myTextViewTitle]
    var constrs = NSLayoutConstraint.constraintsWithVisualFormat("|-8-[new_view]-8-|", options: NSLayoutFormatOptions(0), metrics: nil, views: views)
    self.view.addConstraints(constrs)
    self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-8-[new_view]", options: NSLayoutFormatOptions(0), metrics: nil, views: views))
    self.myTextViewTitle.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[new_view(220@300)]", options: NSLayoutFormatOptions(0), metrics: nil, views: views))
</code>```

No results. With or without height contraint added for my textview in interface builder...

EDIT 2

I need an UITextView and not an UIlabel, because of the back button, to use an exclusion path.

```<code>     let exclusionPathBack:UIBezierPath = UIBezierPath(rect: CGRect(x:backButton.bounds.origin.x, y:backButton.bounds.origin.y, width:backButton.bounds.width+10, height:backButton.bounds.height))
     myTextViewTitle.textContainer.exclusionPaths=[exclusionPathBack]
</code>```

答:
In Swift 3.0, where tvHeightConstraint is the height constraint of the subject TextView (if using for multiple textviews, would add it to the function inputs):

```<code>func textViewDidChange(textView: UITextView) {

        let size = textView.sizeThatFits(CGSize(width: textView.frame.size.width, height: CGFloat.greatestFiniteMagnitude))
        if size.height != tvHeightConstraint.constant && size.height > textView.frame.size.height{
            tvHeightConstraint.constant = size.height
            textView.setContentOffset(CGPoint.zero, animated: false)
        }
    }
</code>```

H/T to @cmi and @Pablo Ruan

Body:
In my view controller, I have an UITextView. This textview is filled with a string. The string can be short or long. Depending on the length of the string, the height of the textview has to adjust.
I use storyboards and auto layout.

I have some troubles with the height of the textview.

Sometimes, the height is perfectly adjusted to the text. Sometimes, no, the text is cropped on the first line. Below, the textview is yellow. the blue is a containerview inside a scrollview. Purple is the place for a picture.

The texts are from my core data base, they are string attributes.
Between the screen 1 and 2, the only thing changed is the string.

If I print the strings in the console I have the correct texts :

my amazing new title

Another funny title for demo

The constraints of my textview :

I don't understand why I have 2 different displays.

EDIT

I tried the @Nate advice, in viewDidLoad, I added:

    myTextViewTitle.text="my amazing new title"

    myTextViewTitle.setContentHuggingPriority(1000, forAxis: UILayoutConstraintAxis.Vertical)
    myTextViewTitle.setContentCompressionResistancePriority(1000, forAxis: UILayoutConstraintAxis.Vertical)
    myTextViewTitle.setTranslatesAutoresizingMaskIntoConstraints(false)

    let views = ["new_view": myTextViewTitle]
    var constrs = NSLayoutConstraint.constraintsWithVisualFormat("|-8-[new_view]-8-|", options: NSLayoutFormatOptions(0), metrics: nil, views: views)
    self.view.addConstraints(constrs)
    self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-8-[new_view]", options: NSLayoutFormatOptions(0), metrics: nil, views: views))
    self.myTextViewTitle.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[new_view(220@300)]", options: NSLayoutFormatOptions(0), metrics: nil, views: views))

No results. With or without height contraint added for my textview in interface builder...

EDIT 2

I need an UITextView and not an UIlabel, because of the back button, to use an exclusion path.

     let exclusionPathBack:UIBezierPath = UIBezierPath(rect: CGRect(x:backButton.bounds.origin.x, y:backButton.bounds.origin.y, width:backButton.bounds.width+10, height:backButton.bounds.height))
     myTextViewTitle.textContainer.exclusionPaths=[exclusionPathBack]

Body:
In Swift 3.0, where tvHeightConstraint is the height constraint of the subject TextView (if using for multiple textviews, would add it to the function inputs):

func textViewDidChange(textView: UITextView) {

        let size = textView.sizeThatFits(CGSize(width: textView.frame.size.width, height: CGFloat.greatestFiniteMagnitude))
        if size.height != tvHeightConstraint.constant && size.height > textView.frame.size.height{
            tvHeightConstraint.constant = size.height
            textView.setContentOffset(CGPoint.zero, animated: false)
        }
    }

H/T to @cmi and @Pablo Ruan


问:
Retrieving data from xml file created by xsl
Not sure if the title makes any sense, but I need to read an XML document and retrieve the data created by an XSL XPath query.

The XML is located here and the XSL here. If that's not possible, I'm assuming that I'll have to write the XPath query manually. So my question is, since XSL already generates the total, any way to parse it out of the XML file?

Thank you

答:
If I correctly understand your question, you are asking how to take the totals generated by the XSLT.

I see 2 options:

Reverse engineer the XSLT - try understanding it and produce your own XSLT that calculates the totals you want. Copy the logic from the existing XSLT

Do second XSLT transformation on existing XSLT - take the result of the current XSLT and write your own XSLT that takes the interesting parts from it. For this you need XSLT command line tool.

OwnerDisplayName: lengtche

LastEditorDisplayName: Dimitre Novatchev


问:
MySql deleting rows of csv file
I am trying to upload a csv to a MySql database but the following code is not working. I am entering the query directly into MySql.

```<code>Create table testing.test (
test VARCHAR(50),
test2 VARCHAR(50),
primary key (test));

LOAD DATA LOCAL INFILE 'C:/test.csv'
             INTO TABLE testing.test
             FIELDS
                TERMINATED BY ','
             LINES TERMINATED BY '\r\n';
</code>```

Basically it deletes all rows but the final row of the table. It produces the following message: "7 row(s) affected Records: 8 deleted: 0 Skipped". Any ideas why the rows are being deleted?

答:
Posting my comment to the question as answer for others: </p>

<p>I would assume that your line break encoding does not match that of the csv file. That can result in lines getting skipped, since they do not match the described format. Only the last line will get accepted in such scenario, since for that no terminating line break is required. </p>

Title: MySql deleting rows of csv file

Body:
I am trying to upload a csv to a MySql database but the following code is not working. I am entering the query directly into MySql.

Create table testing.test (
test VARCHAR(50),
test2 VARCHAR(50),
primary key (test));

LOAD DATA LOCAL INFILE 'C:/test.csv'
             INTO TABLE testing.test
             FIELDS
                TERMINATED BY ','
             LINES TERMINATED BY '\r\n';

Basically it deletes all rows but the final row of the table. It produces the following message: "7 row(s) affected Records: 8 deleted: 0 Skipped". Any ideas why the rows are being deleted?

Body:
Posting my comment to the question as answer for others:

I would assume that your line break encoding does not match that of the csv file. That can result in lines getting skipped, since they do not match the described format. Only the last line will get accepted in such scenario, since for that no terminating line break is required.


问:
Why do you have to use fetch for Rails params?
In the docs, they have:

```<code>params = ActionController::Parameters.new(person: { name: "Francesco" })
</code>```

and then use params.fetch(:person) to get person, but can't you just do params[:person]? to get the same data?

答:
Why do you have to use fetch for Rails params?

You don't.

You're looking at the documentation for fetch method. Naturally, it uses fetch everywhere. There's also [] method:

```<code>params = ActionController::Parameters.new(person: { name: "Francesco" })
params[:person] # => <ActionController::Parameters {"name"=>"Francesco"} permitted: false>
params[:none]   # => nil
</code>```

Body:
In the docs, they have:

params = ActionController::Parameters.new(person: { name: "Francesco" })

and then use params.fetch(:person) to get person, but can't you just do params[:person]? to get the same data?

Body:
Why do you have to use fetch for Rails params?

You don't.

You're looking at the documentation for fetch method. Naturally, it uses fetch everywhere. There's also [] method:

params = ActionController::Parameters.new(person: { name: "Francesco" })
params[:person] # => <ActionController::Parameters {"name"=>"Francesco"} permitted: false>
params[:none]   # => nil


问:
How to create a transaction log on WinSCP on SSIS package
I have SSIS package, which uses winscp to execute some commands in a text file to upload files to a FTP site. I use DTExec.exe to execute this SSIS package. Right now, I need to show winscp FTP log including display file name uploaded on FTP site. Does someone know how to capture the log? I use '>' and it does not work.</p>

答:
WinSCP can generate its own log using /log command-line switch (or /xmllog):

```<code>winscp.com /script=script.txt /log=winscp.log
</code>```

If you want to just capture WinSCP console output:

Make sure you are using winscp.com, not winscp.exe.

Run winscp.com via cmd.exe, as that is what understands the >.

```<code>cmd.exe /C winscp.com /script=script.txt > winscp.log
</code>```

In both cases, you will typically need to use full paths to all files (winscp.com, script.txt, winscp.log).

Body:
WinSCP can generate its own log using /log command-line switch (or /xmllog):

winscp.com /script=script.txt /log=winscp.log

If you want to just capture WinSCP console output:

Make sure you are using winscp.com, not winscp.exe.

Run winscp.com via cmd.exe, as that is what understands the >.

cmd.exe /C winscp.com /script=script.txt > winscp.log

In both cases, you will typically need to use full paths to all files (winscp.com, script.txt, winscp.log).


问:
How long does it take to change a thread's priority in Java?
What I can't find is any statement on whether changing a thread's priority is a costly operation, time-wise. I would like to do it frequently, but if each switch carries a significant time penalty it is probably not worth the trouble. </p>

答:
What I can't find is any statement on whether changing a thread's priority is a costly operation, time-wise. I would like to do it frequently, but if each switch carries a significant time penalty it is probably not worth the trouble.

Any answer here is going to be very OS dependent.  I suspect with most Unix variants that the answer is no, it's not costly.  It may require some sort of data synchronization but otherwise it is just setting a value on the thread's administrative information.  I suspect that there is no rescheduling of the threads as discussed in the comments.

That said, without knowing more about your particular use case, I doubt it is going to be worth the trouble.  As I say in the answer listed below, about the only time thread prioritization will make a difference is if all of the threads are completely CPU bound and you want one task or another to get more cycles.

Also, thread priorities are very non-linear and small changes to them may have little to no effect so any overhead incurred in setting the thread priorities will overwhelm any benefits gained by changing them.

See my answer here:
Guide for working with Linux thread priorities and scheduling policies?

Also, check out this article about Java thread priorities and some real life testing of them under Linux.  To quote:

As can be seen, thread priorities 1-8 end up with a practically equal share of the CPU, whilst priorities 9 and 10 get a vastly greater share (though with essentially no difference between 9 and 10). The version tested was Java 6 Update 10.


问:
Change the speed of setContentOffset:animated:?
Is there a way to change the speed of the animation when scrolling a UITableView using setContentOffset:animated:? I want to scroll it to the top, but slowly. When I try the following, it causes the bottom few cells to disappear before the animation starts (specifically, the ones that won't be visible when the scroll is done):

```<code>[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:3.0];
[self.tableView setContentOffset:CGPointMake(0, 0)];
[UIView commitAnimations];
</code>```

Any other way around this problem? There is a private method _setContentOffsetAnimationDuration that works, but I don't want to be rejected from the app store.

答:
Setting the content offset directly did not work for me. However, wrapping setContentOffset(offset, animated: false) inside an animation block did the trick.

```<code>UIView.animate(withDuration: 0.5, animations: {
                self.tableView.setContentOffset(
               CGPoint(x: 0, y: yOffset), animated: false)
            })
</code>```

Body:
Is there a way to change the speed of the animation when scrolling a UITableView using setContentOffset:animated:? I want to scroll it to the top, but slowly. When I try the following, it causes the bottom few cells to disappear before the animation starts (specifically, the ones that won't be visible when the scroll is done):

[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:3.0];
[self.tableView setContentOffset:CGPointMake(0, 0)];
[UIView commitAnimations];

Any other way around this problem? There is a private method _setContentOffsetAnimationDuration that works, but I don't want to be rejected from the app store.

Body:
Setting the content offset directly did not work for me. However, wrapping setContentOffset(offset, animated: false) inside an animation block did the trick.

UIView.animate(withDuration: 0.5, animations: {
                self.tableView.setContentOffset(
               CGPoint(x: 0, y: yOffset), animated: false)
            })


问:
Selective copying maven resources
I have a Java application build under maven. It contains two properties files - application.default.properties and application.properties. The second one suppose to supplement and/or overwrite some properties. I do have also logback.xml file in the same src/main/resources directory.
I want to keep logging and default properties in the jar file but move application.properies to the root of the tree. I put the following piece into the build section of my pom.xml

```<code>    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <targetPath>${user.dir}</targetPath>
            <filtering>false</filtering>
            <includes>
                <include>application.properties</include>
            </includes>
        </resource>
    </resources>
</code>```

It does copy the application.properties file as expected, but other two files disappeared from the jar file.
Can someone please tell me what I am doing wrong and how to alleviate the problem.
P.S. I did browse maven documentation but couldn't find the answer there, so please do not tell me RTFM, but if it is there provide a pointer to it.

答:
What you need is another <resource> section that would include application.default.properties and logback.xml and treat them differently.

```<code><build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <targetPath>${user.dir}</targetPath>
            <filtering>false</filtering>
            <includes>
                <include>application.properties</include>
            </includes>
        </resource>
        <resource>
            <directory>src/main/resources</directory>
            <filtering>false</filtering>
            <excludes>
                <exclude>application.properties</exclude>
            </excludes>
        </resource>
    </resources>
</build>
</code>```

This copies application.properties into ${user.dir}, and packages everything else from src/main/resources into the output jar.

Title: Selective copying maven resources

Body:
I have a Java application build under maven. It contains two properties files - application.default.properties and application.properties. The second one suppose to supplement and/or overwrite some properties. I do have also logback.xml file in the same src/main/resources directory.
I want to keep logging and default properties in the jar file but move application.properies to the root of the tree. I put the following piece into the build section of my pom.xml

    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <targetPath>${user.dir}</targetPath>
            <filtering>false</filtering>
            <includes>
                <include>application.properties</include>
            </includes>
        </resource>
    </resources>

It does copy the application.properties file as expected, but other two files disappeared from the jar file.
Can someone please tell me what I am doing wrong and how to alleviate the problem.
P.S. I did browse maven documentation but couldn't find the answer there, so please do not tell me RTFM, but if it is there provide a pointer to it.

Body:
What you need is another <resource> section that would include application.default.properties and logback.xml and treat them differently.

<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <targetPath>${user.dir}</targetPath>
            <filtering>false</filtering>
            <includes>
                <include>application.properties</include>
            </includes>
        </resource>
        <resource>
            <directory>src/main/resources</directory>
            <filtering>false</filtering>
            <excludes>
                <exclude>application.properties</exclude>
            </excludes>
        </resource>
    </resources>
</build>

This copies application.properties into ${user.dir}, and packages everything else from src/main/resources into the output jar.