问:
Django 1.11.7: How do I call a Class method in Views?
In my models.py I have a Class (Paths) with a method, validate_time that tries to access two fields of the Paths model (time_start, time_end):

```<code>class Paths(m.Model):

  time_start: m.TimeField()
  time_end: m.TimeField()

  def validate_time(self):
     start = self.time_start
     end = self.time_end
     print start #print start to test it out
     #...some function that returns True or False
</code>```

I call validate_time in my views.py:

```<code>from .models import Paths

def paths_data(request):
  ps = Paths()
  valid_times = ps.validate_time()
  if valid_times == False:
     ....
</code>```

I see the method, validate_time, is hit because I see the print statement

But it appears the print out says: None

But time_start and time_end have already been saved to the model as strings. How can I get them as their string value in validate_time?

答:
I think self.time_start might not have been set as ps is an empty Path object initialized by 'ps = Paths()' and time_start does not have a default value.
If you are looking for a saved instance, you need to query database for it first with something like Paths.objects.get(your_key=your_value). More details on queries: https://docs.djangoproject.com/en/1.11/topics/db/queries/</p>

Body:
In my models.py I have a Class (Paths) with a method, validate_time that tries to access two fields of the Paths model (time_start, time_end):

class Paths(m.Model):

  time_start: m.TimeField()
  time_end: m.TimeField()

  def validate_time(self):
     start = self.time_start
     end = self.time_end
     print start #print start to test it out
     #...some function that returns True or False

I call validate_time in my views.py:

from .models import Paths

def paths_data(request):
  ps = Paths()
  valid_times = ps.validate_time()
  if valid_times == False:
     ....

I see the method, validate_time, is hit because I see the print statement

But it appears the print out says: None

But time_start and time_end have already been saved to the model as strings. How can I get them as their string value in validate_time?


来源: stackexchange

问:
In Maven 3.5.2, how do I use a profile defined in my settings.xml file in my pom.xml file?
Say I have the following profile defined in my ~/.m2/settings.xml file

```<code> <profiles>
   <profile>
     <id>artifactory</id>
     </repositories>
        <repository>
          <snapshots>
            <enabled>false</enabled>
          </snapshots>
          <id>thirdparty</id>
          <name>scscm-thirdparty</name>
          <url>http://www.mycompany.com/artifactory/my-thirdparty-repo</url>
        </repository>
      </repositories>
    </profile>
  </profiles>
</code>```

Now I want to download a home-built apr-1.6.2.tar.gz arfifact from the thirdparty repository id defined in the settings.xml, so in my pom.xml file I have

```<code><artifactId>apr</artifactId>
<groupId>com.company</groupId>
<version>1.6.2</version>
<packaging>pom</packaging>

<dependencies>
  <dependency>
    <groupId>org.apache</groupId>
    <artifactId>apr</artifactId>
    <version>1.6.2</version>
    <type>tar.gz</type>
  </dependency>
</dependencies>

<build>
  <plugins>
    <plugin>
    <groupId>com.googlecode.maven-download-plugin</groupId>
    <artifactId>download-maven-plugin</artifactId>
    <version>1.4.0</version>
    <executions>
      <execution>
        <id>apr</id>
        <phase>pre-integration-test</phase>
          <goals>
            <goal>wget</goal>
          </goals>
          <configuration>
            # HOW DO I SPECIFY URL FROM PROFILE HERE????
           <unpack>false</unpack>
         </configuration>
      </execution>
    </executions>
    </plugin>
  </plujgins>
</build>
</code>```

I see examples of profiles online, but they're all defined in the pom.xml itself, but that's not what I want to do. I just want to use a URL defined in my settings.xml profile inside my pom.xml file.

答:
activate them via command-line (-P <name>) or with triggers what ever you like. but ask yourself, whether it is the right place to locate your profile. for further info look at  the documentation:

1.Maven Doc

same question?

Profile activation in Eclipse

ContentLicense: CC BY-SA 3.0

Body:
Say I have the following profile defined in my ~/.m2/settings.xml file

 <profiles>
   <profile>
     <id>artifactory</id>
     </repositories>
        <repository>
          <snapshots>
            <enabled>false</enabled>
          </snapshots>
          <id>thirdparty</id>
          <name>scscm-thirdparty</name>
          <url>http://www.mycompany.com/artifactory/my-thirdparty-repo</url>
        </repository>
      </repositories>
    </profile>
  </profiles>

Now I want to download a home-built apr-1.6.2.tar.gz arfifact from the thirdparty repository id defined in the settings.xml, so in my pom.xml file I have

<artifactId>apr</artifactId>
<groupId>com.company</groupId>
<version>1.6.2</version>
<packaging>pom</packaging>

<dependencies>
  <dependency>
    <groupId>org.apache</groupId>
    <artifactId>apr</artifactId>
    <version>1.6.2</version>
    <type>tar.gz</type>
  </dependency>
</dependencies>

<build>
  <plugins>
    <plugin>
    <groupId>com.googlecode.maven-download-plugin</groupId>
    <artifactId>download-maven-plugin</artifactId>
    <version>1.4.0</version>
    <executions>
      <execution>
        <id>apr</id>
        <phase>pre-integration-test</phase>
          <goals>
            <goal>wget</goal>
          </goals>
          <configuration>
            # HOW DO I SPECIFY URL FROM PROFILE HERE????
           <unpack>false</unpack>
         </configuration>
      </execution>
    </executions>
    </plugin>
  </plujgins>
</build>

I see examples of profiles online, but they're all defined in the pom.xml itself, but that's not what I want to do. I just want to use a URL defined in my settings.xml profile inside my pom.xml file.


问:
Google Chrome extension: How to find out if a user has signed in to the Chrome browser?
As part of a Google Chrome extension that I'm building I need to be able to tell if a user has signed in to the Google Chrome browser while the extension is enabled.

How can I do this?

Please note that using OAuth2 (and thus, the chrome.identity API) is beyond the scope of my project so I need to find another way.

EDIT: my question is not a duplicate of this one because the solution in that thread no longer works.

答:
```<code>chrome.identity.getAuthToken({interactive: false}, function (token) {
    if (!token) {
        if (chrome.runtime.lastError.message.match(/not signed in/)) {
            console.log("not singed in");
        } else {
            console.log("singed in");
        }
    }
});
</code>```

And don't forget to add "identity" to permissions.

Body:
chrome.identity.getAuthToken({interactive: false}, function (token) {
    if (!token) {
        if (chrome.runtime.lastError.message.match(/not signed in/)) {
            console.log("not singed in");
        } else {
            console.log("singed in");
        }
    }
});

And don't forget to add "identity" to permissions.


问:
Transition from sentence to one word
What I am trying to achieve is to animate an element width few words in the way that hovered word leaves in the center of the element and the rest smoothly goes out of the bounds. I would also keep it as clear as possible in HTML and not to use fixed pixel amount of margins/widths to position elements.

The very lousy sketch of what I have on my mind is here:

* {
  transition: all 1.5s;
}

div {
  min-width: 150px;
  width: 30%;
  height: 25px;
  line-height: 25px;
  background: orange;
  text-align: center;
  overflow: hidden;
}

div:hover {
  background: white;
  word-spacing: 300px;
}

a:hover::after,
a:hover::before {
  content: ' ';
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  First & Second
</div></code>```

Each word on hover should go to center (possibly not with those 'jumps' visible now when other words disapear). Do you have any ideas? I'm pretty sure that the way I try to follow with word-spacing is wrong.

答:
The issue is that when increasing word spacing the text goes to new line and create this jump thing. So you may add white-space: nowrap and you can also use padding-left to push text and make it in the center :

div {
  min-width: 150px;
  width: 180px;
  height: 25px;
  line-height: 25px;
  background: orange;
  text-align: center;
  overflow: hidden;
  transition: all 0.5s;
  box-sizing: border-box;
  white-space: nowrap;
}

div:hover {
  word-spacing: 80px;
  padding-left: 80px;
  background: white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  First & Second
</div></code>```

Actually the word spacing is applied to the div so you cannot apply hover on word. It's also easier to apply this technique on the first word as the second one will be hide with overflow, but am not sure how you can do the same with the second word with the use of word-spacing.

Here is another idea on how you can do without word-spacing. I used some padding animation and also pseudo element to hide the first word when hovering the second one.

div {
  min-width: 150px;
  width: 180px;
  height: 25px;
  line-height: 25px;
  background: orange;
  text-align: center;
  overflow: hidden;
  transition: all 0.5s;
  box-sizing: border-box;
  white-space: nowrap;
}

.afirst,
.asecond {
  position:relative;
  display: inline-block;
  transition: all 0.5s;
}

.afirst:hover {
  padding: 0 44%;
  background: white;
}
.asecond:hover {
  padding: 0 50% 0 0;
  background: white;
}
.asecond:hover::before {
  content:" ";
  position:absolute;
  left:-50%;
  width:50%;
  top:0;
  bottom:0;
  z-index:99;
  background:#fff;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  First & Second
</div></code>```

I think you can generalize this solution by using :before element in the left and :after element in the right to hide everything else.

Here is an example with multiple word (but not giving center alignement correctly, still need improvement) :

div {
  min-width: 150px;
  height: 25px;
  line-height: 25px;
  background: orange;
  text-align: center;
  overflow: hidden;
  transition: all 0.5s;
  box-sizing: border-box;
  white-space: nowrap;
}

.word {
  position: relative;
  display: inline-block;
  transition: all 0.5s;
}

.word:hover {
  background: white;
  padding: 0 40%;
}

.word:hover::before {
  content: " ";
  position: absolute;
  left: -50%;
  width: 50%;
  top: 0;
  bottom: 0;
  z-index: 99;
  background: #fff;
}

.word:hover::after {
  content: " ";
  position: absolute;
  right: -50%;
  width: 50%;
  top: 0;
  bottom: 0;
  z-index: 99;
  background: #fff;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  First &
  Second &
  third &
  Fourth
</div></code>```

Another solution with perfect centering but less animation for the other words :

div {
  position:relative;
  height: 25px;
  width:500px;
  margin:0 auto;
  line-height: 25px;
  background: orange;
  text-align: center;
  overflow: hidden;
  transition: all 0.5s;
  box-sizing: border-box;
  white-space: nowrap;
}

.word {
  position: relative;
  z-index:9;
  display: inline-block;
  transition: all 0.5s;
}

.word:hover {
  position:absolute;
  right:0;
  left:0;
  top:0;
  bottom:0;
  text-align:center;
  background: white;
  z-index:99;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  First &
  Second &
  third &
  Fourth
</div></code>```

Title: Transition from sentence to one word

Body:
What I am trying to achieve is to animate an element width few words in the way that hovered word leaves in the center of the element and the rest smoothly goes out of the bounds. I would also keep it as clear as possible in HTML and not to use fixed pixel amount of margins/widths to position elements.

The very lousy sketch of what I have on my mind is here:

* {
  transition: all 1.5s;
}

div {
  min-width: 150px;
  width: 30%;
  height: 25px;
  line-height: 25px;
  background: orange;
  text-align: center;
  overflow: hidden;
}

div:hover {
  background: white;
  word-spacing: 300px;
}

a:hover::after,
a:hover::before {
  content: ' ';
}

  First & Second

Each word on hover should go to center (possibly not with those 'jumps' visible now when other words disapear). Do you have any ideas? I'm pretty sure that the way I try to follow with word-spacing is wrong.

Body:
The issue is that when increasing word spacing the text goes to new line and create this jump thing. So you may add white-space: nowrap and you can also use padding-left to push text and make it in the center :

div {
  min-width: 150px;
  width: 180px;
  height: 25px;
  line-height: 25px;
  background: orange;
  text-align: center;
  overflow: hidden;
  transition: all 0.5s;
  box-sizing: border-box;
  white-space: nowrap;
}

div:hover {
  word-spacing: 80px;
  padding-left: 80px;
  background: white;
}

<div>
  <a class="afirst" href="">First</a> & <a class="asecond" href="">Second</a>
</div>

Actually the word spacing is applied to the div so you cannot apply hover on word. It's also easier to apply this technique on the first word as the second one will be hide with overflow, but am not sure how you can do the same with the second word with the use of word-spacing.

Here is another idea on how you can do without word-spacing. I used some padding animation and also pseudo element to hide the first word when hovering the second one.

div {
  min-width: 150px;
  width: 180px;
  height: 25px;
  line-height: 25px;
  background: orange;
  text-align: center;
  overflow: hidden;
  transition: all 0.5s;
  box-sizing: border-box;
  white-space: nowrap;
}

.afirst,
.asecond {
  position:relative;
  display: inline-block;
  transition: all 0.5s;
}

.afirst:hover {
  padding: 0 44%;
  background: white;
}
.asecond:hover {
  padding: 0 50% 0 0;
  background: white;
}
.asecond:hover::before {
  content:" ";
  position:absolute;
  left:-50%;
  width:50%;
  top:0;
  bottom:0;
  z-index:99;
  background:#fff;
}

<div>
  <a class="afirst" href="">First</a> & <a class="asecond" href="">Second</a>
</div>

I think you can generalize this solution by using :before element in the left and :after element in the right to hide everything else.

Here is an example with multiple word (but not giving center alignement correctly, still need improvement) :

div {
  min-width: 150px;
  height: 25px;
  line-height: 25px;
  background: orange;
  text-align: center;
  overflow: hidden;
  transition: all 0.5s;
  box-sizing: border-box;
  white-space: nowrap;
}

.word {
  position: relative;
  display: inline-block;
  transition: all 0.5s;
}

.word:hover {
  background: white;
  padding: 0 40%;
}

.word:hover::before {
  content: " ";
  position: absolute;
  left: -50%;
  width: 50%;
  top: 0;
  bottom: 0;
  z-index: 99;
  background: #fff;
}

.word:hover::after {
  content: " ";
  position: absolute;
  right: -50%;
  width: 50%;
  top: 0;
  bottom: 0;
  z-index: 99;
  background: #fff;
}

<div>
  <a class="word" href="">First</a> &
  <a class="word" href="">Second</a> &
  <a class="word" href="">third</a> &
  <a class="word" href="">Fourth</a>
</div>

Another solution with perfect centering but less animation for the other words :

div {
  position:relative;
  height: 25px;
  width:500px;
  margin:0 auto;
  line-height: 25px;
  background: orange;
  text-align: center;
  overflow: hidden;
  transition: all 0.5s;
  box-sizing: border-box;
  white-space: nowrap;
}

.word {
  position: relative;
  z-index:9;
  display: inline-block;
  transition: all 0.5s;
}

.word:hover {
  position:absolute;
  right:0;
  left:0;
  top:0;
  bottom:0;
  text-align:center;
  background: white;
  z-index:99;
}

<div>
  <a class="word" href="">First</a> &
  <a class="word" href="">Second</a> &
  <a class="word" href="">third</a> &
  <a class="word" href="">Fourth</a>
</div>


问:
Visible browser reflow
I'm trying to make a window based application for web browsers. The number of windows is considerably high, so I'm storing them as HTML files (one per window) that I asynchronously retrieve from the server according to user interaction.

To add a window to the main page, I first add the link elements (CSS) of the downloaded document to its head section, and then I append the content of the body section to a certain div. When a window is closed, I just remove these elements.

This approach seems to be working nicely, but I can see that sometimes when I add a window, its elements are visible out of position with no style, and after a brief moment they are correctly painted.

I don't have a strong background in web programming, but I suspect this might be related to what it is called "browser reflow". Does it mean that it is taking too much time to repaint everything? Is it possible to just hide these "unstyled" elements until it is safe to show them?

Any guidance would be appreciated.

答: Some time away from the computer seems to have relaxed my mind. I was erroneously assuming that adding new link elements to the head section would load the CSS files immediately. Obviously, the browser needs to retrieve them from the server first. So, the DOM elements I'm adding don't show their style because the CSS files have not been downloaded yet. I think this is the right answer.

Title: Visible browser reflow


问:
how can i write a function which will multiply every alphabet of string n times in Haskell
I'm trying to write a function that takes a String and an Int and returns that every element of string  is multiplyed "int" times. That is:

```<code>duplicate :: String -> Int -> String
duplicate " abc " 2
</code>```

the output should be

```<code>Main >> "   aabbcc   "
</code>```

答:
You should look at the following functions in Prelude:

map :: (a -> b) -> [a] -> [b] to "do someting" with every element of a list

replicate :: Int -> a -> [a] to replicate an item n times

concat :: Foldable t => t [a] -> [a] to concat, e.g a list of lists into a single list

Body:
I'm trying to write a function that takes a String and an Int and returns that every element of string  is multiplyed "int" times. That is:

duplicate :: String -> Int -> String
duplicate " abc " 2

the output should be

Main >> "   aabbcc   "


问:
Create React App with react-svg-loader without ejecting fails when trying to minify
I am using create-react-app to build my React application. I've added react-svg-loader and using it in this way:

```<code>export { default as arrowLeft } from '-!react-svg-loader!./arrow-left.svg';
export { default as arrowRight } from '-!react-svg-loader!./arrow-right.svg';
</code>```

But when I am trying to run yarn build - process fails on minification step:

Creating an optimized production build... Failed to compile.

Failed to minify the code from this file:

```<code>    ./node_modules/react-svg-loader/lib/loader.js!./src/icons/arrow-left.svg:6
</code>```

Read more here: http://bit .ly/2tRViJ9

Can I fix it somehow without ejecting?

答:
You need to disable eslint at the top of the file where you import your svg</p>

```<code>/* eslint import/no-webpack-loader-syntax: off */
</code>```

Body:
I am using create-react-app to build my React application. I've added react-svg-loader and using it in this way:

export { default as arrowLeft } from '-!react-svg-loader!./arrow-left.svg';
export { default as arrowRight } from '-!react-svg-loader!./arrow-right.svg';

But when I am trying to run yarn build - process fails on minification step:

Creating an optimized production build... Failed to compile.

Failed to minify the code from this file:

    ./node_modules/react-svg-loader/lib/loader.js!./src/icons/arrow-left.svg:6

Read more here: http://bit .ly/2tRViJ9

Can I fix it somehow without ejecting?

Body:
You need to disable eslint at the top of the file where you import your svg

/* eslint import/no-webpack-loader-syntax: off */


问:
Detecting whether user is logged in or not from a Chrome extension
is there an easy way to detect from a Chrome extension that the user is logged into his google account or not.

I guess there is a nasty way to figure this out by loading a html/css/js resource that requires authentication.
But i'd like to do this in a "clear" way.

thx and best,
 Viktor

ContentLicense: CC BY-SA 2.5


问:
shared-ptr map with lldb pretty printers
I have a std::map where I am using shared_ptrs as keys:

```<code>std::map<shared_ptr<object>, shared_ptr<object>>
</code>```

However, when debugging, I am unable to open these maps using lldb on macOS or gdb on linux. With gdb this issue was fixed on Ubuntu by modifying the file libstdcxx/v6/printers.py and adding iterators to the SharedPointerPrinter class (code shown below). However, I don't know how to fix this issue for lldb. If anyone can help me or point me in the right direction that would be great.

Please let me know if you need other information in order to help me solve this issue and I will happily provide it.

```<code>class SharedPointerPrinter:
    "Print a shared_ptr or weak_ptr"

    class _iterator:
        def __init__(self, sharedPointer):
            self.sharedPointer = sharedPointer
            self.managedValue = sharedPointer.val['_M_ptr']
            self.count = 0

        def __iter__(self):
            return self

        def next(self):
            if self.managedValue == 0:
                raise StopIteration
            self.count = self.count + 1
            if (self.count == 1):
                return ('Use count', self.sharedPointer.val['_M_refcount']['_M_pi']['_M_use_count'])
            elif (self.count == 2):
                return ('Weak count', self.sharedPointer.val['_M_refcount']['_M_pi']['_M_weak_count'] - 1)
            elif (self.count == 3):
                return ('Managed value', self.managedValue)
            else:
                raise StopIteration

    def __init__ (self, typename, val):
        self.typename = typename
        self.val = val

    def children (self):
        return self._iterator(self)

    def to_string (self):
        state = 'empty'
        refcounts = self.val['_M_refcount']['_M_pi']
        if refcounts != 0:
            usecount = refcounts['_M_use_count']
            weakcount = refcounts['_M_weak_count']
            if usecount == 0:
                state = 'expired, weakcount %d' % weakcount
            else:
                state = 'usecount %d, weakcount %d' % (usecount, weakcount - 1)
        return '%s (%s) to %s' % (self.typename, state, self.val['_M_ptr'])
</code>```

答:
You can do pretty much the same thing using lldb's Python data formatters as described on this page:

http://lldb.llvm.org/varformats.html

lldb has data formatters for std::map and std::shared_ptr for clang's version of STL.  So for instance, I see:

```<code>(lldb) fr v a_map
(std::__1::map<std::__1::shared_ptr<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >, std::__1::shared_ptr<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >, std::__1::less<std::__1::shared_ptr<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > >, std::__1::allocator<std::__1::pair<const std::__1::shared_ptr<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >, std::__1::shared_ptr<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > > > >) a_map = size=1 {
  [0] = {
    first = "some text" strong=2 weak=1 {
      __ptr_ = "some text"
    }
    second = "other text" strong=2 weak=1 {
      __ptr_ = "other text"
    }
  }
}
</code>```

Man, those C++ types are verbose!

There are also some formatters for the gcc's STL but I don't know as much about the state of those formatters.

IIUC the data formatters can be used in expressions in gdb.  In lldb, the frame variable command will accept simple structure access expressions, so you can do:

```<code>(lldb) frame var a_map[0].first
(const std::__1::shared_ptr<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >) a_map[0].first = "some text" strong=2 weak=1 {
  __ptr_ = "some text"
}
</code>```

But you can't use the data formatter produced children in the full expression parser.

Body:
I have a std::map where I am using shared_ptrs as keys:

std::map<shared_ptr<object>, shared_ptr<object>>

However, when debugging, I am unable to open these maps using lldb on macOS or gdb on linux. With gdb this issue was fixed on Ubuntu by modifying the file libstdcxx/v6/printers.py and adding iterators to the SharedPointerPrinter class (code shown below). However, I don't know how to fix this issue for lldb. If anyone can help me or point me in the right direction that would be great.

Please let me know if you need other information in order to help me solve this issue and I will happily provide it.

class SharedPointerPrinter:
    "Print a shared_ptr or weak_ptr"

    class _iterator:
        def __init__(self, sharedPointer):
            self.sharedPointer = sharedPointer
            self.managedValue = sharedPointer.val['_M_ptr']
            self.count = 0

        def __iter__(self):
            return self

        def next(self):
            if self.managedValue == 0:
                raise StopIteration
            self.count = self.count + 1
            if (self.count == 1):
                return ('Use count', self.sharedPointer.val['_M_refcount']['_M_pi']['_M_use_count'])
            elif (self.count == 2):
                return ('Weak count', self.sharedPointer.val['_M_refcount']['_M_pi']['_M_weak_count'] - 1)
            elif (self.count == 3):
                return ('Managed value', self.managedValue)
            else:
                raise StopIteration

    def __init__ (self, typename, val):
        self.typename = typename
        self.val = val

    def children (self):
        return self._iterator(self)

    def to_string (self):
        state = 'empty'
        refcounts = self.val['_M_refcount']['_M_pi']
        if refcounts != 0:
            usecount = refcounts['_M_use_count']
            weakcount = refcounts['_M_weak_count']
            if usecount == 0:
                state = 'expired, weakcount %d' % weakcount
            else:
                state = 'usecount %d, weakcount %d' % (usecount, weakcount - 1)
        return '%s (%s) to %s' % (self.typename, state, self.val['_M_ptr'])

Body:
You can do pretty much the same thing using lldb's Python data formatters as described on this page:

http://lldb.llvm.org/varformats.html

lldb has data formatters for std::map and std::shared_ptr for clang's version of STL.  So for instance, I see:

(lldb) fr v a_map
(std::__1::map<std::__1::shared_ptr<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >, std::__1::shared_ptr<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >, std::__1::less<std::__1::shared_ptr<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > >, std::__1::allocator<std::__1::pair<const std::__1::shared_ptr<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >, std::__1::shared_ptr<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > > > >) a_map = size=1 {
  [0] = {
    first = "some text" strong=2 weak=1 {
      __ptr_ = "some text"
    }
    second = "other text" strong=2 weak=1 {
      __ptr_ = "other text"
    }
  }
}

Man, those C++ types are verbose!

There are also some formatters for the gcc's STL but I don't know as much about the state of those formatters.

IIUC the data formatters can be used in expressions in gdb.  In lldb, the frame variable command will accept simple structure access expressions, so you can do:

(lldb) frame var a_map[0].first
(const std::__1::shared_ptr<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >) a_map[0].first = "some text" strong=2 weak=1 {
  __ptr_ = "some text"
}

But you can't use the data formatter produced children in the full expression parser.


问:
Storage Optimisation: JSON vs String with delimiters
The below JSON file costs 163 bytes to store.

```<code>{
  "locations": [
    {
      "station": 6,
      "category": 1034,
      "type": 5
    },
    {
      "station": 3,
      "category": 1171,
      "type": 7
    },
  ]
}
</code>```

But, If the values are put together as a string with delimiters ',' and '_', 6_1034_5,3_1171_7 costs only 17 bytes.

What are the problems with this approach?

Thank you.

答:
The problems that I have seen with this sort of approach are mainly centered around maintainability.

With the delimited approach, the properties of your location items are identified by ordinal. Since there are all numbers, there is nothing to tell you whether the first segment is the station, category, or type; you must know that in advance. Someone new to your code base may not know that and therefore introduce bugs.

Right now all of your data are integers, which are relatively easy to encode and decode and do not risk conflicting with your delimiters. However, if you need to add user-supplied text at some point, you run the risk of that text containing your delimiters. In that case, you will have to invent an escaping/encoding mechanism to ensure that you can reliably detect your delimiters. This may seem simple, but it is more difficult than you may suspect. I've seen it done incorrectly many times.

Using a well-known structured text format like XML or JSON has the advantages that it has fully developed and tested rules for dealing with all types of text, and there are fully developed and tested libraries for reading and writing it.

Depending on your circumstances, this concern over the amount of storage could be a micro-optimization. You might want to try some capacity calculations (e.g., how much actual storage is required for X items) and compare that to the expected number of items vs. the expected amount of storage that will be available.

Body:
The below JSON file costs 163 bytes to store.

{
  "locations": [
    {
      "station": 6,
      "category": 1034,
      "type": 5
    },
    {
      "station": 3,
      "category": 1171,
      "type": 7
    },
  ]
}

But, If the values are put together as a string with delimiters ',' and '_', 6_1034_5,3_1171_7 costs only 17 bytes.

What are the problems with this approach?

Thank you.


问:
Eclipse C Build selected files generates no executable
I'd like to build a single C file on Windows using Eclipse Helios and Cygwin. I rightclick on the file, select "Build selected file", the console output returns but I can't find an executable. I can't use the build project function because I have multiple folders with different applications. (for example it complains that I have more than one main function)

Console output:

Rebuilding selected file(s)

**** Internal Builder is used for build               **** gcc -O0 -g3 -Wall -c -fmessage-length=0 -ofolder\test.o ..\folder\test.c

Build of selected resources is complete.

Build and Run works when I have just one src folder with a single Hello World file for example.

答: the -c in the build statement will only compile, not link so no executable will be generated.  However, an object file will be placed in ../folder  named test.o


问:
XSD 1.0 regex to not match two specific hexadecimal strings
I've been trying to come up with a regex in an XML Schema to match a hex string in the range of 000001-FFFFFE. I can get either 000000 or FFFFFF to not match, but not both within one expression.

Strings that should match: EFEFEF, EEEEEF, FFFFFE, 101010, 10000, 000001

Strings that shouldn't match: 000000, FFFFFF

Anyone have any ideas? I've been beating my head against my keyboard for a few days over this.

In short, all 6-digit hexadecimal values except 000000 and FFFFFF should be allowed.

答:
The following XSD, requiring only XSD 1.0,

```<code><?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:simpleType name="OneHexDigitNot0">
    <xs:restriction base="xs:string">
      <xs:pattern            value="[1-9A-F][0-9A-F]{5}"/>
      <xs:pattern value="[0-9A-F]{1}[1-9A-F][0-9A-F]{4}"/>
      <xs:pattern value="[0-9A-F]{2}[1-9A-F][0-9A-F]{3}"/>
      <xs:pattern value="[0-9A-F]{3}[1-9A-F][0-9A-F]{2}"/>
      <xs:pattern value="[0-9A-F]{4}[1-9A-F][0-9A-F]{1}"/>
      <xs:pattern value="[0-9A-F]{5}[1-9A-F]"/>
    </xs:restriction>
  </xs:simpleType>
  <xs:simpleType name="OneHexDigitNot0AndOneHexDigitNotF">
    <xs:restriction base="OneHexDigitNot0">
      <xs:pattern            value="[0-9A-E][0-9A-F]{5}"/>
      <xs:pattern value="[0-9A-F]{1}[0-9A-E][0-9A-F]{4}"/>
      <xs:pattern value="[0-9A-F]{2}[0-9A-E][0-9A-F]{3}"/>
      <xs:pattern value="[0-9A-F]{3}[0-9A-E][0-9A-F]{2}"/>
      <xs:pattern value="[0-9A-F]{4}[0-9A-E][0-9A-F]{1}"/>
      <xs:pattern value="[0-9A-F]{5}[0-9A-E]"/>
    </xs:restriction>
  </xs:simpleType>

  <xs:element name="r" type="OneHexDigitNot0AndOneHexDigitNotF"/>
</xs:schema>
</code>```

will successfully validate XML documents with an r root element and 6-digit hexadecimal content, except 000000 and FFFFFF, as requested.

Body:
The following XSD, requiring only XSD 1.0,

<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:simpleType name="OneHexDigitNot0">
    <xs:restriction base="xs:string">
      <xs:pattern            value="[1-9A-F][0-9A-F]{5}"/>
      <xs:pattern value="[0-9A-F]{1}[1-9A-F][0-9A-F]{4}"/>
      <xs:pattern value="[0-9A-F]{2}[1-9A-F][0-9A-F]{3}"/>
      <xs:pattern value="[0-9A-F]{3}[1-9A-F][0-9A-F]{2}"/>
      <xs:pattern value="[0-9A-F]{4}[1-9A-F][0-9A-F]{1}"/>
      <xs:pattern value="[0-9A-F]{5}[1-9A-F]"/>
    </xs:restriction>
  </xs:simpleType>
  <xs:simpleType name="OneHexDigitNot0AndOneHexDigitNotF">
    <xs:restriction base="OneHexDigitNot0">
      <xs:pattern            value="[0-9A-E][0-9A-F]{5}"/>
      <xs:pattern value="[0-9A-F]{1}[0-9A-E][0-9A-F]{4}"/>
      <xs:pattern value="[0-9A-F]{2}[0-9A-E][0-9A-F]{3}"/>
      <xs:pattern value="[0-9A-F]{3}[0-9A-E][0-9A-F]{2}"/>
      <xs:pattern value="[0-9A-F]{4}[0-9A-E][0-9A-F]{1}"/>
      <xs:pattern value="[0-9A-F]{5}[0-9A-E]"/>
    </xs:restriction>
  </xs:simpleType>

  <xs:element name="r" type="OneHexDigitNot0AndOneHexDigitNotF"/>
</xs:schema>

will successfully validate XML documents with an r root element and 6-digit hexadecimal content, except 000000 and FFFFFF, as requested.


问:
Trouble updating WPF with UpdateSourceTrigger = PropertyChanged
First (full disclosure), I am a relative beginner with C#, so this is probably an obvious oops.  I've reviewed dozens of similar questions and examples here on stackoverflow already and I still can't put my finder on what I am doing wrong.  I started with a VS 2017 WPFapp project. Changed the OnStartup so I could load my window manually.  Created a class with a timer that increments a value and then used  INotifyPropertyChanged to update a TextBox on my MainWindow.

The WPF window loads fine.  The TextBlock starts with a value of 5, so the binding is at least pointing to my class and value.  You will note in the output that the value is updating with the timer event, and the NotifyPropertyChanged is firing but the TextBlock never changes.

My only thought is that the TextBlock is linked to the wrong instance of my UpdateWPF class, but I don't see how that could be.

Thanks in advance for the help!

Here is my code...

MainWindow.xaml: (Really just dropped a textblock and set the binding)

```<code><Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp1"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">

    <Grid>
        <TextBlock HorizontalAlignment="Left" Height="50" Margin="139,123,0,0" TextWrapping="Wrap" Text="{Binding Path=GetValue,Mode=OneTime,UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Top" Width="215"/>
    </Grid>
</Window>
</code>```

MainWindow.xaml.cs (Didn't change this code at all)

```<code>namespace WpfApp1
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }
}
</code>```

App.xaml (just commented out the StartupUri)

```<code><Application x:Class="WpfApp1.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:WpfApp1">
            <!--StartupUri="MainWindow.xaml"-->
    <Application.Resources>

    </Application.Resources>
</Application>
</code>```

App.xaml.cs (The meat and potatoes)

```<code>namespace WpfApp1
{
    public partial class App : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {

            base.OnStartup(e);
            UpdateWPF uWPF = new UpdateWPF();
            MainWindow w = new MainWindow();
            w.DataContext = uWPF;
            w.Show();
        }

        public class UpdateWPF : INotifyPropertyChanged
        {
            public event PropertyChangedEventHandler PropertyChanged;
            private void NotifyPropertyChanged(String propertyName)
            {
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
                Console.WriteLine("NotifyPropertyChanged Fired.");
            }

            private int value = 5;
            public UpdateWPF()
            {
                Timer aTimer = new System.Timers.Timer();
                aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
                aTimer.Interval = 1000;
                aTimer.Enabled = true;
            }
            private void OnTimedEvent(object source, ElapsedEventArgs e)
            {
                value++;
                Console.WriteLine("Timer Event Fired. New Value is " + value.ToString());
                NotifyPropertyChanged(nameof(GetValue));
            }
            public string GetValue => (value.ToString());
        }
    }
}
</code>```

and the output

```<code>Timer Event Fired. New Value is 6
NotifyPropertyChanged Fired.
Timer Event Fired. New Value is 7
NotifyPropertyChanged Fired.
Timer Event Fired. New Value is 8
NotifyPropertyChanged Fired.
Timer Event Fired. New Value is 9
NotifyPropertyChanged Fired.
Timer Event Fired. New Value is 10
NotifyPropertyChanged Fired.
Timer Event Fired. New Value is 11
NotifyPropertyChanged Fired.
</code>```

答:
As already said in the comment above, you have to set your UpdateSourceTrigger correctly. I also do not recommend the way you implemented your properties. They should look like this:

```<code>private int _value;

public int Value
{
    get => _value;
    set
    {
        _value = value;
        OnPropertyChanged(nameof(Value));
    }
}
</code>```

Now you can just say Value = 0; instead of raising the PropertyChanged event manually.

If you change your NotifyPropertyChanged method to this:

```<code>private void NotifyPropertyChanged([CallerMemberName] string propertyName = null)
{
    PropertyChanged?.Invoke(this, new PropertyChangedEventArgw(propertyName));
            Console.WriteLine("NotifyPropertyChanged Fired.");
}
</code>```

you don't have to pass the property name to NotifyPropertyChanged. The runtime will do this automatically, because of the CallerMemberNameAttribute.

Greetings

Loris

EDIT:

My property example was just an example for a property, not yours. But you just have to change the type and it will work.

This should work for you:

```<code>public class UpdateWPF : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
            Console.WriteLine("NotifyPropertyChanged Fired.");
        }

        private int _value = 5;

        public UpdateWPF()
        {
            Timer aTimer = new System.Timers.Timer();
            aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
            aTimer.Interval = 1000;
            aTimer.Enabled = true;
        }
        private void OnTimedEvent(object source, ElapsedEventArgs e)
        {
            var i = Convert.ToInt32(value);
            Value = ++i;
        }
        public string Value
        {
            get => _value;
            set
            {
                _value = value;
                NotifyPropertyChanged();
            }
        }
    }
</code>```

Body:
First (full disclosure), I am a relative beginner with C#, so this is probably an obvious oops.  I've reviewed dozens of similar questions and examples here on stackoverflow already and I still can't put my finder on what I am doing wrong.  I started with a VS 2017 WPFapp project. Changed the OnStartup so I could load my window manually.  Created a class with a timer that increments a value and then used  INotifyPropertyChanged to update a TextBox on my MainWindow.

The WPF window loads fine.  The TextBlock starts with a value of 5, so the binding is at least pointing to my class and value.  You will note in the output that the value is updating with the timer event, and the NotifyPropertyChanged is firing but the TextBlock never changes.

My only thought is that the TextBlock is linked to the wrong instance of my UpdateWPF class, but I don't see how that could be.

Thanks in advance for the help!

Here is my code...

MainWindow.xaml: (Really just dropped a textblock and set the binding)

<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp1"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">

    <Grid>
        <TextBlock HorizontalAlignment="Left" Height="50" Margin="139,123,0,0" TextWrapping="Wrap" Text="{Binding Path=GetValue,Mode=OneTime,UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Top" Width="215"/>
    </Grid>
</Window>

MainWindow.xaml.cs (Didn't change this code at all)

namespace WpfApp1
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }
}

App.xaml (just commented out the StartupUri)

<Application x:Class="WpfApp1.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:WpfApp1">

    <Application.Resources>

    </Application.Resources>
</Application>

App.xaml.cs (The meat and potatoes)

namespace WpfApp1
{
    public partial class App : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {

            base.OnStartup(e);
            UpdateWPF uWPF = new UpdateWPF();
            MainWindow w = new MainWindow();
            w.DataContext = uWPF;
            w.Show();
        }

        public class UpdateWPF : INotifyPropertyChanged
        {
            public event PropertyChangedEventHandler PropertyChanged;
            private void NotifyPropertyChanged(String propertyName)
            {
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
                Console.WriteLine("NotifyPropertyChanged Fired.");
            }

            private int value = 5;
            public UpdateWPF()
            {
                Timer aTimer = new System.Timers.Timer();
                aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
                aTimer.Interval = 1000;
                aTimer.Enabled = true;
            }
            private void OnTimedEvent(object source, ElapsedEventArgs e)
            {
                value++;
                Console.WriteLine("Timer Event Fired. New Value is " + value.ToString());
                NotifyPropertyChanged(nameof(GetValue));
            }
            public string GetValue => (value.ToString());
        }
    }
}

and the output

Timer Event Fired. New Value is 6
NotifyPropertyChanged Fired.
Timer Event Fired. New Value is 7
NotifyPropertyChanged Fired.
Timer Event Fired. New Value is 8
NotifyPropertyChanged Fired.
Timer Event Fired. New Value is 9
NotifyPropertyChanged Fired.
Timer Event Fired. New Value is 10
NotifyPropertyChanged Fired.
Timer Event Fired. New Value is 11
NotifyPropertyChanged Fired.

Body:
As already said in the comment above, you have to set your UpdateSourceTrigger correctly. I also do not recommend the way you implemented your properties. They should look like this:

private int _value;

public int Value
{
    get => _value;
    set
    {
        _value = value;
        OnPropertyChanged(nameof(Value));
    }
}

Now you can just say Value = 0; instead of raising the PropertyChanged event manually.

If you change your NotifyPropertyChanged method to this:

private void NotifyPropertyChanged([CallerMemberName] string propertyName = null)
{
    PropertyChanged?.Invoke(this, new PropertyChangedEventArgw(propertyName));
            Console.WriteLine("NotifyPropertyChanged Fired.");
}

you don't have to pass the property name to NotifyPropertyChanged. The runtime will do this automatically, because of the CallerMemberNameAttribute.

Greetings

Loris

EDIT:

My property example was just an example for a property, not yours. But you just have to change the type and it will work.

This should work for you:

public class UpdateWPF : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
            Console.WriteLine("NotifyPropertyChanged Fired.");
        }

        private int _value = 5;

        public UpdateWPF()
        {
            Timer aTimer = new System.Timers.Timer();
            aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
            aTimer.Interval = 1000;
            aTimer.Enabled = true;
        }
        private void OnTimedEvent(object source, ElapsedEventArgs e)
        {
            var i = Convert.ToInt32(value);
            Value = ++i;
        }
        public string Value
        {
            get => _value;
            set
            {
                _value = value;
                NotifyPropertyChanged();
            }
        }
    }


问:
Git: "Not currently on any branch." Is there an easy way to get back on a branch, while keeping the changes?
So I've done some work in the repository and when I'm about to commit I realize that I'm not currently on any branch.

This happens a lot when working with submodules and I am able to solve it, but the process is tedious and I've been thinking that there must be an easier way to do this.

Is there an easy way to get back on a branch, while keeping the changes?

答:
Alternatively, you could setup your submodules so that rather than being in their default detached head state you check out a branch.

Edited to add:

One way is to checkout a particular branch of the submodule when you add it with the -b flag:

```<code>git submodule add -b master <remote-repo> <path-to-add-it-to>
</code>```

Another way is to just go into the submodule directory and just check it out

```<code>git checkout master
</code>```

Body:
Alternatively, you could setup your submodules so that rather than being in their default detached head state you check out a branch.

Edited to add:

One way is to checkout a particular branch of the submodule when you add it with the -b flag:

git submodule add -b master <remote-repo> <path-to-add-it-to>

Another way is to just go into the submodule directory and just check it out

git checkout master


问:
Why is accesing services by classname good?
I've always worked in Symfony 2.2 and 2.8
Now glancing at the blog of the version 3.3 and I can't overcome the new feature of getting services by (fully qualified) class name:

```<code>// before Symfony 3.3
$this->get('app.manager.user')->save($user);

// Symfony 3.3
$this->get(UserManager::class)->save($user);
</code>```

Before Symfony 3.3 the service container was a factory with the knowledge of how to instantiate the service class, with the great benefit of a factory: You can swith the old class to any other class, and as long as they both let's say implement the same interface, maybe you don't even have to touch anything else in your code. But if you ask for a service by class name, you have to refactor your whole code, and change the class name in every occurrence of the service. Either when directly accessing by $container->get() or by using typehint and autowire.

Considering these the old way service aliasing seem much more practical or am I just missing something? I know you still can use it the old way, I'm just wondering in what cases could one benefit from preferring this new method instead the classic one.

答:
One of the main points about the new style of service naming it to avoid asking for services by name directly from the container. By typehinting them all (and having them instead created by the framework), then any service that is not being used at all (and is private, so not get-able), can be removed. Anything that is hinted via the container and does not exist will immediately fail on the container building step as well - it would not be possible to rename a service and forget to also change all the other uses of it.

With so much being injected into the controllers (or a controller action) as well, unit testing the services, and even controllers is also more controllable - there wouldn't be any other things that are being pulled from the container within a test.

As for the transition, because of the container compilation step, Symfony is very good about being able to say if there is anything wrong, or at least deprecated. It's not hard to mark all the current services as public with just a small Yaml snippet at the top of each services.yml file (or anywhere else they are defined).

It will be a while until most of the 3rd party bundles and other supporting libraries will be fully 4.0 compatible, but it was also the case for the breaking changes between 2.8 & 3.0. This is a large part of the reason why 2.8 & now 3.4 are long-term-supported versions - with 3.4 supported to November 2021, giving plenty of time to upgrade away from the deprecations and update the 3rd party bundles.

Body:
I've always worked in Symfony 2.2 and 2.8
Now glancing at the blog of the version 3.3 and I can't overcome the new feature of getting services by (fully qualified) class name:

// before Symfony 3.3
$this->get('app.manager.user')->save($user);

// Symfony 3.3
$this->get(UserManager::class)->save($user);

Before Symfony 3.3 the service container was a factory with the knowledge of how to instantiate the service class, with the great benefit of a factory: You can swith the old class to any other class, and as long as they both let's say implement the same interface, maybe you don't even have to touch anything else in your code. But if you ask for a service by class name, you have to refactor your whole code, and change the class name in every occurrence of the service. Either when directly accessing by $container->get() or by using typehint and autowire.

Considering these the old way service aliasing seem much more practical or am I just missing something? I know you still can use it the old way, I'm just wondering in what cases could one benefit from preferring this new method instead the classic one.


问:
Autofill HTML form field with number on page
Is there a way using JS to autofill a HTML form field with a number pre-existing on the page, example below:

So the '123456' number would populate in form field onload.

答:
Yes. Once the DOM is loaded grab the input using the DOM's api and set its value to 123456 or whatever else you want it to be, i.e.

```<code>document.addEventListener("DOMContentLoaded", function(event) {
    document.getElementById("my_input").value = 123456;
});
</code>```

However, if you always want it to start of holding a specific value, why not just make use of the value attribute, which will also show when users have JavaScript disabled:

```<code><input type="text" value="123456">
</code>```

Body:
Yes. Once the DOM is loaded grab the input using the DOM's api and set its value to 123456 or whatever else you want it to be, i.e.

document.addEventListener("DOMContentLoaded", function(event) {
    document.getElementById("my_input").value = 123456;
});

However, if you always want it to start of holding a specific value, why not just make use of the value attribute, which will also show when users have JavaScript disabled:

<input type="text" value="123456">


问:
Is it possible to mix Java 8 and Java 9 source code in the same project without using compiler flags?
In Java 9, you can optionally package a source directory as a module by adding a module-info.java, which defines the things packages that it exports, and which other modules it depends on.

Once you do that, however, you must list ALL dependencies in the module descriptor - and the dependencies must all themselves be modules. Therefore, by extension, if you modularize a single source directory, you must modularize every single source directory company wide.

Furthermore, you cannot define modules in Java 8 or earlier, meaning that in addition to modularizing every single Java source directory, you must convert everything to Java 9. At the same time.

This seems catastrophic if you work in a company with a large base of code that is shared by many different projects.

For now, I can work around the problem by just setting a bunch of compiler flags to avoid defining modules, but that seems like a very poor solution.

I hope that I am understanding this incorrectly?

答:
if you modularize a single source directory, you must modularize
  every single source directory company-wide.

No, that does not hold true, for the fact, that is what automatic modules are designed for and

(to favor the impulse) Yes, eventually that shall be the goal of modularisation.

Reiterating the need of introducing the automatic modules from The State of the Module System:

Bottom-up migration is straightforward, but it is not always possible.
  Even if the maintainer of org-baz-qux.jar has not yet converted it
  into a proper module—or perhaps never will—we might still want to
  modularize our com-foo-app.jar and com-foo-bar.jar components.

When you actually say :

you can optionally package a source directory as a module by adding a
  module-info.java

you tend to migrate that artifact into a module(with module description) and place such modules in the module-path of the libraries using this artifact further.

On the other hand, a .jar of your library without the module-info.class is considered to be present at the class-path when included as a dependency in downstream projects.

Edit from comments:-

it's possible to mix Java 9 source with Java 8 compiled jars, but you
  can't compile a single project containing Java 9 source and Java 8
  source?

Yes, its possible to mix Java9 source with Java8 compile jar and you can still compile them into a single project as well.

Example:- take a look at how Maven does this using maven-compiler-plugin for Java8 projects with module-info.java included.


问:
Multiple nested loops equivalent replacement in python
I have a simple dictionary of the form D = {2: 4, 3: 2, 5: 1, 7: 1}. There are 4 keys which are the primes and  4 values which represent the maximum power. Based on that I want to generate all combinations of the form :

p1^range1 * p2^range2 * p3^range3 * p4^range4

where range1 to range4 are the ranges corresponding to the values of the dictionary of each prime. For p1 = 2 the range will be range(0, 4+1)

The most simplistic way would be a nested for loop with four levels :

```<code>for i1 in range(0, 4+1):
   for i2 in range(0, 2+1):
      for i3 in range(0, 1+1):
         for i4 in range(0, 1+1):
            n = 2**i1 * 3**i2 * 5**i3 * 7**i4
</code>```

which is what I intend and it is correct but this is a non-elegant and mechanical way.

Another way is to use the  itertools.product which works if all the ranges are the same. Basically it is as follows  :

```<code>for x in itertools.product(range(0, 4+1), repeat=4):
    print(x, end='   ')
</code>```

However this will generate all the possible combinations including (2, 2, 3, 4),
(4, 4, 2, 3) or (2, 3, 4, 4) which are not valid in my case as the power of 5 (which is the third element in the tuple) will never be 3 and the power of 7 will never be 4. I want to limit somehow if possible the range of elements . So in this case the maximum tuple will be (4, 2, 1, 1) corresponding to the powers (values in dictionary D). So basically I need ONLY the range of tuples from (0,0,0,0) to (4,2,1,1).

Is there a way to achieve this without using for loops and do it in a similar approach as with itertools.product?

Many thanks in advance.

答:
While itertools is the way to go, this question is an excellent exercise for practicing generator functions:

```<code>def multirange(d):
    if len(d) == 1:
        for i in range(d[0]):
            yield [i]
    elif len(d) > 1:
        for i in range(d[-1]):
            for a in multirange(d[:-1]):
                yield a + [i]

def multirange_b(d):
    l = len(d)
    products = [1]
    for k in d:
        products.append(products[-1]*k)
    n = products[-1]
    for i in range(n):
        yield [(i%products[j+1])//products[j] for j in range(l)]

for l in multirange([4,3,2]):
    print(l)

for l in multirange_b([4,3,2]):
    print(l)
</code>```

Body:
I have a simple dictionary of the form D = {2: 4, 3: 2, 5: 1, 7: 1}. There are 4 keys which are the primes and  4 values which represent the maximum power. Based on that I want to generate all combinations of the form :

p1^range1 * p2^range2 * p3^range3 * p4^range4

where range1 to range4 are the ranges corresponding to the values of the dictionary of each prime. For p1 = 2 the range will be range(0, 4+1)

The most simplistic way would be a nested for loop with four levels :

for i1 in range(0, 4+1):
   for i2 in range(0, 2+1):
      for i3 in range(0, 1+1):
         for i4 in range(0, 1+1):
            n = 2**i1 * 3**i2 * 5**i3 * 7**i4

which is what I intend and it is correct but this is a non-elegant and mechanical way.

Another way is to use the  itertools.product which works if all the ranges are the same. Basically it is as follows  :

for x in itertools.product(range(0, 4+1), repeat=4):
    print(x, end='   ')

However this will generate all the possible combinations including (2, 2, 3, 4),
(4, 4, 2, 3) or (2, 3, 4, 4) which are not valid in my case as the power of 5 (which is the third element in the tuple) will never be 3 and the power of 7 will never be 4. I want to limit somehow if possible the range of elements . So in this case the maximum tuple will be (4, 2, 1, 1) corresponding to the powers (values in dictionary D). So basically I need ONLY the range of tuples from (0,0,0,0) to (4,2,1,1).

Is there a way to achieve this without using for loops and do it in a similar approach as with itertools.product?

Many thanks in advance.

Body:
While itertools is the way to go, this question is an excellent exercise for practicing generator functions:

def multirange(d):
    if len(d) == 1:
        for i in range(d[0]):
            yield [i]
    elif len(d) > 1:
        for i in range(d[-1]):
            for a in multirange(d[:-1]):
                yield a + [i]

def multirange_b(d):
    l = len(d)
    products = [1]
    for k in d:
        products.append(products[-1]*k)
    n = products[-1]
    for i in range(n):
        yield [(i%products[j+1])//products[j] for j in range(l)]

for l in multirange([4,3,2]):
    print(l)

for l in multirange_b([4,3,2]):
    print(l)


问:
Writing data to BluetoothSocket on the UI thread
I'm looking over the Bluetooth Chat sample application from Google and they write to BluetoothSocket's OutputStream on the UI thread. Is that correct? Normally, streams block until the data is sent out.

In my tests (with that app), as long as the devices were close enough, the communication was prompt. When they got farther, the connection was dropped. Is this correct way to send data over Bluetooth? My message size will by 100-500 bytes.

答:
I have wondered about this as well, because as far as I can tell BluetoothChat writes Bluetooth data on the UI thread, as does every other Android Bluetooth example I've found - all of which appear to be based on BluetoothChat.

I have done some more tests along the lines of those Oliv did. Using a Samsung T113 running 4.4.4, I found that for writing 60 character strings, the write generally takes 12-14ms. However, there were also cases where the write took much longer - 35-45ms. Further, if the device being written to is not reading the messages sent to it, eventually the buffer on the sending device will fill and the write operation will block indefinitely (see Android BluetoothSocket OutputStream write blocks infinitely). For these reasons, I think that a well-behaved app that writes Bluetooth will need to do so off the main thread.

(According to Mark Murphy of Commonsware, "all I/O on the main application thread is a bad idea" and BluetoothChat's use of the main thread for writing is "probably just a bug.")


问:
Explaining margins and dealing with tiles
I have few problems that I cannot fix, I will be grateful if somebody will explain me how it works. Firstly, i have a container with id "kafle", I positioned it as I wanted, and now i want to place a few tiles into it. I want do something like this:  I want to tile 1 be 50% width of container with id "kafle", and tile to be another 50% width. I set margin and padding of tile 1 and 2 to 0, but despite this, there is something what makes that tile 2 is going under tile 1, and i don't know why. The other problem is that i don't know how i can place tile 3, 4, 5 and 6 under tile 1, but in one line with tile 2. When im setting display: inline-block to all of the tiles, tile 3, 4, 5 and 6 are going under height of tile 2. How can I deal with it? I will be grateful for explaining it.

html, body{
    height: 100%;
    min-height: 100%;
    margin:0;
}

#kafle{
    position:relative;
    height: 80%;
    width: 60%;
    top:10%;
    left:20%;
    background-color: aquamarine;
}

#onas{
    background-color: coral;
    height:33%;
    width:49%;
    display: inline-block;
    margin:0;
    padding:0;
}

#aktualnosci{
    background-color: firebrick;
    height:90%;
    width:49%;
    display: inline-block;
    margin:0;
    padding:0;
}

#galeria{
    background-color: forestgreen;
    height:10%;
    width:15%;
    display: inline-block;
}

#wspierajanas{
    background-color: khaki;
    height:10%;
    width:15%;
    display: inline-block;
}

#kontakt{
    background-color: fuchsia;
    height:10%;
    width:15%;
    display: inline-block;
}

#minigra{
    background-color: fuchsia;
    height:10%;
    width:15%;
    display: inline-block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title></title>
  <link rel="stylesheet" href="style.css">
</head>

<body>
  <script src="javascript.js"></script>

    <div id="kafle">
        <div id="onas">1</div>
        <div id="aktualnosci">2</div>
       <div id="galeria">3</div>
        <div id="wspierajanas">4</div>
        <div id="kontakt">5</div>
        <div id="minigra">6</div>
    </div>

</body>

</html></code>```

答:
I just finished a Weave for your question.

HTML:

```<code><!DOCTYPE html>
<html>
  <head>
    <title>Tiles</title>
  </head>

  <body>
    <div class="tile1">
      <h1>Tile 1</h1>
    </div>

    <div class="tile2">
      <h1>Tile 2</h1>
    </div>

    <div class="tile3">
      <h1>Tile 3</h1>
    </div>

    <div class="bottomLeftTiles">
      <div class="tile4">
        <h1>Tile 4</h1>
      </div>

      <div class="tile5">
        <h1>Tile 5</h1>
      </div>

      <div class="tile6">
        <h1>Tile 6</h1>
      </div>
    </div>
  </body>
</html>
</code>```

CSS:

```<code>div {
  background-color: rgb(240, 240, 240);
  border: 1px solid rgb(0, 0, 0);
}

h1 {text-align: center;}

.tile1 {
  width: 50%; height: 33%;
  position: absolute;
  left: 0; top: 0;
}

.tile2 {
  width: 50%; height: 100%;
  position: absolute;
  right: 0; top: 0;
}

.tile3 {
  width: 49.6%; height: 33%;
  position: absolute;
  left: 0; top: 33%;
}

.bottomLeftTiles {
  width: 49.6%; height: 33%;
  position: absolute;
  left: 0; top: 66%;
}
.tile4 {
  width: 33%; height: 100%;
  position: relative;
  left: 0; top: 0;
}
.tile5 {
  width: 33%; height: 100%;
  position: absolute;
  left: 33%; top: 0;
}
.tile6 {
  width: 33%; height: 100%;
  position: absolute;
  left: 66%; top: 0;
}
</code>```

You may have to resize a few of the elements but I hope this helps.

Body:
I have few problems that I cannot fix, I will be grateful if somebody will explain me how it works. Firstly, i have a container with id "kafle", I positioned it as I wanted, and now i want to place a few tiles into it. I want do something like this:  I want to tile 1 be 50% width of container with id "kafle", and tile to be another 50% width. I set margin and padding of tile 1 and 2 to 0, but despite this, there is something what makes that tile 2 is going under tile 1, and i don't know why. The other problem is that i don't know how i can place tile 3, 4, 5 and 6 under tile 1, but in one line with tile 2. When im setting display: inline-block to all of the tiles, tile 3, 4, 5 and 6 are going under height of tile 2. How can I deal with it? I will be grateful for explaining it.

html, body{
    height: 100%;
    min-height: 100%;
    margin:0;
}

#kafle{
    position:relative;
    height: 80%;
    width: 60%;
    top:10%;
    left:20%;
    background-color: aquamarine;
}

#onas{
    background-color: coral;
    height:33%;
    width:49%;
    display: inline-block;
    margin:0;
    padding:0;
}

#aktualnosci{
    background-color: firebrick;
    height:90%;
    width:49%;
    display: inline-block;
    margin:0;
    padding:0;
}

#galeria{
    background-color: forestgreen;
    height:10%;
    width:15%;
    display: inline-block;
}

#wspierajanas{
    background-color: khaki;
    height:10%;
    width:15%;
    display: inline-block;
}

#kontakt{
    background-color: fuchsia;
    height:10%;
    width:15%;
    display: inline-block;
}

#minigra{
    background-color: fuchsia;
    height:10%;
    width:15%;
    display: inline-block;
}

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title></title>
  <link rel="stylesheet" href="style.css">

1

2

3

4

5

6

Body:
I just finished a Weave for your question.

HTML:

<!DOCTYPE html>
<html>
  <head>
    <title>Tiles</title>
  </head>

  <body>
    <div class="tile1">
      <h1>Tile 1</h1>
    </div>

    <div class="tile2">
      <h1>Tile 2</h1>
    </div>

    <div class="tile3">
      <h1>Tile 3</h1>
    </div>

    <div class="bottomLeftTiles">
      <div class="tile4">
        <h1>Tile 4</h1>
      </div>

      <div class="tile5">
        <h1>Tile 5</h1>
      </div>

      <div class="tile6">
        <h1>Tile 6</h1>
      </div>
    </div>
  </body>
</html>

CSS:

div {
  background-color: rgb(240, 240, 240);
  border: 1px solid rgb(0, 0, 0);
}

h1 {text-align: center;}

.tile1 {
  width: 50%; height: 33%;
  position: absolute;
  left: 0; top: 0;
}

.tile2 {
  width: 50%; height: 100%;
  position: absolute;
  right: 0; top: 0;
}

.tile3 {
  width: 49.6%; height: 33%;
  position: absolute;
  left: 0; top: 33%;
}

.bottomLeftTiles {
  width: 49.6%; height: 33%;
  position: absolute;
  left: 0; top: 66%;
}
.tile4 {
  width: 33%; height: 100%;
  position: relative;
  left: 0; top: 0;
}
.tile5 {
  width: 33%; height: 100%;
  position: absolute;
  left: 33%; top: 0;
}
.tile6 {
  width: 33%; height: 100%;
  position: absolute;
  left: 66%; top: 0;
}

You may have to resize a few of the elements but I hope this helps.


答:
Try something like:

jQuery(document).ready(function ($) {
     var accountNumberSpan = $('#accountNumber').text();
     $('#myId').val(accountNumberSpan.substr(accountNumberSpan.indexOf(":") + 1));
 });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<span id="accountNumber">Account Number: 12345</span>

<br />
<input type="text" name="myName" id="myId" value="" /></code>```

Title: Autofill HTML form field with number on page

Body:
Is there a way using JS to autofill a HTML form field with a number pre-existing on the page, example below:

So the '123456' number would populate in form field onload.

Body:
Try something like:

jQuery(document).ready(function ($) {
     var accountNumberSpan = $('#accountNumber').text();
     $('#myId').val(accountNumberSpan.substr(accountNumberSpan.indexOf(":") + 1));
 });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<span id="accountNumber">Account Number: 12345</span>

<br />
<input type="text" name="myName" id="myId" value="" />


问:
Composer create project issue
I am getting the following error while creating project

C:\MAMP\htdocs>composer create-project laravel/laravel testing 5.2

Your version of PHP, 5.4.1, is affected by CVE-2013-6420 and cannot safely perform certificate validation, we strongly suggest you upgrade.

答:
This means that your version of PHP is too old and has known vulnerabilities. You should upgrade the PHP version to at least 5.6, but I would recommand to upgrade directly to 7.0 or 7.1. They are under active support (until dec 3rd for 7.0) and have better perfomance.

Moreover laravel 5.2 needs a PHP version >= 5.5.9. It's written in the requirements.

Here is the supported version chart of PHP. You shouldn't use any version that is in red.

Title: Composer create project issue


问:
PM2 dev and prod environments on same server
I have a dev and prod instance of a microservice running on one machine. My ecosystem file gives them the same name. PM2 will not start the second instance when the first is running due to the name (presumably). Any ideas for a workaround here?</p>

答:
Pm2 do not sensitive filename because the name is usual for human not for PM2 process.

The usual mistake:

Two script try to listen one port.

conflict between scripts & resources.

The solution is start first process with pm2 and second process normal start with nodejs and you can see the log and error if not start, or started successfully then start second process first, first process second.

and you can use pm2panel for easily add or remove process in pm2.


问:
Access class/instance attribute from C function in Cython
I am working with a c library that uses setCallback functions. These functions take a function with a fixed signature, e.g.:

```<code>int glfwSetCursorPosCallback(window, mouse_move);
</code>```

Where mouse_move has signature

```<code>void mouse_move(GLFWwindow * window, double xpos, double ypos)
</code>```

But suppose mouse_move depends on other state beyond these function arguments, like a camera struct? In c, I would just make camera a global variables. However, I am working in Cython and I want to use glfwSetCursorPosCallback without recourse to global variables, which are unpythonic and messy. If camera is a class or instance attribute, is there any way to access it from within mouse_move without passing it in as an argument?

答:
This is not a solution to the general problem, but for glfw callbacks, it is possible to associate a void* with your GLFWwindow as follows:

```<code>glfwSetWindowUserPointer(window, yourVoidPtr);
</code>```

and access it later (e.g. in a callback):

```<code>YourData *data = (YourData *) glfwGetWindowUserPointer(window);
</code>```

Body:
I am working with a c library that uses setCallback functions. These functions take a function with a fixed signature, e.g.:

int glfwSetCursorPosCallback(window, mouse_move);

Where mouse_move has signature

void mouse_move(GLFWwindow * window, double xpos, double ypos)

But suppose mouse_move depends on other state beyond these function arguments, like a camera struct? In c, I would just make camera a global variables. However, I am working in Cython and I want to use glfwSetCursorPosCallback without recourse to global variables, which are unpythonic and messy. If camera is a class or instance attribute, is there any way to access it from within mouse_move without passing it in as an argument?

Body:
This is not a solution to the general problem, but for glfw callbacks, it is possible to associate a void* with your GLFWwindow as follows:

glfwSetWindowUserPointer(window, yourVoidPtr);

and access it later (e.g. in a callback):

YourData *data = (YourData *) glfwGetWindowUserPointer(window);


问:
How to fix "containing working copy admin area is missing" in SVN?
I deleted manually a directory I just added, offline, in my repository. I can't restore the directory.

Any attempt to do an update or a commit will fail with:

```<code>"blabla/.svn" containing working copy admin area is missing.
</code>```

I understand why, but is there anyway to fix this.

I don't want to checkout the entire repo and add my changes to it manually, it would take hours.

答:
I had this error recently. It was caused by root owning a couple of files in the directory giving this error.

After I changed the permissions everything worked as expected.

Body:
I deleted manually a directory I just added, offline, in my repository. I can't restore the directory.

Any attempt to do an update or a commit will fail with:

"blabla/.svn" containing working copy admin area is missing.

I understand why, but is there anyway to fix this.

I don't want to checkout the entire repo and add my changes to it manually, it would take hours.


问:
Change order/default item of firefox devtools
is there a way to put my custom contextMenu to the first place, or change the default item?

I don't want to open the devtools and then having to click on my extension

Thanks in advance

答: If I understand you correctly, you want your own context menu item first in the list. That is not possible. See this feature request which was rejected: https://bugzilla.mozilla.org/show_bug.cgi?id=1325758</p>


问:
Simple Negative Lookahead
I get this:

```<code>import re;
print re.findall(r"q(?=u)", "qqq queen quick qeel")
> ['q', 'q'] # for queen and quick
</code>```

But I don't get this:

```<code>import re;
print re.findall(r"q(?!=u)", "qqq queen quick qeel")
> ['q', 'q', 'q', 'q', 'q', 'q'] # every q matches
</code>```

I expected only 4 qs to match because the negative lookahead should see that in the word qeel for example, the letter after the q is not u.

What gives?

答:
It is

```<code>import re
print(re.findall(r"q(?!u)", "qqq queen quick qeel"))
#                  ---^---
# ['q', 'q', 'q', 'q']
</code>```

Without the =, that is. Otherwise, you don't want to have =u in front which is true for all of your qs here. In general, a positive lookahead is formed via (?=...) whereas a negative one is just (?!...).

Sidenote: the ; is not needed at the end of the line unless you want to write everything in one line which is not considered "Pythonic" but totally valid:

```<code>import re; print(re.findall(r"q(?!u)", "qqq queen quick qeel"))
</code>```

Title: Simple Negative Lookahead

Body:
I get this:

import re;
print re.findall(r"q(?=u)", "qqq queen quick qeel")
> ['q', 'q'] # for queen and quick

But I don't get this:

import re;
print re.findall(r"q(?!=u)", "qqq queen quick qeel")
> ['q', 'q', 'q', 'q', 'q', 'q'] # every q matches

I expected only 4 qs to match because the negative lookahead should see that in the word qeel for example, the letter after the q is not u.

What gives?

Body:
It is

import re
print(re.findall(r"q(?!u)", "qqq queen quick qeel"))
#                  ---^---
# ['q', 'q', 'q', 'q']

Without the =, that is. Otherwise, you don't want to have =u in front which is true for all of your qs here. In general, a positive lookahead is formed via (?=...) whereas a negative one is just (?!...).

Sidenote: the ; is not needed at the end of the line unless you want to write everything in one line which is not considered "Pythonic" but totally valid:

import re; print(re.findall(r"q(?!u)", "qqq queen quick qeel"))


问:
Ethereum Javascript console "short write"
Does anyone know what this means? I'm getting it in my ethereum console quite a bit.  It doesn't seem to be breaking anything that I can tell.</p>

答:
In Linux it means that you are exceeding the max filesize.
The max file-size in Linux vary depending on the Kernel version (could be 2Gb).
So, it seems that you are doing an operation that is causing the OS to make a very large file.

(If you can share the full context for the error message we can give you more detailed answer.)


问:
Can objects names be used to create an instance of that object?
So i'm learning to code in javascript, and right now i have a practice example of inheritance by prototype. The thing is, i have to achieve something like this:

```<code>var human = {}
var worker = human.create()
var dev = worker.create()

var adrian = dev.create("Adrian",28,20000)
</code>```

The two points in the excercise go as follow:
1) To get rid of Object.create
2) To get rid of properties assignations Ex: adrian.age = 28;

I already know how to somehow do this on the "Classical Model" but im at a loss as to how to use my object name along with .create

I thought about creating a constructor function and use that to create an instance, but the result is undefined, because i don't have an object created to begin with

答:
Here is an example you may understand (maybe it's helpful):

```<code>function Human() {
  this.showName = function() {
    console.log(this.name);
  }
}

var human = new Human();

function Worker() {
  this.showAge = function() {
    console.log(this.age);
  }
}

Worker.prototype = human;
var worker = new Worker();

function Dev(name, age, year) {
  this.name = name;
  this.age = age;
  this.year = year;

  this.showYear = function() {
    console.log(this.year);
  }
}
Dev.prototype = worker;

var adrian = new Dev('Adrian', 28, 2000);

adrian.showAge(); // 28
adrian.showName(); // 'Adrian'
adrian.showYear(); // 2000
</code>```

You can create instances of objects by calling the constructor. The constructor is a simple function (Human, Worker, Dev).

Every object you create (either by calling the constructor or not) has a special property called prototype. It can be set explicitly by setting the constructor's prototype property and it is the object from which inherits. In JavaScript objects inherit from other objects.

In this example adrian's prototype is worker.

The process can be chained, so worker's prototype is human.

Body:
So i'm learning to code in javascript, and right now i have a practice example of inheritance by prototype. The thing is, i have to achieve something like this:

var human = {}
var worker = human.create()
var dev = worker.create()

var adrian = dev.create("Adrian",28,20000)

The two points in the excercise go as follow:
1) To get rid of Object.create
2) To get rid of properties assignations Ex: adrian.age = 28;

I already know how to somehow do this on the "Classical Model" but im at a loss as to how to use my object name along with .create

I thought about creating a constructor function and use that to create an instance, but the result is undefined, because i don't have an object created to begin with

Body:
Here is an example you may understand (maybe it's helpful):

function Human() {
  this.showName = function() {
    console.log(this.name);
  }
}

var human = new Human();

function Worker() {
  this.showAge = function() {
    console.log(this.age);
  }
}

Worker.prototype = human;
var worker = new Worker();

function Dev(name, age, year) {
  this.name = name;
  this.age = age;
  this.year = year;

  this.showYear = function() {
    console.log(this.year);
  }
}
Dev.prototype = worker;

var adrian = new Dev('Adrian', 28, 2000);

adrian.showAge(); // 28
adrian.showName(); // 'Adrian'
adrian.showYear(); // 2000

You can create instances of objects by calling the constructor. The constructor is a simple function (Human, Worker, Dev).

Every object you create (either by calling the constructor or not) has a special property called prototype. It can be set explicitly by setting the constructor's prototype property and it is the object from which inherits. In JavaScript objects inherit from other objects.

In this example adrian's prototype is worker.

The process can be chained, so worker's prototype is human.


问:
Java : How to determine the correct charset encoding of a stream
With reference to the following thread:
Java App : Unable to read iso-8859-1 encoded file correctly

What is the best way to programatically determine the correct charset encoding of an inputstream/file ?

I have tried using the following:

```<code>File in =  new File(args[0]);
InputStreamReader r = new InputStreamReader(new FileInputStream(in));
System.out.println(r.getEncoding());
</code>```

But on a file which I know to be encoded with ISO8859_1 the above code yields ASCII, which is not correct, and does not allow me to correctly render the content of the file back to the console.

答:
I have used this library, similar to jchardet for detecting encoding in Java:
https://github.com/albfernandez/juniversalchardet</p>

OwnerDisplayName: Joel

Body:
With reference to the following thread:
Java App : Unable to read iso-8859-1 encoded file correctly

What is the best way to programatically determine the correct charset encoding of an inputstream/file ?

I have tried using the following:

File in =  new File(args[0]);
InputStreamReader r = new InputStreamReader(new FileInputStream(in));
System.out.println(r.getEncoding());

But on a file which I know to be encoded with ISO8859_1 the above code yields ASCII, which is not correct, and does not allow me to correctly render the content of the file back to the console.

ContentLicense: CC BY-SA 4.0


答:
you need update your PHP version  source : https://laravel.com/docs/5.2/releases
so  PHP 5.5.9 + for you :)

PHP 5.5.9+
  Since PHP 5.4 will enter "end of life" in September and will no longer receive security updates from the PHP development team, Laravel 5.1 requires PHP 5.5.9 or greater. PHP 5.5.9 allows compatibility with the latest versions of popular PHP libraries such as Guzzle and the AWS SDK.

Title: Composer create project issue

Body:
I am getting the following error while creating project

C:\MAMP\htdocs>composer create-project laravel/laravel testing 5.2

Your version of PHP, 5.4.1, is affected by CVE-2013-6420 and cannot safely perform certificate validation, we strongly suggest you upgrade.


问:
jar is missing in pom.xml error but is usually not included
I am working on a really basic program in spring. This is a snippet of my pom.xml

```<code><dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-mail</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</code>```

This is the error I am getting:

[ERROR] 'dependencies.dependency.version' for org.springframework.boot:spring-boot-starter:jar is missing.
[ERROR] 'dependencies.dependency.version' for org.springframework.boot:spring-boot-starter-mail:jar is missing.
[ERROR] 'dependencies.dependency.version' for org.springframework.boot:spring-boot-starter-test:jar is missing.

I get that this is because my dependencies don't have a < version > section. However, in all the other java applications that I have worked on, including the one I am referencing right now, the versions for these basic dependencies are never included. Is there something else in my pom that I am supposed to include beforehand, that may be included in the files that I am referencing but not the one I have created from scratch? If not, how are they working without the version included in their pom dependencies?
Additionally, how would I go about finding the version for these basic dependencies?

答:
Please add Spring Starter Web Maven Dependency in Pom.xml

```<code><dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>1.5.7.RELEASE</version>
</dependency>
</code>```

As Spring downloads latest version of dependency so we do not have to declare explcitly.

Body:
I am working on a really basic program in spring. This is a snippet of my pom.xml

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-mail</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

This is the error I am getting:

[ERROR] 'dependencies.dependency.version' for org.springframework.boot:spring-boot-starter:jar is missing.
[ERROR] 'dependencies.dependency.version' for org.springframework.boot:spring-boot-starter-mail:jar is missing.
[ERROR] 'dependencies.dependency.version' for org.springframework.boot:spring-boot-starter-test:jar is missing.

I get that this is because my dependencies don't have a < version > section. However, in all the other java applications that I have worked on, including the one I am referencing right now, the versions for these basic dependencies are never included. Is there something else in my pom that I am supposed to include beforehand, that may be included in the files that I am referencing but not the one I have created from scratch? If not, how are they working without the version included in their pom dependencies?
Additionally, how would I go about finding the version for these basic dependencies?

Body:
Please add Spring Starter Web Maven Dependency in Pom.xml

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>1.5.7.RELEASE</version>
</dependency>

As Spring downloads latest version of dependency so we do not have to declare explcitly.


问:
split large CSV on the column value (order date) into small CSV and add double quotes to Order Comments Column through R
I have csv file like this

```<code>customerid orderid paymentamount   orderdate         ordernotes
1213        1233     16.99        01/01/2017 0:05     abcd acd cbvfd
1222        2343     44.99        01/01/2017 1:05     xyzzz
1234        4565     20.99        01/01/2017 2:05
1267        6754     11.99        01/02/2017 0:05     abcdabv
1785        8975     12.99        01/02/2017 1:05     xsdsgff
7654        7657     13.99        01/03/2017 2:00
6545        7867     10.99        01/03/2017 4:00     1/7 xyzzz
                                                      2/8 abcd
</code>```

I have many rows of data and want to split this large CSV on the basis of orderdate into seprate CSV on the basis of each day. I tried this but not getting any results.I also want to add double quotes to order notes column.

```<code>x1 <- read.csv("xyz.csv", header=T, sep=",")
for (date in levels(x1$orderdate)){
  tmp=subset(x1,orderdate== date)
  fn=paste('x1/',gsub(' ','',date),sep='')
  write.csv(tmp,fn,row.names=FALSE)
}
</code>```

答:
You could convert the orderdatecolumn to class date, extract unique dates and go on splitting:

```<code>library(lubridate)

x$orderdate <- strptime(x$orderdate, format = "%d/%m/%Y %H:%M")
for (d in date(x$orderdate)){
  tmp <- subset(x, date(orderdate) == d)
  # do stuff...
}
</code>```

Body:
I have csv file like this

customerid orderid paymentamount   orderdate         ordernotes
1213        1233     16.99        01/01/2017 0:05     abcd acd cbvfd
1222        2343     44.99        01/01/2017 1:05     xyzzz
1234        4565     20.99        01/01/2017 2:05
1267        6754     11.99        01/02/2017 0:05     abcdabv
1785        8975     12.99        01/02/2017 1:05     xsdsgff
7654        7657     13.99        01/03/2017 2:00
6545        7867     10.99        01/03/2017 4:00     1/7 xyzzz
                                                      2/8 abcd

I have many rows of data and want to split this large CSV on the basis of orderdate into seprate CSV on the basis of each day. I tried this but not getting any results.I also want to add double quotes to order notes column.

x1 <- read.csv("xyz.csv", header=T, sep=",")
for (date in levels(x1$orderdate)){
  tmp=subset(x1,orderdate== date)
  fn=paste('x1/',gsub(' ','',date),sep='')
  write.csv(tmp,fn,row.names=FALSE)
}

Body:
You could convert the orderdatecolumn to class date, extract unique dates and go on splitting:

library(lubridate)

x$orderdate <- strptime(x$orderdate, format = "%d/%m/%Y %H:%M")
for (d in date(x$orderdate)){
  tmp <- subset(x, date(orderdate) == d)
  # do stuff...
}


答:
You should be able to do something like:</p>

```<code>x1 <- read.csv("xyz.csv", sep=",", stringsAsFactors = FALSE)
lapply(unique(as.Date(x1$orderdate, "%d/%m/%Y")), function(d) {
  df <- x1[as.Date(x1$orderdate, "%d/%m/%Y")==d,]
  invisible(write.csv(df, sprintf("%s.csv", as.character(d))))
})
</code>```

Title: split large CSV on the column value (order date) into small CSV and add double quotes to Order Comments Column through R

Body:
You should be able to do something like:

x1 <- read.csv("xyz.csv", sep=",", stringsAsFactors = FALSE)
lapply(unique(as.Date(x1$orderdate, "%d/%m/%Y")), function(d) {
  df <- x1[as.Date(x1$orderdate, "%d/%m/%Y")==d,]
  invisible(write.csv(df, sprintf("%s.csv", as.character(d))))
})


问:
How can I compare rows for multiple columns if they are identical
I have one pandas DataFrame and I want to check the rows are identical. This shall work for 3 columns out of the dataframe.

```<code>A B C ...
1 1 1 ...
1 2 3 ...
1 4 4 ...
</code>```

This should bring up a mask with

```<code>True
False
False
</code>```

答:
```<code>In [97]: df.eq(df.iloc[:, 0], axis=0).all(1)
Out[97]:
0     True
1    False
2    False
dtype: bool
</code>```

Body:
I have one pandas DataFrame and I want to check the rows are identical. This shall work for 3 columns out of the dataframe.

A B C ...
1 1 1 ...
1 2 3 ...
1 4 4 ...

This should bring up a mask with

True
False
False


问:
Difference between a statement and a query in SQL
I still live in this ambiguity: conceptually what's the difference between a statement and a query in SQL? Can anybody give a definition for each of them? It would be useful, for example when choosing variables names inside programs in a way that will be clear for everybody.
Thanks!

ADDITIONALLY: How can I call a chunk of SQL code made by more than one statement where statements are separated by a semicolon (;)? Who already replied can edit his answer. Many thanks!

答:
A statement is the general term for a piece of complete, correct SQL that you can send to a DBMS. A query is a statement that will return data, thus a query is a special kind of statement.

A SELECT ... would be a query, a DELETE... just a statement.


问:
Android firebase no data query
Im using the Android SDK for firebase database.

In the database I have a structure where I keep the messages ordered by user, that way if I need their messages I just query by user.

```<code>myDatabase -> messages -> JonDoe
                            -> "You forgot your mail"
                            -> "Buy groceries"
                       -> JaneDoe
                            -> "Dog's birthday!"
</code>```

The problem is if the user doesnt exist the listener keeps waiting forever, and I want to show "You have no messages" in that case. (For example, if I query the user "CharlesDoe" in the example above)

Is there a way to check if a reference exists before/after/during a query?

答:
try this:

```<code>DatabaseReference root =FirebaseDatabase.getInstance().getReference();
DatabaseReference user = root.child("myDatabase").child("messages");
user.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot snapshot) {
        if (snapshot.child("CharlesDoe").exists()) {
            // run some code
        }else{
        Toast.makeText(this,"no messages",Toast.Length_LONG).show();

        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
});
</code>```

Here it will query on node messages and then it will check if the child exists and do the required.

Title: Android firebase no data query

Body:
Im using the Android SDK for firebase database.

In the database I have a structure where I keep the messages ordered by user, that way if I need their messages I just query by user.

myDatabase -> messages -> JonDoe
                            -> "You forgot your mail"
                            -> "Buy groceries"
                       -> JaneDoe
                            -> "Dog's birthday!"

The problem is if the user doesnt exist the listener keeps waiting forever, and I want to show "You have no messages" in that case. (For example, if I query the user "CharlesDoe" in the example above)

Is there a way to check if a reference exists before/after/during a query?

Body:
try this:

DatabaseReference root =FirebaseDatabase.getInstance().getReference();
DatabaseReference user = root.child("myDatabase").child("messages");
user.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot snapshot) {
        if (snapshot.child("CharlesDoe").exists()) {
            // run some code
        }else{
        Toast.makeText(this,"no messages",Toast.Length_LONG).show();

        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
});

Here it will query on node messages and then it will check if the child exists and do the required.


问:
form_with posts back using GET not POST?
I'm trying to post back this form to my app_users_password_reset_path using form_with, but for some reason, the method used is always GET as opposed to POST. In my controller, when I check request.post?, it's always false.

What am I doing wrong here?

```<code># config/routes.rb

match '/app/users/password_reset', to: 'users#password_reset', as: :app_users_password_reset, via: [:get, :post]
</code>```

The output from rails routes for the route in question is:

```<code># > rails routes
app_users_password_reset GET|POST /app/users/password_reset(.:format) users#password_reset
</code>```

Here is the markup for my form:

```<code># password_reset.html.erb

 <div class='row'>
         <div class='body col-md-3'>

            <form>

                <%= form_with scope: :user,
                    method: :POST,
                    url: app_users_password_reset_path,
                    local: true,
                    role: :form do |f| %>

                    <%= f.hidden_field :token, value: @password_reset_token %>

                    <div class="form-group">
                        <%= f.label :user_password, "Password" %>
                        <%= f.password_field :password, value: @password, class: "form-control" %>
                    </div>

                    <div class="form-group">
                        <%= f.label :password_confirmation, "Password confirmation" %>
                        <%= f.password_field :password_confirmation, value: @password_confirmation, class: "form-control"  %>
                    </div>

                    <div class="form-group">
                        <%= f.submit "Reset password", id: "btn-reset-password", class: "btn btn-default" %>
                    </div>
                <% end %>

            </form>

        </div>
</div>
</code>```

答: The form_with code is wrapped inside another html form tag, this may be causing the issue. Try removing the  and  tag.</p>

Body:
I'm trying to post back this form to my app_users_password_reset_path using form_with, but for some reason, the method used is always GET as opposed to POST. In my controller, when I check request.post?, it's always false.

What am I doing wrong here?

# config/routes.rb

match '/app/users/password_reset', to: 'users#password_reset', as: :app_users_password_reset, via: [:get, :post]

The output from rails routes for the route in question is:

# > rails routes
app_users_password_reset GET|POST /app/users/password_reset(.:format) users#password_reset

Here is the markup for my form:

# password_reset.html.erb

            <form>

                <%= form_with scope: :user,
                    method: :POST,
                    url: app_users_password_reset_path,
                    local: true,
                    role: :form do |f| %>

                    <%= f.hidden_field :token, value: @password_reset_token %>

                        <%= f.label :user_password, "Password" %>
                        <%= f.password_field :password, value: @password, class: "form-control" %>

                        <%= f.label :password_confirmation, "Password confirmation" %>
                        <%= f.password_field :password_confirmation, value: @password_confirmation, class: "form-control"  %>

                        <%= f.submit "Reset password", id: "btn-reset-password", class: "btn btn-default" %>

                <% end %>

            </form>