问:
My React/Redux API wont log out properly shows [[PromiseValue]]
Quite new to coding but hitting hurdles with a React/Redux API.

I'm following Bucky Roberts' YouTube tutorial & ive replaced his static names object with an API that i then pull into my reducer.

This logs out the data fine, as an array - but when i try to pull it in to my Container, i get either a map is not a function error (even though it is an array) or if i log out console.log('props: ', this.props) i get [[PromiseValue]] with the array[10] showing.

But i'm pretty sure drilling into that in my component would be a no go.

CONTAINER:

```<code>class UserList extends Component {

  createListItems() {
    console.log('props: ', this.props);
    return this.props.users.map((user) => {
      return (
        <li
          key={user.id}
          onClick={() => this.props.selectUser(user)}
          >
          {user.name}
          </li>
      )
    })
  }

  render() {
    return (
      <div>
        <ul>
        {this.createListItems()}
        </ul>
      </div>
    )
  }
}

function mapStateToProps(state) {
  return {
    users: state.users
  }
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators({selectUser: selectUser}, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(UserList);
</code>```

API:

```<code>const MyData = fetch('https://jsonplaceholder.typicode.com/users')
  .then(function(data1) {
    return data1.json()
  }).then(function(data2) {
    return data2
  }).then(function(data3) {
    console.log('API RESPONSE: ', data3)
    return data3
  })

export default MyData;
</code>```

MyData is then pulled into a reducer, then into combineReducers({}) and the data should show back in mapStateToProps as above in the container. What Am I Doing Wrong? I feel like it's something to do with resolving Promises but my api actually logs everything out correctly. So is it something to do with having API data passed in higher up, in createStore or?:

```<code>import MyData from './MyData'

export default function() {
  return MyData
}
</code>```

答:
The proper way to deal with API requests is to put them inside actions and use some middleware to handle asynchronous functions. I'm not sure what is going on with your API function, but anyway consider this solution:

In componentWillMount call an action which fetches users, example with redux-thunk middleware:

```<code>export function fetchUsers() {
  return async (dispatch) => {
    const { data } = await axios.get('https://jsonplaceholder.typicode.com/users');
    dispatch({
      type: FETCH_USERS,
      payload: data
    });
  }
}
</code>```

Then you won't have a promise in reducer, but json object and you will be able to map the users, but remember that there is a split second when you don't have users to map, so you have to handle this condition to avoid error:

```<code>  createListItems() {
    if(this.props.users.length > 0) {
      return this.props.users.map((user) => {
        return (
          <li
            key={user.id}
            onClick={() => this.props.selectUser(user)}
          >
          {user.name}
          </li>
        )
      })
    } else {
      return <div>Loading...</div>;
    }
  }
</code>```

Body:
Quite new to coding but hitting hurdles with a React/Redux API.

I'm following Bucky Roberts' YouTube tutorial & ive replaced his static names object with an API that i then pull into my reducer.

This logs out the data fine, as an array - but when i try to pull it in to my Container, i get either a map is not a function error (even though it is an array) or if i log out console.log('props: ', this.props) i get [[PromiseValue]] with the array[10] showing.

But i'm pretty sure drilling into that in my component would be a no go.

CONTAINER:

class UserList extends Component {

  createListItems() {
    console.log('props: ', this.props);
    return this.props.users.map((user) => {
      return (

 this.props.selectUser(user)}
          >
          {user.name}

      )
    })
  }

  render() {
    return (

        {this.createListItems()}

    )
  }
}

function mapStateToProps(state) {
  return {
    users: state.users
  }
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators({selectUser: selectUser}, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(UserList);

API:

const MyData = fetch('https://jsonplaceholder.typicode.com/users')
  .then(function(data1) {
    return data1.json()
  }).then(function(data2) {
    return data2
  }).then(function(data3) {
    console.log('API RESPONSE: ', data3)
    return data3
  })

export default MyData;

MyData is then pulled into a reducer, then into combineReducers({}) and the data should show back in mapStateToProps as above in the container. What Am I Doing Wrong? I feel like it's something to do with resolving Promises but my api actually logs everything out correctly. So is it something to do with having API data passed in higher up, in createStore or?:

import MyData from './MyData'

export default function() {
  return MyData
}

Body:
The proper way to deal with API requests is to put them inside actions and use some middleware to handle asynchronous functions. I'm not sure what is going on with your API function, but anyway consider this solution:

In componentWillMount call an action which fetches users, example with redux-thunk middleware:

export function fetchUsers() {
  return async (dispatch) => {
    const { data } = await axios.get('https://jsonplaceholder.typicode.com/users');
    dispatch({
      type: FETCH_USERS,
      payload: data
    });
  }
}

Then you won't have a promise in reducer, but json object and you will be able to map the users, but remember that there is a split second when you don't have users to map, so you have to handle this condition to avoid error:

  createListItems() {
    if(this.props.users.length > 0) {
      return this.props.users.map((user) => {
        return (
          <li
            key={user.id}
            onClick={() => this.props.selectUser(user)}
          >
          {user.name}
          </li>
        )
      })
    } else {
      return <div>Loading...</div>;
    }
  }


来源: stackexchange

问:
extracting a word (of variable length) ending with 동 from a string in R
I have a data frame in R with one column containing an address in Korean. I need to extract one of the words (a word ending with 동), if it's there (it's possible that it's missing) and create a new column named "dong" that will contain this word. So my data is shown in column "address" and desired output is shown in column "dong" shown below.

```<code>address <- c("대전광역시 서구 탄방동 홈플러스","대전광역시 동구 효동 주민센터","대전광역시 대덕구 오정동 한남마트","대전광역시 동구 자양동 87-3번지 성동경로당","대전광역시 유성구 용계로 128")
dong <- c("탄방동","효동","오정동","자양동",NA)
data <- data.frame(address,dong, stringsAsFactors = FALSE)
</code>```

I've tried using grep but it's not giving me exactly what I need.

```<code>grep(".+동\\s",data$address,value=T)
</code>```

I think I have 2 issues: 1) I'm not sure how to write a proper regular expression to identify the word I need and 2) I'm not sure why grep returns the whole string rather than the word. I would appreciate any suggestions.

答:
grep returns the whole string.  In your case, stringr library is useful.

```<code>library(stringr)
str_match(paste0(data$address, ' '), '([^\\s]+동)\\s')
     [,1]      [,2]
[1,] "탄방동 " "탄방동"
[2,] "효동 "   "효동"
[3,] "오정동 " "오정동"
[4,] "자양동 " "자양동"
[5,] NA        NA
</code>```

The column 2 is what you want.  Note that I added a space at the end of strings so that regex would match if "dong" appears at the end of string.

ContentLicense: CC BY-SA 3.0

Body:
I have a data frame in R with one column containing an address in Korean. I need to extract one of the words (a word ending with 동), if it's there (it's possible that it's missing) and create a new column named "dong" that will contain this word. So my data is shown in column "address" and desired output is shown in column "dong" shown below.

address <- c("대전광역시 서구 탄방동 홈플러스","대전광역시 동구 효동 주민센터","대전광역시 대덕구 오정동 한남마트","대전광역시 동구 자양동 87-3번지 성동경로당","대전광역시 유성구 용계로 128")
dong <- c("탄방동","효동","오정동","자양동",NA)
data <- data.frame(address,dong, stringsAsFactors = FALSE)

I've tried using grep but it's not giving me exactly what I need.

grep(".+동\\s",data$address,value=T)

I think I have 2 issues: 1) I'm not sure how to write a proper regular expression to identify the word I need and 2) I'm not sure why grep returns the whole string rather than the word. I would appreciate any suggestions.

Body:
grep returns the whole string.  In your case, stringr library is useful.

library(stringr)
str_match(paste0(data$address, ' '), '([^\\s]+동)\\s')
     [,1]      [,2]
[1,] "탄방동 " "탄방동"
[2,] "효동 "   "효동"
[3,] "오정동 " "오정동"
[4,] "자양동 " "자양동"
[5,] NA        NA

The column 2 is what you want.  Note that I added a space at the end of strings so that regex would match if "dong" appears at the end of string.


问:
PHPDoc for "casted" return type
I have some kind of factory where a method returns one of multiple possible classes but they all inherit the same parent class. The factory method returns always the same class when it gets the same parameter. So when I receive a class from the factory method I know the subclass beside the common parent class.

The problem is that PhpStorm shows me a warning when I try to set the @return type to the child class.

Here an example:

abstract class Base {}
class A extends Base {}
class B extends Base {}

class T {
    /**
     * @param string $class
     * @return Base
     */
    public function returnBase($class)
    {
        switch ($class) {
            case 'A':
                return new A();
                break;
            // ... more cases ...
            default:
                return new B();
        }
    }
    /**
     * @return A
     */
    public function test()
    {
        return $this->returnBase('A'); // Warning: "Return value is expected to be 'A', 'Base' returned"
    }
}
```

I know in this example I could set the return type of returnBase() to A|B, but in my actual code I have much more classes. I don't want to set the return type of the test() method to "Base" because the subclass might have unique methods/properties.

答:
You can set a varibale type for each returnBase() method like this :

```<code>/**
 * @return A
 */
public function test()
{
    /** @var A $a */
    $a =  $this->returnBase('A');
    return $a;
}
</code>```

Accroding to this article about  PHP’s Garbage Collection, a redundant variable doesn't have any impact on memory consumtion.

Title: PHPDoc for "casted" return type

Body:
I have some kind of factory where a method returns one of multiple possible classes but they all inherit the same parent class. The factory method returns always the same class when it gets the same parameter. So when I receive a class from the factory method I know the subclass beside the common parent class.

The problem is that PhpStorm shows me a warning when I try to set the @return type to the child class.

Here an example:

abstract class Base {}
class A extends Base {}
class B extends Base {}

class T {
    /**
     * @param string $class
     * @return Base
     */
    public function returnBase($class)
    {
        switch ($class) {
            case 'A':
                return new A();
                break;
            // ... more cases ...
            default:
                return new B();
        }
    }
    /**
     * @return A
     */
    public function test()
    {
        return $this->returnBase('A'); // Warning: "Return value is expected to be 'A', 'Base' returned"
    }
}

I know in this example I could set the return type of returnBase() to A|B, but in my actual code I have much more classes. I don't want to set the return type of the test() method to "Base" because the subclass might have unique methods/properties.

Body:
You can set a varibale type for each returnBase() method like this :

/**
 * @return A
 */
public function test()
{
    /** @var A $a */
    $a =  $this->returnBase('A');
    return $a;
}

Accroding to this article about  PHP’s Garbage Collection, a redundant variable doesn't have any impact on memory consumtion.


问:
add margin-top and bottom on a div in a table with mpdf
I am facing a problem when i try to add the margin-top or margin-bottom on div elements inside a table for generating pdf with mpdf.

I have something like this:

```<code><table>
<tr>
    <td>
        <div style="margin-top: 20px;">Element1</div>
        <div style="margin-top: 20px;">Element2</div>
        ...
    </td>

    <td>
        <div style="margin-top: 20px;">Element4</div>
        <div style="margin-top: 20px;">Element5</div>
        ...
    </td>
</tr>
</table>
</code>```

The margin styles are not converted.

I think it could be because there are too many nested elements and mpdf doesnt support them in some cases. Have someone already achieved such a problem?

答:
Finally i have found another way to achieve this without using margin style.
 I have just used the simple tag
 to create space between my elements.

```<code><table>
<tr>
<td>
    <br><br>
    <div>Element1</div>
    <br><br>
    <div>Element2</div>
    ...
</td>

<td>
    <br><br>
    <div>Element4</div>
    <br><br>
    <div>Element5</div>
    ...
</td>
</tr>
</table>
</code>```

Mpdf has some limitations in CSS. Sometimes to achieve some tasks we have to think another way. Thanks.

Body:
I am facing a problem when i try to add the margin-top or margin-bottom on div elements inside a table for generating pdf with mpdf.

I have something like this:

Element1

Element2

        ...

Element4

Element5

        ...

The margin styles are not converted.

I think it could be because there are too many nested elements and mpdf doesnt support them in some cases. Have someone already achieved such a problem?

Body:
Finally i have found another way to achieve this without using margin style.
 I have just used the simple tag <br> to create space between my elements.

<table>
<tr>
<td>
    <br><br>
    <div>Element1</div>
    <br><br>
    <div>Element2</div>
    ...
</td>

<td>
    <br><br>
    <div>Element4</div>
    <br><br>
    <div>Element5</div>
    ...
</td>
</tr>
</table>

Mpdf has some limitations in CSS. Sometimes to achieve some tasks we have to think another way. Thanks.


问:
How to format a number using comma as thousands separator in C?
In C, how can I format a large number from e.g. 1123456789 to 1,123,456,789?

I tried using printf("%'10d\n", 1123456789), but that doesn't work.

Could you advise anything? The simpler the solution the better.

答:
I'm new in C programming. Here is my simple code.</p>

```<code>int main()
{
    //  1223 => 1,223
    int n;
    int a[10];
    printf(" n: ");
    scanf_s("%d", &n);
    int i = 0;
    while (n > 0)
    {
        int temp = n % 1000;
        a[i] = temp;
        n /= 1000;
        i++;
    }
    for (int j = i - 1; j >= 0; j--)
    {
        if (j == 0)
        {
            printf("%d.", a[j]);
        }
        else printf("%d,",a[j]);
    }
    getch();
    return 0;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm new in C programming. Here is my simple code.

int main()
{
    //  1223 => 1,223
    int n;
    int a[10];
    printf(" n: ");
    scanf_s("%d", &n);
    int i = 0;
    while (n > 0)
    {
        int temp = n % 1000;
        a[i] = temp;
        n /= 1000;
        i++;
    }
    for (int j = i - 1; j >= 0; j--)
    {
        if (j == 0)
        {
            printf("%d.", a[j]);
        }
        else printf("%d,",a[j]);
    }
    getch();
    return 0;
}


问:
jQuery on click event partially working
```<code>var sideBarAndWrapper = $("#Sidebar,#Wrapper");

$("#SidebarToggle").on("click", function ()
{
    sideBarAndWrapper.toggleClass("hide-sidebar");

    if (sideBarAndWrapper.hasClass("hide-sidebar")) $(this).text("Show Sidebar");
    else $(this).text("Hide Sidebar");
});
</code>```

So the sideBarAndWrapper var toggles the class when clicking on "SidebarToggle", yet it doesn't do anything on the if-else statement.

I tried setting an alarm instead of the changing text instruction still nothing.
I also tried setting an alarm outside the if-else statement to see if it works on "SidebarToggle" click and nothing happens.

Click event doesn't do anything more than creating/removing the class.

答:
UPDATE

Updating my answer with working code/full example:

HTML

```<code><div id="sidebar">sidebar</div>
<div id="wrapper">wrapper</div>

<button>click</button>

<p id="fill-me"></p>
</code>```

jQuery

```<code>var $sideBarAndWrapper = $("#sidebar,#wrapper");

$('button').click(function(e) {
  e.preventDefault();
  e.stopPropagation();

  $sideBarAndWrapper.toggleClass('hide-sidebar');

  if ($sideBarAndWrapper.hasClass('hide-sidebar')) {
    $('#fill-me').empty().text('show sidebar');
  } else {
    $('#fill-me').empty().text('hide sidebar');
  }
});
</code>```

Although I agree with mplungjan, and you should be selecting your elements in a more effective way, it works if you write your if/else statement correctly.

```<code>if (sideBarAndWrapper.hasClass("hide-sidebar")) {
    $(this).text("Show Sidebar");
} else {
    $(this).text("Hide Sidebar");
}
</code>```

Here is an excellent place to start on the basics, written and published by Rebecca Murphey

Title: jQuery on click event partially working

Body:
var sideBarAndWrapper = $("#Sidebar,#Wrapper");

$("#SidebarToggle").on("click", function ()
{
    sideBarAndWrapper.toggleClass("hide-sidebar");

    if (sideBarAndWrapper.hasClass("hide-sidebar")) $(this).text("Show Sidebar");
    else $(this).text("Hide Sidebar");
});

So the sideBarAndWrapper var toggles the class when clicking on "SidebarToggle", yet it doesn't do anything on the if-else statement.

I tried setting an alarm instead of the changing text instruction still nothing.
I also tried setting an alarm outside the if-else statement to see if it works on "SidebarToggle" click and nothing happens.

Click event doesn't do anything more than creating/removing the class.

Body:
UPDATE

Updating my answer with working code/full example:

HTML

<div id="sidebar">sidebar</div>
<div id="wrapper">wrapper</div>

<button>click</button>

<p id="fill-me"></p>

jQuery

var $sideBarAndWrapper = $("#sidebar,#wrapper");

$('button').click(function(e) {
  e.preventDefault();
  e.stopPropagation();

  $sideBarAndWrapper.toggleClass('hide-sidebar');

  if ($sideBarAndWrapper.hasClass('hide-sidebar')) {
    $('#fill-me').empty().text('show sidebar');
  } else {
    $('#fill-me').empty().text('hide sidebar');
  }
});

Although I agree with mplungjan, and you should be selecting your elements in a more effective way, it works if you write your if/else statement correctly.

if (sideBarAndWrapper.hasClass("hide-sidebar")) {
    $(this).text("Show Sidebar");
} else {
    $(this).text("Hide Sidebar");
}

Here is an excellent place to start on the basics, written and published by Rebecca Murphey


问:
Functional way to take element in a list until a limit in Scala
The aim of the method is to take elements in a list until a limit is reached.

e.g.

I've come up with 2 different implementations

```<code>def take(l: List[Int], limit: Int): List[Int] = {
  var sum = 0
  l.takeWhile { e =>
    sum += e
    sum <= limit
  }
}
</code>```

It is straightforward, but a mutable state is used.

```<code>def take(l: List[Int], limit: Int): List[Int] = {
  val summed = l.toStream.scanLeft(0) { case (e, sum) => sum + e }
  l.take(summed.indexWhere(_ > limit) - 1)
}
</code>```

It seems cleaner, but it's more verbose and perhaps less memory efficient because a stream is needed.

Is there a better way ?

答:
if you want to extend your own customize way, you could also use something like:

```<code>def custom(con: => Boolean)(i: Int)(a: => List[Int])(body: => Unit): List[Int] = {
      if (con) {
        body
        custom(con)(i + 1)(a)(body)
      }
      else {
        a.slice(0, i)
      }
    }
</code>```

then call it like this:

```<code>var j = 100
    val t = customTake(j > 80)(0)((0 to 99).toList) {
      j -= 1
    }
    println(t)
</code>```

Body:
The aim of the method is to take elements in a list until a limit is reached.

e.g.

I've come up with 2 different implementations

def take(l: List[Int], limit: Int): List[Int] = {
  var sum = 0
  l.takeWhile { e =>
    sum += e
    sum <= limit
  }
}

It is straightforward, but a mutable state is used.

def take(l: List[Int], limit: Int): List[Int] = {
  val summed = l.toStream.scanLeft(0) { case (e, sum) => sum + e }
  l.take(summed.indexWhere(_ > limit) - 1)
}

It seems cleaner, but it's more verbose and perhaps less memory efficient because a stream is needed.

Is there a better way ?

Body:
if you want to extend your own customize way, you could also use something like:

def custom(con: => Boolean)(i: Int)(a: => List[Int])(body: => Unit): List[Int] = {
      if (con) {
        body
        custom(con)(i + 1)(a)(body)
      }
      else {
        a.slice(0, i)
      }
    }

then call it like this:

var j = 100
    val t = customTake(j > 80)(0)((0 to 99).toList) {
      j -= 1
    }
    println(t)


问:
sql query needs input from another table
I have a database where i want the data from two tables, they look something like this:

```<code>categories:    entries:
+----+------+  +----+-------------+-------+-------------+
| id | name |  | ID | category_id | title | description |
+----+------+  +----+-------------+-------+-------------+
|  1 |  foo |  |  1 |      1      |  bar  | Loreum ip.. |
+----+------+  +----+-------------+-------+-------------+
</code>```

I want to get info from entries, and my input will just be category name and entry title. It does obviously work if i use two statements. something like:

```<code>SELECT `id` FROM `categories` WHERE `name` = 'foo' LIMIT 1;
SELECT `ID`, `category_id`, `title`, `description` FROM `entries` WHERE `title` = 'bar' AND `category_id` = $cat_id LIMIT 1;
</code>```

Where $cat_id is the output from the first entry. But i want to combine these to into one statement, and i don't find join useful here? So my question is basically how can i combine these into one query?

答:
You can join the two tables together and filter as you need.

```<code>select e.*
from entries e
join categories c on e.category_id = c.id
where e.title = 'bar'
    and c.name = 'foo'
order by ??  -- important when using "limit"
limit 1;
</code>```

Also, to get consistent one row, you should add an order by clause with proper column(s) to the query. If you want just any one row, then you may use without it.

To exactly do what you are doing, you can use subquery:

```<code>select *
from entries
where category_id in (
        select id
        from categories
        where name = 'foo'
        limit 1
        )
    and title = 'bar'
    limit 1;
</code>```

But remember that without order by clause, you may get inconsistent results from limit.

Body:
I have a database where i want the data from two tables, they look something like this:

categories:    entries:
+----+------+  +----+-------------+-------+-------------+
| id | name |  | ID | category_id | title | description |
+----+------+  +----+-------------+-------+-------------+
|  1 |  foo |  |  1 |      1      |  bar  | Loreum ip.. |
+----+------+  +----+-------------+-------+-------------+

I want to get info from entries, and my input will just be category name and entry title. It does obviously work if i use two statements. something like:

SELECT `id` FROM `categories` WHERE `name` = 'foo' LIMIT 1;
SELECT `ID`, `category_id`, `title`, `description` FROM `entries` WHERE `title` = 'bar' AND `category_id` = $cat_id LIMIT 1;

Where $cat_id is the output from the first entry. But i want to combine these to into one statement, and i don't find join useful here? So my question is basically how can i combine these into one query?

Body:
You can join the two tables together and filter as you need.

select e.*
from entries e
join categories c on e.category_id = c.id
where e.title = 'bar'
    and c.name = 'foo'
order by ??  -- important when using "limit"
limit 1;

Also, to get consistent one row, you should add an order by clause with proper column(s) to the query. If you want just any one row, then you may use without it.

To exactly do what you are doing, you can use subquery:

select *
from entries
where category_id in (
        select id
        from categories
        where name = 'foo'
        limit 1
        )
    and title = 'bar'
    limit 1;

But remember that without order by clause, you may get inconsistent results from limit.


问:
Duplicate symbol error when adding NSManagedObject subclass, duplicate link
I was trying to create NSManagedObject subclasses (2 related entities) automatically in Xcode. They are generated like this:

However, before I do anything further, when I tried to build and run it, a link error occur, as shown:

duplicate symbol _OBJC_CLASS_$_Photo in:
    /Users/Kefeng/Library/Developer/Xcode/DerivedData/Photomania-aellrakjngugnzcgrleiytvrfvyt/Build/Intermediates/Photomania.build/Debug-iphonesimulator/Photomania.build/Objects-normal/x86_64/Photo+CoreDataClass.o
duplicate symbol _OBJC_METACLASS_$_Photo in:
    /Users/Kefeng/Library/Developer/Xcode/DerivedData/Photomania-aellrakjngugnzcgrleiytvrfvyt/Build/Intermediates/Photomania.build/Debug-iphonesimulator/Photomania.build/Objects-normal/x86_64/Photo+CoreDataClass.o
duplicate symbol _OBJC_CLASS_$_Photography in:
    /Users/Kefeng/Library/Developer/Xcode/DerivedData/Photomania-aellrakjngugnzcgrleiytvrfvyt/Build/Intermediates/Photomania.build/Debug-iphonesimulator/Photomania.build/Objects-normal/x86_64/Photography+CoreDataClass.o
duplicate symbol _OBJC_METACLASS_$_Photography in:
    /Users/Kefeng/Library/Developer/Xcode/DerivedData/Photomania-aellrakjngugnzcgrleiytvrfvyt/Build/Intermediates/Photomania.build/Debug-iphonesimulator/Photomania.build/Objects-normal/x86_64/Photography+CoreDataClass.o
ld: 4 duplicate symbols for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

I tried several times by creating new projects and do the same thing. My original intention is to add some custom methods into those to subclasses. But when I add anything into e.g. Photo+CoreData.h/m, the same error as above showed up.

I found some answers about the "double include" or "save files to the wrong directory", but I didn't do that. Anybody have any idea about this?

答: You should delete all these entities, change "Codegen" settings to "Manual/None" for them in Data Model Inspector, and generate entities again. It works good! You don't need to remove +CoreDataClass.h files from Compile Source. You don't need to mark entities as abstract. You don't need to generate classes by yourself. You should change only "Codegen" settings and regenerate entities automatically.


问:
AccessViolationException in Gl.DrawArrays
I am using OpenGL.net (Available through NuGet) with C# and I am trying to put together a minimal working example for modern OpenGL.

Clearing the screen and Shader Conpilation works, however I am getting an AccessViolationException in the Gl.DrawArrays call on line 158.

What I have done so far:

Reassured Vertex Data is uploaded

Checked the count argument in Gl.DrawArrays is correct

Checked Shaders are correct and compiled

Checked Size Arguments are correct everywhere

Gone through the first few pages of google links on the error  message in context with OpenGL and c#

Code:

```<code>using System;
using System.Text;
using System.Windows.Forms;
using System.IO;
using OpenGL;
using System.Runtime.ExceptionServices;

namespace RenderEngine
{
    public class RenderForm : Form
    {
        private Timer tmr_Render;
        private System.ComponentModel.IContainer components;
        private GlControl glc_screen;
        MemoryLock vertexArrayLock;
        uint vertexArrayID;
        uint vertexbuffer;
        uint shaderProgram;
        private static readonly float[] _ArrayPosition = new float[] {
            0.0f, 0.0f,
            0.5f, 1.0f,
            1.0f, 0.0f
        };

        private static readonly float[] _ArrayColor = new float[] {
            1.0f, 0.0f, 0.0f,
            0.0f, 1.0f, 0.0f,
            0.0f, 0.0f, 1.0f
        };

        public RenderForm()
        {
            InitializeComponent();
        }

        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            this.glc_screen = new OpenGL.GlControl();
            this.tmr_Render = new System.Windows.Forms.Timer(this.components);
            this.SuspendLayout();
            //
            // glc_screen
            //
            this.glc_screen.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            this.glc_screen.ColorBits = ((uint)(24u));
            this.glc_screen.DepthBits = ((uint)(0u));
            this.glc_screen.Dock = System.Windows.Forms.DockStyle.Fill;
            this.glc_screen.Location = new System.Drawing.Point(0, 0);
            this.glc_screen.MultisampleBits = ((uint)(0u));
            this.glc_screen.Name = "glc_screen";
            this.glc_screen.Size = new System.Drawing.Size(784, 561);
            this.glc_screen.StencilBits = ((uint)(0u));
            this.glc_screen.TabIndex = 0;
            this.glc_screen.ContextCreated += new System.EventHandler<OpenGL.GlControlEventArgs>(this.glc_screen_ContextCreated);
            this.glc_screen.Render += new System.EventHandler<OpenGL.GlControlEventArgs>(this.glc_screen_Render);
            //
            // tmr_Render
            //
            this.tmr_Render.Enabled = true;
            this.tmr_Render.Interval = 16;
            this.tmr_Render.Tick += new System.EventHandler(this.tmr_Render_Tick);
            //
            // RenderForm
            //
            this.ClientSize = new System.Drawing.Size(784, 561);
            this.Controls.Add(this.glc_screen);
            this.Name = "RenderForm";
            this.ResumeLayout(false);

        }

        private void glc_screen_ContextCreated(object sender, GlControlEventArgs e)
        {
            GlControl glControl = (GlControl)sender;

            shaderProgram = LoadShaders("../../../RenderEngine/vertex.shader", "../../../RenderEngine/fragment.shader");

            vertexArrayID = Gl.GenVertexArray();
            Gl.BindVertexArray(vertexArrayID);
            Gl.EnableVertexAttribArray(vertexArrayID);

            vertexArrayLock = new MemoryLock(_ArrayPosition);
            vertexbuffer = Gl.GenBuffer();
            Gl.BindBuffer(BufferTargetARB.ArrayBuffer, vertexbuffer);
            Gl.BufferData(BufferTargetARB.ArrayBuffer, /*sizeof(float)*(uint)_ArrayPosition.Length*/ 100, vertexArrayLock.Address, BufferUsageARB.DynamicDraw);
            int indexInShader = 0;// Gl.GetAttribLocation(shaderProgram, "vertexPosition_modelspace");
            int floatsPerVertex = 2;
            bool normalized = false;
            int stride = floatsPerVertex*sizeof(float);
            int arrayBufferOffset = 0;
            Gl.VertexAttribPointer((uint)indexInShader, floatsPerVertex, Gl.FLOAT, normalized, stride, arrayBufferOffset);
            Gl.BindBuffer(BufferTargetARB.ArrayBuffer, 0);
        }

        private uint LoadShaders(string vertexPath, string fragmentPath) {
            uint vertexShaderId = Gl.CreateShader(Gl.VERTEX_SHADER);
            uint fragmentShaderId = Gl.CreateShader(Gl.FRAGMENT_SHADER);

            string vertexCode = File.ReadAllText(vertexPath);
            string fragmentCode = File.ReadAllText(fragmentPath);

            int vertexResult;
            int vertexInfoLogLength;
            StringBuilder vertexInfoLog = new StringBuilder(200);
            Gl.ShaderSource(vertexShaderId, new string[] { vertexCode }/*vertexCode.Split(new char[] { '\r', '\n' })*/);
            Gl.CompileShader(vertexShaderId);
            Gl.GetShader(vertexShaderId, Gl.COMPILE_STATUS, out vertexResult);
            Gl.GetShaderInfoLog(vertexShaderId, 200, out vertexInfoLogLength, vertexInfoLog);
            Console.WriteLine(vertexInfoLog.Length == 0 ? "Vertex shader compiled sucessfully" : vertexInfoLog.ToString());

            int fragmentResult;
            int fragmentInfoLogLength;
            StringBuilder fragmentInfoLog = new StringBuilder(200);
            Gl.ShaderSource(fragmentShaderId, new string[] { fragmentCode }/*fragmentCode.Split(new char[] { '\r', '\n' })*/);
            Gl.CompileShader(fragmentShaderId);
            Gl.GetShader(fragmentShaderId, Gl.COMPILE_STATUS, out fragmentResult);
            Gl.GetShaderInfoLog(fragmentShaderId, 200, out fragmentInfoLogLength, fragmentInfoLog);
            Console.WriteLine(fragmentInfoLog.Length==0 ? "Fragment shader compiled sucessfully" : fragmentInfoLog.ToString());

            uint programId = Gl.CreateProgram();
            Gl.AttachShader(programId, vertexShaderId);
            Gl.AttachShader(programId, fragmentShaderId);
            Gl.LinkProgram(programId);
            int programResult;
            int programInfoLogLength;
            StringBuilder programInfoLog = new StringBuilder(200);
            Gl.GetProgram(programId, Gl.LINK_STATUS, out programResult);
            Gl.GetProgramInfoLog(programId, 200, out programInfoLogLength, programInfoLog);
            Console.WriteLine(programInfoLog.Length == 0 ? "Program linked sucessfully" : programInfoLog.ToString());

            Gl.DetachShader(programId, vertexShaderId);
            Gl.DetachShader(programId, fragmentShaderId);

            Gl.DeleteShader(vertexShaderId);
            Gl.DeleteShader(fragmentShaderId);

            return programId;
        }

        private void glc_screen_Render(object sender, GlControlEventArgs e)
        {
            GlControl senderControl = (GlControl)sender;

            Gl.BindVertexArray(vertexArrayID);
            Gl.BindBuffer(BufferTargetARB.ArrayBuffer, vertexbuffer);

            Gl.CheckErrors();
            Console.WriteLine(Gl.GetError());
            int floatsPerVertex = 2;
            int start = 0;
            int verticies = _ArrayPosition.Length / floatsPerVertex;
            Gl.Clear(ClearBufferMask.ColorBufferBit);
            Gl.ClearColor(1f, .5f, 1f, 0f);
            Gl.UseProgram(shaderProgram);
            Gl.DrawArrays(PrimitiveType.Triangles, start, verticies);

            Gl.DisableVertexAttribArray(vertexArrayID);
        }

        private void tmr_Render_Tick(object sender, EventArgs e)
        {
            glc_screen.Invalidate();
        }
    }
}
</code>```

Vertex Shader:

```<code>#version 330 core
layout(location = 0) in vec2 vertexPosition_modelspace;
void main() {
    gl_Position.xy = vertexPosition_modelspace;
    gl_Position.z = 1.0;
    gl_Position.w = 1.0;
}
</code>```

Fragment Shader:

```<code>#version 330 core
out vec4 color;
void main() {
    color = vec4(1, 0, 0, 0);
}
</code>```

I have no clue what is wrong at this point, any help is greatly appreciated.

答:
I suspect that

```<code>Gl.BufferData(BufferTargetARB.ArrayBuffer, /*sizeof(float)*(uint)_ArrayPosition.Length*/ 100, vertexArrayLock.Address, BufferUsageARB.DynamicDraw);
</code>```

is the root of the problem. You are telling to OpenGL to define a buffer of 100 bytes, and initialize the content from vertexArrayLock.Address. Sadly, vertexArrayLock.Address points to a memory large 6 * sizeof(float) = 24 bytes.

However, I don't understand why you're getting exception on DrawArrays; probably there are other issues I didn't see.

--- Few minutes later ---

Got it. Remove the line:

```<code>Gl.BindBuffer(BufferTargetARB.ArrayBuffer, 0);
</code>```

from glc_screen_ContextCreated. It will alter the VAO state in a way that no buffer is used. Focus of VAO state vector, and you'll get a successfull DrawArrays.

Body:
I am using OpenGL.net (Available through NuGet) with C# and I am trying to put together a minimal working example for modern OpenGL.

Clearing the screen and Shader Conpilation works, however I am getting an AccessViolationException in the Gl.DrawArrays call on line 158.

What I have done so far:

Reassured Vertex Data is uploaded

Checked the count argument in Gl.DrawArrays is correct

Checked Shaders are correct and compiled

Checked Size Arguments are correct everywhere

Gone through the first few pages of google links on the error  message in context with OpenGL and c#

Code:

using System;
using System.Text;
using System.Windows.Forms;
using System.IO;
using OpenGL;
using System.Runtime.ExceptionServices;

namespace RenderEngine
{
    public class RenderForm : Form
    {
        private Timer tmr_Render;
        private System.ComponentModel.IContainer components;
        private GlControl glc_screen;
        MemoryLock vertexArrayLock;
        uint vertexArrayID;
        uint vertexbuffer;
        uint shaderProgram;
        private static readonly float[] _ArrayPosition = new float[] {
            0.0f, 0.0f,
            0.5f, 1.0f,
            1.0f, 0.0f
        };

        private static readonly float[] _ArrayColor = new float[] {
            1.0f, 0.0f, 0.0f,
            0.0f, 1.0f, 0.0f,
            0.0f, 0.0f, 1.0f
        };

        public RenderForm()
        {
            InitializeComponent();
        }

        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            this.glc_screen = new OpenGL.GlControl();
            this.tmr_Render = new System.Windows.Forms.Timer(this.components);
            this.SuspendLayout();
            //
            // glc_screen
            //
            this.glc_screen.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            this.glc_screen.ColorBits = ((uint)(24u));
            this.glc_screen.DepthBits = ((uint)(0u));
            this.glc_screen.Dock = System.Windows.Forms.DockStyle.Fill;
            this.glc_screen.Location = new System.Drawing.Point(0, 0);
            this.glc_screen.MultisampleBits = ((uint)(0u));
            this.glc_screen.Name = "glc_screen";
            this.glc_screen.Size = new System.Drawing.Size(784, 561);
            this.glc_screen.StencilBits = ((uint)(0u));
            this.glc_screen.TabIndex = 0;
            this.glc_screen.ContextCreated += new System.EventHandler<OpenGL.GlControlEventArgs>(this.glc_screen_ContextCreated);
            this.glc_screen.Render += new System.EventHandler<OpenGL.GlControlEventArgs>(this.glc_screen_Render);
            //
            // tmr_Render
            //
            this.tmr_Render.Enabled = true;
            this.tmr_Render.Interval = 16;
            this.tmr_Render.Tick += new System.EventHandler(this.tmr_Render_Tick);
            //
            // RenderForm
            //
            this.ClientSize = new System.Drawing.Size(784, 561);
            this.Controls.Add(this.glc_screen);
            this.Name = "RenderForm";
            this.ResumeLayout(false);

        }

        private void glc_screen_ContextCreated(object sender, GlControlEventArgs e)
        {
            GlControl glControl = (GlControl)sender;

            shaderProgram = LoadShaders("../../../RenderEngine/vertex.shader", "../../../RenderEngine/fragment.shader");

            vertexArrayID = Gl.GenVertexArray();
            Gl.BindVertexArray(vertexArrayID);
            Gl.EnableVertexAttribArray(vertexArrayID);

            vertexArrayLock = new MemoryLock(_ArrayPosition);
            vertexbuffer = Gl.GenBuffer();
            Gl.BindBuffer(BufferTargetARB.ArrayBuffer, vertexbuffer);
            Gl.BufferData(BufferTargetARB.ArrayBuffer, /*sizeof(float)*(uint)_ArrayPosition.Length*/ 100, vertexArrayLock.Address, BufferUsageARB.DynamicDraw);
            int indexInShader = 0;// Gl.GetAttribLocation(shaderProgram, "vertexPosition_modelspace");
            int floatsPerVertex = 2;
            bool normalized = false;
            int stride = floatsPerVertex*sizeof(float);
            int arrayBufferOffset = 0;
            Gl.VertexAttribPointer((uint)indexInShader, floatsPerVertex, Gl.FLOAT, normalized, stride, arrayBufferOffset);
            Gl.BindBuffer(BufferTargetARB.ArrayBuffer, 0);
        }

        private uint LoadShaders(string vertexPath, string fragmentPath) {
            uint vertexShaderId = Gl.CreateShader(Gl.VERTEX_SHADER);
            uint fragmentShaderId = Gl.CreateShader(Gl.FRAGMENT_SHADER);

            string vertexCode = File.ReadAllText(vertexPath);
            string fragmentCode = File.ReadAllText(fragmentPath);

            int vertexResult;
            int vertexInfoLogLength;
            StringBuilder vertexInfoLog = new StringBuilder(200);
            Gl.ShaderSource(vertexShaderId, new string[] { vertexCode }/*vertexCode.Split(new char[] { '\r', '\n' })*/);
            Gl.CompileShader(vertexShaderId);
            Gl.GetShader(vertexShaderId, Gl.COMPILE_STATUS, out vertexResult);
            Gl.GetShaderInfoLog(vertexShaderId, 200, out vertexInfoLogLength, vertexInfoLog);
            Console.WriteLine(vertexInfoLog.Length == 0 ? "Vertex shader compiled sucessfully" : vertexInfoLog.ToString());

            int fragmentResult;
            int fragmentInfoLogLength;
            StringBuilder fragmentInfoLog = new StringBuilder(200);
            Gl.ShaderSource(fragmentShaderId, new string[] { fragmentCode }/*fragmentCode.Split(new char[] { '\r', '\n' })*/);
            Gl.CompileShader(fragmentShaderId);
            Gl.GetShader(fragmentShaderId, Gl.COMPILE_STATUS, out fragmentResult);
            Gl.GetShaderInfoLog(fragmentShaderId, 200, out fragmentInfoLogLength, fragmentInfoLog);
            Console.WriteLine(fragmentInfoLog.Length==0 ? "Fragment shader compiled sucessfully" : fragmentInfoLog.ToString());

            uint programId = Gl.CreateProgram();
            Gl.AttachShader(programId, vertexShaderId);
            Gl.AttachShader(programId, fragmentShaderId);
            Gl.LinkProgram(programId);
            int programResult;
            int programInfoLogLength;
            StringBuilder programInfoLog = new StringBuilder(200);
            Gl.GetProgram(programId, Gl.LINK_STATUS, out programResult);
            Gl.GetProgramInfoLog(programId, 200, out programInfoLogLength, programInfoLog);
            Console.WriteLine(programInfoLog.Length == 0 ? "Program linked sucessfully" : programInfoLog.ToString());

            Gl.DetachShader(programId, vertexShaderId);
            Gl.DetachShader(programId, fragmentShaderId);

            Gl.DeleteShader(vertexShaderId);
            Gl.DeleteShader(fragmentShaderId);

            return programId;
        }

        private void glc_screen_Render(object sender, GlControlEventArgs e)
        {
            GlControl senderControl = (GlControl)sender;

            Gl.BindVertexArray(vertexArrayID);
            Gl.BindBuffer(BufferTargetARB.ArrayBuffer, vertexbuffer);

            Gl.CheckErrors();
            Console.WriteLine(Gl.GetError());
            int floatsPerVertex = 2;
            int start = 0;
            int verticies = _ArrayPosition.Length / floatsPerVertex;
            Gl.Clear(ClearBufferMask.ColorBufferBit);
            Gl.ClearColor(1f, .5f, 1f, 0f);
            Gl.UseProgram(shaderProgram);
            Gl.DrawArrays(PrimitiveType.Triangles, start, verticies);

            Gl.DisableVertexAttribArray(vertexArrayID);
        }

        private void tmr_Render_Tick(object sender, EventArgs e)
        {
            glc_screen.Invalidate();
        }
    }
}

Vertex Shader:

#version 330 core
layout(location = 0) in vec2 vertexPosition_modelspace;
void main() {
    gl_Position.xy = vertexPosition_modelspace;
    gl_Position.z = 1.0;
    gl_Position.w = 1.0;
}

Fragment Shader:

#version 330 core
out vec4 color;
void main() {
    color = vec4(1, 0, 0, 0);
}

I have no clue what is wrong at this point, any help is greatly appreciated.

Body:
I suspect that

Gl.BufferData(BufferTargetARB.ArrayBuffer, /*sizeof(float)*(uint)_ArrayPosition.Length*/ 100, vertexArrayLock.Address, BufferUsageARB.DynamicDraw);

is the root of the problem. You are telling to OpenGL to define a buffer of 100 bytes, and initialize the content from vertexArrayLock.Address. Sadly, vertexArrayLock.Address points to a memory large 6 * sizeof(float) = 24 bytes.

However, I don't understand why you're getting exception on DrawArrays; probably there are other issues I didn't see.

--- Few minutes later ---

Got it. Remove the line:

Gl.BindBuffer(BufferTargetARB.ArrayBuffer, 0);

from glc_screen_ContextCreated. It will alter the VAO state in a way that no buffer is used. Focus of VAO state vector, and you'll get a successfull DrawArrays.


问:
Intents on implements View.onClickListener null object reference
Hi I have alot of buttons on my application and I'm trying to keep it tidy by setting a View.Onclicklistener inside of another class and then linking it back. But the problem I'm having is that if I setup any intents from this other class then my app crashes and I get a null object reference. any ideas as to why, because this can be any intent.

Example of one of the intents I'm trying to implement.

```<code>Button btnContacts = (Button)promptsView.findViewById(R.id.btnContacts);

    btnContacts.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            final Uri uriContact = ContactsContract.Contacts.CONTENT_URI;
            Intent intentPickContact = new Intent(Intent.ACTION_PICK, uriContact);
            startActivityForResult(intentPickContact, REQUEST_CODE_PICK_CONTACTS);

        }
    });
</code>```

Remember this is inside of another class I built which I then reference back to call the onclick listener e.g. btnContacts.setOnClickListener(new onClickListenerName);

Error message

java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.ActivityThread$ApplicationThread android.app.ActivityThread.getApplicationThread()' on a null object reference
at android.app.Activity.startActivityForResult(Activity.java:3942)
                                                                                at android.app.Activity.startActivityForResult(Activity.java:3889)
                                                                                at thedeveloperslounge.projectr.AlarmListViewOnClick.AlarmText.AlarmContactNumber$1.onClick(AlarmContactNumber.java:83)

答:
Hello Just for a update..

In order to fix the current problem I replaced the View.onClickListener completely with a DialogFragment which I can the implement my methods on. All my code for getting contact information is working great now.

ANSWER: BUILD A DIALOG FRAGMENT

Thanks

Body:
Hi I have alot of buttons on my application and I'm trying to keep it tidy by setting a View.Onclicklistener inside of another class and then linking it back. But the problem I'm having is that if I setup any intents from this other class then my app crashes and I get a null object reference. any ideas as to why, because this can be any intent.

Example of one of the intents I'm trying to implement.

Button btnContacts = (Button)promptsView.findViewById(R.id.btnContacts);

    btnContacts.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            final Uri uriContact = ContactsContract.Contacts.CONTENT_URI;
            Intent intentPickContact = new Intent(Intent.ACTION_PICK, uriContact);
            startActivityForResult(intentPickContact, REQUEST_CODE_PICK_CONTACTS);

        }
    });

Remember this is inside of another class I built which I then reference back to call the onclick listener e.g. btnContacts.setOnClickListener(new onClickListenerName);

Error message

java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.ActivityThread$ApplicationThread android.app.ActivityThread.getApplicationThread()' on a null object reference
at android.app.Activity.startActivityForResult(Activity.java:3942)
                                                                                at android.app.Activity.startActivityForResult(Activity.java:3889)
                                                                                at thedeveloperslounge.projectr.AlarmListViewOnClick.AlarmText.AlarmContactNumber$1.onClick(AlarmContactNumber.java:83)


问:
What's the difference between function and function() in C#?
For example,
    Thread t = new Thread(function);
Why not
    Thread t = new Thread(function());
Thank you.

答:
function is just the "function" variable

function() evaluates it, and you're passing its return value as parameter to the thread constructor


问:
How find a summ of days?
I have a table in SQL Server 2008 with data below:

```<code>organization , number of request, date number of request
organization1, ID1139151,         2017-03-15 13:10:01.000
organization1, ID1139152,         2017-03-15 14:31:05.000
organization2, ID1139153,         2017-03-16 10:38:08.000
organization2, ID1139154,         2017-03-16 09:26:04.000
organization2, ID1139155,         2017-03-16 18:09:15.000
organization2, ID1139156,         2017-03-16 20:14:29.000
organization3, ID1139157,         2017-03-23 11:18:18.000
</code>```

Help me to find a summ of days by every organization with help of SQL query.

Result:

```<code>organization , date number of request
organization1, 2
organization2, 4
organization3, 1
</code>```

Thank you!

```<code>CREATE TABLE Mytable (

   [organization] varchar(50) NOT NULL,

   [number of request] varchar(15) NOT NULL,

   [date_number_of_request] datetime NOT NULL,
     )

INSERT INTO Mytable

VALUES

('organization1','ID1139151','2017-03-15 13:10:01.000'),

('organization1','ID1139152','2017-03-15 14:31:05.000'),

('organization2','ID1139153','2017-03-16 10:38:08.000'),

('organization2','ID1139154','2017-03-16 09:26:04.000'),

('organization2','ID1139155','2017-03-16 18:09:15.000'),

('organization2','ID1139156','2017-03-16 20:14:29.000'),

('organization3','ID1139157','2017-03-23 11:18:18.000');
</code>```

答:
Unless I'm missing something, a simple group by would do what you need:

```<code>SELECT  organization,
        COUNT([date_number_of_request]) As [date number of request]
FROM Mytable
GROUP BY organization
</code>```

Result:

```<code>organization , date number of request
organization1, 2
organization2, 4
organization3, 1
</code>```

Title: How find a summ of days?

Body:
I have a table in SQL Server 2008 with data below:

organization , number of request, date number of request
organization1, ID1139151,         2017-03-15 13:10:01.000
organization1, ID1139152,         2017-03-15 14:31:05.000
organization2, ID1139153,         2017-03-16 10:38:08.000
organization2, ID1139154,         2017-03-16 09:26:04.000
organization2, ID1139155,         2017-03-16 18:09:15.000
organization2, ID1139156,         2017-03-16 20:14:29.000
organization3, ID1139157,         2017-03-23 11:18:18.000

Help me to find a summ of days by every organization with help of SQL query.

Result:

organization , date number of request
organization1, 2
organization2, 4
organization3, 1

Thank you!

CREATE TABLE Mytable (

   [organization] varchar(50) NOT NULL,

   [number of request] varchar(15) NOT NULL,

   [date_number_of_request] datetime NOT NULL,
     )

INSERT INTO Mytable

VALUES

('organization1','ID1139151','2017-03-15 13:10:01.000'),

('organization1','ID1139152','2017-03-15 14:31:05.000'),

('organization2','ID1139153','2017-03-16 10:38:08.000'),

('organization2','ID1139154','2017-03-16 09:26:04.000'),

('organization2','ID1139155','2017-03-16 18:09:15.000'),

('organization2','ID1139156','2017-03-16 20:14:29.000'),

('organization3','ID1139157','2017-03-23 11:18:18.000');

Body:
Unless I'm missing something, a simple group by would do what you need:

SELECT  organization,
        COUNT([date_number_of_request]) As [date number of request]
FROM Mytable
GROUP BY organization

Result:

organization , date number of request
organization1, 2
organization2, 4
organization3, 1


问:
How can I clear console
As in the title. How can I clear console in C++?</p>

答:
```<code>#include <cstdlib>

void cls(){
#if defined(_WIN32) //if windows
    system("cls");

#else
    system("clear");    //if other
#endif  //finish
</code>```

}

The just call cls() anywhere

Title: How can I clear console

Body:
#include <cstdlib>

void cls(){
#if defined(_WIN32) //if windows
    system("cls");

#else
    system("clear");    //if other
#endif  //finish

}

The just call cls() anywhere


问:
Explicitly choose which template overload should be used
Can we chose which function template overload should be used in this case?

```<code>struct X { };

struct A { A(X){} };
struct B { B(X){} };

template<class T>
void fun(T, A) { }

template<class T>
void fun(T, B) { }

int main() {
    /* explicitly choose overload */ fun(1, X());
}
</code>```

Error:

```<code>error: call of overloaded 'fun(int, X)' is ambiguous
     /* explicitly choose overload */ fun(1, X());
                                                ^
    candidate: void fun(T, A) [with T = int]
 void fun(T, A) { }
      ^~~
    candidate: void fun(T, B) [with T = int]
 void fun(T, B) { }
      ^~~
</code>```

For normal function it looks like this:

```<code>void fun(A){}
void fun(B){}

int main() {
    ((void(*)(A))(fun))(X());
}
</code>```

Is it possible?

答:
Improving your example, you can try with</p>

```<code> ((void(*)(int, A))(fun))(1, X());
</code>```

Body:
Can we chose which function template overload should be used in this case?

struct X { };

struct A { A(X){} };
struct B { B(X){} };

template<class T>
void fun(T, A) { }

template<class T>
void fun(T, B) { }

int main() {
    /* explicitly choose overload */ fun(1, X());
}

Error:

error: call of overloaded 'fun(int, X)' is ambiguous
     /* explicitly choose overload */ fun(1, X());
                                                ^
    candidate: void fun(T, A) [with T = int]
 void fun(T, A) { }
      ^~~
    candidate: void fun(T, B) [with T = int]
 void fun(T, B) { }
      ^~~

For normal function it looks like this:

void fun(A){}
void fun(B){}

int main() {
    ((void(*)(A))(fun))(X());
}

Is it possible?

Body:
Improving your example, you can try with

 ((void(*)(int, A))(fun))(1, X());


问:
Only was able to recover MySQL data folder (IBD, FRM, and OPT files), can I recover databases?
As title says, I had an unfortunate failure which resulted in me only being able to recover my MySQL data folder (IBD, FRM, and OPT files). I built a new server and installed MySQL 5.6 (old one used 5.5). I copied over the data folder hoping I would get lucky, and I do see my old schemas in MySQL workbench, but when trying to look at any table in them I get an error like this:

https://www.dropbox.com/s/q2eui8eyu621f3c/sqlerror.jpg?dl=0

I don't remember seeing any .data files on the recovered data and am wondering if it's possible for me to recover my old tables. I'm not sure whether or not the old or new is InnoDB or myisam and am not exactly sure how to tell.

Any tips appreciated.

答: In case someone else who doesn't know how to restore their databases runs into a similar issue, I was able to recover my data. Instead of copying and pasting everything in which did not work, I stopped the MySQL service, pasted all the database folders in, and only the "ibdata1" file. Then I restarted the service and loaded up workbench and all my data as restored in 5.6. </p>


问:
How to (better) select with AS in Doctrine's query builder
I am currently using this query and it works:

```<code>$qb = $this->getEntityManager()->createQueryBuilder();
$qb
    ->select('u')
    ->addSelect('SUM(l.corrects) AS score')
    ->from(User::class, 'u')
    ->leftJoin('u.learned', 'l')
    ->groupBy('u.id')
    ->orderBy('score', 'desc')
    ;

return $qb->getQuery()->getResult();
</code>```

But in twig I have to use {{ user['score'] }} & {{ user[0].username }}... What can I do so that I can use {{ user.score }} & {{ user.username }} in twig?

答:
What if you do that in your User entity ?

```<code>// User.php

public function getScore()
{
    $score = 0;
    foreach($this->learned as $learned) {
        $score += $learned->getCorrects();
    }

    return $score;
}
</code>```

You'll be alble to use {{ user.score }}

Body:
I am currently using this query and it works:

$qb = $this->getEntityManager()->createQueryBuilder();
$qb
    ->select('u')
    ->addSelect('SUM(l.corrects) AS score')
    ->from(User::class, 'u')
    ->leftJoin('u.learned', 'l')
    ->groupBy('u.id')
    ->orderBy('score', 'desc')
    ;

return $qb->getQuery()->getResult();

But in twig I have to use {{ user['score'] }} & {{ user[0].username }}... What can I do so that I can use {{ user.score }} & {{ user.username }} in twig?

Body:
What if you do that in your User entity ?

// User.php

public function getScore()
{
    $score = 0;
    foreach($this->learned as $learned) {
        $score += $learned->getCorrects();
    }

    return $score;
}

You'll be alble to use {{ user.score }}


问:
amp in xml getting comverted to "&"
I am creating one url and adding & to that url.

```<code>eg http://xyzc.com/abc.php?arg1=value1&arg2=value2
</code>```

Now I am adding this url to xml .

I am creating xml via tinyxml in c++ and also tried creating same xml in php.

After creating the xml I found out  that "&" is converted to "&"

Is it okay for "&" to get converted to "&"? Why is this happening ? And what could be the possible fix for this?

```<code>$strUrl ="http://xyzc.com/abc.php?";
$strUrl .="arg1=".$value1;
$strUrl .="&arg2=".$value2;
</code>```

The output is coming as

```<code>http://xyzc.com/abc.php?arg1=10&arg2=100
</code>```

答:
XML has a feature called a character reference (&thingy;)

Therefore, all raw & characters must be escaped as &

This is a pre-defined character reference equivalent to & (amp stands for ampersand).

Leaving an unescaped & will create invalid XML.

Note that raw < characters must also be escaped as <  (lt stands for less-than).

ContentLicense: CC BY-SA 2.5

Title: amp in xml getting comverted to "&"

Body:
I am creating one url and adding & to that url.

eg http://xyzc.com/abc.php?arg1=value1&arg2=value2

Now I am adding this url to xml .

I am creating xml via tinyxml in c++ and also tried creating same xml in php.

After creating the xml I found out  that "&" is converted to "&"

Is it okay for "&" to get converted to "&"? Why is this happening ? And what could be the possible fix for this?

$strUrl ="http://xyzc.com/abc.php?";
$strUrl .="arg1=".$value1;
$strUrl .="&arg2=".$value2;

The output is coming as

http://xyzc.com/abc.php?arg1=10&arg2=100

Body:
XML has a feature called a character reference (&thingy;)

Therefore, all raw & characters must be escaped as &amp;

This is a pre-defined character reference equivalent to & (amp stands for ampersand).

Leaving an unescaped & will create invalid XML.

Note that raw < characters must also be escaped as &lt;  (lt stands for less-than).


答:
function is the delegate of the function (signature) and won't be executed.
function() will be executed and you'll get the result  of function in return.

Title: What's the difference between function and function() in C#?

Body:
For example,
    Thread t = new Thread(function);
Why not
    Thread t = new Thread(function());
Thank you.


答:
function refers the address of a function you can call

function() gets the return
value of a function

A third way could be () => function() which
creates a new anonymous function which is calling function (a simple wrapper in this case)

Since function() returns no other function

```<code>Thread t = new Thread(function());
</code>```

would not work because a thread needs a function to call. This means you have to use

```<code>Thread t = new Thread(function);
</code>```

or

```<code>Thread t = new Thread(() => function());
</code>```

to pass a function to a thread.

Body:
function refers the address of a function you can call

function() gets the return
value of a function

A third way could be () => function() which
creates a new anonymous function which is calling function (a simple wrapper in this case)

Since function() returns no other function

Thread t = new Thread(function());

would not work because a thread needs a function to call. This means you have to use

Thread t = new Thread(function);

or

Thread t = new Thread(() => function());

to pass a function to a thread.


问:
How to reset multiple label in one click of button vb net
I created a program that when i click the button, all the Label text will be reset in Empty.

I have 31 labels, and 1 button..

When I click the button, i want that the output will be the labels are empty.

答:
First method

Loop over label using this code:

```<code>For each Lbl as Label in Me.Controls.OfType(Of Label)()

   Lbl.Text = ""

Next
</code>```

Second method

Or you have to list all labels and change .Text property

```<code>Label1.Text = ""
Label2.Text = ""
Label3.Text = ""
...
</code>```

Body:
First method

Loop over label using this code:

For each Lbl as Label in Me.Controls.OfType(Of Label)()

   Lbl.Text = ""

Next

Second method

Or you have to list all labels and change .Text property

Label1.Text = ""
Label2.Text = ""
Label3.Text = ""
...


问:
How can I determine if a user has pressed on a UITableViewCell for 2 seconds?
I am using gesture recognizers:

Initialize in viewDidLoad:

```<code>UILongPressGestureRecognizer *longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
 [self.view addGestureRecognizer:longPressRecognizer];
</code>```

This is what longPress looks like:

```<code>- (void)longPress:(UILongPressGestureRecognizer*)gestureRecognizer {
 if (gestureRecognizer.minimumPressDuration == 2.0) {
  NSLog(@"Pressed for 2 seconds!");
 }
}
</code>```

How can I tie this into?

```<code>- (void)tableView:(UITableView *)tblView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
</code>```

How will didSelectRowAtIndexPath get a reference to gestureRecognizer.minimumPressDuration?

Basically what I'm trying to achieve is:

```<code>**If a user clicks on a cell, check to see if the press is 2 seconds.**
</code>```

答:
add a the indexpath.row to the tableviewcell's tag

```<code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
UILongPressGestureRecognizer *longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(rowButtonAction:)];
[cell setTag:indexPath.row];
[cell addGestureRecognizer:longPressRecognizer];
[longPressRecognizer release];

// Configure the cell...
Group *gp = [_currentItemArray objectAtIndex:indexPath.row];
cell.textLabel.text = gp.name;

return cell;
</code>```

}

and then access that tag in the longPress by using [[gestureRecognizer view] tag]
(in my code its the part with myModalViewController.previousObject = [_currentItemArray objectAtIndex:[[sender view] tag]];

```<code>-(IBAction)rowButtonAction:(UILongPressGestureRecognizer *)sender{
if (sender.state == UIGestureRecognizerStateEnded) {
    GroupsAdd_EditViewController *myModalViewController = [[[GroupsAdd_EditViewController alloc] initWithNibName:@"GroupsAdd_EditViewController" bundle:nil] autorelease];
    myModalViewController.titleText = @"Edit Group";
    myModalViewController.context = self.context;
    myModalViewController.previousObject = [_currentItemArray objectAtIndex:[[sender view] tag]];
    [self.navigationController presentModalViewController:myModalViewController animated:YES];
}
</code>```

}

Body:
I am using gesture recognizers:

Initialize in viewDidLoad:

UILongPressGestureRecognizer *longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
 [self.view addGestureRecognizer:longPressRecognizer];

This is what longPress looks like:

- (void)longPress:(UILongPressGestureRecognizer*)gestureRecognizer {
 if (gestureRecognizer.minimumPressDuration == 2.0) {
  NSLog(@"Pressed for 2 seconds!");
 }
}

How can I tie this into?

- (void)tableView:(UITableView *)tblView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

How will didSelectRowAtIndexPath get a reference to gestureRecognizer.minimumPressDuration?

Basically what I'm trying to achieve is:

**If a user clicks on a cell, check to see if the press is 2 seconds.**

Body:
add a the indexpath.row to the tableviewcell's tag

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
UILongPressGestureRecognizer *longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(rowButtonAction:)];
[cell setTag:indexPath.row];
[cell addGestureRecognizer:longPressRecognizer];
[longPressRecognizer release];

// Configure the cell...
Group *gp = [_currentItemArray objectAtIndex:indexPath.row];
cell.textLabel.text = gp.name;

return cell;

}

and then access that tag in the longPress by using [[gestureRecognizer view] tag]
(in my code its the part with myModalViewController.previousObject = [_currentItemArray objectAtIndex:[[sender view] tag]];

-(IBAction)rowButtonAction:(UILongPressGestureRecognizer *)sender{
if (sender.state == UIGestureRecognizerStateEnded) {
    GroupsAdd_EditViewController *myModalViewController = [[[GroupsAdd_EditViewController alloc] initWithNibName:@"GroupsAdd_EditViewController" bundle:nil] autorelease];
    myModalViewController.titleText = @"Edit Group";
    myModalViewController.context = self.context;
    myModalViewController.previousObject = [_currentItemArray objectAtIndex:[[sender view] tag]];
    [self.navigationController presentModalViewController:myModalViewController animated:YES];
}

}


问:
How can I rename files in bulk based on their comma-separated contents in shell?
I have hundreds of files suffixed with ".txt". The "txt" files contain "id[0-9]" in a column with delimiter "," from other columns. What I want is to extract the "id[0-9]" as the file name of the corresponding file automatically one by one, any ideas?

for example:  ben.txt ,cotains:

aa,bb,cc,id2233,kk

And many files like this.

Then how can I extract id2233 to replace ben.txt to id2233.txt using shell or other methods？

thanks.

答:
I dunno if this is the best way of doing this, but you could loop through all the files in the directory, pick out the "id" field, and issue a rename statement.  Here is one way:

```<code>  for oldf in ben*.txt
  do
    newf=""
    echo " "
    echo "Old file: $oldf"
    newf=`grep ",id" $oldf | sed "s/^.*\x2cid\([0-9]*\).*$/id\1.txt/" | head -1`
    echo "New file: $newf"
    if [ ! "$newf" ]; then
       echo "No valid id found in $oldf.  Please correct before continuing."
       exit 1
    fi
    if [ -f $newf ]; then
       echo "File exists with id found in $oldf.  Please correct before continuing."
       exit 2
    fi
    echo "rename $oldf $newf"
  done
  echo " "
</code>```

Note: this takes the first record with an "id" field and uses that.

This does not assume any particular position for the "id" field and it will use any length number.  However, it does assume that ",id" precedes the id number.

Oh, in this example, the rename command is being echoed to the terminal so it won't actually do anything except show you what it would do.  You'll need to remove the echo to have it actually do what you want.

Hope this helps!

Body:
I dunno if this is the best way of doing this, but you could loop through all the files in the directory, pick out the "id" field, and issue a rename statement.  Here is one way:

  for oldf in ben*.txt
  do
    newf=""
    echo " "
    echo "Old file: $oldf"
    newf=`grep ",id" $oldf | sed "s/^.*\x2cid\([0-9]*\).*$/id\1.txt/" | head -1`
    echo "New file: $newf"
    if [ ! "$newf" ]; then
       echo "No valid id found in $oldf.  Please correct before continuing."
       exit 1
    fi
    if [ -f $newf ]; then
       echo "File exists with id found in $oldf.  Please correct before continuing."
       exit 2
    fi
    echo "rename $oldf $newf"
  done
  echo " "

Note: this takes the first record with an "id" field and uses that.

This does not assume any particular position for the "id" field and it will use any length number.  However, it does assume that ",id" precedes the id number.

Oh, in this example, the rename command is being echoed to the terminal so it won't actually do anything except show you what it would do.  You'll need to remove the echo to have it actually do what you want.

Hope this helps!


问:
Finding the number of occurence of all the permutations of a SubString in a String in C
Basically this program is made up of two other programs.
First Part to find the permutations of a Sub-String and the
Second Part to find the number of occurence of all the permutations in a given String.
I'm not Getting the required output for most cases
I'd be glad if anybody could help.Thanks.

Here is the Program..

```<code>#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

int appearanceCount(int input1,int input2,char* input3,char* input4)
{
     int count=0,temp,i,j,k;
     int no_of_permutations=1;
     for(i=1;i<input1+1;i++)
     {
         no_of_permutations *= i;
     }
     int a = no_of_permutations/((input1-1));

     for (i=0; i < a; i++)
     {
         for(j=0; j<input1-1; j++)
         {
             char temp;
             temp=input3[j];
             input3[j]=input3[j+1];
             input3[j+1] = temp;
             //printf("\n%s",input3);
             char *temp_input4 = input4;
 //Now I have got the permutation
 //Finding the occurance
             while(temp_input4 = (strstr(temp_input4, input3)) )
             {
                 count++;
                 printf("\n%s  -- %s  -- %d",temp_input4,input3,count);
                 temp_input4++;
             }
         }
      }
      return count;
 }

 int main()
 {
     int output = 0;
     int ip1;
     scanf("%d", &ip1);
     int ip2;
     scanf("%d", &ip2);
     char* ip3;
     ip3 = (char *)malloc(512000 * sizeof(char));
     scanf("\n%[^\n]",ip3);
     char* ip4;
     ip4 = (char *)malloc(512000 * sizeof(char));
     scanf("\n%[^\n]",ip4);
     output = appearanceCount(ip1,ip2,ip3,ip4);
     printf("\n%d", output);
     return 0;
 }
</code>```

My Expected output for the values
4
11
cAda
AbrAcadAbRa

would be
2

because the two possible sequence that can be found in the string are Acad and cadA

but I get the output as 0;

答: Try using anagram search and then it will work fine.</p>

Body:
Basically this program is made up of two other programs.
First Part to find the permutations of a Sub-String and the
Second Part to find the number of occurence of all the permutations in a given String.
I'm not Getting the required output for most cases
I'd be glad if anybody could help.Thanks.

Here is the Program..

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

int appearanceCount(int input1,int input2,char* input3,char* input4)
{
     int count=0,temp,i,j,k;
     int no_of_permutations=1;
     for(i=1;i<input1+1;i++)
     {
         no_of_permutations *= i;
     }
     int a = no_of_permutations/((input1-1));

     for (i=0; i < a; i++)
     {
         for(j=0; j<input1-1; j++)
         {
             char temp;
             temp=input3[j];
             input3[j]=input3[j+1];
             input3[j+1] = temp;
             //printf("\n%s",input3);
             char *temp_input4 = input4;
 //Now I have got the permutation
 //Finding the occurance
             while(temp_input4 = (strstr(temp_input4, input3)) )
             {
                 count++;
                 printf("\n%s  -- %s  -- %d",temp_input4,input3,count);
                 temp_input4++;
             }
         }
      }
      return count;
 }

 int main()
 {
     int output = 0;
     int ip1;
     scanf("%d", &ip1);
     int ip2;
     scanf("%d", &ip2);
     char* ip3;
     ip3 = (char *)malloc(512000 * sizeof(char));
     scanf("\n%[^\n]",ip3);
     char* ip4;
     ip4 = (char *)malloc(512000 * sizeof(char));
     scanf("\n%[^\n]",ip4);
     output = appearanceCount(ip1,ip2,ip3,ip4);
     printf("\n%d", output);
     return 0;
 }

My Expected output for the values
4
11
cAda
AbrAcadAbRa

would be
2

because the two possible sequence that can be found in the string are Acad and cadA

but I get the output as 0;


问:
Get files from web directory
I wanted to just get random Images from http://random.cat/, so I wanted to index them using Directory.GetFiles or something like that, but this doesn't work. So what would be the best way to get the functionality of Directory.GetFiles but for http://random.cat/i (this is where the Images are stored, I think)?

Thanks in advance!

答: As mentioned you have to use HttpClient. I dont know any method for listing all files, but this also needs to be set up in the web server hosting the site.</p>

Title: Get files from web directory


答:
you can use join concept like i suggest

```<code>SELECT `ID`, `category_id`, `title`, `description` FROM `entries`
inner join  `categories` on `entries`.`category_id`=`categories`.`id`
WHERE `categories`.`name` = 'foo' AND `title` = 'bar'  LIMIT 1;
</code>```

Seems you look new, please explore concept about sql

Title: sql query needs input from another table

Body:
I have a database where i want the data from two tables, they look something like this:

categories:    entries:
+----+------+  +----+-------------+-------+-------------+
| id | name |  | ID | category_id | title | description |
+----+------+  +----+-------------+-------+-------------+
|  1 |  foo |  |  1 |      1      |  bar  | Loreum ip.. |
+----+------+  +----+-------------+-------+-------------+

I want to get info from entries, and my input will just be category name and entry title. It does obviously work if i use two statements. something like:

SELECT `id` FROM `categories` WHERE `name` = 'foo' LIMIT 1;
SELECT `ID`, `category_id`, `title`, `description` FROM `entries` WHERE `title` = 'bar' AND `category_id` = $cat_id LIMIT 1;

Where $cat_id is the output from the first entry. But i want to combine these to into one statement, and i don't find join useful here? So my question is basically how can i combine these into one query?

Body:
you can use join concept like i suggest

SELECT `ID`, `category_id`, `title`, `description` FROM `entries`
inner join  `categories` on `entries`.`category_id`=`categories`.`id`
WHERE `categories`.`name` = 'foo' AND `title` = 'bar'  LIMIT 1;

Seems you look new, please explore concept about sql


问:
HTML Contactform Security
I'm trying to send an E-Mail via HTML-Contactform.

Therefore I created this html:

```<code><form id="contact_form" action="sendMail.php" method="post">
        <input id="firstname" name="firstname" type="text" placeholder="Vorname" value="Firstname">
        <input id="lastname" name="lastname" type="text" placeholder="Nachname" value="Lastname">
        <input id="mail" name="mail" type="text" placeholder="E-Mail" value="firstname.lastname@web.de">
        <textarea id="msg" name="msg" placeholder="Ihre Nachricht..." >Hallo</textarea>
        <p id="error_print" class="hidden"></p>
        <input id="contact_submit" type="submit" title="Senden">
</form>
</code>```

I am checking the inputs via jQuery and sending it via Ajax to the PHP-File and print my errors to html.

```<code>$('#contact_submit').click(function(){
        var that = $('#contact_form');
        var first_name = $('#firstname').val();
        var last_name = $('#lastname').val();
        var mail = $('#mail').val();
        var msg = $('msg').val();
        if(first_name == "" || last_name == "" || mail == "" || msg == "")
        {
            $('#error_print').removeClass("hidden");
            $('#error_print').text("Bitte füllen Sie alle Felder aus");
        }
        else
        {
            if( !isValidEmailAddress(mail) )
            {
                $('#error_print').removeClass("hidden");
                $('#error_print').text("Keine korrekte Mail");
            }
            else
            {
                if( !$('#error_print').hasClass( "hidden" ) )
                {
                    $('#error_print').addClass("hidden");
                }

                var url = that.attr('action'),
                    method = that.attr('method'),
                    data = {};
                that.find('[name]').each(function(index, value)
                {
                    var name = $(this).attr('name')
                        value = $(this).val();
                    data[name] = value;
                });

                //console.log(data);

                $.ajax({
                   url: url,
                   type: method,
                   data: data,
                   success: function(response)
                   {
                       $('#error_print').removeClass("hidden");
                        $('#error_print').text("Mail wurde versendet");
                   },
                   error: function(error)
                   {
                       $('#error_print').removeClass("hidden");
                       $('#error_print').text("Fehler - Bitte erneut versuchen");
                   }
                });
            }
        }
        return false;
    });
</code>```

In my PHP I am sending the mail like this:

```<code><?php
if(isset($_POST['firstname'], $_POST['lastname'], $_POST['mail'], $_POST['msg']))
{
    $mail = htmlentities($_POST['mail'], ENT_QUOTES);
    $firstname = htmlentities($_POST['firstname'], ENT_QUOTES);
    $lastname = htmlentities($_POST['lastname'], ENT_QUOTES);
    $msg = htmlentities($_POST['msg'], ENT_QUOTES);

    $empfaenger = "empf@mydomain.de";
    $betreff = "Kontaktaufname";

    $from = "From: $fistname $lastname <$mail>";
    $text = $msg;
    //print_r($_POST);
    mail($empfaenger, $betreff, $text, $from)
}?>
</code>```

I do not know if this is the best way to do it. For that I read a lo about injection in mails. But I am not sure if my script is safe enough.

答:
to send the mail you can try this below</p>

```<code><?php

ini_set("SMTP", "smtp.your_internet_service_provider.com");
ini_set("smtp_port", 25 );
ini_set("sendmail_from", "your_mail@example.com");
ini_set("auth_username", "your_mail@example.com");
ini_set("auth_password", "pwd_of_your_mail");

// For the fields $sender / $copy / $receiver, comma separated if there are multiple addresses
$sender = 'your_mail@example.com';
$receiver = 'receiver_mail@example.com';

$object = 'test msg';
$headers  = 'MIME-Version: 1.0' . "\n"; // Version MIME
$headers .= 'Content-type: text/html; charset=ISO-8859-1'."\n"; // the Content-type head for the HTML format
$headers .= 'Reply-To: '.$sender."\n"; // Mail reply
$headers .= 'From: "name_of_sender"<'.$sender.'>'."\n";
$headers .= 'Delivered-to: '.$receiver."\n";

$message = 'Hello from Aotoki !';
if (mail($receiver, $object, $message, $headers)) // Send message
{
    echo 'Your message has been sent ';
}
else // error
{
    echo "Your message could not be sent";
}
?>
</code>```

Title: HTML Contactform Security

Body:
I'm trying to send an E-Mail via HTML-Contactform.

Therefore I created this html:

<form id="contact_form" action="sendMail.php" method="post">
        <input id="firstname" name="firstname" type="text" placeholder="Vorname" value="Firstname">
        <input id="lastname" name="lastname" type="text" placeholder="Nachname" value="Lastname">
        <input id="mail" name="mail" type="text" placeholder="E-Mail" value="firstname.lastname@web.de">
        <textarea id="msg" name="msg" placeholder="Ihre Nachricht..." >Hallo</textarea>

        <input id="contact_submit" type="submit" title="Senden">
</form>

I am checking the inputs via jQuery and sending it via Ajax to the PHP-File and print my errors to html.

$('#contact_submit').click(function(){
        var that = $('#contact_form');
        var first_name = $('#firstname').val();
        var last_name = $('#lastname').val();
        var mail = $('#mail').val();
        var msg = $('msg').val();
        if(first_name == "" || last_name == "" || mail == "" || msg == "")
        {
            $('#error_print').removeClass("hidden");
            $('#error_print').text("Bitte füllen Sie alle Felder aus");
        }
        else
        {
            if( !isValidEmailAddress(mail) )
            {
                $('#error_print').removeClass("hidden");
                $('#error_print').text("Keine korrekte Mail");
            }
            else
            {
                if( !$('#error_print').hasClass( "hidden" ) )
                {
                    $('#error_print').addClass("hidden");
                }

                var url = that.attr('action'),
                    method = that.attr('method'),
                    data = {};
                that.find('[name]').each(function(index, value)
                {
                    var name = $(this).attr('name')
                        value = $(this).val();
                    data[name] = value;
                });

                //console.log(data);

                $.ajax({
                   url: url,
                   type: method,
                   data: data,
                   success: function(response)
                   {
                       $('#error_print').removeClass("hidden");
                        $('#error_print').text("Mail wurde versendet");
                   },
                   error: function(error)
                   {
                       $('#error_print').removeClass("hidden");
                       $('#error_print').text("Fehler - Bitte erneut versuchen");
                   }
                });
            }
        }
        return false;
    });

In my PHP I am sending the mail like this:

<?php
if(isset($_POST['firstname'], $_POST['lastname'], $_POST['mail'], $_POST['msg']))
{
    $mail = htmlentities($_POST['mail'], ENT_QUOTES);
    $firstname = htmlentities($_POST['firstname'], ENT_QUOTES);
    $lastname = htmlentities($_POST['lastname'], ENT_QUOTES);
    $msg = htmlentities($_POST['msg'], ENT_QUOTES);

    $empfaenger = "empf@mydomain.de";
    $betreff = "Kontaktaufname";

    $from = "From: $fistname $lastname <$mail>";
    $text = $msg;
    //print_r($_POST);
    mail($empfaenger, $betreff, $text, $from)
}?>

I do not know if this is the best way to do it. For that I read a lo about injection in mails. But I am not sure if my script is safe enough.

Body:
to send the mail you can try this below

<?php

ini_set("SMTP", "smtp.your_internet_service_provider.com");
ini_set("smtp_port", 25 );
ini_set("sendmail_from", "your_mail@example.com");
ini_set("auth_username", "your_mail@example.com");
ini_set("auth_password", "pwd_of_your_mail");

// For the fields $sender / $copy / $receiver, comma separated if there are multiple addresses
$sender = 'your_mail@example.com';
$receiver = 'receiver_mail@example.com';

$object = 'test msg';
$headers  = 'MIME-Version: 1.0' . "\n"; // Version MIME
$headers .= 'Content-type: text/html; charset=ISO-8859-1'."\n"; // the Content-type head for the HTML format
$headers .= 'Reply-To: '.$sender."\n"; // Mail reply
$headers .= 'From: "name_of_sender"<'.$sender.'>'."\n";
$headers .= 'Delivered-to: '.$receiver."\n";

$message = 'Hello from Aotoki !';
if (mail($receiver, $object, $message, $headers)) // Send message
{
    echo 'Your message has been sent ';
}
else // error
{
    echo "Your message could not be sent";
}
?>


问:
Core Data: Lost the ability to save new documents, but still can edit and save existing documents
I am currently developing the first version of an application using NSPersistentDocument and lightweight migration. The data model went up to version 12 now. When switching from version 9 to version 10, I lost the ability to save new documents, but I didn't notice until now since I was testing with the same old documents from the first versions.

I can still edit and save these documents just fine, I can even produce documents with older versions of my application and migrate them with the current version.

When I open a new document, edit it and wait for auto save or save it myself, configurePersistentStoreCoordinatorForURL crashes:

```<code>2017-03-31 07:58:51.409160+0200 MyCalcApp[5172:1857474] [General] Cannot perform operation since entity with name '(null)' cannot be found
2017-03-31 07:58:51.411774+0200 MyCalcApp[5172:1857474] [General] (
    0   CoreFoundation                      0x00007fffd037937b __exceptionPreprocess + 171
    1   libobjc.A.dylib                     0x00007fffe516d48d objc_exception_throw + 48
    2   CoreFoundation                      0x00007fffd03f7c3d +[NSException raise:format:] + 205
    3   AppKit                              0x00007fffce48ff1b -[_NSManagedProxy _entity] + 138
    4   AppKit                              0x00007fffce490178 -[_NSManagedProxy fetchRequestWithSortDescriptors:limit:] + 89
    5   AppKit                              0x00007fffce49063f -[_NSManagedProxy _storesDidChange:] + 119
    6   CoreFoundation                      0x00007fffd030550c __CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__ + 12
    7   CoreFoundation                      0x00007fffd030540b _CFXRegistrationPost + 427
    8   CoreFoundation                      0x00007fffd0305172 ___CFXNotificationPost_block_invoke + 50
    9   CoreFoundation                      0x00007fffd02c25a3 -[_CFXNotificationRegistrar find:object:observer:enumerator:] + 1827
    10  CoreFoundation                      0x00007fffd02c15dc _CFXNotificationPost + 604
    11  Foundation                          0x00007fffd1ce5997 -[NSNotificationCenter postNotificationName:object:userInfo:] + 66
    12  CoreData                            0x00007fffcfed9736 -[NSPersistentStoreCoordinator(_NSInternalMethods) _postStoresChangedNotificationsForStores:changeKey:options:] + 246
    13  CoreData                            0x00007fffcff9e1c7 __91-[NSPersistentStoreCoordinator addPersistentStoreWithType:configuration:URL:options:error:]_block_invoke + 3015
    14  CoreData                            0x00007fffcffaf378 gutsOfBlockToNSPersistentStoreCoordinatorPerform + 200
    15  libdispatch.dylib                   0x00000001000da78c _dispatch_client_callout + 8
    16  libdispatch.dylib                   0x00000001000db5ad _dispatch_barrier_sync_f_invoke + 307
    17  CoreData                            0x00007fffcff99f52 _perform + 210
    18  CoreData                            0x00007fffcfec9994 -[NSPersistentStoreCoordinator addPersistentStoreWithType:configuration:URL:options:error:] + 564
    19  AppKit                              0x00007fffce4b3c54 -[NSPersistentDocument configurePersistentStoreCoordinatorForURL:ofType:modelConfiguration:storeOptions:error:] + 1176
    20  MyCalcApp                      0x000000010000ee1f -[Document configurePersistentStoreCoordinatorForURL:ofType:modelConfiguration:storeOptions:error:] + 735
    21  AppKit                              0x00007fffce7d8ee8 -[NSPersistentDocument(NSDeprecatedInternal) _configurePersistentStoreCoordinatorForURL:ofType:error:] + 159
    22  AppKit                              0x00007fffce4b43b9 -[NSPersistentDocument writeToURL:ofType:forSaveOperation:originalContentsURL:error:] + 754
    23  AppKit                              0x00007fffce4b5ad0 -[NSPersistentDocument writeSafelyToURL:ofType:forSaveOperation:error:] + 767
    24  AppKit                              0x00007fffce930935 __85-[NSDocument(NSDocumentSaving) _saveToURL:ofType:forSaveOperation:completionHandler:]_block_invoke_2.1116 + 233
    25  AppKit                              0x00007fffce93083d __85-[NSDocument(NSDocumentSaving) _saveToURL:ofType:forSaveOperation:completionHandler:]_block_invoke.1113 + 454
    26  AppKit                              0x00007fffce92e973 __85-[NSDocument(NSDocumentSaving) _saveToURL:ofType:forSaveOperation:completionHandler:]_block_invoke_2.969 + 2071
    27  AppKit                              0x00007fffce34916b __62-[NSDocumentController(NSInternal) _onMainThreadInvokeWorker:]_block_invoke.1972 + 160
    28  CoreFoundation                      0x00007fffd030f21c __CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__ + 12
    29  CoreFoundation                      0x00007fffd02f0034 __CFRunLoopDoBlocks + 356
    30  CoreFoundation                      0x00007fffd02efb76 __CFRunLoopRun + 1878
    31  CoreFoundation                      0x00007fffd02ef1c4 CFRunLoopRunSpecific + 420
    32  HIToolbox                           0x00007fffcf850ebc RunCurrentEventLoopInMode + 240
    33  HIToolbox                           0x00007fffcf850cf1 ReceiveNextEventCommon + 432
    34  HIToolbox                           0x00007fffcf850b26 _BlockUntilNextEventMatchingListInModeWithFilter + 71
    35  AppKit                              0x00007fffcddebe24 _DPSNextEvent + 1120
    36  AppKit                              0x00007fffce56785e -[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 2796
    37  AppKit                              0x00007fffcdde07ab -[NSApplication run] + 926
    38  AppKit                              0x00007fffcddab1de NSApplicationMain + 1237
    39  MyCalcApp                      0x0000000100017ac2 main + 34
    40  libdyld.dylib                       0x00007fffe5a52235 start + 1
    41  ???                                 0x0000000000000005 0x0 + 5
)
</code>```

I looked for an entity with a missing name but did not find one. The data model looks fine, even when I look at the XML source code. There is no NSObjectController or NSArrayController which misses its entity name. configurePersistentStoreCoordinatorForURL crashes whether or not I overwrite it (for lightweight migration).

I cleared all the Xcode derived data folders I could think of, compiled and ran the app on different Macs with different Xcode versions (8.3 and 8.2.1), same problem everywhere. The run argument com.apple.CoreData.SQLDebug does not give any helpful information.

I added some entities from model version 9 to 12 and I might have deleted one, but I can't remember exactly.

Is there some other place Xcode is hiding data model version information such as hashes? Any ideas where to look? Shall I recreate the data model from scratch?

答:
It is always good to explain your problem to somebody else in order to solve it. I found the bug where I didn't expect it.

I have two entities that are connected by a to-many relationship: series of measurements and measurements. I list them in two table views:

If I click on a series in the left table view, I want the right table view to show the corresponding measurements. So the left table view refers to an array controller in Entity Name mode and with its Managed Object Context bound to File's Owner.managedObjectContext. To make the values in the right table view depend on the selection on the left, I created an NSArrayController in class mode (NSMutableDictionary) and bound its content set to the correct relationship set of the first controller:

What I did wrong was that I bound that controller's Managed Object Context to File's Owner.managedObjectContext, too. I thought that was needed to make any changes permanent, but it is not. Strangely it worked when I was using existing documents, but it didn't when I created new ones. So these are the correct settings for the Measurements NSArrayController:

Body:
I am currently developing the first version of an application using NSPersistentDocument and lightweight migration. The data model went up to version 12 now. When switching from version 9 to version 10, I lost the ability to save new documents, but I didn't notice until now since I was testing with the same old documents from the first versions.

I can still edit and save these documents just fine, I can even produce documents with older versions of my application and migrate them with the current version.

When I open a new document, edit it and wait for auto save or save it myself, configurePersistentStoreCoordinatorForURL crashes:

2017-03-31 07:58:51.409160+0200 MyCalcApp[5172:1857474] [General] Cannot perform operation since entity with name '(null)' cannot be found
2017-03-31 07:58:51.411774+0200 MyCalcApp[5172:1857474] [General] (
    0   CoreFoundation                      0x00007fffd037937b __exceptionPreprocess + 171
    1   libobjc.A.dylib                     0x00007fffe516d48d objc_exception_throw + 48
    2   CoreFoundation                      0x00007fffd03f7c3d +[NSException raise:format:] + 205
    3   AppKit                              0x00007fffce48ff1b -[_NSManagedProxy _entity] + 138
    4   AppKit                              0x00007fffce490178 -[_NSManagedProxy fetchRequestWithSortDescriptors:limit:] + 89
    5   AppKit                              0x00007fffce49063f -[_NSManagedProxy _storesDidChange:] + 119
    6   CoreFoundation                      0x00007fffd030550c __CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__ + 12
    7   CoreFoundation                      0x00007fffd030540b _CFXRegistrationPost + 427
    8   CoreFoundation                      0x00007fffd0305172 ___CFXNotificationPost_block_invoke + 50
    9   CoreFoundation                      0x00007fffd02c25a3 -[_CFXNotificationRegistrar find:object:observer:enumerator:] + 1827
    10  CoreFoundation                      0x00007fffd02c15dc _CFXNotificationPost + 604
    11  Foundation                          0x00007fffd1ce5997 -[NSNotificationCenter postNotificationName:object:userInfo:] + 66
    12  CoreData                            0x00007fffcfed9736 -[NSPersistentStoreCoordinator(_NSInternalMethods) _postStoresChangedNotificationsForStores:changeKey:options:] + 246
    13  CoreData                            0x00007fffcff9e1c7 __91-[NSPersistentStoreCoordinator addPersistentStoreWithType:configuration:URL:options:error:]_block_invoke + 3015
    14  CoreData                            0x00007fffcffaf378 gutsOfBlockToNSPersistentStoreCoordinatorPerform + 200
    15  libdispatch.dylib                   0x00000001000da78c _dispatch_client_callout + 8
    16  libdispatch.dylib                   0x00000001000db5ad _dispatch_barrier_sync_f_invoke + 307
    17  CoreData                            0x00007fffcff99f52 _perform + 210
    18  CoreData                            0x00007fffcfec9994 -[NSPersistentStoreCoordinator addPersistentStoreWithType:configuration:URL:options:error:] + 564
    19  AppKit                              0x00007fffce4b3c54 -[NSPersistentDocument configurePersistentStoreCoordinatorForURL:ofType:modelConfiguration:storeOptions:error:] + 1176
    20  MyCalcApp                      0x000000010000ee1f -[Document configurePersistentStoreCoordinatorForURL:ofType:modelConfiguration:storeOptions:error:] + 735
    21  AppKit                              0x00007fffce7d8ee8 -[NSPersistentDocument(NSDeprecatedInternal) _configurePersistentStoreCoordinatorForURL:ofType:error:] + 159
    22  AppKit                              0x00007fffce4b43b9 -[NSPersistentDocument writeToURL:ofType:forSaveOperation:originalContentsURL:error:] + 754
    23  AppKit                              0x00007fffce4b5ad0 -[NSPersistentDocument writeSafelyToURL:ofType:forSaveOperation:error:] + 767
    24  AppKit                              0x00007fffce930935 __85-[NSDocument(NSDocumentSaving) _saveToURL:ofType:forSaveOperation:completionHandler:]_block_invoke_2.1116 + 233
    25  AppKit                              0x00007fffce93083d __85-[NSDocument(NSDocumentSaving) _saveToURL:ofType:forSaveOperation:completionHandler:]_block_invoke.1113 + 454
    26  AppKit                              0x00007fffce92e973 __85-[NSDocument(NSDocumentSaving) _saveToURL:ofType:forSaveOperation:completionHandler:]_block_invoke_2.969 + 2071
    27  AppKit                              0x00007fffce34916b __62-[NSDocumentController(NSInternal) _onMainThreadInvokeWorker:]_block_invoke.1972 + 160
    28  CoreFoundation                      0x00007fffd030f21c __CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__ + 12
    29  CoreFoundation                      0x00007fffd02f0034 __CFRunLoopDoBlocks + 356
    30  CoreFoundation                      0x00007fffd02efb76 __CFRunLoopRun + 1878
    31  CoreFoundation                      0x00007fffd02ef1c4 CFRunLoopRunSpecific + 420
    32  HIToolbox                           0x00007fffcf850ebc RunCurrentEventLoopInMode + 240
    33  HIToolbox                           0x00007fffcf850cf1 ReceiveNextEventCommon + 432
    34  HIToolbox                           0x00007fffcf850b26 _BlockUntilNextEventMatchingListInModeWithFilter + 71
    35  AppKit                              0x00007fffcddebe24 _DPSNextEvent + 1120
    36  AppKit                              0x00007fffce56785e -[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 2796
    37  AppKit                              0x00007fffcdde07ab -[NSApplication run] + 926
    38  AppKit                              0x00007fffcddab1de NSApplicationMain + 1237
    39  MyCalcApp                      0x0000000100017ac2 main + 34
    40  libdyld.dylib                       0x00007fffe5a52235 start + 1
    41  ???                                 0x0000000000000005 0x0 + 5
)

I looked for an entity with a missing name but did not find one. The data model looks fine, even when I look at the XML source code. There is no NSObjectController or NSArrayController which misses its entity name. configurePersistentStoreCoordinatorForURL crashes whether or not I overwrite it (for lightweight migration).

I cleared all the Xcode derived data folders I could think of, compiled and ran the app on different Macs with different Xcode versions (8.3 and 8.2.1), same problem everywhere. The run argument com.apple.CoreData.SQLDebug does not give any helpful information.

I added some entities from model version 9 to 12 and I might have deleted one, but I can't remember exactly.

Is there some other place Xcode is hiding data model version information such as hashes? Any ideas where to look? Shall I recreate the data model from scratch?