问:
React/ES6 onScroll event not getting triggered
I have an onScroll event in my render function. When the site is scrolled it should trigger the listenScrollEvent function which outputs some data. For some reason it is not not getting triggered. I have binded the function in constructor, but apparently it haven't help.

Working example

```<code>import React, {Component} from 'react';
import { render } from 'react-dom';
import Hello from './Hello';

export class Home extends Component {
    constructor(props) {
      super();
          this.listenScrollEvent = this.listenScrollEvent.bind(this);

  }
    listenScrollEvent() {
    console.log('Scroll event detected!');
  }
    render() {
    return (
      <div className="App"  onScroll={this.listenScrollEvent}>

What is Lorem Ipsum?aa
Lorem Ipsum is simply dummy text of the printing and taypesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

Why do we use it?
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).

Where does it come from?
Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.

The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.

Where can I get some?
There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.

      </div>
    );

  }
}

render(<Home />, document.getElementById('root'));
</code>```

Thanks in advance!

答:
Fixed my problem by adding:</p>

```<code>  componentDidMount() {
    window.addEventListener('scroll', this.listenScrollEvent);
  }
  componentWillUnmount() {
    window.removeEventListener('scroll', this.listenScrollEvent);
  }
</code>```

Body:
I have an onScroll event in my render function. When the site is scrolled it should trigger the listenScrollEvent function which outputs some data. For some reason it is not not getting triggered. I have binded the function in constructor, but apparently it haven't help.

Working example

import React, {Component} from 'react';
import { render } from 'react-dom';
import Hello from './Hello';

export class Home extends Component {
    constructor(props) {
      super();
          this.listenScrollEvent = this.listenScrollEvent.bind(this);

  }
    listenScrollEvent() {
    console.log('Scroll event detected!');
  }
    render() {
    return (

What is Lorem Ipsum?aa
Lorem Ipsum is simply dummy text of the printing and taypesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

Why do we use it?
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).

Where does it come from?
Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.

The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.

Where can I get some?
There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.

    );

  }
}

render(<Home />, document.getElementById('root'));

Thanks in advance!

Body:
Fixed my problem by adding:

  componentDidMount() {
    window.addEventListener('scroll', this.listenScrollEvent);
  }
  componentWillUnmount() {
    window.removeEventListener('scroll', this.listenScrollEvent);
  }


来源: stackexchange

问:
Hide elements when width change
I have question because I'm try hide menu when window width is more than 766px. This is my code but not work

HTML

```<code><div class="menu">
    <div class="burger-menu">
        <span></span>
        <span></span>
        <span></span>
    </div>
    <ul class="submenu">
        <li><a href="#about-me">O mnie</a></li>
        <li><a href="">Prace</a></li>
        <li><a href="">Certyfikty</a></li>
        <li><a href="">Cennik</a></li>
        <li><a href="">Kontakt</a></li>
    </ul>
</div>
</code>```

JQuery

```<code>//Burger menu

$('.burger-menu').click(function(){

  $(this).toggleClass('open');

});

//Menu list

$('.burger-menu').click(function(){
    $('.submenu').slideToggle();
});

if($(window).width() > 766){
    $('.submenu').hide();
}else {
    console.log('halo');
};
</code>```

Everything works but when I click burger and menu slide for example on 677px and then resize window to more than 766px menu still there. Thanks for every help

答:
To achieve expected result, use below CSS

```<code>@media (min-width: 766px) {
  .submenu {
    display: none;
  }
}
</code>```

Codepen - https://codepen.io/nagasai/pen/yXRVOe

Other option Using Jquery, make below changes to work on resize and on page load

Check the screen width on load and if width is more than 766px , hide .submenu

On window resize, show the .submenu if the screen width is less than 766px and hide , if more than 766px

Use Jquery, follow below steps

if($(window).width() > 766){
                $('.submenu').hide();
              }

$(window).resize(function(){
       if($(window).width() > 766){
                $('.submenu').hide();
              }
              else {
                 $('.submenu').show();// add else condition to show if condition faile
                console.log('halo');
              };
    });

https://codepen.io/nagasai/pen/vZVyyz

ContentLicense: CC BY-SA 3.0

Title: Hide elements when width change

Body:
I have question because I'm try hide menu when window width is more than 766px. This is my code but not work

HTML

O mnie

Prace

Certyfikty

Cennik

Kontakt

JQuery

//Burger menu

$('.burger-menu').click(function(){

  $(this).toggleClass('open');

});

//Menu list

$('.burger-menu').click(function(){
    $('.submenu').slideToggle();
});

if($(window).width() > 766){
    $('.submenu').hide();
}else {
    console.log('halo');
};

Everything works but when I click burger and menu slide for example on 677px and then resize window to more than 766px menu still there. Thanks for every help

Body:
To achieve expected result, use below CSS

@media (min-width: 766px) {
  .submenu {
    display: none;
  }
}

Codepen - https://codepen.io/nagasai/pen/yXRVOe

Other option Using Jquery, make below changes to work on resize and on page load

Check the screen width on load and if width is more than 766px , hide .submenu

On window resize, show the .submenu if the screen width is less than 766px and hide , if more than 766px

Use Jquery, follow below steps

if($(window).width() > 766){
                $('.submenu').hide();
              }

$(window).resize(function(){
       if($(window).width() > 766){
                $('.submenu').hide();
              }
              else {
                 $('.submenu').show();// add else condition to show if condition faile
                console.log('halo');
              };
    });

https://codepen.io/nagasai/pen/vZVyyz


问:
What is the compile-time type of the "throw" expression in C# 7?
In C# 7 it is possible to raise an exception inside an expression:

```<code>int n = list != null ? list.Count : throw new NullReferenceException("list");
</code>```

In this position, the throw expression can substitute an expression of any type.

Now I want to define a function that executes some action before raising an exception:

```<code>??? DoSomethingAndThrowException(Exception e)
{
    MessageBox.Show("Prepare for an exception!");
    throw e;
}
</code>```

What would be the return type of such function, so that it can be used in the same places as the original throw expression:

```<code>int n = list != null ? list.Count : DoSomethingAndThrowException(new NullReferenceException("list"));
</code>```

There's the option to declare it as a generic method:

```<code>T DoSomethingAndThrowException<T>(Exception e) {...}
</code>```

But this seems cumbersome, as the generic type doesn't occur anywhere in the function body. Is this the only way to do it, or is there some type I don't know of, and which is assignable to any type (an "anti-object" type, so to speak)?

答:
Here is the short specification for the throw-expression feature.

The relevant portion to your question:

The type rules are as follows:

A throw_expression has no type.

A throw_expression is convertible to every type by an implicit conversion.

Body:
In C# 7 it is possible to raise an exception inside an expression:

int n = list != null ? list.Count : throw new NullReferenceException("list");

In this position, the throw expression can substitute an expression of any type.

Now I want to define a function that executes some action before raising an exception:

??? DoSomethingAndThrowException(Exception e)
{
    MessageBox.Show("Prepare for an exception!");
    throw e;
}

What would be the return type of such function, so that it can be used in the same places as the original throw expression:

int n = list != null ? list.Count : DoSomethingAndThrowException(new NullReferenceException("list"));

There's the option to declare it as a generic method:

T DoSomethingAndThrowException<T>(Exception e) {...}

But this seems cumbersome, as the generic type doesn't occur anywhere in the function body. Is this the only way to do it, or is there some type I don't know of, and which is assignable to any type (an "anti-object" type, so to speak)?


问:
Retrieving images - MySQL based or file system based, which one is faster?
I'd like to know if it's faster/better to retrieve image(s) for a particular product or blog post or whatever in a website by getting the path/filename from the database along with the rest of the data, or if I should just create a folder with the product id and use glob to iterate over it or just use the id as filename in case of a single image, for example.

What are the advantages/disadvantages to these approaches?

答:
It's definitely faster to use the paths/name methods (- 1 database calls; composing a string is not a time/memory consuming operation). By the way, in case you'll have different images for the same product id, you might create a foreach loop that looks in the given folder for pic1.png, pic2.png [...] picn.png.

There is a problem, though: changing the images will become a more convoluted process - instead of just uploading new ones and updating the DB, you will have to delete the previous (or previous set) with relative thumbnails if any before uploading the new ones; that will also mean the image change process won't be reversible unless you store the old ones in a backup directory, etc.

So, (you plan to change them often || your users will change them often) ? database : paths

ContentLicense: CC BY-SA 2.5


问:
Python: Check if Any List Item In String, If So Assign Found Item to Variable
I've the following list:

my_list = ['a', 'b', 'c']

I've the following list of strings:

my_strings = ['azz', 'bzz', 'czz']

I'm doing the following to determine if any items of my_list are in contained within a item in my_strings:

```<code>for my_string in my_strings:
    if any(x in my_string for x in my_list):
        # Do Stuff
</code>```

What's the best practice for retaining the x as found in my_list so that I might be able to then do the following:

```<code>#Do Stuff
new_var = my_string.split('x')[1]
</code>```

The desired result would be able to assign zz to new_var by determining that a from my list was in azz from my_strings

答:
You should not use any() because you need to know specifically which element matches a certain string. Simply use a regular for loop instead:

```<code>>>> def split(strings, lst):
...     for string in strings:
...         for el in lst:
...             if el in string:
...                 yield string.split(el)[1]
...
>>>
>>> for string in split(['azz', 'bzz', 'czz'], ['a', 'b', 'c']):
...     print(string)
...
zz
zz
zz
>>>
</code>```

Body:
I've the following list:

my_list = ['a', 'b', 'c']

I've the following list of strings:

my_strings = ['azz', 'bzz', 'czz']

I'm doing the following to determine if any items of my_list are in contained within a item in my_strings:

for my_string in my_strings:
    if any(x in my_string for x in my_list):
        # Do Stuff

What's the best practice for retaining the x as found in my_list so that I might be able to then do the following:

#Do Stuff
new_var = my_string.split('x')[1]

The desired result would be able to assign zz to new_var by determining that a from my list was in azz from my_strings

Body:
You should not use any() because you need to know specifically which element matches a certain string. Simply use a regular for loop instead:

>>> def split(strings, lst):
...     for string in strings:
...         for el in lst:
...             if el in string:
...                 yield string.split(el)[1]
...
>>>
>>> for string in split(['azz', 'bzz', 'czz'], ['a', 'b', 'c']):
...     print(string)
...
zz
zz
zz
>>>


答:
Let's say if you want to split first value of my_string with first value of my_list

```<code>my_string[0].split(my_list[0])
</code>```

Title: Python: Check if Any List Item In String, If So Assign Found Item to Variable

Body:
Let's say if you want to split first value of my_string with first value of my_list

my_string[0].split(my_list[0])


问:
Errors with my python code
My python cod keeps giving me errors like indention and syntax which I keep fixing them but to no avail. So here is the code I'm using I'm still not sure what I'm doing wrong here (BTW this is just due to an argument with a friend about what I can't do)</p>

```<code>import requests
import subprocess
import json
import sys
import threading
import time
from Queue import Queue

numberOfViewers = int(sys.argv[1])
builderThreads = int(sys.argv[2])
startTime = time.time()
numberOfSockets = 0
concurrent = 25
urls = []
urlsUsed = []

def getURL(): # Get tokens
  output = subprocess.Popen(["livestreamer", "twitch.tv/CHANNEL_NAME", "-j"], stdout=subprocess.PIPE).communicate()[0]
        return json.loads(output)['streams']['worst']['url'] # Parse json and return the URL parameter

def build(): # Builds a set of tokens, aka viewers
        global numberOfSockets
        global numberOfViewers
        while True:
                if numberOfSockets < numberOfViewers:
                        numberOfSockets += 1
                        print "Building viewers " + str(numberOfSockets) + "/" + str(numberOfViewers)
                        urls.append(getURL())

def view(): # Opens connections to send views
        global numberOfSockets
        while True:
                url=q.get()
                requests.head(url)
                if (url in urlsUsed):
                        urls.remove(url)
                        urlsUsed.remove(url)
                        numberOfSockets -= 1
                else:
                        urlsUsed.append(url)
                q.task_done()

if __name__ == '__main__':
        for i in range(0, builderThreads):
                threading.Thread(target = build).start()

        while True:
                while (numberOfViewers != numberOfSockets): # Wait until sockets are built
                        time.sleep(1)

                q=Queue(concurrent*2)
                for i in range(concurrent):
                        try:
                                t=threading.Thread(target=view)
                                t.daemon=True
                                t.start()
                        except:
                                print 'thread error'
                try:
                        for url in urls:
                                print url
                                q.put(url.strip())
                                q.join()
                except KeyboardInterrupt:
                        sys.exit(1)
</code>```

答:
You have a couple error in your code:

1: print:
If you are using Python3 -

The print statement has been replaced with a print() function, with
  keyword arguments to replace most of the special syntax of the old
  print statement

for more information about whats new in python 3

2: Indentation:
If you are getting this error:
IndentationError: expected an indented block
that means you have improper indentations. As an interpreted language proper indentation is necessary and important for Python:

Leading whitespace (spaces and tabs) at the beginning of a logical
  line is used to compute the indentation level of the line, which in
  turn is used to determine the grouping of statements.

for more information look at Python reference manual for Indentation

Fixed code example:

I fixed these error for you and below is how it should look like:

```<code>import requests
import subprocess
import json
import sys
import threading
import time
from Queue import Queue

numberOfViewers = int(sys.argv[1])
builderThreads = int(sys.argv[2])
startTime = time.time()
numberOfSockets = 0
concurrent = 25
urls = []
urlsUsed = []

def getURL(): # Get tokens
  output = subprocess.Popen(["livestreamer", "twitch.tv/CHANNEL_NAME", "-j"],
  stdout=subprocess.PIPE).communicate()[0]
  return json.loads(output)['streams']['worst']['url'] # Parse json and return the URL parameter

def build(): # Builds a set of tokens, aka viewers
  global numberOfSockets
  global numberOfViewers
  while True:
    if numberOfSockets < numberOfViewers:
      numberOfSockets += 1
      print ("Building viewers " + str(numberOfSockets) + "/" + str(numberOfViewers))
      urls.append(getURL())

def view(): # Opens connections to send views
  global numberOfSockets
  while True:
    url=q.get()
    requests.head(url)
    if (url in urlsUsed):
      urls.remove(url)
      urlsUsed.remove(url)
      numberOfSockets -= 1
    else:
      urlsUsed.append(url)
      q.task_done()

      if __name__ == '__main__':
        for i in range(0, builderThreads):
          threading.Thread(target = build).start()

          while True:
            while (numberOfViewers != numberOfSockets): # Wait until sockets are built
              time.sleep(1)

              q=Queue(concurrent*2)
              for i in range(concurrent):
                try:
                  t=threading.Thread(target=view)
                  t.daemon=True
                  t.start()
                except:
                  print ('thread error')
                  try:
                    for url in urls:
                      print (url)
                      q.put(url.strip())
                      q.join()
                  except KeyboardInterrupt:
                    sys.exit(1)
</code>```

3.ImportError: No module named 'requests'

This means your module request is missing. Simply install it with using Command line if you have Windows or Terminal if you have a Mac.

```<code>$ sudo pip install requests --upgrade
</code>```

Title: Errors with my python code

Body:
My python cod keeps giving me errors like indention and syntax which I keep fixing them but to no avail. So here is the code I'm using I'm still not sure what I'm doing wrong here (BTW this is just due to an argument with a friend about what I can't do)

import requests
import subprocess
import json
import sys
import threading
import time
from Queue import Queue

numberOfViewers = int(sys.argv[1])
builderThreads = int(sys.argv[2])
startTime = time.time()
numberOfSockets = 0
concurrent = 25
urls = []
urlsUsed = []

def getURL(): # Get tokens
  output = subprocess.Popen(["livestreamer", "twitch.tv/CHANNEL_NAME", "-j"], stdout=subprocess.PIPE).communicate()[0]
        return json.loads(output)['streams']['worst']['url'] # Parse json and return the URL parameter

def build(): # Builds a set of tokens, aka viewers
        global numberOfSockets
        global numberOfViewers
        while True:
                if numberOfSockets < numberOfViewers:
                        numberOfSockets += 1
                        print "Building viewers " + str(numberOfSockets) + "/" + str(numberOfViewers)
                        urls.append(getURL())

def view(): # Opens connections to send views
        global numberOfSockets
        while True:
                url=q.get()
                requests.head(url)
                if (url in urlsUsed):
                        urls.remove(url)
                        urlsUsed.remove(url)
                        numberOfSockets -= 1
                else:
                        urlsUsed.append(url)
                q.task_done()

if __name__ == '__main__':
        for i in range(0, builderThreads):
                threading.Thread(target = build).start()

        while True:
                while (numberOfViewers != numberOfSockets): # Wait until sockets are built
                        time.sleep(1)

                q=Queue(concurrent*2)
                for i in range(concurrent):
                        try:
                                t=threading.Thread(target=view)
                                t.daemon=True
                                t.start()
                        except:
                                print 'thread error'
                try:
                        for url in urls:
                                print url
                                q.put(url.strip())
                                q.join()
                except KeyboardInterrupt:
                        sys.exit(1)

Body:
You have a couple error in your code:

1: print:
If you are using Python3 -

The print statement has been replaced with a print() function, with
  keyword arguments to replace most of the special syntax of the old
  print statement

for more information about whats new in python 3

2: Indentation:
If you are getting this error:
IndentationError: expected an indented block
that means you have improper indentations. As an interpreted language proper indentation is necessary and important for Python:

Leading whitespace (spaces and tabs) at the beginning of a logical
  line is used to compute the indentation level of the line, which in
  turn is used to determine the grouping of statements.

for more information look at Python reference manual for Indentation

Fixed code example:

I fixed these error for you and below is how it should look like:

import requests
import subprocess
import json
import sys
import threading
import time
from Queue import Queue

numberOfViewers = int(sys.argv[1])
builderThreads = int(sys.argv[2])
startTime = time.time()
numberOfSockets = 0
concurrent = 25
urls = []
urlsUsed = []

def getURL(): # Get tokens
  output = subprocess.Popen(["livestreamer", "twitch.tv/CHANNEL_NAME", "-j"],
  stdout=subprocess.PIPE).communicate()[0]
  return json.loads(output)['streams']['worst']['url'] # Parse json and return the URL parameter

def build(): # Builds a set of tokens, aka viewers
  global numberOfSockets
  global numberOfViewers
  while True:
    if numberOfSockets < numberOfViewers:
      numberOfSockets += 1
      print ("Building viewers " + str(numberOfSockets) + "/" + str(numberOfViewers))
      urls.append(getURL())

def view(): # Opens connections to send views
  global numberOfSockets
  while True:
    url=q.get()
    requests.head(url)
    if (url in urlsUsed):
      urls.remove(url)
      urlsUsed.remove(url)
      numberOfSockets -= 1
    else:
      urlsUsed.append(url)
      q.task_done()

      if __name__ == '__main__':
        for i in range(0, builderThreads):
          threading.Thread(target = build).start()

          while True:
            while (numberOfViewers != numberOfSockets): # Wait until sockets are built
              time.sleep(1)

              q=Queue(concurrent*2)
              for i in range(concurrent):
                try:
                  t=threading.Thread(target=view)
                  t.daemon=True
                  t.start()
                except:
                  print ('thread error')
                  try:
                    for url in urls:
                      print (url)
                      q.put(url.strip())
                      q.join()
                  except KeyboardInterrupt:
                    sys.exit(1)

3.ImportError: No module named 'requests'

This means your module request is missing. Simply install it with using Command line if you have Windows or Terminal if you have a Mac.

$ sudo pip install requests --upgrade


问:
C# Visual Studio Data Grid View returning 0 where SQL count is meant to me shown
I have this SQL query which work when I run it in SQL Management Studio.

```<code>select Products.ProductName, ProductTypes.ProductType, count(SaleID) numSales
from Products
join ProductTypes on ( ProductTypes.ProductTypeID= Products.ProductTypeID)
join Sales on ( Sales.ProductID = Products.ProductID)
group by Products.ProductName, ProductTypes.ProductType
</code>```

It returns this table.

Am am integrating this in with Visual Studio Data Grid View and am struggling to get the numSales column to work, right now it just shows 0 for everything like this.

Here is my code for populating the table

```<code>private void DisplayDashboard()
        {
            string numSalesQuery = "select Products.ProductName, ProductTypes.ProductType, count(SaleID) numSales " +
                "from Products join ProductTypes on (ProductTypes.ProductTypeID = Products.ProductTypeID)" +
                "join Sales on (Sales.ProductID = Products.ProductID)" +
                "group by Products.ProductName, ProductTypes.ProductType";

            List<_Dashboard> dashList = new List<_Dashboard>();
            try
            {
                // Automatically  open and close the connection
                using (var conn = ConnectionManager.DatabaseConnection())
                using (var cmd = new SqlCommand(numSalesQuery, conn))
                using (var rdr = cmd.ExecuteReader())
                {

                    while (rdr.Read())
                    {
                        //Define the list items
                        var dashboard = new _Dashboard(
                            rdr["ProductName"].ToString(),
                            rdr["ProductType"].ToString(),
                            int.Parse(rdr["numSales"].ToString()));
                        dashList.Add(dashboard);
                    }
                    dgvDashboard.DataSource = dashList;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Unsuccessful" + ex);
            }

        }
</code>```

Thanks for any help regarding the issue.

Edit:
Here is the _Dashboard Class

```<code>namespace Acme_Project.Business_Logic_Layer
{
    public class _Dashboard
    {
        //Declare properties of a Customer

        public String ProductName { get; set; }
        public string ProductType { get; set; }
        public int NumSales { get; set; }

        //Declaring Default Constructor
        public _Dashboard() { }

        //Parameterised Constructor
        public _Dashboard(string productname, string productype, int numsales)
        {
            ProductName = productname;
            ProductType = productype;
            NumSales = NumSales;
        }
    }
}
</code>```

答: Set NumSales = NumSales to NumSales = numsales inside your parameterised constructor

Body:
I have this SQL query which work when I run it in SQL Management Studio.

select Products.ProductName, ProductTypes.ProductType, count(SaleID) numSales
from Products
join ProductTypes on ( ProductTypes.ProductTypeID= Products.ProductTypeID)
join Sales on ( Sales.ProductID = Products.ProductID)
group by Products.ProductName, ProductTypes.ProductType

It returns this table.

Am am integrating this in with Visual Studio Data Grid View and am struggling to get the numSales column to work, right now it just shows 0 for everything like this.

Here is my code for populating the table

private void DisplayDashboard()
        {
            string numSalesQuery = "select Products.ProductName, ProductTypes.ProductType, count(SaleID) numSales " +
                "from Products join ProductTypes on (ProductTypes.ProductTypeID = Products.ProductTypeID)" +
                "join Sales on (Sales.ProductID = Products.ProductID)" +
                "group by Products.ProductName, ProductTypes.ProductType";

            List<_Dashboard> dashList = new List<_Dashboard>();
            try
            {
                // Automatically  open and close the connection
                using (var conn = ConnectionManager.DatabaseConnection())
                using (var cmd = new SqlCommand(numSalesQuery, conn))
                using (var rdr = cmd.ExecuteReader())
                {

                    while (rdr.Read())
                    {
                        //Define the list items
                        var dashboard = new _Dashboard(
                            rdr["ProductName"].ToString(),
                            rdr["ProductType"].ToString(),
                            int.Parse(rdr["numSales"].ToString()));
                        dashList.Add(dashboard);
                    }
                    dgvDashboard.DataSource = dashList;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Unsuccessful" + ex);
            }

        }

Thanks for any help regarding the issue.

Edit:
Here is the _Dashboard Class

namespace Acme_Project.Business_Logic_Layer
{
    public class _Dashboard
    {
        //Declare properties of a Customer

        public String ProductName { get; set; }
        public string ProductType { get; set; }
        public int NumSales { get; set; }

        //Declaring Default Constructor
        public _Dashboard() { }

        //Parameterised Constructor
        public _Dashboard(string productname, string productype, int numsales)
        {
            ProductName = productname;
            ProductType = productype;
            NumSales = NumSales;
        }
    }
}


问:
Relating The Concept of All Possible Outcomes With Number of Angles (& Sides) Within a Polygon
I am trying to find all possible angles and sides in a given shape. However, I am struggling. This is the start of my code.

```<code>SidesNumber = int(input("How many sides does your shape have: "))
SidesNumber = str(SidesNumber)
ShapeName = input("What is your shape's name. Please enter "+ SidesNumber +" letters: ")
SidesNumber = int(SidesNumber)
while (len(ShapeName) != SidesNumber) or(not ShapeName.isalpha()):
    if (len(ShapeName) != SidesNumber) and(not ShapeName.isalpha()):
        print("Your input does not match the number of vertices your shape has and does not consist of only letters!")
        SidesNumber = str(SidesNumber)
        ShapeName = input("What is your shape's name. Please enter "+ SidesNumber +" letters: ")
        SidesNumber = int(SidesNumber)
    elif len(ShapeName) != SidesNumber:
        print("Your input does not match the number of vertices your shape has!")
        SidesNumber = str(SidesNumber)
        ShapeName = input("What is your shape's name. Please enter "+ SidesNumber +" letters: ")
        SidesNumber = int(SidesNumber)
    elif not ShapeName.isalpha():
        print("Your input does not consist of letters only!")
        SidesNumber = str(SidesNumber)
        ShapeName = input("What is your shape's name. Please enter "+ SidesNumber +" letters: ")
        SidesNumber = int(SidesNumber)
</code>```

Now what I want to do is to get the computer to calculate all the different angles and sides based on the users' inputs.
So if they enter SidesNumber and ABC for the ShapeName I want the computer to find all the angles and sides or all the possible outcomes in other words. So the angles should be ∠ABC, ∠ACB, ∠BAC. And the sides should be AB, BC, AC.

Furthermore, I want these results to be saved in different variables, something like side1 = 'AB'and side2 ='BC' and side3 = 'AC'. For angles something like angle1 = '∠ABC' and angle1 = '∠ACB' and angle1 = '∠BAC'

I already of this code:

```<code>import itertools
dataset = ['1','2','3A','4']
var = list(itertools.combinations(dataset, 3))
print(var)
</code>```

But it seems to be useless for me.

答:
I'm not sure I completely follow your description of what you're trying to do, but think these examples of generating the outcomes might be helpful:

```<code>def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = [iter(iterable) for _ in range(2)]
    next(b, None)
    return zip(a, b)

# hardcode a name for non-interactive testing
shape_name = 'ABC'

sides = [''.join(pair) for pair in pairwise(shape_name + shape_name[0])]
print('sides: {}'.format(sides))

def angle_name(shape_name, side):
    this = shape_name.index(side[-1])  # index of letter for end of this segment
    try:
        nx = shape_name[this+1]  # get letter for next segment
    except IndexError:
        nx = shape_name[0]  # wrap around

    return '∠'+side+nx

angles = [angle_name(shape_name, side) for side in sides]
print('angles: {}'.format(angles))
</code>```

Output:

sides: ['AB', 'BC', 'CA']
angles: ['∠ABC', '∠BCA', '∠CAB']
```

Regardless, I also strongly suggest you read and start following to PEP 8 - Style Guide for Python Code, particularly the Naming Conventions section.

Body:
I am trying to find all possible angles and sides in a given shape. However, I am struggling. This is the start of my code.

SidesNumber = int(input("How many sides does your shape have: "))
SidesNumber = str(SidesNumber)
ShapeName = input("What is your shape's name. Please enter "+ SidesNumber +" letters: ")
SidesNumber = int(SidesNumber)
while (len(ShapeName) != SidesNumber) or(not ShapeName.isalpha()):
    if (len(ShapeName) != SidesNumber) and(not ShapeName.isalpha()):
        print("Your input does not match the number of vertices your shape has and does not consist of only letters!")
        SidesNumber = str(SidesNumber)
        ShapeName = input("What is your shape's name. Please enter "+ SidesNumber +" letters: ")
        SidesNumber = int(SidesNumber)
    elif len(ShapeName) != SidesNumber:
        print("Your input does not match the number of vertices your shape has!")
        SidesNumber = str(SidesNumber)
        ShapeName = input("What is your shape's name. Please enter "+ SidesNumber +" letters: ")
        SidesNumber = int(SidesNumber)
    elif not ShapeName.isalpha():
        print("Your input does not consist of letters only!")
        SidesNumber = str(SidesNumber)
        ShapeName = input("What is your shape's name. Please enter "+ SidesNumber +" letters: ")
        SidesNumber = int(SidesNumber)

Now what I want to do is to get the computer to calculate all the different angles and sides based on the users' inputs.
So if they enter SidesNumber and ABC for the ShapeName I want the computer to find all the angles and sides or all the possible outcomes in other words. So the angles should be ∠ABC, ∠ACB, ∠BAC. And the sides should be AB, BC, AC.

Furthermore, I want these results to be saved in different variables, something like side1 = 'AB'and side2 ='BC' and side3 = 'AC'. For angles something like angle1 = '∠ABC' and angle1 = '∠ACB' and angle1 = '∠BAC'

I already of this code:

import itertools
dataset = ['1','2','3A','4']
var = list(itertools.combinations(dataset, 3))
print(var)

But it seems to be useless for me.

Body:
I'm not sure I completely follow your description of what you're trying to do, but think these examples of generating the outcomes might be helpful:

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = [iter(iterable) for _ in range(2)]
    next(b, None)
    return zip(a, b)

# hardcode a name for non-interactive testing
shape_name = 'ABC'

sides = [''.join(pair) for pair in pairwise(shape_name + shape_name[0])]
print('sides: {}'.format(sides))

def angle_name(shape_name, side):
    this = shape_name.index(side[-1])  # index of letter for end of this segment
    try:
        nx = shape_name[this+1]  # get letter for next segment
    except IndexError:
        nx = shape_name[0]  # wrap around

    return '∠'+side+nx

angles = [angle_name(shape_name, side) for side in sides]
print('angles: {}'.format(angles))

Output:

sides: ['AB', 'BC', 'CA']
angles: ['∠ABC', '∠BCA', '∠CAB']

Regardless, I also strongly suggest you read and start following to PEP 8 - Style Guide for Python Code, particularly the Naming Conventions section.


问:
How do I put extra number at the end of username if duplicate
Hard to explain, and let me show an example.

If username foo already exists in MySQL I want php script will allow it but to be foo1

Then if foo1 exists too, script will generate the username will be foo2

If foo2 existed then become foo3

How to make like that?

Like Col. Shrapnel said Natural increment which seems more sensible. just like "New Folder(3)" stuff in Windows

答:
Try this one (you need to modifiy this to your needs!)</p>

```<code>$username_loop = $username = "foo"; // edit: compatibility to usernames n.e. "foo"
$count = 0;
while (){
  $count++;
  $query =  "SELECT username FROM User WHERE username = ".$username_loop;
  $result = mysql_query($query);
  if ($result){
     $username_loop = $username.$count;
  }
  else break;
}
</code>```

Body:
Try this one (you need to modifiy this to your needs!)

$username_loop = $username = "foo"; // edit: compatibility to usernames n.e. "foo"
$count = 0;
while (){
  $count++;
  $query =  "SELECT username FROM User WHERE username = ".$username_loop;
  $result = mysql_query($query);
  if ($result){
     $username_loop = $username.$count;
  }
  else break;
}


答:
It is simple indeed, you can even do it in a beautiful one liner using list comprehension as follows:

```<code>new_var = [my_string.split(x)[1] for my_string in my_strings for x in my_list if x in my_string]
</code>```

this returns for you 2nd element from all splits of all strings in my_strings in which there exists elements from my_list

Body:
It is simple indeed, you can even do it in a beautiful one liner using list comprehension as follows:

new_var = [my_string.split(x)[1] for my_string in my_strings for x in my_list if x in my_string]

this returns for you 2nd element from all splits of all strings in my_strings in which there exists elements from my_list


问:
When to use type alias vs. single-value union type in Elm
I've been reading over Richard Feldman's Elm SPA app example, and I'm seeing a number of examples of things like this:

```<code>type Username
    = Username String
</code>```

and I'm not sure when it makes sense to use something like that, a single-value union type, vs. just a type alias like this:

```<code>type alias Username
    = String
</code>```

When is it appropriate to use a single-value union type vs. just using a type alias?

答:
There is no hard and fast rule for when it is appropriate, but I tend to follow a few rules of thumb. Let's use an authenticate function example that takes a username and password, both of which are string values.

At a bare minimum, without any additional alias or types, the annotation could be this:

authenticate : String -> String -> Bool
```

<p>Given that annotation, it isn't clear which parameter is the username and which is the password. We can improve the readability by using type aliases:</p>

<pre class="lang-elm prettyprint-override"><code>type alias Username = String
type alias Password = String

authenticate : Username -> Password -> Bool
</code>```

This is better for consumers of my package but type aliases won't disallow you from accidentally swapping the parameters in calling code. For example, this problematic function would compile:

login : Username -> Password -> Bool
login username password =
    if authenticate password username then ...
```

<p>If you want to go a step further and force the explicit declaration of the type every time you use it, you could avoid that type of error because the compiler will catch mixups:</p>

<pre class="lang-elm prettyprint-override"><code>type Username = Username String
type Password = Password String
</code>```

With that definition, you must now explicitly unwrap and package the strings in either a Username or Password constructor every time you use it. This is especially useful for things like units of measure, where such a concept could have avoided the loss of a Mars mission

As you see in Richard's example, going the route of a full type and type constructor means you'll need separate boilerplate functions for json decoding, encoding, etc, which can get tedious. You'll need to find the right balance for your team and projects.

Body:
I've been reading over Richard Feldman's Elm SPA app example, and I'm seeing a number of examples of things like this:

type Username
    = Username String

and I'm not sure when it makes sense to use something like that, a single-value union type, vs. just a type alias like this:

type alias Username
    = String

When is it appropriate to use a single-value union type vs. just using a type alias?

Body:
There is no hard and fast rule for when it is appropriate, but I tend to follow a few rules of thumb. Let's use an authenticate function example that takes a username and password, both of which are string values.

At a bare minimum, without any additional alias or types, the annotation could be this:

authenticate : String -> String -> Bool

Given that annotation, it isn't clear which parameter is the username and which is the password. We can improve the readability by using type aliases:

type alias Username = String
type alias Password = String

authenticate : Username -> Password -> Bool

This is better for consumers of my package but type aliases won't disallow you from accidentally swapping the parameters in calling code. For example, this problematic function would compile:

login : Username -> Password -> Bool
login username password =
    if authenticate password username then ...

If you want to go a step further and force the explicit declaration of the type every time you use it, you could avoid that type of error because the compiler will catch mixups:

type Username = Username String
type Password = Password String

With that definition, you must now explicitly unwrap and package the strings in either a Username or Password constructor every time you use it. This is especially useful for things like units of measure, where such a concept could have avoided the loss of a Mars mission

As you see in Richard's example, going the route of a full type and type constructor means you'll need separate boilerplate functions for json decoding, encoding, etc, which can get tedious. You'll need to find the right balance for your team and projects.


问:
PHP can't read my html inside a file
I have a template class that I can echo out files through it.
I give the address of my file to template class and echo it out.
I have 4 files named: index, topic, topics, register and all of them are doing perfect but topic.php is empty.here is my code for example for the register inside a register controller file.what should I do? thank you.</p>

```<code><?php
$template = new template('templates/register.php');//include the template
//display template
echo $template;
</code>```

答:
I found why this is happening.this is because in classes folder, I have a template class and a topic class and topic is empty.
PHP goes to this directory(I don't know why !!!!).. and echo out topic class except topic file.</p>

Title: PHP can't read my html inside a file

Body:
I have a template class that I can echo out files through it.
I give the address of my file to template class and echo it out.
I have 4 files named: index, topic, topics, register and all of them are doing perfect but topic.php is empty.here is my code for example for the register inside a register controller file.what should I do? thank you.

<?php
$template = new template('templates/register.php');//include the template
//display template
echo $template;


问:
Why a statement written after iterating over an empty list does not work python
To my knowledge, the following code will not work:

```<code>empty_list = []
if empty_list:
    print("It's an empty list, duh...")
</code>```

However, I came across the following situation:

```<code>arr = []
for r in arr:
    print(r)
    print("Why?")
</code>```

While it's understandable that arr is empty, therefore print(r) will return nothing, why the following piece of code does not work?

Does for also tests for boolean?

答:
This should help you understand. An attempt to iterate manually over a list:

```<code>In [349]: x = iter([1, 2, 3])

In [350]: next(x)
Out[350]: 1

In [351]: next(x)
Out[351]: 2

In [352]: next(x)
Out[352]: 3

In [353]: next(x)
---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
<ipython-input-353-5e4e57af3a97> in <module>()
----> 1 next(x)

StopIteration:
</code>```

Meanwhile, an empty list throws a StopIteration immediately:

```<code>In [354]: x = iter([])

In [355]: next(x)
---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
<ipython-input-355-5e4e57af3a97> in <module>()
----> 1 next(x)

StopIteration:
</code>```

This exact thing happens in the for loop, iterating over each element until a StopIteration exception is reached. If you have an empty list, you have nothing to iterate over:

```<code>In [356]: for i in [1, 2, 3]:
     ...:     print(i)
     ...:
1
2
3

In [357]: for i in []:
     ...:     print(i)
     ...:
</code>```

Body:
To my knowledge, the following code will not work:

empty_list = []
if empty_list:
    print("It's an empty list, duh...")

However, I came across the following situation:

arr = []
for r in arr:
    print(r)
    print("Why?")

While it's understandable that arr is empty, therefore print(r) will return nothing, why the following piece of code does not work?

Does for also tests for boolean?

Body:
This should help you understand. An attempt to iterate manually over a list:

In [349]: x = iter([1, 2, 3])

In [350]: next(x)
Out[350]: 1

In [351]: next(x)
Out[351]: 2

In [352]: next(x)
Out[352]: 3

In [353]: next(x)
---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
<ipython-input-353-5e4e57af3a97> in <module>()
----> 1 next(x)

StopIteration:

Meanwhile, an empty list throws a StopIteration immediately:

In [354]: x = iter([])

In [355]: next(x)
---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
<ipython-input-355-5e4e57af3a97> in <module>()
----> 1 next(x)

StopIteration:

This exact thing happens in the for loop, iterating over each element until a StopIteration exception is reached. If you have an empty list, you have nothing to iterate over:

In [356]: for i in [1, 2, 3]:
     ...:     print(i)
     ...:
1
2
3

In [357]: for i in []:
     ...:     print(i)
     ...:


问:
conversion of 2D array to pointer-to-pointer
```<code>Activity solution[a][b];

...

Activity **mother = solution;
</code>```

I want to convert 2D array of objects to pointer-to-pointer. How can I do this;

I searched it on google. however I found only one dimension array example.

答:
This is c++! Everything is possible! But a this is c++ so it requires some level of understanding.

To that end let's start with a simple example of 2 1-dimensional arrays: char firstName[4] = { 'J', 'o', 'n', '\0' } and char lastName[4] = { 'M', 'e', 'e', '\0' } Let's look at a possible memory layout here:

```<code>+------------+-------+
|  Address   | Value |
+------------+-------+
| 0x76543210 | 0x4A  | <- firstName[0] - 'J'
| 0x76543211 | 0x6F  | <- firstName[1] - 'o'
| 0x76543212 | 0x6E  | <- firstName[2] - 'n'
| 0x76543213 | 0x00  | <- firstName[3] - '\0'
+------------+-------+
| 0x76543214 | 0x4D  | <- lastName[0] - 'M'
| 0x76543215 | 0x65  | <- lastName[1] - 'e'
| 0x76543216 | 0x65  | <- lastName[2] - 'e'
| 0x76543217 | 0x00  | <- lastName[3] - '\0'
+------------+-------+
</code>```

Given this memory layout if you were to do cout << firstName << ' ' << lastName you'd get:

0x76543210 0x76543214

These arrays are really just a pointer to their first element! This illustrates Array to Pointer Decay, which you can read more about here: http://en.cppreference.com/w/cpp/language/array#Array-to-pointer_decay

Before we move on there's something important here to note, chars take up exactly 1-byte so the address of each subsequent char in the array will simply be the next address. That's leveraged by the Subscript Operator in this way: firstName[1] is equivalent to *(firstName + 1). This is true for chars but is also true for any other type which takes up more than 1-byte. Let's take for example: short siArray = { 1, 2, 3, 4 }, a possible memory layout of siArray would look like:

```<code>+------------+--------+
|  Address   | Value  |
+------------+--------+
| 0x76543218 | 0x0001 | <- siArray[0] - 1
| 0x7654321A | 0x0002 | <- siArray[1] - 2
| 0x7654321C | 0x0003 | <- siArray[2] - 3
| 0x7654321E | 0x0004 | <- siArray[3] - 4
+------------+--------+
</code>```

Even though cout << siArray << ' ' << &(siArray[1]) will output:

0x76543218 0x7654321A

*(siArray + 1) will still index the same element of siArray as siArray[1]. This is because when doing pointer arithmetic c++ considers the type of the address being operated on, thus incrementing a short* will actually increase the address by sizeof(short). You can read more about pointer arithmetic here: http://en.cppreference.com/w/cpp/language/operator_arithmetic

Lastly let's look at how c++ stores 2-dimensional arrays. Given: char name[2][4] = { { 'J', 'o', 'n', '\0' }, { 'M', 'e', 'e', '\0' } } a possible memory layout would be:

```<code>+------------+-------+
|  Address   | Value |
+------------+-------+
| 0x76543220 | 0x4A  | <- name[0][0] - 'J'
| 0x76543221 | 0x6F  | <- name[0][1] - 'o'
| 0x76543222 | 0x6E  | <- name[0][2] - 'n'
| 0x76543223 | 0x00  | <- name[0][3] - '\0'
| 0x76543224 | 0x4D  | <- name[1][0] - 'M'
| 0x76543225 | 0x65  | <- name[1][1] - 'e'
| 0x76543226 | 0x65  | <- name[1][2] - 'e'
| 0x76543227 | 0x00  | <- name[1][3] - '\0'
+------------+-------+
</code>```

Since we know an 1-dimensional array value is really just a pointer, we can see from this memory layout that name[0] is not a pointer, it's just the first character of the first array. Thus name does not contain 2 1-dimensional array pointers, but contains the contents of the 2 arrays. (Incidentally on a 32-bit machine not storing the pointers saves 8-bytes of memory, which is pretty substantial for an 8-byte 2-dimensional array.) Thus trying to treat name as a char** would try to use the characters as a pointer.

Having understood this we really just need to avoid using c++'s pointer arithmetic to find dereference the value. To do that we'll need to work with a char* so that adding 1 is really just adding 1. So for example:

```<code>const short si2DArray[2][3] = { { 11, 12, 13 }, { 21, 22, 23 } };
const auto psi2DPointer = reinterpret_cast<const char*>(si2DArray);

for(auto i = 0U; i < size(si2DArray); ++i) {
    for(auto j = 0U; j < size(*si2DArray); ++j) {
        cout << *reinterpret_cast<const short*>(psi2DPointer + i * sizeof(*si2DArray) + j * sizeof(**si2DArray)) << '\t';
    }
    cout << endl;
}
</code>```

Live Example

Note that in this example even though I reference si2DArray thought psi2DPointer I'm still using information from si2DArray to do the indexing, namely:

How many arrays are in the major dimension: size(si2DArray)

How many elements are in the minor dimension: size(*si2DArray)

What is the size in memory of the minor dimension: sizeof(*si2DArray)

What is the element type of the array: sizeof(**si2DArray)

You can thus see that the loss of information from converting from an array to a pointer is substantial. You may be tempted to preserve the element type, thereby also simplifying the pointer arithmetic. It's worthwhile to note that only a conversion to char* is considered defined behavior by reinterpret_cast: http://en.cppreference.com/w/cpp/language/reinterpret_cast#Type_aliasing

Body:
Activity solution[a][b];

...

Activity **mother = solution;

I want to convert 2D array of objects to pointer-to-pointer. How can I do this;

I searched it on google. however I found only one dimension array example.

Body:
This is c++! Everything is possible! But a this is c++ so it requires some level of understanding.

To that end let's start with a simple example of 2 1-dimensional arrays: char firstName[4] = { 'J', 'o', 'n', '\0' } and char lastName[4] = { 'M', 'e', 'e', '\0' } Let's look at a possible memory layout here:

+------------+-------+
|  Address   | Value |
+------------+-------+
| 0x76543210 | 0x4A  | <- firstName[0] - 'J'
| 0x76543211 | 0x6F  | <- firstName[1] - 'o'
| 0x76543212 | 0x6E  | <- firstName[2] - 'n'
| 0x76543213 | 0x00  | <- firstName[3] - '\0'
+------------+-------+
| 0x76543214 | 0x4D  | <- lastName[0] - 'M'
| 0x76543215 | 0x65  | <- lastName[1] - 'e'
| 0x76543216 | 0x65  | <- lastName[2] - 'e'
| 0x76543217 | 0x00  | <- lastName[3] - '\0'
+------------+-------+

Given this memory layout if you were to do cout << firstName << ' ' << lastName you'd get:

0x76543210 0x76543214

These arrays are really just a pointer to their first element! This illustrates Array to Pointer Decay, which you can read more about here: http://en.cppreference.com/w/cpp/language/array#Array-to-pointer_decay

Before we move on there's something important here to note, chars take up exactly 1-byte so the address of each subsequent char in the array will simply be the next address. That's leveraged by the Subscript Operator in this way: firstName[1] is equivalent to *(firstName + 1). This is true for chars but is also true for any other type which takes up more than 1-byte. Let's take for example: short siArray = { 1, 2, 3, 4 }, a possible memory layout of siArray would look like:

+------------+--------+
|  Address   | Value  |
+------------+--------+
| 0x76543218 | 0x0001 | <- siArray[0] - 1
| 0x7654321A | 0x0002 | <- siArray[1] - 2
| 0x7654321C | 0x0003 | <- siArray[2] - 3
| 0x7654321E | 0x0004 | <- siArray[3] - 4
+------------+--------+

Even though cout << siArray << ' ' << &(siArray[1]) will output:

0x76543218 0x7654321A

*(siArray + 1) will still index the same element of siArray as siArray[1]. This is because when doing pointer arithmetic c++ considers the type of the address being operated on, thus incrementing a short* will actually increase the address by sizeof(short). You can read more about pointer arithmetic here: http://en.cppreference.com/w/cpp/language/operator_arithmetic

Lastly let's look at how c++ stores 2-dimensional arrays. Given: char name[2][4] = { { 'J', 'o', 'n', '\0' }, { 'M', 'e', 'e', '\0' } } a possible memory layout would be:

+------------+-------+
|  Address   | Value |
+------------+-------+
| 0x76543220 | 0x4A  | <- name[0][0] - 'J'
| 0x76543221 | 0x6F  | <- name[0][1] - 'o'
| 0x76543222 | 0x6E  | <- name[0][2] - 'n'
| 0x76543223 | 0x00  | <- name[0][3] - '\0'
| 0x76543224 | 0x4D  | <- name[1][0] - 'M'
| 0x76543225 | 0x65  | <- name[1][1] - 'e'
| 0x76543226 | 0x65  | <- name[1][2] - 'e'
| 0x76543227 | 0x00  | <- name[1][3] - '\0'
+------------+-------+

Since we know an 1-dimensional array value is really just a pointer, we can see from this memory layout that name[0] is not a pointer, it's just the first character of the first array. Thus name does not contain 2 1-dimensional array pointers, but contains the contents of the 2 arrays. (Incidentally on a 32-bit machine not storing the pointers saves 8-bytes of memory, which is pretty substantial for an 8-byte 2-dimensional array.) Thus trying to treat name as a char** would try to use the characters as a pointer.

Having understood this we really just need to avoid using c++'s pointer arithmetic to find dereference the value. To do that we'll need to work with a char* so that adding 1 is really just adding 1. So for example:

const short si2DArray[2][3] = { { 11, 12, 13 }, { 21, 22, 23 } };
const auto psi2DPointer = reinterpret_cast<const char*>(si2DArray);

for(auto i = 0U; i < size(si2DArray); ++i) {
    for(auto j = 0U; j < size(*si2DArray); ++j) {
        cout << *reinterpret_cast<const short*>(psi2DPointer + i * sizeof(*si2DArray) + j * sizeof(**si2DArray)) << '\t';
    }
    cout << endl;
}

Live Example

Note that in this example even though I reference si2DArray thought psi2DPointer I'm still using information from si2DArray to do the indexing, namely:

How many arrays are in the major dimension: size(si2DArray)

How many elements are in the minor dimension: size(*si2DArray)

What is the size in memory of the minor dimension: sizeof(*si2DArray)

What is the element type of the array: sizeof(**si2DArray)

You can thus see that the loss of information from converting from an array to a pointer is substantial. You may be tempted to preserve the element type, thereby also simplifying the pointer arithmetic. It's worthwhile to note that only a conversion to char* is considered defined behavior by reinterpret_cast: http://en.cppreference.com/w/cpp/language/reinterpret_cast#Type_aliasing


问:
Getting the IListSource does not contain any data sources exception in ASP.NET
I am trying to bind ListView control to data contained in a DataSet type.
I have also introduced paging through DataPager type.

On the first call to DataBind, the binding happens perfectly.
But, when i click Next to retrieve the next set of results, even though my function returns the appropriate DataSet, it is unable to do binding.

```<code> void getSubSet(int rowindex, DataSet resultSet, int pageSize)
 {
   DataSet ds = new DataSet();
   DataTable tb = new DataTable();
   for (int cols = 0; cols < resultSet.Tables[0].Columns.Count; cols++)
   {
     DataColumn dc = new DataColumn(resultSet.Tables[0].Columns[cols].ColumnName,
                                           resultSet.Tables[0].Columns[cols].DataType);
     tb.Columns.Add(dc);
   }
   for (int i = rowindex; ((i < resultSet.Tables[0].Rows.Count) && (i < rowindex + pageSize)); i++ )
   {
     DataRow rowToBeAdded = resultSet.Tables[0].Rows[i];
     DataRow newRow;
     newRow = tb.NewRow();
     for (int j = 0; j < resultSet.Tables[0].Columns.Count; j++)
          newRow[j] = rowToBeAdded[j];
     tb.Rows.Add(newRow);
   }
   ds.Tables.Add(tb);
   return ds;
 }
</code>```

DataSet resultSet contains all results.

The above snippet returns perfect results,
but upon

```<code>LV.DataSource = getSubSet(newIndex, resultSet, pageSize);
LV.DataBind();
</code>```

where LV is a ListView control in the .aspx page. On second call during paging returns exception.

Please help! Thanks!

答:
Are you sure that the rsesultSet parameter passed to the getSubSet method is not empty the second time the method gets executed (on paging)? Debug the code to see whether the returned ds contains data.

If you want to simplify and reduce your code, use SqlDataSource (instead of binding by hand) and assign it directly to the LV via DataSourceID.

Body:
I am trying to bind ListView control to data contained in a DataSet type.
I have also introduced paging through DataPager type.

On the first call to DataBind, the binding happens perfectly.
But, when i click Next to retrieve the next set of results, even though my function returns the appropriate DataSet, it is unable to do binding.

 void getSubSet(int rowindex, DataSet resultSet, int pageSize)
 {
   DataSet ds = new DataSet();
   DataTable tb = new DataTable();
   for (int cols = 0; cols < resultSet.Tables[0].Columns.Count; cols++)
   {
     DataColumn dc = new DataColumn(resultSet.Tables[0].Columns[cols].ColumnName,
                                           resultSet.Tables[0].Columns[cols].DataType);
     tb.Columns.Add(dc);
   }
   for (int i = rowindex; ((i < resultSet.Tables[0].Rows.Count) && (i < rowindex + pageSize)); i++ )
   {
     DataRow rowToBeAdded = resultSet.Tables[0].Rows[i];
     DataRow newRow;
     newRow = tb.NewRow();
     for (int j = 0; j < resultSet.Tables[0].Columns.Count; j++)
          newRow[j] = rowToBeAdded[j];
     tb.Rows.Add(newRow);
   }
   ds.Tables.Add(tb);
   return ds;
 }

DataSet resultSet contains all results.

The above snippet returns perfect results,
but upon

LV.DataSource = getSubSet(newIndex, resultSet, pageSize);
LV.DataBind();

where LV is a ListView control in the .aspx page. On second call during paging returns exception.

Please help! Thanks!


问:
In React, how to prevent a component's CSS import from applying to the entire app?
I'm using facebook's create-react app for my application:

In my Login.js container, I am importing CSS like so:

```<code>import React from 'react';
import '../../styles/users/Login.css'
const Login = () => {
....
</code>```

The problem is the Login.css styles are being applied to my entire application... for example, if Login.css has:

```<code>body {
    background:Red ;
}
</code>```

The entire app would have a body of background: Red; Even outside of the Login container.

What I expected/want is for a CSS import within a container to only apply to that particular container.

Is that possible w React? How are react developers supposed to handle container specific stylings? Do I need to add an ID to all containers and include that in the entire CSS file?

答:
1. Solution: Give your DOM elements class names to use them in your css.

JS:

// in Link.js

import React from 'react';

import '../../styles/Link.css'

const Link = ({children, href}) => (
   {children}
);
```

<p>CSS: </p>

<pre class="lang-js prettyprint-override"><code>// Link.css

.link {
    color: red;
}
</code>```

2. Solution: Inline styles.

JS:

// in Link.js

import React from 'react';

import '../../styles/Link.css'

const Link = ({children, href}) => (
   {children}
);
```

3. Solution: CSS in JS.

There are some libraries that try to solve the styling issue:

Watch this talk: https://speakerdeck.com/vjeux/react-css-in-js

And have a look at this: https://github.com/cssinjs

styled-components: https://github.com/styled-components/styled-components

ContentLicense: CC BY-SA 4.0

Body:
I'm using facebook's create-react app for my application:

In my Login.js container, I am importing CSS like so:

import React from 'react';
import '../../styles/users/Login.css'
const Login = () => {
....

The problem is the Login.css styles are being applied to my entire application... for example, if Login.css has:

body {
    background:Red ;
}

The entire app would have a body of background: Red; Even outside of the Login container.

What I expected/want is for a CSS import within a container to only apply to that particular container.

Is that possible w React? How are react developers supposed to handle container specific stylings? Do I need to add an ID to all containers and include that in the entire CSS file?

Body:
1. Solution: Give your DOM elements class names to use them in your css.

JS:

// in Link.js

import React from 'react';

import '../../styles/Link.css'

const Link = ({children, href}) => (
   <a className="link" href={href}>{children}</a>
);

CSS:

// Link.css

.link {
    color: red;
}

2. Solution: Inline styles.

JS:

// in Link.js

import React from 'react';

import '../../styles/Link.css'

const Link = ({children, href}) => (
   <a style={color: 'red'} href={href}>{children}</a>
);

3. Solution: CSS in JS.

There are some libraries that try to solve the styling issue:

Watch this talk: https://speakerdeck.com/vjeux/react-css-in-js

And have a look at this: https://github.com/cssinjs

styled-components: https://github.com/styled-components/styled-components


问:
How do I convert spaced columns to tabs?

This question is not a duplicate as someone had suggested. Mods, pay attention

I'm running a for loop on multiple files that contain information like below

```<code>1    Leer            Normal   [status]     —      100
1    Wrap            Normal   [physical]   15     90
4    Poison Sting    Poison   [physical]   15     100
9    Bite            Dark     [physical]   60     100
12   Glare           Normal   [status]     —      100
17   Screech         Normal   [status]     —      85
20   Acid            Poison   [special]    40     100
25   Spit Up         Normal   [special]    —      100
25   Stockpile       Normal   [status]     —      —
25   Swallow         Normal   [status]     —      —
28   Acid Spray      Poison   [special]    40     100
33   Mud Bomb        Ground   [special]    65     85
36   Gastro Acid     Poison   [status]     —      100
38   Belch           Poison   [special]    120    90
41   Haze            Ice      [status]     —      —
44   Coil            Poison   [status]     —      —
49   Gunk Shot       Poison   [physical]   120    80
</code>```

I need to be able to extract data from it.

The problem is, each file has different column lengths.

Column 2 sometimes has spaces in it so squeezing all spaces and using space as a delimiter for cut is not an option. I need the columns separated by tabs without using specific information because the loop goes over about 800 files.

```<code>sed 's/  \+/ /g' | cut -f 2 -d " "
</code>```

^ Not what I need since column 2 has spaces in it

```<code>cut -b "5-20"
</code>```

^ Can't use this either because the columns lengths are different for each file.

答:
With sed, to replace multiples consecutive spaces or tabs with one tab:

```<code>sed 's/[[:space:]]\{1,\}/\t/g' file
</code>```

Explanations:

s: substitute

[[:space:]]: space or tab characters

\{1,\}: when at least one occurrence is found

g: apply substitution to all occurrences in line

Edit:

To preserve single spaces in second column, you can replace only when 2 spaces/tabs are found:

```<code>    sed 's/[[:space:]]\{2,\}/\t/g' file
</code>```

Body:
This question is not a duplicate as someone had suggested. Mods, pay attention

I'm running a for loop on multiple files that contain information like below

1    Leer            Normal   [status]     —      100
1    Wrap            Normal   [physical]   15     90
4    Poison Sting    Poison   [physical]   15     100
9    Bite            Dark     [physical]   60     100
12   Glare           Normal   [status]     —      100
17   Screech         Normal   [status]     —      85
20   Acid            Poison   [special]    40     100
25   Spit Up         Normal   [special]    —      100
25   Stockpile       Normal   [status]     —      —
25   Swallow         Normal   [status]     —      —
28   Acid Spray      Poison   [special]    40     100
33   Mud Bomb        Ground   [special]    65     85
36   Gastro Acid     Poison   [status]     —      100
38   Belch           Poison   [special]    120    90
41   Haze            Ice      [status]     —      —
44   Coil            Poison   [status]     —      —
49   Gunk Shot       Poison   [physical]   120    80

I need to be able to extract data from it.

The problem is, each file has different column lengths.

Column 2 sometimes has spaces in it so squeezing all spaces and using space as a delimiter for cut is not an option. I need the columns separated by tabs without using specific information because the loop goes over about 800 files.

sed 's/  \+/ /g' | cut -f 2 -d " "

^ Not what I need since column 2 has spaces in it

cut -b "5-20"

^ Can't use this either because the columns lengths are different for each file.

Body:
With sed, to replace multiples consecutive spaces or tabs with one tab:

sed 's/[[:space:]]\{1,\}/\t/g' file

Explanations:

s: substitute

[[:space:]]: space or tab characters

\{1,\}: when at least one occurrence is found

g: apply substitution to all occurrences in line

Edit:

To preserve single spaces in second column, you can replace only when 2 spaces/tabs are found:

    sed 's/[[:space:]]\{2,\}/\t/g' file


问:
How to calculate histogram of each of the blocks in the image and then concatenate them?
Suppose, I've divided an image to n blocks. I want to calculate histogram of each of the blocks and then concatenate the regional histograms. I studied this page and I write this code:

```<code>Map = imread("",0);
int histSize = 256;
int mapHeight = Map.rows;
int mapWidth = Map.cols;

int RegionRowNum = 9;
int RegionColNum = 9;

int regionHeightUnit = floor(mapHeight / RegionRowNum);  // the height for each region
int regionWidthUnit = floor(mapWidth / RegionColNum);     // the width for each region

int startHeight = floor((mapHeight - regionHeightUnit*RegionRowNum) / 2) + 1;
int startWidth = floor((mapWidth - regionWidthUnit*RegionColNum) / 2) + 1;

int sizes[] = { RegionRowNum, RegionColNum, histoDim };
Mat regionFeaMat = Mat(3, sizes, CV_8U, cv::Scalar(0));
vector<Mat> regionMapSets(RegionRowNum * RegionColNum);
vector<int> regionCoordinates(4);
Mat regionMap;
vector<Mat> regionMapHist;
float range[] = { 0, 256 };
const float* histRange = { range };
bool uniform = true;
bool accumulate = false;

for (int i = 0; i < RegionRowNum; i++)
{
    for (int j = 0; j< RegionColNum; j++)
    {
        // Get the coordinates for each block first
        regionCoordinates[0] = startHeight + i * regionHeightUnit;
        regionCoordinates[1] = regionCoordinates[0] + regionHeightUnit - 1;
        regionCoordinates[2] = startWidth + j * regionWidthUnit;
        regionCoordinates[3] = regionCoordinates[2] + regionWidthUnit - 1;

        if (i == 0)
            regionCoordinates[0] = 1;

        if (i == RegionRowNum - 1)
            regionCoordinates[1] = mapHeight;

        if (j == 0)
            regionCoordinates[2] = 1;

        if (j == RegionColNum - 1)
            regionCoordinates[3] = mapWidth;

        regionMap = Map(Rect(regionCoordinates[2] - 1, regionCoordinates[0] - 1, regionCoordinates[3] - regionCoordinates[2] + 1, regionCoordinates[1] - regionCoordinates[0] + 1));

        regionMapSets[i*RegionColNum + j] = regionMap;
        calcHist(&regionMapSets, 1, 0, Mat(), regionMapHist, 1, &histSize, &histRange, uniform, accumulate);

    }
}
</code>```

but i have this error:

```<code>Severity    Code    Description Project File    Line    Suppression State Detail Description Error (active)

no instance of overloaded function "calcHist" matches the argument list

argument types are: (std::vector<cv::Mat, std::allocator<cv::Mat>> *, int, int, cv::Mat, std::vector<cv::Mat, std::allocator<cv::Mat>>, int, int *, const float **, bool, bool)
</code>```

How to fix it?

答:
I edited my code in following way:
I add this line as output:

```<code>vector<Mat> regionMapHist(RegionRowNum * RegionColNum);
</code>```

and then i edited the arguments of calchist :

```<code>calcHist(&regionMap, 1, 0, Mat(), regionMapHist[i*RegionColNum + j], 1, &histoDim, &histRange, uniform, accumulate);
</code>```

regionMapHist is what i wanted!!

Body:
Suppose, I've divided an image to n blocks. I want to calculate histogram of each of the blocks and then concatenate the regional histograms. I studied this page and I write this code:

Map = imread("",0);
int histSize = 256;
int mapHeight = Map.rows;
int mapWidth = Map.cols;

int RegionRowNum = 9;
int RegionColNum = 9;

int regionHeightUnit = floor(mapHeight / RegionRowNum);  // the height for each region
int regionWidthUnit = floor(mapWidth / RegionColNum);     // the width for each region

int startHeight = floor((mapHeight - regionHeightUnit*RegionRowNum) / 2) + 1;
int startWidth = floor((mapWidth - regionWidthUnit*RegionColNum) / 2) + 1;

int sizes[] = { RegionRowNum, RegionColNum, histoDim };
Mat regionFeaMat = Mat(3, sizes, CV_8U, cv::Scalar(0));
vector<Mat> regionMapSets(RegionRowNum * RegionColNum);
vector<int> regionCoordinates(4);
Mat regionMap;
vector<Mat> regionMapHist;
float range[] = { 0, 256 };
const float* histRange = { range };
bool uniform = true;
bool accumulate = false;

for (int i = 0; i < RegionRowNum; i++)
{
    for (int j = 0; j< RegionColNum; j++)
    {
        // Get the coordinates for each block first
        regionCoordinates[0] = startHeight + i * regionHeightUnit;
        regionCoordinates[1] = regionCoordinates[0] + regionHeightUnit - 1;
        regionCoordinates[2] = startWidth + j * regionWidthUnit;
        regionCoordinates[3] = regionCoordinates[2] + regionWidthUnit - 1;

        if (i == 0)
            regionCoordinates[0] = 1;

        if (i == RegionRowNum - 1)
            regionCoordinates[1] = mapHeight;

        if (j == 0)
            regionCoordinates[2] = 1;

        if (j == RegionColNum - 1)
            regionCoordinates[3] = mapWidth;

        regionMap = Map(Rect(regionCoordinates[2] - 1, regionCoordinates[0] - 1, regionCoordinates[3] - regionCoordinates[2] + 1, regionCoordinates[1] - regionCoordinates[0] + 1));

        regionMapSets[i*RegionColNum + j] = regionMap;
        calcHist(&regionMapSets, 1, 0, Mat(), regionMapHist, 1, &histSize, &histRange, uniform, accumulate);

    }
}

but i have this error:

Severity    Code    Description Project File    Line    Suppression State Detail Description Error (active)

no instance of overloaded function "calcHist" matches the argument list

argument types are: (std::vector<cv::Mat, std::allocator<cv::Mat>> *, int, int, cv::Mat, std::vector<cv::Mat, std::allocator<cv::Mat>>, int, int *, const float **, bool, bool)

How to fix it?

Body:
I edited my code in following way:
I add this line as output:

vector<Mat> regionMapHist(RegionRowNum * RegionColNum);

and then i edited the arguments of calchist :

calcHist(&regionMap, 1, 0, Mat(), regionMapHist[i*RegionColNum + j], 1, &histoDim, &histRange, uniform, accumulate);

regionMapHist is what i wanted!!


问:
Sequelize - Destroy Records with Many to Many Relationship and Through Table
I have a scenario where I am trying to delete a record from a table with a many-to-many relationship, as well as the matching recordId within the junction (through) table that connects my two tables. I know there are set and get methods to create a record for one table and then automatically create the relationship in the through table, but is there a way to delete?

Here is the relationship:

User

```<code>User.belongsToMany(db.Organization, { through: 'organization_member', foreignKey: 'user_id'})
</code>```

Organization

```<code>Organization.belongsToMany(db.User, { through: 'organization_member', foreignKey: 'organization_id'})
</code>```

Note both foreignKey's are aliased to camel case by Sequelize which is why the error message is different than the column mentioned in the association.

And I'm trying to use a destroy command on the user table where any user is associated to the organization associated with the current users session. Unfortunately, the following command doesn't work because organization_id doesn't exist on the user table, but the organization_member junction table. Can anyone help?

```<code>deleteUsers: function(organizationId, t){
        console.log("Step 10: Delete Users");
        //DELETE users
        return models.User.destroy({
            where: {
                organizationId: organizationId
            }
        },{ transaction: t })
    }
</code>```

Error:

```<code>{ [SequelizeDatabaseError: column "organizationId" does not exist]
</code>```

答:
You have two problems

1) you're trying to delete users by organization id, but your users don't have an organization_id column, the organization_member table has that column. Are you trying to remove the association of user and organization, or are you trying to remove the user?

2) You are fighting Sequelize on column names. I think your best bet is to configure Sequelize to just use underscores or camel case for all foreign keys. That way you won't have to worry about always over-ruling it.

Here's my config:

```<code> const db = module.exports = new Sequelize(url, {
   dialect: 'postgres',

   define: {
     underscored: true,       // use snake_case rather than camelCase column names
     freezeTableName: true,   // don't change table names from the one specified
     timestamps: true,        // automatically include timestamp columns
   }
});
</code>```

Body:
I have a scenario where I am trying to delete a record from a table with a many-to-many relationship, as well as the matching recordId within the junction (through) table that connects my two tables. I know there are set and get methods to create a record for one table and then automatically create the relationship in the through table, but is there a way to delete?

Here is the relationship:

User

User.belongsToMany(db.Organization, { through: 'organization_member', foreignKey: 'user_id'})

Organization

Organization.belongsToMany(db.User, { through: 'organization_member', foreignKey: 'organization_id'})

Note both foreignKey's are aliased to camel case by Sequelize which is why the error message is different than the column mentioned in the association.

And I'm trying to use a destroy command on the user table where any user is associated to the organization associated with the current users session. Unfortunately, the following command doesn't work because organization_id doesn't exist on the user table, but the organization_member junction table. Can anyone help?

deleteUsers: function(organizationId, t){
        console.log("Step 10: Delete Users");
        //DELETE users
        return models.User.destroy({
            where: {
                organizationId: organizationId
            }
        },{ transaction: t })
    }

Error:

{ [SequelizeDatabaseError: column "organizationId" does not exist]

Body:
You have two problems

1) you're trying to delete users by organization id, but your users don't have an organization_id column, the organization_member table has that column. Are you trying to remove the association of user and organization, or are you trying to remove the user?

2) You are fighting Sequelize on column names. I think your best bet is to configure Sequelize to just use underscores or camel case for all foreign keys. That way you won't have to worry about always over-ruling it.

Here's my config:

 const db = module.exports = new Sequelize(url, {
   dialect: 'postgres',

   define: {
     underscored: true,       // use snake_case rather than camelCase column names
     freezeTableName: true,   // don't change table names from the one specified
     timestamps: true,        // automatically include timestamp columns
   }
});


问:
Adding a user-defined language in Notepad++
I'm trying to add the syntax plugin for the Go programming language in Notepad++.

There is a repository for such user-defined languages. I downloaded and unzipped the Go files, which contained a README, a userDefinedLang_Go.xml, and go.xml.

I attempted to follow the instructions at the bottom of the page as follows. Since I am using Windows 7 (x64), my Notepad++ directory is "C:\Program Files (x86)\Notepad++".

Having not installed a user defined language before, I didn't have a userDefinedLang.xml file already, so I copied userDefinedLang_Go.xml into the root directory, and renamed it to remove the "_Go", making it userDefinedLang.xml.

I then copied go.xml into C:\Program Files (x86)\Notepad++\plugins\APIs\

This seems to be all of the steps necessary. However, when I open Notepad++, there is no "Go" near "Lang => User Defined", and there is no syntactic coloring on a .go file. Attempting to import via "View => User-Defined Dialogue => import" gives a "fail to import" error.

What am I doing wrong? I'm using a clean installation of Notepad++, which is version 6.1.8.

答: If you don't have any user languages defined before, then after renaming userDefinedLang_Go.xml to userDefinedLang.xml, also edit the text of file by adding the tags <NotepadPlus></NotepadPlus> around the original content.


问:
Polynomial Support Vector Regression in Accord.Net
I'm trying to learn the framework (Accord) but the documentation often comes with broken pieces of code.

I wanted something similar to this.

I've tried different things and nothing seemed to work. Does anyone have a working non-lineal support vector regression example ?

I also tried the official example which doesn't seem to work either.

答:
The documentation is still being put together after the project adopted a new, unified learning API that is now common for all machine learning models. Most of it has just been updated yesterday, but a few parts might still need attention.

Answering your original question, you can find an example for Polynomial SV regression below. Let's say that we have 2-dimensional input vectors, and we would like to learn a mapping from those vectors into a single scalar value.

```<code>// Declare a very simple regression problem
// with only 2 input variables (x and y):
double[][] inputs =
{
    new[] { 3.0, 1.0 },
    new[] { 7.0, 1.0 },
    new[] { 3.0, 1.0 },
    new[] { 3.0, 2.0 },
    new[] { 6.0, 1.0 },
};

double[] outputs =
{
    65.3,
    94.9,
    65.3,
    66.4,
    87.5,
};
</code>```

For the sake of example, we will set the machine Complexity parameter to a very high value, forcing the learning algorithm to find hard-margin solutions that would otherwise not generalize very well. When training in real-world problems, leave the properties UseKernelEstimation and UseComplexityHeuristic set to true or perform a grid search to find their optimal parameters:

```<code>// Create a LibSVM-based support vector regression algorithm
var teacher = new FanChenLinSupportVectorRegression<Polynomial>()
{
    Tolerance = 1e-5,
    // UseKernelEstimation = true,
    // UseComplexityHeuristic = true
    Complexity = 10000,
    Kernel = new Polynomial(degree: 1) // you can change the degree
};
</code>```

Now, after we have created the learning algorithm, we can use it to train a SVM model from the data:

```<code>// Use the algorithm to learn the machine
var svm = teacher.Learn(inputs, outputs);
</code>```

And finally we can get the machine's answers for the set of inputs and we can check how good the values predicted by the machine were in comparison to the expected ground-truth:

```<code>// Get machine's predictions for inputs
double[] prediction = svm.Score(inputs);

// Compute the error in the prediction (should be 0.0)
double error = new SquareLoss(outputs).Loss(prediction);
</code>```

Body:
The documentation is still being put together after the project adopted a new, unified learning API that is now common for all machine learning models. Most of it has just been updated yesterday, but a few parts might still need attention.

Answering your original question, you can find an example for Polynomial SV regression below. Let's say that we have 2-dimensional input vectors, and we would like to learn a mapping from those vectors into a single scalar value.

// Declare a very simple regression problem
// with only 2 input variables (x and y):
double[][] inputs =
{
    new[] { 3.0, 1.0 },
    new[] { 7.0, 1.0 },
    new[] { 3.0, 1.0 },
    new[] { 3.0, 2.0 },
    new[] { 6.0, 1.0 },
};

double[] outputs =
{
    65.3,
    94.9,
    65.3,
    66.4,
    87.5,
};

For the sake of example, we will set the machine Complexity parameter to a very high value, forcing the learning algorithm to find hard-margin solutions that would otherwise not generalize very well. When training in real-world problems, leave the properties UseKernelEstimation and UseComplexityHeuristic set to true or perform a grid search to find their optimal parameters:

// Create a LibSVM-based support vector regression algorithm
var teacher = new FanChenLinSupportVectorRegression<Polynomial>()
{
    Tolerance = 1e-5,
    // UseKernelEstimation = true,
    // UseComplexityHeuristic = true
    Complexity = 10000,
    Kernel = new Polynomial(degree: 1) // you can change the degree
};

Now, after we have created the learning algorithm, we can use it to train a SVM model from the data:

// Use the algorithm to learn the machine
var svm = teacher.Learn(inputs, outputs);

And finally we can get the machine's answers for the set of inputs and we can check how good the values predicted by the machine were in comparison to the expected ground-truth:

// Get machine's predictions for inputs
double[] prediction = svm.Score(inputs);

// Compute the error in the prediction (should be 0.0)
double error = new SquareLoss(outputs).Loss(prediction);


问:
In-App Billing test: android.test.purchased already owned
I am currently testing In-App Billing for a future app, and after I successfully "bought" the test item "android.test.purchased" the first time, I now receive the response code 7 every time I try to buy it again, which means that I already own this item.

12-15 23:02:14.149: E/IabHelper(19829): In-app billing error: Unable
  to buy item, Error response: 7:Item Already Owned

From what I understand, this purchase is supposed to always be possible, right? So that the developer can test his/her app?

If not, how can I "reset" its state to not owned? I am using the util package from the Google In-App Billing Sample.

答:
For testing purposes I also suggest you to insert a piece of code that will be clearing  all the products that you've bought before calling a method that initializes gp purchase flow. That is especially comfortable, when you test just one item at the moment. E.g. like this:</p>

```<code>PurchasesResult purchasesResult = mBillingClient.queryPurchases(BillingClient.SkuType.INAPP);
    for (Purchase sourcePurchase : purchasesResult.getPurchasesList()) {
        if(sourcePurchase != null){

            ConsumeResponseListener listener = new ConsumeResponseListener() {
                @Override
                public void onConsumeResponse(String outToken, @BillingResponse int responseCode) {

                    System.out.println("all consumed");
                }
            };
            mBillingClient.consumeAsync(sourcePurchase.getPurchaseToken(), listener);
        }else{
            System.out.println("null");
        }
    }

// and then initiate whole process with clear "shoping basket"

BillingFlowParams.Builder builder = new BillingFlowParams.Builder()
        .setSku(itemName).setType(BillingClient.SkuType.INAPP);
</code>```

Body:
For testing purposes I also suggest you to insert a piece of code that will be clearing  all the products that you've bought before calling a method that initializes gp purchase flow. That is especially comfortable, when you test just one item at the moment. E.g. like this:

PurchasesResult purchasesResult = mBillingClient.queryPurchases(BillingClient.SkuType.INAPP);
    for (Purchase sourcePurchase : purchasesResult.getPurchasesList()) {
        if(sourcePurchase != null){

            ConsumeResponseListener listener = new ConsumeResponseListener() {
                @Override
                public void onConsumeResponse(String outToken, @BillingResponse int responseCode) {

                    System.out.println("all consumed");
                }
            };
            mBillingClient.consumeAsync(sourcePurchase.getPurchaseToken(), listener);
        }else{
            System.out.println("null");
        }
    }

// and then initiate whole process with clear "shoping basket"

BillingFlowParams.Builder builder = new BillingFlowParams.Builder()
        .setSku(itemName).setType(BillingClient.SkuType.INAPP);